path
stringlengths 4
280
| owner
stringlengths 2
39
| repo_id
int64 21.1k
879M
| is_fork
bool 2
classes | languages_distribution
stringlengths 13
1.95k
⌀ | content
stringlengths 7
482k
| issues
int64 0
13.9k
| main_language
stringclasses 121
values | forks
stringlengths 1
5
| stars
int64 0
111k
| commit_sha
stringlengths 40
40
| size
int64 7
482k
| name
stringlengths 1
100
| license
stringclasses 93
values |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|
src/main/kotlin/io/github/maiconandsilva/quanda/utils/sec/QuandaUserDetails.kt | maiconandsilva | 409,806,532 | false | null | package io.github.maiconandsilva.quanda.utils.sec
import org.springframework.security.core.GrantedAuthority
import org.springframework.security.core.userdetails.User
class QuandaUserDetails(
val email: String?, username: String?, password: String?,
authorities: MutableCollection<out GrantedAuthority?> = mutableListOf(),
enabled: Boolean = true, accountNonExpired: Boolean = true,
credentialsNonExpired: Boolean = true, accountNonLocked: Boolean = true,
) : User(
username, password, enabled, accountNonExpired,
credentialsNonExpired, accountNonLocked, authorities,
) {
constructor(user: io.github.maiconandsilva.quanda.entities.User)
: this(user.email, user.username ?: user.email, user.password)
}
| 0 | Kotlin | 0 | 0 | 58c05d2dc8dee4e9f9079dfdd8717875da6a1b9b | 743 | quanda-api | MIT License |
common/src/main/java/eu/kevin/common/extensions/TextInputLayoutExtensions.kt | getkevin | 375,151,388 | false | {"Kotlin": 238202} | package eu.kevin.common.extensions
import com.google.android.material.textfield.TextInputLayout
fun TextInputLayout.getInputText(): String {
return this.editText?.text?.toString() ?: ""
} | 0 | Kotlin | 2 | 7 | b18fb946b900a0db5632bd81db620d2153603d14 | 193 | kevin-android | MIT License |
app/src/main/java/io/ak1/drawboxsample/ui/components/CustomViews.kt | akshay2211 | 436,719,814 | false | {"Kotlin": 32027} | package io.ak1.drawboxsample.ui.components
import android.widget.SeekBar
import androidx.annotation.DrawableRes
import androidx.compose.animation.*
import androidx.compose.foundation.border
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.material.Icon
import androidx.compose.material.IconButton
import androidx.compose.material.MaterialTheme
import androidx.compose.material.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.MutableState
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.platform.LocalDensity
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.unit.dp
import androidx.compose.ui.viewinterop.AndroidView
import androidx.core.graphics.BlendModeColorFilterCompat
import androidx.core.graphics.BlendModeCompat
import io.ak1.drawbox.DrawController
import io.ak1.drawboxsample.R
/**
* Created by akshay on 29/12/21
* https://ak1.io
*/
@Composable
fun ControlsBar(
drawController: DrawController,
onDownloadClick: () -> Unit,
onColorClick: () -> Unit,
onBgColorClick: () -> Unit,
onSizeClick: () -> Unit,
undoVisibility: MutableState<Boolean>,
redoVisibility: MutableState<Boolean>,
colorValue: MutableState<Color>,
bgColorValue: MutableState<Color>,
sizeValue: MutableState<Int>
) {
Row(modifier = Modifier.padding(12.dp), horizontalArrangement = Arrangement.SpaceAround) {
MenuItems(
R.drawable.ic_download,
"download",
if (undoVisibility.value) MaterialTheme.colors.primary else MaterialTheme.colors.primaryVariant
) {
if (undoVisibility.value) onDownloadClick()
}
MenuItems(
R.drawable.ic_undo,
"undo",
if (undoVisibility.value) MaterialTheme.colors.primary else MaterialTheme.colors.primaryVariant
) {
if (undoVisibility.value) drawController.unDo()
}
MenuItems(
R.drawable.ic_redo,
"redo",
if (redoVisibility.value) MaterialTheme.colors.primary else MaterialTheme.colors.primaryVariant
) {
if (redoVisibility.value) drawController.reDo()
}
MenuItems(
R.drawable.ic_refresh,
"reset",
if (redoVisibility.value || undoVisibility.value) MaterialTheme.colors.primary else MaterialTheme.colors.primaryVariant
) {
drawController.reset()
}
MenuItems(R.drawable.ic_color, "background color", bgColorValue.value, bgColorValue.value == MaterialTheme.colors.background) {
onBgColorClick()
}
MenuItems(R.drawable.ic_color, "stroke color", colorValue.value) {
onColorClick()
}
MenuItems(R.drawable.ic_size, "stroke size", MaterialTheme.colors.primary) {
onSizeClick()
}
}
}
@Composable
fun RowScope.MenuItems(
@DrawableRes resId: Int,
desc: String,
colorTint: Color,
border: Boolean = false,
onClick: () -> Unit
) {
val modifier = Modifier.size(24.dp)
IconButton(
onClick = onClick, modifier = Modifier.weight(1f, true)
) {
Icon(
painterResource(id = resId),
contentDescription = desc,
tint = colorTint,
modifier = if (border) modifier.border(
0.5.dp,
Color.White,
shape = CircleShape
) else modifier
)
}
}
@Composable
fun CustomSeekbar(
isVisible: Boolean,
max: Int = 200,
progress: Int = max,
progressColor: Int,
thumbColor: Int,
onProgressChanged: (Int) -> Unit
) {
val density = LocalDensity.current
AnimatedVisibility(
visible = isVisible,
enter = slideInVertically {
// Slide in from 40 dp from the top.
with(density) { -40.dp.roundToPx() }
} + expandVertically(
// Expand from the top.
expandFrom = Alignment.Top
) + fadeIn(
// Fade in with the initial alpha of 0.3f.
initialAlpha = 0.3f
),
exit = slideOutVertically() + shrinkVertically() + fadeOut()
) {
val context = LocalContext.current
Column(
modifier = Modifier
.height(100.dp)
.fillMaxWidth(),
verticalArrangement = Arrangement.SpaceEvenly
) {
Text(text = "Stroke Width", modifier = Modifier.padding(12.dp, 0.dp, 0.dp, 0.dp))
AndroidView(
{ SeekBar(context) },
modifier = Modifier
.fillMaxWidth()
) {
it.progressDrawable.colorFilter =
BlendModeColorFilterCompat.createBlendModeColorFilterCompat(
progressColor,
BlendModeCompat.SRC_ATOP
)
it.thumb.colorFilter =
BlendModeColorFilterCompat.createBlendModeColorFilterCompat(
thumbColor,
BlendModeCompat.SRC_ATOP
)
it.max = max
it.progress = progress
it.setOnSeekBarChangeListener(object : SeekBar.OnSeekBarChangeListener {
override fun onProgressChanged(p0: SeekBar?, p1: Int, p2: Boolean) {
}
override fun onStartTrackingTouch(p0: SeekBar?) {}
override fun onStopTrackingTouch(p0: SeekBar?) {
onProgressChanged(p0?.progress ?: it.progress)
}
})
}
}
}
} | 8 | Kotlin | 32 | 254 | 4a52321f2f3681d674677c4283d2eff719d02de1 | 5,878 | DrawBox | Apache License 2.0 |
app/src/main/java/com/chrynan/androidsearch/web/ContextualWebSuggestionWebService.kt | chRyNaN | 161,237,148 | false | null | package com.chrynan.androidsearch.web
import kotlinx.coroutines.Deferred
import retrofit2.http.GET
import retrofit2.http.Query
interface ContextualWebSuggestionWebService {
@GET("/api/spelling/AutoComplete?")
fun getSearchSuggestions(@Query("text") query: String, @Query("count") count: Int = 3): Deferred<List<String>>
} | 0 | Kotlin | 0 | 0 | ade50a4bda75e3e71d86457565e63573feaf597b | 332 | Android-Search | Apache License 2.0 |
app/src/main/java/com/example/easymealmvvm/presentation/adapter/MealsByCategoryAdapter.kt | ahmedfkri | 872,422,118 | false | {"Kotlin": 47979} | package com.example.easymealmvvm.presentation.adapter
import android.view.LayoutInflater
import android.view.ViewGroup
import androidx.recyclerview.widget.AsyncListDiffer
import androidx.recyclerview.widget.DiffUtil
import androidx.recyclerview.widget.RecyclerView
import com.bumptech.glide.Glide
import com.example.easymealmvvm.data.model.PopularMeal
import com.example.easymealmvvm.databinding.MealListItemBinding
class MealsByCategoryAdapter : RecyclerView.Adapter<MealsByCategoryAdapter.CategoryViewHolder>() {
//DiffUtil
val diffUtil = object : DiffUtil.ItemCallback<PopularMeal>(){
override fun areItemsTheSame(oldItem: PopularMeal, newItem: PopularMeal): Boolean {
return oldItem.idMeal == newItem.idMeal
}
override fun areContentsTheSame(oldItem: PopularMeal, newItem: PopularMeal): Boolean {
return oldItem == newItem
}
}
val differ = AsyncListDiffer(this, diffUtil)
class CategoryViewHolder(val binding: MealListItemBinding) :
RecyclerView.ViewHolder(binding.root) {
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): CategoryViewHolder {
return CategoryViewHolder(
MealListItemBinding.inflate(
LayoutInflater.from(parent.context),
parent,
false
)
)
}
override fun getItemCount() = differ.currentList.size
override fun onBindViewHolder(holder: CategoryViewHolder, position: Int) {
val meal = differ.currentList[position]
holder.binding.txtMealName.text = meal.strMeal
Glide.with(holder.itemView).load(meal.strMealThumb).into(holder.binding.imgMeal)
}
} | 0 | Kotlin | 0 | 0 | a9202d78d83925ca600a81a0eb32065387fdac3b | 1,713 | EasyMeal | MIT License |
datawedgeconfigurator/src/main/java/com/zebra/nilac/dwconfigurator/models/workflow/modules/WorkflowFreeFormCaptureDecoderModule.kt | nilac8991 | 261,186,326 | false | {"Kotlin": 134096, "Java": 744} | package com.zebra.nilac.dwconfigurator.models.workflow.modules
import com.zebra.nilac.dwconfigurator.models.workflow.WorkflowOutputImageMode
data class WorkflowFreeFormCaptureDecoderModule(
var mode: Mode = Mode.HIGHLIGHT
) : WorkflowGenericModule() {
init {
name = "BarcodeTrackerModule"
}
constructor(mode: Mode, sessionTimeOut: Long) : this() {
this.mode = mode
this.sessionTimeOut = sessionTimeOut
}
constructor(
scanMode: Mode,
sessionTimeOut: Long,
outputImage: WorkflowOutputImageMode
) : this() {
this.mode = scanMode
this.sessionTimeOut = sessionTimeOut
this.outputImage = outputImage
}
enum class Mode {
OFF, HIGHLIGHT, DECODE_AND_HIGHLIGHT
}
} | 0 | Kotlin | 1 | 1 | 791ef7abaf61d864c6e206d290be11f5ae25a2c0 | 780 | datawedge-configurator | MIT License |
src/main/kotlin/com/github/kerubistan/kerub/planner/steps/storage/lvm/pool/create/CreateLvmPoolExecutor.kt | kerubistan | 19,528,622 | false | null | package com.github.kerubistan.kerub.planner.steps.storage.lvm.pool.create
import com.github.kerubistan.kerub.data.config.HostConfigurationDao
import com.github.kerubistan.kerub.host.HostCommandExecutor
import com.github.kerubistan.kerub.model.config.HostConfiguration
import com.github.kerubistan.kerub.model.config.LvmPoolConfiguration
import com.github.kerubistan.kerub.planner.execution.AbstractStepExecutor
import com.github.kerubistan.kerub.utils.junix.storagemanager.lvm.LogicalVolume
import com.github.kerubistan.kerub.utils.junix.storagemanager.lvm.LvmLv
import com.github.kerubistan.kerub.utils.junix.storagemanager.lvm.LvmThinLv
import com.github.kerubistan.kerub.utils.junix.storagemanager.lvm.LvmVg
import io.github.kerubistan.kroki.numbers.compareTo
import io.github.kerubistan.kroki.numbers.times
class CreateLvmPoolExecutor(
private val hostCommandExecutor: HostCommandExecutor,
private val hostCfgDao: HostConfigurationDao
) : AbstractStepExecutor<CreateLvmPool, LogicalVolume>() {
override fun prepare(step: CreateLvmPool) = hostCommandExecutor.execute(step.host) {
LvmVg.list(session = it, vgName = step.vgName).single().let {
val expectedFreeSpace = step.size * 1.01
check(it.freeSize >= expectedFreeSpace) {
"volume group ${step.vgName} on host ${step.host.address} is expected to have at least " +
"$expectedFreeSpace but only have ${it.freeSize}"
}
}
}
override fun perform(step: CreateLvmPool) =
hostCommandExecutor.execute(step.host) {
LvmThinLv.createPool(it, step.vgName, step.name, step.size, step.size / 100.toBigInteger())
LvmLv.list(it, step.vgName, step.name).single()
}
override fun update(step: CreateLvmPool, updates: LogicalVolume) {
hostCfgDao.update(step.host.id,
retrieve = { hostCfgDao[it] ?: HostConfiguration(id = step.host.id) },
change = { hostCfg ->
hostCfg.copy(
storageConfiguration = hostCfg.storageConfiguration + LvmPoolConfiguration(
vgName = step.vgName,
size = updates.size,
poolName = step.name
)
)
}
)
}
} | 109 | Kotlin | 4 | 14 | 99cb43c962da46df7a0beb75f2e0c839c6c50bda | 2,078 | kerub | Apache License 2.0 |
app/src/main/java/com/mty/bangcalendar/ui/main/view/CalendarScrollView.kt | mty1122 | 485,456,860 | false | {"Kotlin": 174548, "C++": 12060, "CMake": 814} | package com.mty.bangcalendar.ui.main.view
import android.view.View
//记录参与滚动的view的上个位置
class CalendarScrollView(val view: View, var lastPosition: Int) | 0 | Kotlin | 0 | 0 | cc34536f2802c243116e5a022488bcbab7dc69f9 | 151 | BangCalendar | Apache License 2.0 |
app/src/main/kotlin/com/mitch/my_unibo/extensions/Float.kt | seve-andre | 511,074,187 | false | {"Kotlin": 320965} | package com.mitch.my_unibo.extensions
import kotlin.math.roundToInt
/**
* Converts [Float] number to percentage [String].
* Rounds up number to [Int], following the rounding-up-to-the-nearest-integer convention.
*
* Examples:
* - 0.33f -> "33%"
* - 0.655f -> "66%"
* - 0.223f -> "22%"
*
* @return number converted to percentage string
*/
fun Float.toPercentage(): String {
return "${(this * 100).roundToInt()}%"
}
| 0 | Kotlin | 0 | 2 | d10efb2a1676ecbf78643f88726b586a3d8c989d | 430 | myUniBo | Apache License 2.0 |
app/src/main/java/com/kproject/chatgpt/data/api/ApiService.kt | jsericksk | 581,359,749 | false | {"Kotlin": 150740} | package com.kproject.chatgpt.data.api
import com.kproject.chatgpt.data.api.entity.MessageBody
import com.kproject.chatgpt.data.api.entity.MessageResponse
import retrofit2.Response
import retrofit2.http.Body
import retrofit2.http.Header
import retrofit2.http.POST
interface ApiService {
@POST("completions")
suspend fun sendMessage(
@Header("Authorization") apiKey: String,
@Body messageBody: MessageBody
): Response<MessageResponse>
companion object {
const val API_BASE_URL = "https://api.openai.com/v1/"
}
} | 0 | Kotlin | 0 | 1 | 15561532c4836be546bd45d6b735b420c427e4ee | 557 | ChatGPT | MIT License |
src/main/kotlin/uk/gov/justice/digital/hmpps/prisonregister/model/PrisonRepository.kt | ministryofjustice | 337,466,567 | false | {"Kotlin": 304451, "Dockerfile": 1443, "Shell": 238} | package uk.gov.justice.digital.hmpps.prisonregister.model
import org.springframework.data.jpa.repository.JpaRepository
import org.springframework.data.jpa.repository.JpaSpecificationExecutor
import org.springframework.data.jpa.repository.Query
import org.springframework.stereotype.Repository
import uk.gov.justice.digital.hmpps.prisonregister.resource.dto.PrisonNameDto
@Repository
interface PrisonRepository : JpaRepository<Prison, String>, JpaSpecificationExecutor<Prison> {
fun findByActiveOrderByPrisonId(active: Boolean): List<Prison>
fun findByPrisonId(prisonCode: String): Prison?
fun findByGpPracticeGpPracticeCode(gpPracticeCode: String): Prison?
fun findAllByPrisonIdIsIn(ids: List<String>): List<Prison>
@Query(
"SELECT new uk.gov.justice.digital.hmpps.prisonregister.resource.dto.PrisonNameDto(p.prisonId, p.name) " +
"FROM Prison p ORDER BY p.name",
)
fun getPrisonNames(): List<PrisonNameDto>
}
| 6 | Kotlin | 1 | 2 | 447ae1d4cb94a0bd18e2169c2537f051c74f1e84 | 940 | prison-register | MIT License |
app/src/main/java/eu/kanade/tachiyomi/ui/reader/viewer/ViewerNavigation.kt | sahilsood25 | 334,852,291 | true | {"Kotlin": 1700067} | package eu.kanade.tachiyomi.ui.reader.viewer
import android.graphics.PointF
import android.graphics.RectF
import eu.kanade.tachiyomi.data.preference.PreferenceValues
import eu.kanade.tachiyomi.util.lang.invert
abstract class ViewerNavigation {
enum class NavigationRegion {
NEXT, PREV, MENU, RIGHT, LEFT
}
data class Region(
val rectF: RectF,
val type: NavigationRegion
) {
fun invert(invertMode: PreferenceValues.TappingInvertMode): Region {
if (invertMode == PreferenceValues.TappingInvertMode.NONE) return this
return this.copy(
rectF = this.rectF.invert(invertMode)
)
}
}
private var constantMenuRegion: RectF = RectF(0f, 0f, 1f, 0.05f)
abstract var regions: List<Region>
var invertMode: PreferenceValues.TappingInvertMode = PreferenceValues.TappingInvertMode.NONE
fun getAction(pos: PointF): NavigationRegion {
val x = pos.x
val y = pos.y
val region = regions.map { it.invert(invertMode) }
.find { it.rectF.contains(x, y) }
return when {
region != null -> region.type
constantMenuRegion.contains(x, y) -> NavigationRegion.MENU
else -> NavigationRegion.MENU
}
}
}
| 0 | null | 0 | 1 | d4081dc8990f1da89957a184fe13ef5afc7b7b20 | 1,296 | tachiyomi | Apache License 2.0 |
src/main/kotlin/com/yl/dev/kt/fast/mykotlionblog/config/SystemConfig.kt | Brianlau0 | 307,585,813 | false | null | package com.yl.dev.kt.fast.mykotlionblog.config
import org.springframework.cache.annotation.EnableCaching
import org.springframework.context.annotation.Configuration
import org.springframework.scheduling.annotation.EnableAsync
import org.springframework.scheduling.annotation.EnableScheduling
@EnableScheduling
@EnableCaching
@EnableAsync
@Configuration
class SystemConfig | 0 | Kotlin | 0 | 0 | 53bae05df2e3ccf0148e255fc71a935125456ac4 | 374 | fast-ws | MIT License |
sample/src/main/java/ro/dobrescuandrei/demonewlibs/model/utils/Commands.kt | irfanirawansukirman | 221,451,047 | false | {"Gradle": 4, "Java Properties": 2, "Shell": 1, "Text": 1, "Ignore List": 3, "Batchfile": 1, "Markdown": 10, "Proguard": 2, "XML": 30, "Kotlin": 66, "Java": 3} | package ro.dobrescuandrei.demonewlibs.model.utils
class RefreshRestaurantListCommand | 1 | null | 5 | 1 | f940702c98847e42dc0ce230485da8f35bc32e32 | 85 | DobDroidMVVM | Apache License 2.0 |
src/main/kotlin/de/matthiaskainer/c4c/repository/database/Database.kt | MatthiasKainer | 359,918,118 | false | null | package de.matthiaskainer.c4c.repository.database
import de.matthiaskainer.c4c.core.DatabaseConfiguration
import de.matthiaskainer.c4c.domain.TestRunResult
import de.matthiaskainer.c4c.repository.domain.ContractTable
import de.matthiaskainer.c4c.repository.domain.VersionTable
import de.matthiaskainer.c4c.repository.domain.TestResultTable
import org.jetbrains.exposed.sql.SchemaUtils
import org.jetbrains.exposed.sql.batchInsert
import org.jetbrains.exposed.sql.insert
import org.jetbrains.exposed.sql.transactions.transaction
import java.time.LocalDateTime
fun connect(databaseConfiguration: DatabaseConfiguration) {
org.jetbrains.exposed.sql.Database.connect(
databaseConfiguration.url,
driver = databaseConfiguration.driver,
user = databaseConfiguration.user,
password = databaseConfiguration.password
)
}
fun initDatasource(databaseConfiguration: DatabaseConfiguration, clean: Boolean = false) {
connect(databaseConfiguration)
transaction {
if (clean) SchemaUtils.drop(ContractTable, VersionTable, TestResultTable)
SchemaUtils.create(ContractTable, VersionTable, TestResultTable)
val demoContract = ContractTable.insert {
it[consumer] = "consumer"
it[provider] = "provider"
it[element] = "element-example"
} get ContractTable.id
val versionId = VersionTable.insert {
it[version] = "1.0.0"
it[lines] = "const some='lines';\n"
it[contractId] = demoContract
} get VersionTable.id
TestResultTable.insert {
it[executionDate] = LocalDateTime.of(2021, 6, 12, 0, 0)
it[result] = TestRunResult.Success.toString()
it[version] = versionId
it[contractId] = demoContract
}
}
} | 0 | Kotlin | 0 | 0 | 4848e640a81e32f5b47f355a83d930817b56b2f8 | 1,811 | c4c.server | MIT License |
data/unit/src/main/java/com/masselis/tpmsadvanced/data/unit/ioc/DataUnitComponent.kt | VincentMasselis | 501,773,706 | false | null | package com.masselis.tpmsadvanced.data.unit.ioc
import com.masselis.tpmsadvanced.core.common.CoreCommonComponent
import com.masselis.tpmsadvanced.data.unit.interfaces.UnitPreferences
import dagger.Component
@DataUnitComponent.Scope
@Component(
dependencies = [CoreCommonComponent::class]
)
public interface DataUnitComponent {
@Component.Factory
public interface Factory {
public fun build(coreCommonComponent: CoreCommonComponent = CoreCommonComponent): DataUnitComponent
}
public val unitPreferences: UnitPreferences
@javax.inject.Scope
public annotation class Scope
public companion object : DataUnitComponent by DaggerDataUnitComponent
.factory()
.build()
}
| 5 | Kotlin | 0 | 0 | bb735a34e0fb162de5342b0140c69ba4fd2cc97b | 723 | TPMS-advanced | Apache License 2.0 |
RCache/src/main/java/id/nesd/rcache/RCaching.kt | rahmat3nanda | 844,839,613 | false | {"Kotlin": 25702} | package id.nesd.rcache
/**
* Interface for RCache.
*/
interface RCaching {
/**
* Gets an instance of RCaching
* @return RCaching
* # Example #
* ```
* // RCaching.instance
* ```
*/
companion object {
lateinit var instance: RCaching
}
/**
* Method for storing data with a defined key.
*
* @param data Data.
* @param key RCache.Key.
* # Example #
* ```
* // RCaching.instance.save(data, RCache.Key("data"))
* ```
*/
fun save(data: ByteArray, key: RCache.Key)
/**
* Method for storing String with a defined key.
*
* @param string String.
* @param key RCache.Key.
* # Example #
* ```
* // RCaching.instance.save("data string", RCache.Key("string"))
* ```
*/
fun save(string: String, key: RCache.Key)
/**
* Method for storing Boolean with a defined key.
*
* @param bool Boolean.
* @param key RCache.Key.
* # Example #
* ```
* // RCaching.instance.save(true, RCache.Key("bool"))
* ```
*/
fun save(bool: Boolean, key: RCache.Key)
/**
* Method for storing Integer with a defined key.
*
* @param integer Int.
* @param key RCache.Key.
* # Example #
* ```
* // RCaching.instance.save(101, RCache.Key("integer"))
* ```
*/
fun save(integer: Int, key: RCache.Key)
/**
* Method for storing Array with a defined key.
*
* @param array List<Any>.
* @param key RCache.Key.
* # Example #
* ```
* // RCaching.instance.save(listOf(101, "string", true), RCache.Key("array"))
* ```
*/
fun save(array: List<Any>, key: RCache.Key)
/**
* Method for storing Map<String, Any> with a defined key.
*
* @param dictionary Map<String, Any>.
* @param key RCache.Key.
* # Example #
* ```
* // RCaching.instance.save(mapOf("bool" to true, "integer" to 101), RCache.Key("dictionary"))
* ```
*/
fun save(dictionary: Map<String, Any>, key: RCache.Key)
/**
* Method for storing Double with a defined key.
*
* @param double Double.
* @param key RCache.Key.
* # Example #
* ```
* // RCaching.instance.save(2.0, RCache.Key("double"))
* ```
*/
fun save(double: Double, key: RCache.Key)
/**
* Method for storing Float with a defined key.
*
* @param float Float.
* @param key RCache.Key.
* # Example #
* ```
* // RCaching.instance.save(3.01f, RCache.Key("float"))
* ```
*/
fun save(float: Float, key: RCache.Key)
/**
* Method for getting data with a defined key.
*
* @param key RCache.Key.
* @return ByteArray?
* # Example #
* ```
* // RCaching.instance.readData(RCache.Key("data"))
* ```
*/
fun readData(key: RCache.Key): ByteArray?
/**
* Method for getting String with a defined key.
*
* @param key RCache.Key.
* @return String?
* # Example #
* ```
* // RCaching.instance.readString(RCache.Key("string"))
* ```
*/
fun readString(key: RCache.Key): String?
/**
* Method for getting Boolean with a defined key.
*
* @param key RCache.Key.
* @return Boolean?
* # Example #
* ```
* // RCaching.instance.readBool(RCache.Key("bool"))
* ```
*/
fun readBool(key: RCache.Key): Boolean?
/**
* Method for getting Integer with a defined key.
*
* @param key RCache.Key.
* @return Int?
* # Example #
* ```
* // RCaching.instance.readInteger(RCache.Key("integer"))
* ```
*/
fun readInteger(key: RCache.Key): Int?
/**
* Method for getting Array with a defined key.
*
* @param key RCache.Key.
* @return List<Any>?
* # Example #
* ```
* // RCaching.instance.readArray(RCache.Key("array"))
* ```
*/
fun readArray(key: RCache.Key): List<Any>?
/**
* Method for getting Map<String, Any> with a defined key.
*
* @param key RCache.Key.
* @return Map<String, Any>?
* # Example #
* ```
* // RCaching.instance.readDictionary(RCache.Key("dictionary"))
* ```
*/
fun readDictionary(key: RCache.Key): Map<String, Any>?
/**
* Method for getting Double with a defined key.
*
* @param key RCache.Key.
* @return Double?
* # Example #
* ```
* // RCaching.instance.readDouble(RCache.Key("double"))
* ```
*/
fun readDouble(key: RCache.Key): Double?
/**
* Method for getting Float with a defined key.
*
* @param key RCache.Key.
* @return Float?
* # Example #
* ```
* // RCaching.instance.readFloat(RCache.Key("float"))
* ```
*/
fun readFloat(key: RCache.Key): Float?
/**
* Method for deleting data stored with a defined key.
*
* @param key RCache.Key.
* # Example #
* ```
* // RCaching.instance.remove(RCache.Key("dictionary"))
* ```
*/
fun remove(key: RCache.Key)
/**
* Method for deleting all data stored via Caching.
*
* # Example #
* ```
* // RCaching.instance.clear()
* ```
*/
fun clear()
} | 0 | Kotlin | 0 | 0 | 65fabdc2ed515543bf16f39908df8e83736859a4 | 5,325 | RCache-Android | MIT License |
app/src/main/java/com/example/gethealthy/presentation/MainActivity.kt | Anilcee | 834,762,612 | false | {"Kotlin": 28150} | package com.example.gethealthy.presentation
import android.content.Intent
import android.os.Bundle
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.core.splashscreen.SplashScreen.Companion.installSplashScreen
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Spacer
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.layout.size
import androidx.compose.foundation.layout.wrapContentSize
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
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.platform.LocalContext
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.tooling.preview.Devices
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import androidx.wear.compose.material.Chip
import androidx.wear.compose.material.ChipDefaults
import androidx.wear.compose.material.Icon
import androidx.wear.compose.material.MaterialTheme
import androidx.wear.compose.material.Text
import androidx.wear.compose.material.TimeText
import com.example.gethealthy.R
import com.example.gethealthy.presentation.theme.GetHealthyTheme
class MainActivity : ComponentActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
installSplashScreen()
super.onCreate(savedInstanceState)
setTheme(android.R.style.Theme_DeviceDefault)
setContent {
WearApp()
}
}
}
@Composable
fun WearApp() {
val context = LocalContext.current
GetHealthyTheme {
Box(
modifier = Modifier
.fillMaxSize()
.background(MaterialTheme.colors.background),
contentAlignment = Alignment.Center
) {
TimeText()
LazyColumn(
horizontalAlignment = Alignment.CenterHorizontally
) {
item {
Spacer(modifier = Modifier.height(32.dp))
}
items(listOf(
ChipData("Adım", R.drawable.walk, Color.Cyan) { context.startActivity(Intent(context, StepCounter::class.java)) },
ChipData("Nabız", R.drawable.hearth, Color.Red) { context.startActivity(Intent(context, HearthRate::class.java)) },
ChipData("Kalori", R.drawable.calorie, Color.Red) { context.startActivity(Intent(context, Calories::class.java)) },
ChipData("Bilgilerim", R.drawable.info, Color.Yellow) { context.startActivity(Intent(context,UserInfo::class.java)) }
)) { chip ->
Chip(
onClick = chip.onClick,
label = { Text(chip.label) },
icon = {
Icon(
painter = painterResource(id = chip.iconRes),
contentDescription = chip.label,
modifier = Modifier
.size(ChipDefaults.LargeIconSize)
.wrapContentSize(align = Alignment.Center),
)
},
modifier = Modifier
.fillMaxWidth()
.padding(horizontal = 16.dp),
colors = ChipDefaults.chipColors(backgroundColor = Color.DarkGray, iconColor = chip.iconColor)
)
Spacer(modifier = Modifier.height(8.dp))
}
}
}
}
}
data class ChipData(val label: String, val iconRes: Int, val iconColor: Color, val onClick: () -> Unit)
@Preview(device = Devices.WEAR_OS_SMALL_ROUND, showSystemUi = true)
@Composable
fun DefaultPreview() {
WearApp()
}
| 0 | Kotlin | 0 | 0 | 9d2fa134ff335ce0968599f95409e889b0a7166b | 4,219 | wearos-health-tracker-app | MIT License |
solar/src/main/java/com/chiksmedina/solar/bold/electronicdevices/Mouse.kt | CMFerrer | 689,442,321 | false | {"Kotlin": 36591890} | package com.chiksmedina.solar.bold.electronicdevices
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 com.chiksmedina.solar.bold.ElectronicDevicesGroup
val ElectronicDevicesGroup.Mouse: ImageVector
get() {
if (_mouse != null) {
return _mouse!!
}
_mouse = Builder(
name = "Mouse", defaultWidth = 24.0.dp, defaultHeight = 24.0.dp,
viewportWidth = 24.0f, viewportHeight = 24.0f
).apply {
path(
fill = SolidColor(Color(0xFF000000)), stroke = null, strokeLineWidth = 0.0f,
strokeLineCap = Butt, strokeLineJoin = Miter, strokeLineMiter = 4.0f,
pathFillType = NonZero
) {
moveTo(19.0f, 8.9741f)
verticalLineTo(14.9861f)
curveTo(19.0f, 18.8598f, 15.866f, 22.0f, 12.0f, 22.0f)
curveTo(8.134f, 22.0f, 5.0f, 18.8598f, 5.0f, 14.9861f)
verticalLineTo(8.9741f)
curveTo(5.0f, 5.3543f, 7.7367f, 2.375f, 11.25f, 2.0f)
verticalLineTo(5.3854f)
curveTo(10.6588f, 5.6669f, 10.25f, 6.2707f, 10.25f, 6.9702f)
verticalLineTo(8.9741f)
curveTo(10.25f, 9.9426f, 11.0335f, 10.7276f, 12.0f, 10.7276f)
curveTo(12.9665f, 10.7276f, 13.75f, 9.9426f, 13.75f, 8.9741f)
verticalLineTo(6.9702f)
curveTo(13.75f, 6.2707f, 13.3412f, 5.6669f, 12.75f, 5.3854f)
verticalLineTo(2.0f)
curveTo(16.2633f, 2.375f, 19.0f, 5.3543f, 19.0f, 8.9741f)
close()
}
}
.build()
return _mouse!!
}
private var _mouse: ImageVector? = null
| 0 | Kotlin | 0 | 0 | 3414a20650d644afac2581ad87a8525971222678 | 2,163 | SolarIconSetAndroid | MIT License |
core/src/main/kotlin/com/r4g3baby/simplemotd/ProjectInfo.kt | r4g3baby | 444,226,350 | false | {"Kotlin": 49549} | package com.r4g3baby.simplemotd
import net.swiftzer.semver.SemVer
import java.util.*
object ProjectInfo {
const val spigotID: Int = 2581
const val bStatsID: Int = 13853
var name: String = "NaN"
private set
var version: SemVer = SemVer()
private set
init {
javaClass.classLoader.getResource("project.properties")?.let { projectFile ->
val properties = Properties().apply {
load(projectFile.openStream())
}
name = properties.getProperty("name", name)
version = SemVer.parse(properties.getProperty("version", version.toString()))
}
}
} | 0 | Kotlin | 0 | 0 | fcd5198d9865177367aea2b7674f7ab84a90fb51 | 657 | SimpleMOTD | MIT License |
app/src/main/java/com/example/remotive/databases/CareerDatabase.kt | arnoldmuiruri | 379,566,676 | false | null | /*
* Copyright (c) 2021 <NAME>
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.example.remotive.databases
import androidx.room.Database
import androidx.room.RoomDatabase
import androidx.room.TypeConverters
import com.example.remotive.models.entities.Career
import com.example.remotive.models.entities.Converter
import com.example.remotive.models.entities.RemoteKeys
//Persistence class for the careers and
// remote keys entities class
@Database(
entities = [Career::class, RemoteKeys::class],
version = 1,
exportSchema = false
)
@TypeConverters(Converter::class)
abstract class CareerDatabase: RoomDatabase() {
abstract fun careersDao(): CareersDao
abstract fun remoteKeysDao(): RemoteKeysDao
} | 0 | Kotlin | 0 | 0 | f159867fe76b8c0f1cb0ca277119a7ddf28d4efc | 1,244 | Remotive | Apache License 2.0 |
epoxy-paging3/src/test/java/com/airbnb/epoxy/paging3/PagedDataModelCacheTest.kt | airbnb | 65,245,890 | false | {"Markdown": 5, "Gradle": 24, "Java Properties": 2, "Shell": 1, "Text": 1, "Ignore List": 20, "Batchfile": 1, "Kotlin": 207, "INI": 11, "Proguard": 10, "XML": 107, "Java": 535, "JSON": 3, "YAML": 1, "HTML": 1, "CSS": 2, "JavaScript": 1} | package com.airbnb.epoxy.paging3
import android.view.View
import androidx.paging.Pager
import androidx.paging.PagingConfig
import androidx.paging.PagingData
import com.airbnb.epoxy.EpoxyController
import com.airbnb.epoxy.EpoxyModel
import kotlinx.coroutines.ExperimentalCoroutinesApi
import kotlinx.coroutines.ObsoleteCoroutinesApi
import kotlinx.coroutines.async
import kotlinx.coroutines.delay
import kotlinx.coroutines.flow.collectLatest
import kotlinx.coroutines.runBlocking
import kotlinx.coroutines.test.advanceTimeBy
import kotlinx.coroutines.test.runTest
import org.hamcrest.CoreMatchers
import org.hamcrest.MatcherAssert
import org.junit.Assert.assertEquals
import org.junit.Test
import org.junit.runner.RunWith
import org.robolectric.RobolectricTestRunner
import org.robolectric.annotation.LooperMode
import kotlin.coroutines.CoroutineContext
@ExperimentalCoroutinesApi
@ObsoleteCoroutinesApi
@RunWith(RobolectricTestRunner::class)
@LooperMode(LooperMode.Mode.LEGACY)
class PagedDataModelCacheTest {
/**
* Simple mode builder for [DummyItem]
*/
private var modelBuildCounter = 0
private val modelBuilder: (Int, DummyItem?) -> EpoxyModel<*> = { pos, item ->
modelBuildCounter++
if (item == null) {
FakePlaceholderModel(pos)
} else {
FakeModel(item)
}
}
/**
* Number of times a rebuild is requested
*/
private var rebuildCounter = 0
private val rebuildCallback: () -> Unit = {
rebuildCounter++
}
private val pagedDataModelCache =
PagedDataModelCache(
modelBuilder = modelBuilder,
rebuildCallback = rebuildCallback,
itemDiffCallback = DummyItem.DIFF_CALLBACK,
modelBuildingHandler = EpoxyController.defaultModelBuildingHandler
)
@Test
fun empty() {
MatcherAssert.assertThat(pagedDataModelCache.getModels(), CoreMatchers.`is`(emptyList()))
}
@Test
fun simple() = runBlocking {
val items = createDummyItems(PAGE_SIZE)
val pagedData = createPagedData(items)
pagedDataModelCache.submitData(pagedData)
assertModelDummyItems(items)
assertAndResetRebuildModels()
}
@Test
fun partialLoad() = runTest {
val items = createDummyItems(INITIAL_LOAD_SIZE + PAGE_SIZE)
val pager = createPager(this.coroutineContext, items)
val deferred = async {
pager.flow.collectLatest {
pagedDataModelCache.submitData(it)
}
}
// advance in time to create first page of data
advanceTimeBy(DEFAULT_DELAY)
// wait for pagedDataModelCache submits data
delay(2000)
assertModelDummyItems(items.subList(0, INITIAL_LOAD_SIZE))
assertAndResetRebuildModels()
pagedDataModelCache.loadAround(INITIAL_LOAD_SIZE - 1)
assertModelDummyItems(items.subList(0, INITIAL_LOAD_SIZE))
MatcherAssert.assertThat(rebuildCounter, CoreMatchers.`is`(0))
// advance in time to create second page of data
advanceTimeBy(DEFAULT_DELAY)
delay(2000)
assertModelDummyItems(items)
assertAndResetRebuildModels()
deferred.cancel()
}
@Test
fun deletion() {
testListUpdate { items, models ->
Modification(
newList = items.copyToMutable().also {
it.removeAt(3)
},
expectedModels = models.toMutableList().also {
it.removeAt(3)
}
)
}
}
@Test
fun deletion_range() {
testListUpdate { items, models ->
Modification(
newList = items.copyToMutable().also {
it.removeAll(items.subList(3, 5))
},
expectedModels = models.toMutableList().also {
it.removeAll(models.subList(3, 5))
}
)
}
}
@Test
fun append() {
val newDummyItem = DummyItem(id = 100, value = "newDummyItem")
testListUpdate { items, models ->
Modification(
newList = items.copyToMutable().also {
it.add(newDummyItem)
},
expectedModels = models.toMutableList().also {
it.add(newDummyItem)
}
)
}
}
@Test
fun append_many() {
val newDummyItems = (100 until 105).map {
DummyItem(id = it, value = "newDummyItem $it")
}
testListUpdate { items, models ->
Modification(
newList = items.copyToMutable().also {
it.addAll(newDummyItems)
},
expectedModels = models.toMutableList().also {
it.addAll(newDummyItems)
}
)
}
}
@Test
fun insert() {
testListUpdate { items, models ->
val newDummyItem =
DummyItem(id = 100, value = "item x")
Modification(
newList = items.copyToMutable().also {
it.add(5, newDummyItem)
},
expectedModels = models.toMutableList().also {
it.add(5, newDummyItem)
}
)
}
}
@Test
fun insert_many() {
testListUpdate { items, models ->
val newDummyItems = (100 until 105).map {
DummyItem(id = it, value = "newDummyItem $it")
}
Modification(
newList = items.copyToMutable().also {
it.addAll(5, newDummyItems)
},
expectedModels = models.toMutableList().also {
it.addAll(5, newDummyItems)
}
)
}
}
@Test
fun move() {
testListUpdate { items, models ->
Modification(
newList = items.toMutableList().also {
it.add(3, it.removeAt(5))
},
expectedModels = models.toMutableList().also {
it.add(3, it.removeAt(5))
}
)
}
}
@Test
fun move_multiple() {
testListUpdate { items, models ->
Modification(
newList = items.toMutableList().also {
it.add(3, it.removeAt(5))
it.add(1, it.removeAt(8))
},
expectedModels = models.toMutableList().also {
it.add(3, it.removeAt(5))
it.add(1, it.removeAt(8))
}
)
}
}
@Test
fun clear() = runBlocking {
val items = createDummyItems(PAGE_SIZE)
val pagedData = createPagedData(items)
pagedDataModelCache.submitData(pagedData)
pagedDataModelCache.getModels()
assertAndResetModelBuild()
pagedDataModelCache.clearModels()
pagedDataModelCache.getModels()
assertAndResetModelBuild()
}
private fun assertAndResetModelBuild() {
MatcherAssert.assertThat(modelBuildCounter > 0, CoreMatchers.`is`(true))
modelBuildCounter = 0
}
private fun assertAndResetRebuildModels() {
MatcherAssert.assertThat(rebuildCounter > 0, CoreMatchers.`is`(true))
rebuildCounter = 0
}
/**
* Helper method to verify multiple list update scenarios
*/
private fun testListUpdate(update: (items: List<DummyItem>, models: List<Any?>) -> Modification) =
runBlocking {
val items = createDummyItems(PAGE_SIZE)
pagedDataModelCache.submitData(createPagedData(items))
val (updatedList, expectedModels) = update(items, collectModelDummyItems())
pagedDataModelCache.submitData(createPagedData(updatedList))
val updatedModels = collectModelDummyItems()
MatcherAssert.assertThat(updatedModels.size, CoreMatchers.`is`(expectedModels.size))
updatedModels.forEachIndexed { index, item ->
when (item) {
is DummyItem -> {
assertEquals(item, expectedModels[index])
}
else -> {
MatcherAssert.assertThat(item, CoreMatchers.`is`(expectedModels[index]))
}
}
}
}
private fun assertModelDummyItems(expected: List<Any?>) {
MatcherAssert.assertThat(collectModelDummyItems(), CoreMatchers.`is`(expected))
}
@Suppress("IMPLICIT_CAST_TO_ANY")
private fun collectModelDummyItems(): List<Any?> {
return pagedDataModelCache.getModels().map {
when (it) {
is FakeModel -> it.item
is FakePlaceholderModel -> it.pos
else -> null
}
}
}
private fun createDummyItems(cnt: Int): List<DummyItem> {
return (0 until cnt).map {
DummyItem(id = it, value = "DummyItem $it")
}
}
private fun createPagedData(items: List<DummyItem>): PagingData<DummyItem> {
return PagingData.from(items)
}
private fun createPager(
coroutineContext: CoroutineContext,
items: List<DummyItem>
): Pager<Int, DummyItem> {
return Pager(
config = PagingConfig(
pageSize = PAGE_SIZE,
initialLoadSize = INITIAL_LOAD_SIZE,
enablePlaceholders = true,
),
initialKey = null,
pagingSourceFactory = {
ListPagingSource(coroutineContext, DEFAULT_DELAY, items)
}
)
}
class FakePlaceholderModel(val pos: Int) : EpoxyModel<View>(-pos.toLong()) {
override fun getDefaultLayout() = throw NotImplementedError("not needed for this test")
}
class FakeModel(val item: DummyItem) : EpoxyModel<View>(item.id.toLong()) {
override fun getDefaultLayout() = throw NotImplementedError("not needed for this test")
}
data class Modification(
val newList: List<DummyItem>,
val expectedModels: List<Any?>
)
private fun List<DummyItem>.copyToMutable(): MutableList<DummyItem> {
return mapTo(arrayListOf()) {
it.copy()
}
}
companion object {
private const val PAGE_SIZE = 10
private const val INITIAL_LOAD_SIZE = PAGE_SIZE * 2
private const val DEFAULT_DELAY = 10000L
}
}
| 315 | Java | 728 | 8,460 | c0813764351e4de97b7abd0694af5dad9db848f2 | 10,600 | epoxy | Apache License 2.0 |
generated-sources/kotlin-server/mojang-authentication/src/main/kotlin/com/github/asyncmc/mojang/authentication/kotlin/server/model/Agent.kt | AsyncMC | 269,845,234 | false | {"Java": 3133439, "C#": 2186101, "C++": 1928640, "PHP": 1682475, "TypeScript": 730015, "Shell": 660104, "Python": 613719, "Ruby": 602211, "Swift": 596778, "Scala": 587419, "JavaScript": 531265, "Rust": 430285, "Haskell": 377293, "Objective-C": 370309, "Ada": 348433, "Perl": 317997, "Eiffel": 315566, "Apex": 315484, "Erlang": 269067, "Kotlin": 259211, "C": 252805, "Go": 208277, "Dart": 181610, "ActionScript": 161847, "R": 113255, "Lua": 105036, "Raku": 82855, "Elixir": 78429, "Elm": 69223, "HTML": 66704, "PowerShell": 60833, "Clojure": 55152, "Groovy": 37392, "CMake": 31575, "CSS": 21108, "Dockerfile": 18359, "TSQL": 9158, "Batchfile": 8384, "QMake": 4256, "Gherkin": 3804, "Vue": 2260, "Makefile": 1792} | /**
* Mojang Authentication API
* No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator)
*
* OpenAPI spec version: 2020-06-05
*
*
* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
* https://openapi-generator.tech
* Do not edit the class manually.
*/
package com.github.asyncmc.mojang.authentication.kotlin.server.model
/**
* Identifies the software doing the request
* @param name The name of the game
* @param version The agent version, usually 1.
*/
data class Agent (
/* The name of the game */
val name: Agent.Name? = null,
/* The agent version, usually 1. */
val version: kotlin.Int? = null
) {
/**
* The name of the game
* Values: MINECRAFT,SCROLLS
*/
enum class Name(val value: kotlin.String){
MINECRAFT("Minecraft"),
SCROLLS("Scrolls");
}
}
| 4 | null | 1 | 1 | b01bbd2bce44bfa2b9ed705a128cf4ecda077916 | 924 | Mojang-API-Libs | Apache License 2.0 |
app/src/main/kotlin/jp/co/yumemi/android/code_check/model/SearchGithubRepositoryModel.kt | darmadevZone | 756,302,788 | false | {"Kotlin": 27415} | package jp.co.yumemi.android.code_check.model
import com.squareup.moshi.Json
import com.squareup.moshi.JsonClass
@JsonClass(generateAdapter = true)
data class SearchGithubRepositoryModel(
@Json(name = "incomplete_results")
val incompleteResults: Boolean?,
val items: List<Item>,
@Json(name = "total_count")
val totalCount: Int?
)
| 4 | Kotlin | 0 | 1 | f4a7137965c5f752166c3e84f1e403be335ae8d4 | 352 | yumemi-coding-test | Apache License 2.0 |
app/src/main/java/org/stepic/droid/storage/migration/MigrationFrom45To46.kt | StepicOrg | 42,045,161 | false | {"Kotlin": 4281147, "Java": 1001895, "CSS": 5482, "Shell": 618} | package org.stepic.droid.storage.migration
import androidx.room.migration.Migration
import androidx.sqlite.db.SupportSQLiteDatabase
import org.stepic.droid.storage.structure.DbStructureCertificateViewItem
import org.stepik.android.cache.certificates.structure.DbStructureCertificate
object MigrationFrom45To46 : Migration(45, 46) {
private const val CODE_SUBMISSION = "code_submission"
override fun migrate(db: SupportSQLiteDatabase) {
DbStructureCertificate.createTable(db)
dropCodeSubmissionTable(db)
dropCertificateViewItemTable(db)
}
private fun dropCodeSubmissionTable(db: SupportSQLiteDatabase) {
db.execSQL("""
DROP TABLE IF EXISTS $CODE_SUBMISSION
""".trimIndent())
}
private fun dropCertificateViewItemTable(db: SupportSQLiteDatabase) {
db.execSQL("""
DROP TABLE IF EXISTS ${DbStructureCertificateViewItem.CERTIFICATE_VIEW_ITEM}
""".trimIndent())
}
} | 13 | Kotlin | 54 | 189 | dd12cb96811a6fc2a7addcd969381570e335aca7 | 972 | stepik-android | Apache License 2.0 |
app/src/main/java/com/evoke/irascompanion/backend/BasicOperations.kt | muyeed15 | 855,594,934 | false | {"Kotlin": 46892} | package com.evoke.irascompanion.backend
import java.text.SimpleDateFormat
import java.util.Date
import java.util.Locale
class BasicOperations {
fun getLastName(fullName: String): String {
val nameParts = fullName.split(" ")
return if (nameParts.size > 1) nameParts.last() else fullName
}
fun getCurrentCourses(jsonString: String): List<Map<String, Any?>> {
val dataMapList = JsonFormatter().formatListMap(jsonString)
val currentCourses = mutableListOf<Map<String, Any?>>()
for (dataMap in dataMapList) {
if (dataMap.getValue("grade") == "Z"){
currentCourses.add(dataMap)
}
}
return currentCourses
}
fun getCurrentSemester(jsonString: String): List<String> {
val dataMapList = JsonFormatter().formatListMap(jsonString)
val currentSemester = mutableListOf<String>()
for (dataMap in dataMapList) {
if (dataMap.getValue("grade") == "Z"){
val year = dataMap.getValue("regYear").toString()
val semester = dataMap.getValue("regSemester").toString()
when (semester) {
"1" -> {
currentSemester.add("Autumn")
}
"2" -> {
currentSemester.add("Spring")
}
"3" -> {
currentSemester.add("Summer")
}
else -> {
currentSemester.add("Unknown")
}
}
currentSemester.add(year)
break
}
}
return currentSemester
}
fun getSemesterWiseCourses(jsonString: String, semester: String, year: String): List<Map<String, Any?>> {
val dataMapList = JsonFormatter().formatListMap(jsonString)
val currentCourses = mutableListOf<Map<String, Any?>>()
val semesterCode: String = when (semester) {
"Autumn" -> {
"1"
}
"Spring" -> {
"2"
}
"Summer" -> {
"3"
}
else -> {
"0"
}
}
for (dataMap in dataMapList) {
if (dataMap.getValue("regSemester") == semesterCode && dataMap.getValue("regYear") == year){
currentCourses.add(dataMap)
}
}
return currentCourses
}
fun getDateTime(): List<String> {
val calendarInfo = mutableListOf<String>()
val timeFormatter = SimpleDateFormat("HH:mm", Locale.getDefault())
val dateFormatter = SimpleDateFormat("yyyy-MM-dd", Locale.getDefault())
val dayFormatter = SimpleDateFormat("EEEE", Locale.getDefault())
val currentDate = Date()
calendarInfo.add(timeFormatter.format(currentDate))
calendarInfo.add(dateFormatter.format(currentDate))
calendarInfo.add(dayFormatter.format(currentDate))
return calendarInfo
}
fun getTime12(time24: String): String {
val inputFormat = SimpleDateFormat("HH:mm", Locale.getDefault())
val outputFormat = SimpleDateFormat("hh:mm a", Locale.getDefault())
val date = inputFormat.parse(time24)
return outputFormat.format(date!!)
}
fun getTodayClasses(jsonString: String): List<Map<String, Any?>> {
val dataMapList = getCurrentCourses(jsonString)
val todayClasses = mutableListOf<Map<String, Any?>>()
val calendarInfo = getDateTime()
val currentDay = calendarInfo[2]
val today = when (currentDay) {
"Sunday", "Tuesday" -> {
"ST"
}
"Monday", "Wednesday" -> {
"MW"
}
"Saturday" -> {
"A"
}
"Thursday" -> {
"R"
}
else -> {
"Unknown"
}
}
for (dataMap in dataMapList) {
val classTime = dataMap.getValue("classTime").toString()
if (classTime.contains(today)) {
todayClasses.add(dataMap)
}
}
return todayClasses
}
fun getClasses(jsonString: String): List<List<Map<String, Any?>>> {
val dataMapList = getTodayClasses(jsonString)
val upcomingClasses = mutableListOf<Map<String, Any?>>()
val finishedClasses = mutableListOf<Map<String, Any?>>()
val runningClasses = mutableListOf<Map<String, Any?>>()
val calendarInfo = getDateTime()
val currentTime = calendarInfo[0].split(":")
for (dataMap in dataMapList) {
val classTime = dataMap.getValue("classTime").toString().split(":")
val classStartHour = classTime[1]
val classStartMin = classTime[2].substring(0, 2)
val classEndHour = classTime[2].substring(3, 5)
val classEndMin = classTime[3]
val currentHour = currentTime[0]
val currentMin = currentTime[1]
val classStartFloatTime = classStartHour.toFloat() + classStartMin.toFloat() / 100
val classEndFloatTime = classEndHour.toFloat() + classEndMin.toFloat() / 100
val currentFloatTime: Float = currentHour.toFloat() + currentMin.toFloat() / 100
if (currentFloatTime in classStartFloatTime..classEndFloatTime) {
runningClasses.add(dataMap)
} else if (currentFloatTime < classStartFloatTime) {
upcomingClasses.add(dataMap)
} else if (currentFloatTime > classEndFloatTime) {
finishedClasses.add(dataMap)
}
}
val sortByClassStartTime: (Map<String, Any?>) -> Float = { dataMap ->
val classTime = dataMap.getValue("classTime").toString().split(":")
val classStartHour = classTime[1]
val classStartMin = classTime[2].substring(0, 2)
classStartHour.toFloat() + classStartMin.toFloat() / 100
}
upcomingClasses.sortBy { sortByClassStartTime(it) }
runningClasses.sortBy { sortByClassStartTime(it) }
finishedClasses.sortBy { sortByClassStartTime(it) }
return listOf(upcomingClasses, runningClasses, finishedClasses)
}
}
fun main() {
val jsonString = "[{courseId=ACN201, courseName=Principles of Accounting, section=2.0, regYear=2024, regSemester=3, grade=Z, classCount=20.0, attend=12.0, wExpCount=0.0, roomId=BC3010, classTime=ST:08:00-09:30}, {courseId=ANT101, courseName=Introduction to Anthropology, section=8.0, regYear=2023, regSemester=3, grade=A-, classCount=26.0, attend=22.0, wExpCount=0.0, roomId=C6004, classTime=MW:09:40-11:10}, {courseId=BDS109, courseName=Bangladesh 1971 through the Lenses, section=4.0, regYear=2023, regSemester=1, grade=B, classCount=22.0, attend=18.0, wExpCount=0.0, roomId=BC7002, classTime=MW:11:20-12:50}, {courseId=CMN201, courseName=Introduction to Communication, section=6.0, regYear=2023, regSemester=2, grade=B+, classCount=22.0, attend=17.0, wExpCount=0.0, roomId=BC8012, classTime=ST:16:20-17:50}, {courseId=CSC101, courseName=Introduction to Computer Programming, section=6.0, regYear=2022, regSemester=1, grade=A-, classCount=14.0, attend=13.0, wExpCount=0.0, roomId=BC5002,, classTime=ST:11:20-12:50}, {courseId=CSC101L, courseName=Lab for CSC101, section=6.0, regYear=2022, regSemester=1, grade=A-, classCount=12.0, attend=10.0, wExpCount=0.0, roomId=CSCLab1, classTime=S:09:40-11:10}, {courseId=CSE104, courseName=Electrical Circuit Analysis, section=5.0, regYear=2023, regSemester=3, grade=C+, classCount=21.0, attend=14.0, wExpCount=0.0, roomId=BC6009, classTime=ST:13:00-14:30}, {courseId=CSE104L, courseName=Lab work based on CSE 104, section=5.0, regYear=2023, regSemester=3, grade=C+, classCount=11.0, attend=9.0, wExpCount=0.0, roomId=CENLAB, classTime=T:11:20-12:50}, {courseId=CSE201, courseName=Discrete Mathematics, section=9.0, regYear=2023, regSemester=2, grade=B+, classCount=21.0, attend=20.0, wExpCount=0.0, roomId=MK5004, classTime=ST:11:20-12:50}, {courseId=CSE203, courseName=Data Structure, section=18.0, regYear=2023, regSemester=3, grade=D, classCount=23.0, attend=18.0, wExpCount=0.0, roomId=MK4005, classTime=MW:11:20-12:50}, {courseId=CSE203L, courseName=Data Structure Lab, section=18.0, regYear=2023, regSemester=3, grade=D, classCount=13.0, attend=8.0, wExpCount=0.0, roomId=CSCLab3, classTime=M:13:00-14:30}, {courseId=CSE204, courseName=Digital Logic Design, section=1.0, regYear=2023, regSemester=1, grade=B+, classCount=23.0, attend=19.0, wExpCount=0.0, roomId=BC5014, classTime=ST:09:40-11:10}, {courseId=CSE204L, courseName=Labwork based on CSE 204, section=1.0, regYear=2023, regSemester=1, grade=B+, classCount=10.0, attend=9.0, wExpCount=0.0, roomId=CENLAB, classTime=S:08:00-09:30}, {courseId=CSE211, courseName=Algorithms, section=8.0, regYear=2023, regSemester=1, grade=B+, classCount=21.0, attend=17.0, wExpCount=0.0, roomId=BC7025, classTime=MW:08:00-09:30}, {courseId=CSE211L, courseName=Labwork based on CSE 211, section=8.0, regYear=2023, regSemester=1, grade=B+, classCount=11.0, attend=7.0, wExpCount=0.0, roomId=CSCLab3, classTime=W:09:40-11:10}, {courseId=CSE213, courseName=Object Oriented Programming, section=4.0, regYear=2024, regSemester=2, grade=B+, classCount=17.0, attend=14.0, wExpCount=0.0, roomId=GPLab, classTime=MW:11:20-12:50}, {courseId=CSE213L, courseName=Labwork based on CSE 213, section=4.0, regYear=2024, regSemester=2, grade=B+, classCount=11.0, attend=9.0, wExpCount=0.0, roomId=GPLab, classTime=W:09:40-11:10}, {courseId=CSE214, courseName=Computer Organization & Architecture, section=2.0, regYear=2024, regSemester=2, grade=B-, classCount=20.0, attend=15.0, wExpCount=0.0, roomId=BC6009, classTime=ST:14:40-16:10}, {courseId=CSE303, courseName=Database Management, section=2.0, regYear=2024, regSemester=3, grade=Z, classCount=16.0, attend=12.0, wExpCount=0.0, roomId=BC5012, classTime=MW:08:00-09:30}, {courseId=CSE303L, courseName=Labwork based on CSE303, section=2.0, regYear=2024, regSemester=3, grade=Z, classCount=8.0, attend=4.0, wExpCount=0.0, roomId=MK7005L, classTime=T:13:00-14:30}, {courseId=ENG101, courseName=English Listening & Speaking Skills, section=24.0, regYear=2022, regSemester=1, grade=A, classCount=24.0, attend=20.0, wExpCount=0.0, roomId=BC7025, classTime=ST:14:40-16:10}, {courseId=ENG102, courseName=English Reading Skills, section=14.0, regYear=2023, regSemester=3, grade=B+, classCount=25.0, attend=18.0, wExpCount=0.0, roomId=BC7025, classTime=ST:08:00-09:30}, {courseId=ENG105, courseName=Business English, section=3.0, regYear=2024, regSemester=3, grade=Z, classCount=18.0, attend=12.0, wExpCount=0.0, roomId=BC7016, classTime=MW:09:40-11:10}, {courseId=MAT104, courseName=Calculus and analytical geometry, section=7.0, regYear=2022, regSemester=1, grade=B, classCount=22.0, attend=19.0, wExpCount=0.0, roomId=BC10018, classTime=MW:14:40-16:10}, {courseId=MAT212, courseName=Probability & Statistics for Science & Engineering, section=1.0, regYear=2024, regSemester=2, grade=A-, classCount=23.0, attend=16.0, wExpCount=0.0, roomId=BC5012, classTime=MW:13:00-14:30}, {courseId=MGT201, courseName=Principles of Management, section=4.0, regYear=2024, regSemester=3, grade=Z, classCount=16.0, attend=13.0, wExpCount=0.0, roomId=BC2021, classTime=ST:09:40-11:10}, {courseId=MUS101, courseName=Music Appreciation, section=2.0, regYear=2023, regSemester=1, grade=A, classCount=26.0, attend=23.0, wExpCount=0.0, roomId=BC7002, classTime=ST:11:20-12:50}, {courseId=PHY101, courseName=University Physics-I, section=3.0, regYear=2022, regSemester=1, grade=B-, classCount=25.0, attend=19.0, wExpCount=0.0, roomId=BC6012, classTime=MW:13:00-14:30}, {courseId=PHY101L, courseName=University Physics-I Lab, section=8.0, regYear=2022, regSemester=1, grade=B-, classCount=12.0, attend=8.0, wExpCount=0.0, roomId=PLab, classTime=W:11:20-12:50}, {courseId=PHY102, courseName=University Physics-II, section=4.0, regYear=2023, regSemester=2, grade=C-, classCount=24.0, attend=17.0, wExpCount=0.0, roomId=MK5004, classTime=MW:09:40-11:10}, {courseId=PHY102L, courseName=University Physics-II Lab, section=4.0, regYear=2023, regSemester=2, grade=A-, classCount=9.0, attend=6.0, wExpCount=0.0, roomId=PLab2, classTime=S:09:40-11:10}]"
println(BasicOperations().getClasses(jsonString))
} | 0 | Kotlin | 0 | 0 | 27f08f27691e2be4ef9aed874d9fa58ad4879473 | 12,492 | iRAS-Companion | MIT License |
data-settings/src/androidTest/java/de/niklasbednarczyk/nbweather/data/settings/serializers/SettingsFontSerializerTest.kt | NiklasBednarczyk | 529,683,941 | false | {"Kotlin": 1065284} | package de.niklasbednarczyk.nbweather.data.settings.serializers
import androidx.datastore.core.Serializer
import de.niklasbednarczyk.nbweather.data.settings.proto.font.SettingsFontProto
import de.niklasbednarczyk.nbweather.test.data.disk.serializers.NBSerializerTest
class SettingsFontSerializerTest : NBSerializerTest<SettingsFontProto>() {
override fun createSerializer(): Serializer<SettingsFontProto> {
return SettingsFontSerializer()
}
override val expectedDefaultValue: SettingsFontProto
get() {
return SettingsFontSerializer.createDefaultValue()
}
override val expectedNewValue: SettingsFontProto
get() {
return SettingsFontProto.getDefaultInstance()
}
} | 14 | Kotlin | 0 | 1 | aa09037fa77f495d6dbf5cdde88e4c2872fc1cf8 | 747 | NBWeather | MIT License |
src/main/kotlin/io/emeraldpay/dshackle/upstream/ethereum/NormalizingReader.kt | emeraldpay | 191,297,773 | false | {"Kotlin": 1137780, "Groovy": 481303, "Shell": 646} | package io.emeraldpay.dshackle.upstream.ethereum
import io.emeraldpay.dshackle.cache.Caches
import io.emeraldpay.dshackle.data.BlockId
import io.emeraldpay.dshackle.reader.DshackleRpcReader
import io.emeraldpay.dshackle.reader.Reader
import io.emeraldpay.dshackle.upstream.Head
import io.emeraldpay.dshackle.upstream.MethodSpecificReader
import io.emeraldpay.dshackle.upstream.rpcclient.DshackleRequest
import io.emeraldpay.dshackle.upstream.rpcclient.DshackleResponse
import io.emeraldpay.etherjar.hex.HexQuantity
import org.slf4j.LoggerFactory
import reactor.core.publisher.Mono
import java.util.concurrent.atomic.AtomicReference
class NormalizingReader(
private val head: AtomicReference<Head>,
private val caches: Caches,
fullBlocksReader: EthereumFullBlocksReader,
) : MethodSpecificReader(), DshackleRpcReader {
companion object {
private val log = LoggerFactory.getLogger(NormalizingReader::class.java)
private val HEX_REGEX = Regex("^0x[0-9a-fA-F]+$")
}
// TODO make configurable, and it supposed to go into the cache config but read from here
private val blockInCache = 6
private val blockByHashFull = BlockByHash(fullBlocksReader)
private val blockByHashAuto = BlockByHashAuto(blockByHashFull)
private val blockByNumber = BlockByNumber(fullBlocksReader, caches.getBlockHashByHeight(), blockByHashAuto)
private val blockByTag = BlockByTag(head, blockByNumber)
init {
register(
"eth_getBlockByHash",
{ params -> params.size >= 2 && acceptBlock(params[0].toString()) && params[1] == true },
blockByHashFull
)
register(
"eth_getBlockByNumber",
{ params -> params.size >= 2 && params[0] is String && acceptBlock(params[0].toString()) && params[1] == true },
blockByNumber
)
register(
"eth_getBlockByNumber",
{ params -> params.size >= 2 && params[0] is String && !isBlockOrNumber(params[0].toString()) && acceptBlock(params[0].toString()) && params[1] == true },
blockByTag
)
}
fun isBlockOrNumber(id: String): Boolean {
return id.matches(HEX_REGEX) && id.length == 66 || id.length <= 18
}
fun acceptHeight(height: Long): Boolean {
val current = head.get().getCurrentHeight() ?: return false
return height >= current - blockInCache
}
fun acceptBlock(id: String): Boolean {
if (id == "latest") {
return true
}
if (!isBlockOrNumber(id)) {
return false
}
val height = if (id.length == 66) {
val blockId = try {
BlockId.from(id)
} catch (t: Throwable) {
return false
}
caches.getHeightByHash(blockId) ?: return false
} else {
try {
HexQuantity.from(id).value.longValueExact()
} catch (t: Throwable) {
return false
}
}
return acceptHeight(height)
}
class BlockByHash(private val fullBlocksReader: EthereumFullBlocksReader) : DshackleRpcReader {
override fun read(key: DshackleRequest): Mono<DshackleResponse> {
val id = try {
BlockId.from(key.params[0] as String)
} catch (t: Throwable) {
log.warn("Invalid request ${key.method}(${key.params}")
return Mono.empty()
}
return fullBlocksReader.byHash.read(id)
.filter { it.json != null }
.map {
DshackleResponse(key.id, it.json!!)
}
}
}
class BlockByHashAuto(private val blockByHash: BlockByHash) : DshackleRpcReader {
override fun read(key: DshackleRequest): Mono<DshackleResponse> {
if (key.params.size != 2) {
return Mono.empty()
}
val full = key.params[1] == true
return if (full) {
blockByHash.read(key)
} else {
Mono.empty()
}
}
}
class BlockByNumber(
private val fullBlocksReader: EthereumFullBlocksReader,
private val hashByHeight: Reader<Long, BlockId>,
private val delegate: DshackleRpcReader,
) : DshackleRpcReader {
override fun read(key: DshackleRequest): Mono<DshackleResponse> {
val height = try {
HexQuantity.from(key.params[0] as String).value.longValueExact()
} catch (t: Throwable) {
log.warn("Invalid request ${key.method}(${key.params}")
return Mono.empty()
}
val usingCachedHeight = hashByHeight.read(height)
.map {
DshackleRequest(key.id, "eth_getBlockByHash", listOf(it.toHex()) + key.params.drop(1))
}
.flatMap(delegate::read)
val readingFromRpc = fullBlocksReader.byHeight
.read(height)
.filter { it.json != null }
.map { DshackleResponse(key.id, it.json!!) }
return usingCachedHeight
.switchIfEmpty(readingFromRpc)
}
}
class BlockByTag(
private val head: AtomicReference<Head>,
private val delegate: DshackleRpcReader,
) : DshackleRpcReader {
override fun read(key: DshackleRequest): Mono<DshackleResponse> {
val number: Long
try {
val blockRef = key.params[0].toString()
when {
blockRef == "latest" -> {
number = head.get().getCurrentHeight() ?: return Mono.empty()
}
blockRef == "earliest" -> {
number = 0
}
blockRef == "pending" -> {
return Mono.empty()
}
else -> {
return Mono.empty()
}
}
} catch (e: IllegalArgumentException) {
log.warn("Not a block number", e)
return Mono.empty()
}
val request = DshackleRequest(key.id, "eth_getBlockByNumber", listOf(HexQuantity.from(number).toHex()) + key.params.drop(1))
return delegate.read(request)
}
}
}
| 74 | Kotlin | 63 | 292 | 8076c81dd6e8213b107718764ec9e094b7653f04 | 6,442 | dshackle | Apache License 2.0 |
CRM/src/main/kotlin/org/example/crm/repositories/specifications/MessageSpecs.kt | M4tT3d | 874,249,564 | false | {"Kotlin": 354206, "TypeScript": 180680, "JavaScript": 3610, "Dockerfile": 2844, "CSS": 2078, "HTML": 302} | package org.example.crm.repositories.specifications
import org.example.crm.entities.Message
import org.example.crm.utils.enums.Channel
import org.example.crm.utils.enums.Priority
import org.example.crm.utils.enums.State
import org.springframework.data.jpa.domain.Specification
object MessageSpecs {
fun stateEqual(state: State): Specification<Message> {
return Specification { root, _, criteriaBuilder ->
criteriaBuilder.equal(root.get<State>("state"), state)
}
}
fun priorityEqual(priority: Priority): Specification<Message> {
return Specification { root, _, criteriaBuilder ->
criteriaBuilder.equal(root.get<Priority>("priority"), priority)
}
}
fun channelEqual(channel: Channel): Specification<Message> {
return Specification { root, _, criteriaBuilder ->
criteriaBuilder.equal(root.get<Channel>("channel"), channel)
}
}
} | 0 | Kotlin | 0 | 0 | 26ff03cc3863e278d0ec6b87ced384122cf66c98 | 939 | wa2-project-job-placement | MIT License |
wallet/wallet-core/src/main/kotlin/co/nilin/opex/wallet/core/inout/WithdrawAcceptCommand.kt | opexdev | 370,411,517 | false | null | package co.nilin.opex.wallet.core.inout
import java.math.BigDecimal
class WithdrawAcceptCommand(
val withdrawId: String,
val destTransactionRef: String?,
val destNote: String?,
val appliedFee: BigDecimal
) | 30 | null | 20 | 46 | f1812b42b836babad24ca9ebbf63683b1c81713e | 223 | core | MIT License |
shared/src/commonMain/kotlin/com/example/coffeeshop/data/json_storage/model/OrderItemsModel.kt | larkes-cyber | 716,249,551 | false | {"Kotlin": 243966, "Swift": 80413} | package com.example.coffeeshop.data.json_storage.model
import com.example.coffeeshop.data.model.DataOrder
import kotlinx.serialization.Serializable
@Serializable
data class OrderItemsModel(
val list:List<DataOrder>
) | 0 | Kotlin | 0 | 1 | b032b04020b0d5d4885e8f94a83a06077f271c09 | 222 | CoffeeShop | Apache License 2.0 |
shared/core/navigation/api/src/commonMain/kotlin/org/mobilenativefoundation/store/news/shared/core/navigation/api/NavigationComponent.kt | matt-ramotar | 742,173,124 | false | {"Kotlin": 36554} | package org.mobilenativefoundation.store.news.shared.core.navigation.api
interface NavigationComponent {
val tabNavigator: TabNavigator
} | 1 | Kotlin | 0 | 0 | 6943b9218cd1aa765dc66145b75b1e63625091af | 142 | news | Apache License 2.0 |
browser-kotlin/src/jsMain/kotlin/web/midi/MIDIConnectionEventInit.kt | karakum-team | 393,199,102 | false | {"Kotlin": 6914539} | // Automatically generated - do not modify!
package web.midi
import js.objects.JsPlainObject
import web.events.EventInit
@JsPlainObject
external interface MIDIConnectionEventInit :
EventInit {
val port: MIDIPort?
}
| 0 | Kotlin | 7 | 31 | c3de7c4098277a67bd40a9f0687579a6b9956cb2 | 226 | types-kotlin | Apache License 2.0 |
feature/login/src/main/java/nl/jovmit/androiddevs/feature/login/LoginModule.kt | mitrejcevski | 694,536,267 | false | {"Kotlin": 79288} | package nl.jovmit.androiddevs.feature.login
import dagger.Module
import dagger.Provides
import dagger.hilt.InstallIn
import dagger.hilt.components.SingletonComponent
import kotlinx.coroutines.CoroutineDispatcher
import kotlinx.coroutines.Dispatchers
import javax.inject.Singleton
@Module
@InstallIn(SingletonComponent::class)
object LoginModule {
@Provides
@Singleton
fun provideUserCatalog(): UsersCatalog {
return InMemoryUsersCatalog(emptyMap())
}
} | 0 | Kotlin | 1 | 6 | f1d675c59af3789c5dc2e767e115dfffd5bf2ba9 | 479 | android-devs-app | Apache License 2.0 |
app/src/main/java/com/npes87184/pokeresearchdictionary/Dict/ChtDict.kt | npes87184 | 131,408,290 | false | null | package com.npes87184.pokeresearchdictionary.Dict
class ChtDict : BaseDict() {
override var strDictFileName: String = "cht.json"
init {
}
} | 5 | Kotlin | 0 | 1 | 85f5a59e46f4ff6b9d2fe47a76fd77097c53ed1f | 153 | PokeResearchDictionary | MIT License |
library/src/androidTest/java/io/constructor/runner/TestRunner.kt | Constructor-io | 132,483,938 | false | {"Kotlin": 549225} | package io.constructor.runner
import io.constructor.ConstructorIoApplication
import android.app.Application
import android.content.Context
import io.appflate.restmock.android.RESTMockTestRunner
/**
* Created by ravindra on 4/2/17.
*/
class TestRunner : RESTMockTestRunner() {
@Throws(InstantiationException::class, IllegalAccessException::class, ClassNotFoundException::class)
override fun newApplication(cl: ClassLoader, className: String, context: Context): Application {
return super.newApplication(cl, ConstructorIoApplication::class.java.name, context)
}
}
| 5 | Kotlin | 1 | 4 | bcd584b80dc16ea83eec5452d1535603fe6325b1 | 588 | constructorio-client-android | MIT License |
common-android/src/main/java/com/base/common_android/ui/mvi/DefaultViewEvent.kt | MikeSPtr | 468,436,885 | false | null | package com.base.common_android.ui.mvi
sealed class DefaultViewEvent : IViewEvent {
data class ErrorViewEvent(
val error: Throwable?,
val message: String?
) : DefaultViewEvent()
data class InfoViewEvent(
val message: String?
) : DefaultViewEvent()
}
| 5 | Kotlin | 0 | 0 | 89f970c3b6046d842f10a40e35e38f41d7ed73ee | 292 | Android-Coroutines-CleanArchitecture-MVI | Apache License 2.0 |
compiler/testData/codegen/box/strings/twoArgumentStringTemplate.kt | JetBrains | 3,432,266 | false | {"Kotlin": 79571273, "Java": 6776465, "Swift": 4063829, "C": 2609744, "C++": 1957654, "Objective-C++": 175279, "JavaScript": 130754, "Python": 59855, "Shell": 34920, "Objective-C": 21463, "Lex": 21452, "Batchfile": 11382, "CSS": 11368, "Ruby": 10470, "Dockerfile": 9907, "Groovy": 7092, "EJS": 5241, "CMake": 4473, "HTML": 2699, "Puppet": 1698, "FreeMarker": 1393, "Roff": 725, "Scala": 80} | fun stringPlus(x: String?, y: Any?) = "$x$y"
fun box(): String {
val t1 = stringPlus("a", "b")
if (t1 != "ab") return "Failed: t1=$t1"
val t2 = stringPlus("a", null)
if (t2 != "anull") return "Failed: t2=$t2"
val t3 = stringPlus(null, "b")
if (t3 != "nullb") return "Failed: t3=$t3"
val t4 = stringPlus(null, null)
if (t4 != "nullnull") return "Failed: t4=$t4"
return "OK"
}
| 181 | Kotlin | 5748 | 49,172 | 33eb9cef3d146062c103f9853d772f0a1da0450e | 416 | kotlin | Apache License 2.0 |
game/src/main/kotlin/gg/rsmod/game/message/encoder/UpdateInvFullEncoder.kt | 2011Scape | 578,880,245 | false | {"Kotlin": 8359518, "Dockerfile": 1354} | package gg.rsmod.game.message.encoder
import gg.rsmod.game.message.MessageEncoder
import gg.rsmod.game.message.impl.UpdateInvFullMessage
import gg.rsmod.net.packet.DataOrder
import gg.rsmod.net.packet.DataType
import gg.rsmod.net.packet.GamePacketBuilder
import kotlin.math.min
/**
* @author Tom <<EMAIL>>
*/
class UpdateInvFullEncoder : MessageEncoder<UpdateInvFullMessage>() {
override fun extract(message: UpdateInvFullMessage, key: String): Number = when (key) {
"container_key" -> message.containerKey
"keyless" -> if(message.invother) 1 else 0
"item_count" -> message.items.size
else -> throw Exception("Unhandled value key.")
}
override fun extractBytes(message: UpdateInvFullMessage, key: String): ByteArray = when (key) {
"items" -> {
/**
* NOTE(Tom): this can change per revision, so figure out a way
* to externalize the structure.
*/
val buf = GamePacketBuilder()
message.items.forEach { item ->
if (item != null) {
buf.put(DataType.BYTE, min(item.amount, 255))
if (item.amount >= 255) {
buf.put(DataType.INT, item.amount)
}
buf.put(DataType.SHORT, DataOrder.LITTLE,item.id + 1)
} else {
buf.put(DataType.BYTE, 0)
buf.put(DataType.SHORT, 0)
}
}
val data = ByteArray(buf.byteBuf.readableBytes())
buf.byteBuf.readBytes(data)
data
}
else -> throw Exception("Unhandled value key.")
}
} | 36 | Kotlin | 138 | 32 | da66bb6d68ebae531ee325b909a6536e798b1144 | 1,688 | game | Apache License 2.0 |
app/src/main/java/com/teamsixers/vmail/ui/main/ShowAllCommandTask.kt | cyrilwongmy | 368,865,227 | false | null | package com.teamsixers.vmail.ui.main
/**
* Show all command Task in MainActivity.
*/
class ShowAllCommandTask: MainViewTask() {
/**
* doTask method will perform show all command tasks detail action
* @param activity MainActivity to perform show all command tasks.
*/
override fun doTask(activity: MainActivity) {
activity.textToSpeech("You can wake up voice assistant and say one of the following command, " +
"open folder, show all commands, log out, " +
"compose message and back for backing to previous page.")
}
} | 0 | Kotlin | 0 | 1 | 5424a29c5678f33c9c599a84b9b81b3aee086aff | 587 | VMaiL | MIT License |
buildSrc/src/main/kotlin/Artifactory.kt | ScottPierce | 247,381,019 | false | {"Objective-C": 134175, "Kotlin": 86484, "Swift": 7264, "Ruby": 4208, "Shell": 434} | import java.io.File
import java.io.FileReader
import java.util.Properties
import org.gradle.api.publish.PublishingExtension
import org.gradle.kotlin.dsl.maven
fun PublishingExtension.configureArtifactory() {
repositories.maven("https://artifacts.werally.in/artifactory/mobile-release/") {
name = "artifactory"
credentials {
username = System.getenv("ARTIFACTORY_USER")
password = System.getenv("ARTIFACTORY_PASSWORD")
}
}
}
data class ArtifactoryCredential(
val user: String,
val password: String
) {
companion object {
private var cache: ArtifactoryCredential? = null
private fun areCredentialsValid(user: String?, password: String?): Boolean {
return !user.isNullOrBlank() && password.isNullOrBlank()
}
fun load(): ArtifactoryCredential {
cache?.let { return it }
var user: String? = null
var password: String? = null
if (System.getenv().containsKey("ARTIFACTORY_USER") && System.getenv().containsKey("ARTIFACTORY_PASSWORD")) {
user = System.getenv("ARTIFACTORY_USER")
password = System.getenv("ARTIFACTORY_PASSWORD")
}
if (!areCredentialsValid(user, password)) {
val ivyFilePath: String = System.getProperty("user.home") + "/.ivy2/.credentials"
val ivyFile = File(ivyFilePath)
if (ivyFile.exists()) {
val props = Properties()
FileReader(ivyFile).use { reader ->
props.load(reader)
}
user = props.getProperty("user")
password = props.getProperty("password")
}
}
check(!areCredentialsValid(user, password)) { "Artifactory credentials are required, but not found." }
return ArtifactoryCredential(
user = user!!,
password = password!!
).also { cache = it }
}
}
}
| 0 | Objective-C | 0 | 0 | ca30b877f37c80c864b043a9919ce22be6c116fe | 2,070 | firebase-kotlin | Apache License 2.0 |
presentation/src/main/java/apps/ricasares/com/myreddit/di/UseCasesModule.kt | ricasares | 111,749,327 | false | {"Gradle": 7, "Java Properties": 2, "Shell": 1, "Text": 1, "Ignore List": 5, "Batchfile": 1, "XML": 17, "Kotlin": 88, "Proguard": 2, "Java": 1} | package apps.ricasares.com.myreddit.di
import apps.ricasares.com.domain.interactor.browse.GetListingUseCase
import apps.ricasares.com.domain.repository.ListingRepository
import apps.ricasares.com.domain.schedulers.ObserveOn
import apps.ricasares.com.domain.schedulers.SubscribeOn
import dagger.Module
/**
* Created by <NAME> on 3/29/18.
*/
@Module
class UseCasesModule {
fun provideGetListingUseCase(
listingRepository: ListingRepository,
subscribeOn: SubscribeOn,
observeOn: ObserveOn) : GetListingUseCase = GetListingUseCase(listingRepository, subscribeOn, observeOn)
} | 0 | Kotlin | 0 | 0 | 494494cbe7cf78af578946e922812f56697a0250 | 616 | RedditApp | Apache License 2.0 |
app/src/main/java/com/example/recyclerview/Constant4.kt | Devanshsati | 801,438,808 | false | {"Kotlin": 10227} | package com.example.recyclerview
object Constant2 {
fun getData(): ArrayList<RvModel>{
return arrayListOf(
RvModel(R.drawable.restaurant2, "Pumpkin Restaurant", "Dehradun, UK, India"),
RvModel(R.drawable.restaurant4, "La Belle Époque", "Paris, France"),
RvModel(R.drawable.restaurant2, "Il Gabbino", "Rome, Italy"),
RvModel(R.drawable.restaurant3, "El Asador de Aranda", "Madrid, Spain"),
RvModel(R.drawable.restaurant5, "The Fat Duck", "Bray, England"),
RvModel(R.drawable.restaurant1, "Noma", "Copenhagen, Denmark"),
RvModel(R.drawable.restaurant2, "Eleven Madison Park", "New York City, USA"),
RvModel(R.drawable.restaurant3, "Le Bernardin", "New York City, USA"),
RvModel(R.drawable.restaurant, "Sukiyabashi Jiro", "Tokyo, Japan"),
RvModel(R.drawable.restaurant5, "Green Garden Cafe", "Mumbai, MH, India"),
RvModel(R.drawable.restaurant5, "Sunrise Bistro", "Bangalore, KA, India"),
RvModel(R.drawable.restaurant1, "Moonlight Diner", "Chennai, TN, India"),
RvModel(R.drawable.restaurant1, "Golden Spoon", "Delhi, DL, India"),
RvModel(R.drawable.restaurant3, "Ocean's Delight", "Goa, GA, India"),
RvModel(R.drawable.restaurant4, "Mountain View Eatery", "Shimla, HP, India"),
RvModel(R.drawable.restaurant, "Urban Bites", "Kolkata, WB, India")
)
}
} | 0 | Kotlin | 0 | 0 | db682bd07c9c731385682d0f2aa7d96a713fbe0a | 1,467 | RecyclerView-Android | MIT License |
buildSrc/src/main/kotlin/jp/dely/koach/gradle/plugins/AndroidLibraryPlugin.kt | delyjp | 268,284,715 | false | null | package jp.dely.koach.gradle.plugins
import com.android.build.gradle.BaseExtension
import com.android.build.gradle.ProguardFiles.getDefaultProguardFile
import jp.dely.koach.gradle.extensions.androidTestImplementation
import jp.dely.koach.gradle.extensions.implementation
import jp.dely.koach.gradle.extensions.testImplementation
import jp.dely.koach.gradle.dependencies.Android
import jp.dely.koach.gradle.dependencies.Junit4
import jp.dely.koach.gradle.dependencies.Kotlin
import org.gradle.api.Plugin
import org.gradle.api.Project
import org.gradle.kotlin.dsl.dependencies
class AndroidLibraryPlugin : Plugin<Project> {
override fun apply(project: Project) {
val extension = project.extensions.findByName("android") as BaseExtension
extension.compileSdkVersion(29)
extension.defaultConfig {
minSdkVersion(15)
targetSdkVersion(29)
versionCode = 1
versionName = "1.0"
testInstrumentationRunner = "androidx.test.runner.AndroidJUnitRunner"
consumerProguardFile("consumer-rules.pro")
}
(extension.buildTypes.findByName("release")
?: extension.buildTypes.create("release")).apply {
isMinifyEnabled = false
proguardFiles(
getDefaultProguardFile("proguard-android-optimize.txt", project.layout),
"proguard-rules.pro"
)
}
extension.sourceSets.all {
java.srcDir("src/${name}/kotlin")
}
project.dependencies {
implementation(Kotlin.stdlib)
implementation(Android.appCompat)
testImplementation(Junit4.junit)
androidTestImplementation(Android.espresso)
androidTestImplementation(Android.junit)
}
}
} | 7 | Kotlin | 0 | 4 | e3c9b58c1f2db3e0bdde7fd1295c299689196847 | 1,809 | Koach | MIT License |
app/src/main/java/com/example/myapplication/util/Empty.kt | DeMoss15 | 222,141,463 | false | null | package com.example.myapplication.util
object Empty {
const val EMPTY_STRING: String = ""
} | 0 | Kotlin | 0 | 0 | bc9dd558000f8fbe996cca82477bea98dd2a5c31 | 96 | PaginatorRenderKit | Apache License 2.0 |
odnoklassniki-android-sdk/src/main/java/ru/ok/android/sdk/TokenStore.kt | wtb2015 | 158,838,424 | true | {"Kotlin": 63485, "Java": 12810} | package ru.ok.android.sdk
import android.content.Context
import android.content.SharedPreferences
import android.content.SharedPreferences.Editor
private const val PREF_ACCESS_TOKEN = "acctkn"
private const val PREF_SESSION_SECRET_KEY = "ssk"
private const val PREF_SDK_TOKEN = "<PASSWORD>"
internal object TokenStore {
@JvmStatic
fun store(context: Context, accessToken: String, sessionSecretKey: String) {
val prefs = getPreferences(context)
val editor = prefs.edit()
editor.putString(PREF_ACCESS_TOKEN, accessToken)
editor.putString(PREF_SESSION_SECRET_KEY, sessionSecretKey)
editor.apply()
}
@JvmStatic
fun removeStoredTokens(context: Context) {
val editor = getPreferences(context).edit()
editor.remove(PREF_ACCESS_TOKEN)
editor.remove(PREF_SESSION_SECRET_KEY)
editor.remove(PREF_SDK_TOKEN)
editor.apply()
}
@JvmStatic
fun getStoredAccessToken(context: Context): String? =
getPreferences(context).getString(PREF_ACCESS_TOKEN, null)
@JvmStatic
fun getStoredSessionSecretKey(context: Context): String? =
getPreferences(context).getString(PREF_SESSION_SECRET_KEY, null)
private fun getPreferences(context: Context): SharedPreferences =
context.getSharedPreferences(Shared.PREFERENCES_FILE, Context.MODE_PRIVATE)
@JvmStatic
fun storeSdkToken(context: Context, sdkToken: String) {
val editor = getPreferences(context).edit()
editor.putString(PREF_SDK_TOKEN, sdkToken)
editor.apply()
}
@JvmStatic
fun getSdkToken(context: Context): String? =
getPreferences(context).getString(PREF_SDK_TOKEN, null)
}
| 0 | Kotlin | 0 | 0 | 349d55a51161714a76e99e8656db60e1e0752c70 | 1,725 | ok-android-sdk | Apache License 2.0 |
tabsflip/src/main/java/com/hardik/tabsflip/FlipTab.kt | Hardik8184 | 225,533,706 | false | null | package com.hardik.tabsflip
import android.animation.AnimatorSet
import android.animation.ObjectAnimator
import android.content.Context
import android.graphics.Color
import android.graphics.drawable.GradientDrawable
import android.os.Build
import androidx.annotation.RequiresApi
import androidx.core.graphics.drawable.DrawableCompat
import android.util.AttributeSet
import android.util.TypedValue
import android.view.ViewGroup
import android.widget.FrameLayout
import com.jem.fliptabs.R.drawable
import com.jem.fliptabs.R.layout
import com.jem.fliptabs.R.styleable
import kotlinx.android.synthetic.main.fliptab.view.*
class FlipTab : FrameLayout {
constructor(context: Context) : super(context)
constructor(
context: Context,
attrs: AttributeSet?
) : super(context, attrs) {
initialize(attrs)
}
constructor(
context: Context,
attrs: AttributeSet?,
defStyleAttr: Int
) : super(
context,
attrs,
defStyleAttr
) {
initialize(attrs)
}
@RequiresApi(Build.VERSION_CODES.LOLLIPOP)
constructor(
context: Context,
attrs: AttributeSet?,
defStyleAttr: Int,
defStyleRes: Int
) : super(context, attrs, defStyleAttr, defStyleRes) {
initialize(attrs)
}
private var isLeftSelected: Boolean = true
private var animationMiddleViewFlippedFlag: Boolean = false
private val leftTabText get() = tab_left.text.toString()
private val rightTabText get() = tab_right.text.toString()
private var tabSelectedListener: TabSelectedListener? = null
private val leftSelectedDrawable by lazy {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
resources.getDrawable(drawable.tab_left_selected, null)
} else {
resources.getDrawable(drawable.tab_left_selected)
}
}
private val rightSelectedDrawable by lazy {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
resources.getDrawable(drawable.tab_right_selected, null)
} else {
resources.getDrawable(drawable.tab_right_selected)
}
}
companion object {
private val FLIP_ANIMATION_DURATION = 500
private val WOBBLE_RETURN_ANIMATION_DURATION = 250
private val WOBBLE_ANGLE: Float = 5f
private val OVERALL_COLOR: Int = Color.parseColor("#ff0099cc")
}
private var flipAnimationDuration =
FLIP_ANIMATION_DURATION
private var wobbleReturnAnimationDuration =
WOBBLE_RETURN_ANIMATION_DURATION
private var wobbleAngle = WOBBLE_ANGLE
init {
inflate(context, layout.fliptab, this)
tab_left.setOnClickListener {
if (isLeftSelected) {
tabSelectedListener?.onTabReselected(isLeftSelected, leftTabText)
} else {
flipTabs()
}
}
tab_right.setOnClickListener {
if (isLeftSelected) {
flipTabs()
} else {
tabSelectedListener?.onTabReselected(isLeftSelected, rightTabText)
}
}
clipChildren = false
clipToPadding = false
}
private fun initialize(attrs: AttributeSet?) {
attrs?.let {
val typedArray = context.obtainStyledAttributes(
it,
styleable.FlipTab, 0, 0
)
typedArray.apply {
flipAnimationDuration =
getInt(
styleable.FlipTab_flipAnimationDuration,
FLIP_ANIMATION_DURATION
)
wobbleReturnAnimationDuration = getInt(
styleable.FlipTab_wobbleReturnAnimationDuration,
WOBBLE_RETURN_ANIMATION_DURATION
)
wobbleAngle = getFloat(
styleable.FlipTab_wobbleAngle,
WOBBLE_ANGLE
)
if (hasValue(styleable.FlipTab_overallColor)) {
setOverallColor(
getColor(
styleable.FlipTab_overallColor,
OVERALL_COLOR
)
)
} else {
setTextColor(
getColor(
styleable.FlipTab_textColor,
OVERALL_COLOR
)
)
setHighlightColor(
getColor(
styleable.FlipTab_highlightColor,
OVERALL_COLOR
)
)
}
if (typedArray.getInt(
styleable.FlipTab_startingTab, 0
) == 1
) {
isLeftSelected = false
tab_selected_container.rotationY = 180f
tab_selected.background = rightSelectedDrawable
tab_selected.scaleX = -1f
}
setLeftTabText(
getString(
styleable.FlipTab_leftTabText
) ?: "Left tab"
)
setRightTabText(
getString(
styleable.FlipTab_rightTabText
) ?: "Right tab"
)
}
typedArray.recycle()
}
}
public fun flipTabs() {
animationMiddleViewFlippedFlag = false
isLeftSelected = !isLeftSelected
tab_selected_container.animate()
.rotationY(if (isLeftSelected) 0f else 180f)
.setDuration(flipAnimationDuration.toLong())
.withStartAction {
(parent as ViewGroup?)?.clipChildren = false
(parent as ViewGroup?)?.clipToPadding = false
tabSelectedListener?.onTabSelected(
isLeftSelected,
if (isLeftSelected) leftTabText else rightTabText
)
}
.setUpdateListener {
if (animationMiddleViewFlippedFlag) return@setUpdateListener
//TODO: Find out a better alternative to changing Background in the middle of animation (might result in dropped frame/stutter)
if (isLeftSelected && tab_selected_container.rotationY <= 90f) {
animationMiddleViewFlippedFlag = true
tab_selected.text = leftTabText
tab_selected.background = leftSelectedDrawable
tab_selected.scaleX = 1f
} else if (!isLeftSelected && tab_selected_container.rotationY >= 90f) {
animationMiddleViewFlippedFlag = true
tab_selected.text = rightTabText
tab_selected.background = rightSelectedDrawable
tab_selected.scaleX = -1f
}
}
.withEndAction {
(parent as ViewGroup?)?.clipChildren = true
(parent as ViewGroup?)?.clipToPadding = true
}
.start()
val animSet = AnimatorSet()
val animator1 = ObjectAnimator.ofFloat(
base_fliptab_container, "rotationY", if (isLeftSelected) -wobbleAngle else wobbleAngle
)
animator1.duration = flipAnimationDuration.toLong()
val animator2 = ObjectAnimator.ofFloat(base_fliptab_container, "rotationY", 0f)
animator2.duration = wobbleReturnAnimationDuration.toLong()
animSet.playSequentially(animator1, animator2)
animSet.start()
}
public interface TabSelectedListener {
public fun onTabSelected(
isLeftTab: Boolean,
tabTextValue: String
): Unit
public fun onTabReselected(
isLeftTab: Boolean,
tabTextValue: String
): Unit
}
public fun setTabSelectedListener(tabSelectedListener: TabSelectedListener) {
this.tabSelectedListener = tabSelectedListener
}
public fun setWobbleAngle(angle: Float) {
wobbleAngle = angle
}
public fun setWobbleReturnAnimationDuration(duration: Int) {
wobbleReturnAnimationDuration = duration
}
public fun setFlipAnimationDuration(duration: Int) {
flipAnimationDuration = duration
}
public fun setOverallColor(color: Int) {
setTextColor(color)
setHighlightColor(color)
}
public fun setTextColor(color: Int) {
tab_left.setTextColor(color)
tab_right.setTextColor(color)
}
public fun setHighlightColor(color: Int) {
(tab_left.background as GradientDrawable)?.setStroke(
TypedValue.applyDimension(
TypedValue.COMPLEX_UNIT_DIP,
2f,
resources.displayMetrics
).toInt(), color
)
(tab_right.background as GradientDrawable)?.setStroke(
TypedValue.applyDimension(
TypedValue.COMPLEX_UNIT_DIP,
2f,
resources.displayMetrics
).toInt(), color
)
(tab_selected.background as GradientDrawable)?.setStroke(
TypedValue.applyDimension(
TypedValue.COMPLEX_UNIT_DIP,
2f,
resources.displayMetrics
).toInt(), color
)
(tab_selected.background as GradientDrawable)?.setColor(color)
DrawableCompat.setTint(leftSelectedDrawable, color)
DrawableCompat.setTint(rightSelectedDrawable, color)
}
public fun setLeftTabText(text: String) {
tab_left.text = text
if (isLeftSelected) {
tab_selected.text = text
}
}
public fun setRightTabText(text: String) {
tab_right.text = text
if (!isLeftSelected) {
tab_selected.text = text
}
}
public fun selectLeftTab(withAnimation: Boolean) {
if (!isLeftSelected) {
if (withAnimation) {
flipTabs()
} else {
isLeftSelected = true
tab_selected_container.rotationY = 0f
tab_selected.text = leftTabText
tab_selected.background = leftSelectedDrawable
tab_selected.scaleX = 1f
tabSelectedListener?.onTabSelected(isLeftSelected, leftTabText)
}
} else {
tabSelectedListener?.onTabReselected(isLeftSelected, leftTabText)
}
}
public fun selectRightTab(withAnimation: Boolean) {
if (isLeftSelected) {
if (withAnimation) {
flipTabs()
} else {
isLeftSelected = false
tab_selected_container.rotationY = 180f
tab_selected.text = rightTabText
tab_selected.background = rightSelectedDrawable
tab_selected.scaleX = -1f
tabSelectedListener?.onTabSelected(isLeftSelected, rightTabText)
}
} else {
tabSelectedListener?.onTabReselected(isLeftSelected, rightTabText)
}
}
} | 1 | null | 1 | 1 | 304ef3af3cd9ac43b02f18c2439c7b7dba62db27 | 9,795 | TabsFlipView | MIT License |
vok-example-crud-flow/src/main/kotlin/com/github/vok/example/crudflow/person/PersonView.kt | kutoman | 136,617,118 | true | {"Kotlin": 294612, "Java": 7954, "CSS": 201} | package com.github.vok.example.crudflow.person
import com.github.vok.karibudsl.flow.div
import com.github.vok.karibudsl.flow.navigateToView
import com.github.vok.karibudsl.flow.text
import com.github.vokorm.findById
import com.vaadin.flow.component.orderedlayout.VerticalLayout
import com.vaadin.flow.router.BeforeEvent
import com.vaadin.flow.router.HasUrlParameter
import com.vaadin.flow.router.Route
/**
* Demonstrates the ability to pass parameters to views.
* @author mavi
*/
@Route("person")
class PersonView: VerticalLayout(), HasUrlParameter<Long> {
override fun setParameter(event: BeforeEvent, id: Long?) {
val person = (if (id == null) null else Person.findById(id)) ?: return navigateToView<PersonListView>()
removeAll()
div {
text("$person")
}
}
}
| 0 | Kotlin | 0 | 0 | 17efb841fcc951715ad87b43946246b7c010b0d1 | 817 | vaadin-on-kotlin | MIT License |
clikt-mordant/src/commonMain/kotlin/com/github/ajalt/clikt/output/MordantHelpFormatter.kt | ajalt | 128,975,548 | false | {"Kotlin": 619429, "Shell": 1858, "Batchfile": 662} | package com.github.ajalt.clikt.output
import com.github.ajalt.clikt.core.Context
import com.github.ajalt.clikt.core.UsageError
import com.github.ajalt.clikt.core.terminal
import com.github.ajalt.clikt.output.HelpFormatter.ParameterHelp
import com.github.ajalt.mordant.rendering.Theme
import com.github.ajalt.mordant.rendering.Whitespace
import com.github.ajalt.mordant.rendering.Widget
import com.github.ajalt.mordant.table.verticalLayout
import com.github.ajalt.mordant.widgets.Text
import com.github.ajalt.mordant.widgets.definitionList
import com.github.ajalt.mordant.widgets.withPadding
/**
* Clikt's default HelpFormatter which uses Mordant to render its output.
*
* To customize help text, you can create a subclass and set it as the `helpFormatter` on your
* command's context.
*/
open class MordantHelpFormatter(
/**
* The current command's context.
*/
context: Context,
/**
* The string to show before the names of required options, or null to not show a mark.
*/
requiredOptionMarker: String? = null,
/**
* If true, the default values will be shown in the help text for parameters that have them.
*/
showDefaultValues: Boolean = false,
/**
* If true, a tag indicating the parameter is required will be shown after the description of
* required parameters.
*/
showRequiredTag: Boolean = false,
) : AbstractHelpFormatter<Widget>(
context,
requiredOptionMarker,
showDefaultValues,
showRequiredTag
) {
protected val theme: Theme get() = context.terminal.theme
override fun formatHelp(
error: UsageError?,
prolog: String,
epilog: String,
parameters: List<ParameterHelp>,
programName: String,
): String {
val widget = verticalLayout {
spacing = 1
cellsFrom(collectHelpParts(error, prolog, epilog, parameters, programName))
}
return context.terminal.render(widget)
}
override fun renderError(parameters: List<ParameterHelp>, error: UsageError): Widget {
return Text(renderErrorString(parameters, error))
}
override fun renderUsage(
parameters: List<ParameterHelp>,
programName: String,
): Widget {
val title = styleUsageTitle(localization.usageTitle())
val prog = "$title $programName"
val usageParts = renderUsageParametersString(parameters)
return if (usageParts.isEmpty()) {
Text(prog, whitespace = Whitespace.NORMAL)
} else {
definitionList {
entry(prog, Text(usageParts, whitespace = Whitespace.NORMAL))
inline = true
descriptionSpacing = 1
}
}
}
override fun renderProlog(prolog: String): Widget {
return renderWrappedText(prolog).withPadding(padEmptyLines = false) { left = 2 }
}
override fun renderEpilog(epilog: String): Widget {
return renderWrappedText(epilog)
}
override fun renderParameters(
parameters: List<ParameterHelp>,
): Widget = definitionList {
for (section in collectParameterSections(parameters)) {
entry(section.title, section.content)
}
}
override fun renderOptionGroup(
help: String?,
parameters: List<ParameterHelp.Option>,
): Widget {
val options = parameters.map(::renderOptionDefinition)
if (help == null) return buildParameterList(options)
val markdown = renderWrappedText(help).withPadding(padEmptyLines = false) {
top = 1
left = 2
bottom = 1
}
return verticalLayout {
cell(markdown)
cell(buildParameterList(options))
}
}
override fun normalizeParameter(name: String): String = "<${name.lowercase()}>"
override fun styleRequiredMarker(name: String): String = theme.style("danger")(name)
override fun styleHelpTag(name: String): String = theme.style("muted")(name)
override fun styleOptionName(name: String): String = theme.style("info")(name)
override fun styleArgumentName(name: String): String = theme.style("info")(name)
override fun styleSubcommandName(name: String): String = theme.style("info")(name)
override fun styleSectionTitle(title: String): String = theme.style("warning")(title)
override fun styleUsageTitle(title: String): String = theme.style("warning")(title)
override fun styleError(title: String): String = theme.style("danger")(title)
override fun styleOptionalUsageParameter(parameter: String): String {
return theme.style("muted")(parameter)
}
override fun styleMetavar(metavar: String): String {
return (theme.style("warning") + theme.style("muted"))(metavar)
}
override fun renderDefinitionTerm(row: DefinitionRow): Widget {
val termPrefix = when {
row.marker.isNullOrEmpty() -> " "
else -> row.marker + " ".drop(row.marker!!.length).ifEmpty { " " }
}
return Text(termPrefix + row.term, whitespace = Whitespace.PRE_WRAP)
}
override fun renderDefinitionDescription(row: DefinitionRow): Widget {
return if (row.description.isBlank()) Text("")
else renderWrappedText(row.description)
}
override fun buildParameterList(rows: List<DefinitionRow>): Widget {
return definitionList {
inline = true
for (row in rows) {
entry(renderDefinitionTerm(row), renderDefinitionDescription(row))
}
}
}
open fun renderWrappedText(text: String): Widget {
// Replace double newlines with a hard line break since there's no Whitespace equivalent for
// markdown's paragraph behavior.
return Text(text.replace("\n\n", "\u0085\u0085"), whitespace = Whitespace.NORMAL)
}
}
| 9 | Kotlin | 121 | 2,520 | 5593cd0b3645a2862b45ea574b1ae0dcb2e5db91 | 5,875 | clikt | Apache License 2.0 |
clikt-mordant/src/commonMain/kotlin/com/github/ajalt/clikt/output/MordantHelpFormatter.kt | ajalt | 128,975,548 | false | {"Kotlin": 619429, "Shell": 1858, "Batchfile": 662} | package com.github.ajalt.clikt.output
import com.github.ajalt.clikt.core.Context
import com.github.ajalt.clikt.core.UsageError
import com.github.ajalt.clikt.core.terminal
import com.github.ajalt.clikt.output.HelpFormatter.ParameterHelp
import com.github.ajalt.mordant.rendering.Theme
import com.github.ajalt.mordant.rendering.Whitespace
import com.github.ajalt.mordant.rendering.Widget
import com.github.ajalt.mordant.table.verticalLayout
import com.github.ajalt.mordant.widgets.Text
import com.github.ajalt.mordant.widgets.definitionList
import com.github.ajalt.mordant.widgets.withPadding
/**
* Clikt's default HelpFormatter which uses Mordant to render its output.
*
* To customize help text, you can create a subclass and set it as the `helpFormatter` on your
* command's context.
*/
open class MordantHelpFormatter(
/**
* The current command's context.
*/
context: Context,
/**
* The string to show before the names of required options, or null to not show a mark.
*/
requiredOptionMarker: String? = null,
/**
* If true, the default values will be shown in the help text for parameters that have them.
*/
showDefaultValues: Boolean = false,
/**
* If true, a tag indicating the parameter is required will be shown after the description of
* required parameters.
*/
showRequiredTag: Boolean = false,
) : AbstractHelpFormatter<Widget>(
context,
requiredOptionMarker,
showDefaultValues,
showRequiredTag
) {
protected val theme: Theme get() = context.terminal.theme
override fun formatHelp(
error: UsageError?,
prolog: String,
epilog: String,
parameters: List<ParameterHelp>,
programName: String,
): String {
val widget = verticalLayout {
spacing = 1
cellsFrom(collectHelpParts(error, prolog, epilog, parameters, programName))
}
return context.terminal.render(widget)
}
override fun renderError(parameters: List<ParameterHelp>, error: UsageError): Widget {
return Text(renderErrorString(parameters, error))
}
override fun renderUsage(
parameters: List<ParameterHelp>,
programName: String,
): Widget {
val title = styleUsageTitle(localization.usageTitle())
val prog = "$title $programName"
val usageParts = renderUsageParametersString(parameters)
return if (usageParts.isEmpty()) {
Text(prog, whitespace = Whitespace.NORMAL)
} else {
definitionList {
entry(prog, Text(usageParts, whitespace = Whitespace.NORMAL))
inline = true
descriptionSpacing = 1
}
}
}
override fun renderProlog(prolog: String): Widget {
return renderWrappedText(prolog).withPadding(padEmptyLines = false) { left = 2 }
}
override fun renderEpilog(epilog: String): Widget {
return renderWrappedText(epilog)
}
override fun renderParameters(
parameters: List<ParameterHelp>,
): Widget = definitionList {
for (section in collectParameterSections(parameters)) {
entry(section.title, section.content)
}
}
override fun renderOptionGroup(
help: String?,
parameters: List<ParameterHelp.Option>,
): Widget {
val options = parameters.map(::renderOptionDefinition)
if (help == null) return buildParameterList(options)
val markdown = renderWrappedText(help).withPadding(padEmptyLines = false) {
top = 1
left = 2
bottom = 1
}
return verticalLayout {
cell(markdown)
cell(buildParameterList(options))
}
}
override fun normalizeParameter(name: String): String = "<${name.lowercase()}>"
override fun styleRequiredMarker(name: String): String = theme.style("danger")(name)
override fun styleHelpTag(name: String): String = theme.style("muted")(name)
override fun styleOptionName(name: String): String = theme.style("info")(name)
override fun styleArgumentName(name: String): String = theme.style("info")(name)
override fun styleSubcommandName(name: String): String = theme.style("info")(name)
override fun styleSectionTitle(title: String): String = theme.style("warning")(title)
override fun styleUsageTitle(title: String): String = theme.style("warning")(title)
override fun styleError(title: String): String = theme.style("danger")(title)
override fun styleOptionalUsageParameter(parameter: String): String {
return theme.style("muted")(parameter)
}
override fun styleMetavar(metavar: String): String {
return (theme.style("warning") + theme.style("muted"))(metavar)
}
override fun renderDefinitionTerm(row: DefinitionRow): Widget {
val termPrefix = when {
row.marker.isNullOrEmpty() -> " "
else -> row.marker + " ".drop(row.marker!!.length).ifEmpty { " " }
}
return Text(termPrefix + row.term, whitespace = Whitespace.PRE_WRAP)
}
override fun renderDefinitionDescription(row: DefinitionRow): Widget {
return if (row.description.isBlank()) Text("")
else renderWrappedText(row.description)
}
override fun buildParameterList(rows: List<DefinitionRow>): Widget {
return definitionList {
inline = true
for (row in rows) {
entry(renderDefinitionTerm(row), renderDefinitionDescription(row))
}
}
}
open fun renderWrappedText(text: String): Widget {
// Replace double newlines with a hard line break since there's no Whitespace equivalent for
// markdown's paragraph behavior.
return Text(text.replace("\n\n", "\u0085\u0085"), whitespace = Whitespace.NORMAL)
}
}
| 9 | Kotlin | 121 | 2,520 | 5593cd0b3645a2862b45ea574b1ae0dcb2e5db91 | 5,875 | clikt | Apache License 2.0 |
keel-front50/src/main/kotlin/com/netflix/spinnaker/keel/front50/Front50Cache.kt | daniloti2005 | 368,344,129 | true | {"Kotlin": 3007380, "Java": 20143, "Slim": 359, "Shell": 338} | package com.netflix.spinnaker.keel.front50
import com.github.benmanes.caffeine.cache.AsyncLoadingCache
import com.netflix.spinnaker.keel.caffeine.CacheFactory
import com.netflix.spinnaker.keel.caffeine.CacheLoadingException
import com.netflix.spinnaker.keel.core.api.DEFAULT_SERVICE_ACCOUNT
import com.netflix.spinnaker.keel.exceptions.ApplicationNotFound
import com.netflix.spinnaker.keel.front50.model.Application
import com.netflix.spinnaker.keel.front50.model.Pipeline
import kotlinx.coroutines.future.await
import kotlinx.coroutines.runBlocking
import org.slf4j.LoggerFactory
import org.springframework.stereotype.Component
@Component
/**
* Memory-based cache for Front50 data. Primarily intended to avoid making repeated slow calls to Front50
* to retrieve application config in bulk (see [allApplications]), but has the side-benefit that retrieving
* individual application configs can be powered by the same bulk data.
*/
class Front50Cache(
private val front50Service: Front50Service,
private val cacheFactory: CacheFactory
) {
companion object {
private val log by lazy { LoggerFactory.getLogger(Front50Cache::class.java) }
}
private val applicationsByName: AsyncLoadingCache<String, Application> = cacheFactory
.asyncBulkLoadingCache(cacheName = "applicationsByName") {
runCatching {
log.debug("Retrieving all applications from Front50")
front50Service.allApplications(DEFAULT_SERVICE_ACCOUNT)
.associateBy { it.name.toLowerCase() }
}
.getOrElse { ex ->
throw CacheLoadingException("Error loading applicationsByName cache", ex)
}
}.also {
// force the cache to initialize
it.get("dummy")
}
private val pipelinesByApplication: AsyncLoadingCache<String, List<Pipeline>> = cacheFactory
.asyncLoadingCache(cacheName = "pipelinesByApplication") { app ->
runCatching {
front50Service.pipelinesByApplication(app)
}
.getOrElse { ex ->
throw CacheLoadingException("Error loading pipelines for app $app", ex)
}
}
/**
* Returns the list of all currently known [Application] configs in Spinnaker from the cache.
*
* The first call to this method is expected to be as slow as a direct call to [Front50Service], as
* the cache needs to be populated with a bulk call. Subsequent calls are expected to return
* near-instantaneously until the cache expires.
*/
suspend fun allApplications(): List<Application> =
applicationsByName.asMap().values.map { it.await() }
/**
* Returns the cached [Application] by name.
*
* This call is expected to be slow before the cache is populated or refreshed, which should be a sporadic event.
*/
suspend fun applicationByName(name: String): Application =
applicationsByName.get(name.toLowerCase()).await() ?: throw ApplicationNotFound(name)
suspend fun pipelinesByApplication(application: String): List<Pipeline> =
pipelinesByApplication.get(application).await()
}
| 0 | null | 0 | 0 | 38a628e8516032b1d21a3458fce1f43bd1791943 | 3,015 | keel | Apache License 2.0 |
app/src/main/kotlin/com/hpedrorodrigues/gzmd/activity/view/SettingsView.kt | hpedrorodrigues | 61,674,206 | false | null | /*
* Copyright 2016 Pedro Rodrigues
*
* 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.hpedrorodrigues.gzmd.activity.view
import android.widget.LinearLayout
import android.widget.RelativeLayout
import android.widget.Switch
import org.adw.library.widgets.discreteseekbar.DiscreteSeekBar
interface SettingsView : BaseView {
fun closeApp(): RelativeLayout
fun enableAutoScroll(): RelativeLayout
fun keepScreenOn(): RelativeLayout
fun toggleCloseTheApp(): Switch
fun toggleEnableAutoScroll(): Switch
fun toggleKeepScreenOn(): Switch
// fun aboutTheApp(): LinearLayout
fun rateTheApp(): LinearLayout
fun shareTheApp(): LinearLayout
fun reportABug(): LinearLayout
fun ideaToImprove(): LinearLayout
fun sendUsYourFeedback(): LinearLayout
fun contactUs(): LinearLayout
fun openSourceLicenses(): LinearLayout
fun scrollSpeed(): DiscreteSeekBar
fun textSize(): DiscreteSeekBar
fun startAboutActivity()
} | 0 | Kotlin | 0 | 0 | 65d19653d3f8fc59f939850bf62ebe0f8ca0e5fb | 1,505 | GZMD | Apache License 2.0 |
app/src/main/java/com/goldze/mvvmhabit/aioui/test/TestListModel.kt | fengao1004 | 505,038,355 | false | {"Java Properties": 2, "Gradle": 6, "Shell": 1, "Markdown": 2, "Git Attributes": 1, "Batchfile": 1, "Text": 4, "Ignore List": 4, "Proguard": 3, "Java": 214, "XML": 141, "Kotlin": 158} | package com.goldze.mvvmhabit.aioui.test
import me.goldze.mvvmhabit.binding.command.BindingAction
import me.goldze.mvvmhabit.binding.command.BindingCommand
/**
* Created by Android Studio.
* User: fengao
* Date: 2022/6/21
* Time: 12:57 上午
*/
class TestListModel(var entity: TestBean) {
var itemClick = BindingCommand<String>(BindingAction {
})
} | 1 | null | 1 | 1 | 1099bd7bfcf8a81d545567ae875b3528aa5fb1cd | 362 | AIO | Apache License 2.0 |
domene/main/no/nav/aap/domene/vilkår/Løsning.kt | navikt | 447,233,076 | false | null | package no.nav.aap.domene.vilkår
import no.nav.aap.domene.visitor.VilkårsvurderingVisitor
import no.nav.aap.modellapi.LøsningModellApi
internal interface Løsning<LØSNING, KVALITETSSIKRING>
where LØSNING : Løsning<LØSNING, KVALITETSSIKRING>,
KVALITETSSIKRING : Kvalitetssikring<LØSNING, KVALITETSSIKRING> {
fun matchMedKvalitetssikring(
totrinnskontroll: Totrinnskontroll<LØSNING, KVALITETSSIKRING>,
kvalitetssikring: KVALITETSSIKRING
)
fun accept(visitor: VilkårsvurderingVisitor) {}
fun toDto(): LøsningModellApi
}
| 1 | Kotlin | 0 | 3 | 1101f3b809a29a75ade51286a3de1cd716d4ce5a | 574 | aap-vedtak | MIT License |
haze-materials/src/commonMain/kotlin/dev/chrisbanes/haze/materials/CupertinoMaterials.kt | chrisbanes | 710,434,447 | false | {"Kotlin": 116723, "Shell": 1077} | // Copyright 2024, <NAME> and the Haze project contributors
// SPDX-License-Identifier: Apache-2.0
package dev.chrisbanes.haze.materials
import androidx.compose.material3.MaterialTheme
import androidx.compose.runtime.Composable
import androidx.compose.runtime.ReadOnlyComposable
import androidx.compose.ui.graphics.BlendMode
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.luminance
import androidx.compose.ui.unit.dp
import dev.chrisbanes.haze.HazeStyle
import dev.chrisbanes.haze.HazeTint
/**
* A class which contains functions to build [HazeStyle]s which implement 'material' styles similar
* to those available on Apple platforms. The values used are taken from the
* [iOS 18 Figma](https://www.figma.com/community/file/1385659531316001292) file published by
* Apple.
*
* The primary use case for using these is for when aiming for consistency with native UI
* (i.e. for when mixing Compose Multiplatform content alongside SwiftUI content).
*/
object CupertinoMaterials {
/**
* A [HazeStyle] which implements a mostly translucent material.
*/
@ExperimentalHazeMaterialsApi
@Composable
@ReadOnlyComposable
fun ultraThin(
containerColor: Color = MaterialTheme.colorScheme.surface,
): HazeStyle = hazeMaterial(
containerColor = containerColor,
lightBackgroundColor = Color(0xFF0D0D0D),
lightForegroundColor = Color(color = 0xBFBFBF, alpha = 0.44f),
darkBackgroundColor = Color(0xFF9C9C9C),
darkForegroundColor = Color(color = 0x252525, alpha = 0.55f),
)
/**
* A [HazeStyle] which implements a translucent material. More opaque than [ultraThin],
* more translucent than [regular].
*/
@ExperimentalHazeMaterialsApi
@Composable
@ReadOnlyComposable
fun thin(
containerColor: Color = MaterialTheme.colorScheme.surface,
): HazeStyle = hazeMaterial(
containerColor = containerColor,
lightBackgroundColor = Color(0xFF333333),
lightForegroundColor = Color(color = 0xA6A6A6, alpha = 0.7f),
darkBackgroundColor = Color(0xFF9C9C9C),
darkForegroundColor = Color(color = 0x252525, alpha = 0.7f),
)
/**
* A [HazeStyle] which implements a somewhat opaque material. More opaque than [thin],
* more translucent than [thick].
*/
@ExperimentalHazeMaterialsApi
@Composable
@ReadOnlyComposable
fun regular(
containerColor: Color = MaterialTheme.colorScheme.surface,
): HazeStyle = hazeMaterial(
containerColor = containerColor,
lightBackgroundColor = Color(0xFF383838),
lightForegroundColor = Color(color = 0xB3B3B3, alpha = 0.82f),
darkBackgroundColor = Color(0xFF8C8C8C),
darkForegroundColor = Color(color = 0x252525, alpha = 0.82f),
)
/**
* A [HazeStyle] which implements a mostly opaque material. More opaque than [regular].
*/
@ExperimentalHazeMaterialsApi
@Composable
@ReadOnlyComposable
fun thick(
containerColor: Color = MaterialTheme.colorScheme.surface,
): HazeStyle = hazeMaterial(
containerColor = containerColor,
lightBackgroundColor = Color(0xFF5C5C5C),
lightForegroundColor = Color(color = 0x999999, alpha = 0.97f),
darkBackgroundColor = Color(0xFF7C7C7C),
darkForegroundColor = Color(color = 0x252525, alpha = 0.9f),
)
@ReadOnlyComposable
@Composable
private fun hazeMaterial(
containerColor: Color = MaterialTheme.colorScheme.surface,
isDark: Boolean = containerColor.luminance() < 0.5f,
lightBackgroundColor: Color,
lightForegroundColor: Color,
darkBackgroundColor: Color,
darkForegroundColor: Color,
): HazeStyle = HazeStyle(
blurRadius = 24.dp,
backgroundColor = MaterialTheme.colorScheme.surface,
tints = listOf(
HazeTint(
color = if (isDark) darkBackgroundColor else lightBackgroundColor,
blendMode = if (isDark) BlendMode.Overlay else BlendMode.ColorDodge,
),
HazeTint(color = if (isDark) darkForegroundColor else lightForegroundColor),
),
)
}
private fun Color(color: Int, alpha: Float): Color {
return Color(color).copy(alpha = alpha)
}
| 5 | Kotlin | 30 | 1,118 | f1b7c55f391db027951553d17c2a606cd57692cf | 4,056 | haze | Apache License 2.0 |
auth_framework/src/main/java/com/vmenon/mpo/auth/framework/di/dagger/AuthComponentProvider.kt | hitoshura25 | 91,402,384 | false | {"Kotlin": 574795, "HTML": 14355, "Gherkin": 11761, "Shell": 4889, "Ruby": 4474} | package com.vmenon.mpo.auth.framework.di.dagger
interface AuthComponentProvider {
fun authComponent(): AuthComponent
} | 15 | Kotlin | 0 | 1 | 21dc7f7a03438f26c16c130e6505b0aefdd64c7d | 123 | Media-Player-Omega-Android | Apache License 2.0 |
src/main/kotlin/net/barribob/parkour/config/ConfigManager.kt | miyo6032 | 274,676,220 | false | null | package net.barribob.parkour.config
import com.google.gson.Gson
import com.google.gson.reflect.TypeToken
import com.google.gson.stream.JsonWriter
import net.barribob.maelstrom.MaelstromMod
import net.barribob.maelstrom.util.Version
import java.io.File
import java.io.FileReader
import java.io.FileWriter
import java.lang.reflect.Type
import java.nio.file.Files
import java.nio.file.StandardCopyOption
data class Config<T>(val data: T, val configVersion: String)
class ConfigManager {
fun <T> handleConfigLoad(defaultConfig: Config<T>, typeToken: TypeToken<Config<T>>, modid: String): T {
val directory = File("./config/${modid}/")
if (!directory.exists()) {
directory.mkdirs()
}
val configFile = File(directory, "config.json")
val gson = Gson()
val configType: Type? = typeToken.type
if (configFile.exists()) {
try {
val existingConfig: Config<T>? = FileReader(configFile).use { reader -> gson.fromJson(reader, configType) }
if (existingConfig != null) {
try {
if (Version(defaultConfig.configVersion) <= Version(existingConfig.configVersion)) {
return existingConfig.data
} else {
val configBackup = File(directory, "config_${existingConfig.configVersion}.json")
Files.copy(configFile.toPath(), configBackup.toPath(), StandardCopyOption.REPLACE_EXISTING)
MaelstromMod.LOGGER.warn("Config file for $modid is outdated. Created backup of config (${configBackup.toRelativeString(directory)}), and using new default.")
}
} catch (e: IllegalArgumentException) {
MaelstromMod.LOGGER.error("Failed to read config file for $modid! Perhaps the config version has been tampered with?")
return defaultConfig.data
}
}
}
catch (e: Exception) {
MaelstromMod.LOGGER.error("Failed to read config file for $modid!")
MaelstromMod.LOGGER.error(e)
return defaultConfig.data
}
}
JsonWriter(FileWriter(configFile)).use { writer ->
writer.setIndent("\t")
gson.toJson(defaultConfig, configType, writer)
}
return defaultConfig.data
}
} | 1 | Kotlin | 2 | 4 | fad5a884eece48588aaeb1a3f70c8d5cf6ac9a85 | 2,487 | mobs-attempt-parkour | Creative Commons Zero v1.0 Universal |
sdk/src/main/java/io/stipop/adapter/viewholder/CurationCardContainerViewHolder.kt | stipop-development | 372,351,610 | false | null | package io.stipop.viewholder
import android.view.LayoutInflater
import android.view.MotionEvent
import android.view.ViewGroup
import androidx.core.view.isVisible
import androidx.recyclerview.widget.RecyclerView
import io.stipop.Config
import io.stipop.R
import io.stipop.StipopUtils
import io.stipop.adapter.PackageHorizontalAdapter
import io.stipop.custom.HorizontalDecoration
import io.stipop.databinding.ItemHorizontalStickerThumbContainerBinding
import io.stipop.models.CuratedCard
import io.stipop.setStipopUnderlineColor
import io.stipop.viewholder.delegates.StickerPackageClickDelegate
internal class CurationCardContainerViewHolder(
private val binding: ItemHorizontalStickerThumbContainerBinding,
val delegate: StickerPackageClickDelegate?
) :
RecyclerView.ViewHolder(binding.root) {
private val horizontalAdapter: PackageHorizontalAdapter by lazy { PackageHorizontalAdapter(delegate = delegate) }
private val decoration = HorizontalDecoration(StipopUtils.dpToPx(12F).toInt(), 0, StipopUtils.dpToPx(10F).toInt())
init {
with(binding) {
underLine.setStipopUnderlineColor()
titleTextView.setTextColor(Config.getTitleTextColor(itemView.context))
recyclerView.apply {
removeItemDecoration(decoration)
addItemDecoration(decoration)
addOnItemTouchListener(listener)
}
}
}
fun bind(curatedCard: CuratedCard?) {
horizontalAdapter.curatedCard = curatedCard
binding.container.isVisible = curatedCard != null
curatedCard?.let { card ->
binding.titleTextView.text = card.cardTitle
binding.recyclerView.adapter = horizontalAdapter
horizontalAdapter.run {
clearData()
updateData(card.packageList)
}
}
}
companion object {
fun create(
parent: ViewGroup,
delegate: StickerPackageClickDelegate?
): CurationCardContainerViewHolder {
val view = LayoutInflater.from(parent.context).inflate(R.layout.item_horizontal_sticker_thumb_container, parent, false)
val binding = ItemHorizontalStickerThumbContainerBinding.bind(view)
return CurationCardContainerViewHolder(binding, delegate)
}
val listener = object : RecyclerView.OnItemTouchListener {
override fun onInterceptTouchEvent(rv: RecyclerView, e: MotionEvent): Boolean {
rv.parent.requestDisallowInterceptTouchEvent(true)
return false
}
override fun onTouchEvent(rv: RecyclerView, e: MotionEvent) {
//
}
override fun onRequestDisallowInterceptTouchEvent(disallowIntercept: Boolean) {
//
}
}
}
}
| 2 | null | 5 | 9 | 98ab3c8ebc153270d3265c9a08c884deb2126d9f | 2,848 | stipop-android-sdk | MIT License |
defitrack-rest/defitrack-protocol-service/src/main/java/io/defitrack/market/adapter/in/resource/LendingMarketVO.kt | decentri-fi | 426,174,152 | false | {"Kotlin": 1268960, "Java": 1948, "Dockerfile": 909} | package io.defitrack.market.adapter.`in`.resource
import io.defitrack.erc20.domain.FungibleTokenInformation
import io.defitrack.networkinfo.NetworkInformation
import io.defitrack.protocol.ProtocolVO
import java.math.BigDecimal
class LendingMarketVO(
id: String,
name: String,
protocol: ProtocolVO,
network: NetworkInformation,
val token: FungibleTokenInformation,
val marketToken: FungibleTokenInformation?,
val rate: Double?,
val poolType: String,
marketSize: BigDecimal?,
prepareInvestmentSupported: Boolean,
exitPositionSupported: Boolean,
val erc20Compatible: Boolean,
val price: BigDecimal,
val totalSupply: BigDecimal,
updatedAt: Long,
deprecated: Boolean
) : MarketVO(
id,
network,
protocol,
name,
prepareInvestmentSupported,
exitPositionSupported,
marketSize,
"lending",
updatedAt,
deprecated
) | 59 | Kotlin | 6 | 10 | 991cf38ff445d408bed3a63c88a009e23272e513 | 908 | defi-hub | MIT License |
app/src/main/java/com/baseproject/data/remote/NetworkBoundResource.kt | shubham-soni9 | 362,546,242 | false | null | package com.baseproject.data.remote
import android.content.Context
import androidx.annotation.MainThread
import androidx.annotation.WorkerThread
import androidx.lifecycle.LiveData
import androidx.lifecycle.MediatorLiveData
import com.baseproject.R
import com.baseproject.data.remote.model.Resource
import com.google.gson.stream.MalformedJsonException
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import retrofit2.Call
import retrofit2.Callback
import retrofit2.HttpException
import retrofit2.Response
import java.io.IOException
import java.net.SocketTimeoutException
/**
* Handling network and local database calls
*/
abstract class NetworkBoundResource<T, V> @MainThread protected constructor(private var baseContext: Context) {
private val result = MediatorLiveData<Resource<T>>()
init {
result.setValue(Resource.loading(null))
// Always load the data from DB initially so that we have
CoroutineScope(Dispatchers.IO).launch {
val dbSource = loadFromDb()
withContext(Dispatchers.Main) {
// Fetch the data from network and add it to the resource
result.addSource(dbSource) {
result.removeSource(dbSource)
if (shouldFetch()) {
fetchFromNetwork(dbSource)
} else {
result.addSource(dbSource) { newData: T ->
if (null != newData) result.value = Resource.success(newData)
}
}
}
}
}
}
/**
* This method fetches the data from remoted service and save it to local db
* @param dbSource - Database source
*/
private fun fetchFromNetwork(dbSource: LiveData<T>) {
result.addSource(dbSource) { newData: T ->
result.setValue(Resource.loading(newData))
}
createCall().enqueue(object : Callback<V> {
override fun onResponse(call: Call<V>, response: Response<V>) {
result.removeSource(dbSource)
saveResultAndReInit(response.body())
}
override fun onFailure(call: Call<V>, t: Throwable) {
result.removeSource(dbSource)
result.addSource(dbSource) { newData: T ->
result.setValue(Resource.error(getCustomErrorMessage(t), newData))
}
}
})
}
private fun getCustomErrorMessage(error: Throwable): String {
return if (error is SocketTimeoutException) {
baseContext.getString(R.string.requestTimeOutError)
} else if (error is MalformedJsonException) {
baseContext.getString(R.string.responseMalformedJson)
} else if (error is IOException) {
baseContext.getString(R.string.networkError)
} else if (error is HttpException) {
error.response().message()
} else {
baseContext.getString(R.string.unknownError)
}
}
@MainThread
private fun saveResultAndReInit(response: V?) {
CoroutineScope(Dispatchers.IO).launch {
if (response != null) {
saveCallResult(response)
}
withContext(Dispatchers.Main) {
result.addSource(loadFromDb()) { newData: T ->
if (null != newData) result.value = Resource.success(newData)
}
}
}
}
@WorkerThread
protected abstract suspend fun saveCallResult(item: V)
@MainThread
private fun shouldFetch(): Boolean {
return true
}
@MainThread
protected abstract suspend fun loadFromDb(): LiveData<T>
@MainThread
protected abstract fun createCall(): Call<V>
val asLiveData: LiveData<Resource<T>>
get() = result
} | 0 | Kotlin | 0 | 0 | f3f888d4c3797c88289c4b0c5554d2f9ebfb253b | 3,956 | MVVM-BaseProject | MIT License |
dusseldorf-oauth2-client/src/test/kotlin/no/nav/helse/dusseldorf/oauth2/client/SignedJwtAccessTokenClientTest.kt | navikt | 177,815,271 | false | {"Kotlin": 263645, "Shell": 4117} | package no.nav.helse.dusseldorf.oauth2.client
import com.nimbusds.jwt.SignedJWT
import no.nav.helse.dusseldorf.testsupport.jws.LoginService
import no.nav.helse.dusseldorf.testsupport.jws.Tokendings
import no.nav.helse.dusseldorf.testsupport.wiremock.WireMockBuilder
import no.nav.helse.dusseldorf.testsupport.wiremock.getAzureV2TokenUrl
import no.nav.helse.dusseldorf.testsupport.wiremock.getTokendingsTokenUrl
import java.net.URI
import kotlin.test.Ignore
import kotlin.test.Test
import kotlin.test.assertEquals
import kotlin.test.assertNotNull
class SignedJwtAccessTokenClientTest {
@Test
@Ignore
fun `Manuelt teste mot Azure Preprod`() {
val clientId = "set-me"
val certificateThumbprint = "set-me"
val privateKeyJwk = """
set-me
""".trimIndent()
val scopes = setOf<String>()
val client = SignedJwtAccessTokenClient(
clientId = clientId,
keyIdProvider = FromCertificateHexThumbprint(certificateThumbprint),
tokenEndpoint = TestData.AZURE_PREPROD_TOKEN_URL,
privateKeyProvider = FromJwk(privateKeyJwk)
)
val accessToken = client.getAccessToken(scopes)
val jwt = SignedJWT.parse(accessToken.accessToken)
println(jwt.parsedString)
println(jwt.header.toJSONObject())
println(jwt.jwtClaimsSet.toJSONObject())
}
@Test
fun `Hente access token`() {
val mock = Oauth2ServerWireMock()
val tokenUrl = mock.getTokenUrl()
val clientId = "test-client-id"
mock.stubGetTokenSignedJwtClientCredentials()
val client = SignedJwtAccessTokenClient(
clientId = clientId,
keyIdProvider = FromCertificateHexThumbprint(TestData.CERTIFICATE_THUMBPRINT_SHA1_HEX),
tokenEndpoint = tokenUrl,
privateKeyProvider = FromJwk(TestData.PRIVATE_KEY_JWK)
)
val resp = client.getAccessToken(
scopes = setOf("en-annen-client/.default")
)
assertNotNull(resp)
mock.stop()
}
@Test
fun `Hente Azure access token med test support`() {
val wireMock = WireMockBuilder()
.withAzureSupport()
.build()
val client = SignedJwtAccessTokenClient(
clientId = "foo",
keyIdProvider = FromCertificateHexThumbprint(TestData.CERTIFICATE_THUMBPRINT_SHA1_HEX),
tokenEndpoint = URI(wireMock.getAzureV2TokenUrl()),
privateKeyProvider = FromJwk(TestData.PRIVATE_KEY_JWK)
)
val response = client.getAccessToken(setOf("fooscope/.default"))
assertNotNull(response)
wireMock.stop()
}
@Test
fun `Hente Tokendings access token med test support`() {
val wireMock = WireMockBuilder()
.withTokendingsSupport()
.build()
val client = SignedJwtAccessTokenClient(
clientId = "min-test-app-a",
keyIdProvider = FromCertificateHexThumbprint(TestData.CERTIFICATE_THUMBPRINT_SHA1_HEX),
tokenEndpoint = URI(wireMock.getTokendingsTokenUrl()),
privateKeyProvider = FromJwk(TestData.PRIVATE_KEY_JWK)
)
val onBehalfOf = LoginService.V1_0.generateJwt(
fnr = "12345566"
)
val response = client.getAccessToken(setOf("min-test-app-b"), onBehalfOf)
val claims = SignedJWT.parse(response.accessToken).jwtClaimsSet
assertEquals("12345566", claims.subject)
assertEquals(Tokendings.getIssuer(), claims.issuer)
assertEquals("min-test-app-a", claims.getStringClaim("client_id"))
assertEquals("min-test-app-b", claims.audience.firstOrNull())
wireMock.stop()
}
} | 4 | Kotlin | 2 | 3 | beb7cfd21f89eb13fdc9b295237ae63c576c990e | 3,795 | dusseldorf-ktor | MIT License |
org.librarysimplified.audiobook.views/src/main/java/org/librarysimplified/audiobook/views/toc/PlayerTOCMainFragment.kt | ThePalaceProject | 379,956,255 | false | {"Kotlin": 718883, "Java": 2554} | package org.librarysimplified.audiobook.views.toc
interface PlayerTOCMainFragment {
fun menusConfigureVisibility()
}
| 1 | Kotlin | 1 | 1 | d8e2d9dde4c20391075fcc6c527c9b9845b92a8e | 120 | android-audiobook | Apache License 2.0 |
org.librarysimplified.audiobook.views/src/main/java/org/librarysimplified/audiobook/views/toc/PlayerTOCMainFragment.kt | ThePalaceProject | 379,956,255 | false | {"Kotlin": 718883, "Java": 2554} | package org.librarysimplified.audiobook.views.toc
interface PlayerTOCMainFragment {
fun menusConfigureVisibility()
}
| 1 | Kotlin | 1 | 1 | d8e2d9dde4c20391075fcc6c527c9b9845b92a8e | 120 | android-audiobook | Apache License 2.0 |
HealthStyle/Project1/app/src/main/java/com/cs4530spring2022/project1/util/HikesAdapter.kt | jingwenvv | 549,972,474 | false | {"Kotlin": 117443} | package com.cs4530spring2022.project1.util
import android.content.Intent
import android.net.Uri
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.TextView
import androidx.recyclerview.widget.RecyclerView
import com.cs4530spring2022.project1.R
class HikesAdapter(private var hikesData: List<ItemsHikesRow> = listOf()) : RecyclerView.Adapter<HikesAdapter.ViewHolder>() {
inner class ViewHolder(v: View) : RecyclerView.ViewHolder(v){
var name: TextView = v.findViewById(R.id.tv_hike)
var address: TextView = v.findViewById(R.id.tv_address)
val pic: ImageView = v.findViewById(R.id.iv_pic)
}
override fun getItemCount() = hikesData.size
override fun onCreateViewHolder(vg: ViewGroup, type: Int): ViewHolder {
return ViewHolder(LayoutInflater.from(vg.context).inflate(R.layout.hike_row, vg,false))
}
override fun onBindViewHolder(vh: ViewHolder, idx: Int) {
vh.name.text = hikesData[idx].name
vh.pic.setImageResource(hikesData[idx].image)
vh.address.text = hikesData[idx].address
vh.itemView.setOnClickListener {
// onClick behavior! Use this information!
val lat = hikesData[idx].latitude
val lon = hikesData[idx].longitude
// Create a Uri from an intent string. Use the result to create an Intent.
val gmmIntentUri =
Uri.parse("geo:" + lat.toString() + "," + lon.toString() + "?q=" + vh.name.text)
// Create an Intent from gmmIntentUri. Set the action to ACTION_VIEW
val mapIntent = Intent(Intent.ACTION_VIEW, gmmIntentUri)
// Make the Intent explicit by setting the Google Maps package
mapIntent.setPackage("com.google.android.apps.maps")
// Attempt to start an activity that can handle the Intent
vh.pic.getContext().startActivity(mapIntent)
}
}
fun setHikesData(data: List<ItemsHikesRow>) {
hikesData = data
notifyDataSetChanged()
}
// TODO : onHikeClicked()
}
| 0 | Kotlin | 0 | 0 | 6f02dba034b32ca793242b589fc233895d9bfeb2 | 2,141 | AndroidApp | MIT License |
komapper-core/src/main/kotlin/org/komapper/core/dsl/expression/SqlBuilderScope.kt | komapper | 349,909,214 | false | {"Kotlin": 2922039, "Java": 57131} | package org.komapper.core.dsl.expression
import org.komapper.core.Dialect
import org.komapper.core.StatementBuffer
/**
* The scope for SQL building.
*/
interface SqlBuilderScope {
val dialect: Dialect
/**
* Appends an SQL fragment.
*/
fun append(text: CharSequence)
/**
* Deletes characters from the SQL string.
*
* @param length character length
*/
fun cutBack(length: Int)
/**
* Processes an operand.
*/
fun visit(operand: Operand)
}
internal class SqlBuilderScopeImpl(
override val dialect: Dialect,
private val buf: StatementBuffer,
private val visitOperand: (Operand) -> Unit,
) : SqlBuilderScope {
override fun append(text: CharSequence) {
buf.append(text)
}
override fun cutBack(length: Int) {
buf.cutBack(length)
}
override fun visit(operand: Operand) {
visitOperand(operand)
}
override fun toString(): String {
return buf.toString()
}
}
| 8 | Kotlin | 14 | 301 | 9fbc0b5652ee732583e977180cdc493e116e1022 | 1,002 | komapper | Apache License 2.0 |
Ant/app/src/main/java/com/example/ant/page/designers/DesignersListVM.kt | BagerYF | 756,641,101 | false | {"Kotlin": 452753} | package com.example.ant.page.designers
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.lifecycle.SavedStateHandle
import androidx.lifecycle.ViewModel
import com.example.ant.common.tools.AppTools
import com.example.ant.model.designer.DesignerModel
import com.example.ant.model.designer.kDesignersAllMaps
import dagger.hilt.android.lifecycle.HiltViewModel
import javax.inject.Inject
@HiltViewModel
class DesignersListVM @Inject constructor(savedStateHandle: SavedStateHandle): ViewModel() {
var allList: MutableList<DesignerModel> = mutableListOf()
var showData: MutableMap<String, MutableList<DesignerModel>> = mutableMapOf()
var group: MutableList<String> = mutableListOf()
var searchText: String = ""
init {
val localData = kDesignersAllMaps.keys.toTypedArray().toList()
for (item in localData) {
val firstCharacter = item.first().uppercaseChar()
val isCharacter = AppTools().containsOnlyLetters(firstCharacter)
val tempModel = DesignerModel(name = item, firstCharacter = "$firstCharacter", isCharacter = isCharacter)
allList.add(tempModel)
}
searchData()
}
fun searchData() {
showData = mutableMapOf()
for (designer in allList) {
if (showData.keys.contains(designer.firstCharacter)) {
var tempList: MutableList<DesignerModel> = showData[designer.firstCharacter]!!
if (searchText.isNotEmpty()) {
if (designer.name.lowercase().contains(searchText.lowercase())) {
tempList.add(designer)
}
} else {
tempList.add(designer)
}
showData[designer.firstCharacter] = tempList
} else {
if (designer.isCharacter) {
var tempList:MutableList<DesignerModel> = mutableListOf()
if (searchText.isNotEmpty()) {
if (designer.name.lowercase().contains(searchText.lowercase())) {
tempList.add(designer)
showData[designer.firstCharacter] = tempList
}
} else {
tempList.add(designer)
showData[designer.firstCharacter] = tempList
}
} else {
if (showData.keys.contains("#")) {
var tempList: MutableList<DesignerModel> = showData["#"]!!
if (searchText.isNotEmpty()) {
if (designer.name.lowercase().contains(searchText.lowercase())) {
tempList.add(designer)
}
} else {
tempList.add(designer)
}
showData["#"] = tempList
} else {
var tempList: MutableList<DesignerModel> = mutableListOf();
if (searchText.isNotEmpty()) {
if (designer.name.lowercase().contains(searchText.lowercase())) {
tempList.add(designer)
showData["#"] = tempList
}
} else {
tempList.add(designer)
showData["#"] = tempList
}
}
}
}
}
group = mutableListOf()
for (key in showData.keys) {
group.add(key)
group.sort()
}
}
} | 0 | Kotlin | 0 | 0 | bdc7f1c061f8bcdf7dd5d3522da4bbae43758932 | 3,839 | Ant | MIT License |
app/src/main/java/tw/ktrssreader/MainActivity.kt | ganeshvl | 324,172,116 | true | {"Kotlin": 165938} | package tw.ktrssreader
import android.os.Bundle
import android.view.Menu
import android.view.MenuItem
import android.view.View
import android.widget.ArrayAdapter
import androidx.appcompat.app.AppCompatActivity
import androidx.lifecycle.lifecycleScope
import kotlinx.android.synthetic.main.activity_main.*
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.flow.*
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import tw.ktrssreader.generated.RssDataReader
import tw.ktrssreader.generated.RssOrderDataReader
import tw.ktrssreader.generated.RssRawDataReader
import tw.ktrssreader.model.channel.AutoMixChannelData
import tw.ktrssreader.model.channel.GoogleChannelData
import tw.ktrssreader.model.channel.ITunesChannelData
import tw.ktrssreader.model.channel.RssStandardChannelData
import java.nio.charset.Charset
import kotlin.concurrent.thread
class MainActivity : AppCompatActivity() {
companion object {
private const val DEFAULT_RSS_URL = "https://feeds.fireside.fm/wzd/rss"
private const val DEFAULT_CHARSET = "UTF-8"
private val RSS_URL_LIST = listOf(
"https://feeds.fireside.fm/wzd/rss",
"https://feeds.soundcloud.com/users/soundcloud:users:221361980/sounds.rss",
"https://feeds.soundcloud.com/users/soundcloud:users:322164009/sounds.rss",
"https://www.mirrormedia.mg/rss/category_readforyou.xml?utm_source=feed_related&utm_medium=itunes",
"https://feeds.fireside.fm/lushu/rss",
"https://sw7x7.libsyn.com/rss",
"https://feeds.fireside.fm/starrocket/rss",
"https://rss.art19.com/real-estate-rookie",
"https://rss.art19.com/so-you-want-to-work-abroad",
"https://feeds.megaphone.fm/mad-money",
"https://www.rnz.co.nz/acast/flying-solo.rss",
"https://rss.whooshkaa.com/rss/podcast/id/6175",
"https://rss.acast.com/how-i-work",
"https://journeytolaunch.libsyn.com/rss",
"https://anchor.fm/s/12680fe4/podcast/rss",
"https://blazingtrails.libsyn.com/rss",
"https://anchor.fm/s/12746230/podcast/rss",
"https://rss.art19.com/wecrashed",
"https://consciouscreators.libsyn.com/rss",
)
}
enum class RssType {
Standard,
ITunes,
GooglePlay,
AutoMix,
Custom,
CustomWithRawData,
CustomWithOrder,
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
spinner.adapter =
ArrayAdapter(this, android.R.layout.simple_spinner_dropdown_item, RssType.values())
etRss.setText(DEFAULT_RSS_URL)
etCharset.setText(DEFAULT_CHARSET)
btnRead.setOnClickListener { read() }
btnCoroutine.setOnClickListener { coRead() }
btnFlow.setOnClickListener { flowRead() }
}
override fun onCreateOptionsMenu(menu: Menu): Boolean {
RSS_URL_LIST.forEach { url -> menu.add(Menu.NONE, View.generateViewId(), Menu.NONE, url) }
return true
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
etRss.setText(item.title)
return true
}
private fun read() {
progressBar.visibility = View.VISIBLE
textView.text = null
thread {
try {
val channel = when (spinner.selectedItem) {
RssType.Standard -> {
Reader.read<RssStandardChannelData>(etRss.text.toString()) {
useCache = rbCacheYes.isChecked
charset = Charset.forName(etCharset.text.toString())
}
}
RssType.ITunes -> {
Reader.read<ITunesChannelData>(etRss.text.toString()) {
useCache = rbCacheYes.isChecked
charset = Charset.forName(etCharset.text.toString())
}
}
RssType.GooglePlay -> {
Reader.read<GoogleChannelData>(etRss.text.toString()) {
useCache = rbCacheYes.isChecked
charset = Charset.forName(etCharset.text.toString())
}
}
RssType.AutoMix -> {
Reader.read<AutoMixChannelData>(etRss.text.toString()) {
useCache = rbCacheYes.isChecked
charset = Charset.forName(etCharset.text.toString())
}
}
RssType.Custom -> {
RssDataReader.read(etRss.text.toString()) {
useCache = rbCacheYes.isChecked
charset = Charset.forName(etCharset.text.toString())
}
}
RssType.CustomWithRawData -> {
RssRawDataReader.read(etRss.text.toString()) {
useCache = rbCacheYes.isChecked
charset = Charset.forName(etCharset.text.toString())
}
}
RssType.CustomWithOrder -> {
RssOrderDataReader.read(etRss.text.toString()) {
useCache = rbCacheYes.isChecked
charset = Charset.forName(etCharset.text.toString())
}
}
else -> error("Invalid item was checked!")
}
runOnUiThread {
textView.text = channel.toString()
progressBar.visibility = View.INVISIBLE
}
} catch (e: Exception) {
e.printStackTrace()
runOnUiThread {
textView.text = e.toString()
progressBar.visibility = View.INVISIBLE
}
}
}
}
private fun coRead() {
lifecycleScope.launch {
textView.text = null
progressBar.visibility = View.VISIBLE
try {
val channel = withContext(Dispatchers.IO) {
when (spinner.selectedItem) {
RssType.Standard -> {
Reader.coRead<RssStandardChannelData>(etRss.text.toString()) {
useCache = rbCacheYes.isChecked
charset = Charset.forName(etCharset.text.toString())
}
}
RssType.ITunes -> {
Reader.coRead<ITunesChannelData>(etRss.text.toString()) {
useCache = rbCacheYes.isChecked
charset = Charset.forName(etCharset.text.toString())
}
}
RssType.GooglePlay -> {
Reader.coRead<GoogleChannelData>(etRss.text.toString()) {
useCache = rbCacheYes.isChecked
charset = Charset.forName(etCharset.text.toString())
}
}
RssType.AutoMix -> {
Reader.coRead<AutoMixChannelData>(etRss.text.toString()) {
useCache = rbCacheYes.isChecked
charset = Charset.forName(etCharset.text.toString())
}
}
RssType.Custom -> {
RssDataReader.coRead(etRss.text.toString()) {
useCache = rbCacheYes.isChecked
charset = Charset.forName(etCharset.text.toString())
}
}
RssType.CustomWithRawData -> {
RssRawDataReader.coRead(etRss.text.toString()) {
useCache = rbCacheYes.isChecked
charset = Charset.forName(etCharset.text.toString())
}
}
RssType.CustomWithOrder -> {
RssOrderDataReader.coRead(etRss.text.toString()) {
useCache = rbCacheYes.isChecked
charset = Charset.forName(etCharset.text.toString())
}
}
else -> error("Invalid item was checked!")
}
}
textView.text = channel.toString()
progressBar.visibility = View.INVISIBLE
} catch (e: Exception) {
e.printStackTrace()
textView.text = e.toString()
progressBar.visibility = View.INVISIBLE
}
}
}
private fun flowRead() {
lifecycleScope.launch {
val flowChannel = when (spinner.selectedItem) {
RssType.Standard -> {
Reader.flowRead<RssStandardChannelData>(etRss.text.toString()) {
useCache = rbCacheYes.isChecked
charset = Charset.forName(etCharset.text.toString())
}
}
RssType.ITunes -> {
Reader.flowRead<ITunesChannelData>(etRss.text.toString()) {
useCache = rbCacheYes.isChecked
charset = Charset.forName(etCharset.text.toString())
}
}
RssType.GooglePlay -> {
Reader.flowRead<GoogleChannelData>(etRss.text.toString()) {
useCache = rbCacheYes.isChecked
charset = Charset.forName(etCharset.text.toString())
}
}
RssType.AutoMix -> {
Reader.flowRead<AutoMixChannelData>(etRss.text.toString()) {
useCache = rbCacheYes.isChecked
charset = Charset.forName(etCharset.text.toString())
}
}
RssType.Custom -> {
RssDataReader.flowRead(etRss.text.toString()) {
useCache = rbCacheYes.isChecked
charset = Charset.forName(etCharset.text.toString())
}
}
RssType.CustomWithRawData -> {
RssRawDataReader.flowRead(etRss.text.toString()) {
useCache = rbCacheYes.isChecked
charset = Charset.forName(etCharset.text.toString())
}
}
RssType.CustomWithOrder -> {
RssOrderDataReader.flowRead(etRss.text.toString()) {
useCache = rbCacheYes.isChecked
charset = Charset.forName(etCharset.text.toString())
}
}
else -> error("Invalid item was checked!")
}
flowChannel.flowOn(Dispatchers.IO)
.onStart {
textView.text = null
progressBar.visibility = View.VISIBLE
}.onEach {
progressBar.visibility = View.INVISIBLE
}.catch { e ->
e.printStackTrace()
textView.text = e.toString()
progressBar.visibility = View.INVISIBLE
}.collect { channel ->
textView.text = channel.toString()
}
}
}
} | 0 | null | 0 | 0 | 3ba654fcfec45e97834db40e27ca8fff277f74bd | 11,990 | KtRssReader | Apache License 2.0 |
remote/src/main/kotlin/io/github/gmvalentino8/github/sample/remote/models/ProtectedMinusBranchMinusRequiredMinusStatusMinusCheckApiModel.kt | wasabi-muffin | 462,369,263 | false | {"Kotlin": 2712155, "Mustache": 4796, "Ruby": 1144, "Shell": 812} | /**
* GitHub v3 REST API
*
* GitHub's v3 REST API.
*
* The version of the OpenAPI document: 1.1.4
*
*
* Please note:
* This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
* Do not edit this file manually.
*/
@file:Suppress(
"ArrayInDataClass",
"EnumEntryName",
"RemoveRedundantQualifierName",
"UnusedImport"
)
package io.github.gmvalentino8.github.sample.remote.models
import io.github.gmvalentino8.github.sample.remote.models.ProtectedBranchRequiredStatusCheckChecksApiModel
import kotlinx.serialization.*
/**
* Protected Branch Required Status Check
* @param contexts
* @param checks
* @param url
* @param enforcementLevel
* @param contextsUrl
* @param strict
*/
@Serializable
data class ProtectedMinusBranchMinusRequiredMinusStatusMinusCheckApiModel(
@SerialName(value = "contexts")
val contexts: kotlin.collections.List<kotlin.String>,
@SerialName(value = "checks")
val checks: kotlin.collections.List<ProtectedBranchRequiredStatusCheckChecksApiModel>,
@SerialName(value = "url")
val url: kotlin.String? = null,
@SerialName(value = "enforcement_level")
val enforcementLevel: kotlin.String? = null,
@SerialName(value = "contexts_url")
val contextsUrl: kotlin.String? = null,
@SerialName(value = "strict")
val strict: kotlin.Boolean? = null
) {
}
| 0 | Kotlin | 0 | 1 | 2194a2504bde08427ad461d92586497c7187fb40 | 1,378 | github-sample-project | Apache License 2.0 |
ui/src/test/kotlin/io/rippledown/interpretation/ConclusionsViewProxy.kt | TimLavers | 513,037,911 | false | {"Kotlin": 1225734, "Gherkin": 86510} | package io.rippledown.interpretation
import androidx.compose.ui.test.assertTextEquals
import androidx.compose.ui.test.junit4.ComposeTestRule
import androidx.compose.ui.test.onNodeWithContentDescription
import androidx.compose.ui.test.performClick
fun ComposeTestRule.requireComment(commentIndex: Int, expected: String) {
onNodeWithContentDescription(textContentDescription(1, 0, commentIndex, expected)).assertTextEquals(expected)
}
fun ComposeTestRule.clickComment(commentIndex: Int, expected: String) {
onNodeWithContentDescription(iconContentDescription(1, 0, commentIndex, expected)).performClick()
}
fun ComposeTestRule.requireConditionForComment(commentIndex: Int, conditionIndex: Int, expected: String) {
onNodeWithContentDescription(textContentDescription(2, commentIndex, conditionIndex, expected)).assertTextEquals(
expected
)
}
fun ComposeTestRule.requireConditionNotShowing(commentIndex: Int, conditionIndex: Int, expected: String) {
onNodeWithContentDescription(textContentDescription(2, commentIndex, conditionIndex, expected)).assertDoesNotExist()
}
| 0 | Kotlin | 0 | 0 | 29b8f6c7606a99fc0719f3f87ef72fd7bfad6e46 | 1,099 | OpenRDR | MIT License |
src/commonMain/kotlin/com/wizbii/cinematic/journey/domain/use/case/ObserveMovieUseCase.kt | wizbii | 762,402,623 | false | {"Kotlin": 149036, "Ruby": 465, "Swift": 60} | package com.wizbii.cinematic.journey.domain.use.case
import com.wizbii.cinematic.journey.domain.entity.Movie
import com.wizbii.cinematic.journey.domain.entity.MovieId
import com.wizbii.cinematic.journey.domain.repository.MovieRepository
import com.wizbii.cinematic.journey.domain.repository.TmdbRepository
import kotlinx.coroutines.ExperimentalCoroutinesApi
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.combine
import kotlinx.coroutines.flow.flatMapLatest
import kotlinx.coroutines.flow.flowOf
class ObserveMovieUseCase(
private val movieRepository: MovieRepository,
private val tmdbRepository: TmdbRepository,
) {
operator fun invoke(movieId: MovieId, language: String): Flow<Movie> =
@OptIn(ExperimentalCoroutinesApi::class)
movieRepository
.getMovie(movieId)
.flatMapLatest { localMovie ->
flowOf(localMovie).combine(
flow = tmdbRepository.getLocalTmdbMovie(
id = localMovie.tmdbId,
language = language,
),
transform = ::Movie,
)
}
}
| 5 | Kotlin | 0 | 2 | cf322bcee0fd9ae6fe745d8d57e1ef429fbb9c24 | 1,167 | CinematicJourney | Apache License 2.0 |
core/src/main/kotlin/de/uulm/se/couchedit/processing/spatial/services/geometric/NearestPointCalculator.kt | sp-uulm | 303,650,849 | false | null | package de.uulm.se.couchedit.processing.spatial.services.geometric
import com.google.inject.Inject
import com.google.inject.Singleton
import de.uulm.se.couchedit.model.graphic.shapes.Point
import de.uulm.se.couchedit.model.graphic.shapes.Shape
import org.locationtech.jts.geom.Coordinate
import org.locationtech.jts.operation.distance.DistanceOp
import java.lang.Math.pow
import kotlin.math.sqrt
@Singleton
class NearestPointCalculator @Inject constructor(private val geometryProvider: JTSGeometryProvider) {
fun isDistanceUnder(
s1: Shape,
s2: Shape,
threshold: Double,
s1ElementId: String? = null,
s2ElementId: String? = null
): Boolean {
val envDistance = this.calculateEnvelopeDistanceBetween(s1, s2, s1ElementId, s2ElementId)
if (envDistance > threshold) {
return false
}
val realDistance = calculateDistanceBetween(s1, s2, s1ElementId, s2ElementId)
return realDistance < threshold
}
fun calculateEnvelopeDistanceBetween(
s1: Shape,
s2: Shape,
s1ElementId: String? = null,
s2ElementId: String? = null
): Double {
val (p1, p2) = calculateNearestEnvelopePointsBetween(s1, s2, s1ElementId, s2ElementId)
val dx = p1.x - p2.x
val dy = p1.y - p2.y
return sqrt(pow(dx, 2.0) + pow(dy, 2.0))
}
fun calculateNearestEnvelopePointsBetween(
s1: Shape,
s2: Shape,
s1ElementId: String? = null,
s2ElementId: String? = null
): Pair<Point, Point> {
val envS1 = geometryProvider.toGeometry(s1, s1ElementId).geometry.envelopeInternal
val envS2 = geometryProvider.toGeometry(s2, s2ElementId).geometry.envelopeInternal
val x1: Double
val x2: Double
val y1: Double
val y2: Double
when {
envS1.minX > envS2.maxX -> {
x1 = envS1.minX
x2 = envS2.maxX
}
envS2.minX > envS1.maxX -> {
x1 = envS1.maxX
x2 = envS2.minX
}
else -> {
x1 = envS1.minX
x2 = x1
}
}
when {
envS1.minY > envS2.maxY -> {
y1 = envS1.minY
y2 = envS2.maxY
}
envS2.minY > envS1.maxY -> {
y1 = envS1.maxY
y2 = envS2.minY
}
else -> {
y1 = envS1.minY
y2 = y1
}
}
return Pair(Point(x1, y1), Point(x2, y2))
}
fun calculateNearestPointsBetween(
s1: Shape,
s2: Shape,
s1ElementId: String? = null,
s2ElementId: String? = null
): Pair<Point, Point> {
val g1 = geometryProvider.toGeometry(s1, s1ElementId)
val g2 = geometryProvider.toGeometry(s2, s2ElementId)
val distanceOp = DistanceOp(g1.geometry, g2.geometry)
val coordinates = distanceOp.nearestPoints()
return Pair(coordinateToPoint(coordinates[0]), coordinateToPoint(coordinates[1]))
}
fun calculateDistanceBetween(
s1: Shape,
s2: Shape,
s1ElementId: String? = null,
s2ElementId: String? = null
): Double {
val g1 = geometryProvider.toGeometry(s1, s1ElementId)
val g2 = geometryProvider.toGeometry(s2, s2ElementId)
val distanceOp = DistanceOp(g1.geometry, g2.geometry)
return distanceOp.distance()
}
fun calculateBorderDistanceBetween(
s1: Shape,
s2: Shape,
s1ElementId: String? = null,
s2ElementId: String? = null
) : Double {
val g1 = geometryProvider.toGeometry(s1, s1ElementId)
val g2 = geometryProvider.toGeometry(s2, s2ElementId)
val distanceOp = DistanceOp(
if(s1 is Point) g1.geometry else g1.geometry.boundary,
if(s2 is Point) g2.geometry else g2.geometry.boundary
)
return distanceOp.distance()
}
private fun coordinateToPoint(coordinate: Coordinate): Point {
return Point(coordinate.x, coordinate.y)
}
}
| 0 | Kotlin | 0 | 0 | 595266c0bca8f2ee6ff633c4b45b91e5f3132cc4 | 4,270 | CouchEdit | Apache License 2.0 |
impl/java/server/src/test/kotlin/br/com/guiabolso/events/server/SuspendingEventProcessorTest.kt | GuiaBolso | 102,665,880 | false | {"Kotlin": 303566} | package br.com.guiabolso.events.server
import br.com.guiabolso.events.EventBuilderForTest.buildResponseEvent
import br.com.guiabolso.events.model.RequestEvent
import br.com.guiabolso.events.server.exception.EventParsingException
import br.com.guiabolso.events.server.exception.handler.ExceptionHandlerRegistry
import io.mockk.coEvery
import io.mockk.coVerify
import io.mockk.every
import io.mockk.mockk
import io.mockk.slot
import kotlinx.coroutines.runBlocking
import org.junit.jupiter.api.Assertions.assertEquals
import org.junit.jupiter.api.BeforeEach
import org.junit.jupiter.api.Test
import org.junit.jupiter.api.assertThrows
class SuspendingEventProcessorTest {
private lateinit var exceptionHandler: ExceptionHandlerRegistry
private lateinit var rawEventProcessor: RawEventProcessor
private lateinit var processor: SuspendingEventProcessor
@BeforeEach
fun setup() {
exceptionHandler = mockk()
rawEventProcessor = mockk {
every { exceptionHandlerRegistry } returns exceptionHandler
every { tracer } returns mockk()
}
processor = SuspendingEventProcessor(rawEventProcessor)
}
@Test
fun `should delegate any valid json to raw event processor`(): Unit = runBlocking {
coEvery { rawEventProcessor.processEvent(any()) } returns buildResponseEvent()
val response = processor.processEvent("{}")
assertEquals(
"{\"name\":\"event:name:response\",\"version\":1,\"id\":\"id\",\"flowId\":\"flowId\",\"payload\":42,\"identity\":{},\"auth\":{},\"metadata\":{}}",
response
)
}
@Test
fun `should route parser exceptions to the ExceptionHandler`(): Unit = runBlocking {
val exception = slot<RuntimeException>()
val response = slot<RequestEvent>()
coEvery {
exceptionHandler.handleException(
capture(exception),
capture(response),
eq(rawEventProcessor.tracer)
)
} throws EventParsingException(null)
assertThrows<EventParsingException> {
runBlocking { processor.processEvent("not a json") }
}
coVerify(exactly = 1) {
exceptionHandler.handleException(
exception.captured,
response.captured,
rawEventProcessor.tracer
)
}
}
@Test
fun `should route create consider null event as a parser exception then route it to the ExceptionHandler`(): Unit =
runBlocking {
val exception = slot<RuntimeException>()
val response = slot<RequestEvent>()
coEvery {
exceptionHandler.handleException(
capture(exception),
capture(response),
eq(rawEventProcessor.tracer)
)
} throws EventParsingException(null)
assertThrows<EventParsingException> {
runBlocking { processor.processEvent("null") }
}
coVerify(exactly = 1) {
exceptionHandler.handleException(
exception.captured,
response.captured,
rawEventProcessor.tracer
)
}
}
}
| 6 | Kotlin | 24 | 22 | 7f7c5716da4d046eb60ef9465f6d92534e827b2d | 3,304 | events-protocol | Apache License 2.0 |
src/main/kotlin/team/msg/hiv2/domain/user/application/facade/UserFacadeImpl.kt | GSM-MSG | 634,687,373 | false | {"Kotlin": 211921, "Dockerfile": 177} | package team.msg.hiv2.domain.user.application.facade
import org.springframework.stereotype.Component
import team.msg.hiv2.domain.user.application.usecase.*
import team.msg.hiv2.domain.user.domain.constant.UserRole
import team.msg.hiv2.domain.user.presentation.data.request.SearchUserKeywordRequest
import team.msg.hiv2.domain.user.presentation.data.request.UpdateUserRoleWebRequest
import team.msg.hiv2.domain.user.presentation.data.request.UpdateUserUseStatusRequest
import team.msg.hiv2.domain.user.presentation.data.response.AllUsersResponse
import team.msg.hiv2.domain.user.presentation.data.response.StudentResponse
import team.msg.hiv2.domain.user.presentation.data.response.UserInfoResponse
import team.msg.hiv2.domain.user.presentation.data.response.UserResponse
import team.msg.hiv2.domain.user.presentation.data.response.UserRoleResponse
import java.util.*
@Component
class UserFacadeImpl(
private val queryAllUsersUseCase: QueryAllUsersUseCase,
private val queryAllUsersByUserRoleUseCase: QueryAllUsersByUserRoleUseCase,
private val queryUserInfoUseCase: QueryUserInfoUseCase,
private val queryMyRoleUseCase: QueryMyRoleUseCase,
private val searchUserByNameKeywordUseCase: SearchUserByNameKeywordUseCase,
private val updateUserUseStatusUseCase: UpdateUserUseStatusUseCase,
private val updateUserRoleUseCase: UpdateUserRoleUseCase,
private val searchStudentByNameKeywordUseCase: SearchStudentByNameKeywordUseCase
) : UserFacade {
override fun queryAllUsers(): AllUsersResponse =
queryAllUsersUseCase.execute()
override fun queryAllUsersByUserRole(userRole: UserRole): AllUsersResponse =
queryAllUsersByUserRoleUseCase.execute(userRole)
override fun queryUserInfo(): UserInfoResponse =
queryUserInfoUseCase.execute()
override fun queryMyRole(): UserRoleResponse =
queryMyRoleUseCase.execute()
override fun searchUserByNameKeyword(request: SearchUserKeywordRequest): List<UserResponse> =
searchUserByNameKeywordUseCase.execute(request)
override fun updateUserUseStatus(userId: UUID, request: UpdateUserUseStatusRequest) =
updateUserUseStatusUseCase.execute(userId, request)
override fun updateUserRole(userId: UUID, request: UpdateUserRoleWebRequest) =
updateUserRoleUseCase.execute(userId, request)
override fun searchStudentByNameKeyword(request: SearchUserKeywordRequest): List<StudentResponse> =
searchStudentByNameKeywordUseCase.execute(request)
} | 0 | Kotlin | 0 | 9 | c236025975e81ea4120969d5f25d88061947a9c4 | 2,498 | Hi-v2-BackEnd | MIT License |
app/src/main/java/org/booncode/thebabyapp/db/NursingDatabase.kt | boon-code | 194,670,236 | false | null | package org.booncode.thebabyapp.db
import android.content.ContentValues
import android.content.Context
import android.database.Cursor
import android.database.sqlite.SQLiteDatabase
import android.database.sqlite.SQLiteOpenHelper
import android.util.Log
import org.booncode.thebabyapp.common.*
import java.lang.IllegalArgumentException
data class NursingEntry(var braSide: BraState = BraState.None,
var start: Long = -1,
var stop: Long = -1,
var duration: Long = -1,
var state: NursingState = NursingState.INVALID,
var id: Long? = null) {
companion object {
val TABLE = "NursingTable"
val ID = "NursingId"
val BRA_SIDE = "BraSide"
val START = "NursingStart"
val STOP = "NursingStop"
val DURATION = "NursingDurationSeconds"
val STATE = "NursingState"
}
}
class NursingDatabase(context: Context,
factory: SQLiteDatabase.CursorFactory?) :
SQLiteOpenHelper(context, DB_NAME, factory, DB_VERSION) {
private var savedEntryListener: OnSavedEntryListener? = null
interface OnSavedEntryListener {
fun onSavedEntry()
}
fun setOnSavedEntryListener(listener: OnSavedEntryListener?) {
savedEntryListener = listener
}
init {
dbInstances.add(this)
}
override fun onCreate(db: SQLiteDatabase?) {
Log.d(TAG, "Database created")
db!!.execSQL("""CREATE TABLE
${NursingEntry.TABLE} (
${NursingEntry.ID} INTEGER PRIMARY KEY AUTOINCREMENT,
${NursingEntry.BRA_SIDE} INTEGER,
${NursingEntry.START} INTEGER,
${NursingEntry.STOP} INTEGER,
${NursingEntry.DURATION} INTEGER,
${NursingEntry.STATE} INTEGER)
""".trimIndent())
}
override fun onUpgrade(db: SQLiteDatabase?, thisVersion: Int, newVersion: Int) {
TODO("Not yet necessary")
}
private fun updateLastEntry(func: (entry: NursingEntry) -> Unit): NursingEntry {
val db = this.writableDatabase
db.beginTransaction()
try {
var entry = lastEntry(db)
if (entry == null)
entry = createNew(db)
func(entry)
Log.d(TAG, "Saving ${entry.braSide}, ${entry.duration} ${entry.id}")
db.update(
NursingEntry.TABLE,
toCV(entry),
"${NursingEntry.ID} = ?",
arrayOf(entry.id.toString())
)
db.setTransactionSuccessful()
return entry
} finally {
db.endTransaction()
db.close()
}
}
fun setBraSide(braSide: BraState): NursingEntry {
return updateLastEntry { entry ->
when (entry.state) {
NursingState.INVALID -> entry.braSide = braSide
else -> {
Log.d(TAG, "Illegal operation, abort")
}
}
}
}
fun setPending(braSide: BraState, start: Long): NursingEntry {
when (braSide) {
BraState.None -> throw IllegalArgumentException("BraState must be Left or Right")
else -> { }
}
if (start < 0) {
throw IllegalArgumentException("start time must be >= 0")
}
return updateLastEntry { entry ->
when (entry.state) {
NursingState.RUNNING, NursingState.INVALID -> {
entry.braSide = braSide
entry.start = start
entry.state = NursingState.RUNNING
}
else -> { }
}
}
}
fun cancelPending(): NursingEntry {
return updateLastEntry { entry ->
when (entry.state) {
NursingState.RUNNING -> entry.state = NursingState.INVALID
else -> { }
}
}
}
fun saveEntry(stop: Long, duration: Long = -1): NursingEntry {
return updateLastEntry { entry ->
when (entry.state) {
NursingState.RUNNING -> {
entry.stop = stop
if (duration < 0) {
entry.duration = entry.stop - entry.start
} else {
entry.duration = duration
}
entry.state = NursingState.SAVED
onSavedEntry()
}
else -> { }
}
}
}
private fun createNew(db: SQLiteDatabase): NursingEntry {
val cv = toCV(NursingEntry(state = NursingState.INVALID))
db.insert(NursingEntry.TABLE, null, cv)
val entry = lastEntry(db)!!
Log.d(TAG, "Create new Entry: ${entry.id}")
return entry
}
private fun queryEntry(cursor: Cursor): NursingEntry? {
try {
if (cursor.count == 0) {
return null
} else {
cursor.moveToFirst()
return toNursingEntry(cursor)
}
} finally {
cursor.close()
}
}
private fun lastEntry(db: SQLiteDatabase): NursingEntry? = queryEntry(queryLastEntry(db))
private fun lastSavedEntry(db: SQLiteDatabase): NursingEntry? = queryEntry(queryLastSavedEntry(db))
fun getLastSavedEntry(): NursingEntry? {
val db = this.readableDatabase
try {
return lastSavedEntry(db)
} finally {
db.close()
}
}
fun getSavedEntries(): Cursor {
val db = this.readableDatabase
return db.rawQuery("""
SELECT * from ${NursingEntry.TABLE}
WHERE ${NursingEntry.STATE} = ?
ORDER BY ${NursingEntry.ID}
DESC
""".trimIndent(), arrayOf(NursingState.SAVED.value.toString()))
}
fun getUnfinishedEntry(): NursingEntry {
val db = this.writableDatabase
db.beginTransaction()
try {
var entry = lastEntry(db)
when (entry?.state) {
NursingState.RUNNING, NursingState.INVALID -> { }
else -> { entry = createNew(db) }
}
db.setTransactionSuccessful()
return entry
} finally {
db.endTransaction()
db.close()
}
}
private fun queryLastSavedEntry(db: SQLiteDatabase): Cursor {
return db.rawQuery("""
SELECT * from ${NursingEntry.TABLE}
WHERE ${NursingEntry.STATE} = ?
ORDER BY ${NursingEntry.ID}
DESC LIMIT 1
""".trimIndent(), arrayOf(NursingState.SAVED.value.toString()))
}
private fun queryLastEntry(db: SQLiteDatabase): Cursor {
return db.rawQuery("""
SELECT * from ${NursingEntry.TABLE}
ORDER BY ${NursingEntry.ID}
DESC LIMIT 1
""".trimIndent(), null)
}
protected fun finalize() {
dbInstances.remove(this)
}
companion object {
private val DB_NAME = "NursingDB"
private val DB_VERSION = 1
private val TAG = "TBA.NursingDB"
private val dbInstances = mutableListOf<NursingDatabase>()
private fun onSavedEntry() {
dbInstances.forEach {
it.savedEntryListener?.onSavedEntry()
}
}
fun toNursingEntry(cursor: Cursor): NursingEntry {
val braSideIdx = cursor.getColumnIndexOrThrow(NursingEntry.BRA_SIDE)
val startIdx = cursor.getColumnIndexOrThrow(NursingEntry.START)
val stopIdx = cursor.getColumnIndexOrThrow(NursingEntry.STOP)
val durationIdx = cursor.getColumnIndexOrThrow(NursingEntry.DURATION)
val stateIdx = cursor.getColumnIndexOrThrow(NursingEntry.STATE)
val idIdx = cursor.getColumnIndexOrThrow(NursingEntry.ID)
return NursingEntry(
braSide = BraState.from(cursor.getInt(braSideIdx)),
start = cursor.getLong(startIdx),
stop = cursor.getLong(stopIdx),
duration = cursor.getLong(durationIdx),
state = NursingState.from(cursor.getInt(stateIdx)),
id = cursor.getLong(idIdx)
)
}
fun toCV(entry: NursingEntry): ContentValues {
val cvs = ContentValues()
with(cvs) {
put(NursingEntry.BRA_SIDE, entry.braSide.getValue())
put(NursingEntry.START, entry.start)
put(NursingEntry.STOP, entry.stop)
put(NursingEntry.DURATION, entry.duration)
put(NursingEntry.STATE, entry.state.getValue())
}
return cvs
}
}
} | 0 | Kotlin | 0 | 0 | 93bb6380f5462ecdd59313155331b01b75568ecf | 8,836 | the-baby-app | MIT License |
app/src/main/java/com/lifeSavers/emergencyapp/activities/ConfirmEmailActivity.kt | crime-story | 611,612,574 | false | null | package com.lifeSavers.emergencyapp.activities
import android.content.Intent
import android.net.Uri
import android.os.Bundle
import android.widget.Button
import androidx.appcompat.app.AppCompatActivity
import com.lifeSavers.emergencyapp.R
class ConfirmEmailActivity : AppCompatActivity() {
private val gmailPackageName = "com.google.android.gm"
private val playStorePackageName = "com.android.vending"
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_confirm_email)
val gmailButton = findViewById<Button>(R.id.gmail_button)
gmailButton.setOnClickListener {
val gmailIntent = packageManager.getLaunchIntentForPackage(gmailPackageName)
if (gmailIntent != null) {
startActivity(gmailIntent)
} else {
val playStoreIntent = Intent(Intent.ACTION_VIEW).apply {
data = Uri.parse("market://details?id=$gmailPackageName")
setPackage(playStorePackageName)
}
startActivity(playStoreIntent)
}
}
val outlookButton = findViewById<Button>(R.id.outlook_button)
outlookButton.setOnClickListener {
val outlookPackageName = "com.microsoft.office.outlook"
val outlookIntent = packageManager.getLaunchIntentForPackage(outlookPackageName)
if (outlookIntent != null) {
startActivity(outlookIntent)
} else {
val playStoreIntent = Intent(Intent.ACTION_VIEW).apply {
data = Uri.parse("market://details?id=$outlookPackageName")
setPackage(playStorePackageName)
}
startActivity(playStoreIntent)
}
}
val loginButton = findViewById<Button>(R.id.login_button)
loginButton.setOnClickListener {
startActivity(Intent(this, LogInActivity::class.java))
}
}
}
| 0 | Kotlin | 0 | 0 | 244e6b873513fa9ab67ad8269ff3a1130cf8b648 | 2,033 | EmergencyApp | MIT License |
app/src/androidTest/java/com/example/myapplication/ExampleInstrumentedTest.kt | PrakashIrom | 831,644,198 | false | {"Kotlin": 94025} | package com.example.myapplication
import androidx.compose.runtime.Composable
import androidx.lifecycle.viewmodel.compose.viewModel
import androidx.test.platform.app.InstrumentationRegistry
import androidx.test.ext.junit.runners.AndroidJUnit4
import com.example.myapplication.api.CreateTokenApi
import com.example.myapplication.viewmodel.TokenResponse
import com.example.myapplication.viewmodel.TokenViewModel
import kotlinx.coroutines.flow.flowOf
import kotlinx.coroutines.test.runTest
import org.junit.Test
import org.junit.runner.RunWith
import org.junit.Assert.*
/**
* Instrumented test, which will execute on an Android device.
*
* See [testing documentation](http://d.android.com/tools/testing).
*/
| 0 | Kotlin | 0 | 0 | 40c5b7303102941fc56ac73022fcf1326004559b | 712 | MMA-Store | Apache License 2.0 |
app/src/main/java/com/nafanya/mp3world/features/artists/di/ArtistsModule.kt | AlexSoWhite | 445,900,000 | false | {"Kotlin": 324834} | package com.nafanya.mp3world.features.artists.di
import androidx.lifecycle.ViewModel
import com.nafanya.mp3world.core.di.viewModel.ViewModelKey
import com.nafanya.mp3world.core.listManagers.ARTIST_LIST_MANAGER_KEY
import com.nafanya.mp3world.core.listManagers.ListManager
import com.nafanya.mp3world.core.listManagers.ListManagerKey
import com.nafanya.mp3world.features.artists.ArtistListManager
import com.nafanya.mp3world.features.artists.ArtistListManagerImpl
import com.nafanya.mp3world.features.artists.viewModel.ArtistListViewModel
import dagger.Binds
import dagger.Module
import dagger.multibindings.IntoMap
@Module
interface ArtistsModule {
@Binds
@[IntoMap ViewModelKey(ArtistListViewModel::class)]
fun bindViewModel(artistListViewModel: ArtistListViewModel): ViewModel
@Binds
@[IntoMap ListManagerKey(ARTIST_LIST_MANAGER_KEY)]
fun bindIntoMap(artistListManager: ArtistListManagerImpl): ListManager
@Binds
fun bind(artistListManager: ArtistListManagerImpl): ArtistListManager
}
| 0 | Kotlin | 0 | 0 | ee7cff2c21e4731caeb3064c21cc89fcfc8a49c2 | 1,024 | mp3world | MIT License |
service/src/main/kotlin/no/nav/su/se/bakover/service/søknadsbehandling/SøknadsbehandlingServiceImpl.kt | navikt | 227,366,088 | false | null | package no.nav.su.se.bakover.service.søknadsbehandling
import arrow.core.Either
import arrow.core.getOrElse
import arrow.core.left
import arrow.core.right
import no.nav.su.se.bakover.common.ident.NavIdentBruker
import no.nav.su.se.bakover.common.journal.JournalpostId
import no.nav.su.se.bakover.common.persistence.SessionFactory
import no.nav.su.se.bakover.common.persistence.TransactionContext
import no.nav.su.se.bakover.common.person.Fnr
import no.nav.su.se.bakover.common.tid.Tidspunkt
import no.nav.su.se.bakover.common.tid.YearRange
import no.nav.su.se.bakover.common.tid.krympTilØvreGrense
import no.nav.su.se.bakover.common.tid.toRange
import no.nav.su.se.bakover.domain.Sak
import no.nav.su.se.bakover.domain.behandling.BehandlingMetrics
import no.nav.su.se.bakover.domain.brev.BrevService
import no.nav.su.se.bakover.domain.dokument.KunneIkkeLageDokument
import no.nav.su.se.bakover.domain.grunnlag.EksterneGrunnlagSkatt
import no.nav.su.se.bakover.domain.grunnlag.Grunnlag.Bosituasjon.Companion.harEPS
import no.nav.su.se.bakover.domain.grunnlag.fradrag.LeggTilFradragsgrunnlagRequest
import no.nav.su.se.bakover.domain.grunnlag.singleFullstendigEpsOrNull
import no.nav.su.se.bakover.domain.oppdrag.UtbetalingsinstruksjonForEtterbetalinger
import no.nav.su.se.bakover.domain.oppgave.OppgaveConfig
import no.nav.su.se.bakover.domain.oppgave.OppgaveId
import no.nav.su.se.bakover.domain.oppgave.OppgaveService
import no.nav.su.se.bakover.domain.person.PersonService
import no.nav.su.se.bakover.domain.revurdering.vilkår.bosituasjon.KunneIkkeLeggeTilBosituasjongrunnlag
import no.nav.su.se.bakover.domain.revurdering.vilkår.bosituasjon.LeggTilBosituasjonerRequest
import no.nav.su.se.bakover.domain.sak.SakService
import no.nav.su.se.bakover.domain.sak.lagNyUtbetaling
import no.nav.su.se.bakover.domain.sak.simulerUtbetaling
import no.nav.su.se.bakover.domain.satser.SatsFactory
import no.nav.su.se.bakover.domain.skatt.Skattegrunnlag
import no.nav.su.se.bakover.domain.statistikk.StatistikkEvent
import no.nav.su.se.bakover.domain.statistikk.StatistikkEventObserver
import no.nav.su.se.bakover.domain.statistikk.notify
import no.nav.su.se.bakover.domain.søknadsbehandling.BeregnetSøknadsbehandling
import no.nav.su.se.bakover.domain.søknadsbehandling.KanBeregnes
import no.nav.su.se.bakover.domain.søknadsbehandling.KunneIkkeLeggeTilGrunnlag
import no.nav.su.se.bakover.domain.søknadsbehandling.KunneIkkeLeggeTilGrunnlag.KunneIkkeLeggeTilFradragsgrunnlag.GrunnlagetMåVæreInnenforBehandlingsperioden
import no.nav.su.se.bakover.domain.søknadsbehandling.KunneIkkeLeggeTilGrunnlag.KunneIkkeLeggeTilFradragsgrunnlag.IkkeLovÅLeggeTilFradragIDenneStatusen
import no.nav.su.se.bakover.domain.søknadsbehandling.KunneIkkeLeggeTilSkattegrunnlag
import no.nav.su.se.bakover.domain.søknadsbehandling.KunneIkkeLeggeTilVilkår
import no.nav.su.se.bakover.domain.søknadsbehandling.LukketSøknadsbehandling
import no.nav.su.se.bakover.domain.søknadsbehandling.SimulertSøknadsbehandling
import no.nav.su.se.bakover.domain.søknadsbehandling.Statusovergang
import no.nav.su.se.bakover.domain.søknadsbehandling.Søknadsbehandling
import no.nav.su.se.bakover.domain.søknadsbehandling.SøknadsbehandlingRepo
import no.nav.su.se.bakover.domain.søknadsbehandling.SøknadsbehandlingService
import no.nav.su.se.bakover.domain.søknadsbehandling.SøknadsbehandlingService.BeregnRequest
import no.nav.su.se.bakover.domain.søknadsbehandling.SøknadsbehandlingService.BrevRequest
import no.nav.su.se.bakover.domain.søknadsbehandling.SøknadsbehandlingService.FantIkkeBehandling
import no.nav.su.se.bakover.domain.søknadsbehandling.SøknadsbehandlingService.HentRequest
import no.nav.su.se.bakover.domain.søknadsbehandling.SøknadsbehandlingService.KunneIkkeBeregne
import no.nav.su.se.bakover.domain.søknadsbehandling.SøknadsbehandlingService.KunneIkkeLeggeTilFamiliegjenforeningVilkårService
import no.nav.su.se.bakover.domain.søknadsbehandling.SøknadsbehandlingService.KunneIkkeLeggeTilFamiliegjenforeningVilkårService.FantIkkeBehandling.tilKunneIkkeLeggeTilFamiliegjenforeningVilkårService
import no.nav.su.se.bakover.domain.søknadsbehandling.SøknadsbehandlingService.KunneIkkeLeggeTilFradragsgrunnlag
import no.nav.su.se.bakover.domain.søknadsbehandling.SøknadsbehandlingService.KunneIkkeLeggeTilUføreVilkår
import no.nav.su.se.bakover.domain.søknadsbehandling.SøknadsbehandlingService.KunneIkkeLeggeTilUtenlandsopphold
import no.nav.su.se.bakover.domain.søknadsbehandling.SøknadsbehandlingService.KunneIkkeSendeTilAttestering
import no.nav.su.se.bakover.domain.søknadsbehandling.SøknadsbehandlingService.KunneIkkeSimulereBehandling
import no.nav.su.se.bakover.domain.søknadsbehandling.SøknadsbehandlingService.KunneIkkeUnderkjenne
import no.nav.su.se.bakover.domain.søknadsbehandling.SøknadsbehandlingService.OppdaterStønadsperiodeRequest
import no.nav.su.se.bakover.domain.søknadsbehandling.SøknadsbehandlingService.OpprettRequest
import no.nav.su.se.bakover.domain.søknadsbehandling.SøknadsbehandlingService.SendTilAttesteringRequest
import no.nav.su.se.bakover.domain.søknadsbehandling.SøknadsbehandlingService.SimulerRequest
import no.nav.su.se.bakover.domain.søknadsbehandling.SøknadsbehandlingService.UnderkjennRequest
import no.nav.su.se.bakover.domain.søknadsbehandling.SøknadsbehandlingTilAttestering
import no.nav.su.se.bakover.domain.søknadsbehandling.SøknadsbehandlingsHandling
import no.nav.su.se.bakover.domain.søknadsbehandling.Søknadsbehandlingshendelse
import no.nav.su.se.bakover.domain.søknadsbehandling.UnderkjentSøknadsbehandling
import no.nav.su.se.bakover.domain.søknadsbehandling.VilkårsvurdertSøknadsbehandling
import no.nav.su.se.bakover.domain.søknadsbehandling.forsøkStatusovergang
import no.nav.su.se.bakover.domain.søknadsbehandling.medFritekstTilBrev
import no.nav.su.se.bakover.domain.søknadsbehandling.opprett.opprettNySøknadsbehandling
import no.nav.su.se.bakover.domain.søknadsbehandling.statusovergang
import no.nav.su.se.bakover.domain.søknadsbehandling.stønadsperiode.oppdaterStønadsperiodeForSøknadsbehandling
import no.nav.su.se.bakover.domain.vilkår.FormuegrenserFactory
import no.nav.su.se.bakover.domain.vilkår.familiegjenforening.LeggTilFamiliegjenforeningRequest
import no.nav.su.se.bakover.domain.vilkår.fastopphold.KunneIkkeLeggeFastOppholdINorgeVilkår
import no.nav.su.se.bakover.domain.vilkår.fastopphold.LeggTilFastOppholdINorgeRequest
import no.nav.su.se.bakover.domain.vilkår.flyktning.KunneIkkeLeggeTilFlyktningVilkår
import no.nav.su.se.bakover.domain.vilkår.flyktning.LeggTilFlyktningVilkårRequest
import no.nav.su.se.bakover.domain.vilkår.formue.LeggTilFormuevilkårRequest
import no.nav.su.se.bakover.domain.vilkår.institusjonsopphold.KunneIkkeLeggeTilInstitusjonsoppholdVilkår
import no.nav.su.se.bakover.domain.vilkår.institusjonsopphold.LeggTilInstitusjonsoppholdVilkårRequest
import no.nav.su.se.bakover.domain.vilkår.lovligopphold.KunneIkkeLeggetilLovligOppholdVilkår
import no.nav.su.se.bakover.domain.vilkår.lovligopphold.LeggTilLovligOppholdRequest
import no.nav.su.se.bakover.domain.vilkår.opplysningsplikt.KunneIkkeLeggeTilOpplysningsplikt
import no.nav.su.se.bakover.domain.vilkår.opplysningsplikt.LeggTilOpplysningspliktRequest
import no.nav.su.se.bakover.domain.vilkår.oppmøte.KunneIkkeLeggeTilPersonligOppmøteVilkår
import no.nav.su.se.bakover.domain.vilkår.oppmøte.LeggTilPersonligOppmøteVilkårRequest
import no.nav.su.se.bakover.domain.vilkår.pensjon.KunneIkkeLeggeTilPensjonsVilkår
import no.nav.su.se.bakover.domain.vilkår.pensjon.LeggTilPensjonsVilkårRequest
import no.nav.su.se.bakover.domain.vilkår.uføre.LeggTilUførevurderingerRequest
import no.nav.su.se.bakover.domain.vilkår.utenlandsopphold.LeggTilFlereUtenlandsoppholdRequest
import no.nav.su.se.bakover.service.skatt.SkatteService
import no.nav.su.se.bakover.service.tilbakekreving.TilbakekrevingService
import no.nav.su.se.bakover.service.utbetaling.UtbetalingService
import org.slf4j.LoggerFactory
import java.time.Clock
import java.time.Year
import java.util.UUID
class SøknadsbehandlingServiceImpl(
private val søknadsbehandlingRepo: SøknadsbehandlingRepo,
private val utbetalingService: UtbetalingService,
private val personService: PersonService,
private val oppgaveService: OppgaveService,
private val behandlingMetrics: BehandlingMetrics,
private val brevService: BrevService,
private val clock: Clock,
private val sakService: SakService,
private val tilbakekrevingService: TilbakekrevingService,
private val formuegrenserFactory: FormuegrenserFactory,
private val satsFactory: SatsFactory,
private val skatteService: SkatteService,
private val sessionFactory: SessionFactory,
) : SøknadsbehandlingService {
private val log = LoggerFactory.getLogger(this::class.java)
private val observers: MutableList<StatistikkEventObserver> = mutableListOf()
fun addObserver(observer: StatistikkEventObserver) {
observers.add(observer)
}
fun getObservers(): List<StatistikkEventObserver> = observers.toList()
/**
* Sideeffekter:
* - søknadsbehandlingen persisteres.
* - det sendes statistikk
*
* @param hentSak Mulighet for å sende med en funksjon som henter en sak, default er null, som gjør at saken hentes på nytt fra persisteringslaget basert på request.sakId.
*/
override fun opprett(
request: OpprettRequest,
hentSak: (() -> Sak)?,
): Either<Sak.KunneIkkeOppretteSøknadsbehandling, Pair<Sak, VilkårsvurdertSøknadsbehandling.Uavklart>> {
val sakId = request.sakId
val sak = hentSak?.let { it() } ?: sakService.hentSak(sakId)
.getOrElse { throw IllegalArgumentException("Fant ikke sak $sakId") }
require(sak.id == sakId) { "sak.id ${sak.id} må være lik request.sakId $sakId" }
return sak.opprettNySøknadsbehandling(
søknadId = request.søknadId,
clock = clock,
saksbehandler = request.saksbehandler,
).map { (sak, nySøknadsbehandling, uavklartSøknadsbehandling, statistikk) ->
søknadsbehandlingRepo.lagreNySøknadsbehandling(nySøknadsbehandling)
observers.notify(statistikk)
Pair(sak, uavklartSøknadsbehandling)
}
}
override fun beregn(request: BeregnRequest): Either<KunneIkkeBeregne, BeregnetSøknadsbehandling> {
val sak: Sak = sakService.hentSakForSøknadsbehandling(request.behandlingId)
val søknadsbehandling: KanBeregnes = sak.hentSøknadsbehandling(request.behandlingId)
.getOrElse { return KunneIkkeBeregne.FantIkkeBehandling.left() }
.let { it as? KanBeregnes ?: return KunneIkkeBeregne.UgyldigTilstand(it::class).left() }
return søknadsbehandling.beregn(
nySaksbehandler = request.saksbehandler,
begrunnelse = request.begrunnelse,
clock = clock,
satsFactory = satsFactory,
uteståendeAvkortingPåSak = sak.uteståendeAvkortingSkalAvkortes,
).mapLeft { feil ->
when (feil) {
no.nav.su.se.bakover.domain.søknadsbehandling.KunneIkkeBeregne.AvkortingErUfullstendig -> {
KunneIkkeBeregne.AvkortingErUfullstendig
}
is no.nav.su.se.bakover.domain.søknadsbehandling.KunneIkkeBeregne.UgyldigTilstandForEndringAvFradrag -> {
KunneIkkeBeregne.UgyldigTilstandForEndringAvFradrag(feil.feil.toService())
}
}
}.map {
søknadsbehandlingRepo.lagre(it)
it
}
}
override fun simuler(request: SimulerRequest): Either<KunneIkkeSimulereBehandling, SimulertSøknadsbehandling> {
val sak = sakService.hentSakForSøknadsbehandling(request.behandlingId)
val søknadsbehandling = sak.hentSøknadsbehandling(request.behandlingId)
.getOrElse { return KunneIkkeSimulereBehandling.FantIkkeBehandling.left() }
return søknadsbehandling.simuler(
saksbehandler = request.saksbehandler,
clock = clock,
) { beregning, uføregrunnlag ->
sak.lagNyUtbetaling(
saksbehandler = request.saksbehandler,
beregning = beregning,
clock = clock,
utbetalingsinstruksjonForEtterbetaling = UtbetalingsinstruksjonForEtterbetalinger.SåFortSomMulig,
uføregrunnlag = uføregrunnlag,
).let {
sak.simulerUtbetaling(
utbetalingForSimulering = it,
periode = beregning.periode,
simuler = utbetalingService::simulerUtbetaling,
kontrollerMotTidligereSimulering = null,
)
}.map { simulertUtbetaling ->
simulertUtbetaling.simulering
}
}.mapLeft {
KunneIkkeSimulereBehandling.KunneIkkeSimulere(it)
}.map {
søknadsbehandlingRepo.lagre(it)
it
}
}
override fun sendTilAttestering(request: SendTilAttesteringRequest): Either<KunneIkkeSendeTilAttestering, SøknadsbehandlingTilAttestering> {
val søknadsbehandlingFraBasenFørStatusovergang = søknadsbehandlingRepo.hent(request.behandlingId)?.let {
statusovergang(
søknadsbehandling = it,
statusovergang = Statusovergang.TilAttestering(request.saksbehandler, request.fritekstTilBrev, clock),
)
}
?: throw IllegalArgumentException("Søknadsbehandling send til attestering: Fant ikke søknadsbehandling ${request.behandlingId}")
søknadsbehandlingFraBasenFørStatusovergang.getOrElse {
return KunneIkkeSendeTilAttestering.HarValideringsfeil(it).left()
}.let { søknadsbehandling ->
val aktørId = personService.hentAktørId(søknadsbehandling.fnr).getOrElse {
log.error("Søknadsbehandling send til attestering: Fant ikke aktør-id knyttet til fødselsnummer for søknadsbehandling ${request.behandlingId}")
return KunneIkkeSendeTilAttestering.KunneIkkeFinneAktørId.left()
}
val eksisterendeOppgaveId: OppgaveId = søknadsbehandling.oppgaveId
val tilordnetRessurs: NavIdentBruker.Attestant? = søknadsbehandling.attesteringer.lastOrNull()?.attestant
val nyOppgaveId: OppgaveId = oppgaveService.opprettOppgave(
OppgaveConfig.AttesterSøknadsbehandling(
søknadId = søknadsbehandling.søknad.id,
aktørId = aktørId,
tilordnetRessurs = tilordnetRessurs,
clock = clock,
),
).getOrElse {
log.error("Søknadsbehandling send til attestering: Kunne ikke opprette Attesteringsoppgave for søknadsbehandling ${request.behandlingId}. Avbryter handlingen.")
return KunneIkkeSendeTilAttestering.KunneIkkeOppretteOppgave.left()
}
val søknadsbehandlingMedNyOppgaveIdOgFritekstTilBrev =
søknadsbehandling.nyOppgaveId(nyOppgaveId).medFritekstTilBrev(request.fritekstTilBrev)
søknadsbehandlingRepo.lagre(søknadsbehandlingMedNyOppgaveIdOgFritekstTilBrev)
oppgaveService.lukkOppgave(eksisterendeOppgaveId).map {
behandlingMetrics.incrementTilAttesteringCounter(BehandlingMetrics.TilAttesteringHandlinger.LUKKET_OPPGAVE)
}.mapLeft {
log.error("Søknadsbehandling send til attestering: Klarte ikke å lukke oppgave ${søknadsbehandling.oppgaveId} for søknadsbehandling ${request.behandlingId}.")
}
behandlingMetrics.incrementTilAttesteringCounter(BehandlingMetrics.TilAttesteringHandlinger.PERSISTERT)
behandlingMetrics.incrementTilAttesteringCounter(BehandlingMetrics.TilAttesteringHandlinger.OPPRETTET_OPPGAVE)
when (søknadsbehandlingMedNyOppgaveIdOgFritekstTilBrev) {
is SøknadsbehandlingTilAttestering.Avslag -> observers.notify(
StatistikkEvent.Behandling.Søknad.TilAttestering.Avslag(
søknadsbehandlingMedNyOppgaveIdOgFritekstTilBrev,
),
)
is SøknadsbehandlingTilAttestering.Innvilget -> observers.notify(
StatistikkEvent.Behandling.Søknad.TilAttestering.Innvilget(
søknadsbehandlingMedNyOppgaveIdOgFritekstTilBrev,
),
)
}
return søknadsbehandlingMedNyOppgaveIdOgFritekstTilBrev.right()
}
}
override fun underkjenn(request: UnderkjennRequest): Either<KunneIkkeUnderkjenne, UnderkjentSøknadsbehandling> {
val søknadsbehandling =
søknadsbehandlingRepo.hent(request.behandlingId) ?: return KunneIkkeUnderkjenne.FantIkkeBehandling.left()
return forsøkStatusovergang(
søknadsbehandling = søknadsbehandling,
statusovergang = Statusovergang.TilUnderkjent(request.attestering),
).mapLeft {
KunneIkkeUnderkjenne.AttestantOgSaksbehandlerKanIkkeVæreSammePerson
}.map { underkjent ->
val aktørId = personService.hentAktørId(underkjent.fnr).getOrElse {
log.error("Fant ikke aktør-id for sak: ${underkjent.id}")
return KunneIkkeUnderkjenne.FantIkkeAktørId.left()
}
val journalpostId: JournalpostId = underkjent.søknad.journalpostId
val eksisterendeOppgaveId = underkjent.oppgaveId
val nyOppgaveId = oppgaveService.opprettOppgave(
OppgaveConfig.Søknad(
journalpostId = journalpostId,
søknadId = underkjent.søknad.id,
aktørId = aktørId,
tilordnetRessurs = underkjent.saksbehandler,
clock = clock,
sakstype = underkjent.søknad.søknadInnhold.type(),
),
).getOrElse {
log.error("Behandling ${underkjent.id} ble ikke underkjent. Klarte ikke opprette behandlingsoppgave")
return@underkjenn KunneIkkeUnderkjenne.KunneIkkeOppretteOppgave.left()
}.also {
behandlingMetrics.incrementUnderkjentCounter(BehandlingMetrics.UnderkjentHandlinger.OPPRETTET_OPPGAVE)
}
val søknadsbehandlingMedNyOppgaveId = underkjent.nyOppgaveId(nyOppgaveId)
søknadsbehandlingRepo.lagre(søknadsbehandlingMedNyOppgaveId)
behandlingMetrics.incrementUnderkjentCounter(BehandlingMetrics.UnderkjentHandlinger.PERSISTERT)
log.info("Behandling ${underkjent.id} ble underkjent. Opprettet behandlingsoppgave $nyOppgaveId")
oppgaveService.lukkOppgave(eksisterendeOppgaveId).mapLeft {
log.error("Kunne ikke lukke attesteringsoppgave $eksisterendeOppgaveId ved underkjenning av behandlingen. Dette må gjøres manuelt.")
}.map {
log.info("Lukket attesteringsoppgave $eksisterendeOppgaveId ved underkjenning av behandlingen")
behandlingMetrics.incrementUnderkjentCounter(BehandlingMetrics.UnderkjentHandlinger.LUKKET_OPPGAVE)
}
when (søknadsbehandlingMedNyOppgaveId) {
is UnderkjentSøknadsbehandling.Avslag -> observers.notify(
StatistikkEvent.Behandling.Søknad.Underkjent.Avslag(
søknadsbehandlingMedNyOppgaveId,
),
)
is UnderkjentSøknadsbehandling.Innvilget -> observers.notify(
StatistikkEvent.Behandling.Søknad.Underkjent.Innvilget(
søknadsbehandlingMedNyOppgaveId,
),
)
}
søknadsbehandlingMedNyOppgaveId
}
}
override fun brev(request: BrevRequest): Either<KunneIkkeLageDokument, ByteArray> {
val behandling = when (request) {
is BrevRequest.MedFritekst -> request.behandling.medFritekstTilBrev(request.fritekst)
is BrevRequest.UtenFritekst -> request.behandling
}
return brevService.lagDokument(behandling).map { it.generertDokument }
}
override fun hent(request: HentRequest): Either<FantIkkeBehandling, Søknadsbehandling> {
return søknadsbehandlingRepo.hent(request.behandlingId)?.right() ?: FantIkkeBehandling.left()
}
override fun hentForSøknad(søknadId: UUID): Søknadsbehandling? {
return søknadsbehandlingRepo.hentForSøknad(søknadId)
}
override fun oppdaterStønadsperiode(
request: OppdaterStønadsperiodeRequest,
): Either<Sak.KunneIkkeOppdatereStønadsperiode, VilkårsvurdertSøknadsbehandling> {
val sak =
sakService.hentSak(request.sakId)
.getOrElse { throw IllegalArgumentException("Fant ikke sak ${request.sakId}") }
return sak.oppdaterStønadsperiodeForSøknadsbehandling(
søknadsbehandlingId = request.behandlingId,
stønadsperiode = request.stønadsperiode,
clock = clock,
formuegrenserFactory = formuegrenserFactory,
saksbehandler = request.saksbehandler,
hentPerson = personService::hentPerson,
saksbehandlersAvgjørelse = request.saksbehandlersAvgjørelse,
).map {
søknadsbehandlingRepo.lagre(it.second)
it.second
}
}
override fun leggTilUførevilkår(
request: LeggTilUførevurderingerRequest,
saksbehandler: NavIdentBruker.Saksbehandler,
): Either<KunneIkkeLeggeTilUføreVilkår, Søknadsbehandling> {
val søknadsbehandling = søknadsbehandlingRepo.hent(request.behandlingId)
?: return KunneIkkeLeggeTilUføreVilkår.FantIkkeBehandling.left()
val vilkår = request.toVilkår(
behandlingsperiode = søknadsbehandling.periode,
clock = clock,
).getOrElse {
return KunneIkkeLeggeTilUføreVilkår.UgyldigInput(it).left()
}
val vilkårsvurdert = søknadsbehandling.leggTilUførevilkår(saksbehandler, vilkår, clock).getOrElse {
return when (it) {
is KunneIkkeLeggeTilVilkår.KunneIkkeLeggeTilUførevilkår.UgyldigTilstand -> {
KunneIkkeLeggeTilUføreVilkår.UgyldigTilstand(fra = it.fra, til = it.til)
}
KunneIkkeLeggeTilVilkår.KunneIkkeLeggeTilUførevilkår.VurderingsperiodeUtenforBehandlingsperiode -> {
KunneIkkeLeggeTilUføreVilkår.VurderingsperiodenKanIkkeVæreUtenforBehandlingsperioden
}
}.left()
}
søknadsbehandlingRepo.lagre(vilkårsvurdert)
return vilkårsvurdert.right()
}
override fun leggTilLovligOpphold(
request: LeggTilLovligOppholdRequest,
saksbehandler: NavIdentBruker.Saksbehandler,
): Either<KunneIkkeLeggetilLovligOppholdVilkår, Søknadsbehandling> {
val søknadsbehandling = søknadsbehandlingRepo.hent(request.behandlingId)
?: return KunneIkkeLeggetilLovligOppholdVilkår.FantIkkeBehandling.left()
val vilkår = request.toVilkår(clock).getOrElse {
return KunneIkkeLeggetilLovligOppholdVilkår.UgyldigLovligOppholdVilkår(it).left()
}
return søknadsbehandling.leggTilLovligOpphold(
lovligOppholdVilkår = vilkår,
saksbehandler = saksbehandler,
clock = clock,
).mapLeft {
KunneIkkeLeggetilLovligOppholdVilkår.FeilVedSøknadsbehandling(it)
}.onRight {
søknadsbehandlingRepo.lagre(it)
}
}
override fun leggTilFamiliegjenforeningvilkår(
request: LeggTilFamiliegjenforeningRequest,
saksbehandler: NavIdentBruker.Saksbehandler,
): Either<KunneIkkeLeggeTilFamiliegjenforeningVilkårService, Søknadsbehandling> {
val søknadsbehandling = søknadsbehandlingRepo.hent(request.behandlingId)
?: return KunneIkkeLeggeTilFamiliegjenforeningVilkårService.FantIkkeBehandling.left()
val familiegjenforeningVilkår = request.toVilkår(
clock = clock,
stønadsperiode = søknadsbehandling.stønadsperiode?.periode,
).getOrElse {
return KunneIkkeLeggeTilFamiliegjenforeningVilkårService.UgyldigFamiliegjenforeningVilkårService(it).left()
}
familiegjenforeningVilkår.vurderingsperioder.single()
return søknadsbehandling.leggTilFamiliegjenforeningvilkår(
familiegjenforening = familiegjenforeningVilkår,
saksbehandler = saksbehandler,
).mapLeft {
it.tilKunneIkkeLeggeTilFamiliegjenforeningVilkårService()
}.onRight {
søknadsbehandlingRepo.lagre(it)
}
}
override fun leggTilFradragsgrunnlag(
request: LeggTilFradragsgrunnlagRequest,
saksbehandler: NavIdentBruker.Saksbehandler,
): Either<KunneIkkeLeggeTilFradragsgrunnlag, Søknadsbehandling> {
val behandling = søknadsbehandlingRepo.hent(request.behandlingId)
?: return KunneIkkeLeggeTilFradragsgrunnlag.FantIkkeBehandling.left()
/**
* I flere av funksjonene i denne fila bruker vi [Statusovergang] og [no.nav.su.se.bakover.domain.søknadsbehandling.StatusovergangVisitor] for å bestemme om det er en gyldig statusovergang, men i dette tilfellet bruker vi domenemodellen sin funksjon leggTilFradragsgrunnlag til dette.
* Vi ønsker gradvis å gå over til sistenevnte måte å gjøre det på.
*/
val oppdatertBehandling =
behandling.oppdaterFradragsgrunnlagForSaksbehandler(saksbehandler, request.fradragsgrunnlag, clock)
.getOrElse {
return it.toService().left()
}
søknadsbehandlingRepo.lagre(oppdatertBehandling)
return oppdatertBehandling.right()
}
private fun KunneIkkeLeggeTilGrunnlag.KunneIkkeLeggeTilFradragsgrunnlag.toService(): KunneIkkeLeggeTilFradragsgrunnlag {
return when (this) {
GrunnlagetMåVæreInnenforBehandlingsperioden -> {
KunneIkkeLeggeTilFradragsgrunnlag.GrunnlagetMåVæreInnenforBehandlingsperioden
}
is IkkeLovÅLeggeTilFradragIDenneStatusen -> {
KunneIkkeLeggeTilFradragsgrunnlag.UgyldigTilstand(
fra = this.status,
til = VilkårsvurdertSøknadsbehandling.Innvilget::class,
)
}
is KunneIkkeLeggeTilGrunnlag.KunneIkkeLeggeTilFradragsgrunnlag.KunneIkkeEndreFradragsgrunnlag -> {
KunneIkkeLeggeTilFradragsgrunnlag.KunneIkkeEndreFradragsgrunnlag(this.feil)
}
}
}
override fun persisterSøknadsbehandling(lukketSøknadbehandling: LukketSøknadsbehandling, tx: TransactionContext) {
søknadsbehandlingRepo.lagre(lukketSøknadbehandling, tx)
}
override fun leggTilUtenlandsopphold(
request: LeggTilFlereUtenlandsoppholdRequest,
saksbehandler: NavIdentBruker.Saksbehandler,
): Either<KunneIkkeLeggeTilUtenlandsopphold, VilkårsvurdertSøknadsbehandling> {
val søknadsbehandling = søknadsbehandlingRepo.hent(request.behandlingId)
?: return KunneIkkeLeggeTilUtenlandsopphold.FantIkkeBehandling.left()
val vilkår = request.tilVilkår(clock).getOrElse {
when (it) {
LeggTilFlereUtenlandsoppholdRequest.UgyldigUtenlandsopphold.OverlappendeVurderingsperioder -> throw IllegalStateException(
"$it Skal ikke kunne forekomme for søknadsbehandling",
)
LeggTilFlereUtenlandsoppholdRequest.UgyldigUtenlandsopphold.PeriodeForGrunnlagOgVurderingErForskjellig -> throw IllegalStateException(
"$it Skal ikke kunne forekomme for søknadsbehandling",
)
}
}
val vilkårsvurdert = søknadsbehandling.leggTilUtenlandsopphold(saksbehandler, vilkår, clock).getOrElse {
return it.tilService().left()
}
søknadsbehandlingRepo.lagre(vilkårsvurdert)
return vilkårsvurdert.right()
}
override fun leggTilOpplysningspliktVilkår(request: LeggTilOpplysningspliktRequest.Søknadsbehandling): Either<KunneIkkeLeggeTilOpplysningsplikt, VilkårsvurdertSøknadsbehandling> {
val søknadsbehandling = søknadsbehandlingRepo.hent(request.behandlingId)
?: return KunneIkkeLeggeTilOpplysningsplikt.FantIkkeBehandling.left()
return søknadsbehandling.leggTilOpplysningspliktVilkårForSaksbehandler(
request.saksbehandler,
request.vilkår,
clock,
).mapLeft {
KunneIkkeLeggeTilOpplysningsplikt.Søknadsbehandling(it)
}.map {
søknadsbehandlingRepo.lagre(it)
it
}
}
override fun leggTilPensjonsVilkår(
request: LeggTilPensjonsVilkårRequest,
saksbehandler: NavIdentBruker.Saksbehandler,
): Either<KunneIkkeLeggeTilPensjonsVilkår, VilkårsvurdertSøknadsbehandling> {
val søknadsbehandling = søknadsbehandlingRepo.hent(request.behandlingId)
?: return KunneIkkeLeggeTilPensjonsVilkår.FantIkkeBehandling.left()
return søknadsbehandling.leggTilPensjonsVilkår(request.vilkår, saksbehandler).mapLeft {
KunneIkkeLeggeTilPensjonsVilkår.Søknadsbehandling(it)
}.map {
søknadsbehandlingRepo.lagre(it)
it
}
}
override fun leggTilFlyktningVilkår(
request: LeggTilFlyktningVilkårRequest,
saksbehandler: NavIdentBruker.Saksbehandler,
): Either<KunneIkkeLeggeTilFlyktningVilkår, VilkårsvurdertSøknadsbehandling> {
val søknadsbehandling = søknadsbehandlingRepo.hent(request.behandlingId)
?: return KunneIkkeLeggeTilFlyktningVilkår.FantIkkeBehandling.left()
return søknadsbehandling.leggTilFlyktningVilkår(saksbehandler, request.vilkår, clock).mapLeft {
KunneIkkeLeggeTilFlyktningVilkår.Søknadsbehandling(it)
}.map {
søknadsbehandlingRepo.lagre(it)
it
}
}
override fun leggTilFastOppholdINorgeVilkår(
request: LeggTilFastOppholdINorgeRequest,
saksbehandler: NavIdentBruker.Saksbehandler,
): Either<KunneIkkeLeggeFastOppholdINorgeVilkår, VilkårsvurdertSøknadsbehandling> {
val søknadsbehandling = søknadsbehandlingRepo.hent(request.behandlingId)
?: return KunneIkkeLeggeFastOppholdINorgeVilkår.FantIkkeBehandling.left()
return søknadsbehandling.leggTilFastOppholdINorgeVilkår(saksbehandler, request.vilkår, clock).mapLeft {
KunneIkkeLeggeFastOppholdINorgeVilkår.Søknadsbehandling(it)
}.map {
søknadsbehandlingRepo.lagre(it)
it
}
}
override fun leggTilPersonligOppmøteVilkår(
request: LeggTilPersonligOppmøteVilkårRequest,
saksbehandler: NavIdentBruker.Saksbehandler,
): Either<KunneIkkeLeggeTilPersonligOppmøteVilkår, VilkårsvurdertSøknadsbehandling> {
val søknadsbehandling = søknadsbehandlingRepo.hent(request.behandlingId)
?: return KunneIkkeLeggeTilPersonligOppmøteVilkår.FantIkkeBehandling.left()
return søknadsbehandling.leggTilPersonligOppmøteVilkår(saksbehandler, request.vilkår, clock).mapLeft {
KunneIkkeLeggeTilPersonligOppmøteVilkår.Søknadsbehandling(it)
}.map {
søknadsbehandlingRepo.lagre(it)
it
}
}
override fun leggTilFormuevilkår(
request: LeggTilFormuevilkårRequest,
): Either<KunneIkkeLeggeTilVilkår.KunneIkkeLeggeTilFormuevilkår, Søknadsbehandling> {
val søknadsbehandling = søknadsbehandlingRepo.hent(request.behandlingId)
?: throw IllegalArgumentException("Fant ikke behandling med id ${request.behandlingId}")
return søknadsbehandling.leggTilFormuegrunnlag(
request = request,
formuegrenserFactory = formuegrenserFactory,
).onRight {
søknadsbehandlingRepo.lagre(it)
}
}
override fun leggTilInstitusjonsoppholdVilkår(
request: LeggTilInstitusjonsoppholdVilkårRequest,
saksbehandler: NavIdentBruker.Saksbehandler,
): Either<KunneIkkeLeggeTilInstitusjonsoppholdVilkår, VilkårsvurdertSøknadsbehandling> {
val søknadsbehandling = søknadsbehandlingRepo.hent(request.behandlingId)
?: return KunneIkkeLeggeTilInstitusjonsoppholdVilkår.FantIkkeBehandling.left()
return søknadsbehandling.leggTilInstitusjonsoppholdVilkår(saksbehandler, request.vilkår, clock).mapLeft {
KunneIkkeLeggeTilInstitusjonsoppholdVilkår.Søknadsbehandling(it)
}.map {
søknadsbehandlingRepo.lagre(it)
it
}
}
override fun leggTilBosituasjongrunnlag(
request: LeggTilBosituasjonerRequest,
saksbehandler: NavIdentBruker.Saksbehandler,
): Either<KunneIkkeLeggeTilBosituasjongrunnlag, VilkårsvurdertSøknadsbehandling> {
val søknadsbehandling = søknadsbehandlingRepo.hent(request.behandlingId)
?: return KunneIkkeLeggeTilBosituasjongrunnlag.FantIkkeBehandling.left()
val bosituasjon =
if (request.bosituasjoner.size > 1) {
throw IllegalArgumentException("Forventer kun 1 bosituasjon element ved søknadsbehandling")
} else {
request.bosituasjoner.first().toDomain(clock = clock, hentPerson = personService::hentPerson)
.getOrElse { return it.left() }
}
return søknadsbehandling.oppdaterBosituasjon(
saksbehandler = saksbehandler,
bosituasjon = bosituasjon,
hendelse = Søknadsbehandlingshendelse(
tidspunkt = Tidspunkt.now(clock),
saksbehandler = saksbehandler,
handling = SøknadsbehandlingsHandling.OppdatertBosituasjon,
),
).mapLeft {
KunneIkkeLeggeTilBosituasjongrunnlag.KunneIkkeLeggeTilGrunnlag(it)
}.map {
sessionFactory.withTransactionContext { tx ->
søknadsbehandlingRepo.lagre(it, tx)
}
it
}
}
override fun leggTilEksternSkattegrunnlag(
behandlingId: UUID,
saksbehandler: NavIdentBruker.Saksbehandler,
): Either<KunneIkkeLeggeTilSkattegrunnlag, Søknadsbehandling> {
val søknadsbehandling = søknadsbehandlingRepo.hent(behandlingId)
?: throw IllegalStateException("Fant ikke behandling $behandlingId")
return søknadsbehandling.leggTilSkatt(
EksterneGrunnlagSkatt.Hentet(
søkers = søknadsbehandling.hentSkattegrunnlagForSøker(
saksbehandler,
skatteService::hentSamletSkattegrunnlagForÅr,
clock,
),
eps = søknadsbehandling.hentSkattegrunnlagForEps(
saksbehandler,
skatteService::hentSamletSkattegrunnlagForÅr,
clock,
),
),
).onRight { søknadsbehandlingRepo.lagre(it) }
}
private fun Søknadsbehandling.hentSkattegrunnlagForSøker(
saksbehandler: NavIdentBruker.Saksbehandler,
samletSkattegrunnlag: (Fnr, NavIdentBruker.Saksbehandler, YearRange) -> Skattegrunnlag,
clock: Clock,
): Skattegrunnlag = samletSkattegrunnlag(fnr, saksbehandler, getYearRangeForSkatt(clock))
private fun Søknadsbehandling.hentSkattegrunnlagForEps(
saksbehandler: NavIdentBruker.Saksbehandler,
samletSkattegrunnlag: (Fnr, NavIdentBruker.Saksbehandler, YearRange) -> Skattegrunnlag,
clock: Clock,
): Skattegrunnlag? = if (grunnlagsdata.bosituasjon.harEPS()) {
samletSkattegrunnlag(
grunnlagsdata.bosituasjon.singleFullstendigEpsOrNull()!!.fnr,
saksbehandler,
getYearRangeForSkatt(clock),
)
} else {
null
}
private fun Søknadsbehandling.getYearRangeForSkatt(clock: Clock): YearRange {
return Year.now(clock).minusYears(1).let {
stønadsperiode?.toYearRange()?.krympTilØvreGrense(it) ?: it.toRange()
}
}
private fun KunneIkkeLeggeTilVilkår.KunneIkkeLeggeTilUtenlandsopphold.tilService(): KunneIkkeLeggeTilUtenlandsopphold =
when (this) {
is KunneIkkeLeggeTilVilkår.KunneIkkeLeggeTilUtenlandsopphold.IkkeLovÅLeggeTilUtenlandsoppholdIDenneStatusen ->
KunneIkkeLeggeTilUtenlandsopphold.UgyldigTilstand(fra = this.fra, til = this.til)
KunneIkkeLeggeTilVilkår.KunneIkkeLeggeTilUtenlandsopphold.VurderingsperiodeUtenforBehandlingsperiode ->
KunneIkkeLeggeTilUtenlandsopphold.VurderingsperiodeUtenforBehandlingsperiode
KunneIkkeLeggeTilVilkår.KunneIkkeLeggeTilUtenlandsopphold.AlleVurderingsperioderMåHaSammeResultat ->
KunneIkkeLeggeTilUtenlandsopphold.AlleVurderingsperioderMåHaSammeResultat
KunneIkkeLeggeTilVilkår.KunneIkkeLeggeTilUtenlandsopphold.MåInneholdeKunEnVurderingsperiode ->
KunneIkkeLeggeTilUtenlandsopphold.MåInneholdeKunEnVurderingsperiode
KunneIkkeLeggeTilVilkår.KunneIkkeLeggeTilUtenlandsopphold.MåVurdereHelePerioden ->
KunneIkkeLeggeTilUtenlandsopphold.MåVurdereHelePerioden
}
}
| 5 | Kotlin | 0 | 1 | fbeb1614c40e0f6fce631d4beb1ba25e2f78ddda | 37,368 | su-se-bakover | MIT License |
MapboxVision/src/main/java/com/mapbox/vision/video/videosource/file/FileVideoDecoder.kt | wayties | 189,125,337 | true | {"Kotlin": 166542, "Shell": 853, "Makefile": 144} | package com.mapbox.vision.video.videosource.file
import android.media.Image
import android.media.MediaCodec
import android.media.MediaExtractor
import android.media.MediaFormat
import com.mapbox.vision.utils.VisionLogger
import com.mapbox.vision.video.videosource.Progress
class FileVideoDecoder(
private val onFrameDecoded: (Image) -> Unit,
private val onFramesEnded: () -> Unit
) : Progress {
companion object {
private const val LOG_FPS_EVERY_MILLIS = 10000
}
private var counterStartTimestamp: Long = 0
private var counterFrames: Int = 0
private var decoder: MediaCodec? = null
private var mediaExtractor: MediaExtractor? = null
private var videoProgressTimestamp = 0L
private var playStartTimestamp = 0L
private fun startDecoder(mimeType: String, trackFormat: MediaFormat) {
decoder = MediaCodec.createDecoderByType(mimeType).apply {
configure(
trackFormat,
null, // no surface, will grab images manually with `decoder.getOutputImage`
null,
0 // 0:decoder 1:encoder
)
setCallback(
object : MediaCodec.Callback() {
override fun onOutputBufferAvailable(codec: MediaCodec, index: Int, info: MediaCodec.BufferInfo) {
onOutputBuffer(codec, index, info)
}
override fun onInputBufferAvailable(codec: MediaCodec, index: Int) {
onInputBuffer(codec, index)
}
override fun onOutputFormatChanged(codec: MediaCodec, format: MediaFormat) {
}
override fun onError(codec: MediaCodec, e: MediaCodec.CodecException) {
VisionLogger.e(e, "FileVideoDecoder", "Error in MediaCodec callback")
}
}
)
start()
}
}
/**
* Plays video, calls [onFrameDecoded] per each frame. Calls [onFramesEnded] when video ends.
*/
fun playVideo(absolutePath: String) {
stopPlayback()
mediaExtractor = MediaExtractor().apply {
setDataSource(absolutePath)
for (i in 0 until trackCount) {
val trackFormat = getTrackFormat(i)
val mimeType = trackFormat.getString(MediaFormat.KEY_MIME) ?: ""
if (mimeType.startsWith("video/")) {
selectTrack(i)
startDecoder(mimeType, trackFormat)
break
}
}
}
playStartTimestamp = System.currentTimeMillis()
counterStartTimestamp = playStartTimestamp
counterFrames = 0
videoProgressTimestamp = 0L
}
fun stopPlayback() {
decoder?.stop()
decoder?.release()
decoder = null
mediaExtractor?.release()
mediaExtractor = null
}
/**
* VideoDecoder should be started to be able to call this method.
*/
override fun setProgress(timestampMillis: Long) {
if (mediaExtractor == null) {
throw IllegalStateException("Can't set progress, video decoding isn't started.")
}
playStartTimestamp = System.currentTimeMillis() - timestampMillis
counterStartTimestamp = System.currentTimeMillis() - timestampMillis
mediaExtractor!!.seekTo(timestampMillis * 1000, MediaExtractor.SEEK_TO_PREVIOUS_SYNC)
videoProgressTimestamp = timestampMillis
}
override fun getProgress(): Long = videoProgressTimestamp
private fun onInputBuffer(codec: MediaCodec, index: Int) {
try {
val inputBuffer = codec.getInputBuffer(index)
val sampleSize = mediaExtractor!!.readSampleData(inputBuffer!!, 0)
if (sampleSize > 0) {
codec.queueInputBuffer(index, 0, sampleSize, mediaExtractor!!.sampleTime, 0)
mediaExtractor!!.advance()
} else {
codec.queueInputBuffer(index, 0, 0, 0, MediaCodec.BUFFER_FLAG_END_OF_STREAM)
onFramesEnded()
}
} catch (e: Exception) {
VisionLogger.e(e, "FileVideoDecoder", "Error in input buffer reading")
}
}
private fun onOutputBuffer(codec: MediaCodec, index: Int, bufferInfo: MediaCodec.BufferInfo) {
try {
if (index >= 0) {
val image = codec.getOutputImage(index)!!
onFrameDecoded(image)
codec.releaseOutputBuffer(
index,
false // true:render to surface
)
videoProgressTimestamp = bufferInfo.presentationTimeUs / 1000
sleepUntilPresentationTime()
countFps()
}
} catch (e: Exception) {
VisionLogger.e(e, "FileVideoDecoder", "Error in output buffer processing")
}
}
private fun sleepUntilPresentationTime() {
val millisFromStart = System.currentTimeMillis() - playStartTimestamp
if (millisFromStart < videoProgressTimestamp) {
try {
Thread.sleep(videoProgressTimestamp - millisFromStart)
} catch (e: InterruptedException) {
VisionLogger.e(e, "FileVideoDecoder")
}
}
}
private fun countFps() {
counterFrames++
val millisPassed = System.currentTimeMillis() - counterStartTimestamp
if (millisPassed > LOG_FPS_EVERY_MILLIS) {
counterStartTimestamp = System.currentTimeMillis()
counterFrames = 0
}
}
}
| 0 | Kotlin | 0 | 0 | e2b7c403085dfdb128a4810a3caa3f4e9b96be6d | 5,668 | mapbox-vision-android | The Unlicense |
app-main/src/main/kotlin/com/github/fj/board/endpoint/v1/reply/UpdateReplyController.kt | oen142 | 449,552,568 | true | {"Kotlin": 584930, "Groovy": 179252, "Java": 88552, "Dart": 11943, "HTML": 1113, "Batchfile": 488, "Shell": 479, "Swift": 404, "Vim Snippet": 314, "Objective-C": 38} | /*
* spring-message-board-demo
* Refer to LICENCE.txt for licence details.
*/
package com.github.fj.board.endpoint.v1.reply
import com.github.fj.board.endpoint.ApiPaths
import com.github.fj.board.endpoint.v1.reply.request.UpdateReplyRequest
import com.github.fj.board.endpoint.v1.reply.response.ReplyInfoResponse
import com.github.fj.board.service.reply.UpdateReplyService
import com.github.fj.board.vo.auth.ClientAuthInfo
import com.github.fj.lib.text.REGEX_UUID
import org.slf4j.LoggerFactory
import org.springframework.http.MediaType
import org.springframework.validation.annotation.Validated
import org.springframework.web.bind.annotation.PathVariable
import org.springframework.web.bind.annotation.RequestBody
import org.springframework.web.bind.annotation.RequestMapping
import org.springframework.web.bind.annotation.RequestMethod
import org.springframework.web.bind.annotation.RestController
import java.util.*
import javax.validation.Valid
import javax.validation.constraints.Pattern
/**
* @author Francesco Jo([email protected])
* @since 04 - Aug - 2020
*/
@RequestMapping(
produces = [MediaType.APPLICATION_JSON_VALUE],
consumes = [MediaType.APPLICATION_JSON_VALUE]
)
@Validated
interface UpdateReplyController {
@RequestMapping(
path = [ApiPaths.REPLY_ID],
method = [RequestMethod.PATCH]
)
fun update(
@Pattern(
regexp = REGEX_UUID,
message = "`replyId` must be in a UUID format."
)
@PathVariable
replyId: String,
@Valid @RequestBody
req: UpdateReplyRequest,
clientInfo: ClientAuthInfo
): ReplyInfoResponse
}
@RestController
internal class UpdateReplyControllerImpl(
private val svc: UpdateReplyService
) : UpdateReplyController {
override fun update(replyId: String, req: UpdateReplyRequest, clientInfo: ClientAuthInfo): ReplyInfoResponse {
LOG.debug("{}: {}", clientInfo.requestLine, req)
val result = svc.update(UUID.fromString(replyId), req, clientInfo)
return ReplyInfoResponse.from(result)
}
companion object {
private val LOG = LoggerFactory.getLogger(UpdateReplyController::class.java)
}
}
| 0 | null | 0 | 0 | 9a3860f780a1c994fcc7f2bed1525a0d73a3fa64 | 2,197 | spring-board-demo | Beerware License |
screen/chirang-note-app/presentation-xml/src/main/java/com/potatomeme/chirang_note_app/presentation_xml/model/ParcelableNote.kt | PotatoMeme | 848,553,898 | false | {"Kotlin": 249418} | package com.potatomeme.chirang_note_app.presentation_xml.model
import android.os.Parcel
import android.os.Parcelable
data class ParcelableNote(
val id: Int = 0,
val title: String?,
val dateTime: String?,
val subtitle: String?,
val noteText: String?,
val imagePath: String?,
val color: String?,
val webLink: String?,
) : Parcelable {
constructor(parcel: Parcel) : this(
parcel.readInt(),
parcel.readString(),
parcel.readString(),
parcel.readString(),
parcel.readString(),
parcel.readString(),
parcel.readString(),
parcel.readString()
)
override fun writeToParcel(parcel: Parcel, flags: Int) {
parcel.writeInt(id)
parcel.writeString(title)
parcel.writeString(dateTime)
parcel.writeString(subtitle)
parcel.writeString(noteText)
parcel.writeString(imagePath)
parcel.writeString(color)
parcel.writeString(webLink)
}
override fun describeContents(): Int {
return 0
}
override fun toString(): String {
return "$title:$dateTime"
}
companion object CREATOR : Parcelable.Creator<ParcelableNote> {
override fun createFromParcel(parcel: Parcel): ParcelableNote {
return ParcelableNote(parcel)
}
override fun newArray(size: Int): Array<ParcelableNote?> {
return arrayOfNulls(size)
}
}
} | 5 | Kotlin | 0 | 0 | 23e1f05f24a97b57d3fe5a4b5852231be8d86bd4 | 1,452 | Android-UI-Test | Apache License 2.0 |
app/src/main/java/com/babestudios/ganbb/common/network/OfflineException.kt | herrbert74 | 321,043,716 | false | null | package com.babestudios.ganbb.common.network
class OfflineException(val obj: Any): Exception() | 0 | Kotlin | 0 | 0 | e18dc6596ebb04ee6373fa4df0524c03644c951e | 95 | GanBreakingBad | MIT License |
app/src/main/java/com/example/bancodigital/data/model/Recharge.kt | DEV-GUS-AGO | 836,022,574 | false | {"Kotlin": 141785} | package com.example.bancodigital.data.model
import android.os.Parcelable
import com.google.firebase.database.FirebaseDatabase
import kotlinx.parcelize.Parcelize
@Parcelize
data class Recharge(
var id: String = "",
var date: Long = 0L,
var amount: Float = 0F,
var number: String = ""
) : Parcelable {
init {
this.id = FirebaseDatabase.getInstance().reference.push().key ?: ""
}
}
| 0 | Kotlin | 0 | 0 | cd8ee534b2152035a81579a019d5f567916775ee | 413 | Banco-Digital | The Unlicense |
knear-sdk/src/main/java/com/knear/android/provider/response/functioncall/transaction/Actions.kt | near | 514,329,257 | false | {"Kotlin": 128819} | package com.knear.android.provider.response.functioncall.transaction
import com.google.gson.annotations.SerializedName
data class Actions (
@SerializedName("FunctionCall" ) var FunctionCall : FunctionCall? = FunctionCall()
)
| 5 | Kotlin | 2 | 20 | 42a2bbeed12257c310a96a4af1ffedda2ea719f1 | 232 | near-api-kotlin | MIT License |
app/src/main/java/au/edu/uts/respfoodie/Classes/MyFirebaseMessagingService.kt | fendylo | 753,162,682 | false | {"Kotlin": 82856} | package au.edu.uts.respfoodie.Classes
import com.google.firebase.messaging.FirebaseMessagingService
import com.google.firebase.messaging.RemoteMessage
class MyFirebaseMessagingService : FirebaseMessagingService() {
override fun onMessageReceived(remoteMessage: RemoteMessage) {
super.onMessageReceived(remoteMessage)
// Handle data payload of FCM messages.
if (remoteMessage.data.isNotEmpty()) {
// Handle the data message here.
}
// Handle notification payload of FCM messages.
remoteMessage.notification?.let {
// Handle the notification message here.
}
}
}
| 0 | Kotlin | 0 | 0 | 8120bfd88dfe5ff0aea7f7dab5330fb626d14e89 | 654 | respfoodie | Apache License 2.0 |
src/main/kotlin/com/github/ferinagy/adventOfCode/aoc2015/2015-11.kt | ferinagy | 432,170,488 | false | {"Kotlin": 768335} | package com.github.ferinagy.adventOfCode.aoc2015
import com.github.ferinagy.adventOfCode.println
import com.github.ferinagy.adventOfCode.readInputText
fun main() {
val input = readInputText(2015, "11-input")
val test1 = readInputText(2015, "11-test1")
println("Part1:")
part1(test1).println()
part1(input).println()
println()
println("Part2:")
part2(test1).println()
part2(input).println()
}
private fun part1(input: String): String {
var pwd = input
while (!meetsPolicy1(pwd)) pwd = pwd.increment()
return pwd
}
private fun part2(input: String): String {
var pwd = part1(input).increment()
while (!meetsPolicy1(pwd)) pwd = pwd.increment()
return pwd
}
private fun meetsPolicy1(pwd: String): Boolean {
if ('i' in pwd || 'o' in pwd || 'l' in pwd) return false
val hasSequence = pwd.windowed(3)
.map { it.toCharArray() }
.any { (a, b, c) -> a.inc() == b && b.inc() == c }
if (!hasSequence) return false
val hasPairs = pwd.windowed(2)
.mapIndexed { index, s -> s to index }
.filter { it.first[0] == it.first[1] }
.let { pairs ->
when {
pairs.size < 2 -> false
pairs.size == 2 -> pairs[1].second - pairs[0].second >= 2
else -> true
}
}
if (!hasPairs) return false
return true
}
private fun String.increment(): String {
if (isEmpty()) return "a"
return if (last() != 'z') {
substring(0, lastIndex) + last().inc()
} else {
substring(0, lastIndex).increment() + 'a'
}
}
| 0 | Kotlin | 0 | 1 | fea30c309aec4eda9574230c7670370468883e32 | 1,615 | advent-of-code | MIT License |
android/src/main/kotlin/io/intheloup/geolocation/helper/AndroidHelper.kt | mit-mit | 128,067,847 | true | {"Dart": 35627, "Kotlin": 15305, "Swift": 14891, "Ruby": 3292, "Objective-C": 535} | // Copyright (c) 2018 Loup Inc.
// Licensed under Apache License v2.0
package io.intheloup.geolocation.helper
import android.Manifest
import android.content.Context
import android.content.pm.PackageManager
import android.os.Build
import android.provider.Settings
import android.support.v4.content.ContextCompat
object AndroidHelper {
fun isLocationPermissionDefinedInManifest(context: Context) = context.packageManager
.getPackageInfo(context.packageName, PackageManager.GET_PERMISSIONS)
.requestedPermissions
.count { it == Manifest.permission.ACCESS_FINE_LOCATION || it == Manifest.permission.ACCESS_COARSE_LOCATION } > 0
fun isLocationEnabled(context: Context): Boolean {
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.KITKAT) {
return true
}
val locationMode = try {
Settings.Secure.getInt(context.contentResolver, Settings.Secure.LOCATION_MODE)
} catch (e: Settings.SettingNotFoundException) {
Settings.Secure.LOCATION_MODE_OFF
}
return locationMode != Settings.Secure.LOCATION_MODE_OFF
}
fun hasLocationPermission(context: Context) =
ContextCompat.checkSelfPermission(context, Manifest.permission.ACCESS_COARSE_LOCATION) == PackageManager.PERMISSION_GRANTED ||
ContextCompat.checkSelfPermission(context, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED
} | 0 | Dart | 0 | 0 | 547583a219cbbb5e0f8820ec2c1cf9980b38089e | 1,469 | geolocation | Apache License 2.0 |
shared/src/commonMain/kotlin/com/gurpreetsk/oofmrlinus/screens/list/ListScreenModel.kt | imGurpreetSK | 835,042,964 | false | {"Kotlin": 30426, "Swift": 677} | package com.gurpreetsk.oofmrlinus.screens.list
import cafe.adriel.voyager.core.model.ScreenModel
import cafe.adriel.voyager.core.model.screenModelScope
import com.gurpreetsk.oofmrlinus.data.MuseumObject
import com.gurpreetsk.oofmrlinus.data.MuseumRepository
import kotlinx.coroutines.flow.SharingStarted
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.stateIn
class ListScreenModel(museumRepository: MuseumRepository) : ScreenModel {
val objects: StateFlow<List<MuseumObject>> =
museumRepository.getObjects()
.stateIn(screenModelScope, SharingStarted.WhileSubscribed(5000), emptyList())
}
| 0 | Kotlin | 0 | 0 | 328eff7abb68b37735f0ef2b6b682b6ddd205b6c | 639 | OofMrLinus | Apache License 2.0 |
app/src/main/java/instamovies/app/presentation/components/RatingBar.kt | mubashirpa | 720,638,343 | false | {"Kotlin": 450402} | package instamovies.app.presentation.components
import android.content.res.ColorStateList
import android.widget.RatingBar
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.size
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.automirrored.outlined.StarHalf
import androidx.compose.material.icons.outlined.Star
import androidx.compose.material.icons.outlined.StarOutline
import androidx.compose.material3.Icon
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.tooling.preview.Preview
import androidx.compose.ui.unit.Dp
import androidx.compose.ui.unit.dp
import androidx.compose.ui.viewinterop.AndroidView
import androidx.core.content.ContextCompat
import instamovies.app.presentation.theme.InstaMoviesTheme
import kotlin.math.ceil
import kotlin.math.floor
import instamovies.app.R.color as Colors
@Composable
fun RatingBar(
rating: Double,
modifier: Modifier = Modifier,
stars: Int = 5,
starColor: Color = MaterialTheme.colorScheme.primary,
starSize: Dp = 20.dp,
) {
val tempRating = rating.coerceAtMost(stars.toDouble())
val filledStars = floor(tempRating).toInt()
val unfilledStars = (stars - ceil(tempRating)).toInt()
val halfStar = !(tempRating.rem(1).equals(0.0))
Row(
modifier = modifier,
verticalAlignment = Alignment.CenterVertically,
) {
repeat(filledStars) {
Icon(
Icons.Outlined.Star,
contentDescription = null,
modifier = Modifier.size(starSize),
tint = starColor,
)
}
if (halfStar) {
Icon(
imageVector = Icons.AutoMirrored.Outlined.StarHalf,
contentDescription = null,
modifier = Modifier.size(starSize),
tint = starColor,
)
}
repeat(unfilledStars) {
Icon(
imageVector = Icons.Outlined.StarOutline,
contentDescription = null,
modifier = Modifier.size(starSize),
tint = Color.DarkGray,
)
}
}
}
@Composable
fun RatingBar(
rating: Double,
onRatingChange: (Float) -> Unit,
modifier: Modifier = Modifier,
isIndicator: Boolean = false,
numStars: Int = 5,
) {
AndroidView(
factory = { context ->
RatingBar(context).apply {
setIsIndicator(isIndicator)
this.numStars = numStars
progressTintList =
ColorStateList.valueOf(ContextCompat.getColor(context, Colors.md_theme_primary))
setOnRatingBarChangeListener { _, rating, _ ->
onRatingChange(rating)
}
}
},
modifier = modifier,
update = { ratingBar ->
ratingBar.rating = rating.toFloat()
},
)
}
@Preview
@Composable
private fun RatingBarPreview() {
InstaMoviesTheme {
Column {
RatingBar(rating = 4.5)
Spacer(modifier = Modifier.height(10.dp))
RatingBar(rating = 3.4, onRatingChange = {})
}
}
}
| 0 | Kotlin | 0 | 1 | fd45c156c6f6f63526946e7c524f9200558fd13a | 3,515 | InstaMovies-v2 | Apache License 2.0 |
backend/src/main/kotlin/ssafy/autonomous/pathfinder/domain/floors/exception/HandleInWallBoundaryException.kt | PathFinder-SSAFY | 643,691,193 | false | null | package ssafy.autonomous.pathfinder.domain.floors.exception
import ssafy.autonomous.pathfinder.global.common.CustomException
import ssafy.autonomous.pathfinder.global.common.ErrorCode
class HandleInWallBoundaryException private constructor(errorCode: ErrorCode) : CustomException(errorCode) {
companion object{
val CODE = FloorsErrorCode.BLOCK_WALL_BOUNDARY_ARRIVAL
}
constructor(): this(CODE)
} | 1 | Kotlin | 3 | 1 | 57e9a94594ff2e3561e62b6c5c9db63cfa4ef203 | 419 | PathFinder | Apache License 2.0 |
app/src/main/java/com/raywenderlich/android/runtracker/MapsActivity.kt | OpungoJacob | 806,434,569 | false | {"Kotlin": 16998} | package com.raywenderlich.android.runtracker
//import android.content.Context
import android.annotation.SuppressLint
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.os.SystemClock
//import androidx.lifecycle.LiveData
//import androidx.lifecycle.MutableLiveData
import com.google.android.gms.maps.CameraUpdateFactory
import com.google.android.gms.maps.GoogleMap
import com.google.android.gms.maps.OnMapReadyCallback
import com.google.android.gms.maps.SupportMapFragment
import com.google.android.gms.maps.model.LatLng
import com.google.android.gms.maps.model.PolylineOptions
//import com.google.android.gms.maps.model.MarkerOptions
import com.raywenderlich.android.runtracker.databinding.ActivityMapsBinding
class MapsActivity : AppCompatActivity(), OnMapReadyCallback {
private lateinit var map: GoogleMap
private lateinit var binding: ActivityMapsBinding
// private val locationProvider = LocationProvider(this)
// private val permissionManager = PermissionsManager(this, locationProvider)
private val presenter = MapPresenter(this)
override fun onCreate(savedInstanceState: Bundle?) {
setTheme(R.style.AppTheme)
super.onCreate(savedInstanceState)
binding = ActivityMapsBinding.inflate(layoutInflater)
setContentView(binding.root)
// Obtain the SupportMapFragment and get notified when the map is ready to be used.
val mapFragment = supportFragmentManager.findFragmentById(R.id.map) as SupportMapFragment
mapFragment.getMapAsync(this)
binding.btnStartStop.setOnClickListener {
if (binding.btnStartStop.text == getString(R.string.start_label)) {
startTracking()
binding.btnStartStop.setText(R.string.stop_label)
} else {
stopTracking()
binding.btnStartStop.setText(R.string.start_label)
}
}
presenter.onViewCreated()
}
/**
* Manipulates the map once available.
* This callback is triggered when the map is ready to be used.
* This is where we can add markers or lines, add listeners or move the camera. In this case,
* we just add a marker near Sydney, Australia.
* If Google Play services is not installed on the device, the user will be prompted to install
* it inside the SupportMapFragment. This method will only be triggered once the user has
* installed Google Play services and returned to the app.
*/
override fun onMapReady(googleMap: GoogleMap) {
map = googleMap
//1
presenter.ui.observe(this) { ui ->
updateUi(ui)
}
//2
presenter.onMapLoaded()
map.uiSettings.isZoomControlsEnabled = true
}
private fun startTracking() {
//1
binding.container.txtPace.text = ""
binding.container.txtDistance.text = ""
//2
binding.container.txtTime.base = SystemClock.elapsedRealtime()
binding.container.txtTime.start()
//3
map.clear()
//4
presenter.startTracking()
}
private fun stopTracking() {
presenter.stopTracking()
binding.container.txtTime.stop()
}
@SuppressLint("MissingPermission")
private fun updateUi(ui: Ui) {
//1
if (ui.currentLocation != null && ui.currentLocation != map.cameraPosition.target) {
map.isMyLocationEnabled = true
map.animateCamera(CameraUpdateFactory.newLatLngZoom(ui.currentLocation, 14f))
}
//2
binding.container.txtDistance.text = ui.formattedDistance
binding.container.txtPace.text = ui.formattedPace
//3
drawRoute(ui.userPath)
}
private fun drawRoute(locations: List<LatLng>) {
val polylineOptions = PolylineOptions()
map.clear()
val points = polylineOptions.points
points.addAll(locations)
map.addPolyline(polylineOptions)
}
}
| 0 | Kotlin | 0 | 0 | 0059d65686c476c8b03360ca4a8bb1c724e9b910 | 3,723 | RunTrackingApp | The Unlicense |
plugin/src/main/kotlin/com/github/triplet/gradle/play/tasks/internal/PlayWorkers.kt | santojon | 196,419,257 | true | {"Kotlin": 127419, "Groovy": 16440, "HTML": 390} | package com.github.triplet.gradle.play.tasks.internal
import com.github.triplet.gradle.play.PlayPublisherExtension
import com.github.triplet.gradle.play.internal.MIME_TYPE_STREAM
import com.github.triplet.gradle.play.internal.RELEASE_NAMES_DEFAULT_NAME
import com.github.triplet.gradle.play.internal.RELEASE_NOTES_DEFAULT_NAME
import com.github.triplet.gradle.play.internal.ReleaseStatus
import com.github.triplet.gradle.play.internal.ResolutionStrategy
import com.github.triplet.gradle.play.internal.has
import com.github.triplet.gradle.play.internal.orNull
import com.github.triplet.gradle.play.internal.readProcessed
import com.github.triplet.gradle.play.internal.releaseStatusOrDefault
import com.github.triplet.gradle.play.internal.resolutionStrategyOrDefault
import com.google.api.client.googleapis.json.GoogleJsonResponseException
import com.google.api.client.googleapis.media.MediaHttpUploader
import com.google.api.client.http.FileContent
import com.google.api.services.androidpublisher.AndroidPublisher
import com.google.api.services.androidpublisher.AndroidPublisherRequest
import com.google.api.services.androidpublisher.model.LocalizedText
import com.google.api.services.androidpublisher.model.Track
import com.google.api.services.androidpublisher.model.TrackRelease
import org.gradle.api.Task
import org.gradle.api.logging.Logger
import org.gradle.api.logging.Logging
import org.gradle.workers.WorkerConfiguration
import java.io.File
import java.io.Serializable
import kotlin.math.roundToInt
internal fun PlayPublishTaskBase.paramsForBase(
config: WorkerConfiguration,
p: Any,
editId: String? = null
) {
val base = PlayWorkerBase.PlayPublishingData(
extension.toSerializable(),
variant.applicationId,
savedEditId,
editId
)
if (this is PlayPublishArtifactBase) {
val artifact = ArtifactWorkerBase.ArtifactPublishingData(
variant.name,
variant.outputs.map { it.versionCode }.first(),
releaseNotesDir,
consoleNamesDir,
releaseName,
mappingFile
)
config.params(p, artifact, base)
} else {
config.params(p, base)
}
}
internal abstract class PlayWorkerBase(private val data: PlayPublishingData) : Runnable {
protected val extension = data.extension
protected val publisher = extension.buildPublisher()
protected val appId = data.applicationId
protected val editId by lazy {
data.editId ?: publisher.getOrCreateEditId(appId, data.savedEditId)
}
protected val edits: AndroidPublisher.Edits = publisher.edits()
protected val logger: Logger = Logging.getLogger(Task::class.java)
protected fun commit() = publisher.commit(extension, appId, editId, data.savedEditId)
protected fun <T> AndroidPublisherRequest<T>.trackUploadProgress(
thing: String
): AndroidPublisherRequest<T> {
mediaHttpUploader?.setProgressListener {
@Suppress("NON_EXHAUSTIVE_WHEN")
when (it.uploadState) {
MediaHttpUploader.UploadState.INITIATION_STARTED ->
println("Starting $thing upload")
MediaHttpUploader.UploadState.MEDIA_IN_PROGRESS ->
println("Uploading $thing: ${(it.progress * 100).roundToInt()}% complete")
MediaHttpUploader.UploadState.MEDIA_COMPLETE ->
println("${thing.capitalize()} upload complete")
}
}
return this
}
internal data class PlayPublishingData(
val extension: PlayPublisherExtension.Serializable,
val applicationId: String,
val savedEditId: File?,
val editId: String?
) : Serializable
}
internal abstract class ArtifactWorkerBase(
private val artifact: ArtifactPublishingData,
private val play: PlayPublishingData
) : PlayWorkerBase(play) {
protected var commit = true
final override fun run() {
upload()
if (commit) commit()
}
abstract fun upload()
protected fun updateTracks(editId: String, versions: List<Long>) {
val track = if (play.savedEditId?.orNull() != null) {
edits.tracks().get(appId, editId, extension.track).execute().apply {
releases = if (releases.isNullOrEmpty()) {
listOf(TrackRelease().applyChanges(versions))
} else {
releases.map {
if (it.status == extension.releaseStatusOrDefault.publishedName) {
it.applyChanges(it.versionCodes.orEmpty() + versions)
} else {
it
}
}
}
}
} else if (extension.releaseStatusOrDefault == ReleaseStatus.IN_PROGRESS) {
edits.tracks().get(appId, editId, extension.track).execute().apply {
val keep = releases.orEmpty().filter {
it.status == ReleaseStatus.COMPLETED.publishedName ||
it.status == ReleaseStatus.DRAFT.publishedName
}
releases = keep + listOf(TrackRelease().applyChanges(versions))
}
} else {
Track().apply {
track = extension.track
releases = listOf(TrackRelease().applyChanges(versions))
}
}
println("Updating ${track.releases.map { it.status }.distinct()} release " +
"($appId:${track.releases.flatMap { it.versionCodes.orEmpty() }}) " +
"in track '${track.track}'")
edits.tracks().update(appId, editId, extension.track, track).execute()
}
protected fun TrackRelease.applyChanges(
versionCodes: List<Long>? = null,
updateStatus: Boolean = true,
updateFraction: Boolean = true,
updateConsoleName: Boolean = true
): TrackRelease {
versionCodes?.let { this.versionCodes = it }
if (updateStatus) status = extension.releaseStatus
if (updateConsoleName) {
name = if (artifact.transientConsoleName == null) {
val file = File(artifact.consoleNamesDir, "${extension.track}.txt").orNull()
?: File(artifact.consoleNamesDir, RELEASE_NAMES_DEFAULT_NAME).orNull()
file?.readProcessed()?.lines()?.firstOrNull()
} else {
artifact.transientConsoleName
}
}
val releaseNotes = artifact.releaseNotesDir?.listFiles().orEmpty().mapNotNull { locale ->
val file = File(locale, "${extension.track}.txt").orNull() ?: run {
File(locale, RELEASE_NOTES_DEFAULT_NAME).orNull() ?: return@mapNotNull null
}
LocalizedText().apply {
language = locale.name
text = file.readProcessed()
}
}
if (releaseNotes.isNotEmpty()) {
val existingReleaseNotes = this.releaseNotes.orEmpty()
this.releaseNotes = if (existingReleaseNotes.isEmpty()) {
releaseNotes
} else {
val merged = releaseNotes.toMutableList()
for (existing in existingReleaseNotes) {
if (merged.none { it.language == existing.language }) merged += existing
}
merged
}
}
if (updateFraction) {
val status = extension.releaseStatus
userFraction = extension.userFraction.takeIf {
status == ReleaseStatus.IN_PROGRESS.publishedName ||
status == ReleaseStatus.HALTED.publishedName
}
}
return this
}
protected fun handleUploadFailures(
e: GoogleJsonResponseException,
file: File
): Nothing? = if (e has "apkUpgradeVersionConflict" || e has "apkNoUpgradePath") {
when (extension.resolutionStrategyOrDefault) {
ResolutionStrategy.AUTO -> throw IllegalStateException(
"Concurrent uploads for variant ${artifact.variantName} (version code " +
"${artifact.versionCode} already used). Make sure to synchronously " +
"upload your APKs such that they don't conflict. If this problem " +
"persists, delete your drafts in the Play Console's artifact library.",
e
)
ResolutionStrategy.FAIL -> throw IllegalStateException(
"Version code ${artifact.versionCode} is too low or has already been used " +
"for variant ${artifact.variantName}.",
e
)
ResolutionStrategy.IGNORE -> println(
"Ignoring artifact ($file) for version code ${artifact.versionCode}")
}
null
} else {
throw e
}
protected fun handleArtifactDetails(editId: String, versionCode: Int) {
val file = artifact.mappingFile
if (file != null && file.length() > 0) {
val mapping = FileContent(MIME_TYPE_STREAM, file)
edits.deobfuscationfiles()
.upload(appId, editId, versionCode, "proguard", mapping)
.trackUploadProgress("mapping file")
.execute()
}
}
internal data class ArtifactPublishingData(
val variantName: String,
val versionCode: Int,
val releaseNotesDir: File?,
val consoleNamesDir: File?,
val transientConsoleName: String?,
val mappingFile: File?
) : Serializable
}
| 0 | Kotlin | 0 | 0 | 94b3b2caa39cd323b9b4ed0b7d76acdd95a8d52d | 9,837 | gradle-play-publisher | MIT License |
app/src/main/java/com/example/spygamers/services/authentication/AuthenticationCheckResponse.kt | Juicy-Lemonberry | 748,985,682 | false | {"Kotlin": 123050} | package com.example.spygamers.services.authentication
import com.example.spygamers.services.ResponseContract
import com.google.gson.annotations.SerializedName
import java.util.Date
data class AuthenticationCheckResponse(
override val status: String,
val result: FullAccountData
) : ResponseContract
data class FullAccountData(
val id: Int,
val username: String,
val email: String,
@SerializedName("created_at")
val createdAt: Date,
@SerializedName("timezone_code")
val timezoneCode: String
) | 0 | Kotlin | 2 | 0 | 78deb69c4b017042b3a6779a0d6d48bdd131ea43 | 532 | SpyGamers-App | MIT License |
app/src/main/java/com/breezefieldkrishnatea/features/meetinglist/model/MeetingListResponseModel.kt | DebashisINT | 796,590,044 | false | {"Kotlin": 14426399, "Java": 1021853} | package com.breezefieldkrishnatea.features.meetinglist.model
import com.breezefieldkrishnatea.base.BaseResponse
import com.breezefieldkrishnatea.features.location.model.MeetingDurationDataModel
import java.io.Serializable
/**
* Created by Saikat on 21-01-2020.
*/
class MeetingListResponseModel : BaseResponse(), Serializable {
var meeting_list: ArrayList<MeetingDurationDataModel>? = null
} | 0 | Kotlin | 0 | 0 | 4a1bcf05788be9bb1afdbf5922e9ec38d7f60f84 | 399 | HareKrishnaEntp | Apache License 2.0 |
auth-redis/src/main/kotlin/cn/spark2fire/auth/config/RedisTokenConfiguration.kt | spark2fire | 332,371,299 | false | null | package cn.spark2fire.auth.config
import cn.spark2fire.auth.token.RedisTokenService
import cn.spark2fire.auth.token.TokenService
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean
import org.springframework.context.annotation.Bean
import org.springframework.context.annotation.Configuration
import org.springframework.data.redis.core.StringRedisTemplate
@Configuration(proxyBeanMethods = false)
class RedisTokenConfiguration {
@Bean
@ConditionalOnMissingBean
fun tokenService(redisTemplate: StringRedisTemplate, properties: AuthProperties): TokenService = RedisTokenService(redisTemplate, properties)
}
| 0 | Kotlin | 0 | 0 | 9c506222ca44861872e7d9e908d8d256896c11ea | 647 | alberti | MIT License |
app/src/main/java/com/breezebppoddar/features/viewAllOrder/interf/ColorListOnCLick.kt | DebashisINT | 518,335,697 | false | {"Kotlin": 14689181, "Java": 1021110} | package com.breezebppoddar.features.viewAllOrder.interf
import com.breezebppoddar.app.domain.NewOrderGenderEntity
import com.breezebppoddar.features.viewAllOrder.model.ProductOrder
interface ColorListOnCLick {
fun colorListOnCLick(size_qty_list: ArrayList<ProductOrder>, adpPosition:Int)
} | 0 | Kotlin | 0 | 0 | 297531612f36f84abcf33edf6809dacc55c3ac99 | 295 | BPPODDARHOSPITAL | Apache License 2.0 |
app/src/main/java/com/breezebppoddar/features/viewAllOrder/interf/ColorListOnCLick.kt | DebashisINT | 518,335,697 | false | {"Kotlin": 14689181, "Java": 1021110} | package com.breezebppoddar.features.viewAllOrder.interf
import com.breezebppoddar.app.domain.NewOrderGenderEntity
import com.breezebppoddar.features.viewAllOrder.model.ProductOrder
interface ColorListOnCLick {
fun colorListOnCLick(size_qty_list: ArrayList<ProductOrder>, adpPosition:Int)
} | 0 | Kotlin | 0 | 0 | 297531612f36f84abcf33edf6809dacc55c3ac99 | 295 | BPPODDARHOSPITAL | Apache License 2.0 |
apigateway/src/main/java/it/try2catch/spingcloudgateway/api/ApiApp.kt | simonetallevi | 262,672,048 | false | null | package it.try2catch.spingcloudgateway.api
import org.springframework.boot.SpringApplication
import org.springframework.boot.autoconfigure.SpringBootApplication
@SpringBootApplication
class ApiApp {
companion object {
@JvmStatic
fun main(args: Array<String>) {
SpringApplication.run(ApiApp::class.java, *args)
}
}
}
| 0 | Kotlin | 0 | 0 | 350cc154f85482a15433a126b37338b40a309069 | 363 | spring-cloud-gateway | MIT License |
vgscollect/src/main/java/com/verygoodsecurity/vgscollect/core/storage/FieldDependencyObserver.kt | verygoodsecurity | 273,198,410 | false | {"Kotlin": 1129139, "Python": 210} | package com.verygoodsecurity.vgscollect.core.storage
import com.verygoodsecurity.vgscollect.core.model.state.VGSFieldState
/** @suppress */
internal interface FieldDependencyObserver {
fun onRefreshState(state: VGSFieldState)
fun onStateUpdate(state: VGSFieldState)
} | 5 | Kotlin | 8 | 8 | 2890032ba73d7d63967610357a8b898b4d6b2832 | 277 | vgs-collect-android | MIT License |
app/src/main/kotlin/me/tmonteiro/kacn/playground/di/NetworkModule.kt | TiagoOlivMonteiro | 199,861,969 | false | null | package me.tmonteiro.kacn.playground.di
import me.tmonteiro.kacn.playground.api.PlaygroundAPI
import me.tmonteiro.kacn.playground.factory.MoshiFactory
import me.tmonteiro.kacn.playground.factory.OkHttpFactory
import me.tmonteiro.kacn.playground.factory.PlaygroundAPIFactory
import me.tmonteiro.kacn.playground.factory.RetrofitFactory
import org.koin.android.ext.koin.androidContext
import org.koin.dsl.module
val networkModule = module {
single { OkHttpFactory.build(androidContext()) }
single { MoshiFactory.build() }
single { RetrofitFactory.build(PlaygroundAPI.API_URL, get(), get()) }
single { PlaygroundAPIFactory.build(get()) }
} | 0 | Kotlin | 0 | 0 | 9181da1430ab13b53a493ae7ce2ed3ef4755ce00 | 653 | kotlin-architecture-component-navigation-playground | Apache License 2.0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.