path
stringlengths
4
280
owner
stringlengths
2
39
repo_id
int64
21.1k
879M
is_fork
bool
2 classes
languages_distribution
stringlengths
13
1.95k
content
stringlengths
7
482k
issues
int64
0
13.9k
main_language
stringclasses
121 values
forks
stringlengths
1
5
stars
int64
0
111k
commit_sha
stringlengths
40
40
size
int64
7
482k
name
stringlengths
1
100
license
stringclasses
93 values
src/main/kotlin/com/github/kerubistan/kerub/planner/steps/storage/fs/create/CreateImageBasedOnTemplateExecutor.kt
kerubistan
19,528,622
false
null
package com.github.kerubistan.kerub.planner.steps.storage.fs.create import com.github.kerubistan.kerub.data.dynamic.VirtualStorageDeviceDynamicDao import com.github.kerubistan.kerub.host.HostCommandExecutor import com.github.kerubistan.kerub.model.dynamic.VirtualStorageFsAllocation import com.github.kerubistan.kerub.utils.junix.qemu.ImageInfo import com.github.kerubistan.kerub.utils.junix.qemu.QemuImg import java.math.BigInteger class CreateImageBasedOnTemplateExecutor( exec: HostCommandExecutor, dynDao: VirtualStorageDeviceDynamicDao ) : AbstractCreateImageExecutor<CreateImageBasedOnTemplate>(exec, dynDao) { override fun createAllocation(step: CreateImageBasedOnTemplate, updates: ImageInfo): VirtualStorageFsAllocation = VirtualStorageFsAllocation( hostId = step.host.id, actualSize = BigInteger.valueOf(updates.diskSize), mountPoint = step.path, type = step.format, fileName = step.allocation.getPath(step.disk.id), capabilityId = step.capability.id, backingFile = step.baseAllocation.getPath(step.baseDisk.id) ) override fun perform(step: CreateImageBasedOnTemplate): ImageInfo = exec.execute(step.host) { session -> QemuImg.create( session = session, format = step.format, path = step.allocation.getPath(step.disk.id), size = step.disk.size, backingFile = step.baseAllocation.getPath(step.baseDisk.id) ) QemuImg.info(session, step.allocation.getPath(step.disk.id)) } }
109
Kotlin
4
14
99cb43c962da46df7a0beb75f2e0c839c6c50bda
1,480
kerub
Apache License 2.0
wear/src/main/java/de/michelinside/glucodatahandler/complications/ActiveComplicationHandler.kt
pachi81
587,280,747
false
{"Kotlin": 813094, "Java": 1673}
package de.michelinside.glucodatahandler import android.annotation.SuppressLint import android.content.ComponentName import android.content.Context import android.content.pm.PackageInfo import android.content.pm.PackageManager import android.os.Build import android.os.Bundle import android.util.Log import androidx.wear.watchface.complications.datasource.ComplicationDataSourceUpdateRequester import de.michelinside.glucodatahandler.common.notifier.* object ActiveComplicationHandler: NotifierInterface { private const val LOG_ID = "GDH.ActiveComplicationHandler" private var packageInfo: PackageInfo? = null private var complicationClasses = mutableMapOf<Int, ComponentName>() private var noComplication = false // check complications at least one time init { Log.d(LOG_ID, "init called") } fun addComplication(id: Int, component: ComponentName) { complicationClasses[id] = component } fun remComplication(id: Int) { complicationClasses.remove(id) noComplication = complicationClasses.isEmpty() } @SuppressLint("QueryPermissionsNeeded") private fun getPackages(context: Context): PackageInfo { if (packageInfo == null) { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) { packageInfo = context.packageManager.getPackageInfo( context.packageName, PackageManager.PackageInfoFlags.of(PackageManager.GET_SERVICES.toLong()) ) } else { @Suppress("DEPRECATION") packageInfo = context.packageManager.getPackageInfo( context.packageName, PackageManager.GET_SERVICES ) } } return packageInfo!! } override fun OnNotifyData(context: Context, dataSource: NotifySource, extras: Bundle?) { Thread { try { if (complicationClasses.isNotEmpty()) { Log.d(LOG_ID, "Update " + complicationClasses.size + " complication(s).") // upgrade all at once can cause a disappear of icon and images in ambient mode, // so use some delay! complicationClasses.forEach { if (dataSource != NotifySource.TIME_VALUE) Thread.sleep(50) // add delay to prevent disappearing complication icons in ambient mode ComplicationDataSourceUpdateRequester .create( context = context, complicationDataSourceComponent = it.value ) .requestUpdate(it.key) } } else if (!noComplication) { noComplication = true // disable to prevent re-updating complications, if there is none... val packageInfo = getPackages(context) Log.d(LOG_ID, "Got " + packageInfo.services.size + " services.") packageInfo.services.forEach { val isComplication = if (dataSource == NotifySource.TIME_VALUE) { // only update time complications TimeComplicationBase::class.java.isAssignableFrom( Class.forName( it.name ) ) } else { BgValueComplicationService::class.java.isAssignableFrom( Class.forName( it.name ) ) } if (isComplication) { if (dataSource != NotifySource.TIME_VALUE) Thread.sleep(10) ComplicationDataSourceUpdateRequester .create( context = context, complicationDataSourceComponent = ComponentName(context, it.name) ) .requestUpdateAll() } } } } catch (exc: Exception) { Log.e(LOG_ID, "Update complication exception: " + exc.toString()) } }.start() } }
5
Kotlin
3
56
8ca4fcef5277806e557161bf90c830d08513765a
4,657
GlucoDataHandler
MIT License
src/main/kotlin/com/github/liff/dbexternalcommandauth/Acquire.kt
liff
715,666,133
false
{"Kotlin": 6421, "Nix": 378}
package com.github.liff.dbexternalcommandauth import com.intellij.credentialStore.Credentials import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.withContext suspend fun acquire( command: String, parse: (String) -> Credentials? = ::parse, ): Result<Credentials?> = withContext(Dispatchers.IO) { val proc = wrap(command).start() proc.outputStream.close() val output = proc.inputStream.readNBytes(MAX_OUTPUT_SIZE).decodeToString() val errors = proc.errorStream.readNBytes(MAX_OUTPUT_SIZE).decodeToString() if (proc.waitFor() == 0) { Result.success(parse(output)) } else { Result.failure(RuntimeException(errors)) } } private const val MAX_OUTPUT_SIZE = 32 * 1024 private fun wrap(command: String): ProcessBuilder { val osName = System.getProperty("os.name") return if (osName.startsWith("Windows")) { ProcessBuilder("cmd.exe", "/c", command) } else { ProcessBuilder("sh", "-c", command) } }
0
Kotlin
0
1
68484ed814763cae7801cc49b72079f1176c7a0b
1,035
db-external-command-auth
MIT License
app/src/main/java/com/guard/ui/customview/MyGridView.kt
jackli688
132,226,850
false
null
package com.guard.ui.customview import android.content.Context import android.graphics.Canvas import android.util.AttributeSet import android.view.ViewGroup /** * @author: jackli * @version: V1.0 * @project: My360 * @package: com.guard.ui.customview * 最终要实现的目标 * @description: https://www.jianshu.com/p/7be162740a95 * https://mp.weixin.qq.com/s/zRdYyYX0jRC4Toywv1zm9Q * @date: 2018/6/11 * @time: 19:57 */ class MyGridView : ViewGroup { constructor(context: Context) : this(context, null) constructor(context: Context, attributeSet: AttributeSet?) : this(context, attributeSet, 0) constructor(context: Context, attributeSet: AttributeSet?, defStyleAttr: Int) : super(context, attributeSet, defStyleAttr) { } override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) { /** * 获得此ViewGroup上级容器为其推荐的宽和高,以及计算模式 */ val widthMode = MeasureSpec.getMode(widthMeasureSpec) val heightMode = MeasureSpec.getMode(heightMeasureSpec) val sizeWidth = MeasureSpec.getSize(widthMeasureSpec) val sizeHeight = MeasureSpec.getSize(heightMeasureSpec) //计算出所用的childView的宽和高 measureChildren(sizeWidth, sizeHeight) var width: Int var height: Int val cCount = childCount var cWidth: Int var cHeight: Int var cParams: MarginLayoutParams? = null var lHeight = 0 var rHeight = 0 var tWidth = 0 var bWidth = 0 for (i in 0 until cCount) { val childView = getChildAt(i) cWidth = childView.measuredWidth cHeight = childView.measuredHeight cParams = childView.layoutParams as MarginLayoutParams //上面的两个childView if ((i == 0) or (i == 1)) { tWidth += cWidth + cParams.leftMargin + cParams.rightMargin } if ((i == 2) or (i == 3)) { bWidth += cWidth + cParams.leftMargin + cParams.rightMargin } if ((i == 0) or (i == 2)) { lHeight += cHeight + cParams.topMargin + cParams.bottomMargin } if ((i == 1) or (i == 3)) { rHeight += cHeight + cParams.topMargin + cParams.bottomMargin } width = Math.max(tWidth, bWidth) height = Math.max(lHeight, rHeight) /** * 如果是wrap_content设置为我们计算的值 * 否则:直接设置为父容器 */ val tempWidth = if (widthMode == MeasureSpec.EXACTLY) sizeWidth else width val tempHeight = if (heightMode == MeasureSpec.EXACTLY) sizeHeight else height setMeasuredDimension(tempWidth, tempHeight) } super.onMeasure(widthMeasureSpec, heightMeasureSpec) } override fun onLayout(changed: Boolean, l: Int, t: Int, r: Int, b: Int) { var cWidth: Int var cHeight: Int var cParams: MarginLayoutParams for (i in 0 until childCount) { val childView = getChildAt(i) cWidth = childView.measuredWidth cHeight = childView.measuredHeight cParams = childView.layoutParams as MarginLayoutParams var cl: Int = 0 var ct: Int = 0 var cr: Int = 0 var cb: Int = 0 when (i) { 0 -> { cl = cParams.leftMargin ct = cParams.topMargin } 1 -> { cl = width - cWidth - cParams.leftMargin - cParams.rightMargin ct = cParams.topMargin } 2 -> { cl = cParams.leftMargin ct = height - cHeight - cParams.bottomMargin } 3 -> { cl = width - cWidth - cParams.leftMargin - cParams.rightMargin ct = height - cHeight - cParams.bottomMargin } } cr = cl + cWidth cb = ct + cHeight childView.layout(cl, ct, cr, cb) } } override fun onDraw(canvas: Canvas?) { super.onDraw(canvas) } override fun onDrawForeground(canvas: Canvas?) { super.onDrawForeground(canvas) } override fun dispatchDraw(canvas: Canvas?) { super.dispatchDraw(canvas) } override fun generateLayoutParams(attrs: AttributeSet?): LayoutParams { return MarginLayoutParams(context, attrs) } }
1
Kotlin
1
1
8e87aebf1eee088428ca598d0bc238a9d3887786
4,593
My360
Apache License 2.0
src/commonMain/kotlin/org/guiVista/gui/widget/widget_base.kt
gui-vista
331,127,836
false
null
package org.guiVista.gui.widget import org.guiVista.core.ObjectBase /** Base interface for all widget's (controls). */ public expect interface WidgetBase : ObjectBase
0
Kotlin
0
0
484e1e8437a3d57faaf5667489d622402fe7be01
169
guivista-gui
Apache License 2.0
geary-core/src/commonMain/kotlin/com/mineinabyss/geary/events/CheckHandler.kt
MineInAbyss
306,093,350
false
null
package com.mineinabyss.geary.events import com.mineinabyss.geary.components.RequestCheck import com.mineinabyss.geary.components.events.FailedCheck import com.mineinabyss.geary.systems.GearyListener import com.mineinabyss.geary.systems.accessors.EventScope import com.mineinabyss.geary.systems.accessors.SourceScope import com.mineinabyss.geary.systems.accessors.TargetScope /** * A handler which will run a check on an event that requests one. */ public abstract class CheckHandler( parentListener: GearyListener, sourceNullable: Boolean ) : GearyHandler(parentListener, sourceNullable) { init { parentListener.event._family.has<RequestCheck>() } public abstract fun check(source: SourceScope?, target: TargetScope, event: EventScope): Boolean override fun handle(source: SourceScope?, target: TargetScope, event: EventScope) { if (!check(source, target, event)) event.entity.apply { remove<RequestCheck>() set(FailedCheck) } } }
19
Kotlin
9
23
b4e5b1b5365d600cdd5eda11ae4d4a0c8249165b
1,014
Geary
MIT License
library/src/main/kotlin/dev/hossain/hangouts/model/location/PhoneI18n.kt
hossain-khan
275,430,458
false
{"Kotlin": 35068}
package dev.hossain.hangouts.model.location import com.squareup.moshi.JsonClass /** * ``` * { * "national_number": "(234) 567-8900", * "international_number": "+1 234-567-8900", * "country_code": 1, * "region_code": "US", * "is_valid": true, * "validation_result": "IS_POSSIBLE" * } * ``` */ @JsonClass(generateAdapter = true) data class PhoneI18n( val national_number: String? = null, val international_number: String? = null, val country_code: Int? = null, val region_code: String? = null, val is_valid: Boolean? = null, val validation_result: String? = null )
9
Kotlin
1
4
5f101dd18a09475e0aaa9909564d78c54644a469
623
kotlin-google-hangouts-parser
MIT License
src/main/kotlin/engine_helpers/ScreenHandler.kt
olracnai
758,262,334
false
{"Kotlin": 31476}
package engine_helpers import androidx.compose.runtime.Composable import views.mainScreenA import views.mainScreenB import java.io.File object ScreenHandler { private const val FILE_PATH = "RJP" private const val FILE_NAME = "MSState" init { File(FILE_PATH).mkdirs() val file = File("$FILE_PATH/$FILE_NAME") if (!file.exists()) { file.createNewFile() // Create the file if it does not exist } } @Composable fun screenHandler() { val filePath = "RJP/MSState" val fileContent = File(filePath).readText() val ramValue = "true" val fileValue = fileContent.ifEmpty { ramValue } when (fileValue) { "true" -> mainScreenA() "false" -> mainScreenB() else -> { println("screenHandler: $fileValue") } } } }
0
Kotlin
0
1
1b3573a7ea6449453723621d1194ff7dd0821447
882
redshift-jetpack
MIT License
sam-kotlin-core/src/test/kotlin/software/elborai/api/services/blocking/SimulationServiceTest.kt
DefinitelyATestOrg
787,029,213
false
{"Kotlin": 12996764, "Shell": 3638, "Dockerfile": 366}
// File generated from our OpenAPI spec by Stainless. package software.elborai.api.services.blocking import java.time.LocalDate import java.time.OffsetDateTime import java.time.format.DateTimeFormatter import java.util.Base64 import java.util.Optional import java.util.UUID import org.assertj.core.api.Assertions.assertThat import org.junit.jupiter.api.Test import org.junit.jupiter.api.Disabled import org.junit.jupiter.api.extension.ExtendWith import org.junit.jupiter.api.BeforeEach import software.elborai.api.TestServerExtension import software.elborai.api.client.IncreaseClient import software.elborai.api.client.okhttp.IncreaseOkHttpClient import software.elborai.api.core.JsonNull import software.elborai.api.core.JsonString import software.elborai.api.core.JsonValue import software.elborai.api.core.http.BinaryResponseContent import software.elborai.api.services.blocking.SimulationService import software.elborai.api.models.* @ExtendWith(TestServerExtension::class) class SimulationServiceTest { @Test fun callCardAuthorizationExpirations() { val client = IncreaseOkHttpClient.builder() .baseUrl(TestServerExtension.BASE_URL) .apiKey("My API Key") .build() val simulationService = client.simulations() val cardPayment = simulationService.cardAuthorizationExpirations(SimulationCardAuthorizationExpirationsParams.builder() .cardPaymentId("card_payment_id") .build()) println(cardPayment) cardPayment.validate() } @Test fun callCardFuelConfirmations() { val client = IncreaseOkHttpClient.builder() .baseUrl(TestServerExtension.BASE_URL) .apiKey("My API Key") .build() val simulationService = client.simulations() val cardPayment = simulationService.cardFuelConfirmations(SimulationCardFuelConfirmationsParams.builder() .amount(123L) .cardPaymentId("card_payment_id") .build()) println(cardPayment) cardPayment.validate() } @Test fun callCardIncrements() { val client = IncreaseOkHttpClient.builder() .baseUrl(TestServerExtension.BASE_URL) .apiKey("My API Key") .build() val simulationService = client.simulations() val cardPayment = simulationService.cardIncrements(SimulationCardIncrementsParams.builder() .amount(123L) .cardPaymentId("card_payment_id") .eventSubscriptionId("event_subscription_id") .build()) println(cardPayment) cardPayment.validate() } @Test fun callCardReversals() { val client = IncreaseOkHttpClient.builder() .baseUrl(TestServerExtension.BASE_URL) .apiKey("My API Key") .build() val simulationService = client.simulations() val cardPayment = simulationService.cardReversals(SimulationCardReversalsParams.builder() .cardPaymentId("card_payment_id") .amount(123L) .build()) println(cardPayment) cardPayment.validate() } }
1
Kotlin
0
0
3a5229b8bc5cf400f07efbd41e00b9cf40663f97
3,068
sam-kotlin
Apache License 2.0
wasi-emscripten-host/src/jvmMain/kotlin/jvm/JvmLocalTimeFormatter.kt
illarionov
769,429,996
false
{"Kotlin": 1838071}
/* * Copyright 2024, the wasm-sqlite-open-helper project authors and contributors. Please see the AUTHORS file * for details. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. * SPDX-License-Identifier: Apache-2.0 */ package ru.pixnews.wasm.sqlite.open.helper.host import ru.pixnews.wasm.sqlite.open.helper.host.include.StructTm import ru.pixnews.wasm.sqlite.open.helper.host.include.StructTm.IsDstFlag import ru.pixnews.wasm.sqlite.open.helper.host.include.asTmIsdstValue import java.time.Instant import java.time.ZoneId import java.time.ZonedDateTime import kotlin.time.Duration public class JvmLocalTimeFormatter( public val localTimeZoneProvider: () -> ZoneId = ZoneId::systemDefault, ) : (Duration) -> StructTm { override fun invoke(epoch: Duration): StructTm { val instant = Instant.ofEpochMilli(epoch.inWholeMilliseconds) val date: ZonedDateTime = ZonedDateTime.ofInstant( instant, localTimeZoneProvider(), ) val zone = date.zone return StructTm( tm_sec = date.second, tm_min = date.minute, tm_hour = date.hour, tm_mday = date.dayOfMonth, tm_mon = date.monthValue - 1, tm_year = date.year - 1900, tm_wday = date.dayOfWeek.value % 7, tm_yday = date.dayOfYear - 1, tm_isdst = if (date.zone.rules.isDaylightSavings(date.toInstant())) { IsDstFlag.IN_EFFECT } else { IsDstFlag.NOT_IN_EFFECT }.asTmIsdstValue(), tm_gmtoff = zone.rules.getOffset(date.toInstant()).totalSeconds, tm_zone = zone.id, ) } }
0
Kotlin
1
3
5f513e2413987ce681f12ea8e14a2aff2c56a7fd
1,734
wasm-sqlite-open-helper
Apache License 2.0
app/src/main/java/com/abbas/gamesign/ui/fragment/base/BaseBindableFragment.kt
AbbasTorabi
624,361,187
false
null
package com.abbas.gamesign.ui.fragment.base import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.databinding.DataBindingUtil import androidx.databinding.ViewDataBinding abstract class BaseBindableFragment<B : ViewDataBinding>(private val layoutId: Int) : BaseFragment() { private var _binding: B? = null protected val binding: B get() = _binding!! override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? { super.onCreateView(inflater, container, savedInstanceState) _binding = DataBindingUtil.inflate(inflater, layoutId, container, false) binding.apply { lifecycleOwner = this@BaseBindableFragment } return binding.root } override fun onDestroyView() { super.onDestroyView() _binding = null } }
0
Kotlin
0
2
0c77483445d835dde22a604125fe9aeafe43a9d5
925
Game-Sign
MIT License
src/test/kotlin/com/fwdekker/randomness/uuid/UuidSettingsTest.kt
champpp96
400,425,822
true
{"Kotlin": 389625, "HTML": 3342}
package com.fwdekker.randomness.uuid import com.fwdekker.randomness.CapitalizationMode import org.assertj.core.api.Assertions.assertThat import org.spekframework.spek2.Spek import org.spekframework.spek2.style.specification.describe /** * Unit tests for [UuidSettings]. */ object UuidSettingsTest : Spek({ lateinit var uuidSettings: UuidSettings beforeEachTest { uuidSettings = UuidSettings() } describe("state management") { it("creates an independent copy") { val copy = uuidSettings.deepCopy() uuidSettings.currentScheme.version = 1 uuidSettings.currentScheme.enclosure = "D" uuidSettings.currentScheme.capitalization = CapitalizationMode.RANDOM uuidSettings.currentScheme.addDashes = false copy.currentScheme.version = 4 copy.currentScheme.enclosure = "p" copy.currentScheme.capitalization = CapitalizationMode.UPPER copy.currentScheme.addDashes = true assertThat(uuidSettings.currentScheme.version).isEqualTo(1) assertThat(uuidSettings.currentScheme.enclosure).isEqualTo("D") assertThat(uuidSettings.currentScheme.capitalization).isEqualTo(CapitalizationMode.RANDOM) assertThat(uuidSettings.currentScheme.addDashes).isEqualTo(false) } it("copies state from another instance") { uuidSettings.currentScheme.version = 4 uuidSettings.currentScheme.enclosure = "nvpB" uuidSettings.currentScheme.capitalization = CapitalizationMode.FIRST_LETTER uuidSettings.currentScheme.addDashes = true val newUuidSettings = UuidSettings() newUuidSettings.loadState(uuidSettings.state) assertThat(newUuidSettings.currentScheme.version).isEqualTo(4) assertThat(newUuidSettings.currentScheme.enclosure).isEqualTo("nvpB") assertThat(newUuidSettings.currentScheme.capitalization).isEqualTo(CapitalizationMode.FIRST_LETTER) assertThat(newUuidSettings.currentScheme.addDashes).isEqualTo(true) } } describe("copying") { describe("copyFrom") { it("makes the two schemes equal") { val schemeA = UuidScheme() val schemeB = UuidScheme(myName = "Name") assertThat(schemeA).isNotEqualTo(schemeB) schemeA.copyFrom(schemeB) assertThat(schemeA).isEqualTo(schemeB) } } describe("copyAs") { it("makes two schemes equal except for the name") { val schemeA = UuidScheme() val schemeB = schemeA.copyAs("NewName") assertThat(schemeA).isNotEqualTo(schemeB) schemeB.myName = schemeA.myName assertThat(schemeA).isEqualTo(schemeB) } } } })
0
null
0
1
f06f8a3a2ae7218bc83b5452a604ddfa21ef0e5a
2,902
intellij-randomness
MIT License
profile/src/main/java/com/nowiwr01p/profile/navigation/ProfileNavigatorImpl.kt
nowiwr01w
584,138,480
false
null
package com.nowiwr01p.profile.navigation import androidx.navigation.NavController import androidx.navigation.NavGraphBuilder import androidx.navigation.compose.navigation import com.nowiwr01p.core_ui.navigators.ProfileNavigator import com.nowiwr01p.core_ui.navigators.main.Navigator import com.nowiwr01p.profile.ProfileScreen class ProfileNavigatorImpl: ProfileNavigator { private lateinit var navController: NavController override fun setNavController(curNavController: NavController) { navController = curNavController } override fun graph(builder: NavGraphBuilder, navigator: Navigator) { builder.navigation(ProfileScreen.ProfileMainScreen.route, ProfileScreen.ProfileMainScreen.rootRoute) { ProfileScreen.ProfileMainScreen.createScreen(builder, navigator) } } }
0
Kotlin
1
3
0ebdf8f0cc072cf1f07810a6c36e710f373bfc7f
826
Protest
MIT License
app/src/main/java/me/tumur/portfolio/utils/adapters/listItemAdapters/experience/task/TaskAdapter.kt
timtbdev
198,095,052
false
null
package me.tumur.portfolio.utils.adapters.listItemAdapters.experience.task import android.view.ViewGroup import androidx.paging.PagedListAdapter import androidx.recyclerview.widget.RecyclerView import me.tumur.portfolio.repository.database.model.task.TaskModel /** * An adapter that provides a list of [TaskModel] to a [RecyclerView] * */ class TaskAdapter : PagedListAdapter<TaskModel, TaskViewHolder>(TaskDiffCallBack()) { /** * Part of the RecyclerView adapter, called when RecyclerView needs a new [TaskViewHolder] * * A [TaskViewHolder] holds the view for the [RecyclerView] as well as providing information * to the RecyclerView such as where on the screen it was last drawn during scrolling. * */ override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): TaskViewHolder { return TaskViewHolder.from(parent) } /** * Part of the RecyclerView adapter, called when the RecyclerView needs to show an item. * * The [TaskViewHolder] passed may be recycled so make sure that this sets any properties * that may be have been set previously * */ override fun onBindViewHolder(holder: TaskViewHolder, position: Int) { holder.bind(getItem(position)) } }
1
Kotlin
16
40
91cc93fdfa6158da0f0aa7caa17fe7707d46ea06
1,254
Portfolio-App-2
Apache License 2.0
android/src/main/java/com/reactnativemultipleimagepicker/ImageLoaderUtils.kt
baronha
340,853,950
false
null
package com.reactnativemultipleimagepicker import android.app.Activity import android.content.Context import android.content.ContextWrapper object ImageLoaderUtils { fun assertValidRequest(context: Context?): Boolean { if (context is Activity) { return !isDestroy(context) } else if (context is ContextWrapper) { if (context.baseContext is Activity) { val activity = context.baseContext as Activity return !isDestroy(activity) } } return true } private fun isDestroy(activity: Activity?): Boolean { return if (activity == null) { true } else activity.isFinishing || activity.isDestroyed } }
33
null
104
378
469336a00ac420d5d335c5e68480f7851d64d152
737
react-native-multiple-image-picker
MIT License
covpass-sdk/src/main/java/de/rki/covpass/sdk/cert/EUValueSetUtils.kt
ljxx
388,073,819
false
null
/* * (C) Copyright IBM Deutschland GmbH 2021 * (C) Copyright IBM Corp. 2021 */ package de.rki.covpass.sdk.cert import de.rki.covpass.sdk.storage.EUValueSetRepository /** * Retrieves the Manufacturers name as defined in EU value set * * @param rawName The raw consent of the EU JSON Schema (e.g. "ORG-100030215") * * @return The matching EU value set (e.g. "Biontech Manufacturing GmbH") */ public fun getManufacturerName(rawName: String): String { return EUValueSetRepository.vaccineManufacturer.valueSetValues[rawName]?.display ?: rawName } /** * Retrieves the Product name as defined in EU value set * * @param rawName The raw consent of the EU JSON Schema (e.g. "EU/1/20/1528") * * @return The matching EU value set (e.g. "Comirnaty") */ public fun getProductName(rawName: String): String { return EUValueSetRepository.vaccineMedicalProduct.valueSetValues[rawName]?.display ?: rawName } /** * Retrieves the Prophylaxis name as defined in EU value set * * @param rawName The raw consent of the EU JSON Schema (e.g. "1119349007") * * @return The matching EU value set (e.g. "SARS-CoV-2 mRNA vaccine") */ public fun getProphylaxisName(rawName: String): String { return EUValueSetRepository.vaccineProphylaxis.valueSetValues[rawName]?.display ?: rawName } /** * Retrieves the test type as defined in EU value set * * @param rawName The raw consent of the EU JSON Schema (e.g. "LP6464-4") * * @return The matching EU value set (e.g. "Nucleic acid amplification with probe detection") */ public fun getTestTypeName(rawName: String): String { return EUValueSetRepository.testType.valueSetValues[rawName]?.display ?: rawName } /** * Retrieves the test result as defined in EU value set * * @param rawName The raw consent of the EU JSON Schema (e.g. "260415000") * * @return The matching EU value set (e.g. "Not detected") */ public fun getTestResultName(rawName: String): String { return EUValueSetRepository.testResult.valueSetValues[rawName]?.display ?: rawName } /** * Retrieves the test manufacturer as defined in EU value set * * @param rawName The raw consent of the EU JSON Schema (e.g. "1232") * * @return The matching EU value set (e.g. "Abbott Rapid Diagnostics, Panbio COVID-19 Ag Test") */ public fun getTestManufacturerName(rawName: String): String { return EUValueSetRepository.testManufacturer.valueSetValues[rawName]?.display ?: rawName } /** * Retrieves the disease agent as defined in EU value set * * @param rawName The raw consent of the EU JSON Schema (e.g. "LP6464-4") * * @return The matching EU value set (e.g. "COVID-19") */ public fun getDiseaseAgentName(rawName: String): String { return EUValueSetRepository.diseaseAgent.valueSetValues[rawName]?.display ?: rawName }
44
Kotlin
60
2
390a45d0c8231e8203439018d0e6702ecb0f0d05
2,772
android-covpass-app
Apache License 2.0
platform/src/main/kotlin/researchstack/backend/enums/IrbDecisionType.kt
S-ResearchStack
520,365,362
false
{"Kotlin": 1297740, "Dockerfile": 202, "Shell": 59}
package researchstack.backend.enums enum class IrbDecisionType(val value: String) { UNSPECIFIED("Unspecified"), EXEMPT("Exempt"), APPROVED("Approved"); }
1
Kotlin
9
29
edd76f219cdb10c8151b8ac14175b1e818a6036a
167
backend-system
Apache License 2.0
app/src/main/java/com/android/fleksy/movie/util/Utils.kt
kairos34
446,395,811
false
{"Kotlin": 78741}
package com.android.fleksy.movie.util import android.graphics.Bitmap import android.os.SystemClock import androidx.compose.ui.graphics.Color import androidx.compose.ui.graphics.toArgb import androidx.core.graphics.alpha import androidx.core.graphics.blue import androidx.core.graphics.green import androidx.core.graphics.red import androidx.palette.graphics.Palette private var lastClickTime: Long = 0 fun safeClick(function: () -> Unit) { if (SystemClock.elapsedRealtime() - lastClickTime < 1000) { return } lastClickTime = SystemClock.elapsedRealtime() function() } fun Bitmap.generateDominantColorState(): Palette.Swatch = Palette.Builder(this) .resizeBitmapArea(0) .maximumColorCount(16) .generate() .swatches .maxByOrNull { swatch -> swatch.population }!! fun getComplimentColor(color: Color): Color { val graphicColor = android.graphics.Color.argb( color.toArgb().alpha, color.toArgb().red, color.toArgb().green, color.toArgb().blue ) // get existing colors val alpha: Int = android.graphics.Color.alpha(graphicColor) var red: Int = android.graphics.Color.red(graphicColor) var blue: Int = android.graphics.Color.blue(graphicColor) var green: Int = android.graphics.Color.green(graphicColor) // find compliments red = red.inv() and 0xff blue = blue.inv() and 0xff green = green.inv() and 0xff return Color(android.graphics.Color.argb(alpha, red, green, blue)) }
0
Kotlin
2
6
5e154367198408e33c572bfec1addbd2e8acad34
1,496
FleksyMovieApp
The Unlicense
src/main/kotlin/org/unbrokendome/gradle/plugins/helm/command/HelmValueOptions.kt
researchgate
297,154,134
true
{"Kotlin": 484209}
package org.unbrokendome.gradle.plugins.helm.command import groovy.lang.Closure import org.gradle.api.Project import org.gradle.api.file.ConfigurableFileCollection import org.gradle.api.file.FileCollection import org.gradle.api.model.ObjectFactory import org.gradle.api.provider.MapProperty import org.gradle.api.provider.Provider import org.gradle.api.resources.TextResource import org.slf4j.LoggerFactory import org.unbrokendome.gradle.plugins.helm.util.mapProperty import java.util.concurrent.Callable interface HelmValueOptions : HelmOptions { val values: Provider<Map<String, Any>> val fileValues: Provider<Map<String, Any>> val valueFiles: FileCollection } interface ConfigurableHelmValueOptions : HelmValueOptions, ConfigurableHelmOptions { /** * Values to be passed directly. * * Entries in the map will be sent to the CLI using either the `--set-string` option (for strings) or the * `--set` option (for all other types). */ override val values: MapProperty<String, Any> /** * Values read from the contents of files. * * Corresponds to the `--set-file` CLI option. * * The values of the map can be of any type that is accepted by [Project.file]. Additionally, when adding a * [Provider] that represents an output file of another task, the consuming task will automatically have a task * dependency on the producing task. * * Not to be confused with [valueFiles], which contains a collection of YAML files that supply multiple values. */ override val fileValues: MapProperty<String, Any> /** * A collection of YAML files containing values. * * Corresponds to the `--values` CLI option. * * Not to be confused with [fileValues], which contains entries whose values are the contents of files. */ override val valueFiles: ConfigurableFileCollection } internal fun ConfigurableHelmValueOptions.mergeValues(toMerge: HelmValueOptions) = apply { values.putAll(toMerge.values) fileValues.putAll(toMerge.fileValues) valueFiles.from(toMerge.valueFiles) } internal data class HelmValueOptionsHolder( override val values: MapProperty<String, Any>, override val fileValues: MapProperty<String, Any>, override val valueFiles: ConfigurableFileCollection ) : ConfigurableHelmValueOptions { constructor(objects: ObjectFactory) : this( values = objects.mapProperty(), fileValues = objects.mapProperty(), valueFiles = objects.fileCollection() ) } internal object HelmValueOptionsApplier : HelmOptionsApplier { private val logger = LoggerFactory.getLogger(javaClass) override fun apply(spec: HelmExecSpec, options: HelmOptions) { if (options is HelmValueOptions) { logger.debug("Applying options: {}", options) with(spec) { val (stringValues, otherValues) = options.values.getOrElse(emptyMap()).toList() .partition { it.second is String } .toList() .map { items -> items.joinToString(separator = ",") { (key, value) -> "$key=$value" } } if (stringValues.isNotEmpty()) { option("--set-string", stringValues) } if (otherValues.isNotEmpty()) { option("--set", otherValues) } buildFileValuesArg(options).takeIf { it.isNotBlank() }?.let { arg -> option("--set-file", arg) } options.valueFiles.takeUnless { it.isEmpty } ?.let { valueFiles -> option("--values", valueFiles.joinToString(",") { it.absolutePath }) } } } } private fun buildFileValuesArg(options: HelmValueOptions): String = options.fileValues.getOrElse(emptyMap()) .entries .joinToString(separator = ",") { (key, value) -> val valueRepresentation = when (val resolvedValue = resolveValue(value)) { is FileCollection -> resolvedValue.singleFile is TextResource -> resolvedValue.asFile() else -> resolvedValue } "$key=$valueRepresentation" } private fun resolveValue(value: Any?): Any? = when (value) { is Provider<*> -> resolveValue(value.orNull) is Callable<*> -> resolveValue(value.call()) is Closure<*> -> resolveValue(value.call()) else -> value } }
0
Kotlin
1
0
fcb71b67f3a94cca090b4c083217638c73678c22
4,718
gradle-helm-plugin
MIT License
kleanarchitekture/app/src/main/java/com/matthiasbruns/kleanarchitekture/app/feature/post/list/adapter/PostListViewHolder.kt
matthiasbruns
121,611,656
false
null
package com.matthiasbruns.kleanarchitekture.app.feature.post.list.adapter import android.support.v7.widget.RecyclerView import android.view.View import com.matthiasbruns.kleanarchitekture.presentation.post.model.PresentationPost import kotlinx.android.synthetic.main.item_post.view.* class PostListViewHolder(itemView: View?) : RecyclerView.ViewHolder(itemView) { fun bind(item: PresentationPost) { itemView.postTitle.text = item.title itemView.postBody.text = item.body } }
1
null
1
11
e5762a16e591c132b05130393ada7e813513a484
501
Klean-ArchiteKture
Apache License 2.0
z2-core/src/jsMain/kotlin/hu/simplexion/z2/adaptive/html/AdaptiveDOMNodeFragment.kt
spxbhuhb
665,463,766
false
{"Kotlin": 1812530, "CSS": 171914, "Java": 20900, "JavaScript": 1950, "HTML": 1854}
/* * Copyright © 2020-2021, Simplexion, Hungary and contributors. Use of this source code is governed by the Apache 2.0 license. */ package hu.simplexion.z2.adaptive.html import hu.simplexion.z2.adaptive.* import hu.simplexion.z2.adaptive.css.AdaptiveCssStyle import kotlinx.dom.hasClass import org.w3c.dom.HTMLElement import org.w3c.dom.Node abstract class AdaptiveDOMNodeFragment( adapter: AdaptiveAdapter<Node>, parent: AdaptiveFragment<Node>?, index: Int, stateSize : Int, val leaf : Boolean ) : AdaptiveFragment<Node>(adapter, parent, index, stateSize), AdaptiveBridge<Node> { @Suppress("UNCHECKED_CAST") fun getStyles(variableIndex : Int) = state[variableIndex] as? Array<out AdaptiveCssStyle> ?: emptyArray() @Suppress("UNCHECKED_CAST") fun getFragmentFactory(variableIndex : Int) = state[variableIndex] as AdaptiveFragmentFactory<Node> val firstTimeInit get() = (dirtyMask == adaptiveInitStateMask) fun addClass(styles: Array<out AdaptiveCssStyle>) { with(receiver as HTMLElement) { val missingClasses = styles.filterNot { hasClass(it.name) } if (missingClasses.isNotEmpty()) { val presentClasses = className.trim() className = buildString { append(presentClasses) if (presentClasses.isNotEmpty()) { append(" ") } missingClasses.joinTo(this, " ") { it.name } } } } } // ------------------------------------------------------------------------- // Bridge overrides // ------------------------------------------------------------------------- override fun remove(child: AdaptiveBridge<Node>) { check(!leaf) (receiver as HTMLElement).removeChild(child.receiver) } override fun replace(oldChild: AdaptiveBridge<Node>, newChild: AdaptiveBridge<Node>) { check(!leaf) throw IllegalStateException() } override fun add(child: AdaptiveBridge<Node>) { check(!leaf) (receiver as HTMLElement).appendChild(child.receiver) } // ------------------------------------------------------------------------- // Fragment overrides // ------------------------------------------------------------------------- override fun genBuild(parent: AdaptiveFragment<Node>, declarationIndex: Int): AdaptiveFragment<Node>? = null override fun genPatchDescendant(fragment: AdaptiveFragment<Node>) = Unit override fun innerMount(bridge: AdaptiveBridge<Node>) { bridge.add(this) containedFragment?.mount(this) } override fun innerUnmount(bridge: AdaptiveBridge<Node>) { containedFragment?.unmount(this) bridge.remove(this) } }
5
Kotlin
0
1
8b0b012d880918efc01d8dafd9a3dba701e90835
2,842
z2-pre
Apache License 2.0
Template/app/src/test/java/ademar/study/template/presenter/BasePresenterTest.kt
ademar111190
76,153,266
false
null
package ademar.study.reddit.presenter import ademar.study.reddit.test.BaseTest import org.junit.Test class BasePresenterTest : BaseTest() { @Test fun testOnAttachView() { val stubView = object : StubLoadDataView() {} val presenter = BasePresenter<StubLoadDataView>() presenter.onAttachView(stubView) } @Test fun testOnDetachView() { val presenter = BasePresenter<StubLoadDataView>() presenter.onDetachView() } }
0
Kotlin
1
1
65466ea1c6e4f75ae9791826a428c7dd8e101f98
481
Studies
MIT License
src/main/kotlin/io/github/dko1905/passwordmanagerserver/service/AuthService.kt
Dko1905
272,766,102
false
null
package io.github.dko1905.passwordmanagerserver.service import io.github.dko1905.passwordmanagerserver.domain.Account import io.github.dko1905.passwordmanagerserver.domain.AccountRole import io.github.dko1905.passwordmanagerserver.domain.Token import io.github.dko1905.passwordmanagerserver.domain.TokenFactory import io.github.dko1905.passwordmanagerserver.repository.AccountRepository import io.github.dko1905.passwordmanagerserver.repository.TokenRepository import org.springframework.beans.factory.annotation.Autowired import org.springframework.core.env.Environment import org.springframework.stereotype.Service import java.sql.SQLException import java.time.Instant import org.springframework.security.access.AccessDeniedException @Service class AuthService( @Autowired private val accountRepository: AccountRepository, @Autowired private val tokenRepository: TokenRepository, @Autowired private val env: Environment ) { private val tokenFactory = TokenFactory(env.getProperty("token.lifetime")!!.toLong()) private val minlifetime: Long = env.getProperty("token.minlifetime")!!.toLong() /** * Check token if it is valid * @return false if it is invalid and so on. */ private fun checkToken(token: Token): Boolean{ // Check for null if(token.USERID == null){ return false } // Check if it is expired if(Instant.now().isAfter(Instant.ofEpochSecond(token.EXP))){ return false } // Check if it exists val token2 = tokenRepository.getToken(token.USERID) return token2 != null && token2.USERID == token.USERID && token2.EXP == token.EXP && token2.UUID == token2.UUID } /** * Deletes account from db, requires ADMIN role * @exception SQLException The normal sql exception, if something is wrong with the db * @exception Exception An abnormal exception * @exception AccessDeniedException If you are not allowed to view it */ fun deleteAccount(token: Token, otherAccountId: Long) { try { if(!checkToken(token)){ throw AccessDeniedException("Token invalid") } val result = accountRepository.getAccount(token.USERID!!) if(result != null){ if(result.ACCOUNTROLE == AccountRole.ADMIN){ if(accountRepository.getAccount(otherAccountId) != null){ accountRepository.removeAccount(otherAccountId) } else{ throw AccessDeniedException("NOT_FOUND") } } else{ throw AccessDeniedException("Account not authorized") } } else{ throw AccessDeniedException("Account could not be found") } } catch (sqlException: SQLException) { throw sqlException } catch (ade: AccessDeniedException) { throw ade } catch (e: Exception) { throw e } } /** * Adds account to db, requires ADMIN role * @exception SQLException The normal sql exception, if something is wrong with the db * @exception Exception An abnormal exception * @exception AccessDeniedException If you are not allowed to view it */ fun addAccount(token: Token, account: Account) { try { if(!checkToken(token)){ throw AccessDeniedException("Token invalid") } val result = accountRepository.getAccount(token.USERID!!) if(result != null){ if(result.ACCOUNTROLE == AccountRole.ADMIN){ accountRepository.addAccount(account) } else{ throw AccessDeniedException("Account not authorized") } } else{ throw AccessDeniedException("No account found") } } catch (sqlException: SQLException) { throw sqlException } catch (ade: AccessDeniedException) { throw ade } catch (e: Exception) { throw e } } /** * Get array of accounts * @exception SQLException The normal sql exception, if something is wrong with the db * @exception Exception An abnormal exception * @exception AccessDeniedException If you are not allowed to view it */ fun getAccounts(token: Token): ArrayList<Account> { try { if(!checkToken(token)){ throw AccessDeniedException("Token invalid") } val result = accountRepository.getAccount(token.USERID!!) if(result != null){ if(result.ACCOUNTROLE == AccountRole.ADMIN){ return accountRepository.getAccounts() } else{ throw AccessDeniedException("Account not authorized") } } else{ throw AccessDeniedException("No account found") } } catch (sqlException: SQLException) { throw sqlException } catch (ade: AccessDeniedException) { throw ade } catch (e: Exception) { throw e } } /** * @return Returns a <code>token</code> or null * @exception SQLException The normal sql exception, if something is wrong with the db * @exception Exception An abnormal exception */ fun login(username: String, password: String): Token? { try { val result = accountRepository.getAccount(username, password) if (result != null) { val token = tokenRepository.getToken(result.ID!!) if (token == null) { val replacement = tokenFactory.createToken(result.ID!!) tokenRepository.replaceToken(replacement) return replacement } else { val exp = Instant.ofEpochSecond(token.EXP).minusSeconds(minlifetime) val now = Instant.now() if (exp <= now) { // Is too old val replacement = tokenFactory.createToken(result.ID!!) tokenRepository.replaceToken(replacement) return replacement } else { return token } } } else { return null } } catch (sqlException: SQLException) { throw sqlException } catch (e: Exception) { throw e } } }
0
Kotlin
0
0
c38475f3988c8ba64b5be82261cbb21ff8bf127e
6,201
passwordManagerServer
MIT License
modules/project/src/main/java/com/bytebitx/project/net/api/HttpProjectApiService.kt
bytebitx
371,705,786
false
{"Kotlin": 368798, "Java": 130630}
package com.bytebitx.project.net.api import com.bytebitx.base.bean.HttpResult import com.bytebitx.project.bean.ArticleData import com.bytebitx.project.bean.ProjectBean import kotlinx.coroutines.flow.Flow import retrofit2.http.GET import retrofit2.http.Path import retrofit2.http.Query /** * author: wangyb * date: 4/7/21 9:24 PM * description: http api */ interface HttpProjectApiService { /** * 项目数据 * http://www.wanandroid.com/project/tree/json */ @GET("project/tree/json") fun getProjectTree(): Flow<HttpResult<List<ProjectBean>>> /** * 项目列表数据 * http://www.wanandroid.com/project/list/1/json?cid=294 * @param page * @param cid */ @GET("project/list/{page}/json") fun getProjectList(@Path("page") page: Int, @Query("cid") cid: Int): Flow<HttpResult<ArticleData>> }
3
Kotlin
13
51
bd66b15a5f990067be7148fabcd22e3fb560bac7
842
WanAndroid
Apache License 2.0
app/src/main/java/com/anioncode/gamevideodagger/model/searchModel/Clip.kt
Lukieoo
271,757,832
false
null
package com.anioncode.gamevideodagger.model.searchModel data class Clip( val clip: String, val clips: Clips, val preview: String, val video: String )
0
Kotlin
0
0
80647926a0a7259094867f814544f1c1fc9263c2
166
GameVideoDagger
MIT License
app/OutWait/app/src/main/java/edu/kit/outwait/waitingQueue/gravityQueue/GravitySlot.kt
OutWait
398,042,615
false
{"Kotlin": 725686}
package edu.kit.outwait.waitingQueue.gravityQueue import org.joda.time.DateTime import org.joda.time.Duration import org.joda.time.Interval /** * This class is models a time slot with gravity characteristics. * For basic information about the gravity concept, see chapter 10.1 * in the design document. * * @property duration how much time is scheduled for the slot. Note that * a duration has no absolute beginning and ending point in time. */ abstract class GravitySlot (val duration: Duration) { /** * This method models the gravity behaviour of the slot. Given the first * possible point in time when the slot could begin, in which time interval * will it take place? (more information: Chapter 10.1 in the design document) * * @param earliestPossibleStart the first possible point in time when the slot could begin * @return interval when the slot takes place if [earliestPossibleStart] is the * earliest possible beginning point in time */ abstract fun interval(earliestPossibleStart : DateTime) : Interval }
0
Kotlin
0
1
d3b878b82294899006b21a91f48877aa555eee6e
1,072
OutWait
MIT License
src/main/kotlin/dev/shtanko/algorithms/leetcode/MaxCoinsYouCanGet.kt
ashtanko
203,993,092
false
null
/* * Copyright 2023 <NAME> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package dev.shtanko.algorithms.leetcode /** * 1561. Maximum Number of Coins You Can Get * @see <a href="https://leetcode.com/problems/maximum-number-of-coins-you-can-get">Source</a> */ fun interface MaxCoinsYouCanGet { operator fun invoke(piles: IntArray): Int } class MaxCoinsYouCanGetGreedy : MaxCoinsYouCanGet { override fun invoke(piles: IntArray): Int { piles.sort() val queue: ArrayDeque<Int> = ArrayDeque() for (num in piles) { queue.addLast(num) } var ans = 0 while (queue.isNotEmpty()) { queue.removeLast() // alice ans += queue.removeLast() // us queue.removeFirst() // bob } return ans } } class MaxCoinsYouCanGetNoQueue : MaxCoinsYouCanGet { override fun invoke(piles: IntArray): Int { piles.sort() var ans = 0 var i: Int = piles.size / 3 while (i < piles.size) { ans += piles[i] i += 2 } return ans } }
4
null
0
19
7e8ad8a85ef49929c6a2229413fa38a87a8ab722
1,621
kotlab
Apache License 2.0
st_flow_demo/src/main/java/com/st/flow_demo/models/Flow.kt
STMicroelectronics
81,465,478
false
{"Kotlin": 2828028, "Java": 25368, "Shell": 13927, "HTML": 3291, "GLSL": 1461}
package com.st.flow_demo.models import androidx.documentfile.provider.DocumentFile import com.st.blue_sdk.board_catalog.models.Sensor import kotlinx.serialization.SerialName import kotlinx.serialization.Serializable import java.util.Objects import java.util.UUID @Serializable data class Flow( @SerialName(value = "version") val version: Int = FLOW_VERSION, @SerialName(value = "id") var id: String, @SerialName(value = "ex_app") var ex_app: Int = FLOW_CUSTOM, @SerialName(value = "category") var category: String? = null, @SerialName(value = "expression") var expression: Flow? = null, @SerialName(value = "statements") var statements: List<Flow> = ArrayList(), @SerialName(value = "board_compatibility") var board_compatibility: ArrayList<String> = ArrayList(), @SerialName(value = "description") var description: String, @SerialName(value = "notes") var notes: String? = null, @SerialName(value = "sensors") var sensors: List<Sensor> = ArrayList(), @SerialName(value = "functions") var functions: List<Function> = ArrayList(), @SerialName(value = "flows") var flows: List<Flow> = ArrayList(), @SerialName(value = "outputs") var outputs: List<Output> = ArrayList() ) { @kotlinx.serialization.Transient //var file: File? = null var file: DocumentFile? = null companion object { var FLOW_VERSION = 1 var FLOW_CUSTOM = 0 } fun generateId() { id = UUID.randomUUID().toString() } fun setBoard_compatibility(board: String) { board_compatibility.add(board) } override fun equals(o: Any?): Boolean { if (this === o) return true if (o == null || javaClass != o.javaClass) return false val flow: Flow = o as Flow return id == flow.id } override fun hashCode(): Int { return Objects.hash(id) } fun canBeUploaded(): Boolean { if (outputs.isEmpty()) { return false } for (output in outputs) { if (output.canUpload) { return true } } return false } fun canBeUsedAsInput(): Boolean { if (outputs.isEmpty()) { return false } for (output in outputs) { if (output.id == Output.OUTPUT_AS_INPUT_ID) { return true } } return false } override fun toString(): String { return "Flow{" + "version=" + version + ", file=" + file + ", id='" + id + '\'' + ", board_compatibility=" + board_compatibility + ", description='" + description + '\'' + ", notes='" + notes + '\'' + ", sensors=" + sensors + ", functions=" + functions + ", flows=" + flows + ", outputs=" + outputs + ", ex_app=" + ex_app + '}' } } fun createNewFlow(boardName: String): Flow { val flow = Flow( version = Flow.FLOW_VERSION, id = "", category = null, expression = null, statements = ArrayList(), board_compatibility = arrayListOf(boardName), description = "New Flow", notes = null, sensors = ArrayList(), functions = ArrayList(), flows = ArrayList(), outputs = ArrayList() ) flow.generateId() return flow }
12
Kotlin
58
114
cd556743faffbf1e759543f639659ae3a40b789a
3,515
STBLESensor_Android
The Unlicense
spring-boot-server/src/main/kotlin/com/witkups/carsharing/users/routes/LocationRepository.kt
Azbesciak
108,768,876
false
{"TypeScript": 151324, "Kotlin": 56658, "HTML": 24892, "CSS": 14058, "JavaScript": 1646, "SQLPL": 1532}
package com.witkups.carsharing.users.routes import com.witkups.carsharing.users.application.Location import org.springframework.data.jpa.repository.JpaRepository interface LocationRepository: JpaRepository<Location, String>
0
TypeScript
2
2
ee67b82d4cb2c5665a114c6f4cf11d02499cf55e
226
CarSharing
MIT License
commutil/src/main/java/com/fz/common/utils/AnyUtils.kt
peihua8858
380,141,169
false
{"Kotlin": 419940, "Java": 208918}
@file:JvmName("AnyUtils") @file:JvmMultifileClass package com.fz.common.utils import android.os.Parcel import android.os.Parcelable import java.io.* import java.lang.reflect.Field import java.math.BigDecimal import java.math.BigInteger import java.util.* /** * 对象深度拷贝 * @author dingpeihua * @date 2021/3/2 15:29 * @version 1.0 */ fun <T : Serializable> T.deepCloneSerializable(): T? { try { ByteArrayOutputStream().use { byteOut -> ObjectOutputStream(byteOut).use { out -> out.writeObject(this) out.flush() ObjectInputStream(ByteArrayInputStream(byteOut.toByteArray())).use { input -> return this::class.java.cast(input.readObject()) } } } } catch (e: Throwable) { e.printStackTrace() return null } } fun <T : Parcelable> T.deepCloneParcelable(): T? { return try { val tClass = this::class.java val source = Parcel.obtain()// Must be one or more of: Parcelable.PARCELABLE_WRITE_RETURN_VALUE this.writeToParcel(source, this.describeContents()) val bytes: ByteArray = source.marshall() source.recycle() val newSource = Parcel.obtain() newSource.unmarshall(bytes, 0, bytes.size) newSource.setDataPosition(0) val name = tClass.toString() val f = tClass.getField("CREATOR") val creator: Parcelable.Creator<T> = f[null] as Parcelable.Creator<T>? ?: throw Exception("Parcelable protocol requires a non-null static Parcelable.Creator object called CREATOR on class $name") val p = creator.createFromParcel(newSource) as T newSource.recycle() p } catch (e: java.lang.Exception) { e.printStackTrace() null } } /** * 将[source]源数据对象(被复制对象)的不为空的数据值拷贝到[this]目标对象中对应的属性值 * [this] 是目标对象,也是返回对象 * @param source 源对象 * @return [this] * @author dingpeihua * @date 2019/3/21 09:17 * @version 1.0 */ fun <T : Any> T.copyField(source: T): T { val sourceFields: Array<Field> = source.javaClass.declaredFields val targetFields: Array<Field> = javaClass.declaredFields for (i in sourceFields.indices) { try { val sourceField = sourceFields[i] val targetField = targetFields[i] sourceField.isAccessible = true targetField.isAccessible = true val sourceValue = sourceField[source] val targetValue = targetField[this] if (sourceValue != null) { if (sourceValue.checkData() || targetValue == null) { if ("" != sourceValue) { //不替换整型基本类型为0的数据 if (sourceField.type == Int::class.javaPrimitiveType && 0 == sourceValue as Int) { continue } targetField[this] = sourceValue } } else { targetValue.copyField(sourceValue) } } } catch (e: Exception) { e.printStackTrace() } } return this } /** * 检查当前类型是否是基本数据类型(包括[Date]、 * [BigDecimal]、[BigInteger]及[Character]) * * @author dingpeihua * @date 2019/4/1 14:29 * @version 1.0 */ fun Any?.checkData(): Boolean { return this != null && (this is String || this is Int || this is Byte || this is Long || this is Double || this is Float || this is Char || this is Short || this is Boolean || this is BigDecimal || this is BigInteger || this is Date) }
0
Kotlin
0
3
1c427090f78ba8d5c8738f758c0225273f606974
3,613
kotlinCommonUtils
Apache License 2.0
kotlin-cdk-wrapper/src/main/kotlin/io/cloudshiftdev/awscdk/services/location/CfnMap.kt
cloudshiftinc
667,063,030
false
{"Kotlin": 142794926}
@file:Suppress("RedundantVisibilityModifier","RedundantUnitReturnType","RemoveRedundantQualifierName","unused","UnusedImport","ClassName","REDUNDANT_PROJECTION","DEPRECATION") package io.cloudshiftdev.awscdk.services.location import io.cloudshiftdev.awscdk.CfnResource import io.cloudshiftdev.awscdk.CfnTag import io.cloudshiftdev.awscdk.IInspectable import io.cloudshiftdev.awscdk.IResolvable import io.cloudshiftdev.awscdk.ITaggableV2 import io.cloudshiftdev.awscdk.TagManager import io.cloudshiftdev.awscdk.TreeInspector import io.cloudshiftdev.awscdk.common.CdkDslMarker import io.cloudshiftdev.awscdk.common.CdkObject import io.cloudshiftdev.awscdk.common.CdkObjectWrappers import kotlin.Any import kotlin.String import kotlin.Unit import kotlin.collections.List import kotlin.jvm.JvmName import io.cloudshiftdev.constructs.Construct as CloudshiftdevConstructsConstruct import software.constructs.Construct as SoftwareConstructsConstruct /** * The `AWS::Location::Map` resource specifies a map resource in your AWS account, which provides * map tiles of different styles sourced from global location data providers. * * Example: * * ``` * // The code below shows an example of how to instantiate this type. * // The values are placeholders you should change. * import io.cloudshiftdev.awscdk.services.location.*; * CfnMap cfnMap = CfnMap.Builder.create(this, "MyCfnMap") * .configuration(MapConfigurationProperty.builder() * .style("style") * // the properties below are optional * .customLayers(List.of("customLayers")) * .politicalView("politicalView") * .build()) * .mapName("mapName") * // the properties below are optional * .description("description") * .pricingPlan("pricingPlan") * .tags(List.of(CfnTag.builder() * .key("key") * .value("value") * .build())) * .build(); * ``` * * [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-location-map.html) */ public open class CfnMap( cdkObject: software.amazon.awscdk.services.location.CfnMap, ) : CfnResource(cdkObject), IInspectable, ITaggableV2 { public constructor( scope: CloudshiftdevConstructsConstruct, id: String, props: CfnMapProps, ) : this(software.amazon.awscdk.services.location.CfnMap(scope.let(CloudshiftdevConstructsConstruct::unwrap), id, props.let(CfnMapProps::unwrap)) ) public constructor( scope: CloudshiftdevConstructsConstruct, id: String, props: CfnMapProps.Builder.() -> Unit, ) : this(scope, id, CfnMapProps(props) ) /** * The Amazon Resource Name (ARN) for the map resource. Used to specify a resource across all AWS * . * * * Format example: `arn:aws:geo:region:account-id:maps/ExampleMap` */ public open fun attrArn(): String = unwrap(this).getAttrArn() /** * The timestamp for when the map resource was created in [ISO * 8601](https://docs.aws.amazon.com/https://www.iso.org/iso-8601-date-and-time-format.html) format: * `YYYY-MM-DDThh:mm:ss.sssZ` . */ public open fun attrCreateTime(): String = unwrap(this).getAttrCreateTime() /** * */ public open fun attrDataSource(): String = unwrap(this).getAttrDataSource() /** * Synonym for `Arn` . * * The Amazon Resource Name (ARN) for the map resource. Used to specify a resource across all AWS * . * * * Format example: `arn:aws:geo:region:account-id:maps/ExampleMap` */ public open fun attrMapArn(): String = unwrap(this).getAttrMapArn() /** * The timestamp for when the map resource was last updated in [ISO * 8601](https://docs.aws.amazon.com/https://www.iso.org/iso-8601-date-and-time-format.html) format: * `YYYY-MM-DDThh:mm:ss.sssZ` . */ public open fun attrUpdateTime(): String = unwrap(this).getAttrUpdateTime() /** * Tag Manager which manages the tags for this resource. */ public override fun cdkTagManager(): TagManager = unwrap(this).getCdkTagManager().let(TagManager::wrap) /** * Specifies the `MapConfiguration` , including the map style, for the map resource that you * create. */ public open fun configuration(): Any = unwrap(this).getConfiguration() /** * Specifies the `MapConfiguration` , including the map style, for the map resource that you * create. */ public open fun configuration(`value`: IResolvable) { unwrap(this).setConfiguration(`value`.let(IResolvable::unwrap)) } /** * Specifies the `MapConfiguration` , including the map style, for the map resource that you * create. */ public open fun configuration(`value`: MapConfigurationProperty) { unwrap(this).setConfiguration(`value`.let(MapConfigurationProperty::unwrap)) } /** * Specifies the `MapConfiguration` , including the map style, for the map resource that you * create. */ @kotlin.Suppress("INAPPLICABLE_JVM_NAME") @JvmName("3fb73b3b0c94a0a1b10d0adb4530f553d086a0ad2e915616eb379f5666d696c2") public open fun configuration(`value`: MapConfigurationProperty.Builder.() -> Unit): Unit = configuration(MapConfigurationProperty(`value`)) /** * An optional description for the map resource. */ public open fun description(): String? = unwrap(this).getDescription() /** * An optional description for the map resource. */ public open fun description(`value`: String) { unwrap(this).setDescription(`value`) } /** * Examines the CloudFormation resource and discloses attributes. * * @param inspector tree inspector to collect and process attributes. */ public override fun inspect(inspector: TreeInspector) { unwrap(this).inspect(inspector.let(TreeInspector::unwrap)) } /** * The name for the map resource. */ public open fun mapName(): String = unwrap(this).getMapName() /** * The name for the map resource. */ public open fun mapName(`value`: String) { unwrap(this).setMapName(`value`) } /** * No longer used. * * If included, the only allowed value is `RequestBasedUsage` . */ public open fun pricingPlan(): String? = unwrap(this).getPricingPlan() /** * No longer used. * * If included, the only allowed value is `RequestBasedUsage` . */ public open fun pricingPlan(`value`: String) { unwrap(this).setPricingPlan(`value`) } /** * Applies one or more tags to the map resource. */ public open fun tags(): List<CfnTag> = unwrap(this).getTags()?.map(CfnTag::wrap) ?: emptyList() /** * Applies one or more tags to the map resource. */ public open fun tags(`value`: List<CfnTag>) { unwrap(this).setTags(`value`.map(CfnTag::unwrap)) } /** * Applies one or more tags to the map resource. */ public open fun tags(vararg `value`: CfnTag): Unit = tags(`value`.toList()) /** * A fluent builder for [io.cloudshiftdev.awscdk.services.location.CfnMap]. */ @CdkDslMarker public interface Builder { /** * Specifies the `MapConfiguration` , including the map style, for the map resource that you * create. * * The map style defines the look of maps and the data provider for your map resource. * * [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-location-map.html#cfn-location-map-configuration) * @param configuration Specifies the `MapConfiguration` , including the map style, for the map * resource that you create. */ public fun configuration(configuration: IResolvable) /** * Specifies the `MapConfiguration` , including the map style, for the map resource that you * create. * * The map style defines the look of maps and the data provider for your map resource. * * [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-location-map.html#cfn-location-map-configuration) * @param configuration Specifies the `MapConfiguration` , including the map style, for the map * resource that you create. */ public fun configuration(configuration: MapConfigurationProperty) /** * Specifies the `MapConfiguration` , including the map style, for the map resource that you * create. * * The map style defines the look of maps and the data provider for your map resource. * * [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-location-map.html#cfn-location-map-configuration) * @param configuration Specifies the `MapConfiguration` , including the map style, for the map * resource that you create. */ @kotlin.Suppress("INAPPLICABLE_JVM_NAME") @JvmName("18e1cd3843bc1dff5c3e6ee70ca7afa1d72f5ecd09d554cc7bc1b6ccb92db904") public fun configuration(configuration: MapConfigurationProperty.Builder.() -> Unit) /** * An optional description for the map resource. * * [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-location-map.html#cfn-location-map-description) * @param description An optional description for the map resource. */ public fun description(description: String) /** * The name for the map resource. * * Requirements: * * * Must contain only alphanumeric characters (A–Z, a–z, 0–9), hyphens (-), periods (.), and * underscores (_). * * Must be a unique map resource name. * * No spaces allowed. For example, `ExampleMap` . * * [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-location-map.html#cfn-location-map-mapname) * @param mapName The name for the map resource. */ public fun mapName(mapName: String) /** * No longer used. If included, the only allowed value is `RequestBasedUsage` . * * *Allowed Values* : `RequestBasedUsage` * * [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-location-map.html#cfn-location-map-pricingplan) * @param pricingPlan No longer used. If included, the only allowed value is `RequestBasedUsage` * . */ public fun pricingPlan(pricingPlan: String) /** * Applies one or more tags to the map resource. * * A tag is a key-value pair helps manage, identify, search, and filter your resources by * labelling them. * * Format: `"key" : "value"` * * Restrictions: * * * Maximum 50 tags per resource * * Each resource tag must be unique with a maximum of one value. * * Maximum key length: 128 Unicode characters in UTF-8 * * Maximum value length: 256 Unicode characters in UTF-8 * * Can use alphanumeric characters (A–Z, a–z, 0–9), and the following characters: + - = . _ : * / * * [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-location-map.html#cfn-location-map-tags) * @param tags Applies one or more tags to the map resource. */ public fun tags(tags: List<CfnTag>) /** * Applies one or more tags to the map resource. * * A tag is a key-value pair helps manage, identify, search, and filter your resources by * labelling them. * * Format: `"key" : "value"` * * Restrictions: * * * Maximum 50 tags per resource * * Each resource tag must be unique with a maximum of one value. * * Maximum key length: 128 Unicode characters in UTF-8 * * Maximum value length: 256 Unicode characters in UTF-8 * * Can use alphanumeric characters (A–Z, a–z, 0–9), and the following characters: + - = . _ : * / * * [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-location-map.html#cfn-location-map-tags) * @param tags Applies one or more tags to the map resource. */ public fun tags(vararg tags: CfnTag) } private class BuilderImpl( scope: SoftwareConstructsConstruct, id: String, ) : Builder { private val cdkBuilder: software.amazon.awscdk.services.location.CfnMap.Builder = software.amazon.awscdk.services.location.CfnMap.Builder.create(scope, id) /** * Specifies the `MapConfiguration` , including the map style, for the map resource that you * create. * * The map style defines the look of maps and the data provider for your map resource. * * [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-location-map.html#cfn-location-map-configuration) * @param configuration Specifies the `MapConfiguration` , including the map style, for the map * resource that you create. */ override fun configuration(configuration: IResolvable) { cdkBuilder.configuration(configuration.let(IResolvable::unwrap)) } /** * Specifies the `MapConfiguration` , including the map style, for the map resource that you * create. * * The map style defines the look of maps and the data provider for your map resource. * * [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-location-map.html#cfn-location-map-configuration) * @param configuration Specifies the `MapConfiguration` , including the map style, for the map * resource that you create. */ override fun configuration(configuration: MapConfigurationProperty) { cdkBuilder.configuration(configuration.let(MapConfigurationProperty::unwrap)) } /** * Specifies the `MapConfiguration` , including the map style, for the map resource that you * create. * * The map style defines the look of maps and the data provider for your map resource. * * [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-location-map.html#cfn-location-map-configuration) * @param configuration Specifies the `MapConfiguration` , including the map style, for the map * resource that you create. */ @kotlin.Suppress("INAPPLICABLE_JVM_NAME") @JvmName("18e1cd3843bc1dff5c3e6ee70ca7afa1d72f5ecd09d554cc7bc1b6ccb92db904") override fun configuration(configuration: MapConfigurationProperty.Builder.() -> Unit): Unit = configuration(MapConfigurationProperty(configuration)) /** * An optional description for the map resource. * * [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-location-map.html#cfn-location-map-description) * @param description An optional description for the map resource. */ override fun description(description: String) { cdkBuilder.description(description) } /** * The name for the map resource. * * Requirements: * * * Must contain only alphanumeric characters (A–Z, a–z, 0–9), hyphens (-), periods (.), and * underscores (_). * * Must be a unique map resource name. * * No spaces allowed. For example, `ExampleMap` . * * [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-location-map.html#cfn-location-map-mapname) * @param mapName The name for the map resource. */ override fun mapName(mapName: String) { cdkBuilder.mapName(mapName) } /** * No longer used. If included, the only allowed value is `RequestBasedUsage` . * * *Allowed Values* : `RequestBasedUsage` * * [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-location-map.html#cfn-location-map-pricingplan) * @param pricingPlan No longer used. If included, the only allowed value is `RequestBasedUsage` * . */ override fun pricingPlan(pricingPlan: String) { cdkBuilder.pricingPlan(pricingPlan) } /** * Applies one or more tags to the map resource. * * A tag is a key-value pair helps manage, identify, search, and filter your resources by * labelling them. * * Format: `"key" : "value"` * * Restrictions: * * * Maximum 50 tags per resource * * Each resource tag must be unique with a maximum of one value. * * Maximum key length: 128 Unicode characters in UTF-8 * * Maximum value length: 256 Unicode characters in UTF-8 * * Can use alphanumeric characters (A–Z, a–z, 0–9), and the following characters: + - = . _ : * / * * [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-location-map.html#cfn-location-map-tags) * @param tags Applies one or more tags to the map resource. */ override fun tags(tags: List<CfnTag>) { cdkBuilder.tags(tags.map(CfnTag::unwrap)) } /** * Applies one or more tags to the map resource. * * A tag is a key-value pair helps manage, identify, search, and filter your resources by * labelling them. * * Format: `"key" : "value"` * * Restrictions: * * * Maximum 50 tags per resource * * Each resource tag must be unique with a maximum of one value. * * Maximum key length: 128 Unicode characters in UTF-8 * * Maximum value length: 256 Unicode characters in UTF-8 * * Can use alphanumeric characters (A–Z, a–z, 0–9), and the following characters: + - = . _ : * / * * [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-location-map.html#cfn-location-map-tags) * @param tags Applies one or more tags to the map resource. */ override fun tags(vararg tags: CfnTag): Unit = tags(tags.toList()) public fun build(): software.amazon.awscdk.services.location.CfnMap = cdkBuilder.build() } public companion object { public val CFN_RESOURCE_TYPE_NAME: String = software.amazon.awscdk.services.location.CfnMap.CFN_RESOURCE_TYPE_NAME public operator fun invoke( scope: CloudshiftdevConstructsConstruct, id: String, block: Builder.() -> Unit = {}, ): CfnMap { val builderImpl = BuilderImpl(CloudshiftdevConstructsConstruct.unwrap(scope), id) return CfnMap(builderImpl.apply(block).build()) } internal fun wrap(cdkObject: software.amazon.awscdk.services.location.CfnMap): CfnMap = CfnMap(cdkObject) internal fun unwrap(wrapped: CfnMap): software.amazon.awscdk.services.location.CfnMap = wrapped.cdkObject as software.amazon.awscdk.services.location.CfnMap } /** * Specifies the map tile style selected from an available provider. * * Example: * * ``` * // The code below shows an example of how to instantiate this type. * // The values are placeholders you should change. * import io.cloudshiftdev.awscdk.services.location.*; * MapConfigurationProperty mapConfigurationProperty = MapConfigurationProperty.builder() * .style("style") * // the properties below are optional * .customLayers(List.of("customLayers")) * .politicalView("politicalView") * .build(); * ``` * * [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-location-map-mapconfiguration.html) */ public interface MapConfigurationProperty { /** * Specifies the custom layers for the style. * * Leave unset to not enable any custom layer, or, for styles that support custom layers, you * can enable layer(s), such as the `POI` layer for the VectorEsriNavigation style. * * * Currenlty only `VectorEsriNavigation` supports CustomLayers. For more information, see * [Custom * Layers](https://docs.aws.amazon.com//location/latest/developerguide/map-concepts.html#map-custom-layers) * . * * * [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-location-map-mapconfiguration.html#cfn-location-map-mapconfiguration-customlayers) */ public fun customLayers(): List<String> = unwrap(this).getCustomLayers() ?: emptyList() /** * Specifies the map political view selected from an available data provider. * * [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-location-map-mapconfiguration.html#cfn-location-map-mapconfiguration-politicalview) */ public fun politicalView(): String? = unwrap(this).getPoliticalView() /** * Specifies the map style selected from an available data provider. * * Valid [Esri map styles](https://docs.aws.amazon.com/location/latest/developerguide/esri.html) * : * * * `VectorEsriNavigation` – The Esri Navigation map style, which provides a detailed basemap * for the world symbolized with a custom navigation map style that's designed for use during the * day in mobile devices. It also includes a richer set of places, such as shops, services, * restaurants, attractions, and other points of interest. Enable the `POI` layer by setting it in * CustomLayers to leverage the additional places data. * * `RasterEsriImagery` – The Esri Imagery map style. A raster basemap that provides one meter * or better satellite and aerial imagery in many parts of the world and lower resolution satellite * imagery worldwide. * * `VectorEsriLightGrayCanvas` – The Esri Light Gray Canvas map style, which provides a * detailed vector basemap with a light gray, neutral background style with minimal colors, labels, * and features that's designed to draw attention to your thematic content. * * `VectorEsriTopographic` – The Esri Light map style, which provides a detailed vector * basemap with a classic Esri map style. * * `VectorEsriStreets` – The Esri Street Map style, which provides a detailed vector basemap * for the world symbolized with a classic Esri street map style. The vector tile layer is similar * in content and style to the World Street Map raster map. * * `VectorEsriDarkGrayCanvas` – The Esri Dark Gray Canvas map style. A vector basemap with a * dark gray, neutral background with minimal colors, labels, and features that's designed to draw * attention to your thematic content. * * Valid [HERE Technologies map * styles](https://docs.aws.amazon.com/location/latest/developerguide/HERE.html) : * * * `VectorHereExplore` – A default HERE map style containing a neutral, global map and its * features including roads, buildings, landmarks, and water features. It also now includes a fully * designed map of Japan. * * `RasterHereExploreSatellite` – A global map containing high resolution satellite imagery. * * `HybridHereExploreSatellite` – A global map displaying the road network, street names, and * city labels over satellite imagery. This style will automatically retrieve both raster and * vector tiles, and your charges will be based on total tiles retrieved. * * * Hybrid styles use both vector and raster tiles when rendering the map that you see. This * means that more tiles are retrieved than when using either vector or raster tiles alone. Your * charges will include all tiles retrieved. * * * * `VectorHereContrast` – The HERE Contrast (Berlin) map style is a high contrast detailed * base map of the world that blends 3D and 2D rendering. * * * The `VectorHereContrast` style has been renamed from `VectorHereBerlin` . `VectorHereBerlin` * has been deprecated, but will continue to work in applications that use it. * * * * `VectorHereExploreTruck` – A global map containing truck restrictions and attributes (e.g. * width / height / HAZMAT) symbolized with highlighted segments and icons on top of HERE Explore * to support use cases within transport and logistics. * * Valid [GrabMaps map * styles](https://docs.aws.amazon.com/location/latest/developerguide/grab.html) : * * * `VectorGrabStandardLight` – The Grab Standard Light map style provides a basemap with * detailed land use coloring, area names, roads, landmarks, and points of interest covering * Southeast Asia. * * `VectorGrabStandardDark` – The Grab Standard Dark map style provides a dark variation of * the standard basemap covering Southeast Asia. * * * Grab provides maps only for countries in Southeast Asia, and is only available in the Asia * Pacific (Singapore) Region ( `ap-southeast-1` ). For more information, see [GrabMaps countries * and area * covered](https://docs.aws.amazon.com/location/latest/developerguide/grab.html#grab-coverage-area) * . * * * Valid [Open Data map * styles](https://docs.aws.amazon.com/location/latest/developerguide/open-data.html) : * * * `VectorOpenDataStandardLight` – The Open Data Standard Light map style provides a detailed * basemap for the world suitable for website and mobile application use. The map includes highways * major roads, minor roads, railways, water features, cities, parks, landmarks, building * footprints, and administrative boundaries. * * `VectorOpenDataStandardDark` – Open Data Standard Dark is a dark-themed map style that * provides a detailed basemap for the world suitable for website and mobile application use. The * map includes highways major roads, minor roads, railways, water features, cities, parks, * landmarks, building footprints, and administrative boundaries. * * `VectorOpenDataVisualizationLight` – The Open Data Visualization Light map style is a * light-themed style with muted colors and fewer features that aids in understanding overlaid * data. * * `VectorOpenDataVisualizationDark` – The Open Data Visualization Dark map style is a * dark-themed style with muted colors and fewer features that aids in understanding overlaid data. * * [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-location-map-mapconfiguration.html#cfn-location-map-mapconfiguration-style) */ public fun style(): String /** * A builder for [MapConfigurationProperty] */ @CdkDslMarker public interface Builder { /** * @param customLayers Specifies the custom layers for the style. * Leave unset to not enable any custom layer, or, for styles that support custom layers, you * can enable layer(s), such as the `POI` layer for the VectorEsriNavigation style. * * * Currenlty only `VectorEsriNavigation` supports CustomLayers. For more information, see * [Custom * Layers](https://docs.aws.amazon.com//location/latest/developerguide/map-concepts.html#map-custom-layers) * . */ public fun customLayers(customLayers: List<String>) /** * @param customLayers Specifies the custom layers for the style. * Leave unset to not enable any custom layer, or, for styles that support custom layers, you * can enable layer(s), such as the `POI` layer for the VectorEsriNavigation style. * * * Currenlty only `VectorEsriNavigation` supports CustomLayers. For more information, see * [Custom * Layers](https://docs.aws.amazon.com//location/latest/developerguide/map-concepts.html#map-custom-layers) * . */ public fun customLayers(vararg customLayers: String) /** * @param politicalView Specifies the map political view selected from an available data * provider. */ public fun politicalView(politicalView: String) /** * @param style Specifies the map style selected from an available data provider. * Valid [Esri map * styles](https://docs.aws.amazon.com/location/latest/developerguide/esri.html) : * * * `VectorEsriNavigation` – The Esri Navigation map style, which provides a detailed basemap * for the world symbolized with a custom navigation map style that's designed for use during the * day in mobile devices. It also includes a richer set of places, such as shops, services, * restaurants, attractions, and other points of interest. Enable the `POI` layer by setting it * in CustomLayers to leverage the additional places data. * * `RasterEsriImagery` – The Esri Imagery map style. A raster basemap that provides one * meter or better satellite and aerial imagery in many parts of the world and lower resolution * satellite imagery worldwide. * * `VectorEsriLightGrayCanvas` – The Esri Light Gray Canvas map style, which provides a * detailed vector basemap with a light gray, neutral background style with minimal colors, * labels, and features that's designed to draw attention to your thematic content. * * `VectorEsriTopographic` – The Esri Light map style, which provides a detailed vector * basemap with a classic Esri map style. * * `VectorEsriStreets` – The Esri Street Map style, which provides a detailed vector basemap * for the world symbolized with a classic Esri street map style. The vector tile layer is * similar in content and style to the World Street Map raster map. * * `VectorEsriDarkGrayCanvas` – The Esri Dark Gray Canvas map style. A vector basemap with a * dark gray, neutral background with minimal colors, labels, and features that's designed to * draw attention to your thematic content. * * Valid [HERE Technologies map * styles](https://docs.aws.amazon.com/location/latest/developerguide/HERE.html) : * * * `VectorHereExplore` – A default HERE map style containing a neutral, global map and its * features including roads, buildings, landmarks, and water features. It also now includes a * fully designed map of Japan. * * `RasterHereExploreSatellite` – A global map containing high resolution satellite imagery. * * `HybridHereExploreSatellite` – A global map displaying the road network, street names, * and city labels over satellite imagery. This style will automatically retrieve both raster and * vector tiles, and your charges will be based on total tiles retrieved. * * * Hybrid styles use both vector and raster tiles when rendering the map that you see. This * means that more tiles are retrieved than when using either vector or raster tiles alone. Your * charges will include all tiles retrieved. * * * * `VectorHereContrast` – The HERE Contrast (Berlin) map style is a high contrast detailed * base map of the world that blends 3D and 2D rendering. * * * The `VectorHereContrast` style has been renamed from `VectorHereBerlin` . * `VectorHereBerlin` has been deprecated, but will continue to work in applications that use it. * * * * `VectorHereExploreTruck` – A global map containing truck restrictions and attributes * (e.g. width / height / HAZMAT) symbolized with highlighted segments and icons on top of HERE * Explore to support use cases within transport and logistics. * * Valid [GrabMaps map * styles](https://docs.aws.amazon.com/location/latest/developerguide/grab.html) : * * * `VectorGrabStandardLight` – The Grab Standard Light map style provides a basemap with * detailed land use coloring, area names, roads, landmarks, and points of interest covering * Southeast Asia. * * `VectorGrabStandardDark` – The Grab Standard Dark map style provides a dark variation of * the standard basemap covering Southeast Asia. * * * Grab provides maps only for countries in Southeast Asia, and is only available in the Asia * Pacific (Singapore) Region ( `ap-southeast-1` ). For more information, see [GrabMaps countries * and area * covered](https://docs.aws.amazon.com/location/latest/developerguide/grab.html#grab-coverage-area) * . * * * Valid [Open Data map * styles](https://docs.aws.amazon.com/location/latest/developerguide/open-data.html) : * * * `VectorOpenDataStandardLight` – The Open Data Standard Light map style provides a * detailed basemap for the world suitable for website and mobile application use. The map * includes highways major roads, minor roads, railways, water features, cities, parks, * landmarks, building footprints, and administrative boundaries. * * `VectorOpenDataStandardDark` – Open Data Standard Dark is a dark-themed map style that * provides a detailed basemap for the world suitable for website and mobile application use. The * map includes highways major roads, minor roads, railways, water features, cities, parks, * landmarks, building footprints, and administrative boundaries. * * `VectorOpenDataVisualizationLight` – The Open Data Visualization Light map style is a * light-themed style with muted colors and fewer features that aids in understanding overlaid * data. * * `VectorOpenDataVisualizationDark` – The Open Data Visualization Dark map style is a * dark-themed style with muted colors and fewer features that aids in understanding overlaid * data. */ public fun style(style: String) } private class BuilderImpl : Builder { private val cdkBuilder: software.amazon.awscdk.services.location.CfnMap.MapConfigurationProperty.Builder = software.amazon.awscdk.services.location.CfnMap.MapConfigurationProperty.builder() /** * @param customLayers Specifies the custom layers for the style. * Leave unset to not enable any custom layer, or, for styles that support custom layers, you * can enable layer(s), such as the `POI` layer for the VectorEsriNavigation style. * * * Currenlty only `VectorEsriNavigation` supports CustomLayers. For more information, see * [Custom * Layers](https://docs.aws.amazon.com//location/latest/developerguide/map-concepts.html#map-custom-layers) * . */ override fun customLayers(customLayers: List<String>) { cdkBuilder.customLayers(customLayers) } /** * @param customLayers Specifies the custom layers for the style. * Leave unset to not enable any custom layer, or, for styles that support custom layers, you * can enable layer(s), such as the `POI` layer for the VectorEsriNavigation style. * * * Currenlty only `VectorEsriNavigation` supports CustomLayers. For more information, see * [Custom * Layers](https://docs.aws.amazon.com//location/latest/developerguide/map-concepts.html#map-custom-layers) * . */ override fun customLayers(vararg customLayers: String): Unit = customLayers(customLayers.toList()) /** * @param politicalView Specifies the map political view selected from an available data * provider. */ override fun politicalView(politicalView: String) { cdkBuilder.politicalView(politicalView) } /** * @param style Specifies the map style selected from an available data provider. * Valid [Esri map * styles](https://docs.aws.amazon.com/location/latest/developerguide/esri.html) : * * * `VectorEsriNavigation` – The Esri Navigation map style, which provides a detailed basemap * for the world symbolized with a custom navigation map style that's designed for use during the * day in mobile devices. It also includes a richer set of places, such as shops, services, * restaurants, attractions, and other points of interest. Enable the `POI` layer by setting it * in CustomLayers to leverage the additional places data. * * `RasterEsriImagery` – The Esri Imagery map style. A raster basemap that provides one * meter or better satellite and aerial imagery in many parts of the world and lower resolution * satellite imagery worldwide. * * `VectorEsriLightGrayCanvas` – The Esri Light Gray Canvas map style, which provides a * detailed vector basemap with a light gray, neutral background style with minimal colors, * labels, and features that's designed to draw attention to your thematic content. * * `VectorEsriTopographic` – The Esri Light map style, which provides a detailed vector * basemap with a classic Esri map style. * * `VectorEsriStreets` – The Esri Street Map style, which provides a detailed vector basemap * for the world symbolized with a classic Esri street map style. The vector tile layer is * similar in content and style to the World Street Map raster map. * * `VectorEsriDarkGrayCanvas` – The Esri Dark Gray Canvas map style. A vector basemap with a * dark gray, neutral background with minimal colors, labels, and features that's designed to * draw attention to your thematic content. * * Valid [HERE Technologies map * styles](https://docs.aws.amazon.com/location/latest/developerguide/HERE.html) : * * * `VectorHereExplore` – A default HERE map style containing a neutral, global map and its * features including roads, buildings, landmarks, and water features. It also now includes a * fully designed map of Japan. * * `RasterHereExploreSatellite` – A global map containing high resolution satellite imagery. * * `HybridHereExploreSatellite` – A global map displaying the road network, street names, * and city labels over satellite imagery. This style will automatically retrieve both raster and * vector tiles, and your charges will be based on total tiles retrieved. * * * Hybrid styles use both vector and raster tiles when rendering the map that you see. This * means that more tiles are retrieved than when using either vector or raster tiles alone. Your * charges will include all tiles retrieved. * * * * `VectorHereContrast` – The HERE Contrast (Berlin) map style is a high contrast detailed * base map of the world that blends 3D and 2D rendering. * * * The `VectorHereContrast` style has been renamed from `VectorHereBerlin` . * `VectorHereBerlin` has been deprecated, but will continue to work in applications that use it. * * * * `VectorHereExploreTruck` – A global map containing truck restrictions and attributes * (e.g. width / height / HAZMAT) symbolized with highlighted segments and icons on top of HERE * Explore to support use cases within transport and logistics. * * Valid [GrabMaps map * styles](https://docs.aws.amazon.com/location/latest/developerguide/grab.html) : * * * `VectorGrabStandardLight` – The Grab Standard Light map style provides a basemap with * detailed land use coloring, area names, roads, landmarks, and points of interest covering * Southeast Asia. * * `VectorGrabStandardDark` – The Grab Standard Dark map style provides a dark variation of * the standard basemap covering Southeast Asia. * * * Grab provides maps only for countries in Southeast Asia, and is only available in the Asia * Pacific (Singapore) Region ( `ap-southeast-1` ). For more information, see [GrabMaps countries * and area * covered](https://docs.aws.amazon.com/location/latest/developerguide/grab.html#grab-coverage-area) * . * * * Valid [Open Data map * styles](https://docs.aws.amazon.com/location/latest/developerguide/open-data.html) : * * * `VectorOpenDataStandardLight` – The Open Data Standard Light map style provides a * detailed basemap for the world suitable for website and mobile application use. The map * includes highways major roads, minor roads, railways, water features, cities, parks, * landmarks, building footprints, and administrative boundaries. * * `VectorOpenDataStandardDark` – Open Data Standard Dark is a dark-themed map style that * provides a detailed basemap for the world suitable for website and mobile application use. The * map includes highways major roads, minor roads, railways, water features, cities, parks, * landmarks, building footprints, and administrative boundaries. * * `VectorOpenDataVisualizationLight` – The Open Data Visualization Light map style is a * light-themed style with muted colors and fewer features that aids in understanding overlaid * data. * * `VectorOpenDataVisualizationDark` – The Open Data Visualization Dark map style is a * dark-themed style with muted colors and fewer features that aids in understanding overlaid * data. */ override fun style(style: String) { cdkBuilder.style(style) } public fun build(): software.amazon.awscdk.services.location.CfnMap.MapConfigurationProperty = cdkBuilder.build() } private class Wrapper( cdkObject: software.amazon.awscdk.services.location.CfnMap.MapConfigurationProperty, ) : CdkObject(cdkObject), MapConfigurationProperty { /** * Specifies the custom layers for the style. * * Leave unset to not enable any custom layer, or, for styles that support custom layers, you * can enable layer(s), such as the `POI` layer for the VectorEsriNavigation style. * * * Currenlty only `VectorEsriNavigation` supports CustomLayers. For more information, see * [Custom * Layers](https://docs.aws.amazon.com//location/latest/developerguide/map-concepts.html#map-custom-layers) * . * * * [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-location-map-mapconfiguration.html#cfn-location-map-mapconfiguration-customlayers) */ override fun customLayers(): List<String> = unwrap(this).getCustomLayers() ?: emptyList() /** * Specifies the map political view selected from an available data provider. * * [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-location-map-mapconfiguration.html#cfn-location-map-mapconfiguration-politicalview) */ override fun politicalView(): String? = unwrap(this).getPoliticalView() /** * Specifies the map style selected from an available data provider. * * Valid [Esri map * styles](https://docs.aws.amazon.com/location/latest/developerguide/esri.html) : * * * `VectorEsriNavigation` – The Esri Navigation map style, which provides a detailed basemap * for the world symbolized with a custom navigation map style that's designed for use during the * day in mobile devices. It also includes a richer set of places, such as shops, services, * restaurants, attractions, and other points of interest. Enable the `POI` layer by setting it * in CustomLayers to leverage the additional places data. * * `RasterEsriImagery` – The Esri Imagery map style. A raster basemap that provides one * meter or better satellite and aerial imagery in many parts of the world and lower resolution * satellite imagery worldwide. * * `VectorEsriLightGrayCanvas` – The Esri Light Gray Canvas map style, which provides a * detailed vector basemap with a light gray, neutral background style with minimal colors, * labels, and features that's designed to draw attention to your thematic content. * * `VectorEsriTopographic` – The Esri Light map style, which provides a detailed vector * basemap with a classic Esri map style. * * `VectorEsriStreets` – The Esri Street Map style, which provides a detailed vector basemap * for the world symbolized with a classic Esri street map style. The vector tile layer is * similar in content and style to the World Street Map raster map. * * `VectorEsriDarkGrayCanvas` – The Esri Dark Gray Canvas map style. A vector basemap with a * dark gray, neutral background with minimal colors, labels, and features that's designed to * draw attention to your thematic content. * * Valid [HERE Technologies map * styles](https://docs.aws.amazon.com/location/latest/developerguide/HERE.html) : * * * `VectorHereExplore` – A default HERE map style containing a neutral, global map and its * features including roads, buildings, landmarks, and water features. It also now includes a * fully designed map of Japan. * * `RasterHereExploreSatellite` – A global map containing high resolution satellite imagery. * * `HybridHereExploreSatellite` – A global map displaying the road network, street names, * and city labels over satellite imagery. This style will automatically retrieve both raster and * vector tiles, and your charges will be based on total tiles retrieved. * * * Hybrid styles use both vector and raster tiles when rendering the map that you see. This * means that more tiles are retrieved than when using either vector or raster tiles alone. Your * charges will include all tiles retrieved. * * * * `VectorHereContrast` – The HERE Contrast (Berlin) map style is a high contrast detailed * base map of the world that blends 3D and 2D rendering. * * * The `VectorHereContrast` style has been renamed from `VectorHereBerlin` . * `VectorHereBerlin` has been deprecated, but will continue to work in applications that use it. * * * * `VectorHereExploreTruck` – A global map containing truck restrictions and attributes * (e.g. width / height / HAZMAT) symbolized with highlighted segments and icons on top of HERE * Explore to support use cases within transport and logistics. * * Valid [GrabMaps map * styles](https://docs.aws.amazon.com/location/latest/developerguide/grab.html) : * * * `VectorGrabStandardLight` – The Grab Standard Light map style provides a basemap with * detailed land use coloring, area names, roads, landmarks, and points of interest covering * Southeast Asia. * * `VectorGrabStandardDark` – The Grab Standard Dark map style provides a dark variation of * the standard basemap covering Southeast Asia. * * * Grab provides maps only for countries in Southeast Asia, and is only available in the Asia * Pacific (Singapore) Region ( `ap-southeast-1` ). For more information, see [GrabMaps countries * and area * covered](https://docs.aws.amazon.com/location/latest/developerguide/grab.html#grab-coverage-area) * . * * * Valid [Open Data map * styles](https://docs.aws.amazon.com/location/latest/developerguide/open-data.html) : * * * `VectorOpenDataStandardLight` – The Open Data Standard Light map style provides a * detailed basemap for the world suitable for website and mobile application use. The map * includes highways major roads, minor roads, railways, water features, cities, parks, * landmarks, building footprints, and administrative boundaries. * * `VectorOpenDataStandardDark` – Open Data Standard Dark is a dark-themed map style that * provides a detailed basemap for the world suitable for website and mobile application use. The * map includes highways major roads, minor roads, railways, water features, cities, parks, * landmarks, building footprints, and administrative boundaries. * * `VectorOpenDataVisualizationLight` – The Open Data Visualization Light map style is a * light-themed style with muted colors and fewer features that aids in understanding overlaid * data. * * `VectorOpenDataVisualizationDark` – The Open Data Visualization Dark map style is a * dark-themed style with muted colors and fewer features that aids in understanding overlaid * data. * * [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-location-map-mapconfiguration.html#cfn-location-map-mapconfiguration-style) */ override fun style(): String = unwrap(this).getStyle() } public companion object { public operator fun invoke(block: Builder.() -> Unit = {}): MapConfigurationProperty { val builderImpl = BuilderImpl() return Wrapper(builderImpl.apply(block).build()) } internal fun wrap(cdkObject: software.amazon.awscdk.services.location.CfnMap.MapConfigurationProperty): MapConfigurationProperty = CdkObjectWrappers.wrap(cdkObject) as? MapConfigurationProperty ?: Wrapper(cdkObject) internal fun unwrap(wrapped: MapConfigurationProperty): software.amazon.awscdk.services.location.CfnMap.MapConfigurationProperty = (wrapped as CdkObject).cdkObject as software.amazon.awscdk.services.location.CfnMap.MapConfigurationProperty } } }
1
Kotlin
0
4
a18731816a3ec710bc89fb8767d2ab71cec558a6
49,427
kotlin-cdk-wrapper
Apache License 2.0
core/src/main/kotlin/com/vmadalin/core/network/responses/DataResponse.kt
vmadalin
192,786,158
false
null
/* * Copyright 2019 <EMAIL> * * 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.stepango.blockme.core.network.library.response import com.stepango.blockme.common.util.annotations.OpenForTesting /** * Marvel API data network response format. * * @param offset The requested offset (number of skipped results) of the call. * @param limit The requested result limit. * @param total The total number of resources available given the current filter set. * @param count The total number of results returned by this call. * @param results The list of [T] returned by the call. */ @OpenForTesting data class DataResponse<T>( val offset: Int, val limit: Int, val total: Int, val count: Int, val results: List<T> )
3
null
9
2,347
9fe0723a3bd515337df0837e528968785772e994
1,259
android-modular-architecture
Apache License 2.0
kotlin-mui/src/main/generated/mui/material/InputLabel.kt
JetBrains
93,250,841
false
null
// Automatically generated - do not modify! @file:JsModule("@mui/material/InputLabel") @file:JsNonModule @file:Suppress( "VIRTUAL_MEMBER_HIDDEN", ) package mui.material external interface InputLabelProps : mui.system.StandardProps, FormLabelProps, react.PropsWithChildren { /** * The content of the component. */ override var children: react.ReactNode? /** * Override or extend the styles applied to the component. */ var classes: InputLabelClasses? var color: FormLabelColor? /** * If `true`, the transition animation is disabled. * @default false */ var disableAnimation: Boolean? /** * If `true`, the component is disabled. */ var disabled: Boolean? /** * If `true`, the label is displayed in an error state. */ var error: Boolean? /** * If `true`, the `input` of this label is focused. */ var focused: Boolean? /** * If `dense`, will adjust vertical spacing. This is normally obtained via context from * FormControl. */ var margin: InputLabelMargin? /** * if `true`, the label will indicate that the `input` is required. */ var required: Boolean? /** * If `true`, the label is shrunk. */ var shrink: Boolean? /** * The system prop that allows defining system overrides as well as additional CSS styles. */ var sx: mui.system.SxProps<mui.system.Theme>? /** * The variant to use. */ var variant: InputLabelVariant? } /** * * Demos: * * - [Text Fields](https://mui.com/components/text-fields/) * * API: * * - [InputLabel API](https://mui.com/api/input-label/) * - inherits [FormLabel API](https://mui.com/api/form-label/) */ @JsName("default") external val InputLabel: react.FC<InputLabelProps>
12
Kotlin
145
983
a99345a0160a80a7a90bf1adfbfdc83a31a18dd6
1,850
kotlin-wrappers
Apache License 2.0
client/src/commonTest/kotlin/com/github/mustafaozhan/ccc/client/viewmodel/MainViewModelTest.kt
CurrencyConverterCalculator
102,633,334
false
null
/* * Copyright (c) 2021 <NAME>. All rights reserved. */ package com.github.mustafaozhan.ccc.client.viewmodel import com.github.mustafaozhan.ccc.client.device import com.github.mustafaozhan.ccc.client.model.Device import com.github.mustafaozhan.ccc.client.util.after import com.github.mustafaozhan.ccc.client.util.before import com.github.mustafaozhan.ccc.client.util.isRewardExpired import com.github.mustafaozhan.ccc.client.viewmodel.main.MainData.Companion.AD_DELAY_INITIAL import com.github.mustafaozhan.ccc.client.viewmodel.main.MainData.Companion.AD_DELAY_NORMAL import com.github.mustafaozhan.ccc.client.viewmodel.main.MainEffect import com.github.mustafaozhan.ccc.client.viewmodel.main.MainViewModel import com.github.mustafaozhan.ccc.common.settings.SettingsRepository import com.github.mustafaozhan.ccc.common.util.nowAsInstant import com.github.mustafaozhan.ccc.common.util.nowAsLong import com.github.mustafaozhan.logmob.initLogger import io.mockative.Mock import io.mockative.any import io.mockative.classOf import io.mockative.given import io.mockative.matching import io.mockative.mock import io.mockative.verify import kotlinx.datetime.DateTimePeriod import kotlinx.datetime.TimeZone import kotlinx.datetime.plus import kotlin.random.Random import kotlin.test.BeforeTest import kotlin.test.Test import kotlin.test.assertEquals import kotlin.test.assertNull import kotlin.test.assertTrue class MainViewModelTest { @Mock private val settingsRepository = mock(classOf<SettingsRepository>()) private val viewModel: MainViewModel by lazy { MainViewModel(settingsRepository) } @BeforeTest fun setup() { initLogger(true) given(settingsRepository) .getter(settingsRepository::lastReviewRequest) .whenInvoked() .thenReturn(0) given(settingsRepository) .setter(settingsRepository::lastReviewRequest) .whenInvokedWith(any()) .thenReturn(Unit) } // SEED @Test fun check_state_is_null() { assertNull(viewModel.state) } @Test fun adDelay_returns_correct_value() { viewModel.data.isInitialAd = true assertEquals(AD_DELAY_INITIAL, viewModel.data.adDelay) viewModel.data.isInitialAd = false assertEquals(AD_DELAY_NORMAL, viewModel.data.adDelay) } // init @Test fun set_lastReviewRequest_now_if_not_initialised_before() { given(settingsRepository) .getter(settingsRepository::lastReviewRequest) .whenInvoked() .thenReturn(0) viewModel // init verify(settingsRepository) .setter(settingsRepository::lastReviewRequest) .with(matching { it == nowAsLong() }) .wasInvoked() } // public methods @Test fun isFirstRun() { val boolean: Boolean = Random.nextBoolean() given(settingsRepository) .getter(settingsRepository::firstRun) .whenInvoked() .thenReturn(boolean) viewModel.isFistRun() verify(settingsRepository) .getter(settingsRepository::firstRun) .wasInvoked() assertEquals(boolean, viewModel.isFistRun()) } @Test fun getAppTheme() { val int: Int = Random.nextInt() given(settingsRepository) .getter(settingsRepository::appTheme) .whenInvoked() .thenReturn(int) viewModel.getAppTheme() verify(settingsRepository) .getter(settingsRepository::firstRun) .wasInvoked() assertEquals(int, viewModel.getAppTheme()) } @Test fun isAdFree() { val long: Long = Random.nextLong() given(settingsRepository) .getter(settingsRepository::adFreeEndDate) .whenInvoked() .thenReturn(long) viewModel.isAdFree() verify(settingsRepository) .getter(settingsRepository::firstRun) .wasInvoked() assertEquals(long, settingsRepository.adFreeEndDate) assertEquals(long.isRewardExpired(), viewModel.isAdFree()) } @Test fun checkReview() { if (device == Device.ANDROID.GOOGLE) { given(settingsRepository) .getter(settingsRepository::lastReviewRequest) .whenInvoked() .thenReturn( nowAsInstant().plus( DateTimePeriod(days = 8), TimeZone.currentSystemDefault() ).toEpochMilliseconds() ) viewModel.effect.before { viewModel.checkReview(0) }.after { assertTrue { it is MainEffect.RequestReview } verify(settingsRepository) .setter(settingsRepository::lastReviewRequest) .with(matching { it == nowAsLong() }) .wasInvoked() } } } // event @Test fun onPause() = with(viewModel) { event.onPause() assertEquals(false, data.adVisibility) assertEquals(true, data.adJob.isCancelled) } @Test fun onResume() = with(viewModel) { event.onResume() if (device is Device.ANDROID.GOOGLE || device is Device.IOS ) { assertEquals(true, data.adVisibility) assertEquals(true, data.adJob.isActive) } } }
15
Kotlin
20
151
f77f7d5c29cfd9781ed6fa3c31e2ed607552aba4
5,496
androidCCC
Apache License 2.0
compiler/testData/integration/ant/jvm/kt11995/test.kt
JakeWharton
99,388,807
true
null
package foo fun foo(a: Any) = foo(1) fun foo(i: Int) = "foo(Int)" fun main() { println(foo("")) }
181
Kotlin
5748
83
4383335168338df9bbbe2a63cb213a68d0858104
104
kotlin
Apache License 2.0
browser-kotlin/src/jsMain/kotlin/web/sse/EventSourceInit.kt
karakum-team
393,199,102
false
{"Kotlin": 6272741}
// Automatically generated - do not modify! package web.sse import kotlinx.js.JsPlainObject @JsPlainObject external interface EventSourceInit { val withCredentials: Boolean? }
0
Kotlin
8
36
95b065622a9445caf058ad2581f4c91f9e2b0d91
183
types-kotlin
Apache License 2.0
tracker/tracker_domain/src/main/java/com/jskako/tracker_domain/use_case/TrackFood.kt
jskako
597,251,147
false
null
package com.jskako.tracker_domain.use_case import com.jskako.tracker_domain.model.MealType import com.jskako.tracker_domain.model.TrackableFood import com.jskako.tracker_domain.model.TrackedFood import com.jskako.tracker_domain.repository.TrackerRepository import java.time.LocalDate import kotlin.math.roundToInt class TrackFood( private val repository: TrackerRepository ) { suspend operator fun invoke( food: TrackableFood, amount: Int, mealType: MealType, date: LocalDate ) { repository.insertTrackedFood( TrackedFood( name = food.name, carbs = ((food.carbsPer100g / 100f) * amount).roundToInt(), protein = ((food.proteinPer100g / 100f) * amount).roundToInt(), fat = ((food.fatPer100g / 100f) * amount).roundToInt(), calories = ((food.caloriesPer100g / 100f) * amount).roundToInt(), imageUrl = food.imageUrl, mealType = mealType, amount = amount, date = date, ) ) } }
0
Kotlin
0
0
1336351b14ef97162c58398a4cd12d7369ae1904
1,106
CalorieTracker
MIT License
src/main/kotlin/id/walt/services/jwt/WaltIdJwtService.kt
walt-id
392,607,264
false
null
package id.walt.services.jwt import com.nimbusds.jose.* import com.nimbusds.jose.crypto.* import com.nimbusds.jose.jwk.Curve import com.nimbusds.jose.jwk.JWK import com.nimbusds.jose.jwk.OctetKeyPair import com.nimbusds.jose.jwk.gen.OctetKeyPairGenerator import com.nimbusds.jwt.JWTClaimsSet import com.nimbusds.jwt.SignedJWT import id.walt.crypto.* import id.walt.model.DidUrl import id.walt.sdjwt.JwtVerificationResult import id.walt.services.did.DidService import id.walt.services.key.KeyService import mu.KotlinLogging import java.security.Provider import java.security.interfaces.ECPublicKey import java.util.* val keyId = "123" // FIXME static keyId open class WaltIdJwtService : JwtService() { private val log = KotlinLogging.logger {} val encKey: OctetKeyPair = OctetKeyPairGenerator(Curve.X25519).keyID(keyId).generate() open val keyService = KeyService.getService() open val provider: Provider = WaltIdProvider() override fun encrypt( kid: String, pubEncKey: OctetKeyPair, payload: String? ): String { val jweObject = JWEObject( JWEHeader.Builder(JWEAlgorithm.ECDH_ES, EncryptionMethod.A256GCM) .contentType("JWT") // required to indicate nested JWT .keyID(kid).build(), Payload(payload) ) val pubEncKeyJwt = pubEncKey.toPublicJWK() val encrypter = X25519Encrypter(pubEncKeyJwt) // encrypter.jcaContext.provider = waltIdProvider jweObject.encrypt(encrypter) return jweObject.serialize() } fun decrypt( jwe: String ): String { val jweObj = JWEObject.parse(jwe) val keyId = jweObj.header.keyID //TODO: key loading/storing //val encKey = KeyManagementService.load(keyId) if (encKey == null) { log.error { "Could not load verifying key for $keyId" } throw IllegalArgumentException("Could not load verifying key for $keyId") } val decrypter = X25519Decrypter(encKey) decrypter.jcaContext.provider = provider jweObj.decrypt(decrypter) return jweObj.payload.toString() } private fun createSignedJwt(jwsAlgorithm: JWSAlgorithm, keyAlias: String, claimsSet: JWTClaimsSet, includeJwk: JWK?) = SignedJWT( JWSHeader .Builder(jwsAlgorithm) .keyID(keyAlias) .type(JOSEObjectType.JWT) .apply { includeJwk?.let { jwk(it) } }.build(), claimsSet )/*.also { // log.debug { "Created signable JWT object: $it." } }*/ override fun sign( keyAlias: String, // verification method payload: String? ): String { // Default JWT claims // val claimsSet = JWTClaimsSet.Builder() // .subject("alice") // .issuer("https://c2id.com") // .expirationTime(Date(Date().getTime() + 60 * 1000)) // .build() val claimsSet = if (payload != null) JWTClaimsSet.parse(payload) else JWTClaimsSet.Builder().subject(keyAlias) .issuer("https://walt.id").expirationTime(Date(Date().time + 60 * 1000)).build() val issuerKey = keyService.load(keyAlias) if (issuerKey == null) { log.error { "Could not load signing key for $keyAlias" } throw IllegalArgumentException("Could not load signing key for $keyAlias") } log.debug { "Signing JWT with algorithm: ${issuerKey.algorithm}" } val includeJwk: JWK? = if (DidService.isDidEbsiV2(keyAlias)) { keyService.toJwk(keyAlias).toPublicJWK() } else { null } val signedJwt = when (issuerKey.algorithm) { KeyAlgorithm.EdDSA_Ed25519 -> { val jwt = createSignedJwt(JWSAlgorithm.EdDSA, keyAlias, claimsSet, includeJwk) //jwt.sign(Ed25519Signer(issuerKey.toOctetKeyPair())) jwt.sign(LdSigner.JwsLtSigner(issuerKey.keyId)) jwt } KeyAlgorithm.ECDSA_Secp256k1 -> { val jwt = createSignedJwt(JWSAlgorithm.ES256K, keyAlias, claimsSet, includeJwk) val jwsSigner = ECDSASigner(ECPrivateKeyHandle(issuerKey.keyId), Curve.SECP256K1) jwsSigner.jcaContext.provider = provider jwt.sign(jwsSigner) jwt } KeyAlgorithm.ECDSA_Secp256r1 -> { val jwt = createSignedJwt(JWSAlgorithm.ES256, keyAlias, claimsSet, includeJwk) val jwsSigner = ECDSASigner(ECPrivateKeyHandle(issuerKey.keyId), Curve.P_256) jwsSigner.jcaContext.provider = provider jwt.sign(jwsSigner) jwt } else -> { log.error { "Algorithm ${issuerKey.algorithm} not supported" } throw UnsupportedOperationException("Algorithm ${issuerKey.algorithm} not supported") } } val serializedSignedJwt = signedJwt.serialize() log.debug { "Signed JWT: $serializedSignedJwt" } return serializedSignedJwt } override fun verify(token: String): JwtVerificationResult { log.debug { "Verifying token: $token" } val jwt = SignedJWT.parse(token) val issuer = jwt.jwtClaimsSet.issuer val keyAlias = jwt.header.keyID.orEmpty().ifEmpty { issuer } if (DidUrl.isDidUrl(keyAlias)) { // issuer is a valid DID if (DidService.isDidEbsiV2(keyAlias) && jwt.header.jwk != null) { DidService.importKeyForDidEbsiV2(DidUrl.from(keyAlias).did, jwt.header.jwk) } else if (!DidService.importKeys(DidUrl.from(keyAlias).did)) { throw IllegalArgumentException("Could not resolve verification keys") } } val verifierKey = keyService.load(keyAlias) val res = when (verifierKey.algorithm) { KeyAlgorithm.EdDSA_Ed25519 -> jwt.verify(Ed25519Verifier(keyService.toEd25519Jwk(verifierKey))) KeyAlgorithm.ECDSA_Secp256k1 -> { val verifier = ECDSAVerifier(PublicKeyHandle(verifierKey.keyId, verifierKey.getPublicKey() as ECPublicKey)) verifier.jcaContext.provider = provider jwt.verify(verifier) } KeyAlgorithm.ECDSA_Secp256r1 -> { val verifier = ECDSAVerifier(PublicKeyHandle(verifierKey.keyId, verifierKey.getPublicKey() as ECPublicKey)) verifier.jcaContext.provider = provider jwt.verify(verifier) } else -> { log.error { "Algorithm ${verifierKey.algorithm} not supported" } throw UnsupportedOperationException("Algorithm ${verifierKey.algorithm} not supported") } } log.debug { "JWT verified returned: $res" } return JwtVerificationResult(res) } override fun parseClaims(token: String): MutableMap<String, Any>? { val jwt = SignedJWT.parse(token) val claimsMap = jwt.jwtClaimsSet.claims return claimsMap } }
7
null
28
83
df8d5cf6bd8c1804a8eb5867f348b15e8e551eeb
7,176
waltid-ssikit
Apache License 2.0
uast/uast-java/src/org/jetbrains/uast/java/expressions/JavaUPostfixExpression.kt
hieuprogrammer
284,920,751
true
null
/* * Copyright 2000-2017 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.jetbrains.uast.java import com.intellij.psi.JavaTokenType import com.intellij.psi.PsiPostfixExpression import org.jetbrains.uast.* class JavaUPostfixExpression( override val sourcePsi: PsiPostfixExpression, givenParent: UElement? ) : JavaAbstractUExpression(givenParent), UPostfixExpression { override val operand: UExpression by lz { JavaConverter.convertOrEmpty(sourcePsi.operand, this) } override val operatorIdentifier: UIdentifier? get() = UIdentifier(sourcePsi.operationSign, this) override fun resolveOperator(): Nothing? = null override val operator: UastPostfixOperator = when (sourcePsi.operationTokenType) { JavaTokenType.PLUSPLUS -> UastPostfixOperator.INC JavaTokenType.MINUSMINUS -> UastPostfixOperator.DEC else -> UastPostfixOperator.UNKNOWN } }
191
null
4372
2
dc846ecb926c9d9589c1ed8a40fdb20e47874db9
1,408
intellij-community
Apache License 2.0
{{cookiecutter.repo_name}}/app/src/main/java/di/component/ApplicationComponent.kt
elsameinar-i
532,148,282
false
{"Kotlin": 62197, "Python": 5451}
package {{ cookiecutter.package_name }}.di.component import android.content.Context import android.content.SharedPreferences import dagger.Component import {{ cookiecutter.package_name }}.App import {{ cookiecutter.package_name }}.di.module.* import {{ cookiecutter.package_name }}.ui.main.MainActivityViewModel {% if cookiecutter.login_page == "y" %} import {{ cookiecutter.package_name }}.ui.login.LoginViewModel {% endif %} import javax.inject.Singleton @Singleton @Component(modules = [ ApplicationModule::class, InterceptorModule::class, NetModule::class, DatabaseModule::class, RepositoryModule::class ]) interface ApplicationComponent { fun app(): App fun context(): Context fun preferences(): SharedPreferences fun inject(mainActivityViewModel: MainActivityViewModel) {% if cookiecutter.login_page == "y" %} fun inject(loginViewModel: LoginViewModel) {% endif %} }
0
Kotlin
0
0
1bd5f6e774e8dd749d53e6d3a960341dc97152b3
929
mobile-android
MIT License
app/src/main/java/com/aappeye/foreksty/data/db/CurrentWeatherDao.kt
ihjohny
198,017,929
false
null
package com.aappeye.foreksty.data.db import androidx.lifecycle.LiveData import androidx.room.Dao import androidx.room.Insert import androidx.room.OnConflictStrategy import androidx.room.Query import com.aappeye.foreksty.data.db.entity.CURRENT_WEATHER_ID import com.aappeye.foreksty.data.db.entity.CurrentWeatherEntry @Dao interface CurrentWeatherDao { @Insert(onConflict = OnConflictStrategy.REPLACE) fun upsert(weatherEntry: CurrentWeatherEntry) @Query("SELECT * FROM current_weather WHERE id = $CURRENT_WEATHER_ID") fun getWeather() : LiveData<CurrentWeatherEntry> }
0
Kotlin
0
5
30f80e8f604b92bce1e7c13b8bc9e260d57980a1
587
Foreksty
Apache License 2.0
presentation/src/main/java/com/sms/presentation/main/ui/detail/StudentInfoComponent.kt
GSM-MSG
625,706,722
false
null
package com.sms.presentation.main.ui.detail import android.content.Intent import android.net.Uri import androidx.compose.foundation.layout.* import androidx.compose.material.Text import androidx.compose.runtime.Composable import androidx.compose.ui.Modifier import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.unit.dp import com.msg.sms.design.component.button.SmsRoundedButton import com.msg.sms.design.component.divider.SmsDivider import com.msg.sms.design.theme.SMSTheme import com.msg.sms.domain.model.student.response.CertificationModel import com.sms.presentation.main.ui.fill_out_information.data.CertificationData import com.sms.presentation.main.ui.fill_out_information.data.WorkConditionData @Composable fun StudentInfoComponent( modifier: Modifier, portfolioLink: String, gsmAuthenticationScore: String, email: String, militaryService: String, workConditionData: WorkConditionData, certificationData: CertificationData, foreignLanguage: List<CertificationModel>, ) { val context = LocalContext.current val titleTextModifier = Modifier .fillMaxWidth(0.4f) .padding(vertical = 8.dp) val contentTextModifier = Modifier .fillMaxWidth(0.6f) .padding(8.dp) Column( modifier = modifier .fillMaxWidth() .padding(bottom = 20.dp) ) { Spacer(modifier = Modifier.height(32.dp)) SMSTheme { colors, typography -> val titleColor = colors.BLACK val contentColor = colors.N40 val titleTypography = typography.body1 val contentTypography = typography.body2 Row(Modifier.fillMaxWidth()) { Text( text = "이메일", modifier = titleTextModifier, color = titleColor, style = titleTypography ) Text( text = email, modifier = contentTextModifier, color = contentColor, style = contentTypography ) } Row(Modifier.fillMaxWidth()) { Text( text = "인증제점수", modifier = titleTextModifier, color = titleColor, style = titleTypography ) Text( text = gsmAuthenticationScore, modifier = contentTextModifier, color = contentColor, style = contentTypography ) } SmsDivider(modifier = Modifier.padding(vertical = 8.dp)) Row(Modifier.fillMaxWidth()) { Text( text = "병특 희망 여부", modifier = titleTextModifier, color = titleColor, style = titleTypography ) Text( text = militaryService, modifier = contentTextModifier, color = contentColor, style = contentTypography ) } Row(Modifier.fillMaxWidth()) { Text( text = "희망 고용 형태", modifier = titleTextModifier, color = titleColor, style = titleTypography ) Text( text = workConditionData.formOfEmployment, modifier = contentTextModifier, color = contentColor, style = contentTypography ) } Row(Modifier.fillMaxWidth()) { Text( text = "희망 연봉", modifier = titleTextModifier, color = titleColor, style = titleTypography ) Text( text = workConditionData.salary, modifier = contentTextModifier, color = contentColor, style = contentTypography ) } SmsDivider(modifier = Modifier.padding(vertical = 8.dp)) Row(Modifier.fillMaxWidth()) { Text( text = "근무 희망 지역", modifier = titleTextModifier, color = titleColor, style = titleTypography ) Text( text = workConditionData.region.joinToString(", "), modifier = contentTextModifier, color = contentColor, style = contentTypography ) } if (foreignLanguage.isNotEmpty()) { SmsDivider(modifier = Modifier.padding(vertical = 8.dp)) Column(Modifier.fillMaxWidth()) { foreignLanguage.forEach { Row { Text( text = it.languageCertificateName, modifier = titleTextModifier, color = titleColor, style = titleTypography ) Text( text = it.score, modifier = contentTextModifier, color = contentColor, style = contentTypography ) } } } } if (certificationData.certification.isNotEmpty()) { SmsDivider(modifier = Modifier.padding(vertical = 8.dp)) Row(Modifier.fillMaxWidth()) { Text( text = "자격증", modifier = titleTextModifier, color = titleColor, style = titleTypography ) Column { certificationData.certification.forEach { Text( text = it, modifier = contentTextModifier, color = contentColor, style = contentTypography ) } } } } Spacer(modifier = Modifier.height(44.dp)) SmsRoundedButton( text = "포트폴리오", modifier = Modifier .fillMaxWidth() .height(48.dp) ) { val urlIntent = Intent( Intent.ACTION_VIEW, Uri.parse(portfolioLink) ) context.startActivity(urlIntent) } } } }
3
Kotlin
1
8
4bcc7f105b0d4358f378549eb359fc894b3a74c2
7,002
SMS-Android
MIT License
coroutines/src/main/kotlin/br/com/devsrsouza/kotlinbukkitapi/coroutines/architecture/impl/CoroutineLifecycle.kt
DevSrSouza
123,673,532
false
null
package br.com.devsrsouza.kotlinbukkitapi.architecture.lifecycle.extensions.impl import br.com.devsrsouza.kotlinbukkitapi.architecture.KotlinPlugin import br.com.devsrsouza.kotlinbukkitapi.architecture.lifecycle.LifecycleListener import br.com.devsrsouza.kotlinbukkitapi.architecture.lifecycle.getOrInsertGenericLifecycle import br.com.devsrsouza.kotlinbukkitapi.collections.onlinePlayerMapOf import br.com.devsrsouza.kotlinbukkitapi.extensions.skedule.BukkitDispatchers import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Job import kotlinx.coroutines.SupervisorJob import org.bukkit.entity.Player internal fun KotlinPlugin.getOrInsertCoroutineLifecycle(): CoroutineLifecycle { return getOrInsertGenericLifecycle(Int.MIN_VALUE) { CoroutineLifecycle(this) } } internal class CoroutineLifecycle( override val plugin: KotlinPlugin ) : LifecycleListener<KotlinPlugin> { inner class PlayerCoroutineScope( val job: Job, val coroutineScope: CoroutineScope ) { fun cancelJobs() = job.cancel() } private val job = SupervisorJob() val pluginCoroutineScope = CoroutineScope(BukkitDispatchers.SYNC + job) private val playersCoroutineScope by lazy { onlinePlayerMapOf<PlayerCoroutineScope>() } override fun onPluginEnable() {} override fun onPluginDisable() { job.cancel() for (scopes in playersCoroutineScope.values) { scopes.cancelJobs() } } fun getPlayerCoroutineScope(player: Player): CoroutineScope { return playersCoroutineScope[player]?.coroutineScope ?: newPlayerCoroutineScope().also { playersCoroutineScope.put(player, it) { playerCoroutineScope -> playerCoroutineScope.cancelJobs() } }.coroutineScope } private fun newPlayerCoroutineScope(): PlayerCoroutineScope { val job = SupervisorJob() return PlayerCoroutineScope( job, CoroutineScope(BukkitDispatchers.SYNC + job) ) } }
11
null
22
144
14874b92734a0273b4e7a748391a6e449bbaae1d
2,116
KotlinBukkitAPI
MIT License
sample-plugin/src/main/java/cn/jessie/sample/plugin/PluginLog.kt
androlua
227,565,051
true
{"Kotlin": 259239, "Java": 11121, "HTML": 996}
package cn.jessie.etc import android.util.Log import android.util.LruCache import cn.jessie.main.MainAppContext import java.io.PrintWriter import java.io.StringWriter import java.util.* interface LogIgnored @Suppress("SpellCheckingInspection", "unused") interface Logdog : LogIgnored { fun isLoggable(priority: Int, tag: String): Boolean fun tag(tag: String): Logdog fun log(priority: Int, tag: String, fn: () -> String): Logdog fun debug(any: Any?): Logdog fun warn(any: Any?): Logdog fun error(any: Any?): Logdog fun wtf(sure: Boolean, any: Any?): Logdog fun time(name: String): Logdog fun count(name: String): Logdog fun memory(): Logdog fun trace(): Logdog companion object : Logdog by Logger() { private var logcatTagPrefix = 0 private const val LRU_CACHE_MAX_SIZE = 256 private val timers = LruCache<String, Long>(LRU_CACHE_MAX_SIZE) private val counters = LruCache<String, Long>(LRU_CACHE_MAX_SIZE) override fun isLoggable(priority: Int, tag: String): Boolean { return MainAppContext.debug } } private open class Logger : Logdog { protected open val tag = "@JC" override fun tag(tag: String): Logdog { val self = this return object : Logger() { override val tag: String = tag override fun isLoggable(priority: Int, tag: String): Boolean { return self.isLoggable(priority, tag) } override fun log(priority: Int, tag: String, fn: () -> String): Logdog { return self.log(priority, tag, fn) } } } override fun isLoggable(priority: Int, tag: String) = true @Synchronized override fun log(priority: Int, tag: String, fn: () -> String): Logdog { if (!isLoggable(priority, tag)) return this val style = getStyle(priority) println(priority, style.top) run { val methodCount = 1 val methodOffset = 0 val trace = Thread.currentThread().stackTrace val stackOffset = getStackOffset(trace) + methodOffset val headerLineCount = Math.min(methodCount, trace.size - 1 - stackOffset) var offset = "" for (i in 0 until headerLineCount) { val stackIndex = i + stackOffset println(priority, style.middle + offset + trace[stackIndex].prettyInfo()) offset += " " } if (headerLineCount > 0) { println(priority, style.divider) } } run { val message = fn() val chunkSize = 4 * 1024 val bytes = message.toByteArray() val length = bytes.size val pageSize = (length - 1) / chunkSize + 1 for (i in 0 until pageSize) { val offset = i * chunkSize val count = Math.min(length - offset, chunkSize) val chunk = String(bytes, offset, count, Charsets.UTF_8) val lines = chunk.split('\n').dropLastWhile { it.isEmpty() }.toTypedArray() for (line in lines) { println(priority, style.middle + line) } } } println(priority, style.bottom) return this } private fun println(priority: Int, text: String) { logcatTagPrefix = (logcatTagPrefix + 1) % 10 Log.println(priority, "$logcatTagPrefix.$tag", text) } override fun debug(any: Any?): Logdog { return log(Log.DEBUG, tag) { stringify(any) } } override fun warn(any: Any?): Logdog { return log(Log.WARN, tag) { stringify(any) } } override fun error(any: Any?): Logdog { return log(Log.ERROR, tag) { stringify(any) } } override fun wtf(sure: Boolean, any: Any?): Logdog { if (sure) return this return log(Log.ASSERT, tag) { stringify(any) } } override fun time(name: String): Logdog { return log(Log.DEBUG, tag) { val currentTime = System.currentTimeMillis() val lastTime = timers[name] ?: currentTime timers.put(name, currentTime) "time($name): ${currentTime - lastTime}ms" } } override fun count(name: String): Logdog { return log(Log.DEBUG, tag) { val lastCount = counters[name] ?: 0L counters.put(name, lastCount + 1) "count($name): ${lastCount + 1}" } } override fun memory(): Logdog { return log(Log.DEBUG, tag) { val runtime = Runtime.getRuntime() """ total memory: ${runtime.totalMemory()} free memory: ${runtime.freeMemory()} max memory: ${runtime.maxMemory()} """.trimIndent() } } override fun trace(): Logdog { return log(Log.DEBUG, tag) { val trace = Thread.currentThread().stackTrace val buffer = StringBuilder() var offset = "" for (e in trace) { val className = e.className.substring(e.className.lastIndexOf(".") + 1) if (offset.isNotEmpty()) buffer.append("\n") buffer.append(offset).append(className).append(".").append(e.methodName) .append(" (").append(e.fileName).append(":").append(e.lineNumber).append(")") offset += " " } buffer.toString() } } private fun StackTraceElement.prettyInfo(): String { val className = className.substring(className.lastIndexOf(".") + 1) val threadName = Thread.currentThread().name return "$className.$methodName ($fileName:$lineNumber) on Thread: $threadName" } private fun getStackOffset(trace: Array<StackTraceElement>): Int { var isInOffsetClass = false for (i in 0 until trace.size) { val traceElement = trace[i] val cls = Class.forName(traceElement.className) if (LogIgnored::class.java.isAssignableFrom(cls)) { isInOffsetClass = true } else if (isInOffsetClass) { return i } } return 0 } private fun getStyle(priority: Int): PrettyStyle { return if (priority > Log.DEBUG) PrettyStyle.DOUBLE else PrettyStyle.SINGLE } private fun stringify(any: Any?): String { return when (any) { null -> "null" is String -> any !javaClass.isArray -> any.toString() is BooleanArray -> Arrays.toString(any) is ByteArray -> Arrays.toString(any) is CharArray -> Arrays.toString(any) is ShortArray -> Arrays.toString(any) is IntArray -> Arrays.toString(any) is LongArray -> Arrays.toString(any) is FloatArray -> Arrays.toString(any) is DoubleArray -> Arrays.toString(any) is Array<*> -> Arrays.deepToString(any) is Throwable -> getStackTraceString(any) else -> any.toString() } } private fun getStackTraceString(throwable: Throwable): String { val stringWriter = StringWriter() val printWriter = PrintWriter(stringWriter) throwable.printStackTrace(printWriter) printWriter.flush() return stringWriter.toString() } } private data class PrettyStyle(val top: String, val divider: String, val middle: String, val bottom: String) { companion object { private const val EMPTY = "" private const val SINGLE_PART = "────────────────────────────" private const val DASHED_PART = "┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄" private const val DOUBLE_PART = "════════════════════════════" private const val SINGLE_LINE = SINGLE_PART + SINGLE_PART + SINGLE_PART + SINGLE_PART private const val DASHED_LINE = DASHED_PART + DASHED_PART + DASHED_PART + DASHED_PART private const val DOUBLE_LINE = DOUBLE_PART + DOUBLE_PART + DOUBLE_PART + DOUBLE_PART private const val SINGLE_TOP = "┌$SINGLE_LINE" private const val SINGLE_DIV = "├$DASHED_LINE" private const val SINGLE_MID = "│ " private const val SINGLE_BOT = "└$SINGLE_LINE" private const val DOUBLE_TOP = "╔$DOUBLE_LINE" private const val DOUBLE_DIV = "╟$DASHED_LINE" private const val DOUBLE_MID = "║ " private const val DOUBLE_BOT = "╚$DOUBLE_LINE" val SINGLE = PrettyStyle(SINGLE_TOP, SINGLE_DIV, SINGLE_MID, SINGLE_BOT) val DOUBLE = PrettyStyle(DOUBLE_TOP, DOUBLE_DIV, DOUBLE_MID, DOUBLE_BOT) val NONE = PrettyStyle(EMPTY, EMPTY, EMPTY, EMPTY) } } }
0
null
0
0
97df8fc44063770b8b4019f07e285b2ba9cf28b5
9,475
jessie
MIT License
app/src/main/java/com/whatsappstatusdownloader/jayanthl/statusdownloaderwhatsapp/Tab4Fragment.kt
Jayanth-L
197,514,750
false
null
package com.whatsappstatusdownloader.jayanthl.statusdownloaderwhatsapp import android.support.v4.app.Fragment import android.os.Bundle import android.os.Environment import android.support.v7.widget.LinearLayoutManager import android.support.v7.widget.RecyclerView import android.support.v7.widget.StaggeredGridLayoutManager import android.util.Log import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.Button import android.widget.Toast import java.io.File class Tab4Fragment : Fragment() { private val TAG: String = "Tab4Fragment" override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? { var view: View = inflater.inflate(R.layout.tab4_fragment, container, false) var recyclerView: RecyclerView = view.findViewById(R.id.recyclerview4) var videoStatusPath: String = Environment.getExternalStorageDirectory().toString() + "/StatusWhatsApp/Videos/" var videoImageList: MutableList<String> = mutableListOf() File(videoStatusPath).walk().forEach { videoImageList.add("$it") } videoImageList.removeAt(0) var adapter = RecyclerViewDownloadImageAdapter(activity!!.applicationContext, videoImageList) adapter.notifyDataSetChanged() var staggeredGridLayoutManager = StaggeredGridLayoutManager(3,LinearLayoutManager.VERTICAL) recyclerView.setHasFixedSize(true) recyclerView.setItemViewCacheSize(20) recyclerView.isDrawingCacheEnabled = true recyclerView.drawingCacheQuality = View.DRAWING_CACHE_QUALITY_HIGH recyclerView.layoutManager = staggeredGridLayoutManager recyclerView.adapter = adapter return view } }
0
Kotlin
1
2
f0361d8c06649bcf52fb4a541a4c87ebfb55ebab
1,789
statusdownloaderforwhatsapp
Apache License 2.0
app/src/main/java/com/vpr/places_together/ui/NavGraphActivity.kt
v1p3rrr
633,636,972
false
null
package com.vpr.places_together.ui import android.os.Bundle import android.view.Menu import androidx.appcompat.app.AppCompatActivity import androidx.navigation.NavController import androidx.navigation.fragment.NavHostFragment import com.vpr.places_together.R import com.vpr.places_together.databinding.ActivityNavGraphBinding import dagger.hilt.android.AndroidEntryPoint @AndroidEntryPoint class NavGraphActivity : AppCompatActivity() { private lateinit var binding: ActivityNavGraphBinding private lateinit var navController: NavController override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) binding = ActivityNavGraphBinding.inflate(layoutInflater) setContentView(binding.root) setSupportActionBar(binding.topAppBar) val navHostFragment = supportFragmentManager.findFragmentById(R.id.nav_host_fragment) as NavHostFragment navController = navHostFragment.navController //todo split repositories for map/users/groups(?)/map objects } }
0
Kotlin
0
0
fc71609d48dbefd64950061c079f99cb599b5b25
1,055
places-together
MIT License
demo-kotlin/src/main/java/me/yokeyword/sample/zhihu/ui/fragment/CycleFragment.kt
qdsfdhvh
166,903,972
true
{"Java": 215233, "Kotlin": 205707}
package me.yokeyword.sample.zhihu.ui.fragment import android.os.Bundle import android.view.View import kotlinx.android.synthetic.main.fragment_cycle.* import kotlinx.android.synthetic.main.toolbar.* import me.yokeyword.fragmentation.start import me.yokeyword.fragmentation.startWithPop import me.yokeyword.sample.R import me.yokeyword.sample.base.BaseFragment import me.yokeyword.sample.base.initToolbarNav /** * Created by YoKeyword on 16/2/7. */ class CycleFragment : BaseFragment() { override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) val num = arguments?.getInt(ARG_NUMBER) ?: 0 val title = "CycleFragment $num" initToolbarNav(toolbar, title) tv_name.text = title btn_next_with_finish.setOnClickListener { startWithPop(CycleFragment.newInstance(num + 1)) } btn_next.setOnClickListener { start(CycleFragment.newInstance(num + 1)) } } override fun getLayoutId() = R.layout.fragment_cycle companion object { private const val ARG_NUMBER = "arg_number" fun newInstance(number: Int): CycleFragment { val args = Bundle() args.putInt(ARG_NUMBER, number) val fragment = CycleFragment() fragment.arguments = args return fragment } } }
0
Java
0
0
3ddb2fe6ee7f8519e78ef0a5806bd217329ed023
1,407
Fragmentation
Apache License 2.0
services/csm.cloud.project.api.timeseries/src/test/kotlin/com/bosch/pt/csm/cloud/projectmanagement/application/config/GraphQlTestConfiguration.kt
boschglobal
805,348,245
false
{"Kotlin": 13156190, "HTML": 274761, "Go": 184388, "HCL": 158560, "Shell": 117666, "Java": 52634, "Python": 51306, "Dockerfile": 10348, "Vim Snippet": 3969, "CSS": 344}
/* * ************************************************************************ * * Copyright: Robert Bosch Power Tools GmbH, 2018 - 2023 * * ************************************************************************ */ package com.bosch.pt.csm.cloud.projectmanagement.application.config import org.springframework.context.annotation.Bean import org.springframework.context.annotation.Configuration import org.springframework.graphql.test.tester.HttpGraphQlTester import org.springframework.test.web.reactive.server.WebTestClient import org.springframework.test.web.servlet.client.MockMvcWebTestClient import org.springframework.web.context.WebApplicationContext @Configuration class GraphQlTestConfiguration { @Bean fun graphQlClient(webApplicationContext: WebApplicationContext): WebTestClient = MockMvcWebTestClient.bindToApplicationContext(webApplicationContext) .configureClient() .baseUrl("/graphql") .build() @Bean fun graphQlTester(graphQlClient: WebTestClient): HttpGraphQlTester = HttpGraphQlTester.create(graphQlClient) }
0
Kotlin
3
9
9f3e7c4b53821bdfc876531727e21961d2a4513d
1,097
bosch-pt-refinemysite-backend
Apache License 2.0
arcade-minigames/src/main/kotlin/net/casual/arcade/minigame/task/impl/NameTagTask.kt
CasualChampionships
621,955,934
false
{"Kotlin": 981165, "Java": 176720, "GLSL": 4396}
package net.casual.arcade.minigame.task.impl import net.casual.arcade.minigame.Minigame import net.casual.arcade.scheduler.task.Task import net.casual.arcade.visuals.nametag.PlayerNameTag public open class NameTagTask( private val minigame: Minigame<*>, private val tag: PlayerNameTag ): Task { init { this.minigame.ui.addNameTag(this.tag) } final override fun run() { this.minigame.ui.removeNameTag(this.tag) } }
1
Kotlin
1
2
b78dd42472d500120dbb3e2670cb67652da4449b
456
arcade
MIT License
packages/expo-modules-core/android/src/test/java/expo/modules/benchmarks/NewArchitectureBenchmark.kt
betomoedano
462,599,485
false
null
package expo.modules.benchmarks import com.facebook.react.bridge.Dynamic import com.facebook.react.bridge.DynamicFromObject import com.facebook.react.bridge.JavaOnlyArray import com.facebook.react.bridge.ReadableArray import expo.modules.adapters.react.NativeModulesProxy import expo.modules.kotlin.ModulesProvider import expo.modules.kotlin.modules.Module import expo.modules.kotlin.modules.ModuleDefinition import org.junit.Before import org.junit.Ignore import org.junit.Test class NewArchitectureBenchmark { private val benchmarkRule = BenchmarkRule(iteration = 1000000) private lateinit var proxy: NativeModulesProxy class MyModule : Module() { private fun retNull(): Any? { return null } override fun definition() = ModuleDefinition { name("MyModule") function("m1") { -> retNull() } function("m2") { _: Int, _: Int -> retNull() } function("m3") { _: IntArray -> retNull() } function("m4") { _: String -> retNull() } } } @Before fun before() { val legacyModuleRegister = expo.modules.core.ModuleRegistry( emptyList(), emptyList(), emptyList(), emptyList() ) proxy = NativeModulesProxy( null, legacyModuleRegister, object : ModulesProvider { override fun getModulesList(): List<Class<out Module>> = listOf(MyModule::class.java) } ) } @Ignore("It's a benchmark") @Test fun `call function with simple arguments`() { val testCases = listOf<Pair<Dynamic, ReadableArray>>( DynamicFromObject("m1") to JavaOnlyArray(), DynamicFromObject("m2") to JavaOnlyArray().apply { pushInt(1) pushInt(2) }, DynamicFromObject("m3") to JavaOnlyArray().apply { pushArray( JavaOnlyArray().apply { pushInt(1) pushInt(2) pushInt(3) } ) }, DynamicFromObject("m4") to JavaOnlyArray().apply { pushString("expo is awesome") } ) val emptyPromise = EmptyRNPromise() repeat(3) { benchmarkRule.run(::`call function with simple arguments`.name) { testCases.forEach { (method, args) -> proxy.callMethod("MyModule", method, args, emptyPromise) } } } } }
1
null
1
4
52d6405570a39a87149648d045d91098374f4423
2,276
expo
MIT License
src/main/kotlin/com/networkedassets/gherkin/runner/metadata/TestMockEndpoint.kt
NetworkedAssets
120,890,153
false
null
package com.networkedassets.gherkin.runner.metadata import com.networkedassets.gherkin.runner.metadata.TestEndpointType.MOCK class TestMockEndpoint(name: String): TestEndpoint(name, MOCK)
3
Kotlin
4
7
b57d6f90acd5183511aa988040d4f33ddcba5bdb
189
gherkin-runner
Apache License 2.0
app/src/main/java/dev/jahidhasanco/montra/presentation/fragment/Onboarding/OnBoardingAdapter.kt
JahidHasanCO
424,880,653
false
null
package dev.jahidhasanco.montra.presentation.fragment.Onboarding import android.content.Context import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.ImageView import android.widget.TextView import androidx.viewpager.widget.PagerAdapter import dev.jahidhasanco.montra.R import dev.jahidhasanco.montra.data.onboarding.OnboardingData class OnBoardingAdapter(private val context: Context, private val data: List<OnboardingData>) : PagerAdapter() { override fun getCount(): Int { return data.size } override fun isViewFromObject(view: View, `object`: Any): Boolean { return view == `object` } override fun destroyItem(container: ViewGroup, position: Int, `object`: Any) { container.removeView(`object` as View) } override fun instantiateItem(container: ViewGroup, position: Int): Any { val view = LayoutInflater.from(context).inflate(R.layout.single_onboarding_layout, null) val imageView: ImageView = view.findViewById(R.id.image_Onboarding) val title: TextView = view.findViewById(R.id.title_Onboarding) val desc: TextView = view.findViewById(R.id.desc_Oboarding) imageView.run { setImageResource(data[position].image) } title.text = data[position].title desc.text = data[position].desc container.addView(view) return view } }
0
Kotlin
0
1
ae33ea5fe8588672c79cccdf010aa02024de8f33
1,442
Montra
MIT License
settle-payment/src/main/java/com/settle/sdk/payment/ui/SettlePaymentOptions.kt
settle-club
845,507,935
false
{"Kotlin": 34811}
package com.settle.sdk.payment.ui data class SettlePaymentOptions @JvmOverloads constructor( val paymentUrl: String, val isFullScreen: Boolean = false )
0
Kotlin
0
0
1cf59ddf28a5f389347cd8a3f05805fe8820dd51
161
settle-android-sdk
MIT License
Stipop/src/main/java/io/stipop/PackUtils.kt
AYOMITIDE-OAJ
608,090,223
false
null
@file:Suppress("KotlinDeprecation") package io.stipop import android.app.Activity import android.os.StrictMode import android.os.StrictMode.ThreadPolicy import io.stipop.model.SPPackage import io.stipop.model.SPSticker import org.json.JSONObject import java.io.File import java.io.FileOutputStream import java.net.URL class PackUtils { companion object { fun downloadAndSaveLocal(activity:Activity, spPackage: SPPackage?, responseCallback: () -> Unit) { val stickers = spPackage!!.stickers // println(stickers) for (sticker in stickers) { val packageId = sticker.packageId val stickerImg = sticker.stickerImg // val encodedString = URLEncoder.encode(stickerImg, "utf-8") downloadImage(activity, packageId, stickerImg, sticker) } responseCallback() } private fun downloadImage(activity:Activity, packageId: Int, encodedString: String?, sticker: SPSticker) { if (encodedString == null) { return } val fileName = encodedString.split(File.separator).last() var filePath = File(activity.filesDir, "stipop/$packageId/$fileName") if (filePath.isDirectory) { filePath.delete() } filePath = File(activity.filesDir, "stipop/$packageId") filePath.mkdirs() filePath = File(activity.filesDir, "stipop/$packageId/$fileName") // println("filePath : $filePath") val policy = ThreadPolicy.Builder().permitAll().build() StrictMode.setThreadPolicy(policy) URL(encodedString).openStream().use { input -> FileOutputStream(filePath).use { output -> input.copyTo(output) } saveStickerJsonData(activity, sticker, packageId) } } fun stickerListOf(activity:Activity, packageId:Int): ArrayList<SPSticker> { val stickerList = ArrayList<SPSticker>() val filePath = File(activity.filesDir, "stipop/$packageId") if (filePath.exists()) { filePath.walkTopDown().forEach { if (it.isFile) { val fileName = it.name if (fileName.contains(".json")) { return@forEach } val sticker = SPSticker() val fileNames = fileName.split(".") if (fileNames.count() > 0) { val jsonFileName = fileNames[0] val file = File(activity.filesDir, "stipop/$packageId/$jsonFileName.json") if (file.isFile) { val json = JSONObject(file.readText()) sticker.stickerId = Utils.getInt(json, "stickerId") sticker.stickerImg = Utils.getString(json, "stickerImg") sticker.favoriteYN = Utils.getString(json, "favoriteYN") } } sticker.packageId = packageId sticker.stickerImg = it.absolutePath stickerList.add(sticker) } } } return stickerList } fun saveStickerJsonData(activity: Activity, sticker: SPSticker, packageId: Int) { val fileName = sticker.stickerImg!!.split(File.separator)!!.last() val fileNames = fileName.split(".") var jsonFileName = fileName if (fileNames.count() > 0) { jsonFileName = fileNames[0] } val filePath = File(activity.filesDir, "stipop/$packageId/$jsonFileName.json") val json = JSONObject() json.put("stickerId", sticker.stickerId) json.put("stickerImg", sticker.stickerImg) json.put("favoriteYN", sticker.favoriteYN) json.put("keyword", sticker.keyword) val policy = ThreadPolicy.Builder().permitAll().build() StrictMode.setThreadPolicy(policy) filePath.writeText(json.toString()) } } }
1
null
1
2
1f99a4f3f00629259feb834a67caefedc3b0884f
4,368
wavychat
MIT License
pexty/floatingapp/window/VideoWindow.kt
aratakileo
379,673,755
false
{"Kotlin": 53026}
package pexty.floatingapp.window import android.content.Context import android.media.MediaMetadataRetriever import android.media.MediaPlayer import android.net.Uri import android.view.Gravity import android.view.ViewGroup import android.widget.LinearLayout import android.widget.VideoView import pexty.utils.Utils open class VideoWindow : DynamicWindow { protected constructor( context: Context, original: VideoWindow ) : super (context, original) { setContent(videoView) } constructor(context: Context, __flags: Int = 0) : super( context, 0, 0, "Video player window", FLAG_ONLY_CONTENT or FLAG_RESIZABLE or FLAG_DRAGGABLE_BY_CONTENT or FLAG_NOT_RESIZABLE_BY_MOTION or __flags ) { setContent(videoView) } companion object { const val FLAG_INFINITE_VIDEO_LOOP = 1 shl 15 } private var mediaMetadataRetriever: MediaMetadataRetriever = MediaMetadataRetriever() private var mediaPlayer: MediaPlayer? = null private var _videoCurrentPoint = 0 private var videoStartPoint = 0 private var _isVideoDidNotPlay = true private var _isHaveVideo = false private val videoView = VideoView(this.context).apply { layoutParams = LinearLayout.LayoutParams( ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT ).apply { gravity = Gravity.CENTER } setOnPreparedListener { mediaPlayer = it } setOnCompletionListener { if (haveFlags(FLAG_INFINITE_VIDEO_LOOP)) { start() videoCurrentPoint = 0 } } } val videoWidth: Int get() = if (mediaMetadataRetriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_VIDEO_WIDTH) != null) mediaMetadataRetriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_VIDEO_WIDTH)!!.toInt() else 0 val videoHeight: Int get() = if (mediaMetadataRetriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_VIDEO_HEIGHT) != null) mediaMetadataRetriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_VIDEO_HEIGHT)!!.toInt() else 0 val videoDuration: Int get() = videoView.duration var videoCurrentPoint: Int get() = _videoCurrentPoint set(value) { if (isClone) println("HaveVideo: ${isHaveVideo()}") if (mediaPlayer != null && !isVideoDidNotPlay() && isHaveVideo()) { _videoCurrentPoint = Utils.by_interval(value, 0, videoDuration) mediaPlayer?.seekTo(_videoCurrentPoint.toLong(), MediaPlayer.SEEK_CLOSEST) } else videoStartPoint = value } fun isVideoDidNotPlay(): Boolean { return _isVideoDidNotPlay } fun isHaveVideo(): Boolean { return _isHaveVideo } fun isPlaying(): Boolean { return videoView.isPlaying } fun start() { if (isHaveVideo()) { videoView.start() if (isVideoDidNotPlay()) { videoCurrentPoint = videoStartPoint videoStartPoint = 0 } _isVideoDidNotPlay = false } } fun pause() { if (isHaveVideo()) videoView.pause() } fun stop() { if (isHaveVideo()) { _videoCurrentPoint = 0 videoView.stopPlayback() } } fun setVideo(uri: Uri) { _isHaveVideo = true videoView.setVideoURI(uri) mediaMetadataRetriever.setDataSource(context, uri) dynamicWindow as VideoWindow if (!isClone) dynamicWindow.setVideo(uri) if (isExists()) start() } fun setVideo(resourceId: Int) { setVideo(Uri.parse("android.resource://${context.packageName}/$resourceId")) } fun setSizeByVideoRatio(widthHalf: Int = 2, heightHalf: Int = 4) { if (videoWidth > videoHeight) { val percent: Float = videoHeight.toFloat() / videoWidth.toFloat() val div = if (Utils.getScreenOrientation(context) == Utils.ORIENTATION_LANDSCAPE) heightHalf else widthHalf minWidth = displayMetrics.widthPixels / div minHeight = (minWidth.toFloat() * percent).toInt() } else { val percent: Float = videoWidth.toFloat() / videoHeight.toFloat() val div = if (Utils.getScreenOrientation(context) == Utils.ORIENTATION_PORTRAIT) heightHalf else widthHalf minHeight = displayMetrics.heightPixels / div minWidth = (minHeight.toFloat() * percent).toInt() } width = 0 height = 0 } override fun createDynamicWindow(): VideoWindow { return VideoWindow(context, this) } override fun _open() { super._open() if (isExists() && !isPlaying()) start() } override fun _close() { stop() super._close() } override fun _mainLoop() { _videoCurrentPoint = videoView.currentPosition super._mainLoop() } }
0
Kotlin
0
6
53f20a5c1bce9ddbf16959461cfafc6384db3910
5,059
FloatingWindows
MIT License
plugins/kotlin/idea/tests/testData/inspectionsLocal/collections/simplifiableCallChain/mapSumWithULong.kt
ingokegel
72,937,917
false
null
// WITH_STDLIB fun main() { listOf(1uL, 2uL).<caret>map { it * it }.sum() }
1
null
1
2
b07eabd319ad5b591373d63c8f502761c2b2dfe8
80
intellij-community
Apache License 2.0
app/src/main/java/br/com/arthurjf/jogodaforca/view/GameplayActivity.kt
arthurjf
625,067,320
false
null
package br.com.arthurjf.jogodaforca.view import android.os.Bundle import androidx.appcompat.app.AppCompatActivity import androidx.lifecycle.ViewModelProvider import br.com.arthurjf.jogodaforca.R import br.com.arthurjf.jogodaforca.data.Word import br.com.arthurjf.jogodaforca.view.ui.main.fragment.GameplayActivityFragment import br.com.arthurjf.jogodaforca.view.ui.viewmodel.GameplayViewModel class GameplayActivity : AppCompatActivity() { companion object { val WORD_KEY = "WORD_KEY_SENDER" } private lateinit var viewModel: GameplayViewModel override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_gameplay) val gameplayFragment = GameplayActivityFragment.newInstance() supportFragmentManager.beginTransaction() .replace(R.id.container, gameplayFragment) .commitNow() val wordData = intent.getParcelableExtra<Word>(WORD_KEY) viewModel = ViewModelProvider(this).get(GameplayViewModel::class.java) viewModel.wordData.value = wordData } }
0
Kotlin
0
0
860d9f9bd044eabb904f402a10ee415787384e2d
1,119
Jogo-da-Forca
MIT License
gaia/src/main/kotlin/fyi/pauli/ichor/gaia/entity/player/UserProfile.kt
ichor-dev
676,285,724
false
{"Kotlin": 95608}
package fyi.pauli.ichor.gaia.entity.player import fyi.pauli.ichor.gaia.extensions.serializers.OldUUIDSerializer import kotlinx.serialization.SerialName import kotlinx.serialization.Serializable import java.util.* /** * Userprofile of a connection. * @property uuid uuid of a connection. * @property username username of a connection- * @property properties list of properties of a connection. * @property profileActions list of actions of a connection. * @author Paul Kindler * @since 01/11/2023 */ @Serializable data class UserProfile( @SerialName("id") val uuid: @Serializable(with = OldUUIDSerializer::class) UUID, @SerialName("name") val username: String, val properties: List<Property>, val profileActions: List<ProfileAction> ) /** * Property data class used in the UserProfile. * @property name name of the property. * @property value value of the property. * @property signature signature of the property. * @author Paul Kindler * @since 01/11/2023 */ @Serializable data class Property(val name: String, val value: String, val signature: String) /** * TODO */ @Serializable class ProfileAction
4
Kotlin
0
0
466f531b1a45887f71188453d8fbf7c11008f7cb
1,126
ichor
Apache License 2.0
ontrack-extension-notifications/src/main/java/net/nemerosa/ontrack/extension/notifications/processing/NotificationProcessingService.kt
nemerosa
19,351,480
false
null
package net.nemerosa.ontrack.extension.notifications.processing import net.nemerosa.ontrack.extension.notifications.model.Notification interface NotificationProcessingService { fun process(item: Notification) }
57
Kotlin
27
97
7c71a3047401e088ba0c6d43aa3a96422024857f
218
ontrack
MIT License
app/src/main/java/com/example/inventory/ui/item/ItemDetailsViewModel.kt
ysmaelnoche
811,165,887
false
{"Kotlin": 46664}
package com.example.inventory.ui.item import androidx.lifecycle.SavedStateHandle import androidx.lifecycle.ViewModel import com.example.inventory.data.ItemsRepository class ItemDetailsViewModel( savedStateHandle: SavedStateHandle ) : ViewModel() { private val itemId: Int = checkNotNull(savedStateHandle[ItemDetailsDestination.itemIdArg]) companion object { private const val TIMEOUT_MILLIS = 5_000L } } data class ItemDetailsUiState( val outOfStock: Boolean = true, val itemDetails: ItemDetails = ItemDetails() )
0
Kotlin
0
0
bdf4638a179e5f57dc6f75be75fc1979ebc683ce
551
inventory2.0
Apache License 2.0
app/src/main/java/com/example/inventory/ui/item/ItemDetailsViewModel.kt
ysmaelnoche
811,165,887
false
{"Kotlin": 46664}
package com.example.inventory.ui.item import androidx.lifecycle.SavedStateHandle import androidx.lifecycle.ViewModel import com.example.inventory.data.ItemsRepository class ItemDetailsViewModel( savedStateHandle: SavedStateHandle ) : ViewModel() { private val itemId: Int = checkNotNull(savedStateHandle[ItemDetailsDestination.itemIdArg]) companion object { private const val TIMEOUT_MILLIS = 5_000L } } data class ItemDetailsUiState( val outOfStock: Boolean = true, val itemDetails: ItemDetails = ItemDetails() )
0
Kotlin
0
0
bdf4638a179e5f57dc6f75be75fc1979ebc683ce
551
inventory2.0
Apache License 2.0
kotlin-cdk-wrapper/src/main/kotlin/io/cloudshiftdev/awscdk/services/rds/SqlServerExInstanceEngineProps.kt
cloudshiftinc
667,063,030
false
null
@file:Suppress("RedundantVisibilityModifier","RedundantUnitReturnType","RemoveRedundantQualifierName","unused","UnusedImport","ClassName","REDUNDANT_PROJECTION","DEPRECATION") package io.cloudshiftdev.awscdk.services.rds import io.cloudshiftdev.awscdk.common.CdkDslMarker import io.cloudshiftdev.awscdk.common.CdkObject import io.cloudshiftdev.awscdk.common.CdkObjectWrappers import kotlin.Unit /** * Properties for SQL Server Express Edition instance engines. * * Used in `DatabaseInstanceEngine.sqlServerEx`. * * Example: * * ``` * // The code below shows an example of how to instantiate this type. * // The values are placeholders you should change. * import io.cloudshiftdev.awscdk.services.rds.*; * SqlServerEngineVersion sqlServerEngineVersion; * SqlServerExInstanceEngineProps sqlServerExInstanceEngineProps = * SqlServerExInstanceEngineProps.builder() * .version(sqlServerEngineVersion) * .build(); * ``` */ public interface SqlServerExInstanceEngineProps { /** * The exact version of the engine to use. */ public fun version(): SqlServerEngineVersion /** * A builder for [SqlServerExInstanceEngineProps] */ @CdkDslMarker public interface Builder { /** * @param version The exact version of the engine to use. */ public fun version(version: SqlServerEngineVersion) } private class BuilderImpl : Builder { private val cdkBuilder: software.amazon.awscdk.services.rds.SqlServerExInstanceEngineProps.Builder = software.amazon.awscdk.services.rds.SqlServerExInstanceEngineProps.builder() /** * @param version The exact version of the engine to use. */ override fun version(version: SqlServerEngineVersion) { cdkBuilder.version(version.let(SqlServerEngineVersion.Companion::unwrap)) } public fun build(): software.amazon.awscdk.services.rds.SqlServerExInstanceEngineProps = cdkBuilder.build() } private class Wrapper( cdkObject: software.amazon.awscdk.services.rds.SqlServerExInstanceEngineProps, ) : CdkObject(cdkObject), SqlServerExInstanceEngineProps { /** * The exact version of the engine to use. */ override fun version(): SqlServerEngineVersion = unwrap(this).getVersion().let(SqlServerEngineVersion::wrap) } public companion object { public operator fun invoke(block: Builder.() -> Unit = {}): SqlServerExInstanceEngineProps { val builderImpl = BuilderImpl() return Wrapper(builderImpl.apply(block).build()) } internal fun wrap(cdkObject: software.amazon.awscdk.services.rds.SqlServerExInstanceEngineProps): SqlServerExInstanceEngineProps = CdkObjectWrappers.wrap(cdkObject) as? SqlServerExInstanceEngineProps ?: Wrapper(cdkObject) internal fun unwrap(wrapped: SqlServerExInstanceEngineProps): software.amazon.awscdk.services.rds.SqlServerExInstanceEngineProps = (wrapped as CdkObject).cdkObject as software.amazon.awscdk.services.rds.SqlServerExInstanceEngineProps } }
4
null
0
4
eb3eef728b34da593a3e55dc423d4f5fa3668e9c
3,025
kotlin-cdk-wrapper
Apache License 2.0
app/src/main/java/com/ryanhodgman/framework/CoroutineActivity.kt
AlgoRyan
159,768,459
false
null
package com.ryanhodgman.framework import android.os.Bundle import androidx.appcompat.app.AppCompatActivity import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.Job import kotlin.coroutines.CoroutineContext /** * Activity that provides a [CoroutineScope]. * * @author <NAME> */ abstract class CoroutineActivity : AppCompatActivity(), CoroutineScope { private lateinit var job: Job override val coroutineContext: CoroutineContext get() = job + Dispatchers.Main override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) job = Job() } override fun onDestroy() { super.onDestroy() job.cancel() } }
0
Kotlin
0
2
b33ad8a5ec757f95cda61b6ca573780b5b60cb14
748
arcore-design-experiments
MIT License
app/src/main/java/com/twobbble/view/customview/CommentDivider.kt
550609334
82,531,843
false
null
package com.twobbble.view.customview import android.content.Context import android.content.res.TypedArray import android.graphics.Canvas import android.graphics.drawable.Drawable import android.support.v7.widget.RecyclerView import android.view.View import com.facebook.drawee.view.SimpleDraweeView import com.twobbble.R import com.twobbble.application.App import com.twobbble.tools.Utils /** * 主页RecyclerView的分隔线 */ class CommentDivider : RecyclerView.ItemDecoration() { private val mDivider: Drawable init { val typedArray = App.instance.obtainStyledAttributes(attrs) //将数组转化为TypedArray mDivider = typedArray.getDrawable(0) //取出这个Drawable文件 typedArray.recycle() //回收TypedArray } override fun onDrawOver(c: Canvas, parent: RecyclerView, state: RecyclerView.State?) { val circle_icon = parent.findViewById<SimpleDraweeView>(R.id.mCommentAvatarImg) val childCount = parent.childCount if (childCount != 0) { val left = (circle_icon.width + Utils.dp2px(32)) val right = (parent.width - Utils.dp2px(16)) for (i in 0 until childCount) { val child = parent.getChildAt(i) val params = child.layoutParams as RecyclerView.LayoutParams val top = child.bottom + params.bottomMargin val bottom = top + mDivider.intrinsicHeight mDivider.alpha = 100 mDivider.setBounds(left.toInt(), top, right.toInt(), bottom) mDivider.draw(c) } } } companion object { private val attrs = intArrayOf(android.R.attr.listDivider)//系统自带分割线文件,获取后先保存为数组 } }
1
null
62
398
e91797a3d4a0fa7737f983a8914eaa109a452054
1,688
Twobbble
Apache License 2.0
ext/acorn-android/acorn-android-statechecks/src/main/java/com/nhaarman/acorn/android/experimental/statechecks/StateSavingFailedException.kt
nhaarman
137,459,947
false
null
/* * Copyright 2018 <NAME> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.nhaarman.acorn.android.experimental.statechecks @ExperimentalStateChecker internal class StateSavingFailedException( cause: Throwable? = null, ) : Exception(cause) { override val message: String? get() = "Could not save instance state for Navigator (see cause below)." }
17
null
7
182
bb4cd33a54103bb1a1cf4c0eecabfcc7b9c352d2
922
acorn
Apache License 2.0
plot-base/src/commonMain/kotlin/jetbrains/datalore/plot/base/render/svg/GroupComponent.kt
b7w
229,423,563
true
{"Kotlin": 4342986, "Python": 257583, "CSS": 1842, "C": 1638, "Shell": 1590, "JavaScript": 1584}
/* * Copyright (c) 2019. JetBrains s.r.o. * Use of this source code is governed by the MIT license that can be found in the LICENSE file. */ package jetbrains.datalore.plot.base.render.svg class GroupComponent : SvgComponent() { override fun buildComponent() { // empty } }
0
null
0
0
811327d17d6af2669d22355ee031eaa2cf5da7bc
295
lets-plot
MIT License
testUtil/src/main/java/com/tfandkusu/template/viewmodel/MockStateObserver.kt
tfandkusu
427,583,819
false
null
package com.tfandkusu.androidview.viewmodel import androidx.lifecycle.LiveData import androidx.lifecycle.Observer import io.mockk.mockk fun <T> LiveData<T>.mockStateObserver(): Observer<T> { val mockObserver = mockk<Observer<T>>(relaxed = true, name = "state") observeForever(mockObserver) return mockObserver }
23
null
0
1
5d8d0aea5a008c53c7444f402858fa0911ed253c
326
android_app_template
Apache License 2.0
app/src/main/kotlin/org/andstatus/app/net/http/HttpReadResult.kt
andstatus
3,040,264
false
null
/* Copyright (C) 2014 yvolk (Yuri Volkov), http://yurivolkov.com * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.andstatus.app.net.http import android.text.TextUtils import android.text.format.Formatter import io.vavr.control.CheckedFunction import io.vavr.control.Try import org.andstatus.app.context.MyContextHolder import org.andstatus.app.context.MyPreferences import org.andstatus.app.net.social.ApiRoutineEnum import org.andstatus.app.net.social.Connection.Companion.parseIso8601Date import org.andstatus.app.util.I18n import org.andstatus.app.util.JsonUtils import org.andstatus.app.util.MagnetUri.Companion.getDownloadableUrl import org.andstatus.app.util.MyLog import org.andstatus.app.util.MyStringBuilder import org.andstatus.app.util.TryUtils import org.json.JSONArray import org.json.JSONException import org.json.JSONObject import org.json.JSONTokener import java.io.InputStream import java.net.URL import java.util.* import java.util.stream.Collector import java.util.stream.Collectors import java.util.stream.Stream class HttpReadResult(val request: HttpRequest) { var url: URL? = request.uri.getDownloadableUrl() private set private var headers: MutableMap<String, MutableList<String>> = mutableMapOf() var redirected = false private var location: Optional<String> = Optional.empty() var retriedWithoutAuthentication = false private val logBuilder: StringBuilder = StringBuilder() private var exception: Exception? = null var strResponse: String = "" var statusLine: String = "" private var statusCodeInt = 0 var statusCode: StatusCode = StatusCode.UNKNOWN private set var delayedTill: Long? = null private set fun requiredUrl(errorMessage: String): URL? = url ?: let { setException(Exception("Mo URL for $errorMessage")) null } fun delayTill(millis: Long): HttpReadResult { if (millis > System.currentTimeMillis()) { delayedTill = millis if (statusCode == StatusCode.UNKNOWN) statusCode = StatusCode.DELAYED } else { delayedTill = null } return this } // See https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Retry-After val retryAfterDate: Long? get() = headers.get("retry-after")?.firstNotNullOfOrNull(::parseSecondsOrDate) // See https://datatracker.ietf.org/doc/html/draft-ietf-httpapi-ratelimit-headers val rateLimitRemaining: Long? get() = headers.get("ratelimit-remaining")?.firstNotNullOfOrNull { it.toLongOrNull() } ?: headers.get("x-ratelimit-remaining")?.firstNotNullOfOrNull { it.toLongOrNull() } val rateLimitReset: Long? get() = headers.get("ratelimit-reset")?.firstNotNullOfOrNull(::parseSecondsOrDate) ?: headers.get("x-ratelimit-reset")?.firstNotNullOfOrNull(::parseSecondsOrDate) fun getHeaders(): MutableMap<String, MutableList<String>> { return headers } fun <T> setHeaders(headers: Stream<T>, keyMapper: (T) -> String?, valueMapper: (T) -> String?): HttpReadResult { return setHeaders(headers.collect(toHeaders(keyMapper, valueMapper))) } private fun setHeaders(headers: MutableMap<String, MutableList<String>>): HttpReadResult { // Header field names are case-insensitive, see https://stackoverflow.com/a/5259004/297710 val lowercaseKeysMap: MutableMap<String, MutableList<String>> = HashMap() headers.entries.forEach { entry -> lowercaseKeysMap[if (entry.key.isEmpty()) "" else entry.key.toLowerCase()] = entry.value } this.headers = lowercaseKeysMap location = Optional.ofNullable(this.headers.get("location")) .orElse(mutableListOf<String>()).stream() .filter { obj: String -> obj.isNotEmpty() } .findFirst() .map { l: String -> l.replace("%3F", "?") } return this } fun getLocation(): Optional<String> { return location } fun setUrl(urlIn: URL?): HttpReadResult { if (urlIn != null && urlIn != url) { url = urlIn } return this } fun setStatusCodeInt(statusCodeInt: Int) { this.statusCodeInt = statusCodeInt statusCode = StatusCode.fromResponseCode(statusCodeInt) } fun appendToLog(chars: CharSequence?) { if (TextUtils.isEmpty(chars)) { return } if (logBuilder.length > 0) { logBuilder.append("; ") } logBuilder.append(chars) } fun logMsg(): String { return logBuilder.toString() } override fun toString(): String { return (logMsg() + (if (statusCode == StatusCode.OK || statusLine.isEmpty()) "" else "; statusLine:'$statusLine'") + (if (statusCodeInt == 0) "" else "; statusCode:$statusCode ($statusCodeInt)") + (if (redirected) "; redirected" else "") + "; url:'$url'" + (if (retriedWithoutAuthentication) "; retried without auth" else "") + (if (strResponse.isEmpty()) "" else "; response:'" + I18n.trimTextAt(strResponse, 40) + "'") + location.map { str: String -> "; location:'$str'" }.orElse("") + (if (exception == null) "" else ";\nexception: $exception") + "\nRequested: " + request) } fun getJsonArrayInObject(arrayName: String): Try<JSONArray> { val method = "getRequestArrayInObject" return getJsonObject() .flatMap { jso: JSONObject? -> if (jso != null) { try { Try.success(jso.getJSONArray(arrayName)) } catch (e: JSONException) { Try.failure(ConnectionException.loggedJsonException(this, "$method, arrayName=$arrayName", e, jso)) } } else Try.success(JSONArray()) } } fun getJsonObject(): Try<JSONObject> { return innerGetJsonObject(strResponse) } fun getResponse(): String { return strResponse } private fun innerGetJsonObject(strJson: String?): Try<JSONObject> { val method = "getJsonObject; " val jso: JSONObject? try { if (strJson.isNullOrEmpty()) { jso = JSONObject() } else { jso = JSONObject(strJson) val error = JsonUtils.optString(jso, "error") if ("Could not authenticate you." == error) { appendToLog("error:$error") return Try.failure(ConnectionException(toString())) } } } catch (e: JSONException) { return Try.failure(ConnectionException.loggedJsonException(this, method + I18n.trimTextAt(toString(), 500), e, strJson)) } return Try.success(jso) } fun getJsonArray(): Try<JSONArray> { return getJsonArray("items") } fun getJsonArray(arrayKey: String): Try<JSONArray> { val method = "getJsonArray; " if (strResponse.isEmpty()) { MyLog.v(this) { "$method; response is empty" } return Try.success(JSONArray()) } val jst = JSONTokener(strResponse) val jsa: JSONArray? try { var obj = jst.nextValue() if (obj is JSONObject) { val jso = obj if (jso.has(arrayKey)) { obj = try { jso.getJSONArray(arrayKey) } catch (e: JSONException) { return Try.failure(ConnectionException.loggedJsonException(this, "'" + arrayKey + "' is not an array?!" + method + toString(), e, jso)) } } else { val iterator = jso.keys() while (iterator.hasNext()) { val key = iterator.next() val obj2 = jso[key] if (obj2 is JSONArray) { MyLog.v(this) { "$method; found array inside '$key' object" } obj = obj2 break } } } } jsa = obj as JSONArray } catch (e: JSONException) { return Try.failure(ConnectionException.loggedJsonException(this, method + toString(), e, strResponse)) } catch (e: Exception) { return Try.failure(ConnectionException.loggedHardJsonException(this, method + toString(), e, strResponse)) } return Try.success(jsa) } fun getExceptionFromJsonErrorResponse(): ConnectionException { var statusCode = statusCode var error = "?" return if (TextUtils.isEmpty(strResponse)) { ConnectionException(statusCode, "Empty response; " + toString()) } else try { val jsonError = JSONObject(strResponse) error = JsonUtils.optString(jsonError, "error", error) if (statusCode == StatusCode.UNKNOWN && error.contains("not found")) { statusCode = StatusCode.NOT_FOUND } ConnectionException(statusCode, "Error='" + error + "'; " + toString()) } catch (e: JSONException) { ConnectionException(statusCode, toString()) } } fun setException(e: Throwable?): HttpReadResult { TryUtils.checkException(e) if (exception == null) { exception = if (e is Exception) e else ConnectionException("Unexpected exception", e) } return this } fun getException(): Exception? { return exception } fun toTryRequest(): Try<HttpRequest> = toTryResult().map { it.request } fun toTryResult(): Try<HttpReadResult> { if (exception is ConnectionException) { return Try.failure(exception) } if (isStatusOk()) { if (request.isFileTooLarge()) { setException(ConnectionException.hardConnectionException( "File, downloaded from '$url', is too large: " + Formatter.formatShortFileSize( MyContextHolder.myContextHolder.getNow().context, request.fileResult?.length() ?: 0), null)) return Try.failure(ConnectionException.from(this)) } MyLog.v(this) { this.toString() } } else { if (strResponse.isNotEmpty()) { setException(getExceptionFromJsonErrorResponse()) } else { setException(ConnectionException.fromStatusCodeAndThrowable(statusCode, toString(), exception)) } return Try.failure(ConnectionException.from(this)) } return Try.success(this) } fun isStatusOk(): Boolean { return exception == null && (statusCode == StatusCode.OK || statusCode == StatusCode.UNKNOWN) } fun toFailure(): Try<HttpReadResult> { return Try.failure(ConnectionException.from(this)) } fun logResponse(): HttpReadResult { if (MyPreferences.isLogNetworkLevelMessages()) { val anyTag: Any = "response" MyLog.logNetworkLevelMessage(anyTag, request.getLogName(), strResponse, MyStringBuilder.of("") .atNewLine("logger-URL", url.toString()) .atNewLine("logger-account", request.connectionData().getAccountName().name) .atNewLine("logger-authenticated", java.lang.Boolean.toString(authenticate())) .apply { builder: MyStringBuilder -> appendHeaders(builder) }.toString()) } return this } fun appendHeaders(builder: MyStringBuilder): MyStringBuilder { builder.atNewLine("Headers:") for ((key, value) in getHeaders()) { builder.atNewLine(key, value.toString()) } return builder } fun authenticate(): Boolean { return !retriedWithoutAuthentication && request.authenticate } fun noMoreHttpRetries(): Boolean { if (authenticate() && request.apiRoutine == ApiRoutineEnum.DOWNLOAD_FILE && statusCode != StatusCode.TOO_MANY_REQUESTS && delayedTill == null ) { onRetryWithoutAuthentication() return false } return true } private fun onRetryWithoutAuthentication() { retriedWithoutAuthentication = true appendToLog("Retrying without authentication" + if (exception == null) "" else ", exception: $exception") exception = null MyLog.v(this) { this.toString() } } fun readStream(msgLog: String?, supplier: CheckedFunction<Unit, InputStream>): Try<HttpReadResult> { return HttpConnectionUtils.readStream(this, msgLog, supplier) } companion object { private fun <T> toHeaders( keyMapper: (T) -> String?, valueMapper: (T) -> String?): Collector<T, *, MutableMap<String, MutableList<String>>> { return Collectors.toMap( { e: T -> keyMapper(e) ?: "" }, { e: T -> valueMapper(e)?.let { mutableListOf(it) } ?: mutableListOf() }, { a: MutableList<String>, b: MutableList<String> -> val out: MutableList<String> = ArrayList(a) out.addAll(b) out }) } fun Try<*>.toHttpReadResult(): HttpReadResult? = fold({ when (it) { is ConnectionException -> it.httpResult else -> null } }, { when(it) { is HttpReadResult -> it else -> null } }) fun parseSecondsOrDate(value: String): Long? = value.toLongOrNull()?.let { it * 1000 + System.currentTimeMillis() } ?: parseIso8601Date(value).let { // Date format is not exactly correct... // see https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Retry-After if (it > 1) it else null } } }
86
null
69
306
6166aded1f115e6e6a7e66ca3756f39f0434663e
15,022
andstatus
Apache License 2.0
game-plugins/src/main/kotlin/org/alter/plugins/content/npcs/kbd/kbd_configs.plugin.kts
AlterRSPS
421,831,790
false
null
package gg.rsmod.plugins.content.npcs.npcInfo.kbd set_multi_combat_region(region = 9033) spawn_npc(Npcs.KING_BLACK_DRAGON, x = 2274, z = 4698, walkRadius = 5) set_combat_def(Npcs.KING_BLACK_DRAGON) { species { + NpcSpecies.DRAGON + NpcSpecies.BASIC_DRAGON } configs { attackSpeed = 3 respawnDelay = 50 } aggro { radius = 16 searchDelay = 1 } stats { hitpoints = 240 attack = 240 strength = 240 defence = 240 magic = 240 } bonuses { defenceStab = 70 defenceSlash = 90 defenceCrush = 90 defenceMagic = 80 defenceRanged = 70 } anims { block = 89 death = 92 } slayerData { xp = 258.0 } }
8
null
33
23
bb3762897621705e99b1ba752a1858bc69900e54
800
Alter
Apache License 2.0
compiler/ir/ir.tree/src/org/jetbrains/kotlin/ir/util/DeepCopyIrTree.kt
JakeWharton
99,388,807
false
null
/* * Copyright 2010-2017 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.jetbrains.kotlin.ir.util import org.jetbrains.kotlin.descriptors.* import org.jetbrains.kotlin.ir.IrElement import org.jetbrains.kotlin.ir.IrStatement import org.jetbrains.kotlin.ir.SourceManager import org.jetbrains.kotlin.ir.declarations.* import org.jetbrains.kotlin.ir.declarations.impl.* import org.jetbrains.kotlin.ir.expressions.* import org.jetbrains.kotlin.ir.expressions.impl.* import org.jetbrains.kotlin.ir.symbols.impl.IrFieldSymbolImpl import org.jetbrains.kotlin.ir.symbols.impl.IrSimpleFunctionSymbolImpl import org.jetbrains.kotlin.ir.symbols.impl.IrVariableSymbolImpl import org.jetbrains.kotlin.ir.visitors.IrElementTransformerVoid import org.jetbrains.kotlin.types.KotlinType import java.util.* inline fun <reified T : IrElement> T.deepCopyOld() = transform(DeepCopyIrTree(), null) as T @Deprecated("Creates unbound symbols") open class DeepCopyIrTree : IrElementTransformerVoid() { protected open fun mapDeclarationOrigin(declarationOrigin: IrDeclarationOrigin) = declarationOrigin protected open fun mapStatementOrigin(statementOrigin: IrStatementOrigin?) = statementOrigin protected open fun mapFileEntry(fileEntry: SourceManager.FileEntry) = fileEntry protected open fun mapModuleDescriptor(descriptor: ModuleDescriptor) = descriptor protected open fun mapPackageFragmentDescriptor(descriptor: PackageFragmentDescriptor) = descriptor protected open fun mapClassDeclaration(descriptor: ClassDescriptor) = descriptor protected open fun mapTypeAliasDeclaration(descriptor: TypeAliasDescriptor) = descriptor protected open fun mapFunctionDeclaration(descriptor: FunctionDescriptor) = descriptor protected open fun mapConstructorDeclaration(descriptor: ClassConstructorDescriptor) = descriptor protected open fun mapPropertyDeclaration(descriptor: PropertyDescriptor) = descriptor protected open fun mapLocalPropertyDeclaration(descriptor: VariableDescriptorWithAccessors) = descriptor protected open fun mapEnumEntryDeclaration(descriptor: ClassDescriptor) = descriptor protected open fun mapVariableDeclaration(descriptor: VariableDescriptor) = descriptor protected open fun mapErrorDeclaration(descriptor: DeclarationDescriptor) = descriptor protected open fun mapSuperQualifier(qualifier: ClassDescriptor?) = qualifier protected open fun mapClassReference(descriptor: ClassDescriptor) = descriptor protected open fun mapValueReference(descriptor: ValueDescriptor) = descriptor protected open fun mapVariableReference(descriptor: VariableDescriptor) = descriptor protected open fun mapPropertyReference(descriptor: PropertyDescriptor) = descriptor protected open fun mapCallee(descriptor: FunctionDescriptor) = descriptor protected open fun mapDelegatedConstructorCallee(descriptor: ClassConstructorDescriptor) = descriptor protected open fun mapEnumConstructorCallee(descriptor: ClassConstructorDescriptor) = descriptor protected open fun mapLocalPropertyReference(descriptor: VariableDescriptorWithAccessors) = descriptor protected open fun mapClassifierReference(descriptor: ClassifierDescriptor) = descriptor protected open fun mapReturnTarget(descriptor: FunctionDescriptor) = mapCallee(descriptor) private inline fun <reified T : IrElement> T.transform() = transform(this@DeepCopyIrTree, null) as T override fun visitElement(element: IrElement): IrElement = throw IllegalArgumentException("Unsupported element type: $element") override fun visitModuleFragment(declaration: IrModuleFragment): IrModuleFragment = IrModuleFragmentImpl( mapModuleDescriptor(declaration.descriptor), declaration.irBuiltins, declaration.files.map { it.transform() } ) override fun visitFile(declaration: IrFile): IrFile = IrFileImpl( mapFileEntry(declaration.fileEntry), mapPackageFragmentDescriptor(declaration.packageFragmentDescriptor), declaration.fileAnnotations.toMutableList(), declaration.declarations.map { it.transform() } ) override fun visitDeclaration(declaration: IrDeclaration): IrStatement = throw IllegalArgumentException("Unsupported declaration type: $declaration") override fun visitClass(declaration: IrClass): IrClass = IrClassImpl( declaration.startOffset, declaration.endOffset, mapDeclarationOrigin(declaration.origin), mapClassDeclaration(declaration.descriptor), declaration.declarations.map { it.transform() } ).apply { thisReceiver = declaration.thisReceiver?.withDescriptor(descriptor.thisAsReceiverParameter) transformTypeParameters(declaration, descriptor.declaredTypeParameters) } private fun IrValueParameter.withDescriptor(newDescriptor: ParameterDescriptor) = IrValueParameterImpl(startOffset, endOffset, origin, newDescriptor, defaultValue?.transform()) override fun visitTypeAlias(declaration: IrTypeAlias): IrTypeAlias = IrTypeAliasImpl( declaration.startOffset, declaration.endOffset, mapDeclarationOrigin(declaration.origin), mapTypeAliasDeclaration(declaration.descriptor) ) override fun visitFunction(declaration: IrFunction): IrFunction = IrFunctionImpl( declaration.startOffset, declaration.endOffset, mapDeclarationOrigin(declaration.origin), mapFunctionDeclaration(declaration.descriptor), declaration.body?.transform() ).transformParameters(declaration) override fun visitConstructor(declaration: IrConstructor): IrConstructor = IrConstructorImpl( declaration.startOffset, declaration.endOffset, mapDeclarationOrigin(declaration.origin), mapConstructorDeclaration(declaration.descriptor), declaration.body!!.transform() ).transformParameters(declaration) protected fun <T : IrTypeParametersContainer> T.transformTypeParameters( original: T, myTypeParameters: List<TypeParameterDescriptor> ): T = apply { original.typeParameters.mapTo(typeParameters) { originalTypeParameter -> copyTypeParameter(originalTypeParameter, myTypeParameters[originalTypeParameter.descriptor.index]) } } protected fun <T : IrFunction> T.transformParameters(original: T): T = apply { transformTypeParameters(original, descriptor.typeParameters) transformValueParameters(original) } protected fun <T : IrFunction> T.transformValueParameters(original: T) = apply { dispatchReceiverParameter = original.dispatchReceiverParameter?.let { copyValueParameter(it, descriptor.dispatchReceiverParameter ?: throw AssertionError("No dispatch receiver in $descriptor")) } extensionReceiverParameter = original.extensionReceiverParameter?.let { copyValueParameter( it, descriptor.extensionReceiverParameter ?: throw AssertionError("No extension receiver in $descriptor") ) } original.valueParameters.mapIndexedTo(valueParameters) { i, originalValueParameter -> copyValueParameter(originalValueParameter, descriptor.valueParameters[i]) } } protected fun copyTypeParameter( originalTypeParameter: IrTypeParameter, newTypeParameterDescriptor: TypeParameterDescriptor ): IrTypeParameterImpl = IrTypeParameterImpl( originalTypeParameter.startOffset, originalTypeParameter.endOffset, mapDeclarationOrigin(originalTypeParameter.origin), newTypeParameterDescriptor ) protected fun copyValueParameter( originalValueParameter: IrValueParameter, newParameterDescriptor: ParameterDescriptor ): IrValueParameterImpl = IrValueParameterImpl( originalValueParameter.startOffset, originalValueParameter.endOffset, mapDeclarationOrigin(originalValueParameter.origin), newParameterDescriptor, originalValueParameter.defaultValue?.transform() ) // TODO visitTypeParameter // TODO visitValueParameter override fun visitProperty(declaration: IrProperty): IrProperty = IrPropertyImpl( declaration.startOffset, declaration.endOffset, mapDeclarationOrigin(declaration.origin), declaration.isDelegated, mapPropertyDeclaration(declaration.descriptor), declaration.backingField?.transform(), declaration.getter?.transform(), declaration.setter?.transform() ) override fun visitField(declaration: IrField): IrField = IrFieldImpl( declaration.startOffset, declaration.endOffset, mapDeclarationOrigin(declaration.origin), mapPropertyDeclaration(declaration.descriptor), declaration.initializer?.transform() ) override fun visitLocalDelegatedProperty(declaration: IrLocalDelegatedProperty): IrLocalDelegatedProperty = IrLocalDelegatedPropertyImpl( declaration.startOffset, declaration.endOffset, mapDeclarationOrigin(declaration.origin), mapLocalPropertyDeclaration(declaration.descriptor), declaration.delegate.transform(), declaration.getter.transform(), declaration.setter?.transform() ) override fun visitEnumEntry(declaration: IrEnumEntry): IrEnumEntry = IrEnumEntryImpl( declaration.startOffset, declaration.endOffset, mapDeclarationOrigin(declaration.origin), mapEnumEntryDeclaration(declaration.descriptor), declaration.correspondingClass?.transform(), declaration.initializerExpression?.transform() ) override fun visitAnonymousInitializer(declaration: IrAnonymousInitializer): IrAnonymousInitializer = IrAnonymousInitializerImpl( declaration.startOffset, declaration.endOffset, mapDeclarationOrigin(declaration.origin), mapClassDeclaration(declaration.descriptor), declaration.body.transform() ) override fun visitVariable(declaration: IrVariable): IrVariable = IrVariableImpl( declaration.startOffset, declaration.endOffset, mapDeclarationOrigin(declaration.origin), mapVariableDeclaration(declaration.descriptor), declaration.initializer?.transform() ) override fun visitBody(body: IrBody): IrBody = throw IllegalArgumentException("Unsupported body type: $body") override fun visitExpressionBody(body: IrExpressionBody): IrExpressionBody = IrExpressionBodyImpl(body.expression.transform()) override fun visitBlockBody(body: IrBlockBody): IrBlockBody = IrBlockBodyImpl( body.startOffset, body.endOffset, body.statements.map { it.transform() } ) override fun visitSyntheticBody(body: IrSyntheticBody): IrSyntheticBody = IrSyntheticBodyImpl(body.startOffset, body.endOffset, body.kind) override fun visitExpression(expression: IrExpression): IrExpression = throw IllegalArgumentException("Unsupported expression type: $expression") override fun <T> visitConst(expression: IrConst<T>): IrConst<T> = expression.copy() override fun visitVararg(expression: IrVararg): IrVararg = IrVarargImpl( expression.startOffset, expression.endOffset, expression.type, expression.varargElementType, expression.elements.map { it.transform() } ) override fun visitSpreadElement(spread: IrSpreadElement): IrSpreadElement = IrSpreadElementImpl( spread.startOffset, spread.endOffset, spread.expression.transform() ) override fun visitBlock(expression: IrBlock): IrBlock = IrBlockImpl( expression.startOffset, expression.endOffset, expression.type, mapStatementOrigin(expression.origin), expression.statements.map { it.transform() } ) override fun visitComposite(expression: IrComposite): IrComposite = IrCompositeImpl( expression.startOffset, expression.endOffset, expression.type, mapStatementOrigin(expression.origin), expression.statements.map { it.transform() } ) override fun visitStringConcatenation(expression: IrStringConcatenation): IrStringConcatenation = IrStringConcatenationImpl( expression.startOffset, expression.endOffset, expression.type, expression.arguments.map { it.transform() } ) override fun visitGetObjectValue(expression: IrGetObjectValue): IrGetObjectValue = IrGetObjectValueImpl( expression.startOffset, expression.endOffset, expression.type, mapClassReference(expression.descriptor) ) override fun visitGetEnumValue(expression: IrGetEnumValue): IrGetEnumValue = IrGetEnumValueImpl( expression.startOffset, expression.endOffset, expression.type, mapClassReference(expression.descriptor) ) override fun visitGetValue(expression: IrGetValue): IrGetValue = IrGetValueImpl( expression.startOffset, expression.endOffset, mapValueReference(expression.descriptor), mapStatementOrigin(expression.origin) ) override fun visitSetVariable(expression: IrSetVariable): IrSetVariable = IrSetVariableImpl( expression.startOffset, expression.endOffset, mapVariableReference(expression.descriptor), expression.value.transform(), mapStatementOrigin(expression.origin) ) override fun visitGetField(expression: IrGetField): IrGetField = IrGetFieldImpl( expression.startOffset, expression.endOffset, mapPropertyReference(expression.descriptor), expression.receiver?.transform(), mapStatementOrigin(expression.origin), mapSuperQualifier(expression.superQualifier) ) override fun visitSetField(expression: IrSetField): IrSetField = IrSetFieldImpl( expression.startOffset, expression.endOffset, mapPropertyReference(expression.descriptor), expression.receiver?.transform(), expression.value.transform(), mapStatementOrigin(expression.origin), mapSuperQualifier(expression.superQualifier) ) override fun visitCall(expression: IrCall): IrCall = shallowCopyCall(expression).transformValueArguments(expression) protected fun shallowCopyCall(expression: IrCall) = when (expression) { is IrCallWithShallowCopy -> expression.shallowCopy( mapStatementOrigin(expression.origin), mapCallee(expression.descriptor), mapSuperQualifier(expression.superQualifier) ) else -> { val newCallee = mapCallee(expression.descriptor) IrCallImpl( expression.startOffset, expression.endOffset, expression.type, newCallee, expression.transformTypeArguments(newCallee), mapStatementOrigin(expression.origin), mapSuperQualifier(expression.superQualifier) ) } } protected fun <T : IrMemberAccessExpression> T.transformValueArguments(original: IrMemberAccessExpression): T = apply { dispatchReceiver = original.dispatchReceiver?.transform() extensionReceiver = original.extensionReceiver?.transform() mapValueParameters { valueParameter -> original.getValueArgument(valueParameter)?.transform() } Unit } protected fun IrMemberAccessExpression.transformTypeArguments(newCallee: CallableDescriptor): Map<TypeParameterDescriptor, KotlinType>? { if (this is IrMemberAccessExpressionBase) return typeArguments val typeParameters = descriptor.original.typeParameters return if (typeParameters.isEmpty()) null else typeParameters.associateBy( { newCallee.typeParameters[it.index] }, { getTypeArgument(it)!! } ) } override fun visitDelegatingConstructorCall(expression: IrDelegatingConstructorCall): IrDelegatingConstructorCall { val newCallee = mapDelegatedConstructorCallee(expression.descriptor) return IrDelegatingConstructorCallImpl( expression.startOffset, expression.endOffset, newCallee, expression.transformTypeArguments(newCallee) ).transformValueArguments(expression) } override fun visitEnumConstructorCall(expression: IrEnumConstructorCall): IrEnumConstructorCall = IrEnumConstructorCallImpl( expression.startOffset, expression.endOffset, mapEnumConstructorCallee(expression.descriptor) ).transformValueArguments(expression) override fun visitGetClass(expression: IrGetClass): IrGetClass = IrGetClassImpl( expression.startOffset, expression.endOffset, expression.type, expression.argument.transform() ) override fun visitFunctionReference(expression: IrFunctionReference): IrExpression { val newCallee = mapCallee(expression.descriptor) return IrFunctionReferenceImpl( expression.startOffset, expression.endOffset, expression.type, newCallee.original, expression.transformTypeArguments(newCallee), mapStatementOrigin(expression.origin) ).transformValueArguments(expression) } override fun visitPropertyReference(expression: IrPropertyReference): IrExpression { val newProperty = mapPropertyReference(expression.descriptor) val newFieldSymbol = if (newProperty.getter == null) IrFieldSymbolImpl(newProperty) else null val newGetterSymbol = newProperty.getter?.let { IrSimpleFunctionSymbolImpl(it.original) } val newSetterSymbol = newProperty.setter?.let { IrSimpleFunctionSymbolImpl(it.original) } return IrPropertyReferenceImpl( expression.startOffset, expression.endOffset, expression.type, newProperty, newFieldSymbol, newGetterSymbol, newSetterSymbol, expression.transformTypeArguments(newProperty), mapStatementOrigin(expression.origin) ).transformValueArguments(expression) } override fun visitLocalDelegatedPropertyReference(expression: IrLocalDelegatedPropertyReference): IrExpression { val newLocalDelegatedProperty = mapLocalPropertyReference(expression.descriptor) val newDelegateDescriptor = mapVariableReference(expression.delegate.descriptor) val newDelegateSymbol = IrVariableSymbolImpl(newDelegateDescriptor) val newGetterSymbol = newLocalDelegatedProperty.getter!!.let { IrSimpleFunctionSymbolImpl(it.original) } val newSetterSymbol = newLocalDelegatedProperty.setter?.let { IrSimpleFunctionSymbolImpl(it.original) } return IrLocalDelegatedPropertyReferenceImpl( expression.startOffset, expression.endOffset, expression.type, newLocalDelegatedProperty, newDelegateSymbol, newGetterSymbol, newSetterSymbol, mapStatementOrigin(expression.origin) ) } override fun visitClassReference(expression: IrClassReference): IrClassReference = IrClassReferenceImpl( expression.startOffset, expression.endOffset, expression.type, mapClassifierReference(expression.descriptor), expression.classType ) override fun visitInstanceInitializerCall(expression: IrInstanceInitializerCall): IrInstanceInitializerCall = IrInstanceInitializerCallImpl( expression.startOffset, expression.endOffset, mapClassReference(expression.classDescriptor) ) override fun visitTypeOperator(expression: IrTypeOperatorCall): IrTypeOperatorCall = IrTypeOperatorCallImpl( expression.startOffset, expression.endOffset, expression.type, expression.operator, expression.typeOperand, expression.argument.transform() ) override fun visitWhen(expression: IrWhen): IrWhen = IrWhenImpl( expression.startOffset, expression.endOffset, expression.type, mapStatementOrigin(expression.origin), expression.branches.map { it.transform() } ) override fun visitBranch(branch: IrBranch): IrBranch = IrBranchImpl( branch.startOffset, branch.endOffset, branch.condition.transform(), branch.result.transform() ) override fun visitElseBranch(branch: IrElseBranch): IrElseBranch = IrElseBranchImpl( branch.startOffset, branch.endOffset, branch.condition.transform(), branch.result.transform() ) private val transformedLoops = HashMap<IrLoop, IrLoop>() private fun getTransformedLoop(irLoop: IrLoop): IrLoop = transformedLoops.getOrElse(irLoop) { getNonTransformedLoop(irLoop) } protected open fun getNonTransformedLoop(irLoop: IrLoop): IrLoop = throw AssertionError("Outer loop was not transformed: ${irLoop.render()}") override fun visitWhileLoop(loop: IrWhileLoop): IrWhileLoop { val newLoop = IrWhileLoopImpl(loop.startOffset, loop.endOffset, loop.type, mapStatementOrigin(loop.origin)) transformedLoops[loop] = newLoop newLoop.label = loop.label newLoop.condition = loop.condition.transform() newLoop.body = loop.body?.transform() return newLoop } override fun visitDoWhileLoop(loop: IrDoWhileLoop): IrDoWhileLoop { val newLoop = IrDoWhileLoopImpl(loop.startOffset, loop.endOffset, loop.type, mapStatementOrigin(loop.origin)) transformedLoops[loop] = newLoop newLoop.label = loop.label newLoop.condition = loop.condition.transform() newLoop.body = loop.body?.transform() return newLoop } override fun visitBreak(jump: IrBreak): IrBreak = IrBreakImpl( jump.startOffset, jump.endOffset, jump.type, getTransformedLoop(jump.loop) ).apply { label = jump.label } override fun visitContinue(jump: IrContinue): IrContinue = IrContinueImpl( jump.startOffset, jump.endOffset, jump.type, getTransformedLoop(jump.loop) ).apply { label = jump.label } override fun visitTry(aTry: IrTry): IrTry = IrTryImpl( aTry.startOffset, aTry.endOffset, aTry.type, aTry.tryResult.transform(), aTry.catches.map { it.transform() }, aTry.finallyExpression?.transform() ) override fun visitCatch(aCatch: IrCatch): IrCatch = IrCatchImpl( aCatch.startOffset, aCatch.endOffset, aCatch.catchParameter.transform(), aCatch.result.transform() ) override fun visitReturn(expression: IrReturn): IrReturn = IrReturnImpl( expression.startOffset, expression.endOffset, expression.type, mapReturnTarget(expression.returnTarget), expression.value.transform() ) override fun visitThrow(expression: IrThrow): IrThrow = IrThrowImpl( expression.startOffset, expression.endOffset, expression.type, expression.value.transform() ) override fun visitErrorDeclaration(declaration: IrErrorDeclaration): IrErrorDeclaration = IrErrorDeclarationImpl( declaration.startOffset, declaration.endOffset, mapErrorDeclaration(declaration.descriptor) ) override fun visitErrorExpression(expression: IrErrorExpression): IrErrorExpression = IrErrorExpressionImpl( expression.startOffset, expression.endOffset, expression.type, expression.description ) override fun visitErrorCallExpression(expression: IrErrorCallExpression): IrErrorCallExpression = IrErrorCallExpressionImpl( expression.startOffset, expression.endOffset, expression.type, expression.description ).apply { explicitReceiver = expression.explicitReceiver?.transform() expression.arguments.mapTo(arguments) { it.transform() } } }
12
null
28
83
4383335168338df9bbbe2a63cb213a68d0858104
25,733
kotlin
Apache License 2.0
core/src/main/java/com/bed/core/domain/models/authentication/AuthenticationModel.kt
bed72
674,410,644
false
{"Kotlin": 151713, "Shell": 492}
package com.bed.core.domain.models.authentication data class AuthenticationModel( val uid: String, val name: String, val email: String, val photo: String, val emailVerified: Boolean )
0
Kotlin
0
1
16e9323baf729459e7eff97881ae130d11cf3973
206
Hogwarts
MIT License
composeApp/src/commonMain/kotlin/dev/lennartegb/vec2compose/app/ImageVectorTransformer.kt
LennartEgb
520,006,256
false
{"Kotlin": 194622, "Shell": 892, "HTML": 636}
package dev.lennartegb.vec2compose.app import androidx.compose.ui.graphics.Color import androidx.compose.ui.graphics.PathFillType import androidx.compose.ui.graphics.SolidColor import androidx.compose.ui.graphics.StrokeCap import androidx.compose.ui.graphics.StrokeJoin import androidx.compose.ui.graphics.vector.PathBuilder import androidx.compose.ui.graphics.vector.PathNode import androidx.compose.ui.graphics.vector.addPathNodes import androidx.compose.ui.graphics.vector.group import androidx.compose.ui.graphics.vector.path import androidx.compose.ui.unit.dp import dev.lennartegb.vec2compose.core.ImageVector import dev.lennartegb.vec2compose.core.raw import androidx.compose.ui.graphics.vector.ImageVector as ComposeImageVector fun ImageVector.toCompose(name: String): ComposeImageVector { ComposeImageVector.Builder( name = name, defaultWidth = width.dp, defaultHeight = height.dp, viewportWidth = viewportWidth, viewportHeight = viewportHeight, tintColor = Color.Black, autoMirror = false ) val builder = ComposeImageVector.Builder( name = name, defaultWidth = width.dp, defaultHeight = height.dp, viewportWidth = viewportWidth, viewportHeight = viewportHeight, tintColor = Color.Black, autoMirror = false ) builder.addNodes(nodes) return builder.build() } private fun ImageVector.Path.FillColor.toColor(): Color { return Color(red = red, green = green, blue = blue, alpha = alpha) } private fun ComposeImageVector.Builder.addNodes(nodes: List<ImageVector.Node>) { nodes.forEach { node -> when (node) { is ImageVector.Group -> group( name = node.name.orEmpty(), rotate = node.rotate, pivotX = node.pivot.x, pivotY = node.pivot.y, scaleX = node.scale.x, scaleY = node.scale.y, translationX = node.translation.x, translationY = node.translation.y ) { addNodes(node.nodes) } is ImageVector.Path -> path( fill = node.fillColor?.let { SolidColor(it.toColor()) }, fillAlpha = node.alpha, stroke = node.stroke.color?.let { SolidColor(it.toColor()) }, strokeAlpha = node.stroke.alpha, strokeLineWidth = node.stroke.width, strokeLineCap = when (node.stroke.cap) { ImageVector.Path.Stroke.Cap.Butt -> StrokeCap.Butt ImageVector.Path.Stroke.Cap.Round -> StrokeCap.Round ImageVector.Path.Stroke.Cap.Square -> StrokeCap.Square }, strokeLineJoin = when (node.stroke.join) { ImageVector.Path.Stroke.Join.Bevel -> StrokeJoin.Bevel ImageVector.Path.Stroke.Join.Miter -> StrokeJoin.Miter ImageVector.Path.Stroke.Join.Round -> StrokeJoin.Round }, strokeLineMiter = node.stroke.miter, pathFillType = when (node.fillType) { ImageVector.Path.FillType.NonZero -> PathFillType.NonZero ImageVector.Path.FillType.EvenOdd -> PathFillType.EvenOdd } ) { addCommands(addPathNodes(node.commands.raw)) } } } } private fun PathBuilder.addCommands(commands: List<PathNode>) { commands.forEach { command -> when (command) { is PathNode.ArcTo -> arcTo( horizontalEllipseRadius = command.horizontalEllipseRadius, verticalEllipseRadius = command.verticalEllipseRadius, theta = command.theta, isMoreThanHalf = command.isMoreThanHalf, isPositiveArc = command.isPositiveArc, x1 = command.arcStartX, y1 = command.arcStartY ) PathNode.Close -> close() is PathNode.CurveTo -> curveTo( x1 = command.x1, y1 = command.y1, x2 = command.x2, y2 = command.y2, x3 = command.x3, y3 = command.y3 ) is PathNode.HorizontalTo -> horizontalLineTo(x = command.x) is PathNode.LineTo -> lineTo(x = command.x, y = command.y) is PathNode.MoveTo -> moveTo(x = command.x, y = command.y) is PathNode.QuadTo -> quadTo( x1 = command.x1, y1 = command.y1, x2 = command.x2, y2 = command.y2 ) is PathNode.ReflectiveCurveTo -> reflectiveCurveTo( x1 = command.x1, y1 = command.y1, x2 = command.x2, y2 = command.y2 ) is PathNode.ReflectiveQuadTo -> reflectiveQuadTo(x1 = command.x, y1 = command.y) is PathNode.RelativeArcTo -> arcToRelative( a = command.horizontalEllipseRadius, b = command.verticalEllipseRadius, theta = command.theta, isMoreThanHalf = command.isMoreThanHalf, isPositiveArc = command.isPositiveArc, dx1 = command.arcStartDx, dy1 = command.arcStartDy ) is PathNode.RelativeCurveTo -> curveToRelative( dx1 = command.dx1, dy1 = command.dy1, dx2 = command.dx2, dy2 = command.dy2, dx3 = command.dx3, dy3 = command.dy3 ) is PathNode.RelativeHorizontalTo -> horizontalLineToRelative(dx = command.dx) is PathNode.RelativeLineTo -> lineToRelative(dx = command.dx, dy = command.dy) is PathNode.RelativeMoveTo -> moveToRelative(dx = command.dx, dy = command.dy) is PathNode.RelativeQuadTo -> quadToRelative( dx1 = command.dx1, dy1 = command.dy1, dx2 = command.dx2, dy2 = command.dy2 ) is PathNode.RelativeReflectiveCurveTo -> reflectiveCurveToRelative( dx1 = command.dx1, dy1 = command.dy1, dx2 = command.dx2, dy2 = command.dy2 ) is PathNode.RelativeReflectiveQuadTo -> reflectiveQuadToRelative( dx1 = command.dx, dy1 = command.dy ) is PathNode.RelativeVerticalTo -> verticalLineToRelative(dy = command.dy) is PathNode.VerticalTo -> verticalLineTo(y = command.y) } } }
1
Kotlin
4
29
cd3e0bf9b4733ef0cffb92e2a2050828fcc1e905
6,741
vec2compose
MIT License
kotlin-cdk-wrapper/src/main/kotlin/io/cloudshiftdev/awscdk/services/cloudwatch/CompositeAlarmProps.kt
cloudshiftinc
667,063,030
false
{"Kotlin": 140726596}
@file:Suppress("RedundantVisibilityModifier","RedundantUnitReturnType","RemoveRedundantQualifierName","unused","UnusedImport","ClassName","REDUNDANT_PROJECTION","DEPRECATION") package io.cloudshiftdev.awscdk.services.cloudwatch import io.cloudshiftdev.awscdk.Duration import io.cloudshiftdev.awscdk.common.CdkDslMarker import io.cloudshiftdev.awscdk.common.CdkObject import io.cloudshiftdev.awscdk.common.CdkObjectWrappers import kotlin.Boolean import kotlin.String import kotlin.Unit /** * Properties for creating a Composite Alarm. * * Example: * * ``` * Alarm alarm1; * Alarm alarm2; * Alarm alarm3; * Alarm alarm4; * IAlarmRule alarmRule = AlarmRule.anyOf(AlarmRule.allOf(AlarmRule.anyOf(alarm1, * AlarmRule.fromAlarm(alarm2, AlarmState.OK), alarm3), AlarmRule.not(AlarmRule.fromAlarm(alarm4, * AlarmState.INSUFFICIENT_DATA))), AlarmRule.fromBoolean(false)); * CompositeAlarm.Builder.create(this, "MyAwesomeCompositeAlarm") * .alarmRule(alarmRule) * .build(); * ``` */ public interface CompositeAlarmProps { /** * Whether the actions for this alarm are enabled. * * Default: true */ public fun actionsEnabled(): Boolean? = unwrap(this).getActionsEnabled() /** * Actions will be suppressed if the suppressor alarm is in the ALARM state. * * Default: - alarm will not be suppressed. */ public fun actionsSuppressor(): IAlarm? = unwrap(this).getActionsSuppressor()?.let(IAlarm::wrap) /** * The maximum duration that the composite alarm waits after suppressor alarm goes out of the * ALARM state. * * After this time, the composite alarm performs its actions. * * Default: - 1 minute extension period will be set. */ public fun actionsSuppressorExtensionPeriod(): Duration? = unwrap(this).getActionsSuppressorExtensionPeriod()?.let(Duration::wrap) /** * The maximum duration that the composite alarm waits for the suppressor alarm to go into the * ALARM state. * * After this time, the composite alarm performs its actions. * * Default: - 1 minute wait period will be set. */ public fun actionsSuppressorWaitPeriod(): Duration? = unwrap(this).getActionsSuppressorWaitPeriod()?.let(Duration::wrap) /** * Description for the alarm. * * Default: - No description. */ public fun alarmDescription(): String? = unwrap(this).getAlarmDescription() /** * Expression that specifies which other alarms are to be evaluated to determine this composite * alarm's state. */ public fun alarmRule(): IAlarmRule /** * Name of the alarm. * * Default: - Automatically generated name. */ public fun compositeAlarmName(): String? = unwrap(this).getCompositeAlarmName() /** * A builder for [CompositeAlarmProps] */ @CdkDslMarker public interface Builder { /** * @param actionsEnabled Whether the actions for this alarm are enabled. */ public fun actionsEnabled(actionsEnabled: Boolean) /** * @param actionsSuppressor Actions will be suppressed if the suppressor alarm is in the ALARM * state. */ public fun actionsSuppressor(actionsSuppressor: IAlarm) /** * @param actionsSuppressorExtensionPeriod The maximum duration that the composite alarm waits * after suppressor alarm goes out of the ALARM state. * After this time, the composite alarm performs its actions. */ public fun actionsSuppressorExtensionPeriod(actionsSuppressorExtensionPeriod: Duration) /** * @param actionsSuppressorWaitPeriod The maximum duration that the composite alarm waits for * the suppressor alarm to go into the ALARM state. * After this time, the composite alarm performs its actions. */ public fun actionsSuppressorWaitPeriod(actionsSuppressorWaitPeriod: Duration) /** * @param alarmDescription Description for the alarm. */ public fun alarmDescription(alarmDescription: String) /** * @param alarmRule Expression that specifies which other alarms are to be evaluated to * determine this composite alarm's state. */ public fun alarmRule(alarmRule: IAlarmRule) /** * @param compositeAlarmName Name of the alarm. */ public fun compositeAlarmName(compositeAlarmName: String) } private class BuilderImpl : Builder { private val cdkBuilder: software.amazon.awscdk.services.cloudwatch.CompositeAlarmProps.Builder = software.amazon.awscdk.services.cloudwatch.CompositeAlarmProps.builder() /** * @param actionsEnabled Whether the actions for this alarm are enabled. */ override fun actionsEnabled(actionsEnabled: Boolean) { cdkBuilder.actionsEnabled(actionsEnabled) } /** * @param actionsSuppressor Actions will be suppressed if the suppressor alarm is in the ALARM * state. */ override fun actionsSuppressor(actionsSuppressor: IAlarm) { cdkBuilder.actionsSuppressor(actionsSuppressor.let(IAlarm.Companion::unwrap)) } /** * @param actionsSuppressorExtensionPeriod The maximum duration that the composite alarm waits * after suppressor alarm goes out of the ALARM state. * After this time, the composite alarm performs its actions. */ override fun actionsSuppressorExtensionPeriod(actionsSuppressorExtensionPeriod: Duration) { cdkBuilder.actionsSuppressorExtensionPeriod(actionsSuppressorExtensionPeriod.let(Duration.Companion::unwrap)) } /** * @param actionsSuppressorWaitPeriod The maximum duration that the composite alarm waits for * the suppressor alarm to go into the ALARM state. * After this time, the composite alarm performs its actions. */ override fun actionsSuppressorWaitPeriod(actionsSuppressorWaitPeriod: Duration) { cdkBuilder.actionsSuppressorWaitPeriod(actionsSuppressorWaitPeriod.let(Duration.Companion::unwrap)) } /** * @param alarmDescription Description for the alarm. */ override fun alarmDescription(alarmDescription: String) { cdkBuilder.alarmDescription(alarmDescription) } /** * @param alarmRule Expression that specifies which other alarms are to be evaluated to * determine this composite alarm's state. */ override fun alarmRule(alarmRule: IAlarmRule) { cdkBuilder.alarmRule(alarmRule.let(IAlarmRule.Companion::unwrap)) } /** * @param compositeAlarmName Name of the alarm. */ override fun compositeAlarmName(compositeAlarmName: String) { cdkBuilder.compositeAlarmName(compositeAlarmName) } public fun build(): software.amazon.awscdk.services.cloudwatch.CompositeAlarmProps = cdkBuilder.build() } private class Wrapper( cdkObject: software.amazon.awscdk.services.cloudwatch.CompositeAlarmProps, ) : CdkObject(cdkObject), CompositeAlarmProps { /** * Whether the actions for this alarm are enabled. * * Default: true */ override fun actionsEnabled(): Boolean? = unwrap(this).getActionsEnabled() /** * Actions will be suppressed if the suppressor alarm is in the ALARM state. * * Default: - alarm will not be suppressed. */ override fun actionsSuppressor(): IAlarm? = unwrap(this).getActionsSuppressor()?.let(IAlarm::wrap) /** * The maximum duration that the composite alarm waits after suppressor alarm goes out of the * ALARM state. * * After this time, the composite alarm performs its actions. * * Default: - 1 minute extension period will be set. */ override fun actionsSuppressorExtensionPeriod(): Duration? = unwrap(this).getActionsSuppressorExtensionPeriod()?.let(Duration::wrap) /** * The maximum duration that the composite alarm waits for the suppressor alarm to go into the * ALARM state. * * After this time, the composite alarm performs its actions. * * Default: - 1 minute wait period will be set. */ override fun actionsSuppressorWaitPeriod(): Duration? = unwrap(this).getActionsSuppressorWaitPeriod()?.let(Duration::wrap) /** * Description for the alarm. * * Default: - No description. */ override fun alarmDescription(): String? = unwrap(this).getAlarmDescription() /** * Expression that specifies which other alarms are to be evaluated to determine this composite * alarm's state. */ override fun alarmRule(): IAlarmRule = unwrap(this).getAlarmRule().let(IAlarmRule::wrap) /** * Name of the alarm. * * Default: - Automatically generated name. */ override fun compositeAlarmName(): String? = unwrap(this).getCompositeAlarmName() } public companion object { public operator fun invoke(block: Builder.() -> Unit = {}): CompositeAlarmProps { val builderImpl = BuilderImpl() return Wrapper(builderImpl.apply(block).build()) } internal fun wrap(cdkObject: software.amazon.awscdk.services.cloudwatch.CompositeAlarmProps): CompositeAlarmProps = CdkObjectWrappers.wrap(cdkObject) as? CompositeAlarmProps ?: Wrapper(cdkObject) internal fun unwrap(wrapped: CompositeAlarmProps): software.amazon.awscdk.services.cloudwatch.CompositeAlarmProps = (wrapped as CdkObject).cdkObject as software.amazon.awscdk.services.cloudwatch.CompositeAlarmProps } }
1
Kotlin
0
4
db2b3a364f5e74d8f80490e7850da7f1e7f1e7d0
9,372
kotlin-cdk-wrapper
Apache License 2.0
domain/src/main/java/com/kurly/android/domain/Food.kt
KurlyMeals
516,862,056
false
null
package com.kurly.android.domain class Food
0
Kotlin
0
0
06362b07db7f233dea6b23fce7cd7161ae13d41b
45
kurlymeals-android
MIT License
src/test/kotlin/com/kotlin/resiliency/ResiliencyApplicationTestsConfiguration.kt
vyvyd
455,698,472
false
null
package com.kotlin.resiliency import com.github.tomakehurst.wiremock.WireMockServer import org.springframework.boot.test.context.TestConfiguration import org.springframework.boot.web.client.RestTemplateBuilder import org.springframework.context.annotation.Bean import org.springframework.context.annotation.Primary import org.springframework.context.annotation.Scope import org.springframework.web.client.RestOperations import org.springframework.web.client.RestTemplate import org.springframework.web.util.DefaultUriBuilderFactory @TestConfiguration class ResiliencyApplicationTestsConfiguration { @Bean @Scope("singleton") fun wireMockServer(): WireMockServer { return WireMockServer(9087).also{ it.start() } } @Bean @Primary fun restOperations(wireMockServer: WireMockServer) : RestOperations { val factory = DefaultUriBuilderFactory(wireMockServer.baseUrl()) return RestTemplate().also { it.uriTemplateHandler = factory } } }
0
Kotlin
0
0
000dbcc3bbe13876908e0eeef709cc9eeb5d2c1a
957
resiliency-with-arrowkt
MIT License
app/src/main/java/me/devsaki/hentoid/util/AchievementsManager.kt
avluis
37,775,708
false
{"C": 4044011, "Kotlin": 2794467, "Java": 616300, "C++": 465431, "CMake": 44472, "M4": 42737, "Shell": 41599, "Roff": 38560, "Makefile": 33752, "Python": 26865, "HTML": 6592, "JavaScript": 6327, "CSS": 1842, "Go": 1235}
package me.devsaki.hentoid.util import android.content.Context import me.devsaki.hentoid.R import me.devsaki.hentoid.core.HentoidApp import me.devsaki.hentoid.database.AchievementsDAO import me.devsaki.hentoid.database.domains.Achievement import me.devsaki.hentoid.enums.Site import me.devsaki.hentoid.events.AchievementEvent import me.devsaki.hentoid.json.core.JsonAchievements import me.devsaki.hentoid.util.file.isLowDeviceStorage import me.devsaki.hentoid.util.file.readStreamAsString import org.greenrobot.eventbus.EventBus import timber.log.Timber import java.time.Instant import kotlin.math.max import kotlin.math.pow object AchievementsManager { private val syncObject = Any() private var storageCache = Settings.achievements val masterdata: Map<Int, Achievement> by lazy { init(HentoidApp.getInstance()) } fun init(context: Context): Map<Int, Achievement> { val result = HashMap<Int, Achievement>() context.resources.openRawResource(R.raw.achievements).use { `is` -> val achievementsStr = readStreamAsString(`is`) val achievementsObj = JsonHelper.jsonToObject( achievementsStr, JsonAchievements::class.java ) achievementsObj.achievements.forEach { entry -> val id = entry.id val title = context.resources.getIdentifier( "ach_name_$id", "string", context.packageName ) val desc = context.resources.getIdentifier( "ach_desc_$id", "string", context.packageName ) result[entry.id] = Achievement( entry.id, entry.type, false, title, desc, R.drawable.ic_achievement ) } } result[62] = Achievement( 62, Achievement.Type.GOLD, true, R.string.ach_name_62, R.string.ach_desc_62, R.drawable.ic_star_full ) result[63] = Achievement( 63, Achievement.Type.GOLD, true, R.string.ach_name_63, R.string.ach_desc_63, R.drawable.ic_star_full ) return result } fun checkPrefs() { if (!isRegistered(1)) { if (1 == Preferences.getActiveSites().size) registerAndSignal(1) } } fun checkStorage(context: Context) { if (!isRegistered(18)) { if (context.isLowDeviceStorage(98)) registerAndSignal(18) } } fun checkCollection() { val db = AchievementsDAO() val now = Instant.now().toEpochMilli() try { val eligibleContent = db.selectEligibleContentIds(); if (!isRegistered(3) || !isRegistered(4) || !isRegistered(5)) { val readPages = db.selectTotalReadPages() if (!isRegistered(5) && readPages >= 5000) registerAndSignal(5) if (!isRegistered(4) && readPages >= 1000) registerAndSignal(4) if (!isRegistered(3) && readPages >= 500) registerAndSignal(3) } if (!isRegistered(6) || !isRegistered(7) || !isRegistered(8)) { val largestArtist = db.selectLargestArtist(eligibleContent, 50) if (!isRegistered(8) && largestArtist >= 50) registerAndSignal(8) if (!isRegistered(7) && largestArtist >= 30) registerAndSignal(7) if (!isRegistered(6) && largestArtist >= 10) registerAndSignal(6) } if (!isRegistered(9) && eligibleContent.size >= 1000) registerAndSignal(9) if (!isRegistered(10) && eligibleContent.size >= 2000) registerAndSignal(10) if (!isRegistered(11) && eligibleContent.size >= 5000) registerAndSignal(11) if (!isRegistered(12)) { val count = db.countWithTagsOr(eligibleContent, "netorare", "ntr") if (count >= 20) registerAndSignal(12) } if (!isRegistered(13)) { val count = db.countWithTagsAnd(eligibleContent, "glasses", "big ass") if (count >= 20) registerAndSignal(13) } if (!isRegistered(14)) { val count = db.countWithTagsOr(eligibleContent, "lingerie") if (count >= 20) registerAndSignal(14) } if (!isRegistered(15)) { val count = db.countWithTagsOr(eligibleContent, "stockings") if (count >= 20) registerAndSignal(15) } if (!isRegistered(17) && eligibleContent.isNotEmpty()) { val newestRead = db.selectNewestRead() val newestDownload = db.selectNewestDownload() val maxDiff = now - max(newestRead, newestDownload) if (maxDiff >= 72 * 60 * 60 * 1000) registerAndSignal(17) } if (!isRegistered(19)) { val invisibleSites = Site.entries.filter { e -> !e.isVisible }.filterNot { e -> e == Site.NONE } val count = db.countWithSitesOr(eligibleContent, invisibleSites) if (count >= 10) registerAndSignal(19) } if (!isRegistered(21)) { val count = db.countWithTagsOr(eligibleContent, "x-ray", "nakadashi") if (count >= 20) registerAndSignal(21) } if (!isRegistered(22)) { val count = db.countWithTagsOr(eligibleContent, "story arc") if (count >= 20) registerAndSignal(22) } if (!isRegistered(23)) { if (db.hasAtLeastCHapters(eligibleContent, 300)) registerAndSignal(23) } if (!isRegistered(24)) { val nbBooks = eligibleContent.size val nbUngroupedBooks = db.selectUngroupedContentIds().size if (nbBooks >= 100 && 0 == nbUngroupedBooks) registerAndSignal(24) } if (!isRegistered(25)) { val count = db.countQueuedBooks() if (count > 50) registerAndSignal(25) } if (!isRegistered(26)) { val count = db.countQueuedBooks() if (count > 100) registerAndSignal(26) } if (!isRegistered(30)) { val oldestUpload = db.selectOldestUpload() if (oldestUpload > 0) { val maxDiff = (now - oldestUpload) / (365L * 24 * 60 * 60 * 1000) // Years if (maxDiff >= 10) registerAndSignal(30) } } } finally { db.cleanup() } } fun trigger(id: Int) { if (isRegistered(id)) return registerAndSignal(id) } private fun registerAndSignal(id: Int) { Timber.d("ACHIEVEMENT $id UNLOCKED") register(id) EventBus.getDefault().postSticky(AchievementEvent(id)) } private fun register(id: Int) { if (id > 63) throw Exception("The app doesn't support more than 64 different achievements") val storageId = 2f.pow(id).toULong() synchronized(syncObject) { storageCache = storageCache or storageId Settings.achievements = storageCache } } fun isRegistered(id: Int): Boolean { return isRegistered(id, storageCache) } private fun isRegistered(id: Int, storage: ULong): Boolean { if (id > 63) throw Exception("The app doesn't support more than 64 different achievements") val storageId = 2f.pow(id).toULong() return (storage and storageId > 0UL) } }
173
C
85
992
f54df07b79da4147951bc9902ab0dbd70edb50f1
7,873
Hentoid
Apache License 2.0
app/src/main/java/com/example/berberappointment/register/Register.kt
BerkayKaramehmetoglu
733,084,694
false
null
package com.example.berberappointment.register import android.text.BoringLayout import com.example.berberappointment.berber.CreateBerber import com.google.firebase.database.IgnoreExtraProperties @IgnoreExtraProperties data class Register( var userName: String? = null, var lastName: String? = null, var phoneNumber: Long? = null, var password: String? = null, var isStaff: Boolean? = false, var isBerber: Boolean? = false, var appointmentDatetime: String? = null, var appointmentBerber: String? = null ) { companion object { fun fromCreateBerber(createBerber: CreateBerber): Register { return Register( userName = createBerber.berberName, lastName = createBerber.berberLName, phoneNumber = createBerber.berberPNumber, password = <PASSWORD>, isBerber = createBerber.isBerber, ) } } }
0
null
0
1
1158d99bb5957d22e816c3a5bf04cbf0cdfc1326
944
BerberAppointment
MIT License
games-server/src/main/kotlin/net/zomis/games/server2/db/DBGame.kt
Tejpbit
260,966,032
true
{"Gradle": 5, "Markdown": 6, "Dockerfile": 1, "JSON": 3, "Shell": 1, "Ignore List": 4, "Batchfile": 1, "Groovy": 1, "HTML": 2, "JavaScript": 16, "Kotlin": 99, "INI": 2, "Dotenv": 2, "Browserslist": 1, "Vue": 32, "CSS": 3, "SVG": 1, "Java": 3, "Java Properties": 1}
package net.zomis.games.server2.db import com.fasterxml.jackson.annotation.JsonIgnore import com.fasterxml.jackson.annotation.JsonUnwrapped import com.fasterxml.jackson.module.kotlin.jacksonObjectMapper import net.zomis.games.dsl.GameSpec import net.zomis.games.dsl.impl.GameImpl import net.zomis.games.dsl.impl.GameSetupImpl import net.zomis.games.dsl.impl.StateKeeper enum class GameState(val value: Int) { HIDDEN(-1), UNFINISHED(0), PUBLIC(1), ; } data class PlayerInGameResults(val result: Double, val resultPosition: Int, val resultReason: String, val score: Map<String, Any?>) data class PlayerInGame(val player: PlayerView?, val playerIndex: Int, val results: PlayerInGameResults?) class BadReplayException(message: String): Exception(message) private val mapper = jacksonObjectMapper() data class DBGameSummary( @JsonIgnore val gameSpec: GameSpec<Any>, val gameId: String, val playersInGame: List<PlayerInGame>, val gameType: String, val gameState: Int, @JsonIgnore val startingState: Map<String, Any>?, val timeStarted: Long, val timeLastAction: Long ) class DBGame(@JsonUnwrapped val summary: DBGameSummary, @JsonIgnore val moveHistory: List<MoveHistory>) { private val gameSetup = GameSetupImpl(summary.gameSpec) @JsonIgnore val stateKeeper = StateKeeper().also { if (summary.startingState != null) it.setState(summary.startingState) } @JsonIgnore val game = gameSetup.createGameWithState(summary.playersInGame.size, gameSetup.getDefaultConfig(), stateKeeper) val views = mutableListOf<Map<String, Any?>>() init { views.add(game.view(null)) moveHistory.withIndex().forEach { move -> performMove(game, move) views.add(game.view(null)) } } private fun performMove(game: GameImpl<Any>, move: IndexedValue<MoveHistory>) { val it = move.value val logic = game.actions[it.moveType] ?: throw BadReplayException("Unable to perform $it: No such move type") val param = if (it.move == null) Unit else mapper.readValue(mapper.writeValueAsString(it.move), logic.parameterClass.java) val actionable = logic.createAction(it.playerIndex, param) if (!logic.isAllowed(actionable)) { val view = game.view(null) throw BadReplayException("Unable to perform $it: Move at index ${move.index} is not allowed. View is $view") } try { logic.replayAction(actionable, it.state) game.stateCheck() } catch (e: Exception) { throw IllegalStateException("Unable to perform move: $move", e) } } fun at(position: Int): GameImpl<Any> { val game = gameSetup.createGame(summary.playersInGame.size, gameSetup.getDefaultConfig()) moveHistory.slice(0 until position).withIndex().forEach { performMove(game, it) } return game } }
0
null
0
0
cb1cafb4d5ae5c09a9edb336f04ef7cf48ee2714
2,938
Server2
MIT License
producer/src/main/kotlin/com/codeforprofit/redis/producer/config/RedisConfiguration.kt
jimador
175,811,188
false
{"Batchfile": 3, "Shell": 3, "Maven POM": 3, "Text": 1, "Ignore List": 3, "Git Attributes": 3, "EditorConfig": 1, "Markdown": 1, "INI": 3, "Java": 6, "YAML": 3, "Kotlin": 5}
package com.codeforprofit.redis.producer.config import org.springframework.boot.context.properties.EnableConfigurationProperties import org.springframework.context.annotation.Bean import org.springframework.context.annotation.Configuration import org.springframework.data.redis.connection.ReactiveRedisConnectionFactory import org.springframework.data.redis.connection.RedisConnectionFactory import org.springframework.data.redis.connection.stream.* import org.springframework.data.redis.core.ReactiveRedisOperations import org.springframework.data.redis.core.ReactiveRedisTemplate import org.springframework.data.redis.serializer.RedisSerializationContext import org.springframework.data.redis.stream.StreamMessageListenerContainer @Configuration @EnableConfigurationProperties(RedisProperties::class) class RedisConfiguration { @Bean fun reactiveRedisOperations(factory: ReactiveRedisConnectionFactory): ReactiveRedisOperations<String, String> { return ReactiveRedisTemplate<String, String>(factory, RedisSerializationContext.string()) } @Bean fun messageListener(factory: RedisConnectionFactory): StreamMessageListenerContainer<String, MapRecord<String, String, String>> { return StreamMessageListenerContainer.create(factory) .apply { receive(Consumer.from("group1", "name1"), StreamOffset.create("stream1", ReadOffset.lastConsumed())) { message -> println(message) } }.also { it.start() } } }
0
Kotlin
0
0
5454c7fa2edf2cd6830ec6e60843ae56f73b80eb
1,502
spring-redis-playground
MIT License
adaptive-ui/src/iosMain/kotlin/fun/adaptive/ui/fragment/layout/AuiRow.kt
spxbhuhb
788,711,010
false
{"Kotlin": 2431816, "Java": 25628, "HTML": 8024, "JavaScript": 3880, "Shell": 687}
/* * Copyright © 2020-2024, <NAME> and contributors. Use of this source code is governed by the Apache 2.0 license. */ package `fun`.adaptive.ui.fragment.layout import `fun`.adaptive.foundation.AdaptiveActual import `fun`.adaptive.foundation.AdaptiveFragment import `fun`.adaptive.ui.AuiAdapter import `fun`.adaptive.ui.aui import `fun`.adaptive.ui.platform.ContainerView import platform.UIKit.UIView @AdaptiveActual(aui) class AuiGrid( adapter: AuiAdapter, parent: AdaptiveFragment, declarationIndex: Int ) : AbstractGrid<UIView, ContainerView>(adapter, parent, declarationIndex) { init { receiver.tag = id } }
34
Kotlin
0
3
d918ce69019eed365dd47b63ea953d1c04b0f89f
643
adaptive
Apache License 2.0
src/main/kotlin/kotlinmud/mob/provider/MobProvider.kt
brandonlamb
275,313,206
true
{"Kotlin": 435931, "Dockerfile": 133, "Shell": 126}
package kotlinmud.mob.provider import java.io.EOFException import kotlinmud.fs.factory.playerMobFile import kotlinmud.fs.loader.Tokenizer import kotlinmud.mob.loader.MobLoader import kotlinmud.mob.model.Mob fun loadMobs(loadSchemaToUse: Int): MutableList<Mob> { val file = playerMobFile() if (!file.exists()) { return mutableListOf() } val tokenizer = Tokenizer(file.readText()) val mobLoader = MobLoader(tokenizer, loadSchemaToUse) val mobs = mutableListOf<Mob>() while (true) { try { mobs.add(mobLoader.load().build()) } catch (e: EOFException) { break } } return mobs }
0
null
0
0
fc03c6230b9b3b66cd63994e74ddd7897732d527
667
kotlinmud
MIT License
shared/src/commonMain/kotlin/reels/ui/components/ReelFooter.kt
pallaw
692,042,871
false
{"Kotlin": 22487, "Swift": 592, "Shell": 228}
package reels.ui.components import androidx.compose.foundation.background import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.aspectRatio import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.size import androidx.compose.foundation.shape.CircleShape import androidx.compose.material.Icon import androidx.compose.material.IconButton import androidx.compose.material.Text import androidx.compose.material.icons.Icons import androidx.compose.material.icons.filled.Comment import androidx.compose.material.icons.filled.Favorite import androidx.compose.material.icons.filled.MoreVert import androidx.compose.material.icons.filled.Share 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.unit.dp import io.kamel.image.KamelImage import io.kamel.image.asyncPainterResource import reelsList.data.model.Reel @Composable fun ReelFooter(reel: Reel) { Column( modifier = Modifier.fillMaxSize().padding(16.dp), verticalArrangement = Arrangement.Bottom ) { FooterCtaButtons() FooterReelInformation(reel) } } @Composable fun FooterCtaButtons() { //CTA buttons Column( modifier = Modifier.fillMaxWidth(), horizontalAlignment = Alignment.End ) { IconButton(onClick = { println("Fav Button clicked") }) { Icon(Icons.Filled.Favorite, contentDescription = "favorite") } IconButton(onClick = { println("Comment Button clicked") }) { Icon(Icons.Filled.Comment, contentDescription = "Comment") } IconButton(onClick = { println("Share Button clicked") }) { Icon(Icons.Filled.Share, contentDescription = "Share") } IconButton(onClick = { println("More Button clicked") }) { Icon(Icons.Filled.MoreVert, contentDescription = "More") } } } @Composable fun FooterReelInformation(reel: Reel) { Column( verticalArrangement = Arrangement.spacedBy(8.dp) ) { Row( horizontalArrangement = Arrangement.spacedBy(4.dp) ) { KamelImage( modifier = Modifier .size(24.dp) .aspectRatio(1.0f) .clip(CircleShape) .background(Color.Black), resource = asyncPainterResource(reel.thumb), contentDescription = "User DP" ) Text("${reel.title}") } Text(maxLines = 2, text = "${reel.description}") } }
0
Kotlin
0
0
40eb6d04acc40dce59746750d5aa7e867299437f
2,936
compose-multiplatform-ios-android-instagram-reels-clone
Apache License 2.0
src/main/kotlin/ml/demidko/subweb/data/types/NormalizedUrl.kt
demidko
403,930,960
false
{"Kotlin": 11118, "Dockerfile": 271}
package ml.demidko.subweb.data.types class NormalizedUrl(s: String) : CharSequence by s .trim(' ', '/') .lowercase() .replaceFirst("https://", "") .replaceFirst("http://", "") .replaceFirst("www.", "")
0
Kotlin
0
1
80ee78c46e134699c3686c59c6781ec472d75b38
224
SubWeb
MIT License
dsl/src/main/kotlin/io/cloudshiftdev/awscdkdsl/services/appmesh/CfnVirtualGatewayVirtualGatewayFileAccessLogPropertyDsl.kt
cloudshiftinc
667,063,030
false
{"Kotlin": 63959868}
@file:Suppress( "RedundantVisibilityModifier", "RedundantUnitReturnType", "RemoveRedundantQualifierName", "unused", "UnusedImport", "ClassName", "REDUNDANT_PROJECTION", "DEPRECATION" ) package cloudshift.awscdk.dsl.services.appmesh import cloudshift.awscdk.common.CdkDslMarker import kotlin.String import software.amazon.awscdk.IResolvable import software.amazon.awscdk.services.appmesh.CfnVirtualGateway /** * An object that represents an access log file. * * Example: * ``` * // The code below shows an example of how to instantiate this type. * // The values are placeholders you should change. * import software.amazon.awscdk.services.appmesh.*; * VirtualGatewayFileAccessLogProperty virtualGatewayFileAccessLogProperty = * VirtualGatewayFileAccessLogProperty.builder() * .path("path") * // the properties below are optional * .format(LoggingFormatProperty.builder() * .json(List.of(JsonFormatRefProperty.builder() * .key("key") * .value("value") * .build())) * .text("text") * .build()) * .build(); * ``` * * [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-appmesh-virtualgateway-virtualgatewayfileaccesslog.html) */ @CdkDslMarker public class CfnVirtualGatewayVirtualGatewayFileAccessLogPropertyDsl { private val cdkBuilder: CfnVirtualGateway.VirtualGatewayFileAccessLogProperty.Builder = CfnVirtualGateway.VirtualGatewayFileAccessLogProperty.builder() /** * @param format The specified format for the virtual gateway access logs. It can be either * `json_format` or `text_format` . */ public fun format(format: IResolvable) { cdkBuilder.format(format) } /** * @param format The specified format for the virtual gateway access logs. It can be either * `json_format` or `text_format` . */ public fun format(format: CfnVirtualGateway.LoggingFormatProperty) { cdkBuilder.format(format) } /** * @param path The file path to write access logs to. You can use `/dev/stdout` to send access * logs to standard out and configure your Envoy container to use a log driver, such as * `awslogs` , to export the access logs to a log storage service such as Amazon CloudWatch * Logs. You can also specify a path in the Envoy container's file system to write the files * to disk. */ public fun path(path: String) { cdkBuilder.path(path) } public fun build(): CfnVirtualGateway.VirtualGatewayFileAccessLogProperty = cdkBuilder.build() }
4
Kotlin
0
3
c59c6292cf08f0fc3280d61e7f8cff813a608a62
2,581
awscdk-dsl-kotlin
Apache License 2.0
kotlin-node/src/jsMain/generated/node/fs/StreamOptions.kt
JetBrains
93,250,841
false
{"Kotlin": 11989651, "JavaScript": 231504}
// Generated by Karakum - do not modify it manually! package node.fs sealed external interface StreamOptions { var flags: String? var encoding: node.buffer.BufferEncoding? var fd: Any? /* number | promises.FileHandle | undefined */ var mode: Double? var autoClose: Boolean? /** * @default false */ var emitClose: Boolean? var start: Double? var highWaterMark: Double? }
33
Kotlin
176
1,266
167767803bf3245ff9277386e261c9f2eab60d6e
421
kotlin-wrappers
Apache License 2.0
calendar/src/main/kotlin/calendar/DBClasses.kt
Buldugmaster99
386,209,155
false
null
package calendar import calendar.Timing.toUTCEpochMinute import javafx.scene.paint.* import logic.LogType import logic.log import org.jetbrains.exposed.dao.IntEntity import org.jetbrains.exposed.dao.IntEntityClass import org.jetbrains.exposed.dao.LongEntity import org.jetbrains.exposed.dao.LongEntityClass import org.jetbrains.exposed.dao.id.EntityID import org.jetbrains.exposed.sql.transactions.transaction import replaceNewline import java.time.LocalDate import java.time.LocalDateTime class Appointment(id: EntityID<Long>): LongEntity(id), DBClass { object Appointments: LongEntityClass<Appointment>(AppointmentTable) companion object { @Suppress("LongParameterList") fun new( start: LocalDateTime, end: LocalDateTime, title: String, description: String, type: Type, allDay: Boolean = false, week: Boolean = false ): Appointment { return transaction { return@transaction Appointments.new { this.start.set(start) this.end.set(end) this.title.set(title) this.description.set(description) this.type.set(type) this.allDay.set(allDay) this.week.set(week) }.also { calendar.Appointments.add(it); log("Appointment $it created", LogType.IMPORTANT) } } } } private var dbStart by AppointmentTable.start private var dbEnd by AppointmentTable.end private var dbTitle by AppointmentTable.title private var dbDescription by AppointmentTable.description private var dbAllDay by AppointmentTable.allDay private var dbType by Type.Types referencedOn AppointmentTable.type private var dbWeek by AppointmentTable.week val start: DBDateTimeObservable = object: DBDateTimeObservable() { override fun abstractGet(): Long = dbStart override fun abstractSet(dat: Long) { dbStart = dat } } val end: DBDateTimeObservable = object: DBDateTimeObservable() { override fun abstractGet(): Long = dbEnd override fun abstractSet(dat: Long) { dbEnd = dat } } val title: DBObservable<String> = object: DBObservable<String>() { override fun abstractGet(): String = dbTitle override fun abstractSet(dat: String) { dbTitle = dat } } val description: DBObservable<String> = object: DBObservable<String>() { override fun abstractGet(): String = dbDescription override fun abstractSet(dat: String) { dbDescription = dat } } val allDay: DBObservable<Boolean> = object: DBObservable<Boolean>() { override fun abstractGet(): Boolean = dbAllDay override fun abstractSet(dat: Boolean) { dbAllDay = dat } } val type: DBObservable<Type> = object: DBObservable<Type>() { override fun abstractGet(): Type = dbType override fun abstractSet(dat: Type) { dbType = dat } } val week: DBObservable<Boolean> = object: DBObservable<Boolean>() { override fun abstractGet(): Boolean = dbWeek override fun abstractSet(dat: Boolean) { dbWeek = dat } } override fun remove() { calendar.Appointments.remove(this) log("Appointment $this removed", LogType.IMPORTANT) transaction { delete() } } // [{7} 2022-05-16T00:00 - 2022-05-16T23:59 [{1} test 0x008000ff] frame.Day | test_1_title: test_1_desc] override fun toString(): String = ("[{${id.value}} ${start.value} - ${end.value} ${type.value} " + "${if(week.value) "Week" else "frame.Day"} | " + "${title.value}: ${description.value}]").replaceNewline() override fun equals(other: Any?): Boolean { return if(other !is Appointment) false else other.id == id } override fun hashCode(): Int { var result = start.hashCode() result = 31 * result + end.hashCode() result = 31 * result + title.hashCode() result = 31 * result + description.hashCode() result = 31 * result + type.hashCode() result = 31 * result + week.hashCode() return result } } class Note(id: EntityID<Long>): LongEntity(id), DBClass { object Notes: LongEntityClass<Note>(NoteTable) companion object { fun new(time: LocalDate, text: String, type: Type, week: Boolean): Note { return transaction { return@transaction Notes.new { this.time.set(time) this.text.set(text) this.type.set(type) this.week.set(week) }.also { calendar.Notes.add(it); log("Note $it created", LogType.IMPORTANT) } } } } private var dbTime by NoteTable.time private var dbText by NoteTable.text private var dbType by Type.Types referencedOn NoteTable.type private var dbWeek by NoteTable.week // private val dbFiles by File.Files referrersOn FileTable.note val time: DBDateObservable = object: DBDateObservable() { override fun abstractGet(): Long = dbTime override fun abstractSet(dat: Long) { dbTime = dat } } val text: DBObservable<String> = object: DBObservable<String>() { override fun abstractGet(): String = dbText override fun abstractSet(dat: String) { dbText = dat } } val type: DBObservable<Type> = object: DBObservable<Type>() { override fun abstractGet(): Type = dbType override fun abstractSet(dat: Type) { dbType = dat } } private val files = arrayListOf<File>() // TODO not implemented // val files: DBObservable<SizedIterable<File>> = object: DBObservable<SizedIterable<File>>() { // override fun abstractGet(): SizedIterable<File> = dbFiles // override fun abstractSet(dat: SizedIterable<File>) { // TODO("TODO Not implemented") // } // } val week: DBObservable<Boolean> = object: DBObservable<Boolean>() { override fun abstractGet(): Boolean = dbWeek override fun abstractSet(dat: Boolean) { dbWeek = dat } } override fun remove() { calendar.Notes.remove(this) log("Note $this removed", LogType.IMPORTANT) transaction { delete() } } // [{2} 2022-05-16T00:00 [{1} test 0x008000ff] ||: test_note_text] override fun toString(): String = "[{${id.value}} ${time.value} ${type.value} |$files|: ${text.value}]".replaceNewline() override fun equals(other: Any?): Boolean { return if(other !is Note) false else other.id == id } override fun hashCode(): Int { var result = time.hashCode() result = 31 * result + text.hashCode() result = 31 * result + type.hashCode() result = 31 * result + week.hashCode() result = 31 * result + files.hashCode() return result } } class File(id: EntityID<Long>): LongEntity(id), DBClass { object Files: LongEntityClass<File>(FileTable) companion object { fun new(_data: ByteArray, _name: String, _origin: String): File { return transaction { return@transaction Files.new { // data.set(_data) name.set(_name) origin.set(_origin) }.also { calendar.Files.add(it); log("File $it created", LogType.IMPORTANT) } } } } // private var dbData by FileTable.data private var dbName by FileTable.name private var dbOrigin by FileTable.origin // var data: DBObservableD<ByteArray, String> = object: DBObservableD<ByteArray, String>(dbData) { // override fun convertFrom(value: ByteArray?): String? = value?.decodeToString() // override fun convertTo(value: String?): ByteArray? = value?.encodeToByteArray() // } var name: DBObservable<String> = object: DBObservable<String>() { override fun abstractGet(): String = dbName override fun abstractSet(dat: String) { dbName = dat } } var origin: DBObservable<String> = object: DBObservable<String>() { override fun abstractGet(): String = dbOrigin override fun abstractSet(dat: String) { dbOrigin = dat } } override fun remove() { calendar.Files.remove(this) log("File $this removed", LogType.IMPORTANT) transaction { delete() } } // [{2} testfile C:/Users/fef/Documents/test.txt] override fun toString(): String = "[{${id.value}} ${name.value} ${origin.value}]".replaceNewline() override fun equals(other: Any?): Boolean { return if(other !is File) false else other.id == id } override fun hashCode(): Int { var result = name.hashCode() result = 31 * result + origin.hashCode() return result } } class Reminder(id: EntityID<Long>): LongEntity(id), DBClass { object Reminders: LongEntityClass<Reminder>(ReminderTable) companion object { fun new(_deadline: LocalDateTime?, _appointment: Appointment?, _title: String, _description: String): Reminder { return transaction { return@transaction Reminders.new { deadline.set(_deadline) appointment.set(_appointment) title.set(_title) description.set(_description) }.also { calendar.Reminders.add(it); log("Reminder $it created", LogType.IMPORTANT) } } } } private var dbDeadline by ReminderTable.deadline private var dbAppointment by Appointment.Appointments optionalReferencedOn ReminderTable.appointment private var dbTitle by ReminderTable.title private var dbDescription by ReminderTable.description val deadline: DBObservableBase<LocalDateTime?, Long?> = object: DBObservableBase<LocalDateTime?, Long?>() { override fun abstractGet(): Long? = dbDeadline override fun abstractSet(dat: Long?) { dbDeadline = dat } override fun convertFrom(value: LocalDateTime?): Long? = value?.toUTCEpochMinute() override fun convertTo(value: Long?): LocalDateTime? = if(value != null) Timing.fromUTCEpochMinuteToLocalDateTime(value) else null } val appointment: DBObservable<Appointment?> = object: DBObservable<Appointment?>() { override fun abstractGet(): Appointment? = dbAppointment override fun abstractSet(dat: Appointment?) { dbAppointment = dat } } val title: DBObservable<String> = object: DBObservable<String>() { override fun abstractGet(): String = dbTitle override fun abstractSet(dat: String) { dbTitle = dat } } val description: DBObservable<String> = object: DBObservable<String>() { override fun abstractGet(): String = dbDescription override fun abstractSet(dat: String) { dbDescription = dat } } override fun remove() { calendar.Reminders.remove(this) log("Reminder $this removed", LogType.IMPORTANT) transaction { delete() } } // [{14} 2022-05-16T00:00 | test_title: test_description] override fun toString(): String = "[{${id.value}} ${deadline.value} | ${title.value}: ${description.value} (${appointment.value})]".replaceNewline() override fun equals(other: Any?): Boolean { return if(other !is Reminder) false else other.id == id } override fun hashCode(): Int { var result = deadline.hashCode() result = 31 * result + title.hashCode() result = 31 * result + description.hashCode() return result } } class Type(id: EntityID<Int>): IntEntity(id), DBClass { object Types: IntEntityClass<Type>(TypeTable) companion object { fun new(_name: String, _color: Color): Type { return transaction { return@transaction Types.new { name.set(_name) color.set(_color) }.also { calendar.Types.add(it); log("Type $it created", LogType.IMPORTANT) } } } } private var dbName by TypeTable.name private var dbColor by TypeTable.color val name: DBObservable<String> = object: DBObservable<String>() { override fun abstractGet(): String = dbName override fun abstractSet(dat: String) { dbName = dat } } val color: DBObservableBase<Color, String> = object: DBObservableBase<Color, String>() { override fun convertFrom(value: Color): String = value.toString() override fun convertTo(value: String): Color = Color.valueOf(value) override fun abstractGet(): String = dbColor override fun abstractSet(dat: String) { dbColor = dat } } override fun remove() { calendar.Types.remove(this) log("Type $this removed", LogType.IMPORTANT) transaction { delete() } } // [{1} test_1_type 0x008000ff] override fun toString(): String = "[{${id.value}} ${name.value} ${color.value}]".replaceNewline() override fun equals(other: Any?): Boolean { return if(other !is Type) false else other.id == id } override fun hashCode(): Int { var result = name.hashCode() result = 31 * result + color.hashCode() return result } } interface DBClass { override fun hashCode(): Int override fun equals(other: Any?): Boolean override fun toString(): String fun remove() }
18
Kotlin
0
2
beef0cbcfca23885f3960ea8e32e5a487e5ab353
11,955
Calendar
MIT License
crabzilla-pgclient/src/test/kotlin/io/github/crabzilla/pgclient/projection/GreedyProjectionIT.kt
crabzilla
91,769,036
false
null
package io.github.crabzilla.pgclient.projection import io.github.crabzilla.core.EventTopics import io.github.crabzilla.core.json.JsonSerDer import io.github.crabzilla.example1.example1Json import io.github.crabzilla.json.KotlinJsonSerDer import io.github.crabzilla.pgclient.TestRepository import io.github.crabzilla.pgclient.command.cleanDatabase import io.github.crabzilla.pgclient.command.config import io.github.crabzilla.pgclient.command.pgPool import io.vertx.core.Vertx import io.vertx.core.json.JsonObject import io.vertx.junit5.VertxExtension import io.vertx.junit5.VertxTestContext import io.vertx.pgclient.PgPool import org.junit.jupiter.api.BeforeEach import org.junit.jupiter.api.DisplayName import org.junit.jupiter.api.Test import org.junit.jupiter.api.extension.ExtendWith @ExtendWith(VertxExtension::class) @DisplayName("Forcing projector to be greedy") class GreedyProjectionIT { lateinit var jsonSerDer: JsonSerDer lateinit var pgPool: PgPool private lateinit var testRepo: TestRepository @BeforeEach fun setup(vertx: Vertx, tc: VertxTestContext) { jsonSerDer = KotlinJsonSerDer(example1Json) pgPool = pgPool(vertx) testRepo = TestRepository(pgPool) cleanDatabase(pgPool) .compose { vertx.deployProjector( config, "service:crabzilla.example1.customer.CustomersSlowEventsProjector" ) } .onFailure { tc.failNow(it) } .onSuccess { tc.completeNow() } } @Test @DisplayName("forcing it starting greedy then sending a command the events will be projected") fun a0(tc: VertxTestContext, vertx: Vertx) { val target = "crabzilla.example1.customer.CustomersSlowEventsProjector" pgPool .preparedQuery("NOTIFY " + EventTopics.STATE_TOPIC.name.lowercase() + ", 'Customer'") .execute() .compose { Thread.sleep(500) vertx.eventBus().request<JsonObject>("crabzilla.projectors.$target.status", null) }.onSuccess { println(it.body().encodePrettily()) if (it.body().getBoolean("greedy")) { tc.completeNow() } else { tc.failNow("Status should be greedy") } } } }
1
null
8
62
09cb11ffb7cc9ecb328cf47f15d79587137b1895
2,157
crabzilla
Apache License 2.0
MidiTools/src/main/kotlin/com/example/android/miditools/MidiConstants.kt
android
525,124,832
false
{"Kotlin": 206640}
/* * Copyright (C) 2022 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.example.android.miditools /** * MIDI related constants and static methods. * These values are defined in the MIDI Standard 1.0 * available from the MIDI Manufacturers Association. */ object MidiConstants { const val TAG = "MidiTools" const val STATUS_COMMAND_MASK = 0xF0.toByte() // Channel voice messages. const val STATUS_NOTE_OFF = 0x80.toByte() const val STATUS_NOTE_ON = 0x90.toByte() const val STATUS_CONTROL_CHANGE = 0xB0.toByte() const val STATUS_PROGRAM_CHANGE = 0xC0.toByte() const val STATUS_PITCH_BEND = 0xE0.toByte() const val STATUS_PER_NOTE_PITCH_BEND = 0x60.toByte() // System Common Messages. const val STATUS_SYSTEM_EXCLUSIVE = 0xF0.toByte() // System Real-Time Messages const val STATUS_TIMING_CLOCK = 0xF8.toByte() private const val STATUS_ACTIVE_SENSING = 0xFE.toByte() /** Number of bytes in a message nc from 8c to Ec */ private val CHANNEL_BYTE_LENGTHS = intArrayOf(3, 3, 3, 3, 2, 2, 3) /** Number of bytes in a message Fn from F0 to FF */ private val SYSTEM_BYTE_LENGTHS = intArrayOf( 1, 2, 3, 2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ) const val MAX_CHANNELS = 16 const val MIDI_INPUT_PORT = 1 const val MIDI_OUTPUT_PORT = 2 const val MIDI_INPUT_OUTPUT_PORT = 3 /** * MIDI messages, except for SysEx, are 1,2 or 3 bytes long. * You can tell how long a MIDI message is from the first status byte. * Do not call this for SysEx, which has variable length. * @param statusByte * @return number of bytes in a complete message, zero if data byte passed */ @JvmStatic fun getBytesPerMessage(statusByte: Byte): Int { // Java bytes are signed so we need to mask off the high bits // to get a value between 0 and 255. val statusInt: Int = statusByte.toInt() and 0xFF return when { statusInt >= 0xF0 -> { // System messages use low nibble for size. SYSTEM_BYTE_LENGTHS[statusInt and 0x0F] } statusInt >= 0x80 -> { // Channel voice messages use high nibble for size. CHANNEL_BYTE_LENGTHS[(statusInt shr 4) - 8] } else -> { 0 // data byte } } } /** * @param msg * @param offset * @param count * @return true if the entire message is ActiveSensing commands */ fun isAllActiveSensing( msg: ByteArray, offset: Int, count: Int ): Boolean { // Count bytes that are not active sensing. var goodBytes = 0 for (i in 0 until count) { val b = msg[offset + i] if (b != STATUS_ACTIVE_SENSING) { goodBytes++ } } return goodBytes == 0 } }
0
Kotlin
11
40
f30bceee0b1257359088d8acec4a95248b5695be
3,476
midi-samples
Apache License 2.0
library/src/main/java/com/github/ininmm/library/annotation/TagModel.kt
ininmm
129,585,786
false
null
package com.github.ininmm.library.annotation import android.support.annotation.StringDef /** * 註解的標籤 * Created by <NAME> * on 2018/2/11. */ class TagModel { companion object { const val DEFAULT = "RxBusDefaultTag" } @Retention(AnnotationRetention.RUNTIME) @Target(AnnotationTarget.FUNCTION, AnnotationTarget.PROPERTY_GETTER, AnnotationTarget.PROPERTY_SETTER) @StringDef(DEFAULT) annotation class Tag(val value: String = DEFAULT) }
0
Kotlin
1
4
a6ded2a27d6ef311a258c6c7021c4014b6ea7ba8
493
RxBus2
Apache License 2.0
app/src/main/java/com/harvard/art/museums/data/pojo/Venue.kt
pvulkov
190,898,492
false
null
package com.harvard.art.museums.data.pojo data class Venue( val address1: String, val address2: String? = null, val begindate: String, val city: String, val country: String, val enddate: String, val fullname: String, val ishamvenue: Int, val name: String, val state: String, val venueid: Int, val zipcode: String, val galleries: List<Gallery> = listOf() )
0
Kotlin
0
0
74d4d681fe8f276438c1a4cfdd332476f91b218d
460
Harvard-Art-Museums
Apache License 2.0
detail/src/main/java/com/pyamsoft/fridge/detail/DetailEmptyState.kt
androidok
426,877,914
false
{"Kotlin": 703826}
/* * Copyright 2021 <NAME> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.pyamsoft.fridge.detail import android.view.ViewGroup import com.pyamsoft.fridge.db.item.FridgeItem.Presence.NEED import com.pyamsoft.fridge.detail.databinding.DetailEmptyBinding import com.pyamsoft.pydroid.arch.BaseUiView import com.pyamsoft.pydroid.arch.UiRender import com.pyamsoft.pydroid.loader.ImageLoader import com.pyamsoft.pydroid.loader.Loaded import javax.inject.Inject class DetailEmptyState @Inject internal constructor( parent: ViewGroup, private val imageLoader: ImageLoader, ) : BaseUiView<DetailViewState, DetailViewEvent.ListEvent, DetailEmptyBinding>(parent) { override val viewBinding = DetailEmptyBinding::inflate override val layoutRoot by boundView { detailEmptyRoot } private var loaded: Loaded? = null init { doOnTeardown { clear() } } private fun clear() { loaded?.dispose() loaded = null binding.detailEmptyMessage.text = null } override fun onRender(state: UiRender<DetailViewState>) { state.render(viewScope) { handleLoading(it) } } private fun handleLoading(state: DetailViewState) { state.isLoading.let { loading -> clear() if (!loading) { if (state.displayedItems.isEmpty()) { val isNeed = state.listItemPresence == NEED loadText(isNeed, state.search.text.isNotBlank()) loadImage(isNeed) } } } } private fun loadText(isNeed: Boolean, isSearch: Boolean) { val text = when { isSearch -> "Your search returned no results." isNeed -> "Your shopping list is empty, make a note about anything you need to buy!" else -> "Your fridge is empty, add items to your shopping list and go to the store!" } binding.detailEmptyMessage.text = text } private fun loadImage(isNeed: Boolean) { val icon = if (isNeed) R.drawable.bg_item_need else R.drawable.bg_item_have loaded = imageLoader.asDrawable().load(icon).into(binding.detailEmptyImage) } }
0
null
0
0
adef301263e0f2d778268bbb1421162a12353c74
2,567
fridgefriend
Apache License 2.0
app/src/main/java/com/amazon/firetv/integrationsdk/sdk/FireTvPlaybackReporter.kt
amzn
734,477,657
false
{"Kotlin": 59908, "Shell": 529}
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 package com.amazon.firetv.integrationsdk.sdk import android.content.Context import android.util.Log import com.amazon.tv.developer.sdk.content.personalization.AmazonPlaybackReceiver import com.amazon.tv.developer.sdk.content.personalization.model.AmazonContentId import com.amazon.tv.developer.sdk.content.personalization.model.AmazonPlaybackEvent import com.amazon.tv.developer.sdk.content.personalization.model.AmazonPlaybackState import com.amazon.tv.developer.sdk.content.personalization.model.AmazonProfileId /** * Reports AmazonPlaybackEvent objects to the AmazonPlaybackReceiver in the Fire TV Integration SDK. * */ class FireTvPlaybackReporter(private val context: Context) { fun reportPlayingEvent( playbackPositionMs: Long, durationMs: Long, contentId: String, profileId: String ) { isFTVIntegrationSDKSupportedOnDevice(context) { Log.i(TAG, "Reporting playback event with state: PLAYING, content id: $contentId, playback position: $playbackPositionMs, profile id: $profileId") reportEvent( AmazonPlaybackState.PLAYING, playbackPositionMs, durationMs, contentId, profileId ) } } fun reportPausedEvent( playbackPositionMs: Long, durationMs: Long, contentId: String, profileId: String ) { isFTVIntegrationSDKSupportedOnDevice(context) { Log.i(TAG, "Reporting playback event with state: PAUSED, content id: $contentId, playback position: $playbackPositionMs, profile id: $profileId") reportEvent( AmazonPlaybackState.PAUSED, playbackPositionMs, durationMs, contentId, profileId ) } } fun reportExitEvent( playbackPositionMs: Long, durationMs: Long, contentId: String, profileId: String ) { isFTVIntegrationSDKSupportedOnDevice(context) { Log.i(TAG, "Reporting playback event with state: EXIT, content id: $contentId, playback position: $playbackPositionMs, profile id: $profileId") reportEvent( AmazonPlaybackState.EXIT, playbackPositionMs, durationMs, contentId, profileId ) } } fun reportInterstitialEvent( playbackPositionMs: Long, durationMs: Long, contentId: String, profileId: String ) { isFTVIntegrationSDKSupportedOnDevice(context) { Log.i( TAG, "Reporting playback event with state: INTERSTITIAL, content id: $contentId, playback position: $playbackPositionMs, profile id: $profileId" ) reportEvent( AmazonPlaybackState.INTERSTITIAL, playbackPositionMs, durationMs, contentId, profileId ) } } private fun reportEvent( playbackState: Int, playbackPositionMs: Long, durationMs: Long, contentId: String, profileId: String ) { val event = AmazonPlaybackEvent.builder() .state(playbackState) .playbackPositionMs(playbackPositionMs) .durationMs(durationMs) .contentId( AmazonContentId.builder() .namespace(AmazonContentId.NAMESPACE_CDF_ID) .id(contentId) .build() ) .profileId( /* Refer to app/src/main/java/com/amazon/firetv/integrationsdk/video/player/VideoPlayerFragment.kt for information on sending the profile ID. */ AmazonProfileId.builder() .namespace(AmazonProfileId.NAMESPACE_APP_INTERNAL) .id(profileId) .build() ) .buildActiveEvent() AmazonPlaybackReceiver.getInstance(context).addPlaybackEvent(event) } companion object { private val TAG = FireTvPlaybackReporter::class.java.simpleName } }
0
Kotlin
0
0
51cf5555052707308107cdab4a13858bd7d34215
4,365
ftv-integration-sdk-sample-app
Apache License 2.0
bandyer-android-design/src/main/java/com/bandyer/sdk_design/chat/adapter_items/message/abstract_message/BandyerBaseChatMessageViewHolder.kt
Bandyer
337,367,845
false
null
/* * Copyright 2021-2022 Bandyer @ https://www.bandyer.com * * 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.bandyer.sdk_design.chat.adapter_items.message.abstract_message import android.text.format.DateUtils import android.view.View import com.bandyer.sdk_design.chat.imageviews.BandyerChatMessageStatusImageView import com.bandyer.sdk_design.chat.layout.BandyerBaseChatMessageLayout import com.bandyer.sdk_design.utils.KotlinConstraintSet.Companion.changeConstraints import com.google.android.material.card.MaterialCardView import com.mikepenz.fastadapter.FastAdapter /** * Base Chat Message View Holder * @property F Layout to use for the message view * @property T Type of Message Item to display * @constructor */ @Suppress("UNCHECKED_CAST") abstract class BandyerBaseChatMessageViewHolder<F, T> constructor(view: View) : FastAdapter.ViewHolder<T>(view) where T : BandyerBaseChatMessageItem<*>, F : BandyerBaseChatMessageLayout { private var messageLayout: F = view as F private var messageContent: MaterialCardView = messageLayout.dataViewContainer as MaterialCardView /** * @suppress */ final override fun bindView(item: T, payloads: List<Any>) { bind(item, messageLayout, payloads) val pending = item.data.pending val seen = item.data.seen.invoke() val sent = item.data.sent when { seen -> messageLayout.statusView?.state = BandyerChatMessageStatusImageView.State.SEEN sent -> messageLayout.statusView?.state = BandyerChatMessageStatusImageView.State.SENT pending -> messageLayout.statusView?.state = BandyerChatMessageStatusImageView.State.PENDING } messageLayout.showStatus(item.data.mine && (pending || seen || sent)) messageLayout.timestampTextView!!.text = DateUtils.getRelativeTimeSpanString(item.data.timestamp) messageLayout.changeConstraints { if (item.data.mine) messageContent.id endToEndOf messageLayout.id else messageContent.id startToStartOf messageLayout.id } } /** * On Bind of the message * @param item T Message Item * @param itemView F Message Item * @param payloads MutableList<Any> of payload */ abstract fun bind(item: T, itemView: F, payloads: List<Any>) /** * On unBind of the message * @param item T Message Item * @param itemView F Message Item */ abstract fun unbind(item: T, itemView: F) /** * @suppress */ final override fun unbindView(item: T) { unbind(item, messageLayout) messageLayout.changeConstraints { clear(messageContent.id) } messageLayout.showStatus(false) } }
0
Kotlin
1
1
d25c7b14302015cdad2df298391a2cb891df1a8e
3,244
Bandyer-Android-Design
Apache License 2.0
entity-service/src/main/kotlin/com/egm/stellio/entity/authorization/AuthorizationService.kt
stellio-hub
257,818,724
false
null
package com.egm.stellio.entity.authorization import java.net.URI interface AuthorizationService { companion object { const val USER_PREFIX: String = "urn:ngsi-ld:User:" const val AUTHORIZATION_ONTOLOGY = "https://ontology.eglobalmark.com/authorization#" const val EGM_ROLES = AUTHORIZATION_ONTOLOGY + "roles" const val R_CAN_READ = AUTHORIZATION_ONTOLOGY + "rCanRead" const val R_CAN_WRITE = AUTHORIZATION_ONTOLOGY + "rCanWrite" const val R_CAN_ADMIN = AUTHORIZATION_ONTOLOGY + "rCanAdmin" const val SERVICE_ACCOUNT_ID = AUTHORIZATION_ONTOLOGY + "serviceAccountId" const val ADMIN_ROLE_LABEL = "stellio-admin" const val CREATION_ROLE_LABEL = "stellio-creator" val ADMIN_ROLES: Set<String> = setOf(ADMIN_ROLE_LABEL) val CREATION_ROLES: Set<String> = setOf(CREATION_ROLE_LABEL).plus(ADMIN_ROLES) val ADMIN_RIGHT: Set<String> = setOf(R_CAN_ADMIN) val WRITE_RIGHT: Set<String> = setOf(R_CAN_WRITE).plus(ADMIN_RIGHT) val READ_RIGHT: Set<String> = setOf(R_CAN_READ).plus(WRITE_RIGHT) } fun userIsAdmin(userSub: String): Boolean fun userCanCreateEntities(userSub: String): Boolean fun filterEntitiesUserCanRead(entitiesId: List<URI>, userSub: String): List<URI> fun filterEntitiesUserCanUpdate(entitiesId: List<URI>, userSub: String): List<URI> fun filterEntitiesUserCanAdmin(entitiesId: List<URI>, userSub: String): List<URI> fun splitEntitiesByUserCanAdmin(entitiesId: List<URI>, userSub: String): Pair<List<URI>, List<URI>> fun userCanReadEntity(entityId: URI, userSub: String): Boolean fun userCanUpdateEntity(entityId: URI, userSub: String): Boolean fun userIsAdminOfEntity(entityId: URI, userSub: String): Boolean fun createAdminLink(entityId: URI, userSub: String) fun createAdminLinks(entitiesId: List<URI>, userSub: String) }
38
null
6
14
0d9c089ca10dcd92af274ae5411d48634a4a9b30
1,896
stellio-context-broker
Apache License 2.0
src/main/kotlin/dev/voqal/assistant/tool/text/DeleteLineTool.kt
voqal
716,228,492
false
{"Kotlin": 1209055, "Java": 493485, "JavaScript": 13007, "Go": 10765, "Python": 9638, "TypeScript": 828, "Groovy": 568, "PHP": 315, "Rust": 308}
package dev.voqal.assistant.tool.text import com.aallam.openai.api.chat.Tool import com.aallam.openai.api.core.Parameters import com.intellij.openapi.application.ReadAction import com.intellij.openapi.command.WriteCommandAction import com.intellij.openapi.components.service import com.intellij.openapi.project.Project import com.intellij.openapi.util.ThrowableComputable import dev.voqal.assistant.VoqalDirective import dev.voqal.assistant.focus.DetectedIntent import dev.voqal.assistant.focus.SpokenTranscript import dev.voqal.assistant.tool.VoqalTool import dev.voqal.services.VoqalStatusService import dev.voqal.services.getVoqalLogger import dev.voqal.services.scope import io.vertx.core.json.JsonArray import io.vertx.core.json.JsonObject import kotlinx.coroutines.launch class DeleteLineTool : VoqalTool() { companion object { const val NAME = "delete_line" } override val name = NAME override suspend fun actionPerformed(args: JsonObject, directive: VoqalDirective) { val project = directive.project val log = project.getVoqalLogger(this::class) val editor = directive.ide.editor if (editor == null) { log.warn("No editor found") project.service<VoqalStatusService>().updateText("No editor found") return } var line = args.getString("line") if (line == null) { log.debug("No line specified. Using current line.") line = ReadAction.compute(ThrowableComputable { val caretModel = editor.caretModel val caretOffset = caretModel.offset val document = editor.document val lineNumber = document.getLineNumber(caretOffset) (lineNumber + 1).toString() }) } log.debug("Triggering delete line: $line") WriteCommandAction.runWriteCommandAction(editor.project, ThrowableComputable { val document = editor.document val lineStart = document.getLineStartOffset(line.toInt() - 1) val lineEnd = document.getLineEndOffset(line.toInt() - 1) document.deleteString((lineStart - 1).coerceAtLeast(0), lineEnd) project.scope.launch { project.service<VoqalStatusService>().updateText("Deleted line: $line") } }) } override suspend fun getTranscriptIntent(project: Project, transcript: SpokenTranscript): DetectedIntent? { return attemptIntentExtract(transcript.cleanTranscript)?.let { (intent, args) -> DetectedIntent(intent, args, transcript, this) } } internal fun attemptIntentExtract(rawString: String): Pair<String, Map<String, String>>? { return if (rawString == "delete line") { Pair(NAME, mapOf()) } else { null } } override fun isVisible(directive: VoqalDirective): Boolean = false override fun asTool(directive: VoqalDirective) = Tool.function( name = NAME, description = "Delete the line at the specified position.", parameters = Parameters.fromJsonString(JsonObject().apply { put("type", "object") put("properties", JsonObject().apply { put("line", JsonObject().apply { put("type", "integer") put("description", "The line number to delete.") }) }) put("required", JsonArray().add("line")) }.toString()) ) }
1
Kotlin
8
90
1a4eac0c4907c44a88288d6af6a686b97b003583
3,526
coder
Apache License 2.0
plugins/radar-android-phone/src/main/java/org/radarbase/passive/phone/PhoneContactListProvider.kt
RADAR-base
85,591,443
false
{"C++": 2958963, "Kotlin": 809848, "Java": 517842, "C": 289748, "HTML": 42350, "PHP": 10200, "Makefile": 8527, "RenderScript": 997}
/* * Copyright 2017 The Hyve * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.radarbase.passive.phone import android.Manifest import org.radarbase.android.RadarService import org.radarbase.android.source.BaseSourceState import org.radarbase.android.source.SourceProvider import org.radarbase.passive.phone.PhoneSensorProvider.Companion.MODEL import org.radarbase.passive.phone.PhoneSensorProvider.Companion.PRODUCER open class PhoneContactListProvider(radarService: RadarService) : SourceProvider<BaseSourceState>(radarService) { override val description: String get() = radarService.getString(R.string.phone_contact_list_description) override val serviceClass: Class<PhoneContactsListService> = PhoneContactsListService::class.java override val pluginNames = listOf( "phone_contacts", "contact_list", "contacts", ".phone.PhoneContactListProvider", "org.radarbase.passive.phone.PhoneContactListProvider", "org.radarcns.phone.PhoneContactListProvider") override val displayName: String get() = radarService.getString(R.string.contact_list) override val isDisplayable: Boolean = false override val permissionsNeeded: List<String> = listOf(Manifest.permission.READ_CONTACTS) override val sourceProducer: String = PRODUCER override val sourceModel: String = MODEL override val version: String = BuildConfig.VERSION_NAME }
40
C++
7
5
f62557c1721e9f4b74a84fbadfb3b052d6bab8e7
1,975
radar-commons-android
Apache License 2.0
app/src/main/java/com/yandroid/movie/data/UpcomingPagingSource.kt
Mohammadfazel03
510,253,442
false
null
package com.yandroid.movie.data import androidx.paging.PagingSource import androidx.paging.PagingState import com.yandroid.movie.data.api.APIKEY import com.yandroid.movie.data.api.ApiService import com.yandroid.movie.data.model.Movie import java.lang.Exception class UpcomingPagingSource(private val api: ApiService) : PagingSource<Int, Movie>() { override fun getRefreshKey(state: PagingState<Int, Movie>): Int? { return state.anchorPosition?.let { anchorPosition -> val anchorPage = state.closestPageToPosition(anchorPosition) anchorPage?.prevKey?.plus(1) ?: anchorPage?.nextKey?.minus(1) } } override suspend fun load(params: LoadParams<Int>): LoadResult<Int, Movie> { return try { val currentPage = params.key ?: 1 val result = api.getUpcomingMovie(APIKEY,currentPage) if (!result.statusMessage.isNullOrEmpty()) throw Exception(result.statusMessage) LoadResult.Page( result.result, if (currentPage == 1) null else currentPage - 1, if (currentPage == result.totalPage) null else currentPage + 1 ) } catch (e: Exception) { LoadResult.Error(e) } } }
0
Kotlin
0
2
4fa6bf8b447808b897f92233e3f18de62a755bda
1,272
movie-mvvm-application
MIT License
app/src/main/java/com/yandroid/movie/data/UpcomingPagingSource.kt
Mohammadfazel03
510,253,442
false
null
package com.yandroid.movie.data import androidx.paging.PagingSource import androidx.paging.PagingState import com.yandroid.movie.data.api.APIKEY import com.yandroid.movie.data.api.ApiService import com.yandroid.movie.data.model.Movie import java.lang.Exception class UpcomingPagingSource(private val api: ApiService) : PagingSource<Int, Movie>() { override fun getRefreshKey(state: PagingState<Int, Movie>): Int? { return state.anchorPosition?.let { anchorPosition -> val anchorPage = state.closestPageToPosition(anchorPosition) anchorPage?.prevKey?.plus(1) ?: anchorPage?.nextKey?.minus(1) } } override suspend fun load(params: LoadParams<Int>): LoadResult<Int, Movie> { return try { val currentPage = params.key ?: 1 val result = api.getUpcomingMovie(APIKEY,currentPage) if (!result.statusMessage.isNullOrEmpty()) throw Exception(result.statusMessage) LoadResult.Page( result.result, if (currentPage == 1) null else currentPage - 1, if (currentPage == result.totalPage) null else currentPage + 1 ) } catch (e: Exception) { LoadResult.Error(e) } } }
0
Kotlin
0
2
4fa6bf8b447808b897f92233e3f18de62a755bda
1,272
movie-mvvm-application
MIT License
DeliBuddy/app/src/main/java/yapp/android1/delibuddy/base/BaseViewModel.kt
YAPP-19th
399,058,402
false
null
package yapp.android1.delibuddy.base import androidx.lifecycle.ViewModel import androidx.lifecycle.viewModelScope import kotlinx.coroutines.Job import kotlinx.coroutines.* import kotlinx.coroutines.flow.MutableSharedFlow import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.SharedFlow import kotlinx.coroutines.flow.StateFlow import yapp.android1.delibuddy.model.Event import yapp.android1.delibuddy.util.EventFlow import yapp.android1.delibuddy.util.MutableEventFlow import yapp.android1.domain.NetworkResult import yapp.android1.domain.entity.NetworkError typealias RetryAction = () -> Unit abstract class BaseViewModel<E : Event> : ViewModel() { private var job: Job? = null private val _loading = MutableStateFlow<Boolean>(false) val loading: StateFlow<Boolean> = _loading private val _showToast = MutableEventFlow<String>() val showToast: EventFlow<String> = _showToast protected abstract suspend fun handleEvent(event: E) protected abstract suspend fun handleError(result: NetworkResult.Error, retryAction: RetryAction?) fun occurEvent(event: E) { job = viewModelScope.launch { handleEvent(event) } } fun showProgress() { _loading.value = true } fun hideProgress() { _loading.value = false } suspend fun showToast(message: String) { _showToast.emit(message) } override fun onCleared() { job = null super.onCleared() } }
15
Kotlin
2
14
8967c395e2a8ad346ae24bc2a2fe4fbd3df29376
1,500
Android-Team-1-Frontend
Apache License 2.0
DeliBuddy/app/src/main/java/yapp/android1/delibuddy/base/BaseViewModel.kt
YAPP-19th
399,058,402
false
null
package yapp.android1.delibuddy.base import androidx.lifecycle.ViewModel import androidx.lifecycle.viewModelScope import kotlinx.coroutines.Job import kotlinx.coroutines.* import kotlinx.coroutines.flow.MutableSharedFlow import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.SharedFlow import kotlinx.coroutines.flow.StateFlow import yapp.android1.delibuddy.model.Event import yapp.android1.delibuddy.util.EventFlow import yapp.android1.delibuddy.util.MutableEventFlow import yapp.android1.domain.NetworkResult import yapp.android1.domain.entity.NetworkError typealias RetryAction = () -> Unit abstract class BaseViewModel<E : Event> : ViewModel() { private var job: Job? = null private val _loading = MutableStateFlow<Boolean>(false) val loading: StateFlow<Boolean> = _loading private val _showToast = MutableEventFlow<String>() val showToast: EventFlow<String> = _showToast protected abstract suspend fun handleEvent(event: E) protected abstract suspend fun handleError(result: NetworkResult.Error, retryAction: RetryAction?) fun occurEvent(event: E) { job = viewModelScope.launch { handleEvent(event) } } fun showProgress() { _loading.value = true } fun hideProgress() { _loading.value = false } suspend fun showToast(message: String) { _showToast.emit(message) } override fun onCleared() { job = null super.onCleared() } }
15
Kotlin
2
14
8967c395e2a8ad346ae24bc2a2fe4fbd3df29376
1,500
Android-Team-1-Frontend
Apache License 2.0