path
stringlengths 4
280
| owner
stringlengths 2
39
| repo_id
int64 21.1k
879M
| is_fork
bool 2
classes | languages_distribution
stringlengths 13
1.95k
⌀ | content
stringlengths 7
482k
| issues
int64 0
13.9k
| main_language
stringclasses 121
values | forks
stringlengths 1
5
| stars
int64 0
111k
| commit_sha
stringlengths 40
40
| size
int64 7
482k
| name
stringlengths 1
100
| license
stringclasses 93
values |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|
app/src/main/java/com/example/assignment_9/fragments/BaseFragment.kt | SawThanDar18 | 215,930,903 | false | null | package com.example.assignment_9.fragments
import android.os.Bundle
import androidx.fragment.app.Fragment
import com.example.assignment_9.data.models.MovieModel
import com.example.assignment_9.data.models.MovieModelImpl
abstract class BaseFragment: Fragment() {
private lateinit var model: MovieModel
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
model = MovieModelImpl
}
} | 0 | Kotlin | 0 | 0 | c3ac4e960fbb8e9519fa5a21a78196c5ba0a7c8a | 448 | Assignment_9 | Apache License 2.0 |
src/main/kotlin/no/nav/arbeidsplassen/emailer/api/v1/EmailDTO.kt | navikt | 344,235,170 | false | {"Kotlin": 12780, "Dockerfile": 196, "Shell": 49} | package no.nav.arbeidsplassen.emailer.api.v1
import com.fasterxml.jackson.annotation.JsonIgnoreProperties
@JsonIgnoreProperties(ignoreUnknown = true)
data class EmailDTO(
val identifier: String?,
val recipient: String,
val subject: String,
val content: String,
val type: String,
val attachments: List<AttachmentDto> = listOf()
)
data class AttachmentDto(
val name: String,
val contentType: String,
val base64Content: String
) | 0 | Kotlin | 0 | 0 | 4fd946a945ada26d291dd0a1d79e893fbfe38cd1 | 464 | pam-emailer | MIT License |
sdk/src/commonMain/kotlin/com/kss/zoom/model/Model.kt | Kotlin-server-squad | 710,163,911 | false | {"Kotlin": 127202} | package com.kss.zoom.model
import com.kss.zoom.model.context.DynamicContext
interface Model {
val id: String
val context: DynamicContext
}
| 6 | Kotlin | 0 | 1 | 9b0d63788a52ad016f9cb36566bba38249db8d5b | 149 | zoomsdk | Apache License 2.0 |
resource/src/main/kotlin/me/jiangcai/common/resource/bean/VFSResourceService.kt | mingshz | 166,675,112 | false | {"Gradle": 20, "INI": 11, "Shell": 2, "Text": 1, "Ignore List": 3, "Batchfile": 1, "Markdown": 10, "XML": 8, "Kotlin": 311, "JavaScript": 1, "HTML": 4, "Java Properties": 10, "Java": 71, "JSON": 2} | package me.jiangcai.common.resource.bean
import me.jiangcai.common.resource.Resource
import me.jiangcai.common.resource.impl.LocalResource
import me.jiangcai.common.resource.impl.VFSResource
import org.apache.commons.logging.LogFactory
import org.apache.commons.vfs2.FileSystemException
import org.springframework.beans.factory.annotation.Autowired
import java.io.File
import java.io.IOException
import java.io.InputStream
import java.net.URI
import java.net.URISyntaxException
import java.nio.file.Files
import java.nio.file.Path
import java.nio.file.Paths
import java.nio.file.StandardCopyOption
/**
* @author CJ
*/
@Suppress("SpringJavaAutowiredMembersInspection")
class VFSResourceService(uri: String, home: String) : AbstractResourceService() {
companion object {
const val ServletContextResourcePath = "/_resources"
}
private val log = LogFactory.getLog(VFSResourceService::class.java)
private val uriPrefix: URI
private var localFileMode: Boolean = false
private var fileHome: URI? = null
private var fileFile: File? = null
@Autowired
private lateinit var vfsHelper: VFSHelper
init {
val newHome = if (!home.endsWith("/")) "$home/" else home
val newUri = if (!uri.endsWith("/")) "$uri/" else uri
try {
val homeUri = URI(newHome)
if ("file" == homeUri.scheme || homeUri.scheme == null) {
localFileMode = true
fileHome = null
fileFile = File(homeUri.path)
} else {
localFileMode = false
fileFile = null
fileHome = homeUri
}
} catch (e: URISyntaxException) {
// if (autoHome) {
// localFileMode = true
// fileHome = null
// fileFile = File(newHome)
// } else
throw IllegalArgumentException(e)
}
log.info("ResourceService running on $newHome, via:$newUri")
try {
uriPrefix = URI(newUri)
} catch (e: URISyntaxException) {
throw IllegalArgumentException(e)
}
}
@Throws(IOException::class)
override fun uploadResource(path: String, data: InputStream): Resource {
if (path.startsWith("/"))
throw IllegalArgumentException("bad resource path:$path")
// 检查是否是本地文件系统,如果是的话就使用本地文件系统技术
if (localFileMode) {
val path1 = getLocalPath(path)
Files.createDirectories(path1.parent)
Files.copy(data, path1, StandardCopyOption.REPLACE_EXISTING)
return getResource(path)
}
val filePath = fileHome!!.toString() + path
data.use { input ->
vfsHelper.handle(filePath) { file ->
file.content.outputStream.use { out ->
try {
input.copyTo(out)
out.flush()
} catch (e: IOException) {
throw FileSystemException(e)
}
}
null
}
}
return getResource(path)
}
@Throws(IOException::class)
override fun moveResource(path: String, fromPath: String): Resource {
if (path.startsWith("/"))
throw IllegalArgumentException("bad resource path:$path")
// 检查是否是本地文件系统,如果是的话就使用本地文件系统技术
if (localFileMode) {
val path1 = getLocalPath(path)
Files.createDirectories(path1.parent)
Files.move(getLocalPath(fromPath), path1, StandardCopyOption.REPLACE_EXISTING)
return getResource(path)
}
val filePath = fileHome!!.toString() + path
vfsHelper.handle(fileHome!!.toString() + fromPath) { fromFile ->
vfsHelper.handle(filePath) { toFile ->
fromFile.moveTo(toFile)
null
}
null
}
return getResource(path)
}
private fun getLocalPath(path: String): Path {
val file = File(fileFile!!.toString() + File.separator + path)
return Paths.get(file.toURI())
}
override fun getResource(path: String): Resource {
if (path.startsWith("/"))
throw IllegalArgumentException("bad resource path:$path")
val url = uriPrefix.toString() + path
if (localFileMode) {
return LocalResource(path, fileFile!!.toString() + File.separator + path, url)
}
val filePath = fileHome!!.toString() + path
return try {
VFSResource(path, vfsHelper, filePath, URI(url))
} catch (e: URISyntaxException) {
log.error("解释资源时", e)
throw IOException("资源格式", e)
}
}
@Throws(IOException::class)
override fun deleteResource(path: String) {
if (path.startsWith("/"))
throw IllegalArgumentException("bad resource path:$path")
if (localFileMode) {
val ioPath = Paths.get(fileFile!!.toString() + File.separator + path)
Files.deleteIfExists(ioPath)
return
}
val filePath = fileHome!!.toString() + path
vfsHelper.handle(filePath) {
it.delete()
}
}
} | 1 | null | 1 | 1 | 34060249958f817da4e1668109c37dcf8cbf2600 | 5,258 | library | MIT License |
kotlin/inheritance/inheritance.kt | correabuscar | 612,696,919 | false | {"Rust": 1803503, "Python": 767765, "Shell": 246939, "C": 164784, "HTML": 106231, "JavaScript": 103041, "LLVM": 11714, "Nix": 8766, "CMake": 8468, "Kotlin": 7600, "C++": 6900, "Zig": 3410, "Nim": 1844, "Awk": 1004, "Assembly": 774, "Go": 380, "Makefile": 197} | //import kotlin.math.PI
import kotlin.math.pow
import kotlin.math.sqrt
fun main() {
println("Hello, bug-prone world!")
val squareCabin = SquareCabin(6, 50.0)
//val capacity=1 //lul, 'with' has no effect on this
with (squareCabin) {
println("\nSquare Cabin\n============")
println("Capacity: ${capacity}") // 1 not 6
println("Material: ${buildingMaterial}")
println("Has room? ${hasRoom()}")
println("Floor area: ${floorArea()}")
println("Floor area: %.2f".format(floorArea()))
}
val roundHut = RoundHut(3, 10.0)
with(roundHut) {
println("\nRound Hut\n=========")
println("Material: ${buildingMaterial}")
println("Capacity: ${capacity}")
println("Has room? ${hasRoom()}")
println("Floor area: ${floorArea()}")
println("Floor area: %.2f".format(floorArea()))
println("Has room? ${hasRoom()}")
getRoom()
println("Has room? ${hasRoom()}")
getRoom()
println("Carpet size: ${calculateMaxCarpetSize()}")
}
val roundTower = RoundTower(4,15.5)
with(roundTower) {
println("\nRound Tower\n==========")
println("Material: ${buildingMaterial}")
println("Capacity: ${capacity}")
println("Has room? ${hasRoom()}")
println("Floor area: ${floorArea()}")
println("Floor area: %.2f".format(floorArea()))
println("Carpet size: ${calculateMaxCarpetSize()}")
}
}
abstract class Dwelling(private var residents: Int){
abstract val buildingMaterial: String
abstract val capacity: Int
fun hasRoom(): Boolean {
return residents < capacity
}
abstract fun floorArea(): Double
fun getRoom() {
if (capacity > residents) {
residents++
println("You got a room!")
} else {
println("Sorry, at capacity and no rooms left.")
}
}
}
class SquareCabin(var residents: Int,
val length: Double) : Dwelling(residents) {
override val buildingMaterial = "Wood"
override val capacity = 6
override fun floorArea(): Double {
return length.pow(2)
}
}
open class RoundHut(residents: Int,
val radius: Double) : Dwelling(residents) {
override val buildingMaterial = "Straw"
override val capacity = 4
override fun floorArea(): Double {
//return PI * radius.pow(2) // import needed
return kotlin.math.PI * radius.pow(2) // import not needed this way
}
fun calculateMaxCarpetSize(): Double {
val diameter = 2 * radius
return sqrt(diameter.pow(2) / 2)
}
}
class RoundTower(residents: Int,
radius: Double,
val floors: Int=2) : RoundHut(residents, radius) {
override val buildingMaterial = "Stone"
//override val capacity = 4
override val capacity = 4 * floors
override fun floorArea(): Double {
return super.floorArea() * floors
}
}
| 0 | Rust | 0 | 0 | ee5274890fdbf3b509fdb8a3214a8e4ecb68918f | 2,918 | sandbox | The Unlicense |
features/exchanges/src/main/java/com/fappslab/mbchallenge/features/exchanges/data/model/ExchangeResponse.kt | F4bioo | 845,138,188 | false | {"Kotlin": 242545} | package com.fappslab.mbchallenge.features.exchanges.data.model
import com.google.gson.annotations.SerializedName
internal data class ExchangeResponse(
@SerializedName("exchange_id") val exchangeId: String?,
@SerializedName("website") val website: String?,
@SerializedName("name") val name: String?,
@SerializedName("data_quote_start") val dataQuoteStart: String?,
@SerializedName("data_quote_end") val dataQuoteEnd: String?,
@SerializedName("data_orderbook_start") val dataOrderBookStart: String?,
@SerializedName("data_orderbook_end") val dataOrderBookEnd: String?,
@SerializedName("data_trade_start") val dataTradeStart: String?,
@SerializedName("data_trade_end") val dataTradeEnd: String?,
@SerializedName("data_symbols_count") val dataSymbolsCount: Int?,
@SerializedName("volume_1hrs_usd") val volume1hrsUsd: Double?,
@SerializedName("volume_1day_usd") val volume1dayUsd: Double?,
@SerializedName("volume_1mth_usd") val volume1mthUsd: Double?
)
| 0 | Kotlin | 0 | 0 | d81eff4b566578b5dc8596b7cbfcfb2e12e652b6 | 1,004 | MBChallenge | MIT License |
src/main/kotlin/com/justai/jaicf/plugin/inspections/PathValueAnnotationInspection.kt | just-ai | 394,978,762 | false | null | package com.justai.jaicf.plugin.inspections
import com.intellij.codeInspection.LocalInspectionTool
import com.intellij.codeInspection.ProblemsHolder
import com.justai.jaicf.plugin.utils.PATH_ARGUMENT_ANNOTATION_NAME
import com.justai.jaicf.plugin.utils.stringValueOrNull
import org.jetbrains.kotlin.psi.KtAnnotated
import org.jetbrains.kotlin.psi.KtAnnotatedExpression
import org.jetbrains.kotlin.psi.KtParameter
class PathValueAnnotationInspection : LocalInspectionTool() {
override fun getID() = "PathValueAnnotationInspection"
override fun buildVisitor(holder: ProblemsHolder, isOnTheFly: Boolean) = PathValueVisitor(holder)
class PathValueVisitor(holder: ProblemsHolder) : AnnotatedElementVisitor(holder) {
override fun visitAnnotatedElement(annotatedElement: KtAnnotated) {
if (annotatedElement.isNotAnnotatedWithPathValue)
return
when (annotatedElement) {
is KtParameter ->
if (annotatedElement.defaultValue != null && annotatedElement.defaultValue!!.stringValueOrNull == null)
registerWeakWarning(annotatedElement.defaultValue!!, message)
is KtAnnotatedExpression ->
if (annotatedElement.baseExpression?.stringValueOrNull == null)
registerWeakWarning(annotatedElement.baseExpression ?: annotatedElement, message)
}
}
private val KtAnnotated.isNotAnnotatedWithPathValue
get() = annotationEntries.none {
it.shortName?.identifier == PATH_ARGUMENT_ANNOTATION_NAME/* &&
it.argumentExpressionOrDefaultValue("shouldUseLiterals")?.text != "false"*/
}
companion object {
private const val message =
"JAICF Plugin is not able to resolve the path annotated with @PathValue"
}
}
}
| 5 | Kotlin | 1 | 3 | 8868f5a6d2d02bd79ca526cf942d59df7d528d14 | 1,902 | jaicf-plugin | Apache License 2.0 |
app/src/main/java/reach52/marketplace/community/models/Company.kt | reach52 | 422,514,975 | false | {"Kotlin": 1436380, "Java": 18303} | package reach52.marketplace.community.models
import reach52.marketplace.community.models.insured.Address
data class Company(
val identifier: String,
val name: String,
val type: String,
val telecommunication: String,
val address: List<Address>
) | 0 | Kotlin | 0 | 0 | 629c52368d06f978f19238d0bd865f4ef84c23d8 | 286 | Marketplace-Community-Edition | MIT License |
fluxo-core/src/commonMain/kotlin/kt/fluxo/core/internal/ConcurrentHashMap.common.kt | fluxo-kt | 566,869,438 | false | null | package kt.fluxo.core.internal
import kt.fluxo.core.annotation.InternalFluxoApi
@InternalFluxoApi
@Suppress("FunctionName")
internal expect fun <K, V> ConcurrentHashMap(): MutableMap<K, V>
| 3 | Kotlin | 0 | 5 | 475f65186b273f02e875c59176dd3a4af0b0365f | 191 | fluxo-mvi | Apache License 2.0 |
fixgrep-core/src/main/kotlin/org/tools4j/fixgrep/linehandlers/DefaultFixLineHandlerWithNoCarriageReturn.kt | tools4j | 124,669,693 | false | null | package org.tools4j.fixgrep.linehandlers
import org.tools4j.fixgrep.formatting.Formatter
import java.util.function.Consumer
/**
* User: benjw
* Date: 9/20/2018
* Time: 5:13 PM
*/
class DefaultFixLineHandlerWithNoCarriageReturn(val formatter: Formatter, val lineWriter: Consumer<String>) : FixLineHandler {
override fun handle(fixLine: FixLine) {
if(!formatter.spec.shouldPrint(fixLine)) return
val formattedLine = formatter.format(fixLine)
if(formattedLine != null) lineWriter.accept(formattedLine)
}
override fun finish() {
//no-op
}
} | 0 | Kotlin | 1 | 7 | e2cbc5b0b174f7ab462603e8ff65701501dfeae1 | 591 | market-simulator | MIT License |
jcamera/src/main/java/com/longrou/jcamera/provider/CameraProvider.kt | jxj2118 | 189,346,023 | false | null | package com.longrou.jcamera.provider
import android.content.Context
import androidx.core.content.FileProvider
/**
* @Description:
* @Author: LongRou
* @CreateDate: 2019/5/23 11:24
* @Version: 1.0
**/
class CameraProvider : FileProvider() {
companion object{
fun getFileProviderName(context: Context): String {
return context.packageName + ".provider"
}
}
} | 10 | Kotlin | 10 | 50 | 289310c09907e7d91e1eeab327ecc19b817dbc71 | 399 | JCamera | MIT License |
test/Intent/src/main/java/UseIntentGetByteArrayExtra.kt | wada811 | 562,910,344 | false | null | import android.content.Intent
class UseIntentGetByteArrayExtra {
fun getByteArrayExtra(intent: Intent) {
intent.getByteArrayExtra("")
}
} | 4 | Kotlin | 0 | 2 | 96b76dd5ffe4ba5ac23fdccfb35f46a4299c3e47 | 154 | ax | Apache License 2.0 |
fontawesome/src/de/msrd0/fontawesome/icons/FA_KITCHEN_SET.kt | msrd0 | 363,665,023 | false | {"Kotlin": 3912511, "Jinja": 2214} | /* @generated
*
* This file is part of the FontAwesome Kotlin library.
* https://github.com/msrd0/fontawesome-kt
*
* This library is not affiliated with FontAwesome.
*
* 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 de.msrd0.fontawesome.icons
import de.msrd0.fontawesome.Icon
import de.msrd0.fontawesome.Style
import de.msrd0.fontawesome.Style.SOLID
/** Kitchen Set */
object FA_KITCHEN_SET: Icon {
override val name get() = "Kitchen Set"
override val unicode get() = "e51a"
override val styles get() = setOf(SOLID)
override fun svg(style: Style) = when(style) {
SOLID -> """<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 576 512"><path d="M80 144C80 108.7 108.7 80 144 80C179.3 80 208 108.7 208 144C208 179.3 179.3 208 144 208C108.7 208 80 179.3 80 144zM284.4 176C269.9 240.1 212.5 288 144 288C64.47 288 0 223.5 0 144C0 64.47 64.47 0 144 0C212.5 0 269.9 47.87 284.4 112H356.2C365 102.2 377.8 96 392 96H496C522.5 96 544 117.5 544 144C544 170.5 522.5 192 496 192H392C377.8 192 365 185.8 356.2 176H284.4zM144 48C90.98 48 48 90.98 48 144C48 197 90.98 240 144 240C197 240 240 197 240 144C240 90.98 197 48 144 48zM424 264V272H520C533.3 272 544 282.7 544 296C544 309.3 533.3 320 520 320H280C266.7 320 256 309.3 256 296C256 282.7 266.7 272 280 272H376V264C376 250.7 386.7 240 400 240C413.3 240 424 250.7 424 264zM288 464V352H512V464C512 490.5 490.5 512 464 512H336C309.5 512 288 490.5 288 464zM176 320C202.5 320 224 341.5 224 368C224 394.5 202.5 416 176 416H160C160 433.7 145.7 448 128 448H64C46.33 448 32 433.7 32 416V336C32 327.2 39.16 320 48 320H176zM192 368C192 359.2 184.8 352 176 352H160V384H176C184.8 384 192 376.8 192 368zM200 464C213.3 464 224 474.7 224 488C224 501.3 213.3 512 200 512H24C10.75 512 0 501.3 0 488C0 474.7 10.75 464 24 464H200z"/></svg>"""
else -> null
}
}
| 0 | Kotlin | 0 | 0 | ee6a62d201fd5df2555859271cb0c6a7ee887e7a | 2,328 | fontawesome-kt | Apache License 2.0 |
src/main/kotlin/ai/chatinfra/context/time/TimeContext.kt | chatinfra | 765,326,824 | false | {"Kotlin": 106309, "Java": 54} | package ai.chatinfra.ai.chatinfra.context.time
import affair.lib.util.time.day
import affair.lib.util.time.setDay
import affair.lib.util.time.setMidnight
import affair.lib.util.time.setMinute2
import kotlinx.datetime.Clock.System.now
import kotlinx.datetime.DayOfWeek
import kotlinx.datetime.Instant
import kotlinx.datetime.LocalDate
import kotlinx.datetime.LocalDateTime
import kotlinx.datetime.LocalTime
import kotlinx.datetime.TimeZone
import kotlinx.datetime.atStartOfDayIn
import kotlinx.datetime.toInstant
import kotlinx.datetime.toLocalDateTime
import java.util.*
import kotlin.math.max
import kotlin.math.min
import kotlin.time.Duration
import kotlin.time.Duration.Companion.hours
import kotlin.time.Duration.Companion.seconds
interface TimeContext {
val tz: TimeZone
val now: Instant
fun LocalDateTime.setDay(day: DayOfWeek): LocalDateTime = setDay(day, tz)
fun LocalDateTime.nextDay(): LocalDateTime = (instant + 1.day).local
fun LocalDateTime.setMinute(minute: Int): LocalDateTime = setMinute2(minute)
fun Instant.toLocalDateTime(): LocalDateTime = toLocalDateTime(tz)
fun Instant.toDays(to: Instant): List<LocalDate> = mutableListOf<LocalDate>().apply {
var ts = this@toDays
while (ts < to) {
add(ts.toLocalDateTime().date)
ts += 1.day
}
}
fun LocalDate.toPromptDateString(): String = "$dayOfWeekLowerCapped $this"
fun LocalDate.atStartOfDay(): LocalDateTime = atStartOfDayIn(tz).toLocalDateTime()
fun LocalDate.atEndOfDay(): LocalDateTime = (atStartOfDayIn(tz) + 24.hours - 1.seconds).toLocalDateTime()
fun LocalDate.atStartOfDayInstant(): Instant = atStartOfDayIn(tz)
fun LocalDate.atEndOfDayInstant(): Instant = atEndOfDay().toInstant(tz)
val tomorrowStartOfLocalInstant: Instant
get() = (now.local.setMidnight().instant + 1.day)
val tomorrowStartOfLocal: LocalDateTime
get() = (now.local.setMidnight().instant + 1.day).local
val nextMonday: Instant
get() = now.local
.setMidnight()
.setDay(java.time.DayOfWeek.MONDAY).instant
val nextTuesday: Instant
get() = now.local
.setMidnight()
.nextDay()
.setDay(java.time.DayOfWeek.TUESDAY).instant
val yesterday: Instant
get() = (now.local.setMidnight().instant - 1.day)
val dayOfTomorrow: DayOfWeek
get() = (now + 1.day).toLocalDateTime(tz).dayOfWeek
val dayOfDayAfterTomorrow: DayOfWeek
get() = (now + 2.day).toLocalDateTime(tz).dayOfWeek
val LocalDate.dayOfWeekLowerCapped: String
get() = dayOfWeek.name.lowercase().cap
val LocalDateTime.dayOfWeekLowerCapped: String
get() = date.dayOfWeekLowerCapped
val Instant.local: LocalDateTime
get() = toLocalDateTime()
val LocalDateTime.instant: Instant
get() = toInstant(tz)
operator fun LocalDateTime.plus(day: Duration): LocalDateTime = (toInstant(tz) + day).toLocalDateTime(tz)
operator fun LocalTime.minus(other: LocalTime): Duration {
val date = now.local.date
return LocalDateTime(date, this).instant - LocalDateTime(date, other).instant
}
fun maxInstant(i1: Instant, i2: Instant): Instant = max(i1.toEpochMilliseconds(), i2.toEpochMilliseconds()).run { Instant.fromEpochMilliseconds(this) }
fun minInstant(i1: Instant, i2: Instant): Instant = min(i1.toEpochMilliseconds(), i2.toEpochMilliseconds()).run { Instant.fromEpochMilliseconds(this) }
companion object {
fun createRealtime(tz: TimeZone = TimeZone.currentSystemDefault(), getNow: () -> Instant = { now() }): TimeContext = Realtime(tz = tz, getNow = getNow)
fun createJanFirst2025(tz: TimeZone = TimeZone.currentSystemDefault()): TimeContext = Static(tz = tz, now = LocalDateTime(2025, 1, 1, 0, 0).toInstant(tz))
fun createStatic(): TimeContext = Static(tz = TimeZone.currentSystemDefault(), now = now())
fun createFromInstant(i: Instant): TimeContext = Static(tz = TimeZone.currentSystemDefault(), now = i)
}
data class Static(override val tz: TimeZone = TimeZone.currentSystemDefault(), override val now: Instant) : TimeContext
data class Realtime(override val tz: TimeZone = TimeZone.currentSystemDefault(), val getNow: () -> Instant = { now() }) : TimeContext {
override val now: Instant
get() = getNow()
}
}
val String.cap: String
get() = replaceFirstChar { if (it.isLowerCase()) it.titlecase(Locale.getDefault()) else it.toString() }
val String.decap: String
get() = replaceFirstChar { it.lowercase(Locale.getDefault()) } | 0 | Kotlin | 0 | 0 | 929b39beef33054024669c2eb1555e936aa83716 | 4,658 | workstation | MIT License |
model/src/main/java/com/fearaujo/model/User.kt | feharaujo | 125,389,423 | false | null | package com.fearaujo.model
import com.fasterxml.jackson.annotation.JsonProperty
data class User(
@field:JsonProperty("likes_count")
val likesCount: Int? = null,
@field:JsonProperty("avatar_url")
val avatarUrl: String? = null,
@field:JsonProperty("followers_count")
val followersCount: Int? = null,
@field:JsonProperty("name")
val name: String? = null,
@field:JsonProperty("bio")
val bio: String? = null,
@field:JsonProperty("location")
val location: String? = null,
@field:JsonProperty("followings_count")
val followingsCount: Int? = null,
@field:JsonProperty("username")
val username: String? = null
) | 0 | Kotlin | 0 | 0 | 32e5531b563631152737186915d06c8633c665d1 | 628 | Dribbble-Android | MIT License |
MLN-Android/buildSrc/mlnPlugin/src/main/kotlin/com/jdd/android/mln/ModuleConfig.kt | momotech | 209,464,640 | false | {"C": 10709384, "Java": 4810073, "Objective-C": 2521606, "Lua": 419100, "Kotlin": 98796, "Shell": 33644, "FreeMarker": 29400, "Objective-C++": 11980, "CMake": 6555, "Ruby": 6494, "Makefile": 3309, "Python": 420, "C++": 191} | package com.jdd.android.mln
import org.objectweb.asm.AnnotationVisitor
import org.objectweb.asm.ClassReader
import org.objectweb.asm.Opcodes
internal class ModuleConfig(
val className: String// like com/immomo/mln/bridge/com$$immomo$$demo$$Register
)
internal class ModuleConfigAnnotationVisitor(
private val classReader: ClassReader,
val onVisitEnd: (ModuleConfig) -> Unit
) : AnnotationVisitor(Opcodes.ASM6) {
override fun visitEnd() {
onVisitEnd(ModuleConfig(classReader.className))
}
} | 98 | C | 206 | 1,612 | 6341ff6f4db5db0400691b70b4e595bffd623b36 | 521 | MLN | MIT License |
vmtools/src/main/kotlin/com/vmloft/develop/library/tools/voice/view/VMRecorderView.kt | lzan13 | 78,939,095 | false | {"Kotlin": 759701, "Java": 45897, "HTML": 2434, "C": 2090, "Makefile": 967} | package com.vmloft.develop.library.tools.voice.view
import android.content.Context
import android.graphics.Paint
import android.util.AttributeSet
import android.view.View
import com.vmloft.develop.library.tools.permission.VMPermission
import com.vmloft.develop.library.tools.utils.VMSystem
import com.vmloft.develop.library.tools.voice.bean.VMVoiceBean
import com.vmloft.develop.library.tools.voice.recorder.VMRecorderActionListener
import com.vmloft.develop.library.tools.voice.recorder.VMRecorderEngine
import com.vmloft.develop.library.tools.voice.recorder.VMRecorderManager
import java.util.*
/**
* Created by lzan13 on 2024/01/10
* 描述:自定义录音控件
*/
open class VMRecorderView @JvmOverloads constructor(context: Context, attrs: AttributeSet? = null, defStyleAttr: Int = 0) :
View(context, attrs, defStyleAttr) {
// 画笔
lateinit var paint: Paint
// 是否开始录制
var isStart = false
var isReadyCancel = false // 取消状态
var isUsable = false // 是否可用
var startTime: Long = 0 // 录制开始时间
var durationTime: Int = 0 // 录制持续时间
var voiceDecibel = 1 // 声音分贝
var countDownTime: Int = 0 // 录制倒计时
// 录音声音分贝集合
var decibelList = mutableListOf<Int>()
var decibelCount: Int = 0 // 声音分贝总数,用来计算抽样
// 定时器
var timer: Timer? = null
// 录音控件回调接口
private var recorderActionListener: VMRecorderActionListener? = null
// 录音联动动画控件
private var recorderWaveformView: VMRecorderWaveformView? = null
// 录音引擎
lateinit var recorderEngine: VMRecorderEngine
/**
* 启动录音时间记录
*/
fun startRecordTimer() {
// 开始录音,记录开始录制时间
startTime = System.currentTimeMillis()
timer = Timer()
timer?.purge()
val task: TimerTask = object : TimerTask() {
override fun run() {
if (!isStart) return
durationTime = (System.currentTimeMillis() - startTime).toInt()
countDownTime = VMRecorderManager.maxDuration - durationTime
voiceDecibel = recorderEngine.decibel()
if (durationTime > VMRecorderManager.maxDuration) {
VMSystem.runInUIThread({ stopRecord(false) })
}
// 将声音分贝添加到集合,这里防止过大,进行抽样保存
if (decibelCount % 2 == 1) {
decibelList.add(voiceDecibel)
}
onRecordDecibel(voiceDecibel)
val fftData = recorderEngine.getFFTData()
onRecordFFTData(fftData)
val simple = decibelCount % (VMRecorderManager.touchAnimTime / VMRecorderManager.sampleTime).toInt()
if (simple == 0) {
// startInnerAnim()
// startOuterAnim()
}
decibelCount++
postInvalidate()
}
}
timer?.scheduleAtFixedRate(task, 10, VMRecorderManager.sampleTime.toLong())
}
/**
* 开始录音
*/
open fun startRecord() {
isStart = true
// 调用录音机开始录制音频
val code: Int = recorderEngine.startRecord(null)
if (code == VMRecorderManager.errorNone) {
startRecordTimer()
onRecordStart()
} else if (code == VMRecorderManager.errorRecording) {
// TODO 正在录制中,不做处理
} else if (code == VMRecorderManager.errorSystem) {
isStart = false
onRecordError(code, "录音系统错误")
reset()
}
invalidate()
}
/**
* 停止录音
*
* @param cancel 是否为取消
*/
open fun stopRecord(cancel: Boolean = false) {
stopTimer()
if (cancel) {
recorderEngine.cancelRecord()
onRecordCancel()
} else {
val code: Int = recorderEngine.stopRecord()
if (code == VMRecorderManager.errorFailed) {
onRecordError(code, "录音失败")
} else if (code == VMRecorderManager.errorSystem || durationTime < 1000) {
if (durationTime < 1000) {
// 录制时间太短
onRecordError(VMRecorderManager.errorShort, "录音时间过短")
} else {
onRecordError(VMRecorderManager.errorShort, "录音系统出现错误")
}
} else {
onRecordComplete()
}
}
reset()
invalidate()
}
/**
* 停止计时
*/
private fun stopTimer() {
timer?.purge()
timer?.cancel()
timer = null
}
/**
* 重置控件
*/
fun reset() {
isStart = false
isReadyCancel = false
startTime = 0L
durationTime = 0
countDownTime = 0
decibelList.clear()
}
// 录音开始
open fun onRecordStart() {
recorderWaveformView?.visibility = VISIBLE
recorderActionListener?.onStart()
}
// 录音取消
fun onRecordCancel() {
recorderWaveformView?.visibility = GONE
recorderActionListener?.onCancel()
}
// 录音完成
fun onRecordComplete() {
recorderWaveformView?.visibility = GONE
val bean = VMVoiceBean(duration = durationTime, path = recorderEngine.getRecordFile())
// 这里在录制完成后,需要清空 decibelList
bean.decibelList.addAll(decibelList)
recorderActionListener?.onComplete(bean)
}
// 录音分贝变化
fun onRecordDecibel(decibel: Int) {
recorderWaveformView?.updateDecibel(decibel)
recorderActionListener?.onDecibel(voiceDecibel)
}
// 录音分贝变化
fun onRecordFFTData(data: DoubleArray) {
recorderWaveformView?.updateFFTData(data)
recorderActionListener?.onRecordFFTData(data)
}
// 录音出现错误
fun onRecordError(code: Int, desc: String) {
recorderWaveformView?.visibility = GONE
recorderActionListener?.onError(code, desc)
}
/**
* 检查权限
*/
fun checkPermission() {
// 检查录音权限
if (VMPermission.checkRecord()) {
isUsable = true
} else {
isUsable = false
VMPermission.requestRecord(context) {
if (it) {
isUsable = true
invalidate()
} else {
isUsable = false
invalidate()
}
}
}
}
override fun onVisibilityChanged(changedView: View, visibility: Int) {
super.onVisibilityChanged(changedView, visibility)
if (visibility == 0) {
// View 可见 检查下权限
isUsable = VMPermission.checkRecord()
}
}
/**
* 设置录音联动波形控件
*/
fun setRecorderWaveformView(view: VMRecorderWaveformView?) {
recorderWaveformView = view
}
/**
* 设置录音回调
*/
fun setRecorderActionListener(listener: VMRecorderActionListener?) {
recorderActionListener = listener
}
}
| 0 | Kotlin | 14 | 34 | c6eca3fb479d82ca14ca3bdcc3fb5f5494a4db0c | 6,841 | VMLibrary | MIT License |
app/src/main/java/tr/com/gndg/self/domain/model/Label.kt | Cr3bain | 840,332,370 | false | {"Kotlin": 567278} | package tr.com.gndg.self.domain.model
import tr.com.gndg.self.core.dataSource.roomDatabase.entity.LabelEntity
data class Label(
val id : Long?,
val uuid: String,
val labelName: String
)
fun Label.toLabelEntity() = LabelEntity(
uuid = this.uuid, labelName = this.labelName
) | 0 | Kotlin | 0 | 0 | 12e58c3753a642bfd922d9cca44486eef3453e88 | 292 | self | Apache License 2.0 |
data/attraction_image/src/test/java/tw/com/deathhit/data/attraction_image/MapperExtTest.kt | Deathhit | 748,190,483 | false | {"Kotlin": 128617} | package tw.com.deathhit.data.attraction_image
import org.junit.Test
import tw.com.deathhit.core.app_database.view.AttractionImageItemView
import java.util.UUID
import kotlin.random.Random
class MapperExtTest {
@Test
fun mapAttractionImageItemToDO() {
//Given
val attractionImageItem = AttractionImageItemView(
attractionId = getRandomStr(),
imageUrl = getRandomStr(),
remoteOrder = getRandomInt()
)
//When
val attractionImageDO = attractionImageItem.toDO()
//Then
assert(attractionImageDO.attractionId == attractionImageItem.attractionId)
assert(attractionImageDO.imageUrl == attractionImageItem.imageUrl)
}
private fun getRandomInt() = Random.nextInt()
private fun getRandomStr() = UUID.randomUUID().toString()
} | 0 | Kotlin | 0 | 0 | cb94ead56f0257cdd30815cc9b20ca932ca3a351 | 838 | TaipeiTour | Apache License 2.0 |
app/src/androidTest/java/com/example/testapplication/espresso/assertion/DelayView.kt | DaniZakaria63 | 668,744,134 | false | null | package com.example.testapplication.espresso.assertion
import android.view.View
import androidx.test.espresso.UiController
import androidx.test.espresso.ViewAction
import androidx.test.espresso.matcher.ViewMatchers
import org.hamcrest.Matcher
class DelayView(val time: Long) : ViewAction {
override fun getDescription(): String = "Wait for delay"
override fun getConstraints(): Matcher<View> = ViewMatchers.isRoot()
override fun perform(uiController: UiController?, view: View?) {
uiController?.loopMainThreadForAtLeast(time)
}
} | 0 | Kotlin | 0 | 0 | e49765fd227152e25d62b8fa60aadd3522d6aad6 | 557 | test-flow-notification | The Unlicense |
src/main/kotlin/org/jetbrains/fortran/util/ParserEnum.kt | Julianna-fil | 264,682,052 | true | {"Kotlin": 422088, "Fortran": 37632, "Lex": 11709, "Java": 7211, "HTML": 6153} | package org.jetbrains.fortran.util
enum class MathOperators(val sign: String, val precedence: Int) {
PLUS("+", 2),
MINUS("-", 2),
MULTIPLY("*", 3),
DIVISION("/", 4),
POWER("^", 5),
EXPONENTIAL("E", 5),
UNARY("u", 6);
}
enum class FunctionalOperators(val func: String) {
sin("sin("),
cos("cos("),
tan("tan("),
asin("asin("),
acos("acos("),
atan("atan("),
sinh("sinh("),
cosh("cosh("),
tanh("tanh("),
log2("log2("),
log10("log10("),
ln("ln("),
logx("log"),
sqrt("sqrt("),
exp("exp(")
} | 0 | Kotlin | 0 | 0 | 8abf8c5612a2dfd03e8f3469887176af7f27affe | 574 | fortran-plugin | Apache License 2.0 |
libnavigation-base/src/test/java/com/mapbox/navigation/base/options/EHorizonOptionsTest.kt | jackgregory | 337,518,939 | true | {"Kotlin": 1912845, "Java": 124339, "Python": 10396, "Makefile": 5455, "JavaScript": 2362, "Shell": 1686} | package com.mapbox.navigation.base.options
import com.mapbox.navigation.testing.BuilderTest
import org.junit.Test
class EHorizonOptionsTest : BuilderTest<EHorizonOptions, EHorizonOptions.Builder>() {
override fun getImplementationClass() = EHorizonOptions::class
override fun getFilledUpBuilder() = EHorizonOptions.Builder()
.length(1500.0)
.expansion(1)
.branchLength(150.0)
.includeGeometries(true)
@Test
override fun trigger() {
// trigger, see KDoc
}
}
| 0 | null | 0 | 0 | 81a06b641ddbdb4bc05c35663618b56615da6312 | 522 | mapbox-navigation-android | Apache License 2.0 |
vuesaxicons/src/commonMain/kotlin/moe/tlaster/icons/vuesax/vuesaxicons/crypto/outline/Ontology.kt | Tlaster | 560,394,734 | false | {"Kotlin": 25133302} | package moe.tlaster.icons.vuesax.vuesaxicons.crypto.outline
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.PathFillType
import androidx.compose.ui.graphics.PathFillType.Companion.NonZero
import androidx.compose.ui.graphics.SolidColor
import androidx.compose.ui.graphics.StrokeCap
import androidx.compose.ui.graphics.StrokeCap.Companion.Butt
import androidx.compose.ui.graphics.StrokeJoin
import androidx.compose.ui.graphics.StrokeJoin.Companion.Miter
import androidx.compose.ui.graphics.vector.ImageVector
import androidx.compose.ui.graphics.vector.ImageVector.Builder
import androidx.compose.ui.graphics.vector.path
import androidx.compose.ui.unit.dp
import moe.tlaster.icons.vuesax.vuesaxicons.crypto.OutlineGroup
public val OutlineGroup.Ontology: ImageVector
get() {
if (_ontology != null) {
return _ontology!!
}
_ontology = Builder(name = "Ontology", defaultWidth = 24.0.dp, defaultHeight = 24.0.dp,
viewportWidth = 24.0f, viewportHeight = 24.0f).apply {
path(fill = SolidColor(Color(0xFF000000)), stroke = null, strokeLineWidth = 0.0f,
strokeLineCap = Butt, strokeLineJoin = Miter, strokeLineMiter = 4.0f,
pathFillType = NonZero) {
moveTo(11.7005f, 22.7498f)
curveTo(11.6005f, 22.7498f, 11.5105f, 22.7498f, 11.4105f, 22.7498f)
curveTo(5.9305f, 22.5998f, 1.4805f, 17.8798f, 1.4805f, 12.2398f)
verticalLineTo(5.2098f)
curveTo(1.4805f, 4.6998f, 1.7805f, 4.2498f, 2.2505f, 4.0598f)
curveTo(2.7205f, 3.8698f, 3.2504f, 3.9698f, 3.6104f, 4.3298f)
lineTo(18.4405f, 19.1598f)
curveTo(18.5905f, 19.3098f, 18.6705f, 19.5098f, 18.6605f, 19.7198f)
curveTo(18.6505f, 19.9298f, 18.5605f, 20.1198f, 18.4005f, 20.2598f)
curveTo(16.5405f, 21.8698f, 14.1705f, 22.7498f, 11.7005f, 22.7498f)
close()
moveTo(2.9805f, 5.8098f)
verticalLineTo(12.2398f)
curveTo(2.9805f, 17.0798f, 6.7805f, 21.1198f, 11.4505f, 21.2498f)
curveTo(13.3805f, 21.2898f, 15.2505f, 20.7298f, 16.7805f, 19.6198f)
lineTo(2.9805f, 5.8098f)
close()
}
path(fill = SolidColor(Color(0xFF000000)), stroke = null, strokeLineWidth = 0.0f,
strokeLineCap = Butt, strokeLineJoin = Miter, strokeLineMiter = 4.0f,
pathFillType = NonZero) {
moveTo(21.2696f, 19.9001f)
curveTo(20.9496f, 19.9001f, 20.6296f, 19.7701f, 20.3896f, 19.5301f)
lineTo(5.6896f, 4.8301f)
curveTo(5.5396f, 4.6801f, 5.4596f, 4.4801f, 5.4696f, 4.2701f)
curveTo(5.4796f, 4.0601f, 5.5696f, 3.8701f, 5.7296f, 3.7301f)
curveTo(7.6396f, 2.0601f, 10.1096f, 1.1701f, 12.6696f, 1.2501f)
curveTo(18.0996f, 1.4001f, 22.5196f, 6.0801f, 22.5196f, 11.6801f)
verticalLineTo(18.6401f)
curveTo(22.5196f, 19.1501f, 22.2196f, 19.6001f, 21.7496f, 19.7901f)
curveTo(21.5996f, 19.8601f, 21.4396f, 19.9001f, 21.2696f, 19.9001f)
close()
moveTo(7.3496f, 4.3701f)
lineTo(21.0296f, 18.0501f)
verticalLineTo(11.6901f)
curveTo(21.0296f, 6.9001f, 17.2596f, 2.8901f, 12.6296f, 2.7601f)
curveTo(10.7196f, 2.7201f, 8.8696f, 3.2701f, 7.3496f, 4.3701f)
close()
}
}
.build()
return _ontology!!
}
private var _ontology: ImageVector? = null
| 0 | Kotlin | 0 | 2 | b8a8231e6637c2008f675ae76a3423b82ee53950 | 3,704 | VuesaxIcons | MIT License |
client-coroutines/src/main/kotlin/io/provenance/client/coroutines/gas/prices/UrlGasPrices.kt | provenance-io | 436,014,429 | false | {"Kotlin": 74296} | package io.provenance.client.coroutines.gas.prices
import com.google.gson.Gson
import cosmos.base.v1beta1.CoinOuterClass
import io.provenance.client.common.gas.GasPrice
import kotlinx.coroutines.CoroutineScope
import org.apache.http.client.methods.HttpGet
import org.apache.http.impl.client.HttpClientBuilder
import java.io.InputStream
import java.io.InputStreamReader
/**
*
*/
fun CoroutineScope.urlGasPrices(
uri: String,
fetch: suspend (uri: String) -> InputStream = defaultHttpFetch,
marshal: suspend (body: InputStream) -> CoinOuterClass.Coin = defaultCoinMarshal,
): GasPrices = gasPrices { marshal(fetch(uri)) }
/**
*
*/
private val gson = Gson().newBuilder().create()
/**
*
*/
private val httpClient = HttpClientBuilder.create().build()
/**
*
*/
private val defaultHttpFetch: suspend (uri: String) -> InputStream = {
val result = httpClient.execute(HttpGet(it))
require(result.statusLine.statusCode in 200..299) {
"failed to get uri:$it status:${result.statusLine.statusCode}: ${result.statusLine.reasonPhrase}"
}
result.entity.content
}
/**
*
*/
private val defaultCoinMarshal: suspend (body: InputStream) -> CoinOuterClass.Coin = {
it.use { i ->
InputStreamReader(i).use { isr ->
gson.fromJson(isr, GasPrice::class.java).toCoin()
}
}
}
| 1 | Kotlin | 6 | 7 | 93bece535fd9f6ae54a9af100f818dbd9bb1d3f9 | 1,334 | pb-grpc-client-kotlin | Apache License 2.0 |
demo-app/src/main/kotlin/io/getstream/video/android/MainActivity.kt | GetStream | 505,572,267 | false | {"Kotlin": 2549850, "MDX": 279508, "Python": 18285, "Shell": 4455, "JavaScript": 1112, "PureBasic": 107} | /*
* Copyright (c) 2014-2023 Stream.io Inc. All rights reserved.
*
* Licensed under the Stream License;
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://github.com/GetStream/stream-video-android/blob/main/LICENSE
*
* 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.getstream.video.android
import android.os.Bundle
import android.util.Log
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.lifecycleScope
import androidx.lifecycle.repeatOnLifecycle
import com.google.firebase.analytics.FirebaseAnalytics
import dagger.hilt.android.AndroidEntryPoint
import io.getstream.video.android.analytics.FirebaseEvents
import io.getstream.video.android.compose.theme.VideoTheme
import io.getstream.video.android.datastore.delegate.StreamUserDataStore
import io.getstream.video.android.tooling.util.StreamFlavors
import io.getstream.video.android.ui.AppNavHost
import io.getstream.video.android.ui.AppScreens
import io.getstream.video.android.util.InAppUpdateHelper
import io.getstream.video.android.util.InstallReferrer
import kotlinx.coroutines.flow.firstOrNull
import kotlinx.coroutines.launch
import javax.inject.Inject
@AndroidEntryPoint
class MainActivity : ComponentActivity() {
@Inject
lateinit var dataStore: StreamUserDataStore
private val firebaseAnalytics by lazy { FirebaseAnalytics.getInstance(this) }
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
// Try to read the Google Play install referrer value. We use it to deliver
// the Call ID from the QR code link.
@Suppress("KotlinConstantConditions")
if (BuildConfig.FLAVOR == StreamFlavors.production) {
InstallReferrer(this).extractInstallReferrer { callId: String ->
Log.d("MainActivity", "Call ID: $callId")
firebaseAnalytics.logEvent(FirebaseEvents.INSTALL_FROM_QR_CODE, null)
startActivity(DeeplinkingActivity.createIntent(this, callId, true))
finish()
}
}
lifecycleScope.launch {
repeatOnLifecycle(Lifecycle.State.CREATED) {
InAppUpdateHelper(this@MainActivity).checkForAppUpdates()
}
}
lifecycleScope.launch {
val isLoggedIn = dataStore.user.firstOrNull() != null
setContent {
VideoTheme {
AppNavHost(
startDestination = if (!isLoggedIn) {
AppScreens.Login.routeWithArg(true) // Pass true for autoLogIn
} else {
AppScreens.CallJoin.route
},
)
}
}
}
}
}
| 3 | Kotlin | 30 | 308 | 1c67906e4c01e480ab180f30b39f341675bc147e | 3,192 | stream-video-android | FSF All Permissive License |
src/main/kotlin/org/rust/lang/core/types/ty/TyFunction.kt | intellij-rust | 42,619,487 | false | null | /*
* Use of this source code is governed by the MIT license that can be
* found in the LICENSE file.
*/
package org.rust.lang.core.types.ty
import org.rust.lang.core.psi.RsTypeAlias
import org.rust.lang.core.types.BoundElement
import org.rust.lang.core.types.infer.TypeFolder
import org.rust.lang.core.types.infer.TypeVisitor
import org.rust.lang.core.types.mergeFlags
data class TyFunction(
val paramTypes: List<Ty>,
val retType: Ty,
override val aliasedBy: BoundElement<RsTypeAlias>? = null
) : Ty(mergeFlags(paramTypes) or retType.flags) {
override fun superFoldWith(folder: TypeFolder): Ty =
TyFunction(paramTypes.map { it.foldWith(folder) }, retType.foldWith(folder), aliasedBy?.foldWith(folder))
override fun superVisitWith(visitor: TypeVisitor): Boolean =
paramTypes.any { it.visitWith(visitor) } || retType.visitWith(visitor)
override fun withAlias(aliasedBy: BoundElement<RsTypeAlias>): Ty = copy(aliasedBy = aliasedBy)
}
| 1,774 | null | 361 | 4,334 | 34f7803a55f542d7c72553c5c84742093d79937c | 980 | intellij-rust | MIT License |
publisher-sdk/src/test/java/com/criteo/publisher/csm/MetricDirectoryUnitTest.kt | vpathania1 | 303,953,882 | true | {"Java Properties": 1, "Markdown": 2, "Shell": 1, "Batchfile": 1, "Gradle Kotlin DSL": 6, "Kotlin": 87, "Java": 275, "INI": 1, "Proguard": 2} | /*
* Copyright 2020 Criteo
*
* 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.criteo.publisher.csm
import android.content.Context
import com.criteo.publisher.mock.MockBean
import com.criteo.publisher.mock.MockedDependenciesRule
import com.criteo.publisher.util.BuildConfigWrapper
import com.nhaarman.mockitokotlin2.*
import org.assertj.core.api.Assertions.assertThat
import org.junit.Rule
import org.junit.Test
import org.mockito.InjectMocks
import org.mockito.Mock
import org.mockito.junit.MockitoJUnit
import java.io.File
import java.io.FilenameFilter
class MetricDirectoryUnitTest {
@Rule
@JvmField
val mockitoRule = MockitoJUnit.rule()
@Rule
@JvmField
val mockedDependenciesRule = MockedDependenciesRule()
@MockBean
private lateinit var buildConfigWrapper: BuildConfigWrapper
@Mock
private lateinit var context: Context
@Mock
private lateinit var parser: MetricParser
@InjectMocks
private lateinit var directory: MetricDirectory
@Test
fun listFiles_GivenDirectoryReturningNull_ReturnEmpty() {
directory = spy(directory) {
doReturn(mock<File>()).whenever(mock).directoryFile
}
directory.directoryFile.stub {
on { listFiles(any<FilenameFilter>()) } doReturn null
}
val files = directory.listFiles()
assertThat(files).isEmpty()
}
} | 0 | null | 0 | 0 | b0d59098cb400d7c0ce7b5c510249f12afea716a | 1,870 | android-publisher-sdk | Apache License 2.0 |
ticktock-compiler/src/main/kotlin/dev/zacsweers/ticktock/compiler/JavaWriter.kt | ZacSweers | 273,987,567 | false | {"Java": 73404, "Kotlin": 35667, "Shell": 395} | /*
* Copyright (C) 2020 <NAME> & <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
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package dev.zacsweers.ticktock.compiler
import com.squareup.javapoet.CodeBlock
import com.squareup.javapoet.FieldSpec
import com.squareup.javapoet.JavaFile
import com.squareup.javapoet.MethodSpec
import com.squareup.javapoet.ParameterizedTypeName
import com.squareup.javapoet.TypeName
import com.squareup.javapoet.TypeSpec
import dev.zacsweers.ticktock.runtime.ZoneIdsProvider
import java.nio.file.Files
import java.nio.file.Path
import java.util.Arrays
import javax.lang.model.element.Modifier.FINAL
import javax.lang.model.element.Modifier.PRIVATE
import javax.lang.model.element.Modifier.PUBLIC
import javax.lang.model.element.Modifier.STATIC
internal class JavaWriter(
private val outputDir: Path
) : RulesWriter {
override fun writeZoneIds(packageName: String, version: String, zoneIds: Set<String>) {
val versionField = version(version)
val zoneIdsField = regionId(zoneIds)
val typeSpec = TypeSpec.classBuilder("GeneratedZoneIdsProvider")
.addModifiers(FINAL)
.addSuperinterface(ZoneIdsProvider::class.java)
.addField(versionField)
.addMethod(
MethodSpec.methodBuilder("getVersionId")
.addAnnotation(Override::class.java)
.addModifiers(PUBLIC)
.returns(versionField.type)
.addStatement("return \$N", versionField)
.build()
)
.addField(zoneIdsField)
.addMethod(
MethodSpec.methodBuilder("getZoneIds")
.addAnnotation(Override::class.java)
.addModifiers(PUBLIC)
.returns(zoneIdsField.type)
.addStatement("return \$N", zoneIdsField)
.build()
)
.build()
Files.createDirectories(outputDir)
JavaFile.builder(packageName, typeSpec)
.build()
.writeTo(outputDir)
}
private fun version(version: String): FieldSpec {
return FieldSpec.builder(String::class.java, "VERSION_ID", PRIVATE, STATIC, FINAL)
.initializer("\$S", version)
.build()
}
private fun regionId(allRegionIds: Set<String>): FieldSpec {
val blocks = allRegionIds.map { CodeBlock.of("\$S", it) }
val joinedBlocks = CodeBlock.join(blocks, ",\n")
val initializer = CodeBlock.builder()
.add("\$T.asList(\n$>$>", Arrays::class.java)
.add(joinedBlocks)
.add("$<$<)")
.build()
val listType: TypeName = ParameterizedTypeName.get(Collection::class.java, String::class.java)
return FieldSpec.builder(listType, "ZONE_IDS", PRIVATE, STATIC, FINAL)
.initializer(initializer)
.build()
}
}
| 3 | Java | 7 | 137 | 018fd08805a1f2326e9abcbdc3b569f364985e96 | 3,132 | ticktock | Apache License 2.0 |
app/src/main/java/com/nawrot/mateusz/sportapp/news/NewsFragment.kt | mateusz-nawrot | 111,785,233 | false | null | package com.nawrot.mateusz.sportapp.news
import android.content.Context
import android.support.v4.app.Fragment
import dagger.android.support.AndroidSupportInjection
import retrofit2.Retrofit
import javax.inject.Inject
class NewsFragment : Fragment() {
@Inject
lateinit var retrofit: Retrofit
override fun onAttach(context: Context?) {
AndroidSupportInjection.inject(this)
super.onAttach(context)
}
} | 0 | Kotlin | 0 | 0 | dc5966d4648b6967213ca14a531526e1c7abda25 | 436 | sportapp | Apache License 2.0 |
src/com/aaron/binarytree/ktx/BinaryTree.kt | aaronzzx | 433,869,082 | false | {"Kotlin": 54422, "Java": 20372} | @file:Suppress("UNUSED")
package com.aaron.binarytree.ktx
import com.aaron.binarytree.base.IBinaryTree
import com.aaron.binarytree.base.IBinaryTreeTraversal
import com.aaron.binarytree.base.Visitor
/**
* @author <EMAIL>
* @since 2021/12/1
*/
private const val Z = 0
/**
* 按前序输入 List
*/
fun <E> IBinaryTreeTraversal<E>.toListByPreorder(): List<E> {
val list = createList()
preorderTraversal(inflateInto(list))
return list
}
/**
* 按中序输出 List
*/
fun <E> IBinaryTreeTraversal<E>.toListByInorder(): List<E> {
val list = createList()
inorderTraversal(inflateInto(list))
return list
}
/**
* 按后序输出 List
*/
fun <E> IBinaryTreeTraversal<E>.toListByPostorder(): List<E> {
val list = createList()
postorderTraversal(inflateInto(list))
return list
}
/**
* 按层序输出 List
*/
fun <E> IBinaryTreeTraversal<E>.toListByLevelOrder(): List<E> {
val list = createList()
levelOrderTraversal(inflateInto(list))
return list
}
private fun <E> inflateInto(collection: MutableCollection<E>): Visitor<E> {
return object : Visitor<E>() {
override fun visit(item: E): Boolean {
collection.add(item)
return false
}
}
}
private fun <E> IBinaryTreeTraversal<E>.createList(): MutableList<E> {
return when (this) {
is IBinaryTree<E> -> ArrayList(size)
else -> ArrayList()
}
} | 0 | Kotlin | 0 | 0 | ee469b5d413c203c66e707bc528cc04134546e7c | 1,377 | BinaryTree | Apache License 2.0 |
recycler/src/main/java/com/shim/recycler/recyclerlist/ListOptimizationConfig.kt | shimshimbola | 346,238,988 | false | null | package com.shim.recycler.recyclerlist
import android.widget.RelativeLayout
data class ListOptimizationConfig(
val optHandler: ViewOptHandler,
val relativeLayout: RelativeLayout,
val noOfCols: Int = 1) | 0 | Kotlin | 0 | 0 | fc5dd8c9ac8e2a110c6e8d5f3602e550fdfea702 | 227 | Custom-Recycler | MIT License |
app/src/main/java/com/pet/chat/network/data/receive/UserOnline.kt | ViktorMorgachev | 438,899,533 | false | null | package com.pet.chat.network.data.receive
import com.google.gson.annotations.SerializedName
data class UserOnline(
@SerializedName("id")
var userID: Number,
var online: Boolean
) | 0 | Kotlin | 0 | 0 | 14065fa300ece434f4605b56938e7c80a4dde4f4 | 193 | ChatBest | Apache License 2.0 |
app/src/main/java/com/jerry/assessment/features/mobilecoverage/domain/model/MobileAvailability.kt | jchodev | 730,705,691 | false | {"Kotlin": 257177} | package com.jerry.assessment.features.mobilecoverage.domain.model
data class MobileAvailability (
val addressShortDescription: String,
val postCode: String = "",
//EE
val eeVoiceOutdoor: Int = 0,
val eeVoiceOutdoorNo4g: Int = 0,
val eeVoiceIndoor: Int = 0,
val eeVoiceIndoorNo4g: Int = 0,
val eeDataOutdoor: Int = 0,
val eeDataOutdoorNo4g: Int = 0,
val eeDataIndoor: Int = 0,
val eeDataIndoorNo4g: Int = 0,
//Three
val h3VoiceOutdoor: Int = 0,
val h3VoiceOutdoorNo4g: Int = 0,
val h3VoiceIndoor: Int = 0,
val h3VoiceIndoorNo4g: Int = 0,
val h3DataOutdoor: Int = 0,
val h3DataOutdoorNo4g: Int = 0,
val h3DataIndoor: Int = 0,
val h3DataIndoorNo4g: Int = 0,
//O2
val o2VoiceOutdoor: Int = 0,
val o2VoiceOutdoorNo4g: Int = 0,
val o2VoiceIndoor: Int = 0,
val o2VoiceIndoorNo4g: Int = 0,
val o2DataOutdoor: Int = 0,
val o2DataOutdoorNo4g: Int = 0,
val o2DataIndoor: Int = 0,
val o2DataIndoorNo4g: Int = 0,
//Vodafone
val voVoiceOutdoor: Int = 0,
val voVoiceOutdoorNo4g: Int = 0,
val voVoiceIndoor: Int = 0,
val voVoiceIndoorNo4g: Int = 0,
val voDataOutdoor: Int = 0,
val voDataOutdoorNo4g: Int = 0,
val voDataIndoor: Int = 0,
val voDataIndoorNo4g: Int = 0,
val signalTypeList : List<ProviderSignalType>
)
enum class SignalType(val value: String) {
DATA_INDOOR("data_indoor"),
DATA_OUTDOOR("data_outdoor"),
VOICE_INDOOR("voice_indoor"),
VOICE_OUTDOOR("voice_outdoor")
}
enum class Provider(val value: String) {
EE("ee"),
THREE("three"),
O2("o2"),
VODAFONE("vodafone")
}
data class ProviderSignalType(
val signalType : SignalType,
val providerSignalList: List<ProviderSignal>
)
data class ProviderSignal(
val provider: Provider,
val fourG: Int,
val nonFourG: Int
)
| 0 | Kotlin | 0 | 1 | 5cdbdeb2cf9178310bce2eb2e4028409d4f40fbd | 1,876 | mobile-coverage-2 | MIT License |
mobile/src/main/java/de/lemke/nakbuch/domain/buchUseCases/AddHymnToHistoryListUseCase.kt | Lemkinator | 475,012,572 | false | null | package de.lemke.nakbuch.domain.buchUseCases
import de.lemke.nakbuch.data.BuchRepository
import de.lemke.nakbuch.domain.model.Hymn
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
import java.time.LocalDateTime
import javax.inject.Inject
class AddHymnToHistoryListUseCase @Inject constructor(
private val buchRepository: BuchRepository
) {
suspend operator fun invoke(hymn: Hymn) = withContext(Dispatchers.Default) {
buchRepository.addToHistoryList(hymn, LocalDateTime.now())
}
} | 0 | Kotlin | 0 | 5 | 36180e6761139bf1e3a6c750a2616501c7662c9e | 528 | NAK-Buch | MIT License |
projects/club/src/fanpoll/club/ClubNotification.kt | csieflyman | 359,559,498 | false | {"Kotlin": 737653, "JavaScript": 16441, "HTML": 5481, "PLpgSQL": 3891, "Dockerfile": 126} | /*
* Copyright (c) 2021. fanpoll All rights reserved.
*/
package fanpoll.club
import fanpoll.club.features.ClubUserTable
import fanpoll.club.features.UserDTO
import fanpoll.infra.app.UserDeviceTable
import fanpoll.infra.auth.principal.UserType
import fanpoll.infra.base.query.DynamicQuery
import fanpoll.infra.database.sql.transaction
import fanpoll.infra.database.util.DynamicDBQuery
import fanpoll.infra.database.util.toDTO
import fanpoll.infra.notification.Notification
import fanpoll.infra.notification.NotificationCategory
import fanpoll.infra.notification.NotificationType
import fanpoll.infra.notification.Recipient
import fanpoll.infra.notification.channel.NotificationChannel
import fanpoll.infra.openapi.schema.operation.support.OpenApiIgnore
import kotlinx.serialization.Transient
import org.jetbrains.exposed.sql.JoinType
import org.jetbrains.exposed.sql.select
import kotlin.reflect.full.memberProperties
import kotlin.reflect.typeOf
object ClubNotification {
val SendNotification = ClubNotificationType(
"sendNotification",
setOf(NotificationChannel.Email, NotificationChannel.Push, NotificationChannel.SMS),
NotificationCategory.System
)
private val notificationType = typeOf<ClubNotificationType>()
val AllTypes = ClubNotification::class.memberProperties
.filter { it.returnType == notificationType }
.map { it.getter.call(this) as ClubNotificationType }
}
class ClubNotificationType(
name: String,
channels: Set<NotificationChannel>,
category: NotificationCategory,
@Transient @OpenApiIgnore private val lazyLoadBlock: (NotificationType.(Notification) -> Unit)? = null
) : NotificationType(ClubConst.projectId, name, channels, category, null, null, lazyLoadBlock) {
override fun findRecipients(userFilters: Map<UserType, String>?): Set<Recipient> {
val userFilter = userFilters?.get(ClubUserType.User.value)?.let {
if (it.isBlank()) null
else DynamicDBQuery.convertPredicate(DynamicQuery.parseFilter(it), UserDTO.mapper)
}
return transaction {
val query = ClubUserTable.join(UserDeviceTable, JoinType.LEFT, ClubUserTable.id, UserDeviceTable.userId) {
UserDeviceTable.enabled eq true
}.slice(
ClubUserTable.id, ClubUserTable.account, ClubUserTable.name,
ClubUserTable.email, ClubUserTable.mobile, ClubUserTable.lang,
UserDeviceTable.id, UserDeviceTable.pushToken
).select { ClubUserTable.enabled eq true }
userFilter?.let { query.adjustWhere { it } }
query.toList().toDTO(UserDTO::class).map { user ->
with(user) {
Recipient(
account!!, ClubUserType.User.value, id, name, lang, email, mobile,
devices?.mapNotNull { it.pushToken }?.toSet()
)
}
}.toSet()
}
}
} | 1 | Kotlin | 9 | 58 | 0336a40bc9a5a8501b7e8cc6aeebd2112e6b4431 | 2,977 | multi-projects-architecture-with-Ktor | MIT License |
src/main/kotlin/dev/wigger/mood/shareing/SharingRepository.kt | LukasW01 | 796,396,744 | false | {"Kotlin": 39268, "HTML": 26923, "Dockerfile": 318, "Shell": 221} | package dev.wigger.mood.shareing
import io.quarkus.hibernate.orm.panache.PanacheRepository
import jakarta.enterprise.context.ApplicationScoped
import java.util.UUID
@ApplicationScoped
class SharingRepository : PanacheRepository<Sharing> {
fun persistOne(sharing: Sharing) = persistAndFlush(sharing)
fun delete(userId: UUID, delegatorId: UUID) = delete("user.id = ?1 and delegator.id = ?2", userId, delegatorId)
fun findByUserId(userId: UUID): List<Sharing>? = find("user.id = ?1", userId).list()
fun findByUserIdAndDelegatorId(userId: UUID, delegatorId: UUID): Sharing? = find("user.id = ?1 and delegator.id = ?2", userId, delegatorId).firstResult()
fun updateOne(
userId: UUID,
delegatorId: UUID,
sharing: Sharing,
) {
findByUserIdAndDelegatorId(userId, delegatorId)?.apply {
permissions = sharing.permissions
persistAndFlush(this)
}
}
}
| 0 | Kotlin | 0 | 0 | b9b5f35d855e9bb7f14c250e422ab89392a393fe | 945 | mood | MIT License |
utils/src/main/kotlin/ru/inforion/lab403/common/utils/Shell.kt | xthebat | 315,958,303 | false | {"Gradle Kotlin DSL": 33, "INI": 1, "Shell": 1, "Text": 1, "Ignore List": 1, "Batchfile": 1, "Markdown": 1, "Kotlin": 257, "Java Properties": 1, "JSON": 1, "Java": 3} | package ru.inforion.lab403.common.utils
import ru.inforion.lab403.common.logging.FINE
import ru.inforion.lab403.common.logging.logger
import java.io.ByteArrayOutputStream
import java.util.concurrent.TimeUnit
class Shell(vararg val cmd: String, val timeout: Long = -1) {
companion object {
val log = logger(FINE)
}
var status: Int = 0
var stdout = String()
var stderr = String()
fun execute(): Shell {
val bout = ByteArrayOutputStream()
val berr = ByteArrayOutputStream()
log.finer { "Executing shell command: ${cmd.joinToString(" ")}" }
val process = Runtime.getRuntime().exec(cmd)
process.inputStream.copyTo(bout)
process.errorStream.copyTo(berr)
if (timeout == -1L)
process.waitFor()
else
process.waitFor(timeout, TimeUnit.MILLISECONDS)
status = process.exitValue()
stdout = bout.toString()
stderr = berr.toString()
return this
}
} | 1 | null | 1 | 1 | e42ce78aa5d230025f197b044db4a698736d1630 | 997 | kotlin-extensions | MIT License |
lib/src/main/kotlin/model/UserLocationProfile.kt | hossain-khan | 871,432,503 | false | {"Kotlin": 8790} | package dev.hossain.timeline.model
import com.squareup.moshi.Json
import com.squareup.moshi.JsonClass
/**
* Represents a user location profile with a list of frequent places.
*
* Example JSON:
* ```json
* {
* "frequentPlaces": [
* {
* "placeId": "ChIJd8BlQ2BZwokRAFUEcm_qrcA",
* "placeLocation": "40.712776°, -74.005974°",
* "label": "WORK"
* },
* {
* "placeId": "ChIJd8BlQ2BZwokRAFUEcm_qrcB",
* "placeLocation": "40.713776°, -74.006974°",
* "label": "HOME"
* }
* ]
* }
* ```
*/
@JsonClass(generateAdapter = true)
data class UserLocationProfile(
val frequentPlaces: List<FrequentPlace>
)
/**
* Represents a frequent place with place ID, place location, and label.
*
* Example JSON:
* ```json
* {
* "placeId": "ChIJd8BlQ2BZwokRAFUEcm_qrcA",
* "placeLocation": "40.712776°, -74.005974°",
* "label": "WORK"
* }
* ```
*/
@JsonClass(generateAdapter = true)
data class FrequentPlace(
val placeId: String,
val placeLocation: String,
val label: String
) | 1 | Kotlin | 0 | 0 | 0555afd12038aa91321e004ebf7266f24055948e | 1,057 | kgeo-device-timeline | MIT License |
src/test/kotlin/nl/hannahsten/utensils/collections/MultisetTest.kt | Hannah-Sten | 115,186,492 | false | {"Gradle": 1, "Shell": 1, "Text": 1, "Ignore List": 1, "Batchfile": 1, "YAML": 1, "Markdown": 1, "Java Properties": 1, "Kotlin": 37, "Java": 1} | package nl.hannahsten.utensils.collections
import org.junit.Test
import kotlin.test.assertEquals
import kotlin.test.assertFalse
import kotlin.test.assertNotEquals
import kotlin.test.assertTrue
/**
* @author <NAME>
*/
abstract class MultisetTest {
/**
* Hash multiset without any elements.
*/
abstract val emptySet: MutableMultiset<Int>
/**
* Test set with:
* `1*-1`, `3*2`, `2*3`, `1*4`.
*/
abstract val testSet: MutableMultiset<Int>
@Test
fun emptyMultiset() {
assertMultisetEquals(emptySet, emptyMultiset<Int>())
assertEquals(0, emptyMultiset<Int>().size)
assertEquals(0, emptyMultiset<Int>().totalCount)
}
@Test
fun multisetOf() {
assertMultisetEquals(emptySet, multisetOf<Int>())
val created = multisetOf(-1, 2, 2, 2, 3, 3, 4)
assertMultisetEquals(testSet, created)
}
@Test
fun mutableMultisetOf() {
assertMultisetEquals(emptySet, mutableMultisetOf<Int>())
val created = mutableMultisetOf(-1, 2, 2, 2, 3, 3, 4)
assertMultisetEquals(testSet, created)
}
@Test
fun toMultiset() {
val elts = listOf(-1, 2, 2, 2, 3, 3, 4)
assertMultisetEquals(testSet, elts.toMultiset())
assertMultisetEquals(emptySet, emptyList<Int>().toMultiset())
}
@Test
fun toMutableMultiset() {
val elts = listOf(-1, 2, 2, 2, 3, 3, 4)
assertMultisetEquals(testSet, elts.toMutableMultiset())
assertMultisetEquals(emptySet, emptyList<Int>().toMutableMultiset())
}
@Test
fun arrayToMultiset() {
val empty = emptyArray<Int>()
val array = intArrayOf(-1, 2, 2, 2, 3, 3, 4)
assertMultisetEquals(emptySet, empty.toMultiset())
assertMultisetEquals(testSet, array.toMultiset())
}
@Test
fun arrayToMutableMultiset() {
val empty = emptyArray<Int>()
val array = intArrayOf(-1, 2, 2, 2, 3, 3, 4)
assertMultisetEquals(emptySet, empty.toMutableMultiset())
assertMultisetEquals(testSet, array.toMutableMultiset())
}
@Test
fun mapToMultiset() {
val empty = emptyMap<Int, Int>()
val map = mapOf(
-1 to 1,
2 to 3,
3 to 2,
4 to 1
)
assertMultisetEquals(emptySet, empty.toMultiset())
assertMultisetEquals(testSet, map.toMultiset())
}
@Test
fun mapToMutableMultiset() {
val empty = emptyMap<Int, Int>()
val map = mapOf(
-1 to 1,
2 to 3,
3 to 2,
4 to 1
)
assertMultisetEquals(emptySet, empty.toMutableMultiset())
assertMultisetEquals(testSet, map.toMutableMultiset())
}
@Test
fun getSize() {
assertEquals(0, emptySet.size)
assertEquals(4, testSet.size)
}
@Test
fun getTotalCount() {
assertEquals(0, emptySet.totalCount)
assertEquals(7, testSet.totalCount)
}
@Test
fun count() {
val empty = emptySet
(-3..7).forEach { assertEquals(0, empty[it]) }
val test = testSet
assertEquals(1, test[-1])
assertEquals(0, test[0])
assertEquals(0, test[1])
assertEquals(3, test[2])
assertEquals(2, test[3])
assertEquals(1, test[4])
assertEquals(0, test[5])
assertEquals(0, test[Int.MAX_VALUE])
}
@Test
fun setCount() {
val empty = emptySet
empty.setCount(2, 14)
empty[4] = Int.MAX_VALUE
assertEquals(14, empty[2])
assertEquals(Int.MAX_VALUE, empty.count(4))
val test = testSet
assertEquals(3, test[2])
test[2] = 19
assertEquals(19, test.count(2))
}
@Test(expected = IllegalArgumentException::class)
fun setCountNegative() {
val empty = emptySet
empty.setCount(3, -1)
}
@Test
fun clearElement() {
val empty = emptySet
val naught = empty.clearElement(29)
assertEquals(0, empty[29])
assertEquals(0, naught)
val test = testSet
val nothing = test.clearElement(-23)
val threeTwos = test.clearElement(2)
assertEquals(0, test[-23])
assertEquals(0, test[2])
assertEquals(0, nothing)
assertEquals(3, threeTwos)
}
@Test
fun isEmpty() {
assertTrue(emptySet.isEmpty())
val test = testSet
assertFalse(test.isEmpty())
test.clearElement(-1)
test.clearElement(2)
test[3] = 0
test.setCount(4, 0)
assertTrue(test.isEmpty())
}
@Test
fun clear() {
val empty = emptySet
empty.clear()
assertTrue(empty.isEmpty())
val test = testSet
test.clear()
assertTrue(test.isEmpty())
}
@Test
fun contains() {
val empty = emptySet
(-3..7).forEach { assertFalse(it in empty) }
val test = testSet
assertFalse(-2 in test)
assertTrue(-1 in test)
assertFalse(0 in test)
assertFalse(1 in test)
assertTrue(2 in test)
assertTrue(3 in test)
assertTrue(4 in test)
assertFalse(5 in test)
assertFalse(Int.MAX_VALUE in test)
}
@Test
fun containsAll() {
val empty = emptySet
assertTrue(empty.containsAll(emptyList()))
assertFalse(empty.containsAll(listOf(0)))
assertFalse(empty.containsAll(listOf(1, 2, 3, 4, 5)))
val test = testSet
assertTrue(test.containsAll(emptySet()))
assertTrue(test.containsAll(listOf(3)))
assertTrue(test.containsAll(listOf(-1, 2, 3, 4)))
assertFalse(test.containsAll(listOf(-1, 9, 3, 4)))
assertFalse(test.containsAll(listOf(-10)))
}
@Test
fun put() {
val empty = emptySet
empty.put(3, 19)
assertEquals(19, empty[3])
empty.put(3, 129389)
assertEquals(19, empty[3])
}
@Test(expected = IllegalArgumentException::class)
fun putNegativeCount() {
emptySet.put(3, -1)
}
@Test
fun add() {
val empty = emptySet
assertTrue(empty.add(3))
assertTrue(empty.add(3))
empty.add(3, 2)
empty.add(2, 10)
assertEquals(4, empty[3])
assertEquals(10, empty[2])
}
@Test
fun addAll() {
val empty = emptySet
assertTrue(empty.addAll(listOf(1, 2, 2, 3)))
assertEquals(1, empty[1])
assertEquals(2, empty[2])
assertEquals(1, empty[3])
val singleton = emptySet
assertTrue(singleton.addAll(listOf(-19)))
assertEquals(1, singleton[-19])
val none = emptySet
assertFalse(none.addAll(emptyList()))
assertEquals(0, none[12])
assertEquals(0, none[-1])
}
@Test
fun remove() {
val empty = emptySet
assertFalse(empty.remove(3))
assertEquals(0, empty.size)
val test = testSet
assertTrue(test.remove(4))
assertTrue(test.remove(2))
assertFalse(test.remove(4))
assertEquals(0, test[-2])
assertEquals(1, test[-1])
assertEquals(2, test[2])
assertEquals(2, test[3])
assertEquals(0, test[4])
}
@Test
fun removeAll() {
val empty = emptySet
assertFalse(empty.removeAll(emptyList()))
assertFalse(empty.removeAll(listOf(1)))
assertFalse(empty.removeAll(listOf(1, 2, 3, 4)))
val test = testSet
assertFalse(test.removeAll(emptyList()))
assertFalse(test.removeAll(listOf(100)))
assertFalse(test.removeAll(listOf(100, 200, 300, 400)))
assertTrue(test.removeAll(listOf(2, 3, 3, 3, 4)))
assertTrue(test.removeAll(listOf(2)))
assertEquals(0, test[-2])
assertEquals(1, test[-1])
assertEquals(1, test[2])
assertEquals(0, test[3])
assertEquals(0, test[4])
}
@Test
fun retainAll() {
val empty = emptySet
assertFalse(empty.retainAll(emptyList()))
assertFalse(empty.retainAll(listOf(1)))
assertFalse(empty.retainAll(listOf(1, 2, 3, 4)))
val test = testSet
assertTrue(test.retainAll(emptyList()))
assertTrue(test.isEmpty())
val test1 = testSet
assertTrue(test1.retainAll(listOf(-1)))
test1.forEach { assertTrue(it < 0) }
val test2 = testSet
assertTrue(test2.retainAll(listOf(2, 4)))
assertEquals(0, test2[-2])
assertEquals(0, test2[-1])
assertEquals(3, test2[2])
assertEquals(0, test2[3])
assertEquals(1, test2[4])
assertEquals(0, test2[5])
}
@Test
fun valueIterator() {
val empty = emptySet
assertEquals(0, empty.toList().size)
val test = testSet
assertEquals(setOf(-1, 2, 3, 4), test.toSet())
}
@Test
fun `value iterator`() {
assertEquals(0, emptySet.valueIterator().asSequence().map { it.second }.sum())
assertEquals(7, testSet.valueIterator().asSequence().map { it.second }.sum())
}
@Test
fun `to string`() {
assertEquals("[]", emptySet.toString())
assertEquals("[1*-1, 3*2, 2*3, 1*4]", testSet.toString())
}
@Test
fun equals() {
assertEquals(emptySet, emptySet)
assertEquals(testSet, testSet)
assertNotEquals(emptySet, testSet)
}
fun <T> assertMultisetEquals(expected: Multiset<T>, actual: Multiset<T>) {
assertTrue(expected.elementEquals(actual))
}
fun <T> Multiset<T>.elementEquals(other: Multiset<T>): Boolean {
for (key in this) {
val value = this[key]
if (other[key] != value) {
return false
}
}
for (key in other) {
val value = other[key]
if (this[key] != value) {
return false
}
}
return true
}
} | 0 | Kotlin | 0 | 4 | f8aab17e5107272c0e7b6fa3ddc67df4281b6cf6 | 9,995 | Utensils | MIT License |
android/src/main/kotlin/com/usercentrics/sdk/flutter/bridge/GetABTestingVariantBridge.kt | Usercentrics | 416,296,210 | false | {"Dart": 343894, "Kotlin": 204588, "Swift": 105016, "Ruby": 2063, "Shell": 1316, "HTML": 1050, "Objective-C": 733} | package com.usercentrics.sdk.flutter.bridge
import com.usercentrics.sdk.flutter.api.FlutterMethodCall
import com.usercentrics.sdk.flutter.api.FlutterResult
import com.usercentrics.sdk.flutter.api.UsercentricsProxy
import com.usercentrics.sdk.flutter.api.UsercentricsProxySingleton
internal class GetABTestingVariantBridge(
private val usercentrics: UsercentricsProxy = UsercentricsProxySingleton
): MethodBridge {
override val name: String
get() = "getABTestingVariant"
override fun invoke(call: FlutterMethodCall, result: FlutterResult) {
assert(name == call.method)
result.success(usercentrics.instance.getABTestingVariant())
}
}
| 0 | Dart | 8 | 4 | a06a5ec81bb21a125718942efd2880b5086d07ae | 675 | flutter-sdk | Apache License 2.0 |
app/src/main/java/com/mbmc/fiinfo/ui/stats/StatsRepository.kt | mbmc | 43,665,769 | false | null | package com.mbmc.fiinfo.ui.stats
import com.mbmc.fiinfo.data.Stat
import com.mbmc.fiinfo.database.EventDao
import kotlinx.coroutines.flow.Flow
import javax.inject.Inject
class StatsRepository @Inject constructor(private val eventDao: EventDao) {
fun getStats(): Flow<List<Stat>> =
eventDao.getStats()
} | 3 | Kotlin | 6 | 33 | ebbf058c19b5045958d22035c8529bf8070703f4 | 317 | FiInfo | Apache License 2.0 |
app/src/main/java/com/example/echofind/data/viewmodel/LoginSpotifyViewModel.kt | mutu8 | 854,980,460 | false | {"Kotlin": 99018} | // Archivo: com.example.echofind.data.test.LoginViewModel.kt
package com.example.echofind.data.viewmodel
import android.media.MediaPlayer
import android.util.Base64
import android.util.Log
import androidx.compose.runtime.mutableStateListOf
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.example.echofind.data.model.player.TrackItem
import com.example.echofind.data.service.AuthService
import com.example.echofind.data.service.SpotifyService
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import retrofit2.Retrofit
import retrofit2.converter.gson.GsonConverterFactory
import java.nio.charset.StandardCharsets
class LoginSpotifyViewModel(
private val authViewModel: AuthViewModel ) : ViewModel() {
private val retrofit = Retrofit.Builder()
.baseUrl("https://accounts.spotify.com/")
.addConverterFactory(GsonConverterFactory.create())
.build()
private val authService = retrofit.create(AuthService::class.java)
private var accessToken: String = ""
// Almacenamiento de las pistas en el ViewModel
private val _tracks = mutableStateListOf<TrackItem>()
val tracks: List<TrackItem> = _tracks
fun login(clientId: String, clientSecret: String, callback: (Boolean) -> Unit) {
viewModelScope.launch {
try {
// Codificar clientId y clientSecret en Base64
val credentials = "$clientId:$clientSecret"
val authHeader = "Basic " + Base64.encodeToString(credentials.toByteArray(StandardCharsets.UTF_8), Base64.NO_WRAP)
// Hacer la solicitud de login
val response = authService.login(authorization = authHeader)
accessToken = response.access_token // Guardamos el token
callback(true) // Login exitoso
} catch (e: Exception) {
e.printStackTrace()
callback(false) // Login fallido
}
}
}
fun getToken(): String {
return accessToken
}
// Función para obtener las pistas de una playlist y almacenarlas en el ViewModel
fun getPlaylistTracks(token: String, playlistId: String, callback: () -> Unit) {
viewModelScope.launch {
try {
val spotifyViewModel = SpotifyViewModel()
val playlistTracks = spotifyViewModel.getPlaylistTracks(token, playlistId)
_tracks.clear()
if (playlistTracks != null) {
_tracks.addAll(playlistTracks)
}
callback()
} catch (e: Exception) {
e.printStackTrace()
callback()
}
}
}
// Función para reproducir la vista previa de una pista y cambiar automáticamente al terminar
fun playPreviewTrack(previewUrl: String, onCompletion: () -> Unit): MediaPlayer? {
return try {
val mediaPlayer = MediaPlayer().apply {
setDataSource(previewUrl) // Configura la URL de la vista previa
prepare() // Prepara el reproductor de audio
start() // Reproduce la pista de vista previa
}
mediaPlayer.setOnCompletionListener {
mediaPlayer.release() // Libera el reproductor cuando termine la reproducción
onCompletion() // Ejecutar la acción de reproducción automática al finalizar
}
mediaPlayer // Devolver el MediaPlayer para poder controlarlo más adelante
} catch (e: Exception) {
Log.e("MediaPlayerError", "Error al reproducir la vista previa: ${e.message}")
null // Retorna null si ocurre algún error
}
}
// Función para seleccionar y guardar una canción
fun seleccionarCancion(trackItem: TrackItem) {
// Llamada para guardar la canción en Firestore
authViewModel.guardarCancionSeleccionada(trackItem)
}
// ViewModel interno para Spotify
inner class SpotifyViewModel : ViewModel() {
private val retrofit = Retrofit.Builder()
.baseUrl("https://api.spotify.com/")
.addConverterFactory(GsonConverterFactory.create())
.build()
private val spotifyService = retrofit.create(SpotifyService::class.java)
// Función para obtener las pistas de una lista de reproducción
suspend fun getPlaylistTracks(token: String, playlistId: String): List<TrackItem>? {
return try {
val response = spotifyService.getPlaylistTracks("Bearer $token", playlistId)
response.items.map { it.track }.filter { it.preview_url != null }
} catch (e: Exception) {
e.printStackTrace()
null // Error
}
}
}
}
| 0 | Kotlin | 0 | 0 | ab73f7def6325127cf47abfe6b312b6b15194d19 | 4,869 | EchoFind | MIT License |
app/src/main/java/com/example/echofind/data/viewmodel/LoginSpotifyViewModel.kt | mutu8 | 854,980,460 | false | {"Kotlin": 99018} | // Archivo: com.example.echofind.data.test.LoginViewModel.kt
package com.example.echofind.data.viewmodel
import android.media.MediaPlayer
import android.util.Base64
import android.util.Log
import androidx.compose.runtime.mutableStateListOf
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.example.echofind.data.model.player.TrackItem
import com.example.echofind.data.service.AuthService
import com.example.echofind.data.service.SpotifyService
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import retrofit2.Retrofit
import retrofit2.converter.gson.GsonConverterFactory
import java.nio.charset.StandardCharsets
class LoginSpotifyViewModel(
private val authViewModel: AuthViewModel ) : ViewModel() {
private val retrofit = Retrofit.Builder()
.baseUrl("https://accounts.spotify.com/")
.addConverterFactory(GsonConverterFactory.create())
.build()
private val authService = retrofit.create(AuthService::class.java)
private var accessToken: String = ""
// Almacenamiento de las pistas en el ViewModel
private val _tracks = mutableStateListOf<TrackItem>()
val tracks: List<TrackItem> = _tracks
fun login(clientId: String, clientSecret: String, callback: (Boolean) -> Unit) {
viewModelScope.launch {
try {
// Codificar clientId y clientSecret en Base64
val credentials = "$clientId:$clientSecret"
val authHeader = "Basic " + Base64.encodeToString(credentials.toByteArray(StandardCharsets.UTF_8), Base64.NO_WRAP)
// Hacer la solicitud de login
val response = authService.login(authorization = authHeader)
accessToken = response.access_token // Guardamos el token
callback(true) // Login exitoso
} catch (e: Exception) {
e.printStackTrace()
callback(false) // Login fallido
}
}
}
fun getToken(): String {
return accessToken
}
// Función para obtener las pistas de una playlist y almacenarlas en el ViewModel
fun getPlaylistTracks(token: String, playlistId: String, callback: () -> Unit) {
viewModelScope.launch {
try {
val spotifyViewModel = SpotifyViewModel()
val playlistTracks = spotifyViewModel.getPlaylistTracks(token, playlistId)
_tracks.clear()
if (playlistTracks != null) {
_tracks.addAll(playlistTracks)
}
callback()
} catch (e: Exception) {
e.printStackTrace()
callback()
}
}
}
// Función para reproducir la vista previa de una pista y cambiar automáticamente al terminar
fun playPreviewTrack(previewUrl: String, onCompletion: () -> Unit): MediaPlayer? {
return try {
val mediaPlayer = MediaPlayer().apply {
setDataSource(previewUrl) // Configura la URL de la vista previa
prepare() // Prepara el reproductor de audio
start() // Reproduce la pista de vista previa
}
mediaPlayer.setOnCompletionListener {
mediaPlayer.release() // Libera el reproductor cuando termine la reproducción
onCompletion() // Ejecutar la acción de reproducción automática al finalizar
}
mediaPlayer // Devolver el MediaPlayer para poder controlarlo más adelante
} catch (e: Exception) {
Log.e("MediaPlayerError", "Error al reproducir la vista previa: ${e.message}")
null // Retorna null si ocurre algún error
}
}
// Función para seleccionar y guardar una canción
fun seleccionarCancion(trackItem: TrackItem) {
// Llamada para guardar la canción en Firestore
authViewModel.guardarCancionSeleccionada(trackItem)
}
// ViewModel interno para Spotify
inner class SpotifyViewModel : ViewModel() {
private val retrofit = Retrofit.Builder()
.baseUrl("https://api.spotify.com/")
.addConverterFactory(GsonConverterFactory.create())
.build()
private val spotifyService = retrofit.create(SpotifyService::class.java)
// Función para obtener las pistas de una lista de reproducción
suspend fun getPlaylistTracks(token: String, playlistId: String): List<TrackItem>? {
return try {
val response = spotifyService.getPlaylistTracks("Bearer $token", playlistId)
response.items.map { it.track }.filter { it.preview_url != null }
} catch (e: Exception) {
e.printStackTrace()
null // Error
}
}
}
}
| 0 | Kotlin | 0 | 0 | ab73f7def6325127cf47abfe6b312b6b15194d19 | 4,869 | EchoFind | MIT License |
client/android/div-histogram/src/main/java/com/yandex/div/histogram/metrics/RenderMetrics.kt | divkit | 523,491,444 | false | {"Kotlin": 7327303, "Swift": 5164616, "Svelte": 1148832, "TypeScript": 912803, "Dart": 630920, "Python": 536031, "Java": 507940, "JavaScript": 152546, "CSS": 37870, "HTML": 23434, "C++": 20911, "CMake": 18677, "Shell": 8895, "PEG.js": 7210, "Ruby": 3723, "C": 1425, "Objective-C": 38} | package com.yandex.div.histogram.metrics
import kotlin.math.max
internal class RenderMetrics {
var bindingMs: Long = 0
private set
var rebindingMs: Long = 0
private set
var measureMs: Long = 0
private set
var layoutMs: Long = 0
private set
var drawMs: Long = 0
private set
val totalMs: Long
get() = max(bindingMs, rebindingMs) + measureMs + layoutMs + drawMs
fun binding(duration: Long) {
bindingMs = duration
}
fun rebinding(duration: Long) {
rebindingMs = duration
}
fun addMeasure(duration: Long) {
measureMs += duration
}
fun addLayout(duration: Long) {
layoutMs += duration
}
fun addDraw(duration: Long) {
drawMs += duration
}
fun reset() {
measureMs = 0
layoutMs = 0
drawMs = 0
bindingMs = 0
rebindingMs = 0
}
}
| 5 | Kotlin | 128 | 2,240 | dd102394ed7b240ace9eaef9228567f98e54d9cf | 928 | divkit | Apache License 2.0 |
app/src/main/java/com/assessment/lloyds/ui/details/component/DetailsItemView.kt | somia-gmail | 652,513,300 | false | null | package com.assessment.lloyds.ui.details.component
import android.content.Context
import android.util.AttributeSet
import android.widget.TextView
import com.assessment.lloyds.R
import com.assessment.lloyds.base.view.BaseConstraintLayout
class DetailsItemView : BaseConstraintLayout {
private val textViewLabel: TextView = findViewById(R.id.textViewLabel)
private val textViewValue: TextView = findViewById(R.id.textViewValue)
override val layoutId: Int
get() = R.layout.view_detail_item
constructor(context: Context) : super(context) {
setWidthMatchParent()
}
constructor(context: Context, attrs: AttributeSet) : super(context, attrs) {
setWidthMatchParent()
}
fun bind(model: ActorDetailsModel) {
textViewLabel.text = model.label
textViewValue.text = model.value
}
}
data class ActorDetailsModel(val label: String, val value: String) | 0 | Kotlin | 0 | 0 | 03c717b570a67e65eef6e4323e6fe7ecf238f60c | 917 | Assessment-Harry-Potter | MIT License |
base/base-common-jvm/src/main/java/dev/dexsr/klio/base/theme/ThemeObjectReceiver.kt | flammky | 462,795,948 | false | {"Kotlin": 5222947} | package dev.dexsr.klio.base.theme
interface ThemeObjectReceiver
| 0 | Kotlin | 6 | 56 | 2b8b4affab4306e351cfc8721c15a5bc7ecba908 | 65 | Music-Player | Apache License 2.0 |
app/src/main/java/com/stocksexchange/android/ui/base/fragments/BaseSearchFragment.kt | nscoincommunity | 277,168,471 | true | {"Kotlin": 2814235} | package com.stocksexchange.android.ui.base.fragments
import android.os.Bundle
import android.text.InputType
import android.text.TextWatcher
import android.view.View
import android.view.WindowManager.LayoutParams.SOFT_INPUT_ADJUST_PAN
import android.view.WindowManager.LayoutParams.SOFT_INPUT_ADJUST_UNSPECIFIED
import android.view.inputmethod.EditorInfo
import android.widget.TextView.OnEditorActionListener
import com.stocksexchange.android.theming.ThemingUtil
import com.stocksexchange.android.ui.base.mvp.presenters.BasePresenter
import com.stocksexchange.android.ui.views.toolbars.SearchToolbar
import com.stocksexchange.core.utils.extensions.setSoftInputMode
import com.stocksexchange.core.utils.listeners.adapters.TextWatcherAdapter
/**
* A base fragment that performs a search.
*/
abstract class BaseSearchFragment<T : BaseFragment<*>, P : BasePresenter<*, *>> : BaseFragmentChildFragment<T, P>() {
companion object {
const val KEY_SEARCH_QUERY = "search_query"
}
private var mIsSearchQueryEmpty: Boolean = true
private var mSearchQuery: String = ""
override fun onFetchExtras(extras: Bundle) = with(extras) {
mSearchQuery = getString(KEY_SEARCH_QUERY, "")
mIsSearchQueryEmpty = mSearchQuery.isEmpty()
}
override fun preInit() {
super.preInit()
setSoftInputMode(SOFT_INPUT_ADJUST_PAN)
}
override fun init() {
super.init()
initSearchToolbar()
}
fun getSearchQuery(): String = mSearchQuery
private fun initSearchToolbar() {
with(getSearchToolbar()) {
setOnLeftButtonClickListener {
mPresenter.onNavigateUpPressed()
}
setHintText(getInputHint())
setInputType(getInputType())
addTextWatcher(mSearchQueryTextWatcher)
setOnEditorActionListener(mOnEditorActionListener)
if(mIsSearchQueryEmpty) {
hideClearInputButton(false)
} else {
showClearInputButton(false)
}
setOnClearInputButtonClickListener(mOnClearInputBtnClickListener)
ThemingUtil.Main.searchToolbar(this, getAppTheme())
}
}
private fun showClearInputButton() {
getSearchToolbar().showClearInputButton(true)
}
private fun hideClearInputButton() {
getSearchToolbar().hideClearInputButton(true)
}
private fun showKeyboard(shouldDelay: Boolean) {
getSearchToolbar().showKeyboard(shouldDelay)
}
private fun hideKeyboard() {
getSearchToolbar().hideKeyboard()
}
protected abstract fun performSearch(query: String)
protected abstract fun cancelSearch()
private fun setSearchQuery(query: String) {
getSearchToolbar().setText(query)
}
protected abstract fun getInputHint(): String
protected open fun getInputType(): Int = InputType.TYPE_CLASS_TEXT
protected abstract fun getSearchToolbar(): SearchToolbar
override fun onResume() {
super.onResume()
if(mIsSearchQueryEmpty) {
showKeyboard(true)
} else {
hideKeyboard()
setSearchQuery(mSearchQuery)
}
}
override fun onSelected() {
super.onSelected()
if(isInitialized() && mIsSearchQueryEmpty) {
showKeyboard(false)
}
}
private val mSearchQueryTextWatcher: TextWatcher = object : TextWatcherAdapter {
override fun onTextChanged(text: CharSequence, start: Int, before: Int, count: Int) {
if(text.isNotEmpty()) {
if(mIsSearchQueryEmpty) {
mIsSearchQueryEmpty = false
getSearchToolbar().showClearInputButton(true)
}
} else {
if(!mIsSearchQueryEmpty) {
mIsSearchQueryEmpty = true
getSearchToolbar().hideClearInputButton(true)
}
}
mSearchQuery = text.toString()
performSearch(mSearchQuery)
}
}
private val mOnEditorActionListener: OnEditorActionListener = OnEditorActionListener { _, actionId, _ ->
if(actionId == EditorInfo.IME_ACTION_SEARCH) {
hideKeyboard()
}
true
}
private val mOnClearInputBtnClickListener: ((View) -> Unit) = {
cancelSearch()
setSearchQuery("")
showKeyboard(false)
}
override fun navigateBack(): Boolean {
hideKeyboard()
return super.navigateBack()
}
override fun onRestoreState(savedState: Bundle) {
super.onRestoreState(savedState)
savedState.apply {
mSearchQuery = getString(KEY_SEARCH_QUERY, "")
mIsSearchQueryEmpty = mSearchQuery.isEmpty()
}
}
override fun onSaveState(savedState: Bundle) {
super.onSaveState(savedState)
with(savedState) {
putString(KEY_SEARCH_QUERY, mSearchQuery)
}
}
override fun onRecycle() {
super.onRecycle()
setSoftInputMode(SOFT_INPUT_ADJUST_UNSPECIFIED)
getSearchToolbar().recycle()
}
} | 0 | null | 0 | 0 | 52766afab4f96506a2d9ed34bf3564b6de7af8c3 | 5,197 | Android-app | MIT License |
common/uiKitComponents/src/main/kotlin/odoo/miem/android/common/uiKitComponents/screenTemplates/recruitmentLike/components/screen/RecruitmentLikeScreenSearch.kt | 19111OdooApp | 546,191,502 | false | {"Kotlin": 889625} | package odoo.miem.android.common.uiKitComponents.screenTemplates.recruitmentLike.components.screen
import androidx.annotation.StringRes
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Column
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.saveable.rememberSaveable
import androidx.compose.runtime.setValue
import androidx.compose.ui.Modifier
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.text.input.TextFieldValue
import com.mxalbert.sharedelements.FadeMode
import com.mxalbert.sharedelements.MaterialArcMotionFactory
import com.mxalbert.sharedelements.SharedElement
import com.mxalbert.sharedelements.SharedElementsTransitionSpec
import odoo.miem.android.common.uiKitComponents.R
import odoo.miem.android.common.uiKitComponents.textfields.SearchTextField
import odoo.miem.android.common.uiKitComponents.utils.SharedElementConstants
@Composable
fun RecruitmentLikeScreenSearch(
onSearchBarClicked: () -> Unit,
@StringRes searchHintRes: Int,
) = Column {
var searchInput by rememberSaveable(stateSaver = TextFieldValue.Saver) {
mutableStateOf(TextFieldValue())
}
SharedElement(
key = stringResource(R.string.recruitment_search_bar_key),
screenKey = stringResource(R.string.recruitment_search_screen_key),
transitionSpec = SharedElementsTransitionSpec(
pathMotionFactory = MaterialArcMotionFactory,
durationMillis = SharedElementConstants.transitionDurationMills,
fadeMode = FadeMode.Through,
fadeProgressThresholds = SharedElementConstants.progressThreshold
)
) {
SearchTextField(
value = searchInput,
onValueChange = { searchInput = it },
enabled = false,
modifier = Modifier.clickable { onSearchBarClicked() },
stringRes = searchHintRes,
)
}
}
| 0 | Kotlin | 1 | 5 | e107fcbb8db2d179d40b5c1747051d2cb75e58c6 | 2,021 | OdooApp-Android | Apache License 2.0 |
src/commonJvmAndroidMain/kotlin/matt/time/dur/dur.kt | mgroth0 | 532,381,128 | false | {"Kotlin": 20035} |
package matt.time.dur
import kotlin.time.Duration
@Suppress("NOTHING_TO_INLINE")
actual inline fun sleep(duration: Duration) = Thread.sleep(duration.inWholeMilliseconds)
| 0 | Kotlin | 0 | 0 | dd0b7a48e865fdac1a1ed8bf117bb8a209259097 | 178 | time | MIT License |
soapui-streams/src/main/kotlin/eu/k5/soapui/streams/model/test/SuuTestStepListener.kt | denninger-eu | 244,302,123 | false | null | package eu.k5.soapui.streams.model.test
import eu.k5.soapui.streams.listener.VisitResult
interface SuuTestStepListener {
fun transfer(step: SuuTestStepPropertyTransfers)
fun enterRestRequest(step: SuuTestStepRestRequest): VisitResult
fun exitRestRequest(step: SuuTestStepRestRequest)
fun enterWsdlRequest(step: SuuTestStepWsdlRequest): VisitResult
fun exitWsdlRequest(step: SuuTestStepWsdlRequest)
fun properties(step: SuuTestStepProperties)
fun delay(step: SuuTestStepDelay)
fun script(step: SuuTestStepScript)
fun createAssertionListener(): SuuAssertionListener
companion object {
val NO_OP = object : SuuTestStepListener {
override fun exitWsdlRequest(step: SuuTestStepWsdlRequest) {
}
override fun enterWsdlRequest(step: SuuTestStepWsdlRequest): VisitResult {
return VisitResult.TERMINATE
}
override fun script(step: SuuTestStepScript) {
}
override fun properties(step: SuuTestStepProperties) {
}
override fun exitRestRequest(step: SuuTestStepRestRequest) {
}
override fun createAssertionListener(): SuuAssertionListener {
return SuuAssertionListener.NO_OP
}
override fun enterRestRequest(step: SuuTestStepRestRequest): VisitResult {
return VisitResult.TERMINATE
}
override fun transfer(step: SuuTestStepPropertyTransfers) {
}
override fun delay(step: SuuTestStepDelay) {
}
}
}
} | 5 | Kotlin | 0 | 0 | 665e54e4ac65d6c7e9805bb1b44f30f9ec702ce3 | 1,629 | soapui-utils | Apache License 2.0 |
src/main/kotlin/pw/dotdash/township/plugin/permission/PermissionRegistryModule.kt | Arvenwood | 239,849,867 | false | null | package pw.dotdash.township.plugin.permission
import pw.dotdash.township.api.permission.Permission
import pw.dotdash.township.plugin.permission.util.AbstractPrefixCheckRegistryModule
class PermissionRegistryModule(
private val claimPermissions: ClaimPermissionRegistryModule,
private val townPermissions: TownPermissionRegistryModule
) : AbstractPrefixCheckRegistryModule<Permission>("township") {
override fun registerDefaults() {
this.claimPermissions.all.forEach(this::register)
this.townPermissions.all.forEach(this::register)
}
} | 1 | null | 1 | 2 | bb476a9bbd8659f6474316caee22be73dc1d5ba2 | 569 | Township | MIT License |
restring/src/test/java/dev/b3nedikt/restring/internal/repository/model/StringResourceTest.kt | B3nedikt | 202,513,039 | false | {"Kotlin": 109430, "Java": 7950} | package dev.b3nedikt.restring.internal.repository.model
import dev.b3nedikt.restring.repository.STRING_VALUE
import dev.b3nedikt.restring.repository.TEXT_VALUE
import org.amshove.kluent.shouldBeEqualTo
import org.junit.Test
import org.junit.runner.RunWith
import org.robolectric.RobolectricTestRunner
@RunWith(RobolectricTestRunner::class)
class StringTest {
@Test
fun jsonConversionWorksForStringResources() {
val stringResource = StringResource(STRING_VALUE, isText = false)
StringResource.fromJson(stringResource.toJson()) shouldBeEqualTo stringResource
}
@Test
fun jsonConversionWorksForTextResources() {
val textResource = StringResource(TEXT_VALUE, isText = true)
StringResource.fromJson(textResource.toJson()).value.toString() shouldBeEqualTo
textResource.value.toString()
}
} | 1 | Kotlin | 30 | 312 | 3b7e70408d4c735b52096dca021838fb9710ba95 | 861 | restring | Apache License 2.0 |
app/src/main/java/com/github/hadilq/movieschallenge/di/PopularMoviesActivityModule.kt | hadilq | 177,737,157 | false | {"Gradle Kotlin DSL": 4, "Java Properties": 1, "Shell": 1, "Ignore List": 6, "Batchfile": 1, "Markdown": 1, "Gradle": 3, "Kotlin": 49, "INI": 1, "Proguard": 3, "XML": 24, "Java": 4, "JSON": 1, "YAML": 1} | /***
* Copyright 2019 Hadi Lashkari Ghouchani
*
* 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.github.hadilq.movieschallenge.di
import com.github.hadilq.movieschallenge.presentation.popular.MoviesScope
import com.github.hadilq.movieschallenge.presentation.popular.PopularMoviesActivity
import com.github.hadilq.movieschallenge.presentation.popular.PopularMoviesAssistedModule
import dagger.Module
import dagger.android.ContributesAndroidInjector
@Module
abstract class PopularMoviesActivityModule {
@MoviesScope
@ContributesAndroidInjector(modules = [PopularMoviesAssistedModule::class])
internal abstract fun get(): PopularMoviesActivity
} | 1 | null | 1 | 1 | 882aec04a7fe817c29becdf0c94531412b674f94 | 1,182 | MoviesChallenge | Apache License 2.0 |
movie/src/main/java/com/ruzhan/movie/video/WebVideoActivity.kt | ckrgithub | 150,102,569 | false | null | package com.ruzhan.movie.video
import android.annotation.SuppressLint
import android.app.Activity
import android.content.Intent
import android.graphics.PixelFormat
import android.os.Bundle
import android.support.v7.app.AppCompatActivity
import android.view.View
import android.view.Window
import android.view.WindowManager
import com.ruzhan.movie.R
import com.tencent.smtt.sdk.WebChromeClient
import com.tencent.smtt.sdk.WebView
import com.tencent.smtt.sdk.WebViewClient
import kotlinx.android.synthetic.main.activity_web_video.*
/**
* Created by ruzhan123 on 2018/7/5.
*/
class WebVideoActivity : AppCompatActivity() {
companion object {
private const val VIDEO_URL: String = "URL"
private const val MAX_PROGRESS = 80
@JvmStatic
fun launch(activity: Activity, url: String) {
val intent = Intent(activity, WebVideoActivity::class.java)
intent.putExtra(VIDEO_URL, url)
activity.startActivity(intent)
}
}
@SuppressLint("SetJavaScriptEnabled")
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
requestWindowFeature(Window.FEATURE_NO_TITLE)
window.setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN)
window.setFormat(PixelFormat.TRANSLUCENT)
setContentView(R.layout.activity_web_video)
val webSettings = web_view.settings
webSettings.javaScriptEnabled = true
webSettings.domStorageEnabled = true
web_view.webChromeClient = object : WebChromeClient() {
override fun onProgressChanged(view: WebView, newProgress: Int) {
if (load_progress.visibility != View.VISIBLE && newProgress < MAX_PROGRESS) {
load_progress.visibility = View.VISIBLE
} else if (newProgress > MAX_PROGRESS) {
load_progress.visibility = View.INVISIBLE
}
}
}
web_view.webViewClient = WebViewClient()
val url = intent.getStringExtra(VIDEO_URL)
web_view.loadUrl(url)
}
override fun onResume() {
web_view.onResume()
super.onResume()
}
override fun onPause() {
web_view.onPause()
super.onPause()
}
override fun onDestroy() {
web_view.destroy()
super.onDestroy()
}
} | 1 | null | 1 | 1 | e73bcaf999e3de04905e781004f02ede6d85eaea | 2,424 | Lion | Apache License 2.0 |
app/src/main/java/com/bendaniel10/weatherlite/service/WeatherLiteService.kt | bendaniel10 | 95,213,073 | false | {"Gradle": 3, "Java Properties": 2, "Shell": 1, "Text": 1, "Ignore List": 2, "Batchfile": 1, "Markdown": 1, "Proguard": 1, "Java": 1, "XML": 17, "Kotlin": 12} | package com.bendaniel10.weatherlite.service
import android.graphics.Bitmap
import com.bendaniel10.weatherlite.webservice.WeatherResponse
/**
* Created by bendaniel on 23/06/2017.
*/
interface WeatherLiteService {
fun getWeatherForcast(latitude: Double, longitude: Double) : WeatherResponse?
fun getWeatherConditionBitmapForIcon(icon: String?): Bitmap?
} | 0 | Kotlin | 0 | 4 | f41cb73a232d19aef5c25c657a7a27a8a62eeeec | 366 | weather-lite-kotlin | Apache License 2.0 |
jtransc-core/src/com/jtransc/ast/treeshaking/TemplateReferences.kt | dsp-omen | 68,166,383 | true | {"INI": 6, "YAML": 2, "Batchfile": 6, "Shell": 4, "Text": 7, "Gradle": 22, "Markdown": 9, "EditorConfig": 1, "Ignore List": 22, "Java": 934, "Maven POM": 4, "HTML": 8, "Java Properties": 8, "Kotlin": 172, "Haxe": 33, "C++": 1, "JavaScript": 11, "SVG": 1, "JAR Manifest": 1, "XML": 8, "C": 1} | package com.jtransc.ast.treeshaking
import com.jtransc.ast.AstProgram
import com.jtransc.ast.template.CommonTagHandler
import com.jtransc.template.Minitemplate
fun GetTemplateReferences(program: AstProgram, templateStr: String): List<CommonTagHandler.Result> {
val refs = arrayListOf<CommonTagHandler.Result>()
val template = Minitemplate(templateStr, Minitemplate.Config(
extraTags = listOf(
Minitemplate.Tag(
":programref:", setOf(), null,
aliases = listOf(
//"sinit", "constructor", "smethod", "method", "sfield", "field", "class",
"SINIT", "CONSTRUCTOR", "SMETHOD", "METHOD", "SFIELD", "FIELD", "CLASS"
)
) {
val tag = it.first().token.name
val desc = it.first().token.content
val ref = CommonTagHandler.getRef(program, tag, desc, hashMapOf())
refs += ref
Minitemplate.BlockNode.TEXT("")
}
),
extraFilters = listOf(
)
))
template(hashMapOf<String, Any?>())
return refs
} | 0 | Java | 0 | 1 | b80145585ad02e5201a0615bfee7f6843d2eea3c | 942 | jtransc | Apache License 2.0 |
platform/remote-driver/test-sdk/src/com/intellij/driver/sdk/ui/Locators.kt | JetBrains | 2,489,216 | false | null | package com.intellij.driver.sdk.ui
import java.awt.Component
object Locators {
const val ATTR_ACCESSIBLE_NAME = "@accessiblename"
const val ATTR_CLASS = "@class"
const val ATTR_TITLE = "@title"
const val ATTR_VISIBLE_TEXT = "@visible_text"
const val ATTR_TOOLTIP = "@tooltiptext"
const val ATTR_JAVA_CLASS = "@javaclass"
fun byAccessibleName(name: String): String = byAttribute(ATTR_ACCESSIBLE_NAME, name)
fun byAccessibleNameContains(name: String): String = byAttributeContains(ATTR_ACCESSIBLE_NAME, name)
fun byVisibleText(text: String): String = byAttribute(ATTR_VISIBLE_TEXT, text)
fun byVisibleTextContains(text: String): String = byAttributeContains(ATTR_VISIBLE_TEXT, text)
fun byTitle(title: String): String = byAttribute(ATTR_TITLE, title)
fun byTitleContains(title: String): String = byAttributeContains(ATTR_TITLE, title)
fun byClass(cls: String): String = byAttribute(ATTR_CLASS, cls)
fun byTooltip(tooltip: String): String = byAttribute(ATTR_TOOLTIP, tooltip)
fun byClassAndAccessibleName(cls: String, accessibleName: String) =
byAttributes(ATTR_CLASS to cls, ATTR_ACCESSIBLE_NAME to accessibleName)
fun <T : Component> byType(type: Class<T>) = byType(type.name)
fun byType(type: String) = """//div[@javaclass="$type" or contains(@classhierarchy, "$type ") or contains(@classhierarchy, " $type ")]"""
fun byJavaClassContains(type: String) = byAttributeContains(ATTR_JAVA_CLASS, type)
fun byAttribute(name: String, value: String) = byAttributes(name to value)
fun byAttributes(attr: Pair<String, String>, vararg attrs: Pair<String, String>) =
"//div[${listOf(attr, *attrs).joinToString(" and ") { "${it.first}='${it.second}'" }}]"
fun byAttributeContains(name: String, value: String) = "//div[contains($name,'$value')]"
fun componentWithChild(componentLocator: String, childLocator: String) = "${componentLocator}[.${childLocator}]"
} | 284 | null | 5162 | 16,707 | def6433a5dd9f0a984cbc6e2835d27c97f2cb5f0 | 1,901 | intellij-community | Apache License 2.0 |
platform/remote-driver/test-sdk/src/com/intellij/driver/sdk/ui/Locators.kt | JetBrains | 2,489,216 | false | null | package com.intellij.driver.sdk.ui
import java.awt.Component
object Locators {
const val ATTR_ACCESSIBLE_NAME = "@accessiblename"
const val ATTR_CLASS = "@class"
const val ATTR_TITLE = "@title"
const val ATTR_VISIBLE_TEXT = "@visible_text"
const val ATTR_TOOLTIP = "@tooltiptext"
const val ATTR_JAVA_CLASS = "@javaclass"
fun byAccessibleName(name: String): String = byAttribute(ATTR_ACCESSIBLE_NAME, name)
fun byAccessibleNameContains(name: String): String = byAttributeContains(ATTR_ACCESSIBLE_NAME, name)
fun byVisibleText(text: String): String = byAttribute(ATTR_VISIBLE_TEXT, text)
fun byVisibleTextContains(text: String): String = byAttributeContains(ATTR_VISIBLE_TEXT, text)
fun byTitle(title: String): String = byAttribute(ATTR_TITLE, title)
fun byTitleContains(title: String): String = byAttributeContains(ATTR_TITLE, title)
fun byClass(cls: String): String = byAttribute(ATTR_CLASS, cls)
fun byTooltip(tooltip: String): String = byAttribute(ATTR_TOOLTIP, tooltip)
fun byClassAndAccessibleName(cls: String, accessibleName: String) =
byAttributes(ATTR_CLASS to cls, ATTR_ACCESSIBLE_NAME to accessibleName)
fun <T : Component> byType(type: Class<T>) = byType(type.name)
fun byType(type: String) = """//div[@javaclass="$type" or contains(@classhierarchy, "$type ") or contains(@classhierarchy, " $type ")]"""
fun byJavaClassContains(type: String) = byAttributeContains(ATTR_JAVA_CLASS, type)
fun byAttribute(name: String, value: String) = byAttributes(name to value)
fun byAttributes(attr: Pair<String, String>, vararg attrs: Pair<String, String>) =
"//div[${listOf(attr, *attrs).joinToString(" and ") { "${it.first}='${it.second}'" }}]"
fun byAttributeContains(name: String, value: String) = "//div[contains($name,'$value')]"
fun componentWithChild(componentLocator: String, childLocator: String) = "${componentLocator}[.${childLocator}]"
} | 284 | null | 5162 | 16,707 | def6433a5dd9f0a984cbc6e2835d27c97f2cb5f0 | 1,901 | intellij-community | Apache License 2.0 |
applications/webapp/src/main/kotlin/hu/deepdata/tenderbase/webapp/ctrl/OrganizationListController.kt | deepdata-ltd | 126,977,680 | false | {"Java": 248439, "Kotlin": 216969, "HTML": 34826, "Shell": 2255, "JavaScript": 1755} | package hu.deepdata.tenderbase.webapp.ctrl
import hu.deepdata.tenderbase.webapp.model.*
import hu.deepdata.tenderbase.webapp.svc.*
import org.springframework.beans.factory.annotation.*
import org.springframework.data.domain.*
import org.springframework.data.web.*
import org.springframework.stereotype.*
import org.springframework.web.bind.annotation.*
import org.springframework.web.servlet.*
/**
* @author <NAME>
*/
@Controller
@RequestMapping("/organizations/")
class OrganizationListController {
@Autowired
var counts: IndexServce? = null
@Autowired
var service: OrganizationListService? = null
@GetMapping("/")
fun list(@ModelAttribute filters: OrganizationFilters, @PageableDefault(size = 10) pageable: Pageable): ModelAndView {
val page = service!!.queryOrganizations(filters, pageable)
return ModelAndView("organization-list", mapOf(
"filters" to filters,
"organizationCount" to counts?.organizationCount(),
"organizations" to page,
"pageLinkPrefix" to "/organizations/?$filters&page="
))
}
} | 1 | Java | 1 | 1 | c680dcce5d4fdeb337516a3d88713aa30dfa56dd | 1,036 | tenderbase | Apache License 2.0 |
app/src/main/java/app/odapplications/bitstashwallet/modules/ratelist/RateListView.kt | bitstashco | 220,133,996 | false | null | package app.odapplications.bitstashwallet.modules.ratelist
import androidx.lifecycle.MutableLiveData
import app.odapplications.bitstashwallet.SingleLiveEvent
import java.util.*
class RateListView : RateListModule.IView {
var currentDate = MutableLiveData<Date>()
val reloadLiveEvent = SingleLiveEvent<Void>()
override fun showCurrentDate(currentDate: Date) {
this.currentDate.postValue(currentDate)
}
override fun reload() {
reloadLiveEvent.call()
}
}
| 3 | null | 3 | 11 | 64c242dbbcb6b4df475a608b1edb43f87e5091fd | 498 | BitStash-Android-Wallet | MIT License |
app/src/main/java/app/odapplications/bitstashwallet/modules/ratelist/RateListView.kt | bitstashco | 220,133,996 | false | null | package app.odapplications.bitstashwallet.modules.ratelist
import androidx.lifecycle.MutableLiveData
import app.odapplications.bitstashwallet.SingleLiveEvent
import java.util.*
class RateListView : RateListModule.IView {
var currentDate = MutableLiveData<Date>()
val reloadLiveEvent = SingleLiveEvent<Void>()
override fun showCurrentDate(currentDate: Date) {
this.currentDate.postValue(currentDate)
}
override fun reload() {
reloadLiveEvent.call()
}
}
| 3 | null | 3 | 11 | 64c242dbbcb6b4df475a608b1edb43f87e5091fd | 498 | BitStash-Android-Wallet | MIT License |
core/src/main/kotlin/info/laht/threekt/lights/Light.kt | markaren | 196,544,572 | false | null | package info.laht.threekt.lights
import info.laht.threekt.core.Object3D
import info.laht.threekt.core.Object3DImpl
import info.laht.threekt.math.Color
import info.laht.threekt.math.SphericalHarmonics3
import kotlin.math.PI
private const val DEFAULT_INTENSITY = 1f
interface LightWithShadow {
val shadow: LightShadow
}
interface LightWithTarget {
val target: Object3D
}
sealed class Light(
color: Color? = null,
intensity: Number? = null
) : Object3DImpl() {
val color = color ?: Color(0xffffff)
var intensity = intensity?.toFloat() ?: DEFAULT_INTENSITY
init {
receiveShadow = false
}
fun copy(source: Light): Light {
super.copy(source, true)
color.copy(source.color)
this.intensity = source.intensity
return this
}
}
class AmbientLight(
color: Color? = null,
intensity: Number? = null
) : Light(color, intensity) {
constructor(color: Int, intensity: Number? = null) : this(Color(color), intensity)
init {
castShadow = false
}
}
internal class LightProbe(
var sh: SphericalHarmonics3 = SphericalHarmonics3(),
intensity: Number? = null
) : Light(Color(), intensity) {
fun copy(source: LightProbe): LightProbe {
this.sh.copy(source.sh)
this.intensity = source.intensity
return this
}
}
class DirectionalLight(
color: Color? = null,
intensity: Number? = null
) : Light(color, intensity), LightWithShadow, LightWithTarget {
constructor(color: Int, intensity: Number? = null) : this(Color(color), intensity)
override var target = Object3DImpl()
override var shadow = DirectionalLightShadow()
init {
this.position.copy(Object3D.defaultUp)
this.updateMatrix()
}
}
class PointLight(
color: Color? = null,
intensity: Number? = null,
distance: Number? = null,
decay: Number? = null
) : Light(color, intensity), LightWithShadow {
var distance = distance?.toFloat() ?: 0f
var decay = decay?.toFloat() ?: 1f
override val shadow = PointLightShadow()
constructor(
color: Int,
intensity: Number? = null,
distance: Number? = null,
decay: Number? = null
) : this(Color(color), intensity, distance, decay)
fun copy(source: PointLight): PointLight {
super.copy(source)
this.distance = source.distance
this.decay = source.decay
this.shadow.copy(source.shadow)
return this
}
}
class RectAreaLight(
color: Color? = null,
intensity: Number? = null,
width: Number? = null,
height: Number? = null
) : Light(color, intensity) {
var width = width?.toFloat() ?: 10f
var height = height?.toFloat() ?: 10f
constructor(
color: Int,
intensity: Number? = null,
width: Number? = null,
height: Number? = null
) : this(Color(color), intensity, width, height)
fun copy(source: RectAreaLight): RectAreaLight {
super.copy(source)
this.width = source.width
this.height = source.height
return this
}
}
class SpotLight(
color: Color? = null,
intensity: Number? = null,
distance: Number? = null,
angle: Number? = null,
penumbra: Number? = null,
decay: Number? = null
) : Light(color, intensity), LightWithShadow, LightWithTarget {
var distance = distance?.toFloat() ?: 0f
var angle = angle?.toFloat() ?: (PI / 3).toFloat()
var penumbra = penumbra?.toFloat() ?: 0f
var decay = decay?.toFloat() ?: 1f
override var target = Object3DImpl()
override var shadow = SpotLightShadow()
constructor(color: Int, intensity: Number? = null,
distance: Number? = null,
angle: Number? = null,
penumbra: Number? = null,
decay: Number? = null
) : this(Color(color), intensity, distance, angle, penumbra, decay)
var power: Float
get() {
return intensity * PI.toFloat()
}
set(value) {
this.intensity = value / PI.toFloat()
}
constructor(color: Int, intensity: Number? = null) : this(Color(color), intensity)
init {
position.copy(Object3D.defaultUp)
updateMatrix()
}
fun copy(source: SpotLight): SpotLight {
super.copy(source)
this.distance = source.distance
this.angle = source.angle
this.penumbra = source.penumbra
this.decay = source.decay
this.target = source.target.clone()
this.shadow = source.shadow.clone()
return this
}
}
class HemisphereLight(
val skyColor: Color,
val groundColor: Color,
intensity: Number? = null
) : Light(skyColor, intensity) {
constructor(skyColor: Int,
groundColor: Int,
intensity: Number? = null
) : this(Color(skyColor), Color(groundColor), intensity)
fun copy(source: HemisphereLight): HemisphereLight {
super.copy(source)
groundColor.copy(source.groundColor)
return this
}
}
| 7 | null | 14 | 187 | 8dc6186d777182da6831cf1c79f39ee2d5960cd7 | 5,225 | three.kt | MIT License |
download/src/main/java/com/yww/download/IDownload.kt | wavening | 180,977,597 | false | null | package com.yww.download
/**
* @Author WAVENING
* @Date 2019/3/21-15:18
*/
interface IDownload {
fun bindDownloadTool(tool: Any)
} | 1 | null | 1 | 1 | 964e3eaa52e2aefdc10b883394910e61fdb2e467 | 144 | KotlinLibs | Apache License 2.0 |
App/Hero/app/src/main/java/work/onss/hero/data/repository/score/ScoreDao.kt | China-1977 | 459,170,680 | false | {"Java": 271006, "JavaScript": 130372, "TypeScript": 34036, "Kotlin": 21587, "Groovy": 5463, "Shell": 961, "Less": 45} | package work.onss.hero.data.repository.score
import androidx.paging.PagingSource
import androidx.room.Dao
import androidx.room.Insert
import androidx.room.OnConflictStrategy
import androidx.room.Query
@Dao
interface ScoreDao {
@Query("SELECT * FROM score")
fun getAll(): PagingSource<Int, Score>
@Insert(onConflict = OnConflictStrategy.REPLACE)
suspend fun insert(scores: List<Score>)
@Query("DELETE FROM score")
suspend fun deleteAll()
} | 1 | null | 1 | 1 | 6030664843ba65e00cf85aa5222acd85ae7cf3cb | 467 | merchant | Apache License 2.0 |
app/src/main/java/com/github/braillesystems/learnbraille/ui/views/HelpView.kt | braille-systems | 246,795,546 | false | null | package com.github.braillesystems.learnbraille.ui.views
import android.content.Context
import android.util.AttributeSet
import android.util.TypedValue
import android.widget.LinearLayout
import android.widget.TextView
import androidx.core.text.parseAsHtml
import com.github.braillesystems.learnbraille.R
import com.github.braillesystems.learnbraille.data.repository.PreferenceRepository
import com.github.braillesystems.learnbraille.utils.extendedTextSize
import org.koin.core.KoinComponent
import org.koin.core.inject
class HelpView : LinearLayout, KoinComponent {
private val preferenceRepository: PreferenceRepository by inject()
constructor(context: Context) : super(context)
constructor(context: Context, attrSet: AttributeSet) : super(context, attrSet)
constructor(
context: Context, attrSet: AttributeSet, defStyleAttr: Int
) : super(
context, attrSet, defStyleAttr
)
fun setSeparatedText(text: String) {
val helpItems = text.split('&')
helpItems.forEach { helpItem ->
val textView = TextView(context).apply {
setPaddingRelative(30, 0, 20, 0)
setTextSize(
TypedValue.COMPLEX_UNIT_SP,
if (preferenceRepository.extendedAccessibilityEnabled) {
context.extendedTextSize
} else {
context.resources.getDimension(R.dimen.help_message_text_size)
}
)
this.text = helpItem.parseAsHtml()
}
addView(textView)
}
}
}
| 35 | Kotlin | 3 | 9 | e7e41e88d814aa4f7dd118ed023cdd6f955d53e5 | 1,616 | learn-braille | Apache License 2.0 |
app/src/sharedTest/kotlin/de/developercity/arcanosradio/BaseTest.kt | fibelatti | 156,989,942 | false | null | package de.developercity.arcanosradio
abstract class BaseTest
| 0 | Kotlin | 1 | 1 | b594c10821ce08117f04c2811dbe8e900cbd0d6f | 63 | arcanos-radio-kotlin | MIT License |
weatherapp/app/src/androidTest/java/fr/ekito/myweatherapp/room_test_modules.kt | FlorentDambreville | 157,077,084 | false | {"Kotlin": 88080} | //package fr.ekito.myweatherapp
//
//import android.arch.persistence.room.Room
//import fr.ekito.myweatherapp.data.datasource.room.WeatherDatabase
//import org.koin.dsl.module.applicationContext
//
///**
// * In-Memory Room Database definition
// */
//val roomTestModule = applicationContext {
// bean {
// Room.inMemoryDatabaseBuilder(get(), WeatherDatabase::class.java)
// .allowMainThreadQueries()
// .build()
// }
//} | 0 | Kotlin | 0 | 0 | 062f5f03357fedf1c8ddeb77062238f4db549132 | 456 | mvvm-live-data | Creative Commons Attribution 4.0 International |
app/src/main/java/ru/reminder/createreminder/domain/di/DomainModule.kt | AmV1to | 712,265,749 | false | {"Kotlin": 114083} | package ru.reminder.createreminder.domain.di
import org.koin.dsl.module
import ru.reminder.core.ManageResources
import ru.reminder.createreminder.domain.AlarmWrapper
import ru.reminder.createreminder.domain.CreateInteractor
import ru.reminder.createreminder.domain.HandleDomainException
import ru.reminder.createreminder.domain.HandleTime
val domainModule = module {
factory<CreateInteractor> {
CreateInteractor.Base(
handleTime = get(),
alarm = get(),
manageResources = get(),
handleException = HandleDomainException(get()),
repository = get(),
)
}
factory<ManageResources> {
ManageResources.Base(get())
}
factory<HandleTime.Mutable> {
HandleTime.Base()
}
factory<AlarmWrapper> {
AlarmWrapper.Base(get())
}
}
| 0 | Kotlin | 0 | 0 | 9debfa4a6fdddb241ee1cbacf1e9e255ae4f7ac1 | 848 | Reminder | Apache License 2.0 |
src/main/kotlin/org/wagham/db/scopes/KabotDBServerConfigScope.kt | kaironbot | 540,862,397 | false | {"Kotlin": 202544} | package org.wagham.db.scopes
import com.mongodb.client.model.UpdateOptions
import org.litote.kmongo.coroutine.CoroutineCollection
import org.litote.kmongo.eq
import org.wagham.db.KabotMultiDBClient
import org.wagham.db.enums.CollectionNames
import org.wagham.db.exceptions.ResourceNotFoundException
import org.wagham.db.models.NyxConfig
import org.wagham.db.models.ServerConfig
import org.wagham.db.utils.isSuccessful
class KabotDBServerConfigScope(
override val client: KabotMultiDBClient
) : KabotDBScope<ServerConfig> {
override val collectionName = CollectionNames.SERVER_CONFIG.stringValue
override fun getMainCollection(guildId: String): CoroutineCollection<ServerConfig> =
client.getGuildDb(guildId).getCollection(collectionName)
/**
* Retrieves the [ServerConfig] for the guild passed as parameter.
*
* @param guildId the id of the guild for which to get the config
* @return a [ServerConfig]
* @throws ResourceNotFoundException if no config was defined
*/
suspend fun getGuildConfig(guildId: String): ServerConfig =
getMainCollection(guildId)
.findOne(ServerConfig::id eq "serverConfig")
?: throw ResourceNotFoundException("ServerConfig", "serverConfig")
/**
* Updates the current [ServerConfig] for a guild or creates it if it does not exist.
*
* @param guildId the id of the guild.
* @param config the updated [ServerConfig].
* @return true if the operation was successful, false otherwise
*/
suspend fun setGuildConfig(guildId: String, config: ServerConfig) =
getMainCollection(guildId).updateOne(
ServerConfig::id eq "serverConfig",
config.copy(id = "serverConfig"),
UpdateOptions().upsert(true)
).isSuccessful()
/**
* Retrieves the [NyxConfig] for the guild passed as parameter.
*
* @param guildId the id of the guild.
* @return a [NyxConfig]
* @throws ResourceNotFoundException if no config was defined
*/
suspend fun getNyxConfig(guildId: String): NyxConfig =
client.getGuildDb(guildId).getCollection<NyxConfig>(collectionName)
.findOne(NyxConfig::id eq "nyxConfig")
?: throw ResourceNotFoundException("ServerConfig", "nyxConfig")
/**
* Updates the current [NyxConfig] for a guild or creates it if it does not exist.
*
* @param guildId the id of the guild.
* @param config the updated [NyxConfig].
* @return true if the operation was successful, false otherwise
*/
suspend fun setNyxConfig(guildId: String, config: NyxConfig): Boolean =
client.getGuildDb(guildId).getCollection<NyxConfig>(collectionName)
.updateOne(
NyxConfig::id eq "nyxConfig",
config.copy(id = "nyxConfig"),
UpdateOptions().upsert(true)
).isSuccessful()
} | 1 | Kotlin | 0 | 0 | 34b31d141db7510a5d73b80ed2d41d36ec211d0c | 2,918 | kabot-db-connector | MIT License |
navigator/src/main/java/com/depromeet/threedays/navigator/HabitUpdateNavigator.kt | depromeet12th | 548,194,728 | false | null | package com.depromeet.threedays.navigator
interface HabitUpdateNavigator : Navigator
| 0 | Kotlin | 1 | 15 | 1cc08fcf2b038924ab0fe5feaaff548974f40f4d | 86 | three-days-android | MIT License |
plugins/github/src/org/jetbrains/plugins/github/pullrequest/ui/toolwindow/GHRepositoryConnectionManager.kt | bbz525 | 247,478,033 | true | null | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package org.jetbrains.plugins.github.pullrequest.ui.toolwindow
import git4idea.remote.hosting.HostedGitRepositoryConnectionManager
import kotlinx.coroutines.*
import kotlinx.coroutines.flow.*
import org.jetbrains.plugins.github.api.GHRepositoryConnection
import org.jetbrains.plugins.github.authentication.accounts.GHAccountManager
import org.jetbrains.plugins.github.authentication.accounts.GithubAccount
import org.jetbrains.plugins.github.pullrequest.config.GithubPullRequestsProjectUISettings
import org.jetbrains.plugins.github.util.GHGitRepositoryMapping
import org.jetbrains.plugins.github.util.GHHostedRepositoriesManager
internal class GHRepositoryConnectionManager(scope: CoroutineScope,
private val repositoriesManager: GHHostedRepositoriesManager,
private val accountManager: GHAccountManager,
private val settings: GithubPullRequestsProjectUISettings)
: HostedGitRepositoryConnectionManager<GHGitRepositoryMapping, GithubAccount, GHRepositoryConnection> {
private val connectionRequestsFlow = MutableSharedFlow<Pair<GHGitRepositoryMapping, GithubAccount>?>()
override val state by lazy {
connectionRequestsFlow
.handleConnectionRequest()
.stateIn(scope, SharingStarted.Eagerly, null)
}
private fun Flow<Pair<GHGitRepositoryMapping, GithubAccount>?>.handleConnectionRequest(): Flow<GHRepositoryConnection?> =
channelFlow {
var connection: GHRepositoryConnection? = null
distinctUntilChanged().collectLatest { request ->
try {
val (repo, account) = request ?: throw CancellationException()
combine(repositoriesManager.knownRepositoriesState, accountManager.accountsState) { repositories, accounts ->
if (!repositories.contains(repo)) {
throw CancellationException()
}
if (!accounts.contains(account)) {
throw CancellationException()
}
}.collectLatest {
coroutineScope {
accountManager.getCredentialsState(this, account).collectLatest { token ->
if (token == null) {
throw CancellationException()
}
else {
val currentConnection = connection
if (currentConnection != null && currentConnection.repo == repo && currentConnection.account == account) {
currentConnection.token = token
}
else {
connection = GHRepositoryConnection(repo, account, token)
}
send(connection)
withContext(Dispatchers.Main) {
settings.selectedRepoAndAccount = repo to account
}
}
}
}
}
}
catch (ce: Exception) {
connection = null
send(null)
}
}
}
init {
scope.launch {
settings.selectedRepoAndAccount?.let {
tryConnect(it.first, it.second)
}
}
}
override suspend fun tryConnect(repo: GHGitRepositoryMapping, account: GithubAccount) {
connectionRequestsFlow.emit(repo to account)
}
override suspend fun disconnect() {
withContext(Dispatchers.Main) {
settings.selectedRepoAndAccount = null
}
connectionRequestsFlow.emit(null)
}
}
| 0 | null | 0 | 0 | 04aa5152bb4273dd045360e2e2fad92c2f7b3cf8 | 3,594 | intellij-community | Apache License 2.0 |
shared/src/commonMain/kotlin/com/aglushkov/wordteacher/shared/features/add_article/AddArticleDecomposeComponent.kt | soniccat | 302,971,014 | false | {"Kotlin": 1151087, "Go": 185844, "Swift": 38695, "TypeScript": 29600, "Dockerfile": 5502, "JavaScript": 3131, "Makefile": 3016, "Shell": 2690, "Ruby": 1740, "HTML": 897, "Java": 872, "SCSS": 544, "C": 59} | package com.aglushkov.wordteacher.shared.features.add_article
import com.aglushkov.wordteacher.shared.analytics.Analytics
import com.aglushkov.wordteacher.shared.features.BaseDecomposeComponent
import com.aglushkov.wordteacher.shared.features.add_article.vm.AddArticleVM
import com.aglushkov.wordteacher.shared.features.add_article.vm.AddArticleVMImpl
import com.aglushkov.wordteacher.shared.features.add_article.vm.ArticleContentExtractor
import com.aglushkov.wordteacher.shared.features.cardset_info.CardSetInfoDecomposeComponent
import com.aglushkov.wordteacher.shared.features.cardset_info.CardSetInfoDecomposeComponent.Companion
import com.aglushkov.wordteacher.shared.features.cardset_info.vm.CardSetInfoVM
import com.aglushkov.wordteacher.shared.general.TimeSource
import com.aglushkov.wordteacher.shared.repository.article.ArticlesRepository
import com.aglushkov.wordteacher.shared.repository.cardset.CardSetsRepository
import com.arkivanov.decompose.ComponentContext
import com.arkivanov.essenty.instancekeeper.InstanceKeeper
import com.arkivanov.essenty.instancekeeper.getOrCreate
import com.arkivanov.essenty.lifecycle.doOnDestroy
import com.arkivanov.essenty.statekeeper.consume
class AddArticleDecomposeComponent(
componentContext: ComponentContext,
articlesRepository: ArticlesRepository,
contentExtractors: Array<ArticleContentExtractor>,
cardSetsRepository: CardSetsRepository,
timeSource: TimeSource,
analytics: Analytics,
private val initialState: AddArticleVM.State,
): AddArticleVMImpl(
componentContext.stateKeeper.consume(
key = KEY_STATE,
strategy = AddArticleVM.State.serializer()
) ?: initialState,
articlesRepository,
contentExtractors,
cardSetsRepository,
timeSource,
analytics,
), ComponentContext by componentContext, BaseDecomposeComponent {
override val componentName: String = "Screen_AddArticle"
init {
baseInit(analytics)
stateKeeper.register(
key = KEY_STATE,
strategy = AddArticleVM.State.serializer()
) {
createState()
}
}
private companion object {
private const val KEY_STATE = "STATE"
}
} | 0 | Kotlin | 1 | 11 | 30b667bc80d488f7aba881647c2534f7f95574c6 | 2,201 | WordTeacher | MIT License |
app/src/main/kotlin/com/yizhenwind/keeper/common/delegate/DataBindingLazy.kt | WangZhiYao | 658,053,133 | false | {"Kotlin": 91950} | package com.yizhenwind.keeper.common.delegate
import android.annotation.SuppressLint
import android.view.LayoutInflater
import androidx.collection.ArrayMap
import androidx.databinding.ViewDataBinding
import java.lang.reflect.Method
import kotlin.reflect.KClass
/**
*
*
* @author WangZhiYao
* @since 2023/6/21
*/
internal val dataBindingMethodSignature = arrayOf(LayoutInflater::class.java)
internal val dataBindingMethodMap = ArrayMap<KClass<out ViewDataBinding>, Method>()
class DataBindingLazy<DB : ViewDataBinding>(
private val dataBindingClass: KClass<DB>,
private val layoutInflaterProducer: () -> LayoutInflater
) : Lazy<DB> {
private var cached: DB? = null
override val value: DB
get() {
var args = cached
if (args == null) {
val layoutInflater = layoutInflaterProducer()
val method: Method = dataBindingMethodMap[dataBindingClass]
?: dataBindingClass.java.getMethod("inflate", *dataBindingMethodSignature)
.also { method ->
// Save a reference to the method
dataBindingMethodMap[dataBindingClass] = method
}
@SuppressLint("BanUncheckedReflection") // needed for method.invoke
@Suppress("UNCHECKED_CAST")
args = method.invoke(null, layoutInflater) as DB
cached = args
}
return args
}
override fun isInitialized(): Boolean = cached != null
}
| 1 | Kotlin | 0 | 2 | 03ee88855b6b4d084312f51be745493f51e79373 | 1,566 | Keeper | Apache License 2.0 |
query-model/jpql/src/main/kotlin/com/linecorp/kotlinjdsl/querymodel/jpql/entity/impl/JpqlEntityTreat.kt | line | 442,633,985 | false | {"Kotlin": 1959613, "JavaScript": 5144, "Shell": 1023} | package com.linecorp.kotlinjdsl.querymodel.jpql.entity.impl
import com.linecorp.kotlinjdsl.Internal
import com.linecorp.kotlinjdsl.querymodel.jpql.entity.Entity
import kotlin.reflect.KClass
@Internal
data class JpqlEntityTreat<T : Any, S : T> internal constructor(
val entity: Entity<T>,
val type: KClass<S>,
) : Entity<S> {
override val alias: String get() = entity.alias
}
| 4 | Kotlin | 86 | 705 | 3a58ff84b1c91bbefd428634f74a94a18c9b76fd | 389 | kotlin-jdsl | Apache License 2.0 |
core/src/main/java/me/tatocaster/core/base/BaseActivity.kt | tatocaster | 253,899,293 | false | null | package me.tatocaster.core.base
import androidx.appcompat.app.AppCompatActivity
abstract class BaseActivity : AppCompatActivity() {
} | 0 | Kotlin | 0 | 3 | 32c3eab1e0f544d75457bc5300d82a38b91e7126 | 136 | covid19-IoT | MIT License |
src/test/resources/examples/springFormatDateAndDateTime/controllers/Controllers.kt | cjbooms | 229,844,927 | false | null | package ie.zalando.controllers
import org.springframework.format.`annotation`.DateTimeFormat
import org.springframework.http.ResponseEntity
import org.springframework.stereotype.Controller
import org.springframework.validation.`annotation`.Validated
import org.springframework.web.bind.`annotation`.RequestMapping
import org.springframework.web.bind.`annotation`.RequestMethod
import org.springframework.web.bind.`annotation`.RequestParam
import java.time.LocalDate
import java.time.OffsetDateTime
import kotlin.Int
import kotlin.Unit
@Controller
@Validated
@RequestMapping("")
public interface ExampleController {
/**
*
*
* @param bDateTime
* @param cInt
* @param aDate
*/
@RequestMapping(
value = ["/example"],
produces = [],
method = [RequestMethod.GET],
)
public fun `get`(
@DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME) @RequestParam(
value = "bDateTime",
required =
true,
) bDateTime: OffsetDateTime,
@RequestParam(value = "cInt", required = true) cInt: Int,
@DateTimeFormat(iso = DateTimeFormat.ISO.DATE) @RequestParam(value = "aDate", required = false)
aDate: LocalDate?,
): ResponseEntity<Unit>
}
| 33 | null | 41 | 154 | b95cb5bd8bb81e59eca71e467118cd61a1848b3f | 1,263 | fabrikt | Apache License 2.0 |
access-checkout/src/main/java/com/worldpay/access/checkout/validation/filters/AccessCheckoutInputFilter.kt | Worldpay | 186,591,910 | false | null | package com.worldpay.access.checkout.validation.filters
import android.text.InputFilter
internal interface AccessCheckoutInputFilter : InputFilter
| 0 | Kotlin | 0 | 8 | 81646fea72036055f2906303a0878bd82ec124b4 | 149 | access-checkout-android | MIT License |
android/src/main/java/com/maskedtextinput/MaskedTextInputPackage.kt | IvanIhnatsiuk | 753,113,458 | false | {"Kotlin": 18486, "Swift": 7050, "TypeScript": 5347, "Ruby": 3982, "Objective-C": 2540, "JavaScript": 2122, "Objective-C++": 1526, "C": 103} | package com.maskedtextinput
import com.facebook.react.ReactPackage
import com.facebook.react.bridge.NativeModule
import com.facebook.react.bridge.ReactApplicationContext
import com.facebook.react.uimanager.ViewManager
import com.maskedtextinput.managers.MaskedTextInputDecoratorViewManager
class MaskedTextInputPackage : ReactPackage {
override fun createNativeModules(reactContext: ReactApplicationContext): List<NativeModule> = emptyList()
override fun createViewManagers(reactContext: ReactApplicationContext): List<ViewManager<*, *>> =
listOf(MaskedTextInputDecoratorViewManager(reactContext))
}
| 1 | Kotlin | 0 | 1 | dc2d66711532d375ea39683d1c2fec9ac3b60828 | 611 | react-native-advanced-input-mask | MIT License |
data/src/main/java/com/example/data/network/ApiService.kt | SLAYERVIX | 596,361,819 | false | null | package com.example.data.network
import com.example.data.Constants.API_KEY
import com.example.data.Constants.NEO_END_POINT
import com.example.data.Constants.PLANETARY_END_POINT
import com.example.data.Util
import com.example.domain.entity.neo.NeoResponse
import com.example.domain.entity.planetary.PlanetaryResponse
import retrofit2.Response
import retrofit2.http.GET
import retrofit2.http.Query
interface ApiService {
@GET(PLANETARY_END_POINT)
suspend fun getPlanetaryData(
@Query("api_key") apiKey : String = API_KEY
) : Response<PlanetaryResponse>
@GET(NEO_END_POINT)
suspend fun getNeoData(
@Query("api_key") apiKey : String = API_KEY,
@Query("start_date") startDate : String = Util.currentDate
) : Response<NeoResponse>
} | 0 | Kotlin | 0 | 1 | 481a25374dc6b90b9cabe5f2ee99800e5068a781 | 778 | Asteroider | MIT License |
gui/editor/src/main/kotlin/org/ide/view/EditorTabPane.kt | kostya05983 | 166,905,072 | false | null | package org.ide.view
import javafx.scene.control.TabPane
import javafx.scene.layout.Priority
import org.ide.styles.EditorTabStyles
import systemdeterminer.InfoSystem
import systemdeterminer.Systems
import tornadofx.*
class EditorTabPane : View() {
var currentEditor: Editor? = null
init {
importStylesheet(EditorTabStyles::class)
}
/**
* init our tabpane with editor and fileName
*/
override val root: TabPane = tabpane {
vgrow = Priority.ALWAYS
subscribe<CreateEditorEvent> { event ->
currentEditor = find(mapOf(Editor::path to event.path))
selectionModel.select(
tab(parseName(event.path)) {
add(currentEditor!!)
}
)
}
}
/**
* get fileName from path
* @param path - path opening file
*/
private fun parseName(path: String): String {
val infoSystem = InfoSystem()
return when (infoSystem.getType()) {
Systems.Windows -> path.substringAfterLast("\\")
Systems.MacOs -> TODO()
Systems.Linux -> path.substringAfterLast("/")
Systems.Other -> TODO()
}
}
}
class CreateEditorEvent(val path: String) : FXEvent() | 1 | Kotlin | 0 | 0 | f3e51dcf96fe201ec2cd2ae97bb54cb5444915e3 | 1,277 | PythonIde | MIT License |
data/src/main/java/com/thirfir/data/repository/PostRepositoryImpl.kt | ThirFir | 670,598,007 | false | null | package com.thirfir.data.repository
import android.util.Log
import com.thirfir.data.datasource.remote.PostRemoteDataSource
import com.thirfir.data.toPost
import com.thirfir.domain.model.Post
import com.thirfir.domain.repository.PostRepository
import javax.inject.Inject
class PostRepositoryImpl @Inject constructor(
private val postRemoteDataSource: PostRemoteDataSource
) : PostRepository {
override suspend fun getPost(bulletin: Int, pid: Int): Post {
return postRemoteDataSource.getPostDTO(bulletin, pid).toPost()
}
} | 0 | Kotlin | 0 | 1 | 5a5cbdc206473da15fc976b5b9e2269934c26a70 | 542 | KReminder | Apache License 2.0 |
src/com/koxudaxi/poetry/PyPoetryPackageManager.kt | systemallica | 288,434,129 | false | {"Text": 5, "Gradle": 2, "INI": 1, "Shell": 1, "Ignore List": 1, "Batchfile": 1, "YAML": 4, "Markdown": 6, "Java Properties": 3, "Kotlin": 26, "Java": 7, "XML": 2, "TOML": 3, "Python": 1} | // Copyright 2000-2018 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.koxudaxi.poetry
import com.intellij.execution.ExecutionException
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.module.Module
import com.intellij.openapi.projectRoots.Sdk
import com.intellij.openapi.roots.OrderRootType
import com.intellij.openapi.vfs.VfsUtil
import com.intellij.openapi.vfs.VirtualFile
import com.jetbrains.python.packaging.*
import com.jetbrains.python.sdk.PythonSdkType
import com.jetbrains.python.sdk.associatedModule
import com.jetbrains.python.sdk.baseDir
import com.jetbrains.python.sdk.pipenv.runPipEnv
/**
* @author vlan
*/
/**
* This source code is edited by @koxudaxi (<NAME>)
*/
class PyPoetryPackageManager(val sdk: Sdk) : PyPackageManager() {
@Volatile
private var packages: List<PyPackage>? = null
private var requirements: List<PyRequirement>? = null
private var outdatedPackages: Map<String, PoetryOutdatedVersion> = emptyMap()
init {
PyPackageUtil.runOnChangeUnderInterpreterPaths(sdk) {
PythonSdkType.getInstance().setupSdkPaths(sdk)
}
}
override fun installManagement() {}
override fun hasManagement() = true
override fun install(requirementString: String) {
install(parseRequirements(requirementString), emptyList())
}
override fun install(requirements: List<PyRequirement>?, extraArgs: List<String>) {
val args = if (requirements == null || requirements.isEmpty()) {
listOfNotNull(listOf("install"),
extraArgs)
.flatten()
} else {
listOfNotNull(listOf("add"),
requirements.map { it.name },
extraArgs)
.flatten()
}
try {
runPoetry(sdk, *args.toTypedArray())
} finally {
sdk.associatedModule?.baseDir?.refresh(true, false)
refreshAndGetPackages(true)
}
}
override fun uninstall(packages: List<PyPackage>) {
val args = listOf("uninstall") +
packages.map { it.name }
try {
runPipEnv(sdk, *args.toTypedArray())
} finally {
sdk.associatedModule?.baseDir?.refresh(true, false)
refreshAndGetPackages(true)
}
}
override fun refresh() {
with(ApplicationManager.getApplication()) {
invokeLater {
runWriteAction {
val files = sdk.rootProvider.getFiles(OrderRootType.CLASSES)
VfsUtil.markDirtyAndRefresh(true, true, true, *files)
}
PythonSdkType.getInstance().setupSdkPaths(sdk)
}
}
}
override fun createVirtualEnv(destinationDir: String, useGlobalSite: Boolean): String {
throw ExecutionException("Creating virtual environments based on Pipenv environments is not supported")
}
override fun getPackages() = packages
fun getRequirements() = requirements
fun getOutdatedPackages() = outdatedPackages
override fun refreshAndGetPackages(alwaysRefresh: Boolean): List<PyPackage> {
return refreshAndGetPackages(alwaysRefresh, true)
}
fun refreshAndGetPackages(alwaysRefresh: Boolean, notify: Boolean): List<PyPackage> {
if (alwaysRefresh || packages == null) {
packages = null
val outputInstallDryRun = try {
runPoetry(sdk, "install", "--dry-run", "--no-root")
} catch (e: ExecutionException) {
packages = emptyList()
return packages ?: emptyList()
}
val allPackage = parsePoetryInstallDryRun(outputInstallDryRun)
packages = allPackage.first
requirements = allPackage.second
val outputOutdatedPackages = try {
runPoetry(sdk, "show", "--outdated")
} catch (e: ExecutionException) {
outdatedPackages = emptyMap()
}
if (outputOutdatedPackages is String) {
outdatedPackages = parsePoetryShowOutdated(outputOutdatedPackages)
}
if (notify) {
ApplicationManager.getApplication().messageBus.syncPublisher(PACKAGE_MANAGER_TOPIC).packagesRefreshed(sdk)
}
}
return packages ?: emptyList()
}
override fun getRequirements(module: Module): List<PyRequirement>? = requirements
override fun parseRequirements(text: String): List<PyRequirement> =
PyRequirementParser.fromText(text)
override fun parseRequirement(line: String): PyRequirement? =
PyRequirementParser.fromLine(line)
override fun parseRequirements(file: VirtualFile): List<PyRequirement> =
PyRequirementParser.fromFile(file)
override fun getDependents(pkg: PyPackage): Set<PyPackage> {
// TODO: Parse the dependency information from `pipenv graph`
return emptySet()
}
companion object {
fun getInstance(sdk: Sdk): PyPoetryPackageManager {
return PyPoetryPackageManagers.getInstance().forSdk(sdk)
}
}
private fun getVersion(version: String): String {
return if (Regex("^[0-9]").containsMatchIn(version)) "==$version" else version
}
private fun toRequirements(packages: List<PyPackage>): List<PyRequirement> =
packages
.asSequence()
// .filterNot { (_, pkg) -> pkg.editable ?: false }
// TODO: Support requirements markers (PEP 496), currently any packages with markers are ignored due to PY-30803
// .filter { (_, pkg) -> pkg.markers == null }
.flatMap { it -> this.parseRequirements("${it.name}${it.version?.let { getVersion(it) } ?: ""}").asSequence() }
.toList()
/**
* Parses the output of `poetry install --dry-run ` into a list of packages.
*/
fun parsePoetryInstallDryRun(input: String): Pair<List<PyPackage>, List<PyRequirement>> {
fun getNameAndVersion(line: String): Pair<String, String> {
return line.split(" ").let {
Pair(it[4], it[5].replace(Regex("[()]"), ""))
}
}
val pyPackages = mutableListOf<PyPackage>()
val pyRequirements = mutableListOf<PyRequirement>()
input
.lineSequence()
.filter { it.endsWith(")") || it.endsWith("Already installed") }
.forEach { line ->
getNameAndVersion(line).also {
when {
line.contains("Already installed") -> pyPackages.add(PyPackage(it.first, it.second, null, emptyList()))
line.contains("Installing") -> pyRequirements.addAll(this.parseRequirements(it.first + getVersion(it.second)).asSequence())
}
}
}
return Pair(pyPackages.distinct().toList(), pyRequirements.distinct().toList())
}
} | 1 | null | 1 | 1 | d429afd33013170f58cba0b5b052001e8e04f721 | 7,186 | poetry-pycharm-plugin | Apache License 2.0 |
src/main/java/codes/stevobrock/androidtoolbox/view/ActionTextViewListItem.kt | StevoGTA | 255,703,252 | false | null | package codes.stevobrock.androidtoolbox.view
import android.view.LayoutInflater
import android.view.View
import android.widget.TextView
//----------------------------------------------------------------------------------------------------------------------
class ActionTextViewListItem : ActionListItem {
//------------------------------------------------------------------------------------------------------------------
// Properties
override val view :View
get() {
// Do super
val view = super.view
// Set Text(s)
this.titleTextView = view.findViewById(this.titleTextViewResourceID)
this.titleTextView!!.text = this.title
if (this.subtitleTextViewResourceID > 0) {
this.subtitleTextView = view.findViewById(this.subtitleTextViewResourceID)
this.subtitleTextView!!.text = this.subtitle
}
return view
}
private var subtitleTextViewResourceID = 0
private var titleTextViewResourceID :Int
private var subtitle :String? = null
private var title :String
private var subtitleTextView :TextView? = null
private var titleTextView :TextView? = null
// Lifecycle methods
//------------------------------------------------------------------------------------------------------------------
constructor(layoutInflater :LayoutInflater, resourceID :Int, titleTextViewResourceID :Int, title :String,
subtitleTextViewResourceID :Int, subtitle :String?, listener :ActionListItem.Listener) :
super(layoutInflater, resourceID, listener) {
// Store
this.titleTextViewResourceID = titleTextViewResourceID
this.subtitleTextViewResourceID = subtitleTextViewResourceID
this.title = title
this.subtitle = subtitle
}
//------------------------------------------------------------------------------------------------------------------
constructor(layoutInflater :LayoutInflater, resourceID :Int, titleTextViewResourceID :Int, title :String,
listener :ActionListItem.Listener) : super(layoutInflater, resourceID, listener) {
// Store
this.titleTextViewResourceID = titleTextViewResourceID
this.title = title
}
// Instance methods
//------------------------------------------------------------------------------------------------------------------
fun setTitle(title :String) { this.title = title }
//------------------------------------------------------------------------------------------------------------------
fun setSubtitle(subtitle :String?) { this.subtitle = subtitle }
}
| 0 | Kotlin | 0 | 0 | 7731944857d839814b5be5414c432e4a14bdc89a | 2,446 | AndroidToolbox | MIT License |
app/src/main/java/com/example/aimstar/inappmessage/android/MainActivity.kt | supsysjp | 741,833,914 | false | {"Kotlin": 2945} | package com.example.aimstar.inappmessage.android
import android.content.SharedPreferences
import android.os.Bundle
import android.util.Log
import androidx.appcompat.app.AppCompatActivity
import androidx.core.content.edit
import com.example.aimstar.inappmessage.android.databinding.ActivityMainBinding
import jp.co.aimstar.messaging.android.AimstarInAppMessaging
import jp.co.aimstar.messaging.android.AimstarInAppMessagingListener
import jp.co.aimstar.messaging.android.data.http.AimstarException
import jp.co.aimstar.messaging.android.data.model.InAppMessage
class MainActivity : AppCompatActivity() {
companion object {
private const val API_KEY = ""
}
private val pref: SharedPreferences by lazy {
getSharedPreferences(
"my_pref",
MODE_PRIVATE,
)
}
private var tenantId: String?
set(value) {
pref.edit {
putString("tenantId", value)
}
}
get() = pref.getString("tenantId", null)
private var customerId: String?
set(value) {
pref.edit {
putString("customerId", value)
}
}
get() = pref.getString("customerId", null)
private lateinit var binding: ActivityMainBinding
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = ActivityMainBinding.inflate(layoutInflater)
val view = binding.root
setContentView(view)
AimstarInAppMessaging.listener = object : AimstarInAppMessagingListener {
override fun messageDismissed(message: InAppMessage) {
Log.d("MainActivity", "messageDismissed")
}
override fun messageClicked(message: InAppMessage) {
Log.d("MainActivity", "messageClicked")
}
override fun messageDetectedForDisplay(message: InAppMessage) {
Log.d("MainActivity", "messageDetectedForDisplay")
}
override fun messageError(message: InAppMessage?, error: AimstarException) {
Log.d("MainActivity", "messageError")
}
}
binding.button.apply {
setOnClickListener {
val tenantId = binding.tenantIdTextView.text.toString()
AimstarInAppMessaging.setup(
context = applicationContext,
apiKey = API_KEY,
tenantId = tenantId
)
val customerId = binding.customerIdTextView.text.toString()
AimstarInAppMessaging.customerId = customerId
AimstarInAppMessaging.isStrictLogin = binding.strictLoginCheckbox.isChecked
val screenName = binding.screenNameTextView.text.toString()
AimstarInAppMessaging.fetch(activity = this@MainActivity, screenName = screenName)
}
}
}
} | 0 | Kotlin | 0 | 0 | 14a071b8278bb7b8fe33b437f2c879ddc9ef6583 | 2,945 | aimstar-in-app-message-android | Apache License 2.0 |
btc/src/main/kotlin/com/d3/btc/cli/RefreshWallets.kt | blockchain-Bobby | 199,616,558 | true | {"Kotlin": 447289, "Java": 44751, "Groovy": 449, "Shell": 190} | /*
* Copyright D3 Ledger, Inc. All Rights Reserved.
* SPDX-License-Identifier: Apache-2.0
*/
@file:JvmName("BtcRefreshWalletsMain")
package com.d3.btc.cli
import org.bitcoinj.params.RegTestParams
import org.bitcoinj.wallet.Wallet
import java.io.File
/**
* Recreates Regtest wallets. Good fo testing.
*/
fun main(args: Array<String>) {
val networkParams = RegTestParams.get()
// Wallet for keys
val keysWallet = Wallet(networkParams)
// Wallet for transfers
val transfersWallet = Wallet(networkParams)
//Save files
keysWallet.saveToFile(File("deploy/bitcoin/regtest/keys.d3.wallet"))
transfersWallet.saveToFile(File("deploy/bitcoin/regtest/transfers.d3.wallet"))
}
| 0 | Kotlin | 0 | 0 | f223e63d89ef42cc5ccdde870249af6f15b38c94 | 704 | d3-btc | Apache License 2.0 |
app/src/main/java/com/sedsoftware/yaptalker/presentation/features/navigation/MainActivityView.kt | EitlerPereira | 115,528,632 | true | {"Kotlin": 350092, "Shell": 1229, "IDL": 510, "Prolog": 237, "CSS": 50} | package com.sedsoftware.yaptalker.presentation.features.navigation
import android.text.Spanned
import com.arellomobile.mvp.viewstate.strategy.AddToEndSingleStrategy
import com.arellomobile.mvp.viewstate.strategy.SkipStrategy
import com.arellomobile.mvp.viewstate.strategy.StateStrategyType
import com.sedsoftware.yaptalker.presentation.base.BaseView
@StateStrategyType(AddToEndSingleStrategy::class)
interface MainActivityView : BaseView {
fun setAppbarTitle(title: String)
fun selectNavDrawerItem(item: Long)
@StateStrategyType(SkipStrategy::class)
fun displayFormattedEulaText(spanned: Spanned)
}
| 0 | Kotlin | 0 | 0 | e90fd7f7ed3024e1a58f9f8e0e1ba01cd986bcd1 | 612 | YapTalker | Apache License 2.0 |
compose/src/commonMain/kotlin/io/github/gaaabliz/kliz/compose/common/ui/card/LinkCard.kt | GaaabLiz | 769,193,666 | false | {"Kotlin": 306682} | package io.github.gaaabliz.kliz.compose.common.ui.card
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.Card
import androidx.compose.material.Icon
import androidx.compose.material.MaterialTheme
import androidx.compose.material.Text
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Web
import androidx.compose.runtime.Composable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.vector.ImageVector
import androidx.compose.ui.unit.dp
import io.github.gaaabliz.kliz.compose.common.theme.doveGray
import io.github.gaaabliz.kliz.compose.common.theme.uniupo
@Composable
fun LinkCard(
icon : ImageVector = Icons.Default.Web,
iconColor : Color = doveGray,
title : String = "Titolo",
payload : String = "https://www.google.com",
payloadTextShown : String = payload,
onClick : (String) -> Unit = {},
) {
Card(
shape = RoundedCornerShape(8.dp),
backgroundColor = MaterialTheme.colors.background,
modifier = Modifier
.padding(4.dp)
.fillMaxWidth()
.clickable {
onClick(payload)
}
) {
Row(
modifier = Modifier
.fillMaxWidth()
.padding(8.dp),
verticalAlignment = Alignment.CenterVertically
) {
Icon(
icon,
contentDescription = "Icon of $title",
tint = iconColor,
modifier = Modifier
.clip(CircleShape)
)
Column(
modifier = Modifier
.padding(8.dp)
.fillMaxWidth()
) {
Text(text = title, color = uniupo, style = MaterialTheme.typography.subtitle2)
Spacer(modifier = Modifier.height(2.dp))
Text(text = payloadTextShown, color = Color.Black, style = MaterialTheme.typography.subtitle1)
}
}
}
} | 0 | Kotlin | 0 | 0 | f9cbc327b9784eb3f093f6a9161e390b81db22d1 | 2,551 | ktliz | Apache License 2.0 |
feature/exercise_view/src/main/kotlin/de/tum/informatics/www1/artemis/native_app/feature/exercise_view/service/impl/TextEditorServiceImpl.kt | ls1intum | 537,104,541 | false | null | package de.tum.informatics.www1.artemis.native_app.feature.exercise_view.service.impl
import de.tum.informatics.www1.artemis.native_app.core.data.NetworkResponse
import de.tum.informatics.www1.artemis.native_app.core.data.cookieAuth
import de.tum.informatics.www1.artemis.native_app.core.data.performNetworkCall
import de.tum.informatics.www1.artemis.native_app.core.data.service.impl.KtorProvider
import de.tum.informatics.www1.artemis.native_app.core.model.exercise.participation.Participation
import de.tum.informatics.www1.artemis.native_app.feature.exercise_view.service.TextEditorService
import io.ktor.client.call.*
import io.ktor.client.request.*
import io.ktor.http.*
class TextEditorServiceImpl(private val ktorProvider: KtorProvider) : TextEditorService {
override suspend fun getParticipation(
participationId: Long,
serverUrl: String,
authToken: String
): NetworkResponse<Participation> {
return performNetworkCall {
ktorProvider.ktorClient.get(serverUrl) {
url {
appendPathSegments("api", "text-editor", participationId.toString())
}
contentType(ContentType.Application.Json)
cookieAuth(authToken)
}.body()
}
}
} | 1 | Kotlin | 0 | 2 | d9a0833905cdad14da0f9cf4863b6cf85747941d | 1,290 | artemis-android | Apache License 2.0 |
src/main/kotlin/ch/obermuhlner/kimage/matrix/Functions.kt | eobermuhlner | 345,794,166 | false | null | package ch.obermuhlner.kimage.matrix
import ch.obermuhlner.kimage.Scaling
import ch.obermuhlner.kimage.math.*
import kotlin.math.abs
import kotlin.math.pow
import kotlin.math.sqrt
fun Matrix.contentToString(multiline: Boolean = false): String {
val str = StringBuilder()
str.append("[")
for (y in 0 until height) {
if (y != 0) {
str.append(" ")
}
str.append("[")
for (x in 0 until width) {
if (x != 0) {
str.append(" ,")
}
str.append(this[x, y])
}
str.append("]")
if (multiline && y != height - 1) {
str.appendLine()
}
}
str.append("]")
if (multiline) {
str.appendLine()
}
return str.toString()
}
fun Matrix.contentEquals(other: Matrix, epsilon: Double = 1E-10): Boolean {
if (height != other.height || width != other.width) {
return false
}
for (y in 0 until height) {
for (x in 0 until width) {
if (abs(this[x, y] - other[x, y]) > epsilon) {
return false
}
}
}
return true
}
fun max(m1: Matrix, m2: Matrix): Matrix {
val m = m1.create()
for (y in 0 until m1.height) {
for (x in 0 until m1.width) {
m[x, y] = kotlin.math.max(m1[x, y], m2[x, y])
}
}
return m
}
fun Matrix.rotateLeft(): Matrix {
val m = create(height, width)
for (y in 0 until height) {
for (x in 0 until width) {
m[x, height - y - 1] = this[y, x]
}
}
return m
}
fun Matrix.rotateRight(): Matrix {
val m = create(height, width)
for (y in 0 until height) {
for (x in 0 until width) {
m[width - x - 1, y] = this[y, x]
}
}
return m
}
fun Matrix.stretchClassic(min: Double, max: Double, func: (value: Double) -> Double = { it }): Matrix {
val denom = func(max - min)
return this.copy().onEach { value ->
when {
value < min -> 0.0
value > max -> 1.0
else -> func(value - min) / denom
}
}
}
fun Matrix.averageError(other: Matrix): Double {
var sum = 0.0
for (index in 0 until size) {
val delta = this[index] - other[index]
sum += delta * delta
}
return sum / size
}
fun Matrix.scaleBy(scaleWidth: Double, scaleHeight: Double, offsetX: Double = 0.0, offsetY: Double = 0.0, scaling: Scaling = Scaling.Bicubic): Matrix {
val newWidth = (width * scaleWidth).toInt()
val newHeight = (height * scaleHeight).toInt()
return scaleTo(newWidth, newHeight, offsetX, offsetY, scaling)
}
fun Matrix.scaleTo(newWidth: Int, newHeight: Int, offsetX: Double = 0.0, offsetY: Double = 0.0, scaling: Scaling = Scaling.Bicubic): Matrix {
return when (scaling) {
Scaling.Nearest -> scaleNearestTo(newWidth, newHeight, offsetX, offsetY)
Scaling.Bilinear -> scaleBilinearTo(newWidth, newHeight, offsetX, offsetY)
Scaling.Bicubic -> scaleBicubicTo(newHeight, newWidth, offsetX, offsetY)
}
}
private fun Matrix.scaleNearestTo(newWidth: Int, newHeight: Int, offsetX: Double = 0.0, offsetY: Double = 0.0): Matrix {
val m = create(newWidth, newHeight)
for (newY in 0 until newHeight) {
for (newX in 0 until newWidth) {
val oldX = (newX.toDouble() / newWidth * width + offsetX).toInt()
val oldY = (newY.toDouble() / newHeight * height + offsetY).toInt()
val newValue = this[oldX, oldY]
m[newX, newY] = newValue
}
}
return m
}
private fun Matrix.scaleBilinearTo(newWidth: Int, newHeight: Int, offsetX: Double = 0.0, offsetY: Double = 0.0): Matrix {
val m = create(newWidth, newHeight)
for (newY in 0 until newHeight) {
for (newX in 0 until newWidth) {
val oldX = newX.toDouble() / newWidth * (width - 1) + offsetX + 0.5
val oldY = newY.toDouble() / newHeight * (height - 1) + offsetY + 0.5
val oldXInt = oldX.toInt()
val oldYInt = oldY.toInt()
val oldXFract = oldX - oldXInt
val oldYFract = oldY - oldYInt
val v00 = this[oldXInt, oldYInt]
val v01 = this[oldXInt + 1, oldYInt]
val v10 = this[oldXInt, oldYInt + 1]
val v11 = this[oldXInt + 1, oldYInt + 1]
val newValue = mixBilinear(v00, v01, v10, v11, oldYFract, oldXFract)
m[newX, newY] = newValue
}
}
return m
}
private fun Matrix.scaleBicubicTo(newHeight: Int, newWidth: Int, offsetX: Double = 0.0, offsetY: Double = 0.0): Matrix {
val m = create(newWidth, newHeight)
for (newY in 0 until newHeight) {
for (newX in 0 until newWidth) {
val oldX = newX.toDouble() / newWidth * (width - 1) + offsetX + 0.5
val oldY = newY.toDouble() / newHeight * (height - 1) + offsetY + 0.5
val oldXInt = oldX.toInt()
val oldYInt = oldY.toInt()
val oldXFract = oldX - oldXInt
val oldYFract = oldY - oldYInt
val v00 = this[oldXInt - 1, oldYInt - 1]
val v10 = this[oldXInt - 1, oldYInt + 0]
val v20 = this[oldXInt - 1, oldYInt + 1]
val v30 = this[oldXInt - 1, oldYInt + 2]
val v01 = this[oldXInt + 0, oldYInt - 1]
val v11 = this[oldXInt + 0, oldYInt + 0]
val v21 = this[oldXInt + 0, oldYInt + 1]
val v31 = this[oldXInt + 0, oldYInt + 2]
val v02 = this[oldXInt + 1, oldYInt - 1]
val v12 = this[oldXInt + 1, oldYInt + 0]
val v22 = this[oldXInt + 1, oldYInt + 1]
val v32 = this[oldXInt + 1, oldYInt + 2]
val v03 = this[oldXInt + 2, oldYInt - 1]
val v13 = this[oldXInt + 2, oldYInt + 0]
val v23 = this[oldXInt + 2, oldYInt + 1]
val v33 = this[oldXInt + 2, oldYInt + 2]
val col0 = mixCubicHermite(v00, v10, v20, v30, oldYFract)
val col1 = mixCubicHermite(v01, v11, v21, v31, oldYFract)
val col2 = mixCubicHermite(v02, v12, v22, v32, oldYFract)
val col3 = mixCubicHermite(v03, v13, v23, v33, oldYFract)
val newValue = mixCubicHermite(col0, col1, col2, col3, oldXFract)
m[newX, newY] = clamp(newValue, 0.0, 1.0)
}
}
return m
}
fun Matrix.interpolate(fixPoints: List<Pair<Int, Int>>, valueFunc: (Pair<Int, Int>) -> Double = { valueAt(
this,
it.first,
it.second
) }, power: Double = estimatePowerForInterpolation(fixPoints.size)): Matrix {
val fixValues = fixPoints.map { valueFunc(it) }
return interpolate(fixPoints, fixValues, power)
}
fun Matrix.interpolate(fixPoints: List<Pair<Int, Int>>, fixValues: List<Double>, power: Double = estimatePowerForInterpolation(fixPoints.size)): Matrix {
val m = create()
for (y in 0 until height) {
for (x in 0 until width) {
m[x, y] = interpolate(x, y, fixPoints, fixValues, power)
}
}
return m
}
fun valueAt(matrix: Matrix, x: Int, y: Int): Double {
return matrix[x, y]
}
fun Matrix.medianAround(x: Int, y: Int, radius: Int = 10): Double {
return crop(x - radius, y - radius, radius+radius+1, radius+radius+1).median()
}
private fun interpolate(
x: Int,
y: Int,
fixPoints: List<Pair<Int, Int>>,
fixValues: List<Double>,
power: Double = estimatePowerForInterpolation(fixPoints.size)
): Double {
require(fixPoints.size == fixValues.size)
val distances = DoubleArray(fixPoints.size)
var totalDistance = 0.0
for (i in fixPoints.indices) {
val fixX = fixPoints[i].first
val fixY = fixPoints[i].second
val dX = (x-fixX).toDouble()
val dY = (y-fixY).toDouble()
val distance = sqrt(dX*dX + dY*dY)
distances[i] = distance
totalDistance += distance
}
val factors = DoubleArray(fixPoints.size)
var totalFactor = 0.0
for (i in fixPoints.indices) {
var factor = 1.0 - distances[i] / totalDistance
factor = factor.pow(power)
factors[i] = factor
totalFactor += factor
}
var mixedValue = 0.0
for (i in fixPoints.indices) {
val fixValue = fixValues[i]
val factor = factors[i] / totalFactor
mixedValue += fixValue * factor
}
return mixedValue
}
fun estimatePowerForInterpolation(n: Int): Double = n.toDouble().pow(1.6)
| 0 | Kotlin | 0 | 1 | f94065fe5c35328fd799656229e28daeedba223b | 8,458 | kimage | MIT License |
app/src/main/java/com/mariana/harmonia/activities/EligeModoJuegoActivity.kt | almudenaiparraguirre | 748,158,542 | false | {"Kotlin": 251693, "JavaScript": 1432} | package com.mariana.harmonia.activities
import android.Manifest
import android.animation.AnimatorSet
import android.animation.ObjectAnimator
import android.annotation.SuppressLint
import android.content.Intent
import android.content.pm.PackageManager
import android.media.MediaPlayer
import android.os.Build
import android.os.Bundle
import android.view.MotionEvent
import android.view.View
import android.view.animation.AnimationUtils
import android.widget.FrameLayout
import android.widget.ImageView
import android.widget.ProgressBar
import android.widget.TextView
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import androidx.lifecycle.lifecycleScope
import com.bumptech.glide.Glide
import com.daimajia.androidanimations.library.Techniques
import com.daimajia.androidanimations.library.YoYo
import com.google.firebase.messaging.FirebaseMessaging
import com.mariana.harmonia.MainActivity
import com.mariana.harmonia.R
import com.mariana.harmonia.activities.fragments.CargaFragment
import com.mariana.harmonia.activities.fragments.FragmentoDificultadDesafio
import com.mariana.harmonia.interfaces.PlantillaActivity
import com.mariana.harmonia.models.db.FirebaseDB
import com.mariana.harmonia.utils.ServicioActualizacion
import com.mariana.harmonia.utils.Utils
import com.mariana.harmonia.utils.UtilsDB
import kotlinx.coroutines.launch
import kotlinx.coroutines.runBlocking
/**
* Actividad principal para elegir el modo de juego.
*/
class EligeModoJuegoActivity : AppCompatActivity(), PlantillaActivity {
companion object{
// Se usa para poder llamarla desde otras activitis
lateinit var instance: EligeModoJuegoActivity
}
private var RC_NOTIFICATION = 99
private lateinit var mediaPlayer: MediaPlayer
lateinit var nombreTextView: TextView
lateinit var porcentajeTextView: TextView
private lateinit var imageViewFotoPerfil: ImageView
private lateinit var progressBar: ProgressBar
private lateinit var botonAventura: androidx.appcompat.widget.AppCompatButton
private lateinit var botonDesafio: androidx.appcompat.widget.AppCompatButton
private lateinit var botonAjustes: androidx.appcompat.widget.AppCompatButton
/**
* Función llamada al crear la actividad.
*/
@SuppressLint("ClickableViewAccessibility")
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
var firebaseMessagin:FirebaseMessaging = FirebaseMessaging.getInstance()
firebaseMessagin.subscribeToTopic("new_user_forums")
setContentView(R.layout.elige_modo_juego_activity) // Inflar el layout primero
Utils.isExternalStorageWritable()
Utils.isExternalStorageReadable()
val imageView: ImageView = findViewById(R.id.fondoImageView)
val anim = AnimationUtils.loadAnimation(applicationContext, R.anim.animacion_principal)
imageView.startAnimation(anim)
instance = this
nombreTextView = findViewById(R.id.nombreModoDeJuego)
porcentajeTextView = findViewById(R.id.porcentajeTextView)
progressBar = findViewById(R.id.progressBarCarga)
imageViewFotoPerfil = findViewById(R.id.imageViewFotoPerfil)
botonAventura = findViewById(R.id.botonAventura)
botonDesafio = findViewById(R.id.botonDesafio)
botonAjustes = findViewById(R.id.botonOpciones)
inicilalizarVariablesThis()
inicializarConBase()
lifecycleScope.launch {
downloadImage2()
}
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
requestPermissions(arrayOf(Manifest.permission.POST_NOTIFICATIONS), RC_NOTIFICATION)
}
val serviceIntent = Intent(this, ServicioActualizacion::class.java)
startService(serviceIntent)
println("SERVICIO CONTADOR COMENZO")
crearFragmentoCarga()
//animacion Botones
//animacion Botones
val botones = listOf(botonAventura, botonDesafio, botonAjustes)
// Define la animación de escala para cada botón
val animacionAgrandar = botones.map {
val scaleX = ObjectAnimator.ofFloat(it, "scaleX", 1.2f)
val scaleY = ObjectAnimator.ofFloat(it, "scaleY", 1.2f)
AnimatorSet().apply {
play(scaleX).with(scaleY)
duration = 300 // Duración de la animación en milisegundos
}
}
// Define la animación de escala para restaurar el tamaño original del botón
val animacionReducir = botones.map {
val scaleX = ObjectAnimator.ofFloat(it, "scaleX", 1.0f)
val scaleY = ObjectAnimator.ofFloat(it, "scaleY", 1.0f)
AnimatorSet().apply {
play(scaleX).with(scaleY)
duration = 300 // Duración de la animación en milisegundos
}
}
botones.forEachIndexed { index, button ->
button.setOnTouchListener { _, event ->
when (event.action) {
MotionEvent.ACTION_DOWN -> {
// Inicia la animación de agrandar cuando se toca el botón
animacionAgrandar[index].start()
true
}
MotionEvent.ACTION_UP -> {
// Detiene la animación de agrandar y inicia la animación de reducir cuando se suelta el botón
animacionAgrandar[index].cancel()
animacionReducir[index].start()
// Ejecuta la acción correspondiente al botón
when (button.id) {
R.id.botonAventura -> irModoAventura()
R.id.botonDesafio -> irDesafio()
R.id.botonOpciones -> clickOpciones()
}
true
}
else -> false
}
}
}
}
private fun incializarConexionNotificaciones() {
var firebaseMessagin:FirebaseMessaging = FirebaseMessaging.getInstance()
firebaseMessagin.subscribeToTopic("new_user_forums")
}
/**
* Función para crear y mostrar el fragmento de carga.
*/
fun crearFragmentoCarga(){
val fragment = CargaFragment()
val fragmentManager = supportFragmentManager
val fragmentTransaction = fragmentManager.beginTransaction()
fragmentTransaction.replace(R.id.fragment_container_carga, fragment)
fragmentTransaction.addToBackStack(null)
fragmentTransaction.commit()
ocultarFragmento()
}
/**
* Función para inicializar datos de la interfaz basándose en la base de datos.
*/
fun inicializarConBase() = runBlocking {
val experiencia = UtilsDB.getExperiencia()
val nivel = calcularNivel(experiencia!!)
var experienciaSobrante = UtilsDB.getExperiencia()!!%100
nombreTextView.text = UtilsDB.getNombre()
porcentajeTextView.text = "NV. "+nivel.toString()
progressBar.progress = experienciaSobrante
}
/**
* Función para inicializar variables específicas de esta actividad.
*/
private fun inicilalizarVariablesThis() {
Utils.degradadoTexto(this, R.id.cerrarSesion,R.color.rosa,R.color.morado)
Utils.degradadoTexto(this, R.id.titleTextView,R.color.rosa,R.color.morado)
Utils.degradadoTexto(this, R.id.eligeModo,R.color.rosa,R.color.morado)
mediaPlayer = MediaPlayer.create(this, R.raw.sonido_cuatro)
//Utils.serializeImage(this,R.mipmap.img_gema)
//imageViewFotoPerfil.setImageBitmap(Utils.deserializeImage(this,"/storage/emulated/0/Download/imagenSerializada.json"))
}
/**
* Función para descargar la imagen de perfil del usuario desde Firebase Storage.
*/
private fun downloadImage2() {
val storageRef = FirebaseDB.getInstanceStorage().reference
val userId = FirebaseDB.getInstanceFirebase().currentUser?.uid
val imagesRef = storageRef.child("imagenesPerfilGente").child("$userId.jpg")
imagesRef.downloadUrl.addOnSuccessListener { url ->
Glide.with(this)
.load(url)
.into(imageViewFotoPerfil)
// Call the function to change the name and upload the image
/*runBlocking {
changeAndUploadImage(url)
}*/
}.addOnFailureListener { exception ->
println("Error al cargar la imagen: ${exception.message}")
imageViewFotoPerfil.setImageResource(R.mipmap.fotoperfil_guitarra)
}
}
fun calcularNivel(experiencia: Int): Int {
val N_max = 100 // Nivel máximo deseado
val c = 3 // Factor de ajuste
var nivel = experiencia.toDouble() / (c * N_max)
// Asegurarse de que el nivel no supere el nivel máximo deseado
nivel = nivel.coerceAtMost(N_max.toDouble())
// Redondear el nivel a un número entero si es necesario
nivel = nivel
return nivel.toInt()
}
/**
* Función para abrir la actividad del perfil del usuario.
*/
fun menu_perfil(view: View){
mediaPlayer.start()
mostrarFragmento()
val intent = Intent(this, PerfilUsuarioActivity::class.java)
startActivity(intent)
inicializarConBase()
}
/**
* Función para cerrar la sesión del usuario.
*/
fun cerrarSesion(view: View) {
mediaPlayer.start()
val serviceIntent = Intent(this, ServicioActualizacion::class.java)
stopService(serviceIntent)
println("SERVICIO CONTADOR CERRADO")
FirebaseDB.getInstanceFirebase().signOut()
UtilsDB.currentUser?.reload()
val intent = Intent(this, MainActivity::class.java)
startActivity(intent)
finish()
finishAffinity()
}
/**
* Función para abrir la actividad de configuración.
*/
fun clickOpciones() {
YoYo.with(Techniques.Bounce).duration(1000).playOn(findViewById(R.id.botonOpciones))
mediaPlayer.start()
val intent = Intent(this, ConfiguracionActivity::class.java)
startActivity(intent)
}
/**
* Función para abrir la actividad de niveles de aventura.
*/
fun irModoAventura() {
YoYo.with(Techniques.Bounce).duration(1000).playOn(findViewById(R.id.botonAventura))
mostrarFragmento()
mediaPlayer.start()
val intent = Intent(this, NivelesAventuraActivity::class.java)
startActivity(intent)
mostrarFragmento()
}
/**
* Función para abrir la actividad de desafío.
*/
fun irDesafio() {
YoYo.with(Techniques.Bounce).duration(1000).playOn(findViewById(R.id.botonDesafio))
mediaPlayer.start()
// Crea una instancia del fragmento que deseas mostrar
val fragment = FragmentoDificultadDesafio()
// Obtén el administrador de fragmentos y comienza una transacción
val fragmentManager = supportFragmentManager
val fragmentTransaction = fragmentManager.beginTransaction()
// Reemplaza el contenido del contenedor de fragmentos con el fragmento que deseas mostrar
fragmentTransaction.replace(R.id.fragment_container_desafio, fragment)
// Agrega la transacción al historial de retroceso (opcional)
fragmentTransaction.addToBackStack(null)
// Realiza la transacción
fragmentTransaction.commit()
}
/**
* Función para manejar el botón de retroceso.
*/
override fun onBackPressed() {
super.onBackPressed()
}
/**
* Función para ocultar el fragmento de carga.
*/
fun ocultarFragmento(){
var fragmento = findViewById<FrameLayout>(R.id.fragment_container_carga)
fragmento.visibility = View.GONE
}
/**
* Función para mostrar el fragmento de carga.
*/
fun mostrarFragmento(){
var fragmento = findViewById<FrameLayout>(R.id.fragment_container_carga)
fragmento.visibility = View.VISIBLE
}
/**
* Función para manejar los resultados de la solicitud de permisos.
*/
override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<String>, grantResults: IntArray) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults)
if (requestCode == RC_NOTIFICATION) {
if (grantResults.isNotEmpty() && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
Toast.makeText(this, "ALLOWED", Toast.LENGTH_SHORT).show()
} else {
Toast.makeText(this, "DENIED", Toast.LENGTH_SHORT).show()
}
}
}
} | 1 | Kotlin | 0 | 5 | d5b91bec58e686a92f2ddc5c4526503b052dea85 | 12,799 | HarmoniaPlus | MIT License |
app/src/main/java/com/mariana/harmonia/activities/EligeModoJuegoActivity.kt | almudenaiparraguirre | 748,158,542 | false | {"Kotlin": 251693, "JavaScript": 1432} | package com.mariana.harmonia.activities
import android.Manifest
import android.animation.AnimatorSet
import android.animation.ObjectAnimator
import android.annotation.SuppressLint
import android.content.Intent
import android.content.pm.PackageManager
import android.media.MediaPlayer
import android.os.Build
import android.os.Bundle
import android.view.MotionEvent
import android.view.View
import android.view.animation.AnimationUtils
import android.widget.FrameLayout
import android.widget.ImageView
import android.widget.ProgressBar
import android.widget.TextView
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import androidx.lifecycle.lifecycleScope
import com.bumptech.glide.Glide
import com.daimajia.androidanimations.library.Techniques
import com.daimajia.androidanimations.library.YoYo
import com.google.firebase.messaging.FirebaseMessaging
import com.mariana.harmonia.MainActivity
import com.mariana.harmonia.R
import com.mariana.harmonia.activities.fragments.CargaFragment
import com.mariana.harmonia.activities.fragments.FragmentoDificultadDesafio
import com.mariana.harmonia.interfaces.PlantillaActivity
import com.mariana.harmonia.models.db.FirebaseDB
import com.mariana.harmonia.utils.ServicioActualizacion
import com.mariana.harmonia.utils.Utils
import com.mariana.harmonia.utils.UtilsDB
import kotlinx.coroutines.launch
import kotlinx.coroutines.runBlocking
/**
* Actividad principal para elegir el modo de juego.
*/
class EligeModoJuegoActivity : AppCompatActivity(), PlantillaActivity {
companion object{
// Se usa para poder llamarla desde otras activitis
lateinit var instance: EligeModoJuegoActivity
}
private var RC_NOTIFICATION = 99
private lateinit var mediaPlayer: MediaPlayer
lateinit var nombreTextView: TextView
lateinit var porcentajeTextView: TextView
private lateinit var imageViewFotoPerfil: ImageView
private lateinit var progressBar: ProgressBar
private lateinit var botonAventura: androidx.appcompat.widget.AppCompatButton
private lateinit var botonDesafio: androidx.appcompat.widget.AppCompatButton
private lateinit var botonAjustes: androidx.appcompat.widget.AppCompatButton
/**
* Función llamada al crear la actividad.
*/
@SuppressLint("ClickableViewAccessibility")
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
var firebaseMessagin:FirebaseMessaging = FirebaseMessaging.getInstance()
firebaseMessagin.subscribeToTopic("new_user_forums")
setContentView(R.layout.elige_modo_juego_activity) // Inflar el layout primero
Utils.isExternalStorageWritable()
Utils.isExternalStorageReadable()
val imageView: ImageView = findViewById(R.id.fondoImageView)
val anim = AnimationUtils.loadAnimation(applicationContext, R.anim.animacion_principal)
imageView.startAnimation(anim)
instance = this
nombreTextView = findViewById(R.id.nombreModoDeJuego)
porcentajeTextView = findViewById(R.id.porcentajeTextView)
progressBar = findViewById(R.id.progressBarCarga)
imageViewFotoPerfil = findViewById(R.id.imageViewFotoPerfil)
botonAventura = findViewById(R.id.botonAventura)
botonDesafio = findViewById(R.id.botonDesafio)
botonAjustes = findViewById(R.id.botonOpciones)
inicilalizarVariablesThis()
inicializarConBase()
lifecycleScope.launch {
downloadImage2()
}
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
requestPermissions(arrayOf(Manifest.permission.POST_NOTIFICATIONS), RC_NOTIFICATION)
}
val serviceIntent = Intent(this, ServicioActualizacion::class.java)
startService(serviceIntent)
println("SERVICIO CONTADOR COMENZO")
crearFragmentoCarga()
//animacion Botones
//animacion Botones
val botones = listOf(botonAventura, botonDesafio, botonAjustes)
// Define la animación de escala para cada botón
val animacionAgrandar = botones.map {
val scaleX = ObjectAnimator.ofFloat(it, "scaleX", 1.2f)
val scaleY = ObjectAnimator.ofFloat(it, "scaleY", 1.2f)
AnimatorSet().apply {
play(scaleX).with(scaleY)
duration = 300 // Duración de la animación en milisegundos
}
}
// Define la animación de escala para restaurar el tamaño original del botón
val animacionReducir = botones.map {
val scaleX = ObjectAnimator.ofFloat(it, "scaleX", 1.0f)
val scaleY = ObjectAnimator.ofFloat(it, "scaleY", 1.0f)
AnimatorSet().apply {
play(scaleX).with(scaleY)
duration = 300 // Duración de la animación en milisegundos
}
}
botones.forEachIndexed { index, button ->
button.setOnTouchListener { _, event ->
when (event.action) {
MotionEvent.ACTION_DOWN -> {
// Inicia la animación de agrandar cuando se toca el botón
animacionAgrandar[index].start()
true
}
MotionEvent.ACTION_UP -> {
// Detiene la animación de agrandar y inicia la animación de reducir cuando se suelta el botón
animacionAgrandar[index].cancel()
animacionReducir[index].start()
// Ejecuta la acción correspondiente al botón
when (button.id) {
R.id.botonAventura -> irModoAventura()
R.id.botonDesafio -> irDesafio()
R.id.botonOpciones -> clickOpciones()
}
true
}
else -> false
}
}
}
}
private fun incializarConexionNotificaciones() {
var firebaseMessagin:FirebaseMessaging = FirebaseMessaging.getInstance()
firebaseMessagin.subscribeToTopic("new_user_forums")
}
/**
* Función para crear y mostrar el fragmento de carga.
*/
fun crearFragmentoCarga(){
val fragment = CargaFragment()
val fragmentManager = supportFragmentManager
val fragmentTransaction = fragmentManager.beginTransaction()
fragmentTransaction.replace(R.id.fragment_container_carga, fragment)
fragmentTransaction.addToBackStack(null)
fragmentTransaction.commit()
ocultarFragmento()
}
/**
* Función para inicializar datos de la interfaz basándose en la base de datos.
*/
fun inicializarConBase() = runBlocking {
val experiencia = UtilsDB.getExperiencia()
val nivel = calcularNivel(experiencia!!)
var experienciaSobrante = UtilsDB.getExperiencia()!!%100
nombreTextView.text = UtilsDB.getNombre()
porcentajeTextView.text = "NV. "+nivel.toString()
progressBar.progress = experienciaSobrante
}
/**
* Función para inicializar variables específicas de esta actividad.
*/
private fun inicilalizarVariablesThis() {
Utils.degradadoTexto(this, R.id.cerrarSesion,R.color.rosa,R.color.morado)
Utils.degradadoTexto(this, R.id.titleTextView,R.color.rosa,R.color.morado)
Utils.degradadoTexto(this, R.id.eligeModo,R.color.rosa,R.color.morado)
mediaPlayer = MediaPlayer.create(this, R.raw.sonido_cuatro)
//Utils.serializeImage(this,R.mipmap.img_gema)
//imageViewFotoPerfil.setImageBitmap(Utils.deserializeImage(this,"/storage/emulated/0/Download/imagenSerializada.json"))
}
/**
* Función para descargar la imagen de perfil del usuario desde Firebase Storage.
*/
private fun downloadImage2() {
val storageRef = FirebaseDB.getInstanceStorage().reference
val userId = FirebaseDB.getInstanceFirebase().currentUser?.uid
val imagesRef = storageRef.child("imagenesPerfilGente").child("$userId.jpg")
imagesRef.downloadUrl.addOnSuccessListener { url ->
Glide.with(this)
.load(url)
.into(imageViewFotoPerfil)
// Call the function to change the name and upload the image
/*runBlocking {
changeAndUploadImage(url)
}*/
}.addOnFailureListener { exception ->
println("Error al cargar la imagen: ${exception.message}")
imageViewFotoPerfil.setImageResource(R.mipmap.fotoperfil_guitarra)
}
}
fun calcularNivel(experiencia: Int): Int {
val N_max = 100 // Nivel máximo deseado
val c = 3 // Factor de ajuste
var nivel = experiencia.toDouble() / (c * N_max)
// Asegurarse de que el nivel no supere el nivel máximo deseado
nivel = nivel.coerceAtMost(N_max.toDouble())
// Redondear el nivel a un número entero si es necesario
nivel = nivel
return nivel.toInt()
}
/**
* Función para abrir la actividad del perfil del usuario.
*/
fun menu_perfil(view: View){
mediaPlayer.start()
mostrarFragmento()
val intent = Intent(this, PerfilUsuarioActivity::class.java)
startActivity(intent)
inicializarConBase()
}
/**
* Función para cerrar la sesión del usuario.
*/
fun cerrarSesion(view: View) {
mediaPlayer.start()
val serviceIntent = Intent(this, ServicioActualizacion::class.java)
stopService(serviceIntent)
println("SERVICIO CONTADOR CERRADO")
FirebaseDB.getInstanceFirebase().signOut()
UtilsDB.currentUser?.reload()
val intent = Intent(this, MainActivity::class.java)
startActivity(intent)
finish()
finishAffinity()
}
/**
* Función para abrir la actividad de configuración.
*/
fun clickOpciones() {
YoYo.with(Techniques.Bounce).duration(1000).playOn(findViewById(R.id.botonOpciones))
mediaPlayer.start()
val intent = Intent(this, ConfiguracionActivity::class.java)
startActivity(intent)
}
/**
* Función para abrir la actividad de niveles de aventura.
*/
fun irModoAventura() {
YoYo.with(Techniques.Bounce).duration(1000).playOn(findViewById(R.id.botonAventura))
mostrarFragmento()
mediaPlayer.start()
val intent = Intent(this, NivelesAventuraActivity::class.java)
startActivity(intent)
mostrarFragmento()
}
/**
* Función para abrir la actividad de desafío.
*/
fun irDesafio() {
YoYo.with(Techniques.Bounce).duration(1000).playOn(findViewById(R.id.botonDesafio))
mediaPlayer.start()
// Crea una instancia del fragmento que deseas mostrar
val fragment = FragmentoDificultadDesafio()
// Obtén el administrador de fragmentos y comienza una transacción
val fragmentManager = supportFragmentManager
val fragmentTransaction = fragmentManager.beginTransaction()
// Reemplaza el contenido del contenedor de fragmentos con el fragmento que deseas mostrar
fragmentTransaction.replace(R.id.fragment_container_desafio, fragment)
// Agrega la transacción al historial de retroceso (opcional)
fragmentTransaction.addToBackStack(null)
// Realiza la transacción
fragmentTransaction.commit()
}
/**
* Función para manejar el botón de retroceso.
*/
override fun onBackPressed() {
super.onBackPressed()
}
/**
* Función para ocultar el fragmento de carga.
*/
fun ocultarFragmento(){
var fragmento = findViewById<FrameLayout>(R.id.fragment_container_carga)
fragmento.visibility = View.GONE
}
/**
* Función para mostrar el fragmento de carga.
*/
fun mostrarFragmento(){
var fragmento = findViewById<FrameLayout>(R.id.fragment_container_carga)
fragmento.visibility = View.VISIBLE
}
/**
* Función para manejar los resultados de la solicitud de permisos.
*/
override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<String>, grantResults: IntArray) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults)
if (requestCode == RC_NOTIFICATION) {
if (grantResults.isNotEmpty() && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
Toast.makeText(this, "ALLOWED", Toast.LENGTH_SHORT).show()
} else {
Toast.makeText(this, "DENIED", Toast.LENGTH_SHORT).show()
}
}
}
} | 1 | Kotlin | 0 | 5 | d5b91bec58e686a92f2ddc5c4526503b052dea85 | 12,799 | HarmoniaPlus | MIT License |
src/main/kotlin/me/odin/features/general/GuildCommands.kt | odtheking | 650,091,570 | false | null | package me.odin.features.general
import kotlinx.coroutines.DelicateCoroutinesApi
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
import me.odin.Odin.Companion.config
import me.odin.Odin.Companion.mc
import me.odin.utils.skyblock.ChatUtils
import net.minecraft.util.StringUtils.stripControlCodes
import net.minecraftforge.client.event.ClientChatReceivedEvent
import net.minecraftforge.fml.common.eventhandler.SubscribeEvent
object GuildCommands {
@OptIn(DelicateCoroutinesApi::class)
@SubscribeEvent
fun guild(event: ClientChatReceivedEvent) {
if (!config.guildCommands) return
val message = stripControlCodes(event.message.unformattedText)
val match = Regex("Guild > (\\[.+])? ?(.+) (\\[.+])?: ?!(.+)").find(message) ?: return
val ign = match.groups[2]?.value
val msg = match.groups[4]?.value?.lowercase()
GlobalScope.launch {
delay(150)
ChatUtils.guildCmdsOptions(msg!!, ign!!)
if (config.guildGM && mc.thePlayer.name !== ign) ChatUtils.autoGM(msg.drop(1), ign)
}
}
} | 0 | Kotlin | 0 | 0 | bd227af42c5507b9deaeea4ca49d41cf629158da | 1,136 | Odin | The Unlicense |
enro/src/androidTest/java/dev/enro/core/compose/ManuallyBoundComposableTest.kt | isaac-udy | 256,179,010 | false | null | package dev.enro.core.compose
import dev.enro.core.destinations.ComposableDestinations
import dev.enro.core.destinations.IntoChildContainer
import dev.enro.core.destinations.assertPushesTo
import dev.enro.core.destinations.launchComposableRoot
import org.junit.Assert.assertNotEquals
import org.junit.Test
class ManuallyBoundComposableTest {
@Test
fun givenManuallyDefinedComposable_whenComposableIsAsRootOfNavigation_thenCorrectComposableIsDisplayed() {
val root = launchComposableRoot()
root.assertPushesTo<ComposableDestination, ComposableDestinations.ManuallyBound>(IntoChildContainer)
}
@Test
fun givenManuallyDefinedComposable_whenManuallyDefinedComposableIsPushedMultipleTimes_thenTheDestinationIsUnique() {
val root = launchComposableRoot()
val first = root.assertPushesTo<ComposableDestination, ComposableDestinations.ManuallyBound>(IntoChildContainer)
val second = root.assertPushesTo<ComposableDestination, ComposableDestinations.ManuallyBound>(IntoChildContainer)
val third = root.assertPushesTo<ComposableDestination, ComposableDestinations.ManuallyBound>(IntoChildContainer)
assertNotEquals(first.navigationContext, second.navigationContext)
assertNotEquals(first.navigationContext.contextReference, second.navigationContext.contextReference)
assertNotEquals(first.navigationContext, third.navigationContext)
assertNotEquals(first.navigationContext.contextReference, third.navigationContext.contextReference)
assertNotEquals(second.navigationContext, third.navigationContext)
assertNotEquals(second.navigationContext.contextReference, third.navigationContext.contextReference)
}
} | 13 | Kotlin | 13 | 217 | 84dbdbd4b6dda314629353b06db6491863431a91 | 1,724 | Enro | Apache License 2.0 |
common/all/src/commonMain/kotlin/com/tunjid/me/common/ui/archivelist/ArchiveFiltering.kt | tunjid | 439,670,817 | false | null | /*
* Copyright 2021 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* 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.tunjid.me.common.ui.archivelist
import androidx.compose.animation.AnimatedVisibility
import androidx.compose.animation.core.animateFloatAsState
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.PaddingValues
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.defaultMinSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.Button
import androidx.compose.material.Icon
import androidx.compose.material.MaterialTheme
import androidx.compose.material.Surface
import androidx.compose.material.Text
import androidx.compose.material.icons.Icons.Filled
import androidx.compose.material.icons.filled.ArrowDropDown
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.rotate
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import com.tunjid.me.core.model.Descriptor
import com.tunjid.me.core.model.minus
import com.tunjid.me.core.model.plus
import com.tunjid.me.common.ui.common.ChipAction
import com.tunjid.me.common.ui.common.ChipEditInfo
import com.tunjid.me.common.ui.common.Chips
@Composable
fun ArchiveFilters(
item: QueryState,
onChanged: (Action) -> Unit
) {
val isExpanded = item.expanded
Surface(
modifier = Modifier
.fillMaxWidth()
.padding(16.dp),
shape = MaterialTheme.shapes.medium,
elevation = 1.dp,
) {
Column(
modifier = Modifier,
) {
Row(
modifier = Modifier
.defaultMinSize(minHeight = 48.dp)
.fillMaxWidth()
.clickable { onChanged(Action.ToggleFilter()) },
horizontalArrangement = Arrangement.SpaceBetween,
verticalAlignment = Alignment.CenterVertically,
) {
Text(
modifier = Modifier.padding(horizontal = 16.dp),
text = "Filters",
textAlign = TextAlign.Center,
fontSize = 18.sp,
)
DropDownButton(isExpanded, onChanged)
}
AnimatedVisibility(visible = isExpanded) {
FilterChips(
modifier = Modifier
.padding(8.dp)
.weight(1F),
state = item,
onChanged = onChanged
)
}
}
}
}
@Composable
private fun FilterChips(
modifier: Modifier,
state: QueryState,
onChanged: (Action) -> Unit
) {
Column(
modifier = modifier
) {
Chips(
modifier = Modifier.fillMaxWidth(),
name = "Categories:",
chips = state.startQuery.contentFilter.categories.map(com.tunjid.me.core.model.Descriptor.Category::value),
color = MaterialTheme.colors.primaryVariant,
editInfo = ChipEditInfo(
currentText = state.categoryText.value,
onChipChanged = onChipFilterChanged(
state = state,
reader = QueryState::categoryText,
writer = com.tunjid.me.core.model.Descriptor::Category,
onChanged = onChanged
)
)
)
Chips(
modifier = Modifier.fillMaxWidth(),
name = "Tags:",
chips = state.startQuery.contentFilter.tags.map(com.tunjid.me.core.model.Descriptor.Tag::value),
color = MaterialTheme.colors.secondary,
editInfo = ChipEditInfo(
currentText = state.tagText.value,
onChipChanged = onChipFilterChanged(
state = state,
reader = QueryState::tagText,
writer = com.tunjid.me.core.model.Descriptor::Tag,
onChanged = onChanged
)
)
)
}
}
@Composable
private fun DropDownButton(
isExpanded: Boolean,
onChanged: (Action) -> Unit
) {
val rotation by animateFloatAsState(if (isExpanded) 0f else -90f)
Button(
modifier = Modifier
.defaultMinSize(minWidth = 1.dp, minHeight = 1.dp)
.rotate(rotation),
onClick = { onChanged(Action.ToggleFilter()) },
shape = RoundedCornerShape(40.dp),
contentPadding = PaddingValues(4.dp),
content = {
Icon(imageVector = Filled.ArrowDropDown, contentDescription = "Arrow")
})
}
private fun onChipFilterChanged(
state: QueryState,
reader: (QueryState) -> com.tunjid.me.core.model.Descriptor,
writer: (String) -> com.tunjid.me.core.model.Descriptor,
onChanged: (Action) -> Unit
): (ChipAction) -> Unit = {
when (it) {
ChipAction.Added -> onChanged(
Action.Fetch.Reset(
query = state.startQuery + reader(state),
)
)
is ChipAction.Changed -> onChanged(Action.FilterChanged(writer(it.text)))
is ChipAction.Removed -> onChanged(
Action.Fetch.Reset(
query = state.startQuery - writer(it.text),
)
)
}
}
| 0 | Kotlin | 1 | 17 | 710745fa1cc2201458b69c61351fe5f585b87a28 | 6,179 | me | Apache License 2.0 |
client/src/commonMain/kotlin/com/inkapplications/telegram/client/KtorPlatformModule.kt | InkApplications | 511,871,853 | false | null | package com.inkapplications.telegram.client
import io.ktor.client.engine.*
/**
* Internal platform specific dependencies.
*/
internal expect object KtorPlatformModule {
val engine: HttpClientEngineFactory<*>
}
| 0 | Kotlin | 0 | 0 | 5cda3570ce2ae4a9bf1f33acbbf8787fc5c95510 | 218 | telegram-kotlin-sdk | MIT License |
src/main/kotlin/moe/lina/hafsa/util/ColorToStringSerializer.kt | nullium21 | 609,594,504 | false | null | package moe.lina.hafsa.util
import dev.kord.common.Color
import kotlinx.serialization.KSerializer
import kotlinx.serialization.descriptors.PrimitiveKind
import kotlinx.serialization.descriptors.PrimitiveSerialDescriptor
import kotlinx.serialization.descriptors.SerialDescriptor
import kotlinx.serialization.encoding.Decoder
import kotlinx.serialization.encoding.Encoder
object ColorToStringSerializer : KSerializer<Color> {
override val descriptor: SerialDescriptor
get() = PrimitiveSerialDescriptor("PluralKit.color", PrimitiveKind.STRING)
override fun deserialize(decoder: Decoder): Color
= Color(decoder.decodeString().toInt(16))
override fun serialize(encoder: Encoder, value: Color) {
encoder.encodeString("${
value.red.toString(16).padStart(2, '0')
}${
value.green.toString(16).padStart(2, '0')
}${
value.blue.toString(16).padStart(2, '0')
}")
}
} | 0 | Kotlin | 0 | 0 | 360eaff1eedc69dce9a01200132bee897f0b7a59 | 957 | hafsa | MIT License |
shared/connect4/src/commonTest/kotlin/connect4/messages/Connect4MessagesTest.kt | Domo3000 | 509,616,464 | false | {"Kotlin": 329990} | package connect4.messages
import connect4.game.Player
import kotlin.test.Test
import kotlin.test.assertEquals
class Connect4MessagesTest {
@Test
fun serialize() {
val messages: Set<Connect4Message> = setOf(
ConnectedMessage(0),
PickedAIMessage(AIChoice.Hard),
PickedPlayerMessage(Player.FirstPlayer),
GameStartedMessage(Player.FirstPlayer),
GameFinishedMessage(Player.FirstPlayer),
NextMoveMessage(0),
WaitMessage,
ContinueMessage
)
messages.forEach {
assertEquals(
expected = it,
actual = Connect4Messages.decode(Connect4Messages.encode(it))
)
}
}
} | 0 | Kotlin | 0 | 6 | da5562a7404a7af58dda842842875a24476a81e1 | 749 | Portfolio | MIT License |
data/src/main/kotlin/com.twere.data/api/dribbble/model/Rebound.kt | CodeBranch | 59,782,960 | true | {"Kotlin": 65701} | package com.twere.data.api.dribbble.model
import com.google.gson.annotations.Expose
import com.google.gson.annotations.SerializedName
import java.util.Date
data class Rebound(
@SerializedName("id") @Expose var id: Long,
@SerializedName("title") @Expose var title: String,
@SerializedName("description") @Expose var description: String,
@SerializedName("width") @Expose var width: Int,
@SerializedName("height") @Expose var height: Int,
@SerializedName("images") @Expose var images: Images,
@SerializedName("views_count") @Expose var viewsCount: Int,
@SerializedName("likes_count") @Expose var likesCount: Int,
@SerializedName("comments_count") @Expose var commentsCount: Int,
@SerializedName("attachments_count") @Expose var attachmentsCount: Int,
@SerializedName("rebounds_count") @Expose var reboundsCount: Int,
@SerializedName("buckets_count") @Expose var bucketsCount: Int,
@SerializedName("created_at") @Expose var createdAt: Date,
@SerializedName("updated_at") @Expose var updatedAt: Date,
@SerializedName("html_url") @Expose var htmlUrl: String,
@SerializedName("attachments_url") @Expose var attachmentsUrl: String,
@SerializedName("comments_url") @Expose var commentsUrl: String,
@SerializedName("likes_url") @Expose var likesUrl: String,
@SerializedName("projects_url") @Expose var projectsUrl: String,
@SerializedName("rebounds_url") @Expose var reboundsUrl: String,
@SerializedName("rebound_source_url") @Expose var reboundSourceUrl: String,
@SerializedName("tags") @Expose var tags: Array<Int>, //TODO
@SerializedName("user") @Expose var user: User,
@SerializedName("team") @Expose var team: Team) {
} | 0 | Kotlin | 0 | 0 | f8b283a0807648d7973dc1d32b83923d073dfd15 | 1,713 | Android-Clean-Kotlin | Apache License 2.0 |
app/src/main/java/com/ando/chathouse/domain/pojo/ChatContext.kt | Ando-Lin | 624,359,996 | false | null | package com.ando.chathouse.domain.pojo
data class ChatContext (
val myUid: Int,
val order: Order = Order.TIME_DESC,
){
enum class Order{
TIME_DESC
}
}
| 0 | Kotlin | 0 | 0 | 1978552779fc0b76ab87a7d1bfe498cb544466d4 | 176 | chat-house | MIT License |
src/main/kotlin/no/nav/helseidnavtest/edi20/EDI20DialogmeldingGenerator.kt | navikt | 754,033,318 | false | {"Kotlin": 176052} | package no.nav.helseidnavtest.edi20
import no.nav.helseidnavtest.oppslag.adresse.Innsending
import no.nav.helseopplysninger.apprec.XMLAppRec
import no.nav.helseopplysninger.hodemelding.XMLMsgHead
import org.springframework.oxm.jaxb.Jaxb2Marshaller
import org.springframework.stereotype.Component
import java.io.StringWriter
@Component
class EDI20DialogmeldingGenerator(private val marshaller: Jaxb2Marshaller,
private val mapper: EDI20DialogmeldingMapper) {
fun marshal(innsending: Innsending) =
StringWriter().run {
marshaller.createMarshaller().marshal(mapper.hodemelding(innsending), this)
toString()
}
fun unmarshal(xml: String) = marshaller.createUnmarshaller().unmarshal(xml.byteInputStream()).let {
when (it) {
is XMLMsgHead -> mapper.innsending(it)
is XMLAppRec -> mapper.apprec(it)
else -> throw IllegalArgumentException("Unknown type: ${it.javaClass}")
}
}
}
| 0 | Kotlin | 0 | 0 | c460e7d02c2c42671c4f772066736674814b7613 | 1,011 | helseid-nav-test | MIT License |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.