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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
Kotlin/1_TwoSum.kt
|
Roiw
| 198,638,278
| false
|
{"C#": 304577, "Python": 67487, "JavaScript": 11539, "Kotlin": 3096, "C++": 432}
|
class Solution {
fun twoSum(nums: IntArray, target: Int): IntArray {
for (i in 0..nums.size - 1) {
for (j in 0..nums.size - 1){
if (nums[i] + nums[j] == target && i != j){
return intArrayOf(i,j)
}
}
}
return intArrayOf()
}
}
| 0
|
C#
|
0
| 0
|
deb178dab743a4123204355de3e4603c63ea23f2
| 342
|
LeetCode
|
MIT License
|
app/src/main/java/com/mhdsuhail/ratemyproperty/ui/homescreen/HomeScreeViewModel.kt
|
mhdsuhail172
| 600,567,194
| false
| null |
package com.mhdsuhail.ratemyproperty.ui.homescreen
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.mhdsuhail.ratemyproperty.data.PropertyDetails
import com.mhdsuhail.ratemyproperty.data.PropertyRepository
import com.mhdsuhail.ratemyproperty.util.Routes
import com.mhdsuhail.ratemyproperty.util.UiEvent
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.channels.Channel
import kotlinx.coroutines.flow.receiveAsFlow
import kotlinx.coroutines.launch
import javax.inject.Inject
@HiltViewModel
class HomeScreeViewModel @Inject constructor(private val propertyRepository: PropertyRepository) :
ViewModel() {
private val _uiEvent = Channel<UiEvent>()
val uiEvent = _uiEvent.receiveAsFlow()
val favoriteProperties = propertyRepository.getAllFavouritePropertyDetails()
val myListings = propertyRepository.getAllPropertiesDetails()
private var removedPropertyDetails: PropertyDetails? = null
fun onEvent(event: HomeScreenEvents) {
when (event) {
is HomeScreenEvents.OnClickFavourite -> {
viewModelScope.launch {
var favstate = false
if (!event.propertyDetails.favourite) {
favstate = true
}
propertyRepository.updatePropertyDetails(event.propertyDetails.copy(favourite = favstate))
var actionSting: String? = null
var uiMessage: String = ""
if (favstate) {
uiMessage = "Added to"
} else {
uiMessage = "Removed from"
actionSting = "UNDO"
}
sendUiEvent(
UiEvent.ShowSnackbar(
message = " $uiMessage favourites",
action = actionSting
)
)
}
}
is HomeScreenEvents.OnClickPropertyCard -> {
sendUiEvent(UiEvent.Navigate(Routes.PROP_VIEW_PAGE + "?prop_uri=${event.propertyDetails.uri}"))
}
is HomeScreenEvents.OnClickUndoAddToFav -> {
viewModelScope.launch {
removedPropertyDetails?.let {
propertyRepository.updatePropertyDetails(it.copy(favourite = true))
}
}
}
}
}
private fun sendUiEvent(event: UiEvent) {
viewModelScope.launch {
_uiEvent.send(event)
}
}
}
| 0
|
Kotlin
|
0
| 4
|
20bc9c664aab2bb441b5b33685131e9ce53bf0a5
| 2,642
|
RateMyProperty
|
MIT License
|
app/src/main/java/com/moviebag/unofficial/presentation/splash/SplashActivity.kt
|
ajayverma16305
| 344,219,499
| false
| null |
package com.moviebag.unofficial.presentation.splash
import android.animation.ObjectAnimator
import android.animation.PropertyValuesHolder
import android.graphics.drawable.AnimationDrawable
import android.os.Bundle
import android.os.Handler
import android.view.View
import android.view.WindowManager
import android.view.animation.DecelerateInterpolator
import android.view.animation.OvershootInterpolator
import androidx.appcompat.app.AppCompatActivity
import androidx.core.animation.doOnEnd
import com.moviebag.unofficial.R
import com.moviebag.unofficial.presentation.home.HomeActivity
import kotlinx.android.synthetic.main.activity_splash.*
class SplashActivity : AppCompatActivity() {
private val handler = Handler()
override fun onCreate(savedInstanceState: Bundle?) {
window.setFlags(WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS, WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS)
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_splash)
setupAnimationOfViews()
handler.postDelayed({
HomeActivity.start(this)
supportFinishAfterTransition()
}, 3000)
}
private fun setupAnimationOfViews() {
imageViewForeground.post {
ObjectAnimator.ofFloat(imageViewForeground, View.Y, imageViewForeground.height.toFloat(), 0f).apply {
duration = 1000
interpolator = OvershootInterpolator()
start()
}
}
/*
img_logo.post {
val scaleX = PropertyValuesHolder.ofFloat(View.SCALE_X, 1.0f, 1.3f, 1.0f)
val scaleY = PropertyValuesHolder.ofFloat(View.SCALE_Y, 1.0f, 1.3f, 1.0f)
ObjectAnimator.ofPropertyValuesHolder(img_logo, scaleX, scaleY).apply {
duration = 1000
startDelay = 750L
start()
doOnEnd { (img_logo.drawable as AnimationDrawable).start() }
}
}*/
text.post {
ObjectAnimator.ofFloat(text, View.ALPHA, 0f, 1f).apply {
duration = 1250
startDelay = 1750L
interpolator = DecelerateInterpolator(1.2f)
start()
}
}
}
override fun onPause() {
super.onPause()
handler.removeCallbacksAndMessages(null)
(img_logo.drawable as? AnimationDrawable)?.stop()
}
}
| 0
|
Kotlin
|
0
| 0
|
801dc97a9bb310123a96e7fef0da8b53a0e8e222
| 2,416
|
MovieBag
|
MIT License
|
lab04-viewmodel/app/src/main/java/th/ac/kku/cis/lab04_viewmodel/StudentModel.kt
|
tanapattara
| 721,514,655
| false
|
{"Kotlin": 49235}
|
package th.ac.kku.cis.lab04_viewmodel
data class StudentModel(
val id:Int,
val name:String,
val studentId:String)
| 0
|
Kotlin
|
0
| 0
|
b9da8d4daa3a77544098edc35b60fb428f6c3ad5
| 127
|
android-jetpack-compose-lab
|
MIT License
|
cxrv/src/main/kotlin/com/xiaocydx/cxrv/internal/_ArrayList.kt
|
xiaocydx
| 460,257,515
| false
|
{"Kotlin": 1336945}
|
/*
* Copyright 2022 xiaocydx
*
* 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.xiaocydx.cxrv.internal
import java.util.*
/**
* clone当前ArrayList再遍历
*/
@Suppress("UNCHECKED_CAST")
internal inline fun <E> ArrayList<E>.cloneAccessEach(action: (E) -> Unit) {
(clone() as ArrayList<E>).accessEach(action)
}
/**
* clone当前ArrayList再遍历
*/
@Suppress("UNCHECKED_CAST")
internal inline fun <E> ArrayList<E>.cloneAccessEachIndexed(action: (index: Int, E) -> Unit) {
(clone() as ArrayList<E>).accessEachIndexed(action)
}
/**
* 用于频繁遍历访问元素的场景,减少迭代器对象的创建
*/
internal inline fun <E> ArrayList<E>.accessEach(action: (E) -> Unit) {
for (index in this.indices) action(get(index))
}
/**
* 用于频繁遍历访问元素的场景,减少迭代器对象的创建
*/
internal inline fun <E> ArrayList<E>.accessEachIndexed(action: (index: Int, E) -> Unit) {
for (index in this.indices) action(index, get(index))
}
/**
* 用于频繁遍历访问元素的场景,减少迭代器对象的创建
*/
internal inline fun <E> ArrayList<E>.reverseAccessEach(action: (E) -> Unit) {
for (index in this.indices.reversed()) action(get(index))
}
internal fun <E> ArrayList<E>.toUnmodifiableList(): List<E> = Collections.unmodifiableList(this)
internal fun <E> ArrayList<E>.swap(from: Int, to: Int) = Collections.swap(this, from, to)
internal fun <E> Sequence<E>.toArrayList() = ArrayList<E>().also(::toCollection)
| 0
|
Kotlin
|
0
| 9
|
2a6cf952830415e13ff13d954b301fa44245bc2a
| 1,844
|
CXRV
|
Apache License 2.0
|
src/main/kotlin/name/stepin/Application.kt
|
stepin
| 636,449,498
| false
|
{"Kotlin": 49893, "Shell": 5986}
|
package name.stepin
import org.springframework.boot.autoconfigure.SpringBootApplication
import org.springframework.boot.autoconfigure.r2dbc.R2dbcAutoConfiguration
import org.springframework.boot.runApplication
@SpringBootApplication(exclude = [R2dbcAutoConfiguration::class])
class Application
fun main(args: Array<String>) {
runApplication<Application>(*args)
}
| 0
|
Kotlin
|
0
| 4
|
44e0c5b571b25ebc9b1ceae2df4048eecd56f56a
| 370
|
kotlin-bootstrap-app
|
MIT License
|
app/src/main/java/com/puutaro/commandclick/proccess/edit/lib/SpinnerInstance.kt
|
puutaro
| 596,852,758
| false
|
{"Kotlin": 1472142, "JavaScript": 147417, "HTML": 19619}
|
package com.puutaro.commandclick.proccess.edit.lib
import android.content.Context
import android.widget.Spinner
import com.puutaro.commandclick.util.StringLength
object SpinnerInstance {
fun make(
context: Context?,
editableSpinnerList: List<String>,
onFixNormalSpinner: Boolean,
): Spinner {
if(
onFixNormalSpinner
) return Spinner(context)
val spinnerMaxStringNum = StringLength.maxCountFromList(editableSpinnerList)
val spinnerDialogStringNumThreshold = 30
return if(
spinnerMaxStringNum < spinnerDialogStringNumThreshold
) {
Spinner(context)
} else Spinner(context, Spinner.MODE_DIALOG)
}
}
| 2
|
Kotlin
|
3
| 54
|
000db311f5780b2861a2143f7985507b06cae5f1
| 724
|
CommandClick
|
MIT License
|
chat/src/main/java/com/crafttalk/chat/data/repository/ChatBehaviorRepository.kt
|
AndSky90
| 400,089,101
| true
|
{"Kotlin": 334797}
|
package com.crafttalk.chat.data.repository
import com.crafttalk.chat.data.api.socket.SocketApi
import com.crafttalk.chat.domain.repository.IChatBehaviorRepository
import com.crafttalk.chat.initialization.ChatMessageListener
import com.crafttalk.chat.presentation.ChatInternetConnectionListener
import com.crafttalk.chat.utils.ChatStatus
import javax.inject.Inject
class ChatBehaviorRepository
@Inject constructor(
private val socketApi: SocketApi
) : IChatBehaviorRepository {
override fun setInternetConnectionListener(listener: ChatInternetConnectionListener) {
socketApi.setInternetConnectionListener(listener)
}
override fun setMessageListener(listener: ChatMessageListener) {
socketApi.setMessageListener(listener)
}
override fun setStatusChat(newStatus: ChatStatus) {
if (newStatus in listOf(ChatStatus.ON_CHAT_SCREEN_FOREGROUND_APP, ChatStatus.ON_CHAT_SCREEN_BACKGROUND_APP)) {
socketApi.cleanBufferMessages()
}
socketApi.chatStatus = newStatus
}
override fun getStatusChat(): ChatStatus = socketApi.chatStatus
override fun createSessionChat() {
socketApi.initSocket()
}
override fun destroySessionChat() {
socketApi.destroySocket()
}
override fun dropChat() {
socketApi.dropChat()
}
override fun giveFeedbackOnOperator(countStars: Int) {
socketApi.giveFeedbackOnOperator(countStars)
}
}
| 0
| null |
0
| 0
|
23a69456b0616dc4cf26c1915edc4c00d3f783c5
| 1,453
|
crafttalk-android-sdk
|
Apache License 2.0
|
server/install/src/main/kotlin/org/jetbrains/bsp/bazel/install/BazelBspEnvironmentCreator.kt
|
JetBrains
| 826,262,028
| false
|
{"Kotlin": 3064918, "Starlark": 370388, "Java": 165158, "Scala": 37245, "Python": 34754, "Lex": 17493, "Dockerfile": 8674, "Shell": 7379, "HTML": 1310, "Rust": 680, "Go": 428, "C++": 113}
|
package org.jetbrains.bsp.bazel.install
import ch.epfl.scala.bsp4j.BspConnectionDetails
import java.nio.file.Path
class BazelBspEnvironmentCreator(projectRootDir: Path, private val discoveryDetails: BspConnectionDetails) :
EnvironmentCreator(projectRootDir) {
override fun create() {
createDotBazelBsp()
createDotBsp(discoveryDetails)
}
}
| 2
|
Kotlin
|
18
| 45
|
1d79484cfdf8fc31d3a4b214655e857214071723
| 355
|
hirschgarten
|
Apache License 2.0
|
src/main/kotlin/jempasam/hexlink/utils/LoadableRegistry.kt
|
Jempasam
| 674,693,089
| false
|
{"Kotlin": 314532, "Java": 5001, "mcfunction": 299}
|
package jempasam.hexlink.utils
import com.mojang.serialization.Lifecycle
import net.minecraft.tag.TagKey
import net.minecraft.util.Identifier
import net.minecraft.util.math.random.Random
import net.minecraft.util.registry.Registry
import net.minecraft.util.registry.RegistryEntry
import net.minecraft.util.registry.RegistryKey
import net.minecraft.util.registry.SimpleRegistry
class LoadableRegistry<T>(key: RegistryKey<out Registry<T>>, lifecycle: Lifecycle): Registry<T>(key, lifecycle) {
private var inner = SimpleRegistry<T>(key, lifecycle, null)
private var locked = true
fun clear(){
inner = SimpleRegistry(key, lifecycle, null)
locked=false
}
fun lock(){
locked=true
}
fun register(id: Identifier, value: T) {
if (locked) throw IllegalStateException("Registry is locked")
Registry.register(inner, id, value)
}
override fun iterator() = inner.iterator()
override fun get(id: Identifier?) = inner.get(id)
override fun get(index: Int) = inner.get(index)
override fun size() = inner.size()
override fun getLifecycle() = inner.lifecycle
override fun getIds() = inner.ids
override fun getEntrySet() = inner.entrySet
override fun getKeys() = inner.keys
override fun getRandom(random: Random?) = inner.getRandom(random)
override fun containsId(id: Identifier?) = inner.containsId(id)
override fun freeze() = inner.freeze()
override fun getEntry(rawId: Int) = inner.getEntry(rawId)
override fun streamEntries() = inner.streamEntries()
override fun streamTagsAndEntries() = inner.streamTagsAndEntries()
override fun streamTags() = inner.streamTags()
override fun clearTags() = inner.clearTags()
override fun populateTags(tagEntries: MutableMap<TagKey<T>, MutableList<RegistryEntry<T>>>?) = inner.populateTags(tagEntries)
override fun containsTag(tag: TagKey<T>?) = inner.containsTag(tag)
override fun getOrCreateEntryList(tag: TagKey<T>?) = inner.getOrCreateEntryList(tag)
override fun getEntryList(tag: TagKey<T>?) = inner.getEntryList(tag)
override fun getEntry(key: RegistryKey<T>) = inner.getEntry(key)
override fun createEntry(value: T) = inner.createEntry(value)
override fun getOrCreateEntryDataResult(key: RegistryKey<T>?) = inner.getOrCreateEntryDataResult(key)
override fun getOrCreateEntry(key: RegistryKey<T>?) = inner.getOrCreateEntry(key)
override fun contains(key: RegistryKey<T>?) = inner.contains(key)
override fun getEntryLifecycle(entry: T) = inner.getEntryLifecycle(entry)
override fun getId(value: T) = inner.getId(value)
override fun getKey(entry: T) = inner.getKey(entry)
override fun get(key: RegistryKey<T>?) = inner.get(key)
override fun getRawId(value: T?) = inner.getRawId(value)
}
| 1
|
Kotlin
|
1
| 1
|
1d4fac0db502a68921f1275c84eb9541f7f714fc
| 2,832
|
Hexlink
|
MIT License
|
src/main/kotlin/io/bloco/faker/components/Placeholdit.kt
|
blocoio
| 45,912,125
| false
|
{"Kotlin": 80930}
|
package io.bloco.faker.components
import io.bloco.faker.FakerComponent
import io.bloco.faker.FakerData
class Placeholdit(data: FakerData) : FakerComponent(data) {
@JvmOverloads
fun image(
size: String = "300x300",
format: String = "png",
backgroundColor: String? = null,
textColor: String? = null,
text: String? = null
): String {
require(size.matches(SIZE_REGEX.toRegex())) { "Size should be specified in format 300x300" }
require(SUPPORTED_FORMATS.contains(format)) { "Supported formats are ${SUPPORTED_FORMATS.joinToString(",")}" }
backgroundColor?.let {
require(it.matches(HEX_REGEX.toRegex())) { "backgroundColor must be a hex value without '#'" }
}
require(!(backgroundColor == null && textColor != null)) { "backgroundColor must be used with the textColor" }
textColor?.let {
require(it.matches(HEX_REGEX.toRegex())) { "textColor must be a hex value without '#'" }
}
var imageUrl = "$PLACEHOLDER_URL$size.$format"
backgroundColor?.let { imageUrl += "/$it" }
textColor?.let { imageUrl += "/$it" }
text?.let { imageUrl += "?text=$it" }
return imageUrl
}
companion object {
val SUPPORTED_FORMATS = listOf("png", "jpg", "jpeg", "gif")
private const val PLACEHOLDER_URL = "https://placehold.it/"
private const val SIZE_REGEX = "^[0-9]+x[0-9]+$"
private const val HEX_REGEX = "((?:^[0-9a-fA-F]{3}$)|(?:^[0-9a-fA-F]{6}$)){1}(?!.*[^0-9a-fA-F])"
}
}
| 0
|
Kotlin
|
26
| 183
|
6adc5aa63c3a14d4fd1ca12e71a649e2fed02eae
| 1,570
|
faker
|
MIT License
|
src/test/kotlin/com/wearefrancis/auth/dto/mapper/ReadUserByAdminDTOMapperTest.kt
|
WeAreFrancis
| 88,411,069
| false
| null |
package com.wearefrancis.auth.dto.mapper
import com.wearefrancis.auth.domain.User
import org.assertj.core.api.Assertions.assertThat
import org.junit.Before
import org.junit.Test
class ReadUserByAdminDTOMapperTest {
private lateinit var readUserByAdminDTOMapper: ReadUserByAdminDTOMapper
@Before
fun setUp() {
readUserByAdminDTOMapper = ReadUserByAdminDTOMapper()
}
@Test
fun convertShouldConvertUserToReadUserByAdminDTO() {
// GIVEN
val user = User(
email = "<EMAIL>",
enabled = true,
locked = true,
password = "<PASSWORD>",
role = User.Role.ADMIN,
username = "gleroy"
)
// WHEN
val readUserByAdminDTO = readUserByAdminDTOMapper.convert(user)
// THEN
assertThat(readUserByAdminDTO.email).isEqualTo(user.email)
assertThat(readUserByAdminDTO.enabled).isEqualTo(user.enabled)
assertThat(readUserByAdminDTO.id).isEqualTo(user.id)
assertThat(readUserByAdminDTO.locked).isEqualTo(!user.isAccountNonLocked)
assertThat(readUserByAdminDTO.role).isEqualTo(user.role)
assertThat(readUserByAdminDTO.username).isEqualTo(user.username)
}
}
| 0
|
Kotlin
|
0
| 2
|
2b358547485d4c0fb732bb880e65b800a099c56d
| 1,260
|
auth-service
|
Apache License 2.0
|
pixelgrid/src/main/kotlin/com/deflatedpickle/rawky/pixelgrid/api/LayerCategory.kt
|
DeflatedPickle
| 197,672,095
| false
| null |
package com.deflatedpickle.rawky.pixelgrid.api
enum class LayerCategory {
BACKGROUND,
UNDER_DECO,
GRID,
OVER_DECO,
CURSOR,
DEBUG,
}
| 7
|
Kotlin
|
6
| 27
|
b8859e8f706132574996a5157a99145515aac52e
| 156
|
Rawky
|
MIT License
|
kachetor/src/commonMain/kotlin/com/vipulasri/kachetor/FileSystemProvider.kt
|
vipulasri
| 754,452,913
| false
|
{"Kotlin": 27843}
|
/*
* Copyright 2024 <NAME>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.vipulasri.kachetor
import okio.FileSystem
import okio.Path
internal expect object FileSystemProvider {
val fileSystem: FileSystem
val cacheDirectoryPath: Path?
}
| 0
|
Kotlin
|
0
| 12
|
cc228665de4da48fba1ce74a38a8e6e2ba72f27e
| 774
|
kachetor
|
Apache License 2.0
|
grundlagen-tag-08-listenfunktionen-2-just1984/Aufgabe24/src/Aufgabe24.kt
|
just1984
| 639,436,580
| false
| null |
fun main() {
var namensliste = listOf("Lisa", "Marko", "Sebastian", "Marie", "Florian", "Henrik", "Lillie", "Martin")
// TODO 24a
println("Bitte gebe eine Zahl zwischen 1-8 ein:")
var index1 = readln()
var index2 = index1.toInt()
var namensAusgabe = namensliste[index2 -1]
println(namensAusgabe)
//Todo 24b
println("Bitte gebe zwei Zahlen zwischen 1-8 ein:")
var index3: String = readln()
var index4: String = readln()
var index5 = index3.toInt()
var index6 = index4.toInt()
var teilListe = namensliste.slice(index5 -1 until index6 -1)
println(teilListe)
}
| 0
|
Kotlin
|
0
| 0
|
df3e8b35fdc1c53e0d412e427f03ad5bf3cb12ee
| 616
|
school_progress_kotlin
|
MIT License
|
src/test/kotlin/fr/uphf/feature/detector/InfixFunctionDectectorSpek.kt
|
brunomateus
| 170,135,541
| false
|
{"Kotlin": 239889, "Shell": 14}
|
package fr.uphf.feature.detector
import fr.uphf.analyze.compileTo
import fr.uphf.analyze.getResult
import io.gitlab.arturbosch.detekt.api.Finding
import org.assertj.core.api.Assertions.*
import org.jetbrains.kotlin.psi.KtFile
import org.spekframework.spek2.Spek
import org.spekframework.spek2.style.gherkin.Feature
object InfixFunctionDectectorSpek : Spek({
Feature("Infix function") {
lateinit var file: KtFile
lateinit var code: String
Scenario("Infix Klass uses") {
Given("One infix function"){
code = """
infix fun Int.add(b : Int) : Int = this + b
fun main(){
val y = 10 add 20
}
""".trimIndent()
}
lateinit var result: Map<String, List<Finding>>
When("the file is analyzed") {
file = compileTo(code)
val detector = InfixFunctionDetector()
val findings = detector.analyze(file)
result = getResult(findings)
}
val nFinding = 1
Then("it should report $nFinding findings") {
assertThat(result.map { it.value.size }.sum()).isEqualTo(nFinding)
}
And("report 1 uses of infix function"){
assertThat(result["infix_func"]).hasSize(1)
}
}
}
})
| 0
|
Kotlin
|
0
| 0
|
91e0a2d181ac373fc581cd5b7039ef32e9437cf6
| 1,340
|
KotlinAstFeatureExtractor
|
MIT License
|
cottontaildb-core/src/main/kotlin/org/vitrivr/cottontail/core/queries/predicates/Predicate.kt
|
vitrivr
| 160,775,368
| false
|
{"Kotlin": 2769415, "TypeScript": 98011, "Java": 97672, "HTML": 38965, "ANTLR": 23679, "CSS": 8582, "SCSS": 1690, "JavaScript": 1441, "Dockerfile": 548}
|
package org.vitrivr.cottontail.core.queries.predicates
import org.vitrivr.cottontail.core.database.ColumnDef
import org.vitrivr.cottontail.core.queries.binding.Binding
import org.vitrivr.cottontail.core.queries.nodes.Node
import org.vitrivr.cottontail.core.queries.nodes.NodeWithCost
import org.vitrivr.cottontail.core.tuple.Tuple
/**
* A [Predicate] is a [Node] that is being evaluated as part of a Cottontail DB query.
*
* Generally, [Predicate]s are assumed to operate on [Tuple]s and usually affect a set of [ColumnDef]s in that [Tuple].
*
* @author <NAME>
* @version 1.5.0
*/
sealed interface Predicate : NodeWithCost {
/** Set of [ColumnDef] that are accessed by this [Predicate]. */
val columns: Set<Binding.Column>
}
| 24
|
Kotlin
|
20
| 38
|
bc4d0aa435aac78628fa7771dbf8333f1fe5a971
| 747
|
cottontaildb
|
MIT License
|
src/org/analogjs/entities/analog/AnalogSourceComponent.kt
|
analogjs
| 741,542,399
| false
|
{"Kotlin": 83806, "Java": 729}
|
package org.analogjs.entities.analog
import com.intellij.lang.ecmascript6.psi.ES6ImportDeclaration
import com.intellij.lang.javascript.psi.util.stubSafeChildren
import com.intellij.model.Pointer
import com.intellij.openapi.vfs.VirtualFileManager
import com.intellij.psi.PsiElement
import com.intellij.psi.PsiFile
import com.intellij.psi.util.CachedValueProvider.Result
import com.intellij.psi.util.PsiModificationTracker
import com.intellij.refactoring.suggested.createSmartPointer
import org.analogjs.analogScript
import org.analogjs.lang.AnalogFile
import org.angular2.Angular2DecoratorUtil
import org.angular2.entities.*
import org.angular2.entities.source.Angular2SourceUtil
class AnalogSourceComponent(file: AnalogFile) : AnalogSourceDirective(file), Angular2Component {
override val templateFile: PsiFile
get() = file
override val imports: Set<Angular2Entity>
get() = getCachedValue {
Result.create(resolveImports(), PsiModificationTracker.MODIFICATION_COUNT)
}
override val jsResolveScope: PsiElement?
get() = file.analogScript
override val jsExportScope: PsiElement?
get() = jsResolveScope
override val isScopeFullyResolved: Boolean
get() = true
override val ngContentSelectors: List<Angular2DirectiveSelector>
get() = getCachedValue {
Result.create(Angular2SourceUtil.getNgContentSelectors(file), file)
}
override val cssFiles: List<PsiFile>
get() = getCachedValue {
Result.create(findCssFiles(), VirtualFileManager.VFS_STRUCTURE_MODIFICATIONS, file)
}
override val attributes: Collection<Angular2DirectiveAttribute>
get() = emptyList()
override val directiveKind: Angular2DirectiveKind
get() = Angular2DirectiveKind.REGULAR
override fun createPointer(): Pointer<AnalogSourceComponent> {
val file = file.createSmartPointer()
return Pointer {
file.dereference()?.let { AnalogSourceComponent(it) }
}
}
override val isStandalone: Boolean
get() = true
private fun resolveImports() =
file.analogScript
?.stubSafeChildren
?.asSequence()
?.filterIsInstance<ES6ImportDeclaration>()
?.flatMap { import ->
import.importedBindings
.asSequence()
.flatMap { it.multiResolve(false).asSequence() }
.filter { it.isValidResult }
.mapNotNull { Angular2EntitiesProvider.getEntity(it.element) } +
import.importSpecifiers
.asSequence()
.flatMap { it.multiResolve(false).asSequence() }
.filter { it.isValidResult }
.mapNotNull { Angular2EntitiesProvider.getEntity(it.element) }
}
?.toSet()
?: emptySet()
private fun findCssFiles() =
Angular2SourceUtil.findCssFiles(getDefineMetadataProperty(Angular2DecoratorUtil.STYLE_URLS_PROP), true)
.plus(listOfNotNull(Angular2SourceUtil.getReferencedFile(getDefineMetadataProperty(Angular2DecoratorUtil.STYLE_URL_PROP), true)))
.toList()
}
| 4
|
Kotlin
|
0
| 7
|
37a32a7b23de1ae67c5e40ac911f7c901ed9b970
| 2,952
|
idea-plugin
|
MIT License
|
fyno-kotlin-core/src/main/java/io/fyno/kotlin_sdk/RequestHandler.kt
|
fynoio
| 574,803,067
| false
|
{"Kotlin": 147424, "Java": 38026}
|
package io.fyno.kotlin_sdk
import android.util.Log
import org.json.JSONObject
import java.io.BufferedWriter
import java.io.IOException
import java.io.OutputStream
import java.io.OutputStreamWriter
import java.net.HttpURLConnection
import java.net.URL
import javax.net.ssl.HttpsURLConnection
object RequestHandler {
@Throws(IOException::class)
fun requestPOST(r_url: String?, postDataParams: JSONObject?, method: String = "POST"): Int {
val url = URL(r_url)
val conn: HttpURLConnection = url.openConnection() as HttpURLConnection
conn.setRequestProperty("Content-Type", "application/json");
conn.setRequestProperty("Authorization", "Bearer ${FynoUser.getApi()}")
conn.readTimeout = 3000
conn.connectTimeout = 3000
conn.requestMethod = method
conn.doInput = true
conn.doOutput = true
val os: OutputStream = conn.outputStream
val writer = BufferedWriter(OutputStreamWriter(os, "UTF-8"))
if (postDataParams != null)
writer.write(postDataParams.toString())
writer.flush()
writer.close()
os.close()
val responseCode: Int = conn.responseCode // To Check for 200
Log.d("RequestPost", "requestPOST method = $method url = $url: "+conn.responseMessage,)
if (responseCode == HttpsURLConnection.HTTP_OK || responseCode == HttpsURLConnection.HTTP_CREATED || responseCode == HttpsURLConnection.HTTP_ACCEPTED) {
Log.i("RequestPost", "requestPOST: "+conn.responseMessage)
} else {
Log.e("RequestPost", "requestPOST: "+conn.responseMessage)
}
return responseCode
}
@Throws(IOException::class)
fun requestGET(r_url: String?, postDataParams: JSONObject? = null, method: String = "GET"): Int {
val url = URL(r_url)
val conn: HttpURLConnection = url.openConnection() as HttpURLConnection
conn.setRequestProperty("Content-Type", "application/json");
conn.setRequestProperty("Authorization", "Bearer ${FynoUser.getApi()}")
conn.readTimeout = 3000
conn.connectTimeout = 3000
conn.requestMethod = method
conn.doInput = true
conn.doOutput = true
val os: OutputStream = conn.outputStream
val writer = BufferedWriter(OutputStreamWriter(os, "UTF-8"))
if(postDataParams != null)
writer.write(postDataParams.toString())
writer.flush()
writer.close()
os.close()
val responseCode: Int = conn.responseCode // To Check for 200
Log.d("RequestGet", "requestGET: "+conn.responseMessage)
return responseCode;
}
}
| 0
|
Kotlin
|
0
| 1
|
a228c3466600f002ba0aedf4013c1baaf25c60c5
| 2,658
|
kotlin-sdk
|
MIT License
|
app/src/main/java/com/demo/jsonpreviewer/EditJsonViewModel.kt
|
dazhaoDai
| 610,672,510
| false
| null |
package com.demo.jsonpreviewer
import android.content.Context
import android.preference.PreferenceManager
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import okio.buffer
import okio.source
import java.io.InputStream
import java.nio.charset.Charset
/**
*
* Created by dazhao.dai on 2023/2/23
*/
class EditJsonViewModel() : ViewModel() {
val jsonData: MutableLiveData<String?> = MutableLiveData()
fun loadAdConfig(context: Context) {
var configString: String? = null
val inputStream: InputStream? =
context.resources?.openRawResource(R.raw.json_file)
try {
configString = inputStream?.source()?.buffer()?.readString(Charset.defaultCharset())
} catch (e: Exception) {
e.printStackTrace()
} finally {
try {
inputStream?.close()
} catch (e: Exception) {
e.printStackTrace()
}
}
jsonData.value = configString
}
}
| 0
|
Kotlin
|
0
| 8
|
5057b9bb72130f3822b5581c40ea04725ef7394d
| 1,018
|
JsonPreviewer
|
Apache License 2.0
|
app/src/main/java/es/refil/bottlesadmin/di/AppModule.kt
|
carloscabruja
| 644,538,779
| false
| null |
package es.refil.bottlesadmin.di
import android.app.Application
import android.content.Context
import com.google.firebase.firestore.CollectionReference
import com.google.firebase.firestore.ktx.firestore
import com.google.firebase.ktx.Firebase
import com.google.mlkit.vision.barcode.common.Barcode
import com.google.mlkit.vision.codescanner.GmsBarcodeScanner
import com.google.mlkit.vision.codescanner.GmsBarcodeScannerOptions
import com.google.mlkit.vision.codescanner.GmsBarcodeScanning
import dagger.Module
import dagger.Provides
import dagger.hilt.InstallIn
import dagger.hilt.components.SingletonComponent
import es.refil.bottlesadmin.common.Constants.FIRESTORE_COLLECTION_BOTTLES
import es.refil.bottlesadmin.data.repository.BottlesRepositoryImpl
import es.refil.bottlesadmin.domain.repository.BottlesRepository
import es.refil.bottlesadmin.domain.use_case.AddBottleToFirestore
import es.refil.bottlesadmin.domain.use_case.DeleteBottleFromFirestore
import es.refil.bottlesadmin.domain.use_case.GetBottlesFromFirestore
import es.refil.bottlesadmin.domain.use_case.StartScanning
import es.refil.bottlesadmin.domain.use_case.UseCases
import javax.inject.Singleton
@Module
@InstallIn(SingletonComponent::class)
object AppModule {
@Provides
@Singleton
fun provideContext(app: Application): Context {
return app.applicationContext
}
@Provides
@Singleton
fun provideBarCodeOptions(): GmsBarcodeScannerOptions {
return GmsBarcodeScannerOptions.Builder()
.setBarcodeFormats(Barcode.FORMAT_ALL_FORMATS)
.build()
}
@Provides
@Singleton
fun provideBarCodeScanner(
context: Context,
options: GmsBarcodeScannerOptions
): GmsBarcodeScanner {
return GmsBarcodeScanning.getClient(context, options)
}
@Provides
@Singleton
fun provideBottlesRef() = Firebase.firestore.collection(FIRESTORE_COLLECTION_BOTTLES)
@Provides
@Singleton
fun provideBottlesRepository(
bottlesRef: CollectionReference,
scanner: GmsBarcodeScanner
): BottlesRepository = BottlesRepositoryImpl(bottlesRef, scanner)
@Provides
@Singleton
fun provideBottlesUseCases(bottlesRepository: BottlesRepository) = UseCases(
getBottlesFromFirestore = GetBottlesFromFirestore(bottlesRepository),
addBottleToFirestore = AddBottleToFirestore(bottlesRepository),
deleteBottleFromFirestore = DeleteBottleFromFirestore(bottlesRepository),
startScanning = StartScanning(bottlesRepository)
)
}
| 0
|
Kotlin
|
0
| 2
|
d85c77e380f4f0d278239fb6bf80318c0e403df6
| 2,548
|
BottlesAdmin
|
MIT License
|
src/main/kotlin/derivean/rest/root/hero/endpoint/DeleteEndpoint.kt
|
marek-hanzal
| 259,577,282
| false
| null |
package derivean.rest.root.hero.endpoint
import derivean.storage.repository.HeroRepository
import io.ktor.application.*
import io.ktor.auth.*
import io.ktor.routing.*
import io.ktor.util.*
import leight.container.IContainer
import leight.http.withAnyRole
import leight.mapper.AbstractActionMapper
import leight.rest.*
@KtorExperimentalAPI
class DeleteEndpoint(container: IContainer) : AbstractActionEndpoint(container) {
private val deleteMapper: DeleteMapper by container.lazy()
override fun install(routing: Routing) {
"/api/root/hero/delete".let { url ->
discovery {
name = "root.hero.delete"
link = url
description = "Delete a Hero"
}
routing.authenticate {
withAnyRole("root") {
post(url) {
resolve(call, deleteMapper)
}
}
}
}
}
}
class DeleteMapper(container: IContainer) : AbstractActionMapper<ApplicationRequest<DeleteMapper.Request>, Response<out Any>>(container) {
private val heroRepository: HeroRepository by container.lazy()
override fun resolve(item: ApplicationRequest<Request>) = try {
ok(storage.write {
heroRepository.delete(item.request.id)
})
} catch (e: Throwable) {
logger.error(e.message, e)
internalServerError(ValidationResponse.build {
message = "Some ugly internal server error happened!"
})
}
data class Request(val id: String)
}
| 112
|
Kotlin
|
0
| 1
|
7a485228438c5fb9a61b1862e8164f5e87361e4a
| 1,340
|
DeRivean
|
Apache License 2.0
|
src/main/kotlin/derivean/rest/root/hero/endpoint/DeleteEndpoint.kt
|
marek-hanzal
| 259,577,282
| false
| null |
package derivean.rest.root.hero.endpoint
import derivean.storage.repository.HeroRepository
import io.ktor.application.*
import io.ktor.auth.*
import io.ktor.routing.*
import io.ktor.util.*
import leight.container.IContainer
import leight.http.withAnyRole
import leight.mapper.AbstractActionMapper
import leight.rest.*
@KtorExperimentalAPI
class DeleteEndpoint(container: IContainer) : AbstractActionEndpoint(container) {
private val deleteMapper: DeleteMapper by container.lazy()
override fun install(routing: Routing) {
"/api/root/hero/delete".let { url ->
discovery {
name = "root.hero.delete"
link = url
description = "Delete a Hero"
}
routing.authenticate {
withAnyRole("root") {
post(url) {
resolve(call, deleteMapper)
}
}
}
}
}
}
class DeleteMapper(container: IContainer) : AbstractActionMapper<ApplicationRequest<DeleteMapper.Request>, Response<out Any>>(container) {
private val heroRepository: HeroRepository by container.lazy()
override fun resolve(item: ApplicationRequest<Request>) = try {
ok(storage.write {
heroRepository.delete(item.request.id)
})
} catch (e: Throwable) {
logger.error(e.message, e)
internalServerError(ValidationResponse.build {
message = "Some ugly internal server error happened!"
})
}
data class Request(val id: String)
}
| 112
|
Kotlin
|
0
| 1
|
7a485228438c5fb9a61b1862e8164f5e87361e4a
| 1,340
|
DeRivean
|
Apache License 2.0
|
security/domain/src/main/kotlin/com/kuki/security/domain/event/UserDeleted.kt
|
akuchalskij
| 649,018,448
| false
| null |
package com.kuki.security.domain.event
import com.kuki.framework.domain.Event
import com.kuki.security.domain.valueobject.UserId
import kotlinx.datetime.Instant
import kotlinx.serialization.Serializable
@Serializable
data class UserDeleted(
val userId: UserId,
val deletedAt: Instant,
) : Event
| 0
|
Kotlin
|
0
| 1
|
a72ecdf553a62d7d5b472362f50284e634e44207
| 305
|
kotlin-ktor-ddd-es-cqrs
|
Apache License 2.0
|
spring-crm-rest/src/main/kotlin/com/thijsboehme/springdemo/rest/CustomerNotFoundException.kt
|
ThijsBoehme
| 290,450,294
| false
| null |
package com.thijsboehme.springdemo.rest
class CustomerNotFoundException: RuntimeException {
constructor(): super()
constructor(message: String?): super(message)
constructor(message: String?, cause: Throwable?): super(message, cause)
constructor(cause: Throwable?): super(cause)
constructor(message: String?, cause: Throwable?, enableSuppression: Boolean, writableStackTrace: Boolean): super(
message,
cause,
enableSuppression,
writableStackTrace
)
}
| 0
|
Kotlin
|
0
| 0
|
48031da2cbc99314b17a05d1f6417700b26b26c4
| 507
|
portfolio-spring-hibernate-udemy
|
MIT License
|
app/src/main/java/it/unibs/mp/horace/backend/RoomJournal.kt
|
H3isenb3rg
| 604,173,455
| false
| null |
package it.unibs.mp.horace.backend
class RoomJournal {
}
| 10
|
Kotlin
|
0
| 0
|
cad49fbf830280c3750f7f67d94c711067aab33f
| 57
|
MobileProgramming2023
|
MIT License
|
app/src/main/java/com/italiasimon/themoviedatabase/ui/adapter/FavoriteAdapter.kt
|
simonitalia
| 450,519,134
| false
|
{"Kotlin": 57774}
|
package com.italiasimon.themoviedatabase.ui.adapter
import android.view.LayoutInflater
import android.view.ViewGroup
import androidx.annotation.LayoutRes
import androidx.databinding.DataBindingUtil
import androidx.recyclerview.widget.DiffUtil
import androidx.recyclerview.widget.ListAdapter
import androidx.recyclerview.widget.RecyclerView
import com.italiasimon.themoviedatabase.R
import com.italiasimon.themoviedatabase.databinding.ItemFavoriteBinding
import com.italiasimon.themoviedatabase.models.Movie
class FavoriteMovieAdapter(
private val listener: MovieRecyclerViewAdapterListener,
) : ListAdapter<Movie, FavoriteMovieAdapter.ViewHolder>(AdapterDiffCallback()) {
/*
* Diff Util for managing Data changes
*/
class AdapterDiffCallback: DiffUtil.ItemCallback<Movie>() {
override fun areItemsTheSame(oldItem: Movie, newItem: Movie): Boolean {
return oldItem.id == newItem.id
}
override fun areContentsTheSame(oldItem: Movie, newItem: Movie): Boolean {
return oldItem.id == newItem.id
}
}
/*
* Bridge between Adapter class and xml ui Views
* Setting Views with data handled by BindingAdapters
*/
class ViewHolder(val viewDataBinding: ItemFavoriteBinding): RecyclerView.ViewHolder(viewDataBinding.root) {
companion object {
@LayoutRes
val LAYOUT = R.layout.item_favorite
}
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
val withDataBinding: ItemFavoriteBinding = DataBindingUtil.inflate(
LayoutInflater.from(parent.context),
ViewHolder.LAYOUT,
parent,
false)
return ViewHolder(withDataBinding)
}
// bridge between data item and item view (ui layout)
override fun onBindViewHolder(holder: ViewHolder, position: Int) {
val item = getItem(position)
holder.viewDataBinding.also {
it.favorite = item // connects to layout item data variable
}
// pass favorite item pressed back to listener
holder.itemView.setOnClickListener {
listener.onMovieItemPressed(item)
}
}
}
| 0
|
Kotlin
|
0
| 0
|
c69c4bfc307b2a8984bf3e29eec7457b7dd9b24f
| 2,213
|
the-movie-database
|
Apache License 2.0
|
DesktopApp/src/main/kotlin/custom/Theme.kt
|
nisrulz
| 366,738,555
| false
| null |
package custom
import androidx.compose.material.MaterialTheme
import androidx.compose.material.lightColors
import androidx.compose.runtime.Composable
private val CustomLightColorPalette = lightColors(
primary = MyPrimaryColor,
primaryVariant = MyBorderColor,
secondary = MyLightBgColor
)
@Composable
fun DesktopTheme(content: @Composable() () -> Unit) {
MaterialTheme(
colors = CustomLightColorPalette,
content = content
)
}
| 0
|
Kotlin
|
0
| 4
|
8690a040c97444f5445d886bd10a012d42b3ab40
| 463
|
JetSetCompose
|
Apache License 2.0
|
app/src/main/kotlin/cz/drekorian/android/flickr/ui/Extensions.kt
|
Drekorian
| 788,443,614
| false
|
{"Kotlin": 58339}
|
package cz.drekorian.android.flickr.ui
import androidx.compose.foundation.layout.PaddingValues
import androidx.compose.ui.unit.Dp
import androidx.compose.ui.unit.LayoutDirection
operator fun PaddingValues.plus(other: PaddingValues): PaddingValues =
CompoundPaddingValues(this, other)
private class CompoundPaddingValues(
private val first: PaddingValues,
private val second: PaddingValues,
) : PaddingValues {
override fun calculateBottomPadding(): Dp {
return first.calculateBottomPadding() + second.calculateBottomPadding()
}
override fun calculateLeftPadding(layoutDirection: LayoutDirection): Dp {
return first.calculateLeftPadding(layoutDirection) + second.calculateLeftPadding(layoutDirection)
}
override fun calculateRightPadding(layoutDirection: LayoutDirection): Dp {
return first.calculateRightPadding(layoutDirection) + second.calculateRightPadding(layoutDirection)
}
override fun calculateTopPadding(): Dp {
return first.calculateTopPadding() + second.calculateTopPadding()
}
}
| 3
|
Kotlin
|
0
| 0
|
d93a16d3aebb70d6503e1172d0ca24ae1c3cf29a
| 1,072
|
flickr
|
MIT License
|
presentation/src/main/java/com/nemesis/rio/presentation/profile/overview/character/mplus/scores/CharacterMythicPlusScoresDataActionsHandler.kt
|
N3-M3-S1S
| 370,791,918
| false
| null |
package com.nemesis.rio.presentation.profile.overview.character.mplus.scores
interface CharacterMythicPlusScoresDataActionsHandler {
fun onSelectScoresTypeClicked()
fun onSelectSeasonClicked()
}
| 0
|
Kotlin
|
0
| 0
|
62dc309a7b4b80ff36ea624bacfa7b00b5d8607e
| 204
|
rio
|
MIT License
|
common/src/main/kotlin/tech/cuda/woden/common/service/TeamService.kt
|
cuda-tech
| 234,125,581
| false
|
{"Kotlin": 532433, "JavaScript": 97771, "Vue": 95927, "CSS": 10200, "Dockerfile": 267, "HTML": 208}
|
/*
* 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 tech.cuda.woden.common.service
import me.liuwj.ktorm.database.Database
import me.liuwj.ktorm.dsl.and
import me.liuwj.ktorm.dsl.asc
import me.liuwj.ktorm.dsl.eq
import me.liuwj.ktorm.dsl.inList
import me.liuwj.ktorm.global.addEntity
import me.liuwj.ktorm.global.global
import tech.cuda.woden.common.i18n.I18N
import tech.cuda.woden.common.service.dao.TeamDAO
import tech.cuda.woden.common.service.dto.TeamDTO
import tech.cuda.woden.common.service.dto.toTeamDTO
import tech.cuda.woden.common.service.exception.DuplicateException
import tech.cuda.woden.common.service.exception.NotFoundException
import tech.cuda.woden.common.service.po.TeamPO
import java.time.LocalDateTime
/**
* @author Jensen Qi <jinxiu.qi@alu.hit.edu.cn>
* @since 0.1.0
*/
object TeamService : Service(TeamDAO) {
/**
* 分页查询项目组信息
* 如果提供了[pattern],则进行模糊查询
*/
fun listing(
page: Int? = null,
pageSize: Int? = null,
pattern: String? = null,
ids: List<Int>? = null
): Pair<List<TeamDTO>, Int> {
val conditions = mutableListOf(TeamDAO.isRemove eq false)
if (ids != null && ids.isNotEmpty()) {
conditions.add(TeamDAO.id.inList(ids) eq true)
}
val (teams, count) = batch<TeamPO>(
pageId = page,
pageSize = pageSize,
filter = conditions.reduce { a, b -> a and b },
like = TeamDAO.name.match(pattern),
orderBy = TeamDAO.id.asc()
)
return teams.map { it.toTeamDTO() } to count
}
/**
* 通过[id]查找项目组信息
* 如果找不到或已被删除,则返回 null
*/
fun findById(id: Int) = find<TeamPO>(where = (TeamDAO.isRemove eq false) and (TeamDAO.id eq id))?.toTeamDTO()
/**
* 通过[name]查找项目组信息
* 如果找不到或已被删除,则返回 null
*/
fun findByName(name: String) =
find<TeamPO>(where = (TeamDAO.isRemove eq false) and (TeamDAO.name eq name))?.toTeamDTO()
/**
* 通过文件路径查找项目组
* 如果找不到或已被删除,则返回 null
*/
fun findByFilePath(path: String) = findByName(path.trimStart('/').split('/').first())
/**
* 创建名称为[name]项目组
* 如果已存在名称为[name]的项目组,则抛出 DuplicateException
*/
fun create(name: String): TeamDTO = Database.global.useTransaction {
find<TeamPO>(where = (TeamDAO.isRemove eq false) and (TeamDAO.name eq name))?.let {
throw DuplicateException(I18N.team, it.name, I18N.existsAlready)
}
val team = TeamPO {
this.name = name
this.isRemove = false
this.createTime = LocalDateTime.now()
this.updateTime = LocalDateTime.now()
}
TeamDAO.addEntity(team)
return team.toTeamDTO()
}
/**
* 更新项目组[id]信息
* 如果给定的项目组[id]不存在或已被删除,则抛出 NotFoundException
* 如果试图更新[name],且已存在名称为[name]的项目组,则抛出 DuplicateException
*/
fun update(id: Int, name: String? = null): TeamDTO = Database.global.useTransaction {
val team = find<TeamPO>(where = (TeamDAO.isRemove eq false) and (TeamDAO.id eq id))
?: throw NotFoundException(I18N.team, id, I18N.notExistsOrHasBeenRemove)
name?.let {
findByName(name)?.let { throw DuplicateException(I18N.team, name, I18N.existsAlready) }
team.name = name
}
anyNotNull(name)?.let {
team.updateTime = LocalDateTime.now()
team.flushChanges()
}
return team.toTeamDTO()
}
/**
* 删除项目组[id]
* 如果指定的项目组[id]不存在或已被删除,则抛出 NotFoundException
*/
fun remove(id: Int) = Database.global.useTransaction {
val team = find<TeamPO>(where = (TeamDAO.isRemove eq false) and (TeamDAO.id eq id))
?: throw NotFoundException(I18N.team, id, I18N.notExistsOrHasBeenRemove)
team.isRemove = true
team.updateTime = LocalDateTime.now()
team.flushChanges()
}
/**
* 检查[teamIds]对应的项目组是否都存在,如果存在则返回,否则抛出 NotFoundException
*/
fun checkTeamsAllExistsAndReturn(teamIds: Set<Int>): List<TeamDTO> {
val teams = listing(page = 1, pageSize = teamIds.size, ids = teamIds.toList()).first
if (teamIds.size != teams.size) {
val exists = teams.map { it.id }.toSet()
val missing = teamIds.filter { !exists.contains(it) }.joinToString(",")
throw NotFoundException(I18N.team, missing, I18N.notExistsOrHasBeenRemove)
}
return teams
}
}
| 0
|
Kotlin
|
0
| 0
|
2efc2de1cad2646ea129637752b15d868ca13c7d
| 4,951
|
woden-deprecated
|
Apache License 2.0
|
data/src/main/java/uoc/cbonache/tfg/data/repository/query/Query.kt
|
cbonacheuoc
| 109,753,411
| true
|
{"Kotlin": 144808, "Java": 6706}
|
package uoc.cbonache.tfg.data.repository.query
import uoc.cbonache.tfg.Result
/**
* Created by Borja on 21/3/17.
*/
interface Query {
fun queryAll(parameters: HashMap<String, *>? = null, queryable: Any? = null): Result<Collection<*>, *> {
return Result.Failure()
}
fun query(parameters: HashMap<String, *>? = null, queryable: Any? = null): Result<*, *> {
return Result.Failure()
}
}
| 0
|
Kotlin
|
0
| 1
|
c6c3cdc87eb96aaf179a6442111371aebe0a80dc
| 420
|
Transpdroid-Android-App
|
Apache License 2.0
|
app/src/main/java/com/tc/gamegallery/domain/Screenshot.kt
|
JerbiJ456
| 804,320,356
| false
|
{"Kotlin": 128407}
|
package com.tc.gamegallery.domain
data class Screenshot(
val image: String
)
| 0
|
Kotlin
|
0
| 0
|
06425f3849a5ff4ec9162c8ce20dcab8e2b7a480
| 82
|
Game-Gallery
|
MIT License
|
app/src/main/java/com/jetpack/compose/learning/animation/Tabbar.kt
|
SimformSolutionsPvtLtd
| 379,199,800
| false
| null |
package com.jetpack.compose.learning.animation
import androidx.compose.animation.animateColor
import androidx.compose.animation.animateColorAsState
import androidx.compose.animation.core.Spring
import androidx.compose.animation.core.animateDp
import androidx.compose.animation.core.spring
import androidx.compose.animation.core.updateTransition
import androidx.compose.foundation.BorderStroke
import androidx.compose.foundation.border
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.offset
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.layout.wrapContentSize
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.Icon
import androidx.compose.material.Scaffold
import androidx.compose.material.TabPosition
import androidx.compose.material.TabRow
import androidx.compose.material.Text
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.AccountBox
import androidx.compose.material.icons.filled.Home
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.vector.ImageVector
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import com.jetpack.compose.learning.R
import com.jetpack.compose.learning.animation.ui.theme.colorPrimaryDark
import com.jetpack.compose.learning.animation.ui.theme.pinkColor
import com.jetpack.compose.learning.animation.ui.theme.pinkColorDark
import com.jetpack.compose.learning.theme.lightBlue200
@Composable
private fun TabBar(
backgroundColor: Color, tabPage: TabPage1, onTabSelected: (tabPage: TabPage1) -> Unit
) {
TabRow(selectedTabIndex = tabPage.ordinal,
backgroundColor = backgroundColor,
indicator = { tabPositions ->
HomeTabIndicator1(tabPositions, tabPage)
}) {
HomeTab(icon = Icons.Default.Home,
title = stringResource(R.string.home),
onClick = { onTabSelected(TabPage1.Home) })
HomeTab(icon = Icons.Default.AccountBox,
title = stringResource(R.string.work),
onClick = { onTabSelected(TabPage1.Work) })
}
}
@Composable
fun TabBarContent() {
// The currently selected tab.
var tabPage by remember { mutableStateOf(TabPage1.Home) }
// The background color. The value is changed by the current tab.
val backgroundColor by animateColorAsState(if (tabPage == TabPage1.Home) lightBlue200 else pinkColor)
Scaffold(topBar = {
TabBar(backgroundColor = backgroundColor,
tabPage = tabPage,
onTabSelected = { tabPage = it })
}, backgroundColor = backgroundColor) {}
}
@Composable
private fun HomeTabIndicator1(
tabPositions: List<TabPosition>, tabPage: TabPage1
) {
val transition = updateTransition(
tabPage, label = "Tab indicator"
)
val indicatorLeft by transition.animateDp(
transitionSpec = {
if (TabPage1.Home isTransitioningTo TabPage1.Work) {
// Indicator moves to the right.
// Low stiffness spring for the left edge so it moves slower than the right edge.
spring(stiffness = Spring.StiffnessVeryLow)
} else {
// Indicator moves to the left.
// Medium stiffness spring for the left edge so it moves faster than the right edge.
spring(stiffness = Spring.StiffnessMedium)
}
}, label = "Indicator left"
) { page ->
tabPositions[page.ordinal].left
}
val indicatorRight by transition.animateDp(
transitionSpec = {
if (TabPage1.Home isTransitioningTo TabPage1.Work) {
// Indicator moves to the right
// Medium stiffness spring for the right edge so it moves faster than the left edge.
spring(stiffness = Spring.StiffnessMedium)
} else {
// Indicator moves to the left.
// Low stiffness spring for the right edge so it moves slower than the left edge.
spring(stiffness = Spring.StiffnessVeryLow)
}
}, label = "Indicator right"
) { page ->
tabPositions[page.ordinal].right
}
val color by transition.animateColor(
label = "Border color"
) { page ->
if (page == TabPage1.Home) colorPrimaryDark else Color.White
}
Box(
Modifier
.fillMaxSize()
.wrapContentSize(align = Alignment.BottomStart)
.offset(x = indicatorLeft)
.width(indicatorRight - indicatorLeft)
.padding(4.dp)
.fillMaxSize()
.border(
BorderStroke(2.dp, color), RoundedCornerShape(4.dp)
)
)
}
private enum class TabPage1 {
Home, Work
}
@Composable
private fun HomeTab(
icon: ImageVector, title: String, onClick: () -> Unit, modifier: Modifier = Modifier
) {
Row(
modifier = modifier
.padding(4.dp)
.clip(RoundedCornerShape(4.dp))
.clickable(onClick = onClick)
.padding(16.dp),
horizontalArrangement = Arrangement.Center,
verticalAlignment = Alignment.CenterVertically
) {
Icon(
imageVector = icon, contentDescription = null
)
Spacer(modifier = Modifier.width(16.dp))
Text(text = title)
}
}
@Preview
@Composable
private fun PreviewTabBar() {
TabBarContent()
}
| 0
| null |
8
| 99
|
06fa9850a3cdfabfda2d09da1f4eda93898b8733
| 6,151
|
SSComposeCookBook
|
Apache License 2.0
|
api/config/src/main/kotlin/org/rsmod/api/config/refs/BaseModGroups.kt
|
rsmod
| 293,875,986
| false
|
{"Kotlin": 1817705}
|
package org.rsmod.api.config.refs
import org.rsmod.api.type.builders.mod.ModGroupBuilder
import org.rsmod.game.type.mod.ModGroup
public object BaseModGroups : ModGroupBuilder() {
public val player: ModGroup =
build("player") {
moderator = false // Declared for explicitness in api - not required.
administrator = false // Declared for explicitness in api - not required.
modLevels = setOf(BaseModLevels.player)
}
}
| 0
|
Kotlin
|
64
| 95
|
3ba446ed70bcde0870ef431e1a8527efc6837d6c
| 473
|
rsmod
|
ISC License
|
androidApp/src/main/java/com/rld/justlisten/android/ui/searchscreen/components/PlaylistResult.kt
|
RLD-JL
| 495,044,961
| false
|
{"Kotlin": 301525, "Swift": 344}
|
package com.rld.justlisten.android.ui.searchscreen.components
import androidx.compose.foundation.lazy.LazyRow
import androidx.compose.foundation.lazy.itemsIndexed
import androidx.compose.runtime.Composable
import com.rld.justlisten.android.ui.playlistscreen.components.PlaylistRowItem
import com.rld.justlisten.viewmodel.screens.playlist.PlaylistItem
@Composable
fun PlaylistResult(
playlist: List<PlaylistItem>,
onPlaylistPressed: (String, String, String, String, Boolean) -> Unit) {
LazyRow {
itemsIndexed(items = playlist) { _, playlistItem ->
PlaylistRowItem(
playlistItem = playlistItem,
onPlaylistClicked = onPlaylistPressed
)
}
}
}
| 3
|
Kotlin
|
3
| 82
|
e7060fe54f59551b89587698149274e5647b3216
| 728
|
Just-Listen
|
Apache License 2.0
|
ocaml/src/main/java/de/markusressel/kodehighlighter/language/ocaml/rule/NumberRule.kt
|
markusressel
| 167,466,321
| false
|
{"Kotlin": 113203, "Python": 19475, "OCaml": 10026, "Shell": 2354, "Makefile": 156}
|
package de.markusressel.kodehighlighter.language.ocaml.rule
import de.markusressel.kodehighlighter.core.rule.LanguageRule
import de.markusressel.kodehighlighter.core.rule.RuleHelper
import de.markusressel.kodehighlighter.core.rule.RuleMatch
class NumberRule : LanguageRule {
override fun findMatches(text: CharSequence): List<RuleMatch> {
return RuleHelper.findRegexMatches(text, PATTERN)
}
companion object {
val PATTERN = "\\b(0[xX][a-fA-F0-9_]+[Lln]?|0[oO][0-7_]+[Lln]?|0[bB][01_]+[Lln]?|[0-9][0-9_]*([Lln]|(\\.[0-9_]*)?([eE][-+]?[0-9_]+)?)?)".toRegex()
}
}
| 12
|
Kotlin
|
3
| 19
|
8811982b1f35ff3b43d4885b01b2781e1e30815b
| 597
|
KodeHighlighter
|
MIT License
|
buildSrc/src/main/kotlin/Constants.kt
|
Genti2024
| 793,968,607
| false
|
{"Kotlin": 275256}
|
object Constants {
const val packageName = "kr.genti.android"
const val compileSdk = 34
const val minSdk = 28
const val targetSdk = 34
const val versionCode = 15
const val versionName = "1.1.6"
}
| 1
|
Kotlin
|
1
| 7
|
fa968bcbe736fec105e9d2e5ae89485074f46941
| 220
|
Genti-Android
|
MIT License
|
app/src/main/java/com/jintin/roomsample/MainViewModel.kt
|
Jintin
| 325,205,950
| false
| null |
package com.jintin.roomsample
import android.app.Application
import androidx.lifecycle.AndroidViewModel
import androidx.lifecycle.asLiveData
import androidx.lifecycle.viewModelScope
import kotlinx.coroutines.launch
import kotlin.random.Random
class MainViewModel(application: Application) : AndroidViewModel(application) {
private val database: UserDatabase = UserDatabase.getInstance(application)
private val userDao = database.userDao()
private val userName = listOf("Peter", "Jane", "Tim", "Tina")
val liveData = database.userDao().list().asLiveData()
fun update(user: User) {
viewModelScope.launch {
userDao.update(user)
}
}
fun delete(user: User) {
viewModelScope.launch {
userDao.delete(user)
}
}
fun addRandomUser() {
viewModelScope.launch {
val name = userName[Random.nextInt(userName.size)]
val user = User(name, Random.nextInt(100))
userDao.insert(user)
}
}
}
| 0
|
Kotlin
|
0
| 1
|
3b1e8c32423b94921b8c93659c7ad8050e7145ca
| 1,024
|
RoomSample
|
MIT License
|
app/src/main/java/io/github/ascenderx/mobilescript/ui/menu/MenuHandler.kt
|
user0x4A35
| 239,868,041
| false
| null |
package io.github.ascenderx.mobilescript.ui.menu
interface MenuHandler {
fun attachMenuEventListener(listener: MenuEventListener)
fun detachMenuEventListener()
fun showOptionItem(id: Int)
fun hideOptionItem(id: Int)
fun navigateTo(destination: Int)
}
| 0
|
Kotlin
|
0
| 0
|
e743c8f888445e5a1b1ed3bf37f27c7dfc2d907a
| 271
|
byui-cs499-downerj
|
Apache License 2.0
|
common/user/domain/src/commonTest/kotlin/dev/alvr/katana/common/user/domain/usecases/SaveUserIdUseCaseTest.kt
|
alvr
| 446,535,707
| false
|
{"Kotlin": 464229, "Swift": 594}
|
package dev.alvr.katana.common.user.domain.usecases
import arrow.core.left
import arrow.core.right
import dev.alvr.katana.common.user.domain.failures.UserFailure
import dev.alvr.katana.common.user.domain.repositories.UserRepository
import dev.alvr.katana.core.common.coroutines.KatanaDispatcher
import dev.alvr.katana.core.domain.failures.Failure
import dev.alvr.katana.core.domain.usecases.invoke
import dev.alvr.katana.core.tests.di.coreTestsModule
import dev.alvr.katana.core.tests.koinExtension
import dev.alvr.katana.core.tests.shouldBeLeft
import dev.alvr.katana.core.tests.shouldBeRight
import dev.mokkery.answering.returns
import dev.mokkery.everySuspend
import dev.mokkery.mock
import dev.mokkery.verifySuspend
import io.kotest.core.spec.style.FreeSpec
import io.kotest.core.test.TestCase
import org.koin.test.KoinTest
import org.koin.test.inject
internal class SaveUserIdUseCaseTest : FreeSpec(), KoinTest {
private val dispatcher by inject<KatanaDispatcher>()
private val repo = mock<UserRepository>()
private lateinit var useCase: SaveUserIdUseCase
init {
"successfully saving user id" {
everySuspend { repo.saveUserId() } returns Unit.right()
useCase().shouldBeRight(Unit)
verifySuspend { repo.saveUserId() }
}
listOf(
UserFailure.FetchingUser to UserFailure.FetchingUser.left(),
UserFailure.SavingUser to UserFailure.SavingUser.left(),
Failure.Unknown to Failure.Unknown.left(),
).forEach { (expected, failure) ->
"failure saving user id ($expected)" {
everySuspend { repo.saveUserId() } returns failure
useCase().shouldBeLeft(expected)
verifySuspend { repo.saveUserId() }
}
}
}
override suspend fun beforeEach(testCase: TestCase) {
useCase = SaveUserIdUseCase(dispatcher, repo)
}
override fun extensions() = listOf(koinExtension(coreTestsModule))
}
| 1
|
Kotlin
|
0
| 59
|
218ae9276f5ebd655e6587019d6a5c42e092137a
| 1,995
|
katana
|
Apache License 2.0
|
online_food_recipes_example/app/src/main/java/com/dev/online_food_recipes_example/utils/CustomExtensionFunction.kt
|
PhoenixNest
| 472,614,701
| false
| null |
package com.dev.online_food_recipes_example.utils
import androidx.lifecycle.LifecycleOwner
import androidx.lifecycle.LiveData
import androidx.lifecycle.Observer
// Custom Function to Fix the Fetch-Data-Twice-Call
private fun <T> LiveData<T>.observeOnce(lifecycleOwner: LifecycleOwner, observer: Observer<T>) {
observe(lifecycleOwner, object : Observer<T> {
override fun onChanged(t: T) {
// The Data is not from the Local access is obtained from the Cloud
// we just need Observe the LiveData Object only Once and not Every-Time
removeObserver(this)
observer.onChanged(t)
}
})
}
| 0
|
Kotlin
|
0
| 0
|
00df973b674768a28abc8e83312474f8bae933bc
| 653
|
google_jetpack_in_use
|
MIT License
|
app/src/main/java/com/productivity/fullmangement/ui/composables/ExpandableCard.kt
|
Amrjyniat
| 443,723,945
| false
| null |
package com.productivity.fullmangement.ui.composables
import androidx.compose.animation.AnimatedVisibility
import androidx.compose.animation.animateContentSize
import androidx.compose.animation.core.LinearOutSlowInEasing
import androidx.compose.animation.core.animateFloatAsState
import androidx.compose.animation.core.tween
import androidx.compose.foundation.layout.*
import androidx.compose.material.*
import androidx.compose.material.ContentAlpha.medium
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.ArrowDropDown
import androidx.compose.material.icons.filled.ExpandMore
import androidx.compose.runtime.*
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.alpha
import androidx.compose.ui.draw.rotate
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.Shape
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.Dp
import androidx.compose.ui.unit.TextUnit
import androidx.compose.ui.unit.dp
import com.productivity.fullmangement.ui.theme.GrayWhite
import com.productivity.fullmangement.ui.theme.Shapes
@ExperimentalMaterialApi
@Composable
fun ExpandableCard(
modifier: Modifier = Modifier,
title: String,
titleFontSize: TextUnit = MaterialTheme.typography.h6.fontSize,
titleFontWeight: FontWeight = FontWeight.Normal,
shape: Shape = Shapes.medium,
padding: Dp = 8.dp,
content: @Composable ColumnScope.() -> Unit
) {
var expandedState by remember { mutableStateOf(false) }
val rotationState by animateFloatAsState(
targetValue = if (expandedState) 180f else 0f
)
Card(
modifier = modifier
.fillMaxWidth()
.animateContentSize(
animationSpec = tween(
durationMillis = 300,
easing = LinearOutSlowInEasing
)
),
shape = shape,
backgroundColor = GrayWhite,
onClick = {
expandedState = !expandedState
}
) {
Column(
modifier = Modifier
.fillMaxWidth()
.padding(padding)
) {
Row(
verticalAlignment = Alignment.CenterVertically
) {
Text(
modifier = Modifier
.weight(6f),
text = title,
fontSize = titleFontSize,
fontWeight = titleFontWeight,
maxLines = 1,
overflow = TextOverflow.Ellipsis
)
IconButton(
modifier = Modifier
.weight(1f)
.alpha(ContentAlpha.medium)
.rotate(rotationState),
onClick = {
expandedState = !expandedState
}) {
Icon(
imageVector = Icons.Default.ExpandMore,
contentDescription = "Drop-Down Arrow",
tint = MaterialTheme.colors.primary
)
}
}
AnimatedVisibility(visible = expandedState) {
content()
}
}
}
}
@ExperimentalMaterialApi
@Composable
@Preview
fun ExpandableCardPreview() {
ExpandableCard(
title = "My Title",
content = {
Text("kasjdhkjash")
}
)
}
| 0
|
Kotlin
|
1
| 5
|
5dd68e34ded2fb405c7cb60b2a476ae0a1c0c969
| 3,626
|
FullManagement
|
Apache License 2.0
|
shared/src/commonMain/kotlin/ui/AddLocation.kt
|
evilya
| 661,036,698
| false
|
{"Kotlin": 60411, "Swift": 527, "Ruby": 101}
|
package ui
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.text.KeyboardOptions
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.sharp.Check
import androidx.compose.material3.CircularProgressIndicator
import androidx.compose.material3.Icon
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Text
import androidx.compose.material3.TextField
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.MutableState
import androidx.compose.runtime.collectAsState
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.runtime.snapshotFlow
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.focus.FocusRequester
import androidx.compose.ui.focus.focusRequester
import androidx.compose.ui.platform.LocalSoftwareKeyboardController
import androidx.compose.ui.text.input.ImeAction
import androidx.compose.ui.text.input.KeyboardCapitalization
import androidx.compose.ui.text.input.KeyboardType
import androidx.compose.ui.unit.dp
import cafe.adriel.voyager.core.model.ScreenModel
import cafe.adriel.voyager.core.model.screenModelScope
import cafe.adriel.voyager.core.screen.Screen
import cafe.adriel.voyager.koin.getScreenModel
import data.Location
import data.LocationId
import data.LocationRepository
import data.WeatherApi
import data.getCurrentLocation
import dev.icerock.moko.permissions.Permission
import dev.icerock.moko.permissions.PermissionsController
import dev.icerock.moko.permissions.compose.BindEffect
import dev.icerock.moko.permissions.compose.rememberPermissionsControllerFactory
import forekast.shared.generated.resources.Res
import forekast.shared.generated.resources.location_search_current
import forekast.shared.generated.resources.location_search_hint
import kotlinx.coroutines.flow.debounce
import kotlinx.coroutines.flow.filter
import kotlinx.coroutines.flow.map
import kotlinx.coroutines.flow.mapLatest
import kotlinx.coroutines.launch
import org.jetbrains.compose.resources.stringResource
import org.koin.core.parameter.parametersOf
class AddLocationScreenModel(
private val locationRepository: LocationRepository,
private val weatherApi: WeatherApi,
val permissionController: PermissionsController,
) : ScreenModel {
val addedLocations = locationRepository.observeLocations()
.map { locations -> locations.map { it.id }.toSet() }
val locationSearchQuery = mutableStateOf("")
val locationSearchInProgress = mutableStateOf(false)
val currentLocationAdded = mutableStateOf(false)
val searchResults = snapshotFlow { locationSearchQuery.value }
.filter { it.isNotBlank() }
.debounce(500)
.mapLatest { query ->
locationSearchInProgress.value = true
weatherApi.searchLocation(query)
.also { locationSearchInProgress.value = false }
}
fun addLocation(location: Location) {
locationRepository.addLocation(location)
}
fun addCurrentLocation() {
screenModelScope.launch {
permissionController.providePermission(Permission.LOCATION)
val currentLocation = runCatching { getCurrentLocation() }
.getOrNull() ?: return@launch
weatherApi.searchLocation(currentLocation)
.onSuccess { location ->
location?.let(::addLocation).also {
currentLocationAdded.value = true
}
}
}
}
}
class AddLocationScreen : Screen {
@Composable
override fun Content() {
val permissionControllerFactory = rememberPermissionsControllerFactory()
val screenModel = getScreenModel<AddLocationScreenModel>(
parameters = { parametersOf(permissionControllerFactory.createPermissionsController()) },
)
val locationQuery = remember { screenModel.locationSearchQuery }
val searchResults by screenModel.searchResults.collectAsState(Result.success(emptyList()))
val searchInProgress by screenModel.locationSearchInProgress
val addedLocationIds by screenModel.addedLocations.collectAsState(emptySet())
val currentLocationAdded by screenModel.currentLocationAdded
val keyboardController = LocalSoftwareKeyboardController.current
val focusRequester = remember { FocusRequester() }
BindEffect(screenModel.permissionController)
AddLocation(
locationQuery = locationQuery,
searchResults = searchResults,
searchInProgress = searchInProgress,
addedLocationIds = addedLocationIds,
currentLocationAdded = currentLocationAdded,
onSearchLocationClick = {
if (addedLocationIds.contains(it.id)) return@AddLocation
screenModel.addLocation(it)
keyboardController?.hide()
},
onCurrentLocationClick = {
if (currentLocationAdded) return@AddLocation
screenModel.addCurrentLocation()
keyboardController?.hide()
},
modifier = Modifier
.fillMaxWidth()
.focusRequester(focusRequester),
)
LaunchedEffect(Unit) {
focusRequester.requestFocus()
}
}
}
@Composable
fun AddLocation(
locationQuery: MutableState<String>,
searchResults: Result<List<Location>>,
searchInProgress: Boolean,
addedLocationIds: Set<LocationId>,
currentLocationAdded: Boolean,
onSearchLocationClick: (Location) -> Unit,
onCurrentLocationClick: () -> Unit,
modifier: Modifier = Modifier,
) {
LazyColumn(
verticalArrangement = Arrangement.Top,
horizontalAlignment = Alignment.CenterHorizontally,
modifier = modifier.padding(vertical = 8.dp).fillMaxWidth(),
) {
item {
TextField(
keyboardOptions = KeyboardOptions(
keyboardType = KeyboardType.Text,
capitalization = KeyboardCapitalization.Words,
autoCorrect = false,
imeAction = ImeAction.Done,
),
placeholder = { Text(text = stringResource(Res.string.location_search_hint)) },
singleLine = true,
value = locationQuery.value,
onValueChange = { locationQuery.value = it },
modifier = Modifier
.padding(horizontal = 16.dp, vertical = 8.dp)
.fillMaxWidth(),
)
}
if (searchInProgress) {
item {
CircularProgressIndicator(modifier = Modifier.size(24.dp))
}
}
item {
CurrentLocationItem(
added = currentLocationAdded,
onClick = onCurrentLocationClick,
)
}
searchResults.getOrNull()?.map { location ->
item(key = location.id.id) {
SearchLocationItem(
location = location,
added = addedLocationIds.contains(location.id),
onClick = onSearchLocationClick,
)
}
}
}
}
@Composable
private fun LocationItem(
modifier: Modifier = Modifier,
added: Boolean,
content: @Composable () -> Unit,
) {
Row(
verticalAlignment = Alignment.CenterVertically,
modifier = modifier
.fillMaxWidth()
.padding(
vertical = 8.dp,
horizontal = 16.dp,
),
) {
content()
Spacer(modifier = Modifier.weight(1f))
if (added) {
Icon(
imageVector = Icons.Sharp.Check,
contentDescription = "Location added checkmark",
)
}
}
}
@Composable
private fun SearchLocationItem(
location: Location,
added: Boolean,
onClick: (Location) -> Unit,
) {
LocationItem(
modifier = Modifier
.clickable(enabled = !added) { onClick(location) },
added = added,
) {
Column(
horizontalAlignment = Alignment.Start,
) {
Text(
text = location.name,
style = MaterialTheme.typography.titleMedium,
)
location.country?.let { country ->
Text(
text = country,
style = MaterialTheme.typography.titleSmall,
)
}
}
}
}
@Composable
private fun CurrentLocationItem(
added: Boolean,
onClick: () -> Unit,
) {
LocationItem(
modifier = Modifier
.clickable(enabled = !added) { onClick() },
added = added,
) {
Text(
text = stringResource(Res.string.location_search_current),
style = MaterialTheme.typography.titleMedium,
)
}
}
| 0
|
Kotlin
|
0
| 0
|
122b809cd43e0766d822b7bb2fa4aeb7097772a6
| 9,584
|
forekast
|
Apache License 2.0
|
planty-client/common/src/commonMain/kotlin/nest/planty/ui/theme/platform.kt
|
HLCaptain
| 693,789,413
| false
|
{"Kotlin": 186539, "Python": 9666, "C++": 4729, "HTML": 1243, "JavaScript": 1215, "CSS": 173}
|
package nest.planty.ui.theme
import androidx.compose.runtime.Composable
@Composable
expect fun PlantyTheme(content: @Composable () -> Unit)
| 0
|
Kotlin
|
0
| 0
|
bf42461ccd164962a0d19c3718ff074ca1aaa350
| 141
|
planty
|
MIT License
|
src/main/kotlin/vulnerabilities/dto/PackageWithVersions.kt
|
fraunhofer-iem
| 738,423,065
| false
|
{"Kotlin": 73169, "Dockerfile": 1484}
|
package vulnerabilities.dto
import artifact.model.VersionDto
import kotlinx.serialization.Serializable
@Serializable
data class PackageWithVersions(
val packageX: Package,
val versions: List<VersionDto> = listOf()
)
| 6
|
Kotlin
|
0
| 0
|
94db757f2512e8ecf436ec905db2262c2870e00f
| 226
|
Libyear-ORT
|
MIT License
|
shoring/fxapp/src/main/kotlin/com/panopset/fxapp/FxDoc.kt
|
panopset
| 752,122,553
| false
|
{"Kotlin": 600277, "Java": 26106, "Shell": 9716, "CSS": 4623, "JavaScript": 4084, "Batchfile": 2807, "HTML": 1317}
|
package com.panopset.fxapp
import com.panopset.compat.*
import javafx.scene.Scene
import javafx.scene.control.TextField
import javafx.stage.Stage
import java.io.File
class FxDoc : Anchor, LogDsiplayer {
val stage: Stage
lateinit var menuBarStatusMessage: TextField
lateinit var scene: Scene
constructor(panApplication: PanApplication, stage: Stage, file: File) : super(panApplication, file) {
this.stage = stage
}
constructor(panApplication: PanApplication, stage: Stage) : super(panApplication) {
this.stage = stage
}
override fun updateTitle() {
stage.title = createWindowTitle()
}
fun closeWindow() {
saveWindow()
stage.close()
}
fun saveWindow() {
persistentMapFile.put(
KEY_WINDOW_DIMS,
combineDelim("|", stage.x.toString(), stage.y.toString(), stage.width.toString(), stage.height.toString())
)
saveDataToFile()
}
override fun dspmsg(msg: String) {
menuBarStatusMessage.text = msg
}
override fun warn(msg: String) {
dspmsg(msg)
}
override fun clear() {
dspmsg("")
}
override fun getPriorMessage(): String {
return menuBarStatusMessage.text
}
override fun green(msg: String) {
dspmsg(msg)
}
override fun errorMsg(message: String, throwable: Throwable) {
dspmsg(message)
}
override fun errorMsg(message: String, file: File) {
dspmsg(message)
}
override fun errorMsg(message: String) {
dspmsg(message)
}
override fun errorMsg(file: File, throwable: Throwable) {
//dspmsg(msg)
}
override fun errorEx(throwable: Throwable) {
dspmsg(throwable.message?: "unfathomable")
}
override fun debug(message: String) {
dspmsg(message)
}
// fun setLogLis() {
// Logop.setLogListener(object: LogListener {
// override fun log(logEntry: LogEntry) {
// FontManagerFX.setMenubarLogRecord(
// logEntry,
// menuBarStatusMessage
// )
// }
// })
// }
}
/*
application.doAfterLaunch(this)
override fun doAfterLaunch(fxDoc: FxDoc) {
super.doAfterLaunch(fxDoc)
val floor = getFloor(fxDoc)
Platform.runLater {
updateEnvironmentWithProps(floor, panCheckboxMenu.currentSelection)
}
}
*/
| 0
|
Kotlin
|
0
| 0
|
6143695aae5dc208b2a484074580c676f0f8f7f2
| 2,503
|
pan
|
MIT License
|
src/Day03.kt
|
wellithy
| 571,903,945
| false
| null |
package day03
import util.*
@JvmInline
value class Item(val char: Char) {
fun priority(): Int =
when (char) {
in 'a'..'z' -> (char - 'a') + 1
in 'A'..'Z' -> (char - 'A') + 27
else -> error("")
}
}
fun Set<Item>.priority(): Int = single().priority()
@JvmInline
value class Rucksack(val items: List<Item>) {
fun asSet(): Set<Item> =
items.toSet()
private fun sub(from: Int = 0, to: Int = items.size): Set<Item> =
items.subList(from, to).toSet()
fun priority(): Int =
(items.size / 2).let { sub(to = it) intersect sub(from = it) }.priority()
companion object {
fun of(line: String): Rucksack =
line.toCharArray().map(::Item).let(::Rucksack)
}
}
@JvmInline
value class Group(val rucksacks: List<Rucksack>) {
init {
require(rucksacks.size == SIZE)
}
fun priority(): Int =
rucksacks.map(Rucksack::asSet).reduce { acc, s -> acc intersect s }.priority()
companion object {
const val SIZE: Int = 3
fun of(lines: List<String>): Group =
lines.map(Rucksack::of).let(::Group)
}
}
fun part1(input: Sequence<String>): Int =
input.map(Rucksack::of).map(Rucksack::priority).sum()
fun part2(input: Sequence<String>): Int =
input.chunked(Group.SIZE).map(Group::of).map(Group::priority).sum()
fun main() {
test(::part1, 157)
go(::part1, 8252)
test(::part2, 70)
go(::part2, 2828)
}
| 0
|
Kotlin
|
0
| 0
|
6d5fd4f0d361e4d483f7ddd2c6ef10224f6a9dec
| 1,487
|
aoc2022
|
Apache License 2.0
|
meistercharts-canvas/src/jsTest/kotlin/com/meistercharts/config/ParseJsonScripTagTest.kt
|
Neckar-IT
| 599,079,962
| false
|
{"Kotlin": 5819931, "HTML": 87784, "JavaScript": 1378, "CSS": 1114}
|
/**
* Copyright 2023 Neckar IT GmbH, Mössingen, Germany
*
* 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.meistercharts.canvas.layout.cache.com.meistercharts.config
import assertk.*
import assertk.assertions.*
import com.meistercharts.config.ChartConfigParsingSupport
import it.neckar.commons.kotlin.js.render
import kotlinx.browser.document
import kotlinx.html.dom.append
import kotlinx.html.js.script
import kotlinx.html.unsafe
import kotlinx.serialization.Serializable
import kotlinx.serialization.json.Json
import kotlin.test.Test
class ParseJsonScripTagTest {
@Test
fun testIt() {
val body = requireNotNull(document.body)
val toSerialize = MyJsonObject("asdf", 1234)
val json = Json { prettyPrint = true }
val id = "meistercharts-json-data"
body.append {
script {
type = "application/json"
attributes["id"] = id
unsafe { +json.encodeToString(MyJsonObject.serializer(), toSerialize) }
}
}
assertThat(document.render()).contains("asdf")
if (false) {
println("--------------")
println(document.render())
println("--------------")
}
val parsed = ChartConfigParsingSupport().parseChartsConfig<MyJsonObject>(id)
assertThat(parsed).isEqualTo(toSerialize)
}
@Serializable
data class MyJsonObject(
val foo: String,
val fooBar: Int,
)
}
| 3
|
Kotlin
|
3
| 5
|
ed849503e845b9d603598e8d379f6525a7a92ee2
| 1,887
|
meistercharts
|
Apache License 2.0
|
app/src/test/java/com/marknkamau/justjava/ui/login/LogInPresenterTest.kt
|
godiLabs
| 196,942,734
| true
|
{"Kotlin": 156721}
|
package com.marknkamau.justjava.ui.login
import com.marknjunge.core.auth.AuthService
import com.marknjunge.core.data.firebase.UserService
import com.marknjunge.core.model.AuthUser
import com.marknjunge.core.model.UserDetails
import com.marknkamau.justjava.data.local.PreferencesRepository
import io.mockk.MockKAnnotations
import io.mockk.coEvery
import io.mockk.every
import io.mockk.impl.annotations.MockK
import io.mockk.verify
import kotlinx.coroutines.Dispatchers
import org.junit.Before
import org.junit.Test
/**
* Created by <NAME>.
* <EMAIL>
* https://github.com/MarkNjunge
*/
class LogInPresenterTest {
@MockK
private lateinit var view: LogInView
@MockK
private lateinit var preferences: PreferencesRepository
@MockK
private lateinit var auth: AuthService
@MockK
private lateinit var userService: UserService
private lateinit var presenter: LogInPresenter
@Before
fun setup() {
MockKAnnotations.init(this, relaxUnitFun = true)
presenter = LogInPresenter(view, preferences, auth, userService, Dispatchers.Unconfined)
}
@Test
fun should_closeActivity_when_signedIn() {
every { auth.isSignedIn() } returns true
presenter.checkSignInStatus()
verify { view.closeActivity() }
}
@Test
fun should_finishSignIn_when_signInAndUserDefaults_success() {
// Succeed in signing in
coEvery {
auth.signIn(any(), any())
} returns ""
// Succeed in getting user defaults
coEvery {
userService.getUserDetails(any())
} returns UserDetails("", "", "", "", "")
every { auth.getCurrentUser() } returns AuthUser("", "", "")
// Succeed updating FCM token
coEvery{
userService.updateUserFcmToken(any())
} returns Unit
presenter.signIn("", "")
verify { view.finishSignIn() }
}
@Test
fun should_displayMessage_when_signIn_failed() {
// Fail in signing in
coEvery {
auth.signIn(any(), any())
} throws Exception("")
presenter.signIn("", "")
verify { view.displayMessage(any()) }
}
@Test
fun should_displayMessage_when_getUserDefaults_failed() {
// Succeed in signing in
coEvery {
auth.signIn(any(), any())
} returns ""
// Fail in getting user defaults
coEvery{
userService.getUserDetails(any())
} throws Exception("")
every { auth.getCurrentUser() } returns AuthUser("", "", "")
// Succeed updating FCM token
coEvery {
userService.updateUserFcmToken(any())
} returns Unit
presenter.signIn("", "")
verify { view.displayMessage(any()) }
}
@Test
fun should_displayMessage_when_sendPasswordRestEmail_success() {
// Succeed sending email
coEvery {
auth.sendPasswordResetEmail(any())
} returns Unit
presenter.resetUserPassword("")
verify {
view.displayMessage(any())
}
}
@Test
fun should_displayMessage_when_sendPasswordRestEmail_failed() {
// Fail sending email
coEvery {
auth.sendPasswordResetEmail(any())
} throws Exception("")
presenter.resetUserPassword("")
verify { view.displayMessage(any()) }
}
}
| 0
|
Kotlin
|
0
| 0
|
13d6695c341d96343607e37b4761e6b4d56a59ad
| 3,410
|
JustJava-Android
|
Apache License 2.0
|
camerax_lib/src/main/java/com/kiylx/camerax_lib/main/manager/model/VisionType.kt
|
Knightwood
| 517,621,489
| false
|
{"Kotlin": 248505, "Java": 31809}
|
package com.kiylx.camerax_lib.main.manager.model
enum class VisionType {
Barcode, Face, Object, OCR
}
| 0
|
Kotlin
|
6
| 34
|
4db9a7dafd770415d7f85b3f5159bcb542e2925d
| 106
|
CameraX-Helper
|
Apache License 2.0
|
gallery-app/src/commonMain/kotlin/io/ashdavies/gallery/GalleryPresenter.kt
|
ashdavies
| 36,688,248
| false
|
{"Kotlin": 209662, "HCL": 21205, "Shell": 3934, "Mustache": 2101}
|
@file:Suppress("INLINE_FROM_HIGHER_PLATFORM")
package io.ashdavies.gallery
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.produceState
import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.runtime.setValue
import com.arkivanov.essenty.parcelable.Parcelable
import com.arkivanov.essenty.parcelable.Parcelize
import com.slack.circuit.runtime.CircuitUiEvent
import com.slack.circuit.runtime.CircuitUiState
import com.slack.circuit.runtime.presenter.Presenter
import com.slack.circuit.runtime.presenter.presenterOf
import com.slack.circuit.runtime.screen.Screen
import com.slack.circuit.runtime.ui.Ui
import com.slack.circuit.runtime.ui.ui
import io.ashdavies.content.PlatformContext
import io.ashdavies.http.DefaultHttpClient
import io.ashdavies.playground.DatabaseFactory
import kotlinx.coroutines.launch
@Parcelize
public object GalleryScreen : Parcelable, Screen {
internal sealed interface Event : CircuitUiEvent {
data class Expand(val index: Int) : Event
data class Result(val value: File) : Event
data class Toggle(val index: Int) : Event
data object Capture : Event
data object Collapse : Event
data object Delete : Event
data object Sync : Event
}
internal data class State(
val itemList: List<StandardItem> = emptyList(),
val expandedItem: ExpandedItem? = null,
val showCapture: Boolean,
val isLoggedIn: Boolean,
val eventSink: (Event) -> Unit,
) : CircuitUiState {
data class StandardItem(
val title: String,
val imageModel: Any?,
val isSelected: Boolean,
val state: SyncState,
)
data class ExpandedItem(
val contentDescription: String,
val imageModel: Any?,
val isExpanded: Boolean,
)
}
}
public fun GalleryPresenterFactory(context: PlatformContext): Presenter.Factory {
val database = DatabaseFactory(PlaygroundDatabase.Schema, context) { PlaygroundDatabase(it) }
val storage = StorageManager(PathProvider(context).images)
val images = ImageManager(storage, database.imageQueries)
val engine = InMemoryHttpClientEngine(emptyList())
val sync = SyncManager(DefaultHttpClient(engine))
return Presenter.Factory { screen, _, _ ->
when (screen) {
is GalleryScreen -> presenterOf { GalleryPresenter(images, sync) }
else -> null
}
}
}
public fun GalleryUiFactory(context: PlatformContext): Ui.Factory {
val storage = StorageManager(PathProvider(context).images)
return Ui.Factory { screen, _ ->
when (screen) {
is GalleryScreen -> ui<GalleryScreen.State> { state, modifier ->
GalleryScreen(
state = state,
manager = storage,
modifier = modifier,
)
}
else -> null
}
}
}
@Composable
internal fun GalleryPresenter(images: ImageManager, sync: SyncManager): GalleryScreen.State {
val itemList by produceState(emptyList<Image>(), images) {
images.list.collect { value = it }
}
var expandedItem by remember { mutableStateOf<GalleryScreen.State.ExpandedItem?>(null) }
var selected by remember { mutableStateOf(emptyList<Image>()) }
var takePhoto by remember { mutableStateOf(false) }
val syncState by produceState(emptyMap<String, SyncState>()) {
sync.state.collect { value = it }
}
val coroutineScope = rememberCoroutineScope()
return GalleryScreen.State(
itemList = itemList.map {
GalleryScreen.State.StandardItem(
title = it.name,
imageModel = File(it.path),
isSelected = it in selected,
state = syncState[it.name] ?: SyncState.NOT_SYNCED,
)
},
expandedItem = expandedItem,
showCapture = takePhoto,
isLoggedIn = false,
) { event ->
when (event) {
is GalleryScreen.Event.Capture -> takePhoto = true
is GalleryScreen.Event.Collapse -> {
expandedItem = expandedItem?.copy(isExpanded = false)
}
is GalleryScreen.Event.Delete -> {
selected.forEach { images.remove(it) }
selected = emptyList()
}
is GalleryScreen.Event.Expand -> {
expandedItem = GalleryScreen.State.ExpandedItem(
contentDescription = itemList[event.index].name,
imageModel = File(itemList[event.index].path),
isExpanded = true,
)
}
is GalleryScreen.Event.Sync -> coroutineScope.launch {
selected.forEach { sync.sync(it.path) }
selected = emptyList()
}
is GalleryScreen.Event.Result -> {
images.add(event.value)
takePhoto = false
}
is GalleryScreen.Event.Toggle -> itemList[event.index].also {
if (it in selected) selected -= it else selected += it
}
}
}
}
| 41
|
Kotlin
|
33
| 116
|
9c8783ea1a205050c5de7507e621a70f2bc5c892
| 5,355
|
playground.ashdavies.dev
|
Apache License 2.0
|
app/src/main/java/dev/shorthouse/coinwatch/ui/screen/settings/component/SettingsItem.kt
|
shorthouse
| 655,260,745
| false
|
{"Kotlin": 669344}
|
package dev.shorthouse.coinwatch.ui.screen.settings.component
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.width
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.rounded.ChevronRight
import androidx.compose.material.icons.rounded.Home
import androidx.compose.material3.Icon
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.vector.ImageVector
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import dev.shorthouse.coinwatch.ui.theme.AppTheme
@Composable
fun SettingsItem(
title: String,
onClick: () -> Unit,
modifier: Modifier = Modifier,
subtitle: String? = null,
leadingIcon: ImageVector? = null,
trailingIcon: ImageVector? = null
) {
Row(
verticalAlignment = Alignment.CenterVertically,
modifier = modifier
.fillMaxWidth()
.clickable { onClick() }
.padding(horizontal = 16.dp)
.height(80.dp)
) {
leadingIcon?.let {
Icon(
imageVector = leadingIcon,
tint = MaterialTheme.colorScheme.onBackground,
contentDescription = null
)
Spacer(Modifier.width(12.dp))
}
Column(modifier = Modifier.weight(1f)) {
Text(
text = title,
color = MaterialTheme.colorScheme.onBackground,
style = MaterialTheme.typography.bodyMedium
)
subtitle?.let {
Text(
text = it,
color = MaterialTheme.colorScheme.onSurfaceVariant,
style = MaterialTheme.typography.bodyMedium
)
}
}
trailingIcon?.let {
Icon(
imageVector = trailingIcon,
tint = MaterialTheme.colorScheme.onBackground,
contentDescription = null
)
}
}
}
@Composable
@Preview(showBackground = true)
fun SettingsItemPreview() {
AppTheme {
SettingsItem(
title = "Start destination",
subtitle = "Market",
leadingIcon = Icons.Rounded.Home,
trailingIcon = Icons.Rounded.ChevronRight,
onClick = {}
)
}
}
| 3
|
Kotlin
|
7
| 85
|
26b7499114c939342b17a057d1d41c6f8094ee99
| 2,810
|
CoinWatch
|
Apache License 2.0
|
glide-v3/src/main/kotlin/com/ronnnnn/glidemigrationsample/AppGlideModule.kt
|
ronnnnn
| 94,607,669
| false
| null |
package com.ronnnnn.glidemigrationsample
import android.content.Context
import com.bumptech.glide.Glide
import com.bumptech.glide.GlideBuilder
import com.bumptech.glide.integration.okhttp3.OkHttpGlideModule
import com.bumptech.glide.integration.okhttp3.OkHttpUrlLoader
import com.bumptech.glide.load.DecodeFormat
import com.bumptech.glide.load.engine.cache.LruResourceCache
import com.bumptech.glide.load.model.GlideUrl
import com.ronnnnn.glidemigrationsample.services.GMSRetrofit
import java.io.InputStream
/**
* Created by kokushiseiya on 2017/06/20.
*/
class AppGlideModule : OkHttpGlideModule() {
override fun applyOptions(context: Context, builder: GlideBuilder) {
builder.setMemoryCache(LruResourceCache(1024 * 1024 * 100)) // 100MB cache
.setDecodeFormat(DecodeFormat.PREFER_ARGB_8888) // default decode format is PREFER_RGB_565
}
override fun registerComponents(context: Context, glide: Glide) {
val client = GMSRetrofit.okHttpClient
glide.register(GlideUrl::class.java, InputStream::class.java, OkHttpUrlLoader.Factory(client))
}
}
| 0
|
Kotlin
|
2
| 5
|
6c060f5b679e95802a7dd0b9410fb8d403b8ac0b
| 1,102
|
GlideMigrationSample
|
Apache License 2.0
|
hello-world/model/src/main/kotlin/com/gongsung/sample/SampleModel.kt
|
403-gallery-gongsung
| 736,332,935
| false
|
{"Kotlin": 96306}
|
package com.gongsung.sample
interface SampleIdentity {
val sampleIdentity: Long
companion object {
fun of(id: Long) = SimpleSampleIdentity(sampleIdentity = id)
}
}
interface SampleProps {
val value: String
}
interface SampleModel :
SampleIdentity,
SampleProps
data class SimpleSampleIdentity(
override val sampleIdentity: Long,
) : SampleIdentity
| 14
|
Kotlin
|
0
| 1
|
0f9322f55b2ae1fbfa1d36dadd9310f619afa1a4
| 388
|
meet-in
|
Apache License 2.0
|
app/src/main/java/com/turastory/falcon/MainActivity.kt
|
turastory
| 154,104,058
| false
| null |
package com.turastory.falcon
import android.os.Bundle
import android.support.v7.app.AppCompatActivity
import android.util.Log
import android.view.Menu
import android.view.MenuItem
import android.widget.Toast
import com.turastory.falcon.ui.feed.FeedFragment
import com.turastory.falcon.ui.feed.FeedViewModel
import com.turastory.falcon.ui.makeGone
import com.turastory.falcon.ui.makeVisible
import com.turastory.falcon.ui.wallet.WalletFragment
import com.turastory.falcon.util.EventBus
import kotlinx.android.synthetic.main.main_activity.*
class MainActivity : AppCompatActivity() {
// TODO: more concrete implementation
private var state: String = "initial"
private val feedViewModel by lazy {
FeedViewModel(Provider.provideDataSource(applicationContext))
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.main_activity)
setSupportActionBar(bottomAppBar)
addFeedButton.setOnClickListener {
Log.e("asdf", "Sending events")
EventBus.sendEvent("add_feed")
}
if (savedInstanceState == null) {
showFeed()
}
}
override fun onCreateOptionsMenu(menu: Menu?): Boolean {
menuInflater.inflate(R.menu.bottom_app_bar_items, menu)
return true
}
override fun onOptionsItemSelected(item: MenuItem?): Boolean {
return item?.run {
when (itemId) {
R.id.action_feed -> showFeed()
R.id.action_wallet -> showWallet()
R.id.action_settings -> toast("Settings!")
}
return true
} ?: false
}
private fun toast(s: String) {
Toast.makeText(this, s, Toast.LENGTH_SHORT).show()
}
private fun showWallet() {
if (state == "wallet")
return
state = "wallet"
supportFragmentManager.beginTransaction()
.replace(R.id.container, WalletFragment.newInstance(), "wallet")
.commitNow()
addFeedButton.makeGone()
}
private fun showFeed() {
if (state == "feed")
return
state = "feed"
supportFragmentManager.beginTransaction()
.replace(R.id.container, FeedFragment.newInstance().apply {
setViewModel(feedViewModel)
}, "feed")
.commitNow()
addFeedButton.makeVisible()
}
}
| 0
|
Kotlin
|
0
| 0
|
ec2d5472d7d7a4172b056e938bc4a0e1a8e41471
| 2,459
|
falcon-android
|
Apache License 2.0
|
dsl/src/main/kotlin/com/faendir/awscdkkt/generated/services/athena/EngineVersionPropertyDsl.kt
|
F43nd1r
| 643,016,506
| false
| null |
package com.faendir.awscdkkt.generated.services.athena
import com.faendir.awscdkkt.AwsCdkDsl
import javax.`annotation`.Generated
import kotlin.Unit
import software.amazon.awscdk.services.athena.CfnWorkGroup
@Generated
public fun buildEngineVersionProperty(initializer: @AwsCdkDsl
CfnWorkGroup.EngineVersionProperty.Builder.() -> Unit): CfnWorkGroup.EngineVersionProperty =
CfnWorkGroup.EngineVersionProperty.Builder().apply(initializer).build()
| 1
|
Kotlin
|
0
| 0
|
a1cf8fbfdfef9550b3936de2f864543edb76348b
| 455
|
aws-cdk-kt
|
Apache License 2.0
|
umbrella-starter/app/src/main/java/com/raywenderlich/android/rwandroidtutorial/base/BasePresenter.kt
|
pethersilva
| 197,105,482
| false
| null |
package com.raywenderlich.android.rwandroidtutorial.base
interface BasePresenter {
fun onDestroy()
}
| 0
|
Kotlin
|
0
| 0
|
f5b0ffd0ff0d85568e3dc5842a08b4537e36949e
| 105
|
umbrella-mvp
|
MIT License
|
app/src/main/java/com/goldenowl/ecommerce/utils/FieldValidators.kt
|
longnghia
| 490,517,031
| false
|
{"Kotlin": 599604, "Shell": 367}
|
package com.goldenowl.ecommerce.utils
import android.text.Editable
import android.text.TextWatcher
import android.util.Patterns
import java.util.regex.Pattern
object FieldValidators {
/**
* checking pattern of email
* @param email input email
* @return true if matches with email address else false
*/
fun isValidEmail(email: String): Boolean {
return Patterns.EMAIL_ADDRESS.matcher(email).matches()
}
/**
* checking is string contain any number
* @param string value to check
* @return true if contain else false
*/
fun isStringContainNumber(text: String): Boolean {
val pattern = Pattern.compile(".*\\d.*")
val matcher = pattern.matcher(text)
return matcher.matches()
}
/**
* checking if if string contain upper and lower case value
* @param string to check
* @return true if contain else false
*/
fun isStringLowerAndUpperCase(text: String): Boolean {
val lowerCasePattern = Pattern.compile(".*[a-z].*")
val upperCasePattern = Pattern.compile(".*[A-Z].*")
val lowerCasePatterMatcher = lowerCasePattern.matcher(text)
val upperCasePatterMatcher = upperCasePattern.matcher(text)
return if (!lowerCasePatterMatcher.matches()) {
false
} else upperCasePatterMatcher.matches()
}
/**
* checking is string contain any special character
* @param string to check
* @return return true if contain else false.
*/
fun isStringContainSpecialCharacter(text: String): Boolean {
val specialCharacterPattern = Pattern.compile("[^a-zA-Z0-9 ]")
val specialCharacterMatcher = specialCharacterPattern.matcher(text)
return specialCharacterMatcher.find()
}
interface TextChange : TextWatcher {
abstract fun onTextChanged(s: CharSequence?)
override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {
}
override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {
onTextChanged(s)
}
override fun afterTextChanged(s: Editable?) {
}
}
}
| 0
|
Kotlin
|
1
| 3
|
2fce27c406981cac795c8dce80ffac832abf14e3
| 2,191
|
E-Commerce-Application
|
MIT License
|
module-navigation/src/main/java/com/pp/navigation/repository/SystemRepository.kt
|
PPQingZhao
| 651,920,234
| false
|
{"Kotlin": 391209, "Java": 23883}
|
package com.pp.navigation.repository
import androidx.paging.Pager
import androidx.paging.PagingConfig
import androidx.paging.PagingData
import com.pp.common.http.wanandroid.api.WanAndroidService
import com.pp.common.http.wanandroid.bean.*
import com.pp.common.paging.ArticlePagingSource
import kotlinx.coroutines.flow.Flow
object SystemRepository {
suspend fun getSystemList(): ResponseBean<List<ArticleListBean>> {
return runCatchingResponse {
WanAndroidService.systemApi.getSystem()
}
}
fun getSystemArticle(cid: Int): Flow<PagingData<ArticleBean>> {
return Pager(config = PagingConfig(15), initialKey = 0, pagingSourceFactory = {
SystemArticlePagingSource(cid)
}).flow
}
private class SystemArticlePagingSource(val cid: Int) : ArticlePagingSource() {
override suspend fun getPageData(page: Int): ArticlePageBean? {
return WanAndroidService.systemApi.getSystemArticle(cid = cid, page = page).data
}
}
}
| 0
|
Kotlin
|
0
| 1
|
fa136caa315c4eab80e0d86ce9ee2a210cda6fec
| 1,021
|
WanAndroid-kotlin
|
Apache License 2.0
|
library-service/src/main/kotlin/library/service/business/books/domain/BookRecord.kt
|
nt-ca-aqe
| 100,617,700
| false
| null |
package library.service.business.books.domain
import library.service.business.books.domain.composites.Book
import library.service.business.books.domain.states.Available
import library.service.business.books.domain.states.BookState
import library.service.business.books.domain.states.Borrowed
import library.service.business.books.domain.types.Author
import library.service.business.books.domain.types.BookId
import library.service.business.books.domain.types.Borrower
import library.service.business.books.domain.types.Title
import library.service.business.books.exceptions.BookAlreadyBorrowedException
import library.service.business.books.exceptions.BookAlreadyReturnedException
import java.time.OffsetDateTime
import java.util.*
/**
* Aggregate of a [Book], its unique reference ID ([UUID]) and [state][BookState].
*/
data class BookRecord(
val id: BookId,
val book: Book,
val state: BookState = Available
) {
/**
* Changes the [Title] of this [BookRecord's][BookRecord] [Book]
*
* @param title the new [Title]
* @return a new [BookRecord] instance with the new [Title]
*/
fun changeTitle(title: Title) = copy(book = book.copy(title = title))
/**
* Changes the list of [Authors][Author] of this [BookRecord's][BookRecord]
* [Book]. Might be empty in order to remove the existing authors.
*
* @param authors the new list of [Authors][Author]
* @return a new [BookRecord] instance with the new [Authors][Author]
*/
fun changeAuthors(authors: List<Author>) = copy(book = book.copy(authors = authors.toList()))
/**
* Changes the number of pages of this [BookRecord's][BookRecord] [Book].
* Might be null in order to remove the existing number of pages.
*
* @param numberOfPages the new number of pages
* @return a new [BookRecord] instance with the new number of pages
*/
fun changeNumberOfPages(numberOfPages: Int?) = copy(book = book.copy(numberOfPages = numberOfPages))
/**
* Tries to borrow this [BookRecord].
*
* Borrowing is a book's transition from the [Available] to the [Borrowed]
* state. And can only be executed if the book is in the [Available] state.
* Attempting to borrow an already [Borrowed] book will result in an
* exception.
*
* In order to borrow a book, a [Borrower] and an [OffsetDateTime] for
* the time of borrowing must be provided.
*
* @param by who is borrowing the book
* @param on when was the book borrowed
* @return a new [BookRecord] instance with the new state of [Borrowed]
* @throws BookAlreadyBorrowedException in case the book is already
* [Borrowed] by someone
*/
fun borrow(by: Borrower, on: OffsetDateTime): BookRecord {
if (state is Borrowed) {
throw BookAlreadyBorrowedException(id)
}
return copy(state = Borrowed(by, on))
}
/**
* Tries to return this [BookRecord].
*
* Returning is a book's transition from the [Borrowed] to the [Available]
* state. And can only be executed if the book is in the [Borrowed] state.
* Attempting to return an already [Available] book will result in an
* exception.
*
* @return a new [BookRecord] instance with the new state of [Available]
* @throws BookAlreadyReturnedException in case the book is already
* [Available]
*/
fun `return`(): BookRecord {
if (state is Available) {
throw BookAlreadyReturnedException(id)
}
return copy(state = Available)
}
}
| 11
|
Kotlin
|
11
| 14
|
2942752684ce82167880908caed4111e402b6caa
| 3,603
|
library-app
|
Apache License 2.0
|
app/src/main/java/com/tao/chinachuclient/ui/programdetail/ProgramDetailActivity.kt
|
sugtao4423
| 41,703,434
| false
| null |
package com.tao.chinachuclient.ui.programdetail
import android.app.AlertDialog
import android.content.Intent
import android.graphics.BitmapFactory
import android.os.Bundle
import android.util.Base64
import android.view.Menu
import android.view.MenuItem
import android.widget.SeekBar
import android.widget.SeekBar.OnSeekBarChangeListener
import android.widget.Toast
import androidx.activity.viewModels
import androidx.annotation.StringRes
import androidx.appcompat.app.AppCompatActivity
import com.tao.chinachuclient.R
import com.tao.chinachuclient.databinding.ActivityProgramDetailBinding
import com.tao.chinachuclient.databinding.CaptureDialogBinding
import com.tao.chinachuclient.ui.SelectionLinkMovementMethod
import com.tao.chinachuclient.ui.StreamingUtil
import com.tao.chinachuclient.ui.showimage.ShowImageActivity
import sugtao4423.library.chinachu4j.Program
import sugtao4423.library.chinachu4j.Recorded
import sugtao4423.library.chinachu4j.Reserve
import sugtao4423.support.progressdialog.ProgressDialog
class ProgramDetailActivity : AppCompatActivity() {
private val viewModel: ProgramDetailActivityViewModel by viewModels()
private var progressDialog: ProgressDialog? = null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
val binding = ActivityProgramDetailBinding.inflate(layoutInflater).also {
it.lifecycleOwner = this
it.viewModel = viewModel
}
setContentView(binding.root)
supportActionBar?.setDisplayHomeAsUpEnabled(true)
viewModel.programType = intent.getIntExtra("type", -1)
if (viewModel.programType == -1) {
finish()
return
}
intent.getSerializableExtra("reserve")?.let { viewModel.reserveProgram = it as Reserve }
intent.getSerializableExtra("recorded")?.let { viewModel.recordedProgram = it as Recorded }
intent.getSerializableExtra("program")?.let { viewModel.program = it as Program }
binding.programDetailDetail.movementMethod = SelectionLinkMovementMethod(this)
viewModel.onToast.observe(this) {
Toast.makeText(this, it, Toast.LENGTH_SHORT).show()
}
viewModel.toggleProgressDialog.observe(this) {
if (progressDialog != null) {
progressDialog!!.dismiss()
progressDialog = null
return@observe
}
progressDialog = ProgressDialog(this).apply {
setMessage(getString(R.string.loading))
isIndeterminate = false
setProgressStyle(ProgressDialog.STYLE_SPINNER)
setCancelable(true)
show()
}
}
viewModel.actionBarTitle.observe(this) {
supportActionBar?.title = it
}
viewModel.thumbnailBase64.observe(this) {
val decodedString = Base64.decode(it, Base64.DEFAULT)
val img = BitmapFactory.decodeByteArray(decodedString, 0, decodedString.size)
binding.programDetailImage.setImageBitmap(img)
}
viewModel.showOpenThumbnailDialog.observe(this) {
showOpenThumbnailDialog(it)
}
viewModel.startShowImageActivity.observe(this) {
startActivity(Intent(this, ShowImageActivity::class.java).apply {
putExtra("base64", it.base64)
putExtra("programId", it.programId)
putExtra("pos", it.pos)
})
}
viewModel.startStreamingApp.observe(this) {
StreamingUtil(this).startStreamingApp(it)
}
viewModel.operationResultDialog.observe(this) {
AlertDialog.Builder(this).setTitle(it.title).setMessage(it.message).show()
}
}
private fun showOpenThumbnailDialog(data: ProgramDetailActivityViewModel.OpenThumbnailDialogData) {
val binding = CaptureDialogBinding.inflate(layoutInflater).also {
it.data = data
it.capSeek.setOnSeekBarChangeListener(object : OnSeekBarChangeListener {
override fun onProgressChanged(seekBar: SeekBar, progress: Int, fromUser: Boolean) {
it.capPos.setText(progress.toString())
}
override fun onStartTrackingTouch(seekBar: SeekBar?) {}
override fun onStopTrackingTouch(seekBar: SeekBar?) {}
})
}
AlertDialog.Builder(this).also {
it.setView(binding.root)
it.setNegativeButton(R.string.cancel, null)
it.setPositiveButton(R.string.ok) { _, _ ->
viewModel.openCapture(
binding.capPos.text.toString().toInt(),
binding.capResolution.text.toString()
)
}
it.setNeutralButton(R.string.zoom_this_state) { _, _ ->
viewModel.openCaptureThisState()
}
it.show()
}
}
override fun onCreateOptionsMenu(menu: Menu): Boolean {
viewModel.onCreateOptionsMenu(menu)
return true
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
fun confirm(@StringRes titleRes: Int) {
AlertDialog.Builder(this).apply {
setTitle(titleRes)
setMessage(viewModel.programFullTitle)
setNegativeButton(R.string.cancel, null)
setPositiveButton(R.string.ok) { _, _ -> viewModel.doOptionOperations(item.itemId) }
show()
}
}
when (item.itemId) {
android.R.id.home -> finish()
ProgramDetailActivityViewModel.MenuId.RESERVE -> {
confirm(R.string.is_reserve)
}
ProgramDetailActivityViewModel.MenuId.DELETE_RESERVE -> {
confirm(R.string.is_delete_reserve)
}
ProgramDetailActivityViewModel.MenuId.SKIP_RESERVE_RELEASE -> {
confirm(R.string.is_skip_reserve_release)
}
ProgramDetailActivityViewModel.MenuId.SKIP_RESERVE -> {
confirm(R.string.is_skip_reserve)
}
ProgramDetailActivityViewModel.MenuId.PLAY_STREAMING -> {
viewModel.startPlayStreamingApp()
}
ProgramDetailActivityViewModel.MenuId.PLAY_ENCODE_STREAMING -> {
viewModel.startPlayEncodeStreamingActivity()
}
ProgramDetailActivityViewModel.MenuId.DELETE_RECORDED_FILE -> {
confirm(R.string.is_delete_recorded_file)
}
}
return super.onOptionsItemSelected(item)
}
}
| 0
|
Kotlin
|
1
| 12
|
790ed77fcf66fb6197b7bc6a39faa2ad5bb96c23
| 6,673
|
ChinachuClient
|
MIT License
|
src/main/kotlin/it/scoppelletti/spaceship/types/AbstractDateConverter.kt
|
dscoppelletti
| 263,568,278
| false
| null |
/*
* Copyright (C) 2019 <NAME>, <http://www.scoppelletti.it/>.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package it.scoppelletti.spaceship.types
import it.scoppelletti.spaceship.i18n.I18NProvider
import java.time.LocalDate
import java.time.format.DateTimeFormatter
import java.time.format.DateTimeFormatterBuilder
import java.time.format.DateTimeParseException
import java.time.format.SignStyle
import java.time.temporal.ChronoField
private const val DATE_SEP = '/'
/**
* Abstract implementation of `DateConverter` interface.
*
* @since 1.0.0
*
* @constructor
* @param i18nProvider Provides I18N dependencies.
*/
public abstract class AbstractDateConverter protected constructor(
private val i18nProvider: I18NProvider
) : DateConverter {
private val formatter: DateTimeFormatter by lazy {
createFormatter()
}
private val parser: DateTimeFormatter by lazy {
createParser()
}
override fun format(value: LocalDate?): String? =
value?.format(formatter)
private fun createFormatter() : DateTimeFormatter {
val order: Array<ChronoField> = getDateFormatOrder()
return DateTimeFormatterBuilder()
.appendValue(order[0], order[0].toMaxWidth())
.appendLiteral(DATE_SEP)
.appendValue(order[1], order[1].toMaxWidth())
.appendLiteral(DATE_SEP)
.appendValue(order[2], order[2].toMaxWidth())
.toFormatter(i18nProvider.currentLocale())
}
@Throws(DateTimeParseException::class)
override fun parse(text: String?): LocalDate? {
if (text.isNullOrBlank()) {
return null
}
val s = text.trim()
.replace('-', DATE_SEP)
.replace('.', DATE_SEP)
return LocalDate.parse(s, parser)
}
private fun createParser() : DateTimeFormatter {
val order: Array<ChronoField> = getDateFormatOrder()
return DateTimeFormatterBuilder()
.appendValue(order[0], order[0].toMinWidth(),
order[0].toMaxWidth(), SignStyle.NOT_NEGATIVE)
.appendLiteral(DATE_SEP)
.appendValue(order[1], order[1].toMinWidth(),
order[1].toMaxWidth(), SignStyle.NOT_NEGATIVE)
.appendLiteral(DATE_SEP)
.appendValue(order[2], order[2].toMinWidth(),
order[2].toMaxWidth(), SignStyle.NOT_NEGATIVE)
.toFormatter(i18nProvider.currentLocale())
}
/**
* Gets the current date format.
*
* @return The date format as an array of three `ChronoField` values.
*/
protected abstract fun getDateFormatOrder(): Array<ChronoField>
}
private fun ChronoField.toMinWidth(): Int =
if (this == ChronoField.YEAR) 4 else 1
private fun ChronoField.toMaxWidth(): Int =
if (this == ChronoField.YEAR) 4 else 2
| 0
|
Kotlin
|
0
| 0
|
fe5118713f44ebf0328b210d9cf1c99e42c6b061
| 3,456
|
spaceship-stdlib
|
Apache License 2.0
|
just-chat/src/main/java/es/rudo/justchat/models/UserData.kt
|
rudoapps
| 561,220,683
| false
|
{"Kotlin": 132536}
|
package es.rudo.justchat.models
open class UserData {
var userId: String? = null
var userName: String? = null
var userPhoto: String? = null
var userDeviceToken: String? = null
}
| 0
|
Kotlin
|
0
| 0
|
72cc7c871ef96792f53adf83319b598cceaf712a
| 195
|
JustChat-kotlin
|
MIT License
|
app/src/main/java/com/masterplus/trdictionary/features/word_detail/word_category/WordCategoryPage.kt
|
Ramazan713
| 634,957,286
| false
|
{"Kotlin": 990286}
|
package com.masterplus.trdictionary.features.word_detail.word_category
import androidx.compose.material3.windowsizeclass.WindowWidthSizeClass
import androidx.compose.runtime.Composable
import androidx.compose.ui.res.stringResource
import androidx.paging.compose.LazyPagingItems
import androidx.window.layout.DisplayFeature
import com.masterplus.trdictionary.R
import com.masterplus.trdictionary.core.domain.enums.ListDetailContentType
import com.masterplus.trdictionary.core.shared_features.word_list_detail.domain.model.WordWithSimilar
import com.masterplus.trdictionary.core.shared_features.word_list_detail.domain.use_case.save_point_info.SavePointCategoryInfoUseCases
import com.masterplus.trdictionary.core.shared_features.word_list_detail.presentation.WordsListDetailDialogEvent
import com.masterplus.trdictionary.core.shared_features.word_list_detail.presentation.WordsListDetailEvent
import com.masterplus.trdictionary.core.shared_features.word_list_detail.presentation.WordsListDetailSheetEvent
import com.masterplus.trdictionary.core.shared_features.word_list_detail.presentation.WordsListDetailState
import com.masterplus.trdictionary.core.shared_features.word_list_detail.presentation.pager.WordsPagerListDetailAdaptivePage
@Composable
fun WordCategoryPage(
state: WordsListDetailState,
onEvent: (WordsListDetailEvent) -> Unit,
words: LazyPagingItems<WordWithSimilar>,
listDetailContentType: ListDetailContentType,
windowWidthSizeClass: WindowWidthSizeClass,
displayFeatures: List<DisplayFeature>,
savePointInfo: SavePointCategoryInfoUseCases.SavePointCategoryInfo,
onNavigateBack: (()->Unit)?,
onRelatedWordClicked: (Int) -> Unit,
initPos: Int
) {
WordsPagerListDetailAdaptivePage(
state = state,
onEvent = onEvent,
words = words,
initPos = initPos,
topBarTitle = stringResource(R.string.word_list_c),
listHeaderDescription = savePointInfo.savePointTitle,
listDetailContentType = listDetailContentType,
windowWidthSizeClass = windowWidthSizeClass,
displayFeatures = displayFeatures,
onNavigateBack = onNavigateBack,
onListItemLongClick = {i,w->
onEvent(
WordsListDetailEvent.ShowSheet(
WordsListDetailSheetEvent.ShowSelectBottomMenu(
word = w,
pos = i,
savePointDestination = savePointInfo.savePointDestination,
listIdControl = null,
)
)
)
},
onNavigateToRelatedWord = onRelatedWordClicked,
onDetailFavoriteClick = {w->
onEvent(WordsListDetailEvent.AddFavorite(w.wordId))
},
onDetailSelectListPressed = {w->
onEvent(
WordsListDetailEvent.ShowSheet(
WordsListDetailSheetEvent.ShowSelectList(w.wordId,null))
)
},
onSavePointClick = {pos->
onEvent(
WordsListDetailEvent.ShowDialog(
WordsListDetailDialogEvent.EditSavePoint(
savePointDestination = savePointInfo.savePointDestination,
shortTitle = savePointInfo.savePointTitle,
pos = pos
)
)
)
},
)
}
| 0
|
Kotlin
|
0
| 1
|
0aa1643c4347203f9339dfa4896bf176712472c9
| 3,389
|
Turkce-ve-Osmanlica-Sozluk
|
Apache License 2.0
|
app/src/main/java/com/jnj/vaccinetracker/common/data/encryption/SecurePasswordGenerator.kt
|
johnsonandjohnson
| 503,902,626
| false
|
{"Kotlin": 1690434}
|
package com.jnj.vaccinetracker.common.data.encryption
import java.security.SecureRandom
import javax.inject.Inject
import javax.inject.Singleton
@Singleton
class SecurePasswordGenerator @Inject constructor() {
private val secureRandom by lazy {
SecureRandom()
}
fun generateSecurePassword(maxLength: Int, upperCase: Boolean, lowerCase: Boolean, numbers: Boolean, specialCharacters: Boolean): String {
val upperCaseChars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
val lowerCaseChars = "abcdefghijklmnopqrstuvwxyz"
val numberChars = "0123456789"
val specialChars = "!@#$%^&*()_-+=<>?/{}~|"
var allowedChars = ""
val rn = secureRandom
val sb = StringBuilder(maxLength)
//this will fulfill the requirements of atleast one character of a type.
if (upperCase) {
allowedChars += upperCaseChars
sb.append(upperCaseChars[rn.nextInt(upperCaseChars.length - 1)])
}
if (lowerCase) {
allowedChars += lowerCaseChars
sb.append(lowerCaseChars[rn.nextInt(lowerCaseChars.length - 1)])
}
if (numbers) {
allowedChars += numberChars
sb.append(numberChars[rn.nextInt(numberChars.length - 1)])
}
if (specialCharacters) {
allowedChars += specialChars
sb.append(specialChars[rn.nextInt(specialChars.length - 1)])
}
//fill the allowed length from different chars now.
for (i in sb.length until maxLength) {
sb.append(allowedChars[rn.nextInt(allowedChars.length)])
}
return sb.toString()
}
}
| 2
|
Kotlin
|
1
| 1
|
3b9730f742e488543bed86f4dec6c67e477b1f15
| 1,650
|
vxnaid
|
Apache License 2.0
|
app/src/main/java/com/example/moviedb/ui/screen/favoritemovie/FavoriteMovieViewModel.kt
|
pareen1504
| 186,191,995
| false
| null |
package com.example.moviedb.ui.screen.favoritemovie
import com.example.moviedb.data.local.dao.MovieDao
import com.example.moviedb.data.model.Movie
import com.example.moviedb.ui.base.BaseLoadMoreRefreshViewModel
import kotlinx.coroutines.launch
class FavoriteMovieViewModel(
private val movieDao: MovieDao
) : BaseLoadMoreRefreshViewModel<Movie>() {
override fun loadData(page: Int) {
ioScope.launch {
try {
onLoadSuccess(page, movieDao.getFavorite(getNumberItemPerPage(), page))
} catch (e: Exception) {
onLoadFail(e)
}
}
}
}
| 0
|
Kotlin
|
0
| 0
|
046b44ecdd2bda8d764ffd90f2fa4298adb90097
| 625
|
TheMoviePlanet
|
Apache License 2.0
|
src/test/kotlin/io/openapiprocessor/core/model/datatypes/SingleDataTypeSpec.kt
|
openapi-processor
| 268,750,021
| false
| null |
/*
* Copyright 2021 https://github.com/openapi-processor/openapi-processor-core
* PDX-License-Identifier: Apache-2.0
*/
package io.openapiprocessor.core.model.datatypes
import io.kotest.core.spec.style.StringSpec
import io.kotest.data.blocking.forAll
import io.kotest.data.row
import io.kotest.matchers.shouldBe
class SingleDataTypeSpec : StringSpec({
"uses id name and type name of item" {
val ndt = SingleDataType("Single", "wrap",
ObjectDataType(DataTypeName("Foo", "FooX"), "pkg", linkedMapOf())
)
ndt.getName() shouldBe "Single<Foo>"
ndt.getTypeName() shouldBe "Single<FooX>"
}
"should create import with type name" {
forAll(row("Foo", "Foo"), row("Fooo", "FoooX")) { id, type ->
val ndt = SingleDataType("Single", "wrap",
ObjectDataType(DataTypeName(id, type), "pkg")
)
ndt.getImports() shouldBe setOf(
"wrap.Single",
"pkg.$type"
)
}
}
})
| 8
|
Kotlin
|
4
| 7
|
1bf168c0af909fbdf7fa44ab3f9712492fb1380d
| 1,027
|
openapi-processor-core
|
Apache License 2.0
|
app/src/main/java/com/battlelancer/seriesguide/ui/menus/ManualSyncMenu.kt
|
UweTrottmann
| 1,990,682
| false
|
{"Kotlin": 2280980, "Java": 880919, "PowerShell": 1268}
|
// SPDX-License-Identifier: Apache-2.0
// Copyright 2024 <NAME>
package com.battlelancer.seriesguide.ui.menus
import android.content.Context
import android.view.Menu
import android.view.MenuInflater
import android.view.MenuItem
import androidx.annotation.MenuRes
import androidx.core.view.MenuProvider
import com.battlelancer.seriesguide.R
import com.battlelancer.seriesguide.sync.SgSyncAdapter
/**
* Adds actions for manual syncing at the last position in the menu.
*
* As this requires a [context], probably only instantiate when it is available,
* for example using lazy initialization.
*/
open class ManualSyncMenu(
private val context: Context,
@MenuRes private val menuRes: Int
) : MenuProvider {
override fun onCreateMenu(menu: Menu, menuInflater: MenuInflater) {
menuInflater.inflate(menuRes, menu)
menu.addSubMenu(Menu.NONE, 0, Menu.CATEGORY_SECONDARY, R.string.sync_manually).apply {
add(Menu.NONE, MENU_ITEM_SYNC_UPDATE_ID, Menu.NONE, R.string.sync_and_update)
add(Menu.NONE, MENU_ITEM_SYNC_DOWNLOAD_ID, Menu.NONE, R.string.sync_and_download_all)
}
}
override fun onMenuItemSelected(menuItem: MenuItem): Boolean {
return when (menuItem.itemId) {
MENU_ITEM_SYNC_UPDATE_ID -> {
SgSyncAdapter.requestSyncDeltaImmediate(context, true)
true
}
MENU_ITEM_SYNC_DOWNLOAD_ID -> {
SgSyncAdapter.requestSyncFullImmediate(context, true)
true
}
else -> false
}
}
companion object {
// Choose IDs unlikely to collide with generated menu item IDs
private const val MENU_ITEM_SYNC_UPDATE_ID = 1
private const val MENU_ITEM_SYNC_DOWNLOAD_ID = 2
}
}
| 56
|
Kotlin
|
401
| 1,966
|
c7bc6445ecc58b841c1887a56146dc2d2f817007
| 1,800
|
SeriesGuide
|
Apache License 2.0
|
src/main/kotlin/io/foxcapades/lib/cli/builder/util/CharacterAppender.kt
|
Foxcapades
| 850,780,005
| false
|
{"Kotlin": 238928}
|
package io.foxcapades.lib.cli.builder.util
/**
* Defines a function that may be called to append a character to a buffer or
* stream.
*
* Simple example:
* ```kt
* val bld = StringBuilder()
*
* funThatTakesCharAppender(bld::append)
* ```
*
* @since 1.0.0
*/
fun interface CharacterAppender {
/**
* Appends the given character to the underlying buffer or stream.
*
* @param char Character to append.
*/
fun append(char: Char)
/**
* Convenience method for appending multiple characters at once.
*
* By default, this method simply calls `append(Char)` in a loop for each
* character in the given string, however explicit implementations of this
* interface may implement this in a more effective manner.
*
* @param string String of characters to append.
*/
fun append(string: CharSequence) = string.forEach(::append)
/**
* Convenience method for appending multiple characters at once.
*
* By default, this method simply calls `append(Char)` in a loop for each
* character in the given array, however explicit implementations of this
* interface may implement this in a more effective manner.
*
* @param string Array of characters to append.
*/
fun append(string: CharArray) = string.forEach(::append)
}
| 8
|
Kotlin
|
0
| 0
|
09e7d46cd02ded22d38e0dfacab63c4b7d8a9220
| 1,288
|
lib-kt-cli-builder
|
MIT License
|
src/main/kotlin/com/github/salomonbrys/gradle/kotlin/js/assembleweb/KotlinMppJsAssembleWebExtension.kt
|
dany-kun
| 161,050,809
| true
|
{"Kotlin": 20135}
|
package com.github.salomonbrys.gradle.kotlin.js.assembleweb
import com.github.salomonbrys.gradle.kotlin.js.jscompiletasks.mainJsCompileTask
import org.gradle.api.Action
import org.gradle.api.Project
import org.gradle.api.internal.plugins.DslObject
import org.jetbrains.kotlin.gradle.dsl.KotlinMultiplatformExtension
import org.jetbrains.kotlin.gradle.plugin.KotlinTarget
import java.lang.IllegalArgumentException
open class KotlinMppJsAssembleWebExtension(val project: Project) : KotlinJsAssembleWebExtension {
private fun createWebTargetFrom(target: KotlinTarget) = KotlinJsWebTarget(target.name, target.mainJsCompileTask, listOf(target.defaultConfigurationName), "${project.buildDir}/web/${target.name}")
val targets = project.container(KotlinJsWebTarget::class.java) {
val kotlin = project.extensions.getByName("kotlin") as KotlinMultiplatformExtension
val target = kotlin.targets.findByName(it) ?: throw IllegalArgumentException("Could not fined Kotlin target $it")
createWebTargetFrom(target)
}
init {
@Suppress("LeakingThis")
DslObject(this).extensions.add("targets", targets)
}
@JvmOverloads
fun KotlinTarget.thisTarget(action: Action<KotlinJsWebTarget> = Action {}) {
val target = createWebTargetFrom(this)
action.execute(target)
targets.add(target)
}
}
| 0
|
Kotlin
|
0
| 0
|
14788052f38d65f75288a6606237dbd781315c9c
| 1,365
|
Kotlin-JS-Gradle-Utils
|
MIT License
|
snippet-generator/src/gen.kt
|
WeAthFoLD
| 162,103,893
| true
|
{"Kotlin": 1737, "TypeScript": 869}
|
import com.google.gson.Gson
import java.io.File
class Item(val prefix: String, val body: Array<String>)
fun l(vararg xs: String): Array<String> = xs.toList().toTypedArray()
fun main(args: Array<String>) {
val gson = Gson()
val result = mutableMapOf(
"update" to Item("_update", l("function _update()", "$0", "end")),
"update60" to Item("_update60", l("function _update60()", "$0", "end")),
"init" to Item("_init", l("function _init()", "$0", "end")),
"draw" to Item("_draw", l("function _draw()", "$0", "end"))
)
val generalFuncs = listOf(
"flip",
"camera", "circ", "circfill", "clip", "cls", "color", "cursor", "fget",
"flip", "fset", "line", "pal", "palt", "pget", "print", "pset", "rect",
"rectfill", "sget", "spr", "sset", "sspr",
"add", "all", "del", "foreach", "pairs",
"btn", "btnp",
"music", "sfx",
"map", "mget", "mset",
"cstore", "memcpy", "memset", "peek", "poke", "reload",
"abs", "atan2", "band", "bnot", "bor", "bxor", "cos", "flr",
"max", "mid", "min", "rnd", "shl", "shr", "sin", "sqrt", "srand",
"cartdata", "dget", "dset",
"cocreate", "coresume", "costatus", "yield",
"setmetatable", "getmetatable", "type", "sub", "tonum", "tostr",
"time",
"menuitem", "extcmd",
"assert", "printh", "stat"
)
for (f in generalFuncs) {
result += f to Item(f, l("$f($0)"))
}
val generalTokens = listOf(
"function", "local", "begin", "end", "if", "else", "then", "for", "while"
)
for (f in generalTokens) {
result += f to Item(f, l(f));
}
File("D:\\test.json").writeText(gson.toJson(result))
}
| 0
|
Kotlin
|
0
| 0
|
17a800825dcbe37179f3ffac7f652332ec262b63
| 1,737
|
pico8-vscode
|
MIT License
|
account/src/main/java/com/davidm/account/entities/ClearedBalance.kt
|
davidmarinangeli
| 241,917,460
| false
| null |
package com.davidm.account.entities
data class ClearedBalance(
val currency: String,
val minorUnits: Int
)
| 0
|
Kotlin
|
0
| 9
|
f9ca93065beec4be7c8b6bc6c3b3ee0116b6317d
| 115
|
Sweet-Bank
|
Apache License 2.0
|
app/src/main/java/com/lmorda/shopper/app/ShopperApplication.kt
|
lmorda
| 503,058,600
| false
| null |
package com.lmorda.shopper.app
import android.app.Application
import dagger.hilt.android.HiltAndroidApp
@HiltAndroidApp
class ShopperApplication: Application() {
}
| 0
|
Kotlin
|
0
| 0
|
abd90671bcdd0e8d282f87ffa3fcf213c0953c8f
| 165
|
android-compose-sample
|
Apache License 2.0
|
NeumorphicViewSet/src/main/java/com/smb/neumorphicviewset/NeuButton.kt
|
SMehranB
| 365,499,118
| false
| null |
package com.smb.neumorphicviewset
import android.annotation.SuppressLint
import android.content.Context
import android.graphics.*
import android.os.Build
import android.util.AttributeSet
import android.view.MotionEvent
import android.view.View
import androidx.annotation.ColorInt
import androidx.annotation.DrawableRes
import androidx.annotation.FontRes
import androidx.annotation.StyleRes
import androidx.core.content.ContextCompat
import androidx.core.graphics.ColorUtils
import androidx.core.graphics.drawable.toBitmap
import com.smb.neumorphicviewset.interfaces.NeuUtil
class NeuButton : View, NeuUtil {
constructor(context: Context): super(context){
initAttributes(context, null, 0)
}
constructor(context: Context, attributeSet: AttributeSet) : super(context, attributeSet){
initAttributes(context, attributeSet, 0)
}
constructor(context: Context, attributeSet: AttributeSet, defStyleAttr: Int) : super(context, attributeSet, defStyleAttr){
initAttributes(context, attributeSet, defStyleAttr)
}
/* Paint objects */
private val backgroundPaint = Paint(Paint.ANTI_ALIAS_FLAG)
private val textPaint = Paint(Paint.ANTI_ALIAS_FLAG)
private val lightPaint = Paint(Paint.ANTI_ALIAS_FLAG)
private val shadowPaint = Paint(Paint.ANTI_ALIAS_FLAG)
private val drawablePaint = Paint(Paint.ANTI_ALIAS_FLAG)
/* Background parameters */
private var mBackgroundColor = ContextCompat.getColor(context, R.color.neuPrimaryColor)
private var cornerRadius: Float = dpToPixel(context, 8)
private val backgroundRectF = RectF()
/* Shadow and lighting parameters */
private var shadowMargin: Float = dpToPixel(context, 12)
private var lightDensity: Float = 0.5f
private var shadowDensity: Float = 0.5f
private var jutSize: Int = 1
private var jut: Jut = Jut.NORMAL
/* Drawable Parameters */
private lateinit var drawableStartBitmap: Bitmap
private lateinit var drawableEndBitmap: Bitmap
private var drawablePadding: Float = dpToPixel(context, 8)
private var drawableStartX: Float = 0f
private var drawableEndX: Float = 0f
private var drawablesY: Float = 0f
private var drawableDimension:Float = dpToPixel(context, 25)
private var drawableStart: Int = 0
private var drawableEnd: Int = 0
private var drawableTint: Int = 0
/* Text parameters */
private var mTextX: Float = 0f
private var mTextY: Float = 0f
private var textXOffSet: Float = 0f
private var horizontalPadding: Float = dpToPixel(context, 16)
private var verticalPadding: Float = dpToPixel(context, 16)
private var textHeight: Float = 0f
var textSizeDp: Float = dpToPixel(context, 16)
set(value) {
field = value
requestLayout()
}
@ColorInt
var textColor: Int = Color.BLACK
set(value) {
field = value
invalidate()
}
@StyleRes
var textStyle: Int = Typeface.NORMAL
set(value) {
field = value
requestLayout()
}
@FontRes
var textFont: Int = 0
set(value) {
field = value
requestLayout()
}
var disabledTextColor = Color.GRAY
var text: String = "Neumorphic Button"
set(value) {
field = value
requestLayout()
}
private fun initAttributes(context: Context, attributeSet: AttributeSet?, defStyleAttr: Int) {
val attrs = context.theme.obtainStyledAttributes(attributeSet, R.styleable.NeuButton, defStyleAttr, 0)
attrs.apply {
cornerRadius = getDimension(R.styleable.NeuButton_nb_cornerRadius, cornerRadius)
mBackgroundColor = getInteger(R.styleable.NeuButton_nb_ButtonColor, mBackgroundColor)
drawableDimension = getDimension(R.styleable.NeuButton_nb_drawableDimension, drawableDimension)
drawableStart = getResourceId(R.styleable.NeuButton_nb_drawableStart, 0)
drawableEnd = getResourceId(R.styleable.NeuButton_nb_drawableEnd, 0)
drawablePadding = getDimension(R.styleable.NeuButton_nb_drawablePadding, drawablePadding)
drawableTint = getInteger(R.styleable.NeuButton_nb_drawableTint, drawableTint)
lightDensity = getFloat(R.styleable.NeuButton_nb_lightDensity, lightDensity).coerceAtMost(1f)
shadowDensity = getFloat(R.styleable.NeuButton_nb_shadowDensity, shadowDensity).coerceAtMost(1f)
jutSize = getInt(R.styleable.NeuButton_nb_JutSize, jutSize)
horizontalPadding = getDimension(R.styleable.NeuButton_nb_HorizontalPadding, horizontalPadding)
verticalPadding = getDimension(R.styleable.NeuButton_nb_VerticalPadding, verticalPadding)
textStyle = getInt(R.styleable.NeuButton_nb_textStyle, textStyle)
textSizeDp = getDimension(R.styleable.NeuButton_nb_textSize, textSizeDp)
textColor = getInteger(R.styleable.NeuButton_nb_textColor, textColor)
textFont = getResourceId(R.styleable.NeuButton_nb_fontFamily, 0)
disabledTextColor = getInteger(R.styleable.NeuButton_nb_disabledTextColor, disabledTextColor)
text = getString(R.styleable.NeuButton_nb_text) ?: text
isEnabled = getBoolean(R.styleable.NeuButton_nb_enabled, true)
recycle()
}
when (jutSize) {
0 -> jut = Jut.SMALL
1 -> jut = Jut.NORMAL
2 -> jut = Jut.LARGE
}
setLayerTypeBasedOnSDK(this, lightPaint)
}
override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) {
val desiredDimensions = getDesiredDimensions()
val desiredWidth = desiredDimensions.width
val desiredHeight = desiredDimensions.height
setMeasuredDimension(getFinalDimension(desiredWidth, widthMeasureSpec),
getFinalDimension(desiredHeight, heightMeasureSpec))
}
override fun onLayout(changed: Boolean, left: Int, top: Int, right: Int, bottom: Int) {
adjustDrawables(drawableTint)
adjustJutParams(jut)
adjustText()
backgroundRectF.set(shadowMargin, shadowMargin, width.minus(shadowMargin), height.minus(shadowMargin))
backgroundPaint.color = mBackgroundColor
if (!isEnabled) {
disable()
}
super.onLayout(changed, left, top, right, bottom)
}
override fun onDraw(canvas: Canvas?) {
canvas?.apply {
drawRoundRect(backgroundRectF, cornerRadius, cornerRadius, lightPaint)
drawRoundRect(backgroundRectF, cornerRadius, cornerRadius, shadowPaint)
drawRoundRect(backgroundRectF, cornerRadius, cornerRadius, backgroundPaint)
drawText(text, mTextX, mTextY, textPaint)
if (drawableStart != 0) {
drawBitmap(drawableStartBitmap, drawableStartX, drawablesY, drawablePaint)
}
if (drawableEnd != 0) {
drawBitmap(drawableEndBitmap, drawableEndX, drawablesY, drawablePaint)
}
}
}
@SuppressLint("ClickableViewAccessibility")
override fun onTouchEvent(event: MotionEvent?): Boolean {
if(event?.action == MotionEvent.ACTION_DOWN && isEnabled){
if(event.x in backgroundRectF.left..backgroundRectF.right &&
event.y in backgroundRectF.top..backgroundRectF.bottom){
performClick()
return true
}
return false
}
return false
}
fun disable(){
textPaint.color = disabledTextColor
adjustDrawables(disabledTextColor)
isEnabled = false
invalidate()
}
fun enable() {
textPaint.color = textColor
adjustDrawables(drawableTint)
isEnabled = true
requestLayout()
}
fun setBackgroundParams(@ColorInt color: Int, radiusDp: Int) {
cornerRadius = dpToPixel(context, radiusDp)
mBackgroundColor = color
backgroundPaint.color = color
shadowPaint.color = color
lightPaint.color = color
invalidate()
}
fun setJutParams(jut: Jut) {
this.jut = jut
adjustJutParams(jut)
invalidate()
}
fun setJutParams(lightDensity: Float, shadowDensity: Float) {
this.lightDensity = lightDensity
this.shadowDensity = shadowDensity
adjustJutParams(jut)
invalidate()
}
fun setJutParams(lightDensity: Float, shadowDensity: Float, jut: Jut) {
this.lightDensity = lightDensity
this.shadowDensity = shadowDensity
this.jut = jut
adjustJutParams(jut)
invalidate()
}
fun setDrawableParams(@DrawableRes drawableStart: Int?, @DrawableRes drawableEnd: Int?) {
drawableStart?.let { this.drawableStart = it }
drawableEnd?.let { this.drawableEnd = it }
requestLayout()
}
fun setDrawableParams(@DrawableRes drawableStart: Int?, @DrawableRes drawableEnd: Int?, @ColorInt tint: Int?) {
drawableStart?.let { this.drawableStart = it }
drawableEnd?.let { this.drawableEnd = it }
tint?.let { drawableTint = it }
requestLayout()
}
fun setDrawableParams(@DrawableRes drawableStart: Int?, @DrawableRes drawableEnd: Int?, @ColorInt tint: Int?, horizontalPaddingDp: Int) {
drawableStart?.let { this.drawableStart = it }
drawableEnd?.let { this.drawableEnd = it }
tint?.let { drawableTint = it }
drawablePadding = dpToPixel(context, horizontalPaddingDp)
requestLayout()
}
fun setDrawableDimension(dimensionDp: Int) {
drawableDimension = dpToPixel(context, dimensionDp)
requestLayout()
}
fun setTextPaddings(horizontalPaddingDp: Int, verticalPaddingDp: Int) {
horizontalPadding = dpToPixel(context, horizontalPaddingDp)
verticalPadding = dpToPixel(context, verticalPaddingDp)
}
fun setText(text: String, sizeDp: Int, @ColorInt color: Int) {
this.text = text
textSizeDp = dpToPixel(context, sizeDp)
textColor = color
requestLayout()
}
fun setText(text: String, sizeDp: Int) {
this.text = text
textSizeDp = dpToPixel(context, sizeDp)
requestLayout()
}
fun setTypeface(style: Int, @FontRes font: Int) {
textStyle = style
textFont = font
requestLayout()
}
fun setTypeface(@StyleRes style: Int) {
textStyle = style
requestLayout()
}
private fun adjustDrawables(tint: Int) {
if(drawableStart != 0) {
val drawable = ContextCompat.getDrawable(context, drawableStart)!!
if (tint != 0) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
drawable.setTint(tint)
}
}
drawableStartBitmap = drawable.toBitmap(drawableDimension.toInt(), drawableDimension.toInt(), Bitmap.Config.ARGB_8888)
drawableStartX = shadowMargin.plus(drawablePadding)
}
if(drawableEnd != 0) {
val drawable = ContextCompat.getDrawable(context, drawableEnd)!!
if (tint != 0) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
drawable.setTint(tint)
}
}
drawableEndBitmap = drawable.toBitmap(drawableDimension.toInt(), drawableDimension.toInt(), Bitmap.Config.ARGB_8888)
drawableEndX = width
.minus(shadowMargin)
.minus(drawablePadding)
.minus(drawableDimension)
}
drawablesY = height.div(2f).minus(drawableDimension.div(2))
}
private fun adjustText() {
/**
* Setting all text parameters before the text is drawn
*/
textPaint.apply {
typeface = getTypeFace(context, textFont, textStyle)
textSize = this@NeuButton.textSizeDp
color = textColor
textAlign = Paint.Align.CENTER
}
mTextX = width.div(2f).plus(textXOffSet) // textXOffSet is the offset caused by the drawables on either side
val textVerticalMid = textPaint.descent().plus(textPaint.ascent()).div(2)
mTextY = height.div(2f).minus(textVerticalMid)
}
private fun getDesiredDimensions(): NeuUtil.MinimumDimensions {
/** Need to set the parameters that are determining in the measurement
* of the length of the text since the size of the view is calculated
* based on the height and the width of the text
*/
textPaint.apply {
typeface = getTypeFace(context, textFont, textStyle)
textSize = this@NeuButton.textSizeDp
}
textHeight = textPaint.descent().minus(textPaint.ascent())
val width = textPaint.measureText(text)
.plus(shadowMargin.times(2)) //the margin dedicated to the lighting and shadow from each side
.plus(horizontalPadding.times(2)) //this padding applies only to the text increasing the width of the view
.plus(getDrawablesCollectiveWidth())
val height = textHeight
.plus(shadowMargin.times(2))
.plus(verticalPadding.times(2)) //this padding applies only to the text increasing the height of the view
return NeuUtil.MinimumDimensions(width.toInt(), height.toInt())
}
private fun getDrawablesCollectiveWidth(): Float {
/**
* Calculating the amount of (collective) space needed for
* one or both of the drawables to be drawn
*/
var width = 0f
textXOffSet = 0f
if(drawableStart != 0){
width = width.plus(drawableDimension).plus(drawablePadding.times(2))
textXOffSet = textXOffSet
.plus(drawableDimension) //to put offset the text to the right
.plus(drawablePadding.times(2)) //Also to put offset the text to the right
.minus(horizontalPadding.div(2)) // to put the text in the middle of the distance between the drawable and the end of the view
}
if(drawableEnd != 0){
width = width.plus(drawableDimension).plus(drawablePadding.times(2))
textXOffSet = textXOffSet
.minus(drawableDimension)
.minus(drawablePadding.times(2))
.plus(horizontalPadding.div(2))
}
// The offset is divided by 2 to draw the text exactly
// in the middle of the available space between the drawables
textXOffSet = textXOffSet.div(2)
return width
}
private fun adjustJutParams(jut: Jut) {
var radius = 0f
var lightOffset = 0f
var shadowOffset = 0f
when (jut) {
Jut.SMALL -> {
radius = 25f
lightOffset = 7f
shadowOffset = 8f
}
Jut.NORMAL -> {
radius = 25f
lightOffset = 9f
shadowOffset = 10f
}
Jut.LARGE -> {
radius = 25f
lightOffset = 10f
shadowOffset = 11f
}
}
lightPaint.apply {
color = mBackgroundColor
setShadowLayer(radius, -lightOffset, -lightOffset, ColorUtils.blendARGB(mBackgroundColor, Color.WHITE, lightDensity))
}
shadowPaint.apply {
color = mBackgroundColor
setShadowLayer(radius, shadowOffset, shadowOffset, ColorUtils.blendARGB(mBackgroundColor, Color.BLACK, shadowDensity))
}
}
}
| 0
|
Kotlin
|
0
| 5
|
0e12f8305f1a5b8c70e7c9dbfa7336d27a0cc738
| 15,689
|
NeumorphicViewSet
|
MIT License
|
MyLib_Kotlin/src/test/kotlin/lib/datastructure/graph/undirectedgraph/UndirectedGraphEdgeTest.kt
|
CWKSC
| 420,659,931
| false
|
{"Kotlin": 32463}
|
package lib.datastructure.graph.undirectedgraph
import org.junit.jupiter.api.Assertions.*
import org.junit.jupiter.api.Nested
import org.junit.jupiter.api.Test
internal class UndirectedGraphEdgeTest {
@Nested
inner class EqualTest {
@Test
fun `Exchange node, should return true`() {
val edge1 = UndirectedGraphEdge(1, 2, 42)
val edge2 = UndirectedGraphEdge(2, 1, 42)
assertTrue(edge1 == edge2)
}
@Test
fun `Same node in set`() {
val edge1 = UndirectedGraphEdge(1, 2, 42)
val edge2 = UndirectedGraphEdge(2, 1, 42)
val set = setOf(edge1, edge2)
assertEquals(1, set.size)
}
}
}
| 0
|
Kotlin
|
0
| 1
|
54e046367103f6b26381bb22f997412d0bc3b43f
| 725
|
my-lib-kotlin-deprecated
|
MIT License
|
app/src/main/java/com/mrmannwood/hexlauncher/LauncherApplication.kt
|
MrMannWood
| 298,718,785
| false
| null |
package com.mrmannwood.hexlauncher
import android.app.Activity
import android.app.Application
import android.content.Intent
import android.content.IntentFilter
import android.os.Build
import android.os.StrictMode
import androidx.appcompat.app.AppCompatDelegate
import androidx.core.content.FileProvider
import com.mrmannwood.hexlauncher.applist.AppListUpdater
import com.mrmannwood.hexlauncher.applist.writeAppsToFile
import com.mrmannwood.hexlauncher.executors.diskExecutor
import com.mrmannwood.hexlauncher.foregrounddetection.ForegroundActivityListener
import com.mrmannwood.hexlauncher.launcher.PackageObserverBroadcastReceiver
import com.mrmannwood.hexlauncher.settings.PreferenceExtractor
import com.mrmannwood.hexlauncher.settings.PreferenceKeys
import com.mrmannwood.hexlauncher.settings.PreferencesRepository
import com.mrmannwood.hexlauncher.timber.FileLoggerTree
import com.mrmannwood.launcher.BuildConfig
import com.mrmannwood.launcher.R
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.SupervisorJob
import kotlinx.coroutines.launch
import timber.log.Timber
import java.io.File
import java.util.concurrent.CountDownLatch
class LauncherApplication : Application() {
companion object {
val applicationScope = CoroutineScope(SupervisorJob() + Dispatchers.Main)
}
override fun onCreate() {
super.onCreate()
Timber.plant(FileLoggerTree.getAndInit(this@LauncherApplication))
if (BuildConfig.DEBUG) {
DebugBuildModeConfiguration.onApplicationCreate(this@LauncherApplication)
} else {
ReleaseBuildModeConfiguration.onApplicationCreate(this@LauncherApplication)
}
installUncaughtExceptionHandler()
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.Q) {
AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_YES)
}
PreferencesRepository.watchPref(
context = this@LauncherApplication,
key = PreferenceKeys.Logging.ENABLE_DISK_LOGGING,
extractor = PreferenceExtractor.BooleanExtractor
).observeForever { enable ->
if (enable == true) {
FileLoggerTree.get().enableDiskFlush()
} else {
FileLoggerTree.get().disableDiskFlush()
}
}
DB.get(this@LauncherApplication)
AppListUpdater.updateAppList(applicationContext)
registerReceiver(
PackageObserverBroadcastReceiver(),
IntentFilter().apply {
addDataScheme("package")
addAction(Intent.ACTION_PACKAGE_ADDED)
addAction(Intent.ACTION_PACKAGE_REMOVED)
}
)
ForegroundActivityListener.init(this)
CoroutineScope(Dispatchers.IO).launch {
File(filesDir, "rage_shake").deleteRecursively()
}
}
private fun installUncaughtExceptionHandler() {
val exceptionHandler = Thread.getDefaultUncaughtExceptionHandler()
Thread.setDefaultUncaughtExceptionHandler { thread, throwable ->
try {
Timber.e(throwable, "An uncaught exception occurred on thread ${thread.name}")
} catch (ignored: Throwable) { }
exceptionHandler?.uncaughtException(thread, throwable)
}
}
fun rageShakeThing(activity: Activity) {
diskExecutor.execute {
val rageShakeDir = File(filesDir, "rage_shake")
writeAppsToFile(activity, rageShakeDir)
val latch = CountDownLatch(1)
FileLoggerTree.get().copyLogsTo(File(filesDir, "rage_shake")) { latch.countDown() }
runCatching { latch.await() }
val uris = ArrayList(
rageShakeDir.listFiles()?.map {
FileProvider.getUriForFile(
activity, "com.mrmannwood.hexlauncher.fileprovider", it)
} ?: emptyList()
)
val debugInfo ="""
OS Version: ${System.getProperty("os.version")} (${Build.VERSION.INCREMENTAL})
OS API Level: ${Build.VERSION.SDK_INT}
Device: ${Build.DEVICE}
Model and Product: ${Build.MODEL} ${Build.PRODUCT}
App Version: ${getString(R.string.app_version)}
""".trimIndent()
activity.startActivity(
Intent(Intent.ACTION_SEND_MULTIPLE).apply {
type = "text/plain"
putExtra(Intent.EXTRA_EMAIL, arrayOf(getString(R.string.dev_email)))
putExtra(Intent.EXTRA_SUBJECT, "Rage Shake Report")
putExtra(Intent.EXTRA_STREAM, uris)
putExtra(Intent.EXTRA_TEXT, getString(R.string.rage_shake_email_body, debugInfo))
addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION)
}
)
}
}
private interface BuildModeConfiguration {
fun onApplicationCreate(application: Application)
}
private object DebugBuildModeConfiguration : BuildModeConfiguration {
override fun onApplicationCreate(application: Application) {
Timber.plant(Timber.DebugTree())
StrictMode.setThreadPolicy(StrictMode.ThreadPolicy.Builder().detectAll().build())
StrictMode.setVmPolicy(StrictMode.VmPolicy.Builder().detectAll().build())
}
}
private object ReleaseBuildModeConfiguration : BuildModeConfiguration {
override fun onApplicationCreate(application: Application) {
}
}
}
| 3
|
Kotlin
|
2
| 7
|
de338a5589a624fd25347dd6720a365fed2b4f33
| 5,622
|
launcher
|
Apache License 2.0
|
circle-selector/src/main/java/net.kibotu.circleselector/CircleSelector.kt
|
kibotu
| 84,978,123
| false
| null |
package net.kibotu.circleselector
import android.annotation.SuppressLint
import android.app.Activity
import android.content.Context
import android.content.res.Resources
import android.graphics.Point
import android.os.Build
import android.util.AttributeSet
import android.util.DisplayMetrics
import android.util.Log
import android.view.MotionEvent
import android.view.ViewConfiguration
import android.widget.FrameLayout
import java.lang.ref.WeakReference
/**
* http://neevek.net/posts/2013/10/13/implementing-onInterceptTouchEvent-and-onTouchEvent-for-ViewGroup.html
*
*
* Purpose of this view is to being able to communicate
* <pre>
* 0) consume all events of children and parents
* 1) click
* 2) long press
* 3) dragging
* 4) angle between pivot and latest touch event point
</pre> *
*/
open class CircleSelector @JvmOverloads constructor(
context: Context,
attrs: AttributeSet? = null,
defStyleAttr: Int = 0
) : FrameLayout(context, attrs, defStyleAttr) {
var enableLogging = false
private var previous = Vector2()
private var start = Vector2()
/**
* Defines the time in millis when the long press event gets fired.
*/
private var longPressTimeout: Int = 0
/**
* Distance after which it counts as move gesture.
*/
private var minDistanceMovingGesture: Int = 0
/**
* Defines if view is currently in a long press gesture.
*/
// endregion
// region long press
private var isLongPressing: Boolean = false
/**
* Defines if view is currently in active a moving gesture.
*/
private var isBeingDragged: Boolean = false
/**
* Holds current angle between pivot and current touch point.
*/
/**
* Retrieves current angle between pivot of view and latest touch gesture point.
*
* @return Euler angle with offset [DEGREE_OFFSET]
*/
var angle: Double = 0.toDouble()
private set(angle) {
onAngleUpdate(angle)
field = angle
}
/**
* Used for clamped Y value.
*/
private var currentClamped = Vector2()
/**
* Holds current touch coordinate.
*/
var current = Vector2()
/**
* Defines center of the screen.
*/
private lateinit var screenCenter: Vector2
/**
* Defines pivot of view.
*/
lateinit var center: Vector2
/**
* Defines pivot offset.
*/
private var offset: Vector2 = Vector2()
/**
* <img src="http://i.imgur.com/Cwtr7ku.png"></img>
*
*
* Returns angle calculated by the dragging movement based from the screenCenter of the screen.
*
* @return Angle in degree.
*/
var angleUpdateListener: ((Double, CircleSelector) -> Unit)? = null
/**
* Callback for moving gesture changes.
*/
var onDragUpdateListener: ((Boolean, CircleSelector) -> Unit)? = null
/**
* Callback for long press changes. [longPressTimeout]
*/
var onLongPressedListener: ((Boolean, CircleSelector) -> Unit)? = null
/**
* Callback for click event.
*/
var onTapListener: ((Int, CircleSelector) -> Unit)? = null
/**
* used as buffer to retrieve view location on screen
*/
private var location = IntArray(2)
private val isMoveGesture: Boolean
get() = isMoveGesture(start, current, minDistanceMovingGesture.toFloat())
init {
if (!isInEditMode) {
val screenDimensions = getScreenDimensions(CircleSelector.activity)
screenCenter = Vector2(screenDimensions.width / 2f, screenDimensions.height / 2f)
}
longPressTimeout = ViewConfiguration.getLongPressTimeout()
minDistanceMovingGesture = dpToPx(20)
}
/**
* {@inheritDoc}
*
*
* <pre>
* In a nutshell: it can consume touch events before its children.
*
* 0) consume all events of children and parents
</pre> *
*/
override fun onInterceptTouchEvent(event: MotionEvent): Boolean {
if (isInEditMode)
return false
when (event.action) {
MotionEvent.ACTION_DOWN -> {
log("[onInterceptTouchEvent] ACTION_DOWN " + event)
previous.set(event.rawX, event.rawY)
start.set(event.rawX, event.rawY)
}
MotionEvent.ACTION_CANCEL, MotionEvent.ACTION_UP -> {
log("[onInterceptTouchEvent] ACTION_UP || ACTION_CANCEL downTime=" + (event.eventTime - event.downTime) + " " + event)
seDragging(false)
}
MotionEvent.ACTION_MOVE -> seDragging(true)
else -> log("[onInterceptTouchEvent] Unhandled " + event)
}
return true
}
/**
* {@inheritDoc}
*
*
* We communicate the following events to callbacks:
* <pre>
* 0) consume all events of children and parents
* 1) click
* 2) long press
* 3) dragging
* 4) angle between pivot and latest touch event point
</pre> *
*/
@SuppressLint("ClickableViewAccessibility")
override fun onTouchEvent(event: MotionEvent): Boolean {
if (isInEditMode)
return false
// touch event duration
val downTime = event.eventTime - event.downTime
when (event.action) {
MotionEvent.ACTION_CANCEL, MotionEvent.ACTION_UP -> {
log("[onTouchEvent] ACTION_UP || ACTION_CANCEL downTime=$downTime $event")
seDragging(false)
// downtime below long press duration then fire click, otherwise send cancel long press event
if (downTime < longPressTimeout) {
if (!isMoveGesture)
onClick(downTime.toInt())
} else
onLongPress(false)
}
MotionEvent.ACTION_MOVE -> {
log("[onTouchEvent] ACTION_MOVE downTime=$downTime $event")
getLocationInWindow(location)
current.set(event.rawX, event.rawY)
currentClamped.set(event.rawX, location[1].toFloat())
center = Vector2(location[0].toFloat() + width / 2f + offset.x, location[1].toFloat() + height / 2f + offset.y)
angle = Vector2(currentClamped).sub(center).nor().angle() + DEGREE_OFFSET
if (downTime >= longPressTimeout) {
log("[ACTION_MOVE] downTime=" + downTime)
onLongPress(true)
}
val consume = !isMoveGesture || isLongPressing
log("[isMoveGesture] start=" + start + " current=" + current + " distance=" + start.dst(current) + " minDistanceMovingGesture=" + minDistanceMovingGesture + " isMoveGesture=" + isMoveGesture + " isLongPressing=" + isLongPressing + " consume=" + consume)
// consume touch event inside scroll container like view pagers
parent.requestDisallowInterceptTouchEvent(consume)
seDragging(true)
}
else -> log("[onTouchEvent] Unhandled " + event)
}
return true
}
// region click
private fun onClick(duration: Int) {
log("[onClick] duration=$duration")
onTapListener?.invoke(duration, this)
}
private fun onLongPress(isLongPressing: Boolean) {
if (this.isLongPressing != isLongPressing)
onLongPressedListener?.invoke(isLongPressing, this)
this.isLongPressing = isLongPressing
}
fun setLongPressTimeout(longPressTimeout: Int) {
this.longPressTimeout = Math.abs(longPressTimeout)
}
// endregion
// region angle
private fun onAngleUpdate(angle: Double) {
if (java.lang.Double.compare(this.angle, angle) != 0)
angleUpdateListener?.invoke(angle, this)
}
/**
* Changes Pivot for computing angle.
*/
fun setPivotOffset(offsetX: Int, offsetY: Int) {
offset.set(offsetX.toFloat(), offsetY.toFloat())
postInvalidate()
}
// endregion
// region dragging
/**
* Fires moving gesture event.
*
* @param isBeingDragged `true` if being dragged.
*/
private fun seDragging(isBeingDragged: Boolean) {
onDragUpdate(isBeingDragged)
this.isBeingDragged = isBeingDragged
}
private fun onDragUpdate(isBeingDragged: Boolean) {
if (this.isBeingDragged != isBeingDragged)
onDragUpdateListener?.invoke(isLongPressing, this)
}
// endregion
private fun tag(): String {
return javaClass.simpleName
}
private fun log(message: String?) {
if (enableLogging)
Log.v(tag(), message)
}
companion object {
private var _activity: WeakReference<Activity?>? = null
@JvmStatic
var activity: Activity?
set(value) {
_activity = WeakReference(value)
}
get() = _activity?.get()
/**
* <img src="http://i.imgur.com/Cwtr7ku.png"></img>
*
*
* We need a 90 degree offset towards [Math.atan2].
*/
const val DEGREE_OFFSET = 90.0
fun dpToPx(dp: Int): Int {
val scale = density
return (dp * scale + 0.5f).toInt()
}
private val density: Float
get() = Resources.getSystem().displayMetrics.density
private fun getDefaultDisplay(activity: Activity?): android.view.Display {
return activity!!.windowManager.defaultDisplay
}
fun getScreenDimensions(activity: Activity?): Dimension {
val dm = DisplayMetrics()
val display = getDefaultDisplay(activity)
display.getMetrics(dm)
var screenWidth = dm.widthPixels
var screenHeight = dm.heightPixels
if (Build.VERSION.SDK_INT < 17) {
try {
screenWidth = android.view.Display::class.java.getMethod("getRawWidth").invoke(display) as Int
screenHeight = android.view.Display::class.java.getMethod("getRawHeight").invoke(display) as Int
} catch (ignored: Exception) {
}
}
if (Build.VERSION.SDK_INT >= 17) {
try {
val realSize = Point()
android.view.Display::class.java.getMethod("getRealSize", Point::class.java).invoke(display, realSize)
screenWidth = realSize.x
screenHeight = realSize.y
} catch (ignored: Exception) {
}
}
return Dimension(screenWidth, screenHeight)
}
private fun isMoveGesture(start: Vector2?, end: Vector2?, distance: Float): Boolean {
return start != null && end != null && start.dst(end) >= distance
}
fun nearestNumber(number: Float, vararg numbers: Float): Float {
var distance = Math.abs(numbers[0] - number)
var index = 0
for (c in 1 until numbers.size) {
val cDistance = Math.abs(numbers[c] - number)
if (cDistance < distance) {
index = c
distance = cDistance
}
}
return numbers[index]
}
}
}
| 0
|
Kotlin
|
0
| 0
|
d8b7e34609e628ba0eaf873e47d376d515db7c49
| 11,400
|
CircleSelector
|
Apache License 2.0
|
app/src/main/java/com/ciscowebex/androidsdk/kitchensink/messaging/teams/detail/TeamDetailActivity.kt
|
webex
| 137,331,913
| false
|
{"Kotlin": 921538}
|
package com.ciscowebex.androidsdk.kitchensink.messaging.teams.detail
import android.content.Context
import android.content.Intent
import android.os.Bundle
import android.view.View
import androidx.databinding.DataBindingUtil
import androidx.lifecycle.Observer
import com.ciscowebex.androidsdk.kitchensink.BaseActivity
import com.ciscowebex.androidsdk.kitchensink.R
import com.ciscowebex.androidsdk.kitchensink.databinding.ActivityTeamDetailBinding
import com.ciscowebex.androidsdk.kitchensink.utils.Constants
import org.koin.android.ext.android.inject
class TeamDetailActivity : BaseActivity() {
lateinit var binding: ActivityTeamDetailBinding
private val teamDetailViewModel : TeamDetailViewModel by inject()
private lateinit var teamId: String
companion object {
fun getIntent(context: Context, teamId: String): Intent {
val intent = Intent(context, TeamDetailActivity::class.java)
intent.putExtra(Constants.Intent.TEAM_ID, teamId)
return intent
}
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
teamId = intent.getStringExtra(Constants.Intent.TEAM_ID) ?: ""
DataBindingUtil.setContentView<ActivityTeamDetailBinding>(this, R.layout.activity_team_detail)
.also { binding = it }
.apply {
binding.progressLayout.visibility = View.VISIBLE
teamDetailViewModel.team.observe(this@TeamDetailActivity, Observer { model ->
model?.let {
progressLayout.visibility = View.GONE
binding.team = it
}
})
}
}
override fun onResume() {
super.onResume()
teamDetailViewModel.getTeamById(teamId)
}
}
| 8
|
Kotlin
|
19
| 14
|
bd8568ce01829f71754102339f11533e15356f08
| 1,869
|
webex-android-sdk-example
|
MIT License
|
app/src/main/java/com/develrm/f1standings/ui/MainActivity.kt
|
emanuellucas2
| 791,554,119
| false
|
{"Kotlin": 18884}
|
package com.develrm.f1standings.ui
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import androidx.fragment.app.commit
import com.develrm.f1standings.R
import com.develrm.f1standings.databinding.ActivityMainBinding
class MainActivity : AppCompatActivity() {
private lateinit var binding: ActivityMainBinding
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = ActivityMainBinding.inflate(layoutInflater)
setContentView(binding.root)
initView(binding)
}
private fun initView(binding: ActivityMainBinding) {
binding.tabLayout.getTabAt(0)?.view?.setOnClickListener{
supportFragmentManager.commit {
replace(binding.fragmentContainerView.id, DriverFragment())
}
}
binding.tabLayout.getTabAt(1)?.view?.setOnClickListener{
supportFragmentManager.commit {
replace(binding.fragmentContainerView.id, ConstructorFragment())
}
}
supportFragmentManager.commit {
replace(binding.fragmentContainerView.id, DriverFragment())
}
}
}
| 0
|
Kotlin
|
0
| 0
|
999908cf6e0d3cf6f480f9cf1b6e6d9e7772dd03
| 1,183
|
F1Standings
|
MIT License
|
src/main/kotlin/org/rapturemain/currencyconverter/controller/CurrenciesController.kt
|
rapturemain
| 433,157,411
| false
|
{"Kotlin": 29783, "Dockerfile": 275}
|
package org.rapturemain.currencyconverter.controller
import org.rapturemain.currencyconverter.exception.CurrencyAlreadyExistsException
import org.rapturemain.currencyconverter.exception.CurrencyCodeIsInvalidException
import org.rapturemain.currencyconverter.exception.NoCurrencyExistsException
import org.rapturemain.currencyconverter.exceptionhandler.ParameterInvalidException
import org.rapturemain.currencyconverter.exceptionhandler.UnknownException
import org.rapturemain.currencyconverter.model.RecordsWrapper
import org.rapturemain.currencyconverter.service.CurrencyExchangeRateProviderService
import org.rapturemain.currencyconverter.service.CurrencyProviderService
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.http.HttpStatus
import org.springframework.http.ResponseEntity
import org.springframework.web.bind.annotation.*
@RestController
@RequestMapping("/restapi/v1/currencies/")
class CurrenciesController
@Autowired constructor(val currencyProvider: CurrencyProviderService,
val exchangeRateProvider: CurrencyExchangeRateProviderService){
@PutMapping
fun addCurrency(@RequestParam code: String): ResponseEntity<Any> {
try {
currencyProvider.addCurrency(code)
return ResponseEntity<Any>(HttpStatus.NO_CONTENT)
} catch (ex: Exception) {
when (ex) {
is CurrencyAlreadyExistsException -> throw ParameterInvalidException("code", ex.message)
is CurrencyCodeIsInvalidException -> throw ParameterInvalidException("code", ex.message)
else -> throw UnknownException(ex)
}
}
}
@GetMapping
fun getCurrencies(): ResponseEntity<RecordsWrapper<String>> {
return ResponseEntity(RecordsWrapper(currencyProvider.getCurrencies()), HttpStatus.OK)
}
@DeleteMapping
fun deleteCurrency(@RequestParam code: String): ResponseEntity<Any> {
try {
if (!currencyProvider.isValidCode(code)) {
throw CurrencyCodeIsInvalidException(code)
}
exchangeRateProvider.deleteRatesOf(code)
currencyProvider.deleteCurrency(code)
return ResponseEntity(HttpStatus.NO_CONTENT)
} catch (ex: Exception) {
when (ex) {
is NoCurrencyExistsException -> throw ParameterInvalidException("code", ex.message)
is CurrencyCodeIsInvalidException -> throw ParameterInvalidException("code", ex.message)
else -> throw UnknownException(ex)
}
}
}
}
| 0
|
Kotlin
|
0
| 0
|
0de1f482917e12bfa1e65cd00caae27c689d4474
| 2,604
|
currency-converter
|
Apache License 2.0
|
src/main/kotlin/com/github/kory33/kalgebra/structures/instances/ring/IntRing.kt
|
kory33
| 135,460,140
| false
| null |
package com.github.kory33.kalgebra.structures.instances.ring
import com.github.kory33.kalgebra.structures.Ring
import com.github.kory33.kalgebra.structures.instances.group.IntAdditiveGroup
import com.github.kory33.kalgebra.structures.instances.monoid.IntMultiplicativeMonoid
class IntRing(value: Int): Ring<Int, IntRing>(value) {
override val plusOperation = IntAdditiveGroup
override val multOperation = IntMultiplicativeMonoid
override fun lift(value: Int): IntRing = IntRing(value)
}
| 0
|
Kotlin
|
0
| 2
|
ae2420a27ef848c13fd5728d6c5cfeae3901f905
| 505
|
Kalgebra
|
MIT License
|
plugins/amazonq/codewhisperer/jetbrains-community/src/software/aws/toolkits/jetbrains/services/codewhisperer/popup/handlers/CodeWhispererPopupTypedHandler.kt
|
aws
| 91,485,909
| false
|
{"Kotlin": 7507266, "TypeScript": 132101, "C#": 97693, "Vue": 47529, "Java": 19596, "JavaScript": 12450, "HTML": 5878, "Python": 2939, "Shell": 2920, "Dockerfile": 2209, "SCSS": 2045, "CSS": 1827, "PowerShell": 386, "Batchfile": 77}
|
// Copyright 2022 Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
package software.aws.toolkits.jetbrains.services.codewhisperer.popup.handlers
import com.intellij.openapi.actionSystem.DataContext
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.editor.actionSystem.TypedActionHandler
import software.aws.toolkits.jetbrains.services.codewhisperer.model.InvocationContext
import software.aws.toolkits.jetbrains.services.codewhisperer.model.SessionContextNew
import software.aws.toolkits.jetbrains.services.codewhisperer.popup.CodeWhispererPopupManager
import software.aws.toolkits.jetbrains.services.codewhisperer.popup.CodeWhispererPopupManagerNew
class CodeWhispererPopupTypedHandler(
private val defaultHandler: TypedActionHandler,
val states: InvocationContext,
) : TypedActionHandler {
override fun execute(editor: Editor, charTyped: Char, dataContext: DataContext) {
CodeWhispererPopupManager.getInstance().dontClosePopupAndRun {
defaultHandler.execute(editor, charTyped, dataContext)
ApplicationManager.getApplication().messageBus.syncPublisher(
CodeWhispererPopupManager.CODEWHISPERER_USER_ACTION_PERFORMED
).type(states, charTyped.toString())
}
}
}
class CodeWhispererPopupTypedHandlerNew(
private val defaultHandler: TypedActionHandler,
val sessionContext: SessionContextNew,
) : TypedActionHandler {
override fun execute(editor: Editor, charTyped: Char, dataContext: DataContext) {
CodeWhispererPopupManagerNew.getInstance().dontClosePopupAndRun {
defaultHandler.execute(editor, charTyped, dataContext)
ApplicationManager.getApplication().messageBus.syncPublisher(
CodeWhispererPopupManager.CODEWHISPERER_USER_ACTION_PERFORMED
).type(sessionContext, charTyped.toString())
}
}
}
| 519
|
Kotlin
|
220
| 757
|
a81caf64a293b59056cef3f8a6f1c977be46937e
| 1,988
|
aws-toolkit-jetbrains
|
Apache License 2.0
|
examples/src/tl/telegram/ShippingOption.kt
|
andreypfau
| 719,064,910
| false
|
{"Kotlin": 62259}
|
// This file is generated by TLGenerator.kt
// Do not edit manually!
package tl.telegram
import io.github.andreypfau.tl.serialization.TLCombinatorId
import kotlin.jvm.JvmName
import kotlinx.serialization.SerialName
import kotlinx.serialization.Serializable
@Serializable
@SerialName("shippingOption")
@TLCombinatorId(0xB6213CDF)
public data class ShippingOption(
@get:JvmName("id")
public val id: String,
@get:JvmName("title")
public val title: String,
@get:JvmName("prices")
public val prices: List<LabeledPrice>,
) {
public companion object
}
| 0
|
Kotlin
|
0
| 1
|
11f05ad1f977235e3e360cd6f6ada6f26993208e
| 575
|
tl-kotlin
|
MIT License
|
core/src/main/java/com/fightpandemics/core/dagger/CoreComponent.kt
|
FightPandemics
| 261,618,622
| false
| null |
package com.fightpandemics.core.dagger
import com.fightpandemics.core.dagger.module.ContextModule
import com.fightpandemics.core.dagger.module.DataModule
import com.fightpandemics.core.dagger.module.DatabaseModule
import com.fightpandemics.core.dagger.module.NetworkModule
import com.fightpandemics.core.dagger.module.RemoteModule
import com.fightpandemics.core.dagger.module.SharedPreferencesModule
import com.fightpandemics.core.dagger.module.ViewModelBuilderModule
import com.fightpandemics.core.data.api.FightPandemicsAPI
import com.fightpandemics.core.data.prefs.PreferenceStorage
import com.fightpandemics.core.domain.repository.LocationRepository
import com.fightpandemics.core.domain.repository.LoginRepository
import com.fightpandemics.core.domain.repository.PostsRepository
import com.fightpandemics.core.domain.repository.ProfileRepository
import dagger.Component
import javax.inject.Singleton
/*
*
* created by <NAME>
*
* @Singleton ensures the same copy of all the dependencies is injected to anything that needs it.
* @Component makes Dagger create a graph of dependencies.
* The "modules" attribute tells Dagger what Modules to include when building the graph
* */
@Singleton
@Component(
modules = [
ContextModule::class,
DataModule::class,
DatabaseModule::class,
NetworkModule::class,
RemoteModule::class,
SharedPreferencesModule::class,
ViewModelBuilderModule::class
]
)
interface CoreComponent {
// Factory that is used to create instances of this subcomponent
@Component.Factory
interface Factory {
fun create(
contextModule: ContextModule,
sharedPreferencesModule: SharedPreferencesModule,
): CoreComponent
}
// The return type of functions inside the component interface is what can be provided from the container
// fun provideContext(): Context
fun providesPreferenceStorage(): PreferenceStorage
fun providePostsRepository(): PostsRepository
fun provideLoginRepository(): LoginRepository
fun provideLocationRepository(): LocationRepository
fun provideFightPandemicsAPI(): FightPandemicsAPI
fun providesProfileRepository(): ProfileRepository
}
| 45
|
Kotlin
|
12
| 14
|
c054328e374cc6ffa38881165769bf0d84b417c4
| 2,223
|
FightPandemics-android
|
MIT License
|
app-tracking-protection/app-tracking-api/src/main/java/com/duckduckgo/mobile/android/app/tracking/AppTrackerDetector.kt
|
hojat72elect
| 822,396,044
| false
|
{"Kotlin": 11626231, "HTML": 65873, "Ruby": 16984, "C++": 10312, "JavaScript": 5520, "CMake": 1992, "C": 1076, "Shell": 784}
|
package com.duckduckgo.mobile.android.app.tracking
import androidx.annotation.WorkerThread
interface AppTrackerDetector {
/**
* Evaluates whether the specified domain requested by the specified uid is a tracker.
* This method should be called off the UI thread.
*
* @param domain the domain to evaluate
* @param uid the uid of the app requesting the domain
*
* @return [AppTracker] if the request is a tracker, null otherwise
*/
@WorkerThread
fun evaluate(domain: String, uid: Int): AppTracker?
data class AppTracker(
val domain: String,
val uid: Int,
val trackerCompanyDisplayName: String,
val trackingAppId: String,
val trackingAppName: String,
)
}
| 0
|
Kotlin
|
0
| 0
|
b89591136b60933d6a03fac43a38ee183116b7f8
| 756
|
DuckDuckGo
|
Apache License 2.0
|
app/src/androidTest/java/org/rfcx/incidents/ResponseDbTest.kt
|
rfcx
| 104,899,135
| false
|
{"Kotlin": 1176262, "Java": 1049}
|
package org.rfcx.incidents
import androidx.arch.core.executor.testing.InstantTaskExecutorRule
import io.realm.Realm
import io.realm.RealmConfiguration
import org.junit.Assert
import org.junit.Before
import org.junit.Rule
import org.junit.Test
import org.rfcx.incidents.data.local.ResponseDb
import org.rfcx.incidents.entity.response.Response
import org.rfcx.incidents.entity.response.SyncState
class ResponseDbTest {
private lateinit var responseDb: ResponseDb
@get:Rule
val rule = InstantTaskExecutorRule()
@Before
fun setup() {
val realm = realm()
responseDb = ResponseDb(realm)
}
@Test
fun canSaveReport() {
// Arrange
val expectedId = 1
val expectedValue = "xyz"
// Act
responseDb.save(response(1, "random-string", expectedValue, SyncState.UNSENT))
// Assert
val actual = responseDb.getResponseById(expectedId)
Assert.assertEquals(expectedValue, actual?.streamId)
}
@Test
fun canCountUnsent() {
// Arrange
val expectedUnsent = 2L
responseDb.save(response(1, "random-string-1", "xxx", SyncState.UNSENT))
responseDb.save(response(2, "random-string-2", "xxx", SyncState.SENT))
responseDb.save(response(3, "random-string-3", "yyy", SyncState.UNSENT))
// Act
val actualUnsent = responseDb.unsentCount()
// Assert
Assert.assertEquals(expectedUnsent, actualUnsent)
}
@Test
fun canMarkSentReport() {
// Arrange
val response = response(4, "random-string-4", "yyy", SyncState.UNSENT)
responseDb.save(response)
// Act
responseDb.markSent(response.id, "abbc", "123")
// Assert
val actual = responseDb.getResponseById(response.id)
Assert.assertEquals(SyncState.SENT.value, actual?.syncState)
}
private fun realm(): Realm {
val config = RealmConfiguration.Builder()
.name("myrealm.realm")
.inMemory()
.build()
return Realm.getInstance(config)
}
private fun response(id: Int, guid: String, streamId: String, syncState: SyncState): Response {
return Response(
id = id,
guid = guid,
streamId = streamId,
syncState = syncState.value
)
}
}
| 30
|
Kotlin
|
0
| 0
|
cbcb9402733a959104aff97f26d04244b73bc109
| 2,348
|
guardian-app-android
|
Apache License 2.0
|
app/src/main/java/com/tomaszrykala/midionandroid/midi/MidiController.kt
|
tomaszrykala
| 127,637,090
| false
| null |
package com.tomaszrykala.midionandroid.midi
import android.app.Application
import android.arch.lifecycle.AndroidViewModel
import android.arch.lifecycle.LifecycleOwner
import android.arch.lifecycle.Observer
import android.content.Context
import android.media.midi.MidiDevice
import android.media.midi.MidiDeviceInfo
import android.media.midi.MidiInputPort
import android.media.midi.MidiManager
import android.os.Handler
import android.util.Log
class MidiController(
context: Context,
private val midiManager: MidiManager = context.getSystemService(Context.MIDI_SERVICE) as MidiManager,
private val midiDeviceMonitor: MidiDeviceMonitor = MidiDeviceMonitor(context, midiManager)
) : AndroidViewModel(context.applicationContext as Application) {
companion object {
const val TAG: String = "MidiController"
}
private var midiInputPort: MidiInputPort? = null
private var midiDevice: MidiDevice? = null
fun open(midiDeviceInfo: MidiDeviceInfo) =
close().also {
midiDeviceInfo
.ports.first { it.type == MidiDeviceInfo.PortInfo.TYPE_INPUT }
.portNumber.also { portNumber ->
midiManager.openDevice(midiDeviceInfo, {
midiDevice = it
midiInputPort = it.openInputPort(portNumber)
}, Handler())
}
}
fun send(event: MidiEvent) {
Log.d(TAG, event.toString())
byteArrayOf((event.type.byte + event.channel).toByte(), event.note, event.pressure, event.channel)
.apply { midiInputPort?.send(this, 0, size) }
}
fun observeDevices(lifecycleOwner: LifecycleOwner, observer: Observer<List<MidiDeviceInfo>>) =
midiDeviceMonitor.observe(lifecycleOwner, observer)
fun removeObserver(observer: Observer<List<MidiDeviceInfo>>) =
midiDeviceMonitor.removeObserver(observer).also { close() }
fun close() {
midiInputPort?.close()
midiInputPort = null
midiDevice?.close()
midiDevice = null
}
}
| 1
|
Kotlin
|
0
| 1
|
cd6bd3dcf17ffe3f307d821558df6edbf3755b14
| 2,125
|
MidiOnAndroid
|
Apache License 2.0
|
backend/src/test/kotlin/fr/gouv/cacem/monitorenv/infrastructure/api/endpoints/bff/SemaphoresITests.kt
|
MTES-MCT
| 462,794,012
| false
|
{"TypeScript": 1358478, "Kotlin": 815514, "Python": 209694, "Shell": 21375, "CSS": 19997, "JavaScript": 8409, "Makefile": 8169, "Dockerfile": 6554, "PLpgSQL": 4966, "HTML": 864}
|
package fr.gouv.cacem.monitorenv.infrastructure.api.endpoints.bff
import fr.gouv.cacem.monitorenv.config.MapperConfiguration
import fr.gouv.cacem.monitorenv.config.WebSecurityConfig
import fr.gouv.cacem.monitorenv.domain.entities.semaphore.SemaphoreEntity
import fr.gouv.cacem.monitorenv.domain.use_cases.semaphores.GetAllSemaphores
import fr.gouv.cacem.monitorenv.domain.use_cases.semaphores.GetSemaphoreById
import fr.gouv.cacem.monitorenv.infrastructure.api.endpoints.bff.v1.Semaphores
import org.hamcrest.Matchers.equalTo
import org.junit.jupiter.api.Test
import org.locationtech.jts.geom.Point
import org.locationtech.jts.io.WKTReader
import org.mockito.BDDMockito.given
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest
import org.springframework.boot.test.mock.mockito.MockBean
import org.springframework.context.annotation.Import
import org.springframework.test.web.servlet.MockMvc
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get
import org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath
import org.springframework.test.web.servlet.result.MockMvcResultMatchers.status
@Import(WebSecurityConfig::class, MapperConfiguration::class)
@WebMvcTest(value = [(Semaphores::class)])
class SemaphoresITests {
@Autowired
private lateinit var mockMvc: MockMvc
@MockBean
private lateinit var getAllSemaphores: GetAllSemaphores
@MockBean
private lateinit var getSemaphoreById: GetSemaphoreById
@Test
fun `Should get all semaphores`() {
// Given
val wktReader = WKTReader()
val pointString = "POINT (-4.54877816747593 48.305559876971)"
val point = wktReader.read(pointString) as Point
val semaphore = SemaphoreEntity(
id = 1,
name = "Semaphore 1",
geom = point,
)
given(getAllSemaphores.execute()).willReturn(listOf(semaphore))
// When
mockMvc.perform(get("/bff/v1/semaphores"))
// Then
.andExpect(status().isOk)
.andExpect(jsonPath("$[0].id", equalTo(semaphore.id)))
.andExpect(jsonPath("$[0].name", equalTo(semaphore.name)))
.andExpect(jsonPath("$[0].geom.type", equalTo("Point")))
.andExpect(jsonPath("$[0].geom.coordinates.[0]", equalTo(-4.54877817)))
.andExpect(jsonPath("$[0].geom.coordinates.[1]", equalTo(48.30555988)))
}
@Test
fun `Should get specific semaphore`() {
// Given
val wktReader = WKTReader()
val pointString = "POINT (-4.54877816747593 48.305559876971)"
val point = wktReader.read(pointString) as Point
val semaphore = SemaphoreEntity(
id = 21,
name = "Semaphore 1",
geom = point,
)
given(getSemaphoreById.execute(21)).willReturn(semaphore)
// When
mockMvc.perform(get("/bff/v1/semaphores/21"))
// Then
.andExpect(status().isOk)
.andExpect(jsonPath("$.id", equalTo(semaphore.id)))
.andExpect(jsonPath("$.name", equalTo(semaphore.name)))
.andExpect(jsonPath("$.geom.type", equalTo("Point")))
.andExpect(jsonPath("$.geom.coordinates.[0]", equalTo(-4.54877817)))
.andExpect(jsonPath("$.geom.coordinates.[1]", equalTo(48.30555988)))
}
}
| 190
|
TypeScript
|
1
| 3
|
f755ce65909e473e564ff5e273b9b4930e82ad4d
| 3,425
|
monitorenv
|
MIT License
|
src/main/kotlin/org/sjoblomj/adventofcode/day4/Day4.kt
|
sjoblomj
| 161,537,410
| false
| null |
package org.sjoblomj.adventofcode.day4
import org.sjoblomj.adventofcode.readFile
import java.time.format.DateTimeFormatter
import kotlin.system.measureTimeMillis
private const val inputFile = "src/main/resources/inputs/day4.txt"
fun day4() {
println("== DAY 4 ==")
val timeTaken = measureTimeMillis { calculateAndPrintDay4() }
println("Finished Day 4 in $timeTaken ms\n")
}
private fun calculateAndPrintDay4() {
val content = parseIndata(inputFile)
println("Guard who is most asleep * minute guard that guard is the most asleep: ${calculatePart1Checksum(content)}")
println("Guard who is most frequently asleep the same minute * that minute: ${calculatePart2Checksum(content)}")
}
internal fun parseIndata(fileName: String) = parseIndata(readFile(fileName))
internal fun calculatePart1Checksum(shifts: List<Shift>): Int {
val guardId = getGuardIdWhoIsTheMostAsleep(shifts)
val minute = getMinuteThatGuardIsTheMostAsleep(shifts, guardId)
return guardId * minute
}
internal fun calculatePart2Checksum(shifts: List<Shift>): Int {
val pair = shifts
.map { it.id }
.map { id -> Pair(id, getMinuteAndTheNumberOfTimesGuardIsAsleepTheMost(shifts, id)) }
.maxBy { (_, pairOfMinuteAndCount) -> pairOfMinuteAndCount.second }
?: throw RuntimeException("Couldn't find the guard who is the most asleep")
val guardId = pair.first
val minute = pair.second.first
return guardId * minute
}
internal fun getGuardIdWhoIsTheMostAsleep(shifts: List<Shift>): Int {
return shifts
.map { it.id }
.map { id -> Pair(id, getTotalSleepTime(shifts, id)) }
.maxBy { it.second }
?.first
?: throw RuntimeException("Couldn't find the guard who is the most asleep")
}
internal fun getMinuteThatGuardIsTheMostAsleep(shifts: List<Shift>, guardId: Int): Int {
val pairOfMinuteAndCount = getMinuteAndTheNumberOfTimesGuardIsAsleepTheMost(shifts, guardId)
return pairOfMinuteAndCount.first
}
private fun getMinuteAndTheNumberOfTimesGuardIsAsleepTheMost(shifts: List<Shift>, guardId: Int): Pair<Int, Int> {
val shiftsForGuard = shifts.filter { it.id == guardId }
return (0 until 60)
.map { minute ->
Pair(minute, shiftsForGuard
.map { shift -> isAsleepAtGivenMinute(shift, minute) }
.filter { isAsleep -> isAsleep }
.count()
)
}
.maxBy { it.second }
?: throw RuntimeException("Couldn't find the guard who is the most asleep")
}
private fun isAsleepAtGivenMinute(shift: Shift, minute: Int): Boolean {
for (i in shift.minuteWhenFallingAsleep.indices) {
if (minute >= shift.minuteWhenFallingAsleep[i] && minute < shift.minuteWhenAwoken[i])
return true
}
return false
}
internal fun getTotalSleepTime(shifts: List<Shift>, guardId: Int): Int {
return shifts
.filter { it.id == guardId }
.map { getTotalSleepTimeForShift(it) }
.sum()
}
private fun getTotalSleepTimeForShift(shift: Shift): Int {
return shift.minuteWhenFallingAsleep.zip(shift.minuteWhenAwoken) { timeAsleep, timeAwoken -> timeAwoken - timeAsleep }.sum()
}
internal fun visualize(indata: List<Shift>): String {
val maxIdLength = indata.map { it.id.toString().length }.max()?:3
val idSpaces = " ".repeat(maxIdLength)
return "" +
"Date ID$idSpaces Minute\n" +
" $idSpaces 000000000011111111112222222222333333333344444444445555555555\n" +
" $idSpaces 012345678901234567890123456789012345678901234567890123456789\n" +
indata.joinToString("\n") { visualizeShift(it, maxIdLength) }
}
private fun visualizeShift(shift: Shift, maxIdLength: Int): String {
val date = shift.date.format(DateTimeFormatter.ofPattern("MM-dd"))
val id = "#" + shift.id + " ".repeat(maxIdLength - shift.id.toString().length)
var s = ""
for (i in shift.minuteWhenFallingAsleep.indices) {
s += ".".repeat(shift.minuteWhenFallingAsleep[i] - s.length)
s += "#".repeat(shift.minuteWhenAwoken[i] - s.length)
}
s += ".".repeat(60 - s.length)
return "$date $id $s"
}
| 0
|
Kotlin
|
0
| 0
|
80db7e7029dace244a05f7e6327accb212d369cc
| 3,988
|
adventofcode2018
|
MIT License
|
app/src/main/java/io/github/durun/timestampcalendar/ui/SettingsActivity.kt
|
Durun
| 453,370,169
| false
| null |
package io.github.durun.timestampcalendar.ui
import android.app.Activity
import android.app.AlertDialog
import android.app.ProgressDialog
import android.os.Bundle
import android.os.Looper
import android.view.View
import android.widget.Toast
import androidx.activity.result.contract.ActivityResultContracts
import androidx.appcompat.app.AppCompatActivity
import androidx.preference.EditTextPreference
import androidx.preference.PreferenceFragmentCompat
import io.github.durun.timestampcalendar.R
import io.github.durun.timestampcalendar.databinding.SettingsActivityBinding
import io.github.durun.timestampcalendar.libs.*
class SettingsActivity : AppCompatActivity() {
private lateinit var binding: SettingsActivityBinding
private lateinit var settingsFragment: SettingsFragment
private lateinit var auth: MyAuth
private val startSignIn =
registerForActivityResult(ActivityResultContracts.StartActivityForResult()) { result ->
val data = result.data
if (result.resultCode == Activity.RESULT_OK && data != null) {
auth.handleSignInResult(data)
Toast.makeText(this, "Logged in", Toast.LENGTH_SHORT).show()
}
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = SettingsActivityBinding.inflate(layoutInflater)
setContentView(binding.root)
if (savedInstanceState == null) {
settingsFragment = SettingsFragment()
supportFragmentManager
.beginTransaction()
.replace(binding.settings.id, settingsFragment)
.commit()
}
supportActionBar?.setDisplayHomeAsUpEnabled(true)
auth = MyAuth(this)
}
class SettingsFragment : PreferenceFragmentCompat() {
override fun onCreatePreferences(savedInstanceState: Bundle?, rootKey: String?) {
setPreferencesFromResource(R.xml.root_preferences, rootKey)
}
}
fun loginToGoogle(view: View) {
startSignIn.launch(auth.signInIntent())
}
fun createSpreadSheet(view: View) {
// サインインしてなければ中止
if (!auth.isSignedIn()) {
Toast.makeText(this, "Not logged in", Toast.LENGTH_SHORT).show()
return
}
val progress = ProgressDialog(this)
.apply {
title = "Creating Data SpreadSheet"
setProgressStyle(ProgressDialog.STYLE_SPINNER)
}
progress.show()
Thread {
Looper.prepare()
val sheetId = DataSheet.getIdOrNull(auth.credential)
if (sheetId != null) {
// シートが見つかった
runOnUiThread {
settingsFragment
.findPreference<EditTextPreference>("spread_sheet_id")
?.text = sheetId
Toast.makeText(this, "${DataSheet.title} already exists", Toast.LENGTH_SHORT)
.show()
}
} else {
sheetsService(auth.credential).Spreadsheets()
.create(DataSheet.newSheet())
.execute()
val id = DataSheet.getIdOrNull(auth.credential)
?: kotlin.run {
progress.dismiss()
return@Thread
}
runOnUiThread {
settingsFragment
.findPreference<EditTextPreference>("spread_sheet_id")
?.text = id
Toast.makeText(this, "Created Sheet", Toast.LENGTH_SHORT).show()
}
}
progress.dismiss()
}.start()
}
fun selectSpreadSheet(view: View) {
// サインインしてなければ中止
if (!auth.isSignedIn()) {
Toast.makeText(this, "Not logged in", Toast.LENGTH_SHORT).show()
return
}
val progress = ProgressDialog(this)
.apply {
setCancelable(true)
setTitle("Loading sheet list")
setProgressStyle(ProgressDialog.STYLE_SPINNER)
}
val thread = Thread {
Looper.prepare()
val sheets = getSpreadSheetList()
val items = sheets.map { it.name }.toTypedArray()
var selected: Int? = null
progress.dismiss()
runOnUiThread {
val dialog = AlertDialog.Builder(this)
.setTitle("Select Data Sheet")
// 表示アイテムを指定する //
.setSingleChoiceItems(items, -1) { _, i ->
selected = i
}
// 決定・キャンセル用にボタンも配置 //
.setPositiveButton("OK") { _, _ ->
if (selected != null) {
settingsFragment
.findPreference<EditTextPreference>("spread_sheet_id")
?.text = sheets[selected!!].id
}
}
.setNeutralButton("Cancel") { _, _ -> }
.create()
dialog.show()
}
}
progress.show()
thread.start()
}
data class SheetEntry(val name: String, val id: String)
private fun getSpreadSheetList(): List<SheetEntry> {
val service = MyAuth(this)
.let {
it.signInLastAccount()
if (!it.isSignedIn()) {
Toast.makeText(this, "Not logged in", Toast.LENGTH_SHORT).show()
return emptyList()
}
driveService(it.credential)
}
val files = service.Files()
.list()
.setCorpora("user")
.setOrderBy("viewedByMeTime desc")
.setQ("mimeType='application/vnd.google-apps.spreadsheet'")
.setPageSize(100)
.execute()
.files
return files.map { SheetEntry(it.name, it.id) }
}
fun selectCalendar(view: View) {
// サインインしてなければ中止
if (!auth.isSignedIn()) {
Toast.makeText(this, "Not logged in", Toast.LENGTH_SHORT).show()
return
}
// Prepare ProgressDialog
val progress = ProgressDialog(this)
.apply {
setCancelable(true)
setTitle("Loading calendar list")
setProgressStyle(ProgressDialog.STYLE_SPINNER)
}
val thread = Thread {
Looper.prepare()
// Get calendar list
val calendars = calendarService(auth.credential).CalendarList()
.list()
.execute()
.items
.filter { it.accessRole == "owner" }
val items = calendars.map { it.summary }.toTypedArray()
var selected: Int? = null
// Dismiss ProgressDialog
progress.dismiss()
// Show
runOnUiThread {
val dialog = AlertDialog.Builder(this)
.setTitle("Select Calendar")
// 表示アイテムを指定する //
.setSingleChoiceItems(items, -1) { _, i ->
selected = i
}
// 決定・キャンセル用にボタンも配置 //
.setPositiveButton("OK") { _, _ ->
if (selected != null) {
settingsFragment
.findPreference<EditTextPreference>("calendar_id")
?.text = calendars[selected!!].id
}
}
.setNeutralButton("Cancel") { _, _ -> }
.create()
dialog.show()
}
}
// Start
progress.show()
thread.start()
}
}
| 0
|
Kotlin
|
0
| 0
|
23c9c8a68f7512b2ad3b81ccf026925fc4c28d32
| 7,947
|
timestamp-calendar
|
MIT License
|
json-builder/kotlin/src/generated/kotlin/divkit/dsl/InputValidator.kt
|
divkit
| 523,491,444
| false
|
{"Kotlin": 7327303, "Swift": 5164616, "Svelte": 1148832, "TypeScript": 912803, "Dart": 630920, "Python": 536031, "Java": 507940, "JavaScript": 152546, "CSS": 37870, "HTML": 23434, "C++": 20911, "CMake": 18677, "Shell": 8895, "PEG.js": 7210, "Ruby": 3723, "C": 1425, "Objective-C": 38}
|
@file:Suppress(
"unused",
"UNUSED_PARAMETER",
)
package divkit.dsl
import com.fasterxml.jackson.annotation.JsonAnyGetter
import com.fasterxml.jackson.annotation.JsonIgnore
import com.fasterxml.jackson.annotation.JsonValue
import divkit.dsl.annotation.*
import divkit.dsl.core.*
import divkit.dsl.scope.*
import kotlin.Any
import kotlin.String
import kotlin.Suppress
import kotlin.collections.List
import kotlin.collections.Map
/**
* Possible values: [InputValidatorRegex], [InputValidatorExpression].
*/
@Generated
sealed interface InputValidator
@Generated
fun InputValidator.asList() = listOf(this)
| 5
|
Kotlin
|
128
| 2,240
|
dd102394ed7b240ace9eaef9228567f98e54d9cf
| 615
|
divkit
|
Apache License 2.0
|
app/src/main/java/com/cards/coverflow/CoverFlowAdapter.kt
|
kamleshsangani
| 585,285,017
| false
| null |
package com.cards.coverflow
import android.content.Context
import android.graphics.Color
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import androidx.constraintlayout.widget.ConstraintLayout
import androidx.recyclerview.widget.RecyclerView
import com.cards.coverflow.R
class CoverFlowAdapter : RecyclerView.Adapter<CoverFlowAdapter.ViewHolder> {
private val mContext: Context
private val mColors = intArrayOf(
Color.BLUE, Color.BLACK, Color.CYAN, Color.GRAY, Color.MAGENTA, Color.RED, Color.YELLOW
)
private var clickCb: onItemClick? = null
constructor(c: Context) {
mContext = c
}
constructor(c: Context, cb: onItemClick?) {
mContext = c
clickCb = cb
}
fun setClickListener(cb: onItemClick?) {
clickCb = cb
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
val layout = R.layout.layout_item
val v = LayoutInflater.from(mContext).inflate(layout, parent, false)
return ViewHolder(v)
}
override fun onBindViewHolder(holder: ViewHolder, position1: Int) {
val position = holder.bindingAdapterPosition
holder.layout.setBackgroundColor(mColors[position])
holder.itemView.setOnClickListener {
if (clickCb != null) {
clickCb!!.clickItem(position)
}
}
holder.text.text = position.toString()
}
override fun getItemCount(): Int {
return mColors.size
}
inner class ViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
//var img: ImageView
var layout: ConstraintLayout
var text: TextView
init {
//img = itemView.findViewById(R.id.img)
layout = itemView.findViewById(R.id.outer_layout)
text = itemView.findViewById(R.id.labelTextView)
}
}
interface onItemClick {
fun clickItem(pos: Int)
}
}
| 0
|
Kotlin
|
0
| 0
|
facc41cf38710db94c03ea12734f18312c0ce49d
| 2,023
|
CardSwipe
|
Apache License 2.0
|
src/main/java/thedarkcolour/futuremc/entity/fish/EntityGroupFish.kt
|
Sepera-okeq
| 257,567,349
| false
|
{"Text": 2, "Java Properties": 1, "Gradle": 1, "Shell": 1, "Ignore List": 1, "Batchfile": 1, "Markdown": 1, "INI": 1, "Kotlin": 123, "Java": 71, "JSON": 372, "HAProxy": 1}
|
package thedarkcolour.futuremc.entity.fish
import net.minecraft.entity.IEntityLivingData
import net.minecraft.entity.ai.EntityAIBase
import net.minecraft.world.DifficultyInstance
import net.minecraft.world.World
import java.util.stream.Stream
abstract class EntityGroupFish(worldIn: World) : EntityFish(worldIn) {
var groupLeader: EntityGroupFish? = null
var groupSize = 1
open val maxGroupSize: Int
get() = super.getMaxSpawnedInChunk()
override fun initEntityAI() {
super.initEntityAI()
tasks.addTask(5, AIFollowLeader(this))
}
class AIFollowLeader(private val fish: EntityGroupFish) : EntityAIBase() {
private var navigateTimer: Int = 0
private var randomInt: Int
init {
randomInt = genInt(fish)
}
private fun genInt(fish: EntityGroupFish): Int {
return 200 + fish.rand.nextInt(200) % 20
}
override fun shouldExecute(): Boolean {
return when {
fish.isGroupLeader() -> {
false
}
fish.hasGroupLeader() -> {
true
}
randomInt > 0 -> {
--randomInt
false
}
else -> {
randomInt = this.genInt(fish)
val predicate = { fish: EntityGroupFish? -> fish!!.canGroupGrow() || !fish.hasGroupLeader() }
val list = fish.world.getEntitiesWithinAABB(
fish::class.java,
fish.entityBoundingBox.grow(8.0, 8.0, 8.0),
predicate::invoke
)
val groupFish: EntityGroupFish =
list.stream().filter(EntityGroupFish::canGroupGrow).findAny().orElse(fish)
groupFish.acceptMembers(list.stream().filter { !it.hasGroupLeader() })
fish.hasGroupLeader()
}
}
}
override fun shouldContinueExecuting(): Boolean {
return fish.hasGroupLeader() && fish.inRangeOfGroupLeader()
}
override fun startExecuting() {
navigateTimer = 0
}
override fun resetTask() {
fish.leaveGroup()
}
override fun updateTask() {
if (--navigateTimer <= 0) {
navigateTimer = 10
fish.moveToGroupLeader()
}
}
}
fun isGroupLeader(): Boolean {
return groupSize > 1
}
fun hasGroupLeader(): Boolean {
return groupLeader?.isEntityAlive ?: false
}
fun canGroupGrow(): Boolean {
return isGroupLeader() && groupSize < maxGroupSize
}
fun acceptMembers(stream: Stream<EntityGroupFish>) {
stream.limit((maxGroupSize - groupSize).toLong()).filter {
it != this
}.forEach {
it.setLeader(this)
}
}
private fun setLeader(groupLeaderIn: EntityGroupFish): EntityGroupFish {
groupLeader = groupLeaderIn
++groupLeaderIn.groupSize
return groupLeaderIn
}
fun inRangeOfGroupLeader(): Boolean {
return getDistanceSq(groupLeader!!) <= 121.0
}
fun leaveGroup() {
--groupLeader!!.groupSize
groupLeader = null
}
fun moveToGroupLeader() {
if (hasGroupLeader()) {
getNavigator().tryMoveToEntityLiving(groupLeader!!, 1.0)
}
}
override fun shouldSwimAway(): Boolean = !hasGroupLeader()
override fun getMaxSpawnedInChunk(): Int {
return maxGroupSize
}
override fun onInitialSpawn(difficulty: DifficultyInstance, livingdata: IEntityLivingData?): IEntityLivingData {
super.onInitialSpawn(difficulty, livingdata)
return if (livingdata == null) {
GroupData(this)
} else {
setLeader((livingdata as GroupData).groupLeader)
livingdata
}
}
class GroupData(val groupLeader: EntityGroupFish) : IEntityLivingData
override fun onUpdate() {
super.onUpdate()
if (isGroupLeader() && rand.nextInt(200) == 1) {
val list = world.getEntitiesWithinAABB(this::class.java, entityBoundingBox.grow(8.0))
if (list.size <= 1) {
groupSize = 1
}
}
}
}
| 1
| null |
1
| 1
|
b343d2a134eab9575b1f9b45422862b2e964e74a
| 4,402
|
Future-MC
|
FSF All Permissive License
|
src/main/kotlin/org/snd/mediaserver/model/mediaserver/MediaServerLibrary.kt
|
Snd-R
| 463,859,568
| false
| null |
package org.snd.mediaserver.model.mediaserver
data class MediaServerLibrary(
val id: MediaServerLibraryId,
val name: String,
val roots: Collection<String>,
)
| 11
|
Kotlin
|
9
| 99
|
0584078f460c5d8c7b740bbe77905fab1c0ad105
| 171
|
komf
|
MIT License
|
Common/src/main/java/cn/afternode/matrilib/core/MotionData.kt
|
tumuidle
| 609,710,313
| false
| null |
package cn.afternode.matrilib.core
import org.bukkit.Location
data class MotionData(
val motionX: Double = 0.0, val motionY: Double = 0.0, val motionZ: Double = 0.0, val baseLoc: Location,
val onGround: Boolean = true)
| 0
|
Kotlin
|
0
| 1
|
28f7698034cbd0314d67992d209d545aab435aed
| 229
|
MatriLib
|
MIT License
|
graphics/src/main/kotlin/matt/fx/graphics/wrapper/node/line/arc/arc.kt
|
mgroth0
| 497,866,693
| false
|
{"Kotlin": 1308654}
|
package matt.fx.graphics.wrapper.node.line.arc
import javafx.scene.Parent
import javafx.scene.shape.Arc
import matt.fx.graphics.wrapper.node.impl.NodeWrapperImpl
import matt.fx.graphics.wrapper.node.attachTo
import matt.fx.graphics.wrapper.node.shape.ShapeWrapper
fun NodeWrapperImpl<Parent>.arc(
centerX: Number = 0.0,
centerY: Number = 0.0,
radiusX: Number = 0.0,
radiusY: Number = 0.0,
startAngle: Number = 0.0,
length: Number = 0.0,
op: ArcWrapper.()->Unit = {}
) =
ArcWrapper(
centerX.toDouble(), centerY.toDouble(), radiusX.toDouble(), radiusY.toDouble(), startAngle.toDouble(),
length.toDouble()
).attachTo(this, op)
open class ArcWrapper(
node: Arc = Arc(),
): ShapeWrapper<Arc>(node) {
constructor(
centerX: Double,
centerY: Double,
radiusX: Double,
radiusY: Double,
startAngle: Double,
length: Double
): this(Arc(centerX, centerY, radiusX, radiusY, startAngle, length))
var centerX by node::centerX
var centerY by node::centerY
var radiusX by node::radiusX
var radiusY by node::radiusY
var startAngle by node::startAngle
var length by node::length
}
| 0
|
Kotlin
|
0
| 0
|
496b4c03add27fc2825099b5454a05f0493c06ce
| 1,110
|
fx
|
MIT License
|
src/main/kotlin/dev/ufer/model/DocumentType.kt
|
NickUfer
| 313,388,092
| false
| null |
package dev.ufer.model
enum class DocumentType(val value: String) {
DOCUMENT_TYPE("DocumentType"),
COLLECTION_TYPE("CollectionType"),
EMPTY("");
}
| 0
|
Kotlin
|
0
| 0
|
af459e44f7e956919000dd633e817bdf4071687d
| 160
|
remarkable-privatecloud
|
MIT License
|
src/main/kotlin/nl/mitchelnijdam/kafkaretrytest/configuration/KafkaBatchConsumerConfiguration.kt
|
MitchelNijdam-Rockstars
| 224,873,136
| false
| null |
package nl.mitchelnijdam.kafkaretrytest.configuration
import nl.mitchelnijdam.kafkaretrytest.exception.TransientException
import nl.mitchelnijdam.kafkaretrytest.kafka.error.SimpleCustomBatchErrorHandler
import nl.mitchelnijdam.kafkaretrytest.kafka.error.ExtensiveCustomBatchErrorHandler
import org.springframework.context.annotation.Bean
import org.springframework.context.annotation.Configuration
import org.springframework.kafka.annotation.EnableKafka
import org.springframework.kafka.config.ConcurrentKafkaListenerContainerFactory
import org.springframework.kafka.config.KafkaListenerContainerFactory
import org.springframework.kafka.core.ConsumerFactory
import org.springframework.kafka.core.KafkaTemplate
import org.springframework.kafka.listener.ContainerProperties
import org.springframework.kafka.listener.SeekToCurrentBatchErrorHandler
import org.springframework.util.backoff.ExponentialBackOff
import org.springframework.util.backoff.FixedBackOff
@Configuration
@EnableKafka
class KafkaBatchConsumerConfiguration {
@Bean
fun kafkaBatchFactory(kafkaConsumerFactory: ConsumerFactory<Any, Any>): KafkaListenerContainerFactory<*> {
val factory = ConcurrentKafkaListenerContainerFactory<Int, String>()
factory.consumerFactory = kafkaConsumerFactory
factory.isBatchListener = true
/**
* From documentation: Since this error handler has no mechanism to "recover" after retries are exhausted,
* if the BackOffExecution returns STOP, the previous interval will be used for all subsequent delays.
* The maximum delay must be less than the max.poll.interval.ms consumer property.
*
* https://docs.spring.io/spring-kafka/reference/html/#seek-to-current
*/
val errorHandler = SeekToCurrentBatchErrorHandler()
errorHandler.setBackOff(FixedBackOff(BACK_OFF_PERIOD, 1L))
factory.setBatchErrorHandler(errorHandler)
return factory
}
@Bean
fun customErrorHandlerKafkaBatchFactory(
kafkaConsumerFactory: ConsumerFactory<Any, Any>,
simpleCustomBatchErrorHandler: SimpleCustomBatchErrorHandler
): KafkaListenerContainerFactory<*> {
val factory = ConcurrentKafkaListenerContainerFactory<Int, String>()
factory.consumerFactory = kafkaConsumerFactory
factory.isBatchListener = true
factory.containerProperties.ackMode = ContainerProperties.AckMode.MANUAL_IMMEDIATE
factory.setBatchErrorHandler(simpleCustomBatchErrorHandler)
return factory
}
@Bean
fun extensiveCustomErrorHandlerKafkaBatchFactory(
kafkaConsumerFactory: ConsumerFactory<Any, Any>,
kafkaTemplate: KafkaTemplate<Any, Any>
): KafkaListenerContainerFactory<*> {
val factory = ConcurrentKafkaListenerContainerFactory<Int, String>()
factory.consumerFactory = kafkaConsumerFactory
factory.isBatchListener = true
val backOff = FixedBackOff(BACK_OFF_PERIOD, MAX_ATTEMPTS.toLong())
//val backOff = ExponentialBackOff()
//backOff.initialInterval = 1_000L
//backOff.maxInterval = 30_000L // this should not be bigger than max.poll.interval.ms
//backOff.maxElapsedTime = 30_000L // total elapsed time, only way to stop the backoff
val errorHandler = ExtensiveCustomBatchErrorHandler(kafkaTemplate, backOff)
errorHandler.addRetryableException(TransientException::class.java)
factory.setBatchErrorHandler(errorHandler)
return factory
}
}
| 0
|
Kotlin
|
1
| 4
|
b3890ee905cb92c7cf6365afa6ea16792b4aeaf6
| 3,545
|
kafka-retry-demo
|
Apache License 2.0
|
app/src/main/java/com/example/composeshoppinglist/MainActivity.kt
|
LasseHindsberg
| 861,428,572
| false
|
{"Kotlin": 9482}
|
package com.example.composeshoppinglist
import android.content.Context
import android.os.Build
import android.os.Bundle
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.activity.enableEdgeToEdge
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxHeight
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.foundation.text.KeyboardOptions
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Add
import androidx.compose.material.icons.filled.Delete
import androidx.compose.material3.Button
import androidx.compose.material3.Card
import androidx.compose.material3.CardDefaults
import androidx.compose.material3.Divider
import androidx.compose.material3.ElevatedCard
import androidx.compose.material3.HorizontalDivider
import androidx.compose.material3.Icon
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.OutlinedTextField
import androidx.compose.material3.Scaffold
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateListOf
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Modifier
import androidx.compose.ui.text.input.KeyboardType
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import com.example.composeshoppinglist.ui.theme.ComposeShoppingListTheme
import java.nio.file.Files.delete
class MainActivity : ComponentActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
enableEdgeToEdge()
setContent {
ComposeShoppingListTheme {
Scaffold(modifier = Modifier.fillMaxSize()) { innerPadding ->
ShoppingList(
modifier = Modifier.padding(innerPadding)
)
}
}
}
}
}
@Composable
fun ShoppingList(modifier: Modifier = Modifier) {
val shoppingItems = remember { mutableStateListOf<String>() }
var shoppingItem by remember { mutableStateOf("") }
var showItems by remember { mutableStateOf(true) }
Column(modifier = modifier.padding(10.dp)) {
Text(text = "Shopping List", style = MaterialTheme.typography.headlineLarge)
Row(
modifier = modifier.fillMaxWidth(),
horizontalArrangement = Arrangement.SpaceBetween
) {
OutlinedTextField(
value = shoppingItem,
onValueChange = { shoppingItem = it },
keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Text),
// modifier = modifier.fillMaxWidth(),
label = { Text("Enter your shopping item") }
)
Button(onClick = {
if (shoppingItem.isNotBlank()) {
shoppingItems.add(shoppingItem)
shoppingItem = ""
}
modifier.padding(8.dp)
.size(height = 50.dp, width = 50.dp)
}) {
Icon(Icons.Default.Add, contentDescription = "Add Item")
}
}
Spacer(modifier = Modifier.height(16.dp))
if (showItems) {
LazyColumn(modifier = modifier.fillMaxHeight()) {
items(shoppingItems) { item ->
ElevatedCard(
elevation = CardDefaults.cardElevation(
defaultElevation = 6.dp
),
) {
Row(
modifier
.padding(8.dp)
.fillMaxWidth(),
horizontalArrangement = Arrangement.SpaceBetween
) {
Text(
text = item,
fontSize = 20.sp
)
Icon(
Icons.Default.Delete,
contentDescription = "remove item",
modifier
.clickable { shoppingItems.remove(item) }
.size(32.dp)
)
}
}
Spacer(modifier = modifier.height(8.dp))
}
}
}
}
}
@Preview(showSystemUi = true, showBackground = true)
@Composable
fun ShoppingPreview() {
ComposeShoppingListTheme {
ShoppingList()
}
}
| 0
|
Kotlin
|
0
| 0
|
01ddff9ffd635b2e82c2d5710ba2370bc6884c48
| 5,425
|
ComposeShoppingListBasic
|
MIT License
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.