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/myproject/Main.kt | yngvark | 320,208,902 | false | null | package myproject
import com.yngvark.robothelper.RobotHelper
import java.awt.Robot
import java.awt.event.KeyEvent
import java.io.File
val robot = RobotHelper(Robot())
class ClassUsedJustToGetExecutableFilename {}
fun main(args: Array<String>) {
if (args.isEmpty()) {
val name = File(
ClassUsedJustToGetExecutableFilename::class.java.getProtectionDomain()
.codeSource.location.path
).name
println("USAGE: $name <AWS account ID>")
return
}
for (arg in args) {
println("Arg: $arg")
}
val accountId = args[args.size - 1]
println("Logging in to AWS account: $accountId")
login(accountId)
// hello()
}
private fun login(accountId: String) {
robot
.pressAndRelease(KeyEvent.VK_CONTROL, KeyEvent.VK_F)
.type(accountId)
.pressAndRelease(KeyEvent.VK_ENTER)
.pressAndRelease(KeyEvent.VK_ESCAPE)
.pressAndRelease(KeyEvent.VK_TAB)
.pressAndRelease(KeyEvent.VK_SPACE)
.pressAndRelease(KeyEvent.VK_TAB)
.pressAndRelease(
KeyEvent.VK_ENTER
)
}
private fun hello() {
robot.sleep(200)
.type("HELLO2")
}
| 0 | Kotlin | 0 | 0 | 58f4919af31678fedbb46633a3d64294b5b4443c | 1,191 | aws-console-signin-robot | MIT License |
src/main/kotlin/com/sandrabot/sandra/managers/RedisManager.kt | sandrabot | 121,549,855 | false | null | /*
* Copyright 2017-2022 <NAME> and <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.sandrabot.sandra.managers
import com.sandrabot.sandra.config.RedisConfig
import redis.clients.jedis.Jedis
import redis.clients.jedis.JedisPool
import redis.clients.jedis.JedisPoolConfig
/**
* This class provides a means of communication with a redis server.
*/
class RedisManager(config: RedisConfig) {
private val pool = JedisPool(
JedisPoolConfig(), config.host, config.port,
config.timeout, config.password, config.database
)
val resource: Jedis
get() = pool.resource
operator fun get(key: String): String? = resource.use { it.get(key) }
operator fun set(key: String, value: String) {
resource.use { it.set(key, value) }
}
fun del(key: String) {
resource.use { it.del(key) }
}
fun shutdown() {
pool.destroy()
}
}
| 1 | null | 3 | 5 | 43d363209fb1e0d933dae9d9c8475c62ae3e625a | 1,434 | sandra | Apache License 2.0 |
bookmark/domain/src/main/java/tickmarks/bookmark/domain/BookmarkRepository.kt | annypatel | 137,336,539 | false | {"Kotlin": 80750, "Shell": 600} | package tickmarks.bookmark.domain
import io.reactivex.Completable
/**
* Repository for managing bookmarks.
*/
interface BookmarkRepository {
/**
* To save a bookmark.
*
* @param bookmark The bookmark to be saved.
*/
fun saveBookmark(bookmark: Bookmark): Completable
}
| 0 | Kotlin | 0 | 9 | 5ad30bca0329bd79334748baf228d9a0f1ba4dbb | 301 | tickmarks | Apache License 2.0 |
src/main/docsite/complex/masterdetails.kt | anonhyme | 45,768,170 | true | {"JavaScript": 1784835, "Kotlin": 328451, "HTML": 2312} | package complex
import net.yested.bootstrap.Grid
import net.yested.bootstrap.Column
import bootstrap.Person
import net.yested.div
import net.yested.Div
import net.yested.bootstrap.btsButton
import net.yested.bootstrap.ButtonSize
import net.yested.bootstrap.Form
import net.yested.with
import net.yested.bootstrap.Validator
import net.yested.bootstrap.Select
import net.yested.ButtonType
import net.yested.bootstrap.ButtonLook
import net.yested.bootstrap.row
import net.yested.bootstrap.pageHeader
import net.yested.bootstrap.Medium
import net.yested.Fade
import net.yested.bootstrap.FormStyle
import net.yested.bootstrap.Small
import net.yested.Component
import org.w3c.dom.HTMLElement
import java.util.ArrayList
import net.yested.bootstrap.InputField
import net.yested.compareByValue
import net.yested.bootstrap.StringInputField
enum class Continent(val label:String) {
EUROPE("Europe"),
AMERICA("America"),
ASIA("Asia"),
AFRICA("Africa")
}
data class City(val name:String, val continent:Continent)
class DetailScreen(
val editedCity:City?,
val saveHandler:(City)->Unit,
val cancelHandler:()->Unit) : Component {
val textInput = StringInputField(placeholder = "City name")
val validator = Validator(inputElement = textInput, errorText = "Name is mandatory", validator = { it.size > 3})
val select = Select(options = Continent.values().toList(), renderer = { it.label })
fun save() {
if (validator.isValid()) {
saveHandler(City(textInput.data, select.selectedItems.first()))
}
}
init {
if (editedCity != null) {
textInput.data = editedCity.name
select.selectedItems = listOf(editedCity.continent)
}
}
override val element: HTMLElement
get() = (Form(formStyle = FormStyle.HORIZONTAL, labelDef = Small(4), inputDef = Small(8)) with {
item(label = { +"City name"}, validator = validator) {
+textInput
}
item(label = { +"Continent" }) {
+select
}
item(label = {}) {
div {
btsButton(label = { +"Save" }, look = ButtonLook.PRIMARY, type = ButtonType.SUBMIT, onclick = { save() })
nbsp()
btsButton(label = { +"Cancel" }, onclick = { cancelHandler() })
}
}
}).element
}
class MasterScreen(val list:ArrayList<City>, val editHandler:Function1<City?, Unit>) : Component {
val grid =
Grid(columns = arrayOf(
Column(label = { +"City name"},
render = { +it.name }, sortFunction = compareByValue<City, String> { it.name },
defaultSort = true),
Column(label = { +"Continent"},
render = { +it.continent.label},
sortFunction = compareByValue<City, String> { it.continent.label }),
Column(label = { },
render = { city -> btsButton(size = ButtonSize.EXTRA_SMALL, label = { +"Edit" }, onclick = { editHandler(city) })},
sortFunction = compareByValue<City, String> { it.name }),
Column(label = { },
render = { city -> btsButton(size = ButtonSize.EXTRA_SMALL, look = ButtonLook.DANGER, label = { +"Delete" }, onclick = { deleteCity(city) })},
sortFunction = compareByValue<City, String> { it.name })));
fun deleteCity(city: City) {
list.remove(city)
grid.list = list
}
init {
grid.list = list
}
override val element: HTMLElement
get() = (Div() with {
+grid
btsButton(label = { +"Add" }, onclick = { editHandler(null) })
}).element
}
class MasterDetailDemo(): Component {
val placeholder = Div()
val list = arrayListOf(
City("Prague", Continent.EUROPE),
City("London", Continent.EUROPE),
City("New York", Continent.AMERICA))
fun saveCity(originalCity: City?, newCity: City) {
if (originalCity != null) {
list.remove(originalCity)
}
list.add(newCity)
displayMasterScreen()
}
fun editCity(city: City? = null) {
placeholder.setChild(DetailScreen(editedCity = city, saveHandler = { saveCity(city, it) }, cancelHandler = { displayMasterScreen() }), Fade())
}
fun displayMasterScreen() {
placeholder.setChild(MasterScreen(list, { editCity(it) }), Fade())
}
init {
displayMasterScreen()
}
override val element: HTMLElement
get() = (Div() with {
+placeholder
}).element
}
fun masterDetail() =
div {
row {
col(Medium(12)) {
pageHeader { h3 { +"Master / Detail" } }
}
}
row {
col(Medium(6)) {
h4 { +"Demo" }
+MasterDetailDemo()
}
col(Medium(6)) {
h4 { +"Source code"}
a(href = "https://github.com/jean79/yested/blob/master/src/main/docsite/complex/masterdetails.kt") {+"Source code is deployed on GitHub"}
}
}
} | 0 | JavaScript | 0 | 0 | 167d03fde647db96cfd9d906cd994245de91cd25 | 5,327 | yested | MIT License |
src/main/docsite/complex/masterdetails.kt | anonhyme | 45,768,170 | true | {"JavaScript": 1784835, "Kotlin": 328451, "HTML": 2312} | package complex
import net.yested.bootstrap.Grid
import net.yested.bootstrap.Column
import bootstrap.Person
import net.yested.div
import net.yested.Div
import net.yested.bootstrap.btsButton
import net.yested.bootstrap.ButtonSize
import net.yested.bootstrap.Form
import net.yested.with
import net.yested.bootstrap.Validator
import net.yested.bootstrap.Select
import net.yested.ButtonType
import net.yested.bootstrap.ButtonLook
import net.yested.bootstrap.row
import net.yested.bootstrap.pageHeader
import net.yested.bootstrap.Medium
import net.yested.Fade
import net.yested.bootstrap.FormStyle
import net.yested.bootstrap.Small
import net.yested.Component
import org.w3c.dom.HTMLElement
import java.util.ArrayList
import net.yested.bootstrap.InputField
import net.yested.compareByValue
import net.yested.bootstrap.StringInputField
enum class Continent(val label:String) {
EUROPE("Europe"),
AMERICA("America"),
ASIA("Asia"),
AFRICA("Africa")
}
data class City(val name:String, val continent:Continent)
class DetailScreen(
val editedCity:City?,
val saveHandler:(City)->Unit,
val cancelHandler:()->Unit) : Component {
val textInput = StringInputField(placeholder = "City name")
val validator = Validator(inputElement = textInput, errorText = "Name is mandatory", validator = { it.size > 3})
val select = Select(options = Continent.values().toList(), renderer = { it.label })
fun save() {
if (validator.isValid()) {
saveHandler(City(textInput.data, select.selectedItems.first()))
}
}
init {
if (editedCity != null) {
textInput.data = editedCity.name
select.selectedItems = listOf(editedCity.continent)
}
}
override val element: HTMLElement
get() = (Form(formStyle = FormStyle.HORIZONTAL, labelDef = Small(4), inputDef = Small(8)) with {
item(label = { +"City name"}, validator = validator) {
+textInput
}
item(label = { +"Continent" }) {
+select
}
item(label = {}) {
div {
btsButton(label = { +"Save" }, look = ButtonLook.PRIMARY, type = ButtonType.SUBMIT, onclick = { save() })
nbsp()
btsButton(label = { +"Cancel" }, onclick = { cancelHandler() })
}
}
}).element
}
class MasterScreen(val list:ArrayList<City>, val editHandler:Function1<City?, Unit>) : Component {
val grid =
Grid(columns = arrayOf(
Column(label = { +"City name"},
render = { +it.name }, sortFunction = compareByValue<City, String> { it.name },
defaultSort = true),
Column(label = { +"Continent"},
render = { +it.continent.label},
sortFunction = compareByValue<City, String> { it.continent.label }),
Column(label = { },
render = { city -> btsButton(size = ButtonSize.EXTRA_SMALL, label = { +"Edit" }, onclick = { editHandler(city) })},
sortFunction = compareByValue<City, String> { it.name }),
Column(label = { },
render = { city -> btsButton(size = ButtonSize.EXTRA_SMALL, look = ButtonLook.DANGER, label = { +"Delete" }, onclick = { deleteCity(city) })},
sortFunction = compareByValue<City, String> { it.name })));
fun deleteCity(city: City) {
list.remove(city)
grid.list = list
}
init {
grid.list = list
}
override val element: HTMLElement
get() = (Div() with {
+grid
btsButton(label = { +"Add" }, onclick = { editHandler(null) })
}).element
}
class MasterDetailDemo(): Component {
val placeholder = Div()
val list = arrayListOf(
City("Prague", Continent.EUROPE),
City("London", Continent.EUROPE),
City("New York", Continent.AMERICA))
fun saveCity(originalCity: City?, newCity: City) {
if (originalCity != null) {
list.remove(originalCity)
}
list.add(newCity)
displayMasterScreen()
}
fun editCity(city: City? = null) {
placeholder.setChild(DetailScreen(editedCity = city, saveHandler = { saveCity(city, it) }, cancelHandler = { displayMasterScreen() }), Fade())
}
fun displayMasterScreen() {
placeholder.setChild(MasterScreen(list, { editCity(it) }), Fade())
}
init {
displayMasterScreen()
}
override val element: HTMLElement
get() = (Div() with {
+placeholder
}).element
}
fun masterDetail() =
div {
row {
col(Medium(12)) {
pageHeader { h3 { +"Master / Detail" } }
}
}
row {
col(Medium(6)) {
h4 { +"Demo" }
+MasterDetailDemo()
}
col(Medium(6)) {
h4 { +"Source code"}
a(href = "https://github.com/jean79/yested/blob/master/src/main/docsite/complex/masterdetails.kt") {+"Source code is deployed on GitHub"}
}
}
} | 0 | JavaScript | 0 | 0 | 167d03fde647db96cfd9d906cd994245de91cd25 | 5,327 | yested | MIT License |
tgbotapi.api/src/commonMain/kotlin/dev/inmo/tgbotapi/extensions/api/stickers/AddStickerToSet.kt | InsanusMokrassar | 163,152,024 | false | null | package dev.inmo.tgbotapi.extensions.api.stickers
import dev.inmo.tgbotapi.bot.TelegramBot
import dev.inmo.tgbotapi.requests.abstracts.InputFile
import dev.inmo.tgbotapi.requests.stickers.AddStickerToSet
import dev.inmo.tgbotapi.requests.stickers.InputSticker
import dev.inmo.tgbotapi.types.StickerFormat
import dev.inmo.tgbotapi.types.StickerSetName
import dev.inmo.tgbotapi.types.StickerType
import dev.inmo.tgbotapi.types.chat.CommonUser
import dev.inmo.tgbotapi.types.UserId
import dev.inmo.tgbotapi.types.stickers.MaskPosition
import dev.inmo.tgbotapi.types.stickers.StickerSet
public suspend fun TelegramBot.addStickerToSet(
userId: UserId,
stickerSetName: StickerSetName,
inputSticker: InputSticker
): Boolean = execute(
AddStickerToSet(userId, stickerSetName, inputSticker)
)
public suspend fun TelegramBot.addStickerToSet(
userId: UserId,
stickerSetName: String,
inputSticker: InputSticker
): Boolean = addStickerToSet(userId, StickerSetName(stickerSetName), inputSticker)
public suspend fun TelegramBot.addStickerToSet(
userId: UserId,
stickerSet: StickerSet,
sticker: InputSticker
): Boolean = addStickerToSet(
userId,
stickerSet.name,
sticker
)
public suspend fun TelegramBot.addStickerToSet(
userId: UserId,
stickerSet: StickerSet,
sticker: InputFile,
format: StickerFormat,
emojis: List<String>,
keywords: List<String> = emptyList()
): Boolean = addStickerToSet(
userId,
stickerSet,
when (stickerSet.stickerType) {
StickerType.CustomEmoji -> InputSticker.WithKeywords.CustomEmoji(
sticker,
format,
emojis,
keywords
)
StickerType.Mask -> InputSticker.Mask(
sticker,
format,
emojis
)
StickerType.Regular -> InputSticker.WithKeywords.Regular(
sticker,
format,
emojis,
keywords
)
is StickerType.Unknown -> error("Unable to create sticker to the set with type ${stickerSet.stickerType}")
}
)
public suspend fun TelegramBot.addStickerToSet(
userId: UserId,
stickerSet: StickerSet,
sticker: InputFile,
format: StickerFormat,
emojis: List<String>,
maskPosition: MaskPosition? = null
): Boolean = addStickerToSet(
userId,
stickerSet.name,
when (stickerSet.stickerType) {
StickerType.CustomEmoji -> InputSticker.WithKeywords.CustomEmoji(
sticker,
format,
emojis,
emptyList()
)
StickerType.Mask -> InputSticker.Mask(
sticker,
format,
emojis,
maskPosition
)
StickerType.Regular -> InputSticker.WithKeywords.Regular(
sticker,
format,
emojis,
emptyList()
)
is StickerType.Unknown -> error("Unable to create sticker to the set with type ${stickerSet.stickerType}")
}
)
public suspend fun TelegramBot.addStickerToSet(
user: CommonUser,
stickerSet: StickerSet,
sticker: InputSticker
): Boolean = addStickerToSet(
user.id,
stickerSet.name,
sticker
)
public suspend fun TelegramBot.addStickerToSet(
user: CommonUser,
stickerSet: StickerSet,
sticker: InputFile,
format: StickerFormat,
emojis: List<String>,
keywords: List<String> = emptyList()
): Boolean = addStickerToSet(
user.id, stickerSet, sticker, format, emojis, keywords
)
public suspend fun TelegramBot.addStickerToSet(
user: CommonUser,
stickerSet: StickerSet,
sticker: InputFile,
format: StickerFormat,
emojis: List<String>,
maskPosition: MaskPosition? = null
): Boolean = addStickerToSet(
user.id, stickerSet, sticker, format, emojis, maskPosition
)
| 8 | null | 29 | 358 | 482c375327b7087699a4cb8bb06cb09869f07630 | 3,815 | ktgbotapi | Apache License 2.0 |
src/main/kotlin/com/kcrud/api/graphql/frameworks/kgraphql/schema/employee/EmployeeMutations.kt | perracolabs | 682,128,013 | false | null | /*
* Copyright (c) 2023-Present Perraco Labs. All rights reserved.
* This work is licensed under the terms of the MIT license.
* For a copy, see <https://opensource.org/licenses/MIT>
*/
package kcrud.server.domain.employee.graphql.kgraphql
import com.apurebase.kgraphql.Context
import com.apurebase.kgraphql.schema.dsl.SchemaBuilder
import kcrud.base.graphql.kgraphql.annotation.KGraphQLAPI
import kcrud.base.graphql.kgraphql.utils.GraphQLError
import kcrud.server.domain.employee.entities.EmployeeEntity
import kcrud.server.domain.employee.entities.EmployeeRequest
import kcrud.server.domain.employee.exceptions.EmployeeError
import kcrud.server.domain.employee.graphql.utils.EmployeeServiceResolver
import kcrud.server.domain.employee.service.EmployeeService
import org.koin.core.component.KoinComponent
import java.util.*
/**
* Employee mutation definitions.
*
* @param schemaBuilder The SchemaBuilder instance for configuring the schema.
*/
@KGraphQLAPI
internal class EmployeeMutations(private val schemaBuilder: SchemaBuilder) : KoinComponent {
/**
* Configures input types for mutations.
*/
fun configureInputs(): EmployeeMutations {
schemaBuilder.apply {
inputType<EmployeeRequest> {
name = "Input type definition for Employee."
}
}
return this
}
/**
* Configures mutation resolvers to modify data.
*/
fun configureMutations(): EmployeeMutations {
schemaBuilder.apply {
mutation("createEmployee") {
description = "Creates a new employee."
resolver { context: Context, employee: EmployeeRequest ->
val service: EmployeeService = EmployeeServiceResolver.get(context = context)
service.create(employeeRequest = employee)
}
}
mutation("updateEmployee") {
description = "Updates an existing employee."
resolver { context: Context, employeeId: UUID, employee: EmployeeRequest ->
val service: EmployeeService = EmployeeServiceResolver.get(context = context)
val updatedEmployee: EmployeeEntity? = service.update(employeeId = employeeId, employeeRequest = employee)
updatedEmployee
?: GraphQLError.of(error = EmployeeError.EmployeeNotFound(employeeId = employeeId))
}
}
mutation("deleteEmployee") {
description = "Deletes an existing employee."
resolver { context: Context, employeeId: UUID ->
val service: EmployeeService = EmployeeServiceResolver.get(context = context)
service.delete(employeeId = employeeId)
}
}
mutation("deleteAllEmployees") {
description = "Deletes all existing employees."
resolver { context: Context ->
val service: EmployeeService = EmployeeServiceResolver.get(context = context)
service.deleteAll()
}
}
}
return this
}
}
| 0 | null | 0 | 2 | db1a4763931e5aa02b72a2b58dae423737b11187 | 3,190 | Kcrud | MIT License |
app/src/main/java/com/gtech/prodialog/MainActivity.kt | GtechGovind | 705,322,613 | false | {"Kotlin": 16531} | package com.gtech.prodialog
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import com.gtech.pro_dialog.ProDialog
import com.gtech.prodialog.databinding.ActivityMainBinding
class MainActivity : AppCompatActivity() {
private lateinit var binding: ActivityMainBinding
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = ActivityMainBinding.inflate(layoutInflater)
setContentView(binding.root)
initLayout()
}
private fun initLayout() {
binding.successDialog.setOnClickListener {
ProDialog.build(this)
.type(ProDialog.TYPE.SUCCESS)
.title("Success Dialog")
.position(ProDialog.POSITIONS.CENTER)
.description("Your task was completed successfully.")
.onPositive("OK") {
// Positive button action
}
.show()
}
binding.errorDialog.setOnClickListener {
ProDialog.build(this)
.type(ProDialog.TYPE.ERROR)
.title("Success Dialog")
.position(ProDialog.POSITIONS.CENTER)
.description("Your task was completed successfully.")
.onPositive("OK") {
// Positive button action
}
.show()
}
binding.infoDialog.setOnClickListener {
ProDialog.build(this)
.type(ProDialog.TYPE.INFO)
.title("Success Dialog")
.position(ProDialog.POSITIONS.CENTER)
.description("Your task was completed successfully.")
.onPositive("OK") {
// Positive button action
}
.show()
}
binding.alertDialog.setOnClickListener {
ProDialog.build(this)
.type(ProDialog.TYPE.ALERT)
.title("Success Dialog")
.position(ProDialog.POSITIONS.CENTER)
.description("Your task was completed successfully.")
.onPositive("OK") {
// Positive button action
}
.show()
}
}
} | 0 | Kotlin | 0 | 0 | f583a0ee2850418dedb73c10f115d4e0e0ca3ffe | 2,280 | ProDialog | MIT License |
app/src/main/java/dev/tcode/thinmp/view/screen/PlaylistDetailScreen.kt | tcode-dev | 392,735,283 | false | null | package dev.tcode.thinmp.view.screen
import androidx.compose.foundation.background
import androidx.compose.foundation.gestures.detectTapGestures
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.lazy.grid.GridItemSpan
import androidx.compose.foundation.lazy.grid.itemsIndexed
import androidx.compose.material3.MaterialTheme
import androidx.compose.runtime.Composable
import androidx.compose.runtime.collectAsState
import androidx.compose.runtime.getValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Brush
import androidx.compose.ui.input.pointer.pointerInput
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.unit.dp
import androidx.constraintlayout.compose.ConstraintLayout
import androidx.lifecycle.viewmodel.compose.viewModel
import dev.tcode.thinmp.constant.StyleConstant
import dev.tcode.thinmp.model.media.SongModel
import dev.tcode.thinmp.model.media.valueObject.AlbumId
import dev.tcode.thinmp.view.collapsingTopAppBar.DetailCollapsingTopAppBarView
import dev.tcode.thinmp.view.collapsingTopAppBar.detailSize
import dev.tcode.thinmp.view.dropdownMenu.FavoriteSongDropdownMenuItemView
import dev.tcode.thinmp.view.dropdownMenu.PlaylistDropdownMenuItemView
import dev.tcode.thinmp.view.dropdownMenu.ShortcutDropdownMenuItemView
import dev.tcode.thinmp.view.image.ImageView
import dev.tcode.thinmp.view.layout.CommonLayoutView
import dev.tcode.thinmp.view.row.DropdownMenuView
import dev.tcode.thinmp.view.row.MediaRowView
import dev.tcode.thinmp.view.title.PrimaryTitleView
import dev.tcode.thinmp.view.title.SecondaryTitleView
import dev.tcode.thinmp.view.util.CustomGridCellsFixed
import dev.tcode.thinmp.view.util.CustomLifecycleEventObserver
import dev.tcode.thinmp.view.util.gridSpanCount
import dev.tcode.thinmp.viewModel.AlbumDetailViewModel
@Composable
fun AlbumDetailScreen(id: String, viewModel: AlbumDetailViewModel = viewModel()) {
val uiState by viewModel.uiState.collectAsState()
val spanCount: Int = gridSpanCount()
val (size, gradientHeight, primaryTitlePosition, secondaryTitlePosition) = detailSize()
CustomLifecycleEventObserver(viewModel)
CommonLayoutView { showPlaylistRegisterPopup ->
DetailCollapsingTopAppBarView(title = uiState.primaryText, columns = CustomGridCellsFixed(spanCount), spanCount = spanCount, dropdownMenus = { callback ->
ShortcutDropdownMenuItemView(AlbumId(id), callback)
}) {
item(span = { GridItemSpan(spanCount) }) {
ConstraintLayout(
Modifier
.fillMaxWidth()
.height(size)
) {
val (primary, secondary, tertiary) = createRefs()
ImageView(
uri = uiState.imageUri, contentScale = ContentScale.Fit, modifier = Modifier.fillMaxSize()
)
Box(
modifier = Modifier
.fillMaxWidth()
.height(gradientHeight)
.constrainAs(primary) {
top.linkTo(parent.bottom, margin = -gradientHeight)
}
.background(
brush = Brush.verticalGradient(
0.0f to MaterialTheme.colorScheme.background.copy(alpha = 0F),
1.0F to MaterialTheme.colorScheme.background,
)
),
) {}
Row(
Modifier
.fillMaxWidth()
.height(StyleConstant.ROW_HEIGHT.dp)
.constrainAs(secondary) {
top.linkTo(parent.top, margin = primaryTitlePosition)
},
verticalAlignment = Alignment.CenterVertically,
horizontalArrangement = Arrangement.Center,
) {
PrimaryTitleView(uiState.primaryText)
}
Row(
Modifier
.fillMaxWidth()
.height(25.dp)
.constrainAs(tertiary) {
top.linkTo(parent.top, margin = secondaryTitlePosition)
},
verticalAlignment = Alignment.CenterVertically,
horizontalArrangement = Arrangement.Center,
) {
SecondaryTitleView(uiState.secondaryText)
}
}
}
itemsIndexed(uiState.songs, span = { _: Int, _: SongModel -> GridItemSpan(spanCount) }) { index, song ->
DropdownMenuView(dropdownContent = { callback ->
val callbackPlaylist = {
showPlaylistRegisterPopup(song.songId)
callback()
}
FavoriteSongDropdownMenuItemView(song.songId, callback)
PlaylistDropdownMenuItemView(callbackPlaylist)
}) { callback ->
MediaRowView(song.name, song.artistName, song.getImageUri(), Modifier.pointerInput(index) {
detectTapGestures(onLongPress = { callback() }, onTap = { viewModel.start(index) })
})
}
}
}
}
} | 0 | null | 0 | 5 | 1e99c1c87dad4c450cb0b8b6b742104450df9e81 | 5,918 | ThinMP_Android_Kotlin | MIT License |
kotlin-antd/src/main/kotlin/antd/checkbox/Checkbox.kt | oxiadenine | 206,398,615 | false | null | @file:JsModule("antd/lib/checkbox")
@file:JsNonModule
package antd.checkbox
import antd.*
import org.w3c.dom.*
import org.w3c.dom.events.MouseEvent
import react.*
@JsName("default")
external object CheckboxComponent : Component<CheckboxProps, RState> {
val Group: CheckboxGroupComponent
override fun render(): ReactElement?
}
external interface CheckboxProps : AbstractCheckboxProps<CheckboxChangeEvent>, RProps {
var indeterminate: Boolean?
}
external interface AbstractCheckboxProps<T> {
var prefixCls: String?
var className: String?
var defaultChecked: Boolean?
var checked: Boolean?
var style: dynamic
var disabled: Boolean?
var onChange: ((e: T) -> Unit)?
var onClick: MouseEventHandler<HTMLElement>?
var onMouseEnter: MouseEventHandler<HTMLElement>?
var onMouseLeave: MouseEventHandler<HTMLElement>?
var onKeyPress: KeyboardEventHandler<HTMLElement>?
var onKeyDown: KeyboardEventHandler<HTMLElement>?
var value: Any?
var tabIndex: Number?
var name: String?
var children: ReactElement?
var id: String?
var autoFocus: Boolean?
}
external interface CheckboxChangeEventTarget : CheckboxProps {
override var checked: Boolean?
}
external interface CheckboxChangeEvent {
val target: CheckboxChangeEventTarget
val stopPropagation: () -> Unit
val preventDefault: () -> Unit
val nativeEvent: MouseEvent
}
| 1 | null | 8 | 50 | e0017a108b36025630c354c7663256347e867251 | 1,413 | kotlin-js-wrappers | Apache License 2.0 |
crud-framework-hibernate5-connector/src/main/java/com/antelopesystem/crudframework/jpa/lazyinitializer/LazyInitializerPersistentHooks.kt | antelopesystems | 279,278,095 | false | {"Java": 272601, "Kotlin": 129883, "ANTLR": 1954} | package com.antelopesystem.crudframework.jpa.lazyinitializer
import com.antelopesystem.crudframework.crud.hooks.interfaces.*
import com.antelopesystem.crudframework.jpa.lazyinitializer.annotation.InitializeLazyOn
import com.antelopesystem.crudframework.model.BaseCrudEntity
import com.antelopesystem.crudframework.modelfilter.DynamicModelFilter
import com.antelopesystem.crudframework.ro.PagingDTO
import com.antelopesystem.crudframework.utils.utils.ReflectionUtils
import org.hibernate.Hibernate
class LazyInitializerPersistentHooks : ShowHooks<Long, BaseCrudEntity<Long>>,
ShowByHooks<Long, BaseCrudEntity<Long>>,
IndexHooks<Long, BaseCrudEntity<Long>>,
UpdateHooks<Long, BaseCrudEntity<Long>>,
UpdateFromHooks<Long, BaseCrudEntity<Long>>,
CreateHooks<Long, BaseCrudEntity<Long>>,
CreateFromHooks<Long, BaseCrudEntity<Long>> {
override fun onShow(entity: BaseCrudEntity<Long>?) {
entity ?: return
initializeLazyFields(entity) { it.show }
}
override fun onCreateFrom(entity: BaseCrudEntity<Long>, ro: Any) {
initializeLazyFields(entity) { it.createFrom }
}
override fun onCreate(entity: BaseCrudEntity<Long>) {
initializeLazyFields(entity) { it.create }
}
override fun onIndex(filter: DynamicModelFilter, result: PagingDTO<BaseCrudEntity<Long>>) {
result.data ?: return
for (entity in result.data) {
initializeLazyFields(entity) { it.index }
}
}
override fun onShowBy(entity: BaseCrudEntity<Long>?) {
entity ?: return
initializeLazyFields(entity) { it.showBy }
}
override fun onUpdateFrom(entity: BaseCrudEntity<Long>, ro: Any) {
initializeLazyFields(entity) { it.updateFrom }
}
override fun onUpdate(entity: BaseCrudEntity<Long>) {
initializeLazyFields(entity) { it.update }
}
private fun initializeLazyFields(entity: BaseCrudEntity<Long>, condition: (annotation: InitializeLazyOn) -> Boolean) {
ReflectionUtils.doWithFields(entity::class.java) {
val annotation = it.getDeclaredAnnotation(ANNOTATION_TYPE) ?: return@doWithFields
if(condition(annotation)) {
ReflectionUtils.makeAccessible(it)
Hibernate.initialize(it.get(entity))
}
}
}
companion object {
private val ANNOTATION_TYPE = InitializeLazyOn::class.java
}
} | 22 | Java | 1 | 4 | e7560472889f3760029d03f48c3af5f441bb4cf1 | 2,441 | crud-framework | Creative Commons Attribution 3.0 Unported |
bmm-core/src/main/kotlin/de/miraculixx/bmm/utils/serializer/ColorSerializer.kt | MiraculixxT | 556,926,486 | false | {"Kotlin": 161451, "Java": 2253} | package de.miraculixx.bmm.utils.serializer
import de.bluecolored.bluemap.api.math.Color
import kotlinx.serialization.KSerializer
import kotlinx.serialization.descriptors.PrimitiveKind
import kotlinx.serialization.descriptors.PrimitiveSerialDescriptor
import kotlinx.serialization.encoding.Decoder
import kotlinx.serialization.encoding.Encoder
object ColorSerializer : KSerializer<Color> {
override val descriptor = PrimitiveSerialDescriptor("Color", PrimitiveKind.STRING)
override fun deserialize(decoder: Decoder): Color {
return decoder.decodeString().split(",").let {
Color(it[0].toInt(), it[1].toInt(), it[2].toInt(), it[3].toFloat())
}
}
override fun serialize(encoder: Encoder, value: Color) {
encoder.encodeString("${value.red},${value.green},${value.blue},${value.alpha}")
}
} | 7 | Kotlin | 7 | 15 | a2aa75e98b8bea04a285ce8856948a3279334388 | 844 | bluemap-marker | MIT License |
app/src/main/java/xyz/teamgravity/notepad/presentation/theme/Theme.kt | raheemadamboev | 312,077,625 | false | null | package xyz.teamgravity.notepad.presentation.theme
import android.app.Activity
import android.os.Build
import androidx.compose.foundation.isSystemInDarkTheme
import androidx.compose.material3.*
import androidx.compose.runtime.Composable
import androidx.compose.runtime.SideEffect
import androidx.compose.ui.graphics.toArgb
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.platform.LocalView
import androidx.core.view.ViewCompat
private val DarkColorScheme = darkColorScheme(
primary = GreenGrey30,
onPrimary = White,
primaryContainer = Green30,
onPrimaryContainer = White700,
inversePrimary = Green40,
secondary = DeepGreen80,
onSecondary = DeepGreen20,
secondaryContainer = GreenGrey30,
onSecondaryContainer = DeepGreen90,
tertiary = Violet80,
onTertiary = Violet20,
tertiaryContainer = Violet30,
onTertiaryContainer = Violet90,
error = Red80,
onError = Red20,
errorContainer = Red30,
onErrorContainer = Red90,
background = DarkGray,
onBackground = White700,
surface = DarkGray200,
onSurface = White700,
inverseSurface = Grey20,
inverseOnSurface = Grey95,
surfaceVariant = DarkGray200,
onSurfaceVariant = White700,
outline = GreenGrey80
)
private val LightColorScheme = lightColorScheme(
primary = Green40,
onPrimary = White,
primaryContainer = Green90,
onPrimaryContainer = Green10,
inversePrimary = Green80,
secondary = DeepGreen40,
onSecondary = White,
secondaryContainer = DeepGreen90,
onSecondaryContainer = DeepGreen10,
tertiary = Violet40,
onTertiary = White,
tertiaryContainer = Violet90,
onTertiaryContainer = Violet10,
error = Red40,
onError = White,
errorContainer = Red90,
onErrorContainer = Red10,
background = Grey99,
onBackground = Grey10,
surface = GreenGrey90,
onSurface = GreenGrey30,
inverseSurface = Grey20,
inverseOnSurface = Grey95,
surfaceVariant = GreenGrey90,
onSurfaceVariant = GreenGrey30,
outline = GreenGrey50
)
@Composable
fun NotepadTheme(
darkTheme: Boolean = isSystemInDarkTheme(),
dynamicColor: Boolean = false,
content: @Composable () -> Unit,
) {
val colorScheme = when {
dynamicColor && Build.VERSION.SDK_INT >= Build.VERSION_CODES.S -> {
val context = LocalContext.current
if (darkTheme) dynamicDarkColorScheme(context) else dynamicLightColorScheme(context)
}
darkTheme -> DarkColorScheme
else -> LightColorScheme
}
val view = LocalView.current
if (!view.isInEditMode) {
SideEffect {
(view.context as Activity).window.statusBarColor = colorScheme.primary.toArgb()
ViewCompat.getWindowInsetsController(view)?.isAppearanceLightStatusBars = darkTheme
}
}
MaterialTheme(
colorScheme = colorScheme,
typography = Typography,
content = content
)
} | 0 | Kotlin | 0 | 9 | 6d883b53b283a7737e82f0e414f649259a5708fd | 2,979 | notepad-app | Apache License 2.0 |
app/src/main/kotlin/com/ave/vastgui/app/activity/FileActivity.kt | SakurajimaMaii | 353,212,367 | false | null | /*
* Copyright 2022 VastGui <EMAIL>
*
* 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.ave.vastgui.app.activity
import android.os.Bundle
import android.view.MotionEvent
import android.widget.EditText
import androidx.appcompat.app.AppCompatActivity
import com.ave.vastgui.app.R
import com.ave.vastgui.app.databinding.ActivityFileBinding
import com.ave.vastgui.app.log.logFactory
import com.ave.vastgui.tools.utils.drawable
import com.ave.vastgui.tools.view.extension.hideKeyBroad
import com.ave.vastgui.tools.view.extension.isShouldHideKeyBroad
import com.ave.vastgui.tools.viewbinding.viewBinding
// Author: SakurajimaMai
// Email: <EMAIL>
// Date: 2022/5/31
// Documentation: https://ave.entropy2020.cn/documents/tools/core-topics/app-data-and-files/file-manager/file-mgr/
class FileActivity : AppCompatActivity(R.layout.activity_file) {
private val logcat = logFactory(FileActivity::class.java)
private val binding by viewBinding(ActivityFileBinding::bind)
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding.button.setOnClickListener {
logcat.d("这是一条日志")
logcat.e(NullPointerException("this object is null."))
}
val drawable = drawable(R.drawable.ic_github).also {
logcat.d(it!!::class.java.simpleName)
}
binding.icon1.run { }
null.isNullOrBlank()
binding.icon1.setImageDrawable(drawable)
}
override fun onTouchEvent(event: MotionEvent?): Boolean {
if (MotionEvent.ACTION_DOWN == event?.action) {
val view = currentFocus
if (null != view && view is EditText) {
if (view.isShouldHideKeyBroad(event)) {
view.hideKeyBroad()
}
}
}
return super.onTouchEvent(event)
}
} | 8 | null | 6 | 64 | 81c5ca59680143d9523c01852d9587a8d926c1c3 | 2,375 | Android-Vast-Extension | Apache License 2.0 |
app/src/main/java/estimator/kissteam/com/estimatorclient/dal/services/request_response/UserResponse.kt | 301shevchukanton | 125,558,124 | false | null | package estimator.kissteam.com.estimatorclient.dal.services.request_response
/**
* Created by <NAME> on 17.03.2018.
*/
class UserResponse(val id: String?,
val email: String?,
val created_at: String?,
val updated_at: String?) | 0 | Kotlin | 0 | 0 | c89dc901c20aaa835be057923b55bfedb004bf44 | 249 | EstimatorClient | Apache License 2.0 |
solar/src/main/java/com/chiksmedina/solar/bold/users/UserPlus.kt | CMFerrer | 689,442,321 | false | {"Kotlin": 36591890} | package com.chiksmedina.solar.bold.users
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.PathFillType.Companion.EvenOdd
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.UsersGroup
val UsersGroup.UserMinus: ImageVector
get() {
if (_userMinus != null) {
return _userMinus!!
}
_userMinus = Builder(
name = "UserMinus", 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 = EvenOdd
) {
moveTo(13.5126f, 21.4874f)
curveTo(14.0251f, 22.0f, 14.8501f, 22.0f, 16.5f, 22.0f)
curveTo(18.1499f, 22.0f, 18.9749f, 22.0f, 19.4874f, 21.4874f)
curveTo(20.0f, 20.9749f, 20.0f, 20.1499f, 20.0f, 18.5f)
curveTo(20.0f, 16.8501f, 20.0f, 16.0251f, 19.4874f, 15.5126f)
curveTo(18.9749f, 15.0f, 18.1499f, 15.0f, 16.5f, 15.0f)
curveTo(14.8501f, 15.0f, 14.0251f, 15.0f, 13.5126f, 15.5126f)
curveTo(13.0f, 16.0251f, 13.0f, 16.8501f, 13.0f, 18.5f)
curveTo(13.0f, 20.1499f, 13.0f, 20.9749f, 13.5126f, 21.4874f)
close()
moveTo(15.9167f, 17.9167f)
horizontalLineTo(14.9444f)
curveTo(14.6223f, 17.9167f, 14.3611f, 18.1778f, 14.3611f, 18.5f)
curveTo(14.3611f, 18.8222f, 14.6223f, 19.0833f, 14.9444f, 19.0833f)
horizontalLineTo(15.9167f)
horizontalLineTo(17.0833f)
horizontalLineTo(18.0556f)
curveTo(18.3777f, 19.0833f, 18.6389f, 18.8222f, 18.6389f, 18.5f)
curveTo(18.6389f, 18.1778f, 18.3777f, 17.9167f, 18.0556f, 17.9167f)
horizontalLineTo(17.0833f)
horizontalLineTo(15.9167f)
close()
}
path(
fill = SolidColor(Color(0xFF000000)), stroke = null, strokeLineWidth = 0.0f,
strokeLineCap = Butt, strokeLineJoin = Miter, strokeLineMiter = 4.0f,
pathFillType = NonZero
) {
moveTo(15.6782f, 13.5028f)
curveTo(15.2051f, 13.5085f, 14.7642f, 13.5258f, 14.3799f, 13.5774f)
curveTo(13.737f, 13.6639f, 13.0334f, 13.8705f, 12.4519f, 14.4519f)
curveTo(11.8705f, 15.0333f, 11.6639f, 15.737f, 11.5775f, 16.3799f)
curveTo(11.4998f, 16.9576f, 11.4999f, 17.6635f, 11.5f, 18.414f)
verticalLineTo(18.586f)
curveTo(11.4999f, 19.3365f, 11.4998f, 20.0424f, 11.5775f, 20.6201f)
curveTo(11.6381f, 21.0712f, 11.7579f, 21.5522f, 12.0249f, 22.0f)
curveTo(12.0166f, 22.0f, 12.0083f, 22.0f, 12.0f, 22.0f)
curveTo(4.0f, 22.0f, 4.0f, 19.9853f, 4.0f, 17.5f)
curveTo(4.0f, 15.0147f, 7.5817f, 13.0f, 12.0f, 13.0f)
curveTo(13.3262f, 13.0f, 14.577f, 13.1815f, 15.6782f, 13.5028f)
close()
}
path(
fill = SolidColor(Color(0xFF000000)), stroke = null, strokeLineWidth = 0.0f,
strokeLineCap = Butt, strokeLineJoin = Miter, strokeLineMiter = 4.0f,
pathFillType = NonZero
) {
moveTo(12.0f, 6.0f)
moveToRelative(-4.0f, 0.0f)
arcToRelative(4.0f, 4.0f, 0.0f, true, true, 8.0f, 0.0f)
arcToRelative(4.0f, 4.0f, 0.0f, true, true, -8.0f, 0.0f)
}
}
.build()
return _userMinus!!
}
private var _userMinus: ImageVector? = null
| 0 | Kotlin | 0 | 0 | 3414a20650d644afac2581ad87a8525971222678 | 4,294 | SolarIconSetAndroid | MIT License |
photoeditor/src/androidTest/java/ja/burhanrashid52/photoeditor/DrawingViewUndoRedoTest.kt | burhanrashid52 | 118,602,757 | false | null | package ja.burhanrashid52.photoeditor
import androidx.test.ext.junit.runners.AndroidJUnit4
import ja.burhanrashid52.photoeditor.shape.ShapeAndPaint
import junit.framework.TestCase.assertEquals
import junit.framework.TestCase.assertFalse
import org.junit.Test
import org.junit.runner.RunWith
import org.mockito.Mockito
@RunWith(AndroidJUnit4::class)
internal class DrawingViewUndoRedoTest : BaseDrawingViewTest() {
@Test
fun testUndoReturnFalseWhenThereNothingToUndo() {
val drawingView = DrawingView(context)
assertFalse(drawingView.undo())
}
@Test
fun testRedoReturnFalseWhenThereNothingToRedo() {
val drawingView = DrawingView(context)
assertFalse(drawingView.redo())
}
@Test
fun testUndoAndRedoWithListenerWhenAnythingIsDrawnOnCanvas() {
val brushViewChangeListener = Mockito.mock(BrushViewChangeListener::class.java)
val drawingView = setupDrawingViewWithChangeListener(brushViewChangeListener)
// Add 3 Shapes
swipeView(drawingView)
swipeView(drawingView)
swipeView(drawingView)
Mockito.verify(brushViewChangeListener, Mockito.times(3)).onViewAdd(drawingView)
verifyUndo(drawingView, brushViewChangeListener)
verifyRedo(drawingView, brushViewChangeListener)
}
private fun verifyUndo(
drawingView: DrawingView,
brushViewChangeListener: BrushViewChangeListener
) {
val drawingPaths = drawingView.drawingPath
val undoPaths = drawingPaths.first
val redoPaths = drawingPaths.second
assertEquals(3, undoPaths.size)
assertEquals(0, redoPaths.size)
drawingView.undo()
assertEquals(2, undoPaths.size)
assertEquals(1, redoPaths.size)
Mockito.verify(brushViewChangeListener, Mockito.times(1)).onViewRemoved(drawingView)
drawingView.undo()
assertEquals(1, undoPaths.size)
assertEquals(2, redoPaths.size)
Mockito.verify(brushViewChangeListener, Mockito.times(2)).onViewRemoved(drawingView)
drawingView.undo()
assertEquals(0, undoPaths.size)
assertEquals(3, redoPaths.size)
Mockito.verify(brushViewChangeListener, Mockito.times(3)).onViewRemoved(drawingView)
}
private fun verifyRedo(
drawingView: DrawingView,
brushViewChangeListener: BrushViewChangeListener
) {
val drawingPaths = drawingView.drawingPath
val undoPaths = drawingPaths.first
val redoPaths = drawingPaths.second
assertEquals(undoPaths.size, 0)
assertEquals(redoPaths.size, 3)
drawingView.redo()
assertEquals(undoPaths.size, 1)
assertEquals(redoPaths.size, 2)
Mockito.verify(brushViewChangeListener, Mockito.times(4)).onViewAdd(drawingView)
drawingView.redo()
assertEquals(undoPaths.size, 2)
assertEquals(redoPaths.size, 1)
Mockito.verify(brushViewChangeListener, Mockito.times(5)).onViewAdd(drawingView)
drawingView.redo()
assertEquals(undoPaths.size, 3)
assertEquals(redoPaths.size, 0)
Mockito.verify(brushViewChangeListener, Mockito.times(6)).onViewAdd(drawingView)
}
@Test
fun testUndoRedoAndPaintColorWhenEverythingIsCleared() {
val brushViewChangeListener = Mockito.mock(BrushViewChangeListener::class.java)
val drawingView = setupDrawingViewWithChangeListener(brushViewChangeListener)
val paths = drawingView.drawingPath
val undoPaths = paths.first
val redoPaths = paths.second
val linePath = Mockito.mock(ShapeAndPaint::class.java)
undoPaths.add(linePath)
undoPaths.add(linePath)
redoPaths.add(linePath)
drawingView.clearAll()
assertEquals(undoPaths.size, 0)
assertEquals(redoPaths.size, 0)
}
} | 71 | null | 988 | 4,100 | 76f1b03281f3123f9687ae01955831d60ce797eb | 3,855 | PhotoEditor | MIT License |
app/src/main/java/top/chilfish/chillchat/data/repository/MessageRepository.kt | Chilfish | 638,930,009 | false | null | package top.chilfish.chillchat.data.repository
import android.util.Log
import com.drake.net.Get
import io.socket.client.Socket
import kotlinx.coroutines.CoroutineDispatcher
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import kotlinx.serialization.encodeToString
import kotlinx.serialization.json.Json
import top.chilfish.chillchat.data.messages.Message
import top.chilfish.chillchat.data.messages.MessageDao
import top.chilfish.chillchat.data.messages.MessagesItem
import top.chilfish.chillchat.data.module.ApplicationScope
import top.chilfish.chillchat.data.module.IODispatcher
import top.chilfish.chillchat.provider.curId
import javax.inject.Inject
import javax.inject.Singleton
@Singleton
class MessageRepository @Inject constructor(
private val dao: MessageDao,
private val chatsRepo: ChatsListRepository,
private val socket: Socket,
private val api: ApiRequest,
@ApplicationScope
private val scope: CoroutineScope,
@IODispatcher
private val ioDispatcher: CoroutineDispatcher,
) {
fun getAll(chatterId: String) = dao.getAll(curId, chatterId)
suspend fun insert(message: Message) = dao.insert(message)
suspend fun delete(id: String) = dao.deleteById(id)
suspend fun deleteAll() = dao.deleteAll()
suspend fun loadAll() = withContext(ioDispatcher) {
val res = api.request {
Get<List<MessagesItem>>("/messages/${curId}")
} ?: return@withContext
dao.deleteAll()
res.forEach {
Log.d("Chat", "fetch messages: ${it.messages}")
dao.insertAll(it.messages)
}
}
private suspend fun insertAndUpdate(mes: Message, chatterId: String) =
withContext(ioDispatcher) {
launch { chatsRepo.updateById(chatterId, mes.content, mes.time) }
launch { dao.insert(mes) }
Unit
}
suspend fun sendMes(chatterId: String, content: String) = withContext(ioDispatcher) {
val message = Message(
sendId = curId,
receiveId = chatterId,
content = content
)
socket.emit("send_message", Json.encodeToString(message))
insertAndUpdate(message, chatterId)
}
suspend fun receiveMes() = withContext(ioDispatcher) {
socket.on("message") { args ->
val message = Json.decodeFromString<Message>(args[0].toString())
Log.d("Chat", "receive: ${args[0]}")
scope.launch {
insertAndUpdate(message, message.sendId)
}
}
Unit
}
suspend fun isRead(chatterId: String) = withContext(ioDispatcher) {
socket.emit("read", """{"userId":"$curId","chatterId":"$chatterId"}""")
Unit
}
}
| 0 | Kotlin | 1 | 4 | 623b5a3505624eb494c44b91bfffdc73a980d463 | 2,787 | Chill-Chat | MIT License |
shared/src/commonMain/kotlin/com/somabits/spanish/ui/product/DataPackCard.kt | chiljamgossow | 581,781,635 | false | {"Kotlin": 905901, "Swift": 1817} | package com.somabits.spanish.ui.product
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.PaddingValues
import androidx.compose.foundation.layout.Spacer
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.material3.Button
import androidx.compose.material3.ButtonDefaults
import androidx.compose.material3.Card
import androidx.compose.material3.CardDefaults
import androidx.compose.material3.Icon
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.graphics.vector.ImageVector
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.unit.dp
import com.somabits.spanish.ui.guide.LargeRadialGradient
import com.somabits.spanish.ui.theme.CardColorScheme
@Composable
fun DataPackCard(
modifier: Modifier = Modifier,
colorScheme: CardColorScheme,
imageVector: ImageVector? = null,
title: String,
body: String,
verbList: List<String>,
buttonText: String,
backgroundGradient: Boolean = true,
onClick: () -> Unit,
) {
Card(
modifier = modifier,
colors = CardDefaults.cardColors(
contentColor = colorScheme.content,
containerColor = colorScheme.container
),
) {
val paddingHorizontal = 16.dp
val paddingVertical = 16.dp
val padding = PaddingValues(
horizontal = paddingHorizontal,
)
Box(
modifier = Modifier
.clip(MaterialTheme.shapes.medium)
.background(
LargeRadialGradient(
colors = listOf(
colorScheme.container,
colorScheme.color.copy(alpha = .2f),
colorScheme.container.copy(alpha = .6f)
),
colorStops = listOf(.1f, .5f, 0.9f)
)
).takeIf { backgroundGradient } ?: Modifier,
) {
Column(
horizontalAlignment = Alignment.CenterHorizontally,
verticalArrangement = Arrangement.SpaceAround
) {
Text(
text = title,
style = MaterialTheme.typography.titleLarge,
modifier = Modifier
.padding(padding)
.padding(top = paddingVertical)
.fillMaxWidth(),
textAlign = TextAlign.Center
)
Spacer(modifier = Modifier.height(8.dp))
Text(
text = body,
style = MaterialTheme.typography.bodyMedium,
modifier = Modifier
.padding(padding)
.fillMaxWidth(),
textAlign = TextAlign.Center
)
Spacer(modifier = Modifier.height(8.dp))
Text(
text = verbList.joinToString(separator = " - "),
style = MaterialTheme.typography.bodyLarge,
modifier = Modifier
.padding(padding)
.fillMaxWidth(),
textAlign = TextAlign.Center
)
Spacer(modifier = Modifier.height(16.dp))
Button(
onClick = onClick,
modifier = Modifier
.padding(padding)
.padding(bottom = paddingVertical),
colors = ButtonDefaults.buttonColors(
containerColor = colorScheme.color,
contentColor = colorScheme.onColor
),
) {
imageVector?.let {
Icon(
imageVector = imageVector,
contentDescription = null,
modifier = Modifier
.padding(end = 8.dp)
.size(20.dp),
)
}
Text(
text = buttonText,
)
}
}
}
}
}
| 1 | Kotlin | 0 | 0 | e680c7048721fb9a2cbfb7cb5a9db3e39ac73b45 | 4,788 | Spanish | MIT License |
js/js.translator/testData/box/callableReference/function/extensionFromTopLevelUnitOneStringArg.kt | JakeWharton | 99,388,807 | false | null | // This test was adapted from compiler/testData/codegen/box/callableReference/function/.
package foo
fun run(arg1: A, arg2: String, funRef:A.(String) -> Unit): Unit {
return arg1.funRef(arg2)
}
class A {
var result = "Fail"
}
fun A.foo(newResult: String) {
result = newResult
}
fun box(): String {
val a = A()
val x = A::foo
x(a, "OK")
if (a.result != "OK") return a.result
// TODO: uncomment when KT-13312 gets fixed
/*
val a1 = A()
run(a1, "OK", A::foo)
if (a1.result != "OK) return a1.result
*/
return "OK"
}
| 181 | null | 5748 | 83 | 4383335168338df9bbbe2a63cb213a68d0858104 | 575 | kotlin | Apache License 2.0 |
ui/features/tasks/src/main/java/city/zouitel/tasks/di/tasksKoinModule.kt | City-Zouitel | 576,223,915 | false | {"Kotlin": 556982} | package city.zouitel.tasks.di
import city.zouitel.tasks.mapper.NoteAndTaskMapper
import city.zouitel.tasks.mapper.TaskMapper
import city.zouitel.tasks.ui.NoteAndTaskScreenModel
import city.zouitel.tasks.ui.TaskScreenModel
import org.koin.core.module.dsl.factoryOf
import org.koin.dsl.module
val tasksKoinModule = module {
factoryOf(::TaskMapper)
factoryOf(::NoteAndTaskMapper)
factoryOf(::TaskScreenModel)
factoryOf(::NoteAndTaskScreenModel)
} | 43 | Kotlin | 13 | 120 | 07941aad43dade00f368bbf231eea22822b2777e | 462 | JetNote | Apache License 2.0 |
aspoet/src/main/kotlin/com/google/androidstudiopoet/generators/project/GradlewGenerator.kt | android | 106,021,222 | false | null | /*
Copyright 2017 Google Inc.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
https://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package com.google.androidstudiopoet.generators.project
import com.google.androidstudiopoet.models.ProjectBlueprint
import com.google.androidstudiopoet.utils.joinPath
import com.google.androidstudiopoet.writers.GithubDownloader
import java.io.File
import java.io.FileInputStream
import java.nio.file.Files
import java.nio.file.StandardCopyOption
object GradlewGenerator {
private val ref = "master"
fun generateGradleW(root: String, projectBlueprint: ProjectBlueprint) {
val gradlew = "gradlew"
val gradlewbat = "gradlew.bat"
if (!File(getAssetsFolderPath()).exists() ||
!File(getAssetsFolderPath(), gradlew).exists() ||
!File(getAssetsFolderPath(), gradlewbat).exists() ||
!File(getAssetsFolderPath(), "gradle/wrapper").exists()
) {
println("AS Poet needs network access to download gradle files from Github " +
"\nhttps://github.com/android/android-studio-poet/tree/master/resources/gradle-assets?ref=$ref " +
"\nplease copy/paste the gradle folder directly to the generated root folder")
return
}
val gradleWFile = File(root, gradlew).toPath()
Files.copy(FileInputStream(File(getAssetsFolderPath(), gradlew)), gradleWFile, StandardCopyOption.REPLACE_EXISTING)
Files.copy(FileInputStream(File(getAssetsFolderPath(), gradlewbat)), File(root, gradlewbat).toPath(), StandardCopyOption.REPLACE_EXISTING)
Runtime.getRuntime().exec("chmod u+x " + gradleWFile)
val gradleFolder = File(root, "gradle")
gradleFolder.mkdir()
val gradleWrapperFolder = File(gradleFolder, "wrapper")
gradleWrapperFolder.mkdir()
val sourceFolder = File(getAssetsFolderPath(), "gradle/wrapper")
val gradleWrapperJar = "gradle-wrapper.jar"
val gradleWrapperProperties = "gradle-wrapper.properties"
Files.copy(FileInputStream(File(sourceFolder, gradleWrapperJar)),
File(gradleWrapperFolder, gradleWrapperJar).toPath(),
StandardCopyOption.REPLACE_EXISTING)
File(gradleWrapperFolder, gradleWrapperProperties).
writeText(gradleWrapper(projectBlueprint.gradleVersion))
}
private fun getAssetsFolderPath(): String {
var assetsFolder: String = System.getProperty("user.home")
.joinPath(".aspoet")
.joinPath("gradle-assets")
if (!File(assetsFolder).exists()) {
GithubDownloader().downloadDir(
"https://api.github.com/repos/android/" +
"android-studio-poet/contents/resources/gradle-assets?ref=$ref",
assetsFolder)
}
return assetsFolder
}
private fun gradleWrapper(gradleVersion: String) = """
distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists
distributionUrl=https\://services.gradle.org/distributions/gradle-$gradleVersion-bin.zip
"""
}
| 12 | Kotlin | 89 | 680 | f820e9cc0e5d7db4de9a7e31b818277143546f73 | 3,641 | android-studio-poet | Apache License 2.0 |
matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/room/model/call/CallAssertedIdentityContent.kt | matrix-org | 287,466,066 | false | null | /*
* Copyright 2021 The Matrix.org Foundation C.I.C.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.matrix.android.sdk.api.session.room.model.call
import com.squareup.moshi.Json
import com.squareup.moshi.JsonClass
/**
* This event is sent by the callee when they wish to answer the call.
*/
@JsonClass(generateAdapter = true)
data class CallAssertedIdentityContent(
/**
* Required. The ID of the call this event relates to.
*/
@Json(name = "call_id") override val callId: String,
/**
* Required. ID to let user identify remote echo of their own events
*/
@Json(name = "party_id") override val partyId: String? = null,
/**
* Required. The version of the VoIP specification this messages adheres to.
*/
@Json(name = "version") override val version: String?,
/**
* Optional. Used to inform the transferee who they're now speaking to.
*/
@Json(name = "asserted_identity") val assertedIdentity: AssertedIdentity? = null
) : CallSignalingContent {
/**
* A user ID may be included if relevant, but unlike target_user, it is purely informational.
* The asserted identity may not represent a matrix user at all,
* in which case just a display_name may be given, or a perhaps a display_name and avatar_url.
*/
@JsonClass(generateAdapter = true)
data class AssertedIdentity(
@Json(name = "id") val id: String? = null,
@Json(name = "display_name") val displayName: String? = null,
@Json(name = "avatar_url") val avatarUrl: String? = null
)
}
| 75 | null | 27 | 97 | 55cc7362de34a840c67b4bbb3a14267bc8fd3b9c | 2,176 | matrix-android-sdk2 | Apache License 2.0 |
apriltagdetection/src/main/java/com/apriltagdetection/config/model/ApriltagDetection.kt | easedroid | 265,847,075 | false | {"C": 3448495, "C++": 28896, "Kotlin": 21162, "CMake": 12218, "Objective-C": 3368} | package com.apriltagdetection.config.model
import android.util.Size
class ApriltagDetection {
// The decoded ID of the tag
var id: Int = 0
// How many error bits were corrected? Note: accepting large numbers of
// corrected errors leads to greatly increased false positive rates.
// NOTE: As of this implementation, the detector cannot detect tags with
// a hamming distance greater than 2.
var hamming: Int = 0
// The center of the detection in image pixel coordinates.
var c = DoubleArray(2)
// The corners of the tag in image pixel coordinates. These always
// wrap counter-clock wise around the tag.
// Flattened to [x0 y0 x1 y1 ...] for JNI convenience
var p = DoubleArray(8)
var r = DoubleArray(9)
//var byte: ByteArray = ByteArray(640*640)
} | 0 | C | 2 | 2 | 75fa740aecb06693c62562d2445269c79c4e69c3 | 816 | apriltag_detector_android | Apache License 2.0 |
app/src/main/java/com/kotlinproject/modernfoodrecipesapp/model/ingredientssearch/models/recipe_details/RecipeDetailsResponse.kt | kbrakendirci | 476,260,445 | false | null | package com.example.recipeapp.model
import java.io.Serializable
data class Result(
val aggregateLikes: Int,
val analyzedInstructions: List<AnalyzedInstructionX>,
val cheap: Boolean,
val cookingMinutes: Int,
val creditsText: String,
val cuisines: List<String>,
val dairyFree: Boolean,
val diets: List<String>,
val dishTypes: List<String>,
val gaps: String,
val glutenFree: Boolean,
val healthScore: Double,
val id: Int,
val image: String,
val imageType: String,
val license: String,
val lowFodmap: Boolean,
val occasions: List<Any>,
val preparationMinutes: Int,
val pricePerServing: Double,
val readyInMinutes: Int,
val servings: Int,
val sourceName: String,
val sourceUrl: String,
val spoonacularScore: Double,
val spoonacularSourceUrl: String,
val summary: String,
val sustainable: Boolean,
val title: String,
val vegan: Boolean,
val vegetarian: Boolean,
val veryHealthy: Boolean,
val veryPopular: Boolean,
val weightWatcherSmartPoints: Int
): Serializable | 0 | null | 0 | 2 | 359bf58306f0d27c78e8df87a6bad3e290e68994 | 1,095 | MLRecipeRecommendApp | MIT License |
app/src/test/java/org/simple/clinic/summary/bloodpressures/BloodPressureSummaryViewEffectHandlerTest.kt | simpledotorg | 132,515,649 | false | null | package org.simple.clinic.summary.bloodpressures
import org.mockito.kotlin.doReturn
import org.mockito.kotlin.mock
import org.mockito.kotlin.verify
import org.mockito.kotlin.verifyNoMoreInteractions
import org.mockito.kotlin.verifyNoInteractions
import org.mockito.kotlin.whenever
import dagger.Lazy
import io.reactivex.Observable
import org.junit.After
import org.junit.Test
import org.simple.sharedTestCode.TestData
import org.simple.clinic.bp.BloodPressureRepository
import org.simple.clinic.mobius.EffectHandlerTestCase
import org.simple.clinic.util.scheduler.TrampolineSchedulersProvider
import java.util.UUID
class BloodPressureSummaryViewEffectHandlerTest {
private val uiActions = mock<BloodPressureSummaryViewUiActions>()
private val bloodPressureRepository = mock<BloodPressureRepository>()
private val patientUuid = UUID.fromString("6b00207f-a613-4adc-9a72-dff68481a3ff")
private val currentFacility = TestData.facility(uuid = UUID.fromString("2257f737-0e8a-452d-a270-66bdc2422664"))
private val effectHandler = BloodPressureSummaryViewEffectHandler(
bloodPressureRepository = bloodPressureRepository,
schedulersProvider = TrampolineSchedulersProvider(),
facility = Lazy { currentFacility },
uiActions = uiActions
).build()
private val testCase = EffectHandlerTestCase(effectHandler)
@After
fun tearDown() {
testCase.dispose()
}
@Test
fun `when load blood pressures effect is received, then load blood pressures`() {
// given
val numberOfBpsToDisplay = 3
val bloodPressure = TestData.bloodPressureMeasurement(
UUID.fromString("51ac042d-2f70-495c-a3e3-2599d8990da2"),
patientUuid
)
val bloodPressures = listOf(bloodPressure)
whenever(bloodPressureRepository.newestMeasurementsForPatient(patientUuid = patientUuid, limit = numberOfBpsToDisplay)) doReturn Observable.just(bloodPressures)
// when
testCase.dispatch(LoadBloodPressures(patientUuid, numberOfBpsToDisplay))
// then
testCase.assertOutgoingEvents(BloodPressuresLoaded(bloodPressures))
verifyNoInteractions(uiActions)
}
@Test
fun `when load blood pressures count effect is received, then load blood pressures count`() {
// given
val bloodPressuresCount = 10
whenever(bloodPressureRepository.bloodPressureCount(patientUuid)) doReturn Observable.just(bloodPressuresCount)
// when
testCase.dispatch(LoadBloodPressuresCount(patientUuid))
// then
testCase.assertOutgoingEvents(BloodPressuresCountLoaded(bloodPressuresCount))
verifyNoInteractions(uiActions)
}
@Test
fun `when load current facility effect is received, then load current facility`() {
// when
testCase.dispatch(LoadCurrentFacility)
// then
testCase.assertOutgoingEvents(CurrentFacilityLoaded(currentFacility))
verifyNoInteractions(uiActions)
}
@Test
fun `when open blood pressure entry sheet effect is received, then open blood pressure entry sheet`() {
// when
testCase.dispatch(OpenBloodPressureEntrySheet(patientUuid, currentFacility))
// then
testCase.assertNoOutgoingEvents()
verify(uiActions).openBloodPressureEntrySheet(patientUuid, currentFacility)
verifyNoMoreInteractions(uiActions)
}
@Test
fun `when open blood pressure update sheet effect is received, then open blood pressure update sheet`() {
// given
val bloodPressure = TestData.bloodPressureMeasurement(
UUID.fromString("3c59796e-780b-4e2d-9aaf-8cd662975378"),
patientUuid
)
// when
testCase.dispatch(OpenBloodPressureUpdateSheet(bloodPressure))
// then
testCase.assertNoOutgoingEvents()
verify(uiActions).openBloodPressureUpdateSheet(bloodPressure.uuid)
verifyNoMoreInteractions(uiActions)
}
@Test
fun `when show blood pressure history screen effect is received, then show blood pressure history screen`() {
// when
testCase.dispatch(ShowBloodPressureHistoryScreen(patientUuid))
// then
testCase.assertNoOutgoingEvents()
verify(uiActions).showBloodPressureHistoryScreen(patientUuid)
verifyNoMoreInteractions(uiActions)
}
}
| 15 | null | 73 | 236 | ff699800fbe1bea2ed0492df484777e583c53714 | 4,134 | simple-android | MIT License |
app/src/main/kotlin/com/numero/itube/ui/search/item/SearchVideoItem.kt | NUmeroAndDev | 130,776,366 | false | null | package com.numero.itube.ui.search.item
import com.bumptech.glide.load.resource.bitmap.CenterCrop
import com.bumptech.glide.load.resource.bitmap.RoundedCorners
import com.numero.itube.GlideApp
import com.numero.itube.R
import com.numero.itube.model.Video
import com.xwray.groupie.kotlinandroidextensions.Item
import com.xwray.groupie.kotlinandroidextensions.ViewHolder
import kotlinx.android.synthetic.main.view_holder_video.*
class SearchVideoItem(
val video: Video.Search
) : Item() {
override fun getLayout(): Int = R.layout.view_holder_video
override fun bind(viewHolder: ViewHolder, position: Int) {
val context = viewHolder.root.context
viewHolder.titleTextView.text = video.title
val cornerRadius = context.resources.getDimensionPixelSize(R.dimen.thumbnail_corner_radius)
GlideApp.with(context)
.load(video.thumbnailUrl.value)
.transforms(CenterCrop(), RoundedCorners(cornerRadius))
.into(viewHolder.thumbnailImageView)
}
} | 2 | Kotlin | 0 | 3 | f1ed07fd0efb98239563c8940f69d498ba6f2602 | 1,036 | iTube-android | MIT License |
kotlin-modules/kotlin-libraries-1/src/main/kotlin/cn/tuyucheng/taketoday/kotlin/kodein/MongoDao.kt | tuyucheng7 | 576,611,966 | false | null | package cn.tuyucheng.taketoday.kotlin.kodein
class MongoDao : Dao | 0 | null | 6 | 173 | 38b150b1a976112b6cc660d8e0ab4cf438c50958 | 66 | taketoday-tutorial4j | MIT License |
app/src/main/java/com/schaefer/mymovies/domain/mapper/SelfDomainMapper.kt | arturschaefer | 318,792,328 | false | {"Kotlin": 160961} | package com.schaefer.mymovies.domain.mapper
import com.schaefer.mymovies.core.Mapper
import com.schaefer.mymovies.data.model.Self
import com.schaefer.mymovies.domain.model.SelfDomain
class SelfDomainMapper: Mapper<Self, SelfDomain> {
override fun map(source: Self): SelfDomain {
return SelfDomain(source.href.orEmpty())
}
} | 0 | Kotlin | 0 | 0 | a2580e6020ef40b2efbbafd95c3e5db7ab3b1bb3 | 341 | My-Shows | MIT License |
app/src/main/java/eu/ginlo_apps/ginlo/services/LoadPendingTimedMessagesTask.kt | cdskev | 358,279,979 | false | {"Git Config": 1, "Gradle": 3, "Markdown": 5, "Java Properties": 2, "Shell": 1, "Ignore List": 1, "Text": 2, "Proguard": 1, "INI": 1, "XML": 393, "Java": 438, "Kotlin": 168, "JSON": 1, "HTML": 1} | // Copyright (c) 2020-2024 ginlo.net GmbH
package eu.ginlo_apps.ginlo.services
import android.content.Intent
import androidx.core.app.JobIntentService
import eu.ginlo_apps.ginlo.context.SimsMeApplication
import eu.ginlo_apps.ginlo.exception.LocalizedException
import eu.ginlo_apps.ginlo.greendao.MessageDao
import eu.ginlo_apps.ginlo.log.LogUtil
import org.greenrobot.greendao.query.WhereCondition
class LoadPendingTimedMessagesTask : JobIntentService() {
override fun onHandleWork(intent: Intent) {
val messageController = SimsMeApplication.getInstance().messageController
try {
val timedMessageGuids = messageController.timedMessagesGuids
if (timedMessageGuids.size <= 0) {
return
}
val queryBuilder = messageController.dao.queryBuilder()
when {
timedMessageGuids.size == 1 -> queryBuilder.where(MessageDao.Properties.Guid.eq(timedMessageGuids[0]))
timedMessageGuids.size == 2 -> queryBuilder.whereOr(
MessageDao.Properties.Guid.eq(timedMessageGuids[0]),
MessageDao.Properties.Guid.eq(timedMessageGuids[1])
)
timedMessageGuids.size > 2 -> {
val moreConditions = mutableListOf<WhereCondition>()
for (i in 2 until timedMessageGuids.size) {
moreConditions.add(MessageDao.Properties.Guid.eq(timedMessageGuids[i]))
}
queryBuilder.whereOr(
MessageDao.Properties.Guid.eq(timedMessageGuids[0]),
MessageDao.Properties.Guid.eq(timedMessageGuids[1]),
*moreConditions.toTypedArray()
)
}
}
val localMessages = queryBuilder.build().forCurrentThread().list()
val messagesToLoad = mutableListOf<String>()
for (guid in timedMessageGuids) {
val localMessage = localMessages.firstOrNull { it.guid == guid }
if (localMessage?.data == null) {
messagesToLoad.add(guid)
}
}
if (messagesToLoad.size > 0) {
messageController.loadTimedMessages(messagesToLoad)
}
} catch (e: LocalizedException) {
LogUtil.w(
LoadPendingTimedMessagesTask::class.java.simpleName,
"Something wrong when executing LoadPendingTimedMessagesTask",
e
)
}
}
companion object {
fun start() {
val intent = Intent(SimsMeApplication.getInstance(), LoadPendingTimedMessagesTask::class.java)
enqueueWork(SimsMeApplication.getInstance(), LoadPendingTimedMessagesTask::class.java, 1, intent)
}
}
} | 1 | Java | 0 | 5 | 5609a68a539fc5fd9666d3d5f93be750fa5a2b77 | 2,870 | ginlo-android | Apache License 2.0 |
appAndroid/src/main/java/io/github/manuelernesto/meukumbu/ui/send/SendFragment.kt | manuelernesto | 248,243,659 | false | {"Kotlin": 23100} | package io.github.manuelernesto.meukumbu.ui.send
import androidx.lifecycle.ViewModelProvider
import android.os.Bundle
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import io.github.manuelernesto.meukumbu.R
class SendFragment : Fragment() {
private lateinit var viewModel: SendViewModel
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
return inflater.inflate(R.layout.send_fragment, container, false)
}
override fun onActivityCreated(savedInstanceState: Bundle?) {
super.onActivityCreated(savedInstanceState)
viewModel = ViewModelProvider(this).get(SendViewModel::class.java)
// TODO: Use the ViewModel
}
} | 0 | Kotlin | 11 | 62 | 609c8592fcaa5c222e2ba7af4a350565316caa48 | 832 | meu_kumbu | MIT License |
app/src/main/java/com/vlv/githubapicompose/ui/screens/home/widget/Search.kt | KhomDrake | 610,078,208 | false | null | package com.vlv.githubapicompose.ui.screens.home.widget
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.foundation.text.KeyboardActions
import androidx.compose.foundation.text.KeyboardOptions
import androidx.compose.material.Icon
import androidx.compose.material.Text
import androidx.compose.material.TextField
import androidx.compose.material.TextFieldDefaults
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Search
import androidx.compose.runtime.Composable
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.getValue
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.ExperimentalComposeUiApi
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.platform.LocalSoftwareKeyboardController
import androidx.compose.ui.text.input.ImeAction
import androidx.compose.ui.text.input.KeyboardType
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import com.vlv.githubapicompose.ui.theme.GithubApiTheme
import com.vlv.githubapicompose.ui.theme.PrimaryColor
import com.vlv.githubapicompose.ui.theme.SecondaryColor
import com.vlv.githubapicompose.ui.theme.Typography
@OptIn(ExperimentalComposeUiApi::class)
@Composable
fun Search(
hint: String,
modifier: Modifier = Modifier,
initialValue: String = "",
onValueChange: (String) -> Unit = {},
onClickSearchIcon: (String) -> Unit = {}
) {
var actualValue by remember {
mutableStateOf(initialValue)
}
val keyboardController = LocalSoftwareKeyboardController.current
TextField(
value = actualValue,
onValueChange = {
actualValue = it
onValueChange.invoke(it)
},
textStyle = Typography.body2,
singleLine = true,
shape = RoundedCornerShape(8.dp),
modifier = modifier,
keyboardActions = KeyboardActions {
if(actualValue.isEmpty().not()) {
onClickSearchIcon.invoke(actualValue)
}
defaultKeyboardAction(ImeAction.Done)
},
placeholder = {
Text(
text = hint,
style = Typography.body2,
color = Color.Gray
)
},
keyboardOptions = KeyboardOptions(
autoCorrect = true,
imeAction = ImeAction.Search,
keyboardType = KeyboardType.Text
),
trailingIcon = {
Icon(
Icons.Default.Search,
contentDescription = "Search",
modifier = Modifier
.size(24.dp)
.clickable {
if(actualValue.isEmpty()) return@clickable
onClickSearchIcon.invoke(actualValue)
keyboardController?.hide()
},
tint = Color.White
)
},
colors = TextFieldDefaults.textFieldColors(
textColor = Color.White,
backgroundColor = SecondaryColor,
focusedIndicatorColor = Color.Transparent,
unfocusedIndicatorColor = Color.Transparent,
disabledIndicatorColor = Color.Transparent,
cursorColor = PrimaryColor,
focusedLabelColor = PrimaryColor
)
)
}
@Preview
@Composable
fun SearchPreview() {
GithubApiTheme {
var language by remember {
mutableStateOf("kotlin")
}
Search(
initialValue = language,
hint = "Write a language",
modifier = Modifier.fillMaxWidth(),
onValueChange = {
language = it
},
onClickSearchIcon = {
language += "test"
}
)
}
} | 0 | Kotlin | 0 | 0 | 43fc3f907ec07fdfa3b824faaf0cf13eb08ca952 | 4,055 | GithubApi-Compose | MIT License |
csaf-import/src/test/kotlin/io/github/csaf/sbom/retrieval/RetrievedProviderTest.kt | csaf-sbom | 840,395,176 | false | {"Kotlin": 144606, "Java": 5247} | /*
* Copyright (c) 2024, The Authors. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package io.github.csaf.sbom.retrieval
import io.github.csaf.sbom.validation.ValidationException
import kotlin.test.*
import kotlinx.coroutines.channels.toList
import kotlinx.coroutines.test.runTest
class RetrievedProviderTest {
init {
CsafLoader.defaultLoaderFactory = { CsafLoader(mockEngine()) }
}
@Test fun testRetrievedProviderFrom() = runTest { providerTest("example.com") }
@Test
fun testRetrievedProviderFromSecurityTxt() = runTest {
providerTest("provider-with-securitytxt.com")
}
@Test
fun testRetrievedProviderFromDNSPath() = runTest { providerTest("publisher-with-dns.com") }
@Test
fun testRetrievedProviderBrokenDomain() {
val exception =
assertFailsWith<Exception> {
runTest { RetrievedProvider.from("broken-domain.com").getOrThrow() }
}
assertEquals(
"Could not retrieve https://csaf.data.security.broken-domain.com: Not Found",
exception.message
)
}
@Test
fun testRetrievedProviderEmptyIndex() = runTest {
val provider = RetrievedProvider.from("no-distributions.com").getOrThrow()
val expectedDocumentCount = provider.countExpectedDocuments()
assertEquals(0, expectedDocumentCount)
val documentResults = provider.fetchDocuments().toList()
assertTrue(documentResults.isEmpty())
}
@Test
fun testFetchDocumentIndices() = runTest {
val provider = RetrievedProvider.from("example.com").getOrThrow()
val documentIndexResults = provider.fetchDocumentIndices().toList()
assertEquals(
2,
documentIndexResults.size,
"Expected exactly 2 results: One index.txt content and one fetch error"
)
assertTrue(documentIndexResults[0].second.isSuccess)
assertFalse(documentIndexResults[1].second.isSuccess)
}
private suspend fun providerTest(domain: String) {
val provider = RetrievedProvider.from(domain).getOrThrow()
val expectedDocumentCount = provider.countExpectedDocuments()
assertEquals(3, expectedDocumentCount, "Expected 3 documents")
val documentResults = provider.fetchDocuments().toList()
assertEquals(
4,
documentResults.size,
"Expected exactly 4 results: One document, two document errors, one index error"
)
// Check some random property on successful document
assertEquals(
"Bundesamt für Sicherheit in der Informationstechnik",
documentResults[0].getOrThrow().json.document.publisher.name
)
// Check document validation error
val validationException =
assertIs<ValidationException>(documentResults[1].exceptionOrNull()?.cause)
assertContentEquals(
listOf(
"Filename \"bsi-2022_2-01.json\" does not match conformance, expected \"bsi-2022-0001.json\""
),
validationException.errors
)
// Check download error
val fetchException = assertIs<Exception>(documentResults[2].exceptionOrNull()?.cause)
assertEquals(
"Could not retrieve https://$domain/directory/2024/does-not-exist.json: Not Found",
fetchException.message
)
// Check index error
assertEquals(
"Failed to fetch index.txt from directory at https://$domain/invalid-directory",
documentResults[3].exceptionOrNull()?.message
)
}
}
| 17 | Kotlin | 0 | 2 | ce80ae867c05daedd409c17a0a47718895a2a378 | 4,166 | kotlin-csaf | Apache License 2.0 |
editor/src/main/com/mbrlabs/mundus/editor/Editor.kt | mbrlabs | 48,520,201 | false | null | /*
* Copyright (c) 2016. See AUTHORS file.
*
* 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.mbrlabs.mundus.editor
import com.badlogic.gdx.ApplicationListener
import com.badlogic.gdx.InputAdapter
import com.badlogic.gdx.backends.lwjgl3.Lwjgl3WindowAdapter
import com.badlogic.gdx.graphics.Color
import com.badlogic.gdx.graphics.g3d.ModelBatch
import com.badlogic.gdx.graphics.g3d.ModelInstance
import com.badlogic.gdx.utils.GdxRuntimeException
import com.mbrlabs.mundus.editor.core.project.ProjectContext
import com.mbrlabs.mundus.editor.core.project.ProjectManager
import com.mbrlabs.mundus.editor.core.registry.Registry
import com.mbrlabs.mundus.editor.events.ProjectChangedEvent
import com.mbrlabs.mundus.editor.events.SceneChangedEvent
import com.mbrlabs.mundus.editor.input.FreeCamController
import com.mbrlabs.mundus.editor.input.InputManager
import com.mbrlabs.mundus.editor.input.ShortcutController
import com.mbrlabs.mundus.editor.shader.Shaders
import com.mbrlabs.mundus.editor.tools.ToolManager
import com.mbrlabs.mundus.editor.ui.UI
import com.mbrlabs.mundus.editor.utils.Compass
import com.mbrlabs.mundus.editor.utils.GlUtils
import com.mbrlabs.mundus.editor.utils.UsefulMeshs
import org.apache.commons.io.FileUtils
import org.apache.commons.io.FilenameUtils
/**
* @author Marcus Brummer
* @version 07-06-2016
*/
class Editor : Lwjgl3WindowAdapter(), ApplicationListener,
ProjectChangedEvent.ProjectChangedListener,
SceneChangedEvent.SceneChangedListener {
private lateinit var axesInstance: ModelInstance
private lateinit var compass: Compass
private lateinit var camController: FreeCamController
private lateinit var shortcutController: ShortcutController
private lateinit var inputManager: InputManager
private lateinit var projectManager: ProjectManager
private lateinit var registry: Registry
private lateinit var toolManager: ToolManager
override fun create() {
Mundus.setAppIcon()
Mundus.registerEventListener(this)
camController = Mundus.inject()
shortcutController = Mundus.inject()
inputManager = Mundus.inject()
projectManager = Mundus.inject()
registry = Mundus.inject()
toolManager = Mundus.inject()
setupInput()
// TODO dispose this
val axesModel = UsefulMeshs.createAxes()
axesInstance = ModelInstance(axesModel)
// open last edited project or create default project
var context: ProjectContext? = projectManager.loadLastProject()
if (context == null) {
context = createDefaultProject()
}
if(context == null) {
throw GdxRuntimeException("Couldn't open a project")
}
compass = Compass(context.currScene.cam)
// change project; this will fire a ProjectChangedEvent
projectManager.changeProject(context)
}
private fun setupInput() {
// NOTE: order in wich processors are added is important: first added,
// first executed!
inputManager.addProcessor(shortcutController)
inputManager.addProcessor(UI)
// when user does not click on a ui element -> unfocus UI
inputManager.addProcessor(object : InputAdapter() {
override fun touchDown(screenX: Int, screenY: Int, pointer: Int, button: Int): Boolean {
UI.unfocusAll()
return false
}
})
inputManager.addProcessor(toolManager)
inputManager.addProcessor(camController)
toolManager.setDefaultTool()
}
private fun setupSceneWidget() {
val batch = Mundus.inject<ModelBatch>()
val context = projectManager.current()
val scene = context.currScene
val sg = scene.sceneGraph
UI.sceneWidget.setCam(context.currScene.cam)
UI.sceneWidget.setRenderer { cam ->
if (scene.skybox != null) {
batch.begin(scene.cam)
batch.render(scene.skybox.skyboxInstance, scene.environment, Shaders.skyboxShader)
batch.end()
}
sg.update()
sg.render()
toolManager.render()
compass.render(batch)
}
compass.setWorldCam(context.currScene.cam)
camController.setCamera(context.currScene.cam)
UI.sceneWidget.setCam(context.currScene.cam)
context.currScene.viewport = UI.sceneWidget.viewport
}
override fun render() {
GlUtils.clearScreen(Color.WHITE)
UI.act()
camController.update()
toolManager.act()
UI.draw()
}
override fun onProjectChanged(event: ProjectChangedEvent) {
setupSceneWidget()
}
override fun onSceneChanged(event: SceneChangedEvent) {
setupSceneWidget()
}
private fun createDefaultProject(): ProjectContext? {
if (registry.lastOpenedProject == null || registry.projects.size == 0) {
val name = "Default Project"
var path = FileUtils.getUserDirectoryPath()
path = FilenameUtils.concat(path, "MundusProjects")
return projectManager.createProject(name, path)
}
return null
}
override fun closeRequested(): Boolean {
UI.showDialog(UI.exitDialog)
return false
}
override fun resize(width: Int, height: Int) {
UI.viewport.update(width, height, true)
}
override fun pause() {}
override fun resume() {}
override fun dispose() {
Mundus.dispose()
}
}
| 7 | null | 40 | 200 | d3fb804aa780ad95575846b8b9f3b15b6bc9cbe3 | 6,076 | Mundus | Apache License 2.0 |
core/src/screens/MainMenuScreen.kt | PatriotCodes | 114,823,813 | false | null | package screens
import com.alextriukhan.match3.DiamondStoryGame
import com.badlogic.gdx.Gdx
import com.badlogic.gdx.Screen
import com.badlogic.gdx.assets.AssetManager
import com.badlogic.gdx.graphics.GL20
import com.badlogic.gdx.net.HttpRequestBuilder
import com.badlogic.gdx.scenes.scene2d.Stage
import com.badlogic.gdx.scenes.scene2d.ui.Label
import com.badlogic.gdx.scenes.scene2d.ui.Table
import com.badlogic.gdx.scenes.scene2d.ui.TextButton
import enums.Screens
import gameobjects.Level
import utils.GlobalAssets
import utils.setOnClickListener
/*
This Screen should only be disposed only on quit game probably,
as it won't have too much of resources, but that is
a thing to be be considered.
*/
class MainMenuScreen(private val assetManager: AssetManager, private val game: DiamondStoryGame) : Screen {
private val assets = GlobalAssets(assetManager)
private val table = Table()
private val title = Label("Diamond Story", assets.skin)
private val newGameButton = TextButton("Story Mode", assets.skin)
private val stage = Stage()
private val exitButton = TextButton("Quit", assets.skin)
val levelsData = mutableListOf<Level>()
init {
// TODO: this should be moved to GameMapScreen and receive start level to load and range (all is got from stage info file)
var levelNumber = 1
while (true) {
val levelFile = Gdx.files.internal("levels/l$levelNumber.json")
if (levelFile.exists()) {
levelsData.add(levelNumber - 1, HttpRequestBuilder.json.fromJson(Level::class.java,levelFile))
} else {
break
}
levelNumber++
}
table.setFillParent(true)
table.add(title).padBottom(20f).row()
newGameButton.label.setFontScale(0.2f)
table.add(newGameButton).width(100f).padBottom(20f).row()
exitButton.label.setFontScale(0.2f)
table.add(exitButton).width(100f).padBottom(20f).row()
stage.addActor(table)
newGameButton.setOnClickListener {
game.pushScreen(LoadingScreen(assetManager, game, Screens.GAME_SCREEN, levelsData[0]))
}
exitButton.setOnClickListener {
Gdx.app.exit()
}
Gdx.input.inputProcessor = stage
}
override fun hide() {
}
override fun show() {
}
override fun render(delta: Float) {
Gdx.gl.glClearColor(0 / 255f, 0 / 255f, 0 / 255f, 1f)
Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT)
stage.act(delta)
stage.draw()
}
override fun pause() {
}
override fun resume() {
}
override fun resize(width: Int, height: Int) {
}
override fun dispose() {
assetManager.dispose()
}
} | 13 | Kotlin | 0 | 5 | 3c654ce4744c1e0dab9c8727c25738baabfd304f | 2,796 | Diamond-Story | MIT License |
app/src/main/java/com/sdss/workout/setup/SetupFinishScreen.kt | charmas3r | 374,553,434 | true | {"Kotlin": 182117, "Swift": 21514, "Ruby": 2200, "HTML": 560} | package com.sdss.workout.setup
import android.content.Intent
import androidx.compose.foundation.Image
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.material.MaterialTheme
import androidx.compose.material.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import androidx.navigation.NavController
import com.google.accompanist.pager.ExperimentalPagerApi
import com.sdss.workout.R
import com.sdss.workout.intro.IntroScreens
import com.sdss.workout.main.MainScreenActivity
@ExperimentalPagerApi
@Composable
fun SetupFinishScreen(navController: NavController?) {
val context = LocalContext.current
SetupScreenLayout(
onPrimaryClick = { navController?.navigate(IntroScreens.SetupFinish.route) },
secondaryButtonRes = R.string.btn_not_today,
onSecondaryClick = {
context.startActivity(Intent(context, MainScreenActivity::class.java))
},
onBackClick = { navController?.popBackStack() }) {
Column(Modifier.padding(16.dp), horizontalAlignment = Alignment.CenterHorizontally) {
Spacer(modifier = Modifier.height(16.dp))
Image(painter = painterResource(id = R.drawable.workout_item_image_1), contentDescription = null)
Spacer(modifier = Modifier.height(32.dp))
Text(text = stringResource(id = R.string.setup_finish_intro_desc), textAlign = TextAlign.Center)
}
}
}
@ExperimentalPagerApi
@Preview
@Composable
fun SetupFinishPreview() {
MaterialTheme {
SetupFinishScreen(null)
}
} | 0 | Kotlin | 0 | 0 | 946c3deb810fdc01d5738457b2322457f6f08071 | 2,035 | WorkoutApp | Apache License 2.0 |
character-search/src/test/java/com/leinaro/character_search/CharacterSearchViewModelTest.kt | leinaro | 531,701,831 | false | {"Kotlin": 131691, "Java": 176} | package com.leinaro.character_search
import androidx.paging.Pager
import com.leinaro.domain.ui_models.CharacterUiModel
import com.leinaro.domain.usecases.GetCharactersUseCase
import io.mockk.MockKAnnotations
import io.mockk.every
import io.mockk.impl.annotations.MockK
import io.mockk.mockk
import io.mockk.verify
import kotlinx.coroutines.ExperimentalCoroutinesApi
import kotlinx.coroutines.test.TestCoroutineDispatcher
import kotlinx.coroutines.test.runBlockingTest
import org.junit.Before
import org.junit.Rule
import org.junit.Test
@ExperimentalCoroutinesApi
internal class CharacterSearchViewModelTest {
private val testDispatcher = TestCoroutineDispatcher()
@MockK(relaxed = true)
private lateinit var getCharactersUseCase: GetCharactersUseCase
@ExperimentalCoroutinesApi
@get:Rule
var mainCoroutineRule = MainCoroutineRule()
private lateinit var subject: CharacterSearchViewModel
@Before fun setUp() {
MockKAnnotations.init(this, relaxUnitFun = true)
subject = CharacterSearchViewModel(testDispatcher, getCharactersUseCase)
}
@Test fun `Should get characters`() = runBlockingTest {
// given
val pager = mockk<Pager<Int, CharacterUiModel>>(relaxed = true)
every { getCharactersUseCase.execute(any()) } returns pager
// when
subject.getCharacters("")
// then
verify(exactly = 1) { getCharactersUseCase.execute("") }
}
} | 10 | Kotlin | 0 | 0 | 4b421c47e65cb95da310042c6da714ea36d31bc1 | 1,392 | marvel | Creative Commons Zero v1.0 Universal |
mobile_app1/module1096/src/main/java/module1096packageKt0/Foo1.kt | uber-common | 294,831,672 | false | null | package module1096packageKt0;
annotation class Foo1Fancy
@Foo1Fancy
class Foo1 {
fun foo0(){
module1096packageKt0.Foo0().foo2()
}
fun foo1(){
foo0()
}
fun foo2(){
foo1()
}
} | 6 | Java | 6 | 72 | 9cc83148c1ca37d0f2b2fcb08c71ac04b3749e5e | 201 | android-build-eval | Apache License 2.0 |
cli/src/main/kotlin/Main.kt | sschuberth | 110,685,170 | false | null | @file:Suppress("ArgumentListWrapping")
package dev.schuberth.stan.cli
import com.github.ajalt.clikt.core.CliktCommand
import com.github.ajalt.clikt.core.ProgramResult
import com.github.ajalt.clikt.core.UsageError
import com.github.ajalt.clikt.core.context
import com.github.ajalt.clikt.core.subcommands
import com.github.ajalt.clikt.output.MordantHelpFormatter
import com.github.ajalt.clikt.parameters.arguments.argument
import com.github.ajalt.clikt.parameters.arguments.multiple
import com.github.ajalt.clikt.parameters.options.convert
import com.github.ajalt.clikt.parameters.options.default
import com.github.ajalt.clikt.parameters.options.multiple
import com.github.ajalt.clikt.parameters.options.option
import com.github.ajalt.clikt.parameters.options.splitPair
import com.github.ajalt.clikt.parameters.types.enum
import com.github.ajalt.clikt.parameters.types.file
import dev.schuberth.stan.Exporter
import dev.schuberth.stan.model.ConfigurationFile
import dev.schuberth.stan.Parser
import dev.schuberth.stan.utils.Logger
import dev.schuberth.stan.utils.alsoIfNull
import java.io.File
import java.lang.System.Logger.Level
import kotlin.time.measureTimedValue
import org.koin.core.context.GlobalContext.startKoin
import org.koin.dsl.module
fun main(args: Array<String>) = Main().main(args)
class Main : CliktCommand(invokeWithoutSubcommand = true), Logger {
private val userHome by lazy {
val fixedUserHome = System.getProperty("user.home").takeUnless { it.isBlank() || it == "?" } ?: listOfNotNull(
System.getenv("HOME"),
System.getenv("USERPROFILE")
).first {
it.isNotBlank()
}
File(fixedUserHome)
}
private val logLevel by option(
"--log-level", "-l",
help = "The log level to use."
).enum<Level>().default(Level.INFO)
private val configFile by option(
"--config-file", "-c",
help = "The configuration file to use."
).file(mustExist = true, canBeFile = true, canBeDir = false, mustBeWritable = false, mustBeReadable = true)
.default(userHome.resolve(".config/stan/config.json"))
private val parserOptions by option(
"--parser-option", "-p",
help = "A parser specific option. The key is the (case-insensitive) name of the parser, and the value is an " +
"arbitrary key-value pair. For example: -p PostbankPDF=textOutputDir=text/output/dir"
).splitPair().convert { (format, option) ->
require(format in Parser.ALL) {
"Parser format '$format' must be one of ${Parser.ALL.keys}."
}
format to Pair(option.substringBefore("="), option.substringAfter("=", ""))
}.multiple()
private val statementGlobs by argument().multiple()
init {
context {
helpFormatter = { MordantHelpFormatter(context = it, requiredOptionMarker = "*", showDefaultValues = true) }
}
subcommands(ExportCommand(), FilterCommand())
}
override fun run() {
setRootLogLevel(logLevel)
logger.info { "Available parsers: ${Parser.ALL.keys.joinToString()}" }
logger.info { "Available exporters: ${Exporter.ALL.keys.joinToString()}" }
val config = if (configFile.isFile) {
ConfigurationFile.load(configFile)
} else {
ConfigurationFile.loadDefault()
}
val statementFiles = config.getStatementFiles() + ConfigurationFile.resolveGlobs(
statementGlobs.mapTo(mutableSetOf()) { File(it) }
)
if (statementFiles.isEmpty()) throw UsageError("No statement file(s) specified.")
val configModule = module {
single { config }
}
startKoin {
modules(configModule)
}
// Merge the list of pairs into a map which contains each format only once associated to all its options.
val parserOptionsMap = sortedMapOf<String, MutableMap<String, String>>(String.CASE_INSENSITIVE_ORDER)
parserOptions.forEach { (format, option) ->
val parserSpecificOptionsMap = parserOptionsMap.getOrPut(format) { mutableMapOf() }
parserSpecificOptionsMap[option.first] = option.second
}
val (parsedStatements, duration) = measureTimedValue {
statementFiles.mapNotNull {
val file = it.normalize()
runCatching {
val parserEntry = Parser.ALL.entries.find { (_, parser) -> parser.isApplicable(file) }
parserEntry?.let { (name, parser) ->
print("Parsing statement '$file'... ")
parser.parse(file, parserOptionsMap[name].orEmpty()).also { statementsFromFile ->
println(
"recognized $name statement dated from ${statementsFromFile.fromDate} to " +
"${statementsFromFile.toDate}."
)
}
}.alsoIfNull {
println("No applicable parser found for file '$file'.")
}
}.onFailure { e ->
System.err.println("Error parsing '$file'.")
e.printStackTrace()
}.getOrNull()
}
}
println("Successfully parsed ${parsedStatements.size} of ${statementFiles.size} statement(s) in $duration.\n")
if (parsedStatements.isEmpty()) {
System.err.println("No statements found.")
throw ProgramResult(2)
}
println("Checking parsed statements for consistency...")
val sortedStatements = parsedStatements.toSortedSet(compareBy { it.fromDate })
sortedStatements.zipWithNext().forEach { (curr, next) ->
if (curr.bankId != next.bankId) {
System.err.println(
"Statements '${curr.filename}' (${curr.bankId}) and '${next.filename}' (${next.bankId}) do not " +
"belong to the same bank."
)
throw ProgramResult(2)
}
if (curr.accountId != next.accountId) {
System.err.println(
"Statements '${curr.filename}' (${curr.accountId}) and '${next.filename}' (${next.accountId}) do " +
"not belong to the same account."
)
throw ProgramResult(2)
}
if (curr.toDate.plusDays(1) != next.fromDate) {
System.err.println(
"Statements '${curr.filename}' (${curr.toDate}) and '${next.filename}' (${next.fromDate}) are " +
"not consecutive."
)
throw ProgramResult(2)
}
if (curr.balanceNew != next.balanceOld) {
System.err.println(
"Balances of statements '${curr.filename}' (${curr.balanceNew}) and '${next.filename}' " +
"(${next.balanceOld}) are not successive."
)
throw ProgramResult(2)
}
}
println(
"All ${sortedStatements.size} parsed statements of originally ${statementFiles.size} statements passed " +
"the consistency checks.\n"
)
currentContext.findOrSetObject { sortedStatements }
}
}
| 0 | null | 2 | 18 | 2862becd5c276ae39448879a424f4149ca06e8ab | 7,435 | stan | Apache License 2.0 |
localization/src/commonMain/kotlin/org/timemates/app/localization/EnglishStrings.kt | timemates | 575,537,317 | false | null | package org.timemates.app.localization
import io.timemates.sdk.authorization.sessions.types.value.ConfirmationCode
import io.timemates.sdk.timers.types.value.TimerDescription
import io.timemates.sdk.timers.types.value.TimerName
import io.timemates.sdk.users.profile.types.value.UserDescription
import io.timemates.sdk.users.profile.types.value.UserName
object EnglishStrings : Strings {
override val appName: String = "TimeMates"
override val start: String = "Start"
override val nextStep: String = "Next step"
override val authorization: String = "Authorization"
override val authorizationDescription: String = """
Welcome to $appName! Please provide your email address to proceed with the
authorization process. We will send a verification code to your email to confirm your
identity.
""".trimIndent()
override val confirmation: String = "Confirmation"
override val confirmationCode: String = "Confirmation code"
override val confirmationDescription: String = "We’ve just sent a letter with confirmation code to your email address. We do this to confirm that you’re the owner of this email."
override val email: String = "Email address"
override val changeEmail: String = "Change email"
override val emailSizeIsInvalid: String = "Email address size should be in range of 5 and 200 symbols"
override val emailIsInvalid: String = "Email address is invalid."
override val codeSizeIsInvalid: String = "Code size should be ${ConfirmationCode.SIZE} symbols length"
override val codeIsInvalid: String = "Confirmation code should consist only from [a-Z] and [0-9]"
override val unknownFailure: String = "Unknown failure happened"
override val confirmationAttemptFailed: String = "Confirmation code is invalid. Recheck and try again."
override val tooManyAttempts: String = "Too many attempts."
override val dismiss: String = "Dismiss"
override val done: String = "Done"
override val almostDone: String = "Almost done"
override val configureNewAccountDescription: String = "Welcome to TimeMates! Let’s start our journey by configuring your profile details."
override val aboutYou: String = "About you"
override val yourName: String = "Your name"
override val nameSizeIsInvalid: String = "Name size should be in range of ${UserName.SIZE_RANGE.first} to ${UserName.SIZE_RANGE.last} symbols."
override val nameIsInvalid: String = "Name consists from illegal characters."
override val aboutYouSizeIsInvalid: String = "User description should be in range of ${UserDescription.SIZE_RANGE.first} and ${UserDescription.SIZE_RANGE.last} symbols."
override val timerSettings: String = "Edit timer"
override val description: String = "Description"
override val name: String = "Name"
override val workTime: String = "Work time (min)"
override val restTime: String = "Rest time (min)"
override val every: String = "Every"
override val minutes: String = "Minutes"
override val advancedRestSettingsDescription: String = "Enable big rest time (extended rest every X rounds)."
override val publicManageTimerStateDescription: String = "Everyone can manage timer state"
override val confirmationRequiredDescription: String = "Always require confirmation before round start"
override val timerNameSizeIsInvalid: String = "Name size should be in range of ${TimerName.SIZE_RANGE.first} to ${TimerName.SIZE_RANGE.last} symbols."
override val timerDescriptionSizeIsInvalid: String = "Timer description should be in range of ${TimerDescription.SIZE_RANGE.first} and ${TimerDescription.SIZE_RANGE.last} symbols."
override val save: String = "Save"
override val welcome: String = "Welcome to TimeMates"
override val welcomeDescription: String = "Unlock Your Productivity: Seamlessly Organize Tasks, Collaborate Effortlessly, and Achieve your Goals."
override val letsStart: String = "Let’s start"
override val timerCreation: String = "Add timer"
override val noTimers: String = "You don't have any timers yet."
override val confirmationWaitingTimerDescription: String = "Waiting for confirmation."
override val alreadyExists: String = "It already exists or functionality isn't supposed to be used twice."
override val invalidArgument: String = "Invalid input information."
override val notFound: String = "Entity is not found."
override val unauthorized: String = "Your authorized was whether terminated or expired, please relogin."
override val unavailable: String = "Service is not available at the moment, please try again later."
override val unsupported: String = "This functionality is not yet supported."
override fun internalError(message: String): String {
return "Internal server failure has happened, details: $message"
}
override fun inactiveTimerDescription(daysSincePaused: Int): String {
return if (daysSincePaused == 0) "Last activity was today" else "Last activity was $daysSincePaused days ago"
}
override fun runningTimerDescription(people: Int): String {
return if (people == 0) "You are using this timer." else "You and $people other people are using this timer."
}
}
| 21 | null | 0 | 27 | af5f6048c2cef30ac56d80754de54849650d78d2 | 5,240 | app | MIT License |
src/test/kotlin/ExecutorServiceTest.kt | syahrulfahmi | 734,462,073 | false | {"Kotlin": 34990} | import org.junit.jupiter.api.Test
import java.util.Date
import java.util.concurrent.Executors
class ExecutorServiceTest {
@Test
fun testSingleThreadPool() {
val executorService = Executors.newSingleThreadExecutor()
repeat(10) {
val runnable = Runnable {
Thread.sleep(1000)
println("DONE $it, ${Thread.currentThread().name} ${Date()}")
}
executorService.execute(runnable)
}
println("MENUNGGU")
Thread.sleep(11_000)
println("SELESAI")
}
@Test
fun testFixThreadPool() {
val executorService = Executors.newFixedThreadPool(3)
repeat(10) {
val runnable = Runnable {
Thread.sleep(1000)
println("DONE $it, ${Thread.currentThread().name} ${Date()}")
}
executorService.execute(runnable)
}
println("MENUNGGU")
Thread.sleep(11_000)
println("SELESAI")
}
@Test
fun testCacheThreadPool() {
val executorService = Executors.newCachedThreadPool()
repeat(10) {
val runnable = Runnable {
Thread.sleep(1000)
println("DONE $it, ${Thread.currentThread().name} ${Date()}")
}
executorService.execute(runnable)
}
println("MENUNGGU")
Thread.sleep(11_000)
println("SELESAI")
}
} | 0 | Kotlin | 0 | 0 | df7b4f7b8226cc657d15b750b716b1b3ecd0e64f | 1,440 | learn-kotlin-coroutines | MIT License |
src/test/kotlin/com/github/ovargasmahisoft/jdbcplugin/utils/TemplateTest.kt | ovargasmahisoft | 298,445,393 | false | null | package com.github.ovargasmahisoft.jdbcplugin.utils
import com.github.ovargasmahisoft.jdbcplugin.actions.GenerateCodeAction
import groovy.text.GStringTemplateEngine
import org.junit.Assert
import org.junit.Test
import java.util.Collections
class TemplateTest {
class Dummy(val item: String, val items: List<Dummy> = Collections.emptyList())
@Test
fun testGroovyTemplate() {
val templateText = GenerateCodeAction::class.java.getResource("/template/template.grv").readText()
val engine = GStringTemplateEngine()
val template = engine
.createTemplate(templateText)
.make(
mapOf(
Pair("table", Dummy("value item", listOf(
Dummy("1"),
Dummy("2"),
Dummy("3")
)))
)
)
val value = template.toString()
Assert.assertEquals("", value)
}
} | 0 | Kotlin | 0 | 1 | f915709b7a17330852896deeca9ce3a8f65cdc79 | 969 | jdbc-plugin | Apache License 2.0 |
src/main/kotlin/no/nav/familie/ef/sak/behandlingsflyt/steg/BeregnYtelseSteg.kt | navikt | 206,805,010 | false | null | package no.nav.familie.ef.sak.behandlingsflyt.steg
import no.nav.familie.ef.sak.behandling.domain.Behandling
import no.nav.familie.ef.sak.behandling.domain.BehandlingType
import no.nav.familie.ef.sak.beregning.BeregningService
import no.nav.familie.ef.sak.beregning.tilInntektsperioder
import no.nav.familie.ef.sak.fagsak.FagsakService
import no.nav.familie.ef.sak.felles.dto.Periode
import no.nav.familie.ef.sak.infrastruktur.exception.feilHvis
import no.nav.familie.ef.sak.infrastruktur.featuretoggle.FeatureToggleService
import no.nav.familie.ef.sak.simulering.SimuleringService
import no.nav.familie.ef.sak.tilbakekreving.TilbakekrevingService
import no.nav.familie.ef.sak.tilkjentytelse.TilkjentYtelseService
import no.nav.familie.ef.sak.tilkjentytelse.domain.AndelTilkjentYtelse
import no.nav.familie.ef.sak.tilkjentytelse.domain.TilkjentYtelse
import no.nav.familie.ef.sak.tilkjentytelse.domain.taMedAndelerFremTilDato
import no.nav.familie.ef.sak.vedtak.VedtakService
import no.nav.familie.ef.sak.vedtak.domain.AktivitetType
import no.nav.familie.ef.sak.vedtak.domain.VedtaksperiodeType
import no.nav.familie.ef.sak.vedtak.dto.Avslå
import no.nav.familie.ef.sak.vedtak.dto.Innvilget
import no.nav.familie.ef.sak.vedtak.dto.Opphør
import no.nav.familie.ef.sak.vedtak.dto.VedtakDto
import no.nav.familie.ef.sak.vedtak.dto.erSammenhengende
import no.nav.familie.ef.sak.vedtak.dto.tilPerioder
import org.springframework.stereotype.Service
import java.time.LocalDate
import java.util.UUID
@Service
class BeregnYtelseSteg(private val tilkjentYtelseService: TilkjentYtelseService,
private val beregningService: BeregningService,
private val simuleringService: SimuleringService,
private val vedtakService: VedtakService,
private val tilbakekrevingService: TilbakekrevingService,
private val fagsakService: FagsakService,
private val featureToggleService: FeatureToggleService) : BehandlingSteg<VedtakDto> {
override fun validerSteg(behandling: Behandling) {
}
override fun stegType(): StegType {
return StegType.BEREGNE_YTELSE
}
override fun utførSteg(behandling: Behandling, data: VedtakDto) {
validerGyldigeVedtaksperioder(behandling, data)
val aktivIdent = fagsakService.fagsakMedOppdatertPersonIdent(behandling.fagsakId).hentAktivIdent()
nullstillEksisterendeVedtakPåBehandling(behandling.id)
vedtakService.lagreVedtak(vedtakDto = data, behandlingId = behandling.id)
when (data) {
is Innvilget -> {
opprettTilkjentYtelseForInnvilgetBehandling(data, behandling, aktivIdent)
simuleringService.hentOgLagreSimuleringsresultat(behandling)
}
is Opphør -> {
opprettTilkjentYtelseForOpphørtBehandling(behandling, data, aktivIdent)
simuleringService.hentOgLagreSimuleringsresultat(behandling)
}
is Avslå -> {
simuleringService.slettSimuleringForBehandling(behandling.id)
tilbakekrevingService.slettTilbakekreving(behandling.id)
}
}
}
private fun validerGyldigeVedtaksperioder(behandling: Behandling, data: VedtakDto) {
if (data is Innvilget) {
val harOpphørsperioder = data.perioder.any { it.periodeType == VedtaksperiodeType.MIDLERTIDIG_OPPHØR }
val harInnvilgedePerioder = data.perioder.any { it.periodeType != VedtaksperiodeType.MIDLERTIDIG_OPPHØR }
feilHvis(harOpphørsperioder && !harInnvilgedePerioder) {
"Må ha innvilgelsesperioder i tillegg til opphørsperioder"
}
feilHvis(!behandling.erMigrering() && harPeriodeEllerAktivitetMigrering(data)) {
"Kan ikke inneholde aktivitet eller periode av type migrering"
}
}
}
private fun harPeriodeEllerAktivitetMigrering(data: Innvilget) =
data.perioder.any { it.periodeType == VedtaksperiodeType.MIGRERING || it.aktivitet == AktivitetType.MIGRERING }
private fun nullstillEksisterendeVedtakPåBehandling(behandlingId: UUID) {
tilkjentYtelseService.slettTilkjentYtelseForBehandling(behandlingId)
vedtakService.slettVedtakHvisFinnes(behandlingId)
}
private fun opprettTilkjentYtelseForOpphørtBehandling(behandling: Behandling,
vedtak: Opphør,
aktivIdent: String) {
feilHvis(behandling.type != BehandlingType.REVURDERING) { "Kan kun opphøre ved revurdering" }
val nyeAndeler = andelerForOpphør(behandling, vedtak.opphørFom.atDay(1))
tilkjentYtelseService.opprettTilkjentYtelse(TilkjentYtelse(personident = aktivIdent,
behandlingId = behandling.id,
andelerTilkjentYtelse = nyeAndeler))
}
private fun opprettTilkjentYtelseForInnvilgetBehandling(vedtak: Innvilget,
behandling: Behandling,
aktivIdent: String) {
if (featureToggleService.isEnabled("familie.ef.sak.innvilge-med-opphoer")) {
feilHvis(!vedtak.perioder.erSammenhengende()) { "Periodene må være sammenhengende" }
}
val andelerTilkjentYtelse: List<AndelTilkjentYtelse> = lagBeløpsperioderForInnvilgetVedtak(vedtak, behandling, aktivIdent)
feilHvis(andelerTilkjentYtelse.isEmpty()) { "Innvilget vedtak må ha minimum en beløpsperiode" }
val nyeAndeler = when (behandling.type) {
BehandlingType.FØRSTEGANGSBEHANDLING -> andelerTilkjentYtelse
BehandlingType.REVURDERING -> {
val opphørsperioder = finnOpphørsperioder(vedtak)
andelerForInnvilgetRevurdering(behandling, andelerTilkjentYtelse, opphørsperioder)
}
else -> error("Steg ikke støttet for type=${behandling.type}")
}
tilkjentYtelseService.opprettTilkjentYtelse(TilkjentYtelse(personident = aktivIdent,
behandlingId = behandling.id,
andelerTilkjentYtelse = nyeAndeler))
}
private fun finnOpphørsperioder(vedtak: Innvilget) =
vedtak.perioder.filter { it.periodeType == VedtaksperiodeType.MIDLERTIDIG_OPPHØR }.tilPerioder()
private fun finnInnvilgedePerioder(vedtak: Innvilget) =
vedtak.perioder.filter { it.periodeType != VedtaksperiodeType.MIDLERTIDIG_OPPHØR }.tilPerioder()
private fun lagBeløpsperioderForInnvilgetVedtak(vedtak: Innvilget,
behandling: Behandling,
aktivIdent: String) =
beregningService.beregnYtelse(finnInnvilgedePerioder(vedtak), vedtak.inntekter.tilInntektsperioder())
.map {
AndelTilkjentYtelse(beløp = it.beløp.toInt(),
stønadFom = it.periode.fradato,
stønadTom = it.periode.tildato,
kildeBehandlingId = behandling.id,
personIdent = aktivIdent,
samordningsfradrag = it.beregningsgrunnlag?.samordningsfradrag?.toInt() ?: 0,
inntekt = it.beregningsgrunnlag?.inntekt?.toInt() ?: 0,
inntektsreduksjon = it.beregningsgrunnlag?.avkortningPerMåned?.toInt() ?: 0)
}
private fun andelerForInnvilgetRevurdering(behandling: Behandling,
beløpsperioder: List<AndelTilkjentYtelse>,
opphørsperioder: List<Periode>): List<AndelTilkjentYtelse> {
return behandling.forrigeBehandlingId?.let {
val forrigeTilkjenteYtelse = hentForrigeTilkjenteYtelse(behandling)
return slåSammenAndelerSomSkalVidereføres(beløpsperioder, forrigeTilkjenteYtelse, opphørsperioder)
} ?: beløpsperioder
}
fun slåSammenAndelerSomSkalVidereføres(beløpsperioder: List<AndelTilkjentYtelse>,
forrigeTilkjentYtelse: TilkjentYtelse,
opphørsperioder: List<Periode>): List<AndelTilkjentYtelse> {
val fomPerioder = beløpsperioder.firstOrNull()?.stønadFom ?: LocalDate.MAX
val fomOpphørPerioder = opphørsperioder.firstOrNull()?.fradato ?: LocalDate.MAX
val nyePerioderUtenOpphør = forrigeTilkjentYtelse.taMedAndelerFremTilDato(minOf(fomPerioder, fomOpphørPerioder)) + beløpsperioder
return vurderPeriodeForOpphør(nyePerioderUtenOpphør, opphørsperioder)
}
fun vurderPeriodeForOpphør(andelTilkjentYtelser: List<AndelTilkjentYtelse>,
opphørsperioder: List<Periode>): List<AndelTilkjentYtelse> {
return andelTilkjentYtelser.map {
val tilkjentPeriode = it.periode
if (opphørsperioder.none { periode -> periode.overlapper(tilkjentPeriode) }) {
listOf(it)
} else if (opphørsperioder.any { periode -> periode.omslutter(tilkjentPeriode) }) {
listOf()
} else {
val overlappendeOpphør = opphørsperioder.first { periode -> periode.overlapper(tilkjentPeriode) }
if (overlappendeOpphør.overlapperIStartenAv(tilkjentPeriode)) {
vurderPeriodeForOpphør(listOf(it.copy(stønadFom = overlappendeOpphør.tildato.plusDays(1))), opphørsperioder)
} else if (overlappendeOpphør.overlapperISluttenAv(tilkjentPeriode)) {
vurderPeriodeForOpphør(listOf(it.copy(stønadTom = overlappendeOpphør.fradato.minusDays(1))), opphørsperioder)
} else { // periode blir delt i to av opphold.
vurderPeriodeForOpphør(listOf(it.copy(stønadTom = overlappendeOpphør.fradato.minusDays(1)),
it.copy(stønadFom = overlappendeOpphør.tildato.plusDays(1))), opphørsperioder)
}
}
}.flatten()
}
private fun andelerForOpphør(behandling: Behandling, opphørFom: LocalDate): List<AndelTilkjentYtelse> {
val forrigeTilkjenteYtelse = hentForrigeTilkjenteYtelse(behandling)
feilHvis(forrigeTilkjenteYtelse.andelerTilkjentYtelse.none { andel ->
andel.stønadFom <= opphørFom && andel.stønadTom >= opphørFom
}) { "Opphørsdato sammenfaller ikke med løpende vedtaksperioder" }
return forrigeTilkjenteYtelse.taMedAndelerFremTilDato(opphørFom)
}
private fun hentForrigeTilkjenteYtelse(behandling: Behandling): TilkjentYtelse {
val forrigeBehandlingId = behandling.forrigeBehandlingId
?: error("Finner ikke forrige behandling til behandling=${behandling.id}")
return tilkjentYtelseService.hentForBehandling(forrigeBehandlingId)
}
}
| 6 | Kotlin | 2 | 0 | cc43ffc5d00f8a2ff011cf20d7c2e76844164477 | 11,397 | familie-ef-sak | MIT License |
app/src/test/java/com/kylecorry/trail_sense/tools/tides/domain/DefaultTideSelectionStrategyTest.kt | kylecorry31 | 215,154,276 | false | {"Kotlin": 2589968, "Python": 22919, "HTML": 18863, "Shell": 5290, "CSS": 5120, "JavaScript": 3814, "Batchfile": 2553} | package com.kylecorry.trail_sense.tools.tides.domain
import com.kylecorry.sol.science.oceanography.Tide
import com.kylecorry.sol.time.Time.utc
import com.kylecorry.trail_sense.tools.tides.domain.selection.DefaultTideSelectionStrategy
import kotlinx.coroutines.runBlocking
import org.junit.jupiter.api.Assertions
import org.junit.jupiter.api.Test
import java.time.Instant
internal class DefaultTideSelectionStrategyTest {
@Test
fun getTide() = runBlocking {
val strategy = DefaultTideSelectionStrategy()
val tides = listOf(
TideTable(2, listOf(Tide.high(Instant.ofEpochMilli(100).utc())), null, null),
TideTable(1, listOf(Tide.high(Instant.ofEpochMilli(10).utc())), null, null)
)
Assertions.assertEquals(tides[0], strategy.getTide(tides))
}
@Test
fun getTideEmptyList() = runBlocking {
val strategy = DefaultTideSelectionStrategy()
val tides = emptyList<TideTable>()
Assertions.assertNull(strategy.getTide(tides))
}
} | 456 | Kotlin | 66 | 989 | 41176d17b498b2dcecbbe808fbe2ac638e90d104 | 1,024 | Trail-Sense | MIT License |
app/src/test/java/com/gabcode/compassabout/ui/AboutViewModelTest.kt | gabpa3 | 802,339,168 | false | {"Kotlin": 46620} | package com.gabcode.compassabout.ui
import android.util.Log
import com.gabcode.compassabout.domain.FindCharSequenceOccurrencesUseCase
import com.gabcode.compassabout.domain.FindEveryTenthCharacterUseCase
import com.gabcode.compassabout.domain.GrabContentUseCase
import com.gabcode.compassabout.domain.TenthCharacterDomain
import com.gabcode.compassabout.domain.WordOccurrenceDomain
import com.gabcode.compassabout.util.asResult
import io.mockk.MockKAnnotations
import io.mockk.coEvery
import io.mockk.coVerify
import io.mockk.every
import io.mockk.impl.annotations.MockK
import io.mockk.mockkStatic
import io.mockk.spyk
import io.mockk.unmockkAll
import kotlinx.coroutines.flow.flow
import kotlinx.coroutines.test.runTest
import org.junit.After
import org.junit.Assert.assertTrue
import org.junit.Before
import org.junit.Rule
import org.junit.Test
class AboutViewModelTest {
@get:Rule
val mainDispatcherRule = MainDispatcherRule()
@MockK
private lateinit var grabContentUseCase: GrabContentUseCase
@MockK
private lateinit var findTenthUseCaseMock: FindEveryTenthCharacterUseCase
@MockK
private lateinit var findOccurrencesMock: FindCharSequenceOccurrencesUseCase
private lateinit var sut: AboutViewModel
@Before
fun setUp() {
MockKAnnotations.init(this, relaxed = true)
sut = spyk(AboutViewModel(grabContentUseCase, findTenthUseCaseMock, findOccurrencesMock))
}
@After
fun tearDown() {
unmockkAll()
}
@Test
fun `when fetch content then call grab content usecase`() = runTest {
mockLog()
sut.fetchContent()
coVerify { grabContentUseCase.invoke() }
}
@Test
fun `when start processing data then call usecases`() = runTest {
mockLog()
sut.startProcessingData()
coVerify { findTenthUseCaseMock.invoke() }
coVerify { findOccurrencesMock.invoke() }
}
@Test
fun `when find tenth character use case get data then notify its success state`() = runTest {
mockLog()
val flowResult = flow<Collection<TenthCharacterDomain>> {
val list = listOf(
TenthCharacterDomain('a', 10),
TenthCharacterDomain('b', 20),
TenthCharacterDomain('c', 30)
)
emit(list)
}.asResult()
coEvery { findTenthUseCaseMock.invoke() } returns flowResult
sut.startProcessingData()
val collectUiState = sut.tenthCharacters.value
assertTrue(collectUiState is UIState.Success)
assertTrue((collectUiState as UIState.Success).data.size == 3)
}
@Test
fun `when find tenth character use case result failure then notify its state`() = runTest {
mockLog()
val flowResult = flow<Collection<TenthCharacterDomain>> {
throw IllegalStateException("Error throw in test")
}.asResult()
coEvery { findTenthUseCaseMock.invoke() } returns flowResult
sut.startProcessingData()
val collectUiState = sut.tenthCharacters.value
assertTrue(collectUiState is UIState.Error)
assertTrue((collectUiState as UIState.Error).throwable.message == "Error throw in test")
}
@Test
fun `when find word occurrence use case get result success then notify its state`() = runTest {
mockLog()
val flowResult = flow<Collection<WordOccurrenceDomain>> {
val list = listOf(
WordOccurrenceDomain("<p>", 3),
WordOccurrenceDomain("Hola", 1),
WordOccurrenceDomain("Mundo", 1),
WordOccurrenceDomain("</p>", 1)
)
emit(list)
}.asResult()
coEvery { findOccurrencesMock.invoke() } returns flowResult
sut.startProcessingData()
val collectUiState = sut.wordOccurrences.value
assertTrue(collectUiState is UIState.Success)
assertTrue((collectUiState as UIState.Success).data.size == 4)
}
@Test
fun `when find word occurrence use case result failure then notify its state`() = runTest {
mockLog()
val flowResult = flow<Collection<WordOccurrenceDomain>> {
throw IllegalStateException()
}.asResult()
coEvery { findOccurrencesMock.invoke() } returns flowResult
sut.startProcessingData()
val collectUiState = sut.wordOccurrences.value
assertTrue(collectUiState is UIState.Error)
assertTrue((collectUiState as UIState.Error).throwable is IllegalStateException)
}
private fun mockLog() {
mockkStatic(Log::class)
every { Log.d(any<String>(), any<String>()) } returns 0
}
}
| 0 | Kotlin | 0 | 0 | 9f086a32fc2d3d7c0fc539aa05ffee588ccc1038 | 4,688 | compass-about | Apache License 2.0 |
app/src/test/java/com/gabcode/compassabout/ui/AboutViewModelTest.kt | gabpa3 | 802,339,168 | false | {"Kotlin": 46620} | package com.gabcode.compassabout.ui
import android.util.Log
import com.gabcode.compassabout.domain.FindCharSequenceOccurrencesUseCase
import com.gabcode.compassabout.domain.FindEveryTenthCharacterUseCase
import com.gabcode.compassabout.domain.GrabContentUseCase
import com.gabcode.compassabout.domain.TenthCharacterDomain
import com.gabcode.compassabout.domain.WordOccurrenceDomain
import com.gabcode.compassabout.util.asResult
import io.mockk.MockKAnnotations
import io.mockk.coEvery
import io.mockk.coVerify
import io.mockk.every
import io.mockk.impl.annotations.MockK
import io.mockk.mockkStatic
import io.mockk.spyk
import io.mockk.unmockkAll
import kotlinx.coroutines.flow.flow
import kotlinx.coroutines.test.runTest
import org.junit.After
import org.junit.Assert.assertTrue
import org.junit.Before
import org.junit.Rule
import org.junit.Test
class AboutViewModelTest {
@get:Rule
val mainDispatcherRule = MainDispatcherRule()
@MockK
private lateinit var grabContentUseCase: GrabContentUseCase
@MockK
private lateinit var findTenthUseCaseMock: FindEveryTenthCharacterUseCase
@MockK
private lateinit var findOccurrencesMock: FindCharSequenceOccurrencesUseCase
private lateinit var sut: AboutViewModel
@Before
fun setUp() {
MockKAnnotations.init(this, relaxed = true)
sut = spyk(AboutViewModel(grabContentUseCase, findTenthUseCaseMock, findOccurrencesMock))
}
@After
fun tearDown() {
unmockkAll()
}
@Test
fun `when fetch content then call grab content usecase`() = runTest {
mockLog()
sut.fetchContent()
coVerify { grabContentUseCase.invoke() }
}
@Test
fun `when start processing data then call usecases`() = runTest {
mockLog()
sut.startProcessingData()
coVerify { findTenthUseCaseMock.invoke() }
coVerify { findOccurrencesMock.invoke() }
}
@Test
fun `when find tenth character use case get data then notify its success state`() = runTest {
mockLog()
val flowResult = flow<Collection<TenthCharacterDomain>> {
val list = listOf(
TenthCharacterDomain('a', 10),
TenthCharacterDomain('b', 20),
TenthCharacterDomain('c', 30)
)
emit(list)
}.asResult()
coEvery { findTenthUseCaseMock.invoke() } returns flowResult
sut.startProcessingData()
val collectUiState = sut.tenthCharacters.value
assertTrue(collectUiState is UIState.Success)
assertTrue((collectUiState as UIState.Success).data.size == 3)
}
@Test
fun `when find tenth character use case result failure then notify its state`() = runTest {
mockLog()
val flowResult = flow<Collection<TenthCharacterDomain>> {
throw IllegalStateException("Error throw in test")
}.asResult()
coEvery { findTenthUseCaseMock.invoke() } returns flowResult
sut.startProcessingData()
val collectUiState = sut.tenthCharacters.value
assertTrue(collectUiState is UIState.Error)
assertTrue((collectUiState as UIState.Error).throwable.message == "Error throw in test")
}
@Test
fun `when find word occurrence use case get result success then notify its state`() = runTest {
mockLog()
val flowResult = flow<Collection<WordOccurrenceDomain>> {
val list = listOf(
WordOccurrenceDomain("<p>", 3),
WordOccurrenceDomain("Hola", 1),
WordOccurrenceDomain("Mundo", 1),
WordOccurrenceDomain("</p>", 1)
)
emit(list)
}.asResult()
coEvery { findOccurrencesMock.invoke() } returns flowResult
sut.startProcessingData()
val collectUiState = sut.wordOccurrences.value
assertTrue(collectUiState is UIState.Success)
assertTrue((collectUiState as UIState.Success).data.size == 4)
}
@Test
fun `when find word occurrence use case result failure then notify its state`() = runTest {
mockLog()
val flowResult = flow<Collection<WordOccurrenceDomain>> {
throw IllegalStateException()
}.asResult()
coEvery { findOccurrencesMock.invoke() } returns flowResult
sut.startProcessingData()
val collectUiState = sut.wordOccurrences.value
assertTrue(collectUiState is UIState.Error)
assertTrue((collectUiState as UIState.Error).throwable is IllegalStateException)
}
private fun mockLog() {
mockkStatic(Log::class)
every { Log.d(any<String>(), any<String>()) } returns 0
}
}
| 0 | Kotlin | 0 | 0 | 9f086a32fc2d3d7c0fc539aa05ffee588ccc1038 | 4,688 | compass-about | Apache License 2.0 |
app/src/test/java/dev/zezula/books/viewmodel/ShelvesViewModelTest.kt | zezulaon | 589,699,261 | false | {"Kotlin": 433845} | package dev.zezula.books.viewmodel
import dev.zezula.books.MainDispatcherRule
import dev.zezula.books.data.model.shelf.previewShelfEntities
import dev.zezula.books.data.source.db.ShelfAndBookDao
import dev.zezula.books.di.appUnitTestModule
import dev.zezula.books.ui.screen.shelves.ShelvesViewModel
import kotlinx.coroutines.ExperimentalCoroutinesApi
import kotlinx.coroutines.flow.collect
import kotlinx.coroutines.launch
import kotlinx.coroutines.test.UnconfinedTestDispatcher
import kotlinx.coroutines.test.runTest
import org.junit.Before
import org.junit.Rule
import org.junit.Test
import org.koin.test.KoinTest
import org.koin.test.KoinTestRule
import org.koin.test.inject
import kotlin.test.assertEquals
import kotlin.test.assertFalse
import kotlin.test.assertNull
import kotlin.test.assertTrue
/**
* The [androidx.lifecycle.ViewModel] tests use Repositories/UseCases initialized with fake data sources (DAO, Network)
* to test flow coming from the data layer. On the other hand, flow emissions (mostly UI state emissions) are tested via
* [kotlinx.coroutines.flow.StateFlow]'s current value - tests validates the [androidx.lifecycle.ViewModel]'s latest
* UI state.
*
* For the StateFlow object to work in these tests, there must be at least one collector for the given flow. Also all
* coroutines that collect these flows have to be cancelled at the end of each test.
*
* More info:
* https://developer.android.com/kotlin/flow/test#statein
* https://developer.android.com/kotlin/coroutines/test
*/
@OptIn(ExperimentalCoroutinesApi::class)
class ShelvesViewModelTest : KoinTest {
private val viewModel: ShelvesViewModel by inject()
private val shelfAndBookDao: ShelfAndBookDao by inject()
// Rule that replaces main dispatcher used in ViewModel's scope with a test dispatcher used in these tests.
@get:Rule
val mainDispatcherRule = MainDispatcherRule()
@get:Rule
val koinTestRule = KoinTestRule.create {
modules(appUnitTestModule)
}
private val shelvesTestData = previewShelfEntities
@Before
fun setupRepository() = runTest {
shelfAndBookDao.addOrUpdate(shelvesTestData)
}
@Test
fun shelves_are_initialized() = runTest {
val collectJob = launch(UnconfinedTestDispatcher()) { viewModel.uiState.collect() }
// Check that UI state in viewModel has same amount of shelves as test data
assertEquals(shelvesTestData.size, viewModel.uiState.value.shelves.size)
collectJob.cancel()
}
@Test
fun new_shelf_can_be_created() = runTest {
val collectJob = launch(UnconfinedTestDispatcher()) { viewModel.uiState.collect() }
val createdShelfTitle = "test shelf title"
viewModel.createShelf(createdShelfTitle)
// Check that the UI state was updated with the new shelf
assertTrue(viewModel.uiState.value.shelves.any { it.title == createdShelfTitle })
collectJob.cancel()
}
@Test
fun shelf_can_be_updated() = runTest {
val collectJob = launch(UnconfinedTestDispatcher()) { viewModel.uiState.collect() }
val shelfToUpdate = viewModel.uiState.value.shelves.first()
val updatedShelfTitle = "test update shelf title"
viewModel.updateShelf(shelfToUpdate, updatedShelfTitle)
// Check that the UI state was updated with the new shelf
assertTrue(viewModel.uiState.value.shelves.any { it.title == updatedShelfTitle })
collectJob.cancel()
}
@Test
fun shelf_can_be_deleted() = runTest {
val collectJob = launch(UnconfinedTestDispatcher()) { viewModel.uiState.collect() }
val shelfToDelete = viewModel.uiState.value.shelves.first()
viewModel.deleteShelf(shelfToDelete)
// Check that the UI state was updated with the new shelf
assertFalse(viewModel.uiState.value.shelves.contains(shelfToDelete))
collectJob.cancel()
}
@Test
fun on_edit_button_click_shows_dialog() = runTest {
val collectJob = launch(UnconfinedTestDispatcher()) { viewModel.uiState.collect() }
// Check initial state -> no shelf is selected and no dialog is being shown
assertNull(viewModel.uiState.value.selectedShelf)
assertFalse(viewModel.uiState.value.showAddOrEditShelfDialog)
val shelfToEdit = viewModel.uiState.value.shelves.first()
viewModel.onEditShelfClicked(shelfToEdit)
// Check that correct shelf is selected and the dialog is being shown
assertEquals(shelfToEdit, viewModel.uiState.value.selectedShelf)
assertTrue(viewModel.uiState.value.showAddOrEditShelfDialog)
collectJob.cancel()
}
}
| 1 | Kotlin | 0 | 6 | 606a11a634b93212a25fad92bfab54f80dd8e5cd | 4,670 | my-library | Apache License 2.0 |
lomout-config/src/test/kotlin/net/pototskiy/apps/lomout/api/script/MainAndIdeLoggerTest.kt | pavru | 172,818,183 | false | null | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package net.pototskiy.apps.lomout.api.script
import org.junit.jupiter.api.parallel.Execution
import org.junit.jupiter.api.parallel.ExecutionMode
@Execution(ExecutionMode.CONCURRENT)
internal class MainAndIdeLoggerTest {
@org.junit.jupiter.api.Test
fun info() {
val logger = MainAndIdeLogger()
logger.info("Test message", Exception("Test exception"))
assert(true)
}
@org.junit.jupiter.api.Test
fun warn() {
val logger = MainAndIdeLogger()
logger.warn("Test message", Exception("Test exception"))
assert(true)
}
@org.junit.jupiter.api.Test
fun error() {
val logger = MainAndIdeLogger()
logger.error("Test message", Exception("Test exception"))
assert(true)
}
@org.junit.jupiter.api.Test
fun trace() {
val logger = MainAndIdeLogger()
logger.trace("Test message", Exception("Test exception"))
assert(true)
}
@org.junit.jupiter.api.Test
fun debug() {
val logger = MainAndIdeLogger()
logger.debug("Test message", Exception("Test exception"))
assert(true)
}
}
| 0 | Kotlin | 1 | 0 | 96b9715fab77ade907948527e1bfeb4c210ba988 | 1,949 | lomout | Apache License 2.0 |
analysis/analysis-api-fir/src/org/jetbrains/kotlin/analysis/api/fir/scopes/KtFirPackageScope.kt | JetBrains | 3,432,266 | false | {"Kotlin": 78943108, "Java": 6823266, "Swift": 4063298, "C": 2609288, "C++": 1970234, "Objective-C++": 171723, "JavaScript": 138329, "Python": 59488, "Shell": 32312, "TypeScript": 22800, "Objective-C": 22132, "Lex": 21352, "Groovy": 17400, "Batchfile": 11748, "CSS": 11368, "Ruby": 10470, "Dockerfile": 9857, "EJS": 5241, "HTML": 4877, "CMake": 4448, "Pascal": 1698, "FreeMarker": 1393, "Roff": 725, "Scala": 80} | /*
* Copyright 2010-2020 JetBrains s.r.o. and Kotlin Programming Language contributors.
* Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file.
*/
package org.jetbrains.kotlin.analysis.api.fir.scopes
import org.jetbrains.kotlin.analysis.api.fir.KaFirSession
import org.jetbrains.kotlin.analysis.api.lifetime.KaLifetimeToken
import org.jetbrains.kotlin.analysis.api.lifetime.withValidityAssertion
import org.jetbrains.kotlin.analysis.api.scopes.KaScope
import org.jetbrains.kotlin.analysis.api.scopes.KaScopeNameFilter
import org.jetbrains.kotlin.analysis.api.symbols.KaCallableSymbol
import org.jetbrains.kotlin.analysis.api.symbols.KaClassifierSymbol
import org.jetbrains.kotlin.analysis.api.symbols.KaConstructorSymbol
import org.jetbrains.kotlin.analysis.api.symbols.KaPackageSymbol
import org.jetbrains.kotlin.fir.scopes.impl.FirPackageMemberScope
import org.jetbrains.kotlin.name.FqName
import org.jetbrains.kotlin.name.Name
internal class KaFirPackageScope(
private val fqName: FqName,
private val analysisSession: KaFirSession,
) : KaScope {
override val token: KaLifetimeToken get() = analysisSession.token
private val firScope: FirPackageMemberScope by lazy(LazyThreadSafetyMode.PUBLICATION) {
FirPackageMemberScope(fqName, analysisSession.useSiteSession)
}
override fun getPossibleCallableNames(): Set<Name> = withValidityAssertion {
DeclarationsInPackageProvider.getTopLevelCallableNamesInPackageProvider(fqName, analysisSession)
}
override fun getPossibleClassifierNames(): Set<Name> = withValidityAssertion {
DeclarationsInPackageProvider.getTopLevelClassifierNamesInPackageProvider(fqName, analysisSession)
}
override fun getCallableSymbols(nameFilter: KaScopeNameFilter): Sequence<KaCallableSymbol> = withValidityAssertion {
firScope.getCallableSymbols(getPossibleCallableNames().filter(nameFilter), analysisSession.firSymbolBuilder)
}
override fun getCallableSymbols(names: Collection<Name>): Sequence<KaCallableSymbol> = withValidityAssertion {
firScope.getCallableSymbols(names, analysisSession.firSymbolBuilder)
}
override fun getClassifierSymbols(nameFilter: KaScopeNameFilter): Sequence<KaClassifierSymbol> = withValidityAssertion {
firScope.getClassifierSymbols(getPossibleClassifierNames().filter(nameFilter), analysisSession.firSymbolBuilder)
}
override fun getClassifierSymbols(names: Collection<Name>): Sequence<KaClassifierSymbol> = withValidityAssertion {
firScope.getClassifierSymbols(names, analysisSession.firSymbolBuilder)
}
override fun getConstructors(): Sequence<KaConstructorSymbol> = withValidityAssertion {
emptySequence()
}
override fun getPackageSymbols(nameFilter: KaScopeNameFilter): Sequence<KaPackageSymbol> = withValidityAssertion {
sequence {
analysisSession.useSitePackageProvider.getSubPackageFqNames(fqName, analysisSession.targetPlatform, nameFilter).forEach {
yield(analysisSession.firSymbolBuilder.createPackageSymbol(fqName.child(it)))
}
}
}
}
| 180 | Kotlin | 5642 | 48,082 | 2742b94d9f4dbdb1064e65e05682cb2b0badf2fc | 3,175 | kotlin | Apache License 2.0 |
backend/src/main/kotlin/com/pao/repositories/Repo.kt | DesenvolvimentoSistemasSoftware | 771,009,250 | false | {"Kotlin": 58514, "HTML": 73} | package com.pao.repositories
import com.pao.data.classes.Pedido
import com.pao.data.classes.User
import com.pao.data.table.PedidoTable
import com.pao.data.table.UserTable
import org.jetbrains.exposed.sql.insert
import com.pao.repositories.DatabaseFactory.dbQuery
import org.jetbrains.exposed.sql.ResultRow
import org.jetbrains.exposed.sql.select
import org.jetbrains.exposed.sql.update
import org.jetbrains.exposed.sql.and
class Repo {
// User functions in database
suspend fun addUser(user: User) {
dbQuery{
UserTable.insert { ut->
ut[UserTable.email] = user.email
ut[UserTable.nome] = user.nome
ut[UserTable.senha] = user.senha
}
}
}
suspend fun findUserByEmail(email:String) = dbQuery {
UserTable.select { UserTable.email.eq(email) }
.map { rowToUser(it) }
.singleOrNull()
}
private fun rowToUser(row:ResultRow?): User? {
if (row == null) {
return null
}
return User(
nome = row[UserTable.nome],
email = row[UserTable.email],
senha = row[UserTable.senha]
)
}
// Pedido functions in database
suspend fun addPedido(ord: Pedido, email: String) {
dbQuery {
PedidoTable.insert { pt->
pt[PedidoTable.id] = ord.id
pt[PedidoTable.userEmail] = email
pt[PedidoTable.valorTotal] = ord.valorTotal
pt[PedidoTable.status] = ord.status
}
}
}
suspend fun getAllPedidos(email: String):List<Pedido> = dbQuery {
PedidoTable.select {
PedidoTable.userEmail.eq(email)
}.mapNotNull { rowToPedido(it) }
}
suspend fun updatePedidoStatus(id:String, email:String, newStatus:String){
dbQuery {
PedidoTable.update(
where = {
(PedidoTable.id eq id) and (PedidoTable.userEmail eq email)
},
){
it[PedidoTable.status] = newStatus
}
}
}
private fun rowToPedido(row:ResultRow?): Pedido? {
if (row == null) {
return null
}
return Pedido(
id = row[PedidoTable.id],
valorTotal = row[PedidoTable.valorTotal],
status = row[PedidoTable.status]
)
}
}
| 10 | Kotlin | 0 | 0 | 45a29b24dea733b0d2b342097fdcb345debcce3b | 2,412 | Paozim | MIT License |
core/data/src/main/java/com/nyinyihtunlwin/data/model/response/RefreshTokenResponse.kt | nyinyihtunlwin-codigo | 802,104,160 | false | {"Kotlin": 149133} | package com.nyinyihtunlwin.data.model.response
import kotlinx.serialization.SerialName
import kotlinx.serialization.Serializable
@Serializable
data class RefreshTokenResponse(
@SerialName("access_token")
val accessToken: String? = null,
@SerialName("token_type")
val tokenType: String? = null,
@SerialName("expires_in")
val expiresIn: Int? = null,
@SerialName("refresh_token")
val refreshToken: String? = null,
@SerialName("created_at")
val createdAt: Int? = null
)
| 1 | Kotlin | 0 | 0 | afadf7187c23f4abee41e9ff16c5d0544af4b996 | 508 | nimble-survey | Apache License 2.0 |
kohii-sample/src/main/java/kohii/v1/sample/ui/overlay/VideoItemHolder.kt | fuxingkai | 223,119,865 | true | {"Kotlin": 565036, "Java": 28428, "Prolog": 2839} | /*
* Copyright (c) 2019 <NAME>, <EMAIL>
*
* 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 kohii.v1.sample.ui.overlay
import android.view.LayoutInflater
import android.view.View
import android.view.View.OnClickListener
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.TextView
import androidx.core.view.isVisible
import androidx.recyclerview.selection.ItemDetailsLookup.ItemDetails
import kohii.v1.core.Playback
import kohii.v1.core.Rebinder
import kohii.v1.sample.R
import kohii.v1.sample.data.Video
import kotlin.properties.Delegates
internal class VideoItemHolder(
inflater: LayoutInflater,
parent: ViewGroup,
private val clickListener: OnClickListener
) : BaseViewHolder(inflater, R.layout.holder_video_text_overlay, parent),
Playback.Callback,
Playback.StateListener,
OnClickListener {
override fun onClick(v: View?) {
clickListener.onItemClick(v!!, null, adapterPosition, itemId, rebinder)
}
val videoTitle = itemView.findViewById(R.id.videoTitle) as TextView
internal val thumbnail = itemView.findViewById(R.id.videoImage) as ImageView
internal val playerViewContainer = itemView.findViewById(R.id.playerViewContainer) as ViewGroup
internal val videoInfo = itemView.findViewById(R.id.videoInfo) as TextView
init {
itemView.findViewById<View>(R.id.playerContainer)
.setOnClickListener(this)
}
internal var videoData: Video? by Delegates.observable<Video?>(
initialValue = null,
onChange = { _, _, value ->
if (value != null) {
val firstItem = value.playlist.first()
videoImage = firstItem.image
videoFile = firstItem.sources.first()
.file
} else {
videoImage = null
videoFile = null
}
}
)
internal var videoFile: String? = null
internal var videoImage: String? = null
internal val videoTag: String?
get() = this.videoFile?.let { "$it::$adapterPosition" }
// Trick
internal val rebinder: Rebinder?
get() = this.videoTag?.let { Rebinder(it) }
override fun onRecycled(success: Boolean) {
super.onRecycled(success)
this.videoData = null
thumbnail.isVisible = true
}
override fun beforePlay(playback: Playback) {
thumbnail.isVisible = false
}
override fun afterPause(playback: Playback) {
thumbnail.isVisible = true
}
override fun onEnded(playback: Playback) {
thumbnail.isVisible = true
}
override fun onInActive(playback: Playback) {
thumbnail.isVisible = true
}
// Selection
fun getItemDetails(): ItemDetails<Rebinder> {
return object : ItemDetails<Rebinder>() {
override fun getSelectionKey() = rebinder
override fun getPosition() = adapterPosition
}
}
}
| 0 | null | 0 | 0 | 5306f7d543220eff30e149afca91c76fb0a87f21 | 3,287 | kohii | Apache License 2.0 |
vector/src/main/java/im/vector/app/core/ui/views/QrCodeImageView.kt | tchapgouv | 340,329,238 | false | null | /*
* Copyright 2020 New Vector Ltd
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package varta.cdac.app.core.ui.views
import android.content.Context
import android.graphics.Color
import android.util.AttributeSet
import androidx.appcompat.widget.AppCompatImageView
import varta.cdac.app.core.qrcode.toBitMatrix
import varta.cdac.app.core.qrcode.toBitmap
class QrCodeImageView @JvmOverloads constructor(
context: Context, attrs: AttributeSet? = null, defStyleAttr: Int = 0
) : AppCompatImageView(context, attrs, defStyleAttr) {
private var data: String? = null
init {
setBackgroundColor(Color.WHITE)
}
fun setData(data: String) {
this.data = data
render()
}
override fun onSizeChanged(w: Int, h: Int, oldw: Int, oldh: Int) {
super.onSizeChanged(w, h, oldw, oldh)
render()
}
private fun render() {
data
?.takeIf { height > 0 }
?.let {
val bitmap = it.toBitMatrix(height).toBitmap()
post { setImageBitmap(bitmap) }
}
}
}
| 55 | null | 6 | 9 | b248ca2dbb0953761d2780e4fba756acc3899958 | 1,623 | tchap-android | Apache License 2.0 |
src/main/kotlin/pl/jwizard/core/radioplayback/rmf/RmfApiResponse.kt | jwizard-bot | 512,298,084 | false | {"Kotlin": 272965} | /*
* Copyright (c) 2024 by JWizard
* Originally developed by <NAME> <https://miloszgilga.pl>
*/
package pl.jwizard.core.radioplayback.rmf
import com.google.gson.JsonElement
data class RmfApiResponse(
val author: String,
val title: String,
val timestamp: Long,
val coverBigUrl: String,
) {
constructor(jsonElement: JsonElement) : this(
jsonElement.asJsonObject["author"].asString,
jsonElement.asJsonObject["title"].asString,
jsonElement.asJsonObject["timestamp"].asLong,
jsonElement.asJsonObject["coverBigUrl"].asString,
)
}
| 1 | Kotlin | 0 | 2 | d177ef4ba3b65c87581afff5be8832bcef43012c | 543 | jwizard-core | Apache License 2.0 |
arranger-runtime/src/main/java/dev/mkeeda/arranger/runtime/Run.kt | mkeeda | 565,651,877 | false | null | package dev.mkeeda.arranger.runtime
import androidx.compose.runtime.BroadcastFrameClock
import androidx.compose.runtime.Composable
import androidx.compose.runtime.Composition
import androidx.compose.runtime.CompositionContext
import androidx.compose.runtime.Recomposer
import androidx.compose.runtime.snapshots.Snapshot
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.coroutineScope
import kotlinx.coroutines.delay
import kotlinx.coroutines.job
import kotlinx.coroutines.launch
fun DocumentNode.setContent(
parent: CompositionContext,
content: @Composable () -> Unit
): Composition {
return Composition(DocumentNodeApplier(this), parent).apply {
setContent(content)
}
}
suspend fun CoroutineScope.document(content: @Composable DocumentScope.() -> Unit) {
val rootNode = GroupNode()
val clock = BroadcastFrameClock()
val composeContext = coroutineContext + clock
launch(composeContext) {
while(true) {
clock.sendFrame(0L)
println("-------output--------")
println(rootNode.render())
println("-------output end--------")
delay(100)
}
}
coroutineScope {
val recomposer = Recomposer(composeContext)
val scope = object : DocumentScope {}
val composition = rootNode.setContent(recomposer) {
scope.content()
}
var applyScheduled = false
val snapshotHandle = Snapshot.registerGlobalWriteObserver {
if (!applyScheduled) {
applyScheduled = true
launch {
applyScheduled = false
Snapshot.sendApplyNotifications()
}
}
}
launch(composeContext) {
recomposer.runRecomposeAndApplyChanges()
}
composeContext.job.invokeOnCompletion {
println("cancel")
composition.dispose()
snapshotHandle.dispose()
}
}
}
| 0 | Kotlin | 0 | 0 | 839bde2e840f170ce3096012b9ee0699c91bbf7d | 1,998 | arranger | Apache License 2.0 |
app/src/main/java/com/example/android/politicalpreparedness/election/VoterInfoViewModel.kt | FAdiGabriele | 395,675,118 | false | {"Kotlin": 52031} | package com.example.android.politicalpreparedness.election
import android.content.Context
import android.content.Intent
import android.net.Uri
import androidx.lifecycle.*
import com.example.android.politicalpreparedness.network.models.Address
import com.example.android.politicalpreparedness.network.models.Division
import com.example.android.politicalpreparedness.network.models.Election
import com.example.android.politicalpreparedness.network.models.VoterInfoResponse
import com.example.android.politicalpreparedness.repository.ElectionsRepository
import kotlinx.coroutines.launch
import javax.inject.Inject
class VoterInfoViewModel @Inject constructor(private val repository: ElectionsRepository) : ViewModel() {
val voterInfo : LiveData<VoterInfoResponse> = Transformations.map(repository.voterInfoResponseApiList){ it }
val getMalformedVoterInfoResponse : MutableLiveData<Boolean> = repository.getMalformedVoterInfoResponse
private var _electionFound = MutableLiveData<Election?>()
val electionFound : LiveData<Election?> get() = _electionFound
fun addElectionToDatabase(election: Election){
viewModelScope.launch {
repository.addElection(election)
}
}
fun removeElectionFromDatabase(id : Int){
viewModelScope.launch {
repository.removeElection(id)
}
}
fun getElectionFromDatabase(id : Int){
viewModelScope.launch {
_electionFound.value = repository.getElectionById(id)
}
}
fun getAddressFromDivision(division: Division): Address{
return Address("", "", "", division.state, "")
}
fun getVoterInfoFromApi(address : Address, id : Int){
repository.getVoterInfoFromApi(address, id)
}
fun generateURLIntent(context: Context, url : String){
val uri = Uri.parse(url)
val intent = Intent(Intent.ACTION_VIEW, uri)
context.startActivity(intent)
}
} | 0 | Kotlin | 0 | 0 | 7043c4b6fdb8cc8209c6987a898b2554c7030cb1 | 1,946 | finalUdacityProject | Apache License 2.0 |
src/commonMain/kotlin/fr/acinq/lightning/bin/db/payments/IncomingReceivedWithType.kt | ACINQ | 769,273,066 | false | {"Kotlin": 232917, "Dockerfile": 1575} | /*
* Copyright 2021 ACINQ SAS
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
@file:UseSerializers(
SatoshiSerializer::class,
MilliSatoshiSerializer::class,
ByteVector32Serializer::class,
UUIDSerializer::class,
)
package fr.acinq.lightning.bin.db.payments
import fr.acinq.bitcoin.ByteVector32
import fr.acinq.bitcoin.Satoshi
import fr.acinq.bitcoin.TxId
import fr.acinq.lightning.MilliSatoshi
import fr.acinq.lightning.db.IncomingPayment
import fr.acinq.lightning.bin.db.serializers.v1.ByteVector32Serializer
import fr.acinq.lightning.bin.db.serializers.v1.MilliSatoshiSerializer
import fr.acinq.lightning.bin.db.serializers.v1.UUIDSerializer
import fr.acinq.lightning.bin.db.serializers.v1.SatoshiSerializer
import io.ktor.utils.io.charsets.*
import io.ktor.utils.io.core.*
import kotlinx.serialization.*
import kotlinx.serialization.builtins.SetSerializer
enum class IncomingReceivedWithTypeVersion {
MULTIPARTS_V1,
}
sealed class IncomingReceivedWithData {
@Serializable
sealed class Part : IncomingReceivedWithData() {
sealed class Htlc : Part() {
@Serializable
data class V0(
@Serializable val amount: MilliSatoshi,
@Serializable val channelId: ByteVector32,
val htlcId: Long
) : Htlc()
}
sealed class NewChannel : Part() {
/** V2 supports dual funding. New fields: service/miningFees, channel id, funding tx id, and the confirmation/lock timestamps. Id is removed. */
@Serializable
data class V2(
@Serializable val amount: MilliSatoshi,
@Serializable val serviceFee: MilliSatoshi,
@Serializable val miningFee: Satoshi,
@Serializable val channelId: ByteVector32,
@Serializable val txId: ByteVector32,
@Serializable val confirmedAt: Long?,
@Serializable val lockedAt: Long?,
) : NewChannel()
}
sealed class SpliceIn : Part() {
@Serializable
data class V0(
@Serializable val amount: MilliSatoshi,
@Serializable val serviceFee: MilliSatoshi,
@Serializable val miningFee: Satoshi,
@Serializable val channelId: ByteVector32,
@Serializable val txId: ByteVector32,
@Serializable val confirmedAt: Long?,
@Serializable val lockedAt: Long?,
) : SpliceIn()
}
sealed class FeeCredit : Part() {
@Serializable
data class V0(
val amount: MilliSatoshi
) : FeeCredit()
}
}
companion object {
/** Deserializes a received-with blob from the database using the given [typeVersion]. */
fun deserialize(
typeVersion: IncomingReceivedWithTypeVersion,
blob: ByteArray,
): List<IncomingPayment.ReceivedWith> = DbTypesHelper.decodeBlob(blob) { json, _ ->
when (typeVersion) {
IncomingReceivedWithTypeVersion.MULTIPARTS_V1 -> DbTypesHelper.polymorphicFormat.decodeFromString(SetSerializer(PolymorphicSerializer(Part::class)), json).map {
when (it) {
is Part.Htlc.V0 -> IncomingPayment.ReceivedWith.LightningPayment(
amount = it.amount,
channelId = it.channelId,
htlcId = it.htlcId
)
is Part.NewChannel.V2 -> IncomingPayment.ReceivedWith.NewChannel(
amount = it.amount,
serviceFee = it.serviceFee,
miningFee = it.miningFee,
channelId = it.channelId,
txId = TxId(it.txId),
confirmedAt = it.confirmedAt,
lockedAt = it.lockedAt,
)
is Part.SpliceIn.V0 -> IncomingPayment.ReceivedWith.SpliceIn(
amount = it.amount,
serviceFee = it.serviceFee,
miningFee = it.miningFee,
channelId = it.channelId,
txId = TxId(it.txId),
confirmedAt = it.confirmedAt,
lockedAt = it.lockedAt,
)
is Part.FeeCredit.V0 -> IncomingPayment.ReceivedWith.FeeCreditPayment(
amount = it.amount
)
}
}
}
}
}
}
/** Only serialize received_with into the [IncomingReceivedWithTypeVersion.MULTIPARTS_V1] type. */
fun List<IncomingPayment.ReceivedWith>.mapToDb(): Pair<IncomingReceivedWithTypeVersion, ByteArray>? = map {
when (it) {
is IncomingPayment.ReceivedWith.LightningPayment -> IncomingReceivedWithData.Part.Htlc.V0(
amount = it.amount,
channelId = it.channelId,
htlcId = it.htlcId
)
is IncomingPayment.ReceivedWith.NewChannel -> IncomingReceivedWithData.Part.NewChannel.V2(
amount = it.amount,
serviceFee = it.serviceFee,
miningFee = it.miningFee,
channelId = it.channelId,
txId = it.txId.value,
confirmedAt = it.confirmedAt,
lockedAt = it.lockedAt,
)
is IncomingPayment.ReceivedWith.SpliceIn -> IncomingReceivedWithData.Part.SpliceIn.V0(
amount = it.amount,
serviceFee = it.serviceFee,
miningFee = it.miningFee,
channelId = it.channelId,
txId = it.txId.value,
confirmedAt = it.confirmedAt,
lockedAt = it.lockedAt,
)
is IncomingPayment.ReceivedWith.FeeCreditPayment -> IncomingReceivedWithData.Part.FeeCredit.V0(
amount = it.amount
)
}
}.takeIf { it.isNotEmpty() }?.toSet()?.let {
IncomingReceivedWithTypeVersion.MULTIPARTS_V1 to DbTypesHelper.polymorphicFormat.encodeToString(
SetSerializer(PolymorphicSerializer(IncomingReceivedWithData.Part::class)), it
).toByteArray(Charsets.UTF_8)
}
| 9 | Kotlin | 14 | 99 | 9414518536f32bba8e6c88c809a7e34f8bbdfa85 | 6,859 | phoenixd | Apache License 2.0 |
ground/src/main/java/com/google/android/ground/ui/datacollection/tasks/polygon/DrawAreaTaskMapFragment.kt | google | 127,777,820 | false | {"Kotlin": 1400224} | /*
* Copyright 2023 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.android.ground.ui.datacollection.tasks.polygon
import android.os.Bundle
import androidx.hilt.navigation.fragment.hiltNavGraphViewModels
import androidx.lifecycle.lifecycleScope
import com.google.android.ground.R
import com.google.android.ground.ui.common.AbstractMapFragmentWithControls
import com.google.android.ground.ui.common.BaseMapViewModel
import com.google.android.ground.ui.datacollection.DataCollectionViewModel
import com.google.android.ground.ui.map.CameraPosition
import com.google.android.ground.ui.map.Feature
import com.google.android.ground.ui.map.MapFragment
import dagger.hilt.android.AndroidEntryPoint
import javax.inject.Inject
import kotlinx.coroutines.launch
@AndroidEntryPoint
class DrawAreaTaskMapFragment @Inject constructor() : AbstractMapFragmentWithControls() {
private lateinit var mapViewModel: BaseMapViewModel
private val dataCollectionViewModel: DataCollectionViewModel by
hiltNavGraphViewModels(R.id.data_collection)
private val viewModel: DrawAreaTaskViewModel by lazy {
// Access to this viewModel is lazy for testing. This is because the NavHostController could
// not be initialized before the Fragment under test is created, leading to
// hiltNavGraphViewModels() to fail when called on launch.
val taskId = arguments?.getString(TASK_ID_FRAGMENT_ARG_KEY) ?: error("null taskId fragment arg")
dataCollectionViewModel.getTaskViewModel(taskId) as DrawAreaTaskViewModel
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
mapViewModel = getViewModel(BaseMapViewModel::class.java)
}
override fun getMapViewModel(): BaseMapViewModel = mapViewModel
override fun onMapReady(map: MapFragment) {
super.onMapReady(map)
viewLifecycleOwner.lifecycleScope.launch {
viewModel.draftArea.collect { feature: Feature? ->
map.setFeatures(if (feature == null) setOf() else setOf(feature))
}
}
}
override fun onMapCameraMoved(position: CameraPosition) {
super.onMapCameraMoved(position)
if (!viewModel.isMarkedComplete()) {
val mapCenter = position.coordinates
viewModel.updateLastVertexAndMaybeCompletePolygon(mapCenter) { c1, c2 ->
map.getDistanceInPixels(c1, c2)
}
}
}
companion object {
const val TASK_ID_FRAGMENT_ARG_KEY = "taskId"
}
}
| 225 | Kotlin | 115 | 244 | ee40584064ef2b1fa443f9894d35082b0d2be50d | 2,952 | ground-android | Apache License 2.0 |
ui/ui-core/src/commonMain/kotlin/androidx/ui/core/gesture/GestureUtils.kt | Sathawale27 | 282,379,594 | false | null | /*
* Copyright 2020 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package androidx.compose.ui.gesture
import androidx.compose.ui.input.pointer.PointerInputFilter
import androidx.compose.ui.input.pointer.PointerInputModifier
import androidx.compose.ui.platform.PointerInputChange
import androidx.compose.ui.unit.Duration
import androidx.compose.ui.unit.IntSize
import androidx.compose.ui.unit.inMilliseconds
import androidx.compose.ui.util.fastAny
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Job
import kotlinx.coroutines.launch
import kotlin.coroutines.CoroutineContext
// TODO(shepshapard): This continues to be very confusing to use. Have to come up with a better
// way of easily expressing this.
/**
* Utility method that determines if any pointers are currently in [bounds].
*
* A pointer is considered in bounds if it is currently down and it's current
* position is within the provided [bounds]
*
* @return True if at least one pointer is in bounds.
*/
fun List<PointerInputChange>.anyPointersInBounds(bounds: IntSize) =
fastAny {
it.current.down &&
it.current.position!!.x >= 0 &&
it.current.position.x < bounds.width &&
it.current.position.y >= 0 &&
it.current.position.y < bounds.height
}
internal class PointerInputModifierImpl(override val pointerInputFilter: PointerInputFilter) :
PointerInputModifier
/**
* Run [block] after [duration] time passes using [context].
*
* @return [Job] which is a reference to the running coroutine such that it can be cancelled via [Job.cancel].
*/
internal fun delay(duration: Duration, context: CoroutineContext, block: () -> Unit): Job =
CoroutineScope(context).launch {
kotlinx.coroutines.delay(duration.inMilliseconds())
block()
} | 1 | null | 1 | 1 | 549e3e3003cd308939ff31799cf1250e86d3e63e | 2,379 | androidx | Apache License 2.0 |
src/main/kotlin/com/example/authorizationserver/security/OidcUserInfoService.kt | andersonviudes | 755,300,511 | false | {"Kotlin": 28691} | package com.example.authorizationserver.security
import com.example.authorizationserver.user.User
import org.springframework.security.oauth2.core.oidc.OidcUserInfo
import org.springframework.stereotype.Service
@Service
class OidcUserInfoService(private val userDetailsService: AuthorizationServerUserDetailsService) {
fun loadUser(username: String): OidcUserInfo {
val user = userDetailsService.loadUserByUsername(username) as User
return OidcUserInfo.builder()
.subject(user.identifier.toString())
.name(user.firstName + " " + user.lastName)
.givenName(user.firstName)
.familyName(user.lastName)
.nickname(username)
.preferredUsername(username)
.profile("https://example.com/$username")
.website("https://example.com")
.email(user.email)
.emailVerified(true)
.claim("roles", user.roles)
.zoneinfo("Europe/Berlin")
.locale("de-DE")
.updatedAt("1970-01-01T00:00:00Z")
.build()
}
}
| 0 | Kotlin | 0 | 0 | a7ee6144bc9d19525f66257c8fae69da12cfdeb2 | 1,086 | custom-spring-authorization-server | Apache License 2.0 |
azure-communication-ui/chat/src/test/java/com/azure/android/communication/ui/chat/repository/storage/MessageRepositoryTreeBackedImplDelegateUnitTest.kt | Azure | 429,521,705 | false | {"Kotlin": 2573728, "Java": 167445, "Shell": 3964, "HTML": 1856} | // Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
package com.azure.android.communication.ui.chat.repository.storage
import com.azure.android.communication.ui.chat.repository.MessageRepository
import org.junit.Test
import org.junit.runner.RunWith
import org.mockito.junit.MockitoJUnitRunner
@RunWith(MockitoJUnitRunner::class)
class MessageRepositoryTreeBackedImplDelegateUnitTest {
private fun getMessageRepo(): MessageRepository {
return MessageRepository.createTreeBackedRepository()
}
@Test
fun messageRepositoryListStorage_addPage_test() =
MessageRepositoryUnitTest.addPageTest(getMessageRepo())
@Test
fun messageRepositoryListStorage_removeMessage_test() =
MessageRepositoryUnitTest.removeMessageTest(getMessageRepo())
@Test
fun messageRepositoryListStorage_editMessage_test() =
MessageRepositoryUnitTest.editMessageTest(getMessageRepo())
@Test
fun messageRepositoryListStorage_removeMessageTest() =
MessageRepositoryUnitTest.removeMessageTest(getMessageRepo())
@Test
fun messageRepositoryListStorage_OutOfOrderTest() =
MessageRepositoryUnitTest.outOfOrderTest(getMessageRepo())
@Test
fun messageRepositoryListStorage_indexOfTest() =
MessageRepositoryUnitTest.indexOfTest(getMessageRepo())
}
| 7 | Kotlin | 28 | 24 | d7e46c6063e8e9d3ed548acff2465b5d0f57b1b2 | 1,366 | communication-ui-library-android | MIT License |
src/main/kotlin/service/FriendMessageListener.kt | CoderKuo | 447,180,191 | false | null | package com.dakuo.service
import net.mamoe.mirai.event.events.FriendMessageEvent
import net.mamoe.mirai.message.data.At
import net.mamoe.mirai.message.data.MessageChain
import net.mamoe.mirai.message.data.content
import net.mamoe.mirai.message.data.toPlainText
class FriendMessageListener(private val event: FriendMessageEvent) {
suspend fun monitor(){
val plainText = getPlainText(event.message)
val split = plainText.split(" ")
if (split[0].equals("#setcookie")){
if (split[1].isEmpty()){
event.friend.sendMessage("格式错误! 正确格式: #setcookie cookie")
return
}
CookieService.setCookies(plainText.removePrefix("#setcookie"))
event.friend.sendMessage("设置成功")
return
}
if (split[0].equals("#顶帖")){
if (split.size == 1){
event.friend.sendMessage("格式错误! 正确格式: #顶帖 帖子id")
return
}
val useServerBump = McbbsUseMagic.useServerBump(split[1])
if (useServerBump){
event.friend.sendMessage("success")
}else{
event.friend.sendMessage("error")
}
}
}
private fun getPlainText(str: MessageChain):String{
val content = str.content.toPlainText();
return if (content.equals("")) "" else content.contentToString().trim()
}
} | 0 | Kotlin | 0 | 1 | 921be3bdd69029b0bb595c677bf317859c6f08d5 | 1,414 | McbbsServerBumpPlugin | MIT License |
js/js.translator/testData/incremental/invalidation/gettersAndSettersInlining/main/m.kt | workfilemmfloe | 492,307,576 | false | {"Markdown": 132, "Gradle": 432, "Gradle Kotlin DSL": 645, "Java Properties": 18, "Kotlin": 42515, "Shell": 47, "Ignore List": 21, "Batchfile": 24, "Git Attributes": 9, "Dockerfile": 6, "INI": 166, "Java": 2875, "XML": 662, "Text": 14300, "JavaScript": 309, "JAR Manifest": 2, "Roff": 240, "Roff Manpage": 47, "Protocol Buffer": 13, "Proguard": 14, "AsciiDoc": 1, "YAML": 7, "EditorConfig": 1, "OpenStep Property List": 11, "JSON": 187, "C": 151, "Objective-C": 78, "C++": 273, "LLVM": 1, "Swift": 73, "Pascal": 1, "Python": 5, "CMake": 3, "HTML": 16, "Objective-C++": 12, "Groovy": 20, "Diff": 5, "EJS": 1, "CSS": 6, "JSON with Comments": 12, "JFlex": 2, "Ant Build System": 53, "Dotenv": 5, "Graphviz (DOT)": 84, "Maven POM": 80, "Ruby": 5, "Scala": 1} | fun box(stepId: Int): String {
val parent = Parent("parent")
val child = Child("child")
if (parent.name != "parent") return "fail: initial parent name at step $stepId"
if (child.name != "child") return "fail: initial child name at step $stepId"
parent.name = "updated parent"
if (parent.name != "updated parent") return "fail: updated parent name at step $stepId"
child.name = "updated child"
if (child.name != "updated child") return "fail: updated child name at step $stepId"
if (!parent.isValid) return "fail: parent is invalid at step $stepId"
if (!child.isValid) return "fail: child is invalid at step $stepId"
return "OK"
}
| 4 | null | 1 | 1 | 9ee026819756cebc46bd03e0e5672ecdda5ce9bf | 681 | kotlin | Apache License 2.0 |
Tutorial1-1Basics/src/main/java/com/smarttoolfactory/tutorial1_1basics/chapter6_graphics/Tutorial6_13BorderProgressTimer.kt | SmartToolFactory | 326,400,374 | false | {"Kotlin": 2849459} | package com.smarttoolfactory.tutorial1_1basics.chapter6_graphics
import androidx.compose.animation.core.Animatable
import androidx.compose.animation.core.LinearEasing
import androidx.compose.animation.core.animateFloatAsState
import androidx.compose.animation.core.tween
import androidx.compose.foundation.Canvas
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.material.Button
import androidx.compose.material.Slider
import androidx.compose.material.Text
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.CarRental
import androidx.compose.material3.Icon
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.derivedStateOf
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.drawBehind
import androidx.compose.ui.geometry.CornerRadius
import androidx.compose.ui.geometry.Offset
import androidx.compose.ui.geometry.Rect
import androidx.compose.ui.geometry.RoundRect
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.Path
import androidx.compose.ui.graphics.PathMeasure
import androidx.compose.ui.graphics.drawscope.Stroke
import androidx.compose.ui.graphics.drawscope.clipPath
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
import kotlin.math.roundToInt
@Preview
@Composable
fun Tutorial6_13Screen() {
TutorialContent()
}
@Composable
private fun TutorialContent() {
BorderProgressSample1()
// BorderProgressSample2()
}
@Composable
private fun BorderProgressSample1() {
val startDurationInSeconds = 20
var currentTime by remember {
mutableStateOf(startDurationInSeconds)
}
var targetValue by remember {
mutableStateOf(100f)
}
var timerStarted by remember {
mutableStateOf(false)
}
val progress by animateFloatAsState(
targetValue = targetValue,
animationSpec = tween(startDurationInSeconds * 1000, easing = LinearEasing)
)
LaunchedEffect(key1 = timerStarted) {
if (timerStarted) {
while (currentTime > 0) {
delay(1000)
currentTime--
}
}
timerStarted = false
}
Column(
modifier = Modifier
.fillMaxSize()
.padding(40.dp),
horizontalAlignment = Alignment.CenterHorizontally
) {
// This is the progress path which wis changed using path measure
val pathWithProgress by remember {
mutableStateOf(Path())
}
// using path
val pathMeasure by remember { mutableStateOf(PathMeasure()) }
val path = remember {
Path()
}
Box(contentAlignment = Alignment.Center) {
Canvas(modifier = Modifier.size(250.dp, 140.dp)) {
if (path.isEmpty) {
path.addRoundRect(
RoundRect(
Rect(offset = Offset.Zero, size),
cornerRadius = CornerRadius(60.dp.toPx(), 60.dp.toPx())
)
)
}
pathWithProgress.reset()
pathMeasure.setPath(path, forceClosed = false)
pathMeasure.getSegment(
startDistance = 0f,
stopDistance = pathMeasure.length * progress / 100f,
pathWithProgress,
startWithMoveTo = true
)
clipPath(path) {
drawRect(Color.LightGray)
}
drawPath(
path = path,
style = Stroke(
6.dp.toPx()
),
color = Color.Gray
)
drawPath(
path = pathWithProgress,
style = Stroke(
6.dp.toPx()
),
color = Color.Blue
)
}
Text(text = "$currentTime", fontSize = 40.sp, color = Color.Blue)
}
Spacer(modifier = Modifier.height(20.dp))
Box(contentAlignment = Alignment.Center) {
Canvas(modifier = Modifier.size(250.dp, 140.dp)) {
if (path.isEmpty) {
path.addRoundRect(
RoundRect(
Rect(offset = Offset.Zero, size),
cornerRadius = CornerRadius(60.dp.toPx(), 60.dp.toPx())
)
)
}
pathWithProgress.reset()
pathMeasure.setPath(path, forceClosed = false)
pathMeasure.getSegment(
startDistance = 0f,
stopDistance = pathMeasure.length * progress.roundToInt() / 100f,
pathWithProgress,
startWithMoveTo = true
)
clipPath(path) {
drawRect(Color.LightGray)
}
drawPath(
path = path,
style = Stroke(
6.dp.toPx()
),
color = Color.Gray
)
drawPath(
path = pathWithProgress,
style = Stroke(
6.dp.toPx()
),
color = Color.Blue
)
}
Text(text = "$currentTime", fontSize = 40.sp, color = Color.Blue)
}
Spacer(modifier = Modifier.height(20.dp))
Box(contentAlignment = Alignment.Center) {
Canvas(modifier = Modifier.size(250.dp, 140.dp)) {
if (path.isEmpty) {
path.addRoundRect(
RoundRect(
Rect(offset = Offset.Zero, size),
cornerRadius = CornerRadius(60.dp.toPx(), 60.dp.toPx())
)
)
}
pathWithProgress.reset()
pathMeasure.setPath(path, forceClosed = false)
pathMeasure.getSegment(
startDistance = 0f,
stopDistance = pathMeasure.length * ((currentTime.toFloat() / startDurationInSeconds)),
pathWithProgress,
startWithMoveTo = true
)
clipPath(path) {
drawRect(Color.LightGray)
}
drawPath(
path = path,
style = Stroke(
6.dp.toPx()
),
color = Color.Gray
)
drawPath(
path = pathWithProgress,
style = Stroke(
6.dp.toPx()
),
color = Color.Blue
)
}
Text(text = "$currentTime", fontSize = 40.sp, color = Color.Blue)
}
Spacer(modifier = Modifier.height(20.dp))
Button(
modifier = Modifier.fillMaxWidth(),
onClick = {
if (currentTime > 0) {
targetValue = 0f
timerStarted = true
} else {
currentTime = startDurationInSeconds
timerStarted = true
}
}) {
Text(text = "Start Timer")
}
Text(
text = "currentTime: $currentTime, " +
"progress: ${progress.toInt()}",
color = if (progress == 0f) Color.DarkGray else Color.Red
)
}
}
@Preview
@Composable
fun BorderProgressSample2() {
val pathMeasure by remember { mutableStateOf(PathMeasure()) }
val path = remember {
Path()
}
val pathWithProgress by remember {
mutableStateOf(Path())
}
val animatable = remember {
Animatable(0f)
}
val isFilled by remember {
derivedStateOf { animatable.value == 100f }
}
val coroutineScope = rememberCoroutineScope()
Column(
modifier = Modifier.fillMaxSize().padding(16.dp)
) {
// Text("Progress: ${animatable.value.toInt()}")
Slider(
value = animatable.value,
onValueChange = {
coroutineScope.launch {
animatable.animateTo(it)
}
},
valueRange = 0f..100f
)
Icon(
modifier = Modifier.size(128.dp)
.drawBehind {
if (path.isEmpty) {
path.addRoundRect(
RoundRect(
Rect(offset = Offset.Zero, size),
cornerRadius = CornerRadius(16.dp.toPx(), 16.dp.toPx())
)
)
pathMeasure.setPath(path, forceClosed = false)
}
pathWithProgress.reset()
pathMeasure.setPath(path, forceClosed = false)
pathMeasure.getSegment(
startDistance = 0f,
stopDistance = pathMeasure.length * animatable.value / 100f,
pathWithProgress,
startWithMoveTo = true
)
drawPath(
path = path,
style = Stroke(
4.dp.toPx()
),
color = Color.Black
)
drawPath(
path = pathWithProgress,
style = Stroke(
4.dp.toPx()
),
color = Color.Blue
)
},
tint = if (isFilled) Color.Blue else Color.Black,
imageVector = Icons.Default.CarRental,
contentDescription = null
)
}
} | 4 | Kotlin | 312 | 3,006 | efea98b63e63a85b80f7dc1bd4ca6d769e35905d | 10,991 | Jetpack-Compose-Tutorials | Apache License 2.0 |
android/wearable/src/main/java/me/tinykitten/trainlcd/wearable/DataClass.kt | TrainLCD | 217,714,638 | false | null | package me.tinykitten.trainlcd.wearable
data class WearablePayload(
var stateKey: String,
var stationName: String,
var stationNameRoman: String,
var stationNumber: String,
var badLocationAccuracy: Boolean,
var isNextLastStop: Boolean
)
| 36 | null | 1 | 40 | 9864ca58c30edfbae3897500ddb79fa634ca4115 | 249 | MobileApp | MIT License |
2022/Ktor/WebServers/src/main/kotlin/StaticContents_0.kt | kyoya-p | 253,926,918 | false | null | import io.ktor.http.content.*
import io.ktor.routing.*
import io.ktor.server.engine.*
import io.ktor.server.netty.*
import java.io.File
// implementation("io.ktor:ktor-server-core:1.6.7")
// implementation("io.ktor:ktor-server-netty:1.6.7")
@Suppress("JSON_FORMAT_REDUNDANT")
fun main() {
embeddedServer(Netty, port = 8080) {
routing {
static("static") {
// コンテンツのルートフォルダのデフォルトはカレント実行ディレクトリ(プロジェクトルート)
staticRootFolder = File(System.getProperty("user.dir")) // デフォルト以外を指定する場合
files("css")
files("js")
file("image.png")
file("random.txt", "image.png")
default("index.html")
}
}
}.start(wait = true)
}
| 7 | Kotlin | 0 | 1 | 5cc4121186e8a1cf86725641ffa3d56aa255b04e | 768 | samples | Apache License 2.0 |
fontawesome/src/de/msrd0/fontawesome/icons/FA_FORUMBEE.kt | msrd0 | 363,665,023 | false | null | /* @generated
*
* This file is part of the FontAwesome Kotlin library.
* https://github.com/msrd0/fontawesome-kt
*
* This library is not affiliated with FontAwesome.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package de.msrd0.fontawesome.icons
import de.msrd0.fontawesome.Icon
import de.msrd0.fontawesome.Style
import de.msrd0.fontawesome.Style.BRANDS
/** Forumbee */
object FA_FORUMBEE: Icon {
override val name get() = "Forumbee"
override val unicode get() = "f211"
override val styles get() = setOf(BRANDS)
override fun svg(style: Style) = when(style) {
BRANDS -> """<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 448 512"><path d="M5.8 309.7C2 292.7 0 275.5 0 258.3 0 135 99.8 35 223.1 35c16.6 0 33.3 2 49.3 5.5C149 87.5 51.9 186 5.8 309.7zm392.9-189.2C385 103 369 87.8 350.9 75.2c-149.6 44.3-266.3 162.1-309.7 312 12.5 18.1 28 35.6 45.2 49 43.1-151.3 161.2-271.7 312.3-315.7zm15.8 252.7c15.2-25.1 25.4-53.7 29.5-82.8-79.4 42.9-145 110.6-187.6 190.3 30-4.4 58.9-15.3 84.6-31.3 35 13.1 70.9 24.3 107 33.6-9.3-36.5-20.4-74.5-33.5-109.8zm29.7-145.5c-2.6-19.5-7.9-38.7-15.8-56.8C290.5 216.7 182 327.5 137.1 466c18.1 7.6 37 12.5 56.6 15.2C240 367.1 330.5 274.4 444.2 227.7z"/></svg>"""
else -> null
}
}
| 1 | Kotlin | 0 | 0 | 35406669ca5592ee3480ccfba51a00d975ac07af | 1,755 | fontawesome-kt | Apache License 2.0 |
examples/src/main/kotlin/com/algolia/instantsearch/examples/showcase/view/highlighting/HighlightingShowcase.kt | algolia | 55,971,521 | false | null | package com.algolia.instantsearch.examples.showcase.view.highlighting
import android.os.Bundle
import androidx.appcompat.app.AppCompatActivity
import com.algolia.instantsearch.core.connection.ConnectionHandler
import com.algolia.instantsearch.core.hits.connectHitsView
import com.algolia.instantsearch.examples.R
import com.algolia.instantsearch.searcher.hits.HitsSearcher
import com.algolia.instantsearch.examples.showcase.view.*
import com.algolia.instantsearch.examples.databinding.IncludeSearchBinding
import com.algolia.instantsearch.examples.databinding.ShowcaseHighlightingBinding
import com.algolia.instantsearch.examples.showcase.view.list.movie.Movie
import com.algolia.search.helper.deserialize
class HighlightingShowcase : AppCompatActivity() {
private val searcher = HitsSearcher(client, stubIndexName)
private val connection = ConnectionHandler()
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
val binding = ShowcaseHighlightingBinding.inflate(layoutInflater)
val searchBinding = IncludeSearchBinding.bind(binding.searchBox.root)
setContentView(binding.root)
val adapter = HighlightingAdapter()
connection += searcher.connectHitsView(adapter) { response ->
response.hits.deserialize(Movie.serializer())
}
configureToolbar(binding.toolbar)
configureSearcher(searcher)
configureRecyclerView(binding.hits, adapter)
configureSearchView(searchBinding.searchView, getString(R.string.search_movies))
configureSearchBox(searchBinding.searchView, searcher, connection)
searcher.searchAsync()
}
override fun onDestroy() {
super.onDestroy()
searcher.cancel()
connection.clear()
}
}
| 5 | Kotlin | 22 | 140 | 7feb9f30bd32c963161ceead279d1c4f1525d783 | 1,799 | instantsearch-android | Apache License 2.0 |
src/main/kotlin/ru/ezhov/example/ddd/sample/phone/model/Target.kt | ezhov-da | 310,930,063 | false | null | @file:Suppress("DataClassPrivateConstructor")
package ru.ezhov.example.ddd.sample.phone.model
import arrow.core.Either
sealed class Target(val type: Type) {
data class Phone private constructor(val value: String) : Target(type = Type.PHONE) {
companion object {
private const val VALID_PHONE = "\\d+"
fun of(value: String): Either<ValidationErrors, Phone> {
val errors = mutableListOf<String>()
if (!VALID_PHONE.toRegex().matches(value)) {
errors.add("Bad phone '$value'. Phone must be equal '$VALID_PHONE'")
}
return when (errors.isEmpty()) {
true -> Either.Right(Phone(value = value))
false -> Either.Left(ValidationErrors(errors))
}
}
}
}
data class Email private constructor(val value: String) : Target(type = Type.EMAIL) {
companion object {
private const val VALID_EMAIL = "\\w+@\\w+\\.\\w+"
fun of(value: String): Either<ValidationErrors, Email> {
val errors = mutableListOf<String>()
if (!VALID_EMAIL.toRegex().matches(value)) {
errors.add("Bad email '$value'. Email must be equal '${VALID_EMAIL}'")
}
return when (errors.isEmpty()) {
true -> Either.Right(Email(value = value))
false -> Either.Left(ValidationErrors(errors))
}
}
}
}
}
data class ValidationErrors(val errors: List<String>)
enum class Type {
PHONE,
EMAIL
}
fun main() {
printResult(Target.Phone.of("qweqweqweqweqwe"))
printResult(Target.Phone.of("79564535352"))
printResult(Target.Email.of("kb;dv80atdvasbdv"))
printResult(Target.Email.of("<EMAIL>"))
}
private fun <E, T> printResult(e: Either<E, T>) {
when (e) {
is Either.Left -> println(e.value)
is Either.Right -> println(e.value)
}
} | 0 | Kotlin | 0 | 0 | 34407c25ada74dfd727e583597d1e06b3ca3b236 | 2,021 | learn-kotlin | MIT License |
app/src/main/java/com/amazon/ivs/broadcast/injection/InjectionModule.kt | aws-samples | 408,961,293 | false | null | package com.amazon.ivs.broadcast.injection
import com.amazon.ivs.broadcast.App
import com.amazon.ivs.broadcast.cache.PREFERENCES_NAME
import com.amazon.ivs.broadcast.cache.PreferenceProvider
import com.amazon.ivs.broadcast.cache.SecuredPreferenceProvider
import com.amazon.ivs.broadcast.common.broadcast.BroadcastManager
import dagger.Module
import dagger.Provides
import javax.inject.Singleton
@Module
class InjectionModule(private val context: App) {
@Singleton
@Provides
fun providePreferences() = PreferenceProvider(context, PREFERENCES_NAME)
@Singleton
@Provides
fun provideSecuredPreferences() = SecuredPreferenceProvider(context)
@Singleton
@Provides
fun provideBroadcastManager() = BroadcastManager(context)
}
| 0 | Kotlin | 4 | 9 | 084a2f8f3448041add862156f3fa95ffe3314d8b | 760 | amazon-ivs-broadcast-for-android-demo | MIT No Attribution |
core/src/main/kotlin/com/github/haschi/dominium/haushaltsbuch/core/application/Anwendung.kt | haschi | 52,821,330 | false | null | package com.github.haschi.dominium.haushaltsbuch.core.application
import com.github.haschi.dominium.haushaltsbuch.core.domain.Historie
import org.axonframework.commandhandling.CommandBus
import org.axonframework.commandhandling.gateway.CommandGatewayFactory
import kotlin.reflect.KClass
import org.axonframework.config.Configuration
import org.axonframework.queryhandling.QueryGateway
open class Anwendung(private val konfiguration: Configuration)
{
open fun stop()
{
konfiguration.shutdown()
}
private val commandBus: CommandBus get() = konfiguration.commandBus()
private val commandGatewayFactory
get() = CommandGatewayFactory(commandBus)
private fun <T : Any> gateway(kClass: KClass<T>): T
{
return commandGatewayFactory.createGateway(kClass.java)
}
private val queryGateway: QueryGateway get() = konfiguration.queryGateway()
private val historie: Historie by lazy {
konfiguration.getComponent(Historie::class.java)
}
fun api(): Dominium
{
return Dominium(
gateway(HaushaltsbuchführungApi::class),
gateway(InventurApi::class),
konfiguration.commandGateway(),
queryGateway,
historie)
}
} | 11 | Kotlin | 2 | 4 | e3222c613c369b4a58026ce42c346b575b3082e5 | 1,274 | dominium | MIT License |
demo/src/main/kotlin/zsu/serial/demo1/Demo1.kt | zsqw123 | 759,914,610 | false | {"Kotlin": 400} | package zsu.serial.demo1
import kotlinx.serialization.KSerializer
import kotlinx.serialization.Serializable
import kotlinx.serialization.descriptors.SerialDescriptor
import kotlinx.serialization.encodeToString
import kotlinx.serialization.encoding.Decoder
import kotlinx.serialization.encoding.Encoder
import kotlinx.serialization.json.Json
import kotlin.reflect.KType
import kotlin.reflect.typeOf
@Serializable(Request.Serializer::class)
class Request<T>(
val body: T, val bodyType: KType,
) {
class Serializer<T> : KSerializer<Request<T>> {
override val descriptor: SerialDescriptor = error("")
override fun deserialize(decoder: Decoder): Request<T> = error("")
override fun serialize(encoder: Encoder, value: Request<T>) = error("")
}
}
inline fun <reified T> Request(body: T) = Request(body, typeOf<T>())
fun <T> submitRequest(request: Request<T>) {
println(Json.encodeToString(request))
}
fun main() {
submitRequest(Request(1))
}
| 0 | Kotlin | 0 | 0 | 110f82671670522f8b0e59339fa101f5ac92f7e0 | 984 | KSerializationSample | Apache License 2.0 |
domene/src/main/kotlin/no/nav/tiltakspenger/vedtak/Tiltaksaktivitet.kt | navikt | 487,246,438 | false | null | package no.nav.tiltakspenger.vedtak
import java.time.LocalDate
import java.time.LocalDateTime
// Dokumentert her: https://confluence.adeo.no/display/ARENA/Arena+-+Tjeneste+Webservice+-+TiltakOgAktivitet_v1#ArenaTjenesteWebserviceTiltakOgAktivitet_v1-HentTiltakOgAktiviteterForBrukerResponse
data class Tiltaksaktivitet(
val tiltak: Tiltak, // Det vi får her er teksten i Enumen, ikke koden. Det er litt klønete..
val aktivitetId: String,
val tiltakLokaltNavn: String?,
val arrangør: String?,
val bedriftsnummer: String?,
val deltakelsePeriode: DeltakelsesPeriode,
val deltakelseProsent: Float?,
val deltakerStatus: DeltakerStatus,
val statusSistEndret: LocalDate?,
val begrunnelseInnsøking: String?,
val antallDagerPerUke: Float?,
val tidsstempelHosOss: LocalDateTime,
) : Tidsstempler {
override fun tidsstempelKilde(): LocalDateTime = statusSistEndret?.atStartOfDay() ?: tidsstempelHosOss
override fun tidsstempelHosOss(): LocalDateTime = tidsstempelHosOss
data class DeltakelsesPeriode(
val fom: LocalDate?,
val tom: LocalDate?,
)
companion object {
// https://trello.com/c/KVY0kO8n/129-mapping-av-tiltakstype-fra-s%C3%B8knaden
// Verdiene man kan angi i søknaden har korresponderende kodeverdier i Tiltaksnavn fra Arena
fun mapTiltaksType(tiltaksType: String): Tiltak? =
when (tiltaksType) {
"JOBSOK" -> Tiltak.JOBBK
"PRAKSORD" -> Tiltak.ARBTREN
"AMO" -> Tiltak.GRUPPEAMO
"Annet" -> null // TODO: Hvordan mappe Annet?
else -> null
}
}
enum class Tiltaksgruppe(val navn: String) {
AFT("Arbeidsforberedende trening"),
AMB("Tiltak i arbeidsmarkedsbedrift"),
ARBPRAKS("Arbeidspraksis"),
ARBRREHAB("Arbeidsrettet rehabilitering"),
ARBTREN("Arbeidstrening"),
AVKLARING("Avklaring"),
BEHPSSAM("Behandling - lettere psykiske/sammensatte lidelser"),
ETAB("Egenetablering"),
FORSOK("Forsøk"),
LONNTILS("Lønnstilskudd"),
OPPFOLG("Oppfølging"),
OPPL("Opplæring"),
TILRETTE("Tilrettelegging"),
UTFAS("Tiltak under utfasing"),
VARIGASV("Varig tilrettelagt arbeid"),
JOBBSKAP("Jobbskapingsprosjekter"),
BIO("Bedriftsintern opplæring (BIO)"),
BISTAND("Arbeid med Bistand (AB)"),
INST_S("Nye plasser institusjonelle tiltak"),
MIDSYSS("Midlertidig sysselsetting"),
}
enum class Tiltak(val navn: String, val tiltaksgruppe: Tiltaksgruppe, val rettPåTiltakspenger: Boolean) {
AMBF1("AMB Avklaring (fase 1)", Tiltaksgruppe.UTFAS, true),
KURS("Andre kurs", Tiltaksgruppe.UTFAS, false),
ANNUTDANN("Annen utdanning", Tiltaksgruppe.UTFAS, false),
ABOPPF("Arbeid med bistand A oppfølging", Tiltaksgruppe.UTFAS, true),
ABUOPPF("Arbeid med bistand A utvidet oppfølging", Tiltaksgruppe.UTFAS, true),
ABIST("Arbeid med Bistand (AB)", Tiltaksgruppe.UTFAS, true),
ABTBOPPF("Arbeid med bistand B", Tiltaksgruppe.UTFAS, true),
LONNTILAAP("Arbeidsavklaringspenger som lønnstilskudd", Tiltaksgruppe.FORSOK, false),
ARBFORB("Arbeidsforberedende trening (AFT)", Tiltaksgruppe.AFT, true),
AMO("Arbeidsmarkedsopplæring (AMO)", Tiltaksgruppe.UTFAS, true),
AMOE("Arbeidsmarkedsopplæring (AMO) enkeltplass", Tiltaksgruppe.UTFAS, true),
AMOB("Arbeidsmarkedsopplæring (AMO) i bedrift", Tiltaksgruppe.UTFAS, true),
AMOY("Arbeidsmarkedsopplæring (AMO) yrkeshemmede", Tiltaksgruppe.UTFAS, true),
PRAKSORD("Arbeidspraksis i ordinær virksomhet", Tiltaksgruppe.UTFAS, true),
PRAKSKJERM("Arbeidspraksis i skjermet virksomhet", Tiltaksgruppe.UTFAS, true),
ARBRRHBAG("Arbeidsrettet rehabilitering", Tiltaksgruppe.UTFAS, true),
ARBRRHBSM("Arbeidsrettet rehabilitering - sykmeldt arbeidstaker", Tiltaksgruppe.UTFAS, true),
ARBRRHDAG("Arbeidsrettet rehabilitering (dag)", Tiltaksgruppe.ARBRREHAB, true),
ARBRDAGSM("Arbeidsrettet rehabilitering (dag) - sykmeldt arbeidstaker", Tiltaksgruppe.UTFAS, true),
ARBRRDOGN("Arbeidsrettet rehabilitering (døgn)", Tiltaksgruppe.UTFAS, true),
ARBDOGNSM("Arbeidsrettet rehabilitering (døgn) - sykmeldt arbeidstaker", Tiltaksgruppe.UTFAS, true),
ASV("Arbeidssamvirke (ASV)", Tiltaksgruppe.UTFAS, false),
ARBTREN("Arbeidstrening", Tiltaksgruppe.ARBTREN, true),
ATG("Arbeidstreningsgrupper", Tiltaksgruppe.UTFAS, false),
AVKLARAG("Avklaring", Tiltaksgruppe.AVKLARING, true),
AVKLARUS("Avklaring", Tiltaksgruppe.UTFAS, true),
AVKLARSP("Avklaring - sykmeldt arbeidstaker", Tiltaksgruppe.UTFAS, true),
AVKLARKV("Avklaring av kortere varighet", Tiltaksgruppe.UTFAS, true),
AVKLARSV("Avklaring i skjermet virksomhet", Tiltaksgruppe.UTFAS, true),
BIA("Bedriftsintern attføring", Tiltaksgruppe.UTFAS, false),
BIO("Bedriftsintern opplæring (BIO)", Tiltaksgruppe.BIO, false),
BREVKURS("Brevkurs", Tiltaksgruppe.UTFAS, false),
DIGIOPPARB("Digitalt oppfølgingstiltak for arbeidsledige (jobbklubb)", Tiltaksgruppe.OPPFOLG, true),
DIVTILT("Diverse tiltak", Tiltaksgruppe.UTFAS, false),
ETAB("Egenetablering", Tiltaksgruppe.ETAB, false),
EKSPEBIST("Ekspertbistand", Tiltaksgruppe.TILRETTE, false),
ENKELAMO("Enkeltplass AMO", Tiltaksgruppe.OPPL, true),
ENKFAGYRKE("Enkeltplass Fag- og yrkesopplæring VGS og høyere yrkesfaglig utdanning", Tiltaksgruppe.OPPL, true),
FLEKSJOBB("Fleksibel jobb - lønnstilskudd av lengre varighet", Tiltaksgruppe.UTFAS, false),
TILRTILSK(
"Forebyggings- og tilretteleggingstilskudd IA virksomheter og BHT-honorar",
Tiltaksgruppe.UTFAS,
false
),
KAT("Formidlingstjenester", Tiltaksgruppe.UTFAS, true),
VALS("Formidlingstjenester - Ventelønn", Tiltaksgruppe.UTFAS, true),
FORSAMOENK("Forsøk AMO enkeltplass", Tiltaksgruppe.FORSOK, true),
FORSAMOGRU("Forsøk AMO gruppe", Tiltaksgruppe.FORSOK, false),
FORSFAGENK("Forsøk fag- og yrkesopplæring enkeltplass", Tiltaksgruppe.FORSOK, true),
FORSFAGGRU("Forsøk fag- og yrkesopplæring gruppe", Tiltaksgruppe.FORSOK, false),
FORSHOYUTD("Forsøk høyere utdanning", Tiltaksgruppe.FORSOK, true),
FUNKSJASS("Funksjonsassistanse", Tiltaksgruppe.TILRETTE, true),
GRUNNSKOLE("Grunnskole", Tiltaksgruppe.UTFAS, false),
GRUPPEAMO("Gruppe AMO", Tiltaksgruppe.OPPL, true),
GRUFAGYRKE("Gruppe Fag- og yrkesopplæring VGS og høyere yrkesfaglig utdanning", Tiltaksgruppe.OPPL, true),
HOYEREUTD("Høyere utdanning", Tiltaksgruppe.OPPL, true),
HOYSKOLE("Høyskole/Universitet", Tiltaksgruppe.UTFAS, false),
INDJOBSTOT("Individuell jobbstøtte (IPS)", Tiltaksgruppe.OPPFOLG, true),
IPSUNG("Individuell karrierestøtte (IPS Ung)", Tiltaksgruppe.OPPFOLG, true),
INDOPPFOLG("Individuelt oppfølgingstiltak", Tiltaksgruppe.UTFAS, true),
INKLUTILS("Inkluderingstilskudd", Tiltaksgruppe.TILRETTE, true),
ITGRTILS("Integreringstilskudd", Tiltaksgruppe.UTFAS, false),
JOBBKLUBB("Intern jobbklubb", Tiltaksgruppe.UTFAS, true),
JOBBFOKUS("Jobbfokus/Utvidet formidlingsbistand", Tiltaksgruppe.UTFAS, true),
JOBBK("Jobbklubb", Tiltaksgruppe.OPPFOLG, true),
JOBBBONUS("Jobbklubb med bonusordning", Tiltaksgruppe.UTFAS, true),
JOBBSKAP("Jobbskapingsprosjekter", Tiltaksgruppe.UTFAS, false),
AMBF2("Kvalifisering i arbeidsmarkedsbedrift", Tiltaksgruppe.UTFAS, false),
TESTING("Lenes testtiltak", Tiltaksgruppe.OPPFOLG, false),
STATLAERL("Lærlinger i statlige etater", Tiltaksgruppe.UTFAS, false),
LONNTILS("Lønnstilskudd", Tiltaksgruppe.UTFAS, false),
REAKTUFOR("Lønnstilskudd - reaktivisering av uførepensjonister", Tiltaksgruppe.UTFAS, false),
LONNTILL("Lønnstilskudd av lengre varighet", Tiltaksgruppe.UTFAS, false),
MENTOR("Mentor", Tiltaksgruppe.OPPFOLG, true),
MIDLONTIL("Midlertidig lønnstilskudd", Tiltaksgruppe.LONNTILS, false),
NETTAMO("Nettbasert arbeidsmarkedsopplæring (AMO)", Tiltaksgruppe.UTFAS, true),
NETTKURS("Nettkurs", Tiltaksgruppe.UTFAS, false),
INST_S("Nye plasser institusjonelle tiltak", Tiltaksgruppe.UTFAS, false),
NYTEST("Nytt testtiltak", Tiltaksgruppe.ARBTREN, false),
INDOPPFAG("Oppfølging", Tiltaksgruppe.OPPFOLG, true),
INDOPPFSP("Oppfølging - sykmeldt arbeidstaker", Tiltaksgruppe.UTFAS, true),
PV("Produksjonsverksted (PV)", Tiltaksgruppe.UTFAS, false),
INDOPPRF("Resultatbasert finansiering av formidlingsbistand", Tiltaksgruppe.FORSOK, true),
REFINO("Resultatbasert finansiering av oppfølging", Tiltaksgruppe.FORSOK, true),
SPA("Spa prosjekter", Tiltaksgruppe.UTFAS, true),
SUPPEMP("Supported Employment", Tiltaksgruppe.FORSOK, true),
SYSSLANG("Sysselsettingstiltak for langtidsledige", Tiltaksgruppe.UTFAS, false),
YHEMMOFF("Sysselsettingstiltak for yrkeshemmede", Tiltaksgruppe.UTFAS, false),
SYSSOFF("Sysselsettingstiltak i offentlig sektor for yrkeshemmede", Tiltaksgruppe.UTFAS, false),
LONNTIL("Tidsbegrenset lønnstilskudd", Tiltaksgruppe.UTFAS, false),
TIDSUBLONN("Tidsubestemt lønnstilskudd", Tiltaksgruppe.UTFAS, false),
AMBF3("Tilrettelagt arbeid i arbeidsmarkedsbedrift", Tiltaksgruppe.UTFAS, false),
TILRETTEL("Tilrettelegging for arbeidstaker", Tiltaksgruppe.UTFAS, false),
TILPERBED("Tilretteleggingstilskudd for arbeidssøker", Tiltaksgruppe.UTFAS, true),
TILSJOBB("Tilskudd til sommerjobb", Tiltaksgruppe.LONNTILS, false),
UFØREPENLØ("Uførepensjon som lønnstilskudd", Tiltaksgruppe.UTFAS, false),
UTDYRK("Utdanning", Tiltaksgruppe.UTFAS, true),
UTDPERMVIK("Utdanningspermisjoner", Tiltaksgruppe.UTFAS, false),
VIKARBLED("Utdanningsvikariater", Tiltaksgruppe.UTFAS, false),
UTBHLETTPS("Utredning/behandling lettere psykiske lidelser", Tiltaksgruppe.UTFAS, true),
UTBHPSLD("Utredning/behandling lettere psykiske og sammensatte lidelser", Tiltaksgruppe.UTFAS, true),
UTBHSAMLI("Utredning/behandling sammensatte lidelser", Tiltaksgruppe.UTFAS, true),
UTVAOONAV("Utvidet oppfølging i NAV", Tiltaksgruppe.FORSOK, true),
UTVOPPFOPL("Utvidet oppfølging i opplæring", Tiltaksgruppe.OPPFOLG, true),
VARLONTIL("Varig lønnstilskudd", Tiltaksgruppe.LONNTILS, false),
VATIAROR("Varig tilrettelagt arbeid i ordinær virksomhet", Tiltaksgruppe.VARIGASV, false),
VASV("Varig tilrettelagt arbeid i skjermet virksomhet", Tiltaksgruppe.VARIGASV, false),
VV("Varig vernet arbeid (VVA)", Tiltaksgruppe.UTFAS, false),
VIDRSKOLE("Videregående skole", Tiltaksgruppe.UTFAS, false),
OPPLT2AAR("2-årig opplæringstiltak", Tiltaksgruppe.UTFAS, true),
AB("To be deleted", Tiltaksgruppe.UTFAS, true),
OUTDEF("Ukjent", Tiltaksgruppe.UTFAS, true)
}
enum class DeltakerStatus(val tekst: String) {
AKTUELL("Aktuell"),
AVSLAG("Fått avslag"),
DELAVB("Deltakelse avbrutt"),
FULLF("Fullført"),
GJENN("Gjennomføres"),
GJENN_AVB("Gjennomføring avbrutt"),
GJENN_AVL("Gjennomføring avlyst"),
IKKAKTUELL("Ikke aktuell"),
IKKEM("Ikke møtt"),
INFOMOETE("Informasjonsmøte"),
JATAKK("Takket ja til tilbud"),
NEITAKK("Takket nei til tilbud"),
TILBUD("Godkjent tiltaksplass"),
VENTELISTE("Venteliste")
}
}
| 6 | Kotlin | 0 | 2 | dde1b0532caed17b6bad77e1de4917f829adea1c | 11,729 | tiltakspenger-vedtak | MIT License |
core/designsystem/src/main/java/com/jerryalberto/mmas/core/designsystem/theme/Theme.kt | jchodev | 749,966,300 | false | {"Kotlin": 82580} | package com.jerryalberto.mmas.core.designsystem.theme
import android.app.Activity
import android.os.Build
import androidx.annotation.VisibleForTesting
import androidx.compose.foundation.isSystemInDarkTheme
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.darkColorScheme
import androidx.compose.material3.dynamicDarkColorScheme
import androidx.compose.material3.dynamicLightColorScheme
import androidx.compose.material3.lightColorScheme
import androidx.compose.material3.windowsizeclass.ExperimentalMaterial3WindowSizeClassApi
import androidx.compose.runtime.Composable
import androidx.compose.runtime.SideEffect
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.toArgb
import androidx.compose.ui.platform.LocalConfiguration
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.platform.LocalView
import androidx.core.view.WindowCompat
@VisibleForTesting
val LightColorScheme = lightColorScheme(
primary = Purple40,
onPrimary = Color.White,
primaryContainer = Purple90,
onPrimaryContainer = Purple10,
secondary = Orange40,
onSecondary = Color.White,
secondaryContainer = Orange90,
onSecondaryContainer = Orange10,
tertiary = Blue40,
onTertiary = Color.White,
tertiaryContainer = Blue90,
onTertiaryContainer = Blue10,
error = Red40,
onError = Color.White,
errorContainer = Red90,
onErrorContainer = Red10,
background = DarkPurpleGray99,
onBackground = DarkPurpleGray10,
surface = DarkPurpleGray99,
onSurface = DarkPurpleGray10,
surfaceVariant = PurpleGray90,
onSurfaceVariant = PurpleGray30,
outline = PurpleGray50
)
/**
* Dark default theme color scheme
*/
@VisibleForTesting
val DarkColorScheme = darkColorScheme(
primary = Purple80,
onPrimary = Purple20,
primaryContainer = Purple30,
onPrimaryContainer = Purple90,
secondary = Orange80,
onSecondary = Orange20,
secondaryContainer = Orange30,
onSecondaryContainer = Orange90,
tertiary = Blue80,
onTertiary = Blue20,
tertiaryContainer = Blue30,
onTertiaryContainer = Blue90,
error = Red80,
onError = Red20,
errorContainer = Red30,
onErrorContainer = Red90,
background = DarkPurpleGray10,
onBackground = DarkPurpleGray90,
surface = DarkPurpleGray10,
onSurface = DarkPurpleGray90,
surfaceVariant = PurpleGray30,
onSurfaceVariant = PurpleGray80,
outline = PurpleGray60
)
@OptIn(ExperimentalMaterial3WindowSizeClassApi::class)
@Composable
fun MmasTheme(
darkTheme: Boolean = isSystemInDarkTheme(),
// Dynamic color is available on Android 12+
dynamicColor: Boolean = true,
content: @Composable () -> Unit
) {
val colorScheme = when {
dynamicColor && Build.VERSION.SDK_INT >= Build.VERSION_CODES.S -> {
val context = LocalContext.current
if (darkTheme) dynamicDarkColorScheme(context) else dynamicLightColorScheme(context)
}
darkTheme -> DarkColorScheme
else -> LightColorScheme
}
// val view = LocalView.current
// if (!view.isInEditMode) {
// SideEffect {
// val window = (view.context as Activity).window
// window.statusBarColor = colorScheme.primary.toArgb()
// WindowCompat.getInsetsController(window, view).isAppearanceLightStatusBars = darkTheme
// }
// }
MaterialTheme(
colorScheme = colorScheme,
typography = Typography,
shapes = shapes,
content = content
)
}
@Composable
fun getDimen(): Dimens{
val configuration = LocalConfiguration.current
return if (configuration.screenWidthDp < 600) {
compactDimens
} else {
largeDimens
}
}
val MaterialTheme.dimens
@Composable
get() = getDimen() | 0 | Kotlin | 1 | 2 | c95fed063a20e65fb48a71ad9f3173574f13b6b7 | 3,837 | MMAS-JC | MIT License |
client/app/src/main/java/com/healthc/app/presentation/auth/register/UserInfoFragment.kt | Team-HealthC | 601,915,784 | false | {"Kotlin": 175023} | package com.example.healthc.presentation.auth.register
import android.content.Intent
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Toast
import androidx.databinding.DataBindingUtil
import androidx.fragment.app.Fragment
import androidx.fragment.app.activityViewModels
import androidx.lifecycle.flowWithLifecycle
import androidx.lifecycle.lifecycleScope
import androidx.navigation.fragment.findNavController
import com.example.healthc.R
import com.example.healthc.databinding.FragmentUserInfoBinding
import com.example.healthc.domain.utils.Resource
import com.example.healthc.presentation.auth.AuthViewModel
import com.example.healthc.presentation.home.MainActivity
import com.google.android.material.chip.Chip
import dagger.hilt.android.AndroidEntryPoint
import kotlinx.coroutines.flow.launchIn
import kotlinx.coroutines.flow.onEach
@AndroidEntryPoint
class UserInfoFragment : Fragment() {
private var _binding: FragmentUserInfoBinding? = null
private val binding get() = checkNotNull(_binding)
private val viewModel by activityViewModels<AuthViewModel>()
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View {
_binding = DataBindingUtil.inflate(inflater, R.layout.fragment_user_info, container, false)
binding.viewModel = viewModel
binding.lifecycleOwner = viewLifecycleOwner
return binding.root
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
initView()
observeData()
}
private fun initView(){
binding.allergyChipGroup.setOnCheckedStateChangeListener { group, checkedIds ->
val allergyList : MutableList<String> = mutableListOf()
checkedIds.forEach{ id ->
allergyList.add(group.findViewById<Chip>(id).text.toString())
}
viewModel.setAllergy(allergyList)
}
binding.backButton.setOnClickListener {
findNavController().popBackStack()
}
}
private fun observeData(){
viewModel.signUpEvent.flowWithLifecycle(viewLifecycleOwner.lifecycle)
.onEach {
when(it){
is Resource.Loading ->{
// TODO loading screen
}
is Resource.Success -> {
startMainActivity()
}
is Resource.Failure -> {
Toast.makeText(requireContext(), "회원가입에 실패하였습니다.", Toast.LENGTH_SHORT).show()
}
else -> {}
}
}.launchIn(viewLifecycleOwner.lifecycleScope)
}
private fun startMainActivity(){
val intent = Intent(requireContext(), MainActivity::class.java)
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP)
startActivity(intent)
}
override fun onDestroyView() {
_binding = null
super.onDestroyView()
}
} | 5 | Kotlin | 1 | 2 | d74bff575502c4360e9735e8d558b907240ed4fe | 3,154 | HealthC_Android | MIT License |
core/src/commonTest/kotlin/pw/binom/TestQueueCompose.kt | caffeine-mgn | 182,165,415 | false | null | package pw.binom
import kotlin.test.Test
import kotlin.test.assertEquals
import kotlin.test.fail
import pw.binom.thread.*
class TestQueueCompose {
@Test
fun testFirstEmpty() {
val queue1 = FreezedStack<String>().asFiFoQueue()
val queue2 = FreezedStack<String>().asFiFoQueue()
val queue = queue1 + queue2
queue2.push("1")
queue2.push("2")
assertEquals("1", queue.pop())
assertEquals("2", queue.pop())
try {
queue.pop()
fail()
} catch (e: NoSuchElementException) {
//NOP
}
}
@Test
fun testSecondEmpty() {
val queue1 = FreezedStack<String>().asFiFoQueue()
val queue2 = FreezedStack<String>().asFiFoQueue()
val queue = queue1 + queue2
queue1.push("1")
queue1.push("2")
assertEquals("1", queue.pop())
assertEquals("2", queue.pop())
try {
queue.pop()
fail()
} catch (e: NoSuchElementException) {
//NOP
}
}
@Test
fun testNotFull(){
val queue1 = FreezedStack<String>().asFiFoQueue()
val queue2 = FreezedStack<String>().asFiFoQueue()
val queue = queue1 + queue2
queue2.push("1")
queue1.push("2")
queue2.push("3")
queue1.push("4")
queue2.push("5")
queue2.push("6")
assertEquals("1", queue.pop())
assertEquals("2", queue.pop())
assertEquals("3", queue.pop())
assertEquals("4", queue.pop())
assertEquals("5", queue.pop())
assertEquals("6", queue.pop())
try {
queue.pop()
fail()
} catch (e: NoSuchElementException) {
//NOP
}
}
} | 7 | null | 2 | 59 | 580ff27a233a1384273ef15ea6c63028dc41dc01 | 1,780 | pw.binom.io | Apache License 2.0 |
legacy/src/main/kotlin/rs/emulate/legacy/graphics/GraphicsDecoder.kt | apollo-rsps | 50,723,825 | false | null | package rs.emulate.legacy.graphics
import io.netty.buffer.ByteBuf
import rs.emulate.legacy.archive.Archive
import rs.emulate.legacy.graphics.GraphicsConstants.INDEX_FILE_NAME
import rs.emulate.legacy.graphics.sprite.MediaId
import java.nio.ByteBuffer
/**
* A base class for graphics ArchiveEntry decoders.
*
* @param graphics The [Archive] containing the graphical data.
* @param name The name of the graphic file to decode.
*/
abstract class GraphicsDecoder(graphics: Archive, protected val name: MediaId) {
/**
* The [ByteBuffer] containing the graphic data.
*/
protected val data: ByteBuf = when (name) {
is MediaId.Id -> graphics.entries.find { it.identifier == name.value }?.buffer ?: error("Can't find sprite archive")
is MediaId.Name -> graphics[name.value + ".dat"].buffer
}
/**
* The [ByteBuffer] containing the file indices.
*/
protected val index: ByteBuf = graphics[INDEX_FILE_NAME].buffer
}
| 6 | null | 5 | 12 | fba5069744a04835c23373c1d11f90b201cdc604 | 970 | Vicis | ISC License |
dsl/src/main/kotlin/io/cloudshiftdev/awscdkdsl/services/inspector/CfnResourceGroupPropsDsl.kt | cloudshiftinc | 667,063,030 | false | {"Kotlin": 70198112} | @file:Suppress(
"RedundantVisibilityModifier",
"RedundantUnitReturnType",
"RemoveRedundantQualifierName",
"unused",
"UnusedImport",
"ClassName",
"REDUNDANT_PROJECTION",
"DEPRECATION"
)
package cloudshift.awscdk.dsl.services.inspector
import cloudshift.awscdk.common.CdkDslMarker
import kotlin.Any
import kotlin.collections.Collection
import kotlin.collections.MutableList
import software.amazon.awscdk.IResolvable
import software.amazon.awscdk.services.inspector.CfnResourceGroupProps
/**
* Properties for defining a `CfnResourceGroup`.
*
* Example:
* ```
* // The code below shows an example of how to instantiate this type.
* // The values are placeholders you should change.
* import software.amazon.awscdk.services.inspector.*;
* CfnResourceGroupProps cfnResourceGroupProps = CfnResourceGroupProps.builder()
* .resourceGroupTags(List.of(CfnTag.builder()
* .key("key")
* .value("value")
* .build()))
* .build();
* ```
*
* [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-inspector-resourcegroup.html)
*/
@CdkDslMarker
public class CfnResourceGroupPropsDsl {
private val cdkBuilder: CfnResourceGroupProps.Builder = CfnResourceGroupProps.builder()
private val _resourceGroupTags: MutableList<Any> = mutableListOf()
/**
* @param resourceGroupTags The tags (key and value pairs) that will be associated with the
* resource group. For more information, see
* [Tag](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-resource-tags.html)
* .
*/
public fun resourceGroupTags(vararg resourceGroupTags: Any) {
_resourceGroupTags.addAll(listOf(*resourceGroupTags))
}
/**
* @param resourceGroupTags The tags (key and value pairs) that will be associated with the
* resource group. For more information, see
* [Tag](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-resource-tags.html)
* .
*/
public fun resourceGroupTags(resourceGroupTags: Collection<Any>) {
_resourceGroupTags.addAll(resourceGroupTags)
}
/**
* @param resourceGroupTags The tags (key and value pairs) that will be associated with the
* resource group. For more information, see
* [Tag](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-resource-tags.html)
* .
*/
public fun resourceGroupTags(resourceGroupTags: IResolvable) {
cdkBuilder.resourceGroupTags(resourceGroupTags)
}
public fun build(): CfnResourceGroupProps {
if (_resourceGroupTags.isNotEmpty()) cdkBuilder.resourceGroupTags(_resourceGroupTags)
return cdkBuilder.build()
}
}
| 3 | Kotlin | 0 | 3 | 256ad92aebe2bcf9a4160089a02c76809dbbedba | 2,761 | awscdk-dsl-kotlin | Apache License 2.0 |
domain/src/main/java/com/joeloewi/domain/repository/HoYoLABRepository.kt | joeloewi7178 | 489,906,155 | false | null | package com.joeloewi.domain.repository
import com.joeloewi.domain.entity.BaseResponse
import com.joeloewi.domain.entity.GameRecordCardData
import com.joeloewi.domain.entity.GenshinDailyNoteData
import com.joeloewi.domain.entity.UserFullInfo
interface HoYoLABRepository {
suspend fun getUserFullInfo(cookie: String): Result<UserFullInfo>
suspend fun getGameRecordCard(
cookie: String,
uid: Long
): Result<GameRecordCardData?>
suspend fun getGenshinDailyNote(
cookie: String,
roleId: Long,
server: String,
): Result<GenshinDailyNoteData?>
//uses message, retcode from response
suspend fun changeDataSwitch(
cookie: String,
switchId: Int,
isPublic: Boolean,
gameId: Int
): Result<BaseResponse>
} | 10 | Kotlin | 0 | 3 | 7ad75f550e7b93b6c6372e9f7ad505adadac6d54 | 801 | Croissant | Apache License 2.0 |
core/src/main/java/io/karte/android/core/logger/Appender.kt | plaidev | 208,185,127 | false | {"Kotlin": 857882, "Java": 27008, "Ruby": 13282, "Shell": 3765, "CSS": 157} | //
// Copyright 2020 PLAID, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
package io.karte.android.core.logger
import android.util.Log
internal interface Appender {
fun append(log: LogEvent)
}
internal class ConsoleAppender : Appender {
override fun append(log: LogEvent) {
if (Logger.level > log.level) return
when {
log.level == LogLevel.VERBOSE && log.throwable == null ->
Log.v(log.tag, log.message)
log.level == LogLevel.VERBOSE && log.throwable != null ->
Log.v(log.tag, log.message, log.throwable)
log.level == LogLevel.DEBUG && log.throwable == null ->
Log.d(log.tag, log.message)
log.level == LogLevel.DEBUG && log.throwable != null ->
Log.d(log.tag, log.message, log.throwable)
log.level == LogLevel.INFO && log.throwable == null ->
Log.i(log.tag, log.message)
log.level == LogLevel.INFO && log.throwable != null ->
Log.i(log.tag, log.message, log.throwable)
log.level == LogLevel.WARN && log.throwable == null ->
Log.w(log.tag, log.message)
log.level == LogLevel.WARN && log.throwable != null ->
Log.w(log.tag, log.message, log.throwable)
log.level == LogLevel.ERROR && log.throwable == null ->
Log.e(log.tag, log.message)
log.level == LogLevel.ERROR && log.throwable != null ->
Log.e(log.tag, log.message, log.throwable)
}
}
}
| 3 | Kotlin | 4 | 5 | 01a977dc3b440c998ae860f589987f3e4aaba635 | 2,090 | karte-android-sdk | Apache License 2.0 |
analysis/low-level-api-fir/testData/lazyResolve/compilerRequiredAnnotationsOnProperty.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} | annotation class Anno(val s: String)
@Deprecated("property")
@Anno("property")
@set:Deprecated("setter")
var memberP<caret>roperty = 32
@Deprecated("getter")
@Anno("getter")
get() = field
@Anno("setter")
@setparam:[Deprecated("setparam") Anno("setparam")]
set(value) {
field = value
} | 181 | Kotlin | 5748 | 49,172 | 33eb9cef3d146062c103f9853d772f0a1da0450e | 321 | kotlin | Apache License 2.0 |
feature-nft-impl/src/main/java/jp/co/soramitsu/nft/impl/navigation/NavAction.kt | soramitsu | 278,060,397 | false | null | package jp.co.soramitsu.nft.impl.navigation
sealed interface NavAction {
object BackPressed : NavAction
object QRCodeScanner : NavAction
class ShowError(
val errorTitle: String?,
val errorText: String
) : NavAction
@JvmInline
value class ShowToast(
val toastMessage: String
) : NavAction
@JvmInline
value class ShareText(
val text: String
) : NavAction
}
| 15 | null | 30 | 89 | 1de6dfa7c77d4960eca2d215df2bdcf71a2ef5f2 | 433 | fearless-Android | Apache License 2.0 |
feature/sample/pkg/src/main/java/com/dawn/sample/pkg/feature/data/entity/CountDownList.kt | blank-space | 304,529,347 | false | null | package com.dawn.sample.pkg.feature.data.entity
import com.dawn.base.viewmodel.iface.IBaseList
/**
* @author : LeeZhaoXing
* @date : 2021/9/2
* @desc :
*/
data class CountDownList(val list: MutableList<Long>) : IBaseList {
override fun getDataList(): MutableList<Long> = list
override fun getTotals(): Int = list.size
} | 0 | Kotlin | 2 | 6 | bc95dce263adc6968e1c55eccf18ebfc8362c2b5 | 338 | scaffold | Apache License 2.0 |
app/src/main/java/cn/cqautotest/sunnybeach/ui/activity/UserCenterActivity.kt | anjiemo | 378,095,612 | false | null | package cn.cqautotest.sunnybeach.ui.activity
import android.annotation.SuppressLint
import androidx.activity.viewModels
import androidx.core.content.ContextCompat
import by.kirich1409.viewbindingdelegate.viewBinding
import cn.cqautotest.sunnybeach.R
import cn.cqautotest.sunnybeach.app.AppActivity
import cn.cqautotest.sunnybeach.databinding.UserCenterActivityBinding
import cn.cqautotest.sunnybeach.manager.UserManager
import cn.cqautotest.sunnybeach.model.UserBasicInfo
import cn.cqautotest.sunnybeach.util.*
import cn.cqautotest.sunnybeach.viewmodel.UserViewModel
import com.bumptech.glide.Glide
import com.bumptech.glide.load.engine.DiskCacheStrategy
import java.io.File
/**
* author : A Lonely Cat
* github : https://github.com/anjiemo/SunnyBeach
* time : 2021/10/26
* desc : 个人中心界面
*/
class UserCenterActivity : AppActivity(), CameraActivity.OnCameraListener {
private val mBinding by viewBinding<UserCenterActivityBinding>()
private val mUserViewModel by viewModels<UserViewModel>()
private var mUserBasicInfo: UserBasicInfo? = null
override fun getLayoutId(): Int = R.layout.user_center_activity
override fun initView() {
val tvGetAllowance = mBinding.tvGetAllowance
tvGetAllowance.text = getDefaultAllowanceTips()
tvGetAllowance.setRoundRectBg(ContextCompat.getColor(this, R.color.pink), 3.dp)
checkAllowance()
}
private fun checkAllowance(block: (isGetAllowance: Boolean) -> Unit = {}) {
val tvGetAllowance = mBinding.tvGetAllowance
mUserViewModel.checkAllowance().observe(this) {
val isGetAllowance = it.getOrNull() ?: return@observe
tvGetAllowance.text = if (isGetAllowance) "已领取" else getDefaultAllowanceTips()
tvGetAllowance.isEnabled = isGetAllowance.not()
takeIf { isGetAllowance }?.let {
val disableTextColor = ContextCompat.getColor(this, R.color.btn_text_disable_color)
tvGetAllowance.setTextColor(disableTextColor)
val disableBgColor = ContextCompat.getColor(this, R.color.btn_bg_disable_color)
tvGetAllowance.setRoundRectBg(disableBgColor, 3.dp)
}
block.invoke(isGetAllowance)
}
}
private fun getDefaultAllowanceTips() = if (UserManager.currUserIsVip()) "领取津贴" else "成为VIP"
override fun initData() {
val userBasicInfo = UserManager.loadUserBasicInfo()
userBasicInfo?.let { mUserBasicInfo = it }
}
override fun onResume() {
super.onResume()
Glide.with(this)
.load(mUserBasicInfo?.avatar)
.placeholder(R.mipmap.ic_default_avatar)
.error(R.mipmap.ic_default_avatar)
.circleCrop()
.diskCacheStrategy(DiskCacheStrategy.NONE)
.skipMemoryCache(true)
.into(mBinding.ivAvatar)
mBinding.tvNickName.text = mUserBasicInfo?.nickname ?: "游客"
}
override fun initEvent() {
val tvGetAllowance = mBinding.tvGetAllowance
mBinding.llUserInfoContainer.setFixOnClickListener {
takeIfLogin { userBasicInfo ->
val userId = userBasicInfo.id
ViewUserActivity.start(context, userId)
}
}
mBinding.ivAvatar.setFixOnClickListener {
simpleToast("此功能暂未开放")
// CameraActivity.start(this, this)
}
mBinding.ivBecomeVip.setFixOnClickListener {
BrowserActivity.start(this, "https://www.sunofbeach.net/vip")
}
tvGetAllowance.setFixOnClickListener {
mUserViewModel.getAllowance().observe(this) { result ->
result.getOrNull()?.let {
tvGetAllowance.text = "已领取"
tvGetAllowance.isEnabled = it.not()
val disableTextColor =
ContextCompat.getColor(this, R.color.btn_text_disable_color)
tvGetAllowance.setTextColor(disableTextColor)
val disableBgColor = ContextCompat.getColor(this, R.color.btn_bg_disable_color)
tvGetAllowance.setRoundRectBg(disableBgColor, 3.dp)
checkAllowance { isGetAllowance ->
takeIf { isGetAllowance }?.let {
simpleToast("当月津贴已领取")
}
}
}
}
}
}
@SuppressLint("SetTextI18n")
override fun initObserver() {
mUserViewModel.getAchievement().observe(this) {
val userAchievement = it.getOrNull() ?: return@observe
mBinding.tvNickName.text = mUserBasicInfo?.nickname ?: "游客"
// 此字段在 v2 版本的接口将会修改
mBinding.tvVip.text = when (mUserBasicInfo?.isVip) {
"1" -> "正式会员"
"0" -> "普通会员"
else -> "普通会员"
}
mBinding.tvSobCurrency.text = "SOB币:${userAchievement.sob}"
mBinding.tvDynamicNum.text = userAchievement.momentCount.toString()
mBinding.tvFollowNum.text = userAchievement.followCount.toString()
mBinding.tvFansNum.text = userAchievement.fansCount.toString()
}
}
override fun onSelected(file: File?) {
file ?: return
Glide.with(this)
.load(file)
.placeholder(R.mipmap.ic_default_avatar)
.error(R.mipmap.ic_default_avatar)
.circleCrop()
.into(mBinding.ivAvatar)
simpleToast("暂不支持更换头像")
}
} | 1 | null | 5 | 19 | 687bcbbb1b08a3dac4d44d04f9dbad84d554b279 | 5,524 | SunnyBeach | Apache License 2.0 |
src/main/kotlin/lt/ekgame/ui/containers/FlexRowContainer.kt | ekgame | 422,901,098 | false | {"Kotlin": 152475} | package lt.ekgame.ui.containers
import lt.ekgame.ui.*
import lt.ekgame.ui.constraints.*
import lt.ekgame.ui.containers.helpers.FlexPlacementHelper
import java.awt.Color
open class FlexRowContainer(
id: String = "",
parent: Container?,
size: SizeConstraints = SizeConstraints.DEFAULT,
padding: PaddingValues = PaddingValues.ZERO,
background: Color? = null,
var gap: Float = 0f,
var horizontalAlignment: Alignment = StartAlignment,
var verticalAlignment: Alignment = StartAlignment,
var verticalContainerAlignment: Alignment = StartAlignment,
) : GenericContainer(id, parent, size, padding, background) {
private fun getTotalGapSize(): Float = (computedChildren.size - 1).coerceAtLeast(0)*gap
private fun getTotalChildWidthWithGaps(): Float = getTotalChildWidth() + getTotalGapSize()
private fun calculateFlex(elements: List<Placeable>): FlexPlacementHelper {
requireNotNull(placeable.width) { "The placeable has to have defined width to apply flex." }
val flexHelper = FlexPlacementHelper()
elements.forEach { child ->
val currentBucketWidth = flexHelper.getCurrentBucketWidth(gap)
val childWidth = child.width ?: 0f
if (currentBucketWidth + childWidth > getInnerWidth()) {
flexHelper.addBucket()
}
flexHelper.add(child)
}
return flexHelper
}
override fun measure(container: Container?): Boolean {
if (!super.measure(container) || !isValidPlaceable()) {
return false
}
val availableWidth = placeable.width!! - this.padding.horizontal
val availableHeight = placeable.height!! - this.padding.vertical
val childPlaceables = getRemeasuredChildren(container)
val flex = calculateFlex(childPlaceables)
val flexHeight = flex.getTotalHeight(gap)
var offsetX = 0f
var offsetY = 0f
(0 until flex.getNumBuckets()).forEach { bucketIndex ->
val bucket = flex.getBucket(bucketIndex)
val bucketWidth = flex.getBucketWidth(bucketIndex, gap)
val bucketMaxHeight = flex.getBucketMaxHeight(bucketIndex)
bucket.forEach {
it.x = padding.left + offsetX + horizontalAlignment.calculate(bucketWidth, availableWidth)
it.y = padding.top + offsetY + verticalAlignment.calculate(it.height!!, bucketMaxHeight) + verticalContainerAlignment.calculate(flexHeight, availableHeight)
offsetX += it.width!! + gap
}
offsetX = 0f
offsetY += bucketMaxHeight + gap
}
return true
}
override fun recalculateContainerWidth(container: Container?) {
placeable.width = applyMinMaxWidth(when (this.size.width) {
is ContentSize -> getTotalChildWidthWithGaps() + this.padding.horizontal
else -> placeable.width
}, container)
}
override fun recalculateContainerHeight(container: Container?) {
placeable.height = applyMinMaxHeight(when {
this.size.height is ContentSize && placeable.width != null -> {
val flex = calculateFlex(computedChildren.asPlaceables())
flex.getTotalHeight(gap) + this.padding.vertical
}
else -> placeable.height
}, container)
}
} | 0 | Kotlin | 0 | 1 | 6ab0986eccb9f8f64b0edb5790f643163491af82 | 3,370 | ek-ui | MIT License |
src/main/kotlin/uk/gov/justice/digital/hmpps/sentenceplan/entity/StepEntity.kt | ministryofjustice | 783,789,996 | false | {"Kotlin": 134325, "Makefile": 2474, "Dockerfile": 1145} | package uk.gov.justice.digital.hmpps.sentenceplan.entity
import com.fasterxml.jackson.annotation.JsonIgnore
import jakarta.persistence.Column
import jakarta.persistence.Entity
import jakarta.persistence.EnumType
import jakarta.persistence.Enumerated
import jakarta.persistence.FetchType
import jakarta.persistence.GeneratedValue
import jakarta.persistence.GenerationType
import jakarta.persistence.Id
import jakarta.persistence.JoinColumn
import jakarta.persistence.ManyToOne
import jakarta.persistence.Table
import org.springframework.data.jpa.repository.JpaRepository
import java.time.LocalDateTime
import java.util.UUID
@Entity(name = "Step")
@Table(name = "step")
class StepEntity(
@Id
@Column(name = "id")
@GeneratedValue(strategy = GenerationType.IDENTITY)
@JsonIgnore
val id: Long? = null,
@Column(name = "uuid")
val uuid: UUID = UUID.randomUUID(),
@Column(name = "description")
val description: String,
@Column(name = "status")
@Enumerated(EnumType.STRING)
val status: StepStatus = StepStatus.NOT_STARTED,
@Column(name = "creation_date", columnDefinition = "TIMESTAMP")
val creationDate: LocalDateTime = LocalDateTime.now(),
// this is nullable in the declaration to enable ignoring the field in JSON serialisation
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "goal_id", nullable = false)
@JsonIgnore
val goal: GoalEntity? = null,
@Column(name = "actor", nullable = false)
var actor: String,
)
enum class StepStatus {
NOT_STARTED,
IN_PROGRESS,
CANNOT_BE_DONE_YET,
COMPLETED,
}
interface StepRepository : JpaRepository<StepEntity, Long> {
fun findByUuid(uuid: UUID): StepEntity?
}
| 3 | Kotlin | 0 | 1 | 237d07620715d7c01eb9671d0090005ed582fe02 | 1,659 | hmpps-sentence-plan | MIT License |
common-ui-list/file-system/src/main/java/com/storyteller_f/file_system/instance/local/RootAccessFileInstance.kt | storytellerF | 576,917,592 | false | null | package com.storyteller_f.file_system.instance.local
import com.storyteller_f.file_system.FileInstanceFactory
import com.storyteller_f.file_system.instance.FileInstance
import com.storyteller_f.file_system.model.DirectoryItemModel
import com.storyteller_f.file_system.model.FileItemModel
import com.storyteller_f.file_system.util.FileInstanceUtility
import com.topjohnwu.superuser.nio.ExtendedFile
import com.topjohnwu.superuser.nio.FileSystemManager
import java.io.*
class RootAccessFileInstance(path: String, private val remote: FileSystemManager) : FileInstance(path, FileInstanceFactory.rootFileSystemRoot) {
private var extendedFile = remote.getFile(path)
override fun getFile(): FileItemModel {
return FileItemModel(extendedFile.name, extendedFile.absolutePath, extendedFile.isHidden, extendedFile.lastModified(), extendedFile.isSymlink, extendedFile.extension)
}
override fun getDirectory(): DirectoryItemModel {
return DirectoryItemModel(extendedFile.name, extendedFile.absolutePath, extendedFile.isHidden, extendedFile.lastModified(), extendedFile.isSymlink)
}
override fun getFileInputStream(): FileInputStream = extendedFile.inputStream()
override fun getFileOutputStream(): FileOutputStream = extendedFile.outputStream()
override fun listInternal(
fileItems: MutableList<FileItemModel>,
directoryItems: MutableList<DirectoryItemModel>
) {
val listFiles = extendedFile.listFiles()
listFiles?.forEach {
val format = it.permissions()
if (it.isFile) {
FileInstanceUtility.addFile(fileItems, it, format)
} else if (it.isDirectory) {
FileInstanceUtility.addDirectory(directoryItems, it, format)
}
}
}
private fun ExtendedFile.permissions(): String {
val w = canWrite()
val e = canExecute()
val r = canRead()
return com.storyteller_f.file_system.util.permissions(r, w, e, isFile)
}
override fun isFile(): Boolean = extendedFile.isFile
override fun exists(): Boolean = extendedFile.exists()
override fun isDirectory(): Boolean = extendedFile.isDirectory
override fun deleteFileOrEmptyDirectory(): Boolean = extendedFile.delete()
override fun rename(newName: String?): Boolean {
TODO("Not yet implemented")
}
override fun toParent(): FileInstance {
return RootAccessFileInstance(File(path).parent!!, remote)
}
override fun changeToParent() {
TODO("Not yet implemented")
}
override fun getDirectorySize(): Long {
TODO("Not yet implemented")
}
override fun createFile(): Boolean {
TODO("Not yet implemented")
}
override fun isHidden() = extendedFile.isHidden
override fun createDirectory(): Boolean {
TODO("Not yet implemented")
}
override fun toChild(name: String, isFile: Boolean, createWhenNotExists: Boolean): FileInstance {
return RootAccessFileInstance(File(file, name).absolutePath, remote)
}
override fun changeToChild(name: String, isFile: Boolean, createWhenNotExists: Boolean) {
val tempFile = File(file, name)
val childFile = remote.getFile(file.absolutePath)
file = tempFile
extendedFile = childFile
}
override fun changeTo(path: String) {
val tempFile = File(path)
val childFile = remote.getFile(path)
file = tempFile
extendedFile = childFile
}
override fun getParent(): String? = extendedFile.parent
override fun isSymbolicLink(): Boolean {
return extendedFile.isSymlink
}
} | 4 | Kotlin | 0 | 1 | 2b46cd3f304859823a6f2a73e28e05f808d7b48e | 3,662 | common-ui-list-structure | MIT License |
src/main/kotlin/moe/nea/firmament/gui/config/AllConfigsGui.kt | nea89o | 637,563,904 | false | null |
package moe.nea.firmament.gui.config
import io.github.notenoughupdates.moulconfig.observer.ObservableList
import io.github.notenoughupdates.moulconfig.xml.Bind
import net.minecraft.client.gui.screen.Screen
import net.minecraft.text.Text
import moe.nea.firmament.features.FeatureManager
import moe.nea.firmament.repo.RepoManager
import moe.nea.firmament.util.MC
import moe.nea.firmament.util.MoulConfigUtils
import moe.nea.firmament.util.ScreenUtil.setScreenLater
object AllConfigsGui {
val allConfigs
get() = listOf(
RepoManager.Config
) + FeatureManager.allFeatures.mapNotNull { it.config }
fun <T> List<T>.toObservableList(): ObservableList<T> = ObservableList(this)
class MainMapping(val allConfigs: List<ManagedConfig>) {
@get:Bind("configs")
val configs = allConfigs.map { EntryMapping(it) }.toObservableList()
class EntryMapping(val config: ManagedConfig) {
@Bind
fun name() = Text.translatable("firmament.config.${config.name}").string
@Bind
fun openEditor() {
config.showConfigEditor(MC.screen)
}
}
}
fun makeScreen(parent: Screen? = null): Screen {
return MoulConfigUtils.loadScreen("config/main", MainMapping(allConfigs), parent)
}
fun showAllGuis() {
setScreenLater(makeScreen())
}
}
| 25 | null | 6 | 37 | 9cdc30e024fac9fe04eeeccb15dfd46f4aa648cb | 1,390 | Firmament | Apache License 2.0 |
src/main/kotlin/com/codepoetics/stygian/Domain.kt | poetix | 92,292,108 | false | null | package com.codepoetics.stygian
import java.util.concurrent.CompletableFuture
/**
* An asynchronously-returned result.
*/
typealias Async<O> = CompletableFuture<O>
/**
* A function which returns a result asynchronously.
*/
typealias AsyncFunction<I, O> = (I) -> Async<O>
/**
* A function which returns a result asynchronously.
*/
typealias AsyncFunction2<I1, I2, O> = (I1, I2) -> Async<O>
/**
* A named action, which accepts an input and returns an asynchronous result.
*/
data class Action<I, O>(val name: String, val operation: AsyncFunction<I, O>): AsyncFunction<I, O> by operation {
fun decorate(decorator: (AsyncFunction<I, O>) -> AsyncFunction<I, O>): Action<I, O> = copy(operation = decorator(operation))
}
/**
* A named condition, which accepts an input and asynchronously returns either True orIf False.
*/
data class Condition<T>(val name: String, val operation: AsyncFunction<T, Boolean>): AsyncFunction<T, Boolean> by operation {
fun decorate(decorator: (AsyncFunction<T, Boolean>) -> AsyncFunction<T, Boolean>): Condition<T> = copy(operation = decorator(operation))
}
/**
* Convert a synchronous function into an asynchronous one.
*/
fun <I, O> liftAsync(f: (I) -> O): AsyncFunction<I, O> = { i ->
val result = CompletableFuture<O>()
try {
result.complete(f(i))
} catch (e: Throwable) {
result.completeExceptionally(e)
}
result
}
/**
* Convert a synchronous function into an asynchronous one.
*/
fun <I1, I2, O> liftAsync2(f: (I1, I2) -> O): AsyncFunction2<I1, I2, O> = { i1, i2 ->
val result = CompletableFuture<O>()
try {
result.complete(f(i1, i2))
} catch (e: Throwable) {
result.completeExceptionally(e)
}
result
} | 1 | null | 1 | 1 | 62d54c9ad2c8ffe88c17415148e1f09507efca0e | 1,733 | stygian | MIT License |
pack/src/main/kotlin/io/github/shkschneider/awesome/pack/PlayerHealth.kt | shkschneider | 555,774,039 | false | null | package io.github.shkschneider.awesome.pack
import io.github.shkschneider.awesome.custom.Event
import net.fabricmc.fabric.api.event.lifecycle.v1.ServerLifecycleEvents
object PlayerHealth {
private const val NAME = "Health"
operator fun invoke() {
@Event("ServerLifecycleEvents.ServerStarted")
ServerLifecycleEvents.SERVER_STARTED.register(ServerLifecycleEvents.ServerStarted { server ->
if (server.scoreboard.objectives.none { it.name == NAME }) {
// couldn't get it to display using server.scoreboard
server.commandManager.execute(server.commandSource, "/scoreboard objectives add $NAME health")
server.commandManager.execute(server.commandSource, "/scoreboard objectives setdisplay belowName $NAME")
}
})
}
}
| 0 | Kotlin | 0 | 0 | 0ff68dafdbd5a8be3b4626875efe960bd97478f2 | 824 | mc_awesome | MIT License |
app/src/main/java/com/teobaranga/monica/contacts/detail/activities/edit/ui/EditContactActivityUiState.kt | teobaranga | 686,113,276 | false | {"Kotlin": 407315} | package com.teobaranga.monica.contacts.detail.activities.edit.ui
import androidx.compose.foundation.text.input.TextFieldState
import androidx.compose.runtime.Stable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateListOf
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.setValue
import kotlinx.coroutines.flow.StateFlow
import java.time.LocalDate
sealed interface EditContactActivityUiState {
data object Loading : EditContactActivityUiState
@Stable
data class Loaded(
val participantResults: StateFlow<List<ActivityParticipant>>,
) : EditContactActivityUiState {
var date: LocalDate by mutableStateOf(LocalDate.now())
val participantSearch = TextFieldState()
val participants = mutableStateListOf<ActivityParticipant.Contact>()
val summary = TextFieldState()
val details = TextFieldState()
}
}
| 2 | Kotlin | 1 | 16 | 1fd67b6d5692c50fc29377a33210546f62419cc7 | 938 | monica | Apache License 2.0 |
plugin/project-plugin/src/main/kotlin/plugin/ProjectPlugin.kt | top-bettercode | 387,652,015 | false | null | package plugin
import ProjectUtil.isBoot
import ProjectUtil.isCloud
import ProjectUtil.isCore
import ProjectUtil.needDoc
import org.gradle.api.JavaVersion
import org.gradle.api.Plugin
import org.gradle.api.Project
import org.gradle.api.plugins.JavaPluginExtension
import org.gradle.api.tasks.SourceSet
/**
*
* @author <NAME>
*/
class ProjectPlugin : Plugin<Project> {
override fun apply(project: Project) {
project.description = project.findProperty("application.name") as? String
project.allprojects.forEach { subProject ->
subProject.plugins.apply("idea")
subProject.plugins.apply("java")
subProject.group = subProject.properties["app.packageName"] as String
subProject.version = subProject.properties["app.version"] as String
//idea
subProject.extensions.configure(org.gradle.plugins.ide.idea.model.IdeaModel::class.java) { idea ->
idea.module {
it.inheritOutputDirs = false
it.isDownloadJavadoc = false
it.isDownloadSources = true
val convention = subProject.extensions.getByType(
JavaPluginExtension::class.java
)
it.outputDir = convention.sourceSets
.getByName(SourceSet.MAIN_SOURCE_SET_NAME).java.classesDirectory.get().asFile
it.testOutputDir = convention.sourceSets
.getByName(SourceSet.TEST_SOURCE_SET_NAME).java.classesDirectory.get().asFile
}
}
//java
subProject.extensions.configure(org.gradle.api.plugins.JavaPluginExtension::class.java) { java ->
java.sourceCompatibility = JavaVersion.VERSION_1_8
java.targetCompatibility = JavaVersion.VERSION_1_8
}
//plugins
subProject.plugins.apply {
apply("summer.profile")
apply("summer.packageinfo")
apply("org.springframework.boot")
apply("io.spring.dependency-management")
}
if (subProject.needDoc) {
subProject.plugins.apply {
apply("summer.generator")
apply("summer.autodoc")
}
}
if (subProject.isBoot) {
subProject.plugins.apply {
apply("application")
apply("summer.dist")
}
}
//dependencies
ProjectDependencies.config(subProject)
//tasks
SubProjectTasks.config(subProject)
if (subProject.isCore) {
CoreProjectTasks.config(subProject)
}
}
//tasks
RootProjectTasks.config(project)
//docker
if (project.isCloud) {
project.apply { project.plugins.apply(Docker::class.java) }
}
}
} | 0 | Kotlin | 0 | 1 | 6fe2f1eb2e5db2c3b24eef3dd01a1cadbd2a3d17 | 3,014 | summer | Apache License 2.0 |
core/src/main/java/at/specure/data/dao/CellLocationDao.kt | dzlabing | 362,143,915 | true | {"Kotlin": 1366399, "Java": 589125, "HTML": 45339, "Shell": 4061} | package at.specure.data.dao
import androidx.room.Dao
import androidx.room.Insert
import androidx.room.OnConflictStrategy
import androidx.room.Query
import androidx.room.Transaction
import at.specure.data.Tables
import at.specure.data.entity.CellLocationRecord
@Dao
interface CellLocationDao {
@Query("SELECT * from ${Tables.CELL_LOCATION} WHERE testUUID == :testUUID")
fun get(testUUID: String): List<CellLocationRecord>
@Insert(onConflict = OnConflictStrategy.IGNORE)
fun insert(cellLocation: CellLocationRecord): Long
@Query("DELETE FROM ${Tables.CELL_LOCATION} WHERE testUUID=:testUUID")
fun remove(testUUID: String)
@Query("SELECT * FROM ${Tables.CELL_LOCATION} WHERE testUUID=:testUUID AND areaCode==:areaCode AND locationId==:locationId AND scramblingCode==:scramblingCode")
fun getSingleCellLocation(testUUID: String, areaCode: Int?, locationId: Int?, scramblingCode: Int): List<CellLocationRecord>
@Transaction
open fun insertNew(testUUID: String, cellLocationList: List<CellLocationRecord>) {
cellLocationList.forEach {
val cellLocationsExist = getSingleCellLocation(testUUID, it.areaCode, it.locationId, it.scramblingCode)
if (cellLocationsExist.isEmpty()) {
insert(it)
}
}
}
} | 0 | Kotlin | 0 | 0 | 7cfb1e8fdba99cfd959369982878eccc1af60573 | 1,306 | open-rmbt-android | Apache License 2.0 |
src/test/kotlin/com/codingjj/jsondbconverter/database/JsonTblRepository.kt | coding-jj | 361,540,795 | false | null | package com.codingjj.jsondbconverter.database
import org.springframework.data.repository.CrudRepository
import java.util.*
interface JsonTblRepository : CrudRepository<JsonTblEntity, UUID> | 0 | Kotlin | 1 | 0 | 0262f0bcab1d32af2a085dcb4e50ef01227f78a6 | 190 | json-db-converter | MIT License |
app/src/main/java/com/kyhsgeekcode/disassembler/FoundString.kt | KYHSGeekCode | 126,714,855 | false | {"Git Config": 1, "Gradle": 4, "YAML": 3, "Java Properties": 2, "Markdown": 7, "Shell": 1, "Text": 1, "Ignore List": 3, "Batchfile": 1, "Git Attributes": 1, "C": 34, "Kotlin": 106, "JSON": 5, "CMake": 1, "Proguard": 1, "XML": 59, "Java": 38, "C++": 15} | package com.kyhsgeekcode.disassembler
data class FoundString(
val length: Int = 0,
val offset: Long = 0,
val string: String = ""
) | 96 | Kotlin | 91 | 570 | 26916bb894f02f027eb0f38082b0094f5cf0fc3b | 143 | ARMDisasm | MIT License |
app/src/main/java/com/example/android/politicalpreparedness/election/VoterInfoViewModelFactory.kt | simbastart001 | 748,825,661 | false | {"Kotlin": 60979} | package com.example.android.politicalpreparedness.election
import android.app.Application
import androidx.lifecycle.ViewModel
import androidx.lifecycle.ViewModelProvider
import com.example.android.politicalpreparedness.network.models.Election
class VoterInfoViewModelFactory(
private val election: Election,
private val app: Application
) : ViewModelProvider.Factory {
@Suppress("unchecked_cast")
override fun <T : ViewModel> create(modelClass: Class<T>): T {
if (modelClass.isAssignableFrom(VoterInfoViewModel::class.java)) {
return VoterInfoViewModel(election, app) as T
}
throw IllegalArgumentException("Unknown ViewModel class")
}
}
| 0 | Kotlin | 0 | 0 | 6875619798580f60ad03f5b62ad6485965a00611 | 695 | PolticalPreparedness-App | Apache License 2.0 |
baselib/src/main/java/com/wukangjie/baselib/presenter/RequestCallback.kt | wukangjie | 188,939,915 | false | null | package com.wukangjie.baselib.presenter
import com.wukangjie.baselib.remote.BaseException
interface RequestCallback<T> {
fun onSuccess(data: T)
}
interface RequestMultiplyCallback<T> : RequestCallback<T> {
fun onFail(e: BaseException)
} | 0 | Kotlin | 0 | 0 | cc59ded26f2c1a7bef65cd63ccf22d461625e0a7 | 252 | K-MVVM | Apache License 2.0 |
app/src/main/java/com/twobbble/view/adapter/ItemShotAdapter.kt | 550609334 | 82,531,843 | false | null | package com.twobbble.view.adapter
import android.animation.AnimatorInflater
import android.animation.AnimatorSet
import android.animation.ObjectAnimator
import android.support.v7.widget.CardView
import android.support.v7.widget.RecyclerView
import android.view.LayoutInflater
import android.view.MotionEvent
import android.view.View
import android.view.ViewGroup
import android.view.animation.AccelerateDecelerateInterpolator
import android.view.animation.OvershootInterpolator
import com.twobbble.R
import com.twobbble.application.App
import com.twobbble.entity.Shot
import com.twobbble.tools.ImageLoad
import com.twobbble.tools.Utils
import com.twobbble.tools.hasNavigationBar
import kotlinx.android.synthetic.main.item_card_bottom.view.*
import kotlinx.android.synthetic.main.item_card_head.view.*
import kotlinx.android.synthetic.main.item_shots.view.*
import kotlinx.android.synthetic.main.pull_up_load_layout.view.*
/**
* Created by liuzipeng on 2017/2/22.
*/
class ItemShotAdapter(var mShots: MutableList<Shot>, val itemClick: (Int) -> Unit, val userClick: (Int) -> Unit) : RecyclerView.Adapter<ItemShotAdapter.ViewHolder>() {
val NORMAL = 0
val LOAD_MORE = 1
val CARD_TAP_DURATION: Long = 100
lateinit private var mLastViewHolder: ViewHolder
private var mOldPosition = 0
override fun onCreateViewHolder(parent: ViewGroup?, viewType: Int): ViewHolder {
if (viewType == NORMAL) {
return ViewHolder(LayoutInflater.from(parent?.context).inflate(R.layout.item_shots, parent, false))
} else {
return ViewHolder(LayoutInflater.from(parent?.context).inflate(R.layout.pull_up_load_layout, parent, false))
}
}
override fun getItemCount(): Int = mShots.size + 1
override fun onBindViewHolder(holder: ViewHolder, position: Int) {
if (position == mShots.size) {
App.instance.hasNavigationBar {
holder.itemView.mNavigationBar.visibility = View.VISIBLE
}
mLastViewHolder = holder
} else {
holder.bindShots(mShots[position])
holder.itemView.mItemCard.setOnClickListener {
itemClick.invoke(position)
}
holder.itemView.mHeadLayout.setOnClickListener {
userClick.invoke(position)
}
addCardZAnimation(holder.itemView?.mItemCard)
}
}
override fun onViewAttachedToWindow(holder: ViewHolder) {
if (holder.layoutPosition > mOldPosition) {
addItemAnimation(holder.itemView.mItemCard)
mOldPosition = holder.layoutPosition
}
}
private fun addItemAnimation(mItemCard: CardView?) {
mItemCard?.let {
val scaleX = ObjectAnimator.ofFloat(it, "translationY", 500f, 0f)
// val scaleY = ObjectAnimator.ofFloat(mItemCard, "scaleY", 0.5f, 1f)
// val set = AnimatorSet()
// set.playTogether(scaleX, scaleY)
scaleX.duration = 500
scaleX.start()
}
}
private fun addCardZAnimation(mItemCard: CardView?) {
mItemCard?.setOnTouchListener { _, motionEvent ->
when (motionEvent.action) {
MotionEvent.ACTION_DOWN -> mItemCard.animate().translationZ(Utils.dp2px(24)).duration = CARD_TAP_DURATION
MotionEvent.ACTION_UP -> mItemCard.animate().translationZ(0f).duration = CARD_TAP_DURATION
MotionEvent.ACTION_CANCEL -> mItemCard.animate().translationZ(0f).duration = CARD_TAP_DURATION
}
false
}
}
fun hideProgress() {
mLastViewHolder.itemView.mLoadLayout.visibility = View.GONE
}
fun loadError(retryListener: () -> Unit) {
mLastViewHolder.itemView.mRetryLoadProgress.visibility = View.GONE
mLastViewHolder.itemView.mReTryText.visibility = View.VISIBLE
mLastViewHolder.itemView.mLoadLayout.setOnClickListener {
mLastViewHolder.itemView.mRetryLoadProgress.visibility = View.VISIBLE
mLastViewHolder.itemView.mReTryText.visibility = View.GONE
retryListener.invoke()
}
}
fun getSize(): Int = mShots.size
fun addItems(shots: MutableList<Shot>) {
val position = mShots.size
mShots.addAll(shots)
notifyItemInserted(position)
}
fun addItem(position: Int, shot: Shot) {
mShots.add(position, shot)
notifyItemInserted(position)
}
fun deleteItem(position: Int) {
mShots.removeAt(position)
notifyItemRemoved(position)
}
override fun getItemViewType(position: Int): Int = if (position == mShots.size) LOAD_MORE else NORMAL
inner class ViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
fun bindShots(shot: Shot) {
with(shot) {
ImageLoad.frescoLoadCircle(itemView.mAvatarImg, shot.user?.avatar_url.toString())
ImageLoad.frescoLoadNormal(itemView.mContentImg, itemView.mImgProgress, shot.images?.normal.toString(), shot.images?.teaser.toString())
itemView.mTitleText.text = shot.title
itemView.mAuthorText.text = shot.user?.name
itemView.mLikeCountText.text = shot.likes_count.toString()
itemView.mCommentCountText.text = shot.comments_count.toString()
itemView.mViewsCountText.text = shot.views_count.toString()
itemView.mImgProgress.visibility = View.VISIBLE
if (shot.animated) itemView.mGifTag.visibility = View.VISIBLE else itemView.mGifTag.visibility = View.GONE
if (shot.rebounds_count > 0) {
itemView.mReboundLayout.visibility = View.VISIBLE
itemView.mReboundCountText.text = shot.rebounds_count.toString()
} else itemView.mReboundLayout.visibility = View.GONE
if (shot.attachments_count > 0) {
itemView.mAttachmentLayout.visibility = View.VISIBLE
itemView.mAttachmentCountText.text = shot.attachments_count.toString()
} else itemView.mAttachmentLayout.visibility = View.GONE
}
}
}
} | 1 | Kotlin | 62 | 398 | e91797a3d4a0fa7737f983a8914eaa109a452054 | 6,187 | Twobbble | Apache License 2.0 |
app/src/test/java/com/stevesoltys/seedvault/transport/backup/ApkBackupTest.kt | seedvault-app | 104,299,796 | false | null | package com.stevesoltys.seedvault.transport.backup
import android.content.pm.ApplicationInfo.FLAG_SYSTEM
import android.content.pm.ApplicationInfo.FLAG_TEST_ONLY
import android.content.pm.ApplicationInfo.FLAG_UPDATED_SYSTEM_APP
import android.content.pm.InstallSourceInfo
import android.content.pm.PackageInfo
import android.content.pm.PackageManager
import android.content.pm.Signature
import android.util.PackageUtils
import com.stevesoltys.seedvault.MAGIC_PACKAGE_MANAGER
import com.stevesoltys.seedvault.getRandomString
import com.stevesoltys.seedvault.metadata.ApkSplit
import com.stevesoltys.seedvault.metadata.PackageMetadata
import com.stevesoltys.seedvault.metadata.PackageState.UNKNOWN_ERROR
import io.mockk.coEvery
import io.mockk.every
import io.mockk.mockk
import io.mockk.mockkStatic
import kotlinx.coroutines.runBlocking
import org.junit.jupiter.api.Assertions.assertArrayEquals
import org.junit.jupiter.api.Assertions.assertEquals
import org.junit.jupiter.api.Assertions.assertNull
import org.junit.jupiter.api.Assertions.assertThrows
import org.junit.jupiter.api.Assertions.assertTrue
import org.junit.jupiter.api.Test
import org.junit.jupiter.api.io.TempDir
import java.io.ByteArrayOutputStream
import java.io.File
import java.io.IOException
import java.io.OutputStream
import java.nio.file.Path
import kotlin.random.Random
@Suppress("BlockingMethodInNonBlockingContext")
internal class ApkBackupTest : BackupTest() {
private val pm: PackageManager = mockk()
private val streamGetter: suspend (suffix: String) -> OutputStream = mockk()
private val apkBackup = ApkBackup(pm, settingsManager, metadataManager)
private val signatureBytes = byteArrayOf(0x01, 0x02, 0x03)
private val signatureHash = byteArrayOf(0x03, 0x02, 0x01)
private val sigs = arrayOf(Signature(signatureBytes))
private val packageMetadata = PackageMetadata(
time = Random.nextLong(),
version = packageInfo.longVersionCode - 1,
signatures = listOf("AwIB")
)
init {
mockkStatic(PackageUtils::class)
}
@Test
fun `does not back up @pm@`() = runBlocking {
val packageInfo = PackageInfo().apply { packageName = MAGIC_PACKAGE_MANAGER }
assertNull(apkBackup.backupApkIfNecessary(packageInfo, UNKNOWN_ERROR, streamGetter))
}
@Test
fun `does not back up when setting disabled`() = runBlocking {
every { settingsManager.backupApks() } returns false
assertNull(apkBackup.backupApkIfNecessary(packageInfo, UNKNOWN_ERROR, streamGetter))
}
@Test
fun `does not back up test-only apps`() = runBlocking {
packageInfo.applicationInfo.flags = FLAG_TEST_ONLY
every { settingsManager.backupApks() } returns true
assertNull(apkBackup.backupApkIfNecessary(packageInfo, UNKNOWN_ERROR, streamGetter))
}
@Test
fun `does not back up system apps`() = runBlocking {
packageInfo.applicationInfo.flags = FLAG_SYSTEM
every { settingsManager.backupApks() } returns true
assertNull(apkBackup.backupApkIfNecessary(packageInfo, UNKNOWN_ERROR, streamGetter))
}
@Test
fun `does not back up the same version`() = runBlocking {
packageInfo.applicationInfo.flags = FLAG_UPDATED_SYSTEM_APP
val packageMetadata = packageMetadata.copy(
version = packageInfo.longVersionCode
)
expectChecks(packageMetadata)
assertNull(apkBackup.backupApkIfNecessary(packageInfo, UNKNOWN_ERROR, streamGetter))
}
@Test
fun `does back up the same version when signatures changes`() {
packageInfo.applicationInfo.sourceDir = "/tmp/doesNotExist"
expectChecks()
assertThrows(IOException::class.java) {
runBlocking {
assertNull(apkBackup.backupApkIfNecessary(packageInfo, UNKNOWN_ERROR, streamGetter))
}
}
}
@Test
fun `do not accept empty signature`() = runBlocking {
every { settingsManager.backupApks() } returns true
every {
metadataManager.getPackageMetadata(packageInfo.packageName)
} returns packageMetadata
every { sigInfo.hasMultipleSigners() } returns false
every { sigInfo.signingCertificateHistory } returns emptyArray()
assertNull(apkBackup.backupApkIfNecessary(packageInfo, UNKNOWN_ERROR, streamGetter))
}
@Test
fun `test successful APK backup`(@TempDir tmpDir: Path) = runBlocking {
val apkBytes = byteArrayOf(0x04, 0x05, 0x06)
val tmpFile = File(tmpDir.toAbsolutePath().toString())
packageInfo.applicationInfo.sourceDir = File(tmpFile, "test.apk").apply {
assertTrue(createNewFile())
writeBytes(apkBytes)
}.absolutePath
val apkOutputStream = ByteArrayOutputStream()
val updatedMetadata = PackageMetadata(
time = 0L,
state = UNKNOWN_ERROR,
version = packageInfo.longVersionCode,
installer = getRandomString(),
sha256 = "eHx5jjmlvBkQNVuubQzYejay4Q_QICqD47trAF2oNHI",
signatures = packageMetadata.signatures
)
expectChecks()
coEvery { streamGetter.invoke("") } returns apkOutputStream
every {
pm.getInstallSourceInfo(packageInfo.packageName)
} returns InstallSourceInfo(null, null, null, updatedMetadata.installer)
assertEquals(
updatedMetadata,
apkBackup.backupApkIfNecessary(packageInfo, UNKNOWN_ERROR, streamGetter)
)
assertArrayEquals(apkBytes, apkOutputStream.toByteArray())
}
@Test
fun `test successful APK backup with two splits`(@TempDir tmpDir: Path) = runBlocking {
// create base APK
val apkBytes = byteArrayOf(0x04, 0x05, 0x06) // not random because of hash
val tmpFile = File(tmpDir.toAbsolutePath().toString())
packageInfo.applicationInfo.sourceDir = File(tmpFile, "test.apk").apply {
assertTrue(createNewFile())
writeBytes(apkBytes)
}.absolutePath
// set split names
val split1Name = "config.arm64_v8a"
val split2Name = "config.xxxhdpi"
packageInfo.splitNames = arrayOf(split1Name, split2Name)
// create two split APKs
val split1Bytes = byteArrayOf(0x07, 0x08, 0x09)
val split1Sha256 = "ZqZ1cVH47lXbEncWx-Pc4L6AdLZOIO2lQuXB5GypxB4"
val split2Bytes = byteArrayOf(0x01, 0x02, 0x03)
val split2Sha256 = "A5BYxvLAy0ksUzsKTRTvd8wPeKvMztUofYShogEc-4E"
packageInfo.applicationInfo.splitSourceDirs = arrayOf(
File(tmpFile, "test-$split1Name.apk").apply {
assertTrue(createNewFile())
writeBytes(split1Bytes)
}.absolutePath,
File(tmpFile, "test-$split2Name.apk").apply {
assertTrue(createNewFile())
writeBytes(split2Bytes)
}.absolutePath
)
// create streams
val apkOutputStream = ByteArrayOutputStream()
val split1OutputStream = ByteArrayOutputStream()
val split2OutputStream = ByteArrayOutputStream()
// expected new metadata for package
val updatedMetadata = PackageMetadata(
time = 0L,
state = UNKNOWN_ERROR,
version = packageInfo.longVersionCode,
installer = getRandomString(),
splits = listOf(
ApkSplit(split1Name, split1Sha256),
ApkSplit(split2Name, split2Sha256)
),
sha256 = "eHx5jjmlvBkQNVuubQzYejay4Q_QICqD47trAF2oNHI",
signatures = packageMetadata.signatures
)
expectChecks()
coEvery { streamGetter.invoke("") } returns apkOutputStream
coEvery { streamGetter.invoke("_$split1Sha256") } returns split1OutputStream
coEvery { streamGetter.invoke("_$split2Sha256") } returns split2OutputStream
every {
pm.getInstallSourceInfo(packageInfo.packageName)
} returns InstallSourceInfo(null, null, null, updatedMetadata.installer)
assertEquals(
updatedMetadata,
apkBackup.backupApkIfNecessary(packageInfo, UNKNOWN_ERROR, streamGetter)
)
assertArrayEquals(apkBytes, apkOutputStream.toByteArray())
assertArrayEquals(split1Bytes, split1OutputStream.toByteArray())
assertArrayEquals(split2Bytes, split2OutputStream.toByteArray())
}
private fun expectChecks(packageMetadata: PackageMetadata = this.packageMetadata) {
every { settingsManager.backupApks() } returns true
every {
metadataManager.getPackageMetadata(packageInfo.packageName)
} returns packageMetadata
every { PackageUtils.computeSha256DigestBytes(signatureBytes) } returns signatureHash
every { sigInfo.hasMultipleSigners() } returns false
every { sigInfo.signingCertificateHistory } returns sigs
}
}
| 98 | null | 9 | 998 | 2bbeece7b7a09e1b3d19f15cb037b197e7e032c6 | 8,949 | seedvault | Apache License 2.0 |
app/src/main/java/com/jesen/cod/gitappkotlin/utils/NaviViewExt.kt | Jesen0823 | 343,987,158 | false | {"Java Properties": 3, "Gradle": 7, "Shell": 1, "Text": 1, "Ignore List": 5, "Batchfile": 1, "Markdown": 2, "Proguard": 4, "Kotlin": 125, "INI": 5, "XML": 69, "Java": 8, "JSON": 3} | import android.annotation.SuppressLint
import android.support.annotation.IdRes
import android.support.design.widget.NavigationView
import android.support.v4.view.GravityCompat
import android.support.v4.view.ViewCompat
import android.support.v4.widget.DrawerLayout
import android.support.v7.view.menu.MenuItemImpl
import android.view.View
import com.jesen.cod.common.ext.otherwise
import com.jesen.cod.common.ext.yes
import com.jesen.cod.gitappkotlin.utils.AppLog
//import com.jesen.cod.gitappkotlin.view.config.NavViewItem
inline fun NavigationView.doOnLayoutAvailable(crossinline black: () -> Unit) {
ViewCompat.isLaidOut(this).yes {
// 布局重新绘制
black()
}.otherwise {
addOnLayoutChangeListener(object : View.OnLayoutChangeListener {
override fun onLayoutChange(
v: View?,
left: Int,
top: Int,
right: Int,
bottom: Int,
oldLeft: Int,
oldTop: Int,
oldRight: Int,
oldBottom: Int
) {
removeOnLayoutChangeListener(this)
black()
}
})
}
}
/**
* 选择指定的菜单,并执行相应的操作
*/
@SuppressLint("RestrictedApi")
fun NavigationView.selectItem(@IdRes resId: Int) {
doOnLayoutAvailable {
//AppLog.d("selectItem ", "title:${NavViewItem[resId].title}")
setCheckedItem(resId)
(menu.findItem(resId) as MenuItemImpl)()
}
}
inline fun DrawerLayout.afterClosed(crossinline black: () -> Unit) {
if (isDrawerOpen(GravityCompat.START)) {
closeDrawer(GravityCompat.START)
addDrawerListener(
object : DrawerLayout.DrawerListener {
override fun onDrawerStateChanged(p0: Int) = Unit
override fun onDrawerSlide(p0: View, p1: Float) = Unit
override fun onDrawerOpened(p0: View) = Unit
override fun onDrawerClosed(p0: View) {
removeDrawerListener(this)
black()
}
}
)
} else {
black()
}
} | 2 | Kotlin | 0 | 0 | 69f9b7ec07bc70545feff5788b02a29373fe66cf | 2,129 | GitAppKotlin | Apache License 2.0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.