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
domain/src/main/kotlin/land/sungbin/apilibrary/domain/usecase/ApiLibraryFetchUseCase.kt
duckie-team
557,999,746
false
{"Kotlin": 115491}
/* * Designed and developed by 2022 <NAME>. * * Licensed under the MIT. * Please see full license: https://github.com/duckie-team/ApiLibrary/blob/trunk/LICENSE */ package land.sungbin.apilibrary.domain.usecase import land.sungbin.apilibrary.domain.repository.ApiLibraryRepository class ApiLibraryFetchUseCase( private val repository: ApiLibraryRepository, ) { suspend operator fun invoke() = runCatching { repository.fetchAllApis().sortedBy { apiItem -> apiItem.name } } }
11
Kotlin
0
4
157f41d6dc98b00c71ee1c2390567a38f495d94f
521
ApiLibrary
MIT License
code/src/main/kotlin/exceptions/GenericPassedFunctionException.kt
HotCL
120,297,748
false
{"TeX": 261407, "Kotlin": 233661, "HCL": 8763, "C++": 3550}
package exceptions /** * It is not allowed to pass a function into another function if the argument-function is generic. * For instance: * var map = (list[num] l, func[num, text] f): list[text] {...} * var something = (T1 i): T2 {...} * :something map * is not allowed. */ class GenericPassedFunctionException(lineNumber: Int, lineIndex: Int, lineText: String) : ParserException(lineNumber, lineIndex, lineText) { override val errorMessage = "You cannot pass a function with generic types into another function." override val helpText = "Make sure that any function passed into another function isn't generic." }
1
TeX
1
4
b6adbc46cc7347aacd45dce5fddffd6fee2d37ac
645
P4-HCL
Apache License 2.0
src/main/kotlin/com/blr19c/falowp/bot/system/plugin/hook/HookTypeEnum.kt
falowp-bot
736,172,318
false
{"Kotlin": 229423, "HTML": 3910}
package com.blr19c.falowp.bot.system.plugin.hook /** * 注入类型 */ enum class HookTypeEnum { /** * 前置 */ BEFORE, /** * 后置 */ AFTER_RETURNING, /** * 异常通知 */ AFTER_THROWING, /** * 最终通知 */ AFTER_FINALLY, /** * 环绕 */ AROUND }
0
Kotlin
0
6
4dfb4620ce2ef529bcf27bc1b719587eb668b56e
315
falowp-bot-system
Apache License 2.0
src/main/kotlin/nieldw/socially/domain/events/RelationshipEvents.kt
MateuszNaKodach
188,601,748
true
{"Kotlin": 23660}
package nieldw.socially.domain.events import nieldw.socially.domain.ContactId import nieldw.socially.domain.RelationshipLevel data class RelationshipLevelUpdatedEvent( val contactId: ContactId, val newRelationshipLevel: RelationshipLevel )
0
Kotlin
0
0
5adbc9f4a1d48a14a6fb2f7a5d845bc6d944810c
257
ContactsAxonDemo
MIT License
library/src/main/java/com/jonapoul/extensions/time/TimeUnits.kt
jonapoul
375,762,483
false
null
package com.jonapoul.extensions.data private const val SECONDS_IN_MS = 1_000L private const val MINUTES_IN_MS = SECONDS_IN_MS * 60L private const val HOURS_IN_MS = MINUTES_IN_MS * 60L private const val DAYS_IN_MS = HOURS_IN_MS * 24L @JvmInline value class Millis(val ms: Long) : Comparable<Millis> { override fun compareTo(other: Millis): Int = ms.compareTo(other.ms) } @JvmInline value class Seconds(val seconds: Long) : Comparable<Seconds> { fun toMillis(): Millis = Millis(seconds * SECONDS_IN_MS) override fun compareTo(other: Seconds): Int = seconds.compareTo(other.seconds) } @JvmInline value class Minutes(val minutes: Long) : Comparable<Minutes> { fun toMillis(): Millis = Millis(minutes * MINUTES_IN_MS) override fun compareTo(other: Minutes): Int = minutes.compareTo(other.minutes) } @JvmInline value class Hours(val hours: Long) : Comparable<Hours> { fun toMillis(): Millis = Millis(hours * HOURS_IN_MS) override fun compareTo(other: Hours): Int = hours.compareTo(other.hours) } @JvmInline value class Days(val days: Long) : Comparable<Days> { fun toMillis(): Millis = Millis(days * DAYS_IN_MS) override fun compareTo(other: Days): Int = days.compareTo(other.days) } inline val Long.ms get() = Millis(this) inline val Int.ms get() = Millis(this.toLong()) inline val Long.sec get() = Seconds(this) inline val Int.sec get() = Seconds(this.toLong()) inline val Long.min get() = Minutes(this) inline val Int.min get() = Minutes(this.toLong()) inline val Long.hr get() = Hours(this) inline val Int.hr get() = Hours(this.toLong()) inline val Long.days get() = Days(this) inline val Int.days get() = Days(this.toLong())
0
Kotlin
0
0
95760476dc741b7a53dba6bc66fe2caed7c5c7b8
1,720
android-extensions
Apache License 2.0
app/src/main/java/com/app/missednotificationsreminder/ApplicationComponent.kt
httpdispatch
45,973,237
false
{"Gradle Kotlin DSL": 4, "Java Properties": 2, "Shell": 1, "Ignore List": 2, "Batchfile": 1, "Markdown": 1, "Proguard": 1, "XML": 84, "Java": 45, "Kotlin": 168}
package com.app.missednotificationsreminder import android.content.Context import dagger.BindsInstance import dagger.Component import dagger.android.AndroidInjector import dagger.android.support.AndroidSupportInjectionModule import javax.inject.Singleton /** * Main component for the application. */ @Singleton @Component( modules = [ AndroidSupportInjectionModule::class, ApplicationModule::class ]) interface ApplicationComponent : AndroidInjector<CustomApplication> { @Component.Factory interface Factory { fun create(@BindsInstance applicationContext: Context): ApplicationComponent } }
46
Kotlin
22
73
8f8c012f6ebc63c8a6262ac0e7afbbd89f798355
656
MissedNotificationsReminder
Apache License 2.0
src/test/kotlin/morpher/model/model/notice/infrastructure/dto/request/RequestBudgetBreakdown.kt
Qlifyw
282,825,141
false
null
package com.procurement.notice.infrastructure.dto.request import com.fasterxml.jackson.annotation.JsonInclude import com.fasterxml.jackson.annotation.JsonProperty import com.procurement.notice.model.ocds.Value data class RequestBudgetBreakdown( @field:JsonProperty("id") @param:JsonProperty("id") val id: String, @field:JsonInclude(JsonInclude.Include.NON_NULL) @field:JsonProperty("description") @param:JsonProperty("description") val description: String?, @field:JsonInclude(JsonInclude.Include.NON_NULL) @field:JsonProperty("amount") @param:JsonProperty("amount") val amount: Value?, @field:JsonInclude(JsonInclude.Include.NON_NULL) @field:JsonProperty("period") @param:JsonProperty("period") val period: RequestPeriod?, @field:JsonInclude(JsonInclude.Include.NON_NULL) @field:JsonProperty("sourceParty") @param:JsonProperty("sourceParty") val sourceParty: RequestOrganizationReference?, @field:JsonInclude(JsonInclude.Include.NON_NULL) @field:JsonProperty("europeanUnionFunding") @param:JsonProperty("europeanUnionFunding") val europeanUnionFunding: RequestEuropeanUnionFunding? )
0
Kotlin
0
0
e799e42b32c3159ff49448aeec22d2df85c6f687
1,137
mionik
MIT License
data-table/src/commonMain/kotlin/com/seanproctor/datatable/TableDecorationScope.kt
sproctor
638,790,475
false
{"Kotlin": 64304}
/* * Copyright 2019 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.seanproctor.datatable /** * Collects the vertical/horizontal offsets of each row/column of a [DataTable] that are available * to a table decoration when its body is executed on a [TableDecorationScope] instance. */ interface TableDecorationScope { val verticalOffsets: List<Int> val horizontalOffsets: List<Int> } internal data class TableDecorationScopeImpl( override val verticalOffsets: List<Int>, override val horizontalOffsets: List<Int> ) : TableDecorationScope
1
Kotlin
11
80
1edea2e5c654405b3a8a386c295ea4c233e98017
1,118
compose-data-table
Apache License 2.0
lib/src/main/java/tech/relaycorp/awaladroid/endpoint/Endpoint.kt
relaycorp
327,584,039
false
{"Kotlin": 224510}
package tech.relaycorp.awaladroid.endpoint /** * Awala endpoint. */ public abstract class Endpoint(public val nodeId: String)
9
Kotlin
1
2
03dd6a0a7c3e2f72dc12a3ea72d4b0d418375e9d
129
awala-endpoint-android
Apache License 2.0
src/main/kotlin/me/modmuss50/fr/mutlipart/PipeMultipart.kt
modmuss50
47,500,948
false
null
package me.modmuss50.fr.mutlipart import cofh.api.energy.IEnergyConnection import cofh.api.energy.IEnergyProvider import cofh.api.energy.IEnergyReceiver import ic2.api.energy.EnergyNet import ic2.api.energy.tile.IEnergySink import ic2.api.energy.tile.IEnergySource import me.modmuss50.fr.FluxedRedstone import me.modmuss50.fr.network.FRNetworkHandler import net.minecraft.block.Block import net.minecraft.block.properties.PropertyBool import net.minecraft.block.properties.PropertyEnum import net.minecraft.block.state.BlockStateContainer import net.minecraft.block.state.IBlockState import net.minecraft.entity.Entity import net.minecraft.entity.player.EntityPlayer import net.minecraft.item.ItemStack import net.minecraft.nbt.NBTTagCompound import net.minecraft.util.EnumFacing import net.minecraft.util.ITickable import net.minecraft.util.ResourceLocation import net.minecraft.util.math.AxisAlignedBB import net.minecraft.util.math.BlockPos import net.minecraft.world.World import net.minecraftforge.common.capabilities.Capability import net.minecraftforge.common.property.ExtendedBlockState import net.minecraftforge.common.property.IExtendedBlockState import net.minecraftforge.common.property.Properties import net.minecraftforge.energy.CapabilityEnergy import net.minecraftforge.energy.IEnergyStorage import reborncore.common.misc.Functions import reborncore.common.misc.vecmath.Vecs3dCube import reborncore.mcmultipart.MCMultiPartMod import reborncore.mcmultipart.microblock.IMicroblock import reborncore.mcmultipart.multipart.ISlottedPart import reborncore.mcmultipart.multipart.Multipart import reborncore.mcmultipart.multipart.MultipartHelper import reborncore.mcmultipart.multipart.PartSlot import reborncore.mcmultipart.raytrace.PartMOP import java.util.* open class PipeMultipart() : Multipart(), ISlottedPart, ITickable, IEnergyStorage { override fun getSlotMask(): EnumSet<PartSlot>? { return EnumSet.of(PartSlot.CENTER) } open fun getPipeType(): PipeTypeEnum { return PipeTypeEnum.REDSTONE } var boundingBoxes = arrayOfNulls<Vecs3dCube>(14) var center = 0.6F var offset = 0.1F var connectedSides = HashMap<EnumFacing, BlockPos>() var ic2ConnectionCache = HashSet<EnumFacing>() var power = 0 init { refreshBounding() } fun refreshBounding() { val centerFirst = (center - offset).toDouble() val thickness = getPipeType().thickness!! val w = (thickness / 16) - 0.5 boundingBoxes[6] = Vecs3dCube(centerFirst.toDouble() - w - 0.03, centerFirst.toDouble() - w - 0.08, centerFirst.toDouble() - w - 0.03, centerFirst.toDouble() + w + 0.08, centerFirst.toDouble() + w + 0.04, centerFirst.toDouble() + w + 0.08) boundingBoxes[6] = Vecs3dCube(centerFirst - w, centerFirst - w, centerFirst - w, centerFirst + w, centerFirst + w, centerFirst + w) var i = 0 for (dir in EnumFacing.values()) { val xMin1 = (if (dir.frontOffsetX < 0) 0.0 else (if (dir.frontOffsetX === 0) centerFirst - w else centerFirst + w)) val xMax1 = (if (dir.frontOffsetX > 0) 1.0 else (if (dir.frontOffsetX === 0) centerFirst + w else centerFirst - w)) val yMin1 = (if (dir.frontOffsetY < 0) 0.0 else (if (dir.frontOffsetY === 0) centerFirst - w else centerFirst + w)) val yMax1 = (if (dir.frontOffsetY > 0) 1.0 else (if (dir.frontOffsetY === 0) centerFirst + w else centerFirst - w)) val zMin1 = (if (dir.frontOffsetZ < 0) 0.0 else (if (dir.frontOffsetZ === 0) centerFirst - w else centerFirst + w)) val zMax1 = (if (dir.frontOffsetZ > 0) 1.0 else (if (dir.frontOffsetZ === 0) centerFirst + w else centerFirst - w)) boundingBoxes[i] = Vecs3dCube(xMin1, yMin1, zMin1, xMax1, yMax1, zMax1) i++ } } override fun addCollisionBoxes(mask: AxisAlignedBB?, list: MutableList<AxisAlignedBB>?, collidingEntity: Entity?) { for (facing in EnumFacing.values()) { if (connectedSides.containsKey(facing)) { if (boundingBoxes[Functions.getIntDirFromDirection(facing)]!!.toAABB().intersectsWith(mask)) { list!!.add(boundingBoxes[Functions.getIntDirFromDirection(facing)]!!.toAABB()) } } } if (boundingBoxes[6]!!.toAABB().intersectsWith(mask)) { list!!.add(boundingBoxes[6]!!.toAABB()) } } override fun addSelectionBoxes(list: MutableList<AxisAlignedBB>?) { for (facing in EnumFacing.values()) { if (connectedSides.containsKey(facing)) { list!!.add(boundingBoxes[Functions.getIntDirFromDirection(facing)]!!.toAABB()) } } list!!.add(boundingBoxes[6]!!.toAABB()) } override fun getModelPath(): ResourceLocation? { return ResourceLocation("fluxedredstone:FRPipe") } fun checkConnections(refreshIC2: Boolean = false) { connectedSides.clear() if (FluxedRedstone.ic2Support && world.isRemote) { if (refreshIC2) { ic2ConnectionCache.clear() } if (nextId > 8192) nextId = 0 // Request a new connection map nextId++ FluxedRedstone.ic2Interface.waiting.forcePut(nextId, this) FRNetworkHandler.instance.sendToServer(FRNetworkHandler.MsgRequestIC2Map(nextId, pos)) } for (facing in EnumFacing.values()) { if (shouldConnectTo(pos, facing)) { connectedSides.put(facing, pos) } } } fun shouldConnectTo(pos: BlockPos?, dir: EnumFacing?): Boolean { if (dir != null) { if (internalShouldConnectTo(pos, dir)) { var otherPipe = getPipe(world, pos!!.offset(dir), dir) if (otherPipe != null && !otherPipe.internalShouldConnectTo(otherPipe.pos, dir.opposite)) { return false } return true } } return false } fun internalShouldConnectTo(pos: BlockPos?, dir: EnumFacing?): Boolean { var slottedPart = PartSlot.getFaceSlot(dir) if (slottedPart != null) { var part = container.getPartInSlot(slottedPart) if (part != null && part is IMicroblock.IFaceMicroblock) { if (!part.isFaceHollow) { return false } } } // if (!OcclusionHelper.occlusionTest(container.parts, this, boundingBoxes[Functions.getIntDirFromDirection(dir)]!!.toAABB())) { // return false // } var otherPipe = getPipe(world, pos!!.offset(dir), dir) if (otherPipe != null) { return true } var tile = world.getTileEntity(pos.offset(dir)) if (tile != null) { if(FluxedRedstone.RFSupport){ if (tile is IEnergyConnection) { if (tile.canConnectEnergy(dir)) { return true } } } if(FluxedRedstone.teslaSupport && FluxedRedstone.teslaManager.canConnect(tile, dir!!)){ return true } if (tile.hasCapability(CapabilityEnergy.ENERGY, dir?.opposite)) { return true } if (FluxedRedstone.ic2Support) { if (world.isRemote && ic2ConnectionCache.contains(dir)) { return true } else if (!world.isRemote) { return FluxedRedstone.ic2Interface.connectable(EnergyNet.instance.getTile(world, pos.offset(dir!!)), dir.opposite) } } } return false } fun getPipe(world: World, blockPos: BlockPos, side: EnumFacing?): PipeMultipart? { val container = MultipartHelper.getPartContainer(world, blockPos) ?: return null if (side != null) { val part = container.getPartInSlot(PartSlot.getFaceSlot(side)) if (part is IMicroblock.IFaceMicroblock && !part.isFaceHollow()) { return null } } val part = container.getPartInSlot(PartSlot.CENTER) if (part is PipeMultipart) { return part } else { return null } } override fun getExtendedState(state: IBlockState?): IBlockState? { var extState = state as IExtendedBlockState return extState.withProperty(UP, shouldConnectTo(pos, EnumFacing.UP))!!.withProperty(DOWN, shouldConnectTo(pos, EnumFacing.DOWN))!!.withProperty(NORTH, shouldConnectTo(pos, EnumFacing.NORTH))!!.withProperty(EAST, shouldConnectTo(pos, EnumFacing.EAST))!!.withProperty(WEST, shouldConnectTo(pos, EnumFacing.WEST))!!.withProperty(SOUTH, shouldConnectTo(pos, EnumFacing.SOUTH)).withProperty(TYPE, getPipeType()) } override fun onAdded() { super.onAdded() checkConnections(true) } override fun onNeighborBlockChange(block: Block?) { super.onNeighborBlockChange(block) checkConnections(true) } override fun createBlockState(): BlockStateContainer? { return ExtendedBlockState(MCMultiPartMod.multipart, arrayOf(TYPE), arrayOf(UP, DOWN, NORTH, EAST, WEST, SOUTH)) } override fun update() { if (world != null) { if (world.totalWorldTime % 80 == 0.toLong()) { checkConnections(false) } if (world.isRemote) { return } for (face in EnumFacing.values()) { if (connectedSides.containsKey(face)) { var offPos = pos.offset(face) var tile = world.getTileEntity(offPos)!! if(tile == null){ continue } //Tesla if(FluxedRedstone.teslaSupport){ FluxedRedstone.teslaManager.update(this, tile, face) } //Forge if (tile.hasCapability(CapabilityEnergy.ENERGY, face.opposite)) { var energy: IEnergyStorage? = tile.getCapability(CapabilityEnergy.ENERGY, face.opposite) var didExtract = false //Let other machines push to FE though the caps // if (energy!!.canExtract()) { // var move = energy.extractEnergy(Math.min(getPipeType().maxRF, getPipeType().maxRF * 4 - power), false) // if (move != 0) { // power += move // didExtract = true // } // // } if (energy!!.canReceive() && !didExtract) { var move = energy.receiveEnergy(Math.min(getPipeType().maxRF, power), false) if (move != 0) { power -= move } } } //RF if (FluxedRedstone.RFSupport && tile is IEnergyConnection) { if (tile is IEnergyProvider) { if (tile.canConnectEnergy(face)) { var move = tile.extractEnergy(face.opposite, Math.min(getPipeType().maxRF, getPipeType().maxRF * 4 - power), false) if (move != 0) { power += move } } } if (tile is IEnergyReceiver) { if (tile.canConnectEnergy(face)) { var move = tile.receiveEnergy(face.opposite, Math.min(getPipeType().maxRF, power), false) if (move != 0) { power -= move } } } } // EU if (FluxedRedstone.ic2Support && !world.isRemote) { // EnergyNet is serverside only val ic2Tile = EnergyNet.instance.getTile(tile.world, tile.pos) if (ic2Tile != null) { if (ic2Tile is IEnergySource && ic2Tile.emitsEnergyTo(IC2Interface.DUMMY_ACCEPTOR, face.opposite)) { var move = Math.min(getPipeType().maxRF.toDouble() / FluxedRedstone.rfPerEU, (getPipeType().maxRF * 4 - power) / FluxedRedstone.rfPerEU) if (move != 0.0 && move <= ic2Tile.offeredEnergy) { ic2Tile.drawEnergy(move) power += Math.round(move * FluxedRedstone.rfPerEU).toInt() } } else if (ic2Tile is IEnergySink && ic2Tile.acceptsEnergyFrom(IC2Interface.DUMMY_EMITTER, face.opposite)) { var move = Math.min(getPipeType().maxRF.toDouble() / FluxedRedstone.rfPerEU, power / FluxedRedstone.rfPerEU) if (move != 0.0 && ic2Tile.demandedEnergy >= move) { var leftover = ic2Tile.injectEnergy(face.opposite, move, 12.0) // What does the 3rd parameter do? Someone tell me! power -= Math.round(move * FluxedRedstone.rfPerEU).toInt() power += Math.floor(leftover * FluxedRedstone.rfPerEU).toInt() } } } } var pipe = getPipe(world, pos.offset(face), face) if (pipe != null) { var averPower = (power + pipe.power) / 2 pipe.power = averPower if(averPower % 2 != 0 && power != 0){ averPower ++ } power = averPower } } } } } override fun writeToNBT(tag: NBTTagCompound?): NBTTagCompound { super.writeToNBT(tag) tag!!.setInteger("power", power) return tag } override fun readFromNBT(tag: NBTTagCompound?) { super.readFromNBT(tag) power = tag!!.getInteger("power") } override fun getPickBlock(player: EntityPlayer?, hit: PartMOP?): ItemStack? { return ItemStack(FluxedRedstone.itemMultiPipe.get(getPipeType())) } override fun getDrops(): MutableList<ItemStack>? { var list = ArrayList<ItemStack>() list.add(ItemStack(FluxedRedstone.itemMultiPipe.get(getPipeType()))) return list } override fun getHardness(hit: PartMOP?): Float { return 1F } companion object { val UP = Properties.toUnlisted(PropertyBool.create("up")) val DOWN = Properties.toUnlisted(PropertyBool.create("down")) val NORTH = Properties.toUnlisted(PropertyBool.create("north")) val EAST = Properties.toUnlisted(PropertyBool.create("east")) val SOUTH = Properties.toUnlisted(PropertyBool.create("south")) val WEST = Properties.toUnlisted(PropertyBool.create("west")) var TYPE = PropertyEnum.create("variant", PipeTypeEnum::class.java) var nextId = -1 } override fun hasCapability(capability: Capability<*>, facing: EnumFacing?): Boolean { if(capability == CapabilityEnergy.ENERGY){ return true } return super.hasCapability(capability, facing) } override fun <T : Any?> getCapability(capability: Capability<T>, facing: EnumFacing?): T? { if(capability == CapabilityEnergy.ENERGY){ return this as T } return super.getCapability(capability, facing) } override fun canExtract(): Boolean { return true } override fun getMaxEnergyStored(): Int { return getPipeType().maxRF * 4 } override fun getEnergyStored(): Int { return power } override fun extractEnergy(maxExtract: Int, simulate: Boolean): Int { if (!canExtract()) return 0 val energyExtracted = Math.min(power, Math.min(getPipeType().maxRF, maxExtract)) if (!simulate) power -= energyExtracted return energyExtracted } override fun receiveEnergy(maxReceive: Int, simulate: Boolean): Int { if (!canReceive()) return 0 val energyReceived = Math.min(maxEnergyStored - power, Math.min(getPipeType().maxRF, maxReceive)) if (!simulate) power += energyReceived return energyReceived } override fun canReceive(): Boolean { return power < maxEnergyStored } }
2
Kotlin
6
14
32bf3ef79ecca9109107faece0149b6ea1a34ce9
17,337
Fluxed-Redstone
MIT License
app/src/main/java/com/evosticlabs/apollo/screens/SplashScreen.kt
idee24
831,997,261
false
{"Kotlin": 80255, "Python": 10120, "Java": 412}
package com.evosticlabs.apollo.screens import androidx.compose.foundation.Image import androidx.compose.foundation.background import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.size import androidx.compose.material3.Text import androidx.compose.runtime.Composable import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.res.painterResource import androidx.compose.ui.text.style.TextAlign import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.sp import androidx.navigation.NavController import com.evosticlabs.apollo.R import com.evosticlabs.apollo.ui.theme.BackgroundBlue import com.evosticlabs.apollo.ui.theme.TextBlue /** *@Created by Yerimah on 22/07/2024. */ @Composable fun SplashScreen() { Box( modifier = Modifier .fillMaxSize() .background(color = BackgroundBlue) ) { Image( painter = painterResource(id = R.drawable.splash_logo), contentDescription = "Splash Logo", modifier = Modifier .size(height = 300.dp, width = 700.dp) .align(Alignment.Center) ) Text( text = "Copyright © 2016 MIT. All rights reserved.", textAlign = TextAlign.Center, color = TextBlue, fontSize = 10.sp, modifier = Modifier .align(Alignment.BottomCenter) .padding(32.dp) ) } }
0
Kotlin
0
0
1dd54d17e9f6b202020b10cff361f44ed15ee133
1,656
apollo_android
MIT License
room/room-compiler-processing/src/main/java/androidx/room/compiler/processing/XTypeElement.kt
RikkaW
389,105,112
false
null
/* * Copyright (C) 2020 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package androidx.room.compiler.processing import com.squareup.javapoet.ClassName interface XTypeElement : XHasModifiers, XElement, XMemberContainer { /** * The qualified name of the Class/Interface. */ val qualifiedName: String /** * The qualified name of the package that contains this element. */ val packageName: String /** * SimpleName of the type converted to String. * * @see [javax.lang.model.element.Element.getSimpleName] */ val name: String /** * The type represented by this [XTypeElement]. */ override val type: XType /** * The super type of this element if it represents a class. */ val superType: XType? /** * Javapoet [ClassName] of the type. */ override val className: ClassName /** * The [XTypeElement] that contains this [XTypeElement] if it is an inner class/interface. */ val enclosingTypeElement: XTypeElement? override val fallbackLocationText: String get() = qualifiedName /** * Returns `true` if this [XTypeElement] represents an interface */ fun isInterface(): Boolean /** * Returns `true` if this [XTypeElement] represents a Kotlin functional interface, * i.e. marked with the keyword `fun` */ fun isFunctionalInterface(): Boolean /** * Returns `true` if this [XTypeElement] represents an ordinary class. ie not an enum, object, * annotation, interface, or other type of specialty class. */ fun isClass(): Boolean /** * Returns `true` if this [XTypeElement] represents a Kotlin data class */ fun isDataClass(): Boolean /** * Returns `true` if this [XTypeElement] represents a Kotlin value class */ fun isValueClass(): Boolean /** * Returns `true` if this [XTypeElement] represents a class with the Kotlin `expect` keyword */ fun isExpect(): Boolean /** * Returns `true` if this [XTypeElement] represents a Kotlin annotation class or a Java * annotation type. */ fun isAnnotationClass(): Boolean /** * Returns `true` if this [XTypeElement] is a non-companion `object` in Kotlin */ fun isKotlinObject(): Boolean /** * Returns `true` if this [XTypeElement] is declared as a Kotlin `companion object` */ fun isCompanionObject(): Boolean /** * Fields declared in this type * includes all instance/static fields in this */ fun getDeclaredFields(): List<XFieldElement> /** * All fields, including private supers. * Room only ever reads fields this way. */ fun getAllFieldsIncludingPrivateSupers(): Sequence<XFieldElement> { return collectFieldsIncludingPrivateSupers(this) } /** * Returns the primary constructor for the type, if it exists. * * Note that this only exists for classes declared in Kotlin. */ fun findPrimaryConstructor(): XConstructorElement? /** * methods declared in this type * includes all instance/static methods in this */ fun getDeclaredMethods(): List<XMethodElement> /** * Methods declared in this type and its parents * includes all instance/static methods in this (including private) * includes all instance/static methods in parent CLASS if they are accessible from this (e.g. * not private). * does not include static methods in parent interfaces */ fun getAllMethods(): Sequence<XMethodElement> { return collectAllMethods(this) } /** * Instance methods declared in this and supers * include non private instance methods * also includes non-private instance methods from supers */ fun getAllNonPrivateInstanceMethods(): Sequence<XMethodElement> { return getAllMethods().filter { !it.isPrivate() && !it.isStatic() } } /** * Returns the list of constructors in this type element */ fun getConstructors(): List<XConstructorElement> /** * List of interfaces implemented by this class */ fun getSuperInterfaceElements(): List<XTypeElement> /** * Returns the list of all classes nested directly within this class, including companion * objects. */ fun getEnclosedTypeElements(): List<XTypeElement> }
6
null
937
7
6d53f95e5d979366cf7935ad7f4f14f76a951ea5
5,000
androidx
Apache License 2.0
android/app/src/main/kotlin/com/example/scorekeeper/MainActivity.kt
He-Martijn
450,554,690
false
{"Dart": 8335, "Swift": 404, "Kotlin": 128, "Objective-C": 38}
package com.example.scorekeeper import io.flutter.embedding.android.FlutterActivity class MainActivity: FlutterActivity() { }
0
Dart
0
0
60f58ca5b7b6d6f2dc8bd459e13e2f4dfda42c26
128
scorekeeper
MIT License
14-interfaces-enums/src/interfaces/Family.kt
johnehunt
286,785,922
false
null
package interfaces class Family { // ... fun add(org: Organizer) { // ... } }
0
Kotlin
0
3
9dfc541c93b13d7e7aee289408103538faa23134
98
kotlin-book
Apache License 2.0
src/main/kotlin/uk/gov/justice/digital/hmpps/prisonerfromnomismigration/csip/CSIPMappingService.kt
ministryofjustice
452,734,022
false
{"Kotlin": 2526024, "Mustache": 1803, "Dockerfile": 1377}
package uk.gov.justice.digital.hmpps.prisonerfromnomismigration.csip import kotlinx.coroutines.reactive.awaitFirstOrDefault import org.springframework.beans.factory.annotation.Qualifier import org.springframework.core.ParameterizedTypeReference import org.springframework.stereotype.Service import org.springframework.web.reactive.function.client.WebClient import org.springframework.web.reactive.function.client.WebClientResponseException import org.springframework.web.reactive.function.client.awaitBodilessEntity import reactor.core.publisher.Mono import uk.gov.justice.digital.hmpps.prisonerfromnomismigration.helpers.awaitBodyOrNullWhenNotFound import uk.gov.justice.digital.hmpps.prisonerfromnomismigration.integration.history.CreateMappingResult import uk.gov.justice.digital.hmpps.prisonerfromnomismigration.integration.history.DuplicateErrorResponse import uk.gov.justice.digital.hmpps.prisonerfromnomismigration.integration.history.MigrationMapping import uk.gov.justice.digital.hmpps.prisonerfromnomismigration.nomismappings.model.CSIPFactorMappingDto import uk.gov.justice.digital.hmpps.prisonerfromnomismigration.nomismappings.model.CSIPMappingDto @Service class CSIPMappingService(@Qualifier("mappingApiWebClient") webClient: WebClient) : MigrationMapping<CSIPMappingDto>(domainUrl = "/mapping/csip", webClient) { suspend fun getCSIPReportByNomisId(nomisCSIPReportId: Long): CSIPMappingDto? = webClient.get() .uri("/mapping/csip/nomis-csip-id/{nomisCSIPReportId}", nomisCSIPReportId) .retrieve() .awaitBodyOrNullWhenNotFound() suspend fun deleteCSIPReportMappingByDPSId(dpsCSIPReportId: String) { webClient.delete() .uri("/mapping/csip/dps-csip-id/{dpsCSIPReportId}", dpsCSIPReportId) .retrieve() .awaitBodilessEntity() } suspend fun getCSIPFactorByNomisId(nomisCSIPFactorId: Long): CSIPFactorMappingDto? = webClient.get() .uri("/mapping/csip/factors/nomis-csip-factor-id/{nomisCSIPFactorId}", nomisCSIPFactorId) .retrieve() .awaitBodyOrNullWhenNotFound() suspend fun deleteCSIPFactorMappingByDPSId(dpsCSIPFactorId: String) { webClient.delete() .uri("/mapping/csip/factors/dps-csip-factor-id/{dpsCSIPFactorId}", dpsCSIPFactorId) .retrieve() .awaitBodilessEntity() } suspend fun createCSIPFactorMapping( mapping: CSIPFactorMappingDto, ): CreateMappingResult<CSIPFactorMappingDto> { return webClient.post() .uri("/mapping/csip/factors") .bodyValue( mapping, ) .retrieve() .bodyToMono(Unit::class.java) .map { CreateMappingResult<CSIPFactorMappingDto>() } .onErrorResume(WebClientResponseException.Conflict::class.java) { Mono.just(CreateMappingResult(it.getResponseBodyAs(object : ParameterizedTypeReference<DuplicateErrorResponse<CSIPFactorMappingDto>>() {}))) } .awaitFirstOrDefault(CreateMappingResult()) } }
1
Kotlin
1
2
c2246f3388fdbd46f6dba28c26940048607f9704
2,917
hmpps-prisoner-from-nomis-migration
MIT License
app/src/main/java/com/example/sally/rxjavakotlin/ui/home/HomeActivity.kt
sallySalem
121,965,570
false
null
package com.example.sally.rxjavakotlin.ui.home import android.app.Activity import android.content.Intent import android.os.Bundle import android.support.v4.content.ContextCompat import android.support.v4.widget.SwipeRefreshLayout import android.support.v7.widget.LinearLayoutManager import android.view.View import android.view.View.* import android.widget.Toast import com.example.sally.rxjavakotlin.R import com.example.sally.rxjavakotlin.data.model.RepositoryModel import com.example.sally.rxjavakotlin.ui.base.BaseActivity import com.example.sally.rxjavakotlin.ui.details.DetailsActivity import dagger.android.AndroidInjection import kotlinx.android.synthetic.main.activity_home.* import javax.inject.Inject class HomeActivity : BaseActivity(), HomeView { @Inject lateinit var homePresenter: HomePresenter var repositoryAdapter: RepositoryAdapter? = null override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) initView(); homePresenter.onCreate(); } private fun initView() { swipe_container.setColorSchemeColors( ContextCompat.getColor(this, android.R.color.holo_blue_dark), ContextCompat.getColor(this, android.R.color.holo_red_dark), ContextCompat.getColor(this, android.R.color.holo_green_dark), ContextCompat.getColor(this, android.R.color.holo_orange_dark)) swipe_container.isRefreshing = true swipe_container.setOnRefreshListener(pullToRefreshListener) } override fun initRepositoryList(repositoriesList: ArrayList<RepositoryModel>) { //init recyclerView repositoryAdapter = RepositoryAdapter(repositoriesList, itemClickListener) val linearLayoutManager = LinearLayoutManager(this) rv_repositories_list.layoutManager = linearLayoutManager rv_repositories_list.adapter = repositoryAdapter } override fun loadRepositoriesList() { tv_empty_data.visibility = GONE rv_repositories_list.visibility = VISIBLE repositoryAdapter?.notifyDataSetChanged() } override fun hideSwipeRefreshLayout() { swipe_container.isRefreshing = false } override fun hideRepositoriesList() { rv_repositories_list.visibility = View.GONE tv_empty_data.visibility = View.VISIBLE } override fun showErrorMessage() { Toast.makeText(this, R.string.mesg_server_error, Toast.LENGTH_LONG).show() } override fun navigateToRepositoryDetails(repositoryModel: RepositoryModel) { DetailsActivity.open(this, repositoryModel) } private val pullToRefreshListener = SwipeRefreshLayout.OnRefreshListener { homePresenter.onRepositoryListRefresh() } /* Listener to handle RecyclerView item select */ private val itemClickListener = object : OnItemSelectedListener { override fun onClick(view: View, position: Int) { homePresenter.onItemClick(position) } } override fun initializeDagger() { AndroidInjection.inject(this) } override fun initializePresenter() { super.presenter = homePresenter homePresenter.view = this } override var layoutId: Int = R.layout.activity_home companion object { fun open(activity: Activity) { val intent = Intent(activity, HomeActivity::class.java) activity.startActivity(intent) } } }
0
Kotlin
0
0
6e80ce733fb2e98350e86006a6f2fb3957739f46
3,474
Rx-MVP-kotlin
Apache License 2.0
fresco-bridge/src/main/kotlin/drivechain/bridge/fresco/FrescoBridgeModule.kt
InkApplications
106,982,918
false
null
package drivechain.bridge.fresco import dagger.Module import dagger.Provides import dagger.multibindings.IntoSet import drivechain.lifecycle.application.ApplicationLifecycleSubscriber import okhttp3.OkHttpClient @Module class FrescoBridgeModule { @Provides @IntoSet fun fresco(okHttpClient: OkHttpClient): ApplicationLifecycleSubscriber = FrescoInitializer(okHttpClient) }
1
Kotlin
2
3
070d7d77291272f60cff9650c7c6e5240c6b58f1
378
DriveChain
MIT License
compass/src/main/java/com/arch/jonnyhsia/compass/facade/IRouteInterceptor.kt
jonnyhsia
179,116,275
false
null
package com.arch.jonnyhsia.compass.facade /** * 原生页跳转拦截 (对应 @Route 注解中的 Interceptor) * 优先级: 低 * * 主要用于用户登录等条件拦截, 跳转到其他页面 */ interface IRouteInterceptor { fun intercept(intent: ProcessableIntent) }
0
Kotlin
0
3
8b38a99fcadf38d11065839b55904a60b4c1b630
206
Compass
MIT License
junit5/src/test/kotlin/com/toasttab/gradle/testkit/TestKitIntegrationTest.kt
open-toast
694,203,503
false
{"Kotlin": 44971, "Java": 66}
/* * Copyright (c) 2024 Toast Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.toasttab.gradle.testkit import org.junit.jupiter.api.Test import strikt.api.expectThat import strikt.assertions.contains @TestKit(gradleVersions = ["8.6", "8.7"]) class TestKitIntegrationTest { @Test fun `basic project`(project: TestProject) { expectThat( project.build("dependencies").output ).contains("compileClasspath") } @ParameterizedWithGradleVersions fun `basic parameterized project`(project: TestProject) { val output = project.build("dependencies").output expectThat( output ).contains("compileClasspath") } }
0
Kotlin
0
1
af30e72f2f2f50c9d7f54c6e3acc388b6b7d9e17
1,217
testkit-plugins
Apache License 2.0
library/src/main/java/com/dino/lib/dialog/progress/PriorityProgressDialog.kt
dino9
124,686,433
false
null
package com.dino.lib.dialog.progress import android.app.Dialog import android.app.ProgressDialog import android.content.Context import android.content.DialogInterface import android.os.Bundle import androidx.fragment.app.Fragment import androidx.fragment.app.FragmentManager import com.dino.lib.dialog.BaseDialogBuilder import com.dino.lib.dialog.BaseDialogFragment import com.dino.lib.dialog.PriorityMode import com.dino.lib.dialog.PriorityMode.LOW import com.dino.lib.dialog.R /** * Created by dineshkumar.m on 11/03/18. */ class PriorityProgressDialog : BaseDialogFragment() { private var mTitle: CharSequence? = null private var mMessage: CharSequence? = null private val mIsIndeterminate = false override var priority: PriorityMode = LOW private set override var customTag: String? = null private set private var mIsTouchOutsideCancel = true private var mIsCircleProgress: Boolean = false private var mOnDismissListener: DialogInterface.OnDismissListener? = null private var mOnCancelListener: DialogInterface.OnCancelListener? = null private var mOnShowListener: DialogInterface.OnShowListener? = null override fun onCreateDialog(savedInstanceState: Bundle?): Dialog { if (mIsCircleProgress) { //View view = getActivity().getLayoutInflater().inflate(R.layout.ui_progress_dialog, null); // val dialog = Dialog(activity, R.style.ProgressDialogPrimary) //dialog.setContentView(view);` dialog.setCanceledOnTouchOutside(mIsTouchOutsideCancel) return dialog } else { if (mMessage == null) { mMessage = getString(R.string.dialog_loading) } val progressDialog = ProgressDialog(activity) progressDialog.setMessage(mMessage) if (mTitle != null) progressDialog.setTitle(mTitle) progressDialog.isIndeterminate = mIsIndeterminate return progressDialog } } override fun onActivityCreated(savedInstanceState: Bundle?) { super.onActivityCreated(savedInstanceState) if (arguments == null) { throw IllegalArgumentException("use ProgressDialogBuilder to construct this dialog") } } override fun build(initialBuilder: Builder): Builder? { return null } class ProgressDialogBuilder( context: Context, fragmentManager: FragmentManager ) : BaseDialogBuilder<ProgressDialogBuilder>( context, fragmentManager, PriorityProgressDialog::class.java ) { private var mTitle: CharSequence? = null private var mMessage: CharSequence? = null private var mIsCircleProgress: Boolean = false private var mOnDismissListener: DialogInterface.OnDismissListener? = null private var mOnCancelListener: DialogInterface.OnCancelListener? = null private var mOnShowListener: DialogInterface.OnShowListener? = null override fun self(): ProgressDialogBuilder { return this } fun setTitle(titleResourceId: Int): ProgressDialogBuilder { mTitle = mContext.getString(titleResourceId) return this } fun setTitle(title: CharSequence): ProgressDialogBuilder { mTitle = title return this } fun setMessage(messageResourceId: Int): ProgressDialogBuilder { mMessage = mContext.getString(messageResourceId) return this } fun setMessage(message: CharSequence): ProgressDialogBuilder { mMessage = message return this } override fun setPriority(priority: PriorityMode): ProgressDialogBuilder { mPriority = priority super.setPriority(priority) return this } override fun getPriority(): PriorityMode { return mPriority } override fun setTag(tag: String): ProgressDialogBuilder { mTag = tag super.setTag(mTag) return this } override fun getTag(): String { return mTag } fun setCircleProgress(isCircle: Boolean): ProgressDialogBuilder { mIsCircleProgress = isCircle return this } fun setTouchOutsideCancel(touchOutsideCancel: Boolean): ProgressDialogBuilder { mCancelableOnTouchOutside = touchOutsideCancel return this } override fun setCancelable(cancelable: Boolean): ProgressDialogBuilder { mCancelable = cancelable return this } fun setOnDismissListener(onDismissListener: DialogInterface.OnDismissListener): ProgressDialogBuilder { mOnDismissListener = onDismissListener return this } fun setOnCancelListener(onCancelListener: DialogInterface.OnCancelListener): ProgressDialogBuilder { mOnCancelListener = onCancelListener return this } fun setOnShowListener(onShowListener: DialogInterface.OnShowListener): ProgressDialogBuilder { mOnShowListener = onShowListener return this } override fun build(): BaseDialogFragment { return showAllowingStateLoss() } private fun showAllowingStateLoss(): PriorityProgressDialog { val fragment = create() initFragment(fragment) fragment.showAllowingStateLoss(mFragmentManager, mTag) return fragment } private fun create(): PriorityProgressDialog { val args = Bundle() val fragment = Fragment.instantiate(mContext, mClass.name, args) as PriorityProgressDialog args.putBoolean(ARG_CANCELABLE_ON_TOUCH_OUTSIDE, mCancelableOnTouchOutside) args.putBoolean(ARG_USE_DARK_THEME, mUseDarkTheme) args.putBoolean(ARG_USE_LIGHT_THEME, mUseLightTheme) if (mTargetFragment != null) { fragment.setTargetFragment(mTargetFragment, mRequestCode) } else { args.putInt(ARG_REQUEST_CODE, mRequestCode) } fragment.isCancelable = mCancelable return fragment } private fun initFragment(fragment: PriorityProgressDialog) { fragment.mTitle = this.mTitle fragment.mMessage = this.mMessage fragment.customTag = this.mTag fragment.priority = this.mPriority fragment.mIsTouchOutsideCancel = this.mCancelableOnTouchOutside fragment.mIsCircleProgress = this.mIsCircleProgress fragment.priority = this.mPriority fragment.mOnDismissListener = this.mOnDismissListener fragment.mOnCancelListener = this.mOnCancelListener fragment.mOnShowListener = this.mOnShowListener } } companion object { fun createBuilder( context: Context, fragmentManager: FragmentManager ): ProgressDialogBuilder { return ProgressDialogBuilder(context, fragmentManager) } } }
1
Kotlin
1
4
6c1f81d18fc504aa9ff20b748d32bb6d1d412272
6,471
PriorityDialog
The Unlicense
baselib/src/main/java/com/wukangjie/baselib/base/fragment/BaseMainFragment.kt
wukangjie
188,939,915
false
null
package com.wukangjie.baselib.base.fragment import android.content.Context /** * tab页中,带有画面跳转功能的画面的容器fragment */ open class BaseMainFragment : BaseFragment() { protected var _mBackToFirstListener: OnBackToFirstListener? = null override fun onAttach(context: Context) { super.onAttach(context) if (context is OnBackToFirstListener) { _mBackToFirstListener = context } else { throw RuntimeException("$context must implement OnBackToFirstListener") } } override fun onDetach() { super.onDetach() _mBackToFirstListener = null } /** * 处理回退事件 * * @return */ override fun onBackPressedSupport(): Boolean { if (childFragmentManager.backStackEntryCount > 1) { popChild() } else { if (shouldFinishActivity()) { // 如果是 第一个Fragment 则退出app _mActivity!!.finish() } else { // 如果不是,则回到第一个Fragment _mBackToFirstListener!!.onBackToFirstFragment() } } return true } protected fun shouldFinishActivity(): Boolean { return false } interface OnBackToFirstListener { fun onBackToFirstFragment() } }
0
Kotlin
0
0
cc59ded26f2c1a7bef65cd63ccf22d461625e0a7
1,292
K-MVVM
Apache License 2.0
src/main/kotlin/samples/Analytics.kt
frozencure
253,615,832
false
null
package samples import com.github.frozencure.helix.HelixClient import com.github.frozencure.helix.auth.model.OAuthCredentials import kotlinx.coroutines.runBlocking import java.time.Duration import java.time.Instant fun getExtensionAnalytics() { val credentials = OAuthCredentials("<OAuth access token here>", "<App Client ID here>") val helixClient = HelixClient(credentials) runBlocking { print( helixClient.analytics.getExtensionAnalytics(12345, Instant.now() - Duration.ofDays(1), Instant.now()) .resources ) } } fun getGameAnalytics() { val credentials = OAuthCredentials("<OAuth access token here>", "<App Client ID here>") val helixClient = HelixClient(credentials) runBlocking { print( helixClient.analytics.getGameAnalytics(12345, Instant.now() - Duration.ofDays(1), Instant.now()) .resources ) } }
3
Kotlin
3
17
285d49ad2ddf19f8ba2d0973ca17a40168fac914
930
twitch-client
MIT License
src/main/kotlin/uk/gov/justice/digital/hmpps/jobsboard/api/jsonprofile/JobsBoardProfileDTO.kt
ministryofjustice
775,484,528
false
{"Kotlin": 43059, "Dockerfile": 1146}
package uk.gov.justice.digital.hmpps.jobsboard.data.jsonprofile import io.swagger.v3.oas.annotations.media.Schema import uk.gov.justice.digital.hmpps.jobsboard.api.entity.JobsBoardProfile import java.time.LocalDateTime data class JobsBoardProfileDTO( @Schema(description = "This is the ID of the inmate ", name = "offenderId", pattern = "^[A-Z]\\d{4}[A-Z]{2}\$", required = true) val offenderId: String, @Schema(description = "This is the prision ID of the inmate ", name = "prisonId") var prisonId: String? = null, @Schema(description = "This is the prision Name of the inmate ", name = "prisonName") var prisonName: String? = null, @Schema(description = "This is the person who creates the Job.Even though it is passed from front end it wil be automatically set to the right value at the time of record creation ", name = "createdBy", required = true) var createdBy: String, @Schema(description = "This is the creation date and time of Job record .Even though it is passed from front end it wil be automatically set to the right value at the time of record creation ", name = "createdDateTime", required = true) var createdDateTime: LocalDateTime, @Schema(description = "This is the person who modifies the Job.Even though it is passed from front end it wil be automatically set to the right value at the time of record modification ", name = "modifiedBy", required = true) var modifiedBy: String, @Schema(description = "This is the schema version used", name = "schemaVersion", required = false) var schemaVersion: String? = null, ) { constructor(profileEntity: JobsBoardProfile) : this( offenderId = profileEntity.offenderId, prisonId = profileEntity.prisonId, prisonName = profileEntity.prisonName, createdBy = profileEntity.createdBy.toString(), createdDateTime = profileEntity.createdDateTime!!, modifiedBy = profileEntity.modifiedBy!!, schemaVersion = profileEntity.schemaVersion, ) }
0
Kotlin
0
0
7fbc4be4c6506ed2b3c8b8513535274ae8f34add
1,963
hmpps-jobs-board-api
MIT License
app/src/main/java/com/josdem/authenticator/state/ApplicationState.kt
josdem
729,984,698
false
{"Kotlin": 21248}
package com.josdem.authenticator.state object ApplicationState { private val memory = HashMap<String, Any>() fun storeValue( key: String, value: Any, ) { memory[key] = value } fun getValue(key: String): Any? { return memory[key] } }
3
Kotlin
2
1
042de84f37e25de72965f2616f74b9872ce2e0cd
292
android-authenticator
Apache License 2.0
testing/src/main/java/org/oppia/android/testing/lightweightcheckpointing/ExplorationCheckpointTestHelper.kt
harshpatel63
330,956,278
true
{"Kotlin": 5294875, "Starlark": 152600, "Java": 32457, "Shell": 8681}
package org.oppia.android.testing.lightweightcheckpointing import androidx.lifecycle.Observer import androidx.test.platform.app.InstrumentationRegistry import com.google.common.truth.Truth.assertThat import org.mockito.ArgumentCaptor import org.mockito.Captor import org.mockito.Mock import org.mockito.Mockito.atLeastOnce import org.mockito.Mockito.reset import org.mockito.Mockito.verify import org.mockito.MockitoAnnotations import org.oppia.android.app.model.ExplorationCheckpoint import org.oppia.android.app.model.ProfileId import org.oppia.android.domain.exploration.lightweightcheckpointing.ExplorationCheckpointController import org.oppia.android.testing.threading.TestCoroutineDispatchers import org.oppia.android.util.data.AsyncResult import org.oppia.android.util.data.DataProvider import org.oppia.android.util.data.DataProviders.Companion.toLiveData import javax.inject.Inject import javax.inject.Singleton const val FAKE_EXPLORATION_ID_1 = "fake_exploration_id_1" const val FAKE_EXPLORATION_TITLE_1 = "Fake exploration title_1" const val FAKE_EXPLORATION_ID_2 = "fake_exploration_id_2" const val FAKE_EXPLORATION_TITLE_2 = "Fake exploration title_2" /** This helper class allows storing are retrieving exploration checkpoints for testing. */ @Singleton class ExplorationCheckpointTestHelper @Inject constructor( private val explorationCheckpointController: ExplorationCheckpointController, private val testCoroutineDispatchers: TestCoroutineDispatchers ) { init { MockitoAnnotations.initMocks(this) } @Mock lateinit var mockLiveDataObserver: Observer<AsyncResult<Any?>> @Captor lateinit var liveDataResultCaptor: ArgumentCaptor<AsyncResult<Any?>> @Mock lateinit var mockExplorationCheckpointObserver: Observer<AsyncResult<ExplorationCheckpoint>> @Captor lateinit var explorationCheckpointCaptor: ArgumentCaptor<AsyncResult<ExplorationCheckpoint>> /** * Saves a fake checkpoint for explorationId [FAKE_EXPLORATION_ID_1] for the specified profileId. * The size of the checkpoint saved here is 67 bytes. */ fun saveFakeExplorationCheckpoint(internalProfileId: Int) { val checkpoint = createFakeExplorationCheckpoint(FAKE_EXPLORATION_TITLE_1, timestamp = 0L) val saveCheckpointDataProvider = explorationCheckpointController.recordExplorationCheckpoint( ProfileId.newBuilder().setInternalId(internalProfileId).build(), FAKE_EXPLORATION_ID_1, checkpoint ) verifyProviderFinishesWithSuccess(saveCheckpointDataProvider) } /** * Saves two fake checkpoints, one for [FAKE_EXPLORATION_ID_1] and the other for * [FAKE_EXPLORATION_ID_2]. Together both the exploration take up 137 bytes of storage space. */ fun saveTwoFakeExplorationCheckpoint(internalProfileId: Int) { var checkpoint = createFakeExplorationCheckpoint(FAKE_EXPLORATION_TITLE_1, timestamp = 0L) var saveCheckpointDataProvider = explorationCheckpointController.recordExplorationCheckpoint( ProfileId.newBuilder().setInternalId(internalProfileId).build(), FAKE_EXPLORATION_ID_1, checkpoint ) verifyProviderFinishesWithSuccess(saveCheckpointDataProvider) checkpoint = createFakeExplorationCheckpoint(FAKE_EXPLORATION_TITLE_2, timestamp = 1L) saveCheckpointDataProvider = explorationCheckpointController.recordExplorationCheckpoint( ProfileId.newBuilder().setInternalId(internalProfileId).build(), FAKE_EXPLORATION_ID_2, checkpoint ) verifyProviderFinishesWithSuccess(saveCheckpointDataProvider) } /** * Function to verify progress for the exploration specified by the explorationId exists in the * checkpoint database of the specified profileId. */ fun verifyExplorationProgressIsSaved(internalProfileId: Int, explorationId: String) { val retrieveCheckpointDataProvider = explorationCheckpointController.retrieveExplorationCheckpoint( ProfileId.newBuilder().setInternalId(internalProfileId).build(), explorationId ) InstrumentationRegistry.getInstrumentation().runOnMainSync { reset(mockExplorationCheckpointObserver) retrieveCheckpointDataProvider.toLiveData().observeForever(mockExplorationCheckpointObserver) } // Provide time for the data provider to finish. testCoroutineDispatchers.runCurrent() // Verify that the observer was called, and that the result was success. InstrumentationRegistry.getInstrumentation().runOnMainSync { verify(mockExplorationCheckpointObserver, atLeastOnce()) .onChanged(explorationCheckpointCaptor.capture()) assertThat(explorationCheckpointCaptor.value.isSuccess()).isTrue() } } /** * Function to verify no progress for the exploration specified by the explorationId exists in the * checkpoint database of the specified profileId. */ fun verifyExplorationProgressIsDeleted(internalProfileId: Int, explorationId: String) { val retrieveCheckpointDataProvider = explorationCheckpointController.retrieveExplorationCheckpoint( ProfileId.newBuilder().setInternalId(internalProfileId).build(), explorationId ) InstrumentationRegistry.getInstrumentation().runOnMainSync { reset(mockExplorationCheckpointObserver) retrieveCheckpointDataProvider.toLiveData().observeForever(mockExplorationCheckpointObserver) } // Provide time for the data provider to finish. testCoroutineDispatchers.runCurrent() // Verify that the observer was called, and that the result was failure. InstrumentationRegistry.getInstrumentation().runOnMainSync { verify(mockExplorationCheckpointObserver, atLeastOnce()) .onChanged(explorationCheckpointCaptor.capture()) assertThat(explorationCheckpointCaptor.value.isFailure()).isTrue() assertThat(explorationCheckpointCaptor.value.getErrorOrNull()).isInstanceOf( ExplorationCheckpointController.ExplorationCheckpointNotFoundException::class.java ) } } private fun createFakeExplorationCheckpoint( explorationTitle: String, timestamp: Long ): ExplorationCheckpoint { return ExplorationCheckpoint.newBuilder() .setExplorationTitle(explorationTitle) .setPendingStateName("fake_state_0") .setTimestampOfFirstCheckpoint(timestamp) .setStateIndex(0) .build() } private fun verifyProviderFinishesWithSuccess(dataProvider: DataProvider<Any?>) { // Ensure interactions with LiveData occur on the main thread for Espresso compatibility. InstrumentationRegistry.getInstrumentation().runOnMainSync { reset(mockLiveDataObserver) dataProvider.toLiveData().observeForever(mockLiveDataObserver) } // Provide time for the data provider to finish. testCoroutineDispatchers.runCurrent() // Verify that the observer was called, and that the result was successful. InstrumentationRegistry.getInstrumentation().runOnMainSync { verify(mockLiveDataObserver, atLeastOnce()) .onChanged(liveDataResultCaptor.capture()) assertThat(liveDataResultCaptor.value.isSuccess()).isTrue() } } }
0
Kotlin
0
1
c42dca3eb6c69821784063fb18621a81473735ce
7,104
oppia-android
Apache License 2.0
app/src/main/java/com/dee/popularmovies/ui/movies/ui/MovieDetailsFragment.kt
DeeAndroid
611,321,790
false
null
package com.dee.popularmovies.ui.movies.ui import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.fragment.app.Fragment import androidx.fragment.app.activityViewModels import androidx.lifecycle.lifecycleScope import com.dee.popularmovies.data.viewmodel.MainViewModel import com.dee.popularmovies.databinding.FragmentMovieDetailsBinding import com.dee.popularmovies.utils.loadImage import kotlinx.coroutines.Job class MovieDetailsFragment : Fragment() { private lateinit var binding: FragmentMovieDetailsBinding private val viewModel: MainViewModel by activityViewModels() private lateinit var movieDetailJob: Job override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View? { // Inflate the layout for this fragment binding = FragmentMovieDetailsBinding.inflate(inflater, container, false) binding.back.setOnClickListener { activity?.onBackPressedDispatcher?.onBackPressed() } movieDetailJob = viewLifecycleOwner.lifecycleScope.launchWhenCreated { viewModel._movieDetail.observe(viewLifecycleOwner) { binding.movieDetails = it it?.posterPath?.let { path -> binding.moviecover.loadImage("https://image.tmdb.org/t/p/w500/$path") } } } return binding.root } }
0
Kotlin
0
0
bcbaf3d0318821e2a26b03358d70c9e0aee542a3
1,493
TmdbMovies
MIT License
app/src/main/java/com/dee/popularmovies/ui/movies/ui/MovieDetailsFragment.kt
DeeAndroid
611,321,790
false
null
package com.dee.popularmovies.ui.movies.ui import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.fragment.app.Fragment import androidx.fragment.app.activityViewModels import androidx.lifecycle.lifecycleScope import com.dee.popularmovies.data.viewmodel.MainViewModel import com.dee.popularmovies.databinding.FragmentMovieDetailsBinding import com.dee.popularmovies.utils.loadImage import kotlinx.coroutines.Job class MovieDetailsFragment : Fragment() { private lateinit var binding: FragmentMovieDetailsBinding private val viewModel: MainViewModel by activityViewModels() private lateinit var movieDetailJob: Job override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View? { // Inflate the layout for this fragment binding = FragmentMovieDetailsBinding.inflate(inflater, container, false) binding.back.setOnClickListener { activity?.onBackPressedDispatcher?.onBackPressed() } movieDetailJob = viewLifecycleOwner.lifecycleScope.launchWhenCreated { viewModel._movieDetail.observe(viewLifecycleOwner) { binding.movieDetails = it it?.posterPath?.let { path -> binding.moviecover.loadImage("https://image.tmdb.org/t/p/w500/$path") } } } return binding.root } }
0
Kotlin
0
0
bcbaf3d0318821e2a26b03358d70c9e0aee542a3
1,493
TmdbMovies
MIT License
sam-java-core/src/test/kotlin/software/elborai/api/models/AgentDeleteParamsTest.kt
DefinitelyATestOrg
787,029,081
false
{"Kotlin": 712664, "Shell": 1286, "Dockerfile": 305}
// File generated from our OpenAPI spec by Stainless. package software.elborai.api.models import org.assertj.core.api.Assertions.assertThat import org.junit.jupiter.api.Test import software.elborai.api.models.* class AgentDeleteParamsTest { @Test fun createAgentDeleteParams() { AgentDeleteParams.builder().id("string").build() } @Test fun getPathParam() { val params = AgentDeleteParams.builder().id("string").build() assertThat(params).isNotNull // path param "id" assertThat(params.getPathParam(0)).isEqualTo("string") // out-of-bound path param assertThat(params.getPathParam(1)).isEqualTo("") } }
1
Kotlin
0
0
31707be70bc9f98f8659f918bd036b91f6e7f137
687
sam-java
Apache License 2.0
app/src/main/java/id/android/basics/compose/ui/components/CommonUI.kt
budioktaviyan
565,297,433
false
null
package id.android.basics.compose.ui.components import androidx.compose.foundation.background import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.Spacer import androidx.compose.foundation.layout.height import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.size import androidx.compose.foundation.layout.width import androidx.compose.material.ContentAlpha import androidx.compose.material.Divider import androidx.compose.material.Icon import androidx.compose.material.LocalContentAlpha import androidx.compose.material.MaterialTheme import androidx.compose.material.Text import androidx.compose.material.icons.Icons import androidx.compose.material.icons.filled.ChevronRight import androidx.compose.runtime.Composable import androidx.compose.runtime.CompositionLocalProvider import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.graphics.Color import androidx.compose.ui.res.stringResource import androidx.compose.ui.semantics.clearAndSetSemantics import androidx.compose.ui.semantics.contentDescription import androidx.compose.ui.unit.dp import id.android.basics.compose.R import java.text.DecimalFormat /** * A row representing the basic information of an Account */ @Composable fun AccountRow(name: String, number: Int, amount: Float, color: Color) { val subtitleStringResource = stringResource(R.string.account_redacted) BaseRow( color = color, title = name, subtitle = "$subtitleStringResource ${AccountDecimalFormat.format(number)}", amount = amount, negative = false ) } /** * A row representing the basic information of a Bill */ @Composable fun BillRow(name: String, due: String, amount: Float, color: Color) { BaseRow( color = color, title = name, subtitle = "Due $due", amount = amount, negative = true ) } @Composable private fun BaseRow(color: Color, title: String, subtitle: String, amount: Float, negative: Boolean) { val dollarSign = if (negative) "–$ " else "$ " val formattedAmount = formatAmount(amount) Row( modifier = Modifier .height(68.dp) .clearAndSetSemantics { contentDescription = "$title account ending in ${subtitle.takeLast(4)}, current balance $dollarSign$formattedAmount" }, verticalAlignment = Alignment.CenterVertically ) { val typography = MaterialTheme.typography AccountIndicator( color = color, modifier = Modifier ) Spacer(Modifier.width(12.dp)) Column(Modifier) { Text( text = title, style = typography.body1 ) CompositionLocalProvider(LocalContentAlpha provides ContentAlpha.medium) { Text( text = subtitle, style = typography.subtitle1 ) } } Spacer(Modifier.weight(1f)) Row(horizontalArrangement = Arrangement.SpaceBetween) { Text( text = dollarSign, style = typography.h6, modifier = Modifier.align(Alignment.CenterVertically) ) Text( text = formattedAmount, style = typography.h6, modifier = Modifier.align(Alignment.CenterVertically) ) } Spacer(Modifier.width(16.dp)) CompositionLocalProvider(LocalContentAlpha provides ContentAlpha.medium) { Icon( imageVector = Icons.Filled.ChevronRight, contentDescription = null, modifier = Modifier .padding(end = 12.dp) .size(24.dp) ) } } ComposerDivider() } /** * A vertical colored line that is used in a [BaseRow] to differentiate accounts */ @Composable private fun AccountIndicator(color: Color, modifier: Modifier = Modifier) { Spacer( modifier .size( 4.dp, 36.dp ) .background(color = color) ) } @Composable fun ComposerDivider(modifier: Modifier = Modifier) { Divider( color = MaterialTheme.colors.background, thickness = 1.dp, modifier = modifier ) } private val AccountDecimalFormat = DecimalFormat("####") private val AmountDecimalFormat = DecimalFormat("#,###.##") fun formatAmount(amount: Float): String = AmountDecimalFormat.format(amount) /** * Used with accounts and bills to create the animated circle */ fun <E> List<E>.extractProportions(selector: (E) -> Float): List<Float> { val total = this.sumOf { selector(it).toDouble() } return this.map { (selector(it).div(total)).toFloat() } }
0
Kotlin
0
1
fd9c6e3f64a99eb74abc498665bbe54ea6204d48
4,558
compose-basics
MIT License
plugins/search-everywhere-ml/ranking/core/test/com/intellij/searchEverywhereMl/ranking/core/features/SearchEverywhereStateFeaturesProviderTest.kt
JetBrains
2,489,216
false
null
package com.intellij.searchEverywhereMl.ranking.features import com.intellij.ide.actions.searcheverywhere.FileSearchEverywhereContributor import com.intellij.ide.actions.searcheverywhere.SearchEverywhereManagerImpl import com.intellij.searchEverywhereMl.ranking.features.SearchEverywhereStateFeaturesProvider.Companion.QUERY_CONTAINS_ABBREVIATIONS_DATA_KEY import com.intellij.searchEverywhereMl.ranking.features.SearchEverywhereStateFeaturesProvider.Companion.QUERY_CONTAINS_PATH_DATA_KEY import com.intellij.testFramework.fixtures.BasePlatformTestCase class SearchEverywhereStateFeaturesProviderTest : BasePlatformTestCase() { private val featuresProvider = SearchEverywhereStateFeaturesProvider() fun `test contains path feature exists in all tab`() { val features = featuresProvider.getSearchStateFeatures(SearchEverywhereManagerImpl.ALL_CONTRIBUTORS_GROUP_ID, "foo", project, null, false) assertNotNull(features.findFeature(QUERY_CONTAINS_PATH_DATA_KEY)) } fun `test contains path feature exists in files tab`() { val features = featuresProvider.getSearchStateFeatures(FileSearchEverywhereContributor::class.java.simpleName, "foo", project, null, false) assertNotNull(features.findFeature(QUERY_CONTAINS_PATH_DATA_KEY)) } fun `test contains path feature is false when no path specified`() { val features = featuresProvider.getSearchStateFeatures(FileSearchEverywhereContributor::class.java.simpleName, "foo", project, null, false) val containsPath = features.getFeatureValue(QUERY_CONTAINS_PATH_DATA_KEY) assertFalse(containsPath) } fun `test contains path feature is false when nothing before slash`() { val features = featuresProvider.getSearchStateFeatures(FileSearchEverywhereContributor::class.java.simpleName, "/foo", project, null, false) val containsPath = features.getFeatureValue(QUERY_CONTAINS_PATH_DATA_KEY) assertFalse(containsPath) } fun `test contains path feature is true with one slash`() { val features = featuresProvider.getSearchStateFeatures(FileSearchEverywhereContributor::class.java.simpleName, "bar/foo", project, null, false) val containsPath = features.getFeatureValue(QUERY_CONTAINS_PATH_DATA_KEY) assertTrue(containsPath) } fun `test contains path feature is true with multiple slashes`() { val features = featuresProvider.getSearchStateFeatures(FileSearchEverywhereContributor::class.java.simpleName, "/x/bar/foo", project, null, false) val containsPath = features.getFeatureValue(QUERY_CONTAINS_PATH_DATA_KEY) assertTrue(containsPath) } fun `test is abbreviation is true for uppercase queries`() { val features = featuresProvider.getSearchStateFeatures(FileSearchEverywhereContributor::class.java.simpleName, "FPCDP", project, null, false) assertTrue(features.getFeatureValue(QUERY_CONTAINS_ABBREVIATIONS_DATA_KEY)) } fun `test is abbreviation is true for uppercase queries with spaces in between letters`() { val features = featuresProvider.getSearchStateFeatures(FileSearchEverywhereContributor::class.java.simpleName, "F P CDP", project, null, false) assertTrue(features.getFeatureValue(QUERY_CONTAINS_ABBREVIATIONS_DATA_KEY)) } fun `test is abbreviation is false for mixed case queries`() { val features = featuresProvider.getSearchStateFeatures(FileSearchEverywhereContributor::class.java.simpleName, "FPrCaDaP", project, null, false) assertFalse(features.getFeatureValue(QUERY_CONTAINS_ABBREVIATIONS_DATA_KEY)) } fun `test is abbreviation is false for mixed case queries with spaces in between word chunks`() { val features = featuresProvider.getSearchStateFeatures(FileSearchEverywhereContributor::class.java.simpleName, "Fe Pr CaDaP", project, null, false) assertFalse(features.getFeatureValue(QUERY_CONTAINS_ABBREVIATIONS_DATA_KEY)) } fun `test is abbreviation is false for lowercase queries`() { val features = featuresProvider.getSearchStateFeatures(FileSearchEverywhereContributor::class.java.simpleName, "fpcdp", project, null, false) assertFalse(features.getFeatureValue(QUERY_CONTAINS_ABBREVIATIONS_DATA_KEY)) } fun `test is uppercase is true for uppercase queries`() { val features = featuresProvider.getSearchStateFeatures(FileSearchEverywhereContributor::class.java.simpleName, "FPCDP", project, null, false) assertTrue(features.getFeatureValue(QUERY_CONTAINS_ABBREVIATIONS_DATA_KEY)) } fun `test is uppercase is true for uppercase queries with spaces in between letters`() { val features = featuresProvider.getSearchStateFeatures(FileSearchEverywhereContributor::class.java.simpleName, "F P CDP", project, null, false) assertTrue(features.getFeatureValue(QUERY_CONTAINS_ABBREVIATIONS_DATA_KEY)) } fun `test is uppercase is false for mixed case queries`() { val features = featuresProvider.getSearchStateFeatures(FileSearchEverywhereContributor::class.java.simpleName, "Fe Pr CaDaP", project, null, false) assertFalse(features.getFeatureValue(QUERY_CONTAINS_ABBREVIATIONS_DATA_KEY)) } fun `test is uppercase is false for lowercase queries`() { val features = featuresProvider.getSearchStateFeatures(FileSearchEverywhereContributor::class.java.simpleName, "fpcdp", project, null, false) assertFalse(features.getFeatureValue(QUERY_CONTAINS_ABBREVIATIONS_DATA_KEY)) } }
284
null
5162
16,707
def6433a5dd9f0a984cbc6e2835d27c97f2cb5f0
5,339
intellij-community
Apache License 2.0
app/src/main/java/com/mathroda/messengerclone/ui/channels/utils/CustomChannel.kt
MathRoda
516,097,712
false
null
package com.erdi.messengerclone.ui.channels.utils import androidx.compose.foundation.ExperimentalFoundationApi import androidx.compose.foundation.layout.* import androidx.compose.foundation.lazy.LazyColumn import androidx.compose.foundation.lazy.LazyListState import androidx.compose.foundation.lazy.items import androidx.compose.material.ExperimentalMaterialApi import androidx.compose.runtime.Composable import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.unit.dp import com.erdi.messengerclone.ui.channels.components.DefaultChannelsLoadingMoreIndicator import com.erdi.messengerclone.ui.channels.components.MessengerCloneScrollerChannel import io.getstream.chat.android.client.models.Channel import io.getstream.chat.android.client.models.User import io.getstream.chat.android.compose.handlers.LoadMoreHandler import io.getstream.chat.android.compose.state.channels.list.ChannelItemState import io.getstream.chat.android.compose.state.channels.list.ChannelsState import io.getstream.chat.android.compose.ui.components.LoadingFooter @ExperimentalMaterialApi @ExperimentalFoundationApi @Composable fun CustomChannel( channelsState: ChannelsState, lazyListState: LazyListState, onLastItemReached: () -> Unit, onSearchClick: () -> Unit, searchState: Boolean, modifier: Modifier = Modifier, contentPadding: PaddingValues = PaddingValues(), helperContent: @Composable BoxScope.() -> Unit = {}, loadingMoreContent: @Composable () -> Unit = { DefaultChannelsLoadingMoreIndicator() }, itemContent: @Composable (ChannelItemState) -> Unit, divider: @Composable () -> Unit, currentUser: User?, onChannelClick: (Channel) -> Unit, ) { val (_, isLoadingMore, endOfChannels, channelItems) = channelsState Box(modifier = modifier) { LazyColumn( modifier = Modifier.fillMaxSize(), state = lazyListState, horizontalAlignment = Alignment.CenterHorizontally, contentPadding = contentPadding ) { item { DummyFirstChannelItem() if (!searchState) { CustomSearchInputButton( onClick = onSearchClick ) MessengerCloneScrollerChannel( channelsState = channelsState , currentUser = currentUser, onChannelClick = onChannelClick ) } } items( items = channelItems, key = { it.channel.cid } ) { item -> itemContent(item) divider() } if (isLoadingMore) { item { loadingMoreContent() } } } if (!endOfChannels && channelItems.isNotEmpty()) { LoadMoreHandler(lazyListState) { onLastItemReached() } } } } /** * The default loading more indicator. */ @Composable internal fun DefaultChannelsLoadingMoreIndicator() { LoadingFooter(modifier = Modifier.fillMaxWidth()) } /** * Represents an almost invisible dummy item to be added to the top of the list. * * If the list is scrolled to the top and a channel new item is added or moved * to the position above, then the list will automatically autoscroll to it. */ @Composable private fun DummyFirstChannelItem() { Box( modifier = Modifier .height(1.dp) .fillMaxWidth() ) }
1
null
12
96
f6bb09079f35e14e7fceb1bfbad1fa49e9c58daa
3,766
Messenger-clone
Apache License 2.0
network/src/main/java/com/patrykkosieradzki/theanimalapp/network/services/AnimalApiService.kt
k0siara
340,592,684
false
{"Kotlin": 96140}
package com.patrykkosieradzki.theanimalapp.network.services import com.patrykkosieradzki.theanimalapp.network.model.AnimalResponse import com.patrykkosieradzki.theanimalapp.network.utils.ApiResult import retrofit2.http.GET import retrofit2.http.Query interface AnimalApiService { @GET("images/search") suspend fun getRandomAnimal(): ApiResult<List<RandomAnimalResponse>> @GET("images/search") suspend fun getAnimals( @Query("page") page: Int, @Query("limit") limit: Int, @Query("order") order: String = DEFAULT_ANIMAL_ORDER ): ApiResult<List<AnimalResponse>> @GET("images/search") suspend fun getAnimal( @Query("image_url") imageUrl: String ): ApiResult<AnimalResponse> companion object { const val DEFAULT_ANIMAL_ORDER = "desc" } } data class RandomAnimalResponse( val url: String )
0
Kotlin
0
1
3398c01fd62e4a9bfa7033d7736e7e70745a22ec
874
TheAnimalApp
Apache License 2.0
src/main/kotlin/com/dpforge/ibmpc/cpu/instruction/JCXZ.kt
int02h
426,397,665
false
{"Kotlin": 257077, "Assembly": 189629, "Shell": 90}
package com.dpforge.ibmpc.cpu.instruction import com.dpforge.ibmpc.cpu.CPU import com.dpforge.ibmpc.cpu.timing.Timing.ConditionalTiming object JCXZ { fun short(cpu: CPU): Int = cpu.jumpShortIf(ConditionalTiming.JCC) { cx == 0 } }
0
Kotlin
0
3
eff28d661750ca511dafae930fe2b911f8d7b5d9
237
ibm-pc
MIT License
detekt-gradle-plugin/src/main/kotlin/io/gitlab/arturbosch/detekt/DetektPlugin.kt
detekt
71,729,669
false
null
package io.gitlab.arturbosch.detekt import dev.detekt.gradle.plugin.CONFIGURATION_DETEKT_PLUGINS import dev.detekt.gradle.plugin.DetektBasePlugin import dev.detekt.gradle.plugin.DetektBasePlugin.Companion.CONFIG_DIR_NAME import dev.detekt.gradle.plugin.DetektBasePlugin.Companion.CONFIG_FILE import dev.detekt.gradle.plugin.internal.DetektAndroidCompilations import dev.detekt.gradle.plugin.internal.DetektJvmCompilations import dev.detekt.gradle.plugin.internal.DetektKmpJvmCompilations import dev.detekt.gradle.plugin.internal.conventionCompat import io.gitlab.arturbosch.detekt.extensions.DetektExtension import io.gitlab.arturbosch.detekt.internal.DetektPlain import org.gradle.api.Incubating import org.gradle.api.Plugin import org.gradle.api.Project import org.gradle.api.provider.ProviderFactory import java.net.URL import java.util.jar.Manifest class DetektPlugin : Plugin<Project> { override fun apply(project: Project) { project.pluginManager.apply(DetektBasePlugin::class.java) val extension = project.extensions.getByType(DetektExtension::class.java) configurePluginDependencies(project, extension) setTaskDefaults(project, extension) project.registerDetektPlainTask(extension) project.registerDetektJvmTasks(extension) val enableAndroidTasks = !project.providers .gradleProperty(DETEKT_ANDROID_DISABLED_PROPERTY) .getOrElse("false") .toBoolean() if (enableAndroidTasks) { project.registerDetektAndroidTasks(extension) } val enableMppTasks = !project.providers .gradleProperty(DETEKT_MULTIPLATFORM_DISABLED_PROPERTY) .getOrElse("false") .toBoolean() if (enableMppTasks) { project.registerDetektMultiplatformTasks(extension) } project.registerGenerateConfigTask(extension) } private fun Project.registerDetektJvmTasks(extension: DetektExtension) { plugins.withId("org.jetbrains.kotlin.jvm") { DetektJvmCompilations.registerTasks(project, extension) } } private fun Project.registerDetektMultiplatformTasks(extension: DetektExtension) { plugins.withId("org.jetbrains.kotlin.multiplatform") { DetektKmpJvmCompilations.registerTasks(project, extension) } } private fun Project.registerDetektAndroidTasks(extension: DetektExtension) { plugins.withId("kotlin-android") { DetektAndroidCompilations.registerTasks(project, extension) DetektAndroidCompilations.linkTasks(project, extension) } } private fun Project.registerDetektPlainTask(extension: DetektExtension) { DetektPlain(this).registerTasks(extension) } private fun Project.registerGenerateConfigTask(extension: DetektExtension) { val detektGenerateConfigSingleExecution = project.gradle.sharedServices.registerIfAbsent( "DetektGenerateConfigSingleExecution", DetektGenerateConfigTask.SingleExecutionBuildService::class.java ) { spec -> spec.maxParallelUsages.set(1) } tasks.register(GENERATE_CONFIG, DetektGenerateConfigTask::class.java) { it.configFile.convention { extension.config.lastOrNull() ?: project.file("$rootDir/$CONFIG_DIR_NAME/$CONFIG_FILE") } it.usesService(detektGenerateConfigSingleExecution) } } private fun configurePluginDependencies(project: Project, extension: DetektExtension) { project.configurations.create(CONFIGURATION_DETEKT) { configuration -> configuration.isVisible = false configuration.isTransitive = true configuration.description = "The $CONFIGURATION_DETEKT dependencies to be used for this project." configuration.isCanBeResolved = true configuration.isCanBeConsumed = false configuration.defaultDependencies { dependencySet -> val version = extension.toolVersion.get() dependencySet.add(project.dependencies.create("io.gitlab.arturbosch.detekt:detekt-cli:$version")) } } } private fun setTaskDefaults(project: Project, extension: DetektExtension) { project.tasks.withType(Detekt::class.java).configureEach { task -> task.detektClasspath.conventionCompat(project.configurations.getAt(CONFIGURATION_DETEKT)) task.pluginClasspath.conventionCompat(project.configurations.getAt(CONFIGURATION_DETEKT_PLUGINS)) val reportName = if (task.name.startsWith(DETEKT_TASK_NAME) && task.name != DETEKT_TASK_NAME) { task.name.removePrefix(DETEKT_TASK_NAME).decapitalize() } else { task.name } task.reports.html { report -> report.required.convention(DEFAULT_REPORT_ENABLED_VALUE) report.outputLocation.convention(extension.reportsDir.file("$reportName.html")) } task.reports.md { report -> report.required.convention(DEFAULT_REPORT_ENABLED_VALUE) report.outputLocation.convention(extension.reportsDir.file("$reportName.md")) } task.reports.sarif { report -> report.required.convention(DEFAULT_REPORT_ENABLED_VALUE) report.outputLocation.convention(extension.reportsDir.file("$reportName.sarif")) } task.reports.xml { report -> report.required.convention(DEFAULT_REPORT_ENABLED_VALUE) report.outputLocation.convention(extension.reportsDir.file("$reportName.xml")) } } project.tasks.withType(DetektCreateBaselineTask::class.java).configureEach { task -> task.detektClasspath.conventionCompat(project.configurations.getAt(CONFIGURATION_DETEKT)) task.pluginClasspath.conventionCompat(project.configurations.getAt(CONFIGURATION_DETEKT_PLUGINS)) } project.tasks.withType(DetektGenerateConfigTask::class.java).configureEach { task -> task.detektClasspath.conventionCompat(project.configurations.getAt(CONFIGURATION_DETEKT)) task.pluginClasspath.conventionCompat(project.configurations.getAt(CONFIGURATION_DETEKT_PLUGINS)) } } internal companion object { internal const val DETEKT_TASK_NAME = "detekt" internal const val BASELINE_TASK_NAME = "detektBaseline" private const val GENERATE_CONFIG = "detektGenerateConfig" val defaultExcludes = listOf("build/") val defaultIncludes = listOf("**/*.kt", "**/*.kts") internal const val DETEKT_ANDROID_DISABLED_PROPERTY = "detekt.android.disabled" internal const val DETEKT_MULTIPLATFORM_DISABLED_PROPERTY = "detekt.multiplatform.disabled" internal const val DEFAULT_REPORT_ENABLED_VALUE = true } } internal const val CONFIGURATION_DETEKT = "detekt" internal fun ProviderFactory.isWorkerApiEnabled(): Boolean = gradleProperty("detekt.use.worker.api").getOrElse("false") == "true" @Incubating fun getSupportedKotlinVersion(): String = DetektPlugin::class.java.classLoader.getResources("META-INF/MANIFEST.MF") .asSequence() .mapNotNull { runCatching { readVersion(it) }.getOrNull() } .first() private fun readVersion(resource: URL): String? = resource.openConnection() .apply { useCaches = false } .getInputStream() .use { Manifest(it).mainAttributes.getValue("KotlinImplementationVersion") }
190
null
772
6,253
c5d7ed3da2824534d0e15f8404ad4f1c59fb553c
7,636
detekt
Apache License 2.0
src/main/kotlin/io/github/markgregg/expression/exceptions/IncompatibleTypeException.kt
markgregg
565,568,268
false
{"Kotlin": 194364}
package io.github.markgregg.expression.exceptions class IncompatibleTypeException(message: String) : RuntimeException(message)
1
Kotlin
0
0
f28ccf2d0dc344fc4f5ea887da466c68e270afbf
127
adaptable-expression
Apache License 2.0
app/src/main/java/com/github/rooneyandshadows/lightbulb/easyrecyclerviewdemo/demo/views/SelectableRecyclerView.kt
RooneyAndShadows
424,519,760
false
{"Kotlin": 226361}
package com.github.rooneyandshadows.lightbulb.easyrecyclerviewdemo.demo.views import android.content.Context import android.util.AttributeSet import com.github.rooneyandshadows.lightbulb.easyrecyclerview.EasyRecyclerView import com.github.rooneyandshadows.lightbulb.easyrecyclerviewdemo.demo.views.adapters.SelectableAdapter import com.github.rooneyandshadows.lightbulb.easyrecyclerviewdemo.demo.models.DemoModel import com.github.rooneyandshadows.lightbulb.recycleradapters.abstraction.EasyRecyclerAdapter class SelectableRecyclerView @JvmOverloads constructor( context: Context, attrs: AttributeSet? = null, ) : EasyRecyclerView<DemoModel>(context, attrs) { override val adapter: SelectableAdapter get() = super.adapter as SelectableAdapter init { setAdapter(SelectableAdapter()) } }
0
Kotlin
3
9
bfb334b627e1b52644c7f9c1ff222a046a757fea
824
lightbulb-easyrecyclerview
Apache License 2.0
app/src/main/java/com/example/digionebank/testes/TesteFuncionarioGerente.kt
JonathasLopes
393,851,255
false
null
package com.example.digionebank.testes import com.example.digionebank.Gerente fun main() { val joao = Gerente("Joao", "123.456.789-78", 5000.0, "123") ImprimeRelatorioFuncionario.imprime(joao); TesteAutenticacao().autentica(joao) }
0
Kotlin
0
0
970ca98efdcfe035e3341b6f67fa4192e10a610d
247
DigiOneBank
MIT License
app/src/main/java/com/devpulsar/mlkitexample/MainActivity.kt
barbariwan
746,848,429
false
{"Kotlin": 7165}
package com.devpulsar.mlkitexample import android.os.Bundle import androidx.appcompat.app.AppCompatActivity import androidx.fragment.app.commit import com.devpulsar.mlkitexample.fragment.BarcodeScannerFragment class MainActivity : AppCompatActivity(R.layout.activity_main) { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) if (savedInstanceState == null) { supportFragmentManager.commit { setReorderingAllowed(true) add(R.id.fragment_container_view, BarcodeScannerFragment()) } } } }
0
Kotlin
0
0
8f3e758c6e81e3751ebfcb705b4a3b8916b8111e
615
MLKitExample
MIT License
challenge/flutter/all_samples/widgets_defaulttextstyletransition_1/android/app/src/main/kotlin/com/example/widgets_defaulttextstyletransition_1/MainActivity.kt
davidzou
5,868,257
false
{"C++": 11211831, "CMake": 9084708, "Dart": 1111417, "HTML": 1009596, "Swift": 548973, "C": 446637, "Java": 193711, "Kotlin": 80348, "Objective-C": 20634, "Shell": 6476, "AIDL": 6075, "Dockerfile": 1384, "Groovy": 368}
package com.example.widgets_defaulttextstyletransition_1 import io.flutter.embedding.android.FlutterActivity class MainActivity: FlutterActivity() { }
1
C++
1
4
1060f6501c432510e164578d4af60a49cd5ed681
153
WonderingWall
Apache License 2.0
src/main/java/com/statsig/androidsdk/Store.kt
statsig-io
357,712,105
false
null
package com.statsig.androidsdk import android.content.SharedPreferences import androidx.core.content.edit import com.google.gson.Gson import com.google.gson.annotations.SerializedName import com.google.gson.reflect.TypeToken private const val INITIALIZE_RESPONSE_KEY: String = "Statsig.INITIALIZE_RESPONSE" private const val STICKY_USER_EXPERIMENTS_KEY: String = "Statsig.STICKY_USER_EXPERIMENTS" private const val STICKY_DEVICE_EXPERIMENTS_KEY: String = "Statsig.STICKY_DEVICE_EXPERIMENTS" private data class StickyUserExperiments( @SerializedName("user_id") val userID: String?, @SerializedName("values") val experiments: MutableMap<String, APIDynamicConfig>, ) internal class Store (userID: String?, private val sharedPrefs: SharedPreferences) { private val gson = Gson() private var cache: InitializeResponse private var stickyDeviceExperiments: MutableMap<String, APIDynamicConfig> private lateinit var stickyUserExperiments: StickyUserExperiments init { val cachedResponse = StatsigUtil.getFromSharedPrefs(sharedPrefs, INITIALIZE_RESPONSE_KEY) val cachedDeviceValues = StatsigUtil.getFromSharedPrefs(sharedPrefs, STICKY_DEVICE_EXPERIMENTS_KEY) cache = InitializeResponse(mapOf(), mapOf(), false, 0) if (cachedResponse != null) { cache = gson.fromJson(cachedResponse, InitializeResponse::class.java) } stickyDeviceExperiments = mutableMapOf() if (cachedDeviceValues != null) { val type = object : TypeToken<MutableMap<String, APIDynamicConfig>>() {}.type stickyDeviceExperiments = gson.fromJson(cachedDeviceValues, type) ?: stickyDeviceExperiments } loadAndResetStickyUserValues(userID) } fun loadAndResetStickyUserValues(newUserID: String?) { val cachedUserValues = StatsigUtil.getFromSharedPrefs(sharedPrefs, STICKY_USER_EXPERIMENTS_KEY) stickyUserExperiments = StickyUserExperiments(newUserID, mutableMapOf()) if (cachedUserValues != null) { stickyUserExperiments = gson.fromJson(cachedUserValues, StickyUserExperiments::class.java) ?: stickyUserExperiments if (stickyUserExperiments.userID != newUserID) { stickyUserExperiments = StickyUserExperiments(newUserID, mutableMapOf()) StatsigUtil.saveStringToSharedPrefs(sharedPrefs, STICKY_USER_EXPERIMENTS_KEY, gson.toJson(stickyUserExperiments)) } } } fun save(data: InitializeResponse) { cache = data StatsigUtil.saveStringToSharedPrefs(sharedPrefs, INITIALIZE_RESPONSE_KEY, gson.toJson(cache)) } fun checkGate(gateName: String): APIFeatureGate { val hashName = StatsigUtil.getHashedString(gateName) if ( cache.featureGates == null || !cache.featureGates!!.containsKey(hashName)) { return APIFeatureGate(gateName, false, "") } return cache.featureGates!![hashName] ?: APIFeatureGate(gateName, false, "") } fun getConfig(configName: String): DynamicConfig { val hashName = StatsigUtil.getHashedString(configName) if ( cache.configs == null || !cache.configs!!.containsKey(hashName)) { return DynamicConfig(configName) } var config = cache.configs!![hashName] return DynamicConfig(configName, config?.value ?: mapOf(), config?.ruleID ?: "", config?.secondaryExposures ?: arrayOf()) } fun getExperiment(experimentName: String, keepDeviceValue: Boolean): DynamicConfig { val hashName = StatsigUtil.getHashedString(experimentName) val stickyValue = stickyUserExperiments.experiments[hashName] ?: stickyDeviceExperiments[hashName] val latestValue = cache.configs?.get(hashName) // If flag is false, or experiment is NOT active, simply remove the sticky experiment value, and return the latest value if (!keepDeviceValue || latestValue?.isExperimentActive == false) { removeStickyValue(hashName) return getConfig(experimentName) } // If sticky value is already in cache, use it if (stickyValue != null) { return DynamicConfig(experimentName, stickyValue?.value ?: mapOf(), stickyValue?.ruleID ?: "", stickyValue?.secondaryExposures ?: arrayOf()) } // If the user has NOT been exposed before, and is in this active experiment, then we save the value as sticky if (latestValue != null && latestValue.isExperimentActive && latestValue.isUserInExperiment) { if (latestValue?.isDeviceBased) { stickyDeviceExperiments[hashName] = latestValue } else { stickyUserExperiments.experiments[hashName] = latestValue } cacheStickyValues() } return getConfig(experimentName) } private fun removeStickyValue(key: String) { stickyUserExperiments.experiments.remove(key) stickyDeviceExperiments.remove(key) cacheStickyValues() } private fun cacheStickyValues() { StatsigUtil.saveStringToSharedPrefs(sharedPrefs, STICKY_USER_EXPERIMENTS_KEY, gson.toJson(stickyUserExperiments)) StatsigUtil.saveStringToSharedPrefs(sharedPrefs, STICKY_DEVICE_EXPERIMENTS_KEY, gson.toJson(stickyDeviceExperiments)) } }
0
Kotlin
1
3
bbc05ef820cb9e97e8fae4b858bf490b1cec15a6
5,394
android-sdk
ISC License
app/src/main/kotlin/zenith/Faults.kt
DavidMacDonald11
674,797,283
false
null
package zenith import java.io.File interface Faultable { val faultPosition: UIntRange } class Fault(label: String, val type: Char, val obj: Faultable, msg: String) { val message = "$label ${mapType()}: $msg" private fun mapType() = when(type) { 'W' -> "Warning" 'E' -> "Error" 'F' -> "Failure" else -> throw IllegalArgumentException() } } interface FaultResult { val faults: List<Fault> val errored get() = faults.any { it.type in listOf('E', 'F') } val failed get() = faults.any { it.type == 'F' } } fun printFaults( filePath: String, faults: List<Fault>, printWarnings: Boolean = false ): Boolean { if(faults.isEmpty()) return false if(!printWarnings && faults.all { it.type == 'W' }) return false File(filePath).useLines { val lines = it.toList().map { "$it\n" } println("Faults in $filePath:") for(fault in faults) { println(fault.message) printFileLines(lines, fault.obj.faultPosition) } } return true } private fun printFileLines(lines: List<String>, position: UIntRange) { var charCount = 0u var lineNum = 0 for(line in lines) { if(charCount + line.length.toUInt() > position.start) break charCount += line.length.toUInt() lineNum += 1 } do { if(lineNum == lines.size) { println("${"%4d".format(lineNum + 1)}|EOF") println(" |^^^") return } val line = lines[lineNum] val marks = StringBuilder() for(i in line.indices) { marks.append(if(charCount in position) "^" else " ") charCount += 1u } print("${"%4d".format(lineNum + 1)}|$line") println(" |$marks") lineNum += 1 } while(charCount < position.endInclusive) }
0
Kotlin
0
0
6f4ca7e3379212f4723f20e2a312cfb27d4e387a
1,866
Zenith-Compiler
MIT License
androidApp/src/main/java/dev/johnoreilly/mortycomposekmm/ui/episodes/EpisodeDetailView.kt
joreilly
323,447,684
false
null
package dev.johnoreilly.mortycomposekmm.ui.episodes import androidx.compose.foundation.Image import androidx.compose.foundation.layout.* import androidx.compose.foundation.lazy.LazyColumn import androidx.compose.foundation.shape.CircleShape import androidx.compose.material.* import androidx.compose.material.icons.Icons import androidx.compose.material.icons.filled.ArrowBack import androidx.compose.runtime.Composable import androidx.compose.runtime.LaunchedEffect import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.ui.Modifier import androidx.compose.ui.graphics.Color import androidx.compose.ui.unit.dp import coil.compose.rememberImagePainter import dev.johnoreilly.mortycomposekmm.fragment.EpisodeDetail import dev.johnoreilly.mortycomposekmm.ui.MainViewModel @Composable fun EpisodeDetailView(viewModel: MainViewModel, episodeId: String, popBack: () -> Unit) { val (episode, setEpisode) = remember { mutableStateOf<EpisodeDetail?>(null) } LaunchedEffect(episodeId) { setEpisode(viewModel.getEpisode(episodeId)) } Scaffold( topBar = { TopAppBar( title = { Text(episode?.name ?: "") }, navigationIcon = { IconButton(onClick = { popBack() }) { Icon(Icons.Filled.ArrowBack, contentDescription = "Back") } } ) }) { Surface(color = Color.LightGray) { LazyColumn(modifier = Modifier.padding(top = 16.dp)) { episode?.let { item(episode.id) { Text( "Characters", style = MaterialTheme.typography.h5, color = LocalContentColor.current, modifier = Modifier.padding(vertical = 8.dp, horizontal = 16.dp) ) Surface(color = Color.White) { EpisodeCharactersList(episode) } } } } } } } @Composable private fun EpisodeCharactersList(episode: EpisodeDetail) { Column(modifier = Modifier.padding(horizontal = 16.dp)) { episode.characters.filterNotNull().forEach { character -> Row(modifier = Modifier.padding(vertical = 8.dp)) { Surface( modifier = Modifier.size(28.dp), shape = CircleShape, color = MaterialTheme.colors.onSurface.copy(alpha = 0.2f) ) { Image( painter = rememberImagePainter(character.image), modifier = Modifier.size(28.dp), contentDescription = character.name ) } Text( character.name, modifier = Modifier.padding(start = 8.dp, end = 8.dp), style = MaterialTheme.typography.h6 ) } Divider() } } }
1
null
14
252
df980faf61f0f8836fc3e9b196875f08666f2bc7
3,185
MortyComposeKMM
Apache License 2.0
bound/kt/src/test/kotlin/web5/sdk/dids/methods/jwk/DidJwkTests.kt
TBD54566975
716,632,191
false
null
package web5.sdk.dids.methods.jwk import org.junit.jupiter.api.Assertions.* import org.junit.jupiter.api.Test import web5.sdk.rust.DidJwk as RustCoreDidJwk import web5.sdk.rust.ed25519GeneratorGenerate as rustCoreEd25519GeneratorGenerate class DidJwkTests { @Test fun `can create did jwk same as rust core`() { val jwk = rustCoreEd25519GeneratorGenerate() val didJwk = DidJwk(jwk) val rustCoreDidJwk = RustCoreDidJwk.fromPublicJwk(jwk); assertEquals(rustCoreDidJwk.getData().did.uri, didJwk.did.uri) assertEquals(rustCoreDidJwk.getData().document.id, didJwk.document.id) } @Test fun `can resolve did jwk uri`() { val didUri = "did:jwk:<KEY>" val resolvedDid = DidJwk.resolve(didUri) assertEquals(resolvedDid.document!!.id, didUri) } @Test fun `throws exception if did method is not jwk`() { val resolutionResult = DidJwk.resolve("did:example:123") assertEquals(resolutionResult.resolutionMetadata.error!!.name, "INVALID_DID"); } }
75
null
5
8
ea1c48ea336ab8f24d38e4fdbbb63430418fb010
1,055
web5-rs
Apache License 2.0
presentation/src/main/java/com/wa2c/android/cifsdocumentsprovider/presentation/PresentationModule.kt
wa2c
309,159,444
false
{"Kotlin": 319584}
package com.wa2c.android.cifsdocumentsprovider.presentation import android.content.Context import com.wa2c.android.cifsdocumentsprovider.domain.repository.CifsRepository import dagger.Module import dagger.hilt.EntryPoint import dagger.hilt.InstallIn import dagger.hilt.android.EntryPointAccessors import dagger.hilt.components.SingletonComponent @Module @InstallIn(SingletonComponent::class) internal object PresentationModule { @EntryPoint @InstallIn(SingletonComponent::class) interface DocumentsProviderEntryPoint { fun getCifsRepository(): CifsRepository } } fun provideCifsRepository(context: Context): CifsRepository { val clazz = PresentationModule.DocumentsProviderEntryPoint::class.java val hiltEntryPoint = EntryPointAccessors.fromApplication(context, clazz) return hiltEntryPoint.getCifsRepository() }
31
Kotlin
17
139
cb662b0e8b092ce2e6b320e3dc2a1a21ed655992
853
cifs-documents-provider
MIT License
kotlin/local-data-api/test/com/koxudaxi/localDataApi/ModelsTest.kt
koxudaxi
189,569,756
false
null
package com.koxudaxi.localDataApi import java.util.* import kotlin.test.* class ModelsTest { @Test fun testSqlParameter() { assertEquals("aGVsbG8=", SqlParameter("value", Field(blobValue = "aGVsbG8=")).value.blobValue) assertEquals("DECIMAL", SqlParameter("value", Field(stringValue = "123"), typeHint = "DECIMAL").typeHint) assertEquals(null, SqlParameter("value", Field(stringValue = "123")).typeHint) assertEquals(null, SqlParameter("value", Field(stringValue = "123"), typeHint = null).typeHint) // hello as bytes assertEquals( byteArrayOf(104, 101, 108, 108, 111).toList(), (SqlParameter("value", Field(blobValue = "aGVsbG8=")).castValue as ByteArray).toList()) assertEquals("dog", SqlParameter("value", Field(stringValue = "dog")).castValue) assertEquals((123).toDouble(), SqlParameter("value", Field(doubleValue = (123).toDouble())).castValue) assertEquals((123).toLong(), SqlParameter("value", Field(longValue = (123).toLong())).castValue) assertEquals(true, SqlParameter("value", Field(booleanValue = true)).castValue) assertEquals(java.sql.Date.valueOf("2020-10-12"), SqlParameter("value", Field(stringValue = "2020-10-12"), typeHint = "DATE").castValue) assertEquals((123).toBigDecimal(), SqlParameter("value", Field(stringValue = "123"), typeHint = "DECIMAL").castValue) assertEquals(java.sql.Time.valueOf("12:23:45"), SqlParameter("value", Field(stringValue = "12:23:45"), typeHint = "TIME").castValue) assertEquals(java.sql.Timestamp.valueOf("2021-03-10 12:23:45.968123"), SqlParameter("value", Field(stringValue = "2021-03-10 12:23:45.968123"), typeHint = "TIMESTAMP").castValue) assertEquals(UUID.fromString("abc08ed7-d834-47e8-9ef1-87b88bd774fb"), SqlParameter("value", Field(stringValue = "abc08ed7-d834-47e8-9ef1-87b88bd774fb"), typeHint = "UUID").castValue) assertEquals("dog", SqlParameter("value", Field(stringValue = "dog"), typeHint = "unknown").castValue) assertEquals(null, SqlParameter("value", Field(isNull = true)).castValue) assertEquals(true, SqlParameter("value", Field(isNull = true)).value.isNull) } @Test fun testArrayValueFromList() { assertEquals(listOf("a", "b"), ArrayValue.fromList(listOf("a", "b")).stringValues) assertEquals(listOf(true, false), ArrayValue.fromList(listOf(true, false)).booleanValues) assertEquals(listOf(1.toDouble(), 2.toDouble()), ArrayValue.fromList(listOf(1.toDouble(), 2.toDouble())).doubleValues) assertEquals(listOf(1.toLong(), 2.toLong()), ArrayValue.fromList(listOf(1.toLong(), 2.toLong())).longValues) val array = ArrayValue.fromList(listOf(listOf("a", "b"), listOf("c", "d"))).arrayValues!! assertEquals(listOf("a", "b"), array[0].stringValues) assertEquals(listOf("c", "d"), array[1].stringValues) } }
17
Python
16
94
9f80b144f1c2ffd9501c7eb8b7e1db981281422e
3,030
local-data-api
MIT License
app/src/main/java/com/a10miaomiao/bilimiao/entity/UpperChannelVideoInfo.kt
10miaomiao
115,510,569
false
null
package com.a10miaomiao.bilimiao.entity /** * Created by 10喵喵 on 2017/10/31. */ data class UpperChannelVideoInfo( var code: Int, var message: String, var data: UperChannelVideoData ) { data class UperChannelVideoData( var list: UperChannelVideoList ) data class UperChannelVideoList( var archives: List<VideoArchives> ) data class VideoArchives( var aid: Int, var duration: Int, var title: String, var pic: String, var pubdate: Long, var stat: VideoStat ) data class VideoStat( var danmaku: Int, var view: Int ) }
1
null
1
20
dfd78b56b5c41eb49454836ee2bce5cefc667db7
694
bilimiao
Apache License 2.0
core/db/src/test/java/com/memorati/core/db/model/AdditionalInfoEntityTest.kt
HeidelX
640,943,698
false
{"Kotlin": 332940, "Ruby": 1925}
package com.memorati.core.db.model import kotlinx.serialization.encodeToString import kotlinx.serialization.json.Json import kotlin.test.Test import kotlin.test.assertEquals class AdditionalInfoEntityTest { private val infoString1 = """ {"difficulty":1.0,"consecutiveCorrectCount":0,"memoryStrength":1.0,"totalReviews":0} """.trimIndent() private val infoString2 = """ {"difficulty":2.0,"consecutiveCorrectCount":0,"memoryStrength":1.0,"totalReviews":0} """.trimIndent() private val infoString1Legacy = """ {"difficulty":1.0,"consecutiveCorrectCount":0,"memoryStrength":1.0} """.trimIndent() private val infoString2Legacy = """ {"difficulty":2.0,"consecutiveCorrectCount":0,"memoryStrength":1.0} """.trimIndent() @Test fun `Encode AdditionalInfoEntity to string`() { assertEquals( infoString2, Json.encodeToString(AdditionalInfoEntity(difficulty = 2.0)), ) assertEquals( infoString1, Json.encodeToString(AdditionalInfoEntity()), ) } @Test fun `Decode string to AdditionalInfoEntity `() { assertEquals( AdditionalInfoEntity(difficulty = 2.0), Json.decodeFromString(infoString2), ) assertEquals( AdditionalInfoEntity(), Json.decodeFromString(infoString1), ) } @Test fun `Decode string legacy to AdditionalInfoEntity `() { assertEquals( AdditionalInfoEntity(difficulty = 2.0), Json.decodeFromString(infoString2Legacy), ) assertEquals( AdditionalInfoEntity(), Json.decodeFromString(infoString1Legacy), ) } }
0
Kotlin
0
0
b1caa3497644913a623590c313d67e421a24bdf4
1,786
Memorati
MIT License
app/src/main/kotlin/io/xps/playground/ui/feature/filesystem/FileSystemFragment.kt
serhii-petrenko-dev
593,936,096
false
{"Kotlin": 226184, "Java": 6274}
package io.xps.playground.ui.feature.filesystem import android.content.Context import android.content.Intent import android.os.Build import android.os.Bundle import android.os.Environment import android.os.StatFs import android.os.storage.StorageManager import android.os.storage.StorageManager.ACTION_MANAGE_STORAGE import android.util.Log import android.view.View import androidx.annotation.RequiresApi import androidx.compose.animation.AnimatedVisibility import androidx.compose.animation.fadeIn import androidx.compose.animation.fadeOut import androidx.compose.foundation.Image import androidx.compose.foundation.border import androidx.compose.foundation.clickable import androidx.compose.foundation.layout.* import androidx.compose.foundation.lazy.LazyColumn import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.material3.* import androidx.compose.runtime.Composable import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.draw.clip import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.platform.ViewCompositionStrategy import androidx.compose.ui.res.painterResource import androidx.compose.ui.text.style.TextAlign import androidx.compose.ui.unit.dp import androidx.core.content.getSystemService import androidx.fragment.app.Fragment import androidx.fragment.app.viewModels import dagger.hilt.android.AndroidEntryPoint import io.xps.playground.R import io.xps.playground.databinding.FragmentComposeBinding import io.xps.playground.tools.byteSizeToString import io.xps.playground.tools.viewBinding import io.xps.playground.ui.composables.ScreenTittle import io.xps.playground.ui.theme.PlaygroundTheme import okio.buffer import okio.source import java.io.File import java.security.SecureRandom import java.util.* import kotlin.math.roundToInt @AndroidEntryPoint class FileSystemFragment: Fragment(R.layout.fragment_compose) { private val binding by viewBinding(FragmentComposeBinding::bind) private val viewModel by viewModels<FileSystemViewModel>() override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) binding.containerCompose.setViewCompositionStrategy( ViewCompositionStrategy.DisposeOnViewTreeLifecycleDestroyed ) binding.containerCompose.setContent { PlaygroundTheme { FileSystemScreen() } } val bytes = generateBytes(viewModel.sampleDataSize) val byteBuffer = bytes.inputStream().source().buffer().readByteString() Log.d("byteBuffer sha256", byteBuffer.md5().hex()) } private fun queryFreeSpace(internalStorage: Boolean): Pair<Long, Long> { val storageDirectory = if(internalStorage) { Environment.getDataDirectory() } else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) { Environment.getStorageDirectory() } else { Environment.getExternalStorageDirectory() } val stats = StatFs(storageDirectory!!.path) val blockSize = stats.blockSizeLong val availableSpace = (stats.availableBlocksLong * blockSize) val totalSpace = (stats.blockCountLong * blockSize) return Pair(availableSpace, totalSpace) } private fun generateBytes(mbSize: Float): ByteArray { val byteSize = (mbSize * 1024 * 1024).roundToInt() val array = ByteArray(byteSize) SecureRandom().nextBytes(array) return array } @RequiresApi(Build.VERSION_CODES.O) private fun allocateFreeSpace(context: Context, mb: Float){ val bytesNeeded = (1024 * 1024 * mb).toLong() val storageManager = context.getSystemService<StorageManager>()!! val appSpecificInternalDirUuid: UUID = storageManager.getUuidForPath(context.filesDir) val availableBytes: Long = storageManager.getAllocatableBytes(appSpecificInternalDirUuid) if (availableBytes >= bytesNeeded) { storageManager.allocateBytes(appSpecificInternalDirUuid, bytesNeeded) } else { val storageIntent = Intent().apply { // To request that the user remove all app cache files instead, set // "action" to ACTION_CLEAR_APP_CACHE. action = ACTION_MANAGE_STORAGE } } } @Composable fun FileSystemScreen() { Surface { LazyColumn( modifier = Modifier.fillMaxSize(), contentPadding = PaddingValues(horizontal = 24.dp) ) { item { ScreenTittle(text = "Storage") } item { val (available, total) = queryFreeSpace(true) StorageItem(true, available, total) } item { val (available, total) = queryFreeSpace(false) StorageItem(false, available, total) } item { val context = LocalContext.current AccessTestItem("Internal Storage", context.filesDir) } } } } @Composable fun StorageItem(internalStorage: Boolean, available: Long, total: Long) { Column { val used = total - available Text( text = if (internalStorage) "Internal" else "External", style = MaterialTheme.typography.bodyMedium ) Row(verticalAlignment = Alignment.Bottom) { Text( text = used.byteSizeToString(false).filter { it.isDigit() }, style = MaterialTheme.typography.titleLarge ) Column(modifier = Modifier.padding(bottom = 8.dp)) { Row { Text( modifier = Modifier.padding(start = 4.dp), text = "${ used.byteSizeToString(false) .filter { !it.isDigit() && it.isLetter()}} used", style = MaterialTheme.typography.bodySmall ) Spacer(modifier = Modifier.weight(1f)) Text( text = "${total.byteSizeToString(false) .replace(" ", "") } total", style = MaterialTheme.typography.bodySmall ) } } } LinearProgressIndicator( modifier = Modifier .fillMaxWidth() .height(15.dp) .clip(RoundedCornerShape(50)), progress = (used.toDouble() / total.toDouble()).toFloat() ) } } //TODO Write Actual Test @Composable fun AccessTestItem(tittle: String, target: File) { Text( modifier = Modifier.padding(vertical = 16.dp), text = tittle, style = MaterialTheme.typography.bodyMedium ) Column( modifier = Modifier .border( width = 4.dp, color = MaterialTheme.colorScheme.primary, shape = RoundedCornerShape(12) ).padding(16.dp), ) { val start = remember { mutableStateOf(false)} AnimatedVisibility( visible = start.value, enter = fadeIn(), exit = fadeOut() ) { Column{ ActionItem("Write", ActionItemState.Success("k12h3jkh31kjh21kj1321")) ActionItem("Read", ActionItemState.Error("k12h3jkh31kjh21kj1321")) } } AnimatedVisibility( visible = !start.value, enter = fadeIn(), exit = fadeOut() ) { Text( modifier = Modifier .clickable { start.value = !start.value } .fillMaxWidth() .padding(vertical = 48.dp), text = "Tap to start", textAlign = TextAlign.Center ) } } } @Composable fun ActionItem(tittle: String, state: ActionItemState){ Row( verticalAlignment = Alignment.CenterVertically, modifier = Modifier.padding(vertical = 8.dp), ) { Column { Text( modifier = Modifier.padding(top = 4.dp), text = tittle, style = MaterialTheme.typography.bodyMedium ) when(state){ is ActionItemState.Success -> { Text( text = state.message, style = MaterialTheme.typography.bodySmall ) } is ActionItemState.Error -> { Text( text = state.error, style = MaterialTheme.typography.bodySmall ) } is ActionItemState.Loading -> {} } } Spacer(modifier = Modifier.weight(1f)) when(state){ is ActionItemState.Success -> { Image( modifier = Modifier.size(30.dp), painter = painterResource(id = R.drawable.ic_check), contentDescription = null ) } is ActionItemState.Error -> { Image( modifier = Modifier.size(30.dp), painter = painterResource(id = R.drawable.ic_error), contentDescription = null ) } is ActionItemState.Loading -> { CircularProgressIndicator(modifier = Modifier) } } } } sealed class ActionItemState { data class Success(val message: String): ActionItemState() data class Error(val error: String): ActionItemState() object Loading: ActionItemState() } }
0
Kotlin
0
0
bc0277d1200aa5078c8943c67aa8fa9dfe37b8ce
10,587
playground
MIT License
src/main/kotlin/io/openfuture/api/exception/EventTypeException.kt
OpenFuturePlatform
134,381,311
false
null
package io.openfuture.api.exception class EventTypeException(message: String?) : RuntimeException(message)
11
JavaScript
7
42
4cf6df0407c9a941bd1e0b6d01a9ab05f4db0ef6
107
open-api
Apache License 2.0
certificatetransparency/src/main/kotlin/com/appmattus/certificatetransparency/internal/loglist/deserializer/StateDeserializer.kt
appmattus
319,979,095
false
null
/* * Copyright 2021 Appmattus Limited * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.appmattus.certificatetransparency.internal.loglist.deserializer import com.appmattus.certificatetransparency.internal.loglist.model.v3.State import kotlinx.serialization.json.JsonElement import kotlinx.serialization.json.JsonObject import kotlinx.serialization.json.JsonPrimitive import kotlinx.serialization.json.JsonTransformingSerializer internal class StateDeserializer : JsonTransformingSerializer<State>(State.serializer()) { override fun transformDeserialize(element: JsonElement): JsonElement { if (element is JsonObject) { val key = element.keys.first() val entry = element[key] as JsonObject return JsonObject(entry + ("type" to JsonPrimitive(key))) } return element } }
7
null
24
91
469354b7a5692535bece8901d6d9fef1ab1f8093
1,363
certificatetransparency
Apache License 2.0
src/main/kotlin/infrastructure/api/ApiRouter.kt
SmartOperatingBlock
610,670,082
false
null
/* * Copyright (c) 2023. Smart Operating Block * * Use of this source code is governed by an MIT-style * license that can be found in the LICENSE file or at * https://opensource.org/licenses/MIT. */ package infrastructure.api import application.controller.manager.StaffTrackingDatabaseManager import infrastructure.api.routes.trackingAPI import io.ktor.http.HttpStatusCode import io.ktor.serialization.kotlinx.json.json import io.ktor.server.application.Application import io.ktor.server.application.install import io.ktor.server.engine.embeddedServer import io.ktor.server.netty.Netty import io.ktor.server.plugins.contentnegotiation.ContentNegotiation import io.ktor.server.plugins.statuspages.StatusPages import io.ktor.server.response.respondText import io.ktor.server.routing.routing import java.time.format.DateTimeParseException /** * The API router of the application. */ class ApiRouter(private val staffTrackingDatabaseManager: StaffTrackingDatabaseManager) { private val version = "v1" private val apiPath: String = "/api/$version" companion object { /** The port of the KTor server. */ const val NETTY_PORT = 3000 } /** Start the Ktor server. */ fun start() { embeddedServer(Netty, port = NETTY_PORT) { module(this) }.start(wait = false) } /** The KTor Application module. */ fun module(app: Application) { with(app) { configureRouting() configureSerialization() exceptionHandler() } } /** * Extension function to configure routing management. */ private fun Application.configureRouting() { routing { trackingAPI(staffTrackingDatabaseManager, apiPath) } } /** * Extension function to configure serialization management. */ private fun Application.configureSerialization() { install(ContentNegotiation) { json() } } private fun Application.exceptionHandler() { install(StatusPages) { exception<DateTimeParseException> { call, _ -> call.respondText( text = "Date time information must be in ISO 8601 format", status = HttpStatusCode.BadRequest, ) } } } }
5
Kotlin
0
0
ca393dfdb186a8b2a02fd7144a593b71399d2b34
2,340
staff-tracking-microservice
MIT License
video-sdk/src/main/java/com/kaleyra/video_sdk/extensions/MaterialM3ColorUtilsExtensions.kt
KaleyraVideo
686,975,102
false
{"Kotlin": 5030623, "Shell": 7470, "Python": 6756, "Java": 1213}
package com.kaleyra.video_sdk.extensions import com.kaleyra.material_color_utilities.scheme.Scheme import com.kaleyra.video_common_ui.utils.SchemeUtils.toColorScheme /** * Generate a light color scheme from input argb seed * @receiver ColorScheme the resulting light color scheme * @param seed Int input argb seed */ fun lightColorSchemeFrom(seed: Int) = Scheme.light(seed).toColorScheme() /** * Generate a dark color scheme from input argb seed * @receiver ColorScheme the resulting dark color scheme * @param seed Int input argb seed */ fun darkColorSchemeFrom(seed: Int) = Scheme.dark(seed).toColorScheme()
0
Kotlin
0
1
6633ca0924ebaab16ffa9c47745e45ec55d42952
621
VideoAndroidSDK
Apache License 2.0
health/connect/connect-client/src/main/java/androidx/health/connect/client/records/CyclingPedalingCadenceRecord.kt
androidx
256,589,781
false
null
/* * Copyright (C) 2022 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package androidx.health.connect.client.records import androidx.annotation.FloatRange import androidx.health.connect.client.aggregate.AggregateMetric import androidx.health.connect.client.aggregate.AggregateMetric.AggregationType.AVERAGE import androidx.health.connect.client.aggregate.AggregateMetric.AggregationType.MAXIMUM import androidx.health.connect.client.aggregate.AggregateMetric.AggregationType.MINIMUM import androidx.health.connect.client.aggregate.AggregateMetric.Companion.doubleMetric import androidx.health.connect.client.records.metadata.Metadata import java.time.Instant import java.time.ZoneOffset /** * Captures the user's cycling pedaling cadence. Each record represents a series of measurements. */ public class CyclingPedalingCadenceRecord( override val startTime: Instant, override val startZoneOffset: ZoneOffset?, override val endTime: Instant, override val endZoneOffset: ZoneOffset?, override val samples: List<Sample>, override val metadata: Metadata = Metadata.EMPTY, ) : SeriesRecord<CyclingPedalingCadenceRecord.Sample> { /* * Generated by the IDE: Code -> Generate -> "equals() and hashCode()". */ override fun equals(other: Any?): Boolean { if (this === other) return true if (other !is CyclingPedalingCadenceRecord) return false if (startTime != other.startTime) return false if (startZoneOffset != other.startZoneOffset) return false if (endTime != other.endTime) return false if (endZoneOffset != other.endZoneOffset) return false if (samples != other.samples) return false if (metadata != other.metadata) return false return true } /* * Generated by the IDE: Code -> Generate -> "equals() and hashCode()". */ override fun hashCode(): Int { var result = startTime.hashCode() result = 31 * result + (startZoneOffset?.hashCode() ?: 0) result = 31 * result + endTime.hashCode() result = 31 * result + (endZoneOffset?.hashCode() ?: 0) result = 31 * result + samples.hashCode() result = 31 * result + metadata.hashCode() return result } companion object { private const val TYPE = "CyclingPedalingCadenceSeries" private const val RPM_FIELD = "rpm" /** * Metric identifier to retrieve average cycling pedaling cadence from * [androidx.health.connect.client.aggregate.AggregationResult]. */ @JvmField val RPM_AVG: AggregateMetric<Double> = doubleMetric(TYPE, AVERAGE, RPM_FIELD) /** * Metric identifier to retrieve minimum cycling pedaling cadence from * [androidx.health.connect.client.aggregate.AggregationResult]. */ @JvmField val RPM_MIN: AggregateMetric<Double> = doubleMetric(TYPE, MINIMUM, RPM_FIELD) /** * Metric identifier to retrieve maximum cycling pedaling cadence from * [androidx.health.connect.client.aggregate.AggregationResult]. */ @JvmField val RPM_MAX: AggregateMetric<Double> = doubleMetric(TYPE, MAXIMUM, RPM_FIELD) } /** * Represents a single measurement of the cycling pedaling cadence. * * @param time The point in time when the measurement was taken. * @param revolutionsPerMinute Cycling revolutions per minute. Valid range: 0-10000. * * @see CyclingPedalingCadenceRecord */ public class Sample( val time: Instant, @FloatRange(from = 0.0, to = 10_000.0) val revolutionsPerMinute: Double, ) { init { requireNonNegative(value = revolutionsPerMinute, name = "revolutionsPerMinute") } /* * Generated by the IDE: Code -> Generate -> "equals() and hashCode()". */ override fun equals(other: Any?): Boolean { if (this === other) return true if (other !is Sample) return false if (time != other.time) return false if (revolutionsPerMinute != other.revolutionsPerMinute) return false return true } /* * Generated by the IDE: Code -> Generate -> "equals() and hashCode()". */ override fun hashCode(): Int { var result = time.hashCode() result = 31 * result + revolutionsPerMinute.hashCode() return result } } }
30
null
950
5,321
98b929d303f34d569e9fd8a529f022d398d1024b
5,019
androidx
Apache License 2.0
onestore_iap_sample/sample_subscription/src/main/java/com/onestore/sample/subscription/base/BaseRecyclerViewAdapter.kt
ONE-store
283,635,557
false
{"Kotlin": 123343}
/** * @author tia.lee * @since 2021. 06.24 */ package com.onestore.sample.subscription.base import androidx.recyclerview.widget.RecyclerView abstract class BaseRecyclerViewAdapter<T>: RecyclerView.Adapter<RecyclerView.ViewHolder>() { interface OnItemClickListener { fun <T> onItemClick(position: Int, item: T) } lateinit var listener: OnItemClickListener }
0
Kotlin
9
11
5fceaea4234dfcfca73d302b4575bf59705ec2fb
383
onestore_iap_release
Apache License 2.0
common-lib/src/main/kotlin/me/chosante/common/skills/Agility.kt
CharlyRien
670,146,796
false
{"Kotlin": 223963, "CSS": 73}
package me.chosante.common.skills import me.chosante.common.Characteristic import me.chosante.common.skills.AgilityCharacteristic.Dodge import me.chosante.common.skills.AgilityCharacteristic.DodgeAndLock import me.chosante.common.skills.AgilityCharacteristic.Initiative import me.chosante.common.skills.AgilityCharacteristic.Lock import me.chosante.common.skills.AgilityCharacteristic.Willpower data class Agility( override val maxPointsToAssign: Int, val lock: Lock = Lock(0), val dodge: Dodge = Dodge(0), val initiative: Initiative = Initiative(0), val dodgeAndLock: SkillCharacteristic.PairedCharacteristic = DodgeAndLock(0), val willpower: Willpower = Willpower(0), ) : Assignable<Agility> { init { val sumOfAssignedPoints = lock.pointsAssigned + dodge.pointsAssigned + initiative.pointsAssigned + dodgeAndLock.first.pointsAssigned + willpower.pointsAssigned check(sumOfAssignedPoints in 0..maxPointsToAssign) } val allCharacteristicValues: CharacteristicValues get() = getAllCharacteristicValues(getCharacteristics()) override fun getCharacteristics(): List<SkillCharacteristic> { return listOf( lock, dodge, initiative, dodgeAndLock, willpower ) } override fun pointsAssigned(): Int { return listOf( lock, dodge, initiative, dodgeAndLock, willpower ).sumOf { it.pointsAssigned } } } sealed class AgilityCharacteristic( name: String, pointsAssigned: Int, maxPointsAssignable: Int, unitValue: Int, characteristic: Characteristic?, unitType: UnitType, ) : SkillCharacteristic(pointsAssigned, name, maxPointsAssignable, unitValue, characteristic, unitType) { class Lock(pointsAssigned: Int) : AgilityCharacteristic( pointsAssigned = pointsAssigned, maxPointsAssignable = Int.MAX_VALUE, unitValue = 6, unitType = UnitType.FIXED, characteristic = Characteristic.LOCK, name = "Lock" ) class Dodge(pointsAssigned: Int) : AgilityCharacteristic( pointsAssigned = pointsAssigned, maxPointsAssignable = Int.MAX_VALUE, unitValue = 6, unitType = UnitType.FIXED, characteristic = Characteristic.DODGE, name = "Dodge" ) class Initiative(pointsAssigned: Int) : AgilityCharacteristic( pointsAssigned = pointsAssigned, maxPointsAssignable = 20, unitValue = 4, unitType = UnitType.FIXED, characteristic = Characteristic.INITIATIVE, name = "Initiative" ) class DodgeAndLock(pointsAssigned: Int) : PairedCharacteristic( "Dodge and lock", first = Dodge(pointsAssigned), second = Lock(pointsAssigned), maxPointsAssignable = Int.MAX_VALUE ) { class Dodge(pointsAssigned: Int) : AgilityCharacteristic( pointsAssigned = pointsAssigned, maxPointsAssignable = Int.MAX_VALUE, unitValue = 4, unitType = UnitType.FIXED, characteristic = Characteristic.DODGE, name = "" ) class Lock(pointsAssigned: Int) : AgilityCharacteristic( pointsAssigned = pointsAssigned, maxPointsAssignable = Int.MAX_VALUE, unitValue = 4, unitType = UnitType.FIXED, characteristic = Characteristic.LOCK, name = "" ) } class Willpower(pointsAssigned: Int) : AgilityCharacteristic( pointsAssigned = pointsAssigned, maxPointsAssignable = 20, unitValue = 1, unitType = UnitType.FIXED, characteristic = Characteristic.WILLPOWER, name = "Willpower" ) }
0
Kotlin
0
13
4d1a3eb6fba3b088637b0771da3845e6d9a75d14
3,999
wakfu-autobuilder
The Unlicense
common/src/main/java/com/kernel/finch/common/contracts/FinchListItem.kt
kernel0x
197,173,098
false
{"Kotlin": 373961}
package com.kernel.finch.common.contracts import com.kernel.finch.common.models.Text interface FinchListItem { val title: Text val id: String get() = when (val title = title) { is Text.CharSequence -> title.charSequence.toString() is Text.ResourceId -> title.resId.toString() } override fun equals(other: Any?): Boolean override fun hashCode(): Int }
2
Kotlin
9
46
4f098309de71b690af5e2a7503444ad1959bf004
413
finch
Apache License 2.0
src/main/kotlin/name/kropp/intellij/makefile/psi/MakefileElementFactory.kt
kropp
76,199,916
false
null
package name.kropp.intellij.makefile.psi import com.intellij.openapi.project.* import com.intellij.psi.* import name.kropp.intellij.makefile.* object MakefileElementFactory { fun createFile(project: Project, text: String) = PsiFileFactory.getInstance(project).createFileFromText("Makefile", MakefileFileType, text) as MakefileFile fun createRule(project: Project, target: String) = createFile(project, "$target:").firstChild as MakefileRule fun createTarget(project: Project, name: String) = createRule(project, name).firstChild.firstChild.firstChild as MakefileTarget fun createVariable(project: Project, name: String) = createFile(project, "$name := ''").firstChild.firstChild as MakefileVariable fun createPrerequisite(project: Project, name: String) = (createFile(project, "a: $name").firstChild as MakefileRule).targetLine.prerequisites!!.normalPrerequisites.firstChild as MakefilePrerequisite fun createWhiteSpace(project: Project, whitespace: String) = createFile(project, whitespace).firstChild as PsiWhiteSpace fun createChars(project: Project, chars: String) = createFile(project, chars).firstChild.node fun createEOL(project: Project, whitespace: String) = createFile(project, whitespace).firstChild fun createRecipe(project: Project, text: String) = createRule(project, "target:\n\t$text").firstChild.nextSibling as MakefileRecipe fun createFunction(project: Project, text: String) = createFile(project, text).firstChild as MakefileFunction fun createSubstitution(project: Project, text: String): MakefileSubstitution = createRecipe(project, text).commandList.first().substitutionList.first() }
1
null
30
168
7b40402eb003c3424f525320725a951446924d0b
1,706
intellij-makefile
MIT License
compottie/src/commonMain/kotlin/io/github/alexzhirkevich/compottie/dynamic/_DynamicDrawProvider.kt
alexzhirkevich
730,724,501
false
{"Kotlin": 891763, "Swift": 601, "HTML": 211}
package io.github.alexzhirkevich.compottie.dynamic import androidx.compose.ui.geometry.Rect import androidx.compose.ui.geometry.Size import androidx.compose.ui.graphics.BlendMode import androidx.compose.ui.graphics.Color import androidx.compose.ui.graphics.ColorFilter import androidx.compose.ui.graphics.Matrix import androidx.compose.ui.graphics.Paint import io.github.alexzhirkevich.compottie.internal.AnimationState import io.github.alexzhirkevich.compottie.internal.animation.AnimatedNumber import io.github.alexzhirkevich.compottie.internal.animation.interpolatedNorm import io.github.alexzhirkevich.compottie.internal.platform.GradientCache import io.github.alexzhirkevich.compottie.internal.platform.GradientShader internal sealed interface DynamicDrawProvider : DynamicDraw { val opacity: PropertyProvider<Float>? val colorFilter: PropertyProvider<ColorFilter?>? val blendMode: PropertyProvider<BlendMode>? val hidden : PropertyProvider<Boolean>? val gradient: GradientProvider? val color: PropertyProvider<Color>? } internal sealed class BaseDynamicDrawProvider : DynamicShapeProvider(), DynamicDraw, DynamicDrawProvider{ final override var opacity: PropertyProvider<Float>? = null private set final override var colorFilter: PropertyProvider<ColorFilter?>? = null private set final override var blendMode: PropertyProvider<BlendMode>? = null private set final override var gradient: GradientProvider? = null private set final override var color: PropertyProvider<Color>? = null private set final override fun opacity(provider: PropertyProvider<Float>) { opacity = provider } final override fun colorFilter(provider: PropertyProvider<ColorFilter?>) { colorFilter = provider } final override fun blendMode(provider: PropertyProvider<BlendMode>) { blendMode = provider } override fun gradient(provider: GradientProvider) { gradient = provider color = null } override fun color(provider: PropertyProvider<Color>) { color = provider gradient = null } } internal fun DynamicDrawProvider?.applyToPaint( paint: Paint, state: AnimationState, parentAlpha: Float, parentMatrix : Matrix, opacity : AnimatedNumber?, size: () -> Rect, gradientCache: GradientCache ) { this?.color?.let { paint.color = it.derive(paint.color, state) } this?.gradient?.let { paint.shader = GradientShader( gradient = it.invoke(state, size()), matrix = parentMatrix, cache = gradientCache ) } var alpha = 1f opacity?.interpolatedNorm(state)?.let { alpha = (alpha * it).coerceIn(0f,1f) } this?.opacity?.let { alpha = it.derive(alpha, state).coerceIn(0f,1f) } paint.alpha = (alpha * parentAlpha).coerceIn(0f,1f) paint.colorFilter = this?.colorFilter.derive(paint.colorFilter, state) paint.blendMode = this?.blendMode.derive(paint.blendMode, state) }
5
Kotlin
7
232
46b008cd7cf40a84261b20c5888359f08368016a
3,081
compottie
MIT License
gradle-plugins/compose/src/main/kotlin/org/jetbrains/compose/resources/ResourcesDSL.kt
JetBrains
293,498,508
false
null
package org.jetbrains.compose.resources import org.gradle.api.Project import org.gradle.api.provider.Provider import java.io.File abstract class ResourcesExtension { /** * Whether the generated resources accessors class should be public or not. * * Default is false. */ var publicResClass: Boolean = false /** * The unique identifier of the resources in the current project. * Uses as package for the generated Res class and for isolation resources in a final artefact. * * If it is empty then `{group name}.{module name}.generated.resources` will be used. * */ var packageOfResClass: String = "" enum class ResourceClassGeneration { Auto, Always, Never } //to support groovy DSL val auto = ResourceClassGeneration.Auto val always = ResourceClassGeneration.Always val never = ResourceClassGeneration.Never /** * The mode of resource class generation. * * - `auto`: The Res class will be generated if the current project has an explicit "implementation" or "api" dependency on the resource's library. * - `always`: Unconditionally generate the Res class. This may be useful when the resources library is available transitively. * - `never`: Never generate the Res class. */ var generateResClass: ResourceClassGeneration = auto } internal fun Provider<ResourcesExtension>.getResourcePackage(project: Project) = map { config -> config.packageOfResClass.takeIf { it.isNotEmpty() } ?: run { val groupName = project.group.toString().lowercase().asUnderscoredIdentifier() val moduleName = project.name.lowercase().asUnderscoredIdentifier() val id = if (groupName.isNotEmpty()) "$groupName.$moduleName" else moduleName "$id.generated.resources" } } //the dir where resources must be placed in the final artefact internal fun Provider<ResourcesExtension>.getModuleResourcesDir(project: Project) = getResourcePackage(project).map { packageName -> File("$COMPOSE_RESOURCES_DIR/$packageName") }
64
null
1174
16,150
7e9832f6494edf3e7967082c11417e78cfd1d9d0
2,058
compose-multiplatform
Apache License 2.0
src/rider/main/kotlin/com/github/rafaelldi/diagnosticsclientplugin/services/gc/LiveGcEventSessionController.kt
rafaelldi
487,741,199
false
null
package com.github.rafaelldi.diagnosticsclientplugin.services.gc import com.github.rafaelldi.diagnosticsclientplugin.common.liveSessionFinished import com.github.rafaelldi.diagnosticsclientplugin.common.liveSessionNotFound import com.github.rafaelldi.diagnosticsclientplugin.common.liveSessionStarted import com.github.rafaelldi.diagnosticsclientplugin.dialogs.GcEventModel import com.github.rafaelldi.diagnosticsclientplugin.generated.LiveGcEventSession import com.github.rafaelldi.diagnosticsclientplugin.generated.diagnosticsHostModel import com.github.rafaelldi.diagnosticsclientplugin.services.common.LiveSessionController import com.intellij.openapi.components.Service import com.intellij.openapi.components.service import com.intellij.openapi.project.Project import com.jetbrains.rider.projectView.solution @Service class LiveGcEventSessionController(project: Project) : LiveSessionController<LiveGcEventSession, GcEventModel>(project) { companion object { fun getInstance(project: Project): LiveGcEventSessionController = project.service() private const val GC_EVENTS = "GC events" } override val sessions = project.solution.diagnosticsHostModel.liveGcEventSessions init { sessions.view(projectComponentLifetime) { lt, pid, session -> viewSession(pid, session, lt) } } override fun createSession(model: GcEventModel): LiveGcEventSession { return LiveGcEventSession() } override fun sessionNotFound(pid: Int) = liveSessionNotFound(GC_EVENTS, pid, project) override fun sessionStarted(pid: Int) = liveSessionStarted(GC_EVENTS, pid, project) override fun sessionFinished(pid: Int) = liveSessionFinished(GC_EVENTS, pid, project) }
4
null
0
4
743f0a74e999b2ac07fe866e4842246bd982f00c
1,736
diagnostics-client-plugin
MIT License
features/auth/src/main/java/com/ribsky/auth/nav/AuthNavigationImpl.kt
nexy791
607,748,138
false
null
package com.ribsky.auth.nav import android.content.Intent import android.os.Bundle import androidx.appcompat.app.AppCompatActivity import androidx.navigation.NavController import com.ribsky.auth.ui.AuthActivity import com.ribsky.navigation.features.AuthNavigation import com.ribsky.navigation.features.LoaderNavigation class AuthNavigationImpl : AuthNavigation { override var activity: AppCompatActivity? = null override var navController: NavController? = null override fun navigateLoader(loaderNavigation: LoaderNavigation) { loaderNavigation.setup(activity, navController) loaderNavigation.navigateHome() } override fun navigateHome(bundle: Bundle?) { activity?.startActivity( Intent(activity, AuthActivity::class.java).apply { addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP or Intent.FLAG_ACTIVITY_CLEAR_TASK or Intent.FLAG_ACTIVITY_NEW_TASK) } ) } }
0
Kotlin
0
7
d2e9f7c04635e1793bfe8f421b4bc5ef162556c0
949
dymka
Apache License 2.0
app/src/main/java/com/tfg/bibliofinder/entities/Classroom.kt
ikergcalvino
671,605,377
false
{"Kotlin": 66993}
package com.tfg.bibliofinder.entities import androidx.room.Entity import androidx.room.ForeignKey import androidx.room.Index import androidx.room.PrimaryKey @Entity( foreignKeys = [ForeignKey( entity = Library::class, parentColumns = ["libraryId"], childColumns = ["libraryId"], onDelete = ForeignKey.CASCADE )], indices = [Index("libraryId")] ) data class Classroom( @PrimaryKey(autoGenerate = true) val classroomId: Long = 0, val name: String, val capacity: Int, var freeSpaces: Int, val type: String, val libraryId: Long )
0
Kotlin
0
0
3dd1ea3c420a85d0eaa66fc565e68dad27a14e7b
591
BiblioFinder
Apache License 2.0
identity/src/test/java/com/stripe/android/identity/utils/UriUtilsTest.kt
stripe
6,926,049
false
null
package com.stripe.android.identity.utils import android.net.Uri import com.google.common.truth.Truth.assertThat import org.junit.Test import org.junit.runner.RunWith import org.robolectric.RobolectricTestRunner @RunWith(RobolectricTestRunner::class) class UriUtilsTest { @Test fun testUrlWithoutQuery() { val uriBefore = Uri.parse("https://path/to/uri.png?query1=123&query2=456") assertThat(uriBefore.urlWithoutQuery()).isEqualTo("https://path/to/uri.png") } }
88
null
644
1,277
174b27b5a70f75a7bc66fdcce3142f1e51d809c8
492
stripe-android
MIT License
app/src/main/java/com/alpriest/energystats/services/DemoNetworking.kt
alpriest
606,081,400
false
{"Kotlin": 612161}
package com.alpriest.energystats.services import com.alpriest.energystats.models.AddressBookResponse import com.alpriest.energystats.models.BatteryResponse import com.alpriest.energystats.models.BatterySettingsResponse import com.alpriest.energystats.models.BatteryTimesResponse import com.alpriest.energystats.models.ChargeTime import com.alpriest.energystats.models.DeviceSettingsGetResponse import com.alpriest.energystats.models.DeviceSettingsValues import com.alpriest.energystats.models.Earning import com.alpriest.energystats.models.EarningsResponse import com.alpriest.energystats.models.NetworkDevice import com.alpriest.energystats.models.PagedDataLoggerListResponse import com.alpriest.energystats.models.PagedDeviceListResponse import com.alpriest.energystats.models.QueryDate import com.alpriest.energystats.models.RawData import com.alpriest.energystats.models.RawResponse import com.alpriest.energystats.models.RawVariable import com.alpriest.energystats.models.ReportResponse import com.alpriest.energystats.models.ReportVariable import com.alpriest.energystats.models.SoftwareVersion import com.alpriest.energystats.models.Time import com.alpriest.energystats.models.VariablesResponse import com.alpriest.energystats.ui.flow.home.dateFormat import com.alpriest.energystats.ui.statsgraph.ReportType import com.google.gson.Gson import com.google.gson.reflect.TypeToken import java.text.SimpleDateFormat import java.time.LocalDate import java.time.ZoneId import java.time.format.DateTimeFormatter import java.util.Locale class DemoNetworking : Networking { override suspend fun ensureHasToken() { // Do nothing } override suspend fun verifyCredentials(username: String, password: String) { // Assume valid } override suspend fun fetchBattery(deviceID: String): BatteryResponse { return when (deviceID) { "f3000-deviceid" -> BatteryResponse(power = 0.28, soc = 76, residual = 7550.0, temperature = 17.3) else -> BatteryResponse(power = 0.78, soc = 46, residual = 17510.0, temperature = 19.3) } } override suspend fun fetchBatterySettings(deviceSN: String): BatterySettingsResponse { return BatterySettingsResponse(20, minSoc = 30) } override suspend fun fetchReport( deviceID: String, variables: List<ReportVariable>, queryDate: QueryDate, reportType: ReportType ): ArrayList<ReportResponse> { val filename = when (reportType) { ReportType.day -> "res/raw/report_day.json" ReportType.month -> "res/raw/report_month.json" ReportType.year -> "res/raw/report_year.json" } val fileContent = this::class.java.classLoader?.getResource(filename)?.readText() val data: NetworkReportResponse = Gson().fromJson(fileContent, object : TypeToken<NetworkReportResponse>() {}.type) return data.result ?: ArrayList() } override suspend fun fetchAddressBook(deviceID: String): AddressBookResponse { if (deviceID == "f3000_deviceid") { return AddressBookResponse(softVersion = SoftwareVersion(master = "1.54", slave = "1.09", manager = "1.49")) } else { return AddressBookResponse(softVersion = SoftwareVersion(master = "2.54", slave = "1.09", manager = "1.56")) } } override suspend fun fetchRaw(deviceID: String, variables: List<RawVariable>, queryDate: QueryDate): ArrayList<RawResponse> { val result = rawData(deviceID) val formatter = DateTimeFormatter.ofPattern(dateFormat) val now = LocalDate.now() return ArrayList(result.map { response -> RawResponse( variable = response.variable, data = response.data.map { val simpleDate = SimpleDateFormat(dateFormat, Locale.getDefault()).parse(it.time) val localDateTime = simpleDate.toInstant().atZone(ZoneId.systemDefault()).toLocalDateTime() .withYear(now.year) .withMonth(now.monthValue) .withDayOfMonth(now.dayOfMonth) RawData(time = localDateTime.format(formatter), value = it.value) }.toTypedArray() ) }.toList()) } override suspend fun fetchDeviceList(): PagedDeviceListResponse { return PagedDeviceListResponse( currentPage = 1, pageSize = 1, total = 1, devices = arrayListOf( NetworkDevice(plantName = "plant 1", deviceID = "h1_deviceid", deviceSN = "998877", hasBattery = true, hasPV = true, deviceType = "H1-3.7-E", moduleSN = "ab"), NetworkDevice(plantName = "plant 2", deviceID = "f3000_deviceid", deviceSN = "123123", hasBattery = false, hasPV = true, deviceType = "F3000", moduleSN = "12") ) ) } override suspend fun fetchVariables(deviceID: String): List<RawVariable> { val fileContent = this::class.java.classLoader?.getResource("res/raw/variables.json")?.readText() val data: NetworkResponse<VariablesResponse> = Gson().fromJson(fileContent, object : TypeToken<NetworkResponse<VariablesResponse>>() {}.type) return data.result?.variables ?: listOf() } private fun rawData(deviceID: String): List<RawResponse> { val fileContent = this::class.java.classLoader?.getResource("res/raw/raw_$deviceID.json")?.readText() val data: NetworkRawResponse = Gson().fromJson(fileContent, object : TypeToken<NetworkRawResponse>() {}.type) return data.result?.toList() ?: listOf() } override suspend fun fetchEarnings(deviceID: String): EarningsResponse { return EarningsResponse( today = Earning( generation = 11.5, earnings = 54.2 ), currency = "GBP (£)", month = Earning( generation = 31.5, earnings = 154.2 ), year = Earning( generation = 81.5, earnings = 254.2 ), cumulate = Earning( generation = 121.5, earnings = 354.2 ), ) } override suspend fun setSoc(minGridSOC: Int, minSOC: Int, deviceSN: String) { } override suspend fun fetchBatteryTimes(deviceSN: String): BatteryTimesResponse { return BatteryTimesResponse( sn = deviceSN, times = listOf( ChargeTime(enableGrid = true, startTime = Time(hour = 0, minute = 0), endTime = Time(hour = 0, minute = 0)), ChargeTime(enableGrid = true, startTime = Time(hour = 0, minute = 0), endTime = Time(hour = 0, minute = 0)), ) ) } override suspend fun setBatteryTimes(deviceSN: String, times: List<ChargeTime>) { } override suspend fun fetchWorkMode(deviceID: String): DeviceSettingsGetResponse { return DeviceSettingsGetResponse(protocol = "H11300", values = DeviceSettingsValues("SelfUse")) } override suspend fun setWorkMode(deviceID: String, workMode: String) { } override suspend fun fetchDataLoggers(): PagedDataLoggerListResponse { return PagedDataLoggerListResponse( 1, 10, 1, listOf( PagedDataLoggerListResponse.DataLogger(moduleSN = "ABC123DEF456", moduleType = "W2", plantName = "<NAME>", version = "3.08", signal = 3, communication = 1), PagedDataLoggerListResponse.DataLogger(moduleSN = "123DEF456ABC", moduleType = "W2", plantName = "<NAME>", version = "3.08", signal = 1, communication = 0) ) ) } override suspend fun fetchErrorMessages() {} }
8
Kotlin
3
3
f7dd0882559da3f7417cb92a7b4fdcd853a43f35
7,734
EnergyStats-Android
MIT License
app/src/main/kotlin/io/github/nuhkoca/libbra/ui/NavHostFragment.kt
nuhkoca
252,193,036
false
null
/* * Copyright (C) 2020. <NAME>. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.github.nuhkoca.libbra.ui import android.content.Context import android.os.Bundle import androidx.fragment.app.FragmentFactory import androidx.navigation.fragment.NavHostFragment import io.github.nuhkoca.libbra.di.factory.LibbraFragmentFactory import io.github.nuhkoca.libbra.ui.di.MainScope import io.github.nuhkoca.libbra.util.ext.libbraApplication import javax.inject.Inject /** * A custom [NavHostFragment] to allow [LibbraFragmentFactory] to inflate fragments using this host. */ @MainScope class NavHostFragment : NavHostFragment() { @Inject lateinit var fragmentFactory: FragmentFactory override fun onAttach(context: Context) { libbraApplication.appComponent.mainComponent().create().inject(this) super.onAttach(context) } override fun onCreate(savedInstanceState: Bundle?) { childFragmentManager.fragmentFactory = fragmentFactory super.onCreate(savedInstanceState) } }
1
null
3
54
68c1b99d3c2966a8eec9395199379b98c21a340f
1,568
libbra
Apache License 2.0
src/main/kotlin/nu/staldal/htmxhttp4kdsl/TodoList.kt
mikaelstaldal
663,933,056
false
null
package nu.staldal.htmxhttp4kdsl import kotlinx.html.Entities import kotlinx.html.HTML import kotlinx.html.InputType import kotlinx.html.TBODY import kotlinx.html.ThScope import kotlinx.html.button import kotlinx.html.id import kotlinx.html.input import kotlinx.html.table import kotlinx.html.tbody import kotlinx.html.td import kotlinx.html.tfoot import kotlinx.html.th import kotlinx.html.thead import kotlinx.html.tr fun HTML.todoList(todoList: Iterable<Todo>) { page("To do list") { table(classes = "table table-hover") { thead { tr { th { scope = ThScope.col +"What to do" } th { scope = ThScope.col +"done" } th { scope = ThScope.col +Entities.nbsp } } } tbody { id = "todo-list" todoList.forEach { todo -> todoRow(todo) } } tfoot { tr { td { attributes["colspan"] = "2" input(classes = "form-control") { id = "description" name = "description" placeholder = "To do..." required = true type = InputType.text attributes["autofocus"] = "autofocus" } } td { button(classes = "btn btn-primary") { attributes["_"] = "on htmx:afterRequest put '' into #description.value" attributes["hx-post"] = "/todo" attributes["hx-include"] = "#description" attributes["hx-target"] = "#todo-list" attributes["hx-swap"] = "beforeend" +"Add" } } } } } } } fun TBODY.todoRow(todo: Todo) { tr { td { +todo.description } td { input { type = InputType.checkBox name = "done" value = "true" checked = todo.done attributes["hx-patch"] = "/todo/${todo.id}" attributes["hx-target"] = "closest tr" attributes["hx-swap"] = "outerHTML" } } td { button(classes = "btn btn-danger") { attributes["hx-confirm"] = "Are you sure?" attributes["hx-delete"] = "/todo/${todo.id}" attributes["hx-target"] = "closest tr" attributes["hx-swap"] = "outerHTML swap:0.5s" +"Delete" } } } }
0
Kotlin
1
2
ee9507d71cc15faa0ad00333b9628dd76df30370
3,086
htmx-http4k-dsl
Apache License 2.0
mahjong-utils-entry/src/commonMain/kotlin/mahjongutils/Coders.kt
ssttkkl
547,654,890
false
null
package mahjongutils import kotlin.reflect.KType import kotlin.reflect.typeOf interface ResultEncoder<out RAW_RESULT : Any> { fun <RESULT : Any> encodeResult(result: Result<RESULT>, resultType: KType): RAW_RESULT } inline fun <RAW_RESULT : Any, reified RESULT : Any> ResultEncoder<RAW_RESULT>.encodeResult( result: Result<RESULT> ): RAW_RESULT { return encodeResult(result, typeOf<Result<RESULT>>()) } interface ParamsDecoder<in RAW_PARAMS : Any> { fun <PARAMS : Any> decodeParams(rawParams: RAW_PARAMS, paramsType: KType): PARAMS } inline fun <RAW_PARAMS : Any, reified PARAMS : Any> ParamsDecoder<RAW_PARAMS>.decodeParams( rawParams: RAW_PARAMS ): PARAMS { return decodeParams(rawParams, typeOf<PARAMS>()) }
2
Kotlin
0
9
571cebf84a5bf04337f162234e2f610954f99e8c
740
mahjong-utils
MIT License
vmtools/src/main/kotlin/com/vmloft/develop/library/tools/widget/barrage/VMBarrageView.kt
lzan13
78,939,095
false
null
package com.vmloft.develop.library.tools.widget.barrage import android.animation.Animator import android.animation.Animator.AnimatorListener import android.animation.ObjectAnimator import android.content.Context import android.util.AttributeSet import android.view.LayoutInflater import android.view.View import android.view.animation.LinearInterpolator import android.widget.RelativeLayout import com.vmloft.develop.library.tools.utils.VMDimen import com.vmloft.develop.library.tools.utils.VMSystem import com.vmloft.develop.library.tools.utils.logger.VMLog import java.util.concurrent.LinkedBlockingQueue /** * Create by lzan13 on 2020/6/3 17:14 * 描述:弹幕控件 */ class VMBarrageView<T> @JvmOverloads constructor(context: Context?, attrs: AttributeSet? = null, defStyleAttr: Int = 0) : RelativeLayout(context, attrs, defStyleAttr) { // 默认最大展示 100 个 private val defaultMaxSize: Int = 100 // 弹幕动画默认耗时 private val defaultDuration: Long = 5 * 1000 // 弹幕之间最大间隔时间 private val defaultMaxInterval: Long = 100 // 是否激活中 private var isActive: Boolean = false private var isPause: Boolean = false // 最大数量 private var mMaxSize: Int = defaultMaxSize // 活动中的数量 private var mActiveSize: Int = 0 // 最后一个弹幕弹出时间 private var mLastTime: Long = 0 // View 构建器 private lateinit var mCreator: VMViewCreator<T> // 数据队列 private lateinit var mDataQueue: LinkedBlockingQueue<T> // View 队列,循环利用 private lateinit var mViewQueue: LinkedBlockingQueue<View> // Anim 集合 private var mAnimList: MutableList<ObjectAnimator> = mutableListOf() /** * 设置 View 构造器 */ fun setCreator(creator: VMViewCreator<T>): VMBarrageView<T> { if (isActive) { return this } mCreator = creator return this } /** * 设置最大数 */ fun setMaxSize(size: Int): VMBarrageView<T> { if (isActive) { return this } if (size <= defaultMaxSize) { mMaxSize = size } return this } /** * 开始构建 */ fun create(list: MutableList<T>?): VMBarrageView<T> { if (isActive) { return this } mDataQueue = LinkedBlockingQueue(mMaxSize * 5) if (list !== null) { mDataQueue.addAll(list) } mViewQueue = LinkedBlockingQueue(mMaxSize) return this } /** * 添加一个新的弹幕数据 */ fun addBarrageList(list: List<T>) { if (isActive) { mDataQueue.addAll(list) } } /** * 添加一个新的弹幕数据 */ fun addBarrage(bean: T) { if (isActive) { mDataQueue.add(bean) } } /** * 启动弹幕 */ fun start() { if (!isActive) { isActive = true startLoop() } } /** * 继续弹幕 */ fun resume() { isPause = false if (isActive) { for (anim in mAnimList) { anim.resume() } } } /** * 暂停弹幕 */ fun pause() { isPause = true if (isActive) { for (anim in mAnimList) { anim.pause() } } } /** * 停止弹幕 */ fun stop() { if (isActive) { isActive = false mDataQueue.clear() mViewQueue.clear() mAnimList.clear() removeAllViews() } } /** * 开启循环 */ private fun startLoop() { VMSystem.runTask { while (isActive && !isPause) { val bean: T = mDataQueue.take() var view: View? = mViewQueue.poll() if (view === null) { if (mActiveSize < mMaxSize) { view = createView() mViewQueue.put(view) } view = mViewQueue.take() } var randomTime = (Math.random() * defaultMaxInterval).toLong() val intervalTime = System.currentTimeMillis() - mLastTime if (intervalTime < randomTime) { Thread.sleep(randomTime - intervalTime) } mLastTime = System.currentTimeMillis() VMSystem.runInUIThread({ mActiveSize++ barrageAnim(view!!, bean) }) } } } /** * 弹幕动画 */ private fun barrageAnim(view: View, bean: T) { // 将 View 加入容器 addView(view) // 绑定数据 mCreator.onBind(view, bean) val width = width.toFloat() // 这里高度加上 48dp 防止随机到最底部时把内容挤压 val height = height.toFloat() - VMDimen.dp2px(48) // 随机设置位置 val randomTop = (Math.random() * height).toInt() val params: LayoutParams = view.layoutParams as LayoutParams params.topMargin = randomTop view.layoutParams = params val randomDuration = (Math.random() * defaultDuration + defaultDuration).toInt() val anim = ObjectAnimator.ofFloat(view, "translationX", width, -width) anim.duration = randomDuration.toLong() anim.interpolator = LinearInterpolator() anim.addListener(object : AnimatorListener { override fun onAnimationRepeat(animation: Animator) {} override fun onAnimationEnd(animation: Animator) { // 结束之后移除 view 并添加到缓存 removeView(view) mViewQueue.put(view) mDataQueue.put(bean) mAnimList.remove(animation) mActiveSize-- } override fun onAnimationCancel(animation: Animator) {} override fun onAnimationStart(animation: Animator) {} }); mAnimList.add(anim) anim.start() } /** * 创建弹幕 */ private fun createView(): View { return LayoutInflater.from(context).inflate(mCreator.layoutId(), null) } override fun onVisibilityChanged(changedView: View, visibility: Int) { super.onVisibilityChanged(changedView, visibility) VMLog.d("onVisibilityChanged $visibility") if (visibility == 0) { // View 可见 继续 resume() } else { // View 不可见 暂停 pause() } } }
0
null
14
34
c6eca3fb479d82ca14ca3bdcc3fb5f5494a4db0c
6,374
VMLibrary
MIT License
app/src/main/java/com/breezebppoddar/features/stockAddCurrentStock/model/CurrentStockGetDataDtls.kt
DebashisINT
518,335,697
false
{"Kotlin": 14689181, "Java": 1021110}
package com.breezebppoddar.features.stockAddCurrentStock.model import com.breezebppoddar.features.stockCompetetorStock.model.ComGetProduct class CurrentStockGetDataDtls { var visited_datetime: String? = null var stock_id: String? = null var shop_id: String? = null var total_qty: String? = null var product_list:ArrayList<CurrGetProduct>? = null }
0
Kotlin
0
0
297531612f36f84abcf33edf6809dacc55c3ac99
369
BPPODDARHOSPITAL
Apache License 2.0
idea/testData/inspections/replaceCallWithComparison/test.kt
JakeWharton
99,388,807
false
null
fun foo() { 1.equals(1) // YES !1.equals(2) // YES 1.compareTo(1) // NO 1.compareTo(1) == 0 // NO 2.compareTo(1) > 0 // YES 0 >= 1.compareTo(2) // YES 2.plus(2) // YES (information) 2.times(2) // YES (information) }
0
null
4
83
4383335168338df9bbbe2a63cb213a68d0858104
287
kotlin
Apache License 2.0
src/data/src/commonMain/kotlin/com/gabrielbmoro/moviedb/data/repository/datasources/database/room/FavoriteMoviesDAO.kt
gabrielbmoro
574,746,759
false
null
package com.gabrielbmoro.moviedb.data.repository.datasources.database.room import androidx.room.Dao import androidx.room.Insert import androidx.room.OnConflictStrategy import androidx.room.Query import com.gabrielbmoro.moviedb.data.repository.datasources.database.room.dto.FavoriteMovieDTO @Dao interface FavoriteMoviesDAO { @Query("SELECT * FROM favorite_movies") suspend fun allFavoriteMovies(): List<FavoriteMovieDTO> @Query("SELECT * FROM favorite_movies WHERE title = :title") suspend fun isThereAMovie(title: String): List<FavoriteMovieDTO> @Query("DELETE FROM favorite_movies WHERE title = :movieTitle") suspend fun removeFavorite(movieTitle: String) @Insert(onConflict = OnConflictStrategy.REPLACE) suspend fun saveFavorite(movieDTO: FavoriteMovieDTO) }
9
null
9
62
0ae8c7ae825162eac685513c293aeb0556eb43ea
800
MovieDB-App
MIT License
app/src/main/java/io/github/alessandrojean/toshokan/presentation/ui/publishers/PublishersViewModel.kt
alessandrojean
495,493,156
false
null
package io.github.alessandrojean.toshokan.presentation.ui.publishers import androidx.lifecycle.ViewModel import androidx.lifecycle.viewModelScope import dagger.hilt.android.lifecycle.HiltViewModel import io.github.alessandrojean.toshokan.repository.PublishersRepository import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.StateFlow import kotlinx.coroutines.flow.asStateFlow import kotlinx.coroutines.flow.update import kotlinx.coroutines.launch import javax.inject.Inject data class PublishersState( val showDeleteWarning: Boolean = false, val selected: List<Long> = emptyList(), ) @HiltViewModel class PublishersViewModel @Inject constructor( private val publishersRepository: PublishersRepository ) : ViewModel() { private val _uiState = MutableStateFlow(PublishersState()) val uiState: StateFlow<PublishersState> = _uiState.asStateFlow() val publishers = publishersRepository.publishers fun showDeleteWarning() = viewModelScope.launch { _uiState.update { it.copy(showDeleteWarning = true) } } fun hideDeleteWarning() = viewModelScope.launch { _uiState.update { it.copy(showDeleteWarning = false) } } fun clearSelection() = viewModelScope.launch { _uiState.update { it.copy(selected = emptyList()) } } fun toggleSelection(id: Long) = viewModelScope.launch { if (id !in uiState.value.selected) { _uiState.update { it.copy(selected = uiState.value.selected + id) } } else { _uiState.update { it.copy( selected = uiState.value.selected.filter { selId -> selId != id } ) } } } fun deleteSelected() = viewModelScope.launch { publishersRepository.bulkDelete(uiState.value.selected) clearSelection() } }
11
Kotlin
1
5
96717312b7a5090901c8604cd069d9468995e99e
1,743
toshokan-android
MIT License
example/customize-everything/customize-everything.main.kts
fiddlededee
835,952,301
false
null
#!/usr/bin/env kotlin @file:DependsOn("ru.fiddlededee:unidoc-publisher:0.7.4") @file:DependsOn("org.redundent:kotlin-xml-builder:1.9.0") import org.redundent.kotlin.xml.Node as XmlNode import converter.FodtConverter import fodt.parseStringAsXML import model.* import reader.GenericHtmlReader import reader.HtmlNode import reader.UnknownTagProcessing import writer.OdWriter import writer.OdtStyleList import java.io.File val htmlToConvert = """ <p>Some paragraph text</p> <my-tag my-attribute='attribute-value'>Some my tag text</my-tag> """.trimIndent() interface MyBackendWriter : BackendWriter { fun write(myNode: MyNode) } class MyNode(var myAttribute: String, override val isInline: Boolean = false) : Node() { private fun write(bw: MyBackendWriter) { bw.write(this) } override fun write(bw: BackendWriter) { this.write(bw as MyBackendWriter) } } class MyHtmlReader( node: Node, htmlNode: HtmlNode, unknownTagProcessingRule: HtmlNode.() -> UnknownTagProcessing = { UnknownTagProcessing.UNDEFINDED }, ) : GenericHtmlReader(node, htmlNode, unknownTagProcessingRule) { override val detectors = arrayOf(::detectMyTag) + super.detectors private fun detectMyTag() { detectByExpression({ it.nodeName() == "my-tag" }) { confirmedNode -> val myNode = MyNode(confirmedNode.attr("my-attribute")) parseNode(addToAST(myNode), confirmedNode) } } } class MyOdWriter(preOdNode: XmlNode? = null, odtStyleList: OdtStyleList) : OdWriter(preOdNode, odtStyleList), MyBackendWriter { override fun newInstance(xmlNode: XmlNode, odtStyleList: OdtStyleList): OdWriter { return MyOdWriter(xmlNode, odtStyleList) } override fun write(myNode: MyNode) { preOdNode.apply { "text:p" { attribute("text:style-name", "Text body") process(myNode) -" (${myNode.myAttribute})" } } } } class MyFodtConverter(init: FodtConverter.() -> Unit) : FodtConverter(init) { override fun newReaderInstance( ast: Node, htmlNode: HtmlNode, unknownTagProcessingRule: HtmlNode.() -> UnknownTagProcessing, customNodeProcessingRule: Node.(htmlNode: HtmlNode) -> Unit ): GenericHtmlReader { return MyHtmlReader(ast, htmlNode, unknownTagProcessingRule) } override fun newOdWriterInstance(odtStyleList: OdtStyleList): OdWriter { return MyOdWriter(odtStyleList = odtStyleList) } } MyFodtConverter { html = htmlToConvert template = File("${__FILE__.parent}/template.fodt").readText() convert() File("${__FILE__.parent}/output/customized-output.fodt") .writeText(fodt()) }.preList
1
null
1
6
790e915d0d44226b63f906e95fe21d9f401967ec
2,754
unidoc-publisher
Apache License 2.0
subprojects/configuration-cache/src/main/kotlin/org/gradle/configurationcache/RelevantProjectsRegistry.kt
gradle
302,322
false
null
/* * Copyright 2020 the original author or authors. * * 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.gradle.configurationcache import org.gradle.api.internal.artifacts.configurations.ConfigurationInternal import org.gradle.api.internal.artifacts.configurations.ProjectDependencyObservedListener import org.gradle.api.internal.artifacts.ivyservice.resolveengine.projectresult.ResolvedProjectConfiguration import org.gradle.api.internal.project.ProjectState import org.gradle.execution.plan.Node import org.gradle.internal.build.BuildState import org.gradle.internal.service.scopes.Scopes import org.gradle.internal.service.scopes.ServiceScope @ServiceScope(Scopes.Build::class) class RelevantProjectsRegistry( private val build: BuildState ) : ProjectDependencyObservedListener { private val targetProjects = mutableSetOf<ProjectState>() fun relevantProjects(nodes: List<Node>): Set<ProjectState> = targetProjects + nodes.mapNotNull { node -> projectStateOf(node)?.takeIf(::isLocalProject) } private fun projectStateOf(node: Node) = node.owningProject?.owner private fun isLocalProject(projectState: ProjectState) = projectState.owner === build override fun dependencyObserved(consumingProject: ProjectState?, targetProject: ProjectState, requestedState: ConfigurationInternal.InternalState, target: ResolvedProjectConfiguration) { targetProjects.add(targetProject) } }
2,095
null
3792
13,076
c1b02a85c1d02816ba0c59fd02b656f6187a4472
2,001
gradle
Apache License 2.0
app/src/main/java/com/kickstarter/services/mutations/CreateCheckoutData.kt
kickstarter
76,278,501
false
null
package com.kickstarter.services.mutations import com.kickstarter.libs.RefTag import com.kickstarter.models.Project import com.kickstarter.models.Reward data class CreateCheckoutData(val project: Project, val amount: String, val locationId: String?, val rewardsIds: List<Reward> = listOf(), val refTag: RefTag?)
8
null
989
5,752
a9187fb484c4d12137c7919a2a53339d67cab0cb
314
android-oss
Apache License 2.0
user/src/main/java/com/harera/hyperpanda/HyperPandaApp.kt
hassan0shaban
297,707,874
false
{"Kotlin": 335864}
package com.harera.hyperpanda import android.app.Application import com.google.firebase.FirebaseApp import com.harera.local.MarketDao import dagger.hilt.android.HiltAndroidApp import javax.inject.Inject @HiltAndroidApp class HyperPandaApp : Application() { @Inject lateinit var database: MarketDao override fun onCreate() { super.onCreate() FirebaseApp.initializeApp(applicationContext) } }
0
Kotlin
0
0
660c829827b9fc85d1ea5a50a22f82f746637730
427
Hyber-Panda
Apache License 2.0
codegen-renderers/src/main/kotlin/io/vrap/codegen/languages/extensions/DescriptionFacetExtensions.kt
pkbharath
218,032,727
true
{"Kotlin": 495067, "RAML": 38932, "PHP": 5795, "TypeScript": 2505, "Dockerfile": 328, "Shell": 327}
package io.vrap.codegen.languages.extensions import io.vrap.rmf.codegen.doc.toHtml import io.vrap.rmf.raml.model.types.AnnotationsFacet import io.vrap.rmf.raml.model.types.DescriptionFacet import io.vrap.rmf.raml.model.types.ObjectInstance import io.vrap.rmf.raml.model.types.StringInstance import org.commonmark.parser.Parser import org.commonmark.renderer.html.HtmlRenderer private val HTML_RENDERER = HtmlRenderer.builder().build() private val PARSER = Parser.builder().build() /** * This extension method converts the description from markdown to html and wraps the result in doc comment. * * @return the description of this as a doc comment */ fun DescriptionFacet.toComment() = this.toHtml()?.let {"/**\n${it.lines().map { '\t'+it }.joinToString(separator = "\n")}\n*/"}?:"" /** * This method extracts the javadoc comment from the "enumDescriptions" annotation - which is of object type. * Each key corresponds to an enum value and the value contains the markdown description of the enum. * <pre> * ResourceType: * (enumDescriptions): * channel: The channel resource type. * type: string * enum: * - channel * - cart-discount * </pre> */ fun StringInstance.toComment(): String? { val enumValues = (eContainer() as AnnotationsFacet).getAnnotation("enumDescriptions") if (enumValues?.value is ObjectInstance) { val description = (enumValues?.value as ObjectInstance).getValue(value) return if (description is StringInstance) { description.value?.let(PARSER::parse)?.let(HTML_RENDERER::render)?.let { "/**\n${it.lines().map { '\t' + it }.joinToString(separator = "\n")}\n*/" } } else { null } } return null }
0
null
0
0
75db7d8b313b6a90f7daa89fbd2f5d9b2ecaf361
1,727
rmf-codegen
Apache License 2.0
src/main/kotlin/us/frollo/frollosdk/model/api/goals/GoalPeriodResponse.kt
frollous
261,670,220
false
null
/* * Copyright 2019 Frollo * * 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 us.frollo.frollosdk.model.api.goals import com.google.gson.annotations.SerializedName import us.frollo.frollosdk.model.coredata.goals.GoalTrackingStatus import java.math.BigDecimal internal data class GoalPeriodResponse( @SerializedName("id") val goalPeriodId: Long, @SerializedName("goal_id") val goalId: Long, @SerializedName("start_date") val startDate: String, // yyyy-MM-dd @SerializedName("end_date") val endDate: String, // yyyy-MM-dd @SerializedName("tracking_status") var trackingStatus: GoalTrackingStatus, @SerializedName("current_amount") val currentAmount: BigDecimal, @SerializedName("target_amount") val targetAmount: BigDecimal, @SerializedName("required_amount") val requiredAmount: BigDecimal, @SerializedName("index") val index: Int )
6
Kotlin
0
2
0d616cba73516453ed1183d903521204d871df85
1,390
frollo-android-sdk
Apache License 2.0
src/main/kotlin/no/skatteetaten/aurora/mokey/service/OpenShiftUserClient.kt
Skatteetaten
104,215,122
false
null
package no.skatteetaten.aurora.mokey.service import com.fkorotkov.kubernetes.metadata import com.fkorotkov.kubernetes.newNamespace import io.fabric8.kubernetes.api.model.Namespace import io.fabric8.kubernetes.api.model.authorization.SelfSubjectAccessReview import io.fabric8.openshift.api.model.Project import kotlinx.coroutines.reactive.awaitFirstOrNull import no.skatteetaten.aurora.kubernetes.KubernetesCoroutinesClient import no.skatteetaten.aurora.springboot.getToken import org.springframework.beans.factory.annotation.Qualifier import org.springframework.security.core.context.ReactiveSecurityContextHolder import org.springframework.stereotype.Service @Suppress("SpringJavaInjectionPointsAutowiringInspection") @Service class OpenShiftUserClient(@Qualifier("managementCoroutinesClient") val client: KubernetesCoroutinesClient) { suspend fun getNamespaceByNameOrNull(p: String): Namespace? = client.getOrNull( resource = newNamespace { metadata { name = p } }, token = getToken() ) suspend fun selfSubjectAccessReview(review: SelfSubjectAccessReview): SelfSubjectAccessReview = client.post( resource = review, token = getToken() ) // This will not work on kubernets, and you cannot fetch all namespaces either... suspend fun getAllProjects(): List<Project> = client.getMany(token = getToken()) private suspend fun getToken() = ReactiveSecurityContextHolder.getContext().awaitFirstOrNull()?.authentication?.getToken() }
1
Kotlin
0
2
4e4aaad197f0617c2d5424e353cbd6a6815ea824
1,539
mokey
Apache License 2.0
app/src/main/java/io/horizontalsystems/bankwallet/modules/safe4/wsafe2safe/SendWsafeService.kt
SAFE-anwang
438,491,711
false
null
package io.horizontalsystems.bankwallet.modules.safe4.wsafe2safe import io.horizontalsystems.bankwallet.R import io.horizontalsystems.bankwallet.core.Clearable import io.horizontalsystems.bankwallet.core.ISendEthereumAdapter import io.horizontalsystems.bankwallet.core.providers.Translator import io.horizontalsystems.bankwallet.entities.Address import io.horizontalsystems.bankwallet.modules.safe4.SafeInfoManager import io.horizontalsystems.bankwallet.modules.send.evm.SendEvmData import io.horizontalsystems.bankwallet.modules.sendevm.IAmountInputService import io.horizontalsystems.bankwallet.modules.sendevm.IAvailableBalanceService import io.horizontalsystems.marketkit.models.BlockchainType import io.horizontalsystems.marketkit.models.Token import io.horizontalsystems.wsafekit.WsafeKit import io.reactivex.BackpressureStrategy import io.reactivex.Flowable import io.reactivex.subjects.PublishSubject import java.math.BigDecimal import java.math.BigInteger import java.util.* import io.horizontalsystems.ethereumkit.models.Address as EvmAddress class SendWsafeService( val sendCoin: Token, val adapter: ISendEthereumAdapter ) : IAvailableBalanceService, IAmountInputService, Clearable { private val stateSubject = PublishSubject.create<State>() var state: State = State.NotReady private set(value) { field = value stateSubject.onNext(value) } val stateObservable: Flowable<State> get() = stateSubject.toFlowable(BackpressureStrategy.BUFFER) private var evmAmount: BigInteger? = null private var addressData: AddressData? = null private var toSafeAddr: Address? = null var addressEnable: Boolean = false private val amountCautionSubject = PublishSubject.create<AmountCaution>() private var amountCaution: AmountCaution = AmountCaution() set(value) { field = value amountCautionSubject.onNext(value) } val amountCautionObservable: Flowable<AmountCaution> get() = amountCautionSubject.toFlowable(BackpressureStrategy.BUFFER) private fun syncState() { val amountError = this.amountCaution.error val evmAmount = this.evmAmount val addressData = this.addressData state = if (addressEnable && amountError == null && evmAmount != null && addressData != null) { if(toSafeAddr != null){ val wsafeKit = WsafeKit.getInstance(adapter.evmKitWrapper.evmKit.chain) val safeAddr = toSafeAddr!!.hex val transactionData = wsafeKit.transactionData(evmAmount, safeAddr) val additionalInfo = SendEvmData.AdditionalInfo.Send(SendEvmData.SendInfo()) State.Ready(SendEvmData(transactionData, additionalInfo)) } else { State.NotReady } } else { State.NotReady } } @Throws private fun validEvmAmount(amount: BigDecimal): BigInteger { val evmAmount = try { amount.movePointRight(sendCoin.decimals).toBigInteger() } catch (error: Throwable) { throw AmountError.InvalidDecimal } if (amount > adapter.balanceData.available) { throw AmountError.InsufficientBalance } return evmAmount } //region IAvailableBalanceService override val availableBalance: BigDecimal get() = adapter.balanceData.available //endregion //region IAmountInputService override val amount: BigDecimal get() = BigDecimal.ZERO override val coin: Token get() = sendCoin override val balance: BigDecimal get() = adapter.balanceData.available override val amountObservable: Flowable<BigDecimal> get() = Flowable.empty() override val coinObservable: Flowable<Optional<Token>> get() = Flowable.empty() override fun onChangeAmount(amount: BigDecimal) { if (amount > BigDecimal.ZERO) { var amountWarning: AmountWarning? = null try { if (amount == balance && (sendCoin.blockchainType is BlockchainType.Ethereum || sendCoin.blockchainType is BlockchainType.BinanceSmartChain || sendCoin.blockchainType is BlockchainType.Polygon)) { amountWarning = AmountWarning.CoinNeededForFee } evmAmount = validEvmAmount(amount) amountCaution = AmountCaution(null, amountWarning) } catch (error: Throwable) { evmAmount = null amountCaution = AmountCaution(error, null) } } else { evmAmount = null amountCaution = AmountCaution() } syncState() } //endregion //region IRecipientAddressService fun setRecipientAddress(address: Address?, to: Address?) { addressData = address?.let { AddressData(evmAddress = EvmAddress(it.hex), domain = it.domain) } toSafeAddr = to syncState() } override fun clear() = Unit //endregion sealed class State { class Ready(val sendData: SendEvmData) : State() object NotReady : State() } sealed class AmountError : Throwable() { object InvalidDecimal : AmountError() object InsufficientBalance : AmountError() { override fun getLocalizedMessage(): String { return Translator.getString(R.string.Swap_ErrorInsufficientBalance) } } } class AmountCaution(val error: Throwable? = null, val amountWarning: AmountWarning? = null) enum class AmountWarning { CoinNeededForFee } data class AddressData(val evmAddress: EvmAddress, val domain: String?) fun isSendMinAmount(safeInfoPO: SafeInfoManager.SafeInfoPO): Boolean { val minSafe = BigDecimal(safeInfoPO.minamount).movePointRight(18) val safeAmount = (evmAmount ?: 0) as BigInteger return BigDecimal(safeAmount) >= minSafe } }
0
null
3
3
a6fb06ea11a0cb366dcf093dcbeb053e628877a9
6,020
SafeWallet-android
MIT License
analysis/analysis-api-platform-interface/src/org/jetbrains/kotlin/analysis/api/platform/declarations/KotlinCompositeDeclarationProvider.kt
JetBrains
3,432,266
false
null
/* * Copyright 2010-2023 JetBrains s.r.o. and Kotlin Programming Language contributors. * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ package org.jetbrains.kotlin.analysis.providers.impl.declarationProviders import org.jetbrains.kotlin.analysis.providers.KotlinCompositeProvider import org.jetbrains.kotlin.analysis.providers.KotlinDeclarationProvider import org.jetbrains.kotlin.analysis.providers.impl.KotlinCompositeProviderFactory import org.jetbrains.kotlin.name.CallableId import org.jetbrains.kotlin.name.ClassId import org.jetbrains.kotlin.name.FqName import org.jetbrains.kotlin.name.Name import org.jetbrains.kotlin.psi.* import org.jetbrains.kotlin.utils.flatMapToNullableSet public class CompositeKotlinDeclarationProvider private constructor( override val providers: List<KotlinDeclarationProvider> ) : KotlinDeclarationProvider(), KotlinCompositeProvider<KotlinDeclarationProvider> { override fun getClassLikeDeclarationByClassId(classId: ClassId): KtClassLikeDeclaration? { return providers.firstNotNullOfOrNull { it.getClassLikeDeclarationByClassId(classId) } } override fun getAllClassesByClassId(classId: ClassId): Collection<KtClassOrObject> { return providers.flatMap { it.getAllClassesByClassId(classId) } } override fun getAllTypeAliasesByClassId(classId: ClassId): Collection<KtTypeAlias> { return providers.flatMap { it.getAllTypeAliasesByClassId(classId) } } override fun getTopLevelKotlinClassLikeDeclarationNamesInPackage(packageFqName: FqName): Set<Name> { return providers.flatMapTo(mutableSetOf()) { it.getTopLevelKotlinClassLikeDeclarationNamesInPackage(packageFqName) } } override fun getTopLevelProperties(callableId: CallableId): Collection<KtProperty> { return providers.flatMapTo(mutableListOf()) { it.getTopLevelProperties(callableId) } } override fun getTopLevelFunctions(callableId: CallableId): Collection<KtNamedFunction> { return providers.flatMapTo(mutableListOf()) { it.getTopLevelFunctions(callableId) } } override fun getTopLevelCallableFiles(callableId: CallableId): Collection<KtFile> { return providers.flatMapTo(mutableListOf()) { it.getTopLevelCallableFiles(callableId) } } override fun getTopLevelCallableNamesInPackage(packageFqName: FqName): Set<Name> { return providers.flatMapTo(mutableSetOf()) { it.getTopLevelCallableNamesInPackage(packageFqName) } } override fun findFilesForFacadeByPackage(packageFqName: FqName): Collection<KtFile> { return providers.flatMapTo(mutableListOf()) { it.findFilesForFacadeByPackage(packageFqName) } } override fun findFilesForFacade(facadeFqName: FqName): Collection<KtFile> { return providers.flatMapTo(mutableListOf()) { it.findFilesForFacade(facadeFqName) } } override fun findInternalFilesForFacade(facadeFqName: FqName): Collection<KtFile> { return providers.flatMapTo(mutableListOf()) { it.findInternalFilesForFacade(facadeFqName) } } override fun findFilesForScript(scriptFqName: FqName): Collection<KtScript> { return providers.flatMapTo(mutableListOf()) { it.findFilesForScript(scriptFqName) } } override fun computePackageSetWithTopLevelCallableDeclarations(): Set<String>? { return providers.flatMapToNullableSet { it.computePackageSetWithTopLevelCallableDeclarations() } } public companion object { public val factory: KotlinCompositeProviderFactory<KotlinDeclarationProvider> = KotlinCompositeProviderFactory( EmptyKotlinDeclarationProvider, ::CompositeKotlinDeclarationProvider, ) public fun create(providers: List<KotlinDeclarationProvider>): KotlinDeclarationProvider = factory.create(providers) } }
182
null
5748
49,172
33eb9cef3d146062c103f9853d772f0a1da0450e
3,866
kotlin
Apache License 2.0
idea/tests/testData/codeInsight/hints/types/QualifiedReferences.kt
JetBrains
278,369,660
false
null
// MODE: local_variable package p class A { class B { class C { class D } } inner class E enum class F { enumCase } } fun foo() { val v1 = A.B.C.D() val v2 = p.A.B.C.D() val v3/*<# : |[p.A.E:kotlin.fqn.class]A.E #>*/ = A().E() val v4 = p.A.F.enumCase val v5 = A.F.enumCase val v6 = p.A() }
284
null
5162
82
cc81d7505bc3e9ad503d706998ae8026c067e838
359
intellij-kotlin
Apache License 2.0
src/commonMain/kotlin/requests/InquireBalance.kt
devngho
565,833,597
false
null
package io.github.devngho.kisopenapi.requests import com.ionspin.kotlin.bignum.decimal.BigDecimal import com.ionspin.kotlin.bignum.integer.BigInteger import io.github.devngho.kisopenapi.KisOpenApi import io.github.devngho.kisopenapi.requests.response.* import io.github.devngho.kisopenapi.requests.util.* import io.github.devngho.kisopenapi.requests.util.YNSerializer.YN import io.ktor.client.call.* import io.ktor.client.request.* import kotlinx.serialization.Contextual import kotlinx.serialization.SerialName import kotlinx.serialization.Serializable class InquireBalance(override val client: KisOpenApi): DataRequest<InquireBalance.InquireBalanceData, InquireBalance.InquireBalanceResponse> { private val url = if (client.isDemo) "https://openapivts.koreainvestment.com:29443/uapi/domestic-stock/v1/trading/inquire-balance" else "https://openapi.koreainvestment.com:9443/uapi/domestic-stock/v1/trading/inquire-balance" @Serializable data class InquireBalanceResponse( @SerialName("tr_id") override var tradeId: String?, @SerialName("gt_uid") override var globalTradeID: String?, @SerialName("msg_cd") override val code: String?, @SerialName("msg1") override val msg: String?, @SerialName("rt_cd") @Serializable(with = ResultCodeSerializer::class) override val isOk: Boolean?, @SerialName("ctx_area_fk100") val continuousAreaFK: String?, @SerialName("ctx_area_nk100") val continuousAreaNK: String?, var output1: List<InquireBalanceResponseOutput1>?, var output2: List<InquireBalanceResponseOutput2>?, override var next: (suspend () -> Response)?, @SerialName("tr_cont") override var tradeContinuous: String? ): Response, TradeContinuousResponse, TradeIdMsg { override val errorDescription: String? = null override val errorCode: String? = null } @Serializable data class InquireBalanceResponseOutput1( @SerialName("pdno") override val ticker: String?, @SerialName("prdt_name") override val productName: String?, @SerialName("trad_dvsn_name") override val buySellDivision: String?, @SerialName("bfdy_buy_qty") @Contextual override val buyCountYesterday: BigInteger?, @SerialName("bfdy_sll_qty") @Contextual override val sellCountYesterday: BigInteger?, @SerialName("thdt_buy_qty") @Contextual override val buyCountToday: BigInteger?, @SerialName("thdt_sll_qty") @Contextual override val sellCountToday: BigInteger?, @SerialName("hldg_qty") @Contextual override val count: BigInteger?, @SerialName("ord_psbl_qty") @Contextual override val countCanOrder: BigInteger?, @SerialName("pchs_avg_pric") @Contextual override val buyAveragePrice: BigDecimal?, @SerialName("pchs_amt") @Contextual override val buyAmount: BigInteger?, @SerialName("prpr") @Contextual override val price: BigInteger?, @SerialName("evlu_amt") @Contextual override val evalAmount: BigInteger?, @SerialName("evlu_pfls_amt") @Contextual override val evalProfitLossAmount: BigInteger?, @SerialName("evlu_pfls_rt") @Contextual override val evalProfitLossRate: BigDecimal?, @SerialName("evlu_erng_rt") @Contextual override val evalProfitRate: BigDecimal?, @SerialName("loan_dt") override val loanDate: String?, @SerialName("loan_amt") @Contextual override val loanAmount: BigInteger?, @SerialName("stln_slng_chgs") @Contextual override val amountShortSelling: BigInteger?, @SerialName("expd_dt") override val expireDate: String?, @SerialName("fltt_rt") @Contextual override val changeRate: BigDecimal?, @SerialName("bfdy_cprs_icdc") @Contextual override val changeFromYesterday: BigInteger?, @SerialName("item_mgna_rt_name") override val stockMarginRateName: String?, @SerialName("grta_rt_name") override val depositRateName: String?, @SerialName("sbst_pric") @Contextual override val substitutePrice: BigInteger?, @SerialName("stck_loan_unpr") @Contextual override val stockLoanPrice: BigInteger?, ): BalanceAccountStock { override val errorDescription: String? = null override val errorCode: String? = null } @Serializable data class InquireBalanceResponseOutput2( @SerialName("dnca_tot_amt") @Contextual override val depositReceivedTotalAmount: BigInteger?, @SerialName("nxdy_excc_amt") @Contextual override val execAmountNextDay: BigInteger?, @SerialName("prvs_rcdl_excc_amt") @Contextual override val domesticExecAmount: BigInteger?, @SerialName("cma_evlu_amt") @Contextual override val cmaEvalAmount: BigInteger?, @SerialName("bfdy_buy_amt") @Contextual override val buyAmountFromYesterday: BigInteger?, @SerialName("thdt_buy_amt") @Contextual override val buyAmountToday: BigInteger?, @SerialName("nxdy_auto_rdpt_amt") @Contextual override val autoRepayNextDayAmount: BigInteger?, @SerialName("bfdy_sll_amt") @Contextual override val sellAmountFromYesterday: BigInteger?, @SerialName("thdt_sll_amt") @Contextual override val sellAmountToday: BigInteger?, @SerialName("d2_auto_rdpt_amt") @Contextual override val autoRepayD2Amount: BigInteger?, @SerialName("bfdy_tlex_amt") @Contextual override val tlexAmountFromYesterday: BigInteger?, @SerialName("thdt_tlex_amt") @Contextual override val tlexAmountToday: BigInteger?, @SerialName("tot_loan_amt") @Contextual override val totalLoanAmount: BigInteger?, @SerialName("scts_evlu_amt") @Contextual override val sctsEvalAmount: BigInteger?, @SerialName("tot_evlu_amt") @Contextual override val totalEvalAmount: BigInteger?, @SerialName("nass_amt") @Contextual override val netWorthAmount: BigInteger?, @SerialName("fncg_gld_auto_rdpt_yn") @Serializable(with = YNSerializer::class) override val loanAutoRepay: Boolean?, @SerialName("pchs_amt_smtl_amt") @Contextual override val buyTotalAmount: BigInteger?, @SerialName("evlu_amt_smtl_amt") @Contextual override val evalTotalAmount: BigInteger?, @SerialName("evlu_pfls_smtl_amt") @Contextual override val evalProfitLossTotalAmount: BigInteger?, @SerialName("tot_sltn_slng_chgs") @Contextual override val totalShortSellingAmount: BigInteger?, @SerialName("bfdy_tot_asst_evlu_amt") @Contextual override val totalEvalAssetAmountFromYesterday: BigInteger?, @SerialName("asst_icdc_amt") @Contextual override val assetChangeAmount: BigInteger?, @SerialName("asst_icdc_erng_rt") @Contextual override val assetChangeRate: BigDecimal?, @SerialName("rlzt_pfls") @Contextual override val realizedProfitLoss: BigInteger?, @SerialName("rlzt_erng_rt") @Contextual override val realizedProfitLossRate: BigDecimal?, @SerialName("rlzt_evlu_pfls") @Contextual override val realEvalProfitLoss: BigInteger?, @SerialName("rlzt_evlu_pfls_erng_rt") @Contextual override val realEvalProfitLossRate: BigDecimal?, ): BalanceAccount { override val errorDescription: String? = null override val errorCode: String? = null } data class InquireBalanceData( val afterHourFinalPrice: Boolean = true, val inquireDivision: InquireDivisionCode = InquireDivisionCode.ByStock, val includeFund: Boolean = false, val includeYesterdaySell: Boolean = false, val includeCost: Boolean = false, override var corp: CorporationRequest? = null, override var tradeContinuous: String? = "", val continuousAreaFK: String = "", val continuousAreaNK: String = "" ) : Data, TradeContinuousData override suspend fun call(data: InquireBalanceData): InquireBalanceResponse { if (data.corp == null) data.corp = client.corp fun HttpRequestBuilder.InquireBalance() { auth(client) tradeId(if(client.isDemo) "VTTC8434R" else "TTTC8494R") data.corp?.let { corporation(it) } url { parameters.run { set("CANO", client.account!![0]) set("ACNT_PRDT_CD", client.account!![1]) set("AFHR_FLPR_YN", data.afterHourFinalPrice.YN) set("OFL_YN", "") set("INQR_DVSN", data.inquireDivision.num) set("UNPR_DVSN", "01") set("FUND_STTL_ICLD_YN", data.includeFund.YN) set("FNCG_AMT_AUTO_RDPT_YN", "N") set("PRCS_DVSN", if (data.includeYesterdaySell) "00" else "01") if (!client.isDemo) set("COST_ICLD_YN", data.includeCost.YN) set("CTX_AREA_FK100", data.continuousAreaFK) set("CTX_AREA_NK100", data.continuousAreaNK) } } } val res = client.httpClient.get(url) { InquireBalance() } return res.body<InquireBalanceResponse>().apply { if (this.errorCode != null) throw RequestError(this.errorDescription) processHeader(res) if (this.tradeContinuous == "F" || this.tradeContinuous == "M") { this.next = { call(data.copy(tradeContinuous = "N", continuousAreaFK = this.continuousAreaFK!!, continuousAreaNK = this.continuousAreaNK!!)) } } } } }
0
Kotlin
1
2
ebd6cb1aeafe74bd4efb84a16daff384a88a5291
9,480
kt_kisopenapi
MIT License
app/src/main/java/com/mk/sheets/compose/samples/CalendarSample1.kt
maxkeppeler
523,345,776
false
null
/* * Copyright (C) 2022-2023. <NAME> (https://www.maxkeppeler.com) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ @file:OptIn(ExperimentalMaterial3Api::class) package com.mk.sheets.compose.samples import androidx.compose.material3.ExperimentalMaterial3Api import androidx.compose.runtime.Composable import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import com.maxkeppeker.sheets.core.models.base.SheetState import com.maxkeppeker.sheets.core.models.base.rememberSheetState import com.maxkeppeler.sheets.calendar.CalendarDialog import com.maxkeppeler.sheets.calendar.models.CalendarConfig import com.maxkeppeler.sheets.calendar.models.CalendarSelection import com.maxkeppeler.sheets.calendar.models.CalendarStyle import java.time.LocalDate @Composable internal fun CalendarSample1(closeSelection: SheetState.() -> Unit) { val selectedDates = remember { mutableStateOf<List<LocalDate>>(listOf()) } val disabledDates = listOf( LocalDate.now().minusDays(7), LocalDate.now().minusDays(12), LocalDate.now().plusDays(3), ) CalendarDialog( state = rememberSheetState(visible = true, onCloseRequest = { closeSelection() }), config = CalendarConfig( yearSelection = true, monthSelection = true, style = CalendarStyle.MONTH, disabledDates = disabledDates ), selection = CalendarSelection.Dates { newDates -> selectedDates.value = newDates }, ) }
8
null
6
816
2af41f317228e982e261522717b6ef5838cd8b58
2,046
sheets-compose-dialogs
Apache License 2.0
lib/src/test/java/tech/relaycorp/awaladroid/test/MockContextTestCase.kt
relaycorp
327,584,039
false
null
package tech.relaycorp.awaladroid.test import com.nhaarman.mockitokotlin2.mock import com.nhaarman.mockitokotlin2.whenever import org.junit.After import org.junit.Before import org.mockito.internal.util.MockUtil import tech.relaycorp.awaladroid.AwalaContext import tech.relaycorp.awaladroid.GatewayClientImpl import tech.relaycorp.awaladroid.endpoint.ChannelManager import tech.relaycorp.awaladroid.endpoint.FirstPartyEndpoint import tech.relaycorp.awaladroid.endpoint.HandleGatewayCertificateChange import tech.relaycorp.awaladroid.endpoint.PrivateThirdPartyEndpointData import tech.relaycorp.awaladroid.endpoint.PublicThirdPartyEndpointData import tech.relaycorp.awaladroid.endpoint.ThirdPartyEndpoint import tech.relaycorp.awaladroid.storage.StorageImpl import tech.relaycorp.awaladroid.storage.mockStorage import tech.relaycorp.relaynet.SessionKey import tech.relaycorp.relaynet.SessionKeyPair import tech.relaycorp.relaynet.nodes.EndpointManager import tech.relaycorp.relaynet.pki.CertificationPath import tech.relaycorp.relaynet.testing.keystores.MockCertificateStore import tech.relaycorp.relaynet.testing.keystores.MockPrivateKeyStore import tech.relaycorp.relaynet.testing.keystores.MockSessionPublicKeyStore import tech.relaycorp.relaynet.testing.pki.KeyPairSet import tech.relaycorp.relaynet.testing.pki.PDACertPath internal abstract class MockContextTestCase { protected open val gatewayClient: GatewayClientImpl = mock() protected open val storage: StorageImpl = mockStorage() protected val privateKeyStore: MockPrivateKeyStore = MockPrivateKeyStore() protected val sessionPublicKeystore: MockSessionPublicKeyStore = MockSessionPublicKeyStore() protected val certificateStore: MockCertificateStore = MockCertificateStore() protected val handleGatewayCertificateChange: HandleGatewayCertificateChange = mock() // We'd ideally use the real thing but we can't use SharedPreferences in unit tests protected val channelManager: ChannelManager = mock() @Before fun setMockContext() { setAwalaContext( AwalaContext( storage, gatewayClient, EndpointManager(privateKeyStore, sessionPublicKeystore), channelManager, privateKeyStore, sessionPublicKeystore, certificateStore, handleGatewayCertificateChange ) ) } @Before fun resetKeystores() { privateKeyStore.clear() sessionPublicKeystore.clear() } @After fun unsetContext(): Unit = unsetAwalaContext() protected suspend fun createEndpointChannel( thirdPartyEndpointType: RecipientAddressType ): EndpointChannel { val firstPartyEndpoint = createFirstPartyEndpoint() val thirdPartySessionKeyPair = SessionKeyPair.generate() val thirdPartyEndpoint = createThirdPartyEndpoint( thirdPartyEndpointType, thirdPartySessionKeyPair.sessionKey, firstPartyEndpoint, ) val firstPartySessionKeyPair = SessionKeyPair.generate() privateKeyStore.saveSessionKey( firstPartySessionKeyPair.privateKey, firstPartySessionKeyPair.sessionKey.keyId, firstPartyEndpoint.nodeId, thirdPartyEndpoint.nodeId, ) whenever(channelManager.getLinkedEndpointAddresses(firstPartyEndpoint)) .thenReturn(setOf(thirdPartyEndpoint.nodeId)) return EndpointChannel( firstPartyEndpoint, thirdPartyEndpoint, thirdPartySessionKeyPair, firstPartySessionKeyPair, ) } protected suspend fun createFirstPartyEndpoint(): FirstPartyEndpoint { val firstPartyEndpoint = FirstPartyEndpointFactory.build() val gatewayAddress = "example.org" privateKeyStore.saveIdentityKey( firstPartyEndpoint.identityPrivateKey, ) val certificate = firstPartyEndpoint.identityCertificate certificateStore.save( CertificationPath( certificate, firstPartyEndpoint.identityCertificateChain ), certificate.issuerCommonName, ) if (MockUtil.isMock(storage)) { whenever(storage.gatewayId.get(firstPartyEndpoint.nodeId)) .thenReturn(certificate.issuerCommonName) whenever(storage.internetAddress.get()) .thenReturn(gatewayAddress) } else { storage.gatewayId.set( firstPartyEndpoint.nodeId, certificate.issuerCommonName ) storage.internetAddress.set( gatewayAddress ) } return firstPartyEndpoint } private suspend fun createThirdPartyEndpoint( thirdPartyEndpointType: RecipientAddressType, sessionKey: SessionKey, firstPartyEndpoint: FirstPartyEndpoint ): ThirdPartyEndpoint { val thirdPartyEndpoint: ThirdPartyEndpoint when (thirdPartyEndpointType) { RecipientAddressType.PRIVATE -> { thirdPartyEndpoint = ThirdPartyEndpointFactory.buildPrivate() val authBundle = CertificationPath( PDACertPath.PDA, listOf(PDACertPath.PRIVATE_ENDPOINT, PDACertPath.PRIVATE_GW) ) whenever( storage.privateThirdParty.get( "${firstPartyEndpoint.nodeId}_${thirdPartyEndpoint.nodeId}" ) ).thenReturn( PrivateThirdPartyEndpointData( KeyPairSet.PDA_GRANTEE.public, authBundle ) ) } else -> { thirdPartyEndpoint = ThirdPartyEndpointFactory.buildPublic() whenever( storage.publicThirdParty.get(thirdPartyEndpoint.nodeId) ).thenReturn( PublicThirdPartyEndpointData( thirdPartyEndpoint.internetAddress, thirdPartyEndpoint.identityKey ) ) } } sessionPublicKeystore.save( sessionKey, thirdPartyEndpoint.nodeId ) return thirdPartyEndpoint } }
9
null
1
2
aee9c5f736b4c65a0e1c3fe4848d10693caa6fec
6,440
awala-endpoint-android
Apache License 2.0
superior-common-parser/src/main/kotlin/io/github/melin/superior/common/relational/SchemaId.kt
melin
140,644,913
false
{"ANTLR": 1556606, "Kotlin": 735308, "Java": 43462}
package io.github.melin.superior.common.relational import org.apache.commons.lang3.StringUtils data class SchemaId(val catalogName: String?, val schemaName: String) { companion object { @JvmStatic fun of(schemaName: String) = SchemaId(schemaName) @JvmStatic fun of(catalogName: String, schemaName: String) = SchemaId(catalogName, schemaName) } constructor(schemaName: String) : this(null, schemaName) fun getFullSchemaName(): String { if (catalogName != null) { return "${catalogName}.${schemaName}" } return schemaName } fun getLowerCatalogName(): String { return StringUtils.lowerCase(catalogName) } fun getLowerSchemaName(): String { return StringUtils.lowerCase(schemaName) } }
5
ANTLR
98
286
76a3043b8e0a161e1073f6c0be452fcfe9eca904
795
superior-sql-parser
Apache License 2.0
packages/library-base/src/commonMain/kotlin/io/realm/kotlin/internal/Mediator.kt
realm
235,075,339
false
{"Kotlin": 4564631, "C++": 126122, "SWIG": 26070, "Shell": 23822, "C": 5126, "CMake": 2858, "Ruby": 1586, "Java": 1470}
/* * Copyright 2021 Realm Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.realm.kotlin.internal import io.realm.kotlin.types.BaseRealmObject import kotlin.reflect.KClass // TODO Public due to being a transitive dependency of ConfigurationImpl public interface Mediator { // TODO OPTIMIZE Most usage of this could be done from cached RealmObjectCompanion instance. // Maybe just eliminate this method to ensure that we don't misuse it in favor of // companionOf(clazz).`io_realm_kotlin_newInstance`() public fun createInstanceOf(clazz: KClass<out BaseRealmObject>): RealmObjectInternal public fun companionOf(clazz: KClass<out BaseRealmObject>): RealmObjectCompanion }
242
Kotlin
57
942
df49eefacba8f57653e232203f44003643468463
1,220
realm-kotlin
Apache License 2.0
app/src/main/kotlin/com/tajmoti/tulip/db/entity/userdata/DbFavoriteTmdbItem.kt
Tajmoti
391,138,914
false
null
package com.tajmoti.tulip.db.entity.userdata import androidx.room.Entity import com.tajmoti.libtulip.model.info.ItemType @Entity(primaryKeys = ["type", "tmdbItemId"]) data class DbFavoriteTmdbItem( val type: ItemType, val tmdbItemId: Long )
6
Kotlin
0
1
7dd02fe23b3205967e02d0efff2b7efd191fe138
251
Tulip
MIT License
app/src/main/java/com/mayokunadeniyi/instantweather/data/model/LocationModel.kt
mayokunadeniyi
236,161,392
false
{"Kotlin": 177122, "Ruby": 955}
package com.mayokunadeniyi.instantweather.data.model /** * Created by Mayokun Adeniyi on 17/03/2020. */ data class LocationModel( val longitude: Double, val latitude: Double )
9
Kotlin
163
763
52cc36b3bd17faf121fa72e1dd3e68eb6f58795d
187
Instant-Weather
MIT License
src/main/kotlin/com/github/elexx/spaarpot/application/SpaarpotApplication.kt
elexx
142,576,576
false
null
package com.github.elexx.spaarpot.application import com.github.elexx.spaarpot.events.ShutdownEvent import tornadofx.* fun main(args: Array<String>) = launch<SpaarpotApplication>(args) class SpaarpotApplication : App(MainWindow::class, Styles::class) { override fun stop() { fire(ShutdownEvent) super.stop() } }
0
Kotlin
0
0
ff95aa633cfad98350d9878e3fe2b529d819a112
339
spaarpot
Apache License 2.0
test/dev/eakin/dao/primes/MyLinkedList.kt
GregEakin
244,196,646
false
null
/* * Copyright (c) 2020. Greg Eakin * * 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.eakin.dao.primes class MyLinkedList<T>(private val head: T, private val tail: MyList<T>) : MyList<T> { override fun head(): T { return head } override fun tail(): MyList<T> { return tail } override val isEmpty: Boolean get() = false }
0
Kotlin
0
0
0cb708fc2c6f83cd2c1619001691c404d1603659
892
NutrishSr28.Kotlin
Apache License 2.0
discord-bot/src/commonMain/kotlin/service/Environment.kt
SPYunderscore04
640,315,150
false
{"Kotlin": 7608}
package service import util.getEnvVariable import util.lazyLogger private val log by lazyLogger(Environment::class) object Environment { val discordBotToken = getEnvVariable("DISCORD_BOT_TOKEN") init { log.trace { "Environment initialized" } } }
0
Kotlin
0
0
d6fd70ce040bcfbb6d3103a4d5967579a2d9159b
270
Lili
MIT License
model/com/example/todo/TodoRemote.kt
kotlin-everywhere
74,202,701
false
null
package com.example.todo import com.github.kotlin_everywhere.rpc.Remote import com.github.kotlin_everywhere.rpc.get import com.github.kotlin_everywhere.rpc.post import com.github.kotlin_everywhere.rpc.put import com.github.kotlin_everywhere.rpc.delete import java.util.* class TodoRemote : Remote() { val add = post<AddTodo, Todo>() val edit = put<EditTodo, Todo>() val delete = delete<UUID, Unit>() val list = get<Unit, Array<Todo>>() data class AddTodo(val message: String) data class EditTodo(val id: UUID, val message: String) data class Todo(val id: UUID, val message: String) }
0
Kotlin
0
0
dbf5a714dc3b94d91a580d55ba8282d69491206e
615
kotlin-everywhere-todo
MIT License
Backpack/src/main/java/net/skyscanner/backpack/flare/BpkFlare.kt
Skyscanner
117,813,847
false
null
/** * Backpack for Android - Skyscanner's Design System * * Copyright 2018-2021 Skyscanner Ltd * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.skyscanner.backpack.flare import android.content.Context import android.graphics.Bitmap import android.graphics.Canvas import android.graphics.Paint import android.graphics.PorterDuff import android.graphics.PorterDuffXfermode import android.graphics.RectF import android.graphics.Region import android.os.Build import android.util.AttributeSet import android.view.View import android.widget.FrameLayout import androidx.appcompat.content.res.AppCompatResources import net.skyscanner.backpack.R import net.skyscanner.backpack.util.unsafeLazy import net.skyscanner.backpack.util.use /** * [BpkFlare] is designed to render a single item inside a "bubble". * Think of message apps and how they show content inside text bubbles. * * This view uses bitmap masking to mask the flare shape and corners. * When hardware acceleration is enabled this doesn't work as expected, so hardware * acceleration is disabled for this view. * * [BpkFlare] is designed to work with only one child and will throw an error if more than * one is provided. * * No background or padding should be set to this view, set it directly to its * child. */ open class BpkFlare @JvmOverloads constructor( context: Context, attrs: AttributeSet? = null, defStyleAttr: Int = 0 ) : FrameLayout(context, attrs, defStyleAttr) { enum class PointerPosition(internal val id: Int, internal val offset: Float) { START(0, 0.25f), MIDDLE(1, 0.5f), END(2, 0.75f), } enum class PointerDirection(internal val id: Int) { DOWN(0), UP(1), } enum class InsetPaddingMode(internal val id: Int) { NONE(0), BOTTOM(1), TOP(2), } private val pointerMask by unsafeLazy { val pointerDrawable = AppCompatResources.getDrawable(context, R.drawable.flare_default_pointer)!!.apply { setBounds(0, 0, intrinsicWidth, intrinsicHeight) } Bitmap.createBitmap(pointerDrawable.intrinsicWidth, pointerDrawable.intrinsicHeight, Bitmap.Config.ARGB_8888).apply { pointerDrawable.draw(Canvas(this)) } } private val radiusMask by unsafeLazy { val radiiDrawable = AppCompatResources.getDrawable(context, R.drawable.flare_default_radius)!!.apply { setBounds(0, 0, intrinsicWidth, intrinsicHeight) } Bitmap.createBitmap(radiiDrawable.intrinsicWidth, radiiDrawable.intrinsicHeight, Bitmap.Config.ARGB_8888).apply { radiiDrawable.draw(Canvas(this)) } } private val clipRect = RectF() private val paint = Paint().apply { xfermode = PorterDuffXfermode(PorterDuff.Mode.DST_OUT) isAntiAlias = true } /** * Specify if corner radius should be added or not. */ var round = false set(value) { field = value requestLayout() } /** * Specify the horizontal position of the flare. * * @see [PointerPosition] */ var pointerPosition = PointerPosition.MIDDLE set(value) { field = value requestLayout() } /** * Specify the vertical direction of the flare. * * @see [PointerDirection] */ var pointerDirection = PointerDirection.DOWN set(value) { field = value requestLayout() } /** * Specify if extra padding should be added to account * for the view clipping used to display the flare pointer. * * @see [InsetPaddingMode] */ var insetPaddingMode = InsetPaddingMode.NONE set(value) { field = value requestLayout() } init { initialize(attrs, defStyleAttr) } private fun initialize(attrs: AttributeSet?, defStyleAttr: Int) { context.theme.obtainStyledAttributes(attrs, R.styleable.BpkFlare, defStyleAttr, 0) ?.use { round = it.getBoolean(R.styleable.BpkFlare_flareRound, round) pointerPosition = it.getInt(R.styleable.BpkFlare_flarePointerPosition, pointerPosition.id) .let(::mapXmlToPointerPosition) ?: pointerPosition pointerDirection = it.getInt(R.styleable.BpkFlare_flarePointerDirection, pointerDirection.id) .let(::mapXmlToPointerDirection) ?: pointerDirection insetPaddingMode = it.getInt(R.styleable.BpkFlare_flareInsetPaddingMode, insetPaddingMode.id) .let(::mapXmlToInsetPaddingMode) ?: insetPaddingMode } background = null setWillNotDraw(false) setPadding(0, 0, 0, 0) // PorterDuffXfermode doesn't work in some devices when hardware acceleration is on setLayerType(LAYER_TYPE_SOFTWARE, null) } override fun onViewAdded(child: View) { super.onViewAdded(child) if (this.childCount > 1) { throw IllegalStateException("BpkFlare should have only one child") } when (insetPaddingMode) { InsetPaddingMode.NONE -> {} InsetPaddingMode.BOTTOM -> setPaddingVertical(child, child.paddingTop, child.paddingBottom + pointerMask.height) InsetPaddingMode.TOP -> setPaddingVertical(child, child.paddingTop + pointerMask.height, child.paddingBottom) } } override fun draw(canvas: Canvas) { val count = canvas.saveCount val width = width.toFloat() val height = height.toFloat() val pointerHalfWidth = pointerMask.width / 2 val pointerOffset = if (layoutDirection == View.LAYOUT_DIRECTION_RTL) { 1 - pointerPosition.offset } else { pointerPosition.offset } val pointerYStart = height - pointerMask.height val pointerXStart = width * pointerOffset - pointerHalfWidth val pointerXEnd = width * pointerOffset + pointerHalfWidth when (pointerDirection) { PointerDirection.DOWN -> clipPointerArea(pointerYStart, pointerXStart, height, canvas, width, pointerXEnd) PointerDirection.UP -> clipPointerArea(0f, pointerXStart, pointerMask.height.toFloat(), canvas, width, pointerXEnd) } super.draw(canvas) canvas.restoreToCount(count) drawPointerMask(canvas, pointerXStart, pointerYStart) if (round) { drawRadiusMask(canvas) } } private fun clipPointerArea( pointerYStart: Float, pointerXStart: Float, height: Float, canvas: Canvas, width: Float, pointerXEnd: Float ) { clipRect.set(0f, pointerYStart, pointerXStart, height) canvas.clipOutRectCompat(clipRect) clipRect.set(width, pointerYStart, pointerXEnd, height) canvas.clipOutRectCompat(clipRect) } private fun drawPointerMask(canvas: Canvas, pointerXStart: Float, pointerYStart: Float) { val count = canvas.saveCount val width = width.toFloat() val height = height.toFloat() when (pointerDirection) { PointerDirection.UP -> { canvas.rotate(180f, width / 2, height / 2) canvas.drawBitmap(pointerMask, pointerXStart, pointerYStart, paint) } PointerDirection.DOWN -> canvas.drawBitmap(pointerMask, pointerXStart, pointerYStart, paint) } canvas.restoreToCount(count) } private fun drawRadiusMask(canvas: Canvas) { val width = width.toFloat() val height = height.toFloat() val radiusHeight = radiusMask.height val radiusWidth = radiusMask.width val radiusHalfHeight = radiusHeight.toFloat() / 2 val radiusHalfWidth = radiusHeight.toFloat() / 2 val pointerHeight = pointerMask.height val count = canvas.saveCount // bottom left corner canvas.drawBitmap(radiusMask, 0f, height - pointerHeight - radiusHeight, paint) // top right corner canvas.rotate(180f, radiusHalfWidth, radiusHalfHeight) canvas.drawBitmap(radiusMask, -(width - radiusWidth), 0f, paint) // top left corner canvas.rotate(-90f, radiusHalfWidth, radiusHalfHeight) canvas.drawBitmap(radiusMask, 0f, 0f, paint) // bottom right corner canvas.rotate(-180f, radiusHalfWidth, radiusHalfHeight) canvas.drawBitmap(radiusMask, -(height - pointerHeight - radiusHeight), width - radiusWidth, paint) canvas.restoreToCount(count) } private fun mapXmlToPointerPosition(id: Int) = PointerPosition.values().find { it.id == id } private fun mapXmlToPointerDirection(id: Int) = PointerDirection.values().find { it.id == id } private fun mapXmlToInsetPaddingMode(id: Int) = InsetPaddingMode.values().find { it.id == id } private fun setPaddingVertical(child: View, paddingTop: Int, paddingBottom: Int) { if (child.paddingStart > 0 || child.paddingEnd > 0) { child.setPaddingRelative(child.paddingStart, paddingTop, child.paddingEnd, paddingBottom) } else { child.setPadding(child.paddingLeft, paddingTop, child.paddingRight, paddingBottom) } } } private fun Canvas.clipOutRectCompat(rect: RectF) { if (Build.VERSION.SDK_INT >= 26) { this.clipOutRect(rect) } else { @Suppress("DEPRECATION") this.clipRect(rect, Region.Op.DIFFERENCE) } }
8
null
32
94
9b5448b446c7bc46560e430595829e5f4f090e6b
9,359
backpack-android
Apache License 2.0
codegen/smithy-aws-swift-codegen/src/main/kotlin/software/amazon/smithy/aws/swift/codegen/AddProtocols.kt
awslabs
278,475,105
false
{"Swift": 264012689, "Kotlin": 353669, "Smithy": 100541, "Shell": 23167, "Dockerfile": 879}
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * SPDX-License-Identifier: Apache-2.0. */ package software.amazon.smithy.aws.swift.codegen import software.amazon.smithy.aws.swift.codegen.protocols.awsjson.AWSJSON1_0ProtocolGenerator import software.amazon.smithy.aws.swift.codegen.protocols.awsjson.AWSJSON1_1ProtocolGenerator import software.amazon.smithy.aws.swift.codegen.protocols.awsquery.AWSQueryProtocolGenerator import software.amazon.smithy.aws.swift.codegen.protocols.ec2query.EC2QueryProtocolGenerator import software.amazon.smithy.aws.swift.codegen.protocols.restjson.AWSRestJson1ProtocolGenerator import software.amazon.smithy.aws.swift.codegen.protocols.restxml.RestXMLProtocolGenerator import software.amazon.smithy.swift.codegen.integration.ProtocolGenerator import software.amazon.smithy.swift.codegen.integration.SwiftIntegration /** * Integration that registers protocol generators this package provides */ class AddProtocols : SwiftIntegration { /** * Gets the sort order of the customization from -128 to 127, with lowest * executed first. * * @return Returns the sort order, defaults to -10. */ override val order: Byte = -10 override val protocolGenerators: List<ProtocolGenerator> = listOf( AWSRestJson1ProtocolGenerator(), AWSJSON1_0ProtocolGenerator(), AWSJSON1_1ProtocolGenerator(), RestXMLProtocolGenerator(), AWSQueryProtocolGenerator(), EC2QueryProtocolGenerator() ) }
143
Swift
78
398
08334ae7385b08c14d01dfb961df8632761a9647
1,520
aws-sdk-swift
Apache License 2.0
implementation/src/main/kotlin/com/aoc/image/utility/ImageDataAssembler.kt
TomPlum
227,887,094
false
null
package com.aoc.image.utility import com.aoc.image.EncodedSpaceImage import com.aoc.image.Pixel import com.aoc.image.SpaceImageDimensions import com.aoc.image.SpaceImageLayer /** * Assembles the given data string (Format 12020102221010...) into an [EncodedSpaceImage] */ class ImageDataAssembler { fun assemble(imageDataString: String, dimensions: SpaceImageDimensions): EncodedSpaceImage { val imageData: List<Pixel> = imageDataString.chunked(1).map { Pixel.fromColourCode(it.toInt()) } return EncodedSpaceImage(imageData.chunked(dimensions.width * dimensions.height).map { SpaceImageLayer(it, dimensions) }) } }
7
null
1
2
12d47cc9c50aeb9e20bcf110f53d097d8dc3762f
663
advent-of-code-2019
Apache License 2.0
api/coroutines/v1.5.3/src/commonMain/kotlin/dev/whyoleg/ktd/api/chat/SearchPublicChats.kt
whyoleg
202,767,670
false
null
@file:Suppress( "unused" ) @file:UseExperimental( BotsOnly::class, TestingOnly::class ) package dev.whyoleg.ktd.api.chat import dev.whyoleg.ktd.* import dev.whyoleg.ktd.api.* import dev.whyoleg.ktd.api.TdApi.* /** * Searches public chats by looking for specified query in their username and title * Currently only private chats, supergroups and channels can be public * Returns a meaningful number of results * Returns nothing if the length of the searched username prefix is less than 5 * Excludes private chats with contacts and chats from the chat list from the results * * @query - Query to search for */ suspend fun TelegramClient.searchPublicChats( query: String? = null ): Chats = chat( SearchPublicChats( query ) ) /** * Searches public chats by looking for specified query in their username and title * Currently only private chats, supergroups and channels can be public * Returns a meaningful number of results * Returns nothing if the length of the searched username prefix is less than 5 * Excludes private chats with contacts and chats from the chat list from the results */ suspend fun TelegramClient.chat( f: SearchPublicChats ): Chats = exec(f) as Chats
7
Kotlin
11
45
7284eeabef0bd002dc72634351ab751b048900e9
1,225
ktd
Apache License 2.0
lib/src/main/java/me/ibrahimsn/lib/internal/ext/CoroutineExt.kt
ibrahimsn98
291,533,450
false
null
package me.ibrahimsn.lib.internal.ext import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.withContext internal suspend fun <T> default( block: suspend () -> T ) = withContext(Dispatchers.Default) { block.invoke() } internal suspend fun <T> io( block: suspend () -> T ) = withContext(Dispatchers.IO) { block.invoke() }
5
null
24
96
d152d0e784e1b0f55e02bc81a449735435e59b15
349
PhoneNumberKit
Apache License 2.0
0385.Mini Parser.kt
sarvex
842,260,390
false
{"Kotlin": 1775678, "PowerShell": 418}
/** * // This is the interface that allows for creating nested lists. * // You should not implement it, or speculate about its implementation * public interface NestedInteger { * // Constructor initializes an empty nested list. * public NestedInteger(); * * // Constructor initializes a single integer. * public NestedInteger(int value); * * // @return true if this NestedInteger holds a single integer, rather than a nested list. * public boolean isInteger(); * * // @return the single integer that this NestedInteger holds, if it holds a single integer * // Return null if this NestedInteger holds a nested list * public Integer getInteger(); * * // Set this NestedInteger to hold a single integer. * public void setInteger(int value); * * // Set this NestedInteger to hold a nested list and adds a nested integer to it. * public void add(NestedInteger ni); * * // @return the nested list that this NestedInteger holds, if it holds a nested list * // Return empty list if this NestedInteger holds a single integer * public List<NestedInteger> getList(); * } </NestedInteger> */ internal class Solution { fun deserialize(s: String): NestedInteger { if ("" == s || "[]" == s) { return NestedInteger() } if (s[0] != '[') { return NestedInteger(s.toInt()) } val ans: NestedInteger = NestedInteger() var depth = 0 var i = 1 var j = 1 while (i < s.length) { if (depth == 0 && (s[i] == ',' || i == s.length - 1)) { ans.add(deserialize(s.substring(j, i))) j = i + 1 } else if (s[i] == '[') { ++depth } else if (s[i] == ']') { --depth } ++i } return ans } }
0
Kotlin
0
0
17a80985d970c8316fb694e4952692e598d700af
1,699
kotlin-leetcode
MIT License
platform/android/goldengate/GoldenGateConnectionManager/src/test/java/com/fitbit/goldengate/stackservice/CoapStackServiceProviderTest.kt
vedangshah
263,597,650
true
{"C": 2261205, "C++": 760746, "Kotlin": 743036, "Swift": 646307, "Objective-C": 133325, "CMake": 119304, "Python": 114534, "JavaScript": 20929, "HTML": 13841, "Shell": 2660, "Dockerfile": 1379, "Mercury": 817, "Ruby": 165}
// Copyright 2017-2020 Fitbit, Inc // SPDX-License-Identifier: Apache-2.0 package com.fitbit.goldengate.stackservice import com.fitbit.goldengate.bindings.coap.CoapEndpoint import com.fitbit.goldengate.bindings.node.BluetoothAddressNodeKey import com.fitbit.goldengate.node.stack.StackNode import com.fitbit.goldengate.node.stack.StackNodeBuilder import com.nhaarman.mockitokotlin2.doReturn import com.nhaarman.mockitokotlin2.mock import org.junit.Test class CoapStackServiceProviderTest { @Test operator fun invoke() { val nodeKey = mock<BluetoothAddressNodeKey>() val coapEndpoint = mock<CoapEndpoint>() val stackNode = mock<StackNode<CoapEndpoint>> { on { stackService } doReturn coapEndpoint } val stackNodeBuilder = mock<StackNodeBuilder<CoapEndpoint>> { on { build(nodeKey) } doReturn stackNode } //This should not error out CoapStackServiceProvider.invoke(stackNodeBuilder = stackNodeBuilder).get(nodeKey) } }
0
null
0
0
1b50f4eede04927980cd4dbb4c61a625e11f4729
1,021
golden-gate
Apache License 2.0