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/wannabit/io/cosmostaion/model/viewModel/neutron/DaoViewModel.kt
|
cosmostation
| 418,314,439
| false
|
{"Java": 9401828, "Kotlin": 430818}
|
package wannabit.io.cosmostaion.model.viewModel.neutron
import android.content.Context
import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import com.google.gson.Gson
import kotlinx.coroutines.launch
import wannabit.io.cosmostaion.base.chains.ChainConfig
import wannabit.io.cosmostaion.dao.Account
import wannabit.io.cosmostaion.model.repository.neutron.DaoRepository
import wannabit.io.cosmostaion.model.viewModel.BaseViewModel
import wannabit.io.cosmostaion.network.res.neutron.*
import kotlin.Pair
class DaoViewModel(private val daoRepository: DaoRepository) : BaseViewModel() {
private var _daoListData = MutableLiveData<List<ResDaoData?>?>()
val daoListData: LiveData<List<ResDaoData?>?> get() = _daoListData
fun loadDaoListData(chainConfig: ChainConfig) = backScope.launch {
try {
daoRepository.getDaoData(chainConfig).let { response ->
if (response.isSuccessful) {
_daoListData.postValue(response.body())
} else {
_daoListData.postValue(null)
}
}
} catch (_: Exception) { }
}
private var _daoProposalListData = MutableLiveData<List<Pair<String?, ProposalData?>>>()
val daoProposalListData: LiveData<List<Pair<String?, ProposalData?>>> get() = _daoProposalListData
fun loadDaoProposalListData(chainConfig: ChainConfig, contractAddressList: MutableList<String?>) = backScope.launch {
try {
val proposalMap = contractAddressList.flatMap { address ->
val response = daoRepository.getDaoProposalListData(chainConfig, address)
Gson().fromJson(response, ResProposalData::class.java).proposals.map { Pair(address, it) }
}
_daoProposalListData.postValue(proposalMap)
} catch (_: Exception) { }
}
private var _daoMyVoteStatusData = MutableLiveData<List<ResMyVoteStatus>>()
val daoMyVoteStatusData: LiveData<List<ResMyVoteStatus>> get() = _daoMyVoteStatusData
fun loadDaoProposalMyVoteData(c: Context, chainConfig: ChainConfig, account: Account) = backScope.launch {
try {
daoRepository.getMyVoteStatus(c, chainConfig, account).let { response ->
if (response.isSuccessful) {
_daoMyVoteStatusData.postValue(response.body())
}
}
} catch (_: Exception) { }
}
private var _daoMemberStatus = MutableLiveData<ResMemberList?>()
val daoMemberStatus: LiveData<ResMemberList?> get() = _daoMemberStatus
fun loadMemberList(chainConfig: ChainConfig, contractAddress: String?) = backScope.launch {
try {
daoRepository.getListMemberData(chainConfig, contractAddress)?.let { response ->
if (response.isNotEmpty()) {
_daoMemberStatus.postValue(Gson().fromJson(response, ResMemberList::class.java))
} else {
_daoMemberStatus.postValue(null)
}
}
} catch (_: Exception) {
_daoMemberStatus.postValue(null)
}
}
}
| 0
|
Java
|
51
| 66
|
4a89189b1f7f053a1cd97a1e0371940bad52bd05
| 3,138
|
cosmostation-android
|
MIT License
|
kotlin-electron/src/jsMain/generated/electron/common/LoginItemSettings.kt
|
JetBrains
| 93,250,841
| false
|
{"Kotlin": 11411371, "JavaScript": 154302}
|
package electron.common
typealias LoginItemSettings = electron.core.LoginItemSettings
| 28
|
Kotlin
|
173
| 1,250
|
9e9dda28cf74f68b42a712c27f2e97d63af17628
| 88
|
kotlin-wrappers
|
Apache License 2.0
|
app/src/main/java/eu/kanade/presentation/manga/MangaScreenConstants.kt
|
mihonapp
| 743,704,912
| false
| null |
package eu.kanade.presentation.manga
enum class DownloadAction {
NEXT_1_CHAPTER,
NEXT_5_CHAPTERS,
NEXT_10_CHAPTERS,
CUSTOM,
UNREAD_CHAPTERS,
ALL_CHAPTERS,
}
enum class EditCoverAction {
EDIT,
DELETE,
}
enum class MangaScreenItem {
INFO_BOX,
ACTION_ROW,
DESCRIPTION_WITH_TAG,
CHAPTER_HEADER,
CHAPTER,
}
| 72
| null |
447
| 9,867
|
f3a2f566c8a09ab862758ae69b43da2a2cd8f1db
| 357
|
mihon
|
Apache License 2.0
|
TabnineSelfHosted/src/main/java/com/tabnineSelfHosted/Initializer.kt
|
zxqfl
| 199,185,542
| false
| null |
package com.tabnineSelfHosted
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.application.PreloadingActivity
import com.intellij.openapi.components.ServiceManager
import com.intellij.openapi.progress.ProgressIndicator
import com.intellij.openapi.project.Project
import com.intellij.openapi.startup.StartupActivity
import com.tabnineCommon.chat.actions.AskChatAction
import com.tabnineCommon.lifecycle.initializeLifecycleEndpoints
import com.tabnineCommon.logging.initTabnineLogger
import com.tabnineCommon.notifications.ConnectionLostNotificationHandler
import com.tabnineCommon.userSettings.AppSettingsState
import com.tabnineSelfHosted.binary.lifecycle.UserInfoService
import java.util.concurrent.atomic.AtomicBoolean
class Initializer : PreloadingActivity(), StartupActivity {
override fun preload(indicator: ProgressIndicator) {
initialize()
}
override fun runActivity(project: Project) {
initialize()
}
private fun initialize() {
if (initialized.getAndSet(true) || ApplicationManager.getApplication().isUnitTestMode) {
return
}
initTabnineLogger()
connectionLostNotificationHandler.startConnectionLostListener()
val host = AppSettingsState.instance.cloud2Url
SelfHostedInitializer().initialize(host) {
AppSettingsState.instance.cloud2Url = it
}
AskChatAction.register()
initializeLifecycleEndpoints()
ServiceManager.getService(UserInfoService::class.java).startUpdateLoop()
}
companion object {
private val connectionLostNotificationHandler = ConnectionLostNotificationHandler()
private val initialized = AtomicBoolean(false)
}
}
| 38
| null |
57
| 509
|
1cc05157fdfd742059be88f00fb92bc58e005a1c
| 1,747
|
tabnine-intellij
|
MIT License
|
android/app/src/main/java/com/algorand/android/ui/send/shared/AddNoteBottomSheet.kt
|
perawallet
| 364,359,642
| false
|
{"Swift": 8753304, "Kotlin": 7709389, "Objective-C": 88978, "Shell": 7715, "Ruby": 4727, "C": 596}
|
/*
* Copyright 2022 Pera Wallet, LDA
* 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.algorand.android.ui.send.shared
import android.os.Bundle
import android.view.View
import androidx.navigation.fragment.navArgs
import com.algorand.android.R
import com.algorand.android.core.BaseBottomSheet
import com.algorand.android.databinding.BottomSheetAddNoteBinding
import com.algorand.android.customviews.toolbar.buttoncontainer.model.TextButton
import com.algorand.android.models.ToolbarConfiguration
import com.algorand.android.utils.setNavigationResult
import com.algorand.android.utils.viewbinding.viewBinding
class AddNoteBottomSheet : BaseBottomSheet(
layoutResId = R.layout.bottom_sheet_add_note
) {
private val binding by viewBinding(BottomSheetAddNoteBinding::bind)
private val args by navArgs<AddNoteBottomSheetArgs>()
private val toolbarConfiguration = ToolbarConfiguration(
titleResId = R.string.add_note,
startIconResId = R.drawable.ic_close,
startIconClick = ::navBack
)
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
configureToolbar()
configureInputLayout()
}
private fun configureInputLayout() {
binding.noteInputLayout.apply {
text = args.note.orEmpty()
addByteLimiter(NOTE_MAX_SIZE_IN_BYTE)
// If transaction note is xnote(locked note) then we should non-editable this area
if (!args.isInputFieldEnabled) {
setAsNonFocusable()
return
}
requestFocus()
}
}
private fun configureToolbar() {
binding.toolbar.apply {
configure(toolbarConfiguration)
setEndButton(button = TextButton(stringResId = R.string.done, onClick = ::onDoneClick))
}
}
private fun onDoneClick() {
setNavigationResult(ADD_NOTE_RESULT_KEY, binding.noteInputLayout.text)
navBack()
}
companion object {
private const val NOTE_MAX_SIZE_IN_BYTE = 1024
const val ADD_NOTE_RESULT_KEY = "add_note_result"
}
}
| 22
|
Swift
|
62
| 181
|
92fc77f73fa4105de82d5e87b03c1e67600a57c0
| 2,671
|
pera-wallet
|
Apache License 2.0
|
dsl/src/main/kotlin/io/cloudshiftdev/awscdkdsl/services/quicksight/CfnTemplateSectionBasedLayoutPaperCanvasSizeOptionsPropertyDsl.kt
|
cloudshiftinc
| 667,063,030
| false
| null |
@file:Suppress(
"RedundantVisibilityModifier",
"RedundantUnitReturnType",
"RemoveRedundantQualifierName",
"unused",
"UnusedImport",
"ClassName",
"REDUNDANT_PROJECTION",
"DEPRECATION"
)
package cloudshift.awscdk.dsl.services.quicksight
import cloudshift.awscdk.common.CdkDslMarker
import kotlin.String
import software.amazon.awscdk.IResolvable
import software.amazon.awscdk.services.quicksight.CfnAnalysis
/**
* The options for a paper canvas of a section-based layout.
*
* Example:
* ```
* // The code below shows an example of how to instantiate this type.
* // The values are placeholders you should change.
* import software.amazon.awscdk.services.quicksight.*;
* SectionBasedLayoutPaperCanvasSizeOptionsProperty sectionBasedLayoutPaperCanvasSizeOptionsProperty
* = SectionBasedLayoutPaperCanvasSizeOptionsProperty.builder()
* .paperMargin(SpacingProperty.builder()
* .bottom("bottom")
* .left("left")
* .right("right")
* .top("top")
* .build())
* .paperOrientation("paperOrientation")
* .paperSize("paperSize")
* .build();
* ```
*
* [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-quicksight-analysis-sectionbasedlayoutpapercanvassizeoptions.html)
*/
@CdkDslMarker
public class CfnAnalysisSectionBasedLayoutPaperCanvasSizeOptionsPropertyDsl {
private val cdkBuilder: CfnAnalysis.SectionBasedLayoutPaperCanvasSizeOptionsProperty.Builder =
CfnAnalysis.SectionBasedLayoutPaperCanvasSizeOptionsProperty.builder()
/**
* @param paperMargin Defines the spacing between the canvas content and the top, bottom, left,
* and right edges.
*/
public fun paperMargin(paperMargin: IResolvable) {
cdkBuilder.paperMargin(paperMargin)
}
/**
* @param paperMargin Defines the spacing between the canvas content and the top, bottom, left,
* and right edges.
*/
public fun paperMargin(paperMargin: CfnAnalysis.SpacingProperty) {
cdkBuilder.paperMargin(paperMargin)
}
/**
* @param paperOrientation The paper orientation that is used to define canvas dimensions.
* Choose one of the following options:.
* * PORTRAIT
* * LANDSCAPE
*/
public fun paperOrientation(paperOrientation: String) {
cdkBuilder.paperOrientation(paperOrientation)
}
/** @param paperSize The paper size that is used to define canvas dimensions. */
public fun paperSize(paperSize: String) {
cdkBuilder.paperSize(paperSize)
}
public fun build(): CfnAnalysis.SectionBasedLayoutPaperCanvasSizeOptionsProperty =
cdkBuilder.build()
}
| 4
| null |
0
| 3
|
c59c6292cf08f0fc3280d61e7f8cff813a608a62
| 2,650
|
awscdk-dsl-kotlin
|
Apache License 2.0
|
packages/mongodb-mql-model/src/test/kotlin/com/mongodb/jbplugin/mql/NodeTest.kt
|
mongodb-js
| 797,134,624
| false
|
{"Kotlin": 358451, "Shell": 1926, "Java": 906, "HTML": 254}
|
package com.mongodb.jbplugin.mql
import com.mongodb.jbplugin.mql.components.*
import org.junit.jupiter.api.Assertions.*
import org.junit.jupiter.api.Test
import org.junit.jupiter.params.ParameterizedTest
import org.junit.jupiter.params.provider.MethodSource
class NodeTest {
@Test
fun `is able to get a component if exists`() {
val node = Node<Unit?>(null, listOf(Named("myName")))
val named = node.component<Named>()
assertEquals("myName", named!!.name)
}
@Test
fun `returns null if a component does not exist`() {
val node = Node<Unit?>(null, listOf(Named("myName")))
val named = node.component<HasFieldReference<Unit?>>()
assertNull(named)
}
@Test
fun `is able to get all components of the same type`() {
val node =
Node<Unit?>(
null,
listOf(
HasFieldReference(HasFieldReference.Known(null, "field1")),
HasFieldReference(
HasFieldReference.Known(
null,
"field2",
),
),
),
)
val fieldReferences = node.components<HasFieldReference<Unit?>>()
assertEquals("field1", (fieldReferences[0].reference as HasFieldReference.Known).fieldName)
assertEquals("field2", (fieldReferences[1].reference as HasFieldReference.Known).fieldName)
}
@Test
fun `returns true if a component of that type exists`() {
val node =
Node<Unit?>(
null,
listOf(HasFieldReference(HasFieldReference.Known(null, "field1"))),
)
val hasFieldReferences = node.hasComponent<HasFieldReference<Unit?>>()
assertTrue(hasFieldReferences)
}
@Test
fun `returns false if a component of that type does not exist`() {
val node =
Node<Unit?>(
null,
listOf(HasFieldReference(HasFieldReference.Known(null, "field1"))),
)
val hasNamedComponent = node.hasComponent<Named>()
assertFalse(hasNamedComponent)
}
@MethodSource("validComponents")
@ParameterizedTest
fun `does support the following component`(
component: Component,
componentClass: Class<Component>,
) {
val node =
Node<Unit?>(
null,
listOf(
component,
),
)
assertNotNull(node.component(componentClass))
}
companion object {
@JvmStatic
fun validComponents(): Array<Array<Any>> =
arrayOf(
arrayOf(HasChildren<Unit?>(emptyList()), HasChildren::class.java),
arrayOf(HasCollectionReference(HasCollectionReference.Unknown), HasCollectionReference::class.java),
arrayOf(
HasCollectionReference(HasCollectionReference.Known(Namespace("db", "coll"))),
HasCollectionReference::class.java,
),
arrayOf(
HasCollectionReference(HasCollectionReference.OnlyCollection("coll")),
HasCollectionReference::class.java,
),
arrayOf(HasFieldReference(HasFieldReference.Unknown), HasFieldReference::class.java),
arrayOf(HasFieldReference(HasFieldReference.Known(null, "abc")), HasFieldReference::class.java),
arrayOf(HasFilter<Unit?>(Node(null, emptyList())), HasFilter::class.java),
arrayOf(HasValueReference(HasValueReference.Unknown), HasValueReference::class.java),
arrayOf(HasValueReference(HasValueReference.Constant(null, 123, BsonInt32)),
HasValueReference::class.java),
arrayOf(HasValueReference(HasValueReference.Runtime(null, BsonInt32)), HasValueReference::class.java),
arrayOf(HasValueReference(HasValueReference.Unknown), HasValueReference::class.java),
arrayOf(Named("abc"), Named::class.java),
)
}
}
| 2
|
Kotlin
|
0
| 3
|
73a49b3e70883af142010f872b5951a067724717
| 4,145
|
intellij
|
Apache License 2.0
|
server/src/main/kotlin/org/kryptonmc/krypton/entity/KryptonLivingEntity.kt
|
KryptonMC
| 255,582,002
| false
| null |
/*
* This file is part of the Krypton project, licensed under the Apache License v2.0
*
* Copyright (C) 2021-2023 KryptonMC and the contributors of the Krypton project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.kryptonmc.krypton.entity
import org.kryptonmc.api.entity.ArmorSlot
import org.kryptonmc.api.entity.EquipmentSlot
import org.kryptonmc.api.entity.Hand
import org.kryptonmc.api.entity.LivingEntity
import org.kryptonmc.api.entity.attribute.Attribute
import org.kryptonmc.api.entity.attribute.AttributeType
import org.kryptonmc.api.fluid.Fluid
import org.kryptonmc.api.util.Vec3i
import org.kryptonmc.api.world.Difficulty
import org.kryptonmc.krypton.entity.attribute.AttributeMap
import org.kryptonmc.krypton.entity.attribute.AttributeSupplier
import org.kryptonmc.krypton.entity.attribute.DefaultAttributes
import org.kryptonmc.krypton.entity.attribute.KryptonAttribute
import org.kryptonmc.krypton.entity.attribute.KryptonAttributeType
import org.kryptonmc.krypton.entity.attribute.KryptonAttributeTypes
import org.kryptonmc.krypton.entity.attribute.downcast
import org.kryptonmc.krypton.entity.ai.memory.Brain
import org.kryptonmc.krypton.entity.metadata.MetadataKeys
import org.kryptonmc.krypton.entity.player.KryptonPlayer
import org.kryptonmc.krypton.entity.serializer.EntitySerializer
import org.kryptonmc.krypton.entity.serializer.LivingEntitySerializer
import org.kryptonmc.krypton.item.KryptonItemStack
import org.kryptonmc.krypton.entity.components.KryptonEquipable
import org.kryptonmc.krypton.entity.util.EquipmentSlots
import org.kryptonmc.krypton.packet.out.play.PacketOutUpdateAttributes
import org.kryptonmc.krypton.world.KryptonWorld
@Suppress("LeakingThis")
abstract class KryptonLivingEntity(world: KryptonWorld) : KryptonEntity(world), LivingEntity, KryptonEquipable {
abstract override val type: KryptonEntityType<KryptonLivingEntity>
override val serializer: EntitySerializer<out KryptonLivingEntity>
get() = LivingEntitySerializer
final override val maxHealth: Float
get() = attributes.getValue(KryptonAttributeTypes.MAX_HEALTH).toFloat()
override var absorption: Float = 0F
final override var isDead: Boolean = false
final override var deathTime: Int = 0
final override var hurtTime: Int = 0
final override var lastHurtTimestamp: Int = 0
private var tickCount = 0
val attributes: AttributeMap = AttributeMap(DefaultAttributes.get(type))
open val brain: Brain = Brain()
private var headYaw = position.yaw
@Suppress("MemberVisibilityCanBePrivate")
var lastHurtByMob: KryptonLivingEntity? = null
set(value) {
field = value
lastHurtByMobTime = tickCount
}
private var lastHurtByMobTime = 0
@Suppress("MemberVisibilityCanBePrivate")
var lastHurtByPlayer: KryptonPlayer? = null
set(value) {
field = value
lastHurtByPlayerTime = tickCount
}
private var lastHurtByPlayerTime = 0
open val isBaby: Boolean
get() = false
final override var isGliding: Boolean
get() = data.getFlag(MetadataKeys.Entity.FLAGS, FLAG_ENTITY_GLIDING)
set(value) = data.setFlag(MetadataKeys.Entity.FLAGS, FLAG_ENTITY_GLIDING, value)
final override var isUsingItem: Boolean
get() = data.getFlag(MetadataKeys.LivingEntity.FLAGS, FLAG_USING_ITEM)
set(value) = data.setFlag(MetadataKeys.LivingEntity.FLAGS, FLAG_USING_ITEM, value)
final override var hand: Hand
get() = if (data.getFlag(MetadataKeys.LivingEntity.FLAGS, FLAG_OFFHAND)) Hand.OFF else Hand.MAIN
set(value) = data.setFlag(MetadataKeys.LivingEntity.FLAGS, FLAG_OFFHAND, value == Hand.OFF)
final override var isInRiptideSpinAttack: Boolean
get() = data.getFlag(MetadataKeys.LivingEntity.FLAGS, FLAG_IN_RIPTIDE_SPIN_ATTACK)
set(value) = data.setFlag(MetadataKeys.LivingEntity.FLAGS, FLAG_IN_RIPTIDE_SPIN_ATTACK, value)
override var health: Float
get() = data.get(MetadataKeys.LivingEntity.HEALTH)
set(value) = data.set(MetadataKeys.LivingEntity.HEALTH, value)
var arrowCount: Int
get() = data.get(MetadataKeys.LivingEntity.ARROWS)
set(value) = data.set(MetadataKeys.LivingEntity.ARROWS, value)
var stingerCount: Int
get() = data.get(MetadataKeys.LivingEntity.STINGERS)
set(value) = data.set(MetadataKeys.LivingEntity.STINGERS, value)
final override var sleepingPosition: Vec3i?
get() = data.get(MetadataKeys.LivingEntity.BED_LOCATION)
set(value) = data.set(MetadataKeys.LivingEntity.BED_LOCATION, value)
init {
data.set(MetadataKeys.LivingEntity.HEALTH, maxHealth)
}
override fun defineData() {
super.defineData()
data.define(MetadataKeys.LivingEntity.FLAGS, 0)
data.define(MetadataKeys.LivingEntity.HEALTH, 1F)
data.define(MetadataKeys.LivingEntity.POTION_EFFECT_COLOR, 0)
data.define(MetadataKeys.LivingEntity.POTION_EFFECT_AMBIENCE, false)
data.define(MetadataKeys.LivingEntity.ARROWS, 0)
data.define(MetadataKeys.LivingEntity.STINGERS, 0)
data.define(MetadataKeys.LivingEntity.BED_LOCATION, null)
}
override fun postTick() {
super.postTick()
if (attributes.isDirty()) sendPacketToViewersAndSelf(PacketOutUpdateAttributes.create(id, attributes.dirty()))
}
abstract override fun getEquipment(slot: EquipmentSlot): KryptonItemStack
override fun getHeldItem(hand: Hand): KryptonItemStack {
if (hand == Hand.MAIN) return getEquipment(EquipmentSlot.MAIN_HAND)
if (hand == Hand.OFF) return getEquipment(EquipmentSlot.OFF_HAND)
error("Tried to get held item for hand $hand that should not exist! Please sure that no plugins are injecting entries in to enums!")
}
override fun setHeldItem(hand: Hand, item: KryptonItemStack) {
when (hand) {
Hand.MAIN -> setEquipment(EquipmentSlot.MAIN_HAND, item)
Hand.OFF -> setEquipment(EquipmentSlot.OFF_HAND, item)
else -> error("Tried to set held item for hand $hand that should not exist! Please sure that no plugins are injecting " +
"entries in to enums!")
}
}
override fun getArmor(slot: ArmorSlot): KryptonItemStack = getEquipment(EquipmentSlots.fromArmorSlot(slot))
override fun setArmor(slot: ArmorSlot, item: KryptonItemStack) {
setEquipment(EquipmentSlots.fromArmorSlot(slot), item)
}
fun canAttack(target: KryptonLivingEntity): Boolean {
if (target is KryptonPlayer && world.difficulty === Difficulty.PEACEFUL) return false
return target.canBeSeenAsEnemy()
}
@Suppress("FunctionOnlyReturningConstant", "UnusedPrivateMember") // This will have logic in the future
fun canStandOnFluid(fluid: Fluid): Boolean = false
protected fun getAttribute(type: KryptonAttributeType): KryptonAttribute? = attributes.getAttribute(type)
override fun getAttribute(type: AttributeType): Attribute? = getAttribute(type.downcast())
final override fun isAlive(): Boolean = super.isAlive() && health > 0F
open fun canBeSeenAsEnemy(): Boolean = !isInvulnerable && canBeSeenByAnyone()
open fun canBeSeenByAnyone(): Boolean = isAlive()
open fun soundVolume(): Float = 1F
open fun voicePitch(): Float {
val babyFactor = if (isBaby) 1.5F else 1F
return (random.nextFloat() - random.nextFloat()) * 0.2F + babyFactor
}
fun killCredit(): KryptonLivingEntity? {
// TODO: Check combat tracker here
if (lastHurtByPlayer != null) return lastHurtByPlayer
if (lastHurtByMob != null) return lastHurtByMob
return null
}
override fun headYaw(): Float = headYaw
override fun showToViewer(viewer: KryptonPlayer) {
super.showToViewer(viewer)
viewer.connection.send(PacketOutUpdateAttributes.create(id, attributes.syncable()))
}
companion object {
private const val FLAG_ENTITY_GLIDING = 7
private const val FLAG_USING_ITEM = 0
private const val FLAG_OFFHAND = 1
private const val FLAG_IN_RIPTIDE_SPIN_ATTACK = 2
@JvmStatic
fun attributes(): AttributeSupplier.Builder = AttributeSupplier.builder()
.add(KryptonAttributeTypes.MAX_HEALTH)
.add(KryptonAttributeTypes.KNOCKBACK_RESISTANCE)
.add(KryptonAttributeTypes.MOVEMENT_SPEED)
.add(KryptonAttributeTypes.ARMOR)
.add(KryptonAttributeTypes.ARMOR_TOUGHNESS)
}
}
| 27
|
Kotlin
|
11
| 233
|
a9eff5463328f34072cdaf37aae3e77b14fcac93
| 9,080
|
Krypton
|
Apache License 2.0
|
src/main/kotlin/me/steven/indrev/gui/controllers/BiomassGeneratorController.kt
|
superJK921
| 297,734,676
| false
| null |
package me.steven.indrev.gui.controllers
import io.github.cottonmc.cotton.gui.widget.WGridPanel
import io.github.cottonmc.cotton.gui.widget.WItemSlot
import me.steven.indrev.IndustrialRevolution
import me.steven.indrev.gui.PatchouliEntryShortcut
import me.steven.indrev.gui.widgets.misc.WFuel
import me.steven.indrev.utils.configure
import me.steven.indrev.utils.identifier
import net.minecraft.entity.player.PlayerEntity
import net.minecraft.entity.player.PlayerInventory
import net.minecraft.screen.ScreenHandlerContext
import net.minecraft.util.Identifier
class BiomassGeneratorController(
syncId: Int,
playerInventory: PlayerInventory,
ctx: ScreenHandlerContext
) :
IRGuiController(
IndustrialRevolution.BIOMASS_GENERATOR_HANDLER,
syncId,
playerInventory,
ctx
), PatchouliEntryShortcut {
init {
val root = WGridPanel()
setRootPanel(root)
configure("block.indrev.biomass_generator", ctx, playerInventory, blockInventory, propertyDelegate)
// Fuel input
root.add(WItemSlot.of(blockInventory, 2), 4, 2)
// Burning widget
root.add(WFuel(propertyDelegate), 4, 1)
root.validate(this)
}
override fun canUse(player: PlayerEntity?): Boolean = true
override fun getEntry(): Identifier = identifier("machines/generators")
override fun getPage(): Int = 5
companion object {
val SCREEN_ID = identifier("biomass_generator")
}
}
| 1
| null |
1
| 1
|
c8d1b3ae534d177105f807c645db715346839840
| 1,477
|
Industrial-Revolution
|
Apache License 2.0
|
app/src/main/java/me/ppvan/metour/MainActivity.kt
|
quanminhhoanga
| 708,860,979
| false
|
{"Kotlin": 116676}
|
package me.ppvan.metour
import android.os.Bundle
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Surface
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.tooling.preview.Preview
import androidx.core.view.WindowCompat
import androidx.navigation.compose.NavHost
import androidx.navigation.compose.composable
import androidx.navigation.compose.rememberNavController
import me.ppvan.metour.ui.theme.MeTourTheme
import me.ppvan.metour.ui.view.HomeView
import me.ppvan.metour.ui.view.LoginView
import me.ppvan.metour.ui.view.RegisterView
import me.ppvan.metour.ui.view.TourDetailsView
class MainActivity : ComponentActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
WindowCompat.setDecorFitsSystemWindows(window, false)
setContent {
MeTourTheme {
// A surface container using the 'background' color from the theme
Surface(
modifier = Modifier.fillMaxSize(),
color = MaterialTheme.colorScheme.background
) {
MeTourApp()
}
}
}
}
}
@Composable
fun MeTourApp() {
val navigator = rememberNavController()
NavHost(navController = navigator, startDestination = Routes.Home.name) {
composable(route = Routes.Home.name) {
HomeView(navigateToDetails = { id -> navigator.navigate("${Routes.Tour.name}/${id}") })
}
composable(
route = "${Routes.Tour.name}/{id}"
) { backStackEntry ->
val id = backStackEntry.arguments.let {
if (it == null) {
"1"
} else {
it.getString("id", "1")
}
}
TourDetailsView(id = id.toInt()) {
navigator.popBackStack()
}
}
composable(route = Routes.Register.name) {
RegisterView()
}
composable(route = Routes.Login.name) {
LoginView()
}
}
}
enum class Routes {
Home, Tour, Register, Login
}
@Preview(showBackground = true)
@Composable
fun GreetingPreview() {
MeTourTheme {
MeTourApp()
}
}
| 0
|
Kotlin
|
0
| 0
|
612bc8a56344c7f1f7ce1ab61f01d55c11f52ed8
| 2,479
|
TourismMobileApp
|
MIT License
|
flowbinding-viewpager/src/androidTest/java/reactivecircus/flowbinding/viewpager/ViewPagerPageSelectedFlowTest.kt
|
mochadwi
| 326,126,160
| true
|
{"Kotlin": 469647, "Shell": 2411}
|
package reactivecircus.flowbinding.viewpager
import androidx.test.filters.LargeTest
import androidx.test.internal.runner.junit4.statement.UiThreadStatement.runOnUiThread
import androidx.viewpager.widget.ViewPager
import org.amshove.kluent.shouldEqual
import org.junit.Test
import reactivecircus.blueprint.testing.action.swipeLeftOnView
import reactivecircus.blueprint.testing.action.swipeRightOnView
import reactivecircus.flowbinding.testing.FlowRecorder
import reactivecircus.flowbinding.testing.launchTest
import reactivecircus.flowbinding.testing.recordWith
import reactivecircus.flowbinding.viewpager.fixtures.ViewPagerFragment
import reactivecircus.flowbinding.viewpager.test.R
@LargeTest
class ViewPagerPageSelectedFlowTest {
@Test
fun pageSelections_swipe() {
launchTest<ViewPagerFragment> {
val recorder = FlowRecorder<Int>(testScope)
getViewById<ViewPager>(R.id.viewPager).pageSelections().recordWith(recorder)
recorder.takeValue() shouldEqual 0
recorder.assertNoMoreValues()
swipeLeftOnView(R.id.viewPager)
recorder.takeValue() shouldEqual 1
recorder.assertNoMoreValues()
cancelTestScope()
swipeRightOnView(R.id.viewPager)
recorder.assertNoMoreValues()
}
}
@Test
fun pageSelections_programmatic() {
launchTest<ViewPagerFragment> {
val recorder = FlowRecorder<Int>(testScope)
val viewPager = getViewById<ViewPager>(R.id.viewPager)
viewPager.pageSelections().recordWith(recorder)
recorder.takeValue() shouldEqual 0
recorder.assertNoMoreValues()
runOnUiThread { viewPager.currentItem = 1 }
recorder.takeValue() shouldEqual 1
recorder.assertNoMoreValues()
cancelTestScope()
runOnUiThread { viewPager.currentItem = 0 }
recorder.assertNoMoreValues()
}
}
@Test
fun pageSelections_skipInitialValue() {
launchTest<ViewPagerFragment> {
val recorder = FlowRecorder<Int>(testScope)
val viewPager = getViewById<ViewPager>(R.id.viewPager)
viewPager.pageSelections()
.skipInitialValue()
.recordWith(recorder)
recorder.assertNoMoreValues()
runOnUiThread { viewPager.currentItem = 1 }
recorder.takeValue() shouldEqual 1
recorder.assertNoMoreValues()
cancelTestScope()
runOnUiThread { viewPager.currentItem = 0 }
recorder.assertNoMoreValues()
}
}
}
| 0
| null |
0
| 0
|
b2b56b9834cf003146193e9cfa3e2cb4e813439b
| 2,646
|
FlowBinding
|
Apache License 2.0
|
app/src/main/java/ro/alexmamo/firemag/domain/model/User.kt
|
alexmamo
| 569,800,514
| false
| null |
package ro.alexmamo.firemag.domain.model
data class User (
val uid: String,
val photoUrl: String,
val displayName: String,
val email: String
)
| 0
|
Kotlin
|
1
| 9
|
d648c129c9d9f0841b898b6c178170e404f35024
| 159
|
FireMag
|
Apache License 2.0
|
android/src/main/java/com/visioncamerafacetflite/VisionCameraFaceTflitePlugin.kt
|
edritech93
| 741,416,649
| false
|
{"Kotlin": 16619, "Swift": 15495, "TypeScript": 11777, "Ruby": 4407, "Objective-C": 3214, "JavaScript": 2205, "Objective-C++": 1568, "C": 103}
|
package com.visioncamerafacetflite
import android.graphics.Bitmap
import android.graphics.Canvas
import android.graphics.Matrix
import android.graphics.Rect
import android.graphics.RectF
import com.google.android.gms.tasks.Tasks
import com.google.mlkit.vision.common.InputImage
import com.google.mlkit.vision.common.internal.ImageConvertUtils
import com.google.mlkit.vision.face.Face
import com.google.mlkit.vision.face.FaceContour
import com.google.mlkit.vision.face.FaceDetection
import com.google.mlkit.vision.face.FaceDetectorOptions
import com.mrousavy.camera.frameprocessor.Frame
import com.mrousavy.camera.frameprocessor.FrameProcessorPlugin
import com.mrousavy.camera.frameprocessor.VisionCameraProxy
import com.mrousavy.camera.types.Orientation
import kotlin.math.ceil
class VisionCameraFaceTflitePlugin(proxy: VisionCameraProxy, options: Map<String, Any>?): FrameProcessorPlugin() {
private var faceDetectorOptions = FaceDetectorOptions.Builder()
.setPerformanceMode(FaceDetectorOptions.PERFORMANCE_MODE_FAST)
.setContourMode(FaceDetectorOptions.CONTOUR_MODE_NONE)
.setClassificationMode(FaceDetectorOptions.CLASSIFICATION_MODE_ALL)
.setMinFaceSize(0.15f)
.build()
private var faceDetector = FaceDetection.getClient(faceDetectorOptions)
private fun processBoundingBox(boundingBox: Rect): MutableMap<String, Any> {
val bounds: MutableMap<String, Any> = HashMap()
// Calculate offset (we need to center the overlay on the target)
val offsetX = (boundingBox.exactCenterX() - ceil(boundingBox.width().toDouble())) / 2.0f
val offsetY = (boundingBox.exactCenterY() - ceil(boundingBox.height().toDouble())) / 2.0f
val x = boundingBox.right + offsetX
val y = boundingBox.top + offsetY
bounds["x"] = boundingBox.centerX() + (boundingBox.centerX() - x)
bounds["y"] = boundingBox.centerY() + (y - boundingBox.centerY())
bounds["width"] = boundingBox.width().toDouble()
bounds["height"] = boundingBox.height().toDouble()
bounds["boundingCenterX"] = boundingBox.centerX().toDouble()
bounds["boundingCenterY"] = boundingBox.centerY().toDouble()
bounds["boundingExactCenterX"] = boundingBox.exactCenterX().toDouble()
bounds["boundingExactCenterY"] = boundingBox.exactCenterY().toDouble()
return bounds
}
private fun processFaceContours(face: Face): MutableMap<String, Any> {
// All faceContours
val faceContoursTypes = intArrayOf(
FaceContour.FACE,
FaceContour.LEFT_EYEBROW_TOP,
FaceContour.LEFT_EYEBROW_BOTTOM,
FaceContour.RIGHT_EYEBROW_TOP,
FaceContour.RIGHT_EYEBROW_BOTTOM,
FaceContour.LEFT_EYE,
FaceContour.RIGHT_EYE,
FaceContour.UPPER_LIP_TOP,
FaceContour.UPPER_LIP_BOTTOM,
FaceContour.LOWER_LIP_TOP,
FaceContour.LOWER_LIP_BOTTOM,
FaceContour.NOSE_BRIDGE,
FaceContour.NOSE_BOTTOM,
FaceContour.LEFT_CHEEK,
FaceContour.RIGHT_CHEEK
)
val faceContoursTypesStrings = arrayOf(
"FACE",
"LEFT_EYEBROW_TOP",
"LEFT_EYEBROW_BOTTOM",
"RIGHT_EYEBROW_TOP",
"RIGHT_EYEBROW_BOTTOM",
"LEFT_EYE",
"RIGHT_EYE",
"UPPER_LIP_TOP",
"UPPER_LIP_BOTTOM",
"LOWER_LIP_TOP",
"LOWER_LIP_BOTTOM",
"NOSE_BRIDGE",
"NOSE_BOTTOM",
"LEFT_CHEEK",
"RIGHT_CHEEK"
)
val faceContoursTypesMap: MutableMap<String, Any> = HashMap()
for (i in faceContoursTypesStrings.indices) {
val contour = face.getContour(faceContoursTypes[i])
val points = contour!!.points
val pointsArray: MutableCollection<Any> = ArrayList()
for (j in points.indices) {
val currentPointsMap: MutableMap<String, Any> = HashMap()
currentPointsMap["x"] = points[j].x.toDouble()
currentPointsMap["y"] = points[j].y.toDouble()
pointsArray.add(currentPointsMap)
}
faceContoursTypesMap[faceContoursTypesStrings[contour.faceContourType - 1]] = pointsArray
}
return faceContoursTypesMap
}
override fun callback(frame: Frame, params: Map<String, Any>?): Any? {
try {
val mediaImage = frame.image
if (mediaImage != null) {
val image = InputImage.fromMediaImage(mediaImage, Orientation.PORTRAIT.toDegrees())
val task = faceDetector.process(image)
val faces = Tasks.await(task)
val array: MutableCollection<Any> = ArrayList()
for (face in faces) {
val map: MutableMap<String, Any> = HashMap()
val bmpFrameResult = ImageConvertUtils.getInstance().getUpRightBitmap(image)
val bmpFaceResult = Bitmap.createBitmap(
Constant.TF_OD_API_INPUT_SIZE,
Constant.TF_OD_API_INPUT_SIZE,
Bitmap.Config.ARGB_8888
)
val faceBB = RectF(face.boundingBox)
val cvFace = Canvas(bmpFaceResult)
val sx = Constant.TF_OD_API_INPUT_SIZE.toFloat() / faceBB.width()
val sy = Constant.TF_OD_API_INPUT_SIZE.toFloat() / faceBB.height()
val matrix = Matrix()
matrix.postTranslate(-faceBB.left, -faceBB.top)
matrix.postScale(sx, sy)
cvFace.drawBitmap(bmpFrameResult, matrix, null)
val imageResult: String = Convert().getBase64Image(bmpFaceResult).toString()
map["rollAngle"] =
face.headEulerAngleZ.toDouble()
map["pitchAngle"] =
face.headEulerAngleX.toDouble()
map["yawAngle"] = face.headEulerAngleY.toDouble()
map["leftEyeOpenProbability"] = face.leftEyeOpenProbability!!.toDouble()
map["rightEyeOpenProbability"] = face.rightEyeOpenProbability!!.toDouble()
map["smilingProbability"] = face.smilingProbability!!.toDouble()
// val contours = processFaceContours(face);
val bounds = processBoundingBox(face.boundingBox)
map["bounds"] = bounds
// map["contours"] = contours
map["imageResult"] = imageResult
array.add(map)
}
return array
} else {
return null
}
} catch (e: Exception) {
e.printStackTrace().toString()
return null
}
}
}
| 0
|
Kotlin
|
0
| 0
|
96b2f4567ded44ade57a00fed608bf4a896e3c97
| 6,117
|
vision-camera-face-tflite
|
MIT License
|
app/src/main/java/io/github/takusan23/akaridroid/ui/component/AkariCanvasCompose.kt
|
takusan23
| 584,131,815
| false
| null |
package io.github.takusan23.akaridroid.ui.component
import androidx.compose.foundation.Image
import androidx.compose.foundation.gestures.detectDragGestures
import androidx.compose.foundation.layout.Box
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.asImageBitmap
import androidx.compose.ui.graphics.painter.BitmapPainter
import androidx.compose.ui.input.pointer.pointerInput
import io.github.takusan23.akaridroid.data.CanvasElementData
import io.github.takusan23.akaridroid.ui.tool.AkariCanvas
/**
* キャンバス
* Bitmapにしたのを表示しているので、多分エンコード結果と同じになるはずです。
*
* @param modifier [Modifier]
* @param elementList 描画する要素
* @param videoHeight 動画の高さ
* @param videoWidth 動画の幅
*/
@Composable
fun AkariCanvasCompose(
modifier: Modifier = Modifier,
videoWidth: Int,
videoHeight: Int,
elementList: List<CanvasElementData>,
) {
val (bitmap, canvas) = remember { AkariCanvas.createCanvas(videoWidth, videoHeight) }
val hittingElement = remember { mutableStateOf<CanvasElementData?>(null) }
LaunchedEffect(key1 = elementList) {
AkariCanvas.render(canvas, elementList)
}
Box {
Image(
modifier = modifier
// ElementList 更新時に再起動するため
.pointerInput(key1 = elementList) {
detectDragGestures(
onDragStart = { (x, y) ->
val hitBox = AkariCanvas.calcElementHitBox(elementList)
hittingElement.value = hitBox.firstOrNull { (_, rectF) -> rectF.contains(x, y) }?.first
},
onDragEnd = {
hittingElement.value = null
},
onDrag = { change, (x, y) ->
change.consume()
}
)
},
painter = BitmapPainter(bitmap.asImageBitmap()),
contentDescription = null
)
if (hittingElement.value != null) {
Text(text = "あたり = ${hittingElement.value}")
}
}
}
| 0
|
Kotlin
|
0
| 0
|
f1b481e30a226607467099ac16aa819553784728
| 2,325
|
AkariDroid
|
Apache License 2.0
|
fastadapter-extensions-paged/src/main/java/com/mikepenz/fastadapter/paged/PagedItemListImpl.kt
|
mikepenz
| 48,688,603
| false
| null |
package com.mikepenz.fastadapter.paged
import android.util.Log
import androidx.paging.AsyncPagedListDiffer
import androidx.paging.PagedList
import androidx.recyclerview.widget.AsyncDifferConfig
import androidx.recyclerview.widget.ListUpdateCallback
import com.mikepenz.fastadapter.GenericItem
import com.mikepenz.fastadapter.IAdapterNotifier
import com.mikepenz.fastadapter.IIdDistributor
import com.mikepenz.fastadapter.utils.DefaultItemList
/**
* A item list implementation to support the PagedList from the `androidx.paging:paging-runtime` jetpack library
*/
@ExperimentalPagedSupport
open class PagedItemListImpl<Model, Item : GenericItem>(
listUpdateCallback: ListUpdateCallback,
differConfig: AsyncDifferConfig<Model>,
var placeholderInterceptor: (position: Int) -> Item = getDefaultPlaceholderInterceptor(),
var interceptor: (element: Model) -> Item?
) : DefaultItemList<Item>() {
val differ: AsyncPagedListDiffer<Model> = AsyncPagedListDiffer<Model>(listUpdateCallback, differConfig)
var idDistributor: IIdDistributor<Item> = IIdDistributor.DEFAULT as IIdDistributor<Item>
private val cache: HashMap<Model, Item> = hashMapOf()
/**
* Defines if the DefaultIdDistributor is used to provide an ID to all added items which do not yet define an id
*/
var isUseIdDistributor = true
override val items: MutableList<Item>
get() = differ.currentList?.mapNotNull { getItem(it) }?.toMutableList() ?: mutableListOf()// Note this is not efficient
override val isEmpty: Boolean
get() = differ.currentList?.isEmpty() == true
override fun get(position: Int): Item {
return differ.getItem(position)?.let { getItem(it) } ?: run {
Log.w(TAG, "Position currently contains a placeholder")
placeholderInterceptor.invoke(position)
}
}
override fun peek(position: Int): Item? {
return if (differ.itemCount > position) {
differ.currentList?.subList(position, position + 1)?.first()?.let { cache[it] }
} else {
null
}
}
private fun getItem(model: Model): Item? {
return cache[model] ?: run {
return interceptor.invoke(model)?.let {
if (isUseIdDistributor) {
idDistributor.checkId(it)
}
cache[model] = it
it
}
}
}
override fun getAdapterPosition(identifier: Long): Int = differ.currentList?.indexOfFirst { getItem(it)?.identifier == identifier }
?: throw RuntimeException("No item found at position")
/** Managed by the [PagedList] not supported to be managed via the [PagedModelAdapter] */
override fun remove(position: Int, preItemCount: Int) {
throw UnsupportedOperationException("Not supported")
}
/** Managed by the [PagedList] not supported to be managed via the [PagedModelAdapter] */
override fun removeRange(position: Int, itemCount: Int, preItemCount: Int) {
throw UnsupportedOperationException("Not supported")
}
/** Managed by the [PagedList] not supported to be managed via the [PagedModelAdapter] */
override fun move(fromPosition: Int, toPosition: Int, preItemCount: Int) {
throw UnsupportedOperationException("Not supported")
}
override fun size(): Int {
return differ.currentList?.size ?: 0
}
/** Managed by the [PagedList] not supported to be managed via the [PagedModelAdapter] */
override fun clear(preItemCount: Int) {
throw UnsupportedOperationException("Not supported")
}
/** Managed by the [PagedList] not supported to be managed via the [PagedModelAdapter] */
override fun set(position: Int, item: Item, preItemCount: Int) {
throw UnsupportedOperationException("Not supported")
}
/** Managed by the [PagedList] not supported to be managed via the [PagedModelAdapter] */
override fun addAll(items: List<Item>, preItemCount: Int) {
throw UnsupportedOperationException("Not supported")
}
/** Managed by the [PagedList] not supported to be managed via the [PagedModelAdapter] */
override fun addAll(position: Int, items: List<Item>, preItemCount: Int) {
throw UnsupportedOperationException("Not supported")
}
/** Managed by the [PagedList] not supported to be managed via the [PagedModelAdapter] */
override fun set(items: List<Item>, preItemCount: Int, adapterNotifier: IAdapterNotifier?) {
throw UnsupportedOperationException("Not supported")
}
/** Managed by the [PagedList] not supported to be managed via the [PagedModelAdapter] */
override fun setNewList(items: List<Item>, notify: Boolean) {
throw UnsupportedOperationException("Not supported")
}
/**
* Set the new list to be displayed.
*
* If a list is already being displayed, a diff will be computed on a background thread, which
* will dispatch Adapter.notifyItem events on the main thread.
*
* @param pagedList The new list to be displayed.
*/
fun submitList(pagedList: PagedList<Model>?) {
differ.submitList(pagedList)
}
/**
* Set the new list to be displayed.
*
* If a list is already being displayed, a diff will be computed on a background thread, which
* will dispatch Adapter.notifyItem events on the main thread.
*
* The commit callback can be used to know when the PagedList is committed, but note that it
* may not be executed. If PagedList B is submitted immediately after PagedList A, and is
* committed directly, the callback associated with PagedList A will not be run.
*
* @param pagedList The new list to be displayed.
* @param commitCallback Optional runnable that is executed when the PagedList is committed, if
* it is committed.
*/
fun submitList(pagedList: PagedList<Model>?, commitCallback: Runnable?) {
differ.submitList(pagedList, commitCallback)
}
/**
* Get the item from the current PagedList at the specified index.
*
* Note that this operates on both loaded items and null padding within the PagedList.
*
* @param position Index of item to get, must be >= 0, and < {@link #getItemCount()}.
* @return The item, or null, if a null placeholder is at the specified position.
*/
fun getItem(position: Int): Model? {
return differ.getItem(position)
}
/**
* Returns the PagedList currently being displayed by the Adapter.
*
* This is not necessarily the most recent list passed to [.submitList],
* because a diff is computed asynchronously between the new list and the current list before
* updating the currentList value. May be null if no PagedList is being presented.
*
* @return The list currently being displayed.
*
* @see AsyncPagedListDiffer.onCurrentListChanged
*/
fun getCurrentList(): PagedList<Model>? {
return differ.currentList
}
/**
* Add a PagedListListener to receive updates when the current PagedList changes.
*
* @param listener Listener to receive updates.
*
* @see getCurrentList
* @see removePagedListListener
*/
fun addPagedListListener(listener: AsyncPagedListDiffer.PagedListListener<Model>) {
differ.addPagedListListener(listener)
}
/**
* Removes a PagedListListener to receive updates when the current PagedList changes.
*
* @param listener Listener to receive updates.
*
* @see getCurrentList
* @see addPagedListListener
*/
fun removePagedListListener(listener: AsyncPagedListDiffer.PagedListListener<Model>) {
differ.removePagedListListener(listener)
}
companion object {
private const val TAG = "PagedItemListImpl"
/**
* Returns the default placeholder interceptor
*
* Note if your PagedItemList should contain placeholder, you have to provide a logic what the adapter should show while in placeholding state
*/
internal fun <Item : GenericItem> getDefaultPlaceholderInterceptor(): (Int) -> Item {
return { throw RuntimeException("No item found at position") }
}
}
}
| 9
| null |
500
| 3,827
|
77761873d8f5c469a3dcc49766e2960826bbe62b
| 8,309
|
FastAdapter
|
Apache License 2.0
|
src/main/kotlin/br/com/tecnoinfo/baseapi/mapper/PagetoPageDetMapper.kt
|
GilbertoMattos
| 587,541,296
| false
| null |
package br.com.tecnoinfo.baseapi.mapper
import br.com.tecnoinfo.baseapi.wrapper.response.PageDet
import org.springframework.data.domain.Page
import org.springframework.stereotype.Component
@Component
class PagetoPageDetMapper : Mapper<Page<*>, PageDet> {
override fun map(param: Page<*>): PageDet {
return PageDet(
totalRegistros = param.totalElements,
totalPage = param.totalPages,
pageNumber = param.number,
pageSize = param.size,
isLast = param.isLast,
isFirst = param.isFirst
)
}
}
| 0
|
Kotlin
|
0
| 0
|
bb9e50a1b243ea37c9d5de588165eddde74adaea
| 583
|
base-api
|
Apache License 2.0
|
app/src/main/java/org/ergoplatform/android/wallet/WalletFragment.kt
|
B2skk
| 424,350,097
| false
| null |
package org.ergoplatform.android.wallet
import android.os.Bundle
import android.text.format.DateUtils
import android.view.*
import android.view.animation.Animation
import android.view.animation.AnimationUtils
import androidx.fragment.app.Fragment
import androidx.fragment.app.findFragment
import androidx.navigation.fragment.NavHostFragment
import androidx.navigation.fragment.findNavController
import androidx.recyclerview.widget.DiffUtil
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.launch
import org.ergoplatform.ErgoAmount
import org.ergoplatform.android.AppDatabase
import org.ergoplatform.android.NodeConnector
import org.ergoplatform.android.R
import org.ergoplatform.android.databinding.CardWalletBinding
import org.ergoplatform.android.databinding.EntryWalletTokenBinding
import org.ergoplatform.android.databinding.FragmentWalletBinding
import org.ergoplatform.android.tokens.inflateAndBindTokenView
import org.ergoplatform.android.ui.navigateSafe
import java.util.*
class WalletFragment : Fragment() {
private var _binding: FragmentWalletBinding? = null
// save last shown wallet list in case view is destroyed
// this is to preserve user's scroll position
private var lastWalletList: List<WalletDbEntity> = emptyList()
// This property is only valid between onCreateView and
// onDestroyView.
private val binding get() = _binding!!
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setHasOptionsMenu(true)
}
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View {
_binding = FragmentWalletBinding.inflate(inflater, container, false)
binding.recyclerview.layoutManager = LinearLayoutManager(requireContext())
return binding.root
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
val walletAdapter = WalletAdapter(lastWalletList)
binding.recyclerview.adapter = walletAdapter
AppDatabase.getInstance(requireContext()).walletDao().getWalletsWithStates()
.observe(viewLifecycleOwner,
{ walletList ->
walletAdapter.walletList = walletList.sortedBy {
it.walletConfig.displayName?.toLowerCase(
Locale.getDefault()
)
}
lastWalletList = walletAdapter.walletList
binding.swipeRefreshLayout.visibility =
if (walletList.isEmpty()) View.GONE else View.VISIBLE
binding.emptyView.root.visibility =
if (walletList.isEmpty()) View.VISIBLE else View.GONE
})
binding.emptyView.cardRestoreWallet.setOnClickListener {
findNavController().navigate(R.id.restoreWalletFragmentDialog)
}
binding.emptyView.cardReadonlyWallet.setOnClickListener {
NavHostFragment.findNavController(requireParentFragment())
.navigate(R.id.addReadOnlyWalletFragmentDialog)
}
binding.emptyView.cardCreateWallet.setOnClickListener {
NavHostFragment.findNavController(requireParentFragment())
.navigate(R.id.createWalletDialog)
}
val nodeConnector = NodeConnector.getInstance()
val rotateAnimation =
AnimationUtils.loadAnimation(requireContext(), R.anim.rotate_indefinitely)
rotateAnimation.setAnimationListener(object : Animation.AnimationListener {
override fun onAnimationStart(animation: Animation?) {
}
override fun onAnimationEnd(animation: Animation?) {
}
override fun onAnimationRepeat(animation: Animation?) {
if (nodeConnector.isRefreshing.value == false) {
binding.ergoLogoBack.clearAnimation()
}
}
})
binding.swipeRefreshLayout.setOnRefreshListener {
if (!nodeConnector.refreshByUser(requireContext())) {
binding.swipeRefreshLayout.isRefreshing = false
}
}
nodeConnector.isRefreshing.observe(viewLifecycleOwner, { isRefreshing ->
if (!isRefreshing) {
binding.swipeRefreshLayout.isRefreshing = false
binding.connectionError.visibility =
if (nodeConnector.lastHadError) View.VISIBLE else View.INVISIBLE
refreshTimeSinceSyncLabel()
} else {
binding.ergoLogoBack.clearAnimation()
binding.ergoLogoBack.startAnimation(rotateAnimation)
}
})
nodeConnector.fiatValue.observe(viewLifecycleOwner, { value ->
if (value == 0f) {
binding.ergoPrice.visibility = View.GONE
} else {
binding.ergoPrice.visibility = View.VISIBLE
binding.ergoPrice.amount = value.toDouble()
binding.ergoPrice.setSymbol(nodeConnector.fiatCurrency.toUpperCase(Locale.getDefault()))
}
binding.labelErgoPrice.visibility = binding.ergoPrice.visibility
})
}
private fun refreshTimeSinceSyncLabel() {
val nodeConnector = NodeConnector.getInstance()
val lastRefresMs = nodeConnector.lastRefreshMs
binding.synctime.text = if (lastRefresMs > 0) getString(
R.string.label_last_sync,
if (System.currentTimeMillis() - lastRefresMs < 60000L) getString(R.string.label_last_sync_just_now) else
DateUtils.getRelativeTimeSpanString(lastRefresMs)
)
else null
}
override fun onCreateOptionsMenu(menu: Menu, inflater: MenuInflater) {
super.onCreateOptionsMenu(menu, inflater)
inflater.inflate(R.menu.fragment_wallet, menu)
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
when (item.itemId) {
R.id.menu_add_wallet -> {
findNavController().navigateSafe(WalletFragmentDirections.actionToAddWalletChooserFragment())
return true
}
else -> {
return super.onOptionsItemSelected(item)
}
}
}
override fun onResume() {
super.onResume()
refreshTimeSinceSyncLabel()
NodeConnector.getInstance().refreshWhenNeeded(requireContext())
}
override fun onDestroyView() {
super.onDestroyView()
_binding = null
}
}
class WalletAdapter(initWalletList: List<WalletDbEntity>) : RecyclerView.Adapter<WalletViewHolder>() {
var walletList: List<WalletDbEntity> = initWalletList
set(value) {
val diffCallback = WalletDiffCallback(field, value)
field = value
val diffResult = DiffUtil.calculateDiff(diffCallback)
diffResult.dispatchUpdatesTo(this)
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): WalletViewHolder {
val cardWalletBinding =
CardWalletBinding.inflate(LayoutInflater.from(parent.context), parent, false)
val cardViewHolder = WalletViewHolder(cardWalletBinding)
return cardViewHolder
}
override fun onBindViewHolder(holder: WalletViewHolder, position: Int) {
holder.bind(walletList.get(position))
}
override fun getItemCount(): Int {
return walletList.size
}
}
class WalletViewHolder(val binding: CardWalletBinding) : RecyclerView.ViewHolder(binding.root) {
fun bind(wallet: WalletDbEntity) {
binding.walletName.text = wallet.walletConfig.displayName
binding.walletBalance.amount = ErgoAmount(wallet.getBalanceForAllAddresses()).toDouble()
// Fill token headline
val tokens = wallet.getTokensForAllAddresses()
val tokenCount = tokens.size
binding.walletTokenNum.text = tokenCount.toString()
binding.walletTokenNum.visibility = if (tokenCount == 0) View.GONE else View.VISIBLE
binding.labelTokenNum.visibility = binding.walletTokenNum.visibility
binding.walletTokenUnfold.visibility = binding.walletTokenNum.visibility
binding.walletTokenEntries.visibility =
if (tokenCount == 0 || !wallet.walletConfig.unfoldTokens) View.GONE else View.VISIBLE
binding.walletTokenUnfold.setImageResource(
if (wallet.walletConfig.unfoldTokens)
R.drawable.ic_remove_circle_24 else R.drawable.ic_add_circle_24
)
// Fill unconfirmed fields
val unconfirmed = wallet.getUnconfirmedBalanceForAllAddresses()
binding.walletUnconfirmed.amount = ErgoAmount(unconfirmed).toDouble()
binding.walletUnconfirmed.visibility = if (unconfirmed == 0L) View.GONE else View.VISIBLE
binding.labelWalletUnconfirmed.visibility = binding.walletUnconfirmed.visibility
// Set button listeners
val navigateToDetailsView: (v: View) -> Unit = {
NavHostFragment.findNavController(itemView.findFragment())
.navigateSafe(
WalletFragmentDirections.actionNavigationWalletToNavigationWalletDetails(
wallet.walletConfig.id
)
)
}
binding.cardView.setOnClickListener(navigateToDetailsView)
binding.buttonDetails.setOnClickListener(navigateToDetailsView)
binding.buttonReceive.setOnClickListener {
NavHostFragment.findNavController(itemView.findFragment())
.navigateSafe(
WalletFragmentDirections.actionNavigationWalletToReceiveToWalletFragment(
wallet.walletConfig.id
)
)
}
binding.buttonSend.setOnClickListener {
NavHostFragment.findNavController(itemView.findFragment())
.navigateSafe(
WalletFragmentDirections.actionNavigationWalletToSendFundsFragment(
wallet.walletConfig.id
)
)
}
binding.walletSettings.setOnClickListener {
NavHostFragment.findNavController(itemView.findFragment())
.navigateSafe(
WalletFragmentDirections.actionNavigationWalletToWalletConfigFragment(
wallet.walletConfig.id
)
)
}
val launchUnfoldTokenFieldChange: (v: View) -> Unit = {
GlobalScope.launch {
AppDatabase.getInstance(it.context).walletDao().updateWalletTokensUnfold(
wallet.walletConfig.id,
!wallet.walletConfig.unfoldTokens
)
// we don't need to update UI here - the DB change will trigger a rebind of the card
}
}
binding.walletTokenUnfold.setOnClickListener(launchUnfoldTokenFieldChange)
binding.labelTokenNum.setOnClickListener(launchUnfoldTokenFieldChange)
binding.walletTokenNum.setOnClickListener(launchUnfoldTokenFieldChange)
// Fill fiat value
val nodeConnector = NodeConnector.getInstance()
val ergoPrice = nodeConnector.fiatValue.value ?: 0f
if (ergoPrice == 0f) {
binding.walletFiat.visibility = View.GONE
} else {
binding.walletFiat.visibility = View.VISIBLE
binding.walletFiat.amount = ergoPrice * binding.walletBalance.amount
binding.walletFiat.setSymbol(nodeConnector.fiatCurrency.toUpperCase())
}
// Fill token entries
binding.walletTokenEntries.apply {
removeAllViews()
if (wallet.walletConfig.unfoldTokens) {
val maxTokensToShow = 5
val dontShowAll = tokens.size > maxTokensToShow
val tokensToShow =
(if (dontShowAll) tokens.subList(
0,
maxTokensToShow - 1
) else tokens)
val layoutInflater = LayoutInflater.from(context)
tokensToShow.forEach {
inflateAndBindTokenView(it, this, layoutInflater)
}
// in case we don't show all items, add a hint that not all items were shown
if (dontShowAll) {
val itemBinding =
EntryWalletTokenBinding.inflate(
LayoutInflater.from(itemView.context),
this,
true
)
itemBinding.labelTokenName.setText(R.string.label_more_tokens)
itemBinding.labelTokenVal.text =
"+" + (tokens.size - maxTokensToShow + 1).toString()
}
}
}
}
}
class WalletDiffCallback(val oldList: List<WalletDbEntity>, val newList: List<WalletDbEntity>) :
DiffUtil.Callback() {
override fun getOldListSize(): Int {
return oldList.size
}
override fun getNewListSize(): Int {
return newList.size
}
override fun areItemsTheSame(oldItemPosition: Int, newItemPosition: Int): Boolean {
return oldList.get(oldItemPosition).walletConfig.id == newList.get(newItemPosition).walletConfig.id
}
override fun areContentsTheSame(oldItemPosition: Int, newItemPosition: Int): Boolean {
// always redraw
return false
}
}
| 1
| null |
1
| 1
|
dcdc780f8514d27435591172e8e73935fefddee2
| 13,745
|
ergo-wallet-android
|
Apache License 2.0
|
src/main/kotlin/io/kanro/idea/plugin/protobuf/buf/project/BufProjectInitializer.kt
|
devkanro
| 351,091,577
| false
| null |
package io.kanro.idea.plugin.protobuf.buf.project
import com.intellij.openapi.components.service
import com.intellij.openapi.project.Project
import com.intellij.openapi.startup.ProjectActivity
import com.intellij.openapi.vfs.VirtualFileManager
class BufProjectInitializer : ProjectActivity {
override suspend fun execute(project: Project) {
val fileManager = project.service<BufFileManager>()
VirtualFileManager.getInstance().addAsyncFileListener(BufFileListener(project, fileManager), project)
}
}
| 8
| null |
10
| 76
|
0ce1fd26e742569f7c4278a80d6909c081dfa92c
| 525
|
intellij-protobuf-plugin
|
Apache License 2.0
|
ui-kit/src/main/java/com/quickblox/android_ui_kit/presentation/dialogs/AvatarDialog.kt
|
QuickBlox
| 637,751,718
| false
|
{"Kotlin": 1833847}
|
/*
* Created by Injoit on 26.3.2023.
* Copyright © 2023 Quickblox. All rights reserved.
*/
package com.quickblox.android_ui_kit.presentation.dialogs
import android.content.Context
import android.view.View
import com.quickblox.android_ui_kit.R
import com.quickblox.android_ui_kit.presentation.base.BaseDialog
import com.quickblox.android_ui_kit.presentation.theme.UiKitTheme
class AvatarDialog constructor(
context: Context, title: String, theme: UiKitTheme?, private val listener: AvatarDialogListener
) : BaseDialog(context, title, theme) {
companion object {
fun show(context: Context, title: String, theme: UiKitTheme?, listener: AvatarDialogListener) {
AvatarDialog(context, title, theme, listener).show()
}
}
override fun collectViewsTemplateMethod(): List<View?> {
val views = mutableListOf<View?>()
val cameraItem = buildCameraItem()
val galleryItem = buildGalleryItem()
val removeItem = buildRemoveItem()
views.add(cameraItem)
views.add(galleryItem)
views.add(removeItem)
return views
}
private fun buildCameraItem(): View {
val cameraItem = MenuItem(context)
themeDialog?.getMainTextColor()?.let {
cameraItem.setColorText(it)
}
themeDialog?.getMainElementsColor()?.let {
cameraItem.setRipple(it)
}
cameraItem.setText(context.getString(R.string.camera))
cameraItem.setItemClickListener {
dismiss()
listener.onClickCamera()
}
return cameraItem
}
private fun buildGalleryItem(): View {
val galleryItem = MenuItem(context)
themeDialog?.getMainTextColor()?.let {
galleryItem.setColorText(it)
}
themeDialog?.getMainElementsColor()?.let {
galleryItem.setRipple(it)
}
galleryItem.setText(context.getString(R.string.gallery))
galleryItem.setItemClickListener {
dismiss()
listener.onClickGallery()
}
return galleryItem
}
private fun buildRemoveItem(): View {
val removeItem = MenuItem(context)
themeDialog?.getMainTextColor()?.let {
removeItem.setColorText(it)
}
themeDialog?.getMainElementsColor()?.let {
removeItem.setRipple(it)
}
removeItem.setText(context.getString(R.string.remove_photo))
removeItem.setItemClickListener {
dismiss()
listener.onClickRemove()
}
return removeItem
}
interface AvatarDialogListener {
fun onClickCamera()
fun onClickGallery()
fun onClickRemove()
}
}
| 1
|
Kotlin
|
0
| 4
|
0ef856d22efb1540d6e238a073badbf31c03961a
| 2,729
|
android-ui-kit
|
MIT License
|
app/src/main/java/com/kieronquinn/app/classicpowermenu/ui/screens/settings/quickaccesswallet/SettingsQuickAccessWalletViewModel.kt
|
KieronQuinn
| 410,362,831
| false
|
{"Kotlin": 737388, "Java": 280783, "AIDL": 22512}
|
package com.kieronquinn.app.classicpowermenu.ui.screens.settings.quickaccesswallet
import android.content.Context
import android.content.Intent
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.kieronquinn.app.classicpowermenu.components.navigation.AppNavigation
import com.kieronquinn.app.classicpowermenu.components.navigation.ContainerNavigation
import com.kieronquinn.app.classicpowermenu.components.quickaccesswallet.GooglePayConstants
import com.kieronquinn.app.classicpowermenu.components.settings.Settings
import com.kieronquinn.app.classicpowermenu.ui.screens.settings.container.SettingsContainerFragmentDirections
import com.kieronquinn.app.classicpowermenu.utils.extensions.isAppInstalled
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.map
import kotlinx.coroutines.launch
abstract class SettingsQuickAccessWalletViewModel: ViewModel() {
abstract val showQuickAccessWallet: Flow<Boolean>
abstract val showQuickAccessWalletInitialState: Boolean
abstract var showLoyaltyCards: Boolean
abstract var showPreview: Boolean
abstract var accessWhileLocked: Boolean
abstract var hideCardNumber: Boolean
abstract val showLoyaltyCardsChanged: Flow<Unit>
abstract val isGooglePayInstalled: Boolean
abstract fun onSwitchClicked()
abstract fun onChangeGooglePaySettingsClicked()
abstract fun onReorderLoyaltyCardsClicked()
}
class SettingsQuickAccessWalletViewModelImpl(context: Context, private val settings: Settings, private val navigation: AppNavigation, private val containerNavigation: ContainerNavigation): SettingsQuickAccessWalletViewModel() {
private val packageManager = context.packageManager
override val showQuickAccessWallet = settings.quickAccessWalletShowFlow
override val showQuickAccessWalletInitialState = settings.quickAccessWalletShow
override var showLoyaltyCards by settings::quickAccessWalletShowLoyaltyCards
override var showPreview by settings::quickAccessWalletShowPreview
override var accessWhileLocked by settings::quickAccessWalletAccessWhileLocked
override var hideCardNumber by settings::quickAccessWalletHideCardNumberWhenLocked
override val showLoyaltyCardsChanged = settings.quickAccessWalletShowLoyaltyCardsFlow.map { }
override val isGooglePayInstalled
get() = GooglePayConstants.isGooglePayInstalled(packageManager) || GooglePayConstants.isGPayInstalled(packageManager)
override fun onSwitchClicked() {
settings.quickAccessWalletShow = !settings.quickAccessWalletShow
}
override fun onChangeGooglePaySettingsClicked() {
viewModelScope.launch {
navigation.navigate(getGooglePayIntent() ?: return@launch)
}
}
override fun onReorderLoyaltyCardsClicked() {
viewModelScope.launch {
containerNavigation.navigate(SettingsContainerFragmentDirections.actionSettingsContainerFragmentToSettingsQuickAccessWalletRearrangeFragment())
}
}
private fun getGooglePayIntent(): Intent? {
return if(GooglePayConstants.isGPayInstalled(packageManager)){
packageManager.getLaunchIntentForPackage(GooglePayConstants.NBU_PAISA_PACKAGE_NAME)
}else{
packageManager.getLaunchIntentForPackage(GooglePayConstants.WALLET_NFC_REL_PACKAGE_NAME)
}
}
}
| 9
|
Kotlin
|
19
| 607
|
fe566cf30f4539f84887c78d8f388a38b8fe69b7
| 3,358
|
ClassicPowerMenu
|
Apache License 2.0
|
app/src/main/java/com/yanbin/reactivestickynote/ui/view/BoardView.kt
|
hungyanbin
| 378,550,510
| false
| null |
package com.yanbin.reactivestickynote.ui.view
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.runtime.Composable
import androidx.compose.runtime.ReusableContent
import androidx.compose.runtime.State
import androidx.compose.runtime.getValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import com.yanbin.reactivestickynote.model.Note
import com.yanbin.reactivestickynote.model.Position
import java.util.*
@Composable
fun BoardView(
notes: List<Note>,
selectedNote: Optional<Note>,
updateNotePosition: (String, Position) -> Unit,
onNoteClicked: (Note) -> Unit
) {
Box(Modifier.fillMaxSize()) {
notes.forEach { note ->
val onNotePositionChanged: (Position) -> Unit = { delta ->
updateNotePosition(note.id, delta)
}
val selected = selectedNote.filter { it.id == note.id }.isPresent
ReusableContent(key = note.id) {
StickyNote(
modifier = Modifier.align(Alignment.Center),
note = note,
selected = selected,
onPositionChanged = onNotePositionChanged,
onClick = onNoteClicked
)
}
}
}
}
| 1
|
Kotlin
|
1
| 2
|
5fee0681303cceebf7331fd02683cddd52494894
| 1,335
|
ReactiveStickyNote
|
MIT License
|
app/src/main/java/com/mindsync/mindmapview/EditDescriptionDialog.kt
|
hegleB
| 784,266,225
| false
|
{"Kotlin": 79055}
|
package com.mindsync.mindmapview
import android.app.Dialog
import android.content.DialogInterface
import android.graphics.Color
import android.graphics.drawable.ColorDrawable
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.view.WindowManager
import androidx.fragment.app.DialogFragment
import androidx.fragment.app.viewModels
import com.mindsync.mindmapview.databinding.DialogEditDescriptionBinding
class EditDescriptionDialog : DialogFragment() {
private var _binding: DialogEditDescriptionBinding? = null
private val binding get() = _binding!!
private val editDescriptionViewModel: EditDescriptionViewModel by viewModels()
private var submitListener: ((String) -> (Unit))? = null
private var description: String = ""
fun setDescription(description: String) {
this.description = description
}
fun setSubmitListener(submitListener: ((String) -> (Unit))) {
this.submitListener = submitListener
}
override fun onCreateDialog(savedInstanceState: Bundle?): Dialog {
val dialog = super.onCreateDialog(savedInstanceState)
dialog.window?.setBackgroundDrawable(ColorDrawable(Color.TRANSPARENT))
// dialog.window?.attributes?.windowAnimations = R.style.AnimationDialogStyle
isCancelable = true
return dialog
}
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?,
): View {
_binding = DialogEditDescriptionBinding.inflate(inflater, container, false)
return binding.root
}
override fun onViewCreated(
view: View,
savedInstanceState: Bundle?,
) {
super.onViewCreated(view, savedInstanceState)
setBinding()
setViewModel()
setupCancelBtn()
setupSubmitBtn()
}
override fun onStart() {
super.onStart()
resizeDialog()
}
private fun setBinding() {
binding.vm = editDescriptionViewModel
}
private fun setViewModel() {
submitListener?.let {
editDescriptionViewModel.submitListener = this.submitListener
}
if (description.isNotEmpty()) {
editDescriptionViewModel.setDescription(description)
}
}
private fun setupSubmitBtn() {
binding.btnSubmit.setOnClickListener {
editDescriptionViewModel.submitListener?.invoke(editDescriptionViewModel.description.value)
dismiss()
}
}
private fun setupCancelBtn() {
binding.btnCancel.setOnClickListener {
dismiss()
}
}
private fun resizeDialog() {
val params: ViewGroup.LayoutParams? = dialog?.window?.attributes
val displayMetrics = requireActivity().resources.displayMetrics
val deviceWidth = displayMetrics.widthPixels
val deviceHeight = displayMetrics.heightPixels
params?.width = (deviceWidth * 0.8).toInt()
params?.height = (deviceHeight * 0.5).toInt()
dialog?.window?.attributes = params as WindowManager.LayoutParams
}
override fun onDismiss(dialog: DialogInterface) {
_binding = null
super.onDismiss(dialog)
}
}
| 0
|
Kotlin
|
0
| 0
|
a634e55d664dac80e3dcf4c17b4339d38dff6f57
| 3,281
|
MindMapView
|
MIT License
|
sykepenger-etterlevelse/src/main/kotlin/no/nav/helse/etterlevelse/SubsumsjonVisitor.kt
|
navikt
| 193,907,367
| false
| null |
package no.nav.helse.etterlevelse
import no.nav.helse.hendelser.Periode
import java.time.LocalDate
interface SubsumsjonVisitor {
fun preVisitSubsumsjon(
utfall: Subsumsjon.Utfall,
lovverk: String,
versjon: LocalDate,
paragraf: Paragraf,
ledd: Ledd?,
punktum: Punktum?,
bokstav: Bokstav?,
input: Map<String, Any>,
output: Map<String, Any>,
kontekster: Map<String, KontekstType>
) {}
fun visitGrupperbarSubsumsjon(perioder: List<Periode>) {}
fun visitBetingetSubsumsjon(funnetRelevant: Boolean) {}
fun postVisitSubsumsjon(
utfall: Subsumsjon.Utfall,
lovverk: String,
versjon: LocalDate,
paragraf: Paragraf,
ledd: Ledd?,
punktum: Punktum?,
bokstav: Bokstav?,
input: Map<String, Any>,
output: Map<String, Any>,
kontekster: Map<String, KontekstType>
) {}
}
| 2
|
Kotlin
|
6
| 5
|
2f940cad2bc6a756033a4e19edc5236a0648c971
| 940
|
helse-spleis
|
MIT License
|
food-delivery-app/app/src/main/java/com/bkarakoca/fooddeliveryapp/scene/restaurant/detail/FRRestaurantDetailVM.kt
|
kkocaburak
| 509,401,156
| false
|
{"Kotlin": 130651}
|
package com.bkarakoca.fooddeliveryapp.scene.restaurant.detail
import androidx.lifecycle.MutableLiveData
import com.bkarakoca.fooddeliveryapp.base.BaseViewModel
import com.bkarakoca.fooddeliveryapp.data.uimodel.restaurant.listitem.RestaurantUIModel
import dagger.hilt.android.lifecycle.HiltViewModel
import javax.inject.Inject
@HiltViewModel
class FRRestaurantDetailVM @Inject constructor() : BaseViewModel() {
val restaurantUIModel = MutableLiveData<RestaurantUIModel>()
fun initializeVM(args: FRRestaurantDetailArgs) {
restaurantUIModel.value = args.restaurantUIModel
}
}
| 0
|
Kotlin
|
0
| 3
|
764b032bfcbd8fb2e2b1aa68f089eeb95fb0184a
| 597
|
android-food-delivery-example
|
Apache License 2.0
|
backpack-compose/src/main/kotlin/net/skyscanner/backpack/compose/flare/internal/BpkFlareImpl.kt
|
Skyscanner
| 117,813,847
| false
| null |
/**
* Backpack for Android - Skyscanner's Design System
*
* Copyright 2018 Skyscanner Ltd
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package net.skyscanner.backpack.compose.flare.internal
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.ui.graphics.RectangleShape
import androidx.compose.ui.graphics.Shape
import androidx.compose.ui.unit.dp
import net.skyscanner.backpack.compose.flare.BpkFlarePointerDirection
import net.skyscanner.backpack.compose.flare.BpkFlareRadius
import net.skyscanner.backpack.compose.tokens.BpkDimension
import net.skyscanner.backpack.compose.utils.FlareShape
internal fun FlareShape(
radius: BpkFlareRadius,
pointerDirection: BpkFlarePointerDirection,
): Shape =
FlareShape(
flareHeight = FlareHeight,
pointerDirection = pointerDirection,
applyAntialiasFix = true,
borderRadius = when (radius) {
BpkFlareRadius.None -> 0.dp
BpkFlareRadius.Medium -> BpkDimension.BorderRadius.Md
},
)
internal fun FlareRectShape(radius: BpkFlareRadius): Shape = when (radius) {
BpkFlareRadius.None -> RectangleShape
BpkFlareRadius.Medium -> RoundedCornerShape(BpkDimension.BorderRadius.Md)
}
internal fun FlareContentPadding(insetContent: Boolean = false) =
when (insetContent) {
true -> FlareHeight
false -> 0.dp
}
private val FlareHeight = 11.dp
| 8
|
Kotlin
|
31
| 94
|
9b5448b446c7bc46560e430595829e5f4f090e6b
| 1,874
|
backpack-android
|
Apache License 2.0
|
app/src/main/java/com/hamburger/kotlinqiitareader/ui/item/ItemViewModel.kt
|
ham-burger
| 200,448,368
| false
| null |
package com.hamburger.kotlinqiitareader.ui.item
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import androidx.lifecycle.ViewModelProvider
import com.hamburger.kotlinqiitareader.extension.observeOnMainThread
import com.hamburger.kotlinqiitareader.extension.subscribeOnIOThread
import com.hamburger.kotlinqiitareader.service.dto.ItemDetailDTO
import com.hamburger.kotlinqiitareader.service.paging.NetworkState
import com.hamburger.kotlinqiitareader.service.web_api.ItemWebApi
import io.reactivex.disposables.CompositeDisposable
import io.reactivex.rxkotlin.addTo
class ItemViewModel(
val id: String
) : ViewModel() {
class Factory(
private val id: String
) : ViewModelProvider.NewInstanceFactory() {
override fun <T : ViewModel> create(modelClass: Class<T>): T {
return ItemViewModel(id) as T
}
}
var data = MutableLiveData<ItemDetailDTO?>().apply {
value = null
}
val networkState = MutableLiveData<NetworkState>().apply {
value = NetworkState.SUCCESS
}
private var compositeDisposable = CompositeDisposable()
init {
getItem()
}
private fun getItem() {
ItemWebApi()
.request
.show(id)
.subscribeOnIOThread()
.observeOnMainThread()
.subscribe({
data.postValue(it.body())
}, {
})
.addTo(compositeDisposable)
}
}
| 1
|
Kotlin
|
1
| 1
|
0f564ff8adb4f42db2b3f2f0f173887ddc17cba1
| 1,477
|
KotlinQiitaReader
|
Apache License 2.0
|
app/src/main/java/eu/darken/androidstarter/common/lists/modular/mods/ClickMod.kt
|
d4rken
| 367,445,682
| false
| null |
package eu.darken.androidstarter.common.lists.modular.mods
import eu.darken.androidstarter.common.lists.modular.ModularAdapter
class ClickMod<VHT : ModularAdapter.VH> constructor(
private val listener: (VHT, Int) -> Unit
) : ModularAdapter.Module.Binder<VHT> {
override fun onBindModularVH(adapter: ModularAdapter<VHT>, vh: VHT, pos: Int, payloads: MutableList<Any>) {
vh.itemView.setOnClickListener { listener.invoke(vh, pos) }
}
}
| 0
|
Kotlin
|
2
| 8
|
0e704d561d39ca3b3ea755da2d05815dfa4ee196
| 455
|
android-starter-v4
|
Apache License 2.0
|
src/main/kotlin/core/UnderlingError.kt
|
darthmachina
| 637,608,931
| false
| null |
package core
import arrow.core.None
import arrow.core.Option
sealed class UnderlingError(
open val message: String,
open val throwable: Option<Throwable> = None
)
data class DateParsError(override val message: String, override val throwable: Option<Throwable> = None) : UnderlingError(message, throwable)
data class RepeatInfoParseError(override val message: String, override val throwable: Option<Throwable> = None) : UnderlingError(message, throwable)
| 0
| null |
0
| 1
|
fe584feb9f40ff6353c55b7311b5fddfe65fbce0
| 464
|
underling-obsidian
|
MIT License
|
src/main/kotlin/uk/gov/justice/digital/hmpps/hmppsidentifyremandperiodsapi/calculatereleasedatesapi/model/RelevantRemandReleaseDateCalculationRequest.kt
|
ministryofjustice
| 642,301,009
| false
|
{"Kotlin": 182357, "Dockerfile": 1376}
|
package uk.gov.justice.digital.hmpps.hmppsidentifyremandperiodsapi.calculatereleasedatesapi.model
import uk.gov.justice.digital.hmpps.hmppsidentifyremandperiodsapi.relevantremand.model.Sentence
import java.time.LocalDate
data class RelevantRemandReleaseDateCalculationRequest(
val relevantRemands: List<RelevantRemand>,
val sentence: Sentence,
val calculateAt: LocalDate,
)
| 3
|
Kotlin
|
0
| 1
|
bbebc2f554d6c06fe019c2081870c551e94f4ea8
| 382
|
hmpps-identify-remand-periods-api
|
MIT License
|
Entrega/app/src/main/java/com/jjmorillo/ladespensademicasa/ui/fragmenNavigationDrawer/PescadosFragment.kt
|
jjmorleo
| 356,499,729
| false
| null |
package com.jjmorillo.ladespensademicasa.ui.fragmenNavigationDrawer
import android.os.Bundle
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.core.os.bundleOf
import androidx.fragment.app.activityViewModels
import androidx.fragment.app.viewModels
import androidx.navigation.fragment.NavHostFragment
import androidx.recyclerview.widget.DividerItemDecoration
import androidx.recyclerview.widget.RecyclerView
import com.google.firebase.auth.FirebaseAuth
import com.google.firebase.auth.ktx.auth
import com.google.firebase.ktx.Firebase
import com.jjmorillo.ladespensademicasa.R
import com.jjmorillo.ladespensademicasa.adapters.ProductosRecyclerViewAdapter
import com.jjmorillo.ladespensademicasa.databinding.FragmentDrogueriaLimpiezaBinding
import com.jjmorillo.ladespensademicasa.database.entities.Producto
import com.jjmorillo.ladespensademicasa.viewModels.CarritoViewModel
import com.jjmorillo.ladespensademicasa.viewModels.ProductoViewModel
class DrogueriaLimpiezaFragment : Fragment(), ProductosRecyclerViewAdapter.ProductosAdapterListener {
private var _binding: FragmentDrogueriaLimpiezaBinding? = null
val modelCarrito: CarritoViewModel by activityViewModels()
val modelProductos: ProductoViewModel by viewModels()
private lateinit var auth: FirebaseAuth
private val binding get() = _binding!!
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
_binding= FragmentDrogueriaLimpiezaBinding.inflate(inflater, container, false)
val view= binding.root
auth = Firebase.auth
val model: ProductoViewModel by viewModels()
model.obtenerDrogueriaLimpieza().observe(viewLifecycleOwner, {
createRecyclerView(it)
})
// Inflate the layout for this fragment
return view
}
private fun createRecyclerView(productos: List<Producto>) {
//apply es para el patron builder
val mAdapter = ProductosRecyclerViewAdapter(productos as MutableList<Producto>, modelCarrito, this, CarritoViewModel())
val recyclerView = binding!!.drogueriaLimpiezaRecyclerViewFragment
recyclerView.apply {
//EL RECYCLERVIEW VA A SER UNA LISTA VERTICAL
//layoutManager = GridLayoutManager(requireContext(), RecyclerView.VERTICAL, false)
adapter = mAdapter
//PARA AÑADIR LINEAS VERTICALES Y HORIZONTALES
addItemDecoration(DividerItemDecoration(requireContext(), RecyclerView.VERTICAL))
addItemDecoration(DividerItemDecoration(requireContext(), RecyclerView.HORIZONTAL))
}
}
override fun verDetalle(producto: Producto) {
val data= bundleOf("data" to producto)
NavHostFragment.findNavController(this).navigate(R.id.action_to_detalleFragment,data)
}
override fun verCart(producto: Producto) {
NavHostFragment.findNavController(this).navigate(R.id.action_to_mobile_cartFragment)
}
}
| 0
|
Kotlin
|
0
| 0
|
1f555d30c298501215655317578de2c8cc3ea465
| 3,083
|
la-despensa-de-mi-casa
|
MIT License
|
app/src/main/java/net/rubey/materialswipedismiss/DemoActivity.kt
|
markusrubey
| 146,635,933
| false
| null |
package net.rubey.materialswipedismiss
import android.os.Bundle
import android.support.v4.content.ContextCompat
import android.support.v7.app.AppCompatActivity
import android.support.v7.widget.helper.ItemTouchHelper
import android.support.v7.widget.helper.ItemTouchHelper.END
import android.support.v7.widget.helper.ItemTouchHelper.START
import kotlinx.android.synthetic.main.demo_activity.*
import net.rubey.materialswipedismiss.lib.SwipeDismissStyle
import net.rubey.materialswipedismiss.lib.SwipeDismissTouchHelperCallback
import net.rubey.materialswipedismiss.list.DemoListItem
import net.rubey.materialswipedismiss.list.DemoListItemAdapter
class DemoActivity : AppCompatActivity() {
private val list = DemoListItem.values().toList()
private val listAdapter = DemoListItemAdapter()
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.demo_activity)
val swipeDismissStyle = SwipeDismissStyle(
colorBackground = ContextCompat.getColor(this, R.color.colorBackgroundDark),
colorInnerShadow = ContextCompat.getColor(this, R.color.colorShadow),
colorIcon = ContextCompat.getColor(this, R.color.colorIcon),
colorIconReveal = ContextCompat.getColor(this, R.color.colorIconReveal),
cornerRadius = resources.getDimensionPixelSize(R.dimen.corner_radius),
iconDrawable = ContextCompat.getDrawable(this, R.drawable.ic_delete)!!,
iconPadding = resources.getDimensionPixelSize(R.dimen.padding_normal)
)
val swipeDismissCallback = SwipeDismissTouchHelperCallback(swipeDismissStyle, listAdapter, START or END)
ItemTouchHelper(swipeDismissCallback).attachToRecyclerView(recyclerView)
recyclerView.adapter = listAdapter
listAdapter.submitList(list)
}
}
| 0
|
Kotlin
|
0
| 0
|
7740493b4aef319ea2a101e30e23dd89ad511177
| 1,869
|
MaterialSwipeDismiss
|
Apache License 2.0
|
cpg-core/src/main/kotlin/de/fraunhofer/aisec/cpg/helpers/neo4j/LocationConverter.kt
|
Fraunhofer-AISEC
| 225,386,107
| false
|
{"Kotlin": 3152711, "LLVM": 170593, "C++": 42625, "Go": 35624, "C": 31808, "Java": 28991, "TypeScript": 4908, "Shell": 2939, "Python": 2787, "JavaScript": 751, "Ruby": 201}
|
/*
* Copyright (c) 2019, Fraunhofer AISEC. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* $$$$$$\ $$$$$$$\ $$$$$$\
* $$ __$$\ $$ __$$\ $$ __$$\
* $$ / \__|$$ | $$ |$$ / \__|
* $$ | $$$$$$$ |$$ |$$$$\
* $$ | $$ ____/ $$ |\_$$ |
* $$ | $$\ $$ | $$ | $$ |
* \$$$$$ |$$ | \$$$$$ |
* \______/ \__| \______/
*
*/
package de.fraunhofer.aisec.cpg.helpers.neo4j
import de.fraunhofer.aisec.cpg.sarif.PhysicalLocation
import de.fraunhofer.aisec.cpg.sarif.Region
import java.net.URI
import org.neo4j.ogm.typeconversion.CompositeAttributeConverter
/**
* This class converts a [PhysicalLocation] into the the necessary composite attributes when
* persisting a node into a Neo4J graph database.
*/
class LocationConverter : CompositeAttributeConverter<PhysicalLocation?> {
override fun toGraphProperties(value: PhysicalLocation?): Map<String, *> {
val properties: MutableMap<String, Any> = HashMap()
if (value != null) {
properties[ARTIFACT] = value.artifactLocation.uri.toString()
properties[START_LINE] = value.region.startLine
properties[END_LINE] = value.region.endLine
properties[START_COLUMN] = value.region.startColumn
properties[END_COLUMN] = value.region.endColumn
}
return properties
}
override fun toEntityAttribute(value: Map<String, *>?): PhysicalLocation? {
return try {
val startLine = toInt(value?.get(START_LINE)) ?: return null
val endLine = toInt(value?.get(END_LINE)) ?: return null
val startColumn = toInt(value?.get(START_COLUMN)) ?: return null
val endColumn = toInt(value?.get(END_COLUMN)) ?: return null
val uri = URI.create(value?.get(ARTIFACT) as? String ?: "")
PhysicalLocation(uri, Region(startLine, startColumn, endLine, endColumn))
} catch (e: NullPointerException) {
null
}
}
private fun toInt(objectToMap: Any?): Int? {
val value = objectToMap?.toString()?.toLong() ?: return null
return Math.toIntExact(value)
}
companion object {
const val START_LINE = "startLine"
const val END_LINE = "endLine"
const val START_COLUMN = "startColumn"
const val END_COLUMN = "endColumn"
const val ARTIFACT = "artifact"
}
}
| 74
|
Kotlin
|
58
| 217
|
ded24ab341cdf17c8dc9b385d6faa3fa529b706d
| 3,060
|
cpg
|
Apache License 2.0
|
app/src/main/java/com/personal/tmdb/detail/presentation/detail/components/Details.kt
|
Avvami
| 755,489,313
| false
| null |
package com.personal.tmdb.detail.presentation.detail.components
import android.net.Uri
import androidx.compose.animation.AnimatedVisibility
import androidx.compose.animation.animateContentSize
import androidx.compose.foundation.Image
import androidx.compose.foundation.background
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.ExperimentalLayoutApi
import androidx.compose.foundation.layout.FlowRow
import androidx.compose.foundation.layout.FlowRowScope
import androidx.compose.foundation.layout.IntrinsicSize
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.sizeIn
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.foundation.text.selection.SelectionContainer
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.rounded.Add
import androidx.compose.material3.Icon
import androidx.compose.material3.LinearProgressIndicator
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.State
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.text.SpanStyle
import androidx.compose.ui.text.buildAnnotatedString
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.text.withStyle
import androidx.compose.ui.unit.dp
import coil.compose.AsyncImage
import com.personal.tmdb.R
import com.personal.tmdb.UserState
import com.personal.tmdb.core.navigation.RootNavGraph
import com.personal.tmdb.core.presentation.PreferencesState
import com.personal.tmdb.core.util.C
import com.personal.tmdb.core.util.MediaType
import com.personal.tmdb.core.util.compactDecimalFormat
import com.personal.tmdb.core.util.formatDate
import com.personal.tmdb.core.util.formatRuntime
import com.personal.tmdb.core.util.formatTvShowRuntime
import com.personal.tmdb.core.util.formatVoteAverage
import com.personal.tmdb.core.util.formatVoteAverageToColor
import com.personal.tmdb.core.util.shimmerEffect
import com.personal.tmdb.detail.domain.models.MediaDetailInfo
import com.personal.tmdb.detail.presentation.collection.CollectionState
import com.personal.tmdb.detail.presentation.detail.DetailUiEvent
import com.personal.tmdb.ui.theme.backgroundLight
import com.personal.tmdb.ui.theme.justWatch
import com.personal.tmdb.ui.theme.tmdbDarkBlue
@OptIn(ExperimentalLayoutApi::class)
@Composable
fun Details(
onNavigateTo: (route: String) -> Unit,
mediaType: MediaType?,
info: () -> MediaDetailInfo,
collectionState: () -> CollectionState,
isOverviewCollapsed: () -> Boolean,
showMore: () -> Boolean,
preferencesState: State<PreferencesState>,
userState: State<UserState>,
detailUiEvent: (DetailUiEvent) -> Unit
) {
SelectionContainer {
Column(
modifier = Modifier.padding(horizontal = 16.dp),
verticalArrangement = Arrangement.spacedBy(16.dp)
) {
Column(
verticalArrangement = Arrangement.spacedBy(8.dp)
) {
Column(
verticalArrangement = Arrangement.spacedBy(4.dp)
) {
info().name?.let { title ->
Text(
text = title,
style = MaterialTheme.typography.titleLarge,
fontWeight = FontWeight.Medium
)
}
contentRow(info = info, userState = userState).takeIf { it.isNotEmpty() }?.let { components ->
FlowRow(
horizontalArrangement = Arrangement.spacedBy(6.dp),
verticalArrangement = Arrangement.spacedBy(8.dp)
) {
components.forEachIndexed { index, component ->
component()
if (index != components.lastIndex) {
Icon(
modifier = Modifier
.size(6.dp)
.align(Alignment.CenterVertically),
painter = painterResource(id = R.drawable.icon_fiber_manual_record_fill1_wght400),
contentDescription = null,
tint = MaterialTheme.colorScheme.onSurfaceVariant
)
}
}
}
}
}
info().voteAverage?.let { voteAverage ->
Column(
verticalArrangement = Arrangement.spacedBy(4.dp)
) {
LinearProgressIndicator(
modifier = Modifier
.fillMaxWidth()
.height(8.dp)
.clip(RoundedCornerShape(2.dp)),
progress = { voteAverage.div(10f) },
trackColor = MaterialTheme.colorScheme.surfaceVariant,
color = formatVoteAverageToColor(voteAverage)
)
Row(
modifier = Modifier.fillMaxWidth(),
verticalAlignment = Alignment.CenterVertically,
horizontalArrangement = Arrangement.spacedBy(12.dp)
) {
Row(
verticalAlignment = Alignment.CenterVertically,
horizontalArrangement = Arrangement.spacedBy(8.dp)
) {
Box(
modifier = Modifier
.sizeIn(minWidth = 32.dp, minHeight = 32.dp)
.clip(MaterialTheme.shapes.small)
.background(justWatch),
contentAlignment = Alignment.Center
) {
Image(
modifier = Modifier.size(20.dp),
painter = painterResource(id = R.drawable.tmdb_logo_square),
contentDescription = stringResource(id = R.string.tmdb)
)
}
Column {
Row(
verticalAlignment = Alignment.CenterVertically,
horizontalArrangement = Arrangement.spacedBy(2.dp)
) {
Text(
text = formatVoteAverage(voteAverage),
style = MaterialTheme.typography.labelLarge,
color = MaterialTheme.colorScheme.onBackground
)
Icon(
modifier = Modifier.size(14.dp),
painter = painterResource(id = R.drawable.icon_bar_chart_fill0_wght400),
contentDescription = null,
tint = MaterialTheme.colorScheme.onBackground
)
}
info().voteCount?.takeIf { it != 0 }?.let { voteCount ->
Row(
verticalAlignment = Alignment.CenterVertically,
horizontalArrangement = Arrangement.spacedBy(2.dp)
) {
Text(
text = compactDecimalFormat(voteCount.toLong()),
style = MaterialTheme.typography.labelSmall,
color = MaterialTheme.colorScheme.onSurfaceVariant
)
Icon(
modifier = Modifier.size(12.dp),
painter = painterResource(id = R.drawable.icon_group_fill0_wght400),
contentDescription = null,
tint = MaterialTheme.colorScheme.onSurfaceVariant
)
}
}
}
}
Row(
modifier = Modifier
.clip(MaterialTheme.shapes.small)
.clickable { /*TODO: Show rate bottom sheet*/ },
verticalAlignment = Alignment.CenterVertically,
horizontalArrangement = Arrangement.spacedBy(8.dp)
) {
Box(
modifier = Modifier
.sizeIn(minWidth = 32.dp, minHeight = 32.dp)
.clip(MaterialTheme.shapes.small)
.background(MaterialTheme.colorScheme.surfaceContainer),
contentAlignment = Alignment.Center
) {
if (/*TODO: Not rated by user*/true) {
Icon(
modifier = Modifier.size(20.dp),
imageVector = Icons.Rounded.Add,
contentDescription = "Add rating",
tint = MaterialTheme.colorScheme.primary
)
} else {
/*TODO: User rating*/
}
}
if (/*TODO: Not rated by user*/true) {
Text(
text = stringResource(id = R.string.rate_now),
style = MaterialTheme.typography.titleMedium,
color = MaterialTheme.colorScheme.primary
)
} else {
/*TODO: User rating*/
}
}
}
}
}
info().tagline?.let { tagline ->
Text(
modifier = Modifier
.clip(MaterialTheme.shapes.small)
.background(MaterialTheme.colorScheme.surfaceVariant)
.padding(10.dp),
text = "\"$tagline\"",
style = MaterialTheme.typography.bodyLarge
)
}
info().overview?.let { overview ->
Text(
modifier = Modifier
.fillMaxWidth()
.clip(MaterialTheme.shapes.extraSmall)
.animateContentSize()
.clickable {
detailUiEvent(DetailUiEvent.ChangeCollapsedOverview)
},
text = overview,
style = MaterialTheme.typography.bodyLarge,
maxLines = if (isOverviewCollapsed()) 4 else Int.MAX_VALUE,
overflow = TextOverflow.Ellipsis
)
}
if (info().credits != null || !info().genres.isNullOrEmpty()) {
Column {
info().createdBy?.firstOrNull()?.let { createdBy ->
AnnotatedListText(
annotationTag = AnnotationTag.CAST,
titlePrefix = stringResource(id = R.string.creator),
items = listOf(
AnnotatedItem(id = createdBy.id, name = createdBy.name)
),
onNavigateTo = onNavigateTo
)
}
info().credits?.crew?.find { it.department == "Directing" }?.let { director ->
AnnotatedListText(
annotationTag = AnnotationTag.CAST,
titlePrefix = stringResource(id = R.string.director),
items = listOf(
AnnotatedItem(id = director.id, name = director.name)
),
onNavigateTo = onNavigateTo
)
}
info().credits?.cast?.let { cast ->
if (cast.isNotEmpty()) {
Row(
modifier = Modifier
.clip(RoundedCornerShape(2.dp))
.clickable { onNavigateTo(RootNavGraph.CAST + "/${Uri.encode(info().name ?: "") ?: ""}/${mediaType?.name?.lowercase() ?: ""}/${info().id}") },
verticalAlignment = Alignment.CenterVertically,
horizontalArrangement = Arrangement.spacedBy(2.dp)
) {
val annotatedString = buildAnnotatedString {
val starring = stringResource(id = R.string.starring)
withStyle(
style = SpanStyle(
color = MaterialTheme.colorScheme.onSurfaceVariant,
fontStyle = MaterialTheme.typography.labelLarge.fontStyle,
fontSize = MaterialTheme.typography.labelLarge.fontSize,
fontWeight = MaterialTheme.typography.labelLarge.fontWeight
)
) {
append("$starring ")
}
withStyle(
style = SpanStyle(
color = MaterialTheme.colorScheme.onSurfaceVariant,
fontStyle = MaterialTheme.typography.bodyMedium.fontStyle,
fontSize = MaterialTheme.typography.bodyMedium.fontSize
)
) {
append(cast.joinToString(", ") { it.name })
}
}
Text(
modifier = Modifier.weight(1f, false),
text = annotatedString,
maxLines = 1,
overflow = TextOverflow.Ellipsis,
onTextLayout = { textLayoutResult ->
if (textLayoutResult.hasVisualOverflow) detailUiEvent(DetailUiEvent.ChangeShowMoreState)
}
)
AnimatedVisibility(visible = showMore()) {
Text(
text = stringResource(id = R.string.more),
style = MaterialTheme.typography.labelMedium,
color = MaterialTheme.colorScheme.onSurfaceVariant
)
}
}
}
}
info().aggregateCredits?.cast?.let { cast ->
if (cast.isNotEmpty()) {
Row(
modifier = Modifier
.clip(RoundedCornerShape(2.dp))
.clickable {
onNavigateTo(
RootNavGraph.CAST + "/${Uri.encode(info().name ?: "") ?: ""}/${mediaType?.name?.lowercase() ?: ""}/${info().id}"
)
},
verticalAlignment = Alignment.CenterVertically,
horizontalArrangement = Arrangement.spacedBy(2.dp)
) {
val annotatedString = buildAnnotatedString {
val starring = stringResource(id = R.string.starring)
withStyle(
style = SpanStyle(
color = MaterialTheme.colorScheme.onSurfaceVariant,
fontStyle = MaterialTheme.typography.labelLarge.fontStyle,
fontSize = MaterialTheme.typography.labelLarge.fontSize,
fontWeight = MaterialTheme.typography.labelLarge.fontWeight
)
) {
append("$starring ")
}
withStyle(
style = SpanStyle(
color = MaterialTheme.colorScheme.onSurfaceVariant,
fontStyle = MaterialTheme.typography.bodyMedium.fontStyle,
fontSize = MaterialTheme.typography.bodyMedium.fontSize
)
) {
append(cast.joinToString(", ") { it.name })
}
}
Text(
modifier = Modifier.weight(1f, false),
text = annotatedString,
maxLines = 1,
overflow = TextOverflow.Ellipsis,
onTextLayout = { textLayoutResult ->
if (textLayoutResult.hasVisualOverflow) detailUiEvent(DetailUiEvent.ChangeShowMoreState)
}
)
AnimatedVisibility(visible = showMore()) {
Text(
text = stringResource(id = R.string.more),
style = MaterialTheme.typography.labelMedium,
color = MaterialTheme.colorScheme.onSurfaceVariant
)
}
}
}
}
info().genres?.let { genres ->
if (genres.isNotEmpty()) {
AnnotatedListText(
annotationTag = AnnotationTag.GENRE,
titlePrefix = stringResource(id = R.string.genres),
items = genres.map { genre ->
AnnotatedItem(id = genre.id, name = genre.name)
},
onNavigateTo = onNavigateTo
)
}
}
}
}
info().belongsToCollection?.let { belongToCollection ->
Box(
modifier = Modifier
.height(IntrinsicSize.Min)
.clip(RoundedCornerShape((preferencesState.value.corners / 1.125).dp))
.clickable { onNavigateTo(RootNavGraph.COLLECTION + "/${belongToCollection.id}") }
) {
AsyncImage(
modifier = Modifier.fillMaxSize(),
model = C.TMDB_IMAGES_BASE_URL + C.BACKDROP_W1280 + belongToCollection.backdropPath,
contentDescription = "Backdrop",
contentScale = ContentScale.Crop,
placeholder = painterResource(id = R.drawable.placeholder),
error = painterResource(id = R.drawable.placeholder)
)
Column(
modifier = Modifier
.fillMaxWidth()
.background(tmdbDarkBlue.copy(alpha = .7f))
.padding(12.dp),
verticalArrangement = Arrangement.spacedBy(4.dp)
) {
Text(
text = stringResource(id = R.string.part_of_collection, belongToCollection.name ?: ""),
style = MaterialTheme.typography.titleLarge,
fontWeight = FontWeight.Medium,
color = backgroundLight
)
if (collectionState().isLoading) {
Text(
modifier = Modifier
.fillMaxWidth()
.clip(MaterialTheme.shapes.small)
.shimmerEffect(
backgroundLight,
backgroundLight.copy(alpha = .3f)
),
text = "",
style = MaterialTheme.typography.bodyMedium,
color = Color.Transparent,
minLines = 2,
maxLines = 2,
overflow = TextOverflow.Ellipsis
)
} else {
collectionState().collectionInfo?.parts?.let { partInfos ->
Text(
text = stringResource(id = R.string.includes, partInfos.joinToString(", ") { it.name.toString() }),
style = MaterialTheme.typography.bodyMedium,
color = backgroundLight,
minLines = 2,
maxLines = 2,
overflow = TextOverflow.Ellipsis
)
}
}
}
}
}
}
}
}
}
@OptIn(ExperimentalLayoutApi::class)
@Composable
fun contentRow(
info: () -> MediaDetailInfo,
userState: State<UserState>
): List<@Composable (FlowRowScope.() -> Unit)> {
return with(info()) {
val userCountryCode = userState.value.userInfo?.iso31661 ?: "US"
val tvShowContentRating = contentRatings?.contentRatingsResults?.find { it.iso31661 == userCountryCode }?.rating?.takeIf { it.isNotEmpty() }
val movieContentRating = releaseDates?.releaseDatesResults?.find { it.iso31661 == userCountryCode }?.releaseDates
?.find { it.certification.isNotEmpty() }?.certification?.takeIf { it.isNotEmpty() }
buildList<@Composable FlowRowScope.() -> Unit> {
releaseDate?.let { releaseDate ->
add {
Text(
text = formatDate(releaseDate),
style = MaterialTheme.typography.bodyLarge,
color = MaterialTheme.colorScheme.onSurfaceVariant,
modifier = Modifier.align(Alignment.CenterVertically)
)
}
}
tvShowContentRating?.let { showRating ->
add {
Text(
modifier = Modifier
.clip(MaterialTheme.shapes.extraSmall)
.background(MaterialTheme.colorScheme.surfaceVariant)
.padding(horizontal = 8.dp)
.align(Alignment.CenterVertically),
text = showRating,
style = MaterialTheme.typography.bodyLarge,
color = MaterialTheme.colorScheme.onSurfaceVariant
)
}
}
movieContentRating?.let { movieRating ->
add {
Text(
modifier = Modifier
.clip(MaterialTheme.shapes.extraSmall)
.background(MaterialTheme.colorScheme.surfaceVariant)
.padding(horizontal = 8.dp)
.align(Alignment.CenterVertically),
text = movieRating,
style = MaterialTheme.typography.bodyLarge,
color = MaterialTheme.colorScheme.onSurfaceVariant
)
}
}
runtime?.let { runtime ->
val context = LocalContext.current
add {
Text(
modifier = Modifier.align(Alignment.CenterVertically),
text = formatRuntime(runtime, context),
style = MaterialTheme.typography.bodyLarge,
color = MaterialTheme.colorScheme.onSurfaceVariant
)
}
}
if (numberOfSeasons != null && numberOfEpisodes != null) {
add {
Text(
modifier = Modifier.align(Alignment.CenterVertically),
text = formatTvShowRuntime(numberOfSeasons, numberOfEpisodes),
style = MaterialTheme.typography.bodyLarge,
color = MaterialTheme.colorScheme.onSurfaceVariant
)
}
}
}
}
}
| 0
| null |
0
| 2
|
d5b4d2ee9eb9616ab0e217f8d6fff45723bf5e58
| 29,223
|
TMDB
|
MIT License
|
src/main/kotlin/net/papierkorb2292/command_crafter/editor/MinecraftServerConnection.kt
|
Papierkorb2292
| 584,879,864
| false
|
{"Kotlin": 106935, "Java": 59908, "TypeScript": 3609, "JavaScript": 1615}
|
package net.papierkorb2292.command_crafter.editor
import com.mojang.brigadier.CommandDispatcher
import net.minecraft.server.command.ServerCommandSource
interface MinecraftServerConnection {
val commandDispatcher: CommandDispatcher<ServerCommandSource>
val functionPermissionLevel: Int
}
| 0
|
Kotlin
|
0
| 4
|
397e9b82b1a79209a3d2fe070c5b49979e715019
| 296
|
CommandCrafter
|
MIT License
|
NBEffects/src/main/java/cn/wufuqi/nbeffects/bean/Vec3.kt
|
wufuqi123
| 572,812,247
| false
|
{"Kotlin": 55427, "GLSL": 19095, "Java": 6490}
|
package cn.wufuqi.nbeffects.bean
data class Vec3(var r: Float, var g: Float, var b: Float): UniformInterface() {
override fun toArray(): FloatArray {
return floatArrayOf(r, g, b)
}
}
| 0
|
Kotlin
|
0
| 7
|
fbd2d7b4312891e15b41d98fb96c1374ccd9324b
| 200
|
NBEffects
|
Apache License 2.0
|
SKIE/compiler/kotlin-plugin/src/kgp_common/kotlin/co/touchlab/skie/sir/element/SirClass.kt
|
touchlab
| 685,579,240
| false
|
{"Kotlin": 1061981, "Swift": 24501, "Shell": 183}
|
package co.touchlab.skie.sir.element
import co.touchlab.skie.sir.SirFqName
import co.touchlab.skie.sir.element.util.sirDeclarationParent
import co.touchlab.skie.sir.type.DeclaredSirType
class SirClass(
override var simpleName: String,
parent: SirDeclarationParent,
var kind: Kind = Kind.Class,
override var visibility: SirVisibility = SirVisibility.Public,
superTypes: List<DeclaredSirType> = emptyList(),
attributes: List<String> = emptyList(),
var publicTypeAlias: SirTypeAlias? = null,
var internalTypeAlias: SirTypeAlias? = null,
var isInherentlyHashable: Boolean = false,
override var isPrimitive: Boolean = false,
) : SirTypeDeclaration, SirDeclarationNamespace, SirTypeParameterParent, SirElementWithAttributes {
override var parent: SirDeclarationParent by sirDeclarationParent(parent)
val superTypes: MutableList<DeclaredSirType> = superTypes.toMutableList()
override val attributes: MutableList<String> = attributes.toMutableList()
override val defaultType: DeclaredSirType by lazy {
toType(emptyList())
}
override val isHashable: Boolean
get() = isInherentlyHashable || superTypes.any { it.isHashable }
override val typeParameters: MutableList<SirTypeParameter> = mutableListOf()
override val declarations: MutableList<SirDeclaration> = mutableListOf()
/**
* Name used to generate SKIE code.
*/
override val fqName: SirFqName
get() = super.fqName
override val originalFqName: SirFqName = fqName
/**
* Name that is expected to be used by external Swift code.
*/
override val publicName: SirFqName
get() = publicTypeAlias?.publicName ?: fqName
/**
* Name used by SKIE generated code to avoid many problems with ambiguous identifiers and bugs in Swift compiler.
*/
override val internalName: SirFqName
get() = internalTypeAlias?.internalName ?: publicName
override fun toString(): String = "${this::class.simpleName}: $fqName${if (fqName != publicName) "($publicName)" else ""}"
enum class Kind {
Class,
Enum,
Struct,
Protocol,
}
companion object {
context(SirDeclarationParent)
operator fun invoke(
simpleName: String,
kind: Kind = Kind.Class,
visibility: SirVisibility = SirVisibility.Public,
superTypes: List<DeclaredSirType> = emptyList(),
attributes: List<String> = emptyList(),
internalTypeAlias: SirTypeAlias? = null,
isInherentlyHashable: Boolean = false,
isPrimitive: Boolean = false,
): SirClass =
SirClass(
simpleName = simpleName,
parent = this@SirDeclarationParent,
kind = kind,
visibility = visibility,
superTypes = superTypes,
attributes = attributes,
internalTypeAlias = internalTypeAlias,
isInherentlyHashable = isInherentlyHashable,
isPrimitive = isPrimitive,
)
}
}
val SirClass.superClassType: DeclaredSirType?
get() = superTypes.map { it.resolveAsDirectClassSirType() }
.firstOrNull { (it?.declaration as? SirClass)?.kind == SirClass.Kind.Class }
val SirClass.superClass: SirClass?
get() = superClassType?.declaration as? SirClass
fun DeclaredSirType.resolveAsDirectClassSirType(): DeclaredSirType? =
when (declaration) {
is SirClass -> this
is SirTypeAlias -> {
when (val type = declaration.type) {
is DeclaredSirType -> type.resolveAsDirectClassSirType()
else -> null
}
}
}
fun DeclaredSirType.resolveAsDirectSirClass(): SirClass? =
resolveAsDirectClassSirType()?.declaration as? SirClass
| 8
|
Kotlin
|
4
| 409
|
73e41b4240fabfa05cddfcd30a08adb213c74064
| 3,858
|
SKIE
|
Apache License 2.0
|
src/main/kotlin/no/nav/familie/ef/søknad/ettersending/EttersendingService.kt
|
navikt
| 204,012,464
| false
|
{"Kotlin": 384792, "Dockerfile": 215}
|
package no.nav.familie.ef.søknad.ettersending
import no.nav.familie.ef.søknad.ettersending.mapper.EttersendingMapper
import no.nav.familie.ef.søknad.søknad.SøknadClient
import no.nav.familie.ef.søknad.søknad.domain.Kvittering
import no.nav.familie.ef.søknad.søknad.mapper.KvitteringMapper
import no.nav.familie.kontrakter.ef.ettersending.EttersendelseDto
import no.nav.familie.kontrakter.felles.ef.StønadType
import org.springframework.stereotype.Service
import java.time.LocalDateTime
@Service
class EttersendingService(private val søknadClient: SøknadClient) {
fun sendInn(
ettersending: EttersendelseDto,
innsendingMottatt: LocalDateTime,
): Kvittering {
val ettersedingRequestData: Map<StønadType, EttersendelseDto> = EttersendingMapper.groupByStønad(ettersending, innsendingMottatt)
val kvittering = søknadClient.sendInnEttersending(ettersedingRequestData)
return KvitteringMapper.mapTilEkstern(kvittering, innsendingMottatt)
}
fun hentEttersendingForPerson(personIdent: String): List<EttersendelseDto> {
return søknadClient.hentEttersendingForPerson(personIdent)
}
}
| 1
|
Kotlin
|
1
| 1
|
733b7d42cdb5e7fce29e8dc8e3cedfc07beedbc8
| 1,144
|
familie-ef-soknad-api
|
MIT License
|
libs/pandautils/src/main/java/com/instructure/pandautils/room/model/PendingSubmissionCommentWithFileUploadInput.kt
|
instructure
| 179,290,947
| false
| null |
package com.instructure.pandautils.room.model
import androidx.room.Embedded
import androidx.room.Relation
import com.instructure.canvasapi2.models.postmodels.CommentSendStatus
import com.instructure.canvasapi2.models.postmodels.FileUploadWorkerData
import com.instructure.canvasapi2.models.postmodels.PendingSubmissionComment
import com.instructure.pandautils.room.entities.FileUploadInputEntity
import com.instructure.pandautils.room.entities.PendingSubmissionCommentEntity
import java.util.*
data class PendingSubmissionCommentWithFileUploadInput(
@Embedded
val pendingSubmissionCommentEntity: PendingSubmissionCommentEntity,
@Relation(
parentColumn = "workerId",
entityColumn = "workerId"
)
val fileUploadInput: FileUploadInputEntity?
) {
fun toApiModel(): PendingSubmissionComment {
return PendingSubmissionComment(
pendingSubmissionCommentEntity.pageId,
pendingSubmissionCommentEntity.comment
).apply {
date = pendingSubmissionCommentEntity.date
id = pendingSubmissionCommentEntity.id
status = CommentSendStatus.valueOf(pendingSubmissionCommentEntity.status)
workerId = if (pendingSubmissionCommentEntity.workerId != null && pendingSubmissionCommentEntity.workerId != "null") {
UUID.fromString(pendingSubmissionCommentEntity.workerId)
} else {
null
}
workerInputData = FileUploadWorkerData(
fileUploadInput?.filePaths ?: emptyList(),
fileUploadInput?.courseId ?: -1L,
fileUploadInput?.assignmentId ?: -1L,
fileUploadInput?.userId ?: -1L
)
attemptId = pendingSubmissionCommentEntity.attemptId
}
}
}
| 7
| null |
85
| 99
|
1bac9958504306c03960bdce7fbb87cc63bc6845
| 1,801
|
canvas-android
|
Apache License 2.0
|
app/src/main/java/org/stepic/droid/ui/quiz/QuizDelegate.kt
|
StepicOrg
| 42,045,161
| false
|
{"Kotlin": 4281147, "Java": 1001895, "CSS": 5482, "Shell": 618}
|
package org.stepic.droid.ui.quiz
import android.view.View
import android.view.ViewGroup
import android.widget.Button
import org.stepik.android.model.Reply
import org.stepik.android.model.Submission
import org.stepik.android.model.attempts.Attempt
abstract class QuizDelegate {
abstract var isEnabled: Boolean
abstract var actionButton: Button?
abstract fun onCreateView(parent: ViewGroup): View
protected open fun onViewCreated(view: View) {}
fun createView(parent: ViewGroup) =
onCreateView(parent).also { onViewCreated(it) }
abstract fun setAttempt(attempt: Attempt?)
abstract fun setSubmission(submission: Submission?)
abstract fun createReply(): Reply
}
| 13
|
Kotlin
|
54
| 189
|
dd12cb96811a6fc2a7addcd969381570e335aca7
| 701
|
stepik-android
|
Apache License 2.0
|
examples/getting-started/shared/src/mingwX64Main/kotlin/dev/kotbase/gettingstarted/shared/Platform.mingwX64.kt
|
jeffdgr8
| 518,984,559
| false
|
{"Kotlin": 2266831, "Python": 294}
|
package dev.kotbase.gettingstarted.shared
actual class Platform actual constructor() {
actual val platform: String = "Windows"
}
| 0
|
Kotlin
|
0
| 7
|
ec8fbeb0d3e6c487ec8fb48ba2ba5388c71a29b1
| 134
|
kotbase
|
Apache License 2.0
|
app/src/main/java/com/kevalpatel2106/ci/greenbuild/di/ViewModelFactoryModule.kt
|
kevalpatel2106
| 129,620,378
| false
| null |
/*
* Copyright 2018 <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.kevalpatel2106.ci.greenbuild.di
import android.arch.lifecycle.ViewModel
import android.arch.lifecycle.ViewModelProvider
import com.kevalpatel2106.ci.greenbuild.about.AboutViewModel
import com.kevalpatel2106.ci.greenbuild.base.arch.DaggerViewModelFactory
import com.kevalpatel2106.ci.greenbuild.base.arch.ViewModelKey
import com.kevalpatel2106.ci.greenbuild.branchPicker.BranchPickerViewModel
import com.kevalpatel2106.ci.greenbuild.buildList.RecentBuildsFragment
import com.kevalpatel2106.ci.greenbuild.buildList.RecentBuildsListViewModel
import com.kevalpatel2106.ci.greenbuild.buildList.RepoBuildsListViewModel
import com.kevalpatel2106.ci.greenbuild.cacheList.CacheListViewModel
import com.kevalpatel2106.ci.greenbuild.ciSelector.CiSelectorViewModel
import com.kevalpatel2106.ci.greenbuild.cronList.CronListViewModel
import com.kevalpatel2106.ci.greenbuild.cronList.addCron.AddCronViewModel
import com.kevalpatel2106.ci.greenbuild.envVariableList.EnvVarsListViewModel
import com.kevalpatel2106.ci.greenbuild.envVariableList.editVariable.EditVariableViewModel
import com.kevalpatel2106.ci.greenbuild.main.MainActivityViewModel
import com.kevalpatel2106.ci.greenbuild.repoDetail.RepoDetailViewModel
import com.kevalpatel2106.ci.greenbuild.repoList.RepoListViewModel
import dagger.Binds
import dagger.Module
import dagger.multibindings.IntoMap
/**
* Created by Keval on 17/04/18.
*
* @author <a href="https://github.com/kevalpatel2106">kevalpatel2106</a>
*/
@Module
abstract class ViewModelFactoryModule {
@Binds
internal abstract fun bindViewModelFactory(factory: DaggerViewModelFactory): ViewModelProvider.Factory
@Binds
@IntoMap
@ViewModelKey(RepoListViewModel::class)
internal abstract fun bindRepoListViewModel(viewModel: RepoListViewModel): ViewModel
@Binds
@IntoMap
@ViewModelKey(RepoBuildsListViewModel::class)
internal abstract fun bindBuildListViewModel(viewModelRepo: RepoBuildsListViewModel): ViewModel
@Binds
@IntoMap
@ViewModelKey(CiSelectorViewModel::class)
internal abstract fun bindCiSelectorViewModel(viewModel: CiSelectorViewModel): ViewModel
@Binds
@IntoMap
@ViewModelKey(RepoDetailViewModel::class)
internal abstract fun bindRepoDetailViewModel(viewModel: RepoDetailViewModel): ViewModel
@Binds
@IntoMap
@ViewModelKey(EnvVarsListViewModel::class)
internal abstract fun bindEnvVarsListViewModel(viewModel: EnvVarsListViewModel): ViewModel
@Binds
@IntoMap
@ViewModelKey(CacheListViewModel::class)
internal abstract fun bindCacheListViewModel(viewModel: CacheListViewModel): ViewModel
@Binds
@IntoMap
@ViewModelKey(EditVariableViewModel::class)
internal abstract fun bindEditVariableViewModel(viewModel: EditVariableViewModel): ViewModel
@Binds
@IntoMap
@ViewModelKey(CronListViewModel::class)
internal abstract fun bindCronListViewModel(viewModel: CronListViewModel): ViewModel
@Binds
@IntoMap
@ViewModelKey(AddCronViewModel::class)
internal abstract fun bindAddCronViewModel(viewModel: AddCronViewModel): ViewModel
@Binds
@IntoMap
@ViewModelKey(BranchPickerViewModel::class)
internal abstract fun bindBranchPickerViewModel(viewModel: BranchPickerViewModel): ViewModel
@Binds
@IntoMap
@ViewModelKey(MainActivityViewModel::class)
internal abstract fun bindMainActivityViewModel(viewModel: MainActivityViewModel): ViewModel
@Binds
@IntoMap
@ViewModelKey(AboutViewModel::class)
internal abstract fun bindAboutViewModel(viewModel: AboutViewModel): ViewModel
@Binds
@IntoMap
@ViewModelKey(RecentBuildsListViewModel::class)
internal abstract fun bindRecentBuildsListViewModel(viewModel: RecentBuildsListViewModel): ViewModel
}
| 6
|
Kotlin
|
14
| 75
|
da9f2e64cd09848528f313d0e3188b7c40f4b3f7
| 4,372
|
green-build
|
Apache License 2.0
|
pretixscan/app/src/main/java/eu/pretix/pretixscan/droid/AndroidHttpClientFactory.kt
|
pretix
| 173,713,911
| false
|
{"Kotlin": 221714, "Java": 23039, "HTML": 1961, "Shell": 716}
|
package eu.pretix.pretixscan.droid
import android.os.Build
import eu.pretix.libpretixsync.api.HttpClientFactory
import eu.pretix.libpretixsync.api.RateLimitInterceptor
import okhttp3.OkHttpClient
import java.security.cert.X509Certificate
import java.util.concurrent.TimeUnit
import javax.net.ssl.HostnameVerifier
import javax.net.ssl.SSLContext
import javax.net.ssl.X509TrustManager
import javax.security.cert.CertificateException
class AndroidHttpClientFactory(val app: PretixScan) : HttpClientFactory {
override fun buildClient(ignore_ssl: Boolean): OkHttpClient {
val builder = OkHttpClient.Builder()
builder.addNetworkInterceptor(AndroidUserAgentInterceptor())
if (app.flipperInit?.interceptor != null) {
builder.addNetworkInterceptor(app.flipperInit!!.interceptor!!)
}
builder.addNetworkInterceptor(RateLimitInterceptor())
builder.connectTimeout(30, TimeUnit.SECONDS)
builder.readTimeout(30, TimeUnit.SECONDS)
builder.writeTimeout(30, TimeUnit.SECONDS)
if (ignore_ssl) {
val trustAllCerts = arrayOf<X509TrustManager>(object : X509TrustManager {
override fun getAcceptedIssuers(): Array<X509Certificate> {
return emptyArray()
}
@Throws(CertificateException::class)
override fun checkClientTrusted(chain: Array<java.security.cert.X509Certificate>, authType: String) {
}
@Throws(CertificateException::class)
override fun checkServerTrusted(chain: Array<java.security.cert.X509Certificate>, authType: String) {
}
fun checkServerTrusted(chain: Array<java.security.cert.X509Certificate>, authType: String, wat: String) {
// Called reflectively by
// https://android.googlesource.com/platform/frameworks/base/+/master/core/java/android/net/http/X509TrustManagerExtensions.java#64
}
})
// Install the all-trusting trust manager
val sslContext = SSLContext.getInstance("SSL")
sslContext.init(null, trustAllCerts, java.security.SecureRandom())
val sslSocketFactory = sslContext.getSocketFactory()
builder.sslSocketFactory(sslSocketFactory, trustAllCerts[0])
builder.hostnameVerifier(HostnameVerifier { hostname, session -> true })
} else if (Build.VERSION.SDK_INT < 26) { // Android 7.0 or lower
val certificates = CustomTrust().getCertificates()
builder.sslSocketFactory(certificates.sslSocketFactory(), certificates.trustManager)
}
return builder.build()
}
}
| 15
|
Kotlin
|
18
| 23
|
5b0d6108dfacb9635447b1943229b290e5150efd
| 2,725
|
pretixscan-android
|
Apache License 2.0
|
umaserverdemo/src/main/kotlin/com/lightspark/plugins/Routing.kt
|
lightsparkdev
| 590,703,408
| false
| null |
package com.lightspark.plugins
import com.lightspark.UmaConfig
import com.lightspark.Vasp2
import com.lightspark.sdk.uma.InMemoryPublicKeyCache
import com.lightspark.sdk.uma.UmaProtocolHelper
import io.ktor.server.application.Application
import io.ktor.server.application.ApplicationCall
import io.ktor.server.application.call
import io.ktor.server.response.respondText
import io.ktor.server.routing.get
import io.ktor.server.routing.post
import io.ktor.server.routing.routing
fun Application.configureRouting(config: UmaConfig) {
val pubKeyCache = InMemoryPublicKeyCache()
val uma = UmaProtocolHelper(pubKeyCache)
val vasp2 = Vasp2(config, uma)
routing {
get("/api/umalookup/:receiver") {
call.respondText("Hello World!")
}
get("/api/umapayreq/:callbackUuid") {
call.respondText("Hello World!")
}
post("/api/sendpayment/:callbackUuid") {
call.respondText("Hello World!")
}
// End VASP1 Routes
// VASP2 Routes:
get("/.well-known/lnurlp/:username") {
call.debugLog(vasp2.handleLnurlp(call))
}
get("/api/uma/payreq/:uuid") {
call.debugLog(vasp2.handleLnurlPayreq(call))
}
post("/api/uma/payreq/:uuid") {
call.debugLog(vasp2.handleUmaPayreq(call))
}
// End VASP2 Routes
// Shared:
get("/.well-known/lnurlpubkey") {
// It doesn't matter which vasp protocol handles this since they share a config and cache.
call.debugLog(vasp2.handlePubKeyRequest(call))
}
}
}
private fun ApplicationCall.debugLog(message: String) {
application.environment.log.debug(message)
}
| 0
|
Kotlin
|
0
| 2
|
b7b7a1133f69ad58522f01af71ce807d89adfc8e
| 1,733
|
kotlin-sdk
|
Apache License 2.0
|
buildSrc/subprojects/packaging/src/main/kotlin/org/gradle/gradlebuild/packaging/ShadedJarPlugin.kt
|
Verdinjoshua26
| 187,253,049
| false
| null |
/*
* Copyright 2018 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.gradle.gradlebuild.packaging
import accessors.base
import org.gradle.api.Action
import org.gradle.api.ActionConfiguration
import org.gradle.api.Plugin
import org.gradle.api.Project
import org.gradle.api.artifacts.Configuration
import org.gradle.api.artifacts.dsl.DependencyHandler
import org.gradle.api.artifacts.transform.ArtifactTransform
import org.gradle.api.attributes.Usage
import org.gradle.api.file.ProjectLayout
import org.gradle.api.model.ObjectFactory
import org.gradle.api.tasks.TaskProvider
import org.gradle.api.tasks.bundling.Jar
import org.gradle.kotlin.dsl.*
private
const val relocatedClassesAndAnalysisType = "relocatedClassesAndAnalysis"
private
const val relocatedClassesType = "relocatedClasses"
private
const val entryPointsType = "entryPoints"
private
const val classTreesType = "classTrees"
private
const val manifestsType = "manifests"
/**
* Creates a shaded jar of the publication of the current project.
*
* The shaded jar is added as an artifact to the {@code publishRuntime} configuration.
*/
open class ShadedJarPlugin : Plugin<Project> {
override fun apply(project: Project): Unit = project.run {
val shadedJarExtension = createShadedJarExtension(createConfigurationToShade())
registerTransforms(shadedJarExtension)
val shadedJarTask = addShadedJarTask(shadedJarExtension)
plugins.withId("gradlebuild.publish-public-libraries") {
addShadedJarArtifact(shadedJarTask)
}
}
private
fun Project.createShadedJarExtension(configurationToShade: Configuration) =
extensions.create<ShadedJarExtension>("shadedJar", layout, objects, configurationToShade)
private
fun Project.registerTransforms(shadedJarExtension: ShadedJarExtension) {
afterEvaluate {
dependencies {
registerTransform {
from
.attribute(artifactType, "jar")
.attribute(minified, true)
to.attribute(artifactType, relocatedClassesAndAnalysisType)
artifactTransform(ShadeClassesTransform::class.java) {
params(
"org.gradle.internal.impldep",
shadedJarExtension.keepPackages.get(),
shadedJarExtension.unshadedPackages.get(),
shadedJarExtension.ignoredPackages.get()
)
}
}
}
}
dependencies {
registerArtifactTypeTransform<FindRelocatedClasses>(relocatedClassesAndAnalysisType, relocatedClassesType)
registerArtifactTypeTransform<FindEntryPoints>(relocatedClassesAndAnalysisType, entryPointsType)
registerArtifactTypeTransform<FindClassTrees>(relocatedClassesAndAnalysisType, classTreesType)
registerArtifactTypeTransform<FindManifests>(relocatedClassesAndAnalysisType, manifestsType)
}
}
private
fun Project.createConfigurationToShade(): Configuration {
val configurationName = "jarsToShade"
afterEvaluate {
dependencies.add(configurationName, project)
}
return configurations.create(configurationName) {
attributes.attribute(Usage.USAGE_ATTRIBUTE, objects.named(Usage::class.java, Usage.JAVA_RUNTIME))
isCanBeResolved = true
isCanBeConsumed = false
}
}
private
fun Project.addShadedJarTask(shadedJarExtension: ShadedJarExtension): TaskProvider<ShadedJar> {
val configurationToShade = shadedJarExtension.shadedConfiguration
val baseVersion: String by rootProject.extra
val jar: TaskProvider<Jar> = tasks.withType(Jar::class.java).named("jar")
return tasks.register("${project.name}ShadedJar", ShadedJar::class.java) {
dependsOn(jar)
jarFile.set(layout.buildDirectory.file("shaded-jar/${base.archivesBaseName}-shaded-$baseVersion.jar"))
classTreesConfiguration.from(configurationToShade.artifactViewForType(classTreesType))
entryPointsConfiguration.from(configurationToShade.artifactViewForType(entryPointsType))
relocatedClassesConfiguration.from(configurationToShade.artifactViewForType(relocatedClassesType))
manifests.from(configurationToShade.artifactViewForType(manifestsType))
buildReceiptFile.set(shadedJarExtension.buildReceiptFile)
}
}
private
fun Project.addShadedJarArtifact(shadedJarTask: TaskProvider<ShadedJar>) {
artifacts.add("publishRuntime", mapOf(
"file" to shadedJarTask.get().jarFile.get().asFile,
"name" to base.archivesBaseName,
"type" to "jar",
"builtBy" to shadedJarTask
))
}
private
fun Configuration.artifactViewForType(artifactTypeName: String) = incoming.artifactView {
attributes.attribute(artifactType, artifactTypeName)
}.files
private
inline fun <reified T : ArtifactTransform> DependencyHandler.registerArtifactTypeTransform(fromType: String, toType: String, action: Action<ActionConfiguration> = Action {}) =
registerTransform {
from.attribute(artifactType, fromType)
to.attribute(artifactType, toType)
artifactTransform(T::class.java, action)
}
}
open class ShadedJarExtension(layout: ProjectLayout, objects: ObjectFactory, val shadedConfiguration: Configuration) {
/**
* The build receipt properties file.
*
* The file will be included in the shaded jar under {@code /org/gradle/build-receipt.properties}.
*/
val buildReceiptFile = layout.fileProperty()
/**
* Retain only those classes in the keep package hierarchies, plus any classes that are reachable from these classes.
*/
val keepPackages = objects.setProperty(String::class.java)!!
/**
* Do not rename classes in the unshaded package hierarchies. Always includes 'java'.
*/
val unshadedPackages = objects.setProperty(String::class.java)!!
/**
* Do not retain classes in the ignore packages hierarchies, unless reachable from some other retained class.
*/
val ignoredPackages = objects.setProperty(String::class.java)!!
}
| 10
| null |
1
| 2
|
cfeeb71d1e3159f5d10856aef854344ba92c4a0f
| 6,948
|
gradle
|
Apache License 2.0
|
pluto-plugins/plugins/exceptions/lib/src/main/java/com/pluto/plugins/exceptions/internal/ui/ListFragment.kt
|
androidPluto
| 390,471,457
| false
|
{"Kotlin": 744352, "Shell": 646}
|
package com.pluto.plugins.exceptions.internal.ui
import android.os.Bundle
import android.view.View
import android.view.View.GONE
import android.view.View.VISIBLE
import androidx.core.widget.doOnTextChanged
import androidx.fragment.app.Fragment
import androidx.fragment.app.activityViewModels
import androidx.lifecycle.Observer
import androidx.lifecycle.lifecycleScope
import androidx.navigation.fragment.findNavController
import com.pluto.plugins.exceptions.PlutoExceptions
import com.pluto.plugins.exceptions.R
import com.pluto.plugins.exceptions.databinding.PlutoExcepFragmentListBinding
import com.pluto.plugins.exceptions.internal.persistence.ExceptionEntity
import com.pluto.utilities.extensions.hideKeyboard
import com.pluto.utilities.extensions.linearLayoutManager
import com.pluto.utilities.extensions.showMoreOptions
import com.pluto.utilities.extensions.toast
import com.pluto.utilities.list.BaseAdapter
import com.pluto.utilities.list.CustomItemDecorator
import com.pluto.utilities.list.DiffAwareAdapter
import com.pluto.utilities.list.DiffAwareHolder
import com.pluto.utilities.list.ListItem
import com.pluto.utilities.setOnDebounceClickListener
import com.pluto.utilities.viewBinding
class ListFragment : Fragment(R.layout.pluto_excep___fragment_list) {
private val binding by viewBinding(PlutoExcepFragmentListBinding::bind)
private val viewModel: CrashesViewModel by activityViewModels()
private val crashAdapter: BaseAdapter by lazy { CrashesAdapter(onActionListener) }
private var isFetchingInProgress: Boolean = false
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
binding.crashList.apply {
adapter = crashAdapter
addItemDecoration(CustomItemDecorator(requireContext()))
}
binding.search.doOnTextChanged { text, _, _, _ ->
viewLifecycleOwner.lifecycleScope.launchWhenResumed {
text?.toString()?.let {
PlutoExceptions.session.lastSearchText = it
crashAdapter.list = filteredLogs(it)
if (it.isEmpty()) {
binding.crashList.linearLayoutManager()?.scrollToPositionWithOffset(0, 0)
}
}
}
}
binding.search.setText(PlutoExceptions.session.lastSearchText)
binding.close.setOnDebounceClickListener {
requireActivity().finish()
}
binding.options.setOnDebounceClickListener {
context?.showMoreOptions(it, R.menu.pluto_excep___menu_more_options) { item ->
when (item.itemId) {
R.id.clear -> viewModel.deleteAll()
}
}
}
isFetchingInProgress = true
viewModel.fetchAll()
viewModel.exceptions.removeObserver(exceptionObserver)
viewModel.exceptions.observe(viewLifecycleOwner, exceptionObserver)
}
private val exceptionObserver = Observer<List<ExceptionEntity>> {
isFetchingInProgress = false
crashAdapter.list = filteredLogs(binding.search.text.toString())
}
private fun filteredLogs(search: String): List<ExceptionEntity> {
var list = emptyList<ExceptionEntity>()
if (isFetchingInProgress) {
binding.loaderGroup.visibility = VISIBLE
} else {
binding.loaderGroup.visibility = GONE
viewModel.exceptions.value?.let {
list = it.filter { exception ->
(exception.data.exception.name ?: "").contains(search, true) ||
(exception.data.exception.file ?: "").contains(search, true)
}
}
binding.noItemText.text = getString(
if (search.isNotEmpty()) R.string.pluto_excep___no_search_result else R.string.pluto_excep___no_crashes_text
)
binding.noItemText.visibility = if (list.isEmpty()) VISIBLE else GONE
}
return list
}
private val onActionListener = object : DiffAwareAdapter.OnActionListener {
override fun onAction(action: String, data: ListItem, holder: DiffAwareHolder?) {
if (data is ExceptionEntity) {
requireActivity().hideKeyboard()
if (data.id != null) {
viewModel.fetch(data.id)
findNavController().navigate(R.id.openDetails)
} else {
requireContext().toast(getString(R.string.pluto_excep___invalid_id))
}
}
}
}
}
| 23
|
Kotlin
|
64
| 657
|
5562cb7065bcbcf18493820e287d87c7726f630b
| 4,622
|
pluto
|
Apache License 2.0
|
compiler/ir/ir.tree/gen/org/jetbrains/kotlin/ir/expressions/impl/IrCatchImpl.kt
|
JetBrains
| 3,432,266
| false
| null |
/*
* Copyright 2010-2024 JetBrains s.r.o. and Kotlin Programming Language contributors.
* Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file.
*/
// This file was generated automatically. See compiler/ir/ir.tree/tree-generator/ReadMe.md.
// DO NOT MODIFY IT MANUALLY.
@file:Suppress("DuplicatedCode")
package org.jetbrains.kotlin.ir.expressions.impl
import org.jetbrains.kotlin.ir.declarations.IrVariable
import org.jetbrains.kotlin.ir.expressions.IrCatch
import org.jetbrains.kotlin.ir.expressions.IrExpression
import org.jetbrains.kotlin.ir.util.IrElementConstructorIndicator
class IrCatchImpl internal constructor(
@Suppress("UNUSED_PARAMETER") constructorIndicator: IrElementConstructorIndicator?,
override val startOffset: Int,
override val endOffset: Int,
override var catchParameter: IrVariable,
) : IrCatch() {
override lateinit var result: IrExpression
}
| 183
| null |
5748
| 49,172
|
33eb9cef3d146062c103f9853d772f0a1da0450e
| 952
|
kotlin
|
Apache License 2.0
|
app/src/main/java/com/kieronquinn/app/taptap/ui/screens/settings/backuprestore/restore/permissionprompt/SettingsRestoreNotificationPermissionBottomSheetFragment.kt
|
KieronQuinn
| 283,883,226
| false
| null |
package com.kieronquinn.app.taptap.ui.screens.settings.backuprestore.restore.permissionprompt
import android.app.NotificationManager
import android.content.Context
import android.content.Intent
import android.os.Bundle
import android.provider.Settings
import androidx.activity.result.contract.ActivityResultContracts
import androidx.lifecycle.viewModelScope
import androidx.navigation.fragment.findNavController
import androidx.navigation.fragment.navArgs
import com.afollestad.materialdialogs.MaterialDialog
import com.kieronquinn.app.taptap.R
import com.kieronquinn.app.taptap.components.base.BaseBottomSheetDialogFragment
import com.kieronquinn.app.taptap.ui.screens.settings.backuprestore.restore.SettingsBackupRestoreRestoreViewModel
import kotlinx.coroutines.launch
import org.koin.android.viewmodel.ext.android.sharedViewModel
class SettingsRestoreNotificationPermissionBottomSheetFragment: BaseBottomSheetDialogFragment() {
private val permissionGrant = registerForActivityResult(ActivityResultContracts.StartActivityForResult()){}
private val arguments by navArgs<SettingsRestoreNotificationPermissionBottomSheetFragmentArgs>()
private val viewModel by sharedViewModel<SettingsBackupRestoreRestoreViewModel>()
private val isNotificationAccessGranted: Boolean
get(){
val notificationManager = requireContext().getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
return notificationManager.isNotificationPolicyAccessGranted
}
override fun onMaterialDialogCreated(materialDialog: MaterialDialog, savedInstanceState: Bundle?): MaterialDialog = materialDialog.apply {
title(R.string.restore_prompt_permission_title)
message(text = getMessage())
noAutoDismiss()
positiveButton(R.string.restore_prompt_grant){
permissionGrant.launch(getNotificationIntent())
}
negativeButton(R.string.restore_prompt_skip){
viewModel.viewModelScope.launch {
viewModel.skipAndMoveOn(SettingsBackupRestoreRestoreViewModel.SkippedReason.USER_SKIPPED)
}
close()
}
neutralButton(R.string.restore_prompt_cancel){
close()
viewModel.cancel()
}
}
private fun checkPermission(){
if(isNotificationAccessGranted){
viewModel.viewModelScope.launch {
viewModel.iterateAndMoveOn()
}
close()
}
}
override fun onResume() {
super.onResume()
checkPermission()
}
private fun getMessage(): String {
return when(val actionGate = arguments.actionGate){
is SettingsBackupRestoreRestoreViewModel.ActionGate.Action -> {
getString(R.string.restore_prompt_notification_permission_content_action, getString(actionGate.action.action.nameRes))
}
is SettingsBackupRestoreRestoreViewModel.ActionGate.Gate -> {
getString(R.string.restore_prompt_notification_permission_content_gate, getString(actionGate.gate.gate.nameRes))
}
is SettingsBackupRestoreRestoreViewModel.ActionGate.WhenGate -> {
getString(R.string.restore_prompt_notification_permission_content_when_gate, getString(actionGate.parentAction.action.nameRes), getString(actionGate.gate.gate.nameRes))
}
}
}
private fun getNotificationIntent(): Intent {
return Intent(Settings.ACTION_NOTIFICATION_POLICY_ACCESS_SETTINGS).apply {
addCategory(Intent.CATEGORY_DEFAULT)
addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
}
}
private fun close(){
findNavController().navigateUp()
}
}
| 52
| null |
2
| 2,251
|
abec5a3e139786beeea75e2fb5677013d0719bf1
| 3,741
|
TapTap
|
Apache License 2.0
|
live-video-sample/app/src/main/java/com/sendbird/live/videoliveeventsample/adapter/LiveEventListAdapter.kt
|
sendbird
| 542,961,997
| false
|
{"Kotlin": 271278}
|
package com.sendbird.live.uikit.sample.adapter
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.recyclerview.widget.DiffUtil
import androidx.recyclerview.widget.RecyclerView
import coil.load
import com.sendbird.live.LiveEvent
import com.sendbird.live.LiveEventState
import com.sendbird.live.LiveEventType
import com.sendbird.live.uikit.sample.R
import com.sendbird.live.uikit.sample.databinding.ListItemLiveEventBinding
import com.sendbird.live.uikit.sample.util.OnItemClickListener
import com.sendbird.live.uikit.sample.util.displayFormat
open class LiveEventListAdapter : RecyclerView.Adapter<LiveEventListAdapter.LiveEventListHolder>() {
private val liveEventList = mutableListOf<LiveEvent>()
private val cachedLiveEventInfoList = mutableListOf<LiveEventInfo>()
var onItemClickListener: OnItemClickListener<LiveEvent>? = null
var emptyStateView: View? = null
override fun onCreateViewHolder(
parent: ViewGroup,
viewType: Int
): LiveEventListHolder {
val inflater: LayoutInflater = LayoutInflater.from(parent.context)
val binding: ListItemLiveEventBinding = ListItemLiveEventBinding.inflate(inflater, parent, false)
return LiveEventListHolder(binding)
}
override fun onBindViewHolder(holder: LiveEventListHolder, position: Int) {
val liveEvent = liveEventList[position]
holder.bind(liveEvent)
holder.itemView.setOnClickListener {
val channelPosition = holder.adapterPosition
if (channelPosition != RecyclerView.NO_POSITION && onItemClickListener != null) {
onItemClickListener?.onItemClick(it, channelPosition, liveEventList[channelPosition])
}
}
}
override fun getItemCount() = liveEventList.size
fun addItems(liveEvents: List<LiveEvent>?) {
if (liveEvents != null) {
val list = mutableListOf<LiveEvent>().apply {
addAll(liveEventList)
addAll(liveEvents)
}
submitList(list.toList())
}
}
fun submitList(liveEvents: List<LiveEvent>) {
val diffCallback = LiveEventDiffCallback(cachedLiveEventInfoList, liveEvents)
val diffResult = DiffUtil.calculateDiff(diffCallback)
cachedLiveEventInfoList.clear()
cachedLiveEventInfoList.addAll(LiveEventInfo.toLiveEventInfoList(liveEvents))
liveEventList.clear()
liveEventList.addAll(liveEvents)
diffResult.dispatchUpdatesTo(this)
checkEmpty()
}
private fun checkEmpty() {
val visibility = if (liveEventList.isEmpty()) View.VISIBLE else View.GONE
emptyStateView?.visibility = visibility
}
class LiveEventListHolder(private val binding: ListItemLiveEventBinding) :
RecyclerView.ViewHolder(binding.root) {
fun bind(liveEvent: LiveEvent) {
binding.tvTitle.text = if (!liveEvent.title.isNullOrEmpty()) liveEvent.title else binding.root.context.getString(R.string.live_event)
binding.tvSubtitle.text = liveEvent.hosts.joinToString(", ") { it.userId }
binding.tvParticipantCount.text = liveEvent.participantCount.displayFormat()
val indicatorBackgroundRes = if (liveEvent.state == LiveEventState.ONGOING) R.drawable.shape_live_event_ongoing_indicator else R.drawable.shape_live_event_pause_indicator
binding.vLiveIndicator.setBackgroundResource(indicatorBackgroundRes)
binding.tvLiveEventType.text = if (liveEvent.type == LiveEventType.AUDIO_ONLY) "AUDIO ONLY" else "VIDEO"
val coverBackgroundRes =
if (!liveEvent.coverUrl.isNullOrBlank()) liveEvent.coverUrl
else when (adapterPosition % 5) {
0 -> R.drawable.coverimage_live_1
1 -> R.drawable.coverimage_live_2
2 -> R.drawable.coverimage_live_3
3 -> R.drawable.coverimage_live_4
else -> R.drawable.coverimage_live_5
}
binding.ivLiveThumbnail.load(coverBackgroundRes) {
crossfade(true)
placeholder(R.drawable.icon_default_user)
error(R.drawable.icon_default_user)
}
val (stringResId, textAppearance, backgroundResId) = when (liveEvent.state) {
LiveEventState.CREATED -> Triple(R.string.upcoming, R.style.Text12Primary300Bold, R.drawable.shape_live_state_created_background)
LiveEventState.READY -> Triple(R.string.open, R.style.Text12Open300Bold, R.drawable.shape_live_state_ready_background)
LiveEventState.ONGOING -> Triple(R.string.live, R.style.Text12OnDark01Bold, R.drawable.shape_live_state_ongoing_background)
LiveEventState.ENDED -> Triple(R.string.ended, R.style.Text12OnLight02Bold, R.drawable.shape_live_state_ended_background)
}
with(binding.tvLiveEventStatus) {
this.text = context.getString(stringResId)
setTextAppearance(textAppearance)
setBackgroundResource(backgroundResId)
}
}
}
private class LiveEventDiffCallback(
private val oldItems: List<LiveEventInfo>,
private val newItems: List<LiveEvent>
) : DiffUtil.Callback() {
override fun getOldListSize(): Int {
return oldItems.size
}
override fun getNewListSize(): Int {
return newItems.size
}
override fun areItemsTheSame(oldItemPosition: Int, newItemPosition: Int): Boolean {
val oldItem = oldItems[oldItemPosition]
val newItem = newItems[newItemPosition]
return oldItem.liveEventId == newItem.liveEventId
}
override fun areContentsTheSame(oldItemPosition: Int, newItemPosition: Int): Boolean {
val oldItem = oldItems[oldItemPosition]
val newItem = newItems[newItemPosition]
return oldItem.state == newItem.state
&& oldItem.title == newItem.title
&& oldItem.coverUrl == newItem.coverUrl
&& oldItem.hostName == newItem.hosts.joinToString(", ") { it.userId }
&& oldItem.isHostStreaming == newItem.isHostStreaming
&& oldItem.participantCount == newItem.participantCount
}
}
internal class LiveEventInfo(val liveEvent: LiveEvent) {
val liveEventId: String = liveEvent.liveEventId
val participantCount: Int = liveEvent.participantCount
val title: String? = liveEvent.title
val hostName: String? = liveEvent.hosts.joinToString(", ") { it.userId }
val state: LiveEventState = liveEvent.state
val isHostStreaming: Boolean = liveEvent.isHostStreaming
val coverUrl: String? = liveEvent.coverUrl
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (javaClass != other?.javaClass) return false
other as LiveEventInfo
if (liveEvent != other.liveEvent) return false
if (liveEventId != other.liveEventId) return false
if (participantCount != other.participantCount) return false
if (title != other.title) return false
if (hostName != other.hostName) return false
if (state != other.state) return false
if (isHostStreaming != other.isHostStreaming) return false
if (coverUrl != other.coverUrl) return false
return true
}
override fun hashCode(): Int {
var result = liveEvent.hashCode()
result = 31 * result + liveEventId.hashCode()
result = 31 * result + participantCount
result = 31 * result + title.hashCode()
result = 31 * result + (hostName?.hashCode() ?: 0)
result = 31 * result + state.hashCode()
result = 31 * result + isHostStreaming.hashCode()
result = 31 * result + coverUrl.hashCode()
return result
}
companion object {
fun toLiveEventInfoList(liveEventList: List<LiveEvent>): List<LiveEventInfo> {
val results: MutableList<LiveEventInfo> = ArrayList()
for (liveEvent in liveEventList) {
results.add(LiveEventInfo(liveEvent))
}
return results
}
}
}
}
| 1
|
Kotlin
|
1
| 1
|
24aaad8749f827ce4900f06838534335aa2ffb6a
| 8,507
|
sendbird-live-sample-android
|
MIT License
|
app/composeapp/src/main/java/com/example/srmc/composeapp/ui/screens/form/DoctorSchedScreen.kt
|
ajcatindig
| 699,722,916
| false
|
{"Kotlin": 334416}
|
package com.example.srmc.composeapp.ui.screens.form
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.selection.selectable
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.foundation.verticalScroll
import androidx.compose.material.Button
import androidx.compose.material.ButtonDefaults
import androidx.compose.material.Icon
import androidx.compose.material.IconButton
import androidx.compose.material.MaterialTheme
import androidx.compose.material.RadioButton
import androidx.compose.material.RadioButtonDefaults
import androidx.compose.material.Text
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.outlined.ArrowBackIos
import androidx.compose.runtime.Composable
import androidx.compose.runtime.derivedStateOf
import androidx.compose.runtime.getValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.semantics.Role
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import com.example.srmc.composeapp.component.ConnectivityStatus
import com.example.srmc.composeapp.component.dialog.FailureDialog
import com.example.srmc.composeapp.component.dialog.LoaderDialog
import com.example.srmc.composeapp.component.list.ScheduleList
import com.example.srmc.composeapp.component.scaffold.SRMCScaffold
import com.example.srmc.composeapp.component.scaffold.form.SchedListTopBar
import com.example.srmc.composeapp.ui.theme.typography
import com.example.srmc.composeapp.utils.collectState
import com.example.srmc.core.model.Doctor
import com.example.srmc.core.model.Schedules
import com.example.srmc.view.viewmodel.detail.DoctorDetailViewModel
import com.example.srmc.view.viewmodel.form.AppointmentFormViewModel
import com.example.srmc.view.viewmodel.form.SchedulesViewModel
import com.google.accompanist.swiperefresh.SwipeRefresh
import com.google.accompanist.swiperefresh.rememberSwipeRefreshState
@Composable
fun DoctorSchedScreen(
onNavigateUp : () -> Unit,
viewModel1 : DoctorDetailViewModel,
viewModel2 : SchedulesViewModel,
viewModel3 : AppointmentFormViewModel,
onNavigateToSlots : (Int, String) -> Unit)
{
val state1 by viewModel1.collectState()
val state2 by viewModel2.collectState()
val state3 by viewModel3.collectState()
DoctorSchedFormContent(
isLoading = state2.isLoading ,
error = state2.error,
onNavigateUp = onNavigateUp ,
onNavigateToSlots = onNavigateToSlots,
doctor = state1.data,
selectedDoctor = state3.doctor_id,
onSelectedDoctor = viewModel3::setDoctorId,
schedule = state2.data,
selectedDate = state3.date,
onDateChange = viewModel3::setDate)
}
@Composable
fun DoctorSchedFormContent(
isLoading : Boolean,
error : String?,
onNavigateUp : () -> Unit,
onNavigateToSlots : (Int, String) -> Unit,
doctor : Doctor,
selectedDoctor : Int,
onSelectedDoctor : (Int) -> Unit,
schedule : List<Schedules>,
selectedDate : String,
onDateChange : (String) -> Unit
)
{
if (isLoading) {
LoaderDialog()
}
if (error != null) {
FailureDialog(error)
}
Column(modifier = Modifier
.fillMaxSize()
.background(MaterialTheme.colors.surface)
.verticalScroll(rememberScrollState()),
horizontalAlignment = Alignment.CenterHorizontally)
{
BackToDoctor(Modifier.align(Alignment.Start), onBackClick = onNavigateUp)
TopMessageSchedule()
Column(modifier = Modifier
.fillMaxWidth()
.padding(horizontal = 16.dp))
{
DoctorSchedForm(
onNavigateToSlots = onNavigateToSlots,
schedule = schedule,
doctor = doctor,
selectedDoctor = selectedDoctor,
onSelectedDoctor = onSelectedDoctor,
selectedDate = selectedDate,
onDateChange = onDateChange)
}
}
}
@Composable
fun DoctorSchedForm(
onNavigateToSlots : (Int, String) -> Unit,
schedule : List<Schedules>,
doctor : Doctor,
selectedDoctor : Int,
onSelectedDoctor : (Int) -> Unit,
selectedDate : String,
onDateChange : (String) -> Unit)
{
val isValidate by derivedStateOf { selectedDate.isNotBlank() }
Column(modifier = Modifier
.fillMaxSize(),
horizontalAlignment = Alignment.CenterHorizontally,
verticalArrangement = Arrangement.Center)
{
Column(modifier = Modifier
.fillMaxWidth()
.padding(start = 16.dp , end = 16.dp , top = 20.dp , bottom = 16.dp),
horizontalAlignment = Alignment.CenterHorizontally,
verticalArrangement = Arrangement.Center)
{
Row(modifier = Modifier
.fillMaxWidth()
.padding(bottom = 8.dp),
horizontalArrangement = Arrangement.Start,
verticalAlignment = Alignment.CenterVertically)
{
Text(text = "Doctor Info",
style = typography.h5,
fontSize = 18.sp,
textAlign = TextAlign.Start)
}
Row(modifier = Modifier
.fillMaxWidth()
.padding(bottom = 8.dp),
horizontalArrangement = Arrangement.Start,
verticalAlignment = Alignment.CenterVertically)
{
Text(text = "Dr. ${doctor.name.orEmpty()}",
style = typography.caption,
fontSize = 16.sp,
textAlign = TextAlign.Start)
}
Row(modifier = Modifier
.fillMaxWidth()
.padding(bottom = 8.dp),
horizontalArrangement = Arrangement.Start,
verticalAlignment = Alignment.CenterVertically)
{
Text(text = doctor.email ?: "No Email Provided",
style = typography.caption,
fontSize = 16.sp,
textAlign = TextAlign.Start)
}
Row(modifier = Modifier
.fillMaxWidth()
.padding(bottom = 4.dp),
horizontalArrangement = Arrangement.Start,
verticalAlignment = Alignment.CenterVertically)
{
Text(text = doctor.contact_number ?: "No Number Provided",
style = typography.caption,
fontSize = 16.sp,
textAlign = TextAlign.Start)
}
}
Column(modifier = Modifier
.fillMaxWidth()
.padding(start = 16.dp , end = 16.dp , bottom = 16.dp),
verticalArrangement = Arrangement.Center,
horizontalAlignment = Alignment.CenterHorizontally)
{
Row(modifier = Modifier
.fillMaxWidth()
.padding(bottom = 8.dp),
horizontalArrangement = Arrangement.Start,
verticalAlignment = Alignment.CenterVertically)
{
Text(text = "Available Dates",
style = typography.h5,
fontSize = 18.sp,
textAlign = TextAlign.Start)
}
schedule.forEach { index ->
Row(modifier = Modifier
.fillMaxWidth()
.padding(bottom = 0.dp)
.selectable(selected = (selectedDate == index.date) , onClick = { onDateChange(index.date !!) } , role = Role.Button),
horizontalArrangement = Arrangement.Start,
verticalAlignment = Alignment.CenterVertically)
{
RadioButton(
selected = (selectedDate == index.date),
onClick = { onDateChange(index.date!!) },
modifier = Modifier.padding(end = 8.dp),
colors = RadioButtonDefaults.colors(
selectedColor = Color(0xff15C3DD),
unselectedColor = Color(0xff15C3DD).copy(alpha = 0.5f)
))
Text(text = "${index.date_label.orEmpty()} (${index.slots} slots) ",
style = typography.caption,
fontSize = 16.sp,
textAlign = TextAlign.Start)
}
}
}
}
Column(modifier = Modifier
.fillMaxWidth()
.padding(start = 16.dp , end = 16.dp),
horizontalAlignment = Alignment.CenterHorizontally,
verticalArrangement = Arrangement.Center)
{
Row(modifier = Modifier.fillMaxWidth(),
verticalAlignment = Alignment.CenterVertically,
horizontalArrangement = Arrangement.Center)
{
Button(onClick = { onNavigateToSlots(doctor.id!!, selectedDate) } ,
enabled = isValidate ,
modifier = Modifier
.fillMaxSize()
.height(50.dp) ,
colors = ButtonDefaults.buttonColors(backgroundColor = Color(0xff15C3DD)) ,
shape = RoundedCornerShape(25.dp))
{
Text(text = "NEXT" , color = Color.White , style = typography.h6)
}
}
}
}
@Composable
fun BackToDoctor(modifier : Modifier , onBackClick : () -> Unit)
{
IconButton(onClick = onBackClick, modifier.padding(start = 8.dp, end = 8.dp, bottom = 4.dp, top = 20.dp))
{
Icon(
Icons.Outlined.ArrowBackIos , contentDescription = "" ,
tint = MaterialTheme.colors.onPrimary)
}
}
@Composable
fun TopMessageSchedule()
{
Column(modifier = Modifier
.fillMaxWidth()
.padding(horizontal = 16.dp) ,
horizontalAlignment = Alignment.CenterHorizontally ,
verticalArrangement = Arrangement.Center)
{
Text(text = "Select a Date" ,
style = MaterialTheme.typography.h5 ,
fontSize = 25.sp ,
textAlign = TextAlign.Center)
}
}
| 0
|
Kotlin
|
0
| 0
|
eb43372e611366e925c7fae2509efa741d2bdf71
| 11,066
|
SRMC
|
MIT License
|
browser-kotlin/src/jsMain/kotlin/web/crypto/AesKeyAlgorithm.kt
|
karakum-team
| 393,199,102
| false
|
{"Kotlin": 6630901}
|
// Automatically generated - do not modify!
package web.crypto
sealed external interface AesKeyAlgorithm :
KeyAlgorithm {
var length: Short
}
| 0
|
Kotlin
|
6
| 28
|
664781d7bdaf5f4aca206e11990b1d304fd45212
| 152
|
types-kotlin
|
Apache License 2.0
|
src/main/kotlin/nl/utwente/student/metrics/ResponseForAClass.kt
|
MarnickvdA
| 571,956,335
| false
| null |
package nl.utwente.student.metrics
import nl.utwente.student.metamodel.v3.Module
import nl.utwente.student.metamodel.v3.Unit
import nl.utwente.student.metamodel.v3.UnitCall
import nl.utwente.student.visitors.ModuleVisitor
import nl.utwente.student.visitors.SourceElementFinder.findAllByExpressionType
class ResponseForAClass : ModuleVisitor() {
override var result: Int? = 0
override fun getTag(): String = "RFC"
override fun visitModule(module: Module?) {
if (module == null) return
val methods = module.members.filterIsInstance<Unit>()
.filter { !it.id.endsWith(".constructor") && !it.id.endsWith(".initializer") }
val calls = methods
.map { findAllByExpressionType<UnitCall>(it.body) { e -> e is UnitCall } }
.flatten()
.mapNotNull { it.declarableId }
.toSet()
// TODO(Document: How to handle records, should you see the primary constructor as a +1, should you include the 'generated' functions as methods? Should you include getters and setters on properties as methods?)
result = mutableSetOf<String>().also {
it.addAll(methods.map { m -> m.id })
it.addAll(calls)
}.size
}
}
| 0
|
Kotlin
|
0
| 0
|
9fcc44d65eedec25c12c52c6303935719e16bc49
| 1,234
|
LAMP-Framework
|
MIT License
|
src/main/kotlin/model/RequestResult.kt
|
Jakub9
| 834,452,863
| false
|
{"Kotlin": 38612}
|
package de.reeii.checkthesite.model
import de.reeii.checkthesite.checker.SiteChecker
enum class RequestResult {
/**
* Request was successful and the website got checked positively according to the [SiteChecker] implementation
*/
POSITIVE,
/**
* Request was successful, but the website got checked negatively according to the [SiteChecker] implementation
*/
NEGATIVE,
/**
* Request failed for whatever reason (response code not in 200-299, connection failed, whatever)
*/
FAILED
}
| 0
|
Kotlin
|
0
| 0
|
8c6abd1a1640ac557404e630cce99108b4b55ff1
| 537
|
CheckTheSite
|
MIT License
|
demo/src/main/kotlin/dev/skye/daisy/MeterRegistryCounters.kt
|
lopcode
| 342,974,433
| false
|
{"Kotlin": 54970, "Shell": 534}
|
package dev.skye.daisy
import io.micrometer.core.instrument.Counter
import io.micrometer.core.instrument.MeterRegistry
import io.micrometer.core.instrument.Tag
internal fun MeterRegistry.makeGeneratedCounter(queue: String): Counter {
return this.counter(
"messages.generated",
listOf(
Tag.of("queue", queue)
)
)
}
| 0
|
Kotlin
|
0
| 7
|
8c2d2cf20709a05ec28c7efa17ac49778a38e0c2
| 360
|
Daisy
|
Apache License 2.0
|
src/commonMain/kotlin/app/thelema/gltf/GLTFBuffer.kt
|
zeganstyl
| 275,550,896
| false
| null |
/*
* Copyright 2020-2021 <NAME>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package app.thelema.gltf
import app.thelema.app.APP
import app.thelema.app.printElapsedTime
import app.thelema.data.DATA
import app.thelema.data.DataByteOrder
import app.thelema.data.IByteData
import app.thelema.utils.LOG
/** [glTF 2.0 specification](https://github.com/KhronosGroup/glTF/tree/master/specification/2.0#buffers-and-buffer-views)
* @author zeganstyl */
class GLTFBuffer(array: IGLTFArray): GLTFArrayElementAdapter(array) {
var uri: String = ""
var bytes: IByteData = DATA.nullBuffer
var byteLength: Int = bytes.limit
override fun readJson() {
super.readJson()
uri = json.string("uri", "")
byteLength = json.int("byteLength", 0)
if (uri.isEmpty()) {
bytes = gltf.binChunks[elementIndex].chunkData
ready()
} else {
if (uri.startsWith("data:")) {
// data:application/octet-stream;base64,
val headerBody = uri.split(",".toRegex(), 2).toTypedArray()
// System.out.println(header);
val body = headerBody[1]
bytes = DATA.decodeBase64(body)
bytes.order = DataByteOrder.LittleEndian
} else {
val file = gltf.directory.child(DATA.decodeURI(uri))
file.readBytes(
ready = {
bytes = it
ready()
},
error = {
LOG.info("can't read $uri, status: $it")
ready()
}
)
}
}
}
override fun writeJson() {
super.writeJson()
json["uri"] = uri
json["byteLength"] = bytes.limit
}
override fun destroy() {
bytes.destroy()
bytes = DATA.nullBuffer
}
fun writeBytes() {
val file = gltf.directory.child(uri)
bytes.position = 0
file.writeBytes(bytes)
}
}
| 3
|
Kotlin
|
5
| 61
|
8e2943b6d2de3376ce338025b58ff31c14097caf
| 2,576
|
thelema-engine
|
Apache License 2.0
|
app/src/main/java/com/dropbox/android/sample/Graph.kt
|
yigit
| 194,454,615
| false
| null |
package com.dropbox.android.sample
import android.content.Context
import android.text.Html
import androidx.room.Room
import com.dropbox.android.sample.data.model.Children
import com.dropbox.android.sample.data.model.Post
import com.dropbox.android.sample.data.model.RedditDb
import com.dropbox.android.sample.data.remote.Api
import com.dropbox.android.external.fs3.FileSystemPersister
import com.dropbox.android.external.fs3.PathResolver
import com.dropbox.android.external.fs3.SourcePersisterFactory
import com.dropbox.android.external.fs3.filesystem.FileSystemFactory
import com.dropbox.android.external.store4.StoreBuilder
import com.dropbox.android.external.store4.MemoryPolicy
import com.dropbox.android.external.store4.Persister
import com.dropbox.android.external.store4.Store
import com.dropbox.android.external.store4.SourceOfTruth
import com.dropbox.android.external.store4.legacy.BarCode
import com.dropbox.android.external.store4.nonFlowValueFetcher
import com.squareup.moshi.Moshi
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.ExperimentalCoroutinesApi
import kotlinx.coroutines.FlowPreview
import kotlinx.coroutines.delay
import kotlinx.coroutines.withContext
import okio.Buffer
import okio.BufferedSource
import retrofit2.Retrofit
import retrofit2.converter.moshi.MoshiConverterFactory
import java.io.File
import java.io.IOException
import kotlin.time.ExperimentalTime
import kotlin.time.seconds
@OptIn(
FlowPreview::class,
ExperimentalCoroutinesApi::class,
ExperimentalTime::class,
ExperimentalStdlibApi::class
)
object Graph {
private val moshi = Moshi.Builder().build()
fun provideRoomStore(context: SampleApp): Store<String, List<Post>> {
val db = provideRoom(context)
return StoreBuilder
.from(
nonFlowValueFetcher { key: String ->
provideRetrofit().fetchSubreddit(key, 10).data.children.map(::toPosts)
},
sourceOfTruth = SourceOfTruth.from(
reader = db.postDao()::loadPosts,
writer = db.postDao()::insertPosts,
delete = db.postDao()::clearFeedBySubredditName,
deleteAll = db.postDao()::clearAllFeeds
)
)
.build()
}
fun provideRoomStoreMultiParam(context: SampleApp): Store<Pair<String, RedditConfig>, List<Post>> {
val db = provideRoom(context)
return StoreBuilder
.from<Pair<String, RedditConfig>, List<Post>, List<Post>>(
nonFlowValueFetcher { (query, config) ->
provideRetrofit().fetchSubreddit(query, config.limit)
.data.children.map(::toPosts)
},
sourceOfTruth = SourceOfTruth.from(
reader = { (query, _) -> db.postDao().loadPosts(query) },
writer = { (query, _), posts -> db.postDao().insertPosts(query, posts) },
delete = { (query, _) -> db.postDao().clearFeedBySubredditName(query) },
deleteAll = db.postDao()::clearAllFeeds
)
)
.build()
}
private fun provideRoom(context: SampleApp): RedditDb {
return Room.inMemoryDatabaseBuilder(context, RedditDb::class.java)
.build()
}
/**
* Returns a new Persister with the cache as the root.
*/
@Throws(IOException::class)
fun newPersister(cacheDir: File): Persister<BufferedSource, BarCode> {
return SourcePersisterFactory.create(cacheDir)
}
fun provideConfigStore(context: Context): Store<Unit, RedditConfig> {
val fileSystem = FileSystemFactory.create(context.cacheDir)
val fileSystemPersister =
FileSystemPersister.create(fileSystem, object : PathResolver<Unit> {
override fun resolve(key: Unit) = "config.json"
})
val adapter = moshi.adapter<RedditConfig>(RedditConfig::class.java)
return StoreBuilder
.from<Unit, RedditConfig, RedditConfig>(
nonFlowValueFetcher {
delay(500)
RedditConfig(10)
},
sourceOfTruth = SourceOfTruth.fromNonFlow(
reader = {
runCatching {
val source = fileSystemPersister.read(Unit)
source?.let { adapter.fromJson(it) }
}.getOrNull()
},
writer = { _, config ->
val buffer = Buffer()
withContext(Dispatchers.IO) {
adapter.toJson(buffer, config)
}
fileSystemPersister.write(Unit, buffer)
}
))
.cachePolicy(
MemoryPolicy.builder().setExpireAfterWrite(10.seconds).build()
)
.build()
}
private fun provideRetrofit(): Api {
return Retrofit.Builder()
.baseUrl("https://reddit.com/")
.addConverterFactory(MoshiConverterFactory.create(moshi))
.build()
.create(Api::class.java)
}
private fun toPosts(it: Children): Post {
return it.data.copy(
preview = it.data.preview?.let {
it.copy(
images = it.images.map { image ->
@Suppress("DEPRECATION")
image.copy(
source = image.source.copy(
// preview urls are html encoded, need to escape
url = Html.fromHtml(image.source.url).toString()
)
)
}
)
}
)
}
}
| 38
| null |
167
| 6
|
929b4c40a48251ee07372b4ae75cfc3e17c00540
| 5,900
|
Core
|
Apache License 2.0
|
src/main/kotlin/org/agoranomic/assessor/decisions/8266-8274.kt
|
AgoraNomic
| 98,589,628
| false
| null |
package org.agoranomic.assessor.decisions
import org.agoranomic.assessor.dsl.assessment
import org.agoranomic.assessor.dsl.receivers.ai
import org.agoranomic.assessor.dsl.receivers.coauthors
import org.agoranomic.assessor.dsl.receivers.quorum
import org.agoranomic.assessor.dsl.receivers.url
import org.agoranomic.assessor.dsl.votes.endorse
import org.agoranomic.assessor.dsl.votes.match
import org.agoranomic.assessor.dsl.votes.pmBonus
import org.agoranomic.assessor.lib.vote.VoteKind.*
@UseAssessment
fun assessment8266to8274() = assessment {
name("8266-8274")
url("https://mailman.agoranomic.org/cgi-bin/mailman/private/agora-official/2019-November/013256.html")
quorum(8)
strengths {
default(3)
min(0)
max(5)
pmBonus(G)
}
proposals(v0) {
proposal(8266) {
title("Glitter")
ai("1.0")
author(nix)
text(
"""
Enact a Power-1 rule titled "Glitter" with the following text {
If a player has earned a ribbon in the past 7 days but already owned it e CAN
once (until e earns another ribbon), by announcement, earn N+1 coins where
N is the number of current players that do not own the same ribbon.
}"""
)
}
proposal(8267) {
title("Emerald Ribbons")
ai("3.0")
author(Janet)
text(
"""
Amend Rule 2438 ("Ribbons") by appending the following paragraph:
Emerald (E): When a person wins an election, e earns an Emerald Ribbon.
[There's already a ribbon for deputisation, so why shouldn't there be
one for the other way to acquire an office? Also, this is an incentive
to initiate and become candidates in elections.]"""
)
}
proposal(8268) {
title("Deputisation fix")
ai("3.0")
author(Janet)
text(
"""
Amend Rule 2160 ("Deputisation") by replacing the text "acting on eir
own behalf" with the text "acting as emself".
[Per CFJ 2637, taking actions within a public message is not acting on
the behalf of oneself, so it may currently be impossible to deputise
without some shenanigans. "Acting as emself" appears to be the standard
way of phrasing this requirement.]"""
)
}
proposal(8269) {
title("Clean up distribution mechanisms")
ai("3.0")
author(omd)
text(
"""
Amend Rule 1607 (Distribution) by replacing;
The Promotor CAN distribute a proposal which is in the Proposal
Pool at any time, by announcement.
with:
The Promotor CAN distribute a proposal which is in the Proposal
Pool at any time.
[The "by announcement" is redundant with Rule 107's 'notice publication'
method, and IIRC there was a judgement that the two rules actually provide two
separate mechanisms for distributing proposals.]"""
)
}
proposal(8270) {
title("Self-ratifying statements")
ai("3.0")
author(omd)
text(
"""
[Create a mechanism for a public message to be defined as self-ratifying a
statement that's not in the message.
Currently, Rule 2034 does this in a strange implicit way, by saying that the
message "constitutes self-ratifying claims that" such-and-such. I'd call it
dubious, but according to CFJ 3618 as recorded in a FLR annotation (I can't
find the original judgement), it does work, even if the message in question
*explicitly disclaims* the such-and-such. Still, it's better to organize
things in a way that avoids counterfactual assumptions.
Convert two rules to use the new mechanism: Rule 2034, and Rule 107, which
previously vaguely mentioned an error being "correctly identified within one
week". The new wording also requires clarity, as I also proposed separately
(if both proposal pass, this overwrites the wording from the other).]
Amend Rule 1551 (Ratification) by replacing:
When a public document is ratified
with:
When a document or statement (hereafter "document") is ratified
and by replacing:
Ratifying a public document is secured with power threshold 3.
with:
Ratification is secured with power threshold 3.
and by removing:
A public document is part (possibly all) of a public message.
[moved to R2202]
Amend Rule 2202 (Ratification Without Objection) by prepending the paragraph:
A public document is part (possibly all) of a public message.
Amend Rule 2201 (Self-Ratification) by replacing:
A public document defined by the rules as self-ratifying is
ratified when it is continuously undoubted for one week.
A doubt is an explicit public challenge via one of the following
methods, identifying a document and explaining the scope and
nature of a perceived error in it:
with:
When a public document is continuously undoubted for one week
after publication:
- If the rules define it as self-ratifying, it is ratified.
- If the rules define it as a self-ratifying attestation to a
given statement, the statement is ratified.
This clause is inapplicable if the statement to be ratified
cannot be reasonably ascertained from the ruleset and the
contents of the message.
A doubt is an explicit public challenge via one of the following
methods, identifying a document and explaining the scope and
nature of a perceived error in it (or in a statement it attests
to):
Amend Rule 107 (Initiating Agoran Decisions) by replacing the second
sentence with:
To be valid, the notice must clearly specify the following
information:
and by appending the paragraph:
A public notice purporting to initiate an Agoran decision is a
self-ratifying attestation of the notice's validity.
Amend Rule 2034 (Vote Protection and Cutoff for Challenges) by replacing:
A public message purporting to resolve an Agoran decision
constitutes self-ratifying claims that
with:
A public message purporting to resolve an Agoran decision
is a self-ratifying attestation that"""
)
}
proposal(8271) {
title("Doctorate expectations")
ai("3.0")
author(G)
text(
"""
[Puts in a time requirement for Doctorates, also fixes bug]
Change the Power of Rule 1367 (Degrees) to 2.
[I've wondered for a while why we need this at 3!]
Amend Rule 1367 (Degrees) by replacing its last paragraph with:
A specified degree CAN be awarded by any player other than the
awardee, with 2 Agoran consent. It SHOULD only be awarded for the
publication of an original thesis of scholarly worth (including
responses to peer-review), published with explicit intent to qualify
for a degree. Any degree with D.N. as part of its abbreviation
SHOULD take into account the awardee's academic history and participation
in Agora over time. The Herald SHOULD coordinate the peer-review process
and the awarding of degrees."""
)
}
proposal(8272) {
title("The Fat Director")
ai("2.0")
author(Murphy)
coauthors(Gaelan, G)
text(
"""
Amend Rule 2193 (The Registrar) by removing this text:
The Registrar is also responsible for tracking any switches,
defined in a rule, that would otherwise lack an officer to track
them, unless the switch is defined as untracked.
Amend Rule 2423 (First Among Equals) by removing this text:
The Prime Minister is responsible for tracking any switches
defined by the rules, not defined as untracked, and not defined
as tracked by another officer.
Create a rule titled "The Fat Director" with Power 2 and this text:
The Fat Director is an imposed office.
A loose switch is a switch defined by the rules, not defined as
untracked, and not defined as tracked by an officer other than the
Fat Director. The Fat Director is responsible for tracking any
loose switches.
When a proposal creates a loose switch or causes a switch to
become loose, the Fat Director is set to the author of that
proposal. If the Fat Director is vacant and any loose switches
exist, then the Registrar CAN set the Fat Director to any player
by announcement. Any player CAN become the Fat Director by
announcement.
[Would have called it "Fat Controllor", but that would be too close
to "Comptrollor", and I didn't want to merge it with that either.]"""
)
}
proposal(8273) {
title("Clean up your own mess, without making a bigger one")
ai("1.0")
author(Gaelan)
coauthors(Janet)
text(
"""
Remove the following paragraph from Rule 2139 “The Registrar”: {
The Registrar is also responsible for tracking any switches,
defined in a rule, that would otherwise lack an officer to track
them, unless the switch is defined as untracked.
}
Create a power-1 rule titled “Switch Responsibility” with the following text: {
For each type of switch which would otherwise lack an officer to track it,
and is not defined as untracked, there exists an imposed office named
“Tracker of [switch name]” that is responsible for tracking that switch.
}
[1006/44 states:
When a proposal takes effect and creates a new office, if the
proposal does not specify otherwise, the author of that proposal
becomes the holder of the office.
I think this works, but we might need to clarify the meaning of
“creates a new office” to be sure.]"""
)
}
proposal(8274) {
title("Interested proposals")
ai("1.0")
author(Murphy)
coauthors(Oerjan)
text(
"""
Create a rule titled "Interested Proposals" with this text:
Interest is an untracked proposal switch with values
"disinterested" (default) and "interested". The author of a
proposal in the Proposal Pool CAN flip its Interest to Interested
by paying a fee of 5 coins, or by announcement if e most recently
registered less than 3 months ago.
Amend Rule 2496 (Rewards) by replacing this text:
* Being the author of an adopted proposal:
with this text:
* Being the author of an adopted interested proposal:"""
)
}
}
voting {
votes(Aris) {
FOR on 8266
FOR on 8267
FOR on 8268
FOR on 8269
FOR on 8270
FOR on 8271
AGAINST on 8272
FOR on 8273
AGAINST on 8274
}
votes(Janet) {
FOR on 8266
FOR on 8267
FOR on 8268
FOR on 8269
FOR on 8270
FOR on 8271
PRESENT on 8272
PRESENT on 8273
AGAINST on 8274
}
votes(Madrid) {
AGAINST on 8271
FOR on others
}
votes(Bernie) {
endorse(Janet) on all
}
votes(Falsifian) {
FOR on 8266 comment NO_VETO
FOR on 8267
FOR on 8268
PRESENT on 8269
PRESENT on 8270
FOR on 8271
AGAINST on 8272
FOR on 8273 comment NO_VETO
FOR on 8274 comment NO_VETO
}
votes(ATMunn) {
endorse(Falsifian) on all
}
votes(G) {
FOR on 8266
FOR on 8267
FOR on 8268
endorse(Aris) on 8269
FOR on 8270
FOR on 8271
FOR on 8272
AGAINST on 8273
AGAINST on 8274
}
votes(Rance) {
match(G) on all
}
}
}
| 1
| null |
1
| 1
|
4599bda37a691ab971e170c07f1efa214105498a
| 11,737
|
assessor
|
MIT License
|
app/src/main/java/com/example/cocktailsapp/shared/business/DrinkList.kt
|
MertYazi
| 693,573,760
| false
|
{"Kotlin": 217483}
|
package com.example.cocktailsapp.shared.business
data class DrinkList(
val drinks: ArrayList<DrinkItem>
)
| 0
|
Kotlin
|
0
| 1
|
d6b6dd5cb03bb8a6ecfada312b5cefe03e82ae4c
| 110
|
CocktailsApp
|
Apache License 2.0
|
app/src/main/java/com/example/cocktailsapp/shared/business/DrinkList.kt
|
MertYazi
| 693,573,760
| false
|
{"Kotlin": 217483}
|
package com.example.cocktailsapp.shared.business
data class DrinkList(
val drinks: ArrayList<DrinkItem>
)
| 0
|
Kotlin
|
0
| 1
|
d6b6dd5cb03bb8a6ecfada312b5cefe03e82ae4c
| 110
|
CocktailsApp
|
Apache License 2.0
|
sdk/src/main/java/io/matchmore/sdk/api/models/Subscriptions.kt
|
matchmore
| 113,169,361
| false
|
{"Kotlin": 286033, "Java": 12753, "Shell": 510}
|
/*
* MATCHMORE ALPS Core REST API
* ## ALPS by [MATCHMORE](https://dev.matchmore.io) The first version of the MATCHMORE API is an exciting step to allow developers use a context-aware pub/sub cloud service. A lot of mobile applications and their use cases may be modeled using this approach and can therefore profit from using MATCHMORE as their backend service. **Build something great with [ALPS by MATCHMORE](https://dev.matchmore.io)!** Once you've [registered your client](https://dev.matchmore.io/account/register/) it's easy start using our awesome cloud based context-aware pub/sub (admitted, a lot of buzzwords). ## RESTful API We do our best to have all our URLs be [RESTful](https://en.wikipedia.org/wiki/Representational_state_transfer). Every endpoint (URL) may support one of four different http verbs. GET requests fetch information about an object, POST requests create objects, PUT requests update objects, and finally DELETE requests will delete objects. ## Domain Model This is the current domain model extended by an ontology of devices and separation between the developer portal and the ALPS Core. +-----------+ +-------------+ | Developer +----+ Application | +-----------+ +------+------+ | \"Developer Portal\" ........................+.......................................... | \"ALPS Core\" +---+---+ | World | +---+---+ | +-------------+ | +-----+ Publication | | | +------+------+ | | | | | | | | | | | +---+---+ +----+---+-----------------+ | Match | | Device | +---+---+ +----+---+-----------------+ | | | | | | | | | +------+-------+ +---------------+--------------+ +-----+ Subscription | | | | +--------------+ +----+---+ +----+----+ +----+---+ | Pin | | iBeacon | | Mobile | +----+---+ +---------+ +----+---+ | | | +----------+ | +---------+ Location +---------+ +----------+ 1. A **developer** is a mobile application developer registered in the developer portal and allowed to use the **ALPS Developer Portal**. A developer might register one or more **applications** to use the **ALPS Core cloud service**. For developer/application pair a new **world** is created in the **ALPS Core** and assigned an **API key** to enable access to the ALPS Core cloud service **RESTful API**. During the registration, the developer needs to provide additional configuration information for each application, e.g. its default **push endpoint** URI for match delivery, etc. 2. A [**device**](#tag/device) might be either *virtual* like a **pin device** or *physical* like a **mobile device** or **iBeacon device**. A [**pin device**](#tag/device) is one that has geographical [**location**](#tag/location) associated with it but is not represented by any object in the physical world; usually it's location doesn't change frequently if at all. A [**mobile device**](#tag/device) is one that potentially moves together with its user and therefore has a geographical location associated with it. A mobile device is typically a location-aware smartphone, which knows its location thanks to GPS or to some other means like cell tower triangulation, etc. An [**iBeacon device**](#tag/device) represents an Apple conform [iBeacon](https://developer.apple.com/ibeacon/) announcing its presence via Bluetooth LE advertising packets which can be detected by a other mobile device. It doesn't necessary has any location associated with it but it serves to detect and announce its proximity to other **mobile devices**. 3. The hardware and software stack running on a given device is known as its **platform**. This include its hardware-related capabilities, its operating systems, as well as the set of libraries (APIs) offered to developers in order to program it. 4. A devices may issue publications and subscriptions at **any time**; it may also cancel publications and subscriptions issued previously. **Publications** and **subscriptions** do have a definable, finite duration, after which they are deleted from the ALPS Core cloud service and don't participate anymore in the matching process. 5. A [**publication**](#tag/publication) is similar to a Java Messaging Service (JMS) publication extended with the notion of a **geographical zone**. The zone is defined as **circle** with a center at the given location and a range around that location. 6. A [**subscription**](#tag/subscription) is similar to a JMS subscription extended with the notion of **geographical zone**. Again, the zone being defined as **circle** with a center at the given location and a range around that location. 7. **Publications** and **subscriptions** which are associated with a **mobile device**, e.g. user's mobile phone, potentially **follow the movements** of the user carrying the device and therefore change their associated location. 8. A [**match**](#tag/match) between a publication and a subscription occurs when both of the following two conditions hold: 1. There is a **context match** occurs when for instance the subscription zone overlaps with the publication zone or a **proximity event** with an iBeacon device within the defined range occurred. 2. There is a **content match**: the publication and the subscription match with respect to their JMS counterparts, i.e., they were issued on the same topic and have compatible properties and the evaluation of the selector against those properties returns true value. 9. A **push notification** is an asynchronous mechanism that allows an application to receive matches for a subscription on his/her device. Such a mechanism is clearly dependent on the device’s platform and capabilities. In order to use push notifications, an application must first register a device (and possibly an application on that device) with the ALPS core cloud service. 10. Whenever a **match** between a publication and a subscription occurs, the device which owns the subscription receives that match *asynchronously* via a push notification if there exists a registered **push endpoint**. A **push endpoint** is an URI which is able to consume the matches for a particular device and subscription. The **push endpoint** doesn't necessary point to a **mobile device** but is rather a very flexible mechanism to define where the matches should be delivered. 11. Matches can also be retrieved by issuing a API call for a particular device. <a id=\"orgae4fb18\"></a> ## Device Types +----+---+ | Device | +--------+ | id | | name | | group | +----+---+ | +---------------+----------------+ | | | +---+---+ +-------+------+ +----+-----+ | Pin | | iBeacon | | Mobile | +---+---+ +--------------+ +----------+ | | proximityUUID| | platform | | | major | | token | | | minor | +----+-----+ | +-------+------+ | | | | | | <--??? | | +----+-----+ | +----------+ Location +----------+ +----------+ <a id=\"org68cc0d8\"></a> ### Generic `Device` - id - name - group <a id=\"orgc430925\"></a> ### `PinDevice` - location <a id=\"orgecaed9f\"></a> ### `iBeaconDevice` - proximityUUID - major - minor <a id=\"org7b09b62\"></a> ### `MobileDevice` - platform - deviceToken - location
*
* OpenAPI spec version: 0.5.0
* Contact: <EMAIL>
*
* NOTE: This class is auto generated by the swagger code generator program.
* https://github.com/swagger-api/swagger-codegen.git
* Do not edit the class manually.
*/
package io.matchmore.sdk.api.models
import com.google.gson.annotations.SerializedName
import io.matchmore.sdk.utils.Expirable
import io.swagger.annotations.ApiModel
import io.swagger.annotations.ApiModelProperty
/**
* A subscription can be seen as a JMS subscription extended with the notion of geographical zone. The zone again being defined as circle with a center at the given location and a range around that location.
*/
@ApiModel(description = "A subscription can be seen as a JMS subscription extended with the notion of geographical zone. The zone again being defined as circle with a center at the given location and a range around that location. ")
data class Subscription @JvmOverloads constructor(
/**
* The topic of the subscription. This will act as a first match filter. For a subscription to be able to match a publication they must have the exact same topic.
*/
@SerializedName("topic")
@get:ApiModelProperty(required = true, value = "The topic of the subscription. This will act as a first match filter. For a subscription to be able to match a publication they must have the exact same topic. ")
var topic: String? = null,
/**
* The range of the subscription in meters. This is the range around the device holding the subscription in which matches with publications can be triggered.
*/
@SerializedName("range")
@get:ApiModelProperty(required = true, value = "The range of the subscription in meters. This is the range around the device holding the subscription in which matches with publications can be triggered. ")
var range: Double? = null,
/**
* The duration of the subscription in seconds. If set to '0' it will be instant at the time of subscription. Negative values are not allowed.
*/
@SerializedName("duration")
@get:ApiModelProperty(required = true, value = "The duration of the subscription in seconds. If set to '0' it will be instant at the time of subscription. Negative values are not allowed. ")
override var duration: Double? = null,
/**
* This is an expression to filter the publications. For instance 'job='developer'' will allow matching only with publications containing a 'job' key with a value of 'developer'.
*/
@SerializedName("selector")
@get:ApiModelProperty(required = true, value = "This is an expression to filter the publications. For instance 'job='developer'' will allow matching only with publications containing a 'job' key with a value of 'developer'. ")
var selector: String = "",
/**
* The id (UUID) of the device to attach a subscription to.
*/
@SerializedName("deviceId")
@get:ApiModelProperty(required = true, value = "The id (UUID) of the device to attach a subscription to.")
var deviceId: String? = null,
/**
* The id (UUID) of the world that contains device to attach a subscription to.
*/
@SerializedName("worldId")
@get:ApiModelProperty(required = true, value = "The id (UUID) of the world that contains device to attach a subscription to.")
var worldId: String? = null,
/**
* The timestamp of the subscription creation in seconds since Jan 01 1970 (UTC).
*/
@SerializedName("createdAt")
@get:ApiModelProperty(value = "The timestamp of the subscription creation in seconds since Jan 01 1970 (UTC). ")
override val createdAt: Long? = null,
/**
* When match will occurs, they will be notified on these provided URI(s) address(es) in the pushers array.
*/
@SerializedName("pushers")
@get:ApiModelProperty(value = "When match will occurs, they will be notified on these provided URI(s) address(es) in the pushers array. ")
var pushers: List<String>? = null,
/**
* The id (UUID) of the subscription.
*/
@SerializedName("id")
@get:ApiModelProperty(value = "The id (UUID) of the subscription.")
override val id: String? = null,
/**
* Duration in seconds. Defaults to subscription duration (only one match will be delivered for pub/sub pair), this parameter tells when to deliver consecutive matches with the same publication. For example, there is a match between publication and subscription and after matchTTL time publication and subscription are still in the range of each other next match will be sent to subscription. This parameter is useful when you have long-lasting publications/subscriptions, and you want to be notified when a match occurs after some time.
* @return matchTTL
*/
@SerializedName("matchTTL")
@get:ApiModelProperty(value = "Duration in seconds. Defaults to subscription duration (only one match will be delivered for pub/sub pair), this parameter tells when to deliver consecutive matches with the same publication. For example, there is a match between publication and subscription and after matchTTL time publication and subscription are still in the range of each other next match will be sent to subscription. This parameter is useful when you have long-lasting publications/subscriptions, and you want to be notified when a match occurs after some time. ")
var matchTTL: Double? = null,
/**
* Distance in meters. Defaults to two times the subscription range. This parameter says if the subscription will get a match again when the position of publication or subscription changes by matchDTL (publication and subscription still have to be in range after the change). This parameter is useful if you have large subscription/publication and subscription should get a match every time publication or subscription moves by matchDTL meters.
* @return matchDTL
*/
@SerializedName("matchDTL")
@get:ApiModelProperty(value = "Distance in meters. Defaults to two times the subscription range. This parameter says if the subscription will get a match again when the position of publication or subscription changes by matchDTL (publication and subscription still have to be in range after the change). This parameter is useful if you have large subscription/publication and subscription should get a match every time publication or subscription moves by matchDTL meters. ")
var matchDTL: Double? = null
) : HasId, Expirable
| 2
|
Kotlin
|
1
| 2
|
0dfd5ba1953cf04e425d410954b05464b809be39
| 15,659
|
android-sdk
|
MIT License
|
app/src/main/java/com/mayokunadeniyi/instantweather/data/model/Wind.kt
|
mayokunadeniyi
| 236,161,392
| false
| null |
package com.mayokunadeniyi.instantweather.data.model
import android.os.Parcelable
import kotlinx.android.parcel.Parcelize
/**
* Created by <NAME> on 16/03/2020.
*/
@Parcelize
data class Wind(
val speed: Double,
val deg: Int
) : Parcelable
| 9
| null |
163
| 763
|
52cc36b3bd17faf121fa72e1dd3e68eb6f58795d
| 252
|
Instant-Weather
|
MIT License
|
idea/testData/formatter/callChain/CallChainWrapping2.kt
|
Ndex471
| 236,524,761
| true
|
{"Kotlin": 43583583, "Java": 7648290, "JavaScript": 197545, "HTML": 75661, "Lex": 23805, "TypeScript": 21613, "Groovy": 11205, "CSS": 9144, "Shell": 7220, "Batchfile": 5362, "Swift": 2272, "Ruby": 1300, "Objective-C": 404, "Scala": 80}
|
fun test() {
INSTANCE.awswswswswswswswwawswswswswswswswwawswswswswswswswwawswswswswswswswwawswswswswswswswwawswswswswswswswwawswswswswswswswwawswswswswswswsww.awswswswswswswswwawswswswswswswswwawswswswswswswswwawswswswswswswswwawswswswswswswswwawswswswswswswswwawswswswswswswswwawswswswswswswsww.adad.adad
INSTANCE.adad.adad
INSTANCE.adad
INSTANCE.awswswswswswswswwawswswswswswswswwawswswswswswswswwawswswswswswswswwawswswswswswswswwawswswswswswswswwawswswswswswswswwawswswswswswswsww.awswswswswswswswwawswswswswswswswwawswswswswswswswwawswswswswswswswwawswswswswswswswwawswswswswswswswwawswswswswswswswwawswswswswswswsww
(INSTANCE.awswswswswswswswwawswswswswswswswwawswswswswswswswwawswswswswswswswwawswswswswswswswwawswswswswswswswwawswswswswswswswwawswswswswswswsww).awswswswswswswswwawswswswswswswswwawswswswswswswswwawswswswswswswswwawswswswswswswswwawswswswswswswswwawswswswswswswswwawswswswswswswsww
(INSTANCE).awswswswswswswswwawswswswswswswswwawswswswswswswswwawswswswswswswswwawswswswswswswswwawswswswswswswswwawswswswswswswswwawswswswswswswsww.awswswswswswswswwawswswswswswswswwawswswswswswswswwawswswswswswswswwawswswswswswswswwawswswswswswswswwawswswswswswswswwawswswswswswswsww
INSTANCE.awswswswswswswswwawswswswswswswswwawswswswswswswswwawswswswswswswswwawswswswswswswswwawswswswswswswswwawswswswswswswswwawswswswswswswsww
(INSTANCE).awswswswswswswswwawswswswswswswswwawswswswswswswswwawswswswswswswswwawswswswswswswswwawswswswswswswswwawswswswswswswswwawswswswswswswsww
val b = INSTANCE.awswswswswswswswwawswswswswswswswwawswswswswswswswwawswswswswswswswwawswswswswswswswwawswswswswswswswwawswswswswswswswwawswswswswswswsww.awswswswswswswswwawswswswswswswswwawswswswswswswswwawswswswswswswswwawswswswswswswswwawswswswswswswswwawswswswswswswswwawswswswswswswsww
val b = (INSTANCE).awswswswswswswswwawswswswswswswswwawswswswswswswswwawswswswswswswswwawswswswswswswswwawswswswswswswswwawswswswswswswswwawswswswswswswsww.awswswswswswswswwawswswswswswswswwawswswswswswswswwawswswswswswswswwawswswswswswswswwawswswswswswswswwawswswswswswswswwawswswswswswswsww
val b = (INSTANCE.awswswswswswswswwawswswswswswswswwawswswswswswswswwawswswswswswswswwawswswswswswswswwawswswswswswswswwawswswswswswswswwawswswswswswswsww).awswswswswswswswwawswswswswswswswwawswswswswswswswwawswswswswswswswwawswswswswswswswwawswswswswswswswwawswswswswswswswwawswswswswswswsww
val b = (((INSTANCE).awswswswswswswswwawswswswswswswswwawswswswswswswswwawswswswswswswswwawswswswswswswswwawswswswswswswswwawswswswswswswswwawswswswswswswsww)).awswswswswswswswwawswswswswswswswwawswswswswswswswwawswswswswswswswwawswswswswswswswwawswswswswswswswwawswswswswswswswwawswswswswswswsww
val b = INSTANCE.adad.adad
val b = INSTANCE.adad
val b = INSTANCE.awswswswswswswswwawswswswswswswswwawswswswswswswswwawswswswswswswswwawswswswswswswswwawswswswswswswswwawswswswswswswswwawswswswswswswsww
val b = INSTANCE!!!!.awswswswswswswswwawswswswswswswswwawswswswswswswswwawswswswswswswswwawswswswswswswswwawswswswswswswswwawswswswswswswswwawswswswswswswsww
val b = INSTANCE!!.awswswswswswswswwawswswswswswswswwawswswswswswswswwawswswswswswswswwawswswswswswswswwawswswswswswswswwawswswswswswswswwawswswswswswswsww
val b = if (INSTANCE.awswswswswswswswwawswswswswswswswwawswswswswswswswwawswswswswswswswwawswswswswswswswwawswswswswswswswwawswswswswswswswwawswswswswswswsww == INSTANCE.awswswswswswswswwawswswswswswswswwawswswswswswswswwawswswswswswswswwawswswswswswswswwawswswswswswswswwawswswswswswswswwawswswswswswswsww)
true
else
false
if (INSTANCE.awswswswswswswswwawswswswswswswswwawswswswswswswswwawswswswswswswswwawswswswswswswswwawswswswswswswswwawswswswswswswswwawswswswswswswsww == INSTANCE.awswswswswswswswwawswswswswswswswwawswswswswswswswwawswswswswswswswwawswswswswswswswwawswswswswswswswwawswswswswswswswwawswswswswswswsww)
true
else
false
if ((INSTANCE).awswswswswswswswwawswswswswswswswwawswswswswswswswwawswswswswswswswwawswswswswswswswwawswswswswswswswwawswswswswswswswwawswswswswswswsww == INSTANCE.awswswswswswswswwawswswswswswswswwawswswswswswswswwawswswswswswswswwawswswswswswswswwawswswswswswswswwawswswswswswswswwawswswswswswswsww)
true
else
false
val bawdawdwad = INSTANCE.awswswswswswswswwawswswswswswswswwawswswswswswswswwawswswswswswswswwawswswswswswswswwawswswswswswswswwawswswswswswswswwawswswswswswswsww.awswswswswswswswwawswswswswswswswwawswswswswswswswwawswswswswswswswwawswswswswswswswwawswswswswswswswwawswswswswswswswwawswswswswswswsww
val c = INSTANCE.awswswswswswswswwawswswswswswswswwawswswswswswswswwawswswswswswswswwawswswswswswswswwawswswswswswswswwawswswswswswswswwawswswswswswswsww().awswswswswswswswwawswswswswswswswwawswswswswswswswwawswswswswswswswwawswswswswswswswwawswswswswswswswwawswswswswswswswwawswswswswswswsww
val c = INSTANCE().awswswswswswswswwawswswswswswswswwawswswswswswswswwawswswswswswswswwawswswswswswswswwawswswswswswswswwawswswswswswswswwawswswswswswswsww.awswswswswswswswwawswswswswswswswwawswswswswswswswwawswswswswswswswwawswswswswswswswwawswswswswswswswwawswswswswswswswwawswswswswswswsww().adad.adawd
val c = INSTANCE().awswswswswswswswwawswswswswswswswwawswswswswswswswwawswswswswswswswwawswswswswswswswwawswswswswswswswwawswswswswswswswwawswswswswswswsww
}
val b = INSTANCE.awswswswswswswswwawswswswswswswswwawswswswswswswswwawswswswswswswswwawswswswswswswswwawswswswswswswswwawswswswswswswswwawswswswswswswsww.awswswswswswswswwawswswswswswswswwawswswswswswswswwawswswswswswswswwawswswswswswswswwawswswswswswswswwawswswswswswswswwawswswswswswswsww
val bawdawdwad = INSTANCE.awswswswswswswswwawswswswswswswswwawswswswswswswswwawswswswswswswswwawswswswswswswswwawswswswswswswswwawswswswswswswswwawswswswswswswsww.awswswswswswswswwawswswswswswswswwawswswswswswswswwawswswswswswswswwawswswswswswswswwawswswswswswswswwawswswswswswswswwawswswswswswswsww
val c = INSTANCE.awswswswswswswswwawswswswswswswswwawswswswswswswswwawswswswswswswswwawswswswswswswswwawswswswswswswswwawswswswswswswswwawswswswswswswsww().awswswswswswswswwawswswswswswswswwawswswswswswswswwawswswswswswswswwawswswswswswswswwawswswswswswswswwawswswswswswswswwawswswswswswswsww
val c = INSTANCE().awswswswswswswswwawswswswswswswswwawswswswswswswswwawswswswswswswswwawswswswswswswswwawswswswswswswswwawswswswswswswswwawswswswswswswsww.awswswswswswswswwawswswswswswswswwawswswswswswswswwawswswswswswswswwawswswswswswswswwawswswswswswswswwawswswswswswswswwawswswswswswswsww().adad.adawd
// SET_INT: METHOD_CALL_CHAIN_WRAP = 1
// SET_FALSE: WRAP_FIRST_METHOD_IN_CALL_CHAIN
| 0
| null |
0
| 1
|
f7626d6474bff5fceba8506c37480e8918bd11cf
| 6,652
|
kotlin
|
Apache License 2.0
|
plugin/src/main/kotlin/com/github/grishberg/profiler/ui/PluginThemeController.kt
|
Grigory-Rylov
| 256,819,360
| false
| null |
package com.github.grishberg.profiler.ui
import com.github.grishberg.profiler.chart.theme.DarkPalette
import com.github.grishberg.profiler.chart.theme.LightPalette
import com.github.grishberg.profiler.ui.theme.Palette
import com.github.grishberg.profiler.ui.theme.ThemeController
import com.intellij.util.ui.UIUtil
import javax.swing.JMenuBar
class PluginThemeController : ThemeController {
private val dark = UIUtil.isUnderDarcula()
override val palette: Palette = if (dark) DarkPalette() else LightPalette()
override fun applyTheme() = Unit
override fun addToMenu(menu: JMenuBar) = Unit
override fun addThemeSwitchedCallback(callback: Runnable) = Unit
override fun removeThemeSwitchedCallback(callback: Runnable) = Unit
}
| 38
| null |
3
| 97
|
e0ba609640cea72c301ff1537dc9cdd9b67bfe4c
| 755
|
android-methods-profiler
|
Apache License 2.0
|
Kotlin/src/GeneratorAlgorithm.kt
|
pedrolemoz
| 214,701,654
| false
|
{"Python": 6033, "Kotlin": 1313, "Swift": 1308, "Java": 1288, "C": 1205, "JavaScript": 998}
|
fun main() {
var generator = GeneratorAlgorithm()
for (i in 0..100){
println(generator.generateCPF())
}
}
class GeneratorAlgorithm() {
fun generateCPF() : String {
var buildCPF = ArrayList<Int>()
for (i in 0..8) {
buildCPF.add((0..9).random())
}
for (i in 0..1) {
buildCPF.add(digit(buildCPF))
}
return buildString(buildCPF)
}
private fun digit(buildCPF : ArrayList<Int>) : Int {
var sum: Int = 0
var index: Int = buildCPF.size + 1
for (i in buildCPF) {
sum += i * index
index--
}
return verifySum(sum)
}
private fun verifySum(sum: Int) : Int {
if ((sum % 11) < 2) return 0 else return 11 - (sum % 11)
}
private fun buildString(buildCPF : ArrayList<Int>) : String {
var getNumbers = ArrayList<String>()
for (i in buildCPF) {
getNumbers.add(i.toString())
}
var CPF: String = ""
getNumbers.add(3, ".")
getNumbers.add(7, ".")
getNumbers.add(11, "-")
for (i in getNumbers) {
CPF += i.toString()
}
return CPF
}
}
| 0
|
Python
|
0
| 6
|
0a1641dda6808a702763ec21c340fbf66709800e
| 1,313
|
CPFGen
|
Apache License 2.0
|
src/main/kotlin/DamerauLevensthein.kt
|
javacook
| 111,961,341
| false
| null |
package de.kotlincook.textmining
import java.lang.Math.max
import java.util.HashMap
/**
* The Damerau-Levenshtein Algorithm is an extension to the Levenshtein
* Algorithm which solves the edit distance problem between a source string and
* a target string with the following operations:
*
* Character Insertion
* Character Deletion
* Character Replacement
* Adjacent Character Swap
*
* Note that the adjacent character swap operation is an edit that may be
* applied when two adjacent characters in the source string match two adjacent
* characters in the target string, but in reverse order, rather than a
* general allowance for adjacent character swaps.
*
* This implementation allows the client to specify the costs of the various
* edit operations with the restriction that the cost of two swap operations
* must not be less than the cost of a delete operation followed by an insert
* operation. This restriction is required to preclude two swaps involving the
* same character being required for optimality which, in turn, enables a fast
* dynamic programming solution.
*
* The running time of the Damerau-Levenshtein algorithm is O(n*m) where n
* is the length of the source string and m is the length of the target
* string. This implementation consumes O(n*m) space.
*
* @author Kevin L. and Joerg Vollmer (JavaCook & KotlinCook)
* @param deleteCost the cost of deleting a character.
* @param insertCost the cost of inserting a character.
* @param replaceCost the cost of replacing a character.
* @param swapCost the cost of swapping two adjacent characters.
*/
class DamerauLevenshtein(private val deleteCost: Int,
private val insertCost: Int,
private val replaceCost: Int,
private val swapCost: Int) {
init {
check(deleteCost >= 0)
check(insertCost >= 0)
check(replaceCost >= 0)
check(swapCost >= 0)
check(2 * swapCost >= insertCost + deleteCost)
}
/**
* Compute the Damerau-Levenshtein distance between the specified source
* string and the specified target string.
*/
fun compute(source: String, target: String): Int {
if (source.isEmpty()) {
return target.length * insertCost
}
if (target.isEmpty()) {
return source.length * deleteCost
}
val table = Array(source.length) { IntArray(target.length) }
val sourceIndexByCharacter = HashMap<Char, Int>()
if (source[0] != target[0]) {
table[0][0] = Math.min(replaceCost, deleteCost + insertCost)
}
sourceIndexByCharacter.put(source[0], 0)
for (i in 1 until source.length) {
val deleteDistance = table[i - 1][0] + deleteCost
val insertDistance = (i + 1) * deleteCost + insertCost
val matchDistance = i * deleteCost + if (source[i] == target[0]) 0 else replaceCost
table[i][0] = intArrayOf(deleteDistance, insertDistance, matchDistance).min()!!
}
for (j in 1 until target.length) {
val deleteDistance = table[0][j - 1] + insertCost
val insertDistance = (j + 1) * insertCost + deleteCost
val matchDistance = j * insertCost + if (source[0] == target[j]) 0 else replaceCost
table[0][j] = intArrayOf(deleteDistance, insertDistance, matchDistance).min()!!
}
for (i in 1 until source.length) {
var maxSourceLetterMatchIndex = if (source[i] == target[0]) 0 else -1
for (j in 1 until target.length) {
val candidateSwapIndex:Int? = sourceIndexByCharacter[target[j]]
val jSwap = maxSourceLetterMatchIndex
val deleteDistance = table[i - 1][j] + deleteCost
val insertDistance = table[i][j - 1] + insertCost
var matchDistance = table[i - 1][j - 1]
if (source[i] != target[j]) {
matchDistance += replaceCost
} else {
maxSourceLetterMatchIndex = j
}
var swapDistance = Integer.MAX_VALUE;
if (candidateSwapIndex != null && jSwap != -1) {
swapDistance = 0
if (candidateSwapIndex > 0 || jSwap > 0) {
swapDistance = table[max(0, candidateSwapIndex - 1)][max(0, jSwap - 1)]
}
swapDistance += (i - candidateSwapIndex - 1) * deleteCost
swapDistance += (j - jSwap - 1) * insertCost + swapCost
}
table[i][j] = intArrayOf(deleteDistance, insertDistance, matchDistance, swapDistance).min()!!
}
sourceIndexByCharacter.put(source[i], i)
}
return table[source.length - 1][target.length - 1]
}
}
| 0
|
Kotlin
|
0
| 0
|
79fd08394b50016f8174f922abbea8c3cb506e49
| 4,871
|
dameraulevenshtein
|
Apache License 2.0
|
rendering/testSrc/com/android/tools/rendering/classloading/loaders/DelegatingClassLoaderTest.kt
|
JetBrains
| 60,701,247
| false
| null |
/*
* Copyright (C) 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
*
* 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.android.tools.rendering.classloading.loaders
import com.android.tools.rendering.classloading.loadClassBytes
import org.junit.Assert.assertNotNull
import org.junit.Assert.fail
import org.junit.Test
private class TestClass
internal class DelegatingClassLoaderTest {
@Test
fun `check loader successfully finds class`() {
val classLoader =
DelegatingClassLoader(
null,
StaticLoader(TestClass::class.java.canonicalName to loadClassBytes(TestClass::class.java)),
)
assertNotNull(classLoader.loadClass(TestClass::class.java.canonicalName))
// Check that a nonexistent class throws ClassNotFound
try {
classLoader.loadClass("class.do.not.exist")
fail("ClassNotFoundException expected")
} catch (_: ClassNotFoundException) {}
try {
classLoader.loadClass("")
fail("ClassNotFoundException expected")
} catch (_: ClassNotFoundException) {}
}
@Test
fun `check class renaming`() {
val classLoader =
DelegatingClassLoader(
null,
StaticLoader("private.Test" to loadClassBytes(TestClass::class.java)),
)
assertNotNull(classLoader.loadClass("private.Test"))
// Check that a nonexistent class throws ClassNotFound
try {
classLoader.loadClass("class.do.not.exist")
fail("ClassNotFoundException expected")
} catch (_: ClassNotFoundException) {}
try {
classLoader.loadClass("")
fail("ClassNotFoundException expected")
} catch (_: ClassNotFoundException) {}
}
}
| 5
| null |
227
| 948
|
10110983c7e784122d94c7467e9d243aba943bf4
| 2,153
|
android
|
Apache License 2.0
|
lib/src/integrationTest/kotlin/com/lemonappdev/konsist/core/declaration/kokdoc/forkokdoctags/KoKDocDeclarationForTagTest.kt
|
LemonAppDev
| 621,181,534
| false
| null |
package com.lemonappdev.konsist.core.declaration.kokdocdeclaration.kokdoctagsprovider
import com.lemonappdev.konsist.TestSnippetProvider.getSnippetKoScope
import com.lemonappdev.konsist.api.provider.KoKDocProvider
import com.lemonappdev.konsist.api.provider.KoNameProvider
import org.amshove.kluent.shouldBeEqualTo
import org.amshove.kluent.shouldHaveSize
import org.junit.jupiter.api.Test
import org.junit.jupiter.params.ParameterizedTest
import org.junit.jupiter.params.provider.Arguments.arguments
import org.junit.jupiter.params.provider.MethodSource
class KoKDocDeclarationForTagTest {
@ParameterizedTest
@MethodSource("provideValues")
fun `tags-size`(
declarationName: String,
size: Int,
) {
// given
val sut = (
getSnippetFile("tags")
.declarations(includeNested = true)
.filterIsInstance<KoNameProvider>()
.first { it.name == declarationName } as KoKDocProvider
)
.kDoc
// then
sut
?.tags
?.shouldHaveSize(size)
}
@Test
fun `class-with-unknown-tag`() {
// given
val sut = getSnippetFile("class-with-unknown-tag")
.classes()
.first()
.kDoc
// then
sut?.tags shouldBeEqualTo listOf()
}
@Test
fun `tags with multiline param tag`() {
// given
val sut = getSnippetFile("tags")
.classes()
.first()
.kDoc
// then
sut
?.paramTags
?.get(0)
?.description
.shouldBeEqualTo("First line description\nSecond line description")
}
@Test
fun `tags with '@' into description`() {
// given
val sut = getSnippetFile("tags")
.classes()
.first()
.kDoc
// then
sut
?.propertyTags
?.get(0)
?.description
.shouldBeEqualTo("The first @property of the class.")
}
private fun getSnippetFile(fileName: String) =
getSnippetKoScope("core/declaration/kokdocdeclaration/kokdoctagsprovider/snippet/fortag/", fileName)
companion object {
@Suppress("unused")
@JvmStatic
fun provideValues() = listOf(
arguments("SampleClass", 10),
arguments("sampleMethod", 2),
arguments("sampleProperty", 2),
arguments("SampleClassWithoutTags", 0),
)
}
}
| 7
|
Kotlin
|
1
| 71
|
c3cf91622bab1938fecbc96c119cbbb70e372451
| 2,533
|
konsist
|
Apache License 2.0
|
libs/canvas-api-2/src/main/java/com/instructure/canvasapi2/managers/NotificationPreferencesManager.kt
|
instructure
| 179,290,947
| false
| null |
/*
* Copyright (C) 2017 - present Instructure, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.instructure.canvasapi2.managers
import com.instructure.canvasapi2.StatusCallback
import com.instructure.canvasapi2.apis.NotificationPreferencesAPI
import com.instructure.canvasapi2.builders.RestBuilder
import com.instructure.canvasapi2.builders.RestParams
import com.instructure.canvasapi2.models.NotificationPreferenceResponse
import com.instructure.canvasapi2.utils.weave.apiAsync
object NotificationPreferencesManager {
const val IMMEDIATELY = "immediately"
const val NEVER = "never"
fun getNotificationPreferences(
userId: Long,
commChannelId: Long,
forceNetwork: Boolean,
callback: StatusCallback<NotificationPreferenceResponse>
) {
val adapter = RestBuilder(callback)
val params = RestParams(isForceReadFromNetwork = forceNetwork)
NotificationPreferencesAPI.getNotificationPreferences(
userId,
commChannelId,
adapter,
params,
callback
)
}
fun getNotificationPreferencesAsync(
userId: Long,
commChannelId: Long,
forceNetwork: Boolean
) = apiAsync<NotificationPreferenceResponse> { getNotificationPreferences(userId, commChannelId, forceNetwork, it) }
fun updatePreferenceCategory(
categoryName: String,
channelId: Long,
frequency: String,
callback: StatusCallback<NotificationPreferenceResponse>
) {
val adapter = RestBuilder(callback)
val params = RestParams()
NotificationPreferencesAPI.updatePreferenceCategory(
categoryName,
channelId,
frequency,
adapter,
params,
callback
)
}
fun updatePreferenceCategoryAsync(
categoryName: String,
channelId: Long,
frequency: String
) = apiAsync<NotificationPreferenceResponse> { updatePreferenceCategory(categoryName, channelId, frequency, it) }
}
| 4
| null |
71
| 81
|
ee27bb79afb1ae70e6221cd59882f6165f64cf55
| 2,641
|
canvas-android
|
Apache License 2.0
|
feature-crowdloan-api/src/main/java/io/novafoundation/nova/feature_crowdloan_api/data/network/blockhain/binding/TrieIndex.kt
|
novasamatech
| 415,834,480
| false
|
{"Kotlin": 7662708, "Java": 14723, "JavaScript": 425}
|
package io.novafoundation.nova.feature_crowdloan_api.data.network.blockhain.binding
import io.novafoundation.nova.common.data.network.runtime.binding.HelperBinding
import io.novafoundation.nova.common.data.network.runtime.binding.bindNumber
import java.math.BigInteger
typealias TrieIndex = BigInteger
@HelperBinding
fun bindTrieIndex(dynamicInstance: Any?) = bindNumber(dynamicInstance)
| 13
|
Kotlin
|
5
| 9
|
66a5c0949aee03a5ebe870a1b0d5fa3ae929516f
| 391
|
nova-wallet-android
|
Apache License 2.0
|
app/src/main/java/org/simple/clinic/recentpatient/AllRecentPatientsEffect.kt
|
simpledotorg
| 132,515,649
| false
| null |
package org.simple.clinic.recentpatient
import androidx.paging.PagingData
import org.simple.clinic.patient.RecentPatient
import java.util.UUID
sealed class AllRecentPatientsEffect
object LoadAllRecentPatients : AllRecentPatientsEffect()
sealed class AllRecentPatientsViewEffect : AllRecentPatientsEffect()
data class OpenPatientSummary(val patientUuid: UUID) : AllRecentPatientsViewEffect()
data class ShowRecentPatients(val recentPatients: PagingData<RecentPatient>) : AllRecentPatientsViewEffect()
| 7
| null |
74
| 236
|
ff699800fbe1bea2ed0492df484777e583c53714
| 506
|
simple-android
|
MIT License
|
Tutorial1-1Basics/src/main/java/com/smarttoolfactory/tutorial1_1basics/tutorial_list/TutorialList.kt
|
SmartToolFactory
| 326,400,374
| false
| null |
package com.smarttoolfactory.tutorial1_1basics.tutorial_list
import Tutorial2_10Screen3
import Tutorial2_5Screen5
import Tutorial2_5Screen6
import androidx.compose.animation.ExperimentalAnimationApi
import androidx.compose.foundation.ExperimentalFoundationApi
import androidx.compose.material.ExperimentalMaterialApi
import androidx.compose.runtime.Composable
import androidx.compose.ui.ExperimentalComposeUiApi
import androidx.compose.ui.res.stringResource
import com.smarttoolfactory.tutorial1_1basics.R
import com.smarttoolfactory.tutorial1_1basics.chapter1_basics.Tutorial1_1Screen
import com.smarttoolfactory.tutorial1_1basics.chapter1_basics.Tutorial1_2Screen
import com.smarttoolfactory.tutorial1_1basics.chapter2_material_widgets.Tutorial2_10Screen1
import com.smarttoolfactory.tutorial1_1basics.chapter2_material_widgets.Tutorial2_10Screen2
import com.smarttoolfactory.tutorial1_1basics.chapter2_material_widgets.Tutorial2_10Screen4
import com.smarttoolfactory.tutorial1_1basics.chapter2_material_widgets.Tutorial2_10Screen5
import com.smarttoolfactory.tutorial1_1basics.chapter2_material_widgets.Tutorial2_11Screen
import com.smarttoolfactory.tutorial1_1basics.chapter2_material_widgets.Tutorial2_12Screen
import com.smarttoolfactory.tutorial1_1basics.chapter2_material_widgets.Tutorial2_13Screen
import com.smarttoolfactory.tutorial1_1basics.chapter2_material_widgets.Tutorial2_14Screen
import com.smarttoolfactory.tutorial1_1basics.chapter2_material_widgets.Tutorial2_1Screen
import com.smarttoolfactory.tutorial1_1basics.chapter2_material_widgets.Tutorial2_2Screen
import com.smarttoolfactory.tutorial1_1basics.chapter2_material_widgets.Tutorial2_3Screen
import com.smarttoolfactory.tutorial1_1basics.chapter2_material_widgets.Tutorial2_4Screen
import com.smarttoolfactory.tutorial1_1basics.chapter2_material_widgets.Tutorial2_5Screen1
import com.smarttoolfactory.tutorial1_1basics.chapter2_material_widgets.Tutorial2_5Screen2
import com.smarttoolfactory.tutorial1_1basics.chapter2_material_widgets.Tutorial2_5Screen3
import com.smarttoolfactory.tutorial1_1basics.chapter2_material_widgets.Tutorial2_5Screen4
import com.smarttoolfactory.tutorial1_1basics.chapter2_material_widgets.Tutorial2_5Screen7
import com.smarttoolfactory.tutorial1_1basics.chapter2_material_widgets.Tutorial2_5Screen8
import com.smarttoolfactory.tutorial1_1basics.chapter2_material_widgets.Tutorial2_6Screen
import com.smarttoolfactory.tutorial1_1basics.chapter2_material_widgets.Tutorial2_7Screen
import com.smarttoolfactory.tutorial1_1basics.chapter2_material_widgets.Tutorial2_8Screen
import com.smarttoolfactory.tutorial1_1basics.chapter2_material_widgets.Tutorial2_9Screen1
import com.smarttoolfactory.tutorial1_1basics.chapter2_material_widgets.Tutorial2_9Screen2
import com.smarttoolfactory.tutorial1_1basics.chapter2_material_widgets.Tutorial2_9Screen3
import com.smarttoolfactory.tutorial1_1basics.chapter2_material_widgets.Tutorial2_9Screen4
import com.smarttoolfactory.tutorial1_1basics.chapter3_layout.Tutorial3_10Screen
import com.smarttoolfactory.tutorial1_1basics.chapter3_layout.Tutorial3_1Screen1
import com.smarttoolfactory.tutorial1_1basics.chapter3_layout.Tutorial3_1Screen2
import com.smarttoolfactory.tutorial1_1basics.chapter3_layout.Tutorial3_1Screen3
import com.smarttoolfactory.tutorial1_1basics.chapter3_layout.Tutorial3_1Screen4
import com.smarttoolfactory.tutorial1_1basics.chapter3_layout.Tutorial3_1Screen5
import com.smarttoolfactory.tutorial1_1basics.chapter3_layout.Tutorial3_1Screen6
import com.smarttoolfactory.tutorial1_1basics.chapter3_layout.Tutorial3_1Screen7
import com.smarttoolfactory.tutorial1_1basics.chapter3_layout.Tutorial3_1Screen8
import com.smarttoolfactory.tutorial1_1basics.chapter3_layout.Tutorial3_2Screen0
import com.smarttoolfactory.tutorial1_1basics.chapter3_layout.Tutorial3_2Screen1
import com.smarttoolfactory.tutorial1_1basics.chapter3_layout.Tutorial3_2Screen10
import com.smarttoolfactory.tutorial1_1basics.chapter3_layout.Tutorial3_2Screen2
import com.smarttoolfactory.tutorial1_1basics.chapter3_layout.Tutorial3_2Screen3
import com.smarttoolfactory.tutorial1_1basics.chapter3_layout.Tutorial3_2Screen4
import com.smarttoolfactory.tutorial1_1basics.chapter3_layout.Tutorial3_2Screen5
import com.smarttoolfactory.tutorial1_1basics.chapter3_layout.Tutorial3_2Screen6
import com.smarttoolfactory.tutorial1_1basics.chapter3_layout.Tutorial3_2Screen7
import com.smarttoolfactory.tutorial1_1basics.chapter3_layout.Tutorial3_2Screen8
import com.smarttoolfactory.tutorial1_1basics.chapter3_layout.Tutorial3_2Screen9
import com.smarttoolfactory.tutorial1_1basics.chapter3_layout.Tutorial3_3Screen1
import com.smarttoolfactory.tutorial1_1basics.chapter3_layout.Tutorial3_3Screen3
import com.smarttoolfactory.tutorial1_1basics.chapter3_layout.Tutorial3_3Screen4
import com.smarttoolfactory.tutorial1_1basics.chapter3_layout.Tutorial3_3Screen5
import com.smarttoolfactory.tutorial1_1basics.chapter3_layout.Tutorial3_4Screen
import com.smarttoolfactory.tutorial1_1basics.chapter3_layout.Tutorial3_5Screen
import com.smarttoolfactory.tutorial1_1basics.chapter3_layout.Tutorial3_6Screen1
import com.smarttoolfactory.tutorial1_1basics.chapter3_layout.Tutorial3_6Screen2
import com.smarttoolfactory.tutorial1_1basics.chapter3_layout.Tutorial3_7Screen1
import com.smarttoolfactory.tutorial1_1basics.chapter3_layout.Tutorial3_7Screen2
import com.smarttoolfactory.tutorial1_1basics.chapter3_layout.Tutorial3_9Screen
import com.smarttoolfactory.tutorial1_1basics.chapter4_state.Tutorial4_10Screen1
import com.smarttoolfactory.tutorial1_1basics.chapter4_state.Tutorial4_10Screen2
import com.smarttoolfactory.tutorial1_1basics.chapter4_state.Tutorial4_10Screen3
import com.smarttoolfactory.tutorial1_1basics.chapter4_state.Tutorial4_11Screen1
import com.smarttoolfactory.tutorial1_1basics.chapter4_state.Tutorial4_11Screen2
import com.smarttoolfactory.tutorial1_1basics.chapter4_state.Tutorial4_11Screen3
import com.smarttoolfactory.tutorial1_1basics.chapter4_state.Tutorial4_11Screen6
import com.smarttoolfactory.tutorial1_1basics.chapter4_state.Tutorial4_1Screen1
import com.smarttoolfactory.tutorial1_1basics.chapter4_state.Tutorial4_1Screen2
import com.smarttoolfactory.tutorial1_1basics.chapter4_state.Tutorial4_2_1Screen
import com.smarttoolfactory.tutorial1_1basics.chapter4_state.Tutorial4_2_2Screen
import com.smarttoolfactory.tutorial1_1basics.chapter4_state.Tutorial4_2_3Screen
import com.smarttoolfactory.tutorial1_1basics.chapter4_state.Tutorial4_2_4Screen
import com.smarttoolfactory.tutorial1_1basics.chapter4_state.Tutorial4_2_5Screen
import com.smarttoolfactory.tutorial1_1basics.chapter4_state.Tutorial4_2_6Screen
import com.smarttoolfactory.tutorial1_1basics.chapter4_state.Tutorial4_2_7Screen
import com.smarttoolfactory.tutorial1_1basics.chapter4_state.Tutorial4_2_8Screen
import com.smarttoolfactory.tutorial1_1basics.chapter4_state.Tutorial4_3Screen
import com.smarttoolfactory.tutorial1_1basics.chapter4_state.Tutorial4_4Screen
import com.smarttoolfactory.tutorial1_1basics.chapter4_state.Tutorial4_5_1Screen
import com.smarttoolfactory.tutorial1_1basics.chapter4_state.Tutorial4_5_2Screen
import com.smarttoolfactory.tutorial1_1basics.chapter4_state.Tutorial4_6Screen
import com.smarttoolfactory.tutorial1_1basics.chapter4_state.Tutorial4_7_1Screen
import com.smarttoolfactory.tutorial1_1basics.chapter4_state.Tutorial4_7_2Screen
import com.smarttoolfactory.tutorial1_1basics.chapter4_state.Tutorial4_7_3Screen
import com.smarttoolfactory.tutorial1_1basics.chapter5_gesture.Tutorial5_10_1Screen
import com.smarttoolfactory.tutorial1_1basics.chapter5_gesture.Tutorial5_11Screen
import com.smarttoolfactory.tutorial1_1basics.chapter5_gesture.Tutorial5_1Screen1
import com.smarttoolfactory.tutorial1_1basics.chapter5_gesture.Tutorial5_1Screen2
import com.smarttoolfactory.tutorial1_1basics.chapter5_gesture.Tutorial5_1Screen3
import com.smarttoolfactory.tutorial1_1basics.chapter5_gesture.Tutorial5_2Screen
import com.smarttoolfactory.tutorial1_1basics.chapter5_gesture.Tutorial5_3Screen
import com.smarttoolfactory.tutorial1_1basics.chapter5_gesture.Tutorial5_4Screen1
import com.smarttoolfactory.tutorial1_1basics.chapter5_gesture.Tutorial5_4Screen2
import com.smarttoolfactory.tutorial1_1basics.chapter5_gesture.Tutorial5_4Screen3
import com.smarttoolfactory.tutorial1_1basics.chapter5_gesture.Tutorial5_4Screen4
import com.smarttoolfactory.tutorial1_1basics.chapter5_gesture.Tutorial5_5Screen1
import com.smarttoolfactory.tutorial1_1basics.chapter5_gesture.Tutorial5_6Screen1
import com.smarttoolfactory.tutorial1_1basics.chapter5_gesture.Tutorial5_6Screen2
import com.smarttoolfactory.tutorial1_1basics.chapter5_gesture.Tutorial5_6Screen3
import com.smarttoolfactory.tutorial1_1basics.chapter5_gesture.Tutorial5_6Screen4
import com.smarttoolfactory.tutorial1_1basics.chapter5_gesture.Tutorial5_6Screen5
import com.smarttoolfactory.tutorial1_1basics.chapter5_gesture.Tutorial5_6Screen6
import com.smarttoolfactory.tutorial1_1basics.chapter5_gesture.Tutorial5_6Screen7
import com.smarttoolfactory.tutorial1_1basics.chapter5_gesture.Tutorial5_6Screen8
import com.smarttoolfactory.tutorial1_1basics.chapter5_gesture.Tutorial5_6Screen9
import com.smarttoolfactory.tutorial1_1basics.chapter5_gesture.Tutorial5_7Screen1
import com.smarttoolfactory.tutorial1_1basics.chapter5_gesture.Tutorial5_8Screen1
import com.smarttoolfactory.tutorial1_1basics.chapter5_gesture.Tutorial5_8Screen2
import com.smarttoolfactory.tutorial1_1basics.chapter5_gesture.Tutorial5_9Screen1
import com.smarttoolfactory.tutorial1_1basics.chapter5_gesture.Tutorial5_9Screen2
import com.smarttoolfactory.tutorial1_1basics.chapter5_gesture.Tutorial5_9Screen3
import com.smarttoolfactory.tutorial1_1basics.chapter5_gesture.Tutorial5_9Screen5
import com.smarttoolfactory.tutorial1_1basics.chapter5_gesture.Tutorial5_9Screen6
import com.smarttoolfactory.tutorial1_1basics.chapter5_gesture.Tutorial5_9Screen7
import com.smarttoolfactory.tutorial1_1basics.chapter6_graphics.Tutorial6_10Screen
import com.smarttoolfactory.tutorial1_1basics.chapter6_graphics.Tutorial6_11Screen
import com.smarttoolfactory.tutorial1_1basics.chapter6_graphics.Tutorial6_12Screen
import com.smarttoolfactory.tutorial1_1basics.chapter6_graphics.Tutorial6_13Screen
import com.smarttoolfactory.tutorial1_1basics.chapter6_graphics.Tutorial6_14Screen
import com.smarttoolfactory.tutorial1_1basics.chapter6_graphics.Tutorial6_15Screen
import com.smarttoolfactory.tutorial1_1basics.chapter6_graphics.Tutorial6_16Screen
import com.smarttoolfactory.tutorial1_1basics.chapter6_graphics.Tutorial6_17Screen
import com.smarttoolfactory.tutorial1_1basics.chapter6_graphics.Tutorial6_18Screen
import com.smarttoolfactory.tutorial1_1basics.chapter6_graphics.Tutorial6_19Screen
import com.smarttoolfactory.tutorial1_1basics.chapter6_graphics.Tutorial6_1Screen1
import com.smarttoolfactory.tutorial1_1basics.chapter6_graphics.Tutorial6_1Screen2
import com.smarttoolfactory.tutorial1_1basics.chapter6_graphics.Tutorial6_1Screen3
import com.smarttoolfactory.tutorial1_1basics.chapter6_graphics.Tutorial6_1Screen4
import com.smarttoolfactory.tutorial1_1basics.chapter6_graphics.Tutorial6_1Screen5
import com.smarttoolfactory.tutorial1_1basics.chapter6_graphics.Tutorial6_1Screen6
import com.smarttoolfactory.tutorial1_1basics.chapter6_graphics.Tutorial6_1Screen7
import com.smarttoolfactory.tutorial1_1basics.chapter6_graphics.Tutorial6_20Screen
import com.smarttoolfactory.tutorial1_1basics.chapter6_graphics.Tutorial6_21Screen
import com.smarttoolfactory.tutorial1_1basics.chapter6_graphics.Tutorial6_22Screen
import com.smarttoolfactory.tutorial1_1basics.chapter6_graphics.Tutorial6_23Screen
import com.smarttoolfactory.tutorial1_1basics.chapter6_graphics.Tutorial6_24Screen
import com.smarttoolfactory.tutorial1_1basics.chapter6_graphics.Tutorial6_25Screen
import com.smarttoolfactory.tutorial1_1basics.chapter6_graphics.Tutorial6_29ToolTipPieChart
import com.smarttoolfactory.tutorial1_1basics.chapter6_graphics.Tutorial6_2Screen1
import com.smarttoolfactory.tutorial1_1basics.chapter6_graphics.Tutorial6_2Screen2
import com.smarttoolfactory.tutorial1_1basics.chapter6_graphics.Tutorial6_2Screen3
import com.smarttoolfactory.tutorial1_1basics.chapter6_graphics.Tutorial6_4Screen0
import com.smarttoolfactory.tutorial1_1basics.chapter6_graphics.Tutorial6_4Screen1
import com.smarttoolfactory.tutorial1_1basics.chapter6_graphics.Tutorial6_4Screen2
import com.smarttoolfactory.tutorial1_1basics.chapter6_graphics.Tutorial6_4Screen3
import com.smarttoolfactory.tutorial1_1basics.chapter6_graphics.Tutorial6_5Screen
import com.smarttoolfactory.tutorial1_1basics.chapter6_graphics.Tutorial6_6Screen
import com.smarttoolfactory.tutorial1_1basics.chapter6_graphics.Tutorial6_7Screen
import com.smarttoolfactory.tutorial1_1basics.chapter6_graphics.Tutorial6_8Screen1
import com.smarttoolfactory.tutorial1_1basics.chapter6_graphics.Tutorial6_9Screen1
import com.smarttoolfactory.tutorial1_1basics.model.TutorialSectionModel
import com.smarttoolfactory.tutorial1_1basics.ui.GestureListColor
import com.smarttoolfactory.tutorial1_1basics.ui.GraphicsListColor
import com.smarttoolfactory.tutorial1_1basics.ui.LayoutListColor
import com.smarttoolfactory.tutorial1_1basics.ui.StateListColor
/**
* Create list of tutorials with titles, action that navigates to composable function
* inside lambda.
*
* * Tags are for search purposes if there is a Search Component exists.
*/
@ExperimentalAnimationApi
@OptIn(ExperimentalMaterialApi::class)
@ExperimentalFoundationApi
@ExperimentalComposeUiApi
@Composable
fun createComponentTutorialList(onBack: () -> Unit): List<TutorialSectionModel> {
val tutorial1_1 = TutorialSectionModel(
title = stringResource(R.string.title1_1),
action = {
Tutorial1_1Screen()
},
description = "Create Rows, Columns and Box, how to add modifiers to " +
"composables. Set padding, margin, alignment other properties of composables.",
tags = listOf(
TAG_COMPOSE,
TAG_COMPOSE_COLUMN,
TAG_COMPOSE_ROW,
TAG_COMPOSE_BOX,
TAG_COMPOSE_MODIFIER
)
)
val tutorial1_2 = TutorialSectionModel(
title = stringResource(R.string.title1_2),
description = "Create and modify Surface to draw background for Composables," +
" add click action to any composable. Set weight or offset modifiers.",
action = {
Tutorial1_2Screen()
},
tags = listOf(
TAG_COMPOSE,
TAG_COMPOSE_MODIFIER,
TAG_COMPOSE_SURFACE,
TAG_COMPOSE_SHAPE,
TAG_COMPOSE_CLICKABLE
)
)
val tutorial2_1 = TutorialSectionModel(
title = stringResource(R.string.title2_1),
description = "Create Text component with different properties such as " +
"color, background, font weight, family, style, spacing and others.",
action = {
Tutorial2_1Screen()
},
tags = listOf(
TAG_COMPOSE,
TAG_TEXT,
TAG_FONT_STYLE,
TAG_ANNOTATED_STRING,
TAG_HYPERLINK
)
)
val tutorial2_2 = TutorialSectionModel(
title = stringResource(R.string.title2_2),
description = "Create Button with text and/or with image, Floating Action Button " +
", or Chips. Modify properties of buttons such as color, text, or state.",
action = {
Tutorial2_2Screen()
},
tags = listOf(
TAG_COMPOSE,
TAG_BUTTON,
TAG_ICON_BUTTON,
TAG_FAB_BUTTON,
TAG_CHIP
)
)
val tutorial2_3 = TutorialSectionModel(
title = stringResource(R.string.title2_3),
description = "Create TextField component with regular style or outlined. Set error," +
" colors, state, icons, VisualTransformations for phone or " +
"credit card, and IME actions.",
action = {
Tutorial2_3Screen()
},
tags = listOf(
TAG_COMPOSE,
TAG_TEXT_FIELD,
TAG_OUTLINED_TEXT_FIELD,
TAG_IME,
TAG_VISUAL_TRANSFORMATION,
TAG_REGEX
)
)
val tutorial2_4 = TutorialSectionModel(
title = stringResource(R.string.title2_4),
description = "Create Image to display images, set image and crop styles. " +
"Change shape of Image or apply ColorFilter and PorterDuff modes.",
action = {
Tutorial2_4Screen()
},
tags = listOf(
TAG_COMPOSE,
TAG_IMAGE,
TAG_DRAWABLE,
TAG_VECTOR_DRAWABLE,
TAG_BITMAP
)
)
val tutorial2_5_1 = TutorialSectionModel(
title = stringResource(R.string.title2_5_1),
description = "LazyColumn is counterpart of vertical RecyclerView in Compose",
action = {
Tutorial2_5Screen1()
},
tags = listOf(
TAG_COMPOSE,
TAG_LAZY_COLUMN,
TAG_LAZY_COLUMN_VERTICAL_ARRANGEMENT,
TAG_LAZY_COLUMN_CONTENT_PADDING
)
)
val tutorial2_5_2 = TutorialSectionModel(
title = stringResource(R.string.title2_5_2),
description = "LazyColumn scroll state and modify dynamic list",
action = {
Tutorial2_5Screen2()
},
tags = listOf(
TAG_COMPOSE,
TAG_LAZY_COLUMN,
TAG_LAZY_COLUMN_VERTICAL_ARRANGEMENT,
TAG_LAZY_COLUMN_CONTENT_PADDING,
TAG_LAZY_COLUMN_SCROLL,
TAG_LAZY_COLUMN_DYNAMIC_SIZE
)
)
val tutorial2_5_3 = TutorialSectionModel(
title = stringResource(R.string.title2_5_3),
description = "LazyColumn is counterpart of horizontal RecyclerView in Compose",
action = {
Tutorial2_5Screen3()
},
tags = listOf(
TAG_COMPOSE,
TAG_LAZY_ROW,
TAG_LAZY_COLUMN_VERTICAL_ARRANGEMENT,
TAG_LAZY_COLUMN_CONTENT_PADDING
)
)
val tutorial2_5_4 = TutorialSectionModel(
title = stringResource(R.string.title2_5_4),
description = "LazyColumn with StickyHeaders",
action = {
Tutorial2_5Screen4()
},
tags = listOf(
TAG_COMPOSE,
TAG_LAZY_COLUMN,
TAG_LAZY_COLUMN_STICKY_HEADER,
TAG_LAZY_COLUMN_VERTICAL_ARRANGEMENT,
TAG_LAZY_COLUMN_CONTENT_PADDING
)
)
val tutorial2_5_5 = TutorialSectionModel(
title = stringResource(R.string.title2_5_5),
description = "Grid style item display",
action = {
Tutorial2_5Screen5()
},
tags = listOf(
TAG_COMPOSE,
TAG_LAZY_VERTICAL_GRID,
TAG_GRID_CELL,
TAG_LAZY_COLUMN_VERTICAL_ARRANGEMENT,
TAG_LAZY_COLUMN_CONTENT_PADDING
)
)
val tutorial2_5_6 = TutorialSectionModel(
title = stringResource(R.string.title2_5_6),
description = "LazyGridLayout with dynamic height",
action = {
Tutorial2_5Screen6()
},
tags = listOf(
TAG_COMPOSE,
TAG_LAZY_VERTICAL_GRID,
TAG_GRID_CELL,
TAG_LAZY_COLUMN_VERTICAL_ARRANGEMENT,
TAG_LAZY_COLUMN_CONTENT_PADDING
)
)
val tutorial2_5_7 = TutorialSectionModel(
title = stringResource(R.string.title2_5_7),
description = "Create one-line, two-line, three-line or combine other " +
"components to build list items using built-in ListItem component",
action = {
Tutorial2_5Screen7()
},
tags = listOf(
TAG_COMPOSE,
TAG_LAZY_COLUMN,
TAG_LIST_ITEM
)
)
val tutorial2_5_8 = TutorialSectionModel(
title = stringResource(R.string.title2_5_8),
description = "Get meta data about LazyRow/Column by using LazyLayoutState's " +
"LazyListLayoutInfo",
action = {
Tutorial2_5Screen8()
},
tags = listOf(
TAG_COMPOSE,
TAG_LAZY_ROW,
TAG_LAZY_COLUMN,
TAG_LAZY_LIST_LAYOUT_INFO,
TAG_LAZY_LIST_ITEM_INFO
)
)
val tutorial2_6 = TutorialSectionModel(
title = stringResource(R.string.title2_6),
description = "The top app bar displays information and actions " +
"relating to the current screen.",
action = {
Tutorial2_6Screen(onBack)
},
tags = listOf(
TAG_COMPOSE,
TAG_TOP_APP_BAR,
TAG_TOP_APP_BAR_MENU,
TAG_TAB_ROW,
TAG_TAB,
TAG_TAB_INDICATOR,
TAG_TAB_SCROLLABLE
)
)
val tutorial2_7 = TutorialSectionModel(
title = stringResource(R.string.title2_7),
description = "Material Design bottom navigation.\n" +
"Bottom navigation bars allow movement between primary destinations in an app.\n" +
"BottomNavigation should contain multiple BottomNavigationItems, " +
"each representing a singular destination.",
action = {
Tutorial2_7Screen()
},
tags = listOf(
TAG_COMPOSE,
TAG_BOTTOM_NAVIGATION,
TAG_BOTTOM_NAVIGATION_ITEM
)
)
val tutorial2_8 = TutorialSectionModel(
title = stringResource(R.string.title2_8),
description = "Material Design bottom app bar.\n" +
"A bottom app bar displays navigation and key actions at the bottom of screens.",
action = {
Tutorial2_8Screen(onBack)
},
tags = listOf(
TAG_COMPOSE,
TAG_BOTTOM_APP_BAR
)
)
val tutorial2_9_1 = TutorialSectionModel(
title = stringResource(R.string.title2_9_1),
description = "Navigate using side navigation. Navigate after popping from stack. " +
"Open or close drawer with scaffoldState.drawerState",
action = {
Tutorial2_9Screen1()
},
tags = listOf(
TAG_COMPOSE,
TAG_SCAFFOLD,
TAG_NAVIGATION_DRAWER,
TAG_DRAWER_STATE
)
)
val tutorial2_9_2 = TutorialSectionModel(
title = stringResource(R.string.title2_9_2),
description = "Modal navigation drawers block interaction with the rest of " +
"an app’s content with a scrim. They are elevated above most of " +
"the app’s UI and don’t affect the screen’s layout grid.",
action = {
Tutorial2_9Screen2()
},
tags = listOf(
TAG_COMPOSE,
TAG_MODAL_DRAWER,
TAG_DRAWER_STATE
)
)
val tutorial2_9_3 = TutorialSectionModel(
title = stringResource(R.string.title2_9_3),
description = "ModalDrawer sample with Scaffold. ModalDrawer is inside content Scaffold.",
action = {
Tutorial2_9Screen3()
},
tags = listOf(
TAG_COMPOSE,
TAG_SCAFFOLD,
TAG_MODAL_DRAWER,
TAG_DRAWER_STATE
)
)
val tutorial2_9_4 = TutorialSectionModel(
title = stringResource(R.string.title2_9_4),
description = "Another ModalDrawer sample with Scaffold. Scaffold is " +
"inside content of ModalDrawer",
action = {
Tutorial2_9Screen4()
},
tags = listOf(
TAG_COMPOSE,
TAG_SCAFFOLD,
TAG_MODAL_DRAWER,
TAG_DRAWER_STATE
)
)
val tutorial2_10_1 = TutorialSectionModel(
title = stringResource(R.string.title2_10_1),
description = "Create bottom sheet using BottomSheetScaffold and " +
"rememberBottomSheetScaffoldState",
action = {
Tutorial2_10Screen1()
},
tags = listOf(
TAG_COMPOSE,
TAG_SCAFFOLD_BOTTOM_SHEET,
TAG_BOTTOM_SHEET,
TAG_BOTTOM_SHEET_STATE
)
)
val tutorial2_10_2 = TutorialSectionModel(
title = stringResource(R.string.title2_10_2),
description = "Create modal bottom sheet using BottomSheetScaffold and " +
"rememberBottomSheetScaffoldState",
action = {
Tutorial2_10Screen2()
},
tags = listOf(
TAG_COMPOSE,
TAG_MODAL_BOTTOM_SHEET,
TAG_MODAL_BOTTOM_SHEET_VALUE
)
)
val tutorial2_10_3 = TutorialSectionModel(
title = stringResource(R.string.title2_10_3),
description = "Bottom navigation drawers are modal drawers that are " +
"anchored to the bottom of the screen.",
action = {
Tutorial2_10Screen3()
},
tags = listOf(
TAG_COMPOSE,
TAG_BOTTOM_DRAWER
)
)
val tutorial2_10_4 = TutorialSectionModel(
title = stringResource(R.string.title2_10_4),
description = "BottomDrawer with BottomAppBar.",
action = {
Tutorial2_10Screen4()
},
tags = listOf(
TAG_COMPOSE,
TAG_BOTTOM_DRAWER,
TAG_BOTTOM_APP_BAR,
TAG_SCAFFOLD
)
)
val tutorial2_10_5 = TutorialSectionModel(
title = stringResource(R.string.title2_10_5),
description = "A backdrop appears behind all other surfaces in an app, displaying " +
"contextual and actionable content.",
action = {
Tutorial2_10Screen5()
},
tags = listOf(
TAG_COMPOSE,
TAG_BACKDROP_SCAFFOLD
)
)
val tutorial2_11 = TutorialSectionModel(
title = stringResource(R.string.title2_11),
description = "Samples for Snackbar, ProgressIndicator, Slider, CheckBox, " +
"TriStateCheckBox, RadioButton with groups, and Switch.",
action = {
Tutorial2_11Screen()
},
tags = listOf(
TAG_COMPOSE,
TAG_SNACK_BAR,
TAG_LINEAR_PROGRESS_INDICATOR,
TAG_CIRCULAR_PROGRESS_INDICATOR,
TAG_SLIDER,
TAG_CHECKBOX,
TAG_RADIO_BUTTON,
TAG_SWITCH,
TAG_LIST_ITEM
)
)
val tutorial2_12 = TutorialSectionModel(
title = stringResource(R.string.title2_12),
description = "Create Dialog, and AlertDialogs with standard and custom layouts. " +
"Implement on dismiss logic and get result when dialog is closed.",
action = {
Tutorial2_12Screen()
},
tags = listOf(
TAG_COMPOSE,
TAG_DIALOG,
TAG_ALERT_DIALOG,
TAG_DIALOG_PROPERTIES
)
)
val tutorial2_13 = TutorialSectionModel(
title = stringResource(R.string.title2_13),
description = "Create a composable that can be dismissed by swiping left or right.",
action = {
Tutorial2_13Screen()
},
tags = listOf(
TAG_COMPOSE,
TAG_SWIPE_TO_DISMISS
)
)
val tutorial2_14 = TutorialSectionModel(
title = stringResource(R.string.title2_14),
description = "Lazy column compose that has checkbox where items can be checked and unchecked",
action = {
Tutorial2_14Screen()
},
tags = listOf(
TAG_COMPOSE,
TAG_LAZY_COLUMN_CHECKBOX
)
)
return listOf(
tutorial1_1,
tutorial1_2,
tutorial2_1,
tutorial2_2,
tutorial2_3,
tutorial2_4,
tutorial2_5_1,
tutorial2_5_2,
tutorial2_5_3,
tutorial2_5_4,
tutorial2_5_5,
tutorial2_5_6,
tutorial2_5_7,
tutorial2_5_8,
tutorial2_6,
tutorial2_7,
tutorial2_8,
tutorial2_9_1,
tutorial2_9_2,
tutorial2_9_3,
tutorial2_9_4,
tutorial2_10_1,
tutorial2_10_2,
tutorial2_10_3,
tutorial2_10_4,
tutorial2_10_5,
tutorial2_11,
tutorial2_12,
tutorial2_13,
tutorial2_14
)
}
@ExperimentalAnimationApi
@ExperimentalFoundationApi
@ExperimentalComposeUiApi
@Composable
fun createLayoutTutorialList(): List<TutorialSectionModel> {
val tutorial3_1_1 = TutorialSectionModel(
title = stringResource(R.string.title3_1_1),
description = "Create custom modifiers using layout, Measurable, Constraint, Placeable," +
" and LayoutModifier.",
action = {
Tutorial3_1Screen1()
},
tags = listOf(
TAG_COMPOSE,
TAG_CUSTOM_MODIFIER,
TAG_MEASURABLE,
TAG_CONSTRAINTS,
TAG_PLACEABLE,
TAG_LAYOUT_MODIFIER
),
tagColor = LayoutListColor
)
val tutorial3_1_2 = TutorialSectionModel(
title = stringResource(R.string.title3_1_2),
description = "Use Modifier.onGloballyPositioned to get position of a Composable" +
"in parent, root or window.",
action = {
Tutorial3_1Screen2()
},
tags = listOf(
TAG_COMPOSE,
TAG_COMPOSE_MODIFIER,
TAG_COMPOSED_MODIFIER
),
tagColor = LayoutListColor
)
val tutorial3_1_3 = TutorialSectionModel(
title = stringResource(R.string.title3_1_3),
description = "Use Modifier.offset{} and Modifier.graphicsLayer{} to scale, translate or " +
"change other properties of a Composable",
action = {
Tutorial3_1Screen3()
},
tags = listOf(
TAG_COMPOSE,
TAG_COMPOSE_MODIFIER,
TAG_COMPOSE_MODIFIER_GRAPHICS_LAYER,
TAG_SCALE,
TAG_TRANSLATE,
),
tagColor = LayoutListColor
)
val tutorial3_1_4 = TutorialSectionModel(
title = stringResource(R.string.title_1_4),
description = "BoxWithConstraints is a composable that defines its own content " +
"according to the available space, based on the incoming constraints " +
"or the current LayoutDirection.",
action = {
Tutorial3_1Screen4()
},
tags = listOf(
TAG_COMPOSE,
TAG_BOX_WITH_CONSTRAINTS
),
tagColor = LayoutListColor
)
val tutorial3_1_5 = TutorialSectionModel(
title = stringResource(R.string.title_1_5),
description = "In this example Constraints of different size modifiers are observed",
action = {
Tutorial3_1Screen5()
},
tags = listOf(
TAG_COMPOSE,
TAG_COMPOSE_MODIFIER,
TAG_MODIFIER_SIZE,
TAG_MODIFIER_WIDTH,
TAG_MODIFIER_HEIGHT
),
tagColor = LayoutListColor
)
val tutorial3_1_6 = TutorialSectionModel(
title = stringResource(R.string.title_1_6),
description = "Observe how chaining Modifier.size.size, Modifier.sizeIn.size or " +
"Modifier.size.requiredSize or other combination of size modifiers effect final " +
"Constraints.",
action = {
Tutorial3_1Screen6()
},
tags = listOf(
TAG_COMPOSE,
TAG_COMPOSE_MODIFIER,
TAG_MODIFIER_SIZE,
TAG_MODIFIER_WIDTH,
TAG_MODIFIER_HEIGHT,
TAG_MODIFIER_REQUIRED
),
tagColor = LayoutListColor
)
val tutorial3_1_7 = TutorialSectionModel(
title = "3-1-7 Modifier.wrapContentSize",
description = "Use Modifier.wrapContentSize/Width/Height to use content constraints " +
"instead of Constraints forced by parent.",
action = {
Tutorial3_1Screen7()
},
tags = listOf(
TAG_COMPOSE,
TAG_CUSTOM_LAYOUT,
TAG_MEASURABLE,
TAG_CONSTRAINTS
),
tagColor = LayoutListColor
)
val tutorial3_1_8 = TutorialSectionModel(
title = stringResource(R.string.title_3_1_8),
description = "Use Modifier.layout to create LayoutModifier to measure with Constraints " +
"and place Placeables based on which order Modifier.layout is assigned.",
action = {
Tutorial3_1Screen8()
},
tags = listOf(
TAG_COMPOSE,
TAG_LAYOUT_MODIFIER,
TAG_CUSTOM_LAYOUT,
TAG_MEASURABLE,
TAG_CONSTRAINTS,
TAG_PLACEABLE
),
tagColor = LayoutListColor
)
val tutorial3_2_0 = TutorialSectionModel(
title = stringResource(R.string.title3_2_0),
description = "Create custom layout using using layout, " +
"Measurable, Constraint, Placeable.",
action = {
Tutorial3_2Screen0()
},
tags = listOf(
TAG_COMPOSE,
TAG_CUSTOM_LAYOUT,
TAG_MEASURABLE,
TAG_CONSTRAINTS,
TAG_PLACEABLE
),
tagColor = LayoutListColor
)
val tutorial3_2_1 = TutorialSectionModel(
title = stringResource(R.string.title3_2_1),
description = "Create custom layout using using layout, " +
"Measurable, Constraint, Placeable.",
action = {
Tutorial3_2Screen1()
},
tags = listOf(
TAG_COMPOSE,
TAG_CUSTOM_LAYOUT,
TAG_MEASURABLE,
TAG_CONSTRAINTS,
TAG_PLACEABLE
),
tagColor = LayoutListColor
)
val tutorial3_2_2 = TutorialSectionModel(
title = "3-2-2 Custom Layout2",
description = "Create custom layout using using MeasurePolicy " +
"and use intrinsic dimensions.",
action = {
Tutorial3_2Screen2()
},
tags = listOf(
TAG_COMPOSE,
TAG_MEASURE_POLICY,
TAG_INTRINSIC_WIDTH,
TAG_INTRINSIC_HEIGHT,
TAG_CUSTOM_LAYOUT,
TAG_MEASURABLE,
TAG_CONSTRAINTS,
TAG_PLACEABLE
),
tagColor = LayoutListColor
)
val tutorial3_2_3 = TutorialSectionModel(
title = "3-2-3 Constraints",
description = "Create different Constraints to measure Measurables " +
"and observe how constraints" +
"effect dimensions of Placeables and parent Composable.",
action = {
Tutorial3_2Screen3()
},
tags = listOf(
TAG_COMPOSE,
TAG_CUSTOM_LAYOUT,
TAG_MEASURABLE,
TAG_CONSTRAINTS,
TAG_PLACEABLE
),
tagColor = LayoutListColor
)
val tutorial3_2_4 = TutorialSectionModel(
title = "3-2-4 Constraints Bounds",
description = "Update default constraints with or out of bounds of original Constraints" +
", and change layout width out of Constraints bounds to observe how a Composable" +
" is laid out",
action = {
Tutorial3_2Screen4()
},
tags = listOf(
TAG_COMPOSE,
TAG_CUSTOM_LAYOUT,
TAG_MEASURABLE,
TAG_CONSTRAINTS,
TAG_PLACEABLE
),
tagColor = LayoutListColor
)
val tutorial3_2_5 = TutorialSectionModel(
title = "3-2-5 Inner Constraints",
description = "Update default constraints with or out of bounds of original Constraints" +
", and pass Constraints to content to change it's Constraints from size modifier",
action = {
Tutorial3_2Screen5()
},
tags = listOf(
TAG_COMPOSE,
TAG_CUSTOM_LAYOUT,
TAG_MEASURABLE,
TAG_CONSTRAINTS,
TAG_PLACEABLE
),
tagColor = LayoutListColor
)
val tutorial3_2_6 = TutorialSectionModel(
title = "3-2-6 Sibling Constraints",
description = "Inspect how Constraints and assigned width of a layout effects " +
"position of a sibling Composable",
action = {
Tutorial3_2Screen6()
},
tags = listOf(
TAG_COMPOSE,
TAG_CUSTOM_LAYOUT,
TAG_MEASURABLE,
TAG_CONSTRAINTS,
TAG_PLACEABLE
),
tagColor = LayoutListColor
)
val tutorial3_2_7 = TutorialSectionModel(
title = "3-2-7 Constraints.Infinity",
description = "Observe how using infinite constraints incorrectly leads to" +
"exceptions.",
action = {
Tutorial3_2Screen7()
},
tags = listOf(
TAG_COMPOSE,
TAG_CUSTOM_LAYOUT,
TAG_MEASURABLE,
TAG_CONSTRAINTS
),
tagColor = LayoutListColor
)
val tutorial3_2_8 = TutorialSectionModel(
title = "3-2-8 Constrain&Offset",
description = "Use Constraints.offset and/or Constraints.constrainWidth to limit a " +
"Measurable inside parent bounds by creating padding Modifiers " +
"with different variations",
action = {
Tutorial3_2Screen8()
},
tags = listOf(
TAG_COMPOSE,
TAG_CUSTOM_LAYOUT,
TAG_MEASURABLE,
TAG_CONSTRAINTS,
TAG_PLACEABLE
),
tagColor = LayoutListColor
)
val tutorial3_2_9 = TutorialSectionModel(
title = "3-2-9 Constrain&Offset2",
description = "Constraints to measure measurables with Constraints.offset and " +
"Constraints.constrainWidth to limit maximum width or available.",
action = {
Tutorial3_2Screen9()
},
tags = listOf(
TAG_COMPOSE,
TAG_CUSTOM_LAYOUT,
TAG_MEASURABLE,
TAG_CONSTRAINTS,
TAG_PLACEABLE
),
tagColor = LayoutListColor
)
val tutorial3_2_10 = TutorialSectionModel(
title = "3-2-10 Constraints & Modifier.layout",
description = "Constraints to measure measurables with Constraints.offset and " +
"Constraints.constrainWidth to limit maximum width or available " +
"space for Placeable.",
action = {
Tutorial3_2Screen10()
},
tags = listOf(
TAG_COMPOSE,
TAG_CUSTOM_LAYOUT,
TAG_MEASURABLE,
TAG_CONSTRAINTS,
TAG_PLACEABLE
),
tagColor = LayoutListColor
)
val tutorial3_3_1 = TutorialSectionModel(
title = stringResource(R.string.title_3_3_1),
description = "Add custom modifiers to Composable inside a custom layout using it's scope.",
action = {
Tutorial3_3Screen1()
},
tags = listOf(
TAG_COMPOSE,
TAG_CUSTOM_LAYOUT,
TAG_SCOPE,
TAG_PARENT_DATA_MODIFIER,
TAG_MEASURABLE,
TAG_CONSTRAINTS,
TAG_PLACEABLE
),
tagColor = LayoutListColor
)
val tutorial3_3_3 = TutorialSectionModel(
title = stringResource(R.string.title_3_3_3),
description = "Use Modifier.onPlaced invokes after the parent LayoutModifier " +
"and parent layout has been placed and before child " +
"LayoutModifier is placed. This allows child LayoutModifier " +
"to adjust its own placement based on where the parent is.",
action = {
Tutorial3_3Screen3()
},
tags = listOf(
TAG_COMPOSE,
TAG_ON_PLACED_MODIFIER,
TAG_CUSTOM_LAYOUT,
TAG_SCOPE,
TAG_MEASURABLE,
TAG_CONSTRAINTS,
TAG_PLACEABLE
),
tagColor = LayoutListColor
)
val tutorial3_3_4 = TutorialSectionModel(
title = stringResource(R.string.title_3_3_4),
description = "Use Modifier.onPlaced to observe alignment changes.",
action = {
Tutorial3_3Screen4()
},
tags = listOf(
TAG_COMPOSE,
TAG_ON_PLACED_MODIFIER,
TAG_CUSTOM_LAYOUT,
TAG_SCOPE,
TAG_MEASURABLE,
TAG_CONSTRAINTS,
TAG_PLACEABLE
),
tagColor = LayoutListColor
)
val tutorial3_3_5 = TutorialSectionModel(
title = stringResource(R.string.title_3_3_5),
description = "Use Modifier.onPlaced to observe alignment animation.",
action = {
Tutorial3_3Screen5()
},
tags = listOf(
TAG_COMPOSE,
TAG_ON_PLACED_MODIFIER,
TAG_CUSTOM_LAYOUT,
TAG_SCOPE,
TAG_MEASURABLE,
TAG_CONSTRAINTS,
TAG_PLACEABLE
),
tagColor = LayoutListColor
)
val tutorial3_4 = TutorialSectionModel(
title = stringResource(R.string.title_3_4),
description = "Use Modifier.layoutId to get a measurable, and use it to measure another" +
"measurable to match dimensions.",
action = {
Tutorial3_4Screen()
},
tags = listOf(
TAG_COMPOSE,
TAG_CUSTOM_LAYOUT,
TAG_SCOPE,
TAG_LAYOUT_ID_MODIFIER,
TAG_MEASURABLE,
TAG_CONSTRAINTS,
TAG_PLACEABLE
),
tagColor = LayoutListColor
)
val tutorial3_5 = TutorialSectionModel(
title = stringResource(R.string.title_3_5),
description = "SubcomposeLayout allows to subcompose the actual content during " +
"the measuring stage for example to use the values calculated " +
"during the measurement as " +
"params for the composition of the children.",
action = {
Tutorial3_5Screen()
},
tags = listOf(
TAG_COMPOSE,
TAG_SUBCOMPOSE_LAYOUT,
TAG_CUSTOM_LAYOUT,
TAG_MEASURABLE,
TAG_CONSTRAINTS,
TAG_PLACEABLE
),
tagColor = LayoutListColor
)
val tutorial3_6_1 = TutorialSectionModel(
title = stringResource(R.string.title_3_6_1),
description = "Custom layout like whatsapp chat layout that moves " +
"time and message read " +
"status layout right or bottom based on message width.",
action = {
Tutorial3_6Screen1()
},
tags = listOf(
TAG_COMPOSE,
TAG_CUSTOM_LAYOUT,
TAG_MEASURABLE,
TAG_CONSTRAINTS,
TAG_PLACEABLE
),
tagColor = LayoutListColor
)
val tutorial3_6_2 = TutorialSectionModel(
title = stringResource(R.string.title_3_6_2),
description = "Custom layout like whatsapp chat. Added quote and " +
"name tag resized to longest " +
"sibling using SubcomposeColumn from previous examples to have whole layout.",
action = {
Tutorial3_6Screen2()
},
tags = listOf(
TAG_COMPOSE,
TAG_CUSTOM_LAYOUT,
TAG_SUBCOMPOSE_LAYOUT,
TAG_MEASURABLE,
TAG_CONSTRAINTS,
TAG_PLACEABLE
),
tagColor = LayoutListColor
)
val tutorial3_7_1 = TutorialSectionModel(
title = stringResource(R.string.title_3_7_1),
description = "Examine how Composition and Layout phases are called on recomposition.",
action = {
Tutorial3_7Screen1()
},
tags = listOf(
TAG_COMPOSE,
TAG_MEASURABLE,
TAG_CONSTRAINTS,
TAG_CUSTOM_LAYOUT,
TAG_MEASURE_POLICY,
TAG_PHASE_COMPOSITION,
TAG_PHASE_LAYOUT
),
tagColor = LayoutListColor
)
val tutorial3_7_2 = TutorialSectionModel(
title = stringResource(R.string.title_3_7_2),
description = "Examine how Composition and Layout phases are called on recomposition.",
action = {
Tutorial3_7Screen2()
},
tags = listOf(
TAG_COMPOSE,
TAG_MEASURABLE,
TAG_CONSTRAINTS,
TAG_CUSTOM_LAYOUT,
TAG_MEASURE_POLICY,
TAG_PHASE_COMPOSITION,
TAG_PHASE_LAYOUT
),
tagColor = LayoutListColor
)
val tutorial3_9 = TutorialSectionModel(
title = stringResource(R.string.title_3_9),
description = "Detect percentage of visibility of a Composable using Modifier.onPlaced " +
"inside Column with vertical scroll or LazyColumn.",
action = {
Tutorial3_9Screen()
},
tags = listOf(
TAG_COMPOSE,
TAG_LAZY_COLUMN,
TAG_LAZY_LIST_STATE,
TAG_ON_PLACED_MODIFIER
),
tagColor = LayoutListColor
)
val tutorial3_10 = TutorialSectionModel(
title = stringResource(R.string.title_3_10),
description = "Detect position in parent and center an item while its parent is scrolled.",
action = {
Tutorial3_10Screen()
},
tags = listOf(
TAG_COMPOSE,
TAG_LAZY_COLUMN,
TAG_ON_PLACED_MODIFIER
),
tagColor = LayoutListColor
)
return listOf(
tutorial3_1_1,
tutorial3_1_2,
tutorial3_1_3,
tutorial3_1_4,
tutorial3_1_5,
tutorial3_1_6,
tutorial3_1_7,
tutorial3_1_8,
tutorial3_2_0,
tutorial3_2_1,
tutorial3_2_2,
tutorial3_2_3,
tutorial3_2_4,
tutorial3_2_5,
tutorial3_2_6,
tutorial3_2_7,
tutorial3_2_8,
tutorial3_2_9,
tutorial3_2_10,
tutorial3_3_1,
tutorial3_3_3,
tutorial3_3_4,
tutorial3_3_5,
tutorial3_4,
tutorial3_5,
tutorial3_6_1,
tutorial3_6_2,
tutorial3_7_1,
tutorial3_7_2,
tutorial3_9,
tutorial3_10
)
}
@Composable
fun createStateTutorialList(): List<TutorialSectionModel> {
val tutorial4_1_1 = TutorialSectionModel(
title = stringResource(R.string.title_4_1_1),
description = "This tutorial shows how remember and mutableState " +
"effect recomposition and states.",
action = {
Tutorial4_1Screen1()
},
tags = listOf(
TAG_COMPOSE,
TAG_REMEMBER,
TAG_RECOMPOSITION,
TAG_STATE
),
tagColor = StateListColor
)
val tutorial4_1_2 = TutorialSectionModel(
title = stringResource(R.string.title_4_1_2),
description = "This tutorial shows how SnapshotMutationPolicy effects whether " +
"recomposition should be triggered or not.",
action = {
Tutorial4_1Screen2()
},
tags = listOf(
TAG_COMPOSE,
TAG_SNAPSHOT_MUTATION_POLICY,
TAG_REMEMBER,
TAG_RECOMPOSITION,
TAG_STATE
),
tagColor = StateListColor
)
val tutorial4_2_1 = TutorialSectionModel(
title = stringResource(R.string.title_4_2_1),
description = "This tutorial shows how recomposition happens for flat or hierarchical " +
"designs when Composables are in separate functions or stacked together.",
action = {
Tutorial4_2_1Screen()
},
tags = listOf(
TAG_COMPOSE,
TAG_REMEMBER,
TAG_RECOMPOSITION,
TAG_STATE
),
tagColor = StateListColor
)
val tutorial4_2_2 = TutorialSectionModel(
title = stringResource(R.string.title_4_2_2),
description = "This tutorial show how hierarchy of Composables effect Smart Composition",
action = {
Tutorial4_2_2Screen()
},
tags = listOf(
TAG_COMPOSE,
TAG_REMEMBER,
TAG_RECOMPOSITION,
TAG_STATE
),
tagColor = StateListColor
)
val tutorial4_2_3 = TutorialSectionModel(
title = stringResource(R.string.title_4_2_3),
description = "This tutorial shows how scopes(lambda functions) " +
"or hierarchy of Composables " +
"effects Smart Composition. " +
"Uses separate functions for Text, Button, and Columns with random colors are " +
"applied at (re)composition.",
action = {
Tutorial4_2_3Screen()
},
tags = listOf(
TAG_COMPOSE,
TAG_REMEMBER,
TAG_RECOMPOSITION,
TAG_STATE
),
tagColor = StateListColor
)
val tutorial4_2_4 = TutorialSectionModel(
title = stringResource(R.string.title_4_2_4),
description = "This tutorial shows how stable or unstable classes effects recomposition." +
"Skippable functions when called during recomposition, " +
"compose is able to skip the function " +
"if all of the parameters are equal with their previous values.",
action = {
Tutorial4_2_4Screen()
},
tags = listOf(
TAG_COMPOSE,
TAG_STABILITY,
TAG_SKIPPABLE,
TAG_RECOMPOSITION,
TAG_STATE,
TAG_REMEMBER,
),
tagColor = StateListColor
)
val tutorial4_2_5 = TutorialSectionModel(
title = stringResource(R.string.tittle_4_2_5),
description = "This tutorial shows an immutable type that contains unstable types can " +
"be made stable with @Immutable annotation",
action = {
Tutorial4_2_5Screen()
},
tags = listOf(
TAG_COMPOSE,
TAG_STABILITY,
TAG_SKIPPABLE,
TAG_IMMUTABLE,
TAG_RECOMPOSITION,
TAG_STATE,
TAG_REMEMBER,
),
tagColor = StateListColor
)
val tutorial4_2_6 = TutorialSectionModel(
title = stringResource(R.string.tittle_4_2_6),
description = "This tutorial shows an mutable type that contains unstable types can " +
"be made stable with @Stable annotation",
action = {
Tutorial4_2_6Screen()
},
tags = listOf(
TAG_COMPOSE,
TAG_STABILITY,
TAG_SKIPPABLE,
TAG_STABLE,
TAG_RECOMPOSITION,
TAG_STATE,
TAG_REMEMBER,
),
tagColor = StateListColor
)
val tutorial4_2_7 = TutorialSectionModel(
title = stringResource(R.string.tittle_4_2_7),
description = "This tutorial shows unstable types read in a lambda can trigger " +
"recomposition even if the value doesn't change",
action = {
Tutorial4_2_7Screen()
},
tags = listOf(
TAG_COMPOSE,
TAG_STABILITY,
TAG_SKIPPABLE,
TAG_STABLE,
TAG_RECOMPOSITION,
TAG_STATE,
TAG_REMEMBER,
),
tagColor = StateListColor
)
val tutorial4_2_8 = TutorialSectionModel(
title = stringResource(R.string.title_4_2_8),
description = "This tutorial shows @NonRestartableComposable effects skippable and " +
"restartable properties of a Composable",
action = {
Tutorial4_2_8Screen()
},
tags = listOf(
TAG_COMPOSE,
TAG_SKIPPABLE,
TAG_RESTARTABLE,
TAG_NON_RESTARTABLE_COMPOSABLE,
TAG_STABILITY,
TAG_RECOMPOSITION,
TAG_STATE,
TAG_REMEMBER,
),
tagColor = StateListColor
)
val tutorial4_3 = TutorialSectionModel(
title = stringResource(R.string.title_4_3),
description = "Remember produce and remember a new value by calling calculation when " +
"key(s) are updated. Update calculations with buttons.",
action = {
Tutorial4_3Screen()
},
tags = listOf(
TAG_COMPOSE,
TAG_REMEMBER,
TAG_STATE
),
tagColor = StateListColor
)
val tutorial4_4 = TutorialSectionModel(
title = stringResource(R.string.title_4_4),
description = "Create a custom remember and custom component to have badge that changes " +
"its shape based on properties set by custom rememberable.",
action = {
Tutorial4_4Screen()
},
tags = listOf(
TAG_COMPOSE,
TAG_REMEMBER,
TAG_STATE,
TAG_CUSTOM_LAYOUT
),
tagColor = StateListColor
)
val tutorial4_5_1 = TutorialSectionModel(
title = stringResource(R.string.title_4_5_1),
description = "Use remember functions like rememberCoroutineScope, " +
"and rememberUpdatedState and side-effect functions such as " +
"LaunchedEffect and DisposableEffect",
action = {
Tutorial4_5_1Screen()
},
tags = listOf(
TAG_COMPOSE,
TAG_REMEMBER,
TAG_COROUTINE_SCOPE,
TAG_REMEMBER_UPDATED,
TAG_LAUNCHED_EFFECT,
TAG_DISPOSABLE_EFFECT
),
tagColor = StateListColor
)
val tutorial4_5_2 = TutorialSectionModel(
title = stringResource(R.string.title_4_5_2),
description = "Use SideEffect, derivedStateOf, produceState and snapshotFlow.",
action = {
Tutorial4_5_2Screen()
},
tags = listOf(
TAG_COMPOSE,
TAG_REMEMBER,
TAG_SIDE_EFFECT,
TAG_DERIVED_STATE,
TAG_PRODUCE_STATE,
TAG_SNAPSHOT_FLOW,
),
tagColor = StateListColor
)
val tutorial4_6 = TutorialSectionModel(
title = stringResource(R.string.title_4_6),
description = "Recomposition of Modifiers based on states or lambdas they read.",
action = {
Tutorial4_6Screen()
},
tags = listOf(
TAG_COMPOSE,
TAG_REMEMBER,
TAG_COMPOSE_MODIFIER,
TAG_RECOMPOSITION,
),
tagColor = StateListColor
)
val tutorial4_7_1 = TutorialSectionModel(
title = stringResource(R.string.title_4_7_1),
description = "This tutorial changes color or/and offset to display frame phases" +
"Composition->Layout->Draw in one sample.",
action = {
Tutorial4_7_1Screen()
},
tags = listOf(
TAG_COMPOSE,
TAG_COMPOSE_MODIFIER,
TAG_RECOMPOSITION,
TAG_PHASE_COMPOSITION,
TAG_PHASE_LAYOUT,
TAG_PHASE_DRAW
),
tagColor = StateListColor
)
val tutorial4_7_2 = TutorialSectionModel(
title = stringResource(R.string.title_4_7_2),
description = "This tutorial shows Compose phases such as Composition, Layout, and Draw" +
"are set based when a state is read.",
action = {
Tutorial4_7_2Screen()
},
tags = listOf(
TAG_COMPOSE,
TAG_COMPOSE_MODIFIER,
TAG_RECOMPOSITION,
TAG_PHASE_COMPOSITION,
TAG_PHASE_LAYOUT,
TAG_PHASE_DRAW
),
tagColor = StateListColor
)
val tutorial4_7_3 = TutorialSectionModel(
title = stringResource(R.string.title_4_7_3),
description = "This tutorial state reads or lambdas are passed to parents.",
action = {
Tutorial4_7_3Screen()
},
tags = listOf(
TAG_COMPOSE,
TAG_COMPOSE_MODIFIER,
TAG_RECOMPOSITION,
TAG_PHASE_COMPOSITION,
TAG_PHASE_LAYOUT,
TAG_PHASE_DRAW
),
tagColor = StateListColor
)
val tutorial4_10_1 = TutorialSectionModel(
title = stringResource(R.string.title_4_10_1),
description = "movableContentOf converts a lambda into one that moves the remembered " +
"state and nodes created in a previous call " +
"to the new location it is called.",
action = {
Tutorial4_10Screen1()
},
tags = listOf(
TAG_COMPOSE,
TAG_MOVABLE_CONTENT_OF,
TAG_REMEMBER
),
tagColor = StateListColor
)
val tutorial4_10_2 = TutorialSectionModel(
title = stringResource(R.string.title_4_10_2),
description = "Use movableContentOf to inspect effects on Composables when items from " +
"a list while are deleted",
action = {
Tutorial4_10Screen2()
},
tags = listOf(
TAG_COMPOSE,
TAG_MOVABLE_CONTENT_OF,
TAG_SNAPSHOT_STATE_LIST,
TAG_REMEMBER
),
tagColor = StateListColor
)
val tutorial4_10_3 = TutorialSectionModel(
title = stringResource(R.string.title_4_10_3),
description = "Use movableContentOf to inspect state after change in a list",
action = {
Tutorial4_10Screen3()
},
tags = listOf(
TAG_COMPOSE,
TAG_MOVABLE_CONTENT_OF,
TAG_SNAPSHOT_STATE_LIST,
TAG_REMEMBER
),
tagColor = StateListColor
)
val tutorial4_11_1 = TutorialSectionModel(
title = stringResource(R.string.title_4_11_1),
description = "Use SnapshotStateList to trigger recomposition only for updated item",
action = {
Tutorial4_11Screen1()
},
tags = listOf(
TAG_COMPOSE,
TAG_LAZY_COLUMN,
TAG_SNAPSHOT_STATE_LIST,
TAG_RECOMPOSITION,
TAG_REMEMBER,
TAG_STABILITY
),
tagColor = StateListColor
)
val tutorial4_11_2 = TutorialSectionModel(
title = stringResource(R.string.title_4_11_2),
description = "Use SnapshotStateList to trigger recomposition only for updated item and " +
"ViewModel callback to have stable lambda.",
action = {
Tutorial4_11Screen2()
},
tags = listOf(
TAG_COMPOSE,
TAG_LAZY_COLUMN,
TAG_SNAPSHOT_STATE_LIST,
TAG_RECOMPOSITION,
TAG_REMEMBER,
TAG_STABILITY
),
tagColor = StateListColor
)
val tutorial4_11_3 = TutorialSectionModel(
title = stringResource(R.string.title_4_11_3),
description = "Use SnapshotStateList to trigger recomposition only for updated item and " +
"ViewModel callback to have stable lambda and SnapshotStateList for stability " +
"in a scope.",
action = {
Tutorial4_11Screen3()
},
tags = listOf(
TAG_COMPOSE,
TAG_LAZY_COLUMN,
TAG_SNAPSHOT_STATE_LIST,
TAG_RECOMPOSITION,
TAG_REMEMBER,
TAG_STABILITY
),
tagColor = StateListColor
)
val tutorial4_11_6 = TutorialSectionModel(
title = stringResource(R.string.title_4_11_6),
description = "Detect scroll direction of a LazyColumn using LazyListState",
action = {
Tutorial4_11Screen6()
},
tags = listOf(
TAG_COMPOSE,
TAG_LAZY_COLUMN,
TAG_REMEMBER,
TAG_LAZY_LIST_STATE,
TAG_DERIVED_STATE,
TAG_SNAPSHOT_FLOW
),
tagColor = StateListColor
)
return listOf(
tutorial4_1_1,
tutorial4_1_2,
tutorial4_2_1,
tutorial4_2_2,
tutorial4_2_3,
tutorial4_2_4,
tutorial4_2_5,
tutorial4_2_6,
tutorial4_2_7,
tutorial4_2_8,
tutorial4_3,
tutorial4_4,
tutorial4_5_1,
tutorial4_5_2,
tutorial4_6,
tutorial4_7_1,
tutorial4_7_2,
tutorial4_7_3,
tutorial4_10_1,
tutorial4_10_2,
tutorial4_10_3,
tutorial4_11_1,
tutorial4_11_2,
tutorial4_11_3,
tutorial4_11_6
)
}
@Composable
fun createGestureTutorialList(): List<TutorialSectionModel> {
val tutorial5_1_1 = TutorialSectionModel(
title = stringResource(R.string.title_5_1_1),
description = "Use clickable modifier, Indication and InteractionSource." +
"Indication to clip ripples, or create custom ripple effects. " +
"Interaction source to listen for click state" +
"or set state of other composable.",
action = {
Tutorial5_1Screen1()
},
tags = listOf(
TAG_COMPOSE,
TAG_CLICKABLE,
TAG_REMEMBER_RIPPLE,
TAG_INDICATION,
TAG_INTERACTION_SOURCE
),
tagColor = GestureListColor
)
val tutorial5_1_2 = TutorialSectionModel(
title = stringResource(R.string.title_5_1_2),
description = "Use Interaction source to collect interactions or change scale " +
"of Composable's based on interaction state.",
action = {
Tutorial5_1Screen2()
},
tags = listOf(
TAG_COMPOSE,
TAG_CLICKABLE,
TAG_INTERACTION_SOURCE
),
tagColor = GestureListColor
)
val tutorial5_1_3 = TutorialSectionModel(
title = stringResource(R.string.title_5_1_3),
description = "Use Interaction source to listen for click state" +
"or set state of other composable.",
action = {
Tutorial5_1Screen3()
},
tags = listOf(
TAG_COMPOSE,
TAG_CLICKABLE,
TAG_INTERACTION_SOURCE
),
tagColor = GestureListColor
)
val tutorial5_2 = TutorialSectionModel(
title = "5-2 Tap&Drag Gestures",
description = "Use PointerInput to listen press, tap, long press, drag gestures. " +
"detectTapGestures is used for listening for tap, longPress, " +
"doubleYap, and press gestures.\n" +
"detectDragGestures, detectDragAfterLongPress, " +
"detectHorizontalDrag, and detectVerticalDrag" +
"for listening drag gestures.",
action = {
Tutorial5_2Screen()
},
tags = listOf(
TAG_COMPOSE,
TAG_POINTER_INPUT,
TAG_POINTER_INTEROP_FILTER,
TAG_DETECT_TAP_GESTURES,
TAG_DETECT_DRAG_GESTURES,
TAG_ON_PRESS,
TAG_ON_DOUBLE_TAP,
TAG_ON_LONG_PRESS,
TAG_ON_TAP
),
tagColor = GestureListColor
)
val tutorial5_3 = TutorialSectionModel(
title = "5-3 Transform Gestures",
description = "Use PointerInput to listen for detectTransformGesture " +
"to get centroid, pan, zoom and rotate params.",
action = {
Tutorial5_3Screen()
},
tags = listOf(
TAG_COMPOSE,
TAG_POINTER_INPUT,
TAG_DETECT_TRANSFORM_GESTURES,
TAG_CENTROID,
TAG_PAN,
TAG_ZOOM,
TAG_ROTATE
),
tagColor = GestureListColor
)
val tutorial5_4_1 = TutorialSectionModel(
title = "5-4-1 AwaitPointerEventScope1",
description = "Use AwaitPointerEventScope to get awaitFirstDown for down events, " +
"waitForUpOrCancellation for up events, and awaitPointerEvent " +
"for move events with pointers.\n" +
"awaitTouchSlopOrCancellation to check whether pointer crosses " +
"touch slap threshold to start drag motion",
action = {
Tutorial5_4Screen1()
},
tags = listOf(
TAG_COMPOSE,
TAG_POINTER_INPUT,
TAG_AWAIT_POINTER_EVENT_SCOPE,
TAG_POINTER_INPUT_CHANGE,
TAG_AWAIT_FIRST_DOWN,
TAG_WAIT_UP_OR_CANCELLATION,
TAG_AWAIT_POINTER_EVENT,
TAG_AWAIT_TOUCH_SLOP_OR_CANCELLATION,
TAG_AWAIT_DRAG_OR_CANCELLATION
),
tagColor = GestureListColor
)
val tutorial5_4_2 = TutorialSectionModel(
title = "5-4-2 AwaitPointerEventScope2",
description = "Use AwaitPointerEventScope to get ",
action = {
Tutorial5_4Screen2()
},
tags = listOf(
TAG_COMPOSE,
TAG_POINTER_INPUT,
TAG_AWAIT_POINTER_EVENT_SCOPE,
TAG_POINTER_INPUT_CHANGE,
TAG_AWAIT_FIRST_DOWN,
TAG_DRAG,
TAG_HORIZONTAL_DRAG,
TAG_VERTICAL_DRAG,
TAG_AWAIT_HORIZONTAL_TOUCH_SLOP_OR_CANCELLATION,
TAG_AWAIT_VERTICAL_TOUCH_SLOP_OR_CANCELLATION,
),
tagColor = GestureListColor
)
val tutorial5_4_3 = TutorialSectionModel(
title = "5-4-3 Centroid, Zoom, Pan, Rotation",
description = "Use AwaitPointerEventScope to calculate centroid " +
"position and size, zoom, pan, and rotation.",
action = {
Tutorial5_4Screen3()
},
tags = listOf(
TAG_COMPOSE,
TAG_AWAIT_POINTER_EVENT_SCOPE,
TAG_CENTROID,
TAG_PAN,
TAG_ZOOM,
TAG_ROTATE
),
tagColor = GestureListColor
)
val tutorial5_4_4 = TutorialSectionModel(
title = "5-4-4 Long Press Callbacks",
description = "Use AwaitPointerEventScope to create press and long press start and end " +
"callbacks.",
action = {
Tutorial5_4Screen4()
},
tags = listOf(
TAG_COMPOSE,
TAG_POINTER_INPUT,
TAG_AWAIT_POINTER_EVENT_SCOPE,
TAG_POINTER_INPUT_CHANGE,
TAG_AWAIT_FIRST_DOWN,
),
tagColor = GestureListColor
)
val tutorial5_5_1 = TutorialSectionModel(
title = "5-5-1 Combined Gesture Events",
description = "Combine pointerInput function and observe how gestures are performed " +
"when combined with other pointerInput functions",
action = {
Tutorial5_5Screen1()
},
tags = listOf(
TAG_COMPOSE,
TAG_AWAIT_POINTER_EVENT_SCOPE,
),
tagColor = GestureListColor
)
val tutorial5_6_1 = TutorialSectionModel(
title = "5-6-1 Consume Change",
description = "Consume different type of touch events such as down, " +
"position change and check if events are consumed.",
action = {
Tutorial5_6Screen1()
},
tags = listOf(
TAG_COMPOSE,
TAG_AWAIT_POINTER_EVENT_SCOPE,
TAG_POINTER_INPUT_CHANGE,
TAG_AWAIT_FIRST_DOWN,
TAG_AWAIT_POINTER_EVENT,
TAG_CONSUME,
TAG_IS_CONSUMED
),
tagColor = GestureListColor
)
val tutorial5_6_2 = TutorialSectionModel(
title = "5-6-2 Gesture Propagation1",
description = "Consume different type of touch events in Composable in an hierarchy" +
"to display gesture propagation between parent and children with MOVE gestures.",
action = {
Tutorial5_6Screen2()
},
tags = listOf(
TAG_COMPOSE,
TAG_AWAIT_POINTER_EVENT_SCOPE,
TAG_POINTER_INPUT_CHANGE,
TAG_AWAIT_FIRST_DOWN,
TAG_AWAIT_POINTER_EVENT,
TAG_CONSUME,
TAG_IS_CONSUMED
),
tagColor = GestureListColor
)
val tutorial5_6_3 = TutorialSectionModel(
title = "5-6-3 Gesture Propagation2",
description = "Consume different type of touch events in Composable in an hierarchy" +
"to display gesture propagation between parent and children with DRAG gestures.",
action = {
Tutorial5_6Screen3()
},
tags = listOf(
TAG_COMPOSE,
TAG_AWAIT_POINTER_EVENT_SCOPE,
TAG_POINTER_INPUT_CHANGE,
TAG_AWAIT_FIRST_DOWN,
TAG_AWAIT_TOUCH_SLOP_OR_CANCELLATION,
TAG_DRAG,
TAG_CONSUME,
TAG_IS_CONSUMED
),
tagColor = GestureListColor
)
val tutorial5_6_4 = TutorialSectionModel(
title = "5-6-4 Transformation Propagation",
description = "Consume events to rotate, zoom, move or apply drag or " +
"move events on Composables.",
action = {
Tutorial5_6Screen4()
},
tags = listOf(
TAG_COMPOSE,
TAG_AWAIT_POINTER_EVENT_SCOPE,
TAG_POINTER_INPUT_CHANGE,
TAG_AWAIT_FIRST_DOWN,
TAG_AWAIT_TOUCH_SLOP_OR_CANCELLATION,
TAG_CONSUME,
TAG_IS_CONSUMED
),
tagColor = GestureListColor
)
val tutorial5_6_5 = TutorialSectionModel(
title = "5-6-5 PointerEventPass1",
description = "Change PointerEventPass to change direction of event propagation with " +
"child parent relationship.",
action = {
Tutorial5_6Screen5()
},
tags = listOf(
TAG_COMPOSE,
TAG_AWAIT_POINTER_EVENT_SCOPE,
TAG_POINTER_INPUT_CHANGE,
TAG_AWAIT_FIRST_DOWN,
TAG_POINTER_EVENT_PASS
),
tagColor = GestureListColor
)
val tutorial5_6_6 = TutorialSectionModel(
title = "5-6-6 PointerEventPass2",
description = "Change PointerEventPass to change direction of event propagation " +
"with multiple PointerInput.",
action = {
Tutorial5_6Screen6()
},
tags = listOf(
TAG_COMPOSE,
TAG_AWAIT_POINTER_EVENT_SCOPE,
TAG_POINTER_INPUT_CHANGE,
TAG_AWAIT_FIRST_DOWN,
TAG_POINTER_EVENT_PASS
),
tagColor = GestureListColor
)
val tutorial5_6_7 = TutorialSectionModel(
title = "5-6-7 PointerEventPass3",
description = "Change PointerEventPass to change direction of" +
" drag or touch gestures.",
action = {
Tutorial5_6Screen7()
},
tags = listOf(
TAG_COMPOSE,
TAG_AWAIT_POINTER_EVENT_SCOPE,
TAG_POINTER_INPUT_CHANGE,
TAG_AWAIT_FIRST_DOWN,
TAG_POINTER_EVENT_PASS
),
tagColor = GestureListColor
)
val tutorial5_6_8 = TutorialSectionModel(
title = "5-6-8 PointerEventPass4",
description = "Change PointerEventPass to change drag and touch order.",
action = {
Tutorial5_6Screen8()
},
tags = listOf(
TAG_COMPOSE,
TAG_AWAIT_POINTER_EVENT_SCOPE,
TAG_POINTER_INPUT_CHANGE,
TAG_AWAIT_FIRST_DOWN,
TAG_POINTER_EVENT_PASS
),
tagColor = GestureListColor
)
val tutorial5_6_9 = TutorialSectionModel(
title = "5-6-9 PointerEventPass5",
description = "Change PointerEventPass with awaitPointerEvent to get pinch/zoom " +
"gesture or click/long lick first and consume before click based on pass.",
action = {
Tutorial5_6Screen9()
},
tags = listOf(
TAG_COMPOSE,
TAG_AWAIT_POINTER_EVENT_SCOPE,
TAG_POINTER_INPUT_CHANGE,
TAG_AWAIT_FIRST_DOWN,
TAG_AWAIT_POINTER_EVENT,
TAG_POINTER_EVENT_PASS
),
tagColor = GestureListColor
)
val tutorial5_7_1 = TutorialSectionModel(
title = "5-7-1 Ripple Gesture Events",
description = "Implement ripple effect on touch position with gestures.",
action = {
Tutorial5_7Screen1()
},
tags = listOf(
TAG_COMPOSE,
TAG_AWAIT_POINTER_EVENT_SCOPE,
TAG_INDICATION,
TAG_INTERACTION_SOURCE
),
tagColor = GestureListColor
)
val tutorial5_8_1 = TutorialSectionModel(
title = "5-8-1 Drag Modifier",
description = "Use drag Modifier, rememberDraggableState",
action = {
Tutorial5_8Screen1()
},
tags = listOf(
TAG_COMPOSE,
TAG_DRAGGABLE,
TAG_REMEMBER_DRAGGABLE_STATE
),
tagColor = GestureListColor
)
val tutorial5_8_2 = TutorialSectionModel(
title = "5-8-2 Swipe Modifier",
description = "Use swipe modifier, rememberSwipeableState, FractionalThreshold to " +
"create swipeable Composables.",
action = {
Tutorial5_8Screen2()
},
tags = listOf(
TAG_COMPOSE,
TAG_SWIPEABLE,
TAG_REMEMBER_SWIPEABLE_STATE,
TAG_FRACTIONAL_THRESHHOLD
),
tagColor = GestureListColor
)
val tutorial5_9_1 = TutorialSectionModel(
title = "5-9-1 Scrollable Modifier",
description = "Implement scrolling behavior.",
action = {
Tutorial5_9Screen1()
},
tags = listOf(
TAG_COMPOSE,
TAG_SCROLLABLE,
TAG_REMEMBER_SCROLL_STATE
),
tagColor = GestureListColor
)
val tutorial5_9_2 = TutorialSectionModel(
title = "5-9-2 Nested Scrolling1",
description = "Implement nested scrolling using only vertical scrolling " +
"and rememberScrollState.",
action = {
Tutorial5_9Screen2()
},
tags = listOf(
TAG_COMPOSE,
TAG_REMEMBER_SCROLL_STATE
),
tagColor = GestureListColor
)
val tutorial5_9_3 = TutorialSectionModel(
title = "5-9-3 Nested Scrolling2",
description = "This tutorial shows how and when functions, such as onPreScroll, of " +
"NestedScrollConnection called when Modifier.nestedScroll is used.",
action = {
Tutorial5_9Screen3()
},
tags = listOf(
TAG_COMPOSE,
TAG_NESTED_SCROLL,
TAG_NESTED_SCROLL_CONNECTION
),
tagColor = GestureListColor
)
val tutorial5_9_5 = TutorialSectionModel(
title = "5-9-5 Draggable&Nested Scroll",
description = "Build a Modifier.draggable " +
"(which doesn't have nested scroll build in by default)" +
"and add nested scroll support our component that contains draggable",
action = {
Tutorial5_9Screen5()
},
tags = listOf(
TAG_COMPOSE,
TAG_NESTED_SCROLL,
TAG_NESTED_SCROLL_CONNECTION,
TAG_NESTED_SCROLL_DISPATCHER,
TAG_DRAGGABLE,
),
tagColor = GestureListColor
)
val tutorial5_9_6 = TutorialSectionModel(
title = "5-9-6 Collapsing TopAppBar",
description = "Create a collapsing TopAppBar using Modifier.nestedScroll " +
"and NestedScrollConnection",
action = {
Tutorial5_9Screen6()
},
tags = listOf(
TAG_COMPOSE,
TAG_NESTED_SCROLL,
TAG_NESTED_SCROLL_CONNECTION
),
tagColor = GestureListColor
)
val tutorial5_9_7 = TutorialSectionModel(
title = "5-9-7 Collapsing TopAppBar2",
description = "Create a collapsing TopAppBar using Modifier.nestedScroll " +
"and NestedScrollConnection and change scroll with ScrollState",
action = {
Tutorial5_9Screen7()
},
tags = listOf(
TAG_COMPOSE,
TAG_NESTED_SCROLL,
TAG_NESTED_SCROLL_CONNECTION,
),
tagColor = GestureListColor
)
val tutorial5_10_1 = TutorialSectionModel(
title = "5-10-1 Image Touch Detection",
description = "Detect touch position on image and get color at touch position.",
action = {
Tutorial5_10_1Screen()
},
tags = listOf(
TAG_COMPOSE,
TAG_AWAIT_POINTER_EVENT_SCOPE,
TAG_IMAGE,
),
tagColor = GestureListColor
)
val tutorial5_11 = TutorialSectionModel(
title = "5-11 Zoomable LazyColum",
description = "Zoom images inside a LazyColum.",
action = {
Tutorial5_11Screen()
},
tags = listOf(
TAG_COMPOSE,
TAG_AWAIT_POINTER_EVENT_SCOPE,
TAG_AWAIT_FIRST_DOWN,
TAG_AWAIT_POINTER_EVENT,
TAG_IMAGE,
TAG_ZOOM,
TAG_SCALE,
),
tagColor = GestureListColor
)
return listOf(
tutorial5_1_1,
tutorial5_1_2,
tutorial5_1_3,
tutorial5_2,
tutorial5_3,
tutorial5_4_1,
tutorial5_4_2,
tutorial5_4_3,
tutorial5_4_4,
tutorial5_5_1,
tutorial5_6_1,
tutorial5_6_2,
tutorial5_6_3,
tutorial5_6_4,
tutorial5_6_5,
tutorial5_6_6,
tutorial5_6_7,
tutorial5_6_8,
tutorial5_6_9,
tutorial5_7_1,
tutorial5_8_1,
tutorial5_8_2,
tutorial5_9_1,
tutorial5_9_2,
tutorial5_9_3,
tutorial5_9_5,
tutorial5_9_6,
tutorial5_9_7,
tutorial5_10_1,
tutorial5_11
)
}
@Composable
fun createGraphicsTutorialList(): List<TutorialSectionModel> {
val tutorial6_1_1 = TutorialSectionModel(
title = "6-1-1 Canvas Basics",
description = "Use canvas draw basic shapes like line, circle, rectangle," +
"and points with different attributes such as style, stroke cap, brush.",
action = {
Tutorial6_1Screen1()
},
tags = listOf(
TAG_COMPOSE,
TAG_CANVAS,
TAG_DRAW_SCOPE,
TAG_PATH_EFFECT,
TAG_BRUSH
),
tagColor = GraphicsListColor
)
val tutorial6_1_2 = TutorialSectionModel(
title = "6-1-2 Canvas Basics2",
description = "Use canvas to draw arc, with PathEffect, StrokeCap, " +
"StrokeJoin, miter and other attributes and draw images with src, dst attributes",
action = {
Tutorial6_1Screen2()
},
tags = listOf(
TAG_COMPOSE,
TAG_CANVAS,
TAG_DRAW_SCOPE,
TAG_PATH_EFFECT,
TAG_BRUSH
),
tagColor = GraphicsListColor
)
val tutorial6_1_3 = TutorialSectionModel(
title = "6-1-3 Canvas Paths",
description = "Use canvas to draw path using absolute and relative positions, adding " +
"arc to path, drawing custom paths, progress, polygons, quads, and cubic. ",
action = {
Tutorial6_1Screen3()
},
tags = listOf(
TAG_COMPOSE,
TAG_CANVAS,
TAG_DRAW_SCOPE,
TAG_PATH,
TAG_PATH_EFFECT,
TAG_BRUSH
),
tagColor = GraphicsListColor
)
val tutorial6_1_4 = TutorialSectionModel(
title = "6-1-4 Canvas Path Ops",
description = "Use canvas to clip paths, or canvas using path, or rectangle with " +
"operations such as Difference, Intersect, Union, Xor, or ReverseDifference.",
action = {
Tutorial6_1Screen4()
},
tags = listOf(
TAG_COMPOSE,
TAG_CANVAS,
TAG_DRAW_SCOPE,
TAG_PATH,
TAG_PATH_EFFECT,
TAG_BRUSH,
TAG_PATH_OPERATION,
TAG_CLIP_PATH
),
tagColor = GraphicsListColor
)
val tutorial6_1_5 = TutorialSectionModel(
title = "6-1-5 Canvas Path Segments",
description = "Use canvas to flatten Android Path to path segments and display " +
"PathSegment start and/or end points.",
action = {
Tutorial6_1Screen5()
},
tags = listOf(
TAG_COMPOSE,
TAG_CANVAS,
TAG_DRAW_SCOPE,
TAG_PATH,
TAG_PATH_SEGMENT,
TAG_PATH_OPERATION,
TAG_CLIP_PATH,
TAG_PATH_EFFECT
),
tagColor = GraphicsListColor
)
val tutorial6_1_6 = TutorialSectionModel(
title = "6-1-6 Canvas PathEffect",
description = "Use PathEffects such as dashedPathEffect, cornerPathEffect, " +
"chainPathEffect and stompedPathEffect" +
"to draw shapes or add path effects around Composables.",
action = {
Tutorial6_1Screen6()
},
tags = listOf(
TAG_COMPOSE,
TAG_CANVAS,
TAG_DRAW_SCOPE,
TAG_PATH,
TAG_PATH_EFFECT,
TAG_INFINITE_TRANSITION
),
tagColor = GraphicsListColor
)
val tutorial6_1_7 = TutorialSectionModel(
title = "6-1-7 Canvas Stroke Change",
description = "Draw stroke between edges of Canvas, drawing inwards and outwards direction.",
action = {
Tutorial6_1Screen7()
},
tags = listOf(
TAG_COMPOSE,
TAG_CANVAS,
TAG_DRAW_SCOPE
),
tagColor = GraphicsListColor
)
val tutorial6_2_1 = TutorialSectionModel(
title = "6-2-1 Blend Modes(Porter-Duff)",
description = "Use blend(Porter-Duff) modes to change drawing source/destination " +
"or clip based on blend mode, and manipulate pixels.",
action = {
Tutorial6_2Screen1()
},
tags = listOf(
TAG_COMPOSE,
TAG_CANVAS,
TAG_DRAW_SCOPE,
TAG_BLEND_MODE,
TAG_PATH
),
tagColor = GraphicsListColor
)
val tutorial6_2_2 = TutorialSectionModel(
title = "6-2-2 Canvas(ImageBitmap) & Paint",
description = "Use blend(Porter-Duff) modes with androidx.compose.ui.graphics.Canvas " +
"to change drawing source/destination " +
"or clip based on blend mode, and manipulate pixels.",
action = {
Tutorial6_2Screen2()
},
tags = listOf(
TAG_COMPOSE,
TAG_ACTUAL_CANVAS,
TAG_PAINT,
TAG_BLEND_MODE,
TAG_PATH
),
tagColor = GraphicsListColor
)
val tutorial6_2_3 = TutorialSectionModel(
title = "6-2-3 Multi-Color VectorDrawable",
description = "Use blend(Porter-Duff) to create multi colored VectorDrawables or" +
" VectorDrawables with fill/empty animations",
action = {
Tutorial6_2Screen3()
},
tags = listOf(
TAG_COMPOSE,
TAG_CANVAS,
TAG_DRAW_SCOPE,
TAG_BLEND_MODE,
TAG_VECTOR_DRAWABLE
),
tagColor = GraphicsListColor
)
val tutorial6_4_0 = TutorialSectionModel(
title = "6-4-0 Canvas Touch Events",
description = "Test touch down, move and up events and invocations on Canvas",
action = {
Tutorial6_4Screen0()
},
tags = listOf(
TAG_COMPOSE,
TAG_CANVAS,
TAG_DRAW_SCOPE,
TAG_PATH,
TAG_POINTER_INPUT,
TAG_AWAIT_POINTER_EVENT_SCOPE,
TAG_POINTER_INPUT_CHANGE,
TAG_AWAIT_FIRST_DOWN,
TAG_AWAIT_TOUCH_SLOP_OR_CANCELLATION,
TAG_AWAIT_DRAG_OR_CANCELLATION
),
tagColor = GraphicsListColor
)
val tutorial6_4_1 = TutorialSectionModel(
title = "6-4-1 Draw with Touch",
description = "Draw to canvas using touch down, move and up events, or " +
"drag gestures with properties such as color, stroke width," +
" or draw on image.",
action = {
Tutorial6_4Screen1()
},
tags = listOf(
TAG_COMPOSE,
TAG_CANVAS,
TAG_DRAW_SCOPE,
TAG_PATH,
TAG_POINTER_INPUT,
TAG_AWAIT_POINTER_EVENT_SCOPE,
TAG_POINTER_INPUT_CHANGE,
TAG_AWAIT_FIRST_DOWN,
TAG_AWAIT_TOUCH_SLOP_OR_CANCELLATION,
TAG_AWAIT_DRAG_OR_CANCELLATION,
TAG_BLEND_MODE
),
tagColor = GraphicsListColor
)
val tutorial6_4_2 = TutorialSectionModel(
title = "6-4-2 Drawing App",
description = "Draw to canvas using touch down, move and up events using array of " +
"paths to have erase, undo, redo actions " +
"and set properties for each path separately.",
action = {
Tutorial6_4Screen2()
},
tags = listOf(
TAG_COMPOSE,
TAG_CANVAS,
TAG_DRAW_SCOPE,
TAG_PATH,
TAG_POINTER_INPUT,
TAG_AWAIT_POINTER_EVENT_SCOPE,
TAG_POINTER_INPUT_CHANGE,
TAG_AWAIT_FIRST_DOWN,
TAG_BLEND_MODE
),
tagColor = GraphicsListColor
)
val tutorial6_4_3 = TutorialSectionModel(
title = "6-4-3 Canvas Touch Positions",
description = "Detect touch position on canvas and if it's inside bounds of any " +
"drawing, circle in this sample, move it",
action = {
Tutorial6_4Screen3()
},
tags = listOf(
TAG_COMPOSE,
TAG_CANVAS,
TAG_DRAW_SCOPE,
TAG_PATH,
TAG_POINTER_INPUT,
TAG_AWAIT_POINTER_EVENT_SCOPE,
TAG_POINTER_INPUT_CHANGE,
TAG_AWAIT_FIRST_DOWN,
),
tagColor = GraphicsListColor
)
val tutorial6_5 = TutorialSectionModel(
title = "6-5 Color Picker",
description = "Color Picker that calculates angle from center and gets a color " +
"using hue and returns a color as in HSL or RGB color model.",
action = {
Tutorial6_5Screen()
},
tags = listOf(
TAG_COMPOSE,
TAG_CANVAS,
TAG_DRAW_SCOPE,
TAG_POINTER_INPUT,
TAG_AWAIT_POINTER_EVENT_SCOPE,
TAG_POINTER_INPUT_CHANGE,
TAG_AWAIT_FIRST_DOWN,
TAG_BLEND_MODE
),
tagColor = GraphicsListColor
)
val tutorial6_6 = TutorialSectionModel(
title = "6-6 Scale/Translation Edit",
description = "Editable Composable that changes position and scale when touched and dragged" +
"from handles or changes position when touched inside.",
action = {
Tutorial6_6Screen()
},
tags = listOf(
TAG_COMPOSE,
TAG_CANVAS,
TAG_SCALE,
TAG_TRANSLATE,
TAG_POINTER_INPUT,
TAG_AWAIT_POINTER_EVENT_SCOPE,
TAG_POINTER_INPUT_CHANGE,
TAG_AWAIT_FIRST_DOWN,
),
tagColor = GraphicsListColor
)
val tutorial6_7 = TutorialSectionModel(
title = "6-7 Gooey Effect",
description = "Create basic Gooey Effect with static circles " +
"and one with moves with touch",
action = {
Tutorial6_7Screen()
},
tags = listOf(
TAG_COMPOSE,
TAG_CANVAS,
TAG_GOOEY,
TAG_TRANSLATE,
TAG_POINTER_INPUT,
TAG_AWAIT_POINTER_EVENT_SCOPE,
TAG_POINTER_INPUT_CHANGE,
TAG_AWAIT_FIRST_DOWN,
),
tagColor = GraphicsListColor
)
val tutorial6_8_1 = TutorialSectionModel(
title = "6-8-1 Cutout Arc Shape",
description = "Use Path.cubicTo, Path.arcTo to draw cutout shape.",
action = {
Tutorial6_8Screen1()
},
tags = listOf(
TAG_COMPOSE,
TAG_CANVAS,
TAG_PATH,
),
tagColor = GraphicsListColor
)
val tutorial6_9_1 = TutorialSectionModel(
title = "6-9-1 Neon Glow Effect",
description = "Use paint.asFrameworkPaint() to create blur effect to mimic neon glow " +
"and infinite animation to dim and glow infinitely",
action = {
Tutorial6_9Screen1()
},
tags = listOf(
TAG_COMPOSE,
TAG_CANVAS,
TAG_NEON_GLOW,
TAG_INFINITE_TRANSITION
),
tagColor = GraphicsListColor
)
val tutorial6_10 = TutorialSectionModel(
title = "6-10 Ripple on Canvas",
description = "Create ripple effect when user touches specific area using Animatable and" +
"keyFrames to create ripple effect",
action = {
Tutorial6_10Screen()
},
tags = listOf(
TAG_COMPOSE,
TAG_CANVAS,
TAG_INDICATION,
TAG_POINTER_INPUT,
TAG_AWAIT_POINTER_EVENT_SCOPE,
TAG_POINTER_INPUT_CHANGE,
TAG_AWAIT_FIRST_DOWN,
TAG_WAIT_UP_OR_CANCELLATION
),
tagColor = GraphicsListColor
)
val tutorial6_11 = TutorialSectionModel(
title = "6-11 Canvas Erase Percentage",
description = "Use blend(Porter-Duff) modes with androidx.compose.ui.graphics.Canvas " +
"to erase and compare pixels with erased Bitmap to find out " +
"percentage of erased area.",
action = {
Tutorial6_11Screen()
},
tags = listOf(
TAG_COMPOSE,
TAG_ACTUAL_CANVAS,
TAG_PAINT,
TAG_BLEND_MODE,
TAG_PATH
),
tagColor = GraphicsListColor
)
val tutorial6_12 = TutorialSectionModel(
title = "6-12 Diagonal Price Tag",
description = "Use Modifier.drawWithContent, Modifier.composed, " +
"TextMeasurer to draw diagonal price tag with shimmer effect",
action = {
Tutorial6_12Screen()
},
tags = listOf(
TAG_COMPOSE,
TAG_TEXT_MEASURER,
TAG_IMAGE,
TAG_COMPOSE_MODIFIER,
TAG_COMPOSED_MODIFIER,
TAG_CANVAS,
TAG_BRUSH,
TAG_INFINITE_TRANSITION
),
tagColor = GraphicsListColor
)
val tutorial6_13 = TutorialSectionModel(
title = "6-13 Timer with Border",
description = "Use Path segments to create path with progress to display remaining time",
action = {
Tutorial6_13Screen()
},
tags = listOf(
TAG_COMPOSE,
TAG_PATH,
TAG_PATH_SEGMENT,
TAG_CANVAS,
TAG_ANIMATE_FLOAT_AS_STATE
),
tagColor = GraphicsListColor
)
val tutorial6_14 = TutorialSectionModel(
title = "6-14 Pie Chart with Text",
description = "Draw pie chart with dividers, and text between angles.",
action = {
Tutorial6_14Screen()
},
tags = listOf(
TAG_COMPOSE,
TAG_TEXT_MEASURER,
TAG_CANVAS,
TAG_ANIMATABLE
),
tagColor = GraphicsListColor
)
val tutorial6_15 = TutorialSectionModel(
title = "6-15 Pie Chart with Touch Animation",
description = "Animate Pie Chart on touch and get data of touched section.",
action = {
Tutorial6_15Screen()
},
tags = listOf(
TAG_COMPOSE,
TAG_TEXT_MEASURER,
TAG_CANVAS,
TAG_ANIMATABLE,
TAG_DETECT_TAP_GESTURES
),
tagColor = GraphicsListColor
)
val tutorial6_16 = TutorialSectionModel(
title = "6-16 Segmented Border",
description = "Draw border that divides Composable into segments.",
action = {
Tutorial6_16Screen()
},
tags = listOf(
TAG_COMPOSE,
TAG_COMPOSE_MODIFIER,
TAG_COMPOSED_MODIFIER,
TAG_CANVAS,
),
tagColor = GraphicsListColor
)
val tutorial6_17 = TutorialSectionModel(
title = "6-17 Animated Rainbow Border",
description = "Draw animated rainbow color border using BlendMode.SrcIn" +
"and Modifier.drawWithCache",
action = {
Tutorial6_17Screen()
},
tags = listOf(
TAG_COMPOSE,
TAG_COMPOSE_MODIFIER,
TAG_COMPOSED_MODIFIER,
TAG_CANVAS,
TAG_BRUSH,
TAG_BLEND_MODE,
TAG_INFINITE_TRANSITION
),
tagColor = GraphicsListColor
)
val tutorial6_18 = TutorialSectionModel(
title = "6-18 Shimmer Effect",
description = "Draw shimmer Effect using Brush and infinite animation",
action = {
Tutorial6_18Screen()
},
tags = listOf(
TAG_COMPOSE,
TAG_COMPOSE_MODIFIER,
TAG_COMPOSED_MODIFIER,
TAG_CANVAS,
TAG_BRUSH,
TAG_INFINITE_TRANSITION
),
tagColor = GraphicsListColor
)
val tutorial6_19 = TutorialSectionModel(
title = "6-19 Custom Carousel",
description = "Custom carousel with gestures",
action = {
Tutorial6_19Screen()
},
tags = listOf(
TAG_COMPOSE,
TAG_COMPOSE_CLICKABLE,
TAG_SCROLLABLE,
TAG_HORIZONTAL_DRAG,
TAG_COMPOSE_MODIFIER_GRAPHICS_LAYER
),
tagColor = GraphicsListColor
)
val tutorial6_20 = TutorialSectionModel(
title = "6-20 PathParser and PathMeasure",
description = "Create Path from string and animate segments via PathMeasure",
action = {
Tutorial6_20Screen()
},
tags = listOf(
TAG_COMPOSE,
TAG_CANVAS,
TAG_PATH,
TAG_PATH_PARSER,
TAG_PATH_SEGMENT,
TAG_ANIMATE_FLOAT_AS_STATE
),
tagColor = GraphicsListColor
)
val tutorial6_21 = TutorialSectionModel(
title = "6-21 Constant Velocity Animation",
description = "Create constant time animation.",
action = {
Tutorial6_21Screen()
},
tags = listOf(
TAG_COMPOSE,
TAG_CANVAS,
TAG_ANIMATE_OFFSET_AS_STATE,
TAG_ANIMATE_VALUE_AS_STATE
),
tagColor = GraphicsListColor
)
val tutorial6_22 = TutorialSectionModel(
title = "6-22 Arc fill clock",
description = "Create a clock and set time via LaunchedEffect.",
action = {
Tutorial6_22Screen()
},
tags = listOf(
TAG_COMPOSE,
TAG_CANVAS,
TAG_LAUNCHED_EFFECT,
TAG_REMEMBER_UPDATED
),
tagColor = GraphicsListColor
)
val tutorial6_23 = TutorialSectionModel(
title = "6-23 Tab/Switch Animation",
description = "Create a Tab/Switch with fluent blending text and shadow.",
action = {
Tutorial6_23Screen()
},
tags = listOf(
TAG_COMPOSE,
TAG_CANVAS,
TAG_BLEND_MODE,
TAG_ANIMATE_DP_AS_STATE
),
tagColor = GraphicsListColor
)
val tutorial6_24 = TutorialSectionModel(
title = "6-24 Projection change with Lerp",
description = "Animate projection of rotating circle between inner and " +
"outer projection with lerp function.",
action = {
Tutorial6_24Screen()
},
tags = listOf(
TAG_COMPOSE,
TAG_CANVAS,
TAG_INFINITE_TRANSITION,
TAG_ANIMATE_FLOAT_AS_STATE
),
tagColor = GraphicsListColor
)
val tutorial6_25 = TutorialSectionModel(
title = "6-25 BeforeAfter Layout",
description = "Create animatable BeforeAfter layout with Generic or BlendMode.",
action = {
Tutorial6_25Screen()
},
tags = listOf(
TAG_COMPOSE,
TAG_BLEND_MODE,
TAG_COMPOSE_SHAPE,
TAG_INFINITE_TRANSITION,
TAG_ANIMATE_FLOAT_AS_STATE
),
tagColor = GraphicsListColor
)
val tutorial6_29 = TutorialSectionModel(
title = "6-29 Pie Chart with Tool tip",
description = "Animate Pie Chart with tool tip.",
action = {
Tutorial6_29ToolTipPieChart()
},
tags = listOf(
TAG_COMPOSE,
TAG_TEXT_MEASURER,
TAG_CANVAS,
TAG_ANIMATABLE,
TAG_DETECT_TAP_GESTURES
),
tagColor = GraphicsListColor
)
return listOf(
tutorial6_1_1,
tutorial6_1_2,
tutorial6_1_3,
tutorial6_1_4,
tutorial6_1_5,
tutorial6_1_6,
tutorial6_1_7,
tutorial6_2_1,
tutorial6_2_2,
tutorial6_2_3,
tutorial6_4_0,
tutorial6_4_1,
tutorial6_4_2,
tutorial6_4_3,
tutorial6_5,
tutorial6_6,
tutorial6_7,
tutorial6_8_1,
tutorial6_9_1,
tutorial6_10,
tutorial6_11,
tutorial6_12,
tutorial6_13,
tutorial6_14,
tutorial6_15,
tutorial6_16,
tutorial6_17,
tutorial6_18,
tutorial6_19,
tutorial6_20,
tutorial6_21,
tutorial6_22,
tutorial6_23,
tutorial6_24,
tutorial6_25,
tutorial6_29
)
}
| 4
| null |
312
| 3,006
|
efea98b63e63a85b80f7dc1bd4ca6d769e35905d
| 98,651
|
Jetpack-Compose-Tutorials
|
Apache License 2.0
|
app/src/main/kotlin/co/anitrend/retrofit/graphql/data/arch/database/extensions/DatabaseExtensions.kt
|
AniTrend
| 128,179,094
| false
|
{"Kotlin": 295008, "Shell": 235}
|
package co.anitrend.retrofit.graphql.data.arch.database.extensions
import co.anitrend.arch.extension.ext.empty
import co.anitrend.retrofit.graphql.data.arch.database.ISampleStore
import org.koin.core.scope.Scope
internal fun List<*>.toCommaSeparatedValues(): String {
return if (isNotEmpty()) {
joinToString(separator = ",")
} else
String.empty()
}
internal fun String.fromCommaSeparatedValues(): List<String> {
return if (isNotBlank())
split(',')
else
emptyList()
}
internal inline fun <reified T: Enum<*>> String.toEnum(): T {
val `class` = T::class.java
return `class`.enumConstants?.first { it.name == this }!!
}
internal fun Enum<*>.fromEnum(): String {
return name
}
/**
* Facade for obtaining a database contract
*/
internal fun Scope.db() = get<ISampleStore>()
| 4
|
Kotlin
|
19
| 109
|
e0d1a9df279df6d560220f90f353b388d7fc9eea
| 836
|
retrofit-graphql
|
Apache License 2.0
|
app/src/main/java/com/armutyus/ninova/ui/books/adapters/BooksRecyclerViewAdapter.kt
|
armutyus
| 494,403,387
| false
|
{"Kotlin": 258357}
|
package com.armutyus.ninova.ui.books.adapters
import android.content.Intent
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.TextView
import androidx.core.net.toUri
import androidx.recyclerview.widget.AsyncListDiffer
import androidx.recyclerview.widget.DiffUtil
import androidx.recyclerview.widget.RecyclerView
import com.armutyus.ninova.R
import com.armutyus.ninova.constants.Cache.currentBook
import com.armutyus.ninova.constants.Cache.currentLocalBook
import com.armutyus.ninova.constants.Constants.BOOK_DETAILS_INTENT
import com.armutyus.ninova.constants.Constants.BOOK_TYPE_FOR_DETAILS
import com.armutyus.ninova.constants.Constants.LOCAL_BOOK_TYPE
import com.armutyus.ninova.model.DataModel
import com.bumptech.glide.RequestManager
import javax.inject.Inject
import javax.inject.Named
class BooksRecyclerViewAdapter @Inject constructor(
private val glide: RequestManager
) : RecyclerView.Adapter<BooksRecyclerViewAdapter.MainBooksViewHolder>() {
@Named(BOOK_DETAILS_INTENT)
@Inject
lateinit var bookDetailsIntent: Intent
class MainBooksViewHolder(view: View) : RecyclerView.ViewHolder(view)
private val diffUtil = object : DiffUtil.ItemCallback<DataModel.LocalBook>() {
override fun areItemsTheSame(
oldItem: DataModel.LocalBook,
newItem: DataModel.LocalBook
): Boolean {
return oldItem == newItem
}
override fun areContentsTheSame(
oldItem: DataModel.LocalBook,
newItem: DataModel.LocalBook
): Boolean {
return oldItem == newItem
}
}
private val recyclerListDiffer = AsyncListDiffer(this, diffUtil)
var mainBooksList: List<DataModel.LocalBook>
get() = recyclerListDiffer.currentList
set(value) = recyclerListDiffer.submitList(value)
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): MainBooksViewHolder {
val view =
LayoutInflater.from(parent.context).inflate(R.layout.books_main_row, parent, false)
return MainBooksViewHolder(view)
}
override fun onBindViewHolder(holder: MainBooksViewHolder, position: Int) {
val bookCover = holder.itemView.findViewById<ImageView>(R.id.bookImage)
val bookTitle = holder.itemView.findViewById<TextView>(R.id.bookTitleText)
val bookAuthor = holder.itemView.findViewById<TextView>(R.id.bookAuthorText)
val bookPages = holder.itemView.findViewById<TextView>(R.id.bookPageText)
val bookReleaseDate = holder.itemView.findViewById<TextView>(R.id.bookReleaseDateText)
val book = mainBooksList[position]
holder.itemView.setOnClickListener {
bookDetailsIntent.putExtra(BOOK_TYPE_FOR_DETAILS, LOCAL_BOOK_TYPE)
currentLocalBook = book
currentBook = null
holder.itemView.context.startActivity(bookDetailsIntent)
}
holder.itemView.apply {
glide.load(book.bookCoverSmallThumbnail).centerCrop().into(bookCover)
bookTitle.text = book.bookTitle
bookAuthor.text = book.bookAuthors?.joinToString(", ")
bookPages.text = book.bookPages
bookReleaseDate.text = book.bookPublishedDate
}
}
override fun getItemCount(): Int {
return mainBooksList.size
}
}
| 4
|
Kotlin
|
4
| 9
|
d1482f60dc309b1aff82bb725e901ecb4ef58122
| 3,419
|
ninova
|
MIT License
|
mvicore-demo/mvicore-demo-app/src/main/java/com/badoo/mvicoredemo/di/appscope/module/AndroidModule.kt
|
emreakcan
| 287,947,555
| true
|
{"Kotlin": 172910, "Java": 1704, "Shell": 279}
|
package com.badoo.mvicoredemo.di.appscope.module
import android.content.Context
import android.content.SharedPreferences
import android.content.res.Resources
import com.badoo.mvicoredemo.App
import dagger.Module
import dagger.Provides
@Module
class AndroidModule(context: Context) {
private val context: Context = context.applicationContext
@Provides
fun provideApp(): App {
return context as App
}
@Provides
fun provideContext(): Context {
return context
}
@Provides
fun provideResources(): Resources {
return context.resources
}
@Provides
fun provideSharedPreferences(): SharedPreferences {
return context.getSharedPreferences(App::class.java.name, Context.MODE_PRIVATE)
}
}
| 0
|
Kotlin
|
0
| 2
|
b381a0c3684afca743a39808fbc8a2e37a722375
| 769
|
MVICore
|
Apache License 2.0
|
libraries/designsystem/src/main/kotlin/io/element/android/libraries/designsystem/components/list/SingleSelectionListItem.kt
|
element-hq
| 546,522,002
| false
| null |
/*
* Copyright (c) 2023 New Vector Ltd
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.element.android.libraries.designsystem.components.list
import androidx.compose.runtime.Composable
import androidx.compose.runtime.derivedStateOf
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.runtime.saveable.rememberSaveable
import androidx.compose.runtime.setValue
import androidx.compose.ui.Modifier
import androidx.compose.ui.tooling.preview.Preview
import io.element.android.libraries.designsystem.components.dialogs.ListOption
import io.element.android.libraries.designsystem.components.dialogs.SingleSelectionDialog
import io.element.android.libraries.designsystem.components.dialogs.listOptionOf
import io.element.android.libraries.designsystem.preview.ElementThemedPreview
import io.element.android.libraries.designsystem.preview.PreviewGroup
import io.element.android.libraries.designsystem.theme.components.ListItem
import io.element.android.libraries.designsystem.theme.components.Text
import kotlinx.collections.immutable.ImmutableList
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
import kotlin.time.Duration.Companion.seconds
@Composable
fun SingleSelectionListItem(
headline: String,
options: ImmutableList<ListOption>,
onSelectionChanged: (Int) -> Unit,
modifier: Modifier = Modifier,
supportingText: String? = null,
leadingContent: ListItemContent? = null,
resultFormatter: (Int) -> String? = { options.getOrNull(it)?.title },
selected: Int? = null,
displayResultInTrailingContent: Boolean = false,
) {
val coroutineScope = rememberCoroutineScope()
var selectedIndex by rememberSaveable(selected) { mutableStateOf(selected) }
val selectedItem by remember { derivedStateOf { selectedIndex?.let { resultFormatter(it) } } }
val decoratedSupportedText: @Composable (() -> Unit)? = if (!selectedItem.isNullOrBlank() && !displayResultInTrailingContent) {
@Composable {
Text(selectedItem!!)
}
} else {
supportingText?.let {
@Composable {
Text(it)
}
}
}
val trailingContent: ListItemContent? = if (!selectedItem.isNullOrBlank() && displayResultInTrailingContent) {
ListItemContent.Text(selectedItem!!)
} else {
null
}
var displaySelectionDialog by rememberSaveable { mutableStateOf(false) }
ListItem(
modifier = modifier,
headlineContent = { Text(text = headline) },
supportingContent = decoratedSupportedText,
leadingContent = leadingContent,
trailingContent = trailingContent,
onClick = { displaySelectionDialog = true }
)
if (displaySelectionDialog) {
SingleSelectionDialog(
title = headline,
options = options,
onOptionSelected = { index ->
if (index != selectedIndex) {
onSelectionChanged(index)
selectedIndex = index
}
// Delay hiding the dialog for a bit so the new state is displayed in it before being dismissed
coroutineScope.launch {
delay(0.5.seconds)
displaySelectionDialog = false
}
},
onDismissRequest = { displaySelectionDialog = false },
initialSelection = selectedIndex,
)
}
}
@Preview("Single selection List item - no selection", group = PreviewGroup.ListItems)
@Composable
internal fun SingleSelectionListItemPreview() {
ElementThemedPreview {
SingleSelectionListItem(
headline = "Headline",
options = listOptionOf("Option 1", "Option 2", "Option 3"),
onSelectionChanged = {},
)
}
}
@Preview("Single selection List item - no selection, supporting text", group = PreviewGroup.ListItems)
@Composable
internal fun SingleSelectionListItemUnselectedWithSupportingTextPreview() {
ElementThemedPreview {
SingleSelectionListItem(
headline = "Headline",
options = listOptionOf("Option 1", "Option 2", "Option 3"),
supportingText = "Supporting text",
onSelectionChanged = {},
)
}
}
@Preview("Single selection List item - selection in supporting text", group = PreviewGroup.ListItems)
@Composable
internal fun SingleSelectionListItemSelectedInSupportingTextPreview() {
ElementThemedPreview {
SingleSelectionListItem(
headline = "Headline",
options = listOptionOf("Option 1", "Option 2", "Option 3"),
supportingText = "Supporting text",
onSelectionChanged = {},
selected = 1,
)
}
}
@Preview("Single selection List item - selection in trailing content", group = PreviewGroup.ListItems)
@Composable
internal fun SingleSelectionListItemSelectedInTrailingContentPreview() {
ElementThemedPreview {
SingleSelectionListItem(
headline = "Headline",
options = listOptionOf("Option 1", "Option 2", "Option 3"),
supportingText = "Supporting text",
onSelectionChanged = {},
selected = 1,
displayResultInTrailingContent = true,
)
}
}
@Preview("Single selection List item - custom formatter", group = PreviewGroup.ListItems)
@Composable
internal fun SingleSelectionListItemCustomFormattertPreview() {
ElementThemedPreview {
SingleSelectionListItem(
headline = "Headline",
options = listOptionOf("Option 1", "Option 2", "Option 3"),
supportingText = "Supporting text",
onSelectionChanged = {},
resultFormatter = { "Selected index: $it" },
selected = 1,
displayResultInTrailingContent = true,
)
}
}
| 263
| null |
129
| 955
|
31d0621fa15fe153bfd36104e560c9703eabe917
| 6,514
|
element-x-android
|
Apache License 2.0
|
app/src/main/java/com/santansarah/barcodescanner/ui/account/verified/VerifiedScreen.kt
|
santansarah
| 621,930,119
| false
| null |
package com.santansarah.barcodescanner.ui.account.verified
import androidx.compose.foundation.Image
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.material3.Button
import androidx.compose.material3.Divider
import androidx.compose.material3.ElevatedCard
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Scaffold
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.saveable.rememberSaveable
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.RectangleShape
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import androidx.hilt.navigation.compose.hiltViewModel
import com.santansarah.barcodescanner.R
import com.santansarah.barcodescanner.domain.models.SignInState
import com.santansarah.barcodescanner.domain.models.User
import com.santansarah.barcodescanner.domain.models.UserUIState
import com.santansarah.barcodescanner.ui.account.AccountContainer
import com.santansarah.barcodescanner.ui.components.MainAppBar
import com.santansarah.barcodescanner.ui.search.imageanimations.AnimatedSearchImageRow
import com.santansarah.barcodescanner.ui.search.imageanimations.AnimatedSearchImages
import com.santansarah.barcodescanner.ui.theme.BarcodeScannerTheme
import com.santansarah.barcodescanner.ui.theme.brightYellow
@Composable
fun VerifiedScreen(
viewModel: VerifiedViewModel = hiltViewModel(),
onSearch: () -> Unit,
onAccount: () -> Unit,
onAddPhone: () -> Unit
) {
LaunchedEffect(true) {
viewModel.reloadUser()
}
VerifySuccess(onSearch, onAccount, onAddPhone)
}
@OptIn(ExperimentalMaterial3Api::class)
@Composable
private fun VerifySuccess(
onSearch: () -> Unit,
onAccount: () -> Unit,
onAddPhone: () -> Unit
) {
Scaffold(
topBar = {
MainAppBar(
onBackClicked = null,
title = "Your Account",
onAccountClicked = { }
)
}
) { padding ->
Column(
modifier = Modifier
.padding(padding)
//.padding(top = 20.dp)
.fillMaxSize(),
horizontalAlignment = Alignment.CenterHorizontally,
) {
ElevatedCard(
modifier = Modifier
.fillMaxSize(),
shape = RectangleShape
) {
Column(
modifier = Modifier
.background(brightYellow)
.fillMaxWidth()
) {
Text(
modifier = Modifier
.padding(6.dp),
text = "Account verified. Welcome!",
style = MaterialTheme.typography.titleLarge
)
}
Divider(thickness = 2.dp, color = Color.DarkGray)
AnimatedSearchImageRow(false, AnimatedSearchImages.imageList.take(3))
Column(
modifier = Modifier.padding(horizontal = 20.dp)
) {
Text(
modifier = Modifier.padding(bottom = 36.dp),
text = "Your email is verified - what would you like to do next?",
style = MaterialTheme.typography.headlineMedium,
textAlign = TextAlign.Center
)
Button(
modifier = Modifier.fillMaxWidth(),
onClick = { onSearch() }) {
Text(text = "Search Products")
}
Spacer(modifier = Modifier.height(16.dp))
Button(
modifier = Modifier.fillMaxWidth(),
onClick = { onAccount() }) {
Text(text = "Go to My Account")
}
Spacer(modifier = Modifier.height(16.dp))
Button(
modifier = Modifier.fillMaxWidth(),
onClick = { onAddPhone() }) {
Text(text = "Add 2FA Phone Authentication")
}
Spacer(modifier = Modifier.height(20.dp))
}
}
Divider(thickness = 2.dp, color = Color.DarkGray)
}
}
}
@Preview(showBackground = true, showSystemUi = true)
@Composable
fun VerifySuccessPreview() {
var email by rememberSaveable { mutableStateOf("") }
var password by rememberSaveable { mutableStateOf("") }
BarcodeScannerTheme {
VerifySuccess(onSearch = { /*TODO*/ }, onAccount = { /*TODO*/ }) {
}
}
}
| 0
|
Kotlin
|
0
| 3
|
d044d5cd5fcfa1e96cebdec1ac546056cafece13
| 5,671
|
barcode-scanner
|
MIT License
|
site/src/commonMain/kotlin/pt/rvcoding/personalwebsitecomposehtml/models/content/History.kt
|
revs87
| 745,878,560
| false
|
{"Kotlin": 112933, "Dockerfile": 2766, "CSS": 193}
|
package pt.rvcoding.personalwebsitecomposehtml.models.content
import kotlinx.serialization.Serializable
import pt.rvcoding.personalwebsitecomposehtml.models.PersonalContent
@Serializable
data class History(
val title: String,
val subTitle: String,
val period: String,
val description: List<PersonalContent>,
)
| 0
|
Kotlin
|
0
| 0
|
4de8183fa1cbe82f1b356e283bd3196bc130e6a2
| 329
|
personalwebsite-composehtml
|
MIT License
|
px-checkout/src/main/java/com/mercadopago/android/px/internal/repository/DiscountRepository.kt
|
DevZamSe
| 345,492,088
| false
|
{"Java Properties": 1, "Markdown": 7, "Gradle": 17, "Shell": 1, "YAML": 2, "Batchfile": 1, "Text": 1, "Ignore List": 8, "Proguard": 6, "XML": 205, "Kotlin": 356, "Java": 599, "INI": 2, "JSON": 39, "HTML": 309, "JavaScript": 14, "CSS": 6, "SVG": 2, "Python": 2}
|
package com.mercadopago.android.px.internal.repository
import com.mercadopago.android.px.model.DiscountConfigurationModel
internal interface DiscountRepository : LocalRepository<Map<String, DiscountConfigurationModel>> {
/**
* Obtains the discount configuration that applies in a particular moment of the flow
* <p>
* E.g. If the user did not select any payment method, the general discount is retrieved otherwise you will retrieve
* the best discount between the general discount or the selected payment method.
* <p>
* In the future, with a discount selector feature, the selected discount will be dominant over the best one.
*
* @return The current dominant configuration
*/
fun getCurrentConfiguration(): DiscountConfigurationModel
/**
* Obtains the complete discount configuration for a specif custom option.
*
* @param customOptionId The [com.mercadopago.android.px.model.CustomSearchItem] ID.
* @return The discount configuration, returns null if the ID is invalid.
*/
fun getConfigurationFor(customOptionId: String): DiscountConfigurationModel
}
| 1
| null |
1
| 1
|
a9cab26d5235cfc23bd5f12dd7409fd6158f9194
| 1,143
|
px-android
|
MIT License
|
compose/src/main/java/androidx/compose/material/samples/TextFieldSamples.kt
|
Gurupreet
| 293,232,977
| false
| null |
/*
* Copyright 2020 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package androidx.compose.material.samples
import androidx.annotation.Sampled
import androidx.compose.foundation.Icon
import androidx.compose.foundation.Text
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.padding
import androidx.compose.material.AmbientEmphasisLevels
import androidx.compose.material.MaterialTheme
import androidx.compose.material.OutlinedTextField
import androidx.compose.material.TextField
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Favorite
import androidx.compose.material.icons.filled.Info
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.savedinstancestate.savedInstanceState
import androidx.compose.runtime.setValue
import androidx.compose.ui.Modifier
import androidx.compose.ui.text.TextRange
import androidx.compose.ui.text.input.ImeAction
import androidx.compose.ui.text.input.KeyboardType
import androidx.compose.ui.text.input.PasswordVisualTransformation
import androidx.compose.ui.text.input.TextFieldValue
import androidx.compose.ui.unit.dp
@Sampled
@Composable
fun SimpleTextFieldSample() {
var text by savedInstanceState { "" }
TextField(value = text,
onValueChange = { text = it },
label = { Text("Label") }
)
}
@Sampled
@Composable
fun SimpleOutlinedTextFieldSample() {
var text by savedInstanceState { "" }
OutlinedTextField(
value = text,
onValueChange = { text = it },
label = { Text("Label") }
)
}
@Sampled
@Composable
fun TextFieldWithIcons() {
var text by savedInstanceState { "" }
TextField(value = text,
onValueChange = { text = it },
placeholder = { Text("placeholder") },
leadingIcon = { Icon(Icons.Filled.Favorite) },
trailingIcon = { Icon(Icons.Filled.Info) }
)
}
@Sampled
@Composable
fun TextFieldWithPlaceholder() {
var text by savedInstanceState { "" }
TextField(value = text,
onValueChange = { text = it },
label = { Text("Email") },
placeholder = { Text("<EMAIL>") }
)
}
@Sampled
@Composable
fun TextFieldWithErrorState() {
var text by savedInstanceState { "" }
val isValid = text.count() > 5 && '@' in text
TextField(
value = text,
onValueChange = { text = it },
label = {
val label = if (isValid) "Email" else "Email*"
Text(label)
},
isErrorValue = !isValid
)
}
@Sampled
@Composable
fun TextFieldWithHelperMessage() {
var text by savedInstanceState { "" }
val invalidInput = text.count() < 5 || '@' !in text
Column {
TextField(
value = text,
onValueChange = { text = it },
label = {
val label = if (invalidInput) "Email*" else "Email"
Text(label)
},
isErrorValue = invalidInput
)
val textColor = if (invalidInput) {
MaterialTheme.colors.error
} else {
AmbientEmphasisLevels.current.medium.applyEmphasis(MaterialTheme.colors.onSurface)
}
Text(
text = if (invalidInput) "Requires '@' and at least 5 symbols" else "Helper message",
style = MaterialTheme.typography.caption.copy(color = textColor),
modifier = Modifier.padding(start = 16.dp)
)
}
}
@Sampled
@Composable
fun PasswordTextField() {
var password by savedInstanceState { "" }
TextField(
value = password,
onValueChange = { password = it },
label = { Text("Enter password") },
visualTransformation = PasswordVisualTransformation(),
keyboardType = KeyboardType.Password
)
}
@Sampled
@Composable
fun TextFieldSample() {
var text by savedInstanceState(saver = TextFieldValue.Saver) {
TextFieldValue("example", TextRange(0, 7))
}
TextField(value = text,
onValueChange = { text = it },
label = { Text("Label") }
)
}
@Sampled
@Composable
fun OutlinedTextFieldSample() {
var text by savedInstanceState(saver = TextFieldValue.Saver) {
TextFieldValue("example", TextRange(0, 7))
}
OutlinedTextField(
value = text,
onValueChange = { text = it },
label = { Text("Label") }
)
}
@Sampled
@Composable
fun TextFieldWithHideKeyboardOnImeAction() {
var text by savedInstanceState { "" }
TextField(value = text,
onValueChange = { text = it },
label = { Text("Label") },
imeAction = ImeAction.Done,
onImeActionPerformed = { action, softwareController ->
if (action == ImeAction.Done) {
softwareController?.hideSoftwareKeyboard()
// do something here
}
}
)
}
| 2
| null |
1
| 6
|
1c2fa962d0ebda96326ab69d4af15671989c9583
| 5,439
|
Jetpack-Compose-Playground
|
MIT License
|
packages/expo-speech/android/src/main/java/expo/modules/speech/SpeechInputIsToLongException.kt
|
expo
| 65,750,241
| false
|
{"Gemfile.lock": 1, "YAML": 79, "Git Config": 1, "JSON with Comments": 175, "Ignore List": 236, "JSON": 713, "Markdown": 291, "JavaScript": 1979, "Text": 62, "Git Attributes": 7, "Shell": 66, "Ruby": 99, "TSX": 976, "Gradle": 106, "Java Properties": 5, "Batchfile": 4, "INI": 8, "Proguard": 10, "XML": 273, "Kotlin": 1210, "Dotenv": 7, "OpenStep Property List": 30, "Objective-C": 586, "Objective-C++": 49, "Jest Snapshot": 52, "CODEOWNERS": 1, "SVG": 57, "Java": 282, "Swift": 733, "CMake": 5, "C++": 109, "C": 7, "Gradle Kotlin DSL": 3, "JSON5": 1, "HTML": 5, "MATLAB": 1, "Checksums": 6, "Diff": 46, "MDX": 748, "robots.txt": 1, "CSS": 4, "Cloud Firestore Security Rules": 1, "GraphQL": 17, "TOML": 1}
|
package expo.modules.speech
import android.speech.tts.TextToSpeech
import expo.modules.kotlin.exception.CodedException
class SpeechInputIsToLongException : CodedException(
message = "Speech input text is too long! Limit of input length is: ${TextToSpeech.getMaxSpeechInputLength()}"
)
| 668
|
TypeScript
|
5226
| 32,824
|
e62f80228dece98d5afaa4f5c5e4fb195f3daa15
| 289
|
expo
|
Apache License 2.0
|
src/main/kotlin/com/staboss/crypto/cipher/aes/TablesAES.kt
|
staboss
| 263,959,642
| false
|
{"Gradle": 2, "Markdown": 2, "INI": 2, "Shell": 1, "Ignore List": 1, "Batchfile": 1, "Java": 1, "Kotlin": 8, "Text": 3}
|
package com.staboss.crypto.cipher.aes
const val MAX_BLOCK_COLUMNS = 8
const val MAX_KEY_COLUMNS = 8
const val MAX_ROUNDS = 14
/**
* Таблицы Logtable и Alogtable используются для выполнения операции умножения в поле GF(256)
*/
val LOGTABLE = intArrayOf(
0, 0, 25, 1, 50, 2, 26, 198, 75, 199, 27, 104, 51, 238, 223, 3,
100, 4, 224, 14, 52, 141, 129, 239, 76, 113, 8, 200, 248, 105, 28, 193,
125, 194, 29, 181, 249, 185, 39, 106, 77, 228, 166, 114, 154, 201, 9, 120,
101, 47, 138, 5, 33, 15, 225, 36, 18, 240, 130, 69, 53, 147, 218, 142,
150, 143, 219, 189, 54, 208, 206, 148, 19, 92, 210, 241, 64, 70, 131, 56,
102, 221, 253, 48, 191, 6, 139, 98, 179, 37, 226, 152, 34, 136, 145, 16,
126, 110, 72, 195, 163, 182, 30, 66, 58, 107, 40, 84, 250, 133, 61, 186,
43, 121, 10, 21, 155, 159, 94, 202, 78, 212, 172, 229, 243, 115, 167, 87,
175, 88, 168, 80, 244, 234, 214, 116, 79, 174, 233, 213, 231, 230, 173, 232,
44, 215, 117, 122, 235, 22, 11, 245, 89, 203, 95, 176, 156, 169, 81, 160,
127, 12, 246, 111, 23, 196, 73, 236, 216, 67, 31, 45, 164, 118, 123, 183,
204, 187, 62, 90, 251, 96, 177, 134, 59, 82, 161, 108, 170, 85, 41, 157,
151, 178, 135, 144, 97, 190, 220, 252, 188, 149, 207, 205, 55, 63, 91, 209,
83, 57, 132, 60, 65, 162, 109, 71, 20, 42, 158, 93, 86, 242, 211, 171,
68, 17, 146, 217, 35, 32, 46, 137, 180, 124, 184, 38, 119, 153, 227, 165,
103, 74, 237, 222, 197, 49, 254, 24, 13, 99, 140, 128, 192, 247, 112, 7
)
val ALOGTABLE = intArrayOf(
1, 3, 5, 15, 17, 51, 85, 255, 26, 46, 114, 150, 161, 248, 19, 53,
95, 225, 56, 72, 216, 115, 149, 164, 247, 2, 6, 10, 30, 34, 102, 170,
229, 52, 92, 228, 55, 89, 235, 38, 106, 190, 217, 112, 144, 171, 230, 49,
83, 245, 4, 12, 20, 60, 68, 204, 79, 209, 104, 184, 211, 110, 178, 205,
76, 212, 103, 169, 224, 59, 77, 215, 98, 166, 241, 8, 24, 40, 120, 136,
131, 158, 185, 208, 107, 189, 220, 127, 129, 152, 179, 206, 73, 219, 118, 154,
181, 196, 87, 249, 16, 48, 80, 240, 11, 29, 39, 105, 187, 214, 97, 163,
254, 25, 43, 125, 135, 146, 173, 236, 47, 113, 147, 174, 233, 32, 96, 160,
251, 22, 58, 78, 210, 109, 183, 194, 93, 231, 50, 86, 250, 21, 63, 65,
195, 94, 226, 61, 71, 201, 64, 192, 91, 237, 44, 116, 156, 191, 218, 117,
159, 186, 213, 100, 172, 239, 42, 126, 130, 157, 188, 223, 122, 142, 137, 128,
155, 182, 193, 88, 232, 35, 101, 175, 234, 37, 111, 177, 200, 67, 197, 84,
252, 31, 33, 99, 165, 244, 7, 9, 27, 45, 119, 153, 176, 203, 70, 202,
69, 207, 74, 222, 121, 139, 134, 145, 168, 227, 62, 66, 198, 81, 243, 14,
18, 54, 90, 238, 41, 123, 141, 140, 143, 138, 133, 148, 167, 242, 13, 23,
57, 75, 221, 124, 132, 151, 162, 253, 28, 36, 108, 180, 199, 82, 246, 1
)
val S = intArrayOf(
99, 124, 119, 123, 242, 107, 111, 197, 48, 1, 103, 43, 254, 215, 171, 118,
202, 130, 201, 125, 250, 89, 71, 240, 173, 212, 162, 175, 156, 164, 114, 192,
183, 253, 147, 38, 54, 63, 247, 204, 52, 165, 229, 241, 113, 216, 49, 21,
4, 199, 35, 195, 24, 150, 5, 154, 7, 18, 128, 226, 235, 39, 178, 117,
9, 131, 44, 26, 27, 110, 90, 160, 82, 59, 214, 179, 41, 227, 47, 132,
83, 209, 0, 237, 32, 252, 177, 91, 106, 203, 190, 57, 74, 76, 88, 207,
208, 239, 170, 251, 67, 77, 51, 133, 69, 249, 2, 127, 80, 60, 159, 168,
81, 163, 64, 143, 146, 157, 56, 245, 188, 182, 218, 33, 16, 255, 243, 210,
205, 12, 19, 236, 95, 151, 68, 23, 196, 167, 126, 61, 100, 93, 25, 115,
96, 129, 79, 220, 34, 42, 144, 136, 70, 238, 184, 20, 222, 94, 11, 219,
224, 50, 58, 10, 73, 6, 36, 92, 194, 211, 172, 98, 145, 149, 228, 121,
231, 200, 55, 109, 141, 213, 78, 169, 108, 86, 244, 234, 101, 122, 174, 8,
186, 120, 37, 46, 28, 166, 180, 198, 232, 221, 116, 31, 75, 189, 139, 138,
112, 62, 181, 102, 72, 3, 246, 14, 97, 53, 87, 185, 134, 193, 29, 158,
225, 248, 152, 17, 105, 217, 142, 148, 155, 30, 135, 233, 206, 85, 40, 223,
140, 161, 137, 13, 191, 230, 66, 104, 65, 153, 45, 15, 176, 84, 187, 22
)
val Si = intArrayOf(
82, 9, 106, 213, 48, 54, 165, 56, 191, 64, 163, 158, 129, 243, 215, 251,
124, 227, 57, 130, 155, 47, 255, 135, 52, 142, 67, 68, 196, 222, 233, 203,
84, 123, 148, 50, 166, 194, 35, 61, 238, 76, 149, 11, 66, 250, 195, 78,
8, 46, 161, 102, 40, 217, 36, 178, 118, 91, 162, 73, 109, 139, 209, 37,
114, 248, 246, 100, 134, 104, 152, 22, 212, 164, 92, 204, 93, 101, 182, 146,
108, 112, 72, 80, 253, 237, 185, 218, 94, 21, 70, 87, 167, 141, 157, 132,
144, 216, 171, 0, 140, 188, 211, 10, 247, 228, 88, 5, 184, 179, 69, 6,
208, 44, 30, 143, 202, 63, 15, 2, 193, 175, 189, 3, 1, 19, 138, 107,
58, 145, 17, 65, 79, 103, 220, 234, 151, 242, 207, 206, 240, 180, 230, 115,
150, 172, 116, 34, 231, 173, 53, 133, 226, 249, 55, 232, 28, 117, 223, 110,
71, 241, 26, 113, 29, 41, 197, 137, 111, 183, 98, 14, 170, 24, 190, 27,
252, 86, 62, 75, 198, 210, 121, 32, 154, 219, 192, 254, 120, 205, 90, 244,
31, 221, 168, 51, 136, 7, 199, 49, 177, 18, 16, 89, 39, 128, 236, 95,
96, 81, 127, 169, 25, 181, 74, 13, 45, 229, 122, 159, 147, 201, 156, 239,
160, 224, 59, 77, 174, 42, 245, 176, 200, 235, 187, 60, 131, 83, 153, 97,
23, 43, 4, 126, 186, 119, 214, 38, 225, 105, 20, 99, 85, 33, 12, 125
)
val RC = intArrayOf(
0x00, 0x01, 0x02, 0x04, 0x08, 0x10, 0x20, 0x40, 0x80, 0x1B,
0x36, 0x6C, 0xD8, 0xAB, 0x4D, 0x9A, 0x2F, 0x5E, 0xBC, 0x63,
0xC6, 0x97, 0x35, 0x6A, 0xD4, 0xB3, 0x7D, 0xFA, 0xEF, 0xC5
)
val shifts = arrayOf(
intArrayOf(0, 1, 2, 3),
intArrayOf(0, 1, 2, 3),
intArrayOf(0, 1, 2, 3),
intArrayOf(0, 1, 2, 4),
intArrayOf(0, 1, 3, 4)
)
val numrounds = arrayOf(
intArrayOf(10, 11, 12, 13, 14),
intArrayOf(11, 11, 12, 13, 14),
intArrayOf(12, 12, 12, 13, 14),
intArrayOf(13, 13, 13, 13, 14),
intArrayOf(14, 14, 14, 14, 14)
)
| 0
|
Kotlin
|
0
| 0
|
c3cc5847ae5fa53db337bf45c0a99fd44a797c86
| 6,161
|
crypto-symmetric
|
MIT License
|
compiler/ir/ir.tree/src/org/jetbrains/kotlin/ir/builders/IrGenerator.kt
|
JakeWharton
| 99,388,807
| false
| null |
/*
* Copyright 2010-2017 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jetbrains.kotlin.ir.builders
import org.jetbrains.kotlin.builtins.KotlinBuiltIns
import org.jetbrains.kotlin.ir.descriptors.IrBuiltIns
interface IrGenerator {
val context: IrGeneratorContext
}
interface IrGeneratorWithScope : IrGenerator {
val scope: Scope
}
abstract class IrGeneratorContext {
abstract val irBuiltIns: IrBuiltIns
val builtIns: KotlinBuiltIns get() = irBuiltIns.builtIns
}
open class IrGeneratorContextBase(override val irBuiltIns: IrBuiltIns) : IrGeneratorContext()
| 181
| null |
5748
| 83
|
4383335168338df9bbbe2a63cb213a68d0858104
| 1,119
|
kotlin
|
Apache License 2.0
|
filesystem/src/commonMain/kotlin/op/readwrite/ReadFd.kt
|
illarionov
| 848,247,126
| false
|
{"Kotlin": 991649}
|
/*
* Copyright 2024, the wasi-emscripten-host project authors and contributors. Please see the AUTHORS file
* for details. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
* SPDX-License-Identifier: Apache-2.0
*/
package at.released.weh.filesystem.op.readwrite
import at.released.weh.filesystem.error.ReadError
import at.released.weh.filesystem.model.Fd
import at.released.weh.filesystem.op.FileSystemOperation
public data class ReadFd(
public val fd: Fd,
public val iovecs: List<FileSystemByteBuffer>,
public val strategy: ReadWriteStrategy = ReadWriteStrategy.CHANGE_POSITION,
) {
public companion object : FileSystemOperation<ReadFd, ReadError, ULong> {
override val tag: String = "readfd"
}
}
| 0
|
Kotlin
|
0
| 2
|
eac1f7473d21ca17c16e4b1b01185c9e4c7c81a5
| 784
|
wasi-emscripten-host
|
Apache License 2.0
|
app/src/main/java/com/github/ephelsa/mycareer/ui/dialog/LoaderDialog.kt
|
ephelsa
| 312,443,837
| false
| null |
package com.github.ephelsa.mycareer.ui.dialog
import android.annotation.SuppressLint
import android.app.Dialog
import android.graphics.Color
import android.graphics.drawable.ColorDrawable
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.appcompat.app.AlertDialog
import androidx.fragment.app.DialogFragment
import androidx.fragment.app.FragmentTransaction
import com.github.ephelsa.mycareer.R
import com.github.ephelsa.mycareer.databinding.DialogLoaderBinding
class LoaderDialog : DialogFragment() {
private var binding: DialogLoaderBinding? = null
private var isShowing = false
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
dialog?.window?.setBackgroundDrawable(ColorDrawable(Color.TRANSPARENT))
return super.onCreateView(inflater, container, savedInstanceState)
}
@SuppressLint("InflateParams")
override fun onCreateDialog(savedInstanceState: Bundle?): Dialog {
binding = DialogLoaderBinding.bind(layoutInflater.inflate(R.layout.dialog_loader, null))
isCancelable = false
return AlertDialog.Builder(requireActivity())
.setView(binding?.root)
.create()
}
override fun show(transaction: FragmentTransaction, tag: String?): Int {
return if (isShowing) {
super.dismiss()
super.show(transaction, tag)
} else {
super.show(transaction, tag)
}
}
}
| 5
|
Kotlin
|
0
| 2
|
d68ee1b43b6df9e95aa58db72e2999f2207fb94d
| 1,589
|
my-career
|
MIT License
|
app/src/main/java/com/tanasi/sflix/fragments/movie/MovieViewModel.kt
|
stantanasi
| 511,319,545
| false
| null |
package com.tanasi.sflix.fragments.movie
import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.tanasi.sflix.models.Movie
import com.tanasi.sflix.utils.UserPreferences
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
class MovieViewModel(id: String) : ViewModel() {
private val _state = MutableLiveData<State>(State.Loading)
val state: LiveData<State> = _state
sealed class State {
object Loading : State()
data class SuccessLoading(val movie: Movie) : State()
data class FailedLoading(val error: Exception) : State()
}
init {
getMovie(id)
}
private fun getMovie(id: String) = viewModelScope.launch(Dispatchers.IO) {
_state.postValue(State.Loading)
try {
val movie = UserPreferences.currentProvider.getMovie(id)
_state.postValue(State.SuccessLoading(movie))
} catch (e: Exception) {
_state.postValue(State.FailedLoading(e))
}
}
}
| 9
| null |
8
| 56
|
53029752567ee26bc252452d6550b3dc867f90e4
| 1,102
|
sflix
|
Apache License 2.0
|
src/main/kotlin/au/kilemon/messagequeue/queue/exception/DuplicateMessageException.kt
|
Kilemonn
| 521,916,115
| false
| null |
package au.kilemon.messagequeue.queue.exception
/**
* A specific exception used to indicate that an exist `QueueMessage` with the same `UUID` already exists and the new `QueueMessage` can not be added to the queue.
*
* @author github.com/KyleGonzalez
*/
class DuplicateMessageException(uuid: String, queueType: String) : Exception("Duplicate message with UUID [$uuid] exists in queue with type [$queueType].")
| 0
| null |
0
| 5
|
010fad7d516c9cfa7288e27aa966edc4f128c1b1
| 415
|
MessageQueue
|
Apache License 2.0
|
alkemy/src/test/kotlin/io/alkemy/examples/CustomConfigPooled.kt
|
cosmin-marginean
| 630,394,204
| false
| null |
package io.alkemy.examples
import io.alkemy.AlkemyContext
import io.alkemy.config.AlkemyConfig
import io.alkemy.config.Browser
import io.alkemy.use
import io.kotest.core.spec.style.StringSpec
class CustomConfig : StringSpec({
"run with custom config" {
val config = AlkemyConfig.fromSystemProperties()
.copy(
browser = Browser.FIREFOX,
headless = true,
windowWidth = 800,
windowHeight = 600
)
val context = AlkemyContext.NewDriver(config)
context.use {
val form = "#input-example"
val button = "$form button"
val input = "$form input[type='text']"
val loading = "$form #loading"
get("/dynamic_controls")
button.click()
button.shouldBeDisabled()
loading.shouldBeVisible()
input.shouldBeEnabled(10)
}
}
})
| 3
| null |
1
| 14
|
2936f6b76158ff5402a2b8cc6b11d7874843e425
| 944
|
alkemy
|
Apache License 2.0
|
ideaplugin/src/main/kotlin/de/jensklingenberg/htmltocfw/ideaplugin/theme/Theme.kt
|
Foso
| 440,659,239
| false
| null |
package io.github.appspirimentlabs.vectorpreview.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
import com.intellij.openapi.editor.colors.EditorColors
import com.intellij.openapi.editor.colors.EditorColorsManager
import io.github.appspirimentlabs.vectorpreview.theme.intellij.SwingColor
private val DarkGreenColorPalette = darkColors(
primary = green200,
primaryVariant = green700,
secondary = teal200,
onPrimary = Color.Black,
onSecondary = Color.White,
error = Color.Red,
)
private val LightGreenColorPalette = lightColors(
primary = green500,
primaryVariant = green700,
secondary = teal200,
onPrimary = Color.White,
onSurface = Color.Black
)
val toolbarBackground: Color get()= EditorColorsManager.getInstance().schemeForCurrentUITheme.defaultBackground.rgb.let {
Color(it)
}
val tooltipBackground: Color get()= EditorColorsManager.getInstance().schemeForCurrentUITheme.getColor(EditorColors.NOTIFICATION_BACKGROUND)?.rgb?.let {
Color(it)
}?:Color.LightGray
val tooltipText: Color get()= EditorColorsManager.getInstance().schemeForCurrentUITheme.getColor(EditorColors.CARET_COLOR)?.rgb?.let {
Color(it)
}?:Color.LightGray
@Composable
fun WidgetTheme(
darkTheme: Boolean = false,
content: @Composable() () -> Unit,
) {
val colors = if (darkTheme) DarkGreenColorPalette else LightGreenColorPalette
val swingColor = SwingColor()
MaterialTheme(
colors = colors.copy(
background = swingColor.background,
onBackground = swingColor.onBackground,
surface = swingColor.background,
onSurface = swingColor.onBackground,
),
typography = typography,
shapes = shapes,
content = content
)
}
| 668
| null |
645
| 94
|
86b4dfe1b8d0253d2cf67777edf71ae6a4f0a6a6
| 1,931
|
HtmlToComposeWebConverter
|
Apache License 2.0
|
bugsnag-android-performance/src/main/kotlin/com/bugsnag/android/performance/internal/Encodings.kt
|
bugsnag
| 539,491,063
| false
|
{"Kotlin": 501559, "Gherkin": 41179, "Ruby": 7538, "Shell": 2095, "Java": 1362, "Makefile": 617}
|
@file:JvmName("EncodingUtils")
package com.bugsnag.android.performance.internal
import java.util.UUID
private const val UUID_ID_STRING_LENGTH = 32
private const val LONG_ID_STRING_LENGTH = 16
public fun StringBuilder.appendHexPair(b: Int): StringBuilder {
if (b < 16) append('0')
return append(b.toString(16))
}
public fun StringBuilder.appendHexLong(value: Long): StringBuilder {
ensureCapacity(length + LONG_ID_STRING_LENGTH)
return appendHexPair(((value ushr 56) and 0xff).toInt())
.appendHexPair(((value ushr 48) and 0xff).toInt())
.appendHexPair(((value ushr 40) and 0xff).toInt())
.appendHexPair(((value ushr 32) and 0xff).toInt())
.appendHexPair(((value ushr 24) and 0xff).toInt())
.appendHexPair(((value ushr 16) and 0xff).toInt())
.appendHexPair(((value ushr 8) and 0xff).toInt())
.appendHexPair((value and 0xff).toInt())
}
public fun StringBuilder.appendHexUUID(uuid: UUID): StringBuilder {
ensureCapacity(length + UUID_ID_STRING_LENGTH)
return appendHexLong(uuid.mostSignificantBits)
.appendHexLong(uuid.leastSignificantBits)
}
internal fun UUID.toHexString(): String {
return StringBuilder(UUID_ID_STRING_LENGTH)
.appendHexUUID(this)
.toString()
}
internal fun Long.toHexString(): String {
return StringBuilder(LONG_ID_STRING_LENGTH)
.appendHexLong(this)
.toString()
}
internal fun StringBuilder.appendHexString(bytes: ByteArray): StringBuilder {
ensureCapacity(length + (bytes.size * 2))
bytes.forEach { appendHexPair(it.toInt() and 0xff) }
return this
}
| 3
|
Kotlin
|
1
| 4
|
ea6d690ea6701005c26a940e6023248845edecd1
| 1,618
|
bugsnag-android-performance
|
MIT License
|
aoc-2022/src/commonMain/kotlin/fr/outadoc/aoc/scaffold/Day2022Ext.kt
|
outadoc
| 317,517,472
| false
|
{"Kotlin": 183714}
|
package fr.outadoc.aoc.scaffold
internal fun <T, U : Day<T>> U.readDayInput() = readDayInput(year = "2022")
| 0
|
Kotlin
|
0
| 0
|
54410a19b36056a976d48dc3392a4f099def5544
| 109
|
adventofcode
|
Apache License 2.0
|
kt/godot-library/src/main/kotlin/godot/gen/godot/SphereShape3D.kt
|
utopia-rise
| 289,462,532
| false
| null |
// THIS FILE IS GENERATED! DO NOT EDIT IT MANUALLY!
@file:Suppress("PackageDirectoryMismatch", "unused", "FunctionName", "RedundantModalityModifier",
"UNCHECKED_CAST", "JoinDeclarationAndAssignment", "USELESS_CAST",
"RemoveRedundantQualifierName", "NOTHING_TO_INLINE", "NON_FINAL_MEMBER_IN_OBJECT",
"RedundantVisibilityModifier", "RedundantUnitReturnType", "MemberVisibilityCanBePrivate")
package godot
import godot.`annotation`.GodotBaseType
import godot.core.TypeManager
import godot.core.VariantType.DOUBLE
import godot.core.VariantType.NIL
import godot.core.memory.TransferContext
import godot.util.VoidPtr
import kotlin.Boolean
import kotlin.Double
import kotlin.Float
import kotlin.Int
import kotlin.Suppress
/**
* A 3D sphere shape used for physics collision.
*
* Tutorials:
* [https://godotengine.org/asset-library/asset/675](https://godotengine.org/asset-library/asset/675)
*
* A 3D sphere shape, intended for use in physics. Usually used to provide a shape for a [godot.CollisionShape3D].
*
* **Performance:** [godot.SphereShape3D] is fast to check collisions against. It is faster than [godot.BoxShape3D], [godot.CapsuleShape3D], and [godot.CylinderShape3D].
*/
@GodotBaseType
public open class SphereShape3D : Shape3D() {
/**
* The sphere's radius. The shape's diameter is double the radius.
*/
public var radius: Float
get() {
TransferContext.writeArguments()
TransferContext.callMethod(rawPtr, MethodBindings.getRadiusPtr, DOUBLE)
return (TransferContext.readReturnValue(DOUBLE, false) as Double).toFloat()
}
set(`value`) {
TransferContext.writeArguments(DOUBLE to value.toDouble())
TransferContext.callMethod(rawPtr, MethodBindings.setRadiusPtr, NIL)
}
public override fun new(scriptIndex: Int): Boolean {
callConstructor(ENGINECLASS_SPHERESHAPE3D, scriptIndex)
return true
}
public companion object
internal object MethodBindings {
public val setRadiusPtr: VoidPtr = TypeManager.getMethodBindPtr("SphereShape3D", "set_radius")
public val getRadiusPtr: VoidPtr = TypeManager.getMethodBindPtr("SphereShape3D", "get_radius")
}
}
| 63
| null |
39
| 571
|
39dc30230a30d2a6ab4ec3277eb3bc270995ab23
| 2,152
|
godot-kotlin-jvm
|
MIT License
|
core/ui/src/main/kotlin/com/ngapp/metanmobile/core/ui/career/CareerRow.kt
|
ngapp-dev
| 878,233,406
| false
|
{"Kotlin": 1167674}
|
/*
* Copyright 2024 NGApps Dev (https://github.com/ngapp-dev). All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.ngapp.metanmobile.core.ui.career
import androidx.compose.animation.AnimatedVisibility
import androidx.compose.animation.core.animateFloatAsState
import androidx.compose.animation.expandVertically
import androidx.compose.animation.fadeIn
import androidx.compose.animation.fadeOut
import androidx.compose.animation.shrinkVertically
import androidx.compose.foundation.Image
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.width
import androidx.compose.material3.ButtonDefaults
import androidx.compose.material3.Card
import androidx.compose.material3.CardDefaults
import androidx.compose.material3.Icon
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.saveable.rememberSaveable
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.rotate
import androidx.compose.ui.graphics.vector.ImageVector
import androidx.compose.ui.platform.LocalUriHandler
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.res.vectorResource
import androidx.compose.ui.unit.Dp
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import com.ngapp.metanmobile.core.analytics.LocalAnalyticsHelper
import com.ngapp.metanmobile.core.designsystem.component.ButtonWithIcon
import com.ngapp.metanmobile.core.designsystem.component.MMTextButton
import com.ngapp.metanmobile.core.designsystem.component.htmltext.HtmlText
import com.ngapp.metanmobile.core.designsystem.icon.MMIcons
import com.ngapp.metanmobile.core.designsystem.theme.Blue
import com.ngapp.metanmobile.core.designsystem.theme.Gray400
import com.ngapp.metanmobile.core.designsystem.theme.MMShapes
import com.ngapp.metanmobile.core.designsystem.theme.MMTypography
import com.ngapp.metanmobile.core.designsystem.theme.Red700
import com.ngapp.metanmobile.core.designsystem.theme.White
import com.ngapp.metanmobile.core.model.career.CareerResource
import com.ngapp.metanmobile.core.ui.R
import com.ngapp.metanmobile.core.ui.logCareerResourceOpened
@Composable
fun CareerRow(
career: CareerResource,
cardElevation: Dp = 0.dp,
) {
val uriHandler = LocalUriHandler.current
val analyticsHelper = LocalAnalyticsHelper.current
var isExpanded by rememberSaveable { mutableStateOf(false) }
Card(
colors = CardDefaults.cardColors(containerColor = MaterialTheme.colorScheme.onBackground),
elevation = CardDefaults.cardElevation(defaultElevation = cardElevation),
shape = MMShapes.large,
) {
Column(modifier = Modifier.padding(16.dp)) {
Text(
text = career.title,
style = MaterialTheme.typography.displayMedium,
)
Spacer(Modifier.height(16.dp))
Row(modifier = Modifier.padding(top = 8.dp)) {
CareerWidgetIconWithText(
subtitleResId = R.string.core_ui_title_workplace,
text = career.place.ifEmpty { stringResource(R.string.core_ui_text_place_any) },
icon = {
Image(
imageVector = ImageVector.vectorResource(MMIcons.StationCng),
contentDescription = career.place,
modifier = Modifier.height(24.dp),
)
}
)
Spacer(Modifier.width(16.dp))
CareerWidgetIconWithText(
subtitleResId = R.string.core_ui_title_experience,
text = career.exp.ifEmpty { stringResource(R.string.core_ui_text_no_experience) },
icon = {
Icon(
imageVector = MMIcons.Exp,
contentDescription = career.exp,
tint = Red700,
modifier = Modifier.height(24.dp),
)
}
)
}
if (career.description.isNotEmpty()) {
CareerWidgetSubTitle(R.string.core_ui_title_description)
CareerWidgetInfoContent(career.description)
}
AnimatedVisibility(
visible = isExpanded,
enter = fadeIn() + expandVertically(),
exit = fadeOut() + shrinkVertically(),
) {
Column {
if (career.requirements.isNotEmpty()) {
CareerWidgetSubTitle(R.string.core_ui_title_requirements)
CareerWidgetInfoContent(career.requirements)
}
if (career.responsibilities.isNotEmpty()) {
CareerWidgetSubTitle(R.string.core_ui_title_responsibilities)
CareerWidgetInfoContent(career.responsibilities)
}
}
}
if (career.requirements.isNotEmpty() || career.responsibilities.isNotEmpty()) {
MMTextButton(
modifier = Modifier.padding(top = 8.dp),
onClick = { isExpanded = !isExpanded },
colors = ButtonDefaults.textButtonColors(
containerColor = MaterialTheme.colorScheme.onSurfaceVariant.copy(alpha = 0.1f),
),
text = {
Text(
text = if (isExpanded) {
stringResource(R.string.core_ui_button_show_less)
} else {
stringResource(R.string.core_ui_button_show_more)
},
style = MMTypography.bodyLarge,
color = MaterialTheme.colorScheme.onSurfaceVariant,
)
},
trailingIcon = {
val iconRotateState by animateFloatAsState(
targetValue = if (isExpanded) 180f else 0f, label = "arrowAnimation"
)
Icon(
modifier = Modifier.rotate(iconRotateState),
imageVector = MMIcons.ExpandMore,
tint = MaterialTheme.colorScheme.onSurfaceVariant,
contentDescription = if (isExpanded) {
stringResource(R.string.core_ui_button_show_less)
} else {
stringResource(R.string.core_ui_button_show_more)
},
)
}
)
}
ButtonWithIcon(
icon = MMIcons.Email,
iconTint = White,
textResId = R.string.core_ui_button_career_apply,
buttonBackgroundColor = Blue,
fontColor = White,
borderStrokeColor = Blue,
modifier = Modifier.padding(top = 16.dp),
onClick = {
analyticsHelper.logCareerResourceOpened(career.title)
uriHandler.openUri("mailto:<EMAIL>?subject=${career.title}")
}
)
}
}
}
@Composable
private fun CareerWidgetSubTitle(subtitleResId: Int) {
Text(
text = stringResource(subtitleResId),
style = MMTypography.headlineMedium,
color = Gray400,
modifier = Modifier.padding(top = 12.dp)
)
}
@Composable
private fun CareerWidgetInfoContent(text: String) {
HtmlText(
text = text,
modifier = Modifier.padding(top = 8.dp, bottom = 4.dp),
style = MMTypography.titleLarge,
lineHeight = 22.sp,
)
}
@Composable
private fun CareerWidgetIconWithText(
icon: @Composable () -> Unit,
subtitleResId: Int,
text: String,
) {
Row(verticalAlignment = Alignment.CenterVertically) {
icon()
Text(
text = stringResource(subtitleResId),
color = Gray400,
style = MMTypography.headlineMedium,
modifier = Modifier.padding(start = 4.dp),
)
Text(
text = text,
style = MMTypography.titleLarge,
modifier = Modifier.padding(start = 6.dp),
)
}
}
| 0
|
Kotlin
|
0
| 0
|
f44bd23069c40a0342ed1310505f5bcc0547868c
| 9,436
|
metanmobile
|
Apache License 2.0
|
core/src/io/wasin/asteroids/entities/Bullet.kt
|
haxpor
| 96,201,097
| false
| null |
package io.wasin.asteroids.entities
import com.badlogic.gdx.graphics.Color
import com.badlogic.gdx.graphics.glutils.ShapeRenderer
import com.badlogic.gdx.math.MathUtils
import com.badlogic.gdx.utils.Pool
import com.badlogic.gdx.utils.viewport.Viewport
import io.wasin.asteroids.interfaces.IBatchShapeRenderable
import io.wasin.asteroids.interfaces.IBatchWrapperShapeRenderable
/**
* Created by haxpor on 7/10/17.
*/
class Bullet: SpaceObject(), Pool.Poolable, IBatchShapeRenderable {
private var lifeTime: Float = 0.0f
private var lifeTimer: Float = 0.0f
var shouldBeRemoved: Boolean = false
companion object: IBatchWrapperShapeRenderable {
const val SPEED: Float = 350f
const val LIFETIME: Float = 1.0f // in seconds
private var oldShapeRendererColor: Color? = null
override fun beginBatchRender(sr: ShapeRenderer) {
// save old color of renderer, we will set it back later
oldShapeRendererColor = sr.color
sr.color = Color.WHITE
sr.begin(ShapeRenderer.ShapeType.Line)
}
override fun endBatchRender(sr: ShapeRenderer) {
sr.end()
// set old color back to renderer
oldShapeRendererColor?.let { sr.color = it }
}
}
fun spawn(x: Float, y: Float, radians: Float) {
this.x = x
this.y = y
this.radians = radians
dx = MathUtils.cos(radians) * SPEED
dy = MathUtils.sin(radians) * SPEED
width = 2
height = 2
lifeTime = LIFETIME
lifeTimer = 0.0f
}
override fun reset() {
x = 0f
y = 0f
radians = 0f
dx = 0f
dy = 0f
width = 0
height = 0
lifeTime = LIFETIME
lifeTimer = 0.0f
shouldBeRemoved = false
}
fun update(dt: Float, viewport: Viewport) {
x += dx * dt
y += dy * dt
wrap(viewport)
lifeTimer += dt
if (lifeTimer > lifeTime) {
shouldBeRemoved = true
}
}
/**
* Suitable for individual render call on its own.
* Thus no need for caller to prepare state or set anything prior to this call to properly
* render Bullet.
*/
fun render(sr: ShapeRenderer) {
beginBatchRender(sr)
renderBatch(sr)
endBatchRender(sr)
}
/**
* Expected caller to set type to begin with ShapeType.Line, thus it can batch rendering
* several of Bullet
*/
override fun renderBatch(sr: ShapeRenderer) {
sr.circle(x - width/2f, y - height/2f, width.toFloat()/2f)
}
}
| 0
|
Kotlin
|
6
| 34
|
001fea22df35a6d1ed18d6312b3d3248262de0ac
| 2,634
|
asteroids
|
MIT License
|
project-wizard/idea/src/org/jetbrains/kotlin/tools/projectWizard/wizard/ui/components/DropDownComponent.kt
|
JetBrains
| 278,369,660
| false
| null |
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package org.jetbrains.kotlin.tools.projectWizard.wizard.ui.components
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.ui.ComboBox
import com.intellij.ui.ColoredListCellRenderer
import com.intellij.ui.SimpleTextAttributes
import org.jetbrains.kotlin.tools.projectWizard.core.Context
import org.jetbrains.kotlin.tools.projectWizard.core.entity.SettingValidator
import org.jetbrains.kotlin.tools.projectWizard.core.entity.ValidationResult
import org.jetbrains.kotlin.tools.projectWizard.core.entity.settingValidator
import org.jetbrains.kotlin.tools.projectWizard.core.entity.settings.SettingReference
import org.jetbrains.kotlin.tools.projectWizard.settings.DisplayableSettingItem
import org.jetbrains.kotlin.tools.projectWizard.wizard.ui.componentWithCommentAtBottom
import org.jetbrains.kotlin.utils.addToStdlib.safeAs
import java.awt.event.ItemEvent
import javax.swing.DefaultComboBoxModel
import javax.swing.Icon
import javax.swing.JComponent
import javax.swing.JList
class DropDownComponent<T : DisplayableSettingItem>(
context: Context,
private val initialValues: List<T> = emptyList(),
description: String? = null,
initiallySelectedValue: T? = null,
labelText: String? = null,
private val filter: (T) -> Boolean = { true },
private val validator: SettingValidator<T> = settingValidator { ValidationResult.OK },
private val iconProvider: (T) -> Icon? = { null },
onValueUpdate: (T, isByUser: Boolean) -> Unit = { _, _ -> }
) : UIComponent<T>(
context,
labelText,
validator,
onValueUpdate
) {
@Suppress("UNCHECKED_CAST")
private val combobox = ComboBox(
initialValues.filter(filter).toTypedArray<DisplayableSettingItem>() as Array<T>
).apply {
selectedItem = initiallySelectedValue
renderer = object : ColoredListCellRenderer<T>() {
override fun customizeCellRenderer(
list: JList<out T>,
value: T?,
index: Int,
selected: Boolean,
hasFocus: Boolean
) {
if (value == null) return
icon = iconProvider(value)
append(value.text)
value.greyText?.let {
append(" $it", SimpleTextAttributes.GRAYED_ATTRIBUTES)
}
if (this@apply.selectedItem != value) read {
validator.validate(this, value)
.safeAs<ValidationResult.ValidationError>()
?.messages
?.firstOrNull()
?.let { error ->
append(" $error.", SimpleTextAttributes.ERROR_ATTRIBUTES)
}
}
}
}
addItemListener { event ->
if (event?.stateChange == ItemEvent.SELECTED) {
@Suppress("UNCHECKED_CAST")
(event.item as? T)?.let(::fireValueUpdated)
}
}
}
override val alignTarget: JComponent get() = combobox
override val uiComponent = componentWithCommentAtBottom(combobox, description)
fun filterValues() {
val selectedItem = model.selectedItem
safeUpdateUi {
model.removeAllElements()
initialValues.filter(filter).forEach(model::addElement)
when {
model.getIndexOf(selectedItem) != -1 -> {
model.selectedItem = selectedItem
}
model.size != 0 -> {
combobox.selectedIndex = 0
combobox.selectedItem?.let {
ApplicationManager.getApplication().invokeLater {
@Suppress("UNCHECKED_CAST")
forceValueUpdate(it as T)
}
}
}
}
}
uiComponent.repaint()
}
private val model get() = combobox.model as DefaultComboBoxModel
val valuesCount
get() = combobox.model.size
override fun updateUiValue(newValue: T) = safeUpdateUi {
combobox.selectedItem = newValue
}
override fun onValueUpdated(reference: SettingReference<*, *>?) {
super.onValueUpdated(reference)
filterValues()
}
@Suppress("UNCHECKED_CAST")
override fun getUiValue(): T? = combobox.selectedItem as? T
}
| 191
| null |
4372
| 82
|
cc81d7505bc3e9ad503d706998ae8026c067e838
| 4,555
|
intellij-kotlin
|
Apache License 2.0
|
app/features/settings/src/main/java/tv/orange/features/settings/bridge/settings/OrangeViewSettingsFragment.kt
|
NyanArchive
| 503,292,084
| false
| null |
package tv.orange.features.settings.bridge.settings
import tv.orange.features.settings.bridge.IFragment
import tv.twitch.android.settings.base.BaseSettingsFragment
import tv.twitch.android.settings.base.BaseSettingsPresenter
class OrangeSettingsFragment : BaseSettingsFragment(), IFragment {
lateinit var presenterImpl: BaseSettingsPresenter
override fun createPresenter(): BaseSettingsPresenter {
return presenterImpl
}
override fun setPresenter(presenter: BaseSettingsPresenter) {
presenterImpl = presenter
}
}
| 0
|
Kotlin
|
0
| 2
|
69f8dcc9df76fe4a48b2fcad8290f8d1cfcc5ff6
| 552
|
OrangeTV
|
Apache License 2.0
|
plugin-dotnet-agent/src/test/kotlin/jetbrains/buildServer/dotnet/test/dotcover/DotCoverProjectSerializerTest.kt
|
JetBrains
| 49,584,664
| false
| null |
/*
* Copyright 2000-2021 JetBrains s.r.o.
*
* 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 jetbrains.buildServer.dotnet.test.dotcover
import jetbrains.buildServer.Serializer
import jetbrains.buildServer.XmlDocumentService
import jetbrains.buildServer.XmlDocumentServiceImpl
import jetbrains.buildServer.agent.*
import jetbrains.buildServer.agent.runner.PathsService
import jetbrains.buildServer.dotcover.CoverageFilter
import jetbrains.buildServer.dotcover.CoverageFilterProvider
import jetbrains.buildServer.dotcover.DotCoverProject
import jetbrains.buildServer.dotcover.DotCoverProjectSerializerImpl
import jetbrains.buildServer.dotnet.test.agent.ArgumentsServiceStub
import org.jmock.Expectations
import org.jmock.Mockery
import org.jmock.api.Invocation
import org.jmock.lib.action.CustomAction
import org.testng.Assert
import org.testng.annotations.BeforeMethod
import org.testng.annotations.Test
import org.w3c.dom.Document
import java.io.ByteArrayOutputStream
import java.io.File
import java.io.OutputStream
class DotCoverProjectSerializerTest {
private val _realXmlDocumentService: XmlDocumentService = XmlDocumentServiceImpl()
private val _argumentsService: ArgumentsService = ArgumentsServiceStub()
private lateinit var _ctx: Mockery
private lateinit var _pathService: PathsService
private lateinit var _xmlDocumentService: XmlDocumentService
private lateinit var _coverageFilterProvider: CoverageFilterProvider
@BeforeMethod
fun setUp() {
_ctx = Mockery()
_pathService = _ctx.mock<PathsService>(PathsService::class.java)
_xmlDocumentService = _ctx.mock<XmlDocumentService>(XmlDocumentService::class.java)
_coverageFilterProvider = _ctx.mock<CoverageFilterProvider>(CoverageFilterProvider::class.java)
}
@Test
fun shouldGenerateContent() {
// Given
val outputStream = ByteArrayOutputStream()
val document = _realXmlDocumentService.create()
val tempDir = File("temp")
val workingDirectory = Path(File("workDir").path)
val tool = Path(File("wd", "tool").path)
val expectedContent = "<CoverageParams xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\">" +
"<Executable>" + tool.path + "</Executable>" +
"<Arguments>arg1</Arguments>" +
"<WorkingDir>" + workingDirectory.path + "</WorkingDir>" +
"<Output>" + File(tempDir, "snapshot.dcvr").path + "</Output>" +
"<Filters>" +
"<IncludeFilters>" +
"<FilterEntry>" +
"<ModuleMask>aaa</ModuleMask>" +
"<ClassMask>*</ClassMask>" +
"<FunctionMask>*</FunctionMask>" +
"</FilterEntry>" +
"</IncludeFilters>" +
"<ExcludeFilters>" +
"<FilterEntry>" +
"<ModuleMask>bbb</ModuleMask>" +
"<ClassMask>*</ClassMask>" +
"<FunctionMask>*</FunctionMask>" +
"</FilterEntry>" +
"</ExcludeFilters>" +
"</Filters>" +
"<AttributeFilters>" +
"<AttributeFilterEntry>" +
"<ClassMask>aaa</ClassMask>" +
"</AttributeFilterEntry>" +
"<AttributeFilterEntry>" +
"<ClassMask>bbb</ClassMask>" +
"</AttributeFilterEntry>" +
"</AttributeFilters>" +
"</CoverageParams>"
_ctx.checking(object : Expectations() {
init {
oneOf<XmlDocumentService>(_xmlDocumentService).create()
will(returnValue(document))
oneOf<CoverageFilterProvider>(_coverageFilterProvider).filters
will(returnValue(sequenceOf(
CoverageFilter(CoverageFilter.CoverageFilterType.Include, CoverageFilter.Any, "aaa", CoverageFilter.Any, CoverageFilter.Any),
CoverageFilter(CoverageFilter.CoverageFilterType.Exclude, CoverageFilter.Any, "bbb", CoverageFilter.Any, CoverageFilter.Any)
)))
oneOf<CoverageFilterProvider>(_coverageFilterProvider).attributeFilters
will(returnValue(sequenceOf(
CoverageFilter(CoverageFilter.CoverageFilterType.Exclude, CoverageFilter.Any, CoverageFilter.Any, "aaa", CoverageFilter.Any),
CoverageFilter(CoverageFilter.CoverageFilterType.Exclude, CoverageFilter.Any, CoverageFilter.Any, "bbb", CoverageFilter.Any),
CoverageFilter(CoverageFilter.CoverageFilterType.Include, CoverageFilter.Any, CoverageFilter.Any, "ccc", CoverageFilter.Any)
)))
oneOf<XmlDocumentService>(_xmlDocumentService).serialize(document, outputStream)
will(object : CustomAction("doc") {
@Throws(Throwable::class)
override fun invoke(invocation: Invocation): Any? {
_realXmlDocumentService.serialize(invocation.getParameter(0) as Document, invocation.getParameter(1) as OutputStream)
return null
}
})
}
})
val instance = createInstance()
val dotCoverProject = DotCoverProject(
CommandLine(null, TargetType.Tool, tool, workingDirectory, listOf(CommandLineArgument("arg1")), emptyList()),
Path(File(tempDir, "config.dotCover").path),
Path(File(tempDir, "snapshot.dcvr").path))
// When
instance.serialize(dotCoverProject, outputStream)
val actual = String(outputStream.toByteArray()).trim { it <= ' ' }.replace("\n", "").replace("\r", "")
val expected = expectedContent.trim { it <= ' ' }.replace("\n", "").replace("\r", "")
// Then
_ctx.assertIsSatisfied()
Assert.assertEquals(actual, expected)
}
@Test
fun shouldGenerateContentWhenNoFilters() {
// Given
val outputStream = ByteArrayOutputStream()
val document = _realXmlDocumentService.create()
val tempDir = File("temp")
val workingDirectory = Path("workDir")
val tool = Path(File("wd", "tool").path)
val expectedContent = "<CoverageParams xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\">" +
"<Executable>" + tool.path + "</Executable>" +
"<Arguments/>" +
"<WorkingDir>" + workingDirectory.path + "</WorkingDir>" +
"<Output>" + File(tempDir, "snapshot.dcvr").path + "</Output>" +
"</CoverageParams>"
_ctx.checking(object : Expectations() {
init {
oneOf<XmlDocumentService>(_xmlDocumentService).create()
will(returnValue(document))
oneOf<CoverageFilterProvider>(_coverageFilterProvider).filters
will(returnValue(emptySequence<CoverageFilter>()))
oneOf<CoverageFilterProvider>(_coverageFilterProvider).attributeFilters
will(returnValue(emptySequence<CoverageFilter>()))
oneOf<XmlDocumentService>(_xmlDocumentService).serialize(document, outputStream)
will(object : CustomAction("doc") {
@Throws(Throwable::class)
override fun invoke(invocation: Invocation): Any? {
_realXmlDocumentService.serialize(invocation.getParameter(0) as Document, invocation.getParameter(1) as OutputStream)
return null
}
})
}
})
val instance = createInstance()
val dotCoverProject = DotCoverProject(
CommandLine(null, TargetType.Tool, tool, workingDirectory, emptyList(), emptyList()),
Path(File(tempDir, "config.dotCover").path),
Path(File(tempDir, "snapshot.dcvr").path))
// When
instance.serialize(dotCoverProject, outputStream)
val actual = String(outputStream.toByteArray()).trim { it <= ' ' }.replace("\n", "").replace("\r", "")
val expected = expectedContent.trim { it <= ' ' }.replace("\n", "").replace("\r", "")
// Then
_ctx.assertIsSatisfied()
Assert.assertEquals(actual, expected)
}
private fun createInstance(): Serializer<DotCoverProject> {
return DotCoverProjectSerializerImpl(
_xmlDocumentService,
_argumentsService,
_coverageFilterProvider)
}
}
| 15
| null |
23
| 91
|
27d046d4f924620de40edcb78aab04a28affc665
| 9,195
|
teamcity-dotnet-plugin
|
Apache License 2.0
|
grpc-multiplatform-lib/src/androidJvmCommon/kotlin/io/github/timortel/kotlin_multiplatform_grpc_lib/KMChannel.kt
|
TimOrtel
| 503,391,702
| false
|
{"Kotlin": 330017, "ANTLR": 2178, "Dockerfile": 193, "HTML": 191}
|
package io.github.timortel.kotlin_multiplatform_grpc_lib
import io.grpc.ManagedChannel
import io.grpc.ManagedChannelBuilder
/**
* The Jvm [KMChannel] wraps the grpc [ManagedChannel] and delegates its operations to the wrapped native channel.
*/
actual class KMChannel private constructor(val managedChannel: ManagedChannel) {
actual class Builder(private val impl: ManagedChannelBuilder<*>) {
actual companion object {
actual fun forAddress(
name: String,
port: Int
): Builder {
return Builder(ManagedChannelBuilder.forAddress(name, port))
}
}
actual fun usePlaintext(): Builder = apply {
impl.usePlaintext()
}
actual fun build(): KMChannel = KMChannel(impl.build())
}
}
| 1
|
Kotlin
|
14
| 62
|
c2ab8b52c36cade78ba8cc5be1123ff006f715a2
| 821
|
GRPC-Kotlin-Multiplatform
|
Apache License 2.0
|
app/src/test/java/com/example/android_study/Java/Juc/_7_Future_FutureTask_Callable/_1_Example.kt
|
RhythmCoderZZF
| 281,057,053
| false
| null |
package com.example.android_study.Java.Juc._7_Future_FutureTask_Callable
import org.junit.Test
import java.util.concurrent.Callable
import java.util.concurrent.Executors
import java.util.concurrent.FutureTask
/**
* Author:create by RhythmCoder
* Date:2021/7/6
* Description:
*/
class _1_Example {
/**
* Runnable
*/
private inner class MyRunnable : Runnable {
override fun run() {
println("子线程开始执行...")
Thread.sleep(2000)
println("子线程开始执行完毕")
}
}
/**
* Callable
*/
inner class MyCallable : Callable<String> {
override fun call(): String {
println("子线程开始执行...")
Thread.sleep(2000)
println("子线程开始执行完毕")
return Thread.currentThread().name
}
}
//_________________________submit(Callable())________________________________________
@Test
fun t() {
val executor = Executors.newSingleThreadExecutor()
val future = executor.submit(MyCallable())
println("结果:${future.get()}")
}
//_________________________submit(Runnable)________________________________________
@Test
fun t1() {
val executor = Executors.newSingleThreadExecutor()
val future = executor.submit(MyRunnable())
println("结果:${future.get()}")
}
//_________________________submit(FutureTask(Callable))________________________________________
@Test
fun t2() {
val executor = Executors.newSingleThreadExecutor()
val futureTask = FutureTask(MyCallable())
executor.submit(futureTask)
println("结果:${futureTask.get()}")
}
//_________________________submit(FutureTask(Runnable))________________________________________
@Test
fun t3() {
val executor = Executors.newSingleThreadExecutor()
val futureTask = FutureTask(MyRunnable(), "111")
executor.submit(futureTask)
println("结果:${futureTask.get()}")
}
//_________________________cancel Task________________________________________
@Test
fun t4() {
val executor = Executors.newSingleThreadExecutor()
val future=executor.submit(MyCallable())
Thread.sleep(1000)
if (!future.isDone) {
println("取消任务:${future.cancel(true)}")
}
println("结果:${future.get()}")
}
}
| 0
|
Kotlin
|
0
| 0
|
797cb3961876a1dac95d6438a632742cb9e27ed6
| 2,373
|
AndroidStudy
|
Apache License 2.0
|
compose/src/main/java/org/zhiwei/compose/screen/gesture/ClickableScreen.kt
|
iOrchid
| 156,658,695
| false
|
{"Kotlin": 1005931, "Java": 2777}
|
package org.zhiwei.compose.screen.gesture
import android.widget.Toast
import androidx.compose.animation.AnimatedVisibility
import androidx.compose.foundation.Indication
import androidx.compose.foundation.IndicationInstance
import androidx.compose.foundation.background
import androidx.compose.foundation.clickable
import androidx.compose.foundation.interaction.InteractionSource
import androidx.compose.foundation.interaction.MutableInteractionSource
import androidx.compose.foundation.interaction.PressInteraction
import androidx.compose.foundation.interaction.collectIsPressedAsState
import androidx.compose.foundation.isSystemInDarkTheme
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.foundation.verticalScroll
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.ShoppingCart
import androidx.compose.material.ripple.LocalRippleTheme
import androidx.compose.material.ripple.RippleAlpha
import androidx.compose.material.ripple.RippleTheme
import androidx.compose.material.ripple.rememberRipple
import androidx.compose.material3.Button
import androidx.compose.material3.ButtonDefaults
import androidx.compose.material3.Icon
import androidx.compose.material3.Surface
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.CompositionLocalProvider
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.State
import androidx.compose.runtime.getValue
import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.shadow
import androidx.compose.ui.geometry.CornerRadius
import androidx.compose.ui.geometry.Offset
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.drawscope.ContentDrawScope
import androidx.compose.ui.graphics.graphicsLayer
import androidx.compose.ui.platform.LocalContext
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 kotlinx.coroutines.delay
import kotlinx.coroutines.flow.launchIn
import kotlinx.coroutines.flow.onEach
import kotlinx.coroutines.launch
import org.zhiwei.compose.ui.widget.Title_Desc_Text
import org.zhiwei.compose.ui.widget.Title_Sub_Text
import org.zhiwei.compose.ui.widget.Title_Text
@Composable
internal fun Clickable_Screen(modifier: Modifier = Modifier) {
Column(
modifier
.fillMaxSize()
.verticalScroll(rememberScrollState())
) {
Title_Text(title = "Clickable")
Title_Sub_Text(title = "1. 演示常规点击的交互、ripple水波纹效果以及边界和样式。")
//在基础篇,有说明,modifier的许多操作符,有作用顺序而不同效果。
BasicClickable()
Title_Sub_Text(title = "2. interactionSource相关,即compose控件的交互,比如点击/双击/长按/拖拽等。")
UI_Interaction()
}
}
//region 基础使用
@Composable
private inline fun BasicClickable() {
Title_Desc_Text(desc = "clip的作用对比,裁剪的形状和点击作用的水波ripple返回,会因clickable的位置而不同。")
val modifierWithClip = Modifier
.fillMaxWidth()
.height(40.dp)
//裁剪形状clip的作用,用于裁剪形状区域rect
.shadow(elevation = 2.dp, shape = RoundedCornerShape(16.dp), clip = true)
.background(Color(0xffBDBDBD))
UI_Clip2Clickable(modifierWithClip)
Title_Desc_Text(desc = "水波ripple的范围限定,通过interactionSource来设置。")
UI_RippleBounded(modifierWithClip)
Title_Desc_Text(desc = "通过主题theme来设置控件的点击效果的水波ripple")
UI_ThemeRipple(modifierWithClip)
Title_Desc_Text(desc = "自定义的点击交互,这里简单演示的是ripple")
UI_Indication()
}
//clickable点击效果与shape的clip作用前后的对比
@Composable
private fun UI_Clip2Clickable(modifierWithClip: Modifier) {
Column(
modifier = Modifier
.fillMaxWidth()
.padding(8.dp)
) {
Box(
contentAlignment = Alignment.Center,
modifier = modifierWithClip
.clickable {}
) {
Text(
text = "点击在clip前",
color = Color.White,
textAlign = TextAlign.Center
)
}
Spacer(modifier = Modifier.height(8.dp))
Box(
contentAlignment = Alignment.Center,
modifier = Modifier
//clickable而后再应用clip的modifier。这里用到了then操作符,就是将另外的modifier作用于当前
.clickable {}
.then(modifierWithClip)
) {
Text(
text = "Clip后写clickable",
color = Color.White,
textAlign = TextAlign.Center
)
}
}
}
//ripple范围的限定
@Composable
private fun UI_RippleBounded(modifierWithClip: Modifier) {
Column(
modifier = Modifier
.fillMaxWidth()
.padding(8.dp)
) {
//如果多个控件使用同一个MutableInteractionSource,交互效果会同步
val mutableInteractionSource = remember { MutableInteractionSource() }
val mutableInteractionSource2 = remember { MutableInteractionSource() }
Box(
contentAlignment = Alignment.Center,
modifier = modifierWithClip
.clickable(
interactionSource = mutableInteractionSource,
//ripple水波的自定义
indication = rememberRipple(
bounded = true,//限定作用范围
radius = 260.dp,//水波半径
color = Color.Yellow,//水波颜色
)
) {}
) {
Text(
text = "限定ripple范围",
color = Color.White,
textAlign = TextAlign.Center
)
}
Spacer(modifier = Modifier.height(8.dp))
Box(
contentAlignment = Alignment.Center,
modifier = Modifier
.clickable(
interactionSource = mutableInteractionSource2,
//ripple水波的自定义
indication = rememberRipple(
bounded = false,//不限定作用范围
radius = 260.dp,//水波半径
color = Color.Green,//水波颜色
)
) {}
.then(modifierWithClip)
) {
Text(
text = "不限定水波ripple",
color = Color.White,
textAlign = TextAlign.Center
)
}
}
}
//通过theme主题设置ripple样式
@Composable
private fun UI_ThemeRipple(modifierWithClip: Modifier) {
//自定义的ripple theme,也可以封装成类,接收color和alpha等需要的参数。
val customRippleTheme = object : RippleTheme {
@Composable
override fun defaultColor(): Color {
return Color.Red
}
@Composable
override fun rippleAlpha(): RippleAlpha {
return RippleTheme.defaultRippleAlpha(
Color.Red,
lightTheme = !isSystemInDarkTheme()
)
}
}
Column(
Modifier
.fillMaxWidth()
.padding(8.dp)
) {
//简单理解CompositionLocalProvider就是提供一个限定数据作用域的方式,减少触发compose重组的影响范围,以提升性能。
CompositionLocalProvider(value = LocalRippleTheme provides customRippleTheme) {
Box(modifier = modifierWithClip.clickable { }, contentAlignment = Alignment.Center) {
Text(text = "自定义RippleTheme的演示", color = Color.White)
}
}
}
}
//自定义的indication,简单演示按压效果
@Composable
private fun UI_Indication() {
val indicationA = CustomIndication(Color.Yellow, .4f)
val indicationB = CustomIndication(Color.Cyan, .4f, drawRoundedShape = false)
Column(
Modifier
.fillMaxWidth()
.padding(8.dp)
) {
Box(
modifier = Modifier
.fillMaxWidth()
.height(40.dp)
.shadow(elevation = 2.dp, shape = RoundedCornerShape(16.dp), clip = true)
.background(Color(0xffBDBDBD))
.clickable(
indication = indicationA,
interactionSource = MutableInteractionSource()
) { }, contentAlignment = Alignment.Center
) {
Text(text = "自定义indication的演示", color = Color.White)
}
Spacer(modifier = Modifier.height(10.dp))
Box(
modifier = Modifier
.fillMaxWidth()
.height(40.dp)
.background(Color(0xffBDBDBD), shape = RoundedCornerShape(16.dp))
.clickable(
indication = indicationB,
interactionSource = MutableInteractionSource()
) { }, contentAlignment = Alignment.Center
) {
Text(text = "自定义indication无边界", color = Color.Black)
}
}
}
//自定义的indication
private class CustomIndication(
private val pressColor: Color,//按压后的颜色
private val alpha: Float,//透明度
private val drawRoundedShape: Boolean = true,//是否绘制ripple在区域内
private val cornerRadius: CornerRadius = CornerRadius(16f, 16f),//圆角
) : Indication {
private inner class DefaultIndicationInstance(private val isPressed: State<Boolean>) :
IndicationInstance {
override fun ContentDrawScope.drawIndication() {
//作用对象的compose容器,内容要绘制
drawContent()
when {
//表示 有触压动作时候才会有的逻辑
isPressed.value -> {
if (drawRoundedShape) {
//根据设置,绘制
drawRoundRect(
cornerRadius = cornerRadius,
color = pressColor.copy(
alpha = alpha
), size = size
)
} else {
//绘制一个大大的圆,根据size的宽度,作为半径的圆
drawCircle(
radius = size.width,
color = pressColor.copy(
alpha = alpha
)
)
}
}
}
}
}
@Composable
override fun rememberUpdatedInstance(interactionSource: InteractionSource): IndicationInstance {
//collectIsPressedAsState 按钮的交互状态,
val isPressed = interactionSource.collectIsPressedAsState()
return remember(interactionSource) {
DefaultIndicationInstance(isPressed)
}
}
}
//endregion
//region 交互相关
@Composable
private fun UI_Interaction() {
Title_Desc_Text(desc = "collectIsPressedAsState,感知按钮的触压事件")
val btnInteraction = remember { MutableInteractionSource() }
//感知按压相关事件,类似的还有hover,dragged,focus
val isPressed by btnInteraction.collectIsPressedAsState()
Button(onClick = { }, modifier = Modifier.fillMaxWidth(), interactionSource = btnInteraction) {
Text(text = if (isPressed) "按下⛰️" else "未🈚️🍐按压")
}
//通过clickable的interactionSource感知交互事件
Spacer(modifier = Modifier.height(8.dp))
val boxInteraction = remember { MutableInteractionSource() }
LaunchedEffect(key1 = null) {
//这里启动一个协程,来搜集box的交互事件,interactions是个flow
boxInteraction.interactions
//这里可以看到,搜集到三种状态,press,release,和cancel;
.onEach { println("📦:boxInteraction,$it") }
.launchIn(this)
}
//注意点击,按压 按钮时候,看log输出事件
Box(
modifier = Modifier
.fillMaxWidth()
.height(40.dp)
.padding(horizontal = 8.dp)
.background(
Color.LightGray,
RoundedCornerShape(8.dp)
)
.clickable(
interactionSource = boxInteraction,
indication = rememberRipple(),
onClick = {}),
contentAlignment = Alignment.Center
) {
Text(text = "点击并搜集交互状态")
}
Title_Desc_Text(desc = "按压状态实现动画交互的按钮")
Column(Modifier.fillMaxWidth(), horizontalAlignment = Alignment.CenterHorizontally) {
PressIconButton(
onClick = { },
icon = { Icon(imageVector = Icons.Filled.ShoppingCart, contentDescription = null) },
text = {
Text(
text = "点击添加"
)
})
ElasticButton(modifier = Modifier.shadow(
8.dp, RoundedCornerShape(10.dp)
), onClick = { }) {
Surface(shape = RoundedCornerShape(10.dp)) {
Text(
text = "缩放效果的按钮",
fontSize = 14.sp,
modifier = Modifier
.background(Color(0xffFFA726))
.padding(10.dp),
color = Color.White
)
}
}
}
Title_Desc_Text(desc = "多控件UI共用交互interactionSource")
ShareInteractionSource()
}
/**
* 简单封装的一个按钮,按下状态下,会显示icon,松开后,仅有文字。
*/
@Composable
private fun PressIconButton(
onClick: () -> Unit,
icon: @Composable () -> Unit,
text: @Composable () -> Unit,
modifier: Modifier = Modifier,
interactionSource: MutableInteractionSource = remember { MutableInteractionSource() },
) {
//按压状态
val isPressed by interactionSource.collectIsPressedAsState()
Button(onClick = onClick, modifier, interactionSource = interactionSource) {
//compose的动画,这里会根据按压状态来控制显示隐藏
AnimatedVisibility(visible = isPressed) {
if (isPressed) {
Row {
icon()
Spacer(modifier = Modifier.size(ButtonDefaults.IconSpacing))
}
}
}
text()
}
}
/**
* 简单封装的缩放按压效果的按钮
*/
@Composable
private fun ElasticButton(
modifier: Modifier = Modifier,
onClick: () -> Unit,
indication: Indication? = null,
interactionSource: MutableInteractionSource = remember { MutableInteractionSource() },
content: @Composable () -> Unit,
) {
val isPressed by interactionSource.collectIsPressedAsState()
Box(
modifier = Modifier
.graphicsLayer {
//根据按压状态,缩放按钮
scaleX = if (isPressed) .95f else 1f
scaleY = if (isPressed) .95f else 1f
}
.then(
modifier.clickable(
interactionSource = interactionSource,
indication = indication
) { onClick() })
) { content() }
}
@Composable
private fun ShareInteractionSource() {
val context = LocalContext.current
// 外面的交互interactionSource和内部的共用,然后外部点击会触发UI交互;⚠️注意:共享的是UI交互,而不是click事件。
val interactionSource = remember { MutableInteractionSource() }
val coroutineScope = rememberCoroutineScope()
Column(
modifier = Modifier
.fillMaxWidth()
.padding(8.dp)
) {
Column(
modifier = Modifier
.fillMaxWidth()
.shadow(2.dp, RoundedCornerShape(8.dp), clip = true)
.background(color = Color(0xffFFA726))
.clickable {
//这段协程代码,为了演示 同步交互UI效果,这里故意延迟了按钮的释放
coroutineScope.launch {
val press = PressInteraction.Press(Offset.Zero)
interactionSource.emit(
press
)
delay(300)
interactionSource.emit(
PressInteraction.Release(press)
)
}
Toast
.makeText(context, "点击了外部", Toast.LENGTH_SHORT)
.show()
}
.padding(8.dp)
) {
Text("Outer Composable", color = Color.White)
Column(
modifier = Modifier
.padding(8.dp)
.fillMaxWidth()
.shadow(2.dp, RoundedCornerShape(8.dp), clip = true)
.background(color = Color.Cyan)
.clickable(
interactionSource = interactionSource,
indication = rememberRipple(),
onClick = {
Toast
.makeText(context, "内部click点击", Toast.LENGTH_SHORT)
.show()
}
)
.padding(8.dp)
) {
Text(
"Inner Composable",
color = Color.White,
modifier = Modifier.fillMaxWidth()
)
}
}
}
}
//endregion
@Preview(showBackground = true, backgroundColor = 0xFFFFFFFF)
@Composable
private fun PreviewClickable() {
Clickable_Screen()
}
| 0
|
Kotlin
|
111
| 627
|
2c24cb98da0b1731279fd9c1473c1aa229198fa7
| 17,332
|
android-jetpack-demo
|
Apache License 2.0
|
composeApp/src/androidMain/kotlin/co/moregpt/ai/utils/SuperUtils.kt
|
obelieve
| 766,344,687
| false
|
{"Kotlin": 222990, "Swift": 594, "HTML": 304}
|
package co.moregpt.ai.utils
import android.content.Context
import android.content.Intent
import android.media.MediaDrm
import android.os.Build
import android.util.Base64
import java.util.*
/**
* @desc content
* Created by zxy
**/
object SuperUtils {
fun getDeviceInfo():String{
return Build.MANUFACTURER+"-"+Build.MODEL
}
fun getDeviceUUId(): String? {
val wideVineUuid = UUID(-0x121074568629b532L, -0x5c37d8232ae2de13L)
var wvDrm: MediaDrm? = null
return try {
wvDrm = MediaDrm(wideVineUuid)
val wideVineId = wvDrm.getPropertyByteArray(MediaDrm.PROPERTY_DEVICE_UNIQUE_ID)
//optional encoding to convert the array in string.
Base64.encodeToString(wideVineId, Base64.NO_WRAP)
} catch (e: Exception) {
e.printStackTrace()
null
} finally {
if (wvDrm != null) {
try{
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {
wvDrm.close()
} else {
wvDrm.release()
}
}catch (e:Exception){
e.printStackTrace()
}
}
}
}
fun share(context: Context,message: String){
val sendIntent = Intent()
sendIntent.action = Intent.ACTION_SEND
sendIntent.putExtra(Intent.EXTRA_TEXT, message)
sendIntent.putExtra(Intent.EXTRA_TITLE, "")
sendIntent.type = "text/plain"
val shareIntent = Intent.createChooser(sendIntent, null)
shareIntent.flags = Intent.FLAG_ACTIVITY_NEW_TASK
context.startActivity(shareIntent)
}
}
| 0
|
Kotlin
|
0
| 1
|
e6c7b646635414fac4433a0fc07c44e27db24227
| 1,713
|
compose-multiplatform-moregpt
|
MIT License
|
app/src/main/java/com/juangm/randomusers/presentation/ui/extensions/ImageViewExtension.kt
|
juangranadilla
| 182,758,014
| false
| null |
package com.juangm.randomusers.presentation.ui.extensions
import android.graphics.Bitmap
import android.widget.ImageView
import androidx.core.graphics.drawable.RoundedBitmapDrawableFactory
import com.bumptech.glide.Glide
import com.bumptech.glide.request.RequestOptions
import com.bumptech.glide.request.target.BitmapImageViewTarget
fun <T> ImageView.circleImage(uri: T, borderSize: Float, borderColor: Int, placeHolder: Int) {
Glide.with(context)
.asBitmap()
.load(uri)
.error(placeHolder)
.apply(RequestOptions.circleCropTransform())
.into(object : BitmapImageViewTarget(this) {
override fun setResource(resource: Bitmap?) {
val circularBitmapDrawable = RoundedBitmapDrawableFactory.create(
context.resources,
if (borderSize > 0) {
resource?.addBorder(borderSize, borderColor)
} else {
resource
}
)
circularBitmapDrawable.isCircular = true
setImageDrawable(circularBitmapDrawable)
}
})
}
| 0
|
Kotlin
|
3
| 5
|
37ed5c2176b97845f6c3cb866cf1fb40f7da82b4
| 1,159
|
RandomUsers
|
Apache License 2.0
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.