path
stringlengths 4
280
| owner
stringlengths 2
39
| repo_id
int64 21.1k
879M
| is_fork
bool 2
classes | languages_distribution
stringlengths 13
1.95k
⌀ | content
stringlengths 7
482k
| issues
int64 0
13.9k
| main_language
stringclasses 121
values | forks
stringlengths 1
5
| stars
int64 0
111k
| commit_sha
stringlengths 40
40
| size
int64 7
482k
| name
stringlengths 1
100
| license
stringclasses 93
values |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|
src/main/kotlin/com/enhe/endpoint/consts/DagpModule.kt | dingshichen | 577,605,646 | false | {"Kotlin": 215117, "Java": 29200} | // @author ding.shichen
// @email [email protected]
// @date 2024-01-20
package com.enhe.endpoint.consts
enum class DagpModule(
val abbreviation: String,
) {
ASSESSMENT("asm"),
ASSET("ast"),
MASTER("mst"),
METADATA("mdm"),
MODEL2("mdl"),
QUALITY("dqm"),
REQUIREMENT("req"),
STANDARD("std"),
PROFILE("prf"),
SYSTEM("sys"),
;
fun tableNamePrefix(): String {
return abbreviation + "_"
}
}
fun ofDagpModule(value: String): DagpModule? {
return DagpModule.entries.find { it.name.equals(value, true) }
} | 0 | Kotlin | 2 | 3 | 23656796abebb24459ac9d20e415f47663cef6ee | 580 | enhe-endpoint | Apache License 2.0 |
presentation/src/test/java/com/sanogueralorenzo/presentation/model/UserItemMapperTest.kt | mararosa | 279,106,439 | false | null | @file:Suppress("IllegalIdentifier")
package com.sanogueralorenzo.presentation.model
import com.sanogueralorenzo.presentation.createUser
import org.junit.Assert.assertTrue
import org.junit.Before
import org.junit.Test
class UserItemMapperTest {
private lateinit var mapper: UserItemMapper
@Before
fun setUp() {
mapper = UserItemMapper(addressItemMapper = AddressItemMapper(LatLngMapper()), companyItemMapper = CompanyItemMapper())
}
@Test
fun `map entity to domain`() {
// given
val user = createUser()
// when
val userItem = mapper.mapToPresentation(user)
// then
assertTrue(userItem.id == user.id)
assertTrue(userItem.name == user.name)
assertTrue(userItem.username == user.username)
assertTrue(userItem.email == user.email)
assertTrue(userItem.phone == user.phone)
assertTrue(userItem.website == user.website)
assertTrue(userItem.addressItem.street == user.address.street)
assertTrue(userItem.addressItem.suite == user.address.suite)
assertTrue(userItem.addressItem.city == user.address.city)
assertTrue(userItem.addressItem.zipcode == user.address.zipcode)
assertTrue(userItem.addressItem.latLng.latitude.toString() == user.address.geo.lat)
assertTrue(userItem.addressItem.latLng.longitude.toString() == user.address.geo.lng)
assertTrue(userItem.companyItem.name == user.name)
assertTrue(userItem.companyItem.catchPhrase == user.company.catchPhrase)
assertTrue(userItem.companyItem.bs == user.company.bs)
}
}
| 0 | null | 0 | 1 | c5f5c171a1381ecc7641a65761e06f794db359e4 | 1,619 | Android-Kotlin-Clean-Architecture | Apache License 2.0 |
presentation/src/test/java/com/sanogueralorenzo/presentation/model/UserItemMapperTest.kt | mararosa | 279,106,439 | false | null | @file:Suppress("IllegalIdentifier")
package com.sanogueralorenzo.presentation.model
import com.sanogueralorenzo.presentation.createUser
import org.junit.Assert.assertTrue
import org.junit.Before
import org.junit.Test
class UserItemMapperTest {
private lateinit var mapper: UserItemMapper
@Before
fun setUp() {
mapper = UserItemMapper(addressItemMapper = AddressItemMapper(LatLngMapper()), companyItemMapper = CompanyItemMapper())
}
@Test
fun `map entity to domain`() {
// given
val user = createUser()
// when
val userItem = mapper.mapToPresentation(user)
// then
assertTrue(userItem.id == user.id)
assertTrue(userItem.name == user.name)
assertTrue(userItem.username == user.username)
assertTrue(userItem.email == user.email)
assertTrue(userItem.phone == user.phone)
assertTrue(userItem.website == user.website)
assertTrue(userItem.addressItem.street == user.address.street)
assertTrue(userItem.addressItem.suite == user.address.suite)
assertTrue(userItem.addressItem.city == user.address.city)
assertTrue(userItem.addressItem.zipcode == user.address.zipcode)
assertTrue(userItem.addressItem.latLng.latitude.toString() == user.address.geo.lat)
assertTrue(userItem.addressItem.latLng.longitude.toString() == user.address.geo.lng)
assertTrue(userItem.companyItem.name == user.name)
assertTrue(userItem.companyItem.catchPhrase == user.company.catchPhrase)
assertTrue(userItem.companyItem.bs == user.company.bs)
}
}
| 0 | null | 0 | 1 | c5f5c171a1381ecc7641a65761e06f794db359e4 | 1,619 | Android-Kotlin-Clean-Architecture | Apache License 2.0 |
src/main/kotlin/online/hudacek/fxradio/ui/menu/AboutMenu.kt | Joseph5610 | 255,174,080 | false | null | /*
* Copyright 2020 FXRadio by hudacek.online
*
* 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 online.hudacek.fxradio.ui.menu
import javafx.scene.control.MenuItem
import online.hudacek.fxradio.FxRadio
import online.hudacek.fxradio.util.Modal
import online.hudacek.fxradio.util.open
import tornadofx.action
import tornadofx.get
class AboutMenu : BaseMenu(FxRadio.appName) {
val aboutMainItems: List<MenuItem>
get() = listOf(
item(messages["menu.app.about"] + " " + FxRadio.appName) {
action {
Modal.About.open()
}
},
item(messages["menu.app.server"]) {
action {
Modal.Servers.open()
}
}
)
override val menuItems = mutableListOf<MenuItem>().apply {
addAll(aboutMainItems)
addAll(listOf(
separator(),
item(messages["menu.app.quit"]) {
action {
primaryStage.close()
}
}
))
}
}
| 3 | Kotlin | 1 | 2 | ba3414e1ea4c5851564d9a69510cab8c1a8ce8c7 | 1,684 | fxradio-main | Apache License 2.0 |
src/main/kotlin/kext/ExtensionScope.kt | MeteorLite | 477,212,168 | false | null |
package kext
/**
* The different strategies that can be used each time an extension is
* requested using the [ExtensionManager].
*/
enum class ExtensionScope {
/** Keep a single instance */
GLOBAL,
/** Create a new instance each time */
LOCAL,
/** Keep a single instance per session */
SESSION
} | 0 | Kotlin | 1 | 0 | 4eb933b3feb41ea1cba16dfad8fb78e3bcb69b62 | 329 | Kext | MIT License |
src/Day07.kt | li-xin-yi | 573,617,763 | false | null | import java.util.*
class Dir {
val children = mutableMapOf<String, Dir>()
var size = -1
}
fun main() {
fun getRootDir(input: List<String>): Dir {
val root = Dir()
val stack = Stack<Dir>()
var cur: Dir = root
for (line in input) {
val words = line.split(" ")
if (words[0] == "$" && words[1] == "cd") {
when (words[2]) {
"/" -> {
stack.clear()
stack.push(root)
}
".." -> stack.pop()
else -> stack.push(cur.children[words[2]]!!)
}
cur = stack.peek()
} else if (words[0] != "$") {
if (cur.children.containsKey(words[1])) continue
cur.children[words[1]] = Dir()
if (words[0] != "dir") {
cur.children[words[1]]!!.size = words[0].toInt()
}
}
}
return root
}
fun solvePart1(input: List<String>): Int {
var res = 0
val root = getRootDir(input)
fun dfs(root: Dir): Int {
if (root.size != -1) return root.size
root.size = root.children.values.sumOf { dfs(it) }
if (root.size <= 100000) res += root.size
return root.size
}
dfs(root)
return res
}
fun solvePart2(input: List<String>): Int {
val root = getRootDir(input)
val lst = mutableListOf<Int>()
fun dfs(root: Dir): Int {
if (root.size != -1) return root.size
root.size = root.children.values.sumOf { dfs(it) }
lst.add(root.size)
return root.size
}
val target = 30000000 - (70000000 - dfs(root))
return lst.filter { it >= target }.minOrNull()!!
}
val testInput = readInput("input/Day07_test")
check(solvePart1(testInput) == 95437)
check(solvePart2(testInput) == 24933642)
val input = readInput("input/Day07_input")
println(solvePart1(input))
println(solvePart2(input))
} | 0 | Kotlin | 0 | 1 | fb18bb7e462b8b415875a82c5c69962d254c8255 | 2,132 | AoC-2022-kotlin | Apache License 2.0 |
src/main/java/net/tinzin/tesser/TesserClient.kt | elytra | 146,140,180 | false | {"Java": 8688, "Kotlin": 6102} | package net.tinzin.tesser
import net.minecraft.client.renderer.entity.Render
import net.minecraft.client.renderer.entity.RenderManager
import net.minecraft.entity.Entity
import net.tinzin.tesser.entity.EntityTesserCrystal
import net.tinzin.tesser.entity.RenderTesserCrystal
import org.dimdev.rift.listener.client.EntityRendererAdder
class TesserClient : EntityRendererAdder {
override fun addEntityRenderers(entityRenderMap: MutableMap<Class<out Entity>, Render<out Entity>>, renderManager: RenderManager?) {
entityRenderMap[EntityTesserCrystal::class.java] = RenderTesserCrystal(renderManager)
}
} | 0 | Java | 0 | 0 | 6a0f525a3ace89a267cc14d6c17c778637e45d53 | 616 | Tesser | MIT License |
src/main/kotlin/io/github/dockyardmc/protocol/packets/play/clientbound/ClientboundSetHeadYawPacket.kt | DockyardMC | 650,731,309 | false | null | package io.github.dockyardmc.protocol.packets.play.clientbound
import io.github.dockyardmc.annotations.ClientboundPacketInfo
import io.github.dockyardmc.annotations.WikiVGEntry
import io.github.dockyardmc.entities.Entity
import io.github.dockyardmc.extentions.writeVarInt
import io.github.dockyardmc.protocol.packets.ClientboundPacket
import io.github.dockyardmc.protocol.packets.ProtocolState
@WikiVGEntry("Set Head Rotation")
@ClientboundPacketInfo(0x48, ProtocolState.PLAY)
class ClientboundSetHeadYawPacket(entity: Entity): ClientboundPacket() {
init {
data.writeVarInt(entity.entityId)
data.writeByte((entity.location.yaw * 256 / 360).toInt())
}
} | 9 | null | 5 | 45 | 660256d52c12e5b3632103ee93aaafe5ce9b9db3 | 680 | Dockyard | MIT License |
library/src/main/java/com/camerash/filterdrawer/ParentItem.kt | Camerash | 150,241,216 | false | null | package com.camerash.filterdrawer
import android.support.annotation.ColorRes
import android.support.v4.content.ContextCompat
import android.support.v7.widget.DividerItemDecoration
import android.support.v7.widget.LinearLayoutManager
import android.support.v7.widget.RecyclerView
import android.view.View
import android.widget.LinearLayout
import net.cachapa.expandablelayout.ExpandableLayout
/**
* Abstract class for base implementation of ParentItem used in FilterDrawer
*
* @author Camerash
* @see FilterDrawer
*/
abstract class ParentItem {
/**
* Supply the drawable icon resource for the ParentItem
*
* @return The icon drawable resource
*/
abstract fun getParentIcon(): Int
/**
* Supply title for the ParentItem
*
* @return Title of ChildItem
*/
abstract fun getParentTitle(): String
/**
* Supply the layout resource for the customization of ParentItem
*
* @return The layout resource used by ParentItem
*/
abstract fun getLayoutRes(): Int
/**
* Supply the root linear layout id for the customization of ParentItem
*
* @return Id of root linear layout
*/
abstract fun getRootLinearLayoutId(): Int
/**
* Supply the view id who is responsible for receiving
* the onClick event for toggling expansion of ParentItem.
*
* Used for the customization of ParentItem
* @return Id of the view
*/
abstract fun getToggleExpandOnClickViewId(): Int
/**
* Supply the list of ChildItem under this ParentItem
*
* @return List of ChileItem under this ParentItem
* @see ChildItem
*/
abstract fun getChildCollection(): List<ChildItem>
/**
* Supply the ViewHolder used by the ParentItem
*
* @return The view holder
*/
abstract fun getViewHolder(v: View): ViewHolder
/**
* Supply the color resource used in title text
* when none of the ChildItems under this ParentItem are selected
*
* @return The color resource
*/
abstract fun getDefaultTextColorRes(): Int
/**
* Supply the color resource used in title text
* when one or more ChildItems under this ParentItem are selected
*
* @return The color resource
*/
abstract fun getSelectedTextColorRes(): Int
/**
* Supply the color resource of icon used
* when none of the ChildItems under this ParentItem are selected
*
* @return The color resource
*/
abstract fun getDefaultIconColorRes(): Int
/**
* Supply the color resource of icon used
* when one or more ChildItems under this ParentItem are selected
*
* @return The color resource
*/
abstract fun getSelectedIconColorRes(): Int
/**
* Supply the option of whether the ChildItems of this ParentItem
* can be multi-selected
*
* @return Whether multi-selected ChildItems are allowed
*/
abstract fun allowSelectMultiple(): Boolean
/**
* Base implementation of the ViewHolder of ParentItem used in the FilterDrawer's RecyclerView
*
* @param v View used in constructing ViewHolder
* @see ParentAdapter
*/
abstract inner class ViewHolder(v: View) : RecyclerView.ViewHolder(v) {
/**
* The root LinearLayout to add our ExpandableLayout into
*/
private var root: LinearLayout
/**
* The view responsible for receiving onClick event to toggle expansion of the ParentItem
*/
private var headerView: View = itemView.findViewById(getToggleExpandOnClickViewId())
/**
* The ExpandableLayout which host the child RecyclerView
*/
var expandableView: ExpandableLayout = ExpandableLayout(v.context)
/**
* The ChildItem RecyclerView
*/
var recyclerView: RecyclerView = RecyclerView(v.context)
init {
try {
root = itemView.findViewById(getRootLinearLayoutId())
} catch (e: ClassCastException) {
throw IllegalArgumentException("Please use LinearLayout as the root layout")
}
expandableView.addView(recyclerView)
headerView.setOnClickListener { expandableView.toggle() }
root.addView(expandableView, root.childCount)
expandableView.collapse()
expandableView.orientation = ExpandableLayout.VERTICAL
}
/**
* Called when ViewHolder binds with ParentItem
*
* @param parent The ParentItem to bind with ViewHolder
* @param parentViewPool The RecycledViewPool to be set for the ChildItem RecyclerView for better ViewHolder re-usability
* @param childAdapterList The list of ChildAdapter in this FilterDrawer
* @param callback Callback to ParentAdapter when the related ChildAdapter's selection changes.
*/
@Suppress("UNCHECKED_CAST")
internal fun <Parent, Child> bindView(parent: Parent, parentViewPool: RecyclerView.RecycledViewPool, childAdapterList: ArrayList<ChildAdapter<Parent, Child>>, callback: (Set<Child>, Boolean) -> Unit)
where Parent : ParentItem, Child : ChildItem {
bindView(parent)
// Construct filter recycler
val llm = LinearLayoutManager(itemView.context)
val did = DividerItemDecoration(itemView.context, llm.orientation)
val adapter = ChildAdapter(parent, parent.getChildCollection() as List<Child>) { childItem, selected -> callback(childItem, selected) }
recyclerView.setRecycledViewPool(parentViewPool)
recyclerView.layoutManager = llm
recyclerView.addItemDecoration(did)
recyclerView.adapter = adapter
recyclerView.isNestedScrollingEnabled = false
childAdapterList.add(adapterPosition, adapter)
}
/**
* Called when ViewHolder binds with ParentItem
*
* @param parent The ParentItem to bind with ViewHolder
*/
abstract fun bindView(parent: ParentItem)
/**
* Called when one of the ChildItem is selected
*
* @param parent The ParentItem that bound with this ViewHolder
* @param childSet The currently selected set of ChildItem
*/
abstract fun onChildSelect(parent: ParentItem, childSet: Set<ChildItem>)
/**
* Called when one of the ChildItem is deselected
*
* @param parent The ParentItem that bound with this ViewHolder
* @param childSet The currently selected set of ChildItem
*/
abstract fun onChildDeselect(parent: ParentItem, childSet: Set<ChildItem>)
/**
* Called when the FilterDrawer resets
*
* @param parent The ParentItem that bound with this ViewHolder
*/
abstract fun onReset(parent: ParentItem)
/**
* Helper method for Supply color from color resource
*
* @param color The color resource
* @return The color
*/
fun getColor(@ColorRes color: Int) = ContextCompat.getColor(itemView.context, color)
}
} | 1 | Kotlin | 2 | 17 | 4d79b90fedc6135255e325b9b16954dafe0a9e0f | 7,244 | FilterDrawer | MIT License |
apps/shared/data/src/commonMain/kotlin/com/baptistecarlier/am24/shared/data/repository/KtorGoatRepository.kt | BapNesS | 781,361,632 | false | null | package com.baptistecarlier.am24.shared.data.repository
import com.baptistecarlier.am24.shared.data.mapper.GoatDetailMapper
import com.baptistecarlier.am24.shared.data.mapper.GoatTeaserMapper
import com.baptistecarlier.am24.shared.data.model.GoatDetailDto
import com.baptistecarlier.am24.shared.data.model.GoatTeaserDto
import com.baptistecarlier.am24.shared.data.network.KtorClient
import com.baptistecarlier.am24.shared.domain.model.GoatDetail
import com.baptistecarlier.am24.shared.domain.model.GoatTeaser
import com.baptistecarlier.am24.shared.domain.repository.GoatRepository
import io.ktor.client.call.body
import io.ktor.client.request.get
class KtorGoatRepository(
private val ktorClient: KtorClient
) : GoatRepository {
// URLs
private val allUrl =
"https://bapness.github.io/goat-multiplatform/fakeApi/goat/all.json"
private fun detailUrl(id: String) =
"https://bapness.github.io/goat-multiplatform/fakeApi/goat/$id/details.json"
// Mappers
private val goatTeaserMapper = GoatTeaserMapper()
private val goatDetailMapper = GoatDetailMapper()
// Implementations
override suspend fun getAllGoat(): List<GoatTeaser>? = runCatching {
ktorClient.httpClient.get(allUrl)
.body<List<GoatTeaserDto>>()
.mapNotNull(goatTeaserMapper::mapOrNull)
}.getOrNull()
override suspend fun getGoat(id: String): GoatDetail? = runCatching {
ktorClient.httpClient.get(detailUrl((id)))
.body<GoatDetailDto>()
.let(goatDetailMapper::mapOrNull)
}.getOrNull()
}
| 0 | null | 0 | 3 | 8a07812369181db3a041fe7c9f78a99bbc8ab717 | 1,578 | goat-multiplatform | Apache License 2.0 |
synergy-module-proxy-mcbe/src/main/kotlin/com/valaphee/synergy/proxy/mcbe/service/OAuth20Authenticator.kt | valaphee | 476,972,429 | false | {"Kotlin": 278748, "C++": 70332, "C": 3487, "Java": 2209, "JavaScript": 1482, "Shell": 397, "Makefile": 149} | /*
* Copyright (c) 2022, Valaphee.
*
* 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.valaphee.synergy.proxy.mcbe.service
import com.valaphee.synergy.HttpClient
import io.ktor.client.call.body
import io.ktor.client.request.forms.submitForm
import io.ktor.http.HttpStatusCode
import io.ktor.http.Parameters
import kotlinx.coroutines.delay
import java.awt.Desktop
import java.awt.Toolkit
import java.awt.datatransfer.StringSelection
import java.net.URI
/**
* @author <NAME>
*/
class OAuth20Authenticator {
private var oauth20Token: OAuth20Token? = null
val accessToken get() = oauth20Token?.accessToken
suspend fun run() {
val oauth20ConnectRequest = HttpClient.submitForm("https://login.live.com/oauth20_connect.srf", Parameters.build {
append("client_id", "0000000048183522")
append("scope", "service::user.auth.xboxlive.com::MBI_SSL")
append("response_type", "device_code")
})
if (oauth20ConnectRequest.status == HttpStatusCode.OK) {
val oauth20Connect = oauth20ConnectRequest.body<OAuth20Connect>()
Desktop.getDesktop().browse(URI(oauth20Connect.verificationUri))
val userCode = StringSelection(oauth20Connect.userCode)
Toolkit.getDefaultToolkit().systemClipboard.setContents(userCode, userCode)
var i = 0
while (i++ < oauth20Connect.expiresIn / oauth20Connect.interval) {
val oauth20TokenRequest = HttpClient.submitForm("https://login.live.com/oauth20_token.srf", Parameters.build {
append("client_id", "0000000048183522")
append("grant_type", "urn:ietf:params:oauth:grant-type:device_code")
append("device_code", oauth20Connect.deviceCode)
})
if (oauth20TokenRequest.status == HttpStatusCode.OK) {
oauth20Token = oauth20TokenRequest.body()
break
}
delay(oauth20Connect.interval * 1000L)
}
}
}
}
| 0 | Kotlin | 0 | 1 | 614cc5504d335561f5d57cd40d7191d054ae9492 | 2,580 | synergy | Apache License 2.0 |
vck/src/commonMain/kotlin/at/asitplus/wallet/lib/iso/MobileSecurityObject.kt | a-sit-plus | 602,578,639 | false | {"Kotlin": 1076316} | @file:OptIn(ExperimentalSerializationApi::class)
package at.asitplus.wallet.lib.iso
import at.asitplus.KmmResult.Companion.wrap
import at.asitplus.signum.indispensable.cosef.io.ByteStringWrapper
import at.asitplus.signum.indispensable.cosef.io.ByteStringWrapperSerializer
import kotlinx.serialization.*
/**
* Part of the ISO/IEC 18013-5:2021 standard: Data structure for MSO (9.1.2.4)
*/
@Serializable
data class MobileSecurityObject(
@SerialName("version")
val version: String,
@SerialName("digestAlgorithm")
val digestAlgorithm: String,
@SerialName("valueDigests")
val valueDigests: Map<String, ValueDigestList>,
@SerialName("deviceKeyInfo")
val deviceKeyInfo: DeviceKeyInfo,
@SerialName("docType")
val docType: String,
@SerialName("validityInfo")
val validityInfo: ValidityInfo,
) {
fun serialize() = vckCborSerializer.encodeToByteArray(this)
/**
* Ensures serialization of this structure in [IssuerSigned.issuerAuth]:
* ```
* IssuerAuth = COSE_Sign1 ; The payload is MobileSecurityObjectBytes
* MobileSecurityObjectBytes = #6.24(bstr .cbor MobileSecurityObject)
* ```
*
* See ISO/IEC 18013-5:2021, 9.1.2.4 Signing method and structure for MSO
*/
fun serializeForIssuerAuth() = vckCborSerializer.encodeToByteArray(
ByteStringWrapperSerializer(serializer()), ByteStringWrapper(this)
).wrapInCborTag(24)
companion object {
/**
* Deserializes the structure from the [IssuerSigned.issuerAuth] is deserialized:
* ```
* IssuerAuth = COSE_Sign1 ; The payload is MobileSecurityObjectBytes
* MobileSecurityObjectBytes = #6.24(bstr .cbor MobileSecurityObject)
* ```
*
* See ISO/IEC 18013-5:2021, 9.1.2.4 Signing method and structure for MSO
*/
fun deserializeFromIssuerAuth(it: ByteArray) = kotlin.runCatching {
vckCborSerializer.decodeFromByteArray(
ByteStringWrapperSerializer(serializer()),
it.stripCborTag(24)
).value
}.wrap()
fun deserialize(it: ByteArray) = kotlin.runCatching {
vckCborSerializer.decodeFromByteArray<MobileSecurityObject>(it)
}.wrap()
}
}
| 11 | Kotlin | 1 | 22 | 6f29a2ba84aceda63026afcfc8fd6cc0d8ccbb00 | 2,274 | vck | Apache License 2.0 |
services/reddit/src/main/kotlin/io/sweers/catchup/service/reddit/model/RedditSubmission.kt | seerazz | 152,505,983 | true | {"Kotlin": 602518, "Java": 27064, "Shell": 4178, "Python": 1310} | /*
* Copyright (c) 2017 <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 io.sweers.catchup.data.reddit.model
import com.squareup.moshi.Json
import io.sweers.catchup.ui.base.HasStableId
import org.threeten.bp.Instant
abstract class RedditSubmission : RedditObject(), HasStableId {
abstract fun author(): String
@Json(name = "author_flair_text") abstract fun authorFlairText(): String?
@Json(name = "banned_by") abstract fun bannedBy(): String?
abstract fun created(): Instant
@Json(name = "created_utc") abstract fun createdUtc(): Instant
abstract fun gilded(): Int
abstract fun id(): String
abstract fun name(): String
abstract fun saved(): Boolean
abstract fun score(): Int
abstract fun subreddit(): String
abstract fun ups(): Int
override fun stableId(): Long = id().hashCode().toLong()
}
| 0 | Kotlin | 0 | 0 | 7d504ff2451d65cfdcf8abce2b5233af5c9d9e50 | 1,361 | CatchUp-Perf-Kotlin | Apache License 2.0 |
tvShowFeature/src/main/java/com/example/tvshowfeature/seriesList/SeriesScreenType.kt | Bit-Camp-IO | 643,303,285 | false | null | package com.example.tvshowfeature.seriesList
enum class SeriesScreenType(val screenTitle: String) {
OnTheAir("ON The Air"),
NowPlaying("Now Playing"),
TopRated("Top Rated"),
Popular("Popular"),
Similar("Similar"),
Recommended("Recommended"),
Bookmarked("Bookmarked")
}
| 0 | Kotlin | 1 | 2 | 82141ba5d053fe9c3112d1150b226aceb6125a48 | 298 | TMDA-Android | Apache License 2.0 |
tvShowFeature/src/main/java/com/example/tvshowfeature/seriesList/SeriesScreenType.kt | Bit-Camp-IO | 643,303,285 | false | null | package com.example.tvshowfeature.seriesList
enum class SeriesScreenType(val screenTitle: String) {
OnTheAir("ON The Air"),
NowPlaying("Now Playing"),
TopRated("Top Rated"),
Popular("Popular"),
Similar("Similar"),
Recommended("Recommended"),
Bookmarked("Bookmarked")
}
| 0 | Kotlin | 1 | 2 | 82141ba5d053fe9c3112d1150b226aceb6125a48 | 298 | TMDA-Android | Apache License 2.0 |
dependencies/src/main/kotlin/com/project/picpicker/helper/TomlHelper.kt | dev-darck | 499,210,154 | false | null | package com.project.picpicker.helper
import com.project.picpicker.checker.model.TomlLibVersion
import com.project.picpicker.checker.model.Version
import com.project.picpicker.depToml
import com.project.picpicker.safeFindLibrary
import com.project.picpicker.safeFindVersion
import org.gradle.api.Project
class TomlHelper(val project: Project) {
private val libToml = project.rootDir.walk().maxDepth(2).find { it.name.contains(TOML_VERSION) }
private val contentToml = lazy { libToml?.inputStream()?.bufferedReader()?.use { it.readText() } }
val listLibrary = project.depToml.libraryAliases.map {
project.depToml.safeFindLibrary(it).get()
}
fun findVersion(name: String): String = project.depToml.safeFindVersion(name).displayName
fun findLibrary(name: String) = project.depToml.findLibrary(name).orElseGet {
null
}?.get()
fun currentTomlLib(module: String): String? {
val result = contentToml.value ?: return null
val startSearch = result.indexOf(LIBRARIES)
val textForSearch = result.subSequence(startSearch + LIBRARIES.length, result.length)
return textForSearch.lines().find { it.contains(module) }?.split(" ")?.first()
}
fun currentTomlVersion(module: String): TomlLibVersion? {
val result = contentToml.value ?: return null
val startSearch = result.indexOf(LIBRARIES)
val textForSearch = result.subSequence(startSearch + LIBRARIES.length, result.length)
val findModule = "module = \"$module\""
val match = textForSearch.lines().find { it.contains(findModule) }
return if (match != null) {
val position = match.indexOf(VERSION) + VERSION.length
val versionName = match.subSequence(position, match.lastIndex).replace("\"".toRegex(), "").trim()
TomlLibVersion(
module,
versionName,
)
} else {
null
}
}
fun writeVersion(libs: List<Version>) {
if (libToml == null) {
println("This file is not found \"$TOML_VERSION\"")
return
}
var result = contentToml.value ?: return
libs.forEach { version ->
println("Update $version")
if (version.newVersion.isNotEmpty() && version.oldVersion.isNotEmpty()) {
result = result.replace(
"${version.tomlVersion.tomlVersion} = \"${version.oldVersion}\"",
"${version.tomlVersion.tomlVersion} = \"${version.newVersion}\""
)
} else {
println("New version or old version is empty")
}
}
libToml.bufferedWriter().use { it.write(result) }
}
companion object {
const val TOML_FILE = "gradle/libs.versions.toml"
private const val TOML_VERSION = "libs.versions.toml"
private const val VERSION = "version.ref = "
private const val LIBRARIES = "[libraries]"
}
}
| 1 | Kotlin | 0 | 0 | d6b0e8f79a8b229f7cec3907547bd05b01af606d | 2,995 | PicPicker | Apache License 2.0 |
lib/src/integrationTest/kotlin/com/lemonappdev/konsist/core/declaration/kofile/KoFileDeclarationTest.kt | LemonAppDev | 621,181,534 | false | {"Kotlin": 4854719, "Python": 17926} | package com.lemonappdev.konsist.core.declaration.kofiledeclaration
import com.lemonappdev.konsist.TestSnippetProvider.getSnippetKoScope
import org.amshove.kluent.shouldBeEqualTo
import org.amshove.kluent.shouldNotBeEqualTo
import org.junit.jupiter.api.Test
class KoFileDeclarationTest {
@Test
fun `file-to-string`() {
// given
val sut = getSnippetFile("file-to-string")
.files
.first()
// then
sut.toString() shouldBeEqualTo sut.path
}
@Test
fun `files-are-equal`() {
// given
val file1 = getSnippetFile("files-are-equal")
.files
.first()
val file2 = getSnippetFile("files-are-equal")
.files
.first()
// then
file1 shouldBeEqualTo file2
}
@Test
fun `files-are-not-equal`() {
// given
val file1 = getSnippetFile("files-are-not-equal")
.files
.first()
val file2 = getSnippetFile("files-are-equal")
.files
.first()
// then
file1 shouldNotBeEqualTo file2
}
@Test
fun `files-with-the-same-hashcode`() {
// given
val file1 = getSnippetFile("files-with-the-same-hashcode")
.files
.first()
val file2 = getSnippetFile("files-with-the-same-hashcode")
.files
.first()
// then
file1.hashCode() shouldBeEqualTo file2.hashCode()
}
@Test
fun `files-with-the-different-hashcode`() {
// given
val file1 = getSnippetFile("files-with-the-different-hashcode")
.files
.first()
val file2 = getSnippetFile("files-with-the-same-hashcode")
.files
.first()
// then
file1.hashCode() shouldNotBeEqualTo file2.hashCode()
}
private fun getSnippetFile(fileName: String) = getSnippetKoScope("core/declaration/kofiledeclaration/snippet/forgeneral/", fileName)
}
| 7 | Kotlin | 26 | 995 | 603d19e179f59445c5f4707c1528a438e4595136 | 2,017 | konsist | Apache License 2.0 |
zircon.jvm/src/test/kotlin/org/hexworks/zircon/internal/component/impl/DefaultComponentTest.kt | smomen | 193,348,171 | true | {"Kotlin": 1393224, "Java": 131288} | package org.hexworks.zircon.internal.component.impl
import org.assertj.core.api.Assertions.assertThat
import org.hexworks.zircon.api.Components
import org.hexworks.zircon.api.Positions
import org.hexworks.zircon.api.Sizes
import org.hexworks.zircon.api.builder.component.LabelBuilder
import org.hexworks.zircon.api.builder.component.PanelBuilder
import org.hexworks.zircon.api.builder.data.TileBuilder
import org.hexworks.zircon.api.builder.graphics.TileGraphicsBuilder
import org.hexworks.zircon.api.component.ColorTheme
import org.hexworks.zircon.api.component.ComponentStyleSet
import org.hexworks.zircon.api.component.Visibility
import org.hexworks.zircon.api.component.data.ComponentMetadata
import org.hexworks.zircon.api.component.data.ComponentState
import org.hexworks.zircon.api.component.renderer.impl.DefaultComponentRenderingStrategy
import org.hexworks.zircon.api.data.Position
import org.hexworks.zircon.api.data.Rect
import org.hexworks.zircon.api.data.Size
import org.hexworks.zircon.api.data.Tile
import org.hexworks.zircon.api.extensions.onMouseEvent
import org.hexworks.zircon.api.uievent.MouseEvent
import org.hexworks.zircon.api.uievent.MouseEventType.*
import org.hexworks.zircon.api.uievent.Processed
import org.hexworks.zircon.api.uievent.UIEventPhase.BUBBLE
import org.hexworks.zircon.api.uievent.UIEventPhase.TARGET
import org.hexworks.zircon.internal.component.InternalContainer
import org.junit.Before
import org.junit.Test
import java.util.concurrent.atomic.AtomicBoolean
@Suppress("MemberVisibilityCanBePrivate")
class DefaultComponentTest : CommonComponentTest<DefaultComponent>() {
override lateinit var target: DefaultComponent
override val expectedComponentStyles: ComponentStyleSet
get() = ComponentStyleSet.empty()
var rendered = false
lateinit var appliedColorTheme: ColorTheme
@Before
override fun setUp() {
componentStub = ComponentStub(DefaultContainerTest.COMPONENT_STUB_POSITION_1x1, Size.create(2, 2))
rendererStub = ComponentRendererStub()
target = object : DefaultComponent(
componentMetadata = ComponentMetadata(
size = DefaultContainerTest.SIZE_4x4,
position = POSITION_2_3,
componentStyleSet = COMPONENT_STYLES,
tileset = TILESET_REX_PAINT_20X20),
renderer = DefaultComponentRenderingStrategy(
decorationRenderers = listOf(),
componentRenderer = rendererStub)) {
override fun render() {
rendered = true
}
override fun applyColorTheme(colorTheme: ColorTheme): ComponentStyleSet {
appliedColorTheme = colorTheme
return ComponentStyleSet.empty()
}
override fun acceptsFocus(): Boolean {
return false
}
}
}
@Test
fun shouldUseTilesetFromComponentWhenTransformingToLayer() {
target.toFlattenedLayers().forEach {
assertThat(it.currentTileset().id).isEqualTo(TILESET_REX_PAINT_20X20.id)
}
}
@Test
fun shouldProperlyApplyStylesOnInit() {
assertThat(target.componentStyleSet.currentState())
.isEqualTo(ComponentState.DEFAULT)
}
@Test
fun shouldProperlySetNewPosition() {
target.moveTo(NEW_POSITION_6x7)
assertThat(target.position).isEqualTo(NEW_POSITION_6x7)
}
@Test
fun shouldContainBoundableWhichIsContained() {
assertThat(target.containsBoundable(Rect.create(POSITION_2x3, SIZE_4x4 - Size.one()))).isTrue()
}
@Test
fun shouldNotContainBoundableWhichIsContained() {
assertThat(target.containsBoundable(Rect.create(POSITION_2x3, SIZE_4x4 + Size.one()))).isFalse()
}
@Test
fun shouldContainPositionWhichIsContained() {
assertThat(target.containsPosition(POSITION_2x3)).isTrue()
}
@Test
fun shouldNotContainPositionWhichIsContained() {
assertThat(target.containsPosition(POSITION_2x3 - Position.offset1x1())).isFalse()
}
@Test
fun shouldProperlyDrawOntoTileGraphic() {
val image = TileGraphicsBuilder.newBuilder()
.withSize(SIZE_4x4 + Size.create(POSITION_2x3.x, POSITION_2x3.y))
.build()
val filler = Tile.defaultTile().withCharacter('f')
target.fill(filler)
target.drawOnto(image, POSITION_2x3)
assertThat(image.getTileAt(POSITION_2x3 - Position.offset1x1()).get())
.isEqualTo(Tile.empty())
target.size.fetchPositions().forEach {
assertThat(image.getTileAt(it + POSITION_2x3).get())
.isEqualTo(filler)
}
}
@Test
fun shouldRenderWhenComponentStyleSetIsSet() {
target.componentStyleSet = ComponentStyleSet.empty()
assertThat(rendered).isTrue()
}
@Test
fun shouldRenderWhenVisibilityIsSet() {
target.visibility = Visibility.Hidden
assertThat(rendered).isTrue()
}
@Test
fun shouldNotifyObserversWhenInputIsEmitted() {
var notified = false
target.onMouseEvent(MOUSE_CLICKED) { _, _ ->
notified = true
Processed
}
target.process(
event = MouseEvent(MOUSE_CLICKED, 1, Position.defaultPosition()),
phase = BUBBLE)
assertThat(notified).isTrue()
}
@Test
fun shouldProperlyCreateSnapshot() {
target.fill(TileBuilder.newBuilder().withCharacter('x').build())
val result = target.createSnapshot()
val cells = result.cells.toList()
assertThat(result.tileset).isEqualTo(target.currentTileset())
assertThat(cells.size).isEqualTo(16)
assertThat(cells.first().position).isEqualTo(POSITION_2x3)
}
@Test
fun shouldProperlyHandleMouseEntered() {
target.mouseEntered(
event = MouseEvent(MOUSE_ENTERED, 1, Position.defaultPosition()),
phase = TARGET)
assertThat(target.componentStyleSet.currentState()).isEqualTo(ComponentState.MOUSE_OVER)
assertThat(rendered).isTrue()
}
@Test
fun shouldProperlyCalculateAbsolutePositionWithDeeplyNestedComponents() {
val rootPos = Position.create(1, 1)
val parentPos = Position.create(2, 1)
val leafPos = Position.create(1, 2)
val root = PanelBuilder.newBuilder()
.withSize(Size.create(10, 10))
.withPosition(rootPos)
.build()
val parent = PanelBuilder.newBuilder()
.withSize(Size.create(7, 7))
.withPosition(parentPos)
.build()
root.addComponent(parent)
val leaf = LabelBuilder.newBuilder()
.withPosition(leafPos)
.withText("foo")
.build()
parent.addComponent(leaf)
assertThat(leaf.absolutePosition).isEqualTo(rootPos + parentPos + leafPos)
}
@Test
fun shouldProperlyFetchByPositionWhenContainsPosition() {
assertThat(target.fetchComponentByPosition(POSITION_2x3).get()).isEqualTo(target)
}
@Test
fun shouldNotFetchByPositionWhenDoesNotContainPosition() {
assertThat(target.fetchComponentByPosition(Position.create(100, 100)).isPresent).isFalse()
}
@Test
fun shouldProperlyListenToMousePress() {
val pressed = AtomicBoolean(false)
target.onMouseEvent(MOUSE_PRESSED) { _, _ ->
pressed.set(true)
Processed
}
target.process(
event = MouseEvent(MOUSE_PRESSED, 1, POSITION_2x3),
phase = BUBBLE)
assertThat(pressed.get()).isTrue()
}
@Test
fun shouldNotListenToMousePressOnOtherComponents() {
// TODO: move this test to component container!
}
@Test
fun shouldProperlyListenToMouseRelease() {
// TODO: move this test to component container!
}
@Test
fun shouldNotListenToMouseReleaseOnOtherComponents() {
// TODO: move this test to component container!
}
@Test
fun shouldProperlyTransformToLayers() {
val result = target.toFlattenedLayers()
assertThat(result).hasSize(1)
assertThat(result.first().size).isEqualTo(target.size)
assertThat(result.first().position).isEqualTo(target.position)
}
@Test
fun shouldBeEqualToItself() {
assertThat(target).isEqualTo(target)
}
@Test
fun shouldProperlyCalculatePathFromRoot() {
val root = RootContainer(
componentMetadata = ComponentMetadata(
position = Positions.defaultPosition(),
size = Sizes.create(100, 100),
tileset = TILESET_REX_PAINT_20X20,
componentStyleSet = ComponentStyleSet.empty()),
renderingStrategy = DefaultComponentRenderingStrategy(NoOpGenericRenderer()))
val parent = Components.panel()
.withSize(50, 50)
.withTileset(TILESET_REX_PAINT_20X20)
.build() as InternalContainer
root.addComponent(parent)
parent.addComponent(target)
assertThat(target.calculatePathFromRoot()).containsExactly(root, parent, target)
}
companion object {
val POSITION_2x3 = Position.create(2, 3)
val NEW_POSITION_6x7 = Position.create(6, 7)
val SIZE_4x4 = Size.create(4, 4)
}
}
| 0 | Kotlin | 0 | 0 | bb1f993f8eca72660cd44da736f1643a351bcb68 | 9,574 | zircon | MIT License |
kotlin/knarch-ios/src/main/kotlin/co/touchlab/multiplatform/architecture/db/sqlite/Functions.kt | MaTriXy | 138,565,162 | true | {"Kotlin": 572638, "C++": 146498, "Groovy": 49894, "C": 39735, "Makefile": 35029, "CMake": 25089, "Swift": 18544, "Objective-C": 1081, "Shell": 102} | /*
* Copyright (c) 2018 Touchlab 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 co.touchlab.multiplatform.architecture.db.sqlite
import co.touchlab.knarch.DefaultSystemContext
import co.touchlab.knarch.SystemContext
import co.touchlab.knarch.io.File
import co.touchlab.multiplatform.architecture.db.DatabaseErrorHandler
var systemContext:SystemContext?=null
/**
* Not pretty, but you know
*/
fun initSystemContext(sc:SystemContext){
systemContext = sc
}
actual fun createOpenHelper(
name:String?,
callback:PlatformSQLiteOpenHelperCallback,
errorHandler: DatabaseErrorHandler?):SQLiteOpenHelper{
if(systemContext == null)
throw NullPointerException("Must call initSystemContext")
return PlatformSQLiteOpenHelper(callback,
systemContext!!,
name,
callback.version,
errorHandler
)
}
actual fun deleteDatabase(path:String):Boolean{
return SQLiteDatabase.deleteDatabase(File(path))
} | 0 | Kotlin | 0 | 0 | fe32ccd009e6b24b47653923cb4a0eeb7c0a2dad | 1,523 | knarch.db | Apache License 2.0 |
lib/src/main/kotlin/org/zecdev/zip321/model/MemoBytes.kt | zecdev | 721,262,710 | false | {"Kotlin": 82025} | import java.nio.charset.Charset
import java.util.Base64
class MemoBytes {
companion object {
const val maxLength: Int = 512
fun fromBase64URL(string: String): MemoBytes {
return string.decodeBase64URL()?.let { MemoBytes(it) } ?: throw MemoError.InvalidBase64URL
}
}
val data: ByteArray
sealed class MemoError(message: String) : RuntimeException(message) {
object MemoTooLong : MemoError("MemoBytes exceeds max length of 512 bytes")
object MemoEmpty : MemoError("MemoBytes can't be initialized with empty bytes")
object InvalidBase64URL : MemoError("MemoBytes can't be initialized with invalid Base64URL")
}
@Throws(MemoError::class)
constructor(data: ByteArray) {
require(data.isNotEmpty()) { throw MemoError.MemoEmpty }
require(data.size <= maxLength) { throw MemoError.MemoTooLong }
this.data = data
}
@Throws(MemoError::class)
constructor(string: String) {
require(string.isNotEmpty()) { throw MemoError.MemoEmpty }
require(string.length <= maxLength) { throw MemoError.MemoTooLong }
this.data = string.encodeToByteArray()
}
fun toBase64URL(): String {
return Base64.getUrlEncoder().encodeToString(data)
.replace("/", "_")
.replace("+", "-")
.replace("=", "")
}
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (javaClass != other?.javaClass) return false
other as MemoBytes
if (!data.contentEquals(other.data)) return false
return true
}
override fun hashCode(): Int {
return 31 * data.contentHashCode()
}
}
fun String.decodeBase64URL(): ByteArray? {
return try {
// Replace Base64URL specific characters
val base64URL = replace('-', '+').replace('_', '/')
// Pad the string with '=' characters to make the length a multiple of 4
val paddedBase64 = base64URL + "=".repeat((4 - base64URL.length % 4) % 4)
// Decode the Base64 string into a byte array
Base64.getDecoder().decode(paddedBase64.toByteArray(Charset.defaultCharset()))
} catch (e: IllegalArgumentException) {
// Handle decoding failure and return null
null
}
}
| 2 | Kotlin | 0 | 2 | 95b2532b1d0b5d1155a704484db32db42c4d1842 | 2,315 | zcash-kotlin-payment-uri | MIT License |
app/src/main/java/com/lai/comicmtc_v2/db/BookDao.kt | laishujie | 213,707,320 | false | null | package com.lai.comicmtc_v2.db
import com.lai.comicmtc_v2.bean.detail.ComicDetailResponse
import org.litepal.LitePal
import org.litepal.extension.findFirst
import java.util.*
/**
*
* @author Lai
*
* @time 2019/10/9 1:34
* @describe describe
*
*/
class BookDao {
/**
* 保存chapter阅读记录
*/
fun saveReadChapter(
comicId: String,
comicName: String,
chapter_id: String,
chapterName: String,
type: String
): Boolean {
val chapter = ReadChapter()
chapter.comicId = comicId
chapter.comicName = comicName
chapter.chapter_id = chapter_id
chapter.chapterName = chapterName
chapter.type = type
return chapter.saveOrUpdate("chapter_id=?",chapter_id)
}
/**
* 找到最近读取的章节
*/
fun findLastReadChapter(comicId: String): ReadChapter? {
return LitePal.where("comicId=?", comicId).findLast(ReadChapter::class.java)
}
/**
*找到所有已读章节
*/
fun finReadChapterList(comicId: String?): List<ReadChapter> {
return LitePal.where("comicId=?", comicId).find(ReadChapter::class.java)
}
/**
* 保存阅读位置
*/
fun saveReadPosition(chapter_id: String, position: Int): Boolean {
LitePal.where("chapter_id=?", chapter_id).find(ReadChapter::class.java)?.apply {
if (this.isNotEmpty()) {
val bean = get(0)
bean.readPosition = position
return bean.save()
}
}
return false
}
fun finReadChapterById(chapter_id: String): ReadChapter? {
LitePal.where("chapter_id=?", chapter_id).find(ReadChapter::class.java)?.apply {
if (this.isNotEmpty()) {
return get(0)
}
}
return null
}
fun saveCollection(
comicBean: ComicDetailResponse.ComicBean,
size: Int,
readPosition: Int
): Boolean {
val collection = ComicCollection()
collection.comicId = comicBean.comic_id
collection.comicName = comicBean.name
collection.coverUrl = comicBean.cover
collection.comicSize = size
collection.readChapterPosition = readPosition
return collection.save()
}
fun findCollection(comicId: String): ComicCollection? {
return LitePal.where("comicId=?", comicId).findFirst<ComicCollection>()
}
fun deleteCollection(comicId: String): Int {
findCollection(comicId)?.apply {
return delete()
}
return 0
}
fun finAllCollection(): List<ComicCollection> {
return LitePal.findAll(ComicCollection::class.java)
}
fun saveHistoryRecord(comicBean: ComicDetailResponse.ComicBean) {
val historyRecord = HistoryRecord()
historyRecord.comicId = comicBean.comic_id
historyRecord.name = comicBean.name
historyRecord.time = Date()
historyRecord.saveOrUpdate("comicId=?", comicBean.comic_id)
}
fun findHistoryRecord(): List<HistoryRecord> {
return LitePal.order("time desc").find(HistoryRecord::class.java)
}
fun deleteHistoryRecord(comicId: String): Int {
return LitePal.where("comicId =? ", comicId).findFirst(HistoryRecord::class.java).delete()
}
} | 3 | Java | 27 | 127 | 32513d4cb73e4be5889e86f49bdf794c5c8ee509 | 3,283 | ComicMTC_v2 | Apache License 2.0 |
app/src/main/java/id/davidpratama/a160419103_ubayaculinary/model/RestaurantDao.kt | daviddprtma | 478,382,125 | false | {"Kotlin": 58724} | package id.davidpratama.a160419103_ubayaculinary.model
import androidx.room.Dao
import androidx.room.Insert
import androidx.room.OnConflictStrategy
import androidx.room.Query
@Dao
interface RestaurantDao {
@Insert(onConflict = OnConflictStrategy.REPLACE)
suspend fun insertAllRestaurant(vararg restaurant: Restaurant)
@Query("SELECT * FROM restaurant")
suspend fun selectAllRestaurant():List<Restaurant>
@Query("SELECT * FROM restaurant WHERE idRestaurant= :id")
suspend fun selectRestaurant(id:Int):Restaurant
} | 0 | Kotlin | 0 | 0 | 58ff0db6049943b09a1b060abc79e8142293c651 | 540 | 160419103_UTS-Advanced-Native-Mobile-Programming_Ubaya-Culinary | Apache License 2.0 |
sampleAppKotlin/src/main/java/com/virtusize/sampleappkotlin/WebViewFragment.kt | virtusize | 173,900,278 | false | {"Kotlin": 433690, "Java": 9310, "Shell": 265} | package com.virtusize.sampleappkotlin
import android.os.Bundle
import android.os.Message
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.webkit.WebChromeClient
import android.webkit.WebResourceRequest
import android.webkit.WebView
import android.webkit.WebViewClient
import androidx.activity.result.contract.ActivityResultContracts
import androidx.fragment.app.DialogFragment
import com.virtusize.android.auth.VirtusizeAuth
import com.virtusize.android.auth.VirtusizeWebView
import com.virtusize.android.util.urlString
class WebViewFragment : DialogFragment() {
companion object {
private val TAG = WebViewFragment::class.simpleName
}
private lateinit var webView: VirtusizeWebView
// 1. Register for getting the result of the activity
private val virtusizeSNSAuthLauncher =
registerForActivityResult(
ActivityResultContracts.StartActivityForResult(),
) { result ->
// 3. Handle the SNS auth result by passing the webview and the result to the `VirtusizeAuth.handleVirtusizeSNSAuthResult` function
VirtusizeAuth.handleVirtusizeSNSAuthResult(webView, result.resultCode, result.data)
}
override fun onActivityCreated(savedInstanceState: Bundle?) {
super.onActivityCreated(savedInstanceState)
dialog?.window?.attributes?.windowAnimations = com.virtusize.android.R.style.VirtusizeDialogFragmentAnimation
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setStyle(STYLE_NORMAL, com.virtusize.android.R.style.FullScreenDialogStyle)
}
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?,
): View? {
return inflater.inflate(R.layout.webview_vs, container, false)
}
override fun onViewCreated(
view: View,
savedInstanceState: Bundle?,
) {
super.onViewCreated(view, savedInstanceState)
webView = view.findViewById(R.id.webView)
// 2. Pass the activity launcher to the VirtusizeWebView
webView.setVirtusizeSNSAuthLauncher(virtusizeSNSAuthLauncher)
object : WebViewClient() {
override fun shouldOverrideUrlLoading(
view: WebView?,
url: String,
): Boolean {
Log.d(TAG, "shouldOverrideUrlLoading $url")
return super.shouldOverrideUrlLoading(view, url)
}
override fun shouldOverrideUrlLoading(
view: WebView?,
request: WebResourceRequest?,
): Boolean {
request?.let {
Log.d(TAG, "shouldOverrideUrlLoading ${request.urlString}")
}
return super.shouldOverrideUrlLoading(view, request)
}
override fun onPageFinished(
view: WebView?,
url: String?,
) {
Log.d(TAG, "onPageFinished ${view?.url}")
super.onPageFinished(view, url)
}
}.also { webView.webViewClient = it }
webView.webChromeClient =
object : WebChromeClient() {
override fun onCreateWindow(
view: WebView?,
isDialog: Boolean,
isUserGesture: Boolean,
resultMsg: Message?,
): Boolean {
Log.d(TAG, "onCreateWindow ${view?.url}")
return super.onCreateWindow(view, isDialog, isUserGesture, resultMsg)
}
override fun onCloseWindow(window: WebView?) {
Log.d(TAG, "onCloseWindow")
}
}
webView.loadUrl("https://demo.virtusize.com/")
}
override fun onDestroyView() {
super.onDestroyView()
webView.stopLoading()
webView.destroy()
}
}
| 1 | Kotlin | 2 | 9 | b83c343b1469cb5c51936f6228783d67aa182490 | 4,036 | integration_android | MIT License |
prime-router/src/main/kotlin/serializers/CsvSerializer.kt | sreev | 390,034,639 | true | {"Kotlin": 785646, "HTML": 88142, "HCL": 87171, "Shell": 35824, "CSS": 33170, "Liquid": 22222, "JavaScript": 17028, "PLpgSQL": 12858, "Python": 5030, "Dockerfile": 2436} | package gov.cdc.prime.router.serializers
import com.github.doyaaaaaken.kotlincsv.dsl.csvReader
import com.github.doyaaaaaken.kotlincsv.dsl.csvWriter
import gov.cdc.prime.router.Element
import gov.cdc.prime.router.ElementAndValue
import gov.cdc.prime.router.Mapper
import gov.cdc.prime.router.Metadata
import gov.cdc.prime.router.REPORT_MAX_ERRORS
import gov.cdc.prime.router.REPORT_MAX_ITEMS
import gov.cdc.prime.router.REPORT_MAX_ITEM_COLUMNS
import gov.cdc.prime.router.Receiver
import gov.cdc.prime.router.Report
import gov.cdc.prime.router.ReportId
import gov.cdc.prime.router.ResultDetail
import gov.cdc.prime.router.Schema
import gov.cdc.prime.router.Source
import java.io.InputStream
import java.io.OutputStream
/**
* The CSV serializer is crafted to handle poor data. The logic depends on the type of the element and it cardinality.
*
* | Type | Cardinality | no column on input | empty input value | Invalid input value | valid input value |
* |--------------|-------------|--------------------------------------|--------------------------------------|---------------------|-------------------|
* | FOO | 0..1 | mapper -> default -> empty + warning | mapper -> default -> empty + warning | empty + warning | value |
* | FOO | 1..1 | mapper -> default -> error | mapper -> default -> error | error | value |
* | FOO_OR_BLANK | 0..1 | mapper -> default -> empty + warning | empty | empty + warning | value |
* | FOO_OR_BLANK | 1..1 | mapper -> default -> error | empty | error | value |
*
*/
class CsvSerializer(val metadata: Metadata) {
private data class CsvMapping(
val useCsv: Map<String, List<Element.CsvField>>,
val useMapper: Map<String, Pair<Mapper, List<String>>>,
val useDefault: Map<String, String>,
val errors: List<String>,
val warnings: List<String>,
)
private data class RowResult(
val row: List<String>,
val errors: List<String>,
val warnings: List<String>,
)
fun readExternal(schemaName: String, input: InputStream, source: Source): ReadResult {
return readExternal(schemaName, input, listOf(source))
}
fun readExternal(
schemaName: String,
input: InputStream,
sources: List<Source>,
destination: Receiver? = null,
defaultValues: Map<String, String> = emptyMap(),
): ReadResult {
val schema = metadata.findSchema(schemaName) ?: error("Internal Error: invalid schema name '$schemaName'")
val errors = mutableListOf<ResultDetail>()
val warnings = mutableListOf<ResultDetail>()
var rows = mutableListOf<Map<String, String>>()
csvReader().open(input) {
readAllWithHeaderAsSequence().forEach { row: Map<String, String> ->
rows.add(row)
if (rows.size > REPORT_MAX_ITEMS) {
errors.add(
ResultDetail(
ResultDetail.DetailScope.REPORT, "",
"Report rows ${rows.size} exceeds max allowed $REPORT_MAX_ITEMS rows"
)
)
return@open
}
if (row.size > REPORT_MAX_ITEM_COLUMNS) {
errors.add(
ResultDetail(
ResultDetail.DetailScope.REPORT, "",
"Number of report columns ${row.size} exceeds max allowed $REPORT_MAX_ITEM_COLUMNS"
)
)
return@open
}
}
}
if (errors.size > 0) {
return ReadResult(null, errors, warnings)
}
if (rows.isEmpty()) {
return ReadResult(Report(schema, emptyList(), sources, destination), errors, warnings)
}
val csvMapping = buildMappingForReading(schema, defaultValues, rows[0])
errors.addAll(csvMapping.errors.map { ResultDetail.report(it) })
warnings.addAll(csvMapping.warnings.map { ResultDetail.report(it) })
if (errors.size > REPORT_MAX_ERRORS) {
errors.add(
ResultDetail(
ResultDetail.DetailScope.REPORT, "",
"Number of errors (${errors.size}) exceeded $REPORT_MAX_ERRORS. Stopping further work."
)
)
return ReadResult(null, errors, warnings)
}
if (csvMapping.errors.isNotEmpty()) {
return ReadResult(null, errors, warnings)
}
val mappedRows = rows.mapIndexedNotNull { index, row ->
val result = mapRow(schema, csvMapping, row)
val trackingColumn = schema.findElementColumn(schema.trackingElement ?: "")
var trackingId = if (trackingColumn != null) result.row[trackingColumn] else ""
if (trackingId.isEmpty())
trackingId = "row$index"
errors.addAll(result.errors.map { ResultDetail.item(trackingId, it) })
warnings.addAll(result.warnings.map { ResultDetail.item(trackingId, it) })
if (result.errors.isEmpty()) {
result.row
} else {
null
}
}
if (errors.size > REPORT_MAX_ERRORS) {
errors.add(
ResultDetail(
ResultDetail.DetailScope.REPORT, "",
"Number of errors (${errors.size}) exceeded $REPORT_MAX_ERRORS. Stopping."
)
)
return ReadResult(null, errors, warnings)
}
return ReadResult(Report(schema, mappedRows, sources, destination), errors, warnings)
}
fun readInternal(
schemaName: String,
input: InputStream,
sources: List<Source>,
destination: Receiver? = null,
blobReportId: ReportId? = null
): Report {
val schema = metadata.findSchema(schemaName) ?: error("Internal Error: invalid schema name '$schemaName'")
val rows: List<List<String>> = csvReader().readAll(input).drop(1)
return Report(schema, rows, sources, destination, id = blobReportId)
}
fun write(report: Report, output: OutputStream) {
val schema = report.schema
fun buildHeader(): List<String> = schema.csvFields.map { it.name }
fun buildRows(): List<List<String>> {
return report.itemIndices.map { row ->
schema
.elements
.flatMap { element ->
if (element.csvFields != null) {
element.csvFields.map { field ->
val value = report.getString(row, element.name)
?: error("Internal Error: table is missing '${element.name} column")
element.toFormatted(value, field.format)
}
} else {
emptyList()
}
}
}
}
val allRows = listOf(buildHeader()).plus(buildRows())
csvWriter {
lineTerminator = "\n"
outputLastLineTerminator = true
}.writeAll(allRows, output)
}
fun writeInternal(report: Report, output: OutputStream) {
val schema = report.schema
fun buildHeader(): List<String> = schema.elements.map { it.name }
fun buildRows(): List<List<String>> {
return report.itemIndices.map { row -> report.getRow(row) }
}
val allRows = listOf(buildHeader()).plus(buildRows())
csvWriter {
lineTerminator = "\n"
outputLastLineTerminator = true
}.writeAll(allRows, output)
}
private fun buildMappingForReading(
schema: Schema,
defaultValues: Map<String, String>,
row: Map<String, String>
): CsvMapping {
fun rowContainsAll(fields: List<Element.CsvField>): Boolean {
return fields.find { !row.containsKey(it.name) } == null
}
val useCsv = schema
.elements
.filter { it.csvFields != null && rowContainsAll(it.csvFields) }
.map { it.name to it.csvFields!! }
.toMap()
val useMapper = schema
.elements
.filter { it.mapper?.isNotBlank() == true } // TODO: check for the presence of fields
.map { it.name to Pair(it.mapperRef!!, it.mapperArgs!!) }
.toMap()
val useDefault = schema
.elements
.map { it.name to it.defaultValue(defaultValues) }
.toMap()
// Figure out what is missing or ignored
val requiredHeaders = schema
.filterCsvFields { it.cardinality == Element.Cardinality.ONE && it.default == null && it.mapper == null }
.map { it.name }
.toSet()
val optionalHeaders = schema
.filterCsvFields {
(it.cardinality == null || it.cardinality == Element.Cardinality.ZERO_OR_ONE) &&
it.default == null && it.mapper == null
}
.map { it.name }
.toSet()
val headersWithDefault = schema.filterCsvFields { it.default != null || it.mapper != null }
.map { it.name }
val actualHeaders = row.keys.toSet()
val missingRequiredHeaders = requiredHeaders - actualHeaders
val missingOptionalHeaders = optionalHeaders - actualHeaders
val ignoredHeaders = actualHeaders - requiredHeaders - optionalHeaders - headersWithDefault
val errors = missingRequiredHeaders.map { "Missing '$it' header" }
val warnings = missingOptionalHeaders.map { "Missing '$it' header" } +
ignoredHeaders.map { "Unexpected '$it' header is ignored" }
return CsvMapping(useCsv, useMapper, useDefault, errors, warnings)
}
/**
* For a input row from the CSV file map to a schema defined row by
*
* 1. Using values from the csv file
* 2. Using a mapper defined by the schema
* 3. Using the default defined by the schema
*
* If the element `canBeBlank` then only step 1 is used.
*
* Also, format values into the normalized format for the type
*/
private fun mapRow(schema: Schema, csvMapping: CsvMapping, inputRow: Map<String, String>): RowResult {
val lookupValues = mutableMapOf<String, String>()
val errors = mutableListOf<String>()
val warnings = mutableListOf<String>()
val placeholderValue = "**%%placeholder**"
val failureValue = "**^^validationFail**"
fun useCsv(element: Element): String? {
val csvFields = csvMapping.useCsv[element.name] ?: return null
val subValues = csvFields.map {
val value = inputRow.getValue(it.name)
Element.SubValue(it.name, value, it.format)
}
for (subValue in subValues) {
if (subValue.value.isBlank()) {
return if (element.canBeBlank) "" else null
}
val error = element.checkForError(subValue.value, subValue.format)
if (error != null) {
when (element.cardinality) {
Element.Cardinality.ONE -> errors += error
Element.Cardinality.ZERO_OR_ONE -> warnings += error
}
return failureValue
}
}
return if (subValues.size == 1) {
element.toNormalized(subValues[0].value, subValues[0].format)
} else {
element.toNormalized(subValues)
}
}
fun useMapperPlaceholder(element: Element): String? {
return if (csvMapping.useMapper[element.name] != null) placeholderValue else null
}
fun useMapper(element: Element): String? {
val (mapper, args) = csvMapping.useMapper[element.name] ?: return null
val valueNames = mapper.valueNames(element, args)
val valuesForMapper = valueNames.map { elementName ->
val valueElement = schema.findElement(elementName)
?: error(
"Schema Error: Could not find element '$elementName' for mapper " +
"'${mapper.name}' from '${element.name}'."
)
val value = lookupValues[elementName]
?: error("Schema Error: No mapper input for $elementName")
ElementAndValue(valueElement, value)
}
return mapper.apply(element, args, valuesForMapper)
}
fun useDefault(element: Element): String {
return csvMapping.useDefault[element.name] ?: ""
}
// Build up lookup values
schema.elements.forEach { element ->
val value = useCsv(element) ?: useMapperPlaceholder(element) ?: useDefault(element)
lookupValues[element.name] = value
}
// Output with value
val outputRow = schema.elements.map { element ->
var value = lookupValues[element.name] ?: error("Internal Error: Second pass should have all values")
if (value == placeholderValue) {
value = useMapper(element) ?: useDefault(element)
}
if (value.isBlank() && !element.canBeBlank) {
when (element.cardinality) {
Element.Cardinality.ONE -> errors += "Empty value for '${element.name}'"
Element.Cardinality.ZERO_OR_ONE -> {
}
}
}
if (value == failureValue) {
value = ""
}
value
}
return RowResult(outputRow, errors, warnings)
}
} | 0 | null | 0 | 0 | fcd394d210cc327acdddb7e3e646fb100e499bbd | 14,156 | prime-reportstream | Creative Commons Zero v1.0 Universal |
src/main/kotlin/net/ndrei/teslapoweredthingies/machines/portablemultitank/MultiTankBlock.kt | MinecraftModDevelopmentMods | 77,729,751 | false | null | package net.ndrei.teslapoweredthingies.machines.portablemultitank
import net.minecraft.block.state.BlockStateContainer
import net.minecraft.block.state.IBlockState
import net.minecraft.client.Minecraft
import net.minecraft.client.renderer.BufferBuilder
import net.minecraft.client.renderer.GlStateManager
import net.minecraft.client.renderer.Tessellator
import net.minecraft.client.renderer.block.model.BakedQuad
import net.minecraft.client.renderer.texture.TextureAtlasSprite
import net.minecraft.client.renderer.texture.TextureMap
import net.minecraft.client.renderer.vertex.DefaultVertexFormats
import net.minecraft.item.Item
import net.minecraft.item.ItemStack
import net.minecraft.tileentity.TileEntity
import net.minecraft.util.BlockRenderLayer
import net.minecraft.util.EnumFacing
import net.minecraft.util.ResourceLocation
import net.minecraft.util.math.BlockPos
import net.minecraft.util.math.Vec3d
import net.minecraft.world.IBlockAccess
import net.minecraftforge.common.model.TRSRTransformation
import net.minecraftforge.common.property.ExtendedBlockState
import net.minecraftforge.common.property.IExtendedBlockState
import net.minecraftforge.common.util.Constants
import net.minecraftforge.fluids.Fluid
import net.minecraftforge.fluids.FluidStack
import net.minecraftforge.fml.relauncher.Side
import net.minecraftforge.fml.relauncher.SideOnly
import net.minecraftforge.registries.IForgeRegistry
import net.ndrei.teslacorelib.annotations.AutoRegisterBlock
import net.ndrei.teslacorelib.blocks.AxisAlignedBlock
import net.ndrei.teslacorelib.render.selfrendering.*
import net.ndrei.teslapoweredthingies.client.ThingiesTexture
import net.ndrei.teslapoweredthingies.machines.BaseThingyBlock
import org.lwjgl.opengl.GL11
/**
* Created by CF on 2017-07-16.
*/
@AutoRegisterBlock
@SelfRenderingBlock(false)
object MultiTankBlock
: BaseThingyBlock<MultiTankEntity>("multi_tank", MultiTankEntity::class.java), ISelfRenderingBlock {
lateinit var FLUID_1_PROP: UnlistedFluidProperty private set
lateinit var FLUID_2_PROP: UnlistedFluidProperty private set
lateinit var FLUID_3_PROP: UnlistedFluidProperty private set
lateinit var FLUID_4_PROP: UnlistedFluidProperty private set
lateinit var FLUID_PROPS: Array<UnlistedFluidProperty>
override fun registerItem(registry: IForgeRegistry<Item>) {
registry.register(MultiTankItem)
}
//#region Block Overrides
override fun createBlockState(): BlockStateContainer {
this.FLUID_1_PROP = UnlistedFluidProperty("fluid1")
this.FLUID_2_PROP = UnlistedFluidProperty("fluid2")
this.FLUID_3_PROP = UnlistedFluidProperty("fluid3")
this.FLUID_4_PROP = UnlistedFluidProperty("fluid4")
this.FLUID_PROPS = arrayOf(FLUID_1_PROP, FLUID_2_PROP, FLUID_3_PROP, FLUID_4_PROP)
return ExtendedBlockState(this, arrayOf(AxisAlignedBlock.FACING), this.FLUID_PROPS)
}
//
// override fun registerItem(registry: IForgeRegistry<Item>) {
// registry.register(MultiTankItem)
// }
override fun canRenderInLayer(state: IBlockState?, layer: BlockRenderLayer?): Boolean {
return /*layer == BlockRenderLayer.TRANSLUCENT ||*/ layer == BlockRenderLayer.SOLID || layer == BlockRenderLayer.CUTOUT
}
override fun isOpaqueCube(state: IBlockState?) = false
override fun isFullCube(state: IBlockState?) = false
override fun isTranslucent(state: IBlockState?) = true
override fun doesSideBlockRendering(state: IBlockState?, world: IBlockAccess?, pos: BlockPos?, face: EnumFacing?) = false
//#endregion
override fun getExtendedState(state: IBlockState, world: IBlockAccess, pos: BlockPos): IBlockState {
if (state is IExtendedBlockState) {
val te = world.getTileEntity(pos)
if (te is MultiTankEntity) {
return (0..3).fold(state) { it, index ->
val f = te.getFluid(index)
if (f != null)
it.withProperty(FLUID_PROPS[index], f)
else
it
}
}
}
return super.getExtendedState(state, world, pos)
}
@SideOnly(Side.CLIENT)
override fun getTextures(): List<ResourceLocation> {
return listOf(ThingiesTexture.MULTI_TANK_SIDE.resource)
}
@SideOnly(Side.CLIENT)
override fun getBakeries(layer: BlockRenderLayer?, state: IBlockState?, stack: ItemStack?, side: EnumFacing?, rand: Long, transform: TRSRTransformation): List<IBakery> {
val bakeries = mutableListOf<IBakery>()
// TeslaThingiesMod.logger.info("Building bakeries for '${layer?.toString() ?: "NO LAYER"}'.")
if ((layer == BlockRenderLayer.SOLID) || (layer == null)) {
bakeries.add(listOf(
RawCube(Vec3d(0.0, 0.0, 0.0), Vec3d(32.0, 2.0, 32.0), ThingiesTexture.MULTI_TANK_SIDE.sprite)
.addFace(EnumFacing.UP).uv(8.0f, 8.0f, 16.0f, 16.0f)
.addFace(EnumFacing.DOWN).uv(8.0f, 8.0f, 16.0f, 16.0f)
.addFace(EnumFacing.WEST).uv(0.0f, 0.0f, 8.0f, 0.5f)
.addFace(EnumFacing.NORTH).uv(0.0f, 0.0f, 8.0f, 0.5f)
.addFace(EnumFacing.EAST).uv(0.0f, 0.0f, 8.0f, 0.5f)
.addFace(EnumFacing.SOUTH).uv(0.0f, 0.0f, 8.0f, 0.5f),
RawCube(Vec3d(1.0, 2.0, 1.0), Vec3d(15.0, 30.0, 15.0), ThingiesTexture.MULTI_TANK_SIDE.sprite)
.dualSide()
.addFace(EnumFacing.SOUTH).uv(4.5f, 0.5f, 8.0f, 7.5f)
.addFace(EnumFacing.EAST).uv(4.5f, 0.5f, 8.0f, 7.5f),
RawCube(Vec3d(17.0, 2.0, 1.0), Vec3d(31.0, 30.0, 15.0), ThingiesTexture.MULTI_TANK_SIDE.sprite)
.dualSide()
.addFace(EnumFacing.SOUTH).uv(4.5f, 0.5f, 8.0f, 7.5f)
.addFace(EnumFacing.WEST).uv(4.5f, 0.5f, 8.0f, 7.5f),
RawCube(Vec3d(17.0, 2.0, 17.0), Vec3d(31.0, 30.0, 31.0), ThingiesTexture.MULTI_TANK_SIDE.sprite)
.dualSide()
.addFace(EnumFacing.NORTH).uv(4.5f, 0.5f, 8.0f, 7.5f)
.addFace(EnumFacing.WEST).uv(4.5f, 0.5f, 8.0f, 7.5f),
RawCube(Vec3d(1.0, 2.0, 17.0), Vec3d(15.0, 30.0, 31.0), ThingiesTexture.MULTI_TANK_SIDE.sprite)
.dualSide()
.addFace(EnumFacing.NORTH).uv(4.5f, 0.5f, 8.0f, 7.5f)
.addFace(EnumFacing.EAST).uv(4.5f, 0.5f, 8.0f, 7.5f),
RawCube(Vec3d(0.0, 30.0, 0.0), Vec3d(32.0, 32.0, 32.0), ThingiesTexture.MULTI_TANK_SIDE.sprite)
.addFace(EnumFacing.WEST).uv(0.0f, 0.0f, 8.0f, 0.5f)
.addFace(EnumFacing.NORTH).uv(0.0f, 0.0f, 8.0f, 0.5f)
.addFace(EnumFacing.EAST).uv(0.0f, 0.0f, 8.0f, 0.5f)
.addFace(EnumFacing.SOUTH).uv(0.0f, 0.0f, 8.0f, 0.5f)
.addFace(EnumFacing.UP).uv(8.0f, 0.0f, 16.0f, 8.0f)
.addFace(EnumFacing.DOWN).uv(8.0f, 8.0f, 16.0f, 16.0f)
).combine().static())
}
if ((layer == BlockRenderLayer.CUTOUT) || (layer == null)) {
bakeries.add(listOf(
RawCube(Vec3d(1.0, 2.0, 1.0), Vec3d(15.0, 30.0, 15.0), ThingiesTexture.MULTI_TANK_SIDE.sprite)
.dualSide()
.addFace(EnumFacing.NORTH).uv(0.0f, 8.5f, 3.5f, 15.5f)
.addFace(EnumFacing.WEST).uv(0.0f, 8.5f, 3.5f, 15.5f),
RawCube(Vec3d(17.0, 2.0, 1.0), Vec3d(31.0, 30.0, 15.0), ThingiesTexture.MULTI_TANK_SIDE.sprite)
.dualSide()
.addFace(EnumFacing.NORTH).uv(0.0f, 8.5f, 3.5f, 15.5f)
.addFace(EnumFacing.EAST).uv(0.0f, 8.5f, 3.5f, 15.5f),
RawCube(Vec3d(17.0, 2.0, 17.0), Vec3d(31.0, 30.0, 31.0), ThingiesTexture.MULTI_TANK_SIDE.sprite)
.dualSide()
.addFace(EnumFacing.SOUTH).uv(0.0f, 8.5f, 3.5f, 15.5f)
.addFace(EnumFacing.EAST).uv(0.0f, 8.5f, 3.5f, 15.5f),
RawCube(Vec3d(1.0, 2.0, 17.0), Vec3d(15.0, 30.0, 31.0), ThingiesTexture.MULTI_TANK_SIDE.sprite)
.dualSide()
.addFace(EnumFacing.SOUTH).uv(0.0f, 8.5f, 3.5f, 15.5f)
.addFace(EnumFacing.WEST).uv(0.0f, 8.5f, 3.5f, 15.5f)
).combine().static())
}
if (/*(layer == BlockRenderLayer.TRANSLUCENT) || */(layer == null)) {
val xs = arrayOf(1.1, 1.1, 17.1, 17.1)
val zs = arrayOf(1.1, 17.1, 17.1, 1.1)
val f1s = arrayOf(EnumFacing.NORTH, EnumFacing.SOUTH, EnumFacing.SOUTH, EnumFacing.NORTH)
val f2s = arrayOf(EnumFacing.WEST, EnumFacing.WEST, EnumFacing.EAST, EnumFacing.EAST)
(0..3).mapTo(bakeries) {
CachedBakery({ _state, _stack, _side, _vertexFormat, _transform ->
val info = [email protected](_state, _stack, it)
if (info != null) {
val resource = info.fluid.still
val sprite = (if (resource != null) Minecraft.getMinecraft().textureMapBlocks.getTextureExtry(resource.toString()) else null)
?: Minecraft.getMinecraft().textureMapBlocks.missingSprite
mutableListOf<BakedQuad>().also { list ->
RawCube(Vec3d(xs[it], 2.1, zs[it]), Vec3d(xs[it] + 13.8, 2.0 + 28.0 * (info.amount.toDouble() / 64.0) - 0.1, zs[it] + 13.8), sprite)
.autoUV()
.addFace(f1s[it]).color(info.fluid.color)
.addFace(f2s[it]).color(info.fluid.color)
.addFace(EnumFacing.UP).color(info.fluid.color)
.bake(list, _vertexFormat, _transform)
}
}
else {
mutableListOf<BakedQuad>()
}
}).also { cache ->
cache.keyGetter = { _state, _stack, _ ->
val info = this.getFluidStackInfo(_state, _stack, it)
if (info == null) {
"no info"
}
else {
"${info.fluid.name}::${info.amount}"
}
}
}
}
}
return bakeries.toList()
}
private fun getFluidStackInfo(state: IBlockState?, stack: ItemStack?, index: Int): FluidStackInfo? {
val extended = (state as? IExtendedBlockState)
if (extended != null) {
val fluid = extended.getValue(MultiTankBlock.FLUID_PROPS[index])
if ((fluid != null) && (fluid.fluid != null) && (fluid.amount > 0)) {
return FluidStackInfo(fluid.fluid, Math.round(fluid.amount.toFloat() / 93.75f))
}
}
if ((stack != null) && !stack.isEmpty && stack.hasTagCompound()) {
val nbt = stack.tagCompound
if ((nbt != null) && nbt.hasKey("tileentity", Constants.NBT.TAG_COMPOUND)) {
val teNBT = nbt.getCompoundTag("tileentity")
if (teNBT.hasKey("fluids", Constants.NBT.TAG_COMPOUND)) {
val flNBT = teNBT.getCompoundTag("fluids")
// fluids -> tanks -> (FluidName, Amount)
if (flNBT.hasKey("tanks", Constants.NBT.TAG_LIST)) {
val tNBT = flNBT.getTagList("tanks", Constants.NBT.TAG_COMPOUND)
if (tNBT.tagCount() > index) {
val tank = tNBT.getCompoundTagAt(index)
val fluid = FluidStack.loadFluidStackFromNBT(tank)
if (fluid != null) {
return FluidStackInfo(fluid.fluid, Math.round(fluid.amount.toFloat() / 93.75f))
}
}
}
}
}
}
return null
}
class FluidStackInfo(val fluid: Fluid, val amount: Int)
@SideOnly(Side.CLIENT)
override fun renderTESR(proxy: TESRProxy, te: TileEntity, x: Double, y: Double, z: Double, partialTicks: Float, destroyStage: Int, alpha: Float) {
GlStateManager.enableBlend()
GlStateManager.blendFunc(GlStateManager.SourceFactor.SRC_ALPHA, GlStateManager.DestFactor.ONE_MINUS_SRC_ALPHA)
proxy.bindTexture(TextureMap.LOCATION_BLOCKS_TEXTURE)
val xs = arrayOf(1.1, 17.1, 1.1, 17.1)
val zs = arrayOf(1.1, 1.1, 17.1, 17.1)
val oxs = arrayOf(0.0, 13.8, 0.0, 13.8)
val ozs = arrayOf(0.0, 0.0, 13.8, 13.8)
(0..3).map {
val fluid = (te as? MultiTankEntity)?.getFluid(it)
if ((fluid != null) && (fluid.fluid != null) && (fluid.amount > 0)) {
val amount = Math.round(fluid.amount.toFloat() / 93.75f) / 64.0f
this.drawFluid(xs[it], zs[it], oxs[it], ozs[it], fluid.fluid, amount)
}
}
GlStateManager.disableBlend()
GlStateManager.color(1.0f, 1.0f, 1.0f, 1.0f)
}
@SideOnly(Side.CLIENT)
private fun drawFluid(tankX: Double, tankZ: Double, offX: Double, offZ : Double, fluid: Fluid?, fluidPercent: Float) {
GlStateManager.pushMatrix()
GlStateManager.translate(tankX, 2.0, tankZ)
if ((fluidPercent > 0.0f) && (fluid != null)) {
if (fluidPercent > 0) {
val still = fluid.still
if (still != null) {
val height = 28 * fluidPercent
val color = fluid.color
GlStateManager.color((color shr 16 and 0xFF) / 255.0f, (color shr 8 and 0xFF) / 255.0f, (color and 0xFF) / 255.0f, (color ushr 24 and 0xFF) / 255.0f)
val stillSprite = Minecraft.getMinecraft().textureMapBlocks.getTextureExtry(still.toString())
?: Minecraft.getMinecraft().textureMapBlocks.missingSprite
if (stillSprite != null) {
val xStage = (offX > 0)
val zStage = (offZ > 0)
this.drawSprite(
Vec3d(0.0, 28.0 - height, offZ),
Vec3d(13.8, 28.0, offZ),
stillSprite, zStage, !zStage)
this.drawSprite(
Vec3d(offX, 28.0 - height, 0.0),
Vec3d(offX, 28.0, 13.8),
stillSprite, !xStage, xStage)
this.drawSprite(
Vec3d(0.0, 28.0 - height, 13.8),
Vec3d(13.8, 28.0 - height, 0.0),
stillSprite)
}
}
}
}
GlStateManager.popMatrix()
}
@SideOnly(Side.CLIENT)
private fun drawSprite(start: Vec3d, end: Vec3d, sprite: TextureAtlasSprite, draw1: Boolean = true, draw2: Boolean = true) {
val buffer = Tessellator.getInstance().buffer
buffer.begin(GL11.GL_QUADS, DefaultVertexFormats.POSITION_TEX)
val width = Math.abs(if (end.x == start.x) end.z - start.z else end.x - start.x)
val height = Math.abs(if (end.y == start.y) end.z - start.z else end.y - start.y)
val texW = sprite.maxU - sprite.minU
val texH = sprite.maxV - sprite.minV
val finalW = texW * width / 32.0
val finalH = texH * height / 32.0
this.drawTexture(buffer, start, end, sprite.minU.toDouble(), sprite.minV.toDouble(), sprite.minU + finalW, sprite.minV + finalH, draw1, draw2)
Tessellator.getInstance().draw()
}
@SideOnly(Side.CLIENT)
private fun drawTexture(buffer: BufferBuilder, start: Vec3d, end: Vec3d, minU: Double, minV: Double, maxU: Double, maxV: Double, draw1: Boolean = true, draw2: Boolean = true) {
if (draw1) {
buffer.pos(start.x, start.y, start.z).tex(minU, minV).endVertex()
buffer.pos(start.x, end.y, if (start.x == end.x) start.z else end.z).tex(minU, maxV).endVertex()
buffer.pos(end.x, end.y, end.z).tex(maxU, maxV).endVertex()
buffer.pos(end.x, start.y, if (start.x == end.x) end.z else start.z).tex(maxU, minV).endVertex()
}
if (draw2) {
buffer.pos(start.x, start.y, start.z).tex(minU, minV).endVertex()
buffer.pos(end.x, start.y, if (start.x == end.x) end.z else start.z).tex(maxU, minV).endVertex()
buffer.pos(end.x, end.y, end.z).tex(maxU, maxV).endVertex()
buffer.pos(start.x, end.y, if (start.x == end.x) start.z else end.z).tex(minU, maxV).endVertex()
}
}
}
| 21 | null | 4 | 2 | 22fdcf629e195a73dd85cf0ac0c5dda551085e71 | 17,259 | Tesla-Powered-Thingies | MIT License |
js/js.translator/testData/box/operatorOverloading/plusOverload.kt | JakeWharton | 99,388,807 | false | null | // EXPECTED_REACHABLE_NODES: 1112
package foo
class myInt(a: Int) {
val value = a;
operator fun plus(other: myInt): myInt = myInt(value + other.value)
}
fun box(): String {
return if ((myInt(3) + myInt(5)).value == 8) "OK" else "fail"
} | 184 | null | 5691 | 83 | 4383335168338df9bbbe2a63cb213a68d0858104 | 252 | kotlin | Apache License 2.0 |
RangeBar/src/main/java/com/dannyjung/rangebar/base/BaseTrack.kt | danny-jung | 295,870,887 | false | {"Kotlin": 20777} | package com.dannyjung.rangebar.base
import android.graphics.Canvas
import android.graphics.RectF
abstract class BaseTrack {
abstract val height: Int
val rectF: RectF = RectF()
abstract fun onDraw(canvas: Canvas)
}
| 0 | Kotlin | 0 | 0 | 3bf2326d09c50809d48fed3756f6b3714fd3eeab | 231 | RangeBar | Apache License 2.0 |
platform/statistics/devkit/src/com/intellij/internal/statistic/actions/OpenLocalWhitelistFileAction.kt | slouca10 | 243,684,085 | false | {"Text": 3944, "XML": 4636, "Ant Build System": 13, "Shell": 478, "Markdown": 302, "Ignore List": 79, "Git Attributes": 9, "Batchfile": 30, "SVG": 1988, "Java": 64549, "C++": 20, "HTML": 2727, "Kotlin": 4898, "DTrace": 1, "Gradle": 71, "Java Properties": 97, "INI": 239, "JFlex": 27, "Objective-C": 19, "Groovy": 3347, "XSLT": 109, "JavaScript": 154, "CSS": 55, "JSON": 1082, "desktop": 1, "Python": 10046, "JAR Manifest": 12, "YAML": 381, "C#": 37, "Smalltalk": 17, "Diff": 128, "Erlang": 1, "Rich Text Format": 2, "AspectJ": 2, "Perl": 6, "HLSL": 2, "CoffeeScript": 3, "JSON with Comments": 43, "Vue": 12, "OpenStep Property List": 41, "PlantUML": 3, "Protocol Buffer": 2, "fish": 1, "EditorConfig": 211, "Prolog": 2, "ColdFusion": 2, "Turtle": 2, "TeX": 11, "Elixir": 2, "PHP": 43, "Ruby": 4, "XML Property List": 77, "E-mail": 18, "Roff": 35, "Roff Manpage": 1, "Checksums": 58, "Java Server Pages": 8, "GraphQL": 24, "C": 42, "AMPL": 4, "Linux Kernel Module": 1, "Makefile": 1, "CMake": 6, "Microsoft Visual Studio Solution": 6, "VBScript": 1, "NSIS": 6, "Thrift": 3, "Cython": 10, "reStructuredText": 54, "TOML": 1, "Dockerfile": 1, "Regular Expression": 3, "JSON5": 4} | // Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.internal.statistic.actions
import com.intellij.icons.AllIcons
import com.intellij.idea.ActionsBundle
import com.intellij.internal.statistic.StatisticsBundle
import com.intellij.internal.statistic.actions.OpenWhitelistFileAction.Companion.openFileInEditor
import com.intellij.internal.statistic.eventLog.validator.persistence.EventLogTestWhitelistPersistence
import com.intellij.internal.statistic.eventLog.whitelist.WhitelistTestGroupStorage
import com.intellij.openapi.actionSystem.AnActionEvent
import com.intellij.openapi.project.DumbAwareAction
import com.intellij.ui.JBColor
import com.intellij.ui.LayeredIcon
import com.intellij.ui.TextIcon
import com.intellij.ui.scale.JBUIScale
import com.intellij.util.ui.UIUtil
import java.awt.Font
class OpenLocalWhitelistFileAction(private val myRecorderId: String = "FUS")
: DumbAwareAction(StatisticsBundle.message("stats.open.0.local.whitelist.file", myRecorderId),
ActionsBundle.message("group.OpenLocalWhitelistFileAction.description"),
ICON) {
override fun actionPerformed(e: AnActionEvent) {
val project = e.project ?: return
val file = EventLogTestWhitelistPersistence(myRecorderId).whitelistFile
openFileInEditor(file, project)
}
override fun update(e: AnActionEvent) {
val localWhitelistSize = WhitelistTestGroupStorage.getTestStorage(myRecorderId)?.size() ?: 0
val text = if (localWhitelistSize < 100) localWhitelistSize.toString() else "99+"
val sizeCountIcon = TextIcon(text, JBColor.DARK_GRAY, UIUtil.getLabelBackground(), 1)
sizeCountIcon.setFont(Font(UIUtil.getLabelFont().name, Font.BOLD, JBUIScale.scale(9)))
sizeCountIcon.setInsets(1, 1, 0, 0)
ICON.setIcon(sizeCountIcon, 2, JBUIScale.scale(10), JBUIScale.scale(10))
e.presentation.icon = ICON
}
companion object {
private val ICON = LayeredIcon(3)
init {
ICON.setIcon(AllIcons.FileTypes.Any_type, 0)
ICON.setIcon(AllIcons.Actions.Scratch, 1)
}
}
} | 1 | null | 2 | 1 | 8a4430836e002b846dc4cd97c308e37557b5a015 | 2,149 | intellij-community | Apache License 2.0 |
feature/settings-impl/src/main/kotlin/org/michaelbel/movies/settings/ui/SettingsLanguageBox.kt | michaelbel | 115,437,864 | false | null | package org.michaelbel.movies.settings.ui
import androidx.compose.foundation.background
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
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.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Modifier
import androidx.compose.ui.platform.testTag
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.tooling.preview.PreviewParameter
import androidx.compose.ui.unit.dp
import androidx.constraintlayout.compose.ConstraintLayout
import androidx.constraintlayout.compose.Dimension
import org.michaelbel.movies.common.localization.model.AppLanguage
import org.michaelbel.movies.settings.ktx.languageText
import org.michaelbel.movies.settings_impl.R
import org.michaelbel.movies.ui.preview.DevicePreviews
import org.michaelbel.movies.ui.preview.provider.LanguagePreviewParameterProvider
import org.michaelbel.movies.ui.theme.AmoledTheme
import org.michaelbel.movies.ui.theme.MoviesTheme
@Composable
fun SettingsLanguageBox(
currentLanguage: AppLanguage,
onLanguageSelect: (AppLanguage) -> Unit,
modifier: Modifier = Modifier,
) {
var languageDialog: Boolean by remember { mutableStateOf(false) }
if (languageDialog) {
SettingLanguageDialog(
currentLanguage = currentLanguage,
onLanguageSelect = onLanguageSelect,
onDismissRequest = {
languageDialog = false
}
)
}
ConstraintLayout(
modifier = modifier
.clickable {
languageDialog = true
}
.testTag("ConstraintLayout")
) {
val (title, value) = createRefs()
Text(
text = stringResource(R.string.settings_language),
modifier = Modifier
.constrainAs(title) {
width = Dimension.wrapContent
height = Dimension.wrapContent
start.linkTo(parent.start, 16.dp)
top.linkTo(parent.top)
bottom.linkTo(parent.bottom)
}
.testTag("TitleText"),
style = MaterialTheme.typography.bodyLarge.copy(
color = MaterialTheme.colorScheme.onPrimaryContainer
)
)
Text(
text = currentLanguage.languageText,
modifier = Modifier
.constrainAs(value) {
width = Dimension.wrapContent
height = Dimension.wrapContent
top.linkTo(parent.top)
end.linkTo(parent.end, 16.dp)
bottom.linkTo(parent.bottom)
}
.testTag("ValueText"),
style = MaterialTheme.typography.bodyLarge.copy(
color = MaterialTheme.colorScheme.primary
)
)
}
}
@Composable
@DevicePreviews
private fun SettingsLanguageBoxPreview(
@PreviewParameter(LanguagePreviewParameterProvider::class) language: AppLanguage
) {
MoviesTheme {
SettingsLanguageBox(
currentLanguage = language,
onLanguageSelect = {},
modifier = Modifier
.fillMaxWidth()
.height(52.dp)
.background(MaterialTheme.colorScheme.primaryContainer)
)
}
}
@Composable
@Preview
private fun SettingsLanguageBoxAmoledPreview(
@PreviewParameter(LanguagePreviewParameterProvider::class) language: AppLanguage
) {
AmoledTheme {
SettingsLanguageBox(
currentLanguage = language,
onLanguageSelect = {},
modifier = Modifier
.fillMaxWidth()
.height(52.dp)
.background(MaterialTheme.colorScheme.primaryContainer)
)
}
} | 6 | null | 30 | 81 | 00b1cd807a4e7c894b0792ebb668e4cbcedc5605 | 4,143 | movies | Apache License 2.0 |
app/src/main/java/com/sarlomps/evemento/event/comment/CommentAdapter.kt | sarlomps | 176,547,309 | false | null | package com.hellfish.evemento.event.comment
import android.content.Context
import android.graphics.Paint
import android.support.v4.graphics.drawable.DrawableCompat
import android.support.v7.widget.*
import android.view.View
import android.widget.TextView
import com.hellfish.evemento.R
import com.hellfish.evemento.RecyclerAdapter
import com.hellfish.evemento.api.Comment
import com.hellfish.evemento.event.guest.CircleColor
import kotlinx.android.synthetic.main.comment_content.view.*
class CommentAdapter(comments: MutableList<Comment>, val editListener: (Comment) -> View.OnClickListener) : RecyclerAdapter<CardView, Comment>(comments), CircleColor {
override fun doOnEmptyOnBindViewHolder(): (view: TextView, context: Context?) -> Unit {
return { view, _ ->
view.text = "No comments yet"
}
}
override fun doOnItemOnBindViewHolder(): (view: CardView, item: Comment, context: Context?) -> Unit {
return { view, item, _ ->
DrawableCompat.setTint(view.commentCircle.drawable, circleColor(item.userId, item.name))
view.commentInitial.text = item.name.first().toUpperCase().toString()
view.commentUserName.text = item.name
view.commentUserName.paintFlags = view.commentUserName.paintFlags or Paint.UNDERLINE_TEXT_FLAG
view.commentMessage.text = item.message
view.setOnClickListener(editListener(item))
}
}
override fun layout(item : Int): Int {
return when (item) {
EMPTY_VIEW -> R.layout.fragment_event_list_empty
else -> R.layout.comment_content
}
}
}
| 0 | Kotlin | 0 | 0 | ab68fd31df52e225f61073cad3f5e736a25caeb6 | 1,638 | evemento | MIT License |
app/src/main/java/org/ergoplatform/android/wallet/SaveWalletFragmentDialog.kt | aslesarenko | 382,865,273 | true | {"Kotlin": 96633, "Java": 28755} | package org.ergoplatform.android.wallet
import android.app.KeyguardManager
import android.content.Context
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.biometric.BiometricManager
import androidx.biometric.BiometricPrompt
import androidx.biometric.BiometricPrompt.PromptInfo
import androidx.navigation.fragment.NavHostFragment
import androidx.navigation.fragment.navArgs
import com.google.android.material.snackbar.Snackbar
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.launch
import org.ergoplatform.android.*
import org.ergoplatform.android.databinding.FragmentSaveWalletDialogBinding
import org.ergoplatform.android.ui.FullScreenFragmentDialog
import org.ergoplatform.android.ui.PasswordDialogCallback
import org.ergoplatform.android.ui.PasswordDialogFragment
import org.ergoplatform.android.ui.navigateSafe
import org.ergoplatform.api.AesEncryptionManager
/**
* Dialog to save a created or restored wallet
*/
class SaveWalletFragmentDialog : FullScreenFragmentDialog(), PasswordDialogCallback {
private var _binding: FragmentSaveWalletDialogBinding? = null
private val binding get() = _binding!!
private val args: SaveWalletFragmentDialogArgs by navArgs()
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View {
// Inflate the layout for this fragment
_binding = FragmentSaveWalletDialogBinding.inflate(inflater, container, false)
return binding.root
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
binding.publicAddress.text = getPublicErgoAddressFromMnemonic(args.mnemonic)
val bmm = BiometricManager.from(requireContext())
val methodDesc =
if (bmm.canAuthenticate(BiometricManager.Authenticators.BIOMETRIC_STRONG) == BiometricManager.BIOMETRIC_SUCCESS)
R.string.device_enc_security_biometric_strong
else if (bmm.canAuthenticate(BiometricManager.Authenticators.BIOMETRIC_WEAK) == BiometricManager.BIOMETRIC_SUCCESS)
R.string.device_enc_security_biometric_weak
else if ((requireContext().getSystemService(Context.KEYGUARD_SERVICE) as KeyguardManager).isDeviceSecure)
R.string.device_enc_security_pass
else R.string.device_enc_security_none
binding.descDeviceEncryption.text =
getString(R.string.desc_save_device_encrypted, getString(methodDesc))
if (methodDesc == R.string.device_enc_security_none) {
binding.buttonSaveDeviceenc.isEnabled = false
}
binding.buttonSavePassenc.setOnClickListener {
PasswordDialogFragment().show(
childFragmentManager,
null
)
}
binding.buttonSaveDeviceenc.setOnClickListener {
showBiometricPrompt()
}
}
fun showBiometricPrompt() {
val promptInfo = PromptInfo.Builder()
.setTitle(getString(R.string.title_authenticate))
.setConfirmationRequired(false)
.setDeviceCredentialAllowed(true)
.build()
val callback = object : BiometricPrompt.AuthenticationCallback() {
override fun onAuthenticationSucceeded(result: BiometricPrompt.AuthenticationResult) {
try {
val secretStorage = AesEncryptionManager.encryptDataOnDevice(
serializeSecrets(args.mnemonic).toByteArray()
)
saveToDb(
ENC_TYPE_DEVICE, secretStorage
)
} catch (t: Throwable) {
Snackbar.make(
requireView(),
getString(R.string.error_device_security, t.message),
Snackbar.LENGTH_LONG
).show()
}
}
}
BiometricPrompt(this, callback).authenticate(promptInfo)
}
private fun saveToDb(encType: Int, secretStorage: ByteArray) {
val publicAddress = getPublicErgoAddressFromMnemonic(args.mnemonic)
GlobalScope.launch(Dispatchers.IO) {
// check if the wallet already exists
val walletDao = AppDatabase.getInstance(requireContext()).walletDao()
val existingWallet = walletDao.loadWalletByAddress(publicAddress)
if (existingWallet != null) {
// update enctype and secret storage
val walletConfig = WalletConfigDbEntity(
existingWallet.id,
existingWallet.displayName,
existingWallet.publicAddress,
encType,
secretStorage
)
walletDao.update(walletConfig)
} else {
val walletConfig =
WalletConfigDbEntity(
0,
getString(R.string.label_wallet_default),
publicAddress,
encType,
secretStorage
)
walletDao.insertAll(walletConfig)
NodeConnector.getInstance().invalidateCache()
}
}
NavHostFragment.findNavController(requireParentFragment())
.navigateSafe(SaveWalletFragmentDialogDirections.actionSaveWalletFragmentDialogToNavigationWallet())
}
override fun onPasswordEntered(password: String?): String? {
if (password == null || password.length < 8) {
return getString(R.string.err_password)
} else {
saveToDb(
ENC_TYPE_PASSWORD,
AesEncryptionManager.encryptData(
password,
serializeSecrets(args.mnemonic).toByteArray()
)
)
return null
}
}
override fun onDestroyView() {
super.onDestroyView()
_binding = null
}
} | 0 | null | 0 | 0 | 989b2548e413e3bfd12377dbabc08076adca9c07 | 6,205 | ergo-wallet-android | Apache License 2.0 |
app/src/main/java/com/kieronquinn/app/discoverkiller/utils/extensions/Extensions+TabLayout.kt | KieronQuinn | 273,963,637 | false | {"Kotlin": 417138, "Java": 18179, "AIDL": 4171} | package com.kieronquinn.app.discoverkiller.utils.extensions
import com.google.android.material.tabs.TabLayout
import kotlinx.coroutines.channels.awaitClose
import kotlinx.coroutines.flow.callbackFlow
fun TabLayout.selectTab(position: Int){
selectTab(getTabAt(position))
}
fun TabLayout.onSelected(includeReselection: Boolean = false) = callbackFlow {
val listener = object: TabLayout.OnTabSelectedListener {
override fun onTabSelected(tab: TabLayout.Tab) {
trySend(tab.position)
}
override fun onTabUnselected(tab: TabLayout.Tab) {
//No-op
}
override fun onTabReselected(tab: TabLayout.Tab) {
if(includeReselection){
trySend(tab.position)
}
}
}
addOnTabSelectedListener(listener)
awaitClose {
removeOnTabSelectedListener(listener)
}
} | 1 | Kotlin | 8 | 302 | 8a59868f5de7493b685c20a38239b08f8c1c9259 | 883 | DiscoverKiller | Apache License 2.0 |
src/main/kotlin/br/com/zupacademy/marciosouza/pixkey/client/bcbapi/dto/CreatePixKeyRequest.kt | mfkldev | 396,927,097 | true | {"Kotlin": 64805} | package br.com.zupacademy.marciosouza.pixkey.client.bcbapi.dto
import br.com.zupacademy.marciosouza.TipoChave
import br.com.zupacademy.marciosouza.pixkey.model.PixKeyModel
data class CreatePixKeyRequest(
val keyType: TipoChave,
val key: String,
val bankAccount: BankAccount,
val owner: Owner
) {
companion object {
fun fromModel(pixKeyModel: PixKeyModel): CreatePixKeyRequest {
return CreatePixKeyRequest(
pixKeyModel.keyType,
pixKeyModel.key,
BankAccount(
pixKeyModel.associatedAccount.bankIspb,
pixKeyModel.associatedAccount.branch,
pixKeyModel.associatedAccount.numberAccount,
AccountType.convert(pixKeyModel.accountType)
),
Owner(
TypeOwner.NATURAL_PERSON,
pixKeyModel.associatedAccount.ownerName,
pixKeyModel.associatedAccount.ownerCpf
))
}
}
fun convertKeyType(): KeyType {
return when (this.keyType) {
TipoChave.CPF -> KeyType.CPF
TipoChave.TELEFONE -> KeyType.PHONE
TipoChave.EMAIL -> KeyType.EMAIL
TipoChave.ALEATORIA -> KeyType.RANDOM
else -> KeyType.CNPJ
}
}
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (javaClass != other?.javaClass) return false
other as CreatePixKeyRequest
if (keyType != other.keyType) return false
if (bankAccount != other.bankAccount) return false
if (owner != other.owner) return false
return true
}
override fun hashCode(): Int {
var result = keyType.hashCode()
result = 31 * result + bankAccount.hashCode()
result = 31 * result + owner.hashCode()
return result
}
} | 0 | Kotlin | 0 | 0 | f0b8badf800c56f26856ebf647776f6959014bc7 | 1,921 | orange-talents-06-template-pix-keymanager-grpc | Apache License 2.0 |
app-scaffold/src/main/kotlin/catchup/app/ui/activity/ImageViewerScreen.kt | ZacSweers | 57,029,623 | false | null | package catchup.app.ui.activity
import androidx.compose.animation.AnimatedVisibility
import androidx.compose.animation.animateContentSize
import androidx.compose.animation.core.animateFloatAsState
import androidx.compose.animation.core.tween
import androidx.compose.animation.fadeIn
import androidx.compose.animation.fadeOut
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.statusBarsPadding
import androidx.compose.material3.Surface
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.DisposableEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.toArgb
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.res.colorResource
import androidx.compose.ui.unit.dp
import androidx.core.view.WindowInsetsControllerCompat
import catchup.app.data.LinkManager
import catchup.app.service.UrlMeta
import catchup.app.ui.activity.FlickToDismissState.FlickGestureState.Dismissed
import catchup.app.ui.activity.ImageViewerScreen.Event
import catchup.app.ui.activity.ImageViewerScreen.Event.Close
import catchup.app.ui.activity.ImageViewerScreen.Event.CopyImage
import catchup.app.ui.activity.ImageViewerScreen.Event.NoOp
import catchup.app.ui.activity.ImageViewerScreen.Event.OpenInBrowser
import catchup.app.ui.activity.ImageViewerScreen.Event.SaveImage
import catchup.app.ui.activity.ImageViewerScreen.Event.ShareImage
import catchup.app.ui.activity.ImageViewerScreen.State
import catchup.base.ui.NavButton
import catchup.base.ui.NavButtonType.CLOSE
import catchup.compose.CatchUpTheme
import catchup.compose.rememberStableCoroutineScope
import catchup.di.AppScope
import coil.request.ImageRequest.Builder
import com.google.accompanist.systemuicontroller.rememberSystemUiController
import com.slack.circuit.backstack.NavDecoration
import com.slack.circuit.codegen.annotations.CircuitInject
import com.slack.circuit.foundation.NavigatorDefaults
import com.slack.circuit.foundation.RecordContentProvider
import com.slack.circuit.foundation.screen
import com.slack.circuit.overlay.LocalOverlayHost
import com.slack.circuit.overlay.OverlayHost
import com.slack.circuit.runtime.CircuitUiEvent
import com.slack.circuit.runtime.CircuitUiState
import com.slack.circuit.runtime.Navigator
import com.slack.circuit.runtime.presenter.Presenter
import com.slack.circuit.runtime.screen.Screen
import com.slack.circuitx.overlays.BottomSheetOverlay
import dagger.assisted.Assisted
import dagger.assisted.AssistedFactory
import dagger.assisted.AssistedInject
import dev.zacsweers.catchup.app.scaffold.R
import kotlinx.collections.immutable.ImmutableList
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.launch
import kotlinx.parcelize.Parcelize
import me.saket.telephoto.zoomable.ZoomSpec
import me.saket.telephoto.zoomable.coil.ZoomableAsyncImage
import me.saket.telephoto.zoomable.rememberZoomableImageState
import me.saket.telephoto.zoomable.rememberZoomableState
@Parcelize
data class ImageViewerScreen(
val id: String,
val url: String,
val isBitmap: Boolean,
val alias: String?,
val sourceUrl: String,
) : Screen {
data class State(
val id: String,
val url: String,
val alias: String?,
val sourceUrl: String,
val isBitmap: Boolean,
val eventSink: (Event) -> Unit,
) : CircuitUiState
sealed interface Event : CircuitUiEvent {
data object Close : Event
data object NoOp : Event // Weird but necessary because of the reuse in bottom sheet
data object ShareImage : Event
data object CopyImage : Event
data object SaveImage : Event
data class OpenInBrowser(val url: String) : Event
}
}
class ImageViewerPresenter
@AssistedInject
constructor(
@Assisted private val screen: ImageViewerScreen,
@Assisted private val navigator: Navigator,
private val linkManager: LinkManager
) : Presenter<State> {
@CircuitInject(ImageViewerScreen::class, AppScope::class)
@AssistedFactory
fun interface Factory {
fun create(
screen: ImageViewerScreen,
navigator: Navigator,
): ImageViewerPresenter
}
@Composable
override fun present(): State {
val context = LocalContext.current
val accentColor = colorResource(R.color.colorAccent).toArgb()
val scope = rememberStableCoroutineScope()
return State(
id = screen.id,
url = screen.url,
alias = screen.alias,
isBitmap = screen.isBitmap,
sourceUrl = screen.sourceUrl,
) { event ->
// TODO finish implementing these. Also why is copying an image on android so terrible in
// 2023.
when (event) {
Close -> navigator.pop()
CopyImage -> {}
is OpenInBrowser -> {
scope.launch { linkManager.openUrl(UrlMeta(event.url, accentColor, context)) }
}
SaveImage -> {}
ShareImage -> {}
NoOp -> {}
}
}
}
}
@CircuitInject(ImageViewerScreen::class, AppScope::class)
@Composable
fun ImageViewer(state: State, modifier: Modifier = Modifier) {
var showChrome by remember { mutableStateOf(true) }
// There's no alternative for this yet
@Suppress("DEPRECATION") val systemUiController = rememberSystemUiController()
systemUiController.isSystemBarsVisible = showChrome
DisposableEffect(systemUiController) {
val originalSystemBarsBehavior = systemUiController.systemBarsBehavior
// Set BEHAVIOR_SHOW_TRANSIENT_BARS_BY_SWIPE so the UI doesn't jump when it hides
systemUiController.systemBarsBehavior =
WindowInsetsControllerCompat.BEHAVIOR_SHOW_TRANSIENT_BARS_BY_SWIPE
onDispose {
// TODO this is too late for some reason
systemUiController.isSystemBarsVisible = true
systemUiController.systemBarsBehavior = originalSystemBarsBehavior
}
}
CatchUpTheme(useDarkTheme = true) {
val backgroundAlpha: Float by
animateFloatAsState(targetValue = 1f, animationSpec = tween(), label = "backgroundAlpha")
Surface(
modifier.fillMaxSize().animateContentSize(),
color = Color.Black.copy(alpha = backgroundAlpha),
contentColor = Color.White
) {
Box(Modifier.fillMaxSize()) {
// Image + scrim
val dismissState = rememberFlickToDismissState()
if (dismissState.gestureState is Dismissed) {
state.eventSink(Close)
}
// TODO bind scrim with flick. animate scrim out after flick finishes? Or with flick?
FlickToDismiss(state = dismissState) {
val overlayHost = LocalOverlayHost.current
val scope = rememberStableCoroutineScope()
val zoomableState = rememberZoomableState(ZoomSpec(maxZoomFactor = 2f))
val imageState = rememberZoomableImageState(zoomableState)
// TODO loading loading indicator if there's no memory cached alias
ZoomableAsyncImage(
model =
Builder(LocalContext.current)
.data(state.url)
.apply { state.alias?.let(::placeholderMemoryCacheKey) }
.build(),
contentDescription = "TODO",
modifier = Modifier.fillMaxSize(),
state = imageState,
onClick = { showChrome = !showChrome },
onLongClick = { launchShareSheet(scope, overlayHost, state) },
)
}
// TODO pick color based on if image is underneath it or not. Similar to badges
AnimatedVisibility(
showChrome,
enter = fadeIn(),
exit = fadeOut(),
) {
NavButton(
Modifier.align(Alignment.TopStart).padding(16.dp).statusBarsPadding(),
CLOSE,
) {
state.eventSink(Close)
}
}
}
}
}
}
private fun launchShareSheet(
scope: CoroutineScope,
overlayHost: OverlayHost,
state: State,
) =
scope.launch {
val result =
overlayHost.show(
BottomSheetOverlay<Unit, Event>(Unit, onDismiss = { NoOp }) { _, navigator ->
Column {
// TODO icons?
Text(
modifier =
Modifier.fillMaxWidth().clickable { navigator.finish(ShareImage) }.padding(16.dp),
text = "Share"
)
Text(
modifier =
Modifier.fillMaxWidth().clickable { navigator.finish(SaveImage) }.padding(16.dp),
text = "Save"
)
Text(
modifier =
Modifier.fillMaxWidth().clickable { navigator.finish(CopyImage) }.padding(16.dp),
text = "Copy"
)
Text(
modifier =
Modifier.fillMaxWidth()
.clickable { navigator.finish(OpenInBrowser(state.url)) }
.padding(16.dp),
text = "Open in Browser"
)
}
}
)
state.eventSink(result)
}
// TODO
// generalize this when there's a factory pattern for it in Circuit
// shared element transitions?
class ImageViewerAwareNavDecoration : NavDecoration {
@Composable
override fun <T> DecoratedContent(
args: ImmutableList<T>,
backStackDepth: Int,
modifier: Modifier,
content: @Composable (T) -> Unit
) {
val arg = args.first()
val decoration =
if (arg is RecordContentProvider && arg.record.screen is ImageViewerScreen) {
NavigatorDefaults.EmptyDecoration
} else {
NavigatorDefaults.DefaultDecoration
}
decoration.DecoratedContent(args, backStackDepth, modifier, content)
}
}
| 37 | null | 205 | 1,980 | 3ac348452590f8d9ba02c3e6163fb210df9e37f4 | 10,048 | CatchUp | Apache License 2.0 |
core/src/main/java/tmidev/core/data/repository/CharactersRepository.kt | tminet | 437,921,880 | false | null | package tmidev.core.data.repository
import androidx.paging.PagingSource
import tmidev.core.domain.model.Character
import tmidev.core.domain.model.Comic
import tmidev.core.domain.model.Event
interface CharactersRepository {
fun getCharacters(query: String): PagingSource<Int, Character>
suspend fun getComics(characterId: Int): List<Comic>
suspend fun getEvents(characterId: Int): List<Event>
} | 0 | Kotlin | 1 | 0 | 1cddbd1e69be453d5749957c397e3c849cde9f69 | 409 | MarvelHeroes | MIT License |
src/main/kotlin/com/melowetty/hsepermhelper/extension/UserExtensions.kt | HSE-Perm-Helper | 682,010,195 | false | {"Kotlin": 155109, "Dockerfile": 102} | package com.melowetty.hsepermhelper.extension
import com.melowetty.hsepermhelper.domain.dto.SettingsDto
import com.melowetty.hsepermhelper.domain.dto.UserDto
import com.melowetty.hsepermhelper.domain.entity.SettingsEntity
import com.melowetty.hsepermhelper.domain.entity.UserEntity
import com.melowetty.hsepermhelper.extension.HideLessonExtension.Companion.toDto
import com.melowetty.hsepermhelper.extension.HideLessonExtension.Companion.toEntity
class UserExtensions {
companion object {
fun UserEntity.toDto(): UserDto {
return UserDto(
id = id,
telegramId = telegramId,
settings = settings.toDto(),
)
}
fun UserDto.toEntity(): UserEntity {
return UserEntity(
id = id,
telegramId = telegramId,
settings = settings.toEntity(),
)
}
fun SettingsDto.toEntity(): SettingsEntity {
return SettingsEntity(
id = id,
group = group,
subGroup = subGroup,
isEnabledNewScheduleNotifications = isEnabledNewScheduleNotifications,
isEnabledChangedScheduleNotifications = isEnabledChangedScheduleNotifications,
isEnabledComingLessonsNotifications = isEnabledComingLessonsNotifications,
hiddenLessons = hiddenLessons.map { it.toEntity() }.toHashSet()
)
}
fun SettingsEntity.toDto(): SettingsDto {
return SettingsDto(
id = id,
group = group,
subGroup = subGroup,
isEnabledNewScheduleNotifications = isEnabledNewScheduleNotifications,
isEnabledChangedScheduleNotifications = isEnabledChangedScheduleNotifications,
isEnabledComingLessonsNotifications = isEnabledComingLessonsNotifications,
hiddenLessons = hiddenLessons.map { it.toDto() }.toHashSet(),
)
}
fun Iterable<UserEntity>.getGroupedEntityBySettingsUsers() =
this
.groupBy { "${it.settings.group} ${it.settings.subGroup}} ${it.settings.hiddenLessons}" }
fun Iterable<UserDto>.getGroupedBySettingsUsers() =
this
.groupBy { "${it.settings.group} ${it.settings.subGroup} ${it.settings.hiddenLessons}" }
}
} | 1 | Kotlin | 0 | 0 | b51190b63f148e3e9607cb1b9918fe046f8a34f6 | 2,408 | main-backend | MIT License |
ktor-hosts/ktor-test-host/src/org/jetbrains/ktor/testing/HostTestSuite.kt | hallefy | 94,839,121 | false | null | package org.jetbrains.ktor.testing
import org.jetbrains.ktor.application.*
import org.jetbrains.ktor.cio.*
import org.jetbrains.ktor.content.*
import org.jetbrains.ktor.features.*
import org.jetbrains.ktor.host.*
import org.jetbrains.ktor.http.*
import org.jetbrains.ktor.logging.*
import org.jetbrains.ktor.request.*
import org.jetbrains.ktor.response.*
import org.jetbrains.ktor.routing.*
import org.jetbrains.ktor.util.*
import org.junit.*
import org.junit.runners.model.*
import java.io.*
import java.security.*
import java.util.*
import java.util.concurrent.*
import java.util.concurrent.atomic.*
import java.util.zip.*
import kotlin.concurrent.*
import kotlin.test.*
abstract class HostTestSuite<H : ApplicationHost> : HostTestBase<H>() {
@Test
fun testTextContent() {
createAndStartServer {
handle {
call.respond(TextContent("test", ContentType.Text.Plain.withCharset(Charsets.UTF_8)))
}
}
withUrl("/") {
val fields = headerFields.toMutableMap()
fields.remove(null) // Remove response line HTTP/1.1 200 OK since it's not a header
fields.remove("Date") // Do not check for Date field since it's unstable
// Check content type manually because spacing and case can be different per host
val contentType = fields.remove("Content-Type")?.single()
assertNotNull(contentType) // Content-Type should be present
val parsedContentType = ContentType.parse(contentType!!) // It should parse
assertEquals(ContentType.Text.Plain, parsedContentType.withoutParameters())
assertEquals(Charsets.UTF_8, parsedContentType.charset())
assertEquals(mapOf(
"Connection" to listOf("keep-alive"),
"Content-Length" to listOf("4")), fields)
assertEquals(200, responseCode)
assertEquals("test", inputStream.reader().use { it.readText() })
}
withUrlHttp2("/") {
// assertEquals("test", contentAsString)
}
}
@Test
fun testStream() {
createAndStartServer {
handle {
call.respondWrite {
write("ABC")
flush()
write("123")
flush()
}
}
}
withUrl("/") {
assertEquals(200, responseCode)
assertEquals("ABC123", inputStream.reader().use { it.readText() })
}
}
@Test
fun testRequestContentFormData() {
createAndStartServer {
handle {
call.respond(call.request.receive<ValuesMap>().formUrlEncode())
}
}
withUrl("/") {
doOutput = true
requestMethod = "POST"
outputStream.bufferedWriter().use {
valuesOf("a" to listOf("1")).formUrlEncodeTo(it)
}
assertEquals(200, responseCode)
assertEquals("a=1", inputStream.reader().use { it.readText() })
}
withUrl("/") {
doOutput = false
requestMethod = "GET"
assertEquals(200, responseCode)
assertEquals("", inputStream.reader().use { it.readText() })
}
}
@Test
fun testStreamNoFlush() {
createAndStartServer {
handle {
call.respondWrite {
write("ABC")
write("123")
}
}
}
withUrl("/") {
assertEquals(200, responseCode)
assertEquals("ABC123", inputStream.reader().use { it.readText() })
}
}
@Test
fun testSendTextWithContentType() {
createAndStartServer {
handle {
call.respondText("Hello", ContentType.Text.Plain)
}
}
withUrl("/") {
assertEquals(200, responseCode)
assertEquals("Hello", inputStream.reader().use { it.readText() })
assertTrue(ContentType.parse(getHeaderField(HttpHeaders.ContentType)).match(ContentType.Text.Plain))
}
}
@Test
fun testRedirect() {
createAndStartServer {
handle {
call.respondRedirect("http://localhost:${call.request.port()}/page", true)
}
}
withUrl("/") {
assertEquals(HttpStatusCode.MovedPermanently.value, responseCode)
}
}
@Test
fun testRedirectFromInterceptor() {
createAndStartServer {
application.intercept(ApplicationCallPipeline.Infrastructure) {
call.respondRedirect("/2", true)
}
}
withUrl("/1/") {
assertEquals(HttpStatusCode.MovedPermanently.value, responseCode)
assertEquals("/2", getHeaderField(HttpHeaders.Location))
}
}
@Test
fun testHeader() {
createAndStartServer {
handle {
call.response.headers.append(HttpHeaders.ETag, "test-etag")
call.respondText("Hello", ContentType.Text.Plain)
}
}
withUrl("/") {
assertEquals(200, responseCode)
assertEquals("test-etag", getHeaderField(HttpHeaders.ETag))
}
}
@Test
fun testCookie() {
createAndStartServer {
handle {
call.response.cookies.append("k1", "v1")
call.respondText("Hello", ContentType.Text.Plain)
}
}
withUrl("/") {
assertEquals(200, responseCode)
assertEquals("k1=v1; \$x-enc=URI_ENCODING", getHeaderField(HttpHeaders.SetCookie))
}
}
@Test
fun testStaticServe() {
createAndStartServer {
route("/files/") {
serveClasspathResources("org/jetbrains/ktor/testing")
}
}
withUrl("/files/${HostTestSuite::class.simpleName}.class") {
val bytes = inputStream.readBytes(8192)
assertNotEquals(0, bytes.size)
// class file signature
assertEquals(0xca, bytes[0].toInt() and 0xff)
assertEquals(0xfe, bytes[1].toInt() and 0xff)
assertEquals(0xba, bytes[2].toInt() and 0xff)
assertEquals(0xbe, bytes[3].toInt() and 0xff)
}
assertFailsWith(FileNotFoundException::class) {
withUrl("/files/${HostTestSuite::class.simpleName}.class2") {
inputStream.readBytes()
}
}
assertFailsWith(FileNotFoundException::class) {
withUrl("/wefwefwefw") {
inputStream.readBytes()
}
}
}
@Test
fun testStaticServeFromDir() {
val targetClasses = listOf(File("target/classes"), File("ktor-core/target/classes")).first(File::exists)
val file = targetClasses.walkBottomUp().filter { it.extension == "class" }.first()
testLog.trace("test file is $file")
createAndStartServer {
route("/files/") {
serveFileSystem(targetClasses)
}
}
withUrl("/files/${file.toRelativeString(targetClasses).urlPath()}") {
val bytes = inputStream.readBytes(8192)
assertNotEquals(0, bytes.size)
// class file signature
assertEquals(0xca, bytes[0].toInt() and 0xff)
assertEquals(0xfe, bytes[1].toInt() and 0xff)
assertEquals(0xba, bytes[2].toInt() and 0xff)
assertEquals(0xbe, bytes[3].toInt() and 0xff)
}
assertFailsWith(FileNotFoundException::class) {
withUrl("/files/${file.toRelativeString(targetClasses).urlPath()}2") {
inputStream.readBytes()
}
}
assertFailsWith(FileNotFoundException::class) {
withUrl("/wefwefwefw") {
inputStream.readBytes()
}
}
}
@Test
fun testLocalFileContent() {
val file = listOf(File("src"), File("ktor-core/src")).first { it.exists() }.walkBottomUp().filter { it.extension == "kt" }.first()
testLog.trace("test file is $file")
createAndStartServer {
handle {
call.respond(LocalFileContent(file))
}
}
withUrl("/") {
assertEquals(200, responseCode)
assertEquals(file.readText(), inputStream.reader().use { it.readText() })
}
}
@Test
fun testLocalFileContentWithCompression() {
val file = listOf(File("src"), File("ktor-core/src")).first { it.exists() }.walkBottomUp().filter { it.extension == "kt" }.first()
testLog.trace("test file is $file")
createAndStartServer {
application.install(Compression)
handle {
call.respond(LocalFileContent(file))
}
}
withUrl("/") {
addRequestProperty(HttpHeaders.AcceptEncoding, "gzip")
assertEquals(200, responseCode)
assertEquals(file.readText(), GZIPInputStream(inputStream).reader().use { it.readText() })
assertEquals("gzip", getHeaderField(HttpHeaders.ContentEncoding))
}
}
@Test
fun testLocalFileContentRange() {
val file = listOf(File("src"), File("ktor-core/src")).first { it.exists() }.walkBottomUp().filter { it.extension == "kt" && it.reader().use { it.read().toChar() == 'p' } }.first()
testLog.trace("test file is $file")
createAndStartServer {
application.install(PartialContentSupport)
handle {
call.respond(LocalFileContent(file))
}
}
withUrl("/") {
setRequestProperty(HttpHeaders.Range, RangesSpecifier(RangeUnits.Bytes, listOf(ContentRange.Bounded(0, 0))).toString())
assertEquals(HttpStatusCode.PartialContent.value, responseCode)
assertEquals("p", inputStream.reader().use { it.readText() })
}
withUrl("/") {
setRequestProperty(HttpHeaders.Range, RangesSpecifier(RangeUnits.Bytes, listOf(ContentRange.Bounded(1, 2))).toString())
assertEquals(HttpStatusCode.PartialContent.value, responseCode)
assertEquals("ac", inputStream.reader().use { it.readText() })
}
}
@Test
fun testLocalFileContentRangeWithCompression() {
val file = listOf(File("src"), File("ktor-core/src")).first { it.exists() }.walkBottomUp().filter { it.extension == "kt" && it.reader().use { it.read().toChar() == 'p' } }.first()
testLog.trace("test file is $file")
createAndStartServer {
application.install(Compression)
application.install(PartialContentSupport)
handle {
call.respond(LocalFileContent(file))
}
}
withUrl("/") {
addRequestProperty(HttpHeaders.AcceptEncoding, "gzip")
setRequestProperty(HttpHeaders.Range, RangesSpecifier(RangeUnits.Bytes, listOf(ContentRange.Bounded(0, 0))).toString())
assertEquals(HttpStatusCode.PartialContent.value, responseCode)
assertEquals("p", inputStream.reader().use { it.readText() }) // it should be no compression if range requested
}
}
@Test
fun testJarFileContent() {
createAndStartServer {
handle {
call.respond(call.resolveClasspathWithPath("java/util", "/ArrayList.class")!!)
}
}
withUrl("/") {
assertEquals(200, responseCode)
inputStream.buffered().use { it.readBytes() }.let { bytes ->
assertNotEquals(0, bytes.size)
// class file signature
assertEquals(0xca, bytes[0].toInt() and 0xff)
assertEquals(0xfe, bytes[1].toInt() and 0xff)
assertEquals(0xba, bytes[2].toInt() and 0xff)
assertEquals(0xbe, bytes[3].toInt() and 0xff)
}
}
}
@Test
fun testURIContent() {
createAndStartServer {
handle {
call.respond(URIFileContent(this::class.java.classLoader.getResources("java/util/ArrayList.class").toList().first()))
}
}
withUrl("/") {
assertEquals(200, responseCode)
inputStream.buffered().use { it.readBytes() }.let { bytes ->
assertNotEquals(0, bytes.size)
// class file signature
assertEquals(0xca, bytes[0].toInt() and 0xff)
assertEquals(0xfe, bytes[1].toInt() and 0xff)
assertEquals(0xba, bytes[2].toInt() and 0xff)
assertEquals(0xbe, bytes[3].toInt() and 0xff)
}
}
}
@Test
fun testURIContentLocalFile() {
val file = listOf(File("target/classes"), File("ktor-core/target/classes")).first { it.exists() }.walkBottomUp().filter { it.extension == "class" }.first()
testLog.trace("test file is $file")
createAndStartServer {
handle {
call.respond(URIFileContent(file.toURI()))
}
}
withUrl("/") {
assertEquals(200, responseCode)
inputStream.buffered().use { it.readBytes() }.let { bytes ->
assertNotEquals(0, bytes.size)
// class file signature
assertEquals(0xca, bytes[0].toInt() and 0xff)
assertEquals(0xfe, bytes[1].toInt() and 0xff)
assertEquals(0xba, bytes[2].toInt() and 0xff)
assertEquals(0xbe, bytes[3].toInt() and 0xff)
}
}
}
@Test
fun testPathComponentsDecoding() {
createAndStartServer {
get("/a%20b") {
call.respondText("space")
}
get("/a+b") {
call.respondText("plus")
}
}
withUrl("/a%20b") {
assertEquals(200, responseCode)
assertEquals("space", inputStream.bufferedReader().use { it.readText() })
}
withUrl("/a+b") {
assertEquals(200, responseCode)
assertEquals("plus", inputStream.bufferedReader().use { it.readText() })
}
}
@Test
fun testFormUrlEncoded() {
createAndStartServer {
post("/") {
call.respondText("${call.parameters["urlp"]},${call.request.receive<ValuesMap>()["formp"]}")
}
}
withUrl("/?urlp=1") {
requestMethod = "POST"
doInput = true
doOutput = true
setRequestProperty(HttpHeaders.ContentType, ContentType.Application.FormUrlEncoded.toString())
outputStream.use { out ->
out.writer().apply {
append("formp=2")
flush()
}
}
assertEquals(HttpStatusCode.OK.value, responseCode)
assertEquals("1,2", inputStream.bufferedReader().use { it.readText() })
}
}
@Test
fun testRequestBodyAsyncEcho() {
createAndStartServer {
route("/echo") {
handle {
val buffer = ByteBufferWriteChannel()
call.request.receive<ReadChannel>().copyTo(buffer)
call.respond(object : FinalContent.ReadChannelContent() {
override val headers: ValuesMap get() = ValuesMap.Empty
override fun readFrom() = buffer.toByteArray().toReadChannel()
})
}
}
}
withUrl("/echo") {
requestMethod = "POST"
doInput = true
doOutput = true
setRequestProperty(HttpHeaders.ContentType, ContentType.Text.Plain.toString())
outputStream.use { out ->
out.writer().apply {
append("POST test\n")
append("Another line")
flush()
}
}
assertEquals(200, responseCode)
assertEquals("POST test\nAnother line", inputStream.bufferedReader().use { it.readText() })
}
}
@Test
fun testEchoBlocking() {
createAndStartServer {
post("/") {
val text = call.request.receive<ReadChannel>().toInputStream().bufferedReader().readText()
call.response.status(HttpStatusCode.OK)
call.respond(text)
}
}
withUrl("/") {
requestMethod = "POST"
doInput = true
doOutput = true
setRequestProperty(HttpHeaders.ContentType, ContentType.Text.Plain.toString())
outputStream.use { out ->
out.writer().apply {
append("POST content")
flush()
}
}
assertEquals(200, responseCode)
assertEquals("POST content", inputStream.bufferedReader().use { it.readText() })
}
}
@Test
fun testMultipartFileUpload() {
createAndStartServer {
post("/") {
val response = StringBuilder()
call.request.receive<MultiPartData>().parts.sortedBy { it.partName }.forEach { part ->
when (part) {
is PartData.FormItem -> response.append("${part.partName}=${part.value}\n")
is PartData.FileItem -> response.append("file:${part.partName},${part.originalFileName},${part.streamProvider().bufferedReader().readText()}\n")
}
part.dispose()
}
call.respondText(response.toString())
}
}
withUrl("/") {
requestMethod = "POST"
doInput = true
doOutput = true
setRequestProperty(HttpHeaders.ContentType, ContentType.MultiPart.FormData.withParameter("boundary", "***bbb***").toString())
outputStream.bufferedWriter(Charsets.ISO_8859_1).let { out ->
out.apply {
append("\r\n")
append("--***bbb***\r\n")
append("Content-Disposition: form-data; name=\"a story\"\r\n")
append("\r\n")
append("Hi user. The snake you gave me for free ate all the birds. Please take it back ASAP.\r\n")
append("--***bbb***\r\n")
append("Content-Disposition: form-data; name=\"attachment\"; filename=\"original.txt\"\r\n")
append("Content-Type: text/plain\r\n")
append("\r\n")
append("File content goes here\r\n")
append("--***bbb***--\r\n")
flush()
}
}
assertEquals(200, responseCode)
assertEquals("a story=Hi user. The snake you gave me for free ate all the birds. Please take it back ASAP.\nfile:attachment,original.txt,File content goes here\n", inputStream.bufferedReader().use { it.readText() })
}
}
@Test
fun testRequestTwiceNoKeepAlive() {
createAndStartServer {
get("/") {
call.respond(TextContent("Text", ContentType.Text.Plain))
}
}
withUrl("/") {
setRequestProperty(HttpHeaders.Connection, "close")
assertEquals("Text", inputStream.bufferedReader().use { it.readText() })
}
withUrl("/") {
setRequestProperty(HttpHeaders.Connection, "close")
assertEquals("Text", inputStream.bufferedReader().use { it.readText() })
}
}
@Test
fun testRequestTwiceWithKeepAlive() {
createAndStartServer {
get("/") {
call.respond(TextContent("Text", ContentType.Text.Plain))
}
}
withUrl("/") {
setRequestProperty(HttpHeaders.Connection, "keep-alive")
assertEquals(200, responseCode)
assertEquals("Text", inputStream.bufferedReader().use { it.readText() })
}
withUrl("/") {
setRequestProperty(HttpHeaders.Connection, "keep-alive")
assertEquals(200, responseCode)
assertEquals("Text", inputStream.bufferedReader().use { it.readText() })
}
}
@Test
fun testRequestContentString() {
createAndStartServer {
post("/") {
call.respond(call.request.receive<String>())
}
}
withUrl("/") {
requestMethod = "POST"
doOutput = true
setRequestProperty(HttpHeaders.ContentType, ContentType.Text.Plain.toString())
outputStream.use {
it.write("Hello".toByteArray())
}
assertEquals(200, responseCode)
assertEquals("Hello", inputStream.reader().use { it.readText() })
}
}
@Test
fun testRepeatRequest() {
createAndStartServer {
get("/") {
call.respond("OK ${call.request.queryParameters["i"]}")
}
}
for (i in 1..100) {
withUrl("/?i=$i") {
assertEquals(200, responseCode)
assertEquals("OK $i", inputStream.reader().use { it.readText() })
}
}
}
@Test
fun testRequestContentInputStream() {
createAndStartServer {
post("/") {
call.respond(call.request.receive<InputStream>().reader().readText())
}
}
withUrl("/") {
requestMethod = "POST"
doOutput = true
setRequestProperty(HttpHeaders.ContentType, ContentType.Text.Plain.toString())
outputStream.use {
it.write("Hello".toByteArray())
}
assertEquals(200, responseCode)
assertEquals("Hello", inputStream.reader().use { it.readText() })
}
}
@Test
fun testStatusCodeDirect() {
createAndStartServer {
get("/") {
call.response.status(HttpStatusCode.Found)
call.respond("Hello")
}
}
withUrl("/") {
assertEquals(HttpStatusCode.Found.value, responseCode)
assertEquals("Hello", inputStream.reader().use { it.readText() })
}
}
@Test
fun testStatusCodeViaResponseObject() {
var completed = false
createAndStartServer {
get("/") {
call.respond(HttpStatusCode.Found)
}
}
withUrl("/") {
assertEquals(HttpStatusCode.Found.value, responseCode)
completed = true
}
assertTrue(completed)
}
@Test
fun testStatusCodeViaResponseObject2() {
createAndStartServer {
get("/") {
call.respond(HttpStatusContent(HttpStatusCode.Found, "Hello"))
}
}
withUrl("/") {
assertEquals(HttpStatusCode.Found.value, responseCode)
}
}
@Test
fun test404() {
createAndStartServer {
}
withUrl("/") {
assertEquals(HttpStatusCode.NotFound.value, responseCode)
}
withUrl("/aaaa") {
assertEquals(HttpStatusCode.NotFound.value, responseCode)
}
}
@Test
fun testProxyHeaders() {
createAndStartServer {
install(XForwardedHeadersSupport)
get("/") {
call.respond(call.url { })
}
}
withUrl("/") { port ->
setRequestProperty(HttpHeaders.XForwardedHost, "my-host:90")
val expectedProto = if (port == sslPort) "https" else "http"
assertEquals("$expectedProto://my-host:90/", inputStream.reader().use { it.readText() })
}
withUrl("/") { port ->
setRequestProperty(HttpHeaders.XForwardedHost, "my-host")
val expectedProto = if (port == sslPort) "https" else "http"
assertEquals("$expectedProto://my-host/", inputStream.reader().use { it.readText() })
}
withUrl("/") {
setRequestProperty(HttpHeaders.XForwardedHost, "my-host:90")
setRequestProperty(HttpHeaders.XForwardedProto, "https")
assertEquals("https://my-host:90/", inputStream.reader().use { it.readText() })
}
withUrl("/") {
setRequestProperty(HttpHeaders.XForwardedHost, "my-host")
setRequestProperty(HttpHeaders.XForwardedProto, "https")
assertEquals("https://my-host/", inputStream.reader().use { it.readText() })
}
}
@Test
fun testHostRequestParts() {
createAndStartServer {
get("/path/1") {
call.respond(call.request.path())
}
get("/document/1") {
call.respond(call.request.document())
}
get("/queryString/1") {
call.respond(call.request.queryString())
}
get("/uri/1") {
call.respond(call.request.uri)
}
}
withUrl("/path/1?p=v") {
assertEquals("/path/1", inputStream.reader().use { it.readText() })
}
withUrl("/path/1?") {
assertEquals("/path/1", inputStream.reader().use { it.readText() })
}
withUrl("/path/1") {
assertEquals("/path/1", inputStream.reader().use { it.readText() })
}
withUrl("/document/1?p=v") {
assertEquals("1", inputStream.reader().use { it.readText() })
}
withUrl("/document/1?") {
assertEquals("1", inputStream.reader().use { it.readText() })
}
withUrl("/document/1") {
assertEquals("1", inputStream.reader().use { it.readText() })
}
withUrl("/queryString/1?p=v") {
assertEquals("p=v", inputStream.reader().use { it.readText() })
}
withUrl("/queryString/1?") {
assertEquals("", inputStream.reader().use { it.readText() })
}
withUrl("/queryString/1") {
assertEquals("", inputStream.reader().use { it.readText() })
}
withUrl("/uri/1?p=v") {
assertEquals("/uri/1?p=v", inputStream.reader().use { it.readText() })
}
withUrl("/uri/1?") {
assertEquals("/uri/1?", inputStream.reader().use { it.readText() })
}
withUrl("/uri/1") {
assertEquals("/uri/1", inputStream.reader().use { it.readText() })
}
}
@Test
fun testRequestParameters() {
createAndStartServer {
get("/*") {
call.respond(call.request.queryParameters.getAll(call.request.path().removePrefix("/")).toString())
}
}
withUrl("/single?single=value") {
assertEquals("[value]", inputStream.reader().use { it.readText() })
}
withUrl("/multiple?multiple=value1&multiple=value2") {
assertEquals("[value1, value2]", inputStream.reader().use { it.readText() })
}
withUrl("/missing") {
assertEquals("null", inputStream.reader().use { it.readText() })
}
}
@Test
fun testCallLoggerOnError() {
val message = "expected, ${nextNonce()}"
val collected = CopyOnWriteArrayList<Throwable>()
createAndStartServer({
val delegate = SLF4JApplicationLog("embedded")
log = object : ApplicationLog by delegate {
override val name = "DummyLogger"
override fun fork(name: String) = this
override fun error(message: String, exception: Throwable?) {
if (exception != null) {
collected.add(exception)
}
}
}
}, {
get("/") {
throw ExpectedException(message)
}
})
withUrl("/") {
assertFailsWith<IOException> {
inputStream.reader().use { it.readText() }
}
assertEquals(message, collected.single { it is ExpectedException }.message)
collected.clear()
}
}
@Test(timeout = 30000L)
fun testBlockingConcurrency() {
//println()
val completed = AtomicInteger(0)
createAndStartServer({
executorServiceBuilder = {
Executors.newScheduledThreadPool(3)
}
}, {
get("/{index}") {
val index = call.parameters["index"]!!.toInt()
call.respondWrite {
//print("[$index] ")
try {
append("OK:$index\n")
} finally {
completed.incrementAndGet()
}
}
}
})
val count = 100
val latch = CountDownLatch(count)
val errors = CopyOnWriteArrayList<Throwable>()
val random = Random()
for (i in 1..latch.count) {
thread {
try {
withUrl("/$i") {
//setRequestProperty("Connection", "close")
inputStream.reader().use { reader ->
val firstByte = reader.read()
if (firstByte == -1) {
//println("Premature end of response stream at iteration $i")
fail("Premature end of response stream at iteration $i")
} else {
assertEquals('O', firstByte.toChar())
Thread.sleep(random.nextInt(1000).toLong())
assertEquals("K:$i\n", reader.readText())
}
}
}
} catch (t: Throwable) {
errors += t
} finally {
latch.countDown()
}
}
}
latch.await()
if (errors.isNotEmpty()) {
throw MultipleFailureException(errors)
}
assertEquals(count * 2, completed.get())
}
@Test
fun testBigFile() {
val file = File("target/large-file.dat")
val rnd = Random()
file.bufferedWriter().use { out ->
for (line in 1..30000) {
for (col in 1..(30 + rnd.nextInt(40))) {
out.append('a' + rnd.nextInt(25))
}
out.append('\n')
}
}
val originalSha1 = file.inputStream().use { it.sha1() }
createAndStartServer {
get("/file") { call ->
call.respond(LocalFileContent(file))
}
}
withUrl("/file") {
assertEquals(originalSha1, inputStream.sha1())
}
}
private fun String.urlPath() = replace("\\", "/")
private class ExpectedException(message: String) : RuntimeException(message)
private fun InputStream.sha1(): String {
val md = MessageDigest.getInstance("SHA1")
val bytes = ByteArray(8192)
do {
val rc = read(bytes)
if (rc == -1) {
break
}
md.update(bytes, 0, rc)
} while (true)
return hex(md.digest())
}
} | 0 | null | 0 | 1 | b5dcbe5b740c2d25c7704104e01e0a01bf53d675 | 31,653 | ktor | Apache License 2.0 |
vector/src/main/java/im/vector/riotx/core/extensions/EditText.kt | Dominaezzz | 198,261,955 | true | {"Gradle": 5, "Markdown": 7, "Java Properties": 2, "Shell": 14, "Text": 3, "Ignore List": 4, "Batchfile": 1, "YAML": 2, "Proguard": 3, "Java": 6, "XML": 427, "Kotlin": 1004, "JSON": 5, "HTML": 1} | /*
* Copyright 2019 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 im.vector.riotx.core.extensions
import android.text.Editable
import android.text.InputType
import android.text.TextWatcher
import android.view.MotionEvent
import android.view.View
import android.view.inputmethod.EditorInfo
import android.widget.EditText
import im.vector.riotx.R
fun EditText.setupAsSearch() {
addTextChangedListener(object : TextWatcher {
override fun afterTextChanged(editable: Editable?) {
val clearIcon = if (editable?.isNotEmpty() == true) R.drawable.ic_clear_white else 0
setCompoundDrawablesWithIntrinsicBounds(0, 0, clearIcon, 0)
}
override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) = Unit
override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) = Unit
})
maxLines = 1
inputType = InputType.TYPE_CLASS_TEXT
imeOptions = EditorInfo.IME_ACTION_SEARCH
setOnEditorActionListener { _, actionId, event ->
var consumed = false
if (actionId == EditorInfo.IME_ACTION_SEARCH) {
hideKeyboard()
consumed = true
}
consumed
}
setOnTouchListener(View.OnTouchListener { _, event ->
if (event.action == MotionEvent.ACTION_UP) {
if (event.rawX >= (this.right - this.compoundPaddingRight)) {
text = null
return@OnTouchListener true
}
}
return@OnTouchListener false
})
}
| 0 | Kotlin | 0 | 0 | df6080b1da93039784c1177bab345cbf744c3756 | 2,071 | riotX-android | Apache License 2.0 |
core/src/test/kotlin/tests/model/DatabasesTest.kt | seratch | 367,397,489 | false | null | package tests.model
import kotlin.test.assertNotNull
import notion.api.v1.json.GsonSerializer
import notion.api.v1.model.databases.Databases
import org.junit.Test
class DatabasesTest {
@Test
fun listDatabases() {
val parser = GsonSerializer(true)
val databases: Databases = parser.toDatabases(listDatabasesResponse)
assertNotNull(databases)
}
private val listDatabasesResponse =
"""
{
"object": "list",
"results": [
{
"object": "database",
"id": "dfd4ecb5-2d43-443e-97eb-4700db2c4f75",
"created_time": "2021-05-13T08:05:56.626Z",
"last_edited_time": "2021-05-16T14:21:00.000Z",
"title": [
{
"type": "text",
"text": {
"content": "Test Database",
"link": null
},
"annotations": {
"bold": false,
"italic": false,
"strikethrough": false,
"underline": false,
"code": false,
"color": "default"
},
"plain_text": "Test Database",
"href": null
}
],
"properties": {
"Done": {
"id": ":APL",
"type": "checkbox",
"checkbox": {}
},
"Column 1": {
"id": "=Vlj",
"type": "rich_text",
"rich_text": {}
},
"Link": {
"id": "Jf>F",
"type": "url",
"url": {}
},
"Test Formula": {
"id": "K|aG",
"type": "formula",
"formula": {
"expression": "prop(\"Creator\")"
}
},
"Phone Number": {
"id": "MyWZ",
"type": "phone_number",
"phone_number": {}
},
"Velocity Points": {
"id": "SIsY",
"type": "number",
"number": {
"format": "number"
}
},
"Assignee": {
"id": "ZKb?",
"type": "people",
"people": {}
},
"Last Edited Time": {
"id": "ZMd=",
"type": "last_edited_time",
"last_edited_time": {}
},
"Created Time": {
"id": "ZSgO",
"type": "created_time",
"created_time": {}
},
"Tags": {
"id": "[r|\\",
"type": "multi_select",
"multi_select": {
"options": [
{
"id": "c0a647eb-8e16-48a1-948c-84c6c5253fba",
"name": "Tag1",
"color": "gray"
},
{
"id": "ed307f3d-6b74-45ff-8283-a7a290952b26",
"name": "Tag2",
"color": "pink"
},
{
"id": "ff391f31-95b8-4edd-9205-f024c11e4f5c",
"name": "Tag3",
"color": "yellow"
}
]
}
},
"Description": {
"id": "_;qC",
"type": "rich_text",
"rich_text": {}
},
"Last Editor": {
"id": "`Jbr",
"type": "last_edited_by",
"last_edited_by": {}
},
"Contact": {
"id": "fIt_",
"type": "email",
"email": {}
},
"Attachments": {
"id": "hhy?",
"type": "files",
"files": {}
},
"Due": {
"id": "j=nT",
"type": "date",
"date": {}
},
"Severity": {
"id": "lZ`?",
"type": "select",
"select": {
"options": [
{
"id": "2b52a4e0-7d25-4cb0-b32b-0d7ad7c6428e",
"name": "High",
"color": "pink"
},
{
"id": "fbe38876-81f3-4f64-a28e-34513787b1f6",
"name": "Medium",
"color": "gray"
},
{
"id": "324bef01-1dcf-422e-ab8b-dc8f8b5d32d4",
"name": "Low",
"color": "blue"
}
]
}
},
"Something": {
"id": "lj:?",
"type": "rich_text",
"rich_text": {}
},
"Creator": {
"id": "m`c{",
"type": "created_by",
"created_by": {}
},
"Column": {
"id": "q=>K",
"type": "formula",
"formula": {
"expression": "prop(\"Assignee\") == \"Kaz\""
}
},
"Title": {
"id": "title",
"type": "title",
"title": {}
},
"ID": {
"id": "UQGz",
"type": "unique_id",
"unique_id": {"prefix": "TD"}
}
}
}
],
"next_cursor": null,
"has_more": false
}
""".trimIndent()
}
| 20 | null | 25 | 96 | f2ce512e3d7d3000cbe20e184435437087f7e13f | 4,810 | notion-sdk-jvm | MIT License |
atomicfu-transformer/src/main/kotlin/kotlinx/atomicfu/transformer/FlowAnalyzer.kt | Kotlin | 99,576,820 | false | null | /*
* Copyright 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 kotlinx.atomicfu.transformer
import org.objectweb.asm.Opcodes.*
import org.objectweb.asm.Type
import org.objectweb.asm.tree.*
class FlowAnalyzer(
private val start: AbstractInsnNode?
) {
private var cur: AbstractInsnNode? = null
// the depth at which our atomic variable lies now (zero == top of stack),
// this ref at one slot below it (and we can choose to merge them!)
private var depth = 0
private fun abort(msg: String): Nothing = abort(msg, cur)
private fun unsupported(): Nothing = abort("Unsupported operation on atomic variable")
private fun unrecognized(i: AbstractInsnNode): Nothing = abort("Unrecognized operation ${i.toText()}")
private fun push(n: Int) { depth += n }
private fun pop(n: Int) {
if (depth < n) unsupported()
depth -= n
}
// with stack top containing transformed variables analyses the following sequential data flow until consumed with:
// * "astore" -- result is VarInsnNode
// * "invokevirtual" on it -- result is MethodInsnNode
// All other outcomes produce transformation error
fun execute(): AbstractInsnNode {
var i = start
while (i != null) {
cur = i
executeOne(i)?.let { return it }
i = i.next
}
abort("Flow control falls after the end of the method")
}
private fun executeOne(i: AbstractInsnNode): AbstractInsnNode? {
when (i) {
is LabelNode -> { /* ignore */ }
is LineNumberNode -> { /* ignore */ }
is FrameNode -> { /* ignore */ }
is MethodInsnNode -> {
popDesc(i.desc)
if (i.opcode == INVOKEVIRTUAL && depth == 0) return i // invoke virtual on atomic field ref
if (i.opcode != INVOKESTATIC) pop(1)
pushDesc(i.desc)
}
is FieldInsnNode -> when (i.opcode) {
GETSTATIC -> pushDesc(i.desc)
PUTSTATIC -> popDesc(i.desc)
GETFIELD -> {
pop(1)
pushDesc(i.desc)
}
PUTFIELD -> {
popDesc(i.desc)
pop(1)
}
else -> unrecognized(i)
}
is MultiANewArrayInsnNode -> {
pop(i.dims)
push(1)
}
is LdcInsnNode -> {
when (i.cst) {
is Double -> push(2)
is Long -> push(2)
else -> push(1)
}
}
else -> when (i.opcode) {
ASTORE -> {
if (depth == 0) return i // stored atomic field ref
pop(1) // stored something else
}
NOP -> { /* nop */ }
GOTO, TABLESWITCH, LOOKUPSWITCH, ATHROW, IFEQ, IFNE, IFLT, IFGE, IFGT, IFLE, IFNULL, IFNONNULL,
IF_ICMPEQ, IF_ICMPNE, IF_ICMPLT, IF_ICMPGE, IF_ICMPGT, IF_ICMPLE, IF_ACMPEQ, IF_ACMPNE -> {
abort("Unsupported branching/control within atomic operation")
}
IRETURN, FRETURN, ARETURN, RETURN, LRETURN, DRETURN -> {
abort("Unsupported return within atomic operation")
}
ACONST_NULL -> {
push(1)
}
ICONST_M1, ICONST_0, ICONST_1, ICONST_2, ICONST_3, ICONST_4, ICONST_5, BIPUSH, SIPUSH -> {
push(1)
}
LCONST_0, LCONST_1 -> {
push(2)
}
FCONST_0, FCONST_1, FCONST_2 -> {
push(1)
}
DCONST_0, DCONST_1 -> {
push(2)
}
ILOAD, FLOAD, ALOAD -> {
push(1)
}
LLOAD, DLOAD -> {
push(2)
}
IALOAD, BALOAD, CALOAD, SALOAD -> {
pop(2)
push(1)
}
LALOAD, D2L -> {
pop(2)
push(2)
}
FALOAD -> {
pop(2)
push(1)
}
DALOAD, L2D -> {
pop(2)
push(2)
}
AALOAD -> {
pop(1)
push(1)
}
ISTORE, FSTORE -> {
pop(1)
}
LSTORE, DSTORE -> {
pop(2)
}
IASTORE, BASTORE, CASTORE, SASTORE, FASTORE, AASTORE -> {
pop(3)
}
LASTORE, DASTORE -> {
pop(4)
}
POP, MONITORENTER, MONITOREXIT -> {
pop(1)
}
POP2 -> {
pop(2)
}
DUP -> {
pop(1)
push(2)
}
DUP_X1 -> {
if (depth <= 1) unsupported()
push(1)
}
DUP_X2 -> {
if (depth <= 2) unsupported()
push(1)
}
DUP2 -> {
pop(2)
push(4)
}
DUP2_X1 -> {
if (depth <= 2) unsupported()
push(2)
}
DUP2_X2 -> {
if (depth <= 3) unsupported()
push(2)
}
SWAP -> {
if (depth <= 1) unsupported()
}
IADD, ISUB, IMUL, IDIV, IREM, IAND, IOR, IXOR, ISHL, ISHR, IUSHR, L2I, D2I, FCMPL, FCMPG -> {
pop(2)
push(1)
}
LADD, LSUB, LMUL, LDIV, LREM, LAND, LOR, LXOR -> {
pop(4)
push(2)
}
FADD, FSUB, FMUL, FDIV, FREM, L2F, D2F -> {
pop(2)
push(1)
}
DADD, DSUB, DMUL, DDIV, DREM -> {
pop(4)
push(2)
}
LSHL, LSHR, LUSHR -> {
pop(3)
push(2)
}
INEG, FNEG, I2B, I2C, I2S, IINC -> {
pop(1)
push(1)
}
LNEG, DNEG -> {
pop(2)
push(2)
}
I2L, F2L -> {
pop(1)
push(2)
}
I2F -> {
pop(1)
push(1)
}
I2D, F2D -> {
pop(1)
push(2)
}
F2I, ARRAYLENGTH, INSTANCEOF -> {
pop(1)
push(1)
}
LCMP, DCMPL, DCMPG -> {
pop(4)
push(1)
}
NEW -> {
push(1)
}
NEWARRAY, ANEWARRAY -> {
pop(1)
push(1)
}
CHECKCAST -> {
/* nop for our needs */
}
else -> unrecognized(i)
}
}
return null
}
private fun popDesc(desc: String) {
when (desc[0]) {
'(' -> {
val types = Type.getArgumentTypes(desc)
pop(types.indices.sumBy { types[it].size })
}
'J', 'D' -> pop(2)
else -> pop(1)
}
}
private fun pushDesc(desc: String) {
val index = if (desc[0] == '(') desc.indexOf(')') + 1 else 0
when (desc[index]) {
'V' -> return
'Z', 'C', 'B', 'S', 'I', 'F', '[', 'L' -> {
push(1)
}
'J', 'D' -> {
push(2)
}
}
}
} | 57 | null | 58 | 917 | b94c6bd887ec48a5b172cacc0a1dac3f76c4fdbb | 8,919 | kotlinx-atomicfu | Apache License 2.0 |
compiler/testData/codegen/box/javaInterop/lambdaInstanceOf.kt | JakeWharton | 99,388,807 | false | null | // IGNORE_BACKEND_FIR: JVM_IR
// TARGET_BACKEND: JVM
// WITH_RUNTIME
// FILE: J.java
import kotlin.Function;
import kotlin.jvm.functions.Function0;
import kotlin.jvm.functions.Function1;
import kotlin.jvm.functions.Function2;
public class J {
public static String test(Function<String> x) {
if (x instanceof Function1) return "Fail 1";
if (x instanceof Function2) return "Fail 2";
if (!(x instanceof Function0)) return "Fail 3";
return ((Function0<String>) x).invoke();
}
}
// FILE: K.kt
fun box(): String {
return J.test({ "OK" })
}
| 181 | null | 5748 | 83 | 4383335168338df9bbbe2a63cb213a68d0858104 | 584 | kotlin | Apache License 2.0 |
day7/src/test/kotlin/com/nohex/aoc/day7/CrabAlignerTest.kt | mnohe | 433,396,563 | false | {"Kotlin": 105740} | package com.nohex.aoc.day7
import io.kotest.core.spec.style.StringSpec
import io.kotest.matchers.shouldBe
internal class CrabAlignerTest : StringSpec({
"fixed cost" {
val sut = CrabAligner(loadPositions("example.txt"))
sut.lowestFixedCost shouldBe 37
}
"variable cost" {
val sut = CrabAligner(loadPositions("example.txt"))
sut.lowestVariableCost shouldBe 168
}
})
| 0 | Kotlin | 0 | 0 | 4d7363c00252b5668c7e3002bb5d75145af91c23 | 415 | advent_of_code_2021 | MIT License |
rewrite-test/src/main/kotlin/org/openrewrite/java/ChangeStaticFieldToMethodTest.kt | Postremus | 422,069,127 | true | {"Java": 4133458, "Kotlin": 2041712, "ANTLR": 34959, "Groovy": 9925, "Shell": 1458} | /*
* Copyright 2021 the original author or authors.
* <p>
* 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
* <p>
* https://www.apache.org/licenses/LICENSE-2.0
* <p>
* 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.openrewrite.java
import org.junit.jupiter.api.Test
interface ChangeStaticFieldToMethodTest : JavaRecipeTest {
override val recipe: ChangeStaticFieldToMethod
get() = ChangeStaticFieldToMethod("java.util.Collections", "EMPTY_LIST",
"com.acme.Lists", "of")
@Test
fun migratesQualifiedField(jp: JavaParser) = assertChanged(
jp,
before = """
import java.util.Collections;
import java.util.List;
class A {
public List<String> empty() {
return Collections.EMPTY_LIST;
}
}
""",
after = """
import com.acme.Lists;
import java.util.List;
class A {
public List<String> empty() {
return Lists.of();
}
}
"""
)
@Test
fun migratesStaticImportedField(jp: JavaParser) = assertChanged(
jp,
before = """
import static java.util.Collections.EMPTY_LIST;
class A {
public Object empty() {
return EMPTY_LIST;
}
}
""",
after = """
import com.acme.Lists;
class A {
public Object empty() {
return Lists.of();
}
}
"""
)
@Test
fun migratesFullyQualifiedField(jp: JavaParser) = assertChanged(
jp,
before = """
class A {
public Object empty() {
return java.util.Collections.EMPTY_LIST;
}
}
""",
after = """
import com.acme.Lists;
class A {
public Object empty() {
return Lists.of();
}
}
"""
)
@Test
fun migratesFieldInitializer() = assertChanged(
before = """
import java.util.Collections;
class A {
private final Object collection = Collections.EMPTY_LIST;
}
""",
after = """
import com.acme.Lists;
class A {
private final Object collection = Lists.of();
}
"""
)
@Test
fun ignoresUnrelatedFields(jp: JavaParser) = assertUnchanged(
jp,
before = """
import java.util.Collections;
class A {
static Object EMPTY_LIST = null;
public Object empty1() {
return A.EMPTY_LIST;
}
public Object empty2() {
return EMPTY_LIST;
}
}
"""
)
}
| 0 | null | 0 | 0 | e2d94deee5773c3ab135560bba85bbb708b0b903 | 3,572 | rewrite | Apache License 2.0 |
testing/p2p/inmemory-messaging-impl/src/main/kotlin/net/corda/messaging/emulation/subscription/pubsub/PubSubSubscription.kt | corda | 346,070,752 | false | null | package net.corda.messaging.emulation.subscription.pubsub
import net.corda.lifecycle.LifecycleCoordinatorFactory
import net.corda.lifecycle.LifecycleCoordinatorName
import net.corda.lifecycle.LifecycleStatus
import net.corda.messaging.api.processor.PubSubProcessor
import net.corda.messaging.api.subscription.Subscription
import net.corda.messaging.api.subscription.config.SubscriptionConfig
import net.corda.messaging.emulation.topic.model.Consumption
import net.corda.messaging.emulation.topic.model.RecordMetadata
import net.corda.messaging.emulation.topic.service.TopicService
import net.corda.utilities.debug
import org.slf4j.Logger
import org.slf4j.LoggerFactory
import java.util.concurrent.locks.ReentrantLock
import kotlin.concurrent.withLock
/**
* In-memory pub sub subscription.
* @property subscriptionConfig config for subscription
* @property processor processor to execute upon retrieved records from topic
* @property executor processor is executed using this if it is not null
* @property topicService retrieve records and commit offsets back to topics with this service
* @property lifecycleCoordinatorFactory used to create the lifecycleCoordinator object that external users can follow for updates
*/
@Suppress("LongParameterList")
class PubSubSubscription<K : Any, V : Any>(
internal val subscriptionConfig: SubscriptionConfig,
private val processor: PubSubProcessor<K, V>,
private val topicService: TopicService,
private val lifecycleCoordinatorFactory: LifecycleCoordinatorFactory,
clientIdCounter: String
) : Subscription<K, V> {
companion object {
private val log: Logger = LoggerFactory.getLogger(this::class.java.enclosingClass)
}
private val lifecycleCoordinator = lifecycleCoordinatorFactory.createCoordinator(
LifecycleCoordinatorName(
"${subscriptionConfig.groupName}-PubSubSubscription-${subscriptionConfig.eventTopic}",
//we use clientIdCounter here instead of instanceId as this subscription is readOnly
clientIdCounter
)
) { _, _ -> }
private var currentConsumer: Consumption? = null
private val lock = ReentrantLock()
/**
* Is the subscription running.
*/
override val isRunning: Boolean
get() {
return currentConsumer?.isRunning ?: false
}
/**
* Begin consuming events from the configured topic and process them
* with the given [processor].
*/
override fun start() {
log.debug { "Starting subscription with config: $subscriptionConfig" }
lock.withLock {
if (currentConsumer == null) {
val consumer = PubSubConsumer(this)
lifecycleCoordinator.start()
lifecycleCoordinator.updateStatus(LifecycleStatus.UP)
currentConsumer = topicService.createConsumption(consumer)
}
}
}
/**
* Stop the subscription.
* Unsubscribe from the topic
* Stop the executor.
* Join the thread
*/
override fun close() {
log.debug { "Closing pubsub subscription with config: $subscriptionConfig" }
stopConsumer()
lifecycleCoordinator.close()
}
private fun stopConsumer() {
lock.withLock {
currentConsumer?.stop()
currentConsumer = null
lifecycleCoordinator.updateStatus(LifecycleStatus.DOWN)
}
}
/**
* Attempt to process a collection of [records] with the given [processor].
* [processor] executed using the [executor] if it is not null.
*/
internal fun processRecords(records: Collection<RecordMetadata>) {
val futures = records.mapNotNull {
it.castToType(processor.keyClass, processor.valueClass)
}.mapNotNull{
try {
processor.onNext(it)
} catch (except: Exception) {
log.warn("PubSubConsumer from group ${subscriptionConfig.groupName} failed to process records " +
"from topic ${subscriptionConfig.eventTopic}.", except)
null
}
}
futures.forEach {
try {
it.get()
} catch (except: Exception) {
log.warn("PubSubConsumer from group ${subscriptionConfig.groupName} failed to process records " +
"from topic ${subscriptionConfig.eventTopic}.", except)
}
}
}
override val subscriptionName: LifecycleCoordinatorName
get() = lifecycleCoordinator.name
}
| 96 | null | 7 | 69 | d478e119ab288af663910f9a2df42a7a7b9f5bce | 4,576 | corda-runtime-os | Apache License 2.0 |
app/src/main/java/com/orange/ods/app/ui/components/appbars/top/TopAppBarCustomizationState.kt | Orange-OpenSource | 440,548,737 | false | {"Kotlin": 1041275, "HTML": 26065, "CSS": 14905, "Shell": 587, "JavaScript": 197} | /*
* Software Name: Orange Design System
* SPDX-FileCopyrightText: Copyright (c) Orange SA
* SPDX-License-Identifier: MIT
*
* This software is distributed under the MIT licence,
* the text of which is available at https://opensource.org/license/MIT/
* or see the "LICENSE" file for more details.
*
* Software description: Android library of reusable graphical components
*/
package com.orange.ods.app.ui.components.appbars.top
import androidx.compose.runtime.Composable
import androidx.compose.runtime.MutableIntState
import androidx.compose.runtime.MutableState
import androidx.compose.runtime.mutableIntStateOf
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.saveable.rememberSaveable
import com.orange.ods.app.R
import com.orange.ods.app.ui.CustomAppBarConfiguration
@Composable
fun rememberTopAppBarCustomizationState(
navigationIconEnabled: MutableState<Boolean> = rememberSaveable { mutableStateOf(CustomAppBarConfiguration.Default.isNavigationIconEnabled) },
actionCount: MutableIntState = rememberSaveable { mutableIntStateOf(CustomAppBarConfiguration.Default.actionCount) },
overflowMenuEnabled: MutableState<Boolean> = rememberSaveable { mutableStateOf(CustomAppBarConfiguration.Default.isOverflowMenuEnabled) },
titleLineCount: MutableState<TopAppBarCustomizationState.Title> = rememberSaveable { mutableStateOf(TopAppBarCustomizationState.Title.Short) },
scrollBehavior: MutableState<TopAppBarCustomizationState.ScrollBehavior> = rememberSaveable { mutableStateOf(CustomAppBarConfiguration.Default.scrollBehavior) }
) =
remember(navigationIconEnabled, actionCount, overflowMenuEnabled, titleLineCount, scrollBehavior) {
TopAppBarCustomizationState(navigationIconEnabled, actionCount, overflowMenuEnabled, titleLineCount, scrollBehavior)
}
class TopAppBarCustomizationState(
val navigationIconEnabled: MutableState<Boolean>,
val actionCount: MutableIntState,
val overflowMenuEnabled: MutableState<Boolean>,
val title: MutableState<Title>,
val scrollBehavior: MutableState<ScrollBehavior>
) {
enum class Title(val titleRes: Int) {
Short(R.string.component_app_bars_top_large_title_short_value),
TwoLines(R.string.component_app_bars_top_large_title_two_lines_value),
Long(R.string.component_app_bars_top_large_title_long_value)
}
enum class ScrollBehavior {
None, Collapsible
}
private val maxActionCount = 3
val minActionCount = 0
val isNavigationIconEnabled: Boolean
get() = navigationIconEnabled.value
val isOverflowMenuEnabled: Boolean
get() = overflowMenuEnabled.value
val isOverflowMenuSwitchEnabled: Boolean
get() = actionCount.intValue <= maxActionCount - 1
val maxActionCountSelectable: Int
get() = if (isOverflowMenuEnabled) maxActionCount - 1 else maxActionCount
} | 74 | Kotlin | 7 | 17 | 273a2794ef729ecc443fe1414259e0e1362b4346 | 2,938 | ods-android | MIT License |
processor/src/main/java/com/joom/lightsaber/processor/analysis/BindingsAnalyzer.kt | joomcode | 170,310,869 | false | null | /*
* Copyright 2020 <NAME>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.michaelrocks.lightsaber.processor.analysis
import io.michaelrocks.grip.Grip
import io.michaelrocks.grip.annotatedWith
import io.michaelrocks.grip.classes
import io.michaelrocks.grip.mirrors.ClassMirror
import io.michaelrocks.grip.mirrors.Type
import io.michaelrocks.grip.mirrors.signature.GenericType
import io.michaelrocks.lightsaber.ProvidedAs
import io.michaelrocks.lightsaber.processor.ErrorReporter
import io.michaelrocks.lightsaber.processor.commons.Types
import io.michaelrocks.lightsaber.processor.model.Binding
import io.michaelrocks.lightsaber.processor.model.Dependency
import java.io.File
interface BindingsAnalyzer {
fun analyze(files: Collection<File>): BindingRegistry
}
class BindingsAnalyzerImpl(
private val grip: Grip,
private val analyzerHelper: AnalyzerHelper,
private val errorReporter: ErrorReporter
) : BindingsAnalyzer {
override fun analyze(files: Collection<File>): BindingRegistry {
val bindingRegistry = BindingRegistryImpl()
val bindingsQuery = grip select classes from files where annotatedWith(Types.PROVIDED_AS_TYPE)
bindingsQuery.execute().classes.forEach { mirror ->
createBindingsForClass(mirror).forEach { binding ->
bindingRegistry.registerBinding(binding)
}
}
return bindingRegistry
}
private fun createBindingsForClass(mirror: ClassMirror): Collection<Binding> {
return extractAncestorTypesFromClass(mirror).map { ancestorType ->
val dependency = Dependency(GenericType.Raw(mirror.type))
val qualifier = analyzerHelper.findQualifier(mirror)
val ancestor = Dependency(GenericType.Raw(ancestorType), qualifier)
Binding(dependency, ancestor)
}
}
private fun extractAncestorTypesFromClass(mirror: ClassMirror): Collection<Type.Object> {
val providedAs = mirror.annotations[Types.PROVIDED_AS_TYPE] ?: return emptyList()
@Suppress("UNCHECKED_CAST")
val ancestorTypes = providedAs.values[ProvidedAs::value.name] as? List<*>
if (ancestorTypes == null) {
error("Class ${mirror.type.className} has invalid type in its @ProvidedAs annotation: $ancestorTypes")
return emptyList()
}
return ancestorTypes.mapNotNull {
val ancestorType = it as? Type.Object
if (ancestorType == null) {
error("Class ${mirror.type.className} has a non-class type in its @ProvidedAs annotation: $it")
return@mapNotNull null
}
ancestorType
}
}
private fun error(message: String) {
errorReporter.reportError(message)
}
}
| 3 | null | 8 | 9 | f1eede8e14ecb399a451085fd5d13e77dd67f329 | 3,117 | lightsaber | Apache License 2.0 |
core/src/main/java/com/github/kornilova203/flameviewer/server/handlers/CountMethodsHandlerBase.kt | kornilova203 | 93,492,144 | false | {"Kotlin": 180956, "JavaScript": 100160, "Java": 54903, "CSS": 21077, "HTML": 11624, "Closure Templates": 6734, "Shell": 171} | package com.github.kornilova203.flameviewer.server.handlers
import com.github.kornilova203.flameviewer.FlameLogger
import com.github.kornilova203.flameviewer.converters.trees.Filter
import com.github.kornilova203.flameviewer.server.RequestHandlerBase
import com.github.kornilova203.flameviewer.server.RequestHandlingException
import com.github.kornilova203.flameviewer.server.ServerUtil
import com.google.gson.Gson
import io.netty.channel.ChannelHandlerContext
import io.netty.handler.codec.http.HttpRequest
import io.netty.handler.codec.http.QueryStringDecoder
import java.io.File
abstract class CountMethodsHandlerBase(private val logger: FlameLogger, private val findFile: FindFile) : RequestHandlerBase() {
abstract fun countMethods(file: File, filter: Filter?, decoder: QueryStringDecoder): Int
override fun processGet(request: HttpRequest, ctx: ChannelHandlerContext): Boolean {
val decoder = QueryStringDecoder(request.uri())
val file = findFile(getFileName(decoder))
?: throw RequestHandlingException("File not found. Uri: ${decoder.uri()}")
val filter = getFilter(decoder, logger, true)
val methodsCount = countMethods(file, filter, decoder)
ServerUtil.sendJson(ctx, Gson().toJson(MethodsCounter.NodesCount(methodsCount)), logger)
return true
}
}
| 22 | Kotlin | 8 | 80 | 01700b7bf615d074d7dd0b3afba56e7765a2d120 | 1,335 | java-profiling-plugin | MIT License |
android-test-framework/testSrc/com/android/tools/idea/projectsystem/TestProjectSystem.kt | JetBrains | 60,701,247 | false | null | /*
* Copyright (C) 2017 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.idea.projectsystem
import com.android.ide.common.repository.GradleCoordinate
import com.android.ide.common.repository.GradleVersion
import com.android.ide.common.resources.AndroidManifestPackageNameUtils
import com.android.ide.common.util.PathString
import com.android.projectmodel.ExternalAndroidLibrary
import com.android.tools.idea.projectsystem.ProjectSystemSyncManager.SyncReason
import com.android.tools.idea.projectsystem.ProjectSystemSyncManager.SyncResult
import com.android.tools.idea.run.ApkProvisionException
import com.android.tools.idea.run.ApplicationIdProvider
import com.android.tools.idea.util.androidFacet
import com.google.common.collect.HashMultimap
import com.google.common.util.concurrent.Futures
import com.google.common.util.concurrent.ListenableFuture
import com.intellij.execution.configurations.ModuleBasedConfiguration
import com.intellij.execution.configurations.RunConfiguration
import com.intellij.openapi.Disposable
import com.intellij.openapi.module.Module
import com.intellij.openapi.project.Project
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.psi.PsiClass
import com.intellij.psi.PsiElementFinder
import com.intellij.psi.PsiPackage
import com.intellij.psi.search.GlobalSearchScope
import com.intellij.ui.AppUIUtil
import org.jetbrains.android.facet.AndroidFacet
import java.nio.file.Path
import java.util.concurrent.CountDownLatch
/**
* This implementation of AndroidProjectSystem is used during integration tests and includes methods
* to stub project system functionalities.
*/
class TestProjectSystem @JvmOverloads constructor(
val project: Project,
availableDependencies: List<GradleCoordinate> = listOf(),
private var sourceProvidersFactoryStub: SourceProvidersFactory = SourceProvidersFactoryStub(),
@Volatile private var lastSyncResult: SyncResult = SyncResult.SUCCESS
) : AndroidProjectSystem {
/**
* Injects this project system into the [project] it was created for.
*/
fun useInTests() {
ProjectSystemService.getInstance(project).replaceProjectSystemForTests(this)
}
private val dependenciesByModule: HashMultimap<Module, GradleCoordinate> = HashMultimap.create()
private val availablePreviewDependencies: List<GradleCoordinate>
private val availableStableDependencies: List<GradleCoordinate>
private val incompatibleDependencyPairs: HashMap<GradleCoordinate, GradleCoordinate>
private val coordinateToFakeRegisterDependencyError: HashMap<GradleCoordinate, String>
init {
val sortedHighToLowDeps = availableDependencies.sortedWith(GradleCoordinate.COMPARE_PLUS_HIGHER).reversed()
val (previewDeps, stableDeps) = sortedHighToLowDeps.partition(GradleCoordinate::isPreview)
availablePreviewDependencies = previewDeps
availableStableDependencies = stableDeps
incompatibleDependencyPairs = HashMap()
coordinateToFakeRegisterDependencyError = HashMap()
}
/**
* Adds the given artifact to the given module's list of dependencies.
*/
fun addDependency(artifactId: GoogleMavenArtifactId, module: Module, mavenVersion: GradleVersion) {
val coordinate = artifactId.getCoordinate(mavenVersion.toString())
dependenciesByModule.put(module, coordinate)
}
/**
* @return the set of dependencies added to the given module.
*/
fun getAddedDependencies(module: Module): Set<GradleCoordinate> = dependenciesByModule.get(module)
/**
* Mark a pair of dependencies as incompatible so that [AndroidModuleSystem.analyzeDependencyCompatibility]
* will return them as incompatible dependencies.
*/
fun addIncompatibleDependencyPair(dep1: GradleCoordinate, dep2: GradleCoordinate) {
incompatibleDependencyPairs[dep1] = dep2
}
/**
* Add a fake error condition for [coordinate] such that calling [AndroidModuleSystem.registerDependency] on the
* coordinate will throw a [DependencyManagementException] with error message set to [errorMessage].
*/
fun addFakeErrorForRegisteringDependency(coordinate: GradleCoordinate, errorMessage: String) {
coordinateToFakeRegisterDependencyError[coordinate] = errorMessage
}
override fun getModuleSystem(module: Module): AndroidModuleSystem {
class TestAndroidModuleSystemImpl : AndroidModuleSystem {
override val module = module
override val moduleClassFileFinder: ClassFileFinder = object : ClassFileFinder {
override fun findClassFile(fqcn: String): VirtualFile? = null
}
override fun analyzeDependencyCompatibility(dependenciesToAdd: List<GradleCoordinate>)
: Triple<List<GradleCoordinate>, List<GradleCoordinate>, String> {
val found = mutableListOf<GradleCoordinate>()
val missing = mutableListOf<GradleCoordinate>()
var compatibilityWarningMessage = ""
for (dependency in dependenciesToAdd) {
val wildcardCoordinate = GradleCoordinate(dependency.groupId!!, dependency.artifactId!!, "+")
val lookup = availableStableDependencies.firstOrNull { it.matches(wildcardCoordinate) }
?: availablePreviewDependencies.firstOrNull { it.matches(wildcardCoordinate) }
if (lookup != null) {
found.add(lookup)
if (incompatibleDependencyPairs[lookup]?.let { dependenciesToAdd.contains(it) } == true) {
compatibilityWarningMessage += "$lookup is not compatible with ${incompatibleDependencyPairs[lookup]}\n"
}
}
else {
missing.add(dependency)
compatibilityWarningMessage += "Can't find $dependency\n"
}
}
return Triple(found, missing, compatibilityWarningMessage)
}
override fun getAndroidLibraryDependencies(scope: DependencyScopeType): Collection<ExternalAndroidLibrary> {
return emptySet()
}
override fun canRegisterDependency(type: DependencyType): CapabilityStatus {
return CapabilitySupported()
}
override fun getResourceModuleDependencies() = emptyList<Module>()
override fun getDirectResourceModuleDependents() = emptyList<Module>()
override fun registerDependency(coordinate: GradleCoordinate) {
registerDependency(coordinate, DependencyType.IMPLEMENTATION)
}
override fun registerDependency(coordinate: GradleCoordinate, type: DependencyType) {
coordinateToFakeRegisterDependencyError[coordinate]?.let {
throw DependencyManagementException(it, DependencyManagementException.ErrorCodes.INVALID_ARTIFACT)
}
dependenciesByModule.put(module, coordinate)
}
override fun getRegisteredDependency(coordinate: GradleCoordinate): GradleCoordinate? =
dependenciesByModule[module].firstOrNull { it.matches(coordinate) }
override fun getResolvedDependency(coordinate: GradleCoordinate, scope: DependencyScopeType): GradleCoordinate? =
dependenciesByModule[module].firstOrNull { it.matches(coordinate) }
override fun getModuleTemplates(targetDirectory: VirtualFile?): List<NamedModuleTemplate> {
return emptyList()
}
override fun canGeneratePngFromVectorGraphics(): CapabilityStatus {
return CapabilityNotSupported()
}
override fun getOrCreateSampleDataDirectory(): PathString? = null
override fun getSampleDataDirectory(): PathString? = null
override fun getPackageName(): String? {
val facet = module.androidFacet ?: return null
val primaryManifest = facet.sourceProviders.mainManifestFile ?: return null
return AndroidManifestPackageNameUtils.getPackageNameFromManifestFile(PathString(primaryManifest.path))
}
override fun getManifestOverrides() = ManifestOverrides()
override fun getResolveScope(scopeType: ScopeType): GlobalSearchScope {
return module.getModuleWithDependenciesAndLibrariesScope(scopeType != ScopeType.MAIN)
}
override fun getDependencyPath(coordinate: GradleCoordinate): Path? = null
}
return TestAndroidModuleSystemImpl()
}
override fun getApplicationIdProvider(runConfiguration: RunConfiguration): ApplicationIdProvider {
return object : ApplicationIdProvider {
override fun getPackageName(): String = (runConfiguration as? ModuleBasedConfiguration<*, *>)?.configurationModule?.module?.let { module ->
getModuleSystem(module).getPackageName()
} ?: throw ApkProvisionException("Not supported run configuration")
override fun getTestPackageName(): String? = null
}
}
fun emulateSync(result: SyncResult) {
val latch = CountDownLatch(1)
AppUIUtil.invokeLaterIfProjectAlive(project) {
lastSyncResult = result
project.messageBus.syncPublisher(PROJECT_SYSTEM_SYNC_TOPIC).syncEnded(result)
latch.countDown()
}
latch.await()
}
override fun getSyncManager(): ProjectSystemSyncManager = object : ProjectSystemSyncManager {
override fun syncProject(reason: SyncReason): ListenableFuture<SyncResult> {
emulateSync(SyncResult.SUCCESS)
return Futures.immediateFuture(SyncResult.SUCCESS)
}
override fun isSyncInProgress() = false
override fun isSyncNeeded() = !lastSyncResult.isSuccessful
override fun getLastSyncResult() = lastSyncResult
}
override fun getBuildManager(): ProjectSystemBuildManager = object : ProjectSystemBuildManager {
override fun compileProject() {
error("not supported for the test implementation")
}
override fun getLastBuildResult(): ProjectSystemBuildManager.BuildResult {
error("not supported for the test implementation")
}
override fun addBuildListener(parentDisposable: Disposable, buildListener: ProjectSystemBuildManager.BuildListener) {
error("not supported for the test implementation")
}
}
override fun getDefaultApkFile(): VirtualFile? {
error("not supported for the test implementation")
}
override fun getPathToAapt(): Path {
error("not supported for the test implementation")
}
override fun allowsFileCreation(): Boolean {
error("not supported for the test implementation")
}
override fun getPsiElementFinders() = emptyList<PsiElementFinder>()
override fun getLightResourceClassService(): LightResourceClassService {
return object : LightResourceClassService {
override fun getLightRClasses(qualifiedName: String, scope: GlobalSearchScope) = emptyList<PsiClass>()
override fun getLightRClassesAccessibleFromModule(module: Module, includeTests: Boolean) = emptyList<PsiClass>()
override fun getLightRClassesContainingModuleResources(module: Module) = emptyList<PsiClass>()
override fun findRClassPackage(qualifiedName: String): PsiPackage? = null
override fun getAllLightRClasses() = emptyList<PsiClass>()
override fun getLightRClassesDefinedByModule(module: Module, includeTestClasses: Boolean) = emptyList<PsiClass>()
}
}
override fun getSourceProvidersFactory(): SourceProvidersFactory = sourceProvidersFactoryStub
override fun getAndroidFacetsWithPackageName(project: Project, packageName: String, scope: GlobalSearchScope): List<AndroidFacet> {
return emptyList()
}
}
private class SourceProvidersFactoryStub : SourceProvidersFactory {
override fun createSourceProvidersFor(facet: AndroidFacet): SourceProviders? = null
}
| 5 | null | 230 | 948 | 10110983c7e784122d94c7467e9d243aba943bf4 | 11,934 | android | Apache License 2.0 |
privacysandbox/ui/ui-client/src/main/java/androidx/privacysandbox/ui/client/view/SandboxedSdkView.kt | androidx | 256,589,781 | false | null | /*
* Copyright 2023 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* 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.privacysandbox.ui.client.view
import android.content.Context
import android.content.res.Configuration
import android.os.Build
import android.util.AttributeSet
import android.view.View
import android.view.ViewGroup
import androidx.annotation.RequiresApi
import androidx.privacysandbox.ui.core.SandboxedUiAdapter
import java.util.concurrent.CopyOnWriteArrayList
import kotlin.math.min
/**
* A listener for changes to the state of the UI session associated with SandboxedSdkView.
*/
fun interface SandboxedSdkUiSessionStateChangedListener {
/**
* Called when the state of the session for SandboxedSdkView is updated.
*/
fun onStateChanged(state: SandboxedSdkUiSessionState)
}
/**
* Represents the state of a UI session.
*
* A UI session refers to the session opened with a [SandboxedUiAdapter] to let the host display UI
* from the UI provider. If the host has requested to open a session with its [SandboxedUiAdapter],
* the state will be [Loading] until the session has been opened and the content has been displayed.
* At this point, the state will become [Active]. If there is no active session and no session is
* being loaded, the state is [Idle].
*/
sealed class SandboxedSdkUiSessionState private constructor() {
/**
* A UI session is currently attempting to be opened.
*
* This state occurs when the UI has requested to open a session with its [SandboxedUiAdapter].
* No UI from the [SandboxedUiAdapter] will be shown during this state. When the session has
* been successfully opened and the content has been displayed, the state will transition to
* [Active].
*/
object Loading : SandboxedSdkUiSessionState()
/**
* There is an open session with the supplied [SandboxedUiAdapter] and its UI is currently
* being displayed.
*/
object Active : SandboxedSdkUiSessionState()
/**
* There is no currently open UI session and there is no operation in progress to open one.
*
* The UI provider may close the session at any point, which will result in the state becoming
* [Idle] if the session is closed without an error. If there is an error that causes the
* session to close, the state will be [Error].
*
* If a new [SandboxedUiAdapter] is set on a [SandboxedSdkView], the existing session will close
* and the state will become [Idle].
*/
object Idle : SandboxedSdkUiSessionState()
/**
* There was an error in the UI session.
*
* @param throwable The error that caused the session to end.
*/
class Error(val throwable: Throwable) : SandboxedSdkUiSessionState()
}
// TODO(b/268014171): Remove API requirements once S- support is added
@RequiresApi(Build.VERSION_CODES.TIRAMISU)
class SandboxedSdkView @JvmOverloads constructor(
context: Context,
attrs: AttributeSet? = null
) : ViewGroup(context, attrs) {
private var adapter: SandboxedUiAdapter? = null
private var client: Client? = null
private var isZOrderOnTop = true
private var contentView: View? = null
private var requestedWidth = -1
private var requestedHeight = -1
private var isTransitionGroupSet = false
internal val stateListenerManager: StateListenerManager = StateListenerManager()
/**
* Adds a state change listener to the UI session and immediately reports the current
* state.
*/
fun addStateChangedListener(stateChangedListener: SandboxedSdkUiSessionStateChangedListener) {
stateListenerManager.addStateChangedListener(stateChangedListener)
}
/**
* Removes the specified state change listener from SandboxedSdkView.
*/
fun removeStateChangedListener(
stateChangedListener: SandboxedSdkUiSessionStateChangedListener
) {
stateListenerManager.removeStateChangedListener(stateChangedListener)
}
fun setAdapter(sandboxedUiAdapter: SandboxedUiAdapter) {
if (this.adapter === sandboxedUiAdapter) return
client?.close()
client = null
this.adapter = sandboxedUiAdapter
checkClientOpenSession()
}
/**
* Sets the Z-ordering of the [SandboxedSdkView]'s surface, relative to its window.
*/
fun setZOrderOnTopAndEnableUserInteraction(setOnTop: Boolean) {
if (setOnTop == isZOrderOnTop) return
client?.notifyZOrderChanged(setOnTop)
isZOrderOnTop = setOnTop
checkClientOpenSession()
}
private fun checkClientOpenSession() {
val adapter = adapter
if (client == null && adapter != null && isAttachedToWindow && width > 0 && height > 0) {
stateListenerManager.currentUiSessionState = SandboxedSdkUiSessionState.Loading
client = Client(this)
adapter.openSession(
context,
width,
height,
isZOrderOnTop,
handler::post,
client!!
)
}
}
internal fun requestSize(width: Int, height: Int) {
if (width == this.width && height == this.height) return
requestedWidth = width
requestedHeight = height
requestLayout()
}
internal fun removeContentView() {
if (childCount == 1) {
super.removeViewAt(0)
}
}
internal fun setContentView(contentView: View) {
if (childCount > 1) {
throw IllegalStateException("Number of children views must not exceed 1")
}
this.contentView = contentView
removeContentView()
if (contentView.layoutParams == null) {
super.addView(contentView, 0, generateDefaultLayoutParams())
} else {
super.addView(contentView, 0, contentView.layoutParams)
}
stateListenerManager.currentUiSessionState = SandboxedSdkUiSessionState.Active
}
internal fun onClientClosedSession(error: Throwable? = null) {
removeContentView()
stateListenerManager.currentUiSessionState = if (error != null) {
SandboxedSdkUiSessionState.Error(error)
} else {
SandboxedSdkUiSessionState.Idle
}
}
private fun calculateMeasuredDimension(requestedSize: Int, measureSpec: Int): Int {
val measureSpecSize = MeasureSpec.getSize(measureSpec)
when (MeasureSpec.getMode(measureSpec)) {
MeasureSpec.EXACTLY -> {
return measureSpecSize
}
MeasureSpec.UNSPECIFIED -> {
return if (requestedSize < 0) {
measureSpecSize
} else {
requestedSize
}
}
MeasureSpec.AT_MOST -> {
return if (requestedSize >= 0) {
min(requestedSize, measureSpecSize)
} else {
measureSpecSize
}
}
else -> {
return measureSpecSize
}
}
}
override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) {
val newWidth = calculateMeasuredDimension(requestedWidth, widthMeasureSpec)
val newHeight = calculateMeasuredDimension(requestedHeight, heightMeasureSpec)
setMeasuredDimension(newWidth, newHeight)
}
override fun isTransitionGroup(): Boolean = !isTransitionGroupSet || super.isTransitionGroup()
override fun setTransitionGroup(isTransitionGroup: Boolean) {
super.setTransitionGroup(isTransitionGroup)
isTransitionGroupSet = true
}
override fun onLayout(changed: Boolean, left: Int, top: Int, right: Int, bottom: Int) {
getChildAt(0)?.layout(left, top, right, bottom)
checkClientOpenSession()
}
override fun onAttachedToWindow() {
super.onAttachedToWindow()
checkClientOpenSession()
}
override fun onDetachedFromWindow() {
client?.close()
client = null
super.onDetachedFromWindow()
}
override fun onSizeChanged(
width: Int,
height: Int,
oldWidth: Int,
oldHeight: Int
) {
super.onSizeChanged(width, height, oldWidth, oldHeight)
client?.notifyResized(width, height)
checkClientOpenSession()
}
// TODO(b/270971893) Compare to old configuration before notifying of configuration change.
override fun onConfigurationChanged(config: Configuration?) {
requireNotNull(config) { "Config cannot be null" }
super.onConfigurationChanged(config)
client?.notifyConfigurationChanged(config)
checkClientOpenSession()
}
/**
* @throws UnsupportedOperationException when called
*/
override fun addView(
view: View?,
index: Int,
params: LayoutParams?
) {
throw UnsupportedOperationException("Cannot add a view to SandboxedSdkView")
}
/**
* @throws UnsupportedOperationException when called
*/
override fun removeView(view: View?) {
throw UnsupportedOperationException("Cannot remove a view from SandboxedSdkView")
}
/**
* @throws UnsupportedOperationException when called
*/
override fun removeViewInLayout(view: View?) {
throw UnsupportedOperationException("Cannot remove a view from SandboxedSdkView")
}
/**
* @throws UnsupportedOperationException when called
*/
override fun removeViewsInLayout(start: Int, count: Int) {
throw UnsupportedOperationException("Cannot remove a view from SandboxedSdkView")
}
/**
* @throws UnsupportedOperationException when called
*/
override fun removeViewAt(index: Int) {
throw UnsupportedOperationException("Cannot remove a view from SandboxedSdkView")
}
/**
* @throws UnsupportedOperationException when called
*/
override fun removeViews(start: Int, count: Int) {
throw UnsupportedOperationException("Cannot remove a view from SandboxedSdkView")
}
/**
* @throws UnsupportedOperationException when called
*/
override fun removeAllViews() {
throw UnsupportedOperationException("Cannot remove a view from SandboxedSdkView")
}
/**
* @throws UnsupportedOperationException when called
*/
override fun removeAllViewsInLayout() {
throw UnsupportedOperationException("Cannot remove a view from SandboxedSdkView")
}
internal class Client(private var sandboxedSdkView: SandboxedSdkView?) :
SandboxedUiAdapter.SessionClient {
private var session: SandboxedUiAdapter.Session? = null
private var pendingWidth: Int? = null
private var pendingHeight: Int? = null
private var pendingZOrderOnTop: Boolean? = null
private var pendingConfiguration: Configuration? = null
fun notifyConfigurationChanged(configuration: Configuration) {
val session = session
if (session != null) {
session.notifyConfigurationChanged(configuration)
} else {
pendingConfiguration = configuration
}
}
fun notifyResized(width: Int, height: Int) {
val session = session
if (session != null) {
session.notifyResized(width, height)
} else {
pendingWidth = width
pendingHeight = height
}
}
fun notifyZOrderChanged(isZOrderOnTop: Boolean) {
if (sandboxedSdkView?.isZOrderOnTop == isZOrderOnTop) return
val session = session
if (session != null) {
session.notifyZOrderChanged(isZOrderOnTop)
} else {
pendingZOrderOnTop = isZOrderOnTop
}
}
fun close() {
session?.close()
session = null
sandboxedSdkView?.onClientClosedSession()
sandboxedSdkView = null
}
override fun onSessionOpened(session: SandboxedUiAdapter.Session) {
if (sandboxedSdkView == null) {
session.close()
return
}
sandboxedSdkView?.setContentView(session.view)
this.session = session
val width = pendingWidth
val height = pendingHeight
if ((width != null) && (height != null) && (width >= 0) && (height >= 0)) {
session.notifyResized(width, height)
}
pendingConfiguration?.let {
session.notifyConfigurationChanged(it)
}
pendingConfiguration = null
pendingZOrderOnTop?.let {
session.notifyZOrderChanged(it)
}
pendingZOrderOnTop = null
}
override fun onSessionError(throwable: Throwable) {
if (sandboxedSdkView == null) return
sandboxedSdkView?.onClientClosedSession(throwable)
}
override fun onResizeRequested(width: Int, height: Int) {
if (sandboxedSdkView == null) return
sandboxedSdkView?.requestSize(width, height)
}
}
internal class StateListenerManager {
internal var currentUiSessionState: SandboxedSdkUiSessionState =
SandboxedSdkUiSessionState.Idle
set(value) {
if (field != value) {
field = value
for (listener in stateChangedListeners) {
listener.onStateChanged(currentUiSessionState)
}
}
}
private var stateChangedListeners =
CopyOnWriteArrayList<SandboxedSdkUiSessionStateChangedListener>()
fun addStateChangedListener(listener: SandboxedSdkUiSessionStateChangedListener) {
stateChangedListeners.add(listener)
listener.onStateChanged(currentUiSessionState)
}
fun removeStateChangedListener(listener: SandboxedSdkUiSessionStateChangedListener) {
stateChangedListeners.remove(listener)
}
}
}
| 22 | null | 823 | 4,693 | a3474c3895ee09aff249431af66af2b54641dd4f | 14,723 | androidx | Apache License 2.0 |
privacysandbox/ui/ui-client/src/main/java/androidx/privacysandbox/ui/client/view/SandboxedSdkView.kt | androidx | 256,589,781 | false | null | /*
* Copyright 2023 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* 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.privacysandbox.ui.client.view
import android.content.Context
import android.content.res.Configuration
import android.os.Build
import android.util.AttributeSet
import android.view.View
import android.view.ViewGroup
import androidx.annotation.RequiresApi
import androidx.privacysandbox.ui.core.SandboxedUiAdapter
import java.util.concurrent.CopyOnWriteArrayList
import kotlin.math.min
/**
* A listener for changes to the state of the UI session associated with SandboxedSdkView.
*/
fun interface SandboxedSdkUiSessionStateChangedListener {
/**
* Called when the state of the session for SandboxedSdkView is updated.
*/
fun onStateChanged(state: SandboxedSdkUiSessionState)
}
/**
* Represents the state of a UI session.
*
* A UI session refers to the session opened with a [SandboxedUiAdapter] to let the host display UI
* from the UI provider. If the host has requested to open a session with its [SandboxedUiAdapter],
* the state will be [Loading] until the session has been opened and the content has been displayed.
* At this point, the state will become [Active]. If there is no active session and no session is
* being loaded, the state is [Idle].
*/
sealed class SandboxedSdkUiSessionState private constructor() {
/**
* A UI session is currently attempting to be opened.
*
* This state occurs when the UI has requested to open a session with its [SandboxedUiAdapter].
* No UI from the [SandboxedUiAdapter] will be shown during this state. When the session has
* been successfully opened and the content has been displayed, the state will transition to
* [Active].
*/
object Loading : SandboxedSdkUiSessionState()
/**
* There is an open session with the supplied [SandboxedUiAdapter] and its UI is currently
* being displayed.
*/
object Active : SandboxedSdkUiSessionState()
/**
* There is no currently open UI session and there is no operation in progress to open one.
*
* The UI provider may close the session at any point, which will result in the state becoming
* [Idle] if the session is closed without an error. If there is an error that causes the
* session to close, the state will be [Error].
*
* If a new [SandboxedUiAdapter] is set on a [SandboxedSdkView], the existing session will close
* and the state will become [Idle].
*/
object Idle : SandboxedSdkUiSessionState()
/**
* There was an error in the UI session.
*
* @param throwable The error that caused the session to end.
*/
class Error(val throwable: Throwable) : SandboxedSdkUiSessionState()
}
// TODO(b/268014171): Remove API requirements once S- support is added
@RequiresApi(Build.VERSION_CODES.TIRAMISU)
class SandboxedSdkView @JvmOverloads constructor(
context: Context,
attrs: AttributeSet? = null
) : ViewGroup(context, attrs) {
private var adapter: SandboxedUiAdapter? = null
private var client: Client? = null
private var isZOrderOnTop = true
private var contentView: View? = null
private var requestedWidth = -1
private var requestedHeight = -1
private var isTransitionGroupSet = false
internal val stateListenerManager: StateListenerManager = StateListenerManager()
/**
* Adds a state change listener to the UI session and immediately reports the current
* state.
*/
fun addStateChangedListener(stateChangedListener: SandboxedSdkUiSessionStateChangedListener) {
stateListenerManager.addStateChangedListener(stateChangedListener)
}
/**
* Removes the specified state change listener from SandboxedSdkView.
*/
fun removeStateChangedListener(
stateChangedListener: SandboxedSdkUiSessionStateChangedListener
) {
stateListenerManager.removeStateChangedListener(stateChangedListener)
}
fun setAdapter(sandboxedUiAdapter: SandboxedUiAdapter) {
if (this.adapter === sandboxedUiAdapter) return
client?.close()
client = null
this.adapter = sandboxedUiAdapter
checkClientOpenSession()
}
/**
* Sets the Z-ordering of the [SandboxedSdkView]'s surface, relative to its window.
*/
fun setZOrderOnTopAndEnableUserInteraction(setOnTop: Boolean) {
if (setOnTop == isZOrderOnTop) return
client?.notifyZOrderChanged(setOnTop)
isZOrderOnTop = setOnTop
checkClientOpenSession()
}
private fun checkClientOpenSession() {
val adapter = adapter
if (client == null && adapter != null && isAttachedToWindow && width > 0 && height > 0) {
stateListenerManager.currentUiSessionState = SandboxedSdkUiSessionState.Loading
client = Client(this)
adapter.openSession(
context,
width,
height,
isZOrderOnTop,
handler::post,
client!!
)
}
}
internal fun requestSize(width: Int, height: Int) {
if (width == this.width && height == this.height) return
requestedWidth = width
requestedHeight = height
requestLayout()
}
internal fun removeContentView() {
if (childCount == 1) {
super.removeViewAt(0)
}
}
internal fun setContentView(contentView: View) {
if (childCount > 1) {
throw IllegalStateException("Number of children views must not exceed 1")
}
this.contentView = contentView
removeContentView()
if (contentView.layoutParams == null) {
super.addView(contentView, 0, generateDefaultLayoutParams())
} else {
super.addView(contentView, 0, contentView.layoutParams)
}
stateListenerManager.currentUiSessionState = SandboxedSdkUiSessionState.Active
}
internal fun onClientClosedSession(error: Throwable? = null) {
removeContentView()
stateListenerManager.currentUiSessionState = if (error != null) {
SandboxedSdkUiSessionState.Error(error)
} else {
SandboxedSdkUiSessionState.Idle
}
}
private fun calculateMeasuredDimension(requestedSize: Int, measureSpec: Int): Int {
val measureSpecSize = MeasureSpec.getSize(measureSpec)
when (MeasureSpec.getMode(measureSpec)) {
MeasureSpec.EXACTLY -> {
return measureSpecSize
}
MeasureSpec.UNSPECIFIED -> {
return if (requestedSize < 0) {
measureSpecSize
} else {
requestedSize
}
}
MeasureSpec.AT_MOST -> {
return if (requestedSize >= 0) {
min(requestedSize, measureSpecSize)
} else {
measureSpecSize
}
}
else -> {
return measureSpecSize
}
}
}
override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) {
val newWidth = calculateMeasuredDimension(requestedWidth, widthMeasureSpec)
val newHeight = calculateMeasuredDimension(requestedHeight, heightMeasureSpec)
setMeasuredDimension(newWidth, newHeight)
}
override fun isTransitionGroup(): Boolean = !isTransitionGroupSet || super.isTransitionGroup()
override fun setTransitionGroup(isTransitionGroup: Boolean) {
super.setTransitionGroup(isTransitionGroup)
isTransitionGroupSet = true
}
override fun onLayout(changed: Boolean, left: Int, top: Int, right: Int, bottom: Int) {
getChildAt(0)?.layout(left, top, right, bottom)
checkClientOpenSession()
}
override fun onAttachedToWindow() {
super.onAttachedToWindow()
checkClientOpenSession()
}
override fun onDetachedFromWindow() {
client?.close()
client = null
super.onDetachedFromWindow()
}
override fun onSizeChanged(
width: Int,
height: Int,
oldWidth: Int,
oldHeight: Int
) {
super.onSizeChanged(width, height, oldWidth, oldHeight)
client?.notifyResized(width, height)
checkClientOpenSession()
}
// TODO(b/270971893) Compare to old configuration before notifying of configuration change.
override fun onConfigurationChanged(config: Configuration?) {
requireNotNull(config) { "Config cannot be null" }
super.onConfigurationChanged(config)
client?.notifyConfigurationChanged(config)
checkClientOpenSession()
}
/**
* @throws UnsupportedOperationException when called
*/
override fun addView(
view: View?,
index: Int,
params: LayoutParams?
) {
throw UnsupportedOperationException("Cannot add a view to SandboxedSdkView")
}
/**
* @throws UnsupportedOperationException when called
*/
override fun removeView(view: View?) {
throw UnsupportedOperationException("Cannot remove a view from SandboxedSdkView")
}
/**
* @throws UnsupportedOperationException when called
*/
override fun removeViewInLayout(view: View?) {
throw UnsupportedOperationException("Cannot remove a view from SandboxedSdkView")
}
/**
* @throws UnsupportedOperationException when called
*/
override fun removeViewsInLayout(start: Int, count: Int) {
throw UnsupportedOperationException("Cannot remove a view from SandboxedSdkView")
}
/**
* @throws UnsupportedOperationException when called
*/
override fun removeViewAt(index: Int) {
throw UnsupportedOperationException("Cannot remove a view from SandboxedSdkView")
}
/**
* @throws UnsupportedOperationException when called
*/
override fun removeViews(start: Int, count: Int) {
throw UnsupportedOperationException("Cannot remove a view from SandboxedSdkView")
}
/**
* @throws UnsupportedOperationException when called
*/
override fun removeAllViews() {
throw UnsupportedOperationException("Cannot remove a view from SandboxedSdkView")
}
/**
* @throws UnsupportedOperationException when called
*/
override fun removeAllViewsInLayout() {
throw UnsupportedOperationException("Cannot remove a view from SandboxedSdkView")
}
internal class Client(private var sandboxedSdkView: SandboxedSdkView?) :
SandboxedUiAdapter.SessionClient {
private var session: SandboxedUiAdapter.Session? = null
private var pendingWidth: Int? = null
private var pendingHeight: Int? = null
private var pendingZOrderOnTop: Boolean? = null
private var pendingConfiguration: Configuration? = null
fun notifyConfigurationChanged(configuration: Configuration) {
val session = session
if (session != null) {
session.notifyConfigurationChanged(configuration)
} else {
pendingConfiguration = configuration
}
}
fun notifyResized(width: Int, height: Int) {
val session = session
if (session != null) {
session.notifyResized(width, height)
} else {
pendingWidth = width
pendingHeight = height
}
}
fun notifyZOrderChanged(isZOrderOnTop: Boolean) {
if (sandboxedSdkView?.isZOrderOnTop == isZOrderOnTop) return
val session = session
if (session != null) {
session.notifyZOrderChanged(isZOrderOnTop)
} else {
pendingZOrderOnTop = isZOrderOnTop
}
}
fun close() {
session?.close()
session = null
sandboxedSdkView?.onClientClosedSession()
sandboxedSdkView = null
}
override fun onSessionOpened(session: SandboxedUiAdapter.Session) {
if (sandboxedSdkView == null) {
session.close()
return
}
sandboxedSdkView?.setContentView(session.view)
this.session = session
val width = pendingWidth
val height = pendingHeight
if ((width != null) && (height != null) && (width >= 0) && (height >= 0)) {
session.notifyResized(width, height)
}
pendingConfiguration?.let {
session.notifyConfigurationChanged(it)
}
pendingConfiguration = null
pendingZOrderOnTop?.let {
session.notifyZOrderChanged(it)
}
pendingZOrderOnTop = null
}
override fun onSessionError(throwable: Throwable) {
if (sandboxedSdkView == null) return
sandboxedSdkView?.onClientClosedSession(throwable)
}
override fun onResizeRequested(width: Int, height: Int) {
if (sandboxedSdkView == null) return
sandboxedSdkView?.requestSize(width, height)
}
}
internal class StateListenerManager {
internal var currentUiSessionState: SandboxedSdkUiSessionState =
SandboxedSdkUiSessionState.Idle
set(value) {
if (field != value) {
field = value
for (listener in stateChangedListeners) {
listener.onStateChanged(currentUiSessionState)
}
}
}
private var stateChangedListeners =
CopyOnWriteArrayList<SandboxedSdkUiSessionStateChangedListener>()
fun addStateChangedListener(listener: SandboxedSdkUiSessionStateChangedListener) {
stateChangedListeners.add(listener)
listener.onStateChanged(currentUiSessionState)
}
fun removeStateChangedListener(listener: SandboxedSdkUiSessionStateChangedListener) {
stateChangedListeners.remove(listener)
}
}
}
| 22 | null | 823 | 4,693 | a3474c3895ee09aff249431af66af2b54641dd4f | 14,723 | androidx | Apache License 2.0 |
src/main/kotlin/cn/net/polyglot/verticle/web/ServletVerticle.kt | whitewoodcity | 140,131,596 | false | null | package cn.net.polyglot.verticle.web
import cn.net.polyglot.config.*
import io.vertx.core.json.JsonObject
import io.vertx.kotlin.core.eventbus.requestAwait
import io.vertx.kotlin.coroutines.CoroutineVerticle
import kotlinx.coroutines.launch
abstract class ServletVerticle : CoroutineVerticle() {
override suspend fun start() {
start(this::class.java.asSubclass(this::class.java).name)//缺省以实际继承类名作为地址
println("${this::class.java.asSubclass(this::class.java).name} is deployed")
}
protected fun start(address: String) {
vertx.eventBus().consumer<JsonObject>(address) {
val reqJson = it.body()
val session = HttpSession(reqJson.getJsonObject(COOKIES).getString(SESSION_ID))
launch {
val request = HttpServletRequest(reqJson, session)
when (reqJson.getString(HTTP_METHOD)) {
POST -> {
it.reply(doPost(request).toJson())
}
GET -> {
it.reply(doGet(request).toJson())
}
PUT -> {
it.reply(doPut(request).toJson())
}
else -> it.reply(JsonObject().put(JSON_BODY, "Http Method is not specified"))
}
}
}
}
//Service Proxy of the Session Verticle
inner class HttpSession(private val id: String) {
fun put(key: String, value: String?) {
vertx.eventBus().send(SessionVerticle::class.java.name,
JsonObject().put(ACTION, PUT).put(SESSION_ID, id).put(INFORMATION, JsonObject().put(key, value))
)
}
fun remove(key: String) {
vertx.eventBus().send(SessionVerticle::class.java.name,
JsonObject().put(ACTION, REMOVE).put(SESSION_ID, id).put(INFORMATION, key)
)
}
suspend fun get(key: String): String? {
val result = vertx.eventBus().requestAwait<String>(SessionVerticle::class.java.name,
JsonObject().put(ACTION, GET).put(SESSION_ID, id).put(INFORMATION, key)
)
return result.body()
}
}
enum class HttpServletResponseType {
EMPTY_RESPONSE, TEMPLATE, FILE, JSON
}
inner class HttpServletResponse(val type: HttpServletResponseType, val path: String = "index.htm", private val values: JsonObject = JsonObject()) {
constructor(json: JsonObject = JsonObject()) : this(HttpServletResponseType.JSON, "index.htm", json)
constructor() : this(HttpServletResponseType.EMPTY_RESPONSE)
constructor(filePath: String) : this(HttpServletResponseType.FILE, filePath)
constructor(templatePath: String, values: JsonObject) : this(HttpServletResponseType.TEMPLATE, templatePath, values)
fun toJson(): JsonObject {
return when (type) {
HttpServletResponseType.TEMPLATE -> JsonObject().put(TEMPLATE_PATH, path).put(VALUES, values)
HttpServletResponseType.FILE -> JsonObject().put(FILE_PATH, path)
HttpServletResponseType.JSON -> JsonObject().put(RESPONSE_JSON, values)
else -> JsonObject().put(EMPTY_RESPONSE, true)
}
}
}
inner class HttpServletRequest(val json:JsonObject, val session: HttpSession){
fun getPath():String{
return json.getString(PATH)
}
fun getHttpMethod():String{
return json.getString(HTTP_METHOD)
}
fun getCookies():JsonObject{
return json.getJsonObject(COOKIES)
}
fun getHeaders():JsonObject{
return json.getJsonObject(HEADERS)
}
fun getParams():JsonObject{
return json.getJsonObject(PARAMS)
}
fun getQueryParams():JsonObject{
return json.getJsonObject(QUERY_PARAM)
}
fun getFormAttributes():JsonObject{
return json.getJsonObject(FORM_ATTRIBUTES)
}
fun getUploadFiles():JsonObject{
return json.getJsonObject(UPLOAD_FILES)
}
fun getUploadFileNames():JsonObject{
return json.getJsonObject(UPLOAD_FILE_NAMES)
}
fun bodyAsJson():JsonObject{
return json.getJsonObject(BODY_AS_JSON)
}
}
open suspend fun doGet(request:HttpServletRequest): HttpServletResponse {
return HttpServletResponse()
}
open suspend fun doPost(request:HttpServletRequest): HttpServletResponse {
return HttpServletResponse()
}
open suspend fun doPut(request:HttpServletRequest): HttpServletResponse {
return HttpServletResponse()
}
}
| 6 | null | 29 | 126 | 82f35a489eda0b8c63302733c31966e9339494a1 | 4,222 | social-vertex | MIT License |
vico/core/src/main/java/com/patrykandpatrick/vico/core/component/text/VerticalPositionExtensions.kt | patrykandpatrick | 338,848,755 | false | null | /*
* Copyright 2022 by <NAME> and <NAME>.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.patrykandpatrick.vico.core.component.text
import android.graphics.RectF
import com.patrykandpatrick.vico.core.extension.half
internal fun VerticalPosition.inBounds(
bounds: RectF,
distanceFromPoint: Float = 0f,
componentHeight: Float,
y: Float,
): VerticalPosition {
val topFits = y - distanceFromPoint - componentHeight >= bounds.top
val centerFits = y - componentHeight.half >= bounds.top && y + componentHeight.half <= bounds.bottom
val bottomFits = y + distanceFromPoint + componentHeight <= bounds.bottom
return when (this) {
VerticalPosition.Top -> if (topFits) this else VerticalPosition.Bottom
VerticalPosition.Bottom -> if (bottomFits) this else VerticalPosition.Top
VerticalPosition.Center -> when {
centerFits -> this
topFits -> VerticalPosition.Top
else -> VerticalPosition.Bottom
}
}
}
| 3 | null | 95 | 978 | 3e24d5d78b35b51eb186dbedcae4d81101fd1b9d | 1,525 | vico | Apache License 2.0 |
mobile/src/main/java/co/uk/kenkwok/tulipmania/network/NetworkServiceImpl.kt | kennethkwok | 108,638,140 | false | {"Gradle": 4, "Java Properties": 2, "Shell": 1, "Ignore List": 3, "Batchfile": 1, "Markdown": 1, "Proguard": 2, "Kotlin": 84, "XML": 30, "Java": 11, "JSON": 3} | package co.uk.kenkwok.tulipmania.network
import android.support.annotation.Nullable
import co.uk.kenkwok.tulipmania.models.AnxTicker
import co.uk.kenkwok.tulipmania.models.BitfinexTicker
import co.uk.kenkwok.tulipmania.models.BitstampTicker
import io.reactivex.Observable
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.schedulers.Schedulers
import java.util.concurrent.TimeUnit
/**
* Created by kwokk on 17/04/2017.
*/
class NetworkServiceImpl(private val anxService: ANXApi,
private val bitstampService: BitstampAPI,
private val bitfinexService: BitfinexAPI) : NetworkService {
/**
* Gets the most recent ticker data every 15 seconds
* @param currencyPair BTCUSD,BTCHKD,BTCEUR,BTCCAD,BTCAUD,BTCSGD,BTCJPY,BTCGBP,BTCNZD
* @param apiKey API Key
* @param restSign Rest sign generated by NetworkUtils class
*/
override fun getAnxTickerData(apiKey: String, restSign: String, currencyPair: String, @Nullable extraCcyPairs: String): Observable<AnxTicker> {
return Observable.interval(0, TICKER_INTERVAL, TimeUnit.SECONDS, Schedulers.io())
.flatMap {
anxService
.getMarketTickerObservable(currencyPair, apiKey, restSign, extraCcyPairs)
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
}
.observeOn(AndroidSchedulers.mainThread())
.subscribeOn(Schedulers.io())
}
/**
* Gets the most recent Bitstamp ticker data every 15 seconds
* @param currencyPair btcusd, , btceur, eurusd, xrpusd, xrpeur, xrpbtc, ltcusd, ltceur, ltcbtc, ethusd, etheur, ethbtc
*/
override fun getBitstampTickerData(currencyPair: String): Observable<BitstampTicker> {
return Observable.interval(0, TICKER_INTERVAL, TimeUnit.SECONDS, Schedulers.io())
.flatMap {
bitstampService
.getMarketTickerObservable(currencyPair)
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
}
.observeOn(AndroidSchedulers.mainThread())
.subscribeOn(Schedulers.io())
}
/**
* Gets the most recent Bitfinex ticker data every 15 seconds
* @param currencyPair btcusd
*/
override fun getBitfinexTickerData(currencyPair: String): Observable<BitfinexTicker> {
return Observable.interval(0, TICKER_INTERVAL, TimeUnit.SECONDS, Schedulers.io())
.flatMap {
bitfinexService
.getMarketTickerObservable(currencyPair)
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
}
.observeOn(AndroidSchedulers.mainThread())
.subscribeOn(Schedulers.io())
}
companion object {
private val TICKER_INTERVAL: Long = 15
private val TAG = "NetworkServiceImpl"
}
}
| 1 | null | 1 | 1 | b034e7c3c8678d9e8c475ad8dafd4d005cee67ab | 3,170 | tulipmania | Creative Commons Attribution 3.0 Unported |
verify/src/main/java/com/twilio/verify/data/DateParser.kt | twilio | 232,428,508 | false | null | /*
* Copyright (c) 2020 Twilio 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.twilio.verify.data
import com.twilio.security.logger.Level
import com.twilio.security.logger.Logger
import java.text.ParseException
import java.text.SimpleDateFormat
import java.util.Date
import java.util.Locale
import java.util.TimeZone
internal const val dateFormatTimeZone = "yyyy-MM-dd'T'HH:mm:ssZ"
internal val dateFormatterTimeZone = SimpleDateFormat(dateFormatTimeZone, Locale.US)
private const val dateFormatUTC = "yyyy-MM-dd'T'HH:mm:ss'Z'"
private const val RFC1123_FORMAT = "EEE, dd MMM yyyy HH:mm:ss zzz"
private val dateFormatterUTC =
SimpleDateFormat(dateFormatUTC, Locale.US).apply { timeZone = TimeZone.getTimeZone("UTC") }
internal fun fromRFC3339Date(date: String): Date {
try {
if (date.endsWith("Z")) {
return dateFormatterUTC.parse(date)
}
val firstPart: String = date.substring(0, date.lastIndexOf('-'))
var secondPart: String = date.substring(date.lastIndexOf('-'))
secondPart = (
secondPart.substring(0, secondPart.indexOf(':')) +
secondPart.substring(secondPart.indexOf(':') + 1)
)
val dateString = firstPart + secondPart
return dateFormatterTimeZone.parse(dateString)
} catch (e: ParseException) {
Logger.log(Level.Error, e.toString(), e)
throw e
} catch (e: Exception) {
Logger.log(Level.Error, e.toString(), e)
throw ParseException(e.message, 0)
}
}
internal fun toRFC3339Date(date: Date): String {
return dateFormatterUTC.format(date)
}
internal fun fromRFC1123Date(date: String): Date {
try {
return SimpleDateFormat(RFC1123_FORMAT, Locale.US).parse(date)
} catch (e: ParseException) {
Logger.log(Level.Error, e.toString(), e)
throw e
} catch (e: Exception) {
Logger.log(Level.Error, e.toString(), e)
throw ParseException(e.message, 0)
}
}
| 5 | Kotlin | 3 | 9 | 7599b76a8eff6ceff2d6c5eb05fe0d0ebe7fe172 | 2,397 | twilio-verify-android | Apache License 2.0 |
materi/pertemuan_7/kotlin/loopWhile2.kt | ummi-codelabs | 212,098,159 | false | {"Text": 1, "Markdown": 13, "Go": 15, "Java": 18, "PHP": 21, "Kotlin": 18, "JavaScript": 18, "Python": 17, "Hack": 2, "HTML": 3} | fun main() {
var i = 1
while (i <= 10) {
println(i)
i += 2
}
} | 1 | PHP | 6 | 3 | 1bcdae5400e4e466c1dfacf13a8c6ee0f32825dc | 91 | dasar-pemrograman | MIT License |
api/src/main/kotlin/com/mattmx/ktgui/conversation/EndEmptyPrompt.kt | Matt-MX | 530,062,987 | false | {"Kotlin": 255573, "Java": 8369} | package com.mattmx.ktgui.conversation
import org.bukkit.conversations.ConversationContext
import org.bukkit.conversations.MessagePrompt
import org.bukkit.conversations.Prompt
class EndEmptyPrompt(
private val message: String? = null,
private val after: (() -> Unit)? = null
) : MessagePrompt(), BuildablePrompt {
override fun getNextPrompt(context: ConversationContext): Prompt {
after?.invoke()
return DummyEndOfConversationPrompt()
}
override fun getPromptText(context: ConversationContext): String {
return message ?: ""
}
override fun next(prompt: Prompt) {
}
} | 3 | Kotlin | 3 | 24 | fdc34fce5eeb41f177f890040a58d6c174168434 | 626 | KtPaperGui | Apache License 2.0 |
libraries/designsystem/src/main/kotlin/io/element/android/libraries/designsystem/theme/components/IconButton.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.theme.components
import androidx.compose.foundation.interaction.MutableInteractionSource
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.material3.IconButtonColors
import androidx.compose.material3.IconButtonDefaults
import androidx.compose.material3.LocalContentColor
import androidx.compose.runtime.Composable
import androidx.compose.runtime.CompositionLocalProvider
import androidx.compose.runtime.remember
import androidx.compose.ui.Modifier
import androidx.compose.ui.tooling.preview.Preview
import io.element.android.compound.theme.ElementTheme
import io.element.android.compound.tokens.generated.CompoundIcons
import io.element.android.libraries.designsystem.preview.ElementThemedPreview
import io.element.android.libraries.designsystem.preview.PreviewGroup
// Figma designs: https://www.figma.com/file/G1xy0HDZKJf5TCRFmKb5d5/Compound-Android-Components?type=design&node-id=1182%3A48861&mode=design&t=Shlcvznm1oUyqGC2-1
@Composable
fun IconButton(
onClick: () -> Unit,
modifier: Modifier = Modifier,
enabled: Boolean = true,
colors: IconButtonColors = IconButtonDefaults.iconButtonColors(
contentColor = LocalContentColor.current,
disabledContentColor = ElementTheme.colors.iconDisabled,
),
interactionSource: MutableInteractionSource = remember { MutableInteractionSource() },
content: @Composable () -> Unit
) {
androidx.compose.material3.IconButton(
onClick = onClick,
modifier = modifier,
enabled = enabled,
colors = colors,
interactionSource = interactionSource,
content = content,
)
}
@Preview(group = PreviewGroup.Buttons)
@Composable
internal fun IconButtonPreview() = ElementThemedPreview {
Column {
CompositionLocalProvider(LocalContentColor provides ElementTheme.colors.iconPrimary) {
Row {
IconButton(onClick = {}) {
Icon(imageVector = CompoundIcons.Close(), contentDescription = null)
}
IconButton(enabled = false, onClick = {}) {
Icon(imageVector = CompoundIcons.Close(), contentDescription = null)
}
}
}
CompositionLocalProvider(LocalContentColor provides ElementTheme.colors.iconSecondary) {
Row {
IconButton(onClick = {}) {
Icon(imageVector = CompoundIcons.Close(), contentDescription = null)
}
IconButton(enabled = false, onClick = {}) {
Icon(imageVector = CompoundIcons.Close(), contentDescription = null)
}
}
}
}
}
| 263 | null | 75 | 955 | 31d0621fa15fe153bfd36104e560c9703eabe917 | 3,366 | element-x-android | Apache License 2.0 |
android/src/main/java/org/fossasia/badgemagic/database/ClipArtService.kt | LoopGlitch26 | 263,618,871 | false | null | package org.fossasia.badgemagic.database
import android.graphics.drawable.Drawable
import android.util.SparseArray
import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import org.fossasia.badgemagic.R
import org.fossasia.badgemagic.util.Resource
import org.fossasia.badgemagic.util.StorageUtils
import org.koin.core.KoinComponent
import org.koin.core.inject
class ClipArtService : KoinComponent {
private val clipArts = MutableLiveData<SparseArray<Drawable>>()
private val storageClipArts = MutableLiveData<MutableMap<String, Drawable?>>()
private val resourceHelper: Resource by inject()
private val storageUtils: StorageUtils by inject()
init {
updateClipArts()
}
private fun getAllClips(): SparseArray<Drawable> {
val tempSparseArray = SparseArray<Drawable>()
val listOfDrawables = listOf(
resourceHelper.getDrawable(R.drawable.clip_apple),
resourceHelper.getDrawable(R.drawable.clip_clock),
resourceHelper.getDrawable(R.drawable.clip_dustbin),
resourceHelper.getDrawable(R.drawable.clip_face),
resourceHelper.getDrawable(R.drawable.clip_heart),
resourceHelper.getDrawable(R.drawable.clip_home),
resourceHelper.getDrawable(R.drawable.clip_invader),
resourceHelper.getDrawable(R.drawable.clip_mail),
resourceHelper.getDrawable(R.drawable.clip_mix1),
resourceHelper.getDrawable(R.drawable.clip_mix2),
resourceHelper.getDrawable(R.drawable.clip_mushroom),
resourceHelper.getDrawable(R.drawable.clip_mustache),
resourceHelper.getDrawable(R.drawable.clip_oneup),
resourceHelper.getDrawable(R.drawable.clip_pause),
resourceHelper.getDrawable(R.drawable.clip_spider),
resourceHelper.getDrawable(R.drawable.clip_sun),
resourceHelper.getDrawable(R.drawable.clip_thumbs_up)
)
var lastIndex = 0
listOfDrawables.forEachIndexed { index, drawable ->
drawable?.let {
lastIndex = index
tempSparseArray.append(index, it)
}
}
val drawablesInStorage = getClipsFromStorage().value
drawablesInStorage?.forEach {
tempSparseArray.append(++lastIndex, it.value)
}
return tempSparseArray
}
fun updateClipArts() {
storageClipArts.value = storageUtils.getAllClips()
clipArts.value = getAllClips()
}
fun getClipArts(): LiveData<SparseArray<Drawable>> = clipArts
fun getClipsFromStorage(): LiveData<MutableMap<String, Drawable?>> = storageClipArts
fun deleteClipart(fileName: String) {
storageUtils.deleteClipart(fileName)
updateClipArts()
}
}
| 0 | null | 0 | 2 | cdf3291ce46a9ac16071752912aba845d5178871 | 2,798 | badge-magic-android | Apache License 2.0 |
src/main/kotlin/marisa/cards/OneTimeOff.kt | scarf005 | 574,583,770 | false | {"Kotlin": 393423, "TypeScript": 30744} | package marisa.cards
import basemod.abstracts.CustomCard
import com.megacrit.cardcrawl.actions.common.ApplyPowerAction
import com.megacrit.cardcrawl.actions.common.GainBlockAction
import com.megacrit.cardcrawl.cards.AbstractCard
import com.megacrit.cardcrawl.characters.AbstractPlayer
import com.megacrit.cardcrawl.core.CardCrawlGame
import com.megacrit.cardcrawl.monsters.AbstractMonster
import com.megacrit.cardcrawl.powers.DrawCardNextTurnPower
import marisa.ApplyPowerToPlayerAction
import marisa.patches.AbstractCardEnum
import marisa.powers.Marisa.OneTimeOffPlusPower
import marisa.powers.Marisa.OneTimeOffPower
class OneTimeOff : CustomCard(
ID,
NAME,
IMG_PATH,
COST,
DESCRIPTION,
CardType.SKILL,
AbstractCardEnum.MARISA_COLOR,
CardRarity.UNCOMMON,
CardTarget.SELF
) {
init {
baseBlock = BLOCK_AMT
baseMagicNumber = DRAW
magicNumber = baseMagicNumber
}
override fun use(p: AbstractPlayer, unused: AbstractMonster?) {
addToBot(
GainBlockAction(p, p, block)
)
addToBot(
ApplyPowerAction(p, p, DrawCardNextTurnPower(p, magicNumber), magicNumber)
)
val powerToAdd = if (upgraded) OneTimeOffPlusPower::class else OneTimeOffPower::class
addToBot(ApplyPowerToPlayerAction(powerToAdd))
}
override fun makeCopy(): AbstractCard = OneTimeOff()
override fun upgrade() {
if (upgraded) return
upgradeName()
upgradeBlock(UPGRADE_PLUS_BLOCK)
upgradeMagicNumber(UPGRADE_PLUS_DRAW)
rawDescription = DESCRIPTION_UPG
initializeDescription()
}
companion object {
const val ID = "OneTimeOff"
const val IMG_PATH = "marisa/img/cards/MoraleDelpletion.png"
private val cardStrings = CardCrawlGame.languagePack.getCardStrings(ID)
val NAME = cardStrings.NAME
val DESCRIPTION = cardStrings.DESCRIPTION
val DESCRIPTION_UPG = cardStrings.UPGRADE_DESCRIPTION
private const val COST = 1
private const val BLOCK_AMT = 5
private const val UPGRADE_PLUS_BLOCK = 2
private const val DRAW = 1
private const val UPGRADE_PLUS_DRAW = 1
}
}
| 12 | Kotlin | 7 | 16 | 7de5d81e660c661d36dd6382cb0bdae6e0863562 | 2,215 | Marisa | MIT License |
samples/client/3_1_0_unit_test/kotlin/src/test/kotlin/org/openapijsonschematools/client/components/schemas/PatternpropertiesValidatesPropertiesMatchingARegexTest.kt | openapi-json-schema-tools | 544,314,254 | false | null | package org.openapijsonschematools.client.components.schemas
import org.openapijsonschematools.client.configurations.JsonSchemaKeyword
import org.openapijsonschematools.client.configurations.SchemaConfiguration
import org.openapijsonschematools.client.exceptions.ValidationException
import kotlin.test.Test
import kotlin.test.assertFailsWith
class PatternpropertiesValidatesPropertiesMatchingARegexTest {
companion object {
val configuration = SchemaConfiguration(disabledKeywordFlags=setOf(JsonSchemaKeyword.FORMAT))
}
@Test
fun testMultipleInvalidMatchesIsInvalidFails() {
// multiple invalid matches is invalid
val schema = PatternpropertiesValidatesPropertiesMatchingARegex.PatternpropertiesValidatesPropertiesMatchingARegex1.getInstance()
assertFailsWith<ValidationException>(
block = {
schema.validate(
mapOf(
Pair(
"foo",
"bar"
),
Pair(
"foooooo",
"baz"
)
),
configuration
)
}
)
}
@Test
fun testASingleValidMatchIsValidPasses() {
// a single valid match is valid
val schema = PatternpropertiesValidatesPropertiesMatchingARegex.PatternpropertiesValidatesPropertiesMatchingARegex1.getInstance()
schema.validate(
mapOf(
Pair(
"foo",
1
)
),
configuration
)
}
@Test
fun testIgnoresOtherNonObjectsPasses() {
// ignores other non-objects
val schema = PatternpropertiesValidatesPropertiesMatchingARegex.PatternpropertiesValidatesPropertiesMatchingARegex1.getInstance()
schema.validate(
12,
configuration
)
}
@Test
fun testASingleInvalidMatchIsInvalidFails() {
// a single invalid match is invalid
val schema = PatternpropertiesValidatesPropertiesMatchingARegex.PatternpropertiesValidatesPropertiesMatchingARegex1.getInstance()
assertFailsWith<ValidationException>(
block = {
schema.validate(
mapOf(
Pair(
"foo",
"bar"
),
Pair(
"fooooo",
2
)
),
configuration
)
}
)
}
@Test
fun testMultipleValidMatchesIsValidPasses() {
// multiple valid matches is valid
val schema = PatternpropertiesValidatesPropertiesMatchingARegex.PatternpropertiesValidatesPropertiesMatchingARegex1.getInstance()
schema.validate(
mapOf(
Pair(
"foo",
1
),
Pair(
"foooooo",
2
)
),
configuration
)
}
@Test
fun testIgnoresArraysPasses() {
// ignores arrays
val schema = PatternpropertiesValidatesPropertiesMatchingARegex.PatternpropertiesValidatesPropertiesMatchingARegex1.getInstance()
schema.validate(
listOf(
"foo"
),
configuration
)
}
@Test
fun testIgnoresStringsPasses() {
// ignores strings
val schema = PatternpropertiesValidatesPropertiesMatchingARegex.PatternpropertiesValidatesPropertiesMatchingARegex1.getInstance()
schema.validate(
"foo",
configuration
)
}
}
| 1 | null | 11 | 128 | 9006de722f74b7ca917e4e5d38e4cd6ab5ea6e78 | 3,906 | openapi-json-schema-generator | Apache License 2.0 |
compose/compiler/compiler-hosted/integration-tests/src/jvmTest/kotlin/androidx/compose/compiler/plugins/kotlin/TargetAnnotationsTransformTests.kt | androidx | 256,589,781 | false | null | /*
* Copyright 2021 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* 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.compiler.plugins.kotlin
import org.junit.Test
@Suppress("SpellCheckingInspection") // Expected strings can have partial words
class TargetAnnotationsTransformTests(useFir: Boolean) : AbstractIrTransformTest(useFir) {
@Test
fun testInferUIFromCall() =
verify(
"""
import androidx.compose.runtime.Composable
@Composable
fun Test() {
Text("Hello")
}
"""
)
@Test
fun testInferVectorFromCall() =
verify(
"""
import androidx.compose.runtime.Composable
@Composable
fun Test() {
Circle()
}
"""
)
// No annotations is the same as leaving the applier open.
@Test
fun testInferSimpleOpen() =
verify(
"""
import androidx.compose.runtime.Composable
@Composable
fun Test() { }
"""
)
@Test
fun testInferUnifiedParameters() =
verify(
"""
import androidx.compose.runtime.Composable
@Composable
fun Test(content: @Composable () -> Unit) {
content()
}
"""
)
@Test
fun testInferLambdaParameter() =
verify(
"""
import androidx.compose.runtime.Composable
@Composable
fun Test(content: @Composable () -> Unit) {
Row {
Text("test")
}
}
"""
)
@Test
fun testInferInlineLambdaParameter() =
verify(
"""
import androidx.compose.runtime.Composable
@Composable
fun Test(content: @Composable () -> Unit) {
InlineRow {
Text("test")
}
}
"""
)
@Test
fun testCanInferWithGeneric() =
verify(
"""
import androidx.compose.runtime.Composable
@Composable
fun Test() {
Wrapper {
Text("test")
}
}
"""
)
@Test
fun testCompositionLocalsProvider() =
verify(
"""
import androidx.compose.runtime.Composable
import androidx.compose.runtime.CompositionLocalProvider
@Composable
fun Test() {
CompositionLocalProvider {
Text("test")
}
}
"""
)
@Test
fun testInferringFunInterfaceParameterAnnotations() =
verify(
"""
import androidx.compose.runtime.Composable
fun interface CustomComposable {
@Composable
fun call()
}
@Composable
fun OpenCustom(content: CustomComposable) {
content.call()
}
@Composable
fun ClosedCustom(content: CustomComposable) {
Text("Test")
content.call()
}
@Composable
fun Test() {
OpenCustom {
Text("Test")
}
ClosedCustom {
Text("Test")
}
}
"""
)
@Test
fun testLetIt() =
verifyGoldenComposeIrTransform(
"""
import androidx.compose.runtime.*
@Composable
fun Test(content: (@Composable () -> Unit?)) {
content?.let { it() }
}
"""
)
@Test
fun testOptionalParameters() =
verifyGoldenComposeIrTransform(
"""
import androidx.compose.runtime.*
@Composable
@ComposableTarget("UI")
fun Leaf() { }
@Composable
fun Wrapper(content: @Composable () -> Unit) { content() }
// [0,[0],[0],[0],[0],[0],[0],[0]]
@Composable
fun Optional(
one: @Composable () -> Unit = { },
two: (@Composable () -> Unit)? = null,
three: (@Composable () -> Unit)? = null,
four: (@Composable () -> Unit)? = null,
five: (@Composable () -> Unit)? = null,
six: (@Composable () -> Unit)? = null,
content: @Composable () -> Unit
) {
one()
// Invoke through a ?.
two?.invoke()
// Invoke through a let
three?.let { it() }
// Invoke through a let test
four?.let { four() }
// Invoke through in an then block
if (five != null)
five()
six?.let { it -> Wrapper(it) }
content()
}
@Composable
fun UseOptional() {
Optional {
Leaf()
}
}
"""
)
@Test
fun testReceiverScope() =
verifyGoldenComposeIrTransform(
"""
import androidx.compose.runtime.*
import androidx.compose.ui.layout.*
import androidx.compose.foundation.text.*
import androidx.compose.ui.text.*
import androidx.compose.ui.text.style.*
import androidx.compose.ui.*
@Immutable
interface LocalBoxScope {
@Stable
fun Modifier.align(alignment: Alignment): Modifier
}
object LocalBoxScopeInstance : LocalBoxScope {
override fun Modifier.align(alignment: Alignment): Modifier = Modifier
}
val localBoxMeasurePolicy = MeasurePolicy { _, constraints ->
layout(
constraints.minWidth,
constraints.minHeight
) {}
}
@Composable
inline fun LocalBox(
modifier: Modifier = Modifier,
content: @Composable LocalBoxScope.() -> Unit
) {
Layout(
modifier = modifier,
measurePolicy = localBoxMeasurePolicy,
content = { LocalBoxScopeInstance.content() }
)
}
"""
)
@Test
fun testCallingLayout() =
verifyGoldenComposeIrTransform(
"""
import androidx.compose.runtime.*
import androidx.compose.ui.layout.*
import androidx.compose.foundation.text.*
import androidx.compose.ui.text.*
import androidx.compose.ui.text.style.*
@Composable
fun Test1() {
Layout(content = { }) { _, _ -> error("") }
}
@Composable
fun Test2(content: @Composable ()->Unit) {
Layout(content = content) { _, _ -> error("") }
}
@Composable
fun Test3() {
Test1()
}
@Composable
fun Test4() {
BasicText(text = AnnotatedString("Some text"))
}
val Local = compositionLocalOf { 0 }
@Composable
fun Test5(content: @Composable () -> Unit) {
CompositionLocalProvider(Local provides 5) {
Test1()
content()
}
}
@Composable
fun Test6(test: String) {
CompositionLocalProvider(Local provides 6) {
T(test)
Test1()
}
}
@Composable
fun T(value: String) { }
"""
)
@Suppress("unused")
fun testCollectAsState() =
verifyGoldenComposeIrTransform(
"""
import kotlin.coroutines.*
import kotlinx.coroutines.flow.*
import androidx.compose.runtime.*
@Composable
fun <T> StateFlow<T>.collectAsState(
context: CoroutineContext = EmptyCoroutineContext
): State<T> = collectAsState(value, context)
@Composable
fun <T : R, R> Flow<T>.collectAsState(
initial: R,
context: CoroutineContext = EmptyCoroutineContext
): State<R> = mutableStateOf(initial)
"""
)
@Test
fun testRememberUpdatedState() =
verifyGoldenComposeIrTransform(
source =
"""
import androidx.compose.runtime.*
@Composable
fun Test(content: @Composable () -> Unit) {
val updatedContent by rememberUpdatedState(content)
Defer {
UiContent {
updatedContent()
}
}
}
""",
extra =
"""
import androidx.compose.runtime.*
fun Defer(content: @Composable () -> Unit) { }
fun UiContent(content: @Composable @ComposableTarget("UI") () -> Unit) { }
"""
)
@Test
fun testAddingComposablesToAList() =
verifyGoldenComposeIrTransform(
"""
import androidx.compose.runtime.*
class Scope {
private val list = IntervalList<Scope.(Int) -> (@Composable () -> Unit)>()
fun item(content: @Composable Scope.() -> Unit) {
list.add(1) { @Composable { content() } }
}
}
""",
extra =
"""
class IntervalList<T> {
fun add(size: Int, content: T) { }
}
"""
)
@Test
fun testCallingNullableComposableWithNull() =
verifyGoldenComposeIrTransform(
"""
import androidx.compose.runtime.*
@Composable
fun Test() {
Widget(null)
}
""",
extra =
"""
import androidx.compose.runtime.*
@Composable
fun Widget(content: (@Composable () -> Unit)?) {
if (content != null) content()
}
"""
)
@Test
fun testCallingComposableParameterWithComposableParameter() =
verify(
"""
import androidx.compose.runtime.*
@Composable
fun Test(decorator: @Composable (content: @Composable () -> Unit) -> Unit) {
decorator {
Text("Some text")
}
}
"""
)
@Test
fun testFileScoped() =
verifyGoldenComposeIrTransform(
source =
"""
@file:NComposable
import androidx.compose.runtime.*
@Composable
fun NFromFile() {
Open()
}
@Composable
fun NFromInference() {
N()
}
""",
extra =
"""
import androidx.compose.runtime.*
@ComposableTargetMarker(description = "An N Composable")
@Target(
AnnotationTarget.FILE,
AnnotationTarget.FUNCTION,
AnnotationTarget.PROPERTY_GETTER,
AnnotationTarget.TYPE,
AnnotationTarget.TYPE_PARAMETER,
)
annotation class NComposable()
@Composable @ComposableOpenTarget(0) fun Open() { }
@Composable @NComposable fun N() { }
"""
.trimIndent()
)
@Test
fun testCrossfileFileScope() =
verifyGoldenComposeIrTransform(
source =
"""
import androidx.compose.runtime.*
@Composable
fun InferN() { N() }
""",
extra =
"""
@file:NComposable
import androidx.compose.runtime.*
@ComposableTargetMarker(description = "An N Composable")
@Target(
AnnotationTarget.FILE,
AnnotationTarget.FUNCTION,
AnnotationTarget.PROPERTY_GETTER,
AnnotationTarget.TYPE,
AnnotationTarget.TYPE_PARAMETER,
)
annotation class NComposable()
@Composable fun N() { }
"""
)
@Test
fun testInferringTargetFromAncestorMethod() =
verifyGoldenComposeIrTransform(
source =
"""
import androidx.compose.runtime.Composable
import androidx.compose.runtime.ComposableTarget
import androidx.compose.runtime.ComposableOpenTarget
@Composable @ComposableOpenTarget(0) fun OpenTarget() { }
abstract class Base {
@Composable @ComposableTarget("N") abstract fun Compose()
}
class Valid : Base () {
@Composable override fun Compose() {
OpenTarget()
}
}
"""
)
private fun verify(source: String) = verifyGoldenComposeIrTransform(source, baseDefinition)
private val baseDefinition =
"""
import androidx.compose.runtime.Composable
import androidx.compose.runtime.ComposableTarget
import androidx.compose.runtime.ComposableOpenTarget
import androidx.compose.runtime.Applier
@Composable
@ComposableTarget("UI")
fun Layout() { }
@Composable
@ComposableTarget("UI")
fun Layout(content: @Composable @ComposableTarget("UI") () -> Unit) { }
@Composable
@ComposableTarget("UI")
inline fun InlineLayout(content: @Composable @ComposableTarget("UI") () -> Unit) { }
@Composable
fun Text(text: String) { Layout() }
@Composable
fun Row(content: @Composable () -> Unit) {
Layout(content)
}
@Composable
inline fun InlineRow(content: @Composable () -> Unit) {
InlineLayout(content)
}
@Composable
@ComposableTarget("Vector")
fun Vector() { }
@Composable
fun Circle() { Vector() }
@Composable
fun Square() { Vector() }
@Composable
@ComposableTarget("Vector")
fun Vector(content: @Composable @ComposableTarget("Vector") () -> Unit) { }
@Composable
fun Layer(content: @Composable () -> Unit) { Vector(content) }
@Composable
@ComposableTarget("UI")
fun Drawing(content: @Composable @ComposableTarget("Vector") () -> Unit) { }
@Composable
fun Wrapper(content: @Composable () -> Unit) { content() }
"""
}
| 28 | null | 945 | 5,125 | 55c737bfb7a7320ac5b43787306f0c3af169f420 | 14,747 | androidx | Apache License 2.0 |
model/src/main/kotlin/org/kethereum/model/Address.kt | bakaoh | 136,276,567 | false | null | package org.kethereum.model
data class Address(private val input: String) {
val cleanHex = input.replace("0x","")
@Transient
val hex = "0x$cleanHex"
override fun toString() = "0x" + cleanHex
override fun equals(other: Any?)
= other is Address && other.cleanHex.toUpperCase() == cleanHex.toUpperCase()
override fun hashCode() = cleanHex.toUpperCase().hashCode()
}
| 0 | null | 0 | 2 | 03a6fab6bbab5d71e16974a5e5ddbddaaadee45a | 405 | kethereum | MIT License |
src/main/kotlin/com/suihan74/hatena/model/entry/MaintenanceEntry.kt | suihan74 | 336,699,225 | false | null | package com.suihan74.hatena.model.entry
import com.suihan74.hatena.serializer.InstantISO8601Serializer
import kotlinx.serialization.Serializable
import java.time.Instant
/**
* メンテナンス情報
*/
@Serializable
data class MaintenanceEntry(
val id: String,
val title: String,
val body: String,
val resolved: Boolean,
val url: String,
@Serializable(with = InstantISO8601Serializer::class)
val createdAt: Instant,
@Serializable(with = InstantISO8601Serializer::class)
val updatedAt: Instant
) | 0 | Kotlin | 0 | 0 | d5a538c5005a04a0aec3c739a14a3c0eb875f25c | 526 | hatenaclient-kotlin | MIT License |
app/src/main/java/ch/nevis/exampleapp/domain/interaction/password/PasswordChangerImpl.kt | nevissecurity | 602,532,842 | false | {"Kotlin": 298091, "Ruby": 8543, "CSS": 427} | /**
* Nevis Mobile Authentication SDK Example App
*
* Copyright © 2024. Nevis Security AG. All rights reserved.
*/
package ch.nevis.exampleapp.domain.interaction.password
import ch.nevis.exampleapp.NavigationGraphDirections
import ch.nevis.exampleapp.logging.sdk
import ch.nevis.exampleapp.ui.credential.model.CredentialViewMode
import ch.nevis.exampleapp.ui.credential.parameter.PasswordNavigationParameter
import ch.nevis.exampleapp.ui.navigation.NavigationDispatcher
import ch.nevis.mobile.sdk.api.operation.password.PasswordChangeContext
import ch.nevis.mobile.sdk.api.operation.password.PasswordChangeHandler
import ch.nevis.mobile.sdk.api.operation.password.PasswordChanger
import ch.nevis.mobile.sdk.api.operation.password.PasswordPolicy
import timber.log.Timber
/**
* Default implementation of [PasswordChanger] interface. Navigates to Credential view with the received
* [PasswordChangeHandler], [ch.nevis.mobile.sdk.api.operation.password.PasswordAuthenticatorProtectionStatus]
* and [ch.nevis.mobile.sdk.api.operation.password.PasswordChangeRecoverableError] objects.
*
* @constructor Creates a new instance.
* @param policy An instance of a [PasswordPolicy] interface implementation.
* @param navigationDispatcher An instance of a [NavigationDispatcher] interface implementation.
*/
class PasswordChangerImpl(
private val policy: PasswordPolicy,
private val navigationDispatcher: NavigationDispatcher
) : PasswordChanger {
//region PasswordChanger
/** @suppress */
override fun changePassword(
context: PasswordChangeContext,
handler: PasswordChangeHandler
) {
if (context.lastRecoverableError().isPresent) {
Timber.asTree().sdk("Password change failed. Please try again.")
} else {
Timber.asTree().sdk("Please start Password change.")
}
navigationDispatcher.requestNavigation(
NavigationGraphDirections.actionGlobalCredentialFragment(
PasswordNavigationParameter(
CredentialViewMode.CHANGE,
lastRecoverableError = context.lastRecoverableError().orElse(null),
passwordAuthenticatorProtectionStatus = context.authenticatorProtectionStatus(),
passwordChangeHandler = handler
)
)
)
}
// You can add custom password policy by overriding the `passwordPolicy` getter
/** @suppress */
override fun passwordPolicy(): PasswordPolicy = policy
//endregion
}
| 1 | Kotlin | 0 | 2 | 669d95302da63adc9d99642e5e2d65af62f14ce3 | 2,538 | nevis-mobile-authentication-sdk-example-app-android | MIT License |
src/main/kotlin/com/demonwav/mcdev/platform/mcp/at/AtFileTypeFactory.kt | robertizotov-zz | 101,105,621 | false | {"Gradle": 1, "Markdown": 1, "Gradle Kotlin DSL": 1, "Text": 15, "Java Properties": 3, "Shell": 1, "Ignore List": 1, "Batchfile": 1, "Git Attributes": 1, "XML": 37, "YAML": 2, "INI": 12, "Java": 3, "Groovy": 4, "HAProxy": 2, "Kotlin": 450, "HTML": 28, "JFlex": 2} | /*
* Minecraft Dev for IntelliJ
*
* https://minecraftdev.org
*
* Copyright (c) 2017 minecraft-dev
*
* MIT License
*/
package com.demonwav.mcdev.platform.mcp.at
import com.intellij.openapi.fileTypes.FileNameMatcher
import com.intellij.openapi.fileTypes.FileTypeConsumer
import com.intellij.openapi.fileTypes.FileTypeFactory
import org.jetbrains.annotations.NonNls
class AtFileTypeFactory : FileTypeFactory() {
override fun createFileTypes(consumer: FileTypeConsumer) {
consumer.consume(AtFileType, object : FileNameMatcher {
override fun accept(@NonNls fileName: String) = fileName.endsWith("_at.cfg")
override fun getPresentableString() = "Access Transformer"
})
}
}
| 1 | null | 1 | 1 | 9b91deed668fce98cd21474b9135ec9b92212c2b | 726 | MinecraftDevIntelliJ | MIT License |
src/main/kotlin/com/demonwav/mcdev/platform/mcp/at/AtFileTypeFactory.kt | robertizotov-zz | 101,105,621 | false | {"Gradle": 1, "Markdown": 1, "Gradle Kotlin DSL": 1, "Text": 15, "Java Properties": 3, "Shell": 1, "Ignore List": 1, "Batchfile": 1, "Git Attributes": 1, "XML": 37, "YAML": 2, "INI": 12, "Java": 3, "Groovy": 4, "HAProxy": 2, "Kotlin": 450, "HTML": 28, "JFlex": 2} | /*
* Minecraft Dev for IntelliJ
*
* https://minecraftdev.org
*
* Copyright (c) 2017 minecraft-dev
*
* MIT License
*/
package com.demonwav.mcdev.platform.mcp.at
import com.intellij.openapi.fileTypes.FileNameMatcher
import com.intellij.openapi.fileTypes.FileTypeConsumer
import com.intellij.openapi.fileTypes.FileTypeFactory
import org.jetbrains.annotations.NonNls
class AtFileTypeFactory : FileTypeFactory() {
override fun createFileTypes(consumer: FileTypeConsumer) {
consumer.consume(AtFileType, object : FileNameMatcher {
override fun accept(@NonNls fileName: String) = fileName.endsWith("_at.cfg")
override fun getPresentableString() = "Access Transformer"
})
}
}
| 1 | null | 1 | 1 | 9b91deed668fce98cd21474b9135ec9b92212c2b | 726 | MinecraftDevIntelliJ | MIT License |
src/main/kotlin/net/devoev/vanilla_cubed/networking/Channels.kt | Devoev | 473,273,645 | false | null | package net.devoev.vanilla_cubed.networking
import net.devoev.vanilla_cubed.VanillaCubed
object Channels {
val JUMP_KEY_PRESSED = VanillaCubed.id("jump_key_pressed")
val ENDERITE_SHIELD_SPAWN_PARTICLES = VanillaCubed.id("enderite_shield_spawn_particles")
} | 0 | Kotlin | 1 | 1 | eeacd0115113a7bc1dd9a9ce6d17f95894fac3ee | 267 | vanilla-cubed | Creative Commons Zero v1.0 Universal |
library_core/src/main/java/com/td/framework/mvp/model/BaseParamsInfo.kt | aohanyao | 97,691,578 | false | null | package com.td.framework.mvp.model
import java.io.Serializable
import java.util.*
/**
* Created by jc on 7/26/2017.
*
* 版本:1.0.0
* **说明**<br></br>
* * 基本的参数对象
**** */
interface BaseParamsInfo : Serializable {
/**将参数转换为map*/
fun /*<T : BaseParamsInfo> */mapToParams(/*param: T*/): Map<String, Any> {
//创建参数集合
val mParamsMap = WeakHashMap<String, Any>()
// //获取反射
// this.javaClass
// .kotlin
// .memberProperties
// .forEach {
// mParamsMap.put(it.name, it.get(this).toString())
// }
return mParamsMap
}
}
| 0 | null | 2 | 2 | 0cf83b57ad19fcb8e217507f90c5140b5e1d0d3c | 643 | TdFramework | Apache License 2.0 |
src/leecode/53.kt | DavidZhong003 | 157,566,685 | false | {"Text": 1, "Ignore List": 1, "Markdown": 1, "Kotlin": 77, "Java": 1, "XML": 1} | package leecode
/**
* 53. 最大子序和
* @author doive
* on 2019/6/3 21:15
*/
fun main() {
/**
* 动态规划
* (-2, 1, -3, 4, -1, 2, 1, -5, 4)
* max: -2 -2 1 1 4 4 5 6 6 6
* ans: 0 -2 1 -2 4 3 5 6 -1 4
*/
fun maxSubArray(nums: IntArray): Int {
if (nums.isEmpty()) {
return 0
}
var ans = 0
var max = nums[0]
for (i in 0..nums.lastIndex) {
if (ans < 0) ans = 0
ans += nums[i]
max = Math.max(max, ans)
}
return max
}
/**
* 分治算法
*/
fun maxSubArraySuper(nums: IntArray): Int {
fun maxSubArraySuper(nums: IntArray, left: Int, right: Int): Int {
if (left == right) {
return nums[left]
}
if (left == right - 1) {
return Math.max(nums[left], Math.max(nums[right], nums[left] + nums[right]))
}
val mid = (left + right) / 2
// 左边最大
val leftMax = maxSubArraySuper(nums, left, mid - 1)
// 右边最大
val rightMax = maxSubArraySuper(nums, mid + 1, right)
// 中间最大
var max = nums[mid]
var sum = max
for (i in mid-1 downTo left){
sum += nums[i]
max = Math.max(max,sum)
}
// 右边
sum = max
for (i in mid+1 .. right){
sum += nums[i]
max = Math.max(max,sum)
}
return Math.max(leftMax,Math.max(rightMax,max))
}
return maxSubArraySuper(nums, 0, nums.lastIndex)
}
var startTime = System.currentTimeMillis()
maxSubArray(intArrayOf(-2, 1, -3, 4, -1, 2, 1, -5, 4,1)).println()
"消耗时间:${(System.currentTimeMillis()-startTime)}ms".println()
startTime = System.currentTimeMillis()
maxSubArraySuper(intArrayOf(-2, 1, -3, 4, -1, 2, 1, -5, 4,1)).println()
"消耗时间:${(System.currentTimeMillis()-startTime)}ms".println()
}
| 1 | null | 1 | 1 | 7eabe9d651013bf06fa813734d6556d5c05791dc | 2,010 | LeetCode-kt | Apache License 2.0 |
component/http-service-impl/src/main/kotlin/mikufan/cx/vtool/component/httpser/impl/customizer/UserAgentRestClientCustomizer.kt | CXwudi | 748,516,931 | false | {"Kotlin": 57945} | package mikufan.cx.vtool.component.httpser.impl.customizer
import org.springframework.boot.web.client.RestClientCustomizer
import org.springframework.http.HttpHeaders
import org.springframework.web.client.RestClient
class UserAgentRestClientCustomizer(
private val userAgent: String
) : RestClientCustomizer {
override fun customize(restClientBuilder: RestClient.Builder) {
restClientBuilder.defaultHeader(HttpHeaders.USER_AGENT, userAgent)
}
} | 2 | Kotlin | 0 | 0 | 336f69b36be756e158cb3acee86c312ee868957d | 457 | vsonglist-toolkit | MIT License |
app-kit/src/main/java/media/pixi/appkit/data/followers/FirebaseFollowersProvider.kt | NateWickstrom | 166,901,841 | false | null | package media.pixi.appkit.data.followers
import com.google.firebase.auth.FirebaseAuth
import com.google.firebase.firestore.DocumentReference
import com.google.firebase.firestore.FirebaseFirestore
import com.google.firebase.firestore.QuerySnapshot
import durdinapps.rxfirebase2.RxFirestore
import io.reactivex.Completable
import io.reactivex.Flowable
import io.reactivex.Single
class FirebaseFollowersProvider: FollowersProvider {
private val firestore = FirebaseFirestore.getInstance()
private val auth = FirebaseAuth.getInstance()
override fun follow(userId: String): Completable {
val map = mapOf(USER_ID to false)
return getUserIdSingle().map { getDoc(it, userId) }
.flatMapCompletable { doc -> RxFirestore.setDocument(doc, map) }
}
override fun unFollow(userId: String): Completable {
return getUserIdSingle().map { getDoc(it, userId) }
.flatMapCompletable { doc -> RxFirestore.deleteDocument(doc) } }
override fun getMyFollowers(): Flowable<List<String>> {
return getUserIdSingle()
.toFlowable()
.flatMap { getFollowers(it) }
}
override fun getFollowers(userId: String): Flowable<List<String>> {
val collection = firestore.collection(PEOPLE).document(userId).collection(FOLLOWERS)
return RxFirestore.getCollection(collection)
.map { snap -> toList(snap) }
.toFlowable()
}
private fun toList(query: QuerySnapshot): List<String> {
return query.documents.map { it.id }
}
private fun getUserIdSingle(): Single<String> {
return Single.fromCallable {
auth.currentUser?.uid ?: throw IllegalArgumentException("No user Id found.")
}
}
private fun getDoc(followerUserId: String, followedUserId: String): DocumentReference {
return firestore.collection(PEOPLE)
.document(followedUserId)
.collection(FOLLOWERS)
.document(followerUserId)
}
companion object {
// people // chatId // followers // userID // <blank>
private const val PEOPLE = "people"
private const val FOLLOWERS = "followers"
private const val USER_ID = "user_id"
}
} | 0 | Kotlin | 0 | 0 | 67e3f5cb6e1d0d7ed12002408325823ce1772492 | 2,240 | android-rx-firebase-app-kit | Apache License 2.0 |
sensing/src/main/java/com/google/android/sensing/db/impl/dao/CaptureInfoDao.kt | google-research | 673,685,651 | false | null | /*
* Copyright 2023-2024 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.android.sensing.db.impl.dao
import androidx.room.Dao
import androidx.room.Insert
import androidx.room.OnConflictStrategy
import androidx.room.Query
import androidx.room.Transaction
import com.google.android.sensing.capture.CaptureRequest
import com.google.android.sensing.db.impl.entities.CaptureInfoEntity
import com.google.android.sensing.model.CaptureInfo
import com.google.gson.Gson
import java.time.Instant
import java.util.Date
@Dao
internal abstract class CaptureInfoDao {
@Insert(onConflict = OnConflictStrategy.ABORT)
abstract suspend fun insertCaptureInfoEntity(captureInfoEntity: CaptureInfoEntity)
@Transaction
open suspend fun insertCaptureInfo(captureInfo: CaptureInfo): String {
insertCaptureInfoEntity(captureInfo.toCaptureInfoEntity())
return captureInfo.externalIdentifier
}
@Query("""
SELECT * FROM CaptureInfoEntity WHERE captureId=:captureId
""")
abstract suspend fun getCaptureInfoEntity(captureId: String): List<CaptureInfoEntity>
@Transaction
open suspend fun getCaptureInfo(captureId: String): CaptureInfo? {
return getCaptureInfoEntity(captureId).firstOrNull()?.toCaptureInfo()
}
@Query("""
DELETE FROM CaptureInfoEntity WHERE captureId=:captureId
""")
abstract suspend fun deleteCaptureInfo(captureId: String): Int
}
internal fun CaptureInfo.toCaptureInfoEntity() =
CaptureInfoEntity(
captureId = captureId,
externalIdentifier = externalIdentifier,
captureRequestType = captureRequest::class.java.name,
captureRequest = Gson().toJson(captureRequest),
captureFolder = captureFolder,
captureTime = captureTime?.toInstant() ?: Instant.now(),
)
internal fun CaptureInfoEntity.toCaptureInfo() =
CaptureInfo(
captureId = captureId,
externalIdentifier = externalIdentifier,
captureRequest =
Gson().fromJson(captureRequest, Class.forName(captureRequestType)) as CaptureRequest,
captureFolder = captureFolder,
captureTime = Date.from(captureTime)
)
| 19 | null | 7 | 6 | 0eb97489fc575d6014f99f402207d3eb979af4f4 | 2,602 | CVD-paper-mobile-camera-example | Apache License 2.0 |
project/app/src/main/java/com/marcosvbras/robomarket/flows/robotdetail/viewmodel/RobotDetailViewModel.kt | marcosvbras | 137,366,659 | false | {"Kotlin": 113953, "Java": 3663} | package com.marcosvbras.robomarket.flows.robotdetail.viewmodel
import android.app.Activity.RESULT_OK
import android.databinding.ObservableField
import android.os.Bundle
import com.marcosvbras.robomarket.app.EDIT_ROBOT_REQUEST_CODE
import com.marcosvbras.robomarket.app.ROBOT_TAG
import com.marcosvbras.robomarket.business.beans.Robot
import com.marcosvbras.robomarket.business.model.RobotModel
import com.marcosvbras.robomarket.flows.createrobot.ui.CreateRobotActivity
import com.marcosvbras.robomarket.interfaces.ActivityCallback
import com.marcosvbras.robomarket.app.BaseViewModel
import io.reactivex.disposables.Disposable
class RobotDetailViewModel(private val callback: ActivityCallback) : BaseViewModel() {
private var robot: Robot? = null
private val robotModel: RobotModel = RobotModel()
private var disposable: Disposable? = null
var model = ObservableField<String>()
var manufacturer = ObservableField<String>()
var color = ObservableField<String>()
var year = ObservableField<String>()
var quantity = ObservableField<String>()
var price = ObservableField<String>()
var imageUrl = ObservableField<String>()
fun showData(robot: Robot?) {
this.robot = robot
if (robot != null) {
model.set(robot.model)
manufacturer.set(robot.manufacturer)
color.set(robot.color)
year.set(robot.year.toString())
quantity.set(robot.quantity.toString())
price.set(robot.price.toString())
imageUrl.set(robot.imageUrl.toString())
}
}
fun edit() {
val bundle = Bundle()
bundle.putParcelable(ROBOT_TAG, robot)
callback.openActivityForResult(CreateRobotActivity::class.java, bundle, EDIT_ROBOT_REQUEST_CODE)
}
fun delete() {
cleanupSubscriptions()
if (robot != null) {
robotModel.deleteRobot(robot!!.objectId!!)!!
.subscribe({}, { error ->
callback.showDialogMessage(error.message!!)
cleanupSubscriptions()
}, {
cleanupSubscriptions()
callback.setActivityResult(RESULT_OK)
callback.finishCurrentActivity()
}, { d ->
isLoading.set(true)
disposable = d
})
}
}
override fun onCleared() {
cleanupSubscriptions()
super.onCleared()
}
override fun cleanupSubscriptions() {
isLoading.set(false)
disposable?.dispose()
}
} | 0 | Kotlin | 1 | 1 | b2253686d9d7bfe9a10f1cd0e0253ac29abc6f41 | 2,633 | RoboMarket | Apache License 2.0 |
shared/src/main/java/de/shecken/grillshow/shared/theme/Color.kt | pynnie | 617,506,940 | false | {"Kotlin": 168809, "HTML": 12735} | package de.shecken.grillshow.shared
import androidx.compose.ui.graphics.Color
val md_theme_dark_primary = Color(0xFFFFB4A8)
val md_theme_dark_onPrimary = Color(0xFF690100)
val md_theme_dark_primaryContainer = Color(0xFF930100)
val md_theme_dark_onPrimaryContainer = Color(0xFFFFDAD4)
val md_theme_dark_secondary = Color(0xFFFFB4A8)
val md_theme_dark_onSecondary = Color(0xFF690100)
val md_theme_dark_secondaryContainer = Color(0xFF930100)
val md_theme_dark_onSecondaryContainer = Color(0xFFFFDAD4)
val md_theme_dark_tertiary = Color(0xFFFFB4A8)
val md_theme_dark_onTertiary = Color(0xFF690100)
val md_theme_dark_tertiaryContainer = Color(0xFF930100)
val md_theme_dark_onTertiaryContainer = Color(0xFFFFDAD4)
val md_theme_dark_error = Color(0xFFFFB4AB)
val md_theme_dark_errorContainer = Color(0xFF93000A)
val md_theme_dark_onError = Color(0xFF690005)
val md_theme_dark_onErrorContainer = Color(0xFFFFDAD6)
val md_theme_dark_background = Color(0xFF001F2A)
val md_theme_dark_onBackground = Color(0xFFFFFFFF)
val md_theme_dark_surface = Color(0xFF001F2A)
val md_theme_dark_onSurface = Color(0xFFFFFFFF)
val md_theme_dark_surfaceVariant = Color(0xFF534341)
val md_theme_dark_onSurfaceVariant = Color(0xFFD8C2BE)
val md_theme_dark_outline = Color(0xFFA08C89)
val md_theme_dark_inverseOnSurface = Color(0xFF001F2A)
val md_theme_dark_inverseSurface = Color(0xFFFFFFFF)
val md_theme_dark_inversePrimary = Color(0xFFC00100)
val md_theme_dark_shadow = Color(0xFF000000)
val md_theme_dark_surfaceTint = Color(0xFFFFB4A8)
val md_theme_dark_outlineVariant = Color(0xFF534341)
val md_theme_dark_scrim = Color(0xFF000000)
| 9 | Kotlin | 0 | 2 | 132264aa50c5712605a0b2131fffdd1f416e1c38 | 1,609 | android-grillshow-app | Apache License 2.0 |
connection/src/main/java/com/thoughtworks/cconn/ConnectionFactory.kt | TW-Smart-CoE | 562,334,431 | false | {"Kotlin": 150403, "Java": 1997} | /*
** Copyright 2020, 思特沃克软件技术(北京)有限公司
**
*/
package com.thoughtworks.cconn
import android.content.Context
import com.thoughtworks.cconn.bus.Bus
import com.thoughtworks.cconn.bus.CrossConnectionBus
import com.thoughtworks.cconn.comm.bluetooth.client.BluetoothClient
import com.thoughtworks.cconn.comm.tcp.client.TcpClient
import com.thoughtworks.cconn.network.NetworkDetector
import com.thoughtworks.cconn.network.NetworkRegister
import com.thoughtworks.cconn.network.bluetooth.detector.BluetoothDetector
import com.thoughtworks.cconn.network.bluetooth.register.BluetoothRegister
import com.thoughtworks.cconn.network.nsd.detector.NSDNetworkDetector
import com.thoughtworks.cconn.network.nsd.register.NSDNetworkRegister
import com.thoughtworks.cconn.network.udp.detector.UdpDetector
import com.thoughtworks.cconn.network.udp.register.UdpRegister
/**
* Connection type
*/
enum class ConnectionType {
BLUETOOTH,
TCP,
}
enum class NetworkDiscoveryType {
BLUETOOTH,
NSD,
UDP
}
/**
* Connection factory create connection modules.
*/
object ConnectionFactory {
/**
* Create connection client
*
* @param context android context
* @param connectionType connection type
* @return connection client
*/
fun createConnection(context: Context, connectionType: ConnectionType): Connection =
when (connectionType) {
ConnectionType.BLUETOOTH -> BluetoothClient(context)
ConnectionType.TCP -> TcpClient(context)
}
/**
* Create register, used on server side. Which register server information (such as IP address, MAC ...)
*
* @param context android context
* @param connectionType connectionType
* @return network register
*/
fun createRegister(
context: Context,
networkDiscoveryType: NetworkDiscoveryType
): NetworkRegister =
when (networkDiscoveryType) {
NetworkDiscoveryType.BLUETOOTH -> BluetoothRegister(context)
NetworkDiscoveryType.NSD -> NSDNetworkRegister(context)
NetworkDiscoveryType.UDP -> UdpRegister(context)
}
/**
* Create detector, used on client side. Which detect server information (such as IP address, MAC ...)
*
* @param context android context
* @param connectionType connection type
* @return network detector
*/
fun createDetector(
context: Context,
networkDiscoveryType: NetworkDiscoveryType
): NetworkDetector =
when (networkDiscoveryType) {
NetworkDiscoveryType.BLUETOOTH -> BluetoothDetector(context)
NetworkDiscoveryType.NSD -> NSDNetworkDetector(context)
NetworkDiscoveryType.UDP -> UdpDetector()
}
fun createBus(context: Context): Bus {
return CrossConnectionBus(context)
}
}
| 3 | Kotlin | 0 | 2 | e82e06625876a4be3646c18d4d554b798d5a5e98 | 2,840 | cross-connection-android | Apache License 2.0 |
connection/src/main/java/com/thoughtworks/cconn/ConnectionFactory.kt | TW-Smart-CoE | 562,334,431 | false | {"Kotlin": 150403, "Java": 1997} | /*
** Copyright 2020, 思特沃克软件技术(北京)有限公司
**
*/
package com.thoughtworks.cconn
import android.content.Context
import com.thoughtworks.cconn.bus.Bus
import com.thoughtworks.cconn.bus.CrossConnectionBus
import com.thoughtworks.cconn.comm.bluetooth.client.BluetoothClient
import com.thoughtworks.cconn.comm.tcp.client.TcpClient
import com.thoughtworks.cconn.network.NetworkDetector
import com.thoughtworks.cconn.network.NetworkRegister
import com.thoughtworks.cconn.network.bluetooth.detector.BluetoothDetector
import com.thoughtworks.cconn.network.bluetooth.register.BluetoothRegister
import com.thoughtworks.cconn.network.nsd.detector.NSDNetworkDetector
import com.thoughtworks.cconn.network.nsd.register.NSDNetworkRegister
import com.thoughtworks.cconn.network.udp.detector.UdpDetector
import com.thoughtworks.cconn.network.udp.register.UdpRegister
/**
* Connection type
*/
enum class ConnectionType {
BLUETOOTH,
TCP,
}
enum class NetworkDiscoveryType {
BLUETOOTH,
NSD,
UDP
}
/**
* Connection factory create connection modules.
*/
object ConnectionFactory {
/**
* Create connection client
*
* @param context android context
* @param connectionType connection type
* @return connection client
*/
fun createConnection(context: Context, connectionType: ConnectionType): Connection =
when (connectionType) {
ConnectionType.BLUETOOTH -> BluetoothClient(context)
ConnectionType.TCP -> TcpClient(context)
}
/**
* Create register, used on server side. Which register server information (such as IP address, MAC ...)
*
* @param context android context
* @param connectionType connectionType
* @return network register
*/
fun createRegister(
context: Context,
networkDiscoveryType: NetworkDiscoveryType
): NetworkRegister =
when (networkDiscoveryType) {
NetworkDiscoveryType.BLUETOOTH -> BluetoothRegister(context)
NetworkDiscoveryType.NSD -> NSDNetworkRegister(context)
NetworkDiscoveryType.UDP -> UdpRegister(context)
}
/**
* Create detector, used on client side. Which detect server information (such as IP address, MAC ...)
*
* @param context android context
* @param connectionType connection type
* @return network detector
*/
fun createDetector(
context: Context,
networkDiscoveryType: NetworkDiscoveryType
): NetworkDetector =
when (networkDiscoveryType) {
NetworkDiscoveryType.BLUETOOTH -> BluetoothDetector(context)
NetworkDiscoveryType.NSD -> NSDNetworkDetector(context)
NetworkDiscoveryType.UDP -> UdpDetector()
}
fun createBus(context: Context): Bus {
return CrossConnectionBus(context)
}
}
| 3 | Kotlin | 0 | 2 | e82e06625876a4be3646c18d4d554b798d5a5e98 | 2,840 | cross-connection-android | Apache License 2.0 |
Tokens/AliasTags.kt | noloerino | 107,359,352 | false | null | package texmarkup
val aliasTags = hashMapOf("math" to Math.Companion::create,
"ilmath" to InlineMath.Companion::create,
"part" to ProbPart.Companion::create,
"i" to Italic.Companion::create,
"b" to Bold.Companion::create,
"body" to DocumentT.Companion::create,
"box" to MDFramed.Companion::create)
abstract class AliasTag(id: String, flags: Array<String>, properties: HashMap<String, String>) : Tag(id, flags, properties) {
constructor(id: String) : this(id, arrayOf(), hashMapOf()) { }
abstract val texId: String
override fun evalHelper(tokens: MutableList<Token>, currEnv: ParseEnv): String {
var sb = StringBuilder("\\begin{$texId}\n\t")
evalChildren(sb, tokens, currEnv)
sb.append("\\end{$texId}\n\t")
return sb.toString()
}
}
class Math() : AliasTag("math") {
override val texId = "align*"
override fun evalHelper(tokens: MutableList<Token>, currEnv: ParseEnv): String {
val sb = StringBuilder("\\begin{$texId}")
evalChildren(sb, tokens, ParseEnv.MATH_LITERAL)
if (sb.toString().endsWith("\\\\ ")) {
sb.delete(sb.length - 3, sb.length)
}
sb.append("\\end{$texId}")
return sb.toString()
}
companion object {
fun create(flags: Array<String>, properties: HashMap<String, String>): Tag {
return Math()
}
}
}
class InlineMath() : AliasTag("ilmath") {
override val texId = "$"
override fun evalHelper(tokens: MutableList<Token>, currEnv: ParseEnv): String {
var sb = StringBuilder(texId)
evalChildren(sb, tokens, ParseEnv.MATH_LITERAL)
sb.append(texId)
return sb.toString()
}
companion object {
fun create(flags: Array<String>, properties: HashMap<String, String>): Tag {
return InlineMath()
}
}
}
class ProbPart(flags: Array<String>, properties: HashMap<String, String>) : AliasTag("part", flags, properties) {
override val texId = "item"
override val validFlags = arrayOf("pbr, nobox")
override val validProperties = arrayOf("name")
override fun evalHelper(tokens: MutableList<Token>, currEnv: ParseEnv): String {
var sb = StringBuilder("\\$texId ")
sb.append(if ("name" in properties) Literal(listOf(properties["name"]!!)).eval(mutableListOf(), currEnv) else "\\\\")
if ("nobox" !in flags) {
sb.append("\\begin{mdframed}\\textbf{Solution: }")
}
evalChildren(sb, tokens, currEnv)
if ("nobox" !in flags) {
sb.append("\\end{mdframed}")
}
if ("pbr" in flags) {
sb.append("\\clearpage")
}
return sb.toString()
}
companion object {
fun create(flags: Array<String>, properties: HashMap<String, String>): Tag {
return ProbPart(flags, properties)
}
}
}
class Italic() : AliasTag("i") {
override val texId = "textit"
override fun evalHelper(tokens: MutableList<Token>, currEnv: ParseEnv): String {
var sb = StringBuilder("\\$texId{")
evalChildren(sb, tokens, currEnv)
sb.append("}")
return sb.toString()
}
companion object {
fun create(flags: Array<String>, properties: HashMap<String, String>): Tag {
return Italic()
}
}
}
class Bold() : AliasTag("b") {
override val texId = "textbf"
override fun evalHelper(tokens: MutableList<Token>, currEnv: ParseEnv): String {
val _texId = when (currEnv) {
ParseEnv.MATH_LITERAL -> "mathbf"
else -> "textbf"
}
var sb = StringBuilder("\\$_texId{")
evalChildren(sb, tokens, currEnv)
sb.append("}")
return sb.toString()
}
companion object {
fun create(flags: Array<String>, properties: HashMap<String, String>): Tag {
return Bold()
}
}
}
class DocumentT() : AliasTag("body") {
override val texId = "document"
companion object {
fun create(flags: Array<String>, properties: HashMap<String, String>): Tag {
return DocumentT()
}
}
}
class MDFramed() : AliasTag("box") {
override val texId = "mdframed"
companion object {
fun create(flags: Array<String>, properties: HashMap<String, String>): Tag {
return MDFramed()
}
}
} | 0 | Kotlin | 0 | 1 | cd09bd02a1962aa289e272fcb547ce828f200252 | 4,518 | tex-markup | MIT License |
src/main/kotlin/hello/account/UserController.kt | myfjdthink | 140,362,708 | true | {"Kotlin": 9270} | package hello.account
import hello.account.domain.User
import hello.account.domain.UserRepository
import org.springframework.web.bind.annotation.*
@RestController
@RequestMapping("/users")
class UserController(
private val userService: UserService,
private val userRepository: UserRepository) {
@GetMapping("/test/{id}")
fun test(@PathVariable id: String) = "User(id=$id, name=admin, password=123)"
@PostMapping("/register")
fun findAll(@RequestBody user: User): User {
return userService.register(user)
}
@GetMapping("/{id}")
fun findOne(@PathVariable id: Long): User = userRepository.findById(id).get()
@GetMapping("/findByLastName/{lastName}")
fun findByLastName(@PathVariable lastName: String) = userRepository.findByLastName(lastName)
} | 0 | Kotlin | 0 | 0 | cd13f5bb1a2c093c4f15b3ceaf62bcb7332e785b | 808 | spring-boot-kotlin-demo | Apache License 2.0 |
app/src/main/java/com/danefinlay/ttsutil/Notifications.kt | Danesprite | 220,346,944 | false | null | /*
* TTS Util
*
* Authors: <NAME> <<EMAIL>>
*
* Copyright (C) 2019 <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.danefinlay.ttsutil
import android.app.NotificationChannel
import android.app.NotificationManager
import android.app.PendingIntent
import android.content.Context
import android.content.Intent
import android.net.Uri
import android.os.Build
import android.support.v4.app.NotificationCompat
import com.danefinlay.ttsutil.ui.MainActivity
import org.jetbrains.anko.notificationManager
const val SPEAKING_NOTIFICATION_ID = 1
const val SYNTHESIS_NOTIFICATION_ID = 2
private fun getNotificationBuilder(ctx: Context, notificationId: Int):
NotificationCompat.Builder {
// Create an Intent and PendingIntent for when the user clicks on the
// notification. This should just open/re-open MainActivity.
val notificationIdUri = Uri.parse("notificationId:$notificationId")
val onClickIntent = Intent(ctx,
MainActivity::class.java).apply {
data = notificationIdUri
addFlags(START_ACTIVITY_FLAGS)
}
val contentPendingIntent = PendingIntent.getActivity(
ctx, 0, onClickIntent, 0)
// Just stop speaking for the delete intent (notification dismissal).
val onDeleteIntent = Intent(ctx,
SpeakerIntentService::class.java).apply {
action = ACTION_STOP_SPEAKING
data = notificationIdUri
}
val onDeletePendingIntent = PendingIntent.getService(ctx,
0, onDeleteIntent, 0)
// Set up the notification
// Use the correct notification builder method
val notificationBuilder = when {
Build.VERSION.SDK_INT >= 26 -> {
val id = ctx.getString(R.string.app_name)
val importance = NotificationManager.IMPORTANCE_LOW
ctx.notificationManager.createNotificationChannel(
NotificationChannel(id, id, importance)
)
NotificationCompat.Builder(ctx, id)
}
else -> {
@Suppress("DEPRECATION")
NotificationCompat.Builder(ctx)
}
}
return notificationBuilder.apply {
// Set the icon for the notification
setSmallIcon(android.R.drawable.ic_btn_speak_now)
// Set pending intents.
setContentIntent(contentPendingIntent)
setDeleteIntent(onDeletePendingIntent)
// Make it so the notification stays around after it's clicked on.
setAutoCancel(false)
// Add a notification action for stop speaking.
// Re-use the delete intent.
addAction(android.R.drawable.ic_delete,
ctx.getString(R.string.stop_button),
onDeletePendingIntent)
}
}
fun speakerNotificationBuilder(ctx: Context, notificationId: Int):
NotificationCompat.Builder {
val builder = getNotificationBuilder(ctx, notificationId)
return builder.apply {
// Set the title and text depending on the notification ID.
when (notificationId) {
SPEAKING_NOTIFICATION_ID -> {
setContentTitle(ctx.getString(R.string.speaking_notification_title))
setContentText(ctx.getString(R.string.speaking_notification_text))
}
SYNTHESIS_NOTIFICATION_ID -> {
setContentTitle(ctx.getString(R.string.synthesis_notification_title))
setContentText(ctx.getString(R.string.synthesis_notification_text))
}
else -> {
}
}
}
}
| 9 | null | 5 | 22 | 79f3561232a0f9a55da896db23382b4c223373ed | 4,035 | tts-util-app | Apache License 2.0 |
compiler-plugin/src/test/kotlin/arrow/meta/quotes/scope/plugins/ContinueExpressionPlugin.kt | matiaslev | 228,050,786 | true | {"Kotlin": 736346, "Shell": 3071} | package arrow.meta.quotes.scope.plugins
import arrow.meta.Meta
import arrow.meta.Plugin
import arrow.meta.invoke
import arrow.meta.phases.CompilerContext
import arrow.meta.quotes.Transform
import arrow.meta.quotes.continueExpression
open class ContinueExpressionPlugin : Meta {
override fun intercept(ctx: CompilerContext): List<Plugin> = listOf(
continueExpressionPlugin
)
}
val Meta.continueExpressionPlugin
get() =
"Continue Expression Scope Plugin" {
meta(
continueExpression({ true }) { expression ->
Transform.replace(
replacing = expression,
newDeclaration = when {
targetLabel.value != null -> """continue$targetLabel""".`continue`
else -> """continue""".`continue`
}
)
}
)
} | 0 | null | 0 | 0 | 175dcf1787f8b1acad35e4679177700d14da0587 | 822 | arrow-meta | Apache License 2.0 |
phoenix-ui/src/main/java/com/guoxiaoxing/phoenix/picker/rx/bus/ObserverListener.kt | lianwt115 | 152,687,979 | false | {"Gradle": 7, "Java Properties": 2, "Shell": 1, "Text": 1, "Ignore List": 6, "Batchfile": 1, "Markdown": 1, "Proguard": 5, "XML": 280, "Java": 85, "Kotlin": 268, "JSON": 2, "C++": 4, "AIDL": 1} | package com.guoxiaoxing.phoenix.picker.rx.bus
import com.guoxiaoxing.phoenix.core.model.MediaEntity
import com.guoxiaoxing.phoenix.picker.model.MediaFolder
interface ObserverListener {
fun observerUpFoldersData(folders: List<MediaFolder>)
fun observerUpSelectsData(selectMediaEntities: List<MediaEntity>)
}
| 0 | Kotlin | 2 | 4 | 2fec69b68b593b6eca530019f383d25699b6650b | 318 | qmqiu | Apache License 2.0 |
library/src/jvmTest/kotlin/effekt/casestudies/Anf.kt | kyay10 | 791,451,737 | false | {"Kotlin": 145029, "JavaScript": 90} | @file:Suppress("CONTEXT_RECEIVERS_DEPRECATED")
package effekt.casestudies
import arrow.core.Either
import effekt.get
import effekt.handle
import effekt.handleStateful
import effekt.use
import io.kotest.matchers.shouldBe
import runTestCC
import kotlin.test.Test
class AnfTest {
// let x = f(g(42)) in x
private val exampleTree: Tree = Let("x", App("f", App("g", Lit(42))), Var("x"))
@Test
fun example() = runTestCC {
translate(exampleTree) shouldBe CLet(
"x", CLet("x1", CRet(CLit(42)), CLet("x2", CApp("g", CVar("x1")), CApp("f", CVar("x2")))), CRet(CVar("x"))
)
pretty(translate(exampleTree)) shouldBe """
|let x = let x1 = return 42 in let x2 =
| g(x1)
| in f(x2) in return x
""".trimMargin()
pipeline("42") shouldBe """
|return 42
""".trimMargin()
pipeline("let x = 4 in 42") shouldBe """
|let x = return 4 in return 42
""".trimMargin()
pipeline("let x = let y = 2 in 1 in 42") shouldBe """
|let x = let y = return 2 in return 1 in
| return 42
""".trimMargin()
pipeline("let x = (let y = 2 in 1) in 42") shouldBe """
|let x = let y = return 2 in return 1 in
| return 42
""".trimMargin()
pipeline("let x = (let y = f(42) in 1) in 42") shouldBe """
|let x = let y = let x1 = return 42 in f(
| x1
| ) in return 1 in return 42
""".trimMargin()
}
}
sealed interface Expr
data class CLit(val value: Int) : Expr
data class CVar(val name: String) : Expr
sealed interface Stmt
data class CLet(val name: String, val binding: Stmt, val body: Stmt) : Stmt
data class CApp(val name: String, val arg: Expr) : Stmt
data class CRet(val expr: Expr) : Stmt
fun interface Fresh {
suspend fun fresh(): String
}
suspend fun <R> freshVars(block: suspend context(Fresh) () -> R): R {
data class Data(var i: Int)
return handleStateful(Data(0), Data::copy) {
block {
"x${++(get().i)}"
}
}
}
fun interface Bind {
suspend fun Stmt.bind(): Expr
}
context(Bind, Fresh)
suspend fun Tree.toStmt(): Stmt = when (this) {
is Lit -> CRet(CLit(value))
is Var -> CRet(CVar(name))
// Here we use bind since other than App, CApp requires an expression
is App -> CApp(name, arg.toStmt().bind())
// here we use the handler `bindHere` to mark positions where bindings
// should be inserted.
is Let -> CLet(name, bindHere { binding.toStmt() }, bindHere { body.toStmt() })
}
context(Fresh)
suspend fun bindHere(block: suspend context(Bind) () -> Stmt): Stmt = handle {
block {
use { resume ->
val id = fresh()
CLet(id, this, resume(CVar(id)))
}
}
}
suspend fun translate(e: Tree): Stmt = freshVars { bindHere { e.toStmt() } }
context(Emit)
suspend fun Expr.emit() = text(
when (this) {
is CLit -> value.toString()
is CVar -> name
}
)
context(Indent, DefaultIndent, Flow, Emit, LayoutChoice)
suspend fun Stmt.emit(): Unit = when (this) {
is CLet -> {
text("let"); space(); text(name); space(); text("=")
group {
nested { line(); binding.emit() }
line()
text("in")
}
group { nested { line(); body.emit() } }
}
is CApp -> {
text(name); parens {
group {
nested {
linebreak()
arg.emit()
}
linebreak()
}
}
}
is CRet -> {
text("return"); space(); expr.emit()
}
}
suspend fun pretty(s: Stmt): String = pretty(40) { s.emit() }
suspend fun pipeline(input: String): String = when (val res = parse(input) { parseExpr() }) {
is Either.Right -> pretty(translate(res.value))
is Either.Left -> res.value
} | 5 | Kotlin | 0 | 8 | f608d6f3e3aab65774eb86eaeb09ce0a57698ce4 | 3,630 | KonTinuity | Apache License 2.0 |
AOS/RunWithMe/app/src/main/java/com/ssafy/runwithme/utils/XAccessTokenInterceptor.kt | HanYeop | 531,735,030 | false | {"Kotlin": 709496, "Java": 423758, "JavaScript": 47091, "CSS": 6540, "HTML": 2192, "Shell": 199, "Dockerfile": 176} | package com.ssafy.runwithme.utils
import android.content.SharedPreferences
import kotlinx.coroutines.runBlocking
import okhttp3.Interceptor
import okhttp3.Response
import javax.inject.Inject
class XAccessTokenInterceptor @Inject constructor(
private val sharedPref: SharedPreferences
): Interceptor {
override fun intercept(chain: Interceptor.Chain): Response {
var token = runBlocking {
sharedPref.getString(JWT,"")!!
}
val request = chain.request().newBuilder()
.addHeader(JWT, token)
.build()
return chain.proceed(request)
}
} | 0 | Kotlin | 0 | 4 | bf0a00a69c40361dbe44a8a3e159c9b69f1ade6f | 612 | RunWithMe | MIT License |
ktfx-commons/src/test/kotlin/ktfx/collections/ObservableArraysTest.kt | hanggrian | 102,934,147 | false | {"Kotlin": 1146536, "CSS": 1653} | package ktfx.collections
import com.google.common.truth.Truth.assertThat
import kotlin.test.Test
import kotlin.test.assertEquals
import kotlin.test.assertFalse
import kotlin.test.assertTrue
class ObservableArraysTest {
@Test
fun indices() {
assertThat(observableIntArrayOf(1, 2).indices)
.containsExactly(0, 1)
}
@Test
fun lastIndex() {
assertEquals(1, observableIntArrayOf(1, 2).lastIndex)
}
@Test
fun isEmpty() {
assertFalse(observableIntArrayOf(1, 2).isEmpty())
}
@Test
fun isNotEmpty() {
assertTrue(observableIntArrayOf(1, 2).isNotEmpty())
}
@Test
fun sizeBinding() {
val ints = observableIntArrayOf(1, 2)
val binding = ints.sizeBinding
assertEquals(2, binding.value)
ints += 3
assertEquals(3, binding.value)
}
}
| 1 | Kotlin | 2 | 19 | 6e5ec9fedf8359423c31a2ba64cd175bc9864cd2 | 867 | ktfx | Apache License 2.0 |
src/main/kotlin/nl/bjornvanderlaan/livedemospringwebflux/model/CatDto.kt | BjornvdLaan | 507,929,903 | false | {"Kotlin": 25185} | package nl.bjornvanderlaan.livedemospringwebflux.model
data class CatDto(
val name: String,
val type: String,
val age: Int,
val ownerId: Long? = null,
val owner: Person? = null
)
fun CatDto.toEntity(): Cat = Cat(
name = this.name,
type = this.type,
age = this.age,
ownerId = this.ownerId
) | 0 | Kotlin | 1 | 0 | 78872771f5d93f108b1875ed746b890af2c4a573 | 327 | live-demo-spring-webflux-kotlin | MIT License |
org.librarysimplified.http.tests/src/test/java/org/librarysimplified/http/tests/LSHTTPClientTest.kt | ThePalaceProject | 491,628,613 | false | {"Kotlin": 175869, "Java": 1556} | package org.librarysimplified.http.tests
import org.librarysimplified.http.api.LSHTTPClientProviderType
import org.librarysimplified.http.api.LSHTTPProblemReportParserFactoryType
import org.librarysimplified.http.vanilla.LSHTTPClients
class LSHTTPClientTest : LSHTTPClientContract() {
override fun clients(parsers: LSHTTPProblemReportParserFactoryType): LSHTTPClientProviderType {
return LSHTTPClients(
parsers,
listOf(),
)
}
}
| 0 | Kotlin | 0 | 0 | 8420d312a77c4f96ed68469f5d83c7235616e8d4 | 454 | android-http | Apache License 2.0 |
compiler/testData/codegen/boxInline/anonymousObject/objectInLambdaCapturesAnotherObject.kt | JakeWharton | 99,388,807 | true | null | // IGNORE_BACKEND: JVM_IR
// FILE: 1.kt
package test
public inline fun myRun(block: () -> Unit) {
return block()
}
// FILE: 2.kt
//NO_CHECK_LAMBDA_INLINING
import test.*
fun box(): String {
var res = ""
myRun {
val x = object {
fun foo() {
res = "OK"
}
}
object {
fun bar() = x.foo()
}.bar()
}
return res
}
| 0 | Kotlin | 28 | 83 | 4383335168338df9bbbe2a63cb213a68d0858104 | 416 | kotlin | Apache License 2.0 |
app/src/main/java/org/wikipedia/bridge/CommunicationBridge.kt | greatfire | 460,298,221 | false | null | package org.wikipedia.bridge
import android.annotation.SuppressLint
import android.os.Handler
import android.os.Looper
import android.os.Message
import android.webkit.*
import com.google.gson.JsonObject
import org.wikipedia.bridge.JavaScriptActionHandler.setUp
import org.wikipedia.dataclient.RestService
import org.wikipedia.dataclient.ServiceFactory
import org.wikipedia.json.GsonUtil
import org.wikipedia.page.PageTitle
import org.wikipedia.page.PageViewModel
import org.wikipedia.util.UriUtil
import org.wikipedia.util.log.L
/**
* Two-way communications bridge between JS in a WebView and Java.
*
* Messages TO the WebView are sent by calling loadUrl() with the Javascript payload in it.
*
* Messages FROM the WebView are received by leveraging @JavascriptInterface methods.
*/
@SuppressLint("AddJavascriptInterface", "SetJavaScriptEnabled")
class CommunicationBridge constructor(private val communicationBridgeListener: CommunicationBridgeListener) {
private val eventListeners = HashMap<String, MutableList<JSEventListener>>()
private var isMetadataReady = false
private var isPcsReady = false
private val pendingJSMessages = ArrayList<String>()
private val pendingEvals = HashMap<String, ValueCallback<String>>()
interface JSEventListener {
fun onMessage(messageType: String, messagePayload: JsonObject?)
}
interface CommunicationBridgeListener {
val webView: WebView
val model: PageViewModel
val isPreview: Boolean
val toolbarMargin: Int
}
init {
communicationBridgeListener.webView.settings.javaScriptEnabled = true
communicationBridgeListener.webView.settings.allowUniversalAccessFromFileURLs = true
communicationBridgeListener.webView.settings.mediaPlaybackRequiresUserGesture = false
communicationBridgeListener.webView.webChromeClient = CommunicatingChrome()
communicationBridgeListener.webView.addJavascriptInterface(PcsClientJavascriptInterface(), "pcsClient")
}
fun onPcsReady() {
isPcsReady = true
flushMessages()
}
fun loadBlankPage() {
communicationBridgeListener.webView.loadUrl("about:blank")
}
fun onMetadataReady() {
isMetadataReady = true
flushMessages()
}
val isLoading: Boolean
get() = !(isMetadataReady && isPcsReady)
fun resetHtml(pageTitle: PageTitle) {
isPcsReady = false
isMetadataReady = false
pendingJSMessages.clear()
pendingEvals.clear()
if (communicationBridgeListener.model.shouldLoadAsMobileWeb()) {
communicationBridgeListener.webView.loadUrl(pageTitle.mobileUri)
} else {
communicationBridgeListener.webView.loadUrl(ServiceFactory.getRestBasePath(pageTitle.wikiSite) +
RestService.PAGE_HTML_ENDPOINT + UriUtil.encodeURL(pageTitle.prefixedText))
}
}
fun cleanup() {
pendingJSMessages.clear()
pendingEvals.clear()
eventListeners.clear()
incomingMessageHandler?.removeCallbacksAndMessages(null)
incomingMessageHandler = null
communicationBridgeListener.webView.webViewClient = WebViewClient()
communicationBridgeListener.webView.removeJavascriptInterface("pcsClient")
// Explicitly load a blank page into the WebView, to stop playback of any media.
loadBlankPage()
}
fun addListener(type: String, listener: JSEventListener) {
if (eventListeners.containsKey(type)) {
eventListeners[type]!!.add(listener)
} else {
val listeners = ArrayList<JSEventListener>()
listeners.add(listener)
eventListeners[type] = listeners
}
}
fun execute(js: String) {
pendingJSMessages.add("javascript:$js")
flushMessages()
}
fun evaluate(js: String, callback: ValueCallback<String>) {
pendingEvals[js] = callback
flushMessages()
}
fun evaluateImmediate(js: String, callback: ValueCallback<String?>?) {
communicationBridgeListener.webView.evaluateJavascript(js, callback)
}
private fun flushMessages() {
if (!isPcsReady || !isMetadataReady) {
return
}
for (jsString in pendingJSMessages) {
communicationBridgeListener.webView.loadUrl(jsString)
}
pendingJSMessages.clear()
for (key in pendingEvals.keys) {
communicationBridgeListener.webView.evaluateJavascript(key, pendingEvals[key])
}
pendingEvals.clear()
}
private var incomingMessageHandler: Handler? = Handler(Looper.getMainLooper(), Handler.Callback { msg ->
val message = msg.obj as BridgeMessage
if (!eventListeners.containsKey(message.action)) {
L.e("No such message type registered: " + message.action)
return@Callback false
}
try {
val listeners: List<JSEventListener> = eventListeners[message.action]!!
for (listener in listeners) {
listener.onMessage(message.action!!, message.data)
}
} catch (e: Exception) {
e.printStackTrace()
L.logRemoteError(e)
}
false
})
private class CommunicatingChrome : WebChromeClient() {
override fun onConsoleMessage(consoleMessage: ConsoleMessage): Boolean {
L.d(consoleMessage.sourceId() + ":" + consoleMessage.lineNumber() + " - " + consoleMessage.message())
return true
}
}
private inner class PcsClientJavascriptInterface {
/**
* Called from Javascript to send a message packet to the Java layer. The message must be
* formatted in JSON, and URL-encoded.
*
* @param message JSON structured message received from the WebView.
*/
@JavascriptInterface
@Synchronized
fun onReceiveMessage(message: String?) {
if (incomingMessageHandler != null) {
val msg = Message.obtain(incomingMessageHandler, MESSAGE_HANDLE_MESSAGE_FROM_JS,
GsonUtil.getDefaultGson().fromJson(message, BridgeMessage::class.java))
incomingMessageHandler!!.sendMessage(msg)
}
}
@get:Synchronized
@get:JavascriptInterface
val setupSettings: String
get() = setUp(communicationBridgeListener.webView.context,
communicationBridgeListener.model.title!!, communicationBridgeListener.isPreview,
communicationBridgeListener.toolbarMargin)
}
private class BridgeMessage {
val action: String? = null
get() = field.orEmpty()
val data: JsonObject? = null
}
companion object {
private const val MESSAGE_HANDLE_MESSAGE_FROM_JS = 1
}
}
| 2 | null | 4 | 38 | 8c8de602274b0132fc5d22b394a2c47fcd0bf2eb | 6,875 | apps-android-wikipedia-envoy | Apache License 2.0 |
compose-guard/core/src/test/kotlin/com/joetr/compose/guard/core/ComposeCompilerMetricsProviderTest.kt | j-roskopf | 800,960,208 | false | null | /**
* MIT License
*
* Copyright (c) 2024 Joe Roskopf
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package com.joetr.compose.guard.core
import com.joetr.compose.guard.core.model.StabilityStatus
import org.junit.Before
import org.junit.Rule
import org.junit.Test
import org.junit.rules.TemporaryFolder
import java.io.File
class ComposeCompilerMetricsProviderTest {
@JvmField
@Rule
var folder: TemporaryFolder = TemporaryFolder()
lateinit var reportDirectory: File
@Before
fun before() {
reportDirectory = folder.newFolder("reports/compose")
val classesTxt = folder.newFile("reports/compose/feature_release-classes.txt")
val composableCsv = folder.newFile("reports/compose/feature_release-composables.csv")
val composablesTxt = folder.newFile("reports/compose/feature_release-composables.txt")
val moduleJson = folder.newFile("reports/compose/feature_release-module.json")
classesTxt.writeText(
"""
unstable class TestDataClass {
stable var name: String
<runtime stability> = Unstable
}
""".trimIndent(),
)
composableCsv.writeText(
"""
package,name,composable,skippable,restartable,readonly,inline,isLambda,hasDefaults,defaultsGroup,groups,calls,
com.example.myapplication.feature.MyComposable,MyComposable,1,1,1,0,0,0,1,0,2,1,
""".trimIndent(),
)
composablesTxt.writeText(
"""
restartable skippable scheme("[androidx.compose.ui.UiComposable]") fun MyComposable(
stable modifier: Modifier? = @static Companion
unstable testClass: TestDataClass? = @dynamic TestDataClass("default")
unused stable nonDefaultParameter: Int
)
""".trimIndent(),
)
moduleJson.writeText(
"""
{
"skippableComposables": 1,
"restartableComposables": 1,
"readonlyComposables": 0,
"totalComposables": 1,
"restartGroups": 1,
"totalGroups": 2,
"staticArguments": 0,
"certainArguments": 1,
"knownStableArguments": 17,
"knownUnstableArguments": 0,
"unknownStableArguments": 0,
"totalArguments": 17,
"markedStableClasses": 0,
"inferredStableClasses": 0,
"inferredUnstableClasses": 1,
"inferredUncertainClasses": 0,
"effectivelyStableClasses": 0,
"totalClasses": 1,
"memoizedLambdas": 0,
"singletonLambdas": 0,
"singletonComposableLambdas": 0,
"composableLambdas": 0,
"totalLambdas": 0
}
""".trimIndent(),
)
}
@Test
fun `parse dynamic parameters`() {
val metrics =
ComposeCompilerMetricsProvider(
ComposeCompilerRawReportProvider.FromDirectory(
directory = reportDirectory,
),
)
val amountOfDynamicProperties =
metrics.getComposablesReport().composables.flatMap {
it.params
}.count {
it.stabilityStatus == StabilityStatus.DYNAMIC
}
val amountOfStaticProperties =
metrics.getComposablesReport().composables.flatMap {
it.params
}.count {
it.stabilityStatus == StabilityStatus.STATIC
}
val amountOfMissingProperties =
metrics.getComposablesReport().composables.flatMap {
it.params
}.count {
it.stabilityStatus == StabilityStatus.MISSING
}
val amountOfUnusedProperties =
metrics.getComposablesReport().composables.flatMap {
it.params
}.count {
it.unused
}
assert(amountOfDynamicProperties == 1)
assert(amountOfStaticProperties == 1)
assert(amountOfMissingProperties == 1)
assert(amountOfUnusedProperties == 1)
}
}
| 1 | null | 2 | 80 | 44c8a547b98b600f39b21df3a2fefa781b676db6 | 5,248 | ComposeGuard | MIT License |
composeApp/src/commonMain/kotlin/io/github/snd_r/komelia/ui/common/cards/BookItemCard.kt | Snd-R | 775,064,249 | false | null | package io.github.snd_r.komelia.ui.common.cards
import androidx.compose.foundation.Canvas
import androidx.compose.foundation.ExperimentalFoundationApi
import androidx.compose.foundation.background
import androidx.compose.foundation.combinedClickable
import androidx.compose.foundation.hoverable
import androidx.compose.foundation.interaction.MutableInteractionSource
import androidx.compose.foundation.interaction.collectIsHoveredAsState
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.PaddingValues
import androidx.compose.foundation.layout.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.heightIn
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.layout.widthIn
import androidx.compose.foundation.lazy.LazyRow
import androidx.compose.foundation.lazy.items
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.automirrored.rounded.MenuBook
import androidx.compose.material.icons.filled.MoreVert
import androidx.compose.material3.ButtonDefaults
import androidx.compose.material3.Card
import androidx.compose.material3.FilledTonalButton
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.IconButtonDefaults
import androidx.compose.material3.LinearProgressIndicator
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Text
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.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.geometry.Offset
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.Path
import androidx.compose.ui.graphics.Shadow
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.unit.dp
import io.github.snd_r.komelia.platform.WindowWidth.COMPACT
import io.github.snd_r.komelia.platform.WindowWidth.MEDIUM
import io.github.snd_r.komelia.platform.cursorForHand
import io.github.snd_r.komelia.ui.LocalWindowWidth
import io.github.snd_r.komelia.ui.common.NoPaddingChip
import io.github.snd_r.komelia.ui.common.images.BookThumbnail
import io.github.snd_r.komelia.ui.common.menus.BookActionsMenu
import io.github.snd_r.komelia.ui.common.menus.BookMenuActions
import io.github.snd_r.komga.book.KomgaBook
@Composable
fun BookImageCard(
book: KomgaBook,
bookMenuActions: BookMenuActions?,
onBookClick: (() -> Unit)? = null,
onBookReadClick: (() -> Unit)? = null,
isSelected: Boolean = false,
onSelect: (() -> Unit)? = null,
modifier: Modifier = Modifier,
) {
ItemCard(
modifier = modifier,
onClick = onBookClick,
onLongClick = onSelect
) {
BookHoverOverlay(
book = book,
bookMenuActions = bookMenuActions,
onBookReadClick = onBookReadClick,
onSelect = onSelect,
isSelected = isSelected,
) {
BookImageOverlay(book) {
BookThumbnail(book.id, modifier = Modifier.fillMaxSize(), contentScale = ContentScale.Crop)
}
}
}
}
@Composable
fun BookSimpleImageCard(
book: KomgaBook,
onBookClick: (() -> Unit)? = null,
modifier: Modifier = Modifier
) {
ItemCard(modifier, onBookClick) {
BookImageOverlay(book, false) {
BookThumbnail(book.id, modifier = Modifier.fillMaxSize(), contentScale = ContentScale.Crop)
}
}
}
@Composable
private fun BookImageOverlay(
book: KomgaBook,
showTitle: Boolean = true,
content: @Composable () -> Unit
) {
Box(contentAlignment = Alignment.Center) {
content()
if (showTitle)
CardGradientOverlay()
Column {
if (book.readProgress == null)
Row {
Spacer(Modifier.weight(1f))
BookUnreadTick()
}
Spacer(modifier = Modifier.weight(1f))
Column(Modifier.padding(10.dp)) {
if (showTitle) {
Text(
text = book.metadata.title,
maxLines = 4,
style = MaterialTheme.typography.bodyMedium.copy(
color = Color.White,
shadow = Shadow(
color = Color.Black,
offset = Offset(-1f, -1f),
blurRadius = 0f
),
),
)
}
if (book.deleted) {
Text(
text = "Unavailable",
style = MaterialTheme.typography.bodyMedium.copy(
color = MaterialTheme.colorScheme.error,
shadow = Shadow(
color = Color.Black,
offset = Offset(-1f, -1f),
blurRadius = 0f
),
),
)
}
}
val readProgress = book.readProgress
if (readProgress != null && !readProgress.completed) {
LinearProgressIndicator(
progress = { getReadProgressPercentage(book) },
color = MaterialTheme.colorScheme.tertiary,
trackColor = MaterialTheme.colorScheme.tertiary.copy(alpha = 0.5f),
modifier = Modifier.height(6.dp).fillMaxWidth().background(Color.Black),
)
}
}
}
}
@Composable
private fun BookUnreadTick() {
val color = MaterialTheme.colorScheme.tertiary
Canvas(modifier = Modifier.size(30.dp)) {
val trianglePath = Path().apply {
moveTo(0f, 0f)
lineTo(x = size.width, y = size.height)
lineTo(x = size.width, y = size.height)
lineTo(x = size.width, y = 0f)
}
drawPath(
color = color,
path = trianglePath
)
}
}
@Composable
private fun BookHoverOverlay(
book: KomgaBook,
bookMenuActions: BookMenuActions?,
onBookReadClick: (() -> Unit)?,
isSelected: Boolean,
onSelect: (() -> Unit)?,
content: @Composable () -> Unit
) {
var isActionsMenuExpanded by remember { mutableStateOf(false) }
val interactionSource = remember { MutableInteractionSource() }
val isHovered = interactionSource.collectIsHoveredAsState()
val showOverlay = derivedStateOf { isHovered.value || isActionsMenuExpanded || isSelected }
val border = if (showOverlay.value) overlayBorderModifier() else Modifier
Box(
modifier = Modifier
.fillMaxSize()
.hoverable(interactionSource)
.then(border),
contentAlignment = Alignment.Center
) {
content()
if (showOverlay.value) {
val backgroundColor =
if (isSelected)
Modifier.background(MaterialTheme.colorScheme.secondary.copy(alpha = .5f))
else Modifier
Column(backgroundColor.fillMaxSize()) {
if (onSelect != null) {
SelectionRadioButton(isSelected, onSelect)
Spacer(Modifier.weight(1f))
}
Row(
modifier = Modifier.padding(vertical = 5.dp).fillMaxSize(),
verticalAlignment = Alignment.Bottom,
) {
if (onBookReadClick != null) {
ReadButton(onBookReadClick)
}
Spacer(Modifier.weight(1f))
if (bookMenuActions != null)
BookMenuActionsDropdown(
book = book,
bookMenuActions = bookMenuActions,
isActionsMenuExpanded = isActionsMenuExpanded,
onActionsMenuExpand = { isActionsMenuExpanded = it }
)
}
}
}
}
}
private fun getReadProgressPercentage(book: KomgaBook): Float {
val progress = book.readProgress ?: return 0f
if (progress.completed) return 100f
return progress.page / book.media.pagesCount.toFloat()
}
@OptIn(ExperimentalFoundationApi::class)
@Composable
fun BookDetailedListCard(
book: KomgaBook,
onClick: (() -> Unit)? = null,
bookMenuActions: BookMenuActions? = null,
onBookReadClick: (() -> Unit)? = null,
isSelected: Boolean = false,
onSelect: (() -> Unit)? = null,
modifier: Modifier = Modifier
) {
val interactionSource = remember { MutableInteractionSource() }
val isHovered = interactionSource.collectIsHoveredAsState()
Card(
modifier
.cursorForHand()
.combinedClickable(onClick = onClick ?: {}, onLongClick = onSelect)
.hoverable(interactionSource)
.fillMaxWidth()
) {
Row(
modifier = Modifier
.heightIn(max = 220.dp)
.fillMaxWidth()
.then(
if (isSelected) Modifier.background(MaterialTheme.colorScheme.secondary.copy(alpha = .3f))
else Modifier
)
.padding(10.dp),
verticalAlignment = Alignment.CenterVertically
) {
Box {
BookSimpleImageCard(book)
if (onSelect != null && (isSelected || isHovered.value)) {
SelectionRadioButton(isSelected, onSelect)
}
}
BookDetailedListDetails(
book = book,
bookMenuActions = bookMenuActions,
onBookReadClick = onBookReadClick,
isSelected = isSelected,
onSelect = onSelect
)
}
}
}
@Composable
private fun BookDetailedListDetails(
book: KomgaBook,
bookMenuActions: BookMenuActions?,
onBookReadClick: (() -> Unit)? = null,
isSelected: Boolean,
onSelect: (() -> Unit)?,
) {
val width = LocalWindowWidth.current
Column(Modifier.padding(start = 10.dp)) {
Row(verticalAlignment = Alignment.CenterVertically) {
Text(
book.metadata.title,
fontWeight = FontWeight.Bold,
maxLines = when (width) {
COMPACT, MEDIUM -> 2
else -> 4
}
)
}
LazyRow(
modifier = Modifier.padding(vertical = 5.dp),
horizontalArrangement = Arrangement.spacedBy(5.dp),
verticalAlignment = Alignment.CenterVertically
) {
item { Text("${book.media.pagesCount} pages", style = MaterialTheme.typography.bodySmall) }
items(book.metadata.tags) {
NoPaddingChip(
borderColor = MaterialTheme.colorScheme.surface,
color = MaterialTheme.colorScheme.surface
) {
Text(it, style = MaterialTheme.typography.labelMedium, fontWeight = FontWeight.Bold)
}
}
}
Text(
book.metadata.summary,
maxLines = when (width) {
COMPACT, MEDIUM -> 3
else -> 4
},
style = MaterialTheme.typography.bodyMedium,
overflow = TextOverflow.Ellipsis,
modifier = Modifier.widthIn(max = 1500.dp)
)
Spacer(Modifier.weight(1f))
Row(horizontalArrangement = Arrangement.Start) {
if (onBookReadClick != null) {
ReadButton(onBookReadClick)
}
if (bookMenuActions != null) {
Box {
var isMenuExpanded by remember { mutableStateOf(false) }
IconButton(
onClick = { isMenuExpanded = true },
colors = IconButtonDefaults.iconButtonColors(containerColor = MaterialTheme.colorScheme.surfaceVariant)
) {
Icon(Icons.Default.MoreVert, null)
}
BookActionsMenu(
book = book,
actions = bookMenuActions,
expanded = isMenuExpanded,
onDismissRequest = { isMenuExpanded = false },
)
}
}
}
}
}
@Composable
private fun ReadButton(onClick: () -> Unit) {
FilledTonalButton(
modifier = Modifier.padding(horizontal = 5.dp),
shape = RoundedCornerShape(10.dp),
colors = ButtonDefaults.outlinedButtonColors(containerColor = MaterialTheme.colorScheme.tertiaryContainer),
onClick = onClick,
contentPadding = PaddingValues(vertical = 5.dp, horizontal = 15.dp)
) {
Icon(Icons.AutoMirrored.Rounded.MenuBook, null)
Spacer(Modifier.width(10.dp))
Text("Read")
}
}
@Composable
private fun BookMenuActionsDropdown(
book: KomgaBook,
bookMenuActions: BookMenuActions,
isActionsMenuExpanded: Boolean,
onActionsMenuExpand: (Boolean) -> Unit
) {
Box {
IconButton(
onClick = { onActionsMenuExpand(true) },
colors = IconButtonDefaults.iconButtonColors(containerColor = MaterialTheme.colorScheme.surface)
) {
Icon(Icons.Default.MoreVert, null)
}
BookActionsMenu(
book = book,
actions = bookMenuActions,
expanded = isActionsMenuExpanded,
onDismissRequest = { onActionsMenuExpand(false) },
)
}
}
| 3 | null | 1 | 9 | 5a16d84ed86321e4c7efa96daea9dd7dbfc2308b | 14,568 | Komelia | Apache License 2.0 |
core/src/main/java/com/lionparcel/commonandroid/form/utils/BulkAttachFileAdapter.kt | Lionparcel | 258,373,753 | false | null | package com.lionparcel.commonandroid.form.utils
import android.app.Activity
import android.net.Uri
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.recyclerview.widget.RecyclerView
import com.lionparcel.commonandroid.R
import kotlinx.android.extensions.LayoutContainer
import kotlinx.android.synthetic.main.lp_bulk_attach_file_image_list.*
import kotlinx.android.synthetic.main.lp_bulk_attach_file_view.*
class BulkAttachFileAdapter(
private val listImage : ArrayList<Uri>,
var isEnable : Boolean,
var isError: Boolean ,
private var onItemClicked : ((visibility : Boolean) -> Unit),
private var onPhotoClicked: ((Uri) -> Unit),
private var onPhotoDismiss: ((Uri) -> Unit)
) : RecyclerView.Adapter<BulkAttachFileAdapter.BulkAttachFileViewHolder>() {
private fun deleteImage( position: Int) {
listImage.removeAt(position)
notifyItemRemoved(position)
notifyItemRangeChanged(position, listImage.size)
notifyDataSetChanged()
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): BulkAttachFileViewHolder {
return BulkAttachFileViewHolder(LayoutInflater.from(parent.context).inflate(R.layout.lp_bulk_attach_file_image_list, parent, false))
}
override fun onBindViewHolder(holder: BulkAttachFileViewHolder, position: Int) {
holder.bind(listImage[position], position, isEnable, isError)
}
override fun getItemCount(): Int = listImage.size
inner class BulkAttachFileViewHolder(override val containerView: View) : RecyclerView.ViewHolder(containerView),
LayoutContainer{
fun bind(data : Uri, position: Int, isEnable: Boolean, isError : Boolean){
vwOutlinedBulkAttachFile.isSelected = isError
ivPreviewBulkAttachFile.setImageURI(data)
ibDeletePreviewBulkAttachFile.isEnabled = isEnable
ibDeletePreviewBulkAttachFile.setOnClickListener {
deleteImage(position)
onItemClicked(true)
onPhotoDismiss.invoke(data)
notifyDataSetChanged()
}
ivPreviewBulkAttachFile.setOnClickListener {
onPhotoClicked.invoke(data)
}
}
}
fun enableClose(isEnabled: Boolean) {
this.isEnable = isEnabled
notifyDataSetChanged()
}
fun errorView(isError : Boolean){
this.isError = isError
notifyDataSetChanged()
}
} | 0 | Kotlin | 0 | 0 | e798c14e86433fd232d6063425fdf70505af8014 | 2,556 | common-android | MIT License |
BrasileiraoApp/repository/game-impl/src/main/kotlin/br/com/brasileiraoapp/repository/GameRepositoryImpl.kt | brunoh-almeida | 373,182,895 | false | null | package br.com.brasileiraoapp.repository
import br.com.brasileiraoapp.api.GameApi
import br.com.brasileiraoapp.database.dao.GameDao
import br.com.brasileiraoapp.mapper.GameEntityToGameResponseMapper
import br.com.brasileiraoapp.mapper.GameResponseToGameEntityMapper
import br.com.brasileiraoapp.network.response.NetworkError
import br.com.brasileiraoapp.network.response.NetworkResponse
import br.com.brasileiraoapp.network.response.ZeroResultException
import br.com.brasileiraoapp.network.safeApiCall
import repository.GameRepository
import response.GameResponse
class GameRepositoryImpl(
private val gameApi: GameApi,
private val gameDao: GameDao,
private val gameResponseMapper: GameEntityToGameResponseMapper,
private val gameEntityMapper: GameResponseToGameEntityMapper
) : GameRepository {
override suspend fun getGamesById(gameId: Long):
NetworkResponse<GameResponse, NetworkError> {
gameDao.getGame(gameId)?.let {
return NetworkResponse.Success(gameResponseMapper.mapFrom(it))
} ?: run {
return safeApiCall {
gameApi.getGameById(gameId).content ?: throw ZeroResultException()
}
}
}
override suspend fun getGamesByRound(
round: Int
): NetworkResponse<List<GameResponse>, NetworkError> {
val gamesEntities = gameDao.getGamesByRound(round)
return if (!gamesEntities.isNullOrEmpty()) {
NetworkResponse.Success(
gamesEntities.map { gameResponseMapper.mapFrom(it) }
)
} else {
safeApiCall {
val games = gameApi.getGamesByRound(round).content
games?.forEach {
gameDao.insertAll(gameEntityMapper.mapFrom(it))
}
games ?: listOf()
}
}
}
override suspend fun getGames(): NetworkResponse<List<GameResponse>, NetworkError> {
return safeApiCall {
gameApi.getGames().content ?: listOf()
}
}
override suspend fun getGamesByDay(day: String): NetworkResponse<List<GameResponse>, NetworkError> {
return safeApiCall {
gameApi.getGamesByDay(day).content ?: listOf()
}
}
override suspend fun getGamesByTeam(teamId: Long):
NetworkResponse<List<GameResponse>, NetworkError> {
return safeApiCall {
gameApi.getGamesByTeam(teamId).content ?: listOf()
}
}
} | 0 | Kotlin | 0 | 1 | 0df0b3a594143d921448fbe6f8cf1a1fd6747313 | 2,476 | brasileirao-app | MIT License |
modules/api-remote/src/main/kotlin/ru/astrainteractive/astratemplate/api/remote/RickMortyApiImpl.kt | Astra-Interactive | 378,620,934 | false | null | package ru.astrainteractive.astratemplate.api.remote
import kotlinx.serialization.decodeFromString
import kotlinx.serialization.json.Json
import ru.astrainteractive.astralibs.http.HttpClient
import ru.astrainteractive.astratemplate.api.remote.models.RMResponse
/**
* This is a simple implementation of [RickMortyApi] REST GET request
*/
internal class RickMortyApiImpl(
private val client: HttpClient
) : RickMortyApi {
override suspend fun getRandomCharacter(id: Int): Result<RMResponse> = kotlin.runCatching {
val json = client.get("https://rickandmortyapi.com/api/character/$id").getOrThrow()
Json.decodeFromString<RMResponse>(json)
}
}
| 0 | Kotlin | 0 | 13 | 593a4d31150d76439d1b386206e3f54b67abfff3 | 672 | AstraTemplate | MIT License |
kindex/src/main/kotlin/MavenClient.kt | Monkopedia | 305,151,965 | false | {"Kotlin": 381076, "JavaScript": 1289, "HTML": 912} | /*
* Copyright 2020 Jason Monk
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.monkopedia.kindex
import com.fasterxml.jackson.annotation.JsonRootName
import com.fasterxml.jackson.databind.DeserializationFeature
import com.fasterxml.jackson.databind.MapperFeature
import com.fasterxml.jackson.databind.annotation.JsonSerialize
import com.fasterxml.jackson.dataformat.xml.JacksonXmlModule
import com.fasterxml.jackson.dataformat.xml.XmlMapper
import com.fasterxml.jackson.module.kotlin.readValue
import com.fasterxml.jackson.module.kotlin.registerKotlinModule
import io.ktor.client.HttpClient
import io.ktor.client.request.get
import io.ktor.client.statement.HttpResponse
import io.ktor.utils.io.jvm.javaio.toInputStream
import java.io.File
import kotlinx.serialization.Serializable
private val mapper = XmlMapper(
JacksonXmlModule().apply {
setDefaultUseWrapper(false)
}
).registerKotlinModule()
.configure(MapperFeature.ACCEPT_CASE_INSENSITIVE_PROPERTIES, true)
.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false)
@Serializable
data class MavenArtifact(
val pkg: String,
val target: String,
val version: String? = null
) {
val isResolved get() = version != null
override fun toString(): String {
if (version != null) {
return "$pkg:$target:$version"
}
return shortString()
}
fun shortString(): String = "$pkg:$target"
companion object {
fun from(spec: String): MavenArtifact {
val parts = spec.split(":")
return if (parts.size < 3) {
MavenArtifact(parts[0], parts[1])
} else {
MavenArtifact(parts[0], parts[1], parts[2])
}
}
}
}
interface MavenClient {
suspend fun has(artifact: MavenArtifact): Boolean
suspend fun resolve(artifact: MavenArtifact): MavenArtifact
suspend fun getSources(artifact: MavenArtifact, output: File)
companion object {
fun forUrls(vararg urls: String): MavenClient {
return MultiClient(urls.map { MavenClientImpl(it) })
}
}
}
private class MultiClient(private val clients: List<MavenClient>) : MavenClient {
override suspend fun has(artifact: MavenArtifact): Boolean = clients.any { it.has(artifact) }
override suspend fun resolve(artifact: MavenArtifact): MavenArtifact {
if (artifact.isResolved) {
return artifact
}
return clients.find { it.has(artifact) }?.resolve(artifact)
?: throw IllegalArgumentException("Can't find repo holding $artifact")
}
override suspend fun getSources(artifact: MavenArtifact, output: File) {
clients.find { it.has(artifact) }?.getSources(artifact, output)
?: throw IllegalArgumentException("Can't find repo holding $artifact")
}
}
val client = HttpClient()
private class MavenClientImpl(private val baseUrl: String) : MavenClient {
private val metadataCache =
mutableMapOf<MavenArtifact, Pair<Boolean, MetadataFormat.Metadata?>>()
override suspend fun has(artifact: MavenArtifact): Boolean {
val (present, _) = metadataCache[artifact] ?: fetchMetadata(artifact)
return present
}
override suspend fun resolve(artifact: MavenArtifact): MavenArtifact {
if (artifact.isResolved) {
return artifact
}
val (present, metadata) = metadataCache[artifact] ?: fetchMetadata(artifact)
if (!present) {
throw IllegalArgumentException("Can't find $artifact")
}
return artifact.copy(
version = metadata?.versioning?.latest
?: metadata?.versioning?.versions?.version?.sorted()?.max()
?: throw IllegalArgumentException("No versions found for $artifact")
)
}
private suspend fun fetchMetadata(artifact: MavenArtifact):
Pair<Boolean, MetadataFormat.Metadata?> {
val response: HttpResponse = client.get(
"$baseUrl/${artifact.pkg.replace(".", "/")}/" +
"${artifact.target}/maven-metadata.xml"
)
return (
if (response.status.value != 200) {
Pair(false, null)
} else {
Pair(
true,
mapper.readValue<MetadataFormat.Metadata>(response.content.toInputStream())
)
}
).also {
metadataCache[artifact] = it
}
}
override suspend fun getSources(artifact: MavenArtifact, output: File) {
if (!artifact.isResolved) {
throw IllegalArgumentException("Can't download unresolved $artifact")
}
val content = client.get<ByteArray>(
"$baseUrl/${artifact.pkg.replace(".", "/")}/" +
"${artifact.target}/${artifact.version}/" +
"${artifact.target}-${artifact.version}-sources.jar"
)
output.writeBytes(content)
}
}
object MetadataFormat {
@JsonSerialize
data class Metadata(val versioning: Versioning? = null)
@JsonSerialize
@JsonRootName("versioning")
data class Versioning(
val latest: String? = null,
val release: String? = null,
val versions: Versions? = null,
val lastUpdated: String? = null
)
@JsonSerialize
@JsonRootName("versions")
data class Versions(val version: List<String>? = null)
}
| 0 | Kotlin | 0 | 0 | c6f6a460e00af6b8ffc98b8e39cbad509549bc9f | 6,035 | imdex | Apache License 2.0 |
NLiteAVDemo-Android-Java/call-ui/src/main/java/com/netease/yunxin/nertc/ui/group/GroupMemberPageAdapter.kt | netease-kit | 292,760,923 | false | {"Objective-C": 561786, "JavaScript": 505188, "Kotlin": 345942, "Java": 90377, "TypeScript": 4400, "Ruby": 4111, "Python": 2061, "C": 596} | /*
* Copyright (c) 2022 NetEase, Inc. All rights reserved.
* Use of this source code is governed by a MIT license that can be
* found in the LICENSE file.
*/
package com.netease.yunxin.nertc.ui.group
import android.content.Context
import android.view.ViewGroup
import androidx.recyclerview.widget.DiffUtil
import androidx.recyclerview.widget.RecyclerView
import androidx.viewpager2.widget.ViewPager2
import com.netease.yunxin.kit.alog.ALog
import kotlin.math.ceil
import kotlin.math.min
class GroupMemberPageAdapter(private val context: Context) :
RecyclerView.Adapter<GroupMemberPageAdapter.ViewHolder>() {
private val tag = "GroupMemberPageAdapter"
/**
* 最大页数
*/
private val maxPageSize = 4
/**
* 每页数据大小
*/
private val pageLimit = 4
private val userList = mutableListOf<GroupMemberInfo>()
private val videoViewPool = GroupVideoViewPool()
private var viewPager: ViewPager2? = null
private var lastPageIndex = 0
private var currentPageIndex = 0
private val viewList = mutableListOf<GroupMemberPageView>()
private val selectorOnPage = object : ViewPager2.OnPageChangeCallback() {
override fun onPageSelected(position: Int) {
currentPageIndex = position
if (position == lastPageIndex) {
return
}
getItemList(lastPageIndex)?.forEach {
videoViewPool.recycleRtcVideo(it.uid, true)
}
lastPageIndex = position
notifyItemChanged(position)
}
}
init {
videoViewPool.init(context)
}
fun setData(itemList: List<GroupMemberInfo>, onActionForData: (() -> Unit)? = null) {
if (itemList.isEmpty()) {
return
}
val oldData = userList.getClone()
onActionForData?.invoke()
val diffResult = DiffUtil.calculateDiff(DiffUtilCallback(oldData, itemList))
userList.clear()
userList.addAll(itemList)
diffResult.dispatchUpdatesTo(this)
}
private fun List<GroupMemberInfo>.getClone(): List<GroupMemberInfo> {
val result = mutableListOf<GroupMemberInfo>()
for (item in this) {
result.add(item.clone())
}
return result
}
private fun List<GroupMemberInfo>.update(
index: Int? = null,
item: GroupHelperMemberInfo?
): Int {
item ?: return -1
return if (index == null || index < 0 || index >= size) {
val result = find {
(it.uid == item.uid || it.accId == item.accId)
} ?: return -1
result.uid = item.uid
item.enableAudio?.run {
result.enableAudio = this
}
item.enableVideo?.run {
result.enableVideo = this
}
item.focus?.run {
result.focus = this
}
indexOf(result)
} else {
this[index].run {
uid = item.uid
item.enableAudio?.run {
enableAudio = this
}
item.enableVideo?.run {
enableVideo = this
}
item.focus?.run {
focus = this
}
}
index
}
}
fun updateState(
uid: Long,
focus: Boolean? = null,
enableVideo: Boolean? = null
) {
val index = findPosition(uid)
if (index < 0) {
return
}
getItemList(index)?.update(
item = GroupHelperMemberInfo(
uid = uid,
focus = focus,
enableVideo = enableVideo
)
)
notifyItemChanged(index)
}
fun updateCallerUid(
accId: String,
uid: Long
) {
val index = findPosition(accId)
if (index < 0) {
return
}
getItemList(index)?.update(
item = GroupHelperMemberInfo(
uid = uid,
accId = accId
)
)
notifyItemChanged(index)
}
fun wrapViewpager(viewPager: ViewPager2) {
this.viewPager = viewPager
viewPager.adapter = this
viewPager.registerOnPageChangeCallback(selectorOnPage)
}
fun release() {
videoViewPool.release()
viewPager?.unregisterOnPageChangeCallback(selectorOnPage)
}
override fun getItemViewType(position: Int): Int {
return position
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
val contentView = GroupMemberPageView(context)
contentView.layoutParams = ViewGroup.LayoutParams(
ViewGroup.LayoutParams.MATCH_PARENT,
ViewGroup.LayoutParams.MATCH_PARENT
)
viewList.add(contentView)
return ViewHolder(contentView)
}
override fun onBindViewHolder(holder: ViewHolder, position: Int) {
val pageData = getItemList(position) ?: return
ALog.d(tag, "page data is $pageData.")
holder.pageView.refreshData(pageData, videoViewPool, position == currentPageIndex)
}
override fun getItemCount(): Int = userList.itemCount()
private fun getItemList(position: Int): List<GroupMemberInfo>? =
userList.itemListByPosition(position)
private fun List<GroupMemberInfo>.itemCount(): Int {
return min(maxPageSize, ceil(this.size.toDouble() / pageLimit).toInt())
}
private fun List<GroupMemberInfo>.itemListByPosition(position: Int): List<GroupMemberInfo>? {
if (position < 0 || position >= maxPageSize) {
return null
}
return subList(
position * pageLimit,
min((position + 1) * pageLimit, size)
)
}
private fun findPosition(accId: String): Int {
var result = -1
for (position in 0 until itemCount) {
val item = getItemList(position)?.find {
it.accId == accId
}
if (item != null) {
result = position
break
}
}
return result
}
private fun findPosition(uid: Long): Int {
var result = -1
for (position in 0 until itemCount) {
val item = getItemList(position)?.find {
it.uid == uid
}
if (item != null) {
result = position
break
}
}
return result
}
private inner class DiffUtilCallback(
val oldList: List<GroupMemberInfo>?,
val newList: List<GroupMemberInfo>?
) :
DiffUtil.Callback() {
override fun getOldListSize(): Int = oldList?.itemCount() ?: 0
override fun getNewListSize(): Int = newList?.itemCount() ?: 0
override fun areItemsTheSame(oldItemPosition: Int, newItemPosition: Int): Boolean =
oldList?.itemListByPosition(oldItemPosition) == newList?.itemListByPosition(
newItemPosition
)
override fun areContentsTheSame(oldItemPosition: Int, newItemPosition: Int): Boolean {
val oldItem = oldList?.itemListByPosition(oldItemPosition)
val newItem = newList?.itemListByPosition(newItemPosition)
if (oldItem != newItem) {
return false
}
if (oldItem == null || newItem == null) {
return true
}
var result = true
for (position in oldItem.indices) {
val oldSubItem = oldItem[position]
val newSubItem = newItem[position]
result =
(newSubItem == oldSubItem) &&
(newSubItem.uid == oldSubItem.uid) &&
(newSubItem.enableVideo == oldSubItem.enableVideo) &&
(newSubItem.state == oldSubItem.state) &&
!newSubItem.enableVideo
if (!result) {
break
}
}
return result
}
}
// 创建ViewHolder
class ViewHolder(val pageView: GroupMemberPageView) : RecyclerView.ViewHolder(pageView)
}
| 2 | Objective-C | 27 | 38 | 9b2593a34179155cf2009124bec0e01944359d2d | 8,259 | NEVideoCall-1to1 | MIT License |
compose/foundation/foundation/src/androidAndroidTest/kotlin/androidx/compose/foundation/shape/AbsoluteRoundedCornerShapeTest.kt | RikkaW | 389,105,112 | false | null | /*
* Copyright 2019 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.foundation.shape
import androidx.compose.ui.geometry.CornerRadius
import androidx.compose.ui.geometry.RoundRect
import androidx.compose.ui.geometry.Size
import androidx.compose.ui.geometry.toRect
import androidx.compose.ui.graphics.Outline
import androidx.compose.ui.graphics.Shape
import androidx.compose.ui.unit.Density
import androidx.compose.ui.unit.LayoutDirection
import androidx.compose.ui.unit.dp
import androidx.test.filters.SmallTest
import com.google.common.truth.Truth.assertThat
import org.junit.Assert.assertEquals
import org.junit.Test
import org.junit.runner.RunWith
import org.junit.runners.Parameterized
@SmallTest
@RunWith(Parameterized::class)
class AbsoluteRoundedCornerShapeTest(val layoutDirection: LayoutDirection) {
companion object {
@JvmStatic
@Parameterized.Parameters(name = "{0}")
fun initParameters(): Array<LayoutDirection> =
arrayOf(LayoutDirection.Ltr, LayoutDirection.Rtl)
}
private val density = Density(2f)
private val size = Size(100.0f, 150.0f)
@Test
fun roundedUniformCorners() {
val rounded = AbsoluteRoundedCornerShape(25)
val expectedRadius = CornerRadius(25f)
val outline = rounded.toOutline() as Outline.Rounded
assertThat(outline.roundRect).isEqualTo(RoundRect(size.toRect(), expectedRadius))
}
@Test
fun roundedDifferentRadius() {
val radius1 = 12f
val radius2 = 22f
val radius3 = 32f
val radius4 = 42f
val rounded = AbsoluteRoundedCornerShape(radius1, radius2, radius3, radius4)
val outline = rounded.toOutline() as Outline.Rounded
assertThat(outline.roundRect)
.isEqualTo(
RoundRect(
size.toRect(),
CornerRadius(radius1),
CornerRadius(radius2),
CornerRadius(radius3),
CornerRadius(radius4)
)
)
}
@Test
fun createsRectangleOutlineForZeroSizedCorners() {
val rounded = AbsoluteRoundedCornerShape(0.0f, 0.0f, 0.0f, 0.0f)
assertThat(rounded.toOutline()).isEqualTo(Outline.Rectangle(size.toRect()))
}
@Test
fun roundedCornerShapesAreEquals() {
assertThat(AbsoluteRoundedCornerShape(12.dp)).isEqualTo(AbsoluteRoundedCornerShape(12.dp))
}
@Test
fun roundedCornerUpdateAllCornerSize() {
assertThat(AbsoluteRoundedCornerShape(10.0f).copy(CornerSize(5.dp)))
.isEqualTo(AbsoluteRoundedCornerShape(5.dp))
}
@Test
fun roundedCornerUpdateTwoCornerSizes() {
val original =
AbsoluteRoundedCornerShape(10.0f)
.copy(topStart = CornerSize(3.dp), bottomEnd = CornerSize(50))
assertEquals(CornerSize(3.dp), original.topStart)
assertEquals(CornerSize(10.0f), original.topEnd)
assertEquals(CornerSize(50), original.bottomEnd)
assertEquals(CornerSize(10f), original.bottomStart)
assertThat(
AbsoluteRoundedCornerShape(10.0f)
.copy(topStart = CornerSize(3.dp), bottomEnd = CornerSize(50))
)
.isEqualTo(
AbsoluteRoundedCornerShape(
topLeft = CornerSize(3.dp),
topRight = CornerSize(10.0f),
bottomRight = CornerSize(50),
bottomLeft = CornerSize(10.0f)
)
)
}
@Test
fun objectsWithTheSameCornersAreEquals() {
@Suppress("ReplaceCallWithBinaryOperator")
assertThat(
AbsoluteRoundedCornerShape(
topLeft = CornerSize(4.0f),
topRight = CornerSize(3.0f),
bottomRight = CornerSize(3.dp),
bottomLeft = CornerSize(50)
)
.equals(
AbsoluteRoundedCornerShape(
topLeft = CornerSize(4.0f),
topRight = CornerSize(3.0f),
bottomRight = CornerSize(3.dp),
bottomLeft = CornerSize(50)
)
)
)
.isTrue()
}
@Test
fun objectsWithDifferentCornersAreNotEquals() {
@Suppress("ReplaceCallWithBinaryOperator")
assertThat(
AbsoluteRoundedCornerShape(
topLeft = CornerSize(4.0f),
topRight = CornerSize(3.0f),
bottomRight = CornerSize(3.dp),
bottomLeft = CornerSize(50)
)
.equals(
AbsoluteRoundedCornerShape(
topLeft = CornerSize(4.0f),
topRight = CornerSize(5.0f),
bottomRight = CornerSize(3.dp),
bottomLeft = CornerSize(50)
)
)
)
.isFalse()
}
@Test
fun notEqualsToCutCornersWithTheSameSizes() {
@Suppress("ReplaceCallWithBinaryOperator")
assertThat(
AbsoluteRoundedCornerShape(
topLeft = CornerSize(4.0f),
topRight = CornerSize(3.0f),
bottomRight = CornerSize(3.dp),
bottomLeft = CornerSize(50)
)
.equals(
AbsoluteCutCornerShape(
topLeft = CornerSize(4.0f),
topRight = CornerSize(3.0f),
bottomRight = CornerSize(3.dp),
bottomLeft = CornerSize(50)
)
)
)
.isFalse()
}
@Test
fun copyHasCorrectDefaults() {
assertEquals(
AbsoluteRoundedCornerShape(
topLeft = 5.dp,
topRight = 6.dp,
bottomRight = 3.dp,
bottomLeft = 4.dp
),
AbsoluteRoundedCornerShape(
topLeft = 1.dp,
topRight = 2.dp,
bottomRight = 3.dp,
bottomLeft = 4.dp
)
.copy(topStart = CornerSize(5.dp), topEnd = CornerSize(6.dp))
)
assertEquals(
AbsoluteRoundedCornerShape(
topLeft = 1.dp,
topRight = 2.dp,
bottomRight = 5.dp,
bottomLeft = 6.dp
),
AbsoluteRoundedCornerShape(
topLeft = 1.dp,
topRight = 2.dp,
bottomRight = 3.dp,
bottomLeft = 4.dp
)
.copy(bottomEnd = CornerSize(5.dp), bottomStart = CornerSize(6.dp))
)
}
private fun Shape.toOutline() = createOutline(size, layoutDirection, density)
}
| 29 | null | 1011 | 7 | 6d53f95e5d979366cf7935ad7f4f14f76a951ea5 | 7,698 | androidx | Apache License 2.0 |
project/app/src/main/java/com/example/nattklar/view/BottomNavigationBar.kt | gremble0 | 654,026,932 | false | null | package com.example.nattklar.view
import androidx.compose.animation.AnimatedVisibility
import androidx.compose.animation.AnimatedVisibilityScope
import androidx.compose.animation.core.tween
import androidx.compose.animation.fadeIn
import androidx.compose.animation.fadeOut
import androidx.compose.animation.slideInVertically
import androidx.compose.animation.slideOutVertically
import androidx.compose.foundation.LocalIndication
import androidx.compose.foundation.background
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.*
import androidx.compose.material.ripple.rememberRipple
import androidx.compose.material3.*
import androidx.compose.runtime.Composable
import androidx.compose.runtime.CompositionLocalProvider
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.shadow
import androidx.compose.ui.graphics.painter.Painter
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.unit.dp
import androidx.navigation.NavController
import com.example.nattklar.R
/**
* Shows a navigation bar at the bottom of the screen with four navigation options.
*/
@Composable
fun BottomNavigationBar(navController: NavController, selectedRoute: String) {
val bottomNavItems = listOf(
BottomNavItem(
name = stringResource(R.string.bottomNavBar_homeScreen),
route = "homeScreen",
icon = painterResource(id = R.drawable.telescope_button)
),
BottomNavItem(
name = stringResource(R.string.bottomNavBar_news),
route = "news",
icon = painterResource(id = R.drawable.news_button)
),
BottomNavItem(
name = stringResource(R.string.bottomNavBar_globe),
route = "globe",
icon = painterResource(id = R.drawable.map_button)
),
BottomNavItem(
name = stringResource(R.string.bottomNavBar_wiki),
route = "wiki",
icon = painterResource(id = R.drawable.wiki_button)
),
)
Surface(
modifier = Modifier.shadow(18.dp)
) {
Column (modifier = Modifier.background(color = MaterialTheme.colorScheme.tertiary)) {
Row(
modifier = Modifier
.fillMaxWidth(),
horizontalArrangement = Arrangement.SpaceAround
) {
bottomNavItems.forEach { item ->
val isSelected = selectedRoute == item.route
// Dersom en av navItems-ene blir trykket skal den lyse opp samme som teksten
val contentColor = if (isSelected) MaterialTheme.colorScheme.surface else MaterialTheme.colorScheme.primary
CompositionLocalProvider(
// When an icon is clicked the icon and the text get a ripple effect?
// TODO: I cant understand the sentence below, i tried to translate but correct it if its wrong
// Når ikonet blir trykket blir bare ikke ikonet ha en ripple effekt men teksten og
LocalIndication provides rememberRipple(bounded = false)
) {
Column(
horizontalAlignment = Alignment.CenterHorizontally,
modifier = Modifier
.weight(1f)
.clickable(
onClick = {
navController.navigate(item.route) {
popUpTo(navController.graph.startDestinationId) {
inclusive = true
}
}
}
)
.padding(top = 10.dp)
) {
Icon(
item.icon,
item.name,
modifier = Modifier.size(40.dp),
tint = contentColor
)
// Name taken from values/strings.xml
if (isSelected) {
Text(
text = item.name,
color = contentColor,
textAlign = TextAlign.Center
)
}
}
}
}
}
}
}
}
/**
* Shows a navigation effect animation when a navigation bar button is clicked.
*/
@Composable
fun EnterAnimation(content: @Composable AnimatedVisibilityScope.() -> Unit) {
val isVisible = remember { mutableStateOf(false) }
LaunchedEffect(key1 = true) {
isVisible.value = true
}
AnimatedVisibility(
visible = isVisible.value,
enter = slideInVertically(initialOffsetY = { it })
+ fadeIn(initialAlpha = 0.3f, animationSpec = tween(durationMillis = 500)),
exit = slideOutVertically() + fadeOut(),
content = content
)
}
/**
* This data class holds relevant data for items on the navigation bar.
*/
data class BottomNavItem(
val name: String, // Name of the button
val route: String, // Destination to the screen
val icon: Painter,
) | 0 | Kotlin | 0 | 1 | df7b18ffa521686db16ad605b31af021f2f929eb | 5,799 | nattklar | MIT License |
app/src/main/java/com/hermanowicz/wirelesswhisper/navigation/features/deviceDetails/ui/DeviceDetailsScreen.kt | sirconceptz | 645,645,531 | false | null | package com.hermanowicz.wirelesswhisper.navigation.features.deviceDetails.ui
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.res.stringResource
import androidx.hilt.navigation.compose.hiltViewModel
import com.hermanowicz.wirelesswhisper.R
import com.hermanowicz.wirelesswhisper.components.card.CardPrimary
import com.hermanowicz.wirelesswhisper.components.divider.DividerCardInside
import com.hermanowicz.wirelesswhisper.components.topBarScoffold.TopBarScaffold
import com.hermanowicz.wirelesswhisper.ui.theme.LocalSpacing
@Composable
fun DeviceDetailsScreen(
bottomBar: @Composable () -> Unit,
viewModel: DeviceDetailsViewModel = hiltViewModel()
) {
val macAddress = viewModel.macAddress
TopBarScaffold(
topBarText = stringResource(id = R.string.device_details),
bottomBar = bottomBar
) {
LazyColumn(
modifier = Modifier
.fillMaxWidth()
.padding(LocalSpacing.current.medium)
) {
item {
CardPrimary {
Row(
modifier = Modifier.fillMaxWidth(),
horizontalArrangement = Arrangement.SpaceBetween
) {
Text(
text = stringResource(id = R.string.name)
)
Text(
text = "to do observe"
)
}
DividerCardInside()
Row(
modifier = Modifier.fillMaxWidth(),
horizontalArrangement = Arrangement.SpaceBetween
) {
Text(
text = stringResource(id = R.string.mac_address)
)
Text(
text = macAddress
)
}
}
}
}
}
}
| 0 | Kotlin | 0 | 0 | 787c77a1bec2545587569b1d1b1273396c081400 | 2,347 | WirelessWhisper | Apache License 2.0 |
plugins/evaluation-plugin/core/src/com/intellij/cce/actions/ActionsGenerator.kt | JetBrains | 2,489,216 | false | null | // Copyright 2000-2024 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package com.intellij.cce.actions
import com.intellij.cce.core.CodeFragment
import com.intellij.cce.processor.GenerateActionsProcessor
import com.intellij.cce.util.FileTextUtil.computeChecksum
class ActionsGenerator(private val processor: GenerateActionsProcessor) {
fun generate(code: CodeFragment): FileActions {
processor.process(code)
val actions = processor.getActions()
return FileActions(code.path, computeChecksum(code.text), actions.count { it is CallFeature }, actions)
}
}
| 284 | null | 5162 | 16,707 | def6433a5dd9f0a984cbc6e2835d27c97f2cb5f0 | 622 | intellij-community | Apache License 2.0 |
src/main/kotlin/net/dehya/api/schedules/types/DateSchedule.kt | ryderbelserion | 670,341,905 | false | null | package net.dehya.api.schedules.types
import net.dehya.api.schedules.Schedule
import java.time.LocalDateTime
/**
* A schedule that is based on a date.
*/
class DateSchedule(
private val dateTime: LocalDateTime,
private val block: suspend () -> Unit,
) : Schedule {
// Will check if the date time is valid or not.
init {
if (dateTime.isBefore(LocalDateTime.now())) throw IllegalArgumentException("DateTime must be after now")
}
override val isRepeating: Boolean = false
override suspend fun execute() {
block()
}
override fun shouldRun(nowDateTime: LocalDateTime): Boolean {
return nowDateTime.isEqual(dateTime)
}
} | 0 | Kotlin | 0 | 0 | 7d8a7327b011c16ddcacd8cf6cfcda0c806f0d7f | 686 | Krul | MIT License |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.