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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
app/src/main/java/com/sadashi/apps/extensions/ViewGroupExtension.kt
|
sadashi-ota
| 129,120,443
| false
| null |
package com.sadashi.apps.extensions
import android.support.annotation.LayoutRes
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
fun ViewGroup.inflate(@LayoutRes layoutRes: Int): View {
return LayoutInflater.from(context).inflate(layoutRes, this, false)
}
| 0
|
Kotlin
|
0
| 0
|
f72515a2b4cf415c80243a32e1d6371a70499860
| 304
|
material_ui_like_play_store
|
Apache License 2.0
|
src/main/kotlin/com/komorowskidev/tuicodechallenge/githubrepo/domain/type/GithubRepository.kt
|
komorowskidev
| 698,516,599
| false
|
{"Kotlin": 16517, "Dockerfile": 199}
|
package com.komorowskidev.tuicodechallenge.githubrepo.domain.type
data class GithubRepository(
val name: String,
val fork: Boolean,
)
| 0
|
Kotlin
|
0
| 0
|
d478ebc902b006aa507136fc6549c8d9a69342dd
| 143
|
tuicodechallenge
|
MIT License
|
fluxo-kmp-conf/src/main/kotlin/SetupGradlePlugin.kt
|
fluxo-kt
| 705,309,218
| false
|
{"Kotlin": 470827}
|
import fluxo.conf.dsl.FluxoConfigurationExtension
import fluxo.conf.dsl.fluxoConfiguration
import fluxo.conf.feat.gradlePlugin
import fluxo.conf.impl.e
import fluxo.conf.impl.l
import fluxo.conf.impl.w
import org.gradle.api.Project
import org.jetbrains.kotlin.gradle.dsl.KotlinJvmProjectExtension
public fun Project.setupGradlePlugin(
pluginName: String? = null,
pluginClass: String? = null,
displayName: String? = null,
group: String? = this.group.toString().takeIf { it.isNotBlank() },
tags: List<String>? = null,
pluginId: String? = if (pluginName != null && group != null) "$group.$pluginName" else null,
kotlin: (KotlinJvmProjectExtension.() -> Unit)? = null,
config: (FluxoConfigurationExtension.() -> Unit)? = null,
): Unit = fluxoConfiguration c@{
explicitApi()
kotlin?.let { kotlinJvmConfiguration ->
onConfiguration {
// TODO: Can we avoid this cast?
(this as KotlinJvmProjectExtension).kotlinJvmConfiguration()
}
}
config?.invoke(this)
asGradlePlugin()
pluginName ?: return@c
onConfiguration {
gradlePlugin.apply {
plugins.create(pluginName) {
// TODO: Retry create pluginId from configuration if null?
val logger = logger
if (pluginId.isNullOrEmpty()) {
logger.w("Plugin ID is not set for plugin '$pluginName'!")
} else {
id = pluginId
logger.l("Plugin '$pluginName' prepared with ID '$pluginId'")
}
pluginClass?.let { implementationClass = it }
displayName?.let { this.displayName = it }
this@c.description?.let { this.description = it }
if (!tags.isNullOrEmpty()) {
try {
@Suppress("UnstableApiUsage")
this.tags.set(tags)
} catch (e: Throwable) {
logger.e("Failed to set tags for plugin $pluginName", e)
}
}
}
}
}
}
| 0
|
Kotlin
|
0
| 1
|
96eccd5d159e81bba79f2df0fa434403518df937
| 2,134
|
fluxo-kmp-conf
|
Apache License 2.0
|
halley-ktor/src/main/java/com/infinum/halley/ktor/configuration/HalleyConfiguration.kt
|
infinum
| 515,133,770
| false
| null |
package com.infinum.halley.ktor.configuration
import HAL
import io.ktor.http.ContentType
import io.ktor.http.ContentTypeMatcher
import io.ktor.serialization.Configuration
import io.ktor.serialization.ContentConverter
/**
* A [HalleyPlugin] configuration that is used during installation.
*/
public class HalleyConfiguration : Configuration {
internal class ConverterRegistration(
val converter: ContentConverter,
val contentTypeToSend: ContentType,
val contentTypeMatcher: ContentTypeMatcher,
)
private val registrations = mutableListOf<ConverterRegistration>()
/**
* Registers a [contentType] to a specified [converter] with an optional [configuration] script for a converter.
*/
public override fun <T : ContentConverter> register(
contentType: ContentType,
converter: T,
configuration: T.() -> Unit
) {
val matcher = when (contentType) {
ContentType.HAL -> HalleyContentTypeMatcher
else -> defaultMatcher(contentType)
}
registrations.add(
ConverterRegistration(
converter.apply(configuration),
contentType,
matcher
)
)
}
internal fun registrations() = registrations.toList()
private fun defaultMatcher(pattern: ContentType): ContentTypeMatcher =
object : ContentTypeMatcher {
override fun contains(contentType: ContentType): Boolean =
contentType.match(pattern)
}
}
| 0
|
Kotlin
|
0
| 0
|
0af19cf3a4ffeebb10b5b053dff01bb1acd15dbc
| 1,545
|
android-halley
|
Apache License 2.0
|
app/src/main/java/com/gaugustini/vort/domain/ResultWithNamesCase.kt
|
gaugustini
| 416,395,415
| false
| null |
package com.gaugustini.vort.domain
import com.gaugustini.vort.model.Result
import com.gaugustini.vort.model.ResultWithNames
import com.gaugustini.vort.repository.ArmorPieceRepository
import com.gaugustini.vort.repository.DecorationRepository
import com.gaugustini.vort.repository.LanguageRepository
import com.gaugustini.vort.repository.ResultRepository
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.flow
import kotlinx.coroutines.withContext
import javax.inject.Inject
class ResultWithNamesCase @Inject constructor(
private val resultRepository: ResultRepository,
private val languageRepository: LanguageRepository,
private val armorPieceRepository: ArmorPieceRepository,
private val decorationRepository: DecorationRepository,
) {
private var headList = mapOf<Int, String>()
private var bodyList = mapOf<Int, String>()
private var armsList = mapOf<Int, String>()
private var waistList = mapOf<Int, String>()
private var legsList = mapOf<Int, String>()
private var decorationList = mapOf<Int, String>()
fun getResultListWithNames(language: Int): Flow<List<ResultWithNames>> = flow {
resultRepository.getResultList().collect { list ->
withContext(Dispatchers.IO) { loadLists(list, language) }
this.emit(buildList { list.forEach { result -> add(toResultWithNames(result)) } })
}
}
private suspend fun loadLists(resultList: List<Result>, language: Int) {
var idList: List<Int> =
buildList { resultList.forEach { if (!this.contains(it.head)) add(it.head) } }
var nameIdList = armorPieceRepository.getNameIdList(idList, 1)
var names: List<String> = languageRepository.getNameList(nameIdList, language)
headList = buildMap { idList.forEachIndexed { index, id -> this[id] = names[index] } }
idList = buildList { resultList.forEach { if (!this.contains(it.body)) add(it.body) } }
nameIdList = armorPieceRepository.getNameIdList(idList, 2)
names = languageRepository.getNameList(nameIdList, language)
bodyList = buildMap { idList.forEachIndexed { index, id -> this[id] = names[index] } }
idList = buildList { resultList.forEach { if (!this.contains(it.arms)) add(it.arms) } }
nameIdList = armorPieceRepository.getNameIdList(idList, 3)
names = languageRepository.getNameList(nameIdList, language)
armsList = buildMap { idList.forEachIndexed { index, id -> this[id] = names[index] } }
idList = buildList { resultList.forEach { if (!this.contains(it.waist)) add(it.waist) } }
nameIdList = armorPieceRepository.getNameIdList(idList, 4)
names = languageRepository.getNameList(nameIdList, language)
waistList = buildMap { idList.forEachIndexed { index, id -> this[id] = names[index] } }
idList = buildList { resultList.forEach { if (!this.contains(it.legs)) add(it.legs) } }
nameIdList = armorPieceRepository.getNameIdList(idList, 5)
names = languageRepository.getNameList(nameIdList, language)
legsList = buildMap { idList.forEachIndexed { index, id -> this[id] = names[index] } }
idList = buildList {
resultList.forEach {
it.decorations.forEach { (key, _) -> if (!this.contains(key)) this.add(key) }
}
}.sorted()
nameIdList = decorationRepository.getNameIdList(idList)
names = languageRepository.getNameList(nameIdList, language)
decorationList = buildMap { idList.forEachIndexed { index, id -> this[id] = names[index] } }
}
private fun toResultWithNames(result: Result): ResultWithNames {
return ResultWithNames(
head = headList[result.head] as String,
body = bodyList[result.body] as String,
arms = armsList[result.arms] as String,
waist = waistList[result.waist] as String,
legs = legsList[result.legs] as String,
decorations = buildList {
result.decorations.forEach { (key, value) ->
this.add(Pair(decorationList[key].toString(), value))
}
}
)
}
}
| 0
|
Kotlin
|
0
| 0
|
2f26bb863801caab95733511c6683b527ef33f35
| 4,220
|
vort
|
MIT License
|
app/src/main/java/com/gracedian/explorebojonegoro/ui/welcome/WelcomeActivity.kt
|
rikoarik
| 724,154,798
| false
|
{"Kotlin": 347415}
|
package com.gracedian.explorebojonegoro.ui.welcome
import android.content.Intent
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import androidx.activity.enableEdgeToEdge
import androidx.appcompat.widget.AppCompatButton
import com.gracedian.explorebojonegoro.R
import com.gracedian.explorebojonegoro.ui.auth.RegisterActivity
import com.gracedian.explorebojonegoro.ui.auth.SignInActivity
class WelcomeActivity : AppCompatActivity() {
private lateinit var btLogin: AppCompatButton
private lateinit var btRegister: AppCompatButton
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
enableEdgeToEdge()
setContentView(R.layout.activity_welcome)
SharedPrefManager.isFirstInstall(this)
btLogin = findViewById(R.id.btLogin)
btRegister = findViewById(R.id.btRegister)
btLogin.setOnClickListener {
val intent = Intent(this, SignInActivity::class.java)
startActivity(intent)
}
btRegister.setOnClickListener {
val intent = Intent(this, RegisterActivity::class.java)
startActivity(intent)
}
}
}
| 0
|
Kotlin
|
0
| 1
|
9bd4b5b425a273b5f744cf7c34cb05534d60bc2e
| 1,194
|
ExploreBojonegoro
|
MIT License
|
app/src/main/java/com/yamin/chatchat/adapters/ChatsTabRecyclerViewAdapter.kt
|
YaminArafat
| 609,940,129
| false
| null |
package com.yamin.chatchat.adapters
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import androidx.recyclerview.widget.RecyclerView
import com.bumptech.glide.Glide
import com.yamin.chatchat.data.models.Chats
import com.yamin.chatchat.databinding.ChatsRecyclerViewItemsBinding
import com.yamin.chatchat.helpers.OnItemClickListener
import com.yamin.chatchat.utils.CommonUtils
import de.hdodenhof.circleimageview.CircleImageView
class ChatsTabRecyclerViewAdapter(
private val chatsList: ArrayList<Chats>,
private val currentUserId: String,
private val startChat: OnItemClickListener
) :
RecyclerView.Adapter<ChatsTabRecyclerViewAdapter.ChatsTabViewHolder>() {
private lateinit var viewBinding: ChatsRecyclerViewItemsBinding
inner class ChatsTabViewHolder(binding: ChatsRecyclerViewItemsBinding) : RecyclerView.ViewHolder(binding.root) {
val profileImage: CircleImageView = binding.chatsProfilePic
val profileName: TextView = binding.chatsProfileName
val lastMessage: TextView = binding.chatsMessages
val lastMessageTime: TextView = binding.chatsTime
val seenMessage: CircleImageView = binding.chatsSeenProfilePic
init {
binding.root.setOnClickListener {
val position = adapterPosition
startChat.onClick(chatsList[position].userId)
}
}
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ChatsTabViewHolder {
viewBinding = ChatsRecyclerViewItemsBinding.inflate(LayoutInflater.from(parent.context), parent, false)
return ChatsTabViewHolder(viewBinding)
}
override fun onBindViewHolder(holder: ChatsTabViewHolder, position: Int) {
holder.apply {
Glide.with(itemView).load(chatsList[position].userProfileImage).into(profileImage)
val displayName = chatsList[position].userFirstName + " " + chatsList[position].userLastName
profileName.text = displayName
val lastMessageData = chatsList[position].lastMessage
lastMessageTime.text = CommonUtils.getFormattedTime(lastMessageData.messageTimestamp)
if (lastMessageData.senderId == currentUserId) {
val lastMessageDisplayContent = "You: " + lastMessageData.messageText
lastMessage.text = lastMessageDisplayContent
Glide.with(itemView).load(chatsList[position].userProfileImage).into(seenMessage)
seenMessage.visibility = View.VISIBLE
} else {
lastMessage.text = lastMessageData.messageText
seenMessage.visibility = View.INVISIBLE
}
}
}
override fun getItemCount(): Int {
return chatsList.size
}
fun updateData(newData: ArrayList<Chats>) {
Log.d(TAG, "updateData")
chatsList.clear()
chatsList.addAll(newData)
notifyDataSetChanged()
}
companion object {
const val TAG = "FriendsViewModel"
}
}
| 0
|
Kotlin
|
0
| 0
|
483bd013db258f07d8436fff90bea6c5570ec02e
| 3,106
|
ChatChat
|
Apache License 2.0
|
src/main/kotlin/me/aberrantfox/warmbot/commands/UtilityCommands.kt
|
the-programmers-hangout
| 251,074,725
| false
| null |
package me.aberrantfox.warmbot.commands
import me.aberrantfox.kjdautils.api.dsl.command.*
import me.aberrantfox.kjdautils.extensions.stdlib.toMinimalTimeString
import me.aberrantfox.warmbot.messages.Locale
import java.awt.Color
import java.util.Date
private val startTime = Date()
@CommandSet("Utility")
fun utilityCommands() = commands {
command("Ping") {
requiresGuild = true
description = Locale.PING_DESCRIPTION
execute {
it.respond("JDA ping: ${it.discord.jda.gatewayPing}ms\n")
}
}
command("Uptime") {
description = Locale.UPTIME_DESCRIPTION
execute {
val seconds = (Date().time - startTime.time) / 1000
it.respond {
title = "I have been running since"
description = startTime.toString()
color = Color.WHITE
field {
name = "That's been"
value = seconds.toMinimalTimeString()
}
}
}
}
}
| 0
|
Kotlin
|
0
| 1
|
04233ad02ad14fcaaccd5d57f81b30bfcb8d688d
| 1,036
|
WarmBot
|
MIT License
|
src/main/kotlin/me/aberrantfox/warmbot/commands/UtilityCommands.kt
|
the-programmers-hangout
| 251,074,725
| false
| null |
package me.aberrantfox.warmbot.commands
import me.aberrantfox.kjdautils.api.dsl.command.*
import me.aberrantfox.kjdautils.extensions.stdlib.toMinimalTimeString
import me.aberrantfox.warmbot.messages.Locale
import java.awt.Color
import java.util.Date
private val startTime = Date()
@CommandSet("Utility")
fun utilityCommands() = commands {
command("Ping") {
requiresGuild = true
description = Locale.PING_DESCRIPTION
execute {
it.respond("JDA ping: ${it.discord.jda.gatewayPing}ms\n")
}
}
command("Uptime") {
description = Locale.UPTIME_DESCRIPTION
execute {
val seconds = (Date().time - startTime.time) / 1000
it.respond {
title = "I have been running since"
description = startTime.toString()
color = Color.WHITE
field {
name = "That's been"
value = seconds.toMinimalTimeString()
}
}
}
}
}
| 0
|
Kotlin
|
0
| 1
|
04233ad02ad14fcaaccd5d57f81b30bfcb8d688d
| 1,036
|
WarmBot
|
MIT License
|
app/src/test/java/com/concordium/wallet/data/util/CurrencyUtilUnitTest.kt
|
Concordium
| 358,250,608
| false
| null |
package com.concordium.wallet.data.util
import org.junit.Assert.assertEquals
import org.junit.Test
import java.text.DecimalFormatSymbols
class CurrencyUtilUnitTest {
private val decimalSeparator = DecimalFormatSymbols.getInstance().decimalSeparator
private fun replaceDecimalSep(str: String): String {
if (decimalSeparator != '.') {
return str.replace('.', decimalSeparator)
}
return str
}
@Test
fun formatGTU() {
assertEquals(replaceDecimalSep("0.00"), CurrencyUtil.formatGTU(0))
assertEquals(replaceDecimalSep("1.00"), CurrencyUtil.formatGTU(1000000))
assertEquals(replaceDecimalSep("100.00"), CurrencyUtil.formatGTU(100000000))
assertEquals(replaceDecimalSep("1.20"), CurrencyUtil.formatGTU(1200000))
assertEquals(replaceDecimalSep("1.23"), CurrencyUtil.formatGTU(1230000))
assertEquals(replaceDecimalSep("1.234"), CurrencyUtil.formatGTU(1234000))
assertEquals(replaceDecimalSep("1.2345"), CurrencyUtil.formatGTU(1234500))
assertEquals(replaceDecimalSep("123.4567"), CurrencyUtil.formatGTU(123456700))
assertEquals(replaceDecimalSep("0.0001"), CurrencyUtil.formatGTU(100))
assertEquals(replaceDecimalSep("0.0012"), CurrencyUtil.formatGTU(1200))
assertEquals(replaceDecimalSep("0.01"), CurrencyUtil.formatGTU(10000))
assertEquals(replaceDecimalSep("0.0123"), CurrencyUtil.formatGTU(12300))
assertEquals(replaceDecimalSep("0.20"), CurrencyUtil.formatGTU(200000))
assertEquals(replaceDecimalSep("0.23"), CurrencyUtil.formatGTU(230000))
assertEquals(replaceDecimalSep("0.234"), CurrencyUtil.formatGTU(234000))
assertEquals(replaceDecimalSep("0.2345"), CurrencyUtil.formatGTU(234500))
assertEquals(replaceDecimalSep("-1.00"), CurrencyUtil.formatGTU(-1000000))
assertEquals(replaceDecimalSep("-100.00"), CurrencyUtil.formatGTU(-100000000))
assertEquals(replaceDecimalSep("-1.20"), CurrencyUtil.formatGTU(-1200000))
assertEquals(replaceDecimalSep("-1.23"), CurrencyUtil.formatGTU(-1230000))
assertEquals(replaceDecimalSep("-1.234"), CurrencyUtil.formatGTU(-1234000))
assertEquals(replaceDecimalSep("-1.2345"), CurrencyUtil.formatGTU(-1234500))
assertEquals(replaceDecimalSep("-123.4567"), CurrencyUtil.formatGTU(-123456700))
assertEquals(replaceDecimalSep("-0.0001"), CurrencyUtil.formatGTU(-100))
assertEquals(replaceDecimalSep("-0.0012"), CurrencyUtil.formatGTU(-1200))
assertEquals(replaceDecimalSep("-0.01"), CurrencyUtil.formatGTU(-10000))
assertEquals(replaceDecimalSep("-0.0123"), CurrencyUtil.formatGTU(-12300))
assertEquals(replaceDecimalSep("-0.20"), CurrencyUtil.formatGTU(-200000))
assertEquals(replaceDecimalSep("-0.23"), CurrencyUtil.formatGTU(-230000))
assertEquals(replaceDecimalSep("-0.234"), CurrencyUtil.formatGTU(-234000))
assertEquals(replaceDecimalSep("-0.2345"), CurrencyUtil.formatGTU(-234500))
assertEquals(replaceDecimalSep("-100.234547"), CurrencyUtil.formatGTU(-100234547))
assertEquals(replaceDecimalSep("-100.23454"), CurrencyUtil.formatGTU(-100234540))
assertEquals(replaceDecimalSep("-100.2345"), CurrencyUtil.formatGTU(-100234500))
assertEquals(replaceDecimalSep("-100.234"), CurrencyUtil.formatGTU(-100234000))
assertEquals(replaceDecimalSep("-100.23"), CurrencyUtil.formatGTU(-100230000))
assertEquals(replaceDecimalSep("-100.20"), CurrencyUtil.formatGTU(-100200000))
assertEquals(replaceDecimalSep("-100.00"), CurrencyUtil.formatGTU(-100000000))
//For the following to be tested it needs to be in an instumented test, or an
// alternative solution for the resource string is needed: let the CurrencyUtil use a
// ResourcecProvider.getString (that is set on the AppCore) instead of having reference to context
//assertEquals(replaceDecimalSep("0.00"), CurrencyUtil.formatGTU(0, withGStroke = true))
//assertEquals(replaceDecimalSep("1.00"), CurrencyUtil.formatGTU(10000, withGStroke = true))
//assertEquals(replaceDecimalSep("-1.00"), CurrencyUtil.formatGTU(-10000, withGStroke = true))
}
@Test
fun toGTUValue() {
assertEquals(1000000L, CurrencyUtil.toGTUValue(replaceDecimalSep("1.00")))
assertEquals(1000000L, CurrencyUtil.toGTUValue(replaceDecimalSep("1")))
assertEquals(123456000000L, CurrencyUtil.toGTUValue(replaceDecimalSep("123456")))
assertEquals(1000000L, CurrencyUtil.toGTUValue(replaceDecimalSep("1.0")))
assertEquals(1000000L, CurrencyUtil.toGTUValue(replaceDecimalSep("1.000")))
assertEquals(1000000L, CurrencyUtil.toGTUValue(replaceDecimalSep("1.0000")))
assertEquals(1000000L, CurrencyUtil.toGTUValue(replaceDecimalSep("1.000000")))
assertEquals(null, CurrencyUtil.toGTUValue(replaceDecimalSep("1.00.00.00")))
assertEquals(null, CurrencyUtil.toGTUValue(replaceDecimalSep("")))
assertEquals(null, CurrencyUtil.toGTUValue(replaceDecimalSep("abc")))
assertEquals(-1000000L, CurrencyUtil.toGTUValue(replaceDecimalSep("-1.00")))
assertEquals(-1000000L, CurrencyUtil.toGTUValue(replaceDecimalSep("-1")))
assertEquals(-123456000000L, CurrencyUtil.toGTUValue(replaceDecimalSep("-123456")))
assertEquals(-1000000L, CurrencyUtil.toGTUValue(replaceDecimalSep("-1.0")))
assertEquals(-1000000L, CurrencyUtil.toGTUValue(replaceDecimalSep("-1.000")))
assertEquals(-1000000L, CurrencyUtil.toGTUValue(replaceDecimalSep("-1.0000")))
assertEquals(-1000000L, CurrencyUtil.toGTUValue(replaceDecimalSep("-1.000000")))
assertEquals(null, CurrencyUtil.toGTUValue(replaceDecimalSep("-1.00.00.00")))
}
}
| 77
|
Kotlin
|
1
| 6
|
cf482234db350007bdfef2540e16b07bfa174d03
| 5,808
|
concordium-reference-wallet-android
|
Apache License 2.0
|
app/src/main/java/com/tanasi/mangajap/fragments/reviewsave/ReviewSaveViewModel.kt
|
stantanasi
| 356,597,017
| false
|
{"Kotlin": 527731}
|
package com.tanasi.mangajap.fragments.reviewsave
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.tanasi.jsonapi.JsonApiResponse
import com.tanasi.mangajap.models.Review
import com.tanasi.mangajap.utils.MangaJapApi
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.launch
class ReviewSaveViewModel(id: String?) : ViewModel() {
private val _state = MutableStateFlow<State>(State.Loading)
val state: Flow<State> = _state
sealed class State {
data object Loading : State()
data class SuccessLoading(val review: Review) : State()
data class FailedLoading(val error: JsonApiResponse.Error) : State()
data object Saving : State()
data class SuccessSaving(val review: Review) : State()
data class FailedSaving(val error: JsonApiResponse.Error) : State()
}
init {
getReview(id)
}
private fun getReview(id: String?) = viewModelScope.launch(Dispatchers.IO) {
_state.emit(State.Loading)
try {
if (id == null) {
_state.emit(State.SuccessLoading(Review()))
return@launch
}
val response = MangaJapApi.Reviews.details(id)
when (response) {
is JsonApiResponse.Success -> {
_state.emit(State.SuccessLoading(response.body.data!!))
}
is JsonApiResponse.Error -> {
_state.emit(State.FailedLoading(response))
}
}
} catch (e: Exception) {
_state.emit(State.FailedLoading(JsonApiResponse.Error.UnknownError(e)))
}
}
fun saveReview(review: Review) = viewModelScope.launch(Dispatchers.IO) {
_state.emit(State.Saving)
try {
val id = review.id
val response = if (id == null) {
MangaJapApi.Reviews.create(review)
} else {
MangaJapApi.Reviews.update(id, review)
}
when (response) {
is JsonApiResponse.Success -> {
_state.emit(State.SuccessSaving(response.body.data!!))
}
is JsonApiResponse.Error -> {
_state.emit(State.FailedSaving(response))
}
}
} catch (e: Exception) {
_state.emit(State.FailedSaving(JsonApiResponse.Error.UnknownError(e)))
}
}
}
| 0
|
Kotlin
|
2
| 3
|
18bf10ec562af28cb52a48a3ac3caa64064ea79b
| 2,560
|
mangajap
|
Apache License 2.0
|
domain/src/main/java/com/demont/ldap/domain/business/preferences/GetThemeUseCase.kt
|
MaxMichel2
| 517,036,014
| false
| null |
package com.demont.ldap.domain.business.preferences
import com.demont.ldap.domain.business.base.FlowUseCase
import com.demont.ldap.domain.di.IoDispatcher
import com.demont.ldap.domain.model.Result
import com.demont.ldap.domain.model.preferences.Theme
import com.demont.ldap.domain.preferences.PreferenceRepository
import javax.inject.Inject
import kotlinx.coroutines.CoroutineDispatcher
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.collectLatest
import kotlinx.coroutines.flow.flow
class GetThemeUseCase @Inject constructor(
private val repository: PreferenceRepository,
@IoDispatcher private val dispatcher: CoroutineDispatcher
) : FlowUseCase<Unit, Theme>(dispatcher) {
override fun execute(parameters: Unit): Flow<Result<Theme>> {
return flow {
emit(Result.Loading)
repository.theme.collectLatest {
emit(Result.Success(it))
}
}
}
}
| 0
|
Kotlin
|
0
| 0
|
196237feffbf3b7f44210e0538693fab58ec0def
| 944
|
LDAP
|
Apache License 2.0
|
libs/data/src/main/kotlin/com/astrum/data/property/MigrationProperties.kt
|
yacosta738
| 579,772,354
| false
| null |
package com.astrum.data.property
import org.springframework.boot.context.properties.ConfigurationProperties
@ConfigurationProperties(prefix = "application.migration")
data class MigrationProperties(
var clear: Boolean
)
| 3
|
Kotlin
|
0
| 1
|
0f704b8c8e99de3985d29f3f5364fcbf2d2c5c1b
| 226
|
astrum
|
MIT License
|
rui-kotlin-plugin/src/main/kotlin/hu/simplexion/rui/kotlin/plugin/ir/rum2sir/dirtyMask.kt
|
spxbhuhb
| 635,590,591
| false
| null |
package hu.simplexion.rui.kotlin.plugin.ir.rum2sir
import hu.simplexion.rui.kotlin.plugin.ir.RUI_INVALIDATE
import hu.simplexion.rui.kotlin.plugin.ir.RUI_MASK
import hu.simplexion.rui.kotlin.plugin.ir.rum.RumDirtyMask
import hu.simplexion.rui.kotlin.plugin.ir.sir.SirDirtyMask
import hu.simplexion.rui.kotlin.plugin.ir.util.ClassBoundIrBuilder
import org.jetbrains.kotlin.backend.common.ir.addDispatchReceiver
import org.jetbrains.kotlin.backend.common.lower.DeclarationIrBuilder
import org.jetbrains.kotlin.descriptors.Modality
import org.jetbrains.kotlin.ir.builders.declarations.addValueParameter
import org.jetbrains.kotlin.ir.builders.declarations.buildFun
import org.jetbrains.kotlin.ir.builders.irBlockBody
import org.jetbrains.kotlin.ir.declarations.IrProperty
import org.jetbrains.kotlin.ir.declarations.IrSimpleFunction
import org.jetbrains.kotlin.ir.declarations.IrValueParameter
import org.jetbrains.kotlin.ir.expressions.IrBody
import org.jetbrains.kotlin.ir.util.defaultType
import org.jetbrains.kotlin.name.Name
context(ClassBoundIrBuilder)
fun RumDirtyMask.toSir(): SirDirtyMask {
val property = addProperty(name, irBuiltIns.longType, true, irConst(0))
return SirDirtyMask(
property,
irInvalidate(property),
)
}
context(ClassBoundIrBuilder)
private fun RumDirtyMask.irInvalidate(property: IrProperty): IrSimpleFunction =
irFactory
.buildFun {
name = Name.identifier(RUI_INVALIDATE + index)
returnType = irBuiltIns.unitType
modality = Modality.OPEN
}.also { function ->
function.parent = irClass
val receiver = function.addDispatchReceiver {
type = irClass.defaultType
}
val mask = function.addValueParameter {
name = Name.identifier(RUI_MASK)
type = irBuiltIns.longType
}
function.body = initInvalidateBody(function, property, receiver, mask)
irClass.declarations += function
}
context(ClassBoundIrBuilder)
private fun initInvalidateBody(function: IrSimpleFunction, property: IrProperty, receiver: IrValueParameter, mask: IrValueParameter): IrBody =
DeclarationIrBuilder(irContext, function.symbol).irBlockBody {
+property.irSetValue(
irOr(
property.irGetValue(irGet(receiver)),
irGet(mask)
),
receiver = irGet(receiver)
)
}
| 7
|
Kotlin
|
1
| 18
|
79f120edaba6abf8c14c23ad70aea01992750830
| 2,469
|
rui
|
Apache License 2.0
|
data/coverart/src/main/java/ly/david/data/coverart/BuildCoverArtUrl.kt
|
lydavid
| 458,021,427
| false
| null |
package ly.david.data.coverart
/**
* Builds a fully qualified cover art url from [coverArtPath].
*
* @param thumbnail Determines whether to build url for smaller thumbnail image or not.
*/
fun buildCoverArtUrl(
coverArtPath: String,
thumbnail: Boolean = true
): String {
return if (coverArtPath.isEmpty()) {
""
} else {
"${COVER_ART_ARCHIVE_BASE_URL}release/$coverArtPath" + if (thumbnail) SMALL_SUFFIX else LARGE_SUFFIX
}
}
| 36
|
Kotlin
|
0
| 3
|
d8dd6b9ef7d2d12087b8a0d2ca9b4968d5fb11d9
| 466
|
MusicSearch
|
Apache License 2.0
|
src/main/kotlin/com/geogrind/geogrindbackend/services/sessions/SessionService.kt
|
GeoGrind
| 703,185,030
| false
|
{"Kotlin": 275271, "Shell": 2624, "HTML": 1687, "Dockerfile": 488}
|
package com.geogrind.geogrindbackend.services.sessions
import com.geogrind.geogrindbackend.dto.session.CreateSessionDto
import com.geogrind.geogrindbackend.dto.session.DeleteSessionByIdDto
import com.geogrind.geogrindbackend.dto.session.GetSessionByIdDto
import com.geogrind.geogrindbackend.dto.session.UpdateSessionByIdDto
import com.geogrind.geogrindbackend.models.sessions.Sessions
import com.geogrind.geogrindbackend.models.user_account.UserAccount
import jakarta.servlet.http.Cookie
import jakarta.validation.Valid
import org.springframework.stereotype.Service
@Service
interface SessionService {
suspend fun getAllSessions(): List<Sessions>
suspend fun getSessionById(@Valid requestDto: GetSessionByIdDto): Sessions
suspend fun createSession(@Valid requestDto: CreateSessionDto): Pair<Sessions, Cookie>
suspend fun updateSessionById(@Valid requestDto: UpdateSessionByIdDto): Pair<Sessions, Cookie>
fun deleteSessionById(@Valid requestDto: DeleteSessionByIdDto) : Cookie
// suspend fun handleScheduledSessionDeletion()
}
| 14
|
Kotlin
|
0
| 2
|
c0387735b3795aff0bd7e406117cccb03baecc8c
| 1,050
|
GeoGrind-Backend
|
Apache License 2.0
|
korge-core/src/korlibs/kgl/KmlBufferExt.kt
|
korlibs
| 80,095,683
| false
|
{"Kotlin": 3929805, "C++": 20878, "HTML": 3853, "Swift": 1371, "JavaScript": 328, "Shell": 254, "CMake": 202, "Batchfile": 41, "CSS": 33}
|
package korlibs.kgl
import korlibs.memory.*
fun Buffer.toAsciiString(): String {
var out = ""
for (n in 0 until size) {
val b = getInt8(n)
if (b == 0.toByte()) break
out += b.toInt().toChar()
}
return out
}
fun Buffer.putAsciiString(str: String): Buffer {
var n = 0
for (c in str) {
if (size >= n) setInt8(n++, c.code)
}
if (size >= n) setInt8(n++, 0)
return this
}
fun <T> IntArray.toTempBuffer(callback: (Buffer) -> T): T {
return BufferTemp(this.size) { buffer: Buffer ->
val ints = buffer.i32
for (n in this.indices) ints[n] = this[n]
callback(buffer)
}
}
| 461
|
Kotlin
|
120
| 2,394
|
0ca8644eb43c2ea8148dcd94d5c2a063466b0079
| 589
|
korge
|
Apache License 2.0
|
spring-funk-base/src/test/kotlin/com/github/wakingrufus/funk/TestIntegrationTest.kt
|
wakingrufus
| 787,456,746
| false
|
{"Kotlin": 99118}
|
package com.github.wakingrufus.funk
import org.assertj.core.api.Assertions.assertThat
import org.junit.jupiter.api.Test
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.boot.test.context.SpringBootTest
@SpringBootTest(classes = [TestApplication::class])
class TestIntegrationTest {
@Autowired
val stringbean: String? = null
@Autowired
val bean: String? = null
@Test
fun test() {
assertThat(stringbean).isEqualTo("1")
assertThat(bean).isEqualTo("2")
}
}
| 4
|
Kotlin
|
5
| 43
|
ef23568fe198df7e05a979d1cc7f4eaeb7767283
| 541
|
spring-funk
|
Apache License 2.0
|
spring-funk-base/src/test/kotlin/com/github/wakingrufus/funk/TestIntegrationTest.kt
|
wakingrufus
| 787,456,746
| false
|
{"Kotlin": 99118}
|
package com.github.wakingrufus.funk
import org.assertj.core.api.Assertions.assertThat
import org.junit.jupiter.api.Test
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.boot.test.context.SpringBootTest
@SpringBootTest(classes = [TestApplication::class])
class TestIntegrationTest {
@Autowired
val stringbean: String? = null
@Autowired
val bean: String? = null
@Test
fun test() {
assertThat(stringbean).isEqualTo("1")
assertThat(bean).isEqualTo("2")
}
}
| 4
|
Kotlin
|
5
| 43
|
ef23568fe198df7e05a979d1cc7f4eaeb7767283
| 541
|
spring-funk
|
Apache License 2.0
|
Application/buildSrc/src/main/java/LifeCycle.kt
|
devrath
| 570,594,617
| false
|
{"Kotlin": 238294}
|
object LifeCycle {
private const val lifecycleExtensionsVersion = "2.2.0"
const val lifecycleExtensions = "androidx.lifecycle:lifecycle-extensions:$lifecycleExtensionsVersion"
private const val lifecycleLiveDataVersion = "2.5.1"
const val lifecycleLiveData = "androidx.lifecycle:lifecycle-livedata-ktx:$lifecycleLiveDataVersion"
private const val lifecycleRuntimeKtxVersion = ":2.4.0"
const val lifecycleRuntimeKtx = "androidx.lifecycle:lifecycle-runtime-ktx$lifecycleRuntimeKtxVersion"
}
| 0
|
Kotlin
|
3
| 6
|
17d03b535e2ced992b97cc1e3a6d40c5393afded
| 514
|
Distance-Tracker
|
Apache License 2.0
|
libraries/design/src/main/java/com/fappslab/rickandmortygraphql/libraries/design/dsprogress/DsProgress.kt
|
F4bioo
| 585,168,438
| false
| null |
package com.fappslab.rickandmortygraphql.libraries.design.dsprogress
import android.app.AlertDialog
import android.app.Dialog
import android.graphics.Color
import android.graphics.drawable.ColorDrawable
import android.os.Bundle
import android.view.View
import androidx.core.view.isVisible
import androidx.fragment.app.DialogFragment
import com.fappslab.rickandmortygraphql.libraries.arch.viewbinding.viewBinding
import com.fappslab.rickandmortygraphql.libraries.design.R
import com.fappslab.rickandmortygraphql.libraries.design.databinding.LayoutDsprogressBinding
class DsProgress : DialogFragment(R.layout.layout_dsprogress) {
private val binding: LayoutDsprogressBinding by viewBinding()
var buttonCancel: () -> Unit? = {}
var shouldShowButtonCancel: Boolean = true
var shouldShowMessage: Boolean = true
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
setupCancelButton()
setupMessage()
setupDialog(view)
}
private fun setupDialog(view: View): Dialog {
AlertDialog.Builder(view.context).run {
setView(view)
val builder = create()
builder.window?.setBackgroundDrawable(ColorDrawable(Color.TRANSPARENT))
return builder
}
}
override fun onResume() {
isCancelable = false
super.onResume()
}
private fun setupCancelButton() {
binding.dsButtonCancel.apply {
isVisible = shouldShowButtonCancel
}.setOnClickListener {
buttonCancel.invoke()
dismiss()
}
}
private fun setupMessage() {
binding.dsTextLoading.isVisible = shouldShowMessage
}
}
| 0
|
Kotlin
|
0
| 0
|
b2a46bb919d7159c8417832a731798fdb9d159e9
| 1,747
|
RickAndMorty-GraphQL
|
MIT License
|
app/src/main/java/com/example/androiddevchallenge/CitiesActivity.kt
|
poppito
| 349,556,639
| false
| null |
/*
* Copyright 2021 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.example.androiddevchallenge
import android.os.Bundle
import androidx.activity.compose.setContent
import androidx.appcompat.app.AppCompatActivity
import androidx.compose.animation.core.FastOutLinearInEasing
import androidx.compose.animation.core.LinearEasing
import androidx.compose.animation.core.RepeatMode
import androidx.compose.animation.core.animateFloat
import androidx.compose.animation.core.infiniteRepeatable
import androidx.compose.animation.core.rememberInfiniteTransition
import androidx.compose.animation.core.tween
import androidx.compose.foundation.ExperimentalFoundationApi
import androidx.compose.foundation.Image
import androidx.compose.foundation.background
import androidx.compose.foundation.clickable
import androidx.compose.foundation.isSystemInDarkTheme
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
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.offset
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.lazy.GridCells
import androidx.compose.foundation.lazy.LazyRow
import androidx.compose.foundation.lazy.LazyVerticalGrid
import androidx.compose.material.MaterialTheme
import androidx.compose.material.Surface
import androidx.compose.material.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.MutableState
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.rotate
import androidx.compose.ui.graphics.ColorFilter
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.text.TextStyle
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.compose.ui.zIndex
import com.example.androiddevchallenge.model.Models
import com.example.androiddevchallenge.model.WeatherEvent
import com.example.androiddevchallenge.model.cityItems
import com.example.androiddevchallenge.ui.theme.MyTheme
import com.example.androiddevchallenge.ui.theme.bodyFont
import com.example.androiddevchallenge.ui.theme.darkTransparent
import com.example.androiddevchallenge.ui.theme.headerFont
import com.example.androiddevchallenge.ui.theme.italicFont
import com.example.androiddevchallenge.ui.theme.lightTransparent
import extensions.capitalCase
import extensions.getForecastFromWeatherEvents
import extensions.toFahrenheit
@ExperimentalFoundationApi
class CitiesActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContent {
MyTheme {
AddLayoutElements(data = cityItems)
}
}
}
}
@ExperimentalFoundationApi
@Composable
fun AddLayoutElements(data: List<Models.CityItem>) {
Surface(color = MaterialTheme.colors.background) {
val currentCity = remember { mutableStateOf(-1) }
if (currentCity.value == -1) {
ShowCities(currentCity, data = data)
} else {
CityWeatherDetail(data = data[currentCity.value], currentCity)
}
}
}
@ExperimentalFoundationApi
@Composable
fun ShowCities(
currentCity: MutableState<Int>,
data: List<Models.CityItem>
) {
Column(
modifier = Modifier
.fillMaxSize()
.padding(start = 16.dp, end = 16.dp),
horizontalAlignment = Alignment.CenterHorizontally
) {
Cities(data = data, currentCity = currentCity)
}
}
@ExperimentalFoundationApi
@Composable
private fun Cities(
data: List<Models.CityItem>,
currentCity: MutableState<Int>
) {
LazyVerticalGrid(
modifier = Modifier
.fillMaxWidth(),
cells = GridCells.Adaptive(minSize = 140.dp)
) {
// items
items(data.size) { index ->
City(city = data[index], currentCity = currentCity, index = index)
}
}
}
@Composable
private fun City(city: Models.CityItem, currentCity: MutableState<Int>, index: Int) {
Column(
Modifier
.padding(16.dp)
.fillMaxSize()
.fillMaxHeight()
.clickable { currentCity.value = index },
horizontalAlignment = Alignment.CenterHorizontally,
verticalArrangement = Arrangement.Center
) {
Image(
painter = painterResource(id = city.img),
contentDescription = stringResource(id = R.string.cd_city_img, city.name),
contentScale = ContentScale.Fit,
modifier = Modifier
.fillMaxWidth(0.8f)
.height(150.dp)
.zIndex(1f)
)
Text(
text = city.name.capitalCase(),
modifier = Modifier
.padding(top = 8.dp)
.fillMaxWidth()
.zIndex(1f),
textAlign = TextAlign.Center,
style = MaterialTheme.typography.h1
)
Text(
text = city.country.capitalCase(),
modifier = Modifier
.padding(top = 8.dp)
.fillMaxWidth()
.zIndex(1f),
textAlign = TextAlign.Center,
style = MaterialTheme.typography.h2
)
}
}
@Composable
private fun ShowWeatherAnimation(
primaryWeatherEvent: WeatherEvent
) {
when (primaryWeatherEvent) {
is WeatherEvent.Sun -> {
if (primaryWeatherEvent.level > 1) {
ShowSun()
} else {
ShowOvercast()
}
}
is WeatherEvent.Rain -> {
ShowRain()
}
is WeatherEvent.Snow -> {
ShowSnow()
}
}
}
@Composable
fun CityWeatherDetail(data: Models.CityItem, currentCity: MutableState<Int>) {
Box(
modifier = Modifier
.fillMaxSize()
) {
DrawBackground(weatherEvent = data.primaryWeatherEvent)
Image(
painter = painterResource(id = R.drawable.ic_close),
contentDescription = stringResource(
id = R.string.txt_close
),
modifier = Modifier
.padding(start = 16.dp, top = 16.dp)
.clickable { currentCity.value = -1 }
)
Column(
modifier = Modifier.fillMaxSize(),
horizontalAlignment = Alignment.CenterHorizontally,
verticalArrangement = Arrangement.SpaceEvenly
) {
Column(
modifier = Modifier.fillMaxHeight(0.15f),
horizontalAlignment = Alignment.CenterHorizontally
) {
ShowWeatherAnimation(primaryWeatherEvent = data.primaryWeatherEvent)
}
WeatherText(data = data)
Radar(data = data)
SmallPreviewItems(data = data.weatherPreviews)
}
}
}
@Composable
private fun DrawBackground(weatherEvent: WeatherEvent) {
when (weatherEvent) {
is WeatherEvent.Sun -> {
if (weatherEvent.level > 1) {
Image(
painterResource(id = R.drawable.bg_sunny),
contentDescription = "",
modifier = Modifier.fillMaxHeight(),
contentScale = ContentScale.Crop
)
} else {
Image(
painterResource(id = R.drawable.bg_rain),
contentDescription = "",
modifier = Modifier.fillMaxHeight(),
contentScale = ContentScale.Crop
)
}
}
is WeatherEvent.Rain -> {
Image(
painterResource(id = R.drawable.bg_rain),
contentDescription = "",
modifier = Modifier.fillMaxHeight(),
contentScale = ContentScale.Crop
)
}
is WeatherEvent.Snow -> {
Image(
painterResource(id = R.drawable.bg_snow),
contentDescription = "",
modifier = Modifier.fillMaxHeight(),
contentScale = ContentScale.Crop
)
}
}
Box(
modifier = Modifier
.fillMaxSize()
.background(color = if (isSystemInDarkTheme()) darkTransparent else lightTransparent)
)
}
@Composable
private fun ShowOvercast() {
Box {
ShowSun()
Cloud()
}
}
@Composable
private fun Radar(data: Models.CityItem) {
// generate random translationX
val offsetX = (0..10).random()
// rotate fully then restart
val rotateTransition = rememberInfiniteTransition()
val rotation = rotateTransition.animateFloat(
initialValue = 0f, targetValue = 360f,
animationSpec = infiniteRepeatable(
animation = tween(3000, easing = FastOutLinearInEasing),
repeatMode = RepeatMode.Restart
)
)
val offset = rememberInfiniteTransition()
val offsetting = offset.animateFloat(
initialValue = 0f, targetValue = offsetX.toFloat(),
animationSpec =
infiniteRepeatable(
animation = tween(3000, easing = FastOutLinearInEasing),
repeatMode = RepeatMode.Restart
)
)
Column(
modifier = Modifier
.fillMaxWidth()
.fillMaxHeight(0.5f),
horizontalAlignment = Alignment.CenterHorizontally
) {
Box() {
Image(
painterResource(id = data.map),
contentDescription = stringResource(id = R.string.cd_map),
modifier = Modifier.fillMaxSize()
)
Image(
painterResource(id = if (isSystemInDarkTheme()) R.drawable.ic_bg_light_36 else R.drawable.bg_dark_36),
contentDescription = stringResource(id = R.string.cd_map),
modifier = Modifier.fillMaxSize()
)
Image(
painterResource(id = data.radar),
modifier = Modifier
.size(140.dp)
.offset(x = 140.dp, y = 50.dp)
.padding(start = offsetting.value.dp, end = offsetting.value.dp)
.rotate(rotation.value),
contentDescription = stringResource(id = R.string.cd_wind),
colorFilter = ColorFilter.tint(
color = MaterialTheme.colors.background
)
)
}
}
}
@Composable
private fun WeatherText(data: Models.CityItem) {
Text(
text = stringResource(
id = R.string.txt_degrees, data.foreCast, data.foreCast.toFahrenheit()
),
textAlign = TextAlign.Center,
style = TextStyle(
color = MaterialTheme.colors.onBackground,
fontSize = 24.sp,
fontFamily = headerFont
),
modifier = Modifier
.padding(start = 16.dp, end = 16.dp)
.fillMaxWidth()
)
Column(
horizontalAlignment = Alignment.CenterHorizontally,
verticalArrangement = Arrangement.Center,
modifier = Modifier.fillMaxWidth()
) {
HumidityAndWind(humidity = data.humidity, wind = data.wind)
}
Text(
text = data.name,
style = TextStyle(
color = MaterialTheme.colors.onBackground,
fontSize = 20.sp,
fontFamily = headerFont
),
textAlign = TextAlign.Center,
modifier = Modifier
.padding(start = 16.dp, end = 16.dp)
.fillMaxWidth()
)
Text(
text = data.country,
style = TextStyle(
color = MaterialTheme.colors.onBackground,
fontSize = 18.sp,
fontFamily = bodyFont
),
textAlign = TextAlign.Center,
modifier = Modifier
.padding(start = 16.dp, end = 16.dp)
.fillMaxWidth()
)
Text(
text = data.getForecastFromWeatherEvents(),
style = TextStyle(
color = MaterialTheme.colors.onBackground,
fontSize = 16.sp,
fontFamily = italicFont
),
textAlign = TextAlign.Center,
modifier = Modifier
.padding(start = 16.dp, bottom = 32.dp, end = 16.dp)
.fillMaxWidth()
)
}
@Composable
private fun HumidityAndWind(humidity: Int, wind: Int) {
Row(
modifier = Modifier
.padding(top = 4.dp, bottom = 4.dp)
.fillMaxWidth(),
horizontalArrangement = Arrangement.Center
) {
Image(
painterResource(id = R.drawable.ic_humidity_small),
contentDescription = stringResource(
id = R.string.cd_humidity
),
colorFilter = ColorFilter.tint(
color = MaterialTheme.colors.onBackground
),
modifier = Modifier
.padding(start = 16.dp, end = 16.dp)
.size(24.dp)
)
Text(
stringResource(id = R.string.txt_percentage, humidity),
modifier = Modifier.padding(end = 16.dp),
textAlign = TextAlign.Start
)
}
Row(
modifier = Modifier
.padding(top = 4.dp, bottom = 4.dp)
.fillMaxWidth(),
horizontalArrangement = Arrangement.Center
) {
Image(
painterResource(id = R.drawable.ic_wind_small),
contentDescription = stringResource(
id = R.string.cd_wind
),
colorFilter = ColorFilter.tint(color = MaterialTheme.colors.onBackground),
modifier = Modifier
.padding(start = 16.dp, end = 16.dp)
.size(24.dp)
)
Text(
stringResource(id = R.string.txt_kph, wind),
modifier = Modifier.padding(end = 16.dp),
textAlign = TextAlign.Start
)
}
}
@Composable
private fun ShowSun() {
val rotateTransition = rememberInfiniteTransition()
val rotation = rotateTransition.animateFloat(
initialValue = 0f, targetValue = 360f,
animationSpec = infiniteRepeatable(
animation = tween(3000, easing = FastOutLinearInEasing),
repeatMode = RepeatMode.Reverse
)
)
Image(
painter = painterResource(id = R.drawable.sun),
contentDescription = "",
modifier = Modifier
.padding(16.dp)
.rotate(rotation.value)
)
}
@Composable
private fun ShowSnow() {
val infiniteTransition = rememberInfiniteTransition()
val tx = infiniteTransition.animateFloat(
initialValue = 0f,
targetValue = 150f,
animationSpec = infiniteRepeatable(
animation = tween(5000, easing = FastOutLinearInEasing),
repeatMode = RepeatMode.Reverse
)
)
val rotate = infiniteTransition.animateFloat(
initialValue = 0f,
targetValue = 360f,
animationSpec = infiniteRepeatable(
animation = tween(3000, easing = LinearEasing),
repeatMode = RepeatMode.Reverse
)
)
Row(horizontalArrangement = Arrangement.Center) {
Image(
painter = painterResource(id = R.drawable.snowflake2),
contentDescription = "",
modifier = Modifier
.padding(top = 16.dp, end = 16.dp, bottom = 48.dp)
.offset(x = 0.dp, y = (tx.value + 3).dp)
.rotate(rotate.value),
colorFilter = ColorFilter.tint(color = MaterialTheme.colors.onBackground)
)
Image(
painter = painterResource(id = R.drawable.snowflake3),
contentDescription = "",
modifier = Modifier
.padding(top = 16.dp, end = 16.dp, bottom = 48.dp)
.offset(x = -3.dp, y = tx.value.dp)
.rotate(rotate.value),
colorFilter = ColorFilter.tint(color = MaterialTheme.colors.onBackground)
)
Image(
painter = painterResource(id = R.drawable.snowflake4),
contentDescription = "",
modifier = Modifier
.padding(top = 16.dp, end = 16.dp, bottom = 48.dp)
.offset(x = 2.dp, y = (tx.value + 5).dp)
.rotate(rotate.value),
colorFilter = ColorFilter.tint(color = MaterialTheme.colors.onBackground)
)
Image(
painter = painterResource(id = R.drawable.snowflake1),
contentDescription = "",
modifier = Modifier
.padding(top = 16.dp, end = 16.dp, bottom = 48.dp)
.offset(x = -2.dp, y = (tx.value + 1).dp)
.rotate(rotate.value),
colorFilter = ColorFilter.tint(color = MaterialTheme.colors.onBackground)
)
Image(
painter = painterResource(id = R.drawable.snowflake2),
contentDescription = "",
modifier = Modifier
.padding(top = 16.dp, end = 16.dp, bottom = 48.dp)
.offset(x = 0.dp, y = (tx.value + 3).dp)
.rotate(rotate.value),
colorFilter = ColorFilter.tint(color = MaterialTheme.colors.onBackground)
)
Image(
painter = painterResource(id = R.drawable.snowflake3),
contentDescription = "",
modifier = Modifier
.padding(top = 16.dp, end = 16.dp, bottom = 48.dp)
.offset(x = -1.dp, y = tx.value.dp)
.rotate(rotate.value),
colorFilter = ColorFilter.tint(color = MaterialTheme.colors.onBackground)
)
}
}
@Composable
private fun ShowRain() {
Cloud()
Rain()
}
@Composable
private fun Cloud() {
Image(
painter = painterResource(id = R.drawable.cloud),
contentDescription = stringResource(id = R.string.cd_overcast),
modifier = Modifier
.padding(top = 24.dp),
colorFilter = ColorFilter.tint(color = MaterialTheme.colors.onBackground)
)
}
@Composable
private fun Rain() {
val infiniteTransition = rememberInfiniteTransition()
val tx = infiniteTransition.animateFloat(
initialValue = 0f,
targetValue = 100f,
animationSpec = infiniteRepeatable(
animation = tween(3000, easing = FastOutLinearInEasing),
repeatMode = RepeatMode.Restart
)
)
Image(
painter = painterResource(id = R.drawable.rain),
contentDescription = stringResource(id = R.string.cd_rainy),
modifier = Modifier
.offset(x = 0.dp, y = tx.value.dp)
.padding(end = 16.dp),
colorFilter = ColorFilter.tint(color = MaterialTheme.colors.onBackground)
)
}
@Composable
fun SmallPreviewItems(data: List<Models.WeatherPreviewItem>) {
LazyRow(
modifier = Modifier
.fillMaxSize(),
verticalAlignment = Alignment.Bottom
) {
// items
items(data.size) { index ->
ShowSmallPreviewItem(
day = stringResource(data[index].day),
temperature = data[index].temperature,
weatherEvent = data[index].weather,
humidity = data[index].humidity,
wind = data[index].wind
)
}
}
}
@Composable
fun ShowSmallPreviewItem(
day: String,
temperature: Int,
weatherEvent: String,
humidity: Int,
wind: Int
) {
val rotation = rememberInfiniteTransition()
val rotate = rotation.animateFloat(
initialValue = 0f,
targetValue = 360f,
animationSpec = infiniteRepeatable(
animation = tween(3000, easing = LinearEasing),
repeatMode = RepeatMode.Reverse
)
)
Column(
modifier = Modifier
.width(180.dp)
.height(250.dp),
horizontalAlignment = Alignment.CenterHorizontally,
verticalArrangement = Arrangement.Center
) {
when (weatherEvent) {
Constants.SNOWY -> {
Image(
painterResource(id = R.drawable.snow_small),
contentDescription = stringResource(id = R.string.cd_snowy),
modifier = Modifier
.size(50.dp)
.rotate(rotate.value),
colorFilter = ColorFilter.tint(color = MaterialTheme.colors.onBackground)
)
}
Constants.RAINY -> {
Image(
painterResource(id = R.drawable.rain_small),
contentDescription = stringResource(id = R.string.cd_snowy),
modifier = Modifier.size(50.dp),
colorFilter = ColorFilter.tint(color = MaterialTheme.colors.onBackground)
)
}
Constants.SUNNY -> {
Image(
painterResource(id = R.drawable.sun_small),
contentDescription = stringResource(id = R.string.cd_snowy),
modifier = Modifier
.size(50.dp)
.rotate(rotate.value),
colorFilter = ColorFilter.tint(color = MaterialTheme.colors.onBackground)
)
}
Constants.OVERCAST -> {
Image(
painterResource(id = R.drawable.overcast_small),
contentDescription = stringResource(id = R.string.cd_snowy),
modifier = Modifier
.size(50.dp),
colorFilter = ColorFilter.tint(color = MaterialTheme.colors.onBackground)
)
}
}
Text(
text = day,
style = TextStyle(
color = MaterialTheme.colors.onBackground,
fontSize = 16.sp,
fontFamily = bodyFont
),
textAlign = TextAlign.Center,
modifier = Modifier
.padding(start = 16.dp, end = 16.dp)
)
Text(
text = stringResource(
id = R.string.txt_degrees, temperature, temperature.toFahrenheit()
),
textAlign = TextAlign.Center,
style = TextStyle(
color = MaterialTheme.colors.onBackground,
fontSize = 14.sp,
fontFamily = italicFont
),
modifier = Modifier
.padding(start = 16.dp, end = 16.dp)
)
HumidityAndWind(humidity = humidity, wind = wind)
}
}
@ExperimentalFoundationApi
@Preview("Light Theme", widthDp = 360, heightDp = 640)
@Composable
fun LightPreview() {
MyTheme {
AddLayoutElements(data = cityItems)
}
}
@ExperimentalFoundationApi
@Preview("Dark Theme", widthDp = 360, heightDp = 640)
@Composable
fun DarkPreview() {
MyTheme(darkTheme = true) {
AddLayoutElements(data = cityItems)
}
}
| 0
|
Kotlin
|
0
| 0
|
c4e3feea1587306bd155fc569cdf17a4af82d24f
| 24,140
|
SprocketWeather
|
Apache License 2.0
|
tl/src/main/kotlin/com/github/badoualy/telegram/tl/api/TLInputStickerSetThumb.kt
|
Miha-x64
| 436,587,061
| true
|
{"Kotlin": 3919807, "Java": 75352}
|
package com.github.badoualy.telegram.tl.api
import com.github.badoualy.telegram.tl.TLObjectUtils.SIZE_CONSTRUCTOR_ID
import com.github.badoualy.telegram.tl.TLObjectUtils.SIZE_INT32
import com.github.badoualy.telegram.tl.serialization.TLDeserializer
import com.github.badoualy.telegram.tl.serialization.TLSerializer
import java.io.IOException
/**
* inputStickerSetThumb#9d84f3db
*
* @author <NAME> <EMAIL>
* @see <a href="http://github.com/badoualy/kotlogram">http://github.com/badoualy/kotlogram</a>
*/
class TLInputStickerSetThumb() : TLAbsInputFileLocation() {
var stickerset: TLAbsInputStickerSet = TLInputStickerSetEmpty()
var thumbVersion: Int = 0
private val _constructor: String = "inputStickerSetThumb#9d84f3db"
override val constructorId: Int = CONSTRUCTOR_ID
constructor(stickerset: TLAbsInputStickerSet, thumbVersion: Int) : this() {
this.stickerset = stickerset
this.thumbVersion = thumbVersion
}
@Throws(IOException::class)
override fun serializeBody(tlSerializer: TLSerializer) = with (tlSerializer) {
writeTLObject(stickerset)
writeInt(thumbVersion)
}
@Throws(IOException::class)
override fun deserializeBody(tlDeserializer: TLDeserializer) = with (tlDeserializer) {
stickerset = readTLObject<TLAbsInputStickerSet>()
thumbVersion = readInt()
}
override fun computeSerializedSize(): Int {
var size = SIZE_CONSTRUCTOR_ID
size += stickerset.computeSerializedSize()
size += SIZE_INT32
return size
}
override fun toString() = _constructor
override fun equals(other: Any?): Boolean {
if (other !is TLInputStickerSetThumb) return false
if (other === this) return true
return stickerset == other.stickerset
&& thumbVersion == other.thumbVersion
}
companion object {
const val CONSTRUCTOR_ID: Int = 0x9d84f3db.toInt()
}
}
| 1
|
Kotlin
|
2
| 3
|
1a8963dce921c1e9ef05b9d1e56d8fbcb1ea1c4b
| 1,952
|
kotlogram-resurrected
|
MIT License
|
src/main/kotlin/io/github/natanfudge/genericutils/network/PacketType.kt
|
natanfudge
| 667,527,587
| false
|
{"Kotlin": 78160, "Java": 1256}
|
package io.github.natanfudge.genericutils.network
import io.github.natanfudge.genericutils.csId
import io.github.natanfudge.genericutils.CommonInit
import kotlinx.serialization.KSerializer
import kotlinx.serialization.minecraft.Buf
import kotlinx.serialization.serializer
import net.fabricmc.fabric.api.networking.v1.PacketByteBufs
import net.fabricmc.fabric.api.networking.v1.PacketSender
import net.fabricmc.fabric.api.networking.v1.ServerPlayNetworking
import net.minecraft.server.MinecraftServer
import net.minecraft.server.network.ServerPlayNetworkHandler
import net.minecraft.server.network.ServerPlayerEntity
import net.minecraft.util.Identifier
class C2SPacketType<T>(val id: Identifier, val serializer: KSerializer<T>, val format: Buf) {
context(CommonInit)
fun register(receiveOnServer: (server: MinecraftServer, player: ServerPlayerEntity, handler: ServerPlayNetworkHandler, content: T, responseSender: PacketSender) -> Unit) {
ServerPlayNetworking.registerGlobalReceiver(id) { server, player, handler, buf, responseSender ->
val content = format.decodeFromByteBuf(serializer, buf)
server.execute {
receiveOnServer(server, player, handler, content, responseSender)
}
}
}
}
inline fun <reified T> c2sPacket(path: String, format: Buf = Buf) = C2SPacketType<T>(csId(path), format.serializersModule.serializer(), format)
class S2CPacketType<T>(val id: Identifier, val serializer: KSerializer<T>, val format: Buf) {
fun send(value: T, player: ServerPlayerEntity) {
ServerPlayNetworking.send(player, id, PacketByteBufs.create().also { format.encodeToByteBuf(serializer, value, it) })
}
}
inline fun <reified T> s2cPacket(path: String, format: Buf = Buf) = S2CPacketType<T>(csId(path), format.serializersModule.serializer(), format)
| 0
|
Kotlin
|
0
| 0
|
70b53e8980d8794e3b66c51e4a92b386d1ce05d4
| 1,839
|
CraftingStation-Fabric
|
MIT License
|
plot-base-portable/src/commonMain/kotlin/jetbrains/datalore/plot/base/coord/Coords.kt
|
JetBrains
| 176,771,727
| false
| null |
/*
* Copyright (c) 2020. JetBrains s.r.o.
* Use of this source code is governed by the MIT license that can be found in the LICENSE file.
*/
package jetbrains.datalore.plot.base.coord
import jetbrains.datalore.base.geometry.DoubleRectangle
import jetbrains.datalore.base.geometry.DoubleVector
import jetbrains.datalore.base.interval.DoubleSpan
import jetbrains.datalore.base.spatial.projections.identity
import jetbrains.datalore.plot.base.CoordinateSystem
object Coords {
fun create(
coordMapper: CoordinatesMapper,
): CoordinateSystem {
return DefaultCoordinateSystem(coordMapper)
}
object DemoAndTest {
fun create(
xDomain: DoubleSpan,
yDomain: DoubleSpan,
clientSize: DoubleVector
): CoordinateSystem {
val mapper = CoordinatesMapper.create(
adjustedDomain = DoubleRectangle.hvRange(xDomain, yDomain),
clientSize = clientSize,
projection = identity(),
flipAxis = false
)
return DefaultCoordinateSystem(mapper)
}
}
}
| 97
|
Kotlin
|
47
| 889
|
c5c66ceddc839bec79b041c06677a6ad5f54e416
| 1,123
|
lets-plot
|
MIT License
|
app/src/main/java/com/kodedynamic/recipeoracle/apis/data/mappers/CategoriesMapper.kt
|
kushal2011
| 836,607,411
| false
|
{"Kotlin": 238994}
|
package com.kodedynamic.recipeoracle.apis.data.mappers
import com.kodedynamic.recipeoracle.apis.data.models.CategoriesDto
import com.kodedynamic.recipeoracle.apis.domain.models.CategoriesModel
import com.kodedynamic.recipeoracle.common.Mapper
import javax.inject.Inject
class CategoriesMapper @Inject constructor(
private val cuisineMapper: CuisineMapper
) : Mapper<CategoriesDto, CategoriesModel> {
override fun map(param: CategoriesDto): CategoriesModel {
with(param) {
return CategoriesModel(
cuisines = cuisines?.map { cuisineMapper.map(it) } ?: emptyList()
)
}
}
}
| 0
|
Kotlin
|
0
| 0
|
98b4bdcd58d59fae9a8d3103b831cbecddacd886
| 640
|
Recipe-Oracle
|
MIT License
|
app/src/main/java/com/rosen/lumina/custom/QuantityButtons.kt
|
DerekWasswa
| 731,987,581
| false
|
{"Kotlin": 40907}
|
package com.rosen.lumina.custom
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Add
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
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.res.painterResource
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import com.rosen.lumina.R
import com.rosen.lumina.ui.theme.PaleGray1
import com.rosen.lumina.ui.theme.PaleGray2
import com.rosen.lumina.ui.theme.Peach
import com.rosen.lumina.ui.theme.White
@Composable
fun QuantityButtons(quantity: Int, onQuantityChange: (Int) -> Unit) {
Box(
modifier = Modifier
.background(PaleGray1, shape = RoundedCornerShape(16.dp))
) {
Row(
modifier = Modifier.padding(8.dp),
verticalAlignment = Alignment.CenterVertically,
horizontalArrangement = Arrangement.spacedBy(12.dp)
) {
// Minus Button
Box(
modifier = Modifier
.background(PaleGray2, shape = RoundedCornerShape(12.dp))
) {
IconButton(
modifier = Modifier.size(24.dp),
onClick = { onQuantityChange(quantity - 1) },
enabled = quantity > 1
) {
Icon(painter = painterResource(id = R.drawable.ic_minus), contentDescription = null, tint = Peach)
}
}
// Quantity Text
Text(
text = quantity.toString(),
style = MaterialTheme.typography.bodyLarge.copy(
fontWeight = FontWeight.Bold,
color = White,
fontSize = 18.sp
),
)
// Plus Button
Box(
modifier = Modifier
.background(PaleGray2, shape = RoundedCornerShape(12.dp))
) {
IconButton(
modifier = Modifier.size(24.dp),
onClick = { onQuantityChange(quantity + 1) }
) {
Icon(imageVector = Icons.Default.Add, contentDescription = null, tint = Peach)
}
}
}
}
}
| 0
|
Kotlin
|
0
| 0
|
6ffbfde17a3075c5131bc61baa14ecb89f4fe0d4
| 2,905
|
Lumina
|
Apache License 2.0
|
pillarbox-player/src/test/java/ch/srgssr/pillarbox/player/extension/PlayerCommandsTest.kt
|
SRGSSR
| 519,157,987
| false
|
{"Kotlin": 1473274, "Shell": 549}
|
/*
* Copyright (c) SRG SSR. All rights reserved.
* License information is available from the LICENSE file.
*/
package ch.srgssr.pillarbox.player.extension
import androidx.media3.common.Player
import androidx.media3.common.Player.Commands
import androidx.test.ext.junit.runners.AndroidJUnit4
import io.mockk.every
import io.mockk.mockk
import org.junit.runner.RunWith
import kotlin.test.Test
import kotlin.test.assertFalse
import kotlin.test.assertTrue
@RunWith(AndroidJUnit4::class)
class PlayerCommandsTest {
@Test
fun `can seek to next`() {
val player = mockk<Player> {
every { availableCommands } returnsMany listOf(
Commands.Builder().build(),
Commands.Builder().addAll(Player.COMMAND_STOP, Player.COMMAND_GET_TEXT).build(),
Commands.Builder().addAll(Player.COMMAND_STOP, Player.COMMAND_SEEK_TO_NEXT, Player.COMMAND_GET_TEXT).build()
)
}
assertFalse(player.availableCommands.canSeekToNext())
assertFalse(player.availableCommands.canSeekToNext())
assertTrue(player.availableCommands.canSeekToNext())
}
@Test
fun `can seek to previous`() {
val player = mockk<Player> {
every { availableCommands } returnsMany listOf(
Commands.Builder().build(),
Commands.Builder().addAll(Player.COMMAND_STOP, Player.COMMAND_GET_TEXT).build(),
Commands.Builder().addAll(Player.COMMAND_STOP, Player.COMMAND_SEEK_TO_PREVIOUS, Player.COMMAND_GET_TEXT).build()
)
}
assertFalse(player.availableCommands.canSeekToPrevious())
assertFalse(player.availableCommands.canSeekToPrevious())
assertTrue(player.availableCommands.canSeekToPrevious())
}
@Test
fun `can seek forward`() {
val player = mockk<Player> {
every { availableCommands } returnsMany listOf(
Commands.Builder().build(),
Commands.Builder().addAll(Player.COMMAND_STOP, Player.COMMAND_GET_TEXT).build(),
Commands.Builder().addAll(Player.COMMAND_STOP, Player.COMMAND_SEEK_FORWARD, Player.COMMAND_GET_TEXT).build()
)
}
assertFalse(player.availableCommands.canSeekForward())
assertFalse(player.availableCommands.canSeekForward())
assertTrue(player.availableCommands.canSeekForward())
}
@Test
fun `can seek back`() {
val player = mockk<Player> {
every { availableCommands } returnsMany listOf(
Commands.Builder().build(),
Commands.Builder().addAll(Player.COMMAND_STOP, Player.COMMAND_GET_TEXT).build(),
Commands.Builder().addAll(Player.COMMAND_STOP, Player.COMMAND_SEEK_BACK, Player.COMMAND_GET_TEXT).build()
)
}
assertFalse(player.availableCommands.canSeekBack())
assertFalse(player.availableCommands.canSeekBack())
assertTrue(player.availableCommands.canSeekBack())
}
@Test
fun `can seek`() {
val player = mockk<Player> {
every { availableCommands } returnsMany listOf(
Commands.Builder().build(),
Commands.Builder().addAll(Player.COMMAND_STOP, Player.COMMAND_GET_TEXT).build(),
Commands.Builder().addAll(Player.COMMAND_STOP, Player.COMMAND_SEEK_IN_CURRENT_MEDIA_ITEM, Player.COMMAND_GET_TEXT).build()
)
}
assertFalse(player.availableCommands.canSeek())
assertFalse(player.availableCommands.canSeek())
assertTrue(player.availableCommands.canSeek())
}
@Test
fun `can play pause`() {
val player = mockk<Player> {
every { availableCommands } returnsMany listOf(
Commands.Builder().build(),
Commands.Builder().addAll(Player.COMMAND_STOP, Player.COMMAND_GET_TEXT).build(),
Commands.Builder().addAll(Player.COMMAND_STOP, Player.COMMAND_PLAY_PAUSE, Player.COMMAND_GET_TEXT).build()
)
}
assertFalse(player.availableCommands.canPlayPause())
assertFalse(player.availableCommands.canPlayPause())
assertTrue(player.availableCommands.canPlayPause())
}
@Test
fun `can get tracks`() {
val player = mockk<Player> {
every { availableCommands } returnsMany listOf(
Commands.Builder().build(),
Commands.Builder().addAll(Player.COMMAND_STOP, Player.COMMAND_GET_TEXT).build(),
Commands.Builder().addAll(Player.COMMAND_STOP, Player.COMMAND_GET_TRACKS, Player.COMMAND_GET_TEXT).build()
)
}
assertFalse(player.availableCommands.canGetTracks())
assertFalse(player.availableCommands.canGetTracks())
assertTrue(player.availableCommands.canGetTracks())
}
@Test
fun `can set track selection parameters`() {
val player = mockk<Player> {
every { availableCommands } returnsMany listOf(
Commands.Builder().build(),
Commands.Builder().addAll(Player.COMMAND_STOP, Player.COMMAND_GET_TEXT).build(),
Commands.Builder().addAll(Player.COMMAND_STOP, Player.COMMAND_SET_TRACK_SELECTION_PARAMETERS, Player.COMMAND_GET_TEXT).build()
)
}
assertFalse(player.availableCommands.canSetTrackSelectionParameters())
assertFalse(player.availableCommands.canSetTrackSelectionParameters())
assertTrue(player.availableCommands.canSetTrackSelectionParameters())
}
@Test
fun `can speed and pitch`() {
val player = mockk<Player> {
every { availableCommands } returnsMany listOf(
Commands.Builder().build(),
Commands.Builder().addAll(Player.COMMAND_STOP, Player.COMMAND_GET_TEXT).build(),
Commands.Builder().addAll(Player.COMMAND_STOP, Player.COMMAND_SET_SPEED_AND_PITCH, Player.COMMAND_GET_TEXT).build()
)
}
assertFalse(player.availableCommands.canSpeedAndPitch())
assertFalse(player.availableCommands.canSpeedAndPitch())
assertTrue(player.availableCommands.canSpeedAndPitch())
}
}
| 23
|
Kotlin
|
1
| 13
|
b155c6d3f2da29b8e30555f13ecce64f28f82db2
| 6,196
|
pillarbox-android
|
MIT License
|
android/src/main/kotlin/abdurrahmankaraoglu/app/advanced_background_locator/provider/LocationUpdateListener.kt
|
AbdurrahmanKaraoglu
| 852,799,985
| false
|
{"Kotlin": 57383, "Dart": 28651, "Objective-C": 25219, "C++": 23965, "CMake": 19456, "Swift": 1823, "C": 1425, "HTML": 1218, "Ruby": 768, "Java": 516}
|
package abdurrahmankaraoglu.app.advanced_background_locator.provider
import java.util.HashMap
interface LocationUpdateListener {
fun onLocationUpdated(location: Map<*, *>?)
}
| 0
|
Kotlin
|
0
| 0
|
0707869fb5f9f1372b4b494764b6f632e819bc66
| 180
|
advanced_background_locator
|
MIT License
|
src/all/comicfury/src/eu/kanade/tachiyomi/extension/all/comicfury/ComicFury.kt
|
komikku-app
| 720,497,299
| false
|
{"Kotlin": 6775539, "JavaScript": 2160}
|
package eu.kanade.tachiyomi.extension.all.comicfury
import android.app.Application
import android.content.SharedPreferences
import androidx.preference.PreferenceScreen
import androidx.preference.SwitchPreferenceCompat
import eu.kanade.tachiyomi.lib.textinterceptor.TextInterceptor
import eu.kanade.tachiyomi.lib.textinterceptor.TextInterceptorHelper
import eu.kanade.tachiyomi.network.GET
import eu.kanade.tachiyomi.source.ConfigurableSource
import eu.kanade.tachiyomi.source.model.Filter
import eu.kanade.tachiyomi.source.model.FilterList
import eu.kanade.tachiyomi.source.model.MangasPage
import eu.kanade.tachiyomi.source.model.Page
import eu.kanade.tachiyomi.source.model.SChapter
import eu.kanade.tachiyomi.source.model.SManga
import eu.kanade.tachiyomi.source.online.HttpSource
import eu.kanade.tachiyomi.util.asJsoup
import okhttp3.HttpUrl
import okhttp3.HttpUrl.Companion.toHttpUrl
import okhttp3.Request
import okhttp3.Response
import org.jsoup.nodes.Element
import uy.kohesive.injekt.Injekt
import uy.kohesive.injekt.api.get
import java.text.SimpleDateFormat
import java.util.Locale
class ComicFury(
override val lang: String,
private val siteLang: String = lang, // override lang string used in MangaSearch
private val extraName: String = "",
) : HttpSource(), ConfigurableSource {
override val baseUrl: String = "https://comicfury.com"
override val name: String = "Comic Fury$extraName" // Used for No Text
override val supportsLatest: Boolean = true
override val client = super.client.newBuilder().addInterceptor(TextInterceptor()).build()
/**
* Archive is on a separate page from manga info
*/
override fun chapterListRequest(manga: SManga): Request =
GET("$baseUrl/read/${manga.url.substringAfter("?url=")}/archive")
/**
* Open Archive Url instead of the details page
* Helps with getting past the nfsw pages
*/
override fun getMangaUrl(manga: SManga): String {
return "$baseUrl/read/" + manga.url.substringAfter("?url=") + "/archive"
}
/**
* There are two different ways chapters are setup
* First Way if (true)
* Manga -> Chapter -> Comic -> Pages
* The Second Way if (false)
* Manga -> Comic -> Pages
*
* Importantly the Chapter And Comic Pages can be easy distinguished
* by the name of the list elements in this case archive-chapter/archive-comic
*
* For Manga that doesn't have "chapters" skip the loop. Including All Sub-Comics of Chapters
*
* Put the chapter name into scanlator so read can know what chapter it is.
*
* Chapter Number is handled as Chapter dot Comic. Ex. Chapter 6, Comic 4: chapter_number = 6.4
*
*/
private val archiveSelector = "a:has(div.archive-chapter)"
private val chapterSelector = "a:has(div.archive-comic)"
private val nextArchivePageSelector = "#scroll-content > .onsite-viewer-back-link + .archive-pages a"
private lateinit var currentPage: org.jsoup.nodes.Document
private fun Element.toSManga(): SChapter {
return SChapter.create().apply {
setUrlWithoutDomain(this@toSManga.attr("abs:href"))
name = this@toSManga.select(".archive-comic-title").text()
date_upload = this@toSManga.select(".archive-comic-date").text().toDate()
}
}
private fun collect(url: String): List<SChapter> {
return client.newCall(GET(url, headers)).execute().asJsoup()
.also { currentPage = it }
.select(chapterSelector)
.map { element -> element.toSManga() }
}
override fun chapterListParse(response: Response): List<SChapter> {
val jsp = response.asJsoup()
return if (jsp.selectFirst(archiveSelector) != null) {
val chapters = mutableListOf<SChapter>()
jsp.select(archiveSelector).eachAttr("abs:href").map { url ->
chapters.addAll(collect(url))
currentPage.select(nextArchivePageSelector).eachAttr("abs:href")
.mapNotNull { nextUrl -> chapters.addAll(collect(nextUrl)) }
}
chapters
.mapIndexed { index, sChapter -> sChapter.apply { chapter_number = index.toFloat() } }
.reversed()
} else {
jsp.select(chapterSelector).mapIndexed { i, element ->
element.toSManga().apply { chapter_number = "0.$i".toFloat() }
}.reversed()
}
}
override fun pageListParse(response: Response): List<Page> {
val jsp = response.asJsoup()
val pages: MutableList<Page> = arrayListOf()
val comic = jsp.selectFirst("div.is--comic-page")
for (child in comic!!.select("div.is--image-segment div img")) {
pages.add(
Page(
pages.size,
response.request.url.toString(),
child.attr("src"),
),
)
}
if (showAuthorsNotesPref()) {
for (child in comic.select("div.is--author-notes div.is--comment-box").withIndex()) {
pages.add(
Page(
pages.size,
response.request.url.toString(),
TextInterceptorHelper.createUrl(
jsp.selectFirst("a.is--comment-author")?.ownText()
?.let { "Author's Notes from $it" }
.orEmpty(),
jsp.selectFirst("div.is--comment-content")?.html().orEmpty(),
),
),
)
}
}
return pages
}
/**
* Author name joining maybe redundant.
*
* Manga Status is available but not currently implemented.
*/
override fun mangaDetailsParse(response: Response): SManga {
val jsp = response.asJsoup()
val desDiv = jsp.selectFirst("div.description-tags")
return SManga.create().apply {
setUrlWithoutDomain(response.request.url.toString())
description = desDiv?.parent()?.ownText()
genre = desDiv?.children()?.eachText()?.joinToString(", ")
author = jsp.select("a.authorname").eachText().joinToString(", ")
initialized = true
}
}
override fun searchMangaParse(response: Response): MangasPage {
val jsp = response.asJsoup()
val list: MutableList<SManga> = arrayListOf()
for (result in jsp.select("div.webcomic-result")) {
list.add(
SManga.create().apply {
url = result.selectFirst("div.webcomic-result-avatar a")!!.attr("href")
title = result.selectFirst("div.webcomic-result-title")!!.attr("title")
thumbnail_url = result.selectFirst("div.webcomic-result-avatar a img")!!.absUrl("src")
},
)
}
return MangasPage(list, (jsp.selectFirst("div.search-next-page") != null))
}
override fun searchMangaRequest(page: Int, query: String, filters: FilterList): Request {
val req: HttpUrl.Builder = "$baseUrl/search.php".toHttpUrl().newBuilder()
req.addQueryParameter("query", query)
req.addQueryParameter("page", page.toString())
req.addQueryParameter("language", siteLang)
filters.forEach {
when (it) {
is TagsFilter -> req.addEncodedQueryParameter(
"tags",
it.state.replace(", ", ","),
)
is SortFilter -> req.addQueryParameter("sort", it.state.toString())
is CompletedComicFilter -> req.addQueryParameter(
"completed",
it.state.toInt().toString(),
)
is LastUpdatedFilter -> req.addQueryParameter(
"lastupdate",
it.state.toString(),
)
is ViolenceFilter -> req.addQueryParameter("fv", it.state.toString())
is NudityFilter -> req.addQueryParameter("fn", it.state.toString())
is StrongLangFilter -> req.addQueryParameter("fl", it.state.toString())
is SexualFilter -> req.addQueryParameter("fs", it.state.toString())
else -> {}
}
}
return Request.Builder().url(req.build()).build()
}
private fun Boolean.toInt(): Int = if (this) { 0 } else { 1 }
// START OF AUTHOR NOTES //
private val preferences: SharedPreferences by lazy {
Injekt.get<Application>().getSharedPreferences("source_$id", 0x0000)
}
companion object {
private const val SHOW_AUTHORS_NOTES_KEY = "showAuthorsNotes"
}
private fun showAuthorsNotesPref() =
preferences.getBoolean(SHOW_AUTHORS_NOTES_KEY, false)
override fun setupPreferenceScreen(screen: PreferenceScreen) {
val authorsNotesPref = SwitchPreferenceCompat(screen.context).apply {
key = SHOW_AUTHORS_NOTES_KEY; title = "Show author's notes"
summary = "Enable to see the author's notes at the end of chapters (if they're there)."
setDefaultValue(false)
}
screen.addPreference(authorsNotesPref)
}
// END OF AUTHOR NOTES //
// START OF FILTERS //
override fun getFilterList(): FilterList = getFilterList(0)
private fun getFilterList(sortIndex: Int): FilterList = FilterList(
TagsFilter(),
Filter.Separator(),
SortFilter(sortIndex),
Filter.Separator(),
LastUpdatedFilter(),
CompletedComicFilter(),
Filter.Separator(),
Filter.Header("Flags"),
ViolenceFilter(),
NudityFilter(),
StrongLangFilter(),
SexualFilter(),
)
internal class SortFilter(index: Int) : Filter.Select<String>(
"Sort By",
arrayOf("Relevance", "Popularity", "Last Update"),
index,
)
internal class CompletedComicFilter : Filter.CheckBox("Comic Completed", false)
internal class LastUpdatedFilter : Filter.Select<String>(
"Last Updated",
arrayOf("All Time", "This Week", "This Month", "This Year", "Completed Only"),
0,
)
internal class ViolenceFilter : Filter.Select<String>(
"Violence",
arrayOf("None / Minimal", "Violent Content", "Gore / Graphic"),
2,
)
internal class NudityFilter : Filter.Select<String>(
"Frontal Nudity",
arrayOf("None", "Occasional", "Frequent"),
2,
)
internal class StrongLangFilter : Filter.Select<String>(
"Strong Language",
arrayOf("None", "Occasional", "Frequent"),
2,
)
internal class SexualFilter : Filter.Select<String>(
"Sexual Content",
arrayOf("No Sexual Content", "Sexual Situations", "Strong Sexual Themes"),
2,
)
internal class TagsFilter : Filter.Text("Tags")
// END OF FILTERS //
override fun popularMangaRequest(page: Int): Request =
searchMangaRequest(page, "", getFilterList(1))
override fun popularMangaParse(response: Response): MangasPage = searchMangaParse(response)
override fun latestUpdatesRequest(page: Int): Request =
searchMangaRequest(page, "", getFilterList(2))
override fun latestUpdatesParse(response: Response): MangasPage = searchMangaParse(response)
override fun imageUrlParse(response: Response): String =
throw UnsupportedOperationException()
// Date stuff
private fun String.toDate(): Long {
// remove st nd rd th (e.g. from 4th) but not from AuguST, and commas
val ret = this.replace(Regex("(?<=\\d)(st|nd|rd|th)|,"), "")
return when {
ret.contains(":") -> date[0].parseTime(ret)
this.matches(Regex("\\d{1,2}\\s?\\w{3,9}\\s?\\w{2,4}")) -> date[1].parseTime(ret)
this.matches(Regex("\\w{3,9}\\s?\\d{1,2}\\s?\\d{2,4}")) -> date[2].parseTime(ret)
else -> 0
}
}
private val date = listOf("dd MMM yyyy hh:mm aa", "dd MMM yyyy", "MMM dd yyyy")
.map { SimpleDateFormat(it, Locale.US) }
private fun SimpleDateFormat.parseTime(string: String): Long {
return this.parse(string)?.time ?: 0
}
}
| 22
|
Kotlin
|
8
| 97
|
7fc1d11ee314376fe0daa87755a7590a03bc11c0
| 12,342
|
komikku-extensions
|
Apache License 2.0
|
src/kotlin/src/tutorial/coroutine/async/AsyncRun.kt
|
NanamiMio
| 457,178,790
| true
|
{"HTML": 3072012, "CSS": 1909531, "Scheme": 308236, "Java": 183277, "Emacs Lisp": 108499, "Kotlin": 105053, "Erlang": 76979, "Rust": 75302, "Python": 53551, "Go": 47318, "C": 7008, "Shell": 372}
|
package tutorial.coroutine.async
import kotlinx.coroutines.async
import kotlinx.coroutines.runBlocking
import kotlin.system.measureTimeMillis
fun main() = runBlocking {
//sampleStart
val time = measureTimeMillis {
val one = async {
doSomethingUsefulOne()
}
val two = async {
doSomethingUsefulTwo()
}
println("The answer is ${one.await() + two.await()}")
}
println("Completed in $time ms")
}
| 0
|
HTML
|
0
| 0
|
278937d27d09c1d659eb9e4fc65a2844e5fe3c72
| 425
|
klose911.github.io
|
Apache License 2.0
|
app/src/main/java/com/kvl/serenity/SoundDef.kt
|
kevinvanleer
| 697,405,690
| false
|
{"Kotlin": 78297}
|
package com.kvl.serenity
import androidx.annotation.Keep
@Keep
data class SoundDef(val name: String, val location: String, val filename: String)
| 0
|
Kotlin
|
0
| 0
|
0cbdbcd3962db04411e1511c5933aff016278383
| 147
|
serenity
|
MIT License
|
app/src/main/java/com/dramtar/billscollecting/presenter/UIUpdatingEvent.kt
|
Dramtar
| 544,515,289
| false
| null |
package com.dramtar.billscollecting.presenter
import java.io.File
sealed class UIUpdatingEvent {
data class OpenCreatedCSV(val file: File): UIUpdatingEvent()
object AddBillTypeClicked: UIUpdatingEvent()
object NavigateToOverview: UIUpdatingEvent()
object NavigateToTypeOverview: UIUpdatingEvent()
}
| 0
|
Kotlin
|
0
| 1
|
7ed7aa9bb9fce7fdadc051d52742b9c86fb9a854
| 317
|
Bills-Collecting
|
Apache License 2.0
|
library/src/test/java/dev/zotov/phototime/solarized/SolarizedUnitTest.kt
|
aadithyanr
| 413,385,632
| true
|
{"Kotlin": 19691}
|
package dev.zotov.phototime.solarized
import org.junit.Assert
import org.junit.Test
import java.time.Instant
import java.time.LocalDateTime
import java.time.ZoneOffset
class SolarizedUnitTest {
private val date = Instant.ofEpochSecond(1549918775).atZone(ZoneOffset.UTC).toLocalDateTime()
private val latitude = 47.49801
private val longitude = 19.03991
private val solarized = Solarized(latitude, longitude, date)
// private fun test(time: DateTime, twilight: Twilight, expected: Long) {
//
// val expectedDate = Instant.ofEpochSecond(expected).atZone(ZoneOffset.UTC).toLocalDateTime()
//
//
// val actual = algorithm(
// time = time,
// twilight = twilight,
// date = date,
// latitude = latitude,
// longitude = longitude
// )
// Assert.assertEquals(expectedDate, actual)
// }
private fun getDate(epochSeconds: Long): LocalDateTime {
return Instant.ofEpochSecond(epochSeconds).atZone(ZoneOffset.UTC).toLocalDateTime()
}
@Test
fun testList() {
val expected = SunPhaseList(
firstLight = SunPhase.FirstLight(date = getDate(1549858363)),
morningBlueHour = SunPhase.BlueHour(
start = getDate(1549862676),
end = getDate(1549863414),
),
sunrise = SunPhase.Sunrise(date = getDate(1549864601)),
morningGoldenHour = SunPhase.GoldenHour(
start = getDate(1549863414),
end = getDate(1549867266)
),
day = SunPhase.Day(
start = getDate(1549867266),
end = getDate(1549898164),
),
eveningGoldenHour = SunPhase.GoldenHour(
start = getDate(1549898164),
end = getDate(1549902009),
),
sunset = SunPhase.Sunset(date = getDate(1549900731)),
eveningBlueHour = SunPhase.BlueHour(
start = getDate(1549902009),
end = getDate(1549902746),
),
lastLight = SunPhase.LastLight(date = getDate(1549858363)),
)
Assert.assertEquals(expected, solarized.list)
}
}
| 0
| null |
0
| 0
|
0a0e5af6788ecd406b9898fea6ac790f024d1139
| 2,220
|
solarized-android
|
Do What The F*ck You Want To Public License
|
app/src/main/java/com/kenkoro/taurus/client/feature/orders/presentation/screen/editor/order/util/CustomerState.kt
|
kenkoro
| 746,982,789
| false
|
{"Kotlin": 265963, "JavaScript": 64}
|
package com.kenkoro.taurus.client.feature.orders.presentation.screen.editor.order.util
import com.kenkoro.taurus.client.feature.shared.states.TaurusTextFieldState
class CustomerState(
customer: String? = null,
) : TaurusTextFieldState(
validator = ::isCustomerValid,
errorFor = ::customerValidationError,
) {
init {
customer?.let {
this.text = it
}
}
}
private fun customerValidationError(
customer: String,
errorMessage: String,
): String {
return "$customer $errorMessage"
}
private fun isCustomerValid(customer: String): Boolean {
return customer.isNotBlank()
}
| 3
|
Kotlin
|
0
| 4
|
935ee7470b27759ee0623aed4c4c570aa06523d4
| 606
|
taurus
|
Apache License 2.0
|
easy/ValidAnagram.kt
|
Sternbach-Software
| 631,554,036
| false
| null |
package easy
class ValidAnagram {
companion object {
/**
* # Intuition
Assuming strings are equal length, if you can successfully remove a single instance of a letter `c` from `t` every time you see it in `s` (it is contained in `t`), then the strings have the same letters appearing the same number of times. If the remove was unsuccessful, that means the letter `c` is either not in `t` or not in `t` the number of times it is in `s`.
# Approach
If strings are unequal length, they are not anagrams.
If a character `c` in `s` is also in `t`, remove it from `t`. `t` will get smaller as the loop goes on.
# Complexity
- Time complexity:
Best case: $$O(n)$$ (one iteration).
Worst case: $$O(n * n?)$$ - slightly better than $$O(n^3)$$ (n? is the Termial function of n, otherwise known as the [nth triangular number](https://en.wikipedia.org/wiki/Triangular_number))
In the best case, `s` and `t` are identical, so `remove` performs one iteration before removing `c` from `t`. This means that only one operation is performed for every char in `s`. This does not include the iteration neccesary on the JVM for copying the string into a mutable list (because JVM strings are immutable).
In the worst case, `t` is the reverse of `s`. That means that remove has to iterate over the entire `t` before it can remove `c`. This means that if length ($$n$$) is 5, the first iteration will be 5 operations, the next will be 4, the next 3, etc. This is known by Donald Knuth as the Termial function (The Art of Computer Programming, Vol. 1 page 48) and denoted as $$n?$$ because it is the summation analog to $$n!$$ which uses multiplication.
Interestingly enough, this only beat 5% of Kotlin solutions.
- Space complexity: $$O(1)$$ (assuming string mutability)
Because strings are not mutable in JVM languages, a mutable array needs to be created with the same chars as `t`, so in the below solution, because of implementation details, the space complexity is technically $$O(n)$$, but in languages with string mutability, no new array would need to be created, so the space complexity would be $$O(1)$$.
* */
fun isAnagram(s: String, t: String): Boolean {
if(s.length != t.length) return false
val charArrayOfT = t.toMutableList()
for(char in s) {
if (!charArrayOfT.remove(char)) return false
}
return true
}
@JvmStatic
fun main(args: Array<String>) {
println(isAnagram("cat", "tac"))
println(isAnagram("anagram", "anagram".reversed()))
}
}
}
| 0
|
Kotlin
|
0
| 0
|
2ca833bc0f46ea6f036c397af154fe71a393f4ab
| 2,712
|
Grind75Solutions
|
Apache License 2.0
|
antsadapter/src/main/java/com/papashkin/antsadapter/AntsAdapter.kt
|
Papashkin
| 194,541,888
| false
| null |
package com.papashkin.antsadapter
import android.support.annotation.LayoutRes
import android.support.v7.util.DiffUtil
import android.support.v7.widget.RecyclerView
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
/**
* @author <NAME>
* Realization of the base adapter for recycler view.
* You no need to override all this methods in your adapter extended on this base adapter.
* @see IAntsBaseAdapter
* @See RecyclerView.Adapter
* @see AntsViewHolder
*/
abstract class AntsAdapter<VH : AntsViewHolder<T>, T : Any> : RecyclerView.Adapter<VH>(), IAntsBaseAdapter<T> {
private val items: MutableList<T> = mutableListOf()
private var callback: AntsBaseCallback<T>? = null
override fun add(item: T) {
items += item
notifyItemInserted(items.lastIndex)
}
override fun addAll(items: List<T>) {
if (items.isEmpty()) return
val startPosition = this.items.lastIndex + 1
for (item in items) {
this.items += item
}
notifyItemRangeInserted(startPosition, items.size)
}
override fun addTo(position: Int, item: T) {
items.add(position, item)
notifyItemChanged(position)
}
override fun remove(position: Int) {
items.removeAt(position)
notifyItemRemoved(position)
}
override fun clear() {
val removedSize = items.size
items.clear()
notifyItemRangeRemoved(0, removedSize)
}
override fun setCallback(callback: AntsBaseCallback<T>) {
this.callback = callback
}
override fun update(newItems: List<T>) {
if (callback != null) {
callback!!.setLists(items, newItems)
val diffResult = DiffUtil.calculateDiff(callback!!)
clear()
addAll(newItems)
diffResult.dispatchUpdatesTo(this)
} else {
items.clear()
items.addAll(newItems)
notifyDataSetChanged()
}
}
override fun getList(): List<T> = items
override fun getItemCount(): Int = items.size
protected fun inflate(parent: ViewGroup, @LayoutRes viewType: Int): View =
LayoutInflater.from(parent.context).inflate(viewType, parent, false)
override fun onBindViewHolder(holder: VH, position: Int) {
holder.bind(items[position], position)
}
}
| 0
|
Kotlin
|
0
| 0
|
e1a6ad679852be39207b64d78a32a709cdcaffbc
| 2,372
|
ants_base_adapter
|
MIT License
|
watchmen-model/src/main/kotlin/com/matrdata/watchmen/model/admin/Enumeration.kt
|
Indexical-Metrics-Measure-Advisory
| 478,865,509
| false
|
{"Kotlin": 160616}
|
package com.matrdata.watchmen.model.admin
import com.matrdata.watchmen.model.common.*
import java.time.LocalDateTime
data class EnumItem(
var itemId: EnumItemId? = null,
var code: String? = null,
var label: String? = null,
var parentCode: String? = null,
var replaceCode: String? = null,
var enumId: EnumId? = null,
var tenantId: TenantId? = null,
) : Storable
data class Enum(
var enumId: EnumId? = null,
var name: String? = null,
var description: String? = null,
var parentEnumId: EnumId? = null,
var items: List<EnumItem>? = null,
override var tenantId: TenantId? = null,
override var version: Int? = 1,
override var createdAt: LocalDateTime? = null,
override var createdBy: UserId? = null,
override var lastModifiedAt: LocalDateTime? = null,
override var lastModifiedBy: UserId? = null
) : TenantBasedTuple, OptimisticLock
| 0
|
Kotlin
|
0
| 0
|
bd8ef342a31c4a2bac57f96f00e9069b386e7c5a
| 849
|
watchmen-kotlin
|
MIT License
|
api/src/main/kotlin/de/hanno/hpengine/graphics/constants/TexelComponentType.kt
|
hannomalie
| 330,376,962
| false
|
{"Kotlin": 959590, "GLSL": 658394, "JavaScript": 3160, "Shell": 137, "Batchfile": 65}
|
package de.hanno.hpengine.graphics.constants
enum class TexelComponentType {
Float,
Int,
UnsignedByte
}
| 0
|
Kotlin
|
0
| 0
|
1827c8eaa9dc922871de66185ec489ce3e65bef9
| 116
|
hpengine
|
MIT License
|
petal-cli/src/main/kotlin/CLI.kt
|
NekoGoddessAlyx
| 418,652,485
| false
| null |
package petal.vm
import kotlinx.cli.ArgParser
import kotlinx.cli.ArgType
import kotlinx.cli.required
import java.io.File
fun main(args: Array<String>) {
val parser = ArgParser("Petal")
val fileName by parser.option(ArgType.String, shortName = "f", description = "File Name").required()
parser.parse(args)
val file = File(fileName)
if (!file.exists()) {
println("Could not locate file.")
return
}
val vm = VM()
val result = vm.interpret(file.nameWithoutExtension, file.readText())
println("✨✨✨✨✨✨✨✨✨✨✨✨✨")
print(result.type)
if (result.type == InterpretResultType.SUCCESS) {
print(" ")
print(result.value)
}
println()
}
| 0
|
Kotlin
|
0
| 0
|
bb1fee0549316ebbeae139745f29287f833e1d11
| 708
|
Petal
|
Apache License 2.0
|
src/main/kotlin/denis/bayramgulov/hack4luck/properties/YandexSpeechProperties.kt
|
bayramgulov
| 579,468,593
| false
|
{"Kotlin": 28211}
|
package denis.bayramgulov.hack4luck.properties
import org.springframework.boot.context.properties.ConfigurationProperties
@ConfigurationProperties("yandex-speech")
class YandexSpeechProperties {
lateinit var iam: String
}
| 0
|
Kotlin
|
0
| 0
|
e1532efd7a5ff3ba62a41e3e471b506006d0489e
| 227
|
hack4luck
|
MIT License
|
Android/app/src/main/java/live/ditto/pos/core/presentation/composables/screens/DemoLocationSelectionScreen.kt
|
getditto
| 660,393,373
| false
|
{"Kotlin": 118261, "Swift": 108298, "Shell": 1686}
|
package live.ditto.pos.core.presentation.composables.screens
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.hilt.navigation.compose.hiltViewModel
import androidx.navigation.NavHostController
import live.ditto.pos.LocalActivity
import live.ditto.pos.core.presentation.composables.DemoLocationsList
import live.ditto.pos.core.presentation.viewmodel.CoreViewModel
@Composable
fun DemoLocationSelectionScreen(
coreViewModel: CoreViewModel = hiltViewModel(LocalActivity.current),
navHostController: NavHostController
) {
DemoLocationsList(
modifier = Modifier.fillMaxSize(),
onDemoLocationSelected = {
coreViewModel.updateCurrentLocation(locationId = it.id)
navHostController.popBackStack()
}
)
}
| 14
|
Kotlin
|
0
| 3
|
669dcb812c668d172891090bc4925c29757776e7
| 860
|
demoapp-pos-kds
|
MIT License
|
compose/src/main/kotlin/ui/screen/programs/programloaded/ProgramCoordinates.kt
|
85vmh
| 543,628,296
| false
| null |
package ui.screen.programs.programloaded
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.*
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.Color
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.unit.Dp
import androidx.compose.ui.unit.TextUnit
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import extensions.toFixedDigitsString
import screen.uimodel.AxisPosition
import screen.uimodel.PositionModel
import themes.ComposeFonts
private enum class CoordinateType(
val fontSize: TextUnit,
val width: Dp
) {
PRIMARY(28.sp, 140.dp),
SECONDARY(28.sp, 140.dp),
}
@Composable
fun ProgramCoordinatesView(
currentWcs: String,
positionModel: PositionModel,
modifier: Modifier = Modifier
) {
Row(
modifier = modifier.fillMaxWidth(),
) {
Column {
CoordinatesHeader(currentWcs)
Spacer(modifier = Modifier.height(8.dp))
AxisCoordinate(
positionModel.xAxisPos,
positionModel.isDiameterMode
)
Spacer(modifier = Modifier.height(8.dp))
AxisCoordinate(
positionModel.zAxisPos
)
}
}
}
@Composable
private fun CoordinatesHeader(
currentWcs: String
) {
Row(
modifier = Modifier.fillMaxWidth(),
horizontalArrangement = Arrangement.End
) {
Text(
modifier = Modifier.padding(end = 124.dp),
text = "$currentWcs POS",
fontSize = 24.sp
)
Text(
modifier = Modifier.padding(end = 32.dp),
text = "DTG",
fontSize = 24.sp
)
}
}
@Composable
private fun AxisCoordinate(
axisPosition: AxisPosition,
isDiameterMode: Boolean = false,
modifier: Modifier = Modifier,
) {
Box(
modifier = Modifier
.background(Color.DarkGray),
contentAlignment = Alignment.Center
) {
Row(
verticalAlignment = Alignment.CenterVertically,
modifier = modifier
.fillMaxWidth()
.background(Color(0xffd8e6ff))
) {
//val line = HorizontalAlignmentLine()
AxisLetter(axisPosition, modifier = Modifier)
SpacerOrDiameter(axisPosition.axis == AxisPosition.Axis.X && isDiameterMode, modifier = Modifier)
Position(CoordinateType.PRIMARY, axisPosition, isDiameterMode, modifier = Modifier)
Units(axisPosition.units, modifier = Modifier)
Spacer(modifier = Modifier.width(8.dp))
Position(CoordinateType.SECONDARY, axisPosition, isDiameterMode, modifier = Modifier)
Units(axisPosition.units, modifier = Modifier)
}
}
}
@Composable
private fun AxisLetter(axisPosition: AxisPosition, modifier: Modifier = Modifier) {
Text(
modifier = modifier.padding(start = 8.dp),
text = axisPosition.axis.name,
fontSize = 40.sp,
)
}
@Composable
private fun SpacerOrDiameter(showDiameter: Boolean, modifier: Modifier = Modifier) {
val sizeToFill = 30.dp
if (showDiameter) {
Text(
modifier = modifier
.width(sizeToFill),
text = "\u2300",
textAlign = TextAlign.Start,
fontSize = 20.sp,
)
} else {
Spacer(modifier = modifier.width(sizeToFill))
}
}
@Composable
private fun Position(positionType: CoordinateType, axisPosition: AxisPosition, isDiameterMode: Boolean = false, modifier: Modifier = Modifier) {
val value = when (positionType) {
CoordinateType.PRIMARY -> axisPosition.primaryValue
CoordinateType.SECONDARY -> axisPosition.secondaryValue
}
if (value != null) {
Text(
modifier = modifier.width(positionType.width),
text = (value * (if (isDiameterMode) 2 else 1)).toFixedDigitsString(axisPosition.units.displayDigits),
fontSize = positionType.fontSize,
fontFamily = ComposeFonts.Family.position,
fontWeight = FontWeight.Thin,
textAlign = TextAlign.End
)
} else {
Spacer(modifier = modifier.width(positionType.width))
}
}
@Composable
private fun Units(units: AxisPosition.Units, modifier: Modifier = Modifier) {
Text(
text = units.name.lowercase(),
modifier = modifier.padding(top = 6.dp),
fontSize = 14.sp,
fontWeight = FontWeight.Medium
)
}
| 0
|
Kotlin
|
1
| 2
|
bfa08242829985a8fe0d743085de89057cefcef2
| 4,710
|
mindovercnclathe
|
Apache License 2.0
|
app/src/main/java/net/xblacky/animexstream/di/RepositoryModule.kt
|
naufalprakoso
| 275,484,992
| true
|
{"Kotlin": 138818, "Java": 1567}
|
package net.xblacky.animexstream.di
import dagger.Module
import dagger.Provides
import dagger.Reusable
import dagger.hilt.InstallIn
import dagger.hilt.android.components.ApplicationComponent
import io.realm.Realm
import net.xblacky.animexstream.ui.main.home.HomeRepository
import net.xblacky.animexstream.ui.main.player.EpisodeRepository
import net.xblacky.animexstream.ui.main.search.SearchRepository
import retrofit2.Retrofit
@InstallIn(ApplicationComponent::class)
@Module
class RepositoryModule {
@Provides
@Reusable
fun provideHomeRepository(retrofit: Retrofit): HomeRepository {
return HomeRepository(retrofit)
}
@Provides
@Reusable
fun provideEpisodeRepository(retrofit: Retrofit, realm: Realm): EpisodeRepository {
return EpisodeRepository(retrofit, realm)
}
@Provides
@Reusable
fun provideSearchRepository(retrofit: Retrofit): SearchRepository {
return SearchRepository(retrofit)
}
}
| 0
|
Kotlin
|
1
| 1
|
f557ce683f248231cb7c590779e44dfeb5f42dda
| 969
|
AnimeXStream
|
MIT License
|
app/src/main/java/com/gummybearstudio/infapp/fragments/LoaderFragment.kt
|
Maciej-GBS
| 860,632,348
| false
|
{"Kotlin": 29875}
|
package com.gummybearstudio.infapp.fragments
import android.os.Bundle
import androidx.fragment.app.Fragment
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.lifecycleScope
import androidx.lifecycle.repeatOnLifecycle
import androidx.navigation.Navigation
import com.gummybearstudio.infapp.R
import com.gummybearstudio.infapp.backend.ModelFileProvider
import kotlinx.coroutines.launch
class LoaderFragment : Fragment() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
ModelFileProvider.launchDialog(this) { navigateToCamera() }
}
private fun navigateToCamera() {
lifecycleScope.launch {
repeatOnLifecycle(Lifecycle.State.STARTED) {
if (activity != null) {
Navigation.findNavController(requireActivity(), R.id.navigatorContainer).navigate(
LoaderFragmentDirections.actionLoaderToCamera())
}
}
}
}
}
| 0
|
Kotlin
|
0
| 0
|
443c42a04bf1bba99f8006d965ba14343423284b
| 1,000
|
TFLiteRTApp
|
Apache License 2.0
|
Browser/src/commonMain/kotlin/io/nacular/doodle/dom/Node.kt
|
nacular
| 108,631,782
| false
|
{"Kotlin": 3150677}
|
@file:Suppress("EXPECTED_EXTERNAL_DECLARATION", "WRONG_MODIFIER_TARGET")
package io.nacular.doodle.dom
internal expect abstract external class NodeList() {
abstract val length: Int
open fun item(index: Int): Node?
}
internal expect inline operator fun NodeList.get(index: Int): Node?
internal expect abstract external class Node: JsAny {
fun cloneNode (deep : Boolean ): Node
fun appendChild (node : Node ): Node
fun removeChild (child: Node ): Node
fun insertBefore (node : Node, child: Node?): Node
fun replaceChild (node : Node, child: Node ): Node
fun contains (other: Node? ): Boolean
fun hasChildNodes( ): Boolean
val nodeName : String
val firstChild : Node?
val parentNode : Node?
val childNodes : NodeList
val nextSibling : Node?
var textContent : String?
val parentElement: Element?
}
internal expect fun Node.clear()
| 3
|
Kotlin
|
26
| 613
|
f7414d4c30cdd7632992071234223653e52b978c
| 990
|
doodle
|
MIT License
|
src/main/kotlin/no/nav/dagpenger/soknad/orkestrator/behov/løsere/UtdanningEllerOpplæringBehovløser.kt
|
navikt
| 758,018,874
| false
|
{"Kotlin": 251103, "HTML": 1388, "Dockerfile": 109}
|
package no.nav.dagpenger.soknad.orkestrator.behov.løsere
import no.nav.dagpenger.soknad.orkestrator.behov.Behovløser
import no.nav.dagpenger.soknad.orkestrator.behov.BehovløserFactory.Behov.TarUtdanningEllerOpplæring
import no.nav.dagpenger.soknad.orkestrator.opplysning.db.OpplysningRepository
import no.nav.helse.rapids_rivers.RapidsConnection
class UtdanningEllerOpplæringBehovløser(
rapidsConnection: RapidsConnection,
opplysningRepository: OpplysningRepository,
) : Behovløser(rapidsConnection, opplysningRepository) {
override val behov = TarUtdanningEllerOpplæring.name
override val beskrivendeId = "faktum.tar-du-utdanning"
}
| 0
|
Kotlin
|
0
| 0
|
9069503c23e9067c5b020127da975d92a0d878b6
| 652
|
dp-soknad-orkestrator
|
MIT License
|
buildSrc/src/main/kotlin/SecretLoader.kt
|
NyCodeGHG
| 393,796,405
| false
| null |
/*
* Copyright 2021 NyCode
*
* 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.
*/
import org.gradle.api.Project
import java.io.File
import java.util.*
class SecretLoader(file: File, project: Project) {
private val properties = Properties()
init {
if (!file.exists()) {
project.logger.warn("No secrets file was found! Checked $file")
}
if (file.exists() && !file.canRead()) {
project.logger.error("Unable to read file $file!")
}
if (file.exists() && file.canRead()) {
file.bufferedReader().use {
properties.load(it)
}
}
}
operator fun get(name: String): String? {
return properties.getProperty(name) ?: System.getenv(name)
}
}
| 17
|
Kotlin
|
4
| 4
|
d32635ac47a30bde149955da80c54d399c85d8c2
| 1,310
|
github-api-wrapper
|
Apache License 2.0
|
src/higherOrderFunction.kt
|
myeonginwoo
| 143,044,639
| false
| null |
fun main(args: Array<String>) {
higherOrderFunction1 { println("FP") }
higherOrderFunction2()
higherOrderFunction3 { println("FP") }
}
fun higherOrderFunction1(func: () -> Unit) {
func()
}
fun higherOrderFunction2(): () -> Unit {
return { println("FP") }
}
fun higherOrderFunction3(func: () -> Unit): () -> Unit {
return func
}
| 0
|
Kotlin
|
1
| 0
|
eac92f504dcf576654cd330eb21d06d2ab694dea
| 356
|
t-academy
|
MIT License
|
projects/manage-pom-cases-and-delius/src/test/kotlin/uk/gov/justice/digital/hmpps/integrations/ldap/LdapServiceTest.kt
|
ministryofjustice
| 500,855,647
| false
| null |
package uk.gov.justice.digital.hmpps.integrations.ldap
import org.hamcrest.MatcherAssert.assertThat
import org.hamcrest.Matchers.equalTo
import org.junit.jupiter.api.Test
import org.junit.jupiter.api.extension.ExtendWith
import org.mockito.InjectMocks
import org.mockito.Mock
import org.mockito.junit.jupiter.MockitoExtension
import org.mockito.kotlin.any
import org.mockito.kotlin.eq
import org.mockito.kotlin.whenever
import org.springframework.ldap.core.LdapTemplate
import javax.naming.ldap.LdapName
@ExtendWith(MockitoExtension::class)
class LdapServiceTest {
@Mock
private lateinit var ldapTemplate: LdapTemplate
@InjectMocks
private lateinit var ldapService: LdapService
@Test
fun `find email by username`() {
val user = LdapUser(LdapName("cn=test,ou=Users"), "test", "<EMAIL>")
whenever(ldapTemplate.find(any(), eq(LdapUser::class.java))).thenReturn(listOf(user))
val email = ldapService.findEmailByUsername("test")
assertThat(email, equalTo("<EMAIL>"))
}
}
| 0
|
Kotlin
|
0
| 2
|
2a148131c90e90dcc541dc1c0a2e69fc4f3ea121
| 1,032
|
hmpps-probation-integration-services
|
MIT License
|
core/src/main/kotlin/cloudspec/model/Resource.kt
|
efoncubierta
| 259,448,965
| false
| null |
/*-
* #%L
* CloudSpec Core Library
* %%
* Copyright (C) 2020 Ezequiel Foncubierta
* %%
* 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.
* #L%
*/
package cloudspec.model
/**
* Define a CloudSpec resource.
*
* A resource is anything that can be evaluated. It can be an EC2 instance, an S3 bucket, an entire service, etc.
* Resources have members, that can be either properties or associations.
*
* Resources are provided by the providers.
*/
data class Resource(
val ref: ResourceRef,
override val properties: Properties = emptySet(),
override val associations: Associations = emptySet()
) : MembersContainer
| 3
|
Kotlin
|
2
| 26
|
edabff96392cdb1f0d55b3a9c57ae5c433c7be69
| 1,155
|
cloudspec
|
Apache License 2.0
|
09_OOP1/practice/src/main/kotlin/Dog.kt
|
ILYA-NASA
| 658,033,777
| false
|
{"Kotlin": 71525}
|
class Dog(energy: Int, weight: Int, currentAge: Int, maxAge: Int, name: String) :
Animal(energy, weight, currentAge, maxAge, name) {
override fun move(message: String) {
super.move("$name running")
}
override fun giveOffspring(energy: Int, weight: Int, currentAge: Int, maxAge: Int, name: String): Dog {
super.giveOffspring(energy, weight, currentAge, maxAge, name)
return Dog(energy, weight, currentAge, maxAge, name)
}
}
| 0
|
Kotlin
|
0
| 1
|
7ef691ad58df137bd54825c9a84ae3f54c18dec4
| 467
|
Android-basic
|
NASA Open Source Agreement 1.3
|
test-data/src/main/java/ly/david/data/network/FakeRecordings.kt
|
lydavid
| 458,021,427
| false
| null |
package ly.david.data.network
import ly.david.data.network.api.BrowseRecordingsResponse
import ly.david.data.network.api.SearchRecordingsResponse
val fakeRecording = RecordingMusicBrainzModel(
id = "recording1",
name = "<NAME>",
firstReleaseDate = "2022-11-06",
length = 25300000,
artistCredits = listOf(fakeArtistCredit, fakeArtistCredit2),
)
val fakeRecordings = listOf(
fakeRecording
)
val browseRecordingsResponse = BrowseRecordingsResponse(
count = 1,
offset = 0,
recordings = listOf(fakeRecording)
)
val searchRecordingsResponse = SearchRecordingsResponse(
count = 1,
offset = 0,
listOf(element = fakeRecording)
)
| 11
|
Kotlin
|
0
| 0
|
4067d6463a41acfeeea529faa621b9478051ff5e
| 673
|
MusicSearch
|
Apache License 2.0
|
src/main/kotlin/de/coaster/cringepvp/utils/CringePath.kt
|
RasselbandeDE
| 524,159,699
| false
|
{"Kotlin": 199713}
|
package de.coaster.cringepvp.utils
import de.coaster.cringepvp.extensions.toCringeLocation
import de.coaster.cringepvp.managers.CoroutineManager
import kotlinx.coroutines.delay
import org.bukkit.Location
import org.bukkit.configuration.ConfigurationSection
import org.bukkit.entity.Player
import org.bukkit.util.Vector
class CringePath(vararg locationPoints: Location) {
companion object {
fun fromConfig(config: ConfigurationSection, configKey: String) : CringePath {
val locationAny = config.get(configKey)
if (locationAny is List<*>) {
val locations = locationAny.map { (it as String).toCringeLocation() }
return CringePath(*locations.toTypedArray())
}
else if(locationAny is String) {
val location = locationAny.toCringeLocation()
return CringePath(location)
}
else {
throw IllegalArgumentException("Invalid path format")
}
}
}
val locations = locationPoints.toList()
val steps = locations.size
class Progress(val player: Player, private val path: CringePath, step: Int = 0) {
var currentStep = step
private fun nextStep() {
currentStep++
}
private fun isFinished() : Boolean {
return currentStep >= path.steps
}
private fun getCurrentLocation() : Location {
return path.locations[currentStep]
}
fun startTraveling() {
/* Apply velocity to player to fly to the landingLocation */
player.velocity = getCurrentLocation().toVector().subtract(player.location.toVector()).add(Vector(0.0, 5.0, 0.0))
CoroutineManager.startCoroutine {
while (!isFinished()) {
while (!player.isDead && player.location.distance(getCurrentLocation()) > 5.0) {
player.velocity = getCurrentLocation().toVector().subtract(player.location.toVector()).multiply(0.2)
delay(100)
}
nextStep()
}
}
}
}
}
| 0
|
Kotlin
|
0
| 0
|
6d07a821ddedaf741c131af4e8932e728af37728
| 2,180
|
CringePvP
|
MIT License
|
shared/chart/src/commonMain/kotlin/little/goose/chart/bar/BarData.kt
|
MReP1
| 525,822,587
| false
|
{"Kotlin": 661580}
|
package little.goose.chart.bar
import androidx.compose.ui.graphics.Color
data class BarData(
val xText: String,
val amount: Float,
val yText: String,
val color: Color
)
| 1
|
Kotlin
|
27
| 96
|
fd0e66aefcdb571972e1ba96819255998b46529b
| 187
|
LittleGooseOffice
|
MIT License
|
sphinx/screens/dashboard/dashboard/src/main/java/chat/sphinx/dashboard/ui/feed/FeedRecommendationsViewModel.kt
|
stakwork
| 340,103,148
| false
|
{"Kotlin": 4008358, "Java": 403469, "JavaScript": 4745, "HTML": 4706, "Shell": 2453}
|
package chat.sphinx.dashboard.ui.feed
import chat.sphinx.wrapper_podcast.FeedRecommendation
import kotlinx.coroutines.flow.StateFlow
interface FeedRecommendationsViewModel {
val feedRecommendationsHolderViewStateFlow: StateFlow<List<FeedRecommendation>>
fun feedRecommendationSelected(feed: FeedRecommendation)
fun loadFeedRecommendations()
}
| 90
|
Kotlin
|
11
| 18
|
7811b4f4e5a0cf8a26f343704cfced011b1f9bad
| 357
|
sphinx-kotlin
|
MIT License
|
myddd-starter-domain/src/main/kotlin/org/myddd/vertx/domain/DocumentRepository.kt
|
mydddOrg
| 493,973,123
| false
|
{"Kotlin": 42207}
|
package org.myddd.vertx.domain
import io.vertx.core.Future
import org.myddd.vertx.repository.api.EntityRepository
interface DocumentRepository:EntityRepository {
suspend fun queryDocumentByMediaId(mediaId: String): Future<Document?>
}
| 0
|
Kotlin
|
0
| 0
|
52aab7aab14b640b1bc5d37e58512a926d416fb7
| 240
|
myddd-vertx-scaffold
|
MIT License
|
Android/app/src/main/java/live/ditto/pos/core/data/locations/ditto/LocationsDittoConstants.kt
|
getditto
| 660,393,373
| false
|
{"Kotlin": 118261, "Swift": 108298, "Shell": 1686}
|
package live.ditto.pos.core.data.locations.ditto
const val LOCATIONS_COLLECTIONS_NAME = "locations"
const val LOCATIONS_SUBSCRIPTION_QUERY = """
SELECT * FROM COLLECTION $LOCATIONS_COLLECTIONS_NAME (saleItemIds MAP)
"""
const val SELECT_ALL_LOCATIONS_QUERY = """
SELECT * FROM COLLECTION $LOCATIONS_COLLECTIONS_NAME (saleItemIds MAP)
"""
const val INSERT_CUSTOM_LOCATION_QUERY = """
INSERT INTO COLLECTION $LOCATIONS_COLLECTIONS_NAME (saleItemIds MAP)
DOCUMENTS (:new)
ON ID CONFLICT DO UPDATE
"""
| 14
|
Kotlin
|
0
| 3
|
669dcb812c668d172891090bc4925c29757776e7
| 522
|
demoapp-pos-kds
|
MIT License
|
app/src/main/java/br/espartano/marvelheroescatalog/ui/activities/MainActivity.kt
|
oliveiradev27
| 216,417,185
| false
| null |
package br.espartano.marvelheroescatalog.ui.activities
import android.os.Bundle
import android.os.Parcelable
import android.view.View
import android.view.ViewGroup
import androidx.activity.viewModels
import androidx.appcompat.app.AlertDialog
import androidx.appcompat.app.AppCompatActivity
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import br.espartano.marvelheroescatalog.R
import br.espartano.marvelheroescatalog.data.api.Character
import br.espartano.marvelheroescatalog.ui.adapters.CharactersAdapter
import br.espartano.marvelheroescatalog.viewmodels.CharactersViewModel
import br.espartano.marvelheroescatalog.viewmodels.states.CharactersStates
import com.facebook.shimmer.ShimmerFrameLayout
import dagger.hilt.android.AndroidEntryPoint
@AndroidEntryPoint
class MainActivity : AppCompatActivity() {
val charactersViewModel: CharactersViewModel by viewModels()
private val characters = mutableListOf<Character>()
private val adapter: CharactersAdapter by lazy { CharactersAdapter(characters) }
private lateinit var recyclerHeroes: RecyclerView
private lateinit var frameLoading: ViewGroup
private lateinit var shimmerContainer: ShimmerFrameLayout
private var recyclerState: Parcelable? = null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
configureObserverStates()
initializeViews()
configureListeners()
}
private fun initializeViews() {
shimmerContainer = findViewById(R.id.shimmer_view_container)
frameLoading = findViewById(R.id.fl_loading)
recyclerHeroes = findViewById(R.id.rv_characters)
}
private fun configureListeners() {
val manager = LinearLayoutManager(this)
recyclerHeroes.layoutManager = manager
recyclerHeroes.adapter = adapter
recyclerHeroes.addOnScrollListener(object : RecyclerView.OnScrollListener() {
override fun onScrollStateChanged(recyclerView: RecyclerView, newState: Int) {
super.onScrollStateChanged(recyclerView, newState)
val lastVisibleItemPosition = manager.findLastVisibleItemPosition()
charactersViewModel.loadMoreCharacters(lastVisibleItemPosition)
}
})
}
private fun configureObserverStates() {
charactersViewModel
.getStates()
.observe(this, { state: CharactersStates ->
when (state) {
is CharactersStates.Loading -> { frameLoading.visibility = View.VISIBLE }
is CharactersStates.Loaded -> updateCharacters(state.characters)
is CharactersStates.Error -> showErrorMessage()
is CharactersStates.InitialState -> configureInitialState()
is CharactersStates.EmptyState -> showErrorMessage()
}
})
}
private fun updateCharacters(chars: List<Character>) {
characters.clear()
adapter.add(chars)
recyclerState?.let {
recyclerHeroes.layoutManager?.onRestoreInstanceState(it)
recyclerState = null
}
removeLoadEffect()
}
private fun configureInitialState() {
frameLoading.visibility = View.VISIBLE
shimmerContainer.visibility = View.VISIBLE
shimmerContainer.startShimmer()
charactersViewModel.loadMoreCharacters()
}
private fun removeLoadEffect() {
frameLoading.visibility = View.GONE
shimmerContainer.stopShimmer()
shimmerContainer.visibility = View.GONE
}
private fun showErrorMessage() {
frameLoading.visibility = View.GONE
AlertDialog
.Builder(this)
.setCancelable(false)
.setTitle(R.string.system_message)
.setMessage(R.string.system_body_error)
.setPositiveButton(R.string.try_again) { dialog, _ ->
frameLoading.visibility = View.VISIBLE
charactersViewModel.resetState()
dialog.dismiss()
}
.create()
.show()
}
override fun onSaveInstanceState(outState: Bundle) {
super.onSaveInstanceState(outState)
outState.putParcelable("lmState", recyclerHeroes.layoutManager?.onSaveInstanceState())
}
override fun onRestoreInstanceState(savedInstanceState: Bundle) {
super.onRestoreInstanceState(savedInstanceState)
recyclerState = savedInstanceState.getParcelable("lmState")
}
}
| 0
|
Kotlin
|
0
| 0
|
4a7230b5e3fb34a6c36dbc89bd32cda21654d5ec
| 4,632
|
Marvel-Heroes-Panel
|
MIT License
|
camerax_lib/src/main/java/com/kiylx/camerax_lib/main/manager/model/ManagerConfig.kt
|
Knightwood
| 517,621,489
| false
|
{"Kotlin": 248505, "Java": 31809}
|
package com.kiylx.camerax_lib.main.manager.model
import android.os.Parcelable
import android.util.Size
import android.view.Surface
import androidx.camera.core.ImageCapture
import com.kiylx.camerax_lib.main.store.ImageCaptureConfig
import com.kiylx.camerax_lib.main.store.VideoRecordConfig
import kotlinx.parcelize.Parcelize
@Parcelize
data class ManagerConfig(
var flashMode: Int = FlashModel.CAMERA_FLASH_OFF,
/**
* android R以下时,在少数display为null的情况下,设置预览,拍照的默认分辨率
*/
var size: Size = Size(1280, 720),
/**
* 指定这次相机使用的用例组合,例如拍照,录像,图像识别等 查看[UseCaseMode]
* 也可以使用[UseCaseMode.customGroup] 生成自定义的用例组合
*/
var useCaseMode: Int = UseCaseMode.takePhoto,
/**
* 指定图像分析、拍照、录制的旋转角度,默认可能为[Surface.ROTATION_0]。 默认值是根据display的旋转方向而定
* 因此,如果在此指定值,默认值将不会使用
*/
var rotation: Int = -1,
/**
* 视频录制配置
*/
var recordConfig: VideoRecordConfig = VideoRecordConfig(),
/**
* 拍照配置
*/
var imageCaptureConfig: ImageCaptureConfig = ImageCaptureConfig()
) : Parcelable {
fun isUsingImageAnalyzer(): Boolean {
return UseCaseHexStatus.canAnalyze(useCaseMode)
}
fun isUsingVideoRecorder(): Boolean {
return UseCaseHexStatus.canTakeVideo(useCaseMode)
}
fun isUsingImageCapture(): Boolean {
return UseCaseHexStatus.canTakePicture(useCaseMode)
}
}
/**
* 指定相机绑定何种用例
*/
class UseCaseMode {
companion object {
val takePhoto = customGroup(
UseCaseHexStatus.USE_CASE_PREVIEW,
UseCaseHexStatus.USE_CASE_IMAGE_CAPTURE,
)
val takeVideo = customGroup(
UseCaseHexStatus.USE_CASE_PREVIEW,
UseCaseHexStatus.USE_CASE_VIDEO_CAPTURE,
)
val imageAnalysis = customGroup(
UseCaseHexStatus.USE_CASE_PREVIEW,
UseCaseHexStatus.USE_CASE_IMAGE_ANALYZE,
UseCaseHexStatus.USE_CASE_IMAGE_CAPTURE,
)
/**
* 除了预览画面用例,不使用其他任何用例
*/
const val onlyPreview = UseCaseHexStatus.USE_CASE_PREVIEW
// /**
// * 自定义用例组合,需要实现[IUseCaseHelper]接口,在[IUseCaseHelper.initCustomUseCaseList]方法中实现自定义用例组合的初始化
// * 使用[IUseCaseHelper.provideCustomUseCaseList]方法提供自定义用例组合
// *
// * 且在相机初始化之前调用[UseCaseHolder.setInitImpl]方法,提供[IUseCaseHelper]接口实现
// */
// const val customUseCaseGroup = CUSTOM_USE_CASE_GROUP
/**
* @param useCaseHexState 需要组合在一起使用的用例 [UseCaseHexStatus]
*/
fun customGroup(vararg useCaseHexState: Int): Int {
var result: Int = useCaseHexState[0]
if (useCaseHexState.size > 1) {
for (i in 1 until useCaseHexState.size) {
result = UseCaseHexStatus.addUseCase(result, useCaseHexState[i])
}
}
return result
}
}
}
/**
* 闪光灯模式
*/
class FlashModel {
companion object {
const val CAMERA_FLASH_AUTO = ImageCapture.FLASH_MODE_AUTO
const val CAMERA_FLASH_ON = ImageCapture.FLASH_MODE_ON
const val CAMERA_FLASH_OFF = ImageCapture.FLASH_MODE_OFF
const val CAMERA_FLASH_ALL_ON = 777 //常亮模式
}
}
| 0
|
Kotlin
|
6
| 34
|
4db9a7dafd770415d7f85b3f5159bcb542e2925d
| 3,183
|
CameraX-Helper
|
Apache License 2.0
|
app/src/main/java/io/awaken/data/database/AwakenDatabase.kt
|
SharpKode
| 155,014,956
| true
|
{"Kotlin": 27056, "Java": 6020}
|
package io.awaken.data.database
import android.content.Context
import androidx.room.Database
import androidx.room.Room
import androidx.room.RoomDatabase
import io.awaken.data.ConnectionDao
import io.awaken.data.model.Connection
@Database(entities = [Connection::class], version = 1)
abstract class AwakenDatabase : RoomDatabase() {
abstract fun connectionDao(): ConnectionDao
companion object {
@Volatile
private var INSTANCE: AwakenDatabase? = null
fun getDatabase(context: Context): AwakenDatabase {
return INSTANCE ?: synchronized(this) {
val instance = Room.databaseBuilder(
context.applicationContext,
AwakenDatabase::class.java,
"awaken_db"
).fallbackToDestructiveMigration().build()
INSTANCE = instance
instance
}
}
}
}
| 0
|
Kotlin
|
0
| 0
|
696a353eb03739400cf699c1ea912a8b37e405fc
| 935
|
Awaken
|
Apache License 2.0
|
protocol/src/main/kotlin/net/rsprox/protocol/ProtProvider.kt
|
blurite
| 822,339,098
| false
|
{"Kotlin": 1453055}
|
package net.rsprox.protocol
public fun interface ProtProvider<out T> {
public operator fun get(opcode: Int): T
}
| 2
|
Kotlin
|
4
| 9
|
41535908e6ccb633c8f2564e8961efa771abd6de
| 118
|
rsprox
|
MIT License
|
app/src/main/kotlin/cz/covid19cz/erouska/ui/helpsearch/HelpSearchFragment.kt
|
covid19cz
| 247,683,648
| false
| null |
package cz.covid19cz.erouska.ui.helpsearch
import android.app.SearchManager
import android.content.Context
import android.os.Bundle
import android.view.MenuItem
import android.view.View
import android.widget.SearchView
import androidx.lifecycle.Observer
import cz.covid19cz.erouska.R
import cz.covid19cz.erouska.databinding.FragmentHelpSearchBinding
import cz.covid19cz.erouska.ext.attachKeyboardController
import cz.covid19cz.erouska.ext.show
import cz.covid19cz.erouska.ui.base.BaseFragment
import cz.covid19cz.erouska.utils.Markdown
import cz.covid19cz.erouska.utils.showOrHide
import dagger.hilt.android.AndroidEntryPoint
import kotlinx.android.synthetic.main.fragment_help_search.*
import kotlinx.android.synthetic.main.search_toolbar.*
import javax.inject.Inject
@AndroidEntryPoint
class HelpSearchFragment : BaseFragment<FragmentHelpSearchBinding, HelpSearchVM>(
R.layout.fragment_help_search,
HelpSearchVM::class
) {
@Inject
internal lateinit var markdown: Markdown
override fun onOptionsItemSelected(item: MenuItem): Boolean {
return when (item.itemId) {
android.R.id.home -> {
goBack()
true
}
else -> super.onOptionsItemSelected(item)
}
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
viewModel.fillQuestions()
viewModel.queryData.observe(this,
Observer {
when {
it.isEmpty() -> empty_text_view.text = ""
it.length < viewModel.minQueryLength -> empty_text_view.setText(R.string.help_type_more)
else -> empty_text_view.setText(R.string.help_no_results)
}
})
viewModel.searchEmpty.observe(this,
Observer { isEmpty ->
help_categories.showOrHide(!isEmpty)
empty_text_view.showOrHide(isEmpty)
empty_image_view.showOrHide(isEmpty)
})
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
enableUpInToolbar(true, IconType.UP)
// Associate searchable configuration with the SearchView
val searchManager = activity?.getSystemService(Context.SEARCH_SERVICE) as SearchManager
activity?.toolbar_search_view?.apply {
attachKeyboardController()
setSearchableInfo(searchManager.getSearchableInfo(activity?.componentName))
setOnQueryTextListener(object : SearchView.OnQueryTextListener {
override fun onQueryTextSubmit(query: String?): Boolean {
return false
}
override fun onQueryTextChange(query: String?): Boolean {
viewModel.searchQuery(query)
return true
}
})
setOnCloseListener {
goBack()
true
}
show()
requestFocus()
}
}
override fun onBackPressed(): Boolean {
goBack()
return true
}
private fun removeSearchViewCallbacks() {
activity?.toolbar_search_view?.apply {
setOnCloseListener(null)
setOnQueryTextListener(null)
}
}
private fun goBack() {
removeSearchViewCallbacks()
collapseSearchView()
navController().navigateUp()
}
private fun collapseSearchView() {
activity?.toolbar_search_view?.apply {
setQuery("", false)
}
}
}
| 0
|
Kotlin
|
57
| 205
|
23064413869fe7ba3d083beb9e6c639b59abfbcc
| 3,642
|
erouska-android
|
MIT License
|
google/tasks/src/commonMain/kotlin/net/opatry/google/tasks/model/SurfaceInfo.kt
|
opatry
| 860,583,716
| false
|
{"Kotlin": 667737, "Shell": 13260, "HTML": 451, "Ruby": 196}
|
/*
* Copyright (c) 2024 <NAME>
*
* Permission is hereby granted, free of charge, to any person obtaining
* a copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the Software
* is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
* OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE
* OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
package net.opatry.google.tasks.model
import kotlinx.serialization.SerialName
import kotlinx.serialization.Serializable
@Serializable
/**
* Information about the surface (Docs, Chat Spaces) where this task was assigned from.
*/
abstract class SurfaceInfo {
// @SerialName("driveResourceInfo")
@Serializable
/**
* Information about the [Drive resource](https://developers.google.com/tasks/reference/rest/v1/tasks#driveresourceinfo) where a task was assigned from (the document, sheet, etc.).
*
* @property driveFileId Output only. Identifier of the file in the Drive API.
* @property resourceKey Output only. Resource key required to access files shared via a shared link. Not required for all files. See also developers.google.com/drive/api/guides/resource-keys.
*/
data class DriveResourceInfo(
@SerialName("driveFileId")
val driveFileId: String,
@SerialName("resourceKey")
val resourceKey: String,
) : SurfaceInfo()
// @SerialName("spaceInfo")
@Serializable
/**
* Information about the [Chat Space](https://developers.google.com/tasks/reference/rest/v1/tasks#spaceinfo) where a task was assigned from.
*
* @property space Output only. The Chat space where this task originates from. The format is "spaces/{space}".
*/
data class SpaceInfo(
@SerialName("space")
val space: String,
) : SurfaceInfo()
}
| 4
|
Kotlin
|
0
| 2
|
299f266b7fad0e8d942ec9a10b702977b763e864
| 2,550
|
taskfolio
|
MIT License
|
libraries/remote/src/test/java/com/aliumujib/artic/remote/remote/ArticlesRemoteTest.kt
|
aliumujib
| 210,103,091
| false
|
{"Kotlin": 448715}
|
/*
* Copyright 2020 <NAME>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.aliumujib.artic.remote.remote
import com.aliumujib.artic.data.DummyDataFactory
import com.aliumujib.artic.data.model.ArticleEntity
import com.aliumujib.artic.remote.api.WordPressAPI
import com.aliumujib.artic.remote.impl.ArticlesRemote
import com.aliumujib.artic.remote.mapper.AuthorMapper
import com.aliumujib.artic.remote.mapper.CategoryMapper
import com.aliumujib.artic.remote.mapper.PostsMapper
import okhttp3.OkHttpClient
import okhttp3.mockwebserver.MockResponse
import okhttp3.mockwebserver.MockWebServer
import org.junit.After
import org.junit.Before
import org.junit.Test
import org.mockito.ArgumentMatchers.anyInt
import org.mockito.MockitoAnnotations
import retrofit2.Retrofit
import retrofit2.converter.gson.GsonConverterFactory
import java.io.File
import java.util.concurrent.TimeUnit
class ArticlesRemoteTest {
lateinit var api: WordPressAPI
private lateinit var articlesRemote: ArticlesRemote
private lateinit var postsMapper: PostsMapper
private var categoryMapper = CategoryMapper()
private var authorMapper = AuthorMapper()
private lateinit var mockServer: MockWebServer
@Before
fun setup() {
MockitoAnnotations.initMocks(this)
mockServer = MockWebServer()
// Start the local server
mockServer.start()
val okHttpClient = OkHttpClient.Builder()
.build()
val retrofit = Retrofit.Builder()
//.addCallAdapterFactory(RxJava2CallAdapterFactory.create())
.baseUrl(WordPressAPI.BASE_URL)
.addConverterFactory(GsonConverterFactory.create())
.client(okHttpClient)
.build()
api = retrofit.create(WordPressAPI::class.java)
postsMapper = PostsMapper(categoryMapper, authorMapper)
articlesRemote = ArticlesRemote(api, postsMapper)
}
@Test
fun `check that calling getPostByPage returns posts`() {
val path = "?json=get_posts"
val testObserver = TestObserver<List<ArticleEntity>>()
val mockResponse = MockResponse()
.setResponseCode(200)
.setBody(getJson("json/get_all_categories.json"))
mockServer.enqueue(mockResponse)
articlesRemote.getArticles(0).subscribe(testObserver)
testObserver.awaitTerminalEvent(2, TimeUnit.SECONDS)
testObserver.assertNoErrors()
testObserver.assertValueCount(1)
val request = mockServer.takeRequest()
assertEquals(path, request.path)
}
@Test
fun `test that getPostByPage returns error when timeout is exceeded`() {
val testObserver = TestObserver<List<ArticleEntity>>()
val path = "/blogs"
val mockResponse = MockResponse()
.setResponseCode(200)
.throttleBody(1024, 1, TimeUnit.SECONDS) // Simulate SocketTimeout
.setBody(getJson("json/get_all_categories.json"))
mockServer.enqueue(mockResponse)
articlesRemote.getArticles(0).subscribe(testObserver)
testObserver.awaitTerminalEvent(2, TimeUnit.SECONDS)
testObserver.assertNoValues()
assertEquals(1, testObserver.errorCount())
val request = mockServer.takeRequest()
assertEquals(path, request.path)
}
fun stubAPIResponse() {
whenever(api.getPostByPage(anyInt(), anyInt())).thenReturn(
Observable.just(
PagedPostsListResponse(
ArticlesRemote.PER_PAGE, 50,
3, DummyDataFactory.makePostList(30)
)
)
)
}
/**
* Helper function which will load JSON from
* the path specified
*
* @param path : Path of JSON file
* @return json : JSON from file at given path
*/
fun getJson(path: String): String {
// Load the JSON response
val uri = this.javaClass.classLoader.getResource(path)
val file = File(uri.path)
return String(file.readBytes())
}
@After
@Throws
fun tearDown() {
// We're done with tests, shut it down
mockServer.shutdown()
}
}
| 0
|
Kotlin
|
6
| 47
|
3306935c9c45a888e81819b56b83c478c63e9640
| 4,696
|
Artic
|
Apache License 2.0
|
src/main/kotlin/uk/gov/justice/digital/hmpps/nomisprisonerapi/jpa/repository/AgencyVisitSlotRepository.kt
|
ministryofjustice
| 444,895,409
| false
|
{"Kotlin": 2982892, "PLSQL": 319433, "Dockerfile": 1112}
|
package uk.gov.justice.digital.hmpps.nomisprisonerapi.jpa.repository
import org.springframework.data.repository.CrudRepository
import org.springframework.stereotype.Repository
import uk.gov.justice.digital.hmpps.nomisprisonerapi.jpa.AgencyVisitSlot
import java.time.LocalTime
@Repository
interface AgencyVisitSlotRepository : CrudRepository<AgencyVisitSlot, Long> {
fun findByLocationId(locationId: String): List<AgencyVisitSlot>
fun findByAgencyInternalLocationDescriptionAndAgencyVisitTimeStartTimeAndWeekDay(
roomDescription: String,
startTime: LocalTime,
weekDay: String,
): AgencyVisitSlot?
}
| 1
|
Kotlin
|
2
| 0
|
ca8b0f7ca122431097b3462e3b57803561d75f9e
| 620
|
hmpps-nomis-prisoner-api
|
MIT License
|
app/src/main/java/com/alorma/settingslib/MainActivity.kt
|
eric-ampire
| 362,271,861
| true
|
{"Kotlin": 44012}
|
package com.alorma.settingslib
import android.os.Bundle
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.compose.material.Text
import androidx.navigation.NavHostController
import androidx.navigation.compose.NavHost
import androidx.navigation.compose.composable
import androidx.navigation.compose.navArgument
import androidx.navigation.compose.rememberNavController
import com.alorma.settingslib.ui.Navigation
import com.alorma.settingslib.ui.screens.CheckboxesSettings
import com.alorma.settingslib.ui.screens.MenuLinksSettings
import com.alorma.settingslib.ui.screens.SwitchesSettings
import com.alorma.settingslib.ui.screens.TopLevelSettings
import com.alorma.settingslib.ui.theme.SettingsLibTheme
class MainActivity : ComponentActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContent {
val navController = rememberNavController()
SettingsLibTheme {
NavHost(
navController = navController,
startDestination = Navigation.NAV_TOP_SETTINGS,
) {
composable(Navigation.NAV_TOP_SETTINGS) {
TopLevelSettings(navController = navController)
}
composable(Navigation.NAV_MENU_LINKS) {
MenuLinksSettings(navController = navController)
}
composable(Navigation.NAV_SWITCHES) {
SwitchesSettings(navController = navController)
}
composable(Navigation.NAV_CHECKBOXES) {
CheckboxesSettings(navController = navController)
}
}
}
}
}
}
| 0
| null |
1
| 0
|
5ead5024251243eb9482d11feb10c5dc2341a7b6
| 1,840
|
Compose-Settings
|
MIT License
|
common/src/commonMain/kotlin/io/github/irack/stonemanager/interface/ui/view/common/CommonWidget.kt
|
IRACK000
| 723,712,145
| false
|
{"Kotlin": 136170, "Swift": 540}
|
package io.github.irack.stonemanager.`interface`.ui.view.common
| 0
|
Kotlin
|
0
| 0
|
8e86910e7f2121b99639ab190be36458f7de8b83
| 65
|
StoneManager
|
MIT License
|
akommons-bindings/src/main/java/com/dewarder/akommons/binding/ColorBindings.kt
|
hluhovskyi
| 82,401,091
| false
|
{"Kotlin": 261392}
|
/*
* Copyright (C) 2017 Artem Hluhovskyi
*
* 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.dewarder.akommons.binding
import android.app.Activity
import android.app.Dialog
import android.app.Fragment
import android.content.Context
import android.support.annotation.ColorRes
import android.support.annotation.RestrictTo
import android.view.View
import com.dewarder.akommons.binding.util.contextProvider
import com.dewarder.akommons.binding.util.getSafeThemedColor
import com.dewarder.akommons.binding.util.getThemedColor
import com.dewarder.akommons.util.Optional
import com.dewarder.akommons.util.Required
import kotlin.properties.ReadOnlyProperty
/**
* View
*/
fun View.color(@ColorRes colorRes: Int): ReadOnlyProperty<View, Int>
= requiredColor(contextProvider, colorRes)
fun View.colorOptional(@ColorRes colorRes: Int): ReadOnlyProperty<View, Int?>
= optionalColor(contextProvider, colorRes)
fun View.colors(@ColorRes vararg colorRes: Int): ReadOnlyProperty<View, List<Int>>
= requiredColors(contextProvider, colorRes)
fun View.colorsOptional(@ColorRes vararg colorRes: Int): ReadOnlyProperty<View, List<Int?>>
= optionalColors(contextProvider, colorRes)
/**
* Activity
*/
fun Activity.color(@ColorRes colorRes: Int): ReadOnlyProperty<Activity, Int>
= requiredColor(contextProvider, colorRes)
fun Activity.colorOptional(@ColorRes colorRes: Int): ReadOnlyProperty<Activity, Int?>
= optionalColor(contextProvider, colorRes)
fun Activity.colors(@ColorRes vararg colorRes: Int): ReadOnlyProperty<Activity, List<Int>>
= requiredColors(contextProvider, colorRes)
fun Activity.colorsOptional(@ColorRes vararg colorRes: Int): ReadOnlyProperty<Activity, List<Int?>>
= optionalColors(contextProvider, colorRes)
/**
* Fragment
*/
fun Fragment.color(@ColorRes colorRes: Int): ReadOnlyProperty<Fragment, Int>
= requiredColor(contextProvider, colorRes)
fun Fragment.colorOptional(@ColorRes colorRes: Int): ReadOnlyProperty<Fragment, Int?>
= optionalColor(contextProvider, colorRes)
fun Fragment.colors(@ColorRes vararg colorRes: Int): ReadOnlyProperty<Fragment, List<Int>>
= requiredColors(contextProvider, colorRes)
fun Fragment.colorsOptional(@ColorRes vararg colorRes: Int): ReadOnlyProperty<Fragment, List<Int?>>
= optionalColors(contextProvider, colorRes)
/**
* Dialog
*/
fun Dialog.color(@ColorRes colorRes: Int): ReadOnlyProperty<Dialog, Int>
= requiredColor(contextProvider, colorRes)
fun Dialog.colorOptional(@ColorRes colorRes: Int): ReadOnlyProperty<Dialog, Int?>
= optionalColor(contextProvider, colorRes)
fun Dialog.colors(@ColorRes vararg colorRes: Int): ReadOnlyProperty<Dialog, List<Int>>
= requiredColors(contextProvider, colorRes)
fun Dialog.colorsOptional(@ColorRes vararg colorRes: Int): ReadOnlyProperty<Dialog, List<Int?>>
= optionalColors(contextProvider, colorRes)
/**
* ContextProvider
*/
fun ContextProvider.color(@ColorRes colorRes: Int): ReadOnlyProperty<ContextProvider, Int>
= requiredColor(this::provideContext, colorRes)
fun ContextProvider.colorOptional(@ColorRes colorRes: Int): ReadOnlyProperty<ContextProvider, Int?>
= optionalColor(this::provideContext, colorRes)
fun ContextProvider.colors(@ColorRes vararg colorRes: Int): ReadOnlyProperty<ContextProvider, List<Int>>
= requiredColors(this::provideContext, colorRes)
fun ContextProvider.colorsOptional(@ColorRes vararg colorRes: Int): ReadOnlyProperty<ContextProvider, List<Int?>>
= optionalColors(this::provideContext, colorRes)
/**
* Getters
*/
@RestrictTo(RestrictTo.Scope.LIBRARY_GROUP)
inline fun <R> requiredColor(crossinline contextProvider: () -> Context,
@ColorRes colorRes: Int): ReadOnlyProperty<R, Int> {
return Required { contextProvider().getThemedColor(colorRes) }
}
@RestrictTo(RestrictTo.Scope.LIBRARY_GROUP)
inline fun <R> optionalColor(crossinline contextProvider: () -> Context,
@ColorRes colorRes: Int): ReadOnlyProperty<R, Int?> {
return Optional { contextProvider().getSafeThemedColor(colorRes) }
}
@RestrictTo(RestrictTo.Scope.LIBRARY_GROUP)
inline fun <R> requiredColors(crossinline contextProvider: () -> Context,
@ColorRes colorRes: IntArray): ReadOnlyProperty<R, List<Int>> {
return Required {
val context = contextProvider()
colorRes.map(context::getThemedColor)
}
}
@RestrictTo(RestrictTo.Scope.LIBRARY_GROUP)
inline fun <R> optionalColors(crossinline contextProvider: () -> Context,
@ColorRes colorRes: IntArray): ReadOnlyProperty<R, List<Int?>> {
return Required {
val context = contextProvider()
colorRes.map(context::getSafeThemedColor)
}
}
| 0
|
Kotlin
|
3
| 25
|
0c6001f673e3eeb25e364745ad9942c49737e875
| 5,354
|
AndroidKommons
|
Apache License 2.0
|
app/src/main/java/com/mustafa/movieapp/MovieApp.kt
|
SP2014
| 267,268,228
| true
|
{"Kotlin": 505199}
|
package com.mustafa.movieapp
import android.app.Application
import com.mustafa.movieapp.di.AppInjector
import dagger.android.AndroidInjector
import dagger.android.DispatchingAndroidInjector
import dagger.android.HasAndroidInjector
import timber.log.Timber
import javax.inject.Inject
@Suppress("unused")
class MovieApp : Application(), HasAndroidInjector {
@Inject
lateinit var androidInjector: DispatchingAndroidInjector<Any>
override fun onCreate() {
super.onCreate()
AppInjector.init(this)
if (BuildConfig.DEBUG) {
Timber.plant(Timber.DebugTree())
}
}
override fun androidInjector(): AndroidInjector<Any> {
return androidInjector
}
}
| 0
| null |
0
| 0
|
a64da3622d0c2fb8f8d83f5a913979c471f6b3bf
| 720
|
MoviesApp
|
Apache License 2.0
|
favorite/src/test/java/com/instaleap/favorite/ui/favorite/FavoriteViewModelTest.kt
|
rovargas15
| 845,909,506
| false
|
{"Kotlin": 255524, "Shell": 3714}
|
package com.instaleap.favorite.ui.favorite
import com.instaleap.core.route.Router
import com.instaleap.domain.model.Movie
import com.instaleap.domain.model.Tv
import com.instaleap.domain.usecase.GetFavoriteMovieUseCase
import com.instaleap.domain.usecase.GetFavoriteTvUseCase
import com.instaleap.favorite.ui.favorite.FavoriteContract.Effect
import com.instaleap.favorite.ui.favorite.FavoriteContract.UiEvent
import io.mockk.coEvery
import io.mockk.mockk
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.ExperimentalCoroutinesApi
import kotlinx.coroutines.flow.firstOrNull
import kotlinx.coroutines.flow.flowOf
import kotlinx.coroutines.test.UnconfinedTestDispatcher
import kotlinx.coroutines.test.resetMain
import kotlinx.coroutines.test.runTest
import kotlinx.coroutines.test.setMain
import org.junit.After
import org.junit.Assert
import org.junit.Assert.assertEquals
import org.junit.Before
import org.junit.Test
@ExperimentalCoroutinesApi
class FavoriteViewModelTest {
private val getFavoriteMovieUseCase = mockk<GetFavoriteMovieUseCase>()
private val getFavoriteTvUseCase = mockk<GetFavoriteTvUseCase>()
private val coroutineDispatcher = UnconfinedTestDispatcher()
private lateinit var viewModel: FavoriteViewModel
@Before
fun setup() {
Dispatchers.setMain(coroutineDispatcher)
viewModel =
FavoriteViewModel(
getFavoriteMovieUseCase,
getFavoriteTvUseCase,
coroutineDispatcher,
)
}
@After
fun tearDown() {
Dispatchers.resetMain()
}
@Test
fun `fetchData should update state with favorite movies and tvs`() =
runTest {
val movies = listOf<Movie>(mockk())
val tvs = listOf<Tv>(mockk())
coEvery { getFavoriteMovieUseCase.invoke() } returns flowOf(movies)
coEvery { getFavoriteTvUseCase.invoke() } returns flowOf(tvs)
viewModel.fetchData()
Assert.assertEquals(
viewModel.uiState.value,
FavoriteContract.UiState(
isLoading = false,
listMovies = movies,
listTvs = tvs,
),
)
}
@Test
fun `onUiEvent Navigate should send Effect Navigate`() =
runTest {
val router: Router = mockk()
viewModel.onUiEvent(UiEvent.Navigate(router))
assertEquals(Effect.Navigate(router), viewModel.effects.firstOrNull())
}
@Test
fun `initialState should return UiState with default values`() {
val initialState = viewModel.initialState()
assertEquals(FavoriteContract.UiState(), initialState)
}
@Test
fun `updateState should update the state`() =
runTest {
viewModel.updateState { copy(isLoading = true) }
assertEquals(
FavoriteContract.UiState(isLoading = true),
viewModel.uiState.value,
)
}
}
| 0
|
Kotlin
|
0
| 0
|
277fc502e04753aa81295f167523691033ae8fd0
| 3,027
|
Instaflix
|
Apache License 2.0
|
app/src/main/java/dev/vivvvek/seekerdemo/ui/theme/Theme.kt
|
2307vivek
| 595,118,282
| false
| null |
/*
* Copyright 2023 Vivek Singh
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package dev.vivvvek.seekerdemo.ui.theme
import androidx.compose.material.MaterialTheme
import androidx.compose.material.darkColors
import androidx.compose.material.lightColors
import androidx.compose.runtime.Composable
import androidx.compose.ui.graphics.Color
private val DarkColorPalette = darkColors(
primary = Purple200,
primaryVariant = Purple700,
secondary = Teal200,
background = Color(0xFF0F102B),
surface = Color.White,
onPrimary = Color.White,
onSecondary = Color.Black,
onBackground = Color.White,
onSurface = Color.White,
)
private val LightColorPalette = lightColors(
primary = Purple500,
primaryVariant = Purple700,
secondary = Teal200
/* Other default colors to override
background = Color.White,
surface = Color.White,
onPrimary = Color.White,
onSecondary = Color.Black,
onBackground = Color.Black,
onSurface = Color.Black,
*/
)
@Composable
fun SeekerTheme(content: @Composable () -> Unit) {
MaterialTheme(
colors = DarkColorPalette,
typography = Typography,
shapes = Shapes,
content = content
)
}
| 1
|
Kotlin
|
4
| 98
|
17f639093eca623930c75cd69ca44376e5116e62
| 1,736
|
Seeker
|
Apache License 2.0
|
filePickerLibrary/src/main/java/com/zwc/filepicker/filetype/ImageFileType.kt
|
MrZWC
| 667,748,262
| false
|
{"Java": 134345, "Kotlin": 79046}
|
package com.zwc.filepicker.filetype
/**
* ClassName VideoFileType
* User: zuoweichen
* Date: 2022/5/20 16:32
* Description: 适配过滤器
*/
object ImageFileType : FileType() {
override fun getFileFilter(): Array<String> {
return arrayOf(
"jpg",
"jpeg",
"png",
"gif",
"bmp",
"psd",
"tif",
"jfif",
)
}
override fun getFileTypeTitle(): String {
return "图片"
}
}
| 1
| null |
1
| 1
|
2730cf9a0a4ac66a19f1a9d3b74f189e2a3a1817
| 493
|
androidFilePicker
|
Apache License 2.0
|
app/src/main/java/com/kv/wanandroid/event/LoginEvent.kt
|
Vension
| 173,887,387
| false
|
{"Gradle": 4, "Java Properties": 2, "Shell": 1, "Ignore List": 3, "Batchfile": 1, "Markdown": 1, "Proguard": 2, "Kotlin": 207, "XML": 192, "Java": 23}
|
package com.kv.wanandroid.event
/**
* ========================================================
* 作 者:Vension
* 日 期:2018/11/21 15:37
* 描 述:
* ========================================================
*/
class LoginEvent(var isLogin: Boolean)
| 0
|
Kotlin
|
1
| 0
|
23b2cc2f851289af79ba7c53ce0c858706f13ba0
| 250
|
V-WanAndroid
|
Apache License 2.0
|
generator/src/main/kotlin/com/antwerkz/critter/CritterContext.kt
|
akoranne
| 113,503,519
| true
|
{"Kotlin": 79577, "Java": 22306}
|
package com.antwerkz.critter
import java.util.HashMap
@Suppress("UNCHECKED_CAST")
class CritterContext(val criteriaPkg: String? = null, var force: Boolean = false) {
val classes = HashMap<String, CritterClass>()
fun shouldGenerate(source: Long?, output: Long?): Boolean {
return force || source == null || output == null || output < source
}
fun add(critterClass: CritterClass) {
classes.put("${critterClass.pkgName}.${critterClass.name}", critterClass)
}
/*
fun lookup(name: String): CritterClass? {
var className: String
var pkgName: String = null
if (name.contains(".")) {
} else {
className = name
}
return resolve(pkgName, className)
}
*/
fun resolve(currentPkg: String? = null, name: String): CritterClass? {
return classes[name] ?: currentPkg?.let { classes["$currentPkg.$name"] }
}
fun isEmbedded(currentPkg: String? = null, name: String): Boolean {
return resolve(currentPkg, name)?.isEmbedded ?: false
}
}
| 0
|
Kotlin
|
0
| 0
|
4ba3e293cfab531b42ff709d1df02a3c22d6833c
| 1,061
|
critter
|
Apache License 2.0
|
client-android/lib/src/main/kotlin/stasis/client_android/lib/compression/Compression.kt
|
sndnv
| 153,169,374
| false
|
{"Scala": 3373826, "Kotlin": 1821771, "Dart": 853650, "Python": 363474, "Shell": 70265, "CMake": 8759, "C++": 4051, "HTML": 2655, "Dockerfile": 1942, "Ruby": 1330, "C": 691, "Swift": 594, "JavaScript": 516}
|
package stasis.client_android.lib.compression
import stasis.client_android.lib.model.EntityMetadata
import stasis.client_android.lib.model.SourceEntity
import stasis.client_android.lib.model.TargetEntity
import java.nio.file.Path
import java.util.Locale
interface Compression {
fun defaultCompression(): Compressor
fun disabledExtensions(): Set<String>
fun algorithmFor(entity: Path): String =
if (compressionAllowedFor(entity)) {
defaultCompression().name()
} else {
Identity.name()
}
fun encoderFor(entity: SourceEntity): Encoder =
compressionFor(entity.currentMetadata)
fun decoderFor(entity: TargetEntity): Decoder =
compressionFor(entity.existingMetadata)
private fun compressionAllowedFor(entity: Path): Boolean =
!disabledExtensions().any { extension -> entity.toString().endsWith(".$extension") }
private fun compressionFor(entity: EntityMetadata): Compressor =
when (entity) {
is EntityMetadata.File -> fromString(entity.compression)
is EntityMetadata.Directory -> throw IllegalArgumentException(
"Expected metadata for file but directory metadata for [${entity.path}] provided"
)
}
companion object {
operator fun invoke(
withDefaultCompression: String,
withDisabledExtensions: String
): Compression = invoke(
withDefaultCompression = fromString(compression = withDefaultCompression),
withDisabledExtensions = withDisabledExtensions
.split(",")
.map { it.trim() }
.filter { it.isNotEmpty() }
.distinct()
.toSet()
)
operator fun invoke(
withDefaultCompression: Compressor,
withDisabledExtensions: Set<String>
): Compression = object : Compression {
override fun defaultCompression(): Compressor = withDefaultCompression
override fun disabledExtensions(): Set<String> = withDisabledExtensions
}
fun fromString(compression: String): Compressor =
when (compression.lowercase(Locale.getDefault())) {
Deflate.name() -> Deflate
Gzip.name() -> Gzip
Identity.name() -> Identity
else -> throw IllegalArgumentException("Unsupported compression provided: [$compression]")
}
}
}
| 0
|
Scala
|
4
| 53
|
d7b3002880814039b332b3d5373a16b57637eb1e
| 2,483
|
stasis
|
Apache License 2.0
|
packages/graalvm/src/test/kotlin/elide/runtime/gvm/js/node/AbstractJsModuleTest.kt
|
elide-dev
| 506,113,888
| false
|
{"Kotlin": 4156801, "Rust": 130170, "Java": 51233, "Python": 7851, "JavaScript": 6037, "Ruby": 2474, "C": 1926, "RenderScript": 578, "Shell": 160, "Pkl": 102, "TypeScript": 78, "Swift": 23}
|
/*
* Copyright (c) 2024 Elide Technologies, Inc.
*
* Licensed under the MIT license (the "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* https://opensource.org/license/mit/
*
* Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
* an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under the License.
*/
@file:OptIn(DelicateElideApi::class)
package elide.runtime.gvm.js.node
import org.graalvm.polyglot.Value
import org.graalvm.polyglot.proxy.ProxyHashMap
import org.graalvm.polyglot.proxy.ProxyObject
import elide.runtime.core.DelicateElideApi
import elide.runtime.core.PolyglotEngineConfiguration
import elide.runtime.gvm.internals.intrinsics.js.base64.Base64Intrinsic
import elide.runtime.gvm.internals.intrinsics.js.console.ConsoleIntrinsic
import elide.runtime.gvm.internals.js.AbstractJsIntrinsicTest
import elide.runtime.gvm.internals.node.asserts.NodeAssertModule
import elide.runtime.gvm.internals.node.asserts.NodeAssertStrictModule
import elide.runtime.intrinsics.GuestIntrinsic
import elide.runtime.intrinsics.Symbol
import elide.runtime.plugins.env.EnvConfig
import elide.runtime.plugins.env.environment
import elide.runtime.plugins.js.JavaScript
import elide.runtime.plugins.js.javascript
import elide.runtime.plugins.vfs.VfsConfig
import elide.runtime.plugins.vfs.vfs
internal abstract class AbstractJsModuleTest<T: GuestIntrinsic> : AbstractJsIntrinsicTest<T>() {
abstract val moduleName: String
open fun EnvConfig.configureEnvironment() {
// nothing
}
open fun VfsConfig.configureVfs() {
// nothing
}
@OptIn(DelicateElideApi::class)
protected val polyglotContext by lazy {
engine.acquire()
}
open val supportsEsm: Boolean get() = true
open val supportsCjs: Boolean get() = true
override fun configureEngine(config: PolyglotEngineConfiguration) {
config.apply {
install(JavaScript)
environment { configureEnvironment() }
vfs { configureVfs() }
}
}
private fun beforeExec(
bind: Boolean,
bindAssert: Boolean = true,
bindConsole: Boolean = true,
bindBase64: Boolean = true,
) {
// install bindings under test, if directed
val target = polyglotContext.bindings(JavaScript)
// prep intrinsic bindings under test
val langBindings = if (bind) {
val group = HashMap<Symbol, Any>()
val binding = GuestIntrinsic.MutableIntrinsicBindings.Factory.wrap(group)
provide().install(binding)
if (bindBase64 && !group.any { it.key.symbol.contains("Base64") }) {
Base64Intrinsic().install(binding)
}
if (bindConsole && !group.any { it.key.symbol.contains("console") }) {
ConsoleIntrinsic().install(binding)
}
if (bindAssert && !group.any { it.key.symbol.contains("assert") }) {
NodeAssertModule().install(binding)
NodeAssertStrictModule().install(binding)
}
group
} else {
emptyMap()
}
// prep internal bindings
val internalBindings: MutableMap<String, Any?> = mutableMapOf()
langBindings.forEach {
if (it.key.isInternal) {
internalBindings[it.key.internalSymbol] = it.value
}
}
// install bindings under test (public only so far)
for (binding in langBindings) {
if (binding.key.isInternal) {
continue
}
target.putMember(binding.key.symbol, binding.value)
}
// shim primordials
val primordialsProxy = object: ProxyObject, ProxyHashMap {
override fun getMemberKeys(): Array<String> = internalBindings.keys.toTypedArray()
override fun hasMember(key: String?): Boolean = key != null && key in internalBindings
override fun hasHashEntry(key: Value?): Boolean = key != null && key.asString() in internalBindings
override fun getHashSize(): Long = internalBindings.size.toLong()
override fun getHashEntriesIterator(): Any = internalBindings.entries.iterator()
override fun putMember(key: String?, value: Value?) {
// no-op
}
override fun putHashEntry(key: Value?, value: Value?) {
// no-op
}
override fun getMember(key: String?): Any? = when (key) {
null -> null
else -> internalBindings[key]
}
override fun getHashValue(key: Value?): Any? = getMember(key?.asString())
}
target.putMember("primordials", primordialsProxy)
}
protected fun require(module: String = moduleName, bind: Boolean = true): Value {
beforeExec(bind)
return polyglotContext.javascript(
// language=js
"""require("$module");"""
)
}
protected fun import(module: String = moduleName, bind: Boolean = true): Value {
val modname = module.split(":").last()
val modsymbol = if ("/" in modname) modname.split("/").first() else modname
beforeExec(bind)
return polyglotContext.javascript(
// language=js
"""
import $modsymbol from "$modname";
$modsymbol;
""".trimIndent(),
esm = true,
)
}
protected fun load(module: String = moduleName, bind: Boolean = true): Value = import(module, bind)
}
| 39
|
Kotlin
|
16
| 97
|
652036fb4e8394e8ad1aced2f4bbfaa9e00a5181
| 5,330
|
elide
|
MIT License
|
components-core/src/main/java/com/adyen/checkout/components/core/Item.kt
|
Adyen
| 91,104,663
| false
| null |
/*
* Copyright (c) 2019 <NAME>.
*
* This file is open source and available under the MIT license. See the LICENSE file for more info.
*
* Created by caiof on 27/5/2019.
*/
package com.adyen.checkout.components.core
import com.adyen.checkout.core.exception.ModelSerializationException
import com.adyen.checkout.core.internal.data.model.ModelObject
import com.adyen.checkout.core.internal.data.model.getStringOrNull
import kotlinx.parcelize.Parcelize
import org.json.JSONException
import org.json.JSONObject
@Parcelize
data class Item(
var id: String? = null,
var name: String? = null,
) : ModelObject() {
companion object {
private const val ID = "id"
private const val NAME = "name"
@JvmField
val SERIALIZER: Serializer<Item> = object : Serializer<Item> {
override fun serialize(modelObject: Item): JSONObject {
return try {
JSONObject().apply {
putOpt(ID, modelObject.id)
putOpt(NAME, modelObject.name)
}
} catch (e: JSONException) {
throw ModelSerializationException(Item::class.java, e)
}
}
override fun deserialize(jsonObject: JSONObject): Item {
return Item(
id = jsonObject.getStringOrNull(ID),
name = jsonObject.getStringOrNull(NAME),
)
}
}
}
}
| 28
|
Kotlin
|
59
| 96
|
1f000e27e07467f3a30bb3a786a43de62be003b2
| 1,495
|
adyen-android
|
MIT License
|
app/src/main/java/jp/juggler/subwaytooter/util/LinkHelper.kt
|
tateisu
| 89,120,200
| false
| null |
package jp.juggler.subwaytooter.util
import jp.juggler.subwaytooter.api.entity.Acct
import jp.juggler.subwaytooter.api.entity.Host
import jp.juggler.subwaytooter.api.entity.HostAndDomain
import jp.juggler.subwaytooter.api.entity.TootAccount
import jp.juggler.util.findOrNull
import jp.juggler.util.groupEx
interface LinkHelper : HostAndDomain {
// SavedAccountのロード時にhostを供給する必要があった
override val apiHost: Host
// fun findAcct(url : String?) : String? = null
// fun colorFromAcct(acct : String?) : AcctColor? = null
override val apDomain: Host
val misskeyVersion: Int
get() = 0
val isMisskey: Boolean
get() = misskeyVersion > 0
// FIXME もし将来別のサービスにも対応するなら、ここは書き直す必要がある
val isMastodon: Boolean
get() = misskeyVersion <= 0
// user とか user@host とかを user@host に変換する
// nullや空文字列なら ?@? を返す
fun getFullAcct(src: Acct?): Acct = when {
src?.username?.isEmpty() != false -> Acct.UNKNOWN
src.host?.isValid == true -> src
else -> src.followHost(apDomain.valid() ?: apiHost.valid() ?: Host.UNKNOWN)
}
companion object {
val unknown = object : LinkHelper {
override val apiHost: Host = Host.UNKNOWN
override val apDomain: Host = Host.UNKNOWN
}
fun create(apiHostArg: Host, apDomainArg: Host? = null, misskeyVersion: Int = 0) =
object : LinkHelper {
override val apiHost: Host = apiHostArg
// fun findAcct(url : String?) : String? = null
// fun colorFromAcct(acct : String?) : AcctColor? = null
override val apDomain: Host = apDomainArg ?: apiHostArg
override val misskeyVersion: Int
get() = misskeyVersion
}
}
}
fun LinkHelper.matchHost(src: String?) = apiHost.match(src) || apDomain.match(src)
fun LinkHelper.matchHost(src: Host?) = apiHost == src || apDomain == src
fun LinkHelper.matchHost(src: LinkHelper) =
apiHost == src.apiHost || apDomain == src.apDomain ||
apDomain == src.apiHost || apiHost == src.apDomain
fun LinkHelper.matchHost(src: TootAccount) =
apiHost == src.apiHost || apDomain == src.apDomain ||
apDomain == src.apiHost || apiHost == src.apDomain
// user や user@host から user@host を返す
fun getFullAcctOrNull(
rawAcct: Acct,
url: String,
hostDomain1: HostAndDomain? = null,
hostDomain2: HostAndDomain? = null
) =
if (rawAcct.isValidFull) {
// 最初から有効なfull acctがあればそれを使う
rawAcct
} else {
// URL中のホスト名を使うが、引数でホストとドメインの対応が提供されていればドメインへの変換を試みる
val host = TootAccount.reHostInUrl.matcher(url)
.findOrNull()?.groupEx(1)?.let { Host.parse(it) }
if (host == null) {
null
} else {
Acct.parse(
rawAcct.username,
when (host) {
hostDomain1?.apiHost -> hostDomain1.apDomain
hostDomain2?.apiHost -> hostDomain2.apDomain
else -> host
}
).validFull() // apDomainが ? だった場合など
}
}
| 26
|
Kotlin
|
17
| 137
|
77be9f9396eee9a2e3ee5cef71c80857a1c73615
| 3,124
|
SubwayTooter
|
Apache License 2.0
|
src/main/kotlin/io/openfuture/api/component/web3/event/Decoder.kt
|
OpenFuturePlatform
| 134,381,311
| false
| null |
package io.openfuture.api.component.web3.event
import io.openfuture.api.domain.event.Event
import org.web3j.abi.FunctionReturnDecoder
import org.web3j.abi.TypeReference
import org.web3j.abi.Utils
import org.web3j.abi.datatypes.Type
interface Decoder<T : Event> {
fun decode(addressScaffold: String, rawData: String): T
fun getResponse(rawData: String, signature: List<TypeReference<*>>): List<Type<Any>> =
FunctionReturnDecoder.decode(rawData, Utils.convert(signature))
}
| 11
|
JavaScript
|
7
| 42
|
4cf6df0407c9a941bd1e0b6d01a9ab05f4db0ef6
| 496
|
open-api
|
Apache License 2.0
|
app/src/main/java/jp/seo/station/ekisagasu/repository/impl/PrefectureRepositoryImpl.kt
|
Seo-4d696b75
| 247,417,963
| false
| null |
package jp.seo.station.ekisagasu.repository.impl
import android.content.Context
import android.util.SparseArray
import jp.seo.station.ekisagasu.R
import jp.seo.station.ekisagasu.repository.PrefectureRepository
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
import javax.inject.Inject
class PrefectureRepositoryImpl @Inject constructor() : PrefectureRepository {
private var _prefectures: SparseArray<String>? = null
override suspend fun setData(context: Context) = withContext(Dispatchers.IO) {
try {
val stream = context.resources.openRawResource(R.raw.prefecture)
val reader = stream.bufferedReader()
val array = SparseArray<String>()
reader.lines().forEach { line ->
val data = line.split(",")
if (data.size == 2) {
val id = data[0].toInt()
array.put(id, data[1])
}
}
_prefectures = array
} catch (e: Exception) {
throw RuntimeException("fail to init prefecture names")
}
}
override fun getName(code: Int): String {
if (code < 1 || code > 47) return "unknown"
return _prefectures?.get(code) ?: "not-init"
}
}
| 1
|
Kotlin
|
0
| 0
|
99cda72b3a3b68a99254ce578595f5270674f536
| 1,278
|
checkhelper
|
MIT License
|
buildSrc/src/main/java/co/accelerator/dependencies/library/android/AndroidLibraryDependencies.kt
|
yml-org
| 504,124,065
| false
| null |
package co.accelerator.dependencies.library.android
object AndroidLibraryDependencies {
val prod = AndroidLibraryProductionDependencies
val integrationTest = AndroidLibraryTestDependencies
val unitTest = AndroidLibraryJvmUnitTestDependencies
}
| 1
|
Kotlin
|
2
| 5
|
2b5162b3e687d81546d9c7ce7a666b3a2b6df889
| 257
|
ynetwork-android
|
Apache License 2.0
|
css-gg/src/commonMain/kotlin/compose/icons/cssggicons/ChevronUpR.kt
|
DevSrSouza
| 311,134,756
| false
|
{"Kotlin": 36719092}
|
package compose.icons.cssggicons
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.PathFillType.Companion.EvenOdd
import androidx.compose.ui.graphics.PathFillType.Companion.NonZero
import androidx.compose.ui.graphics.SolidColor
import androidx.compose.ui.graphics.StrokeCap
import androidx.compose.ui.graphics.StrokeCap.Companion.Butt
import androidx.compose.ui.graphics.StrokeJoin
import androidx.compose.ui.graphics.StrokeJoin.Companion.Miter
import androidx.compose.ui.graphics.vector.ImageVector
import androidx.compose.ui.graphics.vector.ImageVector.Builder
import androidx.compose.ui.graphics.vector.path
import androidx.compose.ui.unit.dp
import compose.icons.CssGgIcons
public val CssGgIcons.ChevronUpR: ImageVector
get() {
if (_chevronUpR != null) {
return _chevronUpR!!
}
_chevronUpR = Builder(name = "ChevronUpR", defaultWidth = 24.0.dp, defaultHeight = 24.0.dp,
viewportWidth = 24.0f, viewportHeight = 24.0f).apply {
path(fill = SolidColor(Color(0xFF000000)), stroke = null, strokeLineWidth = 0.0f,
strokeLineCap = Butt, strokeLineJoin = Miter, strokeLineMiter = 4.0f,
pathFillType = NonZero) {
moveTo(14.828f, 14.828f)
lineTo(16.243f, 13.414f)
lineTo(12.0f, 9.172f)
lineTo(7.757f, 13.414f)
lineTo(9.172f, 14.828f)
lineTo(12.0f, 12.0f)
lineTo(14.828f, 14.828f)
close()
}
path(fill = SolidColor(Color(0xFF000000)), stroke = null, strokeLineWidth = 0.0f,
strokeLineCap = Butt, strokeLineJoin = Miter, strokeLineMiter = 4.0f,
pathFillType = EvenOdd) {
moveTo(1.0f, 19.0f)
curveTo(1.0f, 21.209f, 2.791f, 23.0f, 5.0f, 23.0f)
horizontalLineTo(19.0f)
curveTo(21.209f, 23.0f, 23.0f, 21.209f, 23.0f, 19.0f)
verticalLineTo(5.0f)
curveTo(23.0f, 2.791f, 21.209f, 1.0f, 19.0f, 1.0f)
horizontalLineTo(5.0f)
curveTo(2.791f, 1.0f, 1.0f, 2.791f, 1.0f, 5.0f)
verticalLineTo(19.0f)
close()
moveTo(5.0f, 21.0f)
horizontalLineTo(19.0f)
curveTo(20.105f, 21.0f, 21.0f, 20.105f, 21.0f, 19.0f)
verticalLineTo(5.0f)
curveTo(21.0f, 3.895f, 20.105f, 3.0f, 19.0f, 3.0f)
horizontalLineTo(5.0f)
curveTo(3.895f, 3.0f, 3.0f, 3.895f, 3.0f, 5.0f)
verticalLineTo(19.0f)
curveTo(3.0f, 20.105f, 3.895f, 21.0f, 5.0f, 21.0f)
close()
}
}
.build()
return _chevronUpR!!
}
private var _chevronUpR: ImageVector? = null
| 17
|
Kotlin
|
25
| 571
|
a660e5f3033e3222e3553f5a6e888b7054aed8cd
| 2,877
|
compose-icons
|
MIT License
|
app/src/main/java/com/devvailonge/flip/features/categories/create/domain/CategoryCreateUseCase.kt
|
devvailonge
| 358,834,978
| false
| null |
package com.devvailonge.flip.features.categories.create.domain
import android.app.Application
import androidx.lifecycle.LiveData
import androidx.lifecycle.liveData
import com.devvailonge.flip.FlipApplication
import com.devvailonge.flip.R
import com.devvailonge.flip.base.AppDataBase
import com.devvailonge.flip.features.categories.create.presentation.CategoryCreateState
import com.devvailonge.flip.features.categories.data.CategoryDao
import com.devvailonge.flip.features.categories.data.CategoryEntity
import com.devvailonge.flip.features.categories.data.CategoryImage
class CreateCategoryUseCase(
application: Application,
private val categoryDao: CategoryDao = AppDataBase.getDataBase(application).categoryDao()
) {
fun perform(name: String, categoryImage: CategoryImage?): LiveData<CategoryCreateState> {
return liveData {
emit(CategoryCreateState.Loading)
try {
name
.trim()
.takeIf { it.isNotEmpty() }
?.let {
categoryImage?.let {
val result = categoryDao
.insert(CategoryEntity(name = name, categoryImage = it.name))
emit(CategoryCreateState.Success(result, R.string.create_category_success))
} ?: run {
emit(CategoryCreateState.Error(R.string.missing_category_image))
}
} ?: run{
emit(CategoryCreateState.Error(R.string.missing_category_name))
}
} catch (exception: Exception) {
emit(CategoryCreateState.Error(R.string.create_category_failed))
}
}
}
companion object {
fun create(): CreateCategoryUseCase {
return CreateCategoryUseCase(FlipApplication.instance)
}
}
}
| 0
|
Kotlin
|
0
| 1
|
509f44593e4dbe8338f02179e3366c8b228c267f
| 1,936
|
flip
|
MIT License
|
build-app/example/FileManager/app/src/main/java/com/android/samples/filemanager/FileUtils.kt
|
wickimassoy
| 269,890,421
| true
|
{"C++": 23211, "Kotlin": 15854, "CMake": 12971, "Java": 5752, "Lua": 5257, "C": 2024, "Python": 1642, "Shell": 168}
|
/*
* Copyright 2020 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.android.samples.filemanager
import android.content.Intent
import android.os.Environment
import android.webkit.MimeTypeMap
import androidx.appcompat.app.AppCompatActivity
import androidx.core.content.FileProvider
import java.io.File
private const val AUTHORITY = "${BuildConfig.APPLICATION_ID}.provider"
fun getMimeType(url: String): String {
val ext = MimeTypeMap.getFileExtensionFromUrl(url)
return MimeTypeMap.getSingleton().getMimeTypeFromExtension(ext) ?: "text/plain"
}
fun getFilesList(selectedItem: File): List<File> {
val rawFilesList:List<File>? = selectedItem.listFiles()?.filter { !it.isHidden }
val fodlerList:List<File>? = rawFilesList?.filter{it.isDirectory}?.sortedBy{it.name}
val fileList:List<File>? = rawFilesList?.filter{it.isFile}?.sortedBy{it.name}
return if (selectedItem == Environment.getExternalStorageDirectory()) {
//rawFilesList?.toList() ?: listOf()
(fodlerList?.toList() ?: listOf()) + (fileList?.toList() ?: listOf())
} else {
listOf(selectedItem.parentFile) + (fodlerList?.toList() ?: listOf()) + (fileList?.toList() ?: listOf())
}
}
fun renderParentLink(activity: AppCompatActivity): String {
return activity.getString(R.string.go_parent_label)
}
fun renderItem(activity: AppCompatActivity, file: File): String {
return if (file.isDirectory) {
activity.getString(R.string.folder_item, file.name)
} else {
activity.getString(R.string.file_item, file.name)
}
}
fun openFile(activity: AppCompatActivity, selectedItem: File) {
// Get URI and MIME type of file
val uri = FileProvider.getUriForFile(activity.applicationContext, AUTHORITY, selectedItem)
val mime: String = getMimeType(uri.toString())
// Open file with user selected app
val intent = Intent(Intent.ACTION_VIEW)
intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION)
intent.setDataAndType(uri, mime)
return activity.startActivity(intent)
}
| 0
|
C++
|
1
| 2
|
ba3eef6e633403e11611b3bd60ca615bebb2ab1c
| 2,574
|
termux-ndk
|
Apache License 2.0
|
src/test/kotlin/co/nums/intellij/aem/htl/editor/actions/HtlTypingActionTestBase.kt
|
karollewandowski
| 74,054,504
| false
| null |
package co.nums.intellij.aem.htl.editor.actions
import co.nums.intellij.aem.htl.HtlTestBase
import co.nums.intellij.aem.htl.file.HtlFileType
abstract class HtlTypingActionTestBase : HtlTestBase() {
protected fun doTest(given: String, typeChar: Char, expected: String) {
myFixture.configureByText(HtlFileType, given)
myFixture.type(typeChar)
myFixture.checkResult(expected)
}
}
| 0
|
Kotlin
|
8
| 26
|
9e76302b897bddb9ce6721d67787e92be575794f
| 413
|
aem-intellij-plugin
|
MIT License
|
app/src/androidTest/java/com/devdaniel/marvelapp/util/Hooks.kt
|
Cerverussz
| 534,818,141
| false
|
{"Kotlin": 112667}
|
package com.devdaniel.marvelapp.util
import androidx.annotation.IdRes
import androidx.annotation.StringRes
import androidx.appcompat.widget.AppCompatImageButton
import androidx.recyclerview.widget.RecyclerView
import androidx.test.espresso.Espresso.onView
import androidx.test.espresso.ViewInteraction
import androidx.test.espresso.action.ViewActions.click
import androidx.test.espresso.assertion.ViewAssertions.matches
import androidx.test.espresso.contrib.RecyclerViewActions
import androidx.test.espresso.matcher.ViewMatchers.hasDescendant
import androidx.test.espresso.matcher.ViewMatchers.isDescendantOfA
import androidx.test.espresso.matcher.ViewMatchers.isDisplayed
import androidx.test.espresso.matcher.ViewMatchers.withId
import androidx.test.espresso.matcher.ViewMatchers.withParent
import androidx.test.espresso.matcher.ViewMatchers.withText
import com.google.android.material.R
import org.hamcrest.CoreMatchers.allOf
import org.hamcrest.CoreMatchers.containsString
import org.hamcrest.CoreMatchers.instanceOf
fun checkViewIsDisplayedByText(viewText: String) {
onView(withText(viewText)).check(matches(isDisplayed()))
}
fun performClickInViewPositionRecyclerView(
@IdRes viewId: Int,
@IdRes childViewId: Int,
position: Int
) {
onView(withId(viewId)).perform(
RecyclerViewActions.actionOnItemAtPosition<RecyclerView.ViewHolder>(
position,
clickOnViewChild(childViewId)
)
)
}
fun checkViewWithIdAndPartialTextIsDisplayed(@IdRes viewId: Int, viewText: String) {
onView(withId(viewId))
.check(matches(withText(containsString(viewText))))
.check(matches(isDisplayed()))
}
fun checkCustomViewWithIdAndTextIsDisplayedWithParentId(
@IdRes parentViewId: Int,
@IdRes viewId: Int,
viewText: String
) {
onView(
allOf(
withId(viewId),
isDescendantOfA(withId(parentViewId))
)
).check(matches(withText(viewText)))
}
fun checkViewInRecyclerWithIdAndTextIsDisplayed(
@IdRes viewId: Int,
viewText: String,
position: Int
) {
onView(withId(viewId)).check(
matches(
recyclerItemAtPosition(
position,
hasDescendant(
withText(viewText)
)
)
)
)
}
fun checkViewWithIdAndTextIsDisplayed(@IdRes viewId: Int, viewText: String) {
onView(withId(viewId))
.check(matches(withText(viewText)))
.check(matches(isDisplayed()))
}
fun checkViewWithIdAndTextIsDisplayed(@IdRes viewId: Int, @StringRes viewText: Int) {
onView(withId(viewId))
.check(matches(withText(viewText)))
.check(matches(isDisplayed()))
}
fun performClickOnBackButtonInToolbar(@IdRes viewId: Int) {
onView(
allOf(
instanceOf(AppCompatImageButton::class.java),
withParent(withId(viewId))
)
).perform(click())
}
fun checkSnackBarIsDisplayed(withText: String): ViewInteraction {
return onView(
allOf(
withId(R.id.snackbar_text),
withText(withText)
)
)
}
| 0
|
Kotlin
|
1
| 0
|
1b0ca033cd11b712a9b8f3080c0731fcd9622832
| 3,112
|
MarvelApp
|
MIT License
|
Images2/app/src/main/java/com/example/images/GalleryViewModel.kt
|
BennyZhang-Canviz
| 255,919,665
| false
| null |
package com.example.images
import android.app.Application
import androidx.lifecycle.AndroidViewModel
import androidx.paging.toLiveData
class GalleryViewModel(application: Application) : AndroidViewModel(application) {
val photos = PixabayDataSourceFactory(application).toLiveData(1)
fun loadImages(){
photos.value?.dataSource?.invalidate()
}
}
| 0
|
Kotlin
|
0
| 0
|
55ae049d5c880b67251e40cf658c4535d52cd017
| 368
|
Android
|
Apache License 2.0
|
Repairs/app/src/test/java/com/rooio/repairs/ChangeLocationSettingsActivityTest.kt
|
roopairs
| 212,211,326
| false
|
{"XML": 431086, "Kotlin": 299391, "Java": 26386}
|
package com.rooio.repairs
import android.app.Application
import android.content.Intent
import android.widget.Button
import android.widget.Spinner
import android.widget.TextView
import androidx.test.ext.junit.runners.AndroidJUnit4
import com.android.volley.RequestQueue
import org.json.JSONObject
import org.junit.Assert.assertEquals
import org.junit.Assert.assertThat
import org.junit.Before
import org.junit.Test
import org.junit.runner.RunWith
import org.mockito.Mock
import org.mockito.Mockito.mock
import org.robolectric.Robolectric
import org.robolectric.Shadows
@RunWith(AndroidJUnit4::class)
class ChangeLocationSettingsActivityTest {
private lateinit var activity: ChangeLocationSettings
@Mock
val queue: RequestQueue = mock(RequestQueue::class.java)
@Before
@Throws(Exception::class)
fun setUp() {
RestApi.userLocationID = "Test"
RestApi.queue = queue
activity = Robolectric.buildActivity(ChangeLocationSettings::class.java)
.create()
.resume()
.get()
}
@Test
fun testChangeLocation() {
val button = activity.findViewById(R.id.changeLocation) as Button
button.performClick()
val expectedIntent = Intent(activity, LocationSettings::class.java)
val actual: Intent = Shadows.shadowOf(Application()).nextStartedActivity
assertEquals(expectedIntent.component, actual.component)
}
@Test
fun testChangeLocationResponseFunc() {
activity.responseFunc.apply(JSONObject()
.put("physical_address", "1 Grand Ave."))
val currLocation = activity.findViewById(R.id.currentLocation) as TextView
assertEquals(currLocation.text.toString(), "1 Grand Ave.")
}
@Test
fun testChangeLocationErrorFunc() {
activity.errorFunc.apply("Server error")
val error = activity.findViewById(R.id.errorMessage) as TextView
assertEquals(error.text.toString(), "Server error")
}
@Test
fun testClickProviderSpinner() {
val spinner = activity.findViewById(R.id.settings_spinner) as Spinner
spinner.setSelection(0)
val expectedIntent = Intent(activity, PreferredProvidersSettings::class.java)
val actual: Intent = Shadows.shadowOf(Application()).nextStartedActivity
assertEquals(expectedIntent.component, actual.component)
}
}
| 0
|
XML
|
0
| 0
|
e81487aba0a997812769e893dc8e34d21935647f
| 2,396
|
Rooio
|
MIT License
|
src/main/kotlin/com/ort/firewolf/domain/service/message/system/PrivateSystemMessageDomainService.kt
|
h-orito
| 282,923,189
| false
|
{"Kotlin": 928429, "Batchfile": 522, "Shell": 454}
|
package com.ort.firewolf.domain.service.message.system
import com.ort.firewolf.domain.model.player.Player
import com.ort.firewolf.domain.model.village.Village
import com.ort.firewolf.domain.model.village.participant.VillageParticipant
import com.ort.firewolf.domain.service.message.MessageTypeDomainService
import org.springframework.stereotype.Service
@Service
class PrivateSystemMessageDomainService : MessageTypeDomainService {
override fun isViewable(
village: Village,
myself: VillageParticipant?,
player: Player?,
day: Int
): Boolean = village.isViewablePrivateSystemMessage() || myself?.isViewablePrivateSystemMessage() ?: false
}
| 0
|
Kotlin
|
0
| 0
|
8c553f8d4d87c11398e240fb94a1627d1c4a26dd
| 681
|
firewolf-api
|
MIT License
|
kotlin-react-router-dom/src/jsMain/generated/react/router/dom/useFetchers.kt
|
JetBrains
| 93,250,841
| false
|
{"Kotlin": 11571203, "JavaScript": 155592}
|
// Generated by Karakum - do not modify it manually!
@file:JsModule("react-router-dom")
package react.router.dom
import remix.run.router.Fetcher
/**
* Provides all fetchers currently on the page. Useful for layouts and parent
* routes that need to provide pending/optimistic UI regarding the fetch.
*/
external fun useFetchers(): js.core.ReadonlyArray<Fetcher<*>>
| 28
|
Kotlin
|
173
| 1,250
|
3c11ef0b33e2901f3079f7ad5eb5b5cfc27b6a9d
| 371
|
kotlin-wrappers
|
Apache License 2.0
|
app/src/main/java/top/eviarch/simplenote/ui/screen/WebViewContainer.kt
|
Yttehs-HDX
| 763,306,615
| false
|
{"Kotlin": 106052}
|
package top.eviarch.simplenote.ui.screen
import android.annotation.SuppressLint
import android.webkit.WebChromeClient
import android.webkit.WebSettings
import android.webkit.WebView
import android.webkit.WebViewClient
import androidx.compose.runtime.Composable
import androidx.compose.ui.viewinterop.AndroidView
@SuppressLint("SetJavaScriptEnabled")
@Composable
fun WebViewContainer(url: String) {
AndroidView(factory = { context ->
WebView(context).apply {
settings.javaScriptEnabled = true
webViewClient = WebViewClient()
webChromeClient = WebChromeClient()
settings.cacheMode = WebSettings.LOAD_CACHE_ELSE_NETWORK
loadUrl(url)
}
})
}
| 0
|
Kotlin
|
0
| 0
|
ff992e10ec7b79c01ef0cce72eaef909de262435
| 722
|
Simple-Note
|
Apache License 2.0
|
Kawa/src/main/kotlin/sibwaf/kawa/analysis/DelegatingStatementAnalyzer.kt
|
dya-tel
| 332,540,419
| false
| null |
package sibwaf.kawa.analysis
import sibwaf.kawa.AnalyzerState
import sibwaf.kawa.DataFrame
import spoon.reflect.code.CtStatement
class DelegatingStatementAnalyzer(private val analyzers: List<StatementAnalyzer>) : StatementAnalyzer {
override fun supports(statement: CtStatement): Boolean {
return analyzers.isNotEmpty() && analyzers.any { it.supports(statement) }
}
override suspend fun analyze(state: AnalyzerState, statement: CtStatement): DataFrame {
for (analyzer in analyzers) {
if (analyzer.supports(statement)) {
return analyzer.analyze(state, statement)
}
}
throw IllegalArgumentException("Unsupported statement: $statement")
}
}
| 0
|
Kotlin
|
0
| 0
|
f3ff039c6204a659e67554617178a78dc695d1f9
| 730
|
Kawa
|
MIT License
|
app/src/main/java/com/asanarebel/android/ui/base/MvpPresenter.kt
|
ajaysaini-sgvu
| 120,072,531
| false
| null |
package com.asanarebel.android.ui.base
interface MvpPresenter<V : MvpView> {
fun onAttach(mvpView: V)
fun onDetach()
fun handleApiError(error: Any)
}
| 0
|
Kotlin
|
0
| 3
|
f7a0dd5887be597d06c6654fd40e6bf9a76ad42a
| 167
|
search-github-repo
|
Apache License 2.0
|
kotlin-electron/src/jsMain/generated/electron/PowerSaveBlocker.kt
|
JetBrains
| 93,250,841
| false
|
{"Kotlin": 11411371, "JavaScript": 154302}
|
package electron
typealias PowerSaveBlocker = electron.core.PowerSaveBlocker
| 28
|
Kotlin
|
173
| 1,250
|
9e9dda28cf74f68b42a712c27f2e97d63af17628
| 79
|
kotlin-wrappers
|
Apache License 2.0
|
app/src/main/java/com/example/hairharmony/activities/LogIn.kt
|
007-Shivam
| 745,058,133
| false
|
{"Kotlin": 22490}
|
package com.example.hairharmony.activities
import android.content.Context
import androidx.compose.runtime.Composable
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.tooling.preview.Preview
import androidx.navigation.NavHostController
import androidx.navigation.compose.rememberNavController
@Composable
fun LogIn(context: Context = LocalContext.current, navController: NavHostController) {
}
@Preview
@Composable
fun LogInPreview() {
val context = LocalContext.current
val navController = rememberNavController()
LogIn(context, navController)
}
| 0
|
Kotlin
|
1
| 0
|
063bbd2a4400b1377ca12bfbeb287d2b4890596b
| 589
|
Hair_Harmony
|
MIT License
|
app/src/main/kotlin/net/yuzumone/bergamio/di/AppComponent.kt
|
yuzumone
| 81,647,607
| false
| null |
package net.yuzumone.bergamio.di
import dagger.Component
import net.yuzumone.bergamio.MainApp
import javax.inject.Singleton
@Singleton
@Component(modules = arrayOf(AppModule::class))
interface AppComponent {
fun inject(application: MainApp)
fun plus(module: ActivityModule): ActivityComponent
}
| 0
|
Kotlin
|
0
| 0
|
a2335b62dfdc5e182616e9a13c722c138708cfda
| 305
|
bergamio
|
Apache License 2.0
|
app/src/test/java/com/wajahatkarim/tipcalculator/model/RestaurantCalculatorTest.kt
|
wajahatkarim3
| 136,158,316
| false
|
{"Kotlin": 22011}
|
package com.wajahatkarim.tipcalculator.model
import org.junit.Assert.assertEquals
import org.junit.Before
import org.junit.Test
class RestaurantCalculatorTest {
lateinit var calculator: RestaurantCalculator
@Before
fun setup()
{
calculator = RestaurantCalculator()
}
@Test
fun testCalculatorTip()
{
val baseTc = TipCalculation(checkAmount = 10.00)
val testVals = listOf(baseTc.copy(tipPct = 25, tipAmount = 2.5, grandTotal = 12.50),
baseTc.copy(tipPct = 15, tipAmount = 1.5, grandTotal = 11.50),
baseTc.copy(tipPct = 18, tipAmount = 1.8, grandTotal = 11.80))
testVals.forEach {
assertEquals(it, calculator.calculateTip(it.checkAmount, it.tipPct))
}
}
}
| 0
|
Kotlin
|
0
| 2
|
6a7ca5ee77e577610db2086400415b9db1c4e11e
| 783
|
TipCalculator-MVVM-Example
|
Apache License 2.0
|
Android/app/src/main/java/com/plantry/data/dto/response/profile/ResponseProfileInfoDto.kt
|
GDSC-SWU
| 736,526,220
| false
|
{"Kotlin": 312709, "Java": 284329, "Python": 1946, "Dockerfile": 370}
|
package com.plantry.data.dto.response.profile
import kotlinx.serialization.SerialName
import kotlinx.serialization.Serializable
@Serializable
data class ResponseProfileInfoDto(
@SerialName("email")
val email: String?,
@SerialName("nickname")
val nickname: String?,
@SerialName("profileImagePath")
val profileImagePath: String?
)
| 0
|
Kotlin
|
0
| 3
|
7a8074ba1a76027fe09077dd490c8c7eb8a87c9f
| 355
|
2024-Plantry-SolutionChallenge
|
MIT License
|
app/src/main/java/com/g/pocketmal/util/EpisodeType.kt
|
glodanif
| 847,288,195
| false
|
{"Kotlin": 517413, "Java": 112995}
|
package com.g.pocketmal.util
enum class EpisodeType(val type: Int) {
EPISODE(0),
CHAPTER(1),
VOLUME(2)
}
| 0
|
Kotlin
|
1
| 8
|
1a7fe52c2dc59dd3bf4eaeb3d9bb64d469e10845
| 118
|
Pocket_MAL
|
MIT License
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.