path
stringlengths 4
280
| owner
stringlengths 2
39
| repo_id
int64 21.1k
879M
| is_fork
bool 2
classes | languages_distribution
stringlengths 13
1.95k
⌀ | content
stringlengths 7
482k
| issues
int64 0
13.9k
| main_language
stringclasses 121
values | forks
stringlengths 1
5
| stars
int64 0
111k
| commit_sha
stringlengths 40
40
| size
int64 7
482k
| name
stringlengths 1
100
| license
stringclasses 93
values |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
src/main/kotlin/org/arend/psi/ext/ArendLongNameExpr.kt
|
JetBrains
| 96,068,447
| false
| null |
package org.arend.psi.ext
import com.intellij.lang.ASTNode
import org.arend.term.abs.AbstractExpressionVisitor
import org.arend.psi.getChildOfType
import org.arend.psi.getChildOfTypeStrict
class ArendLongNameExpr(node: ASTNode) : ArendExpr(node) {
val longName: ArendLongName
get() = getChildOfTypeStrict()
val levelsExpr: ArendLevelsExpr?
get() = getChildOfType()
val pLevelExpr: ArendAtomOnlyLevelExpr?
get() = getChildOfType()
val hLevelExpr: ArendAtomOnlyLevelExpr?
get() = getChildOfType(1)
override fun <P : Any?, R : Any?> accept(visitor: AbstractExpressionVisitor<in P, out R>, params: P?): R {
val name = longName
val levels = generateSequence(levelsExpr) { it.levelsExpr }.lastOrNull()
if (levels != null) {
val pLevelExprs = levels.pLevelExprs
val hLevelExprs = levels.hLevelExprs
if (pLevelExprs != null && hLevelExprs != null) {
return visitor.visitReference(name, name.referent, null, pLevelExprs.levelExprList, hLevelExprs.levelExprList, params)
}
}
return visitor.visitReference(name, name.referent, null, pLevelExpr?.let { listOf(it) }, hLevelExpr?.let { listOf(it) }, params)
}
}
| 73
| null |
15
| 90
|
b11d0906f9a0d9680675a418cdc50b98e2d33c92
| 1,264
|
intellij-arend
|
Apache License 2.0
|
compiler/ast/src/main/kotlin/motif/ast/compiler/CompilerType.kt
|
uber
| 142,928,098
| false
| null |
/*
* Copyright (c) 2018-2019 Uber Technologies, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package motif.ast.compiler
import com.google.auto.common.MoreTypes
import com.google.common.base.Equivalence
import motif.ast.IrClass
import motif.ast.IrType
import javax.annotation.processing.ProcessingEnvironment
import javax.lang.model.type.DeclaredType
import javax.lang.model.type.TypeKind
import javax.lang.model.type.TypeMirror
class CompilerType(
private val env: ProcessingEnvironment,
val mirror: TypeMirror) : IrType {
private val key: Equivalence.Wrapper<TypeMirror> = MoreTypes.equivalence().wrap(mirror)
fun isInterface(): Boolean {
return IrClass.Kind.INTERFACE == resolveClass()?.kind
}
override val qualifiedName: String by lazy {
val candidate = mirror.toString().let {
if(it.contains("$") && mirror.kind == TypeKind.DECLARED) {
val declaredType: DeclaredType = mirror as DeclaredType
declaredType.asElement().kind
mirror.toString()
} else {
it
}
}
return@lazy if (candidate.startsWith('(')) {
candidate.substringAfter(":: ").dropLast(1)
} else {
candidate
}
}
override val isVoid: Boolean by lazy {
mirror.kind == TypeKind.VOID
}
override fun resolveClass(): IrClass? {
if (mirror.kind != TypeKind.DECLARED) return null
val declaredType: DeclaredType = mirror as DeclaredType
return CompilerClass(env, declaredType)
}
override fun isAssignableTo(type: IrType): Boolean {
val baseMirror = (type as CompilerType).mirror
if (!env.typeUtils.isAssignable(mirror, baseMirror)) {
return false
}
if (env.typeUtils.isSameType(mirror, baseMirror)) {
return true
}
if (mirror !is DeclaredType || baseMirror !is DeclaredType) {
return env.typeUtils.isAssignable(mirror, baseMirror)
}
val matchingType = getMatchingSuperType(baseMirror, mirror) ?: return false
if (baseMirror.typeArguments.isEmpty()) {
return true
}
if (matchingType.typeArguments.size != baseMirror.typeArguments.size) {
return false
}
return env.typeUtils.isAssignable(matchingType, baseMirror)
}
private fun getMatchingSuperType(baseType: DeclaredType, type: DeclaredType): DeclaredType? {
val baseErasure = env.typeUtils.erasure(baseType)
val erasure = env.typeUtils.erasure(type)
if (env.typeUtils.isSameType(baseErasure, erasure)) {
return type
}
return env.typeUtils.directSupertypes(type)
.asSequence()
.mapNotNull { superType ->
getMatchingSuperType(baseType, superType as DeclaredType)
}
.firstOrNull()
}
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (javaClass != other?.javaClass) return false
other as CompilerType
if (key != other.key) return false
return true
}
override fun hashCode(): Int {
return key.hashCode()
}
override fun toString(): String {
return mirror.toString()
}
}
| 31
| null |
37
| 500
|
a0ff8dbbb3aa739b588d6687e52e7df9b5a368e6
| 3,895
|
motif
|
Apache License 2.0
|
compiler/ast/src/main/kotlin/motif/ast/compiler/CompilerType.kt
|
uber
| 142,928,098
| false
| null |
/*
* Copyright (c) 2018-2019 Uber Technologies, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package motif.ast.compiler
import com.google.auto.common.MoreTypes
import com.google.common.base.Equivalence
import motif.ast.IrClass
import motif.ast.IrType
import javax.annotation.processing.ProcessingEnvironment
import javax.lang.model.type.DeclaredType
import javax.lang.model.type.TypeKind
import javax.lang.model.type.TypeMirror
class CompilerType(
private val env: ProcessingEnvironment,
val mirror: TypeMirror) : IrType {
private val key: Equivalence.Wrapper<TypeMirror> = MoreTypes.equivalence().wrap(mirror)
fun isInterface(): Boolean {
return IrClass.Kind.INTERFACE == resolveClass()?.kind
}
override val qualifiedName: String by lazy {
val candidate = mirror.toString().let {
if(it.contains("$") && mirror.kind == TypeKind.DECLARED) {
val declaredType: DeclaredType = mirror as DeclaredType
declaredType.asElement().kind
mirror.toString()
} else {
it
}
}
return@lazy if (candidate.startsWith('(')) {
candidate.substringAfter(":: ").dropLast(1)
} else {
candidate
}
}
override val isVoid: Boolean by lazy {
mirror.kind == TypeKind.VOID
}
override fun resolveClass(): IrClass? {
if (mirror.kind != TypeKind.DECLARED) return null
val declaredType: DeclaredType = mirror as DeclaredType
return CompilerClass(env, declaredType)
}
override fun isAssignableTo(type: IrType): Boolean {
val baseMirror = (type as CompilerType).mirror
if (!env.typeUtils.isAssignable(mirror, baseMirror)) {
return false
}
if (env.typeUtils.isSameType(mirror, baseMirror)) {
return true
}
if (mirror !is DeclaredType || baseMirror !is DeclaredType) {
return env.typeUtils.isAssignable(mirror, baseMirror)
}
val matchingType = getMatchingSuperType(baseMirror, mirror) ?: return false
if (baseMirror.typeArguments.isEmpty()) {
return true
}
if (matchingType.typeArguments.size != baseMirror.typeArguments.size) {
return false
}
return env.typeUtils.isAssignable(matchingType, baseMirror)
}
private fun getMatchingSuperType(baseType: DeclaredType, type: DeclaredType): DeclaredType? {
val baseErasure = env.typeUtils.erasure(baseType)
val erasure = env.typeUtils.erasure(type)
if (env.typeUtils.isSameType(baseErasure, erasure)) {
return type
}
return env.typeUtils.directSupertypes(type)
.asSequence()
.mapNotNull { superType ->
getMatchingSuperType(baseType, superType as DeclaredType)
}
.firstOrNull()
}
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (javaClass != other?.javaClass) return false
other as CompilerType
if (key != other.key) return false
return true
}
override fun hashCode(): Int {
return key.hashCode()
}
override fun toString(): String {
return mirror.toString()
}
}
| 31
| null |
37
| 500
|
a0ff8dbbb3aa739b588d6687e52e7df9b5a368e6
| 3,895
|
motif
|
Apache License 2.0
|
app/src/main/java/cc/sovellus/vrcaa/api/ApiContext.kt
|
Nyabsi
| 745,635,224
| false
| null |
package cc.sovellus.vrcaa.api
import android.content.Context
import android.content.ContextWrapper
import android.content.Intent
import android.content.Intent.FLAG_ACTIVITY_NEW_TASK
import android.content.SharedPreferences
import android.util.Log
import android.widget.Toast
import cc.sovellus.vrcaa.activity.main.MainActivity
import cc.sovellus.vrcaa.api.models.Auth
import cc.sovellus.vrcaa.api.models.Avatar
import cc.sovellus.vrcaa.api.models.Avatars
import cc.sovellus.vrcaa.api.models.Favorites
import cc.sovellus.vrcaa.api.models.Friends
import cc.sovellus.vrcaa.api.models.Instance
import cc.sovellus.vrcaa.api.models.Worlds
import cc.sovellus.vrcaa.api.models.Notifications
import cc.sovellus.vrcaa.api.models.User
import cc.sovellus.vrcaa.api.models.LimitedUser
import cc.sovellus.vrcaa.api.models.Users
import cc.sovellus.vrcaa.api.models.World
import cc.sovellus.vrcaa.helper.cookies
import cc.sovellus.vrcaa.helper.isExpiredSession
import cc.sovellus.vrcaa.helper.twoFactorAuth
import cc.sovellus.vrcaa.service.PipelineService
import com.google.gson.Gson
import okhttp3.Headers
import okhttp3.MediaType
import okhttp3.MediaType.Companion.toMediaTypeOrNull
import okhttp3.OkHttpClient
import okhttp3.Request
import okhttp3.RequestBody
import okhttp3.RequestBody.Companion.toRequestBody
import okhttp3.Response
import okhttp3.internal.EMPTY_REQUEST
import ru.gildor.coroutines.okhttp.await
import java.net.URLEncoder
import kotlin.io.encoding.Base64
import kotlin.io.encoding.ExperimentalEncodingApi
class ApiContext(
context: Context
): ContextWrapper(context) {
private val client: OkHttpClient = OkHttpClient()
private val preferences: SharedPreferences = getSharedPreferences("vrcaa_prefs", 0)
private val apiBase: String = "https://api.vrchat.cloud/api/1"
private val userAgent: String = "VRCAA/0.1 <EMAIL>"
private var cookies: String = ""
init {
cookies = "${preferences.cookies} ${preferences.twoFactorAuth}"
}
enum class TwoFactorType {
EMAIL_OTP,
OTP,
TOTP
}
private suspend fun doRequest(
method: String,
url: String,
headers: Headers,
body: String?
): Any? = when (method)
{
"GET" -> {
val request =
Request.Builder()
.headers(headers = headers)
.url(url)
.get()
.build()
val response = client.newCall(request).await()
when (response.code) {
200 -> {
response
}
429 -> {
Toast.makeText(
this,
"You are being rate-limited, calm down.",
Toast.LENGTH_LONG
).show()
null
}
401 -> {
if (!url.contains("auth/user") && !preferences.isExpiredSession) {
refreshToken()
} else {
null
}
}
else -> {
response.body?.let {
Log.d("VRCAA", "Got unhandled response from server (${response.code}): ${it.string()}")
}
null
}
}
}
"POST" -> {
val type: MediaType? = "application/json; charset=utf-8".toMediaTypeOrNull()
val requestBody: RequestBody = body!!.toRequestBody(type)
val request =
Request.Builder()
.headers(headers = headers)
.url(url)
.post(requestBody)
.build()
val response = client.newCall(request).await()
when (response.code) {
200 -> {
response
}
429 -> {
Toast.makeText(
this,
"You are being rate-limited, calm down.",
Toast.LENGTH_LONG
).show()
null
}
401 -> {
if (!url.contains("auth/user") && !preferences.isExpiredSession) {
refreshToken()
} else {
null
}
}
else -> {
response.body?.let {
Log.d("VRCAA", "Got unhandled response from server (${response.code}): ${it.string()}")
}
null
}
}
}
"PUT" -> {
val request =
Request.Builder()
.headers(headers = headers)
.url(url)
.put(EMPTY_REQUEST)
.build()
val response = client.newCall(request).await()
when (response.code) {
200 -> {
response
}
429 -> {
Toast.makeText(
this,
"You are being rate-limited, calm down.",
Toast.LENGTH_LONG
).show()
null
}
401 -> {
if (!url.contains("auth/user") && !preferences.isExpiredSession) {
refreshToken()
} else {
null
}
}
else -> {
response.body?.let {
Log.d("VRCAA", "Got unhandled response from server (${response.code}): ${it.string()}")
}
null
}
}
}
else -> {
null
}
}
private fun refreshToken() {
// just tell the user to re-login, I give up.
Toast.makeText(
this,
"Your session has expired, please login again.",
Toast.LENGTH_LONG
).show()
preferences.cookies = ""
preferences.isExpiredSession = true
val serviceIntent = Intent(this, PipelineService::class.java)
stopService(serviceIntent)
val intent = Intent(this, MainActivity::class.java)
intent.setFlags(FLAG_ACTIVITY_NEW_TASK)
startActivity(intent)
}
@Suppress("DEPRECATION")
@OptIn(ExperimentalEncodingApi::class)
suspend fun getToken(username: String, password: String): Pair<TwoFactorType, String>? {
val token = Base64.encode((URLEncoder.encode(username) + ":" + URLEncoder.encode(password)).toByteArray())
val headers = Headers.Builder()
headers["Authorization"] = "Basic $token"
headers["User-Agent"] = userAgent
val result = doRequest(
method = "GET",
url = "$apiBase/auth/user",
headers = headers.build(),
body = null
)
return when (result) {
is Response -> {
if (result.body?.string()?.contains("emailOtp") == true) {
Pair(TwoFactorType.EMAIL_OTP, result.headers["Set-Cookie"].toString())
} else {
Pair(TwoFactorType.TOTP, result.headers["Set-Cookie"].toString())
}
}
else -> {
null
}
}
}
suspend fun getAuth(): String? {
val headers = Headers.Builder()
headers["Cookie"] = cookies
headers["User-Agent"] = userAgent
val result = doRequest(
method = "GET",
url = "$apiBase/auth",
headers = headers.build(),
body = null
)
return when (result) {
is Response -> {
Gson().fromJson(result.body?.string(), Auth::class.java).token
}
else -> {
null
}
}
}
suspend fun verifyAccount(token: String, type: TwoFactorType, code: String): String {
val headers = Headers.Builder()
headers["Cookie"] = token
headers["User-Agent"] = userAgent
return when (type) {
TwoFactorType.EMAIL_OTP -> {
val result = doRequest(
method = "POST",
url = "$apiBase/auth/twofactorauth/emailotp/verify",
headers = headers.build(),
body = "{\"code\":\"$code\"}"
)
when (result) {
is Response -> {
result.headers["twoFactorAuth"].toString()
}
else -> {
""
}
}
}
TwoFactorType.TOTP -> {
val result = doRequest(
method = "POST",
url = "$apiBase/auth/twofactorauth/totp/verify",
headers = headers.build(),
body = "{\"code\":\"$code\"}"
)
when (result) {
is Response -> {
result.headers["twoFactorAuth"].toString()
}
else -> {
""
}
}
}
TwoFactorType.OTP -> {
"not_implemented"
}
}
}
suspend fun logout(): Boolean {
val headers = Headers.Builder()
headers["Cookie"] = cookies
headers["User-Agent"] = userAgent
val result = doRequest(
method = "PUT",
url = "$apiBase/logout",
headers = headers.build(),
body = null
)
return when (result) {
is Response -> {
true
}
else -> {
false
}
}
}
suspend fun getSelf(): User? {
val headers = Headers.Builder()
headers["Cookie"] = cookies
headers["User-Agent"] = userAgent
val result = doRequest(
method = "GET",
url = "$apiBase/auth/user",
headers = headers.build(),
body = null
)
return when (result) {
is Response -> {
Gson().fromJson(result.body?.string(), User::class.java)
}
else -> {
null
}
}
}
suspend fun getFriends(offline: Boolean = false): Friends? {
val headers = Headers.Builder()
headers["Cookie"] = cookies
headers["User-Agent"] = userAgent
val result = doRequest(
method = "GET",
url = "$apiBase/auth/user/friends?offline=$offline",
headers = headers.build(),
body = null
)
return when (result) {
is Response -> {
Gson().fromJson(result.body?.string(), Friends::class.java)
}
else -> {
null
}
}
}
suspend fun getFriend(userId: String): LimitedUser? {
val headers = Headers.Builder()
headers["Cookie"] = cookies
headers["User-Agent"] = userAgent
val result = doRequest(
method = "GET",
url = "$apiBase/users/$userId",
headers = headers.build(),
body = null
)
return when (result) {
is Response -> {
Gson().fromJson(result.body?.string(), LimitedUser::class.java)
}
else -> {
null
}
}
}
suspend fun getUser(userId: String): LimitedUser? {
val headers = Headers.Builder()
headers["Cookie"] = cookies
headers["User-Agent"] = userAgent
val result = doRequest(
method = "GET",
url = "$apiBase/users/$userId",
headers = headers.build(),
body = null
)
return when (result) {
is Response -> {
Gson().fromJson(result.body?.string(), LimitedUser::class.java)
}
else -> {
null
}
}
}
// Intent is compromised of <worldId>:<InstanceId>:<Nonce>
// NOTE: `<Nonce>` is only used for private instances.
suspend fun getInstance(intent: String): Instance? {
val headers = Headers.Builder()
headers["Cookie"] = cookies
headers["User-Agent"] = userAgent
val result = doRequest(
method = "GET",
url = "$apiBase/instances/$intent",
headers = headers.build(),
body = null
)
return when (result) {
is Response -> {
Gson().fromJson(result.body?.string(), Instance::class.java)
}
else -> {
null
}
}
}
suspend fun getRecentWorlds(): Worlds? {
val headers = Headers.Builder()
headers["Cookie"] = cookies
headers["User-Agent"] = userAgent
val result = doRequest(
method = "GET",
url = "$apiBase/worlds/recent?featured=false",
headers = headers.build(),
body = null
)
return when (result) {
is Response -> {
Gson().fromJson(result.body?.string(), Worlds::class.java)
}
else -> {
null
}
}
}
suspend fun getWorlds(query: String = "", featured: Boolean = false, n: Int = 50, sort: String = "relevance"): Worlds? {
val headers = Headers.Builder()
headers["Cookie"] = cookies
headers["User-Agent"] = userAgent
val result = doRequest(
method = "GET",
url = "$apiBase/worlds?featured=$featured&n=$n&sort=$sort&search=$query",
headers = headers.build(),
body = null
)
return when (result) {
is Response -> {
Gson().fromJson(result.body?.string(), Worlds::class.java)
}
else -> {
null
}
}
}
suspend fun getWorld(id: String): World? {
val headers = Headers.Builder()
headers["Cookie"] = cookies
headers["User-Agent"] = userAgent
val result = doRequest(
method = "GET",
url = "$apiBase/worlds/$id",
headers = headers.build(),
body = null
)
return when (result) {
is Response -> {
Gson().fromJson(result.body?.string(), World::class.java)
}
else -> {
null
}
}
}
suspend fun getAvatars(featured: Boolean = true, n: Int = 50): Avatars? {
val headers = Headers.Builder()
headers["Cookie"] = cookies
headers["User-Agent"] = userAgent
val result = doRequest(
method = "GET",
url = "$apiBase/avatars?featured=$featured&n=$n",
headers = headers.build(),
body = null
)
return when (result) {
is Response -> {
Gson().fromJson(result.body?.string(), Avatars::class.java)
}
else -> {
null
}
}
}
suspend fun getUsers(username: String, n: Int = 50): Users? {
val headers = Headers.Builder()
headers["Cookie"] = cookies
headers["User-Agent"] = userAgent
val result = doRequest(
method = "GET",
url = "$apiBase/users?search=$username&n=$n",
headers = headers.build(),
body = null
)
return when (result) {
is Response -> {
Gson().fromJson(result.body?.string(), Users::class.java)
}
else -> {
null
}
}
}
suspend fun getFavorites(type: String, n: Int = 50): Favorites? {
val headers = Headers.Builder()
headers["Cookie"] = cookies
headers["User-Agent"] = userAgent
val result = doRequest(
method = "GET",
url = "$apiBase/favorites?type=$type&n=$n", // TODO: if ever needed, implement "tag"
headers = headers.build(),
body = null
)
return when (result) {
is Response -> {
Gson().fromJson(result.body?.string(), Favorites::class.java)
}
else -> {
null
}
}
}
suspend fun getNotifications(): Notifications? {
val headers = Headers.Builder()
headers["Cookie"] = cookies
headers["User-Agent"] = userAgent
val result = doRequest(
method = "GET",
url = "$apiBase/auth/user/notifications",
headers = headers.build(),
body = null
)
return when (result) {
is Response -> {
Gson().fromJson(result.body?.string(), Notifications::class.java)
}
else -> {
null
}
}
}
suspend fun selectAvatar(avatarId: String): User? {
val headers = Headers.Builder()
headers["Cookie"] = cookies
headers["User-Agent"] = userAgent
val result = doRequest(
method = "PUT",
url = "$apiBase/avatars/${avatarId}/select",
headers = headers.build(),
body = null
)
return when (result) {
is Response -> {
Gson().fromJson(result.body?.string(), User::class.java)
}
else -> {
null
}
}
}
suspend fun getAvatar(avatarId: String): Avatar? {
val headers = Headers.Builder()
headers["Cookie"] = cookies
headers["User-Agent"] = userAgent
val result = doRequest(
method = "GET",
url = "$apiBase/avatars/${avatarId}",
headers = headers.build(),
body = null
)
return when (result) {
is Response -> {
Gson().fromJson(result.body?.string(), Avatar::class.java)
}
else -> {
null
}
}
}
}
| 1
| null |
3
| 8
|
69b3be86a31fba1bfea5180c82117b49fe31f90e
| 19,041
|
VRCAA
|
Apache License 2.0
|
androidApp/src/androidMain/kotlin/io/github/kabirnayeem99/MainActivity.kt
|
kabirnayeem99
| 718,206,026
| false
|
{"Kotlin": 44631, "Swift": 624, "Shell": 228}
|
package io.github.kabirnayeem99
import MainView
import android.app.Application
import android.content.Context
import android.content.pm.ApplicationInfo
import android.os.Bundle
import androidx.activity.compose.setContent
import androidx.appcompat.app.AppCompatActivity
import core.di.initKoin
import org.koin.android.ext.koin.androidContext
import org.koin.android.ext.koin.androidLogger
import org.koin.core.logger.Level
class IbtisarAlSallahApp : Application() {
override fun onCreate() {
super.onCreate()
initKoin {
androidLogger(if (isDebug()) Level.ERROR else Level.NONE)
androidContext(this@IbtisarAlSallahApp)
}
}
}
fun Context.isDebug() = 0 != applicationInfo.flags and ApplicationInfo.FLAG_DEBUGGABLE
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContent {
MainView()
}
}
}
| 0
|
Kotlin
|
0
| 0
|
113d33a3f1ca8055799ded330654e2cf178e9b21
| 975
|
ibtisar_al_sallah
|
Apache License 2.0
|
app/src/main/java/com/nistruct/sportstat/api/TeamApi.kt
|
StefanT997Dev
| 366,730,025
| false
| null |
package com.nistruct.sportstat.api
import com.nistruct.sportstat.data.models.api_models.TeamResponse
import com.nistruct.sportstat.data.models.api_models.team.PostTeamRequestBody
import retrofit2.http.Body
import retrofit2.http.GET
import retrofit2.http.POST
interface TeamApi {
@GET("api/teams")
suspend fun getTeams(): List<TeamResponse>
@POST("api/team")
suspend fun postTeam(@Body teamRequestBody: PostTeamRequestBody): TeamResponse
}
| 0
|
Kotlin
|
0
| 0
|
69a2fbd6c994bff99db10796248228e1a8da8986
| 457
|
SportStat
|
Apache License 2.0
|
spring-pulsar-core/src/test/kotlin/com/intuit/spring/pulsar/client/config/PulsarClientConfigTest.kt
|
intuit
| 577,001,055
| false
| null |
package com.intuit.spring.pulsar.client.config
import com.intuit.spring.pulsar.client.TestData
import org.junit.jupiter.api.Test
import kotlin.test.assertEquals
import kotlin.test.assertFalse
import kotlin.test.assertNotNull
import kotlin.test.assertTrue
class PulsarClientConfigTest {
@Test
fun `validate auth config creation with all properties set`() {
val auth = TestData.getAuthConfig()
assertEquals(TestData.userName, auth.userName)
assertEquals(TestData.password, auth.password)
auth.password = "<PASSWORD>"
auth.userName = "user"
assertEquals("user", auth.userName)
assertEquals("pass", auth.password)
}
@Test
fun `validate request config creation with all properties set`() {
val request = TestData.getRequestConfig()
assertEquals(TestData.maxLookupRequest, request.maxLookupRequest)
assertEquals(TestData.concurrentLookupRequest, request.concurrentLookupRequest)
assertEquals(TestData.maxNumberOfRejectedRequestPerConnection, request.maxNumberOfRejectedRequestPerConnection)
request.maxLookupRequest = 10
request.concurrentLookupRequest = 10
request.maxNumberOfRejectedRequestPerConnection = 10
assertEquals(10, request.maxLookupRequest)
assertEquals(10, request.concurrentLookupRequest)
assertEquals(10, request.maxNumberOfRejectedRequestPerConnection)
}
@Test
fun `validate request config creation with no properties set`() {
val request = PulsarClientConfig.PulsarRequestConfig()
assertEquals(50000, request.maxLookupRequest)
assertEquals(5000, request.concurrentLookupRequest)
assertEquals(50, request.maxNumberOfRejectedRequestPerConnection)
}
@Test
fun `validate thread pool config with all properties set`() {
val threadPool = TestData.getThreadPoolConfig()
assertEquals(TestData.numIoThreads, threadPool.numIoThreads)
assertEquals(TestData.numListenerThreads, threadPool.numListenerThreads)
threadPool.numIoThreads = 10
threadPool.numListenerThreads = 10
assertEquals(10, threadPool.numIoThreads)
assertEquals(10, threadPool.numListenerThreads)
}
@Test
fun `validate thread pool config with no properties set`() {
val threadPool = PulsarClientConfig.PulsarThreadPoolConfig()
assertEquals(1, threadPool.numIoThreads)
assertEquals(1, threadPool.numListenerThreads)
}
@Test
fun `validate network config creation with all properties set`() {
val network = TestData.getNetworkConfig()
assertEquals(TestData.networkDuration, network.keepAliveInterval)
assertEquals(TestData.networkDuration, network.connectionTimeout)
assertEquals(TestData.networkDuration, network.requestTimeout)
assertEquals(TestData.networkDuration, network.defaultBackoffInterval)
assertEquals(TestData.networkDuration, network.maxBackoffInterval)
assertEquals(TestData.networkDuration, network.operationTimeout)
assertEquals(false, network.useTcpNoDelay)
network.keepAliveInterval = "1s"
network.connectionTimeout = "1s"
network.requestTimeout = "1s"
network.defaultBackoffInterval = "1s"
network.maxBackoffInterval = "1s"
network.operationTimeout = "1s"
network.useTcpNoDelay = true
assertEquals("1s", network.keepAliveInterval)
assertEquals("1s", network.connectionTimeout)
assertEquals("1s", network.requestTimeout)
assertEquals("1s", network.defaultBackoffInterval)
assertEquals("1s", network.maxBackoffInterval)
assertEquals("1s", network.operationTimeout)
assertEquals(true, network.useTcpNoDelay)
}
@Test
fun `validate network config creation with no properties set`() {
val network = PulsarClientConfig.PulsarNetworkConfig()
assertEquals("30s", network.keepAliveInterval)
assertEquals("10000ms", network.connectionTimeout)
assertEquals("60000ms", network.requestTimeout)
assertEquals("100ms", network.defaultBackoffInterval)
assertEquals("30s", network.maxBackoffInterval)
assertEquals("30000ms", network.operationTimeout)
assertEquals(true, network.useTcpNoDelay)
}
@Test
fun `validate tls config creation with all properties set`() {
val tls = TestData.getTlsConfig()
assertFalse(tls.useTls)
assertFalse(tls.tlsAllowInsecureConnection)
assertFalse(tls.tlsHostnameVerificationEnable)
assertEquals(TestData.tlsTrustCertsFilePath, tls.tlsTrustCertsFilePath)
tls.useTls = true
tls.tlsAllowInsecureConnection = true
tls.tlsHostnameVerificationEnable = false
tls.tlsTrustCertsFilePath = "file_path"
assertTrue(tls.useTls)
assertTrue(tls.tlsAllowInsecureConnection)
assertFalse(tls.tlsHostnameVerificationEnable)
assertEquals("file_path", tls.tlsTrustCertsFilePath)
}
@Test
fun `validate tls config creation with no properties set`() {
val tls = PulsarClientConfig.PulsarTlsConfig()
assertEquals(false, tls.useTls)
assertEquals(false, tls.tlsAllowInsecureConnection)
assertEquals(true, tls.tlsHostnameVerificationEnable)
assertEquals("", tls.tlsTrustCertsFilePath)
}
@Test
fun `validate client config creation with all properties set`() {
val client = PulsarClientConfig(
serviceUrl = TestData.serviceUrl,
statsInterval = "100ms",
tls = PulsarClientConfig.PulsarTlsConfig(),
request = PulsarClientConfig.PulsarRequestConfig(),
network = PulsarClientConfig.PulsarNetworkConfig(),
threadPool = PulsarClientConfig.PulsarThreadPoolConfig(),
auth = PulsarClientConfig.PulsarAuthConfig(TestData.userName, TestData.password)
)
assertEquals(TestData.serviceUrl, client.serviceUrl)
assertEquals("100ms", client.statsInterval)
assertNotNull(client.tls)
assertNotNull(client.request)
assertNotNull(client.network)
assertNotNull(client.threadPool)
assertNotNull(client.auth)
client.serviceUrl = "service_url"
client.statsInterval = "10ms"
client.tls = PulsarClientConfig.PulsarTlsConfig()
client.request = PulsarClientConfig.PulsarRequestConfig()
client.auth = PulsarClientConfig.PulsarAuthConfig()
client.network = PulsarClientConfig.PulsarNetworkConfig()
client.threadPool = PulsarClientConfig.PulsarThreadPoolConfig()
assertEquals("service_url", client.serviceUrl)
assertEquals("10ms", client.statsInterval)
assertNotNull(client.tls)
assertNotNull(client.request)
assertNotNull(client.network)
assertNotNull(client.threadPool)
assertNotNull(client.auth)
}
@Test
fun `validate client config creation with mandatory property sets`() {
val client = TestData.getNominalClientConfig()
assertEquals("http://service/url/", client.serviceUrl)
assertEquals("60s", client.statsInterval)
assertNotNull(client.tls)
assertNotNull(client.request)
assertNotNull(client.network)
assertNotNull(client.threadPool)
assertNotNull(client.auth)
}
}
| 8
|
Kotlin
|
4
| 9
|
fff7f2041724ceeb688a15f39df5b7130a7f598a
| 7,426
|
spring-pulsar
|
MIT License
|
jupyter-lib/api/src/main/kotlin/org/jetbrains/kotlinx/jupyter/api/KernelRunMode.kt
|
Kotlin
| 63,066,291
| false
|
{"Kotlin": 1063374, "JavaScript": 40044, "CSS": 16243, "Python": 15441, "Jupyter Notebook": 1290, "Shell": 74}
|
package org.jetbrains.kotlinx.jupyter.api
import org.jetbrains.kotlinx.jupyter.util.FilteringClassLoader
/**
* Represents settings that depend on the environment in which kernel is running
*/
interface KernelRunMode {
val name: String
/**
* Creates an intermediary ClassLoader between the parent classloader (which is
* usually a classloader that loads kernel classpath) and the chain of REPL classloaders,
* including the base one. If null is returned, no intermediate classloader will be used.
*/
fun createIntermediaryClassLoader(parent: ClassLoader): ClassLoader?
val shouldKillProcessOnShutdown: Boolean
val inMemoryOutputsSupported: Boolean
val isRunInsideIntellijProcess: Boolean
val streamSubstitutionType: StreamSubstitutionType
}
abstract class AbstractKernelRunMode(override val name: String) : KernelRunMode {
override fun toString(): String {
return name
}
}
object StandaloneKernelRunMode : AbstractKernelRunMode("Standalone") {
override fun createIntermediaryClassLoader(parent: ClassLoader) = createDefaultFilteringClassLoader(parent)
override val shouldKillProcessOnShutdown: Boolean get() = true
override val inMemoryOutputsSupported: Boolean get() = false
override val isRunInsideIntellijProcess: Boolean get() = false
override val streamSubstitutionType: StreamSubstitutionType
get() = StreamSubstitutionType.BLOCKING
}
object EmbeddedKernelRunMode : AbstractKernelRunMode("Embedded") {
override fun createIntermediaryClassLoader(parent: ClassLoader) = null
override val shouldKillProcessOnShutdown: Boolean get() = false
override val inMemoryOutputsSupported: Boolean get() = false
override val isRunInsideIntellijProcess: Boolean get() = false
override val streamSubstitutionType: StreamSubstitutionType
get() = StreamSubstitutionType.BLOCKING
}
fun createDefaultFilteringClassLoader(parent: ClassLoader): ClassLoader {
return FilteringClassLoader(parent) { fqn ->
listOf(
"jupyter.kotlin.",
"org.jetbrains.kotlinx.jupyter.api",
"kotlin.",
"kotlinx.serialization.",
).any { fqn.startsWith(it) } ||
(fqn.startsWith("org.jetbrains.kotlin.") && !fqn.startsWith("org.jetbrains.kotlinx.jupyter."))
}
}
| 79
|
Kotlin
|
107
| 1,114
|
63dae6f2c5852d7b9a48068c29e3e803ae88c883
| 2,338
|
kotlin-jupyter
|
Apache License 2.0
|
src/jvmMain/kotlin/tools/empathy/libro/server/sessions/oidc/OpenIdConfiguration.kt
|
ontola
| 624,799,212
| false
| null |
@file:UseSerializers(UrlSerializer::class)
package tools.empathy.libro.server.sessions.oidc
import io.ktor.http.Url
import kotlinx.serialization.SerialName
import kotlinx.serialization.Serializable
import kotlinx.serialization.UseSerializers
import tools.empathy.libro.server.util.UrlSerializer
@Serializable
enum class OIDCResponseType {
@SerialName("none")
None,
@SerialName("code")
Code,
@SerialName("token")
Token,
@SerialName("id_token")
IdToken,
@SerialName("id_token token")
IdTokenToken,
}
@Serializable
enum class OIDCResponseMode {
@SerialName("query")
Query,
@SerialName("fragment")
Fragment,
@SerialName("form_post")
FormPost,
}
@Serializable
enum class OIDCGrantType {
@SerialName("authorization_code")
AuthorizationCode,
@SerialName("password")
Password,
@SerialName("client_credentials")
ClientCredentials,
@SerialName("implicit_oidc")
ImplicitOidc,
@SerialName("refresh_token")
RefreshToken,
}
@Serializable
data class OpenIdConfiguration(
val issuer: Url,
@SerialName("authorization_endpoint")
val authorizationEndpoint: Url,
@SerialName("token_endpoint")
val tokenEndpoint: Url,
@SerialName("registration_endpoint")
val registrationEndpoint: Url,
@SerialName("revocation_endpoint")
val revocationEndpoint: Url,
@SerialName("introspection_endpoint")
val introspectionEndpoint: Url,
@SerialName("userinfo_endpoint")
val userinfoEndpoint: Url,
@SerialName("jwks_uri")
val jwksUri: Url,
@SerialName("scopes_supported")
val scopesSupported: List<String>,
@SerialName("response_types_supported")
val responseTypesSupported: List<OIDCResponseType>,
@SerialName("response_modes_supported")
val responseModesSupported: List<OIDCResponseMode>,
@SerialName("grant_types_supported")
val grantTypesSupported: List<OIDCGrantType>,
@SerialName("token_endpoint_auth_methods_supported")
val tokenEndpointAuthMethodsSupported: List<String>,
@SerialName("subject_types_supported")
val subjectTypesSupported: List<String>,
@SerialName("id_token_signing_alg_values_supported")
val idTokenSigningAlgValuesSupported: List<String>,
@SerialName("claim_types_supported")
val claimTypesSupported: List<String>,
@SerialName("claims_supported")
val claimsSupported: List<String>,
)
| 0
|
Kotlin
|
0
| 0
|
2e9fa6622e00ebf5ffd1cf6156e8abd774430f7e
| 2,424
|
libro-cache
|
MIT License
|
domain/src/commonMain/kotlin/ireader/domain/usecases/preferences/reader_preferences/screens/LibraryScreenPrefUseCases.kt
|
kazemcodes
| 540,829,865
| false
| null |
package ireader.domain.usecases.preferences.reader_preferences.screens
import ireader.domain.usecases.preferences.reader_preferences.LibraryLayoutTypeUseCase
import ireader.domain.usecases.preferences.reader_preferences.SortersDescUseCase
import ireader.domain.usecases.preferences.reader_preferences.SortersUseCase
data class LibraryScreenPrefUseCases(
val libraryLayoutTypeUseCase: LibraryLayoutTypeUseCase,
val sortersDescUseCase: SortersDescUseCase,
val sortersUseCase: SortersUseCase,
)
| 10
| null |
14
| 6
|
b6b2414fa002cec2aa0d199871fcfb4c2e190a8f
| 527
|
IReader
|
Apache License 2.0
|
sudoemail/src/main/java/com/sudoplatform/sudoemail/types/DraftEmailMessage.kt
|
sudoplatform
| 303,299,846
| false
|
{"Kotlin": 916120}
|
/*
* Copyright © 2024 <NAME>, Inc. All rights reserved.
*
* SPDX-License-Identifier: Apache-2.0
*/
package com.sudoplatform.sudoemail.types
import java.util.Date
/**
* Representation of the metadata of a draft email message in the Sudo Platform Email SDK.
*
* @property id [String] Unique identifier of the draft message.
* @property updatedAt [Date] When the draft message was last updated.
*/
internal interface DraftEmailMessage {
val id: String
val updatedAt: Date
}
| 0
|
Kotlin
|
0
| 1
|
8455c546e63488ad9d26f2e98caef73c6e053b4f
| 491
|
sudo-email-android
|
Apache License 2.0
|
app/src/main/kotlin/com/healthmetrix/myscience/feature/statistics/StatisticsModule.kt
|
smart4health
| 593,624,354
| false
| null |
package com.healthmetrix.myscience.feature.statistics
import android.content.Context
import androidx.datastore.core.DataStore
import androidx.datastore.dataStore
import com.healthmetrix.myscience.commons.di.DataStoreWrapper
import dagger.Module
import dagger.Provides
import dagger.hilt.InstallIn
import dagger.hilt.android.qualifiers.ApplicationContext
import dagger.hilt.components.SingletonComponent
import javax.inject.Singleton
@Module
@InstallIn(SingletonComponent::class)
object StatisticsModule {
@Provides
@Singleton
fun provideStatsDataStore(
@ApplicationContext
applicationContext: Context,
): DataStore<StatsSettings> {
val dataStore = dataStore(
fileName = "stats.pb",
serializer = StatsSettingsSerializer,
)
return DataStoreWrapper(applicationContext, dataStore)
}
}
| 0
|
Kotlin
|
0
| 1
|
b18ef21ef3ae24f2a0bcace9cf6b5279ab6746e2
| 869
|
my-science-app
|
MIT License
|
app/src/main/java/br/com/angelorobson/templatemvi/model/builders/GameEntityBuilder.kt
|
angelorobsonmelo
| 276,738,007
| true
|
{"Kotlin": 162806}
|
import br.com.angelorobson.templatemvi.model.entities.GameEntity
import kotlin.random.Random
class GameEntityBuilder {
data class Builder(
private var idGame: Int = 0,
private var title: String = "",
private var image: String = "",
private var discount: Double = 0.0,
private var price: Double = 0.0
) {
fun idGame(idGame: Int) =
apply { this.idGame = idGame }
fun title(title: String) = apply { this.title = title }
fun image(image: String) = apply { this.image = image }
fun discount(discount: Double) = apply { this.discount = discount }
fun price(price: Double) = apply { this.price = price }
fun oneGameEntity() = apply {
idGame = Random(50).nextInt()
title = "The Legend Of Zelda Breath of The Wild"
image = "fs"
discount = 100.0
price = 350.0
}
fun build() = GameEntity(
idGame = idGame,
title = title,
image = image,
discount = discount,
price = price
)
}
}
| 0
|
Kotlin
|
0
| 0
|
4a2dd31d1637b0b4196ae1a42d453052b1c0bd1e
| 1,171
|
mobile-android-challenge
|
MIT License
|
platform/vcs-impl/src/com/intellij/vcs/commit/ToggleChangesViewCommitUiAction.kt
|
hieuprogrammer
| 284,920,751
| false
| null |
// Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.vcs.commit
import com.intellij.openapi.actionSystem.AnActionEvent
import com.intellij.openapi.actionSystem.IdeActions.ACTION_CHECKIN_PROJECT
import com.intellij.openapi.actionSystem.ex.ActionUtil.copyFrom
import com.intellij.openapi.project.DumbAwareToggleAction
import com.intellij.openapi.util.registry.Registry
import com.intellij.openapi.vcs.actions.CommonCheckinProjectAction
import com.intellij.openapi.vcs.actions.getProjectCommitWorkflowHandler
import com.intellij.openapi.vcs.actions.isFromLocalChanges
import com.intellij.openapi.vcs.actions.isProjectUsesNonModalCommit
internal val isToggleCommitUi = Registry.get("vcs.non.modal.commit.toggle.ui")
private class ToggleChangesViewCommitUiAction : DumbAwareToggleAction() {
// need to use `CommonCheckinProjectAction` inheritor - otherwise action is invisible in Local Changes
private val commitProjectAction = object : CommonCheckinProjectAction() {}
init {
copyFrom(this, ACTION_CHECKIN_PROJECT)
}
override fun update(e: AnActionEvent) {
super.update(e)
when {
!e.isProjectUsesNonModalCommit() || !isToggleCommitUi.asBoolean() || !e.isFromLocalChanges() ->
e.presentation.isEnabledAndVisible = false
isSelected(e) -> e.presentation.isEnabledAndVisible = true
else -> commitProjectAction.update(e)
}
}
override fun isSelected(e: AnActionEvent): Boolean = e.getProjectCommitWorkflowHandler()?.isActive == true
override fun setSelected(e: AnActionEvent, state: Boolean) =
if (state) {
commitProjectAction.actionPerformed(e)
}
else {
e.getProjectCommitWorkflowHandler()!!.deactivate(false)
}
}
| 1
| null |
1
| 2
|
dc846ecb926c9d9589c1ed8a40fdb20e47874db9
| 1,807
|
intellij-community
|
Apache License 2.0
|
src/dev/ky3he4ik/battleship_server/Client.kt
|
Ky3He4iK
| 264,867,305
| false
| null |
package dev.ky3he4ik.battleship_server
import br.com.devsrsouza.redissed.RedisObject
import br.com.devsrsouza.redissed.RedissedCommands
import org.java_websocket.WebSocket
import java.net.InetAddress
class Client(name: String, uuid: Long, var connection: WebSocket, database: String, commands: RedissedCommands) {
var lastAccess = System.currentTimeMillis()
class ClientInfo(name: String, uuid: Long, database: String, commands: RedissedCommands) : RedisObject(database, commands) {
val name: String by string(name)
val uuid: Long by long(uuid)
var isAdmin: Boolean by boolean(false)
}
val clientInfo = ClientInfo(name, uuid, "$database:$name", commands)
init {
if (name == "admin") {
for (addr in adminWhitelist)
if (connection.remoteSocketAddress.address.address?.contentEquals(addr) == true)
clientInfo.isAdmin = true
}
}
fun isAlive() = System.currentTimeMillis() - lastAccess < 10_000 // 10 seconds before disconnect
fun update() {
lastAccess = System.currentTimeMillis()
}
companion object {
val adminWhitelist = arrayListOf(
byteArrayOf(127, 0, 0, 1),
InetAddress.getLocalHost().address,
InetAddress.getLoopbackAddress().address,
byteArrayOf(193.toByte(), 38, 54, 97),
byteArrayOf(10, 8, 0, 2)
)
}
}
| 0
|
Kotlin
|
0
| 0
|
e151eb35812d52bc5d4162a7b40c696bbf7857b5
| 1,432
|
battleship_server
|
The Unlicense
|
android/src/com/android/tools/idea/run/deployment/selector/PopupActionGroup.kt
|
JetBrains
| 60,701,247
| false
| null |
/*
* Copyright (C) 2020 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.android.tools.idea.run.deployment.selector
import com.android.tools.idea.adb.wireless.PairDevicesUsingWiFiAction
import com.android.tools.idea.run.deployment.Heading
import com.intellij.openapi.actionSystem.ActionManager
import com.intellij.openapi.actionSystem.AnAction
import com.intellij.openapi.actionSystem.DefaultActionGroup
import com.intellij.openapi.actionSystem.Separator
internal class ActionGroupSection(val headingActionId: String?, val actions: List<AnAction>)
internal fun DefaultActionGroup.addSection(section: ActionGroupSection) {
section.headingActionId
?.let { ActionManager.getInstance().getAction(it) }
?.let { add(Separator(it.templateText)) }
addAll(section.actions)
}
internal fun createActionGroup(vararg sections: ActionGroupSection): DefaultActionGroup =
DefaultActionGroup().apply {
val presentSections = sections.filter { it.actions.isNotEmpty() }
presentSections.firstOrNull()?.let { addSection(it) }
for (section in presentSections.drop(1)) {
addSeparator()
addSection(section)
}
}
internal fun createDeviceSelectorActionGroup(
devices: List<DeploymentTargetDevice>
): DefaultActionGroup {
val actionManager = ActionManager.getInstance()
return createActionGroup(
ActionGroupSection(
Heading.RUNNING_DEVICES_ID,
devices.filter { it.isConnected }.map { SelectDeviceAction(it) },
),
ActionGroupSection(
Heading.AVAILABLE_DEVICES_ID,
devices
.filterNot { it.isConnected }
.map {
when {
it.snapshots.isNotEmpty() -> SnapshotActionGroup(it)
else -> SelectDeviceAction(it)
}
},
),
ActionGroupSection(
null,
listOfNotNull(
actionManager.getAction(SelectMultipleDevicesAction.ID),
actionManager.getAction(PairDevicesUsingWiFiAction.ID),
actionManager.getAction("Android.DeviceManager"),
),
),
ActionGroupSection(
null,
listOfNotNull(actionManager.getAction("DeveloperServices.ConnectionAssistant")),
),
)
}
| 5
| null |
227
| 948
|
10110983c7e784122d94c7467e9d243aba943bf4
| 2,698
|
android
|
Apache License 2.0
|
app/src/main/java/com/syleiman/gingermoney/ui/common/mvvm/FragmentBase.kt
|
AlShevelev
| 158,343,218
| false
|
{"Gradle": 4, "Java Properties": 2, "Shell": 1, "Text": 1, "Ignore List": 3, "Batchfile": 1, "Markdown": 1, "Proguard": 2, "Java": 4, "XML": 137, "Kotlin": 385, "JSON": 1}
|
package com.syleiman.gingermoney.ui.common.mvvm
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.annotation.LayoutRes
import androidx.appcompat.app.AlertDialog
import androidx.databinding.DataBindingUtil
import androidx.databinding.ViewDataBinding
import androidx.fragment.app.Fragment
import androidx.lifecycle.ViewModelProviders
import com.syleiman.gingermoney.R
import com.syleiman.gingermoney.core.utils.app_resources.AppResourcesProvider
import com.syleiman.gingermoney.ui.common.mvvm.displaying_errors.GeneralError
import com.syleiman.gingermoney.ui.common.ui_utils.UIUtils
import com.syleiman.gingermoney.ui.common.mvvm.view_commands.ShowErrorCommand
import com.syleiman.gingermoney.ui.common.mvvm.view_commands.ViewCommand
import javax.inject.Inject
/**
* Base class for all fragments
*/
abstract class FragmentBase<TB: ViewDataBinding, TM: ModelBase, TVM: ViewModelBase<TM>> : Fragment() {
private lateinit var binding: TB
private lateinit var _viewModel: TVM
protected val viewModel: TVM
get() = _viewModel
protected var activeDialog: AlertDialog? = null
@Inject
internal lateinit var resourcesProvider: AppResourcesProvider
@Inject
internal lateinit var uiUtils: UIUtils
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
inject()
_viewModel = ViewModelProviders.of(this).get(provideViewModelType())
}
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
_viewModel.command.observe({viewLifecycleOwner.lifecycle}) {
if(!processViewCommandGeneral(it)) {
processViewCommand(it)
}
}
observeViewModel(_viewModel)
binding = DataBindingUtil.inflate(inflater, provideLayout(), container, false)
binding.lifecycleOwner = this
linkViewModel(binding, _viewModel)
return binding.root
}
override fun onDestroyView() {
super.onDestroyView()
// Close a dialog to avoid leak of view
activeDialog?.takeIf { it.isShowing }?.dismiss()
activeDialog = null
}
override fun onDestroy() {
super.onDestroy()
releaseInjection()
}
abstract fun provideViewModelType(): Class<TVM>
@LayoutRes
protected abstract fun provideLayout(): Int
protected abstract fun inject()
protected open fun releaseInjection() {}
protected open fun observeViewModel(viewModel: TVM) {}
protected abstract fun linkViewModel(binding: TB, viewModel: TVM)
protected open fun processViewCommand(command: ViewCommand) {}
/**
* Process input command
* @return true if the command has been processed
*/
private fun processViewCommandGeneral(command: ViewCommand): Boolean {
when(command) {
is ShowErrorCommand -> {
when(command.error) {
is GeneralError -> {
uiUtils.showError(resourcesProvider.getString(R.string.commonGeneralError))
return true
}
}
}
}
return false
}
}
| 1
| null |
1
| 1
|
91ef2b9bd5c19043104734b588940841fa6f9f4f
| 3,292
|
ginger-money
|
MIT License
|
extension/registry/apicurio-rest/src/main/kotlin/type/ApicurioSchemaData.kt
|
holixon
| 354,810,047
| false
| null |
package io.holixon.avro.adapter.registry.apicurio.type
import io.holixon.avro.adapter.api.AvroSchemaId
import io.holixon.avro.adapter.api.AvroSchemaRevision
import io.holixon.avro.adapter.api.AvroSchemaWithId
import org.apache.avro.Schema
data class ApicurioSchemaData(
val metaData: ApicurioArtifactMetaData,
val apicurioArtifactId: String = metaData.id,
override val schemaId: AvroSchemaId = requireNotNull(metaData.schemaIdProperty) { "schemaId property is null "},
override val namespace: String = requireNotNull(metaData.namespaceProperty) { "namespace property is null "},
override val name: String = requireNotNull(metaData.nameProperty){ "name property is null "},
override val revision: AvroSchemaRevision? = metaData.revisionProperty,
override val schema: Schema,
) : AvroSchemaWithId
| 4
|
Kotlin
|
0
| 4
|
85bd4012adbbab5d3721d87a256cda63958d1a6a
| 811
|
avro-registry-adapter
|
Apache License 2.0
|
app/src/main/java/ru/monkeys/monkeyapp/dialog/LvlDialog.kt
|
metalink94
| 163,214,286
| false
|
{"Java": 60064, "Kotlin": 37600}
|
package ru.monkeys.monkeyapp.dialog
import android.graphics.Color
import android.graphics.drawable.ColorDrawable
import android.os.Bundle
import android.support.v4.app.DialogFragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.view.Window
import kotlinx.android.synthetic.main.lvl_dialog.*
import ru.monkeys.monkeyapp.R
class LvlDialog : DialogFragment() {
var listener: LvlDialogListener? = null
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
dialog.requestWindowFeature(Window.FEATURE_NO_TITLE)
dialog.window.setBackgroundDrawable(ColorDrawable(Color.TRANSPARENT))
return inflater.inflate(R.layout.lvl_dialog, container)
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
val key = arguments?.getSerializable(KEY_ENUM) as LvlEnum?
setText(key)
cancel.setOnClickListener {
dismissAllowingStateLoss()
}
accept.setOnClickListener {
listener?.onAcceptClick(arguments?.getSerializable(KEY_ENUM) as LvlEnum?)
dismissAllowingStateLoss()
}
}
private fun setText(key: LvlEnum?) {
if (key == null) return
title.text = when (key) {
LvlEnum.FIRST -> getString(R.string.first_lvl)
LvlEnum.SECOND -> getString(R.string.second_lvl)
LvlEnum.THIRD -> getString(R.string.third_lvl)
}
}
companion object {
private val KEY_ENUM = "enum"
fun getInstance(enum: LvlEnum): LvlDialog = LvlDialog().apply {
arguments = Bundle().apply {
putSerializable(KEY_ENUM, enum)
}
}
}
}
interface LvlDialogListener {
fun onAcceptClick(lvlEnum: LvlEnum?)
}
enum class LvlEnum {
FIRST,
SECOND,
THIRD
}
| 1
| null |
1
| 1
|
a77f648ac675d96ac447c1b36f083fef4a3fbf6a
| 1,962
|
MonkeyApp
|
Apache License 2.0
|
src/main/java/com/sayzen/campfiresdk/screens/activities/quests/SQuestsList.kt
|
timas130
| 443,351,244
| true
|
{"Kotlin": 1939317}
|
package com.sayzen.campfiresdk.screens.activities.quests
import com.dzen.campfire.api.API_TRANSLATE
import com.sayzen.campfiresdk.R
import com.sayzen.campfiresdk.controllers.t
import com.sup.dev.android.libs.screens.Screen
import com.sup.dev.android.libs.screens.navigator.Navigator
import com.sup.dev.android.views.settings.Settings
class SQuestsList : Screen(R.layout.screen_quests_list) {
private val vRelayRace: Settings = findViewById(R.id.vRelayRace)
private val vRubrics: Settings = findViewById(R.id.vRubrics)
init {
disableNavigation()
disableShadows()
setTitle(t(API_TRANSLATE.app_activities))
vRelayRace.setTitle("Класический новогодний квест")
vRelayRace.setOnClickListener { Navigator.to(SQuestNewYear()) }
vRubrics.setTitle("Однажды зимней ночью")
vRubrics.setSubtitle("Квест от пользователей Campfire")
vRubrics.setOnClickListener { Navigator.to(SQuestDanTank()) }
}
}
| 0
|
Kotlin
|
0
| 0
|
9605c9fd8647477e3d6ef0fcd2dcb33229db8dd4
| 973
|
CampfireSDK
|
Apache License 2.0
|
mobile/src/main/java/co/uk/kenkwok/tulipmania/TulipManiaApplication.kt
|
kennethkwok
| 108,638,140
| false
| null |
package co.uk.kenkwok.tulipmania
import android.app.Activity
import android.app.Application
import android.app.Service
import android.content.Intent
import co.uk.kenkwok.tulipmania.dagger.DaggerAppComponent
import co.uk.kenkwok.tulipmania.service.BitfinexService
import dagger.android.AndroidInjector
import dagger.android.DispatchingAndroidInjector
import dagger.android.HasActivityInjector
import dagger.android.HasServiceInjector
import javax.inject.Inject
/**
* Created by kekwok on 11/09/2017.
*/
class TulipManiaApplication : Application(), HasActivityInjector, HasServiceInjector {
@Inject lateinit var mActivityDispatchingAndroidInjector: DispatchingAndroidInjector<Activity>
@Inject lateinit var mServiceDispatchingAndroidInjector: DispatchingAndroidInjector<Service>
override fun activityInjector(): AndroidInjector<Activity>? {
return mActivityDispatchingAndroidInjector
}
override fun serviceInjector(): AndroidInjector<Service> {
return mServiceDispatchingAndroidInjector
}
override fun onCreate() {
super.onCreate()
DaggerAppComponent
.builder()
.application(this)
.build()
.inject(this)
startService(Intent(this, BitfinexService::class.java))
}
}
| 1
| null |
1
| 1
|
b034e7c3c8678d9e8c475ad8dafd4d005cee67ab
| 1,309
|
tulipmania
|
Creative Commons Attribution 3.0 Unported
|
idea/tests/testData/quickfix/autoImports/importFunctionWithDefinitelyNotNullType.before.Main.kt
|
JetBrains
| 278,369,660
| false
| null |
// "Import extension function 'defNotNull'" "true"
// ERROR: Unresolved reference: defNotNull
// COMPILER_ARGUMENTS: -XXLanguage:+DefinitelyNonNullableTypes
package pckg.useSite
import pckg.dep.defNotNull
fun test() {
"x".<caret>defNotNull("x")
}
| 233
| null |
4912
| 82
|
cc81d7505bc3e9ad503d706998ae8026c067e838
| 252
|
intellij-kotlin
|
Apache License 2.0
|
src/main/kotlin/net/prosavage/factionsx/persist/data/wrappers/Warp.kt
|
ryderbelserion
| 669,875,997
| false
| null |
package net.prosavage.factionsx.persist.data.wrappers
data class Warp(val name: String, val password: String?, val dataLocation: DataLocation) {
fun hasPassword(): Boolean {
return password != null
}
}
| 0
|
Kotlin
|
0
| 0
|
b63ad83b36d434e3b827d3e074d0e13e9ef42929
| 221
|
Factions
|
MIT License
|
src/main/java/com/example/workflow/configuration/CamundaConfiguration.kt
|
sourabhparsekar
| 396,739,738
| false
| null |
package com.example.workflow.configuration
import com.example.workflow.model.FileFormFieldType
import org.camunda.bpm.engine.spring.SpringProcessEngineConfiguration
import org.camunda.bpm.spring.boot.starter.configuration.impl.AbstractCamundaConfiguration
import org.springframework.stereotype.Component
@Component
class CamundaConfiguration : AbstractCamundaConfiguration() {
override fun preInit(processEngineConfiguration: SpringProcessEngineConfiguration?) {
super.preInit(processEngineConfiguration)
processEngineConfiguration?.customFormTypes?.add(FileFormFieldType())
}
}
| 0
|
Kotlin
|
0
| 2
|
cb8a6feaf6c1372b62dfe0d3150b941d35daaa00
| 606
|
camunda-ocr
|
Apache License 2.0
|
vector/src/main/java/im/vector/preference/AddressPreference.kt
|
LiMium
| 119,702,511
| true
|
{"Java": 2804410, "Kotlin": 1162710, "JavaScript": 141316, "HTML": 21094, "Shell": 18894}
|
/*
* Copyright 2018 New Vector Ltd
*
* 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 ms.messageapp.preference
import android.content.Context
import android.support.v7.preference.PreferenceViewHolder
import android.util.AttributeSet
import android.view.View
import android.widget.ImageView
import ms.messageapp.R
/**
* Preference used in Room setting for Room aliases
*/
class AddressPreference : VectorPreference {
// members
private var mMainAddressIconView: ImageView? = null
private var mIsMainIconVisible = false
/**
* @return the main icon view.
*/
val mainIconView: View?
get() = mMainAddressIconView
constructor(context: Context) : super(context)
constructor(context: Context, attrs: AttributeSet) : super(context, attrs)
constructor(context: Context, attrs: AttributeSet, defStyle: Int) : super(context, attrs, defStyle)
init {
widgetLayoutResource = R.layout.vector_settings_address_preference
}
override fun onBindViewHolder(holder: PreferenceViewHolder) {
super.onBindViewHolder(holder)
val view = holder.itemView
mMainAddressIconView = view.findViewById(R.id.main_address_icon_view)
mMainAddressIconView!!.visibility = if (mIsMainIconVisible) View.VISIBLE else View.GONE
}
/**
* Set the main address icon visibility.
*
* @param isVisible true to display the main icon
*/
fun setMainIconVisible(isVisible: Boolean) {
mIsMainIconVisible = isVisible
mMainAddressIconView?.visibility = if (mIsMainIconVisible) View.VISIBLE else View.GONE
}
}
| 3
|
Java
|
4
| 44
|
09bf4c527429fe2c8283c71988efa5796dcc854b
| 2,140
|
mini-vector-android
|
Apache License 2.0
|
dsl/src/main/kotlin/io/cloudshiftdev/awscdkdsl/services/kinesisfirehose/CfnDeliveryStreamProcessorParameterPropertyDsl.kt
|
cloudshiftinc
| 667,063,030
| false
|
{"Kotlin": 63959868}
|
@file:Suppress(
"RedundantVisibilityModifier",
"RedundantUnitReturnType",
"RemoveRedundantQualifierName",
"unused",
"UnusedImport",
"ClassName",
"REDUNDANT_PROJECTION",
"DEPRECATION"
)
package io.cloudshiftdev.awscdkdsl.services.kinesisfirehose
import io.cloudshiftdev.awscdkdsl.common.CdkDslMarker
import kotlin.String
import software.amazon.awscdk.services.kinesisfirehose.CfnDeliveryStream
/**
* The `ProcessorParameter` property specifies a processor parameter in a data processor for an
* Amazon Kinesis Data Firehose delivery stream.
*
* Example:
* ```
* // The code below shows an example of how to instantiate this type.
* // The values are placeholders you should change.
* import software.amazon.awscdk.services.kinesisfirehose.*;
* ProcessorParameterProperty processorParameterProperty = ProcessorParameterProperty.builder()
* .parameterName("parameterName")
* .parameterValue("parameterValue")
* .build();
* ```
*
* [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-kinesisfirehose-deliverystream-processorparameter.html)
*/
@CdkDslMarker
public class CfnDeliveryStreamProcessorParameterPropertyDsl {
private val cdkBuilder: CfnDeliveryStream.ProcessorParameterProperty.Builder =
CfnDeliveryStream.ProcessorParameterProperty.builder()
/**
* @param parameterName The name of the parameter. Currently the following default values are
* supported: 3 for `NumberOfRetries` and 60 for the `BufferIntervalInSeconds` . The
* `BufferSizeInMBs` ranges between 0.2 MB and up to 3MB. The default buffering hint is 1MB
* for all destinations, except Splunk. For Splunk, the default buffering hint is 256 KB.
*/
public fun parameterName(parameterName: String) {
cdkBuilder.parameterName(parameterName)
}
/** @param parameterValue The parameter value. */
public fun parameterValue(parameterValue: String) {
cdkBuilder.parameterValue(parameterValue)
}
public fun build(): CfnDeliveryStream.ProcessorParameterProperty = cdkBuilder.build()
}
| 3
|
Kotlin
|
0
| 3
|
c59c6292cf08f0fc3280d61e7f8cff813a608a62
| 2,121
|
awscdk-dsl-kotlin
|
Apache License 2.0
|
product/web3modal/src/main/kotlin/com/walletconnect/web3/modal/utils/EthUtils.kt
|
WalletConnect
| 435,951,419
| false
|
{"Kotlin": 2502705, "Java": 4366, "Shell": 1892}
|
package com.walletconnect.web3.modal.utils
@Deprecated("com.walletconnect.web3.modal.utils.EthUtils has been deprecated. Please use com.reown.appkit.utils.EthUtils instead from - https://github.com/reown-com/reown-kotlin")
object EthUtils {
const val walletSwitchEthChain = "wallet_switchEthereumChain"
const val walletAddEthChain = "wallet_addEthereumChain"
val ethRequiredMethods = listOf(
"personal_sign",
"eth_signTypedData",
"eth_sendTransaction",
)
val ethOptionalMethods = listOf(walletSwitchEthChain, walletAddEthChain)
val ethMethods = ethRequiredMethods + ethOptionalMethods
const val chainChanged = "chainChanged"
const val accountsChanged = "accountsChanged"
val ethEvents = listOf(chainChanged, accountsChanged)
}
| 78
|
Kotlin
|
71
| 199
|
e373c535d7cefb2f932368c79622ac05763b411a
| 794
|
WalletConnectKotlinV2
|
Apache License 2.0
|
Sushi/app/src/main/java/com/destructo/sushi/ui/anime/upcomingAnime/UpcomingAnimeFragment.kt
|
destructo570
| 302,356,237
| false
| null |
package com.destructo.sushi.ui.anime.upcomingAnime
import android.content.SharedPreferences
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ProgressBar
import androidx.appcompat.widget.Toolbar
import androidx.core.os.bundleOf
import androidx.fragment.app.viewModels
import androidx.navigation.findNavController
import androidx.navigation.fragment.findNavController
import androidx.preference.PreferenceManager
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.destructo.sushi.ANIME_ID_ARG
import com.destructo.sushi.DEFAULT_PAGE_LIMIT
import com.destructo.sushi.NSFW_TAG
import com.destructo.sushi.R
import com.destructo.sushi.adapter.AnimeRankingAdapter
import com.destructo.sushi.databinding.FragmentUpcomingAnimeBinding
import com.destructo.sushi.listener.ListEndListener
import com.destructo.sushi.listener.MalIdListener
import com.destructo.sushi.network.Status
import com.destructo.sushi.ui.base.BaseFragment
import com.destructo.sushi.util.GridSpacingItemDeco
import dagger.hilt.android.AndroidEntryPoint
import kotlinx.android.synthetic.main.fragment_upcoming_anime.view.*
import timber.log.Timber
import javax.inject.Inject
@AndroidEntryPoint
class UpcomingAnimeFragment : BaseFragment(), ListEndListener {
private val upcomingAnimeViewModel:UpcomingAnimeViewModel by viewModels()
private lateinit var binding:FragmentUpcomingAnimeBinding
private lateinit var upcomingAdapter:AnimeRankingAdapter
private lateinit var upcomingAnimeRecycler:RecyclerView
private lateinit var toolbar: Toolbar
private lateinit var upcomingAnimeProgress:ProgressBar
private lateinit var upcomingAnimePaginationProgress:ProgressBar
@Inject
lateinit var sharedPref: SharedPreferences
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
sharedPref = PreferenceManager.getDefaultSharedPreferences(context)
if(savedInstanceState == null){
upcomingAnimeViewModel.clearList()
upcomingAnimeViewModel.getUpcomingList(null,
DEFAULT_PAGE_LIMIT,
sharedPref.getBoolean(NSFW_TAG, false))
}
}
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View {
binding = FragmentUpcomingAnimeBinding
.inflate(inflater, container, false).apply {
lifecycleOwner = viewLifecycleOwner
}
upcomingAnimeRecycler = binding.root.upcomingAnimeRecyclerMain
upcomingAnimeRecycler.apply {
layoutManager = GridLayoutManager(context,3)
addItemDecoration(GridSpacingItemDeco(3,25,true))
}
toolbar = binding.toolbar
upcomingAnimeProgress = binding.upcomingAnimeProgressbar
upcomingAnimePaginationProgress = binding.upcomingPaginationProgress
return binding.root
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
setupToolbar()
upcomingAdapter = AnimeRankingAdapter(MalIdListener {
it?.let { navigateToAnimeDetails(it) }
})
upcomingAdapter.setListEndListener(this)
upcomingAnimeRecycler.adapter = upcomingAdapter
upcomingAnimeViewModel.upcomingList.observe(viewLifecycleOwner){ resource->
when(resource.status){
Status.LOADING->{
upcomingAnimeProgress.visibility = View.VISIBLE
}
Status.SUCCESS->{
upcomingAnimeProgress.visibility = View.GONE
}
Status.ERROR->{
Timber.e("Error: %s", resource.message)
}
}
}
upcomingAnimeViewModel.nextPage.observe(viewLifecycleOwner){ resource->
when(resource.status){
Status.LOADING->{
upcomingAnimePaginationProgress.visibility = View.VISIBLE
}
Status.SUCCESS->{
upcomingAnimePaginationProgress.visibility = View.GONE
}
Status.ERROR->{
Timber.e("Error: %s", resource.message)
}
}
}
upcomingAnimeViewModel.upcomingAnimeList.observe(viewLifecycleOwner){
upcomingAdapter.submitList(it)
}
}
private fun navigateToAnimeDetails(animeMalId: Int){
this.findNavController().navigate(
R.id.animeDetailFragment,
bundleOf(Pair(ANIME_ID_ARG, animeMalId)),
getAnimNavOptions()
)
}
private fun setupToolbar(){
toolbar.setNavigationOnClickListener {view->
view.findNavController().navigateUp()
}
}
override fun onEndReached(position: Int) {
upcomingAnimeViewModel.getNextPage(sharedPref.getBoolean(NSFW_TAG, false))
}
}
| 3
|
Kotlin
|
5
| 21
|
68317c04caa596103d3fd32b0f34fe43b189a721
| 5,052
|
Sushi-Unofficial-MAL-Client
|
Apache License 2.0
|
data/src/main/java/com/dehboxturtle/data/di/modules/NetModule.kt
|
dehboxturtle
| 289,759,994
| true
|
{"Kotlin": 146460}
|
package com.dehboxturtle.data.di.modules
import android.content.Context
import com.google.gson.Gson
import com.dehboxturtle.data.di.providers.NetworkChecker
import com.dehboxturtle.data.net.OkHttpClientFactory
import com.dehboxturtle.data.net.RetrofitFactory
import dagger.Module
import dagger.Provides
import retrofit2.Retrofit
import javax.inject.Singleton
/**
* Copyright (C) 2020 Salvador Martinez
* Licensed under the Apache License Version 2.0
* Dagger module that provides Net class.
*/
@Module
class NetModule {
@Provides
@Singleton
internal fun provideGson(): Gson = Gson()
@Provides
@Singleton
internal fun provideNetworkChecker(context: Context): NetworkChecker = NetworkChecker(context)
@Provides
@Singleton
internal fun provideOkHttpClientFactory(): OkHttpClientFactory = OkHttpClientFactory()
@Provides
@Singleton
internal fun provideRetrofit(
context: Context,
gson: Gson,
okHttpClientFactory: OkHttpClientFactory
): Retrofit =
RetrofitFactory.getRetrofit(context, gson, okHttpClientFactory)
}
| 0
|
Kotlin
|
0
| 0
|
e5c2a00c67d198c21cd052a5e45be5dce375ac96
| 1,103
|
CleanRxNotes
|
Apache License 2.0
|
app/src/androidTest/kotlin/org/andstatus/app/net/social/ConnectionStub.kt
|
andstatus
| 3,040,264
| false
|
{"Kotlin": 3385973, "XSLT": 14655, "HTML": 14046, "CSS": 4427, "Shell": 707}
|
/*
* Copyright (C) 2018 yvolk (<NAME>), http://yurivolkov.com
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.andstatus.app.net.social
import org.andstatus.app.account.AccountConnectionData
import org.andstatus.app.account.MyAccount
import org.andstatus.app.context.DemoData
import org.andstatus.app.context.MyContextHolder.Companion.myContextHolder
import org.andstatus.app.context.TestSuite
import org.andstatus.app.net.http.HttpConnection
import org.andstatus.app.net.http.HttpConnectionOAuthStub
class ConnectionStub private constructor(val connection: Connection) {
val data: AccountConnectionData get() = connection.data
val http: HttpConnectionOAuthStub get() = getHttpStub(connection.oauthHttpOrThrow)
companion object {
fun newFor(accountName: String?): ConnectionStub {
return newFor(DemoData.demoData.getMyAccount(accountName))
}
fun newFor(myAccount: MyAccount): ConnectionStub {
TestSuite.setHttpConnectionStubClass(HttpConnectionOAuthStub::class.java)
myAccount.setConnection()
TestSuite.setHttpConnectionStubClass(null)
return ConnectionStub(myAccount.connection)
}
private fun getHttpStub(http: HttpConnection): HttpConnectionOAuthStub {
if (http is HttpConnectionOAuthStub) return http
val myContext = myContextHolder.getNow()
myContext.httpConnectionStub
throw IllegalStateException("getHttpStub: http is " + http::class.qualifiedName + ", " + myContext)
}
}
}
| 86
|
Kotlin
|
69
| 306
|
6166aded1f115e6e6a7e66ca3756f39f0434663e
| 2,086
|
andstatus
|
Apache License 2.0
|
kotlin-antd/antd-samples/src/main/kotlin/samples/layout/Basic.kt
|
rbargues
| 302,350,324
| true
|
{"Kotlin": 1224294, "HTML": 1503}
|
package samples.layout
import antd.layout.*
import antd.layout.footer
import antd.layout.header
import react.*
import react.dom.*
import styled.*
fun RBuilder.basic() {
styledDiv {
css { +LayoutStyles.basic }
div {
layout {
header { +"Header" }
content { +"Content" }
footer { +"Footer" }
}
layout {
header { +"Header" }
layout {
sider { +"Sider" }
content { +"Content" }
}
footer { +"Footer" }
}
layout {
header { +"Header" }
layout {
content { +"Content" }
sider { +"Sider" }
}
footer { +"Footer" }
}
layout {
sider { +"Sider" }
layout {
header { +"Header" }
content { +"Content" }
footer { +"Footer" }
}
}
}
}
}
| 0
| null |
0
| 0
|
439ef1f01ffea759cf3fc51ede4e60a896cbfd87
| 1,109
|
kotlin-js-wrappers
|
Apache License 2.0
|
src/main/kotlin/androidstudio/tools/missed/features/apkmanagement/presenter/model/InstallApkState.kt
|
rasoulmiri
| 668,869,188
| false
|
{"Kotlin": 440329}
|
package androidstudio.tools.missed.features.apkmanagement.presenter.model
enum class InstallApkState {
Idle, Loading
}
| 0
|
Kotlin
|
0
| 2
|
fb33080fef3289880a4efdaf92bb9826c322cfc4
| 124
|
AndroidStudioToolsMissed
|
Apache License 2.0
|
app/src/b2b/java/eu/ginlo_apps/ginlo/controller/contracts/AcceptOrDeclineCompanyManagementCallback.kt
|
cdskev
| 358,279,979
| false
|
{"Git Config": 1, "Gradle": 3, "Markdown": 5, "Java Properties": 2, "Shell": 1, "Ignore List": 1, "Text": 2, "Proguard": 1, "INI": 1, "XML": 393, "Java": 438, "Kotlin": 168, "JSON": 1, "HTML": 1}
|
// Copyright (c) 2020-2024 ginlo.net GmbH
package eu.ginlo_apps.ginlo.controller.contracts
interface AcceptOrDeclineCompanyManagementCallback {
fun onSuccess(mcState: String)
fun onFail(message: String)
}
| 1
|
Java
|
0
| 5
|
5609a68a539fc5fd9666d3d5f93be750fa5a2b77
| 214
|
ginlo-android
|
Apache License 2.0
|
src/main/kotlin/org/misarch/user/graphql/federation/UserResolver.kt
|
MiSArch
| 761,247,429
| false
|
{"Kotlin": 51538, "Shell": 487, "Dockerfile": 219}
|
package org.misarch.user.graphql.federation
import com.expediagroup.graphql.generator.federation.execution.FederatedTypePromiseResolver
import graphql.schema.DataFetchingEnvironment
import org.misarch.user.graphql.dataloader.UserDataLoader
import org.misarch.user.graphql.model.User
import org.springframework.stereotype.Component
import java.util.*
import java.util.concurrent.CompletableFuture
/**
* Federated resolver for [user]s.
*/
@Component
class UserResolver : FederatedTypePromiseResolver<User> {
override val typeName: String
get() = User::class.simpleName!!
override fun resolve(
environment: DataFetchingEnvironment, representation: Map<String, Any>
): CompletableFuture<User?> {
val id = representation["id"] as String?
return if (id == null) {
CompletableFuture.completedFuture(null)
} else {
environment.getDataLoader<UUID, User>(UserDataLoader::class.simpleName!!)
.load(UUID.fromString(id))
}
}
}
| 0
|
Kotlin
|
0
| 0
|
9ddda7e2206dfc30912f88c1854b293f586c1462
| 1,022
|
user
|
MIT License
|
core/src/test/kotlin/com/malinskiy/marathon/execution/queue/QueueActorTest.kt
|
MarathonLabs
| 129,365,301
| false
| null |
package com.malinskiy.marathon.execution.queue
import com.malinskiy.marathon.analytics.external.Analytics
import com.malinskiy.marathon.analytics.internal.pub.Track
import com.malinskiy.marathon.config.Configuration
import com.malinskiy.marathon.config.strategy.BatchingStrategyConfiguration
import com.malinskiy.marathon.config.vendor.VendorConfiguration
import com.malinskiy.marathon.device.DevicePoolId
import com.malinskiy.marathon.device.DeviceStub
import com.malinskiy.marathon.device.toDeviceInfo
import com.malinskiy.marathon.execution.DevicePoolMessage.FromQueue
import com.malinskiy.marathon.execution.TestBatchResults
import com.malinskiy.marathon.execution.TestResult
import com.malinskiy.marathon.execution.TestShard
import com.malinskiy.marathon.execution.TestStatus
import com.nhaarman.mockitokotlin2.KArgumentCaptor
import com.nhaarman.mockitokotlin2.any
import com.nhaarman.mockitokotlin2.argumentCaptor
import com.nhaarman.mockitokotlin2.mock
import com.nhaarman.mockitokotlin2.reset
import com.nhaarman.mockitokotlin2.times
import com.nhaarman.mockitokotlin2.verify
import kotlinx.coroutines.CompletableDeferred
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.Job
import kotlinx.coroutines.channels.Channel
import kotlinx.coroutines.channels.SendChannel
import kotlinx.coroutines.runBlocking
import org.amshove.kluent.shouldBe
import org.amshove.kluent.shouldBeInstanceOf
import org.amshove.kluent.shouldContainSame
import org.junit.jupiter.api.AfterEach
import org.junit.jupiter.api.BeforeEach
import org.junit.jupiter.api.Test
import java.io.File
import com.malinskiy.marathon.test.Test as MarathonTest
class QueueActorTest {
private lateinit var track: Track
lateinit var job: Job
lateinit var poolChannel: Channel<FromQueue>
lateinit var analytics: Analytics
lateinit var actor: QueueActor
lateinit var testResultCaptor: KArgumentCaptor<TestResult>
lateinit var testBatchResults: TestBatchResults
@BeforeEach
fun setup() {
track = mock()
analytics = mock()
job = Job()
poolChannel = Channel()
}
@AfterEach
fun teardown() {
reset(track, analytics)
job.cancel()
}
@Test
fun `setup 1 should have empty queue`() {
setup_1()
val isEmptyDeferred = CompletableDeferred<Boolean>()
runBlocking {
actor.send(QueueMessage.RequestBatch(TEST_DEVICE_INFO))
poolChannel.receive()
actor.send(QueueMessage.Completed(TEST_DEVICE_INFO, testBatchResults))
actor.send(QueueMessage.IsEmpty(isEmptyDeferred))
isEmptyDeferred.await() shouldBe true
}
}
@Test
fun `setup 1 should report failure`() {
setup_1()
runBlocking {
actor.send(QueueMessage.RequestBatch(TEST_DEVICE_INFO))
poolChannel.receive()
actor.send(QueueMessage.Completed(TEST_DEVICE_INFO, testBatchResults))
verify(track).test(any(), any(), testResultCaptor.capture(), any())
testResultCaptor.firstValue.test shouldBe TEST_1
testResultCaptor.firstValue.status shouldBe TestStatus.FAILURE
}
}
@Test
fun `setup 2 should have non empty queue`() {
setup_2()
val isEmptyDeferred = CompletableDeferred<Boolean>()
runBlocking {
actor.send(QueueMessage.RequestBatch(TEST_DEVICE_INFO))
poolChannel.receive() shouldBeInstanceOf FromQueue.ExecuteBatch::class
actor.send(QueueMessage.Completed(TEST_DEVICE_INFO, testBatchResults))
poolChannel.receive() shouldBeInstanceOf FromQueue.Notify::class
actor.send(QueueMessage.IsEmpty(isEmptyDeferred))
isEmptyDeferred.await() shouldBe false
}
}
@Test
fun `setup 2 should report test failed`() {
setup_2()
runBlocking {
actor.send(QueueMessage.RequestBatch(TEST_DEVICE_INFO))
poolChannel.receive() shouldBeInstanceOf FromQueue.ExecuteBatch::class
actor.send(QueueMessage.Completed(TEST_DEVICE_INFO, testBatchResults))
poolChannel.receive() shouldBeInstanceOf FromQueue.Notify::class
verify(track, times(1)).test(any(), any(), testResultCaptor.capture(), any())
testResultCaptor.firstValue.test shouldBe TEST_1
testResultCaptor.firstValue.status shouldBe TestStatus.FAILURE
}
}
@Test
fun `setup 2 should provide uncompleted test in the batch`() {
setup_2()
runBlocking {
actor.send(QueueMessage.RequestBatch(TEST_DEVICE_INFO))
poolChannel.receive() shouldBeInstanceOf FromQueue.ExecuteBatch::class
actor.send(QueueMessage.Completed(TEST_DEVICE_INFO, testBatchResults))
poolChannel.receive() shouldBeInstanceOf FromQueue.Notify::class
actor.send(QueueMessage.RequestBatch(TEST_DEVICE_INFO))
val actual = poolChannel.receive()
actual shouldBeInstanceOf FromQueue.ExecuteBatch::class
(actual as FromQueue.ExecuteBatch).batch.tests shouldContainSame listOf(TEST_1)
}
}
@Test
fun `setup 2 should have empty queue`() {
setup_2()
val isEmptyDeferred = CompletableDeferred<Boolean>()
runBlocking {
actor.send(QueueMessage.RequestBatch(TEST_DEVICE_INFO))
poolChannel.receive() shouldBeInstanceOf FromQueue.ExecuteBatch::class
actor.send(QueueMessage.Completed(TEST_DEVICE_INFO, testBatchResults))
actor.send(QueueMessage.RequestBatch(TEST_DEVICE_INFO))
poolChannel.receive() shouldBeInstanceOf FromQueue.Notify::class
poolChannel.receive() shouldBeInstanceOf FromQueue.ExecuteBatch::class
actor.send(QueueMessage.Completed(TEST_DEVICE_INFO, testBatchResults))
actor.send(QueueMessage.IsEmpty(isEmptyDeferred))
isEmptyDeferred.await() shouldBe true
}
}
@Test
fun `setup 2 should report test as failed`() {
setup_2()
runBlocking {
actor.send(QueueMessage.RequestBatch(TEST_DEVICE_INFO))
poolChannel.receive()
actor.send(QueueMessage.Completed(TEST_DEVICE_INFO, testBatchResults))
verify(track).test(any(), any(), testResultCaptor.capture(), any())
testResultCaptor.firstValue.test shouldBe TEST_1
testResultCaptor.firstValue.status shouldBe TestStatus.FAILURE
}
}
/**
* uncompleted tests retry quota is 0, max batch size is 1 and one test in the shard and processing finished
*/
private fun setup_1() {
actor =
createQueueActor(
configuration = DEFAULT_CONFIGURATION.copy(
uncompletedTestRetryQuota = 0,
batchingStrategy = BatchingStrategyConfiguration.FixedSizeBatchingStrategyConfiguration(size = 1)
),
tests = listOf(TEST_1),
poolChannel = poolChannel,
analytics = analytics,
job = job,
track = track
)
testResultCaptor = argumentCaptor<TestResult>()
testBatchResults = createBatchResult(
uncompleted = listOf(
createTestResult(TEST_1, TestStatus.FAILURE)
)
)
}
/**
* uncompleted tests retry quota is 1, max batch size is 1 and one test in the shard
*/
private fun setup_2() {
actor =
createQueueActor(
configuration = DEFAULT_CONFIGURATION.copy(
uncompletedTestRetryQuota = 1,
batchingStrategy = BatchingStrategyConfiguration.FixedSizeBatchingStrategyConfiguration(size = 1)
),
tests = listOf(TEST_1),
poolChannel = poolChannel,
analytics = analytics,
job = job,
track = track
)
testResultCaptor = argumentCaptor<TestResult>()
testBatchResults = createBatchResult(
uncompleted = listOf(
createTestResult(TEST_1, TestStatus.FAILURE)
)
)
}
}
private val TEST_DEVICE = DeviceStub()
private val TEST_DEVICE_INFO = TEST_DEVICE.toDeviceInfo()
private val TEST_1 = MarathonTest("", "", "test1", emptyList())
private fun createBatchResult(
finished: List<TestResult> = emptyList(),
failed: List<TestResult> = emptyList(),
uncompleted: List<TestResult> = emptyList()
): TestBatchResults = TestBatchResults(
TEST_DEVICE,
finished,
failed,
uncompleted
)
private fun createTestResult(test: MarathonTest, status: TestStatus) = TestResult(
test = test,
device = TEST_DEVICE_INFO,
status = status,
startTime = 0,
endTime = 0,
stacktrace = null,
attachments = emptyList(),
testBatchId = "stub-batch"
)
private fun createQueueActor(
configuration: Configuration,
tests: List<MarathonTest>,
poolChannel: SendChannel<FromQueue>,
analytics: Analytics,
track: Track,
job: Job
) = QueueActor(
configuration,
TestShard(tests, emptyList()),
analytics,
poolChannel,
DevicePoolId("test"),
mock(),
track,
mock(),
null,
job,
Dispatchers.Unconfined
)
private val DEFAULT_CONFIGURATION = Configuration.Builder(
name = "",
outputDir = File(""),
vendorConfiguration = VendorConfiguration.StubVendorConfiguration,
).apply { analyticsTracking = false }.build()
| 66
| null |
89
| 328
|
77271f081c04093134d8d6ed77e380afd0a362a4
| 9,579
|
marathon
|
Apache License 2.0
|
kotlin-node/src/jsMain/generated/node/net/ServerEvent.kt
|
JetBrains
| 93,250,841
| false
| null |
// Generated by Karakum - do not modify it manually!
package node.net
sealed external interface ServerEvent {
sealed interface CLOSE : node.events.LegacyEventType
sealed interface CONNECTION : node.events.LegacyEventType
sealed interface ERROR : node.events.LegacyEventType
sealed interface LISTENING : node.events.LegacyEventType
sealed interface DROP : node.events.LegacyEventType
companion object {
@seskar.js.JsValue("close")
val CLOSE: CLOSE
@seskar.js.JsValue("connection")
val CONNECTION: CONNECTION
@seskar.js.JsValue("error")
val ERROR: ERROR
@seskar.js.JsValue("listening")
val LISTENING: LISTENING
@seskar.js.JsValue("drop")
val DROP: DROP
@seskar.js.JsValue("close")
fun close(): node.events.EventType<Server, js.array.JsTuple>
@seskar.js.JsValue("connection")
fun connection(): node.events.EventType<Server, js.array.JsTuple1<Socket>>
@seskar.js.JsValue("error")
fun error(): node.events.EventType<Server, js.array.JsTuple1<js.errors.JsError>>
@seskar.js.JsValue("listening")
fun listening(): node.events.EventType<Server, js.array.JsTuple>
@seskar.js.JsValue("drop")
fun drop(): node.events.EventType<Server, js.array.JsTuple1<DropArgument>>
}
}
| 40
| null |
165
| 1,347
|
997ed3902482883db4a9657585426f6ca167d556
| 1,361
|
kotlin-wrappers
|
Apache License 2.0
|
pref-sdk/src/main/kotlin/com/leovp/pref/LPref.kt
|
yhz61010
| 329,485,030
| false
|
{"Gradle Kotlin DSL": 36, "YAML": 2, "Shell": 16, "Java Properties": 2, "Text": 1, "Ignore List": 37, "Batchfile": 1, "Git Attributes": 1, "EditorConfig": 1, "Markdown": 14, "INI": 62, "Kotlin": 420, "Java": 22, "AIDL": 7, "XML": 262, "TOML": 1, "CMake": 2, "Proguard": 5, "C++": 33, "C": 33, "GLSL": 4, "Makefile": 6, "Gradle": 2, "HTML": 1, "JavaScript": 1, "CSS": 1, "Python": 2}
|
package com.leovp.pref_sdk
import android.app.Activity
import android.content.Context
import com.leovp.pref_sdk.base.AbsPref
/**
* Author: <NAME>
* Date: 20-12-10 上午10:01
*/
class LPref(ctx: Context, name: String = ctx.packageName) : AbsPref() {
private val pref = ctx.getSharedPreferences(name, Activity.MODE_PRIVATE)
@Synchronized
override fun put(key: String, v: Int) {
pref.edit().apply {
putInt(key, v)
apply()
}
}
@Synchronized
override fun put(key: String, v: Long) {
pref.edit().apply {
putLong(key, v)
apply()
}
}
@Synchronized
override fun put(key: String, v: Boolean) {
pref.edit().apply {
putBoolean(key, v)
apply()
}
}
@Synchronized
override fun put(key: String, v: Float) {
pref.edit().apply {
putFloat(key, v)
apply()
}
}
@Synchronized
override fun put(key: String, v: String?) {
pref.edit().apply {
putString(key, v)
apply()
}
}
@Synchronized
override fun putSet(key: String, v: Set<String>?) {
pref.edit().apply {
putStringSet(key, v)
apply()
}
}
override fun getInt(key: String, default: Int) = pref.getInt(key, default)
override fun getLong(key: String, default: Long) = pref.getLong(key, default)
override fun getBool(key: String, default: Boolean) = pref.getBoolean(key, default)
override fun getFloat(key: String, default: Float) = pref.getFloat(key, default)
override fun getString(key: String, default: String?): String? = pref.getString(key, default)
override fun getStringSet(key: String, default: Set<String>?): Set<String>? = pref.getStringSet(key, default)
}
| 0
|
Kotlin
|
4
| 9
|
680ec6b101c4089bf6263f4ae42837c8b6e65a26
| 1,844
|
android
|
MIT License
|
arrangor/src/main/kotlin/no/nav/amt/tiltak/ansatt/AnsattDbo.kt
|
navikt
| 393,356,849
| false
|
{"Kotlin": 782863, "PLpgSQL": 635, "Dockerfile": 160}
|
package no.nav.amt.tiltak.ansatt
import no.nav.amt.tiltak.core.domain.arrangor.Ansatt
import no.nav.amt.tiltak.core.domain.arrangor.TilknyttetArrangor
import java.time.LocalDateTime
import java.util.*
data class AnsattDbo(
val id: UUID,
val personligIdent: String,
val fornavn: String,
val mellomnavn: String?,
val etternavn: String,
val sistVelykkedeInnlogging: LocalDateTime,
val tilgangerSistSynkronisert: LocalDateTime,
val createdAt: LocalDateTime,
val modifiedAt: LocalDateTime
) {
fun toAnsatt(virksomheter: List<TilknyttetArrangor>): Ansatt {
return Ansatt(
id = id,
personligIdent = personligIdent,
fornavn = fornavn,
mellomnavn = mellomnavn,
etternavn = etternavn,
arrangorer = virksomheter
)
}
}
| 4
|
Kotlin
|
3
| 4
|
821784cd08cfad8edb1c8ac9e9033e361cecb343
| 743
|
amt-tiltak
|
MIT License
|
src/test/kotlin/Day10Tests.kt
|
derekaspaulding
| 317,756,568
| false
| null |
import day10.*
import org.junit.jupiter.api.Assertions
import org.junit.jupiter.api.Test
class Day10Tests {
@Test
fun `solves the first problem`() {
Assertions.assertEquals(220, solveFirstProblem(testJoltages))
}
@Test
fun `solves the second problem with the simple list`() {
Assertions.assertEquals(8, solveProblemTwo(simpleTestJoltages))
}
@Test
fun `solves the second problem with the complex list`() {
Assertions.assertEquals(19208, solveProblemTwo(testJoltages))
}
}
val simpleTestJoltages = listOf(
16,
10,
15,
5,
1,
11,
7,
19,
6,
12,
4
)
val testJoltages = listOf(
28,
33,
18,
42,
31,
14,
46,
20,
48,
47,
24,
23,
49,
45,
19,
38,
39,
11,
1,
32,
25,
35,
8,
17,
7,
9,
4,
2,
34,
10,
3,
)
| 0
|
Kotlin
|
0
| 0
|
0e26fdbb3415fac413ea833bc7579c09561b49e5
| 923
|
advent-of-code-2020
|
MIT License
|
sentry/src/main/kotlin/com/avito/android/sentry/EnvironmentInfo.kt
|
mduisenov
| 237,274,875
| true
|
{"Kotlin": 2360982, "Python": 14063, "Shell": 13206, "Dockerfile": 7097, "Makefile": 35}
|
package com.avito.android.sentry
import com.avito.git.Git
import com.avito.kotlin.dsl.getOptionalStringProperty
import com.avito.utils.gradle.BuildEnvironment
import com.avito.utils.gradle.buildEnvironment
import org.gradle.api.Project
/**
* Use [Project.environmentInfo] to gain instance
*/
interface EnvironmentInfo {
val node: String?
val environment: Environment
val commit: String?
fun teamcityBuildId(): String?
fun isInvokedFromIde(): Boolean
}
internal class EnvironmentInfoImpl(private val project: Project, private val git: Git) : EnvironmentInfo {
override val node: String? by lazy {
when (environment) {
is Environment.Local -> gitUserEmail ?: userName()
is Environment.Mirakle -> userName()
is Environment.CI -> teamcityAgentName()
is Environment.Unknown -> "unknown"
}
}
override val environment: Environment by lazy {
val buildEnvironment = project.buildEnvironment
when {
(userName() == "teamcity") || (gitUserEmail == "teamcity") -> Environment.CI // we want ci metrics even if "-Pci=false" in CI
buildEnvironment is BuildEnvironment.Local || buildEnvironment is BuildEnvironment.IDE -> Environment.Local
buildEnvironment is BuildEnvironment.CI -> Environment.CI
buildEnvironment is BuildEnvironment.Mirkale -> Environment.Mirakle
else -> Environment.Unknown
}
}
private fun userName(): String? = System.getProperty("user.name")
private fun teamcityAgentName(): String? {
return System.getenv("TEAMCITY_AGENT_NAME")
?: System.getProperty("TEAMCITY_AGENT_NAME", null)
}
override fun teamcityBuildId(): String? {
return project.rootProject.getOptionalStringProperty("teamcityBuildId")
}
private val gitUserEmail: String? by lazy {
if (hasGit) {
git.config("user.email").toOption().orNull()?.substringBefore('@')
} else {
null
}
}
private val hasGit: Boolean = (project.buildEnvironment !is BuildEnvironment.Mirkale)
override val commit: String? by lazy {
if (hasGit) {
git.tryParseRev("HEAD").toOption().orNull()
} else {
null
}
}
override fun isInvokedFromIde() = project.hasProperty("android.injected.invoked.from.ide")
}
/**
* @param publicName это название используется в graphite событиях
*/
sealed class Environment(val publicName: String) {
object Local : Environment("local")
object Mirakle : Environment("mirakle")
object CI : Environment("ci")
object Unknown : Environment("_")
}
| 0
|
Kotlin
|
0
| 0
|
b0513404cc36196fb87ddadd1894b9015beac952
| 2,691
|
avito-android
|
Apache License 2.0
|
app/src/main/java/dalian/razvan/cucer/ibm/screens/currencyDetails/CurrencyDetailsFragmentView.kt
|
daliaan
| 367,817,053
| false
| null |
package dalian.razvan.cucer.ibm.screens.currencyDetails
import dalian.razvan.cucer.ibm.core.baseClasses.BaseFragmentView
interface CurrencyDetailsFragmentView: BaseFragmentView {
}
| 0
|
Kotlin
|
0
| 0
|
f1c87dd1745ee8477d486b036dc5c45aacabe59e
| 182
|
IBM
|
Apache License 2.0
|
adt-ui/src/main/java/com/android/tools/adtui/stdui/StandardDimensions.kt
|
JetBrains
| 60,701,247
| false
|
{"Kotlin": 53054415, "Java": 43443054, "Starlark": 1332164, "HTML": 1218044, "C++": 507658, "Python": 191041, "C": 71660, "Lex": 70302, "NSIS": 58238, "AIDL": 35382, "Shell": 29838, "CMake": 27103, "JavaScript": 18437, "Smali": 7580, "Batchfile": 7357, "RenderScript": 4411, "Clean": 3522, "Makefile": 2495, "IDL": 19}
|
/*
* Copyright (C) 2018 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.android.tools.adtui.stdui
import com.intellij.util.ui.JBUI
/**
* Standard UI Component Dimensions.
*/
object StandardDimensions {
const val OUTER_BORDER_UNSCALED = 2
val COMBO_LEFT_PADDING = JBUI.scale(7)
val HORIZONTAL_PADDING = JBUI.scale(6)
val VERTICAL_PADDING = JBUI.scale(1)
val INNER_BORDER_WIDTH = JBUI.scale(1f)
val OUTER_BORDER_WIDTH = JBUI.scale(OUTER_BORDER_UNSCALED.toFloat())
val DROPDOWN_ARROW_WIDTH = JBUI.scale(8f)
val DROPDOWN_ARROW_HEIGHT = JBUI.scale(5f)
val DROPDOWN_ARROW_HORIZONTAL_PADDING = JBUI.scale(4f)
val DROPDOWN_ARROW_VERTICAL_PADDING_TOP = JBUI.scale(7f)
val DROPDOWN_ARROW_VERTICAL_PADDING_BOTTOM = JBUI.scale(6f)
var MENU_HEIGHT = JBUI.scale(20f)
var MENU_LEFT_PADDING = JBUI.scale(6f)
var MENU_RIGHT_PADDING = JBUI.scale(10f)
var MENU_ICON_TEXT_GAP = JBUI.scale(4f)
var MENU_CHECK_ICON_GAP = JBUI.scale(5f)
}
| 5
|
Kotlin
|
227
| 948
|
10110983c7e784122d94c7467e9d243aba943bf4
| 1,513
|
android
|
Apache License 2.0
|
app/src/main/kotlin/com/exactpro/th2/lwdataprovider/db/DataMeasurement.kt
|
th2-net
| 433,117,188
| false
|
{"Kotlin": 830374, "Python": 4548, "Dockerfile": 116}
|
/*
* Copyright 2022 Exactpro (Exactpro Systems Limited)
*
* 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.exactpro.th2.lwdataprovider.db
interface DataMeasurement {
fun start(name: String): Measurement
}
interface Measurement : AutoCloseable {
fun stop()
override fun close() = stop()
}
| 2
|
Kotlin
|
0
| 0
|
651760781cba85a49f59fac1b9d7aabcb28e2dd1
| 828
|
th2-lw-data-provider
|
Apache License 2.0
|
domain/arbeidssoeker-regler/src/main/kotlin/no/nav/paw/arbeidssokerregisteret/application/Resultat.kt
|
navikt
| 794,874,233
| false
|
{"Kotlin": 609526, "Dockerfile": 143}
|
package no.nav.paw.arbeidssokerregisteret.application
import arrow.core.Either
import arrow.core.left
import arrow.core.right
import no.nav.paw.arbeidssokerregisteret.application.opplysninger.Opplysning
sealed interface Problem {
val opplysninger: Iterable<Opplysning>
val regel: Regel
}
data class SkalAvvises(
override val opplysninger: Iterable<Opplysning>,
override val regel: Regel
): Problem
data class MuligGrunnlagForAvvisning(
override val opplysninger: Iterable<Opplysning>,
override val regel: Regel
): Problem
data class GrunnlagForGodkjenning(
val opplysning: Iterable<Opplysning>,
val regel: Regel
)
fun grunnlagForGodkjenning(regel: Regel, opplysninger: Iterable<Opplysning>): Either<Problem, GrunnlagForGodkjenning> =
GrunnlagForGodkjenning(opplysninger, regel).right()
fun skalAvises(regel: Regel, opplysninger: Iterable<Opplysning>): Either<Problem, GrunnlagForGodkjenning> =
SkalAvvises(opplysninger, regel).left()
fun muligGrunnlagForAvvisning(regel: Regel, opplysninger: Iterable<Opplysning>): Either<Problem, GrunnlagForGodkjenning> =
MuligGrunnlagForAvvisning(opplysninger, regel).left()
| 3
|
Kotlin
|
0
| 1
|
e00be97578399169989b3b81be3ffd6f7d59081c
| 1,163
|
paw-arbeidssoekerregisteret-monorepo-intern
|
MIT License
|
app/src/main/kotlin/de/ljz/questify/core/di/NetworkModule.kt
|
LJZApps
| 806,522,161
| false
|
{"Kotlin": 135023}
|
package de.ljz.questify.core.di
import com.skydoves.sandwich.retrofit.adapters.ApiResponseCallAdapterFactory
import com.squareup.moshi.Moshi
import com.squareup.moshi.kotlin.reflect.KotlinJsonAdapterFactory
import de.ljz.questify.BuildConfig
import de.ljz.questify.data.api.core.ApiClient
import de.ljz.questify.data.api.core.adapters.StringToDateAdapter
import de.ljz.questify.data.api.core.interceptors.FailedRequestInterceptor
import de.ljz.questify.data.sharedpreferences.SessionManager
import okhttp3.OkHttpClient
import okhttp3.logging.HttpLoggingInterceptor
import org.koin.android.ext.koin.androidContext
import org.koin.dsl.module
import retrofit2.Retrofit
import retrofit2.converter.moshi.MoshiConverterFactory
import java.time.Duration
val networkModule = module {
single<SessionManager> { SessionManager(androidContext()) }
single<Moshi> {
Moshi.Builder()
.add(StringToDateAdapter())
.add(KotlinJsonAdapterFactory())
.build()
}
single<Retrofit> {
Retrofit.Builder()
.baseUrl(BuildConfig.BASE_URL)
.client(get())
.addConverterFactory(MoshiConverterFactory.create(get()))
.addCallAdapterFactory(ApiResponseCallAdapterFactory.create())
.build()
}
single<OkHttpClient> {
OkHttpClient.Builder().apply {
callTimeout(Duration.ofMinutes(3))
connectTimeout(Duration.ofMinutes(3))
readTimeout(Duration.ofMinutes(3))
writeTimeout(Duration.ofMinutes(3))
addInterceptor(FailedRequestInterceptor(get()))
if (BuildConfig.DEBUG) {
addNetworkInterceptor(
HttpLoggingInterceptor().apply {
this.level = HttpLoggingInterceptor.Level.BODY
}
)
}
}.build()
}
single<ApiClient> {
ApiClient(
retrofit = get(),
)
}
}
| 0
|
Kotlin
|
0
| 0
|
396903b9bf416c73322732f5d5d4ca625876d40d
| 1,796
|
Questify-Android
|
MIT License
|
src/test/kotlin/com/example/doctorpractice/scheduling/writemodel/InMemoryAggregateRepository.kt
|
th3n3rd
| 411,821,607
| false
|
{"Kotlin": 40186, "Shell": 1509}
|
package com.example.doctorpractice.scheduling.writemodel
import com.example.doctorpractice.scheduling.domain.AggregateRepository
import com.example.doctorpractice.scheduling.domain.AggregateRoot
class InMemoryAggregateRepository<Aggregate : AggregateRoot<Id>, Id>(
private val aggregate: Aggregate
) : AggregateRepository<Aggregate, Id> {
override fun load(id: Id): Aggregate {
return aggregate
}
override fun save(aggregate: Aggregate) {}
}
| 0
|
Kotlin
|
0
| 1
|
6628262ea7780d60c4eb559c80c2facb59b9b546
| 470
|
doctor-practice-cqrs
|
MIT License
|
yify/domain/src/main/java/io/github/kunal26das/yify/domain/model/OrderBy.kt
|
kunal26das
| 283,553,926
| false
| null |
package io.github.kunal26das.yify.domain.model
@Suppress("EnumEntryName")
enum class OrderBy {
asc, desc,
}
| 5
|
Kotlin
|
0
| 1
|
2affe4ce4a57c8779af5e8af0112bfe6f4177d47
| 112
|
yify
|
Apache License 2.0
|
detekt-rules-exceptions/src/test/kotlin/io/gitlab/arturbosch/detekt/rules/exceptions/ThrowingNewInstanceOfSameExceptionSpec.kt
|
detekt
| 71,729,669
| false
| null |
package io.gitlab.arturbosch.detekt.rules.exceptions
import io.gitlab.arturbosch.detekt.test.compileAndLint
import org.assertj.core.api.Assertions.assertThat
import org.junit.jupiter.api.DisplayName
import org.junit.jupiter.api.Nested
import org.junit.jupiter.api.Test
class ThrowingNewInstanceOfSameExceptionSpec {
val subject = ThrowingNewInstanceOfSameException()
@Nested
inner class `a catch block which rethrows a new instance of the caught exception` {
val code = """
fun x() {
try {
} catch (e: IllegalStateException) {
throw IllegalStateException(e)
}
}
""".trimIndent()
@Test
fun `should report`() {
val findings = subject.compileAndLint(code)
assertThat(findings).hasSize(1)
}
}
@Nested
inner class `a catch block which rethrows a new instance of another exception` {
val code = """
fun x() {
try {
} catch (e: IllegalStateException) {
throw IllegalArgumentException(e)
}
}
""".trimIndent()
@Test
fun `should not report`() {
val findings = subject.compileAndLint(code)
assertThat(findings).isEmpty()
}
}
@Nested
@DisplayName(
"a catch block which throws a new instance of the same exception type without wrapping the caught exception"
)
inner class CatchBlockThrowingSameExceptionWithoutWrapping {
val code = """
fun x() {
try {
} catch (e: IllegalStateException) {
throw IllegalStateException()
}
}
""".trimIndent()
@Test
fun `should not report`() {
val findings = subject.compileAndLint(code)
assertThat(findings).isEmpty()
}
}
}
| 9
| null |
772
| 6,253
|
c5d7ed3da2824534d0e15f8404ad4f1c59fb553c
| 1,902
|
detekt
|
Apache License 2.0
|
generator/src/main/kotlin/generator/EntryInfo.kt
|
adamWeesner
| 239,233,558
| false
| null |
package generator
import java.io.File
data class EntryInfo(
val baseDirectory: File,
val className: String,
val data: List<String>
) {
val lowered = className.decapitalize()
val subDirectory = File("${baseDirectory.path}/$lowered")
init {
subDirectory.mkdirs()
}
}
| 1
| null |
1
| 1
|
a04ad390fe844a7d89db2fa726599c23d3f796f6
| 304
|
weesnerDevelopment
|
MIT License
|
app/src/main/java/org/bobstuff/bobboardview/app/simple/SimpleModelData.kt
|
bobthekingofegypt
| 123,321,465
| false
| null |
package org.bobstuff.bobboardview.app.simple
import org.bobstuff.bobboardview.app.R
/**
* Created by bob
*/
data class Card(val description: String, val id: String)
data class BoardList(val uniqueId: Int, val description: String, val cards: MutableList<Card>)
data class Board(val name: String, val boardLists: MutableList<BoardList>)
fun generateTestData(): Board {
val story1 = Card(description = "Investigate how to make a scrum board",
id = "BOB-12")
val story2 = Card(description = "Make the world a better place by solving all it's problems",
id = "BOB-1")
val story3 = Card(description = "Test data for the win",
id = "BOB-2")
val story4 = Card(description = "Lets do this thing",
id = "BOB-3")
val story5 = Card(description = "Lots of words that don't say anything but take up space",
id = "BOB-4")
val story6 = Card(description = "Something smart",
id = "BOB-5")
val boardList1 = BoardList(1, "List 1", mutableListOf(story1, story2))
val boardList2 = BoardList(2, "List 2", mutableListOf(story3))
val boardList3 = BoardList(3, "List 3", mutableListOf(story4, story5, story6))
val boardList4 = BoardList(4, "List 4", mutableListOf())
val boardList5 = BoardList(5, "List 5", mutableListOf())
return Board("Simple Board", mutableListOf(boardList1, boardList2, boardList3, boardList4, boardList5))
}
| 1
|
Kotlin
|
1
| 4
|
a13505aabc152ab9eb62b96c84204e10f5b777c2
| 1,441
|
BobBoardView
|
Apache License 2.0
|
app/src/main/java/com/speakerboxlite/rxentity/EntityCollection.kt
|
AlexExiv
| 240,526,542
| false
| null |
package com.speakerboxlite.rxentity
import io.reactivex.rxjava3.core.Scheduler
import io.reactivex.rxjava3.core.Single
import io.reactivex.rxjava3.disposables.CompositeDisposable
import java.lang.ref.WeakReference
import java.util.concurrent.locks.ReentrantLock
data class EntityCollectionExtraParamsEmpty(val unused: Int = 0)
abstract class EntityCollection<K: Comparable<K>, E: Entity<K>>(val queue: Scheduler)
{
protected val lock = ReentrantLock()
protected val items = mutableListOf<WeakReference<EntityObservable<K, E, *>>>()
val sharedEntities: Map<K, E> get() = _sharedEntities
protected val _sharedEntities = mutableMapOf<K, E>()
protected val dispBag = CompositeDisposable()
fun add(obs: EntityObservable<K, E, *>)
{
lock.lock()
try
{
items.add(WeakReference(obs))
}
finally
{
lock.unlock()
}
}
fun remove(obs: EntityObservable<K, E, *>)
{
lock.lock()
try
{
items.removeAll { obs.uuid == it.get()?.uuid }
}
finally
{
lock.unlock()
}
}
abstract fun RxRequestForCombine(source: String, entity: E, updateChilds: Boolean = true) : Single<E>
abstract fun RxRequestForCombine(source: String, entities: List<E>, updateChilds: Boolean = true) : Single<List<E>>
fun RxUpdate(source: String = "", entity: E): Single<E>
{
val weak = WeakReference(this)
return Single.create<E>
{
weak.get()?.update(source = source, entity = entity)
it.onSuccess(entity)
}
.observeOn(queue)
.subscribeOn(queue)
}
fun RxUpdate(source: String = "", entities: List<E>): Single<List<E>>
{
val weak = WeakReference(this)
return Single.create<List<E>>
{
weak.get()?.update(source = source, entities = entities)
it.onSuccess(entities)
}
.observeOn(queue)
.subscribeOn(queue)
}
open fun update(source: String = "", entity: E)
{
lock.lock()
try
{
_sharedEntities[entity._key] = entity
items.forEach { it.get()?.update(source = "", entity = entity) }
}
finally
{
lock.unlock()
}
}
open fun update(source: String = "", entities: List<E>)
{
lock.lock()
try
{
val map = entities.associateBy {
_sharedEntities[it._key] = it
it._key
}
items.forEach { it.get()?.update(source = "", entities = map) }
}
finally
{
lock.unlock()
}
}
abstract fun commit(entity: E, operation: UpdateOperation)
abstract fun commitByKey(key: K, operation: UpdateOperation)
abstract fun commitByKey(key: K, changes: (E) -> E)
abstract fun commit(entities: List<E>, operation: UpdateOperation)
abstract fun commit(entities: List<E>, operations: List<UpdateOperation>)
abstract fun commitByKeys(keys: List<K>, operation: UpdateOperation)
abstract fun commitByKeys(keys: List<K>, operations: List<UpdateOperation>)
abstract fun commitByKeys(keys: List<K>, changes: (E) -> E)
abstract fun commitDeleteByKeys(keys: Set<K>)
abstract fun commitClear()
abstract fun createSingle(initial: E, refresh: Boolean = false): SingleObservable<K, E>
abstract fun createKeyArray(initial: List<E>): ArrayKeyObservable<K, E>
}
| 0
|
Kotlin
|
0
| 0
|
d100c2a1bd34c0e791df6e812f30a611b6779725
| 3,638
|
RxEntity-Kotlin
|
MIT License
|
core/src/commonMain/kotlin/de/frederikbertling/kosc/core/spec/args/OSCString.kt
|
Burtan
| 796,396,999
| false
|
{"Kotlin": 26257}
|
package de.frederikbertling.kosc.core.spec.args
/**
* A sequence of non-null ASCII characters followed by a null, followed by 0-3 additional null characters to make the
* total number of bits a multiple of 32. (OSC-string examples) In this document, example OSC-strings will be written
* without the null characters, surrounded by double quotes.
*/
data class OSCString(
val value: String
) : OSCArgument
| 1
|
Kotlin
|
0
| 1
|
c7720825a4704eb50768c81222f84aa11d818e68
| 415
|
kOSC
|
Apache License 2.0
|
base/src/main/kotlin/io/goooler/demoapp/base/util/BaseExtensions.kt
|
Goooler
| 188,988,687
| false
| null |
@file:Suppress("unused")
@file:JvmName("BaseExtensionUtil")
@file:OptIn(ExperimentalContracts::class)
package io.goooler.demoapp.base.util
import android.app.Activity
import android.content.ContentUris
import android.content.Context
import android.content.ContextWrapper
import android.content.Intent
import android.graphics.Color
import android.graphics.drawable.GradientDrawable
import android.media.AudioManager
import android.net.Uri
import android.os.Build
import android.os.Bundle
import android.os.Looper
import android.os.Parcelable
import android.text.Spannable
import android.text.Spanned
import android.text.style.ClickableSpan
import android.text.style.ForegroundColorSpan
import android.view.KeyEvent
import android.view.View
import android.view.ViewGroup
import android.view.inputmethod.EditorInfo
import android.view.inputmethod.InputMethodManager
import android.webkit.URLUtil
import android.widget.TextView
import androidx.annotation.ColorInt
import androidx.annotation.IdRes
import androidx.annotation.IntRange
import androidx.annotation.MainThread
import androidx.annotation.Px
import androidx.core.content.getSystemService
import androidx.core.content.pm.ShortcutInfoCompat
import androidx.core.content.pm.ShortcutManagerCompat
import androidx.core.os.bundleOf
import androidx.core.text.parseAsHtml
import androidx.core.text.toSpannable
import androidx.fragment.app.Fragment
import androidx.fragment.app.FragmentActivity
import androidx.fragment.app.FragmentManager
import androidx.fragment.app.commit
import androidx.fragment.app.findFragment
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.LifecycleCoroutineScope
import androidx.lifecycle.coroutineScope
import androidx.lifecycle.findViewTreeLifecycleOwner
import java.io.File
import java.io.Serializable
import java.math.BigDecimal
import java.net.URLConnection
import java.util.Collections
import java.util.UUID
import java.util.regex.Pattern
import kotlin.contracts.ExperimentalContracts
import kotlin.contracts.contract
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.CoroutineStart
import kotlinx.coroutines.Deferred
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.SupervisorJob
import kotlinx.coroutines.async
import kotlinx.coroutines.withContext
// ---------------------Types-------------------------------//
typealias ParamMap = HashMap<String, Any>
// ---------------------Any-------------------------------//
inline val randomUUID: String get() = UUID.randomUUID().toString()
inline val currentTimeMillis: Long get() = System.currentTimeMillis()
inline val currentThreadName: String get() = Thread.currentThread().name
inline val isMainThread: Boolean get() = Looper.getMainLooper() == Looper.myLooper()
fun <T : Any> unsafeLazy(initializer: () -> T): Lazy<T> =
lazy(LazyThreadSafetyMode.NONE, initializer)
// ---------------------CharSequence-------------------------------//
operator fun String.times(@IntRange(from = 0) num: Int): String {
require(num >= 0) {
"Param num should >= 0"
}
val origin = this
return buildString {
for (i in 1..num) append(origin)
}
}
fun String.fromHtml(): Spanned = parseAsHtml()
fun String.toMimeType(): String? = URLConnection.getFileNameMap().getContentTypeFor(this)
fun Array<String>.toMimeTypes(): List<String> = buildList {
this@toMimeTypes.forEach {
it.toMimeType()?.let(::add)
}
}
fun List<String>.toMimeTypes(): List<String> = buildList {
this@toMimeTypes.forEach {
it.toMimeType()?.let(::add)
}
}
fun String.onlyDigits(): String = replace(Regex("\\D*"), "")
fun String.removeAllSpecialCharacters(): String = replace(Regex("[^a-zA-Z]+"), "")
fun String.isValidFilename(): Boolean {
val filenameRegex =
Pattern.compile("[\\\\\\/:\\*\\?\"<>\\|\\x01-\\x1F\\x7F]", Pattern.CASE_INSENSITIVE)
// It's not easy to use regex to detect single/double dot while leaving valid values
// (filename.zip) behind...
// So we simply use equality to check them
return !filenameRegex.matcher(this).find() && "." != this && ".." != this
}
fun Uri.withAppendedId(id: Long): Uri = ContentUris.withAppendedId(this, id)
@OptIn(ExperimentalContracts::class)
fun CharSequence?.isNotNullOrEmpty(): Boolean {
contract {
returns(true) implies (this@isNotNullOrEmpty != null)
}
return this.isNullOrEmpty().not()
}
fun Spannable.withClickableSpan(clickablePart: String, onClickListener: () -> Unit): Spannable {
val clickableSpan = object : ClickableSpan() {
override fun onClick(widget: View) = onClickListener()
}
setSpan(
clickableSpan,
indexOf(clickablePart),
indexOf(clickablePart) + clickablePart.length,
Spannable.SPAN_EXCLUSIVE_EXCLUSIVE
)
return this
}
fun CharSequence.withColorSpan(coloredPart: String, @ColorInt color: Int): Spannable {
return toSpannable().also {
it.setSpan(
ForegroundColorSpan(color),
it.length - coloredPart.length,
it.length,
Spanned.SPAN_EXCLUSIVE_EXCLUSIVE
)
}
}
/**
* subString 防越界处理
*/
fun String.safeSubstring(startIndex: Int, endIndex: Int): String {
val begin = if (startIndex < 0) 0 else startIndex
val end = if (endIndex > length) length else endIndex
return substring(begin, end)
}
fun String?.safeToBoolean(default: Boolean = false): Boolean {
return if (this == null) default else try {
toBoolean()
} catch (e: Throwable) {
e.printStackTrace()
default
}
}
fun String?.safeToInt(default: Int = 0): Int {
return if (this == null) default else try {
toInt()
} catch (e: Throwable) {
e.printStackTrace()
default
}
}
fun String?.safeToLong(default: Long = 0L): Long {
return if (this == null) default else try {
toLong()
} catch (e: Throwable) {
e.printStackTrace()
default
}
}
fun String?.safeToFloat(default: Float = 0f): Float {
return if (this == null) default else try {
toFloat()
} catch (e: Throwable) {
e.printStackTrace()
default
}
}
fun String?.safeToDouble(default: Double = 0.0): Double {
return if (this == null) default else try {
toDouble()
} catch (e: Throwable) {
e.printStackTrace()
default
}
}
@ColorInt
fun String?.safeToColor(@ColorInt default: Int = 0): Int {
return try {
Color.parseColor(this)
} catch (e: Throwable) {
e.printStackTrace()
default
}
}
fun String?.isNetworkUrl(): Boolean = URLUtil.isNetworkUrl(this)
fun String?.isValidUrl(): Boolean = URLUtil.isValidUrl(this)
// ---------------------Calculate-------------------------------//
infix fun Double.plus(that: Double): Double {
return (BigDecimal(this.toString()) + BigDecimal(that.toString())).toDouble()
}
infix fun Double.minus(that: Double): Double {
return (BigDecimal(this.toString()) - BigDecimal(that.toString())).toDouble()
}
infix fun Double.times(that: Double): Double {
return (BigDecimal(this.toString()) * BigDecimal(that.toString())).toDouble()
}
infix fun Double.div(that: Double): Double {
return (BigDecimal(this.toString()) / BigDecimal(that.toString())).toDouble()
}
fun Number.isZero(): Boolean {
return when (this) {
is Byte, is Short, is Int, is Long -> this == 0
is Float, is Double -> BigDecimal(this.toString()) == BigDecimal("0.0")
else -> false
}
}
fun Number.isNotZero(): Boolean = isZero().not()
fun Int?.orZero(): Int = this ?: 0
fun Int.isInvalid(invalidValue: Int = -1) = this == invalidValue
fun Int.isValid(invalidValue: Int = -1) = isInvalid(invalidValue).not()
fun Long.isInvalid(invalidValue: Long = -1) = this == invalidValue
fun Long.isValid(invalidValue: Long = -1) = isInvalid(invalidValue).not()
fun Boolean?.orTrue(): Boolean = this ?: true
fun Boolean?.orFalse(): Boolean = this ?: false
// ---------------------Collections-------------------------------//
@OptIn(ExperimentalContracts::class)
fun <T> Collection<T>?.isNotNullOrEmpty(): Boolean {
contract {
returns(true) implies (this@isNotNullOrEmpty != null)
}
return this.isNullOrEmpty().not()
}
/**
* 判断集合内是否仅有一个元素
*/
@OptIn(ExperimentalContracts::class)
fun <T> Collection<T>?.isSingle(): Boolean {
contract {
returns(true) implies (this@isSingle != null)
}
return this != null && size == 1
}
/**
* 判断集合内是否有多个元素
* @param minSize 最小为 2
*/
@OptIn(ExperimentalContracts::class)
fun <T> Collection<T>?.isMultiple(@IntRange(from = 2) minSize: Int = 2): Boolean {
contract {
returns(true) implies (this@isMultiple != null)
}
val min = if (minSize < 2) 2 else minSize
return this != null && size >= min
}
fun <T> List<T>.safeSubList(fromIndex: Int, toIndex: Int): List<T> {
val endIndex = if (toIndex > size) size else toIndex
return subList(fromIndex, endIndex)
}
/**
* 取集合内第二个元素
*/
fun <T> List<T>.secondOrNull(): T? {
return if (size < 2) null else this[1]
}
/**
* 取集合内第三个元素
*/
fun <T> List<T>.thirdOrNull(): T? {
return if (size < 3) null else this[2]
}
fun <E> List<E>.toUnmodifiableList(): List<E> = Collections.unmodifiableList(this)
fun <T> Set<T>.toUnmodifiableSet(): Set<T> = Collections.unmodifiableSet(this)
fun <K, V> Map<K, V>.toUnmodifiableMap(): Map<K, V> = Collections.unmodifiableMap(this)
fun paramMapOf(vararg pairs: Pair<String, Any>): HashMap<String, Any> =
HashMap<String, Any>(pairs.size).apply { putAll(pairs) }
fun <K, V> MutableMap<K, V>.removeFirst(): Map.Entry<K, V> {
val iterator = iterator()
val element = iterator.next()
iterator.remove()
return element
}
fun <K, V> MutableMap<K, V>.removeFirstOrNull(predicate: (Map.Entry<K, V>) -> Boolean): Map.Entry<K, V>? =
entries.removeFirstOrNull(predicate)
fun <T> MutableCollection<T>.removeFirstOrNull(predicate: (T) -> Boolean): T? {
val iterator = iterator()
while (iterator.hasNext()) {
val element = iterator.next()
if (predicate(element)) {
iterator.remove()
return element
}
}
return null
}
// ---------------------Coroutine-------------------------------//
fun <T> CoroutineScope.defaultAsync(
start: CoroutineStart = CoroutineStart.DEFAULT,
block: suspend CoroutineScope.() -> T
): Deferred<T> = async(SupervisorJob(), start, block)
suspend fun <T> withIoContext(block: suspend CoroutineScope.() -> T): T =
withContext(Dispatchers.IO, block)
suspend fun <T> withDefaultContext(block: suspend CoroutineScope.() -> T): T =
withContext(Dispatchers.Default, block)
// ---------------------File-------------------------------//
fun File.notExists(): Boolean = exists().not()
// ---------------------View-------------------------------//
// ---------------------Intent-------------------------------//
fun Intent.getStringExtra(name: String, defaultValue: String): String =
getStringExtra(name) ?: defaultValue
fun Intent.getCharSequenceExtra(name: String, defaultValue: CharSequence): CharSequence =
getCharSequenceExtra(name) ?: defaultValue
fun <T : Parcelable> Intent.getParcelableExtra(name: String, defaultValue: T): T =
getParcelableExtra(name) ?: defaultValue
fun <T : Serializable> Intent.getSerializableExtra(
name: String,
defaultValue: Serializable
): Serializable = getSerializableExtra(name) ?: defaultValue
// ---------------------Fragment-------------------------------//
fun <T : Fragment> T.putArguments(bundle: Bundle): T {
arguments = bundle
return this
}
fun <T : Fragment> T.putArguments(vararg pairs: Pair<String, Any?>): T =
putArguments(bundleOf(*pairs))
/**
* @param containerViewId 容器 id
* @param fragment 要添加的 fragment
* @param isAddToBackStack 将要添加的 fragment 是否要添加到返回栈,默认不添加
* @param tag fragment 的 tag
*/
@MainThread
fun FragmentManager.addFragment(
fragment: Fragment,
@IdRes containerViewId: Int = android.R.id.content,
isAddToBackStack: Boolean = false,
tag: String? = null
) {
if (fragment.isAdded) return
commit {
if (isAddToBackStack) addToBackStack(tag)
add(containerViewId, fragment, tag)
}
}
/**
* @param containerViewId 容器 id
* @param fragment 要替换的 fragment
* @param isAddToBackStack 将要替换的 fragment 是否要添加到返回栈,默认添加
* @param tag fragment 的 tag
*/
@MainThread
fun FragmentManager.replaceFragment(
fragment: Fragment,
@IdRes containerViewId: Int = android.R.id.content,
isAddToBackStack: Boolean = true,
tag: String? = null
) {
if (fragment.isAdded) return
commit {
if (isAddToBackStack) addToBackStack(tag)
replace(containerViewId, fragment, tag)
}
}
@MainThread
fun Fragment.addFragment(
fragment: Fragment,
@IdRes containerViewId: Int = android.R.id.content,
isAddToBackStack: Boolean = false,
tag: String? = null
) {
childFragmentManager.addFragment(fragment, containerViewId, isAddToBackStack, tag)
}
@MainThread
fun Fragment.replaceFragment(
fragment: Fragment,
@IdRes containerViewId: Int = android.R.id.content,
isAddToBackStack: Boolean = false,
tag: String? = null
) {
childFragmentManager.addFragment(fragment, containerViewId, isAddToBackStack, tag)
}
// ---------------------View-------------------------------//
inline val View.attachedFragment: Fragment?
get() = runCatching { findFragment<Fragment>() }.getOrNull()
inline val View.attachedActivity: Activity?
get() {
var baseContext: Context? = context
while (baseContext is ContextWrapper) {
if (baseContext is Activity) break
baseContext = baseContext.baseContext
}
return baseContext as? Activity
}
inline val View.lifecycle: Lifecycle? get() = findViewTreeLifecycleOwner()?.lifecycle
inline val View.lifecycleScope: LifecycleCoroutineScope? get() = lifecycle?.coroutineScope
fun View.hideSoftInput() {
context.getSystemService<InputMethodManager>()?.hideSoftInputFromWindow(windowToken, 0)
}
fun View.showSoftInput() {
context.getSystemService<InputMethodManager>()?.showSoftInput(this, 0)
}
fun TextView.setOnEditorConfirmActionListener(listener: (TextView) -> Unit) {
setOnEditorActionListener { view, actionId, event ->
val isConfirmAction = if (event != null) {
when (event.keyCode) {
KeyEvent.KEYCODE_DPAD_CENTER, KeyEvent.KEYCODE_ENTER,
KeyEvent.KEYCODE_NUMPAD_ENTER -> true
else -> false
} && event.action == KeyEvent.ACTION_DOWN
} else {
when (actionId) {
EditorInfo.IME_NULL, EditorInfo.IME_ACTION_DONE, EditorInfo.IME_ACTION_NEXT -> true
else -> false
}
}
if (isConfirmAction) {
listener(view)
true
} else {
false
}
}
}
/**
* 设置 view 的背景,支持圆形和矩形,渐变色和描边圆角等
*
* @param shapeType 背景形状,圆、矩形等
* @param gradualColors 渐变色数组,和填充色互斥
* @param angle 渐变色角度
* @param solidColor 填充色,和渐变色数组互斥
* @param strokeColor 描边色
* @param stroke 描边粗细
* @param radius 圆角大小
*/
@JvmOverloads
fun View.setBgShapeGradual(
shapeType: Int = GradientDrawable.RECTANGLE,
@ColorInt gradualColors: IntArray? = null,
angle: Int = 0,
@ColorInt solidColor: Int? = null,
@ColorInt strokeColor: Int = Color.TRANSPARENT,
@Px stroke: Float = 0f,
@Px radius: Float = 0f
) {
background = GradientDrawable().apply {
shape = shapeType
useLevel = false
gradientType = GradientDrawable.LINEAR_GRADIENT
val remainder = angle % 45
val validAngle = if (remainder >= 22.5) {
angle % 360 + 45 - remainder
} else {
angle % 360 - remainder
}
orientation = when (validAngle) {
45 -> GradientDrawable.Orientation.BL_TR
90 -> GradientDrawable.Orientation.BOTTOM_TOP
135 -> GradientDrawable.Orientation.BR_TL
180 -> GradientDrawable.Orientation.RIGHT_LEFT
225 -> GradientDrawable.Orientation.TR_BL
270 -> GradientDrawable.Orientation.TOP_BOTTOM
315 -> GradientDrawable.Orientation.TL_BR
else -> GradientDrawable.Orientation.LEFT_RIGHT
}
if (gradualColors != null && solidColor == null) {
colors = gradualColors
} else if (gradualColors == null && solidColor != null) {
setColor(solidColor)
}
setStroke(stroke.toInt(), strokeColor)
cornerRadius = radius
}
}
/**
* 设置 view 在矩形某几个角上需要圆角的背景
*
* @param solidColor 填充色
* @param topLeft 左上圆角大小
* @param topRight 右上圆角大小
* @param bottomLeft 左下圆角大小
* @param bottomRight 左下圆角大小
*/
@JvmOverloads
fun View.setBgShapeCorners(
@ColorInt solidColor: Int = Color.WHITE,
@Px topLeft: Float = 0f,
@Px topRight: Float = 0f,
@Px bottomLeft: Float = 0f,
@Px bottomRight: Float = 0f
) {
background = GradientDrawable().apply {
shape = GradientDrawable.RECTANGLE
setColor(solidColor)
cornerRadii = floatArrayOf(
topLeft,
topLeft,
topRight,
topRight,
bottomRight,
bottomRight,
bottomLeft,
bottomLeft
)
}
}
fun View.marginDirection(direction: Int, @Px margin: Float) {
if (layoutParams is ViewGroup.MarginLayoutParams) {
val p = layoutParams as ViewGroup.MarginLayoutParams
when (direction) {
0 -> p.marginStart = margin.toInt()
1 -> p.topMargin = margin.toInt()
2 -> p.marginEnd = margin.toInt()
else -> p.bottomMargin = margin.toInt()
}
layoutParams = p
}
}
// ---------------------Context-------------------------------//
fun Context.addDynamicShortcutCompat(id: String, shortcut: ShortcutInfoCompat) {
if (
Build.VERSION.SDK_INT >= Build.VERSION_CODES.N_MR1 &&
ShortcutManagerCompat.getDynamicShortcuts(this).any { it.id == id }.not()
) {
try {
ShortcutManagerCompat.addDynamicShortcuts(this, mutableListOf(shortcut))
} catch (_: Exception) {
}
}
}
/**
* 取消音频静音
*/
fun Context.setMusicUnmute() {
setMusicMute(false)
}
/**
* 设置音频静音
*
* @param mute 是否静音
*/
fun Context.setMusicMute(mute: Boolean = true) {
getSystemService<AudioManager>()?.let {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
val direction = if (mute) AudioManager.ADJUST_UNMUTE else AudioManager.ADJUST_MUTE
it.adjustStreamVolume(AudioManager.STREAM_MUSIC, direction, 0)
} else {
it.setStreamMute(AudioManager.STREAM_MUSIC, mute)
}
}
}
// ---------------------Activity-------------------------------//
@MainThread
fun FragmentActivity.addFragment(
fragment: Fragment,
@IdRes containerViewId: Int = android.R.id.content,
isAddToBackStack: Boolean = false,
tag: String? = null
) {
supportFragmentManager.addFragment(fragment, containerViewId, isAddToBackStack, tag)
}
@MainThread
fun FragmentActivity.replaceFragment(
fragment: Fragment,
@IdRes containerViewId: Int = android.R.id.content,
isAddToBackStack: Boolean = false,
tag: String? = null
) {
supportFragmentManager.replaceFragment(fragment, containerViewId, isAddToBackStack, tag)
}
| 6
|
Kotlin
|
5
| 21
|
12ff6cc1349c36ca2ed532d28ddf6a74ff31ee9a
| 18,572
|
DemoApp
|
Apache License 2.0
|
backend/common-service/src/commonMain/kotlin/com/gchristov/thecodinglove/commonservice/CommonServiceModule.kt
|
gchristov
| 533,472,792
| false
|
{"Kotlin": 377856, "CSS": 87216, "HTML": 54731, "Shell": 1670, "JavaScript": 742, "Dockerfile": 315}
|
package com.gchristov.thecodinglove.commonservice
import co.touchlab.kermit.Logger
import com.gchristov.thecodinglove.commonservicedata.http.HttpService
import com.gchristov.thecodinglove.commonservicedata.pubsub.PubSubDecoder
import com.gchristov.thecodinglove.commonservicedata.pubsub.PubSubPublisher
import com.gchristov.thecodinglove.commonservicedata.pubsub.PubSubSubscription
import com.gchristov.thecodinglove.commonkotlin.AppConfig
import com.gchristov.thecodinglove.commonkotlin.di.DiModule
import com.gchristov.thecodinglove.commonkotlin.JsonSerializer
import org.kodein.di.DI
import org.kodein.di.bindProvider
import org.kodein.di.bindSingleton
import org.kodein.di.instance
object CommonServiceModule : DiModule() {
override fun name() = "common-service"
override fun bindDependencies(builder: DI.Builder) {
builder.apply {
bindProvider { provideHttpService(log = instance()) }
bindSingleton { providePubSubDecoder(jsonSerializer = instance()) }
bindSingleton { providePubSubPublisher() }
bindProvider {
providePubSubSubscription(
log = instance(),
appConfig = instance(),
)
}
}
}
}
expect fun provideHttpService(log: Logger): HttpService
expect fun providePubSubPublisher(): PubSubPublisher
expect fun providePubSubSubscription(
log: Logger,
appConfig: AppConfig,
): PubSubSubscription
expect fun providePubSubDecoder(jsonSerializer: JsonSerializer.Default): PubSubDecoder
| 0
|
Kotlin
|
0
| 3
|
977533cf18f2963a89fc3e93b2b7a2ce313bc0ae
| 1,560
|
thecodinglove-kotlinjs
|
Apache License 2.0
|
mineinabyss-features/src/main/kotlin/com/mineinabyss/features/gondolas/GondolaFeature.kt
|
MineInAbyss
| 115,279,675
| false
| null |
package com.mineinabyss.features.gondolas
import com.mineinabyss.components.gondolas.UnlockedGondolas
import com.mineinabyss.geary.modules.geary
import com.mineinabyss.geary.papermc.tracking.entities.toGeary
import com.mineinabyss.guiy.inventory.guiy
import com.mineinabyss.idofront.commands.arguments.stringArg
import com.mineinabyss.idofront.commands.extensions.actions.playerAction
import com.mineinabyss.idofront.features.Feature
import com.mineinabyss.idofront.features.FeatureDSL
import com.mineinabyss.idofront.messaging.error
import com.mineinabyss.idofront.messaging.success
class GondolaFeature : Feature() {
override fun FeatureDSL.enable() {
geary.pipeline.addSystems(
LoadedGondolas,
GondolaTracker()
)
mainCommand {
"gondola"(desc = "Commands for gondolas") {
permission = "mineinabyss.gondola"
"list"(desc = "Opens the gondola menu") {
permission = "mineinabyss.gondola.list"
playerAction {
guiy { GondolaSelectionMenu(player) }
}
}
"unlock"(desc = "Unlocks a gondola for a player") {
permission = "mineinabyss.gondola.unlock"
val gondola by stringArg()
playerAction {
val gondolas = player.toGeary().get<UnlockedGondolas>() ?: return@playerAction
gondolas.keys.add(gondola)
player.success("Unlocked $gondola")
}
}
"clear"(desc = "Removes all associated gondolas from a player") {
permission = "mineinabyss.gondola.clear"
playerAction {
val gondolas = player.toGeary().getOrSetPersisting<UnlockedGondolas> { UnlockedGondolas() }
gondolas.keys.clear()
player.error("Cleared all gondolas")
}
}
}
}
}
}
| 13
| null |
27
| 99
|
35b12abf13867de5a00acfc4804b1797751b842e
| 2,086
|
MineInAbyss
|
MIT License
|
core/src/commonMain/kotlin/com/erolc/mrouter/route/router/PageRouter.kt
|
ErolC
| 786,106,502
| false
|
{"Kotlin": 205561, "Swift": 620, "HTML": 304}
|
package com.erolc.mrouter.route.router
import com.erolc.mrouter.backstack.BackStack
import com.erolc.mrouter.backstack.entry.PageEntry
import com.erolc.mrouter.backstack.entry.StackEntry
import com.erolc.mrouter.model.Route
import com.erolc.mrouter.register.Address
import com.erolc.mrouter.utils.loge
import kotlinx.coroutines.flow.map
/**
* 页面路由器的实现,将管理一个载体(window/panel)内所有的页面
* @param addresses 存放着该库所注册的所有地址。
* @param parentRouter 父路由,对于window内的页面路由来说,[WindowRouter]将是其父路由,同理,对于panel内的页面路由来说[PanelRouter]将是其父路由。
* 路由器的关系将是[WindowRouter] -> [PageRouter] -> [PanelRouter] -> [PageRouter] -> [PanelRouter]
*/
open class PageRouter(name: String, private val addresses: List<Address>, override val parentRouter: Router) : Router {
internal val backStack = BackStack(name)
internal fun route(stackEntry: StackEntry) {
stackEntry as PageEntry
if (stackEntry.address.config.launchSingleTop)
backStack.findTopEntry()?.let {
if (it.address.path == stackEntry.address.path) {
it as PageEntry
it.scope.run {
args.value = stackEntry.scope.args.value
router = stackEntry.scope.router
onResult = stackEntry.scope.onResult
name = stackEntry.scope.name
}
} else null
} ?: backStack.addEntry(stackEntry.apply { create() })
else
backStack.addEntry(stackEntry.apply { create() })
}
/**
* 获取展示的stack
*/
internal fun getPlayStack() = backStack.backStack.map {
it.takeLast(2).map { it as PageEntry }
}
private fun backPressedImpl() = backStack.preBack(parentRouter)
/**
* 分配路由,将地址分配给不同的路由器并打开
*/
override fun dispatchRoute(route: Route) {
if (route.windowOptions.id == route.windowOptions.currentWindowId)
route(route)
else
parentRouter.dispatchRoute(route)
}
internal fun route(route: Route) {
val address = addresses.find { it.path == route.address }
if (address == null) {
loge("MRouter", "not yet register the address:${route.address}")
return
}
val entry = createPageEntry(route, address, PanelRouter(addresses, this))
route(entry)
}
/**
* 后退方法,将回退到前一个页面
* @param notInterceptor 是否不拦截
*/
override fun backPressed(notInterceptor: () -> Boolean) {
if (notInterceptor() && !backPressedImpl())
parentRouter.backPressed(notInterceptor)
}
internal fun getBackStack() = backStack.backStack
}
| 0
|
Kotlin
|
0
| 0
|
dacbb74a8c2e60359438c7b593c7d50027c06ede
| 2,665
|
MRouter
|
Apache License 2.0
|
src/main/kotlin/org/patternfly/Tag.kt
|
patternfly-kotlin
| 277,769,579
| false
|
{"Kotlin": 541078, "Shell": 3926}
|
package org.patternfly
import dev.fritz2.dom.Tag
import dev.fritz2.dom.html.RenderContext
import dev.fritz2.lenses.IdProvider
import kotlinx.coroutines.Job
import kotlinx.coroutines.flow.Flow
import org.w3c.dom.Element
import org.w3c.dom.Node
internal fun <V, I> Flow<List<V>>.renderShifted(
amount: Int,
tag: Tag<Element>,
idProvider: IdProvider<V, I>,
content: RenderContext.(V) -> RenderContext
) {
val jobs = mutableMapOf<Node, Job>()
/*
mountDomNodePatch(
tag.job,
tag.domNode,
scan(Pair(emptyList(), emptyList()), ::accumulate).map { (old, new) ->
Myer.diff(old, new, idProvider)
.map { patch ->
when (patch) {
is Patch.Insert -> patch.copy(index = patch.index + amount)
is Patch.InsertMany -> patch.copy(index = patch.index + amount)
is Patch.Delete -> patch.copy(start = patch.start + amount)
is Patch.Move -> patch.copy(from = patch.from + amount, to = patch.to + amount)
}
}.map { patch ->
patch.map(tag.job) { value, newJob ->
registerSingle(newJob, tag.unsafeCast<RenderContext>()) {
content(value)
}.also {
jobs[it.domNode] = newJob
}
}
}
}
) { node ->
val job = jobs.remove(node)
if (job != null) job.cancelChildren()
else console.error("could not cancel renderEach-jobs!")
}
*/
}
private fun <T> accumulate(
accumulator: Pair<List<T>, List<T>>,
newValue: List<T>
): Pair<List<T>, List<T>> = Pair(accumulator.second, newValue)
| 65
|
Kotlin
|
5
| 31
|
443c6d6ba229e3b27a57fc2ae28ae0d3f8dd973b
| 1,804
|
patternfly-kotlin
|
Apache License 2.0
|
packages/library-sync/src/commonMain/kotlin/io/realm/kotlin/mongodb/ext/MutableRealmExt.kt
|
realm
| 235,075,339
| false
|
{"Kotlin": 4564631, "C++": 126122, "SWIG": 26070, "Shell": 23822, "C": 5126, "CMake": 2858, "Ruby": 1586, "Java": 1470}
|
/*
* Copyright 2023 Realm Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.realm.kotlin.mongodb.ext
import io.realm.kotlin.MutableRealm
import io.realm.kotlin.UpdatePolicy
import io.realm.kotlin.internal.RealmObjectInternal
import io.realm.kotlin.mongodb.annotations.ExperimentalAsymmetricSyncApi
import io.realm.kotlin.types.AsymmetricRealmObject
/**
* Insert an [AsymmetricRealmObject] into Realm. Since asymmetric objects are "write-only", it is
* not possible to access the managed data after it has been inserted.
*
* @param obj the object to insert.
* @throws IllegalArgumentException if the object graph of [obj] either contains an object
* with a primary key value that already exists or an object from a previous version.
*/
@ExperimentalAsymmetricSyncApi
public fun <T : AsymmetricRealmObject> MutableRealm.insert(obj: T) {
@Suppress("invisible_member", "invisible_reference")
if (this is io.realm.kotlin.internal.InternalMutableRealm) {
val obj = io.realm.kotlin.internal.copyToRealm(
configuration.mediator,
realmReference,
obj,
UpdatePolicy.ERROR
)
(obj as RealmObjectInternal).io_realm_kotlin_objectReference!!.objectPointer.release()
} else {
throw IllegalStateException("Calling insert() on $this is not supported.")
}
}
| 242
|
Kotlin
|
57
| 942
|
df49eefacba8f57653e232203f44003643468463
| 1,869
|
realm-kotlin
|
Apache License 2.0
|
core/kotlinx-coroutines-core/test/channels/ChannelSendReceiveStressTest.kt
|
objcode
| 159,731,828
| false
| null |
/*
* Copyright 2016-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license.
*/
package kotlinx.coroutines.experimental.channels
import kotlinx.coroutines.experimental.*
import kotlinx.coroutines.experimental.selects.*
import org.junit.*
import org.junit.Assert.*
import org.junit.runner.*
import org.junit.runners.*
import java.util.concurrent.atomic.*
import kotlin.coroutines.experimental.*
@RunWith(Parameterized::class)
class ChannelSendReceiveStressTest(
val kind: TestChannelKind,
val nSenders: Int,
val nReceivers: Int
) : TestBase() {
companion object {
@Parameterized.Parameters(name = "{0}, nSenders={1}, nReceivers={2}")
@JvmStatic
fun params(): Collection<Array<Any>> =
listOf(1, 2, 10).flatMap { nSenders ->
listOf(1, 10).flatMap { nReceivers ->
TestChannelKind.values().map { arrayOf<Any>(it, nSenders, nReceivers) }
}
}
}
val timeLimit = 30_000L * stressTestMultiplier // 30 sec
val nEvents = 200_000 * stressTestMultiplier
val maxBuffer = 10_000 // artificial limit for LinkedListChannel
val channel = kind.create()
val sendersCompleted = AtomicInteger()
val receiversCompleted = AtomicInteger()
val dupes = AtomicInteger()
val sentTotal = AtomicInteger()
val received = AtomicIntegerArray(nEvents)
val receivedTotal = AtomicInteger()
val receivedBy = IntArray(nReceivers)
@Test
fun testSendReceiveStress() = runBlocking {
println("--- ChannelSendReceiveStressTest $kind with nSenders=$nSenders, nReceivers=$nReceivers")
val receivers = List(nReceivers) { receiverIndex ->
// different event receivers use different code
launch(DefaultDispatcher + CoroutineName("receiver$receiverIndex")) {
when (receiverIndex % 5) {
0 -> doReceive(receiverIndex)
1 -> doReceiveOrNull(receiverIndex)
2 -> doIterator(receiverIndex)
3 -> doReceiveSelect(receiverIndex)
4 -> doReceiveSelectOrNull(receiverIndex)
}
receiversCompleted.incrementAndGet()
}
}
val senders = List(nSenders) { senderIndex ->
launch(DefaultDispatcher + CoroutineName("sender$senderIndex")) {
when (senderIndex % 2) {
0 -> doSend(senderIndex)
1 -> doSendSelect(senderIndex)
}
sendersCompleted.incrementAndGet()
}
}
// print progress
val progressJob = launch(coroutineContext) {
var seconds = 0
while (true) {
delay(1000)
println("${++seconds}: Sent ${sentTotal.get()}, received ${receivedTotal.get()}")
}
}
try {
withTimeout(timeLimit) {
senders.forEach { it.join() }
channel.close()
receivers.forEach { it.join() }
}
} catch (e: CancellationException) {
println("!!! Test timed out $e")
}
progressJob.cancel()
println("Tested $kind with nSenders=$nSenders, nReceivers=$nReceivers")
println("Completed successfully ${sendersCompleted.get()} sender coroutines")
println("Completed successfully ${receiversCompleted.get()} receiver coroutines")
println(" Sent ${sentTotal.get()} events")
println(" Received ${receivedTotal.get()} events")
println(" Received dupes ${dupes.get()}")
repeat(nReceivers) { receiveIndex ->
println(" Received by #$receiveIndex ${receivedBy[receiveIndex]}")
}
assertEquals(nSenders, sendersCompleted.get())
assertEquals(nReceivers, receiversCompleted.get())
assertEquals(0, dupes.get())
assertEquals(nEvents, sentTotal.get())
if (!kind.isConflated) assertEquals(nEvents, receivedTotal.get())
repeat(nReceivers) { receiveIndex ->
assertTrue("Each receiver should have received something", receivedBy[receiveIndex] > 0)
}
}
private suspend fun doSent() {
sentTotal.incrementAndGet()
if (!kind.isConflated) {
while (sentTotal.get() > receivedTotal.get() + maxBuffer)
yield() // throttle fast senders to prevent OOM with LinkedListChannel
}
}
private suspend fun doSend(senderIndex: Int) {
for (i in senderIndex until nEvents step nSenders) {
channel.send(i)
doSent()
}
}
private suspend fun doSendSelect(senderIndex: Int) {
for (i in senderIndex until nEvents step nSenders) {
select<Unit> { channel.onSend(i) { Unit } }
doSent()
}
}
private fun doReceived(receiverIndex: Int, event: Int) {
if (!received.compareAndSet(event, 0, 1)) {
println("Duplicate event $event at $receiverIndex")
dupes.incrementAndGet()
}
receivedTotal.incrementAndGet()
receivedBy[receiverIndex]++
}
private suspend fun doReceive(receiverIndex: Int) {
while (true) {
try { doReceived(receiverIndex, channel.receive()) }
catch (ex: ClosedReceiveChannelException) { break }
}
}
private suspend fun doReceiveOrNull(receiverIndex: Int) {
while (true) {
doReceived(receiverIndex, channel.receiveOrNull() ?: break)
}
}
private suspend fun doIterator(receiverIndex: Int) {
for (event in channel) {
doReceived(receiverIndex, event)
}
}
private suspend fun doReceiveSelect(receiverIndex: Int) {
while (true) {
try {
val event = select<Int> { channel.onReceive { it } }
doReceived(receiverIndex, event)
} catch (ex: ClosedReceiveChannelException) { break }
}
}
private suspend fun doReceiveSelectOrNull(receiverIndex: Int) {
while (true) {
val event = select<Int?> { channel.onReceiveOrNull { it } } ?: break
doReceived(receiverIndex, event)
}
}
}
| 295
| null |
99
| 5
|
46741db4b0c2863475d5cc6fc75eafadd8e6199d
| 6,348
|
kotlinx.coroutines
|
Apache License 2.0
|
src/main/kotlin/com/williambl/haema/ritual/RitualTableScreenHandler.kt
|
williambl
| 204,155,762
| false
| null |
package com.williambl.haema.ritual
import com.williambl.haema.ability.AbilityModule
import com.williambl.haema.getAbilityLevel
import com.williambl.haema.id
import com.williambl.haema.ritual.craft.RitualInventory
import com.williambl.haema.setAbilityLevel
import io.netty.buffer.Unpooled
import net.fabricmc.api.EnvType
import net.fabricmc.api.Environment
import net.fabricmc.fabric.api.client.networking.v1.ClientPlayNetworking
import net.fabricmc.fabric.api.screenhandler.v1.ExtendedScreenHandlerFactory
import net.minecraft.entity.player.PlayerEntity
import net.minecraft.entity.player.PlayerInventory
import net.minecraft.network.PacketByteBuf
import net.minecraft.screen.PropertyDelegate
import net.minecraft.screen.ScreenHandler
import net.minecraft.screen.ScreenHandlerContext
import net.minecraft.server.network.ServerPlayerEntity
import net.minecraft.text.LiteralText
import net.minecraft.text.Text
import net.minecraft.util.registry.Registry
class RitualTableScreenHandler(syncId: Int, val inv: RitualInventory, private val context: ScreenHandlerContext)
: ScreenHandler(RitualModule.RITUAL_TABLE_SCREEN_HANDLER, syncId) {
constructor(syncId: Int, playerInventory: PlayerInventory, packetByteBuf: PacketByteBuf) : this(
syncId,
RitualInventory(
listOf(),
Registry.FLUID.get(packetByteBuf.readIdentifier()),
packetByteBuf.readBlockPos(),
playerInventory.player,
packetByteBuf.readVarInt()
),
ScreenHandlerContext.EMPTY
)
private val propertyDelegate = object : PropertyDelegate {
val abilities =
AbilityModule.ABILITY_REGISTRY.entrySet.associate { AbilityModule.ABILITY_REGISTRY.getRawId(it.value) to it.value }
override fun size(): Int = abilities.size
override fun get(index: Int): Int {
return inv.player.getAbilityLevel(abilities[index] ?: return 0)
}
override fun set(index: Int, value: Int) {
inv.player.setAbilityLevel(abilities[index] ?: return, value)
}
}
init {
addProperties(propertyDelegate)
}
fun getProperty(index: Int): Int = propertyDelegate[index]
@Environment(EnvType.CLIENT)
fun transferLevels(amount: Int, from: Int, to: Int) {
ClientPlayNetworking.send(id("transferlevels"), PacketByteBuf(Unpooled.buffer()).writeVarInt(syncId).writeVarInt(amount).writeVarInt(from).writeVarInt(to))
}
override fun canUse(player: PlayerEntity): Boolean = canUse(context, player, RitualTable.instance)
class Factory(private val inv: RitualInventory): ExtendedScreenHandlerFactory {
override fun createMenu(syncId: Int, playerInv: PlayerInventory, player: PlayerEntity): ScreenHandler {
return RitualTableScreenHandler(syncId, inv, ScreenHandlerContext.create(inv.player.world, inv.pos))
}
override fun getDisplayName(): Text {
return LiteralText("Ritual Table")
}
override fun writeScreenOpeningData(player: ServerPlayerEntity, buf: PacketByteBuf) {
buf.writeIdentifier(Registry.FLUID.getId(inv.fluid))
buf.writeBlockPos(inv.pos)
buf.writeVarInt(inv.level)
}
}
}
| 28
| null |
15
| 8
|
b4f14bfe91e720eb214b141f1d32e8336d08b430
| 3,244
|
haema
|
MIT License
|
src/main/kotlin/com/github/kkkiio/intellij/protobuf/utils/Debug.kt
|
KKKIIO
| 314,425,028
| false
|
{"Java": 792472, "Kotlin": 55946, "Lex": 12570, "PureBasic": 367, "HTML": 247}
|
package com.github.kkkiio.intellij.protobuf.utils
import com.goide.psi.GoCallExpr
import com.goide.psi.GoExpression
import com.goide.psi.GoFunctionOrMethodDeclaration
import com.goide.psi.GoType
import com.intellij.openapi.util.text.StringUtil
import com.intellij.psi.PsiElement
import com.intellij.psi.util.elementType
fun String.quoteKt() = StringUtil.wrapWithDoubleQuote(StringUtil.escapeStringCharacters(this))
fun PsiElement.repr() = "{text=${text.quoteKt()}, elementType=$elementType, class=${javaClass}}"
fun GoExpression.repr() = "{text=${text.quoteKt()}, class=${javaClass}}"
fun GoCallExpr.repr() = "{expression=${expression.repr()}, args=${argumentList.repr()}, class=${javaClass}}"
fun GoFunctionOrMethodDeclaration.repr() = "{name=$name, class=$javaClass}"
fun GoType.repr() = "{presentationText=${presentationText.quoteKt()}}"
| 2
|
Java
|
1
| 2
|
06b4bd04801826a95099ea750273fb9908aa3788
| 843
|
intellij-protobuf-support
|
Apache License 2.0
|
demos/sandbox-appyx-navigation/common/src/commonMain/kotlin/com/bumble/appyx/demos/sandbox/navigation/node/modal/ModalExamplesNode.kt
|
bumble-tech
| 493,334,393
| false
|
{"Kotlin": 829246, "Python": 2324, "HTML": 347, "Shell": 327, "CSS": 134}
|
package com.bumble.appyx.demos.sandbox.navigation.node.modal
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
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.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.remember
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.unit.dp
import com.bumble.appyx.components.modal.Modal
import com.bumble.appyx.components.modal.ModalModel
import com.bumble.appyx.components.modal.operation.add
import com.bumble.appyx.components.modal.operation.fullScreen
import com.bumble.appyx.components.modal.operation.revert
import com.bumble.appyx.components.modal.operation.show
import com.bumble.appyx.components.modal.ui.ModalVisualisation
import com.bumble.appyx.demos.sandbox.navigation.colors
import com.bumble.appyx.demos.sandbox.navigation.node.modal.ModalExamplesNode.NavTarget
import com.bumble.appyx.demos.sandbox.navigation.ui.TextButton
import com.bumble.appyx.demos.sandbox.navigation.ui.appyx_dark
import com.bumble.appyx.navigation.composable.AppyxNavigationContainer
import com.bumble.appyx.navigation.modality.NodeContext
import com.bumble.appyx.navigation.node.Node
import com.bumble.appyx.navigation.node.node
import com.bumble.appyx.utils.multiplatform.Parcelable
import com.bumble.appyx.utils.multiplatform.Parcelize
import kotlin.random.Random
class ModalExamplesNode(
nodeContext: NodeContext,
private val modal: Modal<NavTarget> = Modal(
model = ModalModel(
initialElements = listOf(NavTarget.Child),
savedStateMap = nodeContext.savedStateMap
),
visualisation = { ModalVisualisation(it) }
)
) : Node<NavTarget>(
nodeContext = nodeContext,
appyxComponent = modal
) {
sealed class NavTarget : Parcelable {
@Parcelize
object Child : NavTarget()
}
override fun buildChildNode(navTarget: NavTarget, nodeContext: NodeContext): Node<*> =
when (navTarget) {
is NavTarget.Child -> node(nodeContext) {
val backgroundColor = remember { colors.shuffled().random() }
Box(
modifier = Modifier
.fillMaxSize()
.background(backgroundColor)
) {
Text(
modifier = Modifier.align(Alignment.Center),
text = Random.nextInt(0, 100).toString(),
fontWeight = FontWeight.ExtraBold
)
}
}
}
@Composable
override fun Content(modifier: Modifier) {
Column(
modifier = modifier
.fillMaxSize()
.background(appyx_dark),
verticalArrangement = Arrangement.Bottom
) {
AppyxNavigationContainer(
appyxComponent = modal,
modifier = Modifier
.fillMaxSize()
.weight(0.9f)
)
Row(
modifier = Modifier
.weight(0.1f)
.fillMaxWidth()
.padding(horizontal = 16.dp),
horizontalArrangement = Arrangement.Center,
verticalAlignment = Alignment.CenterVertically
) {
TextButton(
text = "Add",
modifier = Modifier
.padding(horizontal = 4.dp),
) {
modal.add(NavTarget.Child)
}
TextButton(
text = "Show",
modifier = Modifier
.padding(horizontal = 4.dp),
) {
modal.show()
}
TextButton(
text = "Full",
modifier = Modifier
.padding(horizontal = 4.dp),
) {
modal.fullScreen()
}
TextButton(
text = "Revert",
modifier = Modifier
.padding(horizontal = 4.dp),
) {
modal.revert()
}
}
}
}
}
| 85
|
Kotlin
|
54
| 997
|
f5cc89fbdf9a168a70f8e9f11313e6524914179a
| 4,685
|
appyx
|
Apache License 2.0
|
app/src/main/java/com/diamont/expense/tracker/manageCategoriesFragment/ManageCategoriesFragment.kt
|
dagoston93
| 349,111,048
| false
| null |
package com.diamont.expense.tracker.manageCategoriesFragment
import android.os.Bundle
import android.util.Log
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.databinding.DataBindingUtil
import androidx.fragment.app.activityViewModels
import androidx.lifecycle.Observer
import androidx.lifecycle.ViewModelProvider
import com.diamont.expense.tracker.MainActivityViewModel
import com.diamont.expense.tracker.MainActivityViewModelFactory
import com.diamont.expense.tracker.R
import com.diamont.expense.tracker.addCategoryDialogFragment.AddCategoryDialogFragment
import com.diamont.expense.tracker.databinding.FragmentManageCategoriesBinding
import com.diamont.expense.tracker.util.database.TransactionCategoryListAdapter
import com.diamont.expense.tracker.util.database.TransactionDatabase
import com.google.android.material.dialog.MaterialAlertDialogBuilder
import kotlinx.android.synthetic.main.fragment_manage_categories.*
class ManageCategoriesFragment : Fragment() {
/** Data binding and view model */
private lateinit var binding : FragmentManageCategoriesBinding
private lateinit var viewModel: ManageCategoriesFragmentViewModel
/** Get the Activity View Model */
private val activityViewModel : MainActivityViewModel by activityViewModels {
MainActivityViewModelFactory(
requireNotNull(this.activity).application
)
}
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
/** Inflate the layout for this fragment */
binding = DataBindingUtil.inflate(inflater, R.layout.fragment_manage_categories, container, false)
binding.lifecycleOwner = this
/**
* Create the view model using a view model factory
*/
val application = requireNotNull(this.activity).application
val databaseDao = TransactionDatabase.getInstance(application).transactionDatabaseDao
val viewModelFactory = ManageCategoriesFragmentViewModelFactory(databaseDao)
viewModel = ViewModelProvider(this, viewModelFactory)
.get(ManageCategoriesFragmentViewModel::class.java)
/** Set up values for activity view model */
activityViewModel.setTitle(getString(R.string.manage_categories))
activityViewModel.setBottomNavBarVisibility(false)
activityViewModel.setUpButtonVisibility(true)
activityViewModel.setDrawerLayoutEnabled(false)
/** Set up the recycler view with the adapter */
val adapter = TransactionCategoryListAdapter(
{ id -> AddCategoryDialogFragment(id) {
viewModel.onCategoryListChanged()
}.show(childFragmentManager, AddCategoryDialogFragment.TAG)
},
{id, name, position ->
confirmDeleteCategory(id, name, position)
}
)
binding.rvTransactionCategoryList.adapter = adapter
/** Observe the data and refresh recycler view if it changes */
viewModel.categories.observe(viewLifecycleOwner, Observer {
it?.let{
adapter.submitList(it)
}
})
/**
* Add onClickListener to add category
*/
binding.llAddCategory.setOnClickListener {
AddCategoryDialogFragment(null) {
viewModel.onCategoryListChanged()
}.show(childFragmentManager, AddCategoryDialogFragment.TAG)
}
/** Return the inflated layout */
return binding.root
}
/**
* Call this method to show the confirmation dialog for deleting a category
*/
private fun confirmDeleteCategory(id: Int, name: String, position: Int){
MaterialAlertDialogBuilder(requireContext())
.setTitle(resources.getString(R.string.confirm_delete_dialog_title))
.setMessage(resources.getString(R.string.confirm_delete_category_dialog_text, name))
.setNegativeButton(resources.getString(R.string.cancel)) { _, _ -> }
.setPositiveButton(resources.getString(R.string.delete)) { _, _ ->
viewModel.deleteCategory(id)
}
.show()
}
}
| 0
|
Kotlin
|
0
| 2
|
d5f9bc53418400b46cd0bbdd1e7fd8ca3ff62ab8
| 4,308
|
expense-tracker
|
Apache License 2.0
|
shared/src/commonTest/kotlin/io/github/jelinekma/pragueopendatakotlinlib/v2/TestMedicalInstitutionsClient.kt
|
martinjelinek
| 763,563,087
| false
|
{"Kotlin": 230955}
|
package cz.vse.jelinekma.pragueopendatakotlinlib.v2
import cz.vse.golemiokotlinlib.v2.client.MedicalInstitutionsClient
import cz.vse.golemiokotlinlib.common.entity.responsedata.MedicalGroup
import cz.vse.golemiokotlinlib.common.entity.responsedata.MedicalInstitutionTypes
import cz.vse.jelinekma.pragueopendatakotlinlib.TestClient
import kotlinx.coroutines.test.runTest
import kotlin.test.BeforeTest
import kotlin.test.Test
import kotlin.test.assertEquals
import kotlin.test.assertTrue
class TestMedicalInstitutionsClient : TestClient() {
private lateinit var client: MedicalInstitutionsClient
@BeforeTest
fun setUp() {
client = MedicalInstitutionsClient(apiKey)
}
@Test
fun testGetAllMedicalInstitutions() = runTest {
val testData = client.getAllMedicalInstitutions(
latlng,
50000,
listOf("praha-4"),
MedicalGroup.PHARMACIES,
limit,
offset,
updatedSince
)
assertTrue { testData.isNotEmpty() }
}
@Test
fun getMedicalInstitutionById() = runTest {
val testData = client.getMedicalInstitutionById("53279-dopravni-podnik-hl-m-prahy-as-prakticky-lekar-a-rehabilitace")
assertEquals(
testData.properties?.name,
"Dopravní podnik hl. m. Prahy a.s., Praktický lékař a rehabilitace"
)
}
@Test
fun getMedicalInstitutionsTypesTest() = runTest {
val testData = client.getMedicalInstitutionTypes()
val expectedDate = MedicalInstitutionTypes(
listOf(
"Nemocniční lékárna s odbornými pracovišti",
"Lékárna",
"Lékárna s odbornými pracovišti",
"Výdejna",
"Vojenská lékárna",
"Vojenská lékárna s OOVL",
"Nemocniční lékárna",
"Lékárna s odbornými pracovišti s OOVL",
"Nemocniční lékárna s OOVL",
"Nemocniční lékárna s odbor. pracovišti s OOVL",
"Odloučené oddělení výdeje léčivých přípravků",
"Lékárna s OOVL",
"Lékárna s odborným pracovištěm, která zásobuje lůžková zdravotnická zařízení",
"Lékárna s odborným pracovištěm, která zásobuje lůžková zdravotnická zařízení s OOVL",
"Lékárna zásobujicí zařízení ústavní péče",
"Lékárna zásobujicí zařízení ústavní péče s OOVL"
),
listOf(
"Fakultní nemocnice",
"Nemocnice",
"Ostatní ambulantní zařízení",
"Ostatní zdravotnická zařízení",
"Zdravotní záchranná služba",
"Zdravotnické středisko"
),
)
assertEquals(testData, expectedDate)
}
}
| 0
|
Kotlin
|
0
| 2
|
b49495579ed1de62068fcccd8393357f2b386701
| 2,822
|
golemiokotlin
|
MIT License
|
kotlin_practice/src/main/java/dev/vengateshm/kotlin_practice/programs/ReverseWordsInString.kt
|
vengateshm
| 670,054,614
| false
|
{"Kotlin": 1781634, "Java": 43780}
|
package dev.vengateshm.kotlin_practice.programs
fun reverseWords(input: String): String {
val words = input.split(" ")
val reversedWords = words.map { word -> word.reversed() }
return reversedWords.joinToString(" ")
}
fun reverseWords1(input: String): String {
val words = mutableListOf<String>()
val sb = StringBuilder()
for (c in input) {
if (c == ' ') {
words.add(sb.toString())
sb.clear()
} else {
sb.insert(0, c)
}
}
words.add(sb.toString())
val reversedWords = StringBuilder()
for ((index, word) in words.withIndex()) {
if (index > 0) {
reversedWords.append(' ')
}
reversedWords.append(word)
}
return reversedWords.toString()
}
fun main() {
val input = "<NAME>"
val reversed = reverseWords1(input)
println(reversed)
}
| 0
|
Kotlin
|
0
| 1
|
6fa0f1c3170c56264ba85db4ac081831d6623575
| 883
|
Android-Kotlin-Jetpack-Compose-Practice
|
Apache License 2.0
|
core/src/commonMain/kotlin/io/data2viz/math/Percent.kt
|
data2viz
| 89,368,762
| false
| null |
/*
* Copyright (c) 2018-2019. data2viz sàrl.
*
* 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 io.data2viz.math
/**
* Utility class used to represent a percentage value.
* You can create a Percent using the default constructor:
* - val p = Percent(0.15) // 15%
*
* But it is easier to do so using the extension value ".pct":
* - val p = 15.pct //15%
*/
public inline class Percent(
public val value:Double) {
public operator fun plus(other: Percent) :Percent = Percent(value + other.value)
public operator fun minus(other: Percent) :Percent = Percent(value - other.value)
public operator fun times(other: Percent) :Percent = Percent(value * other.value)
public operator fun div(d: Number) :Percent = Percent(value / d.toDouble())
/**
* Operator to allow to write `20.pct * 3` (= 0.6)
*/
public operator fun times(d: Number) :Double = value * d.toDouble()
public operator fun unaryMinus() :Percent = Percent(-value)
public operator fun unaryPlus() :Percent = this
public operator fun compareTo(other:Percent) : Int = this.value.compareTo(other.value)
/**
* Ensures that this percent is not less than the specified min.
* @return this percent if it's greater than or equal to the min or the min otherwise.
*/
public fun coerceAtLeast(min:Percent): Percent = Percent(value.coerceAtLeast(min.value))
/**
* Ensures that this percent is not greater than the specified max.
* @return this percent if it's less than or equal to the max or the max otherwise.
*/
public fun coerceAtMost(max:Percent): Percent = Percent(value.coerceAtMost(max.value))
/**
* Ensures that this percent lies in the specified range min..max.
*
* @return this value if it's in the range, or minimumValue if this value is less than minimumValue,
* or maximumValue if this value is greater than maximumValue.
*/
public fun coerceIn(min:Percent, max:Percent): Percent = Percent(value.coerceIn(min.value, max.value))
/**
* if > 100% returns 100%,
* if < 0% returns 0%,
* else return the current value.
*/
public fun coerceToDefault(): Percent = Percent(value.coerceIn(.0, 1.0)) // TODO: rename ?
override fun toString(): String = "${value*100}%"
}
/**
* Extension property to create a percent from any number.
*/
public val Number.pct:Percent
get() = Percent(toDouble() / 100.0)
/**
* Extension operator to allow to write `3 * 20.pct` (= 0.6)
*/
public operator fun Number.times(percent:Percent): Double = percent.value * toDouble()
| 81
| null |
29
| 400
|
bc4ed872c526264727f868f5127e48462301dbf8
| 3,243
|
data2viz
|
Apache License 2.0
|
app/src/main/java/io/mainframe/hacs/status/SpaceStatusService.kt
|
ktt-ol
| 75,970,953
| false
|
{"Kotlin": 111905, "HTML": 4091, "JavaScript": 1200}
|
package io.mainframe.hacs.status
import com.launchdarkly.eventsource.EventHandler
import com.launchdarkly.eventsource.EventSource
import com.launchdarkly.eventsource.MessageEvent
import io.mainframe.hacs.common.Constants
import io.mainframe.hacs.main.Status
import okhttp3.internal.closeQuietly
import org.pmw.tinylog.Logger
import java.net.URI
import java.time.Duration
import java.util.concurrent.ConcurrentHashMap
import java.util.concurrent.CopyOnWriteArrayList
typealias EventCallback = (event: StatusEvent, value: String?) -> Unit
interface Subscription {
fun unsubscribe()
}
class SpaceStatusService {
private var eventSourceSse: EventSource? = null
private val lastValues = ConcurrentHashMap<StatusEvent, String>()
private val subscriptions = CopyOnWriteArrayList<EventCallback>()
fun connect() {
val eventHandler = object : EventHandler {
override fun onOpen() = Logger.debug("SSE open")
override fun onClosed() = Logger.debug("SSE closed")
override fun onError(t: Throwable) = Logger.error(t, "SSE error: ${t.message}")
override fun onComment(comment: String) = Logger.info("Got comment: $comment")
override fun onMessage(eventStr: String, messageEvent: MessageEvent) {
Logger.debug("SSE message: '{}' -> '{}'", eventStr, messageEvent.data)
val event = StatusEvent.forEventNameOrNull(eventStr) ?: return
lastValues[event] = messageEvent.data
subscriptions.forEach {
it(event, messageEvent.data)
}
}
}
try {
eventSourceSse = EventSource.Builder(eventHandler, URI.create(Constants.STATUS_SSE_URL))
.connectTimeout(Duration.ofSeconds(3))
.backoffResetThreshold(Duration.ofSeconds(3))
.build()
.also {
it.start()
}
} catch (e: Exception) {
Logger.error(e, "Can't subscribe to status: ${e.message}")
}
}
fun subscribe(callback: EventCallback): Subscription {
subscriptions.add(callback)
return object : Subscription {
override fun unsubscribe() {
subscriptions.remove(callback)
}
}
}
fun getLastValue(event: StatusEvent): String? = lastValues[event]
fun getLastStatusValue(event: StatusEvent): Status? =
getLastValue(event)?.let { Status.byEventStatusValue(it) }
fun disconnect() {
try {
eventSourceSse?.closeQuietly()
} catch (e: Exception) {
Logger.info(e, "Error during disconnecting: ${e.message}")
}
lastValues.clear()
subscriptions.clear()
}
}
| 9
|
Kotlin
|
2
| 24
|
436a68ca87ec2e187811ea002d5d3d7e71116f74
| 2,785
|
hacs
|
MIT License
|
src/main/kotlin/no/nav/meldeplikt/meldekortservice/model/meldegruppe/MeldegruppeResponse.kt
|
navikt
| 207,759,254
| false
|
{"Kotlin": 167950, "Shell": 759, "Dockerfile": 249}
|
package no.nav.meldeplikt.meldekortservice.model.meldegruppe
import com.fasterxml.jackson.annotation.JsonIgnoreProperties
import com.fasterxml.jackson.annotation.JsonInclude
@JsonInclude(JsonInclude.Include.NON_NULL)
@JsonIgnoreProperties(ignoreUnknown = true)
data class MeldegruppeResponse(
val meldegruppeListe: List<Meldegruppe>
)
| 0
|
Kotlin
|
1
| 0
|
f97ad256afeba299f5fda62ddc49ccb579d82011
| 341
|
meldekortservice
|
MIT License
|
sdk/src/main/java/io/matchmore/sdk/Matchmore.kt
|
matchmore
| 113,169,361
| false
|
{"Kotlin": 286033, "Java": 12753, "Shell": 510}
|
package io.matchmore.sdk
import android.Manifest
import android.annotation.SuppressLint
import android.content.Context
import android.support.annotation.RequiresPermission
import io.matchmore.sdk.api.ErrorCallback
import io.matchmore.sdk.api.SuccessCallback
import io.matchmore.sdk.api.models.*
import io.matchmore.sdk.managers.MatchmoreLocationManager
import io.matchmore.sdk.managers.MatchmoreLocationProvider
import io.matchmore.sdk.monitoring.MatchMonitor
import io.matchmore.sdk.store.AsyncReadable
import io.matchmore.sdk.store.CRD
@SuppressLint("StaticFieldLeak")
object Matchmore {
private var matchmoreConfig: MatchmoreConfig? = null
@JvmStatic
val instance: MatchmoreSDK by lazy {
if (!isConfigured()) throw IllegalStateException("Please config first.")
AlpsManager(matchmoreConfig!!)
}
@JvmStatic
@JvmOverloads
fun config(context: Context, apiKey: String, debugLog: Boolean = false) {
if (isConfigured()) throw IllegalStateException("You can not overwrite the configuration.")
this.matchmoreConfig = MatchmoreConfig(context, apiKey, debugLog)
}
@JvmStatic
fun isConfigured() = this.matchmoreConfig != null
}
interface MatchmoreSDK {
/**
* Main mobile device created by `startUsingMainDevice()`.
*/
val main: MobileDevice?
/**
* Async store of all created publications.
*/
val publications: CRD<Publication>
/**
* Async store of all created subscriptions.
*/
val subscriptions: CRD<Subscription>
/**
* Async store of all created devices.
*/
val devices: CRD<Device>
/**
* Async store of all known iBeacon Triples.
*/
val knownBeacons: AsyncReadable<IBeaconTriple>
/**
* [MatchMonitor] allows getting information about new matches, by using listeners.
* It can be used, by opening socket, polling or remote notification.
*/
val matchMonitor: MatchMonitor
/**
* Object responsible for getting location data that will be sent to Matchmore's cloud.
* It's possible to inject your own location manager by conforming to [MatchmoreLocationManager] interface.
*/
val locationManager: MatchmoreLocationManager
/**
* Cached set of matches that have been downloaded so far.
*/
val matches: Set<Match>
/**
* starts updating and sending user's location to Matchmore's cloud.
* Frequency of updates is strictly related to location manager configuration.
*/
@RequiresPermission(Manifest.permission.ACCESS_FINE_LOCATION)
fun startUpdatingLocation()
/**
* Starts updating and sending user's location to Matchmore's cloud.
* Frequency of updates is strictly related to custom object's configuration.
* @property locationProvider object that provides location data, it has to conform to [MatchmoreLocationProvider] interface.
*/
fun startUpdatingLocation(locationProvider: MatchmoreLocationProvider)
/**
* Stops updating and sending user's location to Matchmore's cloud.
*/
fun stopUpdatingLocation()
/**
* Starts ranging known beacons. Known beacon id's can be configured in Matchmore's portal (https://matchmore.io)
*/
@RequiresPermission(allOf = [Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.BLUETOOTH])
fun startRanging()
/**
* Stops ranging known beacons.
*/
fun stopRanging()
/**
* Automatically creates or reuses cached mobile device object. Mobile device object is used to represent the user's smartphone.
*
* @property success Callback that returns successful response from the Matchmore's cloud.
* @property error Callback that returns error response from the Matchmore's cloud.
*/
fun startUsingMainDevice(success: SuccessCallback<MobileDevice>? = null, error: ErrorCallback? = null)
= startUsingMainDevice(null, success, error)
/**
* Creates given mobile device object. Mobile device object is used to represent the user's smartphone.
*
* @property device [MobileDevice] object that will be created on Matchmore's cloud.
* @property success Callback that returns successful response from the Matchmore's cloud.
* @property error Callback that returns error response from the Matchmore's cloud.
*/
fun startUsingMainDevice(device: MobileDevice? = null, success: SuccessCallback<MobileDevice>? = null, error: ErrorCallback? = null)
/**
* Creates new publication attached to main device.
*
* @property publication [Publication] object that will be created on Matchmore's cloud.
* @property success Callback that returns successful response from the Matchmore's cloud.
* @property error Callback that returns error response from the Matchmore's cloud.
*/
fun createPublicationForMainDevice(publication: Publication, success: SuccessCallback<Publication>?, error: ErrorCallback?)
= createPublication(publication, null, success, error)
/**
* Creates new publication attached to device with given id.
*
* @property publication [Publication] object that will be created on Matchmore's cloud.
* @property deviceWithId id of the device that publication will be attached to.
* @property success Callback that returns successful response's object from the Matchmore's cloud.
* @property error Callback that returns error response from the Matchmore's cloud.
*/
fun createPublication(publication: Publication, deviceWithId: String? = null, success: SuccessCallback<Publication>?, error: ErrorCallback?)
/**
* Creates new subscription attached to main device.
*
* @property subscription [Subscription] object that will be created on Matchmore's cloud.
* @property success Callback that returns successful response's object from the Matchmore's cloud.
* @property error Callback that returns error response from the Matchmore's cloud.
*/
fun createSubscriptionForMainDevice(subscription: Subscription, success: SuccessCallback<Subscription>?, error: ErrorCallback?)
= createSubscription(subscription, null, success, error)
/**
* Creates new subscription attached to device with given id.
*
* @property subscription [Subscription] object that will be created on Matchmore's cloud.
* @property deviceWithId id of the device that publication will be attached to.
* @property success Callback that returns successful response's object from the Matchmore's cloud.
* @property error Callback that returns error response from the Matchmore's cloud.
*/
fun createSubscription(subscription: Subscription, deviceWithId: String? = null, success: SuccessCallback<Subscription>?, error: ErrorCallback?)
/**
* Creates new pin device. Device created this way can be accessed via devices store: devices property or through callback's result.
*
* @property pinDevice [PinDevice] object that will be created on Matchmore's cloud.
* @property success Callback that returns successful response's object from the Matchmore's cloud.
* @property error Callback that returns error response from the Matchmore's cloud.
*/
fun createPinDevice(pinDevice: PinDevice, success: SuccessCallback<PinDevice>?, error: ErrorCallback?)
}
| 2
|
Kotlin
|
1
| 2
|
0dfd5ba1953cf04e425d410954b05464b809be39
| 7,378
|
android-sdk
|
MIT License
|
src/main/kotlin/co/mercenary/creators/kotlin/util/json/text/emoji/JSONEmoji.kt
|
mercenary-creators
| 193,142,947
| false
| null |
/*
* Copyright (c) 2021, Mercenary Creators Company. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package co.mercenary.creators.kotlin.util.json.text.emoji
import co.mercenary.creators.kotlin.util.*
class JSONEmoji @FrameworkDsl constructor(private val unicode: String, private val description: String, private val fitzpatrick: Boolean, tags: List<String>, aliases: List<String>) : Emoji {
@FrameworkDsl
private val look = tags.unique().toSorted()
@FrameworkDsl
private val nick = aliases.unique().toSorted()
@FrameworkDsl
override fun getTags(): List<String> {
return look
}
@FrameworkDsl
override fun getAliases(): List<String> {
return nick
}
@FrameworkDsl
override fun getUnicode(code: FitzpatrickExtensionCode): String {
if (isNotFitzpatrick() || code.isNotValid()) {
return getUnicode()
}
return getUnicode(code.toFitzpatrickExtensionType())
}
@FrameworkDsl
override fun getUnicode(type: FitzpatrickExtensionType): String {
if (isNotFitzpatrick() || type.isNotValid()) {
return getUnicode()
}
return getUnicode() + type.getUnicode()
}
@FrameworkDsl
override fun getDescription(): String {
return description.copyOf()
}
@FrameworkDsl
override fun isFitzpatrick(): Boolean {
return fitzpatrick.copyOf()
}
@FrameworkDsl
override fun getUnicode(): String {
return unicode.copyOf()
}
@FrameworkDsl
override fun sizeOf(): Int {
return getUnicode().sizeOf()
}
@FrameworkDsl
override fun toString(): String {
return toJSONString()
}
@FrameworkDsl
override fun hashCode() = idenOf()
@FrameworkDsl
override fun equals(other: Any?) = when (other) {
is JSONEmoji -> this === other || getUnicode() == other.getUnicode() && getDescription() == other.getDescription() && isFitzpatrick() == other.isFitzpatrick() && getTags() isSameAs other.getTags() && getAliases() isSameAs other.getAliases()
else -> false
}
}
| 0
|
Kotlin
|
0
| 0
|
ed38450a1a189230b999eebbb641b1f782589318
| 2,645
|
mercenary-creators-kotlin-util
|
Apache License 2.0
|
core/navigation/src/commonMain/kotlin/nay.kirill.glassOfWater.navigation/Navigation.kt
|
kirillNay
| 695,954,274
| false
|
{"Kotlin": 128591, "HTML": 393}
|
package nay.kirill.glassOfWater.navigation
import kotlinx.coroutines.flow.MutableSharedFlow
class Navigation {
val eventsStack = MutableSharedFlow<Event>(
extraBufferCapacity = 1
)
fun navigateTo(screen: SharedScreens) {
eventsStack.tryEmit(Event.Forward(screen))
}
fun back() {
eventsStack.tryEmit(Event.Back)
}
sealed interface Event {
data class Forward(val screen: SharedScreens) : Event
data object Back : Event
}
}
| 0
|
Kotlin
|
0
| 0
|
d8ab543f790d09f8682913b786dc7d54686bf55a
| 502
|
GlassOfWater-mini-app
|
MIT License
|
compiler/testData/compileJavaAgainstKotlin/class/ImplementsMapPP.kt
|
JakeWharton
| 99,388,807
| true
| null |
package test
abstract class Mine<P1, P2> : java.util.Map<P2, P1>
| 179
|
Kotlin
|
5640
| 83
|
4383335168338df9bbbe2a63cb213a68d0858104
| 66
|
kotlin
|
Apache License 2.0
|
app/src/main/java/org/xtimms/ridebus/data/updater/app/AppUpdateResult.kt
|
ridebus-by
| 379,109,231
| false
| null |
package org.xtimms.ridebus.data.updater.app
sealed class AppUpdateResult {
class NewUpdate(val release: GithubRelease) : AppUpdateResult()
object NoNewUpdate : AppUpdateResult()
}
| 0
|
Kotlin
|
0
| 7
|
086da0d23cdbb238c35622053568361802ebd2bc
| 189
|
ridebus
|
Apache License 2.0
|
apps/etterlatte-behandling/src/main/kotlin/sak/SakRoutes.kt
|
navikt
| 417,041,535
| false
|
{"Kotlin": 6309786, "TypeScript": 1570250, "Handlebars": 27542, "Shell": 12438, "HTML": 1734, "Dockerfile": 676, "CSS": 598, "PLpgSQL": 556}
|
package no.nav.etterlatte.sak
import io.ktor.http.HttpStatusCode
import io.ktor.server.application.call
import io.ktor.server.request.receive
import io.ktor.server.response.respond
import io.ktor.server.routing.Route
import io.ktor.server.routing.get
import io.ktor.server.routing.post
import io.ktor.server.routing.route
import no.nav.etterlatte.behandling.BehandlingRequestLogger
import no.nav.etterlatte.behandling.BehandlingService
import no.nav.etterlatte.behandling.domain.Grunnlagsendringshendelse
import no.nav.etterlatte.behandling.domain.TilstandException
import no.nav.etterlatte.behandling.hendelse.HendelseDao
import no.nav.etterlatte.common.Enheter
import no.nav.etterlatte.grunnlagsendring.GrunnlagsendringsListe
import no.nav.etterlatte.grunnlagsendring.GrunnlagsendringshendelseService
import no.nav.etterlatte.grunnlagsendring.SakMedEnhet
import no.nav.etterlatte.inTransaction
import no.nav.etterlatte.libs.common.Enhetsnummer
import no.nav.etterlatte.libs.common.behandling.FoersteVirkDto
import no.nav.etterlatte.libs.common.behandling.SakType
import no.nav.etterlatte.libs.common.behandling.SisteIverksatteBehandling
import no.nav.etterlatte.libs.common.feilhaandtering.GenerellIkkeFunnetException
import no.nav.etterlatte.libs.common.feilhaandtering.IkkeFunnetException
import no.nav.etterlatte.libs.common.feilhaandtering.UgyldigForespoerselException
import no.nav.etterlatte.libs.common.person.Folkeregisteridentifikator
import no.nav.etterlatte.libs.common.sak.HentSakerRequest
import no.nav.etterlatte.libs.common.sak.Sak
import no.nav.etterlatte.libs.common.sak.SakId
import no.nav.etterlatte.libs.common.sak.Saker
import no.nav.etterlatte.libs.ktor.route.SAKID_CALL_PARAMETER
import no.nav.etterlatte.libs.ktor.route.kunSaksbehandler
import no.nav.etterlatte.libs.ktor.route.kunSystembruker
import no.nav.etterlatte.libs.ktor.route.medBody
import no.nav.etterlatte.libs.ktor.route.sakId
import no.nav.etterlatte.libs.ktor.token.brukerTokenInfo
import no.nav.etterlatte.oppgave.OppgaveService
import no.nav.etterlatte.tilgangsstyring.kunSaksbehandlerMedSkrivetilgang
import no.nav.etterlatte.tilgangsstyring.withFoedselsnummerInternal
import org.slf4j.LoggerFactory
const val KJOERING = "kjoering"
const val ANTALL = "antall"
internal fun Route.sakSystemRoutes(
tilgangService: TilgangService,
sakService: SakService,
behandlingService: BehandlingService,
requestLogger: BehandlingRequestLogger,
) {
val logger = LoggerFactory.getLogger(this::class.java)
route("/saker") {
post("/{$KJOERING}/{$ANTALL}") {
kunSystembruker {
val kjoering = call.parameters[KJOERING]!!
val antall = call.parameters[ANTALL]!!.toInt()
val request = call.receive<HentSakerRequest>()
val spesifikkeSaker = request.spesifikkeSaker
val ekskluderteSaker = request.ekskluderteSaker
val sakstype = request.sakType
val loependeFom = request.loependeFom
call.respond(
Saker(
inTransaction {
sakService.hentSaker(
kjoering,
antall,
spesifikkeSaker,
ekskluderteSaker,
sakstype,
loependeFom,
)
},
),
)
}
}
post("hent") {
kunSystembruker {
medBody<HentSakerRequest> { dto ->
val saker = inTransaction { sakService.hentSakerMedIder(dto.spesifikkeSaker) }
call.respond(SakerDto(saker))
}
}
}
route("/{$SAKID_CALL_PARAMETER}") {
get {
val sak =
inTransaction {
sakService.finnSak(sakId)
} ?: throw GenerellIkkeFunnetException()
call.respond(sak)
}
get("/behandlinger") {
kunSystembruker {
val sakMedBehandlinger =
inTransaction {
val sak = sakService.finnSak(sakId) ?: throw SakIkkeFunnetException("Fant ikke sak=$sakId")
behandlingService.hentSakMedBehandlinger(listOf(sak))
}
call.respond(sakMedBehandlinger)
}
}
get("/behandlinger/sisteIverksatte") {
logger.info("Henter siste iverksatte behandling for $sakId")
val sisteIverksatteBehandling =
inTransaction {
behandlingService
.hentSisteIverksatte(sakId)
?.let { SisteIverksatteBehandling(it.id) }
} ?: throw GenerellIkkeFunnetException()
call.respond(sisteIverksatteBehandling)
}
get("/gradering") {
kunSystembruker { systemBruker ->
logger.info("Henter gradering i sak med id=$sakId")
val gradering =
inTransaction {
sakService.hentGraderingForSak(sakId, systemBruker)
}
call.respond(gradering)
}
}
}
}
post("personer/saker/{type}") {
withFoedselsnummerInternal(tilgangService) { fnr ->
val type: SakType =
enumValueOf(requireNotNull(call.parameters["type"]) { "Må ha en Saktype for å finne eller opprette sak" })
val message = inTransaction { sakService.finnEllerOpprettSakMedGrunnlag(fnr = fnr.value, type) }
requestLogger.loggRequest(brukerTokenInfo, fnr, "personer/saker")
call.respond(message)
}
}
post("personer/getsak/{type}") {
withFoedselsnummerInternal(tilgangService) { fnr ->
val type: SakType =
enumValueOf(requireNotNull(call.parameters["type"]) { "Må ha en Saktype for å finne sak" })
val sak =
inTransaction { sakService.finnSak(fnr.value, type) }.also {
requestLogger.loggRequest(brukerTokenInfo, fnr, "personer/sak")
} ?: throw GenerellIkkeFunnetException()
call.respond(sak)
}
}
}
class PersonManglerSak :
IkkeFunnetException(
code = "PERSON_MANGLER_SAK",
detail = "Personen har ingen saker i Gjenny",
)
class SakIkkeFunnetException(
message: String,
) : UgyldigForespoerselException(
code = "FANT_INGEN_SAK",
detail = message,
)
internal fun Route.sakWebRoutes(
tilgangService: TilgangService,
sakService: SakService,
behandlingService: BehandlingService,
grunnlagsendringshendelseService: GrunnlagsendringshendelseService,
oppgaveService: OppgaveService,
requestLogger: BehandlingRequestLogger,
hendelseDao: HendelseDao,
) {
val logger = LoggerFactory.getLogger(this::class.java)
route("/api") {
route("/sak/{$SAKID_CALL_PARAMETER}") {
get {
val sak =
inTransaction {
sakService.finnSak(sakId)
} ?: throw GenerellIkkeFunnetException()
call.respond(sak)
}
get("/grunnlagsendringshendelser") {
call.respond(
inTransaction {
GrunnlagsendringsListe(
grunnlagsendringshendelseService.hentAlleHendelserForSak(
sakId,
),
)
},
)
}
post("/endre_enhet") {
kunSaksbehandlerMedSkrivetilgang { navIdent ->
val enhetrequest = call.receive<EnhetRequest>()
try {
if (enhetrequest.enhet !in Enheter.entries.map { it.enhetNr }) {
throw UgyldigForespoerselException(
code = "ENHET IKKE GYLDIG",
detail = "enhet ${enhetrequest.enhet} er ikke i listen over gyldige enheter",
)
}
inTransaction { sakService.finnSak(sakId) }
?: throw SakIkkeFunnetException("Fant ingen sak å endre enhet på sakid: $sakId")
val sakMedEnhet =
SakMedEnhet(
enhet = enhetrequest.enhet,
id = sakId,
)
inTransaction {
sakService.oppdaterEnhetForSaker(listOf(sakMedEnhet))
oppgaveService.oppdaterEnhetForRelaterteOppgaver(listOf(sakMedEnhet))
}
logger.info(
"Saksbehandler ${navIdent.ident} endret enhet på sak: $sakId og " +
"tilhørende oppgaver til enhet: ${sakMedEnhet.enhet}",
)
call.respond(HttpStatusCode.OK)
} catch (e: TilstandException.UgyldigTilstand) {
call.respond(HttpStatusCode.BadRequest, "Kan ikke endre enhet på sak og oppgaver")
}
}
}
get("flyktning") {
val flyktning = inTransaction { sakService.finnFlyktningForSak(sakId) }
call.respond(flyktning ?: HttpStatusCode.NoContent)
}
get("/behandlinger/foerstevirk") {
logger.info("Henter første virkningstidspunkt på en iverksatt behandling i sak med id $sakId")
val foersteVirk =
inTransaction { behandlingService.hentFoerstegangsbehandling(sakId).virkningstidspunkt?.dato }
?: throw GenerellIkkeFunnetException()
call.respond(FoersteVirkDto(foersteVirk.atDay(1), sakId))
}
get("/hendelser") {
logger.info("Henter behandlingshendelser i sak med sakId=$sakId")
val hendelser = inTransaction { hendelseDao.hentHendelserISak(sakId) }
call.respond(hendelser)
}
}
route("/personer/") {
post("/navkontor") {
withFoedselsnummerInternal(tilgangService) { fnr ->
val navkontor = sakService.finnNavkontorForPerson(fnr.value)
call.respond(navkontor)
}
}
post("/behandlingerforsak") {
withFoedselsnummerInternal(tilgangService) { fnr ->
val sakMedBehandlinger =
inTransaction {
val saker = sakService.finnSaker(fnr.value)
behandlingService.hentSakMedBehandlinger(saker)
}
requestLogger.loggRequest(
brukerTokenInfo,
Folkeregisteridentifikator.of(sakMedBehandlinger.sak.ident),
"behandlinger",
)
call.respond(sakMedBehandlinger)
}
}
post("sak/{type}") {
withFoedselsnummerInternal(tilgangService) { fnr ->
val opprettHvisIkkeFinnes = call.request.queryParameters["opprettHvisIkkeFinnes"].toBoolean()
val type: SakType =
requireNotNull(call.parameters["type"]) {
"Mangler påkrevd parameter {type} for å hente sak på bruker"
}.let { enumValueOf(it) }
val sak =
inTransaction {
if (opprettHvisIkkeFinnes) {
sakService.finnEllerOpprettSakMedGrunnlag(fnr.value, type)
} else {
sakService.finnSak(fnr.value, type)
}
}.also { requestLogger.loggRequest(brukerTokenInfo, fnr, "personer/sak/type") }
call.respond(sak ?: HttpStatusCode.NoContent)
}
}
post("/getsak/oms") {
withFoedselsnummerInternal(tilgangService) { fnr ->
val saker =
inTransaction { sakService.finnSakerOmsOgHvisAvdoed(fnr.value) }.also {
requestLogger.loggRequest(brukerTokenInfo, fnr, "api/personer/getsak/oms")
}
call.respond(saker)
}
}
post("arkivergrunnlagsendringshendelse") {
kunSaksbehandler { saksbehandler ->
val arkivertHendelse = call.receive<Grunnlagsendringshendelse>()
grunnlagsendringshendelseService.arkiverHendelseMedKommentar(
hendelse = arkivertHendelse,
saksbehandler,
)
call.respond(HttpStatusCode.OK)
}
}
}
}
}
data class EnhetRequest(
val enhet: Enhetsnummer,
)
data class SakerDto(
val saker: Map<SakId, Sak>,
)
| 8
|
Kotlin
|
0
| 6
|
e715675c319d4a0a826855615749573e45ae7a75
| 13,664
|
pensjon-etterlatte-saksbehandling
|
MIT License
|
app/src/main/java/com/hritikbhat/spotify_mvvm_app/ui/fragments/FavouritePlaylistSubFragments/FavouritePlaylistStartFragment.kt
|
HritikBhat
| 714,975,797
| false
|
{"Kotlin": 222613}
|
package com.hritikbhat.spotify_mvvm_app.ui.Fragments.FavouritePlaylistSubFragments
import android.content.SharedPreferences
import android.os.Bundle
import android.util.Log
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.databinding.DataBindingUtil
import androidx.lifecycle.ViewModelProvider
import androidx.lifecycle.viewModelScope
import androidx.navigation.fragment.findNavController
import androidx.recyclerview.widget.LinearLayoutManager
import com.hritikbhat.spotify_mvvm_app.R
import com.hritikbhat.spotify_mvvm_app.Utils.SharedPreferenceInstance
import com.hritikbhat.spotify_mvvm_app.adapters.FavPlaylistAdapter
import com.hritikbhat.spotify_mvvm_app.databinding.FragmentFavouritePlaylistStartBinding
import com.hritikbhat.spotify_mvvm_app.models.FavPlaylistQuery
import com.hritikbhat.spotify_mvvm_app.models.FavPlaylistsX
import com.hritikbhat.spotify_mvvm_app.models.OperationResult
import com.hritikbhat.spotify_mvvm_app.models.Playlist
import com.hritikbhat.spotify_mvvm_app.models.favPlaylists
import com.hritikbhat.spotify_mvvm_app.viewModels.SubFragmentsViewModels.FavPlaylistViewModel
import kotlinx.coroutines.launch
class FavouritePlaylistStartFragment : Fragment(),FavPlaylistAdapter.OnItemClickListener {
private lateinit var viewModel: FavPlaylistViewModel
private lateinit var binding: FragmentFavouritePlaylistStartBinding
private lateinit var sharedPref: SharedPreferences
private lateinit var currPassHash:String
private val favPlaylistRCAdapter = FavPlaylistAdapter()
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View {
binding = DataBindingUtil.inflate(inflater, R.layout.fragment_favourite_playlist_start, container, false)
sharedPref = SharedPreferenceInstance(requireContext()).getSPInstance()
currPassHash = sharedPref.getString("passHash", "").toString()
binding.favPlaylistRC.layoutManager = LinearLayoutManager(context)
viewModel = ViewModelProvider(this)[FavPlaylistViewModel::class.java]
viewModel.viewModelScope.launch {
getUserFavPlaylist()
}
return binding.root
}
private suspend fun getUserFavPlaylist(){
val operationResult: OperationResult<favPlaylists> =
viewModel.getUserFavPlaylist(FavPlaylistQuery(currPassHash,"-1"))
when (operationResult) {
is OperationResult.Success -> {
// Operation was successful, handle the result
val favTransactionResp : favPlaylists = operationResult.data
// if (favTransactionResp.favPlaylists.isEmpty()){
// binding.favPlaylistRC.visibility=View.GONE
// binding.noFavouriteLayout.visibility = View.VISIBLE
// }
// else{
// binding.favPlaylistRC.visibility=View.VISIBLE
// binding.noFavouriteLayout.visibility = View.GONE
// }
val favplaylist = ArrayList<FavPlaylistsX>()
favplaylist.add(FavPlaylistsX(-2, "Create Playlist",-1,""))
favplaylist.add(FavPlaylistsX(-1,"Favourite Songs",-1,""))
favplaylist.addAll(favTransactionResp.favPlaylists)
favPlaylistRCAdapter.updateItems(favplaylist.toList())
binding.favPlaylistRC.adapter = favPlaylistRCAdapter
favPlaylistRCAdapter.setOnItemClickListener(this)
binding.loadingLayout.visibility= View.GONE
binding.favPlaylistRC.visibility= View.VISIBLE
}
is OperationResult.Error -> {
// An error occurred, handle the error
val errorMessage = operationResult.message
Log.e("ERROR", errorMessage)
// Handle the error, for example, display an error message to the user
}
}
}
override fun onItemClick(plid: Int, pname: String, ptype: Int, aname: String) {
viewModel.viewModelScope.launch {
if (plid==-2){
//Send to Custom Playlist Creation
findNavController().navigate(R.id.action_favouritePlaylistStartFragment_to_addCustomPlaylistFragment)
}
else{
//Go to show playlist
val playlist = Playlist(plid,pname,ptype,aname)
val showPlaylistSongsFragmentAction = FavouritePlaylistStartFragmentDirections.actionFavouritePlaylistStartFragmentToShowPlaylistNavGraph(playlist)
findNavController().navigate(showPlaylistSongsFragmentAction)
}
}
}
}
| 0
|
Kotlin
|
0
| 0
|
d73ca6a4405848550b9fdd384c216e41cf324d76
| 4,800
|
Spotify_Clone_MVVM_App
|
MIT License
|
src/jvmTest/kotlin/com/inari/firefly/examples/EasingTest2.kt
|
AndreasHefti
| 387,557,032
| false
| null |
package com.inari.firefly.examples
import com.inari.firefly.*
import com.inari.firefly.core.api.ShapeType
import com.inari.firefly.entity.Entity
import com.inari.firefly.entity.EntitySystem
import com.inari.firefly.graphics.ETransform
import com.inari.firefly.graphics.rendering.RenderingSystem
import com.inari.firefly.graphics.rendering.SimpleTextRenderer
import com.inari.firefly.graphics.shape.EShape
import com.inari.firefly.graphics.text.EText
import com.inari.firefly.info.FFInfoSystem
import com.inari.firefly.info.FrameRateInfo
import com.inari.firefly.physics.animation.AnimationSystem
import com.inari.firefly.physics.animation.EAnimation
import com.inari.firefly.physics.animation.EasedFloatAnimation
import com.inari.firefly.util.geom.EasingTest
fun main(args: Array<String>) {
object : DesktopRunner("EasingTest2", 800, 900) {
override fun init() {
FFInfoSystem
.addInfo(FrameRateInfo)
.activate()
RenderingSystem
FFContext.loadSystem(EntitySystem)
FFContext.loadSystem(AnimationSystem)
for ((index, easingType) in EasingTest.EasingType.values().withIndex()) {
createEasingAnimation(easingType, index)
}
}
private fun createEasingAnimation(type: EasingTest.EasingType, position: Int) {
val ypos = position.toFloat() * (20f + 10f) + 50f
Entity.buildAndActivate {
withComponent(ETransform) {
view(0)
position(10f, ypos)
}
withComponent(EText) {
renderer(SimpleTextRenderer)
fontAsset(SYSTEM_FONT)
text.append(type.name.replace("_", "-"))
blend = BlendMode.NORMAL_ALPHA
tint(1f, 1f, 1f, 1f)
}
}
Entity.buildAndActivate {
withComponent(ETransform) {
view(0)
}
withComponent(EShape) {
this.shapeType = ShapeType.RECTANGLE
fill = true
color(1f, 0f, 0f, 1f)
vertices = floatArrayOf(100f, ypos, 20f, 20f)
}
withComponent(EAnimation) {
withAnimated<Float> {
looping = true
inverseOnLoop = true
animatedProperty = ETransform.Property.POSITION_X
withActiveAnimation(EasedFloatAnimation) {
easing = type.func
startValue = 100f
endValue = 400f
duration = 5000
}
}
}
}
}
}
}
| 2
|
Kotlin
|
0
| 7
|
dad6848b75c9008647b898dc5e1330b2eb04bf65
| 2,872
|
flyko-lib
|
Apache License 2.0
|
src/main/kotlin/org/wagham/db/models/Proficiency.kt
|
ilregnodiwagham
| 540,862,397
| false
| null |
package org.wagham.db.models
import org.bson.codecs.pojo.annotations.BsonId
data class Proficiency(
val name: String,
val isPurchasable: Boolean
)
data class ProficiencyList(
@BsonId val utilType: String,
val values: List<Proficiency> = emptyList()
)
| 0
|
Kotlin
|
0
| 0
|
855e69e26c30a8a392c5bef6f1b6b6e1eece4031
| 269
|
kabot-db-connector
|
MIT License
|
app/src/main/java/com/example/iberdrola/domain/usecases/facturas/GetFacturasBDDUseCase.kt
|
leomenvn
| 781,418,730
| false
|
{"Kotlin": 67530}
|
package com.example.iberdrola.domain.usecases.facturas
import com.example.iberdrola.domain.data.FacturaRepository
import com.example.iberdrola.domain.data.model.Factura
class GetFacturasBDDUseCase(private val repository: FacturaRepository){
suspend operator fun invoke(): List<Factura> {
return repository.getAllFacturasDB()
}
}
| 0
|
Kotlin
|
0
| 1
|
c2ab763e29cdb1b18f4de3d43600c46c96f53d69
| 349
|
kotlinVN
|
Apache License 2.0
|
src/main/kotlin/shou/common/web/element/igcombo/IgCombo.kt
|
NSVN-NguyenDuyThang
| 661,492,559
| false
| null |
package shou.common.web.element.igcombo
import com.microsoft.playwright.Page
import shou.common.web.BasePage
import shou.utils.DataFaker
/**
* @property comboBoxWrapper locator đến thẻ div chứa class ui-igcombo-wrapper (Click vào element này sẽ xổ ra dropdown)
*/
class IgCombo(override var page: Page, private val comboBoxWrapper: String) : BasePage() {
/**
* Chọn item trong combo box dựa theo code <br>
* Sử dụng trong combo box chứa các item có thông tin code (có từ 2 thông tin trở lên, thường có code, name (title), ...)
* @param code
* @return name (title) của item được chọn
*/
internal fun selectByCode(code: String): String {
val id: String = clickToCombobox()
clickToElement(String.format(BY_CODE, id, code))
return page.innerText(String.format(TITLE, id, code))
}
/**
* Chọn item trong combo box dựa theo code <br>
* Sử dụng trong combo box chứa các item có thông tin code và name (nằm trong cùng 1 thẻ div)
* @param code
*/
internal fun selectByCodeTitle(code: String) {
val id: String = clickToCombobox()
clickToElement(String.format(BY_CODE, id, code))
}
/**
* Chọn item trong combo box dựa theo name (title) <br>
* Sử dụng trong các combo box chứa các item chỉ có thông tin về name (title)
* @param title
* @return name (title) của item được chọn
*/
internal fun selectByTitle(title: String): String {
val id: String = clickToCombobox()
clickToElement(String.format(BY_TITLE, id, title))
return title
}
/**
* Chọn item trong combo box dựa theo name (title) <br>
* Sử dụng trong các combo box chứa các item chỉ có thông tin về name (title)
* @param pattern
* @return name (title) của item được chọn
*/
internal fun selectByStartTitle(pattern: String): String {
val id: String = clickToCombobox()
clickToElement(String.format(BY_START_TITLE, id, pattern))
return pattern
}
/**
* Lấy số lượng item trong combo box
* @return
*/
internal fun size(): Int {
val id: String = clickToCombobox()
val size: Int = page.querySelectorAll(String.format(ITEMS, id)).size
clickToElement(comboBoxWrapper)
return size
}
private fun clickToCombobox(): String {
val igComboId: String = DataFaker.generateFakeAlphaNumeric(10)
setAttribute(page.locator(comboBoxWrapper), "id", igComboId)
clickToElement(comboBoxWrapper)
return igComboId
}
companion object {
private const val ITEMS: String = "//div[@dropdown-for='%s']//li[@data-value]"
private const val TITLE: String = "//div[@dropdown-for='%s']//li[@data-value='%s']//div[@class='nts-combo-item']/div[2]"
private const val BY_CODE: String = "//div[@dropdown-for='%s']//li[@data-value='%s']"
private const val BY_TITLE: String = "//div[@dropdown-for='%s']//li[@data-value]//div[@class='nts-combo-item']/div[1][text()='%s\u00a0']"
private const val BY_START_TITLE: String = "//div[@dropdown-for='%s']//li[@data-value]//div[@class='nts-combo-item']/div[1][starts-with(text(),'%s')]"
}
}
| 0
|
Kotlin
|
0
| 0
|
b375d9d2ebb4981209025e6052a3080324042e33
| 3,217
|
playwright-kotlin
|
MIT License
|
InOutReader/app/src/main/java/com/example/inoutreader/env/BorderedText.kt
|
UJHa
| 225,784,760
| false
| null |
/* Copyright 2019 The TensorFlow Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/
package com.example.inoutreader.env
import android.graphics.*
import android.graphics.Paint.Align
import java.util.*
/** A class that encapsulates the tedious bits of rendering legible, bordered text onto a canvas. */
class BorderedText(interiorColor: Int, exteriorColor: Int, textSize: Float) {
private val interiorPaint = Paint()
private val exteriorPaint: Paint
private val textSize: Float
/**
* Creates a left-aligned bordered text object with a white interior, and a black exterior with
* the specified text size.
*
* @param textSize text size in pixels
*/
constructor(textSize: Float) : this(
Color.WHITE,
Color.BLACK,
textSize
) {
}
fun setTypeface(typeface: Typeface?) {
interiorPaint.typeface = typeface
exteriorPaint.typeface = typeface
}
fun drawText(
canvas: Canvas,
posX: Float,
posY: Float,
text: String?
) {
canvas.drawText(text!!, posX, posY, exteriorPaint)
canvas.drawText(text, posX, posY, interiorPaint)
}
fun drawText(
canvas: Canvas,
posX: Float,
posY: Float,
text: String?,
bgPaint: Paint?
) {
val width = exteriorPaint.measureText(text)
val textSize = exteriorPaint.textSize
val paint = Paint(bgPaint)
paint.style = Paint.Style.FILL
paint.alpha = 160
canvas.drawRect(posX, posY + textSize.toInt(), posX + width.toInt(), posY, paint)
canvas.drawText(text!!, posX, posY + textSize, interiorPaint)
}
fun drawLines(
canvas: Canvas,
posX: Float,
posY: Float,
lines: Vector<String?>
) {
var lineNum = 0
for (line in lines) {
drawText(canvas, posX, posY - textSize * (lines.size - lineNum - 1), line)
++lineNum
}
}
fun setInteriorColor(color: Int) {
interiorPaint.color = color
}
fun setExteriorColor(color: Int) {
exteriorPaint.color = color
}
fun setAlpha(alpha: Int) {
interiorPaint.alpha = alpha
exteriorPaint.alpha = alpha
}
fun getTextBounds(
line: String?, index: Int, count: Int, lineBounds: Rect?
) {
interiorPaint.getTextBounds(line, index, count, lineBounds)
}
fun setTextAlign(align: Align?) {
interiorPaint.textAlign = align
exteriorPaint.textAlign = align
}
/**
* Create a bordered text object with the specified interior and exterior colors, text size and
* alignment.
*
* @param interiorColor the interior text color
* @param exteriorColor the exterior text color
* @param textSize text size in pixels
*/
init {
interiorPaint.textSize = textSize
interiorPaint.color = interiorColor
interiorPaint.style = Paint.Style.FILL
interiorPaint.isAntiAlias = false
interiorPaint.alpha = 255
exteriorPaint = Paint()
exteriorPaint.textSize = textSize
exteriorPaint.color = exteriorColor
exteriorPaint.style = Paint.Style.FILL_AND_STROKE
exteriorPaint.strokeWidth = textSize / 8
exteriorPaint.isAntiAlias = false
exteriorPaint.alpha = 255
this.textSize = textSize
}
}
| 1
| null |
5
| 1
|
52b795687be2ddd22d544099543c75d7397c9674
| 3,988
|
Badminton_InOut_Check_App
|
MIT License
|
app/src/androidTest/java/com/ciscowebex/androidsdk/kitchensink/KitchenSinkTest.kt
|
webex
| 137,331,913
| false
|
{"Kotlin": 921538}
|
package com.ciscowebex.androidsdk.kitchensink
import android.app.Activity
import android.content.Context
import android.view.View
import android.view.ViewGroup
import androidx.annotation.IdRes
import androidx.annotation.NonNull
import androidx.annotation.StringRes
import androidx.lifecycle.Lifecycle
import androidx.recyclerview.widget.RecyclerView
import androidx.test.espresso.Espresso.onView
import androidx.test.espresso.PerformException
import androidx.test.espresso.UiController
import androidx.test.espresso.ViewAction
import androidx.test.espresso.action.ViewActions.*
import androidx.test.espresso.assertion.ViewAssertions.matches
import androidx.test.espresso.intent.Intents
import androidx.test.espresso.matcher.ViewMatchers.*
import androidx.test.espresso.web.sugar.Web
import androidx.test.espresso.web.webdriver.DriverAtoms
import androidx.test.espresso.web.webdriver.Locator
import androidx.test.ext.junit.rules.ActivityScenarioRule
import androidx.test.ext.junit.runners.AndroidJUnit4
import androidx.test.platform.app.InstrumentationRegistry
import com.ciscowebex.androidsdk.kitchensink.auth.LoginActivity
import com.ciscowebex.androidsdk.kitchensink.utils.RecyclerViewMatchers.withRecyclerView
import com.ciscowebex.androidsdk.kitchensink.utils.WaitUtils
import com.ciscowebex.androidsdk.kitchensink.utils.WaitUtils.waitForCondition
import com.google.android.material.tabs.TabLayout
import org.hamcrest.Matcher
import org.hamcrest.Matchers.*
import org.junit.After
import org.junit.Before
import org.junit.Rule
import org.junit.rules.Timeout
import org.junit.runner.RunWith
import java.util.concurrent.TimeUnit
@RunWith(AndroidJUnit4::class)
abstract class KitchenSinkTest {
val TAG = KitchenSinkTest::class.java.simpleName
val TIME_1_SEC: Long = 1000
val targetContext: Context by lazy {
InstrumentationRegistry.getInstrumentation().targetContext as Context
}
@get: Rule
val activityRule = ActivityScenarioRule(LoginActivity::class.java)
@Rule
@JvmField
var teamsTestTimeout: Timeout = Timeout(5, TimeUnit.MINUTES)
@Before
open fun initTests() {
Intents.init()
}
@After
fun releaseIntents(){
Intents.release()
}
fun setUpLogin() {
val testEmail = "<EMAIL>"
val testPassword = "<PASSWORD>"
activityRule.scenario.moveToState(Lifecycle.State.RESUMED)
assertViewDisplayed(R.id.btn_oauth_login)
clickOnView(R.id.btn_oauth_login)
WaitUtils.sleep(2000)
if (getActivity() is LoginActivity) {
assertViewDisplayed(R.id.loginWebview)
Web.onWebView().forceJavascriptEnabled()
WaitUtils.waitElementToAppear("IDToken1")
Web.onWebView(withId(R.id.loginWebview)).withElement(DriverAtoms.findElement(Locator.ID, "IDToken1"))
// Clear previous input
.perform(DriverAtoms.clearElement())
// Enter text into the input element
.perform(DriverAtoms.webKeys(testEmail))
WaitUtils.waitElementToAppear("IDButton2")
Web.onWebView(withId(R.id.loginWebview)).withElement(DriverAtoms.findElement(Locator.ID, "IDButton2")).perform(DriverAtoms.webClick())
WaitUtils.waitElementToAppear("IDToken2")
Web.onWebView(withId(R.id.loginWebview)).withElement(DriverAtoms.findElement(Locator.ID, "IDToken2"))
.perform(DriverAtoms.clearElement())
.perform(DriverAtoms.webKeys(testPassword))
WaitUtils.waitElementToAppear("Button1")
Web.onWebView(withId(R.id.loginWebview)).withElement(DriverAtoms.findElement(Locator.ID, "Button1")).perform(DriverAtoms.webClick())
}
waitForCondition(
60, TimeUnit.SECONDS,
{
val homeActivityRootView = getActivity()?.findViewById<View>(R.id.rootHomeActivity)
homeActivityRootView != null
},
{
"$TAG:: Not able to find homeActivityRootView"
}
)
activityRule.scenario.close()
}
protected fun typeTextAction(@IdRes viewId: Int, textToType: String = "Summer is good") {
onView(withId(viewId))
.check(matches(isDisplayed()))
.perform(typeText(textToType))
closeSoftKeyboard()
}
protected fun assertView(@StringRes textOnView: Int) {
onView(withText(textOnView)).check(matches(isDisplayed()))
}
protected fun assertView(@IdRes viewId: Int, @StringRes textOnView: Int) {
onView(allOf(withId(viewId), withText(textOnView))).check(matches(isDisplayed()))
}
protected fun assertViewDisplayed(@IdRes viewId: Int) {
onView(withId(viewId)).check(matches(isDisplayed()))
}
protected fun assertViewNotDisplayed(@IdRes viewId: Int) {
onView(withId(viewId)).check(matches(not(isDisplayed())))
}
protected fun assertViewWithContentDescription(@IdRes viewId: Int, @StringRes stringId: Int) {
onView(allOf(withId(viewId), withContentDescription(stringId)))
}
protected fun clickOnView(@IdRes viewId: Int) {
onView(withId(viewId)).perform(click())
}
protected fun clickOnViewWithText(@StringRes stringId: Int) {
onView(withText(stringId)).perform(click())
}
protected fun longClickOnView(@IdRes viewId: Int) {
onView(withId(viewId)).perform(longClick())
}
protected fun assertViewExists(@IdRes viewId: Int) {
onView(allOf(withId(viewId))).check(matches(isDisplayed()))
}
protected fun assertViewWithText(@IdRes viewId: Int, @NonNull textOnView: String) {
onView(allOf(withId(viewId), withText(containsString(textOnView)))).check(matches(isDisplayed()))
}
protected fun assertViewWithText(@IdRes viewId: Int, @NonNull @StringRes stringId: Int) {
onView(allOf(withId(viewId), withText(stringId))).check(matches(isDisplayed()))
}
protected fun getResourceName(@IdRes id: Int): String {
return targetContext.resources.getResourceName(id)
}
protected fun selectTab(tabIndex: Int): ViewAction {
return object : ViewAction {
override fun getDescription() = "with tab at index $tabIndex"
override fun getConstraints() = allOf(isDisplayed(), isAssignableFrom(TabLayout::class.java))
override fun perform(uiController: UiController, view: View) {
val tabLayout = view as TabLayout
val tabAtIndex: TabLayout.Tab = tabLayout.getTabAt(tabIndex)
?: throw PerformException.Builder()
.withCause(Throwable("No tab at index $tabIndex"))
.build()
tabAtIndex.select()
}
}
}
fun getActivity(): Activity? {
val activity = arrayOfNulls<Activity>(1)
onView(isRoot()).check { view, _ ->
var checkedView = view
while (checkedView is ViewGroup && checkedView.childCount > 0) {
checkedView = checkedView.getChildAt(0)
if (checkedView.context is Activity) {
activity[0] = checkedView.context as Activity
break
}
}
}
return activity[0]
}
protected fun longClickOnListItem(@IdRes viewId: Int, itemPosition: Int, @IdRes targetViewId: Int? = null) {
if (targetViewId == null) {
onView(withRecyclerView(viewId).atPosition(itemPosition))
} else {
onView(withRecyclerView(viewId).atPositionOnView(itemPosition, targetViewId))
}.check(matches(isDisplayed())).perform(longClick())
}
protected fun clickChildViewWithId(id: Int): ViewAction? {
return object : ViewAction {
override fun getConstraints(): Matcher<View> {
return isDisplayed()
}
override fun getDescription(): String {
return "Click on a child view with specified id."
}
override fun perform(uiController: UiController, view: View) {
val v = view.findViewById<View>(id)
v.performClick()
}
}
}
protected fun longclickChildViewWithId(id: Int): ViewAction? {
return object : ViewAction {
override fun getConstraints(): Matcher<View> {
return isDisplayed()
}
override fun getDescription(): String {
return "Click on a child view with specified id."
}
override fun perform(uiController: UiController, view: View) {
val v = view.findViewById<View>(id)
v.performLongClick()
}
}
}
protected fun withCustomConstraints(action: ViewAction, constraints: Matcher<View>): ViewAction? {
return object : ViewAction {
override fun getConstraints(): Matcher<View> {
return constraints
}
override fun getDescription(): String {
return action.description
}
override fun perform(uiController: UiController, view: View) {
action.perform(uiController, view)
}
}
}
protected fun ScrollToBottomAction(): ViewAction? {
return object : ViewAction {
override fun getDescription(): String {
return "scroll RecyclerView to bottom"
}
override fun getConstraints(): Matcher<View> {
return allOf<View>(isAssignableFrom(RecyclerView::class.java), isDisplayed())
}
override fun perform(uiController: UiController?, view: View?) {
val recyclerView = view as RecyclerView
val itemCount = recyclerView.adapter?.itemCount
val position = itemCount?.minus(1) ?: 0
recyclerView.scrollToPosition(position)
uiController?.loopMainThreadUntilIdle()
}
}
}
protected fun clickOnItemInRecyclerView(@IdRes viewId: Int, itemPosition: Int, @IdRes targetViewId: Int? = null) {
if (targetViewId == null) {
onView(withRecyclerView(viewId).atPosition(itemPosition))
} else {
onView(withRecyclerView(viewId).atPositionOnView(itemPosition, targetViewId))
}.check(matches(isDisplayed())).perform(click())
}
}
| 8
|
Kotlin
|
19
| 14
|
f6ce3ab0d33275c7e59a9d5465d3fa635b5e28bd
| 10,581
|
webex-android-sdk-example
|
MIT License
|
app/src/androidTest/java/com/ciscowebex/androidsdk/kitchensink/KitchenSinkTest.kt
|
webex
| 137,331,913
| false
|
{"Kotlin": 921538}
|
package com.ciscowebex.androidsdk.kitchensink
import android.app.Activity
import android.content.Context
import android.view.View
import android.view.ViewGroup
import androidx.annotation.IdRes
import androidx.annotation.NonNull
import androidx.annotation.StringRes
import androidx.lifecycle.Lifecycle
import androidx.recyclerview.widget.RecyclerView
import androidx.test.espresso.Espresso.onView
import androidx.test.espresso.PerformException
import androidx.test.espresso.UiController
import androidx.test.espresso.ViewAction
import androidx.test.espresso.action.ViewActions.*
import androidx.test.espresso.assertion.ViewAssertions.matches
import androidx.test.espresso.intent.Intents
import androidx.test.espresso.matcher.ViewMatchers.*
import androidx.test.espresso.web.sugar.Web
import androidx.test.espresso.web.webdriver.DriverAtoms
import androidx.test.espresso.web.webdriver.Locator
import androidx.test.ext.junit.rules.ActivityScenarioRule
import androidx.test.ext.junit.runners.AndroidJUnit4
import androidx.test.platform.app.InstrumentationRegistry
import com.ciscowebex.androidsdk.kitchensink.auth.LoginActivity
import com.ciscowebex.androidsdk.kitchensink.utils.RecyclerViewMatchers.withRecyclerView
import com.ciscowebex.androidsdk.kitchensink.utils.WaitUtils
import com.ciscowebex.androidsdk.kitchensink.utils.WaitUtils.waitForCondition
import com.google.android.material.tabs.TabLayout
import org.hamcrest.Matcher
import org.hamcrest.Matchers.*
import org.junit.After
import org.junit.Before
import org.junit.Rule
import org.junit.rules.Timeout
import org.junit.runner.RunWith
import java.util.concurrent.TimeUnit
@RunWith(AndroidJUnit4::class)
abstract class KitchenSinkTest {
val TAG = KitchenSinkTest::class.java.simpleName
val TIME_1_SEC: Long = 1000
val targetContext: Context by lazy {
InstrumentationRegistry.getInstrumentation().targetContext as Context
}
@get: Rule
val activityRule = ActivityScenarioRule(LoginActivity::class.java)
@Rule
@JvmField
var teamsTestTimeout: Timeout = Timeout(5, TimeUnit.MINUTES)
@Before
open fun initTests() {
Intents.init()
}
@After
fun releaseIntents(){
Intents.release()
}
fun setUpLogin() {
val testEmail = "<EMAIL>"
val testPassword = "<PASSWORD>"
activityRule.scenario.moveToState(Lifecycle.State.RESUMED)
assertViewDisplayed(R.id.btn_oauth_login)
clickOnView(R.id.btn_oauth_login)
WaitUtils.sleep(2000)
if (getActivity() is LoginActivity) {
assertViewDisplayed(R.id.loginWebview)
Web.onWebView().forceJavascriptEnabled()
WaitUtils.waitElementToAppear("IDToken1")
Web.onWebView(withId(R.id.loginWebview)).withElement(DriverAtoms.findElement(Locator.ID, "IDToken1"))
// Clear previous input
.perform(DriverAtoms.clearElement())
// Enter text into the input element
.perform(DriverAtoms.webKeys(testEmail))
WaitUtils.waitElementToAppear("IDButton2")
Web.onWebView(withId(R.id.loginWebview)).withElement(DriverAtoms.findElement(Locator.ID, "IDButton2")).perform(DriverAtoms.webClick())
WaitUtils.waitElementToAppear("IDToken2")
Web.onWebView(withId(R.id.loginWebview)).withElement(DriverAtoms.findElement(Locator.ID, "IDToken2"))
.perform(DriverAtoms.clearElement())
.perform(DriverAtoms.webKeys(testPassword))
WaitUtils.waitElementToAppear("Button1")
Web.onWebView(withId(R.id.loginWebview)).withElement(DriverAtoms.findElement(Locator.ID, "Button1")).perform(DriverAtoms.webClick())
}
waitForCondition(
60, TimeUnit.SECONDS,
{
val homeActivityRootView = getActivity()?.findViewById<View>(R.id.rootHomeActivity)
homeActivityRootView != null
},
{
"$TAG:: Not able to find homeActivityRootView"
}
)
activityRule.scenario.close()
}
protected fun typeTextAction(@IdRes viewId: Int, textToType: String = "Summer is good") {
onView(withId(viewId))
.check(matches(isDisplayed()))
.perform(typeText(textToType))
closeSoftKeyboard()
}
protected fun assertView(@StringRes textOnView: Int) {
onView(withText(textOnView)).check(matches(isDisplayed()))
}
protected fun assertView(@IdRes viewId: Int, @StringRes textOnView: Int) {
onView(allOf(withId(viewId), withText(textOnView))).check(matches(isDisplayed()))
}
protected fun assertViewDisplayed(@IdRes viewId: Int) {
onView(withId(viewId)).check(matches(isDisplayed()))
}
protected fun assertViewNotDisplayed(@IdRes viewId: Int) {
onView(withId(viewId)).check(matches(not(isDisplayed())))
}
protected fun assertViewWithContentDescription(@IdRes viewId: Int, @StringRes stringId: Int) {
onView(allOf(withId(viewId), withContentDescription(stringId)))
}
protected fun clickOnView(@IdRes viewId: Int) {
onView(withId(viewId)).perform(click())
}
protected fun clickOnViewWithText(@StringRes stringId: Int) {
onView(withText(stringId)).perform(click())
}
protected fun longClickOnView(@IdRes viewId: Int) {
onView(withId(viewId)).perform(longClick())
}
protected fun assertViewExists(@IdRes viewId: Int) {
onView(allOf(withId(viewId))).check(matches(isDisplayed()))
}
protected fun assertViewWithText(@IdRes viewId: Int, @NonNull textOnView: String) {
onView(allOf(withId(viewId), withText(containsString(textOnView)))).check(matches(isDisplayed()))
}
protected fun assertViewWithText(@IdRes viewId: Int, @NonNull @StringRes stringId: Int) {
onView(allOf(withId(viewId), withText(stringId))).check(matches(isDisplayed()))
}
protected fun getResourceName(@IdRes id: Int): String {
return targetContext.resources.getResourceName(id)
}
protected fun selectTab(tabIndex: Int): ViewAction {
return object : ViewAction {
override fun getDescription() = "with tab at index $tabIndex"
override fun getConstraints() = allOf(isDisplayed(), isAssignableFrom(TabLayout::class.java))
override fun perform(uiController: UiController, view: View) {
val tabLayout = view as TabLayout
val tabAtIndex: TabLayout.Tab = tabLayout.getTabAt(tabIndex)
?: throw PerformException.Builder()
.withCause(Throwable("No tab at index $tabIndex"))
.build()
tabAtIndex.select()
}
}
}
fun getActivity(): Activity? {
val activity = arrayOfNulls<Activity>(1)
onView(isRoot()).check { view, _ ->
var checkedView = view
while (checkedView is ViewGroup && checkedView.childCount > 0) {
checkedView = checkedView.getChildAt(0)
if (checkedView.context is Activity) {
activity[0] = checkedView.context as Activity
break
}
}
}
return activity[0]
}
protected fun longClickOnListItem(@IdRes viewId: Int, itemPosition: Int, @IdRes targetViewId: Int? = null) {
if (targetViewId == null) {
onView(withRecyclerView(viewId).atPosition(itemPosition))
} else {
onView(withRecyclerView(viewId).atPositionOnView(itemPosition, targetViewId))
}.check(matches(isDisplayed())).perform(longClick())
}
protected fun clickChildViewWithId(id: Int): ViewAction? {
return object : ViewAction {
override fun getConstraints(): Matcher<View> {
return isDisplayed()
}
override fun getDescription(): String {
return "Click on a child view with specified id."
}
override fun perform(uiController: UiController, view: View) {
val v = view.findViewById<View>(id)
v.performClick()
}
}
}
protected fun longclickChildViewWithId(id: Int): ViewAction? {
return object : ViewAction {
override fun getConstraints(): Matcher<View> {
return isDisplayed()
}
override fun getDescription(): String {
return "Click on a child view with specified id."
}
override fun perform(uiController: UiController, view: View) {
val v = view.findViewById<View>(id)
v.performLongClick()
}
}
}
protected fun withCustomConstraints(action: ViewAction, constraints: Matcher<View>): ViewAction? {
return object : ViewAction {
override fun getConstraints(): Matcher<View> {
return constraints
}
override fun getDescription(): String {
return action.description
}
override fun perform(uiController: UiController, view: View) {
action.perform(uiController, view)
}
}
}
protected fun ScrollToBottomAction(): ViewAction? {
return object : ViewAction {
override fun getDescription(): String {
return "scroll RecyclerView to bottom"
}
override fun getConstraints(): Matcher<View> {
return allOf<View>(isAssignableFrom(RecyclerView::class.java), isDisplayed())
}
override fun perform(uiController: UiController?, view: View?) {
val recyclerView = view as RecyclerView
val itemCount = recyclerView.adapter?.itemCount
val position = itemCount?.minus(1) ?: 0
recyclerView.scrollToPosition(position)
uiController?.loopMainThreadUntilIdle()
}
}
}
protected fun clickOnItemInRecyclerView(@IdRes viewId: Int, itemPosition: Int, @IdRes targetViewId: Int? = null) {
if (targetViewId == null) {
onView(withRecyclerView(viewId).atPosition(itemPosition))
} else {
onView(withRecyclerView(viewId).atPositionOnView(itemPosition, targetViewId))
}.check(matches(isDisplayed())).perform(click())
}
}
| 8
|
Kotlin
|
19
| 14
|
f6ce3ab0d33275c7e59a9d5465d3fa635b5e28bd
| 10,581
|
webex-android-sdk-example
|
MIT License
|
data/src/main/java/com/akochdev/data/database/dao/CharacterListDao.kt
|
AkochDev
| 423,927,462
| false
|
{"Kotlin": 122421}
|
package com.akochdev.data.database.dao
import androidx.room.Dao
import androidx.room.Insert
import androidx.room.OnConflictStrategy
import androidx.room.Query
import com.akochdev.data.database.model.CharacterListItemDBModel
@Dao
interface CharacterListDao {
@Query("SELECT * from character_list ORDER BY name LIMIT :limit OFFSET :offset")
suspend fun findByPage(limit: Int, offset: Int): List<CharacterListItemDBModel>
@Insert(onConflict = OnConflictStrategy.REPLACE)
suspend fun insert(list: List<CharacterListItemDBModel>)
}
| 0
|
Kotlin
|
0
| 0
|
24040b53c7a4450599f129986e4e7ecf00be5e7f
| 547
|
akoch-marvel-list
|
Apache License 2.0
|
providers/src/main/java/com/flixclusive/providers/models/providers/superstream/SuperStreamSubtitleResponse.kt
|
rhenwinch
| 659,237,375
| false
|
{"Kotlin": 1156049}
|
package com.flixclusive.providers.models.providers.superstream
import com.flixclusive.providers.sources.superstream.SuperStreamCommon.captionDomains
import com.google.gson.annotations.SerializedName
internal data class SuperStreamSubtitleResponse(
val code: Int? = null,
val msg: String? = null,
val data: SubtitleData = SubtitleData()
) {
data class SuperStreamSubtitleItem(
@SerializedName("file_path") val filePath: String? = null,
val lang: String? = null,
val language: String? = null,
val order: Int? = null,
) {
companion object {
fun String.toValidSubtitleFilePath(): String {
return replace(captionDomains[0], captionDomains[1])
.replace(Regex("\\s"), "+")
.replace(Regex("[()]")) { result ->
"%" + result.value.toCharArray()[0].code.toByte().toString(16)
}
}
}
}
data class SuperStreamSubtitle(
val language: String? = null,
val subtitles: List<SuperStreamSubtitleItem> = listOf()
)
data class SubtitleData(
val select: List<String> = listOf(),
val list: List<SuperStreamSubtitle> = listOf()
)
}
| 23
|
Kotlin
|
7
| 96
|
a90215b8c40ac0675cd217b38b842d2d57c90acc
| 1,253
|
Flixclusive
|
MIT License
|
app/src/main/java/ru/vitaliy/belyaev/wishapp/utils/AndroidVersionsExt.kt
|
VitaliyBelyaev
| 398,851,175
| false
|
{"Kotlin": 386804, "Swift": 91562, "Ruby": 2345}
|
package ru.vitaliy.belyaev.wishapp.utils
import android.os.Build
val isAndroidVersionSOrAbove: Boolean
get() = Build.VERSION.SDK_INT >= Build.VERSION_CODES.S
| 1
|
Kotlin
|
1
| 23
|
f034eebfd9adaea16f723b3aeb0825b946beea96
| 163
|
WishApp
|
Apache License 2.0
|
src/linuxArm32Main/kotlin/org/guiVista/gui/layout/box.kt
|
gui-vista
| 331,127,836
| false
| null |
package org.guiVista.gui.layout
import gtk3.*
import kotlinx.cinterop.CPointer
import kotlinx.cinterop.reinterpret
public actual class Box(
boxPtr: CPointer<GtkBox>? = null,
orientation: GtkOrientation = GtkOrientation.GTK_ORIENTATION_HORIZONTAL
) : BoxBase {
override val gtkWidgetPtr: CPointer<GtkWidget>? = boxPtr?.reinterpret() ?: gtk_box_new(orientation, 0)
}
public fun boxLayout(
boxPtr: CPointer<GtkBox>? = null,
orientation: GtkOrientation = GtkOrientation.GTK_ORIENTATION_HORIZONTAL,
init: Box.() -> Unit
): Box {
val box = Box(boxPtr, orientation)
box.init()
return box
}
| 0
|
Kotlin
|
0
| 0
|
484e1e8437a3d57faaf5667489d622402fe7be01
| 622
|
guivista-gui
|
Apache License 2.0
|
app-examples/example-kt-02coroutine/src/test/java/foo/bar/example/forecoroutine/feature/counter/CounterWithProgressTest.kt
|
erdo
| 92,027,307
| false
|
{"Kotlin": 602726, "Java": 405950, "Shell": 1405}
|
package foo.bar.example.forecoroutine.feature.counter
import co.early.fore.core.WorkMode
import co.early.fore.kt.core.logging.SystemLogger
import co.early.fore.core.observer.Observer
import co.early.fore.kt.core.delegate.Fore
import co.early.fore.kt.core.delegate.TestDelegateDefault
import io.mockk.mockk
import io.mockk.verify
import org.junit.Assert
import org.junit.Before
import org.junit.Test
/**
* Copyright © 2019 early.co. All rights reserved.
*/
class CounterWithProgressTest {
@Before
fun setup() {
// make the code run synchronously, reroute Log.x to
// System.out.println() so we see it in the test log
Fore.setDelegate(TestDelegateDefault())
}
@Test
@Throws(Exception::class)
fun initialConditions() {
//arrange
val counterWithProgress = CounterWithProgress(logger)
//act
//assert
Assert.assertEquals(false, counterWithProgress.isBusy)
Assert.assertEquals(0, counterWithProgress.progress.toLong())
Assert.assertEquals(0, counterWithProgress.count.toLong())
}
@Test
@Throws(Exception::class)
fun increasesBy20() {
//arrange
val counterWithProgress = CounterWithProgress(logger)
//act
counterWithProgress.increaseBy20()
//assert
Assert.assertEquals(false, counterWithProgress.isBusy)
Assert.assertEquals(0, counterWithProgress.progress.toLong())
Assert.assertEquals(20, counterWithProgress.count.toLong())
}
/**
*
* NB all we are checking here is that observers are called AT LEAST once
*
* We don't really want tie our tests (OR any observers in production code)
* to an expected number of times this method might be called. (This would be
* testing an implementation detail and make the tests unnecessarily brittle)
*
* The contract says nothing about how many times observers will get called,
* only that they will be called if something changes ("something" is not defined
* and can change between implementations).
*
* See the databinding readme for more information about this
*
* @throws Exception
*/
@Test
@Throws(Exception::class)
fun observersNotifiedAtLeastOnce() {
//arrange
val counterWithProgress = CounterWithProgress(logger)
val mockObserver = mockk<Observer>(relaxed = true)
counterWithProgress.addObserver(mockObserver)
//act
counterWithProgress.increaseBy20()
//assert
verify(atLeast = 1) {
mockObserver.somethingChanged()
}
}
/**
* Not so easy to test. We'll skip using verify for this test and do it manually.
* We will test that the progress is:
*
* - published 20 times during one call to increaseBy20()
* - never decreases from the last progress value (except when it gets set back to 0)
*
* @throws Exception
*/
@Test
@Throws(Exception::class)
fun progressIsPublished() {
//arrange
val counterWithProgress = CounterWithProgress(logger)
val pt = ProgressTracker()
counterWithProgress.addObserver {
val latestProgress = counterWithProgress.progress
if (latestProgress != 0) {//or we just ignore it
Assert.assertEquals(true, latestProgress >= pt.latestProgress)//never want progress to go down
if (latestProgress > pt.latestProgress) {//if progress ticks up, then we count it as a progress publication
pt.latestProgress = latestProgress
pt.numberOfProgressPublications++
}
}
}
//act
counterWithProgress.increaseBy20()
//assert
Assert.assertEquals(20, pt.numberOfProgressPublications.toLong())
}
private inner class ProgressTracker {
var numberOfProgressPublications = 0
var latestProgress = 0
}
companion object {
private val logger = SystemLogger()
}
}
| 2
|
Kotlin
|
3
| 46
|
1af5bd3ad9b2395a636fac12c40016fd2c815d0c
| 4,079
|
android-fore
|
Apache License 2.0
|
client/slack-api-client/src/main/kotlin/io/hndrs/slack/api/group/ApiCallMethod.kt
|
hndrs
| 168,710,332
| false
| null |
package com.kreait.slack.api.group
/**
* Abstract Class that represents an api interaction with the slack api
*/
@Suppress("UNCHECKED_CAST")
abstract class ApiCallMethod<Builder, Success, Failure, Params : Any> {
protected var onFailure: ((Failure) -> Any)? = null
protected var onSuccess: ((Success) -> Any)? = null
protected lateinit var params: Params
/**
* @param params the payload type of implementing class
* @return this
*/
fun with(params: Params): Builder {
this.params = params
return this as Builder
}
/**
* @param onSuccess the function that will be invoked on a successful api response
* @return this
*/
fun onSuccess(onSuccess: ((Success) -> Any)?): Builder {
this.onSuccess = onSuccess
return this as Builder
}
/**
* @param onFailure the function that will be invoked on a failing api response (not including network issues)
* @return this
*/
fun onFailure(onFailure: ((Failure) -> Any)?): Builder {
this.onFailure = onFailure
return this as Builder
}
/**
* execution implementation of the request to the slack api
*/
protected abstract fun request(): ApiCallResult<Success, Failure>
/**
* api call invocation
*/
fun invoke(): ApiCallResult<Success, Failure> {
return request()
}
}
| 57
| null |
13
| 16
|
89c5a6ddd0cbac522dd9cd4324901bf2907369a8
| 1,399
|
slack-spring-boot-starter
|
MIT License
|
app/src/main/java/nodomain/freeyourgadget/fossilnotify/App.kt
|
alexbilevskiy
| 622,469,193
| false
| null |
package nodomain.freeyourgadget.fossilnotify
import android.app.Application
import android.app.NotificationChannel
import android.app.NotificationManager
import android.content.Context
import nodomain.freeyourgadget.fossilnotify.service.NotificationService
class App : Application() {
override fun onCreate() {
super.onCreate()
createNotificationChannel()
}
private fun createNotificationChannel() {
val channel = NotificationChannel(
NotificationService.CHANNEL_ID,
"My Notification Name In App Settings",
NotificationManager.IMPORTANCE_DEFAULT
)
channel.description = "My notification description shows in app settings"
val notificationManager = getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
notificationManager.createNotificationChannel(channel)
}
}
| 0
|
Kotlin
|
0
| 0
|
b7e48066e8251dafb516ef15062c36cadae6ba04
| 889
|
fossilnotify
|
Apache License 2.0
|
kotlin-node/src/jsMain/generated/node/wasi/WASIOptions.kt
|
JetBrains
| 93,250,841
| false
| null |
// Generated by Karakum - do not modify it manually!
package node.wasi
sealed external interface WASIOptions {
/**
* An array of strings that the WebAssembly application will
* see as command line arguments. The first argument is the virtual path to the
* WASI command itself.
* @default []
*/
var args: js.array.ReadonlyArray<String>?
/**
* An object similar to `process.env` that the WebAssembly
* application will see as its environment.
* @default {}
*/
var env: Any?
/**
* This object represents the WebAssembly application's
* sandbox directory structure. The string keys of `preopens` are treated as
* directories within the sandbox. The corresponding values in `preopens` are
* the real paths to those directories on the host machine.
*/
var preopens: node.Dict<String>?
/**
* By default, when WASI applications call `__wasi_proc_exit()`
* `wasi.start()` will return with the exit code specified rather than terminatng the process.
* Setting this option to `false` will cause the Node.js process to exit with
* the specified exit code instead.
* @default true
*/
var returnOnExit: Boolean?
/**
* The file descriptor used as standard input in the WebAssembly application.
* @default 0
*/
var stdin: Double?
/**
* The file descriptor used as standard output in the WebAssembly application.
* @default 1
*/
var stdout: Double?
/**
* The file descriptor used as standard error in the WebAssembly application.
* @default 2
*/
var stderr: Double?
/**
* The version of WASI requested.
* Currently the only supported versions are `'unstable'` and `'preview1'`. This option is mandatory.
* @since v19.8.0
*/
var version: WASIOptionsVersion
}
| 40
| null |
165
| 1,347
|
997ed3902482883db4a9657585426f6ca167d556
| 1,881
|
kotlin-wrappers
|
Apache License 2.0
|
app/src/main/java/com/quixom/apps/deviceinfo/fragments/CameraFragment.kt
|
QuixomTech
| 106,003,406
| false
| null |
package com.quixom.apps.deviceinfo.fragments
import android.Manifest
import android.annotation.SuppressLint
import android.annotation.TargetApi
import android.content.Context
import android.content.pm.PackageManager
import android.graphics.Camera
import android.graphics.ImageFormat
import android.hardware.camera2.CameraCharacteristics
import android.hardware.camera2.CameraManager
import android.hardware.camera2.params.StreamConfigurationMap
import android.os.Build
import android.os.Bundle
import android.support.v4.app.ActivityCompat
import android.support.v4.content.ContextCompat
import android.support.v7.widget.LinearLayoutManager
import android.support.v7.widget.RecyclerView
import android.util.Range
import android.util.Rational
import android.util.Size
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.*
import com.quixom.apps.deviceinfo.R
import com.quixom.apps.deviceinfo.adapters.CameraAdapter
import com.quixom.apps.deviceinfo.models.FeaturesHW
import com.quixom.apps.deviceinfo.utilities.KeyUtil
import org.jetbrains.anko.backgroundColor
import org.jetbrains.anko.backgroundDrawable
import org.jetbrains.anko.textColor
import java.lang.StringBuilder
import java.util.*
class CameraFragment : BaseFragment(), View.OnClickListener {
@TargetApi(Build.VERSION_CODES.LOLLIPOP)
override fun onClick(view: View?) {
when (view) {
tvRearCamera -> {
checkCameraPermission("1")
tabSelector(tvRearCamera!!, tvFrontCamera!!)
}
tvFrontCamera -> {
checkCameraPermission("0")
tabSelector(tvFrontCamera!!, tvRearCamera!!)
}
}
}
var ivMenu: ImageView? = null
var ivBack: ImageView? = null
var tvTitle: TextView? = null
var tvCameraFeature: TextView? = null
var tvRearCamera: TextView? = null
var tvFrontCamera: TextView? = null
var textAreaScroller: ScrollView? = null
var llParentCamera: LinearLayout? = null
private var rvCameraFeatures: RecyclerView? = null
var camera: Camera? = null
private var cameraManager: CameraManager? = null
@TargetApi(Build.VERSION_CODES.LOLLIPOP)
override fun onCreateView(inflater: LayoutInflater?, container: ViewGroup?, savedInstanceState: Bundle?): View? {
val view = inflater!!.inflate(R.layout.fragment_camera, container, false)
ivMenu = view.findViewById(R.id.iv_menu)
ivBack = view.findViewById(R.id.iv_back)
tvTitle = view.findViewById(R.id.tv_title)
tvCameraFeature = view.findViewById(R.id.tv_camera_feature)
tvRearCamera = view.findViewById(R.id.tv_rear_camera)
tvFrontCamera = view.findViewById(R.id.tv_front_camera)
textAreaScroller = view.findViewById(R.id.textAreaScroller)
llParentCamera = view.findViewById(R.id.ll_parent_camera)
rvCameraFeatures = view.findViewById(R.id.rv_Camera_Features)
cameraManager = mActivity.getSystemService(Context.CAMERA_SERVICE) as CameraManager?
camera = Camera()
return view
}
@TargetApi(Build.VERSION_CODES.LOLLIPOP)
override fun onActivityCreated(savedInstanceState: Bundle?) {
super.onActivityCreated(savedInstanceState)
initToolbar()
tvRearCamera?.setOnClickListener(this)
tvFrontCamera?.setOnClickListener(this)
if (cameraManager?.cameraIdList?.size!! >= 2) {
llParentCamera?.visibility = View.VISIBLE
} else {
llParentCamera?.visibility = View.GONE
}
rvCameraFeatures?.layoutManager = LinearLayoutManager(mActivity)
rvCameraFeatures?.hasFixedSize()
checkCameraPermission("1")
}
override fun onHiddenChanged(hidden: Boolean) {
super.onHiddenChanged(hidden)
if (!hidden && isAdded) {
initToolbar()
}
}
private fun initToolbar() {
ivMenu?.visibility = View.VISIBLE
ivBack?.visibility = View.GONE
tvTitle?.text = mResources.getString(R.string.camera)
ivMenu?.setOnClickListener {
mActivity.openDrawer()
}
}
@TargetApi(Build.VERSION_CODES.LOLLIPOP)
/**
* this method will show permission pop up messages to user.
*/
private fun checkCameraPermission(ids: String) {
if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
val hasWriteCameraPermission = mActivity.checkSelfPermission(Manifest.permission.CAMERA)
if (hasWriteCameraPermission != PackageManager.PERMISSION_GRANTED) {
requestPermissions(arrayOf(Manifest.permission.CAMERA), KeyUtil.KEY_CAMERA_CODE)
} else {
fetchCameraCharacteristics(cameraManager!!, ids)
}
} else {
fetchCameraCharacteristics(cameraManager!!, ids)
}
}
@TargetApi(Build.VERSION_CODES.LOLLIPOP)
override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<out String>, grantResults: IntArray) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults)
when (requestCode) {
KeyUtil.KEY_CAMERA_CODE -> if (permissions.isNotEmpty()) {
if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
// Permission Granted
fetchCameraCharacteristics(cameraManager!!, "1")
} else if (grantResults[0] == PackageManager.PERMISSION_DENIED) {
// Should we show an explanation?
if (ActivityCompat.shouldShowRequestPermissionRationale(mActivity, Manifest.permission.GET_ACCOUNTS)) {
//Show permission explanation dialog...
Toast.makeText(mActivity, "Need to grant account Permission", Toast.LENGTH_LONG).show()
}
}
}
else -> super.onRequestPermissionsResult(requestCode, permissions, grantResults)
}
}
private fun tabSelector(textview1: TextView, textview2: TextView) {
/*** Set text color */
textview1.textColor = ContextCompat.getColor(mActivity, R.color.font_white)
textview2.textColor = ContextCompat.getColor(mActivity, R.color.orange)
/*** Background color */
textview1.backgroundColor = ContextCompat.getColor(mActivity, R.color.orange)
textview2.backgroundColor = ContextCompat.getColor(mActivity, R.color.font_white)
/*** Set background drawable */
textview1.backgroundDrawable = ContextCompat.getDrawable(mActivity, R.drawable.rectangle_fill)
textview2.backgroundDrawable = ContextCompat.getDrawable(mActivity, R.drawable.rectangle_unfill)
}
@TargetApi(Build.VERSION_CODES.LOLLIPOP)
private fun fetchCameraCharacteristics(cameraManager: CameraManager, ids: String) {
val lists = ArrayList<FeaturesHW>()
val sb = StringBuilder()
val characteristics = cameraManager.getCameraCharacteristics(ids)
for (key in characteristics.keys) {
sb.append(key.name).append("=").append(getCharacteristicsValue(key, characteristics)).append("\n\n")
val keyNm = key.name.split(".")
if (getCharacteristicsValue(key, characteristics) != "") {
if (key.name.split(".").size == 4) {
lists.add(FeaturesHW(keyNm[3], getCharacteristicsValue(key, characteristics)))
} else {
lists.add(FeaturesHW(keyNm[2], getCharacteristicsValue(key, characteristics)))
}
}
}
val adapter = CameraAdapter(lists, mActivity)
//now adding the adapter to RecyclerView
rvCameraFeatures?.adapter = adapter
}
@SuppressLint("NewApi")
@Suppress("UNCHECKED_CAST")
private fun <T> getCharacteristicsValue(key: CameraCharacteristics.Key<T>, characteristics: CameraCharacteristics): String {
val values = mutableListOf<String>()
if (CameraCharacteristics.COLOR_CORRECTION_AVAILABLE_ABERRATION_MODES == key) {
val modes = characteristics.get(key) as IntArray
modes.forEach {
when (it) {
CameraCharacteristics.COLOR_CORRECTION_ABERRATION_MODE_OFF -> values.add("Off")
CameraCharacteristics.COLOR_CORRECTION_ABERRATION_MODE_FAST -> values.add("Fast")
CameraCharacteristics.COLOR_CORRECTION_ABERRATION_MODE_HIGH_QUALITY -> values.add("High Quality")
}
}
} else if (CameraCharacteristics.CONTROL_AE_AVAILABLE_ANTIBANDING_MODES == key) {
val modes = characteristics.get(key) as IntArray
modes.forEach {
when (it) {
CameraCharacteristics.CONTROL_AE_ANTIBANDING_MODE_OFF -> values.add("Off")
CameraCharacteristics.CONTROL_AE_ANTIBANDING_MODE_AUTO -> values.add("Auto")
CameraCharacteristics.CONTROL_AE_ANTIBANDING_MODE_50HZ -> values.add("50Hz")
CameraCharacteristics.CONTROL_AE_ANTIBANDING_MODE_60HZ -> values.add("60Hz")
}
}
} else if (CameraCharacteristics.CONTROL_AE_AVAILABLE_MODES == key) {
val modes = characteristics.get(key) as IntArray
modes.forEach {
when (it) {
CameraCharacteristics.CONTROL_AE_MODE_OFF -> values.add("Off")
CameraCharacteristics.CONTROL_AE_MODE_ON -> values.add("On")
CameraCharacteristics.CONTROL_AE_MODE_ON_ALWAYS_FLASH -> values.add("Always Flash")
CameraCharacteristics.CONTROL_AE_MODE_ON_AUTO_FLASH -> values.add("Auto Flash")
CameraCharacteristics.CONTROL_AE_MODE_ON_AUTO_FLASH_REDEYE -> values.add("Auto Flash Redeye")
}
}
} else if (CameraCharacteristics.CONTROL_AE_AVAILABLE_TARGET_FPS_RANGES == key) {
val ranges = characteristics.get(key) as Array<Range<Int>>
ranges.forEach {
values.add(getRangeValue(it))
}
} else if (CameraCharacteristics.CONTROL_AE_COMPENSATION_RANGE == key) {
val range = characteristics.get(key) as Range<Int>
values.add(getRangeValue(range))
} else if (CameraCharacteristics.CONTROL_AE_COMPENSATION_STEP == key) {
val step = characteristics.get(key) as Rational
values.add(step.toString())
}/* else if (CameraCharacteristics.CONTROL_AE_LOCK_AVAILABLE == key) { // TODO requires >23
val available = characteristics.get(key)
values.add(available.toString())
} */ else if (CameraCharacteristics.CONTROL_AF_AVAILABLE_MODES == key) {
val modes = characteristics.get(key) as IntArray
modes.forEach {
when (it) {
CameraCharacteristics.CONTROL_AF_MODE_OFF -> values.add("Off")
CameraCharacteristics.CONTROL_AF_MODE_AUTO -> values.add("Auto")
CameraCharacteristics.CONTROL_AF_MODE_EDOF -> values.add("EDOF")
CameraCharacteristics.CONTROL_AF_MODE_MACRO -> values.add("Macro")
CameraCharacteristics.CONTROL_AF_MODE_CONTINUOUS_PICTURE -> values.add("Continous Picture")
CameraCharacteristics.CONTROL_AF_MODE_CONTINUOUS_VIDEO -> values.add("Continous Video")
}
}
} else if (CameraCharacteristics.CONTROL_AVAILABLE_EFFECTS == key) {
val effects = characteristics.get(key) as IntArray
effects.forEach {
values.add(when (it) {
CameraCharacteristics.CONTROL_EFFECT_MODE_OFF -> "Off"
CameraCharacteristics.CONTROL_EFFECT_MODE_AQUA -> "Aqua"
CameraCharacteristics.CONTROL_EFFECT_MODE_BLACKBOARD -> "Blackboard"
CameraCharacteristics.CONTROL_EFFECT_MODE_MONO -> "Mono"
CameraCharacteristics.CONTROL_EFFECT_MODE_NEGATIVE -> "Negative"
CameraCharacteristics.CONTROL_EFFECT_MODE_POSTERIZE -> "Posterize"
CameraCharacteristics.CONTROL_EFFECT_MODE_SEPIA -> "Sepia"
CameraCharacteristics.CONTROL_EFFECT_MODE_SOLARIZE -> "Solarize"
CameraCharacteristics.CONTROL_EFFECT_MODE_WHITEBOARD -> "Whiteboard"
else -> {
"Unkownn ${it}"
}
})
}
} /*else if (CameraCharacteristics.CONTROL_AVAILABLE_MODES == key) {
val modes = characteristics.get(key) as IntArray
modes.forEach {
values.add(when (it) {
CameraCharacteristics.CONTROL_MODE_OFF -> "Off"
CameraCharacteristics.CONTROL_MODE_OFF_KEEP_STATE -> "Off Keep State"
CameraCharacteristics.CONTROL_MODE_AUTO -> "Auto"
CameraCharacteristics.CONTROL_MODE_USE_SCENE_MODE -> "Use Scene Mode"
else -> {
"Unkownn ${it}"
}
})
}
}*/ else if (CameraCharacteristics.CONTROL_AVAILABLE_SCENE_MODES == key) {
val modes = characteristics.get(key) as IntArray
modes.forEach {
values.add(when (it) {
CameraCharacteristics.CONTROL_SCENE_MODE_DISABLED -> "Disabled"
CameraCharacteristics.CONTROL_SCENE_MODE_ACTION -> "Action"
CameraCharacteristics.CONTROL_SCENE_MODE_BARCODE -> "Barcode"
CameraCharacteristics.CONTROL_SCENE_MODE_BEACH -> "Beach"
CameraCharacteristics.CONTROL_SCENE_MODE_CANDLELIGHT -> "Candlelight"
CameraCharacteristics.CONTROL_SCENE_MODE_FACE_PRIORITY -> "Face Priority"
CameraCharacteristics.CONTROL_SCENE_MODE_FIREWORKS -> "Fireworks"
CameraCharacteristics.CONTROL_SCENE_MODE_HDR -> "HDR"
CameraCharacteristics.CONTROL_SCENE_MODE_LANDSCAPE -> "Landscape"
CameraCharacteristics.CONTROL_SCENE_MODE_NIGHT -> "Night"
CameraCharacteristics.CONTROL_SCENE_MODE_NIGHT_PORTRAIT -> "Night Portrait"
CameraCharacteristics.CONTROL_SCENE_MODE_PARTY -> "Party"
CameraCharacteristics.CONTROL_SCENE_MODE_PORTRAIT -> "Portrait"
CameraCharacteristics.CONTROL_SCENE_MODE_SNOW -> "Snow"
CameraCharacteristics.CONTROL_SCENE_MODE_SPORTS -> "Sports"
CameraCharacteristics.CONTROL_SCENE_MODE_STEADYPHOTO -> "Steady Photo"
CameraCharacteristics.CONTROL_SCENE_MODE_SUNSET -> "Sunset"
CameraCharacteristics.CONTROL_SCENE_MODE_THEATRE -> "Theatre"
CameraCharacteristics.CONTROL_SCENE_MODE_HIGH_SPEED_VIDEO -> "High Speed Video"
else -> {
"Unkownn ${it}"
}
})
}
} else if (CameraCharacteristics.CONTROL_AVAILABLE_VIDEO_STABILIZATION_MODES == key) {
val modes = characteristics.get(key) as IntArray
modes.forEach {
values.add(when (it) {
CameraCharacteristics.CONTROL_VIDEO_STABILIZATION_MODE_ON -> "On"
CameraCharacteristics.CONTROL_VIDEO_STABILIZATION_MODE_OFF -> "Off"
else -> {
"Unkownn ${it}"
}
})
}
} else if (CameraCharacteristics.CONTROL_AWB_AVAILABLE_MODES == key) {
} /*else if (CameraCharacteristics.CONTROL_AWB_LOCK_AVAILABLE == key) {
} */ else if (CameraCharacteristics.CONTROL_MAX_REGIONS_AE == key) {
} else if (CameraCharacteristics.CONTROL_MAX_REGIONS_AF == key) {
} else if (CameraCharacteristics.CONTROL_MAX_REGIONS_AWB == key) {
} /*else if (CameraCharacteristics.CONTROL_POST_RAW_SENSITIVITY_BOOST_RANGE == key) {
} else if (CameraCharacteristics.DEPTH_DEPTH_IS_EXCLUSIVE == key) {
}*/ else if (CameraCharacteristics.EDGE_AVAILABLE_EDGE_MODES == key) {
} else if (CameraCharacteristics.FLASH_INFO_AVAILABLE == key) {
} else if (CameraCharacteristics.HOT_PIXEL_AVAILABLE_HOT_PIXEL_MODES == key) {
} else if (CameraCharacteristics.INFO_SUPPORTED_HARDWARE_LEVEL == key) {
} else if (CameraCharacteristics.JPEG_AVAILABLE_THUMBNAIL_SIZES == key) {
} else if (CameraCharacteristics.LENS_FACING == key) {
val facing = characteristics.get(key)
values.add(
when (facing) {
CameraCharacteristics.LENS_FACING_BACK -> "Back"
CameraCharacteristics.LENS_FACING_FRONT -> "Front"
CameraCharacteristics.LENS_FACING_EXTERNAL -> "External"
else -> "Unkown"
}
)
} else if (CameraCharacteristics.LENS_INFO_AVAILABLE_APERTURES == key) {
} else if (CameraCharacteristics.LENS_INFO_AVAILABLE_FILTER_DENSITIES == key) {
} else if (CameraCharacteristics.LENS_INFO_AVAILABLE_FOCAL_LENGTHS == key) {
} else if (CameraCharacteristics.LENS_INFO_AVAILABLE_OPTICAL_STABILIZATION == key) {
} else if (CameraCharacteristics.LENS_INFO_FOCUS_DISTANCE_CALIBRATION == key) {
} else if (CameraCharacteristics.LENS_INFO_HYPERFOCAL_DISTANCE == key) {
} else if (CameraCharacteristics.LENS_INFO_MINIMUM_FOCUS_DISTANCE == key) {
}/* else if (CameraCharacteristics.LENS_INTRINSIC_CALIBRATION == key) {
} else if (CameraCharacteristics.LENS_POSE_ROTATION == key) {
} /**/else if (CameraCharacteristics.LENS_POSE_TRANSLATION == key) {
} /**/else if (CameraCharacteristics.LENS_RADIAL_DISTORTION == key) {
}*//* else if (CameraCharacteristics.NOISE_REDUCTION_AVAILABLE_NOISE_REDUCTION_MODES == key) {
} *//*else if (CameraCharacteristics.REPROCESS_MAX_CAPTURE_STALL == key) {
} */ else if (CameraCharacteristics.REQUEST_AVAILABLE_CAPABILITIES == key) {
} else if (CameraCharacteristics.REQUEST_MAX_NUM_INPUT_STREAMS == key) {
} else if (CameraCharacteristics.REQUEST_MAX_NUM_OUTPUT_PROC == key) {
} else if (CameraCharacteristics.REQUEST_MAX_NUM_OUTPUT_PROC_STALLING == key) {
} else if (CameraCharacteristics.REQUEST_MAX_NUM_OUTPUT_RAW == key) {
} else if (CameraCharacteristics.REQUEST_PARTIAL_RESULT_COUNT == key) {
} else if (CameraCharacteristics.REQUEST_PIPELINE_MAX_DEPTH == key) {
} else if (CameraCharacteristics.SCALER_AVAILABLE_MAX_DIGITAL_ZOOM == key) {
} else if (CameraCharacteristics.SCALER_CROPPING_TYPE == key) {
} else if (CameraCharacteristics.SCALER_STREAM_CONFIGURATION_MAP == key) {
val map = characteristics.get(key) as StreamConfigurationMap
val outputFormats = map.outputFormats
outputFormats.forEach {
values.add(printOutputFormat(it, map))
}
} else if (CameraCharacteristics.SENSOR_AVAILABLE_TEST_PATTERN_MODES == key) {
} else if (CameraCharacteristics.SENSOR_BLACK_LEVEL_PATTERN == key) {
} else if (CameraCharacteristics.SENSOR_CALIBRATION_TRANSFORM1 == key) {
} else if (CameraCharacteristics.SENSOR_CALIBRATION_TRANSFORM2 == key) {
} else if (CameraCharacteristics.SENSOR_COLOR_TRANSFORM1 == key) {
} else if (CameraCharacteristics.SENSOR_COLOR_TRANSFORM2 == key) {
} else if (CameraCharacteristics.SENSOR_FORWARD_MATRIX1 == key) {
} else if (CameraCharacteristics.SENSOR_FORWARD_MATRIX2 == key) {
} else if (CameraCharacteristics.SENSOR_INFO_ACTIVE_ARRAY_SIZE == key) {
} else if (CameraCharacteristics.SENSOR_INFO_COLOR_FILTER_ARRANGEMENT == key) {
} else if (CameraCharacteristics.SENSOR_INFO_EXPOSURE_TIME_RANGE == key) {
} /*else if (CameraCharacteristics.SENSOR_INFO_LENS_SHADING_APPLIED == key) {
} */ else if (CameraCharacteristics.SENSOR_INFO_MAX_FRAME_DURATION == key) {
} else if (CameraCharacteristics.SENSOR_INFO_PHYSICAL_SIZE == key) {
} else if (CameraCharacteristics.SENSOR_INFO_PIXEL_ARRAY_SIZE == key) {
} /*else if (CameraCharacteristics.SENSOR_INFO_PRE_CORRECTION_ACTIVE_ARRAY_SIZE == key) {
}*/ else if (CameraCharacteristics.SENSOR_INFO_SENSITIVITY_RANGE == key) {
} else if (CameraCharacteristics.SENSOR_INFO_TIMESTAMP_SOURCE == key) {
} else if (CameraCharacteristics.SENSOR_INFO_WHITE_LEVEL == key) {
} else if (CameraCharacteristics.SENSOR_MAX_ANALOG_SENSITIVITY == key) {
} /*else if (CameraCharacteristics.SENSOR_OPTICAL_BLACK_REGIONS == key) {
}*/ else if (CameraCharacteristics.SENSOR_ORIENTATION == key) {
val orientation = characteristics.get(key) as Int
values.add(orientation.toString())
} else if (CameraCharacteristics.SENSOR_REFERENCE_ILLUMINANT1 == key) {
} else if (CameraCharacteristics.SENSOR_REFERENCE_ILLUMINANT2 == key) {
}/* else if (CameraCharacteristics.SHADING_AVAILABLE_MODES == key) {
}*/ else if (CameraCharacteristics.STATISTICS_INFO_AVAILABLE_FACE_DETECT_MODES == key) {
} else if (CameraCharacteristics.STATISTICS_INFO_AVAILABLE_HOT_PIXEL_MAP_MODES == key) {
}/* else if (CameraCharacteristics.STATISTICS_INFO_AVAILABLE_LENS_SHADING_MAP_MODES == key) {
}*/ else if (CameraCharacteristics.SYNC_MAX_LATENCY == key) {
} else if (CameraCharacteristics.TONEMAP_AVAILABLE_TONE_MAP_MODES == key) {
} else if (CameraCharacteristics.TONEMAP_MAX_CURVE_POINTS == key) {
}
values.sort()
return if (values.isEmpty()) "" else join(", ", values)
}
@TargetApi(Build.VERSION_CODES.LOLLIPOP)
private fun printOutputFormat(outputFormat: Int, map: StreamConfigurationMap): String {
val formatName = getImageFormat(outputFormat)
val outputSizes = map.getOutputSizes(outputFormat);
val outputSizeValues = mutableListOf<String>()
outputSizes.forEach {
val mp = getMegaPixel(it)
outputSizeValues.add("${it.width}x${it.height} (${mp}MP)")
}
val sizesString = join(", ", outputSizeValues)
return "\n$formatName -> [$sizesString]"
}
@TargetApi(Build.VERSION_CODES.LOLLIPOP)
private fun getMegaPixel(size: Size): String {
val mp = (size.width * size.height) / 1000000f
return String.format("%.1f", mp)
}
private fun getImageFormat(format: Int): String {
return when (format) {
ImageFormat.DEPTH16 -> "DEPTH16"
ImageFormat.DEPTH_POINT_CLOUD -> "DEPTH_POINT_CLOUD"
ImageFormat.FLEX_RGBA_8888 -> "FLEX_RGBA_8888"
ImageFormat.FLEX_RGB_888 -> "FLEX_RGB_888"
ImageFormat.JPEG -> "JPEG"
ImageFormat.NV16 -> "NV16"
ImageFormat.NV21 -> "NV21"
ImageFormat.PRIVATE -> "PRIVATE"
ImageFormat.RAW10 -> "RAW10"
ImageFormat.RAW12 -> "RAW12"
ImageFormat.RAW_PRIVATE -> "RAW_PRIVATE"
ImageFormat.RAW_SENSOR -> "RAW_SENSOR"
ImageFormat.RGB_565 -> "RGB_565"
ImageFormat.YUV_420_888 -> "YUV_420_888"
ImageFormat.YUV_422_888 -> "YUV_422_888"
ImageFormat.YUV_444_888 -> "YUV_444_888"
ImageFormat.YUY2 -> "YUY2"
ImageFormat.YV12 -> "YV12"
else -> "Unkown"
}
}
@TargetApi(Build.VERSION_CODES.LOLLIPOP)
private fun <T : Comparable<T>> getRangeValue(range: Range<T>): String {
return "[${range.lower},${range.upper}]"
}
fun <T> join(delimiter: String, elements: Collection<T>?): String {
if (null == elements || elements.isEmpty()) {
return ""
}
val sb = StringBuilder()
val iter = elements.iterator()
while (iter.hasNext()) {
val element = iter.next()
sb.append(element.toString())
if (iter.hasNext()) {
sb.append(delimiter)
}
}
return sb.toString()
}
}
| 4
| null |
47
| 92
|
3f36845e1be0829b90ee171b758ef8b8863bc925
| 24,524
|
DeviceInfo
|
Apache License 2.0
|
fluent-icons-generator/src/jvmMain/kotlin/androidx/compose/material/icons/generator/IconTestingManifestGenerator.kt
|
Konyaco
| 574,321,009
| false
| null |
/*
* Copyright 2020 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package androidx.compose.material.icons.generator
import com.squareup.kotlinpoet.CodeBlock
import com.squareup.kotlinpoet.FileSpec
import com.squareup.kotlinpoet.FunSpec
import com.squareup.kotlinpoet.ParameterizedTypeName.Companion.parameterizedBy
import com.squareup.kotlinpoet.PropertySpec
import com.squareup.kotlinpoet.asClassName
import com.squareup.kotlinpoet.asTypeName
import com.squareup.kotlinpoet.buildCodeBlock
import java.io.File
import kotlin.reflect.KProperty0
/**
* Generates a list named `AllIcons` that contains pairs mapping a [KProperty0] of the generated
* icon to the name of the corresponding XML drawable. This is used so we can run tests comparing
* the generated icon against the original source drawable.
*
* @property icons the list of [Icon]s to generate the manifest from
*/
class IconTestingManifestGenerator(private val icons: List<Icon>) {
/**
* Generates the list and writes it to [outputSrcDirectory].
*/
fun generateTo(outputSrcDirectory: File) {
val propertyNames: MutableList<String> = mutableListOf()
// Split up this list by themes, otherwise we get a Method too large exception.
// We will then generate another file that returns the result of concatenating the list
// for each theme.
icons
.groupBy { it.theme }
.map { (theme, icons) ->
val propertyName = "${theme.themeClassName}Icons"
propertyNames += propertyName
theme to generateListOfIconsForTheme(propertyName, theme, icons)
}
.forEach { (theme, fileSpec) ->
// KotlinPoet bans wildcard imports, and we run into class compilation errors
// (too large a file?) if we add all the imports individually, so let's just add
// the imports to each file manually.
val wildcardImport =
"import androidx.compose.material.icons.${theme.themePackageName}.*"
fileSpec.writeToWithCopyright(outputSrcDirectory) { fileContent ->
fileContent.replace(
"import androidx.compose.ui.graphics.vector.VectorAsset",
"$wildcardImport\n" +
"import androidx.compose.ui.graphics.vector.VectorAsset"
)
}
}
val mainGetter = FunSpec.getterBuilder()
.addStatement("return " + propertyNames.joinToString(" + "))
.build()
FileSpec.builder(PackageNames.MaterialIconsPackage.packageName, "AllIcons")
.addProperty(
PropertySpec.builder("AllIcons", type = listOfIconsType)
.getter(mainGetter)
.build()
).setIndent().build().writeToWithCopyright(outputSrcDirectory)
}
}
/**
* Generates a Kotlin file with a list containing all icons of the given [theme].
*
* @param propertyName the name of the top level property that we should generate the list under
* @param theme the theme that we are generating the file for
* @param allIcons a list containing all icons that we will filter to match [theme]
*/
private fun generateListOfIconsForTheme(
propertyName: String,
theme: IconTheme,
allIcons: List<Icon>
): FileSpec {
val icons = allIcons.filter { it.theme == theme }
val iconStatements = icons.toStatements()
return FileSpec.builder(PackageNames.MaterialIconsPackage.packageName, propertyName)
.addProperty(
PropertySpec.builder(propertyName, type = listOfIconsType)
.initializer(
buildCodeBlock {
addStatement("listOf(")
indent()
iconStatements.forEach { add(it) }
unindent()
addStatement(")")
}
)
.build()
).setIndent().build()
}
/**
* @return a list of [CodeBlock] representing all the statements for the body of the list.
* For example, one statement would look like `(Icons.Filled::Menu) to menu`.
*/
private fun List<Icon>.toStatements(): List<CodeBlock> {
return mapIndexed { index, icon ->
buildCodeBlock {
val iconFunctionReference = "(%T.${icon.theme.themeClassName}::${icon.kotlinName})"
val text = "$iconFunctionReference to \"${icon.xmlFileName}\""
addStatement(if (index != size - 1) "$text," else text, ClassNames.Icons)
}
}
}
private val kPropertyType =
(KProperty0::class).asClassName().parameterizedBy(ClassNames.VectorAsset)
private val pairType = (Pair::class).asClassName().parameterizedBy(
kPropertyType,
(String::class).asTypeName()
)
private val listOfIconsType = (List::class).asClassName().parameterizedBy(pairType)
| 21
| null |
823
| 83
|
9e86d93bf1f9ca63a93a913c990e95f13d8ede5a
| 5,500
|
compose-fluent-ui
|
Apache License 2.0
|
app/src/main/java/com/kevalpatel2106/fxratesample/utils/Extentions.kt
|
kevalpatel2106
| 273,729,277
| false
| null |
package com.zeynelerdi.fxratesample.utils
import androidx.lifecycle.LifecycleOwner
import androidx.lifecycle.LiveData
import androidx.lifecycle.Observer
import io.reactivex.disposables.CompositeDisposable
import io.reactivex.disposables.Disposable
fun <T> LiveData<T>.nullSafeObserve(owner: LifecycleOwner, observer: (t: T) -> Unit) {
observe(owner, Observer { it?.let(observer) })
}
fun Disposable.addTo(compositeDisposable: CompositeDisposable) {
compositeDisposable.add(this)
}
fun Double.toStringUpToTwoDecimal() = String.format("%.2f", this)
fun emptyAmount() = 0.0
| 0
| null |
1
| 4
|
3a8b55c359528eb7cabfbe9610f6b7813b41d427
| 584
|
Currency-Converter-App
|
Apache License 2.0
|
app/src/main/java/com/example/androiddevchallenge/ui/screens/Puppies.kt
|
erlanamanatov
| 342,770,601
| false
| null |
/*
* Copyright 2021 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.example.androiddevchallenge.ui.screens
import androidx.compose.animation.ExperimentalAnimationApi
import androidx.compose.foundation.ExperimentalFoundationApi
import androidx.compose.foundation.Image
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.lazy.GridCells
import androidx.compose.foundation.lazy.LazyVerticalGrid
import androidx.compose.foundation.lazy.items
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.Card
import androidx.compose.material.MaterialTheme
import androidx.compose.material.Scaffold
import androidx.compose.material.Surface
import androidx.compose.material.Text
import androidx.compose.material.TopAppBar
import androidx.compose.runtime.Composable
import androidx.compose.runtime.remember
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.draw.rotate
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.text.font.FontFamily
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import com.example.androiddevchallenge.data.Puppy
import com.example.androiddevchallenge.data.PuppyList
import com.example.androiddevchallenge.ui.theme.MyTheme
import kotlin.random.Random
const val rotationRange = 10
@ExperimentalFoundationApi
@Composable
fun Puppies(
puppies: List<Puppy>,
onPuppyClick: (Int) -> Unit
) {
Scaffold(
topBar = {
TopAppBar(
title = {
Text(
"Puppies",
color = MaterialTheme.colors.onSurface,
fontFamily = FontFamily.Cursive,
fontWeight = FontWeight.Bold,
fontSize = 34.sp
)
},
backgroundColor = MaterialTheme.colors.background,
elevation = 0.dp
)
},
content = {
Box(
modifier = Modifier
.fillMaxSize()
.padding(horizontal = 8.dp)
) {
LazyVerticalGrid(GridCells.Fixed(2)) {
items(puppies) { puppy ->
PuppyItem(
puppy = puppy,
onClick = {
onPuppyClick(it)
}
)
}
}
}
}
)
}
@Composable
fun PuppyItem(
modifier: Modifier = Modifier,
puppy: Puppy,
onClick: (Int) -> Unit
) {
val rotationAngle = remember { rotationRange * (Random.nextFloat() - 0.5f) }
Box(
modifier = modifier
.padding(4.dp)
.rotate(rotationAngle)
) {
Card(
shape = RoundedCornerShape(6.dp),
elevation = 6.dp,
modifier = Modifier
.padding(6.dp)
.clickable { onClick(puppy.id) },
) {
Column(modifier = Modifier.padding(4.dp)) {
Image(
painter = painterResource(id = puppy.image),
contentDescription = "Puppy image",
modifier = Modifier
.fillMaxWidth()
.clip(RoundedCornerShape(4.dp)),
contentScale = ContentScale.FillWidth
)
Text(
text = puppy.name,
fontWeight = FontWeight.Bold,
color = MaterialTheme.colors.primaryVariant
)
Text(
text = puppy.breed,
maxLines = 1,
overflow = TextOverflow.Ellipsis,
style = MaterialTheme.typography.caption
)
}
}
}
}
@ExperimentalAnimationApi
@ExperimentalFoundationApi
@Preview("Light Theme", widthDp = 360, heightDp = 640)
@Composable
fun LightPreview() {
MyTheme {
Surface(color = MaterialTheme.colors.background) {
Puppies(puppies = PuppyList.data, onPuppyClick = {})
}
}
}
| 0
|
Kotlin
|
0
| 0
|
9a160018e4ca09aaaa8eded2ed8c858936ef58b2
| 5,254
|
PuppyApp
|
Apache License 2.0
|
PremiumStorefront/src/main/java/co/geeksempire/premium/storefront/PremiumStorefrontApplication.kt
|
eliasdfazel
| 357,269,336
| false
| null |
/*
* Copyright © 2021 By Geeks Empire.
*
* Created by <NAME>
* Last modified 8/21/21, 10:28 AM
*
* Licensed Under MIT License.
* https://opensource.org/licenses/MIT
*/
package co.geeksempire.premium.storefront
import android.content.Context
import android.os.Bundle
import co.geeksempire.premium.storefront.Database.GeneralConfigurations.FirestoreConfiguration
import co.geeksempire.premium.storefront.Database.Preferences.PreferencesIO
import co.geeksempire.premium.storefront.Preferences.Utils.EntryPreferences
import co.geeksempire.premium.storefront.StorefrontConfigurations.StorefrontSections.CategoryContent.CategoryData
import com.google.android.play.core.splitcompat.SplitCompat
import com.google.android.play.core.splitcompat.SplitCompatApplication
import com.google.firebase.FirebaseApp
import com.google.firebase.analytics.FirebaseAnalytics
import com.google.firebase.firestore.FirebaseFirestore
class PremiumStorefrontApplication : SplitCompatApplication() {
val preferencesIO: PreferencesIO by lazy {
PreferencesIO(context = applicationContext)
}
val entryPreferences: EntryPreferences by lazy {
EntryPreferences(preferencesIO)
}
val firestoreConfiguration: FirestoreConfiguration by lazy {
FirestoreConfiguration()
}
lateinit var firestoreDatabase: FirebaseFirestore
val firebaseAnalytics: FirebaseAnalytics by lazy {
FirebaseAnalytics.getInstance(applicationContext)
}
val categoryData = CategoryData()
override fun onCreate() {
super.onCreate()
FirebaseApp.initializeApp(applicationContext)
firebaseAnalytics.logEvent(this@PremiumStorefrontApplication.javaClass.simpleName, Bundle().apply { putString(this@PremiumStorefrontApplication.javaClass.simpleName, "Started") })
firestoreDatabase = firestoreConfiguration.initialize()
}
override fun attachBaseContext(baseApplicationContext: Context) {
super.attachBaseContext(baseApplicationContext)
SplitCompat.install(this@PremiumStorefrontApplication)
}
}
| 0
|
Kotlin
|
0
| 1
|
c87ce3cb492443f9bf0088f76882ed33e18ad341
| 2,077
|
PremiumStorefront
|
MIT License
|
ui/script/src/main/kotlin/me/gegenbauer/catspy/script/ui/DeviceInfoCard.kt
|
Gegenbauer
| 609,809,576
| false
|
{"Kotlin": 652879}
|
package me.gegenbauer.catspy.script.ui
import info.clearthought.layout.TableLayout
import info.clearthought.layout.TableLayoutConstants
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.async
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import me.gegenbauer.catspy.concurrency.GIO
import me.gegenbauer.catspy.concurrency.ModelScope
import me.gegenbauer.catspy.concurrency.UI
import me.gegenbauer.catspy.context.Contexts
import me.gegenbauer.catspy.context.ServiceManager
import me.gegenbauer.catspy.ddmlib.device.AdamDeviceMonitor
import me.gegenbauer.catspy.java.ext.EMPTY_STRING
import me.gegenbauer.catspy.script.executor.CommandExecutor
import me.gegenbauer.catspy.task.PeriodicTask
import me.gegenbauer.catspy.task.TaskManager
import me.gegenbauer.catspy.view.card.Card
import javax.swing.JComponent
import javax.swing.JLabel
import javax.swing.JPanel
class DeviceInfoCard(
private val scriptUIItems: List<ScriptUIItem>,
private val taskManager: TaskManager,
override val contexts: Contexts = Contexts.default
) : JPanel(), Card {
private val scope = ModelScope()
private var device = ScriptTabPanel.defaultDevice
private var period: Long = 1000L
private val periodUpdateTask = PeriodicTask(period, "UpdateCard", ::updateContent, Dispatchers.GIO)
init {
val rows = DoubleArray(scriptUIItems.size) { TableLayoutConstants.PREFERRED }
layout = TableLayout(
doubleArrayOf(0.2, 0.8),
rows
)
scriptUIItems.forEachIndexed { index, it ->
add(JLabel(it.script.name), getTableConstraint(index, 0))
add(JLabel(), getTableConstraint(index, 1))
}
}
private fun getTableConstraint(row: Int, column: Int): String {
return "$column, $row"
}
override val id: Int
get() = 1
override val component: JComponent
get() = this
override fun updateContent() {
val deviceManager = ServiceManager.getContextService(AdamDeviceMonitor::class.java)
if (deviceManager.getDevices().isNotEmpty()) {
scriptUIItems.forEachIndexed { index, item ->
scope.launch {
val executor = CommandExecutor(taskManager, item.script, Dispatchers.GIO)
val response = executor.execute(device)
response.collect {
val parsedResult = item.parseRule.parse(it.output)
withContext(Dispatchers.UI) {
val label = getComponent(index * 2 + 1) as JLabel
label.text = parsedResult.firstOrNull() ?: EMPTY_STRING
}
}
}
}
}
}
override fun setAutomaticallyUpdate(enabled: Boolean) {
if (enabled) {
taskManager.exec(periodUpdateTask)
} else {
periodUpdateTask.cancel()
}
}
override fun stopAutomaticallyUpdate() {
periodUpdateTask.pause()
}
override fun resumeAutomaticallyUpdate() {
periodUpdateTask.resume()
}
override fun setPeriod(period: Long) {
this.period = period
}
// fun setInfo
}
| 3
|
Kotlin
|
4
| 7
|
70d905761d3cb0cb2e5ee9b80ceec72fca46ee52
| 3,245
|
CatSpy
|
Apache License 2.0
|
app/src/main/java/dlebal/es/coinhivemonitor/api/coinhive/model/CoinhiveSite.kt
|
dlebal
| 169,708,968
| false
| null |
package dlebal.es.coinhivemonitor.api.coinhive.model
import com.google.gson.annotations.SerializedName
/**
* Class data class CoinhiveSite
*
* This class provides CoinhiveSite objects
*/
data class CoinhiveSite(
@SerializedName("hashesPerSecond")
val hashesPerSecond: Long = 0,
@SerializedName("hashesTotal")
val hashesTotal: Long = 0,
@SerializedName("xmrPending")
val xmrPending: Double = 0.0,
@SerializedName("xmrPaid")
val xmrPaid: Double = 0.0,
@SerializedName("name")
val name: String = "",
@SerializedName("history")
val history: List<CoinhiveSiteHistory> = ArrayList(),
@SerializedName("success")
val success: Boolean = false,
@SerializedName("error")
val error: String = ""
)
| 0
|
Kotlin
|
0
| 0
|
903e1537899cb93f2553b2a560c9dd171a863e2b
| 755
|
CoinhiveMonitor
|
Apache License 2.0
|
core/domain/src/main/java/com/wap/wapp/core/domain/usecase/event/GetEventsUseCase.kt
|
pknu-wap
| 689,890,586
| false
|
{"Kotlin": 265360, "Shell": 233}
|
package com.wap.wapp.core.domain.usecase.event
import com.wap.wapp.core.data.repository.event.EventRepository
import com.wap.wapp.core.model.event.Event
import java.time.LocalDate
import javax.inject.Inject
class GetEventsUseCase @Inject constructor(
private val eventRepository: EventRepository,
) {
suspend operator fun invoke(date: LocalDate): Result<List<Event>> = runCatching {
eventRepository.getMonthEvents(date).fold(
onSuccess = { eventsList -> eventsList },
onFailure = { throw (it) },
)
}
}
| 5
|
Kotlin
|
1
| 8
|
97848fa61b703910ae630a67ee6599d99b8e37b4
| 556
|
WAPP
|
MIT License
|
modules/feature/search/src/main/kotlin/kekmech/ru/feature_search/screens/schedule_details/ScheduleDetailsFragment.kt
|
tonykolomeytsev
| 203,239,594
| false
| null |
package kekmech.ru.feature_search.screens.schedule_details
import android.graphics.Point
import android.os.Bundle
import android.view.View
import androidx.recyclerview.widget.LinearLayoutManager
import kekmech.ru.common_adapter.AdapterItem
import kekmech.ru.common_adapter.BaseAdapter
import kekmech.ru.common_analytics.ext.screenAnalytics
import kekmech.ru.common_android.close
import kekmech.ru.common_android.getArgument
import kekmech.ru.common_android.viewbinding.viewBinding
import kekmech.ru.common_android.withArguments
import kekmech.ru.common_elm.BaseBottomSheetDialogFragment
import kekmech.ru.common_kotlin.fastLazy
import kekmech.ru.common_navigation.BottomTab
import kekmech.ru.common_navigation.BottomTabsSwitcher
import kekmech.ru.common_navigation.ClearBackStack
import kekmech.ru.common_navigation.Router
import kekmech.ru.common_schedule.items.ClassesItemBinder
import kekmech.ru.common_schedule.items.ClassesViewHolderImpl
import kekmech.ru.coreui.items.EmptyStateAdapterItem
import kekmech.ru.coreui.items.PullAdapterItem
import kekmech.ru.coreui.items.ShimmerAdapterItem
import kekmech.ru.coreui.items.SpaceAdapterItem
import kekmech.ru.coreui.items.TextAdapterItem
import kekmech.ru.coreui.items.TextWithIconAdapterItem
import kekmech.ru.domain_schedule.dto.SearchResult
import kekmech.ru.domain_schedule_models.dto.Classes
import kekmech.ru.feature_search.R
import kekmech.ru.feature_search.databinding.FragmentScheduleDetailsBinding
import kekmech.ru.feature_search.item.ButtonAdapterItem
import kekmech.ru.feature_search.item.WeekMinItem
import kekmech.ru.feature_search.item.WeekMinItemBinder
import kekmech.ru.feature_search.item.WeekMinViewHolder
import kekmech.ru.feature_search.screens.schedule_details.elm.ScheduleDetailsEffect
import kekmech.ru.feature_search.screens.schedule_details.elm.ScheduleDetailsEvent
import kekmech.ru.feature_search.screens.schedule_details.elm.ScheduleDetailsEvent.Ui
import kekmech.ru.feature_search.screens.schedule_details.elm.ScheduleDetailsState
import kekmech.ru.feature_search.screens.schedule_details.elm.ScheduleDetailsStoreFactory
import org.koin.android.ext.android.inject
import kekmech.ru.common_schedule.R as common_schedule_R
import kekmech.ru.coreui.R as coreui_R
private const val ARG_RESULT_ITEM = "Arg.Item"
internal const val ITEM_BUTTON_SWITCH = 1
internal const val ITEM_FAVORITES = 1
internal class ScheduleDetailsFragment :
BaseBottomSheetDialogFragment<ScheduleDetailsEvent, ScheduleDetailsEffect,
ScheduleDetailsState>(R.layout.fragment_schedule_details) {
private val viewBinding by viewBinding(FragmentScheduleDetailsBinding::bind)
private val adapter by fastLazy { createAdapter() }
private val router by inject<Router>()
private val bottomTabsSwitcher by inject<BottomTabsSwitcher>()
private val analytics by screenAnalytics("SearchScheduleDetails")
override fun createStore() = inject<ScheduleDetailsStoreFactory>().value
.create(getArgument(ARG_RESULT_ITEM))
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
with(viewBinding) {
recyclerView.layoutManager = LinearLayoutManager(requireContext())
recyclerView.adapter = adapter
}
setFixedSizeWorkaround()
}
private fun setFixedSizeWorkaround() {
val display = requireActivity().windowManager.defaultDisplay
val point = Point()
display.getSize(point)
viewBinding.recyclerView.minimumHeight = point.y
}
override fun render(state: ScheduleDetailsState) {
adapter.update(ScheduleDetailsListConverter.map(state, requireContext()))
}
override fun handleEffect(effect: ScheduleDetailsEffect) = when (effect) {
is ScheduleDetailsEffect.CloseAndGoToSchedule -> {
close()
router.executeCommand(ClearBackStack())
bottomTabsSwitcher.changeTab(BottomTab.DASHBOARD)
}
}
private fun createAdapter() = BaseAdapter(
TextAdapterItem(),
SpaceAdapterItem(),
PullAdapterItem(),
ShimmerAdapterItem(coreui_R.layout.item_text_shimmer),
ShimmerAdapterItem(R.layout.item_week_shimmer),
ShimmerAdapterItem(R.layout.item_classes_shimmer),
ButtonAdapterItem(ITEM_BUTTON_SWITCH, R.layout.item_button) {
analytics.sendClick("SwitchSchedule")
store.accept(Ui.Click.SwitchSchedule)
},
TextWithIconAdapterItem {
when (it.itemId) {
ITEM_FAVORITES -> {
analytics.sendClick("AddToFavorites")
store.accept(Ui.Click.Favorites)
}
else -> Unit
}
},
AdapterItem(
isType = { it is WeekMinItem },
layoutRes = R.layout.item_week_min,
viewHolderGenerator = ::WeekMinViewHolder,
itemBinder = WeekMinItemBinder(requireContext()) {
store.accept(Ui.Click.Day(it.date))
},
areItemsTheSame = { _, _ -> true }
),
AdapterItem(
isType = { it is Classes },
layoutRes = common_schedule_R.layout.item_classes_padding_horisontal_16dp,
viewHolderGenerator = ::ClassesViewHolderImpl,
itemBinder = ClassesItemBinder(requireContext()) { /* no-op */ }
),
EmptyStateAdapterItem()
)
companion object {
fun newInstance(resultItem: SearchResult) = ScheduleDetailsFragment()
.withArguments(ARG_RESULT_ITEM to resultItem)
}
}
| 19
|
Kotlin
|
4
| 28
|
209f34745458e150136c3cd6acb1fcad2e12ef9c
| 5,632
|
mpeiapp
|
MIT License
|
walletlibrary/src/main/java/com/microsoft/did/sdk/credential/service/models/attestations/CredentialAttestations.kt
|
microsoft
| 567,422,889
| false
| null |
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
package com.microsoft.did.sdk.credential.service.models.attestations
import kotlinx.serialization.Serializable
/**
* Class to bucket together credential requests.
*/
@Serializable
data class CredentialAttestations(
// IdToken Requests.
val idTokens: List<IdTokenAttestation> = emptyList(),
val accessTokens: List<AccessTokenAttestation> = emptyList(),
// Verifiable Presentation Requests.
val presentations: List<PresentationAttestation> = emptyList(),
// SelfIssued Claim Requests.
val selfIssued: SelfIssuedAttestation = SelfIssuedAttestation()
)
| 7
|
Kotlin
|
8
| 9
|
d7c28891eaa6f6d4bd373be324cd61ba32776622
| 937
|
entra-verifiedid-wallet-library-android
|
MIT License
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.