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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
Data/azure.android.data/src/main/java/com/microsoft/azureandroid/data/util/json/DateTypeAdapter.kt
|
NateRickard
| 108,568,001
| false
| null |
package com.microsoft.azureandroid.data.util.json
import com.google.gson.TypeAdapter
import com.google.gson.stream.JsonReader
import com.google.gson.stream.JsonWriter
import com.microsoft.azureandroid.data.util.RoundtripDateConverter
import java.util.*
/**
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License.
*/
internal class DateTypeAdapter : TypeAdapter<Date>() {
override fun read(`in`: JsonReader?): Date? {
val dateString = `in`?.nextString()
return RoundtripDateConverter.toDate(dateString)
}
override fun write(out: JsonWriter, value: Date?) {
out.value(RoundtripDateConverter.toString(value))
}
}
| 1
|
Kotlin
|
1
| 1
|
4eab6b9b30698081e7f7092e3b5d7e5645fd33f9
| 698
|
Azure.Android
|
MIT License
|
src/main/kotlin/com/basicfu/sip/api/controller/InterfaceController.kt
|
basicfu
| 172,451,351
| false
| null |
package com.basicfu.sip.api.controller
import com.basicfu.sip.api.model.vo.InterfaceVo
import com.basicfu.sip.api.service.InterfaceService
import com.basicfu.sip.core.annotation.Insert
import com.basicfu.sip.core.annotation.Update
import com.basicfu.sip.core.model.Result
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.validation.annotation.Validated
import org.springframework.web.bind.annotation.*
/**
* @author basicfu
* @date 2019/1/11
*/
@RestController
@RequestMapping("/interface")
class InterfaceController {
@Autowired
lateinit var interfaceService: InterfaceService
@GetMapping("/{id}")
fun get(@PathVariable id: Long): Result<Any> {
return Result.success(interfaceService.get(id))
}
@PostMapping("/insert")
fun insert(@Validated(Insert::class) @RequestBody vo: InterfaceVo): Result<Any> {
return Result.success(interfaceService.insert(vo))
}
@PostMapping("/update")
fun update(@Validated(Update::class) @RequestBody vo: InterfaceVo): Result<Any> {
return Result.success(interfaceService.update(vo))
}
@DeleteMapping("/delete")
fun delete(@RequestBody ids: List<Long>): Result<Any> {
return Result.success(interfaceService.delete(ids))
}
@PostMapping("/run/text")
fun runText(@Validated(Insert::class) @RequestBody vo: InterfaceVo): Result<Any> {
return Result.success(interfaceService.run(vo))
}
@PostMapping("/run/form")
fun runForm(@Validated(Insert::class) vo: InterfaceVo): Result<Any> {
return Result.success(interfaceService.run(vo))
}
}
| 0
| null |
0
| 5
|
4ef2a5cb568d1d928be655003f0929e49bdf7209
| 1,636
|
sip-api
|
MIT License
|
app/src/main/java/com/goiz/pokedex/data/pokemon/GenerationIi.kt
|
gsesdras
| 311,452,829
| false
|
{"Gradle": 3, "Java Properties": 2, "Shell": 1, "Text": 1, "Ignore List": 3, "Batchfile": 1, "Markdown": 1, "Proguard": 1, "Kotlin": 193, "XML": 45, "Java": 1, "JSON": 1}
|
package com.goiz.pokedex.data.pokemon
import com.google.gson.annotations.SerializedName
data class GenerationIi(
val crystal: Crystal,
val gold: Gold,
val silver: Silver
)
| 1
| null |
1
| 1
|
3d36c4f787ff76be4d327c19b45608c253ebdca8
| 186
|
afrodev_pokedex
|
MIT License
|
src/org/ice1000/tt/infos.kt
|
dandoh
| 213,273,434
| false
| null |
package org.ice1000.tt
import com.intellij.CommonBundle
import com.intellij.extapi.psi.PsiFileBase
import com.intellij.openapi.fileTypes.FileTypeConsumer
import com.intellij.openapi.fileTypes.FileTypeFactory
import com.intellij.openapi.fileTypes.LanguageFileType
import com.intellij.psi.FileViewProvider
import icons.TTIcons
import org.jetbrains.annotations.NonNls
import org.jetbrains.annotations.PropertyKey
import java.util.*
interface TTFile
object OwOFileType : LanguageFileType(OwOLanguage.INSTANCE) {
override fun getDefaultExtension() = OWO_EXTENSION
override fun getName() = TTBundle.message("owo.name")
override fun getIcon() = TTIcons.OWO_FILE
override fun getDescription() = TTBundle.message("owo.name.description")
}
class OwOFile(viewProvider: FileViewProvider) : PsiFileBase(viewProvider, OwOLanguage.INSTANCE) {
override fun getFileType() = OwOFileType
}
class TTFileTypeFactory : FileTypeFactory() {
override fun createFileTypes(consumer: FileTypeConsumer) {
consumer.consume(MiniTTFileType)
consumer.consume(ACoreFileType)
consumer.consume(OwOFileType)
consumer.consume(AgdaFileType)
consumer.consume(CubicalTTFileType)
consumer.consume(YaccTTFileType)
consumer.consume(VoileFileType)
consumer.consume(MLPolyRFileType)
consumer.consume(MlangFileType)
consumer.consume(NarcFileType)
consumer.consume(RedPrlFileType)
}
}
object TTBundle {
@NonNls private const val BUNDLE = "org.ice1000.tt.tt-bundle"
private val bundle: ResourceBundle by lazy { ResourceBundle.getBundle(BUNDLE) }
@JvmStatic
fun message(@PropertyKey(resourceBundle = BUNDLE) key: String, vararg params: Any) =
CommonBundle.message(bundle, key, *params)
}
| 1
| null |
1
| 1
|
47e013622f1761f4618fa13a391e335af4369b22
| 1,680
|
intellij-dtlc
|
Apache License 2.0
|
src/test/kotlin/g0001_0100/s0082_remove_duplicates_from_sorted_list_ii/SolutionTest.kt
|
javadev
| 190,711,550
| false
|
{"Kotlin": 4870729, "TypeScript": 50437, "Python": 3646, "Shell": 994}
|
package g0001_0100.s0082_remove_duplicates_from_sorted_list_ii
import com_github_leetcode.LinkedListUtils.contructLinkedList
import org.hamcrest.CoreMatchers.equalTo
import org.hamcrest.MatcherAssert.assertThat
import org.junit.jupiter.api.Test
internal class SolutionTest {
@Test
fun deleteDuplicates() {
val head = contructLinkedList(intArrayOf(1, 2, 3, 3, 4, 4, 5))
assertThat(Solution().deleteDuplicates(head).toString(), equalTo("1, 2, 5"))
}
@Test
fun deleteDuplicates2() {
val head = contructLinkedList(intArrayOf(1, 1, 1, 2, 3))
assertThat(Solution().deleteDuplicates(head).toString(), equalTo("2, 3"))
}
}
| 0
|
Kotlin
|
20
| 43
|
e8b08d4a512f037e40e358b078c0a091e691d88f
| 674
|
LeetCode-in-Kotlin
|
MIT License
|
cinescout/movies/data/local/src/commonMain/kotlin/cinescout/movies/data/local/mapper/fieldsMappers.kt
|
4face-studi0
| 280,630,732
| false
| null |
package cinescout.movies.data.local.mapper
import cinescout.database.model.DatabaseTmdbMovieId
import cinescout.movies.domain.model.Rating
import cinescout.movies.domain.model.TmdbMovieId
internal fun DatabaseTmdbMovieId.toId() = TmdbMovieId(value)
internal fun Rating.toDatabaseRating() = value
internal fun TmdbMovieId.toDatabaseId() = DatabaseTmdbMovieId(value)
| 24
|
Kotlin
|
1
| 3
|
dabd9284655ead17314e871530a9664aa6965953
| 367
|
CineScout
|
Apache License 2.0
|
app/src/main/java/com/android/facially/activity/LandmarkActivity.kt
|
xuzaixiang
| 462,157,592
| false
|
{"C++": 657450, "C": 280175, "Kotlin": 48857, "Java": 24152, "GLSL": 4690, "CMake": 1023, "Shell": 381}
|
package com.android.facially.activity
import android.content.Context
import android.content.Intent
import android.opengl.GLES30.*
import android.opengl.GLES31
import android.opengl.Matrix
import com.android.facially.render.OesRender
import com.android.facially.util.calculateMvp
import com.android.facially.opengl.GLProgram
import com.android.facially.opengl.GLShader
import com.android.facially.opengl.GLVao
import com.android.facially.util.readAssert
open class LandmarkActivity : PreviewActivity() {
companion object {
fun launch(context: Context) {
context.startActivity(Intent(context, LandmarkActivity::class.java))
}
}
private val vertex by lazy { GLShader(GL_VERTEX_SHADER, readAssert("landmark.vert")) }
private val fragment by lazy { GLShader(GL_FRAGMENT_SHADER, readAssert("landmark.frag")) }
private val landmarkProgram by lazy { GLProgram(vertex, fragment) }
private val vao by lazy { GLVao(landmarks) }
private var locTexMatrix = 0
private var locMvpMatrix = 0
override fun onSurfaceDestroy() {
vertex.release()
fragment.release()
landmarkProgram.release()
vao.release()
}
override fun onSurfaceCreated() {
super.onSurfaceCreated()
locTexMatrix = landmarkProgram.getUniformLocation("texTransform")
locMvpMatrix = landmarkProgram.getUniformLocation("mvpTransform")
}
private val landmarkMatrix = FloatArray(16)
override fun onDraw(
oes: Int,
rotation: Int,
displayRotation: Int,
width: Int,
height: Int,
surfaceWidth: Int,
surfaceHeight: Int
) {
System.arraycopy(cameraMatrix, 0, landmarkMatrix, 0, 16)
if (oesRender == null)
oesRender = OesRender(this)
oesRender?.onDraw(
oes,
rotation,
displayRotation,
cameraMatrix,
width,
height,
surfaceWidth,
surfaceHeight,
true
)
vao.update(landmarks)
landmarkProgram.use()
glViewport(0, 0, surfaceWidth, surfaceHeight)
// mvp
calculateMvp(rotation, width, height, surfaceWidth, surfaceHeight, cameraMatrix)
glUniformMatrix4fv(locMvpMatrix, 1, false, cameraMatrix, 0)
// tex matrix
when (displayRotation) {
90 -> {
Matrix.translateM(landmarkMatrix, 0, 0f, 1f, 0f)
}
180 -> {
Matrix.translateM(landmarkMatrix, 0, 1f, 1f, 0f)
}
270 -> {
Matrix.translateM(landmarkMatrix, 0, 1f, 0f, 0f)
}
}
Matrix.rotateM(landmarkMatrix, 0, -displayRotation + 0f, 0f, 0f, 1f)
GLES31.glUniformMatrix4fv(locTexMatrix, 1, false, landmarkMatrix, 0)
// Matrix.setIdentityM(cameraMatrix, 0)
// GLES31.glUniformMatrix4fv(locTexMatrix, 1, false, cameraMatrix, 0)
// GLES31.glUniformMatrix4fv(locMvpMatrix, 1, false, cameraMatrix, 0)
vao.bind()
glDrawArrays(GL_POINTS, 0, 106)
vao.unbind()
}
}
| 0
|
C++
|
0
| 0
|
44a1419387a06aec70af2aa1a0bfd7e7a44c8d54
| 3,156
|
glcamera
|
MIT License
|
shared/src/commonMain/kotlin/com/darrenthiores/ecoswap/domain/user/use_cases/GetUser.kt
|
darrenthiores
| 688,372,873
| false
|
{"Kotlin": 770054, "Swift": 362583}
|
package com.darrenthiores.ecoswap.domain.user.use_cases
import com.darrenthiores.ecoswap.domain.user.model.User
import com.darrenthiores.ecoswap.domain.user.repository.UserRepository
import com.darrenthiores.ecoswap.domain.utils.Resource
class GetUser(
private val repository: UserRepository
) {
suspend operator fun invoke(): Resource<User> {
return repository.getUser()
}
}
| 0
|
Kotlin
|
0
| 0
|
6da03175466a0458ba4a28392f7371f8a429d4cf
| 397
|
EcoSwap
|
MIT License
|
core/src/main/kotlin/no/ntnu/ihb/vico/math/Ray.kt
|
NTNU-IHB
| 284,521,287
| false
| null |
package no.ntnu.ihb.vico.math
import org.joml.Matrix4dc
import org.joml.Vector3d
import org.joml.Vector3dc
import kotlin.math.abs
import kotlin.math.max
import kotlin.math.min
import kotlin.math.sqrt
data class Ray @JvmOverloads constructor(
var origin: Vector3d = Vector3d(),
val direction: Vector3d = Vector3d()
) {
private val v = Vector3d()
private var segCenter = Vector3d()
private var segDir = Vector3d()
private var diff = Vector3d()
private var edge1 = Vector3d()
private var edge2 = Vector3d()
private var normal = Vector3d()
fun set(origin: Vector3d, direction: Vector3d): Ray {
this.origin.set(origin)
this.direction.set(direction)
return this
}
fun copy(): Ray {
return Ray().copy(this)
}
fun copy(ray: Ray): Ray {
this.origin.set(ray.origin)
this.direction.set(ray.direction)
return this
}
@JvmOverloads
fun at(t: Double, target: Vector3d = Vector3d()): Vector3d {
return target.set(this.direction).mul(t).add(this.origin)
}
fun lookAt(v: Vector3d): Ray {
this.direction.set(v).sub(this.origin).normalize()
return this
}
fun recast(t: Double): Ray {
this.origin.set(this.at(t, v))
return this
}
@JvmOverloads
fun closestPointToPoint(point: Vector3dc, target: Vector3d = Vector3d()): Vector3d {
point.sub(this.origin, target)
val directionDistance = target.dot(this.direction)
if (directionDistance < 0) {
return target.set(this.origin)
}
return target.set(this.direction).mul(directionDistance).add(this.origin)
}
fun distanceToPoint(point: Vector3d): Double {
return sqrt(this.distanceSqToPoint(point))
}
fun distanceSqToPoint(point: Vector3dc): Double {
val directionDistance = point.sub(this.origin, v).dot(this.direction)
// point behind the ray
if (directionDistance < 0) {
return this.origin.distanceSquared(point)
}
v.set(this.direction).mul(directionDistance).add(this.origin)
return v.distanceSquared(point)
}
fun distanceSqToSegment(
v0: Vector3d,
v1: Vector3d,
optionalPointOnRay: Vector3d? = null,
optionalPointOnSegment: Vector3d? = null
): Double {
// from http://www.geometrictools.com/GTEngine/Include/Mathematics/GteDistRaySegment.h
// It returns the min distance between the ray and the segment
// defined by v0 and v1
// It can also set two optional targets :
// - The closest point on the ray
// - The closest point on the segment
segCenter.set(v0).add(v1).mul(0.5)
segDir.set(v1).sub(v0).normalize()
diff.set(this.origin).sub(segCenter)
val segExtent = v0.distance(v1) * 0.5
val a01 = -this.direction.dot(segDir)
val b0 = diff.dot(this.direction)
val b1 = -diff.dot(segDir)
val c = diff.lengthSquared()
val det = abs(1 - a01 * a01)
var s0: Double
var s1: Double
val sqrDist: Double
if (det > 0) {
// The ray and segment are not parallel.
s0 = a01 * b1 - b0
s1 = a01 * b0 - b1
val extDet = segExtent * det
if (s0 >= 0) {
if (s1 >= -extDet) {
if (s1 <= extDet) {
// region 0
// Minimum at interior points of ray and segment.
val invDet = 1.0 / det
s0 *= invDet
s1 *= invDet
sqrDist = s0 * (s0 + a01 * s1 + 2 * b0) + s1 * (a01 * s0 + s1 + 2 * b1) + c
} else {
// region 1
s1 = segExtent
s0 = max(0.0, -(a01 * s1 + b0))
sqrDist = -s0 * s0 + s1 * (s1 + 2 * b1) + c
}
} else {
// region 5
s1 = -segExtent
s0 = max(0.0, -(a01 * s1 + b0))
sqrDist = -s0 * s0 + s1 * (s1 + 2 * b1) + c
}
} else {
if (s1 <= -extDet) {
// region 4
s0 = max(0.0, -(-a01 * segExtent + b0))
s1 = if (s0 > 0) -segExtent else min(max(-segExtent, -b1), segExtent)
sqrDist = -s0 * s0 + s1 * (s1 + 2 * b1) + c
} else if (s1 <= extDet) {
// region 3
s0 = 0.0
s1 = min(max(-segExtent, -b1), segExtent)
sqrDist = s1 * (s1 + 2 * b1) + c
} else {
// region 2
s0 = max(0.0, -(a01 * segExtent + b0))
s1 = if (s0 > 0) segExtent else min(max(-segExtent, -b1), segExtent)
sqrDist = -s0 * s0 + s1 * (s1 + 2 * b1) + c
}
}
} else {
// Ray and segment are parallel.
s1 = if (a01 > 0) -segExtent else segExtent
s0 = max(0.0, -(a01 * s1 + b0))
sqrDist = -s0 * s0 + s1 * (s1 + 2 * b1) + c
}
optionalPointOnRay?.set(this.direction)?.mul(s0)?.add(this.origin)
optionalPointOnSegment?.set(segDir)?.mul(s1)?.add(segCenter)
return sqrDist
}
fun intersectSphere(sphere: Sphere, target: Vector3d): Vector3d? {
sphere.center.sub(this.origin, v)
val tca = v.dot(this.direction)
val d2 = v.dot(v) - tca * tca
val radius2 = sphere.radius * sphere.radius
if (d2 > radius2) return null
val thc = sqrt(radius2 - d2)
// t0 = first intersect point - entrance on front of sphere
val t0 = tca - thc
// t1 = second intersect point - exit point on back of sphere
val t1 = tca + thc
// test to see if both t0 and t1 are behind the ray - if so, return null
if (t0 < 0 && t1 < 0) return null
// test to see if t0 is behind the ray:
// if it is, the ray is inside the sphere, so return the second exit point scaled by t1,
// in order to always return an intersect point that is in front of the ray.
if (t0 < 0) return this.at(t1, target)
// else t0 is in front of the ray, so return the first collision point scaled by t0
return this.at(t0, target)
}
fun intersectsSphere(sphere: Sphere): Boolean {
return this.distanceSqToPoint(sphere.center) <= (sphere.radius * sphere.radius)
}
fun distanceToPlane(plane: Plane): Double? {
val denominator = plane.normal.dot(this.direction)
if (denominator == 0.0) {
// line is coplanar, return origin
if (plane.distanceToPoint(this.origin) == 0.0) {
return 0.0
}
// Null is preferable to undefined since undefined means.... it is undefined
return null
}
val t = -(this.origin.dot(plane.normal) + plane.constant) / denominator
// Return if the ray never intersects the plane
return if (t >= 0) t else null
}
@JvmOverloads
fun intersectPlane(plane: Plane, target: Vector3d = Vector3d()): Vector3d? {
val t = this.distanceToPlane(plane) ?: return null
return this.at(t, target)
}
fun intersectsPlane(plane: Plane): Boolean {
// check if the ray lies on the plane first
val distToPoint = plane.distanceToPoint(this.origin)
if (distToPoint == 0.0) {
return true
}
val denominator = plane.normal.dot(this.direction)
if (denominator * distToPoint < 0) {
return true
}
// ray origin is behind the plane (and is pointing behind it)
return false
}
fun intersectBox(box: Box3, target: Vector3d): Vector3d? {
var tmin: Double
var tmax: Double
val tymin: Double
val tymax: Double
val tzmin: Double
val tzmax: Double
val invdirx = 1f / this.direction.x
val invdiry = 1f / this.direction.y
val invdirz = 1f / this.direction.z
if (invdirx >= 0) {
tmin = (box.min.x - origin.x) * invdirx
tmax = (box.max.x - origin.x) * invdirx
} else {
tmin = (box.max.x - origin.x) * invdirx
tmax = (box.min.x - origin.x) * invdirx
}
if (invdiry >= 0) {
tymin = (box.min.y - origin.y) * invdiry
tymax = (box.max.y - origin.y) * invdiry
} else {
tymin = (box.max.y - origin.y) * invdiry
tymax = (box.min.y - origin.y) * invdiry
}
if ((tmin > tymax) || (tymin > tmax)) return null
// These lines also handle the case where tmin or tmax is NaN
// (result of 0 * Infinity). x !== x returns true if x is NaN
if (tymin > tmin || tmin != tmin) tmin = tymin
if (tymax < tmax || tmax != tmax) tmax = tymax
if (invdirz >= 0) {
tzmin = (box.min.z - origin.z) * invdirz
tzmax = (box.max.z - origin.z) * invdirz
} else {
tzmin = (box.max.z - origin.z) * invdirz
tzmax = (box.min.z - origin.z) * invdirz
}
if ((tmin > tzmax) || (tzmin > tmax)) return null
if (tzmin > tmin || tmin != tmin) tmin = tzmin
if (tzmax < tmax || tmax != tmax) tmax = tzmax
//return point closest to the ray (positive side)
if (tmax < 0) return null
return this.at(if (tmin >= 0) tmin else tmax, target)
}
fun intersectsBox(box: Box3): Boolean {
return this.intersectBox(box, v) !== null
}
fun intersectTriangle(
a: Vector3d,
b: Vector3d,
c: Vector3d,
backfaceCulling: Boolean,
target: Vector3d
): Vector3d? {
// from http://www.geometrictools.com/GTEngine/Include/Mathematics/GteIntrRay3Triangle3.h
b.sub(a, edge1)
c.sub(a, edge2)
edge1.cross(edge2, normal)
// Solve Q + t*D = b1*E1 + b2*E2 (Q = kDiff, D = ray direction,
// E1 = kEdge1, E2 = kEdge2, N = Cross(E1,E2)) by
// |Dot(D,N)|*b1 = sign(Dot(D,N))*Dot(D,Cross(Q,E2))
// |Dot(D,N)|*b2 = sign(Dot(D,N))*Dot(D,Cross(E1,Q))
// |Dot(D,N)|*t = -sign(Dot(D,N))*Dot(Q,N)
var DdN = this.direction.dot(normal)
val sign: Int
when {
DdN > 0 -> {
if (backfaceCulling) return null
sign = 1
}
DdN < 0 -> {
sign = -1
DdN = -DdN
}
else -> {
return null
}
}
this.origin.sub(a, diff)
val DdQxE2 = sign * this.direction.dot(diff.cross(edge2, edge2))
// b1 < 0, no intersection
if (DdQxE2 < 0) {
return null
}
val DdE1xQ = sign * this.direction.dot(edge1.cross(diff))
// b2 < 0, no intersection
if (DdE1xQ < 0) {
return null
}
// b1+b2 > 1, no intersection
if (DdQxE2 + DdE1xQ > DdN) {
return null
}
// Line intersects triangle, check if ray does.
val QdN = -sign * diff.dot(normal)
// t < 0, no intersection
if (QdN < 0) {
return null
}
// Ray intersects triangle.
return this.at(QdN / DdN, target)
}
fun applyMatrix4(matrix4: Matrix4dc): Ray {
this.origin.mulPosition(matrix4)
this.direction.mulDirection(matrix4)
return this
}
}
| 4
|
Kotlin
|
1
| 8
|
997c708656c274cbcab94cb4375ebfdf46d5e1ad
| 11,899
|
Vico
|
MIT License
|
src/main/kotlin/com/mt/notion/api/user/Bot.kt
|
motui
| 479,945,371
| false
| null |
package com.mt.notion.api.user
import com.mt.notion.common.ObjectType
/**
* bot
*
* @author it.motui
*/
data class Bot(
override val objectType: ObjectType,
override val type: UserType,
override val id: String,
/**
* User's name, as displayed in Notion.
*/
override val name: String? = null,
/**
* Chosen avatar image.
*/
override val avatarUrl: String? = null,
/**
* Properties only present for bot users.
*/
val bot: InternalBot? = null
) : WithUser(objectType, id, type, name, avatarUrl) {
data class InternalBot constructor(
/**
* Information about who owns this bot.
*/
val owner: Owner? = null
)
data class Owner constructor(
/**
* The type of owner - either "workspace" or "user".
*/
val type: String,
/**
* Always true. Only present if owner.type is "workspace".
*/
val workspace: Boolean,
/**
* A user object describing who owns this bot. Currently only "person" users can own bots. See the People
* reference above for more detail. The properties in the user object are based on the bot capabilities.
*/
val user: Person?
)
}
| 0
|
Kotlin
|
0
| 1
|
80b7b256d8d7c34b15cf79d1e5f539c8ef4736b4
| 1,272
|
notion-sdk-kotlin
|
MIT License
|
src/main/java/dev/c0b/jacobsutils/listeners/onCreeperExplodeEvent.kt
|
JacobC1921w
| 810,812,253
| false
|
{"Kotlin": 31307}
|
package dev.c0b.jacobsutils.listeners
import dev.c0b.jacobsutils.JacobsUtils
import org.bukkit.entity.EntityType
import org.bukkit.event.EventHandler
import org.bukkit.event.Listener
import org.bukkit.event.entity.EntityExplodeEvent
class onCreeperExplodeEvent(private val mainInstance: JacobsUtils): Listener {
@EventHandler
fun onCreeperExplode(event: EntityExplodeEvent) {
if(event.entity.type == EntityType.CREEPER) {
if (mainInstance.config.get("creepersDamageBlocks") == false) {
event.blockList().clear()
}
}
}
}
| 0
|
Kotlin
|
0
| 1
|
86c4b2634120335b25ebab09f6610c0693c19e71
| 589
|
JacobsUtils
|
MIT License
|
app/src/main/java/com/tinashe/weather/data/model/TemperatureUnit.kt
|
TinasheMzondiwa
| 126,305,351
| false
| null |
package com.tinashe.weather.data.model
enum class TemperatureUnit(val value: String) {
CELSIUS("celsius"),
FAHRENHEIT("fahrenheit");
companion object {
private val map = values().associateBy(TemperatureUnit::value)
fun fromValue(value: String) = map[value]
}
}
| 0
|
Kotlin
|
2
| 12
|
bdfaea7f00301393494ffda53eb0343dc88d8756
| 298
|
WeatherApp
|
Apache License 2.0
|
src/main/kotlin/de.kevcodez.pubg.model/telemetry/events/BlueZoneCustomOption.kt
|
minchulking91
| 130,461,556
| true
|
{"Kotlin": 26655}
|
package de.kevcodez.pubg.model.telemetry.events
data class BlueZoneCustomOption(
val phaseNum: Int,
val startDelay: Int,
val warningDuration: Int,
val releaseDuration: Int,
val poisonGasDamagePerSecond: Int,
val radiusRate: Int
)
| 0
|
Kotlin
|
0
| 0
|
d886556cd3613aad71923f02692def43b755addb
| 254
|
pubg-api-kotlin
|
MIT License
|
sample/src/main/java/com/example/dics/component/ActivityPermanentComponent.kt
|
sirbralex
| 532,984,642
| false
|
{"Kotlin": 28051}
|
package com.example.dics.component
import com.example.dics.impl.DiComponentFactory
import com.example.dics.impl.DiComponentProvider
class ActivityPermanentComponent : ActivityPermanentDiComponent {
class Factory : DiComponentFactory<ActivityPermanentComponent> {
override fun createComponent(provider: DiComponentProvider): ActivityPermanentComponent {
return ActivityPermanentComponent()
}
}
}
| 0
|
Kotlin
|
0
| 2
|
be6139ae39226908d79be99faa2449a10a7146d1
| 434
|
dics
|
Apache License 2.0
|
domain/src/main/java/com/spiderbiggen/manhwa/domain/usecase/remote/UpdateChaptersFromRemote.kt
|
spiderbiggen
| 624,650,535
| false
|
{"Kotlin": 118713}
|
package com.spiderbiggen.manhwa.domain.usecase.remote
import com.spiderbiggen.manhwa.domain.model.AppError
import com.spiderbiggen.manhwa.domain.model.Either
fun interface UpdateChaptersFromRemote {
suspend operator fun invoke(mangaId: String, skipCache: Boolean): Either<Unit, AppError>
}
| 1
|
Kotlin
|
0
| 0
|
cbd3531735d456a0615f17f7fdf32b1364764c71
| 296
|
manhwa-reader
|
MIT License
|
app/src/main/java/com/layfones/composewanandroid/util/WebViewManager.kt
|
layfones
| 623,881,761
| false
| null |
package com.layfones.composewanandroid.util
import android.annotation.SuppressLint
import android.content.Context
import android.content.MutableContextWrapper
import android.graphics.Color
import android.os.Build
import android.os.Looper
import android.view.ViewGroup
import android.webkit.CookieManager
import android.webkit.WebSettings
import android.webkit.WebView
import androidx.webkit.WebSettingsCompat
import com.layfones.composewanandroid.util.UIModeUtils.isNightMode
@SuppressLint("SetJavaScriptEnabled", "RequiresFeature")
class WebViewManager private constructor() {
companion object {
@Volatile
private var INSTANCE: WebViewManager? = null
private fun instance() = INSTANCE ?: synchronized(this) {
INSTANCE ?: WebViewManager().also { INSTANCE = it }
}
fun prepare(context: Context) {
instance().prepare(context)
}
fun obtain(context: Context): WebView {
return instance().obtain(context)
}
fun recycle(webView: WebView) {
instance().recycle(webView)
}
fun destroy() {
instance().destroy()
}
}
private val webViewCache: MutableList<WebView> = ArrayList(1)
private fun create(context: Context): WebView {
val webView = WebView(context)
webView.setBackgroundColor(Color.TRANSPARENT)
webView.overScrollMode = WebView.OVER_SCROLL_NEVER
val webSetting = webView.settings
webSetting.allowFileAccess = true
webSetting.cacheMode = WebSettings.LOAD_DEFAULT
webSetting.domStorageEnabled = true
webSetting.setGeolocationEnabled(true)
webSetting.javaScriptEnabled = true
webSetting.loadWithOverviewMode = true
webSetting.setSupportZoom(true)
webSetting.displayZoomControls = false
webSetting.useWideViewPort = true
webSetting.mixedContentMode = WebSettings.MIXED_CONTENT_ALWAYS_ALLOW
CookieManager.getInstance().setAcceptThirdPartyCookies(webView, true)
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.TIRAMISU) {
val isAppDarkMode = webView.context.isNightMode()
WebSettingsCompat.setForceDark(
webView.settings,
if (isAppDarkMode) WebSettingsCompat.FORCE_DARK_ON else WebSettingsCompat.FORCE_DARK_OFF
)
}
return webView
}
fun prepare(context: Context) {
if (webViewCache.isEmpty()) {
Looper.myQueue().addIdleHandler {
webViewCache.add(create(MutableContextWrapper(context)))
false
}
}
}
fun obtain(context: Context): WebView {
if (webViewCache.isEmpty()) {
webViewCache.add(create(MutableContextWrapper(context)))
}
val webView = webViewCache.removeFirst()
val contextWrapper = webView.context as MutableContextWrapper
contextWrapper.baseContext = context
webView.clearHistory()
webView.resumeTimers()
return webView
}
fun recycle(webView: WebView) {
try {
webView.stopLoading()
webView.loadDataWithBaseURL("about:blank", "", "text/html", "utf-8", null)
webView.clearHistory()
webView.pauseTimers()
val parent = webView.parent
if (parent != null) {
(parent as ViewGroup).removeView(webView)
}
val contextWrapper = webView.context as MutableContextWrapper
contextWrapper.baseContext = webView.context.applicationContext
} catch (e: Exception) {
e.printStackTrace()
} finally {
if (!webViewCache.contains(webView)) {
webViewCache.add(webView)
}
}
}
fun destroy() {
try {
webViewCache.forEach {
it.removeAllViews()
it.destroy()
webViewCache.remove(it)
}
} catch (e: Exception) {
e.printStackTrace()
}
}
}
| 0
|
Kotlin
|
1
| 3
|
6944e510e0e41f7d5c105a8e308adee417478ac4
| 4,101
|
Jetpack-Compose-Practice
|
Apache License 2.0
|
core/src/main/kotlin/me/kgustave/kson/KSONObject.kt
|
Shengaero
| 108,679,726
| false
| null |
/*
* Copyright 2017 <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.
*/
@file:Suppress("Unused")
package me.kgustave.kson
import kotlin.jvm.JvmField
/**
* @author <NAME>
*/
expect class KSONObject
constructor(map: Map<String, Any?> = HashMap()): MutableMap<String, Any?> {
companion object {
@JvmField val NULL: Null
}
constructor(ksonString: String)
operator fun set(key: String, value: Any?): KSONObject
operator fun plusAssign(pair: Pair<String, Any?>)
operator fun plusAssign(kson: KSONObject)
operator fun plus(pair: Pair<String, Any?>): KSONObject
operator fun plus(kson: KSONObject): KSONObject
fun put(pair: Pair<String, Any?>): KSONObject
fun put(from: Map<String, Any?>): KSONObject
fun putOnce(key: String?, value: Any?): KSONObject
// MutableMap#put and MutableMap#remove overrides
// should force KSONObject to be returned
override fun put(key: String, value: Any?): KSONObject
override fun remove(key: String): KSONObject
// Override the get operator to prevent null
// returns with KSONObject#get
override operator fun get(key: String): Any
fun isNull(key: String): Boolean
inline fun <reified T: Any> opt(key: String): T?
inline fun <reified T> opt(key: String, defaultValue: T): T
infix fun query(pointer: String): Any?
infix fun query(pointer: KSONPointer): Any?
inline infix fun query(pointer: KSONPointer.Builder.() -> Unit): Any?
infix fun String.to(value: Any?): KSONObject
fun toString(indentFactor: Int): String
override fun toString(): String
class Null internal constructor() {
override fun toString(): String
override fun equals(other: Any?): Boolean
override fun hashCode(): Int
}
}
| 0
|
Kotlin
|
0
| 1
|
580c4f1e0121510fe5ede82b123432ec672d23a4
| 2,291
|
KSON
|
Apache License 2.0
|
src/main/kotlin/io/kotest/plugin/intellij/toolwindow/TestFileTree.kt
|
kotest
| 170,580,094
| false
|
{"Kotlin": 290121, "HTML": 454}
|
package io.kotest.plugin.intellij.toolwindow
import com.intellij.ide.util.treeView.NodeRenderer
import com.intellij.openapi.project.Project
import javax.swing.tree.TreeModel
import javax.swing.tree.TreeSelectionModel
class TestFileTree(
project: Project,
) : com.intellij.ui.treeStructure.Tree(),
KotestTestExplorerService.ModelListener {
private val testExplorerTreeSelectionListener = TestExplorerTreeSelectionListener(project)
private val kotestTestExplorerService: KotestTestExplorerService = project.getService(KotestTestExplorerService::class.java)
init {
selectionModel.selectionMode = TreeSelectionModel.SINGLE_TREE_SELECTION
showsRootHandles = true
isRootVisible = false
cellRenderer = NodeRenderer()
// listens to changes in the selections
addTreeSelectionListener(testExplorerTreeSelectionListener)
kotestTestExplorerService.registerModelListener(this)
}
override fun setModel(treeModel: TreeModel) {
val expanded = isExpanded(0)
super.setModel(treeModel)
expandAllNodes()
setModuleGroupNodeExpandedState(expanded)
}
private fun setModuleGroupNodeExpandedState(expanded: Boolean) {
if (expanded) expandRow(0) else collapseRow(0)
}
}
| 33
|
Kotlin
|
24
| 177
|
123d6d9a789832b9ac907b141980e36f835dc6a3
| 1,251
|
kotest-intellij-plugin
|
Apache License 2.0
|
app/src/main/java/com/example/countries/RemoteDataSourceFullName.kt
|
nintenfox
| 627,952,255
| false
| null |
package com.example.countries
import retrofit2.Retrofit
import retrofit2.converter.gson.GsonConverterFactory
import retrofit2.http.GET
import retrofit2.http.Path
interface RestCountriesApiFull {
@GET("name/{name}?fullText=true")
suspend fun getCountryByName(@Path("name") countryName: String): List<Country>
}
var retrofitFull = Retrofit.Builder()
.baseUrl("http://restcountries.com/v3.1/")
.addConverterFactory(GsonConverterFactory.create())
.build()
var restCountriesApiFull = retrofitFull.create(RestCountriesApiFull::class.java)
| 0
|
Kotlin
|
0
| 0
|
7e028cbffd2f42fc1ea073ca81f02ec266284dd9
| 558
|
CountriesApp
|
MIT License
|
src/commonMain/kotlin/com/wizbii/cinematic/journey/presentation/screen/movies/MoviesComponent.kt
|
wizbii
| 762,402,623
| false
|
{"Kotlin": 149036, "Ruby": 465, "Swift": 60}
|
package com.wizbii.cinematic.journey.presentation.screen.movies
import com.wizbii.cinematic.journey.domain.entity.Movie
import com.wizbii.cinematic.journey.domain.entity.MovieId
import com.wizbii.cinematic.journey.domain.entity.Universe
import com.wizbii.cinematic.journey.presentation.component.top.bar.TopBarComponent
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.StateFlow
interface MoviesComponent {
val movies: StateFlow<List<Movie>?>
val topBarComponent: TopBarComponent
val universe: StateFlow<Universe?>
fun onMovieClicked(movieId: MovieId)
fun posterUrl(posterPath: String?, width: Int): Flow<String?>
fun setMovieWatched(movieId: MovieId, watched: Boolean)
}
| 5
|
Kotlin
|
0
| 2
|
cf322bcee0fd9ae6fe745d8d57e1ef429fbb9c24
| 723
|
CinematicJourney
|
Apache License 2.0
|
src/test/kotlin/com/example/mapstructspring/MapstructSpringApplicationTests.kt
|
3LexW
| 528,934,403
| false
| null |
package com.example.mapstructspring
import org.junit.jupiter.api.Test
import org.springframework.boot.test.context.SpringBootTest
@SpringBootTest
class MapstructSpringApplicationTests {
@Test
fun contextLoads() {
}
}
| 0
|
Kotlin
|
0
| 0
|
eac1a31c405d5e03e3a53bb9e712931ac3393a61
| 233
|
mapstruct-spring-kotlin-example
|
Apache License 2.0
|
app/src/main/java/com/lindevhard/android/raspfinder/net/NetManager.kt
|
LinDevHard
| 194,318,200
| false
| null |
package com.lindevhard.android.raspfinder.net
import android.content.Context
import android.net.ConnectivityManager
import android.net.NetworkCapabilities
import android.net.wifi.WifiManager
import android.os.Build
import android.util.Log
class NetManager(applicationContext: Context) {
private var context: Context = applicationContext
fun getContext() = context
fun getWifiManager(): WifiManager =
context.applicationContext.getSystemService(Context.WIFI_SERVICE) as WifiManager
fun isNetworkConnected(): Boolean {
val connectivityManager =
context.applicationContext.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager
return if (Build.VERSION.SDK_INT < 23) {
val networkInfo = connectivityManager.activeNetworkInfo
networkInfo != null && networkInfo.isConnected
} else {
val networkInfo = connectivityManager.activeNetwork
if (networkInfo != null) {
Log.d("NM", "NOT Null")
val networkCapabilities = connectivityManager.getNetworkCapabilities(networkInfo)
networkCapabilities != null && networkCapabilities.hasTransport(NetworkCapabilities.TRANSPORT_WIFI)
} else
false
}
}
}
| 1
|
Kotlin
|
0
| 9
|
de35124cf4a582337b7fcfd1929379d35cf85d8e
| 1,298
|
raspb-finder
|
Apache License 2.0
|
ocpp-2-0-core/src/main/kotlin/com/izivia/ocpp/core20/model/clearvariablemonitoring/ClearVariableMonitoringResp.kt
|
IZIVIA
| 501,708,979
| false
|
{"Kotlin": 1934096}
|
package com.izivia.ocpp.core20.model.clearvariablemonitoring
data class ClearVariableMonitoringResp(
val clearMonitoringResults : List<ClearMonitoringResultType>
)
| 6
|
Kotlin
|
10
| 32
|
bd8e7334ae05ea75d02d96a508269acbe076bcd8
| 168
|
ocpp-toolkit
|
MIT License
|
kotlin-electron/src/jsMain/generated/electron/utility/BeforeSendResponse.kt
|
JetBrains
| 93,250,841
| false
|
{"Kotlin": 12159121, "JavaScript": 330528}
|
// Generated by Karakum - do not modify it manually!
package electron.utility
typealias BeforeSendResponse = electron.core.BeforeSendResponse
| 40
|
Kotlin
|
165
| 1,319
|
a8a1947d73e3ed26426f1e27b641bff427dfd6a0
| 146
|
kotlin-wrappers
|
Apache License 2.0
|
src/main/kotlin/keymanagergrpc/br/com/guilherme/client/dtos/DeletePixKeyRequest.kt
|
Fotkurz
| 397,389,431
| true
|
{"Kotlin": 73675}
|
package keymanagergrpc.br.com.guilherme.client.dtos
import io.micronaut.core.annotation.Introspected
@Introspected
data class DeletePixKeyRequest(
val key: String,
val participant: String
)
| 0
|
Kotlin
|
0
| 0
|
0c470b82b19571bdf3ce7bd357967b4f0e3d551c
| 199
|
orange-talents-06-template-pix-keymanager-grpc
|
Apache License 2.0
|
src/main/kotlin/no/nav/syfo/service/FysiskBrevUtsendingService.kt
|
navikt
| 303,972,532
| false
| null |
package no.nav.syfo.service
import kotlinx.coroutines.runBlocking
import no.nav.syfo.consumer.distribuerjournalpost.JournalpostdistribusjonConsumer
import org.slf4j.LoggerFactory
class FysiskBrevUtsendingService(
val journalpostdistribusjonConsumer: JournalpostdistribusjonConsumer,
) {
private val log = LoggerFactory.getLogger(FysiskBrevUtsendingService::class.qualifiedName)
fun sendBrev(
uuid: String,
journalpostId: String,
) {
runBlocking {
val bestillingsId = journalpostdistribusjonConsumer.distribuerJournalpost(journalpostId, uuid).bestillingsId
log.info("Sendte til print, bestillingsId er $bestillingsId, varsel med UUID: $uuid")
}
}
}
| 1
|
Kotlin
|
3
| 0
|
8490347353778f9e41ec7a3147844da4f56bd1c5
| 727
|
esyfovarsel
|
MIT License
|
app/src/main/java/com/peceoqicka/demo/wheelayoutmanager/DateItemDecoration.kt
|
peceoqicka
| 176,448,211
| false
| null |
package com.peceoqicka.demo.wheelayoutmanager
import android.graphics.Canvas
import android.graphics.Paint
import android.support.v7.widget.RecyclerView
import com.peceoqicka.wheellayoutmanager.WheelLayoutManager
/**
* <pre>
* author : peceoqicka
* time : 2019/3/14
* version : 1.0
* desc :
* </pre>
*/
class DateItemDecoration(
highlightBackgroundColor: Int,
highlightLineWidth: Int,
highlightLineColor: Int,
private val enableHighlightMarker: Boolean = false,
private val highlightMarkerWidth: Int = 0,
highlightMarkerColor: Int = 0,
private val enableHintText: Boolean = false,
private val hintText: String = "",
private val hintTextRightMargin: Int = 0,
hintTextSize: Int = 1,
hintTextColor: Int = 0
) :
RecyclerView.ItemDecoration() {
private val highlightMarkerPaint = Paint()
private val highlightLinePaint = Paint()
private val highlightBgPaint = Paint()
private val hintTextPaint = Paint()
private var hintTextDrawingOffsetY: Int = 0
init {
highlightMarkerPaint.apply {
color = highlightMarkerColor
style = Paint.Style.FILL
}
highlightLinePaint.apply {
color = highlightLineColor
strokeWidth = highlightLineWidth.toFloat()
isAntiAlias = true
}
highlightBgPaint.apply {
color = highlightBackgroundColor
style = Paint.Style.FILL
}
hintTextPaint.apply {
color = hintTextColor
textSize = hintTextSize.toFloat()
isAntiAlias = true
hintTextDrawingOffsetY = -(fontMetricsInt.bottom - fontMetricsInt.top) / 2 - fontMetricsInt.top
}
}
override fun onDraw(c: Canvas, parent: RecyclerView, state: RecyclerView.State) {
val layoutManager = parent.layoutManager as? WheelLayoutManager ?: return
val highlightLineTop = layoutManager.selectionTop + 0f
val highlightLineBottom = highlightLineTop + layoutManager.itemHeight + 0f
val parentWidth = parent.width + 0f
c.drawRect(0f, highlightLineTop, parentWidth, highlightLineBottom, highlightBgPaint)
}
override fun onDrawOver(c: Canvas, parent: RecyclerView, state: RecyclerView.State) {
val layoutManager = parent.layoutManager as? WheelLayoutManager ?: return
val highlightLineTop = layoutManager.selectionTop + 0f
val highlightLineBottom = highlightLineTop + layoutManager.itemHeight + 0f
val parentWidth = parent.width + 0f
val parentHeight = parent.height + 0f
c.drawLine(0f, 0f, parentWidth, 0f, highlightLinePaint)
c.drawLine(0f, highlightLineTop, parentWidth, highlightLineTop, highlightLinePaint)
c.drawLine(0f, highlightLineBottom, parentWidth, highlightLineBottom, highlightLinePaint)
c.drawLine(0f, parentHeight, parentWidth, parentHeight, highlightLinePaint)
if (enableHighlightMarker) {
c.drawRect(
0f, highlightLineTop, highlightMarkerWidth.toFloat(),
highlightLineBottom, highlightMarkerPaint
)
}
if (enableHintText) {
val textY = highlightLineTop + layoutManager.itemHeight / 2 + hintTextDrawingOffsetY
val textX = parent.width - hintTextPaint.measureText(hintText) - hintTextRightMargin
c.drawText(hintText, textX, textY, hintTextPaint)
}
}
}
| 2
|
Kotlin
|
0
| 5
|
a112452f182bdb1bb67ffd837a11c5673656b11f
| 3,475
|
WheelLayoutManager
|
Apache License 2.0
|
src/main/kotlin/no/nav/familie/ks/sak/kjerne/beregning/domene/TilkjentYtelseRepository.kt
|
navikt
| 533,308,075
| false
|
{"Kotlin": 2778706, "Shell": 1039, "Dockerfile": 141}
|
package no.nav.familie.ks.sak.kjerne.beregning.domene
import no.nav.familie.ks.sak.kjerne.behandling.domene.Behandling
import no.nav.familie.ks.sak.kjerne.eøs.differanseberegning.AndelTilkjentYtelsePraktiskLikhet.erIPraksisLik
import no.nav.familie.ks.sak.kjerne.eøs.differanseberegning.AndelTilkjentYtelsePraktiskLikhet.inneholderIPraksis
import org.springframework.data.jpa.repository.JpaRepository
import org.springframework.data.jpa.repository.Modifying
import org.springframework.data.jpa.repository.Query
interface TilkjentYtelseRepository : JpaRepository<TilkjentYtelse, Long> {
@Query("SELECT ty FROM TilkjentYtelse ty JOIN ty.behandling b WHERE b.id = :behandlingId")
fun hentTilkjentYtelseForBehandling(behandlingId: Long): TilkjentYtelse
@Query("SELECT ty FROM TilkjentYtelse ty JOIN ty.behandling b WHERE b.id = :behandlingId")
fun hentOptionalTilkjentYtelseForBehandling(behandlingId: Long): TilkjentYtelse?
@Modifying
@Query("DELETE FROM TilkjentYtelse ty WHERE ty.behandling = :behandling")
fun slettTilkjentYtelseForBehandling(behandling: Behandling)
@Query("SELECT ty FROM TilkjentYtelse ty JOIN ty.behandling b WHERE b.id = :behandlingId AND ty.utbetalingsoppdrag is not null")
fun finnByBehandlingAndHasUtbetalingsoppdrag(behandlingId: Long): TilkjentYtelse?
}
fun TilkjentYtelseRepository.oppdaterTilkjentYtelse(
tilkjentYtelse: TilkjentYtelse,
oppdaterteAndeler: Collection<AndelTilkjentYtelse>,
): TilkjentYtelse {
if (tilkjentYtelse.andelerTilkjentYtelse.erIPraksisLik(oppdaterteAndeler)) {
return tilkjentYtelse
}
// Her er det viktig å beholde de originale andelene, som styres av JPA og har alt av innhold
val skalBeholdes =
tilkjentYtelse.andelerTilkjentYtelse
.filter { oppdaterteAndeler.inneholderIPraksis(it) }
val skalLeggesTil =
oppdaterteAndeler
.filter { !tilkjentYtelse.andelerTilkjentYtelse.inneholderIPraksis(it) }
// Forsikring: Sjekk at det ikke oppstår eller forsvinner andeler når de sjekkes for likhet
if (oppdaterteAndeler.size != (skalBeholdes.size + skalLeggesTil.size)) {
throw IllegalStateException("Avvik mellom antall innsendte andeler og kalkulerte endringer")
}
tilkjentYtelse.andelerTilkjentYtelse.clear()
tilkjentYtelse.andelerTilkjentYtelse.addAll(skalBeholdes + skalLeggesTil)
return this.saveAndFlush(tilkjentYtelse)
}
| 3
|
Kotlin
|
1
| 2
|
f4d9399ceff883c7a14a481407038d41d071b169
| 2,430
|
familie-ks-sak
|
MIT License
|
example/src/main/kotlin/starwars/graphql/droid/DroidMutationResolver.kt
|
pm-dev
| 128,978,530
| false
|
{"Kotlin": 352567, "JavaScript": 52832, "TypeScript": 10121, "HTML": 3834, "Python": 1309, "Shell": 1279, "CSS": 196}
|
@file:Suppress("unused")
package starwars.graphql.droid
import com.coxautodev.graphql.tools.GraphQLMutationResolver
import graphql.schema.DataFetchingEnvironment
import graphql.servlet.ogm.mutate
import org.springframework.stereotype.Component
import starwars.models.Character
import starwars.models.Droid
import starwars.models.Episode
import starwars.models.Name
import java.time.Instant
@Component
internal class DroidMutationResolver : GraphQLMutationResolver {
fun createDroid(
name: String,
primaryFunction: String,
friendIds: Set<Long>,
appearsIn: Set<Episode>,
env: DataFetchingEnvironment
): Droid = env.mutate {
val friends = V<Character>(ids = friendIds)
val droid = saveV(vertex = Droid(
name = Name.parse(raw = name),
appearsIn = appearsIn,
createdAt = Instant.now(),
primaryFunction = primaryFunction))
saveE(edges = Character.friends from droid to friends)
droid
}
}
| 1
|
Kotlin
|
6
| 31
|
8197847f310bd9928ff1eccb7733b59830e3c12e
| 1,054
|
kotlin-gremlin-ogm
|
Apache License 2.0
|
android/app/src/main/java/work/shion/xapprecipe/templates/link_insert_dialog/LinkInsertDialogViewModel.kt
|
tshion
| 261,409,412
| false
| null |
package work.shion.xapprecipe.templates.link_insert_dialog
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
class LinkInsertDialogViewModel : ViewModel() {
val input = MutableLiveData<String?>()
}
| 4
|
Kotlin
|
0
| 0
|
1bd854f0621a0a102c07b7a85f5718cc0c01f5b8
| 233
|
XAppRecipe
|
MIT License
|
app/src/test/kotlin/com/iliasg/startrekfleetcommand/stfcpadd/sync/data/repository/FakeApiRepositoryImpl.kt
|
Iliasgx
| 455,331,101
| false
|
{"Kotlin": 145697}
|
package com.iliasg.startrekfleetcommand.stfcpadd.sync.data.repository
import com.iliasg.startrekfleetcommand.stfcpadd.sync.data.datasources.remote.dto.CompareDto
import com.iliasg.startrekfleetcommand.stfcpadd.sync.data.datasources.remote.dto.ReleaseDto
import com.iliasg.startrekfleetcommand.stfcpadd.sync.data.datasources.remote.dto.TagDto
import com.iliasg.startrekfleetcommand.stfcpadd.sync.domain.models.Tag
import com.iliasg.startrekfleetcommand.stfcpadd.sync.domain.repository.ApiRepository
import com.squareup.moshi.Moshi
import com.squareup.moshi.adapter
import kotlinx.coroutines.runBlocking
import okhttp3.ResponseBody
import java.io.File
@Suppress("BlockingMethodInNonBlockingContext")
@ExperimentalStdlibApi
class FakeApiRepositoryImpl : ApiRepository {
private val moshi = Moshi.Builder().build()
override suspend fun getLatestTag(): Result<Tag> = runBlocking {
val adapter = moshi.adapter<List<TagDto>>()
val response = File("src/debug/assets/response_tags.json").inputStream().use { stream ->
stream.readBytes().decodeToString()
}
val tag = adapter.fromJson(response)!!.first()
return@runBlocking Result.success(
Tag(
version = tag.name,
lastSha = tag.commit.sha
)
)
}
override suspend fun getLatestReleaseAssets(): Result<List<ReleaseDto.ReleaseAsset>> {
return runBlocking {
val adapter = moshi.adapter<ReleaseDto>()
val response = File("src/debug/assets/response_release.json")
.inputStream()
.use { stream ->
stream.readBytes().decodeToString()
}
val release = adapter.fromJson(response)!!
return@runBlocking Result.success(release.assets)
}
}
override suspend fun getUpdates(
savedSha: String,
latestSha: String
): Result<List<CompareDto.FileMetaDto>> = runBlocking {
val adapter = moshi.adapter<CompareDto>()
val response = File("src/debug/assets/response_compare.json")
.inputStream()
.use { stream ->
stream.readBytes().decodeToString()
}
val compare = adapter.fromJson(response)!!
return@runBlocking Result.success(compare.files)
}
override suspend fun downloadLatestDbVersion(version: String): Result<ResponseBody> {
TODO("Not yet implemented")
}
override suspend fun downloadAsset(url: String): Result<ResponseBody> {
TODO("Not yet implemented")
}
}
| 0
|
Kotlin
|
0
| 1
|
277c4936facbddcffb354f2af6e273b44bb37dea
| 2,605
|
STFC-Padd-template
|
Apache License 2.0
|
core/src/main/java/com/dvttest/hiweather/core/extensions/NavigationExtensions.kt
|
zakayothuku
| 461,908,095
| false
| null |
/*
* Copyright (C) 2022. dvt.co.za
*
* 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.dvttest.hiweather.core.extensions
import androidx.fragment.app.Fragment
import androidx.navigation.fragment.findNavController
fun <T> Fragment.setNavigationResult(key: String, value: T) {
findNavController().previousBackStackEntry?.savedStateHandle?.set(key, value)
}
fun <T> Fragment.getNavigationResult(key: String, initialValue: T, onResult: (result: T) -> Unit) {
findNavController()
.currentBackStackEntry
?.savedStateHandle
?.getLiveData(key, initialValue)
?.observe(viewLifecycleOwner) { it.let(onResult) }
}
| 0
|
Kotlin
|
0
| 2
|
b52f8a2a1953548625f158c7b9523387313fb35e
| 1,169
|
dvt-hiweather
|
Apache License 2.0
|
src/main/kotlin/com/pushpyshev/model/entity/tables/Counters.kt
|
Mikuro
| 840,857,804
| false
|
{"Kotlin": 22781, "Dockerfile": 460}
|
package com.pushpyshev.model.entity.tables
import org.jetbrains.exposed.dao.id.IntIdTable
object Counters : IntIdTable("counters") {
val name = varchar("name", 255)
val value = integer("value")
}
| 0
|
Kotlin
|
0
| 0
|
1ff88f155fcea32c7ddd5bf3de0f36246147d7ab
| 205
|
test-crud-app
|
MIT License
|
e2im2/src/main/kotlin/org/duangsuse/AsciiInput.kt
|
duangsuse-valid-projects
| 229,555,986
| false
|
{"C++": 6115, "Kotlin": 5412, "Makefile": 463}
|
package org.duangsuse
import java.io.InputStream
/** Unsafe ([InputStream.read] `-1` return value is discard) ASCII(8-bit) input */
class AsciiInput(private val inner: InputStream): CharIterator() {
override fun hasNext(): Boolean = inner.available() != 0
override fun nextChar(): Char = inner.read().toChar()
}
| 0
|
C++
|
0
| 0
|
c8c5c8b4372095b5775d8e731cc37dbaf510d1b1
| 318
|
e2im-2
|
Apache License 2.0
|
src/main/kotlin/Day07.kt
|
joostbaas
| 573,096,671
| false
| null |
sealed interface FileSystem {
val name: String
val size: Int
get() = when (this) {
is Directory -> children.sumOf { it.size }
is File -> fileSize
}
}
data class File(
override val name: String,
val fileSize: Int,
) : FileSystem
data class Directory(
override val name: String,
val children: MutableList<FileSystem>,
) : FileSystem
fun Directory.allDirectories(): List<Directory> =
this.children.filterIsInstance<Directory>().flatMap { it.allDirectories() } + this
fun List<String>.parseFilesystem(): Directory {
val rootDirectory = Directory("/", mutableListOf())
val currentDirectory = ArrayDeque<Directory>().apply { add(rootDirectory) }
val dirRegex = Regex("""dir ([a-z.]+)""")
val fileRegex = Regex("""([0-9]+) ([a-z.]+)""")
val cdRegex = Regex("""\$ cd ([a-z]+)""")
for (line in this.drop(1)) {
with(line) {
when {
matches(dirRegex) -> dirRegex.find(this)!!.destructured
.let { (name) ->
currentDirectory.last().children.add(Directory(name, mutableListOf()))
}
matches(fileRegex) -> fileRegex.find(this)!!.destructured
.let { (size, name) ->
currentDirectory.last().children.add(File(name, size.toInt()))
}
equals("$ cd ..") -> currentDirectory.removeLast()
matches(cdRegex) -> cdRegex.find(this)!!.destructured
.let { (name) ->
currentDirectory.addLast(
currentDirectory.last().children
.filterIsInstance<Directory>()
.first { it.name == name })
}
else -> { /*doNothing*/
}
}
}
}
return rootDirectory
}
fun day07Part1(input: List<String>): Int =
input.parseFilesystem().allDirectories()
.filter { it.size < 100_000 }
.sumOf { it.size }
fun day07Part2(input: List<String>): Int {
val root = input.parseFilesystem()
val diskSize = 70_000_000
val spaceNeeded = 30_000_000
val spaceAvailable = diskSize - root.size
val extraSpaceNeeded = spaceNeeded - spaceAvailable
return root.allDirectories().filter { it.size >= extraSpaceNeeded }.minOf { it.size }
}
| 0
|
Kotlin
|
0
| 0
|
b4ffaf1e48f5baf3449c69de1076cc5e4f205d75
| 2,439
|
advent-of-code-2022
|
Apache License 2.0
|
src/main/kotlin/gaydar/struct/CMD/DroppedItemInteractionComponentCMD.kt
|
q129303
| 131,508,880
| false
| null |
package gaydar.struct.CMD
import com.badlogic.gdx.math.Vector2
import gaydar.deserializer.channel.ActorChannel.Companion.droppedItemCompToItem
import gaydar.deserializer.channel.ActorChannel.Companion.droppedItemLocation
import gaydar.struct.Actor
import gaydar.struct.Bunch
import gaydar.struct.NetGuidCacheObject
import gaydar.util.debugln
object DroppedItemInteractionComponentCMD
{
fun process(actor : Actor, bunch : Bunch, repObj : NetGuidCacheObject?, waitingHandle : Int, data : HashMap<String, Any?>) : Boolean
{
//try
//{
with(bunch) {
when (waitingHandle)
{
//UActorComponent
1 -> readBit() //bIsActive
2 -> readBit() //bReplicates
//USceneComponent
3 ->
{//TArray<class USceneComponent*> AttachChildren
readUInt16()
var index = readIntPacked()
while (index != 0)
{
readObject()
index = readIntPacked()
}
}
4 -> readObject() //AttachParent
5 -> readName() //AttachSocketName
6 -> readBit() //bAbsoluteLocation
7 -> readBit() //bAbsoluteRotation
8 -> readBit() //bAbsoluteScale
9 -> readBit() //bReplicatesAttachment
10 -> readBit() //bReplicatesAttachmentReference
11 -> readBit() //bVisible
12 ->
{
val relativeLocation = propertyVector()
data["relativeLocation"] = Vector2(relativeLocation.x, relativeLocation.y)
}
13 ->
{
val relativeRotation = readRotationShort()
data["relativeRotation"] = relativeRotation.y
}
14 ->
{
val relativeScale3D = propertyVector()
val a = relativeScale3D
}
//DroppedItemInteractionComponent
15 ->
{
val (itemGUID, _) = readObject()
val (loc, _) = droppedItemLocation[itemGUID] ?: return true
droppedItemCompToItem[repObj!!.outerGUID] = itemGUID
val relativeLocation = data["relativeLocation"] as Vector2
val relativeRotation = data["relativeRotation"] as Float
loc.add(relativeLocation.x, relativeLocation.y, relativeRotation)
}
else -> return false
}
}
return true
//}
//catch (e : Exception)
//{
// debugln { ("DroppedItemInteractionComp is throwing somewhere: $e ${e.stackTrace} ${e.message} ${e.cause}") }
//}
//return false
}
}
| 1
|
Kotlin
|
4
| 3
|
46a956b353933e7ea6b582a06e755e5d863eb6cd
| 2,618
|
PUBG-Radar
|
The Unlicense
|
app/src/main/java/com/example/taskplanner/data/model/entity/Reminder.kt
|
kikichechka
| 781,460,462
| false
|
{"Kotlin": 101495}
|
package com.example.taskplanner.data.model.entity
import androidx.room.ColumnInfo
import androidx.room.Entity
import androidx.room.PrimaryKey
import java.time.LocalDate
import java.time.LocalTime
@Entity(tableName = "reminder")
class Reminder(
@PrimaryKey(autoGenerate = true) override var id: Int? = null,
@ColumnInfo(name = "date") override var date: LocalDate,
@ColumnInfo(name = "title") override var title: String,
@ColumnInfo(name = "finished") override var finished: Boolean = false,
@ColumnInfo(name = "time") var time: LocalTime
) : TypeTask(id, date, title, finished)
| 0
|
Kotlin
|
0
| 0
|
c55fa823a3234d238eda2e15e75c26b1b5d1547e
| 600
|
Task-Planner
|
Apache License 2.0
|
inference/inference-webgpu/src/commonMain/kotlin/io/kinference/webgpu/operators/WebGPUOperatorFactory.kt
|
isomethane
| 591,976,225
| false
| null |
package io.kinference.webgpu.operators
import io.kinference.attribute.Attribute
import io.kinference.attribute.AttributeFactory
import io.kinference.graph.Graph
import io.kinference.operator.*
import io.kinference.protobuf.message.GraphProto
import io.kinference.protobuf.message.TensorProto
import io.kinference.webgpu.WebGPUData
import io.kinference.webgpu.data.tensor.WebGPUTensor
import io.kinference.webgpu.graph.WebGPUGraph
import io.kinference.webgpu.operators.activations.*
import io.kinference.webgpu.operators.flow.*
import io.kinference.webgpu.operators.logical.*
import io.kinference.webgpu.operators.math.*
import io.kinference.webgpu.operators.tensor.*
object WebGPUAttributeFactory : AttributeFactory<WebGPUData<*>> {
override fun createTensor(proto: TensorProto): WebGPUData<*> = WebGPUTensor.create(proto)
override suspend fun createGraph(proto: GraphProto, opSet: OperatorSetRegistry): Graph<WebGPUData<*>> = WebGPUGraph(proto, opSet)
}
object WebGPUOperatorFactory : OperatorFactory<WebGPUData<*>> {
override fun attributeFactory() = WebGPUAttributeFactory
@Suppress("UNCHECKED_CAST")
override fun create(
name: String,
opType: String?,
version: Int?,
attributes: Map<String, Attribute<Any>>,
inputs: List<String>,
outputs: List<String>
): Operator<WebGPUData<*>, WebGPUData<*>> = when (opType) {
"Add" -> Add(name, version, attributes, inputs, outputs)
"Cast" -> Cast(name, version, attributes, inputs, outputs)
"Concat" -> Concat(name, version, attributes, inputs, outputs)
"Constant" -> Constant(name, version, attributes, inputs, outputs)
"ConstantOfShape" -> ConstantOfShape(name, version, attributes, inputs, outputs)
"CumSum" -> CumSum(name, version, attributes, inputs, outputs)
"Div" -> Div(name, version, attributes, inputs, outputs)
"Equal" -> Equal(name, version, attributes, inputs, outputs)
"Erf" -> Erf(name, version, attributes, inputs, outputs)
"Flatten" -> Flatten(name, version, attributes, inputs, outputs)
"Gather" -> Gather(name, version, attributes, inputs, outputs)
"Gemm" -> Gemm(name, version, attributes, inputs, outputs)
"Greater" -> Greater(name, version, attributes, inputs, outputs)
"Identity" -> Identity(name, version, attributes, inputs, outputs)
"LeakyRelu" -> LeakyRelu(name, version, attributes, inputs, outputs)
"Less" -> Less(name, version, attributes, inputs, outputs)
"Log" -> Log(name, version, attributes, inputs, outputs)
"MatMul" -> MatMul(name, version, attributes, inputs, outputs)
"Mul" -> Mul(name, version, attributes, inputs, outputs)
"NonZero" -> NonZero(name, version, attributes, inputs, outputs)
"Not" -> Not(name, version, attributes, inputs, outputs)
"Or" -> Or(name, version, attributes, inputs, outputs)
"Pow" -> Pow(name, version, attributes, inputs, outputs)
"ReduceMean" -> ReduceMean(name, version, attributes, inputs, outputs)
"ReduceSum" -> ReduceSum(name, version, attributes, inputs, outputs)
"Relu" -> Relu(name, version, attributes, inputs, outputs)
"Reshape" -> Reshape(name, version, attributes, inputs, outputs)
"Shape" -> Shape(name, version, attributes, inputs, outputs)
"Sigmoid" -> Sigmoid(name, version, attributes, inputs, outputs)
"Slice" -> Slice(name, version, attributes, inputs, outputs)
"Softmax" -> Softmax(name, version, attributes, inputs, outputs)
"Split" -> Split(name, version, attributes, inputs, outputs)
"Sqrt" -> Sqrt(name, version, attributes, inputs, outputs)
"Squeeze" -> Squeeze(name, version, attributes, inputs, outputs)
"Sub" -> Sub(name, version, attributes, inputs, outputs)
"Tanh" -> Tanh(name, version, attributes, inputs, outputs)
"Transpose" -> Transpose(name, version, attributes, inputs, outputs)
"Unsqueeze" -> Unsqueeze(name, version, attributes, inputs, outputs)
"Where" -> Where(name, version, attributes, inputs, outputs)
else -> error("Unsupported operator: $opType")
} as Operator<WebGPUData<*>, WebGPUData<*>>
}
| 0
|
Kotlin
|
0
| 0
|
3056bc4ebcd03a86d0ee9ef093cdac81491325b2
| 4,249
|
kinference
|
Apache License 2.0
|
app/src/main/java/com/chandistudios/taskrapid/data/room/TaskDao.kt
|
chubozeko
| 491,210,477
| false
| null |
package com.chandistudios.taskrapid.data.room
import androidx.room.*
import com.chandistudios.taskrapid.data.entity.Task
import kotlinx.coroutines.flow.Flow
@Dao
abstract class TaskDao {
// get task with taskId
@Query(value = "SELECT * FROM tasks WHERE task_id = :taskId")
abstract fun getTaskWithId(taskId: Long): Flow<Task>
// get task with taskName
@Query(value = "SELECT * FROM tasks WHERE task_name = :name")
abstract suspend fun getTaskWithName(name: String): Task?
// get all tasks
@Query(value = "SELECT * FROM tasks LIMIT 15")
abstract fun tasks(): Flow<List<Task>>
// get all incomplete tasks
@Query(value = "SELECT * FROM tasks WHERE task_completed = 0")
abstract fun getIncompleteTasks(): Flow<List<Task>>
// get all tasks
@Query(value = "SELECT * FROM tasks LIMIT 15")
abstract fun getAllTasks(): Flow<List<TaskWithType>>
// get all tasks with taskType
@Query("""
SELECT tasks.*
FROM tasks INNER JOIN task_types ON tasks.task_type_id = task_types.id
WHERE task_type_id = :taskTypeId
""")
abstract fun getTasksWithType(taskTypeId: Long): Flow<List<TaskWithType>>
// suspend fun => to make it async
@Insert(onConflict = OnConflictStrategy.REPLACE)
abstract suspend fun insert(entity: Task): Long
@Insert(onConflict = OnConflictStrategy.REPLACE)
abstract suspend fun insertAll(entities: Collection<Task>)
@Update(onConflict = OnConflictStrategy.REPLACE)
abstract suspend fun update(entity: Task)
@Delete
abstract suspend fun delete(entity: Task) // : Long
}
| 0
|
Kotlin
|
0
| 0
|
a38870dd3d2b4dc5f8aeac99d7a40e72e69d669e
| 1,616
|
TaskRapid
|
MIT License
|
main/src/main/java/com/pyamsoft/tetherfi/main/ThemeViewModeler.kt
|
pyamsoft
| 475,225,784
| false
| null |
package com.pyamsoft.tetherfi.main
import android.app.Activity
import androidx.compose.runtime.saveable.SaveableStateRegistry
import com.pyamsoft.pydroid.arch.AbstractViewModeler
import com.pyamsoft.pydroid.ui.theme.Theming
import javax.inject.Inject
class ThemeViewModeler
@Inject
internal constructor(
override val state: MutableThemeViewState,
private val theming: Theming,
) : AbstractViewModeler<ThemeViewState>(state) {
override fun registerSaveState(
registry: SaveableStateRegistry
): List<SaveableStateRegistry.Entry> =
mutableListOf<SaveableStateRegistry.Entry>().apply {
val s = state
registry.registerProvider(KEY_THEME) { s.theme.value.name }.also { add(it) }
}
override fun consumeRestoredState(registry: SaveableStateRegistry) {
val s = state
registry
.consumeRestored(KEY_THEME)
?.let { it as String }
?.let { Theming.Mode.valueOf(it) }
?.also { s.theme.value = it }
}
fun handleSyncDarkTheme(activity: Activity) {
val isDark = theming.isDarkTheme(activity)
state.theme.value = if (isDark) Theming.Mode.DARK else Theming.Mode.LIGHT
}
companion object {
private const val KEY_THEME = "theme"
}
}
| 4
|
Kotlin
|
2
| 52
|
75adef3c88e8957b874c0e58f2bdec5d5ef3151c
| 1,229
|
tetherfi
|
Apache License 2.0
|
app/src/main/java/theshoestore/ca/ui/fragment/DetailFragment.kt
|
gilsonjuniorpro
| 306,688,846
| false
| null |
package theshoestore.ca.ui.fragment
import android.Manifest
import android.app.AlertDialog
import android.content.Intent
import android.content.pm.PackageManager
import android.net.Uri
import android.os.Bundle
import android.os.Environment
import android.os.Handler
import android.provider.MediaStore
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Toast
import androidx.activity.result.contract.ActivityResultContracts
import androidx.appcompat.app.AppCompatActivity
import androidx.core.content.ContextCompat
import androidx.core.content.FileProvider
import androidx.core.content.res.ResourcesCompat
import androidx.fragment.app.Fragment
import androidx.lifecycle.ViewModelProvider
import androidx.navigation.Navigation.findNavController
import com.bumptech.glide.Glide
import com.bumptech.glide.load.engine.DiskCacheStrategy
import com.jarvis.ca.Mark
import theshoestore.ca.R
import theshoestore.ca.databinding.FragmentDetailBinding
import theshoestore.ca.model.Shoes
import theshoestore.ca.repository.ShoesRepository
import theshoestore.ca.util.Util
import theshoestore.ca.viewmodel.DetailViewModel
import theshoestore.ca.viewmodel.DetailViewModelFactory
import java.io.File
import java.util.*
import kotlin.random.Random
class DetailFragment : Fragment() {
private val TAG = DetailFragment::class.java.simpleName
private lateinit var binding: FragmentDetailBinding
private lateinit var detailViewModel: DetailViewModel
private lateinit var detailViewModelFactory: DetailViewModelFactory
private lateinit var messageSuccess: String
private var isInEditionMode = false
private var imagePath: String? = ""
private lateinit var shoesOriginal: DetailFragmentArgs
private lateinit var uri: Uri
private var keepOriginal = true
private val takePicture =
registerForActivityResult(ActivityResultContracts.TakePicture()) { isSaved ->
if (isSaved) {
imagePath = uri.toString()
Glide
.with(requireActivity())
.load(uri)
.placeholder(R.drawable.shoes_sample)
.diskCacheStrategy(DiskCacheStrategy.ALL)
.into(binding.ivPicture)
}
}
private val askMultiplePermissions =
registerForActivityResult(ActivityResultContracts.RequestMultiplePermissions()) { map ->
for (entry in map.entries) {
Toast.makeText(
requireActivity(),
"${entry.key} = ${entry.value}",
Toast.LENGTH_SHORT
).show()
}
}
private val pickImages =
registerForActivityResult(ActivityResultContracts.GetContent()) { uri ->
/*uri?.let {
imagePath = uri.toString()
val bitmap = Util.getBitmap(it)
binding.ivPicture.setImageBitmap(bitmap)
}*/
imagePath = uri.toString()
Glide
.with(requireActivity())
.load(uri)
.placeholder(R.drawable.shoes_sample)
.diskCacheStrategy(DiskCacheStrategy.ALL)
.into(binding.ivPicture)
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
val bar = (activity as AppCompatActivity).supportActionBar
bar?.hide()
}
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
binding = FragmentDetailBinding.inflate(inflater, container, false)
detailViewModelFactory = DetailViewModelFactory(ShoesRepository(requireContext()))
detailViewModel = ViewModelProvider(this, detailViewModelFactory)
.get(DetailViewModel::class.java)
binding.detailViewModel = detailViewModel
binding.lifecycleOwner = this
return binding.root
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
shoesOriginal = DetailFragmentArgs.fromBundle(requireArguments())
shoesOriginal.shoe?.let { detailViewModel.setShoes(it) }
if (shoesOriginal.shoe != null) {
//detailViewModel.setShoes(shoesOriginal.shoe as Shoes)
imagePath = detailViewModel.pictureUri
Util.loadImage(shoesOriginal.shoe!!, requireContext(), binding.ivPicture)
detailViewModel.setActionUpdate()
} else {
detailViewModel.setActionCreate()
}
detailViewModel.isEditing.observe(viewLifecycleOwner, { isEditing ->
if (isEditing) {
changeIconSaveOrEdit()
changeVisibility()
}
})
detailViewModel.action.observe(viewLifecycleOwner, { isCreating ->
if (isCreating == DetailViewModel.Action.CREATE) {
isInEditionMode = true
detailViewModel.setInsertingEnabled()
changeIconShoesToSample()
changeVisibility()
setMessageSuccess(
getString(R.string.msg_shoes_added_success)
)
} else {
setMessageSuccess(
getString(R.string.msg_shoes_updated_success)
)
}
})
detailViewModel.isInserting.observe(viewLifecycleOwner, { isInserting ->
changeIconSaveOrEdit()
changeVisibility()
})
binding.btRegister.setOnClickListener {
saveShoes()
}
binding.ivAddPicture.setOnClickListener {
if ((ContextCompat.checkSelfPermission(
requireContext(),
Manifest.permission.CAMERA
) == PackageManager.PERMISSION_GRANTED) &&
(ContextCompat.checkSelfPermission(
requireContext(),
Manifest.permission.READ_EXTERNAL_STORAGE
) == PackageManager.PERMISSION_GRANTED)
) {
showPictureDialog()
} else {
makeRequest()
}
}
binding.ivSave.setOnClickListener {
if (isInEditionMode) {
saveShoes()
} else {
isInEditionMode = true
detailViewModel.setEditEnabled()
}
}
binding.ivBack.setOnClickListener {
Util.cancelInsertOrEdition(requireContext(), findNavController(requireView()))
}
}
private fun showPictureDialog() {
val items = arrayOf(getString(R.string.select_photo_from_gallery), getString(R.string.capture_photo_from_camera))
val pictureDialog = AlertDialog.Builder(requireContext())
pictureDialog.setTitle(getString(R.string.select_action))
pictureDialog.setItems(items) { _, which ->
if (which == 0) {
choosePhotoFromGallery()
} else {
takePhotoFromCamera()
}
}
val dialog = pictureDialog.create()
dialog.show()
}
private fun choosePhotoFromGallery() {
keepOriginal = false
pickImages.launch("image/*")
}
private fun takePhotoFromCamera() {
val photoFile = File.createTempFile(
"shoes_app_${Calendar.getInstance().timeInMillis}",
".jpg",
requireContext().getExternalFilesDir(Environment.DIRECTORY_PICTURES)
)
uri = FileProvider.getUriForFile(
requireContext(),
"${requireContext().packageName}.provider",
photoFile
)
keepOriginal = false
takePicture.launch(uri)
}
private fun makeRequest() {
askMultiplePermissions.launch(
arrayOf(
Manifest.permission.CAMERA,
Manifest.permission.READ_EXTERNAL_STORAGE
)
)
}
private fun setMessageSuccess(message: String) {
this.messageSuccess = message
}
private fun changeIconSaveOrEdit() {
binding.ivSave.setImageDrawable(
ResourcesCompat.getDrawable(resources, R.drawable.ic_done, null)
)
}
private fun changeIconShoesToSample() {
binding.ivPicture.setImageDrawable(
ResourcesCompat.getDrawable(resources, R.drawable.shoes_sample, null)
)
}
private fun changeVisibility() {
binding.ivAddPicture.visibility = View.VISIBLE
binding.viewAdd.visibility = View.VISIBLE
}
private fun validateFields(): Boolean {
if(!keepOriginal){
if(imagePath.isNullOrEmpty()){
Mark.showAlertError(requireActivity(), getString(R.string.msg_fill_image))
return false
}
if(imagePath.isNullOrBlank()) {
Mark.showAlertError(requireActivity(), getString(R.string.msg_fill_image))
return false
}
}
return when {
binding.tietPrice.text.isNullOrEmpty() -> {
Mark.showAlertError(requireActivity(), getString(R.string.msg_fill_price))
binding.tietPrice.requestFocus()
false
}
binding.tietName.text.isNullOrEmpty() -> {
Mark.showAlertError(requireActivity(), getString(R.string.msg_fill_name))
binding.tietName.requestFocus()
false
}
binding.tietDescription.text.isNullOrEmpty() -> {
Mark.showAlertError(requireActivity(), getString(R.string.msg_fill_description))
binding.tietDescription.requestFocus()
false
}
else -> {
true
}
}
}
private fun saveShoes() {
if (validateFields()) {
isInEditionMode = false
val shoesName: String? =
if (binding.tietName.text.isNullOrBlank()) shoesOriginal.shoe?.title
else binding.tietName.text.toString()
val shoesPrice: String? =
if (binding.tietPrice.text.isNullOrBlank()) shoesOriginal.shoe?.price
else binding.tietPrice.text.toString()
val shoesDescription: String? =
if (binding.tietDescription.text.isNullOrBlank()) shoesOriginal.shoe?.description
else binding.tietDescription.text.toString()
val picture = shoesOriginal.shoe?.picture ?: ""
detailViewModel.saveShoes(shoesName, shoesPrice, shoesDescription, picture, imagePath)
navigateToList()
}
}
private fun navigateToList() {
Mark.showAlertSuccess(requireActivity(), getMessageSuccess())
Handler().postDelayed({
binding.progressBar.visibility = View.GONE
findNavController(requireView()).navigate(
DetailFragmentDirections.actionDetailFragmentToListFragment()
)
}, 2000L)
}
private fun getMessageSuccess(): String {
return this.messageSuccess
}
}
| 0
|
Kotlin
|
0
| 0
|
407bde484b8472f0221b51e33541149c51909e6d
| 11,259
|
TheShoeStore
|
Apache License 2.0
|
telegram-bot/src/main/kotlin/eu/vendeli/tgbot/types/internal/ActivityCtx.kt
|
vendelieu
| 496,567,172
| false
|
{"Kotlin": 520294, "CSS": 356}
|
package eu.vendeli.tgbot.types.internal
@JvmInline
value class ActivityCtx<out T : ProcessedUpdate>(val update: T)
| 5
|
Kotlin
|
6
| 116
|
744bbcf1fe96fcb52c50ddf11cf2dd9a3f98c4b5
| 116
|
telegram-bot
|
Apache License 2.0
|
tabulate-core/src/main/kotlin/io/github/voytech/tabulate/components/document/api/builder/dsl/AttributesApi.kt
|
voytech
| 262,033,710
| false
|
{"Kotlin": 809513, "Java": 7496, "Shell": 679}
|
package io.github.voytech.tabulate.components.document.api.builder.dsl
import io.github.voytech.tabulate.components.document.model.Document
import io.github.voytech.tabulate.core.model.attributes.HeightAttribute
import io.github.voytech.tabulate.core.model.attributes.WidthAttribute
fun DocumentLevelAttributesBuilderApi.width(block: WidthAttribute.Builder.() -> Unit) =
attribute(WidthAttribute.builder<Document>().apply(block))
fun DocumentLevelAttributesBuilderApi.height(block: HeightAttribute.Builder.() -> Unit) =
attribute(HeightAttribute.builder<Document>().apply(block))
| 15
|
Kotlin
|
0
| 2
|
c7886212148dbaba9cfcaeba826ce752b4971bea
| 590
|
tabulate
|
Apache License 2.0
|
tabulate-core/src/main/kotlin/io/github/voytech/tabulate/components/document/api/builder/dsl/AttributesApi.kt
|
voytech
| 262,033,710
| false
|
{"Kotlin": 809513, "Java": 7496, "Shell": 679}
|
package io.github.voytech.tabulate.components.document.api.builder.dsl
import io.github.voytech.tabulate.components.document.model.Document
import io.github.voytech.tabulate.core.model.attributes.HeightAttribute
import io.github.voytech.tabulate.core.model.attributes.WidthAttribute
fun DocumentLevelAttributesBuilderApi.width(block: WidthAttribute.Builder.() -> Unit) =
attribute(WidthAttribute.builder<Document>().apply(block))
fun DocumentLevelAttributesBuilderApi.height(block: HeightAttribute.Builder.() -> Unit) =
attribute(HeightAttribute.builder<Document>().apply(block))
| 15
|
Kotlin
|
0
| 2
|
c7886212148dbaba9cfcaeba826ce752b4971bea
| 590
|
tabulate
|
Apache License 2.0
|
animation/src/main/kotlin/team/duckie/quackquack/animation/AnimatedContent.kt
|
duckie-team
| 523,387,054
| false
| null |
/*
* Designed and developed by Duckie Team, 2022~2023
*
* Licensed under the MIT.
* Please see full license: https://github.com/duckie-team/quack-quack-android/blob/master/LICENSE
*/
package team.duckie.quackquack.animation
import androidx.compose.animation.AnimatedContent
import androidx.compose.animation.AnimatedVisibilityScope
import androidx.compose.animation.ExperimentalAnimationApi
import androidx.compose.animation.SizeTransform
import androidx.compose.animation.fadeIn
import androidx.compose.animation.fadeOut
import androidx.compose.animation.with
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
/**
* 컴포저블의 상태에 변화가 있을 때 자동으로 해당 상태에 맞춰 애니메이션을 적용합니다.
*
* @param targetState 변화를 감지할 컴포저블의 상태값
* @param label Animation Inspector에서 이 애니메이션을 구분할 별칭
* @param content 상태 변화 애니메이션을 적용할 컴포저블 컨텐츠. 인자로는 애니메이션이
* 적용되고 있는 [targetState]의 값이 들어옵니다. **애니메이션이 적용되기 위해선 필수로
* 이 값을 상태로 적용해야 합니다.**
*/
@OptIn(ExperimentalAnimationApi::class)
@Composable
public fun <T> QuackAnimatedContent(
modifier: Modifier = Modifier,
targetState: T,
label: String = "AnimatedContent",
content: @Composable AnimatedVisibilityScope.(animatedTargetState: T) -> Unit,
) {
AnimatedContent(
modifier = modifier,
targetState = targetState,
transitionSpec = {
fadeIn(
animationSpec = QuackAnimationSpec(),
) with fadeOut(
animationSpec = QuackAnimationSpec(),
) using SizeTransform(
clip = false,
sizeAnimationSpec = { _, _ ->
QuackAnimationSpec()
},
)
},
label = label,
content = content,
)
}
| 32
| null |
4
| 56
|
1a36821e39113fa1aec321c688666a2be64b6d47
| 1,625
|
quack-quack-android
|
MIT License
|
src/main/kotlin/me/mical/remoteoperate/RemoteUtils.kt
|
Micalhl
| 534,007,672
| false
| null |
package me.mical.remoteoperate
import com.bekvon.bukkit.residence.api.ResidenceApi
import com.bekvon.bukkit.residence.containers.Flags
import com.bekvon.bukkit.residence.protection.FlagPermissions
import nl.rutgerkok.blocklocker.BlockLockerAPIv2
import org.bukkit.Location
import org.bukkit.block.Block
import org.bukkit.entity.Player
import taboolib.platform.BukkitPlugin
/**
* @author xiaomu
* @since 2022/9/6 10:15
*/
fun String.parseLocation(): Location {
val (world, x, y, z) = split("&", limit = 4)
return Location(plugin.server.getWorld(world), x.toDouble(), y.toDouble(), z.toDouble())
}
fun Location.parseString(): String {
val world = this.world!!.name
val x = blockX
val y = blockY
val z = blockZ
return "$world&$x&$y&$z"
}
private val plugin by lazy {
BukkitPlugin.getInstance()
}
val blockLockerEnabled = plugin.server.pluginManager.getPlugin("BlockLocker") != null
val residenceEnabled = plugin.server.pluginManager.getPlugin("Residence") != null
val itemsAdderEnabled = plugin.server.pluginManager.getPlugin("ItemsAdder") != null
fun Location.checkResidence(user: Player, flags: Flags): Boolean {
if (!residenceEnabled) return true
val residence = ResidenceApi.getResidenceManager().getByLoc(this)
return if (residence == null) true else (residence.ownerUUID == user.uniqueId || residence.permissions.playerHas(
user, flags, FlagPermissions.FlagCombo.OnlyTrue
) || residence.permissions.playerHas(user, Flags.admin, FlagPermissions.FlagCombo.OnlyTrue))
}
fun Block.checkLocker(user: Player): Boolean {
return if (!blockLockerEnabled) true else BlockLockerAPIv2.isAllowed(user, this, false)
}
| 0
|
Kotlin
|
1
| 0
|
351b4d971b4a2721b468b54d82eb0a5993967999
| 1,679
|
RemoteOperate
|
MIT License
|
cottontaildb-dbms/src/main/kotlin/org/vitrivr/cottontail/dbms/execution/operators/definition/CreateIndexOperator.kt
|
vitrivr
| 160,775,368
| false
| null |
package org.vitrivr.cottontail.dbms.execution.operators.definition
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.flow
import org.vitrivr.cottontail.core.basics.Record
import org.vitrivr.cottontail.core.database.Name
import org.vitrivr.cottontail.dbms.catalogue.CatalogueTx
import org.vitrivr.cottontail.dbms.catalogue.DefaultCatalogue
import org.vitrivr.cottontail.dbms.entity.EntityTx
import org.vitrivr.cottontail.dbms.execution.operators.basics.Operator
import org.vitrivr.cottontail.dbms.index.IndexTx
import org.vitrivr.cottontail.dbms.index.IndexType
import org.vitrivr.cottontail.dbms.schema.SchemaTx
import kotlin.time.ExperimentalTime
import kotlin.time.measureTimedValue
/**
* An [Operator.SourceOperator] used during query execution. Creates an [Index]
*
* @author <NAME>
* @version 1.1.0
*/
@ExperimentalTime
class CreateIndexOperator(
private val catalogue: DefaultCatalogue,
private val name: Name.IndexName,
private val type: IndexType,
private val indexColumns: List<Name.ColumnName>,
private val params: Map<String, String>,
private val rebuild: Boolean = false,
) : AbstractDataDefinitionOperator(name, "CREATE INDEX") {
override fun toFlow(context: org.vitrivr.cottontail.dbms.execution.TransactionContext): Flow<Record> {
val catTxn = context.getTx(this.catalogue) as CatalogueTx
val schemaTxn = context.getTx(catTxn.schemaForName(this.name.schema())) as SchemaTx
val entityTxn = context.getTx(schemaTxn.entityForName(this.name.entity())) as EntityTx
val columns = this.indexColumns.map { entityTxn.columnForName(it).columnDef }.toTypedArray()
return flow {
val timedTupleId = measureTimedValue {
val index = entityTxn.createIndex(
this@CreateIndexOperator.name,
this@CreateIndexOperator.type,
columns,
this@CreateIndexOperator.params
)
if (this@CreateIndexOperator.rebuild) {
val indexTxn = context.getTx(index) as IndexTx
indexTxn.rebuild()
}
}
emit(this@CreateIndexOperator.statusRecord(timedTupleId.duration))
}
}
}
| 8
|
Kotlin
|
15
| 15
|
c6e06263d9163f697e0aa5dc334a910521620215
| 2,268
|
cottontaildb
|
MIT License
|
thelema-kx/src/commonMain/kotlin/org/ksdfv/thelema/g2d/TextureAtlas.kt
|
cybernetics
| 365,452,918
| true
|
{"Kotlin": 3356187, "C": 552354, "Java": 355550, "HTML": 6211, "Makefile": 260}
|
/*
* 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 org.ksdfv.thelema.g2d
import org.ksdfv.thelema.fs.IFile
import org.ksdfv.thelema.gl.*
import org.ksdfv.thelema.img.ITexture2D
import org.ksdfv.thelema.img.Texture2D
import org.ksdfv.thelema.net.NET
import org.ksdfv.thelema.utils.LOG
import kotlin.native.concurrent.ThreadLocal
/** Loads images from texture atlases created by TexturePacker.<br></br>
* <br></br>
* A TextureAtlas must be disposed to free up the resources consumed by the backing textures.
* @author <NAME>
*/
class TextureAtlas {
/** Textures of the pages, unordered */
val textures: LinkedHashSet<ITexture2D> = LinkedHashSet(4)
/** Returns all regions in the atlas. */
val regions: ArrayList<AtlasRegion> = ArrayList()
class TextureAtlasData(packFile: IFile, imagesDir: IFile, flip: Boolean) {
class Page(val textureFile: IFile, val width: Float, val height: Float, val useMipMaps: Boolean, val format: Int, val minFilter: Int,
val magFilter: Int, val uWrap: Int, val vWrap: Int) {
var texture: Texture2D? = null
}
class Region {
var page: Page? = null
var index = 0
var name: String? = null
var offsetX = 0f
var offsetY = 0f
var originalWidth = 0
var originalHeight = 0
var rotate = false
var degrees = 0
var left = 0
var top = 0
var width = 0
var height = 0
var flip = false
var splits = IntArray(0) { 0 }
var pads = IntArray(0) { 0 }
}
val pages: ArrayList<Page> = ArrayList()
val regions: ArrayList<Region> = ArrayList()
init {
packFile.readText { status, text ->
if (status == NET.OK) {
val lines = text.split('\n')
var i = 0
while (i < lines.size) {
val line = lines[i]
var pageImage: Page? = null
when {
line.trim { it <= ' ' }.isEmpty() -> pageImage = null
pageImage == null -> {
val file = imagesDir.child(line)
var width = 0f
var height = 0f
i++
if (readTuple(lines[i]) == 2) { // size is only optional for an atlas packed with an old TexturePacker.
width = tuple[0]!!.toInt().toFloat()
height = tuple[1]!!.toInt().toFloat()
i++
readTuple(lines[i])
}
//val format = Pixmap.Format.valueOf(tuple[0]!!)
val format = when (tuple[0]!!) {
"Alpha" -> GL_R8
"Intensity" -> GL_R8
"LuminanceAlpha" -> GL_RG8
"RGB565" -> GL_RGB565
"RGBA4444" -> GL_RGBA4
"RGB888" -> GL_RGB8
"RGBA8888" -> GL_RGBA8
else -> throw RuntimeException("Unknown pixmap format: ${tuple[0]!!}")
}
i++
readTuple(lines[i])
val min = when (tuple[0]!!) {
"Nearest" -> GL_NEAREST
"Linear" -> GL_LINEAR
"MipMapNearestNearest" -> GL_NEAREST_MIPMAP_NEAREST
"MipMapLinearNearest" -> GL_LINEAR_MIPMAP_NEAREST
"MipMapNearestLinear" -> GL_NEAREST_MIPMAP_LINEAR
"MipMapLinearLinear" -> GL_LINEAR_MIPMAP_LINEAR
else -> throw RuntimeException("TextureAtlas: format is unknown: ${tuple[0]}")
}
val max = when (tuple[1]!!) {
"Nearest" -> GL_NEAREST
"Linear" -> GL_LINEAR
"MipMapNearestNearest" -> GL_NEAREST_MIPMAP_NEAREST
"MipMapLinearNearest" -> GL_LINEAR_MIPMAP_NEAREST
"MipMapNearestLinear" -> GL_NEAREST_MIPMAP_LINEAR
"MipMapLinearLinear" -> GL_LINEAR_MIPMAP_LINEAR
else -> throw RuntimeException("TextureAtlas: format is unknown: ${tuple[1]}")
}
val isMipmap = min == GL_NEAREST_MIPMAP_NEAREST ||
min == GL_LINEAR_MIPMAP_NEAREST ||
min == GL_NEAREST_MIPMAP_LINEAR ||
min == GL_LINEAR_MIPMAP_LINEAR
i++
val direction = readValue(lines[i])
var repeatX = GL_CLAMP_TO_EDGE
var repeatY = GL_CLAMP_TO_EDGE
when (direction) {
"x" -> repeatX = GL_REPEAT
"y" -> repeatY = GL_REPEAT
"xy" -> {
repeatX = GL_REPEAT
repeatY = GL_REPEAT
}
}
pageImage = Page(file, width, height, isMipmap, format, min, max, repeatX, repeatY)
pages.add(pageImage)
}
else -> {
i++
val rotateValue = readValue(lines[i])
var degrees: Int
degrees = when {
rotateValue.equals("true", ignoreCase = true) -> 90
rotateValue.equals("false", ignoreCase = true) -> 0
else -> rotateValue.toInt()
}
i++
readTuple(lines[i])
val left = tuple[0]!!.toInt()
val top = tuple[1]!!.toInt()
i++
readTuple(lines[i])
val width = tuple[0]!!.toInt()
val height = tuple[1]!!.toInt()
val region = Region()
region.page = pageImage
region.left = left
region.top = top
region.width = width
region.height = height
region.name = line
region.rotate = degrees == 90
region.degrees = degrees
i++
if (readTuple(lines[i]) == 4) { // split is optional
region.splits = intArrayOf(tuple[0]!!.toInt(), tuple[1]!!.toInt(), tuple[2]!!.toInt(), tuple[3]!!.toInt())
i++
if (readTuple(lines[i]) == 4) { // pad is optional, but only present with splits
region.pads = intArrayOf(tuple[0]!!.toInt(), tuple[1]!!.toInt(), tuple[2]!!.toInt(), tuple[3]!!.toInt())
i++
readTuple(lines[i])
}
}
region.originalWidth = tuple[0]!!.toInt()
region.originalHeight = tuple[1]!!.toInt()
i++
readTuple(lines[i])
region.offsetX = tuple[0]!!.toInt().toFloat()
region.offsetY = tuple[1]!!.toInt().toFloat()
i++
region.index = readValue(lines[i]).toInt()
if (flip) region.flip = true
regions.add(region)
}
}
i++
}
} else {
LOG.error("Error reading file ${packFile.path}, status: $status")
}
}
regions.sortedWith(indexComparator)
}
}
/** Creates an empty atlas to which regions can be added. */
constructor()
/** @param flip If true, all regions loaded will be flipped for use with a perspective where 0,0 is the upper left corner. */
constructor(packFile: IFile, flip: Boolean) : this(packFile, packFile.parent(), flip)
/** Loads the specified pack file, using the parent directory of the pack file to find the page images.
* @param flip If true, all regions loaded will be flipped for use with a perspective where 0,0 is the upper left corner. */
constructor(packFile: IFile, imagesDir: IFile = packFile.parent(), flip: Boolean = false) : this(TextureAtlasData(packFile, imagesDir, flip))
/** @param data May be null.
*/
constructor(data: TextureAtlasData?) {
data?.let { load(it) }
}
private fun load(data: TextureAtlasData) {
val pageToTexture = HashMap<TextureAtlasData.Page, ITexture2D>()
for (page in data.pages) {
var texture: ITexture2D? = page.texture
if (texture == null) {
texture = Texture2D().load(page.textureFile)
if (page.useMipMaps) texture.generateMipmapsGPU()
}
texture.apply {
bind()
minFilter = page.minFilter
magFilter = page.magFilter
sWrap = page.uWrap
tWrap = page.vWrap
}
textures.add(texture)
pageToTexture[page] = texture
}
for (region in data.regions) {
val width = region.width
val height = region.height
val atlasRegion = AtlasRegion(
pageToTexture[region.page]!!, region.left, region.top,
if (region.rotate) height else width, if (region.rotate) width else height
)
atlasRegion.index = region.index
atlasRegion.name = region.name
atlasRegion.offsetX = region.offsetX
atlasRegion.offsetY = region.offsetY
atlasRegion.originalHeight = region.originalHeight
atlasRegion.originalWidth = region.originalWidth
atlasRegion.rotate = region.rotate
atlasRegion.degrees = region.degrees
atlasRegion.splits = region.splits
atlasRegion.pads = region.pads
if (region.flip) atlasRegion.flip(false, true)
regions.add(atlasRegion)
}
}
/** Adds a region to the atlas. The specified texture will be disposed when the atlas is disposed. */
fun addRegion(name: String, texture: Texture2D, x: Int, y: Int, width: Int, height: Int): AtlasRegion {
textures.add(texture)
val region = AtlasRegion(texture, x, y, width, height)
region.name = name
region.index = -1
regions.add(region)
return region
}
/** Adds a region to the atlas. The texture for the specified region will be disposed when the atlas is disposed. */
fun addRegion(name: String, textureRegion: TextureRegion): AtlasRegion {
textures.add(textureRegion.texture)
val region = AtlasRegion(textureRegion)
region.name = name
region.index = -1
regions.add(region)
return region
}
/** Returns the first region found with the specified name. This method uses string comparison to find the region, so the result
* should be cached rather than calling this method multiple times.
* @return The region, or null.
*/
fun findRegion(name: String): AtlasRegion? {
var i = 0
val n = regions.size
while (i < n) {
if (regions[i].name == name) return regions[i]
i++
}
return null
}
/** Returns the first region found with the specified name and index. This method uses string comparison to find the region, so
* the result should be cached rather than calling this method multiple times.
* @return The region, or null.
*/
fun findRegion(name: String, index: Int): AtlasRegion? {
var i = 0
val n = regions.size
while (i < n) {
val region = regions[i]
if (region.name != name) {
i++
continue
}
if (region.index != index) {
i++
continue
}
return region
}
return null
}
/** Returns all regions with the specified name, ordered by smallest to largest [index][AtlasRegion.index]. This method
* uses string comparison to find the regions, so the result should be cached rather than calling this method multiple times. */
fun findRegions(name: String): ArrayList<AtlasRegion> {
val matched: ArrayList<AtlasRegion> =
ArrayList()
var i = 0
val n = regions.size
while (i < n) {
val region = regions[i]
if (region.name == name) matched.add(AtlasRegion(region))
i++
}
return matched
}
/** Returns all regions in the atlas as sprites. This method creates a new sprite for each region, so the result should be
* stored rather than calling this method multiple times.
* See [createSprite]
*/
fun createSprites(): ArrayList<Sprite> {
val sprites = ArrayList<Sprite>()
var i = 0
val n = regions.size
while (i < n) {
sprites.add(newSprite(regions[i]))
i++
}
return sprites
}
/** Returns the first region found with the specified name as a sprite. If whitespace was stripped from the region when it was
* packed, the sprite is automatically positioned as if whitespace had not been stripped. This method uses string comparison to
* find the region and constructs a new sprite, so the result should be cached rather than calling this method multiple times.
* @return The sprite, or null.
*/
fun createSprite(name: String): Sprite? {
var i = 0
val n = regions.size
while (i < n) {
if (regions[i].name == name) return newSprite(regions[i])
i++
}
return null
}
/** Returns the first region found with the specified name and index as a sprite. This method uses string comparison to find the
* region and constructs a new sprite, so the result should be cached rather than calling this method multiple times.
* @return The sprite, or null.
* See [createSprite]
*/
fun createSprite(name: String, index: Int): Sprite? {
var i = 0
val n = regions.size
while (i < n) {
val region = regions[i]
if (region.name != name) {
i++
continue
}
if (region.index != index) {
i++
continue
}
return newSprite(regions[i])
}
return null
}
/** Returns all regions with the specified name as sprites, ordered by smallest to largest [index][AtlasRegion.index]. This
* method uses string comparison to find the regions and constructs new sprites, so the result should be cached rather than
* calling this method multiple times.
* See [createSprite]
*/
fun createSprites(name: String): ArrayList<Sprite> {
val matched: ArrayList<Sprite> = ArrayList()
var i = 0
val n = regions.size
while (i < n) {
val region = regions[i]
if (region.name == name) matched.add(newSprite(region))
i++
}
return matched
}
private fun newSprite(region: AtlasRegion): Sprite {
if (region.packedWidth == region.originalWidth && region.packedHeight == region.originalHeight) {
if (region.rotate) {
val sprite = Sprite(region)
sprite.setBounds(0f, 0f, region.regionHeight.toFloat(), region.regionWidth.toFloat())
sprite.rotate90(true)
return sprite
}
return Sprite(region)
}
return AtlasSprite(region)
}
/** Returns the first region found with the specified name as a [NinePatch]. The region must have been packed with
* ninepatch splits. This method uses string comparison to find the region and constructs a new ninepatch, so the result should
* be cached rather than calling this method multiple times.
* @return The ninepatch, or null.
*/
fun createPatch(name: String): NinePatch? {
var i = 0
val n = regions.size
while (i < n) {
val region = regions[i]
if (region.name == name) {
val splits = region.splits
?: throw IllegalArgumentException("Region does not have ninepatch splits: $name")
val patch = NinePatch(region, splits[0], splits[1], splits[2], splits[3])
if (region.pads != null) patch.setPadding(region.pads!![0].toFloat(), region.pads!![1].toFloat(), region.pads!![2].toFloat(), region.pads!![3].toFloat())
return patch
}
i++
}
return null
}
/** Releases all resources associated with this TextureAtlas instance. This releases all the textures backing all TextureRegions
* and Sprites, which should no longer be used after calling dispose. */
fun dispose() {
for (texture in textures) texture.destroy()
textures.clear()
}
@ThreadLocal
companion object {
val tuple = arrayOfNulls<String>(4)
val indexComparator: Comparator<TextureAtlasData.Region> = Comparator { region1, region2 ->
var i1 = region1.index
if (i1 == -1) i1 = Int.MAX_VALUE
var i2 = region2.index
if (i2 == -1) i2 = Int.MAX_VALUE
i1 - i2
}
fun readValue(line: String): String {
val colon = line.indexOf(':')
if (colon == -1) throw RuntimeException("Invalid line: $line")
return line.substring(colon + 1).trim { it <= ' ' }
}
/** Returns the number of tuple values read (1, 2 or 4). */
fun readTuple(line: String): Int {
val colon = line.indexOf(':')
if (colon == -1) throw RuntimeException("Invalid line: $line")
var lastMatch = colon + 1
var i = 0
while (i < 3) {
val comma = line.indexOf(',', lastMatch)
if (comma == -1) break
tuple[i] = line.substring(lastMatch, comma).trim { it <= ' ' }
lastMatch = comma + 1
i++
}
tuple[i] = line.substring(lastMatch).trim { it <= ' ' }
return i + 1
}
}
}
| 0
| null |
0
| 0
|
c274a903f0a4d17e5ef14773efa144ee8c8809dd
| 20,607
|
thelema-engine
|
Apache License 2.0
|
src/acceptanceTest/kotlin/com/github/jcornaz/islands/test/EndpointTestUtils.kt
|
jcornaz
| 144,144,275
| false
| null |
package com.github.jcornaz.islands.test
import com.google.protobuf.Message
import io.ktor.http.ContentType
import io.ktor.http.HttpHeaders
import io.ktor.http.HttpStatusCode
import io.ktor.http.isSuccess
import io.ktor.server.testing.TestApplicationCall
import io.ktor.server.testing.TestApplicationRequest
import io.ktor.server.testing.setBody
import org.amshove.kluent.shouldBeTrue
import org.amshove.kluent.shouldEqual
import org.amshove.kluent.shouldNotBeNull
import org.spekframework.spek2.style.specification.Suite
fun TestApplicationRequest.setBody(message: Message) {
addHeader(HttpHeaders.Accept, ContentType.Application.OctetStream.toString())
setBody(message.toByteArray())
}
fun Suite.itShouldHandleRequest(expectedStatusCode: HttpStatusCode = HttpStatusCode.OK, getCall: () -> TestApplicationCall) {
it("should handle request") {
getCall().requestHandled.shouldBeTrue()
}
it("should return $expectedStatusCode") {
getCall().response.status() shouldEqual expectedStatusCode
}
if (expectedStatusCode.isSuccess()) {
it("should return a body") {
getCall().response.byteContent.shouldNotBeNull()
}
}
}
| 0
|
Kotlin
|
0
| 2
|
33984a05d79e0007ba73522a313d71bb74365713
| 1,191
|
islands-on-map
|
MIT License
|
app/src/main/java/com/app/jetpack/ui/home/HomeViewModel.kt
|
ldk123456
| 648,167,522
| false
| null |
package com.app.jetpack.ui.home
import android.util.Log
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.viewModelScope
import androidx.paging.DataSource
import androidx.paging.ItemKeyedDataSource
import androidx.paging.PagedList
import com.alibaba.fastjson2.TypeReference
import com.app.jetpack.model.Feed
import com.app.jetpack.ui.base.BasePagedViewModel
import com.app.jetpack.ui.base.MutablePageKeyedDataSource
import com.app.jetpack.ui.login.UserManager
import com.app.lib_common.ext.safeAs
import com.app.lib_network.ApiService
import com.app.lib_network.core.CacheStrategy
import com.app.lib_network.core.JsonCallback
import com.app.lib_network.response.ApiResponse
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
import java.util.concurrent.atomic.AtomicBoolean
class HomeViewModel : BasePagedViewModel<Feed>() {
@Volatile
private var mWithCache = true
private val mCacheLiveData = MutableLiveData<PagedList<Feed>>()
private val mLoadAfter = AtomicBoolean(false)
private var mFeedType: String = ""
fun setFeedType(feedType: String) {
this.mFeedType = feedType
}
fun getCacheLiveData() = mCacheLiveData
override fun createDataSource(): DataSource<out Any, Feed> {
return FeedDataSource()
}
inner class FeedDataSource : ItemKeyedDataSource<Int, Feed>() {
override fun getKey(item: Feed): Int {
return item.id
}
override fun loadAfter(params: LoadParams<Int>, callback: LoadCallback<Feed>) {
loadData(params.key, params.requestedLoadSize, callback)
}
override fun loadBefore(params: LoadParams<Int>, callback: LoadCallback<Feed>) {
callback.onResult(listOf())
}
override fun loadInitial(params: LoadInitialParams<Int>, callback: LoadInitialCallback<Feed>) {
loadData(0, params.requestedLoadSize, callback)
mWithCache = false
}
}
private var first = true
private fun loadData(key: Int, count: Int, callback: ItemKeyedDataSource.LoadCallback<Feed>) {
viewModelScope.launch(Dispatchers.IO) {
if (key > 0 && first) {
first = false
delay(5000)
mLoadAfter.set(true)
}
val request = ApiService.get<ArrayList<Feed>>("/feeds/queryHotFeedsList")
.addParam("feedType", mFeedType)
.addParam("userId", UserManager.getUserId())
.addParam("feedId", key)
.addParam("pageCount", count)
.responseType(object : TypeReference<ArrayList<Feed>>() {}.type)
if (mWithCache) {
request.cacheStrategy(CacheStrategy.CACHE_ONLY)
request.execute(object : JsonCallback<ArrayList<Feed>> {
override fun onCacheSuccess(response: ApiResponse<ArrayList<Feed>>) {
Log.e("loadData", "onCacheSuccess: ")
val dataSource = MutablePageKeyedDataSource<Feed>()
dataSource.data.addAll(response.body ?: listOf())
mCacheLiveData.postValue(dataSource.buildNewPagedList(config))
}
})
}
val netRequest = if (mWithCache) request.clone() else request
netRequest.cacheStrategy(if (key == 0) CacheStrategy.NET_CACHE else CacheStrategy.NET_ONLY)
val response = netRequest.execute()
callback.onResult(response.body ?: listOf())
if (key > 0) {
getBoundaryPagedData().safeAs<MutableLiveData<Boolean>>()?.postValue(!response.body.isNullOrEmpty())
mLoadAfter.set(false)
}
Log.e("loadData", "key: $key")
}
}
fun loadAfter(key: Int, callback: ItemKeyedDataSource.LoadCallback<Feed>) {
if (mLoadAfter.get()) {
callback.onResult(listOf())
return
}
viewModelScope.launch(Dispatchers.IO) {
loadData(key, config.pageSize, callback)
}
}
}
| 0
|
Kotlin
|
0
| 0
|
8b14da1cf3ee28d9f52081b4a830b2e82cbb9319
| 4,142
|
JetpackApp
|
Apache License 2.0
|
app/src/main/java/tech/okcredit/appstartupinstrumentation/MainActivity.kt
|
okcredit
| 386,817,073
| false
| null |
package tech.okcredit.appstartupinstrumentation
import android.content.Intent
import android.os.Bundle
import android.view.View
import android.widget.TextView
import androidx.appcompat.app.AppCompatActivity
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
findViewById<TextView>(R.id.hello_world).text = this.hashCode().toString()
findViewById<View>(R.id.hello_world).setOnClickListener {
startActivity(Intent(this, MainActivity::class.java))
}
}
}
| 0
|
Kotlin
|
3
| 27
|
88ad83b5c60ebebba3fa7832728ac75325328aa5
| 634
|
android-cold-startup-instrumentation
|
Apache License 2.0
|
cockpit-core/src/main/java/com/orbitalhq/cockpit/core/security/authorisation/UserRoleRepository.kt
|
orbitalapi
| 541,496,668
| false
|
{"TypeScript": 9344934, "Kotlin": 5669840, "HTML": 201985, "SCSS": 170620, "HCL": 55741, "Java": 29373, "JavaScript": 24697, "Shell": 8800, "Dockerfile": 7001, "Smarty": 4741, "CSS": 2966, "Mustache": 1392, "Batchfile": 983, "MDX": 884, "PLpgSQL": 337}
|
package com.orbitalhq.cockpit.core.security.authorisation
interface UserRoleRepository {
}
| 9
|
TypeScript
|
10
| 292
|
2be59abde0bd93578f12fc1e2ecf1f458a0212ec
| 92
|
orbital
|
Apache License 2.0
|
datalayer/src/main/java/com/reach/datalayer/remote/bing/BingService.kt
|
Reach2027
| 455,874,347
| false
| null |
/*
* Copyright 2022 Reach2027
*
* 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.reach.datalayer.remote.bing
import retrofit2.http.GET
import retrofit2.http.Query
/**
* 2022/2/5 Reach
*/
interface BingService {
@GET("/HPImageArchive.aspx")
suspend fun getImageUrl(
@Query("format") format: String = "js",
@Query("idx") idx: Int = 0,
@Query("n") n: Int = 8,
@Query("ensearch") en: Int = 1
): BingResult
}
| 0
|
Kotlin
|
0
| 0
|
89903210af0cbf75b8124b89ab0e19d49e4c4025
| 980
|
Todo
|
Apache License 2.0
|
app/src/main/java/com/manuelsoft/loginapp/ui/login/LoginActivity.kt
|
VictorSalazar777
| 419,127,082
| false
| null |
package com.manuelsoft.loginapp.ui.login
import android.content.Intent
import android.net.Uri
import android.os.Bundle
import android.util.Log
import android.view.View
import androidx.activity.viewModels
import androidx.appcompat.app.AppCompatActivity
import androidx.fragment.app.commit
import com.google.android.gms.auth.api.identity.SignInCredential
import com.google.android.material.snackbar.Snackbar
import com.google.firebase.auth.FirebaseUser
import com.manuelsoft.loginapp.R
import com.manuelsoft.loginapp.data.model.GoogleSignInData
import com.manuelsoft.loginapp.databinding.ActivityLoginBinding
import com.manuelsoft.loginapp.firebase.AppAuth
import com.manuelsoft.loginapp.firebase.AppAuthImpl
import com.manuelsoft.loginapp.ui.home.HomeActivity
import com.manuelsoft.loginapp.ui.login.menu.LoginMenuFragment
import com.manuelsoft.loginapp.ui.login.viewmodel.LoginViewModel
import dagger.hilt.android.AndroidEntryPoint
import javax.inject.Inject
@AndroidEntryPoint
class LoginActivity : AppCompatActivity() {
@Inject
lateinit var googleOneTap: GoogleOneTap
@Inject
lateinit var appAuth: AppAuth
private val loginViewModel: LoginViewModel by viewModels()
companion object {
val TAG: String = LoginActivity::class.java.simpleName
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
val binding = ActivityLoginBinding.inflate(layoutInflater)
setContentView(binding.root)
addSignInFragment(savedInstanceState)
setupGoogleSignInOneTap()
observeSignInWithGoogleBtn()
}
private fun addSignInFragment(savedInstanceState: Bundle?) {
if (savedInstanceState == null) {
supportFragmentManager
.commit {
setReorderingAllowed(true)
add(R.id.fragment_container, LoginMenuFragment::class.java, null)
}
}
}
private fun setupGoogleSignInOneTap() {
googleOneTap.setupSignIn(this)
}
private fun observeSignInWithGoogleBtn() {
loginViewModel.clickSignInWithGoogleBtn.observe(this, {
showGoogleSignInOneTapUi()
})
}
private fun showGoogleSignInOneTapUi() {
googleOneTap.showSignInUi(this)
}
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
super.onActivityResult(requestCode, resultCode, data)
resultOfGoogleSignInOneTapUi(requestCode, resultCode, data)
}
private fun resultOfGoogleSignInOneTapUi(
requestCode: Int,
resultCode: Int,
data: Intent?
) {
googleOneTap.onActivityResult(requestCode, resultCode, data, object: SignIn {
override fun onSuccess(signInCredential: SignInCredential) {
val idToken = signInCredential.googleIdToken
val id = signInCredential.id
val password = <PASSWORD>
val profilePictureUri = signInCredential.profilePictureUri
when {
idToken != null -> {
// Got an ID token from Google. Use it to authenticate
// with your backend.
Log.d(TAG, "Got ID token.")
authenticateGoogleToken(idToken, id, profilePictureUri)
}
password != null -> {
// Got a saved username and password. Use them to authenticate
// with your backend.
Log.d(TAG, "Got password.")
loginViewModel.saveGoogleSignInData(GoogleSignInData.GoogleSignInPasswordData(id, password, profilePictureUri))
showHomeActivity()
}
else -> {
// Shouldn't happen.
Log.d(TAG, "No ID token or password!")
showMessage("No ID token or password!")
}
}
}
override fun onFailure(message: String) {
showMessage(message)
}
})
}
private fun authenticateGoogleToken(
idToken: String,
id: String,
profilePictureUri: Uri?
) {
appAuth.firebaseAuthWithGoogle(
idToken,
this@LoginActivity,
object : AppAuthImpl.FirebaseAuthTask {
override fun success(currentUser: FirebaseUser?) {
Log.d(TAG, "current user: $currentUser")
googleTokenAuthenticationSuccessful(idToken, id, profilePictureUri)
}
override fun failure() {
showMessage("Google token authentication failed")
}
})
}
private fun googleTokenAuthenticationSuccessful(
idToken: String,
id: String,
profilePictureUri: Uri?
) {
loginViewModel.saveGoogleSignInData(
GoogleSignInData.GoogleSignInTokenData(
idToken,
id,
profilePictureUri
)
)
showHomeActivity()
}
private fun showMessage(message: String) {
val contextView = findViewById<View>(android.R.id.content)
Snackbar.make(contextView, message, Snackbar.LENGTH_LONG).show()
}
fun showHomeActivity() {
val intent = Intent(this, HomeActivity::class.java)
startActivity(intent)
finish()
}
// override fun onBackPressed() {
// moveTaskToBack(true)
// }
}
| 0
|
Kotlin
|
0
| 0
|
6fa2280cd0bb0d5f7dfc65c603cf56bc590587f5
| 5,631
|
LoginApp
|
MIT License
|
lib_base/src/main/java/com/example/lib_base/dialog/DialogManager.kt
|
TReturn
| 399,864,608
| false
|
{"Kotlin": 347815, "Java": 152179}
|
package com.example.lib_base.dialog
import android.content.Context
import com.lxj.xpopup.XPopup
/**
* @CreateDate: 2023/8/31 15:53
* @Author: 青柠
* @Description:
*/
object DialogManager {
/**
* 获取一个默认的Dialog
* @param context Context
* @param isDismissOnTouch Boolean
* @return XPopup.Builder
*/
fun get(context: Context, isDismissOnTouch: Boolean = true): XPopup.Builder {
return XPopup.Builder(context)
.isDestroyOnDismiss(true)
.dismissOnTouchOutside(isDismissOnTouch)
.dismissOnBackPressed(isDismissOnTouch)
}
/**
* 获取一个View实现的Dialog
* @param context Context
* @param isDismissOnTouch Boolean
* @return XPopup.Builder
*/
fun getViewModel(context: Context, isDismissOnTouch: Boolean = true): XPopup.Builder {
return XPopup.Builder(context)
.isViewMode(true)
.isDestroyOnDismiss(true)
.dismissOnTouchOutside(isDismissOnTouch)
.dismissOnBackPressed(isDismissOnTouch)
}
}
| 0
|
Kotlin
|
1
| 1
|
14d21f13fbe8ea7aa33f0183702ceb886cc96331
| 1,051
|
BaseApp
|
Apache License 2.0
|
glm/src/main/kotlin/glm_/gtc/matrixTransform/gtcMatrixScale.kt
|
boehmseb
| 217,838,544
| true
|
{"Kotlin": 2726177, "Java": 2543}
|
package glm_.gtc.matrixTransform
import glm_.mat4x4.Mat4
import glm_.mat4x4.Mat4d
import glm_.mat3x3.Mat3
import glm_.mat3x3.Mat3d
import glm_.vec3.Vec3
import glm_.vec3.Vec3d
interface gtcMatrixScale {
/** Builds a scale 4 * 4 matrix created from 3 scalars.
*
* @param res resulting scale matrix.
* @param m Input matrix multiplied by this scale matrix.
* @param vX Ratio of scaling for X axis.
* @param vY Ratio of scaling for Y axis.
* @param vZ Ratio of scaling for Z axis.
*
* @see gtc_matrix_transform
* @see - scale(mat<4, 4, T, Q> const& m, T x, T y, T z)
* @see - scale(vec<3, T, Q> const& v)
* @see <a href="https://www.khronos.org/registry/OpenGL-Refpages/gl2.1/xhtml/glScale.xml">glScale man page</a>
*/
fun scale(res: Mat4, m: Mat4, vX: Float, vY: Float, vZ: Float): Mat4 {
res[0, 0] = m[0, 0] * vX
res[0, 1] = m[0, 1] * vX
res[0, 2] = m[0, 2] * vX
res[0, 3] = m[0, 3] * vX
res[1, 0] = m[1, 0] * vY
res[1, 1] = m[1, 1] * vY
res[1, 2] = m[1, 2] * vY
res[1, 3] = m[1, 3] * vY
res[2, 0] = m[2, 0] * vZ
res[2, 1] = m[2, 1] * vZ
res[2, 2] = m[2, 2] * vZ
res[2, 3] = m[2, 3] * vZ
res[3, 0] = m[3, 0]
res[3, 1] = m[3, 1]
res[3, 2] = m[3, 2]
res[3, 3] = m[3, 3]
return res
}
/** Builds a scale 4 * 4 matrix created from 3 scalars.
*
* @param res resulting scale matrix.
* @param m Input matrix multiplied by this scale matrix.
* @param v Ratio of scaling for this axis.
*
* @see gtc_matrix_transform
* @see - scale(mat<4, 4, T, Q> const& m, T x, T y, T z)
* @see - scale(vec<3, T, Q> const& v)
* @see <a href="https://www.khronos.org/registry/OpenGL-Refpages/gl2.1/xhtml/glScale.xml">glScale man page</a>
*/
fun scale(res: Mat4, m: Mat4, v: Vec3): Mat4 = scale(res, m, v.x, v.y, v.z)
/** Builds a scale 4 * 4 matrix created from 3 scalars.
*
* @param m Input matrix multiplied by this scale matrix.
* @param vX Ratio of scaling for X axis.
* @param vY Ratio of scaling for Y axis.
* @param vZ Ratio of scaling for Z axis.
*
* @see gtc_matrix_transform
* @see - scale(mat<4, 4, T, Q> const& m, T x, T y, T z)
* @see - scale(vec<3, T, Q> const& v)
* @see <a href="https://www.khronos.org/registry/OpenGL-Refpages/gl2.1/xhtml/glScale.xml">glScale man page</a>
*/
fun scale(m: Mat4, vX: Float, vY: Float, vZ: Float): Mat4 = scale(Mat4(), m, vX, vY, vZ)
/** Builds a scale 4 * 4 matrix created from 3 scalars.
*
* @param m Input matrix multiplied by this scale matrix.
* @param v Ratio of scaling for this axis.
*
* @see gtc_matrix_transform
* @see - scale(mat<4, 4, T, Q> const& m, T x, T y, T z)
* @see - scale(vec<3, T, Q> const& v)
* @see <a href="https://www.khronos.org/registry/OpenGL-Refpages/gl2.1/xhtml/glScale.xml">glScale man page</a>
*/
fun scale(m: Mat4, v: Vec3): Mat4 = scale(Mat4(), m, v.x, v.y, v.z)
/** Builds a scale 4 * 4 matrix created from 3 scalars.
*
* @param res resulting scale matrix.
* @param m Input matrix multiplied by this scale matrix.
* @param vX Ratio of scaling for X axis.
* @param vY Ratio of scaling for Y axis.
* @param vZ Ratio of scaling for Z axis.
*
* @see gtc_matrix_transform
* @see - scale(mat<4, 4, T, Q> const& m, T x, T y, T z)
* @see - scale(vec<3, T, Q> const& v)
* @see <a href="https://www.khronos.org/registry/OpenGL-Refpages/gl2.1/xhtml/glScale.xml">glScale man page</a>
*/
fun scale(res: Mat4d, m: Mat4d, vX: Double, vY: Double, vZ: Double): Mat4d {
res[0, 0] = m[0, 0] * vX
res[0, 1] = m[0, 1] * vX
res[0, 2] = m[0, 2] * vX
res[0, 3] = m[0, 3] * vX
res[1, 0] = m[1, 0] * vY
res[1, 1] = m[1, 1] * vY
res[1, 2] = m[1, 2] * vY
res[1, 3] = m[1, 3] * vY
res[2, 0] = m[2, 0] * vZ
res[2, 1] = m[2, 1] * vZ
res[2, 2] = m[2, 2] * vZ
res[2, 3] = m[2, 3] * vZ
res[3, 0] = m[3, 0]
res[3, 1] = m[3, 1]
res[3, 2] = m[3, 2]
res[3, 3] = m[3, 3]
return res
}
/** Builds a scale 4 * 4 matrix created from 3 scalars.
*
* @param res resulting scale matrix.
* @param m Input matrix multiplied by this scale matrix.
* @param v Ratio of scaling for this axis.
*
* @see gtc_matrix_transform
* @see - scale(mat<4, 4, T, Q> const& m, T x, T y, T z)
* @see - scale(vec<3, T, Q> const& v)
* @see <a href="https://www.khronos.org/registry/OpenGL-Refpages/gl2.1/xhtml/glScale.xml">glScale man page</a>
*/
fun scale(res: Mat4d, m: Mat4d, v: Vec3d): Mat4d = scale(res, m, v.x, v.y, v.z)
/** Builds a scale 4 * 4 matrix created from 3 scalars.
*
* @param m Input matrix multiplied by this scale matrix.
* @param vX Ratio of scaling for X axis.
* @param vY Ratio of scaling for Y axis.
* @param vZ Ratio of scaling for Z axis.
*
* @see gtc_matrix_transform
* @see - scale(mat<4, 4, T, Q> const& m, T x, T y, T z)
* @see - scale(vec<3, T, Q> const& v)
* @see <a href="https://www.khronos.org/registry/OpenGL-Refpages/gl2.1/xhtml/glScale.xml">glScale man page</a>
*/
fun scale(m: Mat4d, vX: Double, vY: Double, vZ: Double): Mat4d = scale(Mat4d(), m, vX, vY, vZ)
/** Builds a scale 4 * 4 matrix created from 3 scalars.
*
* @param m Input matrix multiplied by this scale matrix.
* @param v Ratio of scaling for this axis.
*
* @see gtc_matrix_transform
* @see - scale(mat<4, 4, T, Q> const& m, T x, T y, T z)
* @see - scale(vec<3, T, Q> const& v)
* @see <a href="https://www.khronos.org/registry/OpenGL-Refpages/gl2.1/xhtml/glScale.xml">glScale man page</a>
*/
fun scale(m: Mat4d, v: Vec3d): Mat4d = scale(Mat4d(), m, v.x, v.y, v.z)
/** Builds a scale 3 * 3 matrix created from 3 scalars.
*
* @param res resulting scale matrix.
* @param m Input matrix multiplied by this scale matrix.
* @param vX Ratio of scaling for X axis.
* @param vY Ratio of scaling for Y axis.
* @param vZ Ratio of scaling for Z axis.
*
* @see gtc_matrix_transform
* @see - scale(mat<3, 3, T, Q> const& m, T x, T y, T z)
* @see - scale(vec<3, T, Q> const& v)
* @see <a href="https://www.khronos.org/registry/OpenGL-Refpages/gl2.1/xhtml/glScale.xml">glScale man page</a>
*/
fun scale(res: Mat3, m: Mat3, vX: Float, vY: Float, vZ: Float): Mat3 {
res[0, 0] = m[0, 0] * vX
res[0, 1] = m[0, 1] * vX
res[0, 2] = m[0, 2] * vX
res[1, 0] = m[1, 0] * vY
res[1, 1] = m[1, 1] * vY
res[1, 2] = m[1, 2] * vY
res[2, 0] = m[2, 0] * vZ
res[2, 1] = m[2, 1] * vZ
res[2, 2] = m[2, 2] * vZ
return res
}
/** Builds a scale 3 * 3 matrix created from 3 scalars.
*
* @param res resulting scale matrix.
* @param m Input matrix multiplied by this scale matrix.
* @param v Ratio of scaling for this axis.
*
* @see gtc_matrix_transform
* @see - scale(mat<3, 3, T, Q> const& m, T x, T y, T z)
* @see - scale(vec<3, T, Q> const& v)
* @see <a href="https://www.khronos.org/registry/OpenGL-Refpages/gl2.1/xhtml/glScale.xml">glScale man page</a>
*/
fun scale(res: Mat3, m: Mat3, v: Vec3): Mat3 = scale(res, m, v.x, v.y, v.z)
/** Builds a scale 3 * 3 matrix created from 3 scalars.
*
* @param m Input matrix multiplied by this scale matrix.
* @param vX Ratio of scaling for X axis.
* @param vY Ratio of scaling for Y axis.
* @param vZ Ratio of scaling for Z axis.
*
* @see gtc_matrix_transform
* @see - scale(mat<3, 3, T, Q> const& m, T x, T y, T z)
* @see - scale(vec<3, T, Q> const& v)
* @see <a href="https://www.khronos.org/registry/OpenGL-Refpages/gl2.1/xhtml/glScale.xml">glScale man page</a>
*/
fun scale(m: Mat3, vX: Float, vY: Float, vZ: Float): Mat3 = scale(Mat3(), m, vX, vY, vZ)
/** Builds a scale 3 * 3 matrix created from 3 scalars.
*
* @param m Input matrix multiplied by this scale matrix.
* @param v Ratio of scaling for this axis.
*
* @see gtc_matrix_transform
* @see - scale(mat<3, 3, T, Q> const& m, T x, T y, T z)
* @see - scale(vec<3, T, Q> const& v)
* @see <a href="https://www.khronos.org/registry/OpenGL-Refpages/gl2.1/xhtml/glScale.xml">glScale man page</a>
*/
fun scale(m: Mat3, v: Vec3): Mat3 = scale(Mat3(), m, v.x, v.y, v.z)
/** Builds a scale 3 * 3 matrix created from 3 scalars.
*
* @param res resulting scale matrix.
* @param m Input matrix multiplied by this scale matrix.
* @param vX Ratio of scaling for X axis.
* @param vY Ratio of scaling for Y axis.
* @param vZ Ratio of scaling for Z axis.
*
* @see gtc_matrix_transform
* @see - scale(mat<3, 3, T, Q> const& m, T x, T y, T z)
* @see - scale(vec<3, T, Q> const& v)
* @see <a href="https://www.khronos.org/registry/OpenGL-Refpages/gl2.1/xhtml/glScale.xml">glScale man page</a>
*/
fun scale(res: Mat3d, m: Mat3d, vX: Double, vY: Double, vZ: Double): Mat3d {
res[0, 0] = m[0, 0] * vX
res[0, 1] = m[0, 1] * vX
res[0, 2] = m[0, 2] * vX
res[1, 0] = m[1, 0] * vY
res[1, 1] = m[1, 1] * vY
res[1, 2] = m[1, 2] * vY
res[2, 0] = m[2, 0] * vZ
res[2, 1] = m[2, 1] * vZ
res[2, 2] = m[2, 2] * vZ
return res
}
/** Builds a scale 3 * 3 matrix created from 3 scalars.
*
* @param res resulting scale matrix.
* @param m Input matrix multiplied by this scale matrix.
* @param v Ratio of scaling for this axis.
*
* @see gtc_matrix_transform
* @see - scale(mat<3, 3, T, Q> const& m, T x, T y, T z)
* @see - scale(vec<3, T, Q> const& v)
* @see <a href="https://www.khronos.org/registry/OpenGL-Refpages/gl2.1/xhtml/glScale.xml">glScale man page</a>
*/
fun scale(res: Mat3d, m: Mat3d, v: Vec3d): Mat3d = scale(res, m, v.x, v.y, v.z)
/** Builds a scale 3 * 3 matrix created from 3 scalars.
*
* @param m Input matrix multiplied by this scale matrix.
* @param vX Ratio of scaling for X axis.
* @param vY Ratio of scaling for Y axis.
* @param vZ Ratio of scaling for Z axis.
*
* @see gtc_matrix_transform
* @see - scale(mat<3, 3, T, Q> const& m, T x, T y, T z)
* @see - scale(vec<3, T, Q> const& v)
* @see <a href="https://www.khronos.org/registry/OpenGL-Refpages/gl2.1/xhtml/glScale.xml">glScale man page</a>
*/
fun scale(m: Mat3d, vX: Double, vY: Double, vZ: Double): Mat3d = scale(Mat3d(), m, vX, vY, vZ)
/** Builds a scale 3 * 3 matrix created from 3 scalars.
*
* @param m Input matrix multiplied by this scale matrix.
* @param v Ratio of scaling for this axis.
*
* @see gtc_matrix_transform
* @see - scale(mat<3, 3, T, Q> const& m, T x, T y, T z)
* @see - scale(vec<3, T, Q> const& v)
* @see <a href="https://www.khronos.org/registry/OpenGL-Refpages/gl2.1/xhtml/glScale.xml">glScale man page</a>
*/
fun scale(m: Mat3d, v: Vec3d): Mat3d = scale(Mat3d(), m, v.x, v.y, v.z)
}
| 0
| null |
0
| 0
|
3d3aea6d420bace96ced057cddeca023129d7c41
| 11,566
|
glm
|
MIT License
|
app/src/main/java/dev/arweb/miweather/miWeatherWidget.kt
|
arwebSE
| 567,722,824
| false
|
{"Kotlin": 7002}
|
package dev.arweb.miweather
import android.app.PendingIntent
import android.appwidget.AppWidgetManager
import android.appwidget.AppWidgetProvider
import android.content.ComponentName
import android.content.Context
import android.content.Intent
import android.util.Log
import android.view.View
import android.widget.RemoteViews
import android.widget.Toast
import okhttp3.*
import org.json.JSONArray
import org.json.JSONObject
import org.json.JSONTokener
import java.io.IOException
import java.time.LocalDateTime
import kotlin.math.roundToInt
/**
* Implementation of App Widget functionality.
*/
class MiWeatherWidget : AppWidgetProvider() {
private var jsonData: JSONObject? = null
override fun onEnabled(context: Context) {
// Enter relevant functionality for when the first widget is created
Toast.makeText(context, "miWeather created", Toast.LENGTH_LONG).show()
updateWidgets(context)
}
override fun onUpdate(
context: Context,
appWidgetManager: AppWidgetManager,
appWidgetIds: IntArray
) {
// There may be multiple widgets active, so update all of them
for (appWidgetId in appWidgetIds) {
updateAppWidget(context, appWidgetManager, appWidgetId)
}
}
// update all widgets
private fun updateWidgets(context: Context) {
val manager = AppWidgetManager.getInstance(context)
val ids = manager.getAppWidgetIds(ComponentName(context, javaClass))
// update each widget
ids.forEach { id -> updateAppWidget(context, manager, id) }
}
private fun updateAppWidget(
context: Context,
appWidgetManager: AppWidgetManager,
appWidgetId: Int
) {
Log.d("MIWEATHER", "updating app widget")
//Toast.makeText(context, "Updating miWeather", Toast.LENGTH_LONG).show()
// Construct the RemoteViews object
val views = RemoteViews(context.packageName, R.layout.mi_weather_widget)
// launch pending intent to increase value stored in shared prefs
views.setOnClickPendingIntent(R.id.refreshButton, pendingIntent(context, "refresh"))
//views.setInt(R.id.loadingView, "setVisibility", View.VISIBLE) // make btn invis
showLoading(context)
apiCall {
// Setup current temp
val currentTemp = jsonData?.getJSONObject("current")?.getDouble("temp")?.roundToInt()
views.setTextViewText(R.id.cTempView, "$currentTemp\u2103")
// Setup min/max temp
val minTemp = jsonData?.getJSONArray("daily")?.getJSONObject(0)?.getJSONObject("temp")?.getDouble("min")?.roundToInt()
val maxTemp = jsonData?.getJSONArray("daily")?.getJSONObject(0)?.getJSONObject("temp")?.getDouble("max")?.roundToInt()
views.setTextViewText(R.id.minTempText, "$minTemp\u2103")
views.setTextViewText(R.id.maxTempText, "$maxTemp\u2103")
// Setup weather icon
val currentIcon = JSONObject(
JSONArray(
jsonData?.getJSONObject("current")?.getString("weather")
)[0].toString()
).getString("icon")
val weatherId: Int = context.resources.getIdentifier(
"weather_$currentIcon",
"drawable",
context.packageName
)
views.setImageViewResource(R.id.weatherIcon, weatherId)
//views.setInt(R.id.loadingView, "setVisibility", View.INVISIBLE) // make btn visible
// Instruct the widget manager to update the widget
appWidgetManager.updateAppWidget(appWidgetId, views)
}
}
private fun pendingIntent(context: Context?, action: String): PendingIntent? {
val intent = Intent(context, javaClass)
intent.action = action
// return pending intent
return PendingIntent.getBroadcast(
context, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_MUTABLE
)
}
private fun showLoading(context: Context) {
val views = RemoteViews(context.packageName, R.layout.mi_weather_widget)
views.setInt(R.id.loadingView, "setVisibility", View.VISIBLE) // make btn vis
}
private fun apiCall(callback: () -> Unit) {
//showLoading(context)
val apiUrl = "https://miel-api.arwebse.repl.co"
val city = "stockholm"
val verify = "5ecf486e3b8d878a4a87"
val freedom = false
val id = "android"
val url = "$apiUrl/weather?q=$city&verify=$verify&freedom=$freedom&id=$id";
val request = Request.Builder().url(url).build()
val okHttpClient = OkHttpClient()
okHttpClient.newCall(request).enqueue(object : Callback {
override fun onFailure(call: Call, e: IOException) {
e.printStackTrace()
}
override fun onResponse(call: Call, response: Response) {
response.use {
if (!response.isSuccessful) throw IOException("Unexpected code $response")
// Parse the JSON string into an object
val body = response.body!!.string()
jsonData = JSONTokener(body).nextValue() as JSONObject
callback()
}
}
})
}
override fun onReceive(context: Context?, intent: Intent?) {
super.onReceive(context, intent)
// On receive intent broadcast
val action = intent!!.action ?: ""
if (context != null && action == "refresh") {
val views = RemoteViews(context.packageName, R.layout.mi_weather_widget)
// launch pending intent to increase value stored in shared prefs
views.setOnClickPendingIntent(R.id.refreshButton, pendingIntent(context, "refresh"))
val cTime = LocalDateTime.now()
Log.d("MIWEATHER", "Time: $cTime")
updateWidgets(context)
}
}
}
| 0
|
Kotlin
|
0
| 0
|
baa995b93177e2ec65787e684dfde542dfc6a4bd
| 5,994
|
miWeather
|
MIT License
|
app/src/main/java/com/lttrung/dormitory/domain/data/network/impl/ContractRetrofitImpl.kt
|
lttrung2001
| 622,933,615
| false
| null |
package com.lttrung.dormitory.domain.data.network.impl
import com.lttrung.dormitory.domain.data.network.ContractNetwork
import com.lttrung.dormitory.domain.data.network.models.FetchRoomContractResponse
import com.lttrung.dormitory.domain.data.network.services.ContractService
import com.lttrung.dormitory.exceptions.FailedException
import com.lttrung.dormitory.utils.HttpStatusCodes
import io.reactivex.rxjava3.core.Single
import javax.inject.Inject
class ContractRetrofitImpl @Inject constructor(
private val service: ContractService
) : ContractNetwork {
override fun getRoomContract(): Single<FetchRoomContractResponse> {
return service.fetchRoomContract().map { response ->
if (response.isSuccessful) {
response.body()!!
} else {
throw FailedException("Get room contract failed.")
}
}
}
override fun registerRoom(roomId: Int): Single<Boolean> {
return service.registerRoom(roomId).map { response ->
if (response.isSuccessful) {
val isSuccess = response.body()!!
if (isSuccess) {
true
} else {
throw FailedException("Register room failed.")
}
} else {
throw FailedException("Register room failed.")
}
}
}
override fun cancelContract(): Single<Unit> {
return service.cancelContract().map { response ->
when (response.code()) {
HttpStatusCodes.OK -> { response.body()!! }
else -> {
throw FailedException("Cancel contract failed.")
}
}
}
}
override fun extendRoom(): Single<Unit> {
return service.extendRoom().map { response ->
when (response.code()) {
HttpStatusCodes.OK -> response.body()!!
else -> throw FailedException("Extend room failed.")
}
}
}
}
| 0
|
Kotlin
|
0
| 0
|
82a1fab3027ad106de61e7ff00c8331da227e92d
| 2,030
|
dormitory
|
MIT License
|
app/src/main/java/com/mexator/petfinder_client/di/DataModule.kt
|
Mexator
| 261,837,159
| false
| null |
package com.mexator.petfinder_client.di
import com.mexator.petfinder_client.data.remote.api_interaction.CookieHolder
import org.koin.dsl.module
val dataModule = module {
single { CookieHolder }
}
| 0
|
Kotlin
|
0
| 0
|
703ef76b8274b5776cbc69e931298a589cd131d2
| 201
|
Petfinder-mobile-client
|
MIT License
|
src/main/kotlin/org/elasticsearch4idea/service/ElasticsearchManager.kt
|
ergoz
| 286,516,221
| true
|
{"Kotlin": 235816}
|
/*
* 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 org.elasticsearch4idea.service
import com.intellij.openapi.Disposable
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.components.Service
import com.intellij.openapi.components.service
import com.intellij.openapi.project.Project
import com.intellij.openapi.ui.Messages
import com.intellij.util.EventDispatcher
import com.intellij.util.ui.UIUtil
import org.elasticsearch4idea.model.*
import org.elasticsearch4idea.rest.ElasticsearchClient
import org.elasticsearch4idea.rest.model.Index
import org.elasticsearch4idea.ui.ElasticsearchClustersListener
import java.util.concurrent.ConcurrentHashMap
@Service
class ElasticsearchManager(project: Project) : Disposable {
private val clusters: MutableMap<String, ElasticsearchCluster> = ConcurrentHashMap()
private val clients: MutableMap<String, ElasticsearchClient> = ConcurrentHashMap()
private val eventDispatcher: EventDispatcher<ElasticsearchClustersListener> =
EventDispatcher.create(ElasticsearchClustersListener::class.java)
private val elasticsearchConfiguration = project.service<ElasticsearchConfiguration>()
fun addClustersListener(listener: ElasticsearchClustersListener) {
eventDispatcher.addListener(listener)
}
fun removeClustersListener(listener: ElasticsearchClustersListener) {
eventDispatcher.removeListener(listener)
}
fun getClusters(): Collection<ElasticsearchCluster> {
return clusters.values
}
fun createAllClusters() {
elasticsearchConfiguration.getConfigurations().forEach {
val cluster = createOrUpdateCluster(it)
ApplicationManager.getApplication()
.invokeLater { eventDispatcher.multicaster.clusterAdded(cluster) }
}
}
fun prepareFetchCluster(clusterLabel: String): RequestExecution<*> {
val clusterConfiguration = elasticsearchConfiguration.getConfiguration(clusterLabel)
if (clusterConfiguration != null) {
return prepareFetchCluster(clusterConfiguration)
}
return RequestExecution.empty()
}
fun prepareAddCluster(clusterConfig: ClusterConfiguration): RequestExecution<*> {
return prepareFetchCluster(clusterConfig)
}
fun prepareChangeCluster(previousLabel: String, clusterConfig: ClusterConfiguration): RequestExecution<*> {
val isNewLabel = clusterConfig.label != previousLabel
if (isNewLabel) {
removeCluster(previousLabel)
}
return prepareFetchCluster(clusterConfig)
}
private fun prepareFetchCluster(clusterConfig: ClusterConfiguration): RequestExecution<*> {
val isNewCluster = !clusters.containsKey(clusterConfig.label)
elasticsearchConfiguration.putClusterConfiguration(clusterConfig)
val cluster = createOrUpdateCluster(clusterConfig)
val clusterStatsRequest = getClient(cluster).prepareGetClusterStats()
val indicesRequest = getClient(cluster).prepareGetIndices()
return RequestExecution(
execution = {
cluster.status = ElasticsearchCluster.Status.LOADING
if (isNewCluster) {
ApplicationManager.getApplication()
.invokeAndWait { eventDispatcher.multicaster.clusterAdded(cluster) }
} else {
ApplicationManager.getApplication()
.invokeAndWait { eventDispatcher.multicaster.clusterChanged(cluster) }
}
val clusterStatsFuture = clusterStatsRequest.executeOnPooledThread()
val indices = indicesRequest.execute()
val clusterStats = clusterStatsFuture.get()
cluster.apply {
clusterName = clusterStats.clusterName
healthStatus = clusterStats.status
}
mergeIndices(cluster, indices)
},
onAbort = {
clusterStatsRequest.abort()
indicesRequest.abort()
}
)
.onSuccess {
cluster.status = ElasticsearchCluster.Status.LOADED
}
.onError {
cluster.indices.clear()
cluster.status = ElasticsearchCluster.Status.NOT_LOADED
}
.finally { _, _ ->
ApplicationManager.getApplication()
.invokeAndWait { eventDispatcher.multicaster.clusterChanged(cluster) }
}
}
private fun mergeIndices(cluster: ElasticsearchCluster, indices: List<Index>) {
synchronized(cluster) {
val indexesByName = indices.associateBy { it.name }
cluster.indices.removeIf { !indexesByName.containsKey(it.name) }
val oldIndexesByName = cluster.indices.associateBy { it.name }
indices.forEach {
val index = if (oldIndexesByName.containsKey(it.name)) {
oldIndexesByName.getValue(it.name)
} else {
val index = ElasticsearchIndex(it.name)
cluster.addIndex(index)
index
}
index.apply {
healthStatus = it.health
status = it.status
this.cluster = cluster
}
}
}
}
private fun createOrUpdateCluster(configuration: ClusterConfiguration): ElasticsearchCluster {
clients.remove(configuration.label)?.close()
return clusters.getOrPut(configuration.label) { ElasticsearchCluster(configuration.label) }
.apply { host = configuration.url }
}
private fun prepareFetchIndices(cluster: ElasticsearchCluster): RequestExecution<*> {
cluster.status = ElasticsearchCluster.Status.NOT_LOADED
return getClient(cluster).prepareGetIndices()
.onSuccess {
mergeIndices(cluster, it)
cluster.status = ElasticsearchCluster.Status.LOADED
}
.onError {
cluster.indices.clear()
cluster.status = ElasticsearchCluster.Status.NOT_LOADED
}
.finally { _, _ ->
ApplicationManager.getApplication()
.invokeLater { eventDispatcher.multicaster.clusterChanged(cluster) }
}
}
fun removeCluster(label: String) {
elasticsearchConfiguration.removeClusterConfiguration(label)
val cluster = clusters.remove(label)!!
clients.remove(label)?.close()
ApplicationManager.getApplication()
.invokeLater { eventDispatcher.multicaster.clusterRemoved(cluster) }
}
fun prepareGetClusterInfo(cluster: ElasticsearchCluster): RequestExecution<ElasticsearchClusterInfo> {
return getClient(cluster).prepareGetClusterStats()
.map { ElasticsearchClusterInfo(it) }
}
fun prepareGetIndexInfo(index: ElasticsearchIndex): RequestExecution<ElasticsearchIndexInfo> {
val indexShortInfoRequest = getClient(index).prepareGetIndex(index.name)
val indexInfoRequest = getClient(index).prepareGetIndexInfo(index.name)
return RequestExecution(
execution = {
val indexShortInfoFuture = indexShortInfoRequest.executeOnPooledThread()
val indexInfo = indexInfoRequest.execute()
val indexShortInfo = indexShortInfoFuture.get()
ElasticsearchIndexInfo(indexShortInfo, indexInfo)
},
onAbort = {
indexShortInfoRequest.abort()
indexInfoRequest.abort()
}
)
}
fun prepareDeleteIndex(index: ElasticsearchIndex): RequestExecution<*> {
return getClient(index).prepareExecution(
Request(
host = index.cluster.host,
path = index.name,
method = Method.DELETE
)
)
.onError(::showErrorMessage)
.onSuccess {
showInfoMessage(it.content, "Index '${index.name}' deleted")
prepareFetchIndices(index.cluster).executeSafely()
}
}
fun prepareCreateIndex(
cluster: ElasticsearchCluster,
indexName: String,
numberOfShards: Int,
numberOfReplicas: Int
): RequestExecution<*> {
return getClient(cluster).prepareExecution(
Request(
host = cluster.host,
path = indexName,
method = Method.PUT,
body = """{
"settings" : {
"index" : {
"number_of_shards" : $numberOfShards,
"number_of_replicas" : $numberOfReplicas
}
}
}"""
)
)
.onError(::showErrorMessage)
.onSuccess {
showInfoMessage(it.content, "Index '$indexName' created")
prepareFetchIndices(cluster).executeSafely()
}
}
fun prepareCreateAlias(index: ElasticsearchIndex, alias: String): RequestExecution<*> {
return getClient(index).prepareExecution(
Request(
host = index.cluster.host,
path = "${index.name}/_alias/$alias",
method = Method.PUT
)
)
.onError(::showErrorMessage)
.onSuccess {
showInfoMessage(it.content, "Alias '$alias' created")
}
}
fun prepareRefreshIndex(index: ElasticsearchIndex): RequestExecution<*> {
return getClient(index).prepareExecution(
Request(
host = index.cluster.host,
path = "${index.name}/_refresh",
method = Method.POST
)
)
.onError(::showErrorMessage)
.onSuccess {
showInfoMessage(it.content, "Index '${index.name}' refreshed")
}
}
fun prepareFlushIndex(index: ElasticsearchIndex): RequestExecution<*> {
return getClient(index).prepareExecution(
Request(
host = index.cluster.host,
path = "${index.name}/_flush",
method = Method.POST
)
)
.onError(::showErrorMessage)
.onSuccess {
showInfoMessage(it.content, "Index '${index.name}' flushed")
}
}
fun prepareForceMergeIndex(
index: ElasticsearchIndex,
maxNumSegments: Int,
onlyExpungeDeletes: Boolean,
flush: Boolean
): RequestExecution<*> {
return getClient(index).prepareExecution(
Request(
host = index.cluster.host,
path = "${index.name}/_forcemerge?" +
"only_expunge_deletes=$onlyExpungeDeletes&max_num_segments=$maxNumSegments&flush=$flush",
method = Method.POST
)
)
.onError(::showErrorMessage)
.onSuccess {
showInfoMessage(it.content, "Force merge '${index.name}' performed")
}
}
fun prepareCloseIndex(index: ElasticsearchIndex): RequestExecution<*> {
return getClient(index).prepareExecution(
Request(
host = index.cluster.host,
path = "${index.name}/_close",
method = Method.POST
)
)
.onError(::showErrorMessage)
.onSuccess {
showInfoMessage(it.content, "Index '${index.name}' closed")
prepareFetchIndices(index.cluster).executeSafely()
}
}
fun prepareOpenIndex(index: ElasticsearchIndex): RequestExecution<*> {
return getClient(index).prepareExecution(
Request(
host = index.cluster.host,
path = "${index.name}/_open",
method = Method.POST
)
)
.onError(::showErrorMessage)
.onSuccess {
showInfoMessage(it.content, "Index '${index.name}' opened")
prepareFetchIndices(index.cluster).executeSafely()
}
}
fun prepareTestConnection(configuration: ClusterConfiguration): RequestExecution<*> {
val elasticsearchClient = ElasticsearchClient(configuration)
return elasticsearchClient.prepareTestConnection()
.finally { _, _ ->
elasticsearchClient.close()
}
}
fun prepareExecuteRequest(request: Request, cluster: ElasticsearchCluster): RequestExecution<Response> {
return getClient(cluster).prepareExecution(request, false)
}
private fun getClient(index: ElasticsearchIndex): ElasticsearchClient {
return getClient(index.cluster)
}
private fun getClient(cluster: ElasticsearchCluster): ElasticsearchClient {
return getClient(cluster.label)
}
@Synchronized
private fun getClient(label: String): ElasticsearchClient {
if (!clients.contains(label)) {
clients[label] = ElasticsearchClient(elasticsearchConfiguration.getConfiguration(label)!!)
}
return clients[label]!!
}
private fun showErrorMessage(e: Exception) {
UIUtil.invokeLaterIfNeeded {
Messages.showErrorDialog(e.message ?: e.toString(), "Error")
}
}
private fun showInfoMessage(message: String, title: String) {
UIUtil.invokeLaterIfNeeded {
Messages.showInfoMessage(message, title)
}
}
override fun dispose() {
clients.values.forEach { it.close() }
}
}
| 0
| null |
1
| 0
|
b7b923e4f984b53ab00acdc7890998c4c2e7aada
| 14,255
|
elasticsearch4idea
|
Apache License 2.0
|
app/src/main/java/ru/glindaqu/ejournal/screens/students/Add.kt
|
glindaqu
| 789,473,966
| false
|
{"Kotlin": 175382}
|
package ru.glindaqu.ejournal.screens.students
import android.annotation.SuppressLint
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
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.shape.RoundedCornerShape
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Check
import androidx.compose.material.icons.filled.KeyboardArrowLeft
import androidx.compose.material3.ExtendedFloatingActionButton
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Scaffold
import androidx.compose.material3.Text
import androidx.compose.material3.TextField
import androidx.compose.material3.TextFieldDefaults
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.draw.alpha
import androidx.compose.ui.draw.clip
import androidx.compose.ui.draw.shadow
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.text.input.TextFieldValue
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import ru.glindaqu.ejournal.DEFAULT_CORNER_CLIP
import ru.glindaqu.ejournal.DEFAULT_HORIZONTAL_PADDING
import ru.glindaqu.ejournal.viewModel.implementation.StudentsViewModel
@Suppress("ktlint:standard:function-naming")
@SuppressLint("UnusedMaterial3ScaffoldPaddingParameter")
@Composable
fun AddStudent(viewModel: StudentsViewModel) {
var name by remember { mutableStateOf(TextFieldValue("")) }
var lastname by remember { mutableStateOf(TextFieldValue("")) }
var patronymic by remember { mutableStateOf(TextFieldValue("")) }
Scaffold(topBar = {
Row(
modifier =
Modifier
.fillMaxWidth()
.clip(
RoundedCornerShape(
bottomStart = DEFAULT_CORNER_CLIP,
bottomEnd = DEFAULT_CORNER_CLIP,
),
).background(MaterialTheme.colorScheme.onBackground),
horizontalArrangement = Arrangement.SpaceBetween,
verticalAlignment = Alignment.CenterVertically,
) {
IconButton(onClick = { viewModel.uiState.value = StudentsUIState.VIEW }) {
Icon(
imageVector = Icons.Default.KeyboardArrowLeft,
contentDescription = null,
tint = Color.Black,
modifier = Modifier.size(30.dp),
)
}
ExtendedFloatingActionButton(
onClick = {
viewModel.insert(
name = name.text,
lastname = lastname.text,
patronymic = patronymic.text,
)
viewModel.uiState.value = StudentsUIState.VIEW
},
modifier =
Modifier
.padding(end = DEFAULT_HORIZONTAL_PADDING / 2)
.padding(10.dp)
.shadow(
elevation = 7.dp,
shape = RoundedCornerShape(DEFAULT_CORNER_CLIP),
clip = true,
ambientColor = Color.Black,
spotColor = Color.Black,
).clip(RoundedCornerShape(DEFAULT_CORNER_CLIP)),
shape = RoundedCornerShape(DEFAULT_CORNER_CLIP),
containerColor = MaterialTheme.colorScheme.primary,
) {
Row(
verticalAlignment = Alignment.CenterVertically,
horizontalArrangement = Arrangement.spacedBy(12.dp),
) {
Text(text = "Сохранить", fontSize = 16.sp)
Icon(
imageVector = Icons.Default.Check,
contentDescription = null,
)
}
}
}
}) {
Column(
horizontalAlignment = Alignment.CenterHorizontally,
modifier =
Modifier
.padding(it)
.padding(top = 10.dp)
.fillMaxSize()
.background(MaterialTheme.colorScheme.background),
verticalArrangement = Arrangement.Center,
) {
Column(verticalArrangement = Arrangement.spacedBy(7.dp)) {
StudentTextField(
value = lastname,
placeholderText = "Фамилия студента",
) { value -> lastname = value }
StudentTextField(value = name, placeholderText = "Имя студента") { value ->
name = value
}
StudentTextField(
value = patronymic,
placeholderText = "Отчество студента",
) { value -> patronymic = value }
}
}
}
}
@Suppress("ktlint:standard:function-naming")
@Composable
internal fun StudentTextField(
value: TextFieldValue,
placeholderText: String,
onValueChange: (TextFieldValue) -> Unit,
) {
TextField(
value = value,
onValueChange = { onValueChange(it) },
placeholder = {
Text(
text = placeholderText,
color = Color.Black,
modifier = Modifier.alpha(0.2f),
)
},
modifier =
Modifier
.clip(RoundedCornerShape(DEFAULT_CORNER_CLIP))
.background(MaterialTheme.colorScheme.onBackground),
colors =
TextFieldDefaults.colors(
unfocusedContainerColor = Color.White,
unfocusedTextColor = Color.Black,
focusedContainerColor = Color.White,
focusedTextColor = Color.Black,
),
maxLines = 1,
singleLine = true,
shape = RoundedCornerShape(DEFAULT_CORNER_CLIP),
)
}
| 0
|
Kotlin
|
0
| 0
|
78468c973531103ecdedf9245316d584cec1b765
| 6,610
|
EJournal
|
MIT License
|
app/src/main/java/com/example/inventory/screen/addinventoryitem/AddInventoryItemState.kt
|
nicolegeorgieva
| 702,417,696
| false
|
{"Kotlin": 71335}
|
package com.example.inventory.screen.addinventoryitem
data class AddInventoryItemState(
val name: String?,
val quantity: String?,
val minQuantityTarget: String?,
val category: String?,
val description: String?,
val imagePath: String?
)
| 0
|
Kotlin
|
0
| 1
|
263cb613a6b39892f36298884810c2f9b3237857
| 260
|
inventory
|
MIT License
|
basick/src/main/java/com/mozhimen/basick/utilk/exts/ExtsViewImage.kt
|
mozhimen
| 353,952,154
| false
| null |
package com.mozhimen.basick.utilk.exts
import android.graphics.drawable.Drawable
import android.widget.ImageView
import com.mozhimen.basick.utilk.view.UtilKViewImage
/**
* @ClassName ExtsKViewImage
* @Description TODO
* @Author mozhimen / <NAME>
* @Date 2022/11/6 14:47
* @Version 1.0
*/
/**
* 自适应图片
* @receiver ImageView
* @param drawable Drawable
*/
fun ImageView.fitImage(
drawable: Drawable
) {
UtilKViewImage.fitImage(this, drawable)
}
| 0
|
Kotlin
|
0
| 2
|
5077b41303c564a4f7acd8e7df03133ebf1e04f2
| 460
|
SwiftKit
|
Apache License 2.0
|
serialization/src/test/kotlin/io/github/airflux/serialization/dsl/writer/array/item/specification/ArrayNullableItemSpecTest.kt
|
airflux
| 336,002,943
| false
| null |
/*
* Copyright 2021-2022 <NAME>.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.github.airflux.serialization.dsl.writer.array.item.specification
import io.github.airflux.serialization.common.DummyWriter
import io.github.airflux.serialization.core.location.Location
import io.github.airflux.serialization.core.value.StringNode
import io.github.airflux.serialization.core.writer.Writer
import io.github.airflux.serialization.core.writer.env.WriterEnv
import io.kotest.core.spec.style.FreeSpec
import io.kotest.matchers.nulls.shouldBeNull
import io.kotest.matchers.shouldBe
internal class ArrayNullableItemSpecTest : FreeSpec() {
companion object {
private const val ITEM_VALUE = "value"
private val ENV = WriterEnv(options = Unit)
private val CONTEXT = Unit
private val LOCATION = Location.empty
}
init {
"The ArrayItemSpec#Nullable type" - {
"when created the instance of a spec of the nullable item" - {
val writer: Writer<Unit, Unit, String> = DummyWriter { StringNode(it) }
val spec = nullable(writer = writer)
"then the instance should contain the writer passed during initialization" {
spec.writer shouldBe writer
}
}
"when the filter was added to the spec" - {
val writer: Writer<Unit, Unit, String> = DummyWriter { StringNode(it) }
val spec = nullable(writer = writer)
val specWithFilter = spec.filter { _, _, _, value -> value.isNotEmpty() }
"when passing a value that satisfies the predicate for filtering" - {
val result = specWithFilter.writer.write(ENV, CONTEXT, LOCATION, ITEM_VALUE)
"then the not null value should be returned" {
result shouldBe StringNode(ITEM_VALUE)
}
}
"when passing a value that does not satisfy the filter predicate" - {
val result = specWithFilter.writer.write(ENV, CONTEXT, LOCATION, "")
"then the null value should be returned" {
result.shouldBeNull()
}
}
}
}
}
}
| 0
|
Kotlin
|
3
| 3
|
9dfcfe4ec288e27f150beeef12dff45f131d0805
| 2,821
|
airflux-serialization
|
Apache License 2.0
|
wgpu4k/src/jvmMain/kotlin/io.ygdrasil.wgpu/RenderPassEncoder.jvm.kt
|
wgpu4k
| 773,068,055
| false
|
{"Kotlin": 1190676, "HTML": 1638, "Dockerfile": 1039, "Shell": 308}
|
package io.ygdrasil.wgpu
import io.ygdrasil.wgpu.internal.jvm.confined
import io.ygdrasil.wgpu.internal.jvm.panama.wgpu_h
import io.ygdrasil.wgpu.internal.jvm.toPointerArray
import java.lang.foreign.MemorySegment
actual class RenderPassEncoder(private val handler: MemorySegment) {
actual fun end() {
wgpu_h.wgpuRenderPassEncoderEnd(handler)
close()
}
actual fun setPipeline(renderPipeline: RenderPipeline) {
wgpu_h.wgpuRenderPassEncoderSetPipeline(handler, renderPipeline.handler)
}
actual fun draw(
vertexCount: GPUSize32,
instanceCount: GPUSize32,
firstVertex: GPUSize32,
firstInstance: GPUSize32
) {
wgpu_h.wgpuRenderPassEncoderDraw(handler, vertexCount, instanceCount, firstVertex, firstInstance)
}
actual fun setBindGroup(index: Int, bindGroup: BindGroup) {
wgpu_h.wgpuRenderPassEncoderSetBindGroup(
handler,
index,
bindGroup.handler,
0L,
MemorySegment.NULL
)
}
actual fun setVertexBuffer(slot: Int, buffer: Buffer) {
wgpu_h.wgpuRenderPassEncoderSetVertexBuffer(
handler,
slot,
buffer.handler,
0L,
buffer.size
)
}
actual fun setIndexBuffer(buffer: Buffer, indexFormat: IndexFormat, offset: GPUSize64, size: GPUSize64) {
wgpu_h.wgpuRenderPassEncoderSetIndexBuffer(handler, buffer.handler, indexFormat.value, offset, size)
}
actual fun executeBundles(bundles: List<RenderBundle>) = confined { arena ->
wgpu_h.wgpuRenderPassEncoderExecuteBundles(
handler,
bundles.size.toLong(),
bundles.map { it.handler }.toPointerArray(arena)
)
}
private fun close() {
wgpu_h.wgpuRenderPassEncoderRelease(handler)
}
}
| 7
|
Kotlin
|
6
| 41
|
822c304afaa72411ae42e86f20c7b5c62b5f9815
| 1,867
|
wgpu4k
|
MIT License
|
wrappers/react-native/android/src/main/java/com/mattrglobalpairingcryptorn/PairingCryptoRnPackage.kt
|
mattrglobal
| 329,755,968
| false
|
{"Rust": 632562, "TypeScript": 143367, "Objective-C": 91752, "Java": 50613, "C": 27696, "JavaScript": 16120, "Shell": 14680, "Kotlin": 13355, "C++": 7021, "Ruby": 3914, "Objective-C++": 3660, "Makefile": 3648, "Swift": 67}
|
package com.mattrglobalpairingcryptorn
import com.facebook.react.ReactPackage
import com.facebook.react.bridge.NativeModule
import com.facebook.react.bridge.ReactApplicationContext
import com.facebook.react.uimanager.ViewManager
class PairingCryptoRnPackage : ReactPackage {
override fun createNativeModules(reactContext: ReactApplicationContext): List<NativeModule> {
return listOf(PairingCryptoRnModule(reactContext))
}
override fun createViewManagers(reactContext: ReactApplicationContext): List<ViewManager<*, *>> {
return emptyList()
}
}
| 11
|
Rust
|
2
| 8
|
b9aa7d1e025e87f9638a780d1422e8c56f43afa4
| 578
|
pairing_crypto
|
Apache License 2.0
|
app/src/main/kotlin/com/mukul/jan/primerandroid/flavor/FlavorContainer.kt
|
Mukuljangir372
| 600,396,968
| false
| null |
package com.mukul.jan.primerandroid.flavor
import android.app.Activity
import com.mukul.jan.primerandroid.BuildConfig
data class Flavor(
val name: String,
val rootEntry: String,
)
class FlavorContainer {
private val base = "com.mukul.jan.primer.flavor"
private val flavors = listOf(
Flavor(name = "full", rootEntry = "$base.full.RootEntry"),
Flavor(name = "login", rootEntry = "$base.login.RootEntry"),
Flavor(name = "onboarding", rootEntry = "$base.onboarding.RootEntry"),
Flavor(name = "serverList", rootEntry = "$base.server.list.RootEntry"),
Flavor(name = "fileList", rootEntry = "$base.file.list.RootEntry"),
Flavor(name = "friendList", rootEntry = "$base.friend.list.RootEntry"),
Flavor(name = "notificationList", rootEntry = "$base.notification.list.RootEntry"),
Flavor(name = "settings", rootEntry = "$base.settings.RootEntry"),
)
fun startFlavorEntry(activity: Activity) {
val buildFlavor = BuildConfig.FLAVOR
val actualFlavor = buildFlavor.removePrefix("dev").removePrefix("prod")
val flavor = flavors.first {
it.name.contains(actualFlavor, ignoreCase = true)
}
val clazz = Class.forName(flavor.rootEntry)
val clazzConstructor = clazz.getConstructor(Activity::class.java)
val obj = clazzConstructor.newInstance(activity)
val entryMethod = clazz.getMethod("enter")
entryMethod.invoke(obj)
}
}
| 0
|
Kotlin
|
4
| 8
|
5135cc81e1bca2c380460694779d5c343de4ea18
| 1,482
|
Primer-Android
|
Apache License 2.0
|
src/test/kotlin/io/wusa/InfoTest.kt
|
ilovemilk
| 169,864,707
| false
| null |
package io.wusa
import io.mockk.every
import io.mockk.mockkObject
import io.mockk.unmockkObject
import io.wusa.exception.NoValidSemverTagFoundException
import io.wusa.extension.SemverGitPluginExtension
import org.gradle.api.GradleException
import org.gradle.api.Project
import org.gradle.testfixtures.ProjectBuilder
import org.junit.jupiter.api.*
@TestInstance(TestInstance.Lifecycle.PER_CLASS)
class InfoTest {
private lateinit var project: Project
private lateinit var semverGitPluginExtension: SemverGitPluginExtension
@BeforeEach
internal fun setUp() {
project = ProjectBuilder.builder().build()
project.plugins.apply(SemverGitPlugin::class.java)
semverGitPluginExtension = project.extensions.getByType(SemverGitPluginExtension::class.java)
mockkObject(GitService)
}
@AfterEach
internal fun tearDown() {
unmockkObject(GitService)
semverGitPluginExtension.tagPrefix = ""
}
@Test
fun `get dirty`() {
val info = Info(project)
every { GitService.isDirty(project = any()) } returns true
Assertions.assertEquals(true, info.dirty)
}
@Test
fun `get last tag`() {
val info = Info(project)
every { GitService.lastTag(project = any(), tagPrefix = any()) } returns "0.1.0"
Assertions.assertEquals("0.1.0", info.lastTag)
}
@Test
fun `get current tag`() {
val info = Info(project)
every { GitService.currentTag(project = any()) } returns "0.1.0"
Assertions.assertEquals("0.1.0", info.tag)
}
@Test
fun `get last tag with prefix`() {
semverGitPluginExtension.tagPrefix = "prj_"
val info = Info(project)
every { GitService.lastTag(project = any(), tagPrefix = any()) } returns "prj_0.1.0"
Assertions.assertEquals("prj_0.1.0", info.lastTag)
}
@Test
fun `get current tag with prefix`() {
semverGitPluginExtension.tagPrefix = "prj_"
val info = Info(project)
every { GitService.currentTag(project = any()) } returns "prj_0.1.0"
Assertions.assertEquals("prj_0.1.0", info.tag)
}
@Test
fun `get short commit`() {
val info = Info(project)
every { GitService.currentCommit(project = any(), isShort = true) } returns "1234567"
Assertions.assertEquals("1234567", info.shortCommit)
}
@Test
fun `get commit`() {
val info = Info(project)
every { GitService.currentCommit(project = any(), isShort = false) } returns "123456789"
Assertions.assertEquals("123456789", info.commit)
}
@Test
fun `get branch`() {
val project = project
val info = Info(project)
Assertions.assertEquals(Branch(project), info.branch)
}
@Test
fun `get version`() {
val project = project
val info = Info(project)
every { GitService.currentTag(project = any()) } returns "0.1.0"
Assertions.assertEquals("Version(major=0, minor=1, patch=0, prerelease=, build=, suffix=null)", info.version.toString())
}
@Test
fun `get version with lightweight tag`() {
val project = project
val info = Info(project)
every { GitService.currentTag(project = any(), tagType = TagType.LIGHTWEIGHT) } returns "0.1.0"
Assertions.assertEquals("Version(major=0, minor=1, patch=0, prerelease=, build=, suffix=null)", info.version.toString())
}
@Test
fun `current version is tagged with tag prefix`() {
semverGitPluginExtension.tagPrefix = "prj_"
val info = Info(project)
every { GitService.currentTag(project = any()) } returns "prj_0.1.0"
Assertions.assertEquals("Version(major=0, minor=1, patch=0, prerelease=, build=, suffix=null)", info.version.toString())
}
@Test
fun `current version has no tag with tag prefix`() {
semverGitPluginExtension.tagPrefix = "prj_"
val info = Info(project)
every { GitService.lastTag(project = any(), tagPrefix = any()) } returns "prj_0.1.0"
Assertions.assertEquals("Version(major=0, minor=2, patch=0, prerelease=, build=, suffix=null)", info.version.toString())
}
@Test
fun `current version has not tag with tag prefix`() {
val info = Info(project)
every { GitService.currentTag(project = any()) } returns "prj_0.1.0"
Assertions.assertThrows(NoValidSemverTagFoundException::class.java ) {
info.version
}
}
@Test
fun `last version has not tag with tag prefix`() {
val info = Info(project)
every { GitService.lastTag(project = any(), tagPrefix = any()) } returns "prj_0.1.0"
Assertions.assertThrows(GradleException::class.java ) {
info.version
}
}
}
| 17
|
Kotlin
|
12
| 42
|
32961344bb8b196fe63fd2660d52b4622111f0b0
| 4,790
|
semver-git-plugin
|
MIT License
|
src/test/kotlin/io/wusa/InfoTest.kt
|
ilovemilk
| 169,864,707
| false
| null |
package io.wusa
import io.mockk.every
import io.mockk.mockkObject
import io.mockk.unmockkObject
import io.wusa.exception.NoValidSemverTagFoundException
import io.wusa.extension.SemverGitPluginExtension
import org.gradle.api.GradleException
import org.gradle.api.Project
import org.gradle.testfixtures.ProjectBuilder
import org.junit.jupiter.api.*
@TestInstance(TestInstance.Lifecycle.PER_CLASS)
class InfoTest {
private lateinit var project: Project
private lateinit var semverGitPluginExtension: SemverGitPluginExtension
@BeforeEach
internal fun setUp() {
project = ProjectBuilder.builder().build()
project.plugins.apply(SemverGitPlugin::class.java)
semverGitPluginExtension = project.extensions.getByType(SemverGitPluginExtension::class.java)
mockkObject(GitService)
}
@AfterEach
internal fun tearDown() {
unmockkObject(GitService)
semverGitPluginExtension.tagPrefix = ""
}
@Test
fun `get dirty`() {
val info = Info(project)
every { GitService.isDirty(project = any()) } returns true
Assertions.assertEquals(true, info.dirty)
}
@Test
fun `get last tag`() {
val info = Info(project)
every { GitService.lastTag(project = any(), tagPrefix = any()) } returns "0.1.0"
Assertions.assertEquals("0.1.0", info.lastTag)
}
@Test
fun `get current tag`() {
val info = Info(project)
every { GitService.currentTag(project = any()) } returns "0.1.0"
Assertions.assertEquals("0.1.0", info.tag)
}
@Test
fun `get last tag with prefix`() {
semverGitPluginExtension.tagPrefix = "prj_"
val info = Info(project)
every { GitService.lastTag(project = any(), tagPrefix = any()) } returns "prj_0.1.0"
Assertions.assertEquals("prj_0.1.0", info.lastTag)
}
@Test
fun `get current tag with prefix`() {
semverGitPluginExtension.tagPrefix = "prj_"
val info = Info(project)
every { GitService.currentTag(project = any()) } returns "prj_0.1.0"
Assertions.assertEquals("prj_0.1.0", info.tag)
}
@Test
fun `get short commit`() {
val info = Info(project)
every { GitService.currentCommit(project = any(), isShort = true) } returns "1234567"
Assertions.assertEquals("1234567", info.shortCommit)
}
@Test
fun `get commit`() {
val info = Info(project)
every { GitService.currentCommit(project = any(), isShort = false) } returns "123456789"
Assertions.assertEquals("123456789", info.commit)
}
@Test
fun `get branch`() {
val project = project
val info = Info(project)
Assertions.assertEquals(Branch(project), info.branch)
}
@Test
fun `get version`() {
val project = project
val info = Info(project)
every { GitService.currentTag(project = any()) } returns "0.1.0"
Assertions.assertEquals("Version(major=0, minor=1, patch=0, prerelease=, build=, suffix=null)", info.version.toString())
}
@Test
fun `get version with lightweight tag`() {
val project = project
val info = Info(project)
every { GitService.currentTag(project = any(), tagType = TagType.LIGHTWEIGHT) } returns "0.1.0"
Assertions.assertEquals("Version(major=0, minor=1, patch=0, prerelease=, build=, suffix=null)", info.version.toString())
}
@Test
fun `current version is tagged with tag prefix`() {
semverGitPluginExtension.tagPrefix = "prj_"
val info = Info(project)
every { GitService.currentTag(project = any()) } returns "prj_0.1.0"
Assertions.assertEquals("Version(major=0, minor=1, patch=0, prerelease=, build=, suffix=null)", info.version.toString())
}
@Test
fun `current version has no tag with tag prefix`() {
semverGitPluginExtension.tagPrefix = "prj_"
val info = Info(project)
every { GitService.lastTag(project = any(), tagPrefix = any()) } returns "prj_0.1.0"
Assertions.assertEquals("Version(major=0, minor=2, patch=0, prerelease=, build=, suffix=null)", info.version.toString())
}
@Test
fun `current version has not tag with tag prefix`() {
val info = Info(project)
every { GitService.currentTag(project = any()) } returns "prj_0.1.0"
Assertions.assertThrows(NoValidSemverTagFoundException::class.java ) {
info.version
}
}
@Test
fun `last version has not tag with tag prefix`() {
val info = Info(project)
every { GitService.lastTag(project = any(), tagPrefix = any()) } returns "prj_0.1.0"
Assertions.assertThrows(GradleException::class.java ) {
info.version
}
}
}
| 17
|
Kotlin
|
12
| 42
|
32961344bb8b196fe63fd2660d52b4622111f0b0
| 4,790
|
semver-git-plugin
|
MIT License
|
rounded/src/commonMain/kotlin/me/localx/icons/rounded/filled/MailboxEnvelope.kt
|
localhostov
| 808,861,591
| false
|
{"Kotlin": 79430321, "HTML": 331, "CSS": 102}
|
package me.localx.icons.rounded.filled
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.PathFillType.Companion.NonZero
import androidx.compose.ui.graphics.SolidColor
import androidx.compose.ui.graphics.StrokeCap.Companion.Butt
import androidx.compose.ui.graphics.StrokeJoin.Companion.Miter
import androidx.compose.ui.graphics.vector.ImageVector
import androidx.compose.ui.graphics.vector.ImageVector.Builder
import androidx.compose.ui.graphics.vector.path
import androidx.compose.ui.unit.dp
import me.localx.icons.rounded.Icons
public val Icons.Filled.MailboxEnvelope: ImageVector
get() {
if (_mailboxEnvelope != null) {
return _mailboxEnvelope!!
}
_mailboxEnvelope = Builder(name = "MailboxEnvelope", defaultWidth = 24.0.dp, defaultHeight =
24.0.dp, viewportWidth = 24.0f, viewportHeight = 24.0f).apply {
path(fill = SolidColor(Color(0xFF000000)), stroke = null, strokeLineWidth = 0.0f,
strokeLineCap = Butt, strokeLineJoin = Miter, strokeLineMiter = 4.0f,
pathFillType = NonZero) {
moveToRelative(1.622f, 15.038f)
curveToRelative(0.123f, -0.023f, 0.248f, -0.038f, 0.378f, -0.038f)
horizontalLineToRelative(8.0f)
curveToRelative(0.129f, 0.0f, 0.255f, 0.015f, 0.377f, 0.038f)
lineToRelative(-3.67f, 3.67f)
curveToRelative(-0.378f, 0.377f, -1.036f, 0.377f, -1.414f, 0.0f)
lineToRelative(-3.671f, -3.67f)
close()
moveTo(8.121f, 20.122f)
curveToRelative(-0.585f, 0.585f, -1.353f, 0.877f, -2.121f, 0.877f)
reflectiveCurveToRelative(-1.536f, -0.292f, -2.121f, -0.877f)
lineTo(0.115f, 16.359f)
curveToRelative(-0.069f, 0.202f, -0.115f, 0.416f, -0.115f, 0.641f)
verticalLineToRelative(5.0f)
curveToRelative(0.0f, 1.105f, 0.895f, 2.0f, 2.0f, 2.0f)
horizontalLineToRelative(8.0f)
curveToRelative(1.105f, 0.0f, 2.0f, -0.895f, 2.0f, -2.0f)
verticalLineToRelative(-5.0f)
curveToRelative(0.0f, -0.226f, -0.046f, -0.439f, -0.115f, -0.642f)
lineToRelative(-3.764f, 3.764f)
close()
moveTo(0.0f, 13.557f)
lineTo(0.0f, 5.223f)
curveTo(0.0f, 2.613f, 1.903f, 0.278f, 4.5f, 0.024f)
curveToRelative(2.98f, -0.291f, 5.5f, 2.054f, 5.5f, 4.976f)
verticalLineToRelative(8.0f)
lineTo(1.999f, 13.0f)
curveToRelative(-0.731f, 0.0f, -1.409f, 0.212f, -1.999f, 0.557f)
close()
moveTo(3.0f, 7.0f)
curveToRelative(0.0f, 0.552f, 0.448f, 1.0f, 1.0f, 1.0f)
horizontalLineToRelative(2.0f)
curveToRelative(0.552f, 0.0f, 1.0f, -0.448f, 1.0f, -1.0f)
reflectiveCurveToRelative(-0.448f, -1.0f, -1.0f, -1.0f)
horizontalLineToRelative(-2.0f)
curveToRelative(-0.552f, 0.0f, -1.0f, 0.448f, -1.0f, 1.0f)
close()
moveTo(24.0f, 6.0f)
verticalLineToRelative(8.5f)
curveToRelative(0.0f, 1.933f, -1.567f, 3.5f, -3.5f, 3.5f)
horizontalLineToRelative(-6.5f)
verticalLineToRelative(-1.0f)
curveToRelative(0.0f, -1.474f, -0.81f, -2.75f, -2.0f, -3.444f)
lineTo(12.0f, 5.0f)
curveToRelative(0.0f, -1.957f, -0.807f, -3.729f, -2.106f, -5.0f)
horizontalLineToRelative(8.106f)
curveToRelative(3.314f, 0.0f, 6.0f, 2.686f, 6.0f, 6.0f)
close()
moveTo(21.0f, 7.0f)
curveToRelative(0.0f, -0.552f, -0.447f, -1.0f, -1.0f, -1.0f)
horizontalLineToRelative(-4.0f)
curveToRelative(-0.553f, 0.0f, -1.0f, 0.448f, -1.0f, 1.0f)
reflectiveCurveToRelative(0.447f, 1.0f, 1.0f, 1.0f)
horizontalLineToRelative(3.0f)
verticalLineToRelative(1.0f)
curveToRelative(0.0f, 0.552f, 0.447f, 1.0f, 1.0f, 1.0f)
reflectiveCurveToRelative(1.0f, -0.448f, 1.0f, -1.0f)
verticalLineToRelative(-2.0f)
close()
}
}
.build()
return _mailboxEnvelope!!
}
private var _mailboxEnvelope: ImageVector? = null
| 1
|
Kotlin
|
0
| 5
|
cbd8b510fca0e5e40e95498834f23ec73cc8f245
| 4,525
|
icons
|
MIT License
|
bidappAds/src/commonMain/kotlin/io/bidapp/kmp/BIDRewarded.kt
|
bidapphub
| 787,934,281
| false
|
{"Kotlin": 35918}
|
package io.bidapp.kmp
public expect class BIDRewarded(activity : Any?){
public fun showRewarded(applicationActivity: Any?, bidShowDelegate : BIDFullShow?)
public fun setLoadDelegate(bidLoadDelegate: BIDFullLoad?)
public fun setAutoLoad(isAutoLoad: Boolean)
public fun isInterstitialReady(): Boolean
public fun load()
public fun destroy()
}
| 0
|
Kotlin
|
0
| 1
|
f8ef4f6bcc8d4dba6009f267ff21e4c3b321b132
| 366
|
bidapp-kotlin-multiplatform-plugin
|
MIT License
|
shared/src/commonMain/kotlin/TextBuilder.kt
|
fcopardo
| 643,314,635
| false
| null |
import androidx.compose.material.LocalTextStyle
import androidx.compose.material.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.text.TextLayoutResult
import androidx.compose.ui.text.TextStyle
import androidx.compose.ui.text.font.FontFamily
import androidx.compose.ui.text.font.FontStyle
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.text.style.TextDecoration
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.unit.TextUnit
class TextBuilder : composable<TextBuilder> {
companion object : BuilderCompanion<TextBuilder>() {
override fun createBuilder(id: String): TextBuilder {
return TextBuilder(id)
}
}
private var text: String = ""
private var color: Color = Color.Unspecified
private var fontSize: TextUnit = TextUnit.Unspecified
private var fontStyle: FontStyle? = null
private var fontWeight: FontWeight? = null
private var fontFamily: FontFamily? = null
private var letterSpacing: TextUnit = TextUnit.Unspecified
private var textDecoration: TextDecoration? = null
private var textAlign: TextAlign? = null
private var lineHeight: TextUnit = TextUnit.Unspecified
private var overflow: TextOverflow = TextOverflow.Clip
private var softWrap: Boolean = true
private var maxLines: Int = Int.MAX_VALUE
private var minLines: Int = 1
private var onTextLayout: (TextLayoutResult) -> Unit = {}
private constructor(id : String) : super(id)
fun text(text : String) : TextBuilder {
this.text = text
return this
}
fun color(newColor : Color): TextBuilder {
color = newColor
return this
}
fun fontSize(fontSize : TextUnit): TextBuilder {
this.fontSize = fontSize
return this
}
fun fontStyle(fontStyle : FontStyle): TextBuilder {
this.fontStyle = fontStyle
return this
}
fun fontFamily(fontFamily: FontFamily): TextBuilder {
this.fontFamily = fontFamily
return this
}
fun letterSpacing(letterSpacing : TextUnit): TextBuilder {
this.letterSpacing = letterSpacing
return this
}
fun textDecoration(textDecoration: TextDecoration): TextBuilder {
this.textDecoration = textDecoration
return this
}
fun textAlign(textAlign: TextAlign): TextBuilder {
this.textAlign = textAlign
return this
}
fun lineHeight(lineHeight : TextUnit): TextBuilder {
this.lineHeight = lineHeight
return this
}
fun overflow(overflow: TextOverflow): TextBuilder {
this.overflow = overflow
return this
}
fun softwrap(wrap : Boolean): TextBuilder {
softWrap = wrap
return this
}
fun maxLines(max : Int){
maxLines = max
}
fun minLines(min : Int): TextBuilder {
if(min > 0) minLines = min
return this
}
fun onTextLayout(onTextLayout: (TextLayoutResult) -> Unit): TextBuilder {
this.onTextLayout = onTextLayout
return this
}
@Composable
fun compose(style : TextStyle? = LocalTextStyle.current, recycle: Boolean? = false){
Text(text, modifier, color, fontSize, fontStyle, fontWeight, fontFamily,
letterSpacing, textDecoration, textAlign, lineHeight, overflow, softWrap,
maxLines, minLines, onTextLayout, style!!)
if(!recycle!!) dispose(id)
}
@Composable override fun compose() {
Text(text, modifier, color, fontSize, fontStyle, fontWeight, fontFamily,
letterSpacing, textDecoration, textAlign, lineHeight, overflow, softWrap,
maxLines, minLines, onTextLayout, LocalTextStyle.current)
dispose(id)
}
}
| 0
|
Kotlin
|
0
| 0
|
463b525197b18839c3c05fb52b62c03bea8d94f4
| 3,873
|
kmm-compose-playground
|
Apache License 2.0
|
src/main/kotlin/org/cdb/homunculus/models/types/ShortText.kt
|
CodeDrillBrigade
| 714,769,385
| false
|
{"Kotlin": 190419, "Dockerfile": 336}
|
package org.cdb.homunculus.models.types
import kotlinx.serialization.Serializable
@JvmInline
@Serializable
value class ShortText(val text: String) {
init {
require(text.length <= 300) {
"A ShortText cannot be greater than 300 chracters"
}
}
override fun toString(): String = text
}
| 0
|
Kotlin
|
0
| 0
|
9830788175ad4ecf8e0a8d8a08b8c1f1c075f4cf
| 295
|
Homunculus
|
MIT License
|
kotlinApp/Application/src/main/java/com/example/android/autofillframework/service/datasource/AutofillRepository.kt
|
sunmTree
| 93,298,013
| true
|
{"Gradle": 7, "Shell": 2, "Markdown": 4, "Batchfile": 2, "Text": 2, "YAML": 2, "Java Properties": 2, "XML": 36, "Kotlin": 20, "Java": 20}
|
/*
* Copyright (C) 2017 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.example.android.autofillframework.service.datasource
import android.content.Context
import com.example.android.autofillframework.service.model.ClientFormData
import java.util.HashMap
interface AutofillRepository {
/**
* Gets saved ClientFormData that contains some objects that can autofill fields with these
* `autofillHints`.
*/
fun getClientFormData(context: Context, focusedAutofillHints: List<String>,
allAutofillHints: List<String>): HashMap<String, ClientFormData>?
/**
* Saves LoginCredential under this datasetName.
*/
fun saveClientFormData(context: Context, clientFormData: ClientFormData)
/**
* Clears all data.
*/
fun clear(context: Context)
}
| 0
|
Java
|
0
| 0
|
d625bdc27c6166aa43efaf02e174c40910b8823b
| 1,365
|
android-AutofillFramework
|
Apache License 2.0
|
src/main/kotlin/no/nav/arbeidsgiver/iatjenester/metrikker/controller/ResponseStatus.kt
|
navikt
| 338,342,215
| false
|
{"Kotlin": 152898, "Shell": 260, "Dockerfile": 148}
|
package no.nav.arbeidsgiver.iatjenester.metrikker.controller
object ResponseStatusConsts {
val OK = ResponseStatus("ok")
val Created = ResponseStatus("created")
val BadRequest = ResponseStatus("bad request")
val Forbidden = ResponseStatus("forbidden")
}
data class ResponseStatus(
val status: String
)
| 0
|
Kotlin
|
0
| 0
|
9b94e437c1d5cd91ae89406150b605b1b1fe099d
| 324
|
ia-tjenester-metrikker
|
MIT License
|
venom/src/test/java/com/github/venom/service/ServiceDelegateTest.kt
|
YarikSOffice
| 255,161,977
| false
| null |
package com.github.venom.service
import android.app.ActivityManager
import android.app.ActivityManager.RunningServiceInfo
import android.content.Context
import android.content.Context.ACTIVITY_SERVICE
import androidx.core.content.ContextCompat
import io.mockk.every
import io.mockk.mockk
import io.mockk.mockkStatic
import io.mockk.verify
import org.junit.Assert.assertFalse
import org.junit.Assert.assertTrue
import org.junit.Before
import org.junit.Test
class ServiceDelegateTest {
private val context = mockk<Context>(relaxed = true)
private lateinit var delegate: ServiceDelegate
@Before
fun setup() {
delegate = ServiceDelegate(context)
}
@Test
fun startService_startServiceIfNotRunning() {
setRunningState(false)
mockkStatic(ContextCompat::class) {
delegate.startService()
// it's not possible to verify the Intent unfortunately
verify { ContextCompat.startForegroundService(any(), any()) }
}
}
@Test
fun startService_dontStartServiceIfAlreadyRunning() {
setRunningState(true)
mockkStatic(ContextCompat::class) {
delegate.startService()
verify(exactly = 0) { ContextCompat.startForegroundService(any(), any()) }
}
}
@Test
fun stopService_stopService() {
delegate.stopService()
verify { context.stopService(any()) }
}
@Test
fun isServiceRunning_returnTrueIfRunning() {
setRunningState(true)
assertTrue(delegate.isServiceRunning())
}
@Test
fun isServiceRunning_returnFalseIfNotRunning() {
setRunningState(false)
assertFalse(delegate.isServiceRunning())
}
@Suppress("DEPRECATION")
private fun setRunningState(running: Boolean) {
val serviceInfo = mockk<RunningServiceInfo>()
serviceInfo.service = mockk {
every { className } returns if (running) VenomService::class.java.name else ""
}
every {
context.getSystemService(ACTIVITY_SERVICE)
} returns mockk<ActivityManager> {
every { getRunningServices(any()) } returns listOf(serviceInfo)
}
}
}
| 1
|
Kotlin
|
12
| 270
|
f9a00a6579778df8130cc982089ae820955ea70e
| 2,201
|
venom
|
MIT License
|
src/main/kotlin/me/yunleah/plugin/coldestiny/util/ToolsUtil.kt
|
Yunleah
| 664,422,335
| false
| null |
package me.yunleah.plugin.coldestiny.util
import me.yunleah.plugin.coldestiny.internal.manager.ConfigManager
import org.bukkit.Material
import org.bukkit.event.entity.EntityDamageEvent
import org.bukkit.event.entity.PlayerDeathEvent
import taboolib.common.platform.function.console
import taboolib.common5.Coerce
import taboolib.common5.cint
import taboolib.module.lang.sendLang
import taboolib.platform.util.killer
import java.util.*
object ToolsUtil {
fun debug(text: String) {
if (ConfigManager.settingDebugEnable) {
return console().sendLang("Plugin-Debug", text)
}
}
fun timing(): Long {
return System.nanoTime()
}
fun timing(start: Long): Double {
return Coerce.format((System.nanoTime() - start).div(1000000.0))
}
fun String.toTime(): Int {
if (this == "") return 0
val units = listOf("s", "min", "hou", "day", "mon", "year")
val unit = units.firstOrNull { this.endsWith(it) } ?: throw IllegalArgumentException("Invalid time unit")
val value = this.dropLast(unit.length).cint
return when (unit) {
"s" -> value * 20
"min" -> value * 20 * 60
"hou" -> value * 20 * 60 * 60
"day" -> value * 20 * 60 * 60 * 24
"mon" -> value * 20 * 60 * 60 * 24 * 30
"year" -> value * 20 * 60 * 60 * 24 * 365
else -> throw IllegalArgumentException("Invalid time unit")
}
}
fun causeDeath(event: PlayerDeathEvent): String {
val killer = event.entity.killer
val killers = event.killer
val damageEvent = event.entity.lastDamageCause
//判断是否为玩家
if (killer != null) { return killer.name }
//判断是否为其他实体
if (killers != null) { return killers.name }
//判断意外死亡
//判断意外死亡
damageEvent?.cause?.let { cause ->
return when (cause) {
in EntityDamageEvent.DamageCause.values() -> cause.name.lowercase(Locale.getDefault())
else -> "unknown"
}
} ?: return "unknown"
}
fun type(event: PlayerDeathEvent): String? {
val killer = event.entity.killer
val killers = event.killer
//判断是否为玩家
if (killer != null) { return "player" }
//判断是否为其他实体
if (killers != null) { return "mob" }
return null
}
fun String.toMaterial(): Material {
return Material.getMaterial(this) ?: throw IllegalArgumentException("Invalid material name: $this")
}
fun String.parsePercent(): Float {
return this.removeSuffix("%").toFloat() / 100.0f
}
}
| 0
|
Kotlin
|
0
| 2
|
366825bb2e2f495f145677ab5f18d7a81dc71ad3
| 2,639
|
ColdEstiny
|
MIT License
|
modules/wasm-binary/src/commonMain/kotlin/reader/ReaderContext.kt
|
wasmium
| 761,480,110
| false
|
{"Kotlin": 352107, "JavaScript": 200}
|
package org.wasmium.wasm.binary.reader
public class ReaderContext(
public val options: ReaderOptions,
) {
/** Total number of imported functions. */
public var numberFunctionImports: UInt = 0u
/** Total number of imported tables. */
public var numberTableImports: UInt = 0u
/** Total number of imported memories. */
public var numberMemoryImports: UInt = 0u
/** Total number of imported globals. */
public var numberGlobalImports: UInt = 0u
/** Total number of imported exceptions. */
public var numberExceptionImports: UInt = 0u
/** Total number of signatures. */
public var numberSignatures: UInt = 0u
/** Total number of tables. */
public var numberTables: UInt = 0u
/** Total number of memories. */
public var numberMemories: UInt = 0u
/** Total number of globals. */
public var numberGlobals: UInt = 0u
/** Total number of imports. */
public var numberImports: UInt = 0u
/** Total number of functions. */
public var numberFunctions: UInt = 0u
/** Total number of exports. */
public var numberExports: UInt = 0u
/** Total number of elements. */
public var numberElementSegments: UInt = 0u
/** Total number of exceptions. */
public var numberExceptions: UInt = 0u
public val numberTotalFunctions: UInt
get() = numberFunctionImports + numberFunctions
public val numberTotalTables: UInt
get() = numberTableImports + numberTables
public val numberTotalMemories: UInt
get() = numberMemoryImports + numberMemories
public val numberTotalGlobals: UInt
get() = numberGlobalImports + numberGlobals
public val numberTotalExceptions: UInt
get() = numberExceptionImports + numberExceptions
public var nameSectionConsumed: Boolean = false
public val messages: MutableList<String> = mutableListOf()
}
| 0
|
Kotlin
|
0
| 1
|
f7ddef76630278616d221e7c8251adf0f11b9587
| 1,895
|
wasmium-wasm-binary
|
Apache License 2.0
|
mb-graphql/src/main/kotlin/com/nomkhonwaan/mb/graphql/PostResolver.kt
|
nomkhonwaan
| 164,768,574
| false
| null |
package com.nomkhonwaan.mb.graphql
import com.coxautodev.graphql.tools.GraphQLResolver
import com.nomkhonwaan.mb.common.messaging.post.Post
import com.nomkhonwaan.mb.common.messaging.user.FindUserByIDQuery
import com.nomkhonwaan.mb.common.messaging.user.User
import com.nomkhonwaan.mb.common.time.toRFC3339
import org.axonframework.queryhandling.QueryGateway
import org.springframework.stereotype.Component
import java.util.concurrent.CompletableFuture
/**
* A resolver of the Post.
* <p>
* This is a specific type resolver for performing field query and mutation.
* Most of the actions performed via the query message bus.
*
* @param queryGateway An injection of the QueryGateway for dealing with query message bus
*/
@Component
class PostResolver(private val queryGateway: QueryGateway) : GraphQLResolver<Post> {
/**
* Resolves an author of the Post from its authorId.
*
* @param post A Post data object
*/
fun author(post: Post): CompletableFuture<User> {
return queryGateway.query(FindUserByIDQuery(post.authorId), User::class.java)
}
/**
* Returns a "publishedAt" string in the RFC3339 format.
* <p>
* This field will be available after the Post has been published. Default is null.
*
* @param post A Post data object
*/
fun publishedAt(post: Post): String? {
return post.publishedAt?.toRFC3339()
}
/**
* Returns a "createdAt" string in the RFC3339 format.
*
* @param post A Post data object
*/
fun createdAt(post: Post): String {
return post.createdAt.toRFC3339()
}
/**
* Returns an "updatedAt" string in the RFC3339 format.
* <p>
* This field will be available after the Post has been updated. Default is null.
*
* @param post A Post data object
*/
fun updatedAt(post: Post): String? {
return post.updatedAt?.toRFC3339()
}
}
| 0
|
Kotlin
|
0
| 0
|
481c3b60568cac387be12cdaeb05f7c538494772
| 1,924
|
mb
|
MIT License
|
app/src/main/java/com/example/dojo/view/MainActivity.kt
|
pgsilva
| 734,131,585
| false
|
{"Kotlin": 9618}
|
package com.example.dojo.view
import android.app.Activity
import android.content.Intent
import android.os.Bundle
import android.widget.Toast
import androidx.recyclerview.widget.LinearLayoutManager
import com.example.dojo.dao.SearchItemsProvider
import com.example.dojo.databinding.ActivityMainBinding
import com.example.dojo.view.form.FormActivity
import com.example.dojo.view.search.adapter.SearchListAdapter
class MainActivity : Activity() {
private val binding by lazy { ActivityMainBinding.inflate(layoutInflater) }
private lateinit var dao: SearchItemsProvider
private lateinit var adapter: SearchListAdapter
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
Toast.makeText(this, "Hello Mr Morales", Toast.LENGTH_LONG).show()
loadDependencies()
setContentView(binding.root)
configureSearchPage()
configureFloatButton()
}
override fun onResume() {
super.onResume()
adapter.refresh(dao.load())
}
private fun loadDependencies() {
dao = SearchItemsProvider()
adapter = SearchListAdapter(context = this, items = dao.load())
}
private fun configureFloatButton() {
binding.fbAddItem.let { fb ->
fb.setOnClickListener {
Intent(this, FormActivity::class.java).run {
startActivity(this)
}
}
}
}
private fun configureSearchPage() {
binding.rvSearchItems.let { rv ->
rv.adapter = adapter
rv.layoutManager = LinearLayoutManager(this)
}
}
}
| 0
|
Kotlin
|
0
| 0
|
3972ca19c8aaafafb75adbe71f0f3490ab9f1d14
| 1,648
|
dojo-android
|
MIT License
|
2020-apps/blog-app/core/src/main/java/shortcourse/readium/core/util/ExtensionFunctions.kt
|
kevin2-cyber
| 437,880,493
| false
|
{"Kotlin": 765037, "CSS": 301626, "SCSS": 287609, "HTML": 208821, "JavaScript": 16612, "Java": 2758, "TypeScript": 366}
|
package shortcourse.readium.core.util
import android.view.View
import android.widget.EditText
import com.google.android.gms.tasks.Tasks
import com.google.android.material.snackbar.BaseTransientBottomBar
import com.google.android.material.snackbar.Snackbar
import com.google.firebase.auth.FirebaseUser
import com.google.firebase.firestore.CollectionReference
import com.google.firebase.firestore.DocumentSnapshot
import com.google.firebase.firestore.FirebaseFirestore
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
import shortcourse.readium.core.model.account.Account
/**
* Extracts text from [EditText] field
*/
val EditText.resolveText get() = text.toString()
/**
* Show a simple [Snackbar]
*/
fun View.showSnackbar(message: String, persisted: Boolean = false, callback: () -> Unit? = {}) =
Snackbar.make(
this,
message,
if (persisted) Snackbar.LENGTH_INDEFINITE else Snackbar.LENGTH_SHORT
)
.addCallback(object : BaseTransientBottomBar.BaseCallback<Snackbar?>() {
override fun onShown(transientBottomBar: Snackbar?) {
super.onShown(transientBottomBar)
if (persisted) {
GlobalScope.launch(Dispatchers.Main) {
// Cancel after 10 secs
delay(10000)
if (transientBottomBar != null && transientBottomBar.isShown) transientBottomBar.dismiss()
}
}
}
override fun onDismissed(transientBottomBar: Snackbar?, event: Int) {
callback()
}
})
.show()
/**
* Creates an [Account] instance from [FirebaseUser]
*/
// region FIRESTORE EXTENSIONS
val FirebaseFirestore.posts get() = collection(Entities.POSTS)
val FirebaseFirestore.accounts get() = collection(Entities.ACCOUNTS)
fun DocumentSnapshot.delete() = Tasks.await(this.reference.delete())
fun CollectionReference.deleteAll() {
val documents = Tasks.await(this.get()).documents
documents.forEach { snapshot ->
if (snapshot.exists()) Tasks.await(snapshot.reference.delete())
}
}
fun FirebaseUser.asAccount(): Account =
Account("", uid, displayName ?: "", displayName ?: "", email!!, "")
.copy(id = Account.generateId(displayName ?: uid, displayName ?: ""))
fun FirebaseFirestore.getAccounts() = collection(Entities.ACCOUNTS).get()
fun FirebaseFirestore.getAccountById(id: String) = document("${Entities.ACCOUNTS}/$id").get()
fun FirebaseFirestore.observeAccountById(id: String) = document("${Entities.ACCOUNTS}/$id")
fun FirebaseFirestore.getComments(postId: String) =
collection("${Entities.POSTS}/$postId/${Entities.COMMENTS}").get()
fun FirebaseFirestore.getPosts() = collection(Entities.POSTS).get()
// endregion FIRESTORE EXTENSIONS
| 0
|
Kotlin
|
0
| 1
|
260d0d3bbae9bfaa24df4fb933188e37c82cc8a6
| 2,911
|
ug-short-course
|
MIT License
|
2020-apps/blog-app/core/src/main/java/shortcourse/readium/core/util/ExtensionFunctions.kt
|
kevin2-cyber
| 437,880,493
| false
|
{"Kotlin": 765037, "CSS": 301626, "SCSS": 287609, "HTML": 208821, "JavaScript": 16612, "Java": 2758, "TypeScript": 366}
|
package shortcourse.readium.core.util
import android.view.View
import android.widget.EditText
import com.google.android.gms.tasks.Tasks
import com.google.android.material.snackbar.BaseTransientBottomBar
import com.google.android.material.snackbar.Snackbar
import com.google.firebase.auth.FirebaseUser
import com.google.firebase.firestore.CollectionReference
import com.google.firebase.firestore.DocumentSnapshot
import com.google.firebase.firestore.FirebaseFirestore
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
import shortcourse.readium.core.model.account.Account
/**
* Extracts text from [EditText] field
*/
val EditText.resolveText get() = text.toString()
/**
* Show a simple [Snackbar]
*/
fun View.showSnackbar(message: String, persisted: Boolean = false, callback: () -> Unit? = {}) =
Snackbar.make(
this,
message,
if (persisted) Snackbar.LENGTH_INDEFINITE else Snackbar.LENGTH_SHORT
)
.addCallback(object : BaseTransientBottomBar.BaseCallback<Snackbar?>() {
override fun onShown(transientBottomBar: Snackbar?) {
super.onShown(transientBottomBar)
if (persisted) {
GlobalScope.launch(Dispatchers.Main) {
// Cancel after 10 secs
delay(10000)
if (transientBottomBar != null && transientBottomBar.isShown) transientBottomBar.dismiss()
}
}
}
override fun onDismissed(transientBottomBar: Snackbar?, event: Int) {
callback()
}
})
.show()
/**
* Creates an [Account] instance from [FirebaseUser]
*/
// region FIRESTORE EXTENSIONS
val FirebaseFirestore.posts get() = collection(Entities.POSTS)
val FirebaseFirestore.accounts get() = collection(Entities.ACCOUNTS)
fun DocumentSnapshot.delete() = Tasks.await(this.reference.delete())
fun CollectionReference.deleteAll() {
val documents = Tasks.await(this.get()).documents
documents.forEach { snapshot ->
if (snapshot.exists()) Tasks.await(snapshot.reference.delete())
}
}
fun FirebaseUser.asAccount(): Account =
Account("", uid, displayName ?: "", displayName ?: "", email!!, "")
.copy(id = Account.generateId(displayName ?: uid, displayName ?: ""))
fun FirebaseFirestore.getAccounts() = collection(Entities.ACCOUNTS).get()
fun FirebaseFirestore.getAccountById(id: String) = document("${Entities.ACCOUNTS}/$id").get()
fun FirebaseFirestore.observeAccountById(id: String) = document("${Entities.ACCOUNTS}/$id")
fun FirebaseFirestore.getComments(postId: String) =
collection("${Entities.POSTS}/$postId/${Entities.COMMENTS}").get()
fun FirebaseFirestore.getPosts() = collection(Entities.POSTS).get()
// endregion FIRESTORE EXTENSIONS
| 0
|
Kotlin
|
0
| 1
|
260d0d3bbae9bfaa24df4fb933188e37c82cc8a6
| 2,911
|
ug-short-course
|
MIT License
|
resume-ab-validation/src/main/kotlin/ru/otus/otuskotlin/validation/ValidationFieldError.kt
|
otuskotlin
| 377,710,400
| false
| null |
package ru.otus.otuskotlin.validation
data class ValidationFieldError(
override val message: String,
override val field: String
) : IValidationError, IValidationFieldError
| 0
|
Kotlin
|
0
| 0
|
920d87731a128acc1c113acd393dcc09ed01411a
| 180
|
ok-202105-resume-ab
|
MIT License
|
app/src/main/java/com/robert/android/lostpets/domain/interactors/impl/GetLanguageInteractorImpl.kt
|
robertene1994
| 303,119,114
| false
| null |
package com.robert.android.lostpets.domain.interactors.impl
import com.robert.android.lostpets.domain.executor.Executor
import com.robert.android.lostpets.domain.executor.MainThread
import com.robert.android.lostpets.domain.interactors.GetLanguageInteractor
import com.robert.android.lostpets.domain.interactors.base.AbstractInteractor
import com.robert.android.lostpets.domain.repository.SettingsRepository
import java.util.Locale
/**
* Clase que extiende la clase AbstractInteractor e implementa la interfaz GetLanguageInteractor.
*
* @author <NAME>
* @see com.robert.android.lostpets.domain.interactors.base.AbstractInteractor
* @see com.robert.android.lostpets.domain.interactors.GetLanguageInteractor
*/
class GetLanguageInteractorImpl(
executor: Executor,
mainThread: MainThread,
callback: GetLanguageInteractor.Callback,
settingsRepository: SettingsRepository
) :
AbstractInteractor(executor, mainThread), GetLanguageInteractor {
private val mCallback: GetLanguageInteractor.Callback = callback
private val mSettingsRepository: SettingsRepository = settingsRepository
override fun run() {
val language = checkDefault(mSettingsRepository.getLanguage())
mMainThread.post(Runnable { mCallback.onLanguageRetrieved(language) })
}
private fun checkDefault(lang: String?): String {
var language = lang
if (language == null || language.trim().isEmpty()) {
language = Locale.getDefault().language.toString()
mSettingsRepository.saveLanguage(language)
}
return language
}
}
| 0
|
Kotlin
|
0
| 0
|
a7af7de031d3ab4e2d14851a117d3729330cd875
| 1,598
|
lostpets-android
|
MIT License
|
api/src/main/kotlin/net/bytemc/bytecloud/api/event/packets/EventUnSubscribePacket.kt
|
bytemcnetzwerk
| 684,494,766
| false
|
{"Kotlin": 178268}
|
package net.bytemc.bytecloud.api.event.packets
import net.bytemc.bytecloud.api.network.PacketBuffer
import net.bytemc.bytecloud.api.network.packet.Packet
class EventUnSubscribePacket : Packet {
override fun write(out: PacketBuffer) {
TODO("Not yet implemented")
}
override fun read(inBuf: PacketBuffer) {
TODO("Not yet implemented")
}
override fun id(): Int {
return 13
}
}
| 0
|
Kotlin
|
3
| 5
|
6657d004ab2d53516506ea57a0cea09506eea8ce
| 426
|
bytecloud
|
Apache License 2.0
|
api/src/main/kotlin/net/bytemc/bytecloud/api/event/packets/EventUnSubscribePacket.kt
|
bytemcnetzwerk
| 684,494,766
| false
|
{"Kotlin": 178268}
|
package net.bytemc.bytecloud.api.event.packets
import net.bytemc.bytecloud.api.network.PacketBuffer
import net.bytemc.bytecloud.api.network.packet.Packet
class EventUnSubscribePacket : Packet {
override fun write(out: PacketBuffer) {
TODO("Not yet implemented")
}
override fun read(inBuf: PacketBuffer) {
TODO("Not yet implemented")
}
override fun id(): Int {
return 13
}
}
| 0
|
Kotlin
|
3
| 5
|
6657d004ab2d53516506ea57a0cea09506eea8ce
| 426
|
bytecloud
|
Apache License 2.0
|
nebulosa-indi-device/src/main/kotlin/nebulosa/indi/device/camera/CameraOffsetMinMaxChanged.kt
|
tiagohm
| 568,578,345
| false
|
{"Kotlin": 2712371, "TypeScript": 513759, "HTML": 249483, "JavaScript": 120539, "SCSS": 11332, "Python": 2817, "Makefile": 445}
|
package nebulosa.indi.device.camera
import nebulosa.indi.device.PropertyChangedEvent
data class CameraOffsetMinMaxChanged(override val device: Camera) : CameraEvent, PropertyChangedEvent
| 26
|
Kotlin
|
2
| 4
|
2099c6f2d7453507289a43efe903c7f92f65f770
| 189
|
nebulosa
|
MIT License
|
app/src/main/java/com/hakmar/employeelivetracking/features/tasks/ui/states/TaskState.kt
|
enginemre
| 584,733,724
| false
| null |
package com.hakmar.employeelivetracking.features.tasks.ui.states
import com.hakmar.employeelivetracking.features.tasks.domain.model.Task
data class TaskState(
var isLoading: Boolean = false,
var isRefreshing: Boolean = false,
var taskList: List<Task> = emptyList(),
var shouldShowDialog: Boolean = false,
var selectedTaskId: Int? = 0
)
| 0
|
Kotlin
|
0
| 0
|
5e348e0a5aac89b4e60607a14a4ef9bbd68545a5
| 358
|
employee_live_tracking
|
The Unlicense
|
kompot/src/main/kotlin/com/revolut/kompot/KompotPlugin.kt
|
revolut-mobile
| 488,970,565
| false
| null |
/*
* Copyright (C) 2022 Revolut
*
* 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.revolut.kompot
import com.revolut.kompot.navigable.Controller
import kotlinx.coroutines.channels.BufferOverflow
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.MutableSharedFlow
object KompotPlugin {
internal val controllerShownSharedFlow = MutableSharedFlow<Controller>(extraBufferCapacity = 16, onBufferOverflow = BufferOverflow.DROP_OLDEST)
fun controllerShowingStream(): Flow<Controller> = controllerShownSharedFlow
}
| 0
|
Kotlin
|
5
| 91
|
1ea49978cd64b74aeac41d1d0bcce68bbcce9d6c
| 1,059
|
kompot
|
Apache License 2.0
|
src/main/kotlin/net/mt32/expoll/helper/Async.kt
|
Universumgames
| 508,613,455
| false
|
{"Kotlin": 318004, "HTML": 6405, "TSQL": 5917, "Dockerfile": 2071, "Shell": 1904, "CSS": 1207}
|
package net.mt32.expoll.helper
import kotlinx.coroutines.runBlocking
fun async(block: suspend () -> Unit): Thread {
val t = Thread {
try {
runBlocking {
block()
}
} catch (e: Exception) {
e.printStackTrace()
}
}
t.start()
return t
}
| 0
|
Kotlin
|
1
| 0
|
0806335cdd4e6c9c88e6f54b1253e67bec37e872
| 326
|
expoll_server
|
MIT License
|
app/src/main/java/com/example/android_chatbot/ui/components/BotChip.kt
|
wilsonng234
| 699,879,489
| false
|
{"Kotlin": 78356}
|
package com.example.android_chatbot.ui.components
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.FilterChip
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun BotChip(
label: String,
selected: Boolean = false,
handleBotChipClicked: () -> Unit = { },
leadingIcon: @Composable (() -> Unit) = { },
modifier: Modifier = Modifier
) {
FilterChip(
onClick = { handleBotChipClicked() },
label = { Text(label) },
selected = selected,
leadingIcon = leadingIcon,
modifier = modifier
)
}
@Composable
@Preview
fun BotChipPreview() {
Row(
horizontalArrangement = Arrangement.SpaceAround,
modifier = Modifier
.fillMaxWidth()
.padding(horizontal = 50.dp)
) {
BotChip(label = "GPT-3.5-Turbo")
BotChip(label = "GPT-4")
}
}
| 0
|
Kotlin
|
0
| 0
|
981c74f413800d29a3cdc615752605a00095e38e
| 1,304
|
Android-ChatBot
|
MIT License
|
app/src/main/java/com/bsuir/bsuirschedule/domain/repository/ScheduleRepository.kt
|
Saydullin
| 526,953,048
| false
|
{"Kotlin": 572249, "HTML": 7301}
|
package com.bsuir.bsuirschedule.domain.repository
import com.bsuir.bsuirschedule.data.db.dao.ScheduleDao
import com.bsuir.bsuirschedule.domain.models.GroupSchedule
import com.bsuir.bsuirschedule.domain.models.Schedule
import com.bsuir.bsuirschedule.domain.models.ScheduleLastUpdatedDate
import com.bsuir.bsuirschedule.domain.models.scheduleSettings.ScheduleSettings
import com.bsuir.bsuirschedule.domain.utils.Resource
interface ScheduleRepository {
val scheduleDao: ScheduleDao
suspend fun getGroupScheduleAPI(groupName: String): Resource<GroupSchedule>
suspend fun getEmployeeScheduleAPI(groupName: String): Resource<GroupSchedule>
suspend fun getEmployeeLastUpdatedDate(scheduleId: Int): Resource<ScheduleLastUpdatedDate>
suspend fun getGroupLastUpdatedDate(scheduleId: Int): Resource<ScheduleLastUpdatedDate>
suspend fun getScheduleById(id: Int): Resource<Schedule>
suspend fun saveSchedule(schedule: Schedule): Resource<Unit>
suspend fun updateScheduleSettings(id: Int, newSettings: ScheduleSettings): Resource<Unit>
suspend fun deleteScheduleById(scheduleId: Int): Resource<Unit>
}
| 0
|
Kotlin
|
0
| 4
|
49dc7e7551a4c0df2ada93648291e24aecb3bda5
| 1,138
|
BSUIR_Schedule
|
Creative Commons Zero v1.0 Universal
|
failfast-examples/src/test/kotlin/failfast/examples/ContractsTest.kt
|
robfletcher
| 333,458,962
| true
|
{"Kotlin": 108563}
|
package failfast.examples
import failfast.ContextDSL
import failfast.FailFast
import failfast.describe
import strikt.api.expectThat
import strikt.assertions.isEqualTo
import java.util.*
fun main() {
FailFast.runTest()
}
// a port of https://github.com/dmcg/minutest/blob/master/core/src/test/kotlin/dev/minutest/examples/ContractsExampleTests.kt
object ContractsTest {
val context = describe("Contracts") {
describe("ArrayList") {
behavesAsMutableCollection(ArrayList<String>())
}
describe("LinkedList") {
behavesAsMutableCollection(LinkedList<String>())
}
}
private suspend fun ContextDSL.behavesAsMutableCollection(fixture: MutableList<String>) {
context("behaves as MutableCollection") {
test("is empty when created") {
expectThat(fixture.isEmpty())
}
test("can add") {
fixture.add("item")
expectThat(fixture.first()).isEqualTo("item")
}
}
}
}
| 0
|
Kotlin
|
0
| 0
|
4af24b125a39352e6c6fc4d991b3b737009759a4
| 1,041
|
failfast
|
MIT License
|
src/main/kotlin/ch/hsr/dsl/dwrtc/util/Config.kt
|
dwrtc
| 150,221,331
| false
| null |
package ch.hsr.dsl.dwrtc.util
import com.natpryce.konfig.*
/** The port the TomP2P peer runs on */
val PEER_PORT = Key("peer.port", intType)
/** The IP the Webserver binds to */
val WEBSERVER_IP = Key("http.ip", stringType)
/** The port the Webserver runs on */
val WEBSERVER_PORT = Key("http.port", intType)
/** The list of peers to bootstrap to. Comma-separated list of "HOST:PORT" */
val BOOTSTRAP_PEER = Key("bootstrap.peer", listType(stringType))
/** Build variable. Pack the resources in the JAR (otherwise, load from file system) */
val PACKED_RESOURCES = Key("packed.resources", booleanType)
/** The configuration object, defining the priorities in which configuration is read */
val config = ConfigurationProperties.systemProperties() overriding
EnvironmentVariables overriding
ConfigurationProperties.fromResource("defaults.properties")
| 3
|
Kotlin
|
3
| 8
|
a3753a27cca7bbf6d4cb21a0b382f52cb281ecb7
| 866
|
dwrtc
|
Apache License 2.0
|
core/logging/src/main/java/com/costular/atomtasks/core/logging/LogcatAtomLogger.kt
|
costular
| 379,913,052
| false
|
{"Kotlin": 566642, "HTML": 7918}
|
package com.costular.atomtasks.core.logging
import android.util.Log
class LogcatAtomLogger : AtomLogger {
override fun log(level: LogLevel, tag: String, text: String) {
Log.println(level.asLogcatLevel(), tag, text)
}
override fun log(
level: LogLevel,
tag: String,
exceptionParams: Map<String, Any?>,
throwable: Throwable
) {
val androidLogLevel = level.asLogcatLevel()
Log.println(androidLogLevel, tag, throwable.stackTraceToString())
exceptionParams.forEach {
Log.println(androidLogLevel, tag, "${it.key} ==> ${it.value}")
}
}
private fun LogLevel.asLogcatLevel(): Int =
when (this) {
LogLevel.VERBOSE -> Log.VERBOSE
LogLevel.DEBUG -> Log.DEBUG
LogLevel.INFO -> Log.INFO
LogLevel.WARN -> Log.WARN
LogLevel.ERROR -> Log.ERROR
}
}
| 0
|
Kotlin
|
0
| 9
|
98f781daebe30ed4b4439629b4d6215153f7fc89
| 921
|
atom-tasks
|
Apache License 2.0
|
teamcity-kotlin-trigger-openapi/src/main/kotlin/jetbrains/buildServer/buildTriggers/remote/BuildType.kt
|
JetBrains
| 307,772,250
| false
| null |
/*
* Copyright 2000-2020 JetBrains s.r.o.
*
* 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 jetbrains.buildServer.buildTriggers.remote
import java.util.*
class BuildType(
val id: String,
val isInQueue: Boolean,
val isPaused: Boolean,
val project: Project,
val runningBuilds: List<RunningBuild>,
val history: List<FinishedBuild>,
val lastChangesStartedBuild: Build?,
val lastChangesSuccessfullyFinished: Build?,
val lastChangesFinished: Build?,
val buildParameters: Map<String, String>,
val parameters: Map<String, String>
)
class Project(val id: String, val isArchived: Boolean)
class Build(val id: Long, val startDate: Date, val isFinished: Boolean, val duration: Long)
class RunningBuild(val build: Build, val agentId: Int)
class FinishedBuild(val build: Build, val finishDate: Date)
| 2
|
Kotlin
|
1
| 1
|
5c509dc7be3599a0c993b7e88e8efa4e1e2a0219
| 1,353
|
teamcity-kotlin-trigger
|
Apache License 2.0
|
src/main/kotlin/com/github/hanseter/json/queryengine/fx/queryUis/AttributePresentQueryUi.kt
|
Hanseter
| 244,839,580
| false
| null |
package com.github.hanseter.json.queryengine.fx.queryUis
import javafx.scene.layout.HBox
import javafx.scene.control.TextField
import javafx.scene.control.Label
import javafx.scene.Node
import org.controlsfx.control.textfield.TextFields
import org.json.JSONObject
import com.github.hanseter.json.queryengine.AttributePath
import com.github.hanseter.json.queryengine.fx.AttributePathTextField
import com.github.hanseter.json.queryengine.fx.QueryBuilderUi
import com.github.hanseter.json.queryengine.AttributeExistsQuery
import javafx.beans.property.SimpleBooleanProperty
import com.github.hanseter.json.queryengine.AttributeExistsQuery.AttributeExistsQueryBuilder
import javafx.beans.property.ReadOnlyBooleanProperty
class AttributePresentQueryUi(fieldNames: JSONObject) : QueryBuilderUi<AttributeExistsQuery> {
private val attrPathField = AttributePathTextField(fieldNames)
private val queryBuilder = AttributeExistsQueryBuilder()
private val isComplete = SimpleBooleanProperty(false)
private val node: Node = HBox(Label("has"), attrPathField)
init {
attrPathField.textProperty().addListener { _, _, new ->
queryBuilder.withAttributePath(new)
isComplete.set(queryBuilder.isComplete())
}
}
override fun isComplete(): ReadOnlyBooleanProperty = isComplete
override fun getNode(): Node = node
override fun getQueryBuilder() = queryBuilder
override fun setPreview(preview: Boolean) {
node.setDisable(preview)
}
}
| 0
|
Kotlin
|
0
| 0
|
c55fdd793fc1429e1518b84beae169578c965734
| 1,438
|
JSONQueryEngineFx
|
MIT License
|
app/src/main/java/com/akexorcist/listadapter/model/PostGenerator.kt
|
akexorcist
| 130,909,890
| false
| null |
package com.akexorcist.listadapter.model
class PostGenerator {
private val post1 = PhotoPost("001", "Looking forward to a wonderful time ahead with the love of my life.", "02/01/2018 12:10", "https://images.unsplash.com/photo-1522199710521-72d69614c702?w=668&q=80")
private val post2 = StatusPost("002", "Waiting eagerly for the winter.", "02/01/2018 12:09")
private val post3 = PhotoPost("003", "Packed my bags and I am almost ready to go... a new job... a new life.", "02/01/2018 12:00", "https://images.unsplash.com/photo-1490984902283-b7f4723f3955?w=668&q=80")
private val post4 = StatusPost("004", "Money may not buy us happiness; but if you hand me a million dollars, I would be more than happy to take it.", "02/01/2018 11:55")
private val post5 = StatusPost("005", "There is no alternative to hard work.", "02/01/2018 11:53")
private val post6 = PhotoPost("006", "Mistakes are what make us human. If you never trip, you never learn to walk.", "02/01/2018 11:53", "https://images.unsplash.com/photo-1522198763288-96e9f39904af?w=668&q=80")
private val post7 = StatusPost("007", "Behind every successful and a charming man, there lie a woman who is rolling her eyes to get him.", "02/01/2018 11:51")
private val post8 = PhotoPost("008", "If one day you manage to have everything, the question is where will you put it?", "02/01/2018 11:48", "https://images.unsplash.com/photo-1502120492606-fba13cc63721?w=668&q=80")
private val post9 = StatusPost("009", "A kid scored 0 marks in his exam. Dad asked \"what is this?\" Kid replied - teacher was short of starts so she gave me the sun.", "02/01/2018 11:45")
private val post10 = StatusPost("010", "When you intend to take a sick leave, you are actually sick! When a boss takes sick leaves, he is considered to be very ill.", "02/01/2018 11:40")
companion object {
fun get(): List<Post> {
return PostGenerator().getPostList()
}
}
private fun getPostList() = when ((0..5).shuffled().first()) {
0 -> getPostList0()
1 -> getPostList1()
2 -> getPostList2()
3 -> getPostList3()
4 -> getPostList4()
5 -> getPostList5()
6 -> getPostList6()
else -> getPostListAll()
}
private fun getPostList0(): List<Post> {
return mutableListOf(post2, post3, post5, post6, post7, post8, post9)
}
private fun getPostList1(): List<Post> {
return mutableListOf(post1, post3, post5, post6, post7)
}
private fun getPostList2(): List<Post> {
return mutableListOf(post3, post4, post5, post6, post8, post10)
}
private fun getPostList3(): List<Post> {
return mutableListOf(post4, post5, post6, post8, post9)
}
private fun getPostList4(): List<Post> {
return mutableListOf(post1, post2, post6, post7, post10)
}
private fun getPostList5(): List<Post> {
return mutableListOf(post2, post3, post4, post5, post6, post9, post10)
}
private fun getPostList6(): List<Post> {
return mutableListOf(post1, post4, post5, post6, post7, post10)
}
private fun getPostListAll(): List<Post> {
return mutableListOf(post1, post2, post3, post4, post5, post6, post7, post8, post9, post10)
}
}
| 0
|
Kotlin
|
3
| 7
|
d6e2f580dc5890b9813ce44cd87f4ffb13e93c10
| 3,275
|
RecyclerView-ListAdapter
|
Apache License 2.0
|
app/src/main/java/com/coclearapp/pdm_project/Activities/PatientsActivity.kt
|
RFuentes22
| 361,808,712
| true
|
{"Kotlin": 104852}
|
package com.coclearapp.pdm_project.Activities
import android.content.Intent
import android.os.Bundle
import android.util.Log
import androidx.appcompat.app.AppCompatActivity
import androidx.lifecycle.LifecycleOwner
import androidx.lifecycle.Observer
import androidx.lifecycle.ViewModelProviders
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.coclearapp.pdm_project.Adapters.PatientAdapter
import com.coclearapp.pdm_project.R
import com.coclearapp.pdm_project.Room.Entity.Patient
import com.coclearapp.pdm_project.ViewModel.PatientViewModel
import com.google.firebase.auth.FirebaseAuth
import com.google.firebase.database.*
import kotlinx.android.synthetic.main.activity_patients.*
class PatientsActivity : AppCompatActivity(), LifecycleOwner {
private lateinit var viewAdapter: PatientAdapter
private lateinit var viewManager: RecyclerView.LayoutManager
companion object {
lateinit var patientViewModel: PatientViewModel
fun patientEditClicked(patient: Patient){
//Log.d("edit",patient.Name_Patient + " " + patient.Date)
patientViewModel.editPatient(patient)
}
fun patientDeleteClicked(idPa: Long) {
patientViewModel.deletePatient(idPa)
}
}
private lateinit var auth: FirebaseAuth
private var mDatabase: DatabaseReference? = null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_patients)
auth = FirebaseAuth.getInstance()
mDatabase = FirebaseDatabase.getInstance().reference
getDataFirebase()
initRecycle(emptyList())
patientViewModel = ViewModelProviders.of(this).get(PatientViewModel::class.java)
patientViewModel.getAllPatients().observe(this, Observer {
viewAdapter.dataChange(it)
})
}
fun initRecycle(patients: List<Patient>) {
viewManager = LinearLayoutManager(this)
viewAdapter =
PatientAdapter(patients, { patientitem: Patient -> patientItemClicked(patientitem) })
rv_patients.apply {
setHasFixedSize(true)
layoutManager = viewManager
adapter = viewAdapter
}
}
private fun patientItemClicked(item: Patient) {
startActivity(
Intent(this, LevelsActivity::class.java).putExtra("name", item.Name_Patient)
.putExtra("level", item.Level.toString())
)
}
private fun getDataFirebase() {
val user = auth.currentUser
mDatabase!!.child("User/${user!!.uid}").addValueEventListener(
object : ValueEventListener {
override fun onCancelled(p0: DatabaseError) {
TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
}
override fun onDataChange(p0: DataSnapshot) {
Log.d("Patient", p0.value.toString())
}
})
}
}
| 3
|
Kotlin
|
0
| 0
|
3d22ef3267dc1443b231b35c44f1a9054471ba54
| 3,093
|
ABCoclear
|
Apache License 2.0
|
core/common/src/commonMain/kotlin/jp/co/yumemi/droidtraining/core/common/CoroutineUtils.kt
|
matsumo0922
| 842,734,172
| false
|
{"Kotlin": 94734, "Swift": 916, "HTML": 318}
|
package jp.co.yumemi.droidtraining.core.common
import io.github.aakira.napier.Napier
import kotlinx.coroutines.CoroutineDispatcher
import kotlinx.coroutines.Dispatchers
import kotlin.coroutines.cancellation.CancellationException
suspend fun <T> suspendRunCatching(block: suspend () -> T): Result<T> = try {
Result.success(block())
} catch (cancellationException: CancellationException) {
throw cancellationException
} catch (throwable: Throwable) {
Napier.i(throwable) { "Failed to evaluate a suspendRunCatchingBlock. Returning failure Result" }
Result.failure(throwable)
}
expect val Dispatchers.IO: CoroutineDispatcher
| 9
|
Kotlin
|
0
| 0
|
cb64d712c220647a17642c58109375f473de774a
| 640
|
android-training-template
|
Apache License 2.0
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.