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
app/src/main/java/com/quizapp/presentation/update_profile/UpdateProfileState.kt
AhmetOcak
591,704,302
false
null
package com.quizapp.presentation.update_profile sealed interface UpdateProfileState { object Nothing : UpdateProfileState object Loading : UpdateProfileState object Success : UpdateProfileState data class Error(val errorMessage: String) : UpdateProfileState }
0
Kotlin
0
5
cc9d467fcd37cc88c9bbac315bd9aae920722bac
276
QuizApp
MIT License
libmultimusic/src/main/kotlin/com/cg/libmultimusic/Result.kt
CGQAQ
124,336,638
false
null
package com.cg.libmultimusic class Result{ var data: List<DataEntray>? = null var code: Int = 0 var error: String? = null inner class DataEntray { var type: String? = null var link: String? = null var songid: String? = null var title: String? = null var author: String? = null var lrc: String? = null var url: String? = null var pic: String? = null } }
0
Kotlin
0
0
1edda3ec6c28c8369edc5e590bbdbce68253ec04
439
MultiMusic
MIT License
app/src/main/java/com/amio/tapo/Settings.kt
yyewolf
727,733,709
false
{"Kotlin": 25380}
package com.amio.tapo import android.content.Intent import android.os.Bundle import android.util.Log import androidx.appcompat.app.AppCompatActivity import androidx.preference.PreferenceFragmentCompat class Settings : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.settings_activity) if (savedInstanceState == null) { supportFragmentManager .beginTransaction() .replace(R.id.settings, SettingsFragment()) .commit() } supportActionBar?.setDisplayHomeAsUpEnabled(true) } class SettingsFragment : PreferenceFragmentCompat() { override fun onCreatePreferences(savedInstanceState: Bundle?, rootKey: String?) { setPreferencesFromResource(R.xml.root_preferences, rootKey) } } fun closeSettings(v: android.view.View) { val intent = Intent(this, MainActivity::class.java) startActivity(intent) } }
0
Kotlin
0
3
1f5d5646b88657b9746b9960c6e23ed5877305a2
1,048
amio2023
ISC License
app/src/main/java/com/puutaro/commandclick/common/variable/SharePrefferenceSetting.kt
puutaro
596,852,758
false
null
package com.puutaro.commandclick.common.variable enum class SharePrefferenceSetting( val defalutStr: String ) { current_app_dir(UsePath.cmdclickDefaultAppDirPath), current_script_file_name(CommandClickShellScript.EMPTY_STRING), on_shortcut(ShortcutOnValueStr.OFF.name), }
1
null
1
31
e2430cb4d1769ac6927f6b4508cd12e4c12eeadb
288
CommandClick
MIT License
kafkistry-sql/src/main/kotlin/com/infobip/kafkistry/sql/model.kt
infobip
456,885,171
false
{"Kotlin": 2628950, "FreeMarker": 812501, "JavaScript": 297269, "CSS": 7204}
package com.infobip.kafkistry.sql import com.infobip.kafkistry.kafka.KafkaAclRule import com.infobip.kafkistry.service.kafkastreams.KStreamAppId import com.infobip.kafkistry.model.ConsumerGroupId import com.infobip.kafkistry.model.KafkaClusterIdentifier import com.infobip.kafkistry.model.PrincipalId import com.infobip.kafkistry.model.QuotaEntityID import com.infobip.kafkistry.model.TopicName //////////////////////////////// // Result of query execution //////////////////////////////// data class QueryResult( val count: Int, val totalCount: Int, val columns: List<ColumnMeta>, val columnLinkedType: Map<Int, LinkedResource.Type>, val linkedCompoundTypes: List<LinkedResource.Type>, val rows: List<QueryResultRow> ) data class ColumnMeta( val name: String, val type: String ) data class QueryResultRow( val values: List<Any?>, val linkedResource: LinkedResource? ) data class LinkedResource( val types: List<Type>, val topic: TopicName? = null, val cluster: KafkaClusterIdentifier? = null, val group: ConsumerGroupId? = null, val principal: PrincipalId? = null, val acl: KafkaAclRule? = null, val quotaEntityID: QuotaEntityID? = null, val kafkaStreamAppId: KStreamAppId? = null, ) { enum class Type { TOPIC, CLUSTER_TOPIC, CLUSTER, CLUSTER_GROUP, PRINCIPAL, PRINCIPAL_ACL, PRINCIPAL_CLUSTER, QUOTA_ENTITY, KSTREAM_APP, } } //////////////////////////////// // Utility //////////////////////////////// data class TableInfo( val name: String, val joinTable: Boolean, val columns: List<ColumnInfo> ) data class ColumnInfo( val name: String, val type: String, val primaryKey: Boolean, val joinKey: Boolean, val referenceKey: Boolean ) data class QueryExample( val title: String, val sql: String )
1
Kotlin
6
42
62403993a76fdf60b4cae3a87c5be0abe4fb3a88
1,980
kafkistry
Apache License 2.0
features/list/viewmodel/src/androidUnitTest/kotlin/imrekaszab/eaplayers/playerlist/PlayerListViewModelTest.kt
kaszabimre
853,228,340
false
{"Kotlin": 123309, "Swift": 2357}
package imrekaszab.eaplayers.playerlist import io.imrekaszab.eaplayers.core.util.testParamCommandExecute import io.imrekaszab.eaplayers.domain.action.EAPlayerAction import io.imrekaszab.eaplayers.domain.model.MockPlayer import io.imrekaszab.eaplayers.domain.store.EAPlayerStore import io.imrekaszab.eaplayers.playerlist.viewmodel.PlayerListViewModel import io.imrekaszab.eaplayers.testing.MainDispatcherRule import io.mockk.coEvery import io.mockk.coVerify import io.mockk.mockk import kotlinx.coroutines.flow.flowOf import kotlinx.coroutines.test.runTest import org.junit.Rule import kotlin.test.BeforeTest import kotlin.test.Test import kotlin.test.assertEquals class PlayerListViewModelTest { private val eaPlayerAction: EAPlayerAction = mockk() private val eaPlayerStore: EAPlayerStore = mockk() private lateinit var viewModel: PlayerListViewModel @get:Rule val mainDispatcherRule = MainDispatcherRule() @BeforeTest fun setUp() { viewModel = PlayerListViewModel(eaPlayerAction, eaPlayerStore) } @Test fun `refreshPlayers with non-empty textFieldValue should call action and update state`() = runTest(mainDispatcherRule.testDispatcher) { // Given val searchValue = "some value" val playerList = listOf(MockPlayer.createMockPlayer()) coEvery { eaPlayerStore.getPlayerList() } returns flowOf(playerList) coEvery { eaPlayerAction.refreshPlayers(any()) } returns Unit // When viewModel.refreshPlayers.testParamCommandExecute(scope = this, param = searchValue) // Then assertEquals(false, viewModel.uiState.value.loading) assertEquals(playerList, viewModel.uiState.value.players) assertEquals(searchValue, viewModel.uiState.value.textFieldValue) coVerify { eaPlayerAction.refreshPlayers(searchValue) } } @Test fun `refreshPlayers with empty textFieldValue should call action with empty string`() = runTest(mainDispatcherRule.testDispatcher) { // Given val playerList = listOf(MockPlayer.createMockPlayer()) coEvery { eaPlayerStore.getPlayerList() } returns flowOf(playerList) coEvery { eaPlayerAction.refreshPlayers(any()) } returns Unit // When viewModel.refreshPlayers.testParamCommandExecute(scope = this, param = "") // Then assertEquals(false, viewModel.uiState.value.loading) assertEquals(playerList, viewModel.uiState.value.players) assertEquals("", viewModel.uiState.value.textFieldValue) coVerify { eaPlayerAction.refreshPlayers("") } } }
15
Kotlin
2
2
85b56abea8531a2ace9aaa76e9508ab3ef64ad7f
2,721
EAPlayers
Apache License 2.0
src/main/kotlin/sql/expr/Equals.kt
blazejsewera
512,261,235
false
{"Kotlin": 6000}
package sql.expr class Equals(private val a: Expression, private val b: Expression) : Expression { override fun toDeclaration(): String { return "${a.toReference()}=${b.toReference()}" } }
0
Kotlin
0
1
26a297008377d5c89ec0edda64f659257bea1cc3
205
fluent-squirrel
Apache License 2.0
app/src/main/java/keda/tech/android/catalog/utils/Helper.kt
Xanity16
800,009,693
false
{"Kotlin": 41384}
package keda.tech.android.catalog.utils import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.launch import kotlinx.coroutines.withContext import java.text.SimpleDateFormat import java.util.Date import java.util.Locale class Helper { companion object { fun getCurrentTimeStamp(date: Date): String? { return SimpleDateFormat( "yyyy-MM-dd HH:mm:ss", Locale.getDefault() ).format(date) //dd/MM/yyyy } } } fun <R> CoroutineScope.executeAsyncTask( onPreExecute: () -> Unit, doInBackground: () -> R, onPostExecute: (R) -> Unit ) = launch { onPreExecute() // runs in Main Thread val result = withContext(Dispatchers.IO) { doInBackground() // runs in background thread without blocking the Main Thread } onPostExecute(result) // runs in Main Thread }
0
Kotlin
0
0
a5b737c80c744321d11dac286498eb52a253357a
912
Test-Android-Muhamad-Fauzan-Luthfi
MIT License
eval4j/test/org/jetbrains/eval4j/jdi/test/jdiTest.kt
hhariri
21,116,939
true
null
/* * Copyright 2010-2014 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.jetbrains.eval4j.jdi.test import org.jetbrains.eval4j.* import com.sun.jdi import junit.framework.TestSuite import org.jetbrains.eval4j.test.buildTestSuite import junit.framework.TestCase import org.jetbrains.eval4j.interpreterLoop import org.junit.Assert.* import java.util.concurrent.CountDownLatch import java.util.concurrent.atomic.AtomicInteger import org.jetbrains.eval4j.ExceptionThrown import org.jetbrains.eval4j.MethodDescription import org.jetbrains.eval4j.ValueReturned import org.jetbrains.eval4j.jdi.* import java.io.File val DEBUGEE_CLASS = javaClass<Debugee>() fun suite(): TestSuite { val connectors = jdi.Bootstrap.virtualMachineManager().launchingConnectors() val connector = connectors[0] println("Using connector $connector") val connectorArgs = connector.defaultArguments() val debugeeName = DEBUGEE_CLASS.getName() println("Debugee name: $debugeeName") connectorArgs["main"]!!.setValue(debugeeName) connectorArgs["options"]!!.setValue("-classpath out/production/eval4j${File.pathSeparator}out/test/eval4j") val vm = connector.launch(connectorArgs)!! val req = vm.eventRequestManager().createClassPrepareRequest() req.addClassFilter("*.Debugee") req.enable() val latch = CountDownLatch(1) var classLoader : jdi.ClassLoaderReference? = null var thread : jdi.ThreadReference? = null Thread { val eventQueue = vm.eventQueue() @mainLoop while (true) { val eventSet = eventQueue.remove() for (event in eventSet.eventIterator()) { when (event) { is jdi.event.ClassPrepareEvent -> { val _class = event.referenceType()!! if (_class.name() == debugeeName) { for (l in _class.allLineLocations()) { if (l.method().name() == "main") { classLoader = l.method().declaringType().classLoader() val breakpointRequest = vm.eventRequestManager().createBreakpointRequest(l) breakpointRequest.enable() println("Breakpoint: $breakpointRequest") vm.resume() break } } } } is jdi.event.BreakpointEvent -> { println("Suspended at: " + event.location()) thread = event.thread() latch.countDown() break @mainLoop } else -> {} } } } }.start() vm.resume() latch.await() var remainingTests = AtomicInteger(0) val suite = buildTestSuite { methodNode, ownerClass, expected -> remainingTests.incrementAndGet() object : TestCase("test" + methodNode.name.capitalize()) { override fun runTest() { val eval = JDIEval( vm, classLoader!!, thread!!, 0 ) val value = interpreterLoop( methodNode, makeInitialFrame(methodNode, listOf()), eval ) fun jdi.ObjectReference?.callToString(): String? { if (this == null) return "null" return (eval.invokeMethod( this.asValue(), MethodDescription( "java/lang/Object", "toString", "()Ljava/lang/String;", false ), listOf()).jdiObj as jdi.StringReference).value() } try { if (value is ExceptionThrown) { val str = value.exception.jdiObj.callToString() System.err.println("Exception: $str") } if (expected is ValueReturned && value is ValueReturned && value.result is ObjectValue) { assertEquals(expected.result.obj().toString(), value.result.jdiObj.callToString()) } else { assertEquals(expected, value) } } finally { if (remainingTests.decrementAndGet() == 0) vm.resume() } } } } return suite }
0
Java
0
0
d150bfbce0e2e47d687f39e2fd233ea55b2ccd26
5,541
kotlin
Apache License 2.0
leetcode-75-kotlin/src/main/kotlin/ReverseLinkedList.kt
Codextor
751,507,040
false
{"Kotlin": 78987}
import commonclasses.ListNode /** * Given the head of a singly linked list, reverse the list, and return the reversed list. * * * * Example 1: * * * Input: head = [1,2,3,4,5] * Output: [5,4,3,2,1] * Example 2: * * * Input: head = [1,2] * Output: [2,1] * Example 3: * * Input: head = [] * Output: [] * * * Constraints: * * The number of nodes in the list is the range [0, 5000]. * -5000 <= Node.val <= 5000 * * * Follow up: A linked list can be reversed either iteratively or recursively. Could you implement both? * @see <a href="https://leetcode.com/problems/reverse-linked-list/">LeetCode</a> * * Example: * var li = ListNode(5) * var v = li.`val` * Definition for singly-linked list. * class ListNode(var `val`: Int) { * var next: ListNode? = null * } */ fun reverseList(head: ListNode?): ListNode? { var previousNode: ListNode? = null var currentNode = head while (currentNode != null) { val nextNode = currentNode.next currentNode.next = previousNode previousNode = currentNode currentNode = nextNode } return previousNode }
0
Kotlin
0
0
a0bb6840b32d6c43dda0872f61a87d641c933729
1,124
leetcode-75
Apache License 2.0
src/main/kotlin/me/peckb/aoc/_2017/calendar/day09/Day09.kt
peckb1
433,943,215
false
null
package me.peckb.aoc._2017.calendar.day09 import javax.inject.Inject import me.peckb.aoc.generators.InputGenerator.InputGeneratorFactory class Day09 @Inject constructor(private val generatorFactory: InputGeneratorFactory) { fun partOne(filename: String) = generatorFactory.forFile(filename).readOne { input -> var groupDepth = 0 var insideGarbage = false var score = 0 input.forEachIndexed loop@ { index, character -> when (character) { '{' -> { if (insideGarbage) return@loop val numCancelsBeforeMe = input.countCancelsBefore(index) if ((numCancelsBeforeMe % 2) == 0) groupDepth ++ } '}' -> { if (insideGarbage) return@loop val numCancelsBeforeMe = input.countCancelsBefore(index) if ((numCancelsBeforeMe % 2) == 0) { score += groupDepth groupDepth -- } } '<' -> { if (insideGarbage) return@loop val numCancelsBeforeMe = input.countCancelsBefore(index) if ((numCancelsBeforeMe % 2) == 0) insideGarbage = true } '>' -> { if (!insideGarbage) return@loop val numCancelsBeforeMe = input.countCancelsBefore(index) if ((numCancelsBeforeMe % 2) == 0) insideGarbage = false } } } score } fun partTwo(filename: String) = generatorFactory.forFile(filename).readOne { input -> var groupDepth = 0 var insideGarbage = false var cancelling = false var garbageCount = 0 input.forEachIndexed loop@ { index, character -> if (insideGarbage) garbageCount++ when (character) { '!' -> { cancelling = !cancelling garbageCount-- } else -> { if (cancelling) { cancelling = false garbageCount-- } when (character) { '{' -> { if (insideGarbage) return@loop val numCancelsBeforeMe = input.countCancelsBefore(index) if ((numCancelsBeforeMe % 2) == 0) groupDepth++ } '}' -> { if (insideGarbage) return@loop val numCancelsBeforeMe = input.countCancelsBefore(index) if ((numCancelsBeforeMe % 2) == 0) groupDepth-- } '<' -> { if (insideGarbage) return@loop val numCancelsBeforeMe = input.countCancelsBefore(index) if ((numCancelsBeforeMe % 2) == 0) insideGarbage = true } '>' -> { if (!insideGarbage) return@loop val numCancelsBeforeMe = input.countCancelsBefore(index) if ((numCancelsBeforeMe % 2) == 0) { garbageCount-- insideGarbage = false } } } } } } garbageCount } private fun String.countCancelsBefore(index: Int): Int { var lookback = 1 var cancels = 0 var keepLooking = true while(keepLooking && index - lookback > 0) { if (this[index - lookback] == '!') { cancels++ } else { keepLooking = false } lookback++ } return cancels } }
0
Kotlin
1
4
62165673b98381031d964a962ed0328474d20870
3,225
advent-of-code
MIT License
library/src/iosMain/kotlin/com/myunidays/klipper/FlipperClient.kt
MyUNiDAYS
639,905,031
false
null
package com.myunidays.klipper actual class FlipperClient internal constructor(val ios: cocoapods.FlipperKit.FlipperClient) { //internal constructor(val ios: cocoapods.Analytics.SEGAnalytics) { }
0
Kotlin
1
2
247e7313ade129c9b5a52c77204717831f2e0d2f
197
Klipper
MIT License
data/src/main/java/com/sentinel/data/datasource/remote/service/GenreService.kt
MatheusMatz
369,885,065
false
null
package com.sentinel.data.datasource.remote.service import com.sentinel.data.datasource.remote.responses.GenreListResponse import retrofit2.Response import retrofit2.http.GET interface GenreService { @GET("genre/movie/list?api_key=<KEY>") suspend fun getMovieGenres(): Response<GenreListResponse> @GET("genre/tv/list?api_key=<KEY>") suspend fun getTVGenres(): Response<GenreListResponse> }
0
Kotlin
0
0
d2e9ae24d36e65349f74c49b7c222dd86ba907c3
410
MyMovieCompendium
MIT License
server/src/main/kotlin/com/thoughtworks/archguard/scanner2/infrastructure/mysql/ScannerClassRepositoryImpl.kt
archguard
460,910,110
false
null
package com.thoughtworks.archguard.scanner2.infrastructure.mysql import com.thoughtworks.archguard.scanner2.domain.model.Dependency import com.thoughtworks.archguard.scanner2.domain.model.JClass import com.thoughtworks.archguard.scanner2.domain.model.JField import com.thoughtworks.archguard.scanner2.domain.repository.JClassRepository import org.jdbi.v3.core.Jdbi import org.jdbi.v3.core.mapper.reflect.ConstructorMapper import org.springframework.stereotype.Repository @Repository class ScannerClassRepositoryImpl(val jdbi: Jdbi) : JClassRepository { override fun findClassParents(systemId: Long, module: String?, name: String?): List<JClass> { val moduleFilter = if (module == null) { "and c.module is NULL" } else { "and c.module='$module'" } val sql = "SELECT DISTINCT p.id as id, p.name as name, p.module as module, p.loc as loc, p.access as access " + " FROM code_class c,`code_ref_class_parent` cp,code_class p" + " WHERE c.id = cp.a AND cp.b = p.id" + " And c.system_id = $systemId" + " AND c.name = '$name' $moduleFilter" return jdbi.withHandle<List<JClassPO>, Nothing> { it.registerRowMapper(ConstructorMapper.factory(JClassPO::class.java)) it.createQuery(sql) .mapTo(JClassPO::class.java) .list() }.map { it.toJClass() } } override fun findClassImplements(systemId: Long, name: String?, module: String?): List<JClass> { val moduleFilter = if (module == null) { "and p.module is NULL" } else { "and p.module='$module'" } val sql = "SELECT DISTINCT c.id as id, c.name as name, c.module as module, c.loc as loc, c.access as access " + " FROM code_class c,`code_ref_class_parent` cp,code_class p" + " WHERE c.id = cp.a AND cp.b = p.id" + " AND c.system_id = $systemId" + " AND p.name = '$name' $moduleFilter" return jdbi.withHandle<List<JClassPO>, Nothing> { it.registerRowMapper(ConstructorMapper.factory(JClassPO::class.java)) it.createQuery(sql) .mapTo(JClassPO::class.java) .list() }.map { it.toJClass() } } override fun findFields(id: String): List<JField> { val sql = "SELECT id, name, type FROM code_field WHERE id in (select b from code_ref_class_fields where a='$id')" return jdbi.withHandle<List<JField>, Nothing> { it.registerRowMapper(ConstructorMapper.factory(JField::class.java)) it.createQuery(sql) .mapTo(JField::class.java) .list() } } override fun getDistinctClassDependenciesAndNotThirdParty(systemId: Long): List<Dependency<String>> { return getAllClassDependenciesAndNotThirdParty(systemId).toSet().toList() } override fun getAllClassDependenciesAndNotThirdParty(systemId: Long): List<Dependency<String>> { val sql = "select a as caller, b as callee from code_ref_class_dependencies where system_id = :systemId " + "and a in (select id from code_class where code_class.system_id = :systemId and is_thirdparty = 0 and is_test = 0) " + "and b in (select id from code_class where code_class.system_id = :systemId and is_thirdparty = 0 and is_test = 0) " + "and a!=b" return jdbi.withHandle<List<IdDependencyDto>, Nothing> { it.registerRowMapper(ConstructorMapper.factory(IdDependencyDto::class.java)) it.createQuery(sql) .bind("systemId", systemId) .mapTo(IdDependencyDto::class.java) .list() }.map { it.toDependency() } } override fun findClassBy(systemId: Long, name: String, module: String?): JClass? { val moduleFilter = if (module == null) { "and module is NULL" } else { "and module='$module'" } val sql = "SELECT id, name, module, loc, access FROM code_class where system_id = $systemId and name = '$name' $moduleFilter limit 1" val withHandle = jdbi.withHandle<JClassPO?, RuntimeException> { it.registerRowMapper(ConstructorMapper.factory(JClassPO::class.java)) it.createQuery(sql) .mapTo(JClassPO::class.java) .firstOrNull() } return withHandle?.toJClass() } override fun getJClassesNotThirdPartyAndNotTest(systemId: Long): List<JClass> { val sql = "SELECT id, name, module, loc, access FROM code_class where system_id = :systemId " + "and is_thirdparty = 0 and is_test = 0" return jdbi.withHandle<List<JClassPO>, Nothing> { it.registerRowMapper(ConstructorMapper.factory(JClassPO::class.java)) it.createQuery(sql) .bind("systemId", systemId) .mapTo(JClassPO::class.java) .list() }.map { it.toJClass() } } }
3
null
89
575
049f3cc8f2c0e2c34e65bb0049f645caa5be9bf8
5,105
archguard
MIT License
src/main/kotlin/com/miguel/tibia_merchants_api/domain/models/Profile.kt
MiguelJeronimo
826,940,577
false
{"Kotlin": 152292, "Dockerfile": 869}
package com.miguel.tibia_merchants_api.domain.models data class Profile( var name: String? = null, var img: String? = null, var tibia_lengend: String? = null, var notes: String? = null, var requeriments: Requeriments? = null, var combat_propierties: CombatPropierties? = null, var general_propierties: GeneralPropierties? = null, var trader_propierties: TraderPropierties? = null, var magic_properties: MagicProperties? = null, var field_propierties: FieldPropierties? = null, var other_propierties: OtherPropierties? = null, var buy_from: ArrayList<BuyFrom>? = null, var sell_from: ArrayList<SellFrom>? = null ) data class BuyFrom( var npc: String? = null, var location: String? = null, var price: String? = null ) data class SellFrom( var npc: String? = null, var location: String? = null, var price: String? = null ) data class Requeriments( var level: String? = null, var vocation: String? = null, var magic_level: String? = null ) data class CombatPropierties( var imbuing_slots: String? = null, var upgrade_classification: String? = null, var attributes: String? = null, var armor: String? = null, var resists: String? = null, var element: String? = null ) data class GeneralPropierties( var classification: String? = null, var also_known_as:String ? = null, var item_class: String? = null, var origin:String?=null, var notes:String? = null, var pickupable: String? = null, var weight: String? = null, var stackable: String? = null, ) data class TraderPropierties( var marketable: String? = null, var value: String? = null, var sold_for: String? = null, var bought_for: String? = null, var loot_value: String? = null, var store_price: String? = null, ) data class FieldPropierties( var blocking: String? = null, var light: String? = null ) data class OtherPropierties( var version: String? = null ) data class MagicProperties( var words: String? = null ) data class Sections( var key: String? = null, var value: String? = null )
0
Kotlin
0
0
10bcf7c068d4b76dc200450e5b90c64d4ac5442e
2,137
tibia-merchants-api
MIT License
api/src/main/kotlin/dev/akif/battleships/game/GameRepository.kt
makiftutuncu
854,576,802
false
{"Kotlin": 55732, "TypeScript": 23305, "Dockerfile": 844, "JavaScript": 689, "HTML": 281}
package dev.akif.battleships.game import dev.akif.battleships.query.GameEntity import org.springframework.data.jpa.repository.JpaRepository import org.springframework.stereotype.Repository @Repository interface GameRepository: JpaRepository<GameEntity, Long>
4
Kotlin
0
0
a90116a20665c13fb8f1f27fcbb17717035840f5
261
getting-your-axe-on
MIT License
app/src/main/java/com/bitshares/oases/ui/wallet/WalletViewModel.kt
huskcasaca
464,732,039
false
null
package com.bitshares.oases.ui.wallet import android.app.Application import com.bitshares.oases.globalPreferenceManager import com.bitshares.oases.globalWalletManager import com.bitshares.oases.provider.local_repo.LocalUserRepository import com.bitshares.oases.ui.base.BaseViewModel class WalletViewModel(application: Application) : BaseViewModel(application) { val account = LocalUserRepository.currentUserAccount val userList = LocalUserRepository.decryptedList(globalWalletManager) val currentUser = LocalUserRepository.decryptCurrentUser(globalWalletManager) val usePassword = globalPreferenceManager.USE_PASSWORD val useBio = globalPreferenceManager.USE_BIO }
0
Kotlin
4
5
2522ec7169a5fd295225caf936bae2edf09b157e
693
bitshares-oases-android
MIT License
src/main/kotlin/uk/gov/justice/digital/hmpps/approvedpremisesapi/config/PrisonCaseNotesConfig.kt
ministryofjustice
515,276,548
false
{"Kotlin": 8393388, "Shell": 15748, "Dockerfile": 1667, "Mustache": 383}
package uk.gov.justice.digital.hmpps.approvedpremisesapi.config import org.springframework.boot.context.properties.ConfigurationProperties import org.springframework.stereotype.Component @Component @ConfigurationProperties(prefix = "prison-case-notes") class PrisonCaseNotesConfigBindingModel { var lookbackDays: Int? = null var prisonApiPageSize: Int? = null var excludedCategories: List<ExcludedCategoryBindingModel>? = null } data class PrisonCaseNotesConfig( val lookbackDays: Int, val prisonApiPageSize: Int, val excludedCategories: List<ExcludedCategory>, ) class ExcludedCategoryBindingModel { var category: String? = null var subcategory: String? = null set(value) { field = if (value == "") null else value } } data class ExcludedCategory( val category: String, val subcategory: String?, ) { fun excluded(otherCategory: String, otherSubcategory: String) = (otherCategory == category && subcategory == null) || (otherCategory == category && otherSubcategory == subcategory) }
21
Kotlin
2
5
5b02281acd56772dc5d587f8cd4678929a191ac0
1,025
hmpps-approved-premises-api
MIT License
compiler/testData/resolvedCalls/implicitReceiverIsThisObject.kt
hhariri
21,116,939
true
null
// !CALL: foo // !EXPLICIT_RECEIVER_KIND: NO_EXPLICIT_RECEIVER // !THIS_OBJECT: A // !RECEIVER_ARGUMENT: NO_RECEIVER class A { fun foo() {} } fun A.bar() { foo() }
0
Java
0
0
d150bfbce0e2e47d687f39e2fd233ea55b2ccd26
174
kotlin
Apache License 2.0
one.irradia.neutrino.views/src/main/java/one/irradia/neutrino/views/api/NeutrinoEventType.kt
irradia
179,164,018
false
null
package one.irradia.neutrino.views.api /** * The root type of events. * * This interface is primarily a marker interface to make it easier to find concrete * event implementations in the IDE and generated documentation. */ interface NeutrinoEventType
0
Kotlin
0
0
4f0e65806453516bc774f3f96c1b3698e996dc9b
258
one.irradia.neutrino
ISC License
app/src/main/kotlin/com/dot/gallery/feature_node/presentation/ignored/IgnoredViewModel.kt
IacobIonut01
614,314,251
false
{"Kotlin": 939452, "Shell": 455}
package com.dot.gallery.feature_node.presentation.ignored import android.annotation.SuppressLint import androidx.compose.runtime.Composable import androidx.lifecycle.ViewModel import androidx.lifecycle.viewModelScope import com.dot.gallery.feature_node.domain.model.BlacklistedAlbum import com.dot.gallery.feature_node.domain.use_case.MediaUseCases import com.dot.gallery.feature_node.presentation.util.RepeatOnResume import dagger.hilt.android.lifecycle.HiltViewModel import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.asStateFlow import kotlinx.coroutines.flow.collectLatest import kotlinx.coroutines.launch import javax.inject.Inject @HiltViewModel class IgnoredViewModel @Inject constructor( private val mediaUseCases: MediaUseCases ): ViewModel() { private val _ignoredState = MutableStateFlow(IgnoredState()) val blacklistState = _ignoredState.asStateFlow() init { getIgnoredAlbums() } @SuppressLint("ComposableNaming") @Composable fun attachToLifecycle() { RepeatOnResume { getIgnoredAlbums() } } fun addToBlacklist(blacklistedAlbum: BlacklistedAlbum) { viewModelScope.launch { mediaUseCases.blacklistUseCase.addToBlacklist(blacklistedAlbum) } } fun removeFromBlacklist(blacklistedAlbum: BlacklistedAlbum) { viewModelScope.launch { mediaUseCases.blacklistUseCase.removeFromBlacklist(blacklistedAlbum) } } private fun getIgnoredAlbums() { viewModelScope.launch { mediaUseCases.blacklistUseCase.blacklistedAlbums.collectLatest { _ignoredState.tryEmit(IgnoredState(it)) } } } }
65
Kotlin
57
997
3510ea658dff358a0ea0716997082d0e06234c83
1,725
Gallery
Apache License 2.0
31-coroutine-channels/src/main/kotlin/com/jjh/coroutine/MultipleSendersApp.kt
johnehunt
286,785,922
false
null
package com.jjh.coroutine import kotlinx.coroutines.GlobalScope import kotlinx.coroutines.channels.Channel import kotlinx.coroutines.delay import kotlinx.coroutines.launch fun main() { suspend fun sendMessage(tag: String, channel: Channel<String>, message: String, time: Long) { repeat (5) { delay(time) println("$tag sending --> $message") channel.send(message) } } suspend fun receiveMessage(channel: Channel<String>) { while (true) { println("Receiver --> ${channel.receive()}") } } println("Main -> Multiple senders and one receiver") val msgChannel = Channel<String>() // Launch multipel sending coroutines GlobalScope.launch { sendMessage("Sender1", msgChannel, "Welcome", 300L) } GlobalScope.launch { sendMessage("Sender2", msgChannel, "Hello", 150L) } // Launch a single receiving coroutine GlobalScope.launch { receiveMessage(msgChannel) } println("Main -> After launching coroutines") println("Main -> Waiting for task - press enter to continue:") readLine() msgChannel.close() println("Main -> Done") }
0
Kotlin
0
3
9fe70db1b4a3435dcfb002512c345e519db1a5f8
1,472
kotlin-book
Apache License 2.0
backend/src/main/kotlin/dev/dres/api/rest/types/WebSocketConnection.kt
taylor-mccants
355,537,231
true
{"Kotlin": 677088, "TypeScript": 271606, "HTML": 111360, "SCSS": 5259, "JavaScript": 1833, "Dockerfile": 412}
package dev.dres.api.rest.types import dev.dres.api.rest.AccessManager import dev.dres.data.model.UID import dev.dres.mgmt.admin.UserManager import io.javalin.plugin.json.JavalinJson import io.javalin.websocket.WsContext import org.eclipse.jetty.server.session.Session import java.nio.ByteBuffer /** * Wraps a [WsContext] and gives access to specific information regarding the user owning that [WsContext] * * @author <NAME> * @version 1.0 */ inline class WebSocketConnection(val context: WsContext) { /** ID of the WebSocket session. */ val sessionId get() = context.sessionId /** ID of the HTTP session that generated this [WebSocketConnection]. */ val httpSessionId get() = (this.context.session.upgradeRequest.session as Session).id /** Name of the user that generated this [WebSocketConnection]. */ val userName get() = UserManager.get(AccessManager.getUserIdForSession(this.httpSessionId) ?: UID.EMPTY)?.username?.name ?: "UNKNOWN" /** IP address of the client. */ val host get() = this.context.session.remoteAddress.hostString fun send(message: Any) = this.context.send(JavalinJson.toJson(message)) fun send(message: String) = this.context.send(message) fun send(message: ByteBuffer) = this.context.send(message) }
0
null
0
0
c42681869837206ed6256d78eba91e0c30ac3176
1,308
DRES
MIT License
core/src/main/java/com/afdhal_fa/core/ui/GamesAdapter.kt
Fuadafdhal
298,238,007
false
null
package com.afdhal_fa.core.ui /** * Copyright 2020 <NAME> Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ import android.annotation.SuppressLint import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.recyclerview.widget.RecyclerView import com.afdhal_fa.core.R import com.afdhal_fa.core.domain.model.Game import com.bumptech.glide.Glide import kotlinx.android.synthetic.main.item_list_game.view.* import java.util.* class GamesAdapter : RecyclerView.Adapter<GamesAdapter.ListViewHolder>() { private var listData = ArrayList<Game>() var onItemClick: ((Game) -> Unit)? = null fun setData(newListData: List<Game>?) { if (newListData == null) return listData.clear() listData.addAll(newListData) notifyDataSetChanged() } override fun onCreateViewHolder(parent: ViewGroup, viewType: Int) = ListViewHolder(LayoutInflater.from(parent.context).inflate(R.layout.item_list_game, parent, false)) override fun getItemCount() = listData.size override fun onBindViewHolder(holder: ListViewHolder, position: Int) { val data = listData[position] holder.bind(data) } inner class ListViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) { @SuppressLint("SetTextI18n") fun bind(data: Game) { with(itemView) { Glide.with(itemView.context) .load(data.imageUrl) .placeholder(R.mipmap.image_placeholder) .into(iv_item_image) tv_item_title.text = data.name } } init { itemView.setOnClickListener { onItemClick?.invoke(listData[adapterPosition]) } } } }
0
Kotlin
1
1
e234cc9f74c9cf1ec632d019d5bcc5c0ba64a55b
2,269
InGame
Apache License 2.0
ui/src/main/java/com/mhacks/app/ui/ticket/TicketDialogProvider.kt
a-ye13
207,436,130
true
{"Kotlin": 302268, "Java": 2165}
package com.mhacks.app.ui.ticket import dagger.Module import dagger.android.ContributesAndroidInjector /** * Provides dependencies into special blend fragment. */ @Module abstract class TicketDialogProvider { @ContributesAndroidInjector(modules = [TicketDialogModule::class]) abstract fun provideTicketDialogFragment(): TicketDialogFragment }
0
null
0
0
edf4ae94b7be31f25bf47a77062c74e80430c663
355
mhacks-android
MIT License
app/src/main/java/hexlay/movyeah/fragments/SearchFragment.kt
hexlay
246,402,717
false
null
package hexlay.movyeah.fragments import androidx.core.view.isVisible import hexlay.movyeah.R import hexlay.movyeah.fragments.base.AbsMoviesFragment import hexlay.movyeah.helpers.dpOf import hexlay.movyeah.helpers.setMargins import hexlay.movyeah.models.Filter import kotlinx.android.synthetic.main.fragment_movies.* class SearchFragment : AbsMoviesFragment() { override var filter: Filter = Filter(this) private var searchText = "" override fun initFragment() { initRecyclerView() initScrollUp() initFilter() initSearch() handleObserver() } override fun initScrollUp() { super.initScrollUp() scroll_up.setMargins(bottom = dpOf(20)) } private fun initSearch() { warning_holder.isVisible = true warning_holder.text = getString(R.string.search_text) movies_reloader.isEnabled = false } override fun initFilter() { fab_filter.hide() } override fun loadMovies() { movieListViewModel.fetchSearchMovie(page, searchText) } fun search(text: String) { if (text.isEmpty()) return searchText = text zeroLoadMovies() } override fun handleObserver() { super.handleObserver() fab_filter.hide() } }
0
Kotlin
0
5
aa74fdb841edf35a47b43d990ecfacd9034dc53c
1,306
MovYeah
Creative Commons Zero v1.0 Universal
plugins/devkit/devkit-kotlin-tests/testData/util/serviceUtil/serviceUsages/kotlin/UsagesOfKtRegisteredApplicationService.kt
JetBrains
2,489,216
false
null
@file:Suppress("UNUSED_PARAMETER", "UNUSED_VARIABLE") import serviceDeclarations.KtRegisteredApplicationService fun foo7() { val service = <caret>KtRegisteredApplicationService.getInstance() }
284
null
5162
16,707
def6433a5dd9f0a984cbc6e2835d27c97f2cb5f0
197
intellij-community
Apache License 2.0
app/src/main/java/me/bakumon/moneykeeper/ui/assets/add/AddAssetsViewModel.kt
twwbmitnlf
166,140,516
true
{"Kotlin": 586558, "Java": 58642}
/* * Copyright 2018 Bakumon. https://github.com/Bakumon * * 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 me.bakumon.moneykeeper.ui.assets.add import androidx.lifecycle.LiveData import androidx.lifecycle.MutableLiveData import io.reactivex.android.schedulers.AndroidSchedulers import io.reactivex.schedulers.Schedulers import me.bakumon.moneykeeper.base.Resource import me.bakumon.moneykeeper.database.entity.Assets import me.bakumon.moneykeeper.database.entity.AssetsModifyRecord import me.bakumon.moneykeeper.datasource.AppDataSource import me.bakumon.moneykeeper.ui.common.BaseViewModel import java.math.BigDecimal /** * AddAssetsViewModel * * @author Bakumon https://bakumon.me */ class AddAssetsViewModel(dataSource: AppDataSource) : BaseViewModel(dataSource) { fun addAssets(assets: Assets): LiveData<Resource<Boolean>> { val liveData = MutableLiveData<Resource<Boolean>>() mDisposable.add(mDataSource.addAssets(assets) .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .subscribe({ liveData.value = Resource.create(true) } ) { throwable -> throwable.printStackTrace() liveData.value = Resource.create(throwable) }) return liveData } fun updateAssets(moneyBefore: BigDecimal, assets: Assets): LiveData<Resource<Boolean>> { val liveData = MutableLiveData<Resource<Boolean>>() mDisposable.add(mDataSource.updateAssets(assets) .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .subscribe({ if (moneyBefore == assets.money) { liveData.value = Resource.create(true) } else { addAssetsModifyRecord(liveData, moneyBefore, assets) } } ) { throwable -> liveData.value = Resource.create(throwable) }) return liveData } private fun addAssetsModifyRecord( liveData: MutableLiveData<Resource<Boolean>>, moneyBefore: BigDecimal, assets: Assets ): LiveData<Resource<Boolean>> { val modifyRecord = AssetsModifyRecord(assetsId = assets.id!!, moneyBefore = moneyBefore, money = assets.money) mDisposable.add(mDataSource.insertAssetsRecord(modifyRecord) .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .subscribe({ liveData.value = Resource.create(true) } ) { throwable -> liveData.value = Resource.create(throwable) }) return liveData } }
1
Kotlin
1
1
822d49e4c515098ef75d7140512412eff590e269
3,254
MoneyKeeper
Apache License 2.0
src/test/kotlin/com/tkroman/kerl/receiver/RpcReceiverTest.kt
tkroman
387,260,318
false
null
package com.tkroman.kerl.receiver import com.tkroman.kerl.RECEIVER_MAILBOX import com.tkroman.kerl.SENDER_PID import com.tkroman.kerl.executor.RpcExecutor import io.appulse.encon.connection.control.SendToRegisteredProcess import io.appulse.encon.connection.regular.Message import io.appulse.encon.mailbox.Mailbox import io.appulse.encon.terms.type.ErlangAtom.ATOM_FALSE import io.appulse.encon.terms.type.ErlangAtom.ATOM_TRUE import io.appulse.encon.terms.type.ErlangPid import io.mockk.Called import io.mockk.confirmVerified import io.mockk.every import io.mockk.excludeRecords import io.mockk.mockk import io.mockk.verify import org.awaitility.kotlin.await import java.util.concurrent.CompletableFuture import java.util.concurrent.TimeUnit import kotlin.test.AfterTest import kotlin.test.Test import kotlin.test.assertEquals import kotlin.test.assertFailsWith internal class RpcReceiverTest { private val mailbox = mockk<Mailbox>() private val executor = mockk<RpcExecutor>() private val rpcReceiver = RpcReceiver(executor) @AfterTest fun cleanUp() { rpcReceiver.close() } @Test fun `throws if failed to start`() { every { mailbox.receive(any(), any()) }.returns(null) val executor = RpcReceiver(executor) executor.start(mailbox) assertFailsWith<IllegalStateException> { executor.start(mailbox) }.also { assertEquals( "Couldn't start RpcReceiver. Make sure it was stopped correctly before reuse", it.message ) } } @Test fun `happy path`() { every { mailbox.receive(1L, TimeUnit.MILLISECONDS) } .returns( Message( SendToRegisteredProcess(SENDER_PID, RECEIVER_MAILBOX), ATOM_TRUE ) ) .andThen(null) every { executor.execute(ATOM_TRUE) } .returns( CompletableFuture.completedFuture( SENDER_PID to ATOM_FALSE ) ) every { mailbox.send(SENDER_PID, ATOM_FALSE) }.returns(Unit) rpcReceiver.start(mailbox) await .pollDelay(5, TimeUnit.MILLISECONDS) .pollInterval(5, TimeUnit.MILLISECONDS) .timeout(1, TimeUnit.SECONDS) .during(500, TimeUnit.MILLISECONDS) .untilAsserted { verify(atLeast = 1) { mailbox.receive(1L, TimeUnit.MILLISECONDS) } verify(exactly = 1) { executor.execute(ATOM_TRUE) } verify(exactly = 1) { mailbox.send(SENDER_PID, ATOM_FALSE) } } rpcReceiver.close() await .pollDelay(5, TimeUnit.MILLISECONDS) .pollInterval(5, TimeUnit.MILLISECONDS) .timeout(1, TimeUnit.SECONDS) .during(500, TimeUnit.MILLISECONDS) .untilAsserted { verify { mailbox.receive().wasNot(Called) } } excludeRecords { mailbox.receive(1L, TimeUnit.MILLISECONDS) } confirmVerified(mailbox, executor) } @Test fun `no send() on failed handler`() { every { mailbox.receive(1L, TimeUnit.MILLISECONDS) } .returns( Message( SendToRegisteredProcess(SENDER_PID, RECEIVER_MAILBOX), ATOM_TRUE ) ) .andThen(null) every { executor.execute(ATOM_TRUE) } .returns( CompletableFuture.failedFuture(IllegalStateException("foo")) ) every { mailbox.send(SENDER_PID, ATOM_FALSE) }.returns(Unit) rpcReceiver.start(mailbox) await .pollDelay(5, TimeUnit.MILLISECONDS) .pollInterval(5, TimeUnit.MILLISECONDS) .timeout(1, TimeUnit.SECONDS) .during(500, TimeUnit.MILLISECONDS) .untilAsserted { verify(atLeast = 1) { mailbox.receive(1L, TimeUnit.MILLISECONDS) } verify(exactly = 1) { executor.execute(ATOM_TRUE) } verify(exactly = 0) { mailbox.send(any<ErlangPid>(), any()) } } excludeRecords { mailbox.receive(1L, TimeUnit.MILLISECONDS) } confirmVerified(mailbox, executor) } @Test fun `no send() on null from handler`() { every { mailbox.receive(1L, TimeUnit.MILLISECONDS) } .returns( Message( SendToRegisteredProcess(SENDER_PID, RECEIVER_MAILBOX), ATOM_TRUE ) ) .andThen(null) every { executor.execute(ATOM_TRUE) } .returns( CompletableFuture.completedFuture(null) ) every { mailbox.send(SENDER_PID, ATOM_FALSE) }.returns(Unit) rpcReceiver.start(mailbox) await .pollDelay(5, TimeUnit.MILLISECONDS) .pollInterval(5, TimeUnit.MILLISECONDS) .timeout(1, TimeUnit.SECONDS) .during(500, TimeUnit.MILLISECONDS) .untilAsserted { verify(atLeast = 1) { mailbox.receive(1L, TimeUnit.MILLISECONDS) } verify(exactly = 1) { executor.execute(ATOM_TRUE) } verify(exactly = 0) { mailbox.send(any<ErlangPid>(), any()) } } excludeRecords { mailbox.receive(1L, TimeUnit.MILLISECONDS) } confirmVerified(mailbox, executor) } }
0
Kotlin
0
0
994745ada93a016cfc22460b82f573d80c7b6250
5,455
kerl
MIT License
age/src/main/java/com/darwin/viola/age/ViolaAgeClassifier.kt
darwinfrancis
348,993,598
false
null
package com.darwin.viola.age import android.content.Context import android.graphics.Bitmap import android.media.FaceDetector import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.launch import kotlinx.coroutines.withContext import java.io.IOException /** * The class ViolaAgeClassifier * * @author <NAME> * @version 1.0 * @since 16 Mar 2021 */ class ViolaAgeClassifier(private val listener: AgeClassificationListener) { private lateinit var classifier: Classifier var isInitialized = false private set private val coroutineScope = CoroutineScope(Dispatchers.IO) fun initialize(context: Context) { if (!isInitialized) { Util.printLog("Initializing Viola age classifier.") val model = Classifier.Model.QUANTIZED_MOBILE_NET val device = Classifier.Device.CPU try { classifier = Classifier.create(context, model, device, 1) isInitialized = true } catch (e: IOException) { val error = "Failed to create age classifier: ${e.javaClass.canonicalName}(${e.message})" Util.printLog(error) listener.onAgeClassificationError(error) } } } fun dispose() { Util.printLog("Disposing age classifier and its resources.") isInitialized = false classifier.close() } @JvmOverloads fun findAgeAsync(faceBitmap: Bitmap, options: AgeOptions = getDefaultAgeOptions()) { Util.debug = options.debug if (isInitialized) { Util.printLog("Processing face bitmap for age classification.") coroutineScope.launch { val resizedBitmap = resize(faceBitmap) val fixedBitmap = Util.forceEvenBitmapSize(resizedBitmap)!! if (!options.preValidateFace || verifyFacePresence(fixedBitmap)) { val results: List<AgeRecognition> = classifier.recognizeImage(resizedBitmap, 0) Util.printLog("Age classification completed, sending back the result.") withContext(Dispatchers.Main) { listener.onAgeClassificationResult(results) } } else { withContext(Dispatchers.Main) { listener.onAgeClassificationError("There is no face portraits in the given image.") } } } } else { Util.printLog("Viola age classifier is not initialized.") listener.onAgeClassificationError("Viola age classifier is not initialized.") } } @JvmOverloads @Throws(IllegalStateException::class, IllegalArgumentException::class) fun findAgeSynchronized( faceBitmap: Bitmap, options: AgeOptions = getDefaultAgeOptions() ): List<AgeRecognition> { Util.debug = options.debug if (isInitialized) { Util.printLog("Processing face bitmap in synchronized manner for age classification.") val resizedBitmap = resize(faceBitmap) val fixedBitmap = Util.forceEvenBitmapSize(resizedBitmap)!! if (options.preValidateFace && !verifyFacePresence(fixedBitmap)) { throw IllegalArgumentException("There is no face portraits in the given image.") } return classifier.recognizeImage(resizedBitmap, 0) } else { Util.printLog("Viola age classifier is not initialized. Throwing exception.") throw IllegalStateException("Viola age classifier is not initialized.") } } private fun getDefaultAgeOptions(): AgeOptions { return AgeOptions.Builder() .build() } private fun verifyFacePresence(bitmap: Bitmap): Boolean { val pBitmap: Bitmap = bitmap.copy(Bitmap.Config.RGB_565, true) val faceDetector = FaceDetector(pBitmap.width, pBitmap.height, 1) val faceArray = arrayOfNulls<FaceDetector.Face>(1) val faceCount = faceDetector.findFaces(pBitmap, faceArray) return faceCount != 0 } private fun resize(image: Bitmap): Bitmap { Util.printLog("Re-scaling input bitmap for fast image processing.") val maxWidth = 300 val maxHeight = 400 val width = image.width val height = image.height val ratioBitmap = width.toFloat() / height.toFloat() val ratioMax = maxWidth.toFloat() / maxHeight.toFloat() var finalWidth = maxWidth var finalHeight = maxHeight if (ratioMax > ratioBitmap) { finalWidth = (maxHeight.toFloat() * ratioBitmap).toInt() } else { finalHeight = (maxWidth.toFloat() / ratioBitmap).toInt() } return Bitmap.createScaledBitmap(image, finalWidth, finalHeight, true) } }
0
Kotlin
3
22
1b1c695a748363c68ba8d93301df7c1c2514cf6f
4,857
viola-age
MIT License
app/src/main/java/com/utsman/smm/app/MessageService.kt
utsmannn
215,515,789
false
{"Java": 10879, "Kotlin": 3192}
package com.utsman.smm.app import android.app.Service import android.content.Intent import android.os.IBinder import android.util.Log import android.widget.Toast import com.utsman.smm.Smm class MessageService : Service() { override fun onBind(p0: Intent?): IBinder? { return null } override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int { Smm.subscribe(this, "apa") { senderId, data -> Log.i("aaa", data.toString()) Toast.makeText(this, data.toString(), Toast.LENGTH_SHORT).show() } return START_STICKY } }
0
Java
0
0
cd8b9372e01c13f6bf9284b330a65668ead7d3bb
602
Simple-Messaging-MQTT
Apache License 2.0
sdk/src/main/java/io/wso2/android/api_authenticator/sdk/models/authorize_flow/AuthorizeFlow.kt
Achintha444
731,559,375
false
{"Kotlin": 76634}
package io.wso2.android.api_authenticator.sdk.models.authorize_flow import com.fasterxml.jackson.core.type.TypeReference import com.fasterxml.jackson.databind.JsonNode import io.wso2.android.api_authenticator.sdk.models.autheniticator_type.AuthenticatorType import io.wso2.android.api_authenticator.sdk.util.JsonUtil /** * Authorize flow data class. Which is used to hold the data of an authentication flow. * * @property flowStatus Status of the authentication flow */ abstract class AuthorizeFlow(open val flowStatus: String) { /** * Convert the object to a json string */ override fun toString(): String { return JsonUtil.getJsonString(this) } }
0
Kotlin
0
0
a9c7676bf0a37c790a63c075041d439416aca5d3
686
wso2-android-api-authenticator-sdk
Apache License 2.0
src/main/kotlin/com/msg/gcms/domain/club/exception/ClubNotExitException.kt
GSM-MSG
592,816,374
false
null
package com.msg.gcms.domain.club.exception import com.msg.gcms.global.exception.ErrorCode import com.msg.gcms.global.exception.exceptions.BasicException class ClubNotExitException : BasicException(ErrorCode.NOT_CLUB_EXIT)
10
Kotlin
0
8
d55e8ed3f343acca0c3937cf07b6fcfb8dd30598
223
GCMS-BackEnd
MIT License
core/src/main/kotlin/org/ocpsoft/prettytime/i18n/Resources_km.kt
mverse
172,166,534
false
{"Gradle Kotlin DSL": 4, "Text": 2, "Maven POM": 2, "INI": 1, "Shell": 1, "Ignore List": 1, "Batchfile": 1, "Markdown": 1, "Kotlin": 118, "Java": 1, "Java Properties": 1}
/* * Copyright 2012 <a href="mailto:<EMAIL>"><NAME>, III</a> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.ocpsoft.prettytime.i18n; import java.util.ListResourceBundle; public class Resources_km : ListResourceBundle(){ companion object { private var OBJECTS = arrayOf( arrayOf("CenturyPattern", "%n %u"), arrayOf("CenturyFuturePrefix", ""), arrayOf("CenturyFutureSuffix", " ពីឥឡូវនេះ"), arrayOf("CenturyPastPrefix", ""), arrayOf("CenturyPastSuffix", " មុន"), arrayOf("CenturySingularName", "សតវត្ស"), arrayOf("CenturyPluralName", "សតវត្ស"), arrayOf("DayPattern", "%n %u"), arrayOf("DayFuturePrefix", ""), arrayOf("DayFutureSuffix", " ពីឥឡូវនេះ"), arrayOf("DayPastPrefix", ""), arrayOf("DayPastSuffix", " មុន"), arrayOf("DaySingularName", "ថ្ងៃ"), arrayOf("DayPluralName", "ថ្ងៃ"), arrayOf("DecadePattern", "%n %u"), arrayOf("DecadeFuturePrefix", ""), arrayOf("DecadeFutureSuffix", " ពីឥឡូវនេះ"), arrayOf("DecadePastPrefix", ""), arrayOf("DecadePastSuffix", " មុន"), arrayOf("DecadeSingularName", "ទសវត្សរ៍"), arrayOf("DecadePluralName", "ទសវត្សរ៍"), arrayOf("HourPattern", "%n %u"), arrayOf("HourFuturePrefix", ""), arrayOf("HourFutureSuffix", " ពីឥឡូវនេះ"), arrayOf("HourPastPrefix", ""), arrayOf("HourPastSuffix", " មុន"), arrayOf("HourSingularName", "ម៉ោង"), arrayOf("HourPluralName", "ម៉ោង"), arrayOf("JustNowPattern", "%u"), arrayOf("JustNowFuturePrefix", ""), arrayOf("JustNowFutureSuffix", "បន្តិចតិចនេះ"), arrayOf("JustNowPastPrefix", "មុននេះបន្តិច"), arrayOf("JustNowPastSuffix", ""), arrayOf("JustNowSingularName", ""), arrayOf("JustNowPluralName", ""), arrayOf("MillenniumPattern", "%n %u"), arrayOf("MillenniumFuturePrefix", ""), arrayOf("MillenniumFutureSuffix", " ពីឥឡូវនេះ"), arrayOf("MillenniumPastPrefix", ""), arrayOf("MillenniumPastSuffix", " មុន"), arrayOf("MillenniumSingularName", "សហស្សវត្ស៍"), arrayOf("MillenniumPluralName", "សហស្សវត្ស៍"), arrayOf("MillisecondPattern", "%n %u"), arrayOf("MillisecondFuturePrefix", ""), arrayOf("MillisecondFutureSuffix", " ពីឥឡូវនេះ"), arrayOf("MillisecondPastPrefix", ""), arrayOf("MillisecondPastSuffix", " មុន"), arrayOf("MillisecondSingularName", "មីលីវិនាទី​"), arrayOf("MillisecondPluralName", "មីលីវិនាទី​"), arrayOf("MinutePattern", "%n %u"), arrayOf("MinuteFuturePrefix", ""), arrayOf("MinuteFutureSuffix", " ពីឥឡូវនេះ"), arrayOf("MinutePastPrefix", ""), arrayOf("MinutePastSuffix", " មុន"), arrayOf("MinuteSingularName", "នាទី"), arrayOf("MinutePluralName", "នាទី"), arrayOf("MonthPattern", "%n %u"), arrayOf("MonthFuturePrefix", ""), arrayOf("MonthFutureSuffix", " ពីឥឡូវនេះ"), arrayOf("MonthPastPrefix", ""), arrayOf("MonthPastSuffix", " មុន"), arrayOf("MonthSingularName", "ខែ"), arrayOf("MonthPluralName", "ខែ"), arrayOf("SecondPattern", "%n %u"), arrayOf("SecondFuturePrefix", ""), arrayOf("SecondFutureSuffix", " ពីឥឡូវនេះ"), arrayOf("SecondPastPrefix", ""), arrayOf("SecondPastSuffix", " មុន"), arrayOf("SecondSingularName", "វិនាទី"), arrayOf("SecondPluralName", "វិនាទី"), arrayOf("WeekPattern", "%n %u"), arrayOf("WeekFuturePrefix", ""), arrayOf("WeekFutureSuffix", " ពីឥឡូវនេះ"), arrayOf("WeekPastPrefix", ""), arrayOf("WeekPastSuffix", " មុន"), arrayOf("WeekSingularName", "សប្តាហ៍"), arrayOf("WeekPluralName", "សប្តាហ៍"), arrayOf("YearPattern", "%n %u"), arrayOf("YearFuturePrefix", ""), arrayOf("YearFutureSuffix", " ពីឥឡូវនេះ"), arrayOf("YearPastPrefix", ""), arrayOf("YearPastSuffix", " មុន"), arrayOf("YearSingularName", "ឆ្នាំ"), arrayOf("YearPluralName", "ឆ្នាំ"), arrayOf("AbstractTimeUnitPattern", ""), arrayOf("AbstractTimeUnitFuturePrefix", ""), arrayOf("AbstractTimeUnitFutureSuffix", ""), arrayOf("AbstractTimeUnitPastPrefix", ""), arrayOf("AbstractTimeUnitPastSuffix", ""), arrayOf("AbstractTimeUnitSingularName", ""), arrayOf("AbstractTimeUnitPluralName", "")) } override fun getContents() = OBJECTS }
1
null
1
1
00b006a5a2a8294f6a5aeccc302f85c79bb8879f
5,064
prettytime
Apache License 2.0
src/main/kotlin/g3201_3300/s3235_check_if_the_rectangle_corner_is_reachable/Solution.kt
javadev
190,711,550
false
{"Kotlin": 4870729, "TypeScript": 50437, "Python": 3646, "Shell": 994}
package g3201_3300.s3235_check_if_the_rectangle_corner_is_reachable // #Hard #Array #Math #Depth_First_Search #Breadth_First_Search #Union_Find #Geometry // #2024_08_03_Time_612_ms_(66.67%)_Space_50.5_MB_(88.89%) import kotlin.math.pow import kotlin.math.sqrt class Solution { fun canReachCorner(x: Int, y: Int, circles: Array<IntArray>): Boolean { val n = circles.size val ds = DisjointSet(n + 5) // Special nodes for boundaries val leftBoundary = n + 3 val topBoundary = n val rightBoundary = n + 1 val bottomBoundary = n + 2 var i = 0 for (it in circles) { val xi = it[0] val yi = it[1] val ri = it[2] if (yi - ri >= y || xi - ri >= x) { continue } if (((xi > (x + y) || yi > y) && (xi > x || yi > x + y))) { continue } if (xi <= ri) { ds.dsu(i, leftBoundary) } if (yi <= ri) { ds.dsu(i, topBoundary) } if (x - xi <= ri) { ds.dsu(i, rightBoundary) } if (y - yi <= ri) { ds.dsu(i, bottomBoundary) } i++ } // Union circles that overlap i = 0 while (i < n) { val x1 = circles[i][0] val y1 = circles[i][1] val r1 = circles[i][2] if (y1 - r1 >= y || x1 - r1 >= x) { i++ continue } if (((x1 > (x + y) || y1 > y) && (x1 > x || y1 > x + y))) { i++ continue } for (j in i + 1 until n) { val x2 = circles[j][0] val y2 = circles[j][1] val r2 = circles[j][2] val dist = sqrt( (x1 - x2.toDouble()).pow(2.0) + (y1 - y2.toDouble()).pow(2.0) ) if (dist <= (r1 + r2)) { ds.dsu(i, j) } } i++ } // Check if left is connected to right or top is connected to bottom if (ds.findUpar(leftBoundary) == ds.findUpar(rightBoundary) || ds.findUpar(leftBoundary) == ds.findUpar(topBoundary) ) { return false } return ( ds.findUpar(bottomBoundary) != ds.findUpar(rightBoundary) && ds.findUpar(bottomBoundary) != ds.findUpar(topBoundary) ) } private class DisjointSet(n: Int) { private val parent: IntArray private val size = IntArray(n + 1) init { size.fill(1) parent = IntArray(n + 1) for (i in 0..n) { parent[i] = i } } fun findUpar(u: Int): Int { if (u == parent[u]) { return u } parent[u] = findUpar(parent[u]) return parent[u] } fun dsu(u: Int, v: Int) { val ulpu = findUpar(u) val ulpv = findUpar(v) if (ulpv == ulpu) { return } if (size[ulpu] < size[ulpv]) { parent[ulpu] = ulpv size[ulpv] += size[ulpu] } else { parent[ulpv] = ulpu size[ulpu] += size[ulpv] } } } }
0
Kotlin
20
43
e8b08d4a512f037e40e358b078c0a091e691d88f
3,470
LeetCode-in-Kotlin
MIT License
app/src/main/java/dev/albertus/expensms/ui/components/WideLayout.kt
albertusdev
864,469,705
false
{"Kotlin": 103347}
package dev.albertus.expensms.ui.components import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.runtime.Composable import androidx.compose.ui.Modifier import dev.albertus.expensms.ui.props.LayoutProps @Composable fun WideLayout( modifier: Modifier = Modifier, props: LayoutProps ) { Row(modifier = modifier) { Column(modifier = Modifier.weight(0.4f)) { TransactionCalendar( availableDates = props.groupedTransactions.keys, onDateSelected = { date -> props.viewModel.selectDate(date) }, selectedDate = props.selectedDate, onMonthChanged = props.viewModel::setSelectedMonth, modifier = Modifier.fillMaxWidth(), transactionCounts = props.transactionCounts ) if (props.showMonthlyTotal) { MonthlyTotalSpending( month = props.selectedMonth, totalSpending = props.viewModel.getMonthlyTotalSpending(), isWideLayout = true, isAmountVisible = props.isAmountVisible ) } } GroupedTransactionList( groupedTransactions = props.filteredTransactions, modifier = Modifier.weight(0.6f), isAmountVisible = props.isAmountVisible, onTransactionClick = props.onTransactionClick, deleteMode = props.deleteMode, selectedTransactions = props.selectedTransactions, onTransactionSelect = props.onTransactionSelect ) } }
5
Kotlin
1
8
f13b993dded9342fd89678e9e26e43fa3e390917
1,705
expensms
MIT License
app/src/main/java/kr/yapp/teamplay/domain/entity/teammain/TeamMainItemType.kt
YAPP-16th
235,351,892
false
{"Gradle": 3, "Java Properties": 2, "Shell": 1, "Ignore List": 2, "Batchfile": 1, "Text": 1, "Markdown": 10, "YAML": 1, "Proguard": 1, "Kotlin": 172, "XML": 104, "Java": 1}
package kr.yapp.teamplay.domain.entity.teammain enum class TeamMainItemType { NOTICE, MATCH_RESULT }
2
Kotlin
2
3
2d919222f158fd448b55b6f12b1a6a367fa048d9
106
Team_Android_2_Client
MIT License
services/hanke-service/src/test/kotlin/fi/hel/haitaton/hanke/HankeControllerTest.kt
City-of-Helsinki
300,534,352
false
null
package fi.hel.haitaton.hanke import fi.hel.haitaton.hanke.domain.Hanke import fi.hel.haitaton.hanke.domain.HankeSearch import fi.hel.haitaton.hanke.domain.HankeYhteystieto import fi.hel.haitaton.hanke.geometria.HankeGeometriatService import org.assertj.core.api.Assertions.assertThat import org.assertj.core.api.Assertions.assertThatExceptionOfType import org.junit.jupiter.api.Test import org.junit.jupiter.api.extension.ExtendWith import org.mockito.Mockito import org.mockito.MockitoAnnotations import org.springframework.beans.factory.annotation.Autowired import org.springframework.context.annotation.Bean import org.springframework.context.annotation.Configuration import org.springframework.context.annotation.Import import org.springframework.http.HttpStatus import org.springframework.http.ResponseEntity import org.springframework.test.context.junit.jupiter.SpringExtension import org.springframework.validation.beanvalidation.MethodValidationPostProcessor import java.time.ZonedDateTime import java.time.temporal.ChronoUnit import javax.validation.ConstraintViolationException @ExtendWith(SpringExtension::class) @Import(HankeControllerTest.TestConfiguration::class) class HankeControllerTest { @Configuration class TestConfiguration { // makes validation happen here in unit test as well @Bean fun bean(): MethodValidationPostProcessor = MethodValidationPostProcessor() @Bean fun hankeService(): HankeService = Mockito.mock(HankeService::class.java) @Bean fun hankeGeometriatService(): HankeGeometriatService = Mockito.mock(HankeGeometriatService::class.java) @Bean fun hankeController( hankeService: HankeService, hankeGeometriatService: HankeGeometriatService ): HankeController = HankeController(hankeService, hankeGeometriatService) } private val mockedHankeTunnus = "AFC1234" @Autowired private lateinit var hankeService: HankeService @Autowired private lateinit var hankeController: HankeController @Test fun `test that the getHankebyTunnus returns ok`() { Mockito.`when`(hankeService.loadHanke(mockedHankeTunnus)) .thenReturn( Hanke( 1234, mockedHankeTunnus, true, "Mannerheimintien remontti remonttinen", "Lorem ipsum dolor sit amet...", getDatetimeAlku(), getDatetimeLoppu(), Vaihe.OHJELMOINTI, null, 1, "Risto", getCurrentTimeUTC(), null, null, SaveType.DRAFT ) ) val response: ResponseEntity<Any> = hankeController.getHankeByTunnus(mockedHankeTunnus) assertThat(response.statusCode).isEqualTo(HttpStatus.OK) assertThat(response.body).isNotNull // Some compilation/build-setups apparently do not allow this .isNotEmpty without () assertThat((response.body as Hanke).nimi).isNotEmpty() } @Test fun `test when called without parameters then getHankeList returns ok and two items without geometry`() { val listOfHanke = listOf( Hanke( 1234, mockedHankeTunnus, true, "Mannerheimintien remontti remonttinen", "Lorem ipsum dolor sit amet...", getDatetimeAlku(), getDatetimeLoppu(), Vaihe.OHJELMOINTI, null, 1, "Risto", getCurrentTimeUTC(), null, null, SaveType.DRAFT ), Hanke( 50, "HAME50", true, "Hämeenlinnanväylän uudistus", "Lorem ipsum dolor sit amet...", getDatetimeAlku(), getDatetimeLoppu(), Vaihe.SUUNNITTELU, SuunnitteluVaihe.KATUSUUNNITTELU_TAI_ALUEVARAUS, 1, "Paavo", getCurrentTimeUTC(), null, null, SaveType.SUBMIT ) ) Mockito.`when`(hankeService.loadAllHanke()).thenReturn(listOfHanke) val response: ResponseEntity<Any> = hankeController.getHankeList() // basic checks for getting a response assertThat(response.statusCode).isEqualTo(HttpStatus.OK) assertThat(response.body).isNotNull // If the status is ok, we expect ResponseEntity<List<Hanke>> @Suppress("UNCHECKED_CAST") val responseList = response as ResponseEntity<List<Hanke>> assertThat(responseList.body?.get(0)?.nimi).isEqualTo("Mannerheimintien remontti remonttinen") assertThat(responseList.body?.get(1)?.nimi).isEqualTo("Hämeenlinnanväylän uudistus") assertThat(responseList.body?.get(0)?.geometriat).isNull() assertThat(responseList.body?.get(1)?.geometriat).isNull() } @Test fun `when called with saveType parameter then getHankeList returns ok and two items`() { MockitoAnnotations.initMocks(this) // both hanke with wanted saveType val listOfHanke = listOf( Hanke( 1234, mockedHankeTunnus, true, "Mannerheimintien remontti remonttinen", "Lorem ipsum dolor sit amet...", getDatetimeAlku(), getDatetimeLoppu(), Vaihe.OHJELMOINTI, null, 1, "Risto", getCurrentTimeUTC(), null, null, SaveType.SUBMIT ), Hanke( 50, "HAME50", true, "Hämeenlinnanväylän uudistus", "Lorem ipsum dolor sit amet...", getDatetimeAlku(), getDatetimeLoppu(), Vaihe.SUUNNITTELU, SuunnitteluVaihe.KATUSUUNNITTELU_TAI_ALUEVARAUS, 1, "Paavo", getCurrentTimeUTC(), null, null, SaveType.SUBMIT ) ) val searchCriteria = HankeSearch(saveType = SaveType.SUBMIT) Mockito.`when`(hankeService.loadAllHanke(searchCriteria)).thenReturn(listOfHanke) val response: ResponseEntity<Any> = hankeController.getHankeList(searchCriteria) // basic checks for getting a response assertThat(response.statusCode).isEqualTo(HttpStatus.OK) assertThat(response.body).isNotNull // If the status is ok, we expect ResponseEntity<List<Hanke>> @Suppress("UNCHECKED_CAST") val responseList = response as ResponseEntity<List<Hanke>> assertThat(responseList.body?.get(0)?.nimi).isEqualTo("Mannerheimintien remontti remonttinen") assertThat(responseList.body?.get(1)?.nimi).isEqualTo("Hämeenlinnanväylän uudistus") } @Test fun `test that the updateHanke can be called with hanke data and response will be 200`() { val partialHanke = Hanke( id = 123, hankeTunnus = "id123", nimi = "<NAME>", kuvaus = "lorem ipsum dolor sit amet...", onYKTHanke = false, alkuPvm = getDatetimeAlku(), loppuPvm = getDatetimeLoppu(), vaihe = Vaihe.SUUNNITTELU, suunnitteluVaihe = SuunnitteluVaihe.KATUSUUNNITTELU_TAI_ALUEVARAUS, version = 1, createdBy = "Tiina", createdAt = getCurrentTimeUTC(), modifiedBy = null, modifiedAt = null, saveType = SaveType.DRAFT ) // mock HankeService response Mockito.`when`(hankeService.updateHanke(partialHanke)).thenReturn(partialHanke) // Actual call val response: ResponseEntity<Any> = hankeController.updateHanke(partialHanke, "id123") assertThat(response.statusCode).isEqualTo(HttpStatus.OK) assertThat(response.body).isNotNull // If the status is ok, we expect ResponseEntity<Hanke> @Suppress("UNCHECKED_CAST") val responseHanke = response as ResponseEntity<Hanke> assertThat(responseHanke.body).isNotNull assertThat(responseHanke.body?.nimi).isEqualTo("hankkeen nimi") } @Test fun `test that the updateHanke will give validation errors from invalid hanke data for name`() { val partialHanke = Hanke( id = 0, hankeTunnus = "id123", nimi = "", kuvaus = "", onYKTHanke = false, alkuPvm = null, loppuPvm = null, vaihe = Vaihe.OHJELMOINTI, suunnitteluVaihe = null, version = 1, createdBy = "", createdAt = null, modifiedBy = null, modifiedAt = null, saveType = SaveType.DRAFT ) // mock HankeService response Mockito.`when`(hankeService.updateHanke(partialHanke)).thenReturn(partialHanke) // Actual call assertThatExceptionOfType(ConstraintViolationException::class.java).isThrownBy { hankeController.updateHanke(partialHanke, "id123") }.withMessageContaining("updateHanke.hanke.nimi: " + HankeError.HAI1002.toString()) } // sending of sub types @Test fun `test that create with listOfOmistaja can be sent to controller and is responded with 200`() { val hanke = Hanke( id = null, hankeTunnus = null, nimi = "<NAME>", kuvaus = "lorem ipsum dolor sit amet...", onYKTHanke = false, alkuPvm = getDatetimeAlku(), loppuPvm = getDatetimeLoppu(), vaihe = Vaihe.OHJELMOINTI, suunnitteluVaihe = null, version = 1, createdBy = "Tiina", createdAt = getCurrentTimeUTC(), modifiedBy = null, modifiedAt = null, saveType = SaveType.DRAFT ) hanke.omistajat = arrayListOf( HankeYhteystieto( null, "Pekkanen", "Pekka", "<EMAIL>", "3212312", null, "Kaivuri ja mies", null, null, null, null, null ) ) val mockedHanke = hanke.copy() mockedHanke.omistajat = mutableListOf(hanke.omistajat[0]) mockedHanke.id = 12 mockedHanke.hankeTunnus = "JOKU12" mockedHanke.omistajat[0].id = 1 // mock HankeService response Mockito.`when`(hankeService.createHanke(hanke)).thenReturn(mockedHanke) // Actual call val response: ResponseEntity<Any> = hankeController.createHanke(hanke) assertThat(response.statusCode).isEqualTo(HttpStatus.OK) assertThat(response.body).isNotNull // If the status is ok, we expect ResponseEntity<Hanke> @Suppress("UNCHECKED_CAST") val responseHanke = response as ResponseEntity<Hanke> assertThat(responseHanke.body).isNotNull assertThat(responseHanke.body?.id).isEqualTo(12) assertThat(responseHanke.body?.hankeTunnus).isEqualTo("JOKU12") assertThat(responseHanke.body?.nimi).isEqualTo("hankkeen nimi") assertThat(responseHanke.body?.omistajat).isNotNull assertThat(responseHanke.body?.omistajat).hasSize(1) assertThat(responseHanke.body?.omistajat!![0].id).isEqualTo(1) assertThat(responseHanke.body?.omistajat!![0].sukunimi).isEqualTo("Pekkanen") } @Test fun `test that the updateHanke will give validation errors from null enum values`() { val partialHanke = Hanke( id = 0, hankeTunnus = "id123", nimi = "", kuvaus = "", onYKTHanke = false, alkuPvm = null, loppuPvm = null, vaihe = null, suunnitteluVaihe = null, version = 1, createdBy = "", createdAt = null, modifiedBy = null, modifiedAt = null, saveType = null ) // mock HankeService response Mockito.`when`(hankeService.updateHanke(partialHanke)).thenReturn(partialHanke) // Actual call assertThatExceptionOfType(ConstraintViolationException::class.java).isThrownBy { hankeController.updateHanke(partialHanke, "id123") }.withMessageContaining("updateHanke.hanke.vaihe: " + HankeError.HAI1002.toString()) .withMessageContaining("updateHanke.hanke.saveType: " + HankeError.HAI1002.toString()) } private fun getDatetimeAlku(): ZonedDateTime { val year = getCurrentTimeUTC().year + 1 return ZonedDateTime.of(year, 2, 20, 23, 45, 56, 0, TZ_UTC) .truncatedTo(ChronoUnit.MILLIS) } private fun getDatetimeLoppu(): ZonedDateTime { val year = getCurrentTimeUTC().year + 1 return ZonedDateTime.of(year, 2, 21, 0, 12, 34, 0, TZ_UTC) .truncatedTo(ChronoUnit.MILLIS) } }
1
Kotlin
4
1
89ac42586cfb1355f79b09062ba54736a4a6adfd
13,442
haitaton-backend
MIT License
app/src/main/java/com/shevelev/my_footprints_remastered/ui/shared/mvvm/view_model/single_live_data/SingleLiveData.kt
AlShevelev
283,178,554
false
null
package com.shevelev.my_footprints_remastered.ui.shared.mvvm.view_model.single_live_data import androidx.annotation.MainThread import androidx.lifecycle.LifecycleOwner import androidx.lifecycle.Observer /** * A lifecycle-aware observable that sends only new updates after subscription, used for events like * navigation and Snackbar messages. * * It's a classic implementation of such behaviour * * @note from here: https://github.com/googlesamples/android-architecture/blob/dev-todo-mvvm-live/todoapp/app/src/main/java/com/example/android/architecture/blueprints/todoapp/SingleLiveEvent.java */ open class SingleLiveData<T> : SingleLiveDataBase<T>() { @MainThread override fun observe(owner: LifecycleOwner, observer: Observer<in T>) { val wrapper = ObserverWrapper(observer) observers.add(wrapper) super.observe(owner, wrapper) } }
0
Kotlin
0
1
6894f98fb439f30ef7a9988043ace059b844c81b
878
MyFootprints_remastered
Apache License 2.0
android/app/src/main/kotlin/nl/viter/glider/MainActivity.kt
Mosc
292,088,887
false
{"Dart": 460061, "Ruby": 2730, "Swift": 2280, "Kotlin": 116, "Objective-C": 38}
package nl.viter.glider import io.flutter.embedding.android.FlutterActivity class MainActivity: FlutterActivity()
33
Dart
20
502
035589e20c6a45a2f1c55095d115e24c4e552218
116
Glider
MIT License
domain/src/main/java/jp/cordea/drops/domain/repository/UserRepository.kt
CORDEA
296,563,404
false
null
package jp.cordea.drops.domain.repository import jp.cordea.drops.domain.AuthenticationCode import jp.cordea.drops.domain.EmailAddress import jp.cordea.drops.domain.User import kotlinx.coroutines.flow.Flow interface UserRepository { fun isUserExists(emailAddress: EmailAddress): Flow<Boolean> fun login(emailAddress: EmailAddress, code: AuthenticationCode): Flow<User> fun signUp(emailAddress: EmailAddress, code: AuthenticationCode): Flow<User> fun find(): Flow<User> }
0
Kotlin
0
0
d6497dae23f832c11b9b4988ec2e3d0909ccf63a
488
drops.android
Apache License 2.0
app/src/main/kotlin/by/anegin/vkdiscover/core/model/Feed.kt
eugene-kirzhanov
159,214,166
false
{"Kotlin": 72538}
package by.anegin.vkdiscover.core.model class Feed( val posts: List<Post>, val nextFrom: String? )
0
Kotlin
0
0
0b7ad65c5e54eefc00673d6fb0171e22bddf0b09
104
vk-mobile-challenge-18
MIT License
src/main/kotlin/no/nav/pdfgen/application/metrics/MetricRegister.kt
navikt
137,488,647
false
{"Kotlin": 83896, "Handlebars": 29296, "HTML": 623, "Dockerfile": 324}
package no.nav.pdfgen.application.metrics import io.prometheus.client.Histogram const val METRICS_NS = "pdfgen" val HTTP_HISTOGRAM: Histogram = Histogram.Builder() .namespace(METRICS_NS) .labelNames("path") .name("requests_duration_seconds") .help("http requests durations for incoming requests in seconds") .register()
0
Kotlin
7
17
0a25516d42f03ab0e770292cae860e040b41c411
367
pdfgen
MIT License
app/src/main/java/com/roshastudio/roshastu/utils/OnDebouncedClickListener.kt
sepandd97
345,416,807
false
null
package com.roshastudio.roshastu.utils import android.view.View import androidx.core.view.postDelayed class OnDebouncedClickListener(private val delayInMilliSeconds: Long, val action: () -> Unit) : View.OnClickListener { var enable = true override fun onClick(view: View?) { if (enable) { enable = false view?.postDelayed(delayInMilliSeconds) { enable = true } action() } } } fun View.setOnDebouncedClickListener(delayInMilliSeconds: Long , action: () -> Unit) { val onDebouncedClickListener = OnDebouncedClickListener(delayInMilliSeconds, action) setOnClickListener(onDebouncedClickListener) }
0
Kotlin
0
0
1f840c763e4be909afcb6af98d52b5542de43e09
670
Roshastu
MIT License
app/src/main/java/com/example/androiddevchallenge/Dog.kt
lixw1021
342,214,327
true
{"Kotlin": 21622}
/* * Copyright 2021 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.example.androiddevchallenge import android.os.Parcelable import androidx.annotation.DrawableRes import kotlinx.android.parcel.Parcelize @Parcelize data class Dog( val id: Int, val name: String, val age: Int, val category: GogCategory, val address: String, val introduce: String, @DrawableRes val image: Int ) : Parcelable enum class GogCategory(val breed: String) { Terrier("Terrier"), Basset_Hound("Basset Hound"), Basset_Retriever("Basset Retriever"), Beagle("Beagle"), Cavapoo("Cavapoo"), Finnish_Spitz("Finnish_Spitz") }
0
Kotlin
0
0
1b33f63d3ad34d689d9fc32373538abed51e8545
1,208
android-dev-challenge-compose
Apache License 2.0
Android/PhoneVar-main/app/src/main/java/kr/osam/phonevar/service/CheckPhoneIsOnAlarmReceiver.kt
osamhack2020
334,637,314
true
{"Markdown": 4, "Maven POM": 1, "Ignore List": 5, "Java Server Pages": 1, "XML": 52, "Java": 44, "CSS": 4, "HTML": 2, "JSON": 5, "JavaScript": 9, "SVG": 1, "Java Properties": 2, "Gradle": 5, "Shell": 1, "INI": 5, "Batchfile": 1, "Text": 1, "Proguard": 3, "Kotlin": 100}
package kr.osam.phonevar.service import android.content.BroadcastReceiver import android.content.Context import android.content.Intent import kr.osam.phonevar.Injection import kr.osam.phonevar.data.LogItem class CheckPhoneIsOnAlarmReceiver : BroadcastReceiver() { override fun onReceive(context: Context?, intent: Intent?) { context?.apply { Injection.provideLogRepository(applicationContext).saveLog(LogItem().apply { logType = 1 }) } } }
0
null
1
1
90b72cd7ad62e16d0e8d9b3bc2bcb1cafea3585b
505
WEB_Phonevar_BCTP
MIT License
samples/android/app/src/main/java/com/vickbt/daraja/android/di/AppModule.kt
VictorKabata
571,285,833
false
{"Kotlin": 96040, "Swift": 3785, "Ruby": 2423}
package com.vickbt.daraja.android.di import com.vickbt.darajakmp.Daraja import org.koin.dsl.module val appModule = module { // Provide a single instance of Daraja single { Daraja.Builder() .setConsumerKey("consumer_key") .setConsumerSecret("consumer_secret") .setPassKey("pass_key") .isSandbox() .build() } }
2
Kotlin
4
38
93d36d3bd0dae35abf0656c6dbff9889732e3b41
390
DarajaMultiplatform
Apache License 2.0
src/test/kotlin/strings/PalindromeTest.kt
alexiscrack3
310,484,737
false
null
package strings import org.junit.jupiter.api.Assertions.* import org.junit.jupiter.api.Test class PalindromeTest { @Test fun `text should be a palindrome when text is equals to 'a'`() { val input = "a" val testObject = Palindrome() val output = testObject.isPalindrome(input) assertTrue(output) } @Test fun `text should be a palindrome when text is equals to 'aba'`() { val input = "aba" val testObject = Palindrome() val output = testObject.isPalindrome(input) assertTrue(output) } @Test fun `text should be a palindrome when text is equals to 'abba'`() { val input = "abba" val testObject = Palindrome() val output = testObject.isPalindrome(input) assertTrue(output) } @Test fun `text should be a palindrome when text is equals to 'ababa'`() { val input = "ababa" val testObject = Palindrome() val output = testObject.isPalindrome(input) assertTrue(output) } @Test fun `text should be a palindrome when text is equals to 'civic'`() { val input = "civic" val testObject = Palindrome() val output = testObject.isPalindrome(input) assertTrue(output) } @Test fun `text should be a palindrome when text is equals to 'level'`() { val input = "level" val testObject = Palindrome() val output = testObject.isPalindrome(input) assertTrue(output) } @Test fun `text should not be a palindrome when text is equals to 'abaa'`() { val input = "abaa" val testObject = Palindrome() val output = testObject.isPalindrome(input) assertFalse(output) } @Test fun `text should not be a palindrome when text is equals to 'ababb'`() { val input = "ababb" val testObject = Palindrome() val output = testObject.isPalindrome(input) assertFalse(output) } @Test fun `permutation of a text should be a palindrome when text is equals to 'Tact Coa'`() { val input = "taco cat" // original word: Tact Coat val testObject = Palindrome() val output = testObject.isPalindromePermutation(input) assertTrue(output) } @Test fun `result should contain all possible palindromic partitions when text is equals to 'nitin'`() { val input = "nitin" val testObject = Palindrome() val expected = listOf( "n i t i n", "n iti n", "nitin" ) val components = mutableListOf<String>() testObject.getPalindromicPartitions(components, input, "", 0) assertEquals(components, expected) } @Test fun `result should contain all possible palindromic partitions when text is equals to 'geeks'`() { val input = "geeks" val testObject = Palindrome() val expected = listOf( "g e e k s", "g ee k s" ) val partitions = mutableListOf<String>() testObject.getPalindromicPartitions(partitions, input, "", 0) assertEquals(partitions, expected) } @Test fun `result should contain all possible palindromic partitions when text is equals to 'abaaba'`() { val input = "abaaba" val testObject = Palindrome() val expected = listOf( "a b a a b a", "a b a aba", "a b aa b a", "a baab a", "aba a b a", "aba aba", "abaaba" ) val partitions = mutableListOf<String>() testObject.getPalindromicPartitions(partitions, input, "", 0) assertEquals(partitions, expected) } }
0
Kotlin
0
0
a2019868ece9ee319d08a150466304bfa41a8ad3
3,770
algorithms-kotlin
MIT License
frontend/android-feedme-app/app/src/main/java/com/mobilesystems/feedme/data/datasource/ShoppingListDataSource.kt
JaninaMattes
523,417,679
false
null
package com.mobilesystems.feedme.data.datasource import com.mobilesystems.feedme.common.networkresult.Resource import com.mobilesystems.feedme.data.request.ProductRequest import com.mobilesystems.feedme.data.request.ShoppingListProductIDRequest import com.mobilesystems.feedme.data.request.ShoppingListRequest import com.mobilesystems.feedme.data.response.ProductIdResponse import com.mobilesystems.feedme.data.response.ShoppingListResponse interface ShoppingListDataSource{ suspend fun loadAllProductsInCurrentShoppingList(userId: Int): Resource<ShoppingListResponse> suspend fun loadAllProductsInOldShoppingList(userId: Int): Resource<ShoppingListResponse> suspend fun updateCurrentShoppingList(request: ShoppingListRequest): Resource<Int> suspend fun updateOldShoppingList(request: ShoppingListRequest): Resource<Int> suspend fun createProductToCurrentShoppingList(request: ProductRequest): Resource<ProductIdResponse> suspend fun addProductToCurrentShoppingList(request: ShoppingListProductIDRequest): Resource<Int> suspend fun addProductToOldShoppingList(request: ShoppingListProductIDRequest): Resource<Int> suspend fun removeProductFromCurrentShoppingList(request: ShoppingListProductIDRequest): Resource<Int> suspend fun removeProductFromOldShoppingList(request: ShoppingListProductIDRequest): Resource<Int> suspend fun updateSingleProductOnCurrentShoppingList(request: ProductRequest): Resource<Int> suspend fun updateSingleProductOnOldShoppingList(request: ProductRequest): Resource<Int> // suspend fun loadSuggestedProductsForShoppingList(): Response<List<Product>>? // Future feature }
1
Kotlin
0
2
3913a24db0ee341b30be864882c14d91cd24f535
1,659
fudge-android-springboot
MIT License
app/src/main/java/com/dafian/android/submissionfootballclub/BaseApplication.kt
mohamad-rizki
154,784,555
false
null
package com.dafian.android.submissionfootballclub import android.app.Application import timber.log.Timber class BaseApplication : Application() { override fun onCreate() { super.onCreate() Timber.plant(Timber.DebugTree()) } }
0
Kotlin
0
0
30f62c7230f6c24b730846d98bbe0b5379b7e11d
253
mrd-submission-1-football-club
MIT License
src/main/kotlin/com/roguepnz/memeagg/source/reddit/RedditException.kt
roguepnz
230,665,605
false
null
package com.roguepnz.memeagg.source.reddit import java.lang.Exception class RedditException(message: String) : Exception(message)
0
Kotlin
2
8
9269b6e4f11505ddb37c560dbdb189f334a853d4
131
meme-aggregator
Apache License 2.0
meta-lottie-plugin/src/main/java/com/stash/metalottie/plugin/tasks/generator/model/theme/ThemeMapper.kt
stash-oss
352,851,614
false
null
package com.stash.metalottie.plugin.tasks.generator.model.theme interface ThemeMapper { /** * Retrieve theme token from hex color value * * @param property value property type (STROKE_COLOR, FILL_COLOR) * @param colorValue encoded property color value from lottie file * @return theme token if match is found or null if no theme mapping found */ fun getThemeToken(property: String, colorValue: String): String? }
0
Kotlin
0
5
e234d18b978cbbe68afc78fe9a128429ad7a8ff8
454
meta-lottie-android
Apache License 2.0
app/src/main/java/io/stanwood/bitrise/ui/login/ui/LoginFragment.kt
stanwood
118,904,821
false
null
/* * Copyright (c) 2018 <NAME> * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package io.stanwood.bitrise.ui.login.ui import android.os.Bundle import androidx.fragment.app.Fragment import android.view.LayoutInflater import android.view.ViewGroup import io.stanwood.bitrise.databinding.FragmentLoginBinding import io.stanwood.bitrise.ui.login.vm.LoginViewModel import org.koin.android.ext.android.inject class LoginFragment : Fragment() { private val viewModel: LoginViewModel by inject() override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?) = FragmentLoginBinding.inflate(inflater, container, false).apply { lifecycle.addObserver(viewModel) vm = viewModel }.root }
3
Kotlin
12
66
19875303cb348a050d5f3928d0894b3b182ef8fa
1,817
Bitrise_Android
MIT License
dsl/src/main/kotlin/com/faendir/awscdkkt/generated/services/timestream/ScheduleConfigurationPropertyDsl.kt
F43nd1r
643,016,506
false
null
package com.faendir.awscdkkt.generated.services.timestream import com.faendir.awscdkkt.AwsCdkDsl import javax.`annotation`.Generated import kotlin.Unit import software.amazon.awscdk.services.timestream.CfnScheduledQuery @Generated public fun buildScheduleConfigurationProperty(initializer: @AwsCdkDsl CfnScheduledQuery.ScheduleConfigurationProperty.Builder.() -> Unit): CfnScheduledQuery.ScheduleConfigurationProperty = CfnScheduledQuery.ScheduleConfigurationProperty.Builder().apply(initializer).build()
1
Kotlin
0
0
a1cf8fbfdfef9550b3936de2f864543edb76348b
519
aws-cdk-kt
Apache License 2.0
backend/src/routes/Routes.kt
sergiocasero
216,584,987
false
null
package com.sergiocasero.routes import com.sergiocasero.commit.common.result.Either import com.sergiocasero.commit.common.result.Error import com.sergiocasero.db.H2LocalDataSource import com.sergiocasero.remote.KtorRemoteDataSource import com.sergiocasero.repository.CommitBackendRepository import io.ktor.application.Application import io.ktor.application.ApplicationCall import io.ktor.http.HttpStatusCode import io.ktor.response.respond fun Application.routes() { val repository = CommitBackendRepository(local = H2LocalDataSource(), remote = KtorRemoteDataSource()) day(repository) track(repository) slot(repository) update(repository) } suspend fun <R : Any> ApplicationCall.execute(either: Either<Error, R>) { when (either) { is Either.Left -> { val statusCode = when (either.error) { Error.NoInternet -> HttpStatusCode(500, "Server error") Error.NotFound -> HttpStatusCode.NotFound Error.InvalidCredentials -> HttpStatusCode.Unauthorized Error.Default -> HttpStatusCode(500, "Server error") } respond(statusCode) } is Either.Right -> respond(either.success) } }
0
Kotlin
0
7
3c2935343fa25e97a4067b6763b0c9d86e9fd3fc
1,224
commit-mpp
Apache License 2.0
kotlin-antd/antd-samples/src/main/kotlin/samples/input/AllowClear.kt
oxiadenine
206,398,615
false
{"Kotlin": 1619835, "HTML": 1515}
package samples.input import antd.ChangeEventHandler import antd.input.input import org.w3c.dom.HTMLInputElement import react.RBuilder import styled.css import styled.styledDiv private val handleChange: ChangeEventHandler<HTMLInputElement> = { console.log(it) } fun RBuilder.allowClear() { styledDiv { css { +InputStyles.allowClear } input { attrs { placeholder = "Input with clear icon" allowClear = true onChange = handleChange } } } }
1
Kotlin
8
50
e0017a108b36025630c354c7663256347e867251
549
kotlin-js-wrappers
Apache License 2.0
api/src/main/kotlin/com/mattmx/ktgui/conversation/refactor/steps/RegExpConversationStep.kt
Matt-MX
530,062,987
false
{"Kotlin": 255573, "Java": 8369}
package com.mattmx.ktgui.conversation.refactor.steps import org.bukkit.conversations.Conversable import java.util.* class RegExpConversationStep<C : Conversable> : StringConversationStep<C>() { lateinit var regex: Regex override fun validate(input: String?): Optional<String> { if (input == null) return Optional.empty() return if (::regex.isInitialized) { if (regex.matches(input)) Optional.of(input) else Optional.empty() } else Optional.empty() } }
3
Kotlin
3
24
fdc34fce5eeb41f177f890040a58d6c174168434
504
KtPaperGui
Apache License 2.0
MyEcMall-K/App/src/main/java/cn/nieking/myecmallk/ui/fragment/MeFragment.kt
NieQing
132,399,328
false
{"Kotlin": 241813, "Java": 7791}
package cn.nieking.myecmallk.ui.fragment import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import cn.nieking.baselibrary.ext.loadUrl import cn.nieking.baselibrary.ext.onClick import cn.nieking.baselibrary.ui.fragment.BaseFragment import cn.nieking.baselibrary.utils.AppPrefsUtils import cn.nieking.myecmallk.R import cn.nieking.myecmallk.ui.activity.SettingActivity import cn.nieking.ordercenter.common.OrderConstant import cn.nieking.ordercenter.common.OrderStatus import cn.nieking.ordercenter.ui.activity.OrderActivity import cn.nieking.ordercenter.ui.activity.ShipAddressActivity import cn.nieking.provider.common.ProviderConstant import cn.nieking.provider.common.afterLogin import cn.nieking.provider.common.isLogined import cn.nieking.usercenter.ui.activity.UserInfoActivity import kotlinx.android.synthetic.main.fragment_me.* import org.jetbrains.anko.startActivity import org.jetbrains.anko.toast class MeFragment : BaseFragment(), View.OnClickListener { override fun onCreateView(inflater: LayoutInflater?, container: ViewGroup?, savedInstanceState: Bundle?): View? { super.onCreateView(inflater, container, savedInstanceState) return inflater?.inflate(R.layout.fragment_me, container, false) } override fun onViewCreated(view: View?, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) initView() } override fun onStart() { super.onStart() loadData() } private fun initView() { mUserIconIv.onClick(this) mUserNameTv.onClick(this) mShareTv.onClick(this) mSettingTv.onClick(this) mAddressTv.onClick(this) mAllOrderTv.onClick(this) mWaitPayOrderTv.onClick(this) mWaitConfirmOrderTv.onClick(this) mCompleteOrderTv.onClick(this) } private fun loadData() { if (isLogined()) { val userIcon = AppPrefsUtils.getString(ProviderConstant.KEY_SP_USER_ICON) if (userIcon.isNotEmpty()) { mUserIconIv.loadUrl(userIcon) } mUserNameTv.text = AppPrefsUtils.getString(ProviderConstant.KEY_SP_USER_NAME) } else { mUserIconIv.setImageResource(R.drawable.icon_default_user) mUserNameTv.text = getString(R.string.un_login_text) } } override fun onClick(v: View?) { when (v?.id) { R.id.mUserIconIv, R.id.mUserNameTv -> { afterLogin { startActivity<UserInfoActivity>() } } R.id.mSettingTv -> { startActivity<SettingActivity>() } R.id.mAddressTv -> { afterLogin { startActivity<ShipAddressActivity>() } } R.id.mAllOrderTv -> { afterLogin { startActivity<OrderActivity>() } } R.id.mWaitPayOrderTv -> { startActivity<OrderActivity>(OrderConstant.KEY_ORDER_STATUS to OrderStatus.ORDER_WAIT_PAY) } R.id.mWaitConfirmOrderTv -> { startActivity<OrderActivity>(OrderConstant.KEY_ORDER_STATUS to OrderStatus.ORDER_WAIT_CONFIRM) } R.id.mCompleteOrderTv -> { startActivity<OrderActivity>(OrderConstant.KEY_ORDER_STATUS to OrderStatus.ORDER_COMPLETED) } R.id.mShareTv -> { toast(R.string.coming_soon_tip) } } } }
0
Kotlin
0
0
07b22622f98c8bfd8b26ea1303d48f6d66cc4b4b
3,536
MyEcMall-K
Apache License 2.0
src/main/kotlin/cc/mycraft/mythic_cookstoves/items/kitchen/OakPestleItem.kt
EpicWork-Little-Mod-Team
512,423,513
false
{"Kotlin": 66347}
package cc.mycraft.mythic_cookstoves.items.kitchen import cc.mycraft.mythic_cookstoves.blocks.ModBlocks import cc.mycraft.mythic_cookstoves.items.ModTab import net.minecraft.world.item.BlockItem class OakPestleItem : BlockItem(ModBlocks.OAK_PESTLE, Properties().tab(ModTab))
0
Kotlin
0
0
620af5cec9204bcf3d6729fac14545e6da480f33
276
MythicCookstoves
Apache License 2.0
app/src/main/java/io/ak1/numpaddemo/MainActivity.kt
akshay2211
115,280,414
false
null
package io.ak1.numpaddemo import android.os.Bundle import androidx.activity.compose.setContent import androidx.appcompat.app.AppCompatActivity import androidx.compose.foundation.Image import androidx.compose.foundation.clickable import androidx.compose.foundation.layout.* import androidx.compose.material.MaterialTheme import androidx.compose.material.Surface import androidx.compose.material.Text import androidx.compose.runtime.Composable import androidx.compose.runtime.collectAsState import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.res.painterResource import androidx.compose.ui.text.font.Font import androidx.compose.ui.text.font.FontFamily import androidx.compose.ui.text.style.TextAlign import androidx.compose.ui.tooling.preview.Preview import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.sp import io.ak1.numpad.BasicConfigs import io.ak1.numpad.NumType import io.ak1.numpad.Numpad import kotlinx.coroutines.flow.MutableStateFlow class MainActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContent { MaterialTheme( content = { Surface(color = MaterialTheme.colors.background) { MainScreen() } } ) } } @Preview @Composable fun MainScreenPreview() { MainScreen() } @Composable fun MainScreen() { var config = MutableStateFlow(BasicConfigs.Config1.getConfig().apply { fontFamily = FontFamily(Font(R.font.quicksand_light)) }) // var testText = MutableStateFlow("") val (text, setText) = remember { mutableStateOf("") } Column(modifier = Modifier.fillMaxSize()) { Box(modifier = Modifier.weight(1f, true)) { Text( text = text,//testText.value, modifier = Modifier .padding(20.dp) .fillMaxWidth() .align(Alignment.Center), textAlign = TextAlign.Center, fontFamily = FontFamily(Font(R.font.satisfy_regular)), fontSize = 30.sp ) Image( modifier = Modifier .clickable { // testText.value += "| " + testText.value config.value = BasicConfigs.Config2 .getConfig() .apply { fontFamily = FontFamily(Font(R.font.satisfy_regular)) } } .padding(20.dp) .align(Alignment.TopEnd), painter = painterResource(R.drawable.ic_settings), contentDescription = "config_icon" ) } Numpad( modifier = Modifier .fillMaxWidth() .height(330.dp), configuration = config.collectAsState().value ) { type, num -> if (type == NumType.NUMBER && text.length < 5) { val txt = text + num setText("$txt") } else if (type == NumType.DELETE && text.isNotEmpty()) { setText(text.substring(0, text.length - 1)) } } } } }
1
Java
19
44
0c35087b7ad3ac853b3ebb44698a1e301d32ca17
3,692
Numpad
Apache License 2.0
app/src/main/java/io/ak1/numpaddemo/MainActivity.kt
akshay2211
115,280,414
false
null
package io.ak1.numpaddemo import android.os.Bundle import androidx.activity.compose.setContent import androidx.appcompat.app.AppCompatActivity import androidx.compose.foundation.Image import androidx.compose.foundation.clickable import androidx.compose.foundation.layout.* import androidx.compose.material.MaterialTheme import androidx.compose.material.Surface import androidx.compose.material.Text import androidx.compose.runtime.Composable import androidx.compose.runtime.collectAsState import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.res.painterResource import androidx.compose.ui.text.font.Font import androidx.compose.ui.text.font.FontFamily import androidx.compose.ui.text.style.TextAlign import androidx.compose.ui.tooling.preview.Preview import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.sp import io.ak1.numpad.BasicConfigs import io.ak1.numpad.NumType import io.ak1.numpad.Numpad import kotlinx.coroutines.flow.MutableStateFlow class MainActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContent { MaterialTheme( content = { Surface(color = MaterialTheme.colors.background) { MainScreen() } } ) } } @Preview @Composable fun MainScreenPreview() { MainScreen() } @Composable fun MainScreen() { var config = MutableStateFlow(BasicConfigs.Config1.getConfig().apply { fontFamily = FontFamily(Font(R.font.quicksand_light)) }) // var testText = MutableStateFlow("") val (text, setText) = remember { mutableStateOf("") } Column(modifier = Modifier.fillMaxSize()) { Box(modifier = Modifier.weight(1f, true)) { Text( text = text,//testText.value, modifier = Modifier .padding(20.dp) .fillMaxWidth() .align(Alignment.Center), textAlign = TextAlign.Center, fontFamily = FontFamily(Font(R.font.satisfy_regular)), fontSize = 30.sp ) Image( modifier = Modifier .clickable { // testText.value += "| " + testText.value config.value = BasicConfigs.Config2 .getConfig() .apply { fontFamily = FontFamily(Font(R.font.satisfy_regular)) } } .padding(20.dp) .align(Alignment.TopEnd), painter = painterResource(R.drawable.ic_settings), contentDescription = "config_icon" ) } Numpad( modifier = Modifier .fillMaxWidth() .height(330.dp), configuration = config.collectAsState().value ) { type, num -> if (type == NumType.NUMBER && text.length < 5) { val txt = text + num setText("$txt") } else if (type == NumType.DELETE && text.isNotEmpty()) { setText(text.substring(0, text.length - 1)) } } } } }
1
Java
19
44
0c35087b7ad3ac853b3ebb44698a1e301d32ca17
3,692
Numpad
Apache License 2.0
upload_sdk/src/main/java/com/fintek/upload_sdk/network/JavaNetCookieJar.kt
ZuiRenA
316,445,923
false
null
package com.fintek.upload_sdk.network import okhttp3.Cookie import okhttp3.CookieJar import okhttp3.HttpUrl import okhttp3.internal.delimiterOffset import okhttp3.internal.trimSubstring import java.io.IOException import java.net.CookieHandler import java.util.* import kotlin.collections.ArrayList /** * Created by ChaoShen on 2020/5/26 */ class JavaNetCookieJar(private val cookieHandler: CookieHandler): CookieJar { override fun loadForRequest(url: HttpUrl): List<Cookie> { val headers = emptyMap<String, List<String>>() val cookieHeaders: Map<String, List<String>> try { cookieHeaders = cookieHandler.get(url.toUri(), headers) } catch (e: IOException) { return emptyList() } var cookies: MutableList<Cookie>? = null cookieHeaders.forEach { (key, value) -> if (("Cookie".equals(key, true) || "Cookie2".equals(key, true)) && value.isNotEmpty()) { value.forEach { header -> if (cookies == null) { cookies = mutableListOf() } cookies?.addAll(decodeHeaderAsJavaNetCookies(url, header)) } } } return if (cookies != null) Collections.unmodifiableList(cookies!!) else emptyList() } override fun saveFromResponse(url: HttpUrl, cookies: List<Cookie>) { val cookieStrings: List<String> = ArrayList<String>(cookies.map { it.toString() }) val multiMap = Collections.singletonMap("Set-Cookie", cookieStrings) try { cookieHandler.put(url.toUri(), multiMap) } catch (e: IOException) { } } private fun decodeHeaderAsJavaNetCookies(url: HttpUrl, header: String): List<Cookie> { val result = arrayListOf<Cookie>() var pos = 0; val limit = header.length; var pairEnd: Int while (pos < limit) { pairEnd = header.delimiterOffset(";,", pos, limit) val equalsSign: Int = header.delimiterOffset('=', pos, pairEnd) val name = header.trimSubstring(pos, equalsSign) if (name.startsWith("$")) { pos = pairEnd + 1 continue } // We have either name=value or just a name. var value = if (equalsSign < pairEnd) header.trimSubstring(equalsSign + 1, pairEnd) else "" // If the value is "quoted", drop the quotes. if (value.startsWith("\"") && value.endsWith("\"")) { value = value.substring(1, value.length - 1) } result.add( Cookie.Builder() .name(name) .value(value) .domain(url.host) .build() ) pos = pairEnd + 1 } return result } }
0
Kotlin
0
0
c6f86baa894d1f0f3e1f987a6de59c7c53e90bdf
2,899
fintek_upload_sdk
MIT License
dogs/src/main/java/com/airbnb/mvrx/dogs/app/EpoxyExtensions.kt
littleGnAl
167,345,526
true
{"Kotlin": 281165, "Java": 1432, "Shell": 363}
package com.airbnb.mvrx.dogs.app import com.airbnb.epoxy.EpoxyController import com.airbnb.epoxy.EpoxyRecyclerView /** * Easily add models to an EpoxyRecyclerView, the same way you would in a buildModels method of EpoxyController. * from https://github.com/airbnb/epoxy/wiki/EpoxyRecyclerView#kotlin-extensions */ fun EpoxyRecyclerView.withModels(buildModelsCallback: EpoxyController.() -> Unit) { setControllerAndBuildModels(object : EpoxyController() { override fun buildModels() { buildModelsCallback() } }) }
1
Kotlin
1
3
7ea6284530a0640f36d12508a669b4f4222902c3
553
MvRx
Apache License 2.0
app/src/main/java/com/cleteci/redsolidaria/ui/activities/main/MainContract.kt
JusticeInternational
250,092,136
false
null
package com.cleteci.redsolidaria.ui.activities.main import com.cleteci.redsolidaria.ui.base.BaseContract class MainContract { interface View: BaseContract.View { fun init() fun showHomeFragment() fun showSearchWithMapFragment() fun showMapFragment() fun showResourcesFragment() fun showSuggestFragment() fun showConfigFragment() fun showProfileFragment() fun showContactFragment() fun showUsersFragment() fun showScanFragment(serviceID: String?, catId: String?, name: String?, isGeneric: Boolean) fun showScanListFragment() fun showResourcesProviderFragment() } interface Presenter: BaseContract.Presenter<View> { fun onDrawerHomeOption() fun onNavUsersOption() fun onNavScanOption() fun onNavResourcesProviderOption() fun onNavSearchOption() fun onNavMapOption() fun onNavResourcesOption() fun onDrawerSuggestOption() fun onDrawerConfigOption() fun onDrawerProfileOption() fun onDrawerContactOption() } }
5
Kotlin
1
1
766168e2c5655f36e0e1898542f8ccb831d7da75
1,142
RedSol-android
MIT License
app/src/main/java/com/monebac/com/ktolingbaic/kotlinbasic/model/CatModel.kt
xuechenbo
303,620,971
false
null
package com.monebac.com.ktolingbaic.kotlinbasic.model import com.monebac.com.utils.LogsUtils class CatModel : CalloutModel(), CalloutInterface { //实现接口属性 override var skilledSports: String = "接口属性:嘤嘤嘤" //实现接口方法 override fun getB() { LogsUtils.e("抓老鼠了") } override fun getCall() { LogsUtils.e("叫~~") } }
1
null
1
1
a2f9e8572c1499e711714c14058ad66ad0941e62
351
KotlinDemo
Apache License 2.0
jdom/src/main/kotlin/org/jonnyzzz/kotlin/xml/bind/jdom/impl/bind/XmlBindImpl.kt
jonnyzzz
48,336,446
false
null
package org.jonnyzzz.kotlin.xml.bind.jdom.impl.bind import org.jdom2.CDATA import org.jdom2.Element import org.jdom2.Text import org.jonnyzzz.kotlin.xml.bind.jdom.impl.JDOMIMPL /** * Created by <EMAIL> */ internal class XmlNameBind : XPropertyImpl<String>(null) { override fun loadImpl(scope: Element?) = scope?.name override fun saveImpl(value: String, scope: Element) { //NOP } } internal class XmlTextBind : XPropertyImpl<String>(null) { override fun loadImpl(scope: Element?) = scope?.text override fun saveImpl(value: String, scope: Element) { scope.setContent(Text(value)) } } internal class XmlCDATABind : XPropertyImpl<String>(null) { override fun loadImpl(scope: Element?) = scope?.text override fun saveImpl(value: String, scope: Element) { scope.setContent(CDATA(value)) } } internal class XmlUnknownBind : XPropertyImpl<Element>(null) { override fun loadImpl(scope: Element?) = scope?.clone() override fun saveImpl(value: Element, scope: Element) { val copy = value.clone() scope.addContent(copy.cloneContent()) copy.attributes?.forEach { scope.setAttribute( it.clone() ) } } } internal class XmlAttributeBind(val attributeName : String) : XPropertyImpl<String>(null) { override fun loadImpl(scope: Element?) = scope?.getAttributeValue(attributeName, null as String?) override fun saveImpl(value: String, scope: Element) { scope.setAttribute(attributeName, value) } } internal class XmlSubBind<T : Any>(val clazz : Class<T>) : XPropertyImpl<T>(null) { override fun loadImpl(scope: Element?): T? = if (scope == null) null else JDOMIMPL.load(scope, clazz) override fun saveImpl(value: T, scope: Element) { JDOMIMPL.save(scope, value) } }
5
Kotlin
7
34
416cbc4ae12aaea77619380fac1c14df531aa0f9
1,725
kotlin.xml.bind
Apache License 2.0
src/main/kotlin/no/nav/familie/ba/sak/kjerne/eøs/valutakurs/VurderingsstrategiForValutakurserRepository.kt
navikt
224,639,942
false
{"Kotlin": 6349064, "Gherkin": 842631, "PLpgSQL": 4478, "Shell": 3094, "Dockerfile": 522}
package no.nav.familie.ba.sak.kjerne.eøs.valutakurs import org.springframework.data.jpa.repository.JpaRepository interface VurderingsstrategiForValutakurserRepository : JpaRepository<VurderingsstrategiForValutakurserDB, Long> { fun findByBehandlingId(behandlingId: Long): VurderingsstrategiForValutakurserDB? }
9
Kotlin
1
9
d5878744bfebd9c358cd0154ab2e0515e238d44b
318
familie-ba-sak
MIT License
src/main/kotlin/dev/castive/javalin_auth/auth/data/model/github/GitHubUser.kt
djcass44
182,171,506
false
null
/* * Copyright 2019 <NAME> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package dev.castive.javalin_auth.auth.data.model.github import com.google.gson.annotations.SerializedName data class GitHubUser( val login: String, // username val id: Int, @SerializedName("avatar_url") val avatarUrl: String, val type: String, // probably always "User" val name: String // display name )
4
Kotlin
0
0
a923eb2c30d96489bd22c273e16beb7f5163281e
936
jmp-auth
Apache License 2.0
app/src/main/java/com/realform/macropaytestpokemon/data/implrepository/userRemoteDataRetrievalImpl/UserDataRetrievalImpl.kt
IvanMedinaH
809,257,969
false
{"Kotlin": 194139}
package com.realform.macropaytestpokemon.data.implrepository.userRemoteDataRetrievalImpl import com.google.firebase.firestore.FirebaseFirestore import com.realform.macropaytestpokemon.data.remote.model.user.UserRemoteDB import com.realform.macropaytestpokemon.domain.repository.login.IUserDataRetrieval class UserDataRetrievalImpl(private val firestore: FirebaseFirestore) : IUserDataRetrieval { override fun getUserById(userId: String, onSuccess: (UserRemoteDB?) -> Unit, onFailure: (Exception) -> Unit) { //referencia a la colección de usuarios en Firestore val usersCollection = firestore.collection("users") //consulta para buscar al usuario por su ID usersCollection.document(userId).get().addOnSuccessListener { firestoreDocument -> if (firestoreDocument != null && firestoreDocument.exists()) { //El documento existe, puedes obtener los datos del usuario val user = firestoreDocument.toObject(UserRemoteDB::class.java) onSuccess(user) } else { //El documento no existe, el usuario no fue encontrado onSuccess(null) } } .addOnFailureListener { exception -> //error al intentar realizar la consulta onFailure(exception) } } }
0
Kotlin
0
0
d6bdc416600f99f80af5264db420929796e109b2
1,391
Pokedex
MIT License
app/src/main/java/br/ifsp/moviedb/ui/activity/navigation/NavigationScreen.kt
pdalbem
844,668,803
false
{"Kotlin": 109217}
package br.ifsp.moviedb.ui.activity.navigation import android.net.Uri import android.os.Bundle import androidx.compose.runtime.Composable import androidx.navigation.NavHostController import androidx.navigation.NavType import androidx.navigation.compose.NavHost import androidx.navigation.compose.composable import androidx.navigation.navArgument import com.google.gson.Gson import br.ifsp.moviedb.model.data.HomeDataModel import br.ifsp.moviedb.ui.fragment.details.DetailsRoute import br.ifsp.moviedb.ui.fragment.home.compose.HomeRoute @Composable fun AppNavHost(navController: NavHostController) { NavHost(navController = navController, startDestination = Navigation.Home.route) { composable( route = Navigation.Home.route, ) { HomeRoute { val model = Uri.encode(Gson().toJson(it)) navController.navigate("${Navigation.Details.route}/$model") } } composable( route = "${Navigation.Details.route}/{model}", arguments = listOf(navArgument("model") { type = ParcelableType() }) ) { backStackEntry -> val post = backStackEntry.arguments?.getParcelable<HomeDataModel>("model") DetailsRoute(passData = post) } } } class ParcelableType : NavType<HomeDataModel>(isNullableAllowed = false) { override fun get(bundle: Bundle, key: String): HomeDataModel? { return bundle.getParcelable(key) } override fun parseValue(value: String): HomeDataModel { return Gson().fromJson(value, HomeDataModel::class.java) } override fun put(bundle: Bundle, key: String, value: HomeDataModel) { bundle.putParcelable(key, value) } }
0
Kotlin
0
0
f30a1f3decafeaf6b4c6789db1febdef41f49289
1,731
movieDB
MIT License
app/src/main/java/com/joshuacerdenia/android/nicefeed/ui/OnBackgroundWorkSettingChanged.kt
kitlith
297,803,241
true
{"Kotlin": 207296}
package com.joshuacerdenia.android.nicefeed.ui interface OnBackgroundWorkSettingChanged { fun onBackgroundWorkSettingChanged(isOn: Boolean) }
0
null
0
0
8a81efe5886b27efbce15b817d2eab9704543550
147
NiceFeed
MIT License
TeamCode/src/main/java/org/firstinspires/ftc/teamcode/opmode/DefaultAuto.kt
bretthat0
536,761,187
false
{"Java": 53276, "Kotlin": 29160}
package org.firstinspires.ftc.teamcode.opmode import org.firstinspires.ftc.teamcode.opmode.base.AutoBase import org.firstinspires.ftc.teamcode.util.* import com.qualcomm.robotcore.eventloop.opmode.Autonomous import org.firstinspires.ftc.teamcode.subsystem.ArmSubsystem import org.firstinspires.ftc.teamcode.subsystem.MecanumDriveSubsystem import org.firstinspires.ftc.teamcode.subsystem.VisionSubsystem @Autonomous(name="Default Auto") open class DefaultAuto: AutoBase() { private lateinit var driveSubsystem: MecanumDriveSubsystem private lateinit var armSubsystem: ArmSubsystem private lateinit var visionSubsystem: VisionSubsystem protected var tagId = 1 protected val tagVisible: Boolean get() = visionSubsystem.visibleTags.isNotEmpty() enum class Direction { FORWARD, BACK, LEFT, RIGHT } override fun onInit() { driveSubsystem = MecanumDriveSubsystem(hardwareMap) armSubsystem = ArmSubsystem(hardwareMap) visionSubsystem = VisionSubsystem(hardwareMap) register(driveSubsystem) //register(armSubsystem) register(visionSubsystem) } override suspend fun onStart() { while (isRunning) { wait(1.0) // Capture ID of visible tag if (tagVisible) { tagId = visionSubsystem.visibleTags[0].id } executeInstructions() wait(1.0) requestOpModeStop() } } protected open suspend fun executeInstructions() { /*drive(Direction.FORWARD, 0.25) positionTurret(60) drive(Direction.FORWARD, 1.0) positionTurret(-60) positionArm(16.0, 5.0) claw(true) positionArm(16.0, 28.0) positionTurret(150) claw(false) positionArm(4.0, 4.0)*/ when (tagId) { 0 -> drive(Direction.LEFT, 1.0) 2 -> drive(Direction.RIGHT, 1.0) } drive(Direction.FORWARD, 1.0) } protected suspend fun drive(direction: Direction, seconds: Double) { driveSubsystem.leftInput = vec2(direction) driveSubsystem.execute() wait(seconds) driveSubsystem.leftInput = Vector2.zero driveSubsystem.execute() } protected suspend fun claw(grabbing: Boolean) { armSubsystem.isGrabbing = grabbing armSubsystem.execute() wait(0.5) } protected suspend fun positionArm(positionX: Double, positionY: Double) { armSubsystem.planePosition = vec2(positionX, positionY) armSubsystem.execute() wait(2.0) } protected suspend fun positionTurret(rotateDegrees: Int) { armSubsystem.rotatePosition = rotateDegrees / 360.0 armSubsystem.execute() wait(2.0) } protected fun vec2(dir: Direction): Vector2 { return when (dir) { Direction.FORWARD -> vec2(0.0, 1.0) Direction.BACK -> vec2(0.0, -1.0) Direction.LEFT -> vec2(-1.0, 0.0) Direction.RIGHT -> vec2(1.0, 0.0) } } }
1
null
1
1
be816f4e3ba56724144d586b4c1ae563cc6e3783
3,077
9357-ftc-powerplay
BSD 3-Clause Clear License
clients/kotlin/generated/src/test/kotlin/org/openapitools/client/models/CatalogProductGroupTest.kt
oapicf
489,369,143
false
{"Markdown": 13009, "YAML": 64, "Text": 6, "Ignore List": 43, "JSON": 688, "Makefile": 2, "JavaScript": 2261, "F#": 1305, "XML": 1120, "Shell": 44, "Batchfile": 10, "Scala": 4677, "INI": 23, "Dockerfile": 14, "Maven POM": 22, "Java": 13384, "Emacs Lisp": 1, "Haskell": 75, "Swift": 551, "Ruby": 1149, "Cabal Config": 2, "OASv3-yaml": 16, "Go": 2224, "Go Checksums": 1, "Go Module": 4, "CMake": 9, "C++": 6688, "TOML": 3, "Rust": 556, "Nim": 541, "Perl": 540, "Microsoft Visual Studio Solution": 2, "C#": 1645, "HTML": 545, "Xojo": 1083, "Gradle": 20, "R": 1079, "JSON with Comments": 8, "QMake": 1, "Kotlin": 3280, "Python": 1, "Crystal": 1060, "ApacheConf": 2, "PHP": 3940, "Gradle Kotlin DSL": 1, "Protocol Buffer": 538, "C": 1598, "Ada": 16, "Objective-C": 1098, "Java Properties": 2, "Erlang": 1097, "PlantUML": 1, "robots.txt": 1, "HTML+ERB": 2, "Lua": 1077, "SQL": 512, "AsciiDoc": 1, "CSS": 3, "PowerShell": 1083, "Elixir": 5, "Apex": 1054, "Visual Basic 6.0": 3, "TeX": 1, "ObjectScript": 1, "OpenEdge ABL": 1, "Option List": 2, "Eiffel": 583, "Gherkin": 1, "Dart": 538, "Groovy": 539, "Elm": 31}
/** * * Please note: * This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). * Do not edit this file manually. * */ @file:Suppress( "ArrayInDataClass", "EnumEntryName", "RemoveRedundantQualifierName", "UnusedImport" ) package org.openapitools.client.models import io.kotlintest.shouldBe import io.kotlintest.specs.ShouldSpec import org.openapitools.client.models.CatalogProductGroup import org.openapitools.client.models.Board import org.openapitools.client.models.EntityStatus class CatalogProductGroupTest : ShouldSpec() { init { // uncomment below to create an instance of CatalogProductGroup //val modelInstance = CatalogProductGroup() // to test the property `id` - ID of the catalog product group. should("test id") { // uncomment below to test the property //modelInstance.id shouldBe ("TODO") } // to test the property `merchantId` - Merchant ID pertaining to the owner of the catalog product group. should("test merchantId") { // uncomment below to test the property //modelInstance.merchantId shouldBe ("TODO") } // to test the property `name` - Name of catalog product group should("test name") { // uncomment below to test the property //modelInstance.name shouldBe ("TODO") } // to test the property `filters` - Object holding a list of filters should("test filters") { // uncomment below to test the property //modelInstance.filters shouldBe ("TODO") } // to test the property `filterV2` - Object holding a list of filters should("test filterV2") { // uncomment below to test the property //modelInstance.filterV2 shouldBe ("TODO") } // to test the property `type` should("test type") { // uncomment below to test the property //modelInstance.type shouldBe ("TODO") } // to test the property `status` should("test status") { // uncomment below to test the property //modelInstance.status shouldBe ("TODO") } // to test the property `feedProfileId` - id of the feed profile belonging to this catalog product group should("test feedProfileId") { // uncomment below to test the property //modelInstance.feedProfileId shouldBe ("TODO") } // to test the property `createdAt` - Unix timestamp in seconds of when catalog product group was created. should("test createdAt") { // uncomment below to test the property //modelInstance.createdAt shouldBe ("TODO") } // to test the property `lastUpdate` - Unix timestamp in seconds of last time catalog product group was updated. should("test lastUpdate") { // uncomment below to test the property //modelInstance.lastUpdate shouldBe ("TODO") } // to test the property `productCount` - Amount of products in the catalog product group should("test productCount") { // uncomment below to test the property //modelInstance.productCount shouldBe ("TODO") } // to test the property `featuredPosition` - index of the featured position of the catalog product group should("test featuredPosition") { // uncomment below to test the property //modelInstance.featuredPosition shouldBe ("TODO") } } }
0
Java
0
2
dcd328f1e62119774fd8ddbb6e4bad6d7878e898
3,610
pinterest-sdk
MIT License
desktop/adapters/src/main/kotlin/com/soyle/stories/character/createArcSection/CreatedCharacterArcSectionReceiver.kt
Soyle-Productions
239,407,827
false
null
package com.soyle.stories.character.createArcSection import com.soyle.stories.usecase.character.arc.section.addCharacterArcSectionToMoralArgument.ArcSectionAddedToCharacterArc interface CreatedCharacterArcSectionReceiver { suspend fun receiveCreatedCharacterArcSection(event: ArcSectionAddedToCharacterArc) }
45
Kotlin
0
9
1a110536865250dcd8d29270d003315062f2b032
316
soyle-stories
Apache License 2.0
Android/Intermediate/Architecture/code/HelloMVVM1/app/src/main/java/com/example/hellomvvm1/viewmodel/BasicViewModel.kt
Ice-House-Engineering
262,230,937
false
null
package com.example.hellomvvm1.viewmodel import androidx.lifecycle.ViewModel import com.example.hellomvvm1.model.Database class BasicViewModel : ViewModel() { fun setCryptocurrencies(newCryptocurrencies : String) { Database.setCryptocurrencies(newCryptocurrencies.toUpperCase()) } fun getCryptocurrencies(): String = Database.getCryptocurrencies() }
2
Kotlin
47
169
ac6ff819a03f8eb01055ebbb2bf08a95f011e09b
375
academy-curriculum
Creative Commons Attribution 4.0 International
restdocs-api-spec/src/test/kotlin/com/keecon/restdocs/apispec/ResourceSnippetTest.kt
keecon
462,124,358
false
{"Kotlin": 346988, "Groovy": 9528, "Java": 6458}
package com.keecon.restdocs.apispec import com.jayway.jsonpath.DocumentContext import com.jayway.jsonpath.JsonPath import com.keecon.restdocs.apispec.ResourceDocumentation.parameterWithName import com.keecon.restdocs.apispec.ResourceDocumentation.partWithName import com.keecon.restdocs.apispec.ResourceDocumentation.resource import org.assertj.core.api.BDDAssertions.then import org.assertj.core.api.BDDAssertions.thenThrownBy import org.junit.jupiter.api.BeforeEach import org.junit.jupiter.api.Test import org.junit.jupiter.api.extension.ExtendWith import org.junitpioneer.jupiter.TempDirectory import org.springframework.http.HttpHeaders.AUTHORIZATION import org.springframework.http.HttpHeaders.CONTENT_TYPE import org.springframework.http.HttpStatus import org.springframework.http.HttpStatus.OK import org.springframework.http.MediaType.APPLICATION_FORM_URLENCODED_VALUE import org.springframework.http.MediaType.APPLICATION_JSON_VALUE import org.springframework.http.MediaType.MULTIPART_FORM_DATA_VALUE import org.springframework.http.MediaType.TEXT_PLAIN_VALUE import org.springframework.restdocs.generate.RestDocumentationGenerator.ATTRIBUTE_NAME_URL_TEMPLATE import org.springframework.restdocs.headers.HeaderDocumentation import org.springframework.restdocs.operation.Operation import org.springframework.restdocs.payload.JsonFieldType import org.springframework.restdocs.payload.PayloadDocumentation.fieldWithPath import org.springframework.restdocs.snippet.Attributes import java.io.File import java.io.IOException import java.nio.file.Path @ExtendWith(TempDirectory::class) class ResourceSnippetTest { lateinit var operation: Operation private val parametersBuilder = ResourceSnippetParametersBuilder() private val operationName: String get() = OPERATION_NAME private lateinit var rootOutputDirectory: File private lateinit var resourceSnippetJson: DocumentContext @BeforeEach fun init(@TempDirectory.TempDir tempDir: Path) { rootOutputDirectory = tempDir.toFile() } @Test fun should_generate_resource_snippet_for_operation_with_request_body() { givenOperationWithRequestBody() givenRequestFieldDescriptors() whenResourceSnippetInvoked() thenSnippetFileExists() thenSnippetFileHasCommonRequestAttributes() thenResourceSnippetContainsCommonRequestAttributes() then(resourceSnippetJson.read<Int>("response.status")).isEqualTo(OK.value()) then(resourceSnippetJson.read<String>("response.example")).isNull() then(resourceSnippetJson.read<List<String>>("tags")).isEqualTo(listOf("some")) } @Test fun should_generate_resource_model_for_operation_with_query_parameter_and_response_body() { givenOperationWithRequestAndResponseBody() givenRequestFieldDescriptors() givenRequestSchemaName() givenResponseFieldDescriptors() givenResponseSchemaName() givenPathParameterDescriptors() givenQueryParameterDescriptors() givenRequestAndResponseHeaderDescriptors() givenTag() whenResourceSnippetInvoked() thenSnippetFileExists() thenSnippetFileHasCommonRequestAttributes() thenResourceSnippetContainsCommonRequestAttributes() then(resourceSnippetJson.read<List<*>>("tags")).hasSize(3) then(resourceSnippetJson.read<String>("request.schema.name")).isNotEmpty then(resourceSnippetJson.read<List<*>>("request.headers")).hasSize(1) then(resourceSnippetJson.read<String>("request.headers[0].name")).isNotEmpty then(resourceSnippetJson.read<String>("request.headers[0].description")).isNotEmpty then(resourceSnippetJson.read<String>("request.headers[0].type")).isNotEmpty then(resourceSnippetJson.read<String>("request.headers[0].default")).isNotEmpty then(resourceSnippetJson.read<Boolean>("request.headers[0].optional")).isFalse then(resourceSnippetJson.read<String>("request.headers[0].example")).isNotEmpty then(resourceSnippetJson.read<List<*>>("request.pathParameters")).hasSize(1) then(resourceSnippetJson.read<String>("request.pathParameters[0].name")).isNotEmpty then(resourceSnippetJson.read<String>("request.pathParameters[0].description")).isNotEmpty then(resourceSnippetJson.read<String>("request.pathParameters[0].type")).isNotEmpty then(resourceSnippetJson.read<String>("request.pathParameters[0].default")).isNull() then(resourceSnippetJson.read<Boolean>("request.pathParameters[0].optional")).isFalse then(resourceSnippetJson.read<Boolean>("request.pathParameters[0].ignored")).isFalse then(resourceSnippetJson.read<List<*>>("request.queryParameters")).hasSize(1) then(resourceSnippetJson.read<String>("request.queryParameters[0].name")).isNotEmpty then(resourceSnippetJson.read<String>("request.queryParameters[0].description")).isNotEmpty then(resourceSnippetJson.read<String>("request.queryParameters[0].type")).isNotEmpty then(resourceSnippetJson.read<String>("request.queryParameters[0].default")).isNotEmpty then(resourceSnippetJson.read<Boolean>("request.queryParameters[0].optional")).isFalse then(resourceSnippetJson.read<Boolean>("request.queryParameters[0].ignored")).isFalse then(resourceSnippetJson.read<List<String>>("request.securityRequirements.requiredScopes")) .containsExactly("scope1", "scope2") then(resourceSnippetJson.read<String>("request.securityRequirements.type")).isEqualTo("OAUTH2") then(resourceSnippetJson.read<String>("request.example")).isNotEmpty then(resourceSnippetJson.read<Int>("response.status")).isEqualTo(HttpStatus.CREATED.value()) then(resourceSnippetJson.read<String>("response.example")).isNotEmpty then(resourceSnippetJson.read<String>("response.schema.name")).isNotEmpty then(resourceSnippetJson.read<List<*>>("response.headers")).hasSize(1) then(resourceSnippetJson.read<String>("response.headers[0].name")).isNotEmpty then(resourceSnippetJson.read<String>("response.headers[0].description")).isNotEmpty then(resourceSnippetJson.read<String>("response.headers[0].type")).isNotEmpty then(resourceSnippetJson.read<String>("response.headers[0].default")).isNull() then(resourceSnippetJson.read<Boolean>("response.headers[0].optional")).isFalse then(resourceSnippetJson.read<String>("response.headers[0].example")).isNotEmpty } @Test fun should_generate_resource_model_for_operation_with_form_parameter_and_response_body() { givenOperationWithRequestAndResponseBody( requestContentType = APPLICATION_FORM_URLENCODED_VALUE, requestContent = "test-param=1" ) givenRequestSchemaName() givenResponseFieldDescriptors() givenResponseSchemaName() givenPathParameterDescriptors() givenFormParameterDescriptors() givenRequestAndResponseHeaderDescriptors() givenTag() whenResourceSnippetInvoked() thenSnippetFileExists() thenSnippetFileHasCommonRequestAttributes() then(resourceSnippetJson.read<String>("request.contentType")).isEqualTo(APPLICATION_FORM_URLENCODED_VALUE) then(resourceSnippetJson.read<String>("request.example")).isEqualTo(operation.request.contentAsString) then(resourceSnippetJson.read<List<*>>("tags")).hasSize(3) then(resourceSnippetJson.read<String>("request.schema.name")).isNotEmpty then(resourceSnippetJson.read<List<*>>("request.headers")).hasSize(1) then(resourceSnippetJson.read<String>("request.headers[0].name")).isNotEmpty then(resourceSnippetJson.read<String>("request.headers[0].description")).isNotEmpty then(resourceSnippetJson.read<String>("request.headers[0].type")).isNotEmpty then(resourceSnippetJson.read<String>("request.headers[0].default")).isNotEmpty then(resourceSnippetJson.read<Boolean>("request.headers[0].optional")).isFalse then(resourceSnippetJson.read<String>("request.headers[0].example")).isNotEmpty then(resourceSnippetJson.read<List<*>>("request.pathParameters")).hasSize(1) then(resourceSnippetJson.read<String>("request.pathParameters[0].name")).isNotEmpty then(resourceSnippetJson.read<String>("request.pathParameters[0].description")).isNotEmpty then(resourceSnippetJson.read<String>("request.pathParameters[0].type")).isNotEmpty then(resourceSnippetJson.read<String>("request.pathParameters[0].default")).isNull() then(resourceSnippetJson.read<Boolean>("request.pathParameters[0].optional")).isFalse then(resourceSnippetJson.read<Boolean>("request.pathParameters[0].ignored")).isFalse then(resourceSnippetJson.read<List<*>>("request.formParameters")).hasSize(1) then(resourceSnippetJson.read<String>("request.formParameters[0].name")).isNotEmpty then(resourceSnippetJson.read<String>("request.formParameters[0].description")).isNotEmpty then(resourceSnippetJson.read<String>("request.formParameters[0].type")).isNotEmpty then(resourceSnippetJson.read<Boolean>("request.formParameters[0].optional")).isFalse then(resourceSnippetJson.read<Boolean>("request.formParameters[0].ignored")).isFalse then(resourceSnippetJson.read<List<String>>("request.securityRequirements.requiredScopes")) .containsExactly("scope1", "scope2") then(resourceSnippetJson.read<String>("request.securityRequirements.type")).isEqualTo("OAUTH2") then(resourceSnippetJson.read<String>("request.example")).isNotEmpty then(resourceSnippetJson.read<Int>("response.status")).isEqualTo(HttpStatus.CREATED.value()) then(resourceSnippetJson.read<String>("response.example")).isNotEmpty then(resourceSnippetJson.read<String>("response.schema.name")).isNotEmpty then(resourceSnippetJson.read<List<*>>("response.headers")).hasSize(1) then(resourceSnippetJson.read<String>("response.headers[0].name")).isNotEmpty then(resourceSnippetJson.read<String>("response.headers[0].description")).isNotEmpty then(resourceSnippetJson.read<String>("response.headers[0].type")).isNotEmpty then(resourceSnippetJson.read<String>("response.headers[0].default")).isNull() then(resourceSnippetJson.read<Boolean>("response.headers[0].optional")).isFalse then(resourceSnippetJson.read<String>("response.headers[0].example")).isNotEmpty } @Test fun should_generate_resource_model_for_operation_with_request_part_and_response_body() { givenOperationWithRequestPartAndResponseBody() givenRequestSchemaName() givenResponseFieldDescriptors() givenResponseSchemaName() givenPathParameterDescriptors() givenRequestPartDescriptors() givenRequestAndResponseHeaderDescriptors() givenTag() whenResourceSnippetInvoked() thenSnippetFileExists() thenSnippetFileHasCommonRequestAttributes() then(resourceSnippetJson.read<String>("request.contentType")).isEqualTo(MULTIPART_FORM_DATA_VALUE) then(resourceSnippetJson.read<String>("request.example")).isEqualTo(operation.request.contentAsString) then(resourceSnippetJson.read<List<*>>("tags")).hasSize(3) then(resourceSnippetJson.read<String>("request.schema.name")).isNotEmpty then(resourceSnippetJson.read<List<*>>("request.headers")).hasSize(1) then(resourceSnippetJson.read<String>("request.headers[0].name")).isNotEmpty then(resourceSnippetJson.read<String>("request.headers[0].description")).isNotEmpty then(resourceSnippetJson.read<String>("request.headers[0].type")).isNotEmpty then(resourceSnippetJson.read<String>("request.headers[0].default")).isNotEmpty then(resourceSnippetJson.read<Boolean>("request.headers[0].optional")).isFalse then(resourceSnippetJson.read<String>("request.headers[0].example")).isNotEmpty then(resourceSnippetJson.read<List<*>>("request.pathParameters")).hasSize(1) then(resourceSnippetJson.read<String>("request.pathParameters[0].name")).isNotEmpty then(resourceSnippetJson.read<String>("request.pathParameters[0].description")).isNotEmpty then(resourceSnippetJson.read<String>("request.pathParameters[0].type")).isNotEmpty then(resourceSnippetJson.read<String>("request.pathParameters[0].default")).isNull() then(resourceSnippetJson.read<Boolean>("request.pathParameters[0].optional")).isFalse then(resourceSnippetJson.read<Boolean>("request.pathParameters[0].ignored")).isFalse then(resourceSnippetJson.read<List<*>>("request.requestParts")).hasSize(2) then(resourceSnippetJson.read<String>("request.requestParts[0].name")).isNotEmpty then(resourceSnippetJson.read<String>("request.requestParts[0].description")).isNotEmpty then(resourceSnippetJson.read<String>("request.requestParts[0].type")).isNotEmpty then(resourceSnippetJson.read<Boolean>("request.requestParts[0].optional")).isFalse then(resourceSnippetJson.read<Boolean>("request.requestParts[0].ignored")).isFalse then(resourceSnippetJson.read<List<String>>("request.securityRequirements.requiredScopes")) .containsExactly("scope1", "scope2") then(resourceSnippetJson.read<String>("request.securityRequirements.type")).isEqualTo("OAUTH2") then(resourceSnippetJson.read<String>("request.example")).isNotEmpty then(resourceSnippetJson.read<Int>("response.status")).isEqualTo(HttpStatus.CREATED.value()) then(resourceSnippetJson.read<String>("response.example")).isNotEmpty then(resourceSnippetJson.read<String>("response.schema.name")).isNotEmpty then(resourceSnippetJson.read<List<*>>("response.headers")).hasSize(1) then(resourceSnippetJson.read<String>("response.headers[0].name")).isNotEmpty then(resourceSnippetJson.read<String>("response.headers[0].description")).isNotEmpty then(resourceSnippetJson.read<String>("response.headers[0].type")).isNotEmpty then(resourceSnippetJson.read<String>("response.headers[0].default")).isNull() then(resourceSnippetJson.read<Boolean>("response.headers[0].optional")).isFalse then(resourceSnippetJson.read<String>("response.headers[0].example")).isNotEmpty } @Test fun should_generate_resource_model_for_operation_without_body() { givenOperationWithoutBody() whenResourceSnippetInvoked() thenSnippetFileExists() thenSnippetFileHasCommonRequestAttributes() } @Test fun should_filter_ignored_request_and_response_fields() { givenOperationWithRequestBodyAndIgnoredRequestField() givenIgnoredAndNotIgnoredRequestFieldDescriptors() givenIgnoredAndNotIgnoredResponseFieldDescriptors() whenResourceSnippetInvoked() thenSnippetFileExists() thenSnippetFilesHasNoIgnoredFields() } @Test fun should_filter_ignored_query_parameters() { givenOperationWithQueryParameters() givenIgnoredAndNotIgnoredQueryParameterDescriptors() whenResourceSnippetInvoked() thenSnippetFileExists() then(resourceSnippetJson.read<List<*>>("request.queryParameters")).hasSize(1) then(resourceSnippetJson.read<String>("request.queryParameters[0].name")).isEqualTo("describedParameter") } @Test fun should_filter_ignored_form_parameters() { givenOperationWithFormParameters() givenIgnoredAndNotIgnoredFormParameterDescriptors() whenResourceSnippetInvoked() thenSnippetFileExists() then(resourceSnippetJson.read<List<*>>("request.formParameters")).hasSize(1) then(resourceSnippetJson.read<String>("request.formParameters[0].name")).isEqualTo("describedParameter") } @Test fun should_generate_query_parameter_attributes() { givenOperationWithPathAndQueryParametersHasAttributes() givenPathParameterDescriptorsHasAttributes() givenQueryParameterDescriptorsHasAttributes() whenResourceSnippetInvoked() thenSnippetFileExists() then(resourceSnippetJson.read<List<*>>("request.pathParameters")).hasSize(2) then(resourceSnippetJson.read<String>("request.pathParameters[0].name")).isEqualTo("no") then(resourceSnippetJson.read<String>("request.pathParameters[0].type")) .isEqualTo(DataType.INTEGER.name) then(resourceSnippetJson.read<String>("request.pathParameters[0].description")) .isEqualTo("number description") then(resourceSnippetJson.read<Boolean>("request.pathParameters[0].optional")).isFalse then(resourceSnippetJson.read<String>("request.pathParameters[1].name")).isEqualTo("type") then(resourceSnippetJson.read<String>("request.pathParameters[1].type")) .isEqualTo(DataType.STRING.name) then(resourceSnippetJson.read<String>("request.pathParameters[1].description")) .isEqualTo("type enum description") then(resourceSnippetJson.read<Boolean>("request.pathParameters[1].optional")).isFalse then(resourceSnippetJson.read<List<String>>("request.pathParameters[1].attributes.enumValues")) .isEqualTo(listOf("T1", "T2", "T3")) then(resourceSnippetJson.read<List<*>>("request.queryParameters")).hasSize(2) then(resourceSnippetJson.read<String>("request.queryParameters[0].name")).isEqualTo("numberParameter") then(resourceSnippetJson.read<String>("request.queryParameters[0].type")) .isEqualTo(DataType.INTEGER.name) then(resourceSnippetJson.read<String>("request.queryParameters[0].description")) .isEqualTo("number description") then(resourceSnippetJson.read<Boolean>("request.queryParameters[0].optional")).isFalse then(resourceSnippetJson.read<String>("request.queryParameters[1].name")).isEqualTo("categoryParameter") then(resourceSnippetJson.read<String>("request.queryParameters[1].type")) .isEqualTo(DataType.STRING.name) then(resourceSnippetJson.read<String>("request.queryParameters[1].description")) .isEqualTo("category enum description") then(resourceSnippetJson.read<Boolean>("request.queryParameters[1].optional")).isFalse then(resourceSnippetJson.read<List<String>>("request.queryParameters[1].attributes.enumValues")) .isEqualTo(listOf("C1", "C2", "C3")) } @Test fun should_generate_form_parameter_attributes() { givenOperationWithRequestAndResponseBody( requestContentType = APPLICATION_FORM_URLENCODED_VALUE, requestContent = "numParameter=22&kindParameter=K3" ) givenFormParameterDescriptorsHasAttributes() whenResourceSnippetInvoked() thenSnippetFileExists() then(resourceSnippetJson.read<List<*>>("request.formParameters")).hasSize(2) then(resourceSnippetJson.read<String>("request.formParameters[0].name")).isEqualTo("numParameter") then(resourceSnippetJson.read<String>("request.formParameters[0].type")) .isEqualTo(DataType.INTEGER.name) then(resourceSnippetJson.read<String>("request.formParameters[0].description")) .isEqualTo("number description") then(resourceSnippetJson.read<Boolean>("request.formParameters[0].optional")).isFalse then(resourceSnippetJson.read<String>("request.formParameters[1].name")).isEqualTo("kindParameter") then(resourceSnippetJson.read<String>("request.formParameters[1].type")) .isEqualTo(DataType.STRING.name) then(resourceSnippetJson.read<String>("request.formParameters[1].description")) .isEqualTo("kind enum description") then(resourceSnippetJson.read<Boolean>("request.formParameters[1].optional")).isFalse then(resourceSnippetJson.read<List<String>>("request.formParameters[1].attributes.enumValues")) .isEqualTo(listOf("K1", "K2", "K3")) } @Test fun should_fail_on_missing_url_template() { givenOperationWithoutUrlTemplate() thenThrownBy { whenResourceSnippetInvoked() } .isInstanceOf(ResourceSnippet.MissingUrlTemplateException::class.java) } @Test fun should_generate_resource_snippet_for_operation_name_placeholders() { givenOperationWithNamePlaceholders() whenResourceSnippetInvoked() thenSnippetFileExists("resource-snippet-test/get-some-by-id") then(resourceSnippetJson.read<String>("operationId")).isEqualTo("resource-snippet-test/get-some-by-id") } @Test fun should_respect_content_type_parameters_for_response() { givenOperationWithRequestAndResponseBody(responseContentType = "application/json;format=format-1") whenResourceSnippetInvoked() thenSnippetFileExists() then(resourceSnippetJson.read<String>("response.contentType")) .isEqualTo("application/json;format=format-1") } private fun givenTag() { parametersBuilder.tag("some") parametersBuilder.tags("someOther", "somethingElse") } private fun thenResourceSnippetContainsCommonRequestAttributes() { then(resourceSnippetJson.read<String>("request.contentType")).isEqualTo("application/json") then(resourceSnippetJson.read<String>("request.example")).isEqualTo(operation.request.contentAsString) then(resourceSnippetJson.read<List<*>>("request.requestFields")).hasSize(1) then(resourceSnippetJson.read<String>("request.requestFields[0].description")).isNotEmpty with(resourceSnippetJson.read<String>("request.requestFields[0].type")) { then(this).isNotEmpty then(JsonFieldType.valueOf(this)).isEqualTo(JsonFieldType.STRING) } then(resourceSnippetJson.read<String>("request.requestFields[0].type")).isNotEmpty then(JsonFieldType.valueOf(resourceSnippetJson.read("request.requestFields[0].type"))).isNotNull then(resourceSnippetJson.read<Boolean>("request.requestFields[0].optional")).isFalse then(resourceSnippetJson.read<Boolean>("request.requestFields[0].ignored")).isFalse } private fun thenSnippetFileHasCommonRequestAttributes() { then(resourceSnippetJson.read<String>("operationId")).isEqualTo("test") then(resourceSnippetJson.read<String>("request.path")).isEqualTo("/some/{id}") then(resourceSnippetJson.read<String>("request.method")).isEqualTo("POST") } private fun thenSnippetFilesHasNoIgnoredFields() { then(resourceSnippetJson.read<List<*>>("request.requestFields")).hasSize(1) then(resourceSnippetJson.read<List<*>>("response.responseFields")).hasSize(1) } private fun givenPathParameterDescriptors() { parametersBuilder.pathParameters(parameterWithName("id").description("an id")) } private fun givenQueryParameterDescriptors() { parametersBuilder.queryParameters( parameterWithName("test-param").type(DataType.STRING).defaultValue("default-value") .description("test param") ) } private fun givenFormParameterDescriptors() { parametersBuilder.formParameters( parameterWithName("test-param").type(DataType.STRING).defaultValue("default-value") .description("test param") ) } private fun givenRequestPartDescriptors() { parametersBuilder.requestParts( partWithName("file") .type(DataType.STRING) .attributes(com.keecon.restdocs.apispec.Attributes.format(DataFormat.BINARY)) .description("test multipart"), partWithName("title") .type(DataType.STRING) .description("multipart title") ) } private fun givenRequestAndResponseHeaderDescriptors() { val headerDescriptor = ResourceDocumentation.headerWithName("X-SOME") .type(DataType.STRING) .defaultValue("default-value") .description("some") parametersBuilder.requestHeaders(headerDescriptor) parametersBuilder.responseHeaders(HeaderDocumentation.headerWithName("X-SOME").description("some")) } private fun thenSnippetFileExists(operationName: String = this.operationName) { with(generatedSnippetFile(operationName)) { then(this).exists() val contents = readText() then(contents).isNotEmpty println(contents) resourceSnippetJson = JsonPath.parse(contents) } } private fun generatedSnippetFile(operationName: String) = File(rootOutputDirectory, "$operationName/resource.json") private fun givenOperationWithoutBody() { val operationBuilder = OperationBuilder("test", rootOutputDirectory) .attribute(ATTRIBUTE_NAME_URL_TEMPLATE, "http://localhost:8080/some/{id}") operationBuilder .request("http://localhost:8080/some/123") .method("POST") operationBuilder .response() .status(201) operation = operationBuilder.build() } private fun givenOperationWithoutUrlTemplate() { val operationBuilder = OperationBuilder("test", rootOutputDirectory) operationBuilder .request("http://localhost:8080/some/123") .method("POST") operationBuilder .response() .status(201) operation = operationBuilder.build() } private fun givenOperationWithNamePlaceholders() { operation = OperationBuilder("{class-name}/{method-name}", rootOutputDirectory) .attribute(ATTRIBUTE_NAME_URL_TEMPLATE, "http://localhost:8080/some/{id}") .testClass(ResourceSnippetTest::class.java) .testMethodName("getSomeById") .request("http://localhost:8080/some/123") .method("POST") .header(CONTENT_TYPE, APPLICATION_JSON_VALUE) .content("{\"comment\": \"some\"}") .build() } private fun givenOperationWithRequestBody() { operation = OperationBuilder("test", rootOutputDirectory) .attribute(ATTRIBUTE_NAME_URL_TEMPLATE, "http://localhost:8080/some/{id}") .request("http://localhost:8080/some/123") .method("POST") .header(CONTENT_TYPE, APPLICATION_JSON_VALUE) .content("{\"comment\": \"some\"}") .build() } private fun givenOperationWithRequestBodyAndIgnoredRequestField() { val operationBuilder = OperationBuilder("test", rootOutputDirectory) operationBuilder .attribute(ATTRIBUTE_NAME_URL_TEMPLATE, "http://localhost:8080/some/{id}") .request("http://localhost:8080/some/123") .method("POST") .header(CONTENT_TYPE, APPLICATION_JSON_VALUE) .content("{\"comment\": \"some\", \"ignored\": \"notVeryImportant\"}") operationBuilder .response() .status(201) .content("{\"comment\": \"some\", \"ignored\": \"notVeryImportant\"}") operation = operationBuilder.build() } private fun givenOperationWithQueryParameters() { val operationBuilder = OperationBuilder("test", rootOutputDirectory) operationBuilder .attribute(ATTRIBUTE_NAME_URL_TEMPLATE, "http://localhost:8080/some/{id}") .request("http://localhost:8080/some/123") .queryParam("describedParameter", "will", "be", "documented") .queryParam("obviousParameter", "wont", "be", "documented") .method("GET") operationBuilder .response() .status(204) operation = operationBuilder.build() } private fun givenOperationWithFormParameters() { val operationBuilder = OperationBuilder("test", rootOutputDirectory) operationBuilder .attribute(ATTRIBUTE_NAME_URL_TEMPLATE, "http://localhost:8080/some/{id}") .request("http://localhost:8080/some/123") .content( "describedParameter=will,be,documented&obviousParameter=wont,be,documented" ) .method("GET") operationBuilder .response() .status(204) operation = operationBuilder.build() } private fun givenOperationWithPathAndQueryParametersHasAttributes() { val operationBuilder = OperationBuilder("test", rootOutputDirectory) operationBuilder .attribute(ATTRIBUTE_NAME_URL_TEMPLATE, "http://localhost:8080/some/{no}/{type}") .request("http://localhost:8080/some/123/T1") .queryParam("numberParameter", "21") .queryParam("categoryParameter", "C2") .method("GET") operationBuilder .response() .status(204) operation = operationBuilder.build() } private fun givenRequestFieldDescriptors() { parametersBuilder.requestFields(fieldWithPath("comment").description("description")) } private fun givenRequestSchemaName() { parametersBuilder.requestSchema(Schema(name = "RequestSchema")) } private fun givenResponseFieldDescriptors() { parametersBuilder.responseFields(fieldWithPath("comment").description("description")) } private fun givenResponseSchemaName() { parametersBuilder.responseSchema(Schema(name = "ResponseSchema")) } private fun givenIgnoredAndNotIgnoredRequestFieldDescriptors() { parametersBuilder.requestFields( fieldWithPath("comment").description("description"), fieldWithPath("ignored").description("description").ignored() ) } private fun givenIgnoredAndNotIgnoredResponseFieldDescriptors() { parametersBuilder.responseFields( fieldWithPath("comment").description("description"), fieldWithPath("ignored").description("description").ignored() ) } private fun givenIgnoredAndNotIgnoredQueryParameterDescriptors() { parametersBuilder.queryParameters( parameterWithName("describedParameter").description("description"), parameterWithName("obviousParameter").description("needs no documentation, too obvious").ignored() ) } private fun givenIgnoredAndNotIgnoredFormParameterDescriptors() { parametersBuilder.formParameters( parameterWithName("describedParameter").description("description"), parameterWithName("obviousParameter").description("needs no documentation, too obvious").ignored() ) } private fun givenPathParameterDescriptorsHasAttributes() { parametersBuilder.pathParameters( parameterWithName("no").type(DataType.INTEGER).description("number description"), parameterWithName("type").description("type enum description").attributes( Attributes.key("enumValues").value(arrayOf("T1", "T2", "T3")) ) ) } private fun givenQueryParameterDescriptorsHasAttributes() { parametersBuilder.queryParameters( parameterWithName("numberParameter").type(DataType.INTEGER).description("number description"), parameterWithName("categoryParameter").description("category enum description").attributes( Attributes.key("enumValues").value(arrayOf("C1", "C2", "C3")) ) ) } private fun givenFormParameterDescriptorsHasAttributes() { parametersBuilder.formParameters( parameterWithName("numParameter").type(DataType.INTEGER).description("number description"), parameterWithName("kindParameter").description("kind enum description").attributes( Attributes.key("enumValues").value(arrayOf("K1", "K2", "K3")) ) ) } private fun givenOperationWithRequestAndResponseBody( requestContentType: String = APPLICATION_JSON_VALUE, requestContent: String = "{\"comment\": \"some\"}", responseContentType: String = APPLICATION_JSON_VALUE, responseContent: String = "{\"comment\": \"some\"}", ) { val operationBuilder = OperationBuilder("test", rootOutputDirectory) .attribute(ATTRIBUTE_NAME_URL_TEMPLATE, "http://localhost:8080/some/{id}") operationBuilder .request("http://localhost:8080/some/123") .queryParam("test-param", "1") .method("POST") .header("X-SOME", "some") .header( AUTHORIZATION, "Bearer eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCJ9" + ".eyJzY29wZSI6WyJzY29wZTEiLCJzY29wZTIiXSwiZXhwIjoxNTA3NzU4NDk4LCJpYXQiOjE1MDc3MT" + "UyOTgsImp0aSI6IjQyYTBhOTFhLWQ2ZWQtNDBjYy1iMTA2LWU5MGNkYWU0M2Q2ZCJ9" + ".eWGo7Y124_Hdrr-bKX08d_oCfdgtlGXo9csz-hvRhRORJi_ZK7PIwM0ChqoLa4AhR-dJ86npid75GB" + "9IxCW2f5E24FyZW2p5swpOpfkEAA4oFuj7jxHiaiqL_HFKKCRsVNAN3hGiSp9Hn3fde0-LlABqMaihd" + "zZzHL-xm8-CqbXT-qBfuscDImZrZQZqhizpSEV4idbEMzZykggLASGoOIL0t0ycfe3yeuQkMUhzZmXu" + "u08VM7zXwWnqfXCa-RmA6wC7ZnWqiJoi0vBr4BrlLR067YoUrT6pgRfiy2HZ0vEE_XY5SBtA-qI2Qnl" + "Jb7eTk7pgFtoGkYdeOZ86k6GDVw" ) .header(CONTENT_TYPE, requestContentType) .content(requestContent) operationBuilder .response() .status(201) .header("X-SOME", "some") .header(CONTENT_TYPE, responseContentType) .content(responseContent) operation = operationBuilder.build() } private fun givenOperationWithRequestPartAndResponseBody() { val operationBuilder = OperationBuilder("test", rootOutputDirectory) .attribute(ATTRIBUTE_NAME_URL_TEMPLATE, "http://localhost:8080/some/{id}") operationBuilder .request("http://localhost:8080/some/123") .method("POST") .header("X-SOME", "some") .header( AUTHORIZATION, "Bearer eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCJ9" + ".eyJzY29wZSI6WyJzY29wZTEiLCJzY29wZTIiXSwiZXhwIjoxNTA3NzU4NDk4LCJpYXQiOjE1MDc3MT" + "UyOTgsImp0aSI6IjQyYTBhOTFhLWQ2ZWQtNDBjYy1iMTA2LWU5MGNkYWU0M2Q2ZCJ9" + ".eWGo7Y124_Hdrr-bKX08d_oCfdgtlGXo9csz-hvRhRORJi_ZK7PIwM0ChqoLa4AhR-dJ86npid75GB" + "9IxCW2f5E24FyZW2p5swpOpfkEAA4oFuj7jxHiaiqL_HFKKCRsVNAN3hGiSp9Hn3fde0-LlABqMaihd" + "zZzHL-xm8-CqbXT-qBfuscDImZrZQZqhizpSEV4idbEMzZykggLASGoOIL0t0ycfe3yeuQkMUhzZmXu" + "u08VM7zXwWnqfXCa-RmA6wC7ZnWqiJoi0vBr4BrlLR067YoUrT6pgRfiy2HZ0vEE_XY5SBtA-qI2Qnl" + "Jb7eTk7pgFtoGkYdeOZ86k6GDVw" ) .header(CONTENT_TYPE, MULTIPART_FORM_DATA_VALUE) .content(" ") // TODO(iwaltgen): must be set to something, otherwise the request content-type is not set .part("title", "some title".toByteArray(), TEXT_PLAIN_VALUE) .part("file", "test file body".toByteArray(), TEXT_PLAIN_VALUE) operationBuilder .response() .status(201) .header("X-SOME", "some") .header(CONTENT_TYPE, APPLICATION_JSON_VALUE) .content("{\"comment\": \"some\"}") operation = operationBuilder.build() } @Throws(IOException::class) private fun whenResourceSnippetInvoked() { resource( parametersBuilder .description("some description") .summary("some summary") .build() ).document(operation) } companion object { private const val OPERATION_NAME = "test" } }
0
Kotlin
0
2
b20ac51a34d8a24d765009426330df4a3db18014
36,064
restdocs-openapi3
MIT License
compiler/testData/diagnostics/tests/deprecated/importJavaSamInterface.fir.kt
JetBrains
3,432,266
false
null
// SKIP_TXT // FILE: test/J.java package test; @Deprecated public interface J { public String foo(int x); } // FILE: K.kt import <!DEPRECATION!>test.J<!>
181
null
5748
49,172
33eb9cef3d146062c103f9853d772f0a1da0450e
162
kotlin
Apache License 2.0
type-system/src/commonMain/kotlin/io/github/charlietap/chasm/type/rolling/substitution/ArrayTypeSubstitutor.kt
CharlieTap
743,980,037
false
{"Kotlin": 2038041, "WebAssembly": 45714}
package io.github.charlietap.chasm.type.rolling.substitution import io.github.charlietap.chasm.ast.type.ArrayType import io.github.charlietap.chasm.ast.type.FieldType internal fun ArrayTypeSubstitutor( arrayType: ArrayType, concreteHeapTypeSubstitutor: ConcreteHeapTypeSubstitutor, ): ArrayType = ArrayTypeSubstitutor( arrayType = arrayType, concreteHeapTypeSubstitutor = concreteHeapTypeSubstitutor, fieldTypeSubstitutor = ::FieldTypeSubstitutor, ) internal fun ArrayTypeSubstitutor( arrayType: ArrayType, concreteHeapTypeSubstitutor: ConcreteHeapTypeSubstitutor, fieldTypeSubstitutor: TypeSubstitutor<FieldType>, ): ArrayType = ArrayType( fieldTypeSubstitutor(arrayType.fieldType, concreteHeapTypeSubstitutor), )
5
Kotlin
3
67
a452ab9e37504517b43118f636a28f54e7bcb57c
774
chasm
Apache License 2.0
app/src/main/java/com/devhomc/videoplayersample/repository/VideoRepository.kt
oidy
534,576,264
false
{"Kotlin": 16666}
package com.devhomc.videoplayersample.repository import android.content.Context import android.media.MediaMetadataRetriever import android.media.MediaMetadataRetriever.METADATA_KEY_ARTIST import android.media.MediaMetadataRetriever.METADATA_KEY_TITLE import android.net.Uri import androidx.media3.common.MediaItem import androidx.media3.common.MediaMetadata import dagger.hilt.android.qualifiers.ApplicationContext import javax.inject.Inject class VideoRepository @Inject constructor(@ApplicationContext private val context: Context) { fun getVideo(fileName: String): MediaItem { val uri = Uri.parse("asset:///${fileName}") val requestMetadata = MediaItem.RequestMetadata.Builder() .setMediaUri(uri) .build() val assetFileDescriptor = context.assets.openFd(fileName) val metadataRetriever = MediaMetadataRetriever() metadataRetriever.setDataSource( assetFileDescriptor.fileDescriptor, assetFileDescriptor.startOffset, assetFileDescriptor.length ) val mediaMetadata = MediaMetadata.Builder() .setTitle(metadataRetriever.extractMetadata(METADATA_KEY_TITLE)) .setArtist(metadataRetriever.extractMetadata(METADATA_KEY_ARTIST)) .build() return MediaItem.Builder() .setRequestMetadata(requestMetadata) .setMediaMetadata(mediaMetadata) .build() } }
0
Kotlin
0
17
c079b4c81ae6ffa228c7e93ce687e8369edda69b
1,453
VideoPlayerSample
Apache License 2.0
sync-script/src/main/kotlin/syncService/ServersSyncService.kt
FreshKernel
799,541,150
false
{"Kotlin": 391024}
package syncService import constants.SyncScriptDotMinecraftFiles import net.benwoodworth.knbt.Nbt import net.benwoodworth.knbt.NbtCompound import net.benwoodworth.knbt.NbtCompression import net.benwoodworth.knbt.NbtList import net.benwoodworth.knbt.NbtTag import net.benwoodworth.knbt.NbtVariant import net.benwoodworth.knbt.add import net.benwoodworth.knbt.buildNbtCompound import net.benwoodworth.knbt.buildNbtList import net.benwoodworth.knbt.decodeFromStream import net.benwoodworth.knbt.encodeToStream import net.benwoodworth.knbt.nbtCompound import net.benwoodworth.knbt.put import syncInfo.models.SyncInfo import syncInfo.models.instance import utils.ExecutionTimer import utils.Logger import utils.buildHtml import utils.isFileEmpty import utils.showErrorMessageAndTerminate import java.io.EOFException import kotlin.io.path.exists import kotlin.io.path.inputStream import kotlin.io.path.isRegularFile import kotlin.io.path.name import kotlin.io.path.outputStream import kotlin.io.path.pathString import kotlin.system.exitProcess class ServersSyncService : SyncService { private val serversDatFilePath = SyncScriptDotMinecraftFiles.ServersDat.path private val serversSyncService = SyncInfo.instance.serverSyncInfo companion object { const val SERVER_NBT_MAIN_COMPOUND_KEY = "" } private val nbt = Nbt { variant = NbtVariant.Java compression = NbtCompression.None } override suspend fun syncData() { val executionTimer = ExecutionTimer() executionTimer.setStartTime() Logger.info(extraLine = true) { "\uD83D\uDD04 Syncing server list..." } val currentRootCompound = loadServersDatFile().getOrElse { showErrorMessageAndTerminate( title = "📁 File Loading Error", message = buildHtml { text("⚠ Unable to read the server list from the file '${serversDatFilePath.pathString}': ") newLine() text("$it") newLines(2) if (it is EOFException) { text("This issue might occur if the file is corrupt or incomplete.") newLine() text("As a potential workaround, consider deleting the file '${serversDatFilePath.pathString}'.") } else { text("Deleting the file '${serversDatFilePath.pathString}' could resolve the issue.") } newLine() boldText("Note: Deleting this file will reset the server list in the game.") }.buildBodyAsText(), ) return } val newServerListCompound: NbtList<NbtCompound> = buildNbtList { serversSyncService.servers.map { val serverCompound = buildNbtCompound { put("ip", it.address) put("name", it.name) } add(serverCompound) } } val newRootCompound = currentRootCompound.let { val mutableRootMap = it.toMutableMap() val mutableMainMap = it[SERVER_NBT_MAIN_COMPOUND_KEY]?.nbtCompound?.toMutableMap() ?: mutableMapOf() mutableMainMap["servers"] = newServerListCompound mutableRootMap[SERVER_NBT_MAIN_COMPOUND_KEY] = NbtCompound(mutableMainMap) NbtCompound(mutableRootMap) } updateServersDatFile(newRootCompound = newRootCompound).getOrElse { showErrorMessageAndTerminate( title = "🚨 File Update Error", message = "⚠️ Unable to update the '${serversDatFilePath.name}' file: $it", ) return } Logger.info { "\uD83D\uDD52 Finished syncing the server list in ${executionTimer.getRunningUntilNowDuration().inWholeMilliseconds}ms." } } private fun loadServersDatFile(): Result<NbtCompound> { return try { if (serversDatFilePath.exists()) { if (!serversDatFilePath.isRegularFile()) { showErrorMessageAndTerminate( title = "❌ Invalid '${serversDatFilePath.name}' File", message = "\uD83D\uDEE0 '${serversDatFilePath.name}' must be a file \uD83D\uDCC2, a directory/folder was found instead.", ) // This will never reach due to the previous statement stopping the application exitProcess(1) } if (serversDatFilePath.isFileEmpty()) { Logger.info { "ℹ️ The file '${serversDatFilePath.name}' exists and is currently empty." } return Result.success(createEmptyServerCompound()) } return Result.success( serversDatFilePath .inputStream() .use { inputStream -> nbt.decodeFromStream<NbtTag>(inputStream) } as NbtCompound, ) } Result.success(createEmptyServerCompound()) } catch (e: Exception) { Result.failure(e) } } private fun updateServersDatFile(newRootCompound: NbtCompound): Result<Unit> = runCatching { serversDatFilePath .outputStream() .use { outputStream -> nbt.encodeToStream(newRootCompound, outputStream) } } private fun createEmptyServerCompound(): NbtCompound = NbtCompound(mapOf(SERVER_NBT_MAIN_COMPOUND_KEY to NbtCompound(emptyMap()))) }
1
Kotlin
0
2
1719f6abd0a48ce0e5aa68607d2b779885a63a87
6,041
kraft-sync
MIT License
app/src/main/java/com/droid47/petpot/search/domain/interactors/UpdateFavouritePetsStatusUseCase.kt
AndroidKiran
247,345,176
false
null
package com.droid47.petpot.search.domain.interactors import com.droid47.petpot.base.usecase.CompletableUseCase import com.droid47.petpot.base.usecase.executor.PostExecutionThread import com.droid47.petpot.base.usecase.executor.ThreadExecutor import com.droid47.petpot.search.domain.repositories.FavouritePetRepository import io.reactivex.Completable import javax.inject.Inject class UpdateFavouritePetsStatusUseCase @Inject constructor( threadExecutor: ThreadExecutor, postExecutionThread: PostExecutionThread, private val favouritePetRepository: FavouritePetRepository ) : CompletableUseCase<Pair<Boolean, Boolean>>(threadExecutor, postExecutionThread) { override fun buildUseCaseCompletable(params: Pair<Boolean, Boolean>): Completable = favouritePetRepository.updateFavoritePetStatus(params.first, params.second) }
1
null
1
2
07d9c0c4f0d5bef32d9705f6bb49f938ecc456e3
844
PetPot
Apache License 2.0
app/common/src/commonMain/kotlin/com/seiko/markdown/demo/MarkdownCode.kt
qdsfdhvh
621,603,345
false
null
package com.seiko.markdown.demo val markdownCode = """ # 1.标题(h标签) h1-h6对应1-6个# ## h2 ### h3 #### h4 ##### h5 ###### h6 This is a **full** on test with some _markdown_! What's really cool is the `code snippets` that show up too. ###### _~~**`This is a test with every kind of formatting`**~~_ Inline [`links`](https://google.com) are now also supported! Here is an example of [another link](https://tylerbwong.me). Inline images are supported as well ![Kotlin](https://developer.android.com/images/jetpack/info-bytes-compose-less-code.png)! Reference images are coming soon! # 2.列表(li>li) #### 无序列表 * This is an `unordered` list item - This is another **unordered** list item * This is yet another [unordered](https://tylerbwong.me) list item #### 有序列表 1. This is an `ordered` list item 2. This is another **ordered** list item 3) This is yet another [ordered](https://tylerbwong.me) list item # 3.引用(blockquote) > 这个是引用的内容 # 4.图片与链接 #### 图片:名字、url #### 链接 [~~小莫~~的主页](http://www.xiaomo.info) # 5.粗体与斜体 > 说明:用两个 * 包含一段文本就是粗体的语法,用一个 * 包含一段文本就是斜体的语法。 **这里是粗体** *这里是斜体* ~~这是删除线~~ # 6.表格 | Tables | Are | Cool | | ----------- |:-----------:| -----:| | col 3 is | right-aligned | ${'$'}1600 | | col 2 is | centered | ${'$'}12 | | zebra stripes | are neat | ${'$'}1 | # 7.代码块 ``` function Hello() { console.log("hello"); } ``` # 8.分割线(hr) 三个或三个以上的星号、减号或者下划线 *** > I am a block quote! > > I am a nested block quote! - [ ] I am an ~~unchecked~~ checkbox - [x] I am a [checked checkbox](https://google.com) """.trimIndent()
0
Kotlin
0
0
3d4d3ababdf21c6e0f4847d49cd65b14012374af
1,772
compose-markdown
MIT License
core/src/main/java/vn/meepo/android/support/core/extension/LiveDataExt.kt
meepo-lab
520,004,629
false
null
package vn.meepo.android.support.core.extension import androidx.fragment.app.Fragment import androidx.lifecycle.* import vn.meepo.android.support.core.AppExecutors import vn.meepo.android.support.core.ConcurrentContext import vn.meepo.android.support.core.ConcurrentScope import vn.meepo.android.support.core.event.LoadingEvent import vn.meepo.android.support.core.event.SingleLiveEvent import vn.meepo.android.support.core.funcational.Form import vn.meepo.android.support.core.isOnMainThread fun <T> LiveData<T>.observe(owner: LifecycleOwner, function: (T?) -> Unit) { observe(owner, Observer(function)) } fun <T, V> LiveData<T>.map(function: (T) -> V): LiveData<V> { val next = MediatorLiveData<V>() next.addSource(this) { next.value = function(it) } return next } fun <T> MutableLiveData<T>.load(background: Boolean = true, function: () -> T): LiveData<T> { if (background) AppExecutors.diskIO.execute { postValue(function()) } else value = function() return this } fun <T> MutableLiveData<T>.loadNotNull( background: Boolean = true, function: () -> T? ): LiveData<T> { if (background) AppExecutors.diskIO.execute { function()?.also { postValue(it) } } else function()?.also { value = it } return this } fun MutableLiveData<*>.call() { this.post(null) } fun <T> MutableLiveData<T>.refresh() { this.post(value) } fun <T> MutableLiveData<T>.post(t: T?) { if (isOnMainThread) value = t else postValue(t) } fun <T> LiveData<T>.subscribe( owner: LifecycleOwner, function: (T) -> Unit ) { observe( when (owner) { is Fragment -> owner.viewLifecycleOwner else -> owner }, Observer(function) ) } fun <T> LiveData<T>.toSingle(): LiveData<T> { return SingleLiveEvent<T>().also { next -> next.addSource(this) { next.value = it } } } fun <T> LiveData<T>.filter(function: (T) -> Boolean): LiveData<T> { return MediatorLiveData<T>().also { next -> next.addSource(this) { if (function(it)) next.value = it } } } fun <T> LiveData<T>.asMutable(): MutableLiveData<T> { return this as? MutableLiveData<T> ?: error("$this is not mutable") } class LoadCacheLiveData<T, V> : MediatorLiveData<Pair<T, V>>() fun <T, V> LiveData<T>.loadCache( background: Boolean = false, function: (T) -> V ): LoadCacheLiveData<T, V> { return LoadCacheLiveData<T, V>().also { next -> next.addSource(this) { if (!background) next.value = it to function(it) else AppExecutors.diskIO.execute { next.postValue(it to function(it)) } } } } fun <T, V> MutableLiveData<V>.doAsync( it: T, concurrent: ConcurrentContext, loadingEvent: LoadingEvent?, errorEvent: SingleLiveEvent<Throwable>?, function: ConcurrentScope.(T) -> V? ) { if (it is Form) { try { it.validate() } catch (e: Throwable) { errorEvent?.postValue(e) return } } loadingEvent?.value = true concurrent.launch { try { postValue(function(it)) } catch (t: Throwable) { errorEvent?.postValue(t) t.printStackTrace() } finally { loadingEvent?.postValue(false) } } } val <T> LiveData<T>.awaitValue: T? get() { var data: T? = null this.observeForever { data = it } return data }
0
Kotlin
0
0
8e1572d02a882224130f27e929924925a0ba18b1
3,524
android-libs
Apache License 2.0
CustomView/app/src/main/java/com/example/customview/views/pra1/PractiseFirstActivity.kt
RivenPlayer-1
707,619,607
false
{"Kotlin": 70235}
package com.example.customview.views.pra1 import androidx.appcompat.app.AppCompatActivity import android.os.Bundle import android.util.Log import android.view.Menu import android.view.MenuItem import android.widget.Toast import androidx.core.view.MenuItemCompat import androidx.viewpager2.widget.ViewPager2 import com.example.customview.R class PractiseFirstActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_practise_first) setSupportActionBar(findViewById(R.id.my_toolbar)) val vp = findViewById<ViewPager2>(R.id.my_vp) } override fun onCreateOptionsMenu(menu: Menu?): Boolean { menuInflater.inflate(R.menu.view_menu, menu) val shareItem = menu?.findItem(R.id.action_share); var myShareActionProvider = MenuItemCompat.getActionProvider(shareItem) myShareActionProvider.setVisibilityListener { Toast.makeText(this, "分享", Toast.LENGTH_SHORT).show() } return true } override fun onOptionsItemSelected(item: MenuItem): Boolean { when (item.itemId) { R.id.action_settings -> { } R.id.action_share -> { Toast.makeText(this, "分享", Toast.LENGTH_SHORT).show() Log.d("aaaaa", "onOptionsItemSelected: aaa") } } return super.onOptionsItemSelected(item) } }
0
Kotlin
0
0
e3b73b0840c98c14e841273c00342ef369a0dbda
1,479
Android
Apache License 2.0
sample/src/main/java/ua/naiksoftware/tooltips/sample/MainActivity.kt
NaikSoftware
172,398,941
false
null
package ua.naiksoftware.tooltips.sample import android.graphics.Color import android.os.Bundle import com.google.android.material.floatingactionbutton.FloatingActionButton import com.google.android.material.snackbar.Snackbar import com.google.android.material.tabs.TabLayout import androidx.viewpager.widget.ViewPager import androidx.appcompat.app.AppCompatActivity import androidx.core.view.doOnPreDraw import ua.naiksoftware.tooltips.TooltipOverlayPopup import ua.naiksoftware.tooltips.TooltipOverlayParams import ua.naiksoftware.tooltips.TooltipPosition import ua.naiksoftware.tooltips.TooltipView import ua.naiksoftware.tooltips.sample.ui.main.SectionsPagerAdapter class MainActivity : AppCompatActivity() { private lateinit var fab: FloatingActionButton private var popup : TooltipOverlayPopup? = null override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) val sectionsPagerAdapter = SectionsPagerAdapter(this, supportFragmentManager) val viewPager: ViewPager = findViewById(R.id.view_pager) viewPager.adapter = sectionsPagerAdapter val tabs: TabLayout = findViewById(R.id.tabs) tabs.setupWithViewPager(viewPager) fab = findViewById(R.id.fab) fab.setOnClickListener { view -> Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG) .setAction("Action", null).show() } val tooltipView = TooltipView(this, "Test tooltip long long skjdcs sdc s c sdc s dcs" + " dc s dc s c s cs dc s dcsdcscdsdc sc sdcsdcsdc s dcs dc s dc sdc sd c sc") val density = resources.displayMetrics.density tooltipView.setPadding( (density * 16).toInt(), (density * 4).toInt(), (density * 16).toInt(), (density * 4).toInt() ) tooltipView.setBubbleColor(Color.BLUE) tooltipView.setTextColor(Color.WHITE) tooltipView.setMaxWidth((density * 200).toInt()) tooltipView.setLineSpacing(5f) fab.doOnPreDraw { popup = TooltipOverlayPopup() popup?.show( TooltipOverlayParams(tooltipView, fab) .dismissOnTouchAnchor(true) .anchorClickable(true) .dismissOnTouchOverlay(false) // .dismissOnTouchOutside(true) .withTransparentOverlay(true) .withTooltipPosition(TooltipPosition.TOP), this ) // popup?.dismissAsync(5000) } } override fun onDestroy() { popup?.dismiss() super.onDestroy() } }
0
Kotlin
0
4
abdead5322a315ce97b2b3e51d4d242c7c9b6020
2,743
OnboardingTooltips
Apache License 2.0
app/src/main/java/com/ddd/carssok/navigation/CarssokNavItem.kt
DDD-Community
566,191,080
false
null
package com.ddd.carssok.navigation import androidx.annotation.DrawableRes import androidx.annotation.StringRes import com.ddd.carssok.R import com.ddd.carssok.feature.home.navi.HomeDestination import com.ddd.carssok.feature.introduce.navi.IntroduceDestination import com.ddd.carssok.feature.record.navi.RecordDestination data class CarssokNavItem( @StringRes val titleResId: Int?, @DrawableRes val icon: Int, @DrawableRes val selectedIcon: Int, val route: String ) object CarssokNavItems { val fabItem = CarssokNavItem( titleResId = null, icon = com.google.android.material.R.drawable.ic_m3_chip_checked_circle, selectedIcon = com.google.android.material.R.drawable.ic_m3_chip_checked_circle, route = RecordDestination.route ) val topLevelBottomNavItems = listOf<CarssokNavItem>( CarssokNavItem( titleResId = R.string.item_bottom_navigation_title_home, icon = R.drawable.ic_bottom_navigation_unselected_home, selectedIcon = R.drawable.ic_bottom_navigation_selected_home, route = HomeDestination.route ), CarssokNavItem( titleResId = R.string.item_bottom_navigation_title_introduce, icon = R.drawable.ic_bottom_navigation_unselected_introduce, selectedIcon = R.drawable.ic_bottom_navigation_selected_introduce, route = IntroduceDestination.route ) ) fun isTopLevelNavItem(route: String?): Boolean { return topLevelBottomNavItems.map { it.route }.contains(route) or (fabItem.route == route) } }
10
Kotlin
0
0
7348d574f1b96eb4b6328e9c0f9a4da7fa4cfebc
1,605
28.8-Android
Apache License 2.0
bittrader-web/src/test/kotlin/org/kentunc/bittrader/web/infrastructure/repository/BalanceRepositoryImplTest.kt
ken-tunc
430,691,495
false
null
package org.kentunc.bittrader.web.infrastructure.repository import com.ninjasquad.springmockk.MockkBean import io.mockk.every import io.mockk.mockk import kotlinx.coroutines.flow.flowOf import kotlinx.coroutines.flow.toList import kotlinx.coroutines.runBlocking import org.junit.jupiter.api.Assertions.assertAll import org.junit.jupiter.api.Assertions.assertEquals import org.junit.jupiter.api.Test import org.kentunc.bittrader.common.infrastructure.webclient.http.order.BalanceApiClient import org.kentunc.bittrader.common.presentation.model.market.BalanceResponse import org.kentunc.bittrader.common.test.model.TestBalance import org.springframework.beans.factory.annotation.Autowired import org.springframework.test.context.junit.jupiter.SpringJUnitConfig @SpringJUnitConfig(BalanceRepositoryImpl::class) internal class BalanceRepositoryImplTest { @MockkBean private lateinit var balanceApiClient: BalanceApiClient @Autowired private lateinit var target: BalanceRepositoryImpl @Test fun testGet() = runBlocking { // setup: val balance = TestBalance.create() val response = mockk<BalanceResponse>() every { response.toBalance() } returns balance every { balanceApiClient.get() } returns flowOf(response) // exercise: val actual = target.get().toList() // verify: assertAll( { assertEquals(1, actual.size) }, { assertEquals(balance, actual[0]) } ) } }
2
Kotlin
0
0
757c83fd604e5758a5e67bbfd98b33c1d9cc1961
1,492
bittrader
MIT License
examples/src/tl/telegram/CodeSettings.kt
andreypfau
719,064,910
false
{"Kotlin": 62259}
// This file is generated by TLGenerator.kt // Do not edit manually! package tl.telegram import io.github.andreypfau.tl.serialization.Base64ByteStringSerializer import io.github.andreypfau.tl.serialization.TLCombinatorId import io.github.andreypfau.tl.serialization.TLConditional import kotlin.jvm.JvmName import kotlinx.io.bytestring.ByteString import kotlinx.serialization.SerialName import kotlinx.serialization.Serializable @Serializable @SerialName("codeSettings") @TLCombinatorId(0xAD253D78) public data class CodeSettings( @get:JvmName("flags") public val flags: Int, @SerialName("allow_flashcall") @TLConditional("flags", 0) @get:JvmName("allowFlashcall") public val allowFlashcall: Unit? = null, @SerialName("current_number") @TLConditional("flags", 1) @get:JvmName("currentNumber") public val currentNumber: Unit? = null, @SerialName("allow_app_hash") @TLConditional("flags", 4) @get:JvmName("allowAppHash") public val allowAppHash: Unit? = null, @SerialName("allow_missed_call") @TLConditional("flags", 5) @get:JvmName("allowMissedCall") public val allowMissedCall: Unit? = null, @SerialName("allow_firebase") @TLConditional("flags", 7) @get:JvmName("allowFirebase") public val allowFirebase: Unit? = null, @SerialName("logout_tokens") @TLConditional("flags", 6) @get:JvmName("logoutTokens") public val logoutTokens: List<@Serializable(Base64ByteStringSerializer::class) ByteString>? = null, @TLConditional("flags", 8) @get:JvmName("token") public val token: String? = null, @SerialName("app_sandbox") @TLConditional("flags", 8) @get:JvmName("appSandbox") public val appSandbox: Boolean? = null, ) { public companion object }
0
Kotlin
0
1
11f05ad1f977235e3e360cd6f6ada6f26993208e
1,787
tl-kotlin
MIT License
template/f-debug/src/main/java/ru/surfstudio/standard/f_debug/reused_components/ReusedComponentsDebugActivityRoute.kt
surfstudio
139,034,657
false
{"Kotlin": 2966626, "Java": 1025166, "FreeMarker": 104337, "Groovy": 43020, "C++": 1542, "Ruby": 884, "CMake": 285, "Shell": 33, "Makefile": 25}
package ru.surfstudio.standard.f_debug.reused_components import android.content.Context import android.content.Intent import ru.surfstudio.android.core.ui.navigation.activity.route.ActivityRoute /** * Роут экрана для показа переиспользуемых компонентов */ class ReusedComponentsDebugActivityRoute : ActivityRoute() { override fun prepareIntent(context: Context): Intent { return Intent(context, ReusedComponentsDebugActivityView::class.java) } }
5
Kotlin
30
249
6d73ebcaac4b4bd7186e84964cac2396a55ce2cc
466
SurfAndroidStandard
Apache License 2.0
client_end_user/shared/src/commonMain/kotlin/presentation/cart/CartUiEffect.kt
TheChance101
671,967,732
false
{"Kotlin": 2473455, "Ruby": 8872, "HTML": 6083, "Swift": 4726, "JavaScript": 3082, "CSS": 1436, "Dockerfile": 1407, "Shell": 1140}
package presentation.cart sealed class CartUiEffect{ data object NavigateUp: CartUiEffect() }
4
Kotlin
55
572
1d2e72ba7def605529213ac771cd85cbab832241
99
beep-beep
Apache License 2.0
lib/i18n/src/jvmMain/kotlin/zakadabar/lib/i18n/backend/module.kt
wiltonlazary
378,492,647
true
{"Kotlin": 1162402, "JavaScript": 2042, "HTML": 1390, "Shell": 506}
/* * Copyright © 2020-2021, <NAME> and contributors. Use of this source code is governed by the Apache 2.0 license. */ package zakadabar.lib.i18n.backend import zakadabar.stack.backend.server fun install() { server += LocaleBl() server += TranslationBl() }
0
null
0
0
1eabec93db32f09cf715048c6cffd0a7948f4d9c
268
zakadabar-stack
Apache License 2.0
common/src/main/java/com/imcys/bilibilias/common/base/BaseFragment.kt
1250422131
280,332,208
false
{"Java": 1038232, "Kotlin": 527284}
package com.imcys.bilibilias.common.base import androidx.fragment.app.Fragment open class BaseFragment : Fragment()
3
Java
43
652
c4c9dcfa3546e90c76698b1d4f468555f89f9135
118
bilibilias
Apache License 2.0
text-compose/src/main/kotlin/com/github/jnnkmsr/text/compose/UiTextResourceMapper.kt
jnnkmsr
673,792,343
false
null
/* * 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.github.jnnkmsr.text.compose import com.github.jnnkmsr.text.IdTextResource import com.github.jnnkmsr.text.StringTextResource import com.github.jnnkmsr.text.TextResource /** * Maps `this` [UiTextResource] instance to a matching [TextResource]. * * @see toUiTextResource */ public fun UiTextResource.toTextResource(): TextResource = when (this) { is UiStringTextResource -> StringTextResource(value) is UiIdTextResource -> IdTextResource(value) } /** * Maps `this` [TextResource] instance to a matching [UiTextResource]. * * @see toUiTextResource */ public fun TextResource.toUiTextResource(): UiTextResource = when (this) { is StringTextResource -> UiStringTextResource(value) is IdTextResource -> UiIdTextResource(value) }
0
Kotlin
0
0
7fa1b780762a7cd65809c23dbf1fbf77f82f7036
1,352
text
Apache License 2.0
dsl/src/main/kotlin/com/faendir/awscdkkt/generated/services/budgets/NotificationPropertyDsl.kt
F43nd1r
643,016,506
false
null
package com.faendir.awscdkkt.generated.services.budgets import com.faendir.awscdkkt.AwsCdkDsl import javax.`annotation`.Generated import kotlin.Unit import software.amazon.awscdk.services.budgets.CfnBudget @Generated public fun buildNotificationProperty(initializer: @AwsCdkDsl CfnBudget.NotificationProperty.Builder.() -> Unit): CfnBudget.NotificationProperty = CfnBudget.NotificationProperty.Builder().apply(initializer).build()
1
Kotlin
0
0
e9a0ff020b0db2b99e176059efdb124bf822d754
441
aws-cdk-kt
Apache License 2.0
app/src/main/java/com/cometchat/pro/androiduikit/ui/fragments/RunFragment.kt
romeJG
569,620,476
false
null
package com.cometchat.pro.androiduikit.ui.fragments import android.Manifest import android.os.Build import android.os.Bundle import android.view.View import android.widget.AdapterView import androidx.fragment.app.Fragment import androidx.fragment.app.viewModels import androidx.lifecycle.Observer import androidx.navigation.fragment.findNavController import androidx.recyclerview.widget.LinearLayoutManager import com.cometchat.pro.androiduikit.adapters.RunAdapter import com.cometchat.pro.androiduikit.other.Constants.REQUEST_CODE_LOCATION_PERMISSIONS import com.cometchat.pro.androiduikit.other.SortType import com.cometchat.pro.androiduikit.other.TrackingUtility import com.cometchat.pro.androiduikit.ui.viewmodels.MainViewModel import com.cometchat.pro.androiduikit.R import dagger.hilt.android.AndroidEntryPoint import kotlinx.android.synthetic.main.fragment_run.* import pub.devrel.easypermissions.AppSettingsDialog import pub.devrel.easypermissions.EasyPermissions @AndroidEntryPoint class RunFragment: Fragment(R.layout.fragment_run),EasyPermissions.PermissionCallbacks { private val viewModel: MainViewModel by viewModels() private lateinit var runAdapter: RunAdapter override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) requestPermissions() setupRecyclerView() when(viewModel.sortType){ SortType.DATE -> spFilter.setSelection(0) SortType.RUNNING_TIME -> spFilter.setSelection(1) SortType.DISTANCE -> spFilter.setSelection(2) SortType.AVG_SPEED -> spFilter.setSelection(3) SortType.CALORIES_BURED -> spFilter.setSelection(4) } spFilter.onItemSelectedListener = object : AdapterView.OnItemSelectedListener{ override fun onNothingSelected(parent: AdapterView<*>?) {} override fun onItemSelected( adapterView: AdapterView<*>?, view: View?, pos: Int, id: Long ) { when(pos){ 0 -> viewModel.sortRuns(SortType.DATE) 1 -> viewModel.sortRuns(SortType.RUNNING_TIME) 2 -> viewModel.sortRuns(SortType.DISTANCE) 3 -> viewModel.sortRuns(SortType.AVG_SPEED) 4 -> viewModel.sortRuns(SortType.CALORIES_BURED) } } } viewModel.runs.observe(viewLifecycleOwner, Observer { runAdapter.submitList(it) }) fab.setOnClickListener{ findNavController().navigate(R.id.action_runFragment_to_trackingFragment) } } private fun setupRecyclerView() = rvRuns.apply{ runAdapter = RunAdapter() adapter = runAdapter layoutManager = LinearLayoutManager(requireContext()) } private fun requestPermissions(){ if(TrackingUtility.hasLocationPermissions(requireContext())){ return } if(Build.VERSION.SDK_INT < Build.VERSION_CODES.Q){ EasyPermissions.requestPermissions( this, "You need to accept location permissions to use this app", REQUEST_CODE_LOCATION_PERMISSIONS, Manifest.permission.ACCESS_COARSE_LOCATION, Manifest.permission.ACCESS_FINE_LOCATION ) }else{ EasyPermissions.requestPermissions( this, "You need to accept location permissions to use this app", REQUEST_CODE_LOCATION_PERMISSIONS, Manifest.permission.ACCESS_COARSE_LOCATION, Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_BACKGROUND_LOCATION ) } } override fun onPermissionsDenied(requestCode: Int, perms: MutableList<String>) { /*if user dennied the location permission permanently this will redirect them to * the loation setting of this app*/ if(EasyPermissions.somePermissionPermanentlyDenied(this, perms)){ AppSettingsDialog.Builder(this).build().show() }else{ requestPermissions() } } override fun onPermissionsGranted(requestCode: Int, perms: MutableList<String>) {} override fun onRequestPermissionsResult( requestCode: Int, permissions: Array<out String>, grantResults: IntArray ) { super.onRequestPermissionsResult(requestCode, permissions, grantResults) EasyPermissions.onRequestPermissionsResult(requestCode, permissions, grantResults,this) } }
0
Kotlin
0
0
7d00d199ee63bf4b82746bb7a9fc57958b600793
4,668
CyclingApp-2021
MIT License
src/main/kotlin/com/mercadolivro/exceptions/AuthenticationException.kt
marco-aurelioo
672,391,369
false
null
package com.mercadolivro.exceptions class AuthenticationException(message: String): Exception(message) { }
0
Kotlin
0
0
98d222f1d292be5dc042907fa5f0add0f07bf1fb
108
mercado-livro
MIT License
kserializers-jvm/src/main/kotlin/com/qualifiedcactus/kSerializersJvm/time/TemporalAsLongSerializers.kt
qualified-cactus
667,084,297
false
null
/* * Copyright 2023 qualified-cactus * * 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.qualifiedcactus.kSerializersJvm.time import kotlinx.serialization.KSerializer import kotlinx.serialization.Serializable import kotlinx.serialization.SerializationException import kotlinx.serialization.descriptors.PrimitiveKind import kotlinx.serialization.descriptors.PrimitiveSerialDescriptor import kotlinx.serialization.descriptors.SerialDescriptor import kotlinx.serialization.encoding.Decoder import kotlinx.serialization.encoding.Encoder import java.time.DateTimeException import java.time.Instant /** * Serialize [Instant] to [Long] (Unix time). Data about milliseconds of this [Instant] is ignored. */ object InstantAsUnixTimeSerializer : KSerializer<Instant> { override val descriptor: SerialDescriptor = PrimitiveSerialDescriptor(this::class.qualifiedName!!, PrimitiveKind.LONG) override fun deserialize(decoder: Decoder): Instant { try { return Instant.ofEpochSecond(decoder.decodeLong()) } catch (e: DateTimeException) { throw SerializationException(e) } } override fun serialize(encoder: Encoder, value: Instant) { encoder.encodeLong(value.epochSecond) } } typealias InstantAsUnixTime = @Serializable(InstantAsUnixTimeSerializer::class) Instant
0
Kotlin
0
0
8d71df7e00386a24b0285ca6cd74ac3a307c8147
1,853
kserializers-jvm
Apache License 2.0
src/main/kotlin/com/workos/common/models/Order.kt
workos
419,780,611
false
null
package com.workos.common.models /** * An enumeration for the orders for pagination. */ enum class Order(val type: String) { /** * Ascending Order */ Asc("asc"), /** * Descending Order */ Desc("desc"), }
1
Kotlin
6
9
8be0571a48e643cea2f0c783ddb4c5fa79be1ed5
227
workos-kotlin
MIT License
src/main/kotlin/com/yapp/web2/domain/folder/entity/SharedType.kt
YAPP-19th
399,059,127
false
null
package com.yapp.web2.domain.folder.entity enum class SharedType { EDIT { override fun inversionState(): SharedType { return CLOSED_EDIT } }, BLOCK_EDIT { override fun inversionState(): SharedType { return CLOSED_BLOCK_EDIT } }, CLOSED_EDIT { override fun inversionState(): SharedType { return EDIT } }, CLOSED_BLOCK_EDIT { override fun inversionState(): SharedType { return BLOCK_EDIT } } ; abstract fun inversionState(): SharedType }
10
Kotlin
1
7
ecc6a3da2a66dceb1a25a4cfe9ed699f0325180a
585
Web-Team-2-Backend
Apache License 2.0
smartthings/src/main/java/ke/co/appslab/smartthings/utils/PowerUtils.kt
wangerekaharun
170,553,096
false
null
package ke.co.appslab.smartthings.utils import android.content.Context import ke.co.appslab.smartthings.R import org.threeten.bp.Duration import org.threeten.bp.Instant import org.threeten.bp.LocalDateTime import org.threeten.bp.ZoneId fun getDurationFormatted(timestamp: Long, context: Context): String { val duration = getDifferenceBetweenTimeAndNow(timestamp) val text: String when { duration.toMinutes() < 1 -> text = context.resources.getString(R.string.few_seconds) duration.toMinutes() < 60 -> text = context.resources.getQuantityString( R.plurals.mins_formatted, duration.toMinutes().toInt(), duration.toMinutes().toInt() ) duration.toHours() < 24 -> { val hoursLong = duration.toHours() val minutes = duration.minusHours(hoursLong) val minutesElapsed = minutes.toMinutes() text = context.resources .getQuantityString( R.plurals.hours_formatted, hoursLong.toInt(), hoursLong.toInt() ) + ", " + context.resources .getQuantityString(R.plurals.mins_formatted, minutesElapsed.toInt(), minutesElapsed.toInt()) } else -> { val days = duration.toDays() val hours = duration.minusDays(days) val hoursLong = hours.toHours() val minutes = hours.minusHours(hoursLong) val minutesElapsed = minutes.toMinutes() text = context.resources.getQuantityString(R.plurals.days_formatted, days.toInt(), days.toInt()) + ", " + context.resources .getQuantityString( R.plurals.hours_formatted, hoursLong.toInt(), hoursLong.toInt() ) + ", " + context.resources .getQuantityString(R.plurals.mins_formatted, minutesElapsed.toInt(), minutesElapsed.toInt()) } } return text } private fun getDifferenceBetweenTimeAndNow(timestamp: Long): Duration { val today = LocalDateTime.now() val otherTime = LocalDateTime.ofInstant(Instant.ofEpochMilli(timestamp), ZoneId.systemDefault()) return Duration.between(otherTime, today) }
1
Kotlin
0
4
910329ce6b682ca3cfecd23870090489281a5e9b
2,292
SmartHome
MIT License