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 |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|
evergreen/src/main/java/app/evergreen/extensions/Email.kt
|
google
| 243,642,653 | false | null |
package app.evergreen.extensions
import android.net.Uri
object Email {
fun createEmailUri(recipientAddress: String, subject: String, body: String) =
Uri.parse("mailto:$recipientAddress?subject=${subject.encodeForEmail()}&body=${body.encodeForEmail()}")
}
| 2 |
Kotlin
|
5
| 9 |
af3a51abd110912135cafd16776b8fbf219225f2
| 263 |
evergreen-checker
|
Apache License 2.0
|
app/src/main/java/fi/efelantti/frisbeegolfer/ZipManager.kt
|
efelantti
| 299,355,717 | false | null |
import android.content.Context
import android.net.Uri
import java.io.*
import java.util.zip.ZipEntry
import java.util.zip.ZipInputStream
import java.util.zip.ZipOutputStream
private const val MODE_WRITE = "w"
private const val MODE_READ = "r"
fun zip(zipFile: File, files: List<File>) {
ZipOutputStream(BufferedOutputStream(FileOutputStream(zipFile))).use { outStream ->
zip(outStream, files)
}
}
fun zip(context: Context, zipFile: Uri, files: List<File>) {
context.contentResolver.openFileDescriptor(zipFile, MODE_WRITE).use { descriptor ->
descriptor?.fileDescriptor?.let {
ZipOutputStream(BufferedOutputStream(FileOutputStream(it))).use { outStream ->
zip(outStream, files)
}
}
}
}
private fun zip(outStream: ZipOutputStream, files: List<File>) {
files.forEach { file ->
outStream.putNextEntry(ZipEntry(file.name))
BufferedInputStream(FileInputStream(file)).use { inStream ->
inStream.copyTo(outStream)
}
}
}
fun unzip(zipFile: File, location: File) {
ZipInputStream(BufferedInputStream(FileInputStream(zipFile))).use { inStream ->
unzip(inStream, location)
}
}
fun unzip(context: Context, zipFile: Uri, location: File) {
context.contentResolver.openFileDescriptor(zipFile, MODE_READ).use { descriptor ->
descriptor?.fileDescriptor?.let {
ZipInputStream(BufferedInputStream(FileInputStream(it))).use { inStream ->
unzip(inStream, location)
}
}
}
}
private fun unzip(inStream: ZipInputStream, location: File) {
if (location.exists() && !location.isDirectory)
throw IllegalStateException("Location file must be directory or not exist")
if (!location.isDirectory) location.mkdirs()
val locationPath = location.absolutePath.let {
if (!it.endsWith(File.separator)) "$it${File.separator}"
else it
}
var zipEntry: ZipEntry?
var unzipFile: File
var unzipParentDir: File?
while (inStream.nextEntry.also { zipEntry = it } != null) {
unzipFile = File(locationPath + zipEntry!!.name)
if (zipEntry!!.isDirectory) {
if (!unzipFile.isDirectory) unzipFile.mkdirs()
} else {
unzipParentDir = unzipFile.parentFile
if (unzipParentDir != null && !unzipParentDir.isDirectory) {
unzipParentDir.mkdirs()
}
BufferedOutputStream(FileOutputStream(unzipFile)).use { outStream ->
inStream.copyTo(outStream)
}
}
}
}
| 0 |
Kotlin
|
1
| 0 |
ee88617fdb907d0071bba4bdab8f6c7a7961d9f7
| 2,600 |
Frisbeegolfer
|
MIT License
|
project/kimmer-sql/src/main/kotlin/org/babyfish/kimmer/sql/meta/config/MiddleTable.kt
|
babyfish-ct
| 447,936,858 | false |
{"Kotlin": 967243}
|
package org.babyfish.kimmer.sql.meta.config
data class MiddleTable (
val tableName: String,
val joinColumnName: String,
val targetJoinColumnName: String
): Storage
| 0 |
Kotlin
|
3
| 37 |
8345d9112292b7f13aaccae681bc91cb51fa9315
| 176 |
kimmer
|
MIT License
|
src/main/kotlin/biz/lermitage/sub/service/checker/impl/VeraCryptChecker.kt
|
jonathanlermitage
| 262,889,547 | false |
{"Kotlin": 65831, "Shell": 1357, "Batchfile": 1172}
|
package biz.lermitage.sub.service.checker.impl
import biz.lermitage.sub.model.Category
import biz.lermitage.sub.model.Logo
import biz.lermitage.sub.model.SoftwareUpdate
import biz.lermitage.sub.service.checker.Checker
import biz.lermitage.sub.service.scrapper.Scrapper
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.stereotype.Service
/**
* VeraCrypt checker.
*/
@Service
class VeraCryptChecker : Checker {
@Autowired
lateinit var scrapper: Scrapper
override fun check(): SoftwareUpdate {
val body = scrapper.fetchHtml("https://www.veracrypt.fr/en/Downloads.html")
var version = body.getElementsByTag("h3")[0].text()
version = version.replace("Latest Stable Release:", "").trim()
return SoftwareUpdate(
listOf(Category.VERACRYPT.label),
"VeraCrypt",
"https://www.veracrypt.fr/en/Downloads.html",
version,
logo = Logo.VERACRYPT
)
}
}
| 0 |
Kotlin
|
3
| 5 |
d391c16da5f08cd5d8dab62b7020fd2a8a2eebd7
| 998 |
software-updates-bot
|
MIT License
|
app/src/main/java/reach52/marketplace/community/resident/adapter/LogisticResidentsAdapter.kt
|
reach52
| 422,514,975 | false |
{"Kotlin": 1436380, "Java": 18303}
|
package reach52.marketplace.community.resident.adapter
import android.content.Context
import android.view.LayoutInflater
import android.view.ViewGroup
import androidx.databinding.DataBindingUtil
import androidx.recyclerview.widget.RecyclerView
import reach52.marketplace.community.R
import reach52.marketplace.community.databinding.XLogisticResidentListItemBinding
import reach52.marketplace.community.resident.entity.Resident
class LogisticResidentsAdapter(
private val context: Context,
private val onItemClick: (resident: Resident) -> Unit = {}
) : RecyclerView.Adapter<LogisticResidentsAdapter.ViewHolder>() {
var residentsList = ArrayList<Resident>()
set(list) {
field = list
notifyDataSetChanged()
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
return ViewHolder(
DataBindingUtil.inflate(LayoutInflater.from(context), R.layout.x_logistic_resident_list_item, parent, false)
)
}
override fun getItemCount(): Int {
return residentsList.size
}
override fun onBindViewHolder(holder: ViewHolder, position: Int) {
val resident = residentsList[position]
holder.setResident(resident)
holder.itemView.setOnClickListener {
onItemClick(resident)
}
}
class ViewHolder(val b: XLogisticResidentListItemBinding) : RecyclerView.ViewHolder(b.root) {
fun setResident(resident: Resident) {
b.resident = resident
}
}
}
| 0 |
Kotlin
|
0
| 0 |
629c52368d06f978f19238d0bd865f4ef84c23d8
| 1,400 |
Marketplace-Community-Edition
|
MIT License
|
waltid-libraries/waltid-did/src/commonTest/kotlin/id/walt/did/serialize/service/ServiceMapTest.kt
|
walt-id
| 701,058,624 | false |
{"Kotlin": 3448224, "Vue": 474904, "TypeScript": 129086, "Swift": 40383, "JavaScript": 18819, "Ruby": 15159, "Dockerfile": 13118, "Python": 3114, "Shell": 1783, "Objective-C": 388, "CSS": 345, "C": 104}
|
package id.walt.did.serialize.service
import id.walt.crypto.utils.JsonUtils.toJsonElement
import id.walt.did.dids.document.models.service.ServiceMap
import id.walt.did.dids.document.models.service.ServiceEndpointObject
import id.walt.did.dids.document.models.service.ServiceEndpointURL
import id.walt.did.dids.document.models.service.RegisteredServiceType
import kotlinx.serialization.encodeToString
import kotlinx.serialization.json.Json
import kotlinx.serialization.json.buildJsonObject
import kotlin.test.Test
import kotlin.test.assertEquals
import kotlin.test.assertTrue
class ServiceMapTest {
private val customProperties = mapOf(
"ckey1" to "cvalue1".toJsonElement(),
"ckey2" to "cvalue2".toJsonElement(),
)
@Test
fun testServiceMapEndpointURLSerialization() {
//with URL endpoint block and no custom properties
val svcBlockWithURLEndpointNoCustom = ServiceMap(
id = "some-id",
type = setOf(RegisteredServiceType.DIDCommMessaging.toString()),
serviceEndpoint = setOf(ServiceEndpointURL("some-url"))
)
val svcBlockWithURLEndpointNoCustomJsonEncodedString =
"""{"id":"some-id","type":"DIDCommMessaging","serviceEndpoint":"some-url"}"""
//encode single element with URL endpoint and no custom properties
assertEquals(
expected = svcBlockWithURLEndpointNoCustomJsonEncodedString,
actual = Json.encodeToString(svcBlockWithURLEndpointNoCustom),
)
//decode single element with URL endpoint and no custom properties
assertEquals(
expected = svcBlockWithURLEndpointNoCustom,
actual = Json.decodeFromString(svcBlockWithURLEndpointNoCustomJsonEncodedString),
)
val svcBlockWithURLEndpointNoCustomListJsonEncodedString =
"""[${svcBlockWithURLEndpointNoCustomJsonEncodedString}]"""
//encode single element with URL endpoint and no custom properties as list
assertEquals(
expected = svcBlockWithURLEndpointNoCustomListJsonEncodedString,
actual = Json.encodeToString(setOf(svcBlockWithURLEndpointNoCustom))
)
//decode single element with URL endpoint and no custom properties as list
assertEquals(
expected = setOf(svcBlockWithURLEndpointNoCustom),
actual = Json.decodeFromString(svcBlockWithURLEndpointNoCustomListJsonEncodedString)
)
//with URL endpoint block and custom properties
val svcBlockWithURLEndpointCustom = ServiceMap(
id = "some-id",
type = setOf(RegisteredServiceType.DIDCommMessaging.toString()),
serviceEndpoint = setOf(ServiceEndpointURL("some-url")),
customProperties = customProperties,
)
val svcBlockWithURLEndpointCustomJsonEncodedString =
"""{"id":"some-id","type":"DIDCommMessaging","serviceEndpoint":"some-url","ckey1":"cvalue1","ckey2":"cvalue2"}"""
//encode single element with URL endpoint and custom properties
assertEquals(
expected = svcBlockWithURLEndpointCustomJsonEncodedString,
actual = Json.encodeToString(svcBlockWithURLEndpointCustom),
)
//decode single element with URL endpoint and custom properties
assertEquals(
expected = svcBlockWithURLEndpointCustom,
actual = Json.decodeFromString(svcBlockWithURLEndpointCustomJsonEncodedString),
)
val svcBlockWithURLEndpointCustomListJsonEncodedString =
"""[${svcBlockWithURLEndpointCustomJsonEncodedString}]"""
//encode single element with URL endpoint and custom properties as list
assertEquals(
expected = svcBlockWithURLEndpointCustomListJsonEncodedString,
actual = Json.encodeToString(setOf(svcBlockWithURLEndpointCustom))
)
//decode single element with URL endpoint and custom properties as list
assertEquals(
expected = setOf(svcBlockWithURLEndpointCustom),
actual = Json.decodeFromString(svcBlockWithURLEndpointCustomListJsonEncodedString)
)
}
@Test
fun testServiceMapEndpointObjectSerialization() {
//with object endpoint block and no custom properties
val svcBlockWithObjectEndpointNoCustom = ServiceMap(
id = "some-id",
type = setOf(RegisteredServiceType.DIDCommMessaging.toString()),
serviceEndpoint = setOf(
ServiceEndpointObject(
buildJsonObject {
put("some-url-property", "url-value".toJsonElement())
put("some-additional-property", "some-value".toJsonElement())
}
),
),
)
val svcBlockWithObjectEndpointNoCustomJsonEncodedString =
"""{"id":"some-id","type":"DIDCommMessaging","serviceEndpoint":{"some-url-property":"url-value","some-additional-property":"some-value"}}"""
//encode single element with object endpoint and no custom properties
assertEquals(
expected = svcBlockWithObjectEndpointNoCustomJsonEncodedString,
actual = Json.encodeToString(svcBlockWithObjectEndpointNoCustom),
)
//decode single element with object endpoint and no custom properties
assertEquals(
expected = svcBlockWithObjectEndpointNoCustom,
actual = Json.decodeFromString(svcBlockWithObjectEndpointNoCustomJsonEncodedString),
)
val svcBlockWithObjectEndpointNoCustomListJsonEncodedString =
"""[${svcBlockWithObjectEndpointNoCustomJsonEncodedString}]"""
//encode single element with object endpoint and no custom properties as list
assertEquals(
expected = svcBlockWithObjectEndpointNoCustomListJsonEncodedString,
actual = Json.encodeToString(setOf(svcBlockWithObjectEndpointNoCustom)),
)
//decode single element with object endpoint and no custom properties as list
assertEquals(
expected = setOf(svcBlockWithObjectEndpointNoCustom),
actual = Json.decodeFromString(svcBlockWithObjectEndpointNoCustomListJsonEncodedString),
)
//with object endpoint block and custom properties
val svcBlockWithObjectEndpointCustom = ServiceMap(
id = "some-id",
type = setOf(RegisteredServiceType.DIDCommMessaging.toString()),
serviceEndpoint = setOf(
ServiceEndpointObject(
buildJsonObject {
put("some-url-property", "url-value".toJsonElement())
put("some-additional-property", "some-value".toJsonElement())
}
),
),
customProperties = customProperties,
)
val svcBlockWithObjectEndpointCustomJsonEncodedString =
"""{"id":"some-id","type":"DIDCommMessaging","serviceEndpoint":{"some-url-property":"url-value","some-additional-property":"some-value"},"ckey1":"cvalue1","ckey2":"cvalue2"}"""
//encode single element with object endpoint and custom properties
assertEquals(
expected = svcBlockWithObjectEndpointCustomJsonEncodedString,
actual = Json.encodeToString(svcBlockWithObjectEndpointCustom),
)
//decode single element with object endpoint and custom properties
assertEquals(
expected = svcBlockWithObjectEndpointCustom,
actual = Json.decodeFromString(svcBlockWithObjectEndpointCustomJsonEncodedString),
)
val svcBlockWithObjectEndpointCustomListJsonEncodedString =
"""[${svcBlockWithObjectEndpointCustomJsonEncodedString}]"""
//encode single element with object endpoint and custom properties as list
assertEquals(
expected = svcBlockWithObjectEndpointCustomListJsonEncodedString,
actual = Json.encodeToString(setOf(svcBlockWithObjectEndpointCustom)),
)
//decode single element with object endpoint and custom properties as list
assertEquals(
expected = setOf(svcBlockWithObjectEndpointCustom),
actual = Json.decodeFromString(svcBlockWithObjectEndpointCustomListJsonEncodedString),
)
}
@Test
fun testServiceMapWithSameEndpoints() {
val svcBlockWithURLEndpoints = ServiceMap(
id = "some-id",
type = setOf(RegisteredServiceType.DIDCommMessaging.toString()),
serviceEndpoint = setOf(
ServiceEndpointURL("some-url"),
ServiceEndpointURL("some-url"),
)
)
assertTrue(svcBlockWithURLEndpoints.serviceEndpoint.size == 1)
val svcBlockWithURLEndpointsJsonEncodedString =
"""{"id":"some-id","type":"DIDCommMessaging","serviceEndpoint":"some-url"}"""
//encode
assertEquals(
expected = svcBlockWithURLEndpointsJsonEncodedString,
actual = Json.encodeToString(svcBlockWithURLEndpoints)
)
//decode
assertEquals(
expected = svcBlockWithURLEndpoints,
actual = Json.decodeFromString(svcBlockWithURLEndpointsJsonEncodedString)
)
val svcBlockWithObjectEndpoints = ServiceMap(
id = "some-id",
type = setOf(RegisteredServiceType.DIDCommMessaging.toString()),
serviceEndpoint = setOf(
ServiceEndpointObject(
buildJsonObject {
put("some-url-property", "url-value".toJsonElement())
put("some-additional-property", "some-value".toJsonElement())
}
),
ServiceEndpointObject(
buildJsonObject {
put("some-url-property", "url-value".toJsonElement())
put("some-additional-property", "some-value".toJsonElement())
}
),
),
)
assertTrue(svcBlockWithObjectEndpoints.serviceEndpoint.size == 1)
val svcBlockWithObjectEndpointsJsonEncodedString =
"""{"id":"some-id","type":"DIDCommMessaging","serviceEndpoint":{"some-url-property":"url-value","some-additional-property":"some-value"}}"""
//encode
assertEquals(
expected = svcBlockWithObjectEndpointsJsonEncodedString,
actual = Json.encodeToString(svcBlockWithObjectEndpoints)
)
//decode
assertEquals(
expected = svcBlockWithObjectEndpoints,
actual = Json.decodeFromString(svcBlockWithObjectEndpointsJsonEncodedString)
)
}
@Test
fun testServiceMapWithMixEndpoints() {
val svcBlock = ServiceMap(
id = "some-id",
type = setOf(RegisteredServiceType.DIDCommMessaging.toString()),
serviceEndpoint = setOf(
ServiceEndpointURL("some-url"),
ServiceEndpointObject(
buildJsonObject {
put("some-url-property", "url-value".toJsonElement())
put("some-additional-property", "some-value".toJsonElement())
}
),
)
)
assertTrue(svcBlock.serviceEndpoint.size == 2)
val svcBlockJsonEncodedString =
"""{"id":"some-id","type":"DIDCommMessaging","serviceEndpoint":["some-url",{"some-url-property":"url-value","some-additional-property":"some-value"}]}"""
//encode
assertEquals(
expected = svcBlockJsonEncodedString,
actual = Json.encodeToString(svcBlock)
)
//decode
assertEquals(
expected = svcBlock,
actual = Json.decodeFromString(svcBlockJsonEncodedString)
)
}
@Test
fun testServiceMapMultipleTypes() {
val svcBlock = ServiceMap(
id = "some-id",
type = setOf(
RegisteredServiceType.DIDCommMessaging.toString(),
"some-other-type",
),
serviceEndpoint = setOf(
ServiceEndpointURL("some-url"),
)
)
assertTrue(svcBlock.type.size == 2)
val svcBlockJsonEncodedString =
"""{"id":"some-id","type":["DIDCommMessaging","some-other-type"],"serviceEndpoint":"some-url"}"""
//encode
assertEquals(
expected = svcBlockJsonEncodedString,
actual = Json.encodeToString(svcBlock)
)
//decode
assertEquals(
expected = svcBlock,
actual = Json.decodeFromString(svcBlockJsonEncodedString),
)
}
}
| 20 |
Kotlin
|
46
| 121 |
48c6b8cfef532e7e837db0bdb39ba64def985568
| 12,775 |
waltid-identity
|
Apache License 2.0
|
app/src/main/kotlin/pro/stuermer/dailyexpenses/data/persistence/ExpensesDao.kt
|
thebino
| 590,016,472 | false | null |
package pro.stuermer.dailyexpenses.data.persistence
import androidx.room.Dao
import androidx.room.Insert
import androidx.room.OnConflictStrategy
import androidx.room.Query
import androidx.room.Update
import java.time.LocalDate
import kotlinx.coroutines.flow.Flow
import pro.stuermer.dailyexpenses.data.persistence.model.Expense
@Dao
interface ExpensesDao {
@Query("SELECT * FROM expenses WHERE expenseDate >= :fromDate and expenseDate <= :toDate")
fun getExpensesForDate(fromDate: LocalDate, toDate: LocalDate): Flow<List<Expense>>
@Query("SELECT * FROM expenses")
fun getAllExpenses(): Flow<List<Expense>>
@Insert(onConflict = OnConflictStrategy.REPLACE)
suspend fun insert(vararg entries: Expense)
@Update(onConflict = OnConflictStrategy.REPLACE)
suspend fun update(vararg expense: Expense)
@Query("DELETE FROM expenses WHERE identifier IN (:ids)")
suspend fun delete(ids: List<String>)
@Query("DELETE FROM expenses")
fun deleteAll()
}
| 0 |
Kotlin
|
0
| 0 |
7974b772596a7027b218040e7e05495aa53959c6
| 993 |
DailyExpenses
|
Apache License 2.0
|
app/src/main/java/com/kalugin19/todoapp/ui/tasks/TasksViewModel.kt
|
kalugin19
| 273,795,840 | false | null |
package com.kalugin19.todoapp.ui.tasks
import androidx.lifecycle.*
import com.kalugin19.todoapp.data.pojo.Task
import com.kalugin19.todoapp.data.pojo.TaskType
import com.kalugin19.todoapp.data.repository.TasksRepository
import com.kalugin19.todoapp.util.Event
import kotlinx.coroutines.launch
class TasksViewModel(
private val tasksRepository: TasksRepository,
handle: SavedStateHandle
) : ViewModel(), ITaskClickListener {
private val _typeLiveData: MutableLiveData<TaskType> = MutableLiveData(TaskType.ALL)
val typeLiveData: LiveData<TaskType> = _typeLiveData
private val _openTaskLiveData: MutableLiveData<String> by lazy { MutableLiveData<String>() }
val openTaskLiveData: LiveData<Event<String>> by lazy {
_openTaskLiveData.map {
val event = Event<String>(it)
event
}
}
val tasksLiveData = Transformations.switchMap(typeLiveData) {
tasksRepository.loadTasks(it)
}
val emptyLiveData: LiveData<Boolean> = Transformations.map(tasksLiveData) {
it?.isEmpty() == true
}
fun loadTasks(type: TaskType) {
_typeLiveData.postValue(type)
}
override fun openTask(id: String) {
_openTaskLiveData.postValue(id)
}
override fun completeTask(task: Task, completed: Boolean) {
viewModelScope.launch {
task.isCompleted = completed
tasksRepository.update(task)
}
}
}
| 0 |
Kotlin
|
0
| 0 |
b14e929fa0ffa2c3c3b038081434dc13eae786a5
| 1,442 |
simple_to_do
|
Apache License 2.0
|
db-objekts-core/src/test/kotlin/com/dbobjekts/component/SelectResultsComponentTest.kt
|
jaspersprengers
| 576,889,038 | false |
{"Kotlin": 1251411, "PLpgSQL": 45872, "Dockerfile": 2463}
|
package com.dbobjekts.component
import com.dbobjekts.testdb.acme.Aliases
import com.dbobjekts.testdb.acme.HasAliases
import com.dbobjekts.testdb.acme.core.Employee
import org.assertj.core.api.Assertions.assertThat
import org.assertj.core.api.Assertions.assertThatThrownBy
import org.junit.jupiter.api.BeforeAll
import org.junit.jupiter.api.Test
class SelectResultsComponentTest : HasAliases by Aliases {
companion object {
val tm = AcmeDB.transactionManager
@BeforeAll
@JvmStatic
fun setup() {
AcmeDB.createExampleCatalog(AcmeDB.transactionManager)
}
}
@Test
fun `select with foreach loop`() {
tm({
var counter = 0
it.select(Employee.name)
.forEachRow({ nmb, row ->
counter += 1
nmb < 5 // break after 5 rows
})
assertThat(counter).isEqualTo(5)
})
}
@Test
fun `test select all employees with iterator`() {
tm({
val buffer = mutableListOf<String?>()
val iterator = it.select(em.name).where(em.id.lt(11))
.orderAsc(em.name).iterator()
while (iterator.hasNext()) {
buffer.add(iterator.next())
}
assertThat(buffer.size).isEqualTo(10)
})
}
@Test
fun `cannot return iterator from transaction block`() {
assertThatThrownBy {
val ret: Iterator<String> = tm({ it.select(em.name).where(em.id.lt(11)).iterator() })
}.hasMessageEndingWith("An Iterator over a ResultSet must be consumed within the transaction block.")
}
@Test
fun `cannot fetch results twice`() {
tm({
val statement = it.select(em.name).where(em.id.lt(11))
statement.asList()
assertThatThrownBy {
statement.asList()
}.hasMessageEndingWith("Cannot retrieve results twice.")
assertThatThrownBy {
statement.first()
}.hasMessageEndingWith("Cannot retrieve results twice.")
assertThatThrownBy {
statement.forEachRow({ _, _ -> true })
}.hasMessageEndingWith("Cannot retrieve results twice.")
assertThatThrownBy {
statement.iterator()
}.hasMessageEndingWith("Cannot retrieve results twice.")
})
}
@Test
fun `select slice of all employees`() {
tm({
val two: List<String> = it.select(em.name).orderAsc(em.name).asSlice(2, 4)
//skipping Alice and Bob
assertThat(two).containsExactly("Charlie", "Diane", "Eve", "Fred")
})
}
@Test
fun `select slice for unavailable range`() {
tm({
val list = it.select(em.name).orderAsc(em.name).asSlice(11, 4)
assertThat(list).isEmpty()
})
}
}
| 0 |
Kotlin
|
2
| 4 |
f4e92c78539909110cf0ab9da1713c20a9b4888b
| 2,919 |
db-objekts
|
Apache License 2.0
|
straight/src/commonMain/kotlin/me/localx/icons/straight/outline/Plus.kt
|
localhostov
| 808,861,591 | false |
{"Kotlin": 79430321, "HTML": 331, "CSS": 102}
|
package me.localx.icons.straight.outline
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.PathFillType.Companion.NonZero
import androidx.compose.ui.graphics.SolidColor
import androidx.compose.ui.graphics.StrokeCap.Companion.Butt
import androidx.compose.ui.graphics.StrokeJoin.Companion.Miter
import androidx.compose.ui.graphics.vector.ImageVector
import androidx.compose.ui.graphics.vector.ImageVector.Builder
import androidx.compose.ui.graphics.vector.path
import androidx.compose.ui.unit.dp
import me.localx.icons.straight.Icons
public val Icons.Outline.Plus: ImageVector
get() {
if (_plus != null) {
return _plus!!
}
_plus = Builder(name = "Plus", defaultWidth = 512.0.dp, defaultHeight = 512.0.dp,
viewportWidth = 24.0f, viewportHeight = 24.0f).apply {
path(fill = SolidColor(Color(0xFF000000)), stroke = null, strokeLineWidth = 0.0f,
strokeLineCap = Butt, strokeLineJoin = Miter, strokeLineMiter = 4.0f,
pathFillType = NonZero) {
moveTo(24.0f, 11.0f)
lineToRelative(-11.0f, 0.0f)
lineToRelative(0.0f, -11.0f)
lineToRelative(-2.0f, 0.0f)
lineToRelative(0.0f, 11.0f)
lineToRelative(-11.0f, 0.0f)
lineToRelative(0.0f, 2.0f)
lineToRelative(11.0f, 0.0f)
lineToRelative(0.0f, 11.0f)
lineToRelative(2.0f, 0.0f)
lineToRelative(0.0f, -11.0f)
lineToRelative(11.0f, 0.0f)
lineToRelative(0.0f, -2.0f)
close()
}
}
.build()
return _plus!!
}
private var _plus: ImageVector? = null
| 1 |
Kotlin
|
0
| 5 |
cbd8b510fca0e5e40e95498834f23ec73cc8f245
| 1,775 |
icons
|
MIT License
|
test/serialize_and_deserialize_binary_tree/CodecTest.kt
|
masx200
| 787,837,300 | false |
{"Kotlin": 58795, "Batchfile": 92}
|
package com.github.masx200.leetcode_test_kotlin.serialize_and_deserialize_binary_tree
import com.github.masx200.leetcode_test_kotlin.insert_into_a_binary_search_tree.TreeNode
import org.junit.jupiter.api.Assertions.assertEquals
import org.junit.jupiter.api.Test
internal class CodecTest {
@Test
fun testserialize() {
assertEquals(
"[100,[-200,null,null],[300,[100,[20,null,null],[300,null,null]],null]]",
Codec().serialize(
Codec().deserialize(
"[100,[-200,null,null],[300,[100,[20,null,null],[300,null,null]],null]]",
),
),
)
assertEquals(
Codec().serialize(
(
TreeNode(
100,
TreeNode(-200),
TreeNode(300, TreeNode(100, TreeNode(20), TreeNode(300))),
)
),
),
Codec().serialize(
Codec().deserialize(
Codec().serialize(
TreeNode(
100,
TreeNode(-200),
TreeNode(
300,
TreeNode(
100,
TreeNode(
20,
),
TreeNode(
300,
),
),
),
),
),
),
),
)
}
@Test
fun testdeserialize() {
assertEquals(
"[100,[20,null,null],[300,[100,[20,null,null],[300,null,null]],null]]",
Codec().serialize(
Codec().deserialize(
"[100,[20,null,null],[300,[100,[20,null,null],[300,null,null]],null]]",
),
),
)
assertEquals("null", Codec().serialize(Codec().deserialize("null")))
assertEquals(null, Codec().deserialize(Codec().serialize(null)))
}
}
| 1 |
Kotlin
|
0
| 1 |
ada65ca5a48d944f992fbabb64ad25fc41944463
| 2,262 |
leetcode-test-kotlin
|
Mulan Permissive Software License, Version 2
|
app/src/main/java/io/horizontalsystems/bankwallet/ui/compose/components/HsIconButton.kt
|
horizontalsystems
| 142,825,178 | false | null |
package io.horizontalsystems.bankwallet.ui.compose.components
import androidx.compose.foundation.clickable
import androidx.compose.foundation.interaction.MutableInteractionSource
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.defaultMinSize
import androidx.compose.material.ContentAlpha
import androidx.compose.material.LocalContentAlpha
import androidx.compose.material.ripple.rememberRipple
import androidx.compose.runtime.Composable
import androidx.compose.runtime.CompositionLocalProvider
import androidx.compose.runtime.remember
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.semantics.Role
import androidx.compose.ui.unit.dp
import io.horizontalsystems.bankwallet.ui.compose.ComposeAppTheme
@Composable
fun HsIconButton(
onClick: () -> Unit,
modifier: Modifier = Modifier,
enabled: Boolean = true,
rippleColor: Color = ComposeAppTheme.colors.oz,
interactionSource: MutableInteractionSource = remember { MutableInteractionSource() },
content: @Composable () -> Unit
) {
Box(
modifier = modifier
.defaultMinSize(48.dp)
.clickable(
onClick = onClick,
enabled = enabled,
role = Role.Button,
interactionSource = interactionSource,
indication = rememberRipple(bounded = false, radius = RippleRadius, color = rippleColor)
),
contentAlignment = Alignment.Center
) {
val contentAlpha = if (enabled) LocalContentAlpha.current else ContentAlpha.disabled
CompositionLocalProvider(LocalContentAlpha provides contentAlpha, content = content)
}
}
// Default radius of an unbounded ripple in an IconButton
private val RippleRadius = 24.dp
| 136 | null |
288
| 551 |
c48fdb4463a1245418edd0ace4d1e7d029bc4d70
| 1,851 |
unstoppable-wallet-android
|
MIT License
|
app/src/main/java/com/shaon2016/compose/HiltApplication.kt
|
shaon2016
| 606,093,998 | false | null |
package com.shaon2016.compose
import android.app.Application
import dagger.hilt.android.HiltAndroidApp
@HiltAndroidApp
class HiltApplication : Application()
| 0 |
Kotlin
|
0
| 0 |
c8475370f0df97669bf76b2a0f571f26c7884789
| 158 |
CleanArchitectureWithJetpackCompose
|
MIT License
|
app/src/main/kotlin/site/paulo/localchat/ui/utils/ViewExtensions.kt
|
paulofernando
| 86,396,589 | false |
{"Kotlin": 175330, "Java": 37488}
|
package site.paulo.localchat.ui.utils
import android.content.Context
import android.view.View
val View.ctx: Context
get() = context
| 8 |
Kotlin
|
0
| 1 |
d75bcbb39240a709c3efd45574bdb1e72005cdfe
| 138 |
localchat
|
Apache License 2.0
|
core/database/src/main/kotlin/com/anbui/recipely/core/database/relations/RecipeAndOwner.kt
|
AnBuiii
| 667,858,307 | false |
{"Kotlin": 596893}
|
package com.vanbui.recipely.core.database.relations
import androidx.room.Embedded
import androidx.room.Relation
import com.vanbui.recipely.core.database.entities.AccountEntity
import com.vanbui.recipely.core.database.entities.LikeEntity
import com.vanbui.recipely.core.database.entities.RecipeEntity
import com.vanbui.recipely.core.database.entities.RecipeIngredientCrossRef
import com.vanbui.recipely.core.database.entities.StepEntity
import com.vanbui.recipely.core.database.entities.toStep
import com.vanbui.recipely.core.model.IngredientItem
import com.vanbui.recipely.core.model.Recipe
data class RecipeAndOwner(
@Embedded
val recipe: RecipeEntity,
@Relation(
parentColumn = "owner_id",
entityColumn = "_id"
)
val owner: AccountEntity,
@Relation(
parentColumn = "_id",
entityColumn = "recipe_id"
)
val steps: List<StepEntity>,
@Relation(
parentColumn = "_id",
entityColumn = "recipe_id"
)
val likes: List<LikeEntity>,
@Relation(
parentColumn = "_id",
entityColumn = "recipe_id",
entity = RecipeIngredientCrossRef::class
)
val ingredients: List<IngredientAndCrossRef>
)
fun RecipeAndOwner.toRecipe(accountId: String?): Recipe {
return Recipe(
id = recipe.id,
title = recipe.title,
imageUrl = recipe.imageUrl,
description = recipe.description,
isLike = likes.any { like -> like.accountId == accountId },
cookTime = "${
steps.sumOf { step -> step.period.toDouble() }.toInt()
} Min",
servings = recipe.servings,
totalCalories = ingredients.sumOf { ingredient ->
ingredient.crossRef.amount.toDouble() * ingredient.ingredient.kcal
}
.toFloat(),
totalCarb = ingredients.sumOf { ingredient ->
ingredient.crossRef.amount.toDouble() * ingredient.ingredient.carb
}
.toFloat(),
totalProtein = ingredients.sumOf { ingredient ->
ingredient.crossRef.amount.toDouble() * ingredient.ingredient.protein
}
.toFloat(),
totalFat = ingredients.sumOf { ingredient ->
ingredient.crossRef.amount.toDouble() * ingredient.ingredient.fat
}
.toFloat(),
ownerId = owner.id,
ownerName = owner.firstName + " " + owner.lastName,
ownerAvatarUrl = owner.avatarUrl,
ownerDescription = owner.bio,
instructions = steps.map {
it.toStep()
},
ingredients = ingredients.map { ingredient ->
IngredientItem(
imageUrl = ingredient.ingredient.imageUrl,
name = ingredient.ingredient.name,
ingredientId = ingredient.ingredient.id,
amount = ingredient.crossRef.amount,
unit = ingredient.ingredient.unit,
price = ingredient.ingredient.price
)
}
)
}
| 3 |
Kotlin
|
2
| 6 |
d794cff96a955346d983eb2953c1a5691d9df13a
| 2,978 |
Recipely
|
Apache License 2.0
|
app/src/main/java/co/tiagoaguiar/course/instagram/search/view/SearchFragment.kt
|
Felipe-Borba
| 751,564,839 | false |
{"Kotlin": 149355}
|
package co.tiagoaguiar.course.instagram.search.view
import android.app.SearchManager
import android.content.Context
import android.view.Menu
import android.view.MenuInflater
import android.view.View
import androidx.appcompat.widget.SearchView
import androidx.recyclerview.widget.LinearLayoutManager
import co.tiagoaguiar.course.instagram.R
import co.tiagoaguiar.course.instagram.common.base.BaseFragment
import co.tiagoaguiar.course.instagram.common.base.DependencyInjector
import co.tiagoaguiar.course.instagram.common.model.User
import co.tiagoaguiar.course.instagram.common.model.UserAuth
import co.tiagoaguiar.course.instagram.databinding.FragmentSearchBinding
import co.tiagoaguiar.course.instagram.search.Search
import co.tiagoaguiar.course.instagram.search.presenter.SearchPresenter
class SearchFragment : BaseFragment<FragmentSearchBinding, Search.Presenter>(
R.layout.fragment_search,
FragmentSearchBinding::bind
), Search.View {
override lateinit var presenter: Search.Presenter
private val searchAdapter by lazy { SearchAdapter(onItemClicked) }
private var searchListener: SearchListener? = null
private val onItemClicked: (String) -> Unit = {
searchListener?.goToProfile(it)
}
override fun onAttach(context: Context) {
super.onAttach(context)
if (context is SearchListener) {
searchListener = context
}
}
override fun setupViews() {
val rv = binding?.searchRv
rv?.layoutManager = LinearLayoutManager(requireContext())
rv?.adapter = searchAdapter
}
override fun setupPresenter() {
presenter = SearchPresenter(this, DependencyInjector.searchRepository())
}
override fun getMenu(): Int = R.menu.menu_search
override fun onCreateOptionsMenu(menu: Menu, inflater: MenuInflater) {
super.onCreateOptionsMenu(menu, inflater)
val searchManager = requireActivity().getSystemService(Context.SEARCH_SERVICE) as SearchManager
val searchView = menu.findItem(R.id.menu_search).actionView as SearchView
searchView.apply {
setSearchableInfo(searchManager.getSearchableInfo(requireActivity().componentName))
setOnQueryTextListener(object : SearchView.OnQueryTextListener {
override fun onQueryTextSubmit(query: String?): Boolean {
return false
}
override fun onQueryTextChange(newText: String?): Boolean {
return if (newText?.isNotEmpty() == true) {
presenter.fetchUsers(newText)
true
} else {
false
}
}
})
}
}
override fun showProgress(enabled: Boolean) {
binding?.searchProgress?.visibility = if (enabled) View.VISIBLE else View.GONE
}
override fun displayFullUsers(users: List<User>) {
binding?.searchTxtEmpty?.visibility = View.GONE
binding?.searchRv?.visibility = View.VISIBLE
searchAdapter.items = users
searchAdapter.notifyDataSetChanged()
}
override fun displayEmptyUsers() {
binding?.searchTxtEmpty?.visibility = View.VISIBLE
binding?.searchRv?.visibility = View.GONE
}
interface SearchListener {
fun goToProfile(uuid: String)
}
}
| 0 |
Kotlin
|
0
| 0 |
58a795ec85a7f530917005cbaeded94d0aebbe76
| 3,375 |
InstagramCopy
|
MIT License
|
loggingsupport/tests/unit/src/com/google/android/libraries/car/loggingsupport/LoggingManagerTest.kt
|
google
| 415,118,653 | false |
{"Kotlin": 865761, "Java": 244253}
|
// Copyright 2021 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
//
// 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.google.android.libraries.car.loggingsupport
import android.content.Context
import androidx.test.core.app.ApplicationProvider
import androidx.test.ext.junit.runners.AndroidJUnit4
import com.google.android.companionprotos.LoggingMessageProto.LoggingMessage
import com.google.android.companionprotos.LoggingMessageProto.LoggingMessage.MessageType
import com.google.android.libraries.car.trustagent.Car
import com.google.android.libraries.car.trustagent.util.LogRecord
import com.google.gson.Gson
import com.nhaarman.mockitokotlin2.any
import com.nhaarman.mockitokotlin2.argumentCaptor
import com.nhaarman.mockitokotlin2.eq
import com.nhaarman.mockitokotlin2.mock
import com.nhaarman.mockitokotlin2.verify
import com.nhaarman.mockitokotlin2.whenever
import java.io.File
import java.util.UUID
import org.junit.Before
import org.junit.Test
import org.junit.runner.RunWith
/** Unit tests for the [LoggingManager] */
@RunWith(AndroidJUnit4::class)
class LoggingManagerTest {
private val testConnectedCar = UUID.randomUUID()
private val mockCar: Car = mock()
private val mockFileUtils: FileUtil = mock()
private val mockListener: LoggingManager.OnLogFilesUpdatedListener = mock()
private val context = ApplicationProvider.getApplicationContext<Context>()
private lateinit var loggingManager: LoggingManager
private val util = FileUtil()
@Before
fun setUp() {
loggingManager = LoggingManager(context)
loggingManager.util = mockFileUtils
loggingManager.onLogFilesUpdatedListener = mockListener
whenever(mockCar.deviceId).thenAnswer { testConnectedCar }
loggingManager.notifyCarConnected(mockCar)
}
@Test
fun onMessageReceived_sendRequest() {
val mockLogRequestMessage = LogMessageUtil
.createRequestMessage(LoggingManager.LOGGING_MESSAGE_VERSION)
loggingManager.onMessageReceived(mockLogRequestMessage, testConnectedCar)
argumentCaptor<ByteArray>().apply {
verify(mockCar).sendMessage(capture(), eq(LoggingManager.FEATURE_ID))
val message = LoggingMessage.parseFrom(lastValue)
assert(message.type == MessageType.LOG)
}
}
@Test
fun onMessageReceived_logMessage() {
val receivedLogs = mockLogMessageReceived(5)
verify(mockFileUtils).writeToFile(eq(receivedLogs), any(), any())
verify(mockListener).onLogFilesUpdated()
}
@Test
fun getLogFiles() {
loggingManager.loadLogFiles()
verify(mockFileUtils).readFiles(any())
}
@Test
fun generateLogFile() {
loggingManager.generateLogFile()
verify(mockListener).onLogFilesUpdated()
}
@Test
fun sendLogRequest() {
loggingManager.sendLogRequest()
argumentCaptor<ByteArray>().apply {
verify(mockCar).sendMessage(capture(), eq(LoggingManager.FEATURE_ID))
val message = LoggingMessage.parseFrom(lastValue)
assert(message.type == MessageType.START_SENDING)
}
}
@Test
fun removeOldLogFiles() {
val logFiles = createRandomLogFiles(LoggingManager.LOG_FILES_MAX_NUM + 1)
whenever(mockFileUtils.readFiles(any())).thenAnswer { logFiles }
val receivedLogs = mockLogMessageReceived(5)
verify(mockFileUtils).writeToFile(eq(receivedLogs), any(), any())
verify(logFiles[0]).delete()
}
private fun mockLogMessageReceived(size: Int): ByteArray {
val mockReceivedLogs = createRandomLogRecords(size)
val mockLogMessage = LogMessageUtil.createMessage(
mockReceivedLogs,
LoggingManager.LOGGING_MESSAGE_VERSION
)
loggingManager.onMessageReceived(mockLogMessage, testConnectedCar)
return mockReceivedLogs
}
private fun createRandomLogFiles(size: Int): List<File> {
val logFiles = mutableListOf<File>()
for (i in 1..size) {
val file: File = mock()
whenever(file.isFile).thenAnswer { true }
whenever(file.lastModified()).thenAnswer { i.toLong() }
logFiles.add(file)
}
return logFiles
}
private fun createRandomLogRecords(size: Int): ByteArray {
val logRecords = mutableListOf<LogRecord>()
var count = size
for (i in 1..count) {
logRecords.add(LogRecord(LogRecord.Level.INFO, "TEST_TAG", "TEST_MESSAGE"))
}
return Gson().toJson(logRecords).toByteArray()
}
}
| 1 |
Kotlin
|
5
| 18 |
912fd5cff1f08577d679bfaff9fc0666b8093367
| 4,773 |
android-auto-companion-android
|
Apache License 2.0
|
app/src/main/kotlin/dev/sanmer/pi/ui/provider/LocalUserPreferences.kt
|
SanmerApps
| 720,492,308 | false |
{"Kotlin": 168116, "Java": 22283}
|
package dev.sanmer.pi.ui.provider
import androidx.compose.runtime.staticCompositionLocalOf
import dev.sanmer.pi.datastore.model.UserPreferences
val LocalUserPreferences = staticCompositionLocalOf { UserPreferences() }
| 0 |
Kotlin
|
8
| 402 |
415159f911bcbce742c048775feb9e460fe0b719
| 219 |
PI
|
MIT License
|
src/main/kotlin/com/zup/Exception/ValorNaoEncontradoException.kt
|
Thalyta-dev
| 382,967,584 | true |
{"Kotlin": 77291, "Smarty": 1792, "Dockerfile": 115}
|
package com.zup.Exception
import java.lang.RuntimeException
class ValorNaoEncontradoException(s: String) : RuntimeException(s) {
}
| 0 |
Kotlin
|
0
| 0 |
c205697d75d1ef7ecc0a84f724e766e3373d1e2e
| 134 |
orange-talents-05-template-pix-keymanager-grpc
|
Apache License 2.0
|
server-core/src/main/kotlin/com/lightningkite/lightningserver/typed/ApiWebsocket.kt
|
lightningkite
| 512,032,499 | false |
{"Kotlin": 2189721, "TypeScript": 38628, "Ruby": 873, "JavaScript": 118}
|
package com.lightningkite.lightningserver.typed
import com.lightningkite.lightningdb.HasId
import com.lightningkite.lightningserver.LSError
import com.lightningkite.lightningserver.auth.AuthOptions
import com.lightningkite.lightningserver.auth.authChecked
import com.lightningkite.lightningserver.auth.authOptions
import com.lightningkite.lightningserver.core.LightningServerDsl
import com.lightningkite.lightningserver.core.ServerPath
import com.lightningkite.lightningserver.exceptions.BadRequestException
import com.lightningkite.lightningserver.http.HttpHeaders
import com.lightningkite.lightningserver.serialization.Serialization
import com.lightningkite.lightningserver.settings.generalSettings
import com.lightningkite.lightningserver.websocket.WebSocketIdentifier
import com.lightningkite.lightningserver.websocket.WebSockets
import com.lightningkite.lightningserver.websocket.test
import kotlinx.coroutines.cancelAndJoin
import kotlinx.coroutines.channels.Channel
import kotlinx.coroutines.channels.ReceiveChannel
import kotlinx.coroutines.coroutineScope
import kotlinx.coroutines.launch
import kotlinx.serialization.KSerializer
import kotlinx.serialization.serializer
import java.net.URLDecoder
data class ApiWebsocket<USER: HasId<*>?, PATH: TypedServerPath, INPUT, OUTPUT>(
override val path: PATH,
override val authOptions: AuthOptions<USER>,
val inputType: KSerializer<INPUT>,
val outputType: KSerializer<OUTPUT>,
override val summary: String,
override val description: String = summary,
val errorCases: List<LSError>,
override val belongsToInterface: Documentable.InterfaceInfo? = null,
val connect: suspend AuthPathPartsAndConnect<USER, PATH, OUTPUT>.() -> Unit,
val message: suspend TypedWebSocketSender<OUTPUT>.(INPUT) -> Unit,
val disconnect: suspend TypedWebSocketSender<OUTPUT>.() -> Unit,
) : Documentable, WebSockets.Handler {
private val wildcards = path.path.segments.filterIsInstance<ServerPath.Segment.Wildcard>()
override suspend fun connect(event: WebSockets.ConnectEvent) {
val auth = event.authChecked<USER>(authOptions)
val receiver = AuthPathPartsAndConnect<USER, PATH, OUTPUT>(
authOrNull = auth,
parts = path.serializers.mapIndexed { idx, ser ->
val name = wildcards.get(idx).name
val str = event.parts[name] ?: throw BadRequestException("Route segment $name not found")
str.parseUrlPartOrBadRequest(path.serializers[idx])
}.toTypedArray(),
event = event,
outputSerializer = outputType,
rawRequest = event
)
this.connect.invoke(receiver)
}
override suspend fun message(event: WebSockets.MessageEvent) {
val parsed = event.content.let { Serialization.json.decodeFromString(inputType, it) }
this.message.invoke(TypedWebSocketSender(event.id, outputType, event.cache), parsed)
}
override suspend fun disconnect(event: WebSockets.DisconnectEvent) {
this.disconnect.invoke(TypedWebSocketSender(event.id, outputType, event.cache))
}
suspend fun send(id: WebSocketIdentifier, content: OUTPUT) =
id.send(Serialization.json.encodeToString(outputType, content))
}
private fun <T> String.parseUrlPartOrBadRequest(serializer: KSerializer<T>): T = try {
Serialization.fromString(URLDecoder.decode(this, Charsets.UTF_8), serializer)
} catch (e: Exception) {
throw BadRequestException("Path part ${this} could not be parsed as a ${serializer.descriptor.serialName}.")
}
@LightningServerDsl
inline fun <reified USER: HasId<*>?, PATH: TypedServerPath, reified INPUT, reified OUTPUT> PATH.apiWebsocket(
summary: String,
description: String = summary,
errorCases: List<LSError>,
belongsToInterface: Documentable.InterfaceInfo? = null,
noinline connect: suspend AuthPathPartsAndConnect<USER, PATH, OUTPUT>.() -> Unit,
noinline message: suspend TypedWebSocketSender<OUTPUT>.(INPUT) -> Unit,
noinline disconnect: suspend TypedWebSocketSender<OUTPUT>.() -> Unit,
): ApiWebsocket<USER, PATH, INPUT, OUTPUT> = apiWebsocket(
authOptions = authOptions<USER>(),
inputType = Serialization.module.serializer(),
outputType = Serialization.module.serializer(),
summary = summary,
description = description,
errorCases = errorCases,
belongsToInterface = belongsToInterface,
connect = connect,
message = message,
disconnect = disconnect,
)
@LightningServerDsl
fun <USER: HasId<*>?, PATH: TypedServerPath, INPUT, OUTPUT> PATH.apiWebsocket(
authOptions: AuthOptions<USER>,
inputType: KSerializer<INPUT>,
outputType: KSerializer<OUTPUT>,
summary: String,
description: String = summary,
errorCases: List<LSError>,
belongsToInterface: Documentable.InterfaceInfo? = null,
connect: suspend AuthPathPartsAndConnect<USER, PATH, OUTPUT>.() -> Unit,
message: suspend TypedWebSocketSender<OUTPUT>.(INPUT) -> Unit,
disconnect: suspend TypedWebSocketSender<OUTPUT>.() -> Unit,
): ApiWebsocket<USER, PATH, INPUT, OUTPUT> {
val ws = ApiWebsocket(
path = this,
authOptions = authOptions,
inputType = inputType,
outputType = outputType,
summary = summary,
description = description,
errorCases = errorCases,
belongsToInterface = belongsToInterface,
connect = connect,
message = message,
disconnect = disconnect,
)
WebSockets.handlers[path] = ws
return ws
}
@LightningServerDsl
inline fun <reified USER: HasId<*>?, reified INPUT, reified OUTPUT> ServerPath.apiWebsocket(
summary: String,
description: String = summary,
errorCases: List<LSError>,
belongsToInterface: Documentable.InterfaceInfo? = null,
noinline connect: suspend AuthPathPartsAndConnect<USER, TypedServerPath0, OUTPUT>.() -> Unit,
noinline message: suspend TypedWebSocketSender<OUTPUT>.(INPUT) -> Unit,
noinline disconnect: suspend TypedWebSocketSender<OUTPUT>.() -> Unit,
): ApiWebsocket<USER, TypedServerPath0, INPUT, OUTPUT> = apiWebsocket(
authOptions = authOptions<USER>(),
inputType = Serialization.module.serializer(),
outputType = Serialization.module.serializer(),
summary = summary,
description = description,
errorCases = errorCases,
belongsToInterface = belongsToInterface,
connect = connect,
message = message,
disconnect = disconnect,
)
@LightningServerDsl
fun <USER: HasId<*>?, INPUT, OUTPUT> ServerPath.apiWebsocket(
authOptions: AuthOptions<USER>,
inputType: KSerializer<INPUT>,
outputType: KSerializer<OUTPUT>,
summary: String,
description: String = summary,
errorCases: List<LSError>,
belongsToInterface: Documentable.InterfaceInfo? = null,
connect: suspend AuthPathPartsAndConnect<USER, TypedServerPath0, OUTPUT>.() -> Unit,
message: suspend TypedWebSocketSender<OUTPUT>.(INPUT) -> Unit,
disconnect: suspend TypedWebSocketSender<OUTPUT>.() -> Unit,
): ApiWebsocket<USER, TypedServerPath0, INPUT, OUTPUT> {
val ws = ApiWebsocket(
path = TypedServerPath0(this),
authOptions = authOptions,
inputType = inputType,
outputType = outputType,
summary = summary,
description = description,
errorCases = errorCases,
belongsToInterface = belongsToInterface,
connect = connect,
message = message,
disconnect = disconnect,
)
WebSockets.handlers[this] = ws
return ws
}
data class TypedVirtualSocket<INPUT, OUTPUT>(val incoming: ReceiveChannel<OUTPUT>, val send: suspend (INPUT) -> Unit)
suspend fun <USER: HasId<*>?, INPUT, OUTPUT> ApiWebsocket<USER, TypedServerPath0, INPUT, OUTPUT>.test(
parts: Map<String, String> = mapOf(),
wildcard: String? = null,
queryParameters: List<Pair<String, String>> = listOf(),
headers: HttpHeaders = HttpHeaders.EMPTY,
domain: String = generalSettings().publicUrl.substringAfter("://").substringBefore("/"),
protocol: String = generalSettings().publicUrl.substringBefore("://"),
sourceIp: String = "0.0.0.0",
test: suspend TypedVirtualSocket<INPUT, OUTPUT>.() -> Unit
) {
this.path.path.test(
parts = parts,
wildcard = wildcard,
queryParameters = queryParameters,
headers = headers,
domain = domain,
protocol = protocol,
sourceIp = sourceIp,
test = {
val channel = Channel<OUTPUT>(20)
coroutineScope {
val job = launch {
for (it in incoming) {
channel.send(Serialization.json.decodeFromString(outputType, it))
}
}
val job2 = launch {
test(TypedVirtualSocket<INPUT, OUTPUT>(
incoming = channel,
send = { send(Serialization.json.encodeToString(inputType, it)) }
))
}
job2.join()
job.cancelAndJoin()
}
},
)
}
| 2 |
Kotlin
|
1
| 5 |
f404cc57cbdbe2a90b4e59d4ecd5ad22e008a730
| 9,092 |
lightning-server
|
MIT License
|
app/src/main/java/com/pilot51/voicenotify/AppWidget.kt
|
pilot51
| 6,212,669 | false |
{"Kotlin": 151162}
|
/*
* Copyright 2011-2023 <NAME>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.pilot51.voicenotify
import android.content.Context
import android.widget.Toast
import androidx.compose.runtime.Composable
import androidx.compose.runtime.collectAsState
import androidx.compose.runtime.getValue
import androidx.compose.ui.graphics.Color
import androidx.glance.*
import androidx.glance.action.actionParametersOf
import androidx.glance.action.clickable
import androidx.glance.appwidget.GlanceAppWidget
import androidx.glance.appwidget.GlanceAppWidgetReceiver
import androidx.glance.appwidget.action.actionStartActivity
import androidx.glance.appwidget.provideContent
import androidx.glance.layout.fillMaxSize
import androidx.glance.unit.ColorProvider
class AppWidget : GlanceAppWidget() {
override suspend fun provideGlance(context: Context, id: GlanceId) {
provideContent {
val isRunning by Service.isRunning.collectAsState()
val isSuspended by Service.isSuspended.collectAsState()
Widget(context, isRunning, isSuspended)
}
}
@Composable
private fun Widget(
context: Context,
isSvcRunning: Boolean,
isSvcSuspended: Boolean
) {
val color = if (!isSvcRunning) Color(0xFFCC0000)
else if (isSvcSuspended) Color(0xFFCC8800)
else Color(0xFF00CC00)
Image(
provider = ImageProvider(R.drawable.widget),
contentDescription = null,
modifier = GlanceModifier
.fillMaxSize()
.clickable {
if (isSvcRunning) {
Toast.makeText(
context,
if (Service.toggleSuspend()) {
R.string.service_suspended
} else R.string.service_running,
Toast.LENGTH_SHORT
).show()
} else {
actionStartActivity(
Common.notificationListenerSettingsIntent,
actionParametersOf()
)
}
},
colorFilter = ColorFilter.tint(ColorProvider(color))
)
}
}
class AppWidgetReceiver : GlanceAppWidgetReceiver() {
override val glanceAppWidget: GlanceAppWidget = AppWidget()
}
| 45 |
Kotlin
|
56
| 158 |
af7d553c22dcfed12b05521265fd7df4383b27d5
| 2,491 |
voicenotify
|
Apache License 2.0
|
src/day14/Code.kt
|
ldickmanns
| 572,675,185 | false |
{"Kotlin": 48227}
|
package day14
import day09.Coordinates
import readInput
// x -> distance to right
// y -> distance down
// Sand falls (at each step)
// - down, if not possible
// - down-left, if not possible
// - down-right, if not possible
// - comes to a rest
typealias RockStroke = List<Coordinates>
val startingPoint = Coordinates(x = 500, y = 0)
operator fun Array<BooleanArray>.get(coordinates: Coordinates) = this[coordinates.y][coordinates.x]
operator fun Array<BooleanArray>.set(coordinates: Coordinates, boolean: Boolean) {
this[coordinates.y][coordinates.x] = boolean
}
val Coordinates.down: Coordinates
get() = copy(y = y + 1)
val Coordinates.downLeft: Coordinates
get() = copy(x = x - 1, y = y + 1)
val Coordinates.downRight: Coordinates
get() = copy(x = x + 1, y = y + 1)
private infix fun Coordinates.inside(grid: Array<BooleanArray>) =
x >= 0 && x < grid.first().size && y >= 0 && y < grid.size
private infix fun Coordinates.outside(grid: Array<BooleanArray>) = !inside(grid)
fun main() {
val input = readInput("day14/input")
// val input = readInput("day14/input_test")
// println(part1(input))
println(part2(input))
}
fun part1(input: List<String>): Int {
val rockStrokes = parseInput(input)
val boundingBox = getBoundingBox(rockStrokes)
val occupationGrid = getOccupationGrid(rockStrokes, boundingBox)
return computeRestingUnits(boundingBox, occupationGrid)
}
private fun parseInput(input: List<String>): List<RockStroke> = input.map { line ->
val coordinatesStrings = line.split(" -> ")
coordinatesStrings.map { coordinatesString ->
val coordinates = coordinatesString.split(",").map { it.toInt() }
Coordinates(coordinates.first(), coordinates.last())
}
}
private fun getBoundingBox(
rockStrokes: List<RockStroke>,
maxYOffset: Int = 0,
xPadding: Int = 0,
): Pair<Coordinates, Coordinates> {
var minCoordinates = startingPoint
var maxCoordinates = startingPoint
rockStrokes.forEach { rockStroke: RockStroke ->
rockStroke.forEach { coordinates: Coordinates ->
if (coordinates.x > maxCoordinates.x) maxCoordinates = maxCoordinates.copy(x = coordinates.x)
if (coordinates.x < minCoordinates.x) minCoordinates = minCoordinates.copy(x = coordinates.x)
if (coordinates.y > maxCoordinates.y) maxCoordinates = maxCoordinates.copy(y = coordinates.y)
if (coordinates.y < minCoordinates.y) minCoordinates = minCoordinates.copy(y = coordinates.y)
}
}
minCoordinates = minCoordinates.copy(x = minCoordinates.x - xPadding)
maxCoordinates = maxCoordinates.copy(x = maxCoordinates.x + xPadding, y = maxCoordinates.y + maxYOffset)
return Pair(minCoordinates, maxCoordinates)
}
private fun getOccupationGrid(
rockStrokes: List<RockStroke>,
boundingBox: Pair<Coordinates, Coordinates>
): Array<BooleanArray> {
val (minCoordinates, maxCoordinates) = boundingBox
val deltaCoordinates = maxCoordinates - minCoordinates
val occupationGrid = Array(deltaCoordinates.y + 1) { BooleanArray(deltaCoordinates.x + 1) }
rockStrokes.forEach { rockStroke: RockStroke ->
rockStroke.windowed(2) {
val lineStart = it.first()
val lineEnd = it.last()
val xRange = if (lineStart.x <= lineEnd.x) lineStart.x..lineEnd.x else lineEnd.x..lineStart.x
val yRange = if (lineStart.y <= lineEnd.y) lineStart.y..lineEnd.y else lineEnd.y..lineStart.y
xRange.forEach { x ->
yRange.forEach { y ->
val normalizedX = x - minCoordinates.x
val normalizedY = y - minCoordinates.y
occupationGrid[normalizedY][normalizedX] = true
}
}
}
}
return occupationGrid
}
private fun computeRestingUnits(
boundingBox: Pair<Coordinates, Coordinates>,
occupationGrid: Array<BooleanArray>
): Int {
var sandPosition = startingPoint - boundingBox.first
var restingUnits = 0
while (true) {
when {
sandPosition.down outside occupationGrid -> break
!occupationGrid[sandPosition.down] -> sandPosition = sandPosition.down
sandPosition.downLeft outside occupationGrid -> break
!occupationGrid[sandPosition.downLeft] -> sandPosition = sandPosition.downLeft
sandPosition.downRight outside occupationGrid -> break
!occupationGrid[sandPosition.downRight] -> sandPosition = sandPosition.downRight
else -> {
if (occupationGrid[sandPosition]) break
occupationGrid[sandPosition] = true
++restingUnits
sandPosition = startingPoint - boundingBox.first
}
}
}
occupationGrid.forEach { row ->
row.forEach { print(if (it) '#' else '.') }
println()
}
println("-".repeat(25))
return restingUnits
}
fun part2(input: List<String>): Int {
val rockStrokes = parseInput(input)
val boundingBox = getBoundingBox(rockStrokes, maxYOffset = 2, xPadding = 200)
val occupationGrid = getOccupationGrid(rockStrokes, boundingBox)
occupationGrid.last().indices.forEach {
occupationGrid.last()[it] = true
}
return computeRestingUnits(boundingBox, occupationGrid)
}
| 0 |
Kotlin
|
0
| 0 |
2654ca36ee6e5442a4235868db8174a2b0ac2523
| 5,359 |
aoc-kotlin-2022
|
Apache License 2.0
|
android/src/main/java/sdk/butterfly_sdk/ActivityProvider.kt
|
avielBS
| 331,069,441 | false | null |
package sdk.butterfly_sdk
import android.app.Activity
import android.app.Application
import android.app.Application.ActivityLifecycleCallbacks
import android.content.ContentProvider
import android.content.ContentValues
import android.database.Cursor
import android.net.Uri
import android.os.Bundle
import java.lang.ref.WeakReference
class ActivityProvider : ContentProvider(), ActivityLifecycleCallbacks {
companion object {
private var topActivity: WeakReference<Activity>? = null
val presentedActivity: Activity?
get() = topActivity?.get()
}
override fun onCreate(): Boolean {
val applicationContext = context?.applicationContext
(applicationContext as? Application)?.registerActivityLifecycleCallbacks(this)
return false
}
override fun onActivityStarted(activity: Activity) {}
override fun onActivityResumed(activity: Activity) {
topActivity = WeakReference<Activity>(activity)
}
override fun onActivityPaused(activity: Activity) {}
override fun onActivityStopped(activity: Activity) {
topActivity = null
}
override fun onActivitySaveInstanceState(activity: Activity, bundle: Bundle) {}
override fun onActivityDestroyed(activity: Activity) {}
//ContentProvider
override fun query(uri: Uri, strings: Array<String>?, s: String?, strings1: Array<String>?, s1: String?): Cursor? {
return null
}
override fun getType(uri: Uri): String? {
return null
}
override fun insert(uri: Uri, contentValues: ContentValues?): Uri? {
return null
}
override fun delete(uri: Uri, s: String?, strings: Array<String>?): Int {
return 0
}
override fun update(uri: Uri, contentValues: ContentValues?, s: String?, strings: Array<String>?): Int {
return 0
}
//Application.ActivityLifecycleCallbacks
override fun onActivityCreated(activity: Activity, bundle: Bundle?) {}
}
| 1 | null |
1
| 1 |
f31786e1b1eb51d4ecdca6dce10de7b6bbd2d7f5
| 1,969 |
ButterflyHostSDk-Flutter
|
MIT License
|
api/src/main/kotlin/com/annotation/flea/adapter/in/ProductController.kt
|
Uhjinkim
| 850,430,659 | false |
{"Kotlin": 182951}
|
package com.annotation.flea.adapter.`in`
import com.annotation.flea.application.service.ProductService
import com.annotation.flea.application.service.UserService
import com.annotation.flea.domain.entity.Category
import com.annotation.flea.mapper.`in`.CategoryDtoMapper
import com.annotation.flea.mapper.`in`.ProductDtoMapper
import com.annotation.flea.presentation.dto.CustomUserDetails
import com.annotation.flea.presentation.dto.ProductDTO
import com.fasterxml.jackson.module.kotlin.jacksonObjectMapper
import org.springframework.security.core.annotation.AuthenticationPrincipal
import org.springframework.web.bind.annotation.*
@RestController
@RequestMapping("/product")
class ProductController(
private val productService: ProductService,
private val userService: UserService,
private val productDtoMapper: ProductDtoMapper,
private val categoryDtoMapper: CategoryDtoMapper,
) {
val mapper = jacksonObjectMapper()
@GetMapping("/list")
fun getProducts(@RequestParam(required = false, defaultValue = "0", value = "page") page: Int,
@RequestParam(required = false, defaultValue = "createdAt", value = "criteria") criteria: String,
@RequestParam(required = false, defaultValue = "", value = "category") category: Category,
) : String {
val products = productService.getProducts(page, criteria, category)
products?.forEach {
productDtoMapper.mapToProductDto(it)
}
return mapper.writeValueAsString(products)
}
@GetMapping("/new")
fun getProductOptions() : String {
val categories = productService.getCategoryList()
val response = categories.map {
categoryDtoMapper.mapToDto(it)
}
return mapper.writeValueAsString(response)
}
@PostMapping("/create")
fun sellProduct(productDto: ProductDTO, @RequestHeader("Authorization") token: String) : String {
val user = userService.loadUserByToken(token) ?: return "user not found"
val product = productDtoMapper.mapToDomain(productDto = productDto, user = user)
productService.sellProduct(product)
return "transaction submitted"
}
@PostMapping("/edit")
fun editProduct(productDto: ProductDTO, @AuthenticationPrincipal customUserDetails: CustomUserDetails) : String {
val user = userService.loadUserByUsername(customUserDetails.username) ?: return "user not found"
val product = productDtoMapper.mapToDomain(productDto = productDto, user = user)
productService.editProduct(product)
return "product edited"
}
}
| 0 |
Kotlin
|
0
| 1 |
3ade2454d5975b89d3a5ac00b36941013e0acc7f
| 2,630 |
Flea-Market
|
MIT License
|
app/src/main/java/com/example/pianostudio/ui/navigation/Navigation.kt
|
coral134
| 695,267,140 | false |
{"Kotlin": 122218}
|
package com.example.pianostudio.ui.navigation
import androidx.activity.compose.BackHandler
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import com.example.pianostudio.ui.screens.practice.StudioPracticingScreen
import com.example.pianostudio.ui.screens.record.StudioPlaybackScreen
import com.example.pianostudio.ui.screens.record.StudioRecordingScreen
// vm seems to be causing pages to rebuild often
@Composable
fun Navigation(modifier: Modifier) {
PageNavigationRoot(
startingRoute = "MainPages/Home",
transitionSpec = fullScreenTransition
) {
val nav = rememberLocalPageNavigator()
BackHandler { nav.navigateTo("MainPages/Home") }
PageSwitcher(modifier = modifier) {
page("MainPages") {
MainPages(modifier = Modifier.fillMaxSize())
}
page("StudioPractice") {
StudioPracticingScreen(modifier = Modifier.fillMaxSize())
}
page("StudioRecord") {
StudioRecordingScreen(modifier = Modifier.fillMaxSize())
}
page("StudioPlayback") {
StudioPlaybackScreen(modifier = Modifier.fillMaxSize())
}
}
}
}
| 0 |
Kotlin
|
0
| 1 |
0d2460908341c8eec0dd23d7248d9c5605205174
| 1,303 |
Piano_Studio
|
MIT License
|
app/src/main/java/zechs/zplex/ui/shared_adapters/banner/BannerViewHolder.kt
|
itszechs
| 381,082,348 | false | null |
package zechs.zplex.ui.shared_adapters.banner
import androidx.recyclerview.widget.RecyclerView
import com.bumptech.glide.request.RequestOptions
import jp.wasabeef.glide.transformations.BlurTransformation
import zechs.zplex.R
import zechs.zplex.data.model.BackdropSize
import zechs.zplex.data.model.tmdb.entities.Media
import zechs.zplex.databinding.ItemWideBannerBinding
import zechs.zplex.utils.Constants.TMDB_IMAGE_PREFIX
import zechs.zplex.utils.GlideApp
class BannerViewHolder(
private val itemBinding: ItemWideBannerBinding,
val bannerAdapter: BannerAdapter
) : RecyclerView.ViewHolder(itemBinding.root) {
fun bind(media: Media) {
val mediaBannerUrl = if (media.backdrop_path == null) {
R.drawable.no_thumb
} else {
"${TMDB_IMAGE_PREFIX}/${BackdropSize.w780}${media.backdrop_path}"
}
itemBinding.apply {
tvTitle.text = media.title
val rating = media.vote_average?.div(2).toString()
val ratingText = "$rating/5"
rbRating.rating = rating.toFloat()
tvRatingText.text = ratingText
GlideApp.with(ivBanner)
.load(mediaBannerUrl)
.placeholder(R.drawable.no_thumb)
.apply(RequestOptions.bitmapTransform(BlurTransformation(100)))
.into(ivBanner)
GlideApp.with(ivMainBanner)
.load(mediaBannerUrl)
.placeholder(R.drawable.no_thumb)
.into(ivMainBanner)
root.setOnClickListener {
bannerAdapter.bannerOnClick.invoke(media)
}
}
}
}
| 0 |
Kotlin
|
0
| 8 |
95cce5c6a0dd32b7e7a5940e87730148706a25ab
| 1,644 |
ZPlex
|
MIT License
|
app/src/main/java/com/vshyrochuk/topcharts/screens/chartpreview/ChartPreviewScreen.kt
|
Mc231
| 524,970,692 | false | null |
package com.vshyrochuk.topcharts.screens.chartpreview
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.collectAsState
import androidx.compose.runtime.getValue
import androidx.compose.ui.platform.LocalUriHandler
import androidx.compose.ui.platform.UriHandler
import androidx.hilt.navigation.compose.hiltViewModel
@Composable
fun ChartPreviewScreen(
viewModel: ChartPreviewViewModel = hiltViewModel(),
uriHandler: UriHandler = LocalUriHandler.current,
dateFormatter: ReleaseDateFormatter = ReleaseDateFormatter,
entityId: String?,
onBackClicked: () -> Unit
) {
val state by viewModel.state.collectAsState(initial = ChartPreviewUIState.Initial)
LaunchedEffect(state == ChartPreviewUIState.Initial) {
viewModel.load(entityId)
}
ChartPreviewContainer(
state = state,
viewModel = viewModel,
entityId = entityId,
dateFormatter = dateFormatter,
uriHandler = uriHandler,
onBackClicked = onBackClicked
)
}
| 0 |
Kotlin
|
0
| 0 |
8b9f6ae00d38e69b81cc466adb14bb7d2b48c20f
| 1,068 |
Top-Charts
|
MIT License
|
app/src/main/java/com/recipeme/utils/IngredientsData.kt
|
SteveMontelongo
| 693,790,986 | false |
{"Kotlin": 92536}
|
package com.recipeme.utils
object IngredientsData {
var map = HashMap<Int, String>()
}
| 0 |
Kotlin
|
0
| 0 |
8d95d4bdf3a0f397df466b74495b3a14b999f1c5
| 92 |
ProjectRecipeMe
|
Apache License 2.0
|
src/main/kotlin/de/rwth_erstis/discordbot_jvm/core/Bot.kt
|
RWTHInformatikErstis2021
| 404,131,986 | false |
{"Java": 19928, "Kotlin": 6150, "Dockerfile": 286, "Shell": 17}
|
package de.rwth_erstis.discordbot_jvm.core
import de.rwth_erstis.discordbot_jvm.CommandHandler
import net.dv8tion.jda.api.JDA
interface Bot {
val jda: JDA
val cmdHandler: CommandHandler
}
| 1 | null |
1
| 1 |
4001de463b9fe621c3d08da93cb8f5143cd6d628
| 199 |
discordbot-jvm
|
MIT License
|
feature/tasks/db/src/main/kotlin/com/github/ilikeyourhat/lsaa/feature/tasks/db/TasksDao.kt
|
ILikeYourHat
| 385,717,121 | false | null |
package pl.softwarealchemy.lsaa.feature.tasks.db
import androidx.room.Dao
import androidx.room.Insert
import androidx.room.Query
@Dao
public interface TasksDao {
@Query("SELECT * FROM task")
public suspend fun getAll(): List<Task>
@Insert
public suspend fun insertAll(vararg tasks: Task)
}
| 12 |
Kotlin
|
2
| 4 |
3c2073e1eb9f10285c84382caf5caad455f2bb9a
| 310 |
Large-Scale-Android-App
|
Apache License 2.0
|
nibel-runtime/src/main/kotlin/nibel/runtime/NoArgs.kt
|
open-turo
| 667,584,375 | false |
{"Kotlin": 102457}
|
package nibel.runtime
import android.os.Parcelable
import nibel.annotations.LegacyEntry
import nibel.annotations.UiEntry
import kotlinx.parcelize.Parcelize
/**
* A special type of args that is treated specially by Nibel's annotation processor and marks a
* screen with no arguments.
*/
@Parcelize
object NoArgs : Parcelable
| 1 |
Kotlin
|
1
| 79 |
e66f29f9030fd6818d9cd2c15a78fc62c0885a23
| 329 |
nibel
|
MIT License
|
integration-testing/src/coreAgentTest/kotlin/CoreAgentTest.kt
|
Kotlin
| 61,722,736 | false | null |
import org.junit.*
import kotlinx.coroutines.*
import kotlinx.coroutines.debug.internal.*
import org.junit.Test
import java.io.*
class CoreAgentTest {
@Test
fun testAgentDumpsCoroutines() = runBlocking {
val baos = ByteArrayOutputStream()
@Suppress("INVISIBLE_MEMBER", "INVISIBLE_REFERENCE")
DebugProbesImpl.dumpCoroutines(PrintStream(baos))
// if the agent works, then dumps should contain something,
// at least the fact that this test is running.
Assert.assertTrue(baos.toString().contains("testAgentDumpsCoroutines"))
}
}
| 295 | null |
1850
| 13,033 |
6c6df2b850382887462eeaf51f21f58bd982491d
| 589 |
kotlinx.coroutines
|
Apache License 2.0
|
Week9/app/src/main/java/com/em4n0101/mytvshows/viewmodel/usershows/UserFavoriteShowsViewModelFactory.kt
|
em4n0101
| 268,436,903 | false | null |
package com.em4n0101.mytvshows.viewmodel.usershows
import androidx.lifecycle.ViewModel
import androidx.lifecycle.ViewModelProvider
import com.em4n0101.mytvshows.model.repositories.ShowsRepository
class UserFavoriteShowsViewModelFactory(private val repository: ShowsRepository):
ViewModelProvider.Factory {
override fun <T : ViewModel?> create(modelClass: Class<T>): T {
return modelClass.getConstructor(ShowsRepository::class.java).newInstance(repository)
}
}
| 0 |
Kotlin
|
0
| 1 |
4f1ebb9d68091ef741ac69f2f46e16f512401de2
| 481 |
AndroidBootcampSummer2020
|
Apache License 2.0
|
kandy-lets-plot/src/main/kotlin/org/jetbrains/kotlinx/kandy/letsplot/layers/stat/bins.kt
|
Kotlin
| 502,039,936 | false | null |
/*
* Copyright 2020-2023 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license.
*/
package org.jetbrains.kotlinx.kandy.letsplot.layers.stat
/*
import org.jetbrains.kotlinx.kandy.dsl.contexts.LayerContext
import org.jetbrains.kotlinx.kandy.dsl.column.invoke
import org.jetbrains.kotlinx.kandy.letsplot.BinWidth2DAes
import org.jetbrains.kotlinx.kandy.letsplot.BinWidthAes
import org.jetbrains.kotlinx.kandy.letsplot.Bins2DAes
import org.jetbrains.kotlinx.kandy.letsplot.BinsAes
<<<<<<< HEAD
interface Bins {
data class ByNumber internal constructor(val number: Int) : Bins
data class ByWidth internal constructor(val width: Double) : Bins
=======
public interface Bins {
public data class ByNumber internal constructor(val number: Int) : Bins
public data class ByWidth internal constructor(val width: Double) : Bins
>>>>>>> main
public companion object {
public fun byNumber(number: Int): ByNumber = ByNumber(number)
public fun byWidth(width: Double): ByWidth = ByWidth(width)
}
}
<<<<<<< HEAD
abstract class WithBinsContext(bins: Bins?): LayerContext(parent) {
=======
public abstract class WithBinsContext(bins: Bins?) : LayerContext() {
>>>>>>> main
private val bins get() = BinsAes(this)
private val binWidth get() = BinWidthAes(this)
init {
bins?.let {
countBins(it)
}
}
@PublishedApi
internal fun countBins(bins: Bins) {
when (bins) {
is Bins.ByNumber -> bins(bins.number)
is Bins.ByWidth -> binWidth(bins.width)
}
}
}
public interface Bins2D {
public data class ByNumber internal constructor(val numberX: Int, val numberY: Int) : Bins2D
public data class ByWidth internal constructor(val widthX: Double, val widthY: Double) : Bins2D
public companion object {
public fun byNumber(numberX: Int, numberY: Int): ByNumber = ByNumber(numberX, numberY)
public fun byWidth(widthX: Double, widthY: Double): ByWidth = ByWidth(widthX, widthY)
}
}
<<<<<<< HEAD
abstract class WithBins2DContext(bins: Bins2D?): LayerContext(parent) {
=======
public abstract class WithBins2DContext(bins: Bins2D?) : LayerContext() {
>>>>>>> main
private val bins get() = Bins2DAes(this)
private val binWidth get() = BinWidth2DAes(this)
init {
bins?.let {
countBins(it)
}
}
@PublishedApi
internal fun countBins(bins: Bins2D) {
when (bins) {
is Bins2D.ByNumber -> bins(bins.numberX to bins.numberY)
is Bins2D.ByWidth -> binWidth(bins.widthX to bins.widthY)
}
}
}
*/
| 79 |
Kotlin
|
0
| 98 |
fd613edc4dd37aac0d0ecdb4245a770e09617fc7
| 2,642 |
kandy
|
Apache License 2.0
|
mps-sync-plugin-lib/src/main/kotlin/org/modelix/mps/sync/mps/factories/SolutionProducer.kt
|
modelix
| 716,210,628 | false |
{"Kotlin": 1234570, "Shell": 1104, "JavaScript": 497}
|
/*
* Copyright (c) 2023.
*
* 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.modelix.mps.sync.mps.factories
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.util.io.systemIndependentPath
import com.intellij.openapi.vfs.VirtualFileManager
import jetbrains.mps.ide.MPSCoreComponents
import jetbrains.mps.persistence.DefaultModelRoot
import jetbrains.mps.project.MPSExtentions
import jetbrains.mps.project.ModuleId
import jetbrains.mps.project.Solution
import jetbrains.mps.project.structure.modules.SolutionDescriptor
import jetbrains.mps.project.structure.modules.SolutionKind
import jetbrains.mps.smodel.GeneralModuleFactory
import jetbrains.mps.vfs.IFile
import jetbrains.mps.vfs.VFSManager
import org.modelix.kotlin.utils.UnstableModelixFeature
import org.modelix.mps.sync.mps.ActiveMpsProjectInjector
import java.io.File
// TODO hacky solution. A nicer one could be: https://github.com/JetBrains/MPS/blob/master/workbench/mps-platform/jetbrains.mps.ide.platform/source_gen/jetbrains/mps/project/modules/SolutionProducer.java
@UnstableModelixFeature(reason = "The new modelix MPS plugin is under construction", intendedFinalization = "2024.1")
class SolutionProducer {
private val project
get() = ActiveMpsProjectInjector.activeMpsProject!!
fun createOrGetModule(name: String, moduleId: ModuleId): Solution {
val exportPath = project.projectFile.systemIndependentPath
val coreComponents = ApplicationManager.getApplication().getComponent(
MPSCoreComponents::class.java,
)
val vfsManager = coreComponents.platform.findComponent(
VFSManager::class.java,
)
val fileSystem = vfsManager!!.getFileSystem(VFSManager.FILE_FS)
val outputFolder: IFile = fileSystem.getFile(exportPath)
val solutionFile = outputFolder.findChild(name).findChild("solution" + MPSExtentions.DOT_SOLUTION)
val solutionDir = outputFolder.findChild(name)
VirtualFileManager.getInstance().syncRefresh()
val modelsDirVirtual = solutionDir.findChild("models")
ensureDirDeletionAndRecreation(modelsDirVirtual)
val descriptor = SolutionDescriptor()
descriptor.namespace = name
descriptor.id = moduleId
descriptor.modelRootDescriptors.add(
DefaultModelRoot.createDescriptor(
solutionFile.parent!!,
solutionFile.parent!!
.findChild(Solution.SOLUTION_MODELS),
),
)
descriptor.kind = SolutionKind.PLUGIN_OTHER
val solution = GeneralModuleFactory().instantiate(descriptor, solutionFile) as Solution
project.addModule(solution)
if (solution.repository == null) {
// this might be a silly workaround...
solution.attach(project.repository)
}
checkNotNull(solution.repository) { "The solution should be in a repo, so also the model will be in a repo and syncReference will not crash" }
return solution
}
private fun ensureDirDeletionAndRecreation(virtualDir: IFile) {
ensureDeletion(virtualDir)
virtualDir.mkdirs()
}
/**
* We experienced issues with physical and virtual files being out of sync.
* This method ensure that files are deleted, recursively both on the virtual filesystem and the physical filesystem.
*/
private fun ensureDeletion(virtualFile: IFile) {
if (virtualFile.isDirectory) {
virtualFile.children?.forEach { child ->
ensureDeletion(child)
}
} else {
if (virtualFile.exists()) {
virtualFile.delete()
}
val physicalFile = File(virtualFile.path)
physicalFile.delete()
}
}
}
| 5 |
Kotlin
|
0
| 0 |
f5cb5c4a6f201a8060c6798f0b03703312172b36
| 4,332 |
modelix.mps-plugins
|
Apache License 2.0
|
app/src/main/java/com/example/bankingappui/data/Finance.kt
|
simbastart001
| 812,921,532 | false | null |
package com.example.bankappui.data
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.vector.ImageVector
data class Finance(
val icon: ImageVector,
val name: String,
val background: Color
)
| 0 | null |
0
| 1 |
96d93d7362656680db61603d15c843947066cb4c
| 232 |
BankingUI-with-Compose
|
MIT License
|
foundation/src/main/java/com/zs/foundation/Player.kt
|
iZakirSheikh
| 828,405,870 | false |
{"Kotlin": 480648}
|
package com.zs.foundation
import android.annotation.SuppressLint
import android.net.Uri
import android.view.ViewGroup
import android.widget.FrameLayout
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.toArgb
import androidx.compose.ui.platform.LocalDensity
import androidx.compose.ui.unit.dp
import androidx.compose.ui.viewinterop.AndroidView
import androidx.media3.common.MediaItem
import androidx.media3.exoplayer.ExoPlayer
import androidx.media3.ui.PlayerControlView
import androidx.media3.ui.PlayerView
import kotlin.math.roundToInt
private inline fun MediaItem(uri: Uri, id: String) = MediaItem.Builder().setUri(uri).setMediaId(id).build();
@SuppressLint("UnsafeOptInUsageError")
@Composable
fun Player(
uri: Uri,
modifier: Modifier = Modifier,
playOnReady: Boolean = true,
useBuiltInController: Boolean = true,
) {
val density = LocalDensity.current
AndroidView(
modifier = modifier,
factory = { context ->
PlayerView(context).apply {
player = ExoPlayer.Builder(context).build().apply {
setMediaItem(MediaItem(uri, uri.toString()))
prepare()
playWhenReady = playOnReady
useController = useBuiltInController
layoutParams = FrameLayout.LayoutParams(
ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT
)
clipToOutline = true
// Set the Background Color of the player as Solid Black Color.
setBackgroundColor(Color.Black.toArgb())
val controller = findViewById<PlayerControlView>(androidx.media3.ui.R.id.exo_controller)
val padding = with(density){
16.dp.roundToPx()
}
controller.setPadding(padding, padding, padding, padding)
}
}
},
onRelease = {
it.player?.release()
it.player = null
},
update = {view ->
view.useController = useBuiltInController
val player = view.player ?: return@AndroidView
if (player.currentMediaItem?.mediaId != uri.toString()) {
player.clearMediaItems()
player.setMediaItem(MediaItem(uri, uri.toString()))
player.prepare()
}
player.playWhenReady = playOnReady
}
)
}
| 1 |
Kotlin
|
0
| 3 |
bc1ec7c63976d25b052250ada4211d55127a327f
| 2,607 |
Gallery
|
Apache License 2.0
|
src/main/kotlin/com/devcharly/kotlin/ant/util/unpackagenamemapper.kt
|
DevCharly
| 61,804,395 | false | null |
/*
* Copyright 2016 <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.devcharly.kotlin.ant
import org.apache.tools.ant.util.UnPackageNameMapper
/******************************************************************************
DO NOT EDIT - this file was generated
******************************************************************************/
interface IUnPackageNameMapperNested {
fun unpackagemapper(
handledirsep: Boolean? = null,
casesensitive: Boolean? = null,
from: String? = null,
to: String? = null)
{
_addUnPackageNameMapper(UnPackageNameMapper().apply {
_init(handledirsep, casesensitive, from, to)
})
}
fun _addUnPackageNameMapper(value: UnPackageNameMapper)
}
fun IGlobPatternMapperNested.unpackagemapper(
handledirsep: Boolean? = null,
casesensitive: Boolean? = null,
from: String? = null,
to: String? = null)
{
_addGlobPatternMapper(UnPackageNameMapper().apply {
_init(handledirsep, casesensitive, from, to)
})
}
fun IFileNameMapperNested.unpackagemapper(
handledirsep: Boolean? = null,
casesensitive: Boolean? = null,
from: String? = null,
to: String? = null)
{
_addFileNameMapper(UnPackageNameMapper().apply {
_init(handledirsep, casesensitive, from, to)
})
}
fun UnPackageNameMapper._init(
handledirsep: Boolean?,
casesensitive: Boolean?,
from: String?,
to: String?)
{
if (handledirsep != null)
setHandleDirSep(handledirsep)
if (casesensitive != null)
setCaseSensitive(casesensitive)
if (from != null)
setFrom(from)
if (to != null)
setTo(to)
}
| 0 |
Kotlin
|
2
| 6 |
b73219cd1b9b57972ed42048c80c6618474f4395
| 2,051 |
kotlin-ant-dsl
|
Apache License 2.0
|
wearsettings/src/main/java/com/thewizrd/wearsettings/actions/MobileDataAction.kt
|
SimpleAppProjects
| 197,253,270 | false | null |
package com.thewizrd.wearsettings.actions
import android.Manifest
import android.content.Context
import android.content.pm.PackageManager
import android.provider.Settings
import androidx.core.content.ContextCompat
import com.thewizrd.shared_resources.actions.Action
import com.thewizrd.shared_resources.actions.ActionStatus
import com.thewizrd.shared_resources.actions.ToggleAction
import com.thewizrd.wearsettings.root.RootHelper
import com.thewizrd.wearsettings.Settings as SettingsHelper
object MobileDataAction {
fun executeAction(context: Context, action: Action): ActionStatus {
if (action is ToggleAction) {
return if (checkSecureSettingsPermission(context)) {
setMobileDataEnabled(context, action.isEnabled)
} else if (SettingsHelper.isRootAccessEnabled() && RootHelper.isRootEnabled()) {
GlobalSettingsAction.putSetting(
"mobile_data",
if (action.isEnabled) {
1
} else {
0
}.toString()
)
} else {
ActionStatus.REMOTE_PERMISSION_DENIED
}
}
return ActionStatus.UNKNOWN
}
private fun setMobileDataEnabled(context: Context, enabled: Boolean): ActionStatus {
return if (ContextCompat.checkSelfPermission(
context,
Manifest.permission.WRITE_SECURE_SETTINGS
) == PackageManager.PERMISSION_GRANTED
) {
val success = Settings.Global.putInt(
context.contentResolver, "mobile_data",
if (enabled) 1 else 0
)
if (success) {
ActionStatus.SUCCESS
} else {
ActionStatus.REMOTE_FAILURE
}
} else {
ActionStatus.REMOTE_PERMISSION_DENIED
}
}
}
| 2 |
Kotlin
|
1
| 8 |
e1d1f0ff0c911b8aacd1ddbcd4e306f664be0957
| 1,928 |
SimpleWear
|
Apache License 2.0
|
app/src/main/java/com/example/movietime/DateActivity.kt
|
tal-sitton
| 529,636,250 | false | null |
package com.example.movietime
import android.content.Intent
import android.os.Bundle
import android.widget.Button
import android.widget.TextView
import java.time.DayOfWeek
import java.time.LocalDateTime
class DateActivity : MyTemplateActivity() {
companion object {
var selectedDays: MutableList<Int> = mutableListOf(LocalDateTime.now().dayOfMonth)
var selectedDatStr: String = "היום"
val selectedHour: MutableList<Hour> = mutableListOf(Hour.ALL_DAY)
var restarted = true
fun checkScreening(screening: Screening): Boolean {
val date = screening.dateTime
return date.dayOfMonth in selectedDays && selectedHour.any { it.between(date) }
}
fun default() {
selectedDays = mutableListOf(LocalDateTime.now().dayOfMonth)
selectedHour.clear()
selectedHour.add(Hour.ALL_DAY)
restarted = true
selectedDatStr = "היום"
}
private fun genText(dateTime: LocalDateTime, addDate: Boolean = true): String {
var out = "יום " + when (dateTime.dayOfWeek) {
DayOfWeek.SUNDAY -> "ראשון"
DayOfWeek.MONDAY -> "שני"
DayOfWeek.TUESDAY -> "שלישי"
DayOfWeek.WEDNESDAY -> "רביעי"
DayOfWeek.THURSDAY -> "חמישי"
DayOfWeek.FRIDAY -> "שישי"
DayOfWeek.SATURDAY -> "שבת"
}
return if (addDate) out + " " + dateTime.dayOfMonth + "/" + dateTime.monthValue else out
}
fun genTextForSelected(day: Int, addDate: Boolean = true): String {
return when (day) {
LocalDateTime.now().dayOfMonth -> "היום"
LocalDateTime.now().plusDays(1).dayOfMonth -> "מחר"
in 1 until LocalDateTime.now().dayOfMonth -> genText(
LocalDateTime.now().plusMonths(1).withDayOfMonth(day), addDate
)
else ->
genText(LocalDateTime.now().withDayOfMonth(day), addDate)
}
}
}
private lateinit var allDay: Button
private lateinit var today: Button
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.actvity_filter_date)
setupTopButtons()
allDay = findViewById(R.id.allDayButton)
today = findViewById(R.id.todayButton)
if (restarted) {
allDay.setBackgroundColor(this.getColor(R.color.purple_500))
today.setBackgroundColor(this.getColor(R.color.purple_500))
}
setupDateButtons()
setupHourButtons()
}
private fun setupDateButtons() {
val now = LocalDateTime.now()
val today = findViewById<Button>(R.id.todayButton)
configDayButton(today, now.dayOfMonth)
val tomorrow = findViewById<Button>(R.id.tomorrowButton)
configDayButton(tomorrow, now.plusDays(1).dayOfMonth)
val twoDays = findViewById<Button>(R.id.twoDaysButton)
twoDays.text = genText(now.plusDays(2))
configDayButton(twoDays, now.plusDays(2).dayOfMonth)
val threeDays = findViewById<Button>(R.id.threeDaysButton)
threeDays.text = genText(now.plusDays(3))
configDayButton(threeDays, now.plusDays(3).dayOfMonth)
val fourDays = findViewById<Button>(R.id.fourDaysButton)
fourDays.text = genText(now.plusDays(4))
configDayButton(fourDays, now.plusDays(4).dayOfMonth)
}
private fun configDayButton(button: Button, day: Int) {
if (!restarted) {
if (selectedDays.contains(day)) {
button.setBackgroundColor(this.getColor(R.color.purple_500))
} else {
button.setBackgroundColor(this.getColor(R.color.purple_200))
}
}
button.setOnClickListener { dayClickListener(button, day) }
}
private fun dayClickListener(button: Button, day: Int) {
val nowDay = LocalDateTime.now().dayOfMonth
if (selectedDays.contains(day)) {
selectedDays.remove(day)
button.setBackgroundColor(this.getColor(R.color.purple_200))
if (selectedDays.isEmpty()) {
selectedDays.add(nowDay)
today.setBackgroundColor(this.getColor(R.color.purple_500))
}
} else {
selectedDays.add(day)
button.setBackgroundColor(this.getColor(R.color.purple_500))
}
if (selectedDays.size == 1) {
selectedDatStr = genTextForSelected(selectedDays[0])
} else {
selectedDatStr = "מספר ימים"
}
}
private fun setupHourButtons() {
val allDay = findViewById<Button>(R.id.allDayButton)
configHourButton(allDay, Hour.ALL_DAY)
val before12 = findViewById<Button>(R.id.before12Button)
configHourButton(before12, Hour.BEFORE_12)
val till15 = findViewById<Button>(R.id.till15Button)
configHourButton(till15, Hour.TILL_15)
val till19 = findViewById<Button>(R.id.till19Button)
configHourButton(till19, Hour.TILL_19)
val after19 = findViewById<Button>(R.id.after19Button)
configHourButton(after19, Hour.AFTER_19)
restarted = false
}
private fun configHourButton(button: Button, hour: Hour) {
if (!restarted) {
if (selectedHour.contains(hour)) {
button.setBackgroundColor(this.getColor(R.color.purple_500))
} else {
button.setBackgroundColor(this.getColor(R.color.purple_200))
}
}
button.setOnClickListener { hourClickListener(button, hour) }
}
private fun hourClickListener(button: Button, hour: Hour) {
if (selectedHour.contains(hour)) {
selectedHour.remove(hour)
button.setBackgroundColor(this.getColor(R.color.purple_200))
if (selectedHour.isEmpty()) {
selectedHour.add(Hour.ALL_DAY)
allDay.setBackgroundColor(this.getColor(R.color.purple_500))
}
} else {
if (hour == Hour.ALL_DAY) {
selectedHour.clear()
selectedHour.add(Hour.ALL_DAY)
allDay.setBackgroundColor(this.getColor(R.color.purple_500))
findViewById<Button>(R.id.before12Button).setBackgroundColor(this.getColor(R.color.purple_200))
findViewById<Button>(R.id.till15Button).setBackgroundColor(this.getColor(R.color.purple_200))
findViewById<Button>(R.id.till19Button).setBackgroundColor(this.getColor(R.color.purple_200))
findViewById<Button>(R.id.after19Button).setBackgroundColor(this.getColor(R.color.purple_200))
} else {
selectedHour.remove(Hour.ALL_DAY)
allDay.setBackgroundColor(this.getColor(R.color.purple_200))
selectedHour.add(hour)
button.setBackgroundColor(this.getColor(R.color.purple_500))
}
}
}
private fun setupTopButtons() {
val mainButton: TextView = findViewById(R.id.dateButton)
mainButton.setBackgroundResource(R.drawable.top_buttons_clicked)
mainButton.text = "אישור"
mainButton.setOnClickListener {
onBackPressedCallback.handleOnBackPressed()
}
val cinemaButton: TextView = findViewById(R.id.cinemaButton)
val movieButton: TextView = findViewById(R.id.movieButton)
val intent = Intent()
intent.addFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION)
intent.addFlags(Intent.FLAG_ACTIVITY_NO_HISTORY)
cinemaButton.setOnClickListener {
intent.setClass(this, CinemaActivity::class.java)
MainActivity.filter()
startActivity(intent)
}
movieButton.setOnClickListener {
intent.setClass(this, MovieActivity::class.java)
MainActivity.filter()
startActivity(intent)
}
}
enum class Hour(val start: Int, val end: Int) {
ALL_DAY(0, 24), BEFORE_12(0, 12), TILL_15(12, 15), TILL_19(15, 19), AFTER_19(19, 24);
fun between(date: LocalDateTime): Boolean {
return date.hour >= start && (date.hour < end || (date.hour == end && date.minute == 0))
}
override fun toString(): String {
return "$start:00 - $end:00"
}
}
}
| 0 |
Kotlin
|
0
| 0 |
0944fa51ab66cddb75c94f7fc86a1607a3ec7359
| 8,462 |
Movie-Time
|
MIT License
|
src/main/kotlin/com/jerryjeon/logjerry/filter/FilterManager.kt
|
jerry-jeon
| 521,791,909 | false |
{"Kotlin": 642877}
|
package com.jerryjeon.logjerry.filter
import com.jerryjeon.logjerry.log.Log
import com.jerryjeon.logjerry.log.Priority
import com.jerryjeon.logjerry.preferences.SortOrderPreferences
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.flow.*
class FilterManager(
originalLogsFlow: StateFlow<List<Log>>,
defaultSortOption: SortOrderPreferences = SortOrderPreferences.load(),
) {
private val filterScope = CoroutineScope(Dispatchers.Default)
val textFiltersFlow: MutableStateFlow<List<TextFilter>> = MutableStateFlow(emptyList())
val priorityFilterFlow: MutableStateFlow<PriorityFilter> = MutableStateFlow(PriorityFilter(Priority.Verbose))
val hiddenLogIndicesFlow: MutableStateFlow<HiddenFilter> = MutableStateFlow(HiddenFilter(emptySet()))
val packageFiltersFlow = MutableStateFlow(PackageFilters(emptyList()))
val tagFiltersFlow = MutableStateFlow(TagFilters(emptyList()))
val packageFilterSortOptionFlow = MutableStateFlow(
defaultSortOption.packageFilterSortOption to defaultSortOption.packageFilterSortOrder
)
val tagFilterSortOptionFlow = MutableStateFlow(
defaultSortOption.tagFilterSortOption to defaultSortOption.tagFilterSortOrder
)
private val packageFilterComparator = packageFilterSortOptionFlow.map {
val (option, order) = it
when (option) {
FilterSortOption.Frequency -> compareByDescending<PackageFilter> { it.frequency }
FilterSortOption.Name -> compareByDescending { it.packageName }
}.let { comparator ->
if (order == SortOrder.Ascending) {
comparator.reversed()
} else {
comparator
}
}
}
private val tagFilterComparator = tagFilterSortOptionFlow.map { it ->
val (option, order) = it
when (option) {
FilterSortOption.Frequency -> compareByDescending<TagFilter> { it.frequency }
FilterSortOption.Name -> compareByDescending { it.tag }
}.let { comparator ->
if (order == SortOrder.Ascending) {
comparator.reversed()
} else {
comparator
}
}
}
val sortedPackageFiltersFlow = packageFiltersFlow.combine(packageFilterComparator) { packageFilters, comparator ->
packageFilters.copy(filters = packageFilters.filters.sortedWith(comparator))
}
.stateIn(filterScope, SharingStarted.Eagerly, PackageFilters(emptyList()))
val sortedTagFiltersFlow = tagFiltersFlow.combine(tagFilterComparator) { tagFilters, comparator ->
tagFilters.copy(filters = tagFilters.filters.sortedWith(comparator))
}
.stateIn(filterScope, SharingStarted.Eagerly, TagFilters(emptyList()))
val filtersFlow = combine(
textFiltersFlow,
priorityFilterFlow,
hiddenLogIndicesFlow,
packageFiltersFlow,
tagFiltersFlow,
) { textFilters, priorityFilter, hiddenLogIndices, packageFilters, tagFilters ->
textFilters + listOf(priorityFilter, hiddenLogIndices) + packageFilters + tagFilters
}
init {
originalLogsFlow.onEach { originalLogs ->
val packageFilters = originalLogs.groupingBy { it.packageName }.eachCount()
.map { (packageName, frequency) ->
PackageFilter(packageName, frequency, true)
}
.let { PackageFilters(it) }
packageFiltersFlow.value = packageFilters
}
.launchIn(filterScope)
originalLogsFlow.onEach { originalLogs ->
val tagFilters = originalLogs.groupingBy { it.tag }.eachCount()
.map { (tag, frequency) ->
TagFilter(tag, frequency, true)
}
.let { TagFilters(it) }
tagFiltersFlow.value = tagFilters
}
.launchIn(filterScope)
}
fun addTextFilter(textFilter: TextFilter) {
textFiltersFlow.value = textFiltersFlow.value + textFilter
}
fun removeTextFilter(textFilter: TextFilter) {
textFiltersFlow.value = textFiltersFlow.value - textFilter
}
fun setPriorityFilter(priorityFilter: PriorityFilter) {
this.priorityFilterFlow.value = priorityFilter
}
fun hide(logIndex: Int) {
hiddenLogIndicesFlow.update { it.copy(hiddenLogIndices = it.hiddenLogIndices + logIndex) }
}
fun unhide(logIndex: Int) {
hiddenLogIndicesFlow.update { it.copy(hiddenLogIndices = it.hiddenLogIndices - logIndex) }
}
fun togglePackageFilter(packageFilter: PackageFilter) {
packageFiltersFlow.update { packageFilters ->
packageFilters.copy(
filters = packageFilters.filters.map {
if (it.packageName == packageFilter.packageName) {
it.copy(include = !it.include)
} else {
it
}
}
)
}
}
fun setAllPackageFilter(include: Boolean) {
packageFiltersFlow.update { packageFilters ->
packageFilters.copy(
filters = packageFilters.filters.map {
it.copy(include = include)
}
)
}
}
fun toggleTagFilter(tagFilter: TagFilter) {
tagFiltersFlow.update { tagFilters ->
tagFilters.copy(
filters = tagFilters.filters.map {
if (it.tag == tagFilter.tag) {
it.copy(include = !it.include)
} else {
it
}
}
)
}
}
fun setAllTagFilter(include: Boolean) {
tagFiltersFlow.update { tagFilters ->
tagFilters.copy(
filters = tagFilters.filters.map {
it.copy(include = include)
}
)
}
}
fun setPackageFilterSortOption(option: FilterSortOption, order: SortOrder) {
packageFilterSortOptionFlow.value = option to order
SortOrderPreferences.save(
SortOrderPreferences(
tagFilterSortOptionFlow.value.first,
tagFilterSortOptionFlow.value.second,
option,
order,
)
)
}
fun setTagFilterSortOption(option: FilterSortOption, order: SortOrder) {
tagFilterSortOptionFlow.value = option to order
SortOrderPreferences.save(
SortOrderPreferences(
option,
order,
packageFilterSortOptionFlow.value.first,
packageFilterSortOptionFlow.value.second,
)
)
}
}
| 3 |
Kotlin
|
5
| 50 |
22e02dc7f342d805dbbe47fa1be67f696eb162bf
| 6,806 |
LogJerry
|
Apache License 2.0
|
app/src/main/java/com/blocksdecoded/dex/core/manager/auth/AuthManager.kt
|
wepobid
| 208,574,428 | true |
{"Kotlin": 408529}
|
package com.blocksdecoded.dex.core.manager.auth
import android.security.keystore.UserNotAuthenticatedException
import com.blocksdecoded.dex.App
import com.blocksdecoded.dex.core.adapter.Erc20Adapter
import com.blocksdecoded.dex.core.adapter.EthereumAdapter
import com.blocksdecoded.dex.core.manager.IAdapterManager
import com.blocksdecoded.dex.core.manager.zrx.IRelayerAdapterManager
import com.blocksdecoded.dex.core.model.AuthData
import com.blocksdecoded.dex.core.security.ISecuredStorage
import io.reactivex.subjects.PublishSubject
class AuthManager(
private val securedStorage: ISecuredStorage
) : IAuthManager {
override var adapterManager: IAdapterManager? = null
override var relayerAdapterManager: IRelayerAdapterManager? = null
override var authData: AuthData? = null
get() = securedStorage.authData//TODO: Load via safeLoad
override var authDataSignal = PublishSubject.create<Unit>()
override val isLoggedIn: Boolean
get() = !securedStorage.noAuthData()
@Throws(UserNotAuthenticatedException::class)
override fun safeLoad() {
authData = securedStorage.authData
authDataSignal.onNext(Unit)
}
@Throws(UserNotAuthenticatedException::class)
override fun login(words: List<String>) {
AuthData(words).let {
securedStorage.saveAuthData(it)
authData = it
authDataSignal.onNext(Unit)
}
}
override fun logout() {
adapterManager?.stopKits()
relayerAdapterManager?.clearRelayers()
EthereumAdapter.clear(App.instance)
Erc20Adapter.clear(App.instance)
authData = null
}
}
| 0 | null |
0
| 0 |
4ecd7072467ac5247d4d0fe3c1b4ffccf64ac1b0
| 1,662 |
dex-app-android
|
MIT License
|
domain/src/main/java/io/aethibo/domain/Plan.kt
|
primepixel
| 353,147,166 | false | null |
package io.aethibo.domain
import com.squareup.moshi.Json
import com.squareup.moshi.JsonClass
@JsonClass(generateAdapter = true)
data class Plan(
val collaborators: Int = 0,
val name: String = "",
@Json(name = "private_repos")
val privateRepos: Int = 0,
val space: Int = 0
)
| 0 |
Kotlin
|
0
| 3 |
233cc83f2b116e944bddaca0beca8a66d3143cae
| 296 |
Fork
|
Apache License 2.0
|
idea/tests/testData/copyright/NoPackage.kt
|
JetBrains
| 278,369,660 | false | null |
/* PRESENT */
fun some() {}
// COMMENTS: 1
| 0 | null |
30
| 82 |
cc81d7505bc3e9ad503d706998ae8026c067e838
| 44 |
intellij-kotlin
|
Apache License 2.0
|
Application/core/core-preferences/src/main/java/com/istudio/core_preferences/domain/InAppReviewPreferences.kt
|
devrath
| 570,594,617 | false |
{"Kotlin": 238294}
|
package com.istudio.core_preferences.domain
import kotlinx.coroutines.flow.Flow
/**
* Provides the preferences that store if the user reviewed the app already, or not.
*
* It also stores info if the user chose to review the app later or never.
*
* If the user chose to never review the app - we don't prompt them with the review flow or dialog.
* If the user chose to review the app later - we check if enough time has passed (e.g. a week).
* If the user already chose to review the app, we shouldn't show the dialog or prompt again.
* */
interface InAppReviewPreferences {
/**
* @return If the user has chosen the "Rate App" option or not.
* */
suspend fun hasUserRatedApp(): Flow<Boolean>
/**
* Stores if the user chose to rate the app or not.
*
* @param hasRated - If the user chose the "Rate App" option.
* */
suspend fun setUserRatedApp(hasRated: Boolean)
/**
* @return If the user has chosen the "Ask Me Later" option or not.
* */
suspend fun hasUserChosenRateLater(): Flow<Boolean>
/**
* Stores if the user wants to rate the app later.
*
* @param hasChosenRateLater - If the user chose the "Ask Me Later" option.
* */
suspend fun setUserChosenRateLater(hasChosenRateLater: Boolean)
/**
* @return Timestamp when the user chose the "Ask Me Later" option.
* */
suspend fun getRateLaterTime(): Flow<Long>
/**
* Stores the time when the user chose to review the app later.
*
* @param time - The timestamp when the user chose the "Ask Me Later" option.
* */
suspend fun setRateLater(time: Long)
/**
* @return The number of times the distance been tracked
* */
suspend fun noOfDistanceTracked(): Flow<Int>
/**
* Stores the number of times the distance been tracked.
*
* @param number - set the number of times
* */
suspend fun setNoOfDistanceTracked(number: Int)
/**
* Clears out the preferences.
*
* Useful for situations where we add some crucial features to the app and want to ask the user
* for an opinion.
*
* This should be used only if the user didn't rate the app before.
* */
suspend fun clearIfUserDidNotRate()
/**
* @return the string value for the current UI mode of application saved
* */
suspend fun getUiModeForApp(): Flow<Int>
/**
* Stores UI mode of the app in the Shared preferences
*
* @param mode - User saves the UI mode selected
* */
suspend fun setUiModeForApp(mode: Int)
suspend fun isUiModeKeyStored(): Flow<Boolean>
}
| 0 |
Kotlin
|
3
| 6 |
17d03b535e2ced992b97cc1e3a6d40c5393afded
| 2,649 |
Distance-Tracker
|
Apache License 2.0
|
bluetooth/src/jsMain/kotlin/UUID.kt
|
splendo
| 191,371,940 | false | null |
/*
Copyright (c) 2020. Splendo Consulting B.V. The Netherlands
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.splendo.kaluga.bluetooth
actual data class UUID(val uuidString: String)
actual val UUID.uuidString: String
get() = uuidString
internal actual fun unsafeUUIDFrom(uuidString: String): UUID = UUID(uuidString = uuidString)
actual fun randomUUID(): UUID = UUID(randomUUIDString())
| 91 |
Kotlin
|
3
| 93 |
cd0f3a583efb69464aa020d206f598c6d15a0899
| 925 |
kaluga
|
Apache License 2.0
|
app/src/main/java/com/arcadan/dodgetheenemies/game/GameParameters.kt
|
ArcaDone
| 351,158,574 | false | null |
package com.arcadan.dodgetheenemies.game
import com.arcadan.dodgetheenemies.enums.PowerUp
import com.arcadan.dodgetheenemies.util.Global
class GameParameters {
companion object {
var instance = GameParameters()
}
var gameRunning: Boolean = false
var shouldStopSpawn: Boolean = false
// ========== Variable Parameters ===========
var hasWon: Boolean = false
// Experience
var nextLevelGap: Double = 1.25
// Movement
var reverseDirection: Boolean = false
var deltaSpeed: Int = 0
// Backpack
var backpack: MutableList<PowerUp> = mutableListOf()
// Jump
var jumpEquationC: Double = (Global.instance.measures.height / 10).toDouble() // Real jump height in pixels
var jumpGravity: Int = 1 // Millis between each position update during jump
fun resetParameters() {
deltaSpeed = 0
}
// ========== Constant Parameters ===========
// Debug
val enableDebugMode: Boolean = false
// Experience
val levelFull = 10000
val newLevel = 1
// Jump
val jumpEquationA: Double = -.01 // Jump width (should be left at this value, this regulates how much time the player spends in air)
val jumpEquationB: Double = 0.0 // Leave this to 0
val megaJumpValue: Double = (Global.instance.measures.height / 4).toDouble()
// Movement
val playerSpeed: Int = 12 // Pixels per rotation detection
// Spawn
val spawnDelayFeature: Int = 5 // Seconds
val spawnDelayPowerUp: Int = 7 // Seconds
val spawnDelayVariation = 1 // + or - Seconds relative to spawnDelay
val maxObjectsOnScreen: Int = 20 // Count
// Physics
val fallSpeed: Int = 20 // Pixels per frame_green
val standingOnASurfaceTolerance = 20 // Pixels
// Hearts
val deltaHearts: Int = 5
val maxHearts: Int = 100
val restoreHeartsRate: Int = 2
// Shop prices
// Power Up
val slurpRedPrice: Int = 250
val speedUpPrice: Int = 200
val megaJumpPrice: Int = 150
val doubleCoinsPrice: Int = 50
// Coins
val littleCoinPrice: Int = 30
val mediumCoinPrice: Int = 50
val largeCoinPrice: Int = 80
val littleChestPrice: Int = 100
val mediumChestPrice: Int = 160
val largeChestPrice: Int = 200
// Hearts
val tenHeartsPrice: Int = 0
val twentyHeartsPrice: Int = 300
val fortyHeartsPrice: Int = 500
val sixtyHeartsPrice: Int = 650
val eightyHeartsPrice: Int = 850
val oneHundredHeartsPrice: Int = 1200
// Gems
val firstGemPrice: Int = 0
val secondGemPrice: Int = 0
// Skins
val firstSkinPrice: Int = 0
val secondSkinPrice: Int = 0
// Shop rewards
// Power Up
val slurpRedReward: Int = 1
val speedUpReward: Int = 1
val megaJumpReward: Int = 1
val doubleCoinsReward: Int = 1
// Coins
val oneHundredCoinsReward: Int = 100
val littleCoinsReward: Int = 230
val mediumCoinsReward: Int = 500
val largeCoinsReward: Int = 760
val littleCoinsChestReward: Int = 1000
val mediumCoinsChestReward: Int = 2000
val largeCoinsChestReward: Int = 3000
// Hearts
val twentyHeartsReward = 20
val fortyHeartsReward = 40
val sixtyHeartsReward = 60
val eightyHeartsReward = 80
val oneHundredHearReward = 100
// Gems
val eightyGemReward: Int = 80
val fiveHundredGemReward: Int = 500
val oneThousandTwoHundredGemsReward: Int = 1200
val twoThousandFiveHundredGemReward: Int = 2500
val sixThousandFiveHundredGemReward: Int = 6500
val fourteenThousandGemsReward: Int = 14000
// Sku
val littleGemsSku = "little_gems"
val mediumGemsSku = "medium_gems"
val largeGemsSku = "large_gems"
val littleGemsChestSku = "little_gem_chest"
val mediumGemsChestSku = "medium_gem_chest"
val largeGemsChestSku = "large_gem_chest"
}
| 0 |
Kotlin
|
0
| 2 |
24133757b19f2b2fea64542347b339f8621284f6
| 3,839 |
DodgeTheEnemies
|
MIT License
|
lib/src/main/java/org/oneui/compose/util/StringExtensions.kt
|
TrainerSnow
| 666,717,085 | false | null |
package org.oneui.compose.util
val String.isInt: Boolean
get() {
return try {
toInt()
true
} catch (_: Exception) {
false
}
}
| 0 |
Kotlin
|
2
| 5 |
65776f20b6747c274deed8b10abe68230399e430
| 194 |
OneUI_Compose
|
Apache License 2.0
|
fdownloader/android/app/src/main/kotlin/com/example/fdownloader/MainActivity.kt
|
smok95
| 325,194,956 | false |
{"C++": 37801, "Dart": 16514, "CMake": 16366, "HTML": 5490, "C": 1463, "Swift": 821, "Kotlin": 256, "Objective-C": 77}
|
package com.example.fdownloader
import io.flutter.embedding.android.FlutterActivity
class MainActivity: FlutterActivity() {
}
| 0 |
C++
|
0
| 1 |
8b8812962017af2ab0075e7d6f4d769e8a61647a
| 128 |
flutter-examples
|
MIT License
|
src/main/kotlin/su/plo/voice/plugin/util/addon.kt
|
plasmoapp
| 713,654,884 | false |
{"Kotlin": 49705}
|
package su.plo.voice.plugin.util
import su.plo.voice.plugin.AddonMeta
import su.plo.voice.plugin.parser.JavaAddonParser
import su.plo.voice.plugin.parser.KotlinAddonParser
import java.io.File
fun File.parseAddonMeta(sourceFiles: Collection<File>) = parseAddon(sourceFiles, this)
private fun parseAddon(sourceFiles: Collection<File>, file: File): AddonMeta? {
val fileName = file.name
if (fileName.endsWith(".java")) {
return JavaAddonParser.parseAddon(sourceFiles, file)
} else if (fileName.endsWith(".kt")) {
return KotlinAddonParser.parseAddon(sourceFiles, file)
}
return null
}
| 0 |
Kotlin
|
0
| 0 |
a34cca1c3e7f996222ed58f68eece0fa6461f5cf
| 623 |
pv-gradle-plugin
|
MIT License
|
modules/core/src/main/java/de/deutschebahn/bahnhoflive/ui/station/info/StationInfoAdapter.kt
|
dbbahnhoflive
| 267,806,942 | false |
{"Kotlin": 1313069, "Java": 729702, "HTML": 43823}
|
package de.deutschebahn.bahnhoflive.ui.station.info
import android.content.Intent
import android.os.Build
import android.view.ViewGroup
import androidx.lifecycle.LifecycleOwner
import androidx.lifecycle.LiveData
import de.deutschebahn.bahnhoflive.BaseApplication
import de.deutschebahn.bahnhoflive.R
import de.deutschebahn.bahnhoflive.analytics.TrackingManager
import de.deutschebahn.bahnhoflive.backend.local.model.ServiceContent
import de.deutschebahn.bahnhoflive.backend.local.model.ServiceContentType
import de.deutschebahn.bahnhoflive.databinding.CardExpandableStationInfoBinding
import de.deutschebahn.bahnhoflive.repository.Station
import de.deutschebahn.bahnhoflive.ui.feedback.WhatsAppInstallation
import de.deutschebahn.bahnhoflive.ui.feedback.createPlaystoreIntent
import de.deutschebahn.bahnhoflive.ui.feedback.deviceName
import de.deutschebahn.bahnhoflive.ui.station.CommonDetailsCardViewHolder
import de.deutschebahn.bahnhoflive.ui.station.StationActivity
import de.deutschebahn.bahnhoflive.util.MailUri
import de.deutschebahn.bahnhoflive.view.SingleSelectionManager
import de.deutschebahn.bahnhoflive.view.inflater
class StationInfoAdapter(
private val serviceContents: List<ServiceContent>,
val trackingManager: TrackingManager,
val dbActionButtonParser: DbActionButtonParser,
val stationLiveData: LiveData<out Station>,
val whatsAppInstallationLiveData: WhatsAppInstallation,
val whatsAppContactliveData: LiveData<String?>,
val lifecycleProvider: () -> LifecycleOwner,
val activityStarter: (Intent) -> Unit
) : androidx.recyclerview.widget.RecyclerView.Adapter<CommonDetailsCardViewHolder<ServiceContent>>() {
val singleSelectionManager: SingleSelectionManager = SingleSelectionManager(this)
override fun onCreateViewHolder(
parent: ViewGroup,
viewType: Int
): CommonDetailsCardViewHolder<ServiceContent> = when (viewType) {
VIEW_TYPE_STATION_COMPLAINT -> StationComplaintServiceContentViewHolder(
parent,
singleSelectionManager,
stationLiveData,
whatsAppInstallationLiveData,
whatsAppContactliveData,
lifecycleProvider,
activityStarter
)
else -> ServiceContentViewHolder(
CardExpandableStationInfoBinding.inflate(parent.inflater, parent, false),
singleSelectionManager,
trackingManager,
dbActionButtonParser
) { dbActionButton: DbActionButton ->
if (dbActionButton.type == DbActionButton.Type.ACTION) {
when (dbActionButton.data) {
"appIssue" -> {
val emailIntent = Intent(
Intent.ACTION_SENDTO,
MailUri().apply {
to = parent.context.getString(R.string.feedback_send_to)
this.subject = parent.context.getString(R.string.feedback_subject)
body = BaseApplication.get().run {
"\n\n\n\n" +
"Um meine folgenden Anmerkungen leichter nachvollziehen zu können, sende ich Ihnen anbei meine Geräteinformationen:\n\n" +
(stationLiveData.value?.let<Station, String> { "Bahnhof: ${it.title} (${it.id})\n" }
?: "") +
"Gerät: $deviceName (${Build.VERSION.SDK_INT})\n" +
"App-Version: $versionName ($versionCode)"
}
}.build()
)
activityStarter(Intent.createChooser(emailIntent, "E-Mail senden..."))
}
"chatbot" -> {
}
"rateApp" -> {
activityStarter(parent.context.createPlaystoreIntent())
}
"mobilitaetsservice" -> run {
(parent.context as? StationActivity)?.showMobilityServiceNumbers()
}
}
}
}
}
override fun onBindViewHolder(
holder: CommonDetailsCardViewHolder<ServiceContent>,
position: Int
) {
holder.bind(serviceContents[position])
}
override fun getItemCount(): Int {
return serviceContents.size
}
override fun getItemViewType(position: Int): Int {
return when (serviceContents[position].type.toLowerCase()) {
ServiceContentType.Local.STATION_COMPLAINT -> VIEW_TYPE_STATION_COMPLAINT
else -> VIEW_TYPE_DEFAULT
}
}
val selectedItem get() = singleSelectionManager.getSelectedItem(serviceContents)
companion object {
const val VIEW_TYPE_DEFAULT = 0
const val VIEW_TYPE_STATION_COMPLAINT = 1
}
}
| 0 |
Kotlin
|
4
| 33 |
ae72e13b97a60ca942b63ff36f8b982ea0a7bb4f
| 4,983 |
dbbahnhoflive-android
|
Apache License 2.0
|
app/core/src/main/java/com/fsck/k9/SettingsChangeListener.kt
|
rcrtn32002
| 378,182,972 | true |
{"Git Config": 1, "Gradle": 27, "INI": 2, "Shell": 5, "Text": 4, "Ignore List": 3, "Batchfile": 1, "Git Attributes": 1, "EditorConfig": 1, "Markdown": 9, "XML": 385, "SVG": 67, "PostScript": 1, "Java": 504, "AIDL": 2, "YAML": 4, "Proguard": 2, "Kotlin": 591, "E-mail": 11, "JSON": 20}
|
package com.fsck.k9
interface SettingsChangeListener {
fun onSettingsChanged()
}
| 0 | null |
0
| 1 |
5520fdac96684879239bc215f715beaf19210459
| 86 |
k-9
|
Apache License 2.0
|
test-suite-kotlin-ksp/src/test/kotlin/io/micronaut/docs/annotation/requestattributes/StoryController.kt
|
micronaut-projects
| 124,230,204 | false |
{"Java": 13018207, "Groovy": 7010109, "Kotlin": 1674872, "HTML": 143, "Shell": 14}
|
/*
* Copyright 2017-2020 original authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.micronaut.docs.annotation.requestattributes
import io.micronaut.http.HttpResponse
import io.micronaut.http.annotation.Controller
import io.micronaut.http.annotation.Get
@Controller("/story")
class StoryController {
@Get("/{id}")
operator fun get(id: String): HttpResponse<Story> {
val story = Story()
story.id = id
return HttpResponse.ok(story)
}
}
| 753 |
Java
|
1061
| 6,059 |
c9144646b31b23bd3c4150dec8ddd519947e55cf
| 1,000 |
micronaut-core
|
Apache License 2.0
|
src/main/kotlin/slack/cli/exec/RetrySignal.kt
|
slackhq
| 465,442,197 | false | null |
/*
* Copyright (C) 2023 Slack Technologies, 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 slack.cli.exec
import com.squareup.moshi.JsonClass
import dev.zacsweers.moshix.sealed.annotations.TypeLabel
import kotlin.time.Duration
@JsonClass(generateAdapter = true, generator = "sealed:type")
internal sealed interface RetrySignal {
/** Unknown issue. */
@TypeLabel("unknown") object Unknown : RetrySignal
/** Indicates an issue that is recognized but cannot be retried. */
@TypeLabel("ack") object Ack : RetrySignal
/** Indicates this issue should be retried immediately. */
@TypeLabel("immediate") object RetryImmediately : RetrySignal
/** Indicates this issue should be retried after a [delay]. */
@TypeLabel("delayed")
@JsonClass(generateAdapter = true)
data class RetryDelayed(
// Can't default to 1.minutes due to https://github.com/ZacSweers/MoshiX/issues/442
val delay: Duration
) : RetrySignal
}
| 3 |
Kotlin
|
4
| 23 |
5e4b625c4651be84c61f8d351be68f48a1faa251
| 1,465 |
kotlin-cli-util
|
Apache License 2.0
|
src/all/jellyfin/src/eu/kanade/tachiyomi/animeextension/all/jellyfin/JellyfinAuthenticator.kt
|
aniyomiorg
| 360,630,872 | false | null |
package eu.kanade.tachiyomi.animeextension.all.jellyfin
import android.content.SharedPreferences
import android.os.Build
import android.util.Log
import eu.kanade.tachiyomi.AppInfo
import eu.kanade.tachiyomi.network.POST
import eu.kanade.tachiyomi.util.parseAs
import kotlinx.serialization.encodeToString
import kotlinx.serialization.json.Json
import kotlinx.serialization.json.buildJsonObject
import kotlinx.serialization.json.put
import okhttp3.Headers
import okhttp3.MediaType.Companion.toMediaType
import okhttp3.OkHttpClient
import okhttp3.RequestBody.Companion.toRequestBody
import uy.kohesive.injekt.injectLazy
class JellyfinAuthenticator(
private val preferences: SharedPreferences,
private val baseUrl: String,
private val client: OkHttpClient,
) {
private val json: Json by injectLazy()
fun login(username: String, password: String): Pair<String?, String?> {
return runCatching {
val authResult = authenticateWithPassword(username, password)
val key = authResult.AccessToken
val userId = authResult.SessionInfo.UserId
saveLogin(key, userId)
Pair(key, userId)
}.getOrElse {
Log.e(LOG_TAG, it.stackTraceToString())
Pair(null, null)
}
}
private fun authenticateWithPassword(username: String, password: String): LoginResponse {
var deviceId = getPrefDeviceId()
if (deviceId.isNullOrEmpty()) {
deviceId = getRandomString()
setPrefDeviceId(deviceId)
}
val aniyomiVersion = AppInfo.getVersionName()
val androidVersion = Build.VERSION.RELEASE
val authHeader = Headers.headersOf(
"X-Emby-Authorization",
"MediaBrowser Client=\"$CLIENT\", Device=\"Android $androidVersion\", DeviceId=\"$deviceId\", Version=\"$aniyomiVersion\"",
)
val body = json.encodeToString(
buildJsonObject {
put("Username", username)
put("Pw", password)
},
).toRequestBody("application/json; charset=utf-8".toMediaType())
val request = POST("$baseUrl/Users/authenticatebyname", headers = authHeader, body = body)
return client.newCall(request).execute().parseAs()
}
private fun getRandomString(): String {
val allowedChars = ('A'..'Z') + ('a'..'z') + ('0'..'9')
return (1..172)
.map { allowedChars.random() }
.joinToString("")
}
private fun saveLogin(key: String, userId: String) {
preferences.edit()
.putString(JFConstants.APIKEY_KEY, key)
.putString(JFConstants.USERID_KEY, userId)
.apply()
}
private fun getPrefDeviceId(): String? = preferences.getString(
DEVICEID_KEY,
null,
)
private fun setPrefDeviceId(value: String) = preferences.edit().putString(
DEVICEID_KEY,
value,
).apply()
companion object {
private const val DEVICEID_KEY = "device_id"
private const val CLIENT = "Aniyomi"
private const val LOG_TAG = "JellyfinAuthenticator"
}
}
| 393 | null |
213
| 531 |
cc6cffd7003b57368b0fe4a96a32bac583874080
| 3,139 |
aniyomi-extensions
|
Apache License 2.0
|
app/src/main/java/org/mopcon/session/app/ui/all/news/NewsFragment.kt
|
MOPCON
| 133,215,529 | false |
{"Kotlin": 232787}
|
package org.mopcon.session.app.ui.all.news
import android.content.Intent
import android.net.Uri
import android.view.LayoutInflater
import android.view.ViewGroup
import androidx.recyclerview.widget.LinearLayoutManager
import org.mopcon.session.app.databinding.FragmentNewsBinding
import org.mopcon.session.app.ui.base.BaseBindingFragment
import org.mopcon.session.app.ui.extension.BottomItemDecoration
import org.koin.androidx.viewmodel.ext.android.viewModel
class NewsFragment : BaseBindingFragment<FragmentNewsBinding>() {
override val bindingInflater: (LayoutInflater, ViewGroup?, Boolean) -> FragmentNewsBinding = FragmentNewsBinding::inflate
private val viewModel: NewsViewModel by viewModel()
private val newsAdapter by lazy {
NewsAdapter(
NewsItemClickListener {
context?.startActivity(Intent(Intent.ACTION_VIEW, Uri.parse(it)))
})
}
override fun initLayout() {
binding.rvNews.apply {
adapter = newsAdapter
layoutManager = LinearLayoutManager(context, LinearLayoutManager.VERTICAL, false)
addItemDecoration(BottomItemDecoration(16))
}
}
override fun initAction() {
viewModel.getNews()
}
override fun initObserver() {
viewModel.news.observe(viewLifecycleOwner) {
newsAdapter.submitList(it)
}
viewModel.isLoading.observe(viewLifecycleOwner) {
if (it) loading() else hideLoading()
}
}
}
| 21 |
Kotlin
|
4
| 8 |
d4a5e52253d01cac3e4b9c0b574ebb99f483db49
| 1,505 |
App-Android
|
MIT License
|
src/main/kotlin/com/jacobtread/alto/utils/nbt/NBTMutableSerializable.kt
|
AltoClient
| 449,599,250 | false |
{"Kotlin": 157065}
|
package com.jacobtread.alto.utils.nbt
import com.jacobtread.alto.utils.nbt.types.NBTCompound
interface NBTMutableSerializable {
/**
* Reads the serialized object from
* the provided NBT compound tag
*
* @param nbt The nbt tag to read from
*/
fun readFromNBT(nbt: NBTCompound)
/**
* Writes the serializable object to the provided
* NBT compound tag and returns it
*
* @param nbt The nbt tag to write to
* @return The provided nbt tag
*/
fun writeToNBT(nbt: NBTCompound)
}
| 0 |
Kotlin
|
0
| 1 |
ea9410cff59a810edcff0b782f362b73f1c9825f
| 546 |
Utilities
|
MIT License
|
app/src/main/java/com/allysonjeronimo/toshop/legacy/util/SQLiteDataHelper.kt
|
allysonjeronimo
| 329,934,342 | false | null |
package com.allysonjeronimo.toshop.legacy.util
import android.content.Context
import android.database.sqlite.SQLiteDatabase
import com.allysonjeronimo.toshop.legacy.entities.*
import com.allysonjeronimo.toshop.legacy.utils.AssetsHelper
import org.json.JSONArray
class SQLiteDataHelper(private val context:Context){
companion object{
private var instance: SQLiteDataHelper? = null
fun getInstance(context: Context) : SQLiteDataHelper {
if(instance == null)
instance = SQLiteDataHelper(context)
return instance!!
}
private const val LIST = "CREATE TABLE IF NOT EXISTS ${ShoppingList.TABLE_NAME} (" +
"${ShoppingList.COLUMN_ID} INTEGER PRIMARY KEY AUTOINCREMENT, " +
"${ShoppingList.COLUMN_DESCRIPTION} TEXT NOT NULL, " +
"${ShoppingList.COLUMN_LAST_UPDATE} TEXT DEFAULT CURRENT_TIMESTAMP)"
private const val ITEM = "CREATE TABLE IF NOT EXISTS ${Item.TABLE_NAME} (" +
"${Item.COLUMN_ID} INTEGER PRIMARY KEY AUTOINCREMENT, " +
"${Item.COLUMN_DESCRIPTION} TEXT NOT NULL, " +
"${Item.COLUMN_QUANTITY} REAL DEFAULT 1, " +
"${Item.COLUMN_UNIT} TEXT DEFAULT 'UN', " +
"${Item.COLUMN_PRICE} REAL DEFAULT 0.0, " +
"${Item.COLUMN_NOTES} TEXT, " +
"${Item.COLUMN_PURCHASED} INTEGER DEFAULT 0, " +
"${Item.COLUMN_LAST_UPDATE} TEXT DEFAULT CURRENT_TIMESTAMP, " +
"${Item.FK_CATEGORY_ID} INTEGER DEFAULT 1, " +
"${Item.FK_COLUMN_LIST_ID} INTEGER, " +
"FOREIGN KEY (${Item.FK_COLUMN_LIST_ID}) " +
"REFERENCES ${ShoppingList.TABLE_NAME} (${ShoppingList.COLUMN_ID}) " +
"ON DELETE CASCADE)"
private const val CATEGORY = "CREATE TABLE IF NOT EXISTS ${Category.TABLE_NAME} (" +
"${Category.COLUMN_ID} INTEGER PRIMARY KEY AUTOINCREMENT, " +
"${Category.COLUMN_RESOURCE_ICON_NAME} TEXT)"
private const val CATEGORY_NAME = "CREATE TABLE IF NOT EXISTS ${CategoryName.TABLE_NAME} (" +
"${CategoryName.COLUMN_ID} INTEGER PRIMARY KEY AUTOINCREMENT, " +
"${CategoryName.COLUMN_LOCALE} TEXT, " +
"${CategoryName.COLUMN_NAME} TEXT, " +
"${CategoryName.FK_COLUMN_CATEGORY_ID} INTEGER REFERENCES ${Category.TABLE_NAME} (${Category.COLUMN_ID}))"
private const val PRODUCT = "CREATE TABLE IF NOT EXISTS ${Product.TABLE_NAME} (" +
"${Product.COLUMN_ID} INTEGER PRIMARY KEY AUTOINCREMENT, " +
"${Product.FK_COLUMN_CATEGORY_ID} INTEGER REFERENCES ${Category.TABLE_NAME} (${Category.COLUMN_ID})) "
private const val PRODUCT_NAME = "CREATE TABLE IF NOT EXISTS ${ProductName.TABLE_NAME} (" +
"${ProductName.COLUMN_ID} INTEGER PRIMARY KEY AUTOINCREMENT, " +
"${ProductName.COLUMN_LOCALE} TEXT, " +
"${ProductName.COLUMN_NAME} TEXT, " +
"${ProductName.FK_COLUMN_PRODUCT_ID} INTEGER REFERENCES ${Product.TABLE_NAME} (${Product.COLUMN_ID})) "
val SQL_CREATE = listOf<String>(
LIST, ITEM, CATEGORY, CATEGORY_NAME, PRODUCT, PRODUCT_NAME
)
const val INSERT_CATEGORY_TEMPLATE =
"INSERT INTO Category (id, resource_icon_name) VALUES (%d, '%s')"
const val INSERT_CATEGORY_NAME_TEMPLATE =
"INSERT INTO CategoryName " +
"(name, locale, category_id) " +
"VALUES ('%s', '%s', %d)"
const val INSERT_PRODUCT_TEMPLATE =
"INSERT INTO Product (id, category_id) VALUES (%d, %d)"
const val INSERT_PRODUCT_NAME_TEMPLATE =
"INSERT INTO ProductName (name, locale, product_id) " +
"VALUES ('%s', '%s', %d)"
const val DELETE_TEMPLATE =
"DELETE FROM %s"
}
public fun getCategories() : List<Category>{
val categoriesJson = AssetsHelper.getInstance(context).loadJSON(AssetsHelper.FILE_CATEGORIES)
val categoriesArray = JSONArray(categoriesJson)
val categories = mutableListOf<Category>()
for(i in 0 until categoriesArray.length()){
val categoryObject = categoriesArray.getJSONObject(i)
val id = categoryObject.getLong("id")
val resourceIconName = categoryObject.getString("resource_icon")
val namesArray = categoryObject.getJSONArray("names")
val category = Category(id, resourceIconName)
for(j in 0 until namesArray.length()){
val nameObject = namesArray.getJSONObject(j)
val name = nameObject.getString("name")
val locale = nameObject.getString("locale")
val categoryName = CategoryName(
locale = locale,
name = name,
categoryId = id
)
category.categoryNames.add(categoryName)
}
categories.add(category)
}
return categories
}
public fun getProducts() : List<Product>{
val productsJson = AssetsHelper.getInstance(context).loadJSON(AssetsHelper.FILE_PRODUCTS)
val productsArray = JSONArray(productsJson)
val products = mutableListOf<Product>()
for(i in 0 until productsArray.length()){
val productObject = productsArray.getJSONObject(i)
val productId = i+1L
val categoryId = productObject.getLong("category_id")
val namesArray = productObject.getJSONArray("names")
val product = Product(productId, categoryId)
for(j in 0 until namesArray.length()){
val nameObject = namesArray.getJSONObject(j)
val name = nameObject.getString("name")
val locale = nameObject.getString("locale")
val productName = ProductName(
locale = locale,
name = name,
productId = productId
)
product.productNames.add(productName)
}
products.add(product)
}
return products
}
fun initDatabase(db: SQLiteDatabase){
SQL_CREATE.forEach {
db.execSQL(it)
}
insertCategories(db)
insertProducts(db)
}
fun clearDatabase(db: SQLiteDatabase){
db.execSQL(DELETE_TEMPLATE.format(Item.TABLE_NAME))
db.execSQL(DELETE_TEMPLATE.format(ShoppingList.TABLE_NAME))
db.execSQL(DELETE_TEMPLATE.format(ProductName.TABLE_NAME))
db.execSQL(DELETE_TEMPLATE.format(Product.TABLE_NAME))
db.execSQL(DELETE_TEMPLATE.format(CategoryName.TABLE_NAME))
db.execSQL(DELETE_TEMPLATE.format(Category.TABLE_NAME))
}
private fun insertCategories(db: SQLiteDatabase){
val categories = getCategories()
categories.forEach { category ->
db.execSQL(
INSERT_CATEGORY_TEMPLATE.format(
category.id, category.resourceIconName
))
category.categoryNames.forEach { categoryName ->
db.execSQL(
INSERT_CATEGORY_NAME_TEMPLATE.format(
categoryName.name, categoryName.locale, categoryName.categoryId
))
}
}
}
private fun insertProducts(db: SQLiteDatabase){
val products = getProducts()
products.forEach { product ->
db.execSQL(
INSERT_PRODUCT_TEMPLATE.format(
product.id, product.categoryId
))
product.productNames.forEach { productName ->
db.execSQL(
INSERT_PRODUCT_NAME_TEMPLATE.format(
productName.name, productName.locale, productName.productId
))
}
}
}
}
| 0 |
Kotlin
|
0
| 3 |
0c5ffd6aaa3d31ac6ac6738abc5caafb000f0b19
| 8,007 |
ToShop
|
MIT License
|
src/main/kotlin/net/modcrafters/nebb/blocks/BlockInfoProperty.kt
|
MinecraftModDevelopmentMods
| 103,860,689 | false | null |
package net.modcrafters.nebb.blocks
import net.minecraftforge.common.property.IUnlistedProperty
import net.modcrafters.nebb.parts.BlockInfo
class BlockInfoProperty(private val propName: String) : IUnlistedProperty<BlockInfo> {
override fun isValid(value: BlockInfo?) = (value != null)
override fun getName() = this.propName
override fun getType() = BlockInfo::class.java
override fun valueToString(value: BlockInfo?) = if (value == null) "" else value.getCacheKey()
}
| 0 |
Kotlin
|
0
| 0 |
5b1544c9d88903b1c466873e357bb8fa28750145
| 487 |
Not-Enough-Building-Blocks
|
MIT License
|
r2dbc-jasync/src/main/kotlin/io/qalipsis/plugins/r2dbc/jasync/search/JasyncResultSetBatchConverter.kt
|
qalipsis
| 428,401,563 | false | null |
/*
* Copyright 2022 AERIS IT Solutions GmbH
*
* 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.qalipsis.plugins.r2dbc.jasync.search
import io.micrometer.core.instrument.Counter
import io.qalipsis.api.context.StepOutput
import io.qalipsis.api.context.StepStartStopContext
import io.qalipsis.api.events.EventsLogger
import io.qalipsis.api.lang.tryAndLogOrNull
import io.qalipsis.api.logging.LoggerHelper.logger
import io.qalipsis.api.meters.CampaignMeterRegistry
import io.qalipsis.plugins.r2dbc.jasync.converters.JasyncResultSetConverter
import io.qalipsis.plugins.r2dbc.jasync.converters.ResultValuesConverter
import java.util.concurrent.atomic.AtomicLong
/**
* Implementation of [JasyncResultSetConverter], to convert the whole result set into a unique record.
*
* @author Fiodar Hmyza
*/
internal class JasyncResultSetBatchConverter<I>(
private val resultValuesConverter: ResultValuesConverter,
private val meterRegistry: CampaignMeterRegistry?,
private val eventsLogger: EventsLogger?
) : JasyncResultSetConverter<ResultSetWrapper, JasyncSearchBatchResults<I, *>, I> {
private val eventPrefix: String = "r2dbc.jasync.search"
private val meterPrefix: String = "r2dbc-jasync-search"
private var recordsCounter: Counter? = null
private lateinit var eventTags: Map<String, String>
override fun start(context: StepStartStopContext) {
meterRegistry?.apply {
val tags = context.toMetersTags()
recordsCounter = counter("$meterPrefix-records", tags)
}
eventTags = context.toEventTags()
}
override fun stop(context: StepStartStopContext) {
meterRegistry?.apply {
remove(recordsCounter!!)
recordsCounter = null
}
}
override suspend fun supply(
offset: AtomicLong,
value: ResultSetWrapper,
input: I,
output: StepOutput<JasyncSearchBatchResults<I, *>>
) {
eventsLogger?.info("${eventPrefix}.records", value.resultSet.size, tags = eventTags)
recordsCounter?.increment(value.resultSet.size.toDouble())
val jasyncSearchResultsList: List<JasyncSearchRecord<Map<String, Any?>>> = value.resultSet.map{ row ->
JasyncSearchRecord(
offset.getAndIncrement(),
value.resultSet.columnNames().map { column ->
column to resultValuesConverter.process(row[column])
}.toMap()
)
}
val jasyncSearchMeters = JasyncSearchMeters(
recordsCounter = value.resultSet.size,
timeToResponse = value.timeToResponse
)
tryAndLogOrNull(log) {
output.send(
JasyncSearchBatchResults (
input = input,
jasyncSearchResultsList,
jasyncSearchMeters
)
)
}
}
companion object {
@JvmStatic
private val log = logger()
}
}
| 0 |
Kotlin
|
0
| 0 |
a5104beb00df4691240e97d9c67b27fd999a3a1f
| 3,499 |
qalipsis-plugin-r2dbc-jasync
|
Apache License 2.0
|
compose/snippets/src/main/java/com/example/compose/snippets/landing/LandingScreen.kt
|
android
| 138,043,025 | false |
{"Kotlin": 1093210, "Java": 5240}
|
/*
* Copyright 2023 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.example.compose.snippets.landing
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.heightIn
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.ListItem
import androidx.compose.material3.Scaffold
import androidx.compose.material3.Text
import androidx.compose.material3.TopAppBar
import androidx.compose.runtime.Composable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.unit.dp
import com.example.compose.snippets.navigation.Destination
@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun LandingScreen(
navigate: (Destination) -> Unit
) {
Scaffold(
topBar = {
TopAppBar(title = {
Text(text = "Android snippets",)
})
}
) { padding ->
NavigationItems(modifier = Modifier.padding(padding)) { navigate(it) }
}
}
@Composable
fun NavigationItems(
modifier: Modifier = Modifier,
navigate: (Destination) -> Unit
) {
LazyColumn(
modifier = modifier
.fillMaxSize(),
verticalArrangement = Arrangement.spacedBy(8.dp),
horizontalAlignment = Alignment.CenterHorizontally,
) {
items(Destination.entries) { destination ->
NavigationItem(destination) {
navigate(
destination
)
}
}
}
}
@Composable
fun NavigationItem(destination: Destination, onClick: () -> Unit) {
ListItem(
headlineContent = {
Text(destination.title)
},
modifier = Modifier
.heightIn(min = 48.dp)
.clickable {
onClick()
}
)
}
| 14 |
Kotlin
|
169
| 666 |
514653c318c747c557f70e32aad2cc7051d44115
| 2,624 |
snippets
|
Apache License 2.0
|
components/proxy/src/test/kotlin/com/hotels/styx/routing/config/BuiltinsTest.kt
|
ExpediaGroup
| 106,841,635 | false | null |
/*
Copyright (C) 2013-2021 Expedia Inc.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package com.hotels.styx.routing.config
import com.fasterxml.jackson.databind.JsonNode
import com.hotels.styx.api.Eventual
import com.hotels.styx.api.HttpRequest.get
import com.hotels.styx.api.HttpResponse.response
import com.hotels.styx.api.HttpResponseStatus.OK
import com.hotels.styx.api.LiveHttpResponse
import com.hotels.styx.api.extension.service.spi.StyxService
import com.hotels.styx.routing.RoutingObject
import com.hotels.styx.RoutingObjectFactoryContext
import com.hotels.styx.routing.RoutingObjectRecord
import com.hotels.styx.routing.db.StyxObjectStore
import com.hotels.styx.ProviderObjectRecord
import com.hotels.styx.requestContext
import com.hotels.styx.routing.handlers.RouteRefLookup
import com.hotels.styx.serviceproviders.ServiceProviderFactory
import io.kotlintest.matchers.types.shouldBeInstanceOf
import io.kotlintest.matchers.withClue
import io.kotlintest.shouldBe
import io.kotlintest.shouldThrow
import io.kotlintest.specs.StringSpec
import io.mockk.every
import io.mockk.mockk
import io.mockk.verify
import reactor.core.publisher.toMono
import java.util.Optional
class BuiltinsTest : StringSpec({
val mockHandler = mockk<RoutingObject> {
every { handle(any(), any()) } returns Eventual.of(LiveHttpResponse.response(OK).build())
}
val routeObjectStore = mockk<StyxObjectStore<RoutingObjectRecord>>()
every { routeObjectStore.get("aHandler") } returns Optional.of(RoutingObjectRecord.create("type", setOf(), mockk(), mockHandler))
"Builds a new handler as per StyxObjectDefinition" {
val routeDef = StyxObjectDefinition("handler-def", "SomeRoutingObject", mockk())
val handlerFactory = httpHandlerFactory(mockHandler)
val context = RoutingObjectFactoryContext(objectFactories = mapOf("SomeRoutingObject" to handlerFactory))
withClue("Should create a routing object handler") {
val handler = Builtins.build(listOf("parents"), context.get(), routeDef)
(handler != null).shouldBe(true)
}
verify {
handlerFactory.build(listOf("parents"), any(), routeDef)
}
}
"Doesn't accept unregistered types" {
val config = StyxObjectDefinition("foo", "ConfigType", mockk())
val context = RoutingObjectFactoryContext(objectStore = routeObjectStore)
val e = shouldThrow<IllegalArgumentException> {
Builtins.build(listOf(), context.get(), config)
}
e.message.shouldBe("Unknown handler type 'ConfigType'")
}
"Returns handler from a configuration reference" {
val routeDb = mapOf("aHandler" to RoutingObject { request, context -> Eventual.of(response(OK).build().stream()) })
val context = RoutingObjectFactoryContext(routeRefLookup = RouteRefLookup { ref -> routeDb[ref.name()] })
val handler = Builtins.build(listOf(), context.get(), StyxObjectReference("aHandler"))
handler.handle(get("/").build().stream(), requestContext())
.toMono()
.block()!!
.status() shouldBe (OK)
}
"Looks up handler for every request" {
val referenceLookup = mockk<RouteRefLookup>()
every { referenceLookup.apply(StyxObjectReference("aHandler")) } returns RoutingObject { request, context -> Eventual.of(response(OK).build().stream()) }
val context = RoutingObjectFactoryContext(routeRefLookup = referenceLookup)
val handler = Builtins.build(listOf(), context.get(), StyxObjectReference("aHandler"))
handler.handle(get("/").build().stream(), requestContext()).toMono().block()
handler.handle(get("/").build().stream(), requestContext()).toMono().block()
handler.handle(get("/").build().stream(), requestContext()).toMono().block()
handler.handle(get("/").build().stream(), requestContext()).toMono().block()
verify(exactly = 4) {
referenceLookup.apply(StyxObjectReference("aHandler"))
}
}
"ServiceProvider factory delegates to appropriate service provider factory method" {
val factory = mockk<ServiceProviderFactory> {
every { create(any(), any(), any(), any()) } returns mockk()
}
val context = RoutingObjectFactoryContext().get()
val serviceConfig = mockk<JsonNode>()
val serviceDb = mockk<StyxObjectStore<ProviderObjectRecord>>()
Builtins.build(
"healthCheckMonitor",
StyxObjectDefinition("healthCheckMonitor", "HealthCheckMonitor", serviceConfig),
serviceDb,
mapOf("HealthCheckMonitor" to factory),
context
)
verify { factory.create("healthCheckMonitor", context, serviceConfig, serviceDb) }
}
"ServiceProvider factory throws an exception for unknown service provider factory name" {
shouldThrow<java.lang.IllegalArgumentException> {
Builtins.build(
"healthCheckMonitor",
StyxObjectDefinition("healthMonitor", "ABC", mockk()),
mockk(),
mapOf(),
RoutingObjectFactoryContext().get())
.shouldBeInstanceOf<StyxService>()
}.message shouldBe "Unknown service provider type 'ABC' for 'healthMonitor' provider"
}
})
fun httpHandlerFactory(handler: RoutingObject): RoutingObjectFactory {
val factory: RoutingObjectFactory = mockk()
every {
factory.build(any(), any(), any())
} returns handler
return factory
}
| 5 | null |
81
| 253 |
ce98188c60a9b8fcf70314451bd28401ea294a4f
| 6,118 |
styx
|
Apache License 2.0
|
hybid.demo/src/main/java/net/pubnative/lite/demo/ui/fragments/signaldata/SignalDataFragment.kt
|
pubnative
| 315,887,000 | false |
{"Gemfile.lock": 1, "Gradle": 23, "Java Properties": 2, "Shell": 1, "Text": 1, "Ignore List": 22, "Batchfile": 1, "Markdown": 2, "Ruby": 2, "INI": 19, "Proguard": 14, "XML": 205, "Java": 543, "JSON": 2, "Kotlin": 236, "HTML": 2, "SVG": 1, "JavaScript": 3}
|
package net.pubnative.lite.demo.ui.fragments.signaldata
import android.os.Bundle
import android.text.TextUtils
import android.view.View
import android.widget.*
import androidx.fragment.app.Fragment
import androidx.recyclerview.widget.DefaultItemAnimator
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.google.android.material.button.MaterialButton
import net.pubnative.lite.demo.R
import net.pubnative.lite.demo.ui.adapters.SignalDataAdapter
import net.pubnative.lite.demo.util.ClipboardUtils
import net.pubnative.lite.sdk.interstitial.HyBidInterstitialAd
import net.pubnative.lite.sdk.rewarded.HyBidRewardedAd
import net.pubnative.lite.sdk.utils.Logger
class SignalDataFragment : Fragment(R.layout.fragment_signal_data) {
private val TAG = SignalDataFragment::class.java.simpleName
private lateinit var signalDataInput: EditText
private lateinit var adSizeGroup: RadioGroup
private lateinit var signalDataList: RecyclerView
private lateinit var loadButton: MaterialButton
private lateinit var showButton: MaterialButton
private val adapter = SignalDataAdapter()
private var selectedSize: Int = R.id.radio_size_banner
private var interstitial: HyBidInterstitialAd? = null
private var rewarded: HyBidRewardedAd? = null
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
signalDataInput = view.findViewById(R.id.input_signal_data)
adSizeGroup = view.findViewById(R.id.group_ad_size)
signalDataList = view.findViewById(R.id.list_signal_data)
loadButton = view.findViewById(R.id.button_load)
showButton = view.findViewById(R.id.button_show)
view.findViewById<ImageButton>(R.id.button_paste_clipboard).setOnClickListener {
pasteFromClipboard()
}
loadButton.setOnClickListener {
loadSignalData()
}
showButton.setOnClickListener {
when (selectedSize) {
R.id.radio_size_interstitial -> {
interstitial?.show()
}
R.id.radio_size_rewarded -> {
rewarded?.show()
}
}
}
adSizeGroup.setOnCheckedChangeListener { _, checkedId ->
selectedSize = checkedId
updateVisibility()
}
val linearLayoutManager = object : LinearLayoutManager(activity, RecyclerView.VERTICAL, false) {
override fun canScrollVertically() = false
}
signalDataList.layoutManager = linearLayoutManager
signalDataList.itemAnimator = DefaultItemAnimator()
signalDataList.adapter = adapter
}
override fun onDestroy() {
interstitial?.destroy()
rewarded?.destroy()
super.onDestroy()
}
private fun updateVisibility() {
if (selectedSize == R.id.radio_size_banner
|| selectedSize == R.id.radio_size_medium
|| selectedSize == R.id.radio_size_leaderboard
|| selectedSize == R.id.radio_size_native
) {
signalDataList.visibility = View.VISIBLE
showButton.visibility = View.GONE
showButton.isEnabled = false
} else {
signalDataList.visibility = View.GONE
showButton.visibility = View.VISIBLE
showButton.isEnabled = false
}
}
private fun pasteFromClipboard() {
val clipboardText = ClipboardUtils.copyFromClipboard(requireActivity())
if (!TextUtils.isEmpty(clipboardText)) {
signalDataInput.setText(clipboardText)
}
}
private fun loadSignalData() {
showButton.isEnabled = false
var signalData = signalDataInput.text.toString()
if (TextUtils.isEmpty(signalData)) {
Toast.makeText(activity, "Please input some signal data", Toast.LENGTH_SHORT).show()
} else {
when (selectedSize) {
R.id.radio_size_interstitial -> {
loadInterstitial(signalData)
}
R.id.radio_size_rewarded -> {
loadRewarded(signalData)
}
else -> {
adapter.refreshWithSignalData(signalData, selectedSize)
}
}
}
}
private fun loadInterstitial(signalData: String) {
interstitial?.destroy()
val interstitialListener = object : HyBidInterstitialAd.Listener {
override fun onInterstitialLoaded() {
Logger.d(TAG, "onInterstitialLoaded")
showButton.isEnabled = true
}
override fun onInterstitialLoadFailed(error: Throwable?) {
Logger.e(TAG, "onInterstitialLoadFailed", error)
Toast.makeText(requireContext(), error?.message, Toast.LENGTH_LONG).show()
showButton.isEnabled = false
}
override fun onInterstitialImpression() {
Logger.d(TAG, "onInterstitialImpression")
}
override fun onInterstitialClick() {
Logger.d(TAG, "onInterstitialClick")
}
override fun onInterstitialDismissed() {
Logger.d(TAG, "onInterstitialDismissed")
showButton.isEnabled = false
}
}
interstitial = HyBidInterstitialAd(requireActivity(), interstitialListener)
interstitial?.prepareAd(signalData)
}
private fun loadRewarded(signalData: String) {
rewarded?.destroy()
val rewardedListener = object : HyBidRewardedAd.Listener {
override fun onRewardedLoaded() {
Logger.d(TAG, "onRewardedLoaded")
showButton.isEnabled = true
}
override fun onRewardedLoadFailed(error: Throwable?) {
Logger.d(TAG, "onRewardedLoadFailed")
Toast.makeText(requireContext(), error?.message, Toast.LENGTH_LONG).show()
showButton.isEnabled = false
}
override fun onRewardedOpened() {
Logger.d(TAG, "onRewardedOpened")
}
override fun onRewardedClosed() {
Logger.d(TAG, "onRewardedClosed")
showButton.isEnabled = false
}
override fun onRewardedClick() {
Logger.d(TAG, "onRewardedClick")
}
override fun onReward() {
Logger.d(TAG, "onReward")
}
}
rewarded = HyBidRewardedAd(requireActivity(), rewardedListener)
rewarded?.prepareAd(signalData)
}
}
| 1 |
Java
|
1
| 7 |
cb0e1e1724a538b05863195f850491a7457db6da
| 6,765 |
pubnative-hybid-android-sdk
|
MIT License
|
src/compile/StatementParser.kt
|
grokthis
| 291,357,012 | false | null |
package com.grokthis.ucisc.compile
import java.lang.IllegalArgumentException
class StatementParser: Parser {
private val dstRegex =
Regex("(?<arg>&?[a-zA-Z0-9\\-_/.]+) *(?<inc>push)? *(?<src><.+)")
override fun parse(line: String, scope: Scope): Scope {
val match = dstRegex.matchEntire(line)
?: throw IllegalArgumentException(
"Expecting valid destination: [&]<register>[.<variable>][/<offset>] [push] [source]"
)
val argString = match.groups["arg"]!!.value
val argument = Argument.parse(argString, scope)
if (argument.addr && argument.offset != 0) {
throw IllegalArgumentException(
"Offset must be zero for address destinations"
)
} else if (!argument.addr && argument.offset !in 0..15) {
throw IllegalArgumentException(
"Offset out of bounds: ${argument.offset} - it must be in 0..15"
)
}
val isInc = match.groups["inc"] != null
val source: Source = Source.parse(match.groups["src"]!!.value, scope)
val statement = Statement(argument, isInc, source)
scope.addWords(statement)
// Changing the PC destroys stack counting, this has to be taken into account
// by the programmer, so we ignore stack changes made when the PC is the target
if (statement.argument.register != Register.PC) {
if (statement.push) {
scope.updateDelta(statement.argument.register, 1)
} else if (statement.source.pop) {
scope.updateDelta(
statement.source.argument.register,
-1 * (statement.source.argument.offset + 1)
)
}
}
return scope
}
override fun matches(line: String): Boolean {
return line.matches(dstRegex)
}
}
| 0 |
Kotlin
|
0
| 1 |
85e94bf157169bd86cb128b38da8d6dda07be4f2
| 1,901 |
ucisc-kotlin
|
MIT License
|
app/src/main/java/com/dlutrix/themoviewikicompose/di/PersistenceModule.kt
|
DLutrix
| 404,992,763 | false | null |
package com.dlutrix.themoviewikicompose.di
import android.content.Context
import androidx.room.Room
import com.dlutrix.themoviewikicompose.data.source.persistence.MovieDatabase
import dagger.Module
import dagger.Provides
import dagger.hilt.InstallIn
import dagger.hilt.android.qualifiers.ApplicationContext
import dagger.hilt.components.SingletonComponent
import javax.inject.Singleton
@Module
@InstallIn(SingletonComponent::class)
object PersistenceModule {
@Provides
@Singleton
fun provideMovieDatabase(
@ApplicationContext appContext: Context
) = Room.databaseBuilder(appContext, MovieDatabase::class.java, "movie.db").build()
}
| 0 |
Kotlin
|
0
| 2 |
8def6b0ed2b38305cce578fcd9d8afdb42b759ee
| 658 |
The-Movie-Wiki-Compose
|
MIT License
|
app/src/main/java/com/example/facedecorater/camera/AugmentFace.kt
|
kbh97102
| 292,490,800 | false | null |
package com.example.facedecorater.camera
import android.graphics.Bitmap
import android.os.Bundle
import android.os.Handler
import android.os.HandlerThread
import android.view.PixelCopy
import androidx.appcompat.app.AppCompatActivity
import com.example.facedecorater.R
import com.example.facedecorater.feature.FaceArFragment
import com.google.ar.core.AugmentedFace
import com.google.ar.core.TrackingState
import com.google.ar.sceneform.ArSceneView
import com.google.ar.sceneform.FrameTime
import com.google.ar.sceneform.rendering.ModelRenderable
import com.google.ar.sceneform.rendering.Renderable
import com.google.ar.sceneform.ux.AugmentedFaceNode
import kotlinx.android.synthetic.main.camera_ar.*
import java.io.File
import java.io.FileOutputStream
import java.io.IOException
import kotlin.collections.HashMap
class AugmentFace : AppCompatActivity() {
private var arFragment: FaceArFragment? = null
private var faceRegionsRenderable: ModelRenderable? = null
private var modelList: HashMap<String, ModelRenderable> = HashMap()
private var changeModel = false
private var currentType : String = "black"
private val faceNodeMap = HashMap<AugmentedFace, AugmentedFaceNode>()
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.camera_ar)
arFragment = face_fragment as FaceArFragment
buildRenderable(R.raw.fox_face, "fox")
buildRenderable(R.raw.yellow_sunglasses, "yellow")
buildRenderable(R.raw.sunglasses, "black")
setArcore()
camera_ar_takeButton.setOnClickListener {
takeShot()
}
camera_ar_stikcer_3.setOnClickListener {
faceRegionsRenderable = modelList["fox"]
changeModel = true
}
camera_ar_sticker_2.setOnClickListener {
if(currentType == "yellow"){
faceRegionsRenderable = modelList["black"]
changeModel = true
currentType = "black"
camera_ar_sticker_2.setImageResource(R.drawable.yellow_glasses_button)
}else{
faceRegionsRenderable = modelList["yellow"]
changeModel = true
currentType = "yellow"
camera_ar_sticker_2.setImageResource(R.drawable.black_glasses_button)
}
}
}
private fun takeShot() {
val photoFile = File(getOutputDirectory(), "test.jpeg")
photoFile.createNewFile()
val bitmap = Bitmap.createBitmap(
arFragment!!.arSceneView.width,
arFragment!!.arSceneView.height,
Bitmap.Config.ARGB_8888
)
val handlerThread = HandlerThread("Save Image")
handlerThread.start()
PixelCopy.request(arFragment!!.arSceneView, bitmap, { copyResult ->
if (copyResult == PixelCopy.SUCCESS) {
try {
val fileOutputStream = FileOutputStream(photoFile)
bitmap.compress(Bitmap.CompressFormat.JPEG, 90, fileOutputStream)
fileOutputStream.apply {
flush()
close()
}
} catch (e: IOException) {
return@request
}
}
handlerThread.quitSafely()
}, Handler(handlerThread.looper))
}
private fun getOutputDirectory(): File {
val mediaDir = externalMediaDirs.firstOrNull()?.let {
File(it, resources.getString(R.string.app_name)).apply { mkdirs() }
}
return if (mediaDir != null && mediaDir.exists())
mediaDir else filesDir
}
private fun setArcore() {
val sceneView: ArSceneView = arFragment!!.arSceneView
sceneView.cameraStreamRenderPriority = Renderable.RENDER_PRIORITY_FIRST
val scene = sceneView.scene
scene.addOnUpdateListener { frameTime: FrameTime? ->
if (faceRegionsRenderable == null) {
return@addOnUpdateListener
}
val faceList =
sceneView.session!!.getAllTrackables(
AugmentedFace::class.java
)
for (face in faceList) {
if (!faceNodeMap.containsKey(face)) {
val faceNode = AugmentedFaceNode(face)
faceNode.setParent(scene)
faceNode.faceRegionsRenderable = faceRegionsRenderable
faceNodeMap[face] = faceNode
}
if (changeModel) {
faceNodeMap.getValue(face).faceRegionsRenderable = faceRegionsRenderable
changeModel = false
}
}
val iter: MutableIterator<Map.Entry<AugmentedFace, AugmentedFaceNode>> =
faceNodeMap.entries.iterator()
while (iter.hasNext()) {
val entry =
iter.next()
val face = entry.key
if (face.trackingState == TrackingState.STOPPED) {
val faceNode = entry.value
faceNode.setParent(null)
iter.remove()
}
}
}
}
private fun buildRenderable(modelSource: Int, type : String) {
ModelRenderable.builder()
.setSource(this, modelSource)
.build()
.thenAccept { modelRenderable: ModelRenderable ->
modelRenderable.isShadowCaster = false
modelRenderable.isShadowReceiver = false
when(type){
"fox" -> modelList["fox"] = modelRenderable
"yellow" -> modelList["yellow"] = modelRenderable
"black" -> {
modelList["black"] = modelRenderable
faceRegionsRenderable = modelRenderable
}
}
}
}
}
| 0 |
Kotlin
|
0
| 1 |
4d046981785f7c9402e949aae66b1d53beab213e
| 5,999 |
FaceDecorater_MoblileSystemProject
|
Apache License 2.0
|
base/src/main/java/org/kin/stellarfork/xdr/Operation.kt
|
gmpassos
| 364,807,652 | false |
{"Gradle": 5, "Markdown": 4, "Java Properties": 2, "Shell": 2, "Ignore List": 4, "Batchfile": 2, "Kotlin": 428, "Java": 24, "INI": 2, "Protocol Buffer": 1, "Proguard": 1, "XML": 36}
|
// Automatically generated by xdrgen
// DO NOT EDIT or your changes may be overwritten
package org.kin.stellarfork.xdr
import org.kin.stellarfork.xdr.AccountID.Companion.encode
import java.io.IOException
// === xdr source ============================================================
// struct Operation
// {
// // sourceAccount is the account used to run the operation
// // if not set, the runtime defaults to "sourceAccount" specified at
// // the transaction level
// AccountID* sourceAccount;
//
// union switch (OperationType type)
// {
// case CREATE_ACCOUNT:
// CreateAccountOp createAccountOp;
// case PAYMENT:
// PaymentOp paymentOp;
// case PATH_PAYMENT:
// PathPaymentOp pathPaymentOp;
// case MANAGE_OFFER:
// ManageOfferOp manageOfferOp;
// case CREATE_PASSIVE_OFFER:
// CreatePassiveOfferOp createPassiveOfferOp;
// case SET_OPTIONS:
// SetOptionsOp setOptionsOp;
// case CHANGE_TRUST:
// ChangeTrustOp changeTrustOp;
// case ALLOW_TRUST:
// AllowTrustOp allowTrustOp;
// case ACCOUNT_MERGE:
// AccountID destination;
// case INFLATION:
// void;
// case MANAGE_DATA:
// ManageDataOp manageDataOp;
// }
// body;
// };
// ===========================================================================
class Operation {
var sourceAccount: AccountID? = null
var body: OperationBody? = null
class OperationBody {
var discriminant: OperationType? = null
var createAccountOp: CreateAccountOp? = null
var paymentOp: PaymentOp? = null
var pathPaymentOp: PathPaymentOp? = null
var manageOfferOp: ManageOfferOp? = null
var createPassiveOfferOp: CreatePassiveOfferOp? = null
var setOptionsOp: SetOptionsOp? = null
var changeTrustOp: ChangeTrustOp? = null
var allowTrustOp: AllowTrustOp? = null
var destination: AccountID? = null
var manageDataOp: ManageDataOp? = null
companion object {
@JvmStatic
@Throws(IOException::class)
fun encode(
stream: XdrDataOutputStream,
encodedOperationBody: OperationBody?
) {
stream.writeInt(encodedOperationBody!!.discriminant!!.value)
when (encodedOperationBody.discriminant) {
OperationType.CREATE_ACCOUNT -> CreateAccountOp.encode(
stream,
encodedOperationBody.createAccountOp!!
)
OperationType.PAYMENT -> PaymentOp.encode(
stream,
encodedOperationBody.paymentOp!!
)
OperationType.PATH_PAYMENT -> PathPaymentOp.encode(
stream,
encodedOperationBody.pathPaymentOp!!
)
OperationType.MANAGE_OFFER -> ManageOfferOp.encode(
stream,
encodedOperationBody.manageOfferOp!!
)
OperationType.CREATE_PASSIVE_OFFER -> CreatePassiveOfferOp.encode(
stream,
encodedOperationBody.createPassiveOfferOp!!
)
OperationType.SET_OPTIONS -> SetOptionsOp.encode(
stream,
encodedOperationBody.setOptionsOp!!
)
OperationType.CHANGE_TRUST -> ChangeTrustOp.encode(
stream,
encodedOperationBody.changeTrustOp!!
)
OperationType.ALLOW_TRUST -> AllowTrustOp.encode(
stream,
encodedOperationBody.allowTrustOp!!
)
OperationType.ACCOUNT_MERGE -> encode(
stream,
encodedOperationBody.destination!!
)
OperationType.INFLATION -> {
}
OperationType.MANAGE_DATA -> ManageDataOp.encode(
stream,
encodedOperationBody.manageDataOp!!
)
}
}
@JvmStatic
@Throws(IOException::class)
fun decode(stream: XdrDataInputStream): OperationBody {
val decodedOperationBody = OperationBody()
val discriminant = OperationType.decode(stream)
decodedOperationBody.discriminant = discriminant
when (decodedOperationBody.discriminant) {
OperationType.CREATE_ACCOUNT ->
decodedOperationBody.createAccountOp = CreateAccountOp.decode(stream)
OperationType.PAYMENT ->
decodedOperationBody.paymentOp = PaymentOp.decode(stream)
OperationType.PATH_PAYMENT ->
decodedOperationBody.pathPaymentOp = PathPaymentOp.decode(stream)
OperationType.MANAGE_OFFER ->
decodedOperationBody.manageOfferOp = ManageOfferOp.decode(stream)
OperationType.CREATE_PASSIVE_OFFER ->
decodedOperationBody.createPassiveOfferOp =
CreatePassiveOfferOp.decode(stream)
OperationType.SET_OPTIONS ->
decodedOperationBody.setOptionsOp = SetOptionsOp.decode(stream)
OperationType.CHANGE_TRUST ->
decodedOperationBody.changeTrustOp = ChangeTrustOp.decode(stream)
OperationType.ALLOW_TRUST ->
decodedOperationBody.allowTrustOp = AllowTrustOp.decode(stream)
OperationType.ACCOUNT_MERGE ->
decodedOperationBody.destination = AccountID.decode(stream)
OperationType.INFLATION -> {
}
OperationType.MANAGE_DATA ->
decodedOperationBody.manageDataOp = ManageDataOp.decode(stream)
}
return decodedOperationBody
}
}
}
companion object {
@JvmStatic
@Throws(IOException::class)
fun encode(
stream: XdrDataOutputStream,
encodedOperation: Operation
) {
if (encodedOperation.sourceAccount != null) {
stream.writeInt(1)
encode(stream, encodedOperation.sourceAccount!!)
} else {
stream.writeInt(0)
}
OperationBody.encode(stream, encodedOperation.body)
}
@JvmStatic
@Throws(IOException::class)
fun decode(stream: XdrDataInputStream): Operation {
val decodedOperation = Operation()
val sourceAccountPresent = stream.readInt()
if (sourceAccountPresent != 0) {
decodedOperation.sourceAccount = AccountID.decode(stream)
}
decodedOperation.body = OperationBody.decode(stream)
return decodedOperation
}
}
}
| 0 |
Kotlin
|
0
| 0 |
6c0a2cd067772d234b8ceeae170e9ff1feb06157
| 7,334 |
kin-core
|
MIT License
|
app/practice1/app/src/main/java/com/example/practice1/Repo.kt
|
PKTOSE
| 560,406,689 | false | null |
package com.example.practice1
import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import com.google.firebase.database.DataSnapshot
import com.google.firebase.database.DatabaseError
import com.google.firebase.database.ValueEventListener
import com.google.firebase.database.ktx.database
import com.google.firebase.ktx.Firebase
class Repo {
fun getData(): LiveData<MutableList<DelayInfo>> {
val mutableData = MutableLiveData<MutableList<DelayInfo>>()
val database = Firebase.database
val myRef = database.getReference("DelayInfo")
myRef.addValueEventListener(object : ValueEventListener {
val listData: MutableList<DelayInfo> = mutableListOf<DelayInfo>()
override fun onDataChange(snapshot: DataSnapshot) {
if (snapshot.exists()){
for (userSnapshot in snapshot.children){
val getData = userSnapshot.getValue(DelayInfo::class.java)
listData.add(getData!!)
mutableData.value = listData
}
}
}
override fun onCancelled(error: DatabaseError) {
TODO("Not yet implemented")
}
})
return mutableData
}
}
| 0 |
Kotlin
|
3
| 2 |
2b3f109274ac936bfc11929756caa5de1f1d7af5
| 1,295 |
SSUbway_2022
|
MIT License
|
app/src/main/java/com/stone/templateapp/demo/socket/TCPClientActivity.kt
|
xiaqu-stone
| 141,563,896 | false |
{"Gradle": 6, "Java Properties": 2, "Text": 1, "Ignore List": 2, "Markdown": 1, "Proguard": 1, "Kotlin": 59, "XML": 39, "Java": 7, "AIDL": 3}
|
package com.stone.templateapp.demo.socket
import android.annotation.SuppressLint
import android.content.Intent
import android.os.Bundle
import android.os.Handler
import android.os.SystemClock
import android.support.v7.app.AppCompatActivity
import com.stone.templateapp.R
import kotlinx.android.synthetic.main.activity_tcpclient.*
import org.jetbrains.anko.act
import org.jetbrains.anko.doAsync
import java.io.*
import java.net.Socket
import java.text.SimpleDateFormat
import java.util.*
class TCPClientActivity : AppCompatActivity() {
companion object {
private const val MSG_RECEIVE_NEW_MSG = 1
private const val MSG_SOCKET_CONNECTED = 2
}
private var mClientSocket: Socket? = null
private var mPrintWriter: PrintWriter? = null
@SuppressLint("SetTextI18n")
private val mHandler = Handler(Handler.Callback {
when (it.what) {
MSG_RECEIVE_NEW_MSG -> tvMsgContainer.text = tvMsgContainer.text.toString() + it.obj
MSG_SOCKET_CONNECTED -> btnSend.isEnabled = true
}
true
})
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_tcpclient)
setTitle(R.string.title_socket_ipc)
btnSend.setOnClickListener { clickBtnSend() }
startService(Intent(act, TCPServerService::class.java))
Thread(Runnable { connectTCPServer() }).start()
// btnSend.postDelayed({ }, 3000)//延迟连接,等待服务端启动完成
}
private fun connectTCPServer() {
var socket: Socket? = null
while (socket == null) {
//通过循环来处理服务端启动延迟的问题,当然这里的循环也是基于处理失败重连的机制上的
//如果不做try catch 处理,当连接失败时会抛错
try {
socket = Socket("localhost", 8688)
mClientSocket = socket
mPrintWriter = PrintWriter(BufferedWriter(OutputStreamWriter(socket.getOutputStream())), true)
mHandler.sendEmptyMessage(MSG_SOCKET_CONNECTED)
println("connect server success")
} catch (e: Exception) {
SystemClock.sleep(1000)
println("connect server failed, retry...")
}
}
val br = BufferedReader(InputStreamReader(socket.getInputStream()))
while (!isFinishing) {
var msg: String? = null
try {
msg = br.readLine()
} catch (e: Exception) {
e.printStackTrace()
}
if (msg != null) {
val time = formatDateTime(System.currentTimeMillis())
val showedMsg = "server $time: $msg\n"
mHandler.obtainMessage(MSG_RECEIVE_NEW_MSG, showedMsg).sendToTarget()
}
}
println("quit...")
mPrintWriter?.close()
br.close()
socket.close()
}
private fun formatDateTime(time: Long): String {
return SimpleDateFormat("(HH:mm:ss)", Locale.CHINA).format(Date(time))
}
@SuppressLint("SetTextI18n")
private fun clickBtnSend() {
val msg: String? = inputMsg.text.toString()
if (!msg.isNullOrEmpty()) {
doAsync { mPrintWriter?.println(msg) }
inputMsg.setText("")
val time = formatDateTime(System.currentTimeMillis())
val showedMsg = "self $time : $msg\n"
tvMsgContainer.text = tvMsgContainer.text.toString() + showedMsg
}
}
override fun onDestroy() {
mClientSocket?.shutdownInput()
mClientSocket?.close()
mHandler.removeCallbacksAndMessages(null)
super.onDestroy()
}
}
| 0 |
Kotlin
|
0
| 0 |
c3bb65611d93aecea776adb8a2a95606b154d7f7
| 3,630 |
StoneDemo
|
Apache License 2.0
|
app/src/main/java/dev/techpolis/studservice/repositories/service/remote/RemoteServicesRepoImpl.kt
|
StudServices
| 353,117,513 | false | null |
package dev.techpolis.studservice.repositories.service.remote
import android.util.Log
import com.google.firebase.database.ktx.database
import com.google.firebase.firestore.ktx.firestore
import com.google.firebase.ktx.Firebase
import dev.techpolis.studservice.data.entities.ServiceEntity
import dev.techpolis.studservice.data.model.ServiceTypeEnum
import kotlinx.coroutines.ExperimentalCoroutinesApi
import kotlinx.coroutines.suspendCancellableCoroutine
import javax.inject.Inject
import javax.inject.Singleton
import kotlin.coroutines.resumeWithException
@ExperimentalCoroutinesApi
@Singleton
class RemoteServicesRepoImpl @Inject constructor() : RemoteServicesRepo {
private val db = Firebase.firestore
private val database = Firebase.database.reference
private val serviceCollection = db.collection(Collections.SERVICES.collectionName)
companion object {
const val TAG = "RemoteServicesRepoImpl"
}
override suspend fun readServices(limit: Int, offset: Int): List<ServiceEntity> =
emptyList()
// suspendCancellableCoroutine { coroutine->
// database.child(Collections.SERVICES.collectionName).get()
// .addOnSuccessListener {
// coroutine.resume(((it.value as HashMap<String, ServiceEntity>).values.toList()), null)
// }
// }
override suspend fun readServicesByType(
type: ServiceTypeEnum,
limit: Int,
offset: Int
): List<ServiceEntity> = emptyList()
//
// suspendCancellableCoroutine { coroutine->
// database.child(Collections.SERVICES.collectionName).get()
// .addOnSuccessListener {services ->
// coroutine.resume(((services.value as HashMap<String, ServiceEntity>).values.toList().filter { it.type == type }), null)
// }.addOnFailureListener {
// coroutine.resumeWithException(it)
// }
// }
override suspend fun readServicesByUser(
userId: String,
limit: Int,
offset: Int
): List<ServiceEntity> = emptyList()
override suspend fun readServicesByUserAndType(
userId: String,
type: ServiceTypeEnum,
limit: Int,
offset: Int
): List<ServiceEntity> = emptyList()
// suspendCancellableCoroutine { coroutine->
// database.child(Collections.SERVICES.collectionName).get()
// .addOnSuccessListener {services ->
// coroutine.resume((((services.value as HashMap<String, ServiceEntity>).values).toList().filter { it.type == type }), null)
//
// }
// }
override suspend fun addServices(services: List<ServiceEntity>) {
services.forEach { addService(it) }
}
override suspend fun addService(service: ServiceEntity) {
serviceCollection.document(service.id.toString())
.set(service)
.addOnSuccessListener { documentReference ->
Log.d(TAG, "DocumentSnapshot added: $documentReference")
}
.addOnFailureListener { e ->
Log.w(TAG, "Error adding document", e)
}
val firebaseId = database.push().key
service.firebaseId = firebaseId
database.child(Collections.SERVICES.collectionName).child(firebaseId!!).setValue(service)
}
override suspend fun deleteService(service: ServiceEntity) {
TODO("Not yet implemented")
}
override suspend fun updateService(newService: ServiceEntity) {
TODO("Not yet implemented")
}
// private fun ServiceEntity.toMap(): Map<String, Any> = mapOf(
// "id" to id,
// "title" to title,
// "ownerId" to ownerId,
// "description" to description,
// "price" to price,
// "tagList" to tagList,
// "type" to type.ordinal,
// "deadlineTime" to deadlineTime,
// )
//
// private fun Map<String, Any>.toModel(): ServiceEntity = ServiceEntity(
// id = this["id"] as String,
// title = this["title"] as,
// ownerId = this["ownerId"] as,
// description = this["description"] as,
// price = this["price"] as,
// tagList = this["tagList"] as,
// type = this["type"] as,
// deadlineTime = this["deadlineTime"] as
// )
}
| 0 |
Kotlin
|
0
| 0 |
a844a9ac31fa02245237a7af68a66b2451dac7cd
| 4,328 |
StudServices-Android
|
MIT License
|
libraries/tools/kotlin-gradle-plugin-integration-tests/src/test/kotlin/org/jetbrains/kotlin/gradle/FakeTestIT.kt
|
JetBrains
| 3,432,266 | false |
{"Kotlin": 79248651, "Java": 6821839, "Swift": 4063506, "C": 2609288, "C++": 1969323, "Objective-C++": 171723, "JavaScript": 138329, "Python": 59488, "Shell": 32251, "TypeScript": 22800, "Objective-C": 22132, "Lex": 21352, "Groovy": 17400, "Batchfile": 11695, "CSS": 11368, "Ruby": 10470, "Dockerfile": 9857, "EJS": 5241, "HTML": 4877, "CMake": 4448, "Pascal": 1698, "FreeMarker": 1393, "Roff": 725, "Scala": 80}
|
/*
* Copyright 2010-2022 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.gradle
import org.junit.Test
import kotlin.test.assertTrue
/**
* Exists so job on CI will not fail with "no tests found" error.
*/
class FakeTestIT : BaseGradleIT() {
@Test
fun name() {
assertTrue(1 == 1)
}
}
| 182 |
Kotlin
|
5646
| 48,182 |
bc1ddd8205f6107c7aec87a9fb3bd7713e68902d
| 471 |
kotlin
|
Apache License 2.0
|
src/main/kotlin/fr/alexandreroman/demos/feelings/local/LocalFeelingService.kt
|
alexandreroman
| 154,897,102 | false | null |
/*
* Copyright (c) 2018 Pivotal Software, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package fr.alexandreroman.demos.feelings.local
import fr.alexandreroman.demos.feelings.services.Feeling
import fr.alexandreroman.demos.feelings.services.FeelingService
import org.springframework.context.annotation.Profile
import org.springframework.stereotype.Service
import java.util.*
/**
* Local [FeelingService] implementation, mainly used in development mode
* when no Azure Text Analytics endpoint is available.
*/
@Profile("!cloud")
@Service
class LocalFeelingService : FeelingService {
private val random = Random()
override fun getFeeling(text: String): Feeling {
val index = random.nextInt(Feeling.values().size)
return Feeling.values()[index]
}
}
| 0 |
Kotlin
|
1
| 0 |
71dbd73349b0ff1928fe861a5606f2ef793c6ab0
| 1,304 |
feelings
|
Apache License 2.0
|
src/main/java/io/github/snrostov/kotlin/react/ide/analyzer/CfgAnalyzer.kt
|
snrostov
| 126,313,212 | 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 io.github.snrostov.kotlin.react.ide.analyzer
import com.intellij.psi.PsiElement
import io.github.snrostov.kotlin.react.ide.analyzer.PropAssignments.Companion.BACK_EDGE
import io.github.snrostov.kotlin.react.ide.utils.RJsObjInterface
import io.github.snrostov.kotlin.react.ide.utils.firstCommonParent
import org.jetbrains.kotlin.cfg.pseudocode.instructions.Instruction
import org.jetbrains.kotlin.cfg.pseudocode.instructions.eval.WriteValueInstruction
import org.jetbrains.kotlin.cfg.pseudocode.instructions.special.SubroutineExitInstruction
import org.jetbrains.kotlin.idea.references.mainReference
import org.jetbrains.kotlin.idea.search.usagesSearch.descriptor
import org.jetbrains.kotlin.psi.KtBinaryExpression
import org.jetbrains.kotlin.psi.KtParameter
import org.jetbrains.kotlin.psi.KtReferenceExpression
/**
* Visits all control flow graph instructions from sink to enter.
* and collects props initialization state ([PropAssignments]).
*/
abstract class CfgAnalyzer {
val visited = mutableMapOf<Instruction, PropAssignments>()
fun getPropsAssigments(instruction: Instruction?): PropAssignments =
if (instruction == null) PropAssignments.EMPTY
else visited.getOrPut(instruction) {
// first, temporary mark this instruction for cycle cases
visited[instruction] = PropAssignments.BACK_EDGE
PropAssignmentsBuilder().also { result ->
instruction.previousInstructions.forEach { prev ->
if (!prev.dead && !(prev is SubroutineExitInstruction && prev.isError)) {
result.addBranch(getPropsAssigments(prev))
}
}
visitInstruction(result, instruction)
}.build()
}
/** Should call [propsState].[PropAssignmentsBuilder.addInitializedProp] on prop write */
abstract fun visitInstruction(propsState: PropAssignmentsBuilder, instruction: Instruction)
fun getPropValue(instruction: WriteValueInstruction): PropAssignment {
val assignment = instruction.element
if (assignment is KtBinaryExpression) {
val right = assignment.right
if (right is KtReferenceExpression) {
val target = right.mainReference.resolve()
if (target is KtParameter) {
return PropAssignment(PropValue.Parameter(target), assignment)
}
}
}
return PropAssignment(PropValue.Mixed, assignment)
}
}
/**
* State of [RJsObjInterface] properties values initialization
*
* @property byProperty Set on initialized props
* @property symbol For symbolic inequality (see [BACK_EDGE])
**/
data class PropAssignments(
val byProperty: Map<RJsObjInterface.Property, PropAssignment>,
val unknownPropsAssignments: List<PropAssignment>,
private val symbol: Any? = null
) {
fun findPropsWithOutdatedParameterTypes() =
byProperty.filter { (prop, assignment) ->
if (assignment.value is PropValue.Parameter) {
val descriptor = assignment.value.parameter.descriptor
if (descriptor != null) {
descriptor.type != prop.declaration.type
} else false
} else false
}
companion object {
val EMPTY = PropAssignments(mapOf(), listOf())
/** Temporary mark this instruction for cycle cases */
val BACK_EDGE = PropAssignments(mapOf(), listOf(), Any())
}
}
class PropAssignment(
val value: PropValue,
val commonParentPsi: PsiElement?
)
class PropAssignmentsBuilder {
private var byProperty: Map<RJsObjInterface.Property, PropAssignment>? = null
private val unknownPropsAssignments = mutableListOf<PropAssignment>()
fun addInitializedProp(property: RJsObjInterface.Property?, value: PropAssignment) {
if (property != null) {
byProperty =
if (byProperty == null) mapOf(property to value)
else byProperty!! + (property to value)
} else {
unknownPropsAssignments.add(value)
}
}
/** Intersects current set of initialized props (if any) and given [propAssignments] */
fun addBranch(propAssignments: PropAssignments) {
// todo(optimize): collection allocations
if (propAssignments != PropAssignments.BACK_EDGE) { // skip back edges (cycles)
byProperty =
if (byProperty == null) propAssignments.byProperty.toMap()
else mutableMapOf<RJsObjInterface.Property, PropAssignment>().also { result ->
val values = byProperty!!
propAssignments.byProperty.forEach { (prop, assignment) ->
val prevValue = values[prop]
if (prevValue != null) {
result[prop] = PropAssignment(
prevValue.value.intersect(assignment.value),
firstCommonParent(prevValue.commonParentPsi, assignment.commonParentPsi)
)
}
}
}
unknownPropsAssignments.addAll(propAssignments.unknownPropsAssignments)
}
}
fun build() = PropAssignments(byProperty?.toMap() ?: mapOf(), unknownPropsAssignments)
}
sealed class PropValue {
class Parameter(val parameter: KtParameter) : PropValue()
object Mixed : PropValue()
}
fun PropValue.intersect(other: PropValue): PropValue = when (this) {
is PropValue.Parameter -> when {
other is PropValue.Parameter && other.parameter == parameter -> this
else -> PropValue.Mixed
}
PropValue.Mixed -> PropValue.Mixed
}
| 0 |
Kotlin
|
1
| 5 |
86268b67ad50c2be20ffc0f7a33118e46014828d
| 6,080 |
idea-kotlin-react
|
Apache License 2.0
|
web-regresjonstest/src/test/kotlin/no/nav/su/se/bakover/web/søknad/ny/OpprettNySakMedSøknadLokalt.kt
|
navikt
| 227,366,088 | false | null |
package no.nav.su.se.bakover.web.søknad.ny
import ch.qos.logback.classic.util.ContextInitializer
import no.nav.su.se.bakover.database.DatabaseBuilder.migrateDatabase
import no.nav.su.se.bakover.database.DatabaseBuilder.newLocalDataSource
/**
* Oppretter en ny sak med en ny digital søknad i den lokale postgres-instansen (bruker de samme endepunktene som frontend).
* Kan kjøres via ./resetdb_and_create_søknad.sh
*/
fun main() {
System.setProperty(ContextInitializer.CONFIG_FILE_PROPERTY, "logback-local.xml")
val dataSource = newLocalDataSource()
migrateDatabase(dataSource)
nyDigitalSøknad(
dataSource = dataSource,
)
}
| 6 |
Kotlin
|
0
| 0 |
2ed4ed4aa002a19d14ce7dd37c27271a227668a8
| 656 |
su-se-bakover
|
MIT License
|
demo/common/src/main/kotlin/dev/alibagherifam/kavoshgar/demo/NavigationDestination.kt
|
alibagherifam
| 586,918,409 | false |
{"Kotlin": 10094}
|
package dev.alibagherifam.kavoshgar.demo
import dev.alibagherifam.kavoshgar.demo.chat.ChatNavigationArgs
sealed class NavigationDestination {
object LobbyList : NavigationDestination()
data class Chat(val args: ChatNavigationArgs) : NavigationDestination()
}
| 0 |
Kotlin
|
2
| 15 |
000659df14e8e38016907a3f1f7a193ade490b80
| 269 |
kavoshgar
|
Apache License 2.0
|
sample/src/main/kotlin/com/example/kotlin/RemoveRedundantQualifier.kt
|
hendraanggrian
| 556,969,715 | false |
{"Kotlin": 94835, "Java": 2866, "Groovy": 310}
|
package com.example.kotlin
import java.io.FileInputStream
fun read(stream: FileInputStream) {
}
| 0 |
Kotlin
|
0
| 1 |
3e4a3f4458dbf7ba3f0805b6aecdd514a580111c
| 98 |
rulebook
|
Apache License 2.0
|
services/hanke-service/src/integrationTest/kotlin/fi/hel/haitaton/hanke/geometria/HankeGeometriatServiceImplITest.kt
|
City-of-Helsinki
| 300,534,352 | false | null |
package fi.hel.haitaton.hanke.geometria
import assertk.assertAll
import assertk.assertThat
import assertk.assertions.isEqualTo
import assertk.assertions.isFalse
import assertk.assertions.isNotNull
import assertk.assertions.isNull
import assertk.assertions.isTrue
import fi.hel.haitaton.hanke.DATABASE_TIMESTAMP_FORMAT
import fi.hel.haitaton.hanke.HaitatonPostgreSQLContainer
import fi.hel.haitaton.hanke.HankeService
import fi.hel.haitaton.hanke.asJsonResource
import fi.hel.haitaton.hanke.domain.Hanke
import org.geojson.Point
import org.junit.jupiter.api.BeforeEach
import org.junit.jupiter.api.Test
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.boot.test.context.SpringBootTest
import org.springframework.jdbc.core.JdbcTemplate
import org.springframework.security.core.context.SecurityContextHolder
import org.springframework.security.test.context.support.WithMockUser
import org.springframework.test.context.ActiveProfiles
import org.springframework.test.context.DynamicPropertyRegistry
import org.springframework.test.context.DynamicPropertySource
import org.springframework.transaction.annotation.Transactional
import org.testcontainers.junit.jupiter.Container
import org.testcontainers.junit.jupiter.Testcontainers
@Testcontainers
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
@ActiveProfiles("default")
@Transactional
@WithMockUser(username = "test", roles = ["haitaton-user"])
internal class HankeGeometriatServiceImplITest {
companion object {
@Container
var container: HaitatonPostgreSQLContainer = HaitatonPostgreSQLContainer()
.withExposedPorts(5433) // use non-default port
.withPassword("<PASSWORD>")
.withUsername("test")
@JvmStatic
@DynamicPropertySource
fun postgresqlProperties(registry: DynamicPropertyRegistry) {
registry.add("spring.datasource.url", container::getJdbcUrl)
registry.add("spring.datasource.username", container::getUsername)
registry.add("spring.datasource.password", container::getPassword)
registry.add("spring.liquibase.url", container::getJdbcUrl)
registry.add("spring.liquibase.user", container::getUsername)
registry.add("spring.liquibase.password", container::getPassword)
}
}
@Autowired
private lateinit var hankeService: HankeService
@Autowired
private lateinit var hankeGeometriatService: HankeGeometriatService
@Autowired
private lateinit var jdbcTemplate: JdbcTemplate
@BeforeEach
fun setUp() {
// delete existing data from database
jdbcTemplate.execute("DELETE FROM HankeGeometriat")
}
@Test
fun `save and load and update`() {
val hankeGeometriat = "/fi/hel/haitaton/hanke/geometria/hankeGeometriat.json"
.asJsonResource(HankeGeometriat::class.java)
val username = SecurityContextHolder.getContext().authentication.name
// For FK constraints we need a Hanke in database
// Using hankeService to create the dummy hanke into database causes
// tunnus and id to be whatever the service thinks is right, so
// they must be picked from the created hanke-instance.
val hanke = hankeService.createHanke(Hanke(hankeGeometriat.hankeId!!, ""))
val hankeTunnus = hanke.hankeTunnus!!
hankeGeometriat.hankeId = hanke.id // replaces the id with the correct one
// Check that the hanke geometry flag is false:
assertThat(hanke.tilat.onGeometrioita).isFalse()
// save
hankeGeometriatService.saveGeometriat(hankeTunnus, hankeGeometriat)
// NOTE: the local Hanke instance has not been updated by the above call. Need to reload
// the hanke to check that the flag changed to true:
val updatedHanke = hankeService.loadHanke(hankeTunnus)
assertThat(updatedHanke).isNotNull()
assertThat(updatedHanke!!.tilat.onGeometrioita).isTrue()
// load
var loadedHankeGeometriat = hankeGeometriatService.loadGeometriat(hankeTunnus)
val createdAt = loadedHankeGeometriat!!.createdAt!!
val modifiedAt = loadedHankeGeometriat.modifiedAt!!
assertAll {
assertThat(loadedHankeGeometriat!!.hankeId).isEqualTo(hankeGeometriat.hankeId)
assertThat(loadedHankeGeometriat!!.version).isEqualTo(0)
assertThat(loadedHankeGeometriat!!.createdByUserId).isEqualTo(username)
assertThat(loadedHankeGeometriat!!.modifiedByUserId).isNull()
assertThat(loadedHankeGeometriat!!.featureCollection!!.features.size).isEqualTo(2)
assertThat(loadedHankeGeometriat!!.featureCollection!!.features[0].geometry is Point)
val loadedPoint = loadedHankeGeometriat!!.featureCollection!!.features[0].geometry as Point
val point = hankeGeometriat.featureCollection!!.features[0].geometry as Point
assertThat(loadedPoint.coordinates).isEqualTo(point.coordinates)
assertThat(loadedHankeGeometriat!!.featureCollection!!.features[0].properties["hankeTunnus"])
.isEqualTo(hankeTunnus)
}
// update
loadedHankeGeometriat.featureCollection!!.features.add(loadedHankeGeometriat.featureCollection!!.features[0])
loadedHankeGeometriat.id = null
loadedHankeGeometriat.version = null
loadedHankeGeometriat.modifiedAt = null
// save
hankeGeometriatService.saveGeometriat(hankeTunnus, loadedHankeGeometriat)
// load
loadedHankeGeometriat = hankeGeometriatService.loadGeometriat(hankeTunnus)
assertAll {
assertThat(loadedHankeGeometriat!!.hankeId).isEqualTo(hankeGeometriat.hankeId)
assertThat(loadedHankeGeometriat.version).isEqualTo(1) // this has increased
assertThat(loadedHankeGeometriat.createdByUserId).isEqualTo(username)
assertThat(loadedHankeGeometriat.createdAt!!.format(DATABASE_TIMESTAMP_FORMAT))
.isEqualTo(createdAt.format(DATABASE_TIMESTAMP_FORMAT))
assertThat(loadedHankeGeometriat.modifiedAt!!.isAfter(modifiedAt)) // this has changed
assertThat(loadedHankeGeometriat.modifiedByUserId).isEqualTo(username)
assertThat(loadedHankeGeometriat.featureCollection!!.features.size).isEqualTo(3) // this has increased
assertThat(loadedHankeGeometriat.featureCollection!!.features[0].geometry is Point)
val loadedPoint = loadedHankeGeometriat.featureCollection!!.features[0].geometry as Point
val point = hankeGeometriat.featureCollection!!.features[0].geometry as Point
assertThat(loadedPoint.coordinates).isEqualTo(point.coordinates)
assertThat(loadedHankeGeometriat.featureCollection!!.features[0].properties["hankeTunnus"])
.isEqualTo(hankeTunnus)
}
// check database too to make sure there is everything correctly
assertAll {
assertThat(jdbcTemplate.queryForObject("SELECT COUNT(*) FROM HankeGeometriat") { rs, _ -> rs.getInt(1) })
.isEqualTo(1)
val ids = jdbcTemplate.query("SELECT id, hankegeometriatid FROM HankeGeometria") { rs, _ ->
Pair(rs.getInt(1), rs.getInt(2))
}
assertThat(ids.size).isEqualTo(3)
ids.forEach { idPair ->
assertThat(idPair.first).isNotNull()
assertThat(idPair.second).isEqualTo(loadedHankeGeometriat!!.id)
}
}
}
}
| 6 | null |
4
| 1 |
8f5d9dd7af0f78b8f19598c484ae657c26f3f9b8
| 7,595 |
haitaton-backend
|
MIT License
|
twitlin/src/common/main/kotlin/com/sorrowblue/twitlin/client/Error.kt
|
SorrowBlue
| 278,215,181 | false | null |
package com.sorrowblue.twitlin.client
import com.sorrowblue.twitlin.annotation.AndroidParcelable
import com.sorrowblue.twitlin.annotation.AndroidParcelize
import com.sorrowblue.twitlin.annotation.JvmSerializable
import kotlinx.serialization.Serializable
/**
* Error
*
* @property message
* @property code
* @constructor Create empty Error
*/
@AndroidParcelize
@Serializable
public data class Error(val message: String, val code: Int) : AndroidParcelable, JvmSerializable
| 0 |
Kotlin
|
0
| 1 |
d6a3fdf66dea3d44f95e6800d35031d9339293cd
| 479 |
Twitlin
|
MIT License
|
mobile/src/main/java/com/ashomok/lullabies/billing_kotlin/AppSku.kt
|
ashomokdev
| 179,253,799 | true |
{"Java": 467041, "Kotlin": 113988}
|
package com.ashomok.lullabies.billing_kotlin
import com.ashomok.lullabies.BuildConfig
object AppSku {
val ADS_FREE_FOREVER_SKU_ID: String = getSkuAdsFreeInApp()
private fun getSkuAdsFreeInApp(): String {
return if (BuildConfig.DEBUG) {
"android.test.purchased"
} else {
"ads_free_forever"
}
}
val ADS_FREE_SUBSCRIPTION_1_MONTH_SKU_IDS: String = getSku1MonthSubscription()
private fun getSku1MonthSubscription(): String {
return if (BuildConfig.DEBUG) {
"android.test.purchased"
} else {
"ads_free_subscription"
}
}
val ADS_FREE_SUBSCRIPTION_1_YEAR_SKU_IDS: String = getSku1YearSubscription()
private fun getSku1YearSubscription(): String {
return if (BuildConfig.DEBUG) {
"android.test.purchased"
} else {
"ads_free_subscription_yearly"
}
}
var INAPP_SKUS = arrayOf(ADS_FREE_FOREVER_SKU_ID)
var SUBSCRIPTION_SKUS =
arrayOf(ADS_FREE_SUBSCRIPTION_1_MONTH_SKU_IDS, ADS_FREE_SUBSCRIPTION_1_YEAR_SKU_IDS)
var AUTO_CONSUME_SKUS = arrayOf<String>()
}
| 19 |
Java
|
1
| 1 |
8f6811e9566376fb66f45afcc1d6c7bc08821662
| 1,152 |
lullabies-v3
|
Apache License 2.0
|
shared/backend/dukecon/src/commonMain/kotlin/org/dukecon/remote/api/Errors.kt
|
dukecon
| 211,271,600 | false | null |
package org.dukecon.remote.api
import io.ktor.http.HttpStatusCode
val COMEBACK_LATER_STATUS = HttpStatusCode(477, "Come Back Later")
val TOO_LATE_STATUS = HttpStatusCode(478, "Too Late")
class UpdateProblem(override val cause: Throwable) : Throwable()
class Unauthorized : Throwable()
class CannotPostVote : Throwable()
class CannotDeleteVote : Throwable()
class CannotFavorite : Throwable()
class TooEarlyVote : Throwable()
class TooLateVote : Throwable()
| 25 |
Kotlin
|
313
| 5 |
aa12bd09830c3407635d0bc3e5691ba1ffaeeb2f
| 460 |
dukecon_mobile
|
Apache License 2.0
|
librarys/Guide/src/main/java/com/aqrlei/guide/lifecycle/Lifecycle.kt
|
AqrLei
| 278,292,323 | false | null |
package com.aqrlei.guide.lifecycle
/**
* Created by AqrLei on 2019-08-23
*/
interface Lifecycle {
fun addLifecycleListener(lifecycleListener: LifecycleListener)
fun removeLifecycleListener(lifecycleListener: LifecycleListener)
fun removeAllLifecycleListener()
}
| 0 |
Kotlin
|
0
| 0 |
d90a6a63dc9aeedfa38f3c3e76160e28641dcd41
| 276 |
AndroidLibs
|
Apache License 2.0
|
src/test/kotlin/com/github/kerubistan/kerub/stories/host/HostSecurityDefs.kt
|
kerubistan
| 19,528,622 | false | null |
package com.github.kerubistan.kerub.stories.host
import com.github.kerubistan.kerub.testBaseUrl
import com.github.kerubistan.kerub.testRestBaseUrl
import com.github.kerubistan.kerub.utils.getLogger
import cucumber.api.java.en.Given
import cucumber.api.java.en.Then
import cucumber.api.java.en.When
import org.apache.http.client.methods.HttpDelete
import org.apache.http.client.methods.HttpGet
import org.apache.http.client.methods.HttpPost
import org.apache.http.client.methods.HttpPut
import org.apache.http.entity.ContentType
import org.apache.http.entity.StringEntity
import org.apache.http.impl.client.HttpClientBuilder
import org.junit.Assert
class HostSecurityDefs {
var user: String = "admin"
var responseCode = 200
companion object private val logger = getLogger(HostSecurityDefs::class)
@Given("A controller")
fun givenAController() {
}
@Given("(\\S+) user")
fun givenAUser(user: String) {
this.user = user
}
@When("user tries to (\\S+) hosts")
fun userAction(action: String) {
val client = HttpClientBuilder.create().build()
val login = HttpPost("$testRestBaseUrl/auth/login")
login.entity = StringEntity("""
{"username":"$user","password":"<PASSWORD>"}
""", ContentType.APPLICATION_JSON)
val loginResp = client.execute(login)
logger.info("login: {}",loginResp.statusLine.statusCode)
when (action) {
"list" -> {
responseCode = client.execute(HttpGet("$testRestBaseUrl/host")).statusLine.statusCode
}
"join" -> {
val join = HttpPut("$testRestBaseUrl/host/join")
join.entity = StringEntity("""
{"host":
{
"@type":"host",
"id":"7880f78c-e21b-4452-ac52-8d8e9d74c463",
"address":"192.168.122.221",
"publicKey":"43:99:3d:4f:35:8f:29:21:28:a2:ba:35:76:75:f0:af",
"dedicated":true
},
"password":""}
""", ContentType.APPLICATION_JSON)
responseCode = client.execute(join).statusLine.statusCode
}
"remove" -> {
responseCode = client.execute(HttpDelete("$testBaseUrl/s/r/host/7880f78c-e21b-4452-ac52-8d8e9d74c463"))
.statusLine.statusCode
}
"update" -> {
val update = HttpPost("$testRestBaseUrl/host/7880f78c-e21b-4452-ac52-8d8e9d74c463")
update.entity = StringEntity(""" {"@type":"host","id":"7880f78c-e21b-4452-ac52-8d8e9d74c463","address":"192.168.122.221","publicKey"
:"43:99:3d:4f:35:8f:29:21:28:a2:ba:35:76:75:f0:af","dedicated":true}""", ContentType.APPLICATION_JSON)
responseCode = client.execute(update).statusLine.statusCode
}
else -> {
throw IllegalArgumentException("not handled action")
}
}
}
@Then("(\\S+) should be received")
fun assertResponseCode(responseCode: Int) {
Assert.assertEquals(responseCode, this.responseCode)
}
}
| 109 | null |
4
| 14 |
99cb43c962da46df7a0beb75f2e0c839c6c50bda
| 2,734 |
kerub
|
Apache License 2.0
|
kotlin/basic/src/main/kotlin/com/shengsiyuan/kotlin4/FeatureTest.kt
|
cuixbo
| 538,532,557 | true |
{"Java": 745660, "Kotlin": 323125, "JavaScript": 80254, "Dart": 24553, "Python": 8877, "HTML": 5008, "Objective-C": 4465, "Starlark": 1916, "Ruby": 776, "CSS": 773, "Thrift": 670, "Swift": 404, "Makefile": 273}
|
package com.shengsiyuan.kotlin4
/**
* Created by suhen
* 18-12-10.
* Email: <EMAIL>
*
* 委托 delegation
*/
interface MyInterface {
fun myPrint()
}
interface MyInterface2 {
fun myPrint()
}
class MyInterfaceImpl(private val str: String) : MyInterface, MyInterface2 {
override fun myPrint() {
println("hello: $str")
}
}
/**
* by 关键字后面的对象实际上会被存储在类的内部, 编译器则会把父接口的所有方法实现出来, 并且将实现转移给委托对象去进行
*/
class MyClass(private val myInterface: MyInterfaceImpl) : MyInterface, MyInterface2 by myInterface {
// override fun myPrint() {
// myInterface.myPrint()
// println("hello world")
// }
}
fun main() {
val myInterfaceImpl = MyInterfaceImpl("suhen")
val myClass = MyClass(myInterfaceImpl)
myClass.myPrint()
}
| 0 | null |
0
| 0 |
8934028fb0bf69c289b82f737682fa5565f1dd76
| 760 |
ShengSiYuan
|
Apache License 2.0
|
android/versioned-abis/expoview-abi44_0_0/src/main/java/abi44_0_0/expo/modules/mailcomposer/MailComposerPackage.kt
|
derekstavis
| 184,342,737 | false | null |
package abi44_0_0.expo.modules.mailcomposer
import android.content.Context
import abi44_0_0.expo.modules.core.BasePackage
class MailComposerPackage : BasePackage() {
override fun createExportedModules(context: Context) =
listOf(MailComposerModule(context))
}
| 1 | null |
1
| 2 |
e377f0cd22db5cd7feb8e80348cd7064db5429b1
| 267 |
expo
|
MIT License
|
app/src/main/java/com/lateinit/rightweight/data/model/remote/LoginModel.kt
|
boostcampwm-2022
| 563,132,819 | false |
{"Kotlin": 320392}
|
package com.lateinit.rightweight.data.model.remote
data class LoginRequestBody(
val postBody: String,
val requestUri: String,
val returnIdpCredential: Boolean,
val returnSecureToken: Boolean
)
data class PostBody(
val id_token: String,
val providerId: String,
) {
override fun toString(): String {
return "id_token=$id_token&providerId=$providerId"
}
}
| 6 |
Kotlin
|
0
| 27 |
ff6116ee9e49bd8ed493d3c6928d0b9a7f892689
| 395 |
android09-RightWeight
|
MIT License
|
app/src/main/java/nl/hva/emergencyexitapp/ui/theme/screens/AppScreens.kt
|
mgyanku
| 876,678,304 | false |
{"Kotlin": 42009}
|
package nl.hva.emergencyexitapp.ui.theme.screens
import androidx.annotation.StringRes
import nl.hva.emergencyexitapp.R
sealed class AppScreens (
val route: String,
@StringRes val resourceId: Int,
val icon: Int
) {
object HomeScreen: AppScreens("home_screen", R.string.home , R.drawable.home)
object SearchScreen: AppScreens("search_screen", R.string.search , R.drawable.search)
object InstructionScreen: AppScreens("instruction_screen", R.string.search , R.drawable.instruction)
object AddScreen: AppScreens("add_screen", R.string.add , R.drawable.add)
object SettingsScreen: AppScreens("settings_screen", R.string.settings , R.drawable.settings)
}
| 0 |
Kotlin
|
0
| 0 |
785eb7e19e65ce11c135a81343a8257b4a09857e
| 684 |
emergency-exit-app
|
MIT License
|
src/main/kotlin/com/bajdcc/LALR1/interpret/os/user/routine/file/URFileLoad.kt
|
bajdcc
| 32,624,604 | false |
{"Kotlin": 1131761, "HTML": 42480, "CSS": 37889, "JavaScript": 2703}
|
package com.bajdcc.LALR1.interpret.os.user.routine.file
import com.bajdcc.LALR1.interpret.os.IOSCodePage
import com.bajdcc.util.ResourceLoader
/**
* 【用户态】读文件
*
* @author bajdcc
*/
class URFileLoad : IOSCodePage {
override val name: String
get() = "/usr/p/<"
override val code: String
get() = ResourceLoader.load(javaClass)
}
| 0 |
Kotlin
|
20
| 65 |
90b19af98da99b53bba5b3269ad5666df7c05e49
| 356 |
jMiniLang
|
MIT License
|
debop4k-core/src/main/kotlin/debop4k/core/Tuplex.kt
|
debop
| 60,844,667 | false | null |
/*
* Copyright (c) 2016. <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.
*
*/
@file:JvmName("Tuplex")
package debop4k.core
import java.io.Serializable
fun <T1> tupleOf(t1: T1) = Tuple1(t1)
fun <T1, T2> tupleOf(t1: T1, t2: T2) = Tuple2(t1, t2)
fun <T1, T2, T3> tupleOf(t1: T1, t2: T2, t3: T3) = Tuple3(t1, t2, t3)
fun <T1, T2, T3, T4> tupleOf(t1: T1, t2: T2, t3: T3, t4: T4) = Tuple4(t1, t2, t3, t4)
fun <T1, T2, T3, T4, T5> tupleOf(t1: T1, t2: T2, t3: T3, t4: T4, t5: T5) = Tuple5(t1, t2, t3, t4, t5)
fun <T1, T2, T3, T4, T5, T6> tupleOf(t1: T1, t2: T2, t3: T3, t4: T4, t5: T5, t6: T6) = Tuple6(t1, t2, t3, t4, t5, t6)
fun <T1, T2, T3, T4, T5, T6, T7> tupleOf(t1: T1, t2: T2, t3: T3, t4: T4, t5: T5, t6: T6, t7: T7)
= Tuple7(t1, t2, t3, t4, t5, t6, t7)
fun <T1, T2, T3, T4, T5, T6, T7, T8> tupleOf(t1: T1, t2: T2, t3: T3, t4: T4, t5: T5, t6: T6, t7: T7, t8: T8)
= Tuple8(t1, t2, t3, t4, t5, t6, t7, t8)
fun <T1, T2, T3, T4, T5, T6, T7, T8, T9> tupleOf(t1: T1, t2: T2, t3: T3, t4: T4, t5: T5, t6: T6, t7: T7, t8: T8, t9: T9)
= Tuple9(t1, t2, t3, t4, t5, t6, t7, t8, t9)
fun <T1, T2, T3, T4, T5, T6, T7, T8, T9, T10> tupleOf(t1: T1, t2: T2, t3: T3, t4: T4, t5: T5, t6: T6, t7: T7, t8: T8, t9: T9, t10: T10)
= Tuple10(t1, t2, t3, t4, t5, t6, t7, t8, t9, t10)
fun <T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11> tupleOf(t1: T1, t2: T2, t3: T3, t4: T4, t5: T5, t6: T6, t7: T7, t8: T8, t9: T9, t10: T10, t11: T11)
= Tuple11(t1, t2, t3, t4, t5, t6, t7, t8, t9, t10, t11)
fun <T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12> tupleOf(t1: T1, t2: T2, t3: T3, t4: T4, t5: T5, t6: T6, t7: T7, t8: T8, t9: T9, t10: T10, t11: T11, t12: T12)
= Tuple12(t1, t2, t3, t4, t5, t6, t7, t8, t9, t10, t11, t12)
fun <T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13> tupleOf(t1: T1, t2: T2, t3: T3, t4: T4, t5: T5, t6: T6, t7: T7, t8: T8, t9: T9, t10: T10, t11: T11, t12: T12, t13: T13)
= Tuple13(t1, t2, t3, t4, t5, t6, t7, t8, t9, t10, t11, t12, t13)
fun <T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14> tupleOf(t1: T1, t2: T2, t3: T3, t4: T4, t5: T5, t6: T6, t7: T7, t8: T8, t9: T9, t10: T10, t11: T11, t12: T12, t13: T13, t14: T14)
= Tuple14(t1, t2, t3, t4, t5, t6, t7, t8, t9, t10, t11, t12, t13, t14)
fun <T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15> tupleOf(t1: T1, t2: T2, t3: T3, t4: T4, t5: T5, t6: T6, t7: T7, t8: T8, t9: T9, t10: T10, t11: T11, t12: T12, t13: T13, t14: T14, t15: T15)
= Tuple15(t1, t2, t3, t4, t5, t6, t7, t8, t9, t10, t11, t12, t13, t14, t15)
data class Tuple1<T1>(override val first: T1) : Product1<T1>, Serializable {
override fun toString(): String {
return "($first)"
}
}
data class Tuple2<T1, T2>(
override val first: T1,
override val second: T2) : Product2<T1, T2>, Serializable {
override fun toString(): String {
return "($first, $second)"
}
}
data class Tuple3<T1, T2, T3>(
override val first: T1,
override val second: T2,
override val third: T3) : Product3<T1, T2, T3>, Serializable {
override fun toString(): String {
return "($first, $second, $third)"
}
}
data class Tuple4<T1, T2, T3, T4>(
override val first: T1,
override val second: T2,
override val third: T3,
override val fourth: T4) : Product4<T1, T2, T3, T4>, Serializable {
override fun toString(): String {
return "($first, $second, $third, $fourth)"
}
}
data class Tuple5<T1, T2, T3, T4, T5>(
override val first: T1,
override val second: T2,
override val third: T3,
override val fourth: T4,
override val fifth: T5) : Product5<T1, T2, T3, T4, T5>, Serializable {
override fun toString(): String {
return "($first, $second, $third, $fourth, $fifth)"
}
}
data class Tuple6<T1, T2, T3, T4, T5, T6>(
override val first: T1,
override val second: T2,
override val third: T3,
override val fourth: T4,
override val fifth: T5,
override val sixth: T6) : Product6<T1, T2, T3, T4, T5, T6>, Serializable {
override fun toString(): String {
return "($first, $second, $third, $fourth, $fifth, $sixth)"
}
}
data class Tuple7<T1, T2, T3, T4, T5, T6, T7>(
override val first: T1,
override val second: T2,
override val third: T3,
override val fourth: T4,
override val fifth: T5,
override val sixth: T6,
override val seventh: T7) : Product7<T1, T2, T3, T4, T5, T6, T7>, Serializable {
override fun toString(): String {
return "($first, $second, $third, $fourth, $fifth, $sixth, $seventh)"
}
}
data class Tuple8<T1, T2, T3, T4, T5, T6, T7, T8>(
override val first: T1,
override val second: T2,
override val third: T3,
override val fourth: T4,
override val fifth: T5,
override val sixth: T6,
override val seventh: T7,
override val eighth: T8) : Product8<T1, T2, T3, T4, T5, T6, T7, T8>, Serializable {
override fun toString(): String {
return "($first, $second, $third, $fourth, $fifth, $sixth, $seventh, $eighth)"
}
}
data class Tuple9<T1, T2, T3, T4, T5, T6, T7, T8, T9>(
override val first: T1,
override val second: T2,
override val third: T3,
override val fourth: T4,
override val fifth: T5,
override val sixth: T6,
override val seventh: T7,
override val eighth: T8,
override val ninth: T9) : Product9<T1, T2, T3, T4, T5, T6, T7, T8, T9>, Serializable {
override fun toString(): String {
return "($first, $second, $third, $fourth, $fifth, $sixth, $seventh, $eighth, $ninth)"
}
}
data class Tuple10<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10>(
override val first: T1,
override val second: T2,
override val third: T3,
override val fourth: T4,
override val fifth: T5,
override val sixth: T6,
override val seventh: T7,
override val eighth: T8,
override val ninth: T9,
override val ten: T10) : Product10<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10>, Serializable {
override fun toString(): String {
return "($first, $second, $third, $fourth, $fifth, $sixth, $seventh, $eighth, $ninth, $ten)"
}
}
data class Tuple11<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11>(
override val first: T1,
override val second: T2,
override val third: T3,
override val fourth: T4,
override val fifth: T5,
override val sixth: T6,
override val seventh: T7,
override val eighth: T8,
override val ninth: T9,
override val ten: T10,
override val eleven: T11) : Product11<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11>, Serializable {
override fun toString(): String {
return "($first, $second, $third, $fourth, $fifth, $sixth, $seventh, $eighth, $ninth, $ten, $eleven)"
}
}
data class Tuple12<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12>(
override val first: T1,
override val second: T2,
override val third: T3,
override val fourth: T4,
override val fifth: T5,
override val sixth: T6,
override val seventh: T7,
override val eighth: T8,
override val ninth: T9,
override val ten: T10,
override val eleven: T11,
override val twelve: T12) : Product12<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12>, Serializable {
override fun toString(): String {
return "($first, $second, $third, $fourth, $fifth, $sixth, $seventh, $eighth, $ninth, $ten, $eleven, $twelve)"
}
}
data class Tuple13<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13>(
override val first: T1,
override val second: T2,
override val third: T3,
override val fourth: T4,
override val fifth: T5,
override val sixth: T6,
override val seventh: T7,
override val eighth: T8,
override val ninth: T9,
override val ten: T10,
override val eleven: T11,
override val twelve: T12,
override val thirteen: T13) : Product13<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13>, Serializable {
override fun toString(): String {
return "($first, $second, $third, $fourth, $fifth, $sixth, $seventh, $eighth, $ninth, $ten, $eleven, $twelve, $thirteen)"
}
}
data class Tuple14<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14>(
override val first: T1,
override val second: T2,
override val third: T3,
override val fourth: T4,
override val fifth: T5,
override val sixth: T6,
override val seventh: T7,
override val eighth: T8,
override val ninth: T9,
override val ten: T10,
override val eleven: T11,
override val twelve: T12,
override val thirteen: T13,
override val fourteen: T14)
: Product14<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14>, Serializable {
override fun toString(): String {
return "($first, $second, $third, $fourth, $fifth, $sixth, $seventh, $eighth, $ninth, $ten, $eleven, $twelve, $thirteen, $fourteen)"
}
}
data class Tuple15<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15>(
override val first: T1,
override val second: T2,
override val third: T3,
override val fourth: T4,
override val fifth: T5,
override val sixth: T6,
override val seventh: T7,
override val eighth: T8,
override val ninth: T9,
override val ten: T10,
override val eleven: T11,
override val twelve: T12,
override val thirteen: T13,
override val fourteen: T14,
override val fifteen: T15)
: Product15<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15>, Serializable {
override fun toString(): String {
return "($first, $second, $third, $fourth, $fifth, $sixth, $seventh, $eighth, $ninth, $ten, $eleven, $twelve, $thirteen, $fourteen, $fifteen)"
}
}
// TODO: Tuple22 까지 만들기 ^^
| 1 |
Kotlin
|
10
| 40 |
5a621998b88b4d416f510971536abf3bf82fb2f0
| 10,138 |
debop4k
|
Apache License 2.0
|
dsl/src/main/kotlin/io/cloudshiftdev/awscdkdsl/services/dynamodb/CfnTableAttributeDefinitionPropertyDsl.kt
|
cloudshiftinc
| 667,063,030 | false | null |
@file:Suppress(
"RedundantVisibilityModifier",
"RedundantUnitReturnType",
"RemoveRedundantQualifierName",
"unused",
"UnusedImport",
"ClassName",
"REDUNDANT_PROJECTION",
"DEPRECATION"
)
package cloudshift.awscdk.dsl.services.dynamodb
import cloudshift.awscdk.common.CdkDslMarker
import kotlin.String
import software.amazon.awscdk.services.dynamodb.CfnTable
/**
* Represents an attribute for describing the key schema for the table and indexes.
*
* 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.dynamodb.*;
* AttributeDefinitionProperty attributeDefinitionProperty = AttributeDefinitionProperty.builder()
* .attributeName("attributeName")
* .attributeType("attributeType")
* .build();
* ```
*
* [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-dynamodb-table-attributedefinition.html)
*/
@CdkDslMarker
public class CfnTableAttributeDefinitionPropertyDsl {
private val cdkBuilder: CfnTable.AttributeDefinitionProperty.Builder =
CfnTable.AttributeDefinitionProperty.builder()
/** @param attributeName A name for the attribute. */
public fun attributeName(attributeName: String) {
cdkBuilder.attributeName(attributeName)
}
/**
* @param attributeType The data type for the attribute, where:.
* * `S` - the attribute is of type String
* * `N` - the attribute is of type Number
* * `B` - the attribute is of type Binary
*/
public fun attributeType(attributeType: String) {
cdkBuilder.attributeType(attributeType)
}
public fun build(): CfnTable.AttributeDefinitionProperty = cdkBuilder.build()
}
| 4 | null |
0
| 3 |
c59c6292cf08f0fc3280d61e7f8cff813a608a62
| 1,797 |
awscdk-dsl-kotlin
|
Apache License 2.0
|
src/day_10/CPUCommand.kt
|
BrumelisMartins
| 572,847,918 | false |
{"Kotlin": 32376}
|
package day_10
@Suppress("SpellCheckingInspection")
enum class CPUCommand(val cycleCount: Int) {
NOOP(1), ADDX(2)
}
| 0 |
Kotlin
|
0
| 0 |
3391b6df8f61d72272f07b89819c5b1c21d7806f
| 120 |
aoc-2022
|
Apache License 2.0
|
core/ui/src/androidMain/kotlin/org/michaelbel/movies/ui/ktx/WindowKtx.kt
|
michaelbel
| 115,437,864 | false |
{"Kotlin": 908384, "Swift": 692, "HTML": 606, "Shell": 235}
|
package org.michaelbel.movies.ui.ktx
import android.view.Window
import android.view.WindowManager
fun Window.setScreenshotBlockEnabled(enabled: Boolean) {
if (enabled) {
setFlags(WindowManager.LayoutParams.FLAG_SECURE, WindowManager.LayoutParams.FLAG_SECURE)
} else {
clearFlags(WindowManager.LayoutParams.FLAG_SECURE)
}
}
| 8 |
Kotlin
|
36
| 271 |
1da1d67e093ecb76057a06da0ef17f746ca06888
| 352 |
movies
|
Apache License 2.0
|
skiko/src/nativeMain/kotlin/org/jetbrains/skiko/OpenGLLibrary.native.kt
|
JetBrains
| 282,864,178 | false | null |
package org.jetbrains.skiko
internal actual fun loadOpenGLLibrary() {
when (hostOs) {
// It is deprecated. See https://developer.apple.com/documentation/opengles
OS.Ios -> throw RenderException("OpenGL on iOS isn't supported")
// Do nothing as we don't know for sure which OS supports OpenGL.
// If there is support, we assume that it is already linked.
// If there is no support, there will be a native crash
// (to throw a RenderException we need to investigate case by case)
else -> Unit
}
}
| 23 | null |
118
| 1,821 |
bbfaf62256fcf0255ac2b5846223f27c43dbfb00
| 559 |
skiko
|
Apache License 2.0
|
ChoreApp/app/src/main/java/com/example/bruno/choreapp/activity/listchores/ChoreAdapterContract.kt
|
brunokarpo
| 130,281,888 | false | null |
package com.example.bruno.choreapp.activity.listchores
import com.example.bruno.choreapp.model.Chore
interface ChoreAdapterView {
fun removeChoreOfList(chore: Chore)
fun updateChoreOnList(chore: Chore)
}
interface ChoreAdapterPresenter {
fun deleteChore(chore: Chore)
fun updateChore(chore: Chore)
}
| 0 |
Kotlin
|
0
| 0 |
1acb5381603e501bd4421d64084438b2e8029654
| 323 |
android-kotlin
|
The Unlicense
|
common/user/data/src/commonMain/kotlin/dev/alvr/katana/common/user/data/di/module.kt
|
alvr
| 446,535,707 | false |
{"Kotlin": 465666, "Swift": 594}
|
package dev.alvr.katana.common.user.data.di
import dev.alvr.katana.common.user.data.managers.UserIdManagerImpl
import dev.alvr.katana.common.user.data.repositories.UserRepositoryImpl
import dev.alvr.katana.common.user.data.sources.id.UserIdRemoteSource
import dev.alvr.katana.common.user.data.sources.id.UserIdRemoteSourceImpl
import dev.alvr.katana.common.user.data.sources.info.UserInfoRemoteSource
import dev.alvr.katana.common.user.data.sources.info.UserInfoRemoteSourceImpl
import dev.alvr.katana.common.user.domain.managers.UserIdManager
import dev.alvr.katana.common.user.domain.repositories.UserRepository
import org.koin.core.module.dsl.singleOf
import org.koin.dsl.bind
import org.koin.dsl.module
private val managersModule = module {
singleOf(::UserIdManagerImpl) bind UserIdManager::class
}
private val repositoriesModule = module {
singleOf(::UserRepositoryImpl) bind UserRepository::class
}
private val sourcesModule = module {
singleOf(::UserIdRemoteSourceImpl) bind UserIdRemoteSource::class
singleOf(::UserInfoRemoteSourceImpl) bind UserInfoRemoteSource::class
}
val commonUserDataModule = module {
includes(managersModule, repositoriesModule, sourcesModule)
}
| 3 |
Kotlin
|
0
| 59 |
bf949c999d220244ac89de1bd1b678d1a3123e0a
| 1,203 |
katana
|
Apache License 2.0
|
KotlinExam/app/src/main/java/com/example/kotlinexam/HelloKotlin.kt
|
hopypark
| 624,662,218 | false |
{"Text": 1, "Ignore List": 73, "Git Attributes": 1, "Markdown": 1, "Gradle Kotlin DSL": 51, "Java Properties": 68, "Shell": 38, "Batchfile": 38, "Kotlin": 63, "XML": 558, "Gradle": 63, "Proguard": 33, "Java": 129}
|
package com.example.kotlinexam
fun main(args: Array<String>){
println(printHello())
var hello:HelloKotlin = HelloKotlin()
hello.greeting("Park")
}
fun printHello(): String {
return "Hello Kotlin World!"
}
class HelloKotlin {
fun greeting(name:String){
println("Hello $name")
}
}
| 0 |
Java
|
0
| 0 |
3782e30c646523def245e7c990a20f52d04dd8c3
| 314 |
Lect_Android_Kotlin
|
MIT License
|
src/main/kotlin/cloud/honeydue/repository/ChoreRepository.kt
|
armory-pilots
| 369,274,541 | false |
{"Kotlin": 12257}
|
package cloud.honeydue.repository
import cloud.honeydue.model.Chore
import cloud.honeydue.model.User
import org.springframework.data.jpa.repository.JpaRepository
interface ChoreRepository : JpaRepository<Chore, Long> {
fun findByUserId(userId: Long?) : MutableSet<Chore>
}
| 0 |
Kotlin
|
0
| 0 |
db20bb901a6bedaf35c394858ac5be275d854924
| 278 |
honeydue-backend
|
MIT License
|
app/src/main/java/com/hemendra/minitheater/presenter/DownloadsPresenter.kt
|
hemendra-sharma
| 145,728,268 | false | null |
package com.hemendra.minitheater.presenter
import android.content.Context
import android.content.Intent
import android.os.Environment
import com.hemendra.minitheater.data.DownloadsList
import com.hemendra.minitheater.data.Movie
import com.hemendra.minitheater.data.Torrent
import com.hemendra.minitheater.presenter.listeners.IDownloadsPresenter
import com.hemendra.minitheater.service.DownloaderService
import com.hemendra.minitheater.service.StreamingService
import com.hemendra.minitheater.utils.Utils
import java.io.File
class DownloadsPresenter private constructor():
IDownloadsPresenter {
companion object {
private var instance : DownloadsPresenter? = null
fun getInstance() : DownloadsPresenter {
if(instance == null) instance = DownloadsPresenter()
return instance!!
}
}
private val dirPath = """${Environment.getExternalStorageDirectory().absolutePath}/MiniTheater"""
private val dir = File(dirPath)
init { dir.mkdirs() }
private val downloadsListFile = File(dir, "downloadingMovies.obj")
private var downloadsList: DownloadsList? = null
init {
downloadsList = Utils.readObjectFromFile(downloadsListFile) as DownloadsList?
if(downloadsList == null) downloadsList = DownloadsList()
}
override fun checkAndStartOngoingDownload(context: Context) {
downloadsList?.let {
for(movie in it.movies) {
if(movie.isDownloading) {
startDownload(context, movie, false)
break
}
}
}
}
override fun checkAndStartOngoingStream(context: Context) {
downloadsList?.let {
for(movie in it.movies) {
if(movie.isStreaming) {
val intent = Intent(context, StreamingService::class.java)
intent.putExtra(DownloaderService.EXTRA_MOVIE, movie)
context.startService(intent)
break
}
}
}
}
override fun addDownload(movie: Movie): DownloadFailureReason {
assert(movie.torrents.size == 1)
if(movie.torrents[0].size_bytes > Utils.getAvailableSpace()) {
return DownloadFailureReason.NOT_ENOUGH_SPACE
} else if(downloadsList?.add(movie) == true) {
saveState()
return DownloadFailureReason.NONE
} else {
return DownloadFailureReason.ALREADY_ADDED
}
}
override fun removeDownload(movie: Movie): Boolean {
if(downloadsList?.remove(movie) == true) {
saveState()
val dir = File(dir.absolutePath+"/"+movie.torrents[0].hash)
if(dir.exists()) {
if(dir.isFile) Utils.deleteFile(dir)
else if(dir.isDirectory) Utils.deleteDirectory(dir)
}
return true
}
return false
}
override fun getDownloadsList(): ArrayList<Movie> {
downloadsList?.let {
return it.movies
}
return ArrayList()
}
override fun startDownload(context: Context,
movie: Movie, stopOngoing: Boolean): DownloadFailureReason {
return if(!stopOngoing && DownloaderService.isRunning) {
DownloadFailureReason.ALREADY_DOWNLOADING
} else if(downloadsList?.startDownload(movie) == true) {
if(stopOngoing) {
context.stopService(Intent(context, DownloaderService::class.java))
}
saveState()
val intent = Intent(context, DownloaderService::class.java)
intent.putExtra(DownloaderService.EXTRA_MOVIE, movie)
val ret = context.startService(intent)
if(ret != null)
DownloadFailureReason.NONE
else
DownloadFailureReason.UNKNOWN
} else {
DownloadFailureReason.UNKNOWN
}
}
override fun pauseOrResumeDownload(context: Context, movie: Movie): Boolean {
return if(!DownloaderService.isRunning) {
false
} else if(downloadsList?.pauseOrResumeDownload(movie) == true) {
saveState()
val intent = Intent(context, DownloaderService::class.java)
intent.putExtra("action", "Pause")
context.startService(intent)
true
} else false
}
override fun stopDownload(context: Context, movie: Movie): Boolean {
return if(!DownloaderService.isRunning) {
false
} else if(downloadsList?.stopDownload(movie) == true) {
saveState()
context.stopService(Intent(context, DownloaderService::class.java))
} else false
}
override fun updateMovie(movie: Movie) {
if(downloadsList?.update(movie) == true) {
saveState()
}
}
override fun getTorrentFile(torrent: Torrent): File? {
val dir = File(dir.absolutePath+"/"+torrent.hash)
return getTorrentFile(dir)
}
private fun getTorrentFile(file: File): File? {
if(file.isFile && file.length() > 0) {
return file
}
//
if(file.exists() && file.isDirectory) {
val files = file.listFiles()
files?.let { subFiles ->
for(subFile in subFiles) {
val f = getTorrentFile(subFile)
if(f != null) return f
}
}
}
return null
}
private fun saveState() {
downloadsList?.let { Utils.writeToFile(it, downloadsListFile) }
}
}
| 0 |
Kotlin
|
0
| 0 |
3dcaf906847fa08bcea7111155d07a6120043d70
| 5,651 |
MiniTheater
|
Apache License 2.0
|
examples/kotlin/src/main/kotlin/com/xebia/functional/xef/conversation/conversations/Animal.kt
|
xebia-functional
| 629,411,216 | false |
{"Kotlin": 3799334, "TypeScript": 67083, "Scala": 16973, "CSS": 6570, "JavaScript": 1935, "Java": 457, "HTML": 395, "Shell": 238}
|
package com.xebia.functional.xef.conversation.conversations
import com.xebia.functional.xef.conversation.llm.openai.OpenAI
import com.xebia.functional.xef.conversation.llm.openai.prompt
import com.xebia.functional.xef.conversation.llm.openai.promptMessage
import com.xebia.functional.xef.prompt.Prompt
import com.xebia.functional.xef.prompt.templates.system
import com.xebia.functional.xef.prompt.templates.user
import kotlinx.serialization.Serializable
@Serializable data class Animal(val name: String, val habitat: String, val diet: String)
@Serializable
data class Invention(val name: String, val inventor: String, val year: Int, val purpose: String)
suspend fun main() {
// This example contemplate the case of using OpenTelemetry for metrics
// To run the example with OpenTelemetry, you can execute the following commands:
// - # docker compose-up server/docker/opentelemetry
// OpenAI.conversation(LocalVectorStore(OpenAI().DEFAULT_EMBEDDING), OpenTelemetryMetric())
OpenAI.conversation {
val animal: Animal = prompt("A unique animal species.")
val invention: Invention = prompt("A groundbreaking invention from the 20th century.")
println("Animal: $animal")
println("Invention: $invention")
val storyPrompt = Prompt {
+system("You are a writer for a science fiction magazine.")
+user("Write a short story of 200 words that involves the animal and the invention")
}
val story: String = promptMessage(storyPrompt)
println(story)
}
}
| 45 |
Kotlin
|
11
| 114 |
cdbc9233badc4468bdcfb6b58b3edfd0cbc5aca9
| 1,506 |
xef
|
Apache License 2.0
|
src/main/kotlin/com/android/billingclient/api/BillingClient.kt
|
AntonioNoack
| 568,083,291 | false | null |
package com.android.billingclient.api
import android.content.Context
class BillingClient(ctx: Context){
object BillingResponseCode {
const val OK = 0
}
object SkuType {
const val INAPP = "inapp"
}
fun startConnection(listener: BillingClientStateListener){
}
fun querySkuDetailsAsync(params: SkuDetailsParams, listener: (billingResult: BillingResult, skuDetailsList: List<SkuDetails>) -> Unit){
}
fun querySkuDetailsAsync(params: SkuDetailsParams, listener: SkuDetailsResponseListener){
}
fun setListener(listener: (billingResult: BillingResult?, purchases: MutableList<Purchase>?) -> Unit): BillingClient = this
fun build() = this
companion object {
fun newBuilder(ctx: Context) = BillingClient(ctx)
}
}
| 0 |
Kotlin
|
0
| 0 |
15e2013bc62282cd0185c9c0be57eaa5b0cb2c68
| 799 |
ElementalCommunityWeb
|
Apache License 2.0
|
app/src/main/java/eu/kanade/tachiyomi/ui/reader/ReaderSettingsSheet.kt
|
az4521
| 176,152,541 | true |
{"Kotlin": 2483150}
|
package eu.kanade.tachiyomi.ui.reader
import android.os.Build
import android.os.Bundle
import android.widget.CompoundButton
import android.widget.Spinner
import androidx.annotation.ArrayRes
import androidx.core.widget.NestedScrollView
import com.f2prateek.rx.preferences.Preference as RxPreference
import com.google.android.material.bottomsheet.BottomSheetDialog
import com.tfcporciuncula.flow.Preference
import eu.kanade.tachiyomi.R
import eu.kanade.tachiyomi.data.preference.PreferencesHelper
import eu.kanade.tachiyomi.data.preference.getOrDefault
import eu.kanade.tachiyomi.databinding.ReaderSettingsSheetBinding
import eu.kanade.tachiyomi.ui.reader.viewer.pager.PagerViewer
import eu.kanade.tachiyomi.ui.reader.viewer.webtoon.WebtoonViewer
import eu.kanade.tachiyomi.util.view.invisible
import eu.kanade.tachiyomi.util.view.visible
import eu.kanade.tachiyomi.widget.IgnoreFirstSpinnerListener
import uy.kohesive.injekt.injectLazy
/**
* Sheet to show reader and viewer preferences.
*/
class ReaderSettingsSheet(private val activity: ReaderActivity) : BottomSheetDialog(activity) {
private val preferences by injectLazy<PreferencesHelper>()
private val binding = ReaderSettingsSheetBinding.inflate(layoutInflater)
init {
// Use activity theme for this layout
val view = binding.root
val scroll = NestedScrollView(activity)
scroll.addView(view)
setContentView(scroll)
}
/**
* Called when the sheet is created. It initializes the listeners and values of the preferences.
*/
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
initGeneralPreferences()
when (activity.viewer) {
is PagerViewer -> initPagerPreferences()
is WebtoonViewer -> initWebtoonPreferences()
}
}
/**
* Init general reader preferences.
*/
private fun initGeneralPreferences() {
binding.viewer.onItemSelectedListener = IgnoreFirstSpinnerListener { position ->
activity.presenter.setMangaViewer(position)
val mangaViewer = activity.presenter.getMangaViewer()
if (mangaViewer == ReaderActivity.WEBTOON || mangaViewer == ReaderActivity.VERTICAL_PLUS || mangaViewer == ReaderActivity.WEBTOON_HORIZ_LTR || mangaViewer == ReaderActivity.WEBTOON_HORIZ_RTL) {
initWebtoonPreferences()
} else {
initPagerPreferences()
}
}
binding.viewer.setSelection(activity.presenter.manga?.viewer ?: 0, false)
binding.rotationMode.bindToPreference(preferences.rotation(), 1)
binding.backgroundColor.bindToIntPreference(preferences.readerTheme(), R.array.reader_themes_values)
binding.showPageNumber.bindToPreference(preferences.showPageNumber())
binding.fullscreen.bindToPreference(preferences.fullscreen())
val hasDisplayCutout = Build.VERSION.SDK_INT >= Build.VERSION_CODES.P &&
activity.window?.decorView?.rootWindowInsets?.displayCutout != null
if (hasDisplayCutout) {
binding.cutoutShort.visible()
binding.cutoutShort.bindToPreference(preferences.cutoutShort())
}
binding.keepscreen.bindToPreference(preferences.keepScreenOn())
binding.longTap.bindToPreference(preferences.readWithLongTap())
binding.alwaysShowChapterTransition.bindToPreference(preferences.alwaysShowChapterTransition())
binding.autoWebtoonMode.bindToPreference(preferences.eh_useAutoWebtoon())
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
binding.trueColor.visible()
binding.trueColor.bindToPreference(preferences.trueColor())
}
}
/**
* Init the preferences for the pager reader.
*/
private fun initPagerPreferences() {
binding.webtoonPrefsGroup.invisible()
binding.pagerPrefsGroup.visible()
binding.scaleType.bindToPreference(preferences.imageScaleType(), 1)
binding.zoomStart.bindToPreference(preferences.zoomStart(), 1)
binding.cropBorders.bindToPreference(preferences.cropBorders())
binding.pageTransitions.bindToPreference(preferences.pageTransitions())
}
/**
* Init the preferences for the webtoon reader.
*/
private fun initWebtoonPreferences() {
binding.pagerPrefsGroup.invisible()
binding.webtoonPrefsGroup.visible()
binding.cropBordersWebtoon.bindToPreference(preferences.cropBordersWebtoon())
binding.webtoonSidePadding.bindToIntPreference(preferences.webtoonSidePadding(), R.array.webtoon_side_padding_values)
}
/**
* Binds a checkbox or switch view with a boolean preference.
*/
private fun CompoundButton.bindToPreference(pref: Preference<Boolean>) {
isChecked = pref.get()
setOnCheckedChangeListener { _, isChecked -> pref.set(isChecked) }
}
/**
* Binds a spinner to an int preference with an optional offset for the value.
*/
private fun Spinner.bindToPreference(pref: RxPreference<Int>, offset: Int = 0) {
onItemSelectedListener = IgnoreFirstSpinnerListener { position ->
pref.set(position + offset)
}
setSelection(pref.getOrDefault() - offset, false)
}
/**
* Binds a spinner to an int preference with an optional offset for the value.
*/
private fun Spinner.bindToPreference(pref: Preference<Int>, offset: Int = 0) {
onItemSelectedListener = IgnoreFirstSpinnerListener { position ->
pref.set(position + offset)
}
setSelection(pref.get() - offset, false)
}
/**
* Binds a spinner to an int preference. The position of the spinner item must
* correlate with the [intValues] resource item (in arrays.xml), which is a <string-array>
* of int values that will be parsed here and applied to the preference.
*/
private fun Spinner.bindToIntPreference(pref: Preference<Int>, @ArrayRes intValuesResource: Int) {
val intValues = resources.getStringArray(intValuesResource).map { it.toIntOrNull() }
onItemSelectedListener = IgnoreFirstSpinnerListener { position ->
pref.set(intValues[position]!!)
}
setSelection(intValues.indexOf(pref.get()), false)
}
}
| 22 |
Kotlin
|
18
| 471 |
a72df3df5073300e02054ee75dc990d196cd6db8
| 6,337 |
TachiyomiAZ
|
Apache License 2.0
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.