path stringlengths 4 280 | owner stringlengths 2 39 | repo_id int64 21.1k 879M | is_fork bool 2
classes | languages_distribution stringlengths 13 1.95k ⌀ | content stringlengths 7 482k | issues int64 0 13.9k | main_language stringclasses 121
values | forks stringlengths 1 5 | stars int64 0 111k | commit_sha stringlengths 40 40 | size int64 7 482k | name stringlengths 1 100 | license stringclasses 93
values |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
src/main/kotlin/com/s13g/sauron/taker/PictureTakerTestingImpl.kt | shaeberling | 72,052,685 | false | null | package com.s13g.sauron.taker
import com.google.common.flogger.FluentLogger
import com.google.common.io.ByteStreams
import com.google.common.util.concurrent.ListenableFuture
import com.google.common.util.concurrent.SettableFuture
import java.io.ByteArrayInputStream
import java.io.ByteArrayOutputStream
import java.io.File
import java.io.FileInputStream
import java.io.FileOutputStream
import java.io.IOException
private val log = FluentLogger.forEnclosingClass()
/**
* Loads the jpeg files from the given directory and offers them in a round-robin way.
*/
fun createTestPictureTakerFrom(directory: File): PictureTaker {
if (!directory.exists() || !directory.isDirectory) {
throw RuntimeException("Directory does not exist: " + directory.absolutePath)
}
val jpegFiles = directory.listFiles { _: File?, name: String ->
name.toLowerCase().endsWith(".jpg")
}
if (jpegFiles == null || jpegFiles.isEmpty()) {
throw RuntimeException("No JPEG files in directory " + directory.absolutePath)
}
val files: MutableList<ByteArray> =
ArrayList(jpegFiles.size)
for (jpegFile in jpegFiles) {
val file = readFile(jpegFile)
if (file != null) {
files.add(file)
}
}
return PictureTakerTestingImpl(files)
}
/**
* A PictureTaker that can be used for testing, when a webcam is not accessible.
*/
class PictureTakerTestingImpl internal constructor(private val testImages: List<ByteArray?>) :
PictureTaker {
private var counter = 0
override fun captureImage(file: File): ListenableFuture<Boolean> {
val future = SettableFuture.create<Boolean>()
try {
FileOutputStream(file).use { out ->
ByteArrayInputStream(testImages[counter]).use { `in` ->
val bytesWritten = ByteStreams.copy(`in`, out)
future.set(bytesWritten > 0)
}
}
} catch (e: IOException) {
log.atSevere().log("Cannot write file.", e)
future.set(false)
}
if (++counter >= testImages.size) {
counter = 0
}
return future
}
}
private fun readFile(file: File): ByteArray? {
val data = ByteArrayOutputStream()
try {
FileInputStream(file).use { input ->
ByteStreams.copy(input, data)
return data.toByteArray()
}
} catch (e: IOException) {
log.atWarning().log("Cannot read file. ", e)
return null
}
} | 5 | Kotlin | 0 | 1 | a913e05af1644b3723022978f2cf102126f93bf6 | 2,330 | sauron | Apache License 2.0 |
app/src/main/java/com/eficksan/rpghelper/MainActivity.kt | AlekseiIvshin | 168,294,135 | false | null | package com.eficksan.rpghelper
import android.os.Bundle
import androidx.appcompat.app.AppCompatActivity
import androidx.navigation.findNavController
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
}
override fun onSupportNavigateUp()
= findNavController(R.id.nav_host_fragment).navigateUp()
}
| 0 | Kotlin | 0 | 0 | b46e4d82edf155d7d8c2f4f457100a6fab3bc3d7 | 459 | RPGHelper | Apache License 2.0 |
features/news/src/main/kotlin/by/anegin/vkcup21/features/news/data/models/PostSource.kt | eugene-kirzhanov | 385,482,551 | false | null | package by.anegin.vkcup21.features.news.data.models
internal class PostSource(
val id: Int,
val name: String?,
private val screenName: String?,
val photo: Photo?
) {
fun getSourceUrl() = "https://vk.com/$screenName"
} | 0 | Kotlin | 0 | 0 | 00afa06d424810fe80675e333facfd42d6b2b75d | 240 | vkcup21 | MIT License |
movie/src/main/java/id/web/dedekurniawan/moviexplorer/movie/data/remote/response/MovieImageApiResponse.kt | BlueShadowBird | 608,123,499 | false | {"Kotlin": 156728} | package id.web.dedekurniawan.moviexplorer.movie.data.remote.response
import com.google.gson.annotations.SerializedName
data class MovieImageApiResponse(
@field:SerializedName("backdrops")
val backdrops: List<MovieImageResponseItem>,
@field:SerializedName("posters")
val posters: List<MovieImageResponseItem>,
@field:SerializedName("id")
val id: Int,
@field:SerializedName("logos")
val logos: List<MovieImageResponseItem>
)
data class MovieImageResponseItem(
@field:SerializedName("aspect_ratio")
val aspectRatio: Float,
@field:SerializedName("file_path")
val filePath: String,
@field:SerializedName("width")
val width: Int,
@field:SerializedName("height")
val height: Int
) | 0 | Kotlin | 0 | 0 | 8b58189bc2391699125d466c6e232a09b04c748d | 700 | Android-Movie-Xporer | MIT License |
app/src/main/java/com/example/yit/local/models/ImageEntity.kt | dorindorsman | 796,692,286 | false | {"Kotlin": 34150} | package com.example.yit.local.models
import androidx.compose.ui.unit.Dp
import androidx.compose.ui.unit.dp
data class ImageEntity(
var id: Int = 0,
var pageURL: String? = null,
var description: String? = null,
var type: String? = null,
var tags: List<String?>? = null,
var previewURL: String? = null,
var previewWidth: Dp = 0.dp,
var previewHeight: Dp = 0.dp,
var webformatURL: String? = null,
var webformatWidth: Dp = 0.dp,
var webformatHeight: Dp = 0.dp,
var largeImageURL: String? = null,
var imageWidth: Dp = 0.dp,
var imageHeight: Dp = 0.dp,
var imageSize: Dp = 0.dp,
var views: Int? = null,
var downloads: Int? = null,
var collections: Int? = null,
var likes: Int? = null,
var comments: Int? = null,
var user_id: Int? = null,
var user: String? = null,
var userImageURL: String? = null,
)
| 0 | Kotlin | 0 | 0 | 921b2947a514b86aab46c460ef2df7762d9b1f2b | 888 | YIT | Apache License 2.0 |
app/src/main/java/com/demo/features/chat/api/ChatRepoProvider.kt | DebashisINT | 614,693,263 | false | null | package com.demo.features.chat.api
object ChatRepoProvider {
fun provideChatRepository(): ChatRepo {
return ChatRepo(ChatApi.create())
}
} | 0 | Kotlin | 0 | 0 | 80c611bcf95487eb57f7c6563f955265e55832df | 156 | FSM_APP_ANDROIDX_TestingUpdate | Apache License 2.0 |
src/main/kotlin/ru/stech/sdp/SdpBodyBuilder.kt | soft-stech | 353,408,638 | false | null | package ru.stech.sdp
import ru.stech.util.LIBNAME
import ru.stech.util.LOCALHOST
class SdpBodyBuilder(val remoteRdpHost: String, val rtpHost: String, val rtpLocalPort: Int) {
override fun toString(): String {
val sdp = if (LOCALHOST != null && rtpLocalPort != null) "v=0\r\n" +
"o=- Z 0 IN IP4 ${rtpHost}\r\n" +
"s=$LIBNAME\r\n" +
"t=0 0\r\n" +
"m=audio ${rtpLocalPort} RTP/AVP 8 120\r\n" +
"c=IN IP4 ${rtpHost}\r\n" +
"a=sendrecv\r\n" +
"a=rtpmap:8 PCMA/8000\r\n" +
"a=rtpmap:120 telephone-event/8000\r\n" +
"a=fmtp:120 0-16" else ""
return sdp
}
} | 0 | Kotlin | 1 | 3 | f3290a74a6cab823cf4501c813e76917e62c1d66 | 721 | sip4k | MIT License |
plugins/plugin-sandbox/testData/firLoadK2Compiled/simple-lang-ver-2.1.kt | JetBrains | 3,432,266 | false | {"Kotlin": 79571273, "Java": 6776465, "Swift": 4063829, "C": 2609744, "C++": 1957654, "Objective-C++": 175279, "JavaScript": 130754, "Python": 59855, "Shell": 34920, "Objective-C": 21463, "Lex": 21452, "Batchfile": 11382, "CSS": 11368, "Ruby": 10470, "Dockerfile": 9907, "Groovy": 7092, "EJS": 5241, "CMake": 4473, "HTML": 2699, "Puppet": 1698, "FreeMarker": 1393, "Roff": 725, "Scala": 80} | // API_VERSION: 2.0
// ALLOW_DANGEROUS_LANGUAGE_VERSION_TESTING
// LANGUAGE_VERSION: 2.1
package test
import org.jetbrains.kotlin.plugin.sandbox.MyInlineable
fun runInlineable(block: @MyInlineable () -> Unit) {}
| 181 | Kotlin | 5748 | 49,172 | 33eb9cef3d146062c103f9853d772f0a1da0450e | 214 | kotlin | Apache License 2.0 |
app/src/main/java/com/marcodallaba/pokeapp/ui/adapters/PokemonLoadStateAdapter.kt | marcodb97 | 304,840,360 | false | null | package com.marcodallaba.pokeapp.ui.adapters
import android.view.ViewGroup
import androidx.paging.LoadState
import androidx.paging.LoadStateAdapter
import com.marcodallaba.pokeapp.ui.viewholders.PokemonLoadStateViewHolder
class PokemonLoadStateAdapter(
private val retry: () -> Unit
) : LoadStateAdapter<PokemonLoadStateViewHolder>() {
override fun onBindViewHolder(holder: PokemonLoadStateViewHolder, loadState: LoadState) {
holder.bind(loadState)
}
override fun onCreateViewHolder(
parent: ViewGroup,
loadState: LoadState
): PokemonLoadStateViewHolder {
return PokemonLoadStateViewHolder.create(parent, retry)
}
}
| 0 | Kotlin | 0 | 0 | 53d874dec840980e2ba44fdccbbf31f0a85a37e9 | 675 | PokeApp | Apache License 2.0 |
src/main/kotlin/com/poseplz/server/application/photobooth/PhotoBoothApplicationService.kt | pobu-team | 678,194,623 | false | {"Kotlin": 144852, "HTML": 42781, "Dockerfile": 340, "CSS": 122} | package com.poseplz.server.application.photobooth
import com.poseplz.server.domain.photobooth.PhotoBooth
import com.poseplz.server.domain.photobooth.PhotoBoothService
import com.poseplz.server.ui.api.photobooth.PhotoBoothResponse
import org.springframework.data.domain.Page
import org.springframework.data.domain.Pageable
import org.springframework.stereotype.Component
@Component
class PhotoBoothApplicationService(
private val photoBoothService: PhotoBoothService,
) {
fun getPhotoBooths(
pageable: Pageable,
): Page<PhotoBoothResponse> {
return photoBoothService.getPhotoBooths(pageable)
.map { it.toPhotoBoothResponse() }
}
fun getPhotoBooth(
photoBoothId: Long,
): PhotoBoothResponse {
return photoBoothService.getPhotoBooth(photoBoothId)
.let { it.toPhotoBoothResponse() }
}
}
| 0 | Kotlin | 0 | 0 | 2e0b43d4f58344e08fc8d0227e4fe4bf2b276296 | 870 | poseplz-server | MIT License |
ocgena-domain/src/main/kotlin/ru/misterpotz/ocgena/simulation_old/semantics/SimulationSemanticsType.kt | MisterPotz | 605,293,662 | false | {"Kotlin": 749008, "TypeScript": 495751, "JavaScript": 36713, "CSS": 14489, "Python": 8026, "HTML": 3173, "Ruby": 285, "EJS": 274, "Java": 140} | package ru.misterpotz.ocgena.simulation_old.semantics
import kotlinx.serialization.SerialName
import kotlinx.serialization.Serializable
@Serializable
enum class SimulationSemanticsType {
@SerialName("original")
ORIGINAL,
@SerialName("time_pn")
SIMPLE_TIME_PN,
}
@Serializable
data class SimulationSemantics(
val type: SimulationSemanticsType
) | 0 | Kotlin | 0 | 1 | 32a25441882c4780ed6b964a24430ef086222b76 | 367 | ocgena | MIT License |
korge-foundation/src/korlibs/math/geom/_MathGeom.ds.kt | korlibs | 80,095,683 | false | {"WebAssembly": 14293935, "Kotlin": 9728800, "C": 77092, "C++": 20878, "TypeScript": 12397, "HTML": 6043, "Python": 4296, "Swift": 1371, "JavaScript": 328, "Shell": 254, "CMake": 202, "CSS": 66, "Batchfile": 41} | @file:Suppress("PackageDirectoryMismatch")
package korlibs.math.geom.ds
import korlibs.datastructure.*
import korlibs.datastructure.ds.*
import korlibs.math.annotations.*
import korlibs.math.geom.*
inline operator fun <T> Array2<T>.get(p: Point): T = get(p.x.toInt(), p.y.toInt())
inline operator fun <T> Array2<T>.set(p: Point, value: T) = set(p.x.toInt(), p.y.toInt(), value)
inline fun <T> Array2<T>.tryGet(p: Point): T? = tryGet(p.x.toInt(), p.y.toInt())
inline fun <T> Array2<T>.trySet(p: Point, value: T) = trySet(p.x.toInt(), p.y.toInt(), value)
inline operator fun <T> Array2<T>.get(p: PointInt): T = get(p.x, p.y)
inline operator fun <T> Array2<T>.set(p: PointInt, value: T) = set(p.x, p.y, value)
inline fun <T> Array2<T>.tryGet(p: PointInt): T? = tryGet(p.x, p.y)
inline fun <T> Array2<T>.trySet(p: PointInt, value: T) = trySet(p.x, p.y, value)
/**
* A Bounding Volume Hierarchy implementation for 1D.
* It uses [Segment1D] to describe volumes and [Ray] for raycasting.
*/
open class BVH1D<T>(
val allowUpdateObjects: Boolean = true
) {
val bvh = BVH<T>(dimensions = 1, allowUpdateObjects = allowUpdateObjects)
fun intersectRay(ray: Ray1D, rect: Rectangle? = null): BVHRect? = bvh.intersectRay(ray.toBVH(), rect?.toBVH())
fun envelope(): Segment1D = bvh.envelope().toSegment1D()
fun intersect(
ray: Ray1D,
returnArray: FastArrayList<BVH.IntersectResult<T>> = fastArrayListOf(),
): FastArrayList<BVH.IntersectResult<T>> = bvh.intersect(ray.toBVH(), returnArray)
fun search(
segment: Segment1D,
returnArray: FastArrayList<BVH.Node<T>> = fastArrayListOf(),
): FastArrayList<BVH.Node<T>> = bvh.search(intervals = segment.toBVH(), return_array = returnArray)
fun insertOrUpdate(segment: Segment1D, obj: T) = bvh.insertOrUpdate(segment.toBVH(), obj)
fun remove(segment: Segment1D, obj: T? = null): FastArrayList<BVH.Node<T>> = bvh.remove(segment.toBVH(), obj = obj)
fun remove(obj: T): Unit = bvh.remove(obj)
fun getObjectBounds(obj: T): Segment1D? = bvh.getObjectBoundsRect(obj)?.toSegment1D()
fun debug() {
bvh.debug()
}
}
data class Segment1D(val start: Double, val end: Double) {
constructor(start: Float, end: Float) : this(start.toDouble(), end.toDouble())
val size: Double get() = end - start
}
data class Ray1D(val start: Double, val dir: Double) {
constructor(start: Float, dir: Float) : this(start.toDouble(), dir.toDouble())
}
fun Segment1D.toBVH(): BVHRect = BVHRect(BVHIntervals(start, size))
fun Ray1D.toBVH(): BVHRay = BVHRay(BVHIntervals(start, dir))
fun BVHRect.toSegment1D(): Segment1D = Segment1D(min(0), max(0))
fun BVHRay.toRay1D(): Ray1D = Ray1D(pos(0), dir(0))
/**
* A Bounding Volume Hierarchy implementation for 2D.
* It uses [Rectangle] to describe volumes and [Ray] for raycasting.
*/
open class BVH2D<T>(
val allowUpdateObjects: Boolean = true
) {
val bvh = BVH<T>(dimensions = 2, allowUpdateObjects = allowUpdateObjects)
fun intersectRay(ray: Ray, rect: Rectangle? = null) = bvh.intersectRay(ray.toBVH(), rect?.toBVH())
fun envelope(): Rectangle = bvh.envelope().toRectangle()
fun intersect(
ray: Ray,
return_array: FastArrayList<BVH.IntersectResult<T>> = fastArrayListOf(),
): FastArrayList<BVH.IntersectResult<T>> = bvh.intersect(ray.toBVH(), return_array)
fun search(
rect: Rectangle,
return_array: FastArrayList<BVH.Node<T>> = fastArrayListOf(),
): FastArrayList<BVH.Node<T>> = bvh.search(intervals = rect.toBVH(), return_array = return_array)
fun insertOrUpdate(rect: Rectangle, obj: T): Unit = bvh.insertOrUpdate(rect.toBVH(), obj)
fun remove(rect: Rectangle, obj: T? = null) = bvh.remove(rect.toBVH(), obj = obj)
fun remove(obj: T) = bvh.remove(obj)
fun getObjectBounds(obj: T) = bvh.getObjectBounds(obj)?.toRectangle()
fun debug() {
bvh.debug()
}
}
fun BVHRect.toRectangle(): Rectangle = Rectangle(min(0), min(1), size(0), size(1))
@Deprecated("Use BVHRect signature")
fun BVHIntervals.toRectangle(): Rectangle = Rectangle(min(0), min(1), size(0), size(1))
fun Rectangle.toBVH(out: BVHIntervals = BVHIntervals(2)): BVHRect {
out.setTo(x, width, y, height)
return BVHRect(out)
}
fun Ray.toBVH(out: BVHIntervals = BVHIntervals(2)): BVHRay {
out.setTo(point.x, direction.x, point.y, direction.y)
return BVHRay(out)
}
fun BVHRay.toRay(): Ray = Ray(pos.toVector2(), dir.toVector2())
fun BVHVector.toVector2(): Vector2D {
checkDimensions(2)
return Vector2D(this[0], this[1])
}
/**
* A Bounding Volume Hierarchy implementation for 3D.
* It uses [AABB3D] to describe volumes and [MRay3D] for raycasting.
*/
open class BVH3D<T>(
val allowUpdateObjects: Boolean = true
) {
val bvh = BVH<T>(dimensions = 3, allowUpdateObjects = allowUpdateObjects)
fun intersectRay(ray: Ray3F, rect: AABB3D? = null): BVHRect? = bvh.intersectRay(ray.toBVH(), rect?.toBVH())
fun envelope(): AABB3D = bvh.envelope().toAABB3D()
fun intersect(
ray: Ray3F,
return_array: FastArrayList<BVH.IntersectResult<T>> = fastArrayListOf(),
): FastArrayList<BVH.IntersectResult<T>> = bvh.intersect(ray.toBVH(), return_array)
fun search(
rect: AABB3D,
return_array: FastArrayList<BVH.Node<T>> = fastArrayListOf(),
): FastArrayList<BVH.Node<T>> = bvh.search(intervals = rect.toBVH(), return_array = return_array)
fun insertOrUpdate(rect: AABB3D, obj: T): Unit = bvh.insertOrUpdate(rect.toBVH(), obj)
fun remove(rect: AABB3D, obj: T? = null): FastArrayList<BVH.Node<T>> = bvh.remove(rect.toBVH(), obj = obj)
fun remove(obj: T): Unit = bvh.remove(obj)
fun getObjectBounds(obj: T): AABB3D? = bvh.getObjectBounds(obj)?.toAABB3D()
fun debug() {
bvh.debug()
}
}
fun BVHIntervals.toAABB3D(): AABB3D = AABB3D(Vector3F(min(0), min(1), min(2)), Vector3F(aPlusB(0), aPlusB(1), aPlusB(2)))
fun BVHRect.toAABB3D(): AABB3D = AABB3D(min.toVector3(), max.toVector3())
fun AABB3D.toBVH(out: BVHIntervals = BVHIntervals(3)): BVHRect {
out.setTo(minX.toDouble(), sizeX.toDouble(), minY.toDouble(), sizeY.toDouble(), minZ.toDouble(), sizeZ.toDouble())
return BVHRect(out)
}
fun Ray3F.toBVH(out: BVHIntervals = BVHIntervals(3)): BVHRay {
out.setTo(pos.x.toDouble(), dir.x.toDouble(), pos.y.toDouble(), dir.y.toDouble(), pos.z.toDouble(), dir.z.toDouble())
return BVHRay(out)
}
fun BVHRay.toRay3D(): Ray3F {
return Ray3F(this.pos.toVector3(), this.pos.toVector3())
}
fun BVHVector.toVector3(): Vector3F {
checkDimensions(3)
return Vector3F(this[0], this[1], this[2])
}
| 444 | WebAssembly | 121 | 2,207 | dc3d2080c6b956d4c06f4bfa90a6c831dbaa983a | 6,636 | korge | Apache License 2.0 |
inference/inference-core/src/jvmTest/kotlin/io/kinference/operators/operations/MaxTest.kt | JetBrains-Research | 244,400,016 | false | {"Kotlin": 2301067, "Python": 4774, "JavaScript": 2402, "Dockerfile": 683} | package io.kinference.operators.operations
import io.kinference.KITestEngine.KIAccuracyRunner
import io.kinference.utils.TestRunner
import kotlin.test.Test
class MaxTest {
private fun getTargetPath(dirName: String) = "max/$dirName/"
@Test
fun test_max_example() = TestRunner.runTest {
KIAccuracyRunner.runFromResources(getTargetPath("test_max_example"))
}
@Test
fun test_max_float16() = TestRunner.runTest {
KIAccuracyRunner.runFromResources(getTargetPath("test_max_float16"))
}
@Test
fun test_max_float32() = TestRunner.runTest {
KIAccuracyRunner.runFromResources(getTargetPath("test_max_float32"))
}
@Test
fun test_max_float64() = TestRunner.runTest {
KIAccuracyRunner.runFromResources(getTargetPath("test_max_float64"))
}
@Test
fun test_max_int8() = TestRunner.runTest {
KIAccuracyRunner.runFromResources(getTargetPath("test_max_int8"))
}
@Test
fun test_max_int16() = TestRunner.runTest {
KIAccuracyRunner.runFromResources(getTargetPath("test_max_int16"))
}
@Test
fun test_max_int32() = TestRunner.runTest {
KIAccuracyRunner.runFromResources(getTargetPath("test_max_int32"))
}
@Test
fun test_max_int64() = TestRunner.runTest {
KIAccuracyRunner.runFromResources(getTargetPath("test_max_int64"))
}
@Test
fun test_max_one_input() = TestRunner.runTest {
KIAccuracyRunner.runFromResources(getTargetPath("test_max_one_input"))
}
@Test
fun test_max_two_inputs() = TestRunner.runTest {
KIAccuracyRunner.runFromResources(getTargetPath("test_max_two_inputs"))
}
@Test
fun test_max_uint8() = TestRunner.runTest {
KIAccuracyRunner.runFromResources(getTargetPath("test_max_uint8"))
}
@Test
fun test_max_uint16() = TestRunner.runTest {
KIAccuracyRunner.runFromResources(getTargetPath("test_max_uint16"))
}
@Test
fun test_max_uint32() = TestRunner.runTest {
KIAccuracyRunner.runFromResources(getTargetPath("test_max_uint32"))
}
@Test
fun test_max_uint64() = TestRunner.runTest {
KIAccuracyRunner.runFromResources(getTargetPath("test_max_uint64"))
}
}
| 7 | Kotlin | 7 | 154 | d98a9c110118c861a608552f4d18b6256897ccad | 2,240 | kinference | Apache License 2.0 |
executors/src/main/kotlin/name/anton3/executors/util/RecentlyStoredCache.kt | Anton3 | 159,801,334 | true | {"Kotlin": 1382186} | package name.anton3.executors.util
import java.util.*
import java.util.concurrent.ConcurrentHashMap
import java.util.concurrent.ConcurrentSkipListMap
import java.util.concurrent.atomic.AtomicInteger
import java.util.concurrent.atomic.AtomicLong
/**
* A map-like container, which automatically removes older entries
*/
class RecentlyStoredCache<Key : Any, Value : Any>(cacheSize: Int) {
fun merge(key: Key, block: (Value?) -> Value): Value {
val newTick = ticker.getAndIncrement()
var oldValueTemp: Pair<Long, Value>? = null
val newValue = contents.compute(key) { _, x ->
oldValueTemp = x
Pair(newTick, block(x?.second))
}!!
val oldValue = oldValueTemp
lastUpdated[newTick] = key
if (oldValue != null) {
lastUpdated.remove(oldValue.first)
} else if (entriesLeft.getAndUpdate { maxOf(it - 1, 0) } == 0) {
lastUpdated.pollFirstEntry()?.let { contents.remove(it.value) }
}
return newValue.second
}
private val contents: MutableMap<Key, Pair<Long, Value>> = ConcurrentHashMap()
private val lastUpdated: NavigableMap<Long, Key> = ConcurrentSkipListMap()
private val ticker: AtomicLong = AtomicLong(0)
private val entriesLeft: AtomicInteger = AtomicInteger(cacheSize)
}
| 2 | Kotlin | 0 | 8 | 773c89751c4382a42f556b6d3c247f83aabec625 | 1,325 | kotlin-vk-api | MIT License |
library/src/main/kotlin/io/fluent/State.kt | rsicarelli | 124,893,442 | true | {"Kotlin": 3709, "Java": 1469} | package io.fluent
interface State {
fun type(): Type
}
| 0 | Kotlin | 0 | 0 | da1bdbc3a03942cb852f6b7be12800bbd16027c8 | 58 | Fluent | MIT License |
processor/src/main/kotlin/kotli/template/multiplatform/compose/dataflow/ai/gemini/GeminiProcessor.kt | kotlitecture | 790,159,970 | false | {"Kotlin": 545071, "Swift": 543, "JavaScript": 313, "HTML": 234} | package kotli.template.multiplatform.compose.dataflow.ai.gemini
import kotli.engine.BaseFeatureProcessor
import kotli.engine.FeatureProcessor
import kotli.engine.FeatureTag
import kotli.engine.TemplateState
import kotli.engine.template.VersionCatalogRules
import kotli.engine.template.rule.RemoveFile
import kotli.engine.template.rule.RemoveMarkedLine
import kotli.template.multiplatform.compose.Rules
import kotli.template.multiplatform.compose.Tags
import kotli.template.multiplatform.compose.userflow.component.markdown.MarkdownProcessor
import kotlin.time.Duration.Companion.hours
object GeminiProcessor : BaseFeatureProcessor() {
const val ID = "dataflow.ai.gemini"
override fun getId(): String = ID
override fun getTags(): List<FeatureTag> = Tags.AllClients
override fun getWebUrl(state: TemplateState): String = "https://github.com/PatilShreyas/generative-ai-kmp"
override fun getIntegrationUrl(state: TemplateState): String = "https://github.com/PatilShreyas/generative-ai-kmp?tab=readme-ov-file#installation-and-usage"
override fun getIntegrationEstimate(state: TemplateState): Long = 1.hours.inWholeMilliseconds
override fun dependencies(): List<Class<out FeatureProcessor>> = listOf(
MarkdownProcessor::class.java
)
override fun doRemove(state: TemplateState) {
state.onApplyRules(
Rules.AiSource,
RemoveFile()
)
state.onApplyRules(
Rules.BuildGradleApp,
RemoveMarkedLine("generativeai")
)
state.onApplyRules(
VersionCatalogRules(
RemoveMarkedLine("generativeai")
)
)
state.onApplyRules(
Rules.DIKt,
RemoveMarkedLine("aiSource")
)
state.onApplyRules(
Rules.ShowcasesKt,
RemoveMarkedLine("Gemini"),
RemoveMarkedLine("Dataflow :: AI"),
)
state.onApplyRules(
Rules.ShowcasesAiDir,
RemoveFile()
)
state.onApplyRules(
Rules.AppModuleKt,
RemoveMarkedLine("GeminiViewModel")
)
}
} | 2 | Kotlin | 3 | 55 | 0ea8aa724e156259d5d5c9c8a423513c61b5156b | 2,148 | template-multiplatform-compose | MIT License |
game/plugins/src/main/kotlin/gg/rsmod/plugins/content/areas/spawns/spawns_10899.plugin.kts | 2011Scape | 578,880,245 | false | {"Kotlin": 8904349, "Dockerfile": 1354} | package gg.rsmod.plugins.content.areas.spawns
spawn_npc(
npc = Npcs.IRON_DRAGON,
x = 2708,
z = 9459,
height = 0,
walkRadius = 5,
direction = Direction.NORTH,
static = false,
) // Iron dragon
spawn_npc(
npc = Npcs.IRON_DRAGON,
x = 2711,
z = 9448,
height = 0,
walkRadius = 5,
direction = Direction.NORTH,
static = false,
) // Iron dragon
spawn_npc(
npc = Npcs.IRON_DRAGON,
x = 2704,
z = 9437,
height = 0,
walkRadius = 5,
direction = Direction.NORTH,
static = false,
) // Iron dragon
spawn_npc(
npc = Npcs.IRON_DRAGON,
x = 2711,
z = 9423,
height = 0,
walkRadius = 5,
direction = Direction.NORTH,
static = false,
) // Iron dragon
spawn_npc(
npc = Npcs.IRON_DRAGON,
x = 2741,
z = 9454,
height = 0,
walkRadius = 5,
direction = Direction.NORTH,
static = false,
) // Iron dragon
spawn_npc(
npc = Npcs.IRON_DRAGON,
x = 2740,
z = 9435,
height = 0,
walkRadius = 5,
direction = Direction.NORTH,
static = false,
) // Iron dragon
spawn_npc(
npc = Npcs.IRON_DRAGON,
x = 2732,
z = 9421,
height = 0,
walkRadius = 5,
direction = Direction.NORTH,
static = false,
) // Iron dragon
spawn_npc(
npc = Npcs.STEEL_DRAGON,
x = 2704,
z = 9446,
height = 0,
walkRadius = 5,
direction = Direction.NORTH,
static = false,
) // Steel dragon
spawn_npc(
npc = Npcs.STEEL_DRAGON,
x = 2727,
z = 9458,
height = 0,
walkRadius = 5,
direction = Direction.NORTH,
static = false,
) // Steel dragon
spawn_npc(
npc = Npcs.STEEL_DRAGON,
x = 2723,
z = 9428,
height = 0,
walkRadius = 5,
direction = Direction.NORTH,
static = false,
) // Steel dragon
| 39 | Kotlin | 143 | 34 | e5400cc71bfa087164153d468979c5a3abc24841 | 1,783 | game | Apache License 2.0 |
la4k-android/src/main/kotlin/AndroidLogger.kt | wswartzendruber | 191,491,678 | false | null | /*
* SPDX-FileCopyrightText: 2020 William Swartzendruber <wswartzendruber@gmail.com>
*
* SPDX-License-Identifier: Apache-2.0
*/
package org.la4k.android
import android.util.Log
import org.la4k.Logger
public class AndroidLogger internal constructor(name: String) : Logger(name) {
val targetName =
if (name.length <= 23)
name
else
"${name.take(10)}...${name.takeLast(10)}"
public override fun fatal(
message: Any?,
throwable: Throwable?,
tag: String?,
): Unit {
if (throwable == null)
Log.e(targetName, message.toString())
else
Log.e(targetName, message.toString(), throwable)
}
public override fun error(
message: Any?,
throwable: Throwable?,
tag: String?,
): Unit {
if (throwable == null)
Log.e(targetName, message.toString())
else
Log.e(targetName, message.toString(), throwable)
}
public override fun warn(
message: Any?,
throwable: Throwable?,
tag: String?,
): Unit {
if (throwable == null)
Log.w(targetName, message.toString())
else
Log.w(targetName, message.toString(), throwable)
}
public override fun info(
message: Any?,
throwable: Throwable?,
tag: String?,
) {
if (throwable == null)
Log.i(targetName, message.toString())
else
Log.i(targetName, message.toString(), throwable)
}
public override fun debug(
message: Any?,
throwable: Throwable?,
tag: String?,
): Unit {
if (throwable == null)
Log.d(targetName, message.toString())
else
Log.d(targetName, message.toString(), throwable)
}
public override fun trace(
message: Any?,
throwable: Throwable?,
tag: String?,
): Unit { }
public override fun isFatalEnabled(tag: String?): Boolean =
Log.isLoggable(targetName, Log.ERROR)
public override fun isErrorEnabled(tag: String?): Boolean =
Log.isLoggable(targetName, Log.ERROR)
public override fun isWarnEnabled(tag: String?): Boolean =
Log.isLoggable(targetName, Log.WARN)
public override fun isInfoEnabled(tag: String?): Boolean =
Log.isLoggable(targetName, Log.INFO)
public override fun isDebugEnabled(tag: String?): Boolean =
Log.isLoggable(targetName, Log.DEBUG)
public override fun isTraceEnabled(tag: String?): Boolean =
false
}
| 0 | Kotlin | 1 | 17 | 61f96b885f4a841e302fdef2ac2744c53edbade8 | 2,587 | la4k | Apache License 2.0 |
src/main/kotlin/hu/hempq/dungeonofoterion/attributes/types/Weapon.kt | hempq | 218,700,199 | false | null | package hu.hempq.dungeonofoterion.attributes.types
import hu.hempq.dungeonofoterion.attributes.ItemCombatStats
import hu.hempq.dungeonofoterion.extensions.GameEntity
interface Weapon : CombatItem
val GameEntity<Weapon>.attackValue: Int
get() = findAttribute(ItemCombatStats::class).get().attackValue
val GameEntity<Weapon>.defenseValue: Int
get() = findAttribute(ItemCombatStats::class).get().defenseValue
| 0 | Kotlin | 0 | 0 | 5b910a2f2eefa58a720d5b580b2f76ef2b152963 | 418 | dungeon-of-oterion | Apache License 2.0 |
aspoet/src/main/kotlin/com/google/androidstudiopoet/generators/bazel/BazelLang.kt | android | 106,021,222 | false | null | /*
Copyright 2018 Google Inc.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
https://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package com.google.androidstudiopoet.generators.bazel
/**
* Bazel uses the Starlark configuration language for BUILD files and .bzl extensions.
*
* Starlark is previously known as Skylark.
*
* https://docs.bazel.build/versions/master/skylark/language.html
*/
private const val BASE_INDENT = " "
sealed class Statement
/**
* foo = "bar"
*/
data class AssignmentStatement(val lhs: String, val rhs: String) : Statement() {
override fun toString() = """$lhs = $rhs"""
}
/**
* load("@foo//bar:baz.bzl", "symbol_foo", "symbol_bar")
*/
data class LoadStatement(val module: String, val symbols: List<String>) : Statement() {
override fun toString() = """load("$module", ${symbols.map { "\"$it\"" }.joinToString(separator = ", ")})"""
}
/**
* # Comment foo bar baz
*/
data class Comment(val comment: String) {
override fun toString(): String = """# $comment"""
}
/**
* A BUILD / BUILD.bazel target.
*
* A target is made of
*
* 1) a rule class.
* 2) mandatory "name" attribute.
* 3) other rule-specific attributes.
*
* e.g.
*
* java_library(
* name = "lib_foo",
* srcs = ["Foo.java", "Bar.java"],
* deps = [":lib_baz"],
* )
*/
data class Target(val ruleClass: String, val attributes: List<Attribute>) : Statement() {
override fun toString() : String {
return when (attributes.size) {
0 -> "$ruleClass()"
else -> """$ruleClass(
$BASE_INDENT${attributes.joinToString(separator = ",\n$BASE_INDENT") { it.toString() }},
)"""
}
}
}
/**
* Data classes representing attributes in targets.
*
* To improve type safety, create data classes implementing Attribute, e.g. StringAttribute.
*
* Bazel supports the following attribute types:
*
* bool
* int
* int_list
* label
* label_keyed_string_dict
* label_list
* license
* output
* output_list
* string
* string_dict
* string_list
* string_list_dict
*
* List of attribute schemas from:
* https://docs.bazel.build/versions/master/skylark/lib/attr.html
*/
sealed class Attribute {
abstract val name: String
abstract val value: Any
}
data class RawAttribute(override val name: String, override val value: String): Attribute() {
override fun toString() = "$name = $value"
}
data class StringAttribute(override val name: String, override val value: String): Attribute() {
override fun toString() = "$name = \"$value\""
}
| 12 | Kotlin | 89 | 680 | f820e9cc0e5d7db4de9a7e31b818277143546f73 | 2,959 | android-studio-poet | Apache License 2.0 |
src/test/kotlin/ru/agalkin/beholder/DataBufferTest.kt | johnnywoo | 21,419,854 | false | null | package ru.agalkin.beholder
import ru.agalkin.beholder.testutils.NetworkedTestAbstract
import kotlin.test.Ignore
import kotlin.test.Test
import kotlin.test.assertEquals
class DataBufferTest : NetworkedTestAbstract() {
@Test
fun testSmoke() {
val messageText = "<15>1 2017-03-03T09:26:44+00:00 sender-host program-name 12345 - - Message: поехали!"
val config = "queue_chunk_messages 5; from udp 3821; to tcp 1212"
feedMessagesIntoConfig(config, 20) {
repeat(20) {
sendToUdp(3821, messageText)
}
}
}
@Test
fun testNowhereToSend() {
val messageText = "Message: поехали!"
val config = "buffer { memory_compression off; } queue_chunk_messages 5; from udp 3821; to tcp 1212"
makeApp(config).use { app ->
val root = app.config.root
var processedMessagesNum = 0
val sentMessagesNum = 20
root.topLevelOutput.addStep(conveyorStepOf {
processedMessagesNum++
})
root.start()
Thread.sleep(100)
repeat(sentMessagesNum) {
sendToUdp(3821, messageText)
}
var timeSpentMillis = 0
while (timeSpentMillis < 300) {
if (processedMessagesNum == sentMessagesNum) {
break
}
Thread.sleep(50)
timeSpentMillis += 50
}
assertEquals(sentMessagesNum, processedMessagesNum, "Expected number of messages does not match")
// total buffer length should be:
// 20 messages / chunk length 5 = 4 chunks
// we ignore first and last chunk = 2 chunks in buffer
// "Message: поехали!" = 24 bytes (17 length + 7 cyrillic second bytes)
// plus \n from tcp newline-terminated = +1 byte
// plus varint length = +1 byte
// 26 bytes per message * 10 messages = 260 bytes
// this is of course not the actual memory usage, but it's something we can measure properly
assertEquals(260, app.defaultBuffer.currentSizeInMemory.get())
}
}
@Test
@Ignore
fun testNowhereToSendCompressed() {
val messageText = "Message: поехали!"
val config = "queue_chunk_messages 5; from udp 3821; to tcp 1212"
makeApp(config).use { app ->
val root = app.config.root
var processedMessagesNum = 0
val sentMessagesNum = 20
root.topLevelOutput.addStep(conveyorStepOf {
processedMessagesNum++
})
root.start()
Thread.sleep(100)
repeat(sentMessagesNum) {
sendToUdp(3821, messageText)
}
var timeSpentMillis = 0
while (timeSpentMillis < 300) {
if (processedMessagesNum == sentMessagesNum) {
break
}
Thread.sleep(50)
timeSpentMillis += 50
}
assertEquals(sentMessagesNum, processedMessagesNum, "Expected number of messages does not match")
// when uncompressed, total buffer length is 260 bytes
// with default lz4-fast compression, it gets down to 74 bytes
assertEquals(74, app.defaultBuffer.currentSizeInMemory.get())
}
}
}
| 0 | Kotlin | 0 | 2 | f25f00b7dd0692ff67d0eda55e6a3d59299e6cdb | 3,431 | beholder | MIT License |
test-okhttp/src/main/kotlin/com/avito/test/http/ServerErrorDispatcher.kt | mduisenov | 237,274,875 | true | {"Kotlin": 2360982, "Python": 14063, "Shell": 13206, "Dockerfile": 7097, "Makefile": 35} | package com.avito.test.http
import okhttp3.mockwebserver.MockResponse
object ServerErrorDispatcher : ConstantResponseDispatcher(MockResponse().setResponseCode(500))
| 0 | Kotlin | 0 | 0 | b0513404cc36196fb87ddadd1894b9015beac952 | 167 | avito-android | Apache License 2.0 |
src/main/kotlin/utilities/MathSample.kt | crowdpro | 214,571,559 | true | {"Kotlin": 90370} | package utilities
object MathSample {
/***
* 10^9 + 7
*/
val mod: Long = (Math.pow(10.0, 9.0) + 7).toLong()
/**
* 最大公約数
* @param big 2つの値の大きな方
* @param small 2つの値の小さな方
*/
fun computeGreatestCommonDivisor(big: Long, small: Long): Long {
val rest = big % small
return if (rest == 0L) big else computeGreatestCommonDivisor(big, rest)
}
/**
* 最小公倍数
* @param big 2つの値の大きな方
* @param small 2つの値の小さな方
*/
fun computeLeastCommonMultiple(small: Long, big: Long): Long {
return small * big / computeGreatestCommonDivisor(big, small)
}
/**
* 素因数分解
* 対象の値が1になるまで素数で順番に割っていき割った数を列挙する
*/
fun computePrimeFactorList(n: Long): List<Long> {
val p = mutableListOf<Long>()
var primeFactor = n
for (i in 2..n) {
while (primeFactor % i == 0L) {
primeFactor /= i
p.add(i)
}
}
return p
}
/**
* 約数を数える
*/
fun countDivisor(n: Long): Long {
val p = computePrimeFactorList(n)
debugLog(p)
var count = 1
var ans = 0L
for (i in p.indices) {
count++
val pi = p[i]
if (i >= p.size - 1 || p[i + 1] != pi) {
ans += count
count = 1
}
}
return ans
}
/**
* 約数の総和を求める
* 素因数分解を行い、各素因数の合計を求め(0乗=1も含める)、それらを掛け合わせる
*/
fun computeDivisorSum(n: Long): Long {
val p = computePrimeFactorList(n)
var ans = 1L
var nSum = 0
var count = 0
for (i in p.indices) {
count++
val pi = p[i]
nSum += Math.pow(pi.toDouble(), count.toDouble()).toInt()
if (i >= p.size - 1 || p[i + 1] != pi) {
ans *= (nSum + 1)
count = 0
nSum = 0
}
}
return ans
}
/**
* 階乗を計算する
*/
fun computeFactorial(n: Long): Long {
return (1..n).reduce { acc, l -> acc * l }
}
} | 0 | null | 0 | 0 | 426178dbd5369a1ff73bed5d6a2ed6e13989bcab | 2,103 | AtCoderLog | The Unlicense |
science/src/main/java/com/kylecorry/sol/science/astronomy/eclipse/solar/SolarEclipseCalculator.kt | kylecorry31 | 294,668,785 | false | null | package com.kylecorry.sol.science.astronomy.eclipse.solar
import com.kylecorry.sol.math.SolMath.square
import com.kylecorry.sol.science.astronomy.Astronomy
import com.kylecorry.sol.science.astronomy.SunTimesMode
import com.kylecorry.sol.science.astronomy.eclipse.Eclipse
import com.kylecorry.sol.science.astronomy.eclipse.EclipseCalculator
import com.kylecorry.sol.science.astronomy.locators.ICelestialLocator
import com.kylecorry.sol.science.astronomy.locators.Moon
import com.kylecorry.sol.science.astronomy.locators.Sun
import com.kylecorry.sol.science.astronomy.moon.MoonTruePhase
import com.kylecorry.sol.science.astronomy.units.HorizonCoordinate
import com.kylecorry.sol.science.astronomy.units.UniversalTime
import com.kylecorry.sol.science.astronomy.units.toInstant
import com.kylecorry.sol.science.astronomy.units.toUniversalTime
import com.kylecorry.sol.units.Coordinate
import java.time.Duration
import java.time.Instant
import java.time.ZoneId
import kotlin.math.PI
import kotlin.math.abs
import kotlin.math.acos
import kotlin.math.sqrt
internal class SolarEclipseCalculator(
private val precision: Duration = Duration.ofMinutes(1),
maxDuration: Duration? = null
) : EclipseCalculator {
private val sun = Sun()
private val moon = Moon()
private val _maxDuration = maxDuration ?: Duration.ofDays(365 * 5)
override fun getNextEclipse(after: Instant, location: Coordinate): Eclipse? {
val nextEclipseTime = getNextEclipseTime(after, location) ?: return null
// Search parameters
val maxSearch = Duration.ofHours(24)
val minTime = nextEclipseTime.minus(maxSearch)
val maxTime = nextEclipseTime.plus(maxSearch)
var maxMagnitude = 0f
var maxObscuration = 0f
var timeOfMaximum = nextEclipseTime
// Search for the start of the eclipse
var currentStartTime = nextEclipseTime.toUniversalTime()
var start = nextEclipseTime
while (start > minTime) {
val sunCoordinates = getCoordinates(sun, currentStartTime, location)
val moonCoordinates = getCoordinates(moon, currentStartTime, location)
// Sun or moon is below the horizon
if (sunCoordinates.altitude < 0 || moonCoordinates.altitude < 0) {
break
}
val magnitude = getMagnitude(currentStartTime, location, sunCoordinates, moonCoordinates)
// Eclipse was not found
if (magnitude.first == 0f) {
break
}
if (magnitude.first > maxMagnitude) {
maxMagnitude = magnitude.first
maxObscuration = magnitude.second
timeOfMaximum = currentStartTime.toInstant()
}
start = currentStartTime.toInstant()
currentStartTime = currentStartTime.minus(precision)
}
// Search for the end of the eclipse
var currentEndTime = nextEclipseTime.toUniversalTime()
var end = nextEclipseTime
while (end < maxTime) {
val sunCoordinates = getCoordinates(sun, currentEndTime, location)
val moonCoordinates = getCoordinates(moon, currentEndTime, location)
// Sun or moon is below the horizon
if (sunCoordinates.altitude < 0 || moonCoordinates.altitude < 0) {
break
}
val magnitude = getMagnitude(currentEndTime, location, sunCoordinates, moonCoordinates)
// Eclipse was not found
if (magnitude.first == 0f) {
break
}
if (magnitude.first > maxMagnitude) {
maxMagnitude = magnitude.first
maxObscuration = magnitude.second
timeOfMaximum = currentEndTime.toInstant()
}
end = currentEndTime.toInstant()
currentEndTime = currentEndTime.plus(precision)
}
return Eclipse(start, end, maxMagnitude, maxObscuration, timeOfMaximum)
}
private fun getNextEclipseTime(after: Instant, location: Coordinate): Instant? {
var timeFromStart = Duration.ZERO
val startUT = after.toUniversalTime()
val defaultSkip = Duration.ofMinutes(15)
while (timeFromStart < _maxDuration) {
val currentTime = startUT.plus(timeFromStart)
val sunCoordinates = getCoordinates(sun, currentTime, location)
val moonCoordinates = getCoordinates(moon, currentTime, location)
// Skip ahead if conditions are not right for an eclipse
val nextSkip = getNextSkip(currentTime, location, sunCoordinates, moonCoordinates)
if (nextSkip != null) {
timeFromStart = timeFromStart.plus(nextSkip)
continue
}
val magnitude = getMagnitude(currentTime, location, sunCoordinates, moonCoordinates).first
if (magnitude > 0) {
return currentTime.toInstant()
}
timeFromStart = timeFromStart.plus(defaultSkip)
}
return null
}
private fun getNextSkip(
time: UniversalTime,
location: Coordinate,
sunCoordinates: HorizonCoordinate,
moonCoordinates: HorizonCoordinate
): Duration? {
// If the moon is close to full, skip a bit
val phase = moon.getPhase(time)
val daysUntilNewMoon = when (phase.phase) {
MoonTruePhase.ThirdQuarter -> 2
MoonTruePhase.WaningGibbous -> 4
MoonTruePhase.Full -> 8
MoonTruePhase.WaxingGibbous -> 12
MoonTruePhase.FirstQuarter -> 14
MoonTruePhase.WaxingCrescent -> 22
else -> 0
}
if (daysUntilNewMoon > 0) {
return Duration.ofDays(daysUntilNewMoon.toLong())
}
// If the sun is down, skip to the next sunrise
if (sunCoordinates.altitude < 0) {
return timeUntilSunrise(time, location)?.plusMinutes(15)
}
// If the moon is down, skip to the next moonrise
if (moonCoordinates.altitude < 0) {
return timeUntilMoonrise(time, location)?.plusMinutes(15)
}
// If the moon is not close to the sun, skip a bit
val distance = sunCoordinates.angularDistanceTo(moonCoordinates)
if (distance > 10) {
return Duration.ofHours(2)
} else if (distance > 2) {
return Duration.ofMinutes(30)
}
return null
}
private fun getMagnitude(
time: UniversalTime,
location: Coordinate,
sunCoordinates: HorizonCoordinate,
moonCoordinates: HorizonCoordinate
): Pair<Float, Float> {
val angularDistance = sunCoordinates.angularDistanceTo(moonCoordinates)
val moonRadius = moon.getAngularDiameter(time, location) / 2.0
val sunRadius = sun.getAngularDiameter(time) / 2.0
return getMagnitude(angularDistance, moonRadius, sunRadius)
}
private fun timeUntilSunrise(time: UniversalTime, location: Coordinate): Duration? {
val nextSunrise = Astronomy.getNextSunrise(
time.atZone(ZoneId.of("UTC")),
location,
SunTimesMode.Actual,
withRefraction = true,
withParallax = true
) ?: return null
return Duration.between(time.toInstant(), nextSunrise.toInstant())
}
private fun timeUntilMoonrise(time: UniversalTime, location: Coordinate): Duration? {
val nextMoonrise = Astronomy.getNextMoonrise(
time.atZone(ZoneId.of("UTC")),
location,
withRefraction = true,
withParallax = true
) ?: return null
return Duration.between(time.toInstant(), nextMoonrise.toInstant())
}
private fun getCoordinates(
locator: ICelestialLocator,
time: UniversalTime,
location: Coordinate
): HorizonCoordinate {
val coordinates = locator.getCoordinates(time)
return HorizonCoordinate.fromEquatorial(
coordinates,
time,
location,
locator.getDistance(time)!!
).withRefraction()
}
private fun getMagnitude(
angularDistance: Double,
moonRadius: Double,
sunRadius: Double
): Pair<Float, Float> {
if (!isAnyEclipse(angularDistance, moonRadius, sunRadius)) {
return 0f to 0f
}
if (isTotalEclipse(angularDistance, moonRadius, sunRadius)) {
val diameterRatio = (moonRadius / sunRadius).toFloat()
return if (sunRadius <= moonRadius) {
diameterRatio to 1f
} else {
val sunArea = PI * sunRadius * sunRadius
val moonArea = PI * moonRadius * moonRadius
diameterRatio to (moonArea / sunArea).toFloat()
}
}
val distance2 = square(angularDistance)
val moonRadius2 = square(moonRadius)
val sunRadius2 = square(sunRadius)
val s = (distance2 + sunRadius2 - moonRadius2) / (2 * angularDistance)
val m = (distance2 + moonRadius2 - sunRadius2) / (2 * angularDistance)
val h =
sqrt(4 * distance2 * sunRadius2 - square(distance2 + sunRadius2 - moonRadius2)) / (2 * angularDistance)
val triangleSun = h * s
val triangleMoon = h * m
val sectorSun = sunRadius2 * acos(s / sunRadius)
val sectorMoon = moonRadius2 * acos(m / moonRadius)
val areaSun = sectorSun - triangleSun
val areaMoon = sectorMoon - triangleMoon
val totalArea = (areaSun + areaMoon).toFloat()
val obscuration = totalArea / (PI * sunRadius2).toFloat()
val lengthOverlap = (sunRadius + moonRadius) - abs(s + m)
val magnitude = (lengthOverlap / (2 * sunRadius)).toFloat()
return magnitude to obscuration
}
private fun isAnyEclipse(
angularDistance: Double,
moonRadius: Double,
sunRadius: Double
): Boolean {
return angularDistance <= moonRadius + sunRadius
}
private fun isTotalEclipse(
angularDistance: Double,
moonRadius: Double,
sunRadius: Double
): Boolean {
return angularDistance <= abs(moonRadius - sunRadius)
}
} | 11 | Kotlin | 3 | 6 | 08f939c2359dfbf675607b50aee537052c287dbe | 10,323 | sol | MIT License |
src/main/kotlin/io/fixture/security/UserDetailsManagerImpl.kt | martinlau | 11,140,245 | false | null | /*
* #%L
* fixture
* %%
* Copyright (C) 2013 <NAME>
* %%
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* #L%
*/
package io.fixture.security
import io.fixture.domain.User
import io.fixture.repository.UserRepository
import java.util.HashSet
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.security.access.AccessDeniedException
import org.springframework.security.authentication.AuthenticationManager
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken
import org.springframework.security.core.authority.SimpleGrantedAuthority
import org.springframework.security.core.context.SecurityContextHolder
import org.springframework.security.core.userdetails.User as SpringUser
import org.springframework.security.core.userdetails.UserDetails
import org.springframework.security.core.userdetails.UsernameNotFoundException
import org.springframework.security.provisioning.UserDetailsManager
import org.springframework.stereotype.Component
import org.springframework.transaction.annotation.Transactional
[Component(value = "userDetailsManager")]
class UserDetailsManagerImpl [Autowired] (
val userRepository: UserRepository
): UserDetailsManager {
[Autowired(required = false)]
var authenticationManager: AuthenticationManager? = null
[Transactional]
public override fun createUser(userDetails: UserDetails) {
val user = User()
user.accountNonExpired = userDetails.isAccountNonExpired()
user.accountNonLocked = userDetails.isAccountNonLocked()
user.authorities = userDetails.getAuthorities().mapTo(HashSet<String>()) { ga -> ga.getAuthority() }
user.credentialsNonExpired = userDetails.isCredentialsNonExpired()
user.enabled = userDetails.isEnabled()
user.password = <PASSWORD>()
user.username = userDetails.getUsername()
userRepository.save(user)
}
[Transactional]
public override fun updateUser(userDetails: UserDetails) {
val user = userRepository.findOne(userDetails.getUsername())
if (user != null) {
user.accountNonExpired = userDetails.isAccountNonExpired()
user.accountNonLocked = userDetails.isAccountNonLocked()
user.authorities = userDetails.getAuthorities().mapTo(HashSet<String>()) { ga -> ga.getAuthority() }
user.credentialsNonExpired = userDetails.isCredentialsNonExpired()
user.enabled = userDetails.isEnabled()
user.password = <PASSWORD>()
user.username = userDetails.getUsername()
userRepository.save(user)
}
}
[Transactional]
public override fun deleteUser(username: String?) {
if (username != null)
userRepository.delete(username)
}
[Transactional]
public override fun changePassword(oldPassword: String?, newPassword: String?) {
val authentication = SecurityContextHolder.getContext().getAuthentication()
if (authentication == null)
throw AccessDeniedException("Can't change password as no Authentication object found in context for current user.")
val username = authentication.getName()
if (authenticationManager != null)
authenticationManager!!.authenticate(UsernamePasswordAuthenticationToken(username, oldPassword))
val user = userRepository.findOne(username!!)
if (user != null) {
user.password = <PASSWORD>
userRepository.save(user)
val userDetails = user.toUserDetails()
val newAuthentication = UsernamePasswordAuthenticationToken(userDetails, newPassword, userDetails.getAuthorities())
SecurityContextHolder.getContext().setAuthentication(newAuthentication)
}
}
[Transactional(readOnly = true)]
public override fun userExists(username: String?): Boolean = username != null && userRepository.exists(username)
[Transactional(readOnly = true)]
public override fun loadUserByUsername(username: String?): UserDetails {
if (username == null)
throw UsernameNotFoundException(username)
val user = userRepository.findOne(username)
if (user == null)
throw UsernameNotFoundException(username)
return user.toUserDetails()
}
fun User.toUserDetails(): UserDetails = SpringUser(
username,
password,
enabled,
accountNonExpired,
credentialsNonExpired,
accountNonLocked,
authorities.map { SimpleGrantedAuthority(it) }
)
}
| 6 | Kotlin | 0 | 0 | a751ea312708bac231f01dbf66ed1859a79f684a | 5,128 | fixture | Apache License 2.0 |
app/src/main/java/com/dicoding/parentpal/ui/auth/LoginActivity.kt | yeetologist | 728,081,674 | false | {"Kotlin": 74288} | package com.dicoding.parentpal.ui.auth
import android.content.Intent
import android.os.Bundle
import android.view.View
import androidx.activity.viewModels
import androidx.appcompat.app.AppCompatActivity
import com.dicoding.parentpal.data.remote.Result
import com.dicoding.parentpal.data.remote.response.LoginResponse
import com.dicoding.parentpal.databinding.ActivityLoginBinding
import com.dicoding.parentpal.ui.MainActivity
import com.dicoding.parentpal.ui.ViewModelFactory
import com.dicoding.parentpal.util.PreferenceManager
import com.dicoding.parentpal.util.showSnackbarShort
class LoginActivity : AppCompatActivity() {
private lateinit var binding: ActivityLoginBinding
private val loginViewModel: LoginViewModel by viewModels {
ViewModelFactory(this)
}
private lateinit var preferenceManager: PreferenceManager
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = ActivityLoginBinding.inflate(layoutInflater)
setContentView(binding.root)
setupAction()
preferenceManager = PreferenceManager(this)
binding.btnSignup.setOnClickListener {
startActivity(Intent(this@LoginActivity, SignupActivity::class.java))
}
binding.btnLoginBack.setOnClickListener {
finish()
}
}
private fun setupAction() {
binding.btnLogin.setOnClickListener {
val email = binding.etLoginEmail.text.toString()
val password = binding.etLoginPassword.text.toString()
loginViewModel.postLogin(email, password).observe(this) {
if (it != null) {
when (it) {
is Result.Loading -> {
showLoading(true)
}
is Result.Success -> {
showLoading(false)
processLogin(it.data)
}
is Result.Error -> {
showLoading(false)
showSnackbarShort(it.error, binding.root)
}
}
}
}
}
}
private fun processLogin(data: LoginResponse) {
val email = binding.etLoginEmail.text.toString()
loginViewModel.getUsers(data.accessToken).observe(this) {
if (it != null) {
when (it) {
is Result.Loading -> {
showLoading(true)
}
is Result.Success -> {
showLoading(false)
it.data.forEach { item ->
if (item.email == email) {
preferenceManager.savePreferences(item)
startActivity(Intent(this, MainActivity::class.java))
finish()
}
}
}
is Result.Error -> {
showLoading(false)
showSnackbarShort(it.error, binding.root)
}
}
}
}
}
private fun showLoading(bool: Boolean) {
binding.vLayer.visibility = if (bool) View.VISIBLE else View.GONE
binding.progressBar.visibility = if (bool) View.VISIBLE else View.GONE
}
} | 0 | Kotlin | 0 | 0 | b7eb602c9c78df4fd89c17ce381a9eed7a20e09b | 3,481 | MD | MIT License |
couchbase-lite/src/commonMain/kotlin/kotbase/Select.kt | jeffdgr8 | 518,984,559 | false | {"Kotlin": 2289925, "Python": 294} | /*
* Copyright 2022-2023 <NAME>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package kotbase
/**
* Select represents the SELECT clause of the query for specifying the returning properties in each
* query result row.
*/
public expect class Select : Query, FromRouter {
public override fun from(dataSource: DataSource): From
}
| 0 | Kotlin | 0 | 7 | 188723bf0c4609b649d157988de44ac140e431dd | 852 | kotbase | Apache License 2.0 |
api/src/main/kotlin/de/jnkconsulting/e3dc/easyrscp/api/frame/WBExternalDataParser.kt | jnk-cons | 691,762,451 | false | {"Kotlin": 914173} | package de.jnkconsulting.e3dc.easyrscp.api.frame
/**
* Defines a parser to parse the binary data of the response blocks which are prefixed with EXTERN_DATA_*.
*
* @since 2.3
*/
interface WBExternalDataParser {
/**
* Parses the data blocks of type [de.jnkconsulting.e3dc.easyrscp.api.frame.tags.WBTag.EXTERN_DATA_SUN],
* [de.jnkconsulting.e3dc.easyrscp.api.frame.tags.WBTag.EXTERN_DATA_NET] and [de.jnkconsulting.e3dc.easyrscp.api.frame.tags.WBTag.EXTERN_DATA_ALL].
*
* @param block Response block from the housekeeper. This must be of a supported type. See function description
*
* @return Parsing result
* @throws IllegalArgumentException If the given data block is not of a supported type or the structure of the external data cannot be interpreted.
*
* @since 2.3
*/
fun parseEnergyData(block: Data): WBExternalEnergyData
}
| 5 | Kotlin | 0 | 1 | b30bee512dabc47bd55eb91d598b9feb4b6b4654 | 891 | easy-rscp | MIT License |
rpgJavaInterpreter-core/src/test/kotlin/com/smeup/rpgparser/overlay/RpgParserOverlayTest11.kt | BezouwenR | 227,047,172 | true | {"Kotlin": 621023, "ANTLR": 158559, "Ruby": 1899, "PowerShell": 861, "Dockerfile": 551, "Batchfile": 395} | package com.smeup.rpgparser.overlay
import com.smeup.rpgparser.assertASTCanBeProduced
import com.smeup.rpgparser.assertCanBeParsed
import com.smeup.rpgparser.executeAnnotations
import com.smeup.rpgparser.interpreter.DummyDBInterface
import com.smeup.rpgparser.interpreter.InternalInterpreter
import com.smeup.rpgparser.interpreter.NumberType
import com.smeup.rpgparser.jvminterop.JavaSystemInterface
import com.smeup.rpgparser.parsing.parsetreetoast.resolve
import com.smeup.rpgparser.rgpinterop.DirRpgProgramFinder
import com.smeup.rpgparser.rgpinterop.RpgSystem
import org.junit.Ignore
import org.junit.Test
import java.io.File
import kotlin.test.assertEquals
@Ignore // randomly fails, probably does not find the .rpgle file
class RpgParserOverlayTest11 {
@Test
fun parseMUTE11_11C_syntax() {
assertCanBeParsed("overlay/MUTE11_11C", withMuteSupport = true)
}
@Test
fun parseMUTE11_11C_ast() {
assertASTCanBeProduced("overlay/MUTE11_11C", considerPosition = true, withMuteSupport = true)
}
@Test
fun parseMUTE11_11C_runtime() {
RpgSystem.addProgramFinder(DirRpgProgramFinder(File("src/test/resources/overlay")))
val cu = assertASTCanBeProduced("overlay/MUTE11_11C", considerPosition = true, withMuteSupport = true)
cu.resolve(DummyDBInterface)
val interpreter = InternalInterpreter(JavaSystemInterface())
interpreter.execute(cu, mapOf())
val annotations = interpreter.systemInterface.getExecutedAnnotation().toSortedMap()
var failed: Int = executeAnnotations(annotations)
if (failed > 0) {
throw AssertionError("$failed/${annotations.size} failed annotation(s) ")
}
}
@Test
fun parseMUTE11_15_syntax() {
assertCanBeParsed("overlay/MUTE11_15", withMuteSupport = true)
}
@Test
fun parseMUTE11_15_ast() {
val cu = assertASTCanBeProduced("overlay/MUTE11_15", considerPosition = true, withMuteSupport = true)
cu.resolve(DummyDBInterface)
val FUND1 = cu.getDataDefinition("£FUND1")
val FUNQT = FUND1.getFieldByName("£FUNQT")
assertEquals(Pair(442, 457), FUNQT.offsets)
assertEquals(NumberType(entireDigits = 10, decimalDigits = 5, rpgType = ""), FUNQT.type)
assertEquals(15, FUNQT.size)
}
@Test
fun parseMUTE11_15_runtime() {
val cu = assertASTCanBeProduced("overlay/MUTE11_15", considerPosition = true, withMuteSupport = true)
cu.resolve(DummyDBInterface)
val interpreter = InternalInterpreter(JavaSystemInterface())
interpreter.execute(cu, mapOf())
val annotations = interpreter.systemInterface.getExecutedAnnotation().toSortedMap()
var failed: Int = executeAnnotations(annotations)
if (failed > 0) {
throw AssertionError("$failed/${annotations.size} failed annotation(s) ")
}
}
@Test
fun parseMUTE11_16_runtime() {
RpgSystem.addProgramFinder(DirRpgProgramFinder(File("src/test/resources/overlay")))
val cu = assertASTCanBeProduced("overlay/MUTE11_16", considerPosition = true, withMuteSupport = true)
cu.resolve(DummyDBInterface)
val interpreter = InternalInterpreter(JavaSystemInterface())
interpreter.execute(cu, mapOf())
val annotations = interpreter.systemInterface.getExecutedAnnotation().toSortedMap()
var failed: Int = executeAnnotations(annotations)
if (failed > 0) {
throw AssertionError("$failed/${annotations.size} failed annotation(s) ")
}
}
}
| 0 | null | 0 | 1 | fe6e72c95b3ee7280c3a39b4370d505fc4905a7f | 3,576 | jariko | Apache License 2.0 |
Introduction/LastPush/Helpers/test/Tests.kt | jetbrains-academy | 504,249,857 | false | null | import org.jetbrains.academy.test.system.invokeWithArgs
import org.junit.jupiter.api.Assertions
import org.junit.jupiter.api.Test
import org.junit.jupiter.api.assertThrows
import org.junit.jupiter.params.ParameterizedTest
import org.junit.jupiter.params.provider.Arguments
import org.junit.jupiter.params.provider.MethodSource
import util.*
import java.lang.reflect.InvocationTargetException
class Test {
companion object {
@JvmStatic
fun patternRows() = patternRowsData()
@JvmStatic
fun patternHeights() = Pattern.values().map { Arguments.of(it.pattern, it.height) }
}
@Test
fun fillPatternRowFunction() {
fillPatternRowMethod.getMethodFromClass()
}
@ParameterizedTest
@MethodSource("patternRows")
fun fillPatternRowImplementation(
patternRow: String,
patternWidth: Int,
expectedRow: String
) {
val userMethod = fillPatternRowMethod.getMethodFromClass()
Assertions.assertEquals(
expectedRow, userMethod.invokeWithArgs(patternRow, patternWidth, clazz = findClassSafe()),
"For pattern row: $patternRow and patternWidth: $patternWidth the function ${fillPatternRowMethod.name} should return $expectedRow"
)
}
@Test
fun fillPatternRowErrorCase() {
val patternRow = ball.repeat(6)
val patternWidth = 5
try {
val userMethod = fillPatternRowMethod.getMethodFromClass()
userMethod.invokeWithArgs(patternRow, patternWidth, clazz = findClassSafe())
} catch (e: InvocationTargetException) {
assert("IllegalStateException" in e.stackTraceToString()) {"The method ${fillPatternRowMethod.name} should throw an IllegalStateException error if patternRow.length > patternWidth, you can check your solution with this data: patternRow = $patternRow and patternWidth = $patternWidth"}
}
}
@Test
fun getPatternHeightFunction() {
getPatternHeightMethod.getMethodFromClass()
}
@ParameterizedTest
@MethodSource("patternHeights")
fun getPatternHeightImplementation(
pattern: String,
patternHeight: Int,
) {
val userMethod = getPatternHeightMethod.getMethodFromClass()
Assertions.assertEquals(
patternHeight, userMethod.invokeWithArgs(pattern, clazz = findClassSafe()),
"For pattern:$newLineSymbol$pattern$newLineSymbol the function ${getPatternHeightMethod.name} should return $patternHeight"
)
}
} | 9 | Kotlin | 0 | 5 | fdd11c7ae582ff7a220218e4a66f87e3e0f97839 | 2,526 | kotlin-onboarding-introduction | MIT License |
app/src/main/java/com/mrz/sp/test/MainActivity.kt | z-zghiba | 270,005,551 | false | null | package com.mrz.sp.test
import android.os.Bundle
import android.util.Log
import androidx.appcompat.app.AppCompatActivity
import com.mrz.sp.Preference
import java.util.*
class MainActivity : AppCompatActivity() {
private val TAG = "PREF==>"
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
Preference.clear()
}
}
| 0 | Kotlin | 2 | 7 | 0900bd15eb70c77e12e557740ea7c364cba9f2b0 | 439 | SP | Apache License 2.0 |
src/main/kotlin/no/nav/samordning/hendelser/security/TpnrValidator.kt | navikt | 156,209,069 | false | null | package no.nav.samordning.hendelser.security
import io.netty.channel.ChannelOption
import io.netty.handler.timeout.ReadTimeoutHandler
import no.nav.pensjonsamhandling.maskinporten.validation.orgno.RequestAwareOrganisationValidator
import org.slf4j.LoggerFactory
import org.springframework.beans.factory.annotation.Value
import org.springframework.http.client.reactive.ReactorClientHttpConnector
import org.springframework.stereotype.Service
import org.springframework.web.reactive.function.client.WebClient
import reactor.core.publisher.Mono
import reactor.netty.http.client.HttpClient
import javax.servlet.http.HttpServletRequest
@Service
class TpnrValidator(
webClientBuilder: WebClient.Builder,
@Value("\${TPCONFIG_URL}")
val tpconfigUri: String
) : RequestAwareOrganisationValidator {
private val webClient = webClientBuilder.clientConnector(
ReactorClientHttpConnector(
HttpClient.create()
.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, CONNECT_TIMEOUT_MILLIS)
.doOnConnected {
it.addHandler(ReadTimeoutHandler(READ_TIMEOUT_MILLIS / 1000))
}
)
).build()
override fun invoke(orgno: String, o: HttpServletRequest): Boolean {
val tpnr = o.getParameter("tpnr").substringBefore('?')
return webClient.get().uri("$tpconfigUri/organisation/validate/" + tpnr + "_" + orgno)
.exchangeToMono { response ->
val status = response.statusCode()
LOG.info("validateOrganisation status [$orgno, $tpnr]: ${status.value()}")
Mono.just(status.is2xxSuccessful)
}
.block()!!
}
companion object {
private val LOG = LoggerFactory.getLogger(TpnrValidator::class.java)
private const val READ_TIMEOUT_MILLIS = 5000
private const val CONNECT_TIMEOUT_MILLIS = 3000
}
}
| 0 | Kotlin | 0 | 1 | c49a2ae8a8d527739332200cb013ef3c9ea3c64c | 1,905 | samordning-hendelse-api | MIT License |
kotest-assertions/kotest-assertions-shared/src/jvmMain/kotlin/io/kotest/assertions/ErrorCollector.kt | kotest | 47,071,082 | false | null | @file:JvmName("jvmerrorcollector")
package io.kotest.assertions
import kotlinx.coroutines.asContextElement
actual val errorCollector: ErrorCollector get() = ThreadLocalErrorCollector.instance.get()
/**
* A [kotlin.coroutines.CoroutineContext.Element] which keeps the error collector synchronized with thread-switching coroutines.
*
* When using [withClue] or [assertSoftly] on the JVM without the Kotest framework, this context element
* should be added to each top-level coroutine context, e.g. via
* - runBlocking(errorCollectorContextElement) { ... }
* - runBlockingTest(Dispatchers.IO + errorCollectorContextElement) { ... }
*/
val errorCollectorContextElement get() = ThreadLocalErrorCollector.instance.asContextElement()
class ThreadLocalErrorCollector : BasicErrorCollector() {
companion object {
val instance = object : ThreadLocal<ErrorCollector>() {
override fun initialValue() = ThreadLocalErrorCollector()
}
}
}
| 37 | null | 470 | 3,260 | 6615f1b1a8b9b54d7f6981f08625b7cdcb9621d7 | 963 | kotest | Apache License 2.0 |
_src/Chapter03/JavaBasedConfiguration/src/lifecycleCallback/Foo.kt | paullewallencom | 319,169,129 | false | null | package lifecycleCallback
class Foo{
fun init(){
println("Foo is initializing...")
}
fun destroy(){
println("Foo is destroying...")
}
} | 0 | Kotlin | 0 | 1 | 7f70b39ec3926fe712617984974b13e6039df5c0 | 169 | android-spring-978-1-7893-4925-2 | Apache License 2.0 |
rsocket-engine/src/main/kotlin/io/timemates/api/rsocket/timers/commands/GetTimerCommand.kt | timemates | 575,534,072 | false | {"Kotlin": 150561} | package io.timemates.api.rsocket.timers.commands
import io.timemates.api.rsocket.ApiContainer
import io.timemates.api.rsocket.authorizations.toExtra
import io.timemates.api.rsocket.common.commands.RSocketCommand
import io.timemates.api.rsocket.timers.sdk
import io.timemates.sdk.timers.requests.GetTimerRequest
import io.timemates.api.timers.requests.GetTimerRequest as RSGetTimerRequest
internal object GetTimerCommand : RSocketCommand<GetTimerRequest, GetTimerRequest.Result> {
override suspend fun execute(apis: ApiContainer, input: GetTimerRequest): GetTimerRequest.Result {
return apis.timers.getTimer(
message = RSGetTimerRequest(
timerId = input.timerId.long,
),
extra = input.accessHash.toExtra(),
).let { result ->
GetTimerRequest.Result(result.sdk())
}
}
} | 2 | Kotlin | 0 | 9 | 937aa16f81a0bb657c7d902e3831994a1e8c7e5d | 864 | sdk | MIT License |
desktop/src/main/java/fr/arthurvimond/processingmultitemplate/desktop/Main.kt | ArthurVimond | 156,523,410 | false | null | package fr.arthurvimond.processingmultitemplate.desktop
import fr.arthurvimond.processingmultitemplate.sketch.Sketch
import processing.core.PApplet
fun main(args: Array<String>) {
PApplet.main(Sketch::class.java.name, args)
} | 0 | Kotlin | 0 | 0 | 34e7020eb425b7731c5be0d278cf2f02d5ad111b | 231 | processing-multi-template | Apache License 2.0 |
desktop/src/main/java/fr/arthurvimond/processingmultitemplate/desktop/Main.kt | ArthurVimond | 156,523,410 | false | null | package fr.arthurvimond.processingmultitemplate.desktop
import fr.arthurvimond.processingmultitemplate.sketch.Sketch
import processing.core.PApplet
fun main(args: Array<String>) {
PApplet.main(Sketch::class.java.name, args)
} | 0 | Kotlin | 0 | 0 | 34e7020eb425b7731c5be0d278cf2f02d5ad111b | 231 | processing-multi-template | Apache License 2.0 |
apps/etterlatte-brev-api/src/main/kotlin/no/nav/etterlatte/brev/vedtak/VedtaksvurderingKlient.kt | navikt | 417,041,535 | false | null | package no.nav.etterlatte.brev.vedtak
import com.github.michaelbull.result.mapBoth
import com.typesafe.config.Config
import io.ktor.client.HttpClient
import no.nav.etterlatte.libs.common.deserialize
import no.nav.etterlatte.libs.common.vedtak.Vedtak
import no.nav.etterlatte.libs.ktorobo.AzureAdClient
import no.nav.etterlatte.libs.ktorobo.DownstreamResourceClient
import no.nav.etterlatte.libs.ktorobo.Resource
import org.slf4j.LoggerFactory
class VedtakvurderingKlientException(override val message: String, override val cause: Throwable) :
Exception(message, cause)
class VedtaksvurderingKlient(config: Config, httpClient: HttpClient) {
private val logger = LoggerFactory.getLogger(VedtaksvurderingKlient::class.java)
private val azureAdClient = AzureAdClient(config)
private val downstreamResourceClient = DownstreamResourceClient(azureAdClient, httpClient)
private val clientId = config.getString("vedtak.client.id")
private val resourceUrl = config.getString("vedtak.resource.url")
suspend fun hentVedtak(behandlingId: String, accessToken: String): Vedtak {
try {
logger.info("Henter vedtaksvurdering behandling med behandlingId=$behandlingId")
return downstreamResourceClient.get(
Resource(clientId, "$resourceUrl/api/behandlinger/$behandlingId/fellesvedtak"),
accessToken
).mapBoth(
success = { resource -> resource.response.let { deserialize(it.toString()) } },
failure = { errorResponse -> throw errorResponse }
)
} catch (e: Exception) {
throw VedtakvurderingKlientException(
"Henting vedtak for behandling med behandlingId=$behandlingId feilet",
e
)
}
}
} | 6 | Kotlin | 0 | 3 | 8d41d2e006b5df41eacef84a670bc162ed72233c | 1,799 | pensjon-etterlatte-saksbehandling | MIT License |
src/main/kotlin/dev/michaelkaserer/demo/user/domain/UserService.kt | mi-kas | 408,870,249 | false | {"Kotlin": 15082} | package dev.michaelkaserer.demo.user.domain
import dev.michaelkaserer.demo.user.db.UserEntity
import dev.michaelkaserer.demo.user.db.UserRepository
import dev.michaelkaserer.demo.user.rest.CreateUserRequest
import org.springframework.stereotype.Service
import java.util.*
@Service
class UserService(
private val userRepository: UserRepository
) {
suspend fun getByApiKey(apiKey: String) = userRepository.findByApiKey(apiKey)
suspend fun create(user: CreateUserRequest): CreateUserOutcome {
if (userRepository.existsByEmail(user.email)) return CreateUserOutcome.AlreadyExisting
val createdUser = userRepository.save(
UserEntity(
email = user.email,
apiKey = generateApiKey(),
)
)
// TODO: Send email with api key to user
return CreateUserOutcome.Success(createdUser)
}
companion object {
fun generateApiKey() = UUID.randomUUID().toString().replace("-", "")
}
} | 0 | Kotlin | 0 | 1 | 12ff7d61f8d30815c7b0352cc9be4f2e94a5d41b | 991 | springboot-webflux-security-apikey-demo | MIT License |
app/src/main/java/com/luckhost/lockscreen_notes/presentation/userLogin/LoginViewModel.kt | LuckHost | 818,856,648 | false | {"Kotlin": 114524} | package com.luckhost.lockscreen_notes.presentation.userLogin
import android.util.Log
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.luckhost.domain.models.Either
import com.luckhost.domain.models.network.AuthToken
import com.luckhost.domain.models.network.LoginInformation
import com.luckhost.domain.useCases.network.GetAuthTokenUseCase
import com.luckhost.domain.useCases.network.SignUpUseCase
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.launch
class LoginViewModel(
private val getAuthTokenUseCase: GetAuthTokenUseCase,
private val signUpUseCase: SignUpUseCase,
): ViewModel() {
private var authToken = AuthToken(null, null)
private val _toastNotification = MutableStateFlow("")
val toastNotification: StateFlow<String> = _toastNotification.asStateFlow()
private val _loginTextState = MutableStateFlow("")
private val _passwordTextState = MutableStateFlow("")
private val _passwordRepeatTextState = MutableStateFlow("")
val loginTextState: StateFlow<String> = _loginTextState.asStateFlow()
val passwordTextState: StateFlow<String> = _passwordTextState.asStateFlow()
val passwordRepeatTextState: StateFlow<String> = _passwordRepeatTextState.asStateFlow()
fun clearToastNotification() {
_toastNotification.value = ""
}
fun updateLoginText(newText: String) {
_loginTextState.value = newText
}
fun updatePasswordText(newText: String) {
_passwordTextState.value = newText
}
fun updatePasswordRepeatText(newText: String) {
_passwordRepeatTextState.value = newText
}
fun signUp() {
viewModelScope.launch {
val response = signUpUseCase.execute(
loginParams = LoginInformation(
username = loginTextState.value,
password = <PASSWORD>
)
)
when(response) {
is Either.Right -> {
_toastNotification.value = "Registration is successful!"
}
is Either.Left -> {
_toastNotification.value = "${response.a}"
Log.e("LoginVM", "error: ${response.a}")
}
}
}
}
fun getToken() {
viewModelScope.launch {
val response = getAuthTokenUseCase.execute(
loginParams = LoginInformation(
username = loginTextState.value,
password = passwordTextState.value
)
)
when(response) {
is Either.Right -> {
authToken = response.b
_toastNotification.value = "Login is successful!"
}
is Either.Left -> {
_toastNotification.value = "${response.a}"
Log.e("LoginVM", "error: ${response.a}")
}
}
}
}
} | 0 | Kotlin | 0 | 0 | 71032665797194ec512803a7dc2167ff75f1f466 | 3,091 | anynote_android | The Unlicense |
store/src/commonTest/kotlin/org/mobilenativefoundation/store/store5/util/fake/NotesDatabase.kt | MobileNativeFoundation | 226,169,258 | false | null | package org.mobilenativefoundation.store.store5.util.fake
import org.mobilenativefoundation.store.store5.util.model.SOTNote
internal class NotesDatabase {
private val db: MutableMap<NotesKey, SOTNote?> = mutableMapOf()
fun put(key: NotesKey, input: SOTNote, fail: Boolean = false): Boolean {
if (fail) {
throw Exception()
}
db[key] = input
return true
}
fun get(key: NotesKey, fail: Boolean = false): SOTNote? {
if (fail) {
throw Exception()
}
return db[key]
}
fun clear(key: NotesKey, fail: Boolean = false): Boolean {
if (fail) {
throw Exception()
}
db.remove(key)
return true
}
fun clear(fail: Boolean = false): Boolean {
if (fail) {
throw Exception()
}
db.clear()
return true
}
}
| 49 | Kotlin | 187 | 2,836 | fbcd34fd168deaf5f731414e1315c704219ac6c8 | 895 | Store | Apache License 2.0 |
app/src/main/java/com/example/myvideocallapp/VideoCallActivity.kt | 100mslive | 389,945,562 | false | null | package com.example.myvideocallapp
import android.os.Bundle
import androidx.activity.viewModels
import androidx.appcompat.app.AppCompatActivity
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.example.myvideocallapp.videocall.list.PeerAdapter
const val BUNDLE_AUTH_TOKEN = "100ms-auth-token-bundle-key"
const val BUNDLE_NAME = "100ms-user-name-bundle-key"
class VideoCallActivity : AppCompatActivity() {
private val TAG = VideoCallActivity::class.java.simpleName
private val peerAdapter = PeerAdapter()
private val NUM_PEERS_PER_ROW = 2
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_video_call)
val authToken = intent?.extras?.getString(BUNDLE_AUTH_TOKEN)
val name = intent?.extras?.getString(BUNDLE_NAME)
val vm: VideoCallVm by viewModels { VideoCallViewModelFactory(name, authToken, application) }
findViewById<RecyclerView>(R.id.recyclerView).apply {
layoutManager = GridLayoutManager(this@VideoCallActivity, NUM_PEERS_PER_ROW)
adapter = peerAdapter
}
vm.videoCallParticipants.observe(this, {
peerAdapter.submitList(it)
})
}
} | 0 | Kotlin | 1 | 6 | 05f7bcd50791a033f7ee545eeea16c703ec6207b | 1,304 | hello-world-android | MIT License |
LibExpQQ/src/main/java/com/xy/qq/login/LoginAssemblyView.kt | xiuone | 291,512,847 | false | null | package com.xy.qq.login
import android.view.View
import xy.xy.base.assembly.load.BaseAssemblyViewLoadDialog
interface LoginAssemblyView : BaseAssemblyViewLoadDialog,LoginQQListener {
fun onCreateQQLoginView(): View?
} | 0 | Kotlin | 1 | 2 | 51bc46fde7d03484241b04cddc77236dbecf4469 | 223 | ajinlib | Apache License 2.0 |
app/src/main/kotlin/com/judas/katachi/feature/configuration/ConfigurationRepository.kt | Judas | 313,080,504 | false | {"Kotlin": 52142} | package com.judas.katachi.feature.configuration
import com.judas.katachi.feature.theme.Theme
import com.judas.katachi.utility.prefReader
import com.judas.katachi.utility.prefWriter
class ConfigurationRepository {
companion object {
// Content
private const val KEY_MOVE_SPEED = "move-speed"
private const val KEY_JOSEKI = "joseki"
// Goban
private const val KEY_BACKGROUND = "background"
private const val KEY_LINE_COLOR = "line-color"
// Black stones
private const val KEY_BLACK_STONE_COLOR = "black-stone-color"
private const val KEY_BLACK_BORDER_COLOR = "black-border-color"
// White stones
private const val KEY_WHITE_STONE_COLOR = "white-stone-color"
private const val KEY_WHITE_BORDER_COLOR = "white-border-color"
private val keys = listOf(
KEY_MOVE_SPEED,
KEY_JOSEKI,
KEY_BACKGROUND,
KEY_LINE_COLOR,
KEY_BLACK_STONE_COLOR,
KEY_BLACK_BORDER_COLOR,
KEY_WHITE_STONE_COLOR,
KEY_WHITE_BORDER_COLOR
)
}
fun clear() = keys.iterator().forEach { prefWriter().remove(it).apply() }
// Content
var moveSpeed: Float
get() = prefReader().getFloat(KEY_MOVE_SPEED, 2f)
set(value) = prefWriter().putFloat(KEY_MOVE_SPEED, value).apply()
var playJoseki: Boolean
get() = prefReader().getBoolean(KEY_JOSEKI, true)
set(value) = prefWriter().putBoolean(KEY_JOSEKI, value).apply()
// Goban
var backgroundColor: Int
get() = prefReader().getInt(KEY_BACKGROUND, Theme.Classic.backgroundColor)
set(value) = prefWriter().putInt(KEY_BACKGROUND, value).apply()
var lineColor: Int
get() = prefReader().getInt(KEY_LINE_COLOR, Theme.Classic.lineColor)
set(value) = prefWriter().putInt(KEY_LINE_COLOR, value).apply()
// Black stones
var blackStoneColor: Int
get() = prefReader().getInt(KEY_BLACK_STONE_COLOR, Theme.Classic.blackStoneColor)
set(value) = prefWriter().putInt(KEY_BLACK_STONE_COLOR, value).apply()
var blackStoneBorderColor: Int
get() = prefReader().getInt(KEY_BLACK_BORDER_COLOR, Theme.Classic.blackStoneBorderColor)
set(value) = prefWriter().putInt(KEY_BLACK_BORDER_COLOR, value).apply()
// White stones
var whiteStoneColor: Int
get() = prefReader().getInt(KEY_WHITE_STONE_COLOR, Theme.Classic.whiteStoneColor)
set(value) = prefWriter().putInt(KEY_WHITE_STONE_COLOR, value).apply()
var whiteStoneBorderColor: Int
get() = prefReader().getInt(KEY_WHITE_BORDER_COLOR, Theme.Classic.whiteStoneBorderColor)
set(value) = prefWriter().putInt(KEY_WHITE_BORDER_COLOR, value).apply()
}
| 0 | Kotlin | 0 | 1 | dd5a536863851ff70ec4c6e60be70ba2298a5abd | 2,778 | Katachi | Apache License 2.0 |
compiler-integration-test/src/test/kotlin/land/sungbin/composeinvestigator/compiler/test/_source/codegen/NoStateTracking.kt | jisungbin | 703,660,716 | false | {"Kotlin": 348589} | /*
* Developed by Ji Sungbin 2024.
*
* Licensed under the MIT.
* Please see full license: https://github.com/jisungbin/ComposeInvestigator/blob/main/LICENSE
*/
@file:Suppress("TestFunctionName", "UNUSED_VARIABLE", "unused")
@file:OptIn(ExperimentalTransitionApi::class)
package land.sungbin.composeinvestigator.compiler.test._source.codegen
import androidx.compose.animation.core.Animatable
import androidx.compose.animation.core.AnimationState
import androidx.compose.animation.core.ExperimentalTransitionApi
import androidx.compose.animation.core.MutableTransitionState
import androidx.compose.animation.core.VectorConverter
import androidx.compose.animation.core.animateFloat
import androidx.compose.animation.core.rememberInfiniteTransition
import androidx.compose.animation.core.rememberTransition
import androidx.compose.runtime.Composable
import androidx.compose.runtime.State
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import land.sungbin.composeinvestigator.runtime.NoInvestigation
@Suppress("UnrememberedMutableState", "UnrememberedAnimatable")
@Composable
private fun UnrememberedStates() {
@NoInvestigation val state = object : State<Int> {
override val value: Int = 0
}
@NoInvestigation val mutableState = mutableStateOf(0)
@NoInvestigation val animatable = Animatable(0f)
@NoInvestigation val animationState = AnimationState(
typeConverter = Float.VectorConverter,
initialValue = 0f,
)
}
@Suppress("UnrememberedMutableState", "UnrememberedAnimatable")
@Composable
private fun UnrememberedStatesDelegation() {
@NoInvestigation val state by object : State<Int> {
override val value: Int = 0
}
@NoInvestigation val mutableState by mutableStateOf(0)
@NoInvestigation val animationState by AnimationState(
typeConverter = Float.VectorConverter,
initialValue = 0f,
)
}
@Composable
private fun RememberedStates() {
@NoInvestigation val state = remember {
object : State<Int> {
override val value: Int = 0
}
}
@NoInvestigation val mutableState = remember { mutableStateOf(0) }
@NoInvestigation val animatable = remember { Animatable(0f) }
@NoInvestigation val animationState = remember {
AnimationState(
typeConverter = Float.VectorConverter,
initialValue = 0f,
)
}
@NoInvestigation val transitionAnimationState =
rememberTransition(transitionState = MutableTransitionState(0f))
.animateFloat(label = "unremembered") { prevState -> prevState * 2 }
@NoInvestigation val infiniteTransition = rememberInfiniteTransition(label = "unremembered")
}
@Composable
private fun RememberedStatesDelegation() {
@NoInvestigation val state by remember {
object : State<Int> {
override val value: Int = 0
}
}
@NoInvestigation val mutableState by remember { mutableStateOf(0) }
@NoInvestigation val animationState by remember {
AnimationState(
typeConverter = Float.VectorConverter,
initialValue = 0f,
)
}
@NoInvestigation val transitionAnimationState
by rememberTransition(transitionState = MutableTransitionState(0f))
.animateFloat(label = "unremembered") { prevState -> prevState * 2 }
}
| 17 | Kotlin | 5 | 212 | aceb52e85ae8c3eee25e7809fdfebc993bd5261f | 3,253 | ComposeInvestigator | MIT License |
src/main/kotlin/VersionControlSystem.kt | Amirbhn | 702,739,506 | false | {"Kotlin": 6569} | import java.io.File
import java.io.FileNotFoundException
import java.util.*
fun main(args: Array<String>) {
when {
args.isEmpty() || args[0] == "--help" -> printHelpPage()
args[0] == "config" -> handleConfigCommand(args)
args[0] == "add" -> handleAddCommand(args)
args[0] == "log" -> handleLogCommand()
args[0] == "commit" -> handleCommitCommand(args)
args[0] == "checkout" -> handleCheckoutCommand(args)
else -> println("'${args[0]}' is not a SVCS command.")
}
}
fun printHelpPage() {
println(
"""
These are SVCS commands:
config Get and set a username.
add Add a file to the index.
log Show commit logs.
commit Save changes.
checkout Restore a file.
""".trimIndent()
)
}
fun handleConfigCommand(args: Array<String>) {
if (args.size < 2) {
val username = getUsername()
if (username.isNotEmpty()) {
println("The username is $username.")
} else {
println("Please, tell me who you are.")
}
} else {
val username = args[1]
saveUsername(username)
println("The username is $username.")
}
}
fun saveUsername(username: String) {
File("vcs/config.txt").apply {
parentFile.mkdirs()
writeText(username)
}
}
fun getUsername(): String {
val configFile = File("vcs/config.txt")
return if (configFile.exists()) configFile.readText() else ""
}
fun handleAddCommand(args: Array<String>) {
createVcsDirectory()
if (args.size < 2) {
listTrackedFiles()
} else {
val fileName = args[1]
val file = File(fileName)
if (file.exists()) {
addToIndex(fileName)
println("The file '$fileName' is tracked.")
} else {
println("Can't find '$fileName'.")
}
}
}
fun createVcsDirectory() {
File("vcs").mkdirs()
}
fun listTrackedFiles() {
val indexFile = File("vcs/index.txt")
if (indexFile.exists()) {
val trackedFiles = indexFile.readLines()
if (trackedFiles.isNotEmpty()) {
println("Tracked files:")
trackedFiles.forEach(::println)
} else {
println("No tracked files.")
}
} else {
println("Add a file to the index.")
}
}
fun addToIndex(fileName: String) {
File("vcs/index.txt").apply {
parentFile.mkdirs()
appendText("$fileName\n")
}
}
fun handleLogCommand() {
val logFile = File("vcs/log.txt")
if (logFile.exists()) {
val commits = logFile.readLines()
if (commits.isNotEmpty()) {
commits.forEach(::println)
} else {
println("No commits yet.")
}
} else {
println("No commits yet.")
}
}
fun handleCommitCommand(args: Array<String>) {
if (args.size < 2) {
println("Message was not passed.")
} else {
val message = args.slice(1 until args.size).joinToString(" ")
val stagedFiles = getStagedFiles()
if (stagedFiles.isNotEmpty()) {
val commitId = generateCommitId()
val commitDirectory = File("vcs/commits/$commitId").apply { mkdirs() }
val previousCommitId = getLatestCommitId()
if (previousCommitId == null || isCommitDifferent(stagedFiles)) {
stagedFiles.forEach { file ->
File(file).copyTo(File(commitDirectory, File(file).name), overwrite = true)
}
updateLog(commitId, message)
println("Changes are committed.")
} else {
println("Nothing to commit.")
}
} else {
println("Nothing to commit.")
}
}
}
fun getStagedFiles(): List<String> {
val indexFile = File("vcs/index.txt")
return if (indexFile.exists()) indexFile.readLines() else emptyList()
}
fun generateCommitId(): String = UUID.randomUUID().toString()
fun updateLog(commitId: String, message: String) {
val logFile = File("vcs/log.txt")
val username = getUsername()
val newEntry = """
commit $commitId
Author: $username
$message
""".trimIndent()
try {
if (logFile.exists()) {
val existingContent = logFile.readText()
val updatedContent = "$newEntry\n$existingContent"
logFile.writeText(updatedContent)
} else {
logFile.createNewFile()
logFile.writeText(newEntry)
}
} catch (e: FileNotFoundException) {
println("Log file does not exist.")
}
}
fun getLatestCommitId(): String? {
val logFile = File("vcs/log.txt")
if (logFile.exists()) {
val commits = logFile.readLines()
if (commits.isNotEmpty()) {
val latestCommit = commits.firstOrNull()
if (latestCommit != null && latestCommit.startsWith("commit ")) {
return latestCommit.substringAfter("commit ")
}
}
}
return null
}
fun isCommitDifferent(stagedFiles: List<String>): Boolean {
val previousCommitId = getLatestCommitId() ?: return true
val previousCommitDirectory = File("vcs/commits/$previousCommitId")
for (file in stagedFiles) {
val currentFile = File(file)
val previousFile = File(previousCommitDirectory, file)
if (!previousFile.exists() || !currentFile.hasSameContent(previousFile)) {
return true
}
}
return false
}
fun File.hasSameContent(other: File): Boolean =
this.readBytes().contentEquals(other.readBytes())
fun handleCheckoutCommand(args: Array<String>) {
if (args.size < 2) {
println("Commit id was not passed.")
} else {
val commitId = args[1]
val commitDirectory = File("vcs/commits/$commitId")
if (commitDirectory.exists()) {
val trackedFiles = getTrackedFiles()
trackedFiles.forEach { file ->
val sourceFile = File(commitDirectory, file)
val destinationFile = File(file)
if (sourceFile.exists()) {
sourceFile.copyTo(destinationFile, overwrite = true)
}
}
println("Switched to commit $commitId.")
} else {
println("Commit does not exist.")
}
}
}
fun getTrackedFiles(): List<String> {
val indexFile = File("vcs/index.txt")
return if (indexFile.exists()) indexFile.readLines() else emptyList()
} | 0 | Kotlin | 0 | 0 | 16d68a0e8fc69e45b40ac2382318073ba2450182 | 6,569 | VersionControlSystem | Creative Commons Zero v1.0 Universal |
libs/serialization/serialization-kryo/src/main/kotlin/net/corda/kryoserialization/serializers/CordaClosureSerializer.kt | corda | 346,070,752 | false | {"Kotlin": 20585419, "Java": 308202, "Smarty": 115357, "Shell": 54409, "Groovy": 30246, "PowerShell": 6470, "TypeScript": 5826, "Solidity": 2024, "Batchfile": 244} | package net.corda.kryoserialization.serializers
import com.esotericsoftware.kryo.Kryo
import com.esotericsoftware.kryo.io.Output
import com.esotericsoftware.kryo.serializers.ClosureSerializer
import java.io.Serializable
internal object CordaClosureSerializer : ClosureSerializer() {
const val ERROR_MESSAGE = "Unable to serialize Java Lambda expression, unless explicitly declared e.g., " +
"Runnable r = (Runnable & Serializable) () -> System.out.println(\"Hello world!\");"
override fun write(kryo: Kryo, output: Output, target: Any) {
if (!isSerializable(target)) {
throw IllegalArgumentException(ERROR_MESSAGE)
}
super.write(kryo, output, target)
}
private fun isSerializable(target: Any): Boolean {
return target is Serializable
}
}
| 11 | Kotlin | 27 | 69 | d478e119ab288af663910f9a2df42a7a7b9f5bce | 819 | corda-runtime-os | Apache License 2.0 |
publish-component/src/main/java/com/kotlin/android/publish/component/widget/article/xml/element/P.kt | R-Gang-H | 538,443,254 | false | null | package com.kotlin.android.publish.component.widget.article.xml.element
import android.graphics.Typeface
import android.text.SpannableStringBuilder
import android.text.Spanned
import android.text.style.AlignmentSpan
import android.text.style.RelativeSizeSpan
import android.text.style.StyleSpan
import com.kotlin.android.publish.component.widget.article.sytle.TextAlign
import com.kotlin.android.publish.component.widget.article.sytle.TextFontSize
import com.kotlin.android.publish.component.widget.article.xml.appendTextJsonFromXml
import com.kotlin.android.publish.component.widget.article.xml.entity.Element
import org.xmlpull.v1.XmlPullParser
/**
* <p> 段落
*
* Created on 2022/3/24.
*
* @author o.s
*/
class P(val element: Element) : IElement {
override fun buildSpan(ssb: SpannableStringBuilder) {
val start = ssb.length
element.items?.forEach {
it.buildSpan(ssb)
}
val end = ssb.length
textAlign?.apply {
ssb.setSpan(AlignmentSpan.Standard(alignment), start, end, Spanned.SPAN_INCLUSIVE_EXCLUSIVE)
}
fontSize?.apply {
ssb.setSpan(RelativeSizeSpan(scale), start, end, Spanned.SPAN_INCLUSIVE_EXCLUSIVE)
}
if (isBold) {
ssb.setSpan(StyleSpan(Typeface.BOLD), start, end, Spanned.SPAN_INCLUSIVE_EXCLUSIVE)
// } else {
// ssb.setSpan(StyleSpan(Typeface.NORMAL), start, end, Spanned.SPAN_INCLUSIVE_INCLUSIVE)
}
}
var textAlign: TextAlign?
get() = when {
element.style?.contains("text-align: justify;") == true -> TextAlign.JUSTIFY
element.style?.contains("text-align: left;") == true -> TextAlign.LEFT
element.style?.contains("text-align: center;") == true -> TextAlign.CENTER
element.style?.contains("text-align: right;") == true -> TextAlign.RIGHT
else -> null
}
set(value) {
element.style = value?.value
}
var fontSize: TextFontSize?
get() = when {
element.clazz?.contains("mini_") == true -> TextFontSize.SMALL
element.clazz?.contains("standard_") == true -> TextFontSize.STANDARD
element.clazz?.contains("medium_") == true -> TextFontSize.BIG
element.clazz?.contains("large_") == true -> TextFontSize.LARGER
else -> null
}
set(value) {
if (isBold) {
element.clazz = value?.clazzBold
} else {
element.clazz = value?.clazz
}
}
var isBold: Boolean
get() = element.clazz?.contains("strong") ?: false
set(value) {
if (value) {
element.clazz = (fontSize ?: TextFontSize.STANDARD).clazzBold
} else {
element.clazz = fontSize?.clazz
}
}
companion object {
fun appendJson(parser: XmlPullParser, sb: StringBuilder) {
appendTextJsonFromXml(
parser = parser,
sb = sb,
tag = "p",
"style" to "style",
"contenteditable" to "editable",
"class" to "clazz",
)
}
}
} | 0 | Kotlin | 0 | 1 | e63b1f9a28c476c1ce4db8d2570d43a99c0cdb28 | 3,233 | Mtime | Apache License 2.0 |
boot-app-server-spring-cloud/dashboard/src/main/kotlin/com/ittianyu/dashboard/controller/DashboardConfigController.kt | ittianyu | 194,419,824 | false | null | package com.ittianyu.dashboard.controller
import com.ittianyu.common.dto.ResultDTO
import com.ittianyu.common.utils.JsonUtils
import com.ittianyu.common.web.utils.ResultFactory
import com.ittianyu.dashboard.service.ConfigService
import com.ittianyu.dashboardapi.api.DashboardConfigApi
import com.ittianyu.dashboardapi.dto.DashboardConfigItemDTO
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.web.bind.annotation.PostMapping
import org.springframework.web.bind.annotation.RequestBody
import org.springframework.web.bind.annotation.RequestMapping
import org.springframework.web.bind.annotation.RestController
@RestController
@RequestMapping(path = ["/config"])
class DashboardConfigController @Autowired constructor(private val configService: ConfigService) : DashboardConfigApi {
override fun get(name: String): ResultDTO<DashboardConfigItemDTO> {
return ResultFactory.success(JsonUtils.fromJson(configService.get(name), DashboardConfigItemDTO::class.java))
}
@PostMapping(path = ["/set"])
fun set(@RequestBody config: Map<String, DashboardConfigItemDTO>): ResultDTO<Void> {
configService.set(config)
return ResultFactory.success()
}
}
| 1 | Kotlin | 0 | 11 | 136b573124a399606be2105da3f8d20212df3d23 | 1,225 | boot-app | Apache License 2.0 |
src/main/kotlin/com/framstag/domainbus/source/postgres/StateProcessor.kt | Framstag | 233,686,175 | false | null | package com.framstag.domainbus.source.postgres
import com.framstag.domainbus.event.EventBatch
import java.util.concurrent.CompletableFuture
internal interface StateProcessor {
fun process(stateData : StateData, producer: CompletableFuture<EventBatch>, context : Context):ProcessResult
} | 0 | Kotlin | 0 | 0 | 9b3b358e9ee6b1e5bac8dd9d72cccefe9c4c09ab | 292 | domainbus | Apache License 2.0 |
app/src/main/java/com/google/samples/apps/sunflower/newsscreen/InfoDetailFragment.kt | Angryestbird | 267,251,847 | false | null | package com.google.samples.apps.sunflower.newsscreen
import android.content.Intent
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.core.app.ShareCompat
import androidx.core.widget.NestedScrollView
import androidx.fragment.app.Fragment
import androidx.fragment.app.viewModels
import androidx.lifecycle.ViewModelProvider
import androidx.navigation.findNavController
import androidx.navigation.fragment.navArgs
import com.google.android.material.snackbar.Snackbar
import com.google.samples.apps.sunflower.R
import com.google.samples.apps.sunflower.data.Movie
import com.google.samples.apps.sunflower.databinding.FragmentInfoDetailBinding
import com.google.samples.apps.sunflower.newsscreen.viewmodels.InfoDetailViewModel
import dagger.android.support.DaggerFragment
import javax.inject.Inject
/**
* A simple [Fragment] subclass.
* Use the [InfoDetailFragment.newInstance] factory method to
* create an instance of this fragment.
*/
class InfoDetailFragment : DaggerFragment() {
@Inject
lateinit var viewModelFactory: ViewModelProvider.Factory
private val infoDetailViewModel: InfoDetailViewModel by viewModels { viewModelFactory }
private val args: InfoDetailFragmentArgs by navArgs()
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?): View? {
val binding = FragmentInfoDetailBinding.inflate(inflater, container, false)
.apply {
viewModel = infoDetailViewModel.apply { plantId.value = args.newsId }
lifecycleOwner = viewLifecycleOwner
callback = object : Callback {
override fun add(plant: Movie?) {
plant?.let {
Snackbar.make(root, R.string.added_plant_to_garden, Snackbar.LENGTH_LONG)
.show()
}
}
}
var isToolbarShown = false
// scroll change listener begins at Y = 0 when image is fully collapsed
plantDetailScrollview?.setOnScrollChangeListener(
NestedScrollView.OnScrollChangeListener { _, _, scrollY, _, _ ->
// User scrolled past image to height of toolbar and the title text is
// underneath the toolbar, so the toolbar should be shown.
val shouldShowToolbar = scrollY > toolbar.height
// The new state of the toolbar differs from the previous state; update
// appbar and toolbar attributes.
if (isToolbarShown != shouldShowToolbar) {
isToolbarShown = shouldShowToolbar
// Use shadow animator to add elevation if toolbar is shown
appbar.isActivated = shouldShowToolbar
// Show the plant name if toolbar is shown
toolbarLayout.isTitleEnabled = shouldShowToolbar
}
}
)
toolbar.setNavigationOnClickListener { view ->
view.findNavController().navigateUp()
}
toolbar.setOnMenuItemClickListener { item ->
when (item.itemId) {
R.id.action_share -> {
createShareIntent()
true
}
else -> false
}
}
}
setHasOptionsMenu(true)
return binding.root
}
// Helper function for calling a share functionality.
// Should be used when user presses a share button/menu item.
@Suppress("DEPRECATION")
private fun createShareIntent() {
val shareText = infoDetailViewModel.plant.value.let { plant ->
if (plant == null) {
""
} else {
getString(R.string.share_text_plant, plant.name)
}
}
val shareIntent = ShareCompat.IntentBuilder.from(activity)
.setText(shareText)
.setType("text/plain")
.createChooserIntent()
.addFlags(Intent.FLAG_ACTIVITY_NEW_DOCUMENT or Intent.FLAG_ACTIVITY_MULTIPLE_TASK)
startActivity(shareIntent)
}
interface Callback {
fun add(plant: Movie?)
}
}
| 0 | Kotlin | 1 | 0 | 11c8f4ae77fb480ed4dfe92e2ccd99e18a831526 | 4,812 | orangetv-android | Apache License 2.0 |
src/test/kotlin/dev/arli/openapi/mapper/OpenAPIMapperTest.kt | alipovatyi | 487,519,792 | false | {"Kotlin": 451322} | package dev.arli.openapi.mapper
import com.google.common.truth.Truth.assertThat
import dev.arli.openapi.OpenAPIGenConfiguration
import dev.arli.openapi.model.ComponentsObject
import dev.arli.openapi.model.HttpSecurityScheme
import dev.arli.openapi.model.Info
import dev.arli.openapi.model.InfoObject
import dev.arli.openapi.model.OpenAPIObject
import dev.arli.openapi.model.PathItemObject
import dev.arli.openapi.model.Server
import dev.arli.openapi.model.ServerObject
import dev.arli.openapi.model.ServerVariables
import dev.arli.openapi.model.Servers
import dev.arli.openapi.model.Tag
import dev.arli.openapi.model.TagObject
import dev.arli.openapi.model.Tags
import dev.arli.openapi.model.security.HttpSecuritySchemeType
import io.ktor.http.Url
import org.junit.jupiter.api.Test
import kotlin.test.assertFailsWith
internal class OpenAPIMapperTest {
private val mapper = OpenAPIMapper()
@Test
fun `Should map OpenAPI to OpenAPI object`() {
val givenPathItems = mapOf("/pet" to PathItemObject())
val givenSecuritySchemes = mapOf(
"security-scheme" to HttpSecurityScheme(
description = "Description",
scheme = HttpSecuritySchemeType.BASIC
)
)
val givenTags = Tags(listOf(Tag(name = "Tag", description = null, externalDocs = null)))
val expectedOpenAPIObject = OpenAPIObject(
openapi = "3.0.3",
info = InfoObject(
title = "Swagger Petstore - OpenAPI 3.0",
version = "1.0.11"
),
servers = listOf(ServerObject(url = Url("http://localhost/server"))),
paths = givenPathItems,
components = ComponentsObject(
securitySchemes = givenSecuritySchemes
),
tags = listOf(TagObject(name = "Tag"))
)
val actualOpenAPIObject = mapper.map(
openAPIGenConfiguration = OpenAPIGenConfiguration(
info = Info(
title = "Swagger Petstore - OpenAPI 3.0",
description = null,
termsOfService = null,
contact = null,
license = null,
version = "1.0.11"
),
servers = Servers(
servers = listOf(
Server(
url = Url("http://localhost/server"),
description = null,
variables = ServerVariables()
)
)
)
),
pathItems = givenPathItems,
securitySchemes = givenSecuritySchemes,
tags = givenTags
)
assertThat(actualOpenAPIObject).isEqualTo(expectedOpenAPIObject)
}
@Test
fun `Should throw exception if info is null`() {
assertFailsWith<IllegalArgumentException> {
mapper.map(
openAPIGenConfiguration = OpenAPIGenConfiguration(
info = null,
servers = Servers()
),
pathItems = emptyMap(),
securitySchemes = emptyMap(),
tags = Tags()
)
}
}
}
| 0 | Kotlin | 1 | 1 | 3637b43dc2e255f263b559a5a80ebf80f3e78d96 | 3,280 | ktor-openapi | Apache License 2.0 |
app/src/main/java/com/hci/tom/android/network/TOMWebSocketListener.kt | TOM-Platform | 837,201,728 | false | {"Kotlin": 154904} | package com.hci.tom.android.network
import android.util.Log
import okhttp3.Response
import okhttp3.WebSocket
import okhttp3.WebSocketListener
import okio.ByteString
open class TOMWebSocketListener(private val worker: ReconnectableWorker): WebSocketListener() {
var isConnected = false
override fun onOpen(webSocket: WebSocket, response: Response) {
Log.d("TOMWebSocketListener", "Websocket opened")
isConnected = true
}
override fun onMessage(webSocket: WebSocket, text: String) {
Log.d("TOMWebSocketListener","Received message: $text")
}
override fun onFailure(webSocket: WebSocket, t: Throwable, response: Response?) {
Log.w("TOMWebSocketListener", t.stackTraceToString())
isConnected = false
worker.attemptReconnect()
}
fun sendBytes(webSocket: WebSocket, bytes: ByteArray?) {
try {
val byteString = ByteString.of(*bytes!!)
webSocket.send(byteString)
} catch (e: Exception) {
Log.e("TOMWebSocketListener", e.stackTraceToString())
}
}
} | 0 | Kotlin | 0 | 1 | baa0ffa4d3fb4e16490f2860f54b18247dbc5a8c | 1,087 | TOM-Client-WearOS | MIT License |
src/test/kotlin/com/github/br1992/geometry/SphereTest.kt | br1992 | 442,847,310 | false | {"Kotlin": 20689} | package com.github.br1992.geometry
import io.kotest.core.spec.style.FreeSpec
import io.kotest.matchers.types.shouldBeInstanceOf
class SphereTest : FreeSpec() {
init {
"Sphere" - {
"should intersect with ray inside of it" {
val sphere = Sphere(pos3(0.0, 0.0, 0.0), 1.0)
val ray = Ray3(pos3(0.0, 0.0, 0.0), vec3(1.0, 1.0, 1.0))
sphere.intersects(ray, 0.0, Double.POSITIVE_INFINITY).shouldBeInstanceOf<SurfaceIntersection>()
}
"should intersect with ray crossing through it" {
val sphere = Sphere(pos3(0.0, 0.0, 0.0), 1.0)
val ray = Ray3(pos3(0.5, 0.5, 2.0), vec3(0.0, 0.0, -1.0))
sphere.intersects(ray, 0.0, Double.POSITIVE_INFINITY).shouldBeInstanceOf<SurfaceIntersection>()
}
"should intersect with ray tangent to it" {
val sphere = Sphere(pos3(0.0, 0.0, 0.0), 1.0)
val ray = Ray3(pos3(.99999, 0.0, 2.0), vec3(0.0, 0.0, -1.0))
sphere.intersects(ray, 0.0, Double.POSITIVE_INFINITY).shouldBeInstanceOf<SurfaceIntersection>()
}
"should not intersect with ray facing away from it" {
val sphere = Sphere(pos3(0.0, 0.0, 0.0), 1.0)
val ray = Ray3(pos3(1.0, 0.0, 2.0), vec3(0.0, 0.0, 1.0))
sphere.intersects(ray, 0.0, Double.POSITIVE_INFINITY).shouldBeInstanceOf<NoIntersection>()
}
"should not intersect with ray that misses it" {
val sphere = Sphere(pos3(0.0, 0.0, 0.0), 1.0)
val ray = Ray3(pos3(0.0, 0.0, 2.0), vec3(0.0, 1.0, 1.0))
sphere.intersects(ray, 0.0, Double.POSITIVE_INFINITY).shouldBeInstanceOf<NoIntersection>()
}
}
}
}
| 0 | Kotlin | 0 | 0 | 8e86230b9895095f3240a9df774ae379a2dea5ba | 1,822 | Luzombra | MIT License |
FinFamily/src/main/java/com/bandtec/finfamily/Avatar.kt | Natayoane | 274,787,455 | true | {"Kotlin": 153399} | package com.bandtec.finfamily
import android.content.Intent
import android.graphics.drawable.BitmapDrawable
import android.os.Bundle
import android.view.View
import android.widget.ImageView
import androidx.appcompat.app.AppCompatActivity
class Avatar : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_avatar)
}
fun chooseAvatar(image: View) {
val profileEdit = Intent(this, ProfileEdit::class.java)
val profile = Intent(this, Profile::class.java)
profileEdit.putExtra("avatar", ((image as ImageView).drawable as BitmapDrawable).bitmap)
profile.putExtra("avatar", (image.drawable as BitmapDrawable).bitmap)
startActivity(profileEdit)
finish()
}
}
| 0 | null | 0 | 1 | 13b5d44e5cff959d3551db6fec6cf08a42ee422d | 826 | fin-family-app | MIT License |
app/src/main/java/com/example/myapplication/Fragments/FragmentWeather.kt | ralonsobeas | 189,850,764 | false | {"Kotlin": 12960} | package com.example.myapplication.Fragments
import android.content.Context
import android.content.res.Resources
import android.gesture.GestureUtils
import android.net.Uri
import android.os.Bundle
import android.support.v4.app.Fragment
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import com.example.myapplication.Data
import com.example.myapplication.R
import kotlinx.android.synthetic.main.fragment_fragment_weather.*
import kotlinx.android.synthetic.main.fragment_fragment_weather.view.*
// TODO: Rename parameter arguments, choose names that match
// the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
private const val DESC = "desc"
private const val TEMP = "temp"
private const val IMG = "img"
private const val DIA = "dia"
/**
* A simple [Fragment] subclass.
* Activities that contain this fragment must implement the
* [FragmentWeather.OnFragmentInteractionListener] interface
* to handle interaction events.
* Use the [FragmentWeather.newInstance] factory method to
* create an instance of this fragment.
*
*/
class FragmentWeather : Fragment() {
// TODO: Rename and change types of parameters
private var desc: String? = null
private var temp: String? = null
private var img: String? = null
private var dia: String? = null
private var listener: OnFragmentInteractionListener? = null
private var rootView: View?=null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
arguments?.let {
desc = it.getString(DESC)
temp = it.getString(TEMP)
img = it.getString(IMG)
dia = it.getString(DIA)
}
}
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
//Recibir los datos de la api del día indicado
rootView =inflater.inflate(R.layout.fragment_fragment_weather, container, false)
rootView!!.tvDia.text=dia
var strtemp = "$temp ºC"
rootView!!.tvTemp.text =strtemp
rootView!!.tvDesc.text=desc
img=img?.replace('-','_',true)
Log.d("IMAGE",img)
rootView!!.imgTiempo.setImageResource(resources.getIdentifier("ic_$img","drawable", context?.packageName))
// Inflate the layout for this fragment
return rootView
}
// TODO: Rename method, update argument and hook method into UI event
fun onButtonPressed(uri: Uri) {
listener?.onFragmentInteraction(uri)
}
override fun onAttach(context: Context) {
super.onAttach(context)
if (context is OnFragmentInteractionListener) {
listener = context
} else {
throw RuntimeException(context.toString() + " must implement OnFragmentInteractionListener")
}
}
override fun onDetach() {
super.onDetach()
listener = null
}
/**
* This interface must be implemented by activities that contain this
* fragment to allow an interaction in this fragment to be communicated
* to the activity and potentially other fragments contained in that
* activity.
*
*
* See the Android Training lesson [Communicating with Other Fragments]
* (http://developer.android.com/training/basics/fragments/communicating.html)
* for more information.
*/
interface OnFragmentInteractionListener {
// TODO: Update argument type and name
fun onFragmentInteraction(uri: Uri)
}
companion object {
/**
* Use this factory method to create a new instance of
* this fragment using the provided parameters.
*
* @param param1 Parameter 1.
* @param param2 Parameter 2.
* @return A new instance of fragment FragmentWeather.
*/
// TODO: Rename and change types and number of parameters
@JvmStatic
fun newInstance(desc: String, temp: String,img:String,dia:String) =
FragmentWeather().apply {
arguments = Bundle().apply {
putString(DESC, desc)
putString(TEMP, temp)
putString(IMG, img)
putString(DIA, dia)
}
}
}
}
| 0 | Kotlin | 0 | 1 | df2e220b87e294f6fd0666162a5d8c5ccfe0516a | 4,382 | AppAndroidElTiempoMiranda | MIT License |
nugu-ux-kit/src/main/java/com/skt/nugu/sdk/platform/android/ux/widget/ChromeWindow.kt | yun-jun-hyengh | 373,401,405 | true | {"Kotlin": 2356664, "Java": 1646, "Ruby": 1432} | /**
* Copyright (c) 2019 SK Telecom Co., Ltd. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http:www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.skt.nugu.sdk.platform.android.ux.widget
import android.content.Context
import android.content.res.Configuration
import android.graphics.Rect
import android.view.View
import android.view.ViewGroup
import android.widget.FrameLayout
import androidx.coordinatorlayout.widget.CoordinatorLayout
import com.skt.nugu.sdk.agent.asr.ASRAgentInterface
import com.skt.nugu.sdk.agent.chips.Chip
import com.skt.nugu.sdk.agent.chips.RenderDirective
import com.skt.nugu.sdk.agent.dialog.DialogUXStateAggregatorInterface
import com.skt.nugu.sdk.client.theme.ThemeManagerInterface
import com.skt.nugu.sdk.core.interfaces.message.Header
import com.skt.nugu.sdk.core.utils.Logger
import com.skt.nugu.sdk.platform.android.NuguAndroidClient
import com.skt.nugu.sdk.platform.android.ux.R
import com.skt.nugu.sdk.agent.chips.RenderDirective.Payload.Target as ChipsRenderTarget
class ChromeWindow(
context: Context,
private val view: View,
private val nuguClientProvider: NuguClientProvider) :
DialogUXStateAggregatorInterface.Listener, ASRAgentInterface.OnResultListener, ThemeManagerInterface.ThemeListener{
companion object {
private const val TAG = "ChromeWindow"
}
interface OnChromeWindowCallback {
fun onExpandStarted()
fun onHiddenFinished()
fun onChipsClicked(item: NuguChipsView.Item)
}
interface CustomChipsProvider {
/**
* Called when custom chip could be shown.
*
* @param isSpeaking Whether TTS is Speaking or not.
* If it is true TTS is speaking.
* If it is false ASR State is EXPECTING_SPEECH which means system is waiting users utterance
*/
fun onCustomChipsAvailable(isSpeaking : Boolean) : Array<Chip>?
}
private var callback: OnChromeWindowCallback? = null
private var contentLayout: ChromeWindowContentLayout
private var screenOnWhileASR = false
private var customChipsProvider: CustomChipsProvider? = null
private var isDarkMode = false
/**
* set ChromeWindow callback
*/
fun setOnChromeWindowCallback(callback: OnChromeWindowCallback?) {
this.callback = callback
}
fun setOnCustomChipsProvider(provider: CustomChipsProvider) {
customChipsProvider = provider
}
interface NuguClientProvider {
fun getNuguClient(): NuguAndroidClient
}
/**
* Returns the visibility of this view
* @return True if the view is expanded
*/
fun isShown(): Boolean {
return contentLayout.isExpanded()
}
/**
* Dismiss the view
*/
fun dismiss() {
contentLayout.dismiss()
}
/**
* If some part of this view is not clipped by any of its parents, then
* return that area in r in global (root) coordinates.
*/
fun getGlobalVisibleRect(outRect: Rect){
contentLayout.getGlobalVisibleRect(outRect)
}
/**
* Control whether we should use the attached view to keep the
* screen on while asr is occurring.
* @param screenOn Supply true to keep the screen on, false to allow it to turn off.
*/
fun setScreenOnWhileASR (screenOn: Boolean) {
if (screenOnWhileASR != screenOn) {
screenOnWhileASR = screenOn
updateLayoutScreenOn()
}
}
private var isThinking = false
private var isSpeaking = false
private var isDialogMode = false
private var isIdle = false
init {
Logger.d(TAG, "[init]")
val parent = view.findSuitableParent()
if (parent == null) {
throw IllegalArgumentException("No suitable parent found from the given view. Please provide a valid view.")
} else {
contentLayout = ChromeWindowContentLayout(context = context, view = parent)
contentLayout.setOnChromeWindowContentLayoutCallback(object : ChromeWindowContentLayout.OnChromeWindowContentLayoutCallback {
override fun shouldCollapsed(): Boolean {
if (isThinking || (isDialogMode && isSpeaking)) {
return false
}
return true
}
override fun onHidden() {
callback?.onHiddenFinished()
}
override fun onChipsClicked(item: NuguChipsView.Item) {
callback?.onChipsClicked(item)
}
})
}
nuguClientProvider.getNuguClient().themeManager.addListener(this)
nuguClientProvider.getNuguClient().addDialogUXStateListener(this)
nuguClientProvider.getNuguClient().addASRResultListener(this)
applyTheme(nuguClientProvider.getNuguClient().themeManager.theme)
}
fun destroy() {
Logger.d(TAG, "[destroy]")
nuguClientProvider.getNuguClient().themeManager.removeListener(this)
nuguClientProvider.getNuguClient().removeDialogUXStateListener(this)
nuguClientProvider.getNuguClient().removeASRResultListener(this)
}
override fun onDialogUXStateChanged(
newState: DialogUXStateAggregatorInterface.DialogUXState,
dialogMode: Boolean,
chips: RenderDirective.Payload?,
sessionActivated: Boolean
) {
isDialogMode = dialogMode
isThinking = newState == DialogUXStateAggregatorInterface.DialogUXState.THINKING
isIdle = newState == DialogUXStateAggregatorInterface.DialogUXState.IDLE
isSpeaking = newState == DialogUXStateAggregatorInterface.DialogUXState.SPEAKING
view.post {
Logger.d(
TAG,
"[onDialogUXStateChanged] newState: $newState, dialogMode: $dialogMode, chips: $chips, sessionActivated: $sessionActivated"
)
voiceChromeController.onDialogUXStateChanged(
newState,
dialogMode,
chips,
sessionActivated
)
when (newState) {
DialogUXStateAggregatorInterface.DialogUXState.EXPECTING -> {
handleExpecting(dialogMode, chips)
}
DialogUXStateAggregatorInterface.DialogUXState.LISTENING -> {
handleListening()
}
DialogUXStateAggregatorInterface.DialogUXState.SPEAKING -> {
handleSpeaking(dialogMode, chips, sessionActivated)
}
DialogUXStateAggregatorInterface.DialogUXState.IDLE -> {
dismiss()
}
else -> {
// nothing to do
}
}
updateLayoutScreenOn()
}
}
private fun handleExpecting(dialogMode: Boolean, payload: RenderDirective.Payload?) {
if (!dialogMode) {
contentLayout.setHint(R.string.nugu_guide_text)
contentLayout.showText()
} else {
contentLayout.hideText()
}
if (payload?.target == ChipsRenderTarget.DM && dialogMode || payload?.target == ChipsRenderTarget.LISTEN) {
updateChips(payload)
} else {
updateChips(null)
updateCustomChips(false)
}
contentLayout.expand()
callback?.onExpandStarted()
}
private fun updateChips(payload: RenderDirective.Payload?) {
contentLayout.updateChips(payload)
}
private fun updateCustomChips(isSpeaking : Boolean) : Boolean {
customChipsProvider?.onCustomChipsAvailable(isSpeaking)?.let { chips ->
contentLayout.updateChips(RenderDirective.Payload(chips = chips,
playServiceId = "", target = ChipsRenderTarget.DM)) //this two values are meaningless
return true
}
return false
}
fun isChipsEmpty() = contentLayout.isChipsEmpty()
private fun handleListening() {
contentLayout.hideText()
contentLayout.hideChips()
}
private fun handleSpeaking(dialogMode: Boolean, payload: RenderDirective.Payload?,
sessionActivated: Boolean) {
contentLayout.hideText()
if (payload?.target == ChipsRenderTarget.SPEAKING) {
updateChips(payload)
return
} else {
contentLayout.hideChips()
if (updateCustomChips(true)) return
}
if (!sessionActivated) {
dismiss()
}
}
override fun onCancel(cause: ASRAgentInterface.CancelCause, header: Header) {
}
override fun onError(type: ASRAgentInterface.ErrorType, header: Header, allowEffectBeep: Boolean) {
}
override fun onNoneResult(header: Header) {
}
override fun onPartialResult(result: String, header: Header) {
view.post {
contentLayout.setText(result)
}
}
override fun onCompleteResult(result: String, header: Header) {
view.post {
contentLayout.setText(result)
}
}
private fun updateLayoutScreenOn() {
val screenOn = screenOnWhileASR && !isIdle
if(view.keepScreenOn != screenOn) {
view.keepScreenOn = screenOn
Logger.d(TAG, "[updateLayoutScreenOn] ${view.keepScreenOn}")
}
}
private val voiceChromeController =
object : DialogUXStateAggregatorInterface.Listener {
override fun onDialogUXStateChanged(
newState: DialogUXStateAggregatorInterface.DialogUXState,
dialogMode: Boolean,
chips: RenderDirective.Payload?,
sessionActivated: Boolean
) {
when (newState) {
DialogUXStateAggregatorInterface.DialogUXState.EXPECTING -> {
contentLayout.startAnimation(NuguVoiceChromeView.Animation.WAITING)
}
DialogUXStateAggregatorInterface.DialogUXState.LISTENING -> {
contentLayout.startAnimation(NuguVoiceChromeView.Animation.LISTENING)
}
DialogUXStateAggregatorInterface.DialogUXState.THINKING -> {
contentLayout.startAnimation(NuguVoiceChromeView.Animation.THINKING)
}
DialogUXStateAggregatorInterface.DialogUXState.SPEAKING -> {
contentLayout.startAnimation(NuguVoiceChromeView.Animation.SPEAKING)
}
else -> {
// nothing to do
}
}
}
}
override fun onThemeChange(theme: ThemeManagerInterface.THEME) {
Logger.d(TAG, "[onThemeChange] $theme")
applyTheme(theme)
}
private fun applyTheme(newTheme: ThemeManagerInterface.THEME) {
val newDarkMode = when (newTheme) {
ThemeManagerInterface.THEME.LIGHT -> false
ThemeManagerInterface.THEME.DARK -> true
ThemeManagerInterface.THEME.SYSTEM -> {
val uiMode = view.resources.configuration.uiMode and Configuration.UI_MODE_NIGHT_MASK
uiMode == Configuration.UI_MODE_NIGHT_YES
}
}
Logger.d(TAG, "[applyTheme] newState=$newTheme, newDarkMode=${newDarkMode}, isDarkMode=$isDarkMode")
val isChanged = newDarkMode != isDarkMode
if(isChanged) {
isDarkMode = newDarkMode
contentLayout.setDarkMode(newDarkMode, newTheme)
}
}
}
private fun View.findSuitableParent() : ViewGroup? {
var view: View? = this
var fallback: ViewGroup? = null
do {
if (view is CoordinatorLayout) {
return view
}
if (view is FrameLayout) {
if (view.getId() == android.R.id.content) {
return view
}
fallback = view
}
if (view != null) {
val parent = view.parent
view = if (parent is View) parent else null
}
} while (view != null)
return fallback
} | 0 | null | 0 | 0 | eaeb90f1e37e75dc63ae17c487fdee4b4eb3429b | 12,667 | nugu-android | Apache License 2.0 |
github_inherited/android/app/src/main/kotlin/com/example/github_inherited/MainActivity.kt | whosramoss | 291,567,061 | false | null | package com.example.github_inherited
import io.flutter.embedding.android.FlutterActivity
class MainActivity: FlutterActivity() {
}
| 0 | Dart | 11 | 49 | 00e9849525ec5eadcf3b00dbcd9d5e05123de33a | 133 | clean-dart-github | Apache License 2.0 |
hellogin-core/src/iosMain/kotlin/com/wonddak/hellogin/core/Error.ios.kt | jmseb3 | 833,469,940 | false | {"Kotlin": 12886, "Ruby": 9398} | package com.wonddak.hellogin.core
import platform.Foundation.NSError
actual typealias Error = NSError | 0 | Kotlin | 0 | 0 | cdf944fb05a3fb440e434b6d4b41238773ba40a9 | 103 | helLogin | Apache License 2.0 |
app/src/main/java/dev/m13d/somenet/timeline/TimelineScreen.kt | 3yebMB | 851,249,108 | false | {"Kotlin": 57980} | package dev.m13d.somenet.timeline
import androidx.compose.foundation.border
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Add
import androidx.compose.material3.FloatingActionButton
import androidx.compose.material3.Icon
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.livedata.observeAsState
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.platform.testTag
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.unit.dp
import dev.m13d.somenet.R
import dev.m13d.somenet.domain.post.Post
import dev.m13d.somenet.timeline.states.TimelineState
import dev.m13d.somenet.ui.component.ScreenTitle
class TimelineScreenState {
var posts by mutableStateOf(emptyList<Post>())
fun updatePosts(newPosts: List<Post>) {
this.posts = newPosts
}
}
@Composable
fun TimelineScreen(
userId: String,
timelineViewModel: TimelineViewModel,
onCreateNewPost: () -> Unit,
) {
val screenState by remember { mutableStateOf(TimelineScreenState()) }
val timelineState by timelineViewModel.timelineState.observeAsState()
timelineViewModel.timelineFor(userId)
if (timelineState is TimelineState.Posts) {
val posts = (timelineState as TimelineState.Posts).posts
screenState.updatePosts(posts)
}
Column(
modifier = Modifier
.fillMaxSize()
.padding(16.dp),
) {
ScreenTitle(titleResource = R.string.timeline)
Spacer(Modifier.height(16.dp))
Box(modifier = Modifier.fillMaxSize()) {
PostsList(
screenState.posts,
modifier = Modifier.align(Alignment.TopCenter)
)
FloatingActionButton(
onClick = { onCreateNewPost() },
modifier = Modifier
.align(Alignment.BottomEnd)
.padding(16.dp)
.testTag(stringResource(id = R.string.createNewPost))
) {
Icon(
imageVector = Icons.Default.Add,
contentDescription = stringResource(id = R.string.createNewPost),
)
}
}
}
}
@Composable
private fun PostsList(
posts: List<Post>,
modifier: Modifier = Modifier,
) {
if (posts.isEmpty()) {
Text(
text = stringResource(id = R.string.emptyTimelineMessage),
modifier = modifier,
)
} else {
LazyColumn(modifier = Modifier.fillMaxSize()) {
items(posts) { post ->
PostItem(post = post)
Spacer(modifier = Modifier.height(8.dp))
}
}
}
}
@Composable
private fun PostItem(
post: Post,
modifier: Modifier = Modifier,
) {
Box(modifier = modifier
.fillMaxWidth()
.clip(shape = RoundedCornerShape(16.dp))
.border(
width = 1.dp,
color = MaterialTheme.colorScheme.onSurface,
shape = RoundedCornerShape(16.dp)
)
) {
Text(
text = post.text,
modifier = Modifier.padding(8.dp)
)
}
}
| 1 | Kotlin | 0 | 0 | 3ce84083291901006ea2f916ef71cef0777a8608 | 4,015 | Some-network | The Unlicense |
androidApp/src/main/java/com/hotmail/arehmananis/composedemo/android/data/remote/ApiServiceKtor.kt | abdul-rehman-ghazi | 841,388,176 | false | {"Kotlin": 53537, "Swift": 342} | package com.hotmail.arehmananis.composedemo.android.data.remote
import com.hotmail.arehmananis.composedemo.android.data.remote.dto.response.GetNewsResponse
interface ApiServiceKtor {
suspend fun topHeadlines(page: Int): GetNewsResponse
suspend fun everything(page: Int, keyword: String): GetNewsResponse
} | 0 | Kotlin | 0 | 0 | f09db8742b34d48b4aa914e46719542c4dbdce8c | 316 | news-app-compose | MIT License |
client/app/src/main/java/com/petrov/vitaliy/caraccidentapp/domain/models/requests/documents/AdministrativeOffenceCaseDecisionUpdateRequest.kt | ADsty | 493,215,764 | false | null | package com.petrov.vitaliy.caraccidentapp.domain.models.requests.documents
import java.sql.Date
import java.sql.Time
data class AdministrativeOffenceCaseDecisionUpdateRequest(
val documentID: Long,
val updatedDateOfFill: Date,
val updatedTimeOfFill: Time,
val updatedPlaceOfFill: String,
val updatedCulpritID: Long,
val updatedCulpritActualPlaceOfResidence: String,
val updatedCaseCircumstances: String,
val updatedCaseDecision: String,
val updatedDateOfReceiving: Date,
val updatedEffectiveDate: Date,
val carAccidentEntityID: Long
)
| 0 | Kotlin | 0 | 0 | d3e957717cb51980d428c533530d45673c1b42fc | 581 | thesis-2022 | MIT License |
courses/kotlin/2-control-flow/code-practice/whats-the-sum/WhatsTheSum.kt | HenestrosaDev | 511,219,452 | false | {"HTML": 128144, "Java": 84555, "C#": 78147, "C++": 75352, "Python": 71625, "C": 61964, "Swift": 38825, "Ruby": 28428, "CSS": 20118, "JavaScript": 13726, "Go": 8636, "Kotlin": 7832, "R": 3731, "Rebol": 17} | fun main(args: Array<String>) {
readLine()?.toInt()?.let { start ->
readLine()?.toInt()?.let { end ->
var sum = 0
for (i in start..end) {
sum += i
}
println(sum)
}
}
} | 0 | HTML | 5 | 39 | 9e3ed6d67a12218b79092414d039994a926102d1 | 191 | sololearn | MIT License |
input/core/src/commonMain/kotlin/symphony/properties/Bounded.kt | aSoft-Ltd | 632,021,007 | false | null | @file:JsExport
package symphony.properties
import kotlin.js.JsExport
interface Bounded<out B> {
val max: B?
val min: B?
} | 0 | Kotlin | 0 | 0 | d12f05cdc6be080e14b48e66ef9c0d346a6ba5ca | 132 | symphony | MIT License |
fluent-icons-extended/src/commonMain/kotlin/com/konyaco/fluent/icons/regular/DeviceMeetingRoomRemote.kt | Konyaco | 574,321,009 | false | null |
package com.konyaco.fluent.icons.regular
import androidx.compose.ui.graphics.vector.ImageVector
import com.konyaco.fluent.icons.Icons
import com.konyaco.fluent.icons.fluentIcon
import com.konyaco.fluent.icons.fluentPath
public val Icons.Regular.DeviceMeetingRoomRemote: ImageVector
get() {
if (_deviceMeetingRoomRemote != null) {
return _deviceMeetingRoomRemote!!
}
_deviceMeetingRoomRemote = fluentIcon(name = "Regular.DeviceMeetingRoomRemote") {
fluentPath {
moveTo(4.1f, 5.35f)
arcTo(3.06f, 3.06f, 0.0f, false, true, 7.06f, 3.0f)
horizontalLineToRelative(9.86f)
curveToRelative(1.42f, 0.0f, 2.65f, 0.97f, 2.98f, 2.35f)
lineToRelative(1.99f, 8.27f)
arcTo(3.55f, 3.55f, 0.0f, false, true, 18.45f, 18.0f)
lineTo(10.5f, 18.0f)
verticalLineToRelative(-1.5f)
horizontalLineToRelative(7.95f)
curveToRelative(1.32f, 0.0f, 2.3f, -1.24f, 2.0f, -2.53f)
lineToRelative(-2.0f, -8.27f)
curveToRelative(-0.17f, -0.7f, -0.8f, -1.2f, -1.52f, -1.2f)
lineTo(7.07f, 4.5f)
curveToRelative(-0.72f, 0.0f, -1.35f, 0.5f, -1.52f, 1.2f)
lineToRelative(-0.67f, 2.8f)
lineTo(3.75f, 8.5f)
curveToRelative(-0.14f, 0.0f, -0.29f, 0.01f, -0.42f, 0.03f)
lineToRelative(0.76f, -3.18f)
close()
moveTo(10.49f, 20.5f)
horizontalLineToRelative(6.76f)
arcToRelative(0.75f, 0.75f, 0.0f, true, false, 0.0f, -1.5f)
lineTo(10.5f, 19.0f)
verticalLineToRelative(1.25f)
lineToRelative(-0.01f, 0.25f)
close()
moveTo(5.75f, 14.5f)
arcToRelative(1.25f, 1.25f, 0.0f, true, false, 0.0f, -2.5f)
arcToRelative(1.25f, 1.25f, 0.0f, false, false, 0.0f, 2.5f)
close()
moveTo(2.0f, 11.25f)
curveToRelative(0.0f, -0.97f, 0.78f, -1.75f, 1.75f, -1.75f)
horizontalLineToRelative(4.0f)
curveToRelative(0.97f, 0.0f, 1.75f, 0.78f, 1.75f, 1.75f)
verticalLineToRelative(9.0f)
curveToRelative(0.0f, 0.97f, -0.78f, 1.75f, -1.75f, 1.75f)
horizontalLineToRelative(-4.0f)
curveTo(2.78f, 22.0f, 2.0f, 21.22f, 2.0f, 20.25f)
verticalLineToRelative(-9.0f)
close()
moveTo(3.75f, 11.0f)
arcToRelative(0.25f, 0.25f, 0.0f, false, false, -0.25f, 0.25f)
verticalLineToRelative(9.0f)
curveToRelative(0.0f, 0.14f, 0.11f, 0.25f, 0.25f, 0.25f)
horizontalLineToRelative(4.0f)
curveToRelative(0.14f, 0.0f, 0.25f, -0.11f, 0.25f, -0.25f)
verticalLineToRelative(-9.0f)
arcToRelative(0.25f, 0.25f, 0.0f, false, false, -0.25f, -0.25f)
horizontalLineToRelative(-4.0f)
close()
}
}
return _deviceMeetingRoomRemote!!
}
private var _deviceMeetingRoomRemote: ImageVector? = null
| 1 | Kotlin | 3 | 83 | 9e86d93bf1f9ca63a93a913c990e95f13d8ede5a | 3,270 | compose-fluent-ui | Apache License 2.0 |
ProfileService/src/main/kotlin/com/github/saboteur/beeline/profileservice/model/Caller.kt | insotriplesix | 256,169,374 | false | null | package com.github.saboteur.beeline.profileservice.model
data class Caller(
val ctn: String,
val callerId: String
) {
companion object {
val empty = Caller(
ctn = "",
callerId = ""
)
}
} | 0 | Kotlin | 0 | 1 | 1266d45fe626d43daa302c69380ced87fcd8fcef | 243 | beeline-task | MIT License |
src/test/intg/com/kotlinspring/controller/CourseControllerIntgTest.kt | osawa-koki | 565,465,778 | false | {"Kotlin": 17093, "Dockerfile": 237} | package com.kotlinspring.controller;
import com.kotlinspring.dto.CourseDTO;
import com.kotlinspring.entity.Course
import com.kotlinspring.repository.CourseRepository
import com.kotlinspring.util.courseEntityList
import org.junit.jupiter.api.Assertions
import org.junit.jupiter.api.Assertions.assertEquals
import org.junit.jupiter.api.BeforeEach
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.client.AutoConfigureWebClient;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.ActiveProfiles;
import org.springframework.test.web.reactive.server.WebTestClient;
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
@ActiveProfiles("test")
@AutoConfigureWebClient
public class CourseControllerIntgTest {
@Autowired
lateinit var webTestClient: WebTestClient
@Autowired
lateinit var courseRepository: CourseRepository
@BeforeEach
fun setUp() {
courseRepository.deleteAll()
val courses = courseEntityList()
courseRepository.saveAll(courses)
}
@Test
fun addCourse() {
val courseDTO = CourseDTO(null, "kotlin", "webapi")
val savedCourseDTO = webTestClient
.post()
.uri("/v1/courses")
.bodyValue(courseDTO)
.exchange()
.expectStatus().isCreated
.expectBody(CourseDTO::class.java)
.returnResult()
.responseBody
Assertions.assertTrue {
savedCourseDTO?.id != null
}
}
@Test
fun retrieveAllCourses() {
val courseDTOs = webTestClient
.get()
.uri("/v1/courses")
.exchange()
.expectStatus().isOk
.expectBodyList(CourseDTO::class.java)
.returnResult()
.responseBody
println("courseDTOs: $courseDTOs")
assertEquals(3, courseDTOs!!.size)
}
@Test
fun updateCourse() {
val courseDTO = CourseDTO(null, "kotlin", "webapi")
val savedCourseDTO = webTestClient
.post()
.uri("/v1/courses")
.bodyValue(courseDTO)
.exchange()
.expectStatus().isCreated
.expectBody(CourseDTO::class.java)
.returnResult()
.responseBody
Assertions.assertTrue {
savedCourseDTO?.id != null
}
val updatedCourseDTO = CourseDTO(savedCourseDTO?.id, "kotlin updated", "webapi updated")
val updatedCourse = webTestClient
.put()
.uri("/v1/courses/${updatedCourseDTO.id}")
.bodyValue(updatedCourseDTO)
.exchange()
.expectStatus().isOk
.expectBody(CourseDTO::class.java)
.returnResult()
.responseBody
assertEquals(updatedCourseDTO.id, updatedCourse?.id)
assertEquals(updatedCourseDTO.name, updatedCourse?.name)
assertEquals(updatedCourseDTO.category, updatedCourse?.category)
}
@Test
fun simple_updateCourse() {
val course = Course(null, "kotlin", "webapi")
courseRepository.save(course)
CourseDTO(course.id, "kotlin updated", "webapi updated")
.let {
webTestClient
.put()
.uri("/v1/courses/{course_id}", it.id)
.bodyValue(it)
.exchange()
.expectStatus().isOk
.expectBody(CourseDTO::class.java)
.returnResult()
.responseBody
}
.let {
assertEquals("kotlin updated", it?.name)
assertEquals("webapi updated", it?.category)
}
}
@Test
fun deleteCourse() {
val course = Course(null, "kotlin", "webapi")
courseRepository.save(course)
webTestClient
.delete()
.uri("/v1/courses/{course_id}", course.id)
.exchange()
.expectStatus().isNoContent
}
}
| 0 | Kotlin | 0 | 0 | 0d3922e941bcc470631c46c1d71c339375f81c75 | 3,674 | cource-catalog-service.kt | Apache License 2.0 |
app/src/main/java/com/wechantloup/side/modules/details/DetailsRouter.kt | Pilou44 | 187,889,252 | false | null | package com.wechantloup.side.modules.details
import android.content.Intent
import com.wechantloup.side.R
import com.wechantloup.side.modules.core.BaseRouter
class DetailsRouter: BaseRouter(), DetailsContract.Router {
override fun share(view: DetailsContract.View, text: String) {
val sharingIntent = Intent(Intent.ACTION_SEND)
sharingIntent.type = "text/plain"
sharingIntent.putExtra(android.content.Intent.EXTRA_TEXT, text)
getActivity(view)?.startActivity(
Intent.createChooser(
sharingIntent,
getActivity(view)?.getString(R.string.share_with)
)
)
}
} | 0 | Kotlin | 0 | 0 | 0bae574d1c95ec8c0e72435a0d74d07e011203b7 | 660 | side | Apache License 2.0 |
app/src/main/java/com/ashishbhoi/tipcalculator/screen/home/TipView.kt | ashishbhoi | 443,431,940 | false | {"Kotlin": 26114} | package com.ashishbhoi.tipcalculator.screen.home
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.material.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.MutableState
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.unit.dp
@Composable
fun TipView(
totalBillState: MutableState<String>,
sliderPercentState: MutableState<Int>
) {
Row(
modifier = Modifier
.padding(horizontal = 8.dp, vertical = 14.dp)
.fillMaxWidth(),
horizontalArrangement = Arrangement.SpaceBetween,
verticalAlignment = Alignment.CenterVertically
) {
Text(text = "Tip")
Text(
text = "$${
"%.2f".format(
totalBillState.value.trim()
.toDouble() * (sliderPercentState.value).toDouble() / 100
)
}", modifier = Modifier.padding(4.dp)
)
}
} | 0 | Kotlin | 0 | 0 | 86031ac94e76e088b92f3932b8b5a5611e8520fb | 1,159 | Tip-Calculator-Jetpack-Compose-Android | MIT License |
duration/src/main/kotlin/eu/markov/kotlin/lucidtime/duration/Days.kt | markov | 156,861,890 | false | null | package eu.markov.kotlin.lucidtime.duration
inline val Double.days: Duration get() = (24.0 * this).hours
inline val Float.days: Duration get() = this.toDouble().days
inline val Long.days: Duration get() = (24L * this).hours
inline val Number.days: Duration get() = this.toLong().days
inline val Double.day: Duration get() = days
inline val Float.day: Duration get() = days
inline val Long.day: Duration get() = days
inline val Number.day: Duration get() = days
| 0 | Kotlin | 0 | 11 | 43b19665b1e5a5c910633e5c9c9507f1e21585b4 | 463 | lucid-time | Apache License 2.0 |
feature-dapp-impl/src/main/java/io/novafoundation/nova/feature_dapp_impl/presentation/search/DappSearchFragment.kt | novasamatech | 415,834,480 | false | {"Kotlin": 11112596, "Rust": 25308, "Java": 17664, "JavaScript": 425} | package io.novafoundation.nova.feature_dapp_impl.presentation.search
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.core.os.bundleOf
import androidx.lifecycle.lifecycleScope
import dev.chrisbanes.insetter.applyInsetter
import io.novafoundation.nova.common.base.BaseBottomSheetFragment
import io.novafoundation.nova.common.di.FeatureUtils
import io.novafoundation.nova.common.utils.applyStatusBarInsets
import io.novafoundation.nova.common.utils.bindTo
import io.novafoundation.nova.common.utils.keyboard.hideSoftKeyboard
import io.novafoundation.nova.common.utils.keyboard.showSoftKeyboard
import io.novafoundation.nova.common.view.dialog.warningDialog
import io.novafoundation.nova.feature_dapp_api.di.DAppFeatureApi
import io.novafoundation.nova.feature_dapp_impl.R
import io.novafoundation.nova.feature_dapp_impl.di.DAppFeatureComponent
import io.novafoundation.nova.feature_dapp_impl.domain.search.DappSearchResult
import kotlinx.android.synthetic.main.fragment_search_dapp.searchDappList
import kotlinx.android.synthetic.main.fragment_search_dapp.searchDappSearch
import kotlinx.android.synthetic.main.fragment_search_dapp.searchDappSearhContainer
class DappSearchFragment : BaseBottomSheetFragment<DAppSearchViewModel>(), SearchDappAdapter.Handler {
companion object {
private const val PAYLOAD = "DappSearchFragment.PAYLOAD"
fun getBundle(payload: SearchPayload) = bundleOf(
PAYLOAD to payload
)
}
private val adapter by lazy(LazyThreadSafetyMode.NONE) { SearchDappAdapter(this) }
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
return layoutInflater.inflate(R.layout.fragment_search_dapp, container, false)
}
override fun initViews() {
searchDappSearch.applyStatusBarInsets()
searchDappSearhContainer.applyInsetter {
type(ime = true) {
padding()
}
}
searchDappList.adapter = adapter
searchDappList.setHasFixedSize(true)
searchDappSearch.cancel.setOnClickListener {
viewModel.cancelClicked()
hideKeyboard()
}
searchDappSearch.searchInput.requestFocus()
searchDappSearch.searchInput.content.showSoftKeyboard()
}
override fun inject() {
FeatureUtils.getFeature<DAppFeatureComponent>(this, DAppFeatureApi::class.java)
.dAppSearchComponentFactory()
.create(this, argument(PAYLOAD))
.inject(this)
}
override fun subscribe(viewModel: DAppSearchViewModel) {
setupDAppNotInCatalogWarning()
searchDappSearch.searchInput.content.bindTo(viewModel.query, lifecycleScope)
viewModel.searchResults.observe(::submitListPreservingViewPoint)
viewModel.dAppNotInCatalogWarning
viewModel.selectQueryTextEvent.observeEvent {
searchDappSearch.searchInput.content.selectAll()
}
}
override fun itemClicked(searchResult: DappSearchResult) {
hideKeyboard()
viewModel.searchResultClicked(searchResult)
}
private fun hideKeyboard() {
searchDappSearch.searchInput.hideSoftKeyboard()
}
private fun submitListPreservingViewPoint(data: List<Any?>) {
val recyclerViewState = searchDappList.layoutManager!!.onSaveInstanceState()
adapter.submitList(data) {
searchDappList.layoutManager!!.onRestoreInstanceState(recyclerViewState)
}
}
private fun setupDAppNotInCatalogWarning() {
viewModel.dAppNotInCatalogWarning.awaitableActionLiveData.observeEvent { event ->
warningDialog(
context = providedContext,
onPositiveClick = { event.onCancel() },
positiveTextRes = R.string.common_close,
negativeTextRes = R.string.dapp_url_warning_open_anyway,
onNegativeClick = { event.onSuccess(Unit) },
styleRes = R.style.AccentNegativeAlertDialogTheme
) {
setTitle(R.string.dapp_url_warning_title)
setMessage(requireContext().getString(R.string.dapp_url_warning_subtitle, event.payload.supportEmail))
}
}
}
}
| 14 | Kotlin | 30 | 50 | 166755d1c3388a7afd9b592402489ea5ca26fdb8 | 4,365 | nova-wallet-android | Apache License 2.0 |
app-tracking-protection/vpn-impl/src/test/java/com/duckduckgo/mobile/android/vpn/service/state/RealVpnStateMonitorTest.kt | hojat72elect | 822,396,044 | false | {"Kotlin": 11626231, "HTML": 65873, "Ruby": 16984, "C++": 10312, "JavaScript": 5520, "CMake": 1992, "C": 1076, "Shell": 784} |
package com.duckduckgo.mobile.android.vpn.service.state
import com.duckduckgo.common.test.CoroutineTestRule
import com.duckduckgo.mobile.android.vpn.VpnFeaturesRegistry
import com.duckduckgo.mobile.android.vpn.dao.HeartBeatEntity
import com.duckduckgo.mobile.android.vpn.dao.VpnHeartBeatDao
import com.duckduckgo.mobile.android.vpn.dao.VpnServiceStateStatsDao
import com.duckduckgo.mobile.android.vpn.heartbeat.VpnServiceHeartbeatMonitor
import com.duckduckgo.mobile.android.vpn.model.VpnServiceState.DISABLED
import com.duckduckgo.mobile.android.vpn.model.VpnServiceState.ENABLED
import com.duckduckgo.mobile.android.vpn.model.VpnServiceStateStats
import com.duckduckgo.mobile.android.vpn.model.VpnStoppingReason.SELF_STOP
import kotlinx.coroutines.test.runTest
import org.junit.Assert
import org.junit.Before
import org.junit.Rule
import org.junit.Test
import org.mockito.Mock
import org.mockito.MockitoAnnotations
import org.mockito.kotlin.whenever
class RealVpnStateMonitorTest {
@get:Rule
var coroutineRule = CoroutineTestRule()
@Mock
private lateinit var vpnHeartBeatDao: VpnHeartBeatDao
@Mock
private lateinit var vpnServiceStateDao: VpnServiceStateStatsDao
@Mock
private lateinit var vpnFeaturesRegistry: VpnFeaturesRegistry
private lateinit var testee: RealVpnStateMonitor
@Before
fun setUp() {
MockitoAnnotations.openMocks(this)
testee = RealVpnStateMonitor(
vpnHeartBeatDao,
vpnServiceStateDao,
vpnFeaturesRegistry,
coroutineRule.testDispatcherProvider,
)
}
@Test
fun whenIsAllaysOnEnabledThenReturnDefaultValueFalse() = runTest {
Assert.assertFalse(testee.isAlwaysOnEnabled())
}
@Test
fun whenVpnLastDisabledByAndroidAndVpnKilledBySystemThenReturnTrue() = runTest {
whenever(vpnServiceStateDao.getLastStateStats()).thenReturn(null)
whenever(vpnHeartBeatDao.hearBeats()).thenReturn(listOf(HeartBeatEntity(type = VpnServiceHeartbeatMonitor.DATA_HEART_BEAT_TYPE_ALIVE)))
whenever(vpnFeaturesRegistry.isAnyFeatureRunning()).thenReturn(false)
Assert.assertTrue(testee.vpnLastDisabledByAndroid())
}
@Test
fun whenVpnLastDisabledByAndroidAndVpnUnexpectedlyDisabledThenReturnTrue() = runTest {
whenever(vpnServiceStateDao.getLastStateStats()).thenReturn(
VpnServiceStateStats(state = DISABLED),
)
Assert.assertTrue(testee.vpnLastDisabledByAndroid())
}
@Test
fun whenVpnLastDisabledByAndroidAndVpnDisabledByUserThenReturnFalse() = runTest {
whenever(vpnServiceStateDao.getLastStateStats()).thenReturn(
VpnServiceStateStats(state = DISABLED, stopReason = SELF_STOP),
)
Assert.assertFalse(testee.vpnLastDisabledByAndroid())
}
@Test
fun whenVpnLastDisabledByAndroidAndVpnEnabledThenReturnFalse() = runTest {
whenever(vpnServiceStateDao.getLastStateStats()).thenReturn(
VpnServiceStateStats(state = ENABLED),
)
Assert.assertFalse(testee.vpnLastDisabledByAndroid())
}
}
| 0 | Kotlin | 0 | 0 | b89591136b60933d6a03fac43a38ee183116b7f8 | 3,113 | DuckDuckGo | Apache License 2.0 |
app/src/main/java/com/mikelau/notes/data/local/NoteLocalRepository.kt | mike14u | 215,270,917 | false | null | package com.mikelau.notes.data.local
import android.app.Application
import androidx.lifecycle.LiveData
import com.mikelau.notes.data.models.Note
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.launch
class NoteLocalRepository(application: Application) {
private val database = NoteDatabase.getInstance(application)
private val noteDao: NoteDao
private val allNotes: LiveData<List<Note>>
init {
noteDao = database.noteDao()
allNotes = noteDao.allNotes
}
fun insert(note: Note) = GlobalScope.launch(Dispatchers.IO) { noteDao.insert(note) }
fun update(note: Note) = GlobalScope.launch(Dispatchers.IO) { noteDao.update(note) }
fun delete(note: Note) = GlobalScope.launch(Dispatchers.IO) { noteDao.delete(note) }
fun deleteAllNotes() = GlobalScope.launch(Dispatchers.IO) { noteDao.deleteAllNotes() }
fun getAllNotes(): LiveData<List<Note>> { return allNotes }
fun close() { if (database.isOpen) database.close() }
}
| 0 | Kotlin | 0 | 0 | 36e90224db9288a34afb628939540af119927230 | 1,036 | android-stack-reference | MIT License |
app/src/main/java/com/kuyuzhiqi/imageblur/MainActivity.kt | kuyu132 | 158,989,580 | false | null | package com.kuyuzhiqi.imageblur
import android.content.Intent
import android.os.Bundle
import android.support.v7.app.AppCompatActivity
import android.support.v7.widget.LinearLayoutManager
import android.view.View
import com.chad.library.adapter.base.BaseQuickAdapter
import com.chad.library.adapter.base.BaseViewHolder
import com.chad.library.adapter.base.listener.OnItemClickListener
import com.kuyuzhiqi.imageblur.ui.BinaryzationActivity
import com.kuyuzhiqi.imageblur.ui.GassBlurActivity
import com.kuyuzhiqi.imageblur.ui.GrayImageActivity
import kotlinx.android.synthetic.main.activity_main.*
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
var list = ArrayList<String>().apply {
add("高斯模糊")
add("灰度图像")
add("二值化")
}
rv_list.adapter = ItemAdapter(list)
rv_list.layoutManager = LinearLayoutManager(this)
rv_list.addOnItemTouchListener(object : OnItemClickListener() {
override fun onSimpleItemClick(adapter: BaseQuickAdapter<*, *>?, view: View?, position: Int) {
when (position) {
0 -> {
startActivity(Intent(this@MainActivity, GassBlurActivity::class.java))
}
1 -> {
startActivity(Intent(this@MainActivity, GrayImageActivity::class.java))
}
2 -> {
startActivity(Intent(this@MainActivity, BinaryzationActivity::class.java))
}
}
}
})
}
class ItemAdapter(list: List<String>) : BaseQuickAdapter<String, BaseViewHolder>(R.layout.item_main, list) {
override fun convert(holder: BaseViewHolder, item: String) {
holder.setText(R.id.tv_name, item)
}
}
}
| 0 | Kotlin | 0 | 0 | 3164bfedb7e2f24df9dfa7b53929a3cff6801095 | 1,968 | ImageBlur | Apache License 2.0 |
src/main/kotlin/dev/paulshields/chronomancy/common/Exceptions.kt | Pkshields | 333,756,390 | false | null | package dev.paulshields.chronomancy.common
class KeyNotFoundException(key: String) : RuntimeException("Key $key was not found.")
class TwelveHourPostfixNotValidException(item: String) : RuntimeException("$item is neither AM or PM.")
class TimeIsNotValidException(timeAsString: String) : RuntimeException("$timeAsString is not a valid time.")
| 0 | Kotlin | 0 | 0 | 9a6cfe2ba145c5904d98c391417a23ef01876923 | 345 | Chronomancy | MIT License |
defitrack-rest/defitrack-protocol-services/defitrack-swapfish/src/main/java/io/defitrack/SwapfishApplication.kt | decentri-fi | 426,174,152 | false | null | package io.defitrack
import org.springframework.boot.autoconfigure.SpringBootApplication
import org.springframework.boot.runApplication
import org.springframework.scheduling.annotation.EnableScheduling
@SpringBootApplication
@EnableScheduling
class SwapfishApplication
fun main(args: Array<String>) {
runApplication<SwapfishApplication>(*args)
} | 16 | Kotlin | 6 | 5 | e4640223e69c30f986b8b4238e026202b08a5548 | 352 | defi-hub | MIT License |
app/src/main/java/com/sample/marvel_mvvm_flow/data/MarvelApi.kt | carloxavier | 490,957,339 | false | {"Kotlin": 11584} | package com.sample.marvel_mvvm_flow.data
import com.sample.marvel_mvvm_flow.domain.MarvelCharacter
import retrofit2.http.GET
interface MarvelApi {
@GET("/v1/public/characters")
suspend fun fetchMarvelCharacters(): MarvelApiResponse<List<MarvelCharacter>>
} | 0 | Kotlin | 0 | 2 | 02e5ed82ec5f18cc7f8119545e1b1e32e0ef8f0c | 266 | android-mvvm-livedata-flow | MIT License |
MyReactNativeApp/android/app/src/main/java/com/awesomeproject/AnExampleReactPackage/ToastModule.kt | ios122 | 106,680,141 | false | null | package com.awesomeproject.AnExampleReactPackage
import android.widget.Toast
import com.facebook.react.bridge.ReactApplicationContext
import com.facebook.react.bridge.ReactContextBaseJavaModule
import com.facebook.react.bridge.ReactMethod
import java.util.HashMap
/**
* Created by yanfeng on 2017/10/12.
*/
class ToastModule(reactContext: ReactApplicationContext) : ReactContextBaseJavaModule(reactContext) {
override fun getName(): String {
return "ToastExample"
}
override fun getConstants(): Map<String, Any>? {
val constants = HashMap<String, Any>()
constants.put(DURATION_SHORT_KEY, Toast.LENGTH_SHORT)
constants.put(DURATION_LONG_KEY, Toast.LENGTH_LONG)
return constants
}
@ReactMethod
fun show(message: String, duration: Int) {
Toast.makeText(reactApplicationContext, message, duration).show()
}
companion object {
private val DURATION_SHORT_KEY = "SHORT"
private val DURATION_LONG_KEY = "LONG"
}
} | 0 | Kotlin | 2 | 9 | 8180f7210c228ad3ec7d6188d0fae042de5f15bc | 1,017 | kotlin-module-sample-for-reactnative | MIT License |
app/src/main/java/com/faigenbloom/familybudget/ui/spendings/list/SpendingsListPage.kt | ZakharchenkoWork | 706,155,222 | false | {"Kotlin": 746176} | package com.faigenbloom.familybudget.ui.spendings.list
import androidx.compose.foundation.Image
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.fillMaxHeight
import androidx.compose.foundation.layout.padding
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Surface
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.mutableStateOf
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import androidx.paging.LoadState
import androidx.paging.PagingData
import androidx.paging.compose.collectAsLazyPagingItems
import com.faigenbloom.familybudget.R
import com.faigenbloom.familybudget.common.TopBar
import com.faigenbloom.familybudget.common.isEmpty
import com.faigenbloom.familybudget.common.ui.Loading
import com.faigenbloom.familybudget.domain.spendings.DatedList
import com.faigenbloom.familybudget.domain.spendings.Pattern
import com.faigenbloom.familybudget.domain.spendings.PlateSizeType
import com.faigenbloom.familybudget.ui.theme.FamillySpandingsTheme
import com.faigenbloom.ninepatch.painterResourceNinePath
import kotlinx.coroutines.flow.flowOf
@Composable
fun SpendingsListPage(
modifier: Modifier = Modifier,
state: SpendingsState,
onOpenSpending: (String) -> Unit,
) {
Column(modifier = modifier) {
TopBar(
title = stringResource(
id = if (state.filterType.isPlanned) {
R.string.spendings_planned_title
} else {
R.string.spendings_previous_title
},
),
)
val lazyPagingItems = state.spendingsPager.collectAsLazyPagingItems()
if (state.isLoading.value.not()) {
if (lazyPagingItems.isEmpty()) {
if (lazyPagingItems.loadState.source.refresh is LoadState.NotLoading &&
lazyPagingItems.loadState.append.endOfPaginationReached
&& lazyPagingItems.itemCount < 1
) {
EmptySpendings(modifier = modifier)
} else {
Loading(true)
}
} else {
DynamicPlatesHolder(
datedPatterns = lazyPagingItems,
filterType = state.filterType,
onSpendingClicked = onOpenSpending,
)
}
} else {
Loading(true)
}
}
}
@Composable
fun EmptySpendings(
modifier: Modifier = Modifier,
) {
Column(
modifier = modifier,
horizontalAlignment = Alignment.CenterHorizontally,
) {
Image(
modifier = Modifier.padding(top = 32.dp),
painter = painterResource(id = R.drawable.icon),
contentDescription = "",
)
Text(
modifier = Modifier.padding(32.dp),
textAlign = TextAlign.Center,
text = stringResource(R.string.spendings_no_spendings_message),
style = MaterialTheme.typography.titleLarge,
color = MaterialTheme.colorScheme.onBackground,
)
Image(
modifier = Modifier.fillMaxHeight(),
painter = painterResourceNinePath(id = R.drawable.icon_arrow_down),
contentDescription = "",
)
}
}
@Preview(showBackground = true)
@Composable
fun SpandingsEmptyPagePreview() {
FamillySpandingsTheme {
Surface {
SpendingsListPage(
onOpenSpending = {},
state = SpendingsState(),
)
}
}
}
@Preview(showBackground = true)
@Composable
fun SpandingsPagePreview() {
FamillySpandingsTheme {
Surface {
SpendingsListPage(
onOpenSpending = {},
state = SpendingsState(
spendingsPager = flowOf(
value = PagingData.from(
listOf(
DatedList(
listOf(
Pattern<SpendingCategoryUiData>(
listOf(
PlateSizeType.SIZE_THREE_BY_ONE,
),
).apply {
items = listOf(
mockSpendingsWithCategoryList[0],
)
},
Pattern<SpendingCategoryUiData>(
listOf(
PlateSizeType.SIZE_TWO_BY_ONE,
),
).apply {
items = listOf(
mockSpendingsWithCategoryList[0],
)
},
Pattern<SpendingCategoryUiData>(
listOf(
PlateSizeType.SIZE_ONE_BY_ONE,
PlateSizeType.SIZE_ONE_BY_ONE,
PlateSizeType.SIZE_ONE_BY_ONE,
),
).apply {
items = listOf(
mockSpendingsWithCategoryList[0],
mockSpendingsWithCategoryList[1],
mockSpendingsWithCategoryList[2],
)
},
Pattern<SpendingCategoryUiData>(
listOf(
PlateSizeType.SIZE_ONE_BY_ONE,
PlateSizeType.SIZE_ONE_BY_ONE,
),
).apply {
items = listOf(
mockSpendingsWithCategoryList[0],
mockSpendingsWithCategoryList[1],
)
},
Pattern<SpendingCategoryUiData>(
listOf(
PlateSizeType.SIZE_ONE_BY_ONE,
),
).apply {
items = listOf(
mockSpendingsWithCategoryList[0],
)
},
),
),
),
),
),
isLoading = mutableStateOf(false),
),
)
}
}
}
| 0 | Kotlin | 0 | 0 | e81fa66d6afd5b79d3299583a73378c3ee1463ca | 7,727 | FamilyBudget | Apache License 2.0 |
tim/src/main/java/com/angcyo/tim/bean/Emoji.kt | angcyo | 229,037,684 | false | {"Kotlin": 3416972, "JavaScript": 5542, "HTML": 1598} | package com.angcyo.tim.bean
import android.graphics.Bitmap
import com.angcyo.tim.util.FaceManager.defaultEmojiSize
/**
*
* Email:<EMAIL>
* @author angcyo
* @date 2021/11/11
* Copyright (c) 2020 ShenZhen Wayto Ltd. All rights reserved.
*/
class Emoji {
var desc: String? = null
var filter: String? = null //[傲慢] [删除]
var icon: Bitmap? = null
var width: Int = defaultEmojiSize
var height: Int = defaultEmojiSize
} | 0 | Kotlin | 4 | 4 | 7c9000a117a0b405c17d19a067874413c52042ba | 439 | UICoreEx | MIT License |
app/src/main/java/com/biomorf/pllmaster/DebugTag.kt | TohaRG2 | 189,725,751 | false | null | package com.biomorf.pllmaster
/**
* Created by anton on 28.11.17. Тэг для записи в лог
*/
object DebugTag {
val TAG = "PLLMaster"
} | 0 | Kotlin | 0 | 0 | cb8f761fa510f11131f39c20f9d8adc3bc1301d9 | 139 | PLLMaster | Apache License 2.0 |
app/src/main/java/com/example/merchantinventory/AdminDetails.kt | Naphtali-cpu | 415,510,092 | false | {"Kotlin": 6575} | package com.example.merchantinventory
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
class AdminDetails : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_admin_details)
}
} | 0 | Kotlin | 0 | 0 | 3942f225fddee15dd470ced0021f3f0069010a9c | 319 | Merchant-Inventory | The Unlicense |
app/src/main/java/com/alwan/bajpsubmission3/data/source/local/room/CatalogueDao.kt | alwanfauzy | 445,742,309 | false | null | package com.alwan.bajpsubmission3.data.source.local.room
import androidx.lifecycle.LiveData
import androidx.paging.DataSource
import androidx.room.*
import androidx.sqlite.db.SimpleSQLiteQuery
import com.alwan.bajpsubmission3.data.source.local.entity.MovieEntity
import com.alwan.bajpsubmission3.data.source.local.entity.TvShowEntity
@Dao
interface CatalogueDao {
@RawQuery(observedEntities = [MovieEntity::class])
fun getMovies(query: SimpleSQLiteQuery): DataSource.Factory<Int, MovieEntity>
@Query("SELECT * FROM movie_entities WHERE id = :id")
fun getMovieById(id: Int): LiveData<MovieEntity>
@Query("SELECT * FROM movie_entities WHERE isFavorite = 1")
fun getFavoriteMovies(): DataSource.Factory<Int, MovieEntity>
@RawQuery(observedEntities = [TvShowEntity::class])
fun getTvShows(query: SimpleSQLiteQuery): DataSource.Factory<Int, TvShowEntity>
@Query("SELECT * FROM tv_show_entities WHERE id = :id")
fun getTvShowById(id: Int): LiveData<TvShowEntity>
@Query("SELECT * FROM tv_show_entities WHERE isFavorite = 1")
fun getFavoriteTvShows(): DataSource.Factory<Int, TvShowEntity>
@Insert(onConflict = OnConflictStrategy.REPLACE)
fun insertMovies(movies: List<MovieEntity>)
@Update
fun updateMovie(movie: MovieEntity)
@Insert(onConflict = OnConflictStrategy.REPLACE)
fun insertTvShows(tvShows: List<TvShowEntity>)
@Update
fun updateTvShow(tvShow: TvShowEntity)
} | 0 | Kotlin | 0 | 0 | 2376b3edc46404c814644a7bcb55dd1f96bf2803 | 1,455 | bajp-s3 | Apache License 2.0 |
camera/camera-camera2-pipe-integration/src/test/java/androidx/camera/camera2/pipe/integration/adapter/SupportedSurfaceCombinationTest.kt | KOLANICH-libs | 445,548,183 | true | {"Kotlin": 68310818, "Java": 60327498, "C++": 9028407, "Python": 292398, "AIDL": 264519, "Shell": 174895, "HTML": 21175, "ANTLR": 19860, "CMake": 12136, "TypeScript": 7599, "C": 7083, "Swift": 3153, "JavaScript": 1343} | /*
* 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
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package androidx.camera.camera2.pipe.integration.adapter
import android.content.Context
import android.graphics.ImageFormat
import android.graphics.SurfaceTexture
import android.hardware.camera2.CameraCharacteristics
import android.hardware.camera2.CameraManager
import android.hardware.camera2.params.StreamConfigurationMap
import android.media.CamcorderProfile
import android.media.MediaRecorder
import android.os.Build
import android.util.Pair
import android.util.Rational
import android.util.Size
import android.view.Surface
import android.view.WindowManager
import androidx.camera.camera2.pipe.CameraId
import androidx.camera.camera2.pipe.CameraMetadata
import androidx.camera.camera2.pipe.integration.CameraPipeConfig
import androidx.camera.camera2.pipe.integration.adapter.GuaranteedConfigurationsUtil.getFullSupportedCombinationList
import androidx.camera.camera2.pipe.integration.adapter.GuaranteedConfigurationsUtil.getLegacySupportedCombinationList
import androidx.camera.camera2.pipe.integration.adapter.GuaranteedConfigurationsUtil.getLevel3SupportedCombinationList
import androidx.camera.camera2.pipe.integration.adapter.GuaranteedConfigurationsUtil.getLimitedSupportedCombinationList
import androidx.camera.camera2.pipe.integration.adapter.GuaranteedConfigurationsUtil.getRAWSupportedCombinationList
import androidx.camera.camera2.pipe.integration.config.CameraAppComponent
import androidx.camera.camera2.pipe.integration.testing.FakeCameraDevicesWithCameraMetaData
import androidx.camera.core.AspectRatio
import androidx.camera.core.CameraSelector
import androidx.camera.core.CameraSelector.LensFacing
import androidx.camera.core.CameraX
import androidx.camera.core.CameraXConfig
import androidx.camera.core.ImageAnalysis
import androidx.camera.core.ImageCapture
import androidx.camera.core.Preview
import androidx.camera.core.SurfaceRequest
import androidx.camera.core.UseCase
import androidx.camera.core.impl.CamcorderProfileProxy
import androidx.camera.core.impl.CameraThreadConfig
import androidx.camera.core.impl.MutableStateObservable
import androidx.camera.core.impl.Observable
import androidx.camera.core.impl.SurfaceCombination
import androidx.camera.core.impl.SurfaceConfig
import androidx.camera.core.impl.UseCaseConfig
import androidx.camera.core.impl.UseCaseConfigFactory
import androidx.camera.core.impl.utils.CompareSizesByArea
import androidx.camera.core.impl.utils.executor.CameraXExecutors
import androidx.camera.testing.CamcorderProfileUtil
import androidx.camera.testing.CameraUtil
import androidx.camera.testing.CameraXUtil
import androidx.camera.testing.Configs
import androidx.camera.testing.SurfaceTextureProvider
import androidx.camera.testing.SurfaceTextureProvider.SurfaceTextureCallback
import androidx.camera.testing.fakes.FakeCamcorderProfileProvider
import androidx.camera.testing.fakes.FakeCamera
import androidx.camera.testing.fakes.FakeCameraFactory
import androidx.camera.testing.fakes.FakeCameraInfoInternal
import androidx.camera.testing.fakes.FakeUseCaseConfig
import androidx.camera.video.FallbackStrategy
import androidx.camera.video.MediaSpec
import androidx.camera.video.Quality
import androidx.camera.video.QualitySelector
import androidx.camera.video.VideoCapture
import androidx.camera.video.VideoOutput
import androidx.camera.video.VideoOutput.SourceState
import androidx.camera.video.VideoSpec
import androidx.test.core.app.ApplicationProvider
import androidx.test.platform.app.InstrumentationRegistry
import androidx.testutils.assertThrows
import com.google.common.truth.Truth
import java.util.Arrays
import java.util.concurrent.ExecutionException
import java.util.concurrent.TimeUnit
import org.junit.After
import org.junit.Before
import org.junit.Test
import org.junit.runner.RunWith
import org.mockito.ArgumentMatchers
import org.mockito.Mockito
import org.robolectric.RobolectricTestRunner
import org.robolectric.Shadows
import org.robolectric.annotation.Config
import org.robolectric.annotation.internal.DoNotInstrument
import org.robolectric.shadow.api.Shadow
import org.robolectric.shadows.ShadowCameraCharacteristics
import org.robolectric.shadows.ShadowCameraManager
@Suppress("DEPRECATION")
@RunWith(RobolectricTestRunner::class)
@DoNotInstrument
@Config(minSdk = Build.VERSION_CODES.LOLLIPOP)
class SupportedSurfaceCombinationTest {
private val cameraId = "0"
private val cameraIdExternal = "0-external"
private val sensorOrientation0 = 0
private val sensorOrientation90 = 90
private val aspectRatio43 = Rational(4, 3)
private val aspectRatio169 = Rational(16, 9)
private val landscapePixelArraySize = Size(4032, 3024)
private val portraitPixelArraySize = Size(3024, 4032)
private val displaySize = Size(720, 1280)
private val vgaSize = Size(640, 480)
private val previewSize = Size(1280, 720)
private val recordSize = Size(3840, 2160)
private val maximumSize = Size(4032, 3024)
private val legacyVideoMaximumVideoSize = Size(1920, 1080)
private val mod16Size = Size(960, 544)
private val profileUhd = CamcorderProfileUtil.createCamcorderProfileProxy(
CamcorderProfile.QUALITY_2160P, recordSize.width, recordSize
.height
)
private val profileFhd = CamcorderProfileUtil.createCamcorderProfileProxy(
CamcorderProfile.QUALITY_1080P, 1920, 1080
)
private val profileHd = CamcorderProfileUtil.createCamcorderProfileProxy(
CamcorderProfile.QUALITY_720P, previewSize.width, previewSize
.height
)
private val profileSd = CamcorderProfileUtil.createCamcorderProfileProxy(
CamcorderProfile.QUALITY_480P, vgaSize.width,
vgaSize.height
)
private val supportedSizes = arrayOf(
Size(4032, 3024), // 4:3
Size(3840, 2160), // 16:9
Size(1920, 1440), // 4:3
Size(1920, 1080), // 16:9
Size(1280, 960), // 4:3
Size(1280, 720), // 16:9
Size(1280, 720), // duplicate the size since Nexus 5X emulator has the
Size(960, 544), // a mod16 version of resolution with 16:9 aspect ratio.
Size(800, 450), // 16:9
Size(640, 480), // 4:3
Size(320, 240), // 4:3
Size(320, 180), // 16:9
Size(256, 144) // 16:9 For checkSmallSizesAreFilteredOut test.
)
private val context = InstrumentationRegistry.getInstrumentation().context
private var cameraFactory: FakeCameraFactory? = null
private var useCaseConfigFactory = Mockito.mock(
UseCaseConfigFactory::class.java
)
private val mockCameraMetadata = Mockito.mock(
CameraMetadata::class.java
)
private val mockCameraAppComponent = Mockito.mock(
CameraAppComponent::class.java
)
private val mockCamcorderProfileAdapter = Mockito.mock(
CamcorderProfileProviderAdapter::class.java
)
private val mockCamcorderProxy = Mockito.mock(
CamcorderProfileProxy::class.java
)
@Before
fun setUp() {
val windowManager = context.getSystemService(Context.WINDOW_SERVICE) as WindowManager
Shadows.shadowOf(windowManager.defaultDisplay).setRealWidth(displaySize.width)
Shadows.shadowOf(windowManager.defaultDisplay).setRealHeight(
displaySize
.height
)
Mockito.`when`(mockCamcorderProfileAdapter.hasProfile(ArgumentMatchers.anyInt()))
.thenReturn(true)
Mockito.`when`(mockCamcorderProxy.videoFrameWidth).thenReturn(3840)
Mockito.`when`(mockCamcorderProxy.videoFrameHeight).thenReturn(2160)
Mockito.`when`(mockCamcorderProfileAdapter[ArgumentMatchers.anyInt()])
.thenReturn(mockCamcorderProxy)
}
@After
fun tearDown() {
CameraXUtil.shutdown()[10000, TimeUnit.MILLISECONDS]
}
@Test
fun checkLegacySurfaceCombinationSupportedInLegacyDevice() {
setupCamera(CameraCharacteristics.INFO_SUPPORTED_HARDWARE_LEVEL_LEGACY)
val supportedSurfaceCombination = SupportedSurfaceCombination(
context, mockCameraMetadata, cameraId,
mockCamcorderProfileAdapter
)
val combinationList = getLegacySupportedCombinationList()
for (combination in combinationList) {
val isSupported =
supportedSurfaceCombination.checkSupported(combination.surfaceConfigList)
Truth.assertThat(isSupported).isTrue()
}
}
@Test
fun checkLegacySurfaceCombinationSubListSupportedInLegacyDevice() {
setupCamera(CameraCharacteristics.INFO_SUPPORTED_HARDWARE_LEVEL_LEGACY)
val supportedSurfaceCombination = SupportedSurfaceCombination(
context, mockCameraMetadata, cameraId,
mockCamcorderProfileAdapter
)
val combinationList = getLegacySupportedCombinationList()
val isSupported = isAllSubConfigListSupported(supportedSurfaceCombination, combinationList)
Truth.assertThat(isSupported).isTrue()
}
@Test
fun checkLimitedSurfaceCombinationNotSupportedInLegacyDevice() {
setupCamera(CameraCharacteristics.INFO_SUPPORTED_HARDWARE_LEVEL_LEGACY)
val supportedSurfaceCombination = SupportedSurfaceCombination(
context, mockCameraMetadata, cameraId,
mockCamcorderProfileAdapter
)
val combinationList = getLimitedSupportedCombinationList()
for (combination in combinationList) {
val isSupported =
supportedSurfaceCombination.checkSupported(combination.surfaceConfigList)
Truth.assertThat(isSupported).isFalse()
}
}
@Test
fun checkFullSurfaceCombinationNotSupportedInLegacyDevice() {
setupCamera(CameraCharacteristics.INFO_SUPPORTED_HARDWARE_LEVEL_LEGACY)
val supportedSurfaceCombination = SupportedSurfaceCombination(
context, mockCameraMetadata, cameraId,
mockCamcorderProfileAdapter
)
val combinationList = getFullSupportedCombinationList()
for (combination in combinationList) {
val isSupported =
supportedSurfaceCombination.checkSupported(combination.surfaceConfigList)
Truth.assertThat(isSupported).isFalse()
}
}
@Test
fun checkLevel3SurfaceCombinationNotSupportedInLegacyDevice() {
setupCamera(CameraCharacteristics.INFO_SUPPORTED_HARDWARE_LEVEL_LEGACY)
val supportedSurfaceCombination = SupportedSurfaceCombination(
context, mockCameraMetadata, cameraId,
mockCamcorderProfileAdapter
)
val combinationList = getLevel3SupportedCombinationList()
for (combination in combinationList) {
val isSupported =
supportedSurfaceCombination.checkSupported(combination.surfaceConfigList)
Truth.assertThat(isSupported).isFalse()
}
}
@Test
fun checkLimitedSurfaceCombinationSupportedInLimitedDevice() {
setupCamera(CameraCharacteristics.INFO_SUPPORTED_HARDWARE_LEVEL_LIMITED)
val supportedSurfaceCombination = SupportedSurfaceCombination(
context, mockCameraMetadata, cameraId,
mockCamcorderProfileAdapter
)
val combinationList = getLimitedSupportedCombinationList()
for (combination in combinationList) {
val isSupported =
supportedSurfaceCombination.checkSupported(combination.surfaceConfigList)
Truth.assertThat(isSupported).isTrue()
}
}
@Test
fun checkLimitedSurfaceCombinationSubListSupportedInLimited3Device() {
setupCamera(CameraCharacteristics.INFO_SUPPORTED_HARDWARE_LEVEL_LIMITED)
val supportedSurfaceCombination = SupportedSurfaceCombination(
context, mockCameraMetadata, cameraId,
mockCamcorderProfileAdapter
)
val combinationList = getLimitedSupportedCombinationList()
val isSupported = isAllSubConfigListSupported(supportedSurfaceCombination, combinationList)
Truth.assertThat(isSupported).isTrue()
}
@Test
fun checkFullSurfaceCombinationNotSupportedInLimitedDevice() {
setupCamera(CameraCharacteristics.INFO_SUPPORTED_HARDWARE_LEVEL_LIMITED)
val supportedSurfaceCombination = SupportedSurfaceCombination(
context, mockCameraMetadata, cameraId,
mockCamcorderProfileAdapter
)
val combinationList = getFullSupportedCombinationList()
for (combination in combinationList) {
val isSupported =
supportedSurfaceCombination.checkSupported(combination.surfaceConfigList)
Truth.assertThat(isSupported).isFalse()
}
}
@Test
fun checkLevel3SurfaceCombinationNotSupportedInLimitedDevice() {
setupCamera(CameraCharacteristics.INFO_SUPPORTED_HARDWARE_LEVEL_LIMITED)
val supportedSurfaceCombination = SupportedSurfaceCombination(
context, mockCameraMetadata, cameraId,
mockCamcorderProfileAdapter
)
val combinationList = getLevel3SupportedCombinationList()
for (combination in combinationList) {
val isSupported =
supportedSurfaceCombination.checkSupported(combination.surfaceConfigList)
Truth.assertThat(isSupported).isFalse()
}
}
@Test
fun checkFullSurfaceCombinationSupportedInFullDevice() {
setupCamera(CameraCharacteristics.INFO_SUPPORTED_HARDWARE_LEVEL_FULL)
val supportedSurfaceCombination = SupportedSurfaceCombination(
context, mockCameraMetadata, cameraId,
mockCamcorderProfileAdapter
)
val combinationList = getFullSupportedCombinationList()
for (combination in combinationList) {
val isSupported =
supportedSurfaceCombination.checkSupported(combination.surfaceConfigList)
Truth.assertThat(isSupported).isTrue()
}
}
@Test
fun checkFullSurfaceCombinationSubListSupportedInFullDevice() {
setupCamera(CameraCharacteristics.INFO_SUPPORTED_HARDWARE_LEVEL_FULL)
val supportedSurfaceCombination = SupportedSurfaceCombination(
context, mockCameraMetadata, cameraId,
mockCamcorderProfileAdapter
)
val combinationList = getFullSupportedCombinationList()
val isSupported = isAllSubConfigListSupported(supportedSurfaceCombination, combinationList)
Truth.assertThat(isSupported).isTrue()
}
@Test
fun checkLevel3SurfaceCombinationNotSupportedInFullDevice() {
setupCamera(CameraCharacteristics.INFO_SUPPORTED_HARDWARE_LEVEL_FULL)
val supportedSurfaceCombination = SupportedSurfaceCombination(
context, mockCameraMetadata, cameraId,
mockCamcorderProfileAdapter
)
val combinationList = getLevel3SupportedCombinationList()
for (combination in combinationList) {
val isSupported =
supportedSurfaceCombination.checkSupported(combination.surfaceConfigList)
Truth.assertThat(isSupported).isFalse()
}
}
@Test
fun checkLimitedSurfaceCombinationSupportedInRawDevice() {
setupCamera(
CameraCharacteristics.INFO_SUPPORTED_HARDWARE_LEVEL_FULL, intArrayOf(
CameraCharacteristics.REQUEST_AVAILABLE_CAPABILITIES_RAW
)
)
val supportedSurfaceCombination = SupportedSurfaceCombination(
context, mockCameraMetadata, cameraId,
mockCamcorderProfileAdapter
)
val combinationList = getLimitedSupportedCombinationList()
for (combination in combinationList) {
val isSupported =
supportedSurfaceCombination.checkSupported(combination.surfaceConfigList)
Truth.assertThat(isSupported).isTrue()
}
}
@Test
fun checkLegacySurfaceCombinationSupportedInRawDevice() {
setupCamera(
CameraCharacteristics.INFO_SUPPORTED_HARDWARE_LEVEL_FULL, intArrayOf(
CameraCharacteristics.REQUEST_AVAILABLE_CAPABILITIES_RAW
)
)
val supportedSurfaceCombination = SupportedSurfaceCombination(
context, mockCameraMetadata, cameraId,
mockCamcorderProfileAdapter
)
val combinationList = getLegacySupportedCombinationList()
for (combination in combinationList) {
val isSupported =
supportedSurfaceCombination.checkSupported(combination.surfaceConfigList)
Truth.assertThat(isSupported).isTrue()
}
}
@Test
fun checkFullSurfaceCombinationSupportedInRawDevice() {
setupCamera(
CameraCharacteristics.INFO_SUPPORTED_HARDWARE_LEVEL_FULL, intArrayOf(
CameraCharacteristics.REQUEST_AVAILABLE_CAPABILITIES_RAW
)
)
val supportedSurfaceCombination = SupportedSurfaceCombination(
context, mockCameraMetadata, cameraId,
mockCamcorderProfileAdapter
)
val combinationList = getFullSupportedCombinationList()
for (combination in combinationList) {
val isSupported =
supportedSurfaceCombination.checkSupported(combination.surfaceConfigList)
Truth.assertThat(isSupported).isTrue()
}
}
@Test
fun checkRawSurfaceCombinationSupportedInRawDevice() {
setupCamera(
CameraCharacteristics.INFO_SUPPORTED_HARDWARE_LEVEL_FULL, intArrayOf(
CameraCharacteristics.REQUEST_AVAILABLE_CAPABILITIES_RAW
)
)
val supportedSurfaceCombination = SupportedSurfaceCombination(
context, mockCameraMetadata, cameraId,
mockCamcorderProfileAdapter
)
val combinationList = getRAWSupportedCombinationList()
for (combination in combinationList) {
val isSupported =
supportedSurfaceCombination.checkSupported(combination.surfaceConfigList)
Truth.assertThat(isSupported).isTrue()
}
}
@Test
fun checkLevel3SurfaceCombinationSupportedInLevel3Device() {
setupCamera(CameraCharacteristics.INFO_SUPPORTED_HARDWARE_LEVEL_3)
val supportedSurfaceCombination = SupportedSurfaceCombination(
context, mockCameraMetadata, cameraId,
mockCamcorderProfileAdapter
)
val combinationList = getLevel3SupportedCombinationList()
for (combination in combinationList) {
val isSupported =
supportedSurfaceCombination.checkSupported(combination.surfaceConfigList)
Truth.assertThat(isSupported).isTrue()
}
}
@Test
fun checkLevel3SurfaceCombinationSubListSupportedInLevel3Device() {
setupCamera(CameraCharacteristics.INFO_SUPPORTED_HARDWARE_LEVEL_3)
val supportedSurfaceCombination = SupportedSurfaceCombination(
context, mockCameraMetadata, cameraId,
mockCamcorderProfileAdapter
)
val combinationList = getLevel3SupportedCombinationList()
val isSupported = isAllSubConfigListSupported(supportedSurfaceCombination, combinationList)
Truth.assertThat(isSupported).isTrue()
}
@Test
fun checkTargetAspectRatio() {
setupCamera(CameraCharacteristics.INFO_SUPPORTED_HARDWARE_LEVEL_LEGACY)
val supportedSurfaceCombination = SupportedSurfaceCombination(
context, mockCameraMetadata, cameraId,
mockCamcorderProfileAdapter
)
val fakeUseCase = FakeUseCaseConfig.Builder()
.setTargetAspectRatio(AspectRatio.RATIO_16_9)
.build()
val useCases: MutableList<UseCase> = ArrayList()
useCases.add(fakeUseCase)
val useCaseToConfigMap = Configs.useCaseConfigMapWithDefaultSettingsFromUseCaseList(
cameraFactory!!.getCamera(cameraId).cameraInfoInternal,
useCases,
useCaseConfigFactory
)
val suggestedResolutionMap = supportedSurfaceCombination.getSuggestedResolutions(
emptyList(),
ArrayList(useCaseToConfigMap.values)
)
val selectedSize = suggestedResolutionMap[useCaseToConfigMap[fakeUseCase]]!!
val resultAspectRatio = Rational(
selectedSize.width,
selectedSize.height
)
Truth.assertThat(resultAspectRatio).isEqualTo(aspectRatio169)
}
@Test
fun checkResolutionForMixedUseCase_AfterBindToLifecycle() {
setupCamera(CameraCharacteristics.INFO_SUPPORTED_HARDWARE_LEVEL_LEGACY)
// The test case make sure the selected result is expected after the regular flow.
val targetAspectRatio = aspectRatio169
val preview = Preview.Builder()
.setTargetAspectRatio(AspectRatio.RATIO_16_9)
.build()
preview.setSurfaceProvider(
CameraXExecutors.directExecutor(),
SurfaceTextureProvider.createSurfaceTextureProvider(
Mockito.mock(
SurfaceTextureCallback::class.java
)
)
)
val imageCapture = ImageCapture.Builder()
.setTargetAspectRatio(AspectRatio.RATIO_16_9)
.build()
val imageAnalysis = ImageAnalysis.Builder()
.setTargetAspectRatio(AspectRatio.RATIO_16_9)
.build()
val cameraUseCaseAdapter = CameraUtil
.createCameraUseCaseAdapter(
context,
CameraSelector.DEFAULT_BACK_CAMERA
)
cameraUseCaseAdapter.addUseCases(listOf(preview, imageCapture, imageAnalysis))
val previewResolution = preview.attachedSurfaceResolution!!
val previewRatio = Rational(
previewResolution.width,
previewResolution.height
)
val imageCaptureResolution = preview.attachedSurfaceResolution
val imageCaptureRatio = Rational(
imageCaptureResolution!!.width,
imageCaptureResolution.height
)
val imageAnalysisResolution = preview.attachedSurfaceResolution
val imageAnalysisRatio = Rational(
imageAnalysisResolution!!.width,
imageAnalysisResolution.height
)
// Checks no correction is needed.
Truth.assertThat(previewRatio).isEqualTo(targetAspectRatio)
Truth.assertThat(imageCaptureRatio).isEqualTo(targetAspectRatio)
Truth.assertThat(imageAnalysisRatio).isEqualTo(targetAspectRatio)
}
@Test
fun checkDefaultAspectRatioAndResolutionForMixedUseCase() {
setupCamera(CameraCharacteristics.INFO_SUPPORTED_HARDWARE_LEVEL_LIMITED)
val supportedSurfaceCombination = SupportedSurfaceCombination(
context, mockCameraMetadata, cameraId,
mockCamcorderProfileAdapter
)
val preview = Preview.Builder().build()
preview.setSurfaceProvider(
CameraXExecutors.directExecutor(),
SurfaceTextureProvider.createSurfaceTextureProvider(
Mockito.mock(
SurfaceTextureCallback::class.java
)
)
)
val imageCapture = ImageCapture.Builder().build()
val imageAnalysis = ImageAnalysis.Builder().build()
// Preview/ImageCapture/ImageAnalysis' default config settings that will be applied after
// bound to lifecycle. Calling bindToLifecycle here to make sure sizes matching to
// default aspect ratio will be selected.
val cameraUseCaseAdapter = CameraUtil.createCameraUseCaseAdapter(
context,
CameraSelector.DEFAULT_BACK_CAMERA
)
cameraUseCaseAdapter.addUseCases(
listOf(
preview,
imageCapture, imageAnalysis
)
)
val useCases: MutableList<UseCase> = ArrayList()
useCases.add(preview)
useCases.add(imageCapture)
useCases.add(imageAnalysis)
val useCaseToConfigMap = Configs.useCaseConfigMapWithDefaultSettingsFromUseCaseList(
cameraFactory!!.getCamera(cameraId).cameraInfoInternal,
useCases,
useCaseConfigFactory
)
val suggestedResolutionMap = supportedSurfaceCombination.getSuggestedResolutions(
emptyList(),
ArrayList(useCaseToConfigMap.values)
)
val previewSize = suggestedResolutionMap[useCaseToConfigMap[preview]]
val imageCaptureSize = suggestedResolutionMap[useCaseToConfigMap[imageCapture]]
val imageAnalysisSize = suggestedResolutionMap[useCaseToConfigMap[imageAnalysis]]
assert(previewSize != null)
val previewAspectRatio = Rational(
previewSize!!.width,
previewSize.height
)
assert(imageCaptureSize != null)
val imageCaptureAspectRatio = Rational(
imageCaptureSize!!.width,
imageCaptureSize.height
)
assert(imageAnalysisSize != null)
val imageAnalysisAspectRatio = Rational(
imageAnalysisSize!!.width,
imageAnalysisSize.height
)
// Checks the default aspect ratio.
Truth.assertThat(previewAspectRatio).isEqualTo(aspectRatio43)
Truth.assertThat(imageCaptureAspectRatio).isEqualTo(aspectRatio43)
Truth.assertThat(imageAnalysisAspectRatio).isEqualTo(aspectRatio43)
// Checks the default resolution.
Truth.assertThat(imageAnalysisSize).isEqualTo(vgaSize)
}
@Test
fun checkSmallSizesAreFilteredOutByDefaultSize480p() {
setupCamera(CameraCharacteristics.INFO_SUPPORTED_HARDWARE_LEVEL_LIMITED)
val supportedSurfaceCombination = SupportedSurfaceCombination(
context, mockCameraMetadata, cameraId,
mockCamcorderProfileAdapter
)
/* This test case is for b/139018208 that get small resolution 144x256 with below
conditions:
1. The target aspect ratio is set to the screen size 1080 x 2220 (9:18.5).
2. The camera doesn't provide any 9:18.5 resolution and the size 144x256(9:16)
is considered the 9:18.5 mod16 version.
3. There is no other bigger resolution matched the target aspect ratio.
*/
val displayWidth = 1080
val displayHeight = 2220
val preview = Preview.Builder()
.setTargetResolution(Size(displayHeight, displayWidth))
.build()
val useCases: MutableList<UseCase> = ArrayList()
useCases.add(preview)
val useCaseToConfigMap = Configs.useCaseConfigMapWithDefaultSettingsFromUseCaseList(
cameraFactory!!.getCamera(cameraId).cameraInfoInternal,
useCases,
useCaseConfigFactory
)
val suggestedResolutionMap = supportedSurfaceCombination.getSuggestedResolutions(
emptyList(),
ArrayList(useCaseToConfigMap.values)
)
// Checks the preconditions.
val preconditionSize = Size(256, 144)
val targetRatio = Rational(displayHeight, displayWidth)
val sizeList = ArrayList(listOf(*supportedSizes))
Truth.assertThat(sizeList).contains(preconditionSize)
for (s in supportedSizes) {
val supportedRational = Rational(s.width, s.height)
Truth.assertThat(supportedRational).isNotEqualTo(targetRatio)
}
// Checks the mechanism has filtered out the sizes which are smaller than default size
// 480p.
val previewSize = suggestedResolutionMap[useCaseToConfigMap[preview]]
Truth.assertThat(previewSize).isNotEqualTo(preconditionSize)
}
@Test
fun checkAspectRatioMatchedSizeCanBeSelected() {
setupCamera(CameraCharacteristics.INFO_SUPPORTED_HARDWARE_LEVEL_LIMITED)
val supportedSurfaceCombination = SupportedSurfaceCombination(
context, mockCameraMetadata, cameraId,
mockCamcorderProfileAdapter
)
// Sets each of mSupportedSizes as target resolution and also sets target rotation as
// Surface.ROTATION to make it aligns the sensor direction and then exactly the same size
// will be selected as the result. This test can also verify that size smaller than
// 640x480 can be selected after set as target resolution.
for (targetResolution in supportedSizes) {
val imageCapture = ImageCapture.Builder().setTargetResolution(
targetResolution
).setTargetRotation(Surface.ROTATION_90).build()
val suggestedResolutionMap = supportedSurfaceCombination.getSuggestedResolutions(
emptyList(),
listOf(imageCapture.currentConfig)
)
Truth.assertThat(targetResolution).isEqualTo(
suggestedResolutionMap[imageCapture.currentConfig]
)
}
}
@Test
fun checkCorrectAspectRatioNotMatchedSizeCanBeSelected() {
setupCamera(CameraCharacteristics.INFO_SUPPORTED_HARDWARE_LEVEL_LIMITED)
val supportedSurfaceCombination = SupportedSurfaceCombination(
context, mockCameraMetadata, cameraId,
mockCamcorderProfileAdapter
)
// Sets target resolution as 1280x640, all supported resolutions will be put into aspect
// ratio not matched list. Then, 1280x720 will be the nearest matched one. Finally,
// checks whether 1280x720 is selected or not.
val targetResolution = Size(1280, 640)
val imageCapture = ImageCapture.Builder().setTargetResolution(
targetResolution
).setTargetRotation(Surface.ROTATION_90).build()
val suggestedResolutionMap = supportedSurfaceCombination.getSuggestedResolutions(
emptyList(),
listOf(imageCapture.currentConfig)
)
Truth.assertThat(Size(1280, 720)).isEqualTo(
suggestedResolutionMap[imageCapture.currentConfig]
)
}
@Test
fun suggestedResolutionsForMixedUseCaseNotSupportedInLegacyDevice() {
setupCamera(CameraCharacteristics.INFO_SUPPORTED_HARDWARE_LEVEL_LEGACY)
val supportedSurfaceCombination = SupportedSurfaceCombination(
context, mockCameraMetadata, cameraId,
mockCamcorderProfileAdapter
)
val imageCapture = ImageCapture.Builder()
.setTargetAspectRatio(AspectRatio.RATIO_16_9)
.build()
val videoCapture = createVideoCapture()
val preview = Preview.Builder()
.setTargetAspectRatio(AspectRatio.RATIO_16_9)
.build()
val useCases: MutableList<UseCase> = ArrayList()
useCases.add(imageCapture)
useCases.add(videoCapture)
useCases.add(preview)
val useCaseToConfigMap = Configs.useCaseConfigMapWithDefaultSettingsFromUseCaseList(
cameraFactory!!.getCamera(cameraId).cameraInfoInternal,
useCases,
useCaseConfigFactory
)
assertThrows(IllegalArgumentException::class.java) {
supportedSurfaceCombination.getSuggestedResolutions(
emptyList(),
ArrayList(useCaseToConfigMap.values)
)
}
}
@Test
fun suggestedResolutionsForCustomizeResolutionsNotSupportedInLegacyDevice() {
setupCamera(CameraCharacteristics.INFO_SUPPORTED_HARDWARE_LEVEL_LEGACY)
val supportedSurfaceCombination = SupportedSurfaceCombination(
context, mockCameraMetadata, cameraId,
mockCamcorderProfileAdapter
)
// Legacy camera only support (PRIV, PREVIEW) + (PRIV, PREVIEW)
val quality = Quality.UHD
val previewResolutionsPairs = listOf(
Pair.create(ImageFormat.PRIVATE, arrayOf(previewSize))
)
val videoCapture = createVideoCapture(quality)
val preview = Preview.Builder()
.setSupportedResolutions(previewResolutionsPairs)
.build()
val useCases: MutableList<UseCase> = ArrayList()
useCases.add(videoCapture)
useCases.add(preview)
val useCaseToConfigMap = Configs.useCaseConfigMapWithDefaultSettingsFromUseCaseList(
cameraFactory!!.getCamera(cameraId).cameraInfoInternal,
useCases,
useCaseConfigFactory
)
assertThrows(IllegalArgumentException::class.java) {
supportedSurfaceCombination.getSuggestedResolutions(
emptyList(),
ArrayList(useCaseToConfigMap.values)
)
}
}
// (PRIV, PREVIEW) + (PRIV, RECORD) + (JPEG, RECORD)
@Test
fun suggestedResolutionsForMixedUseCaseInLimitedDevice() {
setupCamera(CameraCharacteristics.INFO_SUPPORTED_HARDWARE_LEVEL_LIMITED)
val supportedSurfaceCombination = SupportedSurfaceCombination(
context, mockCameraMetadata, cameraId,
mockCamcorderProfileAdapter
)
val imageCapture = ImageCapture.Builder()
.setTargetAspectRatio(AspectRatio.RATIO_16_9)
.build()
val videoCapture = createVideoCapture(Quality.HIGHEST)
val preview = Preview.Builder()
.setTargetAspectRatio(AspectRatio.RATIO_16_9)
.build()
val useCases: MutableList<UseCase> = ArrayList()
useCases.add(imageCapture)
useCases.add(videoCapture)
useCases.add(preview)
val useCaseToConfigMap = Configs.useCaseConfigMapWithDefaultSettingsFromUseCaseList(
cameraFactory!!.getCamera(cameraId).cameraInfoInternal,
useCases,
useCaseConfigFactory
)
val suggestedResolutionMap: Map<UseCaseConfig<*>, Size> =
supportedSurfaceCombination.getSuggestedResolutions(
emptyList(),
ArrayList(useCaseToConfigMap.values)
)
// (PRIV, PREVIEW) + (PRIV, RECORD) + (JPEG, RECORD)
Truth.assertThat(suggestedResolutionMap).containsEntry(
useCaseToConfigMap[imageCapture],
recordSize
)
Truth.assertThat(suggestedResolutionMap).containsEntry(
useCaseToConfigMap[videoCapture],
recordSize
)
Truth.assertThat(suggestedResolutionMap).containsEntry(
useCaseToConfigMap[preview],
previewSize
)
}
@Test
fun suggestedResolutionsInFullDevice_videoHasHigherPriorityThanImage() {
setupCamera(CameraCharacteristics.INFO_SUPPORTED_HARDWARE_LEVEL_FULL)
val supportedSurfaceCombination = SupportedSurfaceCombination(
context, mockCameraMetadata, cameraId,
mockCamcorderProfileAdapter
)
val imageCapture = ImageCapture.Builder()
.setTargetAspectRatio(AspectRatio.RATIO_16_9)
.build()
val videoCapture = createVideoCapture(
QualitySelector.from(
Quality.UHD,
FallbackStrategy.lowerQualityOrHigherThan(Quality.UHD)
)
)
val preview = Preview.Builder()
.setTargetAspectRatio(AspectRatio.RATIO_16_9)
.build()
val useCases: MutableList<UseCase> = ArrayList()
useCases.add(imageCapture)
useCases.add(videoCapture)
useCases.add(preview)
val useCaseToConfigMap = Configs.useCaseConfigMapWithDefaultSettingsFromUseCaseList(
cameraFactory!!.getCamera(cameraId).cameraInfoInternal,
useCases,
useCaseConfigFactory
)
val suggestedResolutionMap: Map<UseCaseConfig<*>, Size> =
supportedSurfaceCombination.getSuggestedResolutions(
emptyList(),
ArrayList(useCaseToConfigMap.values)
)
// There are two possible combinations in Full level device
// (PRIV, PREVIEW) + (PRIV, RECORD) + (JPEG, RECORD) => should be applied
// (PRIV, PREVIEW) + (PRIV, PREVIEW) + (JPEG, MAXIMUM)
Truth.assertThat(suggestedResolutionMap).containsEntry(
useCaseToConfigMap[imageCapture],
recordSize
)
Truth.assertThat(suggestedResolutionMap).containsEntry(
useCaseToConfigMap[videoCapture],
recordSize
)
Truth.assertThat(suggestedResolutionMap).containsEntry(
useCaseToConfigMap[preview],
previewSize
)
}
@Test
fun suggestedResInFullDevice_videoRecordSizeLowPriority_imageCanGetMaxSize() {
setupCamera(CameraCharacteristics.INFO_SUPPORTED_HARDWARE_LEVEL_FULL)
val supportedSurfaceCombination = SupportedSurfaceCombination(
context, mockCameraMetadata, cameraId,
mockCamcorderProfileAdapter
)
val imageCapture = ImageCapture.Builder()
.setTargetAspectRatio(AspectRatio.RATIO_4_3) // mMaximumSize(4032x3024) is 4:3
.build()
val videoCapture = createVideoCapture(
QualitySelector.fromOrderedList(
listOf(Quality.HD, Quality.FHD, Quality.UHD)
)
)
val preview = Preview.Builder()
.setTargetAspectRatio(AspectRatio.RATIO_16_9)
.build()
val useCases: MutableList<UseCase> = ArrayList()
useCases.add(imageCapture)
useCases.add(videoCapture)
useCases.add(preview)
val useCaseToConfigMap = Configs.useCaseConfigMapWithDefaultSettingsFromUseCaseList(
cameraFactory!!.getCamera(cameraId).cameraInfoInternal,
useCases,
useCaseConfigFactory
)
val suggestedResolutionMap: Map<UseCaseConfig<*>, Size> =
supportedSurfaceCombination.getSuggestedResolutions(
emptyList(),
ArrayList(useCaseToConfigMap.values)
)
// There are two possible combinations in Full level device
// (PRIV, PREVIEW) + (PRIV, RECORD) + (JPEG, RECORD)
// (PRIV, PREVIEW) + (PRIV, PREVIEW) + (JPEG, MAXIMUM) => should be applied
Truth.assertThat(suggestedResolutionMap).containsEntry(
useCaseToConfigMap[imageCapture],
maximumSize
)
Truth.assertThat(suggestedResolutionMap).containsEntry(
useCaseToConfigMap[videoCapture],
previewSize
) // Quality.HD
Truth.assertThat(suggestedResolutionMap).containsEntry(
useCaseToConfigMap[preview],
previewSize
)
}
@Test
fun suggestedResolutionsWithSameSupportedListForDifferentUseCases() {
setupCamera(CameraCharacteristics.INFO_SUPPORTED_HARDWARE_LEVEL_FULL)
val supportedSurfaceCombination = SupportedSurfaceCombination(
context, mockCameraMetadata, cameraId,
mockCamcorderProfileAdapter
)
/* This test case is for b/132603284 that divide by zero issue crash happened in below
conditions:
1. There are duplicated two 1280x720 supported sizes for ImageCapture and Preview.
2. supportedOutputSizes for ImageCapture and Preview in
SupportedSurfaceCombination#getAllPossibleSizeArrangements are the same.
*/
val imageCapture = ImageCapture.Builder()
.setTargetResolution(displaySize)
.build()
val preview = Preview.Builder()
.setTargetResolution(displaySize)
.build()
val imageAnalysis = ImageAnalysis.Builder()
.setTargetResolution(displaySize)
.build()
val useCases: MutableList<UseCase> = ArrayList()
useCases.add(imageCapture)
useCases.add(preview)
useCases.add(imageAnalysis)
val useCaseToConfigMap = Configs.useCaseConfigMapWithDefaultSettingsFromUseCaseList(
cameraFactory!!.getCamera(cameraId).cameraInfoInternal,
useCases,
useCaseConfigFactory
)
val suggestedResolutionMap: Map<UseCaseConfig<*>, Size> =
supportedSurfaceCombination.getSuggestedResolutions(
emptyList(),
ArrayList(useCaseToConfigMap.values)
)
Truth.assertThat(suggestedResolutionMap).containsEntry(
useCaseToConfigMap[imageCapture],
previewSize
)
Truth.assertThat(suggestedResolutionMap).containsEntry(
useCaseToConfigMap[preview],
previewSize
)
Truth.assertThat(suggestedResolutionMap).containsEntry(
useCaseToConfigMap[imageAnalysis],
previewSize
)
}
@Test
fun throwsWhenSetBothTargetResolutionAndAspectRatioForDifferentUseCases() {
setupCamera(CameraCharacteristics.INFO_SUPPORTED_HARDWARE_LEVEL_LEGACY)
var previewExceptionHappened = false
val previewBuilder = Preview.Builder()
.setTargetResolution(displaySize)
.setTargetAspectRatio(AspectRatio.RATIO_16_9)
try {
previewBuilder.build()
} catch (e: IllegalArgumentException) {
previewExceptionHappened = true
}
Truth.assertThat(previewExceptionHappened).isTrue()
var imageCaptureExceptionHappened = false
val imageCaptureConfigBuilder = ImageCapture.Builder()
.setTargetResolution(displaySize)
.setTargetAspectRatio(AspectRatio.RATIO_16_9)
try {
imageCaptureConfigBuilder.build()
} catch (e: IllegalArgumentException) {
imageCaptureExceptionHappened = true
}
Truth.assertThat(imageCaptureExceptionHappened).isTrue()
var imageAnalysisExceptionHappened = false
val imageAnalysisConfigBuilder = ImageAnalysis.Builder()
.setTargetResolution(displaySize)
.setTargetAspectRatio(AspectRatio.RATIO_16_9)
try {
imageAnalysisConfigBuilder.build()
} catch (e: IllegalArgumentException) {
imageAnalysisExceptionHappened = true
}
Truth.assertThat(imageAnalysisExceptionHappened).isTrue()
}
@Test
fun suggestedResolutionsForCustomizedSupportedResolutions() {
// Checks all suggested resolutions will become 640x480.
setupCamera(CameraCharacteristics.INFO_SUPPORTED_HARDWARE_LEVEL_LIMITED)
val supportedSurfaceCombination = SupportedSurfaceCombination(
context, mockCameraMetadata, cameraId,
mockCamcorderProfileAdapter
)
val formatResolutionsPairList: MutableList<Pair<Int, Array<Size>>> = ArrayList()
formatResolutionsPairList.add(Pair.create(ImageFormat.JPEG, arrayOf(vgaSize)))
formatResolutionsPairList.add(
Pair.create(ImageFormat.YUV_420_888, arrayOf(vgaSize))
)
formatResolutionsPairList.add(Pair.create(ImageFormat.PRIVATE, arrayOf(vgaSize)))
// Sets use cases customized supported resolutions to 640x480 only.
val imageCapture = ImageCapture.Builder()
.setSupportedResolutions(formatResolutionsPairList)
.build()
val videoCapture = createVideoCapture(Quality.SD)
val preview = Preview.Builder()
.setSupportedResolutions(formatResolutionsPairList)
.build()
val useCases: MutableList<UseCase> = ArrayList()
useCases.add(imageCapture)
useCases.add(videoCapture)
useCases.add(preview)
val useCaseToConfigMap = Configs.useCaseConfigMapWithDefaultSettingsFromUseCaseList(
cameraFactory!!.getCamera(cameraId).cameraInfoInternal,
useCases,
useCaseConfigFactory
)
val suggestedResolutionMap: Map<UseCaseConfig<*>, Size> =
supportedSurfaceCombination.getSuggestedResolutions(
emptyList(),
ArrayList(useCaseToConfigMap.values)
)
// Checks all suggested resolutions will become 640x480.
Truth.assertThat(suggestedResolutionMap).containsEntry(
useCaseToConfigMap[imageCapture],
vgaSize
)
Truth.assertThat(suggestedResolutionMap).containsEntry(
useCaseToConfigMap[videoCapture],
vgaSize
)
Truth.assertThat(suggestedResolutionMap).containsEntry(
useCaseToConfigMap[preview],
vgaSize
)
}
@Test
fun transformSurfaceConfigWithYUVAnalysisSize() {
setupCamera(CameraCharacteristics.INFO_SUPPORTED_HARDWARE_LEVEL_LEGACY)
val supportedSurfaceCombination = SupportedSurfaceCombination(
context, mockCameraMetadata, cameraId,
mockCamcorderProfileAdapter
)
val surfaceConfig = supportedSurfaceCombination.transformSurfaceConfig(
ImageFormat.YUV_420_888, vgaSize
)
val expectedSurfaceConfig =
SurfaceConfig.create(SurfaceConfig.ConfigType.YUV, SurfaceConfig.ConfigSize.VGA)
Truth.assertThat(surfaceConfig).isEqualTo(expectedSurfaceConfig)
}
@Test
fun transformSurfaceConfigWithYUVPreviewSize() {
setupCamera(CameraCharacteristics.INFO_SUPPORTED_HARDWARE_LEVEL_LEGACY)
val supportedSurfaceCombination = SupportedSurfaceCombination(
context, mockCameraMetadata, cameraId,
mockCamcorderProfileAdapter
)
val surfaceConfig = supportedSurfaceCombination.transformSurfaceConfig(
ImageFormat.YUV_420_888, previewSize
)
val expectedSurfaceConfig =
SurfaceConfig.create(SurfaceConfig.ConfigType.YUV, SurfaceConfig.ConfigSize.PREVIEW)
Truth.assertThat(surfaceConfig).isEqualTo(expectedSurfaceConfig)
}
@Test
fun transformSurfaceConfigWithYUVRecordSize() {
setupCamera(CameraCharacteristics.INFO_SUPPORTED_HARDWARE_LEVEL_LEGACY)
val supportedSurfaceCombination = SupportedSurfaceCombination(
context, mockCameraMetadata, cameraId,
mockCamcorderProfileAdapter
)
val surfaceConfig = supportedSurfaceCombination.transformSurfaceConfig(
ImageFormat.YUV_420_888, recordSize
)
val expectedSurfaceConfig =
SurfaceConfig.create(SurfaceConfig.ConfigType.YUV, SurfaceConfig.ConfigSize.RECORD)
Truth.assertThat(surfaceConfig).isEqualTo(expectedSurfaceConfig)
}
@Test
fun transformSurfaceConfigWithYUVMaximumSize() {
setupCamera(CameraCharacteristics.INFO_SUPPORTED_HARDWARE_LEVEL_LEGACY)
val supportedSurfaceCombination = SupportedSurfaceCombination(
context, mockCameraMetadata, cameraId,
mockCamcorderProfileAdapter
)
val surfaceConfig = supportedSurfaceCombination.transformSurfaceConfig(
ImageFormat.YUV_420_888, maximumSize
)
val expectedSurfaceConfig =
SurfaceConfig.create(SurfaceConfig.ConfigType.YUV, SurfaceConfig.ConfigSize.MAXIMUM)
Truth.assertThat(surfaceConfig).isEqualTo(expectedSurfaceConfig)
}
@Test
fun transformSurfaceConfigWithJPEGAnalysisSize() {
setupCamera(CameraCharacteristics.INFO_SUPPORTED_HARDWARE_LEVEL_LEGACY)
val supportedSurfaceCombination = SupportedSurfaceCombination(
context, mockCameraMetadata, cameraId,
mockCamcorderProfileAdapter
)
val surfaceConfig = supportedSurfaceCombination.transformSurfaceConfig(
ImageFormat.JPEG, vgaSize
)
val expectedSurfaceConfig =
SurfaceConfig.create(SurfaceConfig.ConfigType.JPEG, SurfaceConfig.ConfigSize.VGA)
Truth.assertThat(surfaceConfig).isEqualTo(expectedSurfaceConfig)
}
@Test
fun transformSurfaceConfigWithJPEGPreviewSize() {
setupCamera(CameraCharacteristics.INFO_SUPPORTED_HARDWARE_LEVEL_LEGACY)
val supportedSurfaceCombination = SupportedSurfaceCombination(
context, mockCameraMetadata, cameraId,
mockCamcorderProfileAdapter
)
val surfaceConfig = supportedSurfaceCombination.transformSurfaceConfig(
ImageFormat.JPEG, previewSize
)
val expectedSurfaceConfig =
SurfaceConfig.create(SurfaceConfig.ConfigType.JPEG, SurfaceConfig.ConfigSize.PREVIEW)
Truth.assertThat(surfaceConfig).isEqualTo(expectedSurfaceConfig)
}
@Test
fun transformSurfaceConfigWithJPEGRecordSize() {
setupCamera(CameraCharacteristics.INFO_SUPPORTED_HARDWARE_LEVEL_LEGACY)
val supportedSurfaceCombination = SupportedSurfaceCombination(
context, mockCameraMetadata, cameraId,
mockCamcorderProfileAdapter
)
val surfaceConfig = supportedSurfaceCombination.transformSurfaceConfig(
ImageFormat.JPEG, recordSize
)
val expectedSurfaceConfig =
SurfaceConfig.create(SurfaceConfig.ConfigType.JPEG, SurfaceConfig.ConfigSize.RECORD)
Truth.assertThat(surfaceConfig).isEqualTo(expectedSurfaceConfig)
}
@Test
fun transformSurfaceConfigWithJPEGMaximumSize() {
setupCamera(CameraCharacteristics.INFO_SUPPORTED_HARDWARE_LEVEL_LEGACY)
val supportedSurfaceCombination = SupportedSurfaceCombination(
context, mockCameraMetadata, cameraId,
mockCamcorderProfileAdapter
)
val surfaceConfig = supportedSurfaceCombination.transformSurfaceConfig(
ImageFormat.JPEG, maximumSize
)
val expectedSurfaceConfig =
SurfaceConfig.create(SurfaceConfig.ConfigType.JPEG, SurfaceConfig.ConfigSize.MAXIMUM)
Truth.assertThat(surfaceConfig).isEqualTo(expectedSurfaceConfig)
}
@Test
fun maximumSizeForImageFormat() {
setupCamera(CameraCharacteristics.INFO_SUPPORTED_HARDWARE_LEVEL_LEGACY)
val supportedSurfaceCombination = SupportedSurfaceCombination(
context, mockCameraMetadata, cameraId,
mockCamcorderProfileAdapter
)
val maximumYUVSize =
supportedSurfaceCombination.getMaxOutputSizeByFormat(ImageFormat.YUV_420_888)
Truth.assertThat(maximumYUVSize).isEqualTo(maximumSize)
val maximumJPEGSize =
supportedSurfaceCombination.getMaxOutputSizeByFormat(ImageFormat.JPEG)
Truth.assertThat(maximumJPEGSize).isEqualTo(maximumSize)
}
@Test
fun isAspectRatioMatchWithSupportedMod16Resolution() {
setupCamera(CameraCharacteristics.INFO_SUPPORTED_HARDWARE_LEVEL_LIMITED)
val supportedSurfaceCombination = SupportedSurfaceCombination(
context, mockCameraMetadata, cameraId,
mockCamcorderProfileAdapter
)
val preview = Preview.Builder()
.setTargetAspectRatio(AspectRatio.RATIO_16_9)
.setDefaultResolution(mod16Size)
.build()
val imageCapture = ImageCapture.Builder()
.setTargetAspectRatio(AspectRatio.RATIO_16_9)
.setDefaultResolution(mod16Size)
.build()
val useCases: MutableList<UseCase> = ArrayList()
useCases.add(preview)
useCases.add(imageCapture)
val useCaseToConfigMap = Configs.useCaseConfigMapWithDefaultSettingsFromUseCaseList(
cameraFactory!!.getCamera(cameraId).cameraInfoInternal,
useCases,
useCaseConfigFactory
)
val suggestedResolutionMap: Map<UseCaseConfig<*>, Size> =
supportedSurfaceCombination.getSuggestedResolutions(
emptyList(),
ArrayList(useCaseToConfigMap.values)
)
Truth.assertThat(suggestedResolutionMap).containsEntry(
useCaseToConfigMap[preview],
mod16Size
)
Truth.assertThat(suggestedResolutionMap).containsEntry(
useCaseToConfigMap[imageCapture],
mod16Size
)
}
@Test
fun sortByCompareSizesByArea_canSortSizesCorrectly() {
val sizes = arrayOfNulls<Size>(supportedSizes.size)
// Generates a unsorted array from mSupportedSizes.
val centerIndex = supportedSizes.size / 2
// Puts 2nd half sizes in the front
if (supportedSizes.size - centerIndex >= 0) {
System.arraycopy(
supportedSizes,
centerIndex, sizes, 0,
supportedSizes.size - centerIndex
)
}
// Puts 1st half sizes inversely in the tail
for (j in centerIndex - 1 downTo 0) {
sizes[supportedSizes.size - j - 1] = supportedSizes[j]
}
// The testing sizes array will be equal to mSupportedSizes after sorting.
Arrays.sort(sizes, CompareSizesByArea(true))
Truth.assertThat(listOf(*sizes)).isEqualTo(listOf(*supportedSizes))
}
@Test
fun supportedOutputSizes_noConfigSettings() {
setupCamera(CameraCharacteristics.INFO_SUPPORTED_HARDWARE_LEVEL_LIMITED)
val supportedSurfaceCombination = SupportedSurfaceCombination(
context, mockCameraMetadata, cameraId,
mockCamcorderProfileAdapter
)
val useCase = FakeUseCaseConfig.Builder().build()
// There is default minimum size 640x480 setting. Sizes smaller than 640x480 will be
// removed. No any aspect ratio related setting. The returned sizes list will be sorted in
// descending order.
val resultList: List<Size?> = supportedSurfaceCombination.getSupportedOutputSizes(
useCase.currentConfig
)
val expectedList = listOf(
Size(4032, 3024),
Size(3840, 2160),
Size(1920, 1440),
Size(1920, 1080),
Size(1280, 960),
Size(1280, 720),
Size(960, 544),
Size(800, 450),
Size(640, 480)
)
Truth.assertThat(resultList).isEqualTo(expectedList)
}
@Test
fun supportedOutputSizes_aspectRatio4x3() {
setupCamera(CameraCharacteristics.INFO_SUPPORTED_HARDWARE_LEVEL_LIMITED)
val supportedSurfaceCombination = SupportedSurfaceCombination(
context, mockCameraMetadata, cameraId,
mockCamcorderProfileAdapter
)
val useCase = FakeUseCaseConfig.Builder().setTargetAspectRatio(AspectRatio.RATIO_4_3)
.build()
// There is default minimum size 640x480 setting. Sizes smaller than 640x480 will be
// removed. Sizes of aspect ratio 4/3 will be in front of the returned sizes list and the
// list is sorted in descending order. Other items will be put in the following that are
// sorted by aspect ratio delta and then area size.
val resultList: List<Size?> = supportedSurfaceCombination.getSupportedOutputSizes(
useCase.currentConfig
)
val expectedList = listOf( // Matched AspectRatio items, sorted by area size.
Size(4032, 3024),
Size(1920, 1440),
Size(1280, 960),
Size(
640,
480
), // Mismatched AspectRatio items, sorted by aspect ratio delta then area size.
Size(3840, 2160),
Size(1920, 1080),
Size(1280, 720),
Size(960, 544),
Size(800, 450)
)
Truth.assertThat(resultList).isEqualTo(expectedList)
}
@Test
fun supportedOutputSizes_aspectRatio16x9() {
setupCamera(CameraCharacteristics.INFO_SUPPORTED_HARDWARE_LEVEL_LIMITED)
val supportedSurfaceCombination = SupportedSurfaceCombination(
context, mockCameraMetadata, cameraId,
mockCamcorderProfileAdapter
)
val useCase = FakeUseCaseConfig.Builder().setTargetAspectRatio(
AspectRatio.RATIO_16_9
).build()
// There is default minimum size 640x480 setting. Sizes smaller than 640x480 will be
// removed. Sizes of aspect ratio 16/9 will be in front of the returned sizes list and the
// list is sorted in descending order. Other items will be put in the following that are
// sorted by aspect ratio delta and then area size.
val resultList: List<Size?> = supportedSurfaceCombination.getSupportedOutputSizes(
useCase.currentConfig
)
val expectedList = listOf( // Matched AspectRatio items, sorted by area size.
Size(3840, 2160),
Size(1920, 1080),
Size(1280, 720),
Size(960, 544),
Size(
800,
450
), // Mismatched AspectRatio items, sorted by aspect ratio delta then area size.
Size(4032, 3024),
Size(1920, 1440),
Size(1280, 960),
Size(640, 480)
)
Truth.assertThat(resultList).isEqualTo(expectedList)
}
@Test
fun supportedOutputSizes_targetResolution1080x1920InRotation0() {
setupCamera(CameraCharacteristics.INFO_SUPPORTED_HARDWARE_LEVEL_LIMITED)
val supportedSurfaceCombination = SupportedSurfaceCombination(
context, mockCameraMetadata, cameraId,
mockCamcorderProfileAdapter
)
val useCase = FakeUseCaseConfig.Builder().setTargetResolution(
Size(1080, 1920)
).build()
// Unnecessary big enough sizes will be removed from the result list. There is default
// minimum size 640x480 setting. Sizes smaller than 640x480 will also be removed. The
// target resolution will be calibrated by default target rotation 0 degree. The
// auto-resolution mechanism will try to select the sizes which aspect ratio is nearest
// to the aspect ratio of target resolution in priority. Therefore, sizes of aspect ratio
// 16/9 will be in front of the returned sizes list and the list is sorted in descending
// order. Other items will be put in the following that are sorted by aspect ratio delta
// and then area size.
val resultList: List<Size?> = supportedSurfaceCombination.getSupportedOutputSizes(
useCase.currentConfig
)
val expectedList = listOf( // Matched AspectRatio items, sorted by area size.
Size(1920, 1080),
Size(1280, 720),
Size(960, 544),
Size(
800,
450
), // Mismatched AspectRatio items, sorted by aspect ratio delta then area size.
Size(1920, 1440),
Size(1280, 960),
Size(640, 480)
)
Truth.assertThat(resultList).isEqualTo(expectedList)
}
@Test
fun supportedOutputSizes_targetResolutionLargerThan640x480() {
setupCamera(CameraCharacteristics.INFO_SUPPORTED_HARDWARE_LEVEL_LIMITED)
val supportedSurfaceCombination = SupportedSurfaceCombination(
context, mockCameraMetadata, cameraId,
mockCamcorderProfileAdapter
)
val useCase = FakeUseCaseConfig.Builder().setTargetRotation(
Surface.ROTATION_90
).setTargetResolution(Size(1280, 960)).build()
// Unnecessary big enough sizes will be removed from the result list. There is default
// minimum size 640x480 setting. Target resolution larger than 640x480 won't overwrite
// minimum size setting. Sizes smaller than 640x480 will be removed. The auto-resolution
// mechanism will try to select the sizes which aspect ratio is nearest to the aspect
// ratio of target resolution in priority. Therefore, sizes of aspect ratio 4/3 will be
// in front of the returned sizes list and the list is sorted in descending order. Other
// items will be put in the following that are sorted by aspect ratio delta and then area
// size.
val resultList: List<Size?> = supportedSurfaceCombination.getSupportedOutputSizes(
useCase.currentConfig
)
val expectedList = listOf( // Matched AspectRatio items, sorted by area size.
Size(1280, 960),
Size(
640,
480
), // Mismatched AspectRatio items, sorted by aspect ratio delta then area size.
Size(1920, 1080),
Size(1280, 720),
Size(960, 544),
Size(800, 450)
)
Truth.assertThat(resultList).isEqualTo(expectedList)
}
@Test
fun supportedOutputSizes_targetResolutionSmallerThan640x480() {
setupCamera(CameraCharacteristics.INFO_SUPPORTED_HARDWARE_LEVEL_LIMITED)
val supportedSurfaceCombination = SupportedSurfaceCombination(
context, mockCameraMetadata, cameraId,
mockCamcorderProfileAdapter
)
val useCase = FakeUseCaseConfig.Builder().setTargetRotation(
Surface.ROTATION_90
).setTargetResolution(Size(320, 240)).build()
// Unnecessary big enough sizes will be removed from the result list. Minimum size will
// be overwritten as 320x240. Sizes smaller than 320x240 will also be removed. The
// auto-resolution mechanism will try to select the sizes which aspect ratio is nearest
// to the aspect ratio of target resolution in priority. Therefore, sizes of aspect ratio
// 4/3 will be in front of the returned sizes list and the list is sorted in descending
// order. Other items will be put in the following that are sorted by aspect ratio delta
// and then area size.
val resultList: List<Size?> = supportedSurfaceCombination.getSupportedOutputSizes(
useCase.currentConfig
)
val expectedList = listOf( // Matched AspectRatio items, sorted by area size.
Size(
320,
240
), // Mismatched AspectRatio items, sorted by aspect ratio delta then area size.
Size(800, 450)
)
Truth.assertThat(resultList).isEqualTo(expectedList)
}
@Test
fun supportedOutputSizes_targetResolution1800x1440NearTo4x3() {
setupCamera(CameraCharacteristics.INFO_SUPPORTED_HARDWARE_LEVEL_LIMITED)
val supportedSurfaceCombination = SupportedSurfaceCombination(
context, mockCameraMetadata, cameraId,
mockCamcorderProfileAdapter
)
val useCase = FakeUseCaseConfig.Builder().setTargetRotation(
Surface.ROTATION_90
).setTargetResolution(Size(1800, 1440)).build()
// Unnecessary big enough sizes will be removed from the result list. There is default
// minimum size 640x480 setting. Sizes smaller than 640x480 will also be removed. The
// auto-resolution mechanism will try to select the sizes which aspect ratio is nearest
// to the aspect ratio of target resolution in priority. Size 1800x1440 is near to 4/3
// therefore, sizes of aspect ratio 4/3 will be in front of the returned sizes list and
// the list is sorted in descending order.
val resultList: List<Size?> = supportedSurfaceCombination.getSupportedOutputSizes(
useCase.currentConfig
)
val expectedList = listOf( // Sizes of 4/3 are near to aspect ratio of 1800/1440
Size(1920, 1440),
Size(1280, 960),
Size(640, 480), // Sizes of 16/9 are far to aspect ratio of 1800/1440
Size(3840, 2160),
Size(1920, 1080),
Size(1280, 720),
Size(960, 544),
Size(800, 450)
)
Truth.assertThat(resultList).isEqualTo(expectedList)
}
@Test
fun supportedOutputSizes_targetResolution1280x600NearTo16x9() {
setupCamera(CameraCharacteristics.INFO_SUPPORTED_HARDWARE_LEVEL_LIMITED)
val supportedSurfaceCombination = SupportedSurfaceCombination(
context, mockCameraMetadata, cameraId,
mockCamcorderProfileAdapter
)
val useCase = FakeUseCaseConfig.Builder().setTargetResolution(
Size(1280, 600)
).setTargetRotation(Surface.ROTATION_90).build()
// Unnecessary big enough sizes will be removed from the result list. There is default
// minimum size 640x480 setting. Sizes smaller than 640x480 will also be removed. The
// auto-resolution mechanism will try to select the sizes which aspect ratio is nearest
// to the aspect ratio of target resolution in priority. Size 1280x600 is near to 16/9,
// therefore, sizes of aspect ratio 16/9 will be in front of the returned sizes list and
// the list is sorted in descending order.
val resultList: List<Size?> = supportedSurfaceCombination.getSupportedOutputSizes(
useCase.currentConfig
)
val expectedList = listOf( // Sizes of 16/9 are near to aspect ratio of 1280/600
Size(1280, 720),
Size(960, 544),
Size(800, 450), // Sizes of 4/3 are far to aspect ratio of 1280/600
Size(1280, 960),
Size(640, 480)
)
Truth.assertThat(resultList).isEqualTo(expectedList)
}
@Test
fun supportedOutputSizes_maxResolution1280x720() {
setupCamera(CameraCharacteristics.INFO_SUPPORTED_HARDWARE_LEVEL_LIMITED)
val supportedSurfaceCombination = SupportedSurfaceCombination(
context, mockCameraMetadata, cameraId,
mockCamcorderProfileAdapter
)
val useCase = FakeUseCaseConfig.Builder().setMaxResolution(Size(1280, 720)).build()
// There is default minimum size 640x480 setting. Sizes smaller than 640x480 or
// larger than 1280x720 will be removed. The returned sizes list will be sorted in
// descending order.
val resultList: List<Size?> = supportedSurfaceCombination.getSupportedOutputSizes(
useCase.currentConfig
)
val expectedList = listOf(
Size(1280, 720),
Size(960, 544),
Size(800, 450),
Size(640, 480)
)
Truth.assertThat(resultList).isEqualTo(expectedList)
}
@Test
fun supportedOutputSizes_setCustomOrderedResolutions() {
setupCamera(CameraCharacteristics.INFO_SUPPORTED_HARDWARE_LEVEL_LIMITED)
val supportedSurfaceCombination = SupportedSurfaceCombination(
context, mockCameraMetadata, cameraId,
mockCamcorderProfileAdapter
)
val customOrderedResolutions = listOf(
Size(640, 480),
Size(1280, 720),
Size(1920, 1080),
Size(3840, 2160),
)
val useCase = FakeUseCaseConfig.Builder()
.setCustomOrderedResolutions(customOrderedResolutions)
.setTargetResolution(Size(1280, 720))
.setMaxResolution(Size(1920, 1440))
.setDefaultResolution(Size(1280, 720))
.setSupportedResolutions(
listOf(
Pair.create(
ImageFormat.PRIVATE, arrayOf(
Size(800, 450),
Size(640, 480),
Size(320, 240),
)
)
)
).build()
// Custom ordered resolutions is fully respected, meaning it will not be sorted or filtered
// by other configurations such as max/default/target/supported resolutions.
val resultList: List<Size?> = supportedSurfaceCombination.getSupportedOutputSizes(
useCase.currentConfig
)
Truth.assertThat(resultList).containsExactlyElementsIn(customOrderedResolutions).inOrder()
}
@Test
fun supportedOutputSizes_defaultResolution1280x720_noTargetResolution() {
setupCamera(CameraCharacteristics.INFO_SUPPORTED_HARDWARE_LEVEL_LIMITED)
val supportedSurfaceCombination = SupportedSurfaceCombination(
context, mockCameraMetadata, cameraId,
mockCamcorderProfileAdapter
)
val useCase = FakeUseCaseConfig.Builder().setDefaultResolution(
Size(
1280,
720
)
).build()
// There is default minimum size 640x480 setting. Sizes smaller than 640x480 will be
// removed. If there is no target resolution setting, it will be overwritten by default
// resolution as 1280x720. Unnecessary big enough sizes will also be removed. The
// returned sizes list will be sorted in descending order.
val resultList: List<Size?> = supportedSurfaceCombination.getSupportedOutputSizes(
useCase.currentConfig
)
val expectedList = listOf(
Size(1280, 720),
Size(960, 544),
Size(800, 450),
Size(640, 480)
)
Truth.assertThat(resultList).isEqualTo(expectedList)
}
@Test
fun supportedOutputSizes_defaultResolution1280x720_targetResolution1920x1080() {
setupCamera(CameraCharacteristics.INFO_SUPPORTED_HARDWARE_LEVEL_LIMITED)
val supportedSurfaceCombination = SupportedSurfaceCombination(
context, mockCameraMetadata, cameraId,
mockCamcorderProfileAdapter
)
val useCase = FakeUseCaseConfig.Builder().setDefaultResolution(
Size(1280, 720)
).setTargetRotation(Surface.ROTATION_90).setTargetResolution(
Size(1920, 1080)
).build()
// There is default minimum size 640x480 setting. Sizes smaller than 640x480 will be
// removed. There is target resolution 1920x1080, it won't be overwritten by default
// resolution 1280x720. Unnecessary big enough sizes will also be removed. Sizes of
// aspect ratio 16/9 will be in front of the returned sizes list and the list is sorted
// in descending order. Other items will be put in the following that are sorted by
// aspect ratio delta and then area size.
val resultList: List<Size?> = supportedSurfaceCombination.getSupportedOutputSizes(
useCase.currentConfig
)
val expectedList = listOf( // Matched AspectRatio items, sorted by area size.
Size(1920, 1080),
Size(1280, 720),
Size(960, 544),
Size(
800,
450
), // Mismatched AspectRatio items, sorted by aspect ratio delta then area size.
Size(1920, 1440),
Size(1280, 960),
Size(640, 480)
)
Truth.assertThat(resultList).isEqualTo(expectedList)
}
@Test
fun supportedOutputSizes_fallbackToGuaranteedResolution_whenNotFulfillConditions() {
setupCamera(
CameraCharacteristics.INFO_SUPPORTED_HARDWARE_LEVEL_LIMITED, arrayOf(
Size(640, 480),
Size(320, 240),
Size(320, 180),
Size(256, 144)
)
)
val supportedSurfaceCombination = SupportedSurfaceCombination(
context, mockCameraMetadata, cameraId,
mockCamcorderProfileAdapter
)
val useCase = FakeUseCaseConfig.Builder().setTargetResolution(
Size(1920, 1080)
).setTargetRotation(Surface.ROTATION_90).build()
// There is default minimum size 640x480 setting. Sizes smaller than 640x480 will be
// removed. There is target resolution 1920x1080 (16:9). Even 640x480 does not match 16:9
// requirement, it will still be returned to use.
val resultList: List<Size?> = supportedSurfaceCombination.getSupportedOutputSizes(
useCase.currentConfig
)
val expectedList = listOf(Size(640, 480))
Truth.assertThat(resultList).isEqualTo(expectedList)
}
@Test
fun supportedOutputSizes_whenMaxSizeSmallerThanDefaultMiniSize() {
setupCamera(
CameraCharacteristics.INFO_SUPPORTED_HARDWARE_LEVEL_LIMITED, arrayOf(
Size(640, 480),
Size(320, 240),
Size(320, 180),
Size(256, 144)
)
)
val supportedSurfaceCombination = SupportedSurfaceCombination(
context, mockCameraMetadata, cameraId,
mockCamcorderProfileAdapter
)
val useCase = FakeUseCaseConfig.Builder().setMaxResolution(
Size(320, 240)
).build()
// There is default minimum size 640x480 setting. Originally, sizes smaller than 640x480
// will be removed. Due to maximal size bound is smaller than the default minimum size
// bound and it is also smaller than 640x480, the default minimum size bound will be
// ignored. Then, sizes equal to or smaller than 320x240 will be kept in the result list.
val resultList: List<Size?> = supportedSurfaceCombination.getSupportedOutputSizes(
useCase.currentConfig
)
val expectedList = listOf(
Size(320, 240),
Size(320, 180),
Size(256, 144)
)
Truth.assertThat(resultList).isEqualTo(expectedList)
}
@Test
fun supportedOutputSizes_whenMaxSizeSmallerThanSmallTargetResolution() {
setupCamera(
CameraCharacteristics.INFO_SUPPORTED_HARDWARE_LEVEL_LIMITED, arrayOf(
Size(640, 480),
Size(320, 240),
Size(320, 180),
Size(256, 144)
)
)
val supportedSurfaceCombination = SupportedSurfaceCombination(
context, mockCameraMetadata, cameraId,
mockCamcorderProfileAdapter
)
val useCase = FakeUseCaseConfig.Builder().setMaxResolution(
Size(320, 180)
).setTargetResolution(Size(320, 240)).setTargetRotation(
Surface.ROTATION_90
).build()
// The default minimum size 640x480 will be overwritten by the target resolution 320x240.
// Originally, sizes smaller than 320x240 will be removed. Due to maximal size bound is
// smaller than the minimum size bound and it is also smaller than 640x480, the minimum
// size bound will be ignored. Then, sizes equal to or smaller than 320x180 will be kept
// in the result list.
val resultList: List<Size?> = supportedSurfaceCombination.getSupportedOutputSizes(
useCase.currentConfig
)
val expectedList = listOf(
Size(320, 180),
Size(256, 144)
)
Truth.assertThat(resultList).isEqualTo(expectedList)
}
@Test
fun supportedOutputSizes_whenBothMaxAndTargetResolutionsSmallerThan640x480() {
setupCamera(
CameraCharacteristics.INFO_SUPPORTED_HARDWARE_LEVEL_LIMITED, arrayOf(
Size(640, 480),
Size(320, 240),
Size(320, 180),
Size(256, 144)
)
)
val supportedSurfaceCombination = SupportedSurfaceCombination(
context, mockCameraMetadata, cameraId,
mockCamcorderProfileAdapter
)
val useCase = FakeUseCaseConfig.Builder().setMaxResolution(
Size(320, 240)
).setTargetResolution(Size(320, 180)).setTargetRotation(
Surface.ROTATION_90
).build()
// The default minimum size 640x480 will be overwritten by the target resolution 320x180.
// Originally, sizes smaller than 320x180 will be removed. Due to maximal size bound is
// smaller than the minimum size bound and it is also smaller than 640x480, the minimum
// size bound will be ignored. Then, all sizes equal to or smaller than 320x320 will be
// kept in the result list.
val resultList: List<Size?> = supportedSurfaceCombination.getSupportedOutputSizes(
useCase.currentConfig
)
val expectedList = listOf(
Size(320, 180),
Size(256, 144),
Size(320, 240)
)
Truth.assertThat(resultList).isEqualTo(expectedList)
}
@Test
fun supportedOutputSizes_whenMaxSizeSmallerThanBigTargetResolution() {
setupCamera(CameraCharacteristics.INFO_SUPPORTED_HARDWARE_LEVEL_LIMITED)
val supportedSurfaceCombination = SupportedSurfaceCombination(
context, mockCameraMetadata, cameraId,
mockCamcorderProfileAdapter
)
val useCase = FakeUseCaseConfig.Builder().setMaxResolution(
Size(1920, 1080)
).setTargetResolution(Size(3840, 2160)).setTargetRotation(
Surface.ROTATION_90
).build()
// Because the target size 3840x2160 is larger than 640x480, it won't overwrite the
// default minimum size 640x480. Sizes smaller than 640x480 will be removed. The
// auto-resolution mechanism will try to select the sizes which aspect ratio is nearest
// to the aspect ratio of target resolution in priority. Therefore, sizes of aspect ratio
// 16/9 will be in front of the returned sizes list and the list is sorted in descending
// order. Other items will be put in the following that are sorted by aspect ratio delta
// and then area size.
val resultList: List<Size?> = supportedSurfaceCombination.getSupportedOutputSizes(
useCase.currentConfig
)
val expectedList = listOf( // Matched AspectRatio items, sorted by area size.
Size(1920, 1080),
Size(1280, 720),
Size(960, 544),
Size(
800,
450
), // Mismatched AspectRatio items, sorted by aspect ratio delta then area size.
Size(1280, 960),
Size(640, 480)
)
Truth.assertThat(resultList).isEqualTo(expectedList)
}
@Test
fun supportedOutputSizes_whenNoSizeBetweenMaxSizeAndTargetResolution() {
setupCamera(
CameraCharacteristics.INFO_SUPPORTED_HARDWARE_LEVEL_LIMITED, arrayOf(
Size(640, 480),
Size(320, 240),
Size(320, 180),
Size(256, 144)
)
)
val supportedSurfaceCombination = SupportedSurfaceCombination(
context, mockCameraMetadata, cameraId,
mockCamcorderProfileAdapter
)
val useCase = FakeUseCaseConfig.Builder().setMaxResolution(
Size(320, 200)
).setTargetResolution(Size(320, 190)).setTargetRotation(
Surface.ROTATION_90
).build()
// The default minimum size 640x480 will be overwritten by the target resolution 320x190.
// Originally, sizes smaller than 320x190 will be removed. Due to there is no available
// size between the maximal size and the minimum size bound and the maximal size is
// smaller than 640x480, the default minimum size bound will be ignored. Then, sizes
// equal to or smaller than 320x200 will be kept in the result list.
val resultList: List<Size?> = supportedSurfaceCombination.getSupportedOutputSizes(
useCase.currentConfig
)
val expectedList = listOf(
Size(320, 180),
Size(256, 144)
)
Truth.assertThat(resultList).isEqualTo(expectedList)
}
@Test
fun supportedOutputSizes_whenTargetResolutionSmallerThanAnySize() {
setupCamera(
CameraCharacteristics.INFO_SUPPORTED_HARDWARE_LEVEL_LIMITED, arrayOf(
Size(640, 480),
Size(320, 240),
Size(320, 180),
Size(256, 144)
)
)
val supportedSurfaceCombination = SupportedSurfaceCombination(
context, mockCameraMetadata, cameraId,
mockCamcorderProfileAdapter
)
val useCase = FakeUseCaseConfig.Builder().setTargetResolution(
Size(192, 144)
).setTargetRotation(Surface.ROTATION_90).build()
// The default minimum size 640x480 will be overwritten by the target resolution 192x144.
// Because 192x144 is smaller than any size in the supported list, no one will be
// filtered out by it. The result list will only keep one big enough size of aspect ratio
// 4:3 and 16:9.
val resultList: List<Size?> = supportedSurfaceCombination.getSupportedOutputSizes(
useCase.currentConfig
)
val expectedList = listOf(
Size(320, 240),
Size(256, 144)
)
Truth.assertThat(resultList).isEqualTo(expectedList)
}
@Test
fun supportedOutputSizes_whenMaxResolutionSmallerThanAnySize() {
setupCamera(
CameraCharacteristics.INFO_SUPPORTED_HARDWARE_LEVEL_LEGACY, arrayOf(
Size(640, 480),
Size(320, 240),
Size(320, 180),
Size(256, 144)
)
)
val supportedSurfaceCombination = SupportedSurfaceCombination(
context, mockCameraMetadata, cameraId,
mockCamcorderProfileAdapter
)
val useCase = FakeUseCaseConfig.Builder().setMaxResolution(
Size(192, 144)
).build()
// All sizes will be filtered out by the max resolution 192x144 setting and an
// IllegalArgumentException will be thrown.
assertThrows(IllegalArgumentException::class.java) {
supportedSurfaceCombination.getSupportedOutputSizes(useCase.currentConfig)
}
}
@Test
fun supportedOutputSizes_whenMod16IsIgnoredForSmallSizes() {
setupCamera(
CameraCharacteristics.INFO_SUPPORTED_HARDWARE_LEVEL_LIMITED, arrayOf(
Size(640, 480),
Size(320, 240),
Size(320, 180),
Size(296, 144),
Size(256, 144)
)
)
val supportedSurfaceCombination = SupportedSurfaceCombination(
context, mockCameraMetadata, cameraId,
mockCamcorderProfileAdapter
)
val useCase = FakeUseCaseConfig.Builder().setTargetResolution(
Size(185, 90)
).setTargetRotation(Surface.ROTATION_90).build()
// The default minimum size 640x480 will be overwritten by the target resolution 185x90
// (18.5:9). If mod 16 calculation is not ignored for the sizes smaller than 640x480, the
// size 256x144 will be considered to match 18.5:9 and then become the first item in the
// result list. After ignoring mod 16 calculation for small sizes, 256x144 will still be
// kept as a 16:9 resolution as the result.
val resultList: List<Size?> = supportedSurfaceCombination.getSupportedOutputSizes(
useCase.currentConfig
)
val expectedList = listOf(
Size(296, 144),
Size(256, 144),
Size(320, 240)
)
Truth.assertThat(resultList).isEqualTo(expectedList)
}
@Test
fun supportedOutputSizes_whenOneMod16SizeClosestToTargetResolution() {
setupCamera(
CameraCharacteristics.INFO_SUPPORTED_HARDWARE_LEVEL_LEGACY, arrayOf(
Size(1920, 1080),
Size(1440, 1080),
Size(1280, 960),
Size(1280, 720),
Size(864, 480), // This is a 16:9 mod16 size that is closest to 2016x1080
Size(768, 432),
Size(640, 480),
Size(640, 360),
Size(480, 360),
Size(384, 288)
)
)
val supportedSurfaceCombination = SupportedSurfaceCombination(
context, mockCameraMetadata, cameraId,
mockCamcorderProfileAdapter
)
val useCase = FakeUseCaseConfig.Builder().setTargetResolution(
Size(1080, 2016)
).build()
val resultList: List<Size?> = supportedSurfaceCombination.getSupportedOutputSizes(
useCase.currentConfig
)
val expectedList = listOf(
Size(1920, 1080),
Size(1280, 720),
Size(864, 480),
Size(768, 432),
Size(1440, 1080),
Size(1280, 960),
Size(640, 480)
)
Truth.assertThat(resultList).isEqualTo(expectedList)
}
@Test
fun supportedOutputSizesWithPortraitPixelArraySize_aspectRatio16x9() {
val supportedSizes = arrayOf(
Size(1080, 1920),
Size(1080, 1440),
Size(960, 1280),
Size(720, 1280),
Size(1280, 720),
Size(480, 640),
Size(640, 480),
Size(360, 480)
)
// Sets the sensor orientation as 0 and pixel array size as a portrait size to simulate a
// phone device which majorly supports portrait output sizes.
setupCamera(
CameraCharacteristics.INFO_SUPPORTED_HARDWARE_LEVEL_LIMITED,
sensorOrientation0, portraitPixelArraySize, supportedSizes, null
)
val supportedSurfaceCombination = SupportedSurfaceCombination(
context, mockCameraMetadata, cameraId,
mockCamcorderProfileAdapter
)
val useCase = FakeUseCaseConfig.Builder().setTargetAspectRatio(
AspectRatio.RATIO_16_9
).build()
// There is default minimum size 640x480 setting. Sizes smaller than 640x480 will be
// removed. Due to the pixel array size is portrait, sizes of aspect ratio 9/16 will be in
// front of the returned sizes list and the list is sorted in descending order. Other
// items will be put in the following that are sorted by aspect ratio delta and then area
// size.
val resultList: List<Size?> = supportedSurfaceCombination.getSupportedOutputSizes(
useCase.currentConfig
)
val expectedList = listOf( // Matched AspectRatio items, sorted by area size.
Size(1080, 1920),
Size(
720,
1280
), // Mismatched AspectRatio items, sorted by aspect ratio delta then area size.
Size(1080, 1440),
Size(960, 1280),
Size(480, 640),
Size(640, 480),
Size(1280, 720)
)
Truth.assertThat(resultList).isEqualTo(expectedList)
}
@Test
fun supportedOutputSizesOnTabletWithPortraitPixelArraySize_aspectRatio16x9() {
val supportedSizes = arrayOf(
Size(1080, 1920),
Size(1080, 1440),
Size(960, 1280),
Size(720, 1280),
Size(1280, 720),
Size(480, 640),
Size(640, 480),
Size(360, 480)
)
// Sets the sensor orientation as 90 and pixel array size as a portrait size to simulate a
// tablet device which majorly supports portrait output sizes.
setupCamera(
CameraCharacteristics.INFO_SUPPORTED_HARDWARE_LEVEL_LIMITED,
sensorOrientation90, portraitPixelArraySize, supportedSizes, null
)
val supportedSurfaceCombination = SupportedSurfaceCombination(
context, mockCameraMetadata, cameraId,
mockCamcorderProfileAdapter
)
val useCase = FakeUseCaseConfig.Builder().setTargetAspectRatio(
AspectRatio.RATIO_16_9
).build()
// There is default minimum size 640x480 setting. Sizes smaller than 640x480 will be
// removed. Due to the pixel array size is portrait, sizes of aspect ratio 9/16 will be in
// front of the returned sizes list and the list is sorted in descending order. Other
// items will be put in the following that are sorted by aspect ratio delta and then area
// size.
val resultList: List<Size?> = supportedSurfaceCombination.getSupportedOutputSizes(
useCase.currentConfig
)
val expectedList = listOf( // Matched AspectRatio items, sorted by area size.
Size(1080, 1920),
Size(
720,
1280
), // Mismatched AspectRatio items, sorted by aspect ratio delta then area size.
Size(1080, 1440),
Size(960, 1280),
Size(480, 640),
Size(640, 480),
Size(1280, 720)
)
Truth.assertThat(resultList).isEqualTo(expectedList)
}
@Test
fun supportedOutputSizesOnTablet_aspectRatio16x9() {
setupCamera(
CameraCharacteristics.INFO_SUPPORTED_HARDWARE_LEVEL_LIMITED,
sensorOrientation0, landscapePixelArraySize, supportedSizes, null
)
val supportedSurfaceCombination = SupportedSurfaceCombination(
context, mockCameraMetadata, cameraId,
mockCamcorderProfileAdapter
)
val useCase = FakeUseCaseConfig.Builder().setTargetAspectRatio(
AspectRatio.RATIO_16_9
).build()
// There is default minimum size 640x480 setting. Sizes smaller than 640x480 will be
// removed. Sizes of aspect ratio 16/9 will be in front of the returned sizes list and the
// list is sorted in descending order. Other items will be put in the following that are
// sorted by aspect ratio delta and then area size.
val resultList: List<Size?> = supportedSurfaceCombination.getSupportedOutputSizes(
useCase.currentConfig
)
val expectedList = listOf( // Matched AspectRatio items, sorted by area size.
Size(3840, 2160),
Size(1920, 1080),
Size(1280, 720),
Size(960, 544),
Size(
800,
450
), // Mismatched AspectRatio items, sorted by aspect ratio delta then area size.
Size(4032, 3024),
Size(1920, 1440),
Size(1280, 960),
Size(640, 480)
)
Truth.assertThat(resultList).isEqualTo(expectedList)
}
@Test
fun supportedOutputSizesOnTabletWithPortraitSizes_aspectRatio16x9() {
val supportedSizes = arrayOf(
Size(1920, 1080),
Size(1440, 1080),
Size(1280, 960),
Size(1280, 720),
Size(720, 1280),
Size(640, 480),
Size(480, 640),
Size(480, 360)
)
setupCamera(
CameraCharacteristics.INFO_SUPPORTED_HARDWARE_LEVEL_LIMITED,
sensorOrientation0, landscapePixelArraySize, supportedSizes, null
)
val supportedSurfaceCombination = SupportedSurfaceCombination(
context, mockCameraMetadata, cameraId,
mockCamcorderProfileAdapter
)
val useCase = FakeUseCaseConfig.Builder().setTargetAspectRatio(
AspectRatio.RATIO_16_9
).build()
// There is default minimum size 640x480 setting. Sizes smaller than 640x480 will be
// removed. Sizes of aspect ratio 16/9 will be in front of the returned sizes list and the
// list is sorted in descending order. Other items will be put in the following that are
// sorted by aspect ratio delta and then area size.
val resultList: List<Size?> = supportedSurfaceCombination.getSupportedOutputSizes(
useCase.currentConfig
)
val expectedList = listOf( // Matched AspectRatio items, sorted by area size.
Size(1920, 1080),
Size(
1280,
720
), // Mismatched AspectRatio items, sorted by aspect ratio delta then area size.
Size(1440, 1080),
Size(1280, 960),
Size(640, 480),
Size(480, 640),
Size(720, 1280)
)
Truth.assertThat(resultList).isEqualTo(expectedList)
}
@Test
fun determineRecordSizeFromStreamConfigurationMap() {
// Setup camera with non-integer camera Id
setupCamera(
cameraIdExternal, CameraCharacteristics.INFO_SUPPORTED_HARDWARE_LEVEL_LEGACY,
sensorOrientation90, landscapePixelArraySize, supportedSizes, null
)
val supportedSurfaceCombination = SupportedSurfaceCombination(
context, mockCameraMetadata, cameraIdExternal,
mockCamcorderProfileAdapter
)
// Checks the determined RECORD size
Truth.assertThat(
supportedSurfaceCombination.surfaceSizeDefinition.recordSize
).isEqualTo(
legacyVideoMaximumVideoSize
)
}
@Test
fun canGet640x480_whenAnotherGroupMatchedInMod16Exists() {
val supportedSizes = arrayOf(
Size(4000, 3000),
Size(3840, 2160),
Size(1920, 1080),
Size(1024, 738), // This will create a 512/269 aspect ratio group that
// 640x480 will be considered to match in mod16 condition.
Size(800, 600),
Size(640, 480),
Size(320, 240)
)
setupCamera(
CameraCharacteristics.INFO_SUPPORTED_HARDWARE_LEVEL_LIMITED,
sensorOrientation90, landscapePixelArraySize, supportedSizes, null
)
val supportedSurfaceCombination = SupportedSurfaceCombination(
context, mockCameraMetadata, cameraId,
mockCamcorderProfileAdapter
)
// Sets the target resolution as 640x480 with target rotation as ROTATION_90 because the
// sensor orientation is 90.
val useCase = FakeUseCaseConfig.Builder().setTargetResolution(
vgaSize
).setTargetRotation(Surface.ROTATION_90).build()
val suggestedResolutionMap = supportedSurfaceCombination.getSuggestedResolutions(
emptyList(),
listOf(useCase.currentConfig)
)
// Checks 640x480 is final selected for the use case.
Truth.assertThat(suggestedResolutionMap[useCase.currentConfig]).isEqualTo(vgaSize)
}
@Test
fun canGetSupportedSizeSmallerThan640x480_whenLargerMaxResolutionIsSet() {
val supportedSizes = arrayOf(
Size(480, 480)
)
setupCamera(
CameraCharacteristics.INFO_SUPPORTED_HARDWARE_LEVEL_LIMITED,
sensorOrientation90, landscapePixelArraySize, supportedSizes, null
)
val supportedSurfaceCombination = SupportedSurfaceCombination(
context, mockCameraMetadata, cameraId,
mockCamcorderProfileAdapter
)
// Sets the max resolution as 720x1280
val useCase = FakeUseCaseConfig.Builder().setMaxResolution(displaySize).build()
val suggestedResolutionMap = supportedSurfaceCombination.getSuggestedResolutions(
emptyList(),
listOf(useCase.currentConfig)
)
// Checks 480x480 is final selected for the use case.
Truth.assertThat(suggestedResolutionMap[useCase.currentConfig]).isEqualTo(
Size(480, 480)
)
}
@Test
fun previewSizeIsSelectedForImageAnalysis_imageCaptureHasNoSetSizeInLimitedDevice() {
setupCamera(CameraCharacteristics.INFO_SUPPORTED_HARDWARE_LEVEL_LIMITED)
val supportedSurfaceCombination = SupportedSurfaceCombination(
context, mockCameraMetadata, cameraId,
mockCamcorderProfileAdapter
)
val preview = Preview.Builder().build()
preview.setSurfaceProvider(
CameraXExecutors.directExecutor(),
SurfaceTextureProvider.createSurfaceTextureProvider(
Mockito.mock(
SurfaceTextureCallback::class.java
)
)
)
// ImageCapture has no explicit target resolution setting
val imageCapture = ImageCapture.Builder().build()
// A LEGACY-level above device supports the following configuration.
// PRIV/PREVIEW + YUV/PREVIEW + JPEG/MAXIMUM
//
// A LIMITED-level above device supports the following configuration.
// PRIV/PREVIEW + YUV/RECORD + JPEG/RECORD
//
// Even there is a RECORD size target resolution setting for ImageAnalysis, ImageCapture
// will still have higher priority to have a MAXIMUM size resolution if the app doesn't
// explicitly specify a RECORD size target resolution to ImageCapture.
val imageAnalysis = ImageAnalysis.Builder()
.setTargetRotation(Surface.ROTATION_90)
.setTargetResolution(recordSize)
.build()
val useCases: MutableList<UseCase> = ArrayList()
useCases.add(preview)
useCases.add(imageCapture)
useCases.add(imageAnalysis)
val useCaseToConfigMap = Configs.useCaseConfigMapWithDefaultSettingsFromUseCaseList(
cameraFactory!!.getCamera(cameraId).cameraInfoInternal,
useCases,
useCaseConfigFactory
)
val suggestedResolutionMap = supportedSurfaceCombination.getSuggestedResolutions(
emptyList(),
ArrayList(useCaseToConfigMap.values)
)
Truth.assertThat(suggestedResolutionMap[useCaseToConfigMap[imageAnalysis]]).isEqualTo(
previewSize
)
}
@Test
fun recordSizeIsSelectedForImageAnalysis_imageCaptureHasExplicitSizeInLimitedDevice() {
setupCamera(CameraCharacteristics.INFO_SUPPORTED_HARDWARE_LEVEL_LIMITED)
val supportedSurfaceCombination = SupportedSurfaceCombination(
context, mockCameraMetadata, cameraId,
mockCamcorderProfileAdapter
)
val preview = Preview.Builder().build()
preview.setSurfaceProvider(
CameraXExecutors.directExecutor(),
SurfaceTextureProvider.createSurfaceTextureProvider(
Mockito.mock(
SurfaceTextureCallback::class.java
)
)
)
// ImageCapture has no explicit RECORD size target resolution setting
val imageCapture = ImageCapture.Builder()
.setTargetRotation(Surface.ROTATION_90)
.setTargetResolution(recordSize)
.build()
// A LEGACY-level above device supports the following configuration.
// PRIV/PREVIEW + YUV/PREVIEW + JPEG/MAXIMUM
//
// A LIMITED-level above device supports the following configuration.
// PRIV/PREVIEW + YUV/RECORD + JPEG/RECORD
//
// A RECORD can be selected for ImageAnalysis if the ImageCapture has a explicit RECORD
// size target resolution setting. It means that the application know the trade-off and
// the ImageAnalysis has higher priority to get a larger resolution than ImageCapture.
val imageAnalysis = ImageAnalysis.Builder()
.setTargetRotation(Surface.ROTATION_90)
.setTargetResolution(recordSize)
.build()
val useCases: MutableList<UseCase> = ArrayList()
useCases.add(preview)
useCases.add(imageCapture)
useCases.add(imageAnalysis)
val useCaseToConfigMap = Configs.useCaseConfigMapWithDefaultSettingsFromUseCaseList(
cameraFactory!!.getCamera(cameraId).cameraInfoInternal,
useCases,
useCaseConfigFactory
)
val suggestedResolutionMap = supportedSurfaceCombination.getSuggestedResolutions(
emptyList(),
ArrayList(useCaseToConfigMap.values)
)
Truth.assertThat(suggestedResolutionMap[useCaseToConfigMap[imageAnalysis]]).isEqualTo(
recordSize
)
}
private fun setupCamera(hardwareLevel: Int, capabilities: IntArray) {
setupCamera(
hardwareLevel, sensorOrientation90, landscapePixelArraySize,
supportedSizes, capabilities
)
}
private fun setupCamera(hardwareLevel: Int, supportedSizes: Array<Size>) {
setupCamera(
hardwareLevel, sensorOrientation90, landscapePixelArraySize,
supportedSizes, null
)
}
private fun setupCamera(
hardwareLevel: Int,
sensorOrientation: Int = sensorOrientation90,
pixelArraySize: Size = landscapePixelArraySize,
supportedSizes: Array<Size> =
this.supportedSizes,
capabilities: IntArray? = null
) {
setupCamera(
cameraId,
hardwareLevel,
sensorOrientation,
pixelArraySize,
supportedSizes,
capabilities
)
}
private fun setupCamera(
cameraId: String,
hardwareLevel: Int,
sensorOrientation: Int,
pixelArraySize: Size,
supportedSizes: Array<Size>,
capabilities: IntArray?
) {
cameraFactory = FakeCameraFactory()
val characteristics = ShadowCameraCharacteristics.newCameraCharacteristics()
val shadowCharacteristics = Shadow.extract<ShadowCameraCharacteristics>(characteristics)
shadowCharacteristics.set(
CameraCharacteristics.LENS_FACING, CameraCharacteristics.LENS_FACING_BACK
)
shadowCharacteristics.set(
CameraCharacteristics.INFO_SUPPORTED_HARDWARE_LEVEL, hardwareLevel
)
shadowCharacteristics.set(CameraCharacteristics.SENSOR_ORIENTATION, sensorOrientation)
shadowCharacteristics.set(
CameraCharacteristics.SENSOR_INFO_PIXEL_ARRAY_SIZE,
pixelArraySize
)
if (capabilities != null) {
shadowCharacteristics.set(
CameraCharacteristics.REQUEST_AVAILABLE_CAPABILITIES, capabilities
)
}
val cameraManager = ApplicationProvider.getApplicationContext<Context>()
.getSystemService(Context.CAMERA_SERVICE) as CameraManager
(Shadow.extract<Any>(cameraManager) as ShadowCameraManager)
.addCamera(cameraId, characteristics)
val mockMap = Mockito.mock(
StreamConfigurationMap::class.java
)
Mockito.`when`(mockMap.getOutputSizes(ArgumentMatchers.anyInt())).thenReturn(supportedSizes)
// ImageFormat.PRIVATE was supported since API level 23. Before that, the supported
// output sizes need to be retrieved via SurfaceTexture.class.
Mockito.`when`(
mockMap.getOutputSizes(
SurfaceTexture::class.java
)
).thenReturn(supportedSizes)
// This is setup for the test to determine RECORD size from StreamConfigurationMap
Mockito.`when`(
mockMap.getOutputSizes(
MediaRecorder::class.java
)
).thenReturn(supportedSizes)
shadowCharacteristics.set(CameraCharacteristics.SCALER_STREAM_CONFIGURATION_MAP, mockMap)
@LensFacing val lensFacingEnum = CameraUtil.getLensFacingEnumFromInt(
CameraCharacteristics.LENS_FACING_BACK
)
val cameraInfo = FakeCameraInfoInternal(cameraId)
cameraInfo.camcorderProfileProvider = FakeCamcorderProfileProvider.Builder()
.addProfile(
CamcorderProfileUtil.asHighQuality(profileUhd),
profileUhd,
profileFhd,
profileHd,
profileSd,
CamcorderProfileUtil.asLowQuality(profileSd)
).build()
cameraFactory!!.insertCamera(
lensFacingEnum, cameraId
) { FakeCamera(cameraId, null, cameraInfo) }
// set up CameraMetaData
Mockito.`when`(
mockCameraMetadata[CameraCharacteristics.INFO_SUPPORTED_HARDWARE_LEVEL]
).thenReturn(hardwareLevel)
Mockito.`when`(mockCameraMetadata[CameraCharacteristics.SENSOR_ORIENTATION])
.thenReturn(
sensorOrientation
)
Mockito.`when`(
mockCameraMetadata[CameraCharacteristics.SENSOR_INFO_PIXEL_ARRAY_SIZE]
).thenReturn(pixelArraySize)
Mockito.`when`(mockCameraMetadata[CameraCharacteristics.LENS_FACING]).thenReturn(
CameraCharacteristics.LENS_FACING_BACK
)
Mockito.`when`(
mockCameraMetadata[CameraCharacteristics.REQUEST_AVAILABLE_CAPABILITIES]
).thenReturn(capabilities)
Mockito.`when`(
mockCameraMetadata[CameraCharacteristics.SCALER_STREAM_CONFIGURATION_MAP]
).thenReturn(mockMap)
initCameraX(cameraId)
}
private fun initCameraX(cameraId: String) {
val cameraMetaDataMap = mutableMapOf<CameraId, CameraMetadata>()
cameraMetaDataMap[CameraId(cameraId)] = mockCameraMetadata
val cameraDevicesWithCameraMetaData =
FakeCameraDevicesWithCameraMetaData(cameraMetaDataMap, mockCameraMetadata)
Mockito.`when`(mockCameraAppComponent.getCameraDevices())
.thenReturn(cameraDevicesWithCameraMetaData)
cameraFactory!!.cameraManager = mockCameraAppComponent
val cameraXConfig = CameraXConfig.Builder.fromConfig(
CameraPipeConfig.defaultConfig()
)
.setDeviceSurfaceManagerProvider { context: Context?, _: Any?, _: Set<String?>? ->
CameraSurfaceAdapter(
context!!,
mockCameraAppComponent, setOf(cameraId)
)
}
.setCameraFactoryProvider { _: Context?,
_: CameraThreadConfig?,
_: CameraSelector?
->
cameraFactory!!
}
.build()
val cameraX: CameraX = try {
CameraXUtil.getOrCreateInstance(context) { cameraXConfig }.get()
} catch (e: ExecutionException) {
throw IllegalStateException("Unable to initialize CameraX for test.")
} catch (e: InterruptedException) {
throw IllegalStateException("Unable to initialize CameraX for test.")
}
useCaseConfigFactory = cameraX.defaultConfigFactory
}
private fun isAllSubConfigListSupported(
supportedSurfaceCombination: SupportedSurfaceCombination,
combinationList: List<SurfaceCombination>
): Boolean {
for (combination in combinationList) {
val configList = combination.surfaceConfigList
val length = configList.size
if (length <= 1) {
continue
}
for (index in 0 until length) {
val subConfigurationList: MutableList<SurfaceConfig> = ArrayList(configList)
subConfigurationList.removeAt(index)
val isSupported = supportedSurfaceCombination.checkSupported(subConfigurationList)
if (!isSupported) {
return false
}
}
}
return true
}
/** Creates a VideoCapture with one ore more specific Quality */
private fun createVideoCapture(vararg quality: Quality): VideoCapture<TestVideoOutput> {
return createVideoCapture(QualitySelector.fromOrderedList(listOf(*quality)))
}
/** Creates a VideoCapture with a customized QualitySelector */
/** Creates a VideoCapture with a default QualitySelector */
@JvmOverloads
fun createVideoCapture(
qualitySelector: QualitySelector = VideoSpec.QUALITY_SELECTOR_AUTO
): VideoCapture<TestVideoOutput> {
val mediaSpecBuilder = MediaSpec.builder()
mediaSpecBuilder.configureVideo { builder: VideoSpec.Builder ->
builder.setQualitySelector(
qualitySelector
)
}
val videoOutput = TestVideoOutput()
videoOutput.mediaSpecObservable.setState(mediaSpecBuilder.build())
return VideoCapture.withOutput(videoOutput)
}
/** A fake implementation of VideoOutput */
class TestVideoOutput : VideoOutput {
var mediaSpecObservable =
MutableStateObservable.withInitialState(MediaSpec.builder().build())
private var surfaceRequest: SurfaceRequest? = null
private var sourceState: SourceState? = null
override fun onSurfaceRequested(request: SurfaceRequest) {
surfaceRequest = request
}
override fun getMediaSpec(): Observable<MediaSpec> {
return mediaSpecObservable
}
override fun onSourceStateChanged(sourceState: SourceState) {
this.sourceState = sourceState
}
}
} | 0 | Kotlin | 0 | 0 | c542b3a7cf2c46dfe3e071ca57956761e90aaff3 | 108,719 | androidx | Apache License 2.0 |
src/main/kotlin/com/paulmethfessel/bp/lang/xml/ProbeComment.kt | Paulpanther | 370,134,784 | false | null | package com.paulmethfessel.bp.lang.xml
import com.intellij.psi.xml.XmlTag
import com.intellij.psi.xml.XmlTokenType
import com.intellij.xml.util.XmlUtil
import com.paulmethfessel.bp.ide.decorators.BpAnnotator
import com.paulmethfessel.bp.ide.decorators.ProbeHintsProvider2
@Deprecated("Will be removed")
class ProbeComment(
root: XmlTag,
offset: Int
): CommentElement(root, offset) {
companion object {
fun isProbe(root: XmlTag) = root.name == "Probe"
}
val tag = XmlUtil.getTokenOfType(root, XmlTokenType.XML_NAME)
val expression = root.getAttribute(":expression")
override fun annotate(annotator: BpAnnotator) = annotator.annotateProbe(this)
override fun showHint(hinter: ProbeHintsProvider2) = hinter.showHintForProbe(this)
}
| 11 | Kotlin | 0 | 3 | 978cba16290ff95b7cf93b563211373877b66bdc | 772 | intellij-babylonian-plugin | MIT License |
app/src/main/java/thecodemonks/org/nottzapp/ui/dialog/ErrorDialog.kt | Sleekice | 714,873,013 | false | {"Kotlin": 60992} | /**********************************************************
* ERROR DIALOG FRAGMENT
**********************************************************/
/*
* This code defines a BottomSheetDialogFragment that displays an error dialog.
*/
package thecodemonks.org.nottzapp.ui.dialog
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.view.WindowManager
import androidx.navigation.fragment.navArgs
import com.google.android.material.bottomsheet.BottomSheetDialogFragment
import thecodemonks.org.nottzapp.databinding.ErrorDialogLayoutBinding
class ErrorDialog : BottomSheetDialogFragment() {
// Binding for the error dialog layout
private var _binding: ErrorDialogLayoutBinding? = null
private val binding get() = _binding!!
// Retrieve arguments passed to the dialog
private val args: ErrorDialogArgs by navArgs()
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View {
// Inflates the error dialog layout and returns the root view
_binding = ErrorDialogLayoutBinding.inflate(inflater, container, false)
return binding.root
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
binding.run {
// Set the dialog title and message from the arguments
dialogTitle.text = args.title
dialogMessage.text = args.message
// Handle the button click to dismiss the dialog
dialogButtonOk.setOnClickListener { dialog?.dismiss() }
}
}
override fun onStart() {
super.onStart()
// Configure the dialog window layout to match the parent's dimensions
dialog?.window?.setLayout(
WindowManager.LayoutParams.MATCH_PARENT,
WindowManager.LayoutParams.MATCH_PARENT
)
}
override fun onDestroy() {
super.onDestroy()
// Release the binding when the fragment is destroyed
_binding = null
}
}
| 0 | Kotlin | 0 | 0 | 44f3fc48d7cfc8ff041df08fa5d82999e922bda8 | 2,138 | NottzApp | MIT License |
api/src/main/java/com/getcode/generator/MnemonicGenerator.kt | code-payments | 723,049,264 | false | {"Kotlin": 2199788, "C": 198685, "C++": 83029, "Java": 52287, "Shell": 9082, "Ruby": 4626, "CMake": 2594} | package com.getcode.generator
import com.getcode.crypt.MnemonicPhrase
import com.getcode.utils.Base58String
import com.getcode.utils.Base64String
import javax.inject.Inject
class MnemonicGenerator @Inject constructor(
): Generator<Base64String, MnemonicPhrase> {
override fun generate(predicate: Base64String): MnemonicPhrase {
return MnemonicPhrase.fromEntropyB64(predicate)
}
fun generateFromBase58(predicate: Base58String): MnemonicPhrase {
return MnemonicPhrase.fromEntropyB58(predicate)
}
} | 3 | Kotlin | 13 | 14 | 3cda858e3f8be01e560d72293fcd801f5385adfd | 531 | code-android-app | MIT License |
code/text/PostalAddress.kt | check24-profis | 469,706,312 | false | null | @Composable
fun PostalAddressExample() {
var address by remember { mutableStateOf("") }
TextField(
value = address,
onValueChange = { address = it },
)
} | 0 | Kotlin | 3 | 11 | abd64a7d2edac0dbedb4d67d3c0f7b49d9173b88 | 183 | jetpack-compose-is-like-android-view | MIT License |
typescript-kotlin/src/main/kotlin/typescript/nodeModuleNameResolver.fun.kt | turansky | 393,199,102 | false | null | // Automatically generated - do not modify!
@file:JsModule("typescript")
@file:JsNonModule
package typescript
/*
external fun nodeModuleNameResolver(moduleName: string, containingFile: string, compilerOptions: CompilerOptions, host: ModuleResolutionHost, cache?: ModuleResolutionCache, redirectedReference?: ResolvedProjectReference): ResolvedModuleWithFailedLookupLocations
*/
| 0 | Kotlin | 1 | 10 | bcf03704c0e7670fd14ec4ab01dff8d7cca46bf0 | 381 | react-types-kotlin | Apache License 2.0 |
frontend/src/jsMain/kotlin/com/monkopedia/konstructor/frontend/model/KonstructorEditorState.kt | Monkopedia | 418,215,448 | false | null | /*
* Copyright 2022 <NAME>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* 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.monkopedia.konstructor.frontend.model
import codemirror.themeonedark.oneDark
import com.monkopedia.konstructor.common.MessageImportance.ERROR
import com.monkopedia.konstructor.frontend.editor.MirrorStyles
import com.monkopedia.konstructor.frontend.editor.asString
import com.monkopedia.konstructor.frontend.editor.filterMarks
import com.monkopedia.konstructor.frontend.editor.markField
import com.monkopedia.konstructor.frontend.editor.replaceMarks
import com.monkopedia.konstructor.frontend.utils.buildExt
import dukat.codemirror.basicSetup
import dukat.codemirror.commands.history
import dukat.codemirror.language.StreamLanguage
import dukat.codemirror.legacymodes.kotlin
import dukat.codemirror.state.EditorState
import dukat.codemirror.state.`T$5`
import dukat.codemirror.state.TransactionSpec
import dukat.codemirror.view.Decoration
import dukat.codemirror.view.EditorView
import dukat.codemirror.view.ViewUpdate
import dukat.codemirror.view.scrollPastEnd
import dukat.codemirror.vim.vim
import kotlin.math.max
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.MutableSharedFlow
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.SharingStarted
import kotlinx.coroutines.flow.combine
import kotlinx.coroutines.flow.filterNotNull
import kotlinx.coroutines.flow.first
import kotlinx.coroutines.flow.map
import kotlinx.coroutines.flow.stateIn
import kotlinx.coroutines.launch
import styled.getClassSelector
class KonstructorEditorState(
private val model: KonstructionModel,
private val coroutineScope: CoroutineScope
) {
private val heightTheme = EditorView.theme(
buildExt {
set(
"&",
kotlinext.js.js {
height = "calc(100vh - 64px)"
width = "calc(50hw)"
}
)
set(".cm-scroller", kotlinext.js.js { overflow = "auto" })
}
)
var editorState = EditorState.create(
buildExt {
this.doc = ""
this.extensions = arrayOf(
oneDark,
vim(),
basicSetup,
StreamLanguage.define(kotlin),
markField,
EditorView.lineWrapping,
EditorView.updateListener.of(::onViewUpdate),
scrollPastEnd(),
heightTheme,
history()
)
}
)
private val errorClass by lazy {
MirrorStyles.getClassSelector { it::errorLineBackground }.trimStart('.')
}
private val warningClass by lazy {
MirrorStyles.getClassSelector { it::warningLineBackground }.trimStart('.')
}
private val classes = model.messages.map { messages ->
mapOf(
errorClass to messages.filter { it.importance == ERROR }
.mapNotNull { it.line },
warningClass to messages.filter { it.importance != ERROR }
.mapNotNull { it.line }
)
}.stateIn(coroutineScope, SharingStarted.Eagerly, emptyMap())
private val transactionFlow = MutableSharedFlow<TransactionSpec>()
private val currentLine = MutableStateFlow(-1)
private var currentView: EditorView? = null
val setView: (EditorView?) -> Unit = {
currentView = it
}
private fun setMarks(customClasses: Map<String, List<Int>>): TransactionSpec {
val doc = editorState.doc
val marks = customClasses.entries.flatMap { (key, lines) ->
lines.filter {
(it + 1) <= doc.lines.toInt()
}.map {
doc.line(it + 1).let { lineInfo ->
Decoration.mark(
buildExt {
this.`class` = key
}
).range(lineInfo.from, max(lineInfo.to.toInt(), lineInfo.from.toInt() + 1))
}
}
}
return buildExt {
effects = replaceMarks.of(marks.toTypedArray())
}
}
private fun setTransaction(content: String) = buildExt<TransactionSpec> {
effects = filterMarks.of { _, _, _ -> false }
changes = buildExt<`T$5`> {
from = 0
to = editorState.doc.length
insert = content
}
}
private val currentText = MutableStateFlow("")
private val currentSetText = MutableStateFlow("")
val pendingText = MutableStateFlow<String?>(null)
init {
coroutineScope.launch {
transactionFlow.collect { transaction ->
currentView?.dispatch(transaction)
?: editorState.update(transaction).also {
editorState = it.state
}
}
}
coroutineScope.launch {
val initialText = model.currentText.filterNotNull().first()
currentText.value = initialText
currentSetText.value = initialText
transactionFlow.emit(setTransaction(initialText))
launch {
model.currentText.filterNotNull().collect { newText ->
if (newText == currentText.value) return@collect
if (currentText.value == currentSetText.value) {
updateText(newText)
return@collect
}
val rawText = currentText.value
.replace(" ", "")
.replace("\n", "")
.replace("\t", "")
val newRawText = newText
.replace(" ", "")
.replace("\n", "")
.replace("\t", "")
if (rawText != newRawText) {
pendingText.value = newText
} else {
updateText(newText)
}
}
}
classes.collect { classes ->
transactionFlow.emit(setMarks(classes))
}
}
}
suspend fun discardLocalChanges() {
updateText(pendingText.value ?: return)
pendingText.value = null
}
private suspend fun updateText(newText: String) {
transactionFlow.emit(setTransaction(newText))
transactionFlow.emit(setMarks(classes.value))
currentText.value = newText
currentSetText.value = newText
}
val currentMessage: Flow<String?> = combine(currentLine, model.messages) { line, messages ->
messages.find {
it.line == line
}?.message
}
private fun onViewUpdate(viewUpdate: ViewUpdate) {
val pos = viewUpdate.state.selection.main.head.toInt()
val line = viewUpdate.state.doc.lineAt(pos).number.toInt() - 1
currentText.value = viewUpdate.state.doc.asString()
currentLine.value = line
}
fun save(): String {
return currentText.value.also {
pendingText.value = null
}
}
}
| 0 | Kotlin | 0 | 0 | 38f0c0d9adeba659e5cb7bf6b88a6995a3c7546f | 7,652 | Konstructor | Apache License 2.0 |
app/src/main/java/com/itranslate/recorder/general/utils/BindingAdapterUtils.kt | shahin68 | 400,558,240 | false | null | package com.itranslate.recorder.general.utils
import androidx.databinding.BindingAdapter
import androidx.paging.CombinedLoadStates
import androidx.paging.LoadState
import com.google.android.material.progressindicator.CircularProgressIndicator
import com.google.android.material.progressindicator.LinearProgressIndicator
import com.itranslate.recorder.general.extensions.showOrHide
class BindingAdapterUtils {
companion object {
/**
* Binding adapter responsible of binding [CombinedLoadStates] with [CircularProgressIndicator]
*/
@JvmStatic
@BindingAdapter("app:circularProgressIndicator_setShowOrHide")
fun setShowOrHide(circularProgressIndicator: CircularProgressIndicator, combinedStates: CombinedLoadStates) {
when (val state = combinedStates.append) {
is LoadState.NotLoading -> {
circularProgressIndicator.showOrHide(show = false)
}
is LoadState.Loading -> {
circularProgressIndicator.showOrHide(show = !state.endOfPaginationReached)
}
is LoadState.Error -> {
circularProgressIndicator.showOrHide(show = false)
}
}
when (val state = combinedStates.refresh) {
is LoadState.Loading -> {
circularProgressIndicator.showOrHide(show = !state.endOfPaginationReached)
}
}
}
/**
* Binding adapter responsible of binding [showLoading] with [LinearProgressIndicator]
*/
@JvmStatic
@BindingAdapter("app:linearProgressIndicator_setShowOrHide")
fun setShowOrHide(linearProgressIndicator: LinearProgressIndicator, showLoading: Boolean) {
linearProgressIndicator.showOrHide(showLoading)
}
}
} | 0 | Kotlin | 0 | 0 | eb77ff0dbac4e59c18838288378c606c8c3aecf6 | 1,877 | iRecorder | MIT License |
Chapter10/src/main/kotlin/06_Racing.kt | PacktPublishing | 654,570,300 | false | {"Kotlin": 133148} | import arrow.core.merge
import arrow.fx.coroutines.raceN
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.delay
import kotlinx.coroutines.withContext
import kotlin.random.Random
suspend fun main() {
val winner: Pair<String, String> = raceN(
{ preciseWeather() },
{ weatherToday() },
).merge()
println("Winner: $winner")
}
suspend fun preciseWeather() = withContext(Dispatchers.IO) {
delay(Random.nextLong(100))
("Precise Weather" to "+25c")
}
suspend fun weatherToday() = withContext(Dispatchers.IO) {
delay(Random.nextLong(100))
("Weather Today" to "+24c")
} | 0 | Kotlin | 2 | 1 | 5f6669e33db38d3099cdf34bee3ab8750807d10b | 622 | Kotlin-Design-Patterns-and-Best-Practices_Third-Edition | MIT License |
gi/src/commonMain/kotlin/data/activity/ActivityScheduleInfo.kt | Anime-Game-Servers | 642,871,918 | false | {"Kotlin": 612536} | package data.activity
import org.anime_game_servers.core.base.annotations.RemovedIn
import org.anime_game_servers.core.base.annotations.AddedIn
import org.anime_game_servers.core.base.Version
import org.anime_game_servers.core.base.annotations.proto.ProtoModel
@AddedIn(Version.GI_CB2)
@ProtoModel
interface ActivityScheduleInfo {
var activityId: Int
var isOpen: Boolean
var scheduleId: Int
var beginTime: Int
var endTime: Int
@AddedIn(Version.GI_0_9_0)
@RemovedIn(Version.GI_1_0_0)
var hasReward: Boolean
} | 0 | Kotlin | 3 | 6 | 6a45cbe89682bc25543b24db9a21f8012d9f53bc | 541 | anime-game-multi-proto | MIT License |
straight/src/commonMain/kotlin/me/localx/icons/straight/outline/WorkflowSettingAlt.kt | localhostov | 808,861,591 | false | {"Kotlin": 79430321, "HTML": 331, "CSS": 102} | package me.localx.icons.straight.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.straight.Icons
public val Icons.Outline.WorkflowSettingAlt: ImageVector
get() {
if (_workflowSettingAlt != null) {
return _workflowSettingAlt!!
}
_workflowSettingAlt = Builder(name = "WorkflowSettingAlt", 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(4.0f, 14.0f)
horizontalLineToRelative(7.0f)
verticalLineToRelative(2.0f)
horizontalLineToRelative(2.0f)
verticalLineToRelative(-2.0f)
horizontalLineToRelative(7.0f)
verticalLineToRelative(2.0f)
horizontalLineToRelative(2.0f)
verticalLineToRelative(-4.0f)
horizontalLineToRelative(-9.0f)
verticalLineToRelative(-1.612f)
curveToRelative(0.898f, -0.205f, 1.695f, -0.679f, 2.3f, -1.332f)
lineToRelative(1.4f, 0.806f)
lineToRelative(0.998f, -1.733f)
lineToRelative(-1.397f, -0.805f)
curveToRelative(0.129f, -0.419f, 0.199f, -0.863f, 0.199f, -1.324f)
reflectiveCurveToRelative(-0.07f, -0.905f, -0.199f, -1.324f)
lineToRelative(1.397f, -0.805f)
lineToRelative(-0.998f, -1.733f)
lineToRelative(-1.4f, 0.806f)
curveToRelative(-0.606f, -0.654f, -1.402f, -1.128f, -2.3f, -1.332f)
lineTo(13.0f, 0.0f)
horizontalLineToRelative(-2.0f)
verticalLineToRelative(1.612f)
curveToRelative(-0.898f, 0.205f, -1.695f, 0.679f, -2.3f, 1.332f)
lineToRelative(-1.4f, -0.806f)
lineToRelative(-0.998f, 1.733f)
lineToRelative(1.397f, 0.805f)
curveToRelative(-0.129f, 0.419f, -0.199f, 0.863f, -0.199f, 1.324f)
reflectiveCurveToRelative(0.07f, 0.905f, 0.199f, 1.324f)
lineToRelative(-1.397f, 0.805f)
lineToRelative(0.998f, 1.733f)
lineToRelative(1.4f, -0.806f)
curveToRelative(0.606f, 0.654f, 1.402f, 1.128f, 2.3f, 1.332f)
verticalLineToRelative(1.612f)
lineTo(2.0f, 12.0f)
verticalLineToRelative(4.0f)
horizontalLineToRelative(2.0f)
verticalLineToRelative(-2.0f)
close()
moveTo(9.5f, 6.0f)
curveToRelative(0.0f, -1.378f, 1.121f, -2.5f, 2.5f, -2.5f)
reflectiveCurveToRelative(2.5f, 1.122f, 2.5f, 2.5f)
reflectiveCurveToRelative(-1.121f, 2.5f, -2.5f, 2.5f)
reflectiveCurveToRelative(-2.5f, -1.122f, -2.5f, -2.5f)
close()
moveTo(9.0f, 24.0f)
horizontalLineToRelative(6.0f)
verticalLineToRelative(-6.0f)
horizontalLineToRelative(-6.0f)
verticalLineToRelative(6.0f)
close()
moveTo(11.0f, 20.0f)
horizontalLineToRelative(2.0f)
verticalLineToRelative(2.0f)
horizontalLineToRelative(-2.0f)
verticalLineToRelative(-2.0f)
close()
moveTo(18.0f, 18.0f)
verticalLineToRelative(6.0f)
horizontalLineToRelative(6.0f)
verticalLineToRelative(-6.0f)
horizontalLineToRelative(-6.0f)
close()
moveTo(22.0f, 22.0f)
horizontalLineToRelative(-2.0f)
verticalLineToRelative(-2.0f)
horizontalLineToRelative(2.0f)
verticalLineToRelative(2.0f)
close()
moveTo(0.0f, 24.0f)
horizontalLineToRelative(6.0f)
verticalLineToRelative(-6.0f)
lineTo(0.0f, 18.0f)
verticalLineToRelative(6.0f)
close()
moveTo(2.0f, 20.0f)
horizontalLineToRelative(2.0f)
verticalLineToRelative(2.0f)
horizontalLineToRelative(-2.0f)
verticalLineToRelative(-2.0f)
close()
}
}
.build()
return _workflowSettingAlt!!
}
private var _workflowSettingAlt: ImageVector? = null
| 1 | Kotlin | 0 | 5 | cbd8b510fca0e5e40e95498834f23ec73cc8f245 | 5,185 | icons | MIT License |
app/src/main/java/ro/smg/exchangerates/util/Log.kt | mscarlat95 | 262,355,828 | false | null | package ro.smg.exchangerates.util
import ro.smg.exchangerates.BuildConfig
class Log {
companion object {
private val LOG_ENABLE: Boolean = BuildConfig.DEBUG
fun e(tag: String?, msg: String) {
if (LOG_ENABLE) android.util.Log.e(tag, msg)
}
fun e(tag: String?, msg: String?, tr: Throwable?) {
if (LOG_ENABLE) android.util.Log.e(tag, msg, tr)
}
fun d(tag: String?, msg: String) {
if (LOG_ENABLE) android.util.Log.d(tag, msg)
}
fun d(tag: String?, msg: String?, tr: Throwable?) {
if (LOG_ENABLE) android.util.Log.d(tag, msg, tr)
}
fun v(tag: String?, msg: String) {
if (LOG_ENABLE) android.util.Log.v(tag, msg)
}
fun v(tag: String?, msg: String?, tr: Throwable?) {
if (LOG_ENABLE) android.util.Log.v(tag, msg, tr)
}
fun i(tag: String?, msg: String) {
if (LOG_ENABLE) android.util.Log.i(tag, msg)
}
fun i(tag: String?, msg: String?, tr: Throwable?) {
if (LOG_ENABLE) android.util.Log.i(tag, msg, tr)
}
fun w(tag: String?, msg: String) {
if (LOG_ENABLE) android.util.Log.w(tag, msg)
}
fun w(tag: String?, msg: String?, tr: Throwable?) {
if (LOG_ENABLE) android.util.Log.w(tag, msg, tr)
}
}
}
| 0 | Kotlin | 0 | 0 | 7dc945f3dd72c37bd29e7cf108c04afca172cf4f | 1,394 | ExchangeRates | Apache License 2.0 |
app/src/main/java/id/del/ac/delstat/data/repository/literatur/LiteraturRepositoryImpl.kt | matthewalfredoo | 487,180,171 | false | {"Kotlin": 521336} | package id.del.ac.delstat.data.repository.literatur
import id.del.ac.delstat.data.model.literatur.LiteraturApiResponse
import id.del.ac.delstat.data.repository.literatur.datasource.LiteraturRemoteDataSource
import id.del.ac.delstat.domain.repository.LiteraturRepository
import java.io.File
class LiteraturRepositoryImpl(
private val literaturRemoteDataSource: LiteraturRemoteDataSource
) : LiteraturRepository {
override suspend fun getLiteratur(
judul: String?,
tag: String?
): LiteraturApiResponse? {
try {
val response = literaturRemoteDataSource.getLiteratur(judul, tag)
return response.body()
} catch (e: Exception) {
e.printStackTrace()
}
return null
}
override suspend fun getDetailLiteratur(id: Int): LiteraturApiResponse? {
try {
val response = literaturRemoteDataSource.getDetailLiteratur(id)
return response.body()
} catch (e: Exception) {
e.printStackTrace()
}
return null
}
override suspend fun storeLiteratur(
bearerToken: String,
judul: String,
penulis: String,
tahunTerbit: Int,
tag: String,
file: File?
): LiteraturApiResponse? {
try {
val response = literaturRemoteDataSource.storeLiteratur(
bearerToken,
judul,
penulis,
tahunTerbit,
tag,
file
)
return response.body()
} catch (e: Exception) {
e.printStackTrace()
}
return null
}
override suspend fun updateLiteratur(
bearerToken: String,
id: Int,
judul: String,
penulis: String,
tahunTerbit: Int,
tag: String,
file: File?
): LiteraturApiResponse? {
try {
val response = literaturRemoteDataSource.updateLiteratur(
bearerToken,
id,
judul,
penulis,
tahunTerbit,
tag,
file
)
return response.body()
} catch (e: Exception) {
e.printStackTrace()
}
return null
}
override suspend fun deleteLiteratur(bearerToken: String, id: Int): LiteraturApiResponse? {
try {
val response = literaturRemoteDataSource.deleteLiteratur(bearerToken, id)
return response.body()
} catch (e: Exception) {
e.printStackTrace()
}
return null
}
} | 0 | Kotlin | 0 | 1 | 94f508452aa302caf7d40d25c6fd4868a40fbf49 | 2,636 | DelStat | MIT License |
shared/src/commonMain/kotlin/app/duss/easyproject/domain/params/CustomerEnquiryItemCreateOrUpdateRequest.kt | Shahriyar13 | 721,031,988 | false | {"Kotlin": 247935, "Swift": 6282, "Ruby": 2302} | package app.duss.easyproject.domain.params
import com.darkrockstudios.libraries.mpfilepicker.MPFile
class CustomerEnquiryItemCreateOrUpdateRequest (
val id: Long?,
val customerEnquiryId: Long,
val itemId: Long?,
val item: ItemCreateRequest?,
var quantity: Int,
var note: String? = null,
val fileAttachments: List<MPFile<Any>>? = ArrayList(),
) | 0 | Kotlin | 0 | 0 | 3b21efcf1c9bcdc2148884458a7c34f75020e071 | 373 | Kara_EasyProject_CMP | Apache License 2.0 |
kt/src/test/java/spark/surgery/Topo.kt | 5Gene | 815,162,991 | false | {"Kotlin": 118306} | package spark.surgery
import java.util.*
/**
* 拓扑排序并计算每个节点的层级,支持字符串节点
* @param graph 表示有向无环图,键为节点(字符串),值为该节点依赖的所有节点(字符串)
* @return 节点及其对应层级的映射关系,如果存在环,返回 null
*/
fun topologicalSortWithLevels(graph: Map<String, List<String>>): Map<String, Int>? {
val indegree = mutableMapOf<String, Int>()
val adjacencyList = mutableMapOf<String, MutableList<String>>()
// 初始化入度和邻接表
graph.keys.forEach { node ->
indegree[node] = 0
adjacencyList[node] = mutableListOf()
}
// 计算入度并构建邻接表
graph.forEach { (node, dependencies) ->
dependencies.forEach { dependency ->
adjacencyList[dependency]?.add(node)
indegree[node] = indegree.getOrDefault(node, 0) + 1
}
}
// 入度为0的节点入队
val queue: Queue<String> = LinkedList()
val level = mutableMapOf<String, Int>() // 用来记录每个节点的层级
indegree.forEach { (node, deg) ->
if (deg == 0) {
queue.add(node)
level[node] = 0 // 入度为 0 的节点层级为 0
}
}
// 拓扑排序,并计算每个节点的层级
while (queue.isNotEmpty()) {
val node = queue.poll()
adjacencyList[node]?.forEach { dependentNode ->
indegree[dependentNode] = indegree[dependentNode]!! - 1
// 更新依赖节点的层级
level[dependentNode] = maxOf(level.getOrDefault(dependentNode, 0), level[node]!! + 1)
if (indegree[dependentNode] == 0) {
queue.add(dependentNode)
}
}
}
// 检查是否存在环
return if (level.size == graph.size) level else null
}
/**
* 根据层级输出并行可执行的节点
* @param levels 每个节点的层级映射
* @return 根据层级划分的并行任务组
*/
fun findParallelTasks(levels: Map<String, Int>): Map<Int, List<String>> {
val parallelTasks = mutableMapOf<Int, MutableList<String>>()
// 按层级分组
levels.forEach { (node, lvl) ->
parallelTasks.computeIfAbsent(lvl) { mutableListOf() }.add(node)
}
return parallelTasks
}
fun main() {
// 定义有向无环图,节点为字符串,支持多个依赖
val graph = mapOf(
"taskA" to listOf("taskB", "taskC"), // taskA 依赖 taskB 和 taskC
"taskB" to listOf("taskD"), // taskB 依赖 taskD
"taskC" to listOf("taskD", "taskE"), // taskC 依赖 taskD 和 taskE
"taskD" to listOf(), // taskD 无依赖
"taskE" to listOf("taskF"), // taskE 依赖 taskF
"taskF" to listOf() // taskF 无依赖
)
// 1. 执行拓扑排序并计算层级
val levels = topologicalSortWithLevels(graph)
// 2. 找到可以并行执行的任务
if (levels != null) {
println("节点的层级是: $levels")
val parallelTasks = findParallelTasks(levels)
println("可以并行执行的任务组:")
parallelTasks.forEach { (level, tasks) ->
println("层级 $level: ${tasks.joinToString(", ")}")
}
} else {
println("图中存在环,无法进行拓扑排序")
}
}
| 0 | Kotlin | 0 | 0 | 289aa355fa520dfe69516554f012d4d1ca9bbed5 | 2,794 | replace | Apache License 2.0 |
app/src/main/java/com/mohfahmi/mkaassesment/di/AppModule.kt | MohFahmi27 | 447,899,964 | false | null | package com.mohfahmi.mkaassesment.di
import com.mohfahmi.mkaassesment.domain.UsersGithubInteractor
import com.mohfahmi.mkaassesment.domain.usecase.UsersGithubUseCase
import com.mohfahmi.mkaassesment.ui.detail.DetailViewModel
import com.mohfahmi.mkaassesment.ui.home.HomeViewModel
import org.koin.androidx.viewmodel.dsl.viewModel
import org.koin.dsl.module
val useCaseModule = module {
factory<UsersGithubUseCase> { UsersGithubInteractor(get()) }
}
val viewModelModule = module {
viewModel { HomeViewModel(get()) }
viewModel { DetailViewModel(get()) }
} | 0 | Kotlin | 0 | 1 | 9a53345d539d005c199a42123e4a0703f85974f6 | 567 | MkaAssesment | MIT License |
petblocks-bukkit-plugin/petblocks-bukkit-nms-113R1/src/main/java/com/github/shynixn/petblocks/bukkit/logic/business/service/Item113R1ServiceImpl.kt | Tominous | 180,851,910 | true | {"Kotlin": 1474097, "Shell": 2544} | @file:Suppress("UNCHECKED_CAST")
package com.github.shynixn.petblocks.bukkit.logic.business.service
import com.github.shynixn.petblocks.api.business.enumeration.MaterialType
import com.github.shynixn.petblocks.api.business.proxy.ItemStackProxy
import com.github.shynixn.petblocks.api.business.service.ItemService
import org.bukkit.Material
import org.bukkit.entity.Player
import org.bukkit.inventory.ItemStack
import java.lang.reflect.Method
import java.util.*
/**
* Created by Shynixn 2018.
* <p>
* Version 1.2
* <p>
* MIT License
* <p>
* Copyright (c) 2018 by Shynixn
* <p>
* 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:
* <p>
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
* <p>
* 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.
*/
class Item113R1ServiceImpl : ItemService {
private val getIdFromMaterialMethod: Method = { Material::class.java.getDeclaredMethod("getId") }.invoke()
private val getItemInMainHandMethod: Method
private val getItemInOffHandMethod: Method
/**
* Initialize.
*/
init {
val inventoryClazz = Class.forName("org.bukkit.inventory.PlayerInventory")
getItemInMainHandMethod = inventoryClazz.getDeclaredMethod("getItemInMainHand")
getItemInOffHandMethod = inventoryClazz.getDeclaredMethod("getItemInOffHand")
}
/**
* Creates a new itemstack from the given parameters.
*/
override fun createItemStack(type: Any, dataValue: Int): ItemStackProxy {
return Class.forName("com.github.shynixn.petblocks.bukkit.logic.business.proxy.ItemStackProxyImpl")
.getDeclaredConstructor(String::class.java, Int::class.java)
.newInstance(getMaterialValue(type).name, dataValue) as ItemStackProxy
}
/**
* Gets if the given [itemStack] has got the given [type] and [dataValue].
*/
override fun <I> hasItemStackProperties(itemStack: I, type: Any, dataValue: Int): Boolean {
if (itemStack !is ItemStack) {
throw IllegalArgumentException("ItemStack has to be a BukkitItemStack!")
}
val material = getMaterialValue(type)
return material == itemStack.type && dataValue == itemStack.durability.toInt()
}
/**
* Gets the itemstack in the hand of the player with optional offHand flag.
*/
override fun <P, I> getItemInHand(player: P, offHand: Boolean): Optional<I> {
if (player !is Player) {
throw IllegalArgumentException("Player has to be a BukkitPlayer!")
}
return if (offHand) {
Optional.ofNullable(getItemInOffHandMethod.invoke(player.inventory) as I)
} else {
Optional.ofNullable(getItemInMainHandMethod.invoke(player.inventory) as I)
}
}
/**
* Processing if there is any way the given [value] can be mapped to an material.
*/
private fun getMaterialValue(value: Any): Material {
if (value is Int) {
for (material in Material.values()) {
if (getIdFromMaterialMethod(material) == value) {
return material
}
}
} else if (value is String && value.toIntOrNull() != null) {
for (material in Material.values()) {
if (getIdFromMaterialMethod(material) == value.toInt()) {
return material
}
}
} else if (value is String) {
return Material.getMaterial(value) ?: throw IllegalArgumentException("Material $value does not exist!")
} else if (value is MaterialType) {
return getMaterialValue(value.numericId)
}
throw throw IllegalArgumentException("Material $value is not a string or int.")
}
} | 0 | Kotlin | 0 | 1 | 8ca7dcc8083200dab6869fdb4e0a493ebc6ea2b0 | 4,648 | PetBlocks | Apache License 2.0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.