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/spritz/parser/nodes/EnumDefineNode.kt | SpritzLanguage | 606,570,819 | false | null | package spritz.parser.nodes
import spritz.lexer.position.Position
import spritz.lexer.token.Token
import spritz.parser.node.Node
import spritz.util.Argument
/**
* @author surge
* @since 04/03/2023
*/
class ClassDefineNode(val name: Token<*>, val constructor: List<Argument>, val body: Node?, start: Position, end: Position) : Node(start, end) {
override fun toString() = "(Class Define: $name, $constructor, $body)"
} | 0 | Kotlin | 0 | 23 | f50d81fa2d5aa7784ac4c76717603eea079c8db2 | 428 | Spritz | The Unlicense |
spring-boot-schedule/src/main/kotlin/com/example/schedule/SpringBootScheduleApplication.kt | anirban99 | 302,595,489 | false | null | package com.example.schedule
import org.springframework.boot.autoconfigure.SpringBootApplication
import org.springframework.boot.runApplication
@SpringBootApplication
class SpringBootScheduleApplication
fun main(args: Array<String>) {
runApplication<SpringBootScheduleApplication>(*args)
}
| 0 | Kotlin | 8 | 9 | 5b2fefbe07e1b5f36b5a5f633b1d5bb78657d183 | 294 | spring-boot-examples | Apache License 2.0 |
subprojects/core/src/main/kotlin/com/handtruth/mc/mcsman/server/session/Sessions.kt | handtruth | 417,843,728 | false | null | package com.handtruth.mc.mcsman.server.session
import com.handtruth.kommon.Log
import com.handtruth.mc.mcsman.NotExistsMCSManException
import com.handtruth.mc.mcsman.common.access.GlobalPermissions
import com.handtruth.mc.mcsman.server.AgentCheck
import com.handtruth.mc.mcsman.server.MCSManCore
import com.handtruth.mc.mcsman.server.TransactionContext
import com.handtruth.mc.mcsman.server.access.Accesses
import com.handtruth.mc.mcsman.server.util.Loggable
import com.handtruth.mc.mcsman.server.util.suspendTransaction
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.sync.Mutex
import kotlinx.coroutines.sync.withLock
import org.jetbrains.exposed.sql.Database
import org.koin.core.KoinComponent
import org.koin.core.inject
import java.util.concurrent.ConcurrentHashMap
import kotlin.collections.set
open class Sessions : CoroutineScope, Loggable, KoinComponent {
private val db: Database by inject()
private val accesses: Accesses by inject()
private val _sessions: MutableMap<Int, Session> = ConcurrentHashMap(1)
val sessions: Map<Int, Session> get() = _sessions
private val mutex = Mutex()
internal suspend fun putSession(session: Session) {
mutex.withLock {
_sessions[session.id] = session
}
}
internal suspend fun removeSession(session: Session) {
mutex.withLock {
_sessions.remove(session.id)
}
}
final override val coroutineContext = MCSManCore.fork("session")
final override val log = coroutineContext[Log]!!
private suspend inline fun checkPermission() {
val agent = getAgent()
@OptIn(TransactionContext::class)
suspendTransaction(db) {
accesses.global.checkAllowed(agent, GlobalPermissions.session, "session")
}
}
@AgentCheck
suspend fun list(): MutableList<Int> {
checkPermission()
return sessions.keys.toMutableList()
}
@AgentCheck
suspend fun getOrNull(id: Int): Session? {
checkPermission()
return sessions[id]
}
@AgentCheck
suspend fun get(id: Int): Session = getOrNull(id) ?: throw NotExistsMCSManException("session #$id does not exist")
}
| 0 | Kotlin | 0 | 0 | 58b2d4bd0413522dbf1cbabc1c8bab78e1b1edfe | 2,203 | mcsman | Apache License 2.0 |
dexfile/src/main/kotlin/org/tinygears/bat/dexfile/visitor/ClassDefVisitor.kt | TinyGearsOrg | 562,774,371 | false | {"Kotlin": 1879358, "Smali": 712514, "ANTLR": 26362, "Shell": 12090} | /*
* Copyright (c) 2020-2022 Thomas Neidhart.
*
* 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.tinygears.bat.dexfile.visitor
import org.tinygears.bat.dexfile.ClassDef
import org.tinygears.bat.dexfile.DexFile
import org.tinygears.bat.util.StringMatcher
import org.tinygears.bat.util.asInternalClassName
import org.tinygears.bat.util.classNameMatcher
import org.tinygears.bat.visitor.AbstractMultiVisitor
fun multiClassDefVisitorOf(visitor: ClassDefVisitor, vararg visitors: ClassDefVisitor): ClassDefVisitor {
return MultiClassDefVisitor(visitor, *visitors)
}
fun filteredByExternalClassName(regularExpression: String, visitor: ClassDefVisitorIndexed): ClassDefVisitorIndexed {
return ExternalClassNameFilter(regularExpression, visitor)
}
fun filteredByExternalClassName(regularExpression: String, visitor: ClassDefVisitor): ClassDefVisitor {
return ExternalClassNameFilter(regularExpression, visitor).toClassDefVisitor()
}
internal fun allClassData(visitor: ClassDataVisitor): ClassDefVisitor {
return ClassDefVisitor { dexFile, classDef -> classDef.classDataAccept(dexFile, visitor) }
}
fun allStaticFields(visitor: EncodedFieldVisitor): ClassDefVisitor {
return allClassData(allStaticFieldsOfClassData(visitor))
}
fun allInstanceFields(visitor: EncodedFieldVisitor): ClassDefVisitor {
return allClassData(allInstanceFieldsOfClassData(visitor))
}
fun allFields(visitor: EncodedFieldVisitor): ClassDefVisitor {
return allStaticFields(visitor).andThen(allInstanceFields(visitor))
}
fun allDirectMethods(visitor: EncodedMethodVisitor): ClassDefVisitor {
return allClassData(allDirectMethodsOfClassData(visitor))
}
fun allVirtualMethods(visitor: EncodedMethodVisitor): ClassDefVisitor {
return allClassData(allVirtualMethodsOfClassData(visitor))
}
fun allMethods(visitor: EncodedMethodVisitor): ClassDefVisitor {
return allDirectMethods(visitor).andThen(allVirtualMethods(visitor))
}
fun interface ClassDefVisitorIndexed {
fun visitClassDef(dexFile: DexFile, index: Int, classDef: ClassDef)
}
fun interface ClassDefVisitor: ClassDefVisitorIndexed {
fun visitClassDef(dexFile: DexFile, classDef: ClassDef)
override fun visitClassDef(dexFile: DexFile, index: Int, classDef: ClassDef) {
visitClassDef(dexFile, classDef)
}
fun andThen(vararg visitors: ClassDefVisitor): ClassDefVisitor {
return multiClassDefVisitorOf(this, *visitors)
}
}
private fun ClassDefVisitorIndexed.toClassDefVisitor(): ClassDefVisitor {
return ClassDefVisitor { dexFile, classDef -> [email protected](dexFile, 0, classDef) }
}
private class ExternalClassNameFilter(regularExpression: String, private val visitor: ClassDefVisitorIndexed) : ClassDefVisitorIndexed {
private val matcher: StringMatcher = classNameMatcher(regularExpression)
override fun visitClassDef(dexFile: DexFile, index: Int, classDef: ClassDef) {
val externalClassName = classDef.getClassName(dexFile).asInternalClassName().toExternalClassName()
if (accepted(externalClassName)) {
visitor.visitClassDef(dexFile, index, classDef)
}
}
private fun accepted(className: String): Boolean {
return matcher.matches(className)
}
}
private class MultiClassDefVisitor constructor( visitor: ClassDefVisitor,
vararg otherVisitors: ClassDefVisitor)
: AbstractMultiVisitor<ClassDefVisitor>(visitor, *otherVisitors), ClassDefVisitor {
override fun visitClassDef(dexFile: DexFile, classDef: ClassDef) {
for (visitor in visitors) {
visitor.visitClassDef(dexFile, classDef)
}
}
} | 0 | Kotlin | 0 | 0 | 50083893ad93820f9cf221598692e81dda05d150 | 4,223 | bat | Apache License 2.0 |
app/src/main/java/dev/sebastiano/bundel/navigation/NavigationRoute.kt | StylingAndroid | 387,452,390 | true | {"Kotlin": 167839} | package dev.sebastiano.bundel.navigation
import androidx.annotation.StringRes
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.rounded.History
import androidx.compose.material.icons.rounded.NotificationsActive
import androidx.compose.ui.graphics.vector.ImageVector
import dev.sebastiano.bundel.R
internal sealed class NavigationRoute(val route: String) {
object Onboarding : NavigationRoute("onboarding")
object MainScreen : NavigationRoute("main_screen") {
object NotificationsList : NavigationRoute("notifications_list"), BottomNavNavigationRoute {
override val icon: ImageVector = Icons.Rounded.NotificationsActive
override val labelId: Int = R.string.bottom_nav_active_notifications
}
object History : NavigationRoute("history"), BottomNavNavigationRoute {
override val icon: ImageVector = Icons.Rounded.History
override val labelId: Int = R.string.bottom_nav_history
}
}
interface BottomNavNavigationRoute {
val icon: ImageVector
@get:StringRes
val labelId: Int
}
}
| 0 | null | 0 | 1 | e8736f35e4b707af0f3d39ed1a179b1ae3f76d17 | 1,141 | bundel | Apache License 2.0 |
src/main/kotlin/ink/ptms/adyeshach/internal/listener/ListenerArmorStand.kt | Glom-c | 407,904,352 | true | {"Kotlin": 488508} | package ink.ptms.adyeshach.internal.listener
import ink.ptms.adyeshach.common.bukkit.BukkitRotation
import ink.ptms.adyeshach.common.editor.Editor
import ink.ptms.adyeshach.common.entity.type.AdyArmorStand
import org.bukkit.Bukkit
import org.bukkit.Sound
import org.bukkit.event.block.Action
import org.bukkit.event.player.PlayerInteractEvent
import org.bukkit.inventory.EquipmentSlot
import org.bukkit.inventory.ItemStack
import org.bukkit.inventory.meta.ItemMeta
import taboolib.common.LifeCycle
import taboolib.common.platform.Awake
import taboolib.common.platform.SubscribeEvent
import taboolib.common.platform.submit
import taboolib.library.xseries.XMaterial
import taboolib.module.chat.colored
import taboolib.module.ui.openMenu
import taboolib.module.ui.type.Basic
import taboolib.platform.util.*
/**
* @Author sky
* @Since 2020-03-17 21:08
*/
object ListenerArmorStand {
@Awake(LifeCycle.ACTIVE)
fun init() {
submit(period = 20) {
Bukkit.getOnlinePlayers().forEach {
if (it.isOp && Editor.editArmorStand.containsKey(it.name) && it.inventory.itemInMainHand.hasLore("Adyeshach Tool")) {
it.sendLang("armor-stand-editor-2")
}
}
}
}
@SubscribeEvent
fun e(e: PlayerInteractEvent) {
// edit mode
if (e.player.isOp && e.hand == EquipmentSlot.HAND && Editor.editArmorStand.containsKey(e.player.name) && e.player.inventory.itemInMainHand.hasLore("Adyeshach Tool")) {
e.isCancelled = true
if (e.player.isSneaking) {
val bind = Editor.editArmorStand[e.player.name]!!.first
val angle = Editor.editArmorStand[e.player.name]!!.second ?: return
if (e.action == Action.RIGHT_CLICK_AIR || e.action == Action.RIGHT_CLICK_BLOCK) {
angle.add.invoke(bind)
} else if (e.action == Action.LEFT_CLICK_AIR || e.action == Action.LEFT_CLICK_BLOCK) {
angle.subtract.invoke(bind)
}
e.player.playSound(e.player.location, Sound.ENTITY_EXPERIENCE_ORB_PICKUP, 1f, 2f)
} else {
e.player.openMenu<Basic>(e.player.asLangText("armor-stand-editor-name").toString()) {
rows(3)
onBuild(async = true) { _, inv ->
Angle.values().forEach { inv.addItem(it.toItem()) }
}
onClick(lock = true) {
if (it.rawSlot >= 0 && it.rawSlot < Angle.values().size) {
val bind = Editor.editArmorStand[e.player.name]!!.first
val angle = Angle.values()[it.rawSlot]
Editor.editArmorStand[e.player.name] = bind to angle
e.player.closeInventory()
e.player.inventory.setItemInMainHand(e.player.inventory.itemInMainHand.modifyMeta<ItemMeta> {
setDisplayName("&7Angle: &f${angle.name}".colored())
})
e.player.sendLang("armor-stand-editor-1", angle.name)
e.player.sendLang("armor-stand-editor-2")
}
}
}
}
}
}
enum class Angle(val add: (AdyArmorStand) -> (Unit) = { }, val subtract: (AdyArmorStand) -> (Unit) = { }, val item: XMaterial = XMaterial.PAPER) {
// 旋转
ROTATION({
it.setHeadRotation(it.position.yaw + 2f, it.position.pitch)
}, {
it.setHeadRotation(it.position.yaw - 2f, it.position.pitch)
}, XMaterial.GOLDEN_HELMET),
// 坐标
BASE_X({ it.teleport(it.position.add(1.0, 0.0, 0.0)) }, { it.teleport(it.position.subtract(1.0, 0.0, 0.0)) }, XMaterial.ARMOR_STAND),
BASE_Y({ it.teleport(it.position.add(0.0, 1.0, 0.0)) }, { it.teleport(it.position.subtract(0.0, 1.0, 0.0)) }, XMaterial.ARMOR_STAND),
BASE_Z({ it.teleport(it.position.add(0.0, 0.0, 1.0)) }, { it.teleport(it.position.subtract(0.0, 0.0, 1.0)) }, XMaterial.ARMOR_STAND),
// 头部
HEAD_X({ it.setRotation(BukkitRotation.HEAD, it.getRotation(BukkitRotation.HEAD).add(1.0, 0.0, 0.0)) },
{ it.setRotation(BukkitRotation.HEAD, it.getRotation(BukkitRotation.HEAD).subtract(1.0, 0.0, 0.0)) },
XMaterial.IRON_HELMET),
HEAD_Y({ it.setRotation(BukkitRotation.HEAD, it.getRotation(BukkitRotation.HEAD).add(0.0, 1.0, 0.0)) },
{ it.setRotation(BukkitRotation.HEAD, it.getRotation(BukkitRotation.HEAD).subtract(0.0, 1.0, 0.0)) },
XMaterial.IRON_HELMET),
HEAD_Z({ it.setRotation(BukkitRotation.HEAD, it.getRotation(BukkitRotation.HEAD).add(0.0, 0.0, 1.0)) },
{ it.setRotation(BukkitRotation.HEAD, it.getRotation(BukkitRotation.HEAD).subtract(0.0, 0.0, 1.0)) },
XMaterial.IRON_HELMET),
// 身体
BODY_X({ it.setRotation(BukkitRotation.BODY, it.getRotation(BukkitRotation.BODY).add(1.0, 0.0, 0.0)) },
{ it.setRotation(BukkitRotation.BODY, it.getRotation(BukkitRotation.BODY).subtract(1.0, 0.0, 0.0)) },
XMaterial.IRON_CHESTPLATE),
BODY_Y({ it.setRotation(BukkitRotation.BODY, it.getRotation(BukkitRotation.BODY).add(0.0, 1.0, 0.0)) },
{ it.setRotation(BukkitRotation.BODY, it.getRotation(BukkitRotation.BODY).subtract(0.0, 1.0, 0.0)) },
XMaterial.IRON_CHESTPLATE),
BODY_Z({ it.setRotation(BukkitRotation.BODY, it.getRotation(BukkitRotation.BODY).add(0.0, 0.0, 1.0)) },
{ it.setRotation(BukkitRotation.BODY, it.getRotation(BukkitRotation.BODY).subtract(0.0, 0.0, 1.0)) },
XMaterial.IRON_CHESTPLATE),
// 左手
LEFT_ARM_X({ it.setRotation(BukkitRotation.LEFT_ARM, it.getRotation(BukkitRotation.LEFT_ARM).add(1.0, 0.0, 0.0)) },
{ it.setRotation(BukkitRotation.LEFT_ARM, it.getRotation(BukkitRotation.LEFT_ARM).subtract(1.0, 0.0, 0.0)) },
XMaterial.STICK),
LEFT_ARM_Y({ it.setRotation(BukkitRotation.LEFT_ARM, it.getRotation(BukkitRotation.LEFT_ARM).add(0.0, 1.0, 0.0)) },
{ it.setRotation(BukkitRotation.LEFT_ARM, it.getRotation(BukkitRotation.LEFT_ARM).subtract(0.0, 1.0, 0.0)) },
XMaterial.STICK),
LEFT_ARM_Z({ it.setRotation(BukkitRotation.LEFT_ARM, it.getRotation(BukkitRotation.LEFT_ARM).add(0.0, 0.0, 1.0)) },
{ it.setRotation(BukkitRotation.LEFT_ARM, it.getRotation(BukkitRotation.LEFT_ARM).subtract(0.0, 0.0, 1.0)) },
XMaterial.STICK),
// 右手
RIGHT_ARM_X({ it.setRotation(BukkitRotation.RIGHT_ARM, it.getRotation(BukkitRotation.RIGHT_ARM).add(1.0, 0.0, 0.0)) },
{ it.setRotation(BukkitRotation.RIGHT_ARM, it.getRotation(BukkitRotation.RIGHT_ARM).subtract(1.0, 0.0, 0.0)) },
XMaterial.BLAZE_ROD),
RIGHT_ARM_Y({ it.setRotation(BukkitRotation.RIGHT_ARM, it.getRotation(BukkitRotation.RIGHT_ARM).add(0.0, 1.0, 0.0)) },
{ it.setRotation(BukkitRotation.RIGHT_ARM, it.getRotation(BukkitRotation.RIGHT_ARM).subtract(0.0, 1.0, 0.0)) },
XMaterial.BLAZE_ROD),
RIGHT_ARM_Z({ it.setRotation(BukkitRotation.RIGHT_ARM, it.getRotation(BukkitRotation.RIGHT_ARM).add(0.0, 0.0, 1.0)) },
{ it.setRotation(BukkitRotation.RIGHT_ARM, it.getRotation(BukkitRotation.RIGHT_ARM).subtract(0.0, 0.0, 1.0)) },
XMaterial.BLAZE_ROD),
// 左脚
LEFT_LEG_X({ it.setRotation(BukkitRotation.LEFT_LEG, it.getRotation(BukkitRotation.LEFT_LEG).add(1.0, 0.0, 0.0)) },
{ it.setRotation(BukkitRotation.LEFT_LEG, it.getRotation(BukkitRotation.LEFT_LEG).subtract(1.0, 0.0, 0.0)) },
XMaterial.IRON_LEGGINGS),
LEFT_LEG_Y({ it.setRotation(BukkitRotation.LEFT_LEG, it.getRotation(BukkitRotation.LEFT_LEG).add(0.0, 1.0, 0.0)) },
{ it.setRotation(BukkitRotation.LEFT_LEG, it.getRotation(BukkitRotation.LEFT_LEG).subtract(0.0, 1.0, 0.0)) },
XMaterial.IRON_LEGGINGS),
LEFT_LEG_Z({ it.setRotation(BukkitRotation.LEFT_LEG, it.getRotation(BukkitRotation.LEFT_LEG).add(0.0, 0.0, 1.0)) },
{ it.setRotation(BukkitRotation.LEFT_LEG, it.getRotation(BukkitRotation.LEFT_LEG).subtract(0.0, 0.0, 1.0)) },
XMaterial.IRON_LEGGINGS),
// 右脚
RIGHT_LEG_X({ it.setRotation(BukkitRotation.RIGHT_LEG, it.getRotation(BukkitRotation.RIGHT_LEG).add(1.0, 0.0, 0.0)) },
{ it.setRotation(BukkitRotation.RIGHT_LEG, it.getRotation(BukkitRotation.RIGHT_LEG).subtract(1.0, 0.0, 0.0)) },
XMaterial.GOLDEN_LEGGINGS),
RIGHT_LEG_Y({ it.setRotation(BukkitRotation.RIGHT_LEG, it.getRotation(BukkitRotation.RIGHT_LEG).add(0.0, 1.0, 0.0)) },
{ it.setRotation(BukkitRotation.RIGHT_LEG, it.getRotation(BukkitRotation.RIGHT_LEG).subtract(0.0, 1.0, 0.0)) },
XMaterial.GOLDEN_LEGGINGS),
RIGHT_LEG_Z({ it.setRotation(BukkitRotation.RIGHT_LEG, it.getRotation(BukkitRotation.RIGHT_LEG).add(0.0, 0.0, 1.0)) },
{ it.setRotation(BukkitRotation.RIGHT_LEG, it.getRotation(BukkitRotation.RIGHT_LEG).subtract(0.0, 0.0, 1.0)) },
XMaterial.GOLDEN_LEGGINGS);
fun toItem(): ItemStack {
return buildItem(item) {
name = "§7${<EMAIL>}"
}
}
}
}
| 0 | Kotlin | 0 | 0 | ea654b73b9a3a126833219c9baeddf8fb185c43d | 9,383 | Adyeshach | MIT License |
magic-obs/src/main/kotlin/com/github/vatbub/magic/data/CardDatabase.kt | vatbub | 352,061,373 | false | null | /*-
* #%L
* magic-obs
* %%
* Copyright (C) 2019 - 2022 Frederik Kammel
* %%
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* #L%
*/
package com.github.vatbub.magic.data
object CardDatabase {
@Suppress("SENSELESS_COMPARISON")
val cardObjects by lazy {
CardDatabaseParser
.parse()
// Might actually be nullable (Instants, Sorcery have no power or toughness),
// but we don't want them in our list
// and also don't want to pollute the type with the nullable marker
.filter { it.power != null }
.filter { it.toughness != null }
.map { it.fixNulls() }
}
}
data class CardObject(
val name: String,
val card_faces: List<CardFace>?,
val lang: Language,
val type_line: String,
val power: String,
val toughness: String,
val colors: List<ManaColor>,
val color_identity: List<ManaColor>,
val keywords: List<String>?
) {
fun fixNulls() = CardObjectNoNullables(
name,
card_faces?.map { it.fixNulls() } ?: listOf(),
lang,
type_line,
power,
toughness,
colors,
color_identity,
keywords ?: listOf(),
)
}
data class CardObjectNoNullables(
val name: String,
val card_faces: List<CardFaceLessNullables>,
val lang: Language,
val type_line: String,
val power: String,
val toughness: String,
val colors: List<ManaColor>,
val color_identity: List<ManaColor>,
val keywords: List<String>
) {
fun toOverlayCard() = Card(
attack = power.toDoubleOrNull() ?: 1.0,
defense = toughness.toDoubleOrNull() ?: 1.0,
counter = 0,
abilities = keywords.mapNotNull { it.toAbility() }.toSet()
)
}
enum class Language {
en,
es,
fr,
de,
it,
pt,
ja,
ko,
ru,
zhs,
zht,
he,
la,
grc,
ar,
sa,
ph,
}
enum class ManaColor(val apiString: String) {
White("W"),
Blue("U"),
Black("B"),
Red("R"),
Green("G");
companion object {
fun fromApiString(apiString: String) = values().first { it.apiString == apiString }
fun fromArray(iterable: Iterable<String>) = iterable.map { fromApiString(it) }
}
}
data class CardFace(
val name: String,
val type_line: String,
val power: String?,
val toughness: String?,
val colors: List<ManaColor>?,
val color_identity: List<ManaColor>?,
val keywords: List<String>?
) {
fun fixNulls() = CardFaceLessNullables(
name,
type_line,
power,
toughness,
colors ?: listOf(),
color_identity ?: listOf(),
keywords ?: listOf(),
)
}
data class CardFaceLessNullables(
val name: String,
val type_line: String,
val power: String?,
val toughness: String?,
val colors: List<ManaColor>,
val color_identity: List<ManaColor>,
val keywords: List<String>
)
private fun String.toAbility(): Ability? = when (this) {
"Explore" -> null
"Parley" -> null
else -> Ability.values().firstOrNull { it.name == this }
}
| 0 | Kotlin | 0 | 0 | 9919d8db94fd972cba32fab334f59cc43a156988 | 3,624 | magic-obs | Apache License 2.0 |
app/src/main/java/com/wtb/dashTracker/ui/activity_get_permissions/ui/composables/PageIndicator.kt | wtbenica | 433,718,630 | false | {"Kotlin": 715569, "Java": 326} | /*
* Copyright 2023 Wesley T. Benica
*
* 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.wtb.dashTracker.ui.activity_get_permissions.ui.composables
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Circle
import androidx.compose.material.icons.twotone.Circle
import androidx.compose.material3.Card
import androidx.compose.material3.CardDefaults
import androidx.compose.material3.Icon
import androidx.compose.material3.MaterialTheme
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.text.ExperimentalTextApi
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import com.wtb.dashTracker.R
import com.wtb.dashTracker.ui.theme.DashTrackerTheme
@Composable
internal fun PageIndicator(
modifier: Modifier = Modifier,
numPages: Int,
selectedPage: Int = 0
) {
Card(
shape = RoundedCornerShape(0.dp),
colors = CardDefaults.cardColors(
containerColor = MaterialTheme.colorScheme.onTertiary,
contentColor = MaterialTheme.colorScheme.onPrimary
)
) {
Row(
horizontalArrangement = Arrangement.Center,
modifier = Modifier
.fillMaxWidth()
.padding(vertical = 8.dp)
.then(modifier)
) {
for (i in 0 until numPages) {
Icon(
if (i == selectedPage) Icons.Filled.Circle else Icons.TwoTone.Circle,
contentDescription = stringResource(
R.string.content_desc_page_indicator,
selectedPage + 1,
numPages
),
modifier = Modifier.size(8.dp),
tint = MaterialTheme.colorScheme.inversePrimary
)
}
}
}
}
@ExperimentalTextApi
@Preview(showBackground = true)
@Composable
fun PageIndicatorPreview() {
DashTrackerTheme {
PageIndicator(numPages = 4, selectedPage = 1)
}
} | 10 | Kotlin | 0 | 0 | a05d1e03ae9255f9f97b62b1eafc4d85a585d330 | 2,753 | DashTracker | Apache License 2.0 |
app/src/main/java/com/hotmail/or_dvir/sabinesList/ui/SearchScreenModel.kt | or-dvir | 649,311,997 | false | null | package com.hotmail.or_dvir.sabinesList.ui
import cafe.adriel.voyager.core.model.ScreenModel
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asStateFlow
abstract class SearchScreenModel : ScreenModel {
private val _searchQuery = MutableStateFlow("")
val searchQueryFlow: StateFlow<String> = _searchQuery.asStateFlow()
private val _isSearchActive = MutableStateFlow(false)
val isSearchActiveFlow = _isSearchActive.asStateFlow()
fun setSearchQuery(query: String) {
_searchQuery.value = query
}
fun setSearchActiveState(isActive: Boolean) {
_isSearchActive.value = isActive
}
}
| 0 | Kotlin | 0 | 0 | 2a25fe3dc1cc361f98c61b32a541ec14e88507e5 | 700 | SabinesList | Apache License 2.0 |
androidApp/src/main/java/dev/johnoreilly/kikiconf/android/di/AppModule.kt | martinbonnin | 439,969,364 | true | {"Kotlin": 25039, "Swift": 5382} | package dev.johnoreilly.mortycomposekmm.di
import dev.johnoreilly.kikiconf.android.KikiConfViewModel
import org.koin.androidx.viewmodel.dsl.viewModel
import org.koin.dsl.module
val appModule = module {
viewModel { KikiConfViewModel(get()) }
}
| 0 | Kotlin | 0 | 0 | 7c54f4895be1c03dfa76a36d388efe2991b6bed3 | 249 | Confetti | Apache License 2.0 |
api_viewing/src/main/kotlin/com/madness/collision/unit/api_viewing/util/PrefUtil.kt | cliuff | 231,891,447 | false | {"Kotlin": 1532215} | /*
* Copyright 2021 <NAME>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.madness.collision.unit.api_viewing.util
import com.madness.collision.unit.api_viewing.MyUnit
import com.madness.collision.unit.api_viewing.main.MainStatus
internal object PrefUtil {
const val AV_TAGS = "AvTags"
const val API_APK_PRELOAD = "apiAPKPreload"
const val API_APK_PRELOAD_DEFAULT = false
const val API_CIRCULAR_ICON = "SDKCircularIcon"
// render round icon only when user specifies
const val API_CIRCULAR_ICON_DEFAULT = false
const val API_PACKAGE_ROUND_ICON = "APIPackageRoundIcon"
const val API_PACKAGE_ROUND_ICON_DEFAULT = false
const val AV_CLIP_ROUND = "AVClip2Round"
const val AV_CLIP_ROUND_DEFAULT = true
const val AV_SWEET = "AVSweet"
const val AV_SWEET_DEFAULT = true
const val AV_VIEWING_TARGET = "AVViewingTarget"
const val AV_VIEWING_TARGET_DEFAULT = true
const val AV_INCLUDE_DISABLED = "AVIncludeDisabled"
const val AV_INCLUDE_DISABLED_DEFAULT = false
const val AV_SORT_ITEM = "SDKCheckSortSpinnerSelection"
const val AV_SORT_ITEM_DEFAULT = MyUnit.SORT_POSITION_API_TIME
const val AV_LIST_SRC_ITEM = "SDKCheckDisplaySpinnerSelection"
const val AV_LIST_SRC_ITEM_DEFAULT = MainStatus.DISPLAY_APPS_USER
}
| 0 | Kotlin | 9 | 97 | bf61e5587039098c3161f8d1a8cd5c7398cb1b82 | 1,810 | boundo | Apache License 2.0 |
amazon/dynamodb/client/src/main/kotlin/org/http4k/connect/amazon/dynamodb/action/PutItem.kt | http4k | 295,641,058 | false | {"Kotlin": 1624385, "Handlebars": 10370, "CSS": 5434, "Shell": 3178, "JavaScript": 2076, "Python": 1834, "HTML": 675} | package org.http4k.connect.amazon.dynamodb.action
import org.http4k.connect.Http4kConnectAction
import org.http4k.connect.amazon.dynamodb.DynamoDbAction
import org.http4k.connect.amazon.dynamodb.DynamoDbMoshi
import org.http4k.connect.amazon.dynamodb.model.Item
import org.http4k.connect.amazon.dynamodb.model.ReturnConsumedCapacity
import org.http4k.connect.amazon.dynamodb.model.ReturnItemCollectionMetrics
import org.http4k.connect.amazon.dynamodb.model.ReturnValues
import org.http4k.connect.amazon.dynamodb.model.TableName
import org.http4k.connect.amazon.dynamodb.model.TokensToNames
import org.http4k.connect.amazon.dynamodb.model.TokensToValues
import se.ansman.kotshi.JsonSerializable
@Http4kConnectAction
@JsonSerializable
data class PutItem(
val TableName: TableName,
val Item: Item,
val ConditionExpression: String? = null,
val ExpressionAttributeNames: TokensToNames? = null,
val ExpressionAttributeValues: TokensToValues? = null,
val ReturnConsumedCapacity: ReturnConsumedCapacity? = null,
val ReturnItemCollectionMetrics: ReturnItemCollectionMetrics? = null,
val ReturnValues: ReturnValues? = null
) : DynamoDbAction<ModifiedItem>(ModifiedItem::class, DynamoDbMoshi)
| 7 | Kotlin | 17 | 37 | 3522f4a2bf5e476b849ec367700544d89e006f71 | 1,216 | http4k-connect | Apache License 2.0 |
feature/settings/src/main/java/org/expenny/feature/settings/SettingsToolbar.kt | expenny-application | 712,607,222 | false | {"Kotlin": 964616} | package org.expenny.feature.settings
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.TopAppBarScrollBehavior
import androidx.compose.runtime.Composable
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.res.stringResource
import org.expenny.core.resources.R
import org.expenny.core.ui.foundation.ExpennyText
import org.expenny.core.ui.foundation.ExpennyToolbar
@OptIn(ExperimentalMaterial3Api::class)
@Composable
internal fun SettingsToolbar(
scrollBehavior: TopAppBarScrollBehavior,
onBackClick: () -> Unit
) {
ExpennyToolbar(
scrollBehavior = scrollBehavior,
navigationIcon = {
IconButton(onClick = onBackClick) {
Icon(
painter = painterResource(R.drawable.ic_arrow_back),
tint = MaterialTheme.colorScheme.onSurface,
contentDescription = null
)
}
},
title = {
ExpennyText(
text = stringResource(R.string.settings_label),
style = MaterialTheme.typography.titleLarge,
color = MaterialTheme.colorScheme.onSurface
)
}
)
} | 0 | Kotlin | 0 | 0 | 810f202f0092cc170e0d44c757645de122bbdeec | 1,365 | expenny-android | Apache License 2.0 |
usvm-jvm-instrumentation/src/main/kotlin/org/usvm/instrumentation/serializer/SerializationContext.kt | UnitTestBot | 586,907,774 | false | {"Kotlin": 2623144, "Java": 476836} | package org.usvm.instrumentation.serializer
import org.jacodb.api.jvm.JcClasspath
import org.usvm.instrumentation.testcase.descriptor.UTestValueDescriptor
import org.usvm.instrumentation.testcase.api.UTestInst
import java.util.*
class SerializationContext(
val jcClasspath: JcClasspath,
) {
val serializedUTestInstructions = IdentityHashMap<UTestInst, Int>()
val deserializedUTestInstructions: MutableMap<Int, UTestInst> = hashMapOf()
val serializedDescriptors = IdentityHashMap<UTestValueDescriptor, Int>()
val deserializedDescriptors = HashMap<Int, UTestValueDescriptor>()
fun reset() {
serializedUTestInstructions.clear()
serializedDescriptors.clear()
deserializedDescriptors.clear()
}
} | 36 | Kotlin | 4 | 9 | 819268c3c77c05d798891be826164bbede63fdfb | 745 | usvm | Apache License 2.0 |
simple-icons/src/commonMain/kotlin/compose/icons/simpleicons/Niconico.kt | DevSrSouza | 311,134,756 | false | {"Kotlin": 36719092} | package compose.icons.simpleicons
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.PathFillType.Companion.NonZero
import androidx.compose.ui.graphics.SolidColor
import androidx.compose.ui.graphics.StrokeCap.Companion.Butt
import androidx.compose.ui.graphics.StrokeJoin.Companion.Miter
import androidx.compose.ui.graphics.vector.ImageVector
import androidx.compose.ui.graphics.vector.ImageVector.Builder
import androidx.compose.ui.graphics.vector.path
import androidx.compose.ui.unit.dp
import compose.icons.SimpleIcons
public val SimpleIcons.Niconico: ImageVector
get() {
if (_niconico != null) {
return _niconico!!
}
_niconico = Builder(name = "Niconico", defaultWidth = 24.0.dp, defaultHeight = 24.0.dp,
viewportWidth = 24.0f, viewportHeight = 24.0f).apply {
path(fill = SolidColor(Color(0xFF000000)), stroke = null, strokeLineWidth = 0.0f,
strokeLineCap = Butt, strokeLineJoin = Miter, strokeLineMiter = 4.0f,
pathFillType = NonZero) {
moveTo(0.479f, 7.534f)
verticalLineToRelative(12.128f)
arcTo(2.021f, 2.021f, 0.0f, false, false, 2.5f, 21.683f)
horizontalLineToRelative(2.389f)
lineToRelative(1.323f, 2.095f)
arcToRelative(0.478f, 0.478f, 0.0f, false, false, 0.404f, 0.221f)
arcToRelative(0.478f, 0.478f, 0.0f, false, false, 0.441f, -0.221f)
lineToRelative(1.323f, -2.095f)
horizontalLineToRelative(6.983f)
lineToRelative(1.323f, 2.095f)
arcToRelative(0.478f, 0.478f, 0.0f, false, false, 0.441f, 0.221f)
curveToRelative(0.184f, 0.0f, 0.331f, -0.073f, 0.404f, -0.221f)
lineToRelative(1.323f, -2.095f)
horizontalLineToRelative(2.646f)
arcToRelative(2.021f, 2.021f, 0.0f, false, false, 2.021f, -2.021f)
verticalLineTo(7.534f)
arcToRelative(2.021f, 2.021f, 0.0f, false, false, -2.021f, -1.985f)
horizontalLineToRelative(-7.681f)
lineToRelative(4.447f, -4.447f)
lineTo(17.164f, 0.0f)
lineToRelative(-5.145f, 5.145f)
lineTo(6.8f, 0.0f)
lineTo(5.697f, 1.102f)
lineToRelative(4.41f, 4.41f)
horizontalLineTo(2.537f)
arcToRelative(2.021f, 2.021f, 0.0f, false, false, -2.058f, 2.058f)
close()
}
}
.build()
return _niconico!!
}
private var _niconico: ImageVector? = null
| 17 | Kotlin | 25 | 571 | a660e5f3033e3222e3553f5a6e888b7054aed8cd | 2,677 | compose-icons | MIT License |
drm-blockchain/src/test/kotlin/moe/_47saikyo/drm/blockchain/service/RightServiceTest.kt | Smileslime47 | 738,883,139 | false | {"Kotlin": 243069, "Vue": 73384, "Java": 49135, "TypeScript": 25030, "Solidity": 18621, "CSS": 1622, "Dockerfile": 774, "Shell": 511, "HTML": 390} | package moe._47saikyo.drm.blockchain.service
import moe._47saikyo.*
import moe._47saikyo.drm.blockchain.*
import moe._47saikyo.drm.blockchain.configuration.koin.KoinBlockChainWrapperConfiguration
import moe._47saikyo.drm.blockchain.constant.BlockChainConstant
import org.koin.core.context.startKoin
import org.koin.java.KoinJavaComponent.inject
import org.slf4j.LoggerFactory
import org.web3j.abi.FunctionEncoder
import org.web3j.abi.FunctionReturnDecoder
import org.web3j.abi.TypeReference
import org.web3j.abi.datatypes.Function
import org.web3j.protocol.core.DefaultBlockParameterName
import org.web3j.protocol.core.methods.request.Transaction
import kotlin.test.BeforeTest
import kotlin.test.Test
/**
* RightServiceTest
*
* @author 刘一邦
*/
class RightServiceTest {
private val logger = LoggerFactory.getLogger(RightServiceTest::class.java)
private val accountService: AccountService by inject(AccountService::class.java)
private val rightService:RightService by inject(RightService::class.java)
/**
* 初始化区块链连接
*/
@BeforeTest
fun setUp() {
startKoin {
modules(KoinBlockChainWrapperConfiguration.module)
}
BlockChainTest.init()
}
@Test
fun getPureDataWithManagerTest() {
//创建函数调用交易
val function = Function("serialize", emptyList(), listOf(TypeReference.create(string::class.java)))
val transaction = Transaction.createEthCallTransaction(
BlockChain.bankAddress!!,
"0x17ee7ffa7f79a43b51dc7e01ef924b0f541fdfeb",
FunctionEncoder.encode(function)
)
//发送交易并获取结果
val result = BlockChain.web3jInstance!!.ethCall(transaction, DefaultBlockParameterName.LATEST).send().value
//获取函数返回值
val json = FunctionReturnDecoder.decode(result, function.outputParameters)[0].value as String
//解析json并返回
logger.info(json)
}
@Test
fun testAddGas(){
assert(
Estimate.estimateCall(
"0xcb7f6d5c8f5c71c3f604f6fec874a97007dfe4fe",
"0xef563dee888cb304dd660b9f6e6b261f1a2295d2",
"addLicense",
listOf(
address(BlockChainConstant.ADDRESS_PLACEHOLDER)
),
emptyList()
) == BlockChainConstant.Gas.RIGHT_ADD//66014L
)
}
} | 0 | Kotlin | 0 | 4 | e0053b3b1e81e049c6869e4a0f52bfdfb2bcbacb | 2,369 | Digital-Rights-Management | MIT License |
app/src/main/java/com/myapp/foodplus/fragments/DiscoverFragment.kt | ferry582 | 567,829,341 | false | {"Kotlin": 54347} | package com.myapp.foodplus.fragments
import android.content.Context
import android.content.Intent
import android.graphics.Bitmap
import android.graphics.Canvas
import android.net.Uri
import android.os.Bundle
import android.provider.Settings
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.EditText
import android.widget.LinearLayout
import android.widget.Toast
import androidx.constraintlayout.widget.ConstraintLayout
import androidx.core.content.ContextCompat
import androidx.fragment.app.Fragment
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.google.android.gms.maps.CameraUpdateFactory
import com.google.android.gms.maps.GoogleMap
import com.google.android.gms.maps.GoogleMap.OnMarkerClickListener
import com.google.android.gms.maps.OnMapReadyCallback
import com.google.android.gms.maps.SupportMapFragment
import com.google.android.gms.maps.model.BitmapDescriptor
import com.google.android.gms.maps.model.BitmapDescriptorFactory
import com.google.android.gms.maps.model.LatLng
import com.google.android.gms.maps.model.Marker
import com.google.android.gms.maps.model.MarkerOptions
import com.google.android.material.bottomsheet.BottomSheetBehavior
import com.google.android.material.floatingactionbutton.FloatingActionButton
import com.karumi.dexter.Dexter
import com.karumi.dexter.PermissionToken
import com.karumi.dexter.listener.PermissionDeniedResponse
import com.karumi.dexter.listener.PermissionGrantedResponse
import com.karumi.dexter.listener.PermissionRequest
import com.karumi.dexter.listener.single.PermissionListener
import com.myapp.foodplus.R
import com.myapp.foodplus.activities.RestaurantDetailActivity
import com.myapp.foodplus.adaters.RestaurantAdapter
import com.myapp.foodplus.models.RestaurantData
class DiscoverFragment : Fragment(), OnMapReadyCallback, OnMarkerClickListener,
GoogleMap.OnInfoWindowClickListener {
private var isPermissionGranted: Boolean = false
private var myLocationButton: View? = null
override fun onMapReady(googleMap: GoogleMap) {
googleMap.isMyLocationEnabled = true
googleMap.moveCamera(CameraUpdateFactory.newLatLngZoom(LatLng(-7.7796278208676775, 110.42692899786957), 14f))
// googleMap.addMarker( MarkerOptions().position(LatLng(-7.775448482884702, 110.3803106106482)).title("Restaurant 1"))
// get data from string resource
val locName = resources.getStringArray(R.array.loc_name)
val lat = resources.getStringArray(R.array.latitude)
val long = resources.getStringArray(R.array.longitude)
// Display restaurant marker
for (i in locName.indices) {
googleMap.addMarker( MarkerOptions()
.position(LatLng(lat[i].toDouble(), long[i].toDouble()))
.title(locName[i])
.icon(BitmapFromVector(requireContext(), R.drawable.ic_restaurant_location_open)))
}
// // when marker clicked
// googleMap.setOnMarkerClickListener(this)
// when marker's info window clicked
googleMap.setOnInfoWindowClickListener(this)
}
private fun BitmapFromVector(context: Context, vectorResId: Int): BitmapDescriptor? {
val vectorDrawable = ContextCompat.getDrawable(context, vectorResId)
vectorDrawable!!.setBounds(
0,
0,
vectorDrawable.intrinsicWidth,
vectorDrawable.intrinsicHeight
)
val bitmap = Bitmap.createBitmap(
vectorDrawable.intrinsicWidth,
vectorDrawable.intrinsicHeight,
Bitmap.Config.ARGB_8888
)
val canvas = Canvas(bitmap)
vectorDrawable.draw(canvas)
return BitmapDescriptorFactory.fromBitmap(bitmap)
}
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
return inflater.inflate(R.layout.fragment_discover, container, false)
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
// Initialize google maps
checkMyPermission()
if (isPermissionGranted) {
val mapFragment = childFragmentManager.findFragmentById(R.id.map) as SupportMapFragment?
mapFragment?.getMapAsync(this)
myLocationButton = mapFragment?.view?.findViewById(0x2)
// Remove the default my location button
if (myLocationButton != null ) {
myLocationButton?.visibility = View.GONE
}
}
// Configure bottom sheet
val bottomSheet = view.findViewById<ConstraintLayout>(R.id.bottomSheet)
BottomSheetBehavior.from(bottomSheet).apply {
peekHeight = 210
this.state = BottomSheetBehavior.STATE_EXPANDED
// ToDo : set bottom sheet jd expanded ketika radio button di klik (dan ubah tvDescription nya)
}
// Bottom sheet will collapsed when seach edit text is clicked
val etSearch = view.findViewById<EditText>(R.id.etSearch)
etSearch.setOnClickListener {
BottomSheetBehavior.from(bottomSheet).state = BottomSheetBehavior.STATE_COLLAPSED
}
// Configure myLocation Button
view.findViewById<FloatingActionButton>(R.id.fabMyLocation).setOnClickListener {
if(myLocationButton != null)
myLocationButton?.callOnClick()
}
// Configure Restaurants Recycler View
val restaurantDataList = ArrayList<RestaurantData>()
restaurantDataList.addAll(listRestaurantData)
val recyclerView = view.findViewById<RecyclerView>(R.id.rv_restaurant)
recyclerView.layoutManager = LinearLayoutManager(context)
recyclerView.setHasFixedSize(true)
recyclerView.isNestedScrollingEnabled = true
recyclerView.adapter = RestaurantAdapter(requireContext(), restaurantDataList) {
val intent = Intent (context, RestaurantDetailActivity::class.java)
intent.putExtra("OBJECT_INTENT", it)
startActivity(intent)
}
}
private val listRestaurantData: ArrayList<RestaurantData>
get() {
val dataName = resources.getStringArray(R.array.data_restaurant_name)
val dataHighlight = resources.getStringArray(R.array.data_restaurant_highlight)
val dataPhoto = resources.obtainTypedArray(R.array.data_restaurant_photo)
val dataDesc = resources.getStringArray(R.array.data_restaurant_description)
val lists = ArrayList<RestaurantData>()
for (i in 1..5) { // set data restaurant bakery menjadi 5 ke dalam list
for (i in dataName.indices) {
val restaurantData = RestaurantData(
dataName[i], dataHighlight[i], dataPhoto.getResourceId(i, -1), dataDesc[i], 0.0, 0.0
)
lists.add(restaurantData)
}
}
return lists
}
private fun checkMyPermission() {
Dexter.withContext([email protected])
.withPermission(android.Manifest.permission.ACCESS_FINE_LOCATION)
.withListener(object : PermissionListener {
override fun onPermissionGranted(response: PermissionGrantedResponse) {
// Snackbar.make(view!!.findViewById(R.id.discoverLayout), "Permission Granted", Snackbar.LENGTH_LONG).show()
// Toast.makeText([email protected], "Permission Granted", Toast.LENGTH_LONG).show()
isPermissionGranted = true
}
override fun onPermissionDenied(response: PermissionDeniedResponse) {
val intent = Intent()
intent.action = Settings.ACTION_APPLICATION_DETAILS_SETTINGS
val uri: Uri = Uri.fromParts("package", context!!.packageName, "")
intent.data = uri
Toast.makeText([email protected], "Turn on your location permission", Toast.LENGTH_LONG).show()
startActivity(intent)
}
override fun onPermissionRationaleShouldBeShown(
permission: PermissionRequest?,
token: PermissionToken?
) {
token?.continuePermissionRequest()
}
}).check()
}
override fun onMarkerClick(p0: Marker): Boolean {
// // Get data from string resource
// val dataName = resources.getStringArray(R.array.data_restaurant_name)
// val dataHighlight = resources.getStringArray(R.array.data_restaurant_highlight)
// val dataPhoto = resources.obtainTypedArray(R.array.data_restaurant_photo)
// val dataDesc = resources.getStringArray(R.array.data_restaurant_description)
//
// val intent = Intent (context, RestaurantDetailActivity::class.java)
// intent.putExtra("OBJECT_INTENT", RestaurantData(
// dataName[0], dataHighlight[0], dataPhoto.getResourceId(0, -1), dataDesc[0], 0.0, 0.0
// ))
// startActivity(intent)
return true
}
override fun onInfoWindowClick(p0: Marker) {
// Get data from string resource
val dataName = resources.getStringArray(R.array.data_restaurant_name)
val dataHighlight = resources.getStringArray(R.array.data_restaurant_highlight)
val dataPhoto = resources.obtainTypedArray(R.array.data_restaurant_photo)
val dataDesc = resources.getStringArray(R.array.data_restaurant_description)
val intent = Intent (context, RestaurantDetailActivity::class.java)
intent.putExtra("OBJECT_INTENT", RestaurantData(
dataName[0], dataHighlight[0], dataPhoto.getResourceId(0, -1), dataDesc[0], 0.0, 0.0
))
startActivity(intent)
}
} | 0 | Kotlin | 1 | 0 | 14bacec6439817fe458791cf1a8ea56bb730fa0d | 10,040 | food_plus_app | MIT License |
chat/src/main/java/com/crafttalk/chat/data/repository/NotificationRepository.kt | crafttalk | 329,962,842 | false | null | package com.crafttalk.chat.data.repository
import com.crafttalk.chat.data.api.rest.NotificationApi
import com.crafttalk.chat.domain.entity.notification.NetworkCheckSubscription
import com.crafttalk.chat.domain.entity.notification.NetworkResultCheckSubscription
import com.crafttalk.chat.domain.entity.notification.NetworkSubscription
import com.crafttalk.chat.domain.entity.notification.NetworkUnsubscription
import com.crafttalk.chat.domain.repository.INotificationRepository
import com.google.android.gms.tasks.OnCompleteListener
import com.google.firebase.iid.FirebaseInstanceId
import retrofit2.Call
import retrofit2.Callback
import retrofit2.Response
import javax.inject.Inject
class NotificationRepository
@Inject constructor(
private val notificationApi: NotificationApi
) : INotificationRepository {
private fun checkSubscription(uuid: String, hasSubscription: Boolean, success: () -> Unit) {
notificationApi.checkSubscription(NetworkCheckSubscription(uuid)).enqueue(object : Callback<NetworkResultCheckSubscription> {
override fun onResponse(call: Call<NetworkResultCheckSubscription>, response: Response<NetworkResultCheckSubscription>) {
if (response.isSuccessful && response.body()?.result == hasSubscription) {
success()
}
}
override fun onFailure(call: Call<NetworkResultCheckSubscription>, t: Throwable) {}
})
}
override fun subscribe(uuid: String) {
getToken { token ->
checkSubscription(uuid, false) {
notificationApi.subscribe(NetworkSubscription(token, uuid)).enqueue(object : Callback<Unit> {
override fun onResponse(call: Call<Unit>, response: Response<Unit>) {}
override fun onFailure(call: Call<Unit>, t: Throwable) {}
})
}
}
}
override fun unSubscribe(uuid: String) {
checkSubscription(uuid, true) {
notificationApi.unsubscribe(NetworkUnsubscription(uuid)).enqueue(object : Callback<Unit> {
override fun onResponse(call: Call<Unit>, response: Response<Unit>) {}
override fun onFailure(call: Call<Unit>, t: Throwable) {}
})
}
}
override fun getToken(success: (token: String) -> Unit) {
FirebaseInstanceId.getInstance().instanceId
.addOnCompleteListener(OnCompleteListener { task ->
if (!task.isSuccessful) {
return@OnCompleteListener
}
val token = task.result?.token
token?.let(success)
})
}
} | 1 | Kotlin | 3 | 2 | dbedafea31d0d362c5851bbd4440b13897891844 | 2,663 | crafttalk-android-sdk | Apache License 2.0 |
src/main/kotlin/io/jvaas/dsl/html/element/META.kt | JVAAS | 304,887,456 | false | null | package io.jvaas.dsl.html.element
import io.jvaas.dsl.html.*
import io.jvaas.dsl.html.attribute.*
import io.jvaas.dsl.html.funtribute.*
// generated by HtmlDslGenerator.kt
open class META(
charset: String? = null,
content: String? = null,
name: String? = null,
tagName: String = "meta",
selfClosing: Boolean = true
) : AttrCharset,
AttrConTent,
AttrName,
Tag(
tagName = tagName,
selfClosing = selfClosing,
) {
init {
this.charset = charset
this.content = content
this.name = name
}
}
| 0 | Kotlin | 2 | 3 | e6e17b834673e8755ed4cbabacabf9df2a0ffbae | 514 | jvaas-html | Apache License 2.0 |
app/src/test/java/com/ruben/epicworld/viewmodel/GameDetailsVMTest.kt | rubenquadros | 391,401,374 | false | null | package com.ruben.epicworld.viewmodel
import androidx.lifecycle.SavedStateHandle
import com.ruben.epicworld.domain.entity.base.ErrorRecord
import com.ruben.epicworld.domain.entity.base.Record
import com.ruben.epicworld.domain.entity.gamedetails.GameDetailsEntity
import com.ruben.epicworld.domain.interactor.GetGameDetailsUseCase
import com.ruben.epicworld.domain.repository.GamesRepository
import com.ruben.epicworld.presentation.base.ScreenState
import com.ruben.epicworld.presentation.details.GameDetailsSideEffect
import com.ruben.epicworld.presentation.details.GameDetailsState
import com.ruben.epicworld.presentation.details.GameDetailsViewModel
import io.mockk.MockKAnnotations
import io.mockk.clearAllMocks
import io.mockk.coEvery
import io.mockk.coVerify
import io.mockk.confirmVerified
import io.mockk.mockk
import io.mockk.unmockkAll
import kotlinx.coroutines.ExperimentalCoroutinesApi
import kotlinx.coroutines.test.UnconfinedTestDispatcher
import kotlinx.coroutines.test.runTest
import org.junit.After
import org.junit.Before
import org.junit.Test
import org.orbitmvi.orbit.test
/**
* Created by <NAME> on 07/08/21
**/
@ExperimentalCoroutinesApi
class GameDetailsVMTest {
private val mockRepository = mockk<GamesRepository>()
private val useCase = GetGameDetailsUseCase(mockRepository)
private val initialState = GameDetailsState(ScreenState.Loading, null, null)
@Before
fun init() {
MockKAnnotations.init(this, true)
}
@Test
fun `vm should invoke use case to get game details`() = runTest(UnconfinedTestDispatcher()) {
val savedStateHandle = SavedStateHandle().apply {
set("gameId", 2)
}
val gameDetailsViewModel = GameDetailsViewModel(
savedStateHandle,
useCase
).test(initialState = initialState)
val mockResponse = GameDetailsEntity()
coEvery { mockRepository.getGameDetails(2) } answers {
Record(mockResponse, null)
}
val success = gameDetailsViewModel.testIntent {
getGameDetails(2)
}
success.assert(initialState) {
states(
{ copy(screenState = ScreenState.Success, error = null, gameDetails = mockResponse) }
)
}
coVerify { mockRepository.getGameDetails(2) }
confirmVerified(mockRepository)
}
@Test
fun `vm should post side effect when there is error in getting game details`() = runTest(UnconfinedTestDispatcher()) {
val savedStateHandle = SavedStateHandle().apply {
set("gameId", 2)
}
val gameDetailsViewModel = GameDetailsViewModel(
savedStateHandle,
useCase
).test(initialState = initialState)
coEvery { mockRepository.getGameDetails(2) } answers {
Record(null, ErrorRecord.GenericError)
}
val error = gameDetailsViewModel.testIntent {
getGameDetails(2)
}
error.assert(initialState) {
states(
{ copy(screenState = ScreenState.Error, gameDetails = null, error = ErrorRecord.GenericError) }
)
postedSideEffects(
GameDetailsSideEffect.ShowGameDetailsErrorToast
)
}
coVerify { mockRepository.getGameDetails(2) }
confirmVerified(mockRepository)
}
@Test
fun `vm should post side effect when there is error with game id`() = runTest(UnconfinedTestDispatcher()) {
val savedStateHandle = SavedStateHandle()
val gameDetailsViewModel = GameDetailsViewModel(
savedStateHandle,
useCase
).test(initialState = initialState)
val error = gameDetailsViewModel.runOnCreate()
error.assert(initialState) {
postedSideEffects(
GameDetailsSideEffect.ShowGameIdErrorToast
)
}
}
@After
fun tearDown() {
clearAllMocks()
unmockkAll()
}
} | 1 | Kotlin | 9 | 81 | 215317852936a0c0849b6434e030d0ecb9be8546 | 3,998 | Jetpack-Compose-Video-Games-Example | Apache License 2.0 |
app/src/main/java/nawrot/mateusz/lausannefleet/domain/base/ObservableUnitUseCase.kt | mateusz-nawrot | 161,166,079 | false | null | package nawrot.mateusz.lausannefleet.domain.base
import io.reactivex.Observable
abstract class ObservableUnitUseCase<R>(schedulersProvider: SchedulersProvider) : ObservableUseCase<Unit, R>(schedulersProvider) {
fun execute(): Observable<R> {
return execute(Unit)
}
} | 0 | Kotlin | 0 | 0 | 419ad899a080e828a66ab38b481f5a351c4755cb | 287 | lausanne-fleet | MIT License |
app/src/main/java/com/cyh128/hikari_novel/ui/view/main/more/more/about/AboutActivity.kt | 15dd | 645,796,447 | false | {"Kotlin": 332962} | package com.cyh128.hikari_novel.ui.view.main.more.more.about
import android.os.Bundle
import androidx.lifecycle.ViewModelProvider
import com.cyh128.hikari_novel.R
import com.cyh128.hikari_novel.base.BaseActivity
import com.cyh128.hikari_novel.data.model.Event
import com.cyh128.hikari_novel.databinding.ActivityAboutBinding
import com.cyh128.hikari_novel.util.launchWithLifecycle
import com.cyh128.hikari_novel.util.openUrl
import com.google.android.material.dialog.MaterialAlertDialogBuilder
import dagger.hilt.android.AndroidEntryPoint
@AndroidEntryPoint
class AboutActivity : BaseActivity<ActivityAboutBinding>() {
private val viewModel by lazy { ViewModelProvider(this)[AboutViewModel::class.java] }
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setSupportActionBar(binding.tbAAbout)
supportActionBar?.setDisplayHomeAsUpEnabled(true)
binding.tbAAbout.setNavigationOnClickListener { finish() }
launchWithLifecycle {
viewModel.eventFlow.collect { event ->
when (event) {
Event.HaveAvailableUpdateEvent -> {
MaterialAlertDialogBuilder(this@AboutActivity)
.setIcon(R.drawable.ic_release_alert)
.setTitle(R.string.update_available)
.setMessage(R.string.update_available_tip)
.setCancelable(false)
.setPositiveButton(R.string.go_to_download) { _, _ ->
openUrl("https://github.com/15dd/wenku8reader/releases")
}
.setNegativeButton(R.string.cancel) { _, _ -> }
.show()
binding.llAAboutUpdate.isClickable = true
}
Event.NoAvailableUpdateEvent -> {
MaterialAlertDialogBuilder(this@AboutActivity)
.setMessage(R.string.you_have_used_in_latest_version)
.setCancelable(false)
.setPositiveButton(R.string.ok) { _, _ -> }
.show()
binding.llAAboutUpdate.isClickable = true
}
else -> {}
}
}
}
binding.tvAAbout.text =
applicationContext.packageManager.getPackageInfo(packageName, 0).versionName
binding.llAAboutDisclaimers.setOnClickListener {
MaterialAlertDialogBuilder(this)
.setIcon(R.drawable.ic_contract)
.setTitle(R.string.disclaimers)
.setMessage(R.string.disclaimers_message)
.setPositiveButton(R.string.ok) { _, _ -> }
.show()
}
binding.llAAboutUpdate.setOnClickListener {
binding.llAAboutUpdate.isClickable = false
viewModel.checkUpdate()
}
binding.bAAboutGithub.setOnClickListener {
openUrl("https://github.com/15dd/wenku8reader")
}
binding.bAAboutTelegram.setOnClickListener {
openUrl("https://t.me/+JH2H3VpET7ozMTU9")
}
binding.llAAboutHelp.setOnClickListener {
openUrl("https://github.com/15dd/wenku8reader/wiki")
}
}
} | 1 | Kotlin | 12 | 400 | 402efc07ced528fc939d5d645e1f8a8f07636f40 | 3,403 | wenku8reader | MIT License |
library/src/main/java/app/moviebase/ktx/app/BundleExt.kt | MoviebaseApp | 255,294,951 | false | null | package app.moviebase.ktx.app
import android.os.Bundle
@Deprecated("use bundleOf from KTX directly")
inline fun bundle(block: Bundle.() -> Unit) = Bundle().apply(block)
| 0 | Kotlin | 0 | 1 | 2299eb5618e3351ff176a550cffbce0c5b172c79 | 172 | android-ktx | Apache License 2.0 |
bittrader-common/src/test/kotlin/org/kentunc/bittrader/common/infrastructure/webclient/http/connector/ClientHttpConnectorFactoryTest.kt | ken-tunc | 430,691,495 | false | null | package org.kentunc.bittrader.common.infrastructure.webclient.http.connector
import org.junit.jupiter.api.Assertions.assertDoesNotThrow
import org.junit.jupiter.api.Test
internal class ClientHttpConnectorFactoryTest {
private val target = ClientHttpConnectorFactory()
@Test
fun testCreate() {
assertDoesNotThrow {
target.create(1000, 3000)
}
}
}
| 2 | Kotlin | 0 | 0 | 757c83fd604e5758a5e67bbfd98b33c1d9cc1961 | 394 | bittrader | MIT License |
app/src/main/java/vn/loitp/a/cv/rv/recyclerTabLayout/years/RvTabYearsActivity.kt | tplloi | 126,578,283 | false | null | package vn.loitp.a.cv.rv.recyclerTabLayout.years
import android.content.Context
import android.content.Intent
import android.os.Bundle
import android.view.MenuItem
import com.loitp.annotation.IsFullScreen
import com.loitp.annotation.LogTag
import com.loitp.core.base.BaseActivityFont
import com.loitp.core.ext.tranIn
import kotlinx.android.synthetic.main.a_recycler_tab_layout.*
import vn.loitp.R
import vn.loitp.a.cv.rv.recyclerTabLayout.Demo
import java.util.* // ktlint-disable no-wildcard-imports
@LogTag("RvTabYearsActivity")
@IsFullScreen(false)
class RvTabYearsActivity : BaseActivityFont() {
override fun setLayoutResourceId(): Int {
return R.layout.a_recycler_tab_layout
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setupViews()
}
private fun setupViews() {
val keyDemo = intent.getStringExtra(KEY_DEMO)
if (keyDemo.isNullOrEmpty()) {
onBaseBackPressed()
return
}
val demo = Demo.valueOf(keyDemo)
toolbar.setTitle(demo.titleResId)
setSupportActionBar(toolbar)
supportActionBar?.setDisplayHomeAsUpEnabled(true)
val startYear = 1900
val endYear = 3000
val initialYear = Calendar.getInstance().get(Calendar.YEAR)
val items = ArrayList<String>()
for (i in startYear..endYear) {
items.add(i.toString())
}
val demoYearsPagerAdapter = YearsPagerAdapter()
demoYearsPagerAdapter.addAll(items)
viewPager.adapter = demoYearsPagerAdapter
viewPager.currentItem = initialYear - startYear
recyclerTabLayout.setUpWithViewPager(viewPager)
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
if (item.itemId == android.R.id.home) {
onBaseBackPressed()
return true
}
return super.onOptionsItemSelected(item)
}
companion object {
private const val KEY_DEMO = "demo"
fun startActivity(context: Context, demo: Demo) {
val intent = Intent(context, RvTabYearsActivity::class.java)
intent.putExtra(KEY_DEMO, demo.name)
context.startActivity(intent)
context.tranIn()
}
}
}
| 0 | Kotlin | 0 | 10 | 333bebaf3287b1633f35d29b8adaf25b19c1859f | 2,293 | base | Apache License 2.0 |
app/src/main/java/com/comic_con/museum/ar/experience/nav/BottomNavOnPageChangeListener.kt | Comic-Con-Museum | 153,692,659 | false | {"Kotlin": 71992} | package com.comic_con.museum.ar.experience.nav
import android.support.design.widget.BottomNavigationView
import android.support.v4.view.ViewPager
import android.view.MenuItem
class BottomNavOnPageChangeListener(
private val bottomNavBar: BottomNavigationView
): ViewPager.OnPageChangeListener {
private var prevMenuItem: MenuItem? = null
override fun onPageScrollStateChanged(p0: Int) { /* Intentionally blank */ }
override fun onPageScrolled(p0: Int, p1: Float, p2: Int) { /* Intentionally blank */ }
override fun onPageSelected(p0: Int) {
if (prevMenuItem != null) {
prevMenuItem?.isChecked = false
} else {
bottomNavBar.menu.getItem(0).isChecked = false
}
bottomNavBar.menu.getItem(p0).isChecked = true
prevMenuItem = bottomNavBar.menu.getItem(p0);
}
} | 18 | Kotlin | 1 | 8 | 6e5396fde31d57f5bcde87f608d1357c468c90d2 | 850 | ccm-android | Apache License 2.0 |
app/src/main/java/edu/gatech/ccg/aslrecorder/splash/TopicListAdapter.kt | sahirshahryar | 443,472,761 | false | null | /**
* TopicListAdapter.kt
* This file is part of ASLRecorder, licensed under the MIT license.
*
* Copyright (c) 2021 <NAME> <<EMAIL>>
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package edu.gatech.ccg.aslrecorder.splash
import android.content.Context
import android.content.Intent
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import androidx.recyclerview.widget.RecyclerView
import edu.gatech.ccg.aslrecorder.R
import edu.gatech.ccg.aslrecorder.recording.RecordingActivity
import edu.gatech.ccg.aslrecorder.recording.WORDS_PER_SESSION
const val DISABLE_RANDOM = false
const val RANDOM_SEED = 1L
/**
*
*/
class TopicListAdapter: RecyclerView.Adapter<TopicListAdapter.TopicListItem>() {
var UID: String = ""
class TopicListItem(itemView: View):
RecyclerView.ViewHolder(itemView) {
lateinit var wordList: ArrayList<String>
lateinit var title: String
lateinit var description: String
fun setData(wordList: ArrayList<String>,
title: String, description: String, UID: String) {
this.wordList = wordList
this.title = title
this.description = description
// Set labels
val titleText = itemView.findViewById<TextView>(R.id.cardTitle)
titleText.text = title
val descText = itemView.findViewById<TextView>(R.id.cardDescription)
descText.text = description
// When the user clicks on this card, start a recording session
// using the words in this list.
itemView.setOnClickListener {
val recordingActivityIntent = Intent(itemView.context,
RecordingActivity::class.java).apply {
putStringArrayListExtra("WORDS", wordList)
putExtra("UID", UID)
if (DISABLE_RANDOM) {
putExtra("SEED", RANDOM_SEED)
}
}
itemView.context.startActivity(recordingActivityIntent)
}
}
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): TopicListItem {
val view = LayoutInflater.from(parent.context)
.inflate(R.layout.splash_card, parent, false)
return TopicListItem(view)
}
override fun onBindViewHolder(holder: TopicListItem, position: Int) {
val words: ArrayList<String>
/**
* First item is a way to choose words across all categories
*/
if (position == 0) {
words = ArrayList()
for (topic in WordDefinitions.values()) {
val wordArray = holder.itemView.context.resources.getStringArray(topic.resourceId)
words.addAll(listOf(*wordArray))
}
holder.setData(words, "All words",
"$WORDS_PER_SESSION random words from any category", UID)
}
/**
* Remaining list items are for choosing words from specific categories
*/
else {
val topic = WordDefinitions.values()[position - 1]
val wordArray = holder.itemView.context.resources.getStringArray(topic.resourceId)
words = ArrayList(listOf(*wordArray))
holder.setData(words, topic.title, topic.desc, UID)
}
}
override fun getItemCount(): Int {
Log.d("TopicListAdapter", "Item count = ${WordDefinitions.values().size}")
return WordDefinitions.values().size + 1
}
override fun getItemViewType(position: Int): Int {
return R.layout.splash_card
}
}
| 0 | Kotlin | 1 | 0 | c2c4c7f159b44e1caf5169bd3477e7fe60cb58de | 4,743 | ASLRecorder | MIT License |
EvoMaster/core/src/main/kotlin/org/evomaster/core/output/OutputFormat.kt | BrotherKim | 397,139,860 | false | null | package org.evomaster.core.output
/**
* Specify in which format the output test cases should be written to
*/
enum class OutputFormat {
/**
* Use the format specified in the SUT driver.
*
* Note: this should be kept in sync with:
* org.evomaster.client.java.controller.api.dto.SutInfoDto.OutputFormat
* but DEFAULT
*/
DEFAULT,
JAVA_JUNIT_5,
JAVA_JUNIT_4,
KOTLIN_JUNIT_4,
KOTLIN_JUNIT_5,
JS_JEST
;
/*
TODO:
JAVA_TESTNG
KOTLIN_TESTNG
and in the future, also support other languages,
eg JavaScript
*/
fun isJava() = this.name.startsWith("java_", true)
fun isKotlin() = this.name.startsWith("kotlin_", true)
fun isJavaScript() = this.name.startsWith("js_", true)
fun isJavaOrKotlin() = isJava() || isKotlin()
fun isJUnit5() = this.name.endsWith("junit_5", true)
fun isJUnit4() = this.name.endsWith("junit_4", true)
fun isJUnit() = this.name.contains("_junit_", true)
} | 1 | null | 1 | 1 | a7a120fe7c3b63ae370e8a114f3cb71ef79c287e | 1,022 | ASE-Technical-2021-api-linkage-replication | MIT License |
app/src/main/java/me/luowl/wan/data/model/Architecture.kt | luowl123 | 200,819,385 | false | null | package me.luowl.wan.data.model
import java.io.Serializable
/**
*
* Created by luowl
* Date: 2019/7/23
* Desc:
*/
class Architecture :Serializable{
/**
"courseId": 13,
"id": 150,
"name": "开发环境",
"order": 1,
"parentChapterId": 0,
"userControlSetTop": false,
"visible": 1,
"children":[]
* */
var courseId = 0
var id = 0L
var name = ""
var order = 0
var parentChapterId = 0
var userControlSetTop = false
var visible = 1
var children: List<Architecture>? = null
fun getChildrenNames(): String {
if (children == null) return ""
return children!!.joinToString(separator = "\t",transform = {it.name})
}
} | 1 | null | 1 | 14 | 5902a485e680a08fa2a818c418df44f7a40bb269 | 703 | WanAndroid | Apache License 2.0 |
android/DartsScorecard/app/src/main/java/nl/entreco/dartsscorecard/di/service/ServiceScope.kt | Entreco | 110,022,468 | false | {"Markdown": 3, "Text": 3, "Ignore List": 10, "YAML": 2, "SVG": 35, "HTML": 1, "PHP": 1, "CSS": 1, "Gradle": 15, "Java Properties": 2, "Shell": 1, "Batchfile": 1, "Proguard": 7, "Kotlin": 637, "XML": 222, "JSON": 2, "Java": 2} | package nl.entreco.dartsscorecard.di.service
import javax.inject.Scope
/**
* Created by Entreco on 15/11/2017.
*/
@Scope
@Retention(AnnotationRetention.RUNTIME)
annotation class ServiceScope | 7 | null | 1 | 1 | a031a0eeadd0aa21cd587b5008364a16f890b264 | 195 | Darts-Scorecard | Apache License 2.0 |
android/DartsScorecard/app/src/main/java/nl/entreco/dartsscorecard/di/service/ServiceScope.kt | Entreco | 110,022,468 | false | {"Markdown": 3, "Text": 3, "Ignore List": 10, "YAML": 2, "SVG": 35, "HTML": 1, "PHP": 1, "CSS": 1, "Gradle": 15, "Java Properties": 2, "Shell": 1, "Batchfile": 1, "Proguard": 7, "Kotlin": 637, "XML": 222, "JSON": 2, "Java": 2} | package nl.entreco.dartsscorecard.di.service
import javax.inject.Scope
/**
* Created by Entreco on 15/11/2017.
*/
@Scope
@Retention(AnnotationRetention.RUNTIME)
annotation class ServiceScope | 7 | null | 1 | 1 | a031a0eeadd0aa21cd587b5008364a16f890b264 | 195 | Darts-Scorecard | Apache License 2.0 |
src/main/kotlin/io/unthrottled/doki/icon/IconLookup.kt | doki-theme | 126,478,304 | false | null | package io.unthrottled.doki.icon
import com.intellij.icons.AllIcons
import com.intellij.openapi.util.IconLoader
import com.intellij.util.ui.LafIconLookup
import io.unthrottled.doki.util.runSafelyWithResult
import javax.swing.Icon
// og class: com.intellij.util.ui.LafIconLookup
@Suppress("LongParameterList")
object IconLookup {
fun getIcon(
name: String,
selected: Boolean = false,
focused: Boolean = false,
enabled: Boolean = true,
editable: Boolean = false,
pressed: Boolean = false
): Icon {
return findIcon(
name,
selected = selected,
focused = focused,
enabled = enabled,
editable = editable,
pressed = pressed,
isThrowErrorIfNotFound = true
) ?: AllIcons.Actions.Stub
}
private fun findIcon(
name: String,
selected: Boolean = false,
focused: Boolean = false,
enabled: Boolean = true,
editable: Boolean = false,
pressed: Boolean = false,
isThrowErrorIfNotFound: Boolean = false
): Icon? {
var key = name
if (editable) key += "Editable"
if (selected) key += "Selected"
when {
pressed -> key += "Pressed"
focused -> key += "Focused"
!enabled -> key += "Disabled"
}
return runSafelyWithResult({
IconLoader.findIcon(
"/com/intellij/ide/ui/laf/icons/darcula/$key.svg",
LafIconLookup::class.java,
true,
isThrowErrorIfNotFound
)
}) {
attemptToGetLegacy(key, isThrowErrorIfNotFound)
}
}
private fun attemptToGetLegacy(key: String, isThrowErrorIfNotFound: Boolean): Icon? {
return try {
IconLoader.findLafIcon("darcula/$key", LafIconLookup::class.java, isThrowErrorIfNotFound)
} catch (e: Throwable) {
IconLoader.findLafIcon(
"/com/intellij/ide/ui/laf/icons/darcula/$key",
LafIconLookup::class.java,
isThrowErrorIfNotFound
)
}
}
}
| 9 | Kotlin | 22 | 369 | 5565f63a2488a72f023eae7f67dd63ea89a12bf8 | 1,906 | doki-theme-jetbrains | MIT License |
base/src/main/java/net/fitken/base/recyclerview/BasePagedListAdapter.kt | nmhung | 332,231,181 | false | null | package net.fitken.base.recyclerview
import android.view.View
import android.view.ViewGroup
import androidx.databinding.ViewDataBinding
import androidx.paging.PagedListAdapter
import androidx.recyclerview.widget.RecyclerView
import androidx.recyclerview.widget.RecyclerView.NO_POSITION
abstract class BasePagedListAdapter<VH : BasePagedListAdapter.BaseHolder<*, T>, T>(
comparator: BaseComparator<T>,
private var mOnItemClickListener: OnItemClickListener<T>? = null
) : PagedListAdapter<T, VH>(comparator) {
protected abstract fun getViewHolder(parent: ViewGroup, viewType: Int): VH?
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): VH {
val viewHolder = getViewHolder(parent, viewType)
viewHolder?.let { vh ->
vh.itemView.setOnClickListener {
val pos = vh.adapterPosition
if (pos != NO_POSITION && getItem(pos) != null) {
mOnItemClickListener?.onItemClick(it, pos, getItem(pos)!!)
}
}
}
return viewHolder!!
}
override fun onBindViewHolder(holder: VH, position: Int) {
getItem(position)?.let { holder.bindData(it) }
}
open class BaseHolder<out V : ViewDataBinding, in T>(val mViewDataBinding: V) :
RecyclerView.ViewHolder(mViewDataBinding.root) {
open fun bindData(data: T) {}
}
interface OnItemClickListener<in T> {
fun onItemClick(v: View, position: Int, data: T)
}
} | 1 | null | 1 | 1 | 43d3968b6e60288c44655c1f908edd906b4877ab | 1,508 | weather | Apache License 2.0 |
plugins/kotlin/idea/tests/testData/quickfix/supercalls/typeArgumentsRedundantInSuperQualifier.kt | ingokegel | 72,937,917 | false | null | // "Remove type arguments" "true"
interface Foo<T1, T2> {
fun f() {}
}
class Bar: Foo<Int, Boolean> {
fun g() {
super<Foo<Int, <caret>Boolean>>.f();
}
}
// FUS_QUICKFIX_NAME: org.jetbrains.kotlin.idea.quickfix.RemovePsiElementSimpleFix
// FUS_K2_QUICKFIX_NAME: org.jetbrains.kotlin.idea.quickfix.RemovePsiElementSimpleFix | 1 | null | 1 | 2 | b07eabd319ad5b591373d63c8f502761c2b2dfe8 | 342 | intellij-community | Apache License 2.0 |
app/src/main/java/ca/josephroque/bowlingcompanion/statistics/impl/overall/SpareConversionsStatistic.kt | autoreleasefool | 28,992,199 | false | null | package ca.josephroque.bowlingcompanion.statistics.impl.overall
import android.os.Parcel
import android.os.Parcelable
import ca.josephroque.bowlingcompanion.R
import ca.josephroque.bowlingcompanion.common.interfaces.parcelableCreator
import ca.josephroque.bowlingcompanion.games.lane.Deck
import ca.josephroque.bowlingcompanion.games.lane.arePinsCleared
import ca.josephroque.bowlingcompanion.games.lane.isAce
import ca.josephroque.bowlingcompanion.games.lane.isHeadPin
import ca.josephroque.bowlingcompanion.games.lane.isSplit
import ca.josephroque.bowlingcompanion.statistics.StatisticsCategory
import ca.josephroque.bowlingcompanion.statistics.impl.firstball.SecondBallStatistic
/**
* Copyright (C) 2018 <NAME>
*
* Percentage of possible spares which the user successfully spared.
*/
class SpareConversionsStatistic(numerator: Int = 0, denominator: Int = 0) : SecondBallStatistic(numerator, denominator) {
// MARK: Modifiers
/** @Override */
override fun isModifiedByFirstBall(firstBall: Deck, secondBall: Deck): Boolean {
// Don't add a spare chance if the first ball was a split / head pin / aces, unless the second shot was a spare
return !firstBall.arePinsCleared && ((!firstBall.isAce && !firstBall.isHeadPin && !firstBall.isSplit(countS2asS = true)) || secondBall.arePinsCleared)
}
/** @Override */
override fun isModifiedBySecondBall(deck: Deck) = deck.arePinsCleared
// MARK: Overrides
override val titleId = Id
override val id = Id.toLong()
override val category = StatisticsCategory.Overall
override val secondaryGraphDataLabelId = R.string.statistic_total_spare_chances
// MARK: Parcelable
companion object {
/** Creator, required by [Parcelable]. */
@Suppress("unused")
@JvmField val CREATOR = parcelableCreator(::SpareConversionsStatistic)
/** Unique ID for the statistic. */
const val Id = R.string.statistic_spare_conversion
}
/**
* Construct this statistic from a [Parcel].
*/
private constructor(p: Parcel): this(numerator = p.readInt(), denominator = p.readInt())
}
| 30 | null | 5 | 6 | be42ac42d6c842b3126a8841990e5f9c8c6af232 | 2,132 | bowling-companion | Apache License 2.0 |
commons/src/main/java/com/samagra/commons/models/surveydata/SurveyModel.kt | hardikm9850 | 687,311,848 | false | {"Java Properties": 8, "Markdown": 4, "Gradle": 14, "Shell": 3, "Batchfile": 3, "Text": 4, "Ignore List": 10, "Git Config": 1, "INI": 6, "Proguard": 8, "Kotlin": 231, "XML": 739, "JSON": 8, "robots.txt": 1, "HTML": 2, "CSS": 1, "JavaScript": 3, "Java": 1152, "YAML": 1, "GraphQL": 3, "XSLT": 6} | package com.samagra.commons.models.surveydata
import com.google.gson.annotations.SerializedName
data class SurveyModel(
@SerializedName("submission_timestamp") var submissionTimestamp: Long? = null,
@SerializedName("grade") var grade: Int? = null,
@SerializedName("actor_id") var actorId: Int? = null,
@SerializedName("subject_id") var subjectId: Int? = null,
@SerializedName("udise") var udise: Long? = null,
@SerializedName("app_version_code") var appVersionCode: Int? = null,
@SerializedName("questions") var questions: ArrayList<SurveyResultData> = arrayListOf()
) | 1 | null | 1 | 1 | 0dcf0b044da0ac6b58960ac8cce2f2db5910961c | 598 | Nipun-Lakshya-App | MIT License |
idea/idea-completion/testData/handlers/charFilter/Eq1.kt | JakeWharton | 99,388,807 | true | null | var vvv = 1
fun foo() {
<caret>
}
// ELEMENT: vvv
// CHAR: =
| 0 | Kotlin | 28 | 83 | 4383335168338df9bbbe2a63cb213a68d0858104 | 67 | kotlin | Apache License 2.0 |
analysis/low-level-api-fir/src/org/jetbrains/kotlin/analysis/low/level/api/fir/project/structure/CompositeKotlinPackageProvider.kt | JetBrains | 3,432,266 | false | null | /*
* Copyright 2010-2023 JetBrains s.r.o. and Kotlin Programming Language contributors.
* Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file.
*/
package org.jetbrains.kotlin.analysis.low.level.api.fir.project.structure
import org.jetbrains.kotlin.analysis.providers.KotlinPackageProvider
import org.jetbrains.kotlin.name.FqName
import org.jetbrains.kotlin.name.Name
import org.jetbrains.kotlin.platform.TargetPlatform
class CompositeKotlinPackageProvider
private constructor(
private val providers: List<KotlinPackageProvider>
) : KotlinPackageProvider() {
override fun doesPackageExist(packageFqName: FqName, platform: TargetPlatform): Boolean {
return providers.any { it.doesPackageExist(packageFqName, platform) }
}
override fun doesKotlinOnlyPackageExist(packageFqName: FqName): Boolean {
return providers.any { it.doesKotlinOnlyPackageExist(packageFqName) }
}
override fun doesPlatformSpecificPackageExist(packageFqName: FqName, platform: TargetPlatform): Boolean {
return providers.any { it.doesPlatformSpecificPackageExist(packageFqName, platform) }
}
override fun getSubPackageFqNames(packageFqName: FqName, platform: TargetPlatform, nameFilter: (Name) -> Boolean): Set<Name> {
return providers.flatMapTo(mutableSetOf()) { it.getSubPackageFqNames(packageFqName, platform, nameFilter) }
}
override fun getKotlinOnlySubPackagesFqNames(packageFqName: FqName, nameFilter: (Name) -> Boolean): Set<Name> {
return providers.flatMapTo(mutableSetOf()) { it.getKotlinOnlySubPackagesFqNames(packageFqName, nameFilter) }
}
override fun getPlatformSpecificSubPackagesFqNames(
packageFqName: FqName,
platform: TargetPlatform,
nameFilter: (Name) -> Boolean
): Set<Name> {
return providers.flatMapTo(mutableSetOf()) { it.getPlatformSpecificSubPackagesFqNames(packageFqName, platform, nameFilter) }
}
companion object {
fun create(providers: List<KotlinPackageProvider>): KotlinPackageProvider {
return when (providers.size) {
0 -> EmptyKotlinPackageProvider
1 -> providers.single()
else -> CompositeKotlinPackageProvider(providers)
}
}
}
}
| 155 | Kotlin | 5608 | 45,423 | 2db8f31966862388df4eba2702b2f92487e1d401 | 2,330 | kotlin | Apache License 2.0 |
Week1/flamion/ModifiedFizzBuzz.kt | lucastarche | 342,951,751 | false | {"Text": 1, "Markdown": 5, "C++": 2, "Python": 2, "Java": 1, "Kotlin": 1, "Go": 1, "Lua": 1, "XML": 1, "Ignore List": 1, "C#": 1, "EditorConfig": 1, "JavaScript": 1} | import java.util.*
fun main() {
val scanner = Scanner(System.`in`)
val n = scanner.nextInt()
val m = scanner.nextInt()
val replaceLookup: MutableMap<Int, String> = java.util.HashMap()
for (i in 0 until m) {
replaceLookup[scanner.nextInt()] = scanner.next()
}
val builder = StringBuilder()
for (i in 1..n) {
for (j in replaceLookup.keys) {
if (i % j == 0) {
builder.append(replaceLookup[j])
}
}
println(if (builder.isEmpty()) i else builder)
builder.setLength(0)
}
}
| 1 | null | 1 | 1 | e79f8d63ae15575f11629123b6742c4135845c13 | 588 | potw | MIT License |
idea/testData/addImport/ImportClassSimple.kt | staltz | 73,301,428 | true | {"Java": 20614121, "Kotlin": 17984917, "JavaScript": 179664, "HTML": 46362, "Protocol Buffer": 44176, "Lex": 17716, "Groovy": 10124, "ANTLR": 9689, "CSS": 9358, "IDL": 5410, "Shell": 4704, "Batchfile": 3703} | // IMPORT: java.util.ArrayList
package p
fun foo() {}
| 0 | Java | 0 | 1 | 80074c71fa925a1c7173e3fffeea4cdc5872460f | 55 | kotlin | Apache License 2.0 |
idea/testData/addImport/ImportClassSimple.kt | staltz | 73,301,428 | true | {"Java": 20614121, "Kotlin": 17984917, "JavaScript": 179664, "HTML": 46362, "Protocol Buffer": 44176, "Lex": 17716, "Groovy": 10124, "ANTLR": 9689, "CSS": 9358, "IDL": 5410, "Shell": 4704, "Batchfile": 3703} | // IMPORT: java.util.ArrayList
package p
fun foo() {}
| 0 | Java | 0 | 1 | 80074c71fa925a1c7173e3fffeea4cdc5872460f | 55 | kotlin | Apache License 2.0 |
src/larx/ktdemos/KotlinLambdasDemo.kt | Shadowrs | 510,342,840 | false | {"Java": 7257, "Kotlin": 3135} | package larx.ktdemos
import larx.engine.ThreadSchedulerDemo
import larx.engine.ThreadSchedulerDemo.Script
import larx.Misc
fun main() {
System.out.println("[App " + Misc.timestamp() + "] begin")
ThreadSchedulerDemo.mainAppLoop()
KotlinLambdasDemo.test() // kick off a kotlin written task
}
/**
* @author <NAME> (<EMAIL>)
*/
object KotlinLambdasDemo {
// p.s test() method body hotswap will work, but standard Java does not support hotswap of Anonymous classes (lambda expressions: code within the run({}) block)
fun test() {
ThreadSchedulerDemo.run {
it.printf("kotlin demo 1 start")
it.wait(2)
it.printf("wow lol")
}
}
// method with context receiver so you can be even more lazy
fun onInteraction(task: Script.() -> Unit) {
ThreadSchedulerDemo.run(task)
}
} | 1 | null | 1 | 1 | e5b6d26996740387041fef6fedbba6f5643f43a7 | 863 | loom-jdk-demo | MIT License |
Mobile/Android/app/src/main/java/com/razvantmz/onemove/ui/signIn/SignInViewModel.kt | razvantmzz | 315,075,478 | false | {"Text": 1, "Markdown": 1, "Gradle": 3, "Java Properties": 2, "Shell": 1, "Ignore List": 2, "Batchfile": 1, "Proguard": 1, "JSON": 1, "Kotlin": 125, "XML": 114, "Java": 1} | package com.razvantmz.onemove.ui.signIn
import androidx.lifecycle.MutableLiveData
import com.razvantmz.onemove.R
import com.razvantmz.onemove.core.responseHandlers.ApiCallback
import com.razvantmz.onemove.core.responseHandlers.ResponseCode
import com.razvantmz.onemove.core.validations.IValidationProvider
import com.razvantmz.onemove.core.validations.commands.EmailCommand
import com.razvantmz.onemove.core.validations.commands.MinMaxLengthCommand
import com.razvantmz.onemove.models.UserCore
import com.razvantmz.onemove.models.UserDataModel
import com.razvantmz.onemove.repository.AccountRepository
import com.razvantmz.onemove.ui.base.BaseViewModel
import kotlinx.android.synthetic.main.activity_register.view.*
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.Job
import kotlinx.coroutines.launch
class SignInViewModel : BaseViewModel() {
private var email: MutableLiveData<String> = MutableLiveData()
private var password: MutableLiveData<String> = MutableLiveData()
private val signInJob = Job()
private val signInContext = CoroutineScope(Dispatchers.IO + signInJob)
fun setEmail(value:String)
{
email.value = value
}
fun setPassword(value:String)
{
password.value = value
}
override fun onValidationFieldsAdded(validationFields: List<IValidationProvider>) {
validationFields[0].validationCommands.add(EmailCommand(R.string.email))
validationFields[1].validationCommands.add(MinMaxLengthCommand(R.string.email, 3, 20))
}
fun signIn()
{
signInContext.launch {
isUpdating.postValue(true)
AccountRepository.signIn(email.value!!, password.value!!, object : ApiCallback<UserDataModel?>{
override fun onSuccess(responseCode: ResponseCode, data: UserDataModel?) {
isUpdating.postValue(false)
onSuccessCode.postValue(responseCode)
UserCore.Instance.user = data
}
override fun onFailure(responseCode: ResponseCode) {
isUpdating.postValue(false)
onErrorCode.postValue(responseCode)
}
})
}
}
} | 1 | null | 1 | 1 | 05bde5b64e54f6091dedcdd2da7093c3bfa4f522 | 2,262 | gym-app | MIT License |
domain/src/main/java/io/hasegawa/stonesafio/domain/listing/listing_models.kt | AllanHasegawa | 103,752,410 | true | {"Kotlin": 137567, "Java": 3477} | package io.hasegawa.stonesafio.domain.listing
import java.io.Serializable
data class ListingItemModel(
val id: String,
val title: String,
val price: Long,
val zipcode: String,
val seller: String,
val thumbnailHd: String,
val date: String) : Serializable | 0 | Kotlin | 0 | 2 | e3ec1735ae78e303765a60497ae088510d923089 | 312 | desafio-mobile | MIT License |
program/check-upper-case/CheckUpperCase.kt | isyuricunha | 632,079,464 | false | null | import kotlin.math.PI
import java.util.Scanner
fun main(args: Array<String>) {
val scanner = Scanner(System.`in`)
//Input Character
print("Enter a character : ")
val char = scanner.next()[0]
val upperCase = char.isUpperCase()
if(upperCase){
println("Upper Case")
} else{
println("Not Upper Case")
}
}
| 824 | null | 503 | 6 | c3949d3d4bae20112e007af14d4657cc96142d69 | 334 | program | MIT License |
idea/testData/quickfix/variables/unusedVariableWithConstantInitializer.kt | JakeWharton | 99,388,807 | false | null | // "Remove variable 'flag'" "true"
fun foo() {
val <caret>flag = true
} | 1 | null | 28 | 83 | 4383335168338df9bbbe2a63cb213a68d0858104 | 76 | kotlin | Apache License 2.0 |
wire-tests/src/jvmKotlinInteropTest/proto-kotlin/com/squareup/wire/protos/custom_options/ServiceWithOptionsClient.kt | square | 12,274,147 | false | null | // Code generated by Wire protocol buffer compiler, do not edit.
// Source: squareup.protos.custom_options.ServiceWithOptions in custom_options.proto
@file:Suppress("DEPRECATION")
package com.squareup.wire.protos.custom_options
import com.squareup.wire.GrpcCall
import com.squareup.wire.Service
import kotlin.Suppress
@ServiceOptionOneOption(456)
public interface ServiceWithOptionsClient : Service {
@MethodOptionOneOption(789)
public fun MethodWithOptions(): GrpcCall<FooBar, FooBar>
}
| 145 | null | 569 | 4,198 | 3354cdac025b64d2b5b0fac7939c50a3896c6ad8 | 495 | wire | Apache License 2.0 |
src/main/kotlin/com/sk/set0/49. Group Anagrams.kt | sandeep549 | 262,513,267 | false | null | package com.sk.set0
class Solution49 {
fun groupAnagrams2(strs: Array<String>): List<List<String>> {
if (strs.isEmpty()) return ArrayList()
val map: MutableMap<String, MutableList<String>> = HashMap()
for (s in strs) {
val ca = CharArray(26)
for (c in s.toCharArray()) ca[c - 'a']++
val keyStr = String(ca)
if (!map.containsKey(keyStr)) {
map[keyStr] = ArrayList()
}
map[keyStr]!!.add(s)
}
return map.values.toList()
}
}
| 1 | null | 1 | 1 | 67688ec01551e9981f4be07edc11e0ee7c0fab4c | 559 | leetcode-answers-kotlin | Apache License 2.0 |
sendsoknad-innsending/src/main/kotlin/no/nav/sbl/soknadinnsending/fillager/FilestorageService.kt | navikt | 372,400,223 | false | {"YAML": 10, "Maven POM": 11, "XML": 60, "Dockerfile": 1, "Text": 1, "Ignore List": 1, "Markdown": 11, "OASv3-yaml": 3, "Batchfile": 1, "Java": 475, "INI": 12, "Java Properties": 4, "JSON": 8, "Handlebars": 187, "HTML": 2, "CSS": 1, "EditorConfig": 1, "Kotlin": 21, "SQL": 36} | package no.nav.sbl.soknadinnsending.fillager
import no.nav.sbl.soknadinnsending.fillager.dto.FilElementDto
import no.nav.soknad.arkivering.soknadsfillager.api.FilesApi
import no.nav.soknad.arkivering.soknadsfillager.model.FileData
import org.slf4j.LoggerFactory
import org.springframework.stereotype.Service
@Service
class FilestorageService(private val filesClient: FilesApi) : Filestorage {
private val logger = LoggerFactory.getLogger(javaClass)
override fun store(innsendingId: String, files: List<FilElementDto>) {
logger.info("$innsendingId: Storing the following files in Soknadsfillager: ${files.map { it.id + ":" + it.content?.size}}")
val filedata = files.map { FileData(it.id, it.content, it.createdAt) }
filesClient.addFiles(filedata, innsendingId)
}
override fun getFileMetadata(innsendingId: String, ids: List<String>): List<FileData> {
if (ids.isNotEmpty()) {
logger.info("$innsendingId: Getting metadata for the following files from Soknadsfillager: $ids")
return filesClient.findFilesByIds(ids, true, innsendingId)
}
return emptyList()
}
override fun getFiles(innsendingId: String, ids: List<String>): List<FilElementDto> {
if (ids.isNotEmpty()) {
logger.info("$innsendingId: Getting the following files from Soknadsfillager: $ids")
return filesClient.findFilesByIds(ids, false, innsendingId)
.map { FilElementDto(it.id, it.content, it.createdAt) }
}
return emptyList()
}
override fun delete(innsendingId: String, ids: List<String>) {
logger.info("$innsendingId: Deleting the following files from Soknadsfillager: $ids")
filesClient.deleteFiles(ids, innsendingId)
}
}
| 3 | Java | 1 | 0 | aee5be2adc6f26d866f55e2664117957780feeb3 | 1,642 | sendsoknad-boot | MIT License |
src/test/kotlin/com/esentri/wrabbitmq/TestDomain.kt | esentri | 144,853,048 | false | null | package com.esentri.wrabbitmq
object TestDomain {
object ListenerTopic1: WrabbitTopic("TestTopic-1") {
val StringEvent = WrabbitEvent<String>(this, "TT1-TE-1")
val TestObjectObjectEvent = WrabbitEvent<TestObjectObject>(this, "TT1-TE-2")
}
object ReplierTopic1: WrabbitTopic("TestTopic-2") {
val StringToInt = WrabbitEventWithReply<String, Int>(this, "TT2-TE1")
val TestObjectObjectToString = WrabbitEventWithReply<TestObjectObject, String>(this, "TT2-TE2")
val TestObjectObjectToTestObjectNumberText = WrabbitEventWithReply<TestObjectObject, TestObjectNumberText>(this, "TT2-TE3")
}
}
| 3 | Kotlin | 1 | 2 | 16b76b5fcf61af1c1984150bce53993b8a5563ef | 629 | wrabbit-mq | The Unlicense |
app/src/main/java/com/example/weatherapp/composables/NoLocationScreen.kt | MikkoPasanen | 843,533,277 | false | {"Kotlin": 103134} | package com.example.weatherapp.composables
import androidx.compose.foundation.Image
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.width
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import com.example.weatherapp.R
/**
* Composable function for displaying the error screen when GPS access is not granted or was denied.
*/
@Composable
fun NoLocationScreen() {
Column(
verticalArrangement = Arrangement.Center,
horizontalAlignment = Alignment.CenterHorizontally
) {
Text("GPS access is not granted", fontSize = 20.sp, fontWeight = FontWeight.Bold, modifier = Modifier.padding(top = 200.dp))
Text("or was denied", fontSize = 20.sp, fontWeight = FontWeight.Bold)
Image(
painter = painterResource(id = R.drawable.no_location),
contentDescription = null,
modifier = Modifier.width(150.dp).fillMaxSize().padding(bottom = 250.dp)
)
}
} | 0 | Kotlin | 0 | 0 | f9eaab4ff96a492273a115c391a90c16536cb9ec | 1,404 | android-weather-app | MIT License |
geary-papermc-core/src/main/kotlin/com/mineinabyss/geary/papermc/GearyPaperConfig.kt | MineInAbyss | 592,086,123 | false | null | package com.mineinabyss.geary.papermc
import co.touchlab.kermit.Severity
import com.charleskorn.kaml.YamlComment
import kotlinx.serialization.Serializable
@Serializable
class GearyPaperConfig(
val debug: Boolean = false,
@YamlComment("Convert bukkit entities to and from geary, for instance to store and persist components on a player.")
val trackEntities: Boolean = true,
@YamlComment("Convert items to and from geary. Depends on entity tracking.")
val trackItems: Boolean = true,
@YamlComment("If an item has no prefabs encoded, try to find its prefab by matching custom model data.")
val migrateItemCustomModelDataToPrefab: Boolean = true,
@YamlComment("Convert blocks to and from geary.")
val trackBlocks: Boolean = true,
val logLevel: Severity = Severity.Warn,
)
| 0 | Kotlin | 0 | 1 | afb0722015f1d6206b89cc09e210814361decd47 | 810 | geary-papermc | MIT License |
geary-papermc-core/src/main/kotlin/com/mineinabyss/geary/papermc/GearyPaperConfig.kt | MineInAbyss | 592,086,123 | false | null | package com.mineinabyss.geary.papermc
import co.touchlab.kermit.Severity
import com.charleskorn.kaml.YamlComment
import kotlinx.serialization.Serializable
@Serializable
class GearyPaperConfig(
val debug: Boolean = false,
@YamlComment("Convert bukkit entities to and from geary, for instance to store and persist components on a player.")
val trackEntities: Boolean = true,
@YamlComment("Convert items to and from geary. Depends on entity tracking.")
val trackItems: Boolean = true,
@YamlComment("If an item has no prefabs encoded, try to find its prefab by matching custom model data.")
val migrateItemCustomModelDataToPrefab: Boolean = true,
@YamlComment("Convert blocks to and from geary.")
val trackBlocks: Boolean = true,
val logLevel: Severity = Severity.Warn,
)
| 0 | Kotlin | 0 | 1 | afb0722015f1d6206b89cc09e210814361decd47 | 810 | geary-papermc | MIT License |
kt/godot-library/src/main/kotlin/godot/gen/godot/TabContainer.kt | utopia-rise | 289,462,532 | false | null | // THIS FILE IS GENERATED! DO NOT EDIT IT MANUALLY!
@file:Suppress("PackageDirectoryMismatch", "unused", "FunctionName", "RedundantModalityModifier",
"UNCHECKED_CAST", "JoinDeclarationAndAssignment", "USELESS_CAST",
"RemoveRedundantQualifierName", "NOTHING_TO_INLINE", "NON_FINAL_MEMBER_IN_OBJECT",
"RedundantVisibilityModifier", "RedundantUnitReturnType", "MemberVisibilityCanBePrivate")
package godot
import godot.`annotation`.GodotBaseType
import godot.core.VariantType.BOOL
import godot.core.VariantType.JVM_INT
import godot.core.VariantType.LONG
import godot.core.VariantType.NIL
import godot.core.VariantType.OBJECT
import godot.core.VariantType.STRING
import godot.core.VariantType.VECTOR2
import godot.core.Vector2
import godot.core.memory.TransferContext
import godot.signals.Signal0
import godot.signals.Signal1
import godot.signals.signal
import kotlin.Boolean
import kotlin.Int
import kotlin.Long
import kotlin.String
import kotlin.Suppress
import kotlin.Unit
/**
* Tabbed container.
*
* Tutorials:
* [$DOCS_URL/tutorials/ui/gui_containers.html]($DOCS_URL/tutorials/ui/gui_containers.html)
*
* Arranges [godot.Control] children into a tabbed view, creating a tab for each one. The active tab's corresponding [godot.Control] has its `visible` property set to `true`, and all other children's to `false`.
*
* Ignores non-[godot.Control] children.
*
* **Note:** The drawing of the clickable tabs themselves is handled by this node. Adding [godot.TabBar]s as children is not needed.
*/
@GodotBaseType
public open class TabContainer : Container() {
/**
* Emitted when switching to another tab.
*/
public val tabChanged: Signal1<Long> by signal("tab")
/**
* Emitted when a tab is selected, even if it is the current tab.
*/
public val tabSelected: Signal1<Long> by signal("tab")
/**
* Emitted when the user clicks on the button icon on this tab.
*/
public val tabButtonPressed: Signal1<Long> by signal("tab")
/**
* Emitted when the [godot.TabContainer]'s [godot.Popup] button is clicked. See [setPopup] for details.
*/
public val prePopupPressed: Signal0 by signal()
/**
* Sets the position at which tabs will be placed. See [enum TabBar.AlignmentMode] for details.
*/
public var tabAlignment: TabBar.AlignmentMode
get() {
TransferContext.writeArguments()
TransferContext.callMethod(rawPtr, ENGINEMETHOD_ENGINECLASS_TABCONTAINER_GET_TAB_ALIGNMENT,
LONG)
return TabBar.AlignmentMode.values()[TransferContext.readReturnValue(JVM_INT) as Int]
}
set(`value`) {
TransferContext.writeArguments(LONG to value)
TransferContext.callMethod(rawPtr, ENGINEMETHOD_ENGINECLASS_TABCONTAINER_SET_TAB_ALIGNMENT,
NIL)
}
/**
* The current tab index. When set, this index's [godot.Control] node's `visible` property is set to `true` and all others are set to `false`.
*/
public var currentTab: Long
get() {
TransferContext.writeArguments()
TransferContext.callMethod(rawPtr, ENGINEMETHOD_ENGINECLASS_TABCONTAINER_GET_CURRENT_TAB,
LONG)
return TransferContext.readReturnValue(LONG, false) as Long
}
set(`value`) {
TransferContext.writeArguments(LONG to value)
TransferContext.callMethod(rawPtr, ENGINEMETHOD_ENGINECLASS_TABCONTAINER_SET_CURRENT_TAB, NIL)
}
/**
* If `true`, tabs overflowing this node's width will be hidden, displaying two navigation buttons instead. Otherwise, this node's minimum size is updated so that all tabs are visible.
*/
public var clipTabs: Boolean
get() {
TransferContext.writeArguments()
TransferContext.callMethod(rawPtr, ENGINEMETHOD_ENGINECLASS_TABCONTAINER_GET_CLIP_TABS, BOOL)
return TransferContext.readReturnValue(BOOL, false) as Boolean
}
set(`value`) {
TransferContext.writeArguments(BOOL to value)
TransferContext.callMethod(rawPtr, ENGINEMETHOD_ENGINECLASS_TABCONTAINER_SET_CLIP_TABS, NIL)
}
/**
* If `true`, tabs are visible. If `false`, tabs' content and titles are hidden.
*/
public var tabsVisible: Boolean
get() {
TransferContext.writeArguments()
TransferContext.callMethod(rawPtr, ENGINEMETHOD_ENGINECLASS_TABCONTAINER_ARE_TABS_VISIBLE,
BOOL)
return TransferContext.readReturnValue(BOOL, false) as Boolean
}
set(`value`) {
TransferContext.writeArguments(BOOL to value)
TransferContext.callMethod(rawPtr, ENGINEMETHOD_ENGINECLASS_TABCONTAINER_SET_TABS_VISIBLE,
NIL)
}
/**
* If `true`, all tabs are drawn in front of the panel. If `false`, inactive tabs are drawn behind the panel.
*/
public var allTabsInFront: Boolean
get() {
TransferContext.writeArguments()
TransferContext.callMethod(rawPtr, ENGINEMETHOD_ENGINECLASS_TABCONTAINER_IS_ALL_TABS_IN_FRONT,
BOOL)
return TransferContext.readReturnValue(BOOL, false) as Boolean
}
set(`value`) {
TransferContext.writeArguments(BOOL to value)
TransferContext.callMethod(rawPtr,
ENGINEMETHOD_ENGINECLASS_TABCONTAINER_SET_ALL_TABS_IN_FRONT, NIL)
}
/**
* If `true`, tabs can be rearranged with mouse drag.
*/
public var dragToRearrangeEnabled: Boolean
get() {
TransferContext.writeArguments()
TransferContext.callMethod(rawPtr,
ENGINEMETHOD_ENGINECLASS_TABCONTAINER_GET_DRAG_TO_REARRANGE_ENABLED, BOOL)
return TransferContext.readReturnValue(BOOL, false) as Boolean
}
set(`value`) {
TransferContext.writeArguments(BOOL to value)
TransferContext.callMethod(rawPtr,
ENGINEMETHOD_ENGINECLASS_TABCONTAINER_SET_DRAG_TO_REARRANGE_ENABLED, NIL)
}
/**
* [godot.TabContainer]s with the same rearrange group ID will allow dragging the tabs between them. Enable drag with [dragToRearrangeEnabled].
*
* Setting this to `-1` will disable rearranging between [godot.TabContainer]s.
*/
public var tabsRearrangeGroup: Long
get() {
TransferContext.writeArguments()
TransferContext.callMethod(rawPtr,
ENGINEMETHOD_ENGINECLASS_TABCONTAINER_GET_TABS_REARRANGE_GROUP, LONG)
return TransferContext.readReturnValue(LONG, false) as Long
}
set(`value`) {
TransferContext.writeArguments(LONG to value)
TransferContext.callMethod(rawPtr,
ENGINEMETHOD_ENGINECLASS_TABCONTAINER_SET_TABS_REARRANGE_GROUP, NIL)
}
/**
* If `true`, children [godot.Control] nodes that are hidden have their minimum size take into account in the total, instead of only the currently visible one.
*/
public var useHiddenTabsForMinSize: Boolean
get() {
TransferContext.writeArguments()
TransferContext.callMethod(rawPtr,
ENGINEMETHOD_ENGINECLASS_TABCONTAINER_GET_USE_HIDDEN_TABS_FOR_MIN_SIZE, BOOL)
return TransferContext.readReturnValue(BOOL, false) as Boolean
}
set(`value`) {
TransferContext.writeArguments(BOOL to value)
TransferContext.callMethod(rawPtr,
ENGINEMETHOD_ENGINECLASS_TABCONTAINER_SET_USE_HIDDEN_TABS_FOR_MIN_SIZE, NIL)
}
public override fun new(scriptIndex: Int): Boolean {
callConstructor(ENGINECLASS_TABCONTAINER, scriptIndex)
return true
}
/**
* Returns the number of tabs.
*/
public fun getTabCount(): Long {
TransferContext.writeArguments()
TransferContext.callMethod(rawPtr, ENGINEMETHOD_ENGINECLASS_TABCONTAINER_GET_TAB_COUNT, LONG)
return TransferContext.readReturnValue(LONG, false) as Long
}
/**
* Returns the previously active tab index.
*/
public fun getPreviousTab(): Long {
TransferContext.writeArguments()
TransferContext.callMethod(rawPtr, ENGINEMETHOD_ENGINECLASS_TABCONTAINER_GET_PREVIOUS_TAB, LONG)
return TransferContext.readReturnValue(LONG, false) as Long
}
/**
* Returns the child [godot.Control] node located at the active tab index.
*/
public fun getCurrentTabControl(): Control? {
TransferContext.writeArguments()
TransferContext.callMethod(rawPtr,
ENGINEMETHOD_ENGINECLASS_TABCONTAINER_GET_CURRENT_TAB_CONTROL, OBJECT)
return TransferContext.readReturnValue(OBJECT, true) as Control?
}
/**
* Returns the [godot.Control] node from the tab at index [tabIdx].
*/
public fun getTabControl(tabIdx: Long): Control? {
TransferContext.writeArguments(LONG to tabIdx)
TransferContext.callMethod(rawPtr, ENGINEMETHOD_ENGINECLASS_TABCONTAINER_GET_TAB_CONTROL,
OBJECT)
return TransferContext.readReturnValue(OBJECT, true) as Control?
}
/**
* Sets a custom title for the tab at index [tabIdx] (tab titles default to the name of the indexed child node). Set it back to the child's name to make the tab default to it again.
*/
public fun setTabTitle(tabIdx: Long, title: String): Unit {
TransferContext.writeArguments(LONG to tabIdx, STRING to title)
TransferContext.callMethod(rawPtr, ENGINEMETHOD_ENGINECLASS_TABCONTAINER_SET_TAB_TITLE, NIL)
}
/**
* Returns the title of the tab at index [tabIdx]. Tab titles default to the name of the indexed child node, but this can be overridden with [setTabTitle].
*/
public fun getTabTitle(tabIdx: Long): String {
TransferContext.writeArguments(LONG to tabIdx)
TransferContext.callMethod(rawPtr, ENGINEMETHOD_ENGINECLASS_TABCONTAINER_GET_TAB_TITLE, STRING)
return TransferContext.readReturnValue(STRING, false) as String
}
/**
* Sets an icon for the tab at index [tabIdx].
*/
public fun setTabIcon(tabIdx: Long, icon: Texture2D): Unit {
TransferContext.writeArguments(LONG to tabIdx, OBJECT to icon)
TransferContext.callMethod(rawPtr, ENGINEMETHOD_ENGINECLASS_TABCONTAINER_SET_TAB_ICON, NIL)
}
/**
* Returns the [godot.Texture2D] for the tab at index [tabIdx] or `null` if the tab has no [godot.Texture2D].
*/
public fun getTabIcon(tabIdx: Long): Texture2D? {
TransferContext.writeArguments(LONG to tabIdx)
TransferContext.callMethod(rawPtr, ENGINEMETHOD_ENGINECLASS_TABCONTAINER_GET_TAB_ICON, OBJECT)
return TransferContext.readReturnValue(OBJECT, true) as Texture2D?
}
/**
* If [disabled] is `true`, disables the tab at index [tabIdx], making it non-interactable.
*/
public fun setTabDisabled(tabIdx: Long, disabled: Boolean): Unit {
TransferContext.writeArguments(LONG to tabIdx, BOOL to disabled)
TransferContext.callMethod(rawPtr, ENGINEMETHOD_ENGINECLASS_TABCONTAINER_SET_TAB_DISABLED, NIL)
}
/**
* Returns `true` if the tab at index [tabIdx] is disabled.
*/
public fun isTabDisabled(tabIdx: Long): Boolean {
TransferContext.writeArguments(LONG to tabIdx)
TransferContext.callMethod(rawPtr, ENGINEMETHOD_ENGINECLASS_TABCONTAINER_IS_TAB_DISABLED, BOOL)
return TransferContext.readReturnValue(BOOL, false) as Boolean
}
/**
* If [hidden] is `true`, hides the tab at index [tabIdx], making it disappear from the tab area.
*/
public fun setTabHidden(tabIdx: Long, hidden: Boolean): Unit {
TransferContext.writeArguments(LONG to tabIdx, BOOL to hidden)
TransferContext.callMethod(rawPtr, ENGINEMETHOD_ENGINECLASS_TABCONTAINER_SET_TAB_HIDDEN, NIL)
}
/**
* Returns `true` if the tab at index [tabIdx] is hidden.
*/
public fun isTabHidden(tabIdx: Long): Boolean {
TransferContext.writeArguments(LONG to tabIdx)
TransferContext.callMethod(rawPtr, ENGINEMETHOD_ENGINECLASS_TABCONTAINER_IS_TAB_HIDDEN, BOOL)
return TransferContext.readReturnValue(BOOL, false) as Boolean
}
/**
* Sets the button icon from the tab at index [tabIdx].
*/
public fun setTabButtonIcon(tabIdx: Long, icon: Texture2D): Unit {
TransferContext.writeArguments(LONG to tabIdx, OBJECT to icon)
TransferContext.callMethod(rawPtr, ENGINEMETHOD_ENGINECLASS_TABCONTAINER_SET_TAB_BUTTON_ICON,
NIL)
}
/**
* Returns the button icon from the tab at index [tabIdx].
*/
public fun getTabButtonIcon(tabIdx: Long): Texture2D? {
TransferContext.writeArguments(LONG to tabIdx)
TransferContext.callMethod(rawPtr, ENGINEMETHOD_ENGINECLASS_TABCONTAINER_GET_TAB_BUTTON_ICON,
OBJECT)
return TransferContext.readReturnValue(OBJECT, true) as Texture2D?
}
/**
* Returns the index of the tab at local coordinates [point]. Returns `-1` if the point is outside the control boundaries or if there's no tab at the queried position.
*/
public fun getTabIdxAtPoint(point: Vector2): Long {
TransferContext.writeArguments(VECTOR2 to point)
TransferContext.callMethod(rawPtr, ENGINEMETHOD_ENGINECLASS_TABCONTAINER_GET_TAB_IDX_AT_POINT,
LONG)
return TransferContext.readReturnValue(LONG, false) as Long
}
/**
* Returns the index of the tab tied to the given [control]. The control must be a child of the [godot.TabContainer].
*/
public fun getTabIdxFromControl(control: Control): Long {
TransferContext.writeArguments(OBJECT to control)
TransferContext.callMethod(rawPtr,
ENGINEMETHOD_ENGINECLASS_TABCONTAINER_GET_TAB_IDX_FROM_CONTROL, LONG)
return TransferContext.readReturnValue(LONG, false) as Long
}
/**
* If set on a [godot.Popup] node instance, a popup menu icon appears in the top-right corner of the [godot.TabContainer] (setting it to `null` will make it go away). Clicking it will expand the [godot.Popup] node.
*/
public fun setPopup(popup: Node): Unit {
TransferContext.writeArguments(OBJECT to popup)
TransferContext.callMethod(rawPtr, ENGINEMETHOD_ENGINECLASS_TABCONTAINER_SET_POPUP, NIL)
}
/**
* Returns the [godot.Popup] node instance if one has been set already with [setPopup].
*
* **Warning:** This is a required internal node, removing and freeing it may cause a crash. If you wish to hide it or any of its children, use their [godot.Window.visible] property.
*/
public fun getPopup(): Popup? {
TransferContext.writeArguments()
TransferContext.callMethod(rawPtr, ENGINEMETHOD_ENGINECLASS_TABCONTAINER_GET_POPUP, OBJECT)
return TransferContext.readReturnValue(OBJECT, true) as Popup?
}
public companion object
}
| 58 | Kotlin | 25 | 338 | 10ab18864229f5178fc20e0be586d321e306be26 | 14,109 | godot-kotlin-jvm | MIT License |
plugins/analysis/common/src/main/kotlin/arrow/meta/plugins/analysis/phases/analysis/solver/ast/context/elements/FinallySection.kt | arrow-kt | 217,378,939 | false | null | package arrow.meta.plugins.analysis.phases.analysis.solver.ast.context.elements
interface FinallySection : Element {
val finalExpression: BlockExpression
}
| 97 | Kotlin | 40 | 316 | 8d2a80cf3a1275a752c18baceed74cb61aa13b4d | 159 | arrow-meta | Apache License 2.0 |
src/main/kotlin/gg/flyte/hangarWrapper/implementation/hangarProject/Namespace.kt | flytegg | 631,744,062 | false | null | package gg.flyte.hangarWrapper.implementation.hangarProject
import gg.flyte.hangarWrapper.HangarClient
import gg.flyte.hangarWrapper.implementation.hangarUser.User
/**
* Data class representing a namespace for a project or organization, including the owner's name and the slug.
* @property owner the name of the user or organization that owns the namespace
* @property slug the unique identifier for the namespace
*/
data class Namespace(
val owner: String,
val slug: String
) {
/**
* Returns the User object associated with this namespace's owner.
* @return a User object representing the owner of this namespace
*/
fun getOwnerAsUser(): User {
return HangarClient.getUser(owner)
}
} | 0 | Kotlin | 0 | 6 | 9df5d826ae44fc497d365cfcbb2cbaf7c91d1237 | 733 | hangar-wrapper | MIT License |
app/src/main/java/com/lianshang/mvvm/ui/fragment/MainProjectFragment.kt | tangweihong | 420,050,275 | false | null | package com.lianshang.mvvm.ui.fragment
import android.annotation.SuppressLint
import android.graphics.Bitmap
import android.os.Bundle
import android.view.View
import androidx.core.graphics.drawable.toBitmap
import androidx.fragment.app.Fragment
import androidx.fragment.app.FragmentManager
import androidx.fragment.app.FragmentPagerAdapter
import androidx.fragment.app.FragmentStatePagerAdapter
import com.blankj.utilcode.util.LogUtils
import com.gyf.immersionbar.ktx.immersionBar
import com.htt.base_library.base.BaseFragment
import com.htt.base_library.base.BaseLazyFragment
import com.htt.base_library.base.BaseVMFragment
import com.htt.base_library.base.NoViewModel
import com.htt.base_library.util.showToast
import com.lianshang.mvvm.databinding.FragmentWalletBinding
import com.lianshang.mvvm.util.HtmlUtil
import com.lianshang.mvvm.util.ImageSaveUtil
class MainProjectFragment : BaseLazyFragment<NoViewModel, FragmentWalletBinding>() {
override fun lazyLoad() {
// showLoadingDialog("加载中...")
}
override fun initView(view: View, savedInstanceState: Bundle?) {
immersionBar {
titleBar(mViewBinding.includeToolbar.toolbar)
statusBarDarkFont(true, 0.2f)}
var tab1 = TestFragment()
var tab2 = TestFragment()
var tab3 = TestFragment()
var lsit = listOf<Fragment>(tab1, tab2, tab3)
mViewBinding.viewpager.adapter = KotlinPagerAdapter(lsit, childFragmentManager)
mViewBinding.tabLayout.setupWithViewPager(mViewBinding.viewpager)
//
val list = listOf<String>("推荐", "订阅", "收藏")
mViewBinding.tabLayout.getTabAt(0)?.text = list[0]
mViewBinding.tabLayout.getTabAt(1)?.text = list[1]
mViewBinding.tabLayout.getTabAt(2)?.text = list[2]
}
@SuppressLint("WrongConstant")
class KotlinPagerAdapter(var mList: List<Fragment>, fm: FragmentManager) :
FragmentPagerAdapter(fm, 0) {
override fun getItem(position: Int): Fragment {
return mList[position]
}
override fun getCount(): Int {
return mList.size
}
}
override fun setEventListener() {
}
override fun loadData() {
}
override fun onResume() {
super.onResume()
LogUtils.e("onResume")
}
} | 0 | null | 0 | 1 | 3f259a2b8fe183a7578c626418edd0dc8025fe74 | 2,299 | BaseKotlinMVVM | Apache License 2.0 |
src/main/kotlin/xyz/helloyunho/dtja_mcserver_plugin/home/Home.kt | Helloyunho | 723,026,285 | false | {"Kotlin": 19000} | package xyz.helloyunho.dtja_mcserver_plugin.home
import org.bukkit.Location
data class Home(
val location: Location
)
| 0 | Kotlin | 0 | 0 | 3609a3522ba46de3d25dc7d5acfb86bfe5eacf4d | 124 | dtja-mcserver-plugin | Apache License 2.0 |
app/src/main/java/com/github/zsoltk/chesso/model/board/Rank.kt | zsoltk | 369,016,520 | false | null | package com.github.zsoltk.chesso.model.board
enum class Rank {
r1, r2, r3, r4, r5, r6, r7, r8
}
| 2 | Kotlin | 6 | 87 | e31f0913a6af64f7769112f49a909e8ee52d8d09 | 101 | chesso | Apache License 2.0 |
lib-view-record/src/main/java/io/keyss/view_record/VideoRecordConfig.kt | Key-CN | 650,054,103 | false | null | package io.keyss.view_record
import android.media.MediaCodec
import android.media.MediaFormat
import io.keyss.view_record.utils.VRLogger
import kotlin.math.max
data class VideoRecordConfig(
/** 编码类型 */
val videoMimeType: String,
val colorFormat: Int,
var outWidth: Int,
var outHeight: Int,
/** 最终实际采用的比特率 */
var bitRate: Int,
/** 实际视频是动态帧率 */
val frameRate: Float,
/** I帧间隔:秒 */
val iFrameInterval: Float,
) {
val videoMediaCodec: MediaCodec
var videoTrackIndex: Int = -1
var generateVideoFrameIndex: Long = 0
init {
if (outWidth % 2 != 0) {
outWidth -= 1
}
if (outHeight % 2 != 0) {
outHeight -= 1
}
// config
// acv h264
//val mediaFormat = MediaFormat.createVideoFormat(mRecordMediaFormat, mOutWidth, mOutHeight)
val mediaFormat = MediaFormat.createVideoFormat(videoMimeType, outWidth, outHeight)
mediaFormat.setInteger(MediaFormat.KEY_COLOR_FORMAT, colorFormat)
// 码率至少给个256Kbps吧
bitRate = max(outWidth * outHeight, bitRate)
mediaFormat.setInteger(MediaFormat.KEY_BIT_RATE, bitRate)
mediaFormat.setFloat(MediaFormat.KEY_FRAME_RATE, frameRate)
// 关键帧,单位居然是秒,25开始可以float
mediaFormat.setFloat(MediaFormat.KEY_I_FRAME_INTERVAL, iFrameInterval)
videoMediaCodec = MediaCodec.createEncoderByType(videoMimeType)
videoMediaCodec.configure(mediaFormat, null, null, MediaCodec.CONFIGURE_FLAG_ENCODE)
VRLogger.d(
"initVideoConfig: fps=$frameRate, BitRate=$bitRate, outputFormat=${videoMediaCodec.outputFormat}, width = $outWidth, height = $outHeight"
)
}
fun destroy() {
try {
videoMediaCodec.stop()
videoMediaCodec.release()
} catch (e: Exception) {
e.printStackTrace()
}
}
}
| 0 | null | 2 | 2 | 820db29aba30ccf974c7dc40f3dbdadba6655255 | 1,894 | ViewRecord | MIT License |
src/main/kotlin/me/ste/stevesseries/fancydrops/listener/ItemListener.kt | SteveTheEngineer | 234,284,154 | false | null | package me.ste.stevesseries.fancydrops.listener
import com.comphenix.protocol.ProtocolLibrary
import me.ste.stevesseries.fancydrops.item.FancyItem
import me.ste.stevesseries.fancydrops.packet.PacketPlayOutCollectItem
import me.ste.stevesseries.fancydrops.preset.FancyItemPreset
import org.bukkit.event.EventHandler
import org.bukkit.event.EventPriority
import org.bukkit.event.Listener
import org.bukkit.event.entity.EntityPickupItemEvent
import org.bukkit.event.entity.ItemSpawnEvent
object ItemListener : Listener {
@EventHandler(ignoreCancelled = true, priority = EventPriority.MONITOR)
fun onItemSpawn(event: ItemSpawnEvent) {
val preset = FancyItemPreset.matchPreset(event.entity.itemStack)
if (preset != null) {
FancyItem.ITEMS[event.entity.uniqueId] = FancyItem(preset, event.entity)
}
}
@EventHandler(ignoreCancelled = true, priority = EventPriority.MONITOR)
fun onEntityPickupItemVisual(event: EntityPickupItemEvent) {
val fancyItem = FancyItem.ITEMS[event.item.uniqueId]
if (fancyItem != null) {
for (stand in fancyItem.entities) {
ProtocolLibrary.getProtocolManager().broadcastServerPacket(
PacketPlayOutCollectItem(
stand.entityId,
event.entity.entityId,
fancyItem.item.itemStack.amount
).container
)
}
}
}
@EventHandler(ignoreCancelled = true, priority = EventPriority.LOWEST)
fun onEntityEntityPickupItemMechanics(event: EntityPickupItemEvent) {
val fancyItem = FancyItem.ITEMS[event.item.uniqueId]
if (fancyItem != null && !fancyItem.pickupEnabled) {
event.isCancelled = true
}
}
} | 1 | Kotlin | 0 | 0 | bbe63479c02bd9a777ceffbaccabb4adffd02b70 | 1,800 | SS-FancyDrops | MIT License |
video-sdk/src/main/java/com/kaleyra/video_sdk/chat/conversation/ConversationComponent.kt | KaleyraVideo | 686,975,102 | false | {"Kotlin": 5207104, "Shell": 7470, "Python": 6799, "Java": 2583} | /*
* Copyright 2023 Kaleyra @ https://www.kaleyra.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 com.kaleyra.video_sdk.chat.conversation
import android.content.res.Configuration
import androidx.compose.foundation.gestures.scrollBy
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.wrapContentHeight
import androidx.compose.foundation.lazy.LazyListState
import androidx.compose.foundation.lazy.rememberLazyListState
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Surface
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.State
import androidx.compose.runtime.derivedStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.snapshotFlow
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.platform.LocalConfiguration
import androidx.compose.ui.platform.LocalDensity
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import com.kaleyra.video_sdk.R
import com.kaleyra.video_sdk.chat.appbar.model.ChatParticipantDetails
import com.kaleyra.video_sdk.chat.conversation.model.ConversationItem
import com.kaleyra.video_sdk.chat.conversation.model.ConversationState
import com.kaleyra.video_sdk.chat.conversation.model.mock.mockConversationElements
import com.kaleyra.video_sdk.chat.conversation.view.ConversationContent
import com.kaleyra.video_sdk.common.immutablecollections.ImmutableList
import com.kaleyra.video_sdk.common.immutablecollections.ImmutableMap
import com.kaleyra.video_sdk.theme.KaleyraTheme
import kotlinx.coroutines.flow.filter
import kotlinx.coroutines.flow.launchIn
import kotlinx.coroutines.flow.onEach
private const val TOP_THRESHOLD = 15
private val ScrollToBottomThreshold = 128.dp
private val LazyListState.isApproachingTop: Boolean
get() = derivedStateOf {
val totalItemsCount = layoutInfo.totalItemsCount
val lastVisibleItemIndex = layoutInfo.visibleItemsInfo.lastOrNull()?.index ?: 0
totalItemsCount != 0 && totalItemsCount <= lastVisibleItemIndex + TOP_THRESHOLD
}.value
@Composable
internal fun scrollToBottomFabEnabled(listState: LazyListState): State<Boolean> {
val resetScrollThreshold = with(LocalDensity.current) { ScrollToBottomThreshold.toPx() }
return remember {
derivedStateOf {
val firstCompletelyVisibleItem = listState.layoutInfo.visibleItemsInfo.firstOrNull()
val firstCompletelyVisibleItemIndex = firstCompletelyVisibleItem?.index ?: 0
val firstCompletelyVisibleItemOffset = -(firstCompletelyVisibleItem?.offset ?: 0)
firstCompletelyVisibleItemIndex != 0 || firstCompletelyVisibleItemOffset > resetScrollThreshold
}
}
}
@Composable
internal fun ConversationComponent(
modifier: Modifier = Modifier,
conversationState: ConversationState,
participantsDetails: ImmutableMap<String, ChatParticipantDetails>? = null,
onMessageScrolled: (ConversationItem.Message) -> Unit = { },
onApproachingTop: () -> Unit = { },
scrollState: LazyListState = rememberLazyListState(),
) {
val screenHeight = with(LocalDensity.current) {
LocalConfiguration.current.screenHeightDp.dp.toPx()
}
LaunchedEffect(scrollState) {
val index = conversationState.conversationItems?.value?.indexOfFirst { it is ConversationItem.UnreadMessages } ?: -1
if (index != -1) {
scrollState.scrollToItem(index)
scrollState.scrollBy(-screenHeight * 2 / 3f)
}
}
LaunchedEffect(scrollState, conversationState.conversationItems) {
snapshotFlow { scrollState.firstVisibleItemIndex }
.onEach {
val item = conversationState.conversationItems?.value?.getOrNull(it) as? ConversationItem.Message ?: return@onEach
onMessageScrolled(item)
}.launchIn(this)
}
LaunchedEffect(scrollState) {
snapshotFlow { scrollState.isApproachingTop }
.filter { it }
.onEach { onApproachingTop() }
.launchIn(this)
}
LaunchedEffect(conversationState.conversationItems) {
if (scrollState.firstVisibleItemIndex < 3) scrollState.animateScrollToItem(0)
}
Box(
modifier = Modifier
.then(modifier)
) {
if (conversationState.conversationItems == null) LoadingMessagesLabel(Modifier.align(Alignment.Center))
else if (conversationState.conversationItems.value.isEmpty()) NoMessagesLabel(Modifier.align(Alignment.Center))
else {
ConversationContent(
items = conversationState.conversationItems,
participantsDetails = participantsDetails,
isFetching = conversationState.isFetching,
scrollState = scrollState,
modifier = Modifier
.fillMaxWidth()
.wrapContentHeight()
.align(Alignment.BottomCenter)
)
}
}
}
@Composable
internal fun LoadingMessagesLabel(modifier: Modifier = Modifier) {
Row(
horizontalArrangement = Arrangement.Center,
verticalAlignment = Alignment.CenterVertically,
modifier = modifier
) {
Text(
text = stringResource(id = R.string.kaleyra_chat_channel_loading),
style = MaterialTheme.typography.bodyMedium
)
}
}
@Composable
internal fun NoMessagesLabel(modifier: Modifier = Modifier) {
Row(
horizontalArrangement = Arrangement.Center,
verticalAlignment = Alignment.CenterVertically,
modifier = modifier
) {
Text(
text = stringResource(id = R.string.kaleyra_chat_no_messages),
style = MaterialTheme.typography.bodyMedium,
)
}
}
@Preview(name = "Light Mode")
@Preview(uiMode = Configuration.UI_MODE_NIGHT_YES, name = "Dark Mode")
@Composable
internal fun LoadingConversationComponentPreview() = KaleyraTheme {
Surface(color = MaterialTheme.colorScheme.surface) {
ConversationComponent(
conversationState = ConversationState(),
onMessageScrolled = { },
onApproachingTop = { },
scrollState = rememberLazyListState(),
modifier = Modifier.fillMaxSize()
)
}
}
@Preview(name = "Light Mode")
@Preview(uiMode = Configuration.UI_MODE_NIGHT_YES, name = "Dark Mode")
@Composable
internal fun EmptyConversationComponentPreview() = KaleyraTheme {
Surface(color = MaterialTheme.colorScheme.surface) {
ConversationComponent(
conversationState = ConversationState(conversationItems = ImmutableList(listOf())),
modifier = Modifier.fillMaxSize()
)
}
}
@Preview(name = "Light Mode")
@Preview(uiMode = Configuration.UI_MODE_NIGHT_YES, name = "Dark Mode")
@Composable
internal fun ConversationComponentPreview() = KaleyraTheme {
Surface(color = MaterialTheme.colorScheme.surface) {
ConversationComponent(
conversationState = ConversationState(conversationItems = mockConversationElements),
modifier = Modifier.fillMaxSize()
)
}
}
| 0 | Kotlin | 0 | 1 | 9faa41e5903616889f2d0cd79ba21e18afe800ed | 8,069 | VideoAndroidSDK | Apache License 2.0 |
app/src/main/java/org/dexcare/sampleapp/ui/common/viewmodel/BaseTimeSlotViewModel.kt | DexCare | 305,396,501 | false | {"Kotlin": 313821} | package org.dexcare.sampleapp.ui.common.viewmodel
import androidx.databinding.Bindable
import org.dexcare.sampleapp.BR
import org.dexcare.services.retail.models.TimeSlot
import java.time.format.DateTimeFormatter
abstract class BaseTimeSlotViewModel(
timeSlot: TimeSlot? = null
) : BaseViewModel() {
private val formatter = DateTimeFormatter.ofPattern("hh:mm a")
@Bindable
var startTime: String = timeSlot?.slotDateTime?.format(formatter) ?: ""
set(value) {
field = value
notifyPropertyChanged(BR.startTime)
}
}
| 0 | Kotlin | 0 | 1 | 37980a40c211334e94baffcb8d4dcedf4b3cd611 | 571 | DexCareSDK.Android.SampleApp | MIT License |
app/src/main/java/com/melonhead/mangadexfollower/repositories/AuthRepository.kt | taffyrat | 542,405,576 | false | null | package com.melonhead.mangadexfollower.repositories
import android.content.Context
import androidx.core.app.NotificationManagerCompat
import com.melonhead.mangadexfollower.App
import com.melonhead.mangadexfollower.logs.Clog
import com.melonhead.mangadexfollower.models.auth.AuthToken
import com.melonhead.mangadexfollower.models.ui.LoginStatus
import com.melonhead.mangadexfollower.notifications.AuthFailedNotification
import com.melonhead.mangadexfollower.services.AppDataService
import com.melonhead.mangadexfollower.services.LoginService
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.flow.*
import kotlinx.coroutines.launch
class AuthRepository(
private val appContext: Context,
private val appDataService: AppDataService,
private val loginService: LoginService,
externalScope: CoroutineScope,
) {
private val mutableIsLoggedIn = MutableStateFlow<LoginStatus>(LoginStatus.LoggedOut)
val loginStatus = mutableIsLoggedIn.shareIn(externalScope, replay = 1, started = SharingStarted.WhileSubscribed()).distinctUntilChanged()
init {
externalScope.launch {
mutableIsLoggedIn.value = if (appDataService.token.firstOrNull() != null) LoginStatus.LoggedIn else LoginStatus.LoggedOut
refreshToken()
}
}
suspend fun refreshToken(): AuthToken? {
fun signOut() {
Clog.e("Signing out, refresh failed", Exception())
mutableIsLoggedIn.value = LoginStatus.LoggedOut
if ((appContext as App).inForeground) return
val notificationManager = NotificationManagerCompat.from(appContext)
if (!notificationManager.areNotificationsEnabled()) return
AuthFailedNotification.postAuthFailed(appContext)
}
val currentToken = appDataService.token.firstOrNull()
if (currentToken == null) {
signOut()
return null
}
val newToken = loginService.refreshToken(currentToken)
appDataService.updateToken(newToken)
if (newToken == null) {
signOut()
}
return newToken
}
suspend fun authenticate(email: String, password: String) {
Clog.i("authenticate")
mutableIsLoggedIn.value = LoginStatus.LoggingIn
val token = loginService.authenticate(email, password)
appDataService.updateToken(token)
mutableIsLoggedIn.value = LoginStatus.LoggedIn
}
} | 4 | Kotlin | 0 | 0 | 595afc678bd06666a808a8d2f84670fb0315ed72 | 2,440 | mangadexdroid | Do What The F*ck You Want To Public License |
app/src/main/java/com/gitsearch/data/model/Pageable.kt | chrisnkrueger | 118,476,426 | false | null | package com.gitsearch.data.model
data class Pageable<T>(
val value: T?,
val last: Int?,
val next: Int?
)
| 0 | Kotlin | 0 | 3 | ddd4ee0b468f5eb14a2320a6e887aa6349bafd28 | 130 | githubsearch | Apache License 2.0 |
app/src/main/java/com/skydoves/pokedexar/network/PokedexClient.kt | skydoves | 321,092,589 | false | null | /*
* Designed and developed by 2020 skydoves (<NAME>)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.skydoves.pokedexar.network
import com.skydoves.pokedexar.model.PokemonInfo
import com.skydoves.sandwich.ApiResponse
import javax.inject.Inject
class PokedexClient @Inject constructor(
private val pokedexService: PokedexService
) {
suspend fun fetchPokemonInfo(
name: String
): ApiResponse<PokemonInfo> =
pokedexService.fetchPokemonInfo(
name = name
)
}
| 0 | Kotlin | 54 | 566 | db14b250156c2d29bd7acb5a914ce46a3431faae | 1,006 | Pokedex-AR | Apache License 2.0 |
pdfium-library/src/main/java/com/github/barteksc/pdfviewer/util/Rect.kt | beeline09 | 448,825,053 | false | {"C": 358617, "Kotlin": 226845, "C++": 54452, "CMake": 2072, "Python": 1354} | package com.github.barteksc.pdfviewer.util
import android.graphics.RectF
fun RectF.addArea(scaleFactorVertical: Float = 0.3f) {
if (this.top < this.bottom) {
this.top -= this.height() * scaleFactorVertical
this.bottom += this.height() * scaleFactorVertical
} else {
this.top += this.height() * scaleFactorVertical
this.bottom -= this.height() * scaleFactorVertical
}
} | 1 | C | 3 | 3 | 8be61212e25c83dc26e61ee77f569d0867fc9ebc | 414 | AdvancedPdfView | Apache License 2.0 |
pdfium-library/src/main/java/com/github/barteksc/pdfviewer/util/Rect.kt | beeline09 | 448,825,053 | false | {"C": 358617, "Kotlin": 226845, "C++": 54452, "CMake": 2072, "Python": 1354} | package com.github.barteksc.pdfviewer.util
import android.graphics.RectF
fun RectF.addArea(scaleFactorVertical: Float = 0.3f) {
if (this.top < this.bottom) {
this.top -= this.height() * scaleFactorVertical
this.bottom += this.height() * scaleFactorVertical
} else {
this.top += this.height() * scaleFactorVertical
this.bottom -= this.height() * scaleFactorVertical
}
} | 1 | C | 3 | 3 | 8be61212e25c83dc26e61ee77f569d0867fc9ebc | 414 | AdvancedPdfView | Apache License 2.0 |
app/src/main/java/dev/srijith/sample/composenavigations/dashboard/DashboardDependencyComponent.kt | sjthn | 590,043,590 | false | null | package dev.srijith.sample.composenavigations.dashboard
import androidx.lifecycle.ViewModelStoreOwner
import dev.srijith.composenavigations.dependencyinjector.DependencyInjector
import dev.srijith.composenavigations.scopedpresenter.presenter
import dev.srijith.sample.composenavigations.navigation.NavigatorPresenter
interface DashboardDependencyComponent {
val dashboardPresenter: DashboardPresenter
}
class DashboardDependencyComponentImpl(
viewModelStoreOwner: ViewModelStoreOwner,
navigatorPresenter: NavigatorPresenter,
username: String
) :
DashboardDependencyComponent {
override val dashboardPresenter: DashboardPresenter by viewModelStoreOwner.presenter {
DashboardPresenter(navigatorPresenter, username)
}
}
class DashboardDependencyProvider(
private val navigatorPresenter: NavigatorPresenter,
private val username: String
) :
DependencyInjector<DashboardDependencyComponent> {
override fun inject(viewModelStoreOwner: ViewModelStoreOwner): DashboardDependencyComponent {
return DashboardDependencyComponentImpl(
viewModelStoreOwner,
navigatorPresenter,
username
)
}
} | 6 | Kotlin | 0 | 1 | 1c56a884dbe232a697def6dd36b4ccdc15fdac60 | 1,190 | ComposeNavigations | Apache License 2.0 |
app/src/main/java/com/alexllanas/openaudio/presentation/profile/state/ProfileState.kt | alexllanas | 473,371,200 | false | {"Kotlin": 428820} | package com.alexllanas.openaudio.presentation.profile.state
import com.alexllanas.core.domain.models.Track
import com.alexllanas.core.domain.models.User
data class ProfileState(
val avatarUrl: String= "",
val nameText: String= "",
val locationText: String= "",
val bioText: String= "",
val currentPasswordText: String= "",
val newPasswordText: String= "",
val confirmPasswordText: String= "",
val isLoading: Boolean = false,
val error: Throwable? = null
) | 1 | Kotlin | 0 | 5 | 45fee02ca03aa9a66c974759ddf54bdce515e47b | 493 | open-audio | MIT License |
sdk/src/jvmTest/kotlin/com/kss/zoom/sdk/common/UtilsJvmTest.kt | Kotlin-server-squad | 710,163,911 | false | {"Kotlin": 92662, "JavaScript": 98} | package com.kss.zoom.sdk.common
import com.kss.zoom.assertThrows
import com.kss.zoom.auth.model.ZoomException
import com.kss.zoom.verifyFailure
import org.junit.jupiter.api.Assertions.assertEquals
import java.util.concurrent.ExecutionException
import kotlin.test.Test
import kotlin.test.assertTrue
class UtilsJvmTest {
@Test
fun `callSync should return result of block`() {
assertEquals(1, callSync { Result.success(1) }, "`runSync` should return result of block")
}
@Test
fun `callSync should throw an exception if the block fails`() {
val zoomException = ZoomException(500, "Server error")
val exception = assertThrows(ZoomException::class) {
callSync<Int> {
Result.failure(zoomException)
}
}
verifyFailure(zoomException.code, zoomException.message, exception)
}
@Test
fun `callAsync should return result of block as a completable future`() {
val future = callAsync { Result.success(1) }
assertEquals(1, future.get(), "`future` should return result of block")
}
@Test
fun `callAsync should throw an exception if the block fails`() {
val zoomException = ZoomException(500, "Server error")
val future = callAsync { Result.failure<Int>(zoomException) }
val exception = assertThrows(ExecutionException::class) {
future.get()
}
assertTrue(exception.cause is ZoomException, "Expected exception cause is not ZoomException")
verifyFailure(zoomException.code, zoomException.message, exception.cause as ZoomException)
}
} | 6 | Kotlin | 0 | 1 | 335e55782696c80a4365c3d8ef7fdce5b0e2ff12 | 1,623 | zoomsdk | Apache License 2.0 |
src/main/kotlin/mrs/domain/service/room/RoomService.kt | tetsuyaokuyama0312 | 358,807,098 | false | null | package mrs.domain.service.room
import mrs.domain.model.MeetingRoom
import mrs.domain.model.ReservableRoom
import java.time.LocalDate
/**
* 会議室情報取得サービスのインタフェース。
*/
interface RoomService {
/**
* 予約可能会議室取得処理
*
* @param date 会議室情報取得対象日付
* @return 予約可能会議室情報一覧
*/
fun findReservableRooms(date: LocalDate): List<ReservableRoom>
/**
* 会議室情報取得処理
*
* @param roomId 部屋ID
* @return 部屋IDに紐づく会議室情報
*/
fun findMeetingRoom(roomId: Int): MeetingRoom
} | 0 | Kotlin | 0 | 0 | be7c84ff21ed1dae4849254fc15a609bffae644a | 506 | kotlin-mrs | MIT License |
app/src/main/java/com/lemu/pay/checkout/CheckoutApplication.kt | Visels | 853,435,251 | false | {"Kotlin": 125294} | package com.lemu.pay.checkout
import android.app.Application
import dagger.hilt.android.HiltAndroidApp
@HiltAndroidApp
class CheckoutApplication: Application() {
} | 2 | Kotlin | 0 | 0 | 4136bed5ef49764eed96371396fcbc48d2b6f5ca | 165 | Payment-Checkout | MIT License |
mvvmlin/src/main/java/com/aleyn/mvvm/network/interceptor/Printer.kt | msdgwzhy6 | 222,344,941 | true | {"Kotlin": 91091, "Java": 549} | /*
* Copyright 2018 JessYan
*
* 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.aleyn.mvvm.network.interceptor
import android.text.TextUtils
import org.json.JSONArray
import org.json.JSONException
import org.json.JSONObject
import java.io.IOException
import okhttp3.FormBody
import okhttp3.Request
import okhttp3.internal.platform.Platform
import okio.Buffer
/**
* ================================================
* 对 OkHttp 的请求和响应信息进行更规范和清晰的打印, 此类为框架默认实现, 以默认格式打印信息, 若觉得默认打印格式
* 并不能满足自己的需求, 可自行扩展自己理想的打印格式
*/
object Printer {
private val JSON_INDENT = 3
private val LINE_SEPARATOR = System.getProperty("line.separator")
private val DOUBLE_SEPARATOR = LINE_SEPARATOR!! + LINE_SEPARATOR
private val OMITTED_RESPONSE = arrayOf(LINE_SEPARATOR, "Omitted response body")
private val OMITTED_REQUEST = arrayOf(LINE_SEPARATOR, "Omitted request body")
private val N = "\n"
private val T = "\t"
private val REQUEST_UP_LINE =
"┌────── Request ────────────────────────────────────────────────────────────────────────"
private val END_LINE =
"└───────────────────────────────────────────────────────────────────────────────────────"
private val RESPONSE_UP_LINE =
"┌────── Response ───────────────────────────────────────────────────────────────────────"
private val BODY_TAG = "Body:"
private val URL_TAG = "URL: "
private val METHOD_TAG = "Method: @"
private val HEADERS_TAG = "Headers:"
private val STATUS_CODE_TAG = "Status Code: "
private val RECEIVED_TAG = "Received in: "
private val CORNER_UP = "┌ "
private val CORNER_BOTTOM = "└ "
private val CENTER_LINE = "├ "
private val DEFAULT_LINE = "│ "
private fun isEmpty(line: String): Boolean {
return TextUtils.isEmpty(line) || N == line || T == line || TextUtils.isEmpty(line.trim { it <= ' ' })
}
internal fun printJsonRequest(builder: LoggingInterceptor, request: Request) {
val requestBody = LINE_SEPARATOR + BODY_TAG + LINE_SEPARATOR + bodyToString(request)
val tag = builder.requestTag
if (builder.logger == null)
log(builder.type, tag, REQUEST_UP_LINE)
logLines(builder.type, tag, arrayOf(URL_TAG + request.url()), builder.logger, false)
logLines(builder.type, tag, getRequest(request, builder.level), builder.logger, true)
if (request.body() is FormBody) {
val formBody = StringBuilder()
val body = request.body() as FormBody?
if (body != null && body.size() != 0) {
for (i in 0 until body.size()) {
formBody.append(body.encodedName(i) + "=" + body.encodedValue(i) + "&")
}
formBody.delete(formBody.length - 1, formBody.length)
logLines(builder.type, tag, arrayOf(formBody.toString()), builder.logger, true)
}
}
if (builder.level == Level.BASIC || builder.level == Level.BODY) {
logLines(
builder.type,
tag,
requestBody.split(LINE_SEPARATOR.toRegex()).dropLastWhile { it.isEmpty() }.toTypedArray(),
builder.logger,
true
)
}
if (builder.logger == null)
log(builder.type, tag, END_LINE)
}
internal fun printJsonResponse(
builder: LoggingInterceptor, chainMs: Long, isSuccessful: Boolean,
code: Int, headers: String, bodyString: String, segments: List<String>
) {
val responseBody =
LINE_SEPARATOR + BODY_TAG + LINE_SEPARATOR + getJsonString(bodyString)
val tag = builder.responseTag
if (builder.logger == null)
log(builder.type, tag, RESPONSE_UP_LINE)
logLines(
builder.type, tag, getResponse(
headers, chainMs, code, isSuccessful,
builder.level, segments
), builder.logger, true
)
if (builder.level == Level.BASIC || builder.level == Level.BODY) {
logLines(
builder.type,
tag,
responseBody.split(LINE_SEPARATOR.toRegex()).dropLastWhile { it.isEmpty() }.toTypedArray(),
builder.logger,
true
)
}
if (builder.logger == null)
log(builder.type, tag, END_LINE)
}
internal fun printFileRequest(builder: LoggingInterceptor, request: Request) {
val tag = builder.responseTag
if (builder.logger == null)
log(builder.type, tag, REQUEST_UP_LINE)
logLines(builder.type, tag, arrayOf(URL_TAG + request.url()), builder.logger, false)
logLines(builder.type, tag, getRequest(request, builder.level), builder.logger, true)
if (request.body() is FormBody) {
val formBody = StringBuilder()
val body = request.body() as FormBody?
if (body != null && body.size() != 0) {
for (i in 0 until body.size()) {
formBody.append(body.encodedName(i) + "=" + body.encodedValue(i) + "&")
}
formBody.delete(formBody.length - 1, formBody.length)
logLines(builder.type, tag, arrayOf(formBody.toString()), builder.logger, true)
}
}
if (builder.level == Level.BASIC || builder.level == Level.BODY) {
logLines(builder.type, tag, OMITTED_REQUEST, builder.logger, true)
}
if (builder.logger == null)
log(builder.type, tag, END_LINE)
}
internal fun printFileResponse(
builder: LoggingInterceptor, chainMs: Long, isSuccessful: Boolean,
code: Int, headers: String, segments: List<String>
) {
val tag = builder.responseTag
if (builder.logger == null)
log(builder.type, tag, RESPONSE_UP_LINE)
logLines(
builder.type, tag, getResponse(
headers, chainMs, code, isSuccessful,
builder.level, segments
), builder.logger, true
)
logLines(builder.type, tag, OMITTED_RESPONSE, builder.logger, true)
if (builder.logger == null)
log(builder.type, tag, END_LINE)
}
private fun getRequest(request: Request, level: Level): Array<String> {
val message: String
val header = request.headers().toString()
val loggableHeader = level == Level.HEADERS || level == Level.BASIC
message = METHOD_TAG + request.method() + DOUBLE_SEPARATOR +
if (isEmpty(header)) "" else if (loggableHeader) HEADERS_TAG + LINE_SEPARATOR + dotHeaders(
header
) else ""
return message.split(LINE_SEPARATOR.toRegex()).dropLastWhile { it.isEmpty() }
.toTypedArray()
}
private fun getResponse(
header: String, tookMs: Long, code: Int, isSuccessful: Boolean,
level: Level, segments: List<String>
): Array<String> {
val message: String
val loggableHeader = level == Level.HEADERS || level == Level.BASIC
val segmentString = slashSegments(segments)
message =
((if (!TextUtils.isEmpty(segmentString)) "$segmentString - " else "") + "is success : "
+ isSuccessful + " - " + RECEIVED_TAG + tookMs + "ms" + DOUBLE_SEPARATOR + STATUS_CODE_TAG +
code + DOUBLE_SEPARATOR + if (isEmpty(header))
""
else if (loggableHeader)
HEADERS_TAG + LINE_SEPARATOR +
dotHeaders(header)
else
"")
return message.split(LINE_SEPARATOR.toRegex()).dropLastWhile { it.isEmpty() }
.toTypedArray()
}
private fun slashSegments(segments: List<String>): String {
val segmentString = StringBuilder()
for (segment in segments) {
segmentString.append("/").append(segment)
}
return segmentString.toString()
}
private fun dotHeaders(header: String): String {
val headers =
header.split(LINE_SEPARATOR.toRegex()).dropLastWhile { it.isEmpty() }.toTypedArray()
val builder = StringBuilder()
var tag = "─ "
if (headers.size > 1) {
for (i in headers.indices) {
if (i == 0) {
tag = CORNER_UP
} else if (i == headers.size - 1) {
tag = CORNER_BOTTOM
} else {
tag = CENTER_LINE
}
builder.append(tag).append(headers[i]).append("\n")
}
} else {
for (item in headers) {
builder.append(tag).append(item).append("\n")
}
}
return builder.toString()
}
private fun logLines(
type: Int,
tag: String,
lines: Array<String>,
logger: LoggingInterceptor.Logger?,
withLineSize: Boolean
) {
for (line in lines) {
val lineLength = line.length
val MAX_LONG_SIZE = if (withLineSize) 110 else lineLength
for (i in 0..lineLength / MAX_LONG_SIZE) {
val start = i * MAX_LONG_SIZE
var end = (i + 1) * MAX_LONG_SIZE
end = if (end > line.length) line.length else end
if (logger == null) {
log(type, tag, DEFAULT_LINE + line.substring(start, end))
} else {
logger.log(type, tag, line.substring(start, end))
}
}
}
}
private fun bodyToString(request: Request): String {
try {
val copy = request.newBuilder().build()
val buffer = Buffer()
if (copy.body() == null)
return ""
copy.body()!!.writeTo(buffer)
return getJsonString(buffer.readUtf8())
} catch (e: IOException) {
return "{\"err\": \"" + e.message + "\"}"
}
}
internal fun getJsonString(msg: String): String {
var message: String
try {
if (msg.startsWith("{")) {
val jsonObject = JSONObject(msg)
message = jsonObject.toString(JSON_INDENT)
} else if (msg.startsWith("[")) {
val jsonArray = JSONArray(msg)
message = jsonArray.toString(JSON_INDENT)
} else {
message = msg
}
} catch (e: JSONException) {
message = msg
}
return message
}
internal fun log(type: Int, tag: String, msg: String) {
val logger = java.util.logging.Logger.getLogger(tag)
when (type) {
Platform.INFO -> logger.log(java.util.logging.Level.INFO, msg)
else -> logger.log(java.util.logging.Level.WARNING, msg)
}
}
}
| 0 | null | 0 | 1 | a1cffea1498695da73f80cc00b26264da5b204a1 | 11,416 | MVVMLin | Apache License 2.0 |
backend/src/commonMain/kotlin/dev/drzepka/wikilinks/app/model/SearchResultWrapper.kt | drzpk | 513,034,741 | false | null | package dev.drzepka.wikilinks.app.model
import dev.drzepka.wikilinks.common.model.searchresult.LinkSearchResult
data class SearchResultWrapper(
val result: LinkSearchResult?,
val source: String,
val target: String,
val sourceMissing: Boolean = false,
val targetMissing: Boolean = false
)
| 0 | Kotlin | 0 | 1 | ab55472076b04ff6cca0b8ae4777f074d6f7be73 | 310 | wikilinks | Apache License 2.0 |
matisse/src/main/java/github/leavesczy/matisse/CaptureStrategy.kt | leavesCZY | 502,683,055 | false | null | package github.leavesczy.matisse
import android.Manifest
import android.content.Context
import android.content.pm.PackageManager
import android.net.Uri
import android.os.Build
import android.os.Bundle
import android.os.Environment
import android.os.Parcelable
import androidx.compose.runtime.Stable
import androidx.core.app.ActivityCompat
import androidx.core.content.FileProvider
import github.leavesczy.matisse.internal.logic.MediaProvider
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
import kotlinx.parcelize.IgnoredOnParcel
import kotlinx.parcelize.Parcelize
import java.io.File
import java.text.SimpleDateFormat
import java.util.Date
import java.util.Locale
/**
* @Author: leavesCZY
* @Date: 2022/6/6 14:20
* @Desc:
*/
/**
* 拍照策略
*/
@Stable
interface CaptureStrategy : Parcelable {
/**
* 是否需要申请 WRITE_EXTERNAL_STORAGE 权限
*/
fun shouldRequestWriteExternalStoragePermission(context: Context): Boolean
/**
* 生成图片 Uri
*/
suspend fun createImageUri(context: Context): Uri?
/**
* 获取拍照结果
*/
suspend fun loadResource(context: Context, imageUri: Uri): MediaResource?
/**
* 当用户取消拍照时调用
*/
suspend fun onTakePictureCanceled(context: Context, imageUri: Uri)
/**
* 生成图片名
*/
suspend fun createImageName(context: Context): String {
return withContext(context = Dispatchers.Default) {
val time = SimpleDateFormat("yyyyMMdd_HHmmssSSS", Locale.US).format(Date())
return@withContext "IMG_$time.jpg"
}
}
/**
* 用于为相机设置启动参数
* 返回值会传递给启动相机的 Intent
*/
fun getCaptureExtra(): Bundle {
return Bundle.EMPTY
}
}
private const val JPG_MIME_TYPE = "image/jpeg"
/**
* 通过 FileProvider 生成 ImageUri
* 外部必须配置 FileProvider,通过 authority 来实例化 FileProviderCaptureStrategy
* 此策略无需申请任何权限,所拍的照片不会保存在系统相册里
*/
@Parcelize
data class FileProviderCaptureStrategy(
private val authority: String,
private val extra: Bundle = Bundle.EMPTY
) : CaptureStrategy {
@IgnoredOnParcel
private val uriFileMap = mutableMapOf<Uri, File>()
override fun shouldRequestWriteExternalStoragePermission(context: Context): Boolean {
return false
}
override suspend fun createImageUri(context: Context): Uri? {
return withContext(context = Dispatchers.Main.immediate) {
val tempFile = createTempFile(context = context)
if (tempFile != null) {
val uri = FileProvider.getUriForFile(context, authority, tempFile)
uriFileMap[uri] = tempFile
return@withContext uri
}
return@withContext null
}
}
private suspend fun createTempFile(context: Context): File? {
return withContext(context = Dispatchers.IO) {
val storageDir = context.getExternalFilesDir(Environment.DIRECTORY_PICTURES)
val file = File(storageDir, createImageName(context = context))
if (file.createNewFile()) {
file
} else {
null
}
}
}
override suspend fun loadResource(context: Context, imageUri: Uri): MediaResource {
return withContext(context = Dispatchers.Main.immediate) {
val imageFile = uriFileMap[imageUri]!!
uriFileMap.remove(key = imageUri)
val imageFilePath = imageFile.absolutePath
val displayName = imageFile.name
return@withContext MediaResource(
id = 0,
bucketId = "",
bucketName = "",
uri = imageUri,
path = imageFilePath,
name = displayName,
mimeType = JPG_MIME_TYPE
)
}
}
override suspend fun onTakePictureCanceled(context: Context, imageUri: Uri) {
withContext(context = Dispatchers.Main.immediate) {
val imageFile = uriFileMap[imageUri]
uriFileMap.remove(key = imageUri)
withContext(context = Dispatchers.IO) {
if (imageFile != null && imageFile.exists()) {
imageFile.delete()
}
}
}
}
override fun getCaptureExtra(): Bundle {
return extra
}
}
/**
* 通过 MediaStore 生成 ImageUri
* 根据系统版本决定是否需要申请 WRITE_EXTERNAL_STORAGE 权限
* 所拍的照片会保存在系统相册中
*/
@Parcelize
data class MediaStoreCaptureStrategy(private val extra: Bundle = Bundle.EMPTY) : CaptureStrategy {
override fun shouldRequestWriteExternalStoragePermission(context: Context): Boolean {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
return false
}
return ActivityCompat.checkSelfPermission(
context,
Manifest.permission.WRITE_EXTERNAL_STORAGE
) == PackageManager.PERMISSION_DENIED
}
override suspend fun createImageUri(context: Context): Uri? {
return MediaProvider.createImage(
context = context,
imageName = createImageName(context = context),
mimeType = JPG_MIME_TYPE,
relativePath = "DCIM/Camera"
)
}
override suspend fun loadResource(context: Context, imageUri: Uri): MediaResource? {
return MediaProvider.loadResources(context = context, uri = imageUri)
}
override suspend fun onTakePictureCanceled(context: Context, imageUri: Uri) {
MediaProvider.deleteMedia(context = context, uri = imageUri)
}
override fun getCaptureExtra(): Bundle {
return extra
}
}
/**
* 根据系统版本智能选择拍照策略
* 当系统版本小于 Android 10 时,执行 FileProviderCaptureStrategy 策略
* 当系统版本大于等于 Android 10 时,执行 MediaStoreCaptureStrategy 策略
* 既避免需要申请权限,又可以在系统允许的情况下将照片存入到系统相册中
*/
@Parcelize
data class SmartCaptureStrategy(
private val authority: String,
private val extra: Bundle = Bundle.EMPTY
) : CaptureStrategy {
@IgnoredOnParcel
private val proxy = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
MediaStoreCaptureStrategy(extra = extra)
} else {
FileProviderCaptureStrategy(authority = authority, extra = extra)
}
override fun shouldRequestWriteExternalStoragePermission(context: Context): Boolean {
return proxy.shouldRequestWriteExternalStoragePermission(context = context)
}
override suspend fun createImageUri(context: Context): Uri? {
return proxy.createImageUri(context = context)
}
override suspend fun loadResource(context: Context, imageUri: Uri): MediaResource? {
return proxy.loadResource(context = context, imageUri = imageUri)
}
override suspend fun onTakePictureCanceled(context: Context, imageUri: Uri) {
proxy.onTakePictureCanceled(context = context, imageUri = imageUri)
}
override suspend fun createImageName(context: Context): String {
return proxy.createImageName(context = context)
}
override fun getCaptureExtra(): Bundle {
return proxy.getCaptureExtra()
}
} | 0 | null | 59 | 727 | 4a3fdc73606721057ca6957a83057068f2b1c0c9 | 7,023 | Matisse | Apache License 2.0 |
Android/core/presentation/src/main/java/com/dinesh/core/presentation/state/EmployeeState.kt | dineshvg | 247,720,364 | false | null | package com.dinesh.core.presentation.state
import com.dinesh.core.presentation.model.PresentationEmployee
import com.svenjacobs.zen.core.state.State
data class EmployeeState(
val employee: PresentationEmployee? = null,
val sideEffectStates: SideEffectStates = SideEffectStates(),
val position: Int = 0
) : State
data class SideEffectStates(
val initialized: Boolean = true,
val nextClicked: Boolean = false,
val previousClicked: Boolean = false
) | 0 | Kotlin | 0 | 0 | 3497c5e3cd9419eaf28a1771b1ec3695b8302306 | 474 | MVI-Arch-App | Apache License 2.0 |
remote-messaging/remote-messaging-internal/src/main/java/com/duckduckgo/remote/messaging/internal/feature/RMFInternalSettingsActivity.kt | hojat72elect | 822,396,044 | false | {"Kotlin": 11626231, "HTML": 65873, "Ruby": 16984, "C++": 10312, "JavaScript": 5520, "CMake": 1992, "C": 1076, "Shell": 784} |
package com.duckduckgo.remote.messaging.internal.feature
import android.os.Bundle
import com.duckduckgo.anvil.annotations.ContributeToActivityStarter
import com.duckduckgo.anvil.annotations.InjectWith
import com.duckduckgo.common.ui.DuckDuckGoActivity
import com.duckduckgo.common.ui.viewbinding.viewBinding
import com.duckduckgo.common.utils.plugins.PluginPoint
import com.duckduckgo.di.scopes.ActivityScope
import com.duckduckgo.navigation.api.GlobalActivityStarter
import com.duckduckgo.remote.messaging.internal.feature.RMFInternalScreens.InternalSettings
import com.duckduckgo.remotemessaging.internal.databinding.ActivityRmfInternalSettingsBinding
import javax.inject.Inject
@InjectWith(ActivityScope::class)
@ContributeToActivityStarter(InternalSettings::class)
class RMFInternalSettingsActivity : DuckDuckGoActivity() {
@Inject
lateinit var settings: PluginPoint<RmfSettingPlugin>
private val binding: ActivityRmfInternalSettingsBinding by viewBinding()
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(binding.root)
setupToolbar(binding.toolbar)
setupUiElementState()
}
private fun setupUiElementState() {
settings.getPlugins()
.mapNotNull { it.getView(this) }
.forEach { remoteViewPlugin ->
binding.rmfSettingsContent.addView(remoteViewPlugin)
}
}
}
sealed class RMFInternalScreens : GlobalActivityStarter.ActivityParams {
data object InternalSettings : RMFInternalScreens() {
private fun readResolve(): Any = InternalSettings
}
}
| 0 | Kotlin | 0 | 0 | b89591136b60933d6a03fac43a38ee183116b7f8 | 1,641 | DuckDuckGo | Apache License 2.0 |
app/src/main/java/com/alv/todo/ui/create/NewToDoViewModel.kt | adelannucci | 167,173,862 | false | null | package com.alv.todo.ui.create
import android.arch.lifecycle.MutableLiveData
import android.arch.lifecycle.ViewModel
import android.util.Log
import com.alv.todo.data.room.ToDoDao
import com.alv.todo.domain.ToDo
import io.reactivex.Observable
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.disposables.Disposable
import io.reactivex.schedulers.Schedulers
import javax.inject.Inject
class NewToDoViewModel @Inject constructor(
private val toDoDao: ToDoDao
) : ViewModel() {
private lateinit var disposable: Disposable
val isSaving: MutableLiveData<Boolean> = MutableLiveData()
val wasSaved: MutableLiveData<Boolean> = MutableLiveData()
val hasError: MutableLiveData<Boolean> = MutableLiveData()
override fun onCleared() {
super.onCleared()
dispose()
}
fun dispose() {
if (!disposable.isDisposed) {
disposable.dispose()
}
}
fun close() {
disposable = Observable
.fromCallable {
Log.i("CLOSE", "CLOSE")
}
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.doOnSubscribe { isSaving.value = true }
.doAfterTerminate { isSaving.value = false }
.subscribe(
{ wasSaved.value = true },
{ hasError.value = true ; wasSaved.value = false }
)
}
fun save(item: ToDo) {
disposable = Observable
.fromCallable {
if(item != null)
toDoDao.insert(item)
}
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.doOnSubscribe { isSaving.value = true }
.doAfterTerminate { isSaving.value = false }
.subscribe(
{ wasSaved.value = true },
{ hasError.value = true ; wasSaved.value = false }
)
}
} | 0 | Kotlin | 0 | 0 | c2d51356ffa9fdcbf7557454563b6527864eb8ab | 2,085 | todo-list-mvvm-di-room-kotlin | MIT License |
app/src/main/java/com/kelmer/abn/foursquare/data/db/model/LocationInfo.kt | kelmer44 | 258,746,175 | false | null | package com.kelmer.abn.foursquare.data.db.model
data class LocationInfo(
val address: String,
val city: String,
val country: String
) | 0 | Kotlin | 0 | 0 | 4f414ece376d74d1e32dffa52b082c75babcc295 | 146 | abn-test | MIT License |
src/main/kotlin/com/citi/cloudlab/dao/repository/PostTagsRepository.kt | LokiSnow | 598,947,081 | false | {"Kotlin": 29341, "HCL": 15444, "Makefile": 1691, "Dockerfile": 615, "Shell": 142} | package com.citi.cloudlab.dao.repository
import com.citi.cloudlab.dao.model.Post
/**
*
*@author Loki
*@date 2023/5/10
*/
interface PostTagsRepository {
suspend fun save(postId: String, tags: List<String>?)
suspend fun findPosts(tagId: String, lastPostId: String?): List<Post>
} | 1 | Kotlin | 0 | 0 | 90fca99baddfadbaf8947c2d87c90850cbf43f18 | 292 | cloudlab | Apache License 2.0 |
views-dsl-constraintlayout/src/main/kotlin/splitties/views/dsl/constraintlayout/Views.kt | hiennguyen1001 | 163,793,608 | true | {"Kotlin": 310400, "Java": 1908} | /*
* Copyright (c) 2018. <NAME>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package splitties.views.dsl.constraintlayout
import android.content.Context
import android.view.View
import androidx.annotation.IdRes
import androidx.annotation.StyleRes
import androidx.constraintlayout.widget.ConstraintLayout
import splitties.views.dsl.core.NO_THEME
import splitties.views.dsl.core.Ui
import splitties.views.dsl.core.view
import kotlin.contracts.InvocationKind
import kotlin.contracts.contract
// ConstraintLayout
inline fun Context.constraintLayout(
@IdRes id: Int = View.NO_ID,
@StyleRes theme: Int = NO_THEME,
initView: ConstraintLayout.() -> Unit = {}
): ConstraintLayout {
contract { callsInPlace(initView, InvocationKind.EXACTLY_ONCE) }
return view(::ConstraintLayout, id, theme, initView)
}
inline fun View.constraintLayout(
@IdRes id: Int = View.NO_ID,
@StyleRes theme: Int = NO_THEME,
initView: ConstraintLayout.() -> Unit = {}
): ConstraintLayout {
contract { callsInPlace(initView, InvocationKind.EXACTLY_ONCE) }
return context.constraintLayout(id, theme, initView)
}
inline fun Ui.constraintLayout(
@IdRes id: Int = View.NO_ID,
@StyleRes theme: Int = NO_THEME,
initView: ConstraintLayout.() -> Unit = {}
): ConstraintLayout {
contract { callsInPlace(initView, InvocationKind.EXACTLY_ONCE) }
return ctx.constraintLayout(id, theme, initView)
}
| 0 | Kotlin | 0 | 0 | e77c909585f1b6d457af0fe18655e4794434ce50 | 1,928 | Splitties | Apache License 2.0 |
android/src/main/java/com/reactnativepedometerdetails/step/background/StepCounterService.kt | zaixiaoqu | 437,058,689 | false | {"Kotlin": 90481, "JavaScript": 2795} | package com.reactnativepedometerdetails.step.background
import android.app.PendingIntent
import android.app.Service
import android.content.*
import android.hardware.Sensor
import android.hardware.SensorEvent
import android.hardware.SensorEventListener
import android.hardware.SensorManager
import android.os.Binder
import android.os.IBinder
import android.speech.tts.TextToSpeech
import android.speech.tts.Voice
import android.util.Log
import androidx.annotation.Nullable
import java.text.SimpleDateFormat
import java.util.*
import kotlin.math.pow
import android.app.AlarmManager
import android.content.Intent
import android.content.IntentFilter
import android.content.BroadcastReceiver
import com.reactnativepedometerdetails.step.ExtCommon.StepsModel
import com.reactnativepedometerdetails.step.ExtCommon.PaseoDBHelper
class StepCounterService : Service(), SensorEventListener, TextToSpeech.OnInitListener {
private val SERVICEID = 1001
var running = false
var hasAccelerometer = true
var hasStepCounter = true
var sensorManager: SensorManager? = null
var startSteps = 0
var currentSteps = 0
var endSteps = 0
private var targetSteps = 10000 // default values for target steps (overridden later from shared preferences)
var latestDay = 0
var latestHour = 0
private var lastAccelData: FloatArray? = floatArrayOf(0f, 0f, 0f)
lateinit var paseoDBHelper : PaseoDBHelper
private var tts: TextToSpeech? = null
private var ttsAvailable = false
internal var mBinder: IBinder = LocalBinder()
// set up things for resetting steps (to zero (most of the time) at midnight
var myPendingIntent: PendingIntent? = null
var midnightAlarmManager: AlarmManager? = null
var myBroadcastReceiver: BroadcastReceiver? = null
inner class LocalBinder : Binder() {
val serverInstance: StepCounterService
get() = this@StepCounterService
}
@Nullable
override fun onBind(intent: Intent): IBinder? {
return mBinder
}
override fun onCreate() {
super.onCreate()
sensorManager = getSystemService(Context.SENSOR_SERVICE) as SensorManager
running = true
val stepsSensor = sensorManager?.getDefaultSensor(Sensor.TYPE_STEP_COUNTER)
val accelSensor = sensorManager?.getDefaultSensor(Sensor.TYPE_ACCELEROMETER)
if (stepsSensor == null) {
/* Toast.makeText(this, "No Step Counter Sensor - dropping down to Accelerometer !", Toast.LENGTH_SHORT).show()
hasStepCounter = false
if (accelSensor == null) {
Toast.makeText(this, "No Accelerometer Sensor !", Toast.LENGTH_SHORT).show()
hasAccelerometer = false
} else {
sensorManager?.registerListener(this, accelSensor, SensorManager.SENSOR_DELAY_NORMAL, SensorManager.SENSOR_DELAY_NORMAL)
}
*/ } else {
sensorManager?.registerListener(this, stepsSensor, SensorManager.SENSOR_DELAY_UI, SensorManager.SENSOR_DELAY_UI)
}
// point to the Paseo database that stores all the daily steps data
paseoDBHelper = PaseoDBHelper(this)
try {
tts = TextToSpeech(this, this)
}
catch (e: Exception) {
tts = null
}
// set the user's target:
val paseoPrefs = this.getSharedPreferences("ca.chancehorizon.paseo_preferences", 0)
targetSteps = paseoPrefs!!.getFloat("prefDailyStepsTarget", 10000F).toInt()
// set up time to reset steps - immediately (10 senconds) after midnight
val midnightAlarmCalendar: Calendar = Calendar.getInstance()
midnightAlarmCalendar.set(Calendar.HOUR_OF_DAY, 0)
midnightAlarmCalendar.set(Calendar.MINUTE, 0)
midnightAlarmCalendar.set(Calendar.SECOND, 10)
val midnightAlarmTime = midnightAlarmCalendar.getTimeInMillis()
// set up the alarm to reset steps after midnight
registerMyAlarmBroadcast()
// set alarm to repeat every day (as in every 24 hours, which should be every day immediately after midnight)
midnightAlarmManager?.setRepeating(AlarmManager.RTC, midnightAlarmTime, AlarmManager.INTERVAL_DAY, myPendingIntent)
}
override fun onInit(status: Int) {
val paseoPrefs = this.getSharedPreferences("ca.chancehorizon.paseo_preferences", 0)
// set up the text to speech voice
if (status == TextToSpeech.SUCCESS) {
val result = tts?.setLanguage(Locale.US)
if (result == TextToSpeech.LANG_MISSING_DATA ||
result == TextToSpeech.LANG_NOT_SUPPORTED) {
Log.e("TTS", "Language not supported")
}
ttsAvailable = true
} else {
Log.e("TTS", "Initialization failed")
ttsAvailable = false
}
// update shared preferences to not show first run dialog again
val edit: SharedPreferences.Editor = paseoPrefs!!.edit()
edit.putBoolean("prefTTSAvailable", ttsAvailable)
edit.apply()
// make sure that Paseo's widget and notification have up to date steps shown
updatePaseoWidget()
updatePaseoNotification()
}
// set up the alarm to reset steps after midnight (shown in widget and notification)
//
// this is done so that the number of steps shown on a new day when no steps have yet been taken (sensed)
// is reset to zero, rather than showing yesterday's step total (the number of steps shown is only updated when steps are sensed)
private fun registerMyAlarmBroadcast() {
//This is the call back function(BroadcastReceiver) which will be call when your
//alarm time will reached.
myBroadcastReceiver = object : BroadcastReceiver() {
override fun onReceive(context: Context?, intent: Intent?) {
updatePaseoWidget()
updatePaseoNotification()
}
}
registerReceiver(myBroadcastReceiver, IntentFilter("ca.chancehorizon.paseo"))
myPendingIntent = PendingIntent.getBroadcast(this.getApplicationContext(), 0, Intent("ca.chancehorizon.paseo"), PendingIntent.FLAG_IMMUTABLE)
midnightAlarmManager = this.getSystemService(ALARM_SERVICE) as AlarmManager
}
private fun UnregisterAlarmBroadcast() {
midnightAlarmManager?.cancel(myPendingIntent)
baseContext.unregisterReceiver(myBroadcastReceiver)
}
override fun onDestroy() {
// turn off step counter service
stopForeground(true)
val paseoPrefs = this.getSharedPreferences("ca.chancehorizon.paseo_preferences", 0)
val restartService = paseoPrefs!!.getBoolean("prefRestartService", true)
// turn off auto start service
if (restartService) {
val broadcastIntent = Intent()
broadcastIntent.action = "restartservice"
broadcastIntent.setClass(this, Restarter::class.java)
this.sendBroadcast(broadcastIntent)
}
// Shutdown TTS
if (tts != null) {
tts!!.stop()
tts!!.shutdown()
}
sensorManager?.unregisterListener(this)
UnregisterAlarmBroadcast()
super.onDestroy()
}
override fun onTaskRemoved(rootIntent: Intent?) {
super.onTaskRemoved(rootIntent)
stopSelf()
}
override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
startForegroundServiceWithNotification()
super.onStartCommand(intent, flags, startId)
return START_STICKY
}
private fun startForegroundServiceWithNotification() {
}
// needed for step counting (even though it is empty
override fun onAccuracyChanged(p0: Sensor?, p1: Int)
{
}
// this function is triggered whenever there is an event on the device's step counter sensor
// (steps have been detected)
override fun onSensorChanged(event: SensorEvent)
{
if (running)
{
var dateFormat = SimpleDateFormat("yyyyMMdd", Locale.getDefault()) // looks like "19891225"
val today = dateFormat.format(Date()).toInt()
dateFormat = SimpleDateFormat("HH", Locale.getDefault())
val currentHour = dateFormat.format(Date()).toInt()
if (hasStepCounter) {
// read the step count value from the devices step counter sensor
currentSteps = event.values[0].toInt()
}
// *** experimental code for using accelerometer to detect steps on devices that do not hav
// a step counter sensor (currently unused as Paseo will not install on such a device -
// based on settings in manifest)
else if (hasAccelerometer && event.sensor.type == Sensor.TYPE_ACCELEROMETER) {
lastAccelData = lowPassFilter(event.values, lastAccelData)
val accelData = AccelVector(lastAccelData!!)
if (accelData.accelVector > 12.5f) {
if (LASTDETECTION == NOSTEPDETECTED) {
currentSteps = paseoDBHelper.readLastEndSteps() + 1
}
LASTDETECTION = STEPDETECTED
} else {
LASTDETECTION = NOSTEPDETECTED
}
}
// ***
// get the latest step information from the database
if (paseoDBHelper.readRowCount() > 0) {
latestDay = paseoDBHelper.readLastStepsDate()
latestHour = paseoDBHelper.readLastStepsTime()
startSteps = paseoDBHelper.readLastStartSteps()
endSteps = paseoDBHelper.readLastEndSteps()
}
// hour is one more than last hour recorded -> add new hour record to database
if(today == latestDay && currentHour == latestHour + 1 && currentSteps >= startSteps) {
addSteps(today, currentHour, endSteps, currentSteps)
}
// add a new hour record (may be for current day or for a new day)
// also add a new record if the current steps is less than the most recent start steps (happens when phone has been rebooted)
else if (today != latestDay || currentHour != latestHour || currentSteps < startSteps) {
addSteps(today, currentHour, currentSteps, currentSteps)
}
else {
// set endSteps to current steps (update the end steps for current hour)
addSteps(today, currentHour, 0, currentSteps, true)
}
// retrieve today's step total
val theSteps = paseoDBHelper.getDaysSteps(today)
updatePaseoWidget()
updatePaseoNotification()
// check if the user has a mini goal running and update all of the values needed
checkMiniGoal()
// send message to application activity so that it can react to new steps being sensed
val local = Intent()
local.action = "ca.chancehorizon.paseo.action"
local.putExtra("data", theSteps)
this.sendBroadcast(local)
}
}
// update the number of steps shown in Paseo's widget
private fun updatePaseoWidget() {
}
// update the number of steps shown in Paseo's notification
private fun updatePaseoNotification() {
}
// *** used for detecting steps with an accelerometer sensor (on devices that do not have a step sensor)
private fun lowPassFilter(input: FloatArray?, prev: FloatArray?): FloatArray? {
val alpha = 0.1f
if (input == null || prev == null) {
return null
}
for (i in input.indices) {
prev[i] = prev[i] + alpha * (input[i] - prev[i])
}
return prev
}
// ***
// update mini goal fragement and speak alerts when goal or step interval achieved
fun checkMiniGoal() {
val paseoPrefs = this.getSharedPreferences("ca.chancehorizon.paseo_preferences", 0)
val isGoalActive = paseoPrefs!!.getBoolean("prefMiniGoalActive", false)
val useDaySteps = paseoPrefs.getBoolean("prefDaySetpsGoal", false)
val continueAnnouncing = paseoPrefs.getBoolean("prefContinueAnnounce", false)
// continue to announce mini goal progress if the goal is active (not yet achieved)
// or the user has chosen to continue announcements beyond the goal being met
if (isGoalActive || continueAnnouncing) {
// get the mini goal steps amount
val miniGoalSteps = paseoPrefs.getInt("prefMiniGoalSteps", 20)
// get the mini goal interval for text to speech announcements
val miniGoalAlertInterval = paseoPrefs.getInt("prefMiniGoalAlertInterval", 0)
// get the number of steps at which the next announcement will be spoken
var miniGoalNextAlert = paseoPrefs.getInt("prefMiniGoalNextAlert", 0)
// load the number of steps in this day at which the mini goal was started
val miniGoalStartSteps = paseoPrefs.getInt("prefMiniGoalStartSteps", 0)
val stepCount : Int
// load the current number on the devices step counter sensor
val miniGoalEndSteps = paseoDBHelper.readLastEndSteps()
// display goal step count
// default to the steps starting at zero (or use the day's set count, if user has set that option)
if (!useDaySteps) {
stepCount = miniGoalEndSteps - miniGoalStartSteps
}
// or get the current day's steps
else {
stepCount = paseoDBHelper.getDaysSteps(SimpleDateFormat("yyyyMMdd", Locale.getDefault()).format(Date()).toInt())
// start the alert steps at the beginning number of steps for the current day
if (miniGoalNextAlert < stepCount - miniGoalAlertInterval && miniGoalAlertInterval > 0) {
miniGoalNextAlert = ((stepCount + miniGoalAlertInterval)/miniGoalAlertInterval - 1) * miniGoalAlertInterval
}
}
// check if mini goal has been achieved and congratulate the user if it has
if (stepCount >= miniGoalSteps && isGoalActive) {
// update shared preferences to flag that there is no longer a mini goal running
val edit: SharedPreferences.Editor = paseoPrefs.edit()
edit.putBoolean("prefMiniGoalActive", false)
edit.apply()
speakOut("Congratulations on $miniGoalSteps steps!")
// even though the goal has been achieved, update the next alert steps when the user
// has chosen to continue announcements beyond the goal
if (continueAnnouncing) {
miniGoalNextAlert = miniGoalNextAlert + miniGoalAlertInterval
edit.putInt("prefMiniGoalNextAlert", miniGoalNextAlert)
edit.apply()
}
}
// mini goal not yet achieved (or user has chosen announcing to continue), announce mini goal progress at user selected interval
else if ((stepCount >= miniGoalNextAlert) && miniGoalAlertInterval > 0) {
// update shared preferences to save the next alert steps
val edit: SharedPreferences.Editor = paseoPrefs.edit()
speakOut("$miniGoalNextAlert steps!")
// set the next step count for an announcement
miniGoalNextAlert = miniGoalNextAlert + miniGoalAlertInterval
edit.putInt("prefMiniGoalNextAlert", miniGoalNextAlert)
edit.apply()
}
}
}
// insert or update a steps record in the Move database
fun addSteps(date: Int = 0, time: Int = 0, startSteps: Int = 0, endSteps: Int = 0, update: Boolean = false)
{
// update the endsteps for the current hour
if (update)
{
var result = paseoDBHelper.updateEndSteps(
StepsModel(0, date = date, hour = time,
startSteps = startSteps, endSteps = endSteps)
)
}
else
{
var result = paseoDBHelper.insertSteps(StepsModel(0, date = date, hour = time,
startSteps = startSteps, endSteps = endSteps))
}
latestDay = date
}
// use text to speech to "speak" some text
fun speakOut(theText : String) {
val paseoPrefs = this.getSharedPreferences("ca.chancehorizon.paseo_preferences", 0)
val ttsPitch = paseoPrefs!!.getFloat("prefVoicePitch", 100F)
val ttsRate = paseoPrefs.getFloat("prefVoiceRate", 100F)
// set the voice to use to speak with
val ttsVoice = paseoPrefs.getString("prefVoiceLanguage", "en_US - en-US-language")
val ttsLocale1 = ttsVoice!!.substring(0, 2)
val ttsLocale2 = ttsVoice.substring(3)
val voiceobj = Voice(ttsVoice, Locale(ttsLocale1, ttsLocale2), 1, 1, false, null)
tts?.voice = voiceobj
tts?.setPitch(ttsPitch / 100)
tts?.setSpeechRate(ttsRate / 100)
var ttsResult = tts?.speak(theText, TextToSpeech.QUEUE_FLUSH, null, "")
if(ttsResult == -1) {
tts = TextToSpeech(this, this)
ttsResult = tts?.speak(theText, TextToSpeech.QUEUE_FLUSH, null, "")
}
}
companion object {
private const val STEPDETECTED = 1
private const val NOSTEPDETECTED = 0
private var LASTDETECTION = NOSTEPDETECTED
}
}
// *** used to detect steps with accelermeter sensor (on devices that do not have a step sensor)
// get the full acceleration vector from the accelaration on each axis direction
class AccelVector(accelEvent: FloatArray) {
var accelX: Float
var accelY: Float
var accelZ: Float
var accelVector: Double
// calculate the full acceleration vector (kind of like calculating the hypotenuse in 3 dimensions)
init {
accelX = accelEvent[0]
accelY = accelEvent[1]
accelZ = accelEvent[2]
accelVector = Math.sqrt((accelX.pow(2) + accelY.pow(2) + accelZ.pow(2)).toDouble())
}
}
// *** | 6 | Kotlin | 9 | 7 | 77eba39e286c7799920c87a9b676e367b0810a3b | 18,394 | react-native-pedometer-details | MIT License |
composeApp/src/commonMain/kotlin/di/AppModule.kt | pramahalqavi | 765,982,999 | false | {"Kotlin": 48350, "Swift": 594} | package di
fun appModule() = listOf(
networkModule,
viewModelModule,
repositoryModule,
schedulerModule
) | 0 | Kotlin | 0 | 0 | e1a2e73532a925f599d494c59194dbb1bec8a4ee | 114 | studentfinder | MIT License |
src/main/day14/day14.kt | rolf-rosenbaum | 572,864,107 | false | null | package day14
import kotlin.math.max
import kotlin.math.min
import readInput
private typealias Cave = MutableSet<Point>
private typealias Rock = Point
private typealias Grain = Point
private data class Point(val x: Int, val y: Int)
private val source = Point(500, 0)
fun main() {
val input = readInput("main/day14/Day14_test")
println(part1(input))
println(part2(input))
}
fun part1(input: List<String>): Int {
val cave = input.parseTosSolidRock()
return cave.pourSand()
}
fun part2(input: List<String>): Int {
val cave = input.parseTosSolidRock()
val maxX = cave.maxOf { it.x } //.also { println("max x: $it") }
val minX = cave.minOf { it.x } //.also { println("min x: $it") }
val floorY = cave.maxOf { it.y } + 2
cave.addRock(Point(minX - 1500, floorY), Point(maxX + 1500, floorY))
return cave.pourSand()
}
private fun Cave.pourSand(): Int {
val startSize = size
do {
val droppedGrain = source.fall(this)
if (droppedGrain != null) add(droppedGrain)
if (size % 1000 == 0) println(size)
} while (droppedGrain != null)
return size - startSize
}
private fun Grain.fall(cave: Cave): Grain? {
if (cave.contains(source))
return null
if (down().y > cave.maxOf { it.y }) return null
if (!cave.contains(down())) return down().fall(cave)
if (!cave.contains(downLeft())) return downLeft().fall(cave)
if (!cave.contains(downRight())) return downRight().fall(cave)
return this
}
private fun Cave.addRock(start: Point, end: Point) {
val startX = min(start.x, end.x)
val startY = min(start.y, end.y)
val endX = max(start.x, end.x)
val endY = max(start.y, end.y)
(startX..endX).forEach { x ->
(startY..endY).forEach { y ->
add(Rock(x, y))
}
}
}
private fun List<String>.parseTosSolidRock(): Cave {
val cave = mutableSetOf<Point>()
map { line ->
line.split(" -> ")
.map { it.split(", ") }
.windowed(2) { (start, end) ->
cave.addRock(
rock(start.first()),
rock(end.first())
)
}
}
return cave
}
private fun rock(point: String): Rock {
return point.split(",").map { it.toInt() }.let { (x, y) ->
Point(x, y)
}
}
private fun Grain.down() = copy(y = y + 1)
private fun Grain.downLeft() = copy(x = x - 1, y = y + 1)
private fun Grain.downRight() = copy(x = x + 1, y = y + 1)
| 0 | Kotlin | 0 | 2 | a84b1e25be548bc35e269bef4f5c54eb1cf1a742 | 2,490 | aoc-2022 | Apache License 2.0 |
generator/graphql-kotlin-schema-generator/src/main/kotlin/com/expediagroup/graphql/generator/internal/types/generateGraphQLType.kt | ExpediaGroup | 148,706,161 | false | null | /*
* Copyright 2021 Expedia, Inc
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.expediagroup.graphql.generator.internal.types
import com.expediagroup.graphql.generator.SchemaGenerator
import com.expediagroup.graphql.generator.extensions.unwrapType
import com.expediagroup.graphql.generator.internal.extensions.getCustomTypeAnnotation
import com.expediagroup.graphql.generator.internal.extensions.getKClass
import com.expediagroup.graphql.generator.internal.extensions.getUnionAnnotation
import com.expediagroup.graphql.generator.internal.extensions.isEnum
import com.expediagroup.graphql.generator.internal.extensions.isInterface
import com.expediagroup.graphql.generator.internal.extensions.isListType
import com.expediagroup.graphql.generator.internal.extensions.isUnion
import com.expediagroup.graphql.generator.internal.extensions.wrapInNonNull
import graphql.schema.GraphQLType
import graphql.schema.GraphQLTypeReference
import kotlin.reflect.KClass
import kotlin.reflect.KType
/**
* Return a basic GraphQL type given all the information about the kotlin type.
*/
internal fun generateGraphQLType(generator: SchemaGenerator, type: KType, typeInfo: GraphQLKTypeMetadata = GraphQLKTypeMetadata()): GraphQLType {
val hookGraphQLType = generator.config.hooks.willGenerateGraphQLType(type)
val graphQLType = hookGraphQLType
?: generateScalar(generator, type)
?: objectFromReflection(generator, type, typeInfo)
// Do not call the hook on GraphQLTypeReference as we have not generated the type yet
val unwrappedType = graphQLType.unwrapType()
val typeWithNullability = graphQLType.wrapInNonNull(type)
if (unwrappedType !is GraphQLTypeReference) {
return generator.config.hooks.didGenerateGraphQLType(type, typeWithNullability)
}
return typeWithNullability
}
private fun objectFromReflection(generator: SchemaGenerator, type: KType, typeInfo: GraphQLKTypeMetadata): GraphQLType {
val cachedType = generator.cache.get(type, typeInfo)
if (cachedType != null) {
return cachedType
}
val kClass = type.getKClass()
return generator.cache.buildIfNotUnderConstruction(kClass, typeInfo) {
val graphQLType = getGraphQLType(generator, kClass, type, typeInfo)
generator.config.hooks.willAddGraphQLTypeToSchema(type, graphQLType)
}
}
private fun getGraphQLType(
generator: SchemaGenerator,
kClass: KClass<*>,
type: KType,
typeInfo: GraphQLKTypeMetadata
): GraphQLType {
val customTypeAnnotation = typeInfo.fieldAnnotations.getCustomTypeAnnotation()
if (customTypeAnnotation != null) {
return GraphQLTypeReference.typeRef(customTypeAnnotation.typeName)
}
return when {
kClass.isEnum() -> @Suppress("UNCHECKED_CAST") (generateEnum(generator, kClass as KClass<Enum<*>>))
kClass.isListType() -> generateList(generator, type, typeInfo)
kClass.isUnion(typeInfo.fieldAnnotations) -> generateUnion(generator, kClass, typeInfo.fieldAnnotations.getUnionAnnotation())
kClass.isInterface() -> generateInterface(generator, kClass)
typeInfo.inputType -> generateInputObject(generator, kClass)
else -> generateObject(generator, kClass)
}
}
| 21 | Kotlin | 273 | 1,420 | a0a8bad009a4ddbf88ce5c30200f90a091bd3df7 | 3,747 | graphql-kotlin | Apache License 2.0 |
src/main/kotlin/at/cpickl/gadsu/view/components/inputs/meridian.kt | christophpickl | 56,092,216 | false | null | package at.cpickl.gadsu.view.components.inputs
import at.cpickl.gadsu.tcm.model.Meridian
import at.cpickl.gadsu.view.components.panels.GridPanel
import at.cpickl.gadsu.view.logic.ChangeAware
import java.awt.Color
import java.awt.Component
import java.awt.Dimension
import java.awt.Font
import java.awt.Graphics
import java.awt.event.MouseAdapter
import java.awt.event.MouseEvent
import javax.swing.Icon
import javax.swing.JCheckBox
import javax.swing.JComponent
enum class MeridianSelectorLayout {
Horizontal,
Vertical
}
class MeridianSelector(
private val renderLayout: MeridianSelectorLayout = MeridianSelectorLayout.Vertical
) : ChangeAware {
private val checkboxes = Meridian.values().map(::MeridianCheckBox)
var selectedMeridians: List<Meridian>
get() = checkboxes.filter { it.isSelected }.map { it.meridian }
set(value) {
checkboxes.forEach {
it.isSelected = value.contains(it.meridian)
}
}
val component: JComponent by lazy {
GridPanel().apply {
checkboxes.forEachIndexed { i, checkbox ->
val isTopOrLeft = i % 2 == 0
if (isTopOrLeft) {
if (i != 0) {
if (renderLayout == MeridianSelectorLayout.Horizontal) {
c.gridx++
c.gridy = 0
} else {
c.gridx = 0
c.gridy++
}
}
} else {
if (renderLayout == MeridianSelectorLayout.Horizontal) {
c.gridy++
} else {
c.gridx++
}
}
add(checkbox)
}
}
}
override fun onChange(changeListener: () -> Unit) {
checkboxes.forEach {
it.addActionListener { changeListener() }
}
}
fun isAnySelectedMeridianDifferentFrom(treatedMeridians: List<Meridian>) =
selectedMeridians != treatedMeridians
}
private class MeridianCheckBox(val meridian: Meridian) : JCheckBox(), Icon {
companion object {
private val SIZE = 40
}
private var isOver = false
init {
isFocusable = false
preferredSize = Dimension(SIZE, SIZE)
@Suppress("LeakingThis")
icon = this
addMouseListener(object : MouseAdapter() {
override fun mouseEntered(e: MouseEvent) {
isOver = true
repaint()
}
override fun mouseExited(e: MouseEvent) {
isOver = false
repaint()
}
})
}
override fun getIconWidth() = SIZE
override fun getIconHeight() = SIZE
override fun paintIcon(c: Component, g: Graphics, x: Int, y: Int) {
val baseColor = meridian.element.color
g.color = if (isSelected) {
baseColor.darker()
} else if (isOver) {
baseColor
} else {
baseColor.brighter()
}
g.fillRect(0, 0, SIZE, SIZE)
g.color = if (isSelected) {
Color.WHITE
} else if (isOver) {
Color.GRAY
} else {
Color.GRAY.darker()
}
g.font = g.font.deriveFont(Font.BOLD, 14.0F)
g.drawString(meridian.labelShort, 10, 25)
}
}
| 43 | Kotlin | 1 | 2 | f6a84c42e1985bc53d566730ed0552b3ae71d94b | 3,464 | gadsu | Apache License 2.0 |
app/src/main/java/com/example/visuallithuanian/constants/AnimalsSingleton.kt | klaus19 | 541,931,828 | false | {"Kotlin": 778710} | package com.example.visuallithuanian.constants
import com.example.visuallithuanian.R
object AnimalsSingleton {
val hashMapAnimals = HashMap<String,Triple<String,Int,Int>>()
init {
hashMapAnimals["flight"] = Triple("skrydis", R.drawable.flight, R.raw.computer)
hashMapAnimals["fish"] = Triple("žuvis", R.drawable.fish, R.raw.computer)
hashMapAnimals["rabbit"] = Triple("triušis", R.drawable.rabbit, R.raw.computer)
hashMapAnimals["hen"] = Triple("višta", R.drawable.hen, R.raw.computer)
hashMapAnimals["deer"] = Triple("elnias", R.drawable.deer, R.raw.computer)
hashMapAnimals["goat"] = Triple("ožka", R.drawable.goat, R.raw.computer)
hashMapAnimals["zebras"] = Triple("zebras", R.drawable.zebra, R.raw.computer)
hashMapAnimals["worm"] = Triple("kirminas", R.drawable.worm, R.raw.computer)
hashMapAnimals["shark"] = Triple("Ryklys", R.drawable.shark, R.raw.computer)
hashMapAnimals["voras"] = Triple("spider", R.drawable.spider, R.raw.computer)
hashMapAnimals["seagull"] = Triple("žuvėdra", R.drawable.seagull, R.raw.computer)
hashMapAnimals["chimpanzee"] = Triple("šimpanzė", R.drawable.chimpanzee, R.raw.computer)
hashMapAnimals["crocodile"] = Triple("krokodilas", R.drawable.crocodile, R.raw.computer)
hashMapAnimals["Lions"] = Triple("Liūtas", R.drawable.lion, R.raw.computer)
hashMapAnimals["dolphin"] = Triple("delfinas", R.drawable.dolphin, R.raw.computer)
hashMapAnimals["snake"] = Triple("gyvatė", R.drawable.snake, R.raw.computer)
hashMapAnimals["donkey"] = Triple("asilas", R.drawable.donkey, R.raw.computer)
hashMapAnimals["tiger"] = Triple("tigras", R.drawable.tiger, R.raw.computer)
hashMapAnimals["mosquito"] = Triple("uodas", R.drawable.mosquito, R.raw.computer)
hashMapAnimals["pig"] = Triple("kiaulė", R.drawable.pig, R.raw.computer)
hashMapAnimals["jellyfish"] = Triple("medūza", R.drawable.jellyfish, R.raw.computer)
hashMapAnimals["bull"] = Triple("bulius", R.drawable.bull, R.raw.computer)
hashMapAnimals["gorilla"] = Triple("gorila", R.drawable.gorilla, R.raw.computer)
hashMapAnimals["elephant"] = Triple("dramblys", R.drawable.elephant, R.raw.computer)
hashMapAnimals["bird"] = Triple("paukštis", R.drawable.birds, R.raw.computer)
hashMapAnimals["sheep"] = Triple("avis", R.drawable.sheep, R.raw.computer)
hashMapAnimals["giraffe"] = Triple("žirafa", R.drawable.giraffe, R.raw.computer)
hashMapAnimals["cow"] = Triple("karvė", R.drawable.cow, R.raw.computer)
hashMapAnimals["parrot"] = Triple("papūga", R.drawable.parrot, R.raw.computer)
hashMapAnimals["bee"] = Triple("bitė", R.drawable.bee, R.raw.computer)
hashMapAnimals["monkey"] = Triple("beždžionė", R.drawable.monkey, R.raw.computer)
hashMapAnimals["chicken"] = Triple("vištiena", R.drawable.chicken, R.raw.computer)
hashMapAnimals["whale"] = Triple("banginis", R.drawable.whale, R.raw.computer)
hashMapAnimals["butterfly"] = Triple("drugelis", R.drawable.butterfly, R.raw.computer)
hashMapAnimals["kangaroo"] = Triple("kengūra", R.drawable.kangaroo, R.raw.computer)
hashMapAnimals["bear"] = Triple("meška", R.drawable.bear, R.raw.computer)
hashMapAnimals["horse"] = Triple("arklys", R.drawable.horse, R.raw.computer)
hashMapAnimals["camel"] = Triple("kupranugaris", R.drawable.camel, R.raw.computer)
hashMapAnimals["beetle"] = Triple("vabalas", R.drawable.beetle, R.raw.computer)
}
} | 10 | Kotlin | 5 | 9 | c1cea1dda2a4ae4cc21a078c1a1c83eb6b6b40d3 | 3,596 | Labas | Apache License 2.0 |
algorithm/src/androidMain/kotlin/com/alexvanyo/composelife/model/CellStateParser.android.kt | alexvanyo | 375,146,193 | false | {"Kotlin": 2414190} | /*
* Copyright 2023 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.
*/
@file:Suppress("MatchingDeclarationName")
package com.alexvanyo.composelife.model
import android.content.ClipData
import android.content.Context
import com.alexvanyo.composelife.dispatchers.ComposeLifeDispatchers
import com.alexvanyo.composelife.scopes.ApplicationContext
import kotlinx.coroutines.async
import kotlinx.coroutines.awaitAll
import kotlinx.coroutines.coroutineScope
import kotlinx.coroutines.withContext
import me.tatarka.inject.annotations.Inject
@Inject
actual class CellStateParser(
internal actual val flexibleCellStateSerializer: FlexibleCellStateSerializer,
private val dispatchers: ComposeLifeDispatchers,
private val context: @ApplicationContext Context,
) {
suspend fun parseCellState(clipData: ClipData?): DeserializationResult {
val items = clipData?.items.orEmpty()
if (items.isEmpty()) {
return DeserializationResult.Unsuccessful(
warnings = emptyList(),
errors = listOf(EmptyInput()),
)
}
return coroutineScope {
items
.map { clipDataItem ->
async {
parseCellState(clipDataItem.resolveToText())
}
}
.awaitAll()
.reduceToSuccessful()
}
}
@Suppress("InjectDispatcher")
private suspend fun ClipData.Item.resolveToText(): CharSequence =
withContext(dispatchers.IO) {
coerceToText(context)
}
}
private val ClipData.items: List<ClipData.Item> get() = List(itemCount, ::getItemAt)
| 39 | Kotlin | 11 | 136 | 6020282a962fc8207953d98c4a8077a7b08996b5 | 2,218 | composelife | Apache License 2.0 |
examples/src/jvmTest/kotlin/io/kresult/examples/test/JavaIntegrationKnitTest.kt | kresult | 871,077,263 | false | {"Kotlin": 114826} | // This file was automatically generated from OptionalExtension.kt by Knit tool. Do not edit.
package io.kresult.examples.examples.test
import kotlin.test.Test
import kotlinx.coroutines.test.runTest
class JavaIntegrationKnitTest {
@Test fun exampleJava01() = runTest {
io.kresult.examples.exampleJava01.test()
}
@Test fun exampleJava02() = runTest {
io.kresult.examples.exampleJava02.test()
}
}
| 6 | Kotlin | 1 | 2 | 25a575503212d87b79606012d239f9e78abea837 | 415 | kresult | Apache License 2.0 |
client/src/commonMain/kotlin/com/algolia/search/model/response/ResponseSearchUserID.kt | algolia | 153,273,215 | false | null | package com.algolia.search.model.response
import com.algolia.search.model.ClientDate
import com.algolia.search.serialize.KeyHits
import com.algolia.search.serialize.KeyHitsPerPage
import com.algolia.search.serialize.KeyNbHits
import com.algolia.search.serialize.KeyPage
import com.algolia.search.serialize.KeyUpdatedAt
import kotlinx.serialization.SerialName
import kotlinx.serialization.Serializable
@Serializable
public data class ResponseSearchUserID(
/**
* List of [ResponseUserID] matching the query.
*/
@SerialName(KeyHits) val hits: List<ResponseUserID>,
/**
* Number of userIDs matching the query.
*/
@SerialName(KeyNbHits) val nbHits: Int,
/**
* Current page.
*/
@SerialName(KeyPage) val page: Int,
/**
* Number of hits retrieved per page.
*/
@SerialName(KeyHitsPerPage) val hitsPerPage: Int,
/**
* Timestamp of the last update of the index
*/
@SerialName(KeyUpdatedAt) val updatedAt: ClientDate
)
| 8 | Kotlin | 11 | 43 | 1e538208c9aa109653f334ecd22a8205e294c5c1 | 999 | algoliasearch-client-kotlin | MIT License |
pcbridge-spigot/src/main/kotlin/com/projectcitybuild/DependencyContainer.kt | projectcitybuild | 42,997,941 | false | null | package com.projectcitybuild
import com.google.gson.reflect.TypeToken
import com.projectcitybuild.entities.ConfigData
import com.projectcitybuild.modules.chat.ChatBadgeFormatter
import com.projectcitybuild.modules.chat.ChatGroupFormatter
import com.projectcitybuild.modules.ranksync.actions.UpdatePlayerGroups
import com.projectcitybuild.integrations.dynmap.DynmapMarkerIntegration
import com.projectcitybuild.integrations.essentials.EssentialsIntegration
import com.projectcitybuild.integrations.gadgetsmenu.GadgetsMenuIntegration
import com.projectcitybuild.integrations.luckperms.LuckPermsIntegration
import com.projectcitybuild.pcbridge.core.modules.config.Config
import com.projectcitybuild.libs.database.DataSource
import com.projectcitybuild.pcbridge.core.modules.datetime.formatter.DateTimeFormatter
import com.projectcitybuild.pcbridge.core.modules.datetime.formatter.DateTimeFormatterImpl
import com.projectcitybuild.pcbridge.core.modules.datetime.time.LocalizedTime
import com.projectcitybuild.pcbridge.core.modules.datetime.time.Time
import com.projectcitybuild.libs.errorreporting.ErrorReporter
import com.projectcitybuild.libs.errorreporting.outputs.PrintStackTraceOutput
import com.projectcitybuild.libs.errorreporting.outputs.SentryErrorOutput
import com.projectcitybuild.libs.nameguesser.NameGuesser
import com.projectcitybuild.libs.permissions.Permissions
import com.projectcitybuild.libs.permissions.adapters.LuckPermsPermissions
import com.projectcitybuild.libs.playercache.PlayerConfigCache
import com.projectcitybuild.pcbridge.core.storage.JsonStorage
import com.projectcitybuild.modules.joinmessages.PlayerJoinTimeCache
import com.projectcitybuild.pcbridge.core.contracts.PlatformLogger
import com.projectcitybuild.pcbridge.core.contracts.PlatformScheduler
import com.projectcitybuild.pcbridge.core.contracts.PlatformTimer
import com.projectcitybuild.pcbridge.core.modules.filecache.FileCache
import com.projectcitybuild.pcbridge.http.HttpService
import com.projectcitybuild.pcbridge.webserver.HttpServer
import com.projectcitybuild.pcbridge.webserver.HttpServerConfig
import com.projectcitybuild.repositories.*
import com.projectcitybuild.support.spigot.SpigotLogger
import com.projectcitybuild.support.spigot.SpigotNamespace
import com.projectcitybuild.support.spigot.SpigotScheduler
import com.projectcitybuild.support.spigot.eventbroadcast.LocalEventBroadcaster
import com.projectcitybuild.support.spigot.eventbroadcast.SpigotLocalEventBroadcaster
import com.projectcitybuild.support.spigot.listeners.SpigotListenerRegistry
import com.projectcitybuild.support.spigot.SpigotServer
import com.projectcitybuild.support.spigot.SpigotTimer
import org.bukkit.Server
import org.bukkit.plugin.java.JavaPlugin
import java.time.Clock
import java.time.ZoneId
import java.util.Locale
import kotlin.coroutines.CoroutineContext
import java.util.logging.Logger as JavaLogger
class DependencyContainer(
val plugin: JavaPlugin,
val server: Server,
val spigotLogger: JavaLogger,
val minecraftDispatcher: CoroutineContext,
) {
val config: Config<ConfigData> by lazy {
Config(
default = ConfigData.default,
jsonStorage = JsonStorage(
file = plugin.dataFolder.resolve("config.json"),
logger = logger,
typeToken = object : TypeToken<ConfigData>(){},
),
)
}
// TODO: inject config instead of the config keys, otherwise flushing the cache
// will never do anything
val dateTimeFormatter: DateTimeFormatter
get() = DateTimeFormatterImpl(
locale = Locale.forLanguageTag(
config.get().localization.locale,
),
timezone = ZoneId.of(
config.get().localization.timeZone
),
)
val time: Time
get() = LocalizedTime(
clock = Clock.system(
ZoneId.of(config.get().localization.timeZone),
),
)
val logger: PlatformLogger
get() = SpigotLogger(spigotLogger)
val scheduler: PlatformScheduler
get() = SpigotScheduler(plugin)
val timer: PlatformTimer by lazy {
SpigotTimer(plugin)
}
val errorReporter: ErrorReporter by lazy {
ErrorReporter(
outputs = listOf(
SentryErrorOutput(config, logger),
PrintStackTraceOutput(),
)
)
}
val dataSource by lazy {
DataSource(
logger = logger,
hostName = config.get().database.hostName,
port = config.get().database.port,
databaseName = config.get().database.name,
username = config.get().database.username,
password = <PASSWORD>,
shouldRunMigrations = true,
)
}
val listenerRegistry by lazy {
SpigotListenerRegistry(
plugin,
logger,
)
}
val localEventBroadcaster: LocalEventBroadcaster
get() = SpigotLocalEventBroadcaster(scheduler)
val spigotServer: SpigotServer
get() = SpigotServer(server)
val nameGuesser
get() = NameGuesser()
val permissions: Permissions by lazy {
LuckPermsPermissions(logger)
}
val chatGroupFormatter by lazy {
ChatGroupFormatter(
permissions,
config,
)
}
val chatBadgeFormatter by lazy {
ChatBadgeFormatter(
playerConfigRepository,
chatBadgeRepository,
config,
)
}
private val httpService by lazy {
HttpService(
authToken = config.get().api.token,
baseURL = config.get().api.baseUrl,
withLogging = config.get().api.isLoggingEnabled,
contextBuilder = { minecraftDispatcher },
)
}
val webServer by lazy {
HttpServer(
config = HttpServerConfig(
authToken = config.get().webServer.token,
port = config.get().webServer.port,
),
delegate = WebServerDelegate(
scheduler,
server,
logger,
UpdatePlayerGroups(
permissions,
playerGroupRepository,
),
),
logger = logger,
)
}
val spigotNamespace get() = SpigotNamespace(plugin)
val playerJoinTimeCache by lazy {
PlayerJoinTimeCache(time)
}
/**
* Repositories
*/
val chatBadgeRepository by lazy {
ChatBadgeRepository()
}
val playerConfigCache by lazy {
PlayerConfigCache()
}
val playerConfigRepository by lazy {
PlayerConfigRepository(
cache = playerConfigCache,
dataSource,
)
}
val playerBanRepository by lazy {
PlayerBanRepository(httpService.uuidBan)
}
val playerUUIDRepository by lazy {
PlayerUUIDRepository(
server,
httpService.playerUuid,
)
}
val playerGroupRepository by lazy {
PlayerGroupRepository(
httpService.playerGroup,
config,
logger,
)
}
val playerWarningRepository by lazy {
PlayerWarningRepository(
httpService.playerWarning,
)
}
val ipBanRepository by lazy {
IPBanRepository(
httpService.ipBan,
)
}
val warpRepository by lazy {
WarpRepository(dataSource)
}
val aggregateRepository by lazy {
AggregateRepository(
httpService.aggregate,
)
}
val telemetryRepository by lazy {
TelemetryRepository(
httpService.telemetry,
)
}
private val currencyRepository by lazy {
CurrencyRepository(
httpService.currency,
)
}
val verificationURLRepository by lazy {
VerificationURLRepository(
httpService.verificationURL,
)
}
val scheduledAnnouncementsRepository by lazy {
ScheduledAnnouncementsRepository(
config,
FileCache(
JsonStorage(
file = plugin.dataFolder.resolve("cache/scheduled_announcements.json"),
logger = logger,
typeToken = object : TypeToken<ScheduledAnnouncements>(){},
),
),
)
}
/**
* Integrations
*/
val dynmapIntegration by lazy {
DynmapMarkerIntegration(
plugin,
warpRepository,
config,
logger,
)
}
val essentialsIntegration by lazy {
EssentialsIntegration(
plugin,
logger,
)
}
val gadgetsMenuIntegration by lazy {
GadgetsMenuIntegration(
plugin,
logger,
currencyRepository,
)
}
val luckPermsIntegration by lazy {
LuckPermsIntegration(
plugin,
logger,
chatGroupFormatter,
)
}
}
| 9 | Kotlin | 0 | 3 | 8d28ab2bd10ef2dde00d7d5772ff0a5ea94c0a2b | 9,132 | PCBridge | MIT License |
ontrack-extension-github/src/main/java/net/nemerosa/ontrack/extension/github/ingestion/config/parser/ConfigParser.kt | nemerosa | 19,351,480 | false | null | package net.nemerosa.ontrack.extension.github.ingestion.config.parser
import com.fasterxml.jackson.databind.ObjectMapper
import com.fasterxml.jackson.dataformat.yaml.YAMLFactory
import com.fasterxml.jackson.dataformat.yaml.YAMLGenerator
import net.nemerosa.ontrack.extension.github.ingestion.config.model.IngestionConfig
import net.nemerosa.ontrack.extension.github.ingestion.config.model.IngestionConfig.Companion.V1_VERSION
import net.nemerosa.ontrack.extension.github.ingestion.config.model.IngestionConfig.Companion.V2_VERSION
import net.nemerosa.ontrack.json.getTextField
object ConfigParser {
private const val FIELD_VERSION = "version"
private val yamlFactory = YAMLFactory().apply {
enable(YAMLGenerator.Feature.LITERAL_BLOCK_STYLE)
}
private val mapper = ObjectMapper(yamlFactory)
fun parseYaml(yaml: String): IngestionConfig =
try {
val json = mapper.readTree(yaml)
// Gets the version from the JSON
val version = json.getTextField(FIELD_VERSION)
// Gets the parser from the version
val parser: JsonConfigParser = when {
version == V1_VERSION -> ConfigV1Parser
version == V2_VERSION -> ConfigV2Parser
version.isNullOrBlank() -> ConfigOldParser
else -> throw ConfigVersionException(version)
}
// Parsing
parser.parse(json)
} catch (ex: Exception) {
throw ConfigParsingException(ex)
}
/**
* Renders the [config][ingestion config] as a YAML document.
*/
fun toYaml(config: IngestionConfig): String =
mapper.writeValueAsString(config)
} | 58 | null | 27 | 97 | 7c71a3047401e088ba0c6d43aa3a96422024857f | 1,700 | ontrack | MIT License |
next/kmp/window/src/commonMain/kotlin/org/dweb_browser/sys/window/core/WindowRenderHelper.kt | BioforestChain | 594,577,896 | false | null | package org.dweb_browser.sys.window.core
import androidx.compose.foundation.BorderStroke
import androidx.compose.foundation.layout.PaddingValues
import androidx.compose.foundation.layout.RowScope
import androidx.compose.foundation.layout.WindowInsets
import androidx.compose.foundation.layout.requiredSize
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.ArrowBackIosNew
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Scaffold
import androidx.compose.material3.Surface
import androidx.compose.material3.Text
import androidx.compose.material3.TopAppBar
import androidx.compose.material3.TopAppBarDefaults
import androidx.compose.material3.TopAppBarScrollBehavior
import androidx.compose.material3.contentColorFor
import androidx.compose.runtime.Composable
import androidx.compose.runtime.DisposableEffect
import androidx.compose.runtime.Stable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.scale
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.input.nestedscroll.nestedScroll
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.unit.Dp
import androidx.compose.ui.unit.dp
import kotlinx.coroutines.launch
import org.dweb_browser.helper.randomUUID
import org.dweb_browser.sys.window.render.LocalWindowController
import org.dweb_browser.sys.window.render.watchedState
@OptIn(ExperimentalMaterial3Api::class)
@Composable
private fun WindowContentScaffoldWrapper(
renderScope: WindowContentRenderScope,
modifier: Modifier = Modifier,
scrollBehavior: TopAppBarScrollBehavior,
topBar: @Composable () -> Unit = {},
containerColor: Color? = null,
contentColor: Color? = null,
content: @Composable (PaddingValues) -> Unit,
) {
Scaffold(
modifier = modifier.withRenderScope(renderScope)
.nestedScroll(scrollBehavior.nestedScrollConnection),
// TODO 添加 ime 的支持
contentWindowInsets = WindowInsets(0),
topBar = {
topBar()
},
containerColor = containerColor ?: MaterialTheme.colorScheme.background,
contentColor = contentColor ?: contentColorFor(MaterialTheme.colorScheme.background),
content = { innerPadding ->
content(innerPadding)
},
)
}
@Stable
fun Modifier.withRenderScope(renderScope: WindowContentRenderScope) = when (renderScope) {
WindowContentRenderScope.Unspecified -> this
else -> renderScope.run {
[email protected](widthDp / scale, heightDp / scale).scale(scale)// 原始大小
}
}
@Composable
fun WindowController.GoBackButton() {
val uiScope = rememberCoroutineScope()
val win = this
val goBackButtonId = remember { randomUUID() }
/// 我们允许 WindowContentScaffold 在一个 win 中多次使用,比方说响应式布局中,将多个路由页面同时展示
/// 这时候我们会有多个 TopBar 在同时渲染,而为了让 GoBackButton 只出现一个
/// 我们将 goBackButtonId 放到一个数组中,第一个id获得 GoBackButton 的渲染权
/// 因此页面的渲染顺序很重要
DisposableEffect(goBackButtonId) {
win.navigation.goBackButtonStack.add(goBackButtonId)
onDispose {
win.navigation.goBackButtonStack.remove(goBackButtonId)
}
}
val canGoBack by win.watchedState { canGoBack }
if (canGoBack == true && win.navigation.goBackButtonStack.lastOrNull() == goBackButtonId) {
IconButton(onClick = {
// TODO 提供导航功能
uiScope.launch { win.navigation.emitGoBack() }
}) {
Icon(
imageVector = Icons.Default.ArrowBackIosNew,
contentDescription = "Go Back",
)
}
}
}
@Composable
fun WindowContentRenderScope.WindowSurface(
modifier: Modifier = Modifier,
tonalElevation: Dp = 0.dp,
shadowElevation: Dp = 0.dp,
color: Color? = null,
contentColor: Color? = null,
border: BorderStroke? = null,
content: @Composable () -> Unit,
) {
Surface(
modifier = modifier.withRenderScope(this),
tonalElevation = tonalElevation,
shadowElevation = shadowElevation,
color = color ?: MaterialTheme.colorScheme.background,
contentColor = contentColor ?: contentColorFor(MaterialTheme.colorScheme.background),
border = border,
content = content,
)
}
@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun WindowContentRenderScope.WindowContentScaffold(
modifier: Modifier = Modifier,
scrollBehavior: TopAppBarScrollBehavior,
topBar: @Composable () -> Unit,
containerColor: Color? = null,
contentColor: Color? = null,
content: @Composable (PaddingValues) -> Unit,
) {
WindowContentScaffoldWrapper(
this,
modifier,
scrollBehavior = scrollBehavior,
topBar = topBar,
containerColor = containerColor,
contentColor = contentColor,
content = content,
)
}
@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun WindowContentRenderScope.WindowContentScaffoldWithTitle(
modifier: Modifier = Modifier,
topBarTitle: @Composable (scrollBehavior: TopAppBarScrollBehavior) -> Unit = {},
topBarActions: @Composable RowScope.() -> Unit = {},
containerColor: Color? = null,
contentColor: Color? = null,
content: @Composable (PaddingValues) -> Unit,
) {
val scrollBehavior = TopAppBarDefaults.pinnedScrollBehavior()
WindowContentScaffoldWrapper(
this,
modifier,
scrollBehavior = scrollBehavior,
topBar = {
val win = LocalWindowController.current
TopAppBar(
title = { topBarTitle(scrollBehavior) },
windowInsets = WindowInsets(0),
actions = topBarActions,
navigationIcon = { win.GoBackButton() },
scrollBehavior = scrollBehavior,
)
},
containerColor = containerColor,
contentColor = contentColor,
content = content,
)
}
@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun WindowContentRenderScope.WindowContentScaffoldWithTitleText(
modifier: Modifier = Modifier,
topBarTitleText: String,
topBarActions: @Composable RowScope.() -> Unit = {},
containerColor: Color? = null,
contentColor: Color? = null,
content: @Composable (PaddingValues) -> Unit,
) {
WindowContentScaffoldWithTitle(
modifier,
topBarTitle = {
Text(topBarTitleText, maxLines = 1, overflow = TextOverflow.Ellipsis)
},
topBarActions = topBarActions,
containerColor = containerColor,
contentColor = contentColor,
content = content,
)
} | 66 | null | 5 | 20 | 6db1137257e38400c87279f4ccf46511752cd45a | 6,468 | dweb_browser | MIT License |
app/src/main/java/com/example/fluxcode/network/persistence/repositories/BoardRepository.kt | bonoOpalfvens | 226,171,783 | false | null | package com.example.fluxcode.network.persistence.repositories
import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.Transformations
import com.example.fluxcode.domain.Board
import com.example.fluxcode.domain.Post
import com.example.fluxcode.network.CodeApi
import com.example.fluxcode.network.persistence.LocalDB
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
class BoardRepository(private val database: LocalDB) {
val boards: LiveData<List<Board>> =
Transformations.map(database.boardDAO.getTopBoards()){ it.map { b -> b.toDomain() } }
val selectedBoard = MutableLiveData<Board>()
val selectedPosts = MutableLiveData<List<Post>>()
suspend fun refreshBoards() {
withContext(Dispatchers.IO){
val response = CodeApi.retrofitService.getTopBoards()
if(response.isSuccessful) {
val boards = response.body()
boards?.forEach {
database.boardDAO.insertBoard(it.toDBO())
}
}else{
throw Exception("${response.code()}: ${response.message()}")
}
}
}
suspend fun loadBoardById(id: Int) {
withContext(Dispatchers.Main){
val response = CodeApi.retrofitService.getBoardById(id)
if(response.isSuccessful) {
val board = response.body()
withContext(Dispatchers.IO){
database.boardDAO.insertBoard(board!!.toDBO())
board.posts.forEach {
database.postDAO.insertPost(it.toDBO(board.id))
database.postDAO.insertUser(it.user.toDBO())
}
}
selectedBoard.value = board?.toDomain()
selectedPosts.value = board?.toDomain()?.posts
}else{
throw Exception("${response.code()}: ${response.message()}")
}
}
}
} | 0 | Kotlin | 0 | 0 | d50b7d7d76859697c05ccdfc7da091fed2056826 | 2,012 | Android_Code | Apache License 2.0 |
src/速習Kotlin/part1_3/null_cond.kt | JunichiMuto | 217,814,994 | false | null | package 速習Kotlin.part1_3
fun main() {
//セーフコール演算子
var str:String? = "あいうえお"
println(str?.length) //5
var str2:String? = null
println(str2?.length) //null
//スマートキャスト
if(str != null) println(str.length) //5
} | 0 | Kotlin | 0 | 0 | 9bf1d91cdc2d127d758a01d3747d9d7df0b47a2d | 237 | Kotlin-Study | MIT License |
browser-kotlin/src/jsMain/kotlin/web/animations/AnimationEvent.types.deprecated.kt | karakum-team | 393,199,102 | false | {"Kotlin": 6891970} | // Automatically generated - do not modify!
@file:Suppress(
"NON_ABSTRACT_MEMBER_OF_EXTERNAL_INTERFACE",
)
package web.animations
import seskar.js.JsValue
import web.events.EventTarget
import web.events.EventType
sealed external interface AnimationEventTypes_deprecated {
@Deprecated(
message = "Legacy type declaration. Use type function instead!",
replaceWith = ReplaceWith("AnimationEvent.animationCancel()"),
)
@JsValue("animationcancel")
val ANIMATION_CANCEL: EventType<AnimationEvent<EventTarget>>
get() = definedExternally
@Deprecated(
message = "Legacy type declaration. Use type function instead!",
replaceWith = ReplaceWith("AnimationEvent.animationEnd()"),
)
@JsValue("animationend")
val ANIMATION_END: EventType<AnimationEvent<EventTarget>>
get() = definedExternally
@Deprecated(
message = "Legacy type declaration. Use type function instead!",
replaceWith = ReplaceWith("AnimationEvent.animationIteration()"),
)
@JsValue("animationiteration")
val ANIMATION_ITERATION: EventType<AnimationEvent<EventTarget>>
get() = definedExternally
@Deprecated(
message = "Legacy type declaration. Use type function instead!",
replaceWith = ReplaceWith("AnimationEvent.animationStart()"),
)
@JsValue("animationstart")
val ANIMATION_START: EventType<AnimationEvent<EventTarget>>
get() = definedExternally
}
| 0 | Kotlin | 7 | 28 | 8b3f4024ebb4f67e752274e75265afba423a8c38 | 1,474 | types-kotlin | Apache License 2.0 |
app/src/main/java/com/example/tmdbclient/presentation/artist/ArtistAdapter.kt | Suraj820 | 615,681,119 | false | null | package com.example.tmdbclient.presentation.artist
import android.view.LayoutInflater
import android.view.ViewGroup
import androidx.databinding.DataBindingUtil
import androidx.recyclerview.widget.RecyclerView
import com.bumptech.glide.Glide
import com.example.tmdbclient.R
import com.example.tmdbclient.data.model.artist.Artist
import com.example.tmdbclient.databinding.ListItemBinding
class ArtistAdapter : RecyclerView.Adapter<ViewHolder>() {
private val artistList = ArrayList<Artist>()
fun setList(artist: List<Artist>) {
artistList.clear()
artistList.addAll(artist)
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
val layoutInflater = LayoutInflater.from(parent.context)
val binding :ListItemBinding = DataBindingUtil.inflate(
layoutInflater,
R.layout.list_item,
parent,
false
)
return ViewHolder(binding)
}
override fun getItemCount(): Int {
return artistList.size
}
override fun onBindViewHolder(holder: ViewHolder, position: Int) {
holder.bind(artistList[position])
}
}
class ViewHolder (private val binding: ListItemBinding): RecyclerView.ViewHolder(binding.root){
fun bind(artist: Artist){
binding.titleTextView.text = artist.name
binding.descriptionTextView.text= artist.popularity.toString()
val posterURL = "https://image.tmdb.org/t/p/w500"+artist.profilePath
//Pass this from out side of the class
Glide.with(binding.imageView.context)
.load(posterURL)
.into(binding.imageView)
}
} | 0 | Kotlin | 0 | 0 | 089ed65b55853c82dc9c96e67b2a9586276137ce | 1,658 | TMDBClient | MIT License |
app/src/main/java/com/artemchep/literaryclock/utils/ext/BuildExt.kt | AChep | 160,681,782 | false | {"Kotlin": 130814} | package com.artemchep.literaryclock.utils.ext
import com.artemchep.literaryclock.BuildConfig
/**
* Executes the block if this build is
* debug.
*/
inline fun ifDebug(crossinline block: () -> Unit) {
if (BuildConfig.DEBUG) {
block()
}
}
| 4 | Kotlin | 0 | 8 | 0a067570b49474a049960d892a72749ca3cb903c | 257 | literaryclock | Apache License 2.0 |
app/src/main/java/com/shopapp/ui/order/list/router/OrderListRouter.kt | rubygarage | 105,554,295 | false | null | package com.shopapp.ui.order.list.router
import android.content.Context
import com.shopapp.gateway.entity.ProductVariant
import com.shopapp.ui.home.HomeActivity
import com.shopapp.ui.order.details.OrderDetailsActivity
import com.shopapp.ui.product.ProductDetailsActivity
class OrderListRouter {
fun showProduct(context: Context?, variant: ProductVariant) {
context?.let { it.startActivity(ProductDetailsActivity.getStartIntent(it, variant)) }
}
fun showHome(context: Context?, isNewTask: Boolean = false) {
context?.let { it.startActivity(HomeActivity.getStartIntent(it, isNewTask)) }
}
fun showOrder(context: Context?, id: String) {
context?.let { it.startActivity(OrderDetailsActivity.getStartIntent(it, id)) }
}
} | 6 | Kotlin | 100 | 148 | 133b0060626a064b437683c3f0182d2bb3066bdb | 769 | shopapp-android | Apache License 2.0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.