path
stringlengths
4
280
owner
stringlengths
2
39
repo_id
int64
21.1k
879M
is_fork
bool
2 classes
languages_distribution
stringlengths
13
1.95k
content
stringlengths
7
482k
issues
int64
0
13.9k
main_language
stringclasses
121 values
forks
stringlengths
1
5
stars
int64
0
111k
commit_sha
stringlengths
40
40
size
int64
7
482k
name
stringlengths
1
100
license
stringclasses
93 values
src/main/kotlin/com/sbg/vindinium/kindinium/model/board/MetaBoard.kt
SoulBeaver
23,961,494
false
null
package com.sbg.vindinium.kindinium.model.board import java.util.HashMap import java.util.ArrayList import sun.reflect.generics.reflectiveObjects.NotImplementedException import java.util.Queue import java.util.PriorityQueue import com.sbg.vindinium.kindinium.model.Position import com.sbg.vindinium.kindinium.paired import java.util.SortedMap /** * The Meta Board represents the board in greater detail, revealing the position of many unique * objects on the map and routes to each object from an arbitrary position. */ data class MetaBoard(val board: Board) { private val structuredMap: ArrayList<ArrayList<BoardTile>> private val importantTiles: Map<BoardTile, ArrayList<Position>> private val boardNavigator: BoardNavigator /** * Return the position of the specified hero. */ fun hero(symbol: String): Position = hero(toBoardTile(symbol)) fun hero(boardTile: BoardTile): Position = importantTiles[boardTile]!!.single() /** * Return the position of any neutral mine. */ fun neutralMines(): List<Position> = importantTiles[BoardTile.NEUTRAL_GOLD_MINE]!! /** * Return the position of any mine owned by the specified hero. */ fun minesOwnedBy(symbol: String): List<Position> = minesOwnedBy(toBoardTile(symbol.replace("@", "$"))) fun minesOwnedBy(boardTile: BoardTile): List<Position> = importantTiles[boardTile]!! /** * Return the position of all mines. */ fun allMines(): List<Position> = neutralMines() + minesOwnedBy("@1") + minesOwnedBy("@2") + minesOwnedBy("@3") + minesOwnedBy("@4") /** * Return the position of all taverns. */ fun taverns(): List<Position> = importantTiles[BoardTile.TAVERN]!! /** * Plots a path, if possible, to the nearest neutral mine. */ fun nearestNeutralMine(from: Position): Path? = boardNavigator.pathToNearest(neutralMines(), from) /** * Plots a path, if possible, to the nearest mine. */ fun nearestMine(from: Position): Path? = boardNavigator.pathToNearest(allMines(), from) /** * Plots a path, if possible, to the nearest tavern. */ fun nearestTavern(from: Position): Path? = boardNavigator.pathToNearest(taverns(), from) /** * Plots a path, if possible, from `from` to `to`. */ fun pathTo(from: Position, to: Position): Path? = boardNavigator.pathTo(to, from) /** * Return the BoardTile at the given location. * * Alternative syntax: * * metaboard[0, 0] // or metaboard[Position(0, 0)] */ fun get(x: Int, y: Int): BoardTile { return get(Position(x, y)) } fun get(position: Position): BoardTile { return structuredMap[position.y][position.x] } { structuredMap = ArrayList<ArrayList<BoardTile>>() importantTiles = hashMapOf( BoardTile.HERO_ONE to arrayListOf(), BoardTile.HERO_TWO to arrayListOf(), BoardTile.HERO_THREE to arrayListOf(), BoardTile.HERO_FOUR to arrayListOf(), BoardTile.TAVERN to arrayListOf(), BoardTile.NEUTRAL_GOLD_MINE to arrayListOf(), BoardTile.HERO_ONE_GOLD_MINE to arrayListOf(), BoardTile.HERO_TWO_GOLD_MINE to arrayListOf(), BoardTile.HERO_THREE_GOLD_MINE to arrayListOf(), BoardTile.HERO_FOUR_GOLD_MINE to arrayListOf(), BoardTile.ROAD to arrayListOf(), BoardTile.IMPASSABLE_WOOD to arrayListOf() ) boardNavigator = BoardNavigator(this) var i = 0 while (i != board.tiles.size) { if (i % (board.size * 2) == 0) structuredMap.add(arrayListOf()) val left = board.tiles[i] val right = board.tiles[i + 1] structuredMap.last!!.add(toBoardTile("$left$right")) i += 2 } for ((y, row) in structuredMap.withIndices()) { for ((x, tile) in row.withIndices()) { importantTiles[tile]!!.add(Position(x, y)) } } } override fun toString(): String { return StringBuilder() { for (row in structuredMap) appendln(row.fold("") { reconstructed, part -> reconstructed + part }) }.toString() } }
0
Kotlin
1
4
9150d6619229db4932494e95c92f6911a7dd3443
4,348
kindinium
Apache License 2.0
core/data/local/src/main/java/com/fappslab/mbchallenge/core/data/local/model/extension/MapperExtension.kt
F4bioo
845,138,188
false
{"Kotlin": 242545}
package com.fappslab.mbchallenge.core.data.local.model.extension import com.fappslab.mbchallenge.core.data.local.model.ExchangeEntity import com.fappslab.mbchallenge.core.domain.model.Exchange internal fun ExchangeEntity.toExchange(): Exchange { return Exchange( exchangeId = exchangeId, website = website, name = name, dataQuoteStart = dataQuoteStart, dataQuoteEnd = dataQuoteEnd, dataOrderBookStart = dataOrderBookStart, dataOrderBookEnd = dataOrderBookEnd, dataTradeStart = dataTradeStart, dataTradeEnd = dataTradeEnd, dataSymbolsCount = dataSymbolsCount, volume1hrsUsd = volume1hrsUsd, volume1dayUsd = volume1dayUsd, volume1mthUsd = volume1mthUsd, iconUrl = iconUrl, isEditorChoice = isEditorsChoice ) } internal fun Exchange.toExchangeEntity(): ExchangeEntity { return ExchangeEntity( exchangeId = exchangeId, website = website, name = name, dataQuoteStart = dataQuoteStart, dataQuoteEnd = dataQuoteEnd, dataOrderBookStart = dataOrderBookStart, dataOrderBookEnd = dataOrderBookEnd, dataTradeStart = dataTradeStart, dataTradeEnd = dataTradeEnd, dataSymbolsCount = dataSymbolsCount, volume1hrsUsd = volume1hrsUsd, volume1dayUsd = volume1dayUsd, volume1mthUsd = volume1mthUsd, iconUrl = iconUrl, isEditorsChoice = isEditorChoice ) } internal fun List<ExchangeEntity>.toExchangeList(): List<Exchange> { return map { it.toExchange() } } internal fun List<Exchange>.toExchangeListEntity(): List<ExchangeEntity> { return map { it.toExchangeEntity() } }
0
Kotlin
0
0
d81eff4b566578b5dc8596b7cbfcfb2e12e652b6
1,720
MBChallenge
MIT License
core/domain/src/main/java/cc/cryptopunks/crypton/interactor/StorePresence.kt
cryptopunkscc
202,181,919
false
{"Kotlin": 523158, "Shell": 6362}
package cc.cryptopunks.crypton.interactor import cc.cryptopunks.crypton.context.Presence import cc.cryptopunks.crypton.context.SessionScope internal suspend fun SessionScope.storePresence(presence: Presence) = presenceStore reduce { plus(presence.resource.address to presence) }
9
Kotlin
2
7
33dc96367c3a4eb869800b6a0ac84f302bd68502
286
crypton
MIT License
app/src/main/java/com/breezefsmparas/features/newcollectionreport/PendingCollListner.kt
DebashisINT
646,827,078
false
{"Kotlin": 15132793, "Java": 1023856}
package com.breezefsmparas.features.newcollectionreport import com.breezefsmparas.features.photoReg.model.UserListResponseModel interface PendingCollListner { fun getUserInfoOnLick(obj: PendingCollData) }
0
Kotlin
0
0
b3a654585537264aaec676ba124110e998983033
210
ParasPanMasala
Apache License 2.0
save-cloud-common/src/commonMain/kotlin/com/saveourtool/save/filters/ProjectFilters.kt
saveourtool
300,279,336
false
null
package com.saveourtool.save.filters import com.saveourtool.save.entities.ProjectStatus import kotlinx.serialization.Serializable /** * @property name substring that match the beginning of a name * @property statuses current [statuses] of an organization * @property organizationName */ @Serializable data class ProjectFilters( val name: String, val organizationName: String = "", val statuses: Set<ProjectStatus> = setOf(ProjectStatus.CREATED), ) { companion object { val created = ProjectFilters(name = "") /** * The filter which returns projects with any status, not just * [ProjectStatus.CREATED]. */ val any = ProjectFilters( name = "", statuses = enumValues<ProjectStatus>().toSet(), ) } }
160
Kotlin
1
31
d83a26b101c0f809d39a6deab4e183de04cc7832
806
save-cloud
MIT License
src/main/kotlin/me/pi3ro/pvplounge/menu/ServerSelectorMenu.kt
Pi3ro
694,412,154
false
{"Kotlin": 19803}
package me.pi3ro.pvplounge.menu import me.pi3ro.pvplounge.PvPLounge import me.pi3ro.pvplounge.utils.ItemBuilder import me.pi3ro.pvplounge.utils.Utils import me.pi3ro.pvplounge.utils.menu.Button import me.pi3ro.pvplounge.utils.menu.Menu import me.clip.placeholderapi.PlaceholderAPI import org.bukkit.Bukkit import org.bukkit.Material import org.bukkit.entity.Player import org.bukkit.event.inventory.ClickType import org.bukkit.inventory.ItemStack /** * Created by: Pi3ro * Project: PvPLoungeHub * Date: 2023-09-14 @ 05:04 **/ class ServerSelectorMenu : Menu() { override fun getTitle(player: Player?): String? { return Utils.translate(PvPLounge.getInstance().config.getString("SERVERS.TITLE")) } override fun getButtons(player: Player?): MutableMap<Int, Button?> { val buttons: MutableMap<Int, Button?> = HashMap() for (i in 1..9) { val config = PvPLounge.getInstance().config.getConfigurationSection("SERVERS.SERVER_$i") if (config != null) { val serverButton = ServerButton(i) val slot = config.getInt("SLOT") buttons[slot] = serverButton } } val leaveButton = LeaveButton() val leaveSlot = PvPLounge.getInstance().config.getInt("SERVERS.LEAVE.SLOT") buttons[leaveSlot] = leaveButton return buttons } inner class ServerButton(private val serverNumber: Int) : Button() { override fun getButtonItem(viewer: Player?): ItemStack { val serverConfig = PvPLounge.getInstance().config.getConfigurationSection("SERVERS.SERVER_$serverNumber") val loreList = serverConfig.getStringList("LORE").map { PlaceholderAPI.setPlaceholders(viewer, it) } return ItemBuilder(Material.getMaterial(serverConfig.getString("ITEM"))) .setDisplayName(serverConfig.getString("TITLE")) .setDurability(serverConfig.getInt("DURABILITY")) .setLore(loreList) .clearFlags() .build() } override fun clicked(player: Player?, clickType: ClickType?) { Utils.sendToServer(player!!, PvPLounge.getInstance().config.getString("SERVERS.SERVER_$serverNumber.SEND-SERVER")) } } inner class LeaveButton : Button() { override fun getButtonItem(viewer: Player?): ItemStack { val leaveConfig = PvPLounge.getInstance().config.getConfigurationSection("SERVERS.LEAVE") return ItemBuilder(Material.getMaterial(leaveConfig.getString("ITEM"))) .setDisplayName(leaveConfig.getString("TITLE")) .setDurability(leaveConfig.getInt("DURABILITY")) .setLore(leaveConfig.getStringList("LORE")) .clearFlags() .build() } override fun clicked(player: Player?, clickType: ClickType?) { player!!.kickPlayer( Utils.translate( PvPLounge.getInstance().config.getString("SERVERS.LEAVE.MESSAGE") )) } } override fun onClose(player: Player?) { Bukkit.getScheduler().runTaskLater(PvPLounge.getInstance(), Runnable { openMenu(player!!) }, 5L) } }
0
Kotlin
0
0
2c09b77be8dcf91a273ce5bbfe3cbe4364d450f7
3,270
PvPLoungeHub
Apache License 2.0
src/main/kotlin/com/github/dxahtepb/etcdidea/view/SingleSelectionTable.kt
dxahtepb
300,450,509
false
null
package com.github.dxahtepb.etcdidea.view import com.intellij.ui.table.JBTable import javax.swing.ListSelectionModel import javax.swing.table.TableModel class SingleSelectionTable(tableModel: TableModel) : JBTable(tableModel) { init { dragEnabled = false tableHeader.reorderingAllowed = false columnSelectionAllowed = false selectionModel.selectionMode = ListSelectionModel.SINGLE_SELECTION } }
0
Kotlin
0
3
4579b6666382a6bb460d9564bba3908d6e14793d
437
etcd-idea
Apache License 2.0
vuesaxicons/src/commonMain/kotlin/moe/tlaster/icons/vuesax/vuesaxicons/crypto/bulk/Frame.kt
Tlaster
560,394,734
false
{"Kotlin": 25133302}
package moe.tlaster.icons.vuesax.vuesaxicons.crypto.bulk import androidx.compose.ui.graphics.Color import androidx.compose.ui.graphics.PathFillType import androidx.compose.ui.graphics.PathFillType.Companion.NonZero import androidx.compose.ui.graphics.SolidColor import androidx.compose.ui.graphics.StrokeCap import androidx.compose.ui.graphics.StrokeCap.Companion.Butt import androidx.compose.ui.graphics.StrokeJoin 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 moe.tlaster.icons.vuesax.vuesaxicons.crypto.BulkGroup public val BulkGroup.Frame: ImageVector get() { if (_frame != null) { return _frame!! } _frame = Builder(name = "Frame", defaultWidth = 24.0.dp, defaultHeight = 24.0.dp, viewportWidth = 24.0f, viewportHeight = 24.0f).apply { path(fill = SolidColor(Color(0xFFffffff)), stroke = null, strokeLineWidth = 0.0f, strokeLineCap = Butt, strokeLineJoin = Miter, strokeLineMiter = 4.0f, pathFillType = NonZero) { moveTo(24.0f, 0.0f) horizontalLineTo(0.0f) verticalLineTo(24.0f) horizontalLineTo(24.0f) verticalLineTo(0.0f) close() } path(fill = SolidColor(Color(0xFF292D32)), stroke = null, strokeLineWidth = 0.0f, strokeLineCap = Butt, strokeLineJoin = Miter, strokeLineMiter = 4.0f, pathFillType = NonZero) { moveTo(12.0f, 6.0f) lineTo(17.0f, 3.0f) lineTo(22.0f, 6.0f) verticalLineTo(18.0f) lineTo(17.0f, 21.0f) lineTo(7.0f, 15.0f) verticalLineTo(9.0f) lineTo(17.0f, 15.0f) verticalLineTo(9.0f) lineTo(12.0f, 6.0f) close() } path(fill = SolidColor(Color(0xFF292D32)), stroke = null, fillAlpha = 0.4f, strokeAlpha = 0.4f, strokeLineWidth = 0.0f, strokeLineCap = Butt, strokeLineJoin = Miter, strokeLineMiter = 4.0f, pathFillType = NonZero) { moveTo(12.0f, 18.0f) lineTo(7.0f, 21.0f) lineTo(2.0f, 18.0f) verticalLineTo(6.0f) lineTo(7.0f, 3.0f) lineTo(17.0f, 9.0f) verticalLineTo(15.0f) lineTo(7.0f, 9.0f) verticalLineTo(15.0f) lineTo(12.0f, 18.0f) close() } } .build() return _frame!! } private var _frame: ImageVector? = null
0
Kotlin
0
2
b8a8231e6637c2008f675ae76a3423b82ee53950
2,885
VuesaxIcons
MIT License
src/test/kotlin/com/fileee/oihAdapter/interpreter/EmitTest.kt
openintegrationhub
159,690,721
false
null
package com.fileee.oihAdapter.interpreter import arrow.core.some import arrow.effects.IO import arrow.effects.fix import arrow.effects.monadDefer import io.elastic.api.EventEmitter import io.kotlintest.specs.StringSpec import io.mockk.every import io.mockk.mockk import io.mockk.verify import javax.json.Json class EmitSpec : StringSpec({ "emitMessage should call the correct method" { val em = mockk<EventEmitter>() val emAlg = EmitInterpreter(em.some(), IO.monadDefer()) every { em.emitData(any()) } returns em emAlg.emitMessage(Json.createObjectBuilder().build()).fix().unsafeRunSync() verify { em.emitData(any()) } } "emitException should call the correct method" { val em = mockk<EventEmitter>() val emAlg = EmitInterpreter(em.some(), IO.monadDefer()) every { em.emitException(any()) } returns em emAlg.emitError(Exception("MyExcep")).fix().unsafeRunSync() verify { em.emitException(any()) } } "emitSnapshot should call the correct method" { val em = mockk<EventEmitter>() val emAlg = EmitInterpreter(em.some(), IO.monadDefer()) every { em.emitSnapshot(any()) } returns em emAlg.emitSnapshot(Json.createObjectBuilder().build()).fix().unsafeRunSync() verify { em.emitSnapshot(Json.createObjectBuilder().build()) } } // test for emitKeys later })
0
Kotlin
0
0
0bef6ec18c38c34f55b3ede68f7b68a3b7baf743
1,468
fileee-adapter
Apache License 2.0
lib/src/main/kotlin/net/dean/jraw/pagination/DefaultPaginator.kt
hhouyuqing
110,333,531
true
{"Kotlin": 338670, "Java": 127186, "Groovy": 11415}
package net.dean.jraw.pagination import net.dean.jraw.RedditClient import net.dean.jraw.http.HttpRequest import net.dean.jraw.models.Sorting import net.dean.jraw.models.TimePeriod open class DefaultPaginator<T> private constructor( reddit: RedditClient, baseUrl: String, val sortingAlsoInPath: Boolean, val timePeriod: TimePeriod, val sorting: Sorting, limit: Int, clazz: Class<T> ) : Paginator<T, Paginator.Builder<T>>(reddit, baseUrl, limit, clazz) { override fun createNextRequest(): HttpRequest { val sortingString = sorting.name.toLowerCase() val args: MutableMap<String, String> = mutableMapOf( "limit" to limit.toString(radix = 10), "sort" to sortingString ) if (sorting.requiresTimePeriod) args.put("t", timePeriod.name.toLowerCase()) if (current?.nextName != null) args.put("after", current!!.nextName!!) val path = if (sortingAlsoInPath) "$baseUrl/$sortingString" else baseUrl return reddit.requestStub() .path(path) .query(args) .build() } override fun newBuilder() = Builder(reddit, baseUrl, sortingAlsoInPath, clazz) .sorting(sorting) .timePeriod(timePeriod) .limit(limit) open class Builder<T>( reddit: RedditClient, baseUrl: String, /** * If true, the sorting will be included as a query parameter instead of a path parameter. Most endpoints * support (and require) specifying the sorting as a path parameter like this: `/r/pics/top?sort=top`. However, * other endpoints 404 when given a path like this, in which case the sorting will need to be specified via * query parameter only */ protected var sortingAlsoInPath: Boolean = false, clazz: Class<T> ) : Paginator.Builder<T>(reddit, baseUrl, clazz) { protected var limit: Int = Paginator.DEFAULT_LIMIT protected var timePeriod: TimePeriod = Paginator.DEFAULT_TIME_PERIOD protected var sorting = Paginator.DEFAULT_SORTING fun limit(limit: Int): Builder<T> { this.limit = limit; return this } fun sorting(sorting: Sorting): Builder<T> { this.sorting = sorting; return this } fun timePeriod(timePeriod: TimePeriod): Builder<T> { this.timePeriod = timePeriod; return this } override fun build(): DefaultPaginator<T> = DefaultPaginator(reddit, baseUrl, sortingAlsoInPath, timePeriod, sorting, limit, clazz) companion object { inline fun <reified T> create(reddit: RedditClient, baseUrl: String, sortingAlsoInPath: Boolean = false): Builder<T> { return Builder(reddit, baseUrl, sortingAlsoInPath, T::class.java) } } } }
0
Kotlin
0
0
922d497858d62e873ac003b1b8fc392ae514a9ac
2,811
JRAW
MIT License
mockserver/src/main/java/org/fnives/test/showcase/network/mockserver/scenario/general/NotFoundRequestScenario.kt
fknives
356,982,481
false
null
package org.fnives.test.showcase.network.mockserver.scenario.general import okhttp3.mockwebserver.MockResponse import okhttp3.mockwebserver.RecordedRequest import org.fnives.test.showcase.network.mockserver.scenario.RequestScenario internal object NotFoundRequestScenario : RequestScenario { override fun getResponse(request: RecordedRequest): MockResponse = MockResponse().setResponseCode(404).setBody("Not Found") }
9
Kotlin
2
5
5bf503d90e8a13daf5626afc0cdf8bff523d2b94
432
AndroidTest-ShowCase
Apache License 2.0
app/src/main/java/com/aditya/googledeveloperscommunityvisualisationtool/roomdatabase/notificationRoom/NotifyViewModelFactory.kt
soCallmeAdityaKumar
647,671,779
false
{"Kotlin": 441339}
package com.aditya.googledeveloperscommunityvisualisationtool.roomdatabase.notificationRoom import android.content.Context import androidx.lifecycle.ViewModel import androidx.lifecycle.ViewModelProvider import androidx.lifecycle.viewmodel.ViewModelFactoryDsl class NotifyViewModelFactory(val context: Context):ViewModelProvider.Factory { override fun<T: ViewModel>create(modelClass:Class<T>):T{ return NotifyViewModel(context) as T } }
0
Kotlin
1
6
21eabc0cd5a5041f79cfb78bfe4c20d6ffeaaf80
453
Google-Developers-Community-Visualization-Tool
MIT License
src/main/kotlin/org/opensearch/commons/notifications/action/NotificationsActions.kt
opensearch-project
354,136,133
false
null
/* * Copyright OpenSearch Contributors * SPDX-License-Identifier: Apache-2.0 */ package org.opensearch.commons.notifications.action import org.opensearch.action.ActionType /** * All the transport action information for the Notification plugin */ object NotificationsActions { /** * Create notification configuration transport action name. */ const val CREATE_NOTIFICATION_CONFIG_NAME = "cluster:admin/opensearch/notifications/configs/create" /** * Update notification configuration transport action name. */ const val UPDATE_NOTIFICATION_CONFIG_NAME = "cluster:admin/opensearch/notifications/configs/update" /** * Delete notification configuration transport action name. */ const val DELETE_NOTIFICATION_CONFIG_NAME = "cluster:admin/opensearch/notifications/configs/delete" /** * Get notification configuration transport action name. */ const val GET_NOTIFICATION_CONFIG_NAME = "cluster:admin/opensearch/notifications/configs/get" /** * Get notification events transport action name. */ const val GET_NOTIFICATION_EVENT_NAME = "cluster:admin/opensearch/notifications/events/get" /** * Get notification plugin features transport action name. */ const val GET_PLUGIN_FEATURES_NAME = "cluster:admin/opensearch/notifications/features" /** * Get Config List for feature. Internal only - Inter plugin communication. */ const val GET_FEATURE_CHANNEL_LIST_NAME = "cluster:admin/opensearch/notifications/feature/channels/get" /** * Send notification message. Internal only - Inter plugin communication. */ const val SEND_NOTIFICATION_NAME = "cluster:admin/opensearch/notifications/feature/send" /** * Publish legacy notification message. Internal only - Inter plugin communication. * Only for the Alerting and Index Management plugins. */ const val LEGACY_PUBLISH_NOTIFICATION_NAME = "cluster:admin/opensearch/notifications/feature/publish" /** * Create notification configuration transport action type. */ val CREATE_NOTIFICATION_CONFIG_ACTION_TYPE = ActionType(CREATE_NOTIFICATION_CONFIG_NAME, ::CreateNotificationConfigResponse) /** * Update notification configuration transport action type. */ val UPDATE_NOTIFICATION_CONFIG_ACTION_TYPE = ActionType(UPDATE_NOTIFICATION_CONFIG_NAME, ::UpdateNotificationConfigResponse) /** * Delete notification configuration transport action type. */ val DELETE_NOTIFICATION_CONFIG_ACTION_TYPE = ActionType(DELETE_NOTIFICATION_CONFIG_NAME, ::DeleteNotificationConfigResponse) /** * Get notification configuration transport action type. */ val GET_NOTIFICATION_CONFIG_ACTION_TYPE = ActionType(GET_NOTIFICATION_CONFIG_NAME, ::GetNotificationConfigResponse) /** * Get notification events transport action type. */ val GET_NOTIFICATION_EVENT_ACTION_TYPE = ActionType(GET_NOTIFICATION_EVENT_NAME, ::GetNotificationEventResponse) /** * Get notification plugin features transport action type. */ val GET_PLUGIN_FEATURES_ACTION_TYPE = ActionType(GET_PLUGIN_FEATURES_NAME, ::GetPluginFeaturesResponse) /** * Get Config List for feature transport action type. */ val GET_FEATURE_CHANNEL_LIST_ACTION_TYPE = ActionType(GET_FEATURE_CHANNEL_LIST_NAME, ::GetFeatureChannelListResponse) /** * Send notification transport action type. Internal only - Inter plugin communication. */ val SEND_NOTIFICATION_ACTION_TYPE = ActionType(SEND_NOTIFICATION_NAME, ::SendNotificationResponse) /** * Send legacy notification transport action type. Internal only - Inter plugin communication. * Only for the Alerting and Index Management plugins. */ val LEGACY_PUBLISH_NOTIFICATION_ACTION_TYPE = ActionType(LEGACY_PUBLISH_NOTIFICATION_NAME, ::LegacyPublishNotificationResponse) }
17
null
36
6
bccb1bb329517c3c550df9b8fd9df81bbf05e4f1
4,008
common-utils
Apache License 2.0
base/src/main/kotlin/browser/chromeosInfoPrivate/StylusStatus.kt
DATL4G
372,873,797
false
null
package browser.chromeosInfoPrivate import kotlin.String /** * Status of stylus. */ public enum class StylusStatus( private val `value`: String, ) { unsupported("unsupported"), supported("supported"), seen("seen"), ; public override fun toString(): String = value }
0
Kotlin
1
37
ab2a825dd8dd8eb704278f52c603dbdd898d1875
283
Kromex
Apache License 2.0
data_collector/src/main/kotlin/com/sortinghat/backend/data_collector/factories/DockerComposeCollectionComponentsFactory.kt
the-sortinghat
529,660,037
false
null
package com.sortinghat.backend.data_collector.factories import com.sortinghat.backend.data_collector.services.ConverterToDomain import com.sortinghat.backend.data_collector.services.DockerComposeToDomain import com.sortinghat.backend.data_collector.services.FetchDataFromRemoteRepository import com.sortinghat.backend.data_collector.services.ParseDockerCompose import org.springframework.beans.factory.annotation.Autowired import org.springframework.beans.factory.annotation.Qualifier import org.springframework.stereotype.Component @Component @Qualifier("dockerCompose") class DockerComposeCollectionComponentsFactory( @Autowired private val fetcher: FetchDataFromRemoteRepository, @Autowired private val parser: ParseDockerCompose, @Autowired private val converter: DockerComposeToDomain, ): CollectionComponentsFactory { override fun createDataFetcher() = fetcher override fun createDataParser() = parser @Suppress("UNCHECKED_CAST") override fun <Service> createConverterToDomain() = converter as ConverterToDomain<Service> }
0
Kotlin
0
0
95695a1808e477ce67d8257891f4fa9be21f8cce
1,062
backend
MIT License
src/main/kotlin/org/abimon/visi/collections/VCollections.kt
UnderMybrella
83,109,125
false
null
package org.abimon.visi.collections import java.util.* fun <T, U, V> Map<Pair<T, U>, V>.containsFirstPair(t: T): Boolean = keys.any { pair -> pair.first == t } fun <T, U, V> Map<Pair<T, U>, V>.getFirstOfPair(t: T): V? { return get(keys.firstOrNull { pair -> pair.first == t } ?: return null) } fun <T, U, V> Map<Pair<T, U>, V>.getSecondPair(t: T): U? { return (keys.firstOrNull { pair -> pair.first == t } ?: return null).second } fun <T, U, V> Map<Pair<T, U>, V>.containsSecondPair(u: U): Boolean = keys.any { pair -> pair.second == u } fun <T, U, V> Map<Pair<T, U>, V>.getSecondOfPair(u: U): V? { return get(keys.firstOrNull { pair -> pair.second == u } ?: return null) } fun <T, U, V> Map<Pair<T, U>, V>.getFirstPair(u: U): T? { return (keys.firstOrNull { pair -> pair.second == u } ?: return null).first } fun <T, V> Map<Pair<T, T>, V>.contains(t: T): Boolean = keys.any { pair -> pair.first == t || pair.second == t} fun <T, V> Map<Pair<T, T>, V>.getFirst(t: T): V? { return get(keys.firstOrNull { pair -> pair.first == t || pair.second == t } ?: return null) } fun <T, V> Map<Pair<T, T>, V>.getPair(t: T): Pair<T, T>? { return (keys.firstOrNull { pair -> pair.first == t || pair.second == t }) } fun <T, V> Map<Pair<T, T>, V>.getOther(t: T): T? { return (keys.firstOrNull { pair -> pair.first == t } ?: return (keys.firstOrNull { pair -> pair.second == t } ?: return null).first).second } fun <T, V> Map<T, V>.getForValue(v: V): T? = keys.firstOrNull { key -> get(key) == v } fun <T> List<T>.shuffle(): List<T> { val list = ArrayList<T>() val copyList = ArrayList<T>(this) val rng = Random() while(copyList.size > 0) list.add(copyList.removeAt(rng.nextInt(copyList.size))) return list } fun <T> List<T>.random(rng: Random = Random()): T = get(rng.nextInt(size)) fun <T> Array<T>.random(rng: Random = Random()): T = get(rng.nextInt(size)) fun <T> MutableList<T>.remove(predicate: (T) -> Boolean): T? { val index = indexOfFirst(predicate) if(index == -1) return null return removeAt(index) } fun <T> MutableList<T>.tryRemove(predicate: (T) -> Boolean): Optional<T> = Optional.ofNullable(remove(predicate)) fun <T, E: MutableCollection<T>> E.addAllReturning(collection: Collection<T>): E { addAll(collection) return this } fun <T, E: MutableCollection<T>> E.addAll(num: Int, adding: (Int) -> T): Boolean { var added = false for(i in 0 until num) added = add(adding(i)) return added } fun <K, V> HashMap<K, V>.flush(): HashMap<K, V> { val copy = HashMap(this) this.clear() return copy } fun <T> List<T>.random(): T = this[Random().nextInt(size)] fun <T> Iterable<T>.coerceAtMost(size: Int): List<T> { val list = ArrayList<T>() for(element in this) { list.add(element) if(list.size >= size) break } return list } fun <T> List<T>.equalsBy(equalCheck: (Int, T) -> Boolean): Boolean { return indices.all { equalCheck(it, get(it)) } } inline fun <reified T> Iterable<T>.segment(sizes: Int): List<Array<T>> { val list = ArrayList<Array<T>>() val segment = ArrayList<T>() for(element in this) { segment.add(element) if(segment.size >= sizes) { list.add(segment.toTypedArray()) segment.clear() } } return list } fun <T> Iterable<T>.pass(passing: (T, T) -> T): T { val list = this.toList() var t: T = list.first() for(i in (1 until list.size)) t = passing(t, list[i]) return t } fun <T> Collection<T>.joinToPrefixedString(separator: String, elementPrefix: String = "", elementSuffix: String = "", transform: T.() -> String = { this.toString() }) = joinToString(separator) { element -> "$elementPrefix${element.transform()}$elementSuffix"} fun ByteArray.toArrayString(): String = this.contentToString() fun BooleanArray.toArrayString(): String = this.contentToString() fun Array<*>.toArrayString(): String = this.contentToString() fun IntArray.copyFrom(index: Int): IntArray = copyOfRange(index, size) fun <T> Array<T>.copyFrom(index: Int): Array<T> = copyOfRange(index, size) fun <T> List<T>.toSequentialString(separator: String = ", ", finalSeparator: String = ", and ", transform: T.() -> String = { this.toString() }): String { return when (size) { 0 -> "" 1 -> this[0].transform() 2 -> this[0].transform() + finalSeparator + this[1].transform() else -> { var str = "" for (i in 0 until size - 2) str += this[i].transform() + separator str += this[size - 2].transform() + finalSeparator str += this[size - 1].transform() str } } } fun <T> Array<T>.toSequentialString(separator: String = ", ", finalSeparator: String = ", and ", transform: T.() -> String = { this.toString() }): String { return when (size) { 0 -> "" 1 -> this[0].transform() 2 -> this[0].transform() + finalSeparator + this[1].transform() else -> { var str = "" for (i in 0 until size - 2) str += this[i].transform() + separator str += this[size - 2].transform() + finalSeparator str += this[size - 1].transform() str } } } infix fun ByteArray.asBase(base: Int): String = this.joinToString(" ") { byte -> when(base) { 2 -> "0b${byte.toString(2)}" 16 -> "0x${byte.toString(16)}" else -> byte.toString(base) } } infix fun IntArray.asBase(base: Int): String = this.joinToString(" ") { byte -> when(base) { 2 -> "0b${byte.toString(2)}" 16 -> "0x${byte.toString(16)}" else -> byte.toString(base) } } operator fun <K, V> Map<K, V>.get(v: V): K? = getByValue(v) fun <K, V> Map<K, V>.getByValue(v: V): K? = entries.firstOrNull { (_, value) -> value == v }?.key operator fun <T> List<T>.get(index: Int, default: T): T = if(index < size) this[index] else default
0
Kotlin
3
1
7fdb31da497792cc58787940d1321698d8ff410f
6,015
Visi
MIT License
featureflag/src/main/kotlin/no/nav/yrkesskade/featureflag/strategy/NaeringskodeStrategy.kt
navikt
461,907,640
false
null
package no.nav.yrkesskade.featureflag.strategy import no.finn.unleash.UnleashContext import no.finn.unleash.strategy.Strategy class NaeringskodeStrategy(private val context : UnleashContext) : Strategy { override fun getName(): String = "byNaeringskoder" override fun isEnabled(parameters: MutableMap<String, String>): Boolean { return isEnabled(parameters, context) } override fun isEnabled(parameters: MutableMap<String, String>, context: UnleashContext): Boolean { val toggledNaeringskoder = parameters.get("naeringskoder") if (toggledNaeringskoder == null) { return true } val naeringskoder = context.properties.get("naeringskoder") if (naeringskoder == null) { return false } return naeringskoder.split(",").any { toggledNaeringskoder.split(",").contains(it) } } }
1
Kotlin
0
0
12cacc14f94d84b0a39dcc69a7e08c1af4877004
903
yrkesskade-backend-felles
MIT License
Plugin/plugin-repo/src/main/java/com/kronos/plugin/repo/model/IncludeModuleInfo.kt
Leifzhang
283,129,368
false
null
package com.kronos.plugin.repo.model import com.kronos.plugin.repo.RepoLogger import com.kronos.plugin.repo.utils.GitUtil import java.io.File import java.lang.RuntimeException /** * * @Author LiABao * @Since 2021/9/8 * */ open class IncludeModuleInfo( val name: String, private val origin: String, val srcBuild: Boolean, private val repoManageProjectDir: File, val branch: String, val projectNameList: MutableList<String> ) { //模块所属git工程的根路径 var moduleGitRootPath: File init { val moduleRootDirName = origin.split("/").last().split(".").first() moduleGitRootPath = File(repoManageProjectDir, moduleRootDirName) } fun getModulePath(name: String): File { return File(moduleGitRootPath, name) } private fun isModuleGitDirExist(): Boolean { return moduleGitRootPath.exists() } /** * 配置该模块在本地的环境 * => 如果模块尚未clone 则执行clone 并切换到对应分支 * => 如果模块已经在本地,则直接checkout到对应分支 */ fun settingProject() { if (!isModuleGitDirExist()) { GitUtil.clone(moduleGitRootPath, origin) //return } RepoLogger.progressInfo("moudle $name project already exists in path $moduleGitRootPath") val clean = GitUtil.isClean(moduleGitRootPath) val branchChanged = GitUtil.isBranchChanged(moduleGitRootPath, branch) //如果分支未变更过,且本地有修改的文件未保存,则终止,需要用户手动处理 if (branchChanged && !clean) { throw RuntimeException( "[repo] - moudle ${name} is not clean , please commit " + "or revert changes before checkout branch" ) } //本地没有修改的文件则 主动切换分支 if (clean) { //如果是本地已经存在的分支 if (GitUtil.isLocalExistBranch(moduleGitRootPath, branch)) { RepoLogger.progressInfo("moudle ${name}: file:${moduleGitRootPath}.git/refs/heads/${branch} exists so ${branch} is exist Branch in local") GitUtil.checkoutBranch(moduleGitRootPath, branch) } else { if (GitUtil.isRemoteBranch(moduleGitRootPath, branch)) { RepoLogger.progressInfo("moudle ${name} isRemoteBranch") GitUtil.checkoutRemoteBranch(moduleGitRootPath, branch) } else { GitUtil.checkoutNewBranch(moduleGitRootPath, branch) } } tryPullRebase() } } private fun tryPullRebase() { if (!GitUtil.isRemoteBranch(moduleGitRootPath, branch)) return val success = GitUtil.pullRebase(moduleGitRootPath) if (!success) { throw RuntimeException( " execute command [git pull --rebase] for project ${name} failed,please check to see if files conflict," + "if conflict, resolve it. then try again ,\n file status:\n${ GitUtil.fileStatus( moduleGitRootPath ) }" ) } } fun curBranch(): String? { return if (moduleGitRootPath.exists()) { GitUtil.curBranchName(moduleGitRootPath) } else { //没有使用源码依赖模式 null } } }
1
Kotlin
7
91
0308a0cf0366f2754526f4f07922006ebfb27488
3,316
GradleTask
Apache License 2.0
CommonUI/src/main/java/com/drivequant/drivekit/common/ui/component/GaugeConfiguration.kt
DriveQuantPublic
216,339,559
false
null
package com.drivequant.drivekit.common.ui.component import android.content.Context import android.graphics.Color import android.graphics.Typeface import android.text.Spannable import com.drivequant.drivekit.common.ui.DriveKitUI import com.drivequant.drivekit.common.ui.R import com.drivequant.drivekit.common.ui.extension.removeZeroDecimal import com.drivequant.drivekit.common.ui.extension.resSpans import com.drivequant.drivekit.common.ui.utils.DKSpannable import java.math.BigDecimal import java.math.RoundingMode sealed class GaugeConfiguration(open val value: Double) : DKGaugeConfiguration { data class SAFETY(override val value: Double) : GaugeConfiguration(value) data class ECO_DRIVING(override val value: Double) : GaugeConfiguration(value) data class DISTRACTION(override val value: Double) : GaugeConfiguration(value) data class SPEEDING(override val value: Double) : GaugeConfiguration(value) override fun getTitle(context: Context): Spannable { val text = if (value == 11.0) { "-" } else { BigDecimal(value).setScale(1, RoundingMode.HALF_UP).toDouble().removeZeroDecimal() } return DKSpannable().append(text, context.resSpans { size(R.dimen.dk_text_xxbig) typeface(Typeface.BOLD) color(DriveKitUI.colors.mainFontColor()) }).toSpannable() } override fun getScore() = value override fun getMaxScore(): Double = 10.0 override fun getColor(value: Double): Int = getColorFromValue(value, getSteps()) override fun getIcon(): Int = when (this) { is ECO_DRIVING -> R.drawable.dk_common_ecodriving is SAFETY -> R.drawable.dk_common_safety is DISTRACTION -> R.drawable.dk_common_distraction is SPEEDING -> R.drawable.dk_common_eco_accel } override fun getGaugeType(): DKGaugeType = DKGaugeType.OPEN_WITH_IMAGE(getIcon()) private fun getColorFromValue(value: Double, steps: List<Double>): Int { if (value == 11.0) return R.color.dkGaugeBackColor if (value <= steps[0]) return R.color.dkVeryBad if (value <= steps[1]) return R.color.dkBad if (value <= steps[2]) return R.color.dkBadMean if (value <= steps[3]) return R.color.dkMean if (value <= steps[4]) return R.color.dkGoodMean return if (value <= steps[5]) R.color.dkGood else R.color.dkExcellent } private fun getSteps(): List<Double> = when (this) { is ECO_DRIVING -> { val mean = 7.63 val sigma = 0.844 listOf( mean - (2 * sigma), mean - sigma, mean - (0.25 * sigma), mean, mean + (0.25 * sigma), mean + sigma, mean + (2 * sigma) ) } is SAFETY -> listOf(0.0, 5.5, 6.5, 7.5, 8.5, 9.5, 10.0) is DISTRACTION -> listOf(1.0, 7.0, 8.0, 8.5, 9.0, 9.5, 10.0) is SPEEDING -> listOf(3.0, 5.0, 7.0, 8.0, 9.0, 9.5, 10.0) } }
0
Kotlin
2
6
939465ac7264a9d35f53795c0a4c0a77205844eb
3,105
drivekit-ui-android
Apache License 2.0
src/main/kotlin/coroutine/demo/image/Images.kt
woniu0936
595,697,492
false
null
package coroutine.demo.image import java.awt.image.BufferedImage import java.io.File import javax.imageio.ImageIO fun Image.flipHorizontal(): Image { val height = height() val width = width() val pixels = Array(width) { x -> Array(height) { y -> getPixel(width - 1 - x, y) } } return Image(pixels) } fun Image.flipVertical(): Image { val height = height() val width = width() val pixels = Array(width) { x -> Array(height) { y -> getPixel(x, height - 1 - y) } } return Image(pixels) } fun Image.crop(startX: Int, startY: Int, width: Int, height: Int): Image { val pixels = Array(width) { x -> Array(height) { y -> getPixel(startX + x, startY + y) } } return Image(pixels) } fun Image.write(file: File): Boolean { val width = width() val height = height() val bufferImage = BufferedImage(width, height, BufferedImage.TYPE_INT_RGB) Array(height) { y -> Array(width) { x -> val color = getPixel(x, y) bufferImage.setRGB(x, y, color.rgb) } } return ImageIO.write(bufferImage, file.suffixName, file) }
0
Kotlin
0
0
ab7a9ced644faebf7273c10289f3e8b1c35acd10
1,201
KotlinDemo
MIT License
src/main/kotlin/P005_SmalllestMultiple.kt
perihanmirkelam
291,833,878
false
null
/** * P5-Smallest Multiple * 2520 is the smallest number that can be divided by each of the numbers from 1 to 10 without any remainder. * What is the smallest positive number that is evenly divisible by all of the numbers from 1 to 20? */ fun p5() { var num = 10 var isDivisible = false while (true) { num++ repeat(20) { if (num % (it + 1) != 0) isDivisible = false } if (isDivisible) break isDivisible = true } println("A5: $num") }
0
Kotlin
1
3
a24ac440871220c87419bfd5938f80dc22a422b2
509
ProjectEuler
MIT License
src/main/kotlin/me/branchpanic/mods/stockpile/Stockpile.kt
Waterpicker
404,747,171
true
{"Kotlin": 102549, "Java": 1098}
package me.branchpanic.mods.stockpile import me.branchpanic.mods.stockpile.api.upgrade.UpgradeRegistry import me.branchpanic.mods.stockpile.api.upgrade.UpgradeType import me.branchpanic.mods.stockpile.content.block.AttackableBlockCallback import me.branchpanic.mods.stockpile.content.block.BarrelBlock import me.branchpanic.mods.stockpile.content.block.ItemBarrelBlock import me.branchpanic.mods.stockpile.content.block.TrashCanBlock import me.branchpanic.mods.stockpile.content.blockentity.ItemBarrelBlockEntity import me.branchpanic.mods.stockpile.content.blockentity.TrashCanBlockEntity import me.branchpanic.mods.stockpile.content.item.BarrelHatItem import me.branchpanic.mods.stockpile.content.item.BasicUpgradeItem import me.branchpanic.mods.stockpile.content.item.UpgradeRemoverItem import me.branchpanic.mods.stockpile.content.upgrade.CapacityUpgrade import me.branchpanic.mods.stockpile.content.upgrade.MultiplierUpgrade import me.branchpanic.mods.stockpile.content.upgrade.TrashUpgrade import me.branchpanic.mods.stockpile.content.upgrade.UpgradeInstallerCallback import net.fabricmc.api.ModInitializer import net.fabricmc.fabric.api.client.itemgroup.FabricItemGroupBuilder import net.fabricmc.fabric.api.event.player.AttackBlockCallback import net.fabricmc.fabric.api.event.player.UseBlockCallback import net.fabricmc.fabric.api.network.ServerSidePacketRegistry import net.minecraft.block.Block import net.minecraft.block.entity.BlockEntity import net.minecraft.block.entity.BlockEntityType import net.minecraft.entity.EquipmentSlot import net.minecraft.item.BlockItem import net.minecraft.item.Item import net.minecraft.item.ItemGroup import net.minecraft.item.ItemStack import net.minecraft.util.Identifier import net.minecraft.util.registry.Registry object Stockpile : ModInitializer { private val ITEM_GROUP: ItemGroup = FabricItemGroupBuilder.build(id("all")) { ItemStack(ItemBarrelBlock) } internal val BLOCKS: Map<Identifier, Block> = mapOf( id("item_barrel") to BarrelBlock.ITEM, id("trash_can") to TrashCanBlock ) internal val ITEM_SETTINGS = Item.Settings().group(ITEM_GROUP) internal val ITEMS: Map<Identifier, Item> = mapOf( id("capacity_upgrade") to BasicUpgradeItem({ CapacityUpgrade(32) }, ITEM_SETTINGS), id("double_capacity_upgrade") to BasicUpgradeItem({ CapacityUpgrade(64) }, ITEM_SETTINGS), id("multiplier_upgrade") to BasicUpgradeItem({ MultiplierUpgrade(2) }, ITEM_SETTINGS), id("double_multiplier_upgrade") to BasicUpgradeItem({ MultiplierUpgrade(4) }, ITEM_SETTINGS), id("trash_upgrade") to BasicUpgradeItem({ TrashUpgrade() }, ITEM_SETTINGS), id("barrel_hat") to BarrelHatItem, id("upgrade_remover") to UpgradeRemoverItem ) internal val BLOCK_ENTITIES: Map<Identifier, BlockEntityType<out BlockEntity>> = mapOf( id("item_barrel") to ItemBarrelBlockEntity.TYPE, id("trash_can") to TrashCanBlockEntity.TYPE ) internal val UPGRADES: Map<Identifier, UpgradeType> = mapOf( id("capacity") to CapacityUpgrade.TYPE, id("multiplier") to MultiplierUpgrade.TYPE, id("trash") to TrashUpgrade.TYPE ) fun id(path: String): Identifier = Identifier("stockpile", path) override fun onInitialize() { BLOCKS.forEach { (id, block) -> Registry.register(Registry.BLOCK, id, block) if (ITEMS.keys.none { itemId -> itemId == id }) { Registry.register(Registry.ITEM, id, BlockItem(block, ITEM_SETTINGS.maxDamage(0).maxCount(8))) } } ITEMS.forEach { (id, item) -> Registry.register(Registry.ITEM, id, item) } BLOCK_ENTITIES.forEach { (id, blockEntityType) -> Registry.register(Registry.BLOCK_ENTITY_TYPE, id, blockEntityType) } UPGRADES.forEach { (id, upgradeEntry) -> UpgradeRegistry.register(id, upgradeEntry) } UseBlockCallback.EVENT.register(UpgradeInstallerCallback) AttackBlockCallback.EVENT.register(AttackableBlockCallback) ServerSidePacketRegistry.INSTANCE.register(id("barrel_hat_restock")) { ctx, _ -> if (ctx.player?.getEquippedStack(EquipmentSlot.HEAD)?.item != BarrelHatItem) { return@register } if (ctx.player.isSneaking) { BarrelHatItem.pullInventoryFromBarrels(ctx.player) } else { BarrelHatItem.pushInventoryToBarrels(ctx.player) } } } }
0
null
0
0
eea85a487ebe3c33566f5244d83e28a5ced3e400
4,538
stockpile
MIT License
app/src/main/java/com/synrgy/wefly/data/api/json/ContentResponse.kt
WeFly-Team
738,106,597
false
{"Kotlin": 106789, "Ruby": 1042}
package com.synrgy.wefly.data.api.json import com.synrgy.wefly.data.api.json.airport.list.PageAble data class ContentResponse<T>( val content: ArrayList<T>, val pageable: PageAble, )
0
Kotlin
1
0
1324b86a07e2b7bd79189d20d2daefcf971eddfd
193
Android
Apache License 2.0
src/main/kotlin/org/misarch/catalog/graphql/model/CategoricalCategoryCharacteristic.kt
MiSArch
730,141,730
false
{"Kotlin": 137664, "PLpgSQL": 3347, "Shell": 487, "Dockerfile": 219}
package org.misarch.catalog.graphql.model import com.expediagroup.graphql.generator.annotations.GraphQLDescription import com.expediagroup.graphql.generator.annotations.GraphQLIgnore import com.expediagroup.graphql.generator.federation.directives.FieldSet import com.expediagroup.graphql.generator.federation.directives.KeyDirective import org.misarch.catalog.graphql.model.connection.CategoricalCategoryCharacteristicValueConnection import org.misarch.catalog.graphql.model.connection.CategoricalCategoryCharacteristicValueOrder import org.misarch.catalog.graphql.model.connection.ProductVariantVersionConnection import org.misarch.catalog.graphql.model.connection.ProductVariantVersionOrder import org.misarch.catalog.persistence.model.ProductVariantVersionEntity import org.misarch.catalog.persistence.repository.CategoryCharacteristicValueRepository import org.misarch.catalog.persistence.repository.ProductVariantVersionRepository import org.springframework.beans.factory.annotation.Autowired import java.util.* @GraphQLDescription("A categorical characteristic of a category.") @KeyDirective(fields = FieldSet("id")) class CategoricalCategoryCharacteristic( id: UUID, name: String, description: String, categoryId: UUID ) : CategoryCharacteristic(id, name, description, categoryId) { @GraphQLDescription("Get all associated values") suspend fun values( @GraphQLDescription("Number of items to return") first: Int? = null, @GraphQLDescription("Number of items to skip") skip: Int? = null, @GraphQLDescription("Ordering") orderBy: CategoricalCategoryCharacteristicValueOrder? = null, @GraphQLIgnore @Autowired repository: CategoryCharacteristicValueRepository ): CategoricalCategoryCharacteristicValueConnection { return CategoricalCategoryCharacteristicValueConnection( first, skip, orderBy, repository, id ) } }
0
Kotlin
0
0
b4e291b77dcb8ff2ffafe638bc6353bbc0e8a1c9
2,001
catalog
MIT License
src/main/kotlin/de/claudioaltamura/kotlin/examples/Ok.kt
claudioaltamura
172,023,763
false
{"Kotlin": 31200}
package de.claudioaltamura.kotlin.examples fun start(): String = "OK"
0
Kotlin
0
0
310eb4636233b3568d9439531f605eb857b160d6
70
kotlin-examples
MIT License
src/main/kotlin/world/cepi/carbon/whitelist/WhitelistListener.kt
Project-Cepi
314,618,958
false
{"Kotlin": 28485}
package world.cepi.carbon.whitelist import net.kyori.adventure.text.Component import net.kyori.adventure.text.format.NamedTextColor import net.minestom.server.event.player.PlayerLoginEvent internal fun whitelistListener(event: PlayerLoginEvent) { if (WhitelistManager.size() != 0 && !event.player.uuid.whitelisted()) { event.player.kick(Component.text("You are not whitelisted!", NamedTextColor.RED)) } }
2
Kotlin
0
4
5d685acff822993a077f1aa0608884436b9fa74f
422
Carbon
MIT License
app/src/main/java/com/example/studymate/CreateNotesFragment.kt
Dhruv16S
652,624,701
false
null
package com.example.studymate import android.app.Activity import android.content.Context import android.content.Intent import android.content.SharedPreferences import android.content.pm.PackageManager import android.content.res.Resources import android.net.Uri import android.os.Bundle import android.provider.MediaStore import android.util.Log import android.Manifest import android.annotation.SuppressLint import android.graphics.Bitmap import android.graphics.BitmapFactory import android.os.Environment import androidx.fragment.app.Fragment import android.view.LayoutInflater import android.view.MotionEvent import android.view.View import android.view.ViewGroup import android.widget.EditText import android.widget.LinearLayout import android.widget.ScrollView import androidx.core.content.ContextCompat import androidx.core.content.res.ResourcesCompat import android.view.inputmethod.InputMethodManager import android.widget.Button import android.widget.TextView import android.widget.Toast import androidx.cardview.widget.CardView import androidx.core.app.ActivityCompat import androidx.core.content.FileProvider import io.appwrite.Client import io.appwrite.services.Databases import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.launch import com.google.mlkit.vision.common.InputImage import com.google.mlkit.vision.text.TextRecognition import com.google.mlkit.vision.text.latin.TextRecognizerOptions import io.appwrite.models.InputFile import io.appwrite.services.Storage import java.io.File import java.io.FileOutputStream import java.io.IOException import java.text.SimpleDateFormat import java.util.Date import java.util.Locale import com.atwa.filepicker.core.FilePicker import com.itextpdf.text.pdf.PdfReader import com.itextpdf.text.pdf.parser.PdfTextExtractor import io.appwrite.ID import kotlinx.coroutines.DelicateCoroutinesApi import kotlinx.coroutines.GlobalScope @Suppress("DEPRECATION") class CreateNotesFragment : Fragment() { private lateinit var addText : Button private lateinit var addFile : Button private lateinit var addOcr : Button private lateinit var saveNotes : Button private lateinit var scroll : ScrollView private lateinit var displayNotes : LinearLayout private lateinit var noteName : EditText private lateinit var noteContent : EditText private lateinit var preferences: SharedPreferences private lateinit var userId : String private lateinit var sessionId : String private var docCount : Int = 0 private var fileCount : Int = 0 private var capturedImageUri: Uri? = null private var sentencesList = mutableListOf<String>() private var i : Int = 1 private var countOcr : Int = 1 private val cameraPermissionRequestCode = 100 private val imageCaptureRequestCode = 200 private val imageFileName = "captured_image.jpg" private lateinit var filePicker: FilePicker @SuppressLint("ClickableViewAccessibility") override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View { // Inflate the layout for this fragment val v : View = inflater.inflate(R.layout.fragment_create_notes, container, false) preferences = requireActivity().getSharedPreferences("SHARED_PREF", Context.MODE_PRIVATE) if (!hasCameraPermission()) requestCameraPermission() addText = v.findViewById(R.id.addText) addFile = v.findViewById(R.id.addFile) addOcr = v.findViewById(R.id.addOcr) saveNotes = v.findViewById(R.id.saveNotes) scroll = v.findViewById(R.id.scrollView) displayNotes = v.findViewById(R.id.displayNotes) noteName = v.findViewById(R.id.noteName) noteContent = v.findViewById(R.id.noteContent) preferences = requireActivity().getSharedPreferences("SHARED_PREF", Context.MODE_PRIVATE) sessionId = preferences.getString("sessionId", " ").toString() userId = preferences.getString("userId", " ").toString() filePicker = FilePicker.getInstance(this) addText.setOnClickListener { val toBeAdded = noteContent.text.toString() if(toBeAdded.isEmpty()){ Toast.makeText(context, "Enter some text: ", Toast.LENGTH_SHORT).show() return@setOnClickListener } // Create a new CardView sentencesList.add(toBeAdded) createCardText(toBeAdded, i, isOcr = false, isFile = false) i += 1 } addFile.setOnClickListener { readAndUpdateDatabase(shouldUpdate = false, isFileUpdate = true) fileCount += 1 filePicker.pickFile { selectedFile -> selectedFile?.let { val filePath = it.file val type = filePath.toString().takeLast(3) val fileName: String? = it.name if(type == "pdf"){ val extractedData = extractData(filePath.toString()).replace(Regex("[\n\\s]+"), " ") sentencesList.add(extractedData) } // Continue with the file processing logic CoroutineScope(Dispatchers.Main).launch { val client = Client(requireContext()) .setEndpoint("https://cloud.appwrite.io/v1") .setProject("64734c27ee025a6ee21c") val storage = Storage(client) try { storage.createFile( bucketId = "647d72e7564902ca8b17", fileId = userId + fileCount.toString(), file = InputFile.fromPath(filePath.toString()), ) // Mention file creation sentencesList.add(userId + fileCount.toString()) Toast.makeText(context, "File Uploaded!", Toast.LENGTH_SHORT).show() createCardText(fileName.toString(), fileCount, isOcr = false, isFile = true ) // Update changes to db readAndUpdateDatabase(shouldUpdate = true, isFileUpdate = true) } catch (e: Exception) { Log.e("Appwrite", "Error: " + e.message) } } } } } addOcr.setOnClickListener { val cameraIntent = Intent(MediaStore.ACTION_IMAGE_CAPTURE) // Create a file to store the captured image in the app-specific directory val imageFile = createImageFile() capturedImageUri = FileProvider.getUriForFile( requireContext(), requireContext().packageName + ".fileprovider", imageFile ) cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, capturedImageUri) startActivityForResult(cameraIntent, imageCaptureRequestCode) } saveNotes.setOnClickListener { readAndUpdateDatabase(shouldUpdate = false, isFileUpdate = false) if (noteName.text.isEmpty()) { Toast.makeText(context, "Enter a Note Name to proceed", Toast.LENGTH_SHORT).show() } else if(sentencesList.isEmpty()){ Toast.makeText(context, "Enter some text", Toast.LENGTH_SHORT).show() } else { CoroutineScope(Dispatchers.Main).launch { val client = Client(requireContext()) .setEndpoint("https://cloud.appwrite.io/v1") .setProject("64734c27ee025a6ee21c") val databases = Databases(client) val dateFormat = SimpleDateFormat("yyyy-MM-dd", Locale.getDefault()) val currentDate = Date() try { databases.createDocument( databaseId = "6479d563804822fc79bb", collectionId = "6479f9af8834a056c20d", documentId = ID.unique(), data = mapOf( "session-id" to sessionId, "user-id" to userId, "note-name" to noteName.text.toString(), "note-text" to sentencesList, "date-created" to dateFormat.format(currentDate) ) ) Toast.makeText(context, "Note Created!", Toast.LENGTH_SHORT).show() sentencesList = mutableListOf() i = 0 countOcr = 0 noteName.setText("") displayNotes.removeAllViews() // Update changes to db readAndUpdateDatabase(shouldUpdate = true, isFileUpdate = false) Log.d("count", "$docCount") } catch (e: Exception) { Log.e("Appwrite", "Error: " + e.message) } } } } v.setOnTouchListener { _, event -> if (event.action == MotionEvent.ACTION_DOWN) { val imm = requireContext().getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager imm.hideSoftInputFromWindow(v.windowToken, 0) } false } return v } @OptIn(DelicateCoroutinesApi::class) private fun readAndUpdateDatabase(shouldUpdate : Boolean, isFileUpdate : Boolean) { val client = Client(requireContext()) .setEndpoint("https://cloud.appwrite.io/v1") .setProject("64734c27ee025a6ee21c") val database = Databases(client) GlobalScope.launch(Dispatchers.Main) { try { if(!shouldUpdate){ val response = database.getDocument( databaseId = "648081c3025f25473245", collectionId = "6480820466d1d4790f90", documentId = userId, ) docCount = (response.data["notes"] as Long).toInt() fileCount = (response.data["files"] as Long).toInt() } else{ if(isFileUpdate) fileCount += 1 else docCount += 1 database.updateDocument( databaseId = "648081c3025f25473245", collectionId = "6480820466d1d4790f90", documentId = userId, data = mapOf( "files" to fileCount, "notes" to docCount, ) ) } // Further flow for the logged-in user } catch (e: Exception) { // Handle login failure Toast.makeText(context, "Could not fetch data", Toast.LENGTH_SHORT).show() Log.d("Error", "$e") } } } @SuppressLint("SetTextI18n") private fun createCardText(toBeAdded : String, count : Int, isOcr : Boolean, isFile : Boolean) { val cardView = CardView(requireContext()) // Set CardView layout parameters val cardLayoutParams = LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT) cardLayoutParams.setMargins(10.0.dpToPx(), 5.0.dpToPx(), 10.0.dpToPx(), 5.0.dpToPx()) cardView.layoutParams = cardLayoutParams cardView.cardElevation = 25.0.dpToPx().toFloat() cardView.setBackgroundResource(R.drawable.note_card_template) // Create a LinearLayout to hold the TextView and EditText val linearLayout = LinearLayout(requireContext()) linearLayout.orientation = LinearLayout.VERTICAL linearLayout.setPadding(16.0.dpToPx(), 16.0.dpToPx(), 16.0.dpToPx(), 16.0.dpToPx()) // Create the TextView val textView = TextView(requireContext()) if(isOcr) textView.text = "OCR Detected Note ${count}:" else if(isFile) textView.text = "File ${count}: $toBeAdded" else textView.text = "Note ${count}:" textView.typeface = ResourcesCompat.getFont(requireContext(), R.font.open_sans) textView.setTextColor(ContextCompat.getColor(requireContext(), R.color.black)) textView.textSize = 18.0f // Add the TextView to the LinearLayout linearLayout.addView(textView) if(!isFile){// Create the EditText val editText = EditText(requireContext()) val editTextLayoutParams = LinearLayout.LayoutParams( LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT ) editText.layoutParams = editTextLayoutParams editText.typeface = ResourcesCompat.getFont(requireContext(), R.font.montserrat) editText.setTextColor(ContextCompat.getColor(requireContext(), R.color.white)) editText.setHintTextColor(ContextCompat.getColor(requireContext(), R.color.white)) editText.setBackgroundResource(0) // Removes the line associated with the EditText editText.setTextCursorDrawable(R.drawable.black_cursor) editText.setText(toBeAdded) editText.tag = "noteEditText" editText.textSize = 16.0f // Add the EditText to the LinearLayout linearLayout.addView(editText) } // Add the LinearLayout to the CardView cardView.addView(linearLayout) // Add the CardView to the parent LinearLayout (displayNotes) displayNotes.addView(cardView) noteContent.setText("") } private fun Double.dpToPx(): Int { val scale = Resources.getSystem().displayMetrics.density return (this * scale + 0.5f).toInt() } private fun createImageFile(): File { val storageDir: File? = requireContext().getExternalFilesDir(Environment.DIRECTORY_PICTURES) return File(storageDir, imageFileName) } private fun hasCameraPermission(): Boolean { val permission = Manifest.permission.CAMERA val result = ContextCompat.checkSelfPermission(requireContext(), permission) return result == PackageManager.PERMISSION_GRANTED } private fun requestCameraPermission() { ActivityCompat.requestPermissions(requireActivity(), arrayOf(Manifest.permission.CAMERA), cameraPermissionRequestCode) } @Deprecated("Deprecated in Java") override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) { super.onActivityResult(requestCode, resultCode, data) if (requestCode == imageCaptureRequestCode && resultCode == Activity.RESULT_OK) { val imageUri = capturedImageUri // Use the captured image URI instead of data extras if (imageUri != null) { val imageBitmap = loadBitmapFromUri(imageUri) if (imageBitmap != null) { val processedImageUri = saveImageAndGetUri(imageBitmap) processedImageUri?.let { uri -> processCapturedImage(uri) } } else { Log.d("URI", "Failed to load image bitmap from URI.") } } else { Log.d("URI", "Captured image URI is null.") } } } private fun loadBitmapFromUri(uri: Uri): Bitmap? { return try { val inputStream = requireContext().contentResolver.openInputStream(uri) BitmapFactory.decodeStream(inputStream) } catch (e: IOException) { Log.e("LoadBitmap", "Error loading image bitmap: ${e.message}") null } } private fun saveImageAndGetUri(imageBitmap: Bitmap): Uri? { val imagesDirectory = requireContext().getExternalFilesDir(Environment.DIRECTORY_PICTURES) val timeStamp = SimpleDateFormat("yyyyMMdd_HHmmss", Locale.getDefault()).format(Date()) val fileName = "IMG_$timeStamp.jpg" val file = File(imagesDirectory, fileName) return try { FileOutputStream(file).use { outputStream -> imageBitmap.compress(Bitmap.CompressFormat.JPEG, 90, outputStream) outputStream.flush() } FileProvider.getUriForFile(requireContext(), requireContext().packageName + ".fileprovider", file) } catch (e: IOException) { Log.e("SaveImage", "Error saving image: ${e.message}") null } } private fun processCapturedImage(uri: Uri) { val image = InputImage.fromFilePath(requireContext(), uri) val recognizerOptions = TextRecognizerOptions.Builder() .build() TextRecognition.getClient(recognizerOptions) val updatedRecognizer = TextRecognition.getClient(recognizerOptions) updatedRecognizer.process(image) .addOnSuccessListener { visionText -> var recognizedText = visionText.text // Handle the recognized text as desired recognizedText = recognizedText.replace("\n", ". ") createCardText(recognizedText, countOcr, isOcr = true, isFile = false) sentencesList.add(recognizedText) countOcr += 1 } .addOnFailureListener { exception -> // Handle the OCR failure exception.printStackTrace() } } private fun extractData(path : String): String { var extractedText = "" try { val pdfReader = PdfReader(path) val n = pdfReader.numberOfPages for (i in 0 until n) { extractedText = """ $extractedText${ PdfTextExtractor.getTextFromPage(pdfReader, i + 1).trim { it <= ' ' } } """.trimIndent() } pdfReader.close() return extractedText } catch (e: Exception) { e.printStackTrace() } return extractedText } }
0
Kotlin
0
1
9274faab9cac47376b4eb02cf50d64f75d7070b3
18,877
StudyMate
MIT License
src/test/kotlin/io/github/jokoroukwu/zephyrapi/testcyclefilter/OutOfBoundsStepFilterTest.kt
jokoroukwu
471,393,179
false
null
package io.github.jokoroukwu.zephyrapi.testcyclefilter import io.github.jokoroukwu.zephyrapi.publication.TestDataResult import io.github.jokoroukwu.zephyrapi.publication.ZephyrTestResult import io.github.jokoroukwu.zephyrapi.publication.keytoitemmapcomplementor.TestCaseItem import io.github.jokoroukwu.zephyrapi.publication.testcyclefilter.OutOfBoundsStepFilter import io.mockk.clearAllMocks import io.mockk.every import io.mockk.mockk import io.mockk.unmockkObject import org.assertj.core.api.SoftAssertions import org.testng.annotations.AfterClass import org.testng.annotations.AfterMethod import org.testng.annotations.DataProvider import org.testng.annotations.Test class OutOfBoundsStepFilterTest { private val filter = OutOfBoundsStepFilter() private val testCaseItemMock = mockk<TestCaseItem>() private val dataSetResultMock = mockk<TestDataResult>() @AfterMethod(alwaysRun = true) fun tearDown() { unmockkObject(testCaseItemMock, dataSetResultMock) } @AfterClass(alwaysRun = true) fun afterClass() { clearAllMocks() } @Test(dataProvider = "outOfBoundsStepProvider") fun `should return null result when all steps out of bounds`( testCaseItem: TestCaseItem, testResult: ZephyrTestResult ) { val result = filter.filterTestResult(testResult, testCaseItem) with(SoftAssertions()) { assertThat(result.testResult) .`as`("check test result is null") .isNull() val expectedProblemCount = testResult.testDataResults.size assertThat(result.issues.size) .`as`("check problem count equals expected") .isEqualTo(expectedProblemCount) assertAll() } } @Test(dataProvider = "stepsWithinBoundsProvider") fun `should return same result when all steps are within bounds`( testCaseItem: TestCaseItem, testResult: ZephyrTestResult ) { val result = filter.filterTestResult(testResult, testCaseItem) with(SoftAssertions()) { assertThat(result.testResult) .`as`("check test result is unchanged") .isEqualTo(testResult) assertThat(result.issues) .`as`("check problem count equals expected") .isEmpty() assertAll() } } @Test fun `should return expected result when some steps out of bounds and some not`() { every { testCaseItemMock.testScript.steps } returns mockk { every { size } returns 3 } with(dataSetResultMock) { every { failedStepIndex } returns 0 every { index } returns 0 } val secondDataSet = mockk<TestDataResult> { every { failedStepIndex } returns 4 every { index } returns 2 } val testResult = ZephyrTestResult(testDataResults = listOf(dataSetResultMock, secondDataSet), startTime = 1, endTime = 2) val result = filter.filterTestResult(testResult, testCaseItemMock) with(SoftAssertions()) { assertThat(result.testResult) .`as`("zephyr result should contain expected datasets") .isEqualTo(ZephyrTestResult(testDataResults = listOf(dataSetResultMock), startTime = 1, endTime = 2)) assertThat(result.issues) .`as`("check problem count equals expected") .hasSize(1) assertAll() } } @DataProvider private fun stepsWithinBoundsProvider(): Array<Array<Any?>> { every { testCaseItemMock.testScript.steps } returns mockk { every { size } returns 3 } with(dataSetResultMock) { every { failedStepIndex } returnsMany listOf(0, 1, 2) every { index } returnsMany listOf(1, 2, 3) } return arrayOf( arrayOf( testCaseItemMock, ZephyrTestResult(testDataResults = listOf(dataSetResultMock), startTime = 1, endTime = 2) ), arrayOf( testCaseItemMock, ZephyrTestResult( testDataResults = listOf(dataSetResultMock, dataSetResultMock), startTime = 1, endTime = 2 ) ) ) } @DataProvider private fun outOfBoundsStepProvider(): Array<Array<Any?>> { every { testCaseItemMock.testScript.steps } returns mockk { every { size } returns 2 } with(dataSetResultMock) { every { failedStepIndex } returnsMany listOf(3, 4, 5) every { index } returnsMany listOf(1, 2, 3) } return arrayOf( arrayOf( testCaseItemMock, ZephyrTestResult(testDataResults = listOf(dataSetResultMock), startTime = 1, endTime = 2) ), arrayOf( testCaseItemMock, ZephyrTestResult( testDataResults = listOf(dataSetResultMock, dataSetResultMock), startTime = 1, endTime = 2 ) ) ) } }
0
Kotlin
0
0
c720fae44211a321384652ee6efd88cfd5dae877
5,239
zephyr-api
Apache License 2.0
src/main/kotlin/com/coder/gateway/sdk/ex/APIResponseException.kt
coder
490,848,198
false
{"Kotlin": 373297}
package com.coder.gateway.sdk.ex import java.io.IOException import java.net.HttpURLConnection import java.net.URL class APIResponseException(action: String, url: URL, res: retrofit2.Response<*>) : IOException( "Unable to $action: url=$url, code=${res.code()}, details=${ res.errorBody()?.charStream()?.use { it.readText() } ?: "no details provided"}", ) { val isUnauthorized = res.code() == HttpURLConnection.HTTP_UNAUTHORIZED }
53
Kotlin
12
25
652fc04a1ce64c55e2e48e6794ebe6a56b0ee783
491
jetbrains-coder
MIT License
RopeWaysAPI/src/main/kotlin/ru/ropeways/api/controller/WeatherController.kt
AlFilippov
514,555,720
false
null
package ru.ropeways.api.controller import org.springframework.web.bind.annotation.GetMapping import org.springframework.web.bind.annotation.RequestMapping import org.springframework.web.bind.annotation.RequestParam import org.springframework.web.bind.annotation.RestController import ru.ropeways.api.client.dto.Language import ru.ropeways.api.controller.WeatherController.Companion.ROOT_WEATHER import ru.ropeways.api.service.WeatherService @RestController @RequestMapping(ROOT_WEATHER) class WeatherController( private val weatherService: WeatherService, ) { @GetMapping(FORECAST) fun getWeatherT0( @RequestParam("lat") lat: Double, @RequestParam("lon") lon: Double, @RequestParam("lang", required = false) lang: Language, @RequestParam("limit", required = false) limit: Int?, @RequestParam("hours", required = false) hours: Boolean = false, @RequestParam("extra", required = false) extra: Boolean = false, ) = weatherService.getWeatherT0(lat = lat, lon = lon, lang = lang, limit = limit, hours = hours, extra = extra) @GetMapping(INFORMERS) fun getWeatherT1( @RequestParam("lat") lat: Double, @RequestParam("lon") lon: Double, @RequestParam(name = "lang", required = false) lang: Language, ) = weatherService.getWeatherT1(lat = lat, lon = lon, lang = lang) companion object { const val ROOT_WEATHER = "/weather" const val FORECAST = "/forecast" const val INFORMERS = "/informers" } }
0
Kotlin
0
1
b8587bef3897931289bc003f15ecf472c30a7fc4
1,522
RopeWaysBackend
Apache License 2.0
src/main/kotlin/model/Common.kt
Akira-Taniguchi
189,127,591
false
null
package model import com.amazonaws.auth.AWSStaticCredentialsProvider import com.amazonaws.auth.BasicAWSCredentials import com.amazonaws.client.builder.AwsClientBuilder import com.amazonaws.services.dynamodbv2.AmazonDynamoDB import com.amazonaws.services.dynamodbv2.AmazonDynamoDBClientBuilder import com.amazonaws.services.dynamodbv2.model.* import java.util.* private interface TableName { val tableName: String } abstract class DynamoDBBase : TableName { val client = getDynamoDbClient() protected fun deleteItemBase(keyMap: Map<String, AttributeValue>): DeleteItemResult { val request = DeleteItemRequest().withTableName(tableName).withKey(keyMap) return client.deleteItem(request) } protected fun getItemBase(keyMap: Map<String, AttributeValue>): Map<String, AttributeValue> { val request = GetItemRequest().withTableName(tableName).withKey(keyMap) val result = client.getItem(request) if (result.item != null) { return result.item } return emptyMap() } protected fun putItemBase(itemMap: Map<String, AttributeValue>) { val request = PutItemRequest().withTableName(tableName).withItem(itemMap) client.putItem(request) } protected fun query(keyConditions: HashMap<String, Condition>): List<Map<String, AttributeValue>> { val queryRequest = QueryRequest() .withTableName(tableName) .withKeyConditions(keyConditions) val queryResult = client.query(queryRequest) return queryResult.items } protected fun batchGetItem(conditions: List<Map<String, AttributeValue>>): List<Map<String, AttributeValue>>? { val request = BatchGetItemRequest() val keys = KeysAndAttributes().withKeys(conditions) request.addRequestItemsEntry(tableName, keys) val result = client.batchGetItem(request) return result.responses[tableName] } } internal fun getDynamoDbClient(): AmazonDynamoDB { val serviceEndPoint = System.getenv("DYNAMODB_SERVICE_END_POINT") ?: "http://localhost:8000" val region = System.getenv("DYNAMODB_SERVICE_REGION") ?: "" var clientBuilder = AmazonDynamoDBClientBuilder.standard() .withEndpointConfiguration(AwsClientBuilder.EndpointConfiguration(serviceEndPoint, region)) clientBuilder = clientBuilder.withCredentials( AWSStaticCredentialsProvider( BasicAWSCredentials("", "") ) ) return clientBuilder.build() }
0
Kotlin
0
0
74400c1f1042baefca3c62551de859a19a649b4c
2,530
dynamodb-kotlin
MIT License
common/src/commonMain/kotlin/com/demo/ui/utils/chat/ArrowBackiOS.kt
CoronelGlober
529,032,277
false
{"Kotlin": 188877, "Swift": 932, "Ruby": 271}
package com.demo.ui.utils.chat import androidx.compose.material.icons.Icons import androidx.compose.material.icons.materialIcon import androidx.compose.material.icons.materialPath import androidx.compose.ui.graphics.PathFillType import androidx.compose.ui.graphics.vector.ImageVector public val Icons.Filled.IosArrow: ImageVector get() { if (_iosArrow != null) { return _iosArrow!! } _iosArrow = materialIcon(name = "IosArrow") { materialPath( fillAlpha = 1.0F, strokeAlpha = 1.0F, pathFillType = PathFillType.NonZero, ) { moveTo(17.77F, 3.77F) lineToRelative(-1.77F, -1.77F) lineToRelative(-10.0F, 10.0F) lineToRelative(10.0F, 10.0F) lineToRelative(1.77F, -1.77F) lineToRelative(-8.23F, -8.23F) close() } } return _iosArrow!! } private var _iosArrow: ImageVector? = null
0
Kotlin
6
28
e7132da8475544a15b0288c64cdad8999c8747fa
1,032
demo-compose-multiplatform
MIT License
map/src/main/kotlin/de/darkatra/bfme2/map/reader/AssetListReader.kt
DarkAtra
325,887,805
false
null
package de.darkatra.bfme2.map.reader import de.darkatra.bfme2.map.AssetListItem import de.darkatra.bfme2.map.AssetName import de.darkatra.bfme2.map.MapFile import de.darkatra.bfme2.readUInt import org.apache.commons.io.input.CountingInputStream class AssetListReader : AssetReader { override fun read(reader: CountingInputStream, context: MapFileParseContext, builder: MapFile.Builder) { MapFileReader.readAsset(reader, context, AssetName.ASSET_LIST.assetName) { val numberOfAssetListItems = reader.readUInt() val assetList = mutableListOf<AssetListItem>() for (i in 0u until numberOfAssetListItems step 1) { val typeId = reader.readUInt() val instanceId = reader.readUInt() assetList.add( AssetListItem( typeId = typeId, instanceId = instanceId ) ) } context.mapHasAssetList = true builder.assetList( assetList = assetList ) } } }
1
Kotlin
0
1
08704593bf7dd19a81598d7ed9442255e05b96e4
911
bfme2-modding-utils
MIT License
app/src/main/java/fr/gilles/riceattend/ui/screens/pages/details/Worker.kt
Gilles-kpn
498,005,092
false
{"Kotlin": 442751}
package fr.gilles.riceattend.ui.screens.pages.details import android.os.Build import androidx.annotation.RequiresApi import androidx.compose.foundation.ExperimentalFoundationApi import androidx.compose.foundation.clickable import androidx.compose.foundation.layout.* import androidx.compose.foundation.lazy.LazyColumn import androidx.compose.foundation.shape.CircleShape import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.material.* import androidx.compose.material.icons.Icons import androidx.compose.material.icons.outlined.* import androidx.compose.runtime.Composable import androidx.compose.runtime.rememberCoroutineScope import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.draw.clip import androidx.compose.ui.graphics.Color import androidx.compose.ui.layout.ContentScale import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.unit.dp import androidx.navigation.NavHostController import coil.compose.AsyncImage import fr.gilles.riceattend.ui.navigation.Route import fr.gilles.riceattend.ui.viewmodel.WorkerVM import fr.gilles.riceattend.ui.widget.components.* import kotlinx.coroutines.launch @OptIn(ExperimentalMaterialApi::class, ExperimentalFoundationApi::class) @Composable @RequiresApi(Build.VERSION_CODES.O) fun WorkerPage( navHostController: NavHostController, snackbarHostState: SnackbarHostState, viewModel: WorkerVM ) { val scope = rememberCoroutineScope() val modalBottomSheetState = rememberModalBottomSheetState(initialValue = ModalBottomSheetValue.Hidden) when (viewModel.loading) { true -> { LoadingCard() } false -> { viewModel.worker?.let { LazyColumn( modifier = Modifier.fillMaxWidth(), horizontalAlignment = Alignment.CenterHorizontally ) { item{ AppBar( title = it.name, leftContent = { IconButton( onClick = { navHostController.popBackStack() }, ) { Icon( Icons.Outlined.ArrowBack, "Back", ) } }, rightContent = { IconButton(onClick = {}) { } } ) } item{ Card( Modifier .fillMaxWidth() .padding(10.dp) ) { Row( Modifier .fillMaxWidth() .padding(10.dp), horizontalArrangement = Arrangement.Start, verticalAlignment = Alignment.CenterVertically ) { Card( modifier = Modifier .padding(end = 20.dp, start = 10.dp) .width(100.dp) .height(100.dp) .clip(CircleShape) ) { AsyncImage( model = userGravatar(email = it.email), contentDescription = "Profile picture", contentScale = ContentScale.FillWidth, modifier = Modifier .fillMaxSize() .clip(RoundedCornerShape(10.dp)) ) } Column { Text( text = it.name, fontWeight = FontWeight.Bold, modifier = Modifier.padding(bottom = 7.dp) ) Text( text = it.phone, fontWeight = FontWeight.Bold, modifier = Modifier .padding(bottom = 7.dp) .clickable { viewModel.openDialer() } ) Text( text = it.email, modifier = Modifier .padding(bottom = 10.dp) .clickable { viewModel.openMail() }, ) Text( text = "Paye horaire: "+it.hourlyPay+" FCFA", fontWeight = FontWeight.Bold, modifier = Modifier .padding(bottom = 10.dp) .clickable { viewModel.openMail() }, ) } } } } item{ Row( horizontalArrangement = Arrangement.SpaceAround, modifier = Modifier .fillMaxWidth() .padding(10.dp) ) { Button(onClick = { scope.launch { modalBottomSheetState.show() } }, modifier = Modifier .weight(1f) .padding(horizontal = 3.dp) ) { Icon( Icons.Outlined.Edit, "Edit", ) Text(text = "Modifier") } Button( onClick = { /*TODO*/ }, modifier = Modifier .weight(1f) .padding(horizontal = 3.dp), colors = ButtonDefaults.buttonColors( backgroundColor = Color.Red, contentColor = Color.White) ) { Icon( imageVector = Icons.Outlined.Delete, contentDescription = "Delete", ) Text(text = "Supprimer") } } } item { Row( modifier = Modifier .fillMaxWidth() .padding(horizontal = 15.dp), Arrangement.SpaceBetween, Alignment.CenterVertically ) { Text( text = "Activites", ) IconButton(onClick = { it.activityWorkers.sortedBy { activityWorker -> activityWorker.price } .also { result -> it.activityWorkers = result } }) { Icon(Icons.Outlined.FilterList, "Filter") } } } items(it.activityWorkers.size) { index -> Box(Modifier.padding(horizontal = 10.dp)) { ActivityTile( activity = it.activityWorkers[index].activity, onClick = { navHostController.navigate( Route.ActivityRoute.path.replace( "{code}", it.activityWorkers[index].activity.code ) ) { } } ) { Text(text = "Revenu: ${it.activityWorkers[index].price} FCFA") } } } if(it.activityWorkers.isEmpty()){ item { EmptyCard() } } } } } } ModalBottomSheetLayout( sheetContent = { WorkerForm( onSubmit = { viewModel.updateWorker{ scope.launch { modalBottomSheetState.hide() } } }, title = "Modifier les informations", workerFormVM = viewModel.workerFormVM, buttonText = "Modifier", isLoading = viewModel.updateLoading ) }, sheetState = modalBottomSheetState, ) {} }
0
Kotlin
0
1
b75abaf8d21014bdfe79a2ab8db82bcb1f561bf8
10,182
RiceAttend-Mobile
MIT License
uicorek/src/main/java/com/mozhimen/uicorek/datak/DataKRecyclerView.kt
mozhimen
353,952,154
false
null
package com.mozhimen.uicorek.datak import android.content.Context import android.util.AttributeSet import android.view.GestureDetector import android.view.LayoutInflater import android.view.MotionEvent import android.view.View import androidx.recyclerview.widget.RecyclerView import com.mozhimen.basick.utilk.UtilKView import com.mozhimen.uicorek.R import com.mozhimen.uicorek.datak.helpers.DataKAdapter import com.mozhimen.uicorek.refreshk.helpers.RefreshKGestureDetector /** * @ClassName DataKRecyclerView * @Description TODO * @Author mozhimen / <NAME> * @Date 2022/4/22 17:30 * @Version 1.0 */ class DataKRecyclerView @JvmOverloads constructor( context: Context, attrs: AttributeSet? = null, defStyleAttr: Int = 0 ) : RecyclerView(context, attrs, defStyleAttr) { private val TAG = "DataKRecyclerView>>>>>" private var _loadMoreScrollListener: OnScrollListener? = null private var _footerView: View? = null private var _isLoading: Boolean = false private var _isFooterShowing: Boolean = false private var _dataKLoadMoreCallback: IDataKLoadListener? = null private var _prefetchSize: Int = 5 private val _gestureDetector: GestureDetector by lazy { GestureDetector(context, LoadMoreGestureDetector(_prefetchSize, _dataKLoadMoreCallback)) } interface IDataKLoadListener { fun onLoadMore() } /** * 设置底部加载视图 * @param layoutId Int */ fun setFooterView(layoutId: Int) { _footerView = LayoutInflater.from(context).inflate(layoutId, this, false) } /** * 打开加载更多 * @param prefetchSize Int * @param callback Function0<Unit> */ fun enableLoadMore(prefetchSize: Int, callback: IDataKLoadListener?) { require(adapter is DataKAdapter) { "enableLoadMore must use dataKAdapter" } this._prefetchSize = prefetchSize this._dataKLoadMoreCallback = callback _loadMoreScrollListener = LoadMoreListener() addOnScrollListener(_loadMoreScrollListener!!) } /** * 关闭加载更多 */ fun disableLoadMore() { require(adapter is DataKAdapter) { "enableLoadMore must use dataKAdapter" } val dataKAdapter = adapter as DataKAdapter _footerView?.let { if (_footerView!!.parent != null) { dataKAdapter.removeFooterView(_footerView!!) } } _loadMoreScrollListener?.let { removeOnScrollListener(_loadMoreScrollListener!!) _dataKLoadMoreCallback = null _loadMoreScrollListener = null _footerView = null _isFooterShowing = false _isLoading = false } } /** * 是否正在加载 * @return Boolean */ fun isLoading(): Boolean = _isLoading /** * 加载结束 */ fun loadFinished() { require(adapter is DataKAdapter) { "enableLoadMore must use dataKAdapter" } val dataKAdapter = adapter as DataKAdapter _footerView?.let { dataKAdapter.removeFooterView(_footerView!!) } _isFooterShowing = false _isLoading = false } override fun dispatchTouchEvent(ev: MotionEvent?): Boolean { //这里放弃了监听onScroll事件而改用监听手势, 因为fix 原有的滚动, 滚动到边缘触发两次的bug return if (_gestureDetector.onTouchEvent(ev)) true else super.dispatchTouchEvent(ev) } inner class LoadMoreGestureDetector(private val _prefetchSize: Int, private val _callback: IDataKLoadListener?) : RefreshKGestureDetector() { //咱们这里的强转, 因为前面会有前置检查 private val _dataKAdapter by lazy { adapter as DataKAdapter } override fun onScroll(e1: MotionEvent?, e2: MotionEvent?, distanceX: Float, distanceY: Float): Boolean { if (distanceY < 0 && UtilKView.isScroll2Top(this@DataKRecyclerView)) { return true } else { if (distanceY > 0) { if (_isLoading) return false val totalItemCount = _dataKAdapter.itemCount if (totalItemCount <= 0) return false val lastVisibleItem = UtilKView.findLastVisibleItem(this@DataKRecyclerView) //预加载, 就是不需要等待滑动到最后一个item的时候, 就出发下一页的加载动作 val arrivePrefetchPosition = totalItemCount - lastVisibleItem <= _prefetchSize if (!arrivePrefetchPosition) return false//不在预加载范围内则返回 _callback?.onLoadMore() _isLoading = true } return false } } } inner class LoadMoreListener() : OnScrollListener() { //咱们这里的强转, 因为前面会有前置检查 private val _dataKAdapter = adapter as DataKAdapter override fun onScrollStateChanged(recyclerView: RecyclerView, newState: Int) { //需要根据当前的滑动状态, 已决定要不要添加footerView, 要不要执行上拉加载分页的动作 if (_isFooterShowing) return //咱们需要判断当前类表上已经显示的item的个数, 如果列表上已显示的item的数量小于0, 退出 val totalItemCount = _dataKAdapter.itemCount if (totalItemCount <= 0) return //还有一种情况,canScrollVertical 咱们是检查他能不能继续向下滑动, //特殊情况, 咱们的列表已经滑动到底部了, 但是分页失败了。 val lastVisibleItem = UtilKView.findLastVisibleItem(recyclerView) if (lastVisibleItem <= 0) return if (newState == SCROLL_STATE_DRAGGING) { //这边分三个情况: 列表没有铺满屏幕, 铺满但firstVisibleItem还是停留在0, firstVisibleItem>0 //列表不可滑动,但列表没有撑满屏幕,此时lastVisibleItem就等于最后一条item,为了避免这种能情况,还需要加firstVisibleItem!=0 //可以向下滑动, 或者当前已经滑动到最底下了, 此时在拖动列表, 那也是允许分页的 if (UtilKView.isScroll2End(this@DataKRecyclerView)) { _isFooterShowing = true addFooterView() } } } private fun addFooterView() { val footerView = getFooterView() //但是, 这里有个坑...在一些边界场景下, 会出现多次添加的情况, 添加之前先remove -> dataKAdapter.removeFooterView() //主要是为了避免removeFooterView不及时, 在边界场景下可能会出现, footerView还没从recyclerView上移除掉, 但我们又调用了addFooterView //造成的重复添加的情况, 此时会抛出 add view must call removeView form it parent first exception if (footerView.parent != null) { footerView.post { addFooterView() } } else { _dataKAdapter.addFooterView(footerView) } } private fun getFooterView(): View { if (_footerView == null) { _footerView = LayoutInflater.from(context).inflate(R.layout.datak_footer_loading, this@DataKRecyclerView, false) } return _footerView!! } } }
0
Kotlin
0
1
3dd109aff154bff96379cde86e6e4632967cca40
6,690
SwiftMK
Apache License 2.0
app/src/main/java/project/penadidik/geocoding/util/Helper.kt
penadidik
562,671,216
false
null
package project.penadidik.geocoding.util import android.content.Context import android.net.ConnectivityManager object Helper { const val KEY_LAT = "lat" const val KEY_LON = "lon" const val KEY_STATE = "state" const val KEY_COUNTRY = "country" fun isNetworkAvailable(context: Context):Boolean { val conManager = context.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager val internetInfo =conManager.activeNetworkInfo return internetInfo!=null && internetInfo.isConnected } }
0
Kotlin
0
0
48896b285bc1e7fbe73221b5140008a46ae1ee74
548
Geocoding
Apache License 2.0
src/main/kotlin/com/sstep/recipe/manager/controller/ImageController.kt
mainmeatball
372,236,420
false
null
package com.sstep.recipe.manager.controller import com.sstep.recipe.manager.service.FileService import org.springframework.beans.factory.annotation.Autowired import org.springframework.beans.factory.annotation.Qualifier import org.springframework.web.bind.annotation.GetMapping import org.springframework.web.bind.annotation.PostMapping import org.springframework.web.bind.annotation.RequestParam import org.springframework.web.bind.annotation.RestController import org.springframework.web.multipart.MultipartFile import java.util.* @RestController open class ImageController @Autowired constructor( @Qualifier("imageService") private val imageService: FileService ) { @GetMapping(value = ["/image"]) open fun getImage(@RequestParam("id") id: String): ByteArray? { return imageService.getFile(id).content?.data?.toBase64() } private fun ByteArray.toBase64(): ByteArray = Base64.getEncoder().encode(this) @PostMapping("/uploadImages") open fun uploadImages(@RequestParam file: MultipartFile): String? { validate(file) return imageService.saveFile(file.name, file) } private fun validate(file: MultipartFile) { val contentType = requireNotNull(file.contentType) { "File content type is null" } if (!contentType.isImage()) { throw IllegalArgumentException("Only images could be uploaded to server") } } private fun String.isImage() = split("/").firstOrNull() == "image" }
0
Kotlin
0
0
b84abc68cb2609eeb4b0984b5703974723089255
1,487
recipe-organizer
MIT License
app/src/main/java/com/example/mykotlinapp/model/entity/chat/ChatParticipant.kt
vbounyasit
522,266,559
false
{"Kotlin": 507212}
package com.example.mykotlinapp.model.entity.chat import androidx.room.ColumnInfo import androidx.room.Entity @Entity( tableName = "chat_participants", primaryKeys = ["participant_remote_id", "participant_chat_remote_id"] ) data class ChatParticipant( @ColumnInfo(name = "participant_remote_id") val remoteId: String, @ColumnInfo(name = "participant_chat_remote_id") val chatRemoteId: String, @ColumnInfo(name = "participant_first_name") val firstName: String, @ColumnInfo(name = "participant_last_name") val lastName: String, @ColumnInfo(name = "participant_full_name") val fullName: String, @ColumnInfo(name = "participant_profile_picture") val profilePicture: String, @ColumnInfo(name = "is_admin") val isAdmin: Boolean, @ColumnInfo(name = "last_read_time") val lastReadTime: Long?, )
0
Kotlin
0
1
a9812a061f9214b44ba326b77afe335a003cc22e
861
MyAndroidApp
Apache License 2.0
app/src/main/java/com/example/togutravelapp/viewmodel/ViewModelFactory.kt
Fortissible
492,488,387
false
{"Kotlin": 123600}
package com.example.togutravelapp.viewmodel import android.content.Context import androidx.lifecycle.ViewModel import androidx.lifecycle.ViewModelProvider import com.example.togutravelapp.data.repository.UserRepository import com.example.togutravelapp.di.Injection @Suppress("UNCHECKED_CAST") class ViewModelFactory private constructor( private val userRepository: UserRepository ): ViewModelProvider.NewInstanceFactory() { override fun <T : ViewModel> create(modelClass: Class<T>): T = when (modelClass){ ChatListViewModel::class.java -> ChatListViewModel() LoginRegisterViewModel::class.java -> LoginRegisterViewModel(userRepository) LocationListViewModel::class.java -> LocationListViewModel() ObjectListViewModel::class.java -> ObjectListViewModel() TourGuidesViewModel::class.java -> TourGuidesViewModel() else -> throw IllegalArgumentException("Unknown ViewModel class: " + modelClass.name) } as T companion object { @Volatile private var instance : ViewModelFactory?= null fun getInstance(context: Context): ViewModelFactory = instance ?: synchronized(this){ instance ?: ViewModelFactory( Injection.provideUserRepository(context = context) ) }.also { instance = it} } }
0
Kotlin
1
1
c5dd952bd56c7e8ec2764af5215ccd54b30828c3
1,377
ToguTravelApp
MIT License
app/src/main/java/ru/mobile/lukslol/service/db/dao/SummonerDao.kt
silverxcoins
260,674,124
false
{"Kotlin": 73778}
package ru.mobile.lukslol.service.db.dao import androidx.room.* import ru.mobile.lukslol.service.db.entity.DbSummoner @Dao interface SummonerDao { @Query("SELECT * FROM DbSummoner WHERE id = :id") fun getById(id: String): DbSummoner? @Insert(onConflict = OnConflictStrategy.REPLACE) fun insert(summoner: DbSummoner) }
0
Kotlin
0
1
bdedaf16c62777f413e56d0d3a0b1336d1966d98
336
LukS-LoL-Tracker
Apache License 2.0
app/src/main/kotlin/com/absurddevs/vespera/navigation/TopLevelDestination.kt
s0nance
726,207,846
false
{"Kotlin": 83136}
package com.absurddevs.vespera.navigation import androidx.annotation.StringRes import androidx.compose.material3.adaptive.navigationsuite.NavigationSuiteType import androidx.compose.ui.graphics.vector.ImageVector import com.absurddevs.vespera.NavGraph import com.absurddevs.vespera.NavGraphs import com.absurddevs.vespera.R import com.absurddevs.vespera.core.designsystem.icon.VesperaIcons import com.absurddevs.vespera.destinations.HomeScreenDestination import com.absurddevs.vespera.destinations.SettingsScreenDestination import com.ramcosta.composedestinations.spec.DirectionDestinationSpec /** * Type for the top level destination in the app. Each of these destinations can contain one * or more screens (based on the window size). Navigation from one screen to the next within * a single destination will be handled directly in composables. */ sealed class TopLevelDestination( val graph: NavGraph, val direction: DirectionDestinationSpec, val selectedIcon: ImageVector, val unselectedIcon: ImageVector, @StringRes val labelResId: Int ) { data object HOME : TopLevelDestination( graph = NavGraphs.home, direction = HomeScreenDestination, selectedIcon = VesperaIcons.House, unselectedIcon = VesperaIcons.HouseBorder, labelResId = R.string.destination_home ) data object SETTINGS: TopLevelDestination( graph = NavGraphs.settings, direction = SettingsScreenDestination, selectedIcon = VesperaIcons.Settings, unselectedIcon = VesperaIcons.SettingsBorder, labelResId = R.string.destination_settings ) companion object { fun fromNavigationSuiteType(navigationSuiteType: NavigationSuiteType ): List<TopLevelDestination> { return when (navigationSuiteType) { NavigationSuiteType.NavigationBar -> listOf(HOME, SETTINGS) else -> listOf(HOME, SETTINGS) } } } }
0
Kotlin
0
0
5d5ee19ac8771927852d5e285925ec64553ff877
1,968
vespera
MIT License
src/main/kotlin/com/github/gabrielshanahan/phpkt/expressions/assignables/SimpleVariable.kt
gabrielshanahan
226,652,392
false
null
package com.github.gabrielshanahan.phpkt.expressions.assignables /** * A PHP variable with the name [name], such as $a. * * See [Assignable] for all the logic. * * @param name The name of the variable. */ class SimpleVariable(val name: String) : Assignable(name) /** * Helper function to convert Kotlin strings to PHP Variable objects. */ fun `$`(name: String) = SimpleVariable(name)
0
Kotlin
0
0
132f9ef6a517646f1ea1272af8a3066c4c147785
394
PhpKt
MIT License
app/src/main/java/com/annas/playground/data/domain/model/DataState.kt
annasta13
826,067,757
false
{"Kotlin": 230187}
package com.annas.playground.data.domain.model /** * This is the class wrapper to be used in UI layer. This class has four states: * - [Idle] * - [Success] * - [Loading] * - [Error] * */ sealed class DataState<out T> { /**State of success containing [data]*/ data class Success<T>(val data: T) : DataState<T>() /**State of idle*/ data object Idle : DataState<Nothing>() /** State of loading.*/ data object Loading : DataState<Nothing>() /** State of error containing [Error.message]*/ data class Error(val message: String) : DataState<Nothing>() /** Getting error message. * @return * - [DataState.Error.message] if the state is error * - null if the state is not [DataState.Error].*/ fun getErrorMessage(): String? { return when (this) { is Success -> null is Idle -> null is Loading -> null is Error -> message } } /** Getting data of success state. * @return * - [DataState.Success.data] if the state is success * - null if the state is not [DataState.Success] or if the data is success but the data is null.*/ fun getStateData(): T? { return when (this) { is Success -> data is Idle -> null is Loading -> null is Error -> null } } /** * Check if the data is available. * @return true when data list is empty or data object is null * */ private fun isDataEmpty(): Boolean { var value = true val isSuccess = this is Success if (isSuccess) value = when (val data = this.getStateData()) { is List<*> -> data.isEmpty() else -> data == null } return value } /** * Showing empty data message by verifying whether the data is empty or null. * This function verifies the data by [isDataEmpty] function.*/ fun showEmptyMessage(message: String): String? { return if (isDataEmpty()) message else null } fun isIdle() = this is Idle fun isError() = this is Error fun isLoading() = this is Loading fun isSuccess() = this is Success }
0
Kotlin
0
1
a8fa4467421d9c40ff9945c07b60f3108120cd9b
2,200
playground
Apache License 2.0
common/common_presentation/src/main/java/com/serj113/common/presentation/adapter/ItemViewAdapter.kt
serj113
260,604,628
false
null
package com.serj113.common.presentation.adapter import android.view.ViewGroup import androidx.recyclerview.widget.RecyclerView import androidx.viewbinding.ViewBinding import com.serj113.common.presentation.adapter.bindable.BindingCreator import com.serj113.common.presentation.adapter.bindable.ItemView class ItemViewAdapter : RecyclerView.Adapter<ItemViewAdapter.ViewHolder>() { private var mItemViews: MutableList<ItemView> = mutableListOf() private var mItemTypes: HashMap<Int, BindingCreator> = hashMapOf() override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder { val viewBinding = mItemTypes[viewType]!!.createViewBinding(parent) return ViewHolder(viewBinding) } override fun onBindViewHolder(holder: ViewHolder, position: Int) { getItem(position).bindView(holder.viewBinding) } override fun getItemViewType(position: Int): Int { val itemView = getItem(position) val itemViewType = itemView.viewType if (!mItemTypes.containsKey(itemViewType)) { mItemTypes[itemViewType] = itemView } return itemViewType } override fun getItemCount(): Int = mItemViews.size fun addItems(items: List<ItemView>) { mItemViews.addAll(items) notifyDataSetChanged() } fun setItems(items: List<ItemView>) { mItemViews.clear() addItems(items) } fun getItemView(position: Int): ItemView? { return mItemViews.getOrNull(position) } private fun getItem(position: Int) = mItemViews[position] inner class ViewHolder(val viewBinding: ViewBinding) : RecyclerView.ViewHolder(viewBinding.root) }
0
Kotlin
0
4
394a1cbc279cb26a7e2e17716a009274d1c964c3
1,684
Imagine-Movies
Apache License 2.0
src/main/kotlin/turniplabs/projectiles/item/ItemArrowExplosive.kt
Turnip-Labs
634,616,845
false
null
package turniplabs.projectiles.item import net.minecraft.client.Minecraft import turniplabs.projectiles.entity.EntityArrowExplosive class ItemArrowExplosive(i: Int): ItemElementalArrow(i) { override fun shootArrow() { val world = Minecraft.getMinecraft().theWorld val player = Minecraft.getMinecraft().thePlayer if (!world.isMultiplayerAndNotHost) { world.playSoundAtEntity(player, "random.fuse", 1.0f, 1.0f) world.entityJoinedWorld(EntityArrowExplosive(world, player, true, 0)) } } }
0
Kotlin
0
0
561b3dec4f29b6893ef962b84f3ee167a1d1c55d
553
elemental-projectiles
Creative Commons Zero v1.0 Universal
numeriko-core/src/main/kotlin/tomasvolker/numeriko/core/interfaces/array0d/generic/MutableArray0D.kt
fmgonsalves
160,878,513
true
{"Kotlin": 534380}
package tomasvolker.numeriko.core.interfaces.array0d.generic import tomasvolker.numeriko.core.interfaces.arraynd.generic.MutableArrayND interface MutableArray0D<T>: Array0D<T>, MutableArrayND<T> { override fun setValue(value: T, vararg indices: Int) { requireValidIndices(indices) return setValue(value) } override fun setValue(value: T) fun setValue(other: Array0D<T>) { setValue(other.getValue()) } override fun getView(): MutableArray0D<T> = this override fun lowerRank(axis: Int): Nothing { super<Array0D>.lowerRank(axis) } override fun arrayAlongAxis(axis: Int, index: Int): Nothing { super<Array0D>.arrayAlongAxis(axis, index) } }
0
Kotlin
0
0
a353cc233a426332b6c7a2b4385c9fbc5686574a
726
numeriko
Apache License 2.0
shared/record/recordDSImpl/src/uikitMain/kotlin/dmitry/molchanov/recorddsimpl/RecordSettings.kt
MolchanovDmitry
548,285,365
false
{"Kotlin": 107173, "HTML": 334}
package dmitry.molchanov.recorddsimpl import com.russhwolf.settings.NSUserDefaultsSettings import com.russhwolf.settings.coroutines.SuspendSettings import com.russhwolf.settings.coroutines.toSuspendSettings import kotlinx.coroutines.CoroutineDispatcher import platform.Foundation.NSUserDefaults actual class RecordSettings(dispatcher: CoroutineDispatcher) { actual val settings: SuspendSettings = NSUserDefaultsSettings(NSUserDefaults.standardUserDefaults).toSuspendSettings(dispatcher) }
0
Kotlin
0
0
dee62070a223c64236ea397a48fa11b469dc585e
504
SnakeKmp
Apache License 2.0
app/src/main/java/com/example/game_app/ui/game/dialogs/lobby/LobbyAdapter.kt
Gotalicp
704,093,487
false
{"Kotlin": 181720}
package com.example.game_app.ui.game.dialogs.lobby import android.annotation.SuppressLint import android.view.View import android.widget.ImageView import android.widget.TextView import com.example.game_app.R import com.example.game_app.ui.common.RecycleViewAdapter import com.example.game_app.ui.common.ItemClickListener import com.example.game_app.ui.common.AppAcc class LobbyAdapter : RecycleViewAdapter<AppAcc>( { oldItem, newItem -> oldItem == newItem }, { oldItem, newItem -> oldItem == newItem }, R.layout.item_lobby_player ) { var itemClickListener: ItemClickListener<AppAcc>? = null override fun createViewHolder(view: View) = PopupLobbyViewHolder(view) inner class PopupLobbyViewHolder(view: View) : BaseViewHolder(view) { private val image = view.findViewById<ImageView>(R.id.imageProfile) private val name = view.findViewById<TextView>(R.id.nameText) @SuppressLint("SetTextI18n") override fun bind(item: AppAcc) { name.text = item.username image.setImageBitmap(item.image) itemClickListener?.onItemClicked(item, absoluteAdapterPosition) } } }
0
Kotlin
0
0
cf996282fcb73d6011417e19e39505bfa352a71f
1,160
game-app
MIT License
platform/projectModel-api/src/com/intellij/workspaceModel/ide/GlobalWorkspaceModelCache.kt
allotria
37,974,385
false
null
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. package com.intellij.workspaceModel.ide import com.intellij.openapi.application.ApplicationManager import com.intellij.workspaceModel.storage.EntityStorage import org.jetbrains.annotations.ApiStatus @ApiStatus.Internal interface GlobalWorkspaceModelCache { fun loadCache(): EntityStorage? fun scheduleCacheSave() companion object { fun getInstance(): GlobalWorkspaceModelCache? { val application = ApplicationManager.getApplication() return if (!application.isUnitTestMode) application.getService(GlobalWorkspaceModelCache::class.java) else null } } }
1
null
1
1
9b9e3972a437d1a08fc73370fb09b9f45527dd2a
704
intellij-community
Apache License 2.0
authorization-server/src/main/kotlin/io/github/xsmirnovx/oauth2/server/adapters/database/converter/StringListToStringConverter.kt
xsmirnovx
446,996,762
false
null
package io.github.xsmirnovx.oauth2.server.adapters.database.converter import java.util.* import javax.persistence.AttributeConverter import javax.persistence.Converter @Converter class StringListToStringConverter : AttributeConverter<Set<String>?, String> { // TODO: refactor without optional override fun convertToDatabaseColumn(attribute: Set<String>?): String { return Optional.ofNullable(attribute) .filter { attr: Set<String> -> attr.isNotEmpty() } .map { java.lang.String.join(",", attribute) } .orElse("") } override fun convertToEntityAttribute(dbData: String): Set<String> { return Optional.ofNullable(dbData) .filter { data: String -> data.trim { it <= ' ' }.isNotEmpty() } .map { data: String -> setOf(*data.split(",").toTypedArray()) } .orElseGet { setOf() } } }
4
Kotlin
1
0
44e6cee2e978132938857c497342d78648fcef77
886
spring-authorization-server-demo
Apache License 2.0
app/src/main/java/com/bossed/waej/eventbus/EBOpenFinish.kt
Ltow
710,230,789
false
{"Kotlin": 2304560, "Java": 395495, "HTML": 71364}
package com.bossed.waej.eventbus data class EBOpenFinish(var isFinish: Boolean)
0
Kotlin
0
0
8c2e9928f6c47484bec7a5beca32ed4b10200f9c
81
wananexiu
Mulan Permissive Software License, Version 2
wanandroid/app/src/main/kotlin/com/buyehou/wanandroid/model/Pager.kt
chenglongsheng
568,287,738
false
{"Kotlin": 35200, "AIDL": 425}
package com.buyehou.wanandroid.model /** * @author Rosen */ data class Pager<T>( val curPage: Int, val datas: List<T>?, val offset: Int, val over: Boolean, val pageCount: Int, val size: Int, val total: Int )
0
Kotlin
0
1
dd99b5ba3e19a72054bc782a12c88903385bbd05
238
AndroidDemo
MIT License
src/main/kotlin/com/github/vove7/retrofitrestclient2/services/MyApplicationService.kt
Vove7
211,596,099
false
null
package com.github.vove7.retrofitrestclient2.services import com.github.vove7.retrofitrestclient2.MyBundle class MyApplicationService { init { println(MyBundle.message("applicationService")) } }
2
Kotlin
6
50
d8650bef5eede23f7e9197af1c5db961e3a89f73
214
retrofit-rest-client
Apache License 2.0
src/main/kotlin/com/lykke/matching/engine/services/validators/input/impl/CashSwapOperationInputValidatorImpl.kt
MyJetWallet
334,417,928
true
{"Kotlin": 1903525, "Java": 39278}
package com.lykke.matching.engine.services.validators.input.impl import com.lykke.matching.engine.holders.ApplicationSettingsHolder import com.lykke.matching.engine.incoming.parsers.data.CashSwapParsedData import com.lykke.matching.engine.messages.wrappers.CashSwapOperationMessageWrapper import com.lykke.matching.engine.services.validators.impl.ValidationException import com.lykke.matching.engine.services.validators.input.CashSwapOperationInputValidator import com.lykke.matching.engine.utils.NumberUtils import org.apache.log4j.Logger import org.springframework.beans.factory.annotation.Autowired import org.springframework.stereotype.Component @Component class CashSwapOperationInputValidatorImpl @Autowired constructor(private val applicationSettingsHolder: ApplicationSettingsHolder) : CashSwapOperationInputValidator { companion object { private val LOGGER = Logger.getLogger(CashSwapOperationInputValidatorImpl::class.java.name) } override fun performValidation(cashSwapParsedData: CashSwapParsedData) { isAssetExist(cashSwapParsedData) isAssetEnabled(cashSwapParsedData) isVolumeAccuracyValid(cashSwapParsedData) } private fun isAssetExist(cashSwapParsedData: CashSwapParsedData) { val cashSwapContext = getCashSwapContext(cashSwapParsedData) if (cashSwapContext.swapOperation.asset1 == null || cashSwapContext.swapOperation.asset2 == null) { val swapOperation = cashSwapContext.swapOperation LOGGER.info( "Cash swap operation (${swapOperation.externalId}) from client ${swapOperation.walletId1}, asset ${cashSwapParsedData.assetId1} " + "to client ${swapOperation.walletId2}, asset ${cashSwapParsedData.assetId2} " + ": unknown asset" ) throw ValidationException(ValidationException.Validation.UNKNOWN_ASSET) } } private fun isAssetEnabled(cashSwapParsedData: CashSwapParsedData) { val cashSwapContext = getCashSwapContext(cashSwapParsedData) if (applicationSettingsHolder.isAssetDisabled(cashSwapContext.swapOperation.asset1!!.symbol) || applicationSettingsHolder.isAssetDisabled( cashSwapContext.swapOperation.asset2!!.symbol ) ) { val swapOperation = cashSwapContext.swapOperation LOGGER.info( "Cash swap operation (${swapOperation.externalId}) from client ${swapOperation.walletId1}, asset ${cashSwapParsedData.assetId1} " + "to client ${swapOperation.walletId2}, asset ${cashSwapParsedData.assetId2} " + ": disabled asset" ) throw ValidationException(ValidationException.Validation.DISABLED_ASSET) } } private fun isVolumeAccuracyValid(cashSwapParsedData: CashSwapParsedData) { val cashSwapContext = getCashSwapContext(cashSwapParsedData) val swapOperation = cashSwapContext.swapOperation var volumeValid = NumberUtils.isScaleSmallerOrEqual( swapOperation.volume1, swapOperation.asset1!!.accuracy ) if (!volumeValid) { LOGGER.info( "Volume accuracy invalid fromClient ${swapOperation.walletId1}, " + "to client ${swapOperation.walletId2} assetId: ${cashSwapParsedData.assetId1}, volume: ${swapOperation.volume1}" ) throw ValidationException(ValidationException.Validation.INVALID_VOLUME_ACCURACY) } volumeValid = NumberUtils.isScaleSmallerOrEqual( swapOperation.volume2, swapOperation.asset2!!.accuracy ) if (!volumeValid) { LOGGER.info( "Volume accuracy invalid fromClient ${swapOperation.walletId1}, " + "to client ${swapOperation.walletId2} assetId: ${cashSwapParsedData.assetId2}, volume: ${swapOperation.volume2}" ) throw ValidationException(ValidationException.Validation.INVALID_VOLUME_ACCURACY) } } private fun getCashSwapContext(cashSwapParsedData: CashSwapParsedData) = (cashSwapParsedData.messageWrapper as CashSwapOperationMessageWrapper).context!! }
0
Kotlin
1
0
fad1a43743bd7b833bfa4f1490da5e5350b992ff
4,247
MatchingEngine
MIT License
ui/src/main/java/com/pyamsoft/pydroid/ui/internal/billing/listitem/BillingItemContent.kt
semihcebrail
392,469,502
true
{"Kotlin": 589018}
/* * Copyright 2020 Peter Kenji Yamanaka * * 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.pyamsoft.pydroid.ui.internal.billing.listitem import android.view.ViewGroup import com.pyamsoft.pydroid.arch.BaseUiView import com.pyamsoft.pydroid.arch.UiRender import com.pyamsoft.pydroid.billing.BillingSku import com.pyamsoft.pydroid.ui.databinding.BillingItemContentBinding internal class BillingItemContent internal constructor(parent: ViewGroup) : BaseUiView<BillingItemViewState, Nothing, BillingItemContentBinding>(parent) { override val viewBinding = BillingItemContentBinding::inflate override val layoutRoot by boundView { billingItemContentRoot } init { doOnTeardown { clear() } } private fun clear() { binding.billingItemTitle.text = "" binding.billingItemDescription.text = "" } override fun onRender(state: UiRender<BillingItemViewState>) { state.mapChanged { it.sku }.render(viewScope) { handleSku(it) } } private fun handleSku(sku: BillingSku) { binding.billingItemTitle.text = sku.title binding.billingItemDescription.text = sku.description } }
0
null
0
0
b24ac81ec106add94f29bf894cf02c31aa2c66df
1,636
pydroid
Apache License 2.0
app/src/main/java/com/ready/lolchamps/repository/DetailRepository.kt
KimReady
396,788,559
false
null
package com.ready.lolchamps.repository import com.ready.lolchamps.model.ChampionInfo import com.ready.lolchamps.ui.base.UiState import kotlinx.coroutines.flow.Flow interface DetailRepository { fun getChampionInfo(championId: String): Flow<UiState<ChampionInfo>> }
0
Kotlin
3
72
3d26627077bc04625ac149b5cd2cc3150f173a25
269
LOL-Champs
Apache License 2.0
app/src/main/java/com/example/archcomp/ui/ProductsFragment.kt
richardhdezf
471,168,398
false
{"Kotlin": 23414}
package com.example.archcomp.ui import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.fragment.app.Fragment import androidx.fragment.app.viewModels import com.example.archcomp.MainApplication import com.example.archcomp.data.Product import com.example.archcomp.databinding.FragmentProductsBinding import com.google.android.material.snackbar.Snackbar class ProductsFragment : Fragment() { private lateinit var binding: FragmentProductsBinding private val productsViewModel: ProductsViewModel by viewModels { ProductsViewModelFactory( MainApplication.productsRepository, MainApplication.favoritesRepository ) } override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View { binding = FragmentProductsBinding.inflate(inflater, container, false) val root: View = binding.root val productListener = object : ProductListener { override fun onClick(item: Product) { productsViewModel.insertFavorite(item) Snackbar.make(root, "item added to favorites", Snackbar.LENGTH_LONG) .setAction("Action", null).show() } } val productsAdapter = ProductsAdapter(productListener) val productsView = binding.productsView productsView.adapter = productsAdapter productsViewModel .getAll() .observe(viewLifecycleOwner) { itemList -> productsAdapter.submitList(itemList) } return root } }
0
Kotlin
0
0
e1dd0aae378c6ec984053628a73ae4b832e46c8b
1,688
android-architecture-components
Apache License 2.0
lib/src/main/java/com/github/eklipse2k8/charting/data/parceler/DrawableParceler.kt
eklipse2k8
403,391,938
true
{"Kotlin": 945921, "Java": 57298}
package com.github.eklipse2k8.charting.data.parceler import android.graphics.Bitmap import android.graphics.drawable.BitmapDrawable import android.graphics.drawable.Drawable import android.os.Parcel import kotlinx.parcelize.Parceler object DrawableParceler : Parceler<Drawable?> { override fun create(parcel: Parcel): Drawable { val bitmap = parcel.readParcelable<Bitmap>(javaClass.classLoader) return BitmapDrawable(bitmap) } override fun Drawable?.write(parcel: Parcel, flags: Int) { if (this is BitmapDrawable) { parcel.writeParcelable(bitmap, flags) } } }
0
Kotlin
0
0
29d416f36d7fd1b6af13082c2ef6b7d6abe0cab8
593
ComposeChart
Apache License 2.0
app/src/main/java/com/bu/selfstudy/ui/mark/MarkFragment.kt
a0979470582
345,524,123
false
null
package com.bu.selfstudy.ui.mark import android.content.Context import android.graphics.drawable.StateListDrawable import androidx.appcompat.view.ActionMode import android.os.Bundle import android.view.* import androidx.activity.addCallback import androidx.appcompat.app.AppCompatActivity import androidx.core.view.isVisible import androidx.fragment.app.Fragment import androidx.fragment.app.activityViewModels import androidx.fragment.app.setFragmentResultListener import androidx.fragment.app.viewModels import androidx.navigation.fragment.findNavController import androidx.navigation.ui.NavigationUI import androidx.navigation.ui.onNavDestinationSelected import androidx.recyclerview.selection.SelectionPredicates import androidx.recyclerview.selection.SelectionTracker import androidx.recyclerview.selection.StorageStrategy import com.bu.selfstudy.ui.main.ActivityViewModel import com.bu.selfstudy.ui.main.MainActivity import com.bu.selfstudy.NavGraphDirections import com.bu.selfstudy.R import com.bu.selfstudy.databinding.FragmentMarkBinding import com.bu.selfstudy.tool.* import com.bu.selfstudy.tool.myselectiontracker.IdItemDetailsLookup import com.bu.selfstudy.tool.myselectiontracker.IdItemKeyProvider class MarkFragment : Fragment() { private val viewModel: MarkViewModel by viewModels() private val binding: FragmentMarkBinding by viewBinding() private val adapter = MarkAdapter(fragment = this) private val activityViewModel: ActivityViewModel by activityViewModels() private lateinit var tracker: SelectionTracker<Long> private var actionMode: ActionMode? = null override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View { binding.recyclerView.let { it.adapter = adapter it.setHasFixedSize(true) } return binding.root } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { viewModel.wordListLiveData.observe(viewLifecycleOwner) { binding.markNotFound.isVisible = it.isEmpty() adapter.submitList(it) viewModel.refreshWordIdList(it) } viewModel.databaseEvent.observe(viewLifecycleOwner) { when (it?.first) { "delete" -> return@observe "mark" -> return@observe "cancelMark" -> return@observe "update" -> "更新已保存".showToast() "copy"-> ("已複製 ${it.second?.get("count")} 個單字到 「${activityViewModel.getBookName( it.second?.get("bookId") as Long)}」").showToast() "move"-> ("已轉移 ${it.second?.get("count")} 個單字到 「${activityViewModel.getBookName( it.second?.get("bookId") as Long)}」").showToast() } } binding.toolbar.setOnClickListener { findNavController().navigate(R.id.searchFragment) } setDialogResultListener() initSpeedDial() initFastScroll() initSelectionTracker() } private fun initFastScroll() { FastScroller(binding.recyclerView, requireContext().getDrawable(R.drawable.thumb_drawable) as StateListDrawable, requireContext().getDrawable(R.drawable.line_drawable), requireContext().getDrawable(R.drawable.thumb_drawable) as StateListDrawable, requireContext().getDrawable(R.drawable.line_drawable), resources.getDimensionPixelSize(androidx.recyclerview.R.dimen.fastscroll_default_thickness), resources.getDimensionPixelSize(androidx.recyclerview.R.dimen.fastscroll_minimum_range), resources.getDimensionPixelOffset(androidx.recyclerview.R.dimen.fastscroll_margin) ) } private fun setDialogResultListener() { setFragmentResultListener("DialogDeleteCommon") { _, _ -> viewModel.longPressedWordIdList.let { viewModel.deleteWord(it) } } } override fun onActivityCreated(savedInstanceState: Bundle?) { super.onActivityCreated(savedInstanceState) setHasOptionsMenu(true) (activity as MainActivity).let { it.setSupportActionBar(binding.toolbar) NavigationUI.setupActionBarWithNavController( it, findNavController(), it.appBarConfiguration) } } private fun initSpeedDial() { with(binding.speedDialButton){ createChildButtonAndText( R.id.book_fragment_fab_add_word, R.drawable.ic_baseline_search_24, "新增單字" ){ button, textView -> findNavController().navigate(R.id.searchFragment) } createChildButtonAndText( R.id.book_fragment_fab_add_book, R.drawable.ic_baseline_bookmark_24, "新增題庫" ){ button, textView -> findNavController().navigate(R.id.addBookFragment) } mainButton.setOnLongClickListener { resources.getString(R.string.FAB_main).showToast() true } } } override fun onAttach(context: Context) { super.onAttach(context) requireActivity().onBackPressedDispatcher.addCallback(this){ if(binding.speedDialButton.mainButtonIsOpen){ binding.speedDialButton.toggleChange(true) return@addCallback } findNavController().popBackStack() } } private fun initSelectionTracker() { if(::tracker.isInitialized) return tracker = SelectionTracker.Builder( "recycler-view-word-fragment", binding.recyclerView, IdItemKeyProvider(viewModel.wordIdList, true), IdItemDetailsLookup(binding.recyclerView, viewModel.wordIdList, true), StorageStrategy.createLongStorage() ).withSelectionPredicate(SelectionPredicates.createSelectAnything()) .build().also { adapter.tracker = it } val selectionObserver = object : SelectionTracker.SelectionObserver<Long>() { override fun onSelectionChanged() { super.onSelectionChanged() if (!tracker.hasSelection()) { actionMode?.finish() } else { viewModel.refreshLongPressedWord(tracker.selection.toList()) if (actionMode == null) { actionMode = (activity as AppCompatActivity) .startSupportActionMode(actionModeCallback) } actionMode?.title = "${tracker!!.selection.size()}/${viewModel.wordListLiveData.value?.size}" actionMode?.invalidate() } } override fun onSelectionRestored() { super.onSelectionRestored() onSelectionChanged() } } tracker.addObserver(selectionObserver) } fun updateMarkWord(wordId:Long, isMark: Boolean){ viewModel.updateMarkWord(wordId, isMark = isMark) } override fun onOptionsItemSelected(item: MenuItem): Boolean { //自動連結與item id相同的fragment id return item.onNavDestinationSelected(findNavController()) || super.onOptionsItemSelected(item) } override fun onCreateOptionsMenu(menu: Menu, inflater: MenuInflater) { super.onCreateOptionsMenu(menu, inflater) inflater.inflate(R.menu.book_toolbar, menu) } override fun onSaveInstanceState(outState: Bundle) { super.onSaveInstanceState(outState) tracker.onSaveInstanceState(outState) } override fun onViewStateRestored(savedInstanceState: Bundle?) { super.onViewStateRestored(savedInstanceState) tracker.onRestoreInstanceState(savedInstanceState) } val actionModeCallback = object : ActionMode.Callback { /**對於搜尋結果進行操作, 會將ActionMode疊在SearchView上方, 此時鍵盤不會消失 造成使用者能在看不到搜尋框時查詢, 因此ActionMode出現就必須關閉鍵盤 */ override fun onCreateActionMode(mode: ActionMode, menu: Menu): Boolean { mode.menuInflater.inflate(R.menu.word_action_mode, menu) closeKeyboard() return true } override fun onPrepareActionMode(mode: ActionMode, menu: Menu): Boolean{ menu.findItem(R.id.action_edit).isEnabled = (viewModel.longPressedWordIdList.size == 1) return true } override fun onActionItemClicked(mode: ActionMode, item: MenuItem): Boolean { actionModeMenuCallback(item.itemId) return true } override fun onDestroyActionMode(mode: ActionMode) { tracker?.clearSelection() actionMode = null } } private fun actionModeMenuCallback(itemId: Int){ when (itemId) { R.id.action_delete -> findNavController().navigate( NavGraphDirections.actionGlobalDialogDeleteCommon( "刪除單字", "是否刪除 ${viewModel.longPressedWordIdList.size} 個單字?" ) ) R.id.action_choose_all -> tracker!!.setItemsSelected( viewModel.wordIdList, viewModel.wordIdList.size != tracker!!.selection.size() ) R.id.action_mark-> viewModel.updateMarkWord( *viewModel.longPressedWordIdList.toLongArray(), isMark = viewModel.longPressedWordIdList.any { !viewModel.wordIdList.contains(it) } ) R.id.action_copy -> { viewModel.actionType = "copy" findNavController().navigate( NavGraphDirections.actionGlobalDialogChooseBook( title = "複製到題庫" ) ) } R.id.action_move -> { viewModel.actionType = "move" findNavController().navigate( NavGraphDirections.actionGlobalDialogChooseBook( title = "轉移到題庫" ) ) } R.id.action_edit->{ viewModel.getWord(viewModel.longPressedWordIdList.first())?.let { word-> actionMode?.finish() findNavController().navigate( NavGraphDirections.actionGlobalEditWordFragment(word) ) } } } } }
0
null
1
2
5c22ddd02c04eb58c4606f3b16ef5900466cba16
10,870
SelfStudy
Apache License 2.0
base-amigobox/src/main/kotlin/org/ossiaustria/amigobox/ui/loading/LoginCleanupDaoService.kt
ossi-austria
430,606,582
false
{"Kotlin": 456155, "HTML": 2066, "Dockerfile": 441}
package org.ossiaustria.amigobox.ui.loading import org.ossiaustria.lib.domain.database.AlbumDao import org.ossiaustria.lib.domain.database.AlbumShareDao import org.ossiaustria.lib.domain.database.CallDao import org.ossiaustria.lib.domain.database.GroupDao import org.ossiaustria.lib.domain.database.MessageDao import org.ossiaustria.lib.domain.database.MultimediaDao import org.ossiaustria.lib.domain.database.NfcInfoDao import org.ossiaustria.lib.domain.database.PersonDao import org.ossiaustria.lib.domain.services.LoginCleanupService import timber.log.Timber class LoginCleanupDaoService( private val albumDao: AlbumDao, private val albumShareDao: AlbumShareDao, private val callDao: CallDao, private val groupDao: GroupDao, private val messageDao: MessageDao, private val multimediaDao: MultimediaDao, private val nfcInfoDao: NfcInfoDao, private val personDao: PersonDao, ) : LoginCleanupService { override suspend fun cleanup() { Timber.w("cleanup! Delete all locally stored data") albumDao.deleteAll() albumShareDao.deleteAll() callDao.deleteAll() groupDao.deleteAll() messageDao.deleteAll() multimediaDao.deleteAll() nfcInfoDao.deleteAll() personDao.deleteAll() } }
0
Kotlin
0
1
8d8b167555d62e6ceb58a20efe9d6ee0c609b199
1,287
amigo-box
MIT License
src/test/kotlin/com/bardsoftware/sqool/codegen/MatcherSpecTest.kt
dbarashev
537,530,039
false
{"Kotlin": 288225, "PLpgSQL": 80531, "TypeScript": 62308, "Vue": 57792, "FreeMarker": 21105, "Shell": 1979, "JavaScript": 1865, "HTML": 1573, "Dockerfile": 124}
/* * Copyright (c) BarD Software s.r.o 2019 * * This file is a part of SQooL, a service for running SQL contests. * * 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.bardsoftware.sqool.codegen import com.bardsoftware.sqool.codegen.task.spec.MatcherSpec import com.bardsoftware.sqool.codegen.task.spec.RelationSpec import com.bardsoftware.sqool.codegen.task.spec.SqlDataType import com.bardsoftware.sqool.codegen.task.spec.TaskResultColumn import org.junit.jupiter.api.Test import org.junit.jupiter.api.Assertions.* class MatcherSpecTest { private val relationSpec: RelationSpec private val matcherSpec: MatcherSpec init { val keyAttribute = listOf( TaskResultColumn("ship", SqlDataType.TEXT), TaskResultColumn("port", SqlDataType.INT)) val nonKeyAttributes = listOf( TaskResultColumn("transfers_num", SqlDataType.INT), TaskResultColumn("transfer_size", SqlDataType.BIGINT), TaskResultColumn("product", SqlDataType.TEXT)) relationSpec = RelationSpec(keyAttribute, nonKeyAttributes) matcherSpec = MatcherSpec(relationSpec) } @Test fun testWrongKeyColsProjectionDefaultMessage() { assertEquals("Множество кортежей (ship, port) отличается от результатов робота", matcherSpec.wrongKeyColsProjMessage) } @Test fun testRightKeyColsProjectionDefaultMessage() { assertEquals("Кортежи (ship, port) найдены верно", matcherSpec.rightKeyColsProjMessage) } @Test fun testDiffErrorDefaultMessage() { val defaultDiffErrorMessage = matcherSpec.getDiffErrorMessage(TaskResultColumn("transfers_num", SqlDataType.INT)) assertEquals("Максимальное расхождение transfers_num равно ", defaultDiffErrorMessage) } @Test fun testSetDiffErrorMessage() { val transfersNum = TaskResultColumn("transfers_num", SqlDataType.INT) val diffErrorMessage = "Максимальное расхождение количества перевозок равно " matcherSpec.setDiffErrorMessage(transfersNum, diffErrorMessage) assertEquals(diffErrorMessage, matcherSpec.getDiffErrorMessage(transfersNum)) } @Test fun testSetNonNumericAttributeDiffErrorMessageThrowsException() { val exception = assertThrows(IllegalArgumentException::class.java) { matcherSpec.setDiffErrorMessage(TaskResultColumn("product", SqlDataType.TEXT), "sth") } assertEquals("Non-numeric attributes can't have a difference error", exception.message) } @Test fun testSetKeyAttributeDiffErrorMessageThrowsException() { val exception = assertThrows(IllegalArgumentException::class.java) { matcherSpec.setDiffErrorMessage(TaskResultColumn("port", SqlDataType.INT), "sth") } assertEquals("Non-key attributes can't have a difference error", exception.message) } @Test fun testSetNotExistingAttributeDiffErrorMessageThrowsException() { val exception = assertThrows(IllegalArgumentException::class.java) { matcherSpec.setDiffErrorMessage(TaskResultColumn("foo", SqlDataType.INT), "sth") } assertEquals("No such non-key attribute in the relation", exception.message) } @Test fun testGetNonNumericAttributeDiffErrorMessageThrowsException() { val exception = assertThrows(IllegalArgumentException::class.java) { matcherSpec.getDiffErrorMessage(TaskResultColumn("product", SqlDataType.TEXT)) } assertEquals("Non-numeric attributes can't have a difference error", exception.message) } @Test fun testGetKeyAttributeDiffErrorMessageThrowsException() { val exception = assertThrows(IllegalArgumentException::class.java) { matcherSpec.getDiffErrorMessage(TaskResultColumn("port", SqlDataType.INT)) } assertEquals("Non-key attributes can't have a difference error", exception.message) } @Test fun testGetNotExistingAttributeDiffErrorMessageThrowsException() { val exception = assertThrows(IllegalArgumentException::class.java) { matcherSpec.getDiffErrorMessage(TaskResultColumn("foo", SqlDataType.INT)) } assertEquals("No such non-key attribute in the relation", exception.message) } }
0
Kotlin
0
0
464c049de3ad44e925d2372f5677e0054155e734
4,558
sqool
Apache License 2.0
app/src/main/java/juanocampo/test/memoryflipgame/presentation/entities/GameCardViewType.kt
ingjuanocampo
242,367,721
false
null
package juanocampo.test.memoryflipgame.presentation.entities import juanocampo.test.memoryflipgame.R import juanocampo.test.memoryflipgame.view.base.delegate.RecyclerViewType data class GameCardViewType(val id: String, private val imageRes: Int, var isRevealed: Boolean, val index: Int): RecyclerViewType { fun getImageResource(): Int { return if (isRevealed) imageRes else R.drawable.card_back } override fun getDelegateId(): Int { return index } override fun getViewType(): Int { return ViewTypes.GAME_CARD.ordinal } override fun equals(other: Any?): Boolean { return if (other is GameCardViewType) { other.id.compareTo(id) == 0 && other.isRevealed == isRevealed } else { false } } }
0
Kotlin
0
1
78c9719864ea1b78ee9d43b904d2694f9f683133
796
MemoryCardsGame
Apache License 2.0
src/main/kotlin/aosp/working/diffextractor/JGitUtil.kt
AOSPworking
479,370,855
false
null
package aosp.working.diffextractor import com.github.gumtreediff.tree.Tree import org.eclipse.jdt.core.dom.CompilationUnit import org.eclipse.jgit.diff.DiffEntry import org.eclipse.jgit.diff.DiffFormatter import org.eclipse.jgit.lib.* import org.eclipse.jgit.revwalk.RevCommit import org.eclipse.jgit.treewalk.CanonicalTreeParser import org.eclipse.jgit.treewalk.TreeWalk import org.eclipse.jgit.util.io.DisabledOutputStream import java.io.ByteArrayOutputStream import java.io.File class JGitUtil(val repository: Repository) { constructor(repoPath: String): this(makeRepository(repoPath)) /** * 根据一个 commit,获得其与先前 parent commit 间所有存在 diff 的文件名。 * @param commit * @return */ fun getChangeFilesByCommit(commit: RevCommit): List<String> { val result: MutableSet<String> = mutableSetOf() val diffMap = this.getParentMappedDiffEntry(commit) for ((_, diffEntries) in diffMap) { diffEntries.forEach { diffEntry -> getNeedPathFromDiffEntry(diffEntry) .let { if (it !in result) result.add(it) } } } return result.toList() } /** * 根据两个 commit,获得其间的差异,并且获得差异相关的所有文件名。 * 这两个传入的 commit 间没有 parent 关系,任意两个都可以。 * @param curr 当前 commit * @param prev 另一个 commit */ fun getChangeFilesByCommit(curr: RevCommit, prev: RevCommit): List<String> { val result: MutableSet<String> = mutableSetOf() val entries = this.getParentMappedDiffEntry(curr, prev) entries.forEach { entry -> getNeedPathFromDiffEntry( entry ).let { if (it !in result) result.add(it) } } return result.toList() } /** * 传入一个 RevCommit,然后获得他的所有 DiffEntry * 直接传入 RevCommit 能够避免 RevWalk 在 parseCommit 时带来的开销,极大提高性能 * @param curr * @return Map key 是 parent 的 commit,value 是那个 commit 对应的 diff */ fun getParentMappedDiffEntry(curr: RevCommit): Map<RevCommit, List<DiffEntry>> { val result: MutableMap<RevCommit, List<DiffEntry>> = mutableMapOf() curr.parents.forEach { result[it] = this.getParentMappedDiffEntry(curr, it) } return result } /** * 根据 current 和 previous 获取 List<DiffEntry> * @param curr 当前的 commit * @param prev 过去的某个 commit,一般来说是 current commit 的其中一个 parent */ fun getParentMappedDiffEntry(curr: RevCommit, prev: RevCommit): List<DiffEntry> { val reader: ObjectReader = this.repository.newObjectReader() val newTree: ObjectId = curr.tree.id val oldTree: ObjectId = prev.tree.id val newTreeIter = CanonicalTreeParser() val oldTreeIter = CanonicalTreeParser() DiffFormatter(DisabledOutputStream.INSTANCE).use { it.setRepository(this.repository) newTreeIter.reset(reader, newTree) oldTreeIter.reset(reader, oldTree) return it.scan(oldTreeIter, newTreeIter) } } /** * 根据 commit 的 hash id 获得对应的 RevCommit * @param commitId 传入的 commit hash id */ fun parseRevCommit(commitId: String): RevCommit { return this.repository.parseCommit(this.repository.resolve(commitId)) } /** * 获得某 commit 下的某个名为 fileName 的文件 * @param fileName 文件名 * @param commit */ fun extract(fileName: String, commit: RevCommit): ByteArray = TreeWalk.forPath(this.repository, fileName, commit.tree).use { val objectId = it.getObjectId(0) val objectLoader: ObjectLoader = this.repository.open(objectId) val os = ByteArrayOutputStream() objectLoader.copyTo(os) os.toByteArray() } companion object { /** * 给定一个文件系统中的 repo .git 路径,得到一个 Repository 对象。 * @param repoPath */ fun makeRepository(repoPath: String): Repository = RepositoryBuilder() .setGitDir(File(repoPath)) .readEnvironment() .findGitDir() .build() /** * 获得在 diff 中需要的路径。 * @param diffEntry */ fun getNeedPathFromDiffEntry(diffEntry: DiffEntry): String = when (diffEntry.changeType) { DiffEntry.ChangeType.ADD, DiffEntry.ChangeType.COPY, DiffEntry.ChangeType.RENAME -> diffEntry.newPath DiffEntry.ChangeType.MODIFY, DiffEntry.ChangeType.DELETE -> diffEntry.oldPath } } }
0
Kotlin
0
0
012e587f162b810356f5579b1e3ac96823336a1e
4,506
diff_extractor
MIT License
data/src/main/kotlin/team/duckie/app/android/data/quiz/model/GetQuizResponse.kt
duckie-team
503,869,663
false
{"Kotlin": 1819917}
/* * Designed and developed by Duckie Team, 2022 * * Licensed under the MIT. * Please see full license: https://github.com/duckie-team/duckie-android/blob/develop/LICENSE */ package team.duckie.app.android.data.quiz.model import com.fasterxml.jackson.annotation.JsonProperty import team.duckie.app.android.data.challengecomment.model.ChallengeCommentResponse import team.duckie.app.android.data.exam.model.ExamData import team.duckie.app.android.data.exam.model.ProblemData import team.duckie.app.android.data.user.model.UserResponse internal data class GetQuizResponse( @field:JsonProperty("id") val id: Int? = null, @field:JsonProperty("correctProblemCount") val correctProblemCount: Int? = null, @field:JsonProperty("exam") val exam: ExamData? = null, @field:JsonProperty("score") val score: Int? = null, @field:JsonProperty("time") val time: Double? = null, @field:JsonProperty("user") val user: UserResponse? = null, @field:JsonProperty("wrongProblem") val wrongProblem: ProblemData? = null, @field:JsonProperty("wrongAnswer") val wrongAnswer: MeAndMostWrongAnswer? = null, @field:JsonProperty("ranking") val ranking: Int? = null, @field:JsonProperty("requirementAnswer") val requirementAnswer: String? = null, @field:JsonProperty("isBestRecord") val isBestRecord: Boolean? = null, @field:JsonProperty("popularComments") val popularComments: PopularComments?, @field:JsonProperty("solveRank") val solveRank: Int? = null, @field:JsonProperty("percentileRank") val percentileRank: String? = null, ) { data class PopularComments( @field:JsonProperty("total") val total: Int, @field:JsonProperty("data") val data: List<ChallengeCommentResponse>, ) data class MeAndMostWrongAnswer( @field:JsonProperty("me") val me: SimpleWrongAnswer, @field:JsonProperty("most") val most: SimpleWrongAnswer, ) data class SimpleWrongAnswer( @field:JsonProperty("total") val total: Int, @field:JsonProperty("data") val data: String, ) }
32
Kotlin
1
8
5dbd5b7a42c621931d05a96e66431f67a3a50762
2,159
duckie-android
MIT License
compiler/testData/moduleProtoBuf/jvmPackageNameMultifileClass/K2_A.kt
JetBrains
3,432,266
false
{"Kotlin": 79571273, "Java": 6776465, "Swift": 4063829, "C": 2609744, "C++": 1957654, "Objective-C++": 175279, "JavaScript": 130754, "Python": 59855, "Shell": 34920, "Objective-C": 21463, "Lex": 21452, "Batchfile": 11382, "CSS": 11368, "Ruby": 10470, "Dockerfile": 9907, "Groovy": 7092, "EJS": 5241, "CMake": 4473, "HTML": 2699, "Puppet": 1698, "FreeMarker": 1393, "Roff": 725, "Scala": 80}
@file:Suppress("INVISIBLE_MEMBER", "INVISIBLE_REFERENCE") @file:JvmPackageName("j2") @file:JvmName("K2") @file:JvmMultifileClass package k2 fun f1() {}
181
Kotlin
5748
49,172
33eb9cef3d146062c103f9853d772f0a1da0450e
153
kotlin
Apache License 2.0
src/test/kotlin/tests2023/Day004Test.kt
teodor-vasile
573,434,400
false
{"Kotlin": 37611}
package tests2023 import main.kotlin2023.Day004 import org.junit.Test import org.junit.jupiter.api.Assertions.assertEquals import readInputLines internal class Day004Test { private val day004 = Day004() @Test fun day05part1() { val testInput = readInputLines("Day04_2023_Part1") assertEquals(23847, day004.part1(testInput)) } @Test fun day05part2() { val testInput = readInputLines("Day04_2023_Part1") assertEquals(8570000, day004.part2(testInput)) } }
0
Kotlin
0
0
4307622877f4b93050de653ce325fecc5d26405a
518
aoc-2022-kotlin
Apache License 2.0
reflekt-plugin/src/test/resources/org/jetbrains/reflekt/plugin/analysis/data/objects3_test/project/test/Main.kt
JetBrains-Research
293,503,377
false
{"Kotlin": 397259, "Java": 35379}
package org.jetbrains.reflekt.test import org.jetbrains.reflekt.Reflekt fun main() { val objects = Reflekt.objects().withSuperTypes(A1::class) val objects1 = Reflekt.objects().withSuperType<A1>() }
13
Kotlin
9
325
ae53618880e5eb610ddeb2792d63208eade951a8
208
reflekt
Apache License 2.0
app/src/main/java/com/adaldosso/spendykt/persistence/UsersDatabase.kt
daldosso
75,467,676
false
{"Gradle": 3, "Java Properties": 2, "Shell": 1, "Text": 1, "Ignore List": 2, "Batchfile": 1, "Markdown": 1, "XML": 135, "JSON": 1, "Proguard": 1, "Java": 15, "Kotlin": 23}
package com.adaldosso.spendykt.persistence import android.arch.persistence.room.Database import android.arch.persistence.room.Room import android.arch.persistence.room.RoomDatabase import android.content.Context /** * The Room database that contains the Users table */ @Database(entities = [User::class], version = 2) abstract class UsersDatabase : RoomDatabase() { abstract fun userDao(): UserDao companion object { @Volatile private var INSTANCE: UsersDatabase? = null fun getInstance(context: Context): UsersDatabase = INSTANCE ?: synchronized(this) { INSTANCE ?: buildDatabase(context).also { INSTANCE = it } } private fun buildDatabase(context: Context) = Room.databaseBuilder(context.applicationContext, UsersDatabase::class.java, "EstendoApp.db") // .addMigrations(MIGRATION_1_2) .fallbackToDestructiveMigration() .build() @JvmField val MIGRATION_1_2 = Migration1To2() } }
1
null
1
1
c4caeb372ddb98a21b04bf5cee3852062d544c0e
1,045
SpendyKt
MIT License
compound-library/src/main/java/com/lockwood/compound/delegate/CompoundArrayPositionDelegate.kt
imbeerus
244,343,356
false
{"Kotlin": 71189}
package com.lockwood.compound.delegate import kotlin.properties.ReadWriteProperty import kotlin.reflect.KProperty /** * Property that store drawable related value in [array] at specific [position] * * @param T type of stored value * @param array to store values * @param position of value (drawable) */ internal class CompoundArrayPositionDelegate<T>( private val array: Array<T>, private val position: Int, private val onSet: () -> Unit ) : ReadWriteProperty<Any?, T> { /** * @return value from [array] at [position] */ override fun getValue( thisRef: Any?, property: KProperty<*> ): T { return array[position] } /** * Set value in [array] at [position] and then update state of compound drawables * * @see updateCompoundDrawables */ override fun setValue(thisRef: Any?, property: KProperty<*>, value: T) { array[position] = value onSet() } }
0
Kotlin
3
8
62cd86e16a3c29b44ca0a1739ba683bedf2177e1
964
compound-text-view
Apache License 2.0
product/progress/progress-ui/src/main/java/com/yugyd/quiz/progressui/model/DegreeUiMapper.kt
Yugyd
685,349,849
false
{"Kotlin": 873471, "FreeMarker": 22968, "Fluent": 18}
/* * Copyright 2023 <NAME> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.yugyd.quiz.progressui.model import com.yugyd.quiz.domain.api.model.Degree import com.yugyd.quiz.domain.api.model.Degree.ACADEMIC import com.yugyd.quiz.domain.api.model.Degree.AMATEUR import com.yugyd.quiz.domain.api.model.Degree.CANDIDATE import com.yugyd.quiz.domain.api.model.Degree.DOCTOR import com.yugyd.quiz.domain.api.model.Degree.MASTER import com.yugyd.quiz.domain.api.model.Degree.POSTGRADUATE import com.yugyd.quiz.domain.api.model.Degree.PROFESSOR import com.yugyd.quiz.domain.api.model.Degree.SCHOOLBOY import com.yugyd.quiz.domain.api.model.Degree.STUDENT import javax.inject.Inject internal class DegreeUiMapper @Inject constructor() { fun map(model: Degree) = when (model) { SCHOOLBOY -> DegreeUIModel.SCHOOLBOY AMATEUR -> DegreeUIModel.AMATEUR STUDENT -> DegreeUIModel.STUDENT MASTER -> DegreeUIModel.MASTER POSTGRADUATE -> DegreeUIModel.POSTGRADUATE CANDIDATE -> DegreeUIModel.CANDIDATE DOCTOR -> DegreeUIModel.DOCTOR PROFESSOR -> DegreeUIModel.PROFESSOR ACADEMIC -> DegreeUIModel.ACADEMIC } }
0
Kotlin
1
8
0192d1ccabe96b7ac9f9a844259cca7a018aa6b5
1,727
quiz-platform
Apache License 2.0
plot-builder-portable/src/commonMain/kotlin/jetbrains/datalore/plot/builder/presentation/LabelSpec.kt
JetBrains
176,771,727
false
null
/* * Copyright (c) 2019. JetBrains s.r.o. * Use of this source code is governed by the MIT license that can be found in the LICENSE file. */ package jetbrains.datalore.plot.builder.presentation import jetbrains.datalore.base.geometry.DoubleVector import jetbrains.datalore.base.values.Font interface LabelSpec { val font: Font fun dimensions(labelText: String): DoubleVector fun width(labelText: String): Double fun height(): Double }
97
Kotlin
47
889
c5c66ceddc839bec79b041c06677a6ad5f54e416
460
lets-plot
MIT License
suspender/src/main/java/suspender/compiler/builder/BindingManager.kt
josesamuel
244,080,076
false
{"Gradle": 6, "YAML": 1, "Markdown": 2, "INI": 3, "Shell": 1, "Ignore List": 1, "Batchfile": 1, "Text": 1, "Java": 3, "Kotlin": 11, "HTML": 1, "Java Properties": 1}
package suspender.compiler.builder import java.io.File import javax.annotation.processing.Messager import javax.annotation.processing.ProcessingEnvironment import javax.lang.model.element.Element import javax.lang.model.type.TypeMirror import javax.lang.model.util.Elements /** * Manages kotlin file generation */ open class BindingManager(private val processingEnvironment: ProcessingEnvironment) { companion object { const val KAPT_KOTLIN_GENERATED_OPTION_NAME = "kapt.kotlin.generated" } private val elementUtils: Elements = processingEnvironment.elementUtils private var stringTypeMirror: TypeMirror? = null private var charSequenceTypeMirror: TypeMirror? = null private var listTypeMirror: TypeMirror? = null private var setTypeMirror: TypeMirror? = null private var mapTypeMirror: TypeMirror? = null init { stringTypeMirror = getType("java.lang.String") listTypeMirror = getType("java.util.List") setTypeMirror = getType("java.util.Set") mapTypeMirror = getType("java.util.Map") charSequenceTypeMirror = getType("java.lang.CharSequence") } /** * Returns a [TypeMirror] for the given class */ fun getType(className: String?): TypeMirror { return elementUtils.getTypeElement(className).asType() } /** * Returns a [Element] for the given class */ fun getElement(className: String): Element { var cName = className val templateStart = className.indexOf('<') if (templateStart != -1) { cName = className.substring(0, templateStart).trim() } return elementUtils.getTypeElement(cName) } /** * Generates the abstract publisher class */ fun generateProxy(element: Element) { val kaptKotlinGeneratedDir = processingEnvironment.options[KAPT_KOTLIN_GENERATED_OPTION_NAME]?.replace("kaptKotlin", "kapt") kaptKotlinGeneratedDir?.let { element.annotationMirrors.forEach { it.elementValues.forEach { entry -> if (entry.key.simpleName.toString() == "classesToWrap") { val classesToConvert = entry.value.value as List<Any> classesToConvert.forEach { covertClass -> val convertTypeElement = getElement(covertClass.toString().removeSuffix(".class")) ClassBuilder(convertTypeElement, this).generateSuspenderWrapper().writeTo(File(kaptKotlinGeneratedDir)) } } } } } } fun getMessager(): Messager = processingEnvironment.messager internal fun getFunctiondBuilder(element: Element) = MethodBuilder(element, this) }
1
null
1
1
12ecdaa2830b1211f4e839b2ef9a56c7ad7f6dd9
2,784
Suspender
Apache License 2.0
Kotlin/four/src/main/kotlin/com/nlw/four/domain/exception/BusinessException.kt
brunoredes
341,719,792
false
{"TypeScript": 14215, "Kotlin": 10441}
package com.nlw.four.domain.exception open class BusinessException(message:String): RuntimeException(message) { companion object { private const val serialVersionUID = 1L } }
0
TypeScript
0
1
15127f00e24271ba9a81038c60b1f4e7528d1cd0
191
next-level-week-4
MIT License
app/src/main/java/pl/kamilszustak/justfit/domain/usecase/product/GetProductByIdUseCaseImpl.kt
swistak7171
248,487,099
false
null
package pl.kamilszustak.justfit.domain.usecase.product import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.map import pl.kamilszustak.justfit.common.data.Resource import pl.kamilszustak.justfit.data.repository.ProductRepository import pl.kamilszustak.justfit.domain.mapper.product.ProductEntityMapper import pl.kamilszustak.justfit.domain.model.product.Product import javax.inject.Inject import javax.inject.Singleton @Singleton class GetProductByIdUseCaseImpl @Inject constructor( private val productRepository: ProductRepository, private val productEntityMapper: ProductEntityMapper ) : GetProductByIdUseCase { override fun invoke(id: Long, shouldFetch: Boolean): Flow<Resource<Product>> = productRepository.getById(id, shouldFetch) .map { resource -> resource.mapData { product -> productEntityMapper.map(product) } } }
0
Kotlin
0
1
e1b584010dd7edeaa41c7d432fb398f05a2f5dea
936
JustFit
Apache License 2.0
application/app/src/main/java/com/aaronfodor/android/songquiz/model/repository/PlaylistsRepository.kt
androiddevnotesforks
388,546,486
false
{"Kotlin": 441326}
package com.aaronfodor.android.songquiz.model.repository import com.aaronfodor.android.songquiz.model.AccountService import com.aaronfodor.android.songquiz.model.AccountState import com.aaronfodor.android.songquiz.model.TimeService import com.aaronfodor.android.songquiz.model.api.SpotifyApiService import com.aaronfodor.android.songquiz.model.database.PlaylistDAO import com.aaronfodor.android.songquiz.model.repository.dataclasses.* import javax.inject.Inject import javax.inject.Singleton /** * Injected everywhere as a singleton */ @Singleton class PlaylistsRepository @Inject constructor( private val dao: PlaylistDAO, private val spotifyApiService: SpotifyApiService, private val accountService: AccountService, private val timeService: TimeService ) { fun getPlaylists() : List<Playlist>{ // if logged out, show defaults val dbPlaylists = if(accountService.accountState.value == AccountState.LOGGED_OUT){ dao.getAll(AccountService.DEFAULTS_ACCOUNT_ID) ?: listOf() } // if logged in, load playlists else{ var loadedPlaylists = dao.getAll(accountService.getAccountId()) ?: listOf() val isFirstLoadAfterLogin = accountService.getPublicInfo().isFirstLoadAfterLogin // if this is the first load after login, and there are no playlists if(isFirstLoadAfterLogin && loadedPlaylists.isEmpty()){ // set defaults to user restoreDefaultPlaylists() loadedPlaylists = dao.getAll(accountService.getAccountId()) ?: listOf() } if(isFirstLoadAfterLogin){ // first load after login has finished accountService.firstLoadFinishedAfterLogin() } loadedPlaylists } val playlists = mutableListOf<Playlist>() for(item in dbPlaylists){ playlists.add(item.toPlaylist()) } return playlists.reversed() } fun getLastNPlaylists(number: Int) : List<Playlist>{ // if logged out, show defaults val dbPlaylists = if(accountService.accountState.value == AccountState.LOGGED_OUT){ dao.getLastN(AccountService.DEFAULTS_ACCOUNT_ID, number) ?: listOf() } // if logged in, load playlists else{ var loadedPlaylists = dao.getLastN(accountService.getAccountId(), number) ?: listOf() val isFirstLoadAfterLogin = accountService.getPublicInfo().isFirstLoadAfterLogin // if this is the first load after login, and there are no playlists if(isFirstLoadAfterLogin && loadedPlaylists.isEmpty()){ // set defaults to user restoreDefaultPlaylists() loadedPlaylists = dao.getLastN(accountService.getAccountId(), number) ?: listOf() } if(isFirstLoadAfterLogin){ // first load after login has finished accountService.firstLoadFinishedAfterLogin() } loadedPlaylists } val playlists = mutableListOf<Playlist>() for(item in dbPlaylists){ playlists.add(item.toPlaylist()) } return playlists } fun getPlaylistById(id: String) : Playlist{ val dbPlaylists = dao.getById(id, accountService.getAccountId()) ?: listOf() return if(dbPlaylists.isNotEmpty()){ dbPlaylists[0].toPlaylist() } else{ Playlist("") } } fun insertPlaylistById(id: String) : Boolean{ val result = spotifyApiService.getPlaylistById(id) if(result.id == ""){ return false } val playlist = result.toPlaylist() val toInsert = playlist.toDbPlaylist(accountService.getAccountId(), timeService.getTimestampUTC()) dao.insert(toInsert) return true } fun insertPlaylist(playlist: Playlist) : Boolean{ val toInsert = playlist.toDbPlaylist(accountService.getAccountId(), timeService.getTimestampUTC()) dao.insert(toInsert) return true } fun updatePlaylist(playlist: Playlist) : Boolean{ val toUpdate = playlist.toDbPlaylist(accountService.getAccountId(), timeService.getTimestampUTC()) dao.update(toUpdate) return true } fun deletePlaylistById(id: String) : Boolean{ dao.delete(id, accountService.getAccountId()) return true } fun deleteAllPlaylists() : Boolean{ dao.deleteAll(accountService.getAccountId()) return true } fun restoreDefaultPlaylists() : Boolean{ dao.deleteAll(accountService.getAccountId()) val defaults = dao.getAll(AccountService.DEFAULTS_ACCOUNT_ID) ?: listOf() if(accountService.accountState.value == AccountState.LOGGED_IN){ val currentAccountId = accountService.getAccountId() defaults.forEach { it.accountId = currentAccountId } dao.insert(defaults) } return true } fun downloadPlaylistById(id: String) : Playlist{ val apiPlaylist = spotifyApiService.getPlaylistById(id) return apiPlaylist.toPlaylist() } fun searchPlaylistByIdOrName(searchExpression: String, offset: Int = 0) : PlaylistSearchResult{ val rawResults = spotifyApiService.getPlaylistsByIdOrNameOrUserId(searchExpression, offset) return rawResults.toSearchResult(searchExpression) } fun searchGetNextBatch(currentResult: PlaylistSearchResult) : PlaylistSearchResult{ val offset = currentResult.offset + currentResult.limit // the end is already reached if(offset > currentResult.total){ return currentResult } val nextResults = spotifyApiService.getPlaylistsByIdOrNameOrUserId(currentResult.searchExpression, offset).toSearchResult(currentResult.searchExpression) val currentIds = currentResult.items.map { it.id } // remove those that are already in the current list val newItems = nextResults.items.filterNot { currentIds.contains(it.id) } return PlaylistSearchResult( items = currentResult.items + newItems, searchExpression = nextResults.searchExpression, // maxOf needed, as Spotify API retrieves 0s after the 1000th offset limit = maxOf(nextResults.limit, currentResult.limit), offset = maxOf(nextResults.offset, currentResult.offset), total = maxOf(nextResults.total, currentResult.total) ) } }
0
Kotlin
0
0
de3f64b8a07f24ae1984a587e7df79704078df11
6,572
SongQuiz
Apache License 2.0
app/src/main/java/com/yz/books/ui/video/VideoBooksModel.kt
zhangkari
303,389,564
false
{"Java": 1652876, "JavaScript": 556976, "Kotlin": 490955, "HTML": 134175, "CSS": 47226}
package com.yz.books.ui.video import androidx.collection.ArrayMap import com.yz.books.base.viewmodel.ErrorState import com.yz.books.base.viewmodel.LoadedState import com.yz.books.base.viewmodel.LoadingState import com.yz.books.base.viewmodel.State import com.yz.books.common.Constant import com.yz.books.db.DaoHelper import com.yz.books.ext.getApplicationContext import com.yz.books.ext.isNetworkConnected import com.yz.books.ui.base.BaseBooksModel import com.yz.books.ui.video.bean.VideoBookChaptersBean import com.yz.books.ui.video.bean.VideoBooksBean /** * @author lilin * @time on 2019-12-16 22:20 */ class VideoBooksModel: BaseBooksModel(), IVideoBooks { class VideoBooksState(val videoBooksBean: VideoBooksBean?): State() class VideoBookChaptersState(val pageNum: Int, val videoBookChaptersBean: VideoBookChaptersBean?): State() override fun getBooksList(categoryId: Int, pageNum: Int) { if (!Constant.ONLINE_VERSION) { val data = DaoHelper.getVideoBooks(categoryId, pageNum) mBaseState.value = VideoBooksState(data) return } val map = ArrayMap<String, Int>() map["categoryId"] = categoryId map["rows"] = 6 map["page"] = pageNum requestData<VideoBooksBean>().apply { loading { mBaseState.value = LoadingState() } loaded { mBaseState.value = LoadedState() } fail { code, message -> mBaseState.value = ErrorState(message, code) } success { data, _ -> mBaseState.value = VideoBooksState(data) } request { mApiService.getVideoBooksByCategory(map) } } } override fun getBookDetail(bookId: Int) { } override fun getVideoBookChapters(videoId: Int, pageNum: Int) { if (!getApplicationContext().isNetworkConnected()) { val data = DaoHelper.getVideoBookChapters(videoId, pageNum) mBaseState.value = VideoBookChaptersState(pageNum, data) return } val map = ArrayMap<String, Int>() map["videoId"] = videoId map["rows"] = 6 map["page"] = pageNum requestData<VideoBookChaptersBean>().apply { loading { mBaseState.value = LoadingState() } loaded { mBaseState.value = LoadedState() } fail { code, message -> mBaseState.value = ErrorState(message, code) } success { data, _ -> mBaseState.value = VideoBookChaptersState(pageNum, data) } request { mApiService.getVideoBookChapters(map) } } } }
0
Java
2
1
90784936a9ec75e702120941fbfac6f1b40b93d5
2,868
yzlauncher
Apache License 2.0
domain/src/main/kotlin/com/seanshubin/kotlin/tryme/domain/beam/TreeAssembler.kt
SeanShubin
129,466,612
false
null
package com.seanshubin.kotlin.tryme.domain.beam interface TreeAssembler { val name:String fun assemble(assemblerMap: Map<String, TreeAssembler>, tree: Tree<Byte>): Any? }
1
null
1
1
1803f204372d994130167749c22f825c51c6a434
180
kotlin-tryme
The Unlicense
dccomics/src/main/java/com/cubidevs/dccomics/ui/list/SuperHeroesAdapter.kt
Team-111-MisionTic
426,814,942
false
{"Kotlin": 36927}
package com.cubidevs.dccomics.ui.list import android.util.Log import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.ImageView import android.widget.RatingBar import android.widget.TextView import androidx.recyclerview.widget.RecyclerView import com.cubidevs.dccomics.R import com.cubidevs.dccomics.model.SuperheroeItem import com.cubidevs.dccomics.model.TurismoItem import com.squareup.picasso.Picasso class SuperHeroesAdapter( // private val superheroesList: ArrayList<SuperheroeItem>, // private val onItemClicked: (SuperheroeItem) -> Unit private val superheroesList: ArrayList<TurismoItem>, private val onItemClicked: (TurismoItem) -> Unit ) : RecyclerView.Adapter<SuperHeroesAdapter.SuperheroeViewHolder>() { override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): SuperheroeViewHolder { val view = LayoutInflater.from(parent.context).inflate(R.layout.card_view_superheroe_item, parent, false) return SuperheroeViewHolder(view) } override fun onBindViewHolder(holder: SuperheroeViewHolder, position: Int) { // val superheroe = superheroesList[position] val turismo = superheroesList[position] holder.itemView.setOnClickListener { onItemClicked(superheroesList[position]) } // holder.bind(superheroe) holder.bind(turismo) } override fun getItemCount(): Int = superheroesList.size // fun appendItems(newItems: ArrayList<SuperheroeItem>) { fun appendItems(newItems: ArrayList<TurismoItem>) { superheroesList.clear() superheroesList.addAll(newItems) notifyDataSetChanged() } class SuperheroeViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView){ private var nameTextView: TextView = itemView.findViewById(R.id.nombre_textview) private var aliasTextView: TextView = itemView.findViewById(R.id.altura_textview) private var tiempoTextview: TextView = itemView.findViewById(R.id.time_textview) private var calificacionRatingBar: RatingBar = itemView.findViewById(R.id.calificacion_ratingBar ) private var pictureImageView: ImageView = itemView.findViewById(R.id.picture_image_view) // fun bind(superheroe: SuperheroeItem){ fun bind(turismo: TurismoItem){ Log.d("nombre",turismo.name) nameTextView.text = turismo.name aliasTextView.text = turismo.height tiempoTextview.text=turismo.time calificacionRatingBar.rating=turismo.score.toFloat() calificacionRatingBar.refreshDrawableState() Picasso.get().load(turismo.urlPicture).into(pictureImageView) } } }
0
Kotlin
1
1
5966f252450af93ef4499d182a8952f4f9aa9848
2,721
Team-111
MIT License
src/main/kotlin/aoc/year2022/Day08.kt
SackCastellon
573,157,155
false
{"Kotlin": 62581}
package aoc.year2022 import aoc.Puzzle private typealias Tree = Pair<Int, Int> /** * [Day 8 - Advent of Code 2022](https://adventofcode.com/2022/day/8) */ object Day08 : Puzzle<Int, Int> { override fun solvePartOne(input: String): Int { val grid = input.lines().map { it.map(Char::digitToInt) } val hiddenHorizontal = grid .dropLast(1) .withIndex() .asSequence() .drop(1) .flatMap { getHidden(it) { row, col -> row to col } } .toSet() val rows = grid.size val cols = grid.first().size val hiddenVertical = (0 until cols) .asSequence() .drop(1) .map { col -> IndexedValue(col, (0 until rows).map { row -> grid[row][col] }) } .flatMap { getHidden(it) { col, row -> row to col } } .toSet() val hidden = hiddenHorizontal.intersect(hiddenVertical).size return (rows * cols) - hidden } override fun solvePartTwo(input: String): Int { TODO() } private fun getHidden( indexedValue: IndexedValue<Iterable<Int>>, treeBuilder: (Int, Int) -> Tree, ): Set<Tree> { val (index, list) = indexedValue var max = list.first() val ltr = list.withIndex() .asSequence() .drop(1) .filter { (_, n) -> (n <= max).also { if (!it) max = n } } .map { treeBuilder(index, it.index) } .toSet() max = list.last() val rtl = list.withIndex() .reversed() .asSequence() .drop(1) .filter { (_, n) -> (n <= max).also { if (!it) max = n } } .map { treeBuilder(index, it.index) } .toSet() return ltr.intersect(rtl) } }
0
Kotlin
0
0
75b0430f14d62bb99c7251a642db61f3c6874a9e
1,815
advent-of-code
Apache License 2.0
ktfx-layouts/src/test/kotlin/javafx/scene/control/TabPaneTest.kt
hanggrian
102,934,147
false
{"Kotlin": 1146536, "CSS": 1653}
package ktfx.layouts import com.hanggrian.ktfx.test.LayoutsStyledTest import javafx.scene.control.Label import javafx.scene.control.TabPane import kotlin.test.Test import kotlin.test.assertEquals import kotlin.test.assertIs class TabPaneTest : LayoutsStyledTest<KtfxPane, TabPane>() { override fun manager() = KtfxPane() override fun KtfxPane.childCount() = children.size override fun child1() = tabPane {} override fun KtfxPane.child2() = tabPane() override fun child3() = styledTabPane() override fun KtfxPane.child4() = styledTabPane() @Test fun stringInvocation() { tabPane { "World" { content = Label() assertIs<Label>(content) } assertEquals(1, tabs.size) } } }
1
Kotlin
2
19
6e5ec9fedf8359423c31a2ba64cd175bc9864cd2
796
ktfx
Apache License 2.0
src/test/kotlin/uk/gov/justice/digital/hmpps/approvedpremisesapi/factory/TeamFactoryDeliusContext.kt
ministryofjustice
515,276,548
false
{"Kotlin": 8393388, "Shell": 15748, "Dockerfile": 1667, "Mustache": 383}
package uk.gov.justice.digital.hmpps.approvedpremisesapi.factory import uk.gov.justice.digital.hmpps.approvedpremisesapi.model.deliuscontext.Borough import uk.gov.justice.digital.hmpps.approvedpremisesapi.model.deliuscontext.Ldu import uk.gov.justice.digital.hmpps.approvedpremisesapi.model.deliuscontext.Team import uk.gov.justice.digital.hmpps.approvedpremisesapi.util.randomDateBefore import uk.gov.justice.digital.hmpps.approvedpremisesapi.util.randomStringMultiCaseWithNumbers import java.time.LocalDate object TeamFactoryDeliusContext { @Suppress("LongParameterList") fun team( code: String = randomStringMultiCaseWithNumbers(6), name: String = randomStringMultiCaseWithNumbers(10), ldu: Ldu = Ldu(code = randomStringMultiCaseWithNumbers(6), name = randomStringMultiCaseWithNumbers(6)), borough: Borough = Borough( code = randomStringMultiCaseWithNumbers(6), description = randomStringMultiCaseWithNumbers(6), ), startDate: LocalDate = LocalDate.now().randomDateBefore(5), endDate: LocalDate? = null, ) = Team( code = code, name = name, ldu = ldu, borough = borough, startDate = startDate, endDate = endDate, ) }
21
Kotlin
2
5
5b02281acd56772dc5d587f8cd4678929a191ac0
1,193
hmpps-approved-premises-api
MIT License
mui-icons-kotlin/src/jsMain/kotlin/mui/icons/material/KeyboardTabOutlined.kt
karakum-team
387,062,541
false
{"Kotlin": 3079611, "TypeScript": 2249, "HTML": 724, "CSS": 86}
// Automatically generated - do not modify! @file:JsModule("@mui/icons-material/KeyboardTabOutlined") package mui.icons.material @JsName("default") external val KeyboardTabOutlined: SvgIconComponent
0
Kotlin
5
35
60404a8933357df15ecfd8caf6e83258962ca909
202
mui-kotlin
Apache License 2.0
src/main/kotlin/trik/testsys/webclient/service/security/impl/UserValidatorImpl.kt
Pupsen-Vupsen
627,349,038
false
{"Kotlin": 212742, "HTML": 153787, "CSS": 12506, "JavaScript": 3471, "Dockerfile": 953}
package trik.testsys.webclient.service.security.impl import com.beust.klaxon.internal.firstNotNullResult import org.springframework.context.ApplicationContext import org.springframework.stereotype.Service import trik.testsys.core.entity.user.AccessToken import trik.testsys.webclient.entity.user.WebUser import trik.testsys.webclient.service.entity.user.WebUserService import trik.testsys.webclient.service.security.UserValidator @Service class UserValidatorImpl( context: ApplicationContext ) : UserValidator { private val webUserServices = context.getBeansOfType(WebUserService::class.java).values override fun validateExistence(accessToken: AccessToken?): WebUser? { accessToken ?: return null val entity = webUserServices.firstNotNullResult { it.findByAccessToken(accessToken) } return entity } }
6
Kotlin
1
0
6a8958276fa2860e678f7832905c60e99e3bbccf
844
trik-testsys-web-client
Apache License 2.0
AndroidCode/app/src/main/java/com/rootusergroup/roofify/data/myAppDataBase.kt
spocasangre
433,139,517
false
{"Kotlin": 50619, "JavaScript": 27967, "HTML": 176, "CSS": 111}
package com.rootusergroup.roofify.data import android.content.Context import androidx.room.Database import androidx.room.Room import androidx.room.RoomDatabase import com.rootusergroup.roofify.data.daos.PostDAO import com.rootusergroup.roofify.data.daos.UserDAO import com.rootusergroup.roofify.data.entities.Post import com.rootusergroup.roofify.data.entities.User @Database(entities = [User::class, Post::class], version = 4, exportSchema = true ) abstract class myAppDataBase: RoomDatabase() { abstract fun userDao(): UserDAO abstract fun postDao(): PostDAO companion object { @Volatile private var INSTANCE: myAppDataBase? = null fun getDatabase(context: Context): myAppDataBase { return INSTANCE?: synchronized(this){ val instance = Room.databaseBuilder( context, myAppDataBase::class.java, "roofifyDb" ).fallbackToDestructiveMigration().build() INSTANCE = instance instance } } } }
0
Kotlin
0
0
fedb4a58ed46d48187bf5c7f478f5fe7b1a54542
1,076
roofify
The Unlicense
dsl/common/src/main/kotlin/io/mockk/InternalPlatformDsl.kt
m1aw
149,691,444
true
{"Markdown": 7, "Gradle": 20, "YAML": 3, "robots.txt": 1, "INI": 1, "Shell": 2, "Text": 5, "Ignore List": 1, "Batchfile": 1, "XML": 9, "JSON": 1, "JavaScript": 1, "HTML": 3, "SVG": 3, "Java Properties": 2, "Kotlin": 232, "Java": 15, "CMake": 1, "C++": 38, "C": 1, "SCSS": 1}
package io.mockk import kotlin.coroutines.experimental.Continuation expect object InternalPlatformDsl { fun identityHashCode(obj: Any): Int fun <T> runCoroutine(block: suspend () -> T): T fun Any?.toStr(): String fun deepEquals(obj1: Any?, obj2: Any?): Boolean fun unboxChar(value: Any): Any fun Any.toArray(): Array<*> fun classForName(name: String): Any fun dynamicCall( self: Any, methodName: String, args: Array<out Any?>, anyContinuationGen: () -> Continuation<*> ): Any? fun dynamicGet(self: Any, name: String): Any? fun dynamicSet(self: Any, name: String, value: Any?) fun <T> threadLocal(initializer: () -> T): InternalRef<T> } interface InternalRef<T> { val value: T }
0
Kotlin
0
0
5b9937566d9ffa33dfe02c6a44bb9450410d2e35
775
mockk
Apache License 2.0
pixel-core/src/commonMain/kotlin/com.chrynan.pixel/ScreenDimensionUnit.kt
chRyNaN
157,776,400
false
null
package com.chrynan.pixel /** * An interface representing a unit of measure for a Device's screen space, or dimensions. An example of a * [ScreenDimensionUnit] is [Pixels] which represents an amount of pixels on the Device's screen. * * Note that it is possible that multiple [ScreenDimensionUnit]s equal the same value. This could be due to multiple * reasons including what the particular Device and it's platform and operating system support. For instance, for * Javascript in the browser, there may be no notion of density available, so perhaps the same [Number] value in * [Pixels] and [DensityIndependentPixels] is equivalent. * * Note that this interface represents a dimension unit for a device's screen, such as pixels, for a provided amount * represented by the [value] property. This interface (and implementations of it) don't specify exactly how the * dimension unit is represented by the system, other than an abstract notion (pixels). As stated above, this is due to * different platforms handling the values differently (such as physical pixels vs virtual pixels). So a * [ScreenDimensionUnit] on one system (device, OS, platform, etc) might be represented differently than the same * [ScreenDimensionUnit] value on another system. * * @author chRyNaN */ interface ScreenDimensionUnit { /** * The underlying [Float] representing this [ScreenDimensionUnit]. * * @author chRyNaN */ val value: Float /** * The [ScreenDimensionType] of this [ScreenDimensionUnit]. * * @author chRyNaN */ val type: ScreenDimensionType /** * A [Boolean] value indicating whether this [ScreenDimensionUnit] is a constant physical size, meaning that it * represents a static physical size that does not change depending on the pixel density of a Device's screen. * * @author chRyNaN */ val isConstantPhysicalSize: Boolean /** * A [Boolean] value indicating whether this [ScreenDimensionUnit] is a density independent size, meaning that the * Device's pixel density doesn't directly change it's size. Note that this does not mean that it is a constant * physical size indicated by the [isConstantPhysicalSize] property. * * @author chRyNaN */ val isDensityIndependent: Boolean }
0
Kotlin
0
3
7a4c17f5ce58438280c818911f82584020b432ca
2,318
pixel
Apache License 2.0
app/src/main/java/com/example/r2devprosproject/ApplicationController.kt
chdsz123
491,357,055
false
null
package com.example.r2devprosproject import android.app.Application import timber.log.Timber import timber.log.Timber.DebugTree class ApplicationController : Application() { override fun onCreate() { super.onCreate() if (BuildConfig.DEBUG) { Timber.plant(DebugTree()) } } }
0
Kotlin
0
0
f3d153819fc1d3b7bc5da92ab74824cfa9403ca0
320
AndroidProjects
Blue Oak Model License 1.0.0
dexfile/src/main/kotlin/com/github/netomi/bat/dexfile/value/EncodedValue.kt
netomi
265,488,804
false
null
/* * Copyright (c) 2020 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 com.github.netomi.bat.dexfile.value import com.github.netomi.bat.dexfile.* import com.github.netomi.bat.dexfile.io.DexDataInput import com.github.netomi.bat.dexfile.io.DexDataOutput import com.github.netomi.bat.dexfile.io.DexFormatException import com.github.netomi.bat.dexfile.value.visitor.EncodedValueVisitor import com.github.netomi.bat.dexfile.visitor.ReferencedIDVisitor import com.github.netomi.bat.util.toHexStringWithPrefix /** * An abstract base class representing an encoded value inside a dex file. * * @see <a href="https://source.android.com/devices/tech/dalvik/dex-format#encoding">value encoding @ dex format</a> */ abstract class EncodedValue { abstract val valueType: EncodedValueType internal abstract fun readValue(input: DexDataInput, valueArg: Int) protected fun writeType(output: DexDataOutput, valueArg: Int): Int { val typeAndArg = valueArg shl 5 or valueType.value output.writeUnsignedByte(typeAndArg.toShort()) return valueArg } protected abstract fun writeType(output: DexDataOutput): Int internal fun write(output: DexDataOutput) { val valueArg = writeType(output) writeValue(output, valueArg) } internal abstract fun writeValue(output: DexDataOutput, valueArg: Int) abstract fun accept(dexFile: DexFile, visitor: EncodedValueVisitor) internal abstract fun referencedIDsAccept(dexFile: DexFile, visitor: ReferencedIDVisitor) abstract override fun hashCode(): Int abstract override fun equals(other: Any?): Boolean companion object { fun read(input: DexDataInput): EncodedValue { val typeAndArg = input.readUnsignedByte() val valueArg = typeAndArg ushr 5 val valueType = typeAndArg and 0x1f val encodedValue = create(valueType) encodedValue.readValue(input, valueArg) return encodedValue } private fun create(valueType: Int): EncodedValue { return EncodedValueType.of(valueType)?.supplier?.invoke() ?: throw DexFormatException("unexpected encoded value type: ${toHexStringWithPrefix(valueType.toByte())}") } fun readAnnotationValue(input: DexDataInput): EncodedAnnotationValue { val annotation = EncodedAnnotationValue.empty() annotation.readValue(input, 0) return annotation } fun requiredBytesForSignedInt(value: Int): Int { return when (value) { value shl 24 shr 24 -> 1 value shl 16 shr 16 -> 2 value shl 8 shr 8 -> 3 else -> 4 } } fun requiredBytesForSignedLong(value: Long): Int { return when (value) { value shl 56 shr 56 -> 1 value shl 48 shr 48 -> 2 value shl 40 shr 40 -> 3 value shl 32 shr 32 -> 4 value shl 24 shr 24 -> 5 value shl 16 shr 16 -> 6 value shl 8 shr 8 -> 7 else -> 8 } } fun requiredBytesForSignedShort(value: Short): Int { val v = value.toInt() return if (v shl 24 shr 24 == v) 1 else 2 } fun requiredBytesForUnsignedChar(value: Char): Int { return if (value.code shl 24 ushr 24 == value.code) 1 else 2 } fun requiredBytesForUnsignedInt(value: Int): Int { return when (value) { value shl 24 ushr 24 -> 1 value shl 16 ushr 16 -> 2 value shl 8 ushr 8 -> 3 else -> 4 } } fun requiredBytesForFloat(value: Float): Int { val bits = java.lang.Float.floatToIntBits(value) return if (bits shl 8 == 0) 1 else if (bits shl 16 == 0) 2 else if (bits shl 24 == 0) 3 else 4 } fun requiredBytesForDouble(value: Double): Int { val bits = java.lang.Double.doubleToLongBits(value) return if (bits shl 8 == 0L) 1 else if (bits shl 16 == 0L) 2 else if (bits shl 24 == 0L) 3 else if (bits shl 32 == 0L) 4 else if (bits shl 40 == 0L) 5 else if (bits shl 48 == 0L) 6 else if (bits shl 56 == 0L) 7 else 8 } } } enum class EncodedValueType constructor(val value: Int, val supplier: () -> EncodedValue) { BYTE (VALUE_BYTE, { EncodedByteValue.empty() }), SHORT (VALUE_SHORT, { EncodedShortValue.empty() }), CHAR (VALUE_CHAR, { EncodedCharValue.empty() }), INT (VALUE_INT, { EncodedIntValue.empty() }), LONG (VALUE_LONG, { EncodedLongValue.empty() }), FLOAT (VALUE_FLOAT, { EncodedFloatValue.empty() }), DOUBLE (VALUE_DOUBLE, { EncodedDoubleValue.empty() }), METHOD_TYPE (VALUE_METHOD_TYPE, { EncodedMethodTypeValue.empty() }), METHOD_HANDLE (VALUE_METHOD_HANDLE, { EncodedMethodHandleValue.empty() }), STRING (VALUE_STRING, { EncodedStringValue.empty() }), TYPE (VALUE_TYPE, { EncodedTypeValue.empty() }), FIELD (VALUE_FIELD, { EncodedFieldValue.empty() }), METHOD (VALUE_METHOD, { EncodedMethodValue.empty() }), ENUM (VALUE_ENUM, { EncodedEnumValue.empty() }), ARRAY (VALUE_ARRAY, { EncodedArrayValue.empty() }), ANNOTATION (VALUE_ANNOTATION, { EncodedAnnotationValue.empty() }), NULL (VALUE_NULL, { EncodedNullValue }), BOOLEAN (VALUE_BOOLEAN, { EncodedBooleanValue.empty() }); companion object { private val valueToTypeMap: Map<Int, EncodedValueType> by lazy { values().associateBy { it.value } } fun of(valueType: Int) : EncodedValueType? { return valueToTypeMap[valueType] } } }
1
null
3
10
5f5ec931c47dd34f14bd97230a29413ef1cf219c
6,859
bat
Apache License 2.0
app/src/main/java/com/emrekose/videogames/common/Mapper.kt
emrekose26
329,276,392
false
null
package com.emrekose.videogames.common interface Mapper<F, T> { fun mapFrom(from: F): T }
0
Kotlin
0
2
9ff281a07df645bf8477f91f6350fed8bc6e8bb9
94
video-games-app
Apache License 2.0
rd-kt/rd-gen/src/test/kotlin/testModels/testSubpackage/FooRoot.kt
JetBrains
107,686,809
false
{"C#": 1845849, "Kotlin": 1606295, "C++": 1087156, "CMake": 45400, "Batchfile": 8969, "C": 688, "Shell": 672, "Dockerfile": 152}
package testModels.testSubpackage import com.jetbrains.rd.generator.nova.FlowTransform import com.jetbrains.rd.generator.nova.Root import com.jetbrains.rd.generator.nova.kotlin.Kotlin11Generator import com.jetbrains.rd.generator.test.cases.generator.ModelPackageSearchTests import java.io.File object FooRoot : Root( Kotlin11Generator(FlowTransform.AsIs, "testModels.foo", File(ModelPackageSearchTests.kotlinTempOutputDir)) )
36
C#
53
384
e25603699e1751abfe1beeeec77c89db9d3fda80
432
rd
Apache License 2.0
app/src/main/java/dev/oumiya/app/demo/sensor/component/ItemList.kt
ykws
707,805,490
false
{"Kotlin": 10944}
package dev.oumiya.app.demo.sensor.component import android.hardware.Sensor import android.hardware.SensorEvent import android.hardware.SensorEventListener import android.hardware.SensorManager import androidx.compose.animation.core.LinearEasing import androidx.compose.animation.core.tween import androidx.compose.foundation.gestures.animateScrollBy import androidx.compose.foundation.gestures.detectTapGestures import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.size import androidx.compose.foundation.rememberScrollState import androidx.compose.foundation.verticalScroll import androidx.compose.material3.Text import androidx.compose.runtime.Composable import androidx.compose.runtime.DisposableEffect import androidx.compose.runtime.LaunchedEffect import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.runtime.setValue import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.input.pointer.pointerInput import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.platform.LocalDensity import androidx.compose.ui.tooling.preview.Preview import androidx.compose.ui.unit.dp import dev.oumiya.app.demo.sensor.ui.theme.SensorScrollDemoTheme @Composable fun ItemList() { val context = LocalContext.current val sensorManager = context.getSystemService(SensorManager::class.java) ScrollableContent(sensorManager = sensorManager) } @Composable private fun ScrollableContent( sensorManager: SensorManager? = null, ) { var scrollState = rememberScrollState() var scrollOffset by remember { mutableStateOf(0f) } var baseY: Float? by remember { mutableStateOf(null) } var isButtonPressing by remember { mutableStateOf(false) } val density = LocalDensity.current.density DisposableEffect(sensorManager) { if (sensorManager == null) return@DisposableEffect onDispose {} val listener = object : SensorEventListener { override fun onAccuracyChanged(sensor: Sensor?, sccuracy: Int) {} override fun onSensorChanged(event: SensorEvent) { if (isButtonPressing) { if (baseY == null) baseY = event.values[1] val y = event.values[1] val delta = y - (baseY ?: 0f) scrollOffset = delta * 100 * density } } } val accelerometer = sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER) sensorManager.registerListener(listener, accelerometer, SensorManager.SENSOR_DELAY_GAME) onDispose { sensorManager.unregisterListener(listener) } } LaunchedEffect(scrollOffset) { if (isButtonPressing) { scrollState.animateScrollBy( value = scrollOffset, animationSpec = tween(durationMillis = 200, easing = LinearEasing), ) } } Box { Column( modifier = Modifier .fillMaxSize() .verticalScroll(scrollState), ) { repeat(100) { Text(text = "Item $it", modifier = Modifier.padding(16.dp)) } } SensorButton( modifier = Modifier .size(72.dp) .align(Alignment.BottomStart) .padding(start = 8.dp, bottom = 8.dp) .pointerInput(Unit) { detectTapGestures( onPress = { isButtonPressing = true tryAwaitRelease() baseY = null isButtonPressing = false }, ) }, ) } } @Preview(showBackground = true) @Composable fun ScrollableContentPreview() { SensorScrollDemoTheme { ScrollableContent() } }
1
Kotlin
0
0
30ae3a5c3fcae0aede25e3d7178fd83727240111
4,180
motion-scroll-android
MIT License
vk-api/src/main/kotlin/name/alatushkin/api/vk/generated/video/methods/VideoReportCommentMethod.kt
alatushkin
156,866,851
false
null
package name.alatushkin.api.vk.generated.video.methods import com.fasterxml.jackson.core.type.TypeReference import name.alatushkin.api.vk.VkMethod import name.alatushkin.api.vk.api.VkSuccess import name.alatushkin.api.vk.generated.common.Reason /** * Reports (submits a complaint about) a comment on a video. * * [https://vk.com/dev/video.reportComment] * @property [owner_id] ID of the user or community that owns the video. * @property [comment_id] ID of the comment being reported. * @property [reason] Reason for the complaint: , 0 – spam , 1 – child pornography , 2 – extremism , 3 – violence , 4 – drug propaganda , 5 – adult material , 6 – insult, abuse */ class VideoReportCommentMethod() : VkMethod<Boolean>( "video.reportComment", HashMap() ) { var ownerId: Long? by props var commentId: Long? by props var reason: Reason? by props constructor( ownerId: Long? = null, commentId: Long? = null, reason: Reason? = null ) : this() { this.ownerId = ownerId this.commentId = commentId this.reason = reason } fun setOwnerId(ownerId: Long): VideoReportCommentMethod { this.ownerId = ownerId return this } fun setCommentId(commentId: Long): VideoReportCommentMethod { this.commentId = commentId return this } fun setReason(reason: Reason): VideoReportCommentMethod { this.reason = reason return this } override val classRef = VideoReportCommentMethod.classRef companion object { val classRef = object : TypeReference<VkSuccess<Boolean>>() {} } }
2
Kotlin
3
10
123bd61b24be70f9bbf044328b98a3901523cb1b
1,640
kotlin-vk-api
MIT License
src/main/kotlin/no/nav/klage/service/KlageService.kt
navikt
253,461,869
false
{"Kotlin": 271504, "Dockerfile": 133}
package no.nav.klage.service import no.nav.klage.clients.FileClient import no.nav.klage.common.KlageAnkeMetrics import no.nav.klage.common.VedleggMetrics import no.nav.klage.controller.view.OpenKlageInput import no.nav.klage.domain.Bruker import no.nav.klage.domain.KlageAnkeStatus import no.nav.klage.domain.LanguageEnum import no.nav.klage.domain.Tema import no.nav.klage.domain.jpa.Klage import no.nav.klage.domain.jpa.isFinalized import no.nav.klage.domain.klage.AggregatedKlageAnke import no.nav.klage.domain.klage.CheckboxEnum import no.nav.klage.domain.klage.KlageFullInput import no.nav.klage.domain.klage.KlageInput import no.nav.klage.domain.titles.Innsendingsytelse import no.nav.klage.kafka.AivenKafkaProducer import no.nav.klage.repository.KlageRepository import no.nav.klage.repository.KlankeRepository import no.nav.klage.util.getLogger import no.nav.klage.util.klageAnkeIsLonnskompensasjon import no.nav.klage.util.sanitizeText import no.nav.klage.util.vedtakFromDate import org.springframework.stereotype.Service import org.springframework.transaction.annotation.Transactional import java.time.LocalDateTime import java.util.* @Service @Transactional class KlageService( private val klageRepository: KlageRepository, private val klageAnkeMetrics: KlageAnkeMetrics, private val vedleggMetrics: VedleggMetrics, private val kafkaProducer: AivenKafkaProducer, private val fileClient: FileClient, private val klageDittnavPdfgenService: KlageDittnavPdfgenService, private val klankeRepository: KlankeRepository, private val validationService: ValidationService, private val commonService: CommonService, ) { companion object { private const val LOENNSKOMPENSASJON_GRAFANA_TEMA = "LOK" @Suppress("JAVA_CLASS_ON_COMPANION") private val logger = getLogger(javaClass.enclosingClass) } fun createKlage(input: KlageFullInput, bruker: Bruker): Klage { val klage = input.toKlage(bruker = bruker) return klageRepository.save(klage).also { updateMetrics(input = klage) } } fun createKlage(input: KlageInput, bruker: Bruker): Klage { val klage = input.toKlage(bruker = bruker) return klageRepository.save(klage).also { updateMetrics(input = klage) } } fun KlageFullInput.toKlage(bruker: Bruker): Klage { return Klage( checkboxesSelected = checkboxesSelected.toMutableList(), foedselsnummer = bruker.folkeregisteridentifikator.identifikasjonsnummer, fritekst = fritekst, status = KlageAnkeStatus.DRAFT, tema = innsendingsytelse.toTema(), userSaksnummer = userSaksnummer, journalpostId = null, vedtakDate = vedtakDate, internalSaksnummer = internalSaksnummer, language = language, innsendingsytelse = innsendingsytelse, hasVedlegg = hasVedlegg, created = LocalDateTime.now(), modifiedByUser = LocalDateTime.now(), pdfDownloaded = null, ) } fun KlageInput.toKlage(bruker: Bruker): Klage { return Klage( checkboxesSelected = mutableListOf(), foedselsnummer = bruker.folkeregisteridentifikator.identifikasjonsnummer, fritekst = null, status = KlageAnkeStatus.DRAFT, tema = innsendingsytelse.toTema(), userSaksnummer = null, journalpostId = null, vedtakDate = null, internalSaksnummer = internalSaksnummer, language = LanguageEnum.NB, innsendingsytelse = innsendingsytelse, hasVedlegg = false, created = LocalDateTime.now(), modifiedByUser = LocalDateTime.now(), pdfDownloaded = null, ) } private fun updateMetrics(input: Klage) { val temaReport = if (klageAnkeIsLonnskompensasjon(innsendingsytelse = input.innsendingsytelse)) { LOENNSKOMPENSASJON_GRAFANA_TEMA } else { input.innsendingsytelse.toTema().toString() } klageAnkeMetrics.incrementKlagerInitialized(temaReport) } fun getDraftOrCreateKlage(input: KlageInput, bruker: Bruker): Klage { val existingKlage = getLatestKlageDraft( bruker = bruker, tema = input.innsendingsytelse.toTema(), internalSaksnummer = input.internalSaksnummer, innsendingsytelse = input.innsendingsytelse, ) return existingKlage ?: createKlage( input = input, bruker = bruker, ) } fun getLatestKlageDraft( bruker: Bruker, tema: Tema, internalSaksnummer: String?, innsendingsytelse: Innsendingsytelse, ): Klage? { val fnr = bruker.folkeregisteridentifikator.identifikasjonsnummer val klage = klageRepository.findByFoedselsnummerAndStatus(fnr = fnr, status = KlageAnkeStatus.DRAFT) .filter { if (internalSaksnummer != null) { it.tema == tema && it.innsendingsytelse == innsendingsytelse && it.internalSaksnummer == internalSaksnummer } else { it.tema == tema && it.innsendingsytelse == innsendingsytelse } }.maxByOrNull { it.modifiedByUser } return if (klage != null) { validationService.validateKlageAccess(klage = klage, bruker = bruker) klage } else null } fun updateCheckboxesSelected( klageId: UUID, checkboxesSelected: Set<CheckboxEnum>?, bruker: Bruker ): LocalDateTime { val existingKlage = klageRepository.findById(klageId).get() validationService.checkKlankeStatus(existingKlage) validationService.validateKlankeAccess(existingKlage, bruker) existingKlage.checkboxesSelected.clear() if (!checkboxesSelected.isNullOrEmpty()) { existingKlage.checkboxesSelected.addAll(checkboxesSelected) } existingKlage.modifiedByUser = LocalDateTime.now() return existingKlage.modifiedByUser } fun finalizeKlage(klageId: UUID, bruker: Bruker): LocalDateTime { val existingKlage = klankeRepository.findById(klageId).get() as Klage validationService.checkKlankeStatus(klanke = existingKlage, includeFinalized = false) if (existingKlage.isFinalized()) { return existingKlage.modifiedByUser } validationService.validateKlankeAccess(klanke = existingKlage, bruker = bruker) validationService.validateKlage(klage = existingKlage) existingKlage.status = KlageAnkeStatus.DONE existingKlage.modifiedByUser = LocalDateTime.now() kafkaProducer.sendToKafka(createAggregatedKlage(bruker = bruker, klage = existingKlage)) registerFinalizedMetrics(klage = existingKlage) logger.debug( "Klage {} med tema {} er sendt inn.", klageId, existingKlage.tema.name, ) return existingKlage.modifiedByUser } private fun registerFinalizedMetrics(klage: Klage) { val temaReport = if (klageAnkeIsLonnskompensasjon(klage.innsendingsytelse)) { LOENNSKOMPENSASJON_GRAFANA_TEMA } else { klage.tema.toString() } klageAnkeMetrics.incrementKlagerFinalizedTitle(klage.innsendingsytelse) klageAnkeMetrics.incrementKlagerFinalized(temaReport) klageAnkeMetrics.incrementKlagerGrunn(temaReport, klage.checkboxesSelected) if (klage.userSaksnummer != null) { klageAnkeMetrics.incrementOptionalSaksnummer(temaReport) } if (klage.vedtakDate != null) { klageAnkeMetrics.incrementOptionalVedtaksdato(temaReport) } vedleggMetrics.registerNumberOfVedleggPerUser(klage.vedlegg.size.toDouble()) } fun getKlagePdf(klageId: UUID, bruker: Bruker): ByteArray { val existingKlage = klageRepository.findById(klageId).get() validationService.checkKlankeStatus(klanke = existingKlage, includeFinalized = false) validationService.validateKlankeAccess(klanke = existingKlage, bruker = bruker) requireNotNull(existingKlage.journalpostId) return fileClient.getKlageAnkeFile(existingKlage.journalpostId!!) } fun createKlagePdfWithFoersteside(klageId: UUID, bruker: Bruker): ByteArray? { val existingKlage = klageRepository.findById(klageId).get() validationService.checkKlankeStatus(klanke = existingKlage, includeFinalized = false) validationService.validateKlankeAccess(klanke = existingKlage, bruker = bruker) validationService.validateKlage(klage = existingKlage) klageDittnavPdfgenService.createKlagePdfWithFoersteside( createPdfWithFoerstesideInput(klage = existingKlage, bruker) ).also { commonService.setPdfDownloadedWithoutAccessValidation(klankeId = klageId, pdfDownloaded = LocalDateTime.now()) return it } } private fun createAggregatedKlage( bruker: Bruker, klage: Klage ): AggregatedKlageAnke { val vedtak = vedtakFromDate(klage.vedtakDate) return AggregatedKlageAnke( id = klage.id.toString(), fornavn = bruker.navn.fornavn, mellomnavn = bruker.navn.mellomnavn ?: "", etternavn = bruker.navn.etternavn, vedtak = vedtak ?: "", dato = klage.modifiedByUser.toLocalDate(), begrunnelse = sanitizeText(klage.fritekst!!), identifikasjonsnummer = bruker.folkeregisteridentifikator.identifikasjonsnummer, tema = klage.tema.name, ytelse = klage.innsendingsytelse.nb, vedlegg = klage.vedlegg.map { AggregatedKlageAnke.Vedlegg(tittel = it.tittel, ref = it.ref) }, userChoices = klage.checkboxesSelected.map { x -> x.getFullText(klage.language) }, userSaksnummer = klage.userSaksnummer, internalSaksnummer = klage.internalSaksnummer, klageAnkeType = AggregatedKlageAnke.KlageAnkeType.KLAGE, enhetsnummer = null, ) } fun createPdfWithFoerstesideInput(klage: Klage, bruker: Bruker): OpenKlageInput { return OpenKlageInput( foedselsnummer = klage.foedselsnummer, navn = bruker.navn, fritekst = klage.fritekst!!, userSaksnummer = klage.userSaksnummer, internalSaksnummer = klage.internalSaksnummer, vedtakDate = klage.vedtakDate, innsendingsytelse = klage.innsendingsytelse, checkboxesSelected = klage.checkboxesSelected.toSet(), language = klage.language, hasVedlegg = klage.vedlegg.isNotEmpty() || klage.hasVedlegg, ) } fun getKlageDraftsByFnr(bruker: Bruker): List<Klage> { return klageRepository.findByFoedselsnummerAndStatus( fnr = bruker.folkeregisteridentifikator.identifikasjonsnummer, status = KlageAnkeStatus.DRAFT ) } }
1
Kotlin
1
0
88ee93d101b6028bf558e671a5ea2d25e4685540
11,164
klage-dittnav-api
MIT License
idea/testData/intentions/convertReferenceToLambda/itClash.kt
JakeWharton
99,388,807
false
null
// IS_APPLICABLE: true // WITH_RUNTIME fun foo() { listOf(1).forEach { (-it).let(<caret>it::bar) } } fun Int.bar(arg: Int) { }
0
null
28
83
4383335168338df9bbbe2a63cb213a68d0858104
132
kotlin
Apache License 2.0
domain/src/main/java/com/eyther/lumbridge/domain/repository/mortgage/portugal/PortugalMortgageCalculator.kt
ruialmeida51
249,223,684
false
{"Kotlin": 687400}
package com.eyther.lumbridge.domain.repository.mortgage.portugal import com.eyther.lumbridge.domain.model.finance.mortgage.MortgageAmortization import com.eyther.lumbridge.domain.model.finance.mortgage.MortgageCalculation import com.eyther.lumbridge.domain.model.user.UserMortgageDomain import com.eyther.lumbridge.domain.repository.mortgage.MortgageCalculator import com.eyther.lumbridge.domain.time.MONTHS_IN_YEAR import javax.inject.Inject import kotlin.math.pow class PortugalMortgageCalculator @Inject constructor() : MortgageCalculator { companion object { private const val PERCENTAGE = 100.0f private const val DEFAULT_AMORTIZATION = 10000.0f } override fun calculate(mortgageDomain: UserMortgageDomain): MortgageCalculation { val nextPayment = calculateNextPayment( interestRate = requireNotNull(mortgageDomain.interestRate), loanAmount = mortgageDomain.loanAmount, remainingMonths = mortgageDomain.monthsRemaining ) val (nextPaymentCapital, nextPaymentInterest) = calculateMonthlyPaymentCapitalAndInterestPortions( totalMonthlyPayment = nextPayment, remainingLoanAmount = mortgageDomain.loanAmount.toDouble(), interestRate = requireNotNull(mortgageDomain.interestRate) ) val amortizations = calculateAmortization( interestRate = requireNotNull(mortgageDomain.interestRate), loanAmount = mortgageDomain.loanAmount, remainingMonths = mortgageDomain.monthsRemaining ) return MortgageCalculation( loanAmount = mortgageDomain.loanAmount, monthlyPayment = nextPayment.toFloat(), monthlyPaymentCapital = nextPaymentCapital.toFloat(), monthsLeft = mortgageDomain.monthsRemaining, euribor = mortgageDomain.euribor, spread = mortgageDomain.spread, fixedInterestRate = mortgageDomain.fixedInterestRate, mortgageType = mortgageDomain.mortgageType, monthlyPaymentInterest = nextPaymentInterest.toFloat(), amortizations = amortizations ) } /** * Given a fixed interest rate, loan amount, and remaining months, calculates the next payment. * The formula used is the following: * P = r * L / (1 - (1 + r)^-n) * where: * P = monthly payment * r = monthly interest rate * L = loan amount * n = remaining months * The formula is derived from the PMT function in Excel. * * Remember that the interest rate is given in annual percentage (e.g., 3.92%). * To convert it to a decimal, we divide by 100 (3.92 / 100 = 0.0392). * Then, to obtain the monthly interest rate, we divide by 12 (0.0392 / 12). * * @param interestRate The interest rate as a percentage. * @param loanAmount The loan amount. * @param remainingMonths The remaining months. * @return The next payment. */ private fun calculateNextPayment( interestRate: Float, loanAmount: Float, remainingMonths: Int ): Double { val monthlyInterestRate = calculateMonthlyInterestRate( annualInterestRate = interestRate ) val denominator = calculateDenominator( remainingMonths = remainingMonths, monthlyInterestRate = monthlyInterestRate ) return monthlyInterestRate * loanAmount.toDouble() / denominator } /** * Calculates the denominator of the formula used to calculate the next payment. * The denominator is the following: * 1 - (1 + r)^-n * @see calculateNextPayment */ private fun calculateDenominator(remainingMonths: Int, monthlyInterestRate: Float): Float { return 1 - (1 + monthlyInterestRate).pow(-remainingMonths) } /** * Calculates the monthly interest rate. * * The interest rate is given in annual percentage (e.g., 3.92%). * To convert it to a decimal, we divide by 100 (3.92 / 100 = 0.0392). * Then, to obtain the monthly interest rate, we divide by 12 (0.0392 / 12). * * @param annualInterestRate The annual interest rate as a percentage. * @return The monthly interest rate as a decimal. */ private fun calculateMonthlyInterestRate(annualInterestRate: Float): Float { return annualInterestRate / PERCENTAGE / MONTHS_IN_YEAR } /** * Calculates the interest payment and capital payment for a given total monthly payment. * * The formula used for interest payment is the following: * I = P - C * where: * I = interest payment * P = total monthly payment * C = capital payment * * The formula used for capital payment is the following: * C = P - I * where: * C = capital payment * P = total monthly payment * I = interest payment * * @param totalMonthlyPayment The total monthly payment. * @param remainingLoanAmount The remaining loan amount. * @param interestRate The interest rate as a percentage. */ private fun calculateMonthlyPaymentCapitalAndInterestPortions( totalMonthlyPayment: Double, remainingLoanAmount: Double, interestRate: Float ): Pair<Double, Double> { val monthlyInterestRate = calculateMonthlyInterestRate(interestRate) val interestPayment = remainingLoanAmount * monthlyInterestRate val capitalPayment = totalMonthlyPayment - interestPayment return capitalPayment to interestPayment } /** * Calculates the amortizations for a given mortgage. * The amortizations are calculated based on the mortgage type. * @param interestRate The interest rate as a percentage. * @param loanAmount The loan amount. * @param remainingMonths The remaining months. * @return The amortizations. */ private fun calculateAmortization( interestRate: Float, loanAmount: Float, remainingMonths: Int ): List<MortgageAmortization> { val amortizations = mutableListOf<MortgageAmortization>() var startingAmount = loanAmount var iterations = 0 while (startingAmount >= DEFAULT_AMORTIZATION) { startingAmount -= DEFAULT_AMORTIZATION iterations += 1 val nextPayment = calculateNextPayment( interestRate = interestRate, loanAmount = startingAmount, remainingMonths = remainingMonths ) amortizations.add( MortgageAmortization( amortization = DEFAULT_AMORTIZATION * iterations, remainder = startingAmount, nextPayment = nextPayment.toFloat() ) ) } return amortizations } }
8
Kotlin
0
7
8e35f83c34e4b29eae1b048d3fda6aaa81b04858
6,885
lumbridge-android
MIT License
src/main/kotlin/uk/gov/justice/digital/hmpps/hmppsactivitiesmanagementapi/entity/PlannedDeallocation.kt
ministryofjustice
533,838,017
false
null
package uk.gov.justice.digital.hmpps.hmppsactivitiesmanagementapi.entity import jakarta.persistence.Entity import jakarta.persistence.EnumType import jakarta.persistence.Enumerated import jakarta.persistence.GeneratedValue import jakarta.persistence.GenerationType import jakarta.persistence.Id import jakarta.persistence.JoinColumn import jakarta.persistence.OneToOne import jakarta.persistence.Table import java.time.LocalDate import java.time.LocalDateTime @Entity @Table(name = "planned_deallocation") data class PlannedDeallocation( @Id @GeneratedValue(strategy = GenerationType.IDENTITY) val plannedDeallocationId: Long = 0, @OneToOne @JoinColumn(name = "allocation_id", nullable = false) var allocation: Allocation, var plannedDate: LocalDate, var plannedBy: String, @Enumerated(EnumType.STRING) var plannedReason: DeallocationReason, var plannedAt: LocalDateTime = LocalDateTime.now(), )
4
Kotlin
0
1
f69836150816287774d41f9ed3feb1019f9268fd
925
hmpps-activities-management-api
MIT License
Search Algorithms/Kotlin/InterpolationSearch.kt
memr5
151,755,233
false
null
fun interpolationSearch(arr: IntArray, item: Int): Int { var hi = arr.size - 1 var lo = 0 while (item >= arr[lo] && item <= arr[hi] && lo <= hi) { val probe = lo + (hi - lo) * (item - arr[lo]) / (arr[hi] - arr[lo]) if (hi == lo) { return if (arr[lo] == item) { lo } else { -1 } } if (arr[probe] == item) { return probe } if (arr[probe] < item) { lo = probe + 1 } else { hi = probe - 1 } } return -1 } fun main(args: Array<String>) { var arr = intArrayOf( 2, 3, 5, 6, 8, 11, 15, 19, 21, 24, 28, 31, 44, 55, 76 ) val x = 31 val xIndex = interpolationSearch(arr, x) if (xIndex != -1) println("Item $x found at index $xIndex") else println("Element $x not found.") val y = 1 val yIndex = interpolationSearch(arr, y) if (yIndex != -1) println("Item $x found at index $yIndex") else println("Element $x not found.") }
106
null
174
25
e6ef9d7b6f412452249722515fd5cff9c0d7dbab
1,065
Algorithms
MIT License
app/src/main/java/com/hooni/quotesaver/data/model/Quote.kt
hunnihundert
317,061,510
false
null
package com.hooni.quotesaver.data.model import androidx.room.Entity import androidx.room.PrimaryKey @Entity data class Quote( val quote: String, val author: String?, var likes: Int, val tags: List<String>, @PrimaryKey val pk: Int, val image: String?, val language: String ) { override fun equals(other: Any?): Boolean { if (other == null || other !is Quote) return false return pk == other.pk } override fun hashCode(): Int { return pk + quote.hashCode() + author.hashCode() } override fun toString(): String { return "$quote, $author" } }
5
Kotlin
0
5
e5cf2e767dc7ab1c1d88ba66307f994e0f37d314
627
QuoteSaver
Apache License 2.0
src/main/kotlin/ee/nx01/tonclient/utils/UtilsModule.kt
mdorofeev
305,637,520
false
null
package ee.nx01.tonclient.utils import ee.nx01.tonclient.TonClient class UtilsModule(private val tonClient: TonClient) { /** ## convert_address Converts address from any TON format to any TON format */ suspend fun convertAddress( address: String, outputFormat: AddressStringFormat ): String { return tonClient.request<Map<String, String>>( "utils.convert_address", mapOf("address" to address, "output_format" to outputFormat) )["address"] ?: throw RuntimeException() } /** * #calc_storage_fee * Calculates storage fee for an account over a specified time period * @param period Time period in seconds * @return Storage fee over a period of time in nanotokens */ suspend fun calcStorageFee( address: String, period: Int ): Long { val feeString = tonClient.request<Map<String, String>>( "utils.calc_storage_fee", ParamsOfCalcStorageFee(address, period) )["fee"] ?: throw RuntimeException() return feeString.toLong() } /** * #compress_zstd * Compresses data using Zstandard algorithm * @param uncompressed Uncompressed data.Must be encoded as base64. * @param level Compression level, from 1 to 21. Where: 1 - lowest compression level (fastest compression); 21 - highest compression level (slowest compression). If level is omitted, the default compression level is used (currently 3). * @return Compressed data. Must be encoded as base64. */ suspend fun compressZstd(uncompressed: String, level: Int? = null): String { val compressed = tonClient.request<Map<String, String>>( "utils.compress_zstd", ParamsOfCompressZstd(uncompressed, level) )["compressed"] ?: error("Can't parse response") return compressed } /** * #decompress_zstd * Decompresses data using Zstandard algorithm * @param compressed: string – Compressed data. Must be encoded as base64. * @return Decompressed data. Must be encoded as base64. */ suspend fun decompressZstd(compressed: String): String { val decompressed = tonClient.request<Map<String, String>>( "utils.decompress_zstd", ParamsOfDecompressZstd(compressed) )["decompressed"] ?: error("Can't parse response") return decompressed } /** * Validates and returns the type of any TON address. Address types are the following 0:919db8e740d50bf349df2eea03fa30c385d846b991ff5542e67098ee833fc7f7 - standart TON address most commonly used in all cases. Also called as hex addres 919db8e740d50bf349df2eea03fa30c385d846b991ff5542e67098ee833fc7f7 - account ID. A part of full address. Identifies account inside particular workchain EQCRnbjnQNUL80nfLuoD+jDDhdhGuZH/VULmcJjugz/H9wam - base64 address. Also called "user-friendly". Was used at the beginning of TON. Now it is supported for compatibility */ suspend fun getAddressType(param: ParamsOfGetAddressType): ResultOfGetAddressType { return tonClient.request("utils.get_address_type", param) } } data class ParamsOfGetAddressType( val address: String ) data class ResultOfGetAddressType( val addressType: AccountAddressType ) enum class AccountAddressType { AccountId, Hex, Base64 } data class ParamsOfDecompressZstd( val compressed: String ) data class ParamsOfCompressZstd( val uncompressed: String, val level: Int? = null ) data class ParamsOfCalcStorageFee( val account: String, val period: Int ) data class AddressStringFormat( val type: AddressType, val url: Boolean? = null, val test: Boolean? = null, val bounce: Boolean? = null ) enum class AddressType { AccountId, Hex, Base64 }
0
Kotlin
7
9
9e3a1d2c9588ef051f59f9d2c23bcda10336b0a0
3,889
ton-client-kotlin
Apache License 2.0
test/resources/custom_dsl/test_dsl_include.kt
kscripting
53,889,290
false
{"Kotlin": 211739, "Shell": 21414, "Batchfile": 2644, "R": 1047, "Dockerfile": 1006}
fun included() = "kscript is awesome"
37
Kotlin
123
2,028
6acd4e1907478c49cc4e3db640200f926933b15d
37
kscript
MIT License