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 |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|
account-service/src/main/kotlin/com/onegravity/accountservice/persistence/model/Language.kt | 1gravity | 361,878,383 | false | null | package com.onegravity.accountservice.persistence.model
enum class Language(val languageLong: String) {
en("English"),
de("German")
}
| 0 | Kotlin | 4 | 34 | 0d31a4bee1b86a756371a42a2cf64e32213277c0 | 143 | Ktor-Template | Apache License 2.0 |
domain/src/main/java/com/bcassar/domain/utils/Extension.kt | baptistecassar | 557,934,807 | false | null | package com.bcassar.domain.utils
import java.text.SimpleDateFormat
import java.util.*
/**
* Created by bcassar on 27/10/2022
*/
fun String.toDate(): Date {
val simpleDateFormat = SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'")
return simpleDateFormat.parse(this) ?: Date()
} | 0 | Kotlin | 0 | 0 | 396491f034852ba294819da74d2461fece148f6a | 284 | android-nba-fantasy | MIT License |
app/src/main/java/ir/amirsobhan/sticknote/ui/views/TextStyleBar.kt | a1383n | 342,316,747 | false | null | package ir.amirsobhan.sticknote.ui.views
import android.content.Context
import android.graphics.drawable.ColorDrawable
import android.util.AttributeSet
import android.view.LayoutInflater
import android.view.View
import android.widget.LinearLayout
import com.google.android.material.dialog.MaterialAlertDialogBuilder
import ir.amirsobhan.sticknote.R
import ir.amirsobhan.sticknote.databinding.ViewTextstyleBarBinding
import jp.wasabeef.richeditor.RichEditor
class TextStyleBar(context: Context, attrs: AttributeSet?) : LinearLayout(context, attrs) , View.OnClickListener{
private var binding = ViewTextstyleBarBinding.inflate(LayoutInflater.from(context),this,true)
private lateinit var editor : RichEditor
private val defaultColor = context.getColor(R.color.secondary_text)
private val selectedColor = context.getColor(R.color.primary)
fun setEditor(editor: RichEditor){
this.editor = editor
initStyleBar()
}
private fun initStyleBar(){
binding.textStyleUndo.setOnClickListener(this)
binding.textStyleRedo.setOnClickListener(this)
binding.textStyleBold.setOnClickListener(this)
binding.textStyleItalic.setOnClickListener(this)
binding.textStyleUnderline.setOnClickListener(this)
binding.textStyleOl.setOnClickListener(this)
binding.textStyleUl.setOnClickListener(this)
binding.textStyleHeader.setOnClickListener(this)
binding.textStyleJusLeft.setOnClickListener(this)
binding.textStyleJusCenter.setOnClickListener(this)
binding.textStyleHusRight.setOnClickListener(this)
}
override fun onClick(v: View?) {
when(v?.id){
R.id.textStyle_undo -> editor.undo()
R.id.textStyle_redo -> editor.redo()
R.id.textStyle_bold -> editor.setBold().also { changeButtonColor(true,v) }
R.id.textStyle_italic -> editor.setItalic().also { changeButtonColor(true,v) }
R.id.textStyle_underline -> editor.setUnderline().also { changeButtonColor(true,v) }
R.id.textStyle_ol -> editor.setNumbers().also { changeButtonColor(true,v) }
R.id.textStyle_ul -> editor.setBullets().also { changeButtonColor(true,v) }
R.id.textStyle_header -> {
var index = 0
MaterialAlertDialogBuilder(context,R.style.AlertDialogTheme)
.setSingleChoiceItems(R.array.heading_list,0){_,i -> index = i + 1 }
.setPositiveButton(R.string.ok){_, _ -> editor.setHeading(index)}
.show()
}
R.id.textStyle_jus_left -> editor.setAlignLeft().also { changeButtonColor(false,v,binding.textStyleJusCenter,binding.textStyleHusRight) }
R.id.textStyle_jus_center -> editor.setAlignCenter().also { changeButtonColor(false,v,binding.textStyleHusRight,binding.textStyleJusLeft) }
R.id.textStyle_hus_right -> editor.setAlignRight().also { changeButtonColor(false,v,binding.textStyleJusLeft,binding.textStyleJusCenter) }
}
}
private fun changeButtonColor(bool: Boolean,vararg views : View){
views.forEach {
if (getViewColor(it) == defaultColor && bool){
it.setBackgroundColor(selectedColor)
}else{
it.setBackgroundColor(defaultColor)
}
}
if (!bool){
views[0].setBackgroundColor(selectedColor)
}
}
private fun getViewColor(v : View?) = (v?.background as ColorDrawable).color
} | 11 | Kotlin | 0 | 1 | f34e4f45e63cd5965fbd883502d15bb0e0e99daf | 3,531 | sticknote | MIT License |
technocracy.foundation/src/main/kotlin/net/cydhra/technocracy/foundation/content/capabilities/AbstractMutableCapabilityHandler.kt | notphinix | 229,493,759 | true | {"Kotlin": 1063752, "GLSL": 8977} | package net.cydhra.technocracy.foundation.content.capabilities
import net.cydhra.technocracy.foundation.model.tileentities.api.components.AbstractTileEntityComponent
/**
* Superclass to capability handlers that can mark a [parent][AbstractTileEntityComponent] dirty upon mutation. To
* mark a parent dirty, call [markDirty] with a flag whether the client needs to update rendering.
*/
abstract class AbstractMutableCapabilityHandler {
lateinit var componentParent: AbstractTileEntityComponent
open fun markDirty(needsClientRerender: Boolean = false) {
componentParent.markDirty(needsClientRerender)
}
} | 0 | Kotlin | 0 | 0 | 71a044f54f813b0213b6ae1f0394f49324ac9c1c | 628 | Technocracy | MIT License |
data/src/test/java/com/me/data/carlist/datasource/remote/CarRemoteDataSourceImplTest.kt | MohamedHatemAbdu | 384,754,712 | false | null | package com.me.data.carlist.datasource.remote
import com.me.data.carlist.carData
import com.me.data.carlist.datasource.remote.api.ICarApi
import io.reactivex.rxjava3.core.Single
import org.junit.Before
import org.junit.Test
import org.mockito.Mockito.*
class CarRemoteDataSourceImplTest {
private lateinit var dataSource: CarRemoteDataSourceImpl
private val mockApi: ICarApi = mock(ICarApi::class.java)
private val remoteItem = carData.copy(modelName = "remote")
private val throwable = Throwable()
@Before
fun setUp() {
dataSource = CarRemoteDataSourceImpl(mockApi)
}
@Test
fun `get car list remote success`() {
// given
`when`(mockApi.getCarsList()).thenReturn(
Single.just(
listOf(remoteItem)
)
)
// when
val test = dataSource.getCarsList().test()
// then
verify(mockApi).getCarsList()
assert(test.values()[0][0].modelName == remoteItem.modelName)
}
@Test
fun `get car list remote fail`() {
// given
`when`(mockApi.getCarsList()).thenReturn(Single.error(throwable))
// when
val test = dataSource.getCarsList().test()
// then
verify(mockApi).getCarsList()
test.assertError(throwable)
}
} | 0 | Kotlin | 0 | 0 | 8f9b1f5e4c8ce18f65a1cca96fd7e96023312369 | 1,328 | cars-list | Apache License 2.0 |
app/src/main/java/com/github/simonpham/devtiles/service/tiles/CaffeineService.kt | simonpham | 135,440,300 | false | null | package com.github.simonpham.verification.service.tiles
import android.annotation.SuppressLint
import android.os.SystemClock
import android.service.quicksettings.Tile
import com.github.simonpham.verification.R
import com.github.simonpham.verification.SingletonInstances
import com.github.simonpham.verification.service.BaseTileService
/**
* Created by Simon Pham on 6/2/18.
* Email: [email protected]
*/
class CaffeineService : BaseTileService() {
private val wakeLock = SingletonInstances.getWakeLock()
private val helper = SingletonInstances.getCaffeineTileHelper()
private var mLastClickTime: Long = -1
private var mDuration: Int = 0
private val DURATIONS = intArrayOf(
5 * 60, // 5 min
10 * 60, // 10 min
30 * 60, // 30 min
-1 // infinity
)
override fun onTileRemoved() {
super.onTileRemoved()
helper.handleDestroy()
}
override fun onCreate() {
super.onCreate()
helper.service = this
}
override fun refresh() {
if (wakeLock.isHeld) {
qsTile.label = helper.formatValueWithRemainingTime()
qsTile.state = Tile.STATE_ACTIVE
} else {
qsTile.label = getString(R.string.tile_caffeine)
qsTile.state = Tile.STATE_INACTIVE
}
qsTile.updateTile()
}
@SuppressLint("WakelockTimeout")
override fun onClick() {
if (wakeLock.isHeld && (mLastClickTime.toInt() != -1) &&
(SystemClock.elapsedRealtime() - mLastClickTime < 5000)) {
// cycle duration
mDuration++
if (mDuration >= DURATIONS.size) {
// all durations cycled, turn if off
mDuration = -1
helper.stop()
if (wakeLock.isHeld) {
wakeLock.release()
}
} else {
// change duration
helper.createAndStart(DURATIONS[mDuration])
if (!wakeLock.isHeld) {
wakeLock.acquire()
}
}
} else {
// toggle
if (wakeLock.isHeld) {
wakeLock.release()
helper.stop()
} else {
wakeLock.acquire()
mDuration = 0
helper.createAndStart(DURATIONS[mDuration])
}
}
mLastClickTime = SystemClock.elapsedRealtime()
refresh()
}
} | 5 | null | 2 | 5 | eac2b552df53fd67ca59a8cbf8e9c2d6cc3f171e | 2,501 | Tiles-For-Developers | Apache License 2.0 |
geary-papermc-mythicmobs/src/main/kotlin/com/mineinabyss/geary/papermc/mythicmobs/items/MythicMobDropListener.kt | MineInAbyss | 592,086,123 | false | {"Kotlin": 258814} | package com.mineinabyss.geary.papermc.mythicmobs.items
import com.mineinabyss.geary.papermc.features.items.food.ReplaceBurnedDrop
import com.mineinabyss.geary.papermc.tracking.items.gearyItems
import com.mineinabyss.geary.prefabs.PrefabKey
import io.lumine.mythic.api.adapters.AbstractItemStack
import io.lumine.mythic.api.config.MythicLineConfig
import io.lumine.mythic.api.drops.DropMetadata
import io.lumine.mythic.bukkit.adapters.item.ItemComponentBukkitItemStack
import io.lumine.mythic.bukkit.events.MythicDropLoadEvent
import io.lumine.mythic.bukkit.utils.numbers.RandomDouble
import io.lumine.mythic.core.drops.droppables.VanillaItemDrop
import org.bukkit.event.EventHandler
import org.bukkit.event.Listener
import kotlin.jvm.optionals.getOrNull
class MythicMobDropListener : Listener {
@EventHandler
fun MythicDropLoadEvent.onMythicDropLoad() {
if (dropName.lowercase() != "geary") return
val lines = container.line.split(" ")
val prefabKey = PrefabKey.of(lines[1])
val amount = lines.getOrNull(2)?.takeIf { "-" in it } ?: "1-1"
val itemStack = gearyItems.createItem(prefabKey) ?: return
register(
GearyDrop(
prefabKey,
container.line,
config,
ItemComponentBukkitItemStack(itemStack),
RandomDouble(amount)
)
)
}
}
class GearyDrop(
val prefab: PrefabKey,
line: String, config: MythicLineConfig, item: AbstractItemStack, amount: RandomDouble,
) : VanillaItemDrop(line, config, item, amount) {
// val item = gearyItems.createItem(prefab)
val cookedItem = prefab.toEntityOrNull()?.get<ReplaceBurnedDrop>()?.replaceWith?.toItemStack()
val cookedDrop = cookedItem?.let { VanillaItemDrop(line, config, ItemComponentBukkitItemStack(it), amount) }
override fun getDrop(metadata: DropMetadata?, amount: Double): AbstractItemStack {
val isOnFire = (metadata?.dropper?.getOrNull()?.entity?.bukkitEntity?.fireTicks ?: 0) > 0
return if (isOnFire && cookedDrop != null) cookedDrop.getDrop(metadata, amount)
else super.getDrop(metadata, amount)
}
}
| 1 | Kotlin | 0 | 5 | e2fffea48d58db4ea9aa1a58ef46171b29a8a7eb | 2,174 | geary-papermc | MIT License |
app/src/main/java/com/cagataymuhammet/contactlist/data/model/ContactModel.kt | cagataymuhammet | 467,321,973 | false | {"Kotlin": 70478} | package com.cagataymuhammet.contactlist.data.model
import android.os.Parcel
import android.os.Parcelable
import com.google.gson.annotations.SerializedName
data class Contact(
@SerializedName("company_name")
var companyName: String?,
@SerializedName("createdAt")
var createdAt: String?,
@SerializedName("department")
var department: String?,
@SerializedName("email")
var email: String?,
@SerializedName("id")
var id: String?,
@SerializedName("name")
var name: String?,
@SerializedName("number")
var number: Int?,
@SerializedName("surname")
var surname: String?
) : Parcelable {
constructor(parcel: Parcel) : this(
parcel.readString(),
parcel.readString(),
parcel.readString(),
parcel.readString(),
parcel.readString(),
parcel.readString(),
parcel.readValue(Int::class.java.classLoader) as? Int,
parcel.readString()
) {
}
override fun writeToParcel(parcel: Parcel, flags: Int) {
parcel.writeString(companyName)
parcel.writeString(createdAt)
parcel.writeString(department)
parcel.writeString(email)
parcel.writeString(id)
parcel.writeString(name)
parcel.writeValue(number)
parcel.writeString(surname)
}
override fun describeContents(): Int {
return 0
}
companion object CREATOR : Parcelable.Creator<Contact> {
override fun createFromParcel(parcel: Parcel): Contact {
return Contact(parcel)
}
override fun newArray(size: Int): Array<Contact?> {
return arrayOfNulls(size)
}
}
} | 0 | Kotlin | 0 | 3 | e4b212f9f37391c838358412ca466251e954c47a | 1,671 | Contacts | Apache License 2.0 |
app/src/main/java/com/oajstudios/pocketshop/activity/OrderActivity.kt | AYOMITIDE-OAJ | 617,064,177 | false | null | package com.oajstudios.pocketshop.activity
import android.annotation.SuppressLint
import android.app.Activity
import android.content.Intent
import android.os.Build
import android.os.Bundle
import androidx.annotation.RequiresApi
import com.oajstudios.pocketshop.AppBaseActivity
import com.oajstudios.pocketshop.R
import com.oajstudios.pocketshop.adapter.BaseAdapter
import com.oajstudios.pocketshop.models.Order
import com.oajstudios.pocketshop.utils.Constants
import com.oajstudios.pocketshop.utils.Constants.KeyIntent.DATA
import com.oajstudios.pocketshop.utils.Constants.SharedPref.KEY_ORDER_COUNT
import com.oajstudios.pocketshop.utils.extensions.*
import kotlinx.android.synthetic.main.activity_order.*
import kotlinx.android.synthetic.main.activity_order.rlMain
import kotlinx.android.synthetic.main.item_orderlist.view.*
import kotlinx.android.synthetic.main.item_orderlist.view.ivProduct
import kotlinx.android.synthetic.main.item_orderlist.view.tvProductName
import kotlinx.android.synthetic.main.layout_nodata.*
import kotlinx.android.synthetic.main.toolbar.*
import java.text.ParseException
class OrderActivity : AppBaseActivity() {
@SuppressLint("SetTextI18n", "SimpleDateFormat")
private val mOrderAdapter =
BaseAdapter<Order>(R.layout.item_orderlist, onBind = { view, model, _ ->
if (model.line_items.isNotEmpty()) {
if (model.line_items[0].product_images[0].src.isNotEmpty()) {
view.ivProduct.loadImageFromUrl(model.line_items[0].product_images[0].src)
}
if (model.line_items.size > 1) {
view.tvProductName.text =
model.line_items[0].name + " + " + (model.line_items.size - 1) + " " + getString(
R.string.lbl_more_item
)
} else {
view.tvProductName.text = model.line_items[0].name
}
} else {
view.tvProductName.text = getString(R.string.lbl_order_title) + model.id
}
try {
if (model.date_paid != null) {
if (model.transaction_id.isNullOrBlank()) {
view.tvInfo.text =
getString(R.string.lbl_transaction_via) + " " + model.payment_method
} else {
view.tvInfo.text =
getString(R.string.lbl_transaction_via) + " " + model.payment_method
}
} else {
view.tvInfo.text =
getString(R.string.lbl_transaction_via) + " " + model.payment_method
}
} catch (e: ParseException) {
e.printStackTrace()
}
view.tvStatus.text = model.status
view.rlMainOrder.onClick {
launchActivity<OrderDescriptionActivity>(Constants.RequestCode.ORDER_CANCEL) {
putExtra(DATA, model)
}
}
view.tvProductName.changeTextPrimaryColor()
view.tvInfo.changeTextSecondaryColor()
view.tvStatus.changeTextPrimaryColor()
view.tvStatus.changeTextPrimaryColor()
})
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
super.onActivityResult(requestCode, resultCode, data)
if (resultCode == Activity.RESULT_OK) {
if (requestCode == Constants.RequestCode.ORDER_CANCEL) {
getOrderList()
}
}
}
@RequiresApi(Build.VERSION_CODES.M)
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_order)
title = getString(R.string.lbl_my_orders)
setToolbar(toolbar)
mAppBarColor()
rlMain.changeBackgroundColor()
disableHardwareRendering(rvOrder)
rvOrder.adapter = mOrderAdapter
getOrderList()
}
private fun getOrderList() {
getOrder(onApiSuccess = {
if (it.size == 0) {
rlNoData.show()
} else {
rlNoData.hide()
mOrderAdapter.clearItems()
mOrderAdapter.addItems(it)
getSharedPrefInstance().setValue(KEY_ORDER_COUNT, it.size)
sendOrderCountChangeBroadcast()
}
})
}
}
| 1 | Kotlin | 0 | 10 | 48cf66963987da31392350a9afec1125b9cfa4fa | 4,470 | pocketshop | Apache License 2.0 |
src/main/kotlin/org/teamvoided/dusk_autumn/data/gen/models/StoneModels.kt | TeamVoided | 737,359,498 | false | {"Kotlin": 1129694, "Java": 28224} | package org.teamvoided.dusk_autumn.data.gen.models
import net.minecraft.block.Blocks
import net.minecraft.data.client.model.BlockStateModelGenerator
import net.minecraft.data.client.model.TexturedModel
import org.teamvoided.dusk_autumn.DusksAndDungeons
import org.teamvoided.dusk_autumn.init.DnDBlocks
import org.teamvoided.dusk_autumn.init.blocks.DnDStoneBlocks
import org.teamvoided.dusk_autumn.util.*
object StoneModels {
fun stoneModels(gen: BlockStateModelGenerator) {
gen.registerGravestones(
DnDStoneBlocks.GRAVESTONE,
DnDStoneBlocks.SMALL_GRAVESTONE,
DnDStoneBlocks.HAUNTED_GRAVESTONE,
DnDStoneBlocks.SMALL_HAUNTED_GRAVESTONE
)
gen.registerGravestones(
DnDStoneBlocks.DEEPSLATE_GRAVESTONE,
DnDStoneBlocks.SMALL_DEEPSLATE_GRAVESTONE,
DnDStoneBlocks.HAUNTED_DEEPSLATE_GRAVESTONE,
DnDStoneBlocks.SMALL_HAUNTED_DEEPSLATE_GRAVESTONE
)
gen.registerGravestones(
DnDStoneBlocks.TUFF_GRAVESTONE,
DnDStoneBlocks.SMALL_TUFF_GRAVESTONE,
DnDStoneBlocks.HAUNTED_TUFF_GRAVESTONE,
DnDStoneBlocks.SMALL_HAUNTED_TUFF_GRAVESTONE
)
gen.registerGravestones(
DnDStoneBlocks.BLACKSTONE_GRAVESTONE,
DnDStoneBlocks.SMALL_BLACKSTONE_GRAVESTONE,
DnDStoneBlocks.HAUNTED_BLACKSTONE_GRAVESTONE,
DnDStoneBlocks.SMALL_HAUNTED_BLACKSTONE_GRAVESTONE
)
gen.registerHeadstone(DnDStoneBlocks.HEADSTONE)
gen.registerBunnyGrave(DnDStoneBlocks.BUNNY_GRAVE, Blocks.SMOOTH_STONE, Blocks.STONE)
gen.registerAxisRotated(
DnDStoneBlocks.STONE_PILLAR,
TexturedModel.END_FOR_TOP_CUBE_COLUMN,
TexturedModel.END_FOR_TOP_CUBE_COLUMN_HORIZONTAL
)
gen.registerAxisRotated(
DnDStoneBlocks.DEEPSLATE_PILLAR,
TexturedModel.END_FOR_TOP_CUBE_COLUMN,
TexturedModel.END_FOR_TOP_CUBE_COLUMN_HORIZONTAL
)
val mossyPolish = DusksAndDungeons.id("block/overgrown/polished_overlay")
val mossyCobble = DusksAndDungeons.id("block/overgrown/cobblestone_overlay")
val mossyBrick = DusksAndDungeons.id("block/overgrown/bricks_overlay")
gen.registerTintedOverlay(mossyPolish)
gen.registerTintedOverlay(mossyCobble)
gen.registerTintedOverlay(mossyBrick)
gen.cubeAllWithTintedOverlay(
DnDStoneBlocks.OVERGROWN_POLISHED_STONE,
DnDStoneBlocks.MOSSY_POLISHED_STONE,
mossyPolish
)
gen.stairsWithTintedOverlay(
DnDStoneBlocks.OVERGROWN_POLISHED_STONE_STAIRS,
DnDStoneBlocks.MOSSY_POLISHED_STONE,
mossyPolish
)
gen.slabWithTintedOverlay(
DnDStoneBlocks.OVERGROWN_POLISHED_STONE_SLAB,
DnDStoneBlocks.MOSSY_POLISHED_STONE,
mossyPolish
)
gen.wallWithTintedOverlay(
DnDStoneBlocks.OVERGROWN_POLISHED_STONE_WALL,
DnDStoneBlocks.MOSSY_POLISHED_STONE,
mossyPolish
)
gen.cubeAllWithTintedOverlay(DnDStoneBlocks.OVERGROWN_COBBLESTONE, Blocks.MOSSY_COBBLESTONE, mossyCobble)
gen.stairsWithTintedOverlay(DnDStoneBlocks.OVERGROWN_COBBLESTONE_STAIRS, Blocks.MOSSY_COBBLESTONE, mossyCobble)
gen.slabWithTintedOverlay(DnDStoneBlocks.OVERGROWN_COBBLESTONE_SLAB, Blocks.MOSSY_COBBLESTONE, mossyCobble)
gen.wallWithTintedOverlay(DnDStoneBlocks.OVERGROWN_COBBLESTONE_WALL, Blocks.MOSSY_COBBLESTONE, mossyCobble)
gen.cubeAllWithTintedOverlay(DnDStoneBlocks.OVERGROWN_STONE_BRICKS, Blocks.MOSSY_STONE_BRICKS, mossyBrick)
gen.stairsWithTintedOverlay(DnDStoneBlocks.OVERGROWN_STONE_BRICK_STAIRS, Blocks.MOSSY_STONE_BRICKS, mossyBrick)
gen.slabWithTintedOverlay(DnDStoneBlocks.OVERGROWN_STONE_BRICK_SLAB, Blocks.MOSSY_STONE_BRICKS, mossyBrick)
gen.wallWithTintedOverlay(DnDStoneBlocks.OVERGROWN_STONE_BRICK_WALL, Blocks.MOSSY_STONE_BRICKS, mossyBrick)
}
} | 0 | Kotlin | 0 | 0 | 7df0896ea35a8f1c3a2676821629ff16de72d95e | 4,070 | DusksAndDungeons | MIT License |
samples/shared/src/commonMain/kotlin/root/MainScreen.kt | tidal-music | 665,921,859 | false | {"Kotlin": 23112, "Shell": 4257} | package root
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.ExperimentalLayoutApi
import androidx.compose.foundation.layout.FlowColumn
import androidx.compose.foundation.layout.FlowRow
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.padding
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Scaffold
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.collectAsState
import androidx.compose.ui.Modifier
@OptIn(ExperimentalLayoutApi::class)
@Composable
fun MainScreen(mainViewModel: MainViewModel) {
val state = mainViewModel.uiState.collectAsState().value
val textStyle = MaterialTheme.typography.bodyLarge.copy(fontFeatureSettings = "tnum")
MaterialTheme {
Scaffold { paddingValues ->
FlowRow(
verticalArrangement = Arrangement.SpaceAround,
horizontalArrangement = Arrangement.Center,
modifier = Modifier.padding(paddingValues).fillMaxSize(),
) {
FlowColumn(
verticalArrangement = Arrangement.SpaceAround,
horizontalArrangement = Arrangement.Start,
) {
Text("Local: ", style = textStyle)
Text("Synchronized: ", style = textStyle)
}
FlowColumn(
verticalArrangement = Arrangement.SpaceAround,
horizontalArrangement = Arrangement.Start,
) {
Text(state.localEpoch.toIsoString(), style = textStyle)
Text(state.synchronizedEpoch?.toIsoString() ?: "None", style = textStyle)
}
}
}
}
}
| 0 | Kotlin | 0 | 3 | 57c939f20ef327cc383bdb7091c640f7a53c1772 | 1,658 | network-time | MIT License |
app/src/main/java/net/skyscanner/backpack/demo/stories/MapStory.kt | Skyscanner | 117,813,847 | false | null | /**
* Backpack for Android - Skyscanner's Design System
*
* Copyright 2018 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.demo.stories
import android.content.Context
import android.content.Intent
import android.os.Bundle
import android.view.MenuItem
import androidx.appcompat.app.AppCompatActivity
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.runtime.Composable
import androidx.compose.runtime.remember
import androidx.compose.ui.Modifier
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.res.stringResource
import com.google.android.gms.maps.SupportMapFragment
import com.google.android.gms.maps.model.LatLng
import net.skyscanner.backpack.demo.R
import net.skyscanner.backpack.demo.components.MapMarkersComponent
import net.skyscanner.backpack.demo.data.SharedPreferences
import net.skyscanner.backpack.demo.meta.StoryKind
import net.skyscanner.backpack.demo.meta.ViewStory
import net.skyscanner.backpack.demo.ui.ComponentItem
import net.skyscanner.backpack.map.addBpkMarker
import net.skyscanner.backpack.map.getBpkMapAsync
@Composable
@MapMarkersComponent
@ViewStory(kind = StoryKind.DemoOnly)
fun MapStory(modifier: Modifier = Modifier) {
val context = LocalContext.current
val values = remember { MapActivity.Type.values().toList() }
LazyColumn(modifier.fillMaxSize()) {
items(values) {
ComponentItem(
title = when (it) {
MapActivity.Type.PointersOnly -> stringResource(R.string.maps_markers_pointers_only)
MapActivity.Type.Badges -> stringResource(R.string.maps_markers_badges)
MapActivity.Type.BadgesWithIcons -> stringResource(R.string.maps_markers_badges_with_icons)
},
onClick = { context.startActivity(MapActivity.of(context, it)) },
)
}
}
}
class MapActivity : AppCompatActivity() {
enum class Type {
PointersOnly,
Badges,
BadgesWithIcons,
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setTheme(SharedPreferences.getTheme(this))
setContentView(R.layout.activity_map)
setSupportActionBar(findViewById(R.id.detail_toolbar))
supportActionBar?.setDisplayHomeAsUpEnabled(true)
val type = intent.getSerializableExtra(EXTRA_TYPE) as Type
val context = this
if (savedInstanceState == null) {
supportFragmentManager
.findFragmentById(R.id.map_fragment)
.let { it as SupportMapFragment }
.getBpkMapAsync {
it.addBpkMarker(
context = context,
position = LatLng(45.0, 0.0),
title = "Badge 1",
icon = if (type == Type.BadgesWithIcons) R.drawable.bpk_city else 0,
pointerOnly = type == Type.PointersOnly,
)
it.addBpkMarker(
context = context,
position = LatLng(0.0, 0.0),
title = "Badge 2",
icon = if (type == Type.BadgesWithIcons) R.drawable.bpk_city else 0,
pointerOnly = type == Type.PointersOnly,
)
it.addBpkMarker(
context = context,
position = LatLng(-45.0, 0.0),
title = "Badge 3",
icon = if (type == Type.BadgesWithIcons) R.drawable.bpk_city else 0,
pointerOnly = type == Type.PointersOnly,
)
}
}
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
when (item.itemId) {
android.R.id.home -> this.onBackPressed()
}
return super.onOptionsItemSelected(item)
}
companion object {
private const val EXTRA_TYPE = "type"
fun of(context: Context, type: Type): Intent =
Intent(context, MapActivity::class.java)
.putExtra(EXTRA_TYPE, type)
}
}
| 8 | Kotlin | 31 | 94 | 9b5448b446c7bc46560e430595829e5f4f090e6b | 4,857 | backpack-android | Apache License 2.0 |
coco/src/main/java/com/qw/photo/work/BaseWorker.kt | longshihan1 | 239,774,600 | true | {"Kotlin": 65459} | package com.qw.photo.work
import com.qw.photo.agent.IAcceptActivityResultHandler
import com.qw.photo.pojo.BaseParams
import com.qw.photo.pojo.BaseResult
/**
* Created by rocket on 2019/6/18.
*/
abstract class BaseWorker<Params : BaseParams<Result>, Result : BaseResult>(val mHandler: IAcceptActivityResultHandler) :
IWorker<Params, Result> {
lateinit var mParams: Params
override fun setParams(params: Params) {
this.mParams = params
}
} | 0 | Kotlin | 0 | 0 | 882c46f9864d2c48bf45ec41f9d8cdc9690508f7 | 467 | CoCo | Apache License 2.0 |
aws-runtime/aws-config/common/src/aws/sdk/kotlin/runtime/config/profile/AwsConfigParser.kt | awslabs | 121,333,316 | false | null | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
* SPDX-License-Identifier: Apache-2.0
*/
package aws.sdk.kotlin.runtime.config.profile
import aws.sdk.kotlin.runtime.ConfigurationException
import aws.sdk.kotlin.runtime.InternalSdkApi
import aws.smithy.kotlin.runtime.tracing.*
/**
* Maps a set of loaded profiles (keyed by name) to their respective [AwsProfile]s.
*/
@InternalSdkApi
public typealias AwsProfiles = Map<String, AwsProfile>
/**
* Profiles are represented as a map of maps while parsing. Each top-level key is a profile. Its associated
* entries are the property key-value pairs for that profile.
*/
internal typealias RawProfileMap = Map<String, Map<String, AwsConfigValue>>
internal fun RawProfileMap.toProfileMap(): AwsProfiles = mapValues { (k, v) -> AwsProfile(k, v) }
/**
* Base exception for AWS config file parser errors.
*/
public class AwsConfigParseException(message: String, lineNumber: Int) : ConfigurationException(contextMessage(message, lineNumber))
/**
* Parse an AWS configuration file
*
* @param type The type of file to parse
* @param input The payload to parse
*/
internal fun parse(traceSpan: TraceSpan, type: FileType, input: String?): RawProfileMap {
// Inaccessible File: If a file is not found or cannot be opened in the configured location, the implementation must
// treat it as an empty file, and must not attempt to fall back to any other location.
if (input.isNullOrBlank()) return emptyMap()
val tokens = tokenize(type, input)
val profiles = tokens.toProfileMap(traceSpan)
return mergeProfiles(profiles)
}
/**
* Convert an input file's contents into a list of tokens.
*
* The final order of the list has logical relevance w.r.t. the final output, a consumer should not alter or remove
* values from it when attempting to build a set of profiles.
*/
internal fun tokenize(type: FileType, input: String): List<Pair<FileLine, Token>> = buildList {
val lines = input
.lines()
.mapIndexed { index, line -> FileLine(index + 1, line) }
.filter { it.content.isNotBlank() && !it.isComment() }
var currentProfile: Token.Profile? = null
var lastProperty: Token.Property? = null
for (line in lines) {
val token = type.tokenOf(line, currentProfile, lastProperty)
if (token is Token.Profile) {
currentProfile = token
lastProperty = null
} else if (token is Token.Property) {
lastProperty = token
}
add(line to token)
}
}
/**
* Convert the contents of a token list into a profile mapping.
*/
internal fun List<Pair<FileLine, Token>>.toProfileMap(traceSpan: TraceSpan): Map<Token.Profile, MutableMap<String, AwsConfigValue>> = buildMap {
var currentProfile: Token.Profile? = null
var currentProperty: Token.Property? = null
var currentParentMap: MutableMap<String, String>? = null
for ((line, token) in this@toProfileMap) {
when (token) {
is Token.Profile -> {
currentProfile = token
currentProperty = null
if (containsKey(token)) continue
if (!token.isValid) {
traceSpan.warnParse(line) { "Ignoring invalid profile '${token.name}'" }
continue
}
put(token, mutableMapOf())
}
is Token.Property -> {
currentProfile as Token.Profile
currentProperty = token
if (!token.isValid) {
traceSpan.warnParse(line) { "Ignoring invalid property '${token.key}'" }
continue
}
if (!currentProfile.isValid) {
traceSpan.warnParse(line) { "Ignoring property under invalid profile '${currentProfile.name}'" }
continue
}
val profile = this[currentProfile]!!
if (profile.containsKey(token.key)) {
traceSpan.warnParse(line) { "'${token.key}' defined multiple times in profile '${currentProfile.name}'" }
}
if (profile.containsKey(token.key)) {
traceSpan.warnParse(line) { "Overwriting previously-defined property '${token.key}'" }
}
profile[token.key] = AwsConfigValue.String(token.value)
}
is Token.Continuation -> {
currentProfile as Token.Profile
currentProperty as Token.Property
val profile = this[currentProfile]!!
val currentValue = (profile[currentProperty.key] as AwsConfigValue.String).value
profile[currentProperty.key] = AwsConfigValue.String(currentValue + "\n" + token.value)
}
is Token.SubProperty -> {
currentProfile as Token.Profile
currentProperty as Token.Property
if (!token.isValid) {
traceSpan.warnParse(line) { "Ignoring invalid sub-property '${token.key}'" }
continue
}
val profile = this[currentProfile]!!
val property = profile[currentProperty.key]
if (property is AwsConfigValue.String) { // convert newly recognized parent to map
if (property.value.isNotEmpty()) {
traceSpan.warnParse(line) { "Overwriting previously-defined property '${token.key}'" }
}
currentParentMap = mutableMapOf()
profile[currentProperty.key] = AwsConfigValue.Map(currentParentMap)
}
currentParentMap!![token.key] = token.value
}
}
}
}
/**
* When inputs have mixed profile prefixes, drop those without the prefix.
*
* Duplication Handling
*
* Profiles duplicated within the same file have their properties merged.
* If both [profile foo] and [foo] are specified in the same file, their properties are NOT merged.
* If both [profile foo] and [foo] are specified in the configuration file, [profile foo]'s properties are used.
* Properties duplicated within the same file and profile use the later property in the file.
*/
private fun mergeProfiles(tokenIndexMap: Map<Token.Profile, Map<String, AwsConfigValue>>): RawProfileMap =
tokenIndexMap
.filter { entry ->
when (entry.key.profilePrefix) {
true -> true
false -> {
val prefixVariantExists = tokenIndexMap.keys.any { it.profilePrefix && it.name == entry.key.name }
!prefixVariantExists
}
}
}
.mapKeys { entry -> entry.key.name }
private inline fun TraceSpan.warnParse(line: FileLine, crossinline content: () -> String) = warn("AwsConfigParser") {
contextMessage(content(), line.lineNumber)
}
| 89 | Kotlin | 33 | 273 | a859c7a93d86623795e96bbfc48d0aa622e3998d | 6,968 | aws-sdk-kotlin | Apache License 2.0 |
compiler/src/main/java/lang/taxi/TokenStore.kt | taxilang | 601,101,781 | false | null | package lang.taxi
import com.google.common.collect.ArrayListMultimap
import com.google.common.collect.Table
import com.google.common.collect.TreeBasedTable
import lang.taxi.types.SourceNames
import org.antlr.v4.runtime.ParserRuleContext
typealias RowIndex = Int // 0 Based
typealias ColumnIndex = Int // 0 Based
typealias TokenTable = Table<RowIndex, ColumnIndex, ParserRuleContext>
/**
* An exception thrown if we receive a reference to a source file that we don't know about.
* This generally happens when editing in VSCode, as we can receive uri references to files in inconsistent
* formats, and we need to try to normalize them, so they point to the same fle.
*/
class UnknownTokenReferenceException(val providedSourcePath: String, val currentKeys: Collection<String>) :
RuntimeException(
"$providedSourcePath is not present in the token store. Current keys are ${currentKeys.joinToString(",")}"
)
class TokenStore {
private val tables = mutableMapOf<String, TokenTable>()
private val typeReferencesBySourceName = ArrayListMultimap.create<String, TaxiParser.TypeReferenceContext>()
fun tokenTable(sourceName: String): TokenTable {
val sourcePath = SourceNames.normalize(sourceName)
if (!tables.containsKey(sourcePath)) {
throw UnknownTokenReferenceException(sourceName, tables.keys)
}
return tables.getValue(sourcePath)
}
fun containsTokensForSource(sourceName: String): Boolean {
val sourcePath = SourceNames.normalize(sourceName)
return tables.containsKey(sourcePath)
}
fun getTypeReferencesForSourceName(sourceName: String): List<TaxiParser.TypeReferenceContext> {
val normalized = SourceNames.normalize(sourceName)
return typeReferencesBySourceName[normalized]
}
fun insert(sourceName: String, rowNumber: RowIndex, columnIndex: ColumnIndex, context: ParserRuleContext) {
val sourcePath = SourceNames.normalize(sourceName)
tables.getOrPut(sourcePath, { TreeBasedTable.create() })
.put(rowNumber, columnIndex, context)
if (context is TaxiParser.TypeReferenceContext) {
typeReferencesBySourceName[sourceName].add(context)
}
}
operator fun plus(other: TokenStore): TokenStore {
val result = TokenStore()
result.tables.putAll(this.tables)
result.tables.putAll(other.tables)
result.typeReferencesBySourceName.putAll(this.typeReferencesBySourceName)
result.typeReferencesBySourceName.putAll(other.typeReferencesBySourceName)
return result
}
}
| 0 | Kotlin | 0 | 0 | 0672691199c27ddc87c5cd2c9ddd3953e0e5efe7 | 2,543 | taxilang | Apache License 2.0 |
dayjson/src/main/java/com/feature/dayjson/utils/JsonFileIOUtils.kt | wy676579037 | 224,416,546 | true | {"Kotlin": 92278, "Java": 4398} | package com.ruzhan.jsonfile.utils
import java.io.BufferedWriter
import java.io.File
import java.io.FileWriter
import java.io.IOException
object JsonFileIOUtils {
private fun isSpace(s: String?): Boolean {
if (s == null) return true
var i = 0
val len = s.length
while (i < len) {
if (!Character.isWhitespace(s[i])) {
return false
}
++i
}
return true
}
private fun getFileByPath(filePath: String): File? {
return if (isSpace(filePath)) null else File(filePath)
}
fun writeFileFromString(filePath: String,
content: String): Boolean {
return writeFileFromString(getFileByPath(filePath), content)
}
private fun writeFileFromString(file: File?,
content: String?): Boolean {
if (file == null || content == null) return false
if (!createOrExistsFile(file)) return false
var bw: BufferedWriter? = null
return try {
bw = BufferedWriter(FileWriter(file, false))
bw.write(content)
true
} catch (e: IOException) {
e.printStackTrace()
false
} finally {
try {
bw?.close()
} catch (e: IOException) {
e.printStackTrace()
}
}
}
private fun createOrExistsFile(file: File?): Boolean {
if (file == null) return false
if (file.exists()) return file.isFile
if (!createOrExistsDir(file.parentFile)) return false
return try {
file.createNewFile()
} catch (e: IOException) {
e.printStackTrace()
false
}
}
private fun createOrExistsDir(file: File?): Boolean {
return file != null && if (file.exists()) file.isDirectory else file.mkdirs()
}
}
| 0 | null | 0 | 0 | d624d821834bbaf0476892842bfc78061aaf536d | 1,929 | awaker | Apache License 2.0 |
src/commonMain/kotlin/org/snakeyaml/engine/v2/constructor/json/ConstructYamlJsonInt.kt | krzema12 | 642,543,787 | false | null | /*
* Copyright (c) 2018, SnakeYAML
*
* 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 it.krzeminski.snakeyaml.engine.kmp.constructor.json
import it.krzeminski.snakeyaml.engine.kmp.internal.toBigInteger
import it.krzeminski.snakeyaml.engine.kmp.constructor.ConstructScalar
import it.krzeminski.snakeyaml.engine.kmp.nodes.Node
/**
* Create instances for numbers (Integer, Long, BigInteger)
*/
class ConstructYamlJsonInt : ConstructScalar() {
override fun construct(node: Node?): Number {
val value = constructScalar(node)
return createIntNumber(value)
}
/**
* Create number trying fist Integer, then Long, then BigInteger
*
* @param number - the source
* @return number that fits the source
*/
private fun createIntNumber(number: String): Number {
// first try integer, then Long, and BigInteger as the last resource
return number.toIntOrNull()
?: number.toLongOrNull()
?: number.toBigInteger()
}
}
| 9 | Kotlin | 5 | 3 | ff5fc9f1f6962145007d8d10079857bd8d9c2652 | 1,513 | snakeyaml-engine-kmp | Apache License 2.0 |
Data/core-data/src/main/java/com/xiashao/data/database/entity/UserEntity.kt | xiashao | 654,186,557 | false | null | package com.xiashao.data.database.entity
import androidx.annotation.Keep
import androidx.room.ColumnInfo
import androidx.room.Entity
import androidx.room.PrimaryKey
import com.xiashao.model.DataSourceType
import com.xiashao.model.User
import kotlinx.datetime.Instant
@Keep
@Entity(tableName = "users")
data class UserEntity(
@PrimaryKey
val id: Int,
val avatar: String,
val email: String,
@ColumnInfo(name = "first_name")
val firstName: String,
@ColumnInfo(name = "last_name")
val lastName: String,
@ColumnInfo(name = "update_date")
val updateDate: Instant,
// auto migration 1->2
@ColumnInfo(name = "datasource_type")
val dataSourceType: DataSourceType,
)
fun UserEntity.asExternalModel() = User(
id = id,
firstName = firstName,
avatar = avatar,
email = email,
lastName = lastName,
dataSourceType = dataSourceType
)
| 0 | Kotlin | 0 | 0 | 815558f9b1df0c5fa9ba70e33be8eb586047b331 | 897 | ChatGpt-Mobile | Apache License 2.0 |
addressbook-main/src/test/kotlin/com/addressbook/test/TableFillTest.kt | dredwardhyde | 164,920,046 | false | null | package com.addressbook.test
import io.github.bonigarcia.wdm.WebDriverManager
import org.junit.FixMethodOrder
import org.junit.Test
import org.junit.runners.MethodSorters
import org.openqa.selenium.By
import org.openqa.selenium.support.ui.ExpectedConditions
import org.openqa.selenium.support.ui.WebDriverWait
import java.awt.Robot
import java.awt.event.KeyEvent
import java.time.Duration
@FixMethodOrder(MethodSorters.NAME_ASCENDING)
class TableFillTest {
@Test
fun stage1_fillOrganizationTable() {
// Initialize Selenium driver
val driver = WebDriverManager.chromedriver().create()
// Initialize wait driver
val webDriverWait = WebDriverWait(driver, Duration.ofSeconds(20))
// Dismiss certificate choice dialog
Thread {
try {
Thread.sleep(1_000)
val robot = Robot()
robot.keyPress(KeyEvent.VK_ESCAPE)
robot.keyRelease(KeyEvent.VK_ESCAPE)
} catch (e: Exception) {
e.printStackTrace()
}
}.start()
// Open login page
driver.get("https://localhost:9000")
// Wait until page is loaded
webDriverWait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath("//*[@id=\"login\"]")))
// Locate login input field
val loginInput = driver.findElement(By.xpath("//*[@id=\"login\"]"))
// Locate password input field
val passwordInput = driver.findElement(By.xpath("//*[@id=\"password\"]"))
// Locate login button
val loginButton = driver.findElement(By.xpath("/html/body/div[2]/div[3]/div/div[2]/div/button"))
// Enter login for ordinary user
loginInput.sendKeys("user")
// Enter password
passwordInput.sendKeys("<PASSWORD>")
// Click login
loginButton.click()
Thread.sleep(500)
// Locate user info button on navigation bar
webDriverWait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath("/html/body/div/div/div/div/header/div/div/button[1]")))
Thread.sleep(500)
// First level tile
webDriverWait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath("//*[@id=\"application\"]/div/div/a"))).click()
Thread.sleep(500)
// Second level 1 tile
webDriverWait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath("//*[@id=\"application\"]/div/div/a[1]"))).click()
Thread.sleep(500)
// Third level tile
webDriverWait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath("//*[@id=\"application\"]/div/div/a"))).click()
Thread.sleep(500)
// Last level tile
webDriverWait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath("//*[@id=\"application\"]/div/div/a"))).click()
Thread.sleep(500)
// Click first tab - Organizations
webDriverWait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath("//*[@id=\"tables\"]/div/div/button"))).click()
Thread.sleep(500)
var name: String
for (i in 0..1000) {
// Generate test name
name = "Test " + Math.random() + " Name"
// Enter data to create new organization record
driver.findElement(By.xpath("//*[@id=\"name\"]")).sendKeys(name)
driver.findElement(By.xpath("//*[@id=\"street\"]")).sendKeys("Test street")
driver.findElement(By.xpath("//*[@id=\"zip\"]")).sendKeys("Test zip")
// Choose Private type of organization
driver.findElement(By.xpath("//*[@id=\"mui-component-select-type\"]")).click()
driver.findElement(By.xpath("//*[@id=\"menu-type\"]/div[3]/ul/li[2]")).click()
// Click Create organization button
driver.findElement(By.xpath("//*[@id=\"simple-tabpanel-1\"]/div/div[1]/div/button")).click()
Thread.sleep(300)
// Twice sort table by "Last updated" field
driver.findElement(By.xpath("//*[@id=\"simple-tabpanel-1\"]/div/div[2]/div/div[2]/table/thead/tr/th[7]/div[1]/div[1]/div")).click()
Thread.sleep(300)
driver.findElement(By.xpath("//*[@id=\"simple-tabpanel-1\"]/div/div[2]/div/div[2]/table/thead/tr/th[7]/div[1]/div[1]/div")).click()
Thread.sleep(300)
// Find name of first record
driver.findElement(By.xpath("//*[@id=\"simple-tabpanel-1\"]/div/div[2]/div/div[2]/table/tbody/tr[1]")).click()
}
// Wait until all notifications disappear
Thread.sleep(10_000)
// Click logout button
webDriverWait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath("/html/body/div/div/div/div[1]/header/div/div/button[5]"))).click()
webDriverWait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath("/html/body/div[2]/div[3]/div/div[2]/button[2]"))).click()
Thread.sleep(300)
driver.quit()
}
} | 1 | Kotlin | 5 | 10 | 93e23a624e48b9c5f9842b3142997d8161b2559a | 4,955 | addressbook | Apache License 2.0 |
app/src/main/java/com/udacity/asteroidradar/util/DomainMapper.kt | Maniak-pl | 328,315,093 | false | null | package com.udacity.asteroidradar.util
import com.udacity.asteroidradar.data.api.AsteroidResponse
import com.udacity.asteroidradar.data.api.PictureOfDayResponse
import com.udacity.asteroidradar.data.db.AsteroidEntity
import com.udacity.asteroidradar.data.db.PictureEntity
import com.udacity.asteroidradar.data.domain.Asteroid
import com.udacity.asteroidradar.data.domain.PictureOfDay
fun List<AsteroidEntity>.toDomainModel(): List<Asteroid> {
return map {
Asteroid(
id = it.id,
codename = it.codename,
closeApproachDate = it.closeApproachDate,
absoluteMagnitude = it.absoluteMagnitude,
estimatedDiameter = it.estimatedDiameter,
relativeVelocity = it.relativeVelocity,
distanceFromEarth = it.distanceFromEarth,
isPotentiallyHazardous = it.isPotentiallyHazardous
)
}
}
fun PictureEntity.toDomainModel(): PictureOfDay {
return PictureOfDay(
mediaType = this.mediaType,
title = this.title,
url = this.url
)
}
fun List<AsteroidResponse>.toDatabaseModel(): Array<AsteroidEntity> {
return map {
AsteroidEntity(
id = it.id,
codename = it.codename,
closeApproachDate = it.closeApproachDate,
absoluteMagnitude = it.absoluteMagnitude,
estimatedDiameter = it.estimatedDiameter,
relativeVelocity = it.relativeVelocity,
distanceFromEarth = it.distanceFromEarth,
isPotentiallyHazardous = it.isPotentiallyHazardous
)
}.toTypedArray()
}
fun PictureOfDayResponse.toDatabaseModel(): PictureEntity {
return PictureEntity(
mediaType = this.mediaType,
title = this.title,
url = this.url
)
} | 0 | Kotlin | 0 | 0 | 20b3375074fd3aa5be12693a8b3477dd4f8751f6 | 1,777 | AsteroidRadar | Apache License 2.0 |
domain/src/main/java/net/hyakuninanki/reader/domain/question/model/ExamId.kt | rei-m | 265,877,217 | false | null | /*
* Copyright (c) 2020. <NAME>.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package net.hyakuninanki.reader.domain.question.model
import net.hyakuninanki.reader.domain.EntityId
/**
* 力試しID.
*
* @param value 値
*/
data class ExamId(
val value: Long
) : EntityId
| 0 | Kotlin | 0 | 0 | ff79f10344ff2fdafc2c189cc044e11496a5294b | 794 | android-hyakuninisshu-reader | Apache License 2.0 |
abcdecoder/src/jvmMain/kotlin/me/yricky/abcde/util/SelectedFile.kt | Yricky | 799,255,451 | false | {"Kotlin": 276512} | package me.yricky.abcde.util
import me.yricky.oh.abcd.AbcBuf
import me.yricky.oh.abcd.AbcHeader
import me.yricky.oh.common.wrapAsLEByteBuf
import me.yricky.oh.resde.ResIndexBuf
import me.yricky.oh.resde.ResIndexHeader
import java.io.File
import java.nio.ByteOrder
import java.nio.channels.FileChannel
import java.util.zip.ZipFile
sealed class TypedFile(val file:File)
sealed class SelectedFile(file:File):TypedFile(file){
abstract fun valid():Boolean
val buf by lazy {
FileChannel.open(file.toPath())
.map(FileChannel.MapMode.READ_ONLY, 0, file.length())
.let { wrapAsLEByteBuf(it.order(ByteOrder.LITTLE_ENDIAN)) }
}
companion object{
fun fromOrNull(file:File):SelectedFile?{
return when(file.extension.uppercase()){
SelectedAbcFile.EXT -> SelectedAbcFile(file)
SelectedIndexFile.EXT -> SelectedIndexFile(file)
SelectedHapFile.EXT -> SelectedHapFile(file)
else -> null
}
}
}
}
class SelectedAbcFile(file: File, tag:String = file.path) :SelectedFile(file){
val abcBuf by lazy {
AbcBuf(
tag,
buf
)
}
override fun valid(): Boolean {
return file.length() > AbcHeader.SIZE &&
abcBuf.header.isValid()
}
companion object{
const val EXT = "ABC"
}
}
class SelectedIndexFile(file: File,val tag:String = file.path) :SelectedFile(file){
val resBuf by lazy {
ResIndexBuf(buf)
}
override fun valid(): Boolean {
return file.length() > ResIndexHeader.SIZE
}
companion object{
const val EXT = "INDEX"
}
}
class SelectedHapFile(file: File) :SelectedFile(file){
val hap by lazy {
kotlin.runCatching {
ZipFile(file)
}
}
override fun valid(): Boolean {
return hap.isSuccess
}
companion object{
const val EXT = "HAP"
}
} | 2 | Kotlin | 41 | 230 | cf65ba5d90e271f19ccaeca33f85c1b7358988eb | 1,976 | abcde | Apache License 2.0 |
Compose-Flight-Search-App/app/src/test/kotlin/com/example/flightsearchapp/testing/model/database/AirportEntitiesTestData.kt | Jaehwa-Noh | 754,078,368 | false | {"Kotlin": 122112} | package com.example.flightsearchapp.testing.model.database
import com.example.flightsearchapp.data.database.AirportEntity
/**
* Test data for List<[AirportEntity]>.
*/
val airportEntitiesTestData: List<AirportEntity> = listOf(
testAirportEntity(1, "ABC"),
testAirportEntity(2, "CDE"),
testAirportEntity(3, "EFG"),
testAirportEntity(4, "GHI"),
)
/**
* Create test data for [AirportEntity].
*/
fun testAirportEntity(id: Long, code: String) = AirportEntity(
id = id,
name = "name$id",
iataCode = code,
passengers = 10 - id,
)
| 0 | Kotlin | 0 | 0 | c5f18ecd408256b087a6a0a2d63203972b8705ff | 562 | Project-Flight-Search-App | Apache License 2.0 |
src/test/kotlin/org/assertj/generator/gradle/parameter/OutputDirectoryParameter.kt | assertj | 92,816,640 | false | {"Kotlin": 108700, "Java": 4347} | /*
* Copyright 2023. assertj-generator-gradle-plugin contributors.
*
* 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.assertj.generator.gradle.parameter
import net.navatwo.gradle.testkit.junit5.GradleProject
import org.assertj.core.api.AssertionsForInterfaceTypes.assertThat
import org.assertj.generator.gradle.TestUtils.writeBuildFile
import org.assertj.generator.gradle.isSuccessful
import org.gradle.configurationcache.extensions.capitalized
import org.gradle.testkit.runner.GradleRunner
import org.junit.jupiter.api.Test
import java.io.File
/**
* Checks the behaviour of overriding globals in a project
*/
internal class OutputDirectoryParameter {
private val File.buildFile: File
get() = resolve("build.gradle")
private val packagePath: File
get() = File("org/example")
@Test
@GradleProject("output-directory-parameter")
fun change_output_dir_locally(
@GradleProject.Root root: File,
@GradleProject.Runner runner: GradleRunner,
) {
root.buildFile.writeBuildFile(
"""
sourceSets {
main {
assertJ {
// default: generated-srcs/SOURCE_SET_NAME-test/java
outputDir = file('src-gen/foo-bar/java')
}
}
}
"""
)
val result = runner.withArguments("-i", "-s", "test").build()
assertThat(result.task(":generateAssertJ")).isSuccessful()
assertThat(result.task(":test")).isSuccessful()
root.assertFiles("foo-bar", true)
}
private fun File.assertFiles(folderName: String, exists: Boolean) {
val sourceSet = "main"
val generatedPackagePath = resolve("src-gen/$folderName/java")
.resolve(packagePath)
val buildPath = resolve("build")
val path = generatedPackagePath.resolve("${sourceSet.capitalized()}Assert.java")
assertThat(path.exists())
.`as` { "$sourceSet file: ${buildPath.toPath().relativize(path.toPath())} exists" }
.isEqualTo(exists)
}
}
| 11 | Kotlin | 5 | 32 | 8fe43021719ab075f7d4e1b7eae3609a490f9f5e | 2,496 | assertj-generator-gradle-plugin | Apache License 2.0 |
app/src/main/java/com/kavrin/marvin/navigation/TvNavGraph.kt | k4vrin | 503,752,158 | false | {"Kotlin": 562455} | package com.kavrin.marvin.navigation
import androidx.compose.animation.AnimatedContentScope
import androidx.compose.animation.core.tween
import androidx.compose.animation.fadeIn
import androidx.compose.animation.fadeOut
import androidx.compose.runtime.remember
import androidx.hilt.navigation.compose.hiltViewModel
import androidx.navigation.NavGraphBuilder
import androidx.navigation.NavHostController
import androidx.navigation.NavType
import androidx.navigation.navArgument
import com.google.accompanist.navigation.animation.composable
import com.google.accompanist.navigation.animation.navigation
import com.kavrin.marvin.navigation.util.Durations
import com.kavrin.marvin.navigation.util.Graph
import com.kavrin.marvin.navigation.util.HomeScreens
import com.kavrin.marvin.navigation.util.TvScreens
import com.kavrin.marvin.presentation.screens.tv.TvScreen
import com.kavrin.marvin.presentation.screens.tv_season.SeasonViewModel
import com.kavrin.marvin.presentation.screens.tv_season.season.SeasonScreen
import com.kavrin.marvin.util.Constants
fun NavGraphBuilder.tvNavGraph(navHostController: NavHostController) {
navigation(
route = Graph.Tv.route,
startDestination = TvScreens.Tv.route,
arguments = listOf(
navArgument(Constants.ARGUMENT_KEY_ID) {
type = NavType.IntType
}
)
) {
//// Tv Screen ////
composable(
route = TvScreens.Tv.route,
arguments = listOf(
navArgument(Constants.ARGUMENT_KEY_ID) {
type = NavType.IntType
}
),
enterTransition = {
slideIntoContainer(
towards = AnimatedContentScope.SlideDirection.Up,
animationSpec = tween(
durationMillis = Durations.MEDIUM,
delayMillis = Durations.EXTRA_LONG
)
)
},
exitTransition = {
fadeOut(
tween(
durationMillis = Durations.MEDIUM,
delayMillis = Durations.EXTRA_LONG + Durations.EXTRA_SHORT
)
)
},
popEnterTransition = {
fadeIn(
tween(
durationMillis = Durations.SHORT,
delayMillis = Durations.EXTRA_SHORT * 2
)
)
},
popExitTransition = {
slideOutOfContainer(
towards = AnimatedContentScope.SlideDirection.Down,
animationSpec = tween(
durationMillis = Durations.MEDIUM
)
)
}
) {
TvScreen(navHostController = navHostController)
}
///// Season Screen /////
composable(
route = TvScreens.Season.route,
arguments = listOf(
navArgument(Constants.ARGUMENT_KEY_ID) {
type = NavType.IntType
},
navArgument(Constants.ARGUMENT_KEY_SEASON_NUMBER) {
type = NavType.IntType
}
),
enterTransition = {
slideIntoContainer(
towards = AnimatedContentScope.SlideDirection.Left,
animationSpec = tween(
durationMillis = Durations.MEDIUM,
delayMillis = Durations.EXTRA_LONG
)
)
},
exitTransition = {
fadeOut(
tween(
durationMillis = Durations.MEDIUM,
delayMillis = Durations.EXTRA_LONG + Durations.EXTRA_SHORT
)
)
},
popEnterTransition = {
fadeIn(
tween(
durationMillis = Durations.SHORT,
delayMillis = Durations.EXTRA_SHORT * 2
)
)
},
popExitTransition = {
slideOutOfContainer(
towards = AnimatedContentScope.SlideDirection.Right,
animationSpec = tween(
durationMillis = Durations.MEDIUM
)
)
}
) { navBackStackEntry ->
val parentEntry = remember(navBackStackEntry) {
navHostController.getBackStackEntry(route = TvScreens.Season.route)
}
val viewModel = hiltViewModel<SeasonViewModel>(parentEntry)
SeasonScreen(
navHostController = navHostController,
viewModel = viewModel
)
}
///// Episode Screen /////
composable(
route = TvScreens.Episode.route,
arguments = listOf(
navArgument(Constants.ARGUMENT_KEY_ID) {
type = NavType.IntType
}
),
enterTransition = {
slideIntoContainer(
towards = AnimatedContentScope.SlideDirection.Left,
animationSpec = tween(
durationMillis = Durations.MEDIUM,
delayMillis = Durations.LONG
)
)
},
exitTransition = {
fadeOut(
tween(
durationMillis = Durations.MEDIUM,
delayMillis = Durations.EXTRA_LONG
)
)
},
popEnterTransition = {
fadeIn(
tween(
durationMillis = Durations.SHORT,
delayMillis = Durations.EXTRA_SHORT * 2
)
)
},
popExitTransition = {
when (targetState.destination.route) {
HomeScreens.Home.route -> {
slideOutOfContainer(
towards = AnimatedContentScope.SlideDirection.Down,
animationSpec = tween(
durationMillis = Durations.MEDIUM,
delayMillis = Durations.MEDIUM
)
)
}
else -> {
slideOutOfContainer(
towards = AnimatedContentScope.SlideDirection.Down,
animationSpec = tween(
durationMillis = Durations.MEDIUM
)
)
}
}
}
) { navBackStackEntry ->
val parentEntry = remember(navBackStackEntry) {
navHostController.getBackStackEntry(route = Graph.Tv.route)
}
val viewModel = hiltViewModel<SeasonViewModel>(parentEntry)
}
}
} | 0 | Kotlin | 0 | 2 | 13dde151d9d35d2a68a08b2f0b17e89fa9ab56bf | 7,214 | Marvin | MIT License |
app/src/main/java/com/otonishi/example/mvvmviewpagerdi/ui/top/TopActivity.kt | yotonishi | 362,799,143 | false | null | package com.otonishi.example.mvvmviewpagerdi.ui.top
import android.content.Intent
import android.os.Bundle
import androidx.activity.viewModels
import androidx.appcompat.app.AppCompatActivity
import androidx.databinding.DataBindingUtil
import com.otonishi.example.mvvmviewpagerdi.R
import com.otonishi.example.mvvmviewpagerdi.databinding.ActivityTopBinding
import com.otonishi.example.mvvmviewpagerdi.extension.setupActionBar
import com.otonishi.example.mvvmviewpagerdi.ui.viewpager.ViewPagerActivity
import dagger.hilt.android.AndroidEntryPoint
@AndroidEntryPoint
class TopActivity : AppCompatActivity(), TopNavigator {
private val topViewModel: TopViewModel by viewModels()
private val binding by lazy {
DataBindingUtil.setContentView<ActivityTopBinding>(
this@TopActivity, R.layout.activity_top
)
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_top)
setupActionBar(binding.toolbar) {
title = resources.getString(R.string.app_name)
}
binding.viewmodel = topViewModel
topViewModel.setTopTitle()
topViewModel.setCallback(this)
topViewModel.setAuthorName()
}
override fun onSupportNavigateUp(): Boolean {
finish()
return true
}
override fun toViewPager() {
startActivity(Intent(this, ViewPagerActivity::class.java))
}
} | 0 | Kotlin | 0 | 0 | 11d7c288921baf5b6333939033efa60163fb2cbf | 1,464 | mvvm-viewpager-di-sample | Apache License 2.0 |
library/src/main/kotlin/build/buf/connect/impl/BidirectionalStream.kt | bufbuild | 604,763,682 | false | null | // Copyright 2022-2023 Buf Technologies, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package build.buf.connect.impl
import build.buf.connect.BidirectionalStreamInterface
import build.buf.connect.Codec
import build.buf.connect.StreamResult
import build.buf.connect.http.Stream
import kotlinx.coroutines.channels.Channel
import kotlinx.coroutines.channels.ReceiveChannel
import java.lang.Exception
/**
* Concrete implementation of [BidirectionalStreamInterface].
*/
internal class BidirectionalStream<Input, Output>(
val stream: Stream,
private val requestCodec: Codec<Input>,
private val receiveChannel: Channel<StreamResult<Output>>
) : BidirectionalStreamInterface<Input, Output> {
override suspend fun send(input: Input): Result<Unit> {
val msg = try {
requestCodec.serialize(input)
} catch (e: Exception) {
return Result.failure(e)
}
return stream.send(msg)
}
override fun resultChannel(): ReceiveChannel<StreamResult<Output>> {
return receiveChannel
}
override fun close() {
stream.sendClose()
}
override fun isClosed(): Boolean {
return stream.isClosed()
}
override fun sendClose() {
stream.sendClose()
}
override fun receiveClose() {
stream.receiveClose()
}
override fun isSendClosed(): Boolean {
return stream.isSendClosed()
}
override fun isReceiveClosed(): Boolean {
return stream.isReceiveClosed()
}
}
| 11 | Kotlin | 2 | 46 | 4298933845eaf7b204547707ad15f7f956aeb8ac | 2,033 | connect-kotlin | Apache License 2.0 |
src/test/kotlin/kotlinx/fuzzer/fuzzing/storage/exceptions/ReflectionStacktraceTest.kt | zuevmaxim | 245,368,264 | false | {"Kotlin": 125295, "Java": 24863, "Shell": 1145} | package kotlinx.fuzzer.fuzzing.storage.exceptions
import kotlinx.fuzzer.coverage.createCoverageRunner
import kotlinx.fuzzer.fuzzing.TargetMethod
import kotlinx.fuzzer.fuzzing.input.FailInput
import kotlinx.fuzzer.fuzzing.input.Input
import org.junit.jupiter.api.Assertions.assertFalse
import org.junit.jupiter.api.Test
internal class ReflectionStacktraceTest {
companion object {
private const val CLASS_LOCATION = "build/classes/kotlin/test/kotlinx/fuzzer/testclasses/reflection/"
private const val PACKAGE_NAME = "kotlinx.fuzzer.testclasses.reflection"
private const val CLASS_NAME = "kotlinx.fuzzer.testclasses.reflection.ReflectionTestClass"
private val coverageRunner = createCoverageRunner(listOf(CLASS_LOCATION), listOf(PACKAGE_NAME))
private val targetClass = coverageRunner.loadClass(CLASS_NAME) ?: error("Class $CLASS_NAME not found.")
val targetMethod = TargetMethod(targetClass, "test")
}
@Test
fun userReflectionShouldNotBeTrimmed() {
val failInput1 = Input(ByteArray(2)).run(coverageRunner, targetMethod) as FailInput
val failInput2 = Input(ByteArray(3)).run(coverageRunner, targetMethod) as FailInput
assertFalse(failInput1.e.stackTraceEqualTo(failInput2.e))
}
}
| 1 | Kotlin | 0 | 3 | 34255b0a35ee479021a165f2bdbe6ffe0b3109c5 | 1,273 | kotlin-fuzzer | MIT License |
src/test/kotlin/non_test/kotlin_playground/real_oop.kt | christophpickl | 56,092,216 | false | null | package non_test.kotlin_playground
import at.cpickl.gadsu.client.Client
import at.cpickl.gadsu.client.ClientService
import at.cpickl.gadsu.start.allGadsuModules
import at.cpickl.gadsu.testinfra.unsavedValidInstance
import com.google.inject.AbstractModule
import com.google.inject.Guice
import javax.inject.Inject
fun main(args: Array<String>) {
Guice.createInjector(RealOopModule())
.getInstance(RealOopApp::class.java)
.doWork()
}
class RealOopModule : AbstractModule() {
override fun configure() {
val databaseUrl = "jdbc:hsqldb:mem:realOOP"
allGadsuModules(databaseUrl).forEach {
install(it)
}
bind(Gd::class.java).asEagerSingleton()
bind(RealOopApp::class.java).asEagerSingleton()
}
}
interface GdClient {
var firstName: String
fun save()
}
data class GdClientImpl(
var client: Client,
private val clientService: ClientService
) : GdClient {
override var firstName: String
get() = client.firstName
set(value) {
client = client.copy(firstName = value)
}
override fun save() {
// =======>
// clientService.insertOrUpdate(this.client)
// =======>
println("save() => $client")
}
}
class Gd @Inject constructor(
private val clientService: ClientService
) {
fun byClient(client: Client): GdClient {
return GdClientImpl(client, clientService)
}
}
class RealOopApp @Inject constructor(
private val gd: Gd
) {
fun doWork() {
val client = gd.byClient(Client.unsavedValidInstance())
println("client = $client")
client.firstName = "new"
client.save()
println("client = $client")
}
}
| 43 | Kotlin | 1 | 2 | f6a84c42e1985bc53d566730ed0552b3ae71d94b | 1,757 | gadsu | Apache License 2.0 |
ktx/espresso/core/javatests/androidx/test/espresso/HelloKtxTest.kt | Rockyspade | 161,131,999 | true | {"Java": 3999098, "Python": 577320, "HTML": 29998, "Kotlin": 11723, "Shell": 3950, "Dockerfile": 591} | /*
* Copyright (C) 2018 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package androidx.test.espresso
import androidx.test.runner.AndroidJUnit4
import com.google.common.truth.Truth.assertThat
import org.junit.Test
import org.junit.runner.RunWith
@RunWith(AndroidJUnit4::class)
class HelloKtxTest {
@Test
fun doesTestingRock() = assertThat(HelloKtx().testing).isEqualTo("rocks")
}
| 0 | Java | 0 | 1 | 07237c39dd498795962f6b44135647f642a5e359 | 937 | android-test | Apache License 2.0 |
src/main/kotlin/mirrg/kotlin/hydrogen/Collection.kt | MirageFairy | 594,492,956 | false | null | /*
* Copyright 2022 MirrgieRiana
*
* 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:Suppress("unused", "SpellCheckingInspection")
package mirrg.kotlin.hydrogen
val <T : Collection<I>, I> T.notEmptyOrNull get() = takeIf { isNotEmpty() }
val <T : Iterable<I>, I> T.notNoneOrNull get() = takeIf { !none() }
val <I> Array<I>.notEmptyOrNull get() = takeIf { isNotEmpty() }
val <T : Sequence<I>, I> T.notNoneOrNull get() = takeIf { !none() }
| 0 | Kotlin | 0 | 2 | 765cf3544591ba2626f5a374f5e9fc96a3ad1613 | 957 | MirageFairy2023 | Apache License 2.0 |
http4k-incubator/src/main/kotlin/org/http4k/openapi/v3/client/function.kt | Sebruck | 262,967,524 | true | {"Kotlin": 1673185, "JavaScript": 133282, "Java": 31515, "Shell": 10179, "HTML": 4506, "Python": 1592, "CSS": 832} | package org.http4k.openapi.v3.client
import com.squareup.kotlinpoet.CodeBlock
import com.squareup.kotlinpoet.CodeBlock.Companion.of
import com.squareup.kotlinpoet.FunSpec
import com.squareup.kotlinpoet.asClassName
import org.http4k.core.ContentType.Companion.APPLICATION_FORM_URLENCODED
import org.http4k.core.Filter
import org.http4k.core.Method
import org.http4k.core.Request
import org.http4k.core.Response
import org.http4k.core.cookie.Cookie
import org.http4k.openapi.v3.OpenApi3Spec
import org.http4k.openapi.v3.ParameterSpec
import org.http4k.openapi.v3.PathSpec
import org.http4k.openapi.v3.models.buildModelClass
import org.http4k.poet.Property
import org.http4k.poet.Property.Companion.addReturnType
import org.http4k.poet.addCodeBlocks
import org.http4k.poet.asTypeName
import org.http4k.poet.lensDeclarations
import org.http4k.poet.packageMember
import org.http4k.poet.quotedName
fun OpenApi3Spec.function(path: String, method: Method, pathSpec: PathSpec): FunSpec {
val functionName = pathSpec.operationId ?: method.name.toLowerCase() + path.replace('/', '_')
val reifiedPath = path.replace("/{", "/\${")
val messageBindings = pathSpec.parameters.mapNotNull {
val binding = "${it.name}Lens of ${it.name}"
val with = packageMember<Filter>("with")
when (it) {
is ParameterSpec.CookieSpec -> {
val optionality = if (it.required) "" else " ?: \"\""
of("\n.%M(${it.name}Lens of %T(${it.quotedName()}, ${it.name}$optionality))", with, Cookie::class.asClassName())
}
is ParameterSpec.HeaderSpec -> of("\n.%M($binding)", with)
is ParameterSpec.QuerySpec -> of("\n.%M($binding)", with)
else -> null
}
}
val request = messageBindings
.fold(CodeBlock.builder()
.add("val request = %T(%T.$method,·\"$reifiedPath\")", Property<Request>().type, Property<Method>().type)) { acc, next ->
acc.add(next)
}.build()
return FunSpec.builder(functionName).addAllParametersFrom(pathSpec)
.addReturnType(Property<Response>())
.addCodeBlocks(lensDeclarations(pathSpec))
.addCode(request)
.addCode("\nreturn·httpHandler(request)")
.build()
}
private fun FunSpec.Builder.addAllParametersFrom(pathSpec: PathSpec): FunSpec.Builder {
val parameters = pathSpec.parameters.map { it.name to it.asTypeName()!! }
val formParams = pathSpec.requestBody
?.contentFor(APPLICATION_FORM_URLENCODED)
?.schema
?.buildModelClass("form", emptyMap(), mutableMapOf())
?.primaryConstructor?.parameters?.map { it.name to it.type } ?: emptyList()
return (parameters + formParams).fold(this) { acc, next ->
acc.addParameter(next.first, next.second)
}
}
| 0 | null | 0 | 0 | b1233eae0ac39d4f70a463886c651ed0ec2dbb5e | 2,808 | http4k | Apache License 2.0 |
zoomdls/src/main/java/com/zoomcar/uikit/decor/SectionHeader.kt | ZoomCar | 237,639,513 | false | null | package com.zoomcar.uikit.decor
/**
* @created 26/01/2020 - 12:57
* @project Zoomcar
* @author Arun
* Copyright (c) 2020 Zoomcar. All rights reserved.
*/
interface SectionHeader
| 0 | Kotlin | 7 | 3 | cd92e5391b6405b1f857420e01a97f1297c11a54 | 184 | android-dls | Apache License 2.0 |
app/src/main/java/cz/yanas/bitcoin/widgets/NodeStatusWidget.kt | yanascz | 516,121,902 | false | {"Kotlin": 43403} | package cz.yanas.bitcoin.widgets
import android.appwidget.AppWidgetManager
import android.appwidget.AppWidgetProvider
import android.content.BroadcastReceiver
import android.content.ComponentName
import android.content.Context
import android.content.Intent
import android.util.Log
import android.widget.RemoteViews
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
class NodeStatusWidget : AppWidgetProvider() {
override fun onUpdate(context: Context, appWidgetManager: AppWidgetManager, appWidgetIds: IntArray) {
doUpdate(context, appWidgetManager, appWidgetIds)
}
override fun onDeleted(context: Context, appWidgetIds: IntArray) {
for (appWidgetId in appWidgetIds) {
NodeConfigurationRepository.clearConfiguration(context, appWidgetId)
}
}
internal companion object {
fun doUpdate(context: Context, appWidgetManager: AppWidgetManager, appWidgetIds: IntArray) {
CoroutineScope(Dispatchers.IO).launch {
for (appWidgetId in appWidgetIds) {
doUpdate(context, appWidgetManager, appWidgetId)
}
}
}
fun doUpdate(context: Context, appWidgetManager: AppWidgetManager, appWidgetId: Int) {
val configuration = NodeConfigurationRepository.getConfiguration(context, appWidgetId) ?: return
var views: RemoteViews
try {
val nodeStatus = NodeStatusProvider.getNodeStatus(configuration)
views = RemoteViews(context.packageName, R.layout.node_status_widget)
views.setTextViewText(R.id.node_status_block_height, nodeStatus.blockHeight.toString())
views.setTextViewText(R.id.node_status_user_agent, nodeStatus.userAgent)
views.setTextViewText(R.id.node_status_protocol_version, nodeStatus.protocolVersion.toString())
} catch (throwable: Throwable) {
Log.e("NodeStatusWidget", "Node status not available", throwable)
views = RemoteViews(context.packageName, R.layout.widget_error)
}
appWidgetManager.updateAppWidget(appWidgetId, views)
}
}
class ConfigurationActivity : NodeConfigurationActivity() {
override fun updateAppWidget(context: Context, appWidgetManager: AppWidgetManager, appWidgetId: Int) {
CoroutineScope(Dispatchers.IO).launch {
doUpdate(context, appWidgetManager, appWidgetId)
}
}
}
class UpdateReceiver : BroadcastReceiver() {
override fun onReceive(context: Context, intent: Intent) {
val appWidgetManager = AppWidgetManager.getInstance(context)
val nodeStatusWidgetName = ComponentName(context, NodeStatusWidget::class.java)
val appWidgetIds = appWidgetManager.getAppWidgetIds(nodeStatusWidgetName)
doUpdate(context, appWidgetManager, appWidgetIds)
}
}
}
| 2 | Kotlin | 2 | 4 | f678bc3cb9a96f5c3ea39a128c580ea1d81213bd | 3,023 | bitcoin-widgets-android | MIT License |
app/src/main/java/com/battlelancer/seriesguide/movies/MoviesWatchListViewModel.kt | UweTrottmann | 1,990,682 | false | {"Gradle Kotlin DSL": 7, "PowerShell": 1, "Text": 3, "Markdown": 14, "Java Properties": 1, "Shell": 1, "Ignore List": 2, "Batchfile": 1, "Git Attributes": 1, "YAML": 5, "TOML": 1, "INI": 1, "Proguard": 2, "XML": 403, "JSON": 11, "Kotlin": 408, "Java": 170} | // SPDX-License-Identifier: Apache-2.0
// Copyright 2024 <NAME>
package com.battlelancer.seriesguide.movies
import android.app.Application
import com.battlelancer.seriesguide.provider.SeriesGuideContract
class MoviesWatchListViewModel(application: Application) : MoviesWatchedViewModel(application) {
override val selection: String
get() = SeriesGuideContract.Movies.SELECTION_WATCHLIST
} | 50 | Kotlin | 399 | 1,920 | 20bb18d5310046b0400f8b9dc105334f9212f226 | 405 | SeriesGuide | Apache License 2.0 |
packages/SystemUI/src/com/android/systemui/toast/ToastDefaultAnimation.kt | liu-wanshun | 595,904,109 | true | null | /*
* Copyright (C) 2021 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.android.systemui.toast
import android.animation.ObjectAnimator
import android.view.View
import android.view.animation.LinearInterpolator
import android.view.animation.PathInterpolator
import android.animation.AnimatorSet
class ToastDefaultAnimation {
/**
* sum of the in and out animation durations cannot exceed
* [com.android.server.policy.PhoneWindowManager.TOAST_WINDOW_ANIM_BUFFER] to prevent the toast
* window from being removed before animations are completed
*/
companion object {
// total duration shouldn't exceed NotificationManagerService's delay for "in" animation
fun toastIn(view: View): AnimatorSet? {
val icon: View? = view.findViewById(com.android.systemui.R.id.icon)
val text: View? = view.findViewById(com.android.systemui.R.id.text)
if (icon == null || text == null) {
return null
}
val linearInterp = LinearInterpolator()
val scaleInterp = PathInterpolator(0f, 0f, 0f, 1f)
val sX = ObjectAnimator.ofFloat(view, "scaleX", 0.9f, 1f).apply {
interpolator = scaleInterp
duration = 333
}
val sY = ObjectAnimator.ofFloat(view, "scaleY", 0.9f, 1f).apply {
interpolator = scaleInterp
duration = 333
}
val vA = ObjectAnimator.ofFloat(view, "alpha", 0f, 1f).apply {
interpolator = linearInterp
duration = 66
}
text.alpha = 0f // Set now otherwise won't apply until start delay
val tA = ObjectAnimator.ofFloat(text, "alpha", 0f, 1f).apply {
interpolator = linearInterp
duration = 283
startDelay = 50
}
icon.alpha = 0f // Set now otherwise won't apply until start delay
val iA = ObjectAnimator.ofFloat(icon, "alpha", 0f, 1f).apply {
interpolator = linearInterp
duration = 283
startDelay = 50
}
return AnimatorSet().apply {
playTogether(sX, sY, vA, tA, iA)
}
}
fun toastOut(view: View): AnimatorSet? {
// total duration shouldn't exceed NotificationManagerService's delay for "out" anim
val icon: View? = view.findViewById(com.android.systemui.R.id.icon)
val text: View? = view.findViewById(com.android.systemui.R.id.text)
if (icon == null || text == null) {
return null
}
val linearInterp = LinearInterpolator()
val scaleInterp = PathInterpolator(0.3f, 0f, 1f, 1f)
val viewScaleX = ObjectAnimator.ofFloat(view, "scaleX", 1f, 0.9f).apply {
interpolator = scaleInterp
duration = 250
}
val viewScaleY = ObjectAnimator.ofFloat(view, "scaleY", 1f, 0.9f).apply {
interpolator = scaleInterp
duration = 250
}
val viewElevation = ObjectAnimator.ofFloat(view, "elevation",
view.elevation, 0f).apply {
interpolator = linearInterp
duration = 40
startDelay = 150
}
val viewAlpha = ObjectAnimator.ofFloat(view, "alpha", 1f, 0f).apply {
interpolator = linearInterp
duration = 100
startDelay = 150
}
val textAlpha = ObjectAnimator.ofFloat(text, "alpha", 1f, 0f).apply {
interpolator = linearInterp
duration = 166
}
val iconAlpha = ObjectAnimator.ofFloat(icon, "alpha", 1f, 0f).apply {
interpolator = linearInterp
duration = 166
}
return AnimatorSet().apply {
playTogether(
viewScaleX,
viewScaleY,
viewElevation,
viewAlpha,
textAlpha,
iconAlpha)
}
}
}
}
| 0 | Java | 1 | 2 | e99201cd9b6a123b16c30cce427a2dc31bb2f501 | 4,764 | platform_frameworks_base | Apache License 2.0 |
components/kotlin-eventsourcing/src/test/kotlin/dk/cloudcreate/essentials/components/kotlin/eventsourcing/test/GivenWhenThenScenarioTest.kt | cloudcreate-dk | 571,305,651 | false | {"Maven POM": 27, "XML": 18, "Ignore List": 1, "Text": 2, "Markdown": 28, "Java": 894, "Avro IDL": 1, "Kotlin": 87, "YAML": 4} | /*
* Copyright 2021-2024 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
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package dk.cloudcreate.essentials.components.kotlin.eventsourcing.test
import dk.cloudcreate.essentials.components.foundation.types.RandomIdGenerator
import dk.cloudcreate.essentials.components.kotlin.eventsourcing.Decider
import dk.cloudcreate.essentials.kotlin.types.StringValueType
import org.junit.jupiter.api.Test
class GivenWhenThenScenarioTest {
@Test
fun `Create an Order`() {
val scenario = GivenWhenThenScenario(CreateOrderDecider())
var orderId = OrderId.random()
scenario
.given()
.when_(CreateOrder(orderId))
.then_(OrderCreated(orderId))
}
@Test
fun `Create an Order twice`() {
val scenario = GivenWhenThenScenario(CreateOrderDecider())
var orderId = OrderId.random()
scenario
.given(OrderCreated(orderId))
.when_(CreateOrder(orderId))
.thenExpectNoEvent()
}
@Test
fun `Accept an Order`() {
val scenario = GivenWhenThenScenario(AcceptOrderDecider())
var orderId = OrderId.random()
scenario
.given(OrderCreated(orderId))
.when_(AcceptOrder(orderId))
.then_(OrderAccepted(orderId))
}
@Test
fun `Accept an Order twice`() {
val scenario = GivenWhenThenScenario(AcceptOrderDecider())
var orderId = OrderId.random()
scenario
.given(
OrderCreated(orderId),
OrderAccepted(orderId)
)
.when_(AcceptOrder(orderId))
.thenExpectNoEvent()
}
@Test
fun `Accept an Order that has not been created`() {
val scenario = GivenWhenThenScenario(AcceptOrderDecider())
var orderId = OrderId.random()
scenario
.given()
.when_(AcceptOrder(orderId))
.thenFailsWithExceptionType(RuntimeException::class)
}
@Test
fun `Ship an Order`() {
val scenario = GivenWhenThenScenario(ShipOrderDecider())
var orderId = OrderId.random()
scenario
.given(
OrderCreated(orderId),
OrderAccepted(orderId)
)
.when_(ShipOrder(orderId))
.then_(OrderShipped(orderId))
}
@Test
fun `try to Ship an Order that hasn't been Accepted`() {
val scenario = GivenWhenThenScenario(ShipOrderDecider())
var orderId = OrderId.random()
scenario
.given(
OrderCreated(orderId),
)
.when_(ShipOrder(orderId))
.thenFailsWithException(RuntimeException("Cannot ship an order that hasn't been accepted"))
}
}
class CreateOrderDecider : Decider<CreateOrder, OrderEvent> {
override fun handle(cmd: CreateOrder, events: List<OrderEvent>): OrderEvent? {
if (events.isEmpty()) {
return OrderCreated(cmd.id)
}
return null
}
override fun canHandle(cmd: Any): Boolean {
return cmd is CreateOrder
}
}
class AcceptOrderDecider : Decider<AcceptOrder, OrderEvent> {
override fun handle(cmd: AcceptOrder, events: List<OrderEvent>): OrderEvent? {
if (events.isEmpty()) {
throw RuntimeException("Cannot accept an order that hasn't been created")
}
if (events.any { it is OrderAccepted }) {
// Already accepted - idempotent handling
return null
}
return OrderAccepted(cmd.id)
}
override fun canHandle(cmd: Any): Boolean {
return cmd is AcceptOrder
}
}
class ShipOrderDecider : Decider<ShipOrder, OrderEvent> {
override fun handle(cmd: ShipOrder, events: List<OrderEvent>): OrderEvent? {
if (events.isEmpty()) {
throw RuntimeException("Cannot accept an order that hasn't been created")
}
if (events.any { it is OrderShipped}) {
// Already shipped - idempotent handling
return null
}
if (!events.any { it is OrderAccepted }) {
throw RuntimeException("Cannot ship an order that hasn't been accepted")
}
return OrderShipped(cmd.id)
}
override fun canHandle(cmd: Any): Boolean {
return cmd is ShipOrder
}
}
interface OrderCommand {
val id: OrderId
}
interface OrderEvent {
val id: OrderId
}
data class CreateOrder(override val id: OrderId) : OrderCommand
data class AcceptOrder(override val id: OrderId) : OrderCommand
data class ShipOrder(override val id: OrderId) : OrderCommand
data class OrderCreated(override val id: OrderId) : OrderEvent
data class OrderAccepted(override val id: OrderId) : OrderEvent
data class OrderShipped(override val id: OrderId) : OrderEvent
@JvmInline
value class OrderId(override val value: String) : StringValueType<OrderId> {
companion object {
fun random(): OrderId {
return OrderId(RandomIdGenerator.generate())
}
fun of(id: String): OrderId {
return OrderId(id)
}
}
} | 0 | Java | 2 | 3 | 6b428edc1dfd406b0ae55c7e066669d507ecd2a4 | 5,652 | essentials-project | Apache License 2.0 |
LudoCompose/app/src/main/java/hu/bme/aut/android/ludocompose/session/controller/GameController.kt | Kis-Benjamin | 693,261,151 | false | {"Kotlin": 358575, "Shell": 2693, "Dockerfile": 2134} | /*
* Copyright © 2023 <NAME>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package hu.bme.aut.android.ludocompose.session.controller
import hu.bme.aut.android.ludocompose.session.model.BoardDTO
interface GameController {
val hasActive: Boolean
val id: Long
suspend fun load(id: Long)
suspend fun unLoad()
suspend fun getBoard(): BoardDTO
suspend fun select()
suspend fun step()
} | 0 | Kotlin | 0 | 0 | 731f304280ad30068c0149fdd04a94213ebea2e1 | 933 | Ludo | Apache License 2.0 |
Lecture 5/githubclient/app/src/main/java/com/avast/android/lecture/github/login/LoginFragment.kt | avast | 45,212,866 | false | null | package com.avast.android.lecture.github.login
import android.content.Intent
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.Fragment
import androidx.fragment.app.viewModels
import com.avast.android.lecture.github.databinding.FragmentLoginBinding
import com.avast.android.lecture.github.user.UserActivity
import com.avast.android.lecture.github.user.UserFragment
/**
* Login to our application. Offers user to enter username.
*/
class LoginFragment: Fragment() {
private var _binding: FragmentLoginBinding? = null
private val binding: FragmentLoginBinding
get() = _binding!!
private val loginViewModel by viewModels<LoginViewModel>()
/**
* Inflate view hierarchy.
*/
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
_binding = FragmentLoginBinding.inflate(inflater, container, false)
return binding.root
}
/**
* Setup view actions.
*/
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
loginViewModel.username.observe(viewLifecycleOwner) {
binding.txtUsername.editText?.setText(it)
}
binding.btnSearch.setOnClickListener {
val login = binding.txtUsername.editText?.text.toString()
loginViewModel.storeUsername(login)
val intent = Intent(activity, UserActivity::class.java)
intent.putExtra(UserFragment.KEY_USERNAME, login)
startActivity(intent)
}
loginViewModel.loadUsername()
}
override fun onDestroyView() {
super.onDestroyView()
_binding = null
}
} | 0 | Kotlin | 8 | 24 | edafe7bf572df354cb0de98da1abdb14268f939a | 1,759 | android-lectures | Apache License 2.0 |
common/ux/src/main/kotlin/com/adewan/mystuff/common/ux/ThemedContainer.kt | abhishekdewan101 | 564,174,144 | false | null | package com.adewan.mystuff.common.ux
import androidx.compose.foundation.isSystemInDarkTheme
import androidx.compose.material3.MaterialTheme
import androidx.compose.runtime.Composable
import androidx.compose.runtime.SideEffect
import androidx.compose.ui.graphics.Color
import com.google.accompanist.systemuicontroller.rememberSystemUiController
@Composable
fun ThemedContainer(
statusBarColor: Color = MaterialTheme.colorScheme.background,
navigationBarColor: Color = MaterialTheme.colorScheme.background,
content: @Composable () -> Unit
) {
val uiController = rememberSystemUiController()
val useDarkIcons = !isSystemInDarkTheme()
SideEffect {
uiController.setStatusBarColor(color = statusBarColor, darkIcons = useDarkIcons)
uiController.setNavigationBarColor(
color = navigationBarColor,
darkIcons = useDarkIcons
)
}
content()
}
| 2 | Kotlin | 0 | 0 | a8cc7eccd83f8aa23a0225bae79952c7298cc80f | 913 | My-Lists | MIT License |
app/src/main/java/br/com/rafael/eletriccarapp/ui/CalcularCustosActivity.kt | RafaelFdSouza | 574,764,173 | false | null | package br.com.rafael.eletriccarapp.ui
import android.os.Bundle
import androidx.appcompat.app.AppCompatActivity
import br.com.rafael.eletriccarapp.databinding.ActivityCalcularCustosBinding
class CalcularCustosActivity : AppCompatActivity() {
private lateinit var binding: ActivityCalcularCustosBinding
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = ActivityCalcularCustosBinding.inflate(layoutInflater)
setContentView(binding.root)
binding.btnCalcular.setOnClickListener {
binding.tvResultado.text = calculoCusto().toString()
}
binding.imvClose.setOnClickListener {
finish()
}
}
fun calculoCusto(): Float {
val precoKwh = binding.etValorKwh.text.toString().toFloat()
val kmPercorrido = binding.etDistanciaViagem.text.toString().toFloat()
val kmPorKwh = binding.tvKmPorKwh.text.toString().toFloat()
return ((kmPercorrido / kmPorKwh) * precoKwh)
}
} | 0 | Kotlin | 0 | 0 | 2e3583d2ff117e0e56bac7fbe5ddb4de28fac817 | 1,035 | AppEletricCars | MIT License |
app/src/main/java/com/example/nba/presentation/team_detail_screen/TeamDetailScreen.kt | EvaldasSo | 639,254,729 | false | null | package com.example.nba.presentation.team_detail_screen
import android.widget.Toast
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.IntrinsicSize
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxHeight
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.KeyboardArrowLeft
import androidx.compose.material3.CircularProgressIndicator
import androidx.compose.material3.Divider
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.hilt.navigation.compose.hiltViewModel
import androidx.lifecycle.compose.collectAsStateWithLifecycle
import androidx.paging.LoadState
import androidx.paging.compose.LazyPagingItems
import androidx.paging.compose.collectAsLazyPagingItems
import androidx.paging.compose.items
import com.example.nba.R
import com.example.nba.domain.model.GameMatch
import com.example.nba.presentation.home_screen.components.NbaIcon
@Composable
fun TeamDetailRoute(
modifier: Modifier = Modifier,
onBackClick: () -> Unit,
viewModel: TeamDetailViewModel = hiltViewModel(),
) {
val gameMatches = viewModel.gameMatchPagingFlow.collectAsLazyPagingItems()
val teamDetailUiState by viewModel.teamDetailUiState.collectAsStateWithLifecycle()
TeamDetailScreen(
modifier = modifier,
onBackClick = onBackClick,
gameMatches = gameMatches,
teamDetailUiState = teamDetailUiState,
)
}
@Composable
fun BackIconAndText(
modifier: Modifier = Modifier,
title: String,
onBackClick: () -> Unit = {}
) {
Row(
modifier = modifier
.fillMaxWidth(1f),
verticalAlignment = Alignment.CenterVertically,
) {
Row(
modifier = Modifier
.height(IntrinsicSize.Min)
.clickable { onBackClick() },
verticalAlignment = Alignment.CenterVertically,
) {
NbaIcon(
modifier = Modifier
.fillMaxHeight(1f),
imageVector = Icons.Filled.KeyboardArrowLeft,
tint = Color(0, 0, 0, 255),
imageDescription = "Back to home"
)
Text(
text = "Home",
textAlign = TextAlign.Center
)
}
Text(
text = title,
fontSize = 24.sp,
textAlign = TextAlign.Center,
modifier = Modifier.fillMaxWidth(0.8f),
)
}
}
@Composable
fun TeamDetailScreen(
modifier: Modifier = Modifier,
onBackClick: () -> Unit,
gameMatches: LazyPagingItems<GameMatch>,
teamDetailUiState: TeamDetailUiState,
) {
val context = LocalContext.current
LaunchedEffect(key1 = gameMatches.loadState) {
if (gameMatches.loadState.refresh is LoadState.Error) {
Toast.makeText(
context,
"Error: " + (gameMatches.loadState.refresh as LoadState.Error).error.message,
Toast.LENGTH_LONG
).show()
}
}
Column(
modifier = modifier
.fillMaxSize()
.padding(16.dp),
) {
Row {
BackIconAndText(
title = when (teamDetailUiState) {
is TeamDetailUiState.Success -> teamDetailUiState.team.fullName
is TeamDetailUiState.Loading -> ""
},
onBackClick = onBackClick
)
}
Spacer(modifier = Modifier.height(40.dp))
if (gameMatches.loadState.refresh is LoadState.Loading) {
Box(
modifier = Modifier.fillMaxSize()
) {
CircularProgressIndicator(
modifier = Modifier.align(Alignment.Center)
)
}
} else {
DetailBody(gameMatches = gameMatches)
}
}
}
@Composable
fun DetailBody(
gameMatches: LazyPagingItems<GameMatch>,
) {
Column(
modifier = Modifier.fillMaxHeight(1f)
) {
GameRowInfo(
modifier = Modifier
.fillMaxWidth()
.height(IntrinsicSize.Min),
columNames = listOf(
stringResource(R.string.home_name),
stringResource(R.string.home_score),
stringResource(R.string.visitor_name),
stringResource(R.string.visitor_score),
)
)
Divider(Modifier.padding(8.dp))
LazyColumn(
modifier = Modifier
.fillMaxSize(),
verticalArrangement = Arrangement.spacedBy(16.dp),
horizontalAlignment = Alignment.CenterHorizontally
) {
items(
items = gameMatches,
key = { it.id }
) { gameMatch ->
if (gameMatch != null) {
GameRowInfo(
modifier = Modifier.fillMaxWidth(), columNames = listOf(
gameMatch.homeName,
gameMatch.homeScore.toString(),
gameMatch.visitorName,
gameMatch.homeScore.toString()
)
)
}
}
item {
if (gameMatches.loadState.append is LoadState.Loading) {
CircularProgressIndicator()
}
}
}
}
}
@Composable
fun GameRowInfo(
modifier: Modifier = Modifier,
columNames: List<String>,
) {
Row(
modifier = modifier,
verticalAlignment = Alignment.CenterVertically,
horizontalArrangement = Arrangement.SpaceEvenly,
) {
columNames.forEach {
Text(
text = it,
modifier = Modifier.weight(1f),
textAlign = TextAlign.Center
)
}
}
}
| 0 | Kotlin | 0 | 0 | 387c427548a9bc3d92f906f2406019e1bd4d4310 | 6,849 | NBA-Dashboard | Apache License 2.0 |
app/src/main/java/edu/app/productivity/theme/Theme.kt | dee-tree | 707,883,904 | false | {"Kotlin": 188741} | package edu.app.productivity.theme
import android.app.Activity
import androidx.compose.foundation.isSystemInDarkTheme
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.darkColorScheme
import androidx.compose.material3.lightColorScheme
import androidx.compose.runtime.Composable
import androidx.compose.runtime.SideEffect
import androidx.compose.ui.graphics.toArgb
import androidx.compose.ui.platform.LocalView
import androidx.core.view.WindowCompat
private val DarkColorScheme = darkColorScheme(
primary = MossGreen,
onPrimary = CornSilk,
secondary = Buff,
onSecondary = CornSilk,
// background = DarkGray,
background = CafeNoir,
onBackground = CornSilk,
// surface = DarkGray,
surface = CafeNoir,
onSurface = PapayaWhip,
surfaceVariant = Russet,
onSurfaceVariant = CornSilk,
outline = Buff,
errorContainer = CaputMortuum,
onErrorContainer = CornSilk,
surfaceTint = TeaGreen,
primaryContainer = Russet,
onPrimaryContainer = CornSilk
)
private val LightColorScheme = lightColorScheme(
primary = MossGreen,
onPrimary = CornSilk,
secondary = Buff,
onSecondary = CornSilk,
background = PapayaWhip,
onBackground = Russet,
surface = PapayaWhip,
onSurface = Russet,
surfaceVariant = Beige,
onSurfaceVariant = Russet,
outline = Buff,
errorContainer = Cordovan,
onErrorContainer = CornSilk,
surfaceTint = TeaGreen,
primaryContainer = Buff,
onPrimaryContainer = PapayaWhip
)
@Composable
fun ProductivityTheme(
darkTheme: Boolean = isSystemInDarkTheme(),
content: @Composable () -> Unit
) {
val colorScheme = when {
darkTheme -> DarkColorScheme
else -> LightColorScheme
}
val view = LocalView.current
if (!view.isInEditMode) {
SideEffect {
val window = (view.context as Activity).window
window.statusBarColor = colorScheme.primary.toArgb()
WindowCompat.getInsetsController(window, view).isAppearanceLightStatusBars = darkTheme
}
}
MaterialTheme(
colorScheme = colorScheme,
typography = Typography,
content = content
)
}
| 0 | Kotlin | 1 | 0 | 2f80b0633a7da547824323284ccbd65627fea0ad | 2,208 | productivity | Apache License 2.0 |
app/src/main/java/com/varunest/listpullrequests/data/network/model/User.kt | Artnoc1 | 282,994,443 | true | {"Kotlin": 29840} | package com.varunest.listpullrequests.data.network.model
import com.google.gson.annotations.SerializedName
data class User(
@SerializedName("login") val name: String,
@SerializedName("avatar_url") val avatarUrl: String
) | 0 | null | 0 | 0 | 2c5632ecff691b4b2a9ab1043773d060fd03bf1c | 230 | ListPullRequests | Apache License 2.0 |
kotlin-electron/src/jsMain/generated/electron/core/SafeStorageGetSelectedStorageBackendResult.kt | JetBrains | 93,250,841 | false | null | // Generated by Karakum - do not modify it manually!
package electron.core
@Suppress("NESTED_CLASS_IN_EXTERNAL_INTERFACE")
@seskar.js.JsVirtual
sealed external interface SafeStorageGetSelectedStorageBackendResult {
companion object {
@seskar.js.JsValue("basic_text")
val basicText: SafeStorageGetSelectedStorageBackendResult
@seskar.js.JsValue("gnome_libsecret")
val gnomeLibsecret: SafeStorageGetSelectedStorageBackendResult
@seskar.js.JsValue("kwallet")
val kwallet: SafeStorageGetSelectedStorageBackendResult
@seskar.js.JsValue("kwallet5")
val kwallet5: SafeStorageGetSelectedStorageBackendResult
@seskar.js.JsValue("kwallet6")
val kwallet6: SafeStorageGetSelectedStorageBackendResult
@seskar.js.JsValue("unknown")
val unknown: SafeStorageGetSelectedStorageBackendResult
}
}
| 40 | null | 165 | 1,347 | 997ed3902482883db4a9657585426f6ca167d556 | 890 | kotlin-wrappers | Apache License 2.0 |
java/com/mu/jan/problems/threading/WorkManager.kt | Mukuljangir372 | 359,095,214 | false | null | package com.mu.jan.problems.component
import android.content.Context
import androidx.lifecycle.LifecycleOwner
import androidx.lifecycle.Observer
import androidx.work.*
import java.util.concurrent.TimeUnit
/**
* Now, IntentService has been deprecated
* Use WorkManger or jobIntentService
*
* WorkManager - Used for scheduling asynchronous task that expected to run
* even if app not running.
*
* To use WorkManager, we need,
* 1. YourWorker class that extends Worker class.
* 2. WorkRequest - it define how and when task or work will run based on constraints.
* - it can be OneTimeWorkRequest or PeriodicWorkTimeRequest.
*
* 3. At the end, Schedule task with WorkManager.
*/
class UploadWorker(appContext: Context, workerParameters: WorkerParameters)
: Worker(appContext,workerParameters){
override fun doWork(): Result {
return Result.success()
}
}
class Basic{
//work request -
private var myUploadWorkRequest = OneTimeWorkRequestBuilder<UploadWorker>().build()
private fun requestWork(mContext: Context){
//This is How you schedule work with WorkManger
WorkManager.getInstance(mContext).enqueue(myUploadWorkRequest)
}
}
class Full{
/**
* Work request constraints,
* for instance,
* .setRequireCharging(true) - it means, work request will
* enqueue only if device will charging.
* .setRequireNetworkType(NetworkType.CONNECTED) - it means, work request will
* enqueue only if network connected.
* ...
*/
private var myConstraints = Constraints.Builder()
.setRequiresCharging(true)
.setRequiredNetworkType(NetworkType.CONNECTED)
.setRequiresBatteryNotLow(true)
.setRequiresStorageNotLow(true)
.build()
/**
* Here, OneTimeWorkRequestBuilder will do work once
*/
private var myUploadWorkRequest = OneTimeWorkRequestBuilder<UploadWorker>()
.setConstraints(myConstraints)
.build()
/**
* Here, PeriodicWorkRequestBuilder will repeat
* same work every 1 hour.
*/
private var myUploadWorkRequest1 = PeriodicWorkRequestBuilder<UploadWorker>(1,TimeUnit.HOURS)
.setConstraints(myConstraints)
.build()
/**
* Request work
*/
private fun requestWork(mContext: Context){
WorkManager.getInstance(mContext).enqueue(myUploadWorkRequest)
}
/**
* Get info about requested work
*/
private fun getInfoRequestedWork(mContext: Context){
//Don't use like this, Use you activity lifeCycleOwner
var lifeCycleOwner : LifecycleOwner? = null
WorkManager.getInstance(mContext)
.getWorkInfoByIdLiveData(myUploadWorkRequest.id)
.observe(lifeCycleOwner!!, Observer {
//state
if(it.state == WorkInfo.State.SUCCEEDED){
//success
}
})
}
/**
* Chaining work with WorkManager
* we can do multiple tasks with chaining work
* 1. Multiple tasks in series
* 2. Multiple tasks in parallel
*/
private var workRequest1 = OneTimeWorkRequestBuilder<UploadWorker>()
.build()
private var workRequest2 = OneTimeWorkRequestBuilder<UploadWorker>().build()
private fun requestMultipleWork(mContext: Context){
//multiple works in series
WorkManager.getInstance(mContext).beginWith(workRequest1)
.then(workRequest2).enqueue()
}
private fun requestMultipleWork1(mContext: Context){
//multiple works in parallel
WorkManager.getInstance(mContext)
.beginWith(listOf(workRequest1,workRequest2))
.enqueue()
}
/**
* cancel work
*/
private fun cancelWork(mContext: Context){
//for cancel all work
WorkManager.getInstance(mContext).cancelAllWork()
//for cancel work by id
WorkManager.getInstance(mContext).cancelWorkById(workRequest1.id)
}
/**
* input data - sending data to Worker class
*/
var data = Data.Builder()
.putString("key","value")
.build()
var myRequest = OneTimeWorkRequestBuilder<UploadWorker>()
.setInputData(data)
.build()
inner class MyWorker(appContext: Context,params: WorkerParameters)
: Worker(appContext,params){
override fun doWork(): Result {
//get name
var value = inputData.getString("key")
//Or you can can output data
var data = Data.Builder()
.putString("key","value")
.build()
return Result.success(data)
}
}
/**
* Output data - receiving data from worker class
*/
private fun receive(mContext: Context){
//Don't use like this, Use you activity lifeCycleOwner
var lifeCycleOwner : LifecycleOwner? = null
WorkManager.getInstance(mContext)
.getWorkInfoByIdLiveData(myRequest.id)
.observe(lifeCycleOwner!!, Observer {
//state
if(it.state == WorkInfo.State.SUCCEEDED){
//success
//get Output data
val data = it.outputData
}
})
}
}
| 0 | Kotlin | 0 | 1 | bb15517c09041757d859126dc4f39d3409fdd35d | 5,419 | Android-Kotlin-Interview | Apache License 2.0 |
app/src/main/java/com/thorhelgen/rickandmortyinfoapp/presentation/list/ListItem.kt | ThorHelgen | 504,479,815 | false | null | package com.thorhelgen.rickandmortyinfoapp.presentation.list
data class ListItem (
val id: Int,
val name: String,
val firstAdditionalLine: String,
val secondAdditionalLine: String
) {
override fun equals(other: Any?): Boolean =
other is ListItem &&
other.name == name &&
other.firstAdditionalLine == firstAdditionalLine &&
other.secondAdditionalLine == secondAdditionalLine
} | 0 | Kotlin | 0 | 0 | efab3d11784b5a56f60a7efb7a13a022b6333ea3 | 428 | RickAndMortyInfoApp | MIT License |
order-starter/src/main/kotlin/com/labijie/application/order/component/SpringBeanOrderAdapterLocator.kt | hongque-pro | 309,874,586 | false | {"Kotlin": 1051745, "Java": 72766} | package com.labijie.application.order.component
import com.labijie.application.order.exception.OrderAdapterNotFoundException
import com.labijie.application.order.exception.OrderException
import com.labijie.application.payment.configuration.PaymentProperties
import org.springframework.beans.factory.ObjectProvider
import java.util.regex.Pattern
import java.util.stream.Collectors
import kotlin.reflect.KClass
class SpringBeanOrderAdapterLocator(orderAdapterProvider: ObjectProvider<IOrderAdapter<*>>) : IOrderAdapterLocator {
private val orderTypeNamePattern = Pattern.compile("^${PaymentProperties.DEFAULT_STATE_RULE_REGEX}\$")
private val typedOrderAdapters: Map<KClass<*>, IOrderAdapter<*>> = this.buildTypedAdapterMap(orderAdapterProvider)
private val namedOrderAdapters: Map<String, IOrderAdapter<*>> = this.buildNamedAdapterMap(orderAdapterProvider)
fun buildTypedAdapterMap(orderAdapterProvider: ObjectProvider<IOrderAdapter<*>>): Map<KClass<*>, IOrderAdapter<*>> {
val list = orderAdapterProvider.stream().collect(Collectors.toList())
val adapters = list.map {
it.orderType to it
}.toList()
return mapOf(*adapters.toTypedArray())
}
private fun buildNamedAdapterMap(orderAdapterProvider: ObjectProvider<IOrderAdapter<*>>): Map<String, IOrderAdapter<*>> {
val list = orderAdapterProvider.stream().collect(Collectors.toList())
val adapters = list.map {
if(!orderTypeNamePattern.matcher(it.orderTypeName).matches()){
throw OrderException("Only lowercase letters, numbers, - and _ are allowed in IOrderAdapter.orderTypeName .")
}
it.orderTypeName to it
}.toList()
return mapOf(*adapters.toTypedArray())
}
@Suppress("UNCHECKED_CAST")
override fun <T:Any> findAdapter(orderType: KClass<T>): IOrderAdapter<T> {
val adapter = typedOrderAdapters[orderType] ?: throw OrderAdapterNotFoundException(orderType)
return adapter as IOrderAdapter<T>
}
override fun findAdapter(orderType: String): IOrderAdapter<*> {
return namedOrderAdapters[orderType] ?: throw OrderAdapterNotFoundException(orderType)
}
} | 0 | Kotlin | 0 | 8 | 9e2b1f76bbb239ae9029bd27cda2d17f96b13326 | 2,208 | application-framework | Apache License 2.0 |
src/day/_8/Day08.kt | Tchorzyksen37 | 572,924,533 | false | null | package day._8
import java.io.File
fun main() {
fun part1(input: List<String>): Int {
var treeCount = 2 * (input.size - 2) + input[0].length * 2
for ((indexInput, str) in input.withIndex()) {
if (indexInput == 0 || indexInput == input.size - 1) continue
for (indexStr in 1 until str.length - 1) {
// Check left
val leftMax = str.substring(0, indexStr).max()
if (leftMax < str[indexStr]) {
treeCount++
continue
}
// Check right
val rightMax = str.substring(indexStr + 1).max()
if (rightMax < str[indexStr]) {
treeCount++
continue
}
val verticalLine = input.map { it[indexStr] }.joinToString("")
// Check top
val topMax = verticalLine.substring(0, indexInput).max()
if (topMax < str[indexStr]) {
treeCount++
continue
}
// Check bottom
val botMax = verticalLine.substring(indexInput + 1).max()
if (botMax < str[indexStr]) {
treeCount++
continue
}
}
}
return treeCount
}
fun part2(input: List<String>): Int {
var maxTreeScenicScore = 0
for ((indexInput, str) in input.withIndex()) {
if (indexInput == 0 || indexInput == input.size - 1) continue
for (indexStr in 1 until str.length - 1) {
// Check left
val leftSubstring = str.substring(0, indexStr).reversed()
var treeBlockingViewLeftRange = 0
for (element in leftSubstring) {
if (str[indexStr] > element) {
treeBlockingViewLeftRange++
continue
} else if (str[indexStr] <= element) {
treeBlockingViewLeftRange++
}
break
}
// Check right
val rightSubstring = str.substring(indexStr + 1)
var treeBlockingViewRightRange = 0
for (element in rightSubstring) {
if (str[indexStr] > element) {
treeBlockingViewRightRange++
continue
} else if (str[indexStr] <= element) {
treeBlockingViewRightRange++
}
break
}
val verticalLine = input.map { it[indexStr] }.joinToString("")
// Check top
val topSubstring = verticalLine.substring(0, indexInput).reversed()
var treeBlockingViewTopRange = 0
for (element in topSubstring) {
if (str[indexStr] > element) {
treeBlockingViewTopRange++
continue
} else if (str[indexStr] <= element) {
treeBlockingViewTopRange++
}
break
}
// Check bottom
val botSubstring = verticalLine.substring(indexInput + 1)
var treeBlockingViewBotRange = 0
for (element in botSubstring) {
if (str[indexStr] > element) {
treeBlockingViewBotRange++
continue
} else if (str[indexStr] <= element) {
treeBlockingViewBotRange++
}
break
}
val currentTreeScenicScore =
treeBlockingViewLeftRange * treeBlockingViewRightRange * treeBlockingViewTopRange * treeBlockingViewBotRange
if (maxTreeScenicScore < currentTreeScenicScore) maxTreeScenicScore = currentTreeScenicScore
}
}
return maxTreeScenicScore
}
val testInput = File("src/day", "_8/Day08_test.txt").readLines()
check(part1(testInput) == 21)
check(part2(testInput) == 8)
val input = File("src/day", "_8/Day08.txt").readLines()
println(part1(input))
println(part2(input))
} | 0 | Kotlin | 0 | 0 | 9ce2d06c12cdf4c4751117ff0947bff7418bd2fe | 3,198 | advent-of-code-2022 | Apache License 2.0 |
src/main/java/me/shadowalzazel/mcodyssey/recipe_creators/merchant/Sales.kt | ShadowAlzazel | 511,383,377 | false | null | package me.shadowalzazel.mcodyssey.recipe_creators.merchant
import me.shadowalzazel.mcodyssey.enchantments.OdysseyEnchantments
import me.shadowalzazel.mcodyssey.items.Runic
import me.shadowalzazel.mcodyssey.items.Runic.createEnchantedBook
import org.bukkit.Material
import org.bukkit.inventory.ItemStack
import org.bukkit.inventory.MerchantRecipe
object Sales {
fun createLowTierTomeTrade(): MerchantRecipe {
val tomes = listOf(
Runic.TOME_OF_EMBRACE, Runic.TOME_OF_DISCHARGE, Runic.TOME_OF_PROMOTION, Runic.TOME_OF_BANISHMENT, Runic.TOME_OF_HARMONY)
val someTrade = MerchantRecipe(tomes.random().createItemStack(1), 1, (2..5).random(), true).apply {
setIgnoreDiscounts(true)
addIngredient(ItemStack(Material.EMERALD, (23..32).random()))
}
return someTrade
}
fun createLowTierGildedEnchantTrade(): MerchantRecipe {
val enchants = listOf(OdysseyEnchantments.EXPLODING, OdysseyEnchantments.FREEZING_ASPECT,
OdysseyEnchantments.BANE_OF_THE_ILLAGER, OdysseyEnchantments.BACKSTABBER, OdysseyEnchantments.BURST_BARRAGE)
val someTrade = MerchantRecipe(Runic.GILDED_BOOK.createEnchantedBook(enchants.random(), 1), 1, 1, true).apply {
setIgnoreDiscounts(true)
addIngredient(ItemStack(Material.EMERALD, (26..36).random()))
}
return someTrade
}
fun createArcaneBookTrade(): MerchantRecipe {
val book = Runic.ARCANE_BOOK.createItemStack(1)
val someTrade = MerchantRecipe(book, 1, (5..9).random(), true).apply {
setIgnoreDiscounts(true)
addIngredient(ItemStack(Material.EMERALD, (13..21).random()))
}
return someTrade
}
} | 0 | Kotlin | 0 | 3 | c3b46fa8589efdae68224d423af3b8b33a7fc26a | 1,734 | MinecraftOdyssey | MIT License |
app/src/main/java/com/example/weatherapp/feature/weatherforecast/model/SunriseInfo.kt | codeKrishnan | 517,036,927 | false | {"Kotlin": 122530} | package com.example.weatherapp.feature.weatherforecast.model
data class SunriseInfo(
val sunriseTime: String,
val sunsetTime: String,
) | 0 | Kotlin | 0 | 0 | e1966bcd962b40fd52d231fc3d66e6099875bccc | 144 | weather-app | Apache License 2.0 |
src/main/kotlin/com/nylas/models/ReminderOverride.kt | nylas | 202,446,537 | false | {"Kotlin": 531539} | package com.nylas.models
import com.squareup.moshi.Json
/**
* Class representing the reminder details for an event.
*/
data class ReminderOverride(
/**
* The number of minutes before the event start time when a user wants a reminder for this event.
* Reminder minutes are in the following format: "[20]".
*/
@Json(name = "reminder_minutes")
val reminderMinutes: Int? = null,
/**
* Method to remind the user about the event. (Google only).
*/
@Json(name = "reminder_method")
val reminderMethod: ReminderMethod? = null,
)
| 4 | Kotlin | 12 | 31 | d5fb9f80193301bb260e317238a056c0dde28710 | 551 | nylas-java | MIT License |
bitlap-core/src/main/kotlin/org/bitlap/core/sql/udf/UDF2.kt | bitlap | 313,535,150 | false | {"Kotlin": 365002, "Scala": 282290, "TypeScript": 8144, "Shell": 8133, "FreeMarker": 6080, "JavaScript": 836, "Java": 670, "Dockerfile": 589, "Less": 159} | /* Copyright (c) 2023 bitlap.org */
package org.bitlap.core.sql.udf
/**
* A generic interface for defining user-defined functions.
*
* [V1]: input value type
* [V2]: input value type
* [R]: result type
*/
interface UDF2<V1, V2, R> : UDF {
/**
* eval with two inputs.
*/
fun eval(input1: V1, input2: V2): R
}
| 23 | Kotlin | 2 | 22 | 328585f917439b80bc7d1b89b21972b6c8ee9e7f | 334 | bitlap | Apache License 2.0 |
bitlap-core/src/main/kotlin/org/bitlap/core/sql/udf/UDF2.kt | bitlap | 313,535,150 | false | {"Kotlin": 365002, "Scala": 282290, "TypeScript": 8144, "Shell": 8133, "FreeMarker": 6080, "JavaScript": 836, "Java": 670, "Dockerfile": 589, "Less": 159} | /* Copyright (c) 2023 bitlap.org */
package org.bitlap.core.sql.udf
/**
* A generic interface for defining user-defined functions.
*
* [V1]: input value type
* [V2]: input value type
* [R]: result type
*/
interface UDF2<V1, V2, R> : UDF {
/**
* eval with two inputs.
*/
fun eval(input1: V1, input2: V2): R
}
| 23 | Kotlin | 2 | 22 | 328585f917439b80bc7d1b89b21972b6c8ee9e7f | 334 | bitlap | Apache License 2.0 |
kollect-core/src/main/kotlin/kollect/DataSource.kt | 47degrees | 118,812,251 | false | null | package kollect
import arrow.Kind
import arrow.core.None
import arrow.core.Option
import arrow.core.Some
import arrow.core.Tuple2
import arrow.data.NonEmptyList
import arrow.effects.typeclasses.Concurrent
sealed class BatchExecution
object Sequentially : BatchExecution()
object InParallel : BatchExecution()
/**
* A `DataSource` is the recipe for fetching a certain identity `I`, which yields results of type `A`.
*/
interface DataSource<I, A> {
/**
* Name given to the data source. Defaults to "KollectDataSource:${this.javaClass.simpleName}".
*/
fun name(): String = "KollectDataSource:${this.javaClass.simpleName}"
/**
* Fetches a value from the source of data by its given Identity. Requires an instance of Concurrent.
*
* @param id for the fetched item I.
* @return IO<Option<A>> since this operation represents an IO computation that returns an optional result. In
* case the result is not found, it'll return None.
*/
fun <F> fetch(CF: Concurrent<F>, id: I): Kind<F, Option<A>>
/**
* Fetch many identities, returning a mapping from identities to results. If an
* identity wasn't found, it won't appear in the keys.
*/
fun <F> batch(CF: Concurrent<F>, ids: NonEmptyList<I>): Kind<F, Map<I, A>> = CF.binding {
val tuples = KollectExecution.parallel(
CF,
ids.map { id -> fetch(CF, id).map { v -> Tuple2(id, v) } }
).bind()
val results: List<Tuple2<I, A>> = tuples.collect(
f = { Tuple2(it.a, (it.b as Some<A>).t) },
filter = { it.b is Some<A> }
)
results.associateBy({ it.a }, { it.b })
}
fun maxBatchSize(): Option<Int> = None
fun batchExecution(): BatchExecution = InParallel
}
| 8 | Kotlin | 5 | 33 | a72ee95996fc8537406dbc010afe8fd82984b14b | 1,790 | kollect | Apache License 2.0 |
disciple/src/main/java/com/monster/disciple/transformer/AbsErrorCheckTransformer.kt | radishwu | 129,616,187 | false | null | package com.monster.disciple.transformer
import android.content.Context
import android.text.TextUtils
import com.monster.disciple.util.CacheBuilder
import com.monster.disciple.response.BaseResponse
import com.monster.disciple.util.getCacheFunction
import com.monster.disciple.util.newInstanceFunction
import com.monster.disciple.util.saveCacheFunction
import io.reactivex.Observable
import io.reactivex.ObservableSource
import io.reactivex.ObservableTransformer
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.schedulers.Schedulers
import retrofit2.Response
import java.lang.ref.WeakReference
abstract class AbsErrorCheckTransformer<T : Response<R>, R : BaseResponse<*>>(context: Context?) : ObservableTransformer<T, R>, IErrorCheckTransformer {
private var mContextRef: WeakReference<Context>? = WeakReference<Context>(context)
private var mCacheBuilder: CacheBuilder? = null
constructor(context: Context?, cacheBuilder: CacheBuilder?) : this(context) {
mCacheBuilder = cacheBuilder
}
override fun apply(upstream: Observable<T>): ObservableSource<R> {
return if (mCacheBuilder == null || TextUtils.isEmpty(mCacheBuilder?.cacheKey)) {
upstream
.map(newInstanceFunction<T,R>(this))
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
} else {
upstream
.map(newInstanceFunction<T,R>(this))
.map(saveCacheFunction<R>(mContextRef?.get(), mCacheBuilder?.cacheKey))
.startWith(
Observable
.just<String>(mCacheBuilder?.cacheKey)
.map(getCacheFunction<R>(mContextRef?.get(), mCacheBuilder?.type))
.filter { rCacheEntity -> !rCacheEntity.isNil() }
.map { rCacheEntity -> rCacheEntity.response })
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
}
}
}
| 0 | Kotlin | 1 | 3 | ce50e3f26d04131791a91cb24b764c773d7039ac | 2,135 | disciple | Apache License 2.0 |
app/src/main/java/com/serma/dionysus/common/ui/CommonPaging.kt | asuka1211 | 350,113,092 | false | null | package com.serma.dionysus.common.ui
import androidx.compose.foundation.lazy.LazyItemScope
import androidx.compose.foundation.lazy.LazyListScope
import androidx.compose.foundation.lazy.itemsIndexed
import androidx.compose.runtime.Composable
inline fun <T> LazyListScope.pagingList(
item: PagingItems<T>,
loading: Boolean,
canLoading: Boolean,
crossinline loadMore: () -> Unit,
noinline key: ((index: Int, item: T) -> Any)? = null,
crossinline itemContent: @Composable LazyItemScope.(index: Int, item: T) -> Unit,
crossinline itemLoadingContent: @Composable LazyItemScope.() -> Unit
) {
var doubleCheck = loading
this.itemsIndexed(item.items, key) { pos, event ->
if (pos == item.lastPos && !loading && !doubleCheck && canLoading) {
doubleCheck = true
loadMore()
}
itemContent(pos, event)
}
if (loading){
this.item {
itemLoadingContent()
}
}
}
data class PagingItems<T>(val lastPos: Int, val items: List<T>) | 0 | Kotlin | 0 | 0 | 92c1a65d5b52e4d14907f32a3d7d10028aca783e | 1,034 | DionysusProject | Apache License 2.0 |
src/main/kotlin/com/github/widarlein/kavanza/model/DealsAndOrdersModels.kt | widarlein | 208,076,108 | false | null | package com.github.widarlein.kavanza.model
data class DealsAndOrders (
val orders : List<Order>,
val deals : List<String>,
val accounts : List<DealAccount>,
val reservedAmount : Int
)
data class Order (
val transactionFees : TransactionFees,
val orderbook : Orderbook,
val account : OrderAccount,
val status : String,
val statusDescription : String,
val rawStatus : String,
val visibleOnAccountDate : String,
val type : String,
val sum : Int,
val orderId : Int,
val price : Int,
val modifyAllowed : Boolean,
val deletable : Boolean,
val orderDateTime : String
)
data class DealAccount (
val type : String,
val name : Int,
val id : Int
)
data class TransactionFees (
val commission : Int,
val marketFees : Int,
val fundOrderFee : FundOrderFee,
val totalFees : Int,
val totalSum : Int,
val totalSumWithoutFees : Int
)
data class Orderbook (
val name : String,
val id : String,
val type : String,
val currency : String,
val marketPlace : String
)
data class FundOrderFee (
val rate : Int,
val sum : Int
)
data class OrderAccount (
val type : String,
val name : Int,
val id : Int
) | 0 | Kotlin | 0 | 1 | 783bf4b7badd3dd0f63dcc62d298c369dd7c2997 | 1,232 | kavanza | MIT License |
qlive-uikit/src/main/java/com/qlive/uikit/RoomPlayerActivity.kt | qiniu | 538,322,435 | false | null | package com.qlive.uikit
import android.content.Context
import android.content.Intent
import android.os.Bundle
import android.os.Handler
import android.os.Looper
import android.util.Log
import android.view.KeyEvent
import android.view.LayoutInflater
import android.view.WindowManager
import android.widget.Toast
import androidx.core.view.LayoutInflaterCompat
import androidx.lifecycle.lifecycleScope
import com.qlive.avparam.PreviewMode
import com.qlive.core.*
import com.qlive.avparam.RtcException
import com.qlive.core.been.QCreateRoomParam
import com.qlive.core.been.QLiveRoomInfo
import com.qlive.liblog.QLiveLogUtil
import com.qlive.playerclient.QPlayerClient
import com.qlive.pubchatservice.QPublicChat
import com.qlive.pubchatservice.QPublicChatService
import com.qlive.qplayer.QPlayerTextureRenderView
import com.qlive.roomservice.QRoomService
import com.qlive.uikitcore.QLiveUIKitContext
import com.qlive.uikitcore.activity.BaseFrameActivity
import kotlin.coroutines.resume
import kotlin.coroutines.resumeWithException
import kotlin.coroutines.suspendCoroutine
import com.qlive.sdk.QLive
import com.qlive.core.QLiveErrorCode
import com.qlive.core.QLiveErrorCode.CANCELED_JOIN
import com.qlive.uikit.component.FuncCPTBeautyDialogShower
import com.qlive.uikit.component.FuncCPTPlayerFloatingHandler
import com.qlive.uikit.component.OnKeyDownMonitor
import com.qlive.uikitcore.KITLiveInflaterFactory
import com.qlive.uikitcore.backGround
import com.qlive.uikitcore.getCode
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.launch
/**
* 观众activity
* UI插件底座 请勿在activity 做过多UI逻辑代码
*/
class RoomPlayerActivity : BaseFrameActivity() {
companion object {
var replaceLayoutId = -1
internal var startCallBack: QLiveCallBack<QLiveRoomInfo>? = null
fun start(
context: Context,
roomId: String,
extSetter: StartRoomActivityExtSetter?,
callBack: QLiveCallBack<QLiveRoomInfo>?
) {
if(QLive.getLoginUser()==null){
callBack?.onError(QLiveErrorCode.NOT_LOGGED_IN,"QLive.getLoginUser()==null")
return
}
val goRoom = {
startCallBack = callBack
val i = Intent(context, RoomPlayerActivity::class.java)
i.putExtra("roomId", roomId)
extSetter?.setExtParams(i)
context.startActivity(i)
}
val clientRef = FuncCPTPlayerFloatingHandler.currentFloatingPlayerView?.clientRef
//小窗 & activity已经销毁 ->进入不同的房间
if (clientRef != null
&& FuncCPTPlayerFloatingHandler.currentFloatingPlayerView?.activityRef?.get() == null
&& (roomId != clientRef.getService(QRoomService::class.java).roomInfo.liveID)
) {
GlobalScope.launch {
suspendLeftForce(clientRef, context)
goRoom.invoke()
}
} else {
goRoom.invoke()
}
}
private suspend fun suspendLeftForce(mRoomClient: QPlayerClient, context: Context) =
suspendCoroutine<Boolean> { cont ->
val left = {
mRoomClient.leaveRoom(object : QLiveCallBack<Void> {
override fun onError(code: Int, msg: String?) {
cont.resume(false)
}
override fun onSuccess(data: Void?) {
cont.resume(true)
}
})
}
//发离开房间消息
mRoomClient.getService(QPublicChatService::class.java)
?.sendByeBye(context.getString(R.string.live_bye_bye_tip),
object : QLiveCallBack<QPublicChat> {
override fun onError(code: Int, msg: String?) {
left.invoke()
}
override fun onSuccess(data: QPublicChat?) {
left.invoke()
}
})
}
}
private var mRoomId = ""
//拉流客户端
private var mRoomClient: QPlayerClient? = null
//离开房间函数
private val leftRoomActionCall: (isAnchorClose: Boolean, resultCall: QLiveCallBack<Void>) -> Unit =
{ _, it ->
mRoomClient!!.leaveRoom(object : QLiveCallBack<Void> {
override fun onError(code: Int, msg: String?) {
it.onError(code, msg)
}
override fun onSuccess(data: Void?) {
it.onSuccess(data)
mInflaterFactory.onLeft()
}
})
}
//加入房间函数
private val createAndJoinRoomActionCall: (param: QCreateRoomParam?, resultCall: QLiveCallBack<QLiveRoomInfo>) -> Unit =
{ p, c ->
Toast.makeText(this, "player activity can not create", Toast.LENGTH_SHORT).show()
}
private val playerRenderView: QPlayerTextureRenderView by lazy {
findViewById(R.id.playerRenderView)
}
//UI组件上下文
private val mQUIKitContext by lazy {
QLiveUIKitContext(
this@RoomPlayerActivity,
supportFragmentManager,
this@RoomPlayerActivity,
this@RoomPlayerActivity,
leftRoomActionCall,
createAndJoinRoomActionCall,
{ playerRenderView },
{ null }
)
}
//加入房间
private suspend fun suspendJoinRoom(roomId: String) = suspendCoroutine<QLiveRoomInfo> { cont ->
mRoomClient!!.joinRoom(roomId, object :
QLiveCallBack<QLiveRoomInfo> {
override fun onError(code: Int, msg: String) {
cont.resumeWithException(RtcException(code, msg))
}
override fun onSuccess(data: QLiveRoomInfo) {
cont.resume(data)
}
})
}
//UI组件装载器
/**
* UI组件以插件的形式加载进来
* 装载器完成替换删除 功能分发操作
*/
private val mInflaterFactory by lazy {
KITLiveInflaterFactory(
delegate,
mRoomClient!!,
mQUIKitContext
).apply {
addFuncComponent(FuncCPTBeautyDialogShower(this@RoomPlayerActivity))
addFuncComponent(FuncCPTPlayerFloatingHandler(this@RoomPlayerActivity))
}
}
public override fun onCreate(savedInstanceState: Bundle?) {
// onCreate -> 恢复原来的room 原activity 已经销毁
// / 或者新房间 原来的activity存在 / 不存在
Log.d("RoomPlayerActivity", "onCreate")
val intentRoomId = intent?.getStringExtra("roomId") ?: ""
var isNewClient = true
var isNewRoom = true
val clientRef = FuncCPTPlayerFloatingHandler.currentFloatingPlayerView?.clientRef
if (clientRef != null) {
// 原来的activity
//原来的悬浮窗口存在
if (intentRoomId != clientRef.getService(QRoomService::class.java).roomInfo.liveID) {
//销毁原来的房间
clientRef.destroy()
FuncCPTPlayerFloatingHandler.currentFloatingPlayerView?.dismiss()
isNewClient = true
//使用新的直播间
mRoomClient = QLive.createPlayerClient()
Log.d("RoomPlayerActivity", "onCreate跳转到新的直播间")
} else {
//复用原来的房间
mRoomClient = clientRef
FuncCPTPlayerFloatingHandler.currentFloatingPlayerView?.dismiss()
//从悬浮窗回到当前activity
isNewClient = false
isNewRoom = false
Log.d("RoomPlayerActivity", "onCreate 同ID activity")
}
} else {
Log.d("RoomPlayerActivity", "onCreate原来的悬浮窗口不存在 后台没有直播间")
//原来的悬浮窗口不存在 后台没有直播间
isNewClient = true
mRoomClient = QLive.createPlayerClient()
}
mRoomId = intentRoomId
window.addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);//设置透明状态栏
window.addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);//设置透明导航栏
LayoutInflaterCompat.setFactory2(
LayoutInflater.from(this),
mInflaterFactory
)
super.onCreate(savedInstanceState)
initView(true, isNewClient, isNewRoom)
playerRenderView.setDisplayAspectRatio(PreviewMode.ASPECT_RATIO_PAVED_PARENT)
}
override fun onNewIntent(intent: Intent?) {
super.onNewIntent(intent)
setIntent(intent)
// 栈顶复用
// 1 从后台点击小窗口返回
// 2 在直播activity 跳转到直播activity(新的)
val intentRoomId = intent?.getStringExtra("roomId") ?: ""
val clientRef = FuncCPTPlayerFloatingHandler.currentFloatingPlayerView?.clientRef
FuncCPTPlayerFloatingHandler.currentFloatingPlayerView?.dismiss()
//client 一定存在
if (mRoomId == intentRoomId) {
mRoomClient!!.play(playerRenderView)
QLiveLogUtil.d("RoomPlayerActivity", "onNewIntent 旧的activity")
initView(
false, false, false
)
} else {
mRoomId = intentRoomId
QLiveLogUtil.d("RoomPlayerActivity", "onNewIntent 新的activity")
lifecycleScope.launch(Dispatchers.Main) {
suspendLeftForce(mRoomClient!!, this@RoomPlayerActivity)
mInflaterFactory.onLeft()
initView(false, false, true)
}
}
}
private fun initView(isNewActivity: Boolean, isNewClient: Boolean, isNewRoom: Boolean) {
QLiveLogUtil.d("RoomPlayerActivity", "initView ${isNewClient} ${isNewRoom}")
val joinCall = {
mInflaterFactory.onEntering(mRoomId, QLive.getLoginUser())
Handler(Looper.myLooper()!!).post {
backGround {
showLoading(true)
doWork {
//加入房间
val room = suspendJoinRoom(mRoomId)
mInflaterFactory.onGetLiveRoomInfo(room)
startCallBack?.onSuccess(room)
//开始播放
mRoomClient!!.play(playerRenderView)
//分发状态到各个UI组件
mInflaterFactory.onJoined(room, false)
}
catchError {
Toast.makeText(this@RoomPlayerActivity, it.message, Toast.LENGTH_SHORT)
.show()
startCallBack?.onError(it.getCode(), it.message)
finish()
}
onFinally {
startCallBack = null
showLoading(false)
}
}
}
}
if (!isNewActivity) {
//旧的activity
if (!isNewClient && !isNewRoom) {
//没变化
return
}
if (isNewRoom && !isNewClient) {
//重新加入房间
joinCall.invoke()
return
}
} else {
//新的activity === 新的UI
//小窗返回原来的房间
if (!isNewRoom && !isNewClient) {
val room = mRoomClient?.getService(QRoomService::class.java)?.roomInfo
if (room == null) {
joinCall.invoke()
return
}
mInflaterFactory.onEntering(mRoomId, QLive.getLoginUser())
Handler(Looper.myLooper()!!).post {
//加入房间
startCallBack?.onSuccess(room)
mInflaterFactory.onGetLiveRoomInfo(room)
//分发状态到各个UI组件
mInflaterFactory.onJoined(room, true)
//开始播放
mRoomClient!!.play(playerRenderView)
startCallBack = null
}
} else {
//小窗返回新的房间 / 进入新的房间
joinCall.invoke()
}
}
}
override fun init() {}
//安卓重写返回键事件
override fun onKeyDown(keyCode: Int, event: KeyEvent): Boolean {
mInflaterFactory.mComponents.forEach {
if (it is OnKeyDownMonitor) {
if (it.onActivityKeyDown(keyCode, event)) {
return true
}
}
}
return super.onKeyDown(keyCode, event)
}
override fun finish() {
QLiveLogUtil.d("RoomPlayerActivity", "RoomPlayerActivity bef")
super.finish()
}
override fun onDestroy() {
super.onDestroy()
mInflaterFactory.onDestroyed()
//不是小窗模式
if (FuncCPTPlayerFloatingHandler.currentFloatingPlayerView == null) {
mRoomClient?.destroy()
QLiveLogUtil.d("RoomPlayerActivity", "RoomPlayerActivity onDestroy 非小窗")
} else {
QLiveLogUtil.d("RoomPlayerActivity", "RoomPlayerActivity onDestroy 小窗")
}
FuncCPTPlayerFloatingHandler.currentFloatingPlayerView?.activityRef?.clear()
mRoomClient = null
startCallBack?.onError(CANCELED_JOIN, "cancel the join room")
startCallBack = null
}
override fun getLayoutId(): Int {
if (replaceLayoutId > 0) {
return replaceLayoutId
}
return R.layout.kit_activity_room_player
}
override fun onResume() {
super.onResume()
if (FuncCPTPlayerFloatingHandler.currentFloatingPlayerView != null) {
FuncCPTPlayerFloatingHandler.currentFloatingPlayerView?.dismiss()
mRoomClient!!.play(playerRenderView)
QLiveLogUtil.d("RoomPlayerActivity", "RoomPlayerActivity onResume 从小窗恢复")
} else {
QLiveLogUtil.d("RoomPlayerActivity", "RoomPlayerActivity onResume--")
}
mRoomClient!!.resume()
}
override fun onPause() {
super.onPause()
if (true == mQUIKitContext.getLiveFuncComponent(FuncCPTPlayerFloatingHandler::class.java)?.isGoingToRequestFloatPermission) {
return
}
if (FuncCPTPlayerFloatingHandler.currentFloatingPlayerView == null) {
mRoomClient?.pause()
}
}
} | 0 | null | 5 | 5 | 6a13f808c2c36d62944e7a206a1524dba07a9cec | 14,288 | QNLiveKit_Android | MIT License |
ios/provider/src/iosMain/kotlin/com/oztechan/ccc/ios/provider/Logger.kt | Oztechan | 102,633,334 | false | {"Kotlin": 569897, "Swift": 92548, "Ruby": 5756, "HTML": 526} | package com.oztechan.ccc.ios.provider
import co.touchlab.kermit.Logger
import com.github.submob.logmob.initCrashlytics
import com.github.submob.logmob.initLogger
@Suppress("unused")
fun initLogger(): Logger {
// should be before initCrashlytics
initLogger()
initCrashlytics()
return Logger
}
| 20 | Kotlin | 30 | 331 | b245b00b507f29102beb18640e65cefd6e8666fb | 310 | CCC | Apache License 2.0 |
app/src/main/java/com/alirezaafkar/phuzei/presentation/splash/SplashActivity.kt | alirezaafkar | 153,698,863 | false | {"Kotlin": 68284} | package com.alirezaafkar.phuzei.presentation.splash
import android.os.Bundle
import androidx.activity.viewModels
import androidx.appcompat.app.AppCompatActivity
import androidx.lifecycle.ViewModelProvider
import androidx.lifecycle.observe
import com.alirezaafkar.phuzei.App
import com.alirezaafkar.phuzei.presentation.login.LoginActivity
import com.alirezaafkar.phuzei.presentation.main.MainActivity
import javax.inject.Inject
/**
* Created by <NAME> on 16/9/2018AD.
*/
class SplashActivity : AppCompatActivity() {
@Inject
lateinit var viewModelFactory: ViewModelProvider.Factory
private val viewModel: SplashViewModel by viewModels { viewModelFactory }
override fun onCreate(savedInstanceState: Bundle?) {
App.get(this).component?.inject(this)
super.onCreate(savedInstanceState)
viewModel.loginActivityObservable.observe(this) {
LoginActivity.start(this)
finish()
}
viewModel.mainActivityObservable.observe(this) {
MainActivity.start(this)
finish()
}
viewModel.subscribe()
}
}
| 4 | Kotlin | 4 | 17 | 81129034cfb7e625b09320c6e0397e2c4e51a883 | 1,111 | phuzei | Apache License 2.0 |
app/src/main/java/com/aarokoinsaari/accessibilitymap/intent/MapIntent.kt | AaroKoinsaari | 810,639,486 | false | {"Kotlin": 76187} | /*
* Copyright (c) 2024 <NAME>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.aarokoinsaari.accessibilitymap.intent
import com.aarokoinsaari.accessibilitymap.view.model.PlaceClusterItem
import com.google.android.gms.maps.model.LatLng
import com.google.android.gms.maps.model.LatLngBounds
sealed class MapIntent {
data class Move(
val center: LatLng,
val zoomLevel: Float,
val bounds: LatLngBounds
) : MapIntent()
data class MapClick(val item: PlaceClusterItem?) : MapIntent()
}
| 20 | Kotlin | 0 | 0 | dbe6ba49706968dbed577ddbad83d7985dc6e490 | 1,046 | accessibility-map-android | Apache License 2.0 |
app/src/main/java/com/bawp/freader/model/SearchInfo.kt | pdichone | 424,016,512 | false | {"Kotlin": 86022} | package com.bawp.freader.model
data class SearchInfo(
val textSnippet: String
) | 1 | Kotlin | 27 | 40 | 65a270a07498f5286ff1341761ec0346ac4b5529 | 84 | JetAReader | Apache License 2.0 |
source/corpus-url/src/main/kotlin/de/webis/webisstud/thesis/reimer/corpus/url/UrlParser.kt | webis-de | 261,803,727 | false | {"Kotlin": 235840, "Jupyter Notebook": 43040, "Java": 7525} | package de.webis.webisstud.thesis.reimer.corpus.url
import dev.reimer.serialization.jsonl.JsonL
import kotlinx.serialization.Serializable
import java.io.BufferedReader
import java.io.Closeable
import java.io.File
import java.net.URL
interface UrlParser : Closeable {
companion object {
private val JSON_L = JsonL()
internal fun parse(file: File) = JsonParser(file).parse().toMap()
}
private class JsonParser(private val file: File) : UrlParser {
private lateinit var reader: BufferedReader
override fun parse(): Sequence<Pair<String, URL>> {
reader = file.bufferedReader()
return JSON_L.parse(DocumentUrl.serializer(), reader.lineSequence())
.map { it.id to it.url }
}
override fun close() {}
}
fun save(file: File) {
val documentUrls = parse()
.map { (id, url) -> DocumentUrl(id, url) }
JSON_L.save(DocumentUrl.serializer(), documentUrls, file)
}
fun parse(): Sequence<Pair<String, URL>>
@Serializable
private data class DocumentUrl(
val id: String,
@Serializable(with = UrlSerializer::class) val url: URL
)
} | 0 | Kotlin | 2 | 2 | 34cbd80dad107b6a7cd57b6a740d35f76013984a | 1,068 | sigir20-sampling-bias-due-to-near-duplicates-in-learning-to-rank | MIT License |
core/src/main/kotlin/com/github/jschlicht/multitenantdbbenchmark/core/util/MdcKey.kt | jschlicht | 744,785,772 | false | {"Kotlin": 53856} | package com.github.jschlicht.multitenantdbbenchmark.core.util
object MdcKey {
const val db = "db"
const val strategy = "strategy"
const val table = "table"
}
| 1 | Kotlin | 0 | 0 | 5ba6b0c28c89523a3738a9765a147f8e6af6a58c | 171 | multi-tenant-db-benchmark | MIT License |
game/src/main/kotlin/xlitekt/game/event/EventBuilder.kt | runetopic | 448,110,155 | false | null | package xlitekt.game.event
/**
* @author <NAME>
*/
class EventBuilder<T : Event>(
private val events: MutableList<EventListener<*>>
) {
private var filter: (T).() -> Boolean = { true }
fun filter(predicate: (T).() -> Boolean): EventBuilder<T> {
this.filter = predicate
return this
}
fun use(use: T.() -> Unit) {
events.add(EventListener(use, filter))
}
}
| 2 | Kotlin | 3 | 8 | 8f88434e6c02e420f60dc9c42d3570b901b96b78 | 408 | xlitekt | MIT License |
app/src/main/java/com/greenart7c3/nostrsigner/ui/HomeScreen.kt | greenart7c3 | 671,206,453 | false | null | package com.greenart7c3.nostrsigner.ui
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.size
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import com.greenart7c3.nostrsigner.R
import com.greenart7c3.nostrsigner.database.AppDatabase
import com.greenart7c3.nostrsigner.models.Account
import com.greenart7c3.nostrsigner.models.IntentData
import com.greenart7c3.nostrsigner.service.ApplicationNameCache
import com.greenart7c3.nostrsigner.ui.components.MultiEventHomeScreen
import com.greenart7c3.nostrsigner.ui.components.SingleEventHomeScreen
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
@Composable
fun HomeScreen(
modifier: Modifier,
intents: List<IntentData>,
packageName: String?,
applicationName: String?,
account: Account,
database: AppDatabase
) {
var loading by remember { mutableStateOf(false) }
LaunchedEffect(Unit) {
launch(Dispatchers.IO) {
loading = true
try {
database.applicationDao().getAllApplications().forEach {
ApplicationNameCache.names[it.application.key] = it.application.name
}
} finally {
loading = false
}
}
}
if (loading) {
CenterCircularProgressIndicator(modifier)
} else {
Box(
modifier
) {
if (intents.isEmpty()) {
Column(
Modifier.fillMaxSize(),
Arrangement.Center,
Alignment.CenterHorizontally
) {
Text(
stringResource(R.string.nothing_to_approve_yet),
fontWeight = FontWeight.Bold,
fontSize = 21.sp
)
Spacer(Modifier.size(8.dp))
Text(stringResource(R.string.why_not_explore_your_favorite_nostr_app_a_bit))
}
} else if (intents.size == 1) {
SingleEventHomeScreen(
packageName,
applicationName,
intents.first(),
account,
database
) {
loading = it
}
} else {
MultiEventHomeScreen(
intents,
packageName,
account,
database
) {
loading = it
}
}
}
}
}
class Result(
val `package`: String?,
val signature: String?,
val id: String?
)
| 7 | null | 4 | 86 | 685a4de3d6a4260b9b082cdc272e37f2800b8572 | 3,381 | Amber | MIT License |
JusAudio/app/src/main/java/com/curiolabs/jusaudio/persistence/JusAudioDatabase.kt | jusaudio | 229,417,104 | false | null | package com.curiolabs.jusaudio.persistence
import android.content.Context
import androidx.room.Database
import androidx.room.Room
import androidx.room.RoomDatabase
import com.curiolabs.jusaudio.persistence.dao.JusAudiosDao
import com.curiolabs.jusaudio.persistence.dao.JusAudiosFtsDao
import com.curiolabs.jusaudio.persistence.entities.JusAudios
import com.curiolabs.jusaudio.persistence.entities.JusAudiosFts
import com.curiolabs.jusaudio.utility_classes.JusAudioConstants.DATABASE_NAME
@Database(
entities = [JusAudios::class, JusAudiosFts::class],
version = 1,
exportSchema = false
)
abstract class JusAudioDatabase : RoomDatabase() {
abstract fun jusAudiosDao(): JusAudiosDao
abstract fun jusAudiosFtsDao(): JusAudiosFtsDao
companion object {
// Singleton prevents multiple instances of database opening at the
// same time.
@Volatile
private var INSTANCE: JusAudioDatabase? = null
fun getDatabase(context: Context): JusAudioDatabase {
val tempInstance =
INSTANCE
if (tempInstance != null) {
return tempInstance
}
synchronized(this) {
val instance = Room.databaseBuilder(
context.applicationContext,
JusAudioDatabase::class.java,
DATABASE_NAME
).build()
INSTANCE = instance
return instance
}
}
}
}
| 0 | Kotlin | 0 | 0 | 23cd2a2ae1fd609e68f355a3e7484ed57234e7d6 | 1,498 | kotlin-android | MIT License |
app/src/main/java/com/wangkeke/kotlinnet/sqlite/MyDatabaseOpenHelper.kt | hanxiaofeng | 109,393,465 | false | null | package com.wangkeke.kotlinnet.sqlite
import android.content.Context
import android.database.sqlite.SQLiteDatabase
import org.jetbrains.anko.db.*
/**
* Created on 2017/11/15 14:32.
* @author by 王可可
* @version 1.0
*/
class MyDatabaseOpenHelper(ctx: Context) : ManagedSQLiteOpenHelper(ctx, "MyDatabase", null, 1) {
companion object {
private var instance: MyDatabaseOpenHelper? = null
@Synchronized
fun getInstance(ctx: Context): MyDatabaseOpenHelper {
if (instance == null) {
instance = MyDatabaseOpenHelper(ctx.getApplicationContext())
}
return instance!!
}
}
override fun onCreate(db: SQLiteDatabase) {
// Here you create tables
db.createTable("User", true,
"id" to INTEGER + PRIMARY_KEY + UNIQUE,
"name" to TEXT,
"email" to TEXT)
}
override fun onUpgrade(db: SQLiteDatabase, oldVersion: Int, newVersion: Int) {
// Here you can upgrade tables, as usual
db.dropTable("User", true)
}
}
// Access property for Context
val Context.database: MyDatabaseOpenHelper
get() = MyDatabaseOpenHelper.getInstance(getApplicationContext()) | 0 | Kotlin | 0 | 2 | 8bd4b3d8ea9168ef13b15a1b9b6e63b655b3b505 | 1,226 | KotlinNet | Apache License 2.0 |
app/src/main/java/ru/endroad/seasonappraiser/routing/NavigatorHolder.kt | RasM24 | 264,874,942 | false | null | package ru.endroad.seasonappraiser.routing
import androidx.fragment.app.FragmentManager
class NavigatorHolder {
var fragmentManager: FragmentManager? = null
} | 0 | Kotlin | 0 | 0 | b71e3bb9d20033ba13d78b2e2d0c1792434f906a | 162 | App-SeasonAppraiser | Apache License 2.0 |
app/src/main/java/br/com/pokedex/data/api/dto/SpritesDTO.kt | ronaldocoding | 557,359,537 | false | {"Kotlin": 20453} | package br.com.pokedex.data.api.dto
import com.google.gson.annotations.SerializedName
data class SpritesDTO(
@SerializedName("other") val other: OtherDTO
)
| 0 | Kotlin | 0 | 1 | 988266c5ccab5d62ac93813ce103d4a10e5ccff1 | 162 | pokedex | MIT License |
backend/src/main/kotlin/br/tapajos/example/application/port/output/ActionRepositoryPort.kt | yanBrandao | 311,519,801 | false | null | package br.tapajos.example.application.port.output
import br.tapajos.example.application.domain.Action
import br.tapajos.example.application.domain.Actions
interface ActionRepositoryPort: GenericRepositoryPort<Action> {
fun findNotUsedAction(): Actions
} | 0 | Kotlin | 0 | 0 | 4789957f09e2ef8fb874836aa4dd19eb4dc58f83 | 260 | image_and_action | MIT License |
backend/src/main/kotlin/br/tapajos/example/application/port/output/ActionRepositoryPort.kt | yanBrandao | 311,519,801 | false | null | package br.tapajos.example.application.port.output
import br.tapajos.example.application.domain.Action
import br.tapajos.example.application.domain.Actions
interface ActionRepositoryPort: GenericRepositoryPort<Action> {
fun findNotUsedAction(): Actions
} | 0 | Kotlin | 0 | 0 | 4789957f09e2ef8fb874836aa4dd19eb4dc58f83 | 260 | image_and_action | MIT License |
features/tv/src/main/java/com/hrudhaykanth116/tv/ui/screens/search/TvSearchItemUI.kt | hrudhaykanth116 | 300,963,083 | false | {"Kotlin": 479412} | package com.hrudhaykanth116.tv.ui.screens.search
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.material3.MaterialTheme
import androidx.compose.runtime.Composable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.unit.dp
import com.hrudhaykanth116.core.common.resources.Dimens
import com.hrudhaykanth116.core.ui.components.AppCard
import com.hrudhaykanth116.core.ui.components.AppClickableIcon
import com.hrudhaykanth116.core.ui.components.AppIcon
import com.hrudhaykanth116.core.ui.components.AppText
import com.hrudhaykanth116.core.ui.components.AppCircularImage
import com.hrudhaykanth116.core.ui.components.HorizontalSpacer
import com.hrudhaykanth116.core.ui.models.toImageHolder
import com.hrudhaykanth116.tv.ui.models.search.SearchScreenItemUIState
@Composable
fun TvSearchItemUI(
state: SearchScreenItemUIState,
onAdd: () -> Unit
) {
AppCard(
) {
Row(
verticalAlignment = Alignment.CenterVertically,
modifier = Modifier
.fillMaxWidth()
.padding(Dimens.DEFAULT_PADDING)
) {
AppCircularImage(
image = state.image,
modifier = Modifier.size(50.dp)
)
HorizontalSpacer()
Column(
modifier = Modifier.weight(1f)
) {
AppText(
uiText = state.name,
maxLines = 2,
style = MaterialTheme.typography.bodyLarge,
overflow = TextOverflow.Ellipsis,
)
}
HorizontalSpacer()
if(state.isMyTvList){
AppIcon(imageHolder = com.hrudhaykanth116.core.R.drawable.ic_check.toImageHolder(), modifier = Modifier.size(40.dp), tint = Color.Green)
}else{
AppClickableIcon(imageHolder = com.hrudhaykanth116.core.R.drawable.ic_add.toImageHolder(), modifier = Modifier.size(40.dp), onClick = onAdd, iconColor = Color.Green)
}
}
}
} | 0 | Kotlin | 0 | 0 | 964a07bdcdaf5405c76c44823a4814cf800287ab | 2,389 | MAFET | MIT License |
client/app/src/main/java/edu/xww/urchat/network/source/DataSource.kt | yanyu-xww | 446,417,642 | false | {"Kotlin": 96249, "Python": 30238, "Batchfile": 564} | package edu.xww.urchat.network.source
import android.graphics.Bitmap
import android.graphics.BitmapFactory
import android.util.Log
import com.google.protobuf.ByteString
import edu.xww.urchat.data.runtime.SRuntimeData
import edu.xww.urchat.data.runtime.SRuntimeData.SMessageList
import edu.xww.urchat.data.struct.Result
import edu.xww.urchat.data.struct.system.CommonRecyclerViewItem
import edu.xww.urchat.data.struct.user.Contact
import edu.xww.urchat.data.struct.user.Message
import edu.xww.urchat.network.builder.ProtocBuilder
import edu.xww.urchat.network.proto.ProtocolOuterClass
import edu.xww.urchat.network.proto.UserMessageOuterClass
import edu.xww.urchat.network.proto.UserMessageOuterClass.MessageType.*
import edu.xww.urchat.util.Encode
import java.io.ByteArrayOutputStream
import java.lang.Exception
import java.util.*
import java.util.concurrent.locks.ReentrantLock
import kotlin.collections.ArrayList
import kotlin.collections.HashMap
object DataSource {
/**
* Request contact list
*/
fun contacts() {
val protoc = ProtocBuilder().requireContacts().buildValid()
val rt = post(protoc)
if (rt is Result.Success) {
rt.data.bitsMap.forEach {
try {
val uid = it.key
val runtimeContact = SRuntimeData.SContacts[uid]
val contact = ProtocolOuterClass.Protocol.parseFrom(it.value)
if (runtimeContact != null) {
runtimeContact.name =
contact.getPairsOrDefault("displayName", runtimeContact.name)
runtimeContact.icon = contact.getPairsOrDefault("icon", runtimeContact.icon)
runtimeContact.displayName =
contact.getPairsOrDefault("nickname", runtimeContact.displayName)
} else {
SRuntimeData.SContacts +=
Contact.buildNormal(
uid,
contact.getPairsOrDefault("displayName", ""),
contact.getPairsOrDefault("icon", ""),
contact.getPairsOrDefault(
"nickname",
contact.getPairsOrDefault("displayName", "Contact")
)
)
}
} catch (e: Exception) {
Log.e("DataSource", "Load user contact error near ${it.key}\n$e")
}
}
}
SRuntimeData.SContacts.sort()
}
private val lock = ReentrantLock()
/**
* Request messages
*/
fun message() {
val protoc = ProtocBuilder().requireMessage().buildValid()
val rt = post(protoc)
if (rt is Result.Success) {
rt.data.bitsMap.forEach {
try {
val msg = UserMessageOuterClass.UserMessage.parseFrom(it.value)
var m: Message? = null
when (msg.type) {
TEXT -> m = Message.receiveNormalText(msg.message, msg.millisecondTimestamp)
IMAGE -> m = Message.receiveNormalImg(msg.message, msg.millisecondTimestamp)
POSITION -> m = Message.receiveNormalText(msg.message, msg.millisecondTimestamp)
ADD -> { SRuntimeData.SNewContacts += Contact.buildNormal(msg.src, "", "", msg.message, "new") }
DEL -> {}
else -> {}
}
if (m != null) {
SRuntimeData.SMessageBox[msg.src] = msg
SMessageList[msg.src] = m
}
} catch (e: Exception) {
Log.e("DataSource", "Load user message error near ${it.key}\n$e")
}
}
}
}
/**
* Request image
*/
fun image(names: MutableList<String>): HashMap<String, Bitmap> {
val protoc = ProtocBuilder().requireImage(names).buildValid()
val rt = post(protoc)
val map: HashMap<String, Bitmap> = HashMap()
if (rt is Result.Success) {
rt.data.bitsMap.forEach { map[it.key] = Encode.toBitmap(it.value) }
}
return map
}
/**
* post protoc
*/
private fun post(protoc: ProtocolOuterClass.Protocol): Result<ProtocolOuterClass.Protocol> {
return try {
val rt =
SocketHelper.sendRequest(protoc) ?: return Result.Error("Can't connect to server")
if (!rt.valid) return Result.Error("Post Fail")
Result.Success(rt)
} catch (e: Exception) {
Result.Error(e.toString())
}
}
/**
* send protoc
*/
fun send(protoc: ProtocolOuterClass.Protocol): Result<String> {
if (post(protoc) is Result.Success) return Result.Success("")
return Result.Error("Post Fail")
}
/**
* send UserMessageOuterClass.UserMessage
*/
fun sendMessage(msg: UserMessageOuterClass.UserMessage): Result<String> {
val protoc = ProtocBuilder().sendMessage(msg.des, msg).buildValid()
if (post(protoc) is Result.Success) return Result.Success("")
return Result.Error("Post Fail")
}
/**
* update icon
*/
fun updateIcon(filename: String, bitmap: Bitmap): Result<String> {
val s = Encode.toBase64(bitmap)
val protoc =
ProtocBuilder().requireUpdate().putPairs("icon", filename).putBytes(filename, s)
.buildValid()
if (post(protoc) is Result.Success) return Result.Success("")
return Result.Error("Post Fail")
}
/**
* response contact application
*/
fun responseContact(des: String): Result<String> {
val protoc = ProtocBuilder().putPairs("des_uid", des).responseContact().buildValid()
if (post(protoc) is Result.Success) return Result.Success("")
return Result.Error("Post Fail")
}
/**
* send image
*/
fun sendImage(msg: UserMessageOuterClass.UserMessage, bitmap: Bitmap): Result<String> {
val s = Encode.toBase64(bitmap)
val protoc = ProtocBuilder().sendMessage(msg.des, msg).putBytes(msg.message, s).buildValid()
if (post(protoc) is Result.Success) return Result.Success("")
return Result.Error("Post Fail")
}
} | 0 | Kotlin | 0 | 0 | 0091cfd25a2ca953127e2f4f78f2166597a648ee | 6,528 | UrChat | Apache License 2.0 |
app/src/main/java/com/ervilitasila/githubapp/di/ViewModelsModule.kt | ervilitarsila | 799,368,188 | false | {"Kotlin": 32724} | package com.ervilitasila.githubapp.di
import com.ervilitasila.githubapp.ui.home.UserViewModel
import com.ervilitasila.githubapp.ui.userdetail.UserDetailViewModel
import org.koin.androidx.viewmodel.dsl.viewModel
import org.koin.dsl.module
val viewModelsModule = module {
viewModel { UserViewModel(get()) }
viewModel { UserDetailViewModel(get()) }
} | 0 | Kotlin | 0 | 0 | 4adaeb7e4461fe716e2038023d58ce616ed1f09a | 357 | GitHubApp | MIT License |
sample/src/jsCommonMain/kotlin/com/github/panpf/zoomimage/sample/ui/VerHomeScreen.jsCommon.kt | panpf | 647,222,866 | false | {"Kotlin": 4055517, "Shell": 3739} | package com.github.panpf.zoomimage.sample.ui
import androidx.compose.runtime.Composable
@Composable
actual fun VerHomeHeader() {
} | 8 | Kotlin | 16 | 303 | 8627b3429ce148cccbaee751cc6793a63cb48b69 | 133 | zoomimage | Apache License 2.0 |
core/src/jsMain/kotlin/com/chrynan/chords/util/ChordViewModelUtils.kt | TrendingTechnology | 303,027,593 | true | {"Kotlin": 142337, "HTML": 245} | package com.chrynan.chords.util
import com.chrynan.chords.model.ChordViewModel
import com.chrynan.chords.model.StringLabelState
import com.chrynan.chords.view.ChordView
import com.chrynan.colors.Color
@Suppress("unused", "FunctionName")
fun ChordViewModel(
fitToHeight: Boolean = ChordView.DEFAULT_FIT_TO_HEIGHT,
showFretNumbers: Boolean = ChordView.DEFAULT_SHOW_FRET_NUMBERS,
showFingerNumbers: Boolean = ChordView.DEFAULT_SHOW_FINGER_NUMBERS,
stringLabelState: StringLabelState = ChordView.DEFAULT_STRING_LABEL_STATE,
mutedStringText: String = ChordView.DEFAULT_MUTED_TEXT,
openStringText: String = ChordView.DEFAULT_OPEN_TEXT,
fretColor: Color,
fretLabelTextColor: Color,
stringColor: Color,
stringLabelTextColor: Color,
noteColor: Color,
noteLabelTextColor: Color
): ChordViewModel = ChordViewModel(
fitToHeight = fitToHeight,
showFretNumbers = showFretNumbers,
showFingerNumbers = showFingerNumbers,
stringLabelState = stringLabelState,
mutedStringText = mutedStringText,
openStringText = openStringText,
fretColor = fretColor.colorInt,
fretLabelTextColor = fretLabelTextColor.colorInt,
stringColor = stringColor.colorInt,
stringLabelTextColor = stringLabelTextColor.colorInt,
noteColor = noteColor.colorInt,
noteLabelTextColor = noteLabelTextColor.colorInt) | 0 | null | 0 | 0 | 15e7b03a91585862295fe93a87273c7c3e4f3d3e | 1,457 | chords | Apache License 2.0 |
dagpenger/src/test/kotlin/no/nav/dagpenger/features/UtdanningSteg.kt | navikt | 415,800,876 | false | {"Kotlin": 459562, "Gherkin": 63560, "HTML": 1870, "Dockerfile": 204} | package no.nav.dagpenger.features
import io.cucumber.java.BeforeStep
import io.cucumber.java8.No
import io.kotest.assertions.withClue
import io.kotest.matchers.shouldBe
import no.nav.dagpenger.dato.mai
import no.nav.dagpenger.opplysning.Faktum
import no.nav.dagpenger.opplysning.Opplysninger
import no.nav.dagpenger.opplysning.Regelkjøring
import no.nav.dagpenger.regel.Søknadstidspunkt
import no.nav.dagpenger.regel.Utdanning
class UtdanningSteg : No {
private val fraDato = 23.mai(2024)
private val regelsett = listOf(Utdanning.regelsett, Søknadstidspunkt.regelsett)
private val opplysninger = Opplysninger()
@BeforeStep
fun kjørRegler() {
Regelkjøring(fraDato, opplysninger, *regelsett.toTypedArray())
}
init {
Gitt("at personen søker på kravet om dagpenger") {
opplysninger.leggTil(Faktum(Søknadstidspunkt.søknadsdato, 23.mai(2024)))
opplysninger.leggTil(Faktum(Søknadstidspunkt.ønsketdato, 23.mai(2024)))
}
Gitt("at søkeren svarer {boolsk} på spørsmålet om utdanning") { utdanning: Boolean ->
opplysninger.leggTil(Faktum(Utdanning.tarUtdanning, utdanning))
}
Gitt("at unntaket arbeidsmarkedstiltak er {boolsk}") { svar: Boolean ->
opplysninger.leggTil(Faktum(Utdanning.deltakelseIArbeidsmarkedstiltak, svar))
}
Gitt("at unntaket opplæring for innvandrere er {boolsk}") { svar: Boolean ->
opplysninger.leggTil(Faktum(Utdanning.opplæringForInnvandrere, svar))
}
Gitt("at unntaket grunnskoleopplæring er {boolsk}") { svar: Boolean ->
opplysninger.leggTil(Faktum(Utdanning.grunnskoleopplæring, svar))
}
Gitt("at unntaket høyere yrkesfaglig utdanning er {boolsk}") { svar: Boolean ->
opplysninger.leggTil(Faktum(Utdanning.høyereYrkesfagligUtdanning, svar))
}
Gitt("at unntaket høyere utdanning er {boolsk}") { svar: Boolean ->
opplysninger.leggTil(Faktum(Utdanning.høyereUtdanning, svar))
}
Gitt("at unntaket deltar på kurs er {boolsk}") { svar: Boolean ->
opplysninger.leggTil(Faktum(Utdanning.deltakelsePåKurs, svar))
}
Så("skal utfallet om utdanning være {boolsk}") { svar: Boolean ->
withClue("${Utdanning.kravTilUtdanning} skal være tilstede") {
opplysninger.har(Utdanning.kravTilUtdanning) shouldBe true
}
withClue("${Utdanning.kravTilUtdanning} skal være $svar") {
opplysninger.finnOpplysning(Utdanning.kravTilUtdanning).verdi shouldBe svar
}
}
}
}
| 0 | Kotlin | 0 | 0 | e4e6fbe1cff8f51beb0ab3f13b1936d08a7b76ff | 2,641 | dp-behandling | MIT License |
app/src/main/kotlin/com/amsavarthan/tally/data/utils/AppPreferenceSerializer.kt | amsavarthan | 592,784,968 | false | {"Kotlin": 232629, "HTML": 5928} | package com.amsavarthan.tally.data.utils
import androidx.datastore.core.CorruptionException
import androidx.datastore.core.Serializer
import com.amsavarthan.tally.AppPreference
import com.google.protobuf.InvalidProtocolBufferException
import java.io.InputStream
import java.io.OutputStream
import javax.inject.Inject
class AppPreferenceSerializer @Inject constructor() : Serializer<AppPreference> {
override val defaultValue: AppPreference
get() = AppPreference.getDefaultInstance()
override suspend fun readFrom(input: InputStream): AppPreference {
try {
return AppPreference.parseFrom(input)
} catch (exception: InvalidProtocolBufferException) {
throw CorruptionException("Cannot read proto.", exception)
}
}
override suspend fun writeTo(t: AppPreference, output: OutputStream) {
t.writeTo(output)
}
} | 0 | Kotlin | 0 | 4 | 3d5209573aeb755f3ce3f899add6075a28224c9c | 891 | tally | MIT License |
app/src/main/java/com/explosion204/tabatatimer/ui/fragments/SettingsFragment.kt | explosion204 | 302,389,407 | false | null | package com.explosion204.tabatatimer.ui.fragments
import android.app.ActivityManager
import android.content.Context.ACTIVITY_SERVICE
import android.os.Bundle
import androidx.appcompat.app.AlertDialog
import androidx.preference.Preference
import androidx.preference.PreferenceFragmentCompat
import com.explosion204.tabatatimer.Constants.CLEAR_DATA_PREFERENCE
import com.explosion204.tabatatimer.R
class SettingsFragment : PreferenceFragmentCompat() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
findPreference<Preference>(CLEAR_DATA_PREFERENCE)?.setOnPreferenceClickListener {
AlertDialog.Builder(requireContext())
.setMessage(getString(R.string.clear_data_dialog_message))
.setPositiveButton(getString(R.string.clear)) { _, _ ->
(requireActivity().getSystemService(ACTIVITY_SERVICE) as ActivityManager)
.clearApplicationUserData()
}
.setNegativeButton(getString(R.string.cancel)) { _, _ -> }
.setCancelable(true)
.create()
.show()
true
}
}
override fun onCreatePreferences(savedInstanceState: Bundle?, rootKey: String?) {
setPreferencesFromResource(R.xml.preferences, rootKey)
}
} | 0 | Kotlin | 0 | 0 | 651beb94b218bfd405eb152015eae46cf59a8af8 | 1,357 | tabata-timer | Apache License 2.0 |
src/main/kotlin/fe/kartifice/builder/data/recipe/ShapelessRecipeBuilder.kt | natanfudge | 217,017,390 | false | null | package fe.kartifice.builder.data.recipe
import com.google.gson.JsonArray
import fe.kartifice.builder.JsonObjectBuilder
import net.minecraft.util.Identifier
/**
* Builder for a shapeless crafting recipe (`namespace:recipes/id.json`).
* @see [Minecraft Wiki](https://minecraft.gamepedia.com/Recipe.JSON_format)
*/
class ShapelessRecipeBuilder :
RecipeBuilder<ShapelessRecipeBuilder>() {
/**
* Add an ingredient item.
* @param id The item ID.
* @return this
*/
fun ingredientItem(id: Identifier): ShapelessRecipeBuilder {
with("ingredients", ::JsonArray) {
add(JsonObjectBuilder().add("item", id.toString()).build())
}
return this
}
/**
* Add an ingredient item as any of the given tag.
* @param id The tag ID.
* @return this
*/
fun ingredientTag(id: Identifier): ShapelessRecipeBuilder {
with("ingredients", ::JsonArray) {
add(
JsonObjectBuilder().add("tag", id.toString()).build()
)
}
return this
}
/**
* Add an ingredient item as one of a list of options.
* @param settings A callback which will be passed a [MultiIngredientBuilder].
* @return this
*/
fun multiIngredient(settings: MultiIngredientBuilder.() -> Unit): ShapelessRecipeBuilder {
with(
"ingredients",
{ JsonArray() },
{
add(MultiIngredientBuilder().apply(settings).build())
}
)
return this
}
/**
* Set the item produced by this recipe.
* @param id The item ID.
* @param count The number of result items.
* @return this
*/
fun result(id: Identifier, count: Int): ShapelessRecipeBuilder {
root.add("result", JsonObjectBuilder().add("item", id.toString()).add("count", count).build())
return this
}
init {
type(Identifier("crafting_shapeless"))
}
} | 0 | Kotlin | 0 | 0 | 0f9e392bcf2cc0df628cf6d22786759be256284b | 1,976 | Fabricated-Energistics | MIT License |
intellij-plugin/educational-core/branches/231/src/com/jetbrains/edu/learning/taskToolWindow/ui/utils.kt | JetBrains | 43,696,115 | false | {"Kotlin": 4827860, "HTML": 3417303, "Python": 18245, "Java": 13415, "CSS": 12216, "JavaScript": 302, "Shell": 71} | package com.jetbrains.edu.learning.taskToolWindow.ui
import com.intellij.ui.dsl.builder.Cell
import com.intellij.ui.dsl.builder.Row
import com.intellij.ui.dsl.gridLayout.Gaps
import com.intellij.ui.dsl.gridLayout.VerticalGaps
import javax.swing.JComponent
import org.apache.commons.lang.StringEscapeUtils
import org.apache.commons.lang.text.StrSubstitutor
// BACKCOMPAT: 2023.1. Inline it.
fun <T: JComponent> Cell<T>.addGaps(top: Int = 0, left: Int = 0, bottom: Int = 0, right: Int = 0): Cell<T> {
return customize(Gaps(top, left, bottom, right))
}
// BACKCOMPAT: 2023.1. Inline it.
fun Row.addVerticalGaps(top: Int = 0, bottom: Int = 0): Row = customize(VerticalGaps(top, bottom))
// BACKCOMPAT: 2023.2. Inline it.
fun escapeHtml(s: String): String = StringEscapeUtils.escapeHtml(s)
// BACKCOMPAT: 2023.2. Inline it.
fun replaceWithTemplateText(resources: Map<String, String>, templateText: String): String {
return StrSubstitutor(resources).replace(templateText)
} | 5 | Kotlin | 48 | 130 | 96762747ac60cb159b02da0c3c7d1596844194ff | 976 | educational-plugin | Apache License 2.0 |
liveroom-service/likeservice/src/main/java/com/qlive/likeservice/inner/InnerLike.kt | qiniu | 538,322,435 | false | {"Kotlin": 1143492, "Java": 484578} | package com.qlive.likeservice.inner
import java.io.Serializable
internal class InnerLike : Serializable {
var live_id = ""
var user_id = ""
var count = 3
} | 0 | Kotlin | 4 | 5 | 874556472c2b9f64a41a61a113b1e57e9d864ccd | 169 | QNLiveKit_Android | MIT License |
app/src/main/java/com/example/marsphotos/ScreenMain.kt | akbarbin | 737,496,550 | false | {"Kotlin": 162164} | package com.example.marsphotos
import androidx.compose.foundation.border
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.padding
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Add
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.Scaffold
import androidx.compose.material3.Text
import androidx.compose.material3.TopAppBar
import androidx.compose.runtime.Composable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.navigation.NavHostController
import androidx.compose.ui.unit.dp
import androidx.compose.material3.Icon
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.material.icons.filled.Home
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Surface
import androidx.compose.ui.draw.clip
@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun ScreenMain(navController: NavHostController) {
Scaffold(
topBar = {
TopAppBar(
title = { Text(text = "Green Building Meter") }
)
}
) {
Surface(
modifier = Modifier
.fillMaxSize()
.padding(it),
color = MaterialTheme.colorScheme.background
) {
Column(
modifier = Modifier.fillMaxSize(),
verticalArrangement = Arrangement.Center,
horizontalAlignment = Alignment.CenterHorizontally
) {
Icon(
Icons.Default.Home,
contentDescription = "Reports",
modifier = Modifier
// Set image size to 40 dp
.size(70.dp)
// Clip image to be shaped as a circle
.clip(CircleShape)
.border(1.5.dp, MaterialTheme.colorScheme.primary, CircleShape)
)
Text(text = "Reports", modifier = Modifier.padding(16.dp))
Icon(
Icons.Default.Add,
contentDescription = "Add",
modifier = Modifier
// Set image size to 40 dp
.size(70.dp)
// Clip image to be shaped as a circle
.clip(CircleShape)
.border(1.5.dp, MaterialTheme.colorScheme.primary, CircleShape)
)
Text(text = "Add", modifier = Modifier.padding(16.dp))
}
}
}
} | 0 | Kotlin | 0 | 0 | 123d3805aeb91bcb888c56273ed573d1a3b71e21 | 2,802 | green-building-android | Apache License 2.0 |
domain/usecase/src/main/java/com/kazakago/blueprint/domain/usecase/hierarchy/github/RefreshGithubOrgsUseCaseImpl.kt | KazaKago | 60,256,062 | false | null | package com.kazakago.blueprint.domain.usecase.hierarchy.github
import com.kazakago.blueprint.domain.repository.hierarchy.GithubRepository
import javax.inject.Inject
internal class RefreshGithubOrgsUseCaseImpl @Inject constructor(
private val githubRepository: GithubRepository,
) : RefreshGithubOrgsUseCase {
override suspend fun invoke() {
return githubRepository.refreshOrgs()
}
}
| 0 | Kotlin | 1 | 3 | 61551d7bea3a842dbbcab8e05eeb334db0367570 | 406 | blueprint_android | Apache License 2.0 |
src/main/kotlin/cn/vove7/plugin/rest/psi/RestWs.kt | Vove7 | 211,596,099 | false | null | // This is a generated file. Not intended for manual editing.
package cn.vove7.plugin.rest.psi
import com.intellij.psi.PsiElement
interface RestWs : PsiElement | 2 | Kotlin | 6 | 50 | d8650bef5eede23f7e9197af1c5db961e3a89f73 | 161 | retrofit-rest-client | Apache License 2.0 |
rounded/src/commonMain/kotlin/me/localx/icons/rounded/filled/MehRollingEyes.kt | localhostov | 808,861,591 | false | {"Kotlin": 79430321, "HTML": 331, "CSS": 102} | package me.localx.icons.rounded.filled
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.PathFillType.Companion.NonZero
import androidx.compose.ui.graphics.SolidColor
import androidx.compose.ui.graphics.StrokeCap.Companion.Butt
import androidx.compose.ui.graphics.StrokeJoin.Companion.Miter
import androidx.compose.ui.graphics.vector.ImageVector
import androidx.compose.ui.graphics.vector.ImageVector.Builder
import androidx.compose.ui.graphics.vector.path
import androidx.compose.ui.unit.dp
import me.localx.icons.rounded.Icons
public val Icons.Filled.MehRollingEyes: ImageVector
get() {
if (_mehRollingEyes != null) {
return _mehRollingEyes!!
}
_mehRollingEyes = Builder(name = "MehRollingEyes", defaultWidth = 512.0.dp, defaultHeight =
512.0.dp, viewportWidth = 24.0f, viewportHeight = 24.0f).apply {
path(fill = SolidColor(Color(0xFF000000)), stroke = null, strokeLineWidth = 0.0f,
strokeLineCap = Butt, strokeLineJoin = Miter, strokeLineMiter = 4.0f,
pathFillType = NonZero) {
moveTo(17.847f, 9.149f)
curveToRelative(0.49f, 1.106f, -0.234f, 2.9f, -1.347f, 2.851f)
curveToRelative(-1.113f, 0.045f, -1.838f, -1.745f, -1.347f, -2.851f)
arcTo(1.505f, 1.505f, 0.0f, false, false, 17.847f, 9.149f)
close()
moveTo(9.0f, 10.0f)
arcToRelative(2.487f, 2.487f, 0.0f, false, false, -0.153f, -0.851f)
arcToRelative(1.505f, 1.505f, 0.0f, false, true, -2.694f, 0.0f)
curveTo(5.218f, 11.952f, 8.737f, 13.405f, 9.0f, 10.0f)
close()
moveTo(24.0f, 12.0f)
arcTo(12.013f, 12.013f, 0.0f, false, true, 12.0f, 24.0f)
curveTo(-3.9f, 23.4f, -3.894f, 0.6f, 12.0f, 0.0f)
arcTo(12.013f, 12.013f, 0.0f, false, true, 24.0f, 12.0f)
close()
moveTo(7.5f, 14.0f)
curveToRelative(4.612f, -0.129f, 4.611f, -7.872f, 0.0f, -8.0f)
curveTo(2.888f, 6.129f, 2.889f, 13.872f, 7.5f, 14.0f)
close()
moveTo(17.0f, 17.0f)
arcToRelative(1.0f, 1.0f, 0.0f, false, false, -1.0f, -1.0f)
lineTo(8.0f, 16.0f)
arcToRelative(1.0f, 1.0f, 0.0f, false, false, 0.0f, 2.0f)
horizontalLineToRelative(8.0f)
arcTo(1.0f, 1.0f, 0.0f, false, false, 17.0f, 17.0f)
close()
moveTo(20.0f, 10.0f)
curveToRelative(-0.128f, -5.278f, -6.872f, -5.277f, -7.0f, 0.0f)
curveTo(13.128f, 15.278f, 19.872f, 15.277f, 20.0f, 10.0f)
close()
}
}
.build()
return _mehRollingEyes!!
}
private var _mehRollingEyes: ImageVector? = null
| 1 | Kotlin | 0 | 5 | cbd8b510fca0e5e40e95498834f23ec73cc8f245 | 2,908 | icons | MIT License |
sandbox/coffee-maker/src/main/kotlin/org/koin/example/coffee/Heater.kt | InsertKoinIO | 429,817,719 | false | {"Kotlin": 142724, "Shell": 389} | package org.koin.example.coffee
interface Heater {
fun on()
fun off()
fun isHot(): Boolean
} | 10 | Kotlin | 26 | 98 | 34dab75ad64d9cd2b65b8e4e06fd7ca9b7401636 | 105 | koin-annotations | Apache License 2.0 |
shared/src/main/java/de/loosetie/k8s/dsl/manifests/ServiceAccount.kt | loosetie | 283,145,621 | false | {"Kotlin": 10664277} | package de.loosetie.k8s.dsl.manifests
import de.loosetie.k8s.dsl.K8sTopLevel
import de.loosetie.k8s.dsl.K8sDslMarker
import de.loosetie.k8s.dsl.K8sManifest
import de.loosetie.k8s.dsl.HasMetadata
@K8sDslMarker
interface ServiceAccount_core_v1_k8s1_16: K8sTopLevel, HasMetadata {
/** APIVersion defines the versioned schema of this representation of an object. Servers should convert recognized schemas
to the latest internal value, and may reject unrecognized values. More info:
https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#resources */
override val apiVersion: String
get() = "core/v1"
/** Kind is a string value representing the REST resource this object represents. Servers may infer this from the endpoint
the client submits requests to. Cannot be updated. In CamelCase. More info:
https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds */
override val kind: String
get() = "ServiceAccount"
/** Standard object's metadata. More info:
https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata */
val metadata: ObjectMeta_meta_v1_k8s1_16
/** AutomountServiceAccountToken indicates whether pods running as this service account should have an API token
automatically mounted. Can be overridden at the pod level. */
@K8sDslMarker var automountServiceAccountToken: Boolean?
/** ImagePullSecrets is a list of references to secrets in the same namespace to use for pulling any images in pods that
reference this ServiceAccount. ImagePullSecrets are distinct from Secrets because Secrets can be mounted in the pod, but
ImagePullSecrets are only accessed by the kubelet. More info:
https://kubernetes.io/docs/concepts/containers/images/#specifying-imagepullsecrets-on-a-pod */
val imagePullSecrets: List<LocalObjectReference_core_v1_k8s1_16>?
/** Secrets is the list of secrets allowed to be used by pods running using this ServiceAccount. More info:
https://kubernetes.io/docs/concepts/configuration/secret */
val secrets: List<ObjectReference_core_v1_k8s1_16>?
}
@K8sDslMarker
interface ServiceAccount_core_v1_k8s1_17: K8sTopLevel, HasMetadata {
/** APIVersion defines the versioned schema of this representation of an object. Servers should convert recognized schemas
to the latest internal value, and may reject unrecognized values. More info:
https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#resources */
override val apiVersion: String
get() = "core/v1"
/** Kind is a string value representing the REST resource this object represents. Servers may infer this from the endpoint
the client submits requests to. Cannot be updated. In CamelCase. More info:
https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds */
override val kind: String
get() = "ServiceAccount"
/** Standard object's metadata. More info:
https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata */
val metadata: ObjectMeta_meta_v1_k8s1_17
/** AutomountServiceAccountToken indicates whether pods running as this service account should have an API token
automatically mounted. Can be overridden at the pod level. */
@K8sDslMarker var automountServiceAccountToken: Boolean?
/** ImagePullSecrets is a list of references to secrets in the same namespace to use for pulling any images in pods that
reference this ServiceAccount. ImagePullSecrets are distinct from Secrets because Secrets can be mounted in the pod, but
ImagePullSecrets are only accessed by the kubelet. More info:
https://kubernetes.io/docs/concepts/containers/images/#specifying-imagepullsecrets-on-a-pod */
val imagePullSecrets: List<LocalObjectReference_core_v1_k8s1_17>?
/** Secrets is the list of secrets allowed to be used by pods running using this ServiceAccount. More info:
https://kubernetes.io/docs/concepts/configuration/secret */
val secrets: List<ObjectReference_core_v1_k8s1_17>?
}
typealias ServiceAccount_core_v1_k8s1_18 = ServiceAccount_core_v1_k8s1_17
typealias ServiceAccount_core_v1_k8s1_19 = ServiceAccount_core_v1_k8s1_18
typealias ServiceAccount_core_v1_k8s1_20 = ServiceAccount_core_v1_k8s1_19
typealias ServiceAccount_core_v1_k8s1_21 = ServiceAccount_core_v1_k8s1_20 | 0 | Kotlin | 0 | 1 | dd616e546de56240a7a4d3edb18cb4f6529e301b | 4,352 | k8s-dsl | Apache License 2.0 |
app/src/main/java/net/mrjosh/homepi/adapters/AccessoryAdapter.kt | homepi | 350,767,593 | false | null | package net.mrjosh.homepi.adapters
import android.view.View
import net.mrjosh.homepi.R
import android.view.ViewGroup
import android.content.Context
import android.widget.BaseAdapter
import android.view.LayoutInflater
import android.annotation.SuppressLint
import net.mrjosh.homepi.models.Accessory
import androidx.core.content.res.ResourcesCompat
import androidx.appcompat.widget.AppCompatTextView
import androidx.appcompat.widget.AppCompatImageView
class AccessoryAdapter(private val context: Context,
private val accessories: List<Accessory>): BaseAdapter() {
@SuppressLint("InflateParams", "ViewHolder")
override fun getView(position: Int, view: View?, parent: ViewGroup): View? {
val inflater = context.getSystemService(Context.LAYOUT_INFLATER_SERVICE) as LayoutInflater
val gridView = inflater.inflate(R.layout.accessory_card_view, null)
var icon: Int = R.drawable.ic_light_on
val accessory: Accessory = accessories[position]
val accessoryName: AppCompatTextView = gridView.findViewById(R.id.accessory_name)
accessoryName.text = accessory.name
val accessoryIcon: AppCompatImageView = gridView.findViewById(R.id.accessory_icon)
when (accessory.icon) {
"doorbell" -> icon = R.drawable.ic_doorbell
"lamp" -> icon = R.drawable.ic_light_on
}
accessoryIcon.background = ResourcesCompat.getDrawable(context.resources, icon, null)
return gridView
}
override fun getCount(): Int {
return accessories.size
}
override fun getItem(position: Int): Any {
return accessories[position]
}
override fun getItemId(position: Int): Long {
return 0
}
} | 0 | Kotlin | 0 | 2 | bede8ba46d0047de298b4dc940e8469b51674385 | 1,736 | homepi-android | MIT License |
app/src/main/java/com/bossed/waej/ui/RemitAccountActivity.kt | Ltow | 710,230,789 | false | {"Kotlin": 2304560, "Java": 395495, "HTML": 71364} | package com.bossed.waej.ui
import android.app.Dialog
import android.content.Intent
import android.graphics.Color
import android.os.Bundle
import android.os.Handler
import android.text.TextUtils
import android.view.Gravity
import android.view.View
import android.view.ViewGroup
import android.widget.LinearLayout
import android.widget.ProgressBar
import android.widget.TextView
import androidx.activity.result.contract.ActivityResultContracts
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.bigkoo.pickerview.builder.OptionsPickerBuilder
import com.bigkoo.pickerview.view.OptionsPickerView
import com.blankj.utilcode.util.BarUtils
import com.blankj.utilcode.util.GsonUtils
import com.blankj.utilcode.util.LogUtils
import com.blankj.utilcode.util.SPUtils
import com.blankj.utilcode.util.ToastUtils
import com.bossed.waej.R
import com.bossed.waej.adapter.IdTypeAdapter
import com.bossed.waej.base.BaseActivity
import com.bossed.waej.customview.PopWindow
import com.bossed.waej.eventbus.EBLaKaLaBack
import com.bossed.waej.http.Api
import com.bossed.waej.http.BaseResourceObserver
import com.bossed.waej.http.UrlConstants
import com.bossed.waej.http.UrlConstants.GetBankCardInfoUrl
import com.bossed.waej.http.UrlConstants.MerchantListUrl
import com.bossed.waej.http.UrlConstants.NewMerchantUrl
import com.bossed.waej.javebean.BankCardInfoResponse
import com.bossed.waej.javebean.Children
import com.bossed.waej.javebean.ChildrenX
import com.bossed.waej.javebean.CitiesBean
import com.bossed.waej.javebean.City
import com.bossed.waej.javebean.ContractResponse
import com.bossed.waej.javebean.IdTypeBean
import com.bossed.waej.javebean.RemitAccountListResponse
import com.bossed.waej.javebean.RemitAccountResponse
import com.bossed.waej.util.DateFormatUtils
import com.bossed.waej.util.DoubleClicksUtils
import com.bossed.waej.util.GetJsonDataUtil
import com.bossed.waej.util.LoadingUtils
import com.bossed.waej.util.OssUtils
import com.bossed.waej.util.PopupWindowUtils
import com.bossed.waej.util.RetrofitUtils
import com.bumptech.glide.Glide
import com.gyf.immersionbar.ImmersionBar
import com.hjq.bar.OnTitleBarListener
import com.luck.picture.lib.config.PictureConfig
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.disposables.Disposable
import io.reactivex.schedulers.Schedulers
import kotlinx.android.synthetic.main.activity_remit_account.*
import org.greenrobot.eventbus.EventBus
class RemitAccountActivity : BaseActivity(), View.OnClickListener, View.OnLongClickListener {
private var options1Items: ArrayList<City> = ArrayList() //省
private val options2Items = ArrayList<ArrayList<Children>>() //市
private val options3Items = ArrayList<ArrayList<ArrayList<ChildrenX>>>() //区
private var larIdType = "01"//证件类型
private var merRegDistCode = ""//商户地区代码
private var options1 = -1
private var options2 = -1
private var options3 = -1
private var id = ""//商户id
private var auditStatus = -1//0-草稿 1-审核通过 2-审核驳回 3-审核中 4-合同审核中 5-签约中
private var signUrl = ""
private var selectPicType = 0
private var idCardFront = ""//身份证正面
private var idCardBack = ""//身份证背面
override fun getLayoutId(): Int {
return R.layout.activity_remit_account
}
override fun initView(savedInstanceState: Bundle?) {
ImmersionBar.with(this).statusBarDarkFont(true).init()
setMarginTop(tb_remit_account)
val t =
GsonUtils.fromJson(GetJsonDataUtil.getJson(this, "cities.json"), CitiesBean::class.java)
//添加一级数据
options1Items.addAll(t.cities)
options1Items.forEach {
val city = ArrayList<Children>()//二级
city.addAll(it.children)
//添加二级数据
options2Items.add(city)
val childrenXList = ArrayList<ArrayList<ChildrenX>>()//三级
it.children.forEach { itt ->
val areaList = ArrayList<ChildrenX>()
if (itt.children == null || itt.children!!.isEmpty())
areaList.add(ChildrenX("", ""))//如果无地区数据,建议添加空字符串,防止数据为null 导致三个选项长度不匹配造成崩溃
else
areaList.addAll(itt.children!!)
childrenXList.add(areaList)
}
//添加三级数据
options3Items.add(childrenXList)
}
}
override fun initListener() {
tb_remit_account.setOnTitleBarListener(object : OnTitleBarListener {
override fun onLeftClick(view: View?) {
onBackPressed()
}
override fun onTitleClick(view: View?) {
}
override fun onRightClick(view: View?) {
}
})
iv_sfz_zm.setOnLongClickListener(this)
iv_sfz_bm.setOnLongClickListener(this)
}
override fun onLongClick(v: View?): Boolean {
when (v?.id) {
R.id.iv_sfz_zm -> {
PopupWindowUtils.get().showConfirmPop(this, "是否更换当前图片?") {
onClick(tv_sfz_zm)
}
}
R.id.iv_sfz_bm -> {
PopupWindowUtils.get().showConfirmPop(this, "是否更换当前图片?") {
onClick(tv_sfz_bm)
}
}
}
return false
}
override fun onClick(v: View?) {
when (v?.id) {
R.id.ctv_personal -> {
if (DoubleClicksUtils.get().isFastDoubleClick)
return
ctv_personal.isChecked = true
ctv_enterprise.isChecked = false
ll_public.visibility = View.GONE
rl_legal.visibility = View.VISIBLE
}
R.id.ctv_enterprise -> {
if (DoubleClicksUtils.get().isFastDoubleClick)
return
ctv_personal.isChecked = false
ctv_enterprise.isChecked = true
ll_public.visibility = View.VISIBLE
rl_legal.visibility = View.GONE
}
R.id.ctv_yes -> {
if (DoubleClicksUtils.get().isFastDoubleClick)
return
ctv_yes.isChecked = true
ctv_no.isChecked = false
ll_card.visibility = View.GONE
}
R.id.ctv_no -> {
if (DoubleClicksUtils.get().isFastDoubleClick)
return
ctv_no.isChecked = true
ctv_yes.isChecked = false
ll_card.visibility = View.VISIBLE
}
R.id.tv_sfz_zm -> {//负责人身份证-正面
if (DoubleClicksUtils.get().isFastDoubleClick)
return
val intent = Intent(this, SelectPicActivity::class.java)
intent.putExtra("selNum", 1)
intent.putExtra("selMode", PictureConfig.SINGLE)
picLauncher.launch(intent)
selectPicType = 0
}
R.id.tv_sfz_bm -> {//负责人身份证-背面
if (DoubleClicksUtils.get().isFastDoubleClick)
return
val intent = Intent(this, SelectPicActivity::class.java)
intent.putExtra("selNum", 1)
intent.putExtra("selMode", PictureConfig.SINGLE)
picLauncher.launch(intent)
selectPicType = 1
}
R.id.iv_sfz_zm -> {
if (DoubleClicksUtils.get().isFastDoubleClick)
return
PopupWindowUtils.get().showPhotoPop(idCardFront, this, ll_content)
}
R.id.iv_sfz_bm -> {
if (DoubleClicksUtils.get().isFastDoubleClick)
return
PopupWindowUtils.get().showPhotoPop(idCardBack, this, ll_content)
}
R.id.iv_search -> {//查询银行卡信息
if (DoubleClicksUtils.get().isFastDoubleClick)
return
if (!TextUtils.isEmpty(et_acctNo.text.toString()))
getBankCardInfo()
}
R.id.tv_id_type -> {//证件类型
if (DoubleClicksUtils.get().isFastDoubleClick)
return
showIdTypePop()
}
R.id.tv_id_start -> {//身份证开始日期
if (DoubleClicksUtils.get().isFastDoubleClick)
return
PopupWindowUtils.get().showSelDateTimePop(this, 2) {
tv_id_start.text = DateFormatUtils.get().formatDate(it)
}
}
R.id.tv_id_end -> {//身份证结束日期
if (DoubleClicksUtils.get().isFastDoubleClick)
return
PopupWindowUtils.get().showSelDateTimePop(this, 2) {
tv_id_end.text = DateFormatUtils.get().formatDate(it)
}
}
R.id.tv_license_start -> {//营业执照开始日期
if (DoubleClicksUtils.get().isFastDoubleClick)
return
PopupWindowUtils.get().showSelDateTimePop(this, 2) {
tv_license_start.text = DateFormatUtils.get().formatDate(it)
}
}
R.id.tv_license_end -> {//营业执照结束日期
if (DoubleClicksUtils.get().isFastDoubleClick)
return
PopupWindowUtils.get().showSelDateTimePop(this, 2) {
tv_license_end.text = DateFormatUtils.get().formatDate(it)
}
}
R.id.tv_city -> {//地区
if (DoubleClicksUtils.get().isFastDoubleClick)
return
val pvOptions: OptionsPickerView<*> = OptionsPickerBuilder(
this
) { options1, options2, options3, v -> //返回的分别是三个级别的选中位置
tv_city.text =
"${options1Items[options1].pickerViewText}/${options2Items[options1][options2].pickerViewText}/${options3Items[options1][options2][options3].pickerViewText}"
merRegDistCode =
if (TextUtils.isEmpty(options3Items[options1][options2][options3].value)) options2Items[options1][options2].value!! else
options3Items[options1][options2][options3].value!!
this.options1 = options1
this.options2 = options2
this.options3 = options3
}
.setTitleText("城市选择")
.setDividerColor(Color.BLACK)
.setTextColorCenter(Color.BLACK) //设置选中项文字颜色
.setContentTextSize(14)
.setTitleSize(15)
.setTitleBgColor(Color.parseColor("#ffffff"))
.setSubCalSize(13)
.setCancelColor(Color.parseColor("#3477fc"))
.setSubmitColor(Color.parseColor("#3477fc"))
.build<Any>()
pvOptions.setPicker(
options1Items as List<Nothing>?,
options2Items as List<Nothing>?,
options3Items as List<Nothing>?
)
if (options1 != -1 && options2 != -1 && options3 != -1)
pvOptions.setSelectOptions(options1, options2, options3)
pvOptions.show()
}
R.id.btn_commit -> {
if (DoubleClicksUtils.get().isFastDoubleClick)
return
when (auditStatus) {
4 -> {
if (TextUtils.isEmpty(signUrl)) {
if (isComplete())
if (TextUtils.isEmpty(id))
new()
else
update()
else
ToastUtils.showShort("必填项不能为空")
} else {
val intent = Intent(this, SignActivity::class.java)
intent.putExtra("signUrl", signUrl)
startActivity(intent)
}
}
else -> {
if (isComplete())
if (TextUtils.isEmpty(id))
new()
else
update()
else
ToastUtils.showShort("必填项不能为空")
}
}
}
}
}
private val picLauncher =
registerForActivityResult(ActivityResultContracts.StartActivityForResult()) {
when (it.resultCode) {
RESULT_OK -> {
val bundle = it.data!!.extras
ossPost(bundle!!.getString("name")!!, bundle.getString("path")!!)
}
}
}
/**
* 上传图片
*/
private fun ossPost(imgName: String, imgLocalPath: String) {
val dialog = Dialog(this, R.style.Dialog)
val contentView = View.inflate(this, R.layout.layout_progress_dialog, null)
dialog.setContentView(contentView)
dialog.setCancelable(false)
dialog.setCanceledOnTouchOutside(false)
val progressBar = contentView.findViewById<ProgressBar>(R.id.pb_progress)
dialog.show()
val objectKey = "waej3/" + SPUtils.getInstance()
.getInt("shopId") + "/" + System.currentTimeMillis() + imgName
val imgUrl = UrlConstants.BaseOssUrl + objectKey
when (selectPicType) {
0 -> {
Glide.with(this).load(imgLocalPath).into(iv_sfz_zm)
idCardFront = imgUrl
tv_sfz_zm.visibility = View.GONE
}
1 -> {
Glide.with(this).load(imgLocalPath).into(iv_sfz_bm)
idCardBack = imgUrl
tv_sfz_bm.visibility = View.GONE
}
//// 3 -> {
//// Glide.with(this@ShopInfoActivity).load(imgLocalPath).into(iv_logo)
////
//// }
// 4 -> {
// Glide.with(this@ShopInfoActivity).load(imgLocalPath).into(iv_door_head)
// doorPhoto = imgUrl
// tv_door_head.visibility = View.GONE
// }
//
// 5 -> {
// Glide.with(this@ShopInfoActivity).load(imgLocalPath).into(iv_shop_pic)
// shopImage = imgUrl
// tv_shop_pic.visibility = View.GONE
// }
}
OssUtils.get().asyncPutImage(objectKey, imgLocalPath, this,
object : OssUtils.OnOssCallBackListener {
override fun onSuccess(float: Float) {
dialog.dismiss()
ToastUtils.showShort("上传成功,用时:${float}秒")
}
override fun onFailed(e: String) {
dialog.dismiss()
ToastUtils.showShort(e)
}
override fun onProgress(progress: Int) {
progressBar.progress = progress
}
})
}
/**
* 证件类型弹窗
*/
private fun showIdTypePop() {
val popWindow = PopWindow.Builder(this)
.setView(R.layout.layout_pop_made_type)
.setWidthAndHeight(
ViewGroup.LayoutParams.MATCH_PARENT,
ViewGroup.LayoutParams.WRAP_CONTENT
)
.setOutsideTouchable(true)
.setAnimStyle(R.style.BottomAnimation)
.setBackGroundLevel(0.5f)
.setChildrenView { contentView, pop ->
val rv_sel_role = contentView.findViewById<RecyclerView>(R.id.rv_sel_role)
contentView.findViewById<TextView>(R.id.tv_title).text = "证件类型"
if (BarUtils.isNavBarVisible(window)) {
BarUtils.setNavBarLightMode(window, true)
val layoutParams = rv_sel_role.layoutParams as LinearLayout.LayoutParams
layoutParams.bottomMargin = BarUtils.getNavBarHeight()
rv_sel_role.layoutParams = layoutParams
}
rv_sel_role.layoutManager = LinearLayoutManager(this)
val items = ArrayList<IdTypeBean>()
items.add(IdTypeBean("身份证", "01"))
items.add(IdTypeBean("护照", "02"))
items.add(IdTypeBean("港澳通行证", "03"))
items.add(IdTypeBean("台胞证", "04"))
items.add(IdTypeBean("其它证件", "99"))
val adapter = IdTypeAdapter(items, tv_id_type.text.toString())
adapter.bindToRecyclerView(rv_sel_role)
adapter.emptyView = layoutInflater.inflate(R.layout.layout_empty_view, null)
adapter.setOnItemClickListener { _, _, position ->
tv_id_type.text = items[position].name
larIdType = items[position].id
pop.dismiss()
}
contentView.findViewById<View>(R.id.tv_cancel).setOnClickListener {
pop.dismiss()
}
}
.create()
popWindow.isClippingEnabled = false
popWindow.showAtLocation(ll_content, Gravity.BOTTOM, 0, 0)
}
/**
* 新增商户
*/
private fun new() {
LoadingUtils.showLoading(this, "加载中...")
val params = HashMap<String, Any>()
params["merRegName"] = et_merRegName.text.toString()//注册名称
params["merBizName"] = et_merBizName.text.toString()//经营名称
params["merContactName"] = et_merContactName.text.toString()//联系人
params["merContactMobile"] = et_merContactMobile.text.toString()//手机号
params["merRegDistCode"] = merRegDistCode//地区代码
val stringBuilder = StringBuilder()
stringBuilder.append(options1)
stringBuilder.append(",")
stringBuilder.append(options2)
stringBuilder.append(",")
stringBuilder.append(options3)
params["merRegDistCodeCache"] = stringBuilder.toString()//地区代码游标
params["merRegAddr"] = et_merRegAddr.text.toString()//详细地址
params["larIdType"] = larIdType//证件类型
params["larName"] = et_larName.text.toString()//姓名
params["larIdcard"] = et_larIdcard.text.toString()//证件号码
params["larIdcardStDt"] = tv_id_start.text.toString()//证件开始日期
params["larIdcardExpDt"] = tv_id_end.text.toString()//证件有效期
if (ctv_personal.isChecked) {
params["acctTypeCode"] = 58
if (ctv_yes.isChecked)
params["isSamePerson"] = 1
if (ctv_no.isChecked) {
params["isSamePerson"] = 0
params["idCardFront"] = idCardFront
params["idCardBack"] = idCardBack
}
}
if (ctv_enterprise.isChecked) {
params["acctTypeCode"] = 57
params["merBlisName"] = et_merBlisName.text.toString()//营业执照名称
params["merBlis"] = et_merBlis.text.toString()//营业执照号
params["merBlisStDt"] = tv_license_start.text.toString()//营业执照开始日期
params["merBlisExpDt"] = tv_license_end.text.toString()////营业执照有效期
}
params["acctName"] = et_acctName.text.toString()//银行卡名称
params["openningBankCode"] = et_openningBankCode.text.toString()//开户行号
params["openningBankName"] = et_openningBankName.text.toString()//开户行名称
params["clearingBankCode"] = et_clearingBankCode.text.toString()//清算行号
params["acctNo"] = et_acctNo.text.toString()//银行卡号
params["remark"] = et_remark.text.toString()
RetrofitUtils.get()
.postJson(NewMerchantUrl, params, this, object : RetrofitUtils.OnCallBackListener {
override fun onSuccess(s: String) {
LogUtils.d("tag", s)
val t = GsonUtils.fromJson(s, RemitAccountResponse::class.java)
put(t.data!!.id!!.toInt())
Thread {
kotlin.run {
}
}.start()
}
override fun onFailed(e: String) {
ToastUtils.showShort(e)
}
})
}
/**
* 修改
*/
private fun update() {
LoadingUtils.showLoading(this, "加载中...")
val params = HashMap<String, Any>()
params["id"] = id
params["merRegName"] = et_merRegName.text.toString()//注册名称
params["merBizName"] = et_merBizName.text.toString()//经营名称
params["merContactName"] = et_merContactName.text.toString()//联系人
params["merContactMobile"] = et_merContactMobile.text.toString()//手机号
params["merRegDistCode"] = merRegDistCode//地区代码
val stringBuilder = StringBuilder()
stringBuilder.append(options1)
stringBuilder.append(",")
stringBuilder.append(options2)
stringBuilder.append(",")
stringBuilder.append(options3)
params["merRegDistCodeCache"] = stringBuilder.toString()//地区代码游标
params["merRegAddr"] = et_merRegAddr.text.toString()//详细地址
params["larIdType"] = larIdType//证件类型
params["larName"] = et_larName.text.toString()//姓名
params["larIdcard"] = et_larIdcard.text.toString()//证件号码
params["larIdcardStDt"] = tv_id_start.text.toString()//证件开始日期
params["larIdcardExpDt"] = tv_id_end.text.toString()//证件有效期
if (ctv_personal.isChecked) {
params["acctTypeCode"] = 58
if (ctv_yes.isChecked)
params["isSamePerson"] = 1
if (ctv_no.isChecked) {
params["isSamePerson"] = 0
params["idCardFront"] = idCardFront
params["idCardBack"] = idCardBack
}
}
if (ctv_enterprise.isChecked) {
params["acctTypeCode"] = 57
params["merBlisName"] = et_merBlisName.text.toString()//营业执照名称
params["merBlis"] = et_merBlis.text.toString()//营业执照号
params["merBlisStDt"] = tv_license_start.text.toString()//营业执照开始日期
params["merBlisExpDt"] = tv_license_end.text.toString()////营业执照有效期
}
params["acctName"] = et_acctName.text.toString()//银行卡名称
params["openningBankCode"] = et_openningBankCode.text.toString()//开户行号
params["openningBankName"] = et_openningBankName.text.toString()//开户行名称
params["clearingBankCode"] = et_clearingBankCode.text.toString()//清算行号
params["acctNo"] = et_acctNo.text.toString()//银行卡号
params["remark"] = et_remark.text.toString()
RetrofitUtils.get()
.putJson(NewMerchantUrl, params, this, object : RetrofitUtils.OnCallBackListener {
override fun onSuccess(s: String) {
LogUtils.d("tag", s)
val t = GsonUtils.fromJson(s, RemitAccountResponse::class.java)
Handler().post {
put(id.toInt())
}
}
override fun onFailed(e: String) {
ToastUtils.showShort(e)
}
})
}
/**
* 商户列表
*/
private fun getList() {
RetrofitUtils.get()
.getJson(MerchantListUrl, HashMap(), this, object : RetrofitUtils.OnCallBackListener {
override fun onSuccess(s: String) {
LogUtils.d("tag", s)
val t = GsonUtils.fromJson(s, RemitAccountListResponse::class.java)
if (t.rows != null && t.rows!!.isNotEmpty()) {
id = t.rows!![0].id!!
et_merRegName.setText(t.rows!![0].merRegName)
et_merBizName.setText(t.rows!![0].merBizName)
et_merContactName.setText(t.rows!![0].merContactName)
et_merContactMobile.setText(t.rows!![0].merContactMobile)
merRegDistCode = t.rows!![0].merRegDistCode!!
if (!TextUtils.isEmpty(t.rows!![0].merRegDistCodeCache)) {
val options = t.rows!![0].merRegDistCodeCache!!.split(",")
options1 = options[0].toInt()
options2 = options[1].toInt()
options3 = options[2].toInt()
tv_city.text =
"${options1Items[options1].pickerViewText}/${options2Items[options1][options2].pickerViewText}/${options3Items[options1][options2][options3].pickerViewText}"
}
et_merRegAddr.setText(t.rows!![0].merRegAddr)
larIdType = t.rows!![0].larIdType!!
tv_id_type.text = when (larIdType) {
"01" -> "身份证"
"02" -> "护照"
"03" -> "港澳通行证"
"04" -> "台胞证"
"99" -> "其它证件"
else -> "身份证"
}
et_larName.setText(t.rows!![0].larName)
et_larIdcard.setText(t.rows!![0].larIdcard)
tv_id_start.text = t.rows!![0].larIdcardStDt
tv_id_end.text = t.rows!![0].larIdcardExpDt
when (t.rows!![0].acctTypeCode) {
"58" -> {
ctv_personal.isChecked
when (t.rows!![0].isSamePerson) {
0 -> {
ctv_no.isChecked = true
ll_card.visibility = View.VISIBLE
idCardFront = t.rows!![0].idCardFront!!
Glide.with(this@RemitAccountActivity).load(idCardFront)
.into(iv_sfz_zm)
idCardBack = t.rows!![0].idCardBack!!
Glide.with(this@RemitAccountActivity).load(idCardBack)
.into(iv_sfz_bm)
}
1 -> {
ctv_yes.isChecked = true
}
}
}
"57" -> {
ctv_enterprise.isChecked
ll_public.visibility = View.VISIBLE
et_merBlisName.setText(t.rows!![0].merBlisName)
et_merBlis.setText(t.rows!![0].merBlis)
tv_license_start.text = t.rows!![0].merBlisStDt!!
tv_license_end.text = t.rows!![0].merBlisExpDt!!
}
}
et_acctName.setText(t.rows!![0].acctName)
et_acctNo.setText(t.rows!![0].acctNo)
et_openningBankCode.setText(t.rows!![0].openningBankCode)
et_openningBankName.setText(t.rows!![0].openningBankName)
et_clearingBankCode.setText(t.rows!![0].clearingBankCode)
et_remark.setText(t.rows!![0].remark)
auditStatus = t.rows!![0].auditStatus!!
getInfo()
}
if (TextUtils.isEmpty(et_merRegName.text.toString()))
et_merRegName.setText(intent.getStringExtra("businessName"))
if (TextUtils.isEmpty(et_merBizName.text.toString()))
et_merBizName.setText(intent.getStringExtra("fullname"))
if (TextUtils.isEmpty(et_merContactName.text.toString()))
et_merContactName.setText(intent.getStringExtra("contactName"))
if (TextUtils.isEmpty(et_merContactMobile.text.toString()))
et_merContactMobile.setText(intent.getStringExtra("contactPhone"))
}
override fun onFailed(e: String) {
ToastUtils.showShort(e)
}
})
}
/**
* 获取商户信息
*/
private fun getInfo() {
LoadingUtils.showLoading(this, "加载中...")
Api.getInstance().getApiService()
.getMerchantInfo(id.toInt())
.subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread())
.subscribe(object : BaseResourceObserver<String>() {
override fun onComplete() {
LoadingUtils.dismissLoading()
}
override fun onSubscribe(d: Disposable) {
}
override fun onNext(s: String) {
LogUtils.d("tag", s)
val t = GsonUtils.fromJson(s, RemitAccountResponse::class.java)
when (t.code) {
200 -> {
auditStatus = t.data!!.auditStatus!!
if (!TextUtils.isEmpty(t.data!!.signUrl))
signUrl = t.data!!.signUrl!!
when (auditStatus) {
1 -> {
tv_merCupNo.text =
if (t.data!!.merCupNo == null) "" else t.data!!.merCupNo!!
rl_merCupNo.visibility = View.VISIBLE
}
2 -> {
PopupWindowUtils.get().showConfirmPop(
this@RemitAccountActivity,
t.data!!.failCause!!
) {
}
rl_review.visibility = View.GONE
nsv_remit.visibility = View.VISIBLE
btn_commit.text = "保存"
}
3 -> {//3-审核中
rl_review.visibility = View.VISIBLE
nsv_remit.visibility = View.GONE
tv_review.text = "店铺信息已提交审核\n审核时间一般在1~3个工作日"
btn_commit.visibility = View.GONE
}
4 -> {//4-合同审核中
rl_review.visibility = View.VISIBLE
nsv_remit.visibility = View.GONE
tv_review.text = "签约中\n请前往签约界面进行签约!"
btn_commit.text = "去签约"
}
else -> {
rl_review.visibility = View.GONE
nsv_remit.visibility = View.VISIBLE
btn_commit.text = "保存"
}
}
}
500 -> {
rl_review.visibility = View.GONE
nsv_remit.visibility = View.VISIBLE
btn_commit.text = "保存"
ToastUtils.showShort(t.msg)
}
401 -> {
PopupWindowUtils.get().showLoginOutTimePop(this@RemitAccountActivity)
}
else -> {
if (t.msg != null)
ToastUtils.showShort(t.msg)
else
ToastUtils.showShort("异常(代码:${t.code})")
}
}
}
override fun onError(throwable: Throwable) {
ToastUtils.showShort(throwable.message)
LoadingUtils.dismissLoading()
}
})
}
/**
* 提交合同
*/
private fun put(id: Int) {
LoadingUtils.showLoading(this, "加载中...")
Api.getInstance().getApiService()
.putContract(id)
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(object : BaseResourceObserver<String>() {
override fun onComplete() {
}
override fun onSubscribe(d: Disposable) {
}
override fun onNext(s: String) {
LogUtils.d("tag", s)
val response = GsonUtils.fromJson(s, ContractResponse::class.java)
when (response.code) {
200 -> {
if (TextUtils.isEmpty(response.data!!.signUrl))
ToastUtils.showShort(response.msg)
else {
val intent =
Intent(this@RemitAccountActivity, SignActivity::class.java)
intent.putExtra("signUrl", response.data!!.signUrl)
startActivity(intent)
}
}
401 -> {
PopupWindowUtils.get().showLoginOutTimePop(this@RemitAccountActivity)
}
else -> {
if (response.msg != null)
ToastUtils.showShort(response.msg)
else
ToastUtils.showShort("异常(代码:${response.code})")
}
}
LoadingUtils.dismissLoading()
}
override fun onError(throwable: Throwable) {
ToastUtils.showShort(throwable.message!!)
LoadingUtils.dismissLoading()
}
})
}
/**
* 根据银行卡号查询卡信息
*/
private fun getBankCardInfo() {
LoadingUtils.showLoading(this, "加载中...")
val params = HashMap<String, String>()
params["cardNo"] = et_acctNo.text.toString()
RetrofitUtils.get()
.getJson(GetBankCardInfoUrl, params, this, object : RetrofitUtils.OnCallBackListener {
override fun onSuccess(s: String) {
LogUtils.d("tag", s)
val t = GsonUtils.fromJson(s, BankCardInfoResponse::class.java)
et_acctName.setText(t.data!!.cardName)
et_openningBankCode.setText(t.data!!.bankCode)
et_openningBankName.setText(t.data!!.bankName)
et_clearingBankCode.setText(t.data!!.clearingBankCode)
ToastUtils.showShort(t.msg)
}
override fun onFailed(e: String) {
ToastUtils.showShort(e)
}
})
}
private fun isComplete(): Boolean {
return when {
TextUtils.isEmpty(et_merRegName.text.toString()) -> false
TextUtils.isEmpty(et_merBizName.text.toString()) -> false
TextUtils.isEmpty(et_merContactName.text.toString()) -> false
TextUtils.isEmpty(et_merContactMobile.text.toString()) -> false
TextUtils.isEmpty(merRegDistCode) -> false
TextUtils.isEmpty(et_merRegAddr.text.toString()) -> false
TextUtils.isEmpty(et_larName.text.toString()) -> false
TextUtils.isEmpty(et_larIdcard.text.toString()) -> false
TextUtils.isEmpty(tv_id_start.text.toString()) -> false
TextUtils.isEmpty(tv_id_end.text.toString()) -> false
TextUtils.isEmpty(et_acctName.text.toString()) -> false
TextUtils.isEmpty(et_openningBankCode.text.toString()) -> false
TextUtils.isEmpty(et_openningBankName.text.toString()) -> false
TextUtils.isEmpty(et_clearingBankCode.text.toString()) -> false
TextUtils.isEmpty(et_acctNo.text.toString()) -> false
ctv_personal.isChecked && ctv_no.isChecked -> when {
TextUtils.isEmpty(idCardFront) -> false
TextUtils.isEmpty(idCardBack) -> false
else -> true
}
ctv_enterprise.isChecked -> when {
TextUtils.isEmpty(et_merBlisName.text.toString()) -> false
TextUtils.isEmpty(et_merBlis.text.toString()) -> false
TextUtils.isEmpty(tv_license_start.text.toString()) -> false
TextUtils.isEmpty(tv_license_end.text.toString()) -> false
else -> true
}
else -> true
}
}
override fun onBackPressed() {
super.onBackPressed()
EventBus.getDefault().post(EBLaKaLaBack(true))
}
override fun onResume() {
super.onResume()
getList()
}
} | 0 | Kotlin | 0 | 0 | 8c2e9928f6c47484bec7a5beca32ed4b10200f9c | 37,267 | wananexiu | Mulan Permissive Software License, Version 2 |
app/src/main/java/com/inging/notis/extension/ExImage.kt | prdotk | 372,680,673 | false | null | package com.inging.notis.extension
import android.content.Context
import android.graphics.Bitmap
import android.graphics.BitmapFactory
import android.graphics.Canvas
import android.graphics.drawable.BitmapDrawable
import android.graphics.drawable.Drawable
import android.os.Build
import android.util.Log
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
import java.io.File
import java.io.FileNotFoundException
import java.io.FileOutputStream
import java.io.IOException
/**
* Created by annasu on 2021/04/29.
*/
suspend fun String.loadBitmap(context: Context): Bitmap? {
return try {
withContext(Dispatchers.Default) {
val imageFile = File(context.cacheDir, this@loadBitmap)
var bitmap: Bitmap? = null
if (imageFile.exists()) {
bitmap = BitmapFactory.decodeFile(imageFile.absolutePath)
}
bitmap
}
} catch (e: Exception) {
null
}
}
fun BitmapDrawable.saveFile(context: Context, dir: String): String {
return bitmap.saveFile(context, dir)
}
/**
* 이미지 변환
*/
fun Bitmap.saveFile(context: Context, dir: String): String {
val storage = "${context.cacheDir}/$dir"
val imgFile = File(storage, "temp")
var result = ""
try {
File(storage).mkdirs()
imgFile.createNewFile()
val out = FileOutputStream(imgFile)
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
compress(Bitmap.CompressFormat.WEBP_LOSSY, 75, out)
} else {
compress(Bitmap.CompressFormat.WEBP, 75, out)
// compress(Bitmap.CompressFormat.PNG, 70, out)
}
out.close()
// 파일명을 파일 사이즈로 하고 체크
val fileSize = imgFile.length().toString()
val newFile = File(storage, fileSize).apply {
delete()
}
imgFile.renameTo(newFile)
result = "$dir/$fileSize"
} catch (e: FileNotFoundException) {
Log.e("saveBitmapToJpg", "FileNotFoundException : " + e.message)
} catch (e: IOException) {
Log.e("saveBitmapToJpg", "IOException : " + e.message)
}
Log.d("imgPath", context.cacheDir.absolutePath + "/" + dir)
return result
}
// drawable -> bitmap
fun Drawable.getBitmap(): Bitmap? {
val bmp = Bitmap.createBitmap(
intrinsicWidth,
intrinsicHeight,
Bitmap.Config.ARGB_8888
)
val canvas = Canvas(bmp)
setBounds(0, 0, canvas.width, canvas.height)
draw(canvas)
return bmp
} | 0 | Kotlin | 0 | 0 | 15101b8f1a844adc892c2b4ce04a39790b41738d | 2,504 | notis | MIT License |
src/main/kotlin/com/github/kotlinz/kotlinz/Kinds.kt | kotlinz | 60,540,718 | false | null | package com.github.kotlinz.kotlinz
interface K1<T, A> {}
interface K2<T, A, B>: K1<K1<T, A>, B> {}
interface K3<T, A, B, C>: K1<K2<T, A, B>, C> {}
interface K4<T, A, B, C, D>: K1<K3<T, A, B, C>, D> {}
interface K5<T, A, B, C, D, E>: K1<K4<T, A, B, C, D>, E> {}
| 0 | Kotlin | 5 | 46 | 14f4e8f26778b9b609cdcb9e52fca7bb272dcdbf | 262 | kotlinz | Apache License 2.0 |
worldwind/src/commonMain/kotlin/earth/worldwind/ogc/ows/OwsNamespace.kt | WorldWindEarth | 488,505,165 | false | {"Kotlin": 2798182, "JavaScript": 459619, "HTML": 108987, "CSS": 8778} | package earth.worldwind.ogc.ows
const val OWS20_NAMESPACE = "http://www.opengis.net/ows/2.0"
const val OWS20_PREFIX = "ows"
const val XML_NAMESPACE = "http://www.w3.org/2001/XMLSchema"
const val XML_PREFIX = "xml" | 22 | Kotlin | 12 | 98 | b5ee69cdd30f6c6a90bf3bec638a3bc5bdb0fbc2 | 214 | WorldWindKotlin | Apache License 2.0 |
src/main/kotlin/dev/nyman/voikkols/parser/Parser.kt | isofore | 538,580,937 | false | null | package dev.nyman.voikkols.parser
interface Parser<Out> {
fun parse(text: String): Out
}
| 0 | Kotlin | 0 | 0 | db1311df5f254549bc4c4b9ace9b28144c0dd193 | 94 | voikko-ls | MIT License |
src/main/kotlin/parsix/core/CommonParsers.kt | diegopacheco | 367,993,850 | true | {"Kotlin": 62820} | package parsix.core
/**
* The most basic parse, it will always succeed with [result]
*/
fun <I, O> succeed(result: O): Parse<I, O> =
{ _ -> Ok(result) }
/**
* @see notNullable
*/
object RequiredError : TerminalError
/**
* Enhance [parse] so that it can handle a nullable input.
* The final parser will return [RequiredError] if the input is null.
*/
inline fun <I : Any, O> notNullable(crossinline parse: Parse<I, O>): Parse<I?, O> =
{ inp ->
if (inp == null)
RequiredError
else
parse(inp)
}
/**
* Enhance [parse] so that it can handle a nullable input.
* If the input is null, it will use [default] as value.
*/
inline fun <I : Any, O : Any> nullable(
default: O,
crossinline parse: Parse<I, O>
): Parse<I?, O> =
{ inp ->
if (inp == null)
Ok(default)
else
parse(inp)
}
/**
* Enhance [parse] so that it can handle a nullable input.
* If the input is null, that will be the result.
*/
inline fun <I : Any, O : Any> nullable(crossinline parse: Parse<I, O>): Parse<I?, O?> =
{ inp ->
if (inp == null)
Ok(null)
else
parse(inp)
}
/**
* Parse [Any] into [String].
* @return [TypedError] in case of failure.
*/
fun parseString(inp: Any): Parsed<String> =
parseTyped(inp, "string")
/**
* Parse [Any] into [Boolean].
* @return [TypedError] in case of failure.
*/
fun parseBool(inp: Any): Parsed<Boolean> =
parseTyped(inp, "bool")
/**
* @see parseTyped
*/
data class TypedError(val inp: Any, val type: String) : TerminalError
/**
* Generic parser, it can be used to easily convert from [Any] to a specific type [T]
* @return [TypedError] in case of failure
*/
inline fun <reified T> parseTyped(inp: Any, type: String): Parsed<T> =
if (inp is T)
Ok(inp)
else
TypedError(inp, type)
/**
* @see parseMin
*/
data class MinError<T : Comparable<T>>(val inp: Any, val min: T) : TerminalError
/**
* Make a `parse` that ensures a [Comparable] is greater than or equal to [min]
* and returns [MinError] otherwise
*
* A common case is to use it with numbers, for example:
* ```
* parseMin(10)(4) // => MinError(10)
* parseMin(10.5)(11.0) // => Ok(10.5)
* ```
*
* @see parseBetween if you need a range
*/
fun <T : Comparable<T>> parseMin(min: T): Parse<T, T> = { inp ->
if (inp < min)
MinError(inp, min)
else
Ok(inp)
}
/**
* @see parseMax
*/
data class MaxError<T : Comparable<T>>(val inp: Any, val max: T) : TerminalError
/**
* Make a `parse` that ensures a [Comparable] is less a than or equal to [max]
* and returns [MaxError] otherwise
*
* A common case is to use it with numbers, for example:
* ```
* parseMax(10)(4) // => MaxError(10)
* parseMin(10.5)(11.0) // => Ok(10.5)
* ```
*
* @see parseBetween if you need a range
*/
fun <T : Comparable<T>> parseMax(max: T): Parse<T, T> = { inp ->
if (inp > max)
MaxError(inp, max)
else
Ok(inp)
}
data class BetweenError<T : Comparable<T>>(
val inp: Any,
val min: T,
val max: T
) : TerminalError
/**
* Make a `parse` that ensures [Comparable] is between [min] and [max], inclusive,
* and returns [BetweenError] otherwise.
*
* @see parseMin
* @see parseMax
*/
fun <T : Comparable<T>> parseBetween(min: T, max: T): Parse<T, T> = { inp ->
when {
inp < min ->
BetweenError(inp, min, max)
inp > max ->
BetweenError(inp, min, max)
else ->
Ok(inp)
}
}
/**
* @see [parseInt]
*/
data class IntError(val inp: Any) : TerminalError
/**
* Parse an [Any] into a [Int].
* It supports the following types:
* - [Int], returns it
* - [UInt], value must be no greater than [Int.MAX_VALUE], [MaxError] otherwise
* - [Long], value must be between [Int.MIN_VALUE] and [Int.MAX_VALUE], [BetweenError] otherwise
* - [Double], value must be between [Int.MIN_VALUE] and [Int.MAX_VALUE], [BetweenError] otherwise
* - [String], must be a valid int, [IntError] otherwise
*
* Anything else will fail with [IntError]
*/
fun parseInt(inp: Any): Parsed<Int> =
when (inp) {
is String ->
try {
Ok(inp.toInt())
} catch (ex: NumberFormatException) {
IntError(inp)
}
is Int ->
Ok(inp)
is UInt ->
if (inp > Int.MAX_VALUE.toUInt())
MaxError(inp, Int.MAX_VALUE)
else
Ok(inp.toInt())
is Long ->
if (Int.MIN_VALUE > inp || Int.MAX_VALUE < inp)
BetweenError(inp, Int.MIN_VALUE, Int.MAX_VALUE)
else
Ok(inp.toInt())
is Double ->
if (Int.MIN_VALUE > inp || Int.MAX_VALUE < inp)
BetweenError(inp, Int.MIN_VALUE, Int.MAX_VALUE)
else
Ok(inp.toInt())
else ->
IntError(inp)
}
/**
* @see [parseUInt]
*/
data class UIntError(val inp: Any) : TerminalError
/**
* Parse an [Any] into a [UInt].
* It supports the following types:
* - [UInt], returns it
* - [Int], value cannot be less than 0, [MinError] otherwise
* - [Long], value must be between 0 and [UInt.MAX_VALUE], [BetweenError] otherwise
* - [String], must be a valid unsigned int, [UIntError] otherwise
*
* Anything else will fail with [UIntError]
*/
fun parseUInt(inp: Any): Parsed<UInt> =
when (inp) {
is String ->
try {
Ok(inp.toUInt())
} catch (ex: NumberFormatException) {
UIntError(inp)
}
is UInt ->
Ok(inp)
is Int ->
if (inp < 0)
MinError(inp, 0)
else
Ok(inp.toUInt())
is Long ->
if (inp < 0 || inp > UInt.MAX_VALUE.toLong())
BetweenError(inp, UInt.MIN_VALUE, UInt.MAX_VALUE)
else
Ok(inp.toUInt())
is Double ->
if (inp < UInt.MIN_VALUE.toDouble() || inp > UInt.MAX_VALUE.toDouble())
BetweenError(inp, UInt.MIN_VALUE, UInt.MAX_VALUE)
else
Ok(inp.toUInt())
else ->
UIntError(inp)
}
/**
* @see [parseLong]
*/
data class LongError(val inp: Any) : TerminalError
/**
* Parse an [Any] into a [Long].
* It supports the following types:
* - [Long], [Int], [UInt]
* - [Double], must be between [Long.MIN_VALUE] and [Long.MAX_VALUE], [BetweenError] otherwise
* - [String], must be a valid long int, [LongError] otherwise
*
* Anything else will fail with [LongError]
*/
fun parseLong(inp: Any): Parsed<Long> =
when (inp) {
is String ->
try {
Ok(inp.toLong())
} catch (ex: NumberFormatException) {
LongError(inp)
}
is Long ->
Ok(inp)
is UInt ->
Ok(inp.toLong())
is Int ->
Ok(inp.toLong())
is Double ->
if (inp < Long.MIN_VALUE.toDouble() || inp > Long.MAX_VALUE.toDouble())
BetweenError(inp, Long.MIN_VALUE, Long.MAX_VALUE)
else
Ok(inp.toLong())
else ->
LongError(inp)
}
/**
* @see [parseDouble]
*/
data class DoubleError(val inp: Any) : TerminalError
/**
* Parse an [Any] into a [Double].
* It supports the following types:
* - [Double], [Float], [Int], [UInt], [Long]
* - [String], must be a valid double, [DoubleError] otherwise
*
* Anything else will fail with [DoubleError]
*/
fun parseDouble(inp: Any): Parsed<Double> =
when (inp) {
is String ->
try {
Ok(inp.toDouble())
} catch (ex: NumberFormatException) {
LongError(inp)
}
is Double ->
Ok(inp)
is Float ->
Ok(inp.toDouble())
is Long ->
Ok(inp.toDouble())
is UInt ->
Ok(inp.toDouble())
is Int ->
Ok(inp.toDouble())
else ->
DoubleError(inp)
}
| 0 | null | 0 | 0 | 3470695e6502edd7cb42109efba246d8c3d77995 | 8,154 | parsix | Apache License 2.0 |
app/src/main/java/fr/gilles/riceattend/ui/screens/pages/details/PaddyField.kt | Gilles-kpn | 498,005,092 | false | {"Kotlin": 442751} | package fr.gilles.riceattend.ui.screens.pages.details
import android.os.Build
import androidx.annotation.RequiresApi
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.foundation.verticalScroll
import androidx.compose.material.*
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.outlined.*
import androidx.compose.runtime.*
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.navigation.NavHostController
import coil.compose.AsyncImage
import fr.gilles.riceattend.ui.navigation.Route
import fr.gilles.riceattend.ui.viewmodel.PaddyFieldVM
import fr.gilles.riceattend.ui.widget.components.*
import kotlinx.coroutines.launch
@OptIn(ExperimentalMaterialApi::class)
@RequiresApi(Build.VERSION_CODES.O)
@Composable
fun PaddyFieldPage(
snackbarHostState: SnackbarHostState,
navHostController: NavHostController,
viewModel: PaddyFieldVM
) {
val scope = rememberCoroutineScope()
val modalBottomSheetState = rememberModalBottomSheetState(
initialValue = ModalBottomSheetValue.Hidden
)
when (viewModel.loading) {
true -> {
LoadingCard()
}
false -> {
viewModel.paddyField?.let {
Column(
modifier = Modifier
.fillMaxSize()
.verticalScroll(rememberScrollState())
,
horizontalAlignment = Alignment.CenterHorizontally
) {
AppBar(
title = it.name,
leftContent = {
IconButton(
onClick = {
navHostController.popBackStack()
},
) {
Icon(
Icons.Outlined.ArrowBack,
"Back",
)
}
},
rightContent = {
IconButton(onClick = { scope.launch { modalBottomSheetState.show() } }) {
Icon(
Icons.Outlined.Edit,
"Update",
)
}
}
)
Column(
modifier = Modifier
.fillMaxWidth()
.padding(10.dp)
) {
Text(
text = "Informations du plant",
Modifier.padding(vertical = 8.dp, horizontal = 10.dp),
fontSize = 12.sp
)
Card(Modifier.padding(10.dp)){
Column{
AsyncImage(
model = it.plant.image,
contentDescription = "plant",
contentScale = ContentScale.FillWidth,
modifier = Modifier
.fillMaxWidth()
.height(200.dp)
)
Row(
Modifier
.fillMaxWidth()
.padding(horizontal = 10.dp, vertical = 10.dp),
horizontalArrangement = Arrangement.SpaceBetween){
Text("Nom du plant", fontWeight = FontWeight.SemiBold, fontSize = 12.sp)
Text(it.plant.name, fontSize = 12.sp)
}
Row(
Modifier
.fillMaxWidth()
.padding(horizontal = 10.dp, vertical = 10.dp),
horizontalArrangement = Arrangement.SpaceBetween){
Text("Forme du plant" ,fontWeight = FontWeight.SemiBold, fontSize = 12.sp )
Text(
it.plant.shape,
fontSize = 12.sp
)
}
Row(
Modifier
.fillMaxWidth()
.padding(horizontal = 10.dp, vertical = 10.dp),
horizontalArrangement = Arrangement.SpaceBetween){
Text("Temps de culture" ,fontWeight = FontWeight.SemiBold, fontSize = 12.sp )
Text(
it.plant.cultivationTime?.let { it } ?: run {"-"},
fontSize = 12.sp
)
}
Row(
Modifier
.fillMaxWidth()
.padding(horizontal = 10.dp, vertical = 10.dp),
horizontalArrangement = Arrangement.SpaceBetween){
Text("Variété" ,fontWeight = FontWeight.SemiBold, fontSize = 12.sp )
Text(
it.plant.variety?.let { it } ?: run {"-"},
fontSize = 12.sp
)
}
}
}
Text(
text = "Informations de la rizière, ",
Modifier.padding(vertical = 8.dp, horizontal = 10.dp),
fontSize = 12.sp
)
Card(Modifier.padding(10.dp)) {
Column{
Row(
modifier = Modifier
.fillMaxWidth()
.padding(10.dp),
verticalAlignment = Alignment.CenterVertically,
horizontalArrangement = Arrangement.SpaceBetween
) {
Row(verticalAlignment = Alignment.CenterVertically) {
Icon(
Icons.Outlined.ConfirmationNumber,
contentDescription = "Number of plants",
modifier = Modifier
.padding(horizontal = 5.dp)
.size(16.dp)
)
Text(
text = "Nombre de plants",
fontWeight = FontWeight.SemiBold,
fontSize = 12.sp
)
}
Text(
text = it.numberOfPlants.toString() + " plants",
fontSize = 12.sp
)
}
Row(
modifier = Modifier
.fillMaxWidth()
.padding(10.dp),
verticalAlignment = Alignment.CenterVertically,
horizontalArrangement = Arrangement.SpaceBetween
) {
Row(verticalAlignment = Alignment.CenterVertically) {
Icon(
Icons.Outlined.AreaChart,
contentDescription = "area",
modifier = Modifier
.padding(horizontal = 5.dp)
.size(16.dp)
)
Text(
text = "Superficie",
fontSize = 12.sp,
fontWeight = FontWeight.SemiBold
)
}
Text(
text = it.surface.value.toString() + " " + it.surface.unit,
fontSize = 12.sp
)
}
}
}
Text(
text = "Activités sur cette rizière",
Modifier.padding(vertical = 8.dp, horizontal = 10.dp),
fontSize = 12.sp
)
it.activityPaddyFields.forEach { activityPaddyField ->
ActivityTile(activity = activityPaddyField.activity, onClick = {
navHostController.navigate(
Route.ActivityRoute.path.replace(
"{code}",
activityPaddyField.activity.code
)
) {
}
})
if (it.activityPaddyFields.isEmpty()){
EmptyCard()
}
}
}
}
}
}
}
ModalBottomSheetLayout(
sheetContent = {
PaddyFieldForm(
title = "Modifier la riziere",
paddyFormViewModel = viewModel.paddyfieldFormVM,
plants = viewModel.plants,
onClick = {
viewModel.update(onError = {
scope.launch {
snackbarHostState.showSnackbar(
message = "Une erreur est survenue \n$it",
)
}
})
},
isLoading = viewModel.updateLoading,
buttonText = "Modifier",
)
},
sheetState = modalBottomSheetState,
sheetShape = RoundedCornerShape(topStart = 16.dp, topEnd = 16.dp),
) {}
}
| 0 | Kotlin | 0 | 1 | b75abaf8d21014bdfe79a2ab8db82bcb1f561bf8 | 11,713 | RiceAttend-Mobile | MIT License |
Function/src/4-NullValue.kt | zjgyb | 127,631,036 | false | null | fun hello(name: String?):String {
return "Hello " + name
}
fun main(args: Array<String>) {
println(hello("Tony"))
println(hello(null))
} | 0 | Kotlin | 0 | 0 | eeadf39595a52d0717890668798e5c2766b39c83 | 149 | kotlin | MIT License |
bindings/gtk/gtk4/src/nativeMain/kotlin/org/gtkkn/bindings/gtk/ScrollType.kt | gtk-kn | 609,191,895 | false | {"Kotlin": 10448515, "Shell": 2740} | // This is a generated file. Do not modify.
package org.gtkkn.bindings.gtk
import org.gtkkn.native.gtk.GtkScrollType
import org.gtkkn.native.gtk.GtkScrollType.GTK_SCROLL_END
import org.gtkkn.native.gtk.GtkScrollType.GTK_SCROLL_JUMP
import org.gtkkn.native.gtk.GtkScrollType.GTK_SCROLL_NONE
import org.gtkkn.native.gtk.GtkScrollType.GTK_SCROLL_PAGE_BACKWARD
import org.gtkkn.native.gtk.GtkScrollType.GTK_SCROLL_PAGE_DOWN
import org.gtkkn.native.gtk.GtkScrollType.GTK_SCROLL_PAGE_FORWARD
import org.gtkkn.native.gtk.GtkScrollType.GTK_SCROLL_PAGE_LEFT
import org.gtkkn.native.gtk.GtkScrollType.GTK_SCROLL_PAGE_RIGHT
import org.gtkkn.native.gtk.GtkScrollType.GTK_SCROLL_PAGE_UP
import org.gtkkn.native.gtk.GtkScrollType.GTK_SCROLL_START
import org.gtkkn.native.gtk.GtkScrollType.GTK_SCROLL_STEP_BACKWARD
import org.gtkkn.native.gtk.GtkScrollType.GTK_SCROLL_STEP_DOWN
import org.gtkkn.native.gtk.GtkScrollType.GTK_SCROLL_STEP_FORWARD
import org.gtkkn.native.gtk.GtkScrollType.GTK_SCROLL_STEP_LEFT
import org.gtkkn.native.gtk.GtkScrollType.GTK_SCROLL_STEP_RIGHT
import org.gtkkn.native.gtk.GtkScrollType.GTK_SCROLL_STEP_UP
/**
* Scrolling types.
*/
public enum class ScrollType(
public val nativeValue: GtkScrollType,
) {
/**
* No scrolling.
*/
NONE(GTK_SCROLL_NONE),
/**
* Jump to new location.
*/
JUMP(GTK_SCROLL_JUMP),
/**
* Step backward.
*/
STEP_BACKWARD(GTK_SCROLL_STEP_BACKWARD),
/**
* Step forward.
*/
STEP_FORWARD(GTK_SCROLL_STEP_FORWARD),
/**
* Page backward.
*/
PAGE_BACKWARD(GTK_SCROLL_PAGE_BACKWARD),
/**
* Page forward.
*/
PAGE_FORWARD(GTK_SCROLL_PAGE_FORWARD),
/**
* Step up.
*/
STEP_UP(GTK_SCROLL_STEP_UP),
/**
* Step down.
*/
STEP_DOWN(GTK_SCROLL_STEP_DOWN),
/**
* Page up.
*/
PAGE_UP(GTK_SCROLL_PAGE_UP),
/**
* Page down.
*/
PAGE_DOWN(GTK_SCROLL_PAGE_DOWN),
/**
* Step to the left.
*/
STEP_LEFT(GTK_SCROLL_STEP_LEFT),
/**
* Step to the right.
*/
STEP_RIGHT(GTK_SCROLL_STEP_RIGHT),
/**
* Page to the left.
*/
PAGE_LEFT(GTK_SCROLL_PAGE_LEFT),
/**
* Page to the right.
*/
PAGE_RIGHT(GTK_SCROLL_PAGE_RIGHT),
/**
* Scroll to start.
*/
START(GTK_SCROLL_START),
/**
* Scroll to end.
*/
END(GTK_SCROLL_END),
;
public companion object {
public fun fromNativeValue(nativeValue: GtkScrollType): ScrollType =
when (nativeValue) {
GTK_SCROLL_NONE -> NONE
GTK_SCROLL_JUMP -> JUMP
GTK_SCROLL_STEP_BACKWARD -> STEP_BACKWARD
GTK_SCROLL_STEP_FORWARD -> STEP_FORWARD
GTK_SCROLL_PAGE_BACKWARD -> PAGE_BACKWARD
GTK_SCROLL_PAGE_FORWARD -> PAGE_FORWARD
GTK_SCROLL_STEP_UP -> STEP_UP
GTK_SCROLL_STEP_DOWN -> STEP_DOWN
GTK_SCROLL_PAGE_UP -> PAGE_UP
GTK_SCROLL_PAGE_DOWN -> PAGE_DOWN
GTK_SCROLL_STEP_LEFT -> STEP_LEFT
GTK_SCROLL_STEP_RIGHT -> STEP_RIGHT
GTK_SCROLL_PAGE_LEFT -> PAGE_LEFT
GTK_SCROLL_PAGE_RIGHT -> PAGE_RIGHT
GTK_SCROLL_START -> START
GTK_SCROLL_END -> END
else -> error("invalid nativeValue")
}
}
}
| 0 | Kotlin | 0 | 13 | c033c245f1501134c5b9b46212cd153c61f7efea | 3,429 | gtk-kn | Creative Commons Attribution 4.0 International |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.