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/glm_/mat3x3/operators/mat3_operators.kt | kotlin-graphics | 71,653,021 | false | null | package glm_.mat3x3.operators
import glm_.mat2x3.Mat2x3
import glm_.mat3x3.Mat3
import glm_.mat3x3.Mat3.Companion.div
import glm_.mat3x3.Mat3.Companion.minus
import glm_.mat3x3.Mat3.Companion.plus
import glm_.mat3x3.Mat3.Companion.times
import glm_.mat4x3.Mat4x3
import glm_.vec3.Vec3
import glm_.vec3.Vec3.Companion.div
import glm_.vec3.Vec3.Companion.minus
import glm_.vec3.Vec3.Companion.plus
import glm_.vec3.Vec3.Companion.times
/**
* Created by GBarbieri on 10.11.2016.
*/
open class mat3x3_operators {
/** Mat3 = Mat3 + scalar */
inline fun plus(res: Mat3, a: Mat3, b: Float): Mat3 {
plus(res[0], a[0], b, b, b)
plus(res[1], a[1], b, b, b)
plus(res[2], a[2], b, b, b)
return res
}
/** Mat3 = Mat3 - scalar */
inline fun minus(res: Mat3, a: Mat3, b: Float): Mat3 {
minus(res[0], a[0], b, b, b)
minus(res[1], a[1], b, b, b)
minus(res[2], a[2], b, b, b)
return res
}
/** Mat3 = scalar - Mat3 */
inline fun minus(res: Mat3, a: Float, b: Mat3): Mat3 {
minus(res[0], a, a, a, b[0])
minus(res[1], a, a, a, b[1])
minus(res[2], a, a, a, b[2])
return res
}
/** Mat3 = Mat3 * scalar */
inline fun times(res: Mat3, a: Mat3, b: Float): Mat3 {
times(res[0], a[0], b, b, b)
times(res[1], a[1], b, b, b)
times(res[2], a[2], b, b, b)
return res
}
/** Mat3 = Mat3 / scalar */
inline fun div(res: Mat3, a: Mat3, b: Float): Mat3 {
div(res[0], a[0], b, b, b)
div(res[1], a[1], b, b, b)
div(res[2], a[2], b, b, b)
return res
}
/** Mat3 = scalar / Mat3 */
inline fun div(res: Mat3, a: Float, b: Mat3): Mat3 {
div(res[0], a, a, a, b[0])
div(res[1], a, a, a, b[1])
div(res[2], a, a, a, b[2])
return res
}
/** Mat3 = Mat3 + Mat3 */
inline fun plus(res: Mat3, a: Mat3, b: Mat3) = plus(res, a,
b[0, 0], b[0, 1], b[0, 2],
b[1, 0], b[1, 1], b[1, 2],
b[2, 0], b[2, 1], b[2, 2])
/** Mat3 = Mat3 + Mat3 */
inline fun plus(res: Mat3, a: Mat3, b0: Vec3, b1: Vec3, b2: Vec3) = plus(res, a,
b0[0], b0[1], b0[2],
b1[0], b1[1], b1[2],
b2[0], b2[1], b2[2])
/** Mat3 = Mat3 + Mat3 */
inline fun plus(res: Mat3, a: Mat3,
b00: Float, b01: Float, b02: Float,
b10: Float, b11: Float, b12: Float,
b20: Float, b21: Float, b22: Float): Mat3 {
plus(res[0], a[0], b00, b01, b02)
plus(res[1], a[1], b10, b11, b12)
plus(res[2], a[2], b20, b21, b22)
return res
}
/** Mat3 = Mat3 - Mat3 */
inline fun minus(res: Mat3, a: Mat3, b: Mat3) = minus(res, a,
b[0, 0], b[0, 1], b[0, 2],
b[1, 0], b[1, 1], b[1, 2],
b[2, 0], b[2, 1], b[2, 2])
/** Mat3 = Mat3 - Mat3 */
inline fun minus(res: Mat3, a: Mat3, b0: Vec3, b1: Vec3, b2: Vec3) = minus(res, a,
b0[0], b0[1], b0[2],
b1[0], b1[1], b1[2],
b2[0], b2[1], b2[2])
/** Mat3 = Mat3 - Mat3 */
inline fun minus(res: Mat3, a: Mat3,
b00: Float, b01: Float, b02: Float,
b10: Float, b11: Float, b12: Float,
b20: Float, b21: Float, b22: Float): Mat3 {
minus(res[0], a[0], b00, b01, b02)
minus(res[1], a[1], b10, b11, b12)
minus(res[2], a[2], b20, b21, b22)
return res
}
/** Mat3 = Mat3 - Mat3 */
inline fun minus(res: Mat3, a0: Vec3, a1: Vec3, a2: Vec3, b: Mat3) = minus(res,
a0[0], a0[1], a0[2],
a1[0], a1[1], a1[2],
a2[0], a2[1], a2[2], b)
/** Mat3 = Mat3 - Mat3 */
inline fun minus(res: Mat3,
a00: Float, a01: Float, a02: Float,
a10: Float, a11: Float, a12: Float,
a20: Float, a21: Float, a22: Float, b: Mat3): Mat3 {
minus(res[0], a00, a01, a02, b[0])
minus(res[1], a10, a11, a12, b[1])
minus(res[2], a20, a21, a22, b[2])
return res
}
/** Vec3 col = Mat3 * Vec3 row */
inline fun times(res: Vec3, a: Mat3, b: Vec3) = times(res, a, b.x, b.y, b.z)
/** Vec3 col = Mat3 * Vec3 row */
inline fun times(res: Vec3, a: Mat3, b0: Float, b1: Float, b2: Float): Vec3 {
res[0] = a[0, 0] * b0 + a[1, 0] * b1 + a[2, 0] * b2
res[1] = a[0, 1] * b0 + a[1, 1] * b1 + a[2, 1] * b2
res[2] = a[0, 2] * b0 + a[1, 2] * b1 + a[2, 2] * b2
return res
}
/** Vec3 row = Vec3 col * Mat3 */
inline fun times(res: Vec3, a: Vec3, b: Mat3) = times(res, a.x, a.y, a.z, b)
/** Vec3 row = Vec3 col * Mat3 */
inline fun times(res: Vec3, a0: Float, a1: Float, a2: Float, b: Mat3): Vec3 {
res[0] = a0 * b[0, 0] + a1 * b[0, 1] + a2 * b[0, 2]
res[1] = a0 * b[1, 0] + a1 * b[1, 1] + a2 * b[1, 2]
res[2] = a0 * b[2, 0] + a1 * b[2, 1] + a2 * b[2, 2]
return res
}
/** Mat3 = Mat3 * Mat3 */
inline fun times(res: Mat3, a: Mat3, b: Mat3) = times(res, a,
b[0, 0], b[0, 1], b[0, 2],
b[1, 0], b[1, 1], b[1, 2],
b[2, 0], b[2, 1], b[2, 2])
/** Mat3 = Mat3 * Mat3 */
inline fun times(res: Mat3, a: Mat3, b0: Vec3, b1: Vec3, b2: Vec3) = times(res, a,
b0[0], b0[1], b0[2],
b1[0], b1[1], b1[2],
b2[0], b2[1], b2[2])
/** Mat3 = Mat3 * Mat3 */
inline fun times(res: Mat3, a: Mat3,
b00: Float, b01: Float, b02: Float,
b10: Float, b11: Float, b12: Float,
b20: Float, b21: Float, b22: Float): Mat3 {
val v00 = a[0, 0] * b00 + a[1, 0] * b01 + a[2, 0] * b02
val v01 = a[0, 1] * b00 + a[1, 1] * b01 + a[2, 1] * b02
val v02 = a[0, 2] * b00 + a[1, 2] * b01 + a[2, 2] * b02
val v10 = a[0, 0] * b10 + a[1, 0] * b11 + a[2, 0] * b12
val v11 = a[0, 1] * b10 + a[1, 1] * b11 + a[2, 1] * b12
val v12 = a[0, 2] * b10 + a[1, 2] * b11 + a[2, 2] * b12
val v20 = a[0, 0] * b20 + a[1, 0] * b21 + a[2, 0] * b22
val v21 = a[0, 1] * b20 + a[1, 1] * b21 + a[2, 1] * b22
val v22 = a[0, 2] * b20 + a[1, 2] * b21 + a[2, 2] * b22
res[0, 0] = v00; res[1, 0] = v10; res[2, 0] = v20
res[0, 1] = v01; res[1, 1] = v11; res[2, 1] = v21
res[0, 2] = v02; res[1, 2] = v12; res[2, 2] = v22
return res
}
/** Mat23 = Mat3 * Mat23 */
inline fun times(res: Mat2x3, a: Mat3, b: Mat2x3) = times(res, a, b[0], b[1], b[2])
/** Mat23 = Mat3 * Mat23 */
inline fun times(res: Mat2x3, a: Mat3, b0: Vec3, b1: Vec3, b2: Vec3) = times(res, a, b0.x, b0.y, b1.x, b1.y, b2.x, b2.y)
/** Mat23 = Mat3 * Mat23 */
inline fun times(res: Mat2x3, a: Mat3,
b00: Float, b01: Float, b02: Float,
b10: Float, b11: Float, b12: Float): Mat2x3 {
val v00 = a[0, 0] * b00 + a[1, 0] * b01 + a[2, 0] * b02
val v01 = a[0, 1] * b00 + a[1, 1] * b01 + a[2, 1] * b02
val v02 = a[0, 2] * b00 + a[1, 2] * b01 + a[2, 2] * b02
val v10 = a[0, 0] * b10 + a[1, 0] * b11 + a[2, 0] * b12
val v11 = a[0, 1] * b10 + a[1, 1] * b11 + a[2, 1] * b12
val v12 = a[0, 2] * b10 + a[1, 2] * b11 + a[2, 2] * b12
res[0, 0] = v00; res[1, 0] = v10
res[0, 1] = v01; res[1, 1] = v11
res[0, 2] = v02; res[1, 2] = v12
return res
}
/** Mat43 = Mat3 * Mat43 */
inline fun times(res: Mat4x3, a: Mat3, b: Mat4x3) = times(res, a, b[0], b[1], b[2], b[3])
/** Mat43 = Mat3 * Mat43 */
inline fun times(res: Mat4x3, a: Mat3, b0: Vec3, b1: Vec3, b2: Vec3, b3: Vec3) = times(res, a,
b0.x, b0.y, b0.z,
b1.x, b1.y, b1.z,
b2.x, b2.y, b2.z,
b3.x, b3.y, b3.z)
/** Mat43 = Mat3 * Mat43 */
inline fun times(res: Mat4x3, a: Mat3,
b00: Float, b01: Float, b02: Float,
b10: Float, b11: Float, b12: Float,
b20: Float, b21: Float, b22: Float,
b30: Float, b31: Float, b32: Float): Mat4x3 {
val v00 = a[0, 0] * b00 + a[1, 0] * b01 + a[2, 0] * b02
val v01 = a[0, 1] * b00 + a[1, 1] * b01 + a[2, 1] * b02
val v02 = a[0, 2] * b00 + a[1, 2] * b01 + a[2, 2] * b02
val v10 = a[0, 0] * b10 + a[1, 0] * b11 + a[2, 0] * b12
val v11 = a[0, 1] * b10 + a[1, 1] * b11 + a[2, 1] * b12
val v12 = a[0, 2] * b10 + a[1, 2] * b11 + a[2, 2] * b12
val v20 = a[0, 0] * b20 + a[1, 0] * b21 + a[2, 0] * b22
val v21 = a[0, 1] * b20 + a[1, 1] * b21 + a[2, 1] * b22
val v22 = a[0, 2] * b20 + a[1, 2] * b21 + a[2, 2] * b22
val v30 = a[0, 0] * b30 + a[1, 0] * b31 + a[2, 0] * b32
val v31 = a[0, 1] * b30 + a[1, 1] * b31 + a[2, 1] * b32
val v32 = a[0, 2] * b30 + a[1, 2] * b31 + a[2, 2] * b32
res[0, 0] = v00; res[1, 0] = v10; res[2, 0] = v20; res[3, 0] = v30
res[0, 1] = v01; res[1, 1] = v11; res[2, 1] = v21; res[3, 1] = v31
res[0, 2] = v02; res[1, 2] = v12; res[2, 2] = v22; res[3, 2] = v32
return res
}
/** Mat3 = Mat3 / Mat3 = Mat3 * Mat3^-1 */
inline fun div(res: Mat3, a: Mat3, b: Mat3) = div(res, a,
b[0, 0], b[0, 1], b[0, 2],
b[1, 0], b[1, 1], b[1, 2],
b[2, 0], b[2, 1], b[2, 2])
/** Mat3 = Mat3 / Mat3 = Mat3 * Mat3^-1 */
inline fun div(res: Mat3, a: Mat3, b0: Vec3, b1: Vec3, b2: Vec3) = div(res, a,
b0[0], b0[1], b0[2],
b1[0], b1[1], b1[2],
b2[0], b2[1], b2[2])
/** Mat3 = Mat3 / Mat3 = Mat3 * Mat3^-1 */
inline fun div(res: Mat3, a: Mat3,
b00: Float, b01: Float, b02: Float,
b10: Float, b11: Float, b12: Float,
b20: Float, b21: Float, b22: Float): Mat3 {
res[0, 0] = b00; res[1, 0] = b10; res[2, 0] = b20
res[0, 1] = b01; res[1, 1] = b11; res[2, 1] = b21
res[0, 2] = b02; res[1, 2] = b12; res[2, 2] = b22
res.inverseAssign()
a.times(res, res)
return res
}
/** Vec3 col = Mat3 * Vec3 row */
inline fun div(res: Vec3, a: Mat3, b: Vec3) = div(res, a, b.x, b.y, b.z)
/** Vec3 col = Mat3 * Vec3 row */
inline fun div(res: Vec3, a: Mat3, b0: Float, b1: Float, b2: Float): Vec3 {
val oneOverDet = 1 / a.det
val i00 = +(a[1, 1] * a[2, 2] - a[2, 1] * a[1, 2]) * oneOverDet
val i10 = -(a[1, 0] * a[2, 2] - a[2, 0] * a[1, 2]) * oneOverDet
val i20 = +(a[1, 0] * a[2, 1] - a[2, 0] * a[1, 1]) * oneOverDet
val i01 = -(a[0, 1] * a[2, 2] - a[2, 1] * a[0, 2]) * oneOverDet
val i11 = +(a[0, 0] * a[2, 2] - a[2, 0] * a[0, 2]) * oneOverDet
val i21 = -(a[0, 0] * a[2, 1] - a[2, 0] * a[0, 1]) * oneOverDet
val i02 = +(a[0, 1] * a[1, 2] - a[1, 1] * a[0, 2]) * oneOverDet
val i12 = -(a[0, 0] * a[1, 2] - a[1, 0] * a[0, 2]) * oneOverDet
val i22 = +(a[0, 0] * a[1, 1] - a[1, 0] * a[0, 1]) * oneOverDet
res[0] = i00 * b0 + i10 * b1 + i20 * b2
res[1] = i01 * b0 + i11 * b1 + i21 * b2
res[2] = i02 * b0 + i12 * b1 + i22 * b2
return res
}
/** Vec3 row = Vec3 col * Mat3 */
inline fun div(res: Vec3, a: Vec3, b: Mat3) = div(res, a.x, a.y, a.z, b)
/** Vec3 row = Vec3 col * Mat3 */
inline fun div(res: Vec3, a0: Float, a1: Float, a2: Float, b: Mat3): Vec3 {
val oneOverDet = 1 / b.det
val i00 = +(b[1, 1] * b[2, 2] - b[2, 1] * b[1, 2]) * oneOverDet
val i10 = -(b[1, 0] * b[2, 2] - b[2, 0] * b[1, 2]) * oneOverDet
val i20 = +(b[1, 0] * b[2, 1] - b[2, 0] * b[1, 1]) * oneOverDet
val i01 = -(b[0, 1] * b[2, 2] - b[2, 1] * b[0, 2]) * oneOverDet
val i11 = +(b[0, 0] * b[2, 2] - b[2, 0] * b[0, 2]) * oneOverDet
val i21 = -(b[0, 0] * b[2, 1] - b[2, 0] * b[0, 1]) * oneOverDet
val i02 = +(b[0, 1] * b[1, 2] - b[1, 1] * b[0, 2]) * oneOverDet
val i12 = -(b[0, 0] * b[1, 2] - b[1, 0] * b[0, 2]) * oneOverDet
val i22 = +(b[0, 0] * b[1, 1] - b[1, 0] * b[0, 1]) * oneOverDet
res[0] = a0 * i00 + a1 * i01 + a2 * i02
res[1] = a0 * i10 + a1 * i11 + a2 * i12
res[2] = a0 * i20 + a1 * i21 + a2 * i22
return res
}
}
// -- Specific binary arithmetic operators --
operator fun Float.plus(b: Mat3) = plus(Mat3(), b, this)
fun Float.plus(b: Mat3, res: Mat3 = Mat3()) = plus(res, b, this)
infix fun Float.plus_(b: Mat3) = plus(b, b, this)
operator fun Float.minus(b: Mat3) = minus(Mat3(), this, b)
fun Float.minus(b: Mat3, res: Mat3 = Mat3()) = minus(res, this, b)
infix fun Float.minus_(b: Mat3) = minus(b, this, b)
operator fun Float.times(b: Mat3) = times(Mat3(), b, this)
fun Float.times(b: Mat3, res: Mat3 = Mat3()) = times(res, b, this)
infix fun Float.times_(b: Mat3) = times(b, b, this)
operator fun Vec3.times(b: Mat3) = times(Vec3(), this, b)
fun Vec3.times(b: Mat3, res: Vec3 = Vec3()) = times(res, this, b)
infix fun Vec3.times_(b: Mat3) = times(this, this, b)
operator fun Float.div(b: Mat3) = div(Mat3(), this, b)
fun Float.div(b: Mat3, res: Mat3 = Mat3()) = div(res, this, b)
infix fun Float.div_(b: Mat3) = div(b, this, b) | 5 | Kotlin | 19 | 99 | dcbdd6237fbc5af02722b8ea1b404a93ce38a043 | 13,298 | glm | MIT License |
kt/godot-library/src/main/kotlin/godot/gen/godot/EditorResourcePreview.kt | utopia-rise | 289,462,532 | false | null | // THIS FILE IS GENERATED! DO NOT EDIT IT MANUALLY!
@file:Suppress("PackageDirectoryMismatch", "unused", "FunctionName", "RedundantModalityModifier",
"UNCHECKED_CAST", "JoinDeclarationAndAssignment", "USELESS_CAST",
"RemoveRedundantQualifierName", "NOTHING_TO_INLINE", "NON_FINAL_MEMBER_IN_OBJECT",
"RedundantVisibilityModifier", "RedundantUnitReturnType", "MemberVisibilityCanBePrivate")
package godot
import godot.`annotation`.GodotBaseType
import godot.core.StringName
import godot.core.VariantType.ANY
import godot.core.VariantType.NIL
import godot.core.VariantType.OBJECT
import godot.core.VariantType.STRING
import godot.core.VariantType.STRING_NAME
import godot.core.memory.TransferContext
import godot.signals.Signal1
import godot.signals.signal
import kotlin.Any
import kotlin.Boolean
import kotlin.Int
import kotlin.String
import kotlin.Suppress
import kotlin.Unit
/**
* A node used to generate previews of resources or files.
*
* This node is used to generate previews for resources of files.
*
* **Note:** This class shouldn't be instantiated directly. Instead, access the singleton using [godot.EditorInterface.getResourcePreviewer].
*/
@GodotBaseType
public open class EditorResourcePreview internal constructor() : Node() {
/**
* Emitted if a preview was invalidated (changed). [path] corresponds to the path of the preview.
*/
public val previewInvalidated: Signal1<String> by signal("path")
public override fun new(scriptIndex: Int): Boolean {
callConstructor(ENGINECLASS_EDITORRESOURCEPREVIEW, scriptIndex)
return true
}
/**
* Queue a resource file located at [path] for preview. Once the preview is ready, the [receiver]'s [receiverFunc] will be called. The [receiverFunc] must take the following four arguments: [godot.String] path, [godot.Texture2D] preview, [godot.Texture2D] thumbnail_preview, [Variant] userdata. [userdata] can be anything, and will be returned when [receiverFunc] is called.
*
* **Note:** If it was not possible to create the preview the [receiverFunc] will still be called, but the preview will be null.
*/
public fun queueResourcePreview(
path: String,
`receiver`: Object,
receiverFunc: StringName,
userdata: Any?,
): Unit {
TransferContext.writeArguments(STRING to path, OBJECT to receiver, STRING_NAME to receiverFunc, ANY to userdata)
TransferContext.callMethod(rawPtr,
ENGINEMETHOD_ENGINECLASS_EDITORRESOURCEPREVIEW_QUEUE_RESOURCE_PREVIEW, NIL)
}
/**
* Queue the [resource] being edited for preview. Once the preview is ready, the [receiver]'s [receiverFunc] will be called. The [receiverFunc] must take the following four arguments: [godot.String] path, [godot.Texture2D] preview, [godot.Texture2D] thumbnail_preview, [Variant] userdata. [userdata] can be anything, and will be returned when [receiverFunc] is called.
*
* **Note:** If it was not possible to create the preview the [receiverFunc] will still be called, but the preview will be null.
*/
public fun queueEditedResourcePreview(
resource: Resource,
`receiver`: Object,
receiverFunc: StringName,
userdata: Any?,
): Unit {
TransferContext.writeArguments(OBJECT to resource, OBJECT to receiver, STRING_NAME to receiverFunc, ANY to userdata)
TransferContext.callMethod(rawPtr,
ENGINEMETHOD_ENGINECLASS_EDITORRESOURCEPREVIEW_QUEUE_EDITED_RESOURCE_PREVIEW, NIL)
}
/**
* Create an own, custom preview generator.
*/
public fun addPreviewGenerator(generator: EditorResourcePreviewGenerator): Unit {
TransferContext.writeArguments(OBJECT to generator)
TransferContext.callMethod(rawPtr,
ENGINEMETHOD_ENGINECLASS_EDITORRESOURCEPREVIEW_ADD_PREVIEW_GENERATOR, NIL)
}
/**
* Removes a custom preview generator.
*/
public fun removePreviewGenerator(generator: EditorResourcePreviewGenerator): Unit {
TransferContext.writeArguments(OBJECT to generator)
TransferContext.callMethod(rawPtr,
ENGINEMETHOD_ENGINECLASS_EDITORRESOURCEPREVIEW_REMOVE_PREVIEW_GENERATOR, NIL)
}
/**
* Check if the resource changed, if so, it will be invalidated and the corresponding signal emitted.
*/
public fun checkForInvalidation(path: String): Unit {
TransferContext.writeArguments(STRING to path)
TransferContext.callMethod(rawPtr,
ENGINEMETHOD_ENGINECLASS_EDITORRESOURCEPREVIEW_CHECK_FOR_INVALIDATION, NIL)
}
public companion object
}
| 58 | null | 30 | 426 | fc2f3eacf779c21ce18d2161cca63e6dffdb1c91 | 4,449 | godot-kotlin-jvm | MIT License |
feature_workbrowse/src/main/java/com/pimenta/bestv/workbrowse/domain/LoadWorkByTypeUseCase.kt | marcuspimenta | 132,016,354 | false | null | /*
* Copyright (C) 2018 <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 com.pimenta.bestv.workbrowse.domain
import com.pimenta.bestv.workbrowse.presentation.model.TopWorkTypeViewModel
import javax.inject.Inject
/**
* Created by marcus on 23-08-2019.
*/
class LoadWorkByTypeUseCase @Inject constructor(
private val getFavoritesUseCase: GetFavoritesUseCase,
private val getNowPlayingMoviesUseCase: GetNowPlayingMoviesUseCase,
private val getPopularMoviesUseCase: GetPopularMoviesUseCase,
private val getTopRatedMoviesUseCase: GetTopRatedMoviesUseCase,
private val getUpComingMoviesUseCase: GetUpComingMoviesUseCase,
private val getAiringTodayTvShowsUseCase: GetAiringTodayTvShowsUseCase,
private val getOnTheAirTvShowsUseCase: GetOnTheAirTvShowsUseCase,
private val getPopularTvShowsUseCase: GetPopularTvShowsUseCase,
private val getTopRatedTvShowsUseCase: GetTopRatedTvShowsUseCase
) {
operator fun invoke(page: Int, topWorkTypeViewModel: TopWorkTypeViewModel) =
when (topWorkTypeViewModel) {
TopWorkTypeViewModel.FAVORITES_MOVIES -> getFavoritesUseCase()
TopWorkTypeViewModel.NOW_PLAYING_MOVIES -> getNowPlayingMoviesUseCase(page)
TopWorkTypeViewModel.POPULAR_MOVIES -> getPopularMoviesUseCase(page)
TopWorkTypeViewModel.TOP_RATED_MOVIES -> getTopRatedMoviesUseCase(page)
TopWorkTypeViewModel.UP_COMING_MOVIES -> getUpComingMoviesUseCase(page)
TopWorkTypeViewModel.AIRING_TODAY_TV_SHOWS -> getAiringTodayTvShowsUseCase(page)
TopWorkTypeViewModel.ON_THE_AIR_TV_SHOWS -> getOnTheAirTvShowsUseCase(page)
TopWorkTypeViewModel.POPULAR_TV_SHOWS -> getPopularTvShowsUseCase(page)
TopWorkTypeViewModel.TOP_RATED_TV_SHOWS -> getTopRatedTvShowsUseCase(page)
}
}
| 5 | Kotlin | 20 | 54 | 63b92f876dd7d4571d3824e723e67c1872d25cd3 | 2,342 | BESTV | Apache License 2.0 |
app/src/main/java/com/github/hosseinzafari/touristo/presentation/screens/signup/data/usecases/SingupUseCase.kt | HosseinZafari | 630,809,256 | false | null | package com.github.hosseinzafari.touristo.presentation.screens.signup.data.usecases
import com.github.hosseinzafari.touristo.base.system.data_layer.XUseCase
import com.github.hosseinzafari.touristo.presentation.screens.signup.data.SignupDomain
import javax.inject.Inject
/**
* @author Hossein Zafari
* @email [email protected]
* @created 10/05/2023 - 10:03 PM
* @project Touristo
*/
class SingupUseCase @Inject constructor(
override val domain: SignupDomain
) : XUseCase<SignupDomain>() {
suspend operator fun invoke(email: String, password: String ) = domain.signup(email, password )
} | 1 | Kotlin | 0 | 1 | 08bd43d5e9c1c2cb9e9fcaed643bbfcf1a3ca4a0 | 607 | touristo | MIT License |
logging-android-appcenter4/src/main/java/com/fsryan/tools/logging/android/AppCenterDevMetricsLogger.kt | ryansgot | 212,757,848 | false | null | package com.fsryan.tools.logging.android
import android.content.Context
import com.fsryan.tools.logging.FSDevMetricsLogger
import com.microsoft.appcenter.analytics.Analytics
import com.microsoft.appcenter.analytics.EventProperties
class AppCenterDevMetricsLogger : ContextSpecificDevMetricsLogger {
override fun initialize(context: Context) = FSAppCenter.ensureInitialized(context)
override fun id() = "appcenter"
override fun watch(msg: String, attrs: Map<String, String>) {
if (FSAppCenter.analyticsEnabled.get()) {
sendToAppCenter("watch", msg, attrs)
}
}
override fun info(msg: String, attrs: Map<String, String>) {
if (FSAppCenter.analyticsEnabled.get()) {
sendToAppCenter("info", msg, attrs)
}
}
override fun metric(operationName: String, durationNanos: Long) {
if (FSAppCenter.analyticsEnabled.get()) {
Analytics.trackEvent("devMetric", EventProperties().apply {
set("operation", operationName)
set("duration", durationNanos)
})
}
}
private fun sendToAppCenter(
type: String,
msg: String?,
attrs: Map<String, String>
) {
Analytics.trackEvent("devLog", attrs + mapOf(
"devLogType" to type,
"devMessage" to (msg ?: "")
))
}
} | 5 | Kotlin | 2 | 1 | ddf9d66edbda1b81d7fec2a41593ecc2ecc72dfc | 1,374 | logging | Apache License 2.0 |
ground/src/main/java/com/google/android/ground/model/submission/TextTaskData.kt | google | 127,777,820 | false | null | /*
* Copyright 2019 Google LLC
*
* 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.android.ground.model.submission
import kotlinx.serialization.Serializable
/** A user-provided value to a text question task. */
@Serializable
data class TextTaskData(val text: String) : TaskData {
override fun getDetailsText(): String = text
override fun isEmpty(): Boolean = text.trim { it <= ' ' }.isEmpty()
override fun toString(): String = text
companion object {
fun fromString(text: String): TaskData? = if (text.isEmpty()) null else TextTaskData(text)
}
}
| 224 | null | 116 | 245 | 502a3bcafa4d65ba62868036cf5287a4219aaf5c | 1,096 | ground-android | Apache License 2.0 |
ldb/kodein-leveldb/src/commonTest/kotlin/org/kodein/db/leveldb/test/LDBTests_05_ForgetClose.kt | Kodein-Framework | 147,318,269 | false | null | package org.kodein.db.leveldb.test
import org.kodein.db.leveldb.LevelDB
import org.kodein.db.leveldb.LevelDBFactory
import org.kodein.db.leveldb.default
import org.kodein.db.leveldb.inDir
import org.kodein.db.leveldb.inmemory.inMemory
import org.kodein.db.test.utils.AssertLogger
import org.kodein.log.Logger
import org.kodein.log.LoggerFactory
import org.kodein.memory.file.FileSystem
import kotlin.test.Test
import kotlin.test.assertEquals
@Suppress("ClassName")
abstract class LDBTests_05_ForgetClose : LevelDBTests() {
class LDB : LDBTests_05_ForgetClose() { override val factory: LevelDBFactory = LevelDB.default.inDir(FileSystem.tempDirectory.path) }
class IM : LDBTests_05_ForgetClose() { override val factory: LevelDBFactory = LevelDB.inMemory }
@Test
fun test_00_CursorTrack() {
val logger = AssertLogger()
ldb!!.close()
ldb = factory.open("db", options().copy(loggerFactory = LoggerFactory(logger.frontEnd)))
val cursor = ldb!!.newCursor()
val countBeforeClose = logger.entries.count()
ldb!!.close()
assertEquals((countBeforeClose + 1).toLong(), logger.entries.count().toLong())
assertEquals("Cursor must be closed. Creation stack trace:", logger.entries.last().third!!.split("\n".toRegex()).dropLastWhile { it.isEmpty() }.toTypedArray()[0].trim { it <= ' ' })
assertEquals(Logger.Level.WARNING, logger.entries.last().second.level)
cursor.close()
}
@Test
fun test_01_CursorNoTrack() {
val logger = AssertLogger()
ldb!!.close()
ldb = factory.open("db", options().copy(loggerFactory = LoggerFactory(logger.frontEnd), trackClosableAllocation = false))
val cursor = ldb!!.newCursor()
val countBeforeClose = logger.entries.count()
ldb!!.close()
assertEquals((countBeforeClose + 1).toLong(), logger.entries.count().toLong())
assertEquals("Cursor has not been properly closed. To track its allocation, set trackClosableAllocation.", logger.entries.last().third!!.split("\n".toRegex()).dropLastWhile { it.isEmpty() }.toTypedArray()[0].trim { it <= ' ' })
cursor.close()
}
}
| 13 | Kotlin | 22 | 273 | 044ad75e88d14c2702a3716c8150a7ba158d97b6 | 2,167 | Kodein-DB | MIT License |
core/database/src/main/kotlin/com/anbui/recipely/core/database/DatabaseModule.kt | AnBuiii | 667,858,307 | false | null | package com.anbui.recipely.core.database
import android.content.Context
import androidx.room.Room
import dagger.Module
import dagger.Provides
import dagger.hilt.InstallIn
import dagger.hilt.android.qualifiers.ApplicationContext
import dagger.hilt.components.SingletonComponent
import javax.inject.Singleton
@Module
@InstallIn(SingletonComponent::class)
object DatabaseModule {
@Singleton
@Provides
fun provideAppDatabase(@ApplicationContext appContext: Context) =
Room
.databaseBuilder(
appContext,
RecipelyDatabase::class.java,
"Recipely.sqlite"
)
.createFromAsset("recipely.sqlite")
// .fallbackToDestructiveMigration() // todo remove
.build()
} | 3 | null | 2 | 6 | 156f05165742222aa8d6f6f4b26b0c653380c30a | 776 | Recipely | Apache License 2.0 |
app/src/main/java/com/example/dropy/network/services/rider/RiderService.kt | dropyProd | 705,360,878 | false | {"Kotlin": 3916897, "Java": 20617} | package com.example.dropy.network.services.rider
import android.content.Context
import com.example.dropy.network.models.acceptjob.AcceptJobResponse
import com.example.dropy.network.models.acceptjob.request.AcceptJobBody
import com.example.dropy.network.models.canceljob.CancelIncomingJobResponse
import com.example.dropy.network.models.commondataclasses.ActionResultDataClass
import com.example.dropy.network.models.customerqr.body.CustomerQrBody
import com.example.dropy.network.models.favouriteshop.FavShopDataClass
import com.example.dropy.network.models.ongoingjobs.OngoingJobsResponse
import com.example.dropy.network.models.riderincomingjob.RiderIncomingJobResponse
import com.example.dropy.network.models.shopqr.qrbody.QrBody
import com.example.dropy.network.models.shops.ShopsResponse
import com.example.dropy.ui.screens.shops.frontside.checkout.CheckoutDataClass
import retrofit2.Response
import retrofit2.http.Body
import retrofit2.http.GET
import retrofit2.http.POST
import retrofit2.http.Path
interface RiderService {
@GET("jobs/{riderId}")
suspend fun getAllRiderIncomingJobs(@Path("riderId") riderId: Int): RiderIncomingJobResponse
@GET("ongoing-jobs/{riderId}")
suspend fun getAllRiderOngoingJobs(@Path("riderId") riderId: Int): RiderIncomingJobResponse
@GET("accept-job/{riderId}/{deliveryId}")
suspend fun acceptIncomingJobs(
@Path("riderId") riderId: Int,
@Path("deliveryId") deliveryId: Int
): AcceptJobResponse
@POST("verify-qr")
suspend fun verifyQr(@Body qrBody: QrBody): ActionResultDataClass
@POST("verify-cust-qr")
suspend fun verifyCustQr(@Body customerQrBody: CustomerQrBody): ActionResultDataClass
@POST("cancel-job/{deliveryPersonId}/{deliveryId}")
suspend fun cancelIncomingJob(
@Path("deliveryPersonId") deliveryPersonId: Int,
@Path("deliveryId") deliveryId: Int
): CancelIncomingJobResponse
suspend fun getIncomingJobs(riderId: Int, context: Context): RiderIncomingJobResponse?
} | 0 | Kotlin | 0 | 0 | 6d994c9c61207bac28c49717b6c250656fe4ae6b | 2,013 | DropyLateNights | Apache License 2.0 |
src/test/kotlin/br/ufrn/imd/obama/usuario/infrastructure/adapter/EmailGatewayAdapterTest.kt | obama-imd | 491,996,208 | false | {"Kotlin": 248163, "Dockerfile": 249} | package br.ufrn.imd.obama.usuario.infrastructure.adapter
import org.junit.jupiter.api.Test
import org.junit.jupiter.api.assertDoesNotThrow
import org.junit.jupiter.api.extension.ExtendWith
import org.mockito.InjectMocks
import org.mockito.Mock
import org.mockito.Mockito
import org.mockito.Mockito.times
import org.mockito.Mockito.verify
import org.mockito.junit.jupiter.MockitoExtension
import org.springframework.mail.javamail.JavaMailSender
import org.mockito.Mockito.any
import org.mockito.Mockito.`when`
import org.springframework.mail.MailSendException
import org.springframework.mail.SimpleMailMessage
@ExtendWith(MockitoExtension::class)
class EmailGatewayAdapterTest {
@Mock
private lateinit var emailSender: JavaMailSender // Substitua EmailService pela dependência real
@InjectMocks
private lateinit var emailGatewayAdapter: EmailGatewayAdapter
@Test
fun `Deve enviar email com sucesso`() {
val email = "<EMAIL>"
val subject = "Test Subject"
val body = "Test Body"
val message = SimpleMailMessage()
message.setTo(email)
message.subject = subject
message.text = body
assertDoesNotThrow {
emailGatewayAdapter.enviarEmail(email, subject, body)
}
verify(emailSender, times(1)).send(message)
}
@Test
fun `Não deve enviar email com sucesso e não deve lançar exceção`() {
val email = "<EMAIL>"
val subject = "Test Subject"
val body = "Test Body"
val message = SimpleMailMessage()
message.setTo(email)
message.subject = subject
message.text = body
`when`(emailSender.send(any(SimpleMailMessage::class.java))).thenThrow(MailSendException::class.java)
assertDoesNotThrow {
emailGatewayAdapter.enviarEmail(email, subject, body)
}
verify(emailSender, times(1)).send(message)
}
} | 12 | Kotlin | 0 | 4 | d006eeddd3d4b7cc2dce3cc3fe0639c289a0feec | 1,926 | obama | Creative Commons Attribution 4.0 International |
src/main/kotlin/frc/team3324/robot/drivetrain/commands/teleop/Drive.kt | ArnavLondhe | 235,881,785 | true | {"Kotlin": 25675, "Python": 440} | package frc.team3324.robot.drivetrain.commands.teleop
import edu.wpi.first.wpilibj.GenericHID
import edu.wpi.first.wpilibj2.command.CommandBase
import edu.wpi.first.wpilibj.GenericHID.Hand
import frc.team3324.robot.drivetrain.DriveTrain
class Drive(val driveTrain: DriveTrain, val xSpeed: () -> Double, val ySpeed: () -> Double): CommandBase() {
init {
addRequirements(driveTrain)
}
override fun execute() {
driveTrain.curvatureDrive(xSpeed(), ySpeed())
}
override fun isFinished(): Boolean {
return false
}
} | 0 | null | 0 | 0 | 0800bb561da74df0439e685576c9aefc8327d999 | 562 | Metrobots2020Robot | MIT License |
android/app/src/main/kotlin/alexandr/pavlov/ru/arma_helper_nav_bar_ver/MainActivity.kt | Afgan0r | 220,758,009 | false | {"Dart": 12583, "Swift": 404, "Kotlin": 358, "Objective-C": 37} | package alexandr.pavlov.ru.arma_helper_nav_bar_ver
import android.os.Bundle
import io.flutter.app.FlutterActivity
import io.flutter.plugins.GeneratedPluginRegistrant
class MainActivity: FlutterActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
GeneratedPluginRegistrant.registerWith(this)
}
}
| 0 | Dart | 0 | 0 | b16b9a33d0deb9e52cf5e024f7b74c26ab168d91 | 358 | ArmAHelper | Apache License 2.0 |
src/main/kotlin/com/github/vhromada/catalog/web/connector/EpisodeConnector.kt | vhromada | 393,639,974 | false | null | package com.github.vhromada.catalog.web.connector
import com.github.vhromada.catalog.web.connector.io.catalog.ChangeEpisodeRequest
import com.github.vhromada.catalog.web.connector.io.catalog.Episode
import com.github.vhromada.common.entity.Page
import com.github.vhromada.common.filter.PagingFilter
/**
* An interface represents connector for episodes.
*
* @author Vladimir Hromada
*/
interface EpisodeConnector {
/**
* Returns list of episodes for specified season and filter.
*
* @param show show's UUID
* @param season season's UUID
* @return list of episodes for specified season and filter
*/
fun search(show: String, season: String, filter: PagingFilter): Page<Episode>
/**
* Returns episode.
*
* @param show show's UUID
* @param season season's UUID
* @param uuid episode's UUID
* @return episode
*/
fun get(show: String, season: String, uuid: String): Episode
/**
* Adds episode.
*
* @param show show's UUID
* @param season season's UUID
* @param request request for changing episode
* @return created episode
*/
fun add(show: String, season: String, request: ChangeEpisodeRequest): Episode
/**
* Updates episode.
*
* @param show show's UUID
* @param season season's UUID
* @param uuid episode's UUID
* @param request request for changing episode
* @return updated episode
*/
fun update(show: String, season: String, uuid: String, request: ChangeEpisodeRequest): Episode
/**
* Removes episode.
*
* @param show show's UUID
* @param season season's UUID
* @param uuid episode's UUID
*/
fun remove(show: String, season: String, uuid: String)
/**
* Duplicates episode.
*
* @param show show's UUID
* @param season season's UUID
* @param uuid episode's UUID
* @return created duplicated episode
*/
fun duplicate(show: String, season: String, uuid: String): Episode
/**
* Moves episode in list one position up.
*
* @param show show's UUID
* @param season season's UUID
* @param uuid episode's UUID
*/
fun moveUp(show: String, season: String, uuid: String)
/**
* Moves episode in list one position down.
*
* @param show show's UUID
* @param season season's UUID
* @param uuid episode's UUID
*/
fun moveDown(show: String, season: String, uuid: String)
}
| 0 | Kotlin | 0 | 0 | dd56a009f58dd6f259fbe58f0fe09974becd3144 | 2,530 | Catalog-Web-Spring | MIT License |
app/src/test/java/com/github/rovkinmax/rxretainexample/SimpleActivityTest.kt | rovkinmax | 49,500,657 | false | null | package com.github.rovkinmax.rxretainexample
import android.app.Activity
import android.app.FragmentManager
import com.github.rovkinmax.rxretain.EmptySubscriber
import com.github.rovkinmax.rxretain.RetainFactory
import com.github.rovkinmax.rxretain.RetainWrapper
import com.github.rovkinmax.rxretainexample.test.*
import org.junit.Assert
import org.junit.Before
import org.junit.Test
import org.junit.runner.RunWith
import org.mockito.Mockito
import org.robolectric.Robolectric
import org.robolectric.RobolectricGradleTestRunner
import org.robolectric.annotation.Config
import rx.Observable
import rx.Subscriber
import rx.exceptions.OnErrorNotImplementedException
import rx.observers.TestObserver
import rx.observers.TestSubscriber
import java.util.*
import java.util.concurrent.TimeUnit.SECONDS
/**
* @author <NAME> */
@Config(constants = BuildConfig::class, sdk = intArrayOf(21))
@RunWith(RobolectricGradleTestRunner::class)
class SimpleActivityTest {
private lateinit var fragmentManager: FragmentManager
@Before
fun setUp() {
val controller = Robolectric.buildActivity(Activity::class.java).create().start().visible()
val activity = controller.get()
fragmentManager = activity.fragmentManager
}
@Test
fun testSimpleRun() {
val testSubscriber = TestSubscriber<Int>()
RetainFactory.start(fragmentManager, Observable.range(0, 10), testSubscriber)
testSubscriber.assertCompleted()
testSubscriber.assertNoErrors()
testSubscriber.assertValueCount(10)
testSubscriber.assertReceivedOnNext((0..9).toCollection(arrayListOf<Int>()))
}
@Test
fun testThreadSimpleRun() {
val observableThread = Observable.range(0, 10).bindToThread()
val testSubscriber = TestSubscriber<Int>()
RetainFactory.start(fragmentManager, observableThread, testSubscriber)
testSubscriber.awaitTerminalEvent()
testSubscriber.assertCompleted()
testSubscriber.assertValueCount(10)
testSubscriber.assertReceivedOnNext((0..9).toCollection(arrayListOf<Int>()))
}
@Test
fun testRunByEmptySubscribe() {
val firstSubscriber = TestSubscriber<Int>()
createFragmentWithTimer("first", firstSubscriber).subscribe()
firstSubscriber.assertCompleted()
firstSubscriber.assertReceivedOnNext((0..9).toCollection(arrayListOf<Int>()))
}
@Test
fun testErrorWithEmptySubscribeMethod() {
val firstSubscriber = TestSubscriber<Int>()
createFragmentWithOnErrorAction("second", firstSubscriber, TestException("Expected exception")).subscribe()
firstSubscriber.assertError(TestException("Expected exception"))
}
@Test
fun testRunBySubscribeWithOnNextAction() {
val list = ArrayList<Int>()
createFragmentWithTimer("first").subscribe({ list.add(it) })
Assert.assertEquals((0..9).toCollection(arrayListOf<Int>()), list)
}
@Test
fun testErrorWithSubscribeOnNextAction() {
var error: Throwable? = null
try {
createFragmentWithOnErrorAction("second", exception = TestException("Expected exception"))
.subscribe({ })
} catch(e: OnErrorNotImplementedException) {
error = e
}
Assert.assertNotNull(error)
}
@Test fun testRunBySubscribeWithThreeCallbacks() {
var isCompleted = false
createFragmentWithTimer("second").subscribe({}, {}, { isCompleted = true })
Assert.assertTrue(isCompleted)
}
@Test
fun testErrorWithSubscribeByThreeCallbacks() {
var isOnNextCalled = false
var isCompleted = false
var exception: Throwable? = null
createFragmentWithOnErrorAction("second", exception = TestException("Expected exception"))
.subscribe({ isOnNextCalled = true }, { exception = it }, { isCompleted = true })
Assert.assertFalse(isOnNextCalled)
Assert.assertFalse(isCompleted)
Assert.assertEquals(TestException("Expected exception"), exception)
}
@Test fun testRunBySubscribeWithObserver() {
val testObserver = TestObserver<Int>()
createFragmentWithTimer("first").subscribe(testObserver)
testObserver.assertTerminalEvent()
testObserver.assertReceivedOnNext((0..9).toCollection(arrayListOf<Int>()))
}
@Test
fun testErrorWithObserverSubscription() {
val testObserver = TestObserver<Int>()
createFragmentWithOnErrorAction("second", exception = TestException("Expected exception"))
.subscribe(testObserver)
testObserver.assertTerminalEvent()
Assert.assertEquals(arrayListOf(TestException("Expected exception")), testObserver.onErrorEvents)
}
@Test fun testRunBySubscribeWithSubscriber() {
val testSubscriber = TestSubscriber<Int>()
createFragmentWithTimer("first").subscribe(testSubscriber)
testSubscriber.assertCompleted()
testSubscriber.assertReceivedOnNext((0..9).toCollection(arrayListOf<Int>()))
}
@Test
fun testErrorWithSubscriberSubscription() {
val testSubscriber = TestSubscriber<Int>()
createFragmentWithOnErrorAction("second", exception = TestException("Expected exception"))
.subscribe(testSubscriber)
testSubscriber.assertTerminalEvent()
testSubscriber.assertError(TestException("Expected exception"))
}
private fun createFragmentWithTimer(tag: String, subscriber: Subscriber<Int> = EmptySubscriber<Int>()): RetainWrapper<Int> {
return RetainFactory.create(fragmentManager, Observable.range(0, 10), subscriber, tag)
}
private fun createFragmentWithOnErrorAction(tag: String, subscriber: Subscriber<Int> = EmptySubscriber<Int>(), exception: Throwable): RetainWrapper<Int> {
return RetainFactory.create(fragmentManager, Observable.create { throw exception }, subscriber, tag)
}
@Test
fun testStartObservable() {
var testSubscriber = TestSubscriber<Long>()
RetainFactory.start(fragmentManager, Observable.timer(5, SECONDS).bindToThread(), testSubscriber)
testSubscriber.awaitTerminalEvent(2, SECONDS)
val spySubscribers = Mockito.spy(TestSubscriber<Long>())
RetainFactory.start(fragmentManager, Observable.range(0, 10).map { it.toLong() }.bindToThread(), spySubscribers)
testSubscriber.assertUnsubscribed()
if (!spySubscribers.isUnsubscribed)
spySubscribers.awaitTerminalEvent()
Mockito.verify(spySubscribers).onStart()
spySubscribers.assertCompleted()
spySubscribers.assertValueCount(1)
spySubscribers.assertReceivedOnNext(arrayListOf(0.toLong()))
}
@Test
fun testRestartObservable() {
val testSubscriber = TestSubscriber<Long>()
RetainFactory.start(fragmentManager, Observable.timer(5, SECONDS).bindToThread(), testSubscriber)
testSubscriber.awaitTerminalEvent(2, SECONDS)
val spySubscribers = Mockito.spy(TestSubscriber<Long>())
RetainFactory.restart(fragmentManager, Observable.range(0, 10).map { it.toLong() }.bindToThread(), spySubscribers)
testSubscriber.assertUnsubscribed()
Mockito.verify(spySubscribers).onStart()
spySubscribers.awaitTerminalEvent()
spySubscribers.assertCompleted()
spySubscribers.assertValueCount(10)
spySubscribers.assertReceivedOnNext(((0L)..(9L)).toCollection(arrayListOf<Long>()))
}
@Test
fun testStartWithTwoDifferentTags() {
val firstSubscriber = TestSubscriber<Long>()
RetainFactory.start(fragmentManager, Observable.timer(5, SECONDS).bindToThread(), firstSubscriber, "first tag")
firstSubscriber.awaitTerminalEvent(2, SECONDS)
val secondSubscriber = TestSubscriber<Long>()
RetainFactory.start(fragmentManager, Observable.timer(5, SECONDS).bindToThread(), secondSubscriber, "second tag")
secondSubscriber.awaitTerminalEvent()
if (!firstSubscriber.isUnsubscribed) {
firstSubscriber.awaitTerminalEvent()
}
firstSubscriber.assertCompleted()
secondSubscriber.assertCompleted()
}
@Test
fun testFragmentUnsubscribeMethod() {
val testSubscriber = TestSubscriber<Long>()
val fragment = RetainFactory.start(fragmentManager, Observable.timer(50, SECONDS).bindToThread(), testSubscriber)
testSubscriber.awaitTerminalEvent(2, SECONDS)
fragment.unsubscribe()
testSubscriber.assertUnsubscribed()
testSubscriber.assertNoTerminalEvent()
}
@Test
fun testClearCacheAfterFragmentUnsubscribe() {
val testSubscriber = TestSubscriber<Int>()
val fragment = RetainFactory.start(fragmentManager, rangeWithDelay(0, 10).bindToThread(), testSubscriber)
testSubscriber.awaitTerminalEvent(2, SECONDS)
fragment.unsubscribe()
testSubscriber.assertUnsubscribed()
testSubscriber.assertNoTerminalEvent()
val secondSubscriber = TestSubscriber<Int>()
fragment.subscribe(secondSubscriber)
secondSubscriber.awaitTerminalEvent()
secondSubscriber.assertCompleted()
secondSubscriber.assertReceivedOnNext((0..9).toCollection(arrayListOf<Int>()))
}
@Test
fun testCacheResultAfterUnsubscribeSubscription() {
val testSubscriber = TestSubscriber<Int>()
val fragment = RetainFactory.start(fragmentManager, rangeWithDelay(0, 5).bindToThread(), testSubscriber)
testSubscriber.awaitTerminalEvent(2, SECONDS)
testSubscriber.unsubscribe()
val secondSubscriber = TestSubscriber<Int>()
fragment.subscribe(secondSubscriber)
if (!secondSubscriber.isUnsubscribed) {
secondSubscriber.awaitTerminalEvent()
}
testSubscriber.assertNoTerminalEvent()
secondSubscriber.assertTerminalEvent()
secondSubscriber.assertReceivedOnNext((0..4).toCollection(arrayListOf<Int>()))
}
@Test
fun testCacheErrorAfterUnsubscribeSubscription() {
val testSubscriber = TestSubscriber<Int>()
val fragment = RetainFactory.start(fragmentManager,
Observable.create<Int> { delayInThread(5000) ;throw TestException("ha") }.bindToThread(), testSubscriber)
testSubscriber.awaitTerminalEvent(2, SECONDS)
testSubscriber.unsubscribe()
val secondSubscriber = TestSubscriber<Int>()
fragment.subscribe(secondSubscriber)
if (!secondSubscriber.isUnsubscribed) {
secondSubscriber.awaitTerminalEvent()
}
testSubscriber.assertNoTerminalEvent()
secondSubscriber.assertError(TestException("ha"))
}
@Test
fun testDropObservable() {
val subscriber = TestSubscriber<Long>()
val fragment = RetainFactory.start(fragmentManager, Observable.timer(10, SECONDS).bindToThread(), subscriber)
subscriber.awaitTerminalEvent(2, SECONDS)
fragment.unsubscribeAndDropObservable()
var error: Exception? = null
try {
fragment.subscribe()
} catch(e: Exception) {
error = e
}
Assert.assertNotNull(error)
Assert.assertTrue(error is RuntimeException)
Assert.assertEquals("Can't run. First you must create RetainWrapper with not null observer", error?.message)
}
@Test
fun testReplaceObservableByNew() {
val subscriber = TestSubscriber<Long>()
val fragment = RetainFactory.start(fragmentManager, Observable.timer(10, SECONDS).bindToThread(), subscriber)
subscriber.awaitTerminalEvent(2, SECONDS)
fragment.unsubscribeAndDropObservable()
val testSubscriber = TestSubscriber<String>()
RetainFactory.start(fragmentManager, Observable.create<String> { sub ->
sub.onNext("temp1")
sub.onNext("temp2")
sub.onCompleted()
delayInThread(5000)
}.bindToThread(), testSubscriber)
testSubscriber.awaitIfNotUnsubscribed()
testSubscriber.assertCompleted()
testSubscriber.assertReceivedOnNext(arrayListOf("temp1", "temp2"))
}
@Test
fun testSimpleBindWithCompose() {
val subscriber = TestSubscriber<Int>()
val observable = rangeWithDelay(0, 10, 4000)
observable.bindToThread()
.compose(RetainFactory.bindToRetain(fragmentManager))
.subscribe(subscriber)
subscriber.awaitTerminalEvent()
subscriber.assertCompleted()
subscriber.assertReceivedOnNext((0..9).toCollection(arrayListOf()))
}
@Test
fun testUnsubscribeWithCompose() {
val subscriber = TestSubscriber<Int>()
val observable = rangeWithDelay(0, 10, 4000)
val subscription = observable.bindToThread()
.compose(RetainFactory.bindToRetain(fragmentManager))
.subscribe(subscriber)
subscriber.awaitTerminalEvent(2, SECONDS)
subscription.unsubscribe()
subscriber.assertUnsubscribed()
subscriber.awaitTerminalEvent(4, SECONDS)
subscriber.assertNoTerminalEvent()
}
@Test
fun testOnStartAfterRebindingWithCompose() {
val subscriber = TestSubscriber<Int>()
val observable = rangeWithDelay(0, 10, 4000)
val subscription = observable.bindToThread()
.compose(RetainFactory.bindToRetain(fragmentManager))
.subscribe(subscriber)
subscriber.awaitTerminalEvent(2, SECONDS)
subscription.unsubscribe()
subscriber.assertUnsubscribed()
val secondSubscriber = Mockito.spy(TestSubscriber<Int>())
rangeWithDelay(0, 10, 4000)
.bindToThread()
.compose(RetainFactory.bindToRetain(fragmentManager))
.subscribe(secondSubscriber)
secondSubscriber.awaitTerminalEvent()
Mockito.verify(secondSubscriber).onStart()
subscriber.assertNoTerminalEvent()
secondSubscriber.assertReceivedOnNext((0..9).toCollection(arrayListOf()))
}
@Test
fun testErrorWithComposeBinding() {
val firstSubscriber = TestSubscriber<Int>()
errorObservable(TestException("Expected exception"))
.bindToThread()
.compose(RetainFactory.bindToRetain(fragmentManager))
.subscribe(firstSubscriber)
firstSubscriber.awaitTerminalEvent()
firstSubscriber.assertError(TestException("Expected exception"))
}
@Test
fun testErrorAfterUnsubscribeWithCompose() {
val firstSubscriber = TestSubscriber<Int>()
val subscription = errorObservable(TestException("Expected exception"))
.bindToThread()
.compose(RetainFactory.bindToRetain(fragmentManager))
.subscribe(firstSubscriber)
firstSubscriber.awaitTerminalEvent(1, SECONDS)
subscription.unsubscribe()
val secondSubscriber = TestSubscriber<Int>()
errorObservable(TestException("Unexpected exception"))
.bindToThread()
.compose(RetainFactory.bindToRetain(fragmentManager))
.subscribe(secondSubscriber)
secondSubscriber.awaitTerminalEvent()
secondSubscriber.assertError(TestException("Expected exception"))
}
} | 1 | null | 5 | 17 | 811be3403785ffcc343167cd11be08e27e7034d7 | 15,373 | RxRetainFragment | Apache License 2.0 |
kotlin-mui-icons/src/main/generated/mui/icons/material/DirectionsRailway.kt | JetBrains | 93,250,841 | false | null | // Automatically generated - do not modify!
@file:JsModule("@mui/icons-material/DirectionsRailway")
package mui.icons.material
@JsName("default")
external val DirectionsRailway: SvgIconComponent
| 12 | Kotlin | 5 | 983 | 372c0e4bdf95ba2341eda473d2e9260a5dd47d3b | 198 | kotlin-wrappers | Apache License 2.0 |
src/test/java/org/jetbrains/plugins/ideavim/action/motion/text/MotionParagraphPreviousActionTest.kt | JetBrains | 1,459,486 | false | null | /*
* Copyright 2003-2023 The IdeaVim authors
*
* Use of this source code is governed by an MIT-style
* license that can be found in the LICENSE.txt file or at
* https://opensource.org/licenses/MIT.
*/
package org.jetbrains.plugins.ideavim.action.motion.text
import com.maddyhome.idea.vim.command.VimStateMachine
import com.maddyhome.idea.vim.helper.VimBehaviorDiffers
import org.jetbrains.plugins.ideavim.VimTestCase
import org.junit.jupiter.api.Test
class MotionParagraphPreviousActionTest : VimTestCase() {
@VimBehaviorDiffers("")
@Test
fun `test delete till start with empty line`() {
doTest(
"d{",
"""
Lorem ipsum dolor sit amet,
consectetur adipiscing elit
Sed in orci mauris.
hard by the torrent of a mountain pass$c.
""".trimIndent(),
".",
VimStateMachine.Mode.COMMAND,
VimStateMachine.SubMode.NONE,
)
}
}
| 6 | null | 749 | 9,241 | 66b01b0b0d48ffec7b0148465b85e43dfbc908d3 | 905 | ideavim | MIT License |
platform/core/ui/src/main/java/com/orogersilva/myweatherforecast/ui/screen/LoadingScreen.kt | orogersilva | 511,682,755 | false | null | package com.orogersilva.scaffoldandroid.ui.screen
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material3.CircularProgressIndicator
import androidx.compose.runtime.Composable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
@Composable
fun LoadingSubScreen(modifier: Modifier = Modifier) {
Column(
horizontalAlignment = Alignment.CenterHorizontally,
verticalArrangement = Arrangement.Center,
modifier =
modifier
.fillMaxSize()
.background(Color.Transparent),
) {
Column(
horizontalAlignment = Alignment.CenterHorizontally,
verticalArrangement = Arrangement.Center,
modifier =
Modifier
.size(96.dp)
.background(
color = Color.White,
shape = RoundedCornerShape(16.dp),
),
) {
CircularProgressIndicator()
}
}
}
@Preview
@Composable
private fun LoadingSubScreenPreview() {
LoadingSubScreen()
}
| 0 | null | 0 | 3 | ef3abcf66ce4ca699793c700e62cae4ecc4e47e6 | 1,513 | myweatherforecast | Apache License 2.0 |
app/src/main/java/com/serjlaren/sloom/scenes/main/MainFragment.kt | SerjLaren | 478,395,209 | false | null | package com.serjlaren.sloom.scenes.main
import androidx.fragment.app.viewModels
import by.kirich1409.viewbindingdelegate.viewBinding
import com.serjlaren.sloom.R
import com.serjlaren.sloom.common.mvvm.BaseFragment
import com.serjlaren.sloom.databinding.FragmentMainBinding
import dagger.hilt.android.AndroidEntryPoint
@AndroidEntryPoint
class MainFragment : BaseFragment<MainViewModel>(R.layout.fragment_main) {
override val viewModel: MainViewModel by viewModels()
override val viewBinding: FragmentMainBinding by viewBinding()
override fun initViews() {
super.initViews()
with(viewBinding) {
playClickableLayout.setOnClickListener { viewModel.playClicked() }
rulesClickableLayout.setOnClickListener { viewModel.rulesClicked() }
aboutClickableLayout.setOnClickListener { viewModel.aboutClicked() }
}
}
override fun bindViewModel() {
super.bindViewModel()
with(viewModel) {
with(viewBinding) {
bindText(playButtonText, playTextView)
bindText(rulesButtonText, rulesTextView)
bindText(aboutButtonText, aboutTextView)
bindText(additionalInfoText, additionalInfoTextView)
}
}
}
}
| 0 | Kotlin | 0 | 0 | 8d0c6421c2cd89605f85ff8a271092124172b5eb | 1,277 | sloom_android | Apache License 2.0 |
logging/src/commonMain/kotlin/com/fsryan/tools/logging/FSLoggers.kt | ryansgot | 212,757,848 | false | null | package com.fsryan.tools.logging
import kotlin.jvm.JvmStatic
/**
* Base interface for loggers. [FSDevMetrics] and [FSEventLog] look up their
* associated loggers by their Ids. These lookups are set when [FSDevMetrics]
* and [FSEventLog] classes are loaded (respectively).
* @see FSDevMetricsLogger
* @see FSEventLogger
*/
interface FSLogger {
/**
* How this particular [FSLogger] is identified. If multiple loggers have
* duplicate ids, then the last logger specified will overwrite the
* previous loggers.
*/
fun id(): String
/**
* Whether this logger runs in a test environment.
*/
fun runInTestEnvironment(): Boolean = false
companion object {
/**
* Cancels all logging jobs. You can't undo this. Any subsequent logs
* will be dropped.
*/
@JvmStatic
fun cancelLogging() {
cancelLoggingInternal()
}
}
}
/**
* Implementations of [FSDevMetricsLogger] are intended to log events that have
* specific developer benefit. If you need to log an event that should be
* tracked by non-developers, such as screen views, then consider using
* [FSEventLogger] instead. You can log to an [FSDevMetricsLogger] via
* [FSDevMetrics].
*/
interface FSDevMetricsLogger : FSLogger {
/**
* An alarm is a condition that you believe should not occur. If it does
* occur, then using this function declares your intent to be alerted while
* not crashing the app. Add supplemental attributes via the [attrs]
* parameter.
*/
fun alarm(t: Throwable, attrs: Map<String, String> = emptyMap()) {}
/**
* This function is for understanding when something has happened in the
* app that may be of concern. Keep in mind that you'll likely want to
* query whatever analytics backend you have given [msg] and [attrs]
* arguments passed here. Add supplemental attributes via the [attrs]
* parameter.
*/
fun watch(msg: String, attrs: Map<String, String> = emptyMap()) {}
/**
* Use info to monitor events that you have some interest in, but are not
* particularly worrisome as to warrant either a [watch] or an [alarm]. Add
* supplemental attributes via the [attrs] parameter.
*/
fun info(msg: String, attrs: Map<String, String> = emptyMap()) {}
/**
* Use to measure the performance characteristics of an operation. The
* [FSDevMetrics] object has a handy set of functions that you should call
* with respect to metrics: [FSDevMetrics.startTimedOperation],
* [FSDevMetrics.commitTimedOperation], and
* [FSDevMetrics.cancelTimedOperation] are relevant to note (so don't call
* this function yourself).
*/
fun metric(operationName: String, durationNanos: Long) {}
}
/**
* Implementations of [FSEventLogger] are intended to log events that track how
* our users are using the application. If you need to log an event for
* developer benefit, then consider logging to an [FSDevMetricsLogger] instead.
* You can log to an [FSEventLogger] via [FSEventLog].
*/
interface FSEventLogger : FSLogger {
/**
* Add an attribute to the analytics event context. The actual effect of
* adding an attribute is specific to the implementation of [FSEventLogger]
* receiving the attr. However, in general, an attr that is added via this
* function is intended to be logged for every event, whereas, an event
* attr (passed in on the [addEvent] function) is only relevant for that
* specific event.
* @param attrName The name of the attr to add
* @param attrValue The string value of the attr to add
*/
fun addAttr(attrName: String, attrValue: String)
/**
* Attrs are sent for every event. This function allows you to remove an
* attr from the analytics event context. Implementations are free to do
* what they wish if the attr does not exist at the time of removal.
* @param attrName The name of the attr to remove
*/
fun removeAttr(attrName: String)
/**
* Increment an attr value in the analytics event context. The attribute
* should be countable, but since this is not guaranteed, implementations
* should gracefully handle the case in which the attr is not countable.
* @param attrName the name of the attr to increment
*/
fun incrementAttrValue(attrName: String)
/**
* Log an event. The optional [attrs] parameter will add specific
* attributes for this event only.
* @param eventName the name of the event to add
* @param attrs any extra attributes that should be added to this specific
* event
*/
fun addEvent(eventName: String, attrs: Map<String, String> = emptyMap())
/**
* Log a timed operation given the arguments passed in.
* > Note: This is about user behavior--not about application performance.
* > A possible use case would be to start a timed operation when the user
* > views a screen, and then commit that timed operation when the user
* > leaves a screen.
* @param operationName The name of the operation--doubles as the event
* name.
* @param startTimeMillis The time the timed operation was started.
* @param endTimeMillis The time the timed operation ended.
* @param durationAttrName The name of the duration attr--will be ignored
* if null
* @param startTimeMillisAttrName The name of the start time millis attr--
* will be ignored if null
* @param endTimeMillisAttrName The name of the end timem millis attr--will
* be ignored if null
* @param startAttrs The attrs that were stored when the timed operation
* was started
* @param endAttrs The attrs that were added when the timed operation was
* completed.
*/
fun sendTimedOperation(
operationName: String,
startTimeMillis: Long,
endTimeMillis: Long,
durationAttrName: String? = null,
startTimeMillisAttrName: String? = null,
endTimeMillisAttrName: String? = null,
startAttrs: Map<String, String> = emptyMap(),
endAttrs: Map<String, String> = emptyMap()
) {
val durationAttrs = mutableMapOf<String, String>()
durationAttrName?.let { durationAttrs[it] = (endTimeMillis - startTimeMillis).toString() }
startTimeMillisAttrName?.let { durationAttrs[it] = startTimeMillis.toString() }
endTimeMillisAttrName?.let { durationAttrs[it] = endTimeMillis.toString() }
val attrs = startAttrs + endAttrs + durationAttrs
addEvent(operationName, attrs)
}
}
/**
* Add multiple attributes at one time in a map.
* > Note: Do not call this on your own. It is NOT threadsafe.
* @param attrs a map of attrName -> attrValue for all attributes to add
*/
fun FSEventLogger.addAttrs(attrs: Map<String, String>) {
attrs.entries.forEach { addAttr(it.key, it.value) }
}
/**
* Removes multiple attrs at one time.
* > Note: Do not call this on your own. It is NOT threadsafe.
* @param attrs an [Iterable] of the attr names to remove
*/
fun FSEventLogger.removeAttrs(attrNames: Iterable<String>) {
attrNames.forEach { removeAttr(it) }
}
/**
* Run on all when [keys] is empty and run on specific entries when [keys] is
* nonempty
* Threading: NOT thread safe
*
* does not crash when a key is not found
* @see onSomeOrAll to access via isolate state
*/
internal inline fun <T:Any> Map<String, T>.onSomeOrAll(keys: Array<out String>, block: T.() -> Unit) {
when {
keys.isEmpty() -> values.forEach { it.block() }
else -> keys.forEach { key -> get(key)?.block() }
}
}
internal fun <T:FSLogger> Map<String, T>.supportingTestEnvironment() = filterValues { it.runInTestEnvironment() }
internal expect fun createInitialDevMetricsLoggers(): MutableMap<String, FSDevMetricsLogger>
internal expect fun createInitialEventLoggers(): MutableMap<String, FSEventLogger> | 6 | Kotlin | 2 | 1 | dc0a32f3070e40068fc891cdd68607cf2be7f4bc | 7,971 | logging | Apache License 2.0 |
src/main/kotlin/me/steven/indrev/blockentities/miningrig/DrillBlockEntityRenderer.kt | GabrielOlvH | 265,247,813 | false | {"Gradle": 2, "Java Properties": 1, "Shell": 1, "Ignore List": 1, "Batchfile": 1, "Text": 1, "Markdown": 3, "INI": 1, "Java": 24, "JSON": 1480, "Kotlin": 365} | package me.steven.indrev.blockentities.drill
import me.steven.indrev.blocks.machine.DrillBlock
import me.steven.indrev.registry.IRItemRegistry
import me.steven.indrev.utils.identifier
import net.minecraft.client.MinecraftClient
import net.minecraft.client.render.OverlayTexture
import net.minecraft.client.render.RenderLayers
import net.minecraft.client.render.VertexConsumerProvider
import net.minecraft.client.render.WorldRenderer
import net.minecraft.client.render.block.entity.BlockEntityRenderer
import net.minecraft.client.util.ModelIdentifier
import net.minecraft.client.util.math.MatrixStack
import net.minecraft.util.math.Vec3f
class DrillBlockEntityRenderer : BlockEntityRenderer<DrillBlockEntity> {
override fun render(
entity: DrillBlockEntity,
tickDelta: Float,
matrices: MatrixStack?,
vertexConsumers: VertexConsumerProvider,
light: Int,
overlay: Int
) {
val variant = when (entity.inventory[0].item) {
IRItemRegistry.STONE_DRILL_HEAD -> "stone"
IRItemRegistry.IRON_DRILL_HEAD -> "iron"
IRItemRegistry.DIAMOND_DRILL_HEAD -> "diamond"
IRItemRegistry.NETHERITE_DRILL_HEAD -> "netherite"
else -> return
}
val model =
MinecraftClient.getInstance().bakedModelManager.getModel(ModelIdentifier(identifier("drill_head"), variant))
matrices?.run {
push()
val entry = peek()
translate(0.5, 0.0, 0.5)
if (entity.position <= 0.0 && entity.cachedState[DrillBlock.WORKING]) {
multiply(Vec3f.POSITIVE_Y.getDegreesQuaternion( (entity.world!!.time + tickDelta) * 12))
}
translate(-0.5, entity.position, -0.5)
MinecraftClient.getInstance().blockRenderManager.modelRenderer.render(
entry,
vertexConsumers.getBuffer(RenderLayers.getBlockLayer(entity.cachedState)),
null,
model,
-1f,
-1f,
-1f,
WorldRenderer.getLightmapCoordinates(entity.world, entity.pos),
OverlayTexture.DEFAULT_UV
)
pop()
}
}
override fun rendersOutsideBoundingBox(blockEntity: DrillBlockEntity?): Boolean = true
} | 54 | Kotlin | 56 | 192 | 012a1b83f39ab50a10d03ef3c1a8e2651e517053 | 2,324 | Industrial-Revolution | Apache License 2.0 |
feature/home/src/main/kotlin/com/skydoves/pokedex/compose/feature/home/PokedexHome.kt | skydoves | 786,132,659 | false | {"Kotlin": 168350} | /*
* Designed and developed by 2024 skydoves (<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 com.skydoves.pokedex.compose.feature.home
import android.content.res.Configuration
import androidx.compose.animation.AnimatedVisibility
import androidx.compose.animation.AnimatedVisibilityScope
import androidx.compose.animation.SharedTransitionScope
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.PaddingValues
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.lazy.grid.GridCells
import androidx.compose.foundation.lazy.grid.LazyVerticalGrid
import androidx.compose.foundation.lazy.grid.itemsIndexed
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material3.Card
import androidx.compose.material3.CardColors
import androidx.compose.material3.CardDefaults
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.platform.LocalInspectionMode
import androidx.compose.ui.platform.testTag
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.hilt.navigation.compose.hiltViewModel
import androidx.lifecycle.compose.collectAsStateWithLifecycle
import com.kmpalette.palette.graphics.Palette
import com.skydoves.landscapist.ImageOptions
import com.skydoves.landscapist.animation.crossfade.CrossfadePlugin
import com.skydoves.landscapist.components.rememberImageComponent
import com.skydoves.landscapist.glide.GlideImage
import com.skydoves.landscapist.palette.PalettePlugin
import com.skydoves.landscapist.placeholder.shimmer.Shimmer
import com.skydoves.landscapist.placeholder.shimmer.ShimmerPlugin
import com.skydoves.pokedex.compose.core.data.repository.home.FakeHomeRepository
import com.skydoves.pokedex.compose.core.designsystem.component.PokedexAppBar
import com.skydoves.pokedex.compose.core.designsystem.component.PokedexCircularProgress
import com.skydoves.pokedex.compose.core.designsystem.component.pokedexSharedElement
import com.skydoves.pokedex.compose.core.designsystem.theme.PokedexTheme
import com.skydoves.pokedex.compose.core.model.Pokemon
import com.skydoves.pokedex.compose.core.navigation.PokedexScreens
import com.skydoves.pokedex.compose.core.navigation.boundsTransform
import com.skydoves.pokedex.compose.core.navigation.currentComposeNavigator
import com.skydoves.pokedex.compose.core.preview.PokedexPreviewTheme
import com.skydoves.pokedex.compose.core.preview.PreviewUtils
import com.skydoves.pokedex.compose.designsystem.R
import kotlinx.collections.immutable.ImmutableList
import kotlinx.collections.immutable.toImmutableList
@Composable
fun SharedTransitionScope.PokedexHome(
animatedVisibilityScope: AnimatedVisibilityScope,
homeViewModel: HomeViewModel = hiltViewModel(),
) {
val uiState by homeViewModel.uiState.collectAsStateWithLifecycle()
val pokemonList by homeViewModel.pokemonList.collectAsStateWithLifecycle()
Column(modifier = Modifier.fillMaxSize()) {
PokedexAppBar()
HomeContent(
animatedVisibilityScope = animatedVisibilityScope,
uiState = uiState,
pokemonList = pokemonList.toImmutableList(),
fetchNextPokemonList = homeViewModel::fetchNextPokemonList,
)
}
}
@Composable
private fun SharedTransitionScope.HomeContent(
animatedVisibilityScope: AnimatedVisibilityScope,
uiState: HomeUiState,
pokemonList: ImmutableList<Pokemon>,
fetchNextPokemonList: () -> Unit,
) {
Box(modifier = Modifier.fillMaxSize()) {
val threadHold = 8
LazyVerticalGrid(
modifier = Modifier.testTag("PokedexList"),
columns = GridCells.Fixed(2),
contentPadding = PaddingValues(6.dp),
) {
itemsIndexed(items = pokemonList, key = { _, pokemon -> pokemon.name }) { index, pokemon ->
if ((index + threadHold) >= pokemonList.size && uiState != HomeUiState.Loading) {
fetchNextPokemonList()
}
PokemonCard(
animatedVisibilityScope = animatedVisibilityScope,
pokemon = pokemon,
)
}
}
if (uiState == HomeUiState.Loading) {
PokedexCircularProgress()
}
}
}
@Composable
private fun SharedTransitionScope.PokemonCard(
animatedVisibilityScope: AnimatedVisibilityScope,
pokemon: Pokemon,
) {
val composeNavigator = currentComposeNavigator
var palette by remember { mutableStateOf<Palette?>(null) }
val backgroundColor by palette.paletteBackgroundColor()
Card(
modifier = Modifier
.padding(6.dp)
.fillMaxWidth()
.testTag("Pokemon")
.clickable {
composeNavigator.navigate(PokedexScreens.Details.createRoute(pokemon = pokemon))
},
shape = RoundedCornerShape(14.dp),
colors = CardColors(
containerColor = backgroundColor,
contentColor = backgroundColor,
disabledContainerColor = backgroundColor,
disabledContentColor = backgroundColor,
),
elevation = CardDefaults.cardElevation(defaultElevation = 4.dp),
) {
GlideImage(
modifier = Modifier
.align(Alignment.CenterHorizontally)
.padding(top = 20.dp)
.size(120.dp)
.pokedexSharedElement(
isLocalInspectionMode = LocalInspectionMode.current,
state = rememberSharedContentState(key = "image-${pokemon.name}"),
animatedVisibilityScope = animatedVisibilityScope,
boundsTransform = boundsTransform,
),
imageModel = { pokemon.imageUrl },
imageOptions = ImageOptions(contentScale = ContentScale.Inside),
component = rememberImageComponent {
+CrossfadePlugin()
+ShimmerPlugin(
Shimmer.Resonate(
baseColor = Color.Transparent,
highlightColor = Color.LightGray,
),
)
if (!LocalInspectionMode.current) {
+PalettePlugin(
imageModel = pokemon.imageUrl,
useCache = true,
paletteLoadedListener = { palette = it },
)
}
},
previewPlaceholder = painterResource(
id = R.drawable.pokemon_preview,
),
)
Text(
modifier = Modifier
.align(Alignment.CenterHorizontally)
.fillMaxWidth()
.pokedexSharedElement(
isLocalInspectionMode = LocalInspectionMode.current,
state = rememberSharedContentState(key = "name-${pokemon.name}"),
animatedVisibilityScope = animatedVisibilityScope,
boundsTransform = boundsTransform,
)
.padding(12.dp),
text = pokemon.name,
color = PokedexTheme.colors.black,
textAlign = TextAlign.Center,
fontSize = 16.sp,
fontWeight = FontWeight.Bold,
)
}
}
@Preview
@Preview(uiMode = Configuration.UI_MODE_NIGHT_YES)
@Composable
private fun PokedexHomePreview() {
PokedexTheme {
SharedTransitionScope {
AnimatedVisibility(visible = true, label = "") {
PokedexHome(
animatedVisibilityScope = this,
homeViewModel = HomeViewModel(homeRepository = FakeHomeRepository()),
)
}
}
}
}
@Preview
@Preview(uiMode = Configuration.UI_MODE_NIGHT_YES)
@Composable
private fun HomeContentPreview() {
PokedexPreviewTheme { scope ->
HomeContent(
animatedVisibilityScope = scope,
uiState = HomeUiState.Idle,
pokemonList = PreviewUtils.mockPokemonList().toImmutableList(),
fetchNextPokemonList = { HomeViewModel(homeRepository = FakeHomeRepository()) },
)
}
}
| 3 | Kotlin | 93 | 705 | ee2148f0c52a3611fcbdc86849c1d39fdb0c099e | 8,757 | pokedex-compose | Apache License 2.0 |
app/src/main/java/com/cesarwillymc/mbcgroup/domain/usecase/auth/entities/AuthParams.kt | cesarwillymc | 719,282,528 | false | {"Kotlin": 161270} | package com.cesarwillymc.mbcgroup.domain.usecase.auth.entities
/**
* Created by <NAME> on 10/9/23.
* <EMAIL>
*
* IOWA, United States.
*/
data class AuthParams(
val email: String,
val password: String
)
| 0 | Kotlin | 0 | 1 | 603cc1d2c24c22dd833121b8430e8dd4841e91a1 | 216 | MBCGroup | Apache License 2.0 |
feature-staking-api/src/main/java/jp/co/soramitsu/staking/api/domain/model/StakingLedger.kt | soramitsu | 278,060,397 | false | null | package jp.co.soramitsu.feature_staking_api.domain.model
import jp.co.soramitsu.common.utils.sumByBigInteger
import jp.co.soramitsu.fearless_utils.runtime.AccountId
import java.math.BigInteger
class StakingLedger(
val stashId: AccountId,
val total: BigInteger,
val active: BigInteger,
val unlocking: List<UnlockChunk>,
val claimedRewards: List<BigInteger>
)
class UnlockChunk(val amount: BigInteger, val era: BigInteger)
fun StakingLedger.sumStaking(
condition: (chunk: UnlockChunk) -> Boolean
): BigInteger {
return unlocking
.filter { condition(it) }
.sumByBigInteger(UnlockChunk::amount)
}
fun UnlockChunk.isUnbondingIn(activeEraIndex: BigInteger) = era > activeEraIndex
fun UnlockChunk.isRedeemableIn(activeEraIndex: BigInteger) = era <= activeEraIndex
| 9 | null | 30 | 89 | 812c6ed5465d19a0616865cbba3e946d046720a1 | 806 | fearless-Android | Apache License 2.0 |
bpdm-common-test/src/main/kotlin/org/eclipse/tractusx/bpdm/test/config/SelfClientConfigProperties.kt | eclipse-tractusx | 526,621,398 | false | {"Kotlin": 1862616, "Smarty": 16503, "Dockerfile": 3902, "Java": 2019, "Shell": 1221} | /*******************************************************************************
* Copyright (c) 2021,2024 Contributors to the Eclipse Foundation
*
* See the NOTICE file(s) distributed with this work for additional
* information regarding copyright ownership.
*
* This program and the accompanying materials are made available under the
* terms of the Apache License, Version 2.0 which is available 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.
*
* SPDX-License-Identifier: Apache-2.0
******************************************************************************/
package org.eclipse.tractusx.bpdm.test.config
import org.eclipse.tractusx.bpdm.common.util.BpdmClientProperties
import org.eclipse.tractusx.bpdm.common.util.ClientConfigurationProperties
import org.springframework.boot.autoconfigure.security.oauth2.client.OAuth2ClientProperties
import org.springframework.boot.context.properties.ConfigurationProperties
@ConfigurationProperties(prefix = SelfClientConfigProperties.PREFIX)
data class SelfClientConfigProperties(
override val securityEnabled: Boolean = false,
override val baseUrl: String = "",
override val registration: OAuth2ClientProperties.Registration = OAuth2ClientProperties.Registration(),
override val provider: OAuth2ClientProperties.Provider = OAuth2ClientProperties.Provider()
) :BpdmClientProperties {
companion object {
const val PREFIX = "${ClientConfigurationProperties.PREFIX}.self"
}
override fun getId(): String = PREFIX
} | 13 | Kotlin | 15 | 6 | 2a4622c2405b6af23c560160f95233a080df75b8 | 1,835 | bpdm | Apache License 2.0 |
InkKotlinCommons/src/main/java/com/inlacou/inkkotlincommons/rx/observables/CombineSequentialObs.kt | inlacou | 400,138,100 | false | null | package com.inlacou.inkkotlincommons.rx.observables
import com.inlacou.inkkotlincommons.rx.observables.CombineSequentialObs.ErrorBehaviour.*
import io.reactivex.rxjava3.core.*
import io.reactivex.rxjava3.disposables.Disposable
/**
* Tries to execute the given Observable list in the order given. Has three behaviours for when an error is detected.
*
* StopSuccessfullyOnError - Stops with a success returning retrieved data
* StopWronglyOnError - Stops with an error returning error
* AlwaysTryAll - Execute all always, and return retrieved data with nulls instead when an error happened
*
*/
class CombineSequentialObs <T: Any> internal constructor(list: List<Observable<T>>, val errorBehaviour: ErrorBehaviour, val alwaysTryAllOnError: ((Throwable) -> Unit)? = null) : ObservableOnSubscribe<List<T?>> {
private var remaining: List<Observable<T>> = list
private var results: MutableList<T?> = mutableListOf()
private var currentDisposable: Disposable? = null
enum class ErrorBehaviour {
StopSuccessfullyOnError,
StopWronglyOnError,
AlwaysTryAll
}
override fun subscribe(emitter: ObservableEmitter<List<T?>>) {
recursive(emitter)
emitter.setCancellable { currentDisposable?.dispose() }
}
private fun recursive(emitter: ObservableEmitter<List<T?>>) {
if(remaining.isEmpty()) {
emitter.onNext(results)
emitter.onComplete()
return
}
val current = remaining.first()
remaining = remaining.takeLast(remaining.size-1)
currentDisposable = current.subscribe({
results.add(it)
},{
when(errorBehaviour) {
StopSuccessfullyOnError -> {
emitter.onNext(results)
emitter.onComplete()
}
StopWronglyOnError -> {
emitter.onError(it)
emitter.onComplete()
}
AlwaysTryAll -> {
results.add(null)
alwaysTryAllOnError?.invoke(it)
recursive(emitter)
}
}
}, {
recursive(emitter)
})
}
companion object {
fun <T: Any> create(list: List<Observable<T>>, errorBehaviour: ErrorBehaviour = AlwaysTryAll): Observable<List<T?>> {
return Observable.create(CombineSequentialObs(list, errorBehaviour))
}
}
} | 0 | Kotlin | 0 | 0 | cb3457b74f5bd966840e880cd37c61dc981c3c47 | 2,498 | InkCommons | MIT License |
app/src/main/java/com/visal/harrypotter/data/api/AllCharactersApiService.kt | VisalSuresh90 | 714,848,696 | false | {"Kotlin": 136505} | package com.visal.harrypotter.data.api
import com.visal.harrypotter.data.model.HpCharacter
import retrofit2.Response
import retrofit2.http.GET
/**
* Retrofit API service interface for fetching information about all characters.
*/
interface AllCharactersApiService {
/**
* Fetches a list of all characters from the API.
*
* @return A Retrofit Response containing a list of Harry Potter characters.
*/
@GET("/api/characters")
suspend fun getAllCharacters(): Response<List<HpCharacter>>
}
| 0 | Kotlin | 0 | 0 | ec3236bf29f452339fc7b5a00b78f43b169cdb83 | 522 | harry-potter--android-jetpack-compose-hilt-mvvm-coroutine-modular | MIT License |
cli/src/org/partiql/cli/main.kt | partiql | 186,474,394 | false | null | /*
* Copyright 2019 Amazon.com, Inc. or its affiliates. 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.
* A copy of the License is located at:
*
* http://aws.amazon.com/apache2.0/
*
* or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific
* language governing permissions and limitations under the License.
*/
@file:JvmName("Main")
package org.partiql.cli
import com.amazon.ion.system.IonSystemBuilder
import joptsimple.OptionParser
import joptsimple.BuiltinHelpFormatter
import joptsimple.OptionDescriptor
import joptsimple.OptionException
import joptsimple.OptionSet
import org.partiql.cli.functions.ReadFile
import org.partiql.cli.functions.WriteFile
import org.partiql.lang.CompilerPipeline
import org.partiql.lang.eval.EvaluationSession
import org.partiql.lang.eval.ExprValueFactory
import org.partiql.lang.eval.Bindings
import org.partiql.lang.eval.ExprValue
import org.partiql.lang.syntax.SqlParser
import java.io.File
import java.io.FileInputStream
import java.io.FileOutputStream
import kotlin.system.exitProcess
// TODO how can a user pass the catalog here?
private val ion = IonSystemBuilder.standard().build()
private val valueFactory = ExprValueFactory.standard(ion)
private val parser = SqlParser(ion)
private val compilerPipeline = CompilerPipeline.build(ion) {
addFunction(ReadFile(valueFactory))
addFunction(WriteFile(valueFactory))
}
private val optParser = OptionParser()
private val formatter = object : BuiltinHelpFormatter(120, 2) {
override fun format(options: MutableMap<String, out OptionDescriptor>?): String {
return """PartiQL CLI
|Command line interface for executing PartiQL queries. Can be run in an interactive (REPL) mode or non-interactive.
|
|Examples:
|To run in REPL mode simply execute the executable without any arguments:
| partiql
|
|In non-interactive mode we use Ion as the format for input data which is bound to a global variable
|named "input_data", in the example below /logs/log.ion is bound to "input_data":
| partiql --query="SELECT * FROM input_data" --input=/logs/log.ion
|
|The cli can output using PartiQL syntax or Ion using the --output-format option, e.g. to output binary ion:
| partiql --query="SELECT * FROM input_data" --output-format=ION_BINARY --input=/logs/log.ion
|
|To pipe input data in via stdin:
| cat /logs/log.ion | partiql --query="SELECT * FROM input_data" --format=ION_BINARY > output.10n
|
|${super.format(options)}
""".trimMargin()
}
}
enum class OutputFormat {
ION_TEXT, ION_BINARY, PARTIQL, PARTIQL_PRETTY
}
// opt parser options
private val helpOpt = optParser.acceptsAll(listOf("help", "h"), "prints this help")
.forHelp()
private val queryOpt = optParser.acceptsAll(listOf("query", "q"), "PartiQL query, triggers non interactive mode")
.withRequiredArg()
.ofType(String::class.java)
private val environmentOpt = optParser.acceptsAll(listOf("environment", "e"), "initial global environment (optional)")
.withRequiredArg()
.ofType(File::class.java)
private val inputFileOpt = optParser.acceptsAll(listOf("input", "i"), "input file, requires the query option (default: stdin)")
.availableIf(queryOpt)
.withRequiredArg()
.ofType(File::class.java)
private val outputFileOpt = optParser.acceptsAll(listOf("output", "o"), "output file, requires the query option (default: stdout)")
.availableIf(queryOpt)
.withRequiredArg()
.ofType(File::class.java)
private val outputFormatOpt = optParser.acceptsAll(listOf("output-format", "of"), "output format, requires the query option")
.availableIf(queryOpt)
.withRequiredArg()
.ofType(OutputFormat::class.java)
.describedAs("(${OutputFormat.values().joinToString("|")})")
.defaultsTo(OutputFormat.PARTIQL)
/**
* Runs PartiQL CLI.
*
* Has two modes:
* * Interactive (default): Starts a REPL
* * Non-interactive: takes in an PartiQL query as a command line input
*
* Options:
* * -e --environment: takes an environment file to load as the initial global environment
* * Non interactive only:
* * -q --query: PartiQL query
* * -i --input: input file, default STDIN
* * -o --output: output file, default STDOUT
* * -of --output-format: ION_TEXT, ION_BINARY, PARTIQL (default), PARTIQL_PRETTY
*/
fun main(args: Array<String>) = try {
optParser.formatHelpWith(formatter)
val optionSet = optParser.parse(*args)
if (optionSet.has(helpOpt)) {
optParser.printHelpOn(System.out)
System.exit(0) // print help and bail
}
if(optionSet.nonOptionArguments().isNotEmpty()) {
throw IllegalArgumentException("Non option arguments are not allowed!")
}
// common options
val environment = when {
optionSet.has(environmentOpt) -> {
val configSource = optionSet.valueOf(environmentOpt).readText(charset("UTF-8"))
val config = compilerPipeline.compile(configSource).eval(EvaluationSession.standard())
config.bindings
}
else -> Bindings.empty()
}
if (optionSet.has(queryOpt)) {
runCli(environment, optionSet)
}
else {
runRepl(environment)
}
}
catch (e: OptionException) {
System.err.println("${e.message}\n")
optParser.printHelpOn(System.err)
exitProcess(1)
}
catch (e: Exception) {
e.printStackTrace(System.err)
exitProcess(1)
}
private fun runRepl(environment: Bindings<ExprValue>) {
Repl(valueFactory, System.`in`, System.out, parser, compilerPipeline, environment).run()
}
private fun runCli(environment: Bindings<ExprValue>, optionSet: OptionSet) {
val input = if (optionSet.has(inputFileOpt)) {
FileInputStream(optionSet.valueOf(inputFileOpt))
}
else {
EmptyInputStream()
}
val output = if (optionSet.has(outputFileOpt)) {
FileOutputStream(optionSet.valueOf(outputFileOpt))
}
else {
UnclosableOutputStream(System.out)
}
val format = optionSet.valueOf(outputFormatOpt)
val query = optionSet.valueOf(queryOpt)
input.use {
output.use {
Cli(valueFactory, input, output, format, compilerPipeline, environment, query).run()
}
}
}
| 188 | null | 53 | 501 | dfe9129822135185757678bcf6d1dc094cd78f38 | 6,723 | partiql-lang-kotlin | Apache License 2.0 |
src/main/kotlin/com/yapp/web2/util/ExceptionMessage.kt | YAPP-19th | 399,059,127 | false | null | package com.yapp.web2.util
class ExceptionMessage {
companion object {
const val FOLDER_NOT_FOUND = "존재하지 않는 폴더입니다."
const val BOOKMARK_NOT_FOUND = "존재하지 않는 북마크입니다."
const val ACCOUNT_NOT_EXIST = "존재하지 않는 계정입니다."
const val REMIND_CYCLE_VALID_EXCEPTION = "정확한 주기 일자를 입력해주세요."
const val FOLDER_SIZE_EXCEED_EXCEPTION = "하위 폴더는 최대 8개까지 생성을 할 수 있습니다."
const val FOLDER_IS_NOT_ROOT = "보관함이 아닙니다."
const val AlREADY_INVITED = "이미 초대되었습니다."
const val NO_PERMISSION = "권한이 없습니다."
const val NOT_SAME_ROOT_FOLDER = "동일한 보관함이 아닙니다."
const val PASSWORD_DIFFERENT_EXCEPTION = "비밀번호가 일치하지 않습니다."
const val NOT_FOUND_EMAIL = "가입하신 이메일 주소를 찾을 수 없습니다."
const val ALREADY_EXIST_REMIND = "이미 리마인드가 존재합니다."
}
} | 10 | Kotlin | 1 | 7 | ecc6a3da2a66dceb1a25a4cfe9ed699f0325180a | 806 | Web-Team-2-Backend | Apache License 2.0 |
processor-shared-code/src/main/kotlin/br/com/zup/beagle/compiler/shared/BeagleClass.kt | ZupIT | 391,144,851 | false | null | /*
* Copyright 2020 ZUP IT SERVICOS EM TECNOLOGIA E INOVACAO SA
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package br.com.zup.beagle.compiler.util
data class BeagleClass(
val packageName: String,
val className: String
) {
override fun toString(): String {
return "$packageName.$className"
}
} | 1 | null | 2 | 9 | 812a330777edd79a123495e9f678dc8f25a019f7 | 838 | beagle-android | Apache License 2.0 |
app/src/androidTest/java/com/steleot/jetpackcompose/playground/compose/viewmodel/ViewModelFlowScreenTest.kt | Vivecstel | 338,792,534 | false | null | package com.steleot.jetpackcompose.playground.compose.viewmodel
import androidx.compose.ui.test.junit4.createAndroidComposeRule
import com.steleot.jetpackcompose.playground.MainActivity
import com.steleot.jetpackcompose.playground.compose.theme.TestTheme
import org.junit.Rule
import org.junit.Test
class ViewModelFlowScreenTest {
@get:Rule
val composeTestRule = createAndroidComposeRule<MainActivity>()
@Test
fun testViewModelFlowScreen() {
composeTestRule.setContent {
TestTheme {
// ViewModelFlowScreen()
}
}
// todo
}
} | 0 | null | 16 | 161 | d853dddc7b00735dc9067f3325a2662977a01348 | 610 | Jetpack-Compose-Playground | Apache License 2.0 |
privacysandbox/tools/tools-apicompiler/src/test/test-data/fullfeaturedsdk/output/com/mysdk/MyCallbackClientProxy.kt | androidx | 256,589,781 | false | null | package com.mysdk
import android.content.Context
import androidx.privacysandbox.ui.provider.toCoreLibInfo
public class MyCallbackClientProxy(
public val remote: IMyCallback,
public val context: Context,
) : MyCallback {
public override fun onComplete(response: Response): Unit {
remote.onComplete(ResponseConverter(context).toParcelable(response))
}
public override fun onClick(x: Int, y: Int): Unit {
remote.onClick(x, y)
}
public override fun onCompleteInterface(myInterface: MyInterface): Unit {
remote.onCompleteInterface(MyInterfaceStubDelegate(myInterface, context))
}
public override fun onCompleteUiInterface(myUiInterface: MyUiInterface): Unit {
remote.onCompleteUiInterface(IMyUiInterfaceCoreLibInfoAndBinderWrapperConverter.toParcelable(myUiInterface.toCoreLibInfo(context),
MyUiInterfaceStubDelegate(myUiInterface, context)))
}
}
| 16 | null | 787 | 4,563 | 2c8f7ee9eb6bd033a33c2cf8e22b21dd953accac | 935 | androidx | Apache License 2.0 |
app/src/main/java/vn/loitp/app/activity/database/realm/InputCallback.kt | tplloi | 126,578,283 | false | null | package vn.loitp.app.activity.database.realm
interface InputCallback {
fun onText(text: String?)
}
| 0 | Kotlin | 0 | 6 | 55fb45b20a95b924d74f364ecad5101235eba7b8 | 104 | basemaster | Apache License 2.0 |
app/src/main/java/com/batdemir/template/ui/github/detail/GithubDetailViewModel.kt | batdemir | 332,173,381 | false | null | package com.batdemir.template.ui.github.detail
import com.batdemir.template.core.vm.BaseViewModel
import dagger.hilt.android.lifecycle.HiltViewModel
import javax.inject.Inject
@HiltViewModel
class GithubDetailViewModel @Inject constructor() : BaseViewModel() | 0 | Kotlin | 1 | 4 | ec88f6cdcab230886923f67c4f921aa03b591019 | 260 | kotlin.template.project | Apache License 2.0 |
app/src/main/java/com/example/android/architecture/blueprints/todoapp/di/DataModules.kt | Shamans117 | 92,913,354 | true | {"Kotlin": 221078} | /*
* Copyright 2022 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.example.android.architecture.blueprints.todoapp.di
import android.content.Context
import androidx.room.Room
import com.example.android.architecture.blueprints.todoapp.data.DefaultTasksRepository
import com.example.android.architecture.blueprints.todoapp.data.TasksRepository
import com.example.android.architecture.blueprints.todoapp.data.source.local.ToDoDatabase
import com.example.android.architecture.blueprints.todoapp.data.source.network.NetworkDataSource
import com.example.android.architecture.blueprints.todoapp.data.source.network.TasksNetworkDataSource
import dagger.Module
import dagger.Provides
import dagger.hilt.InstallIn
import dagger.hilt.android.qualifiers.ApplicationContext
import dagger.hilt.components.SingletonComponent
import javax.inject.Qualifier
import javax.inject.Singleton
@Qualifier
@Retention(AnnotationRetention.RUNTIME)
annotation class RemoteTasksDataSource
@Module
@InstallIn(SingletonComponent::class)
object RepositoryModule {
@Singleton
@Provides
fun provideTasksRepository(
@RemoteTasksDataSource remoteDataSource: NetworkDataSource,
database: ToDoDatabase,
): TasksRepository {
return DefaultTasksRepository(remoteDataSource, database.taskDao())
}
}
@Module
@InstallIn(SingletonComponent::class)
object DataSourceModule {
@Singleton
@RemoteTasksDataSource
@Provides
fun provideTasksRemoteDataSource(): NetworkDataSource = TasksNetworkDataSource
}
@Module
@InstallIn(SingletonComponent::class)
object DatabaseModule {
@Singleton
@Provides
fun provideDataBase(@ApplicationContext context: Context): ToDoDatabase {
return Room.databaseBuilder(
context.applicationContext,
ToDoDatabase::class.java,
"Tasks.db"
).build()
}
}
| 0 | Kotlin | 0 | 0 | d59e591d00fd37c7ec0ac729120fb3378b3479b2 | 2,426 | android-architecture | Apache License 2.0 |
analysis/analysis-api-impl-base/tests/org/jetbrains/kotlin/analysis/api/impl/base/test/cases/types/AbstractTypeByDeclarationReturnTypeTest.kt | JetBrains | 3,432,266 | false | null | /*
* Copyright 2010-2022 JetBrains s.r.o. and Kotlin Programming Language contributors.
* Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file.
*/
package org.jetbrains.kotlin.analysis.api.impl.base.test.cases.types
import org.jetbrains.kotlin.analysis.api.KaSession
import org.jetbrains.kotlin.analysis.api.types.KaType
import org.jetbrains.kotlin.analysis.test.framework.project.structure.KtTestModule
import org.jetbrains.kotlin.analysis.test.framework.services.expressionMarkerProvider
import org.jetbrains.kotlin.psi.KtDeclaration
import org.jetbrains.kotlin.psi.KtFile
import org.jetbrains.kotlin.test.services.TestServices
abstract class AbstractTypeByDeclarationReturnTypeTest : AbstractTypeTest() {
override fun getType(analysisSession: KaSession, ktFile: KtFile, module: KtTestModule, testServices: TestServices): KaType {
with(analysisSession) {
val declarationAtCaret = testServices.expressionMarkerProvider.getElementOfTypeAtCaret<KtDeclaration>(ktFile)
return declarationAtCaret.getReturnKaType()
}
}
} | 181 | null | 5748 | 49,172 | 33eb9cef3d146062c103f9853d772f0a1da0450e | 1,129 | kotlin | Apache License 2.0 |
client/app/src/main/java/edu/festival/deichkind/models/AuthResponse.kt | festivaledu | 182,123,389 | false | null | package edu.festival.deichkind.models
class AuthResponse {
var auth: Boolean = false
var token: String = ""
var refreshToken: String = ""
var role: Int = 0
} | 1 | Kotlin | 0 | 0 | ccfb0302777285b4a2d58df1c3565108ba5cb3e3 | 176 | Deichkind | MIT License |
client/app/src/main/java/edu/festival/deichkind/models/AuthResponse.kt | festivaledu | 182,123,389 | false | null | package edu.festival.deichkind.models
class AuthResponse {
var auth: Boolean = false
var token: String = ""
var refreshToken: String = ""
var role: Int = 0
} | 1 | Kotlin | 0 | 0 | ccfb0302777285b4a2d58df1c3565108ba5cb3e3 | 176 | Deichkind | MIT License |
core-navigation/src/main/java/com/riyusoft/todo/core/navigation/TopLevelDestination.kt | jeonhoeun | 520,344,732 | false | {"Kotlin": 70352, "Shell": 578, "HTML": 509} | package com.riyusoft.todo.core.navigation
data class TopLevelDestination(
override val route: String,
override val destination: String,
) : TodoNavigationDestination
| 1 | Kotlin | 0 | 0 | 175e250d1e53da29ce8b9bb5e4f24ae513d9404b | 175 | aos-todo-cleanarch-compose-tdd | MIT License |
shared/src/commonTest/kotlin/me/saket/press/shared/db/FolderQueriesTest.kt | maxkeppeler | 323,609,665 | true | {"Kotlin": 532437, "Swift": 36689, "Ruby": 5783} | package me.saket.press.shared.db
import assertk.assertThat
import me.saket.press.shared.containsOnly
import me.saket.press.shared.fakedata.fakeFolder
import me.saket.press.shared.fakedata.fakeNote
import me.saket.press.shared.syncer.git.insert
import me.saket.press.shared.syncer.git.testInsert
import kotlin.test.Test
class FolderQueriesTest : BaseDatabaeTest() {
private val noteQueries get() = database.noteQueries
private val folderQueries get() = database.folderQueries
@Test fun `non empty folders`() {
val folder1 = fakeFolder("folder1")
val folder2 = fakeFolder("folder2")
val folder3 = fakeFolder("folder3")
folderQueries.insert(folder1, folder2, folder3)
noteQueries.testInsert(
fakeNote("Note 1", folderId = folder1.id),
fakeNote("Note 2", folderId = folder1.id),
fakeNote("Note 3", folderId = folder2.id),
fakeNote("Note 4", folderId = folder3.id, isPendingDeletion = true),
fakeNote("", folderId = folder3.id),
fakeNote("# ", folderId = folder3.id),
fakeNote("Note 5"),
)
val nonEmptyFolders = folderQueries.nonEmptyFoldersUnder(parent = null).executeAsList().map { it.name }
assertThat(nonEmptyFolders).containsOnly(
"folder1",
"folder2"
)
}
}
| 1 | null | 1 | 0 | a9ab0d5c3bdde1988d14e8b51beb950cd12bf1f0 | 1,261 | press | Apache License 2.0 |
app/src/main/java/com/utn/MascotApp/Pet.kt | UTN-FRBA-Mobile | 365,539,532 | false | null | package com.utn.MascotApp
import com.google.android.gms.maps.model.LatLng
data class Pet(
val name: String,
val latLng: LatLng,
val address: String,
val rating: Float
) | 0 | Kotlin | 2 | 0 | 5ea8c9046243924b24801d46a61bfd72562765ce | 188 | MascotApp | MIT License |
client/android/sample/src/main/java/com/yandex/divkit/sample/MainPageActivity.kt | divkit | 523,491,444 | false | {"Kotlin": 7327303, "Swift": 5164616, "Svelte": 1148832, "TypeScript": 912803, "Dart": 630920, "Python": 536031, "Java": 507940, "JavaScript": 152546, "CSS": 37870, "HTML": 23434, "C++": 20911, "CMake": 18677, "Shell": 8895, "PEG.js": 7210, "Ruby": 3723, "C": 1425, "Objective-C": 38} | package com.yandex.divkit.sample
import android.os.Bundle
import androidx.appcompat.app.AppCompatActivity
import com.yandex.div.core.Div2Context
import com.yandex.div.core.DivConfiguration
import com.yandex.div.picasso.PicassoDivImageLoader
import com.yandex.div.rive.OkHttpDivRiveNetworkDelegate
import com.yandex.div.rive.RiveCustomViewAdapter
import com.yandex.divkit.sample.databinding.ActivityMainPageBinding
import com.yandex.div.zoom.DivPinchToZoomConfiguration
import com.yandex.div.zoom.DivPinchToZoomExtensionHandler
import okhttp3.OkHttpClient
class MainPageActivity : AppCompatActivity() {
private lateinit var binding: ActivityMainPageBinding
private val assetReader = AssetReader(this)
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = ActivityMainPageBinding.inflate(layoutInflater)
setContentView(binding.root)
setSupportActionBar(findViewById(R.id.toolbar))
binding.toolbarLayout.title = title
val divJson = assetReader.read("sample.json")
val templatesJson = divJson.optJSONObject("templates")
val cardJson = divJson.getJSONObject("card")
val divContext = Div2Context(
baseContext = this,
configuration = createDivConfiguration(),
lifecycleOwner = this
)
val divView = Div2ViewFactory(divContext, templatesJson).createView(cardJson)
binding.list.addView(divView)
}
private fun createDivConfiguration(): DivConfiguration {
return DivConfiguration.Builder(PicassoDivImageLoader(this))
.actionHandler(SampleDivActionHandler())
.extension(
DivPinchToZoomExtensionHandler(
DivPinchToZoomConfiguration.Builder(this).build()
)
)
.divCustomContainerViewAdapter(RiveCustomViewAdapter.Builder(this, OkHttpDivRiveNetworkDelegate(OkHttpClient.Builder().build())).build())
.visualErrorsEnabled(true)
.build()
}
}
| 5 | Kotlin | 128 | 2,240 | dd102394ed7b240ace9eaef9228567f98e54d9cf | 2,064 | divkit | Apache License 2.0 |
app/src/main/java/com/example/rabbitapp/ui/mainTab/mainList/MainListFragment.kt | AgnieszkaKlobus12 | 604,315,829 | false | {"Kotlin": 75601} | package com.example.rabbitapp.ui.mainTab.mainList
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.Fragment
import androidx.fragment.app.activityViewModels
import androidx.navigation.findNavController
import com.example.rabbitapp.R
import com.example.rabbitapp.databinding.FragmentMainListBinding
import com.example.rabbitapp.model.entities.HomeListItem
import com.example.rabbitapp.model.entities.Litter
import com.example.rabbitapp.model.entities.Rabbit
import com.example.rabbitapp.ui.mainTab.MainListViewModel
class MainListFragment : Fragment() {
private var _binding: FragmentMainListBinding? = null
private val binding get() = _binding!!
private val mainListViewModel: MainListViewModel by activityViewModels()
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View {
_binding = FragmentMainListBinding.inflate(inflater, container, false)
return binding.root
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
mainListViewModel.clearSelected()
binding.fragmentHomeListInclude.fragmentListRecyclerView.adapter =
MainListAdapter(mainListViewModel.getAll(), object : OnSelectedItem {
override fun onItemClick(item: HomeListItem) {
if (item is Rabbit) {
mainListViewModel.selectedRabbit = item
view.findNavController()
.navigate(R.id.action_navigation_home_to_rabbitDetailsFragment)
} else {
mainListViewModel.selectedLitter = item as Litter
view.findNavController()
.navigate(R.id.action_navigation_home_to_litterDetailsFragment)
}
}
})
binding.addNewMainButton.setOnClickListener(showFloatingAddButtons())
binding.addRabbitButton.setOnClickListener(moveToAddRabbit())
binding.addLitterButton.setOnClickListener(moveToAddLitter())
}
override fun onDestroyView() {
super.onDestroyView()
_binding = null
}
private fun showFloatingAddButtons(): View.OnClickListener {
return View.OnClickListener {
if (binding.addLitterButton.visibility == View.GONE) {
binding.addLitterButton.visibility = View.VISIBLE
} else {
binding.addLitterButton.visibility = View.GONE
}
if (binding.addRabbitButton.visibility == View.GONE) {
binding.addRabbitButton.visibility = View.VISIBLE
} else {
binding.addRabbitButton.visibility = View.GONE
}
}
}
private fun moveToAddRabbit(): View.OnClickListener {
return View.OnClickListener { view ->
view.findNavController().navigate(R.id.action_navigation_home_to_addRabbitFragment)
}
}
private fun moveToAddLitter(): View.OnClickListener {
return View.OnClickListener { view ->
view.findNavController().navigate(R.id.action_navigation_home_to_addLitterFragment)
}
}
} | 0 | Kotlin | 0 | 1 | ce637a9a0112573293460ae1f74ca6beab779a87 | 3,365 | RabbitApp | MIT License |
matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/database/model/PendingThreePidEntity.kt | matrix-org | 287,466,066 | false | null | /*
* Copyright 2020 The Matrix.org Foundation C.I.C.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.matrix.android.sdk.internal.database.model
import io.realm.RealmObject
/**
* This class is used to store pending threePid data, when user wants to add a threePid to his account.
*/
internal open class PendingThreePidEntity(
var email: String? = null,
var msisdn: String? = null,
var clientSecret: String = "",
var sendAttempt: Int = 0,
var sid: String = "",
var submitUrl: String? = null
) : RealmObject()
| 75 | null | 6 | 97 | 55cc7362de34a840c67b4bbb3a14267bc8fd3b9c | 1,083 | matrix-android-sdk2 | Apache License 2.0 |
src/com/github/felipehjcosta/adapters/infrastructure/MD5.kt | felipehjcosta | 163,593,322 | false | null | package com.github.felipehjcosta.adapters.infrastructure
fun String.toMD5(): String {
val messageDigest = java.security.MessageDigest.getInstance("MD5")
val digested = messageDigest.digest(toByteArray())
return digested.joinToString("") { String.format("%02x", it) }
}
| 0 | Kotlin | 0 | 0 | 3b4aaf4dd8639090e60d00d5261a41ec37c2f762 | 282 | marvelql | MIT License |
app/src/main/java/com/example/myapplication/MainActivity.kt | yo-lolo | 660,058,834 | false | null | package com.example.myapplication
import android.Manifest
import android.content.Context
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.os.Handler
import android.util.Log
import android.widget.Toast
import com.blankj.utilcode.util.ActivityUtils
import com.blankj.utilcode.util.PermissionUtils
import com.example.myapplication.base.BaseActivity
import com.example.myapplication.databinding.ActivityMainBinding
import com.example.myapplication.ui.MarketActivity
class MainActivity : BaseActivity() {
private lateinit var activityMainBinding: ActivityMainBinding
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
activityMainBinding = ActivityMainBinding.inflate(layoutInflater)
setContentView(activityMainBinding.root)
toMyApplicationPage()
}
private fun toMyApplicationPage() {
checkPermissions(
arrayOf(
Manifest.permission.READ_PHONE_STATE,
Manifest.permission.ACCESS_FINE_LOCATION,
Manifest.permission.WRITE_EXTERNAL_STORAGE,
Manifest.permission.READ_EXTERNAL_STORAGE,
Manifest.permission.BLUETOOTH, Manifest.permission.BLUETOOTH_ADMIN
)
) {
/**
* 权限check完成后 执行如下: 1.通过自动登录标识 判断是否要进入登录界面
*/
ActivityUtils.startActivity(MarketActivity::class.java)
finish()
}
}
private fun checkPermissions(
permisssions: Array<String>,
listener: () -> Unit
) {
PermissionUtils.permission(*permisssions)
.callback(object : PermissionUtils.FullCallback {
override fun onGranted(granted: MutableList<String>) {
listener.invoke()
}
override fun onDenied(
deniedForever: MutableList<String>,
denied: MutableList<String>
) {
if (deniedForever.size > 0) {
Toast.makeText(
MainActivity@ this as Context,
"权限被永久拒绝,即将跳转权限设置界面,同意后可以正常使用",
Toast.LENGTH_SHORT
).show()
Handler().postDelayed({ // 如果是被永久拒绝就跳转到应用权限系统设置页面
PermissionUtils.launchAppDetailsSettings()
}, 1000)
Log.i(
TAG,
deniedForever.toString() + "权限被永久拒绝,请前往设置界面允许权限"
)
} else {
Log.i(
TAG,
denied.toString() + "权限获取失败"
)
}
}
})
.request()
}
companion object {
val TAG: String = MainActivity::class.java.simpleName
}
} | 0 | Kotlin | 0 | 0 | 1dc11d6c31a8f2eae1a417042d350124fc3dc2da | 2,989 | yolo | Apache License 2.0 |
app/src/main/java/com/example/myapplication/MainActivity.kt | yo-lolo | 660,058,834 | false | null | package com.example.myapplication
import android.Manifest
import android.content.Context
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.os.Handler
import android.util.Log
import android.widget.Toast
import com.blankj.utilcode.util.ActivityUtils
import com.blankj.utilcode.util.PermissionUtils
import com.example.myapplication.base.BaseActivity
import com.example.myapplication.databinding.ActivityMainBinding
import com.example.myapplication.ui.MarketActivity
class MainActivity : BaseActivity() {
private lateinit var activityMainBinding: ActivityMainBinding
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
activityMainBinding = ActivityMainBinding.inflate(layoutInflater)
setContentView(activityMainBinding.root)
toMyApplicationPage()
}
private fun toMyApplicationPage() {
checkPermissions(
arrayOf(
Manifest.permission.READ_PHONE_STATE,
Manifest.permission.ACCESS_FINE_LOCATION,
Manifest.permission.WRITE_EXTERNAL_STORAGE,
Manifest.permission.READ_EXTERNAL_STORAGE,
Manifest.permission.BLUETOOTH, Manifest.permission.BLUETOOTH_ADMIN
)
) {
/**
* 权限check完成后 执行如下: 1.通过自动登录标识 判断是否要进入登录界面
*/
ActivityUtils.startActivity(MarketActivity::class.java)
finish()
}
}
private fun checkPermissions(
permisssions: Array<String>,
listener: () -> Unit
) {
PermissionUtils.permission(*permisssions)
.callback(object : PermissionUtils.FullCallback {
override fun onGranted(granted: MutableList<String>) {
listener.invoke()
}
override fun onDenied(
deniedForever: MutableList<String>,
denied: MutableList<String>
) {
if (deniedForever.size > 0) {
Toast.makeText(
MainActivity@ this as Context,
"权限被永久拒绝,即将跳转权限设置界面,同意后可以正常使用",
Toast.LENGTH_SHORT
).show()
Handler().postDelayed({ // 如果是被永久拒绝就跳转到应用权限系统设置页面
PermissionUtils.launchAppDetailsSettings()
}, 1000)
Log.i(
TAG,
deniedForever.toString() + "权限被永久拒绝,请前往设置界面允许权限"
)
} else {
Log.i(
TAG,
denied.toString() + "权限获取失败"
)
}
}
})
.request()
}
companion object {
val TAG: String = MainActivity::class.java.simpleName
}
} | 0 | Kotlin | 0 | 0 | 1dc11d6c31a8f2eae1a417042d350124fc3dc2da | 2,989 | yolo | Apache License 2.0 |
libnavigation-util/src/test/java/com/mapbox/navigation/utils/internal/MapboxTimerTest.kt | k4anubhav | 439,334,238 | true | {"Kotlin": 4189704, "Java": 26254, "Python": 11580, "Makefile": 6163, "Shell": 5704} | package com.mapbox.navigation.utils.timer
import com.mapbox.navigation.testing.MainCoroutineRule
import io.mockk.Called
import io.mockk.coVerify
import io.mockk.mockk
import java.util.concurrent.TimeUnit
import kotlinx.coroutines.ExperimentalCoroutinesApi
import kotlinx.coroutines.cancelAndJoin
import org.junit.Rule
import org.junit.Test
@ExperimentalCoroutinesApi
class MapboxTimerTest {
@get:Rule
val coroutineRule = MainCoroutineRule()
private val mapboxTimer = MapboxTimer()
private val mockLambda: () -> Unit = mockk(relaxed = true)
@Test
fun `should not call before interval`() = coroutineRule.runBlockingTest {
mapboxTimer.restartAfterMillis = TimeUnit.MINUTES.toMillis(5)
val job = mapboxTimer.startTimer(mockLambda)
coroutineRule.testDispatcher.advanceTimeBy(TimeUnit.MINUTES.toMillis(4))
job.cancelAndJoin()
coVerify { mockLambda wasNot Called }
}
@Test
fun `should call after interval`() = coroutineRule.runBlockingTest {
mapboxTimer.restartAfterMillis = TimeUnit.MINUTES.toMillis(5)
val job = mapboxTimer.startTimer(mockLambda)
coroutineRule.testDispatcher.advanceTimeBy(TimeUnit.MINUTES.toMillis(6))
job.cancelAndJoin()
coVerify(exactly = 1) { mockLambda.invoke() }
}
@Test
fun `should call after multiple times`() = coroutineRule.runBlockingTest {
mapboxTimer.restartAfterMillis = TimeUnit.MINUTES.toMillis(5)
val job = mapboxTimer.startTimer(mockLambda)
coroutineRule.testDispatcher.advanceTimeBy(TimeUnit.MINUTES.toMillis(26))
job.cancelAndJoin()
coVerify(exactly = 5) { mockLambda.invoke() }
}
@Test
fun `should update interval dynamically`() = coroutineRule.runBlockingTest {
mapboxTimer.restartAfterMillis = TimeUnit.MINUTES.toMillis(1)
val job = mapboxTimer.startTimer(mockLambda)
coroutineRule.testDispatcher.advanceTimeBy(TimeUnit.MINUTES.toMillis(1))
mapboxTimer.restartAfterMillis = TimeUnit.MINUTES.toMillis(10)
coroutineRule.testDispatcher.advanceTimeBy(TimeUnit.MINUTES.toMillis(10))
job.cancelAndJoin()
coVerify(exactly = 2) { mockLambda.invoke() }
}
@Test
fun `should stop when canceled`() = coroutineRule.runBlockingTest {
mapboxTimer.restartAfterMillis = TimeUnit.MINUTES.toMillis(5)
val job = mapboxTimer.startTimer(mockLambda)
coroutineRule.testDispatcher.advanceTimeBy(TimeUnit.MINUTES.toMillis(6))
mapboxTimer.stopJobs()
coroutineRule.testDispatcher.advanceTimeBy(TimeUnit.MINUTES.toMillis(30))
job.cancelAndJoin()
coVerify(exactly = 1) { mockLambda.invoke() }
}
@Test
fun `should subscribe to jobs separately`() = coroutineRule.runBlockingTest {
val mockLambda1: () -> Unit = mockk(relaxed = true)
val mockLambda2: () -> Unit = mockk(relaxed = true)
mapboxTimer.restartAfterMillis = 5000
val firstJob = mapboxTimer.startTimer(mockLambda1)
coroutineRule.testDispatcher.advanceTimeBy(5001)
val secondJob = mapboxTimer.startTimer(mockLambda2)
coroutineRule.testDispatcher.advanceTimeBy(5001)
firstJob.cancelAndJoin()
secondJob.cancelAndJoin()
coVerify(exactly = 2) { mockLambda1.invoke() }
coVerify(exactly = 1) { mockLambda2.invoke() }
}
@Test
fun `should stop and restart normally`() = coroutineRule.runBlockingTest {
mapboxTimer.restartAfterMillis = TimeUnit.MINUTES.toMillis(5)
// Should emit 1
val firstJob = mapboxTimer.startTimer(mockLambda)
coroutineRule.testDispatcher.advanceTimeBy(TimeUnit.MINUTES.toMillis(6))
// Should emit 0 because the jobs are stopped
mapboxTimer.stopJobs()
coroutineRule.testDispatcher.advanceTimeBy(TimeUnit.MINUTES.toMillis(30))
// Should emit 1 after restart
val secondJob = mapboxTimer.startTimer(mockLambda)
coroutineRule.testDispatcher.advanceTimeBy(TimeUnit.MINUTES.toMillis(6))
firstJob.cancelAndJoin()
secondJob.cancelAndJoin()
coVerify(exactly = 2) { mockLambda.invoke() }
}
}
| 0 | null | 1 | 1 | 3751b1323b3e585976a5476176810049061ca1ec | 4,210 | mapbox-navigation-android | Apache License 2.0 |
libImgurApi/src/main/java/com/abhinav/libimgurapi/ImgurClient.kt | AyushGupta2526 | 806,935,183 | false | {"Kotlin": 29645, "Java": 164} | package com.abhinav.libimgurapi
import com.abhinav.libimgurapi.apis.ImgurAPIv3
import com.abhinav.libimgurapi.converters.EnumConverterFactory
import okhttp3.OkHttpClient
import retrofit2.Retrofit
import retrofit2.converter.moshi.MoshiConverterFactory
object ImgurClient {
const val API_KEY = "Add your key here"
// TODO: This should not be placed here remove it when open sourcing this project
private val HttpClinet : OkHttpClient by lazy {
OkHttpClient.Builder()
.addInterceptor{
val request = it.request().newBuilder()
.addHeader("Authorization", "Client-ID $API_KEY")
.build()
it.proceed(request)
}
.build()
}
private val retrofit : Retrofit by lazy {
Retrofit.Builder()
.client(HttpClinet)
.addConverterFactory(MoshiConverterFactory.create())
.addConverterFactory(EnumConverterFactory())
.baseUrl("https://api.imgur.com/3/")
.build()
}
val api: ImgurAPIv3 by lazy {
retrofit.create(ImgurAPIv3::class.java)
}
} | 0 | Kotlin | 0 | 0 | 88c9c93f079533e634fb120051773bd26629b836 | 1,146 | Imguram-Insta-Clone | MIT License |
src/main/kotlin/dev/shtanko/algorithms/leetcode/IntersectionThreeSortedArrays.kt | ashtanko | 203,993,092 | false | null | /*
* Copyright 2020 <NAME>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package dev.shtanko.algorithms.leetcode
/**
* Given three integer arrays arr1, arr2 and arr3 sorted in strictly increasing order,
* return a sorted array of only the integers that appeared in all three arrays.
* @see <a href="https://leetcode.com/problems/intersection-of-three-sorted-arrays/">Source</a>
*/
fun interface IntersectionThreeSortedArrays {
operator fun invoke(arr1: IntArray, arr2: IntArray, arr3: IntArray): List<Int>
}
/**
* Time Complexity: O(n)
* Space Complexity: O(n)
*/
class IntersectionThreeSortedBruteForce : IntersectionThreeSortedArrays {
override operator fun invoke(arr1: IntArray, arr2: IntArray, arr3: IntArray): List<Int> {
val ans: MutableList<Int> = ArrayList()
val counter: MutableMap<Int, Int> = HashMap()
// iterate through arr1, arr2, and arr3 to count the frequencies
for (e in arr1) {
counter[e] = counter.getOrDefault(e, 0) + 1
}
for (e in arr2) {
counter[e] = counter.getOrDefault(e, 0) + 1
}
for (e in arr3) {
counter[e] = counter.getOrDefault(e, 0) + 1
}
for (item in counter.keys) {
if (counter[item] == 3) {
ans.add(item)
}
}
return ans
}
}
/**
* Time Complexity: O(n)
* Space Complexity: O(1)
*/
class IntersectionThreeSortedThreePointers : IntersectionThreeSortedArrays {
override operator fun invoke(arr1: IntArray, arr2: IntArray, arr3: IntArray): List<Int> {
val ans: MutableList<Int> = ArrayList()
// prepare three pointers to iterate through three arrays
// p1, p2, and p3 point to the beginning of arr1, arr2, and arr3 accordingly
// prepare three pointers to iterate through three arrays
// p1, p2, and p3 point to the beginning of arr1, arr2, and arr3 accordingly
var p1 = 0
var p2 = 0
var p3 = 0
while (p1 < arr1.size && p2 < arr2.size && p3 < arr3.size) {
if (arr1[p1] == arr2[p2] && arr2[p2] == arr3[p3]) {
ans.add(arr1[p1])
p1++
p2++
p3++
} else {
if (arr1[p1] < arr2[p2]) {
p1++
} else if (arr2[p2] < arr3[p3]) {
p2++
} else {
p3++
}
}
}
return ans
}
}
| 4 | null | 0 | 19 | bf2c4ab130c4a2740533c1720b7ef6c5406d6e54 | 3,023 | kotlab | Apache License 2.0 |
src/main/kotlin/net/liyze/basin/common/async/TaskMeta.kt | Liyze09 | 637,435,463 | false | {"Kotlin": 96722, "JavaScript": 2722, "HTML": 1238} | /*
* Copyright (c) 2023 Liyze09
*
* 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 net.liyze.basin.common.async
internal class TaskMeta {
lateinit var name: String
lateinit var task: Task
val then: MutableList<TaskMeta> = ArrayList()
fun start(ctx: Context) {
val result = task.run(ctx)
then.forEach {
Thread.ofVirtual().start { it.start(ctx.fork(result)) }
}
}
} | 0 | Kotlin | 0 | 1 | 17aa10a15743c171df152321d8177a6b9e59c576 | 942 | Basin | Apache License 2.0 |
info/src/commonMain/kotlin/com/maxkeppeler/sheets/info/InfoView.kt | maxkeppeler | 523,345,776 | false | null | /*
* Copyright (C) 2022-2023. <NAME> (https://www.maxkeppeler.com)
*
* 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.
*/
@file:OptIn(ExperimentalMaterial3Api::class)
package com.maxkeppeler.sheets.info
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.runtime.Composable
import com.maxkeppeker.sheets.core.models.base.Header
import com.maxkeppeker.sheets.core.models.base.UseCaseState
import com.maxkeppeker.sheets.core.views.ButtonsComponent
import com.maxkeppeker.sheets.core.views.base.FrameBase
import com.maxkeppeler.sheets.info.models.InfoBody
import com.maxkeppeler.sheets.info.models.InfoSelection
import com.maxkeppeler.sheets.info.views.BodyComponent
/**
* Info view for the use-case to display simple information.
* @param useCaseState The state of the sheet.
* @param selection The selection configuration for the dialog view.
* @param header The header to be displayed at the top of the dialog view.
* @param body The body content to be displayed inside the dialog view.
*/
@ExperimentalMaterial3Api
@Composable
fun InfoView(
useCaseState: UseCaseState,
selection: InfoSelection,
header: Header? = null,
body: InfoBody,
) {
FrameBase(
header = header,
layout = { BodyComponent(body) },
buttonsVisible = selection.withButtonView
) {orientation ->
ButtonsComponent(
orientation = orientation,
selection = selection,
onNegative = { selection.onNegativeClick?.invoke() },
onPositive = { selection.onPositiveClick?.invoke() },
state = useCaseState,
)
}
}
| 8 | null | 6 | 816 | 2af41f317228e982e261522717b6ef5838cd8b58 | 2,153 | sheets-compose-dialogs | Apache License 2.0 |
app/src/main/java/com/uogames/remembercards/ui/module/watch/WatchModuleViewModel.kt | Gizcerbes | 476,234,521 | false | {"Kotlin": 676334} | package com.uogames.remembercards.ui.module.watch
import android.content.Context
import com.uogames.dto.global.GlobalModuleView
import com.uogames.dto.local.LocalModuleView
import com.uogames.remembercards.utils.ifNull
import com.uogames.remembercards.viewmodel.MViewModel
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.async
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.SharingStarted
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.flow.shareIn
import kotlinx.coroutines.flow.stateIn
import kotlinx.coroutines.launch
import java.util.UUID
import javax.inject.Inject
class WatchModuleViewModel @Inject constructor(
private val model: MViewModel,
) {
private val viewModelScope = CoroutineScope(Dispatchers.IO)
val shouldReset = model.globalViewModel.shouldReset
val type = MutableStateFlow(false)
val localID = MutableStateFlow<Int?>(null)
val globalID = MutableStateFlow<UUID?>(null)
private val _localModule = MutableStateFlow<MViewModel.LocalModuleModel?>(null)
val localModule = _localModule.asStateFlow()
private val _globalModule = MutableStateFlow<MViewModel.GlobalModuleModel?>(null)
val globalModule = _globalModule.asStateFlow()
private val _size = MutableStateFlow(0)
val size = _size.asStateFlow()
val adapter = WatchModuleAdapter(this)
fun reset() {
type.value = false
localID.value = null
globalID.value = null
_localModule.value = null
_globalModule.value = null
}
fun update() = viewModelScope.launch {
runCatching {
_size.value = 0
localID.value?.apply {
_localModule.value = model.getLocalModel(this)
if (!type.value) _size.value = model.getCountByModule(this)
}
globalID.value?.apply {
_globalModule.value = model.getGlobalModel(this)
if (type.value) _size.value = model.getGlobalCount(this).toInt()
}
}.onFailure {
_size.value = 0
}
}
fun getLocalAsync(position: Int) = viewModelScope.async {
val localID = localID.value.ifNull { return@async null }
model.getLocalModuleCardModel(localID, position)
}
fun getGlobalAsync(position: Int) = viewModelScope.async {
val globalID = globalID.value.ifNull { return@async null }
model.getGlobalModuleCardModel(globalID, position)
}
fun download(view: GlobalModuleView, loading: (String) -> Unit) = model.download(view)
fun setDownloadAction(view: GlobalModuleView, loading: (String) -> Unit) = model.setDownloadAction(view.globalId, loading)
fun getShareAction(module: LocalModuleView) = model.getShareAction(module).stateIn(viewModelScope, SharingStarted.WhileSubscribed(), false)
fun stopDownloading(view: GlobalModuleView) = model.stopDownloading(view.globalId)
fun getPicasso(context: Context) = model.globalViewModel.getPicasso(context)
} | 0 | Kotlin | 0 | 0 | ea694bd872c4ec2e76e761bb9735127a326fce8e | 3,071 | Remember | Apache License 2.0 |
acme-lib/acme-lib-validation/src/main/kotlin/com/acme/validation/OneOfStringsValidator.kt | mattupstate | 496,835,485 | false | {"Kotlin": 268073, "HCL": 28862, "HTML": 15841, "Smarty": 9320, "Shell": 2578, "Dockerfile": 460, "PLpgSQL": 179} | package com.acme.validation
import jakarta.validation.ConstraintValidator
import jakarta.validation.ConstraintValidatorContext
class OneOfStringsValidator : ConstraintValidator<OneOfStrings, String> {
private var annotation: OneOfStrings? = null
override fun initialize(constraintAnnotation: OneOfStrings?) {
annotation = constraintAnnotation
}
override fun isValid(value: String?, context: ConstraintValidatorContext?): Boolean =
annotation!!.values.split(annotation!!.delimiter).contains(value)
}
| 0 | Kotlin | 0 | 6 | 779d77068adf825b8cacc5902a2a70cf000b6a39 | 520 | acme | MIT License |
src/integrationTest/kotlin/com/liftric/octopusdeploy/task/UploadPackageTaskWithWaitIntegrationTest.kt | Liftric | 254,355,172 | false | {"Kotlin": 136774} | package com.liftric.octopusdeploy.task
import com.liftric.octopusdeploy.apiKey
import com.liftric.octopusdeploy.getPackageResponse
import com.liftric.octopusdeploy.serverUrl
import junit.framework.TestCase.assertEquals
import junit.framework.TestCase.assertNotNull
import org.gradle.testkit.runner.GradleRunner
import org.gradle.testkit.runner.TaskOutcome
import org.junit.Rule
import org.junit.Test
import org.junit.rules.TemporaryFolder
import kotlin.random.Random
class UploadPackageTaskIntegrationTest {
@get:Rule
val testProjectDir = TemporaryFolder()
@Test
fun testExecute() {
val major = Random.Default.nextInt(0, 100)
val minor = Random.Default.nextInt(0, 100)
val micro = Random.Default.nextInt(0, 100)
println(testProjectDir.root.absolutePath)
setupBuild(major, minor, micro)
val result = GradleRunner.create()
.forwardOutput()
.withProjectDir(testProjectDir.root)
.withArguments("build", "uploadPackage")
.withPluginClasspath()
.build()
println(result.output)
assertEquals(TaskOutcome.SUCCESS, result.task(":uploadPackage")?.outcome)
val packageItem = getPackageResponse()
.items
?.firstOrNull {
it.version == "$major.$minor.$micro"
}
assertNotNull(packageItem)
assertEquals(".jar", packageItem?.fileExtension)
val secondResult = GradleRunner.create()
.forwardOutput()
.withProjectDir(testProjectDir.root)
.withArguments("build", "uploadPackage")
.withPluginClasspath()
.buildAndFail()
println(secondResult.output)
// override is not set
assertEquals(TaskOutcome.FAILED, secondResult.task(":uploadPackage")?.outcome)
}
fun setupBuild(major: Int, minor: Int, micro: Int) {
testProjectDir.newFile("build.gradle.kts").apply {
writeText(
"""
plugins {
java
id("com.liftric.octopus-deploy-plugin")
}
group = "com.liftric.test"
version = "$major.$minor.$micro"
tasks {
withType<Jar> {
archiveFileName.set(
"${'$'}{archiveBaseName.get()
.removeSuffix("-")}.${'$'}{archiveVersion.get()}.${'$'}{archiveExtension.get()}"
)
}
}
octopus {
serverUrl.set("$serverUrl")
apiKey.set("$apiKey")
generateChangelogSinceLastTag = true
val jar by tasks.existing(Jar::class)
packageName.set(jar.get().archiveBaseName.get().removeSuffix("-"))
version.set(jar.get().archiveVersion.get())
pushPackage.set(jar.get().archiveFile)
}
"""
)
}
testProjectDir.root.setupGitRepoCopy()
}
}
| 1 | Kotlin | 0 | 3 | 7f15caefac9d226591d8344da21504ec80ed8d85 | 2,761 | octopus-deploy-plugin | MIT License |
src/main/kotlin/frc/team449/robot2024/constants/subsystem/ClimberConstants.kt | blair-robot-project | 736,410,238 | false | {"Kotlin": 313771} | package frc.team449.robot2024.constants.subsystem
object ClimberConstants {
const val RIGHT_ID = 10
const val LEFT_ID = 13
const val RIGHT_INVERTED = true
const val LEFT_INVERTED = true
const val CURRENT_LIM = 40
const val RETRACT_VOLTAGE = -12.0
const val EXTEND_VOLTAGE = 8.75
const val DEFAULT_PID_RETRACT = -7.0
const val KP = 1.0
const val KI = 0.0
const val KD = 0.0
const val MAX_SIM_POS = 1.5
const val SIM_SPEED = 0.25
}
| 0 | Kotlin | 1 | 6 | 3433d9c7da844b98aad062bd3e9215156658e2c5 | 462 | robot2024 | MIT License |
core/src/main/java/com/github/grishberg/profiler/analyzer/converter/NameConverter.kt | Grigory-Rylov | 256,819,360 | false | null | package com.github.grishberg.profiler.analyzer.converter
/**
* Converts class names and class methods names.
* For example converts obfuscated names to original names.
*/
interface NameConverter {
fun convertClassName(sourceClassName: String): String
fun convertMethodName(className: String, sourceMethodName: String, type: String?): String
} | 19 | Kotlin | 3 | 97 | e0ba609640cea72c301ff1537dc9cdd9b67bfe4c | 354 | android-methods-profiler | Apache License 2.0 |
src/main/kotlin/fixie/generator/angle/AngleClass.kt | knokko | 687,847,559 | false | {"Kotlin": 245681} | package fixie.generator.angle
import fixie.generator.number.IntType
import fixie.generator.quantity.QuantityClass
import fixie.generator.spin.SpinClass
class AngleClass(
className: String,
val internalType: IntType,
val displayUnit: AngleUnit,
createNumberExtensions: Boolean,
val allowDivisionAndFloatMultiplication: Boolean,
val allowComparisons: Boolean,
val spinClass: SpinClass?
) : QuantityClass(className, createNumberExtensions) {
override fun toString() = "$className($internalType)"
}
| 0 | Kotlin | 0 | 0 | b99e5e35e3c474e3cc97c66c28aee5965572c686 | 557 | fixie | MIT License |
room/room-compiler-processing/src/main/java/androidx/room/compiler/processing/ksp/KspExecutableElement.kt | RikkaW | 389,105,112 | false | null | /*
* Copyright 2020 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package androidx.room.compiler.processing.ksp
import androidx.room.compiler.processing.XAnnotated
import androidx.room.compiler.processing.XExecutableElement
import androidx.room.compiler.processing.XExecutableParameterElement
import androidx.room.compiler.processing.XHasModifiers
import androidx.room.compiler.processing.ksp.KspAnnotated.UseSiteFilter.Companion.NO_USE_SITE
import com.google.devtools.ksp.isConstructor
import com.google.devtools.ksp.symbol.KSFunctionDeclaration
import com.google.devtools.ksp.symbol.Modifier
internal abstract class KspExecutableElement(
env: KspProcessingEnv,
open val containing: KspMemberContainer,
override val declaration: KSFunctionDeclaration
) : KspElement(
env = env,
declaration = declaration
),
XExecutableElement,
XHasModifiers by KspHasModifiers.create(declaration),
XAnnotated by KspAnnotated.create(
env = env,
delegate = declaration,
filter = NO_USE_SITE
) {
override val equalityItems: Array<out Any?> by lazy {
arrayOf(containing, declaration)
}
override val enclosingElement: KspMemberContainer by lazy {
declaration.requireEnclosingMemberContainer(env)
}
override val parameters: List<XExecutableParameterElement> by lazy {
declaration.parameters.map {
KspExecutableParameterElement(
env = env,
method = this,
parameter = it
)
}
}
override fun isVarArgs(): Boolean {
// in java, only the last argument can be a vararg so for suspend functions, it is never
// a vararg function. this would change if room generated kotlin code
return !declaration.modifiers.contains(Modifier.SUSPEND) &&
declaration.parameters.any {
it.isVararg
}
}
companion object {
fun create(
env: KspProcessingEnv,
declaration: KSFunctionDeclaration
): KspExecutableElement {
val enclosingContainer = declaration.findEnclosingMemberContainer(env)
checkNotNull(enclosingContainer) {
"XProcessing does not currently support annotations on top level " +
"functions with KSP. Cannot process $declaration."
}
return when {
declaration.isConstructor() -> {
KspConstructorElement(
env = env,
containing = enclosingContainer as? KspTypeElement ?: error(
"The container for $declaration should be a type element"
),
declaration = declaration
)
}
else -> {
KspMethodElement.create(
env = env,
containing = enclosingContainer,
declaration = declaration
)
}
}
}
}
}
| 6 | null | 937 | 7 | 6d53f95e5d979366cf7935ad7f4f14f76a951ea5 | 3,658 | androidx | Apache License 2.0 |
plot-demo/src/jvmBatikMain/kotlin/plotDemo/plotConfig/Issue_slow_tooltipBatik.kt | JetBrains | 176,771,727 | false | null | /*
* Copyright (c) 2023. JetBrains s.r.o.
* Use of this source code is governed by the MIT license that can be found in the LICENSE file.
*/
package jetbrains.datalore.plotDemo.plotConfig
import jetbrains.datalore.plotDemo.model.plotConfig.Issue_slow_tooltip
import jetbrains.datalore.vis.demoUtils.PlotSpecsDemoWindowBatik
fun main() {
with(Issue_slow_tooltip()) {
PlotSpecsDemoWindowBatik(
"Issue_slow_tooltip",
plotSpecList()
).open()
}
}
| 97 | null | 47 | 889 | c5c66ceddc839bec79b041c06677a6ad5f54e416 | 496 | lets-plot | MIT License |
plot-demo/src/jvmBatikMain/kotlin/plotDemo/plotConfig/Issue_slow_tooltipBatik.kt | JetBrains | 176,771,727 | false | null | /*
* Copyright (c) 2023. JetBrains s.r.o.
* Use of this source code is governed by the MIT license that can be found in the LICENSE file.
*/
package jetbrains.datalore.plotDemo.plotConfig
import jetbrains.datalore.plotDemo.model.plotConfig.Issue_slow_tooltip
import jetbrains.datalore.vis.demoUtils.PlotSpecsDemoWindowBatik
fun main() {
with(Issue_slow_tooltip()) {
PlotSpecsDemoWindowBatik(
"Issue_slow_tooltip",
plotSpecList()
).open()
}
}
| 97 | null | 47 | 889 | c5c66ceddc839bec79b041c06677a6ad5f54e416 | 496 | lets-plot | MIT License |
RippleView/src/main/kotlin/com/ripple/view/RippleView.kt | Leo199206 | 350,188,888 | false | null | package com.cl.common_base.widget.ripple
import android.content.Context
import android.graphics.Canvas
import android.graphics.Color
import android.graphics.Paint
import android.util.AttributeSet
import android.view.View
import androidx.annotation.ColorInt
import androidx.lifecycle.LifecycleOwner
import com.cl.common_base.R
import java.util.*
import kotlin.math.min
class RippleView : View {
constructor(context: Context?) : this(context, null)
constructor(context: Context?, attrs: AttributeSet?) : this(context, attrs, 0)
constructor(context: Context?, attrs: AttributeSet?, defStyleAttr: Int) : super(
context,
attrs,
defStyleAttr
) {
initAttributes(attrs)
initPaint()
if (isStart) {
onStart()
}
}
companion object {
private const val MAX_ALPHA = 255
}
private var paint = Paint()
private var circleMaxRadius: Int = 0
private var circleList: MutableList<RippleCircle> = LinkedList()
private var isStart: Boolean = false
private var isPause: Boolean = false
private var circleCenterX: Float = 0f
private var circleCenterY: Float = 0f
private val rippleLifecycle: RippleLifecycle by lazy {
RippleLifecycle(this)
}
@ColorInt
private var circleColor: Int = Color.RED
private var circleMinRadius: Float = 0f
private var circleCount: Int = 5
private var circleStyle: Paint.Style = Paint.Style.FILL
private var speed: Float = 0.5f
private var circleStrokeWidth: Float = 3f
/**
* 配置参数初始化
* @param attrs AttributeSet?
*/
private fun initAttributes(attrs: AttributeSet?) {
val array = context.obtainStyledAttributes(attrs, R.styleable.RippleView)
for (index in 0 until array.indexCount) {
when (val indexedValue = array.getIndex(index)) {
R.styleable.RippleView_ripple_circle_color -> {
circleColor = array.getColor(indexedValue, Color.RED)
}
R.styleable.RippleView_ripple_circle_min_radius -> {
circleMinRadius = array.getDimension(indexedValue, 0f)
}
R.styleable.RippleView_ripple_circle_count -> {
circleCount = array.getInt(indexedValue, 2)
}
R.styleable.RippleView_ripple_speed -> {
speed = array.getFloat(indexedValue, speed)
}
R.styleable.RippleView_ripple_circle_stroke_width -> {
circleStrokeWidth = array.getDimension(indexedValue, circleStrokeWidth)
}
R.styleable.RippleView_ripple_circle_style -> {
circleStyle = array.getInt(indexedValue, Paint.Style.FILL.ordinal).let {
if (it == Paint.Style.FILL.ordinal) {
Paint.Style.FILL
} else {
Paint.Style.STROKE
}
}
}
R.styleable.RippleView_ripple_circle_start -> {
isStart = array.getBoolean(indexedValue, false)
}
}
}
}
/**
* 圆形半径、透明度参数初始化
*/
private fun initCircle() {
circleMaxRadius = (width / 2 - circleStrokeWidth).toInt()
circleCenterX = width / 2f
circleCenterY = height / 2f
circleList.add(RippleCircle(circleMinRadius, MAX_ALPHA))
}
/**
* 画笔初始化
*/
private fun initPaint() {
paint.style = circleStyle
paint.strokeWidth = circleStrokeWidth
paint.isDither = true
paint.isAntiAlias = true
paint.color = circleColor
}
/**
* 测量控件尺寸
* @param widthMeasureSpec Int
* @param heightMeasureSpec Int
*/
override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) {
val defaultWidth = 200
var defaultHeight = 200
val width = measureSize(widthMeasureSpec, defaultWidth)
val height = measureSize(heightMeasureSpec, defaultHeight)
val size = min(width, height)
setMeasuredDimension(size, size)
}
/**
* 测量尺寸
*
* @param measureSpec
* @param defaultSize
* @return
*/
private fun measureSize(measureSpec: Int, defaultSize: Int): Int {
var result: Int
val mode = MeasureSpec.getMode(measureSpec)
val size = MeasureSpec.getSize(measureSpec)
if (mode == MeasureSpec.EXACTLY) {
result = size
} else {
result = defaultSize
if (mode == MeasureSpec.AT_MOST) {
result = result.coerceAtMost(size)
}
}
return result
}
/**
* 尺寸变动回调
* @param w Int
* @param h Int
* @param oldw Int
* @param oldh Int
*/
override fun onSizeChanged(w: Int, h: Int, oldw: Int, oldh: Int) {
super.onSizeChanged(w, h, oldw, oldh)
initCircle()
}
/**
* 视图绘制
* @param canvas Canvas
*/
override fun onDraw(canvas: Canvas) {
super.onDraw(canvas)
canvas.apply {
onDrawRippleCircle(canvas)
}
}
/**
* 绘制水波纹
* @param canvas Canvas
*/
private fun onDrawRippleCircle(canvas: Canvas) {
if (!isStart) {
return
}
with(circleList.iterator()) {
while (hasNext()) {
next().also {
paint.alpha = it.alpha
canvas.drawCircle(
circleCenterX,
circleCenterY,
it.radius,
paint
)
it.radius += speed
if (it.radius > circleMaxRadius) {
remove()
} else {
it.alpha =
(MAX_ALPHA - (it.radius / circleMaxRadius.toFloat()) * MAX_ALPHA).toInt()
}
}
}
addNewRippleCircle()
}
postInvalidate()
}
/**
* 添加新水波纹
*/
private fun addNewRippleCircle() {
if (circleList.size <= 0) {
return
}
val minMeet = (circleMaxRadius - circleMinRadius) / circleCount
val add = circleList.last().radius > minMeet + circleMinRadius
if (add) {
circleList.add(RippleCircle(circleMinRadius, MAX_ALPHA))
}
}
/**
* 绑定页面生命周期,自动进行资源释放
* @param lifecycleOwner LifecycleOwner?
*/
private fun bindLifecycle(lifecycleOwner: LifecycleOwner?) {
lifecycleOwner
?.lifecycle
?.addObserver(RippleLifecycleAdapter(rippleLifecycle))
}
/**
* 开始播放动画
* @param lifecycleOwner LifecycleOwner?
*/
fun onStart(lifecycleOwner: LifecycleOwner? = null) {
bindLifecycle(lifecycleOwner)
isStart = true
circleList.add(RippleCircle(circleMinRadius, MAX_ALPHA))
postInvalidate()
}
/**
* 动画暂停后,恢复动画播放
*/
fun onResume() {
if (isPause) {
isStart = true
isPause = false
postInvalidate()
}
}
/**
* 停止播放水波纹动画
*/
fun onStop() {
isPause = false
isStart = false
circleList.clear()
}
/**
* 暂停水波纹动画播放
*/
fun onPause() {
if (isStart) {
isPause = true
isStart = false
}
}
} | 0 | null | 0 | 6 | 356c093dafe7e969d9eb5beb5600a1c501cc4af1 | 7,605 | RippleView | Apache License 2.0 |
aws-lambdas/userinfo-api-handlers/src/test/kotlin/com/bkahlert/hello/api/user/GetHandlerTest.kt | bkahlert | 439,967,726 | false | {"Kotlin": 1721426, "CSS": 20318, "JavaScript": 11584, "Shell": 6384, "HTML": 2857, "SCSS": 588} | package com.bkahlert.hello.api.user
import com.amazonaws.services.lambda.runtime.events.APIGatewayProxyRequestEvent
import com.amazonaws.services.lambda.runtime.tests.annotations.Event
import com.auth0.jwk.Jwk
import com.auth0.jwk.JwkProvider
import com.auth0.jwk.UrlJwkProvider
import com.bkahlert.aws.lambda.TestContext
import com.bkahlert.hello.user.info.GetHandler
import com.bkahlert.hello.user.info.JsonWebTokenValidator
import com.bkahlert.kommons.test.fixed
import io.kotest.assertions.json.shouldContainJsonKeyValue
import io.kotest.assertions.json.shouldEqualJson
import io.kotest.matchers.shouldBe
import kotlinx.datetime.Clock
import kotlinx.datetime.Instant
import org.junit.jupiter.api.Disabled
import org.junit.jupiter.params.ParameterizedTest
// TODO replace with token from auth module
class GetHandlerTest {
@Disabled
@ParameterizedTest
@Event(value = "events/get/id-token.json", type = APIGatewayProxyRequestEvent::class)
fun `should validate ID token`(event: APIGatewayProxyRequestEvent, context: TestContext) {
val handler = GetHandler(TestJsonWebTokenValidator())
val response = handler.handleRequest(event, context)
response.statusCode shouldBe 200
// language=json
response.body shouldEqualJson """
{
"at_hash": "DA77KcPSw5NOJ1cVWbLk5A",
"sub": "d2f87456-ed02-49af-8de4-96b9e627d270",
"cognito:groups": [
"eu-central-1_2kcGMqneE_SignInWithApple"
],
"iss": "https://cognito-idp.eu-central-1.amazonaws.com/eu-central-1_2kcGMqneE",
"cognito:username": "SignInWithApple_000340.3f6e937a36b84caaaa2a817ea7d5e69c.0331",
"origin_jti": "43c369dc-7c26-4ce1-afa9-012cdb4d98f2",
"aud": "7lhdbv12q1ud9rgg7g779u8va7",
"identities": [
{
"userId": "000340.3f6e937a36b84caaaa2a817ea7d5e69c.0331",
"providerName": "SignInWithApple",
"providerType": "SignInWithApple",
"issuer": null,
"primary": "true",
"dateCreated": "1671416345385"
}
],
"token_use": "id",
"auth_time": 1671503541,
"exp": 1671507141,
"iat": 1671503541,
"jti": "46ed56e8-6145-413c-9dd0-b1d89a825f41"
}
""".trimIndent()
}
@Disabled
@ParameterizedTest
@Event(value = "events/get/access-token.json", type = APIGatewayProxyRequestEvent::class)
fun `should validate access token`(event: APIGatewayProxyRequestEvent, context: TestContext) {
val handler = GetHandler(TestJsonWebTokenValidator())
val response = handler.handleRequest(event, context)
response.statusCode shouldBe 200
// language=json
response.body shouldEqualJson """
{
"sub": "d2f87456-ed02-49af-8de4-96b9e627d270",
"cognito:groups": [
"eu-central-1_2kcGMqneE_SignInWithApple"
],
"iss": "https://cognito-idp.eu-central-1.amazonaws.com/eu-central-1_2kcGMqneE",
"version": 2,
"client_id": "7lhdbv12q1ud9rgg7g779u8va7",
"origin_jti": "43c369dc-7c26-4ce1-afa9-012cdb4d98f2",
"token_use": "access",
"scope": "openid",
"auth_time": 1671503541,
"exp": 1671507141,
"iat": 1671503541,
"jti": "420799b1-0b66-414d-bc32-c2ed3091e89d",
"username": "SignInWithApple<PASSWORD>"
}
""".trimIndent()
}
@ParameterizedTest
@Event(value = "events/get/refresh-token.json", type = APIGatewayProxyRequestEvent::class)
fun `should reject refresh token`(event: APIGatewayProxyRequestEvent, context: TestContext) {
val handler = GetHandler(TestJsonWebTokenValidator())
val response = handler.handleRequest(event, context)
response.statusCode shouldBe 401
response.body.shouldContainJsonKeyValue("errorMessage", "The token was expected to have 3 parts, but got > 3.")
}
}
fun Jwk(vararg values: Pair<String, Any?>): Jwk = Jwk.fromValues(values.toMap())
fun JwkProvider(vararg jwks: Jwk): JwkProvider = object : UrlJwkProvider("example.com") {
override fun getAll(): List<Jwk> = jwks.asList()
}
fun TestJsonWebTokenValidator(
jwkProvider: JwkProvider = TestTokens.JwkProvider,
issuer: String = TestTokens.IdentityProviderUri,
clientId: String = TestTokens.ClientId,
now: Instant = TestTokens.ExpiresAt,
): JsonWebTokenValidator = JsonWebTokenValidator(
jwkProvider = jwkProvider,
issuer = issuer,
clientId = clientId,
clock = Clock.fixed(now),
)
@Suppress("LongLine", "SpellCheckingInspection")
object TestTokens {
val JwkProvider = JwkProvider(
Jwk(
"alg" to "RS256",
"e" to "AQAB",
"kid" to "<KEY>
"kty" to "RSA",
"n" to "<KEY>",
"use" to "sig"
),
Jwk(
"alg" to "RS256",
"e" to "AQAB",
"kid" to "<KEY>
"kty" to "RSA",
"n" to "<KEY>",
"use" to "sig"
),
)
const val IdentityProviderUri = "https://cognito-idp.eu-central-1.amazonaws.com/eu-central-1_2kcGMqneE"
val ExpiresAt = Instant.fromEpochSeconds(1671507141)
const val ClientId = "7lhdbv12q1ud9rgg7g779u8va7"
const val IdToken =
"<KEY>ex<KEY>"
const val AccessToken =
"eyJraWQiOiJTdGw2ZmdCeG5OSGdXUFdzU0M5bTVQODdOZ0tGb0tPbXlcL1JDRlNkSElCOD0iLCJhbGciOiJSUzI1NiJ9.eyJzdWIiOiJkMmY4NzQ1Ni1lZDAyLTQ5YWYtOGRlNC05NmI5ZTYyN2QyNzAiLCJjb2duaXRvOmdyb3VwcyI6WyJldS1jZW50cmFsLTFfMmtjR01xbmVFX1NpZ25JbldpdGhBcHBsZSJdLCJpc3MiOiJodHRwczpcL1wvY29nbml0by1pZHAuZXUtY2VudHJhbC0xLmFtYXpvbmF3cy5jb21cL2V1LWNlbnRyYWwtMV8ya2NHTXFuZUUiLCJ2ZXJzaW9uIjoyLCJjbGllbnRfaWQiOiI3bGhkYnYxMnExdWQ5cmdnN2c3Nzl1OHZhNyIsIm9yaWdpbl9qdGkiOiI0M2MzNjlkYy03YzI2LTRjZTEtYWZhOS0wMTJjZGI0ZDk4ZjIiLCJ0b2tlbl91c2UiOiJhY2Nlc3MiLCJzY29wZSI6Im9wZW5pZCIsImF1dGhfdGltZSI6MTY3MTUwMzU0MSwiZXhwIjoxNjcxNTA3MTQxLCJpYXQiOjE2NzE1MDM1NDEsImp0aSI6IjQyMDc5OWIxLTBiNjYtNDE0ZC1iYzMyLWMyZWQzMDkxZTg5ZCIsInVzZXJuYW1lIjoiU2lnbkluV2l0aEFwcGxlXzAwMDM0MC4zZjZlOTM3YTM2Yjg0Y2FhYWEyYTgxN2VhN2Q1ZTY5Yy4wMzMxIn0.reLa3TfdP9D_Ie5d4Y8p8xVdzcMMYJlrGQmDJ3CTjPmo-1RBdRf2ImVDlOQHTiOmuBV0FnoGt2GNi7qHNGbjcUb3K-rm6ymWELGGwkEPTX3NkXgby8iAhYXnw1D-hb4pSWVU3zb5Pf5I-vMJQW5WO4N2Z-jVZB8khP0GiYYovY1Qg6vsKGXRqMxCi6nqPYCMvlJ7HPSgC79rKEgN6exrcLiuElVUrfXsigjlHLmu2MqvjigCgqMWMrevvZBp8JQ3qPIij-8N7xNydoDk2Hprv9C8IVdgE9_PesmwPEGJ8AiSjtDK9yWqLSvFRP-qzUecH6XovA-6FipPbXJ2UWv9eg"
const val RefreshToken =
"eyJjdHkiOiJKV1QiLCJlbmMiOiJBMjU2R0NNIiwiYWxnIjoiUlNBLU9BRVAifQ.CcskL1dML80XK3YAuNYSqAaib5AyBvfKaKqO5IJJr-98VS3LFmZxrAeZAyF13086FMCtqt5rVtqLE7JTg53T791DMyPOY-xZC02ZMrZ30_wdNtz0OUR_Z4r5ZVfm9ocqyrZmbiNLamYMZgzhkHzbDYynFJNrH6bMvtEA3Ikh6ZZuAWw15SPYdI_fQy6zq422Y8kUr10vUfCKkE4BM3n03sLPLU4A-sAVlbK_0mHeC6jjL1jBv0ecnbanUzqnwv_E5KBXHjqGjzP2Dzz9PRKgjn85HkGTcEnGC-8XkBx8avraYbBkyPT31ckdj2Xl9Y6ERAnaOYi0fu5fo2zV3COhwg.bKzIXQle05GTOgZo.xQcyZQhPbBCojXBoSn_ynNWLSb2Tv60UtzgLm4IdZM_A05rHOhWlQojqQohyCqjivLwiKbivqz5ZIWxue6jInFHF7miwHA_bXJ8bflZUrxYU1B3ClAJs47D4-r_oQSwvJOskO4fMSHsvMjwiFs5exyDkD_dmRbrhW_4bV35fS7AZDesb3uabK3-ZliaC-pFdMSEr6QX_eEwR0liFe0qUHG8p4lu_GDzBgMnxlKYyCDlBP7MfKaF2vIx9GYDVU1gmy6XhAlvLEFYhC25c6dNwxwxvtcevAwrZFKrapOSFRQfzGCxyrnXJlEwkMKwbMz0B_YN7JXnQ73sPDAWnFZZy6o_bZRc_R7XMdV0nMc090qySa73e_19UbrQSJCxpDNOU6wtcP9LyBTrDTjDBEf9_l7eLIE_OIwWWtmBudWnKRigtvmcE7-JeF5SRVTluNpSUKuLk-khSYFi7nQpjJWmzI1vqqubI0DpZA4XbxUpXlJyEyVyvmUwbIOQvMLTWHQJM04wDXrQ8jDLNPt0gUbJfz80s9tW9jt3z0j39exjosPSfqHKcagqYg4XTqt3XhRKX9PnJjU-lTBL1KMcYjbhpoAfoWGZVtRDm1PWj1Hp_m3TTvg_UJBQfAaHX_XWJVkxFK9d4j8hTE4ViAg8ue6T99xKd2BgNL1TCfRaNLdydsN1aBS76zVUF7nvjw0GEAIGwoR9vyPRCZEnu_nvlxbpNv2ziryjvMlmKkJ-TAyodA8XxLP_EaTkC8TrXEHU9l5wQEOJLW_Xa03CD8cHXlO2nPpz0ytAbiN_0TQxM-xEO57DpZj5yVrp_90o03eU-qYqAp0jjziWsAb5V2rJXffaG2Yh9XNxKZ0O-911Vi-2ihZWzMro6Gdl5Z3YmmquvVLLmEuM6msoLfOXBPsvAr2IeF7QYHmk_8x4h8JN7Ue3zX_ZE65zMWrPosPsq_EO_L3J1kdN1ZYpQ3wfW_Pc196EHLIqF3-8gzRS2xZ2q9fJBVS0onetwG9heDWNrbCbsY3wODxkWXJTsDAKOHaGn2JdOga1YlSpNi0B-Pz-rKguvTXUhBbE7iqgK111mEABkr2uZGRgzGlVh-280Iv94SCjVmLo5HZx4tngWujHLbRHmcgpffYpuvdyKpBqaA9kFe6CfZQcgNJfd-FIA5XUF_7cLXCdotUrUFmnEOeFGToFUe1u1JdyA1SMRtRChb4kmgJPpH3bR8mF90-ETp6SXHGtDElyaETMs7fxaBkMrjXiYh_4SZCZETc7HUtypF9yT8SRNhg2y.IjX_f703NWo0MxEBsCrFWA"
}
| 0 | Kotlin | 0 | 0 | 92e60b7eb9a74cfa957e05e3bf9e59f3ce3a582d | 8,486 | hello | MIT License |
app/src/main/java/com/neal786y/mvparchitecture/main/pojo/zomato/search_restaurants/response/LocationDto.kt | neal786y | 249,264,913 | false | null | package com.neal786y.mvparchitecture.main.pojo.zomato.search_restaurants.response
import com.google.gson.annotations.SerializedName
import java.io.Serializable
data class LocationDto(
@field:SerializedName("address")
val address: String? = null,
@field:SerializedName("locality")
val locality: String? = null,
@field:SerializedName("city")
val city: String? = null,
@field:SerializedName("city_id")
val cityId: Int? = null,
@field:SerializedName("latitude")
val latitude: String? = null,
@field:SerializedName("longitude")
val longitude: String? = null,
@field:SerializedName("zipcode")
val zipcode: String? = null,
@field:SerializedName("country_id")
val countryId: Int? = null,
@field:SerializedName("locality_verbose")
val localityVerbose: String? = null
) | 0 | Kotlin | 0 | 0 | 69c201b439a2c7b12c1020fa213fa6a22988b886 | 790 | Lunching | Apache License 2.0 |
ComboBoxSelectionBackground/src/main/kotlin/example/App.kt | aterai | 158,348,575 | false | null | package example
import java.awt.* // ktlint-disable no-wildcard-imports
import javax.swing.* // ktlint-disable no-wildcard-imports
import javax.swing.plaf.basic.ComboPopup
fun makeUI(): Component {
UIManager.put("ComboBox.selectionBackground", Color.PINK)
UIManager.put("ComboBox.selectionForeground", Color.CYAN)
val model = arrayOf("111", "2222", "33333")
val combo0 = JComboBox(model)
val combo1 = object : JComboBox<String>(model) {
override fun updateUI() {
super.updateUI()
(getAccessibleContext().getAccessibleChild(0) as? ComboPopup)?.list?.also {
it.selectionForeground = Color.WHITE
it.selectionBackground = Color.ORANGE
}
}
}
val combo2 = object : JComboBox<String>(model) {
override fun updateUI() {
setRenderer(null)
super.updateUI()
val renderer = getRenderer()
setRenderer { list, value, index, isSelected, cellHasFocus ->
renderer.getListCellRendererComponent(list, value, index, isSelected, cellHasFocus).also {
if (isSelected) {
it.foreground = Color.WHITE
it.background = Color.ORANGE
} else {
it.foreground = Color.BLACK
it.background = Color.WHITE
}
}
}
}
}
val box = Box.createVerticalBox()
box.border = BorderFactory.createEmptyBorder(5, 5, 5, 5)
box.add(makeTitledPanel("UIManager.put(ComboBox.selection*ground, ...)", combo0))
box.add(Box.createVerticalStrut(5))
box.add(makeTitledPanel("ComboPopup.getList().setSelection*ground(...)", combo1))
box.add(Box.createVerticalStrut(5))
box.add(makeTitledPanel("ListCellRenderer", combo2))
return JPanel(BorderLayout()).also {
it.add(box, BorderLayout.NORTH)
it.preferredSize = Dimension(320, 240)
}
}
private fun makeTitledPanel(title: String, c: Component) = JPanel(BorderLayout()).also {
it.border = BorderFactory.createTitledBorder(title)
it.add(c)
}
fun main() {
EventQueue.invokeLater {
runCatching {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName())
}.onFailure {
it.printStackTrace()
Toolkit.getDefaultToolkit().beep()
}
JFrame().apply {
defaultCloseOperation = WindowConstants.EXIT_ON_CLOSE
contentPane.add(makeUI())
pack()
setLocationRelativeTo(null)
isVisible = true
}
}
}
| 0 | null | 5 | 9 | 47a0c684f64c3db2c8b631b2c20c6c7f9205bcab | 2,369 | kotlin-swing-tips | MIT License |
sample/src/main/java/com/drake/net/sample/ui/fragment/PushRefreshFragment.kt | CPLASF1925 | 311,522,476 | true | {"Java Properties": 2, "YAML": 2, "Gradle": 5, "Shell": 1, "Markdown": 226, "Batchfile": 1, "Text": 1, "Ignore List": 4, "XML": 65, "Java": 82, "Kotlin": 73, "INI": 1, "Proguard": 2, "CSS": 1, "HTML": 1} | /*
* Copyright (C) 2018 Drake, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.drake.net.sample.ui.fragment
import android.os.Bundle
import androidx.fragment.app.Fragment
import com.drake.brv.utils.linear
import com.drake.brv.utils.models
import com.drake.brv.utils.setup
import com.drake.net.Get
import com.drake.net.sample.R
import com.drake.net.sample.mod.ListModel
import com.drake.net.utils.scope
import kotlinx.android.synthetic.main.fragment_push_refresh.*
class PushRefreshFragment : Fragment(R.layout.fragment_push_refresh) {
override fun onActivityCreated(savedInstanceState: Bundle?) {
super.onActivityCreated(savedInstanceState)
rv_push.linear().setup {
addType<String>(R.layout.item_list)
}
page.onRefresh {
scope {
rv_push.models = Get<ListModel>("list").await().data.list
}
}.autoRefresh()
}
}
| 1 | null | 0 | 1 | 1123fa3b48798fcfb97a223b94c2963fbb7c2853 | 1,445 | Net | Apache License 2.0 |
debop4k-core/src/main/kotlin/debop4k/core/Typex.kt | debop | 60,844,667 | false | null | /*
* Copyright (c) 2016. <NAME> <<EMAIL>>
* 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.
*
*/
@file:JvmName("Typex")
package debop4k.core
import java.lang.IllegalArgumentException
import java.lang.IllegalStateException
import java.lang.reflect.*
import kotlin.reflect.KClass
inline fun <reified T : Any> typeRef(): TypeReference<T> = object : TypeReference<T>() {}
inline fun <reified T : Any> fullType(): TypeReference<T> = object : TypeReference<T>() {}
abstract class TypeReference<T> protected constructor() {
public val type: Type by lazy {
javaClass.genericSuperclass.let { superClass ->
if (superClass is Class<*>) {
throw IllegalArgumentException("Internal error: TypeReference constructed without actual type information")
}
(superClass as ParameterizedType).actualTypeArguments[0]
}
}
public val forClass: Class<Any> by lazy { type.erasedType() }
}
@Suppress("UNCHECKED_CAST")
fun Type.erasedType(): Class<Any> = when (this) {
is Class<*> -> this as Class<Any>
is ParameterizedType -> this.rawType.erasedType()
is GenericArrayType -> {
val elementType = this.genericComponentType.erasedType()
val testArray = java.lang.reflect.Array.newInstance(elementType, 0)
testArray.javaClass
}
is TypeVariable<*> -> error("지원되지 않는 수형입니다.")
is WildcardType -> this.upperBounds[0].erasedType()
else -> error("지원되지 않는 수형힙니다.")
}
fun <T : Any> KClass<T>.isAssignableFrom(other: Type): Boolean =
if (this.java == other) true
else this.java.isAssignableFrom(other.erasedType())
fun Class<*>.isAssignableFrom(other: Type): Boolean =
if (this == other) true
else this.isAssignableFrom(other.erasedType())
fun <T : Any> Class<*>.isAssignableFrom(other: KClass<T>): Boolean =
if (this == other.java) true
else this.isAssignableFrom(other.java)
fun <T : Any> KClass<T>.isAssignableFrom(other: Class<*>): Boolean =
if (this.java == other) true
else this.java.isAssignableFrom(other)
fun <T : Any, O : Any> KClass<T>.isAssignableFrom(other: KClass<O>): Boolean =
if (this.java == other.java) true
else this.java.isAssignableFrom(other.java)
fun Type.isAssignableFrom(other: Type): Boolean =
if (this == other) true
else this.erasedType().isAssignableFrom(other.erasedType())
fun Type.isAssignableFrom(other: Class<*>): Boolean =
if (this == other) true
else this.erasedType().isAssignableFrom(other)
fun Type.isAssignableFrom(other: KClass<*>): Boolean =
this.erasedType().isAssignableFrom(other.java)
| 1 | Kotlin | 10 | 40 | 5a621998b88b4d416f510971536abf3bf82fb2f0 | 3,061 | debop4k | Apache License 2.0 |
debop4k-core/src/main/kotlin/debop4k/core/Typex.kt | debop | 60,844,667 | false | null | /*
* Copyright (c) 2016. <NAME> <<EMAIL>>
* 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.
*
*/
@file:JvmName("Typex")
package debop4k.core
import java.lang.IllegalArgumentException
import java.lang.IllegalStateException
import java.lang.reflect.*
import kotlin.reflect.KClass
inline fun <reified T : Any> typeRef(): TypeReference<T> = object : TypeReference<T>() {}
inline fun <reified T : Any> fullType(): TypeReference<T> = object : TypeReference<T>() {}
abstract class TypeReference<T> protected constructor() {
public val type: Type by lazy {
javaClass.genericSuperclass.let { superClass ->
if (superClass is Class<*>) {
throw IllegalArgumentException("Internal error: TypeReference constructed without actual type information")
}
(superClass as ParameterizedType).actualTypeArguments[0]
}
}
public val forClass: Class<Any> by lazy { type.erasedType() }
}
@Suppress("UNCHECKED_CAST")
fun Type.erasedType(): Class<Any> = when (this) {
is Class<*> -> this as Class<Any>
is ParameterizedType -> this.rawType.erasedType()
is GenericArrayType -> {
val elementType = this.genericComponentType.erasedType()
val testArray = java.lang.reflect.Array.newInstance(elementType, 0)
testArray.javaClass
}
is TypeVariable<*> -> error("지원되지 않는 수형입니다.")
is WildcardType -> this.upperBounds[0].erasedType()
else -> error("지원되지 않는 수형힙니다.")
}
fun <T : Any> KClass<T>.isAssignableFrom(other: Type): Boolean =
if (this.java == other) true
else this.java.isAssignableFrom(other.erasedType())
fun Class<*>.isAssignableFrom(other: Type): Boolean =
if (this == other) true
else this.isAssignableFrom(other.erasedType())
fun <T : Any> Class<*>.isAssignableFrom(other: KClass<T>): Boolean =
if (this == other.java) true
else this.isAssignableFrom(other.java)
fun <T : Any> KClass<T>.isAssignableFrom(other: Class<*>): Boolean =
if (this.java == other) true
else this.java.isAssignableFrom(other)
fun <T : Any, O : Any> KClass<T>.isAssignableFrom(other: KClass<O>): Boolean =
if (this.java == other.java) true
else this.java.isAssignableFrom(other.java)
fun Type.isAssignableFrom(other: Type): Boolean =
if (this == other) true
else this.erasedType().isAssignableFrom(other.erasedType())
fun Type.isAssignableFrom(other: Class<*>): Boolean =
if (this == other) true
else this.erasedType().isAssignableFrom(other)
fun Type.isAssignableFrom(other: KClass<*>): Boolean =
this.erasedType().isAssignableFrom(other.java)
| 1 | Kotlin | 10 | 40 | 5a621998b88b4d416f510971536abf3bf82fb2f0 | 3,061 | debop4k | Apache License 2.0 |
base/src/main/java/com/zhangteng/base/adapter/TreeRecyclerViewAdapter.kt | DL-ZhangTeng | 269,325,054 | false | null | package com.zhangteng.base.adapter
import android.annotation.SuppressLint
import android.content.*
import com.zhangteng.base.base.BaseAdapter
import com.zhangteng.base.tree.*
/**
* 树结构的列表适配器
* Created by swing on 2018/6/29.
*/
abstract class TreeRecyclerViewAdapter<T>(data: MutableList<T?>?, defaultExpandLevel: Int) :
BaseAdapter<T, BaseAdapter.DefaultViewHolder>() {
/**
* 存储所有可见的Node
*/
protected var mNodes: MutableList<Node<T?>?>?
/**
* 存储所有的Node
*/
protected var mAllNodes: MutableList<Node<T?>?>?
/**
* 点击的回调接口
*/
private var onTreeNodeClickListener: OnTreeNodeClickListener? = null
open fun setOnTreeNodeClickListener(onTreeNodeClickListener: OnTreeNodeClickListener?) {
this.onTreeNodeClickListener = onTreeNodeClickListener
}
/**
* 相应ListView的点击事件 展开或关闭某节点
*
* @param position
*/
@SuppressLint("NotifyDataSetChanged")
open fun expandOrCollapse(position: Int) {
val n = mNodes?.get(position)
if (n != null) { // 排除传入参数错误异常
if (!n.isLeaf()) {
n.setExpand(!n.isExpand())
mNodes = TreeHelper.filterVisibleNode(mAllNodes)
notifyDataSetChanged() // 刷新视图
}
}
}
override fun onBindViewHolder(holder: DefaultViewHolder, item: T?, position: Int) {
val node = mNodes?.get(position)
onBindViewHolder(holder, node, position)
/**
* 设置节点点击时,可以展开以及关闭;并且将ItemClick事件继续往外公布
*/
holder.itemView.setOnClickListener {
expandOrCollapse(position)
if (onTreeNodeClickListener != null) {
onTreeNodeClickListener!!.onClick(mNodes?.get(position), position)
}
}
}
override fun getItemCount(): Int {
return mNodes?.size ?: 0
}
abstract fun onBindViewHolder(
holder: DefaultViewHolder?,
node: Node<T?>?,
position: Int
)
interface OnTreeNodeClickListener {
open fun <T> onClick(node: Node<T?>?, position: Int)
}
/**
* @param data 原始数据
* @param defaultExpandLevel 默认展开几级树
*/
init {
/**
* 对所有的Node进行排序
*/
mAllNodes = TreeHelper.getSortedNodes(data, defaultExpandLevel)
/**
* 过滤出可见的Node
*/
mNodes = TreeHelper.filterVisibleNode(mAllNodes)
}
} | 0 | null | 0 | 8 | 84b09e2c68cfc9908f6c6a6fc44558da3506445a | 2,416 | BaseLibrary | The Unlicense |
tasks/src/androidMain/kotlin/app/tivi/tasks/SyncLibraryShowsWorker.kt | chrisbanes | 100,624,553 | false | null | // Copyright 2018, Google LLC, Christopher Banes and the Tivi project contributors
// SPDX-License-Identifier: Apache-2.0
package app.tivi.tasks
import android.content.Context
import androidx.work.CoroutineWorker
import androidx.work.WorkerParameters
import app.tivi.domain.interactors.UpdateLibraryShows
import app.tivi.util.Logger
import me.tatarka.inject.annotations.Assisted
import me.tatarka.inject.annotations.Inject
@Inject
class SyncLibraryShows(
@Assisted context: Context,
@Assisted params: WorkerParameters,
private val updateLibraryShows: Lazy<UpdateLibraryShows>,
private val logger: Logger,
) : CoroutineWorker(context, params) {
companion object {
internal const val NIGHTLY_SYNC_TAG = "night-sync-all-followed-shows"
}
override suspend fun doWork(): Result {
logger.d { "$tags worker running" }
val result = updateLibraryShows.value(UpdateLibraryShows.Params(true))
return when {
result.isSuccess -> Result.success()
else -> Result.failure()
}
}
}
| 26 | null | 876 | 6,626 | e261ffbded01c1439b93c550cd6e714c13bb9192 | 1,016 | tivi | Apache License 2.0 |
app/src/main/java/com/breezefieldstatcon/features/addshop/model/UpdateAddressShop.kt | DebashisINT | 878,294,212 | false | {"Kotlin": 16043339, "Java": 1030448} | package com.breezefieldstatcon.features.addshop.model
import com.breezefieldstatcon.app.domain.AddShopDBModelEntity
import com.breezefieldstatcon.app.domain.CallHisEntity
import com.breezefieldstatcon.base.BaseResponse
data class UpdateAddrReq (var user_id:String="",var shop_list:ArrayList<UpdateAddressShop> = ArrayList())
data class UpdateAddressShop(var shop_id:String="",var shop_updated_lat:String="",var shop_updated_long:String="",var shop_updated_address:String="") | 0 | Kotlin | 0 | 0 | 841b394cc9a8c393b0598bd87699d7d798cb1a96 | 478 | StatconEnergiaa | Apache License 2.0 |
modules/mockk/src/commonMain/kotlin/io/mockk/impl/recording/CallRecorderFactories.kt | mockk | 107,331,132 | false | {"Kotlin": 791135, "C++": 67506, "Java": 51094, "HTML": 35111, "JavaScript": 2101, "CMake": 1067, "Shell": 825, "SCSS": 348} | package io.mockk.impl.recording
import io.mockk.MockKGateway.*
import io.mockk.impl.recording.states.CallRecordingState
typealias VerifierFactory = (VerificationParameters) -> CallVerifier
typealias SignatureMatcherDetectorFactory = () -> SignatureMatcherDetector
typealias CallRoundBuilderFactory = () -> CallRoundBuilder
typealias ChildHinterFactory = () -> ChildHinter
typealias PermanentMockerFactory = () -> PermanentMocker
typealias StateFactory = (recorder: CommonCallRecorder) -> CallRecordingState
typealias VerifyingStateFactory = (recorder: CommonCallRecorder, verificationParams: VerificationParameters) -> CallRecordingState
typealias ExclusionStateFactory = (recorder: CommonCallRecorder, exclusionParams: ExclusionParameters) -> CallRecordingState
typealias ChainedCallDetectorFactory = () -> ChainedCallDetector
typealias VerificationCallSorterFactory = () -> VerificationCallSorter
data class CallRecorderFactories(
val signatureMatcherDetector: SignatureMatcherDetectorFactory,
val callRoundBuilder: CallRoundBuilderFactory,
val childHinter: ChildHinterFactory,
val verifier: VerifierFactory,
val permanentMocker: PermanentMockerFactory,
val verificationCallSorter: VerificationCallSorterFactory,
val answeringState: StateFactory,
val stubbingState: StateFactory,
val verifyingState: VerifyingStateFactory,
val exclusionState: ExclusionStateFactory,
val stubbingAwaitingAnswerState: StateFactory,
val safeLoggingState: StateFactory
)
| 296 | Kotlin | 344 | 5,426 | 79abc96d3235710d61beaf677ea1349ba12eea0c | 1,504 | mockk | Apache License 2.0 |
js/js.translator/testData/box/inline/inlineClassEquals.kt | JetBrains | 3,432,266 | false | null | // The test checks an optimization which is implemented only for JS_IR backend
// DONT_TARGET_EXACT_BACKEND: JS
@file:Suppress("RESERVED_MEMBER_INSIDE_VALUE_CLASS")
inline class ClassInt(val x: Int)
inline class ClassString(val x: String)
inline class ClassUnderlayingInline(val x: ClassInt)
inline class ClassNullableInt(val x: Int?)
inline class ClassNullableUnderlayingInline(val x: ClassInt?)
inline class ClassNothing(val x: Nothing?)
value class ClassWithEqualsOverride(val data: Int) {
override fun equals(other: Any?): Boolean = other is ClassWithEqualsOverride && data % 256 == other.data % 256
}
class MyClass(val data: Int) {
override fun equals(other: Any?): Boolean = other is MyClass && data % 10 == other.data % 10
}
inline class ClassUnderlayingWithEquals(val x: MyClass)
interface InterfaceForInlineClass
inline class ClassIntWithInterface(val x: Int) : InterfaceForInlineClass
inline class ClassStringWithInterface(val x: String) : InterfaceForInlineClass
// CHECK_NOT_CALLED_IN_SCOPE: scope=testBasicInt function=equals
// CHECK_NEW_COUNT: function=testBasicInt count=0
fun testBasicInt() {
val a1_1 = ClassInt(1)
val a1_2 = ClassInt(1)
val a2 = ClassInt(2)
assertTrue(a1_1 == a1_1)
assertTrue(a1_1 == a1_2)
assertFalse(a1_1 == a2)
}
// CHECK_NOT_CALLED_IN_SCOPE: scope=testBasicString function=equals
// CHECK_NEW_COUNT: function=testBasicString count=0
fun testBasicString() {
val b1_1 = ClassString("b1")
val b1_2 = ClassString("b1")
val b2 = ClassString("b2")
assertTrue(b1_1 == b1_1)
assertTrue(b1_1 == b1_2)
assertFalse(b1_1 == b2)
}
// CHECK_NOT_CALLED_IN_SCOPE: scope=testFunctionCall function=equals
// CHECK_NEW_COUNT: function=testFunctionCall count=0
fun testFunctionCall() {
// CHECK_NEW_COUNT: function=testFunctionCall$makeClassInt count=0
fun makeClassInt(x: Int): ClassInt {
return ClassInt(x)
}
val a1 = ClassInt(1)
assertTrue(a1 == makeClassInt(1))
assertTrue(makeClassInt(1) == a1)
assertTrue(makeClassInt(1) == makeClassInt(1))
assertFalse(a1 == makeClassInt(2))
assertFalse(makeClassInt(2) == a1)
assertFalse(makeClassInt(2) == makeClassInt(3))
}
// CHECK_NEW_COUNT: function=testTypeErasing count=3
fun testTypeErasing() {
val a1 = ClassInt(1)
// CHECK_CALLED_IN_SCOPE: scope=testTypeErasing$isEqualsWithA1 function=equals
// CHECK_NEW_COUNT: function=testTypeErasing$isEqualsWithA1 count=1
fun <T> isEqualsWithA1(a: T): Boolean {
return a1 == a
}
assertTrue(isEqualsWithA1(a1))
assertTrue(isEqualsWithA1(ClassInt(1)))
val a2 = ClassInt(2)
assertFalse(isEqualsWithA1(a2))
}
// CHECK_NOT_CALLED_IN_SCOPE: scope=testFunctionCall function=equals
// CHECK_NEW_COUNT: function=testTypeErasingAndCast count=4
fun testTypeErasingAndCast() {
fun boxValue(a: Any): ClassInt {
return a as ClassInt
}
val a1_1 = ClassInt(1)
val a1_2 = ClassInt(1)
assertTrue(boxValue(a1_1) == a1_2)
assertTrue(boxValue(a1_1) == boxValue(a1_2))
assertTrue(ClassInt(if (a1_1 == boxValue(a1_2)) 1 else 0) == a1_1)
}
// CHECK_CALLED_IN_SCOPE: scope=testNullableInstances function=equals
// CHECK_NEW_COUNT: function=testNullableInstances count=21
fun testNullableInstances() {
val a1_1: ClassInt? = ClassInt(1)
val a1_2 = ClassInt(1)
val a1_3: ClassInt? = null
val a1_4: ClassInt? = ClassInt(1)
assertTrue(a1_1 == a1_2)
assertTrue(a1_2 == a1_1)
assertTrue(a1_1!! == a1_2)
assertTrue(a1_2 == a1_1!!)
assertTrue(a1_4 == a1_1!!)
assertTrue(a1_4!! == a1_1!!)
val a1_5 = a1_4!!
assertTrue(a1_5 == a1_1!!)
assertFalse(a1_1 == a1_3)
assertFalse(a1_2 == a1_3)
assertFalse(a1_3 == a1_2)
}
fun testUnderlyingInline() {
val x1: ClassInt? = ClassInt(1)
val c1_1 = ClassUnderlayingInline(ClassInt(1))
val c1_2 = ClassUnderlayingInline(ClassInt(1))
val c2 = ClassUnderlayingInline(ClassInt(2))
// CHECK_NOT_CALLED_IN_SCOPE: scope=testUnderlyingInline$caseJsEq function=equals
// CHECK_NEW_COUNT: function=testUnderlyingInline$caseJsEq count=0
fun caseJsEq() {
assertTrue(c1_1 == c1_2)
assertFalse(c1_1 == c2)
val a1 = ClassInt(1)
assertTrue(c1_1.x == a1)
assertTrue(c1_1.x == c1_2.x)
assertFalse(a1 == c2.x)
}
caseJsEq()
// CHECK_CALLED_IN_SCOPE: scope=testUnderlyingInline$caseEquals function=equals
// CHECK_NEW_COUNT: function=testUnderlyingInline$caseEquals count=4
fun caseEquals() {
assertTrue(c1_1 == ClassUnderlayingInline(x1!!))
assertTrue(ClassUnderlayingInline(x1!!) == c1_2)
}
caseEquals()
}
// CHECK_CALLED_IN_SCOPE: scope=testEqualsOverride function=equals
// CHECK_NEW_COUNT: function=testEqualsOverride count=14
fun testEqualsOverride() {
val d1 = ClassWithEqualsOverride(1)
val d2 = ClassWithEqualsOverride(2)
val d257 = ClassWithEqualsOverride(257)
val d1_1: ClassWithEqualsOverride? = ClassWithEqualsOverride(513)
val d1_2: ClassWithEqualsOverride? = null
assertTrue(d1 == d257)
assertTrue(d1_1 == d1)
assertTrue(d1 == d1_1)
assertFalse(d1 == d2)
assertFalse(d1_2 == d1)
assertFalse(d1 == d1_2)
assertFalse(d1_1 == d1_2)
}
// CHECK_NEW_COUNT: function=testNullableUnderlyingType count=1
fun testNullableUnderlyingType() {
val x0 = ClassNullableInt(0)
val x1_1 = ClassNullableInt(1)
val x1_2 = ClassNullableInt(1)
val x_null_1 = ClassNullableInt(null)
val x_null_2 = ClassNullableInt(null)
val nullable_1: ClassNullableInt? = null
val nullable_2: ClassNullableInt? = ClassNullableInt(null)
// CHECK_NOT_CALLED_IN_SCOPE: scope=testNullableUnderlyingType$caseEquals function=equals
// CHECK_NEW_COUNT: function=testNullableUnderlyingType$caseEquals count=0
fun caseEquals() {
assertTrue(x0 == x0)
assertTrue(x0 == ClassNullableInt(0))
assertTrue(x1_1 == x1_2)
assertTrue(x_null_1 == x_null_2)
assertTrue(x_null_1 == ClassNullableInt(null))
assertTrue(x_null_1.x == null)
assertTrue(nullable_1 == null)
assertTrue(nullable_1?.x == null)
assertTrue(nullable_2!!.x == null)
assertTrue(nullable_1?.x == nullable_2!!.x)
assertFalse(x0 == x_null_2)
assertFalse(x1_1 == x0)
assertFalse(x_null_1 == x1_2)
assertFalse(ClassNullableInt(null) == ClassNullableInt(0))
assertFalse(nullable_2 == null)
}
caseEquals()
// CHECK_CALLED_IN_SCOPE: scope=testNullableUnderlyingType$caseJsEq function=equals
// CHECK_NEW_COUNT: function=testNullableUnderlyingType$caseJsEq count=0
fun caseJsEq() {
assertFalse(nullable_1 == nullable_2)
}
caseJsEq()
}
// CHECK_NEW_COUNT: function=testUnderlyingWithEqualsOverride count=4 TARGET_BACKENDS=JS_IR
// CHECK_CALLED_IN_SCOPE: scope=testUnderlyingWithEqualsOverride function=equals
fun testUnderlyingWithEqualsOverride() {
val x0 = ClassUnderlayingWithEquals(MyClass(0))
val x10 = ClassUnderlayingWithEquals(MyClass(10))
val x1_1 = ClassUnderlayingWithEquals(MyClass(1))
val x1_2 = ClassUnderlayingWithEquals(MyClass(1))
assertTrue(x0 == x0)
assertTrue(x0 == x10)
assertTrue(x1_1 == x1_2)
assertFalse(x1_1 == x0)
assertFalse(x10 == x1_2)
}
// CHECK_NEW_COUNT: function=testNullableUnderlyingInlineClass count=1
fun testNullableUnderlyingInlineClass() {
val i1_1: ClassInt? = ClassInt(1)
val i1_2: ClassInt? = ClassInt(1)
val x_null = ClassNullableUnderlayingInline(null)
val x0 = ClassNullableUnderlayingInline(ClassInt(0))
val x1_1 = ClassNullableUnderlayingInline(ClassInt(1))
val x1_2 = ClassNullableUnderlayingInline(ClassInt(1))
val x1_3 = ClassNullableUnderlayingInline(i1_1)
val x1_4 = ClassNullableUnderlayingInline(i1_2!!)
// CHECK_NOT_CALLED_IN_SCOPE: scope=testNullableUnderlyingInlineClass$caseJsEq function=equals
// CHECK_NEW_COUNT: function=testNullableUnderlyingInlineClass$caseJsEq count=0
fun caseJsEq() {
assertTrue(x_null == x_null)
assertTrue(x1_1 == x1_2)
assertTrue(x0 == ClassNullableUnderlayingInline(ClassInt(0)))
assertTrue(x1_1 == x1_3)
assertTrue(x1_4 == x1_3)
assertTrue(x1_4 == x1_2)
assertTrue(x_null == ClassNullableUnderlayingInline(null))
assertTrue(ClassNullableUnderlayingInline(null) == x_null)
assertFalse(x_null == x0)
assertFalse(x0 == x_null)
assertFalse(x1_1 == x_null)
assertFalse(ClassNullableUnderlayingInline(null) == x1_4)
}
caseJsEq()
// CHECK_CALLED_IN_SCOPE: scope=testNullableUnderlyingInlineClass$caseEquals function=equals
// CHECK_NEW_COUNT: function=testNullableUnderlyingInlineClass$caseEquals count=3
fun caseEquals() {
assertTrue(ClassNullableUnderlayingInline(i1_1) == ClassNullableUnderlayingInline(i1_2!!))
}
caseEquals()
}
// CHECK_CALLED_IN_SCOPE: scope=testInlineClassWithInterface function=equals
// CHECK_NEW_COUNT: function=testInlineClassWithInterface count=14
fun testInlineClassWithInterface() {
val xi_1_1: InterfaceForInlineClass = ClassIntWithInterface(1)
val xi_1_2: InterfaceForInlineClass = ClassIntWithInterface(1)
val x_1 = ClassIntWithInterface(1)
val x_2 = ClassIntWithInterface(2)
val yi_foo: InterfaceForInlineClass = ClassStringWithInterface("foo")
val y_foo = ClassStringWithInterface("foo")
val y_bar = ClassStringWithInterface("bar")
assertTrue(xi_1_1 == x_1)
assertTrue(xi_1_1 == xi_1_2)
assertTrue(yi_foo == y_foo)
assertTrue(y_foo == yi_foo)
assertTrue(xi_1_1 as ClassIntWithInterface == x_1)
assertTrue(x_1 == xi_1_1 as ClassIntWithInterface)
assertTrue(xi_1_2 as ClassIntWithInterface == xi_1_1 as ClassIntWithInterface)
assertTrue(xi_1_2 as? ClassIntWithInterface == xi_1_1 as? ClassIntWithInterface)
assertFalse(xi_1_1 == x_2)
assertFalse(yi_foo == y_bar)
assertFalse(xi_1_2 == yi_foo)
}
// CHECK_CALLED_IN_SCOPE: scope=testCompareDifferentInstancesInSmartCast function=equals
// CHECK_NEW_COUNT: function=testCompareDifferentInstancesInSmartCast count=6
@Suppress("EQUALITY_NOT_APPLICABLE")
fun testCompareDifferentInstancesInSmartCast() {
val x1_1: Any = ClassInt(1)
val x1_2 = ClassInt(1)
val y1: Any = ClassString("1")
val y_foo: Any = ClassString("foo")
if (x1_1 is ClassInt && y1 is ClassString) {
assertTrue(x1_2 == x1_1)
assertFalse(x1_1 == y1)
assertFalse(x1_2 == y1)
}
if (x1_1 is ClassInt && y_foo is ClassString) {
assertFalse(x1_1 == y_foo)
assertFalse(x1_2 == y_foo)
assertFalse(y1 == y_foo)
}
}
fun testCompareDifferentInstncesInInlineTemplate() {
inline fun <reified T, reified S> myEq(x: T, y: S) = x == y
// CHECK_NEW_COUNT: function=testCompareDifferentInstncesInInlineTemplate$caseJsEq count=8
fun caseJsEq() {
assertTrue(myEq(ClassInt(1), ClassInt(1)))
assertTrue(myEq(ClassString("foo"), ClassString("foo")))
assertFalse(myEq(ClassInt(1), ClassInt(2)))
assertFalse(myEq(ClassString("foo"), ClassString("bar")))
}
caseJsEq()
// CHECK_CALLED_IN_SCOPE: scope=testCompareDifferentInstncesInInlineTemplate$caseEquals function=equals
// CHECK_NEW_COUNT: function=testCompareDifferentInstncesInInlineTemplate$caseEquals count=4
fun caseEquals() {
assertFalse(myEq(ClassInt(1), ClassString("bar")))
assertFalse(myEq(ClassInt(1), ClassString("1")))
}
caseEquals()
}
// CHECK_CALLED_IN_SCOPE: scope=testNothing function=equals
// CHECK_NEW_COUNT: function=testNothing count=0
fun testNothing() {
val x_undefined_1 = ClassNothing(undefined)
val x_undefined_2 = ClassNothing(undefined)
val x_null_1 = ClassNothing(null)
val x_null_2 = ClassNothing(null)
assertTrue(x_undefined_1 == x_undefined_1)
assertTrue(x_undefined_1 == x_undefined_2)
assertTrue(x_undefined_1 == ClassNothing(undefined))
assertTrue(x_null_1 == x_null_1)
assertTrue(x_null_1 == x_null_2)
assertTrue(x_null_1 == ClassNothing(null))
assertTrue(x_undefined_1 == x_null_1)
assertTrue(x_null_1 == x_undefined_1)
assertTrue(x_undefined_1 == ClassNothing(null))
assertTrue(ClassNothing(null) == x_undefined_1)
assertTrue(ClassNothing(undefined) == x_null_1)
assertTrue(x_null_1 == ClassNothing(undefined))
}
// CHECK_CALLED_IN_SCOPE: scope=testNullableNothing function=equals
// CHECK_NEW_COUNT: function=testNullableNothing count=2
fun testNullableNothing() {
val x_nothing_undefined: ClassNothing? = ClassNothing(undefined)
val x_nothing_null: ClassNothing? = ClassNothing(null)
val x_null: ClassNothing? = null
assertTrue(x_nothing_undefined == x_nothing_null)
assertTrue(x_null == null)
assertTrue(x_null == undefined)
assertTrue(null == x_null)
assertTrue(undefined == x_null)
assertFalse(undefined == x_nothing_null)
assertFalse(x_nothing_null == undefined)
assertFalse(undefined == x_nothing_undefined)
assertFalse(x_nothing_undefined == undefined)
assertFalse(x_null == x_nothing_null)
assertFalse(x_null == x_nothing_undefined)
assertFalse(x_nothing_null == x_null)
assertFalse(x_nothing_undefined == x_null)
}
fun box(): String {
testBasicInt()
testBasicString()
testFunctionCall()
testTypeErasing()
testTypeErasingAndCast()
testNullableInstances()
testUnderlyingInline()
testEqualsOverride()
testNullableUnderlyingType()
testUnderlyingWithEqualsOverride()
testNullableUnderlyingInlineClass()
testInlineClassWithInterface()
testCompareDifferentInstancesInSmartCast()
testCompareDifferentInstncesInInlineTemplate()
testNothing()
testNullableNothing()
return "OK"
}
| 181 | null | 5771 | 49,172 | 33eb9cef3d146062c103f9853d772f0a1da0450e | 13,903 | kotlin | Apache License 2.0 |
app/src/main/java/com/faustinodegroot/sportunity/domain/model/Route.kt | FaustinodG | 723,081,464 | false | {"Kotlin": 38869} | package com.faustinodegroot.sportunity.domain.model
import com.google.gson.annotations.SerializedName
data class Route(
@SerializedName("type") var type: String? = null,
@SerializedName("features") var features: List<Features> = listOf()
)
data class Features(
@SerializedName("type") var type: String? = null,
@SerializedName("geometry") var geometry: Geometry = Geometry(),
@SerializedName("properties") var properties: Properties? = Properties()
)
data class Properties(
@SerializedName("name") var name: String? = null
)
data class Geometry(
@SerializedName("type") var type: String? = null,
@SerializedName("coordinates") var coordinates: List<List<Double>> = listOf()
)
| 0 | Kotlin | 0 | 0 | 18d50f87cc04c71b2ca8fff2820a8191be809f1d | 714 | android_sportunity | MIT License |
libandroid-navigation/src/test/java/com/mapbox/services/android/navigation/v5/internal/navigation/metrics/audio/AudioTypeChainTest.kt | luugiathuy | 227,537,256 | true | {"Gradle": 31, "JSON": 27, "Markdown": 9, "Java Properties": 2, "Shell": 3, "Ignore List": 17, "Batchfile": 1, "Makefile": 1, "YAML": 2, "XML": 283, "JavaScript": 2, "Proguard": 13, "INI": 13, "Java": 312, "Kotlin": 262, "Text": 3, "Python": 2} | package com.mapbox.services.android.navigation.v5.internal.navigation.metrics.audio
import io.mockk.mockk
import io.mockk.verifyOrder
import org.junit.Test
class AudioTypeChainTest {
@Test
fun checksChainIsCorrectWhenSetupCalled() {
val audioTypeChain =
AudioTypeChain()
val unknownAudioType = mockk<AudioTypeResolver.Unknown>(relaxed = true)
val speakerAudioType = mockk<AudioTypeResolver.Speaker>(relaxed = true)
val headphonesAudioType = mockk<AudioTypeResolver.Headphones>(relaxed = true)
val bluetoothAudioType = mockk<AudioTypeResolver.Bluetooth>(relaxed = true)
audioTypeChain.setup(
unknownAudioType,
speakerAudioType,
headphonesAudioType,
bluetoothAudioType
)
verifyOrder {
speakerAudioType.nextChain(eq(unknownAudioType))
headphonesAudioType.nextChain(eq(speakerAudioType))
bluetoothAudioType.nextChain(eq(headphonesAudioType))
}
}
}
| 0 | null | 0 | 1 | 2fb053cde5d83b706f4633da79ec80228a101f24 | 1,029 | mapbox-navigation-android | Apache License 2.0 |
src/main/kotlin/de/rub/bi/inf/openbimrl/rest/OpenBimRlEngineRestApplication.kt | OpenBimRL | 699,764,658 | false | {"Kotlin": 15319, "Dockerfile": 151} | package de.rub.bi.inf.openbimrl.rest
import com.fasterxml.jackson.databind.Module
import com.fasterxml.jackson.databind.module.SimpleModule
import de.rub.bi.inf.openbimrl.rest.serializers.*
import org.springframework.boot.autoconfigure.SpringBootApplication
import org.springframework.boot.runApplication
import org.springframework.context.annotation.Bean
import org.springframework.context.annotation.Configuration
@SpringBootApplication
class OpenBimRlEngineRestApplication
fun main(args: Array<String>) {
runApplication<OpenBimRlEngineRestApplication>(*args)
}
@Configuration
class JacksonConfig {
@Bean
fun customSerializer(): Module? {
val module = SimpleModule()
module.addSerializer(IfcPointerSerializer())
module.addSerializer(EitherSerializer())
module.addSerializer(PairSerializer())
module.addSerializer(BoundingBoxSerializer())
module.addSerializer(BoundingSphereSerializer())
return module
}
}
| 0 | Kotlin | 0 | 0 | 3a84c8b10935641a9b05b1dd320c8b9baa2bea41 | 932 | OpenBimRL-Engine-REST | MIT License |
platform/lang-impl/src/com/intellij/ide/bookmark/ui/tree/BookmarksTreeStructure.kt | ingokegel | 72,937,917 | false | null | // Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package com.intellij.ide.bookmark.ui.tree
import com.intellij.ide.bookmark.ui.BookmarksView
import com.intellij.ide.projectView.impl.CompoundTreeStructureProvider
import com.intellij.ide.util.treeView.AbstractTreeNode
import com.intellij.ide.util.treeView.AbstractTreeStructure
import com.intellij.ide.util.treeView.NodeDescriptor
class BookmarksTreeStructure(val panel: BookmarksView) : AbstractTreeStructure() {
private val root = RootNode(panel)
override fun commit() = Unit
override fun hasSomethingToCommit() = false
override fun createDescriptor(element: Any, parent: NodeDescriptor<*>?) = element as NodeDescriptor<*>
override fun getRootElement(): Any = root
override fun getParentElement(element: Any): Any? = element.asAbstractTreeNode?.parent
override fun getChildElements(element: Any): Array<Any> {
val node = element as? AbstractTreeNode<*>
val children = node?.children?.ifEmpty { null } ?: return emptyArray()
val parent = node.parentFolderNode ?: return children.toTypedArray()
val provider = CompoundTreeStructureProvider.get(panel.project) ?: return children.toTypedArray()
return provider.modify(node, children, parent.settings).toTypedArray()
}
}
| 214 | null | 4829 | 2 | b07eabd319ad5b591373d63c8f502761c2b2dfe8 | 1,330 | intellij-community | Apache License 2.0 |
src/main/java/net/wdsj/mcserver/wdsjmessage/common/cell/StaticTextMessageCell.kt | MeowRay | 816,296,605 | false | {"Kotlin": 35148} | package net.wdsj.mcserver.wdsjmessage.common.cell
import net.md_5.bungee.api.chat.TextComponent
import net.wdsj.mcserver.wdsjmessage.common.msg.Message
import net.wdsj.mcserver.wdsjmessage.common.msg.TextComponentMessage
class StaticTextMessageCell private constructor(
val message: TextComponent,
private val isActiveSupplier: () -> Boolean
) : MessageCell<TextComponent> {
override fun isActive(): Boolean {
return isActiveSupplier.invoke()
}
override fun take(intervalMillis: Long): Message<TextComponent> {
return TextComponentMessage(message)
}
data class Builder private constructor(
var message: TextComponent = TextComponent(""),
var isActiveSupplier: () -> Boolean = { true }
) {
fun setMessage(message: TextComponent) = apply {
this.message = message
}
fun setIsActiveSupplier(isActiveSupplier: () -> Boolean) = apply {
this.isActiveSupplier = isActiveSupplier
}
fun build(): StaticTextMessageCell {
return StaticTextMessageCell(message, isActiveSupplier)
}
companion object {
@JvmStatic
fun newBuilder(block: Builder.() -> Unit): Builder {
return Builder().apply(block)
}
}
}
}
| 0 | Kotlin | 0 | 0 | cecb6919cbef59b43aaf99373b6f7db59acfc228 | 1,318 | WdsjMessage | Apache License 2.0 |
gradle-plugins/compose/src/main/kotlin/org/jetbrains/compose/desktop/application/tasks/AbstractJPackageTask.kt | BaxtiyorNurmatov | 340,560,126 | false | null | /*
* Copyright 2020-2021 JetBrains s.r.o. and respective authors and developers.
* Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE.txt file.
*/
package org.jetbrains.compose.desktop.application.tasks
import org.gradle.api.file.*
import org.gradle.api.provider.ListProperty
import org.gradle.api.provider.Property
import org.gradle.api.provider.Provider
import org.gradle.api.tasks.*
import org.gradle.api.tasks.Optional
import org.gradle.process.ExecResult
import org.gradle.work.ChangeType
import org.gradle.work.InputChanges
import org.jetbrains.compose.desktop.application.dsl.MacOSSigningSettings
import org.jetbrains.compose.desktop.application.dsl.TargetFormat
import org.jetbrains.compose.desktop.application.internal.*
import org.jetbrains.compose.desktop.application.internal.files.MacJarSignFileCopyingProcessor
import org.jetbrains.compose.desktop.application.internal.files.SimpleFileCopyingProcessor
import org.jetbrains.compose.desktop.application.internal.files.fileHash
import org.jetbrains.compose.desktop.application.internal.validation.ValidatedMacOSSigningSettings
import org.jetbrains.compose.desktop.application.internal.validation.validate
import java.io.File
import java.io.Serializable
import java.util.*
import javax.inject.Inject
import kotlin.collections.HashMap
import kotlin.collections.HashSet
import java.io.ObjectInputStream
import java.io.ObjectOutputStream
abstract class AbstractJPackageTask @Inject constructor(
@get:Input
val targetFormat: TargetFormat,
) : AbstractJvmToolOperationTask("jpackage") {
@get:InputFiles
val files: ConfigurableFileCollection = objects.fileCollection()
@get:InputDirectory
@get:Optional
/** @see internal/wixToolset.kt */
val wixToolsetDir: DirectoryProperty = objects.directoryProperty()
@get:Input
@get:Optional
val installationPath: Property<String?> = objects.nullableProperty()
@get:InputFile
@get:Optional
@get:PathSensitive(PathSensitivity.ABSOLUTE)
val licenseFile: RegularFileProperty = objects.fileProperty()
@get:InputFile
@get:Optional
@get:PathSensitive(PathSensitivity.ABSOLUTE)
val iconFile: RegularFileProperty = objects.fileProperty()
@get:Input
val launcherMainClass: Property<String> = objects.notNullProperty()
@get:InputFile
@get:PathSensitive(PathSensitivity.ABSOLUTE)
val launcherMainJar: RegularFileProperty = objects.fileProperty()
@get:Input
@get:Optional
val launcherArgs: ListProperty<String> = objects.listProperty(String::class.java)
@get:Input
@get:Optional
val launcherJvmArgs: ListProperty<String> = objects.listProperty(String::class.java)
@get:Input
val packageName: Property<String> = objects.notNullProperty()
@get:Input
@get:Optional
val packageDescription: Property<String?> = objects.nullableProperty()
@get:Input
@get:Optional
val packageCopyright: Property<String?> = objects.nullableProperty()
@get:Input
@get:Optional
val packageVendor: Property<String?> = objects.nullableProperty()
@get:Input
@get:Optional
val packageVersion: Property<String?> = objects.nullableProperty()
@get:Input
@get:Optional
val linuxShortcut: Property<Boolean?> = objects.nullableProperty()
@get:Input
@get:Optional
val linuxPackageName: Property<String?> = objects.nullableProperty()
@get:Input
@get:Optional
val linuxAppRelease: Property<String?> = objects.nullableProperty()
@get:Input
@get:Optional
val linuxAppCategory: Property<String?> = objects.nullableProperty()
@get:Input
@get:Optional
val linuxDebMaintainer: Property<String?> = objects.nullableProperty()
@get:Input
@get:Optional
val linuxMenuGroup: Property<String?> = objects.nullableProperty()
@get:Input
@get:Optional
val linuxRpmLicenseType: Property<String?> = objects.nullableProperty()
@get:Input
@get:Optional
val macPackageName: Property<String?> = objects.nullableProperty()
@get:Input
@get:Optional
val macDockName: Property<String?> = objects.nullableProperty()
@get:Input
@get:Optional
val winConsole: Property<Boolean?> = objects.nullableProperty()
@get:Input
@get:Optional
val winDirChooser: Property<Boolean?> = objects.nullableProperty()
@get:Input
@get:Optional
val winPerUserInstall: Property<Boolean?> = objects.nullableProperty()
@get:Input
@get:Optional
val winShortcut: Property<Boolean?> = objects.nullableProperty()
@get:Input
@get:Optional
val winMenu: Property<Boolean?> = objects.nullableProperty()
@get:Input
@get:Optional
val winMenuGroup: Property<String?> = objects.nullableProperty()
@get:Input
@get:Optional
val winUpgradeUuid: Property<String?> = objects.nullableProperty()
@get:InputDirectory
@get:Optional
val runtimeImage: DirectoryProperty = objects.directoryProperty()
@get:InputDirectory
@get:Optional
val appImage: DirectoryProperty = objects.directoryProperty()
@get:Input
@get:Optional
internal val nonValidatedMacBundleID: Property<String?> = objects.nullableProperty()
@get:Optional
@get:Nested
internal var nonValidatedMacSigningSettings: MacOSSigningSettings? = null
private inline fun <T> withValidatedMacOSSigning(fn: (ValidatedMacOSSigningSettings) -> T): T? =
nonValidatedMacSigningSettings?.let { nonValidated ->
if (currentOS == OS.MacOS && nonValidated.sign.get()) {
fn(nonValidated.validate(nonValidatedMacBundleID))
} else null
}
@get:LocalState
protected val signDir: Provider<Directory> = project.layout.buildDirectory.dir("compose/tmp/sign")
@get:Internal
private val libsDir: Provider<Directory> = workingDir.map {
it.dir("libs")
}
@get:Internal
private val libsMappingFile: Provider<RegularFile> = workingDir.map {
it.file("libs-mapping.txt")
}
@get:Internal
private val libsMapping = FilesMapping()
override fun makeArgs(tmpDir: File): MutableList<String> = super.makeArgs(tmpDir).apply {
if (targetFormat == TargetFormat.AppImage || appImage.orNull == null) {
// Args, that can only be used, when creating an app image or an installer w/o --app-image parameter
cliArg("--input", tmpDir)
cliArg("--runtime-image", runtimeImage)
val mappedJar = libsMapping[launcherMainJar.ioFile]
?: error("Main jar was not processed correctly: ${launcherMainJar.ioFile}")
cliArg("--main-jar", mappedJar)
cliArg("--main-class", launcherMainClass)
when (currentOS) {
OS.Windows -> {
cliArg("--win-console", winConsole)
}
}
cliArg("--icon", iconFile)
launcherArgs.orNull?.forEach {
cliArg("--arguments", "'$it'")
}
launcherJvmArgs.orNull?.forEach {
cliArg("--java-options", "'$it'")
}
if (currentOS == OS.MacOS) {
macDockName.orNull?.let { dockName ->
cliArg("--java-options", "'-Xdock:name=$dockName'")
}
}
}
if (targetFormat != TargetFormat.AppImage) {
// Args, that can only be used, when creating an installer
cliArg("--app-image", appImage)
cliArg("--install-dir", installationPath)
cliArg("--license-file", licenseFile)
when (currentOS) {
OS.Linux -> {
cliArg("--linux-shortcut", linuxShortcut)
cliArg("--linux-package-name", linuxPackageName)
cliArg("--linux-app-release", linuxAppRelease)
cliArg("--linux-app-category", linuxAppCategory)
cliArg("--linux-deb-maintainer", linuxDebMaintainer)
cliArg("--linux-menu-group", linuxMenuGroup)
cliArg("--linux-rpm-license-type", linuxRpmLicenseType)
}
OS.Windows -> {
cliArg("--win-dir-chooser", winDirChooser)
cliArg("--win-per-user-install", winPerUserInstall)
cliArg("--win-shortcut", winShortcut)
cliArg("--win-menu", winMenu)
cliArg("--win-menu-group", winMenuGroup)
cliArg("--win-upgrade-uuid", winUpgradeUuid)
}
}
}
cliArg("--type", targetFormat.id)
cliArg("--dest", destinationDir)
cliArg("--verbose", verbose)
cliArg("--name", packageName)
cliArg("--description", packageDescription)
cliArg("--copyright", packageCopyright)
cliArg("--app-version", packageVersion)
cliArg("--vendor", packageVendor)
when (currentOS) {
OS.MacOS -> {
cliArg("--mac-package-name", macPackageName)
cliArg("--mac-package-identifier", nonValidatedMacBundleID)
withValidatedMacOSSigning { signing ->
cliArg("--mac-sign", true)
cliArg("--mac-signing-key-user-name", signing.identity)
cliArg("--mac-signing-keychain", signing.keychain)
cliArg("--mac-package-signing-prefix", signing.prefix)
}
}
}
}
private fun invalidateMappedLibs(
inputChanges: InputChanges
): Set<File> {
val outdatedLibs = HashSet<File>()
val libsDirFile = libsDir.ioFile
fun invalidateAllLibs() {
outdatedLibs.addAll(files.files)
outdatedLibs.add(launcherMainJar.ioFile)
logger.debug("Clearing all files in working dir: $libsDirFile")
fileOperations.delete(libsDirFile)
libsDirFile.mkdirs()
}
if (inputChanges.isIncremental) {
val allChanges = inputChanges.getFileChanges(files).asSequence() +
inputChanges.getFileChanges(launcherMainJar)
try {
for (change in allChanges) {
libsMapping.remove(change.file)?.let { fileOperations.delete(it) }
if (change.changeType != ChangeType.REMOVED) {
outdatedLibs.add(change.file)
}
}
} catch (e: Exception) {
logger.debug("Could remove outdated libs incrementally: ${e.stacktraceToString()}")
invalidateAllLibs()
}
} else {
invalidateAllLibs()
}
return outdatedLibs
}
override fun prepareWorkingDir(inputChanges: InputChanges) {
val libsDirFile = libsDir.ioFile
val fileProcessor =
withValidatedMacOSSigning { signing ->
val tmpDirForSign = signDir.ioFile
fileOperations.delete(tmpDirForSign)
tmpDirForSign.mkdirs()
MacJarSignFileCopyingProcessor(
tempDir = tmpDirForSign,
execOperations = execOperations,
signing = signing
)
} ?: SimpleFileCopyingProcessor
val outdatedLibs = invalidateMappedLibs(inputChanges)
for (sourceFile in outdatedLibs) {
assert(sourceFile.exists()) { "Lib file does not exist: $sourceFile" }
val targetFileName =
if (sourceFile.isJarFile)
"${sourceFile.nameWithoutExtension}-${fileHash(sourceFile)}.jar"
else sourceFile.name
val targetFile = libsDirFile.resolve(targetFileName)
fileProcessor.copy(sourceFile, targetFile)
libsMapping[sourceFile] = targetFile
}
}
override fun jvmToolEnvironment(): MutableMap<String, String> =
super.jvmToolEnvironment().apply {
if (currentOS == OS.Windows) {
val wixDir = wixToolsetDir.ioFile
val wixPath = wixDir.absolutePath
val path = System.getenv("PATH") ?: ""
put("PATH", "$wixPath;$path")
}
}
override fun checkResult(result: ExecResult) {
super.checkResult(result)
val outputFile = findOutputFileOrDir(destinationDir.ioFile, targetFormat)
logger.lifecycle("The distribution is written to ${outputFile.canonicalPath}")
}
override fun initState() {
val mappingFile = libsMappingFile.ioFile
if (mappingFile.exists()) {
try {
libsMapping.loadFrom(mappingFile)
} catch (e: Exception) {
fileOperations.delete(mappingFile)
throw e
}
logger.debug("Loaded libs mapping from $mappingFile")
}
}
override fun saveStateAfterFinish() {
val mappingFile = libsMappingFile.ioFile
libsMapping.saveTo(mappingFile)
logger.debug("Saved libs mapping to $mappingFile")
}
}
// Serializable is only needed to avoid breaking configuration cache:
// https://docs.gradle.org/current/userguide/configuration_cache.html#config_cache:requirements
private class FilesMapping : Serializable {
private var mapping = HashMap<File, File>()
operator fun get(key: File): File? =
mapping[key]
operator fun set(key: File, value: File) {
mapping[key] = value
}
fun remove(key: File): File? =
mapping.remove(key)
fun loadFrom(mappingFile: File) {
mappingFile.readLines().forEach { line ->
if (line.isNotBlank()) {
val (k, v) = line.split(File.pathSeparatorChar)
mapping[File(k)] = File(v)
}
}
}
fun saveTo(mappingFile: File) {
mappingFile.parentFile.mkdirs()
mappingFile.bufferedWriter().use { writer ->
mapping.entries
.sortedBy { (k, _) -> k.absolutePath }
.forEach { (k, v) ->
writer.append(k.absolutePath)
writer.append(File.pathSeparatorChar)
writer.appendln(v.absolutePath)
}
}
}
private fun writeObject(stream: ObjectOutputStream) {
stream.writeObject(mapping)
}
private fun readObject(stream: ObjectInputStream) {
mapping = stream.readObject() as HashMap<File, File>
}
} | 0 | null | 0 | 1 | 81bfef76d55c7b8abc7a4484de01bfc1347626f3 | 14,617 | compose-jb | Apache License 2.0 |
src/Application.kt | vilikin | 163,438,775 | false | null | package com.example
import com.example.crawler.Crawler
import com.example.crawler.VeikkausHttpClient
import com.example.engine.LottoEngine
import com.example.store.PersistedLottoHistoryStore
import io.ktor.application.Application
import io.ktor.application.call
import io.ktor.application.install
import io.ktor.features.ContentNegotiation
import io.ktor.gson.gson
import io.ktor.http.ContentType
import io.ktor.http.content.default
import io.ktor.http.content.files
import io.ktor.http.content.static
import io.ktor.response.respond
import io.ktor.response.respondText
import io.ktor.routing.get
import io.ktor.routing.routing
val store = PersistedLottoHistoryStore()
val client = VeikkausHttpClient()
val crawler = Crawler(store, client)
val engine = LottoEngine(store)
fun main(args: Array<String>): Unit = io.ktor.server.netty.EngineMain.main(args)
@Suppress("unused") // Referenced in application.conf
@kotlin.jvm.JvmOverloads
fun Application.module(testing: Boolean = false) {
install(ContentNegotiation) {
gson {
}
}
routing {
get("/api/row") {
call.respond(engine.getRandomRow())
}
get("/actions/scrape") {
crawler.scrapeAndSaveDrawsSinceLatestSavedDraw()
call.respondText("Scraped successfully", contentType = ContentType.Text.Plain)
}
get("/api/stats") {
val map = store.getAllDraws()
.filter { it.primaryNumbers.size == 7 }
.flatMap { it.primaryNumbers }
.groupingBy { it }
.eachCount()
call.respond(map)
}
static("/") {
files("static")
default("static/index.html")
}
}
}
| 0 | Kotlin | 0 | 0 | adbbd99b41c1574669ddc6bf90819ed718a8ee12 | 1,738 | lottokone | MIT License |
demo/src/main/java/pyxis/uzuki/live/richutilskt/demo/Misc.kt | WindSekirun | 92,814,709 | false | null | package pyxis.uzuki.live.richutilskt.demo
import android.content.Context
import pyxis.uzuki.live.richutilskt.utils.browse
internal fun Context.browseToFile(fileName: String) {
browse("https://github.com/WindSekirun/RichUtilsKt/blob/master/RichUtils/src/main/java/pyxis/uzuki/live/richutilskt/%s".format(fileName))
} | 3 | Kotlin | 28 | 171 | 351b6be5c35f7e6864f49f202532a7dd21f2d1df | 321 | RichUtilsKt | Apache License 2.0 |
compiler/testData/codegen/boxWithStdlib/reflection/enclosing/insideLambda/classInLambda.kt | chashnikov | 14,658,474 | false | null | fun box(): String {
val classInLambda = {
class Z {}
Z()
}()
val enclosingMethod = classInLambda.javaClass.getEnclosingMethod()
if (enclosingMethod?.getName() != "invoke") return "method: $enclosingMethod"
val enclosingClass = classInLambda.javaClass.getEnclosingClass()
if (enclosingClass?.getName() != "_DefaultPackage\$box\$classInLambda\$1") return "enclosing class: $enclosingClass"
//KT-5092
//val declaringClass = classInLambda.javaClass.getDeclaringClass()
//if (declaringClass == null) return "class hasn't a declaring class"
return "OK"
} | 0 | null | 0 | 1 | 88a261234860ff0014e3c2dd8e64072c685d442d | 609 | kotlin | Apache License 2.0 |
compiler/testData/codegen/boxWithStdlib/reflection/enclosing/insideLambda/classInLambda.kt | chashnikov | 14,658,474 | false | null | fun box(): String {
val classInLambda = {
class Z {}
Z()
}()
val enclosingMethod = classInLambda.javaClass.getEnclosingMethod()
if (enclosingMethod?.getName() != "invoke") return "method: $enclosingMethod"
val enclosingClass = classInLambda.javaClass.getEnclosingClass()
if (enclosingClass?.getName() != "_DefaultPackage\$box\$classInLambda\$1") return "enclosing class: $enclosingClass"
//KT-5092
//val declaringClass = classInLambda.javaClass.getDeclaringClass()
//if (declaringClass == null) return "class hasn't a declaring class"
return "OK"
} | 0 | null | 0 | 1 | 88a261234860ff0014e3c2dd8e64072c685d442d | 609 | kotlin | Apache License 2.0 |
src/main/kotlin/org/wfanet/measurement/duchy/ComputationStage.kt | VideoAmp | 368,272,602 | true | {"Kotlin": 1266935, "Starlark": 227446, "C++": 158561, "Shell": 7082} | // Copyright 2020 The Cross-Media Measurement Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package org.wfanet.measurement.duchy
import org.wfanet.measurement.internal.duchy.ComputationStage
import org.wfanet.measurement.internal.duchy.protocol.LiquidLegionsSketchAggregationV2
val ComputationStage.name: String
@Suppress("WHEN_ENUM_CAN_BE_NULL_IN_JAVA") // Proto enum fields are never null.
get() =
when (stageCase) {
ComputationStage.StageCase.LIQUID_LEGIONS_SKETCH_AGGREGATION_V2 ->
liquidLegionsSketchAggregationV2.name
ComputationStage.StageCase.STAGE_NOT_SET -> error("Stage not set")
}
val ComputationStage.number: Int
@Suppress("WHEN_ENUM_CAN_BE_NULL_IN_JAVA") // Proto enum fields are never null.
get() =
when (stageCase) {
ComputationStage.StageCase.LIQUID_LEGIONS_SKETCH_AGGREGATION_V2 ->
liquidLegionsSketchAggregationV2.number
ComputationStage.StageCase.STAGE_NOT_SET -> error("Stage not set")
}
fun LiquidLegionsSketchAggregationV2.Stage.toProtocolStage(): ComputationStage =
ComputationStage.newBuilder().setLiquidLegionsSketchAggregationV2(this).build()
| 94 | null | 11 | 4 | 66fd8f1a81b7d93f23d769f7be76d529b6a8d222 | 1,662 | cross-media-measurement | Apache License 2.0 |
composer/src/main/java/io/piano/android/composer/model/SplitTest.kt | tinypass | 56,064,393 | false | {"Kotlin": 263976} | package io.piano.android.composer.model
import com.squareup.moshi.JsonClass
@JsonClass(generateAdapter = true)
public class SplitTest(
@JvmField public val variantId: String,
@JvmField public val variantName: String,
)
| 1 | Kotlin | 10 | 15 | 7110301628367b947331f9f3435355e37de6c448 | 229 | piano-sdk-for-android | Apache License 2.0 |
android-common/src/com/android/tools/idea/log/LoggerWithFixedInfo.kt | JetBrains | 60,701,247 | false | null | /*
* Copyright (C) 2021 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.android.tools.idea.log
import com.intellij.openapi.diagnostic.DelegatingLogger
import com.intellij.openapi.diagnostic.Logger
/**
* A logger that supports adding additional info as a prefix. This allows to, for example, temporarily log a request id next to every
* line of the log as:
*
* "[requestId=anId] The actual log line".
*/
class LoggerWithFixedInfo(delegate: Logger, information: Map<String, String>): DelegatingLogger<Logger>(delegate) {
private val prefix = if (information.isNotEmpty())
"[" + information.entries.joinToString(" ") { "${it.key}=${it.value}" } + "] "
else ""
override fun debug(message: String) {
super.debug("$prefix$message")
}
override fun debug(t: Throwable?) {
debug("", t)
}
override fun debug(message: String, t: Throwable?) {
super.debug("$prefix$message", t)
}
override fun info(message: String) {
super.info("$prefix$message")
}
override fun info(message: String, t: Throwable?) {
super.info("$prefix$message", t)
}
override fun warn(message: String, t: Throwable?) {
super.warn("$prefix$message", t)
}
override fun error(message: String, t: Throwable?, vararg details: String?) {
super.error("$prefix$message", t, *details)
}
} | 5 | null | 227 | 948 | 10110983c7e784122d94c7467e9d243aba943bf4 | 1,874 | android | Apache License 2.0 |
app/src/main/java/com/ramitsuri/notificationjournal/service/PhoneDataLayerListenerService.kt | ramitsuri | 667,037,607 | false | {"Kotlin": 185801, "Shell": 9016, "Python": 2413, "HTML": 551} | package com.ramitsuri.notificationjournal.service
import android.annotation.SuppressLint
import android.util.Log
import com.google.android.gms.wearable.DataEvent
import com.google.android.gms.wearable.DataEventBuffer
import com.google.android.gms.wearable.DataMapItem
import com.google.android.gms.wearable.WearableListenerService
import com.ramitsuri.notificationjournal.core.data.AppDatabase
import com.ramitsuri.notificationjournal.core.model.entry.JournalEntry
import com.ramitsuri.notificationjournal.core.utils.Constants
import com.ramitsuri.notificationjournal.di.ServiceLocator
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.SupervisorJob
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import java.time.Instant
import java.time.ZoneId
class PhoneDataLayerListenerService : WearableListenerService() {
@SuppressLint("VisibleForTests")
override fun onDataChanged(dataEvents: DataEventBuffer) {
val addJournalEntryEvents = mutableListOf<DataEvent>()
val uploadEvents = mutableListOf<DataEvent>()
dataEvents.forEach { event ->
val path = event.dataItem.uri.path ?: ""
if (path.startsWith(Constants.DataSharing.JOURNAL_ENTRY_ROUTE)) {
addJournalEntryEvents.add(event)
} else if (path.startsWith(Constants.DataSharing.REQUEST_UPLOAD_ROUTE)) {
uploadEvents.add(event)
}
}
addJournalEntryEvents.forEach { dataEvent ->
val dataMap = DataMapItem.fromDataItem(dataEvent.dataItem).dataMap
val journalEntryText = dataMap.getString(Constants.DataSharing.JOURNAL_ENTRY_VALUE)
if (journalEntryText != null) {
val journalEntryTimeMillis =
dataMap.getLong(Constants.DataSharing.JOURNAL_ENTRY_TIME)
val journalEntryTime = if (journalEntryTimeMillis == 0L) {
Instant.now()
} else {
Instant.ofEpochMilli(journalEntryTimeMillis)
}
val journalEntryTimeZoneId =
dataMap.getString(Constants.DataSharing.JOURNAL_ENTRY_TIME_ZONE)
val journalEntryTimeZone = try {
ZoneId.of(journalEntryTimeZoneId)
} catch (e: Exception) {
ZoneId.systemDefault()
}
val tag = dataMap.getString(Constants.DataSharing.JOURNAL_ENTRY_TAG)
val journalEntry = JournalEntry(
id = 0,
entryTime = journalEntryTime,
timeZone = journalEntryTimeZone,
text = journalEntryText,
tag = tag,
)
val dao = AppDatabase.getJournalEntryDao(context = applicationContext)
CoroutineScope(SupervisorJob()).launch {
withContext(Dispatchers.IO) {
dao.insert(journalEntry)
}
}
}
}
if (uploadEvents.isNotEmpty()) {
CoroutineScope(SupervisorJob()).launch {
val error = ServiceLocator.repository.upload() ?: return@launch
Log.d(TAG, "Failed to upload: $error")
}
}
}
companion object {
private const val TAG = "PhoneDataLayerListenerService"
}
}
| 0 | Kotlin | 0 | 0 | e7df6762e500a2128b777f186365edf8d6dd1688 | 3,451 | notification-journal | MIT License |
app/src/main/java/com/ljubenvassilev/cities/db/CitiesDb.kt | ljubenvassilev | 148,457,214 | false | null | package com.ljubenvassilev.cities.db
import androidx.room.Database
import androidx.room.RoomDatabase
import com.ljubenvassilev.cities.cities.entities.CityEntity
@Database(entities = [CityEntity::class], version = 1, exportSchema = false)
abstract class CitiesDb : RoomDatabase() {
abstract fun cityDao(): CityDao
companion object {
const val DB_NAME = "cities.db"
}
} | 0 | Kotlin | 1 | 1 | 3f79f74aaaa35a89213e2d7c3194e0810d2561c8 | 390 | Cities | MIT License |
cams-framework-mvvm/src/main/java/com/linwei/cams/component/mvvm/mvvm/ViewModelFactory.kt | WeiShuaiDev | 390,640,743 | false | null | package com.linwei.cams.framework.mvi.mvi
import androidx.lifecycle.ViewModel
import androidx.lifecycle.ViewModelProvider
/**
* ---------------------------------------------------------------------
* @Author: WeiShuai
* @Time: 2022/2/24
* @Contact: <EMAIL>"
* @Follow: https://github.com/WeiShuaiDev
* @Description: MVI架构生产 `ViewModel`工厂类,把 `ViewModel` 存储到 Map集合中 `value`,
* `Class<in ViewModel>` 存储到 Map 集合中 `key`
*-----------------------------------------------------------------------
*/
class ViewModelFactory : ViewModelProvider.Factory {
companion object {
private var INSTANCE: ViewModelFactory? = null
@JvmStatic
fun getInstance(): ViewModelFactory {
return INSTANCE
?: ViewModelFactory().apply {
INSTANCE = this
}
}
}
@Suppress("UNCHECKED_CAST")
override fun <T : ViewModel> create(modelClass: Class<T>): T {
try {
val creator = modelClass.newInstance()
return creator as T
} catch (e: Exception) {
throw RuntimeException()
}
}
} | 1 | Kotlin | 1 | 3 | 37ffb7142ce1141c7b09ef69664c535150d25aaa | 1,143 | CamsModular | Apache License 2.0 |
buildSrc/src/main/kotlin/Dependencies.kt | dss99911 | 138,060,985 | false | null | object deps {
object kotlin {
val gradle = depKotlin("gradle-plugin", versions.kotlin.version)
val serializationGradle = depKotlin("serialization", versions.kotlin.version)
val coroutineCore = depKotlinx("coroutines-core", versions.kotlin.coroutine)
val coroutineTest = depKotlinx("coroutines-test", versions.kotlin.coroutine)
val serializationCore = depKotlinx("serialization-json", versions.kotlin.serialization)
val reflect = depKotlin("reflect", versions.kotlin.version)
val testJunit = depKotlin("test-junit", versions.kotlin.version)
val test = depKotlin("test", versions.kotlin.version)
val testCommon = depKotlin("test-common", versions.kotlin.version)
val testAnnotationCommon = depKotlin("test-annotations-common", versions.kotlin.version)
}
object ktor {
const val core = "io.ktor:ktor-server-core:${versions.kotlin.ktor}"
const val gson = "io.ktor:ktor-gson:${versions.kotlin.ktor}"
const val serialization = "io.ktor:ktor-serialization:${versions.kotlin.ktor}"
const val serverNetty = "io.ktor:ktor-server-netty:${versions.kotlin.ktor}"
const val auth = "io.ktor:ktor-auth:${versions.kotlin.ktor}"
const val authJwt = "io.ktor:ktor-auth-jwt:${versions.kotlin.ktor}"
const val serverSessions = "io.ktor:ktor-server-sessions:${versions.kotlin.ktor}"
const val clientCore = "io.ktor:ktor-client-core:${versions.kotlin.ktor}"
const val clientIos = "io.ktor:ktor-client-ios:${versions.kotlin.ktor}"
const val clientJs = "io.ktor:ktor-client-js:${versions.kotlin.ktor}"
const val clientAndroid = "io.ktor:ktor-client-android:${versions.kotlin.ktor}"
const val clientLogging = "io.ktor:ktor-client-logging:${versions.kotlin.ktor}"
const val clientSerialization = "io.ktor:ktor-client-serialization:${versions.kotlin.ktor}"
const val clientAuth = "io.ktor:ktor-client-auth:${versions.kotlin.ktor}"
const val clientAuthJvm = "io.ktor:ktor-client-auth-jvm:${versions.kotlin.ktor}"
const val clientAuthNative = "io.ktor:ktor-client-auth-native:${versions.kotlin.ktor}"
const val clientAuthJs = "io.ktor:ktor-client-auth-js:${versions.kotlin.ktor}"
const val clientEngineApache = "io.ktor:ktor-client-apache:${versions.kotlin.ktor}"
}
object android {
const val buildToolGradle = "com.android.tools.build:gradle:${versions.android.buildTool}"
const val supportCompat = "com.android.support:support-compat:28.0.0"
const val appCompat = "androidx.appcompat:appcompat:${versions.android.xBase}"
const val core = "androidx.core:core-ktx:1.3.0"
const val vectordrawable = "androidx.vectordrawable:vectordrawable:${versions.android.xBase}"
const val material = "com.google.android.material:material:${versions.android.material}"
const val work = "androidx.work:work-runtime-ktx:2.3.1"
const val anko = "org.jetbrains.anko:anko:0.10.8"
const val timber = "com.jakewharton.timber:timber:4.7.1"
val testCommon = listOf(
"androidx.arch.core:core-testing:2.1.0",
"androidx.test.ext:junit-ktx:1.1.1",
"androidx.test:core-ktx:${versions.android.xTest}",
"androidx.test:core:${versions.android.xTest}",
"androidx.test:rules:${versions.android.xTest}",
"androidx.test:runner:${versions.android.xTest}",
"org.mockito:mockito-core:3.2.4",
kotlin.coroutineTest,
"com.google.truth:truth:1.0.1"
)
val compose = listOf(
Compose.ui,
Compose.material,
Compose.material,
Compose.tooling,
Compose.layout,
Compose.iconsExtended
)
object Compose {
const val animation = "androidx.compose.animation:animation:${versions.android.compose}"
const val foundation = "androidx.compose.foundation:foundation:${versions.android.compose}"
const val layout = "androidx.compose.foundation:foundation-layout:${versions.android.compose}"
const val iconsExtended = "androidx.compose.material:material-icons-extended:${versions.android.compose}"
const val material = "androidx.compose.material:material:${versions.android.compose}"
const val runtime = "androidx.compose.runtime:runtime:${versions.android.compose}"
const val tooling = "androidx.compose.ui:ui-tooling:${versions.android.compose}"
const val ui = "androidx.compose.ui:ui:${versions.android.compose}"
const val uiUtil = "androidx.compose.ui:ui-util:${versions.android.compose}"
const val uiTest = "androidx.compose.ui:ui-test-junit4:${versions.android.compose}"
}
object accompanist {
const val coil = "dev.chrisbanes.accompanist:accompanist-coil:${versions.android.accompanist}"
const val insets = "dev.chrisbanes.accompanist:accompanist-insets:${versions.android.accompanist}"
}
}
object simpleArch {
val client = depSimpleArchitecture("client", version = versions.simpleArch)
val backend = depSimpleArchitecture("backend", version = versions.simpleArch)
val gradle = depSimpleArchitecture("gradle", versions.simpleArch)
object api {
val annotation = depSimpleApi("annotation", versions.simpleArch)
val gradleServiceShared = depSimpleApi("gradle-service-shared", version = versions.simpleArch)
val gradleService = depSimpleApi("gradle-service", version = versions.simpleArch)
val gradleServiceNative = depSimpleApi("gradle-service-native", version = versions.simpleArch)
val gradle = depSimpleApi("gradle", version = versions.simpleArch)
val client = depSimpleApi("client", version = versions.simpleArch)
val backend = depSimpleApi("backend", version = versions.simpleArch)
}
}
object plugin {
val gradleApi = depKotlin("gradle-plugin-api", versions.kotlin.version)
val compilerEmbeddable = depKotlin("compiler-embeddable", versions.kotlin.version)
val compiler = depKotlin("compiler", versions.kotlin.version)
const val auto = "com.google.auto.service:auto-service:1.0-rc6"
const val gradlePublish = "com.gradle.publish:plugin-publish-plugin:0.12.0"
}
object sqldelight {
const val runtime = "com.squareup.sqldelight:runtime:${versions.sqldelight}"
const val coroutine = "com.squareup.sqldelight:coroutines-extensions:${versions.sqldelight}"
const val gradle = "com.squareup.sqldelight:gradle-plugin:${versions.sqldelight}"
const val android = "com.squareup.sqldelight:android-driver:${versions.sqldelight}"
const val native = "com.squareup.sqldelight:native-driver:${versions.sqldelight}"
const val jvm = "com.squareup.sqldelight:sqlite-driver:${versions.sqldelight}"
}
const val shadowGradle = "com.github.jengelman.gradle.plugins:shadow:${versions.shadow}"
const val gson = "com.google.code.gson:gson:2.8.6"
const val logback = "ch.qos.logback:logback-classic:1.2.3"
const val junit = "junit:junit:4.13"
const val krypto = "com.soywiz.korlibs.krypto:krypto:1.12.0"
}
private fun depKotlin(module: String, version: String? = null): String =
"org.jetbrains.kotlin:kotlin-$module${version?.let { ":$version" } ?: ""}"
private fun depKotlinx(module: String, version: String? = null): String =
"org.jetbrains.kotlinx:kotlinx-$module${version?.let { ":$version" } ?: ""}"
private fun depSimpleArchitecture(module: String? = null, version: String? = null): String =
"kim.jeonghyeon:kotlin-simple-architecture${module?.let { "-$module" } ?: ""}${version?.let { ":$version" } ?: ""}"
private fun depSimpleApi(module: String? = null, version: String? = null): String =
"kim.jeonghyeon:kotlin-simple-api${module?.let { "-$module" } ?: ""}${version?.let { ":$version" } ?: ""}"
fun String.getGroupId(): String = split(':')[0]
fun String.getArtifactId(): String = split(':')[1]
fun String.getVersion(): String = split(':')[2]
fun String.toPlugInId(): String = getGroupId() + "." + getArtifactId() | 1 | null | 2 | 38 | e9da57fdab9c9c1169fab422fac7432143e2c02c | 8,314 | kotlin-simple-architecture | Apache License 2.0 |
Yukari/src/main/java/shibafu/yukari/twitter/TwitterApi.kt | shibafu528 | 134,973,177 | false | {"Git Config": 1, "Gradle": 7, "Java Properties": 2, "Shell": 1, "Text": 3, "Ignore List": 6, "Batchfile": 1, "Markdown": 3, "Kotlin": 144, "Proguard": 1, "XML": 167, "Java": 150, "HTML": 1, "Ruby": 1} | package shibafu.yukari.twitter
import android.content.Context
import android.os.Handler
import android.os.Looper
import android.preference.PreferenceManager
import androidx.collection.LongSparseArray
import android.widget.Toast
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.launch
import shibafu.yukari.common.Suppressor
import shibafu.yukari.core.App
import shibafu.yukari.database.AccountManager
import shibafu.yukari.database.AuthUserRecord
import shibafu.yukari.database.Provider
import shibafu.yukari.entity.ShadowUser
import shibafu.yukari.entity.Status
import shibafu.yukari.entity.StatusDraft
import shibafu.yukari.linkage.PostValidator
import shibafu.yukari.linkage.ProviderApi
import shibafu.yukari.linkage.ProviderApiException
import shibafu.yukari.linkage.TimelineHub
import shibafu.yukari.twitter.entity.TwitterMessage
import shibafu.yukari.twitter.entity.TwitterStatus
import shibafu.yukari.util.putDebugLog
import twitter4j.CursorSupport
import twitter4j.StatusUpdate
import twitter4j.Twitter
import twitter4j.TwitterException
import twitter4j.TwitterFactory
import twitter4j.UploadedMedia
import java.io.File
import java.util.regex.Pattern
class TwitterApi : ProviderApi {
private lateinit var context: Context
private lateinit var accountManager: AccountManager
private lateinit var suppressor: Suppressor
private lateinit var timelineHub: TimelineHub
private lateinit var twitterProvider: TwitterProvider
private lateinit var twitterFactory: TwitterFactory
private val twitterInstances = LongSparseArray<Twitter>()
override fun onCreate(context: Context) {
val app = App.getInstance(context)
this.context = app
this.accountManager = app.accountManager
this.suppressor = app.suppressor
this.timelineHub = app.timelineHub
this.twitterProvider = app
this.twitterFactory = TwitterUtil.getTwitterFactory(app)
GlobalScope.launch {
// Blocks, Mutes, No-Retweetsの取得
val twitterAccounts = accountManager.users.filter { it.Provider.apiType == Provider.API_TWITTER }
val sp = PreferenceManager.getDefaultSharedPreferences(app)
if (sp.getBoolean("pref_filter_official", true)) {
twitterAccounts.forEach { userRecord ->
val twitter = getApiClient(userRecord) as? Twitter ?: return@forEach
try {
forEachCursor(twitter::getBlocksIDs) {
suppressor.addBlockedIDs(it.iDs)
}
} catch (ignored: TwitterException) {}
try {
forEachCursor(twitter::getMutesIDs) {
suppressor.addMutedIDs(it.iDs)
}
} catch (ignored: TwitterException) {}
try {
suppressor.addNoRetweetIDs(twitter.noRetweetsFriendships.iDs)
} catch (ignored: TwitterException) {}
}
}
}
}
override fun getApiClient(userRecord: AuthUserRecord?): Any? {
if (userRecord == null) {
return twitterFactory.instance
}
if (userRecord.Provider.apiType != Provider.API_TWITTER) {
return null
}
return synchronized(twitterInstances) {
if (twitterInstances.indexOfKey(userRecord.NumericId) < 0) {
twitterInstances.put(userRecord.NumericId, twitterFactory.getInstance(userRecord.twitterAccessToken))
}
twitterInstances.get(userRecord.NumericId).also {
if (it?.oAuthAccessToken?.userId != userRecord.NumericId) {
throw InstanceCacheBrokenException()
}
}
}
}
override fun getPostValidator(userRecord: AuthUserRecord): PostValidator {
return TweetValidator()
}
override fun getAccountUrl(userRecord: AuthUserRecord): String {
return TwitterUtil.getProfileUrl(userRecord.ScreenName)
}
// 互換用
fun createFavorite(userRecord: AuthUserRecord, id: Long): Boolean {
val twitter = twitterProvider.getTwitter(userRecord) ?: throw IllegalStateException("Twitterとの通信の準備に失敗しました")
try {
val status = twitter.createFavorite(id)
Handler(Looper.getMainLooper()).post {
Toast.makeText(context, "ふぁぼりました (@" + userRecord.ScreenName + ")", Toast.LENGTH_SHORT).show()
}
timelineHub.onFavorite(ShadowUser(userRecord), TwitterStatus(status, userRecord))
return true
} catch (e: TwitterException) {
e.printStackTrace()
Handler(Looper.getMainLooper()).post {
Toast.makeText(context, "ふぁぼれませんでした (@" + userRecord.ScreenName + ")", Toast.LENGTH_SHORT).show()
}
}
return false
}
override fun createFavorite(userRecord: AuthUserRecord, status: Status): Boolean {
val twitter = twitterProvider.getTwitter(userRecord) ?: throw IllegalStateException("Twitterとの通信の準備に失敗しました")
try {
val favoritedStatus = twitter.createFavorite(status.id)
Handler(Looper.getMainLooper()).post {
Toast.makeText(context, "ふぁぼりました (@" + userRecord.ScreenName + ")", Toast.LENGTH_SHORT).show()
}
timelineHub.onFavorite(ShadowUser(userRecord), TwitterStatus(favoritedStatus, userRecord))
return true
} catch (e: TwitterException) {
e.printStackTrace()
Handler(Looper.getMainLooper()).post {
Toast.makeText(context, "ふぁぼれませんでした (@" + userRecord.ScreenName + ")", Toast.LENGTH_SHORT).show()
}
}
return false
}
override fun destroyFavorite(userRecord: AuthUserRecord, status: Status): Boolean {
val twitter = twitterProvider.getTwitter(userRecord) ?: throw IllegalStateException("Twitterとの通信の準備に失敗しました")
try {
val unfavoriteStatus = twitter.destroyFavorite(status.id)
Handler(Looper.getMainLooper()).post {
Toast.makeText(context, "あんふぁぼしました (@" + userRecord.ScreenName + ")", Toast.LENGTH_SHORT).show()
}
timelineHub.onUnfavorite(ShadowUser(userRecord), TwitterStatus(unfavoriteStatus, userRecord))
return true
} catch (e: TwitterException) {
e.printStackTrace()
Handler(Looper.getMainLooper()).post {
Toast.makeText(context, "あんふぁぼに失敗しました (@" + userRecord.ScreenName + ")", Toast.LENGTH_SHORT).show()
}
}
return false
}
override fun postStatus(userRecord: AuthUserRecord, draft: StatusDraft, mediaList: List<File>): Status {
val twitter = twitterProvider.getTwitter(userRecord) ?: throw IllegalStateException("Twitterとの通信の準備に失敗しました")
try {
if (draft.isDirectMessage) {
val inReplyTo = draft.inReplyTo?.url?.let { TwitterUtil.getUserIdFromUrl(it) } ?: -1
if (inReplyTo == -1L) {
throw ProviderApiException("返信先に不正な値が指定されました。")
}
val users = twitter.lookupUsers(inReplyTo, userRecord.NumericId)
val result = twitter.sendDirectMessage(inReplyTo, draft.text)
return TwitterMessage(result,
users.first { it.id == userRecord.NumericId },
users.first { it.id == inReplyTo },
userRecord)
} else {
var text = draft.text
var attachmentUrl = ""
// 画像添付なしで、ツイートを引用している場合は1つだけattachmentUrlに移動させる
if (mediaList.isEmpty()) {
val matcher = PATTERN_QUOTE.matcher(text)
if (matcher.find()) {
val matchUrl = matcher.group().trim()
val newText = matcher.replaceAll("")
// 本文が空になってしまうと投稿できないため、その場合はattachmentUrlに移動させない
if (newText.isNotEmpty()) {
attachmentUrl = matchUrl
text = newText
}
}
}
val update = StatusUpdate(text)
if (attachmentUrl.isNotEmpty()) {
update.attachmentUrl = attachmentUrl
}
// 返信先URLが設定されている場合はin-reply-toに設定する
val inReplyTo = draft.inReplyTo
if (inReplyTo != null) {
val inReplyToId = TwitterUtil.getStatusIdFromUrl(inReplyTo.url)
if (inReplyToId > -1) {
update.inReplyToStatusId = inReplyToId
}
}
// 添付メディアのアップロード
val mediaIds = mediaList.map { file ->
uploadMedia(userRecord, file).mediaId
}
update.setMediaIds(*mediaIds.toLongArray())
// フラグ付きメディアの設定
update.isPossiblySensitive = draft.isPossiblySensitive
putDebugLog(update.toString())
val result = twitter.updateStatus(update)
val status = TwitterStatus(result, userRecord)
timelineHub.onStatus("Twitter.PostStatus", status, true)
return status
}
} catch (e: TwitterException) {
throw ProviderApiException("${e.errorCode} ${e.errorMessage}", e)
}
}
override fun repostStatus(userRecord: AuthUserRecord, status: Status): Boolean {
val twitter = twitterProvider.getTwitter(userRecord) ?: throw IllegalStateException("Twitterとの通信の準備に失敗しました")
try {
twitter.retweetStatus(status.id)
Handler(Looper.getMainLooper()).post {
Toast.makeText(context, "RTしました (@" + userRecord.ScreenName + ")", Toast.LENGTH_SHORT).show()
}
return true
} catch (e: TwitterException) {
e.printStackTrace()
Handler(Looper.getMainLooper()).post {
Toast.makeText(context, "RTに失敗しました (@" + userRecord.ScreenName + ")", Toast.LENGTH_SHORT).show()
}
}
return false
}
override fun destroyStatus(userRecord: AuthUserRecord, status: Status): Boolean {
val twitter = twitterProvider.getTwitter(userRecord) ?: throw IllegalStateException("Twitterとの通信の準備に失敗しました")
try {
twitter.destroyStatus(status.id)
timelineHub.onDelete(Provider.TWITTER.host, status.id)
Handler(Looper.getMainLooper()).post {
Toast.makeText(context, "ツイートを削除しました", Toast.LENGTH_SHORT).show()
}
return true
} catch (e: TwitterException) {
e.printStackTrace()
Handler(Looper.getMainLooper()).post {
Toast.makeText(context, "ツイート削除に失敗しました", Toast.LENGTH_SHORT).show()
}
}
return false
}
override fun showStatus(userRecord: AuthUserRecord, url: String): Status {
val twitter = twitterProvider.getTwitter(userRecord) ?: throw IllegalStateException("Twitterとの通信の準備に失敗しました")
try {
val id = url.toLongOrNull()
if (id != null) {
return TwitterStatus(twitter.showStatus(id), userRecord)
}
val matcher = PATTERN_TWITTER.matcher(url)
if (matcher.find()) {
val extractId = matcher.group(1).toLongOrNull()
if (extractId != null) {
return TwitterStatus(twitter.showStatus(extractId), userRecord)
}
}
throw IllegalArgumentException("非対応URLです : $url")
} catch (e: TwitterException) {
throw ProviderApiException(cause = e)
}
}
private fun uploadMedia(userRecord: AuthUserRecord, file: File): UploadedMedia {
val twitter = twitterProvider.getTwitter(userRecord) ?: throw IllegalStateException("Twitterとの通信の準備に失敗しました")
return twitter.uploadMedia(file)
}
private inline fun <T : CursorSupport> forEachCursor(cursorSupport: (Long) -> T, action: (T) -> Unit) {
var cursor = -1L
do {
val cs = cursorSupport(cursor)
action(cs)
cursor = cs.nextCursor
} while (cs.hasNext())
}
companion object {
private val PATTERN_TWITTER = Pattern.compile("^https?://(?:www\\.)?(?:mobile\\.)?twitter\\.com/(?:#!/)?[0-9a-zA-Z_]{1,15}/status(?:es)?/([0-9]+)/?(?:\\?.+)?\$")
private val PATTERN_QUOTE = Pattern.compile("\\shttps?://(?:www\\.)?(?:mobile\\.)?twitter\\.com/(?:#!/)?[0-9a-zA-Z_]{1,15}/status(?:es)?/([0-9]+)/?(?:\\?.+)?\$")
}
class InstanceCacheBrokenException : Exception("TwitterインスタンスキャッシュのAccessTokenと、要求しているアカウントのUserIDが一致しません!")
} | 58 | Java | 3 | 60 | 28ce3e38b9cf44308bab74f1b6cb8d39a4de2509 | 12,999 | Yukari | Apache License 2.0 |
app/src/main/kotlin/com/rayfantasy/icode/util/ErrorFormat.kt | RayFantasyStudio | 55,142,510 | false | null | /*
* Copyright 2015-2016 RayFantasy Studio
*
* 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.rayfantasy.icode.util
import android.app.Activity
import com.rayfantasy.icode.R
/**
* Created by qweas on 2016/2/3 0003.
*/
fun error(operation: String, rc: Int, activity: Activity): String {
return when (operation) {
"insertCodeGood" -> when (rc) {
-1 -> getStringResources(activity, R.string.internet_error)
-2 -> getStringResources(activity, R.string.failed_to_analysis_local_data_error)
-3 -> getStringResources(activity, R.string.failed_to_analysis_server_data_error)
1 -> getStringResources(activity, R.string.server_unknow_exception_error)
-4 -> getStringResources(activity, R.string.user_not_login_error)
2 -> getStringResources(activity, R.string.cannot_insert_data_to_database_error)
3 -> getStringResources(activity, R.string.check_user_failed_error)
else -> getStringResources(activity, R.string.unknow_error)
}
"addReply" -> when (rc) {
4 -> getStringResources(activity, R.string.check_user_failed_error)
2 -> getStringResources(activity, R.string.cannot_insert_data_to_database_error)
5 -> getStringResources(activity, R.string.sent_code_interval_too_short_error)
-4 -> getStringResources(activity, R.string.user_not_login_error)
3 -> getStringResources(activity, R.string.check_user_failed_error)
else -> getStringResources(activity, R.string.unknow_error)
}
"registerUser" -> when (rc) {
2 -> getStringResources(activity, R.string.cannot_insert_data_to_database_error)
3 -> getStringResources(activity, R.string.check_user_failed_error)
4 -> getStringResources(activity, R.string.pwd_too_short)
5 -> getStringResources(activity, R.string.imei_illegal)
6 -> getStringResources(activity, R.string.imei_already_existed)
else -> getStringResources(activity, R.string.unknow_error)
}
"loginUser" -> when (rc) {
2 -> getStringResources(activity, R.string.cannot_find_user)
3 -> getStringResources(activity, R.string.pwd_error)
else -> getStringResources(activity, R.string.unknow_error)
}
"delete" -> when (rc) {
-4 -> getStringResources(activity, R.string.user_not_login_error)
2 -> getStringResources(activity, R.string.cannot_find_id_in_reply_database_error)
3 -> getStringResources(activity, R.string.check_user_failed_error)
else -> getStringResources(activity, R.string.unknow_error)
}
"editCodeGood" -> when (rc) {
-4 -> getStringResources(activity, R.string.user_not_login_error)
-5 -> getStringResources(activity, R.string.id_is_empty_error)
2 -> getStringResources(activity, R.string.cannot_find_id_in_reply_database_error)
3 -> getStringResources(activity, R.string.check_user_failed_error)
else -> getStringResources(activity, R.string.unknow_error)
};
else -> getStringResources(activity, R.string.unknow_error)
}
}
fun getStringResources(activity: Activity, id: Int) = activity.resources.getString(id) | 0 | Kotlin | 2 | 2 | d82b02c9503152b3a0919db09f66d50f4aae6d53 | 3,856 | iCode-Android-KBinding | Apache License 2.0 |
tangem-sdk/src/main/java/com/tangem/tangem_sdk_new/ui/NfcLocation.kt | Gimly-Blockchain | 267,425,784 | true | {"Java Properties": 8, "Gradle": 8, "Shell": 1, "Markdown": 2, "Batchfile": 1, "Text": 27, "Ruby": 2, "Ignore List": 1, "XML": 397, "INI": 3, "Proguard": 2, "Kotlin": 127, "JSON": 252, "SQL": 9, "Motorola 68K Assembly": 9, "Java": 166, "JAR Manifest": 1, "HTML": 16, "CSS": 6, "JavaScript": 3, "YAML": 1} | package com.tangem.tangem_sdk_new.ui
enum class NfcLocation(val codename: String, val fullName: String, val orientation: Int, val x: Int, val y: Int, val z: Int) {
model1("sailfish", "Google Pixel", 0, 65, 25, 0),
model2("walleye", "Google Pixel 2", 0, 40, 15, 0),
model3("taimen", "Google Pixel 2 XL", 0, 40, 15, 0),
model4("marlin", "Google Pixel XL", 0, 65, 25, 0),
model5("blueline", "Google Pixel 3 ", 0, 40, 30, 0),
model6("crosshatch", "Google Pixel 3 XL", 0, 15, 20, 0),
model7("htc_pme", "HTC 10 ", 0, 50, 20, 0),
model8("htc_himau", "HTC One M9", 0, 50, 20, 0),
model9("htc_himaw", "HTC One M9", 0, 50, 20, 0),
model10("htc_oce", "HTC U Ultra", 0, 50, 20, 0),
model11("htc_ocn", "HTC U11", 0, 50, 25, 0),
model12("htc_ocm", "HTC U11+", 0, 50, 60, 0),
model13("htc_ocluhljapan", "HTC U11 Life", 1, 50, 25, 0),
model14("htc_haydugl", "HTC U11 EYEs", 0, 50, 65, 0),
model15("htc_haydtwl", "HTC U11 EYEs", 0, 50, 65, 0),
model16("htc_ime", "HTC U12+", 0, 50, 20, 0),
model17("htc_bre2dugl", "HTC Desire 12s", 0, 50, 10, 0),
model18("htc_imldugl", "HTC U12 Life", 0, 60, 20, 0),
model19("htc_exodugl", "HTC EXODUS 1", 0, 50, 20, 0),
model20("HWFRD", "Huawei Honor 8", 0, 50, 0, 0),
model21("HWDUK", "Huawei Honor 8 Pro", 0, 50, 0, 0),
model22("HWSTF", "Huawei Honor 9", 0, 50, 0, 0),
model23("HWCOL", "Huawei Honor 10", 0, 50, 0, 0),
model24("HWRVL", "Huawei Honor Note 10", 0, 50, 0, 0),
model25("HWBKL", "Huawei Honor View 10", 0, 50, 0, 0),
model26("HWPCT", "Huawei HONOR V20", 0, 60, 20, 0),
model27("HWTNY", "Huawei Honor Magic 2", 0, 50, 0, 0),
model28("HWBLN-H", "Huawei Mate 9 Lite / Honor 6X", 0, 40, 0, 0),
model29("HWALP", "Huawei Mate 10", 0, 50, 0, 0),
model30("HWBLA", "Huawei Mate 10 Pro", 0, 50, 0, 0),
model31("HWHMA", "Huawei Mate 20", 0, 50, 20, 0),
model32("HWEVR", "Huawei Mate 20 X", 0, 50, 20, 0),
model33("HWLYA", "Huawei Mate 20 Pro", 0, 50, 20, 0),
model34("angler", "Huawei Nexus 6P", 0, 40, 15, 0),
model35("hwALE-", "Huawei P8 Lite ", 1, 75, 65, 0),
model36("HWPRA-H", "Huawei P8 Lite 2017", 0, 50, 25, 0),
model37("HWEVA", "Huawei P9", 0, 50, 0, 0),
model38("HWVIE", "Huawei P9 Plus", 0, 50, 0, 0),
model39("HWVNS-?", "Huawei P9 Lite", 0, 60, 45, 0),
model40("HWVTR", "Huawei P10", 0, 50, 0, 0),
model41("HWWAS-H", "Huawei P10 lite", 0, 50, 0, 0),
model42("HWVKY", "Huawei P10 Plus", 0, 50, 0, 0),
model43("HWEML", "Huawei P20", 0, 50, 50, 0),
model44("HWANE", "Huawei P20 Lite", 0, 50, 20, 0),
model45("HWCLT", "Huawei P20 Pro", 0, 50, 50, 0),
model46("HW-01K", "Huawei P20 Pro", 0, 50, 50, 0),
model47("HWELE", "Huawei P30", 0, 50, 50, 0),
model48("HWVOG", "Huawei P30 Pro", 0, 50, 50, 0),
model49("HW-02L", "Huawei P30 Pro", 0, 50, 50, 0),
model50("HWFIG-H", "Huawei P Smart", 0, 45, 0, 0),
model51("HWPOT-H", "Huawei P smart 2019", 0, 50, 20, 0),
model52("h1", "LG G5", 0, 30, 20, 0),
model53("lucye", "LG G6", 0, 50, 50, 0),
model54("judyln", "LG G7", 0, 50, 50, 0),
model55("hammerhead", "LG Nexus 5", 0, 50, 50, 0),
model56("bullhead", "LG Nexus 5X", 0, 45, 15, 0),
model57("mh", "LG Q6", 1, 25, 50, 0),
model58("ph2n", "LG Stylo 2+", 0, 75, 20, 0),
model59("sf340n", "LG Stylo 3+", 0, 75, 20, 0),
model60("ph1n", "LG Stylus 2", 0, 75, 20, 0),
model61("msf3", "LG Stylus 3", 0, 75, 20, 0),
model62("elsa", "LG V20", 0, 50, 15, 0),
model63("joan", "LG V30", 0, 50, 50, 0),
model64("L-01K", "LG V30+", 0, 50, 50, 0),
model65("judyp", "LG V35 ThinQ", 0, 50, 50, 0),
model66("judyln", "LG G7 ThinQ", 0, 50, 50, 0),
model67("L-02K", "LG JOJO", 0, 50, 60, 0),
model68("mcv5a", "LG Q7", 0, 50, 60, 0),
model69("cv7a", "LG Stylo 4", 0, 50, 60, 0),
model70("nora_8917_n", "Motorola Moto E5", 0, 50, 40, 0),
model71("potter_n", "Motorola Moto G5 Plus", 0, 50, 5, 0),
model72("montana_n", "Motorola Moto G5s", 0, 50, 5, 0),
model73("sanders_n", "Motorola Moto G5s Plus", 0, 50, 5, 0),
model74("ali_n", "Motorola Moto G6", 0, 50, 35, 0),
model75("aljeter_n", "Motorola Moto G6 Play", 0, 50, 35, 0),
model76("evert_n", "Motorola Moto G6 Plus", 0, 40, 40, 0),
model77("river_n", "Motorola moto g(7)", 0, 50, 50, 0),
model78("lake_n", "Motorola moto g(7) plus", 0, 50, 50, 0),
model79("payton", "Motorola Moto X4", 0, 50, 40, 0),
model80("nash", "Motorola Moto Z2 Force", 0, 50, 40, 0),
model81("albus", "Motorola Moto Z2 Play", 0, 50, 5, 0),
model82("beckham", "Motorola Moto Z3 Play", 0, 50, 0, 0),
model83("shamu", "Motorola Nexus 6", 0, 50, 60, 0),
model84("NE1", "Nokia 3", 0, 40, 30, 0),
model85("ND1", "Nokia 5", 0, 40, 30, 0),
model86("PLE", "Nokia 6", 0, 50, 20, 0),
model87("PL2_sprout", "Nokia 6.1", 0, 50, 0, 0),
model88("C1N", "Nokia 7", 0, 50, 25, 0),
model89("B2N", "Nokia 7 Plus", 0, 75, 10, 0),
model90("NB1", "Nokia 8", 0, 50, 30, 0),
model91("A1N_sprout", "Nokia 8 Sirocco", 0, 90, 0, 0),
model92("A1N", "Nokia 8 Sirocco", 0, 90, 0, 0),
model93("OnePlus3", "OnePlus 3", 0, 50, 15, 0),
model94("OnePlus3T", "OnePlus 3t", 0, 50, 15, 0),
model95("OnePlus5", "OnePlus 5", 0, 80, 5, 0),
model96("OnePlus5T", "OnePlus 5t", 0, 80, 5, 0),
model97("OnePlus6", "OnePlus 6", 0, 50, 20, 0),
model98("A0001", "OnePlus One", 0, 50, 50, 0),
model99("OnePlus6T", "OnePlus6T", 0, 50, 20, 0),
model100("OnePlus6TSingle", "OnePlus6T", 0, 50, 20, 0),
model101("OnePlus7Pro", "OnePlus 7 Pro", 0, 30, 25, 0),
model102("OnePlus7ProTMO", "OnePlus 7 Pro", 0, 30, 25, 0),
model103("a5x", "Samsung Galaxy A5 (2016)", 1, 50, 45, 0),
model104("a5y17lte", "Samsung Galaxy A5 (2017)", 1, 65, 45, 0),
model105("a7y17lte", "Samsung Galaxy A7 (2017)", 1, 60, 40, 0),
model106("a7y18lte", "Samsung Galaxy A7 (2018)", 0, 40, 20, 0),
model107("a7y18lteks", "Samsung Galaxy A7 (2018)", 0, 40, 20, 0),
model108("jackpotlte", "Samsung Galaxy A8 (2018)", 1, 50, 50, 0),
model109("a8", "Samsung Galaxy A8 / A8 (2016)", 0, 50, 15, 0),
model110("jackpot2lte", "Samsung Galaxy A8+", 1, 50, 45, 0),
model111("a8sqlte", "Samsung Galaxy A8s", 0, 50, 25, 0),
model112("a8sqltechn", "Samsung Galaxy A8s", 0, 50, 25, 0),
model113("a9xltechn", "Samsung Galaxy A9 (2016)", 1, 50, 45, 0),
model114("a9y18qltekx", "Samsung Galaxy A9 (2018)", 0, 40, 25, 0),
model115("a9y18qlte", "Samsung Galaxy A9 (2018)", 0, 40, 25, 0),
model116("c5ltechn", "Samsung Galaxy C5", 0, 45, 15, 0),
model117("c5pltechn", "Samsung Galaxy C5", 0, 45, 15, 0),
model118("c5proltechn", "Samsung Galaxy C5 Pro", 1, 45, 15, 0),
model119("c7ltechn", "Samsung Galaxy C7", 0, 50, 15, 0),
model120("c7prolte", "Samsung Galaxy C7 Pro", 1, 50, 15, 0),
model121("c9lte", "Samsung Galaxy C9 Pro", 0, 45, 15, 0),
model122("j5x", "Samsung Galaxy J5 (2016)", 1, 40, 50, 0),
model123("j5y17lte", "Samsung Galaxy J5 (2017) / J5 Pro", 1, 60, 50, 0),
model124("j6lte", "Samsung Galaxy J6", 1, 60, 50, 0),
model125("j7y17lte", "Samsung Galaxy J7 Pro", 1, 40, 50, 0),
model126("noblelte", "Samsung Galaxy Note5", 1, 50, 60, 0),
model127("SCV37", "Samsung Galaxy Note8", 1, 50, 45, 0),
model128("SC-01K", "Samsung Galaxy Note8", 1, 50, 45, 0),
model129("great", "Samsung Galaxy Note8", 1, 50, 45, 0),
model130("crownqle", "Samsung Galaxy Note9", 1, 50, 50, 0),
model131("crownlte", "Samsung Galaxy Note9", 1, 50, 50, 0),
model132("SC-01L", "Samsung Galaxy Note9", 1, 50, 50, 0),
model133("SCV40", "Samsung Galaxy Note9", 1, 50, 50, 0),
model134("SC-05G", "Samsung Galaxy S6", 1, 30, 60, 0),
model135("zeroflte", "Samsung Galaxy S6", 1, 30, 60, 0),
model136("SCV31", "Samsung Galaxy S6 edge", 1, 30, 60, 0),
model137("404SC", "Samsung Galaxy S6 edge", 1, 30, 60, 0),
model138("SC-04G", "Samsung Galaxy S6 edge", 1, 30, 60, 0),
model139("zerolte", "Samsung Galaxy S6 edge", 1, 30, 60, 0),
model140("zenlte", "Samsung Galaxy S6 edge+", 1, 50, 55, 0),
model141("heroqlte", "Samsung Galaxy S7", 1, 50, 45, 0),
model142("herolte", "Samsung Galaxy S7", 1, 50, 45, 0),
model143("poseidonlteatt", "Samsung Galaxy S7 Active", 1, 45, 55, 0),
model144("SCV33", "Samsung Galaxy S7 Edge", 1, 50, 45, 0),
model145("SC-02H", "Samsung Galaxy S7 Edge", 1, 50, 45, 0),
model146("hero2", "Samsung Galaxy S7 Edge", 1, 50, 45, 0),
model147("SCV36", "Samsung Galaxy S8", 0, 50, 55, 0),
model148("SC-02J", "Samsung Galaxy S8", 0, 50, 55, 0),
model149("dreamlte", "Samsung Galaxy S8", 0, 50, 55, 0),
model150("dreamqlte", "Samsung Galaxy S8", 0, 50, 55, 0),
model151("cruiserlte", "Samsung Galaxy S8 Active", 0, 50, 50, 0),
model152("SCV35", "Samsung Galaxy S8+", 0, 50, 45, 0),
model153("SC-03J", "Samsung Galaxy S8+", 0, 50, 45, 0),
model154("dream2", "Samsung Galaxy S8+", 0, 50, 45, 0),
model155("SCV38", "Samsung Galaxy S9", 0, 50, 50, 0),
model156("SC-02K", "Samsung Galaxy S9", 0, 50, 50, 0),
model157("starlte", "Samsung Galaxy S9", 0, 50, 50, 0),
model158("starqlte", "Samsung Galaxy S9", 0, 50, 50, 0),
model159("SCV39", "Samsung Galaxy S9+", 0, 50, 60, 0),
model160("SC-03K", "Samsung Galaxy S9+", 0, 50, 60, 0),
model161("star2", "Samsung Galaxy S9+", 0, 50, 60, 0),
model162("beyond1q", "Samsung Galaxy S10", 0, 50, 50, 0),
model163("beyond1", "Samsung Galaxy S10", 0, 50, 50, 0),
model164("beyond2q", "Samsung Galaxy S10+", 0, 50, 50, 0),
model165("beyond2", "Samsung Galaxy S10+", 0, 50, 50, 0),
model166("beyond0q", "Samsung Galaxy S10e", 0, 50, 50, 0),
model167("beyond0", "Samsung Galaxy S10e", 0, 50, 50, 0),
model168("F331", "Sony Xperia E5", 0, 50, 25, 0),
model169("G33", "Sony Xperia L1", 0, 50, 30, 0),
model170("H33", "Sony Xperia L2", 0, 50, 20, 0),
model171("H43", "Sony Xperia L2", 0, 50, 20, 0),
model172("F512", "Sony Xperia X", 0, 10, 5, 1),
model173("suzu", "Sony Xperia X", 0, 10, 5, 1),
model174("F5321", "Sony Xperia X Compact", 0, 50, 55, 0),
model175("SO-02J", "Sony Xperia X Compact", 0, 50, 55, 0),
model176("F813", "Sony Xperia X Performance", 0, 10, 5, 1),
model177("SOV33", "Sony Xperia X Performance", 0, 10, 5, 1),
model178("SO-04H", "Sony Xperia X Performance", 0, 10, 5, 1),
model179("502SO", "Sony Xperia X Performance", 0, 10, 5, 1),
model180("F311", "Sony Xperia XA", 0, 50, 20, 0),
model181("F321", "Sony Xperia XA Ultra", 0, 50, 25, 0),
model182("G31", "Sony Xperia XA1", 0, 50, 20, 0),
model183("G34", "Sony Xperia XA1 Plus", 0, 50, 25, 0),
model184("G32", "Sony Xperia XA1 Ultra", 0, 50, 20, 0),
model185("H31", "Sony Xperia XA2", 0, 50, 15, 0),
model186("H41", "Sony Xperia XA2", 0, 50, 15, 0),
model187("H4493", "Sony Xperia XA2 Plus", 0, 50, 20, 0),
model188("H4413", "Sony Xperia XA2 Plus", 0, 50, 20, 0),
model189("H3413", "Sony Xperia XA2 Plus", 0, 50, 20, 0),
model190("H32", "Sony Xperia XA2 Ultra", 0, 50, 20, 0),
model191("H42", "Sony Xperia XA2 Ultra", 0, 50, 20, 0),
model192("F833", "S<NAME>", 0, 20, 5, 1),
model193("SO-01J", "Sony Xperia XZ", 0, 20, 5, 1),
model194("601SO", "S<NAME>", 0, 20, 5, 1),
model195("SOV34", "<NAME>", 0, 20, 5, 1),
model196("G81", "Sony Xperia XZ Premium", 0, 50, 55, 0),
model197("SO-04J", "Sony Xperia XZ Premium", 0, 50, 55, 0),
model198("G834", "Sony Xperia XZ1", 0, 45, 5, 0),
model199("701SO", "Sony Xperia XZ1", 0, 45, 5, 0),
model200("SOV36", "Sony Xperia XZ1", 0, 45, 5, 0),
model201("SO-01K", "Sony Xperia XZ1", 0, 45, 5, 0),
model202("G8441", "Sony Xperia XZ1 Compact", 0, 50, 30, 0),
model203("SO-02K", "Sony Xperia XZ1 Compact", 0, 50, 30, 0),
model204("H82", "Sony Xperia XZ2", 0, 20, 40, 0),
model205("SOV37", "Sony Xperia XZ2", 0, 20, 40, 0),
model206("SO-03K", "Sony Xperia XZ2", 0, 20, 40, 0),
model207("702SO", "Sony Xperia XZ2", 0, 20, 40, 0),
model208("H8166", "Sony Xperia XZ2 Premium", 0, 60, 20, 0),
model209("SO-04K", "Sony Xperia XZ2 Premium", 0, 60, 20, 0),
model210("SOV38", "Sony Xperia XZ2 Premium", 0, 60, 20, 0),
model211("H8116", "Sony Xperia XZ2 Premium", 0, 60, 20, 0),
model212("H8324", "Sony Xperia XZ2 Compact", 0, 50, 25, 0),
model213("SO-05K", "Sony Xperia XZ2 Compact", 0, 50, 25, 0),
model214("H8314", "Sony Xperia XZ2 Compact", 0, 50, 25, 0),
model215("G823", "Sony Xperia XZs", 0, 20, 5, 1),
model216("602SO", "Sony Xperia XZs", 0, 20, 5, 1),
model217("SOV35", "Sony Xperia XZs", 0, 20, 5, 1),
model218("SO-03J", "Sony Xperia XZs", 0, 20, 5, 1),
model219("801SO", "Sony Xperia XZ3", 0, 60, 20, 0),
model220("H9493", "Sony Xperia XZ3", 0, 60, 20, 0),
model221("H9436", "Sony Xperia XZ3", 0, 60, 20, 0),
model222("SOV39", "Sony Xperia XZ3", 0, 60, 20, 0),
model223("SO-01L", "Sony Xperia XZ3", 0, 60, 20, 0),
model224("H8416", "Sony Xperia XZ3", 0, 60, 20, 0),
model225("gemini", "Xiaomi Mi 5", 0, 40, 20, 0),
model226("capricorn", "Xiaomi Mi 5S", 0, 50, 10, 0),
model227("natrium", "Xiaomi Mi 5S Plus", 0, 45, 15, 0),
model228("sagit", "Xiaomi Mi 6", 0, 50, 20, 0),
model229("dipper", "Xiaomi Mi 8", 0, 45, 20, 0),
model230("ursa", "Xiaomi MI 8 Explorer Edition", 0, 50, 40, 0),
model231("cepheus", "Xiaomi MI 9", 0, 40, 20, 0),
model232("grus", "Xiaomi MI 9 SE", 0, 40, 20, 0),
model233("lithium", "Xiaomi Mi MIX", 0, 20, 20, 0),
model234("chiron", "Xiaomi Mi MIX 2", 0, 45, 20, 0),
model235("polaris", "Xiaomi Mi MIX 2S", 0, 45, 20, 0),
model236("scorpio", "Xiaomi Mi Note 2", 0, 50, 20, 0),
model237("jason", "Xiaomi Mi Note 3", 0, 50, 20, 0),
model238("perseus", "Xiaomi MIX 3", 0, 60, 20, 0),
model239("bbb100", "BlackBerry KEYone", 0, 60, 20, 0),
model240("bbf100", "BlackBerry KEY2", 0, 50, 30, 0),
model241("CatS61", "Cat S61", 0, 50, 50, 0),
} | 0 | Java | 0 | 1 | a94cb113f3aa720406fea0880bccf127702ac521 | 14,076 | tangem-sdk-android | MIT License |
2017/src/main/kotlin/Day08.kt | dlew | 498,498,097 | false | {"Kotlin": 331659, "TypeScript": 69253, "Python": 15598, "JavaScript": 262} | import utils.splitNewlines
import utils.splitWhitespace
object Day08 {
fun part1(input: String): Int {
val registers = mutableMapOf<String, Int>().withDefault { 0 }
val instructions = input.splitNewlines().map(this::parseInstruction)
for (instruction in instructions) {
execute(registers, instruction)
}
return registers.maxValue()
}
fun part2(input: String): Int {
val registers = mutableMapOf<String, Int>().withDefault { 0 }
var maxValue = registers.maxValue()
val instructions = input.splitNewlines().map(this::parseInstruction)
for (instruction in instructions) {
execute(registers, instruction)
maxValue = maxOf(registers.maxValue(), maxValue)
}
return maxValue
}
data class Instruction(val register: String, val amount: Int, val condition: Condition)
data class Condition(val leftOperand: String, val operator: String, val rightOperand: Int)
private fun parseInstruction(instruction: String): Instruction {
val split = instruction.splitWhitespace()
val register = split[0]
val incrementing = split[1] == "inc"
val amount = split[2].toInt() * if (incrementing) 1 else -1
val left = split[4]
val operator = split[5]
val right = split[6].toInt()
return Instruction(
register = register,
amount = amount,
condition = Condition(
leftOperand = left,
operator = operator,
rightOperand = right
)
)
}
private fun execute(registers: MutableMap<String, Int>, instruction: Instruction) {
if (checkCondition(registers, instruction.condition)) {
val newValue = registers.getValue(instruction.register) + instruction.amount
registers[instruction.register] = newValue
}
}
private fun checkCondition(registers: Map<String, Int>, condition: Condition): Boolean {
val leftOperand = registers.getValue(condition.leftOperand)
return when (condition.operator) {
">" -> leftOperand > condition.rightOperand
">=" -> leftOperand >= condition.rightOperand
"==" -> leftOperand == condition.rightOperand
"!=" -> leftOperand != condition.rightOperand
"<" -> leftOperand < condition.rightOperand
"<=" -> leftOperand <= condition.rightOperand
else -> throw IllegalArgumentException("Illegal operator: ${condition.operator}")
}
}
private fun Map<String, Int>.maxValue() = values.max() ?: 0
} | 0 | Kotlin | 0 | 0 | 7b68d89a1228f130ceb6af1111fc5679d90e9c2d | 2,442 | advent-of-code | MIT License |
extension/spring-boot-autoconfigure/src/main/kotlin/io/holixon/axon/gateway/configuration/query/RevisionAwareQueryGatewayConfiguration.kt | holixon | 300,893,720 | false | {"Kotlin": 76933} | package io.holixon.axon.gateway.configuration.query
import io.holixon.axon.gateway.query.RevisionAwareQueryGateway
import org.axonframework.queryhandling.QueryBus
import org.axonframework.queryhandling.QueryGateway
import org.slf4j.LoggerFactory
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty
import org.springframework.boot.context.properties.EnableConfigurationProperties
import org.springframework.context.annotation.Bean
import org.springframework.context.annotation.Configuration
/**
* Activates the revision-aware query gateway.
*/
@Configuration
@EnableConfigurationProperties(RevisionAwareQueryGatewayProperties::class)
@ConditionalOnProperty(prefix = "axon-gateway.query", name = ["type"], havingValue = "revision-aware")
class RevisionAwareQueryGatewayConfiguration {
companion object {
@JvmStatic
private val logger = LoggerFactory.getLogger(RevisionAwareQueryGatewayConfiguration::class.java)
}
/**
* Factory function creating a revision-aware query gateway.
*/
@Bean
fun revisionAwareGateway(queryBus: QueryBus, properties: RevisionAwareQueryGatewayProperties): QueryGateway {
logger.info("REVISION-QUERY-GATEWAY-001: Using revision-aware query gateway.")
return RevisionAwareQueryGateway(queryBus, properties.defaultQueryTimeout)
}
} | 4 | Kotlin | 2 | 6 | a7d4f682b5fd18e5388c6d84fc1d4e47ccf03d00 | 1,319 | axon-gateway-extension | Apache License 2.0 |
core/src/main/kotlin/org/cryptobiotic/rlauxe/core/Cvr.kt | JohnLCaron | 847,947,313 | false | {"Kotlin": 587189} | package org.cryptobiotic.rlauxe.core
// If we knew the contests and candidate indices, we could just use a 2dim array: votes[contest][candidate] : Int
// or we could pass in the Map, but create the index array.
// perhaps the audit contains the string -> index map?
class Cvr(
val id: String,
val votes: Map<Int, Map<Int, Int>>, // contest : candidate : vote
val phantom: Boolean = false
) {
fun hasContest(contestIdx: Int): Boolean = votes[contestIdx] != null
// Let 1candidate(bi) = 1 if ballot i has a mark for candidate, and 0 if not; SHANGRLA section 2, page 4
fun hasMarkFor(contestIdx: Int, candidateIdx: Int): Int {
val contestVotes = votes[contestIdx]
return if (contestVotes == null) 0 else contestVotes[candidateIdx] ?: 0
}
// Is there exactly one vote in the contest among the given candidates?
fun hasOneVote(contestIdx: Int, candidates: List<Int>): Boolean {
val contestVotes = this.votes[contestIdx] ?: return false
val totalVotes = contestVotes.filter{ candidates.contains(it.key) }.map { it.value }.sum()
return (totalVotes == 1)
}
// Is there exactly one vote in the contest among all the legitimate contests?
// This excludes candidates with index >= ncandidates, which are mistakes? miscodeing?
// This assumes candidate indexes are sequential starting at 0.
// This reproduces behavior in SHANGRLA test_Assertion.
// This is only used my supermajority assorter.
fun hasOneVote(contestIdx: Int, ncandidates: Int): Boolean {
val contestVotes = this.votes[contestIdx] ?: return false
val totalVotes = contestVotes.filter { it.key < ncandidates }.map { it.value }.sum()
return (totalVotes == 1)
}
override fun toString(): String {
return "$id: $votes $phantom"
}
}
| 0 | Kotlin | 0 | 0 | 7a916eef31df94bb0639442594267567ae5dd5bc | 1,836 | rlauxe | Open LDAP Public License v1.2 |
simplified-books-database-api/src/main/java/org/nypl/simplified/books/book_database/api/BookFormats.kt | ThePalaceProject | 367,082,997 | false | null | package org.nypl.simplified.books.book_database.api
import one.irradia.mime.api.MIMEType
import one.irradia.mime.vanilla.MIMEParser
import org.nypl.simplified.opds.core.OPDSAcquisitionFeedEntry
/**
* Information about the supported book formats.
*/
object BookFormats {
private fun mimeOf(name: String): MIMEType =
MIMEParser.parseRaisingException(name)
private fun mimesOfList(names: List<String>): Set<MIMEType> =
names.map(this::mimeOf).toSet()
private fun mimesOf(vararg names: String): Set<MIMEType> =
mimesOfList(names.toList())
private fun <T> unionOf(
vararg sets: Set<T>
): Set<T> {
val union = mutableSetOf<T>()
sets.forEach { union.addAll(it) }
return union.toSet()
}
private val FINDAWAY_AUDIO_BOOKS =
mimesOf("application/vnd.librarysimplified.findaway.license+json")
private val GENERIC_AUDIO_BOOKS =
mimesOf(
"application/audiobook+json",
"audio/mpeg"
)
private val LCP_AUDIO_BOOKS =
mimesOf(
"application/audiobook+lcp"
)
private val OVERDRIVE_AUDIO_BOOKS =
mimesOf(
"application/vnd.overdrive.circulation.api+json;profile=audiobook"
)
private val AUDIO_BOOK_MIME_TYPES =
unionOf(
FINDAWAY_AUDIO_BOOKS,
GENERIC_AUDIO_BOOKS,
LCP_AUDIO_BOOKS,
OVERDRIVE_AUDIO_BOOKS
)
private val EPUB_MIME_TYPES =
mimesOf(
"application/epub+zip",
"application/vnd.librarysimplified.axisnow+json"
)
private val PDF_MIME_TYPES =
mimesOf(
"application/pdf"
)
private val SUPPORTED_BOOK_MIME_TYPES =
unionOf(
EPUB_MIME_TYPES,
AUDIO_BOOK_MIME_TYPES,
PDF_MIME_TYPES
)
/**
* @return A set of the MIME types that identify generic audio books
*/
fun audioBookGenericMimeTypes(): Set<MIMEType> =
GENERIC_AUDIO_BOOKS
/**
* @return A set of the MIME types that identify Overdrive audio books
*/
fun audioBookOverdriveMimeTypes(): Set<MIMEType> =
OVERDRIVE_AUDIO_BOOKS
/**
* @return A set of the MIME types that identify Findaway audio books
*/
fun audioBookFindawayMimeTypes(): Set<MIMEType> =
FINDAWAY_AUDIO_BOOKS
/**
* @return A set of the supported book format MIME types
*/
fun supportedBookMimeTypes(): Set<MIMEType> =
SUPPORTED_BOOK_MIME_TYPES
/**
* @return The set of MIME types for EPUBs
*/
fun epubMimeTypes(): Set<MIMEType> =
EPUB_MIME_TYPES
/**
* @return The set of MIME types for EPUBs
*/
fun audioBookMimeTypes(): Set<MIMEType> =
AUDIO_BOOK_MIME_TYPES
/**
* @return The set of MIME types for PDFs
*/
fun pdfMimeTypes(): Set<MIMEType> =
PDF_MIME_TYPES
private val formats = BookFormatDefinition.values()
/**
* @return The probable format of the book in the given OPDS entry
*/
fun inferFormat(entry: OPDSAcquisitionFeedEntry): BookFormatDefinition? {
for (acquisition in entry.acquisitions) {
for (format in formats) {
val available = acquisition.availableFinalContentTypes()
if (available.any { format.supports(it) }) {
return format
}
}
}
return null
}
/**
* The type of available book formats.
*/
enum class BookFormatDefinition {
/**
* The EPUB format.
*/
BOOK_FORMAT_EPUB {
override val shortName: String = "epub"
override fun supportedContentTypes(): Set<MIMEType> {
return epubMimeTypes()
}
},
/**
* The audio book format.
*/
BOOK_FORMAT_AUDIO {
override val shortName: String = "audiobook"
override fun supportedContentTypes(): Set<MIMEType> {
return audioBookMimeTypes()
}
},
/**
* The PDF format
*/
BOOK_FORMAT_PDF {
override val shortName: String = "pdf"
override fun supportedContentTypes(): Set<MIMEType> {
return pdfMimeTypes()
}
};
/**
* The short name of the format
*/
abstract val shortName: String
/**
* The content types supported by this format.
*/
abstract fun supportedContentTypes(): Set<MIMEType>
/**
* @return `true` if the format handle supports content of the given content type
*/
fun supports(
contentType: MIMEType
): Boolean {
return this.supportedContentTypes().any { supportedType ->
contentType.fullType == supportedType.fullType
}
}
}
}
| 109 | null | 4 | 8 | 752bdbdd07177e2819985fe33ed92aeb6d21e0c2 | 4,434 | android-core | Apache License 2.0 |
data-saver-core/src/commonMain/kotlin/com/funny/data_saver/core/DataSaverListState.kt | FunnySaltyFish | 451,806,111 | false | {"Kotlin": 98696} | package com.funny.data_saver.core
import androidx.compose.runtime.Composable
import androidx.compose.runtime.DisposableEffect
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.MutableState
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import com.funny.data_saver.core.DataSaverConverter.findRestorer
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.Job
import kotlinx.coroutines.launch
import kotlin.reflect.KProperty
/**
* A state which holds a list as value. It implements the [MutableState] interface, so you can use
* it just like a normal state.
*
* When assign a new value to it, it will do data persistence according to [SavePolicy], which is IMMEDIATELY
* by default. If you want to save data manually, you can call [saveData].
*
* You can call `val (value, setValue) = state` to get its `set` function.
*
* @param T the class of each element in the list
* @param dataSaverInterface the interface to read/save data, see [DataSaverInterface]
* @param key persistence key
* @param initialValue NOTE: YOU SHOULD READ THE SAVED VALUE AND PASSED IT AS THIS PARAMETER BY YOURSELF(see: [rememberDataSaverListState])
* @param savePolicy how and when to save data, see [SavePolicy]
* @param async Boolean whether to save data asynchronously
* @param coroutineScope CoroutineScope? the scope to launch coroutine, if null, it will create one with [Dispatchers.IO]
*/
class DataSaverMutableListState<T>(
private val dataSaverInterface: DataSaverInterface,
private val key: String,
private val initialValue: List<T> = emptyList(),
private val savePolicy: SavePolicy = SavePolicy.IMMEDIATELY,
private val async: Boolean = false,
private val coroutineScope: CoroutineScope? = null
) : MutableState<List<T>> {
private val listState = mutableStateOf(initialValue)
private var job: Job? = null
private val scope by lazy(LazyThreadSafetyMode.PUBLICATION) {
coroutineScope ?: CoroutineScope(Dispatchers.IO)
}
override var value: List<T>
get() = listState.value
set(value) {
doSetValue(value)
}
@Deprecated(
"请优先使用带`savePolicy`参数的构造函数(The constructor with parameter `savePolicy` is preferred.)",
)
constructor(
dataSaverInterface: DataSaverInterface,
key: String,
value: List<T>,
autoSave: Boolean = true,
) : this(
dataSaverInterface,
key,
value,
if (autoSave) SavePolicy.IMMEDIATELY else SavePolicy.NEVER
)
operator fun setValue(thisObj: Any?, property: KProperty<*>, value: List<T>) {
doSetValue(value)
}
operator fun getValue(thisObj: Any?, property: KProperty<*>): List<T> = listState.value
fun saveData() {
val value = value
if (async) {
job?.cancel()
job = scope.launch {
dataSaverInterface.saveData(
key,
DataSaverConverter.convertListToString(value).also {
log("saveConvertedData(async: $async): $key -> $value(as $it)")
})
}
} else {
dataSaverInterface.saveData(key, DataSaverConverter.convertListToString(value).also {
log("saveConvertedData(async: $async): $key -> $value(as $it)")
})
}
}
fun valueChangedSinceInit() = listState.value.deepEquals(initialValue.toList())
/**
* remove the key and set the value to `replacement`
* @param replacement List<T> new value of the state, `initialValue` by default
*/
fun remove(replacement: List<T> = initialValue) {
dataSaverInterface.remove(key)
listState.value = replacement
log("remove: key: $key, replace the value to $replacement")
}
fun setValueWithoutSave(v: List<T>) {
if (!v.deepEquals(listState.value)) listState.value = v
}
private fun doSetValue(value: List<T>) {
val oldValue = this.listState.value
this.listState.value = value
if (!oldValue.deepEquals(value) && savePolicy == SavePolicy.IMMEDIATELY)
saveData()
}
companion object {
const val TAG = "DataSaverState"
private val logger by lazy(LazyThreadSafetyMode.PUBLICATION) {
DataSaverLogger(DataSaverMutableState.TAG)
}
private fun log(msg: String) {
logger.d(msg)
}
}
override fun component1(): List<T> = value
override fun component2(): (List<T>) -> Unit = ::doSetValue
}
/**
* This function provide an elegant way to do data persistence.
* Check the example in `README.md` to see how to use it.
*
* NOTE: Use another function with parameter `savePolicy` instead
*
* @param key String
* @param default T default value if it is initialized the first time
* @param autoSave Boolean whether to do data persistence each time you do assignment
* @return DataSaverMutableState<T>
*/
@Deprecated("Use another function with parameter `savePolicy` instead", ReplaceWith("rememberDataSaverListState(key=key, initialValue=default)"))
@Composable
inline fun <reified T : Any> rememberDataSaverListState(
key: String,
default: List<T>,
autoSave: Boolean = true
): DataSaverMutableListState<T> = rememberDataSaverListState(
key = key,
initialValue = default,
savePolicy = if (autoSave) SavePolicy.IMMEDIATELY else SavePolicy.NEVER
)
/**
* This function READ AND CONVERT the saved data and return a remembered [DataSaverMutableListState].
* Check the example in `README.md` to see how to use it.
* -------------------------
* 此函数 **读取并转换** 已保存的数据,返回remember后的State
*
* @param key String
* @param initialValue T default value if it is initialized the first time
* @param savePolicy how and when to save data, see [SavePolicy]
* @param async whether to save data asynchronously
* @param senseExternalDataChange whether to sense external data change, default to false. To use this, your [DataSaverInterface.senseExternalDataChange] must be true as well.
* @param coroutineScope CoroutineScope? the scope to launch coroutine, if null, it will create one with [Dispatchers.IO]
* @return DataSaverMutableListState<T>
*/
@Composable
inline fun <reified T : Any> rememberDataSaverListState(
key: String,
initialValue: List<T>,
savePolicy: SavePolicy = SavePolicy.IMMEDIATELY,
async: Boolean = true,
senseExternalDataChange: Boolean = false,
coroutineScope: CoroutineScope? = null,
): DataSaverMutableListState<T> {
val saverInterface = getLocalDataSaverInterface()
var state: DataSaverMutableListState<T>? = null
LaunchedEffect(key1 = senseExternalDataChange) {
if (!senseExternalDataChange || state == null) return@LaunchedEffect
if (!saverInterface.senseExternalDataChange) {
DataSaverLogger.e("to enable senseExternalDataChange, you should set `senseExternalDataChange` to true in DataSaverInterface")
return@LaunchedEffect
}
saverInterface.externalDataChangedFlow?.collect { pair ->
val (k, v) = pair
DataSaverLogger.log("externalDataChangedFlow: $key -> $v")
if (k == key && v != state?.value) {
val d: List<T> = if (v != null) {
try {
v as List<T>
} catch (e: Exception) {
if (v is String) {
val restore = findRestorer<T>()
restore ?: throw e
DataSaverConverter.convertStringToList<T>(v, restore)
} else {
throw e
}
}
} else {
// if the value is null
initialValue
}
// to avoid duplicate save
state?.setValueWithoutSave(d)
}
}
}
DisposableEffect(key, savePolicy) {
onDispose {
DataSaverLogger.log("rememberDataSaverListState: state of key=\"$key\" onDisposed!")
if (savePolicy == SavePolicy.DISPOSED && state != null && state!!.valueChangedSinceInit()) {
state!!.saveData()
}
}
}
return remember(saverInterface, key, async) {
mutableDataSaverListStateOf(
saverInterface,
key,
initialValue,
savePolicy,
async,
coroutineScope
).also { state = it }
}
}
/**
* This function READ AND CONVERT the saved data and return a [DataSaverMutableListState].
* Check the example in `README.md` to see how to use it.
* -------------------------
* 此函数 **读取并转换** 已保存的数据,返回 [DataSaverMutableListState]
*
* @param key String
* @param initialValue T default value if no data persistence has been done
* @param savePolicy how and when to save data, see [SavePolicy]
* @param async whether to save data asynchronously
* @param coroutineScope CoroutineScope? the scope to launch coroutine, if null, it will create one with [Dispatchers.IO]
* @return DataSaverMutableListState<T>
*/
inline fun <reified T> mutableDataSaverListStateOf(
dataSaverInterface: DataSaverInterface,
key: String,
initialValue: List<T> = emptyList(),
savePolicy: SavePolicy = SavePolicy.IMMEDIATELY,
async: Boolean = false,
coroutineScope: CoroutineScope? = null
): DataSaverMutableListState<T> {
val data = try {
if (!dataSaverInterface.contains(key)) initialValue
else dataSaverInterface.readData(key, initialValue)
} catch (e: Exception) {
val restore = findRestorer<T>()
restore ?: throw e
runCatching {
DataSaverConverter.convertStringToList<T>(dataSaverInterface.readData(key, "[]"), restore)
}.onFailure {
DataSaverLogger.e("error while restoring data(key=$key), set to default. StackTrace:\n${it.stackTraceToString()}")
}.getOrDefault(initialValue)
}
return DataSaverMutableListState(dataSaverInterface, key, data, savePolicy, async, coroutineScope)
}
internal fun <T> List<T>.deepEquals(other: List<T>): Boolean {
if (size != other.size) return false
for (i in indices) {
val thisItem = this[i]
val otherItem = other[i]
val itemEquals =
if (thisItem is List<*> && otherItem is List<*>) thisItem.deepEquals(otherItem)
else thisItem == otherItem
if (!itemEquals) return false
}
return true
} | 1 | Kotlin | 5 | 69 | 282f4540481b23eafcb3016d9c39729bea78d519 | 10,681 | ComposeDataSaver | Apache License 2.0 |
seskar/seskar-compiler-plugin/src/main/kotlin/seskar/compiler/union/backend/UnionTransformer.kt | turansky | 279,976,108 | false | null | package seskar.compiler.union.backend
import org.jetbrains.kotlin.backend.common.extensions.IrPluginContext
import org.jetbrains.kotlin.descriptors.ClassKind
import org.jetbrains.kotlin.ir.IrStatement
import org.jetbrains.kotlin.ir.declarations.IrClass
import org.jetbrains.kotlin.ir.declarations.IrDeclarationWithName
import org.jetbrains.kotlin.ir.declarations.IrProperty
import org.jetbrains.kotlin.ir.declarations.createBlockBody
import org.jetbrains.kotlin.ir.expressions.IrExpression
import org.jetbrains.kotlin.ir.expressions.impl.IrConstImpl
import org.jetbrains.kotlin.ir.expressions.impl.IrReturnImpl
import org.jetbrains.kotlin.ir.util.isTopLevelDeclaration
import org.jetbrains.kotlin.ir.visitors.IrElementTransformerVoid
internal class UnionTransformer(
private val context: IrPluginContext,
) : IrElementTransformerVoid() {
override fun visitClass(
declaration: IrClass,
): IrStatement {
if (!declaration.isExternal)
return declaration
val value = declaration.value()
if (value != null && declaration.isTopLevelDeclaration && declaration.kind == ClassKind.OBJECT) {
declaration.annotations += JsName(context, declaration, value.toJsName())
return declaration
}
if (declaration.isJsVirtual()) {
declaration.annotations += JsName(context, declaration, "0")
}
return super.visitClass(declaration)
}
override fun visitProperty(
declaration: IrProperty,
): IrStatement {
val value = declaration.value()
if (value != null) {
addPropertyGetter(declaration, value)
}
return declaration
}
private fun addPropertyGetter(
declaration: IrProperty,
value: Value,
) {
val getter = declaration.getter
?: error("No default getter!")
getter.isInline = true
getter.body = context.irFactory.createBlockBody(
startOffset = declaration.startOffset,
endOffset = declaration.endOffset,
statements = listOf(
IrReturnImpl(
startOffset = declaration.startOffset,
endOffset = declaration.endOffset,
type = context.irBuiltIns.nothingNType,
returnTargetSymbol = getter.symbol,
value = valueConstant(declaration, value),
)
)
)
}
private fun valueConstant(
declaration: IrDeclarationWithName,
value: Value,
): IrExpression {
return when (value) {
is IntValue ->
IrConstImpl.int(
startOffset = declaration.startOffset,
endOffset = declaration.endOffset,
type = context.irBuiltIns.intType,
value = value.value,
)
is StringValue ->
IrConstImpl.string(
startOffset = declaration.startOffset,
endOffset = declaration.endOffset,
type = context.irBuiltIns.stringType,
value = value.value,
)
}
}
}
| 0 | null | 5 | 41 | 6ef30dfce12e2ff8b98c616a9113719fa9d787db | 3,222 | seskar | Apache License 2.0 |
example/android/app/src/main/kotlin/com/instana/flutter/agent_example/MainActivity.kt | instana | 311,961,951 | false | {"Dart": 32316, "Kotlin": 18627, "Swift": 15460, "Ruby": 2262, "Objective-C": 903} | /*
* (c) Copyright IBM Corp. 2021
* (c) Copyright Instana Inc. and contributors 2021
*/
package com.instana.flutter.agent_example
import io.flutter.embedding.android.FlutterActivity
class MainActivity : FlutterActivity() {
}
| 1 | Dart | 4 | 4 | fed600ee927f5d4395b92bc33ce2e13d577ac384 | 231 | flutter-agent | MIT License |
ui/src/main/kotlin/org/wcl/mfn/ui/controller/tools/ContractCalculatorUIController.kt | warnettconsultingltd | 809,363,042 | false | {"Kotlin": 58478, "HTML": 6681, "CSS": 4145} | package org.wcl.mfn.ui.controller.tools
import jakarta.validation.Valid
import jakarta.validation.constraints.Size
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.context.annotation.PropertySource
import org.springframework.core.ParameterizedTypeReference
import org.springframework.http.*
import org.springframework.stereotype.Controller
import org.springframework.ui.Model
import org.springframework.web.bind.annotation.GetMapping
import org.springframework.web.bind.annotation.ModelAttribute
import org.springframework.web.bind.annotation.PostMapping
import org.springframework.web.client.RestTemplate
import org.wcl.mfn.api.controller.tools.ContractCalculatorAPIController
import org.wcl.mfn.config.ui.common.PageTitleConfig
import org.wcl.mfn.config.ui.mvc.*
import org.wcl.mfn.config.ui.tools.*
import org.wcl.mfn.entities.contract.calculator.RequestedRemuneration
import org.wcl.mfn.entities.contract.calculator.SuggestedContract
import org.wcl.mfn.entities.contract.calculator.SuggestedYearlyContract
import org.wcl.mfn.ui.controller.forms.contractcalculator.RequestedRemunerationForm
import org.wcl.mfn.ui.controller.forms.contractcalculator.SalaryEscalatorForm
import java.net.URI
@Controller
@PropertySource("classpath:/url/url.properties")
class ContractCalculatorUIController {
@Autowired
private val pageTitleConfig: PageTitleConfig? = null
@Autowired
private val viewConfig: ViewConfig? = null
@Autowired
private val modelConfig: ModelConfig? = null
@Autowired
private val contractCalculatorConfig: ContractCalculatorConfig? = null
@Autowired
private val contractCalculatorMessagesConfig: ContractCalculatorMessagesConfig? = null
@Autowired
private val apiController: ContractCalculatorAPIController? = null
private var requestedRemuneration = RequestedRemunerationForm(0,0, SalaryEscalatorForm(5))
@GetMapping("/contract-calculator")
fun contractCalculatorPage(model: Model): String {
setModelAttributes(model, generateBlankContracts())
return "pages/tools/contract-calculator"
}
@PostMapping("/contract-calculator/submit")
fun updateSuggestedContracts(@ModelAttribute("requested_remuneration") contractDemands:RequestedRemunerationForm, model:Model): String? {
requestedRemuneration = contractDemands;
setModelAttributes(model, getSuggestedContracts())
return "pages/tools/contract-calculator"
}
@GetMapping("/contract-calculator/reset")
fun resetCalculatorPage(model: Model): String {
setModelAttributes(model, generateBlankContracts())
return "redirect:pages/tools/contract-calculator"
}
private fun setModelAttributes(model: Model, suggestedContracts: List<SuggestedContract>) {
model.addAttribute("page_title", pageTitleConfig!!.contractCalculatorPageTitle())
model.addAttribute("requested_remuneration", requestedRemuneration)
model.addAttribute("suggested_contracts", suggestedContracts)
}
private fun getSuggestedContracts() : List<SuggestedContract> {
val headers = HttpHeaders()
headers.contentType = MediaType.APPLICATION_JSON
headers.accept = listOf(MediaType.APPLICATION_JSON)
val entity: HttpEntity<RequestedRemuneration> = HttpEntity(RequestedRemuneration(
requestedRemuneration.salary,
requestedRemuneration.bonus), headers)
val restTemplate = RestTemplate()
val response: ResponseEntity<List<SuggestedContract>> = restTemplate.exchange(
URI.create("http://localhost:8080/api/contract-calculator"),
HttpMethod.POST,
entity,
typeReference<List<SuggestedContract>>())
return response.body
}
private fun generateBlankContracts(): List<SuggestedContract> {
return listOf(SuggestedContract(
2,0,0,0,
listOf(SuggestedYearlyContract(0,0,0),
SuggestedYearlyContract(0,0,0))
),
SuggestedContract(
3,0,0,0,
listOf(SuggestedYearlyContract(0,0,0),
SuggestedYearlyContract(0,0,0),
SuggestedYearlyContract(0,0,0))
),
SuggestedContract(
4,0,0,0,
listOf(SuggestedYearlyContract(0,0,0),
SuggestedYearlyContract(0,0,0),
SuggestedYearlyContract(0,0,0),
SuggestedYearlyContract(0,0,0))
),
SuggestedContract(
5,0,0,0,
listOf(SuggestedYearlyContract(0,0,0),
SuggestedYearlyContract(0,0,0),
SuggestedYearlyContract(0,0,0),
SuggestedYearlyContract(0,0,0),
SuggestedYearlyContract(0,0,0))
),
SuggestedContract(
6,0,0,0,
listOf(SuggestedYearlyContract(0,0,0),
SuggestedYearlyContract(0,0,0),
SuggestedYearlyContract(0,0,0),
SuggestedYearlyContract(0,0,0),
SuggestedYearlyContract(0,0,0),
SuggestedYearlyContract(0,0,0))
)
)
}
//
// internal data class ContractParameters(val salary: Int, val bonus: Int, val escalator: Int) {
// constructor(salary: Int, bonus: Int) : this(salary, bonus, DEFAULT_ESCALATOR)
//
// companion object {
// private const val DEFAULT_ESCALATOR = 5
// }
// }
// internal data class Escalator(val label: String?, val defaultValue: Int, val max: Int, val step: Int)
private inline fun <reified T> typeReference() = object : ParameterizedTypeReference<T>() {}
}
| 0 | Kotlin | 0 | 0 | dfc6fc7604e502a66e2678aa74bf5ec290c99bd0 | 5,799 | wcl-mfn-manager | Apache License 2.0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.