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/test/kotlin/com/intellij/aws/cloudformation/tests/ReferencesTest.kt | shalupov | 15,524,636 | false | null | package com.intellij.aws.cloudformation.tests
import com.intellij.testFramework.LightPlatformCodeInsightTestCase
import java.io.File
class ReferencesTest: LightPlatformCodeInsightTestCase() {
fun testRefRange() {
configureByFile("refRange.yaml")
TestUtil.checkContent(
File(testDataPath, "refRange.yaml.expected"),
TestUtil.renderReferences(LightPlatformCodeInsightTestCase.myFile)
)
}
override fun getTestDataPath(): String {
return TestUtil.getTestDataPath("references")
}
}
| 41 | Kotlin | 28 | 143 | 22a7a3aaee8784afc49b752c55da518b702fc067 | 520 | idea-cloudformation | Apache License 2.0 |
core/src/main/kotlin/com/toasttab/expediter/types/ArrayDescriptor.kt | open-toast | 685,226,715 | false | null | /*
* Copyright (c) 2023 Toast Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.toasttab.expediter.types
import protokt.v1.toasttab.expediter.v1.AccessDeclaration
import protokt.v1.toasttab.expediter.v1.AccessProtection
import protokt.v1.toasttab.expediter.v1.MemberDescriptor
import protokt.v1.toasttab.expediter.v1.SymbolicReference
import protokt.v1.toasttab.expediter.v1.TypeDescriptor
import protokt.v1.toasttab.expediter.v1.TypeExtensibility
import protokt.v1.toasttab.expediter.v1.TypeFlavor
/**
* Creates type descriptors for arrays. Per https://docs.oracle.com/javase/specs/jls/se7/html/jls-10.html#jls-10.7,
* arrays implement `Cloneable` and `Serializable` and have two members:
* ```
* public final int length;
* public Object clone();
* ```
*/
object ArrayDescriptor {
private val INTERFACES = listOf("java/lang/Cloneable", "java/io/Serializable")
private val FIELDS = listOf(
MemberDescriptor {
ref = SymbolicReference {
name = "length"
signature = "I"
}
protection = AccessProtection.PUBLIC
declaration = AccessDeclaration.INSTANCE
}
)
private val METHODS = listOf(
MemberDescriptor {
ref = SymbolicReference {
name = "clone"
signature = "()Ljava/lang/Object;"
}
protection = AccessProtection.PUBLIC
declaration = AccessDeclaration.INSTANCE
}
)
fun isArray(typeName: String) = typeName.startsWith("[")
fun create(typeName: String) = TypeDescriptor {
name = typeName
superName = "java/lang/Object"
interfaces = INTERFACES
protection = AccessProtection.PUBLIC
flavor = TypeFlavor.CLASS
extensibility = TypeExtensibility.FINAL
fields = FIELDS
methods = METHODS
}
}
| 4 | null | 1 | 5 | e4145ffcd61177d5d0b09f092cb95ef4bf1a7f46 | 2,401 | expediter | Apache License 2.0 |
src/commonMain/kotlin/MainStage3d.kt | korlibs | 607,166,953 | false | null | import korlibs.time.*
import korlibs.korge.input.*
import korlibs.korge.scene.*
import korlibs.korge.tween.*
import korlibs.korge.ui.*
import korlibs.korge.view.*
import korlibs.korge3d.*
import korlibs.math.geom.*
class MainStage3d : Scene() {
lateinit var contentSceneContainer: SceneContainer
override suspend fun SContainer.sceneInit() {
contentSceneContainer = sceneContainer(views).xy(0, 32)
uiHorizontalStack {
sceneButton<CratesScene>("Crates")
sceneButton<PhysicsScene>("Physics")
sceneButton<MonkeyScene>("Monkey")
sceneButton<SkinningScene>("Skinning")
}
contentSceneContainer.changeToDisablingButtons<CratesScene>(this)
//contentSceneContainer.changeToDisablingButtons<SkinningScene>(this)
}
inline fun <reified T : Scene> Container.sceneButton(title: String) {
uiButton(title)
.onClick { contentSceneContainer.changeToDisablingButtons<T>(this) }
//this += Button(title) { contentSceneContainer.changeToDisablingButtons<T>(this) }
// .position(8 + x * 200, views.virtualHeight - 120)
}
private suspend fun Stage3D.orbit(v: View3D, distance: Float, time: TimeSpan) {
viewParent.tween(time = time) { ratio ->
val angle = 360.degrees * ratio
camera.positionLookingAt(
cos(angle) * distance, 0f, sin(angle) * distance, // Orbiting camera
v.transform.translation.x, v.transform.translation.y, v.transform.translation.z
)
}
}
/*
class Button(text: String, handler: suspend () -> Unit) : Container() {
val textField = Text(text, textSize = 32.0).apply { smoothing = false }
private val bounds = textField.textBounds
val g = CpuGraphics().updateShape {
fill(Colors.DARKGREY, 0.7) {
roundRect(bounds.x, bounds.y, bounds.width + 16, bounds.height + 16, 8.0, 8.0)
}
}
var enabledButton = true
set(value) {
field = value
updateState()
}
private var overButton = false
set(value) {
field = value
updateState()
}
fun updateState() {
when {
!enabledButton -> alpha = 0.3
overButton -> alpha = 1.0
else -> alpha = 0.8
}
}
init {
//this += this.solidRect(bounds.width, bounds.height, Colors.TRANSPARENT_BLACK)
this += g.apply {
mouseEnabled = true
}
this += textField.position(8, 8)
mouse {
over { overButton = true }
out { overButton = false }
}
onClick {
if (enabledButton) handler()
}
updateState()
}
}
*/
suspend inline fun <reified T : Scene> SceneContainer.changeToDisablingButtons(buttonContainer: Container) {
for (child in buttonContainer.children.filterIsInstance<UIButton>()) {
//println("DISABLE BUTTON: $child")
child.enabled = false
}
try {
changeTo<T>()
} finally {
for (child in buttonContainer.children.filterIsInstance<UIButton>()) {
//println("ENABLE BUTTON: $child")
child.enabled = true
}
}
}
}
| 7 | Kotlin | 3 | 3 | 8e4059e25f39623825312601706569ac817de336 | 3,500 | korge-k3d | MIT License |
app/src/main/kotlin/app/lawnchair/lawnicons/viewmodel/AcknowledgementViewModel.kt | LawnchairLauncher | 423,607,805 | false | null | package app.lawnchair.lawnicons.viewmodel
import android.text.SpannableString
import android.text.style.URLSpan
import android.text.util.Linkify
import androidx.compose.ui.text.AnnotatedString
import androidx.compose.ui.text.SpanStyle
import androidx.compose.ui.text.buildAnnotatedString
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import app.lawnchair.lawnicons.repository.OssLibraryRepository
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.flow.SharingStarted
import kotlinx.coroutines.flow.flowOn
import kotlinx.coroutines.flow.stateIn
import javax.inject.Inject
@HiltViewModel
class AcknowledgementViewModel @Inject constructor(private val ossLibraryRepository: OssLibraryRepository) : ViewModel() {
fun getNoticeForOssLibrary(
ossLibraryName: String,
linkStyle: SpanStyle,
) = ossLibraryRepository.getNoticeForOssLibrary(
ossLibraryName = ossLibraryName,
annotate = { annotate(it, linkStyle) }
)
.flowOn(Dispatchers.Default)
.stateIn(viewModelScope, SharingStarted.Lazily, null)
private fun annotate(
notice: String,
linkStyle: SpanStyle,
): AnnotatedString {
val spannable = SpannableString(notice)
Linkify.addLinks(spannable, Linkify.WEB_URLS)
val urlSpans = spannable.getSpans(0, notice.length, URLSpan::class.java)
return buildAnnotatedString {
append(notice)
urlSpans.forEach {
val start = spannable.getSpanStart(it)
val end = spannable.getSpanEnd(it)
addStyle(
start = start,
end = end,
style = linkStyle,
)
addStringAnnotation(
tag = "URL",
annotation = it.url,
start = start,
end = end,
)
}
}
}
}
| 42 | null | 459 | 999 | 4d99b9af5d9ff35db98d25aeb83191dfab45de74 | 2,015 | lawnicons | Apache License 2.0 |
sdk/src/main/java/com/qonversion/android/sdk/internal/extensions.kt | qonversion | 224,974,105 | false | null | package com.qonversion.android.sdk.internal
import android.app.Application
import android.content.Context
import android.content.pm.ApplicationInfo
import com.qonversion.android.sdk.dto.QEntitlement
import com.qonversion.android.sdk.internal.dto.QPermission
import org.json.JSONArray
import org.json.JSONObject
import retrofit2.Call
import retrofit2.Callback
import retrofit2.Response
internal fun <T> Call<T>.enqueue(callback: CallBackKt<T>.() -> Unit) {
val callBackKt = CallBackKt<T>()
callback.invoke(callBackKt)
this.enqueue(callBackKt)
}
internal class CallBackKt<T> : Callback<T> {
var onResponse: ((Response<T>) -> Unit)? = null
var onFailure: ((t: Throwable) -> Unit)? = null
override fun onFailure(call: Call<T>, t: Throwable) {
onFailure?.invoke(t)
}
override fun onResponse(call: Call<T>, response: Response<T>) {
onResponse?.invoke(response)
}
}
internal fun Int.isInternalServerError() =
this in Constants.INTERNAL_SERVER_ERROR_MIN..Constants.INTERNAL_SERVER_ERROR_MAX
internal fun JSONObject.toMap(): Map<String, Any?> {
val map = mutableMapOf<String, Any?>()
val keys = keys()
while (keys.hasNext()) {
val key = keys.next()
var value: Any? = get(key)
when {
isNull(key) -> {
value = null
}
value is JSONArray -> {
value = value.toList()
}
value is JSONObject -> {
value = value.toMap()
}
}
map[key] = value
}
return map
}
internal fun JSONArray.toList(): List<Any?> {
val list = mutableListOf<Any?>()
for (i in 0 until length()) {
var value: Any? = get(i)
when {
isNull(i) -> {
value = null
}
value is JSONArray -> {
value = value.toList()
}
value is JSONObject -> {
value = value.toMap()
}
}
list.add(value)
}
return list
}
internal val Context.isDebuggable get() = applicationInfo.flags and ApplicationInfo.FLAG_DEBUGGABLE != 0
internal val Context.application get() = applicationContext as Application
internal fun Int.toBoolean() = this != 0
internal fun String?.toBoolean() = this == "1"
internal fun Boolean.toInt() = if (this) 1 else 0
internal fun Boolean.stringValue() = if (this) "1" else "0"
internal fun Long.milliSecondsToSeconds(): Long = this / 1000
internal fun Long.secondsToMilliSeconds(): Long = this * 1000
internal fun Map<String, QPermission>.toEntitlementsMap(): Map<String, QEntitlement> {
val res = mutableMapOf<String, QEntitlement>()
forEach { (id, permission) -> res[id] = QEntitlement(permission) }
return res
}
internal infix fun <T> List<T>.equalsIgnoreOrder(other: List<T>) =
this.size == other.size && this.toSet() == other.toSet()
| 6 | null | 21 | 122 | 619465b65dbf2612486ec3adad9b0a8750d76c7b | 2,920 | android-sdk | MIT License |
BaseExtend/src/main/java/com/chen/baseextend/view/NoHorizontalScrollerViewPager.kt | chen397254698 | 268,411,455 | false | null | package com.chen.baseextend.view
import android.content.Context
import android.util.AttributeSet
import android.view.MotionEvent
import androidx.viewpager.widget.ViewPager
/**
* Created by zejian
* Time 16/1/7 上午11:12
* Email <EMAIL>
* Description:不可横向滑动的ViewPager
*/
class NoHorizontalScrollerViewPager : ViewPager {
constructor(context: Context) : super(context) {}
constructor(context: Context, attrs: AttributeSet) : super(context, attrs) {}
/**
* 重写拦截事件,返回值设置为false,这时便不会横向滑动了。
*
* @param ev
* @return
*/
override fun onInterceptTouchEvent(ev: MotionEvent): Boolean {
return false
}
/**
* 重写拦截事件,返回值设置为false,这时便不会横向滑动了。
*
* @param ev
* @return
*/
override fun onTouchEvent(ev: MotionEvent): Boolean {
return false
}
}
| 1 | null | 14 | 47 | 85ffc5e307c6171767e14bbfaf992b8d62ec1cc6 | 834 | EasyAndroid | Apache License 2.0 |
powermanager-trigger/src/main/java/com/pyamsoft/powermanager/trigger/TriggerPresenter.kt | pyamsoft | 24,553,477 | false | null | /*
* Copyright 2017 Peter Kenji Yamanaka
*
* 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.powermanager.trigger
import com.pyamsoft.powermanager.trigger.bus.TriggerCreateBus
import com.pyamsoft.powermanager.trigger.bus.TriggerDeleteBus
import com.pyamsoft.powermanager.trigger.db.PowerTriggerEntry
import com.pyamsoft.pydroid.util.presenter.SchedulerViewPresenter
import io.reactivex.Scheduler
import timber.log.Timber
import javax.inject.Inject
import javax.inject.Named
class TriggerPresenter @Inject internal constructor(@Named("obs") obsScheduler: Scheduler,
@Named("sub") subScheduler: Scheduler, private val deleteBus: TriggerDeleteBus,
private val createBus: TriggerCreateBus,
private val interactor: TriggerInteractor) : SchedulerViewPresenter(obsScheduler,
subScheduler) {
fun registerOnBus(onAdd: (PowerTriggerEntry) -> Unit, onAddError: (Throwable) -> Unit,
onTriggerDeleted: (Int) -> Unit, onTriggerDeleteError: (Throwable) -> Unit) {
disposeOnStop {
createBus.listen().subscribeOn(backgroundScheduler).observeOn(
foregroundScheduler).flatMapSingle {
interactor.createTrigger(it.entry).observeOn(foregroundScheduler).onErrorReturn {
Timber.e(it, "createTrigger Error")
onAddError(it)
return@onErrorReturn PowerTriggerEntry.empty
}
}.subscribe({
if (PowerTriggerEntry.isEmpty(it)) {
Timber.w("Empty entry passed, do nothing")
} else {
onAdd(it)
}
}, { Timber.e(it, "onError create bus") })
}
disposeOnStop {
deleteBus.listen().subscribeOn(backgroundScheduler).observeOn(
foregroundScheduler).flatMapSingle {
interactor.delete(it.percent).observeOn(foregroundScheduler).onErrorReturn {
Timber.e(it, "Trigger Delete error")
onTriggerDeleteError(it)
return@onErrorReturn -1
}
}.subscribe({
if (it < 0) {
Timber.w("Trigger delete failed, do nothing")
} else {
onTriggerDeleted(it)
}
}, { Timber.e(it, "onError create bus") })
}
}
fun loadTriggerView(forceRefresh: Boolean, onTriggerLoaded: (PowerTriggerEntry) -> Unit,
onTriggerLoadError: (Throwable) -> Unit, onTriggerLoadFinished: () -> Unit) {
disposeOnStop {
interactor.queryAll(forceRefresh).subscribeOn(backgroundScheduler).observeOn(
foregroundScheduler).doAfterTerminate({ onTriggerLoadFinished() }).subscribe(
{ onTriggerLoaded(it) }, {
Timber.e(it, "onError")
onTriggerLoadError(it)
})
}
}
}
| 0 | Kotlin | 0 | 1 | bfc57e557e56a0503daae89a964a0ab447695b16 | 3,143 | power-manager | Apache License 2.0 |
app/src/main/java/com/codepath/bestsellerlistapp/BestSellerBooksFragment.kt | mateamilloshi | 702,118,454 | false | {"Kotlin": 8597} | package com.codepath.bestsellerlistapp
import android.os.Bundle
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Toast
import androidx.core.widget.ContentLoadingProgressBar
import androidx.fragment.app.Fragment
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.codepath.asynchttpclient.AsyncHttpClient
import com.codepath.asynchttpclient.RequestParams
import com.codepath.asynchttpclient.callback.JsonHttpResponseHandler
import com.codepath.bestsellerlistapp.Person
import com.codepath.bestsellerlistapp.R
import com.google.gson.Gson
import com.google.gson.reflect.TypeToken
import okhttp3.Call
import okhttp3.Headers
import org.json.JSONArray
import org.json.JSONException
import retrofit2.http.GET
import retrofit2.http.Query
private const val API_KEY = "a07e22bc18f5cb106bfe4cc1f83ad8ed"
/*
* The class for the only fragment in the app, which contains the progress bar,
* recyclerView, and performs the network calls to the NY Times API.
*/
class BestSellerBooksFragment : Fragment(), OnListFragmentInteractionListener {
/*
* Constructing the view
*/
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
val view = inflater.inflate(R.layout.fragment_best_seller_books_list, container, false)
val progressBar = view.findViewById<View>(R.id.progress) as ContentLoadingProgressBar
val recyclerView = view.findViewById<View>(R.id.list) as RecyclerView
val context = view.context
recyclerView.layoutManager = GridLayoutManager(context, 1)
updateAdapter(progressBar, recyclerView)
return view
}
/*
* Updates the RecyclerView adapter with new data. This is where the
* networking magic happens!
*/
private fun updateAdapter(progressBar: ContentLoadingProgressBar, recyclerView: RecyclerView) {
progressBar.show()
val client = AsyncHttpClient()
val params = RequestParams()
params["api_key"] = API_KEY
client.get(
"https://api.themoviedb.org/3/person/popular",
params,
object : JsonHttpResponseHandler() {
override fun onSuccess(
statusCode: Int,
headers: Headers,
json: JsonHttpResponseHandler.JSON
) {
progressBar.hide()
try {
val peopleArray: JSONArray = json.jsonObject.getJSONArray("results")
val people = mutableListOf<Person>()
for (i in 0 until peopleArray.length()) {
val personObject = peopleArray.getJSONObject(i)
val person = Person()
// Set the properties using the data from the JSON response
person.id = personObject.getString("id")
person.name = personObject.getString("name")
person.profilePath = "https://image.tmdb.org/t/p/w500/${personObject.getString("profile_path")}"
people.add(person)
}
recyclerView.adapter = PeopleAdapter(people, this@BestSellerBooksFragment)
} catch (e: JSONException) {
Log.e("YourFragment", "Error parsing JSON: ${e.message}")
}
}
/*
* The onFailure function gets called when
* HTTP response status is "4XX" (eg. 401, 403, 404)
*/
override fun onFailure(
statusCode: Int,
headers: Headers?,
errorResponse: String,
t: Throwable?
) {
// The wait for a response is over
progressBar.hide()
// If the error is not null, log it!
t?.message?.let {
Log.e("BestSellerBooksFragment", errorResponse)
}
}
}
)
}
override fun onItemClick(item: Person) {
Toast.makeText(context, "test: " + item.name, Toast.LENGTH_LONG).show()
}
} | 0 | Kotlin | 0 | 0 | 8c0b21e8f74bef1a95d99a2238ea8931da35f081 | 4,479 | FlexterApp2 | Apache License 2.0 |
app/src/main/java/com/masscode/animesuta/di/AppModule.kt | agustiyann | 299,888,684 | false | null | package com.masscode.animesuta.di
import com.masscode.animesuta.core.domain.usecase.AnimeInteractor
import com.masscode.animesuta.core.domain.usecase.AnimeUseCase
import com.masscode.animesuta.detail.DetailAnimeViewModel
import com.masscode.animesuta.home.HomeViewModel
import org.koin.android.viewmodel.dsl.viewModel
import org.koin.dsl.module
val useCaseModule = module {
factory<AnimeUseCase> { AnimeInteractor(get()) }
}
val viewModelModule = module {
viewModel { HomeViewModel(get(), get()) }
viewModel { DetailAnimeViewModel(get()) }
} | 0 | Kotlin | 10 | 55 | 0a51677ddcd69eb9f8c2f9c8da62518c894d06ce | 556 | Android-Clean-Architecture | Apache License 2.0 |
app/src/main/java/com/jetpackcompose/playground/ui/common/components/SearchField.kt | StefanWyszynski | 765,607,090 | false | {"Kotlin": 48635} | package com.jetpackcompose.playground.common.presentation.components
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.wrapContentHeight
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Search
import androidx.compose.material3.Icon
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.TextField
import androidx.compose.material3.TextFieldDefaults
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.text.TextStyle
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
@Composable
fun SearchField(
serachText: String,
onSearchTextChange: (text: String) -> Unit
) {
TextField(
value = serachText,
onValueChange = onSearchTextChange,
modifier = Modifier
.fillMaxWidth()
.wrapContentHeight(),
leadingIcon = {
Icon(
imageVector = Icons.Default.Search,
contentDescription = null
)
},
colors = TextFieldDefaults.colors(
unfocusedContainerColor = MaterialTheme.colorScheme.surface,
focusedContainerColor = MaterialTheme.colorScheme.surface
),
textStyle = TextStyle(fontSize = 13.sp, fontWeight = FontWeight.Bold),
shape = RoundedCornerShape(14.dp),
placeholder = {
})
}
| 0 | Kotlin | 0 | 0 | ca8f5ff7943a37b6c5c2f65213138548888fb109 | 1,564 | JetpackComposePlayground | MIT License |
app/src/main/kotlin/jp/co/yumemi/android/code_check/presentation/util/SnackbarSetting.kt | kokoichi206 | 572,676,235 | false | null | package jp.co.yumemi.android.code_check.presentation.util
import androidx.compose.foundation.background
import androidx.compose.foundation.border
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.*
import androidx.compose.runtime.Composable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.platform.testTag
import androidx.compose.ui.unit.dp
@Composable
fun SnackbarSetting(
snackbarHostState: SnackbarHostState,
modifier: Modifier = Modifier,
) {
Box(
modifier = modifier,
) {
SnackbarHost(
modifier = Modifier.align(Alignment.BottomCenter),
hostState = snackbarHostState,
snackbar = { snackbarData: SnackbarData ->
Card(
shape = RoundedCornerShape(8.dp),
modifier = Modifier
.padding(4.dp)
.wrapContentSize()
.border(
width = 2.dp,
color = androidx.compose.material3.MaterialTheme.colorScheme.outline,
shape = RoundedCornerShape(8.dp)
)
.align(Alignment.Center)
) {
Text(
modifier = Modifier
.background(androidx.compose.material3.MaterialTheme.colorScheme.secondary)
.padding(8.dp)
.testTag(TestTags.SNACK_BAR),
text = snackbarData.message,
color = androidx.compose.material3.MaterialTheme.colorScheme.onSecondary,
)
}
}
)
}
}
| 6 | Kotlin | 0 | 1 | eac5913bebdddaafccde199831598417481cdcd4 | 1,850 | android-engineer-codecheck | Apache License 2.0 |
s2-test/s2-test-bdd/src/main/kotlin/s2/bdd/exception/NoParserFoundException.kt | komune-io | 746,796,094 | false | {"Kotlin": 149768, "Makefile": 4275, "JavaScript": 1453, "Dockerfile": 963, "CSS": 102} | package s2.bdd.exception
import kotlin.reflect.KClass
class NoParserFoundException(
type: KClass<*>
): UnsupportedOperationException("No entry parser registered for type ${type.simpleName}")
| 1 | Kotlin | 0 | 0 | 9b65957be1785aec45efa80c78cc80ea244924ce | 197 | fixers-s2 | Apache License 2.0 |
api/src/main/kotlin/nebulosa/api/calibration/CalibrationFrameService.kt | tiagohm | 568,578,345 | false | {"Kotlin": 2372483, "TypeScript": 377934, "HTML": 198335, "SCSS": 10342, "Python": 2817, "JavaScript": 1165} | package nebulosa.api.calibration
import nebulosa.fits.*
import nebulosa.image.Image
import nebulosa.image.algorithms.transformation.correction.BiasSubtraction
import nebulosa.image.algorithms.transformation.correction.DarkSubtraction
import nebulosa.image.algorithms.transformation.correction.FlatCorrection
import nebulosa.image.format.Header
import nebulosa.image.format.ImageHdu
import nebulosa.image.format.ReadableHeader
import nebulosa.indi.device.camera.FrameType
import nebulosa.log.loggerFor
import org.springframework.stereotype.Service
import java.nio.file.Path
import java.util.*
import kotlin.io.path.isDirectory
import kotlin.io.path.isRegularFile
import kotlin.io.path.listDirectoryEntries
import kotlin.math.abs
import kotlin.math.roundToInt
// https://cdn.diffractionlimited.com/help/maximdl/Understanding_Calibration_Groups.htm
// https://www.astropy.org/ccd-reduction-and-photometry-guide/v/dev/notebooks/00-00-Preface.html
@Service
class CalibrationFrameService(
private val calibrationFrameRepository: CalibrationFrameRepository,
) {
fun calibrate(camera: String, image: Image, createNew: Boolean = false): Image {
val darkFrame = findBestDarkFrames(camera, image).firstOrNull()
val biasFrame = findBestBiasFrames(camera, image).firstOrNull()
val flatFrame = findBestFlatFrames(camera, image).firstOrNull()
return if (darkFrame != null || biasFrame != null || flatFrame != null) {
var transformedImage = if (createNew) image.clone() else image
var calibrationImage = Image(transformedImage.width, transformedImage.height, Header.Empty, transformedImage.mono)
if (biasFrame != null) {
calibrationImage = biasFrame.path!!.fits().use(calibrationImage::load)!!
transformedImage = transformedImage.transform(BiasSubtraction(calibrationImage))
LOG.info("bias frame subtraction applied. frame={}", biasFrame)
} else {
LOG.info(
"no bias frames found. width={}, height={}, bin={}, gain={}",
image.width, image.height, image.header.binX, image.header.gain
)
}
if (darkFrame != null) {
calibrationImage = darkFrame.path!!.fits().use(calibrationImage::load)!!
transformedImage = transformedImage.transform(DarkSubtraction(calibrationImage))
LOG.info("dark frame subtraction applied. frame={}", darkFrame)
} else {
LOG.info(
"no dark frames found. width={}, height={}, bin={}, exposureTime={}, gain={}",
image.width, image.height, image.header.binX, image.header.exposureTimeInMicroseconds, image.header.gain
)
}
if (flatFrame != null) {
calibrationImage = flatFrame.path!!.fits().use(calibrationImage::load)!!
transformedImage = transformedImage.transform(FlatCorrection(calibrationImage))
LOG.info("flat frame correction applied. frame={}", flatFrame)
} else {
LOG.info(
"no flat frames found. filter={}, width={}, height={}, bin={}",
image.header.filter, image.width, image.height, image.header.binX
)
}
transformedImage
} else {
LOG.info(
"no calibration frames found. width={}, height={}, bin={}, gain={}, filter={}, exposureTime={}",
image.width, image.height, image.header.binX, image.header.gain, image.header.filter, image.header.exposureTimeInMicroseconds
)
image
}
}
fun groupedCalibrationFrames(camera: String): Map<CalibrationGroupKey, List<CalibrationFrameEntity>> {
val frames = calibrationFrameRepository.findAll(camera)
return frames.groupBy(CalibrationGroupKey::from)
}
fun upload(camera: String, path: Path): List<CalibrationFrameEntity> {
val files = if (path.isRegularFile() && path.isFits) listOf(path)
else if (path.isDirectory()) path.listDirectoryEntries("*.{fits,fit}").filter { it.isRegularFile() }
else return emptyList()
return upload(camera, files)
}
@Synchronized
fun upload(camera: String, files: List<Path>): List<CalibrationFrameEntity> {
val frames = ArrayList<CalibrationFrameEntity>(files.size)
for (file in files) {
calibrationFrameRepository.delete(camera, "$file")
try {
file.fits().use { fits ->
val hdu = fits.filterIsInstance<ImageHdu>().firstOrNull() ?: return@use
val header = hdu.header
val frameType = header.frameType?.takeIf { it != FrameType.LIGHT } ?: return@use
val exposureTime = if (frameType == FrameType.DARK) header.exposureTimeInMicroseconds else 0L
val temperature = if (frameType == FrameType.DARK) header.temperature else 999.0
val gain = if (frameType != FrameType.FLAT) header.gain else 0.0
val filter = if (frameType == FrameType.FLAT) header.filter else null
val frame = CalibrationFrameEntity(
0L, frameType, camera, filter,
exposureTime, temperature,
header.width, header.height, header.binX, header.binY,
gain, "$file",
)
calibrationFrameRepository.save(frame)
.also(frames::add)
}
} catch (e: Throwable) {
LOG.error("cannot open FITS. path={}, message={}", file, e.message)
}
}
return frames
}
fun edit(id: Long, path: String?, enabled: Boolean): CalibrationFrameEntity {
return with(calibrationFrameRepository.find(id)!!) {
if (!path.isNullOrBlank()) this.path = path
this.enabled = enabled
calibrationFrameRepository.save(this)
}
}
fun delete(id: Long) {
calibrationFrameRepository.delete(id)
}
// exposureTime, temperature, width, height, binX, binY, gain.
fun findBestDarkFrames(camera: String, image: Image): List<CalibrationFrameEntity> {
val header = image.header
val temperature = header.temperature
val frames = calibrationFrameRepository
.darkFrames(camera, image.width, image.height, header.binX, header.exposureTimeInMicroseconds, header.gain)
if (frames.isEmpty()) return emptyList()
// Closest temperature.
val groupedFrames = TreeMap<Int, MutableList<CalibrationFrameEntity>>()
frames.groupByTo(groupedFrames) { abs(it.temperature - temperature).roundToInt() }
// TODO: Dont use if temperature is out of tolerance range
// TODO: Generate master from matched frames.
return groupedFrames.firstEntry().value
}
// filter, width, height, binX, binY.
fun findBestFlatFrames(camera: String, image: Image): List<CalibrationFrameEntity> {
val filter = image.header.filter
// TODO: Generate master from matched frames.
return calibrationFrameRepository
.flatFrames(camera, filter, image.width, image.height, image.header.binX)
}
// width, height, binX, binY, gain.
fun findBestBiasFrames(camera: String, image: Image): List<CalibrationFrameEntity> {
// TODO: Generate master from matched frames.
return calibrationFrameRepository
.biasFrames(camera, image.width, image.height, image.header.binX, image.header.gain)
}
companion object {
@JvmStatic private val LOG = loggerFor<CalibrationFrameService>()
@JvmStatic val ReadableHeader.frameType
get() = frame?.uppercase()?.let {
if ("LIGHT" in it) FrameType.LIGHT
else if ("DARK" in it) FrameType.DARK
else if ("FLAT" in it) FrameType.FLAT
else if ("BIAS" in it) FrameType.BIAS
else null
}
inline val Path.isFits
get() = "$this".let { it.endsWith(".fits") || it.endsWith(".fit") }
}
}
| 2 | Kotlin | 1 | 2 | b44e250a575b375b01acfc84a7c4198b06ab97c5 | 8,321 | nebulosa | MIT License |
src/main/kotlin/br/com/alura/bytebank/modelo/Cliente.kt | giovannanascimento-hotmart | 465,475,377 | false | {"Kotlin": 39474} | package br.com.alura.bytebank.modelo
class Cliente (
val nome: String,
val cpf: String,
var endereco: Endereco = Endereco(),
protected val senha: Int): Autenticavel {
override fun autenticacao(senha: Int): Boolean {
if (this.senha == senha){
return true
}
return false
}
}
| 0 | Kotlin | 1 | 0 | 7e2845b52c28b3f4b89a1731263d476c47e6850f | 337 | bytebank | MIT License |
SafeDriveApp/app/src/main/java/com/example/safedrive/viewModels/FireBaseViewModel.kt | Android-development-group-13 | 771,413,371 | false | {"Kotlin": 12244} | package com.example.safedrive.viewModels
import android.util.Log
import androidx.lifecycle.ViewModel
import com.google.firebase.Firebase
import com.google.firebase.firestore.firestore
data class User(val email: String, val password: String, val fName: String, val lName: String)
class FireBaseViewModel : ViewModel() {
val firestore = Firebase.firestore
fun createUser(user: User) {
firestore.collection("users").add(user)
.addOnSuccessListener { u -> Log.i("***", "User Created") }
.addOnFailureListener { e -> Log.i("***", e.toString()) }
}
fun loginUser(user:String, password: String){
}
} | 1 | Kotlin | 0 | 0 | 1e7badbdb3c868bd8af7b1ff28d0d6fc7fec93ea | 659 | safedrive | MIT License |
core-geojson/src/main/java/com/github/teracy/odpt/core/geojson/response/LineString.kt | teracy | 193,032,147 | false | null | package com.github.teracy.odpt.core.geojson.response
import com.squareup.moshi.Json
/**
* GeoJSONのジオメトリ:"LineString"
*/
data class LineString(
/**
* 2つ以上の座標の配列(個々の座標メンバは、投影された座標では[東行, 北行]の順、地理座標では[経度, 緯度]の順)
*/
@field:Json(name = "coordinates")
val coordinates: List<List<Double>>
) : Geometry(GeometryType.LINE_STRING)
| 0 | Kotlin | 0 | 1 | 002554e4ca6e2f460207cfd1cb8265c2267f149d | 346 | odpt | Apache License 2.0 |
src/jsMain/kotlin/com/jakewharton/platformcollections/PlatformList.kt | JakeWharton | 591,003,112 | false | null | @file:Suppress("EXTENSION_SHADOWED_BY_MEMBER")
package com.jakewharton.platformcollections
public actual typealias PlatformList<E> = JsArray<E>
public actual inline fun <E> PlatformList<E>.add(item: E) {
push(item)
}
public actual fun <E> PlatformList<E>.add(index: Int, item: E) {
if (index < 0 || index > length) {
throw IndexOutOfBoundsException("Index $index, size: $length")
}
splice(index, 0, item)
}
public actual fun <E> PlatformList<E>.asMutableList(): MutableList<E> {
return PlatformListMutableList(this)
}
public actual inline fun <E> PlatformList<E>.clear() {
length = 0
}
public actual inline operator fun <E> PlatformList<E>.contains(item: E): Boolean {
return includes(item)
}
public actual operator fun <E> PlatformList<E>.get(index: Int): E {
if (index < 0 || index >= length) {
throw IndexOutOfBoundsException("Index $index, size: $length")
}
@Suppress("UnsafeCastFromDynamic") // Avoids yet another set of temporary vars.
return asDynamic()[index]
}
public actual inline fun <E> PlatformList<E>.indexOf(item: E): Int {
return indexOf(item)
}
public actual inline fun <E> PlatformList<E>.isEmpty(): Boolean {
return length == 0
}
public actual inline fun <E> PlatformList<E>.lastIndexOf(item: E): Int {
return lastIndexOf(item)
}
public actual inline fun <E> PlatformList<E>.removeAt(index: Int) {
splice(index, 1)
}
public actual inline fun <E> PlatformList<E>.set(index: Int, item: E) {
splice(index, 1, item)
}
public actual inline val <E> PlatformList<E>.size: Int get() = length
public actual fun <E> PlatformList<E>.toMutableList(): MutableList<E> {
val self = asDynamic()
val size = size // Avoid two property reads in JS.
val arrayList = ArrayList<E>(size)
repeat(size) { index ->
@Suppress("UnsafeCastFromDynamic") // Avoids yet another set of temporary vars.
arrayList.add(self[index])
}
return arrayList
}
| 4 | null | 2 | 83 | 3d9824a9c9f60a010fa5c5d8c62bf65084b2a234 | 1,881 | platform-collections | Apache License 2.0 |
rounded/src/commonMain/kotlin/me/localx/icons/rounded/filled/UsersSlash.kt | localhostov | 808,861,591 | false | {"Kotlin": 79430321, "HTML": 331, "CSS": 102} | package me.localx.icons.rounded.filled
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.PathFillType.Companion.NonZero
import androidx.compose.ui.graphics.SolidColor
import androidx.compose.ui.graphics.StrokeCap.Companion.Butt
import androidx.compose.ui.graphics.StrokeJoin.Companion.Miter
import androidx.compose.ui.graphics.vector.ImageVector
import androidx.compose.ui.graphics.vector.ImageVector.Builder
import androidx.compose.ui.graphics.vector.path
import androidx.compose.ui.unit.dp
import me.localx.icons.rounded.Icons
public val Icons.Filled.UsersSlash: ImageVector
get() {
if (_usersSlash != null) {
return _usersSlash!!
}
_usersSlash = Builder(name = "UsersSlash", defaultWidth = 24.0.dp, defaultHeight = 24.0.dp,
viewportWidth = 24.0f, viewportHeight = 24.0f).apply {
path(fill = SolidColor(Color(0xFF000000)), stroke = null, strokeLineWidth = 0.0f,
strokeLineCap = Butt, strokeLineJoin = Miter, strokeLineMiter = 4.0f,
pathFillType = NonZero) {
moveToRelative(16.9f, 24.0f)
lineTo(7.1f, 24.0f)
curveToRelative(-0.3f, 0.0f, -0.584f, -0.135f, -0.774f, -0.367f)
reflectiveCurveToRelative(-0.265f, -0.538f, -0.206f, -0.832f)
curveToRelative(0.565f, -2.782f, 3.038f, -4.801f, 5.88f, -4.801f)
reflectiveCurveToRelative(5.315f, 2.019f, 5.88f, 4.801f)
curveToRelative(0.06f, 0.294f, -0.016f, 0.6f, -0.206f, 0.832f)
reflectiveCurveToRelative(-0.474f, 0.367f, -0.774f, 0.367f)
close()
moveTo(18.0f, 8.0f)
curveToRelative(2.206f, 0.0f, 4.0f, -1.794f, 4.0f, -4.0f)
reflectiveCurveToRelative(-1.794f, -4.0f, -4.0f, -4.0f)
reflectiveCurveToRelative(-4.0f, 1.794f, -4.0f, 4.0f)
reflectiveCurveToRelative(1.794f, 4.0f, 4.0f, 4.0f)
close()
moveTo(23.707f, 22.293f)
lineToRelative(-7.94f, -7.94f)
curveToRelative(0.153f, -0.428f, 0.233f, -0.884f, 0.233f, -1.353f)
curveToRelative(0.0f, -1.068f, -0.416f, -2.073f, -1.172f, -2.828f)
curveToRelative(-1.085f, -1.085f, -2.749f, -1.391f, -4.16f, -0.918f)
lineToRelative(-2.148f, -2.148f)
curveToRelative(0.917f, -0.746f, 1.48f, -1.879f, 1.48f, -3.106f)
curveToRelative(0.0f, -2.206f, -1.794f, -4.0f, -4.0f, -4.0f)
curveToRelative(-1.226f, 0.0f, -2.36f, 0.563f, -3.106f, 1.48f)
lineTo(1.707f, 0.293f)
curveTo(1.316f, -0.098f, 0.684f, -0.098f, 0.293f, 0.293f)
reflectiveCurveTo(-0.098f, 1.316f, 0.293f, 1.707f)
lineToRelative(22.0f, 22.0f)
curveToRelative(0.195f, 0.195f, 0.451f, 0.293f, 0.707f, 0.293f)
reflectiveCurveToRelative(0.512f, -0.098f, 0.707f, -0.293f)
curveToRelative(0.391f, -0.391f, 0.391f, -1.023f, 0.0f, -1.414f)
close()
moveTo(12.126f, 15.978f)
curveToRelative(0.314f, 0.314f, 0.055f, 0.846f, -0.386f, 0.796f)
curveToRelative(-0.867f, -0.097f, -1.708f, -0.476f, -2.373f, -1.141f)
curveToRelative(-0.665f, -0.665f, -1.044f, -1.506f, -1.141f, -2.373f)
curveToRelative(-0.049f, -0.441f, 0.482f, -0.7f, 0.796f, -0.386f)
lineToRelative(3.104f, 3.104f)
close()
moveTo(6.0f, 13.0f)
curveToRelative(0.0f, -0.854f, 0.179f, -1.666f, 0.5f, -2.401f)
lineToRelative(-1.147f, -1.147f)
curveToRelative(-0.25f, -0.25f, -0.614f, -0.35f, -0.957f, -0.261f)
curveTo(2.19f, 9.76f, 0.473f, 11.57f, 0.02f, 13.801f)
curveToRelative(-0.06f, 0.294f, 0.016f, 0.599f, 0.206f, 0.832f)
reflectiveCurveToRelative(0.474f, 0.367f, 0.774f, 0.367f)
horizontalLineToRelative(5.342f)
curveToRelative(-0.221f, -0.626f, -0.342f, -1.299f, -0.342f, -2.0f)
close()
moveTo(23.98f, 13.801f)
curveToRelative(-0.565f, -2.782f, -3.08f, -4.801f, -5.98f, -4.801f)
curveToRelative(-1.0f, 0.0f, -0.975f, 0.702f, -0.803f, 1.0f)
curveToRelative(0.511f, 0.883f, 0.803f, 1.907f, 0.803f, 3.0f)
curveToRelative(0.0f, 0.701f, -0.121f, 1.374f, -0.342f, 2.0f)
horizontalLineToRelative(5.342f)
curveToRelative(0.3f, 0.0f, 0.584f, -0.135f, 0.774f, -0.367f)
reflectiveCurveToRelative(0.265f, -0.538f, 0.206f, -0.832f)
close()
}
}
.build()
return _usersSlash!!
}
private var _usersSlash: ImageVector? = null
| 1 | Kotlin | 0 | 5 | cbd8b510fca0e5e40e95498834f23ec73cc8f245 | 4,908 | icons | MIT License |
build-logic/convention/src/main/kotlin/AndroidLibraryConventionPlugin.kt | jerryOkafor | 677,650,066 | false | null | /*
* The MIT License (MIT)
*
* Copyright (c) 2023 IheNkiri Project
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
import com.android.build.api.variant.LibraryAndroidComponentsExtension
import com.android.build.gradle.LibraryExtension
import me.jerryokafor.ihenkiri.androidTestImplementation
import me.jerryokafor.ihenkiri.configureKotlinAndroid
import me.jerryokafor.ihenkiri.disableUnnecessaryAndroidTests
import me.jerryokafor.ihenkiri.libs
import me.jerryokafor.ihenkiri.testImplementation
import org.gradle.api.Plugin
import org.gradle.api.Project
import org.gradle.kotlin.dsl.configure
import org.gradle.kotlin.dsl.dependencies
import org.gradle.kotlin.dsl.kotlin
class AndroidLibraryConventionPlugin : Plugin<Project> {
override fun apply(target: Project) {
with(target) {
with(pluginManager) {
apply("com.android.library")
apply("kotlin-android")
apply("kotlin-parcelize")
}
extensions.configure<LibraryExtension> {
defaultConfig {
testInstrumentationRunner =
"me.jerryokafor.ihenkiri.core.test.IheNkiriTestRunner"
}
configureKotlinAndroid(this)
lint {
baseline = file("lint-baseline.xml")
// quiet = true
abortOnError = false // fix your lint issue
ignoreWarnings = true
checkDependencies = true
}
packaging {
resources.excludes += "DebugProbesKt.bin"
}
}
extensions.configure<LibraryAndroidComponentsExtension> {
disableUnnecessaryAndroidTests(target)
}
configurations.configureEach {
resolutionStrategy {
force(libs.findLibrary("junit4").get())
// Temporary workaround for https://issuetracker.google.com/174733673
force("org.objenesis:objenesis:2.6")
}
}
dependencies {
testImplementation(kotlin("test"))
androidTestImplementation(kotlin("test"))
}
}
}
}
| 14 | null | 2 | 9 | dd7d1b3350eb1066c78fb77b7a6bcfffd1c4d54b | 3,316 | IheNkiri | MIT License |
utils/test-utils/src/main/java/com/microsoft/device/dualscreen/testing/rules/PublishWindowInfoTrackerDecorator.kt | microsoft | 262,129,243 | false | null | /*
* Copyright 2021 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package androidx.window.testing.layout
import android.app.Activity
import android.content.Context
import androidx.annotation.UiContext
import androidx.window.layout.WindowInfoTracker
import androidx.window.layout.WindowLayoutInfo
import kotlinx.coroutines.flow.Flow
internal class PublishLayoutInfoTracker(
private val core: WindowInfoTracker,
private val flow: Flow<WindowLayoutInfo>
) : WindowInfoTracker by core {
override fun windowLayoutInfo(activity: Activity): Flow<WindowLayoutInfo> {
return flow
}
override fun windowLayoutInfo(@UiContext context: Context): Flow<WindowLayoutInfo> {
return flow
}
}
| 4 | Kotlin | 945 | 63 | 059a23684baff99de1293d1f54119b611a5765a3 | 1,269 | surface-duo-sdk | MIT License |
src/main/kotlin/me/serce/bazillion/libs.kt | SerCeMan | 164,261,128 | false | null | package me.serce.bazillion
import com.fasterxml.jackson.annotation.JsonIgnore
import com.fasterxml.jackson.databind.DeserializationFeature
import com.fasterxml.jackson.databind.ObjectMapper
import com.fasterxml.jackson.module.kotlin.readValue
import com.fasterxml.jackson.module.kotlin.registerKotlinModule
import com.intellij.openapi.components.*
import com.intellij.openapi.externalSystem.model.project.LibraryData
import com.intellij.openapi.externalSystem.model.project.LibraryPathType
import com.intellij.openapi.progress.ProgressIndicator
import com.intellij.openapi.project.Project
import com.intellij.util.io.HttpRequests
import me.serce.bazillion.LibManager.LibMetadata
import me.serce.bazillion.LibManager.Sources
import java.io.File
@State(
name = "BazilLibManager",
storages = [Storage(StoragePathMacros.WORKSPACE_FILE)]
)
class LibManager(private val project: Project) : PersistentStateComponent<LibManager.State> {
companion object {
fun getInstance(project: Project): LibManager =
project.getService(LibManager::class.java)
}
data class State(var json: String = "")
data class Sources(
val url: String,
val repository: String
)
data class LibMetadata(
val name: String,
val coords: String,
val url: String,
val repository: String,
val source: Sources?,
val dependenciesStr: List<String> = arrayListOf(),
@JsonIgnore // not needed for source manager
val allDependencies: MutableList<LibraryData> = arrayListOf()
)
private val mapper: ObjectMapper = ObjectMapper()
.registerKotlinModule()
.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false)
private val actualLibraries: MutableMap<String, LibraryData> = mutableMapOf()
private val librariesMeta: MutableMap<String, LibMetadata> = mutableMapOf()
private val jarLibraries: MutableMap<String, LibraryData> = mutableMapOf()
override fun getState() = State(mapper.writeValueAsString(librariesMeta))
override fun loadState(state: State) {
if (state.json.isNotEmpty()) {
librariesMeta.clear()
try {
librariesMeta.putAll(mapper.readValue(state.json))
} catch (e: Exception) {
LOG.error("error loading state", e);
}
}
}
fun getActualLib(path: String) = actualLibraries[path]
fun getLibMeta(path: String) = librariesMeta[path]
fun getAllLibs(): Collection<LibraryData> = actualLibraries.values
fun refresh(progress: ProgressIndicator) {
actualLibraries.clear()
librariesMeta.clear()
jarLibraries.clear()
val projectRoot = File(project.basePath)
val toDownload = arrayListOf<Pair<LibMetadata, File>>()
// Create a maps of libs
progress.text = "updating third parties"
collectMavenInstalls(projectRoot, toDownload)
LOG.info("resolving libraries")
progress.text = "resolving libraries"
if (toDownload.isNotEmpty()) {
for ((lib, file) in toDownload) {
progress.text2 = "downloading ${lib.coords}"
HttpRequests.request(lib.url).saveToFile(file, progress)
}
}
LOG.info("libraries resolved")
}
private fun collectMavenInstalls(
projectRoot: File,
toDownload: ArrayList<Pair<LibMetadata, File>>
) {
val mavenInstallFiles = projectRoot.walk()
.onEnter { !isNonProjectDirectory(it) }
.filter { it.name == "maven_install.json" }
for (mavenInstall in mavenInstallFiles) {
val depFile = mapper.readValue<Map<String, Map<String, Any>>>(mavenInstall)["dependency_tree"] as Map<String, Any>
val dependencies = depFile["dependencies"] as List<Map<String, Any>>
for (dep in dependencies) {
val coords = dep["coord"] as String
if (coords.contains(":sources:")) {
val artifactCoords = coords.replace(":jar:sources", "")
val lib = librariesMeta[artifactCoords]
if (lib == null || dep["url"] == null) {
LOG.warn("Can't attach sources for '$artifactCoords'")
continue
}
val sources = Sources(
dep["url"] as String,
lib.repository
)
librariesMeta[artifactCoords] = lib.copy(
source = sources
)
val localSourceJar = sources.localSourceJar()
if (localSourceJar.exists()) {
val libraryData = actualLibraries[lib.name]
libraryData?.addPath(LibraryPathType.SOURCE, localSourceJar.absolutePath)
}
continue
}
val url = dep["url"] as String
val (groupId, artifactId, version) = coords.split(":")
val endIndex = url.indexOf("${groupId.replace('.', '/')}/")
if (endIndex == -1) {
LOG.warn("Corrupted dependency url doesn't contain artifact groupid: $url")
continue
}
val repository = url.substring(0, endIndex)
val name = coordsToName(coords)
val lib = LibMetadata(
name,
coords,
url,
repository,
null,
dependenciesStr = dep["dependencies"] as List<String>
)
val jarFile = lib.localJar()
val unresolved = !jarFile.exists()
if (unresolved) {
toDownload.add(lib to jarFile)
}
val libraryData = LibraryData(SYSTEM_ID, lib.coords).apply {
setGroup(groupId)
setArtifactId(artifactId)
setVersion(version)
addPath(LibraryPathType.BINARY, jarFile.absolutePath)
}
lib.allDependencies.add(libraryData)
actualLibraries[lib.name] = libraryData
// well, suddenly this is allowed too.
actualLibraries["${lib.name}_${version.replace(".", "_")}"] = libraryData
librariesMeta[lib.coords] = lib
}
}
for ((_, lib) in librariesMeta) {
for (dependencyCoord in lib.dependenciesStr) {
val libraryData = actualLibraries[coordsToName(dependencyCoord)]
if (libraryData == null) {
LOG.warn("Can't find library data mapping: $dependencyCoord")
continue
}
lib.allDependencies.add(libraryData)
}
}
}
fun getJarLibs(buildFileFolderPath: String, jars: List<String>): List<LibraryData> {
return jars.map { libPath ->
jarLibraries.getOrPut(libPath, {
LibraryData(SYSTEM_ID, libPath).apply {
addPath(LibraryPathType.BINARY, "${buildFileFolderPath}/${libPath}")
}
})
}
}
private fun coordsToName(coords: String): String {
val parts = coords.split(":")
val groupId: String = parts[0]
var artifactId: String = parts[1]
if (parts.size == 5) {
val classifier = parts[3]
artifactId += "_$classifier"
}
return "${groupId}_$artifactId".replace('.', '_').replace('-', '_')
}
}
private fun toLocalRepository(url: String, repository: String) = File(
url.replace(
repository,
File(System.getProperty("user.home"), ".m2/repository/").absolutePath + "/"
)
)
fun LibMetadata.localJar(): File = toLocalRepository(url, repository)
fun Sources.localSourceJar(): File = toLocalRepository(url, repository)
| 1 | null | 4 | 15 | 0b94a19589dfd2950f404bf3e804f86a842ca21a | 7,091 | bazillion | MIT License |
ground/src/main/java/com/google/android/ground/ui/home/SignOutConfirmationDialog.kt | google | 127,777,820 | false | {"Kotlin": 1403201} | /*
* Copyright 2024 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.android.ground.ui.home
import androidx.compose.material3.AlertDialog
import androidx.compose.material3.Text
import androidx.compose.material3.TextButton
import androidx.compose.runtime.Composable
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.tooling.preview.Preview
import com.google.android.ground.R
import com.google.android.ground.ui.theme.AppTheme
@Composable
fun SignOutConfirmationDialog(signOutCallback: () -> Unit, dismissCallback: () -> Unit) {
AlertDialog(
onDismissRequest = { dismissCallback() },
title = { Text(text = stringResource(R.string.sign_out_dialog_title)) },
text = { Text(text = stringResource(R.string.sign_out_dialog_body)) },
dismissButton = {
TextButton(onClick = { dismissCallback() }) { Text(text = stringResource(R.string.cancel)) }
},
confirmButton = {
TextButton(
onClick = {
signOutCallback()
dismissCallback()
}
) {
Text(text = stringResource(R.string.sign_out))
}
},
)
}
@Composable
@Preview
fun PreviewSignOutConfirmationDialog() {
AppTheme { SignOutConfirmationDialog(signOutCallback = {}, dismissCallback = {}) }
}
| 224 | Kotlin | 116 | 245 | 502a3bcafa4d65ba62868036cf5287a4219aaf5c | 1,800 | ground-android | Apache License 2.0 |
wan/src/main/java/com/hzy/wan/viewmodel/BaseViewModel.kt | maxrco | 262,023,085 | false | null | package com.hzy.wan.viewmodel
import androidx.lifecycle.AndroidViewModel
import androidx.lifecycle.LifecycleObserver
import androidx.lifecycle.viewModelScope
import com.aleyn.mvvm.base.IBaseResponse
import com.aleyn.mvvm.event.Message
import com.aleyn.mvvm.event.SingleLiveEvent
import com.aleyn.mvvm.network.ExceptionHandle
import com.aleyn.mvvm.network.ResponseThrowable
import com.hzy.wan.App
import kotlinx.coroutines.*
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.flow
open class BaseViewModel : AndroidViewModel(App.getAppInsatnce()), LifecycleObserver {
val defUI: UIChange by lazy { UIChange() }
/**
* 所有网络请求都在 viewModelScope 域中启动,当页面销毁时会自动
* 调用ViewModel的 #onCleared 方法取消所有协程
*/
fun launchUI(block: suspend CoroutineScope.() -> Unit) = viewModelScope.launch { block() }
/**
* 用流的方式进行网络请求
*/
fun <T> launchFlow(block: suspend () -> T): Flow<T> {
return flow {
emit(block())
}
}
/**
* 不过滤请求结果
* @param block 请求体
* @param error 失败回调
* @param complete 完成回调(无论成功失败都会调用)
* @param isShowDialog 是否显示加载框
*/
fun launchGo(
block: suspend CoroutineScope.() -> Unit,
error: suspend CoroutineScope.(ResponseThrowable) -> Unit = {
defUI.toastEvent.postValue("${it.code}:${it.errMsg}")
},
complete: suspend CoroutineScope.() -> Unit = {},
isShowDialog: Boolean = true
) {
if (isShowDialog) defUI.showDialog.call()
launchUI {
handleException(
withContext(Dispatchers.IO) { block },
{ error(it) },
{
defUI.dismissDialog.call()
complete()
}
)
}
}
/**
* 过滤请求结果,其他全抛异常
* @param block 请求体
* @param success 成功回调
* @param error 失败回调
* @param complete 完成回调(无论成功失败都会调用)
* @param isShowDialog 是否显示加载框
*/
fun <T> launchOnlyresult(
block: suspend CoroutineScope.() -> IBaseResponse<T>,
success: (T) -> Unit,
error: (ResponseThrowable) -> Unit = {
defUI.toastEvent.postValue("${it.code}:${it.errMsg}")
},
complete: () -> Unit = {},
isShowDialog: Boolean = true
) {
if (isShowDialog) defUI.showDialog.call()
launchUI {
handleException(
{ withContext(Dispatchers.IO) { block() } },
{ res ->
executeResponse(res) { success(it) }
},
{
error(it)
},
{
defUI.dismissDialog.call()
complete()
}
)
}
}
/**
* 请求结果过滤
*/
private suspend fun <T> executeResponse(
response: IBaseResponse<T>,
success: suspend CoroutineScope.(T) -> Unit
) {
coroutineScope {
if (response.isSuccess()) success(response.data())
else throw ResponseThrowable(response.code(), response.msg())
}
}
/**
* 异常统一处理
*/
private suspend fun <T> handleException(
block: suspend CoroutineScope.() -> IBaseResponse<T>,
success: suspend CoroutineScope.(IBaseResponse<T>) -> Unit,
error: suspend CoroutineScope.(ResponseThrowable) -> Unit,
complete: suspend CoroutineScope.() -> Unit
) {
coroutineScope {
try {
success(block())
} catch (e: Throwable) {
error(ExceptionHandle.handleException(e))
} finally {
complete()
}
}
}
/**
* 异常统一处理
*/
private suspend fun handleException(
block: suspend CoroutineScope.() -> Unit,
error: suspend CoroutineScope.(ResponseThrowable) -> Unit,
complete: suspend CoroutineScope.() -> Unit
) {
coroutineScope {
try {
block()
} catch (e: Throwable) {
error(ExceptionHandle.handleException(e))
} finally {
complete()
}
}
}
/**
* UI事件
*/
inner class UIChange {
val showDialog by lazy { SingleLiveEvent<String>() }
val dismissDialog by lazy { SingleLiveEvent<Void>() }
val toastEvent by lazy { SingleLiveEvent<String>() }
val msgEvent by lazy { SingleLiveEvent<Message>() }
}
} | 1 | null | 1 | 1 | fbc4f6e1905165ec0348f2856a4dc04c1010bb8e | 4,674 | footballs | Apache License 2.0 |
source/sdk/src/main/java/com/stytch/sdk/common/dfp/ActivityProvider.kt | stytchauth | 314,556,359 | false | null | package com.stytch.sdk.common.dfp
import android.app.Activity
import android.app.Application
import android.os.Bundle
import java.lang.ref.WeakReference
internal class ActivityProvider(application: Application) : Application.ActivityLifecycleCallbacks {
private var _currentActivity = WeakReference<Activity>(null)
internal val currentActivity: Activity?
get() = _currentActivity.get()
private var lastResumedActivityName: String? = null
init {
application.registerActivityLifecycleCallbacks(this)
}
override fun onActivityCreated(activity: Activity, bundle: Bundle?) {
_currentActivity = WeakReference(activity)
}
override fun onActivityStarted(activity: Activity) {
_currentActivity = WeakReference(activity)
}
override fun onActivityResumed(activity: Activity) {
lastResumedActivityName = activity.localClassName
_currentActivity = WeakReference(activity)
}
override fun onActivityPaused(activity: Activity) {
if (lastResumedActivityName != activity.localClassName) return
_currentActivity = WeakReference(null)
}
override fun onActivityStopped(activity: Activity) {
if (lastResumedActivityName != activity.localClassName) return
_currentActivity = WeakReference(null)
}
override fun onActivitySaveInstanceState(activity: Activity, outState: Bundle) {
// noop
}
override fun onActivityDestroyed(activity: Activity) {
if (lastResumedActivityName != activity.localClassName) return
_currentActivity = WeakReference(null)
}
}
| 2 | null | 2 | 23 | 50f005d2273a248eb9c10bfadfc0a3c97dfc1b59 | 1,618 | stytch-android | MIT License |
WebAPI/src/main/kotlin/dev/fstudio/mcworldstats/web/routers/DeathCounter.kt | Kamillaova | 463,396,605 | false | {"Kotlin": 78372} | package dev.fstudio.mcworldstats.web.routers
import dev.fstudio.mcworldstats.util.ConfigManager.config
import dev.fstudio.mcworldstats.web.plugins.json
import io.ktor.application.*
import io.ktor.html.*
import io.ktor.http.*
import io.ktor.response.*
import io.ktor.routing.*
import kotlinx.html.*
import kotlinx.serialization.decodeFromString
import java.io.File
fun Route.routeDeathCounter() {
get("deaths") {
val deathFile = File(config.minecraftWorlds.deathCounterWorld, "deaths.json")
if (deathFile.exists()) {
when (call.request.queryParameters["type"]) {
"json" -> call.respondFile(deathFile)
else -> {
val data = json.decodeFromString<Map<String, Int>>(String(deathFile.readBytes()))
call.respondHtml {
head {
meta {
httpEquiv = "refresh"
content = "30"
}
link {
href =
"https://www.dafontfree.net/embed/Zm9yZ290dGVuLWZ1dHVyaXN0LXJlZ3VsYXImZGF0YS84L2YvNDQ3NjIvZm9yZ290dGVuIGZ1dHVyaXN0IHJnLnR0Zg"
rel = "stylesheet"
type = "text/css"
}
style {
+"h1 { font-family: 'forgotten-futurist-regular', sans-serif; }"
}
}
body {
div("reload-area") {
data.toSortedMap().forEach {
h1 {
+it.value.toString()
}
}
}
}
}
}
}
} else call.respond(HttpStatusCode.BadGateway, "File not found")
}
} | 0 | Kotlin | 0 | 1 | a935ae2b1831949a347c954c70c3df6628d3dde5 | 2,075 | Ellison | MIT License |
reactivestate-core/src/commonMain/kotlin/com/ensody/reactivestate/FatalError.kt | ensody | 246,103,397 | false | {"Kotlin": 188198, "Shell": 3131, "Python": 1267, "Dockerfile": 252} | package com.ensody.reactivestate
public expect fun Throwable.isFatal(): Boolean
/** Throws this exception if it's fatal. Otherwise returns it. */
@Suppress("NOTHING_TO_INLINE")
public inline fun <T : Throwable> T.throwIfFatal(): T =
if (isFatal()) throw this else this
/** Similar to the stdlib [runCatching], but uses [throwIfFatal] to re-throw fatal exceptions immediately. */
public inline fun <T> runCatchingNonFatal(block: () -> T): Result<T> =
try {
Result.success(block())
} catch (e: Throwable) {
Result.failure(e.throwIfFatal())
}
/**
* Similar to the stdlib [runCatching][Unit.runCatching], but uses [throwIfFatal] to re-throw fatal exceptions
* immediately.
*/
public inline fun <T, R> T.runCatchingNonFatal(block: T.() -> R): Result<R> =
try {
Result.success(block())
} catch (e: Throwable) {
Result.failure(e.throwIfFatal())
}
| 3 | Kotlin | 2 | 38 | aee5e749799fc542d23c39cd6862a12e7b8831ae | 907 | ReactiveState-Kotlin | Apache License 2.0 |
shared/src/commonMain/kotlin/com/presta/customer/ui/components/payLoan/ui/PayLoanScreen.kt | morgan4080 | 678,697,424 | false | null | package com.presta.customer.ui.components.payLoan.ui
import androidx.compose.foundation.ExperimentalFoundationApi
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.runtime.Composable
import androidx.compose.runtime.collectAsState
import androidx.compose.runtime.getValue
import com.presta.customer.ui.components.payLoan.PayLoanComponent
@Composable
fun PayLoanScreen(component: PayLoanComponent){
val profileState by component.profileState.collectAsState()
PayLoanContent(
component::onPaySelected,
component::onBack,
state = profileState
)
}
| 0 | Kotlin | 0 | 0 | d26cc0013c5bedf29d2f349b86e90052a0aca64e | 641 | kotlin-multiplatform | Apache License 2.0 |
app/src/main/java/com/wavesplatform/wallet/v2/ui/auth/import_account/ImportAccountFragmentPageAdapter.kt | inozemtsev-roman | 202,315,169 | false | null | /*
* Created by <NAME> on 1/4/2019
* Copyright © 2019 Waves Platform. All rights reserved.
*/
package com.wavesplatform.wallet.v2.ui.auth.import_account
import android.support.v4.app.Fragment
import android.support.v4.app.FragmentManager
import android.support.v4.app.FragmentStatePagerAdapter
import com.wavesplatform.wallet.v2.ui.auth.import_account.manually.EnterSeedManuallyFragment
import com.wavesplatform.wallet.v2.ui.auth.import_account.scan.ScanSeedFragment
class ImportAccountFragmentPageAdapter(fm: FragmentManager?, var titles: Array<String>) : FragmentStatePagerAdapter(fm) {
override fun getItem(position: Int): Fragment {
when (position) {
0 -> {
return ScanSeedFragment()
}
1 -> {
return EnterSeedManuallyFragment()
}
}
return ScanSeedFragment()
}
override fun getCount(): Int = titles.size
override fun getPageTitle(position: Int): CharSequence? {
return titles[position]
}
}
| 1 | null | 1 | 2 | 9359a88dfe96f9fbc78360fd22c17fce252a88ae | 1,034 | PZU-android | MIT License |
src/main/kotlin/com/glinboy/telegram/bot/monitorspringboot/dto/LinkDataDTO.kt | GLinBoy | 537,545,489 | false | {"Kotlin": 21799} | package com.glinboy.telegram.bot.monitorspringboot.dto
data class LinkDataDTO(
val href: String?,
val templated: Boolean?
)
| 23 | Kotlin | 0 | 1 | 8a2ccecda7dff0ac111692fec9e4e2c524ceea6c | 133 | spring-boot-version-monitor-bot | MIT License |
compiler/testData/codegen/box/ranges/literal/progressionMinValueToMinValue.kt | arrow-kt | 109,678,056 | false | null | // TODO: muted automatically, investigate should it be ran for JS_IR or not
// IGNORE_BACKEND: JS_IR
// TODO: muted automatically, investigate should it be ran for JVM_IR or not
// IGNORE_BACKEND: JVM_IR
// Auto-generated by org.jetbrains.kotlin.generators.tests.GenerateRangesCodegenTestData. DO NOT EDIT!
// WITH_RUNTIME
const val MinI = Int.MIN_VALUE
const val MinB = Byte.MIN_VALUE
const val MinS = Short.MIN_VALUE
const val MinL = Long.MIN_VALUE
const val MinC = Char.MIN_VALUE
const val MinUI = UInt.MIN_VALUE
const val MinUB = UByte.MIN_VALUE
const val MinUS = UShort.MIN_VALUE
const val MinUL = ULong.MIN_VALUE
fun box(): String {
val list1 = ArrayList<Int>()
for (i in MinI..MinI step 1) {
list1.add(i)
if (list1.size > 23) break
}
if (list1 != listOf<Int>(MinI)) {
return "Wrong elements for MinI..MinI step 1: $list1"
}
val list2 = ArrayList<Int>()
for (i in MinB..MinB step 1) {
list2.add(i)
if (list2.size > 23) break
}
if (list2 != listOf<Int>(MinB.toInt())) {
return "Wrong elements for MinB..MinB step 1: $list2"
}
val list3 = ArrayList<Int>()
for (i in MinS..MinS step 1) {
list3.add(i)
if (list3.size > 23) break
}
if (list3 != listOf<Int>(MinS.toInt())) {
return "Wrong elements for MinS..MinS step 1: $list3"
}
val list4 = ArrayList<Long>()
for (i in MinL..MinL step 1) {
list4.add(i)
if (list4.size > 23) break
}
if (list4 != listOf<Long>(MinL)) {
return "Wrong elements for MinL..MinL step 1: $list4"
}
val list5 = ArrayList<Char>()
for (i in MinC..MinC step 1) {
list5.add(i)
if (list5.size > 23) break
}
if (list5 != listOf<Char>(MinC)) {
return "Wrong elements for MinC..MinC step 1: $list5"
}
val list6 = ArrayList<UInt>()
for (i in MinUI..MinUI step 1) {
list6.add(i)
if (list6.size > 23) break
}
if (list6 != listOf<UInt>(MinUI)) {
return "Wrong elements for MinUI..MinUI step 1: $list6"
}
val list7 = ArrayList<UInt>()
for (i in MinUB..MinUB step 1) {
list7.add(i)
if (list7.size > 23) break
}
if (list7 != listOf<UInt>(MinUB.toUInt())) {
return "Wrong elements for MinUB..MinUB step 1: $list7"
}
val list8 = ArrayList<UInt>()
for (i in MinUS..MinUS step 1) {
list8.add(i)
if (list8.size > 23) break
}
if (list8 != listOf<UInt>(MinUS.toUInt())) {
return "Wrong elements for MinUS..MinUS step 1: $list8"
}
val list9 = ArrayList<ULong>()
for (i in MinUL..MinUL step 1) {
list9.add(i)
if (list9.size > 23) break
}
if (list9 != listOf<ULong>(MinUL)) {
return "Wrong elements for MinUL..MinUL step 1: $list9"
}
return "OK"
}
| 12 | null | 1 | 43 | d2a24985b602e5f708e199aa58ece652a4b0ea48 | 2,863 | kotlin | Apache License 2.0 |
leakcanary-android-core/src/main/java/leakcanary/internal/activity/db/Db.kt | Pvredev | 254,723,305 | true | {"Kotlin": 837683, "Shell": 1407, "Java": 91} | package leakcanary.internal.activity.db
import android.database.sqlite.SQLiteDatabase
import android.view.View
import leakcanary.internal.InternalLeakCanary
import leakcanary.internal.activity.db.Db.OnDb
import leakcanary.internal.activity.db.Io.OnIo
internal object Db {
private val dbHelper = LeaksDbHelper(InternalLeakCanary.application)
interface OnDb : OnIo {
val db: SQLiteDatabase
}
private class DbContext(override val db: SQLiteDatabase) : OnDb {
var updateUi: (View.() -> Unit)? = null
override fun updateUi(updateUi: View.() -> Unit) {
this.updateUi = updateUi
}
}
fun execute(
view: View,
block: OnDb.() -> Unit
) {
Io.execute(view) {
val dbBlock = DbContext(dbHelper.writableDatabase)
block(dbBlock)
val updateUi = dbBlock.updateUi
if (updateUi != null) {
updateUi(updateUi)
}
}
}
fun closeDatabase() {
// Closing on the serial IO thread to ensure we don't close while using the db.
Io.execute {
dbHelper.close()
}
}
}
internal fun View.executeOnDb(block: OnDb.() -> Unit) {
Db.execute(this, block)
} | 0 | Kotlin | 0 | 2 | fbcf730bb5c89d51cc925d1847f80ec15390fcbe | 1,140 | leakcanary | Apache License 2.0 |
src/main/kotlin/kotlinmud/action/contextBuilder/DoorInRoomContextBuilder.kt | brandonlamb | 275,313,206 | true | {"Kotlin": 435931, "Dockerfile": 133, "Shell": 126} | package kotlinmud.action.contextBuilder
import kotlinmud.action.model.Context
import kotlinmud.action.type.Status
import kotlinmud.helper.string.matches
import kotlinmud.io.type.Syntax
import kotlinmud.room.model.Exit
import kotlinmud.room.model.Room
class DoorInRoomContextBuilder(private val room: Room) : ContextBuilder {
override fun build(syntax: Syntax, word: String): Context<Any> {
return room.exits.find {
it.door != null && matchExit(it, word)
}?.let { Context<Any>(syntax, Status.OK, it.door!!) }
?: Context<Any>(
syntax,
Status.FAILED,
"you don't see that anywhere."
)
}
}
fun matchExit(exit: Exit, word: String): Boolean {
if (matches(exit.door!!.name, word)) {
return true
}
if (matches(exit.direction.value, word)) {
return true
}
return false
}
| 0 | null | 0 | 0 | fc03c6230b9b3b66cd63994e74ddd7897732d527 | 910 | kotlinmud | MIT License |
owncloudComLibrary/src/main/java/com/owncloud/android/lib/resources/oauth/params/ClientRegistrationParams.kt | jesmrec | 464,454,115 | true | {"INI": 2, "Gradle": 4, "Shell": 1, "EditorConfig": 1, "Markdown": 2, "Batchfile": 1, "Ignore List": 1, "XML": 11, "YAML": 2, "Text": 1, "Java": 46, "Kotlin": 74, "JSON": 2} | /* ownCloud Android Library is available under MIT license
*
* @author <NAME>
*
* Copyright (C) 2021 ownCloud GmbH.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
* BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
* ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*
*/
package com.owncloud.android.lib.resources.oauth.params
import com.owncloud.android.lib.common.http.HttpConstants.CONTENT_TYPE_JSON
import okhttp3.MediaType.Companion.toMediaType
import okhttp3.RequestBody
import okhttp3.RequestBody.Companion.toRequestBody
import org.json.JSONArray
import org.json.JSONObject
data class ClientRegistrationParams(
val registrationEndpoint: String,
val clientName: String,
val redirectUris: List<String>,
val tokenEndpointAuthMethod: String,
val applicationType: String
) {
fun toRequestBody(): RequestBody =
JSONObject().apply {
put(PARAM_APPLICATION_TYPE, applicationType)
put(PARAM_CLIENT_NAME, clientName)
put(PARAM_REDIRECT_URIS, JSONArray(redirectUris))
put(PARAM_TOKEN_ENDPOINT_AUTH_METHOD, tokenEndpointAuthMethod)
}.toString().toRequestBody(CONTENT_TYPE_JSON.toMediaType())
companion object {
private const val PARAM_APPLICATION_TYPE = "application_type"
private const val PARAM_CLIENT_NAME = "client_name"
private const val PARAM_TOKEN_ENDPOINT_AUTH_METHOD = "token_endpoint_auth_method"
private const val PARAM_REDIRECT_URIS = "redirect_uris"
}
}
| 0 | Java | 0 | 0 | fb7bfb23e0aeabdcdfaadc48ecbe7c6bca4889b4 | 2,462 | android-library | MIT License |
owncloudComLibrary/src/main/java/com/owncloud/android/lib/resources/oauth/params/ClientRegistrationParams.kt | jesmrec | 464,454,115 | true | {"INI": 2, "Gradle": 4, "Shell": 1, "EditorConfig": 1, "Markdown": 2, "Batchfile": 1, "Ignore List": 1, "XML": 11, "YAML": 2, "Text": 1, "Java": 46, "Kotlin": 74, "JSON": 2} | /* ownCloud Android Library is available under MIT license
*
* @author <NAME>
*
* Copyright (C) 2021 ownCloud GmbH.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
* BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
* ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*
*/
package com.owncloud.android.lib.resources.oauth.params
import com.owncloud.android.lib.common.http.HttpConstants.CONTENT_TYPE_JSON
import okhttp3.MediaType.Companion.toMediaType
import okhttp3.RequestBody
import okhttp3.RequestBody.Companion.toRequestBody
import org.json.JSONArray
import org.json.JSONObject
data class ClientRegistrationParams(
val registrationEndpoint: String,
val clientName: String,
val redirectUris: List<String>,
val tokenEndpointAuthMethod: String,
val applicationType: String
) {
fun toRequestBody(): RequestBody =
JSONObject().apply {
put(PARAM_APPLICATION_TYPE, applicationType)
put(PARAM_CLIENT_NAME, clientName)
put(PARAM_REDIRECT_URIS, JSONArray(redirectUris))
put(PARAM_TOKEN_ENDPOINT_AUTH_METHOD, tokenEndpointAuthMethod)
}.toString().toRequestBody(CONTENT_TYPE_JSON.toMediaType())
companion object {
private const val PARAM_APPLICATION_TYPE = "application_type"
private const val PARAM_CLIENT_NAME = "client_name"
private const val PARAM_TOKEN_ENDPOINT_AUTH_METHOD = "token_endpoint_auth_method"
private const val PARAM_REDIRECT_URIS = "redirect_uris"
}
}
| 0 | Java | 0 | 0 | fb7bfb23e0aeabdcdfaadc48ecbe7c6bca4889b4 | 2,462 | android-library | MIT License |
app/src/main/kotlin/com/cogzidel/calendar/services/SnoozeService.kt | selvakumar1994 | 140,288,445 | true | {"Kotlin": 418618} | package com.cogzidel.calendar.services
import android.app.IntentService
import android.content.Intent
import com.cogzidel.calendar.extensions.config
import com.cogzidel.calendar.extensions.dbHelper
import com.cogzidel.calendar.extensions.rescheduleReminder
import com.cogzidel.calendar.helpers.EVENT_ID
class SnoozeService : IntentService("Snooze") {
override fun onHandleIntent(intent: Intent) {
val eventId = intent.getIntExtra(EVENT_ID, 0)
val event = dbHelper.getEventWithId(eventId)
rescheduleReminder(event, config.snoozeTime)
}
}
| 0 | Kotlin | 0 | 0 | aba35398e6a97b9369f6ad857c3d661f515d398e | 571 | SimpleCalender | Apache License 2.0 |
app/src/main/java/com/dania/productfinder/di/ViewModelModule.kt | daniachan | 335,151,127 | false | null | package com.dania.productfinder.di
import androidx.lifecycle.ViewModel
import androidx.lifecycle.ViewModelProvider
import dagger.Binds
import dagger.Module
import dagger.multibindings.IntoMap
import com.dania.productfinder.ui.search.SearchViewModel
import com.dania.productfinder.viewmodel.GithubViewModelFactory
@Suppress("unused")
@Module
abstract class ViewModelModule {
@Binds
@IntoMap
@ViewModelKey(SearchViewModel::class)
abstract fun bindSearchViewModel(searchViewModel: SearchViewModel): ViewModel
@Binds
abstract fun bindViewModelFactory(factory: GithubViewModelFactory): ViewModelProvider.Factory
} | 0 | Kotlin | 0 | 0 | a7cf8399e5c9e73b7ecadadc78b57b20dfae40c4 | 635 | ProductFinder | MIT License |
PayPal/src/main/java/com/braintreepayments/api/paypal/PayPalLauncher.kt | braintree | 21,631,528 | false | {"Kotlin": 1036089, "Java": 700403, "Shell": 282} | package com.braintreepayments.api.paypal
import android.content.Intent
import androidx.activity.ComponentActivity
import com.braintreepayments.api.BrowserSwitchClient
import com.braintreepayments.api.BrowserSwitchException
import com.braintreepayments.api.BrowserSwitchFinalResult
import com.braintreepayments.api.BrowserSwitchStartResult
import com.braintreepayments.api.core.BraintreeException
/**
* Responsible for launching PayPal user authentication in a web browser
*/
class PayPalLauncher internal constructor(private val browserSwitchClient: BrowserSwitchClient) {
/**
* Used to launch the PayPal flow in a web browser and deliver results to your Activity
*/
constructor() : this(BrowserSwitchClient())
/**
* Launches the PayPal flow by switching to a web browser for user authentication
*
* @param activity the Android Activity from which you will launch the web browser
* @param paymentAuthRequest a [PayPalPaymentAuthRequest.ReadyToLaunch] received from
* calling [PayPalClient.createPaymentAuthRequest]
* @return [PayPalPendingRequest] a [PayPalPendingRequest.Started] should be stored
* to complete the flow upon return to app in
* [PayPalLauncher.handleReturnToApp],
* or a [PayPalPendingRequest.Failure] with an error if the PayPal flow was unable to be
* launched in a browser.
*/
fun launch(
activity: ComponentActivity,
paymentAuthRequest: PayPalPaymentAuthRequest.ReadyToLaunch
): PayPalPendingRequest {
try {
assertCanPerformBrowserSwitch(activity, paymentAuthRequest.requestParams)
} catch (browserSwitchException: BrowserSwitchException) {
val manifestInvalidError = createBrowserSwitchError(browserSwitchException)
return PayPalPendingRequest.Failure(manifestInvalidError)
}
return paymentAuthRequest.requestParams.browserSwitchOptions?.let { options ->
when (val request = browserSwitchClient.start(activity, options)) {
is BrowserSwitchStartResult.Failure -> PayPalPendingRequest.Failure(request.error)
is BrowserSwitchStartResult.Started -> PayPalPendingRequest.Started(request.pendingRequest)
}
} ?: run {
PayPalPendingRequest.Failure(BraintreeException("BrowserSwitchOptions is null"))
}
}
/**
* Captures and delivers the result of a PayPal authentication flow.
*
* For most integrations, this method should be invoked in the onResume method of the Activity
* used to invoke
* [PayPalLauncher.launch].
*
* If the Activity used to launch the PayPal flow has is configured with
* android:launchMode="singleTop", this method should be invoked in the onNewIntent method of
* the Activity.
*
* @param pendingRequest the [PayPalPendingRequest.Started] stored after successfully
* invoking [PayPalLauncher.launch]
* @param intent the intent to return to your application containing a deep link result
* from the PayPal browser flow
* @return a [PayPalPaymentAuthResult.Success] that should be passed to [PayPalClient.tokenize]
* to complete the PayPal payment flow. Returns [PayPalPaymentAuthResult.NoResult] if the user
* canceled the payment flow, or returned to the app without completing the PayPal
* authentication flow.
*/
fun handleReturnToApp(
pendingRequest: PayPalPendingRequest.Started,
intent: Intent
): PayPalPaymentAuthResult {
return when (val browserSwitchResult =
browserSwitchClient.completeRequest(intent, pendingRequest.pendingRequestString)) {
is BrowserSwitchFinalResult.Success -> PayPalPaymentAuthResult.Success(
browserSwitchResult
)
is BrowserSwitchFinalResult.Failure -> PayPalPaymentAuthResult.Failure(
browserSwitchResult.error
)
is BrowserSwitchFinalResult.NoResult -> PayPalPaymentAuthResult.NoResult
}
}
@Throws(BrowserSwitchException::class)
private fun assertCanPerformBrowserSwitch(
activity: ComponentActivity,
params: PayPalPaymentAuthRequestParams
) {
browserSwitchClient.assertCanPerformBrowserSwitch(activity, params.browserSwitchOptions)
}
companion object {
private fun createBrowserSwitchError(exception: BrowserSwitchException): Exception {
return BraintreeException(
"AndroidManifest.xml is incorrectly configured or another app defines the same " +
"browser switch url as this app. See https://developer.paypal.com/" +
"braintree/docs/guides/client-sdk/setup/android/v4#browser-switch-setup " +
"for the correct configuration: " + exception.message
)
}
}
}
| 24 | Kotlin | 233 | 409 | 92dabb74f14e6203259511f6b6a51367e3247fc5 | 4,910 | braintree_android | MIT License |
data/RF03050/rnartist.kts | fjossinet | 449,239,232 | false | {"Kotlin": 8214424} | import io.github.fjossinet.rnartist.core.*
rnartist {
ss {
rfam {
id = "RF03050"
name = "consensus"
use alignment numbering
}
}
theme {
details {
value = 3
}
color {
location {
9 to 13
19 to 23
}
value = "#dbbbd4"
}
color {
location {
41 to 44
51 to 54
}
value = "#9a5758"
}
color {
location {
14 to 18
}
value = "#d590af"
}
color {
location {
45 to 50
}
value = "#6539a5"
}
color {
location {
1 to 8
}
value = "#e963e9"
}
color {
location {
24 to 40
}
value = "#b713a6"
}
color {
location {
55 to 55
}
value = "#3b5d47"
}
}
} | 0 | Kotlin | 0 | 0 | 3016050675602d506a0e308f07d071abf1524b67 | 1,166 | Rfam-for-RNArtist | MIT License |
akari-core/src/main/java/io/github/takusan23/akaricore/v2/common/MediaMuxerTool.kt | takusan23 | 584,131,815 | false | {"Kotlin": 370704, "Java": 67808} | package io.github.takusan23.akaricore.v1.tool
import android.annotation.SuppressLint
import android.media.MediaCodec
import android.media.MediaExtractor
import android.media.MediaMuxer
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.isActive
import kotlinx.coroutines.withContext
import java.io.File
import java.nio.ByteBuffer
/**
* 音声と映像をコンテナフォーマットへしまって一つの動画にする関数がある
* */
object MediaMuxerTool {
/**
* コンテナフォーマットへ格納する
*
* @param resultFile 最終的なファイル
* @param containerFormat [MediaMuxer.OutputFormat.MUXER_OUTPUT_MPEG_4] など
* @param mergeFileList コンテナフォーマットへ入れる音声、映像データの[File]
* */
@SuppressLint("WrongConstant")
suspend fun mixed(
resultFile: File,
containerFormat: Int,
mergeFileList: List<File>,
) = withContext(Dispatchers.Default) {
// 映像と音声を追加して一つの動画にする
val mediaMuxer = MediaMuxer(resultFile.path, containerFormat)
// 音声、映像ファイルの トラック番号 と [MediaExtractor] の Pair
val trackIndexToExtractorPairList = mergeFileList.map {
// MediaExtractorとフォーマット取得
val mediaExtractor = MediaExtractor().apply { setDataSource(it.path) }
val mediaFormat = mediaExtractor.getTrackFormat(0) // 音声には音声、映像には映像しか無いので 0
mediaExtractor.selectTrack(0)
mediaFormat to mediaExtractor
}.map { (format, extractor) ->
// フォーマットをMediaMuxerに渡して、トラックを追加してもらう
val videoTrackIndex = mediaMuxer.addTrack(format)
videoTrackIndex to extractor
}
// MediaMuxerスタート
mediaMuxer.start()
// 映像と音声を一つの動画ファイルに書き込んでいく
trackIndexToExtractorPairList.forEach { (index, extractor) ->
val byteBuffer = ByteBuffer.allocate(1024 * 4096)
val bufferInfo = MediaCodec.BufferInfo()
// データが無くなるまで回す
while (isActive) {
// データを読み出す
val offset = byteBuffer.arrayOffset()
bufferInfo.size = extractor.readSampleData(byteBuffer, offset)
// もう無い場合
if (bufferInfo.size < 0) break
// 書き込む
bufferInfo.presentationTimeUs = extractor.sampleTime
bufferInfo.flags = extractor.sampleFlags // Lintがキレるけど黙らせる
mediaMuxer.writeSampleData(index, byteBuffer, bufferInfo)
// 次のデータに進める
extractor.advance()
}
// あとしまつ
extractor.release()
}
// あとしまつ
mediaMuxer.stop()
mediaMuxer.release()
}
} | 0 | Kotlin | 0 | 0 | f97cf00ac2eb71239e3a9a4b438634ec8d79d48f | 2,575 | AkariDroid | Apache License 2.0 |
radixdlt-kotlin/src/test/kotlin/com/radixdlt/client/application/translate/UniquePropertyTranslatorTest.kt | radixdlt | 144,838,647 | false | null | package com.radixdlt.client.application.translate
import com.radixdlt.client.core.atoms.AtomBuilder
import io.reactivex.observers.TestObserver
import org.junit.Test
import org.mockito.Mockito.mock
class UniquePropertyTranslatorTest {
@Test
fun nullPropertyTest() {
val translator = UniquePropertyTranslator()
val atomBuilder = mock(AtomBuilder::class.java)
val testObserver = TestObserver.create<Any>()
translator.translate(null, atomBuilder).subscribe(testObserver)
testObserver.assertComplete()
}
}
| 1 | Kotlin | 1 | 5 | 37d86b43bd5e9e5c24c85a8f2d7865b51cd24a7b | 555 | radixdlt-kotlin | MIT License |
shared/src/commonMain/kotlin/com/example/moveeapp_compose_kmm/data/account/AccountServiceImpl.kt | adessoTurkey | 673,248,729 | false | {"Kotlin": 334470, "Swift": 3538, "Ruby": 101} | package com.example.moveeapp_compose_kmm.data.account
import com.example.moveeapp_compose_kmm.data.account.login.LoginRequestModel
import com.example.moveeapp_compose_kmm.data.account.login.LoginResponseModel
import com.example.moveeapp_compose_kmm.data.account.login.RequestTokenResponseModel
import com.example.moveeapp_compose_kmm.data.account.login.SessionRequestModel
import com.example.moveeapp_compose_kmm.data.account.login.SessionResponseModel
import com.example.moveeapp_compose_kmm.data.remote.ApiImpl
import com.example.moveeapp_compose_kmm.utils.Constants.SESSION_ID
import io.ktor.client.HttpClient
import io.ktor.client.call.body
import io.ktor.client.request.delete
import io.ktor.client.request.get
import io.ktor.client.request.post
import io.ktor.client.request.setBody
import io.ktor.http.ContentType
import io.ktor.http.contentType
class AccountServiceImpl(
private val client: HttpClient,
) : AccountService {
override suspend fun accountDetails(sessionId: String): AccountDetailModel {
return client.get(ACCOUNT) {
url {
parameters.append(SESSION_ID, sessionId)
}
}.body()
}
//login
override suspend fun createRequestToken(): RequestTokenResponseModel {
return client.get(REQUEST_TOKEN).body()
}
override suspend fun createRequestTokenWithLogin(requestModel: LoginRequestModel): LoginResponseModel {
return client.post(LOGIN) {
contentType(ContentType.Application.Json)
setBody(requestModel)
}.body()
}
override suspend fun createSession(requestModel: SessionRequestModel): SessionResponseModel {
return client.post(SESSION) {
contentType(ContentType.Application.Json)
setBody(requestModel)
}.body()
}
override suspend fun logout(logoutRequestModel: LogoutRequestModel): LogoutResponseModel {
return client.delete(ApiImpl.LOGOUT) {
setBody(logoutRequestModel)
contentType(ContentType.Application.Json)
}.body()
}
companion object {
const val ACCOUNT = "account"
const val REQUEST_TOKEN = "authentication/token/new"
const val LOGIN = "authentication/token/validate_with_login"
const val SESSION = "authentication/session/new"
}
}
| 9 | Kotlin | 3 | 78 | 2dbbd48654ee482258c37f0e51e52eb6af15ec3c | 2,334 | compose-multiplatform-sampleapp | Apache License 2.0 |
src/test/kotlin/io/fixture/controller/StaticControllerTest.kt | martinlau | 11,140,245 | false | null | /*
* #%L
* fixture
* %%
* Copyright (C) 2013 <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.
* #L%
*/
package io.fixture.controller
import kotlin.test.assertEquals
import org.junit.Test
class StaticControllerTest {
val subject = StaticController()
[Test]
fun testIndex() {
assertEquals(".static.index", subject.index())
}
[Test]
fun testAbout() {
assertEquals(".static.about", subject.about())
}
[Test]
fun testAccessDenied() {
assertEquals(".static.access-denied", subject.accessDenied())
}
[Test]
fun testContact() {
assertEquals(".static.contact", subject.contact())
}
[Test]
fun testLogin() {
assertEquals(".static.login", subject.login())
}
[Test]
fun testTerms() {
assertEquals(".static.terms", subject.terms())
}
[Test]
fun testPrivacy() {
assertEquals(".static.privacy", subject.privacy())
}
}
| 6 | Kotlin | 0 | 0 | a751ea312708bac231f01dbf66ed1859a79f684a | 1,494 | fixture | Apache License 2.0 |
libs/crypto/crypto-impl/src/test/kotlin/net/corda/crypto/impl/retrying/CryptoRetryingExecutorsTests.kt | corda | 346,070,752 | false | null | package net.corda.crypto.impl.retrying
import net.corda.crypto.core.CryptoRetryException
import net.corda.v5.crypto.exceptions.CryptoException
import org.assertj.core.api.Assertions.assertThat
import org.junit.jupiter.api.Test
import org.junit.jupiter.api.assertThrows
import org.junit.jupiter.params.ParameterizedTest
import org.junit.jupiter.params.provider.MethodSource
import org.slf4j.LoggerFactory
import java.time.Duration
import java.util.concurrent.TimeoutException
import javax.persistence.LockTimeoutException
import javax.persistence.OptimisticLockException
import javax.persistence.PersistenceException
import javax.persistence.PessimisticLockException
import javax.persistence.QueryTimeoutException
class CryptoRetryingExecutorsTests {
private val defaultRetryTimeout = Duration.ofSeconds(5)
companion object {
private val logger = LoggerFactory.getLogger(this::class.java.enclosingClass)
@JvmStatic
fun mostCommonUnrecoverableExceptions(): List<Throwable> = listOf(
IllegalStateException(),
IllegalArgumentException(),
NullPointerException(),
IndexOutOfBoundsException(),
NoSuchElementException(),
RuntimeException(),
ClassCastException(),
NotImplementedError(),
UnsupportedOperationException(),
CryptoException("error"),
CryptoException(
"error",
CryptoException("error", true)
),
CryptoException(
"error",
TimeoutException()
),
CryptoRetryException("error", TimeoutException()),
PersistenceException()
)
@JvmStatic
fun recoverableExceptions(): List<Throwable> = listOf(
CryptoException("error", true),
TimeoutException(),
LockTimeoutException(),
QueryTimeoutException(),
OptimisticLockException(),
PessimisticLockException(),
java.sql.SQLTransientException(),
java.sql.SQLTimeoutException(),
org.hibernate.exception.LockAcquisitionException("error", java.sql.SQLException()),
org.hibernate.exception.LockTimeoutException("error", java.sql.SQLException()),
RuntimeException("error", TimeoutException()),
PersistenceException("error", LockTimeoutException()),
PersistenceException("error", QueryTimeoutException()),
PersistenceException("error", OptimisticLockException()),
PersistenceException("error", PessimisticLockException()),
PersistenceException("error", java.sql.SQLTransientException()),
PersistenceException("error", java.sql.SQLTimeoutException()),
PersistenceException("error", org.hibernate.exception.LockAcquisitionException(
"error", java.sql.SQLException()
)),
PersistenceException("error", org.hibernate.exception.LockTimeoutException(
"error", java.sql.SQLException()
))
)
}
@Test
fun `Should execute without retrying`() {
var called = 0
val result = CryptoRetryingExecutor(
logger,
BackoffStrategy.createBackoff(3, listOf(100L))
).executeWithRetry {
called++
"Hello World!"
}
assertThat(called).isEqualTo(1)
assertThat(result).isEqualTo("Hello World!")
}
@Test
fun `Should execute withTimeout without retrying`() {
var called = 0
val result = CryptoRetryingExecutorWithTimeout(
logger,
BackoffStrategy.createBackoff(3, listOf(100L)),
defaultRetryTimeout
).executeWithRetry {
called++
"Hello World!"
}
assertThat(called).isEqualTo(1)
assertThat(result).isEqualTo("Hello World!")
}
@Test
fun `CryptoRetryingExecutorWithTimeout should throw CryptoRetryException`() {
var called = 0
assertThrows<CryptoRetryException> {
CryptoRetryingExecutorWithTimeout(
logger,
BackoffStrategy.createBackoff(1, listOf(100L)),
Duration.ofMillis(10)
).executeWithRetry {
called++
Thread.sleep(100)
}
}
assertThat(called).isEqualTo(1)
}
@ParameterizedTest
@MethodSource("mostCommonUnrecoverableExceptions")
fun `CryptoRetryingExecutorWithTimeout should not retry common exceptions`(e: Throwable) {
var called = 0
val actual = assertThrows<Throwable> {
CryptoRetryingExecutorWithTimeout(
logger,
BackoffStrategy.createBackoff(3, listOf(100L)),
defaultRetryTimeout
).executeWithRetry {
called++
throw e
}
}
assertThat(called).isEqualTo(1)
assertThat(actual::class.java).isEqualTo(e::class.java)
}
@Test
fun `CryptoRetryingExecutorWithTimeout should not retry unrecoverable crypto library exception`() {
var called = 0
assertThrows<CryptoException> {
CryptoRetryingExecutorWithTimeout(
logger, BackoffStrategy.createBackoff(3, listOf(100L)),
defaultRetryTimeout
).executeWithRetry {
called++
throw CryptoException("error")
}
}
assertThat(called).isEqualTo(1)
}
@Test
fun `Should eventually fail with retrying`() {
var called = 0
val actual = assertThrows<CryptoRetryException> {
CryptoRetryingExecutor(
logger,
BackoffStrategy.createBackoff(3, listOf(10L))
).executeWithRetry {
called++
throw TimeoutException()
}
}
assertThat(called).isEqualTo(3)
assertThat(actual.cause).isInstanceOf(TimeoutException::class.java)
}
@Test
fun `Should eventually succeed after retrying TimeoutException`() {
var called = 0
val result = CryptoRetryingExecutor(
logger,
BackoffStrategy.createBackoff(3, listOf(10L))
).executeWithRetry {
called++
if (called <= 2) {
throw TimeoutException()
}
"Hello World!"
}
assertThat(called).isEqualTo(3)
assertThat(result).isEqualTo("Hello World!")
}
@ParameterizedTest
@MethodSource("recoverableExceptions")
fun `Should eventually succeed after retrying recoverable exception`(
e: Throwable
) {
var called = 0
val result = CryptoRetryingExecutor(
logger,
BackoffStrategy.createBackoff(3, listOf(10L))
).executeWithRetry {
called++
if (called <= 2) {
throw e
}
"Hello World!"
}
assertThat(called).isEqualTo(3)
assertThat(result).isEqualTo("Hello World!")
}
@ParameterizedTest
@MethodSource("recoverableExceptions")
fun `Should retry all recoverable exceptions`(e: Throwable) {
var called = 0
val result = CryptoRetryingExecutor(
logger,
BackoffStrategy.createBackoff(2, listOf(10L))
).executeWithRetry {
called++
if (called < 2) {
throw e
}
"Hello World!"
}
assertThat(called).isEqualTo(2)
assertThat(result).isEqualTo("Hello World!")
}
}
| 96 | null | 7 | 51 | 08c3e610a0e6ec20143c47d044e0516019ba6578 | 7,719 | corda-runtime-os | Apache License 2.0 |
core/src/main/kotlin/processes/CardProcessWorkers.kt | crowdproj | 543,982,440 | false | {"Kotlin": 595956, "JavaScript": 60372, "HTML": 21115, "Dockerfile": 361} | package com.gitlab.sszuev.flashcards.core.processes
import com.gitlab.sszuev.flashcards.CardContext
import com.gitlab.sszuev.flashcards.core.normalizers.normalize
import com.gitlab.sszuev.flashcards.corlib.ChainDSL
import com.gitlab.sszuev.flashcards.corlib.worker
import com.gitlab.sszuev.flashcards.model.common.AppStatus
import com.gitlab.sszuev.flashcards.model.domain.CardOperation
import com.gitlab.sszuev.flashcards.model.domain.TTSResourceGet
import com.gitlab.sszuev.flashcards.model.domain.TTSResourceId
import com.gitlab.sszuev.flashcards.repositories.CardDbResponse
import com.gitlab.sszuev.flashcards.repositories.CardsDbResponse
import com.gitlab.sszuev.flashcards.repositories.RemoveCardDbResponse
fun ChainDSL<CardContext>.processGetCard() = worker {
this.name = "process get-card request"
test {
this.status == AppStatus.RUN
}
process {
val userId = this.contextUserEntity.id
val cardId = this.normalizedRequestCardEntityId
val res = this.repositories.cardRepository(this.workMode).getCard(userId, cardId)
this.postProcess(res)
}
onException {
fail(
runError(
operation = CardOperation.GET_CARD,
fieldName = this.normalizedRequestCardEntityId.toFieldName(),
description = "exception",
exception = it
)
)
}
}
fun ChainDSL<CardContext>.processGetAllCards() = worker {
this.name = "process get-all-cards request"
test {
this.status == AppStatus.RUN
}
process {
val userId = this.contextUserEntity.id
val dictionaryId = this.normalizedRequestDictionaryId
val res = this.repositories.cardRepository(this.workMode).getAllCards(userId, dictionaryId)
this.postProcess(res)
}
onException {
fail(
runError(
operation = CardOperation.GET_ALL_CARDS,
fieldName = this.normalizedRequestDictionaryId.toFieldName(),
description = "exception",
exception = it
)
)
}
}
fun ChainDSL<CardContext>.processCardSearch() = worker {
this.name = "process card-search request"
test {
this.status == AppStatus.RUN
}
process {
this.postProcess(this.findCardDeck())
}
onException {
this.handleThrowable(CardOperation.SEARCH_CARDS, it)
}
}
fun ChainDSL<CardContext>.processCreateCard() = worker {
this.name = "process create-card request"
test {
this.status == AppStatus.RUN
}
process {
val userId = this.contextUserEntity.id
val res = this.repositories.cardRepository(this.workMode).createCard(userId, this.normalizedRequestCardEntity)
this.postProcess(res)
}
onException {
this.handleThrowable(CardOperation.CREATE_CARD, it)
}
}
fun ChainDSL<CardContext>.processUpdateCard() = worker {
this.name = "process update-card request"
test {
this.status == AppStatus.RUN
}
process {
val userId = this.contextUserEntity.id
val res = this.repositories.cardRepository(this.workMode).updateCard(userId, this.normalizedRequestCardEntity)
this.postProcess(res)
}
onException {
this.handleThrowable(CardOperation.UPDATE_CARD, it)
}
}
fun ChainDSL<CardContext>.processLearnCards() = worker {
this.name = "process learn-cards request"
test {
this.status == AppStatus.RUN
}
process {
this.postProcess(this.learnCards())
}
onException {
this.handleThrowable(CardOperation.LEARN_CARDS, it)
}
}
fun ChainDSL<CardContext>.processResetCards() = worker {
this.name = "process reset-cards request"
test {
this.status == AppStatus.RUN
}
process {
val userId = this.contextUserEntity.id
val res = this.repositories.cardRepository(this.workMode).resetCard(userId, this.normalizedRequestCardEntityId)
this.postProcess(res)
}
onException {
this.handleThrowable(CardOperation.RESET_CARD, it)
}
}
fun ChainDSL<CardContext>.processDeleteCard() = worker {
this.name = "process delete-card request"
test {
this.status == AppStatus.RUN
}
process {
val userId = this.contextUserEntity.id
val res = this.repositories.cardRepository(this.workMode).removeCard(userId, this.normalizedRequestCardEntityId)
this.postProcess(res)
}
onException {
this.handleThrowable(CardOperation.DELETE_CARD, it)
}
}
private suspend fun CardContext.postProcess(res: CardsDbResponse) {
check(res != CardsDbResponse.EMPTY) { "Null response" }
this.errors.addAll(res.errors)
val sourceLangByDictionary = res.dictionaries.associate { it.dictionaryId to it.sourceLang.langId }
val tts = this.repositories.ttsClientRepository(this.workMode)
this.responseCardEntityList = res.cards.map { card ->
val sourceLang = sourceLangByDictionary[card.dictionaryId] ?: return@map card
val words = card.words.map { word ->
val wordAudioId = tts.findResourceId(TTSResourceGet(word.word, sourceLang).normalize())
this.errors.addAll(wordAudioId.errors)
if (wordAudioId.id != TTSResourceId.NONE) {
word.copy(sound = wordAudioId.id)
} else {
word
}
}
val cardAudioString = card.words.joinToString(",") { it.word }
val cardAudioId = tts.findResourceId(TTSResourceGet(cardAudioString, sourceLang).normalize())
this.errors.addAll(cardAudioId.errors)
val cardSound = if (cardAudioId.id != TTSResourceId.NONE) {
cardAudioId.id
} else {
TTSResourceId.NONE
}
card.copy(words = words, sound = cardSound)
}
this.status = if (this.errors.isNotEmpty()) AppStatus.FAIL else AppStatus.RUN
}
private fun CardContext.postProcess(res: CardDbResponse) {
this.responseCardEntity = res.card
if (res.errors.isNotEmpty()) {
this.errors.addAll(res.errors)
}
this.status = if (this.errors.isNotEmpty()) AppStatus.FAIL else AppStatus.RUN
}
private fun CardContext.postProcess(res: RemoveCardDbResponse) {
if (res.errors.isNotEmpty()) {
this.errors.addAll(res.errors)
}
this.status = if (this.errors.isNotEmpty()) AppStatus.FAIL else AppStatus.RUN
} | 5 | Kotlin | 0 | 2 | 71acb1fdffe1d764f44d75c20df96f56629f4bdd | 6,429 | opentutor | Apache License 2.0 |
idea/src/main/kotlin/org/openpolicyagent/ideaplugin/ide/extensions/RegoModuleType.kt | open-policy-agent | 246,697,491 | false | {"Kotlin": 206314, "Open Policy Agent": 35784, "Shell": 12590, "Lex": 2811, "HTML": 108} | /*
* Use of this source code is governed by the MIT license that can be
* found in the LICENSE file.
*/
package org.openpolicyagent.ideaplugin.ide.extensions
import com.intellij.ide.util.projectWizard.ModuleWizardStep
import com.intellij.ide.util.projectWizard.WizardContext
import com.intellij.openapi.module.ModuleType
import com.intellij.openapi.module.ModuleTypeManager
import com.intellij.openapi.roots.ui.configuration.ModulesProvider
import org.openpolicyagent.ideaplugin.lang.RegoIcons
import javax.swing.Icon
class RegoModuleType : ModuleType<RegoModuleBuilder>("REGO_MODULE") {
override fun createModuleBuilder(): RegoModuleBuilder {
return RegoModuleBuilder()
}
override fun getName(): String {
return "Rego Project"
}
override fun getDescription(): String {
return "A Rego project is empty. Create a new Rego File to add."
}
override fun getNodeIcon(isOpened: Boolean): Icon {
return RegoIcons.OPA
}
override fun createWizardSteps(wizardContext: WizardContext, moduleBuilder: RegoModuleBuilder, modulesProvider: ModulesProvider): Array<ModuleWizardStep> {
return super.createWizardSteps(wizardContext, moduleBuilder, modulesProvider)
}
companion object {
private const val ID = "REGO_MODULE"
val INSTANCE: RegoModuleType by lazy { ModuleTypeManager.getInstance().findByID(
ID
) as RegoModuleType
}
}
} | 34 | Kotlin | 21 | 57 | f67f7a8c059889e6f2ef6be7f5cbbd0793023ecd | 1,458 | opa-idea-plugin | MIT License |
feature/settings/view/implementation/src/main/kotlin/com/savvasdalkitsis/uhuruphotos/feature/settings/view/implementation/ui/controller/SettingsViewStateController.kt | savvasdalkitsis | 485,908,521 | false | null | /*
Copyright 2022 <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.savvasdalkitsis.uhuruphotos.feature.settings.view.implementation.ui.controller
import androidx.annotation.StringRes
import androidx.compose.runtime.MutableState
import androidx.compose.runtime.mutableStateOf
import com.savvasdalkitsis.uhuruphotos.foundation.preferences.api.Preferences
import com.savvasdalkitsis.uhuruphotos.foundation.preferences.api.get
import com.savvasdalkitsis.uhuruphotos.foundation.preferences.api.set
import com.savvasdalkitsis.uhuruphotos.foundation.strings.api.R.string
import javax.inject.Inject
class SettingsViewStateController @Inject constructor(
private val preferences: Preferences,
) {
private val allGroups = mutableSetOf<SettingsGroupState>()
val ui = group(string.ui, "settings:group:ui")
val uiFeed = group(string.feed, "settings:group:ui:feed")
val uiTheme = group(string.theme, "settings:group:ui:theme")
val uiSearch = group(string.search, "settings:group:ui:search")
val uiLibrary = group(string.library, "settings:group:ui:library")
val uiMaps = group(string.maps, "settings:group:ui:maps")
val uiVideo = group(string.video, "settings:group:ui:video")
val privacy = group(string.privacy_security, "settings:group:privacy")
val privacyBiometrics = group(string.biometrics, "settings:group:privacy:biometrics")
val privacyShare = group(string.share, "settings:group:privacy:share")
val jobs = group(string.jobs, "settings:group:jobs")
val jobsFeedConfiguration = group(string.feed_sync_job_configuration, "settings:group:jobs:feedConfiguration")
val jobsStatus = group(string.status, "settings:group:jobs:status")
val advanced = group(string.advanced, "settings:group:advanced")
val advancedImageDiskCache = group(string.image_disk_cache, "settings:group:advanced:image:diskCache")
val advancedImageMemoryCache = group(string.image_memory_cache, "settings:group:advanced:image:memoryCache")
val advancedVideoDiskCache = group(string.video_disk_cache, "settings:group:advanced:video:diskCache")
val help = group(string.help, "settings:group:help")
val helpFeedback = group(string.feedback, "settings:group:help:feedback")
fun collapseAll() {
allGroups.forEach { it.collapse() }
}
fun expandAll() {
allGroups.forEach { it.expand() }
}
private fun group(
@StringRes title: Int,
key: String,
): SettingsGroupState = SettingsGroupState(title, preferencesState(key))
.also { allGroups += it }
private fun preferencesState(key: String) = object : MutableState<Boolean> {
private val state = mutableStateOf(preferences.get(key, true))
override var value: Boolean
get() = state.value
set(value) {
preferences.set(key, value)
state.value = value
}
override fun component1(): Boolean = value
override fun component2(): (Boolean) -> Unit = { value = it }
}
} | 70 | null | 26 | 358 | a1159f2236f66fe533f7ba785d47e4201e10424a | 3,520 | uhuruphotos-android | Apache License 2.0 |
analysis/analysis-test-framework/tests/org/jetbrains/kotlin/analysis/test/framework/services/KtTestProjectStructureProvider.kt | JetBrains | 3,432,266 | false | null | /*
* Copyright 2010-2023 JetBrains s.r.o. and Kotlin Programming Language contributors.
* Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file.
*/
package org.jetbrains.kotlin.analysis.test.framework.services
import com.intellij.openapi.project.Project
import com.intellij.psi.PsiElement
import com.intellij.psi.PsiFileSystemItem
import org.jetbrains.kotlin.analysis.api.standalone.base.project.structure.KtStaticProjectStructureProvider
import org.jetbrains.kotlin.analysis.project.structure.*
import org.jetbrains.kotlin.analysis.test.framework.project.structure.KtTestModuleProjectStructure
import org.jetbrains.kotlin.config.LanguageVersionSettings
import org.jetbrains.kotlin.psi.psiUtil.contains
import org.jetbrains.kotlin.serialization.deserialization.builtins.BuiltInSerializerProtocol
import org.jetbrains.kotlin.utils.KotlinExceptionWithAttachments
class KtTestProjectStructureProvider(
override val globalLanguageVersionSettings: LanguageVersionSettings,
private val builtinsModule: KtBuiltinsModule,
private val projectStructure: KtTestModuleProjectStructure,
) : KtStaticProjectStructureProvider() {
override fun getNotUnderContentRootModule(project: Project): KtNotUnderContentRootModule {
error("Not-under content root modules most be initialized explicitly in tests")
}
@OptIn(KtModuleStructureInternals::class)
override fun getModule(element: PsiElement, contextualModule: KtModule?): KtModule {
val containingFile = element.containingFile
val virtualFile = containingFile.virtualFile
if (virtualFile != null) {
if (virtualFile.extension == BuiltInSerializerProtocol.BUILTINS_FILE_EXTENSION) {
return builtinsModule
}
projectStructure.binaryModules
.firstOrNull { binaryModule -> virtualFile in binaryModule.contentScope }
?.let { return it }
}
computeSpecialModule(containingFile)?.let { return it }
return projectStructure.mainModules.firstOrNull { module ->
element in module.ktModule.contentScope
}?.ktModule
?: throw KotlinExceptionWithAttachments("Cannot find KtModule; see the attachment for more details.")
.withAttachment(
virtualFile?.path ?: containingFile.name,
allKtModules.joinToString(separator = System.lineSeparator()) { it.asDebugString() }
)
}
override val allKtModules: List<KtModule> = projectStructure.allKtModules()
override val allSourceFiles: List<PsiFileSystemItem> = projectStructure.allSourceFiles()
} | 180 | null | 5771 | 48,082 | 2742b94d9f4dbdb1064e65e05682cb2b0badf2fc | 2,703 | kotlin | Apache License 2.0 |
app/src/main/kotlin/org/jdc/template/prefs/DisplayThemeType.kt | AnthonyCAS | 200,759,833 | true | {"Kotlin": 159688, "Java": 912} | package org.jdc.template.prefs
enum class DisplayThemeType {
SYSTEM_DEFAULT,
LIGHT,
DARK;
}
| 0 | Kotlin | 0 | 0 | ce4a3a7ecab6452f18a6bc5298ebcc4f7377fd1c | 105 | android-template | Apache License 2.0 |
app/src/main/java/com/felixfavour/mobotithe/gui/view/onboarding/OnboardingWelcomeActivity.kt | felixfavour | 221,737,389 | false | null | package com.felixfavour.mobotithe.gui.view.onboarding
import android.annotation.SuppressLint
import android.content.Context
import android.content.Intent
import android.content.SharedPreferences
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.util.Log
import androidx.databinding.DataBindingUtil
import com.felixfavour.mobotithe.R
import com.felixfavour.mobotithe.databinding.OnboardingWelcomeActivityBinding
import com.felixfavour.mobotithe.gui.MainActivity
import com.felixfavour.mobotithe.gui.view.login.LoginActivity
import kotlinx.android.synthetic.main.onboarding_welcome_activity.*
class OnboardingWelcomeActivity : AppCompatActivity() {
private lateinit var binding: OnboardingWelcomeActivityBinding
companion object {
const val PREF = "my_preferences"
const val TAG = "OW Activity"
const val IS_FIRST_INSTALL = "firstInstall"
const val IS_USER_LOGGED_IN = "is_user_logged_in"
private lateinit var sharedPreferences: SharedPreferences
private lateinit var editor: SharedPreferences.Editor
private lateinit var activityIntent: Intent
}
@SuppressLint("CommitPrefEdits")
override fun onCreate(savedInstanceState: Bundle?) {
sharedPreferences = this.getSharedPreferences(PREF, Context.MODE_PRIVATE)
editor = sharedPreferences.edit()
super.onCreate(savedInstanceState)
Log.d(TAG, "OW Activity has been created")
binding = DataBindingUtil.inflate(layoutInflater, R.layout.onboarding_welcome_activity, container, false)
/*
Add Shared Preference to make onboarding screen to show only after installation
*/
if(sharedPreferences.getBoolean(IS_FIRST_INSTALL, true)) {
setContentView(binding.root)
editor.putBoolean(IS_FIRST_INSTALL, false)
editor.apply()
} else {
Log.d(TAG, "OW Activity has been abandoned")
navigateToActivity()
}
binding.goToLogin.setOnClickListener {
startActivity(Intent(applicationContext, LoginActivity::class.java))
}
binding.googleLogin.setOnClickListener {
startActivity(Intent(applicationContext, LoginActivity::class.java))
}
}
private fun navigateToActivity() {
sharedPreferences = this.getSharedPreferences(PREF, Context.MODE_PRIVATE)
if (sharedPreferences.getBoolean(IS_USER_LOGGED_IN, false)) {
activityIntent = Intent(applicationContext, MainActivity::class.java)
editor.putBoolean(IS_USER_LOGGED_IN, true)
finishAffinity()
} else {
activityIntent = Intent(applicationContext, LoginActivity::class.java)
finishAffinity()
}
startActivity(activityIntent)
}
} | 0 | Kotlin | 0 | 1 | 2678a1525f35e3d196c27d63cb9facce4d063e43 | 2,838 | Mobotithe | MIT License |
compiler/tests-spec/testData/diagnostics/linked/expressions/elvis-operator-expression/p-3/pos/1.1.fir.kt | JetBrains | 3,432,266 | false | null | // !LANGUAGE: +NewInference
// !DIAGNOSTICS: -UNREACHABLE_CODE -UNUSED_VARIABLE -ASSIGNED_BUT_NEVER_ACCESSED_VARIABLE -UNUSED_VALUE -UNUSED_PARAMETER -UNUSED_EXPRESSION
// SKIP_TXT
// TESTCASE NUMBER: 1
fun case1() {
val x = null ?: getNull()
<!DEBUG_INFO_EXPRESSION_TYPE("kotlin.Boolean?")!>x<!>
}
fun getNull(): Boolean? = null
// TESTCASE NUMBER: 2
fun case2() {
val x = A(mutableSetOf({ false }, { println("") })).b ?: false
<!DEBUG_INFO_EXPRESSION_TYPE("kotlin.Any")!>x<!>
}
class A(val b: Set<Any>? = null)
// TESTCASE NUMBER: 3
fun case3() {
val x = null?: throw Exception()
<!DEBUG_INFO_EXPRESSION_TYPE("kotlin.Nothing")!>x<!>
}
// TESTCASE NUMBER: 4
fun case4() {
val x = null <!USELESS_ELVIS_RIGHT_IS_NULL!>?: null<!>
<!DEBUG_INFO_EXPRESSION_TYPE("kotlin.Nothing?")!>x<!>
}
| 157 | null | 5563 | 44,965 | e6633d3d9214402fcf3585ae8c24213a4761cc8b | 823 | kotlin | Apache License 2.0 |
app/src/main/java/com/tanasi/streamflix/ui/PlayerSettingsView.kt | stantanasi | 511,319,545 | false | null | package com.tanasi.streamflix.ui
import android.content.Context
import android.content.res.ColorStateList
import android.content.res.Resources
import android.graphics.Color
import android.util.AttributeSet
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.constraintlayout.widget.ConstraintLayout
import androidx.core.content.ContextCompat
import androidx.media3.common.C
import androidx.media3.common.Player
import androidx.media3.common.TrackSelectionOverride
import androidx.media3.common.Tracks
import androidx.media3.common.util.UnstableApi
import androidx.media3.exoplayer.ExoPlayer
import androidx.media3.ui.CaptionStyleCompat
import androidx.media3.ui.DefaultTrackNameProvider
import androidx.media3.ui.SubtitleView
import androidx.recyclerview.widget.RecyclerView
import com.tanasi.streamflix.R
import com.tanasi.streamflix.databinding.ItemSettingBinding
import com.tanasi.streamflix.databinding.ViewPlayerSettingsBinding
import com.tanasi.streamflix.utils.UserPreferences
import com.tanasi.streamflix.utils.findClosest
import com.tanasi.streamflix.utils.getAlpha
import com.tanasi.streamflix.utils.getRgb
import com.tanasi.streamflix.utils.margin
import com.tanasi.streamflix.utils.mediaServerId
import com.tanasi.streamflix.utils.mediaServers
import com.tanasi.streamflix.utils.setAlpha
import com.tanasi.streamflix.utils.setRgb
import com.tanasi.streamflix.utils.trackFormats
import kotlin.math.roundToInt
@UnstableApi
class PlayerSettingsView @JvmOverloads constructor(
context: Context,
attrs: AttributeSet? = null,
defStyleAttr: Int = 0
) : ConstraintLayout(context, attrs, defStyleAttr) {
val binding = ViewPlayerSettingsBinding.inflate(
LayoutInflater.from(context),
this,
true
)
var player: ExoPlayer? = null
set(value) {
if (field === value) return
value?.let {
Settings.Server.init(it)
Settings.Quality.init(it, resources)
Settings.Subtitle.init(it, resources)
Settings.Speed.refresh(it)
}
value?.addListener(object : Player.Listener {
override fun onEvents(player: Player, events: Player.Events) {
if (events.contains(Player.EVENT_PLAYLIST_METADATA_CHANGED)) {
Settings.Server.init(value)
}
if (events.contains(Player.EVENT_MEDIA_ITEM_TRANSITION)) {
Settings.Server.refresh(value)
}
if (events.contains(Player.EVENT_TRACKS_CHANGED)) {
Settings.Quality.init(value, resources)
Settings.Subtitle.init(value, resources)
}
if (events.contains(Player.EVENT_PLAYBACK_PARAMETERS_CHANGED)) {
Settings.Speed.refresh(value)
}
}
})
field = value
}
var subtitleView: SubtitleView? = null
private var onServerSelected: ((Settings.Server) -> Unit)? = null
private var currentSettings = Setting.MAIN
private val settingsAdapter = SettingsAdapter(this, Settings.list)
private val qualityAdapter = SettingsAdapter(this, Settings.Quality.list)
private val subtitlesAdapter = SettingsAdapter(this, Settings.Subtitle.list)
private val captionStyleAdapter = SettingsAdapter(this, Settings.Subtitle.Style.list)
private val fontColorAdapter = SettingsAdapter(this, Settings.Subtitle.Style.FontColor.list)
private val textSizeAdapter = SettingsAdapter(this, Settings.Subtitle.Style.TextSize.list)
private val fontOpacityAdapter = SettingsAdapter(this, Settings.Subtitle.Style.FontOpacity.list)
private val edgeStyleAdapter = SettingsAdapter(this, Settings.Subtitle.Style.EdgeStyle.list)
private val backgroundColorAdapter = SettingsAdapter(this, Settings.Subtitle.Style.BackgroundColor.list)
private val backgroundOpacityAdapter = SettingsAdapter(this, Settings.Subtitle.Style.BackgroundOpacity.list)
private val windowColorAdapter = SettingsAdapter(this, Settings.Subtitle.Style.WindowColor.list)
private val windowOpacityAdapter = SettingsAdapter(this, Settings.Subtitle.Style.WindowOpacity.list)
private val speedAdapter = SettingsAdapter(this, Settings.Speed.list)
private val serversAdapter = SettingsAdapter(this, Settings.Server.list)
fun onBackPressed(): Boolean {
when (currentSettings) {
Setting.MAIN -> hide()
Setting.QUALITY,
Setting.SUBTITLES,
Setting.SPEED,
Setting.SERVERS -> displaySettings(Setting.MAIN)
Setting.CAPTION_STYLE -> displaySettings(Setting.SUBTITLES)
Setting.CAPTION_STYLE_FONT_COLOR,
Setting.CAPTION_STYLE_TEXT_SIZE,
Setting.CAPTION_STYLE_FONT_OPACITY,
Setting.CAPTION_STYLE_EDGE_STYLE,
Setting.CAPTION_STYLE_BACKGROUND_COLOR,
Setting.CAPTION_STYLE_BACKGROUND_OPACITY,
Setting.CAPTION_STYLE_WINDOW_COLOR,
Setting.CAPTION_STYLE_WINDOW_OPACITY -> displaySettings(Setting.CAPTION_STYLE)
}
return true
}
override fun focusSearch(focused: View, direction: Int): View {
return when {
binding.rvSettings.hasFocus() -> focused
else -> super.focusSearch(focused, direction)
}
}
fun show() {
this.visibility = View.VISIBLE
displaySettings(Setting.MAIN)
}
private fun displaySettings(setting: Setting) {
currentSettings = setting
binding.tvSettingsHeader.apply {
text = when (setting) {
Setting.MAIN -> context.getString(R.string.player_settings_title)
Setting.QUALITY -> context.getString(R.string.player_settings_quality_title)
Setting.SUBTITLES -> context.getString(R.string.player_settings_subtitles_title)
Setting.CAPTION_STYLE -> context.getString(R.string.player_settings_caption_style_title)
Setting.CAPTION_STYLE_FONT_COLOR -> context.getString(R.string.player_settings_caption_style_font_color_title)
Setting.CAPTION_STYLE_TEXT_SIZE -> context.getString(R.string.player_settings_caption_style_text_size_title)
Setting.CAPTION_STYLE_FONT_OPACITY -> context.getString(R.string.player_settings_caption_style_font_opacity_title)
Setting.CAPTION_STYLE_EDGE_STYLE -> context.getString(R.string.player_settings_caption_style_edge_style_title)
Setting.CAPTION_STYLE_BACKGROUND_COLOR -> context.getString(R.string.player_settings_caption_style_background_color_title)
Setting.CAPTION_STYLE_BACKGROUND_OPACITY -> context.getString(R.string.player_settings_caption_style_background_opacity_title)
Setting.CAPTION_STYLE_WINDOW_COLOR -> context.getString(R.string.player_settings_caption_style_window_color_title)
Setting.CAPTION_STYLE_WINDOW_OPACITY -> context.getString(R.string.player_settings_caption_style_window_opacity_title)
Setting.SPEED -> context.getString(R.string.player_settings_speed_title)
Setting.SERVERS -> context.getString(R.string.player_settings_servers_title)
}
}
binding.rvSettings.adapter = when (setting) {
Setting.MAIN -> settingsAdapter
Setting.QUALITY -> qualityAdapter
Setting.SUBTITLES -> subtitlesAdapter
Setting.CAPTION_STYLE -> captionStyleAdapter
Setting.CAPTION_STYLE_FONT_COLOR -> fontColorAdapter
Setting.CAPTION_STYLE_TEXT_SIZE -> textSizeAdapter
Setting.CAPTION_STYLE_FONT_OPACITY -> fontOpacityAdapter
Setting.CAPTION_STYLE_EDGE_STYLE -> edgeStyleAdapter
Setting.CAPTION_STYLE_BACKGROUND_COLOR -> backgroundColorAdapter
Setting.CAPTION_STYLE_BACKGROUND_OPACITY -> backgroundOpacityAdapter
Setting.CAPTION_STYLE_WINDOW_COLOR -> windowColorAdapter
Setting.CAPTION_STYLE_WINDOW_OPACITY -> windowOpacityAdapter
Setting.SPEED -> speedAdapter
Setting.SERVERS -> serversAdapter
}
binding.rvSettings.requestFocus()
}
fun hide() {
this.visibility = View.GONE
}
fun setOnServerSelected(onServerSelected: (server: Settings.Server) -> Unit) {
this.onServerSelected = onServerSelected
}
private enum class Setting {
MAIN,
QUALITY,
SUBTITLES,
CAPTION_STYLE,
CAPTION_STYLE_FONT_COLOR,
CAPTION_STYLE_TEXT_SIZE,
CAPTION_STYLE_FONT_OPACITY,
CAPTION_STYLE_EDGE_STYLE,
CAPTION_STYLE_BACKGROUND_COLOR,
CAPTION_STYLE_BACKGROUND_OPACITY,
CAPTION_STYLE_WINDOW_COLOR,
CAPTION_STYLE_WINDOW_OPACITY,
SPEED,
SERVERS,
}
private class SettingsAdapter(
private val settingsView: PlayerSettingsView,
private val items: List<Item>,
) : RecyclerView.Adapter<SettingViewHolder>() {
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int) =
SettingViewHolder(
settingsView,
ItemSettingBinding.inflate(
LayoutInflater.from(parent.context),
parent,
false
)
)
override fun onBindViewHolder(holder: SettingViewHolder, position: Int) {
holder.displaySettings(items[position])
}
override fun getItemCount() = items.size
}
private class SettingViewHolder(
private val settingsView: PlayerSettingsView,
val binding: ItemSettingBinding,
) : RecyclerView.ViewHolder(binding.root) {
fun displaySettings(item: Item) {
val player = settingsView.player ?: return
val subtitleView = settingsView.subtitleView ?: return
binding.root.apply {
when (item) {
Settings.Subtitle.Style,
Settings.Subtitle.Style.ResetStyle -> margin(bottom = 16F)
else -> margin(bottom = 0F)
}
setOnClickListener {
when (item) {
is Settings -> {
when (item) {
Settings.Quality -> settingsView.displaySettings(Setting.QUALITY)
Settings.Subtitle -> settingsView.displaySettings(Setting.SUBTITLES)
Settings.Speed -> settingsView.displaySettings(Setting.SPEED)
Settings.Server -> settingsView.displaySettings(Setting.SERVERS)
}
}
is Settings.Quality -> {
when (item) {
is Settings.Quality.Auto -> {
player.trackSelectionParameters = player.trackSelectionParameters
.buildUpon()
.setMaxVideoBitrate(Int.MAX_VALUE)
.setForceHighestSupportedBitrate(false)
.build()
settingsView.hide()
}
is Settings.Quality.VideoTrackInformation -> {
player.trackSelectionParameters = player.trackSelectionParameters
.buildUpon()
.setMaxVideoBitrate(item.bitrate)
.setForceHighestSupportedBitrate(true)
.build()
settingsView.hide()
}
}
}
is Settings.Subtitle -> {
when (item) {
Settings.Subtitle.Style -> {
settingsView.displaySettings(Setting.CAPTION_STYLE)
}
is Settings.Subtitle.None -> {
player.trackSelectionParameters = player.trackSelectionParameters
.buildUpon()
.clearOverridesOfType(C.TRACK_TYPE_TEXT)
.setIgnoredTextSelectionFlags(C.SELECTION_FLAG_FORCED.inv())
.build()
settingsView.hide()
}
is Settings.Subtitle.TextTrackInformation -> {
player.trackSelectionParameters = player.trackSelectionParameters
.buildUpon()
.setOverrideForType(
TrackSelectionOverride(
item.trackGroup.mediaTrackGroup,
listOf(item.trackIndex)
)
)
.setTrackTypeDisabled(item.trackGroup.type, false)
.build()
settingsView.hide()
}
}
}
is Settings.Subtitle.Style -> {
when (item) {
Settings.Subtitle.Style.ResetStyle -> {
UserPreferences.also {
it.captionTextSize = Settings.Subtitle.Style.TextSize.DEFAULT.value
it.captionStyle = Settings.Subtitle.Style.DEFAULT
}
subtitleView.also {
it.setFractionalTextSize(SubtitleView.DEFAULT_TEXT_SIZE_FRACTION * UserPreferences.captionTextSize)
it.setStyle(UserPreferences.captionStyle)
}
settingsView.hide()
}
Settings.Subtitle.Style.FontColor -> {
settingsView.displaySettings(Setting.CAPTION_STYLE_FONT_COLOR)
}
Settings.Subtitle.Style.TextSize -> {
settingsView.displaySettings(Setting.CAPTION_STYLE_TEXT_SIZE)
}
Settings.Subtitle.Style.FontOpacity -> {
settingsView.displaySettings(Setting.CAPTION_STYLE_FONT_OPACITY)
}
Settings.Subtitle.Style.EdgeStyle -> {
settingsView.displaySettings(Setting.CAPTION_STYLE_EDGE_STYLE)
}
Settings.Subtitle.Style.BackgroundColor -> {
settingsView.displaySettings(Setting.CAPTION_STYLE_BACKGROUND_COLOR)
}
Settings.Subtitle.Style.BackgroundOpacity -> {
settingsView.displaySettings(Setting.CAPTION_STYLE_BACKGROUND_OPACITY)
}
Settings.Subtitle.Style.WindowColor -> {
settingsView.displaySettings(Setting.CAPTION_STYLE_WINDOW_COLOR)
}
Settings.Subtitle.Style.WindowOpacity -> {
settingsView.displaySettings(Setting.CAPTION_STYLE_WINDOW_OPACITY)
}
}
}
is Settings.Subtitle.Style.FontColor -> {
UserPreferences.captionStyle = CaptionStyleCompat(
UserPreferences.captionStyle.foregroundColor.setRgb(item.color),
UserPreferences.captionStyle.backgroundColor,
UserPreferences.captionStyle.windowColor,
UserPreferences.captionStyle.edgeType,
UserPreferences.captionStyle.edgeColor,
null
)
subtitleView.setStyle(UserPreferences.captionStyle)
settingsView.displaySettings(Setting.CAPTION_STYLE)
}
is Settings.Subtitle.Style.TextSize -> {
UserPreferences.captionTextSize = item.value
subtitleView.setFractionalTextSize(SubtitleView.DEFAULT_TEXT_SIZE_FRACTION * UserPreferences.captionTextSize)
settingsView.displaySettings(Setting.CAPTION_STYLE)
}
is Settings.Subtitle.Style.FontOpacity -> {
UserPreferences.captionStyle = CaptionStyleCompat(
UserPreferences.captionStyle.foregroundColor.setAlpha(item.alpha),
UserPreferences.captionStyle.backgroundColor,
UserPreferences.captionStyle.windowColor,
UserPreferences.captionStyle.edgeType,
UserPreferences.captionStyle.edgeColor,
null
)
subtitleView.setStyle(UserPreferences.captionStyle)
settingsView.displaySettings(Setting.CAPTION_STYLE)
}
is Settings.Subtitle.Style.EdgeStyle -> {
UserPreferences.captionStyle = CaptionStyleCompat(
UserPreferences.captionStyle.foregroundColor,
UserPreferences.captionStyle.backgroundColor,
UserPreferences.captionStyle.windowColor,
item.type,
UserPreferences.captionStyle.edgeColor,
null
)
subtitleView.setStyle(UserPreferences.captionStyle)
settingsView.displaySettings(Setting.CAPTION_STYLE)
}
is Settings.Subtitle.Style.BackgroundColor -> {
UserPreferences.captionStyle = CaptionStyleCompat(
UserPreferences.captionStyle.foregroundColor,
UserPreferences.captionStyle.backgroundColor.setRgb(item.color),
UserPreferences.captionStyle.windowColor,
UserPreferences.captionStyle.edgeType,
UserPreferences.captionStyle.edgeColor,
null
)
subtitleView.setStyle(UserPreferences.captionStyle)
settingsView.displaySettings(Setting.CAPTION_STYLE)
}
is Settings.Subtitle.Style.BackgroundOpacity -> {
UserPreferences.captionStyle = CaptionStyleCompat(
UserPreferences.captionStyle.foregroundColor,
UserPreferences.captionStyle.backgroundColor.setAlpha(item.alpha),
UserPreferences.captionStyle.windowColor,
UserPreferences.captionStyle.edgeType,
UserPreferences.captionStyle.edgeColor,
null
)
subtitleView.setStyle(UserPreferences.captionStyle)
settingsView.displaySettings(Setting.CAPTION_STYLE)
}
is Settings.Subtitle.Style.WindowColor -> {
UserPreferences.captionStyle = CaptionStyleCompat(
UserPreferences.captionStyle.foregroundColor,
UserPreferences.captionStyle.backgroundColor,
UserPreferences.captionStyle.windowColor.setRgb(item.color),
UserPreferences.captionStyle.edgeType,
UserPreferences.captionStyle.edgeColor,
null
)
subtitleView.setStyle(UserPreferences.captionStyle)
settingsView.displaySettings(Setting.CAPTION_STYLE)
}
is Settings.Subtitle.Style.WindowOpacity -> {
UserPreferences.captionStyle = CaptionStyleCompat(
UserPreferences.captionStyle.foregroundColor,
UserPreferences.captionStyle.backgroundColor,
UserPreferences.captionStyle.windowColor.setAlpha(item.alpha),
UserPreferences.captionStyle.edgeType,
UserPreferences.captionStyle.edgeColor,
null
)
subtitleView.setStyle(UserPreferences.captionStyle)
settingsView.displaySettings(Setting.CAPTION_STYLE)
}
is Settings.Speed -> {
player.playbackParameters = player.playbackParameters
.withSpeed(item.value)
settingsView.hide()
}
is Settings.Server -> {
settingsView.onServerSelected?.invoke(item)
settingsView.hide()
}
}
}
}
binding.ivSettingIcon.apply {
when (item) {
is Settings -> {
when (item) {
Settings.Quality -> setImageDrawable(
ContextCompat.getDrawable(context, R.drawable.ic_settings_quality)
)
Settings.Subtitle -> setImageDrawable(
ContextCompat.getDrawable(
context,
when (Settings.Subtitle.selected) {
Settings.Subtitle.Style,
is Settings.Subtitle.None -> R.drawable.ic_settings_subtitle_off
is Settings.Subtitle.TextTrackInformation -> R.drawable.ic_settings_subtitle_on
}
)
)
Settings.Speed -> setImageDrawable(
ContextCompat.getDrawable(
context,
R.drawable.ic_settings_playback_speed
)
)
Settings.Server -> setImageDrawable(
ContextCompat.getDrawable(
context,
R.drawable.ic_settings_servers
)
)
}
visibility = View.VISIBLE
}
else -> {
visibility = View.GONE
}
}
}
binding.vSettingColor.apply {
when (item) {
is Settings.Subtitle.Style.FontColor -> {
backgroundTintList = ColorStateList.valueOf(item.color)
visibility = View.VISIBLE
}
is Settings.Subtitle.Style.BackgroundColor -> {
backgroundTintList = ColorStateList.valueOf(item.color)
visibility = View.VISIBLE
}
is Settings.Subtitle.Style.WindowColor -> {
backgroundTintList = ColorStateList.valueOf(item.color)
visibility = View.VISIBLE
}
else -> {
visibility = View.GONE
}
}
}
binding.tvSettingMainText.apply {
text = when (item) {
is Settings -> when (item) {
Settings.Quality -> context.getString(R.string.player_settings_quality_label)
Settings.Subtitle -> context.getString(R.string.player_settings_subtitles_label)
Settings.Speed -> context.getString(R.string.player_settings_speed_label)
Settings.Server -> context.getString(R.string.player_settings_servers_label)
}
is Settings.Quality -> when (item) {
is Settings.Quality.Auto -> when {
item.isSelected -> when (val track = item.currentTrack) {
null -> context.getString(R.string.player_settings_quality_auto)
else -> context.getString(
R.string.player_settings_quality_auto_selected,
track.height
)
}
else -> context.getString(R.string.player_settings_quality_auto)
}
is Settings.Quality.VideoTrackInformation -> context.getString(
R.string.player_settings_quality,
item.height
)
}
is Settings.Subtitle -> when (item) {
Settings.Subtitle.Style -> context.getString(R.string.player_settings_caption_style_label)
is Settings.Subtitle.None -> context.getString(R.string.player_settings_subtitles_off)
is Settings.Subtitle.TextTrackInformation -> item.name
}
is Settings.Subtitle.Style -> when (item) {
Settings.Subtitle.Style.ResetStyle -> context.getString(R.string.player_settings_caption_style_reset_style_label)
Settings.Subtitle.Style.FontColor -> context.getString(R.string.player_settings_caption_style_font_color_label)
Settings.Subtitle.Style.TextSize -> context.getString(R.string.player_settings_caption_style_text_size_label)
Settings.Subtitle.Style.FontOpacity -> context.getString(R.string.player_settings_caption_style_font_opacity_label)
Settings.Subtitle.Style.EdgeStyle -> context.getString(R.string.player_settings_caption_style_edge_style_label)
Settings.Subtitle.Style.BackgroundColor -> context.getString(R.string.player_settings_caption_style_background_color_label)
Settings.Subtitle.Style.BackgroundOpacity -> context.getString(R.string.player_settings_caption_style_background_opacity_label)
Settings.Subtitle.Style.WindowColor -> context.getString(R.string.player_settings_caption_style_window_color_label)
Settings.Subtitle.Style.WindowOpacity -> context.getString(R.string.player_settings_caption_style_window_opacity_label)
}
is Settings.Subtitle.Style.FontColor -> context.getString(item.stringId)
is Settings.Subtitle.Style.TextSize -> context.getString(item.stringId)
is Settings.Subtitle.Style.FontOpacity -> context.getString(item.stringId)
is Settings.Subtitle.Style.EdgeStyle -> context.getString(item.stringId)
is Settings.Subtitle.Style.BackgroundColor -> context.getString(item.stringId)
is Settings.Subtitle.Style.BackgroundOpacity -> context.getString(item.stringId)
is Settings.Subtitle.Style.WindowColor -> context.getString(item.stringId)
is Settings.Subtitle.Style.WindowOpacity -> context.getString(item.stringId)
is Settings.Speed -> context.getString(item.stringId)
is Settings.Server -> item.name
else -> ""
}
}
binding.tvSettingSubText.apply {
text = when (item) {
is Settings -> when (item) {
Settings.Quality -> when (val selected = Settings.Quality.selected) {
is Settings.Quality.Auto -> when (val track = selected.currentTrack) {
null -> context.getString(R.string.player_settings_quality_auto)
else -> context.getString(
R.string.player_settings_quality_auto_selected,
track.height
)
}
is Settings.Quality.VideoTrackInformation -> context.getString(
R.string.player_settings_quality,
selected.height
)
}
Settings.Subtitle -> when (val selected = Settings.Subtitle.selected) {
Settings.Subtitle.Style,
is Settings.Subtitle.None -> context.getString(R.string.player_settings_subtitles_off)
is Settings.Subtitle.TextTrackInformation -> selected.name
}
Settings.Speed -> context.getString(Settings.Speed.selected.stringId)
Settings.Server -> Settings.Server.selected?.name ?: ""
}
is Settings.Subtitle -> when (item) {
Settings.Subtitle.Style -> context.getString(R.string.player_settings_caption_style_sub_label)
else -> ""
}
is Settings.Subtitle.Style -> when (item) {
Settings.Subtitle.Style.ResetStyle -> ""
Settings.Subtitle.Style.FontColor -> context.getString(Settings.Subtitle.Style.FontColor.selected.stringId)
Settings.Subtitle.Style.TextSize -> context.getString(Settings.Subtitle.Style.TextSize.selected.stringId)
Settings.Subtitle.Style.FontOpacity -> context.getString(Settings.Subtitle.Style.FontOpacity.selected.stringId)
Settings.Subtitle.Style.EdgeStyle -> context.getString(Settings.Subtitle.Style.EdgeStyle.selected.stringId)
Settings.Subtitle.Style.BackgroundColor -> context.getString(Settings.Subtitle.Style.BackgroundColor.selected.stringId)
Settings.Subtitle.Style.BackgroundOpacity -> context.getString(Settings.Subtitle.Style.BackgroundOpacity.selected.stringId)
Settings.Subtitle.Style.WindowColor -> context.getString(Settings.Subtitle.Style.WindowColor.selected.stringId)
Settings.Subtitle.Style.WindowOpacity -> context.getString(Settings.Subtitle.Style.WindowOpacity.selected.stringId)
}
else -> ""
}
visibility = when {
text.isEmpty() -> View.GONE
else -> View.VISIBLE
}
}
binding.ivSettingIsSelected.apply {
visibility = when (item) {
is Settings.Quality -> when {
item.isSelected -> View.VISIBLE
else -> View.GONE
}
is Settings.Subtitle -> when (item) {
Settings.Subtitle.Style -> View.GONE
is Settings.Subtitle.None -> when {
item.isSelected -> View.VISIBLE
else -> View.GONE
}
is Settings.Subtitle.TextTrackInformation -> when {
item.isSelected -> View.VISIBLE
else -> View.GONE
}
}
is Settings.Subtitle.Style.FontColor -> when {
item.isSelected -> View.VISIBLE
else -> View.GONE
}
is Settings.Subtitle.Style.TextSize -> when {
item.isSelected -> View.VISIBLE
else -> View.GONE
}
is Settings.Subtitle.Style.FontOpacity -> when {
item.isSelected -> View.VISIBLE
else -> View.GONE
}
is Settings.Subtitle.Style.EdgeStyle -> when {
item.isSelected -> View.VISIBLE
else -> View.GONE
}
is Settings.Subtitle.Style.BackgroundColor -> when {
item.isSelected -> View.VISIBLE
else -> View.GONE
}
is Settings.Subtitle.Style.BackgroundOpacity -> when {
item.isSelected -> View.VISIBLE
else -> View.GONE
}
is Settings.Subtitle.Style.WindowColor -> when {
item.isSelected -> View.VISIBLE
else -> View.GONE
}
is Settings.Subtitle.Style.WindowOpacity -> when {
item.isSelected -> View.VISIBLE
else -> View.GONE
}
is Settings.Speed -> when {
item.isSelected -> View.VISIBLE
else -> View.GONE
}
is Settings.Server -> when {
item.isSelected -> View.VISIBLE
else -> View.GONE
}
else -> View.GONE
}
}
binding.ivSettingEnter.apply {
visibility = when (item) {
is Settings -> View.VISIBLE
is Settings.Subtitle -> when (item) {
Settings.Subtitle.Style -> View.VISIBLE
is Settings.Subtitle.None -> View.GONE
is Settings.Subtitle.TextTrackInformation -> View.GONE
}
is Settings.Subtitle.Style -> when (item) {
Settings.Subtitle.Style.ResetStyle -> View.GONE
else -> View.VISIBLE
}
else -> View.GONE
}
}
}
}
private interface Item
sealed class Settings : Item {
companion object {
val list = listOf(
Quality,
Subtitle,
Speed,
Server,
)
}
sealed class Quality : Item {
companion object : Settings() {
val list = mutableListOf<Quality>()
val selected: Quality
get() = list.find { it.isSelected } ?: Auto
fun init(player: ExoPlayer, resources: Resources) {
list.clear()
list.add(Auto)
list.addAll(
player.currentTracks.groups
.filter { it.type == C.TRACK_TYPE_VIDEO }
.flatMap { trackGroup ->
trackGroup.trackFormats
.filter { it.selectionFlags and C.SELECTION_FLAG_FORCED == 0 }
.distinctBy { it.width to it.height }
.map { trackFormat ->
VideoTrackInformation(
name = DefaultTrackNameProvider(resources)
.getTrackName(trackFormat),
width = trackFormat.width,
height = trackFormat.height,
bitrate = trackFormat.bitrate,
player = player,
)
}
}
.sortedByDescending { it.height }
)
}
}
abstract val isSelected: Boolean
object Auto : Quality() {
val currentTrack: VideoTrackInformation?
get() = list
.filterIsInstance<VideoTrackInformation>()
.find { it.isCurrentlyPlayed }
override val isSelected: Boolean
get() = list
.filterIsInstance<VideoTrackInformation>()
.none { it.isSelected }
}
class VideoTrackInformation(
val name: String,
val width: Int,
val height: Int,
val bitrate: Int,
val player: ExoPlayer,
) : Quality() {
val isCurrentlyPlayed: Boolean
get() = player.videoFormat?.let { it.bitrate == bitrate } ?: false
override val isSelected: Boolean
get() = player.trackSelectionParameters.maxVideoBitrate == bitrate
}
}
sealed class Subtitle : Item {
companion object : Settings() {
val list = mutableListOf<Subtitle>()
val selected: Subtitle
get() = list.find {
when (it) {
is None -> it.isSelected
is TextTrackInformation -> it.isSelected
else -> false
}
} ?: None
fun init(player: ExoPlayer, resources: Resources) {
list.clear()
list.add(Style)
list.add(None)
list.addAll(
player.currentTracks.groups
.filter { it.type == C.TRACK_TYPE_TEXT }
.flatMap { trackGroup ->
trackGroup.trackFormats
.filter { it.selectionFlags and C.SELECTION_FLAG_FORCED == 0 }
.filter { it.label != null }
.mapIndexed { trackIndex, trackFormat ->
TextTrackInformation(
name = DefaultTrackNameProvider(resources)
.getTrackName(trackFormat),
trackGroup = trackGroup,
trackIndex = trackIndex,
)
}
}
.sortedBy { it.name }
)
}
}
sealed class Style : Item {
companion object : Subtitle() {
val DEFAULT = CaptionStyleCompat(
Color.WHITE,
Color.BLACK.setAlpha(128),
Color.TRANSPARENT,
CaptionStyleCompat.EDGE_TYPE_NONE,
Color.BLACK,
null
)
val list = listOf(
ResetStyle,
FontColor,
TextSize,
FontOpacity,
EdgeStyle,
BackgroundColor,
BackgroundOpacity,
WindowColor,
WindowOpacity,
)
}
object ResetStyle : Style()
class FontColor(
val stringId: Int,
val color: Int,
) : Item {
val isSelected: Boolean
get() = color == UserPreferences.captionStyle.foregroundColor.getRgb()
companion object : Style() {
private val DEFAULT = FontColor(
R.string.player_settings_caption_style_font_color_white,
Color.WHITE
)
val list = listOf(
DEFAULT,
FontColor(
R.string.player_settings_caption_style_font_color_yellow,
Color.YELLOW
),
FontColor(
R.string.player_settings_caption_style_font_color_green,
Color.GREEN
),
FontColor(
R.string.player_settings_caption_style_font_color_cyan,
Color.CYAN
),
FontColor(
R.string.player_settings_caption_style_font_color_blue,
Color.BLUE
),
FontColor(
R.string.player_settings_caption_style_font_color_magenta,
Color.MAGENTA
),
FontColor(
R.string.player_settings_caption_style_font_color_red,
Color.RED
),
FontColor(
R.string.player_settings_caption_style_font_color_black,
Color.BLACK
),
)
val selected: FontColor
get() = list.find { it.isSelected } ?: DEFAULT
}
}
class TextSize(
val stringId: Int,
val value: Float,
) : Item {
val isSelected: Boolean
get() = value == UserPreferences.captionTextSize
companion object : Style() {
val DEFAULT = TextSize(R.string.player_settings_caption_style_text_size_1, 1F)
val list = listOf(
TextSize(R.string.player_settings_caption_style_text_size_0_5, 0.5F),
TextSize(R.string.player_settings_caption_style_text_size_0_75, 0.75F),
DEFAULT,
TextSize(R.string.player_settings_caption_style_text_size_2, 2F),
TextSize(R.string.player_settings_caption_style_text_size_3, 3F),
)
val selected: TextSize
get() = list.find { it.isSelected } ?: DEFAULT
}
}
class FontOpacity(
val stringId: Int,
private val value: Float,
) : Item {
val alpha: Int
get() = (value * 255).roundToInt()
val isSelected: Boolean
get() = alpha == UserPreferences.captionStyle.foregroundColor.getAlpha()
companion object : Style() {
private val DEFAULT = FontOpacity(
R.string.player_settings_caption_style_font_opacity_1,
1F
)
val list = listOf(
FontOpacity(
R.string.player_settings_caption_style_font_opacity_0_5,
0.5F
),
FontOpacity(
R.string.player_settings_caption_style_font_opacity_0_75,
0.75F
),
DEFAULT,
)
val selected: FontOpacity
get() = list.find { it.isSelected } ?: DEFAULT
}
}
class EdgeStyle(
val stringId: Int,
val type: Int,
) : Item {
val isSelected: Boolean
get() = type == UserPreferences.captionStyle.edgeType
companion object : Style() {
private val DEFAULT = EdgeStyle(
R.string.player_settings_caption_style_edge_style_none,
CaptionStyleCompat.EDGE_TYPE_NONE
)
val list = listOf(
DEFAULT,
EdgeStyle(
R.string.player_settings_caption_style_edge_style_raised,
CaptionStyleCompat.EDGE_TYPE_RAISED
),
EdgeStyle(
R.string.player_settings_caption_style_edge_style_depressed,
CaptionStyleCompat.EDGE_TYPE_DEPRESSED
),
EdgeStyle(
R.string.player_settings_caption_style_edge_style_outline,
CaptionStyleCompat.EDGE_TYPE_OUTLINE
),
EdgeStyle(
R.string.player_settings_caption_style_edge_style_drop_shadow,
CaptionStyleCompat.EDGE_TYPE_DROP_SHADOW
),
)
val selected: EdgeStyle
get() = list.find { it.isSelected } ?: DEFAULT
}
}
class BackgroundColor(
val stringId: Int,
val color: Int,
) : Item {
val isSelected: Boolean
get() = color == UserPreferences.captionStyle.backgroundColor.getRgb()
companion object : Style() {
private val DEFAULT = BackgroundColor(
R.string.player_settings_caption_style_background_color_black,
Color.BLACK
)
val list = listOf(
DEFAULT,
BackgroundColor(
R.string.player_settings_caption_style_background_color_yellow,
Color.YELLOW
),
BackgroundColor(
R.string.player_settings_caption_style_background_color_green,
Color.GREEN
),
BackgroundColor(
R.string.player_settings_caption_style_background_color_cyan,
Color.CYAN
),
BackgroundColor(
R.string.player_settings_caption_style_background_color_blue,
Color.BLUE
),
BackgroundColor(
R.string.player_settings_caption_style_background_color_magenta,
Color.MAGENTA
),
BackgroundColor(
R.string.player_settings_caption_style_background_color_red,
Color.RED
),
BackgroundColor(
R.string.player_settings_caption_style_background_color_white,
Color.WHITE
),
)
val selected: BackgroundColor
get() = list.find { it.isSelected } ?: DEFAULT
}
}
class BackgroundOpacity(
val stringId: Int,
private val value: Float,
) : Item {
val alpha: Int
get() = (value * 255).roundToInt()
val isSelected: Boolean
get() = alpha == UserPreferences.captionStyle.backgroundColor.getAlpha()
companion object : Style() {
private val DEFAULT = BackgroundOpacity(
R.string.player_settings_caption_style_background_opacity_0_5,
0.5F
)
val list = listOf(
BackgroundOpacity(
R.string.player_settings_caption_style_background_opacity_0,
0F
),
BackgroundOpacity(
R.string.player_settings_caption_style_background_opacity_0_25,
0.25F
),
DEFAULT,
BackgroundOpacity(
R.string.player_settings_caption_style_background_opacity_0_75,
0.75F
),
BackgroundOpacity(
R.string.player_settings_caption_style_background_opacity_1,
1F
),
)
val selected: BackgroundOpacity
get() = list.find { it.isSelected } ?: DEFAULT
}
}
class WindowColor(
val stringId: Int,
val color: Int,
) : Item {
val isSelected: Boolean
get() = color == UserPreferences.captionStyle.windowColor.getRgb()
companion object : Style() {
private val DEFAULT = WindowColor(
R.string.player_settings_caption_style_window_color_black,
Color.BLACK
)
val list = listOf(
DEFAULT,
WindowColor(
R.string.player_settings_caption_style_window_color_yellow,
Color.YELLOW
),
WindowColor(
R.string.player_settings_caption_style_window_color_green,
Color.GREEN
),
WindowColor(
R.string.player_settings_caption_style_window_color_cyan,
Color.CYAN
),
WindowColor(
R.string.player_settings_caption_style_window_color_blue,
Color.BLUE
),
WindowColor(
R.string.player_settings_caption_style_window_color_magenta,
Color.MAGENTA
),
WindowColor(
R.string.player_settings_caption_style_window_color_red,
Color.RED
),
WindowColor(
R.string.player_settings_caption_style_window_color_white,
Color.WHITE
),
)
val selected: WindowColor
get() = list.find { it.isSelected } ?: DEFAULT
}
}
class WindowOpacity(
val stringId: Int,
private val value: Float,
) : Item {
val alpha: Int
get() = (value * 255).roundToInt()
val isSelected: Boolean
get() = alpha == UserPreferences.captionStyle.windowColor.getAlpha()
companion object : Style() {
private val DEFAULT = WindowOpacity(
R.string.player_settings_caption_style_window_opacity_0,
0F
)
val list = listOf(
DEFAULT,
WindowOpacity(
R.string.player_settings_caption_style_window_opacity_0_25,
0.25F
),
WindowOpacity(
R.string.player_settings_caption_style_window_opacity_0_5,
0.5F
),
WindowOpacity(
R.string.player_settings_caption_style_window_opacity_0_75,
0.75F
),
WindowOpacity(
R.string.player_settings_caption_style_window_opacity_1,
1F
),
)
val selected: WindowOpacity
get() = list.find { it.isSelected } ?: DEFAULT
}
}
}
object None : Subtitle() {
val isSelected: Boolean
get() = list
.filterIsInstance<TextTrackInformation>()
.none { it.isSelected }
}
class TextTrackInformation(
val name: String,
val trackGroup: Tracks.Group,
val trackIndex: Int,
) : Subtitle() {
val isSelected: Boolean
get() = trackGroup.isTrackSelected(trackIndex)
}
}
class Speed(
val stringId: Int,
val value: Float,
) : Item {
var isSelected: Boolean = false
companion object : Settings() {
private val DEFAULT = Speed(R.string.player_settings_speed_1, 1F)
val list = listOf(
Speed(R.string.player_settings_speed_0_25, 0.25F),
Speed(R.string.player_settings_speed_0_5, 0.5F),
Speed(R.string.player_settings_speed_0_75, 0.75F),
DEFAULT,
Speed(R.string.player_settings_speed_1_25, 1.25F),
Speed(R.string.player_settings_speed_1_5, 1.5F),
Speed(R.string.player_settings_speed_1_75, 1.75F),
Speed(R.string.player_settings_speed_2, 2F),
)
val selected: Speed
get() = list.find { it.isSelected }
?: list.find { it.value == 1F }
?: DEFAULT
fun refresh(player: ExoPlayer) {
list.forEach { it.isSelected = false }
list.findClosest(player.playbackParameters.speed) { it.value }?.let {
it.isSelected = true
}
}
}
}
class Server(
val id: String,
val name: String,
) : Item {
var isSelected: Boolean = false
companion object : Settings() {
val list = mutableListOf<Server>()
val selected: Server?
get() = list.find { it.isSelected }
fun init(player: ExoPlayer) {
list.clear()
list.addAll(player.playlistMetadata.mediaServers.map {
Server(
id = it.id,
name = it.name,
)
})
list.firstOrNull()?.isSelected = true
}
fun refresh(player: ExoPlayer) {
list.forEach {
it.isSelected = (it.id == player.mediaMetadata.mediaServerId)
}
}
}
}
}
} | 39 | null | 52 | 93 | c9255fe9ee2ef3ed8bfbeef567950f1a63a51752 | 59,110 | streamflix | Apache License 2.0 |
shared/src/commonMain/kotlin/com/aglushkov/wordteacher/shared/features/definitions/vm/DefinitionsVM.kt | soniccat | 302,971,014 | false | null | package com.aglushkov.wordteacher.shared.features.definitions.vm
import dev.icerock.moko.resources.desc.Resource
import dev.icerock.moko.resources.desc.StringDesc
import com.aglushkov.wordteacher.shared.events.Event
import com.aglushkov.wordteacher.shared.features.cardsets.vm.CardSetViewItem
import com.aglushkov.wordteacher.shared.features.cardsets.vm.CreateCardSetViewItem
import com.aglushkov.wordteacher.shared.general.*
import com.aglushkov.wordteacher.shared.general.connectivity.ConnectivityManager
import com.aglushkov.wordteacher.shared.general.extensions.forward
import com.aglushkov.wordteacher.shared.general.item.BaseViewItem
import com.aglushkov.wordteacher.shared.general.item.generateViewItemIds
import com.aglushkov.wordteacher.shared.general.resource.Resource
import com.aglushkov.wordteacher.shared.general.resource.getErrorString
import com.aglushkov.wordteacher.shared.general.resource.isLoaded
import com.aglushkov.wordteacher.shared.model.ShortCardSet
import com.aglushkov.wordteacher.shared.model.WordTeacherDefinition
import com.aglushkov.wordteacher.shared.model.WordTeacherWord
import com.aglushkov.wordteacher.shared.model.toStringDesc
import com.aglushkov.wordteacher.shared.repository.cardset.CardSetsRepository
import com.aglushkov.wordteacher.shared.repository.config.Config
import com.aglushkov.wordteacher.shared.repository.worddefinition.WordDefinitionRepository
import com.aglushkov.wordteacher.shared.res.MR
import com.arkivanov.essenty.parcelable.Parcelable
import com.arkivanov.essenty.parcelable.Parcelize
import kotlinx.coroutines.CoroutineExceptionHandler
import kotlinx.coroutines.Job
import kotlinx.coroutines.channels.Channel
import kotlinx.coroutines.delay
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.SharingStarted
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.combine
import kotlinx.coroutines.flow.map
import kotlinx.coroutines.flow.receiveAsFlow
import kotlinx.coroutines.flow.stateIn
import kotlinx.coroutines.launch
interface DefinitionsVM {
fun restore(newState: State)
fun onWordSubmitted(word: String?, filter: List<WordTeacherWord.PartOfSpeech> = emptyList())
fun onTryAgainClicked()
fun onPartOfSpeechFilterUpdated(filter: List<WordTeacherWord.PartOfSpeech>)
fun onPartOfSpeechFilterClicked(item: DefinitionsDisplayModeViewItem)
fun onPartOfSpeechFilterCloseClicked(item: DefinitionsDisplayModeViewItem)
fun onDisplayModeChanged(mode: DefinitionsDisplayMode)
fun getErrorText(res: Resource<*>): StringDesc?
val state: State
val definitions: StateFlow<Resource<List<BaseViewItem<*>>>>
val displayModeStateFlow: StateFlow<DefinitionsDisplayMode>
val partsOfSpeechFilterStateFlow: StateFlow<List<WordTeacherWord.PartOfSpeech>>
val selectedPartsOfSpeechStateFlow: StateFlow<List<WordTeacherWord.PartOfSpeech>>
val eventFlow: Flow<Event>
// Card Sets
val cardSets: StateFlow<Resource<List<BaseViewItem<*>>>>
fun onOpenCardSets(item: OpenCardSetViewItem)
fun onAddDefinitionInSet(wordDefinitionViewItem: WordDefinitionViewItem, cardSetViewItem: CardSetViewItem)
@Parcelize
class State(
var word: String? = null
): Parcelable
}
open class DefinitionsVMImpl(
override var state: DefinitionsVM.State,
private val router: DefinitionsRouter,
private val connectivityManager: ConnectivityManager,
private val wordDefinitionRepository: WordDefinitionRepository,
private val cardSetsRepository: CardSetsRepository,
private val idGenerator: IdGenerator
): ViewModel(), DefinitionsVM {
private val eventChannel = Channel<Event>(Channel.BUFFERED)
override val eventFlow = eventChannel.receiveAsFlow()
private val definitionWords = MutableStateFlow<Resource<List<WordTeacherWord>>>(Resource.Uninitialized())
final override var displayModeStateFlow = MutableStateFlow(DefinitionsDisplayMode.BySource)
final override var selectedPartsOfSpeechStateFlow = MutableStateFlow<List<WordTeacherWord.PartOfSpeech>>(emptyList())
override val definitions = combine(
definitionWords,
displayModeStateFlow,
selectedPartsOfSpeechStateFlow
) { a, b, c -> Triple(a, b, c) }
.map { (wordDefinitions, displayMode, partOfSpeechFilter) ->
Logger.v("build view items ${wordDefinitions.data()?.size ?: 0}")
wordDefinitions.copyWith(
buildViewItems(wordDefinitions.data().orEmpty(), displayMode, partOfSpeechFilter)
)
}.stateIn(viewModelScope, SharingStarted.Eagerly, Resource.Uninitialized())
override val partsOfSpeechFilterStateFlow = definitionWords.map {
it.data().orEmpty().map { word ->
word.definitions.keys
}.flatten().distinct()
}.stateIn(viewModelScope, SharingStarted.Eagerly, emptyList())
private val displayModes = listOf(DefinitionsDisplayMode.BySource, DefinitionsDisplayMode.Merged)
private var loadJob: Job? = null
private var word: String?
get() {
return state.word
}
set(value) {
state.word = value
}
override fun restore(newState: DefinitionsVM.State) {
state = newState
word?.let {
loadIfNeeded(it)
} ?: run {
word = "owl"
loadIfNeeded("owl")
}
}
override fun onCleared() {
super.onCleared()
eventChannel.cancel()
}
// Events
override fun onWordSubmitted(word: String?, filter: List<WordTeacherWord.PartOfSpeech>) {
selectedPartsOfSpeechStateFlow.value = filter
if (word == null) {
this.word = null
} else if (word.isNotEmpty()) {
loadIfNeeded(word)
}
}
override fun onPartOfSpeechFilterUpdated(filter: List<WordTeacherWord.PartOfSpeech>) {
selectedPartsOfSpeechStateFlow.value = filter
}
override fun onPartOfSpeechFilterClicked(item: DefinitionsDisplayModeViewItem) {
viewModelScope.launch {
eventChannel.offer(
ShowPartsOfSpeechFilterDialogEvent(
selectedPartsOfSpeechStateFlow.value,
partsOfSpeechFilterStateFlow.value
)
)
}
}
override fun onPartOfSpeechFilterCloseClicked(item: DefinitionsDisplayModeViewItem) {
selectedPartsOfSpeechStateFlow.value = emptyList()
}
override fun onDisplayModeChanged(mode: DefinitionsDisplayMode) {
if (displayModeStateFlow.value == mode) return
displayModeStateFlow.value = mode
}
override fun onTryAgainClicked() {
loadIfNeeded(word!!)
}
// Actions
private fun loadIfNeeded(word: String) {
this.word = word
val stateFlow = wordDefinitionRepository.obtainStateFlow(word)
if (stateFlow.value.isLoaded()) {
definitionWords.value = if (definitionWords.value != stateFlow.value) {
stateFlow.value
} else {
// HACK: copy to trigger flow event
stateFlow.value.copy()
}
} else {
load(word)
}
}
private fun load(word: String) {
val tag = "DefinitionsVM.load"
Logger.v("Start Loading $word", tag)
loadJob?.cancel()
loadJob = viewModelScope.launch(CoroutineExceptionHandler { _, e ->
Logger.e("Load Word exception for $word ${e.message}", tag)
}) {
wordDefinitionRepository.define(word, false).forward(definitionWords)
Logger.v("Finish Loading $word", tag)
}
}
private fun buildViewItems(
words: List<WordTeacherWord>,
displayMode: DefinitionsDisplayMode,
partsOfSpeechFilter: List<WordTeacherWord.PartOfSpeech>
): List<BaseViewItem<*>> {
val items = mutableListOf<BaseViewItem<*>>()
if (words.isNotEmpty()) {
items.add(DefinitionsDisplayModeViewItem(
getPartOfSpeechChipText(partsOfSpeechFilter),
partsOfSpeechFilter.isNotEmpty(),
displayModes,
displayModes.indexOf(displayMode)
))
items.add(WordDividerViewItem())
}
when (displayMode) {
DefinitionsDisplayMode.Merged -> addMergedWords(words, partsOfSpeechFilter, items)
else -> addWordsGroupedBySource(words, partsOfSpeechFilter, items)
}
generateIds(items)
return items
}
private fun getPartOfSpeechChipText(
partOfSpeechFilter: List<WordTeacherWord.PartOfSpeech>,
): StringDesc {
return if (partOfSpeechFilter.isEmpty()) {
StringDesc.Resource(MR.strings.definitions_add_filter)
} else {
val firstFilter = partOfSpeechFilter.first()
firstFilter.toStringDesc()
}
}
private fun generateIds(items: MutableList<BaseViewItem<*>>) {
generateViewItemIds(items, definitions.value.data().orEmpty(), idGenerator)
}
private fun addMergedWords(
words: List<WordTeacherWord>,
partsOfSpeechFilter: List<WordTeacherWord.PartOfSpeech>,
items: MutableList<BaseViewItem<*>>
) {
val word = mergeWords(words, partsOfSpeechFilter)
addWordViewItems(word, partsOfSpeechFilter, items)
items.add(WordDividerViewItem())
}
private fun addWordsGroupedBySource(
words: List<WordTeacherWord>,
partsOfSpeechFilter: List<WordTeacherWord.PartOfSpeech>,
items: MutableList<BaseViewItem<*>>
) {
for (word in words) {
val isAdded = addWordViewItems(word, partsOfSpeechFilter, items)
if (isAdded) {
items.add(WordDividerViewItem())
}
}
}
private fun addWordViewItems(
word: WordTeacherWord,
partsOfSpeechFilter: List<WordTeacherWord.PartOfSpeech>,
items: MutableList<BaseViewItem<*>>
): Boolean {
val topIndex = items.size
for (partOfSpeech in word.definitions.keys.filter {
partsOfSpeechFilter.isEmpty() || partsOfSpeechFilter.contains(it)
}) {
items.add(WordPartOfSpeechViewItem(partOfSpeech.toStringDesc()))
for (def in word.definitions[partOfSpeech].orEmpty()) {
for (d in def.definitions) {
items.add(
WordDefinitionViewItem(
definition = d,
data = WordDefinitionViewData(
word = word,
partOfSpeech = partOfSpeech,
def = def
)
)
)
}
if (def.examples.isNotEmpty()) {
items.add(WordSubHeaderViewItem(
StringDesc.Resource(MR.strings.word_section_examples),
Indent.SMALL
))
for (ex in def.examples) {
items.add(WordExampleViewItem(ex, Indent.SMALL))
}
}
if (def.synonyms.isNotEmpty()) {
items.add(WordSubHeaderViewItem(
StringDesc.Resource(MR.strings.word_section_synonyms),
Indent.SMALL
))
for (synonym in def.synonyms) {
items.add(WordSynonymViewItem(synonym, Indent.SMALL))
}
}
}
}
val hasNewItems = items.size - topIndex > 0
if (hasNewItems) {
items.add(topIndex, WordTitleViewItem(word.word, word.types))
word.transcription?.let {
items.add(topIndex + 1, WordTranscriptionViewItem(it))
}
}
return hasNewItems
}
private fun mergeWords(
words: List<WordTeacherWord>,
partsOfSpeechFilter: List<WordTeacherWord.PartOfSpeech>
): WordTeacherWord {
if (words.size == 1) return words.first()
val allWords = mutableListOf<String>()
val allTranscriptions = mutableListOf<String>()
val allDefinitions = mutableMapOf<WordTeacherWord.PartOfSpeech, List<WordTeacherDefinition>>()
val allTypes = mutableListOf<Config.Type>()
words.forEach {
if (!allWords.contains(it.word)) {
allWords.add(it.word)
}
it.transcription?.let {
if (!allTranscriptions.contains(it)) {
allTranscriptions.add(it)
}
}
for (partOfSpeech in it.definitions.keys.filter { definition ->
partsOfSpeechFilter.isEmpty() || partsOfSpeechFilter.contains(definition)
}) {
val originalDefs = it.definitions[partOfSpeech] as? MutableList ?: continue
var list = allDefinitions[partOfSpeech] as? MutableList
if (list == null) {
list = mutableListOf()
allDefinitions[partOfSpeech] = list
}
list.addAll(originalDefs)
}
for (type in it.types) {
if (!allTypes.contains(type)) {
allTypes.add(type)
}
}
}
val resultWord = allWords.joinToString()
val resultTranscription = if (allTranscriptions.isEmpty())
null
else
allTranscriptions.joinToString()
return WordTeacherWord(resultWord, resultTranscription, allDefinitions, allTypes)
}
override fun getErrorText(res: Resource<*>): StringDesc? {
val hasConnection = connectivityManager.isDeviceOnline
val hasResponse = true // TODO: handle error server response
return res.getErrorString(hasConnection, hasResponse)
}
// card sets
override val cardSets = cardSetsRepository.cardSets.map {
Logger.v("build view items")
it.copyWith(buildCardSetViewItems(it.data() ?: emptyList()))
}.stateIn(viewModelScope, SharingStarted.Eagerly, Resource.Uninitialized())
private fun buildCardSetViewItems(cardSets: List<ShortCardSet>): List<BaseViewItem<*>> {
val items = mutableListOf<BaseViewItem<*>>()
cardSets.forEach {
items.add(CardSetViewItem(it.id, it.name, ""))
}
return listOf(
*items.toTypedArray(),
OpenCardSetViewItem(
text = StringDesc.Resource(MR.strings.definitions_open_cardsets)
)
)
}
override fun onOpenCardSets(item: OpenCardSetViewItem) {
router.openCardSets()
}
override fun onAddDefinitionInSet(
wordDefinitionViewItem: WordDefinitionViewItem,
cardSetViewItem: CardSetViewItem
) {
val viewData = wordDefinitionViewItem.data as WordDefinitionViewData
viewModelScope.launch {
cardSetsRepository.addCard(
setId = cardSetViewItem.id,
term = viewData.word.word,
definitions = viewData.def.definitions,
partOfSpeech = viewData.partOfSpeech,
transcription = viewData.word.transcription,
synonyms = viewData.def.synonyms,
examples = viewData.def.examples
)
}
}
}
data class ShowPartsOfSpeechFilterDialogEvent(
val partsOfSpeech: List<WordTeacherWord.PartOfSpeech>,
val selectedPartsOfSpeech: List<WordTeacherWord.PartOfSpeech>,
override var isHandled: Boolean = false
): Event {
override fun markAsHandled() {
isHandled = true
}
}
private data class WordDefinitionViewData(
val word: WordTeacherWord,
val partOfSpeech: WordTeacherWord.PartOfSpeech,
val def: WordTeacherDefinition
) | 0 | null | 1 | 3 | d853cd31e7a609777bffb6ceef18461cccf8222d | 16,003 | WordTeacher | MIT License |
shared/src/commonMain/kotlin/com/aglushkov/wordteacher/shared/features/definitions/vm/DefinitionsVM.kt | soniccat | 302,971,014 | false | null | package com.aglushkov.wordteacher.shared.features.definitions.vm
import dev.icerock.moko.resources.desc.Resource
import dev.icerock.moko.resources.desc.StringDesc
import com.aglushkov.wordteacher.shared.events.Event
import com.aglushkov.wordteacher.shared.features.cardsets.vm.CardSetViewItem
import com.aglushkov.wordteacher.shared.features.cardsets.vm.CreateCardSetViewItem
import com.aglushkov.wordteacher.shared.general.*
import com.aglushkov.wordteacher.shared.general.connectivity.ConnectivityManager
import com.aglushkov.wordteacher.shared.general.extensions.forward
import com.aglushkov.wordteacher.shared.general.item.BaseViewItem
import com.aglushkov.wordteacher.shared.general.item.generateViewItemIds
import com.aglushkov.wordteacher.shared.general.resource.Resource
import com.aglushkov.wordteacher.shared.general.resource.getErrorString
import com.aglushkov.wordteacher.shared.general.resource.isLoaded
import com.aglushkov.wordteacher.shared.model.ShortCardSet
import com.aglushkov.wordteacher.shared.model.WordTeacherDefinition
import com.aglushkov.wordteacher.shared.model.WordTeacherWord
import com.aglushkov.wordteacher.shared.model.toStringDesc
import com.aglushkov.wordteacher.shared.repository.cardset.CardSetsRepository
import com.aglushkov.wordteacher.shared.repository.config.Config
import com.aglushkov.wordteacher.shared.repository.worddefinition.WordDefinitionRepository
import com.aglushkov.wordteacher.shared.res.MR
import com.arkivanov.essenty.parcelable.Parcelable
import com.arkivanov.essenty.parcelable.Parcelize
import kotlinx.coroutines.CoroutineExceptionHandler
import kotlinx.coroutines.Job
import kotlinx.coroutines.channels.Channel
import kotlinx.coroutines.delay
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.SharingStarted
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.combine
import kotlinx.coroutines.flow.map
import kotlinx.coroutines.flow.receiveAsFlow
import kotlinx.coroutines.flow.stateIn
import kotlinx.coroutines.launch
interface DefinitionsVM {
fun restore(newState: State)
fun onWordSubmitted(word: String?, filter: List<WordTeacherWord.PartOfSpeech> = emptyList())
fun onTryAgainClicked()
fun onPartOfSpeechFilterUpdated(filter: List<WordTeacherWord.PartOfSpeech>)
fun onPartOfSpeechFilterClicked(item: DefinitionsDisplayModeViewItem)
fun onPartOfSpeechFilterCloseClicked(item: DefinitionsDisplayModeViewItem)
fun onDisplayModeChanged(mode: DefinitionsDisplayMode)
fun getErrorText(res: Resource<*>): StringDesc?
val state: State
val definitions: StateFlow<Resource<List<BaseViewItem<*>>>>
val displayModeStateFlow: StateFlow<DefinitionsDisplayMode>
val partsOfSpeechFilterStateFlow: StateFlow<List<WordTeacherWord.PartOfSpeech>>
val selectedPartsOfSpeechStateFlow: StateFlow<List<WordTeacherWord.PartOfSpeech>>
val eventFlow: Flow<Event>
// Card Sets
val cardSets: StateFlow<Resource<List<BaseViewItem<*>>>>
fun onOpenCardSets(item: OpenCardSetViewItem)
fun onAddDefinitionInSet(wordDefinitionViewItem: WordDefinitionViewItem, cardSetViewItem: CardSetViewItem)
@Parcelize
class State(
var word: String? = null
): Parcelable
}
open class DefinitionsVMImpl(
override var state: DefinitionsVM.State,
private val router: DefinitionsRouter,
private val connectivityManager: ConnectivityManager,
private val wordDefinitionRepository: WordDefinitionRepository,
private val cardSetsRepository: CardSetsRepository,
private val idGenerator: IdGenerator
): ViewModel(), DefinitionsVM {
private val eventChannel = Channel<Event>(Channel.BUFFERED)
override val eventFlow = eventChannel.receiveAsFlow()
private val definitionWords = MutableStateFlow<Resource<List<WordTeacherWord>>>(Resource.Uninitialized())
final override var displayModeStateFlow = MutableStateFlow(DefinitionsDisplayMode.BySource)
final override var selectedPartsOfSpeechStateFlow = MutableStateFlow<List<WordTeacherWord.PartOfSpeech>>(emptyList())
override val definitions = combine(
definitionWords,
displayModeStateFlow,
selectedPartsOfSpeechStateFlow
) { a, b, c -> Triple(a, b, c) }
.map { (wordDefinitions, displayMode, partOfSpeechFilter) ->
Logger.v("build view items ${wordDefinitions.data()?.size ?: 0}")
wordDefinitions.copyWith(
buildViewItems(wordDefinitions.data().orEmpty(), displayMode, partOfSpeechFilter)
)
}.stateIn(viewModelScope, SharingStarted.Eagerly, Resource.Uninitialized())
override val partsOfSpeechFilterStateFlow = definitionWords.map {
it.data().orEmpty().map { word ->
word.definitions.keys
}.flatten().distinct()
}.stateIn(viewModelScope, SharingStarted.Eagerly, emptyList())
private val displayModes = listOf(DefinitionsDisplayMode.BySource, DefinitionsDisplayMode.Merged)
private var loadJob: Job? = null
private var word: String?
get() {
return state.word
}
set(value) {
state.word = value
}
override fun restore(newState: DefinitionsVM.State) {
state = newState
word?.let {
loadIfNeeded(it)
} ?: run {
word = "owl"
loadIfNeeded("owl")
}
}
override fun onCleared() {
super.onCleared()
eventChannel.cancel()
}
// Events
override fun onWordSubmitted(word: String?, filter: List<WordTeacherWord.PartOfSpeech>) {
selectedPartsOfSpeechStateFlow.value = filter
if (word == null) {
this.word = null
} else if (word.isNotEmpty()) {
loadIfNeeded(word)
}
}
override fun onPartOfSpeechFilterUpdated(filter: List<WordTeacherWord.PartOfSpeech>) {
selectedPartsOfSpeechStateFlow.value = filter
}
override fun onPartOfSpeechFilterClicked(item: DefinitionsDisplayModeViewItem) {
viewModelScope.launch {
eventChannel.offer(
ShowPartsOfSpeechFilterDialogEvent(
selectedPartsOfSpeechStateFlow.value,
partsOfSpeechFilterStateFlow.value
)
)
}
}
override fun onPartOfSpeechFilterCloseClicked(item: DefinitionsDisplayModeViewItem) {
selectedPartsOfSpeechStateFlow.value = emptyList()
}
override fun onDisplayModeChanged(mode: DefinitionsDisplayMode) {
if (displayModeStateFlow.value == mode) return
displayModeStateFlow.value = mode
}
override fun onTryAgainClicked() {
loadIfNeeded(word!!)
}
// Actions
private fun loadIfNeeded(word: String) {
this.word = word
val stateFlow = wordDefinitionRepository.obtainStateFlow(word)
if (stateFlow.value.isLoaded()) {
definitionWords.value = if (definitionWords.value != stateFlow.value) {
stateFlow.value
} else {
// HACK: copy to trigger flow event
stateFlow.value.copy()
}
} else {
load(word)
}
}
private fun load(word: String) {
val tag = "DefinitionsVM.load"
Logger.v("Start Loading $word", tag)
loadJob?.cancel()
loadJob = viewModelScope.launch(CoroutineExceptionHandler { _, e ->
Logger.e("Load Word exception for $word ${e.message}", tag)
}) {
wordDefinitionRepository.define(word, false).forward(definitionWords)
Logger.v("Finish Loading $word", tag)
}
}
private fun buildViewItems(
words: List<WordTeacherWord>,
displayMode: DefinitionsDisplayMode,
partsOfSpeechFilter: List<WordTeacherWord.PartOfSpeech>
): List<BaseViewItem<*>> {
val items = mutableListOf<BaseViewItem<*>>()
if (words.isNotEmpty()) {
items.add(DefinitionsDisplayModeViewItem(
getPartOfSpeechChipText(partsOfSpeechFilter),
partsOfSpeechFilter.isNotEmpty(),
displayModes,
displayModes.indexOf(displayMode)
))
items.add(WordDividerViewItem())
}
when (displayMode) {
DefinitionsDisplayMode.Merged -> addMergedWords(words, partsOfSpeechFilter, items)
else -> addWordsGroupedBySource(words, partsOfSpeechFilter, items)
}
generateIds(items)
return items
}
private fun getPartOfSpeechChipText(
partOfSpeechFilter: List<WordTeacherWord.PartOfSpeech>,
): StringDesc {
return if (partOfSpeechFilter.isEmpty()) {
StringDesc.Resource(MR.strings.definitions_add_filter)
} else {
val firstFilter = partOfSpeechFilter.first()
firstFilter.toStringDesc()
}
}
private fun generateIds(items: MutableList<BaseViewItem<*>>) {
generateViewItemIds(items, definitions.value.data().orEmpty(), idGenerator)
}
private fun addMergedWords(
words: List<WordTeacherWord>,
partsOfSpeechFilter: List<WordTeacherWord.PartOfSpeech>,
items: MutableList<BaseViewItem<*>>
) {
val word = mergeWords(words, partsOfSpeechFilter)
addWordViewItems(word, partsOfSpeechFilter, items)
items.add(WordDividerViewItem())
}
private fun addWordsGroupedBySource(
words: List<WordTeacherWord>,
partsOfSpeechFilter: List<WordTeacherWord.PartOfSpeech>,
items: MutableList<BaseViewItem<*>>
) {
for (word in words) {
val isAdded = addWordViewItems(word, partsOfSpeechFilter, items)
if (isAdded) {
items.add(WordDividerViewItem())
}
}
}
private fun addWordViewItems(
word: WordTeacherWord,
partsOfSpeechFilter: List<WordTeacherWord.PartOfSpeech>,
items: MutableList<BaseViewItem<*>>
): Boolean {
val topIndex = items.size
for (partOfSpeech in word.definitions.keys.filter {
partsOfSpeechFilter.isEmpty() || partsOfSpeechFilter.contains(it)
}) {
items.add(WordPartOfSpeechViewItem(partOfSpeech.toStringDesc()))
for (def in word.definitions[partOfSpeech].orEmpty()) {
for (d in def.definitions) {
items.add(
WordDefinitionViewItem(
definition = d,
data = WordDefinitionViewData(
word = word,
partOfSpeech = partOfSpeech,
def = def
)
)
)
}
if (def.examples.isNotEmpty()) {
items.add(WordSubHeaderViewItem(
StringDesc.Resource(MR.strings.word_section_examples),
Indent.SMALL
))
for (ex in def.examples) {
items.add(WordExampleViewItem(ex, Indent.SMALL))
}
}
if (def.synonyms.isNotEmpty()) {
items.add(WordSubHeaderViewItem(
StringDesc.Resource(MR.strings.word_section_synonyms),
Indent.SMALL
))
for (synonym in def.synonyms) {
items.add(WordSynonymViewItem(synonym, Indent.SMALL))
}
}
}
}
val hasNewItems = items.size - topIndex > 0
if (hasNewItems) {
items.add(topIndex, WordTitleViewItem(word.word, word.types))
word.transcription?.let {
items.add(topIndex + 1, WordTranscriptionViewItem(it))
}
}
return hasNewItems
}
private fun mergeWords(
words: List<WordTeacherWord>,
partsOfSpeechFilter: List<WordTeacherWord.PartOfSpeech>
): WordTeacherWord {
if (words.size == 1) return words.first()
val allWords = mutableListOf<String>()
val allTranscriptions = mutableListOf<String>()
val allDefinitions = mutableMapOf<WordTeacherWord.PartOfSpeech, List<WordTeacherDefinition>>()
val allTypes = mutableListOf<Config.Type>()
words.forEach {
if (!allWords.contains(it.word)) {
allWords.add(it.word)
}
it.transcription?.let {
if (!allTranscriptions.contains(it)) {
allTranscriptions.add(it)
}
}
for (partOfSpeech in it.definitions.keys.filter { definition ->
partsOfSpeechFilter.isEmpty() || partsOfSpeechFilter.contains(definition)
}) {
val originalDefs = it.definitions[partOfSpeech] as? MutableList ?: continue
var list = allDefinitions[partOfSpeech] as? MutableList
if (list == null) {
list = mutableListOf()
allDefinitions[partOfSpeech] = list
}
list.addAll(originalDefs)
}
for (type in it.types) {
if (!allTypes.contains(type)) {
allTypes.add(type)
}
}
}
val resultWord = allWords.joinToString()
val resultTranscription = if (allTranscriptions.isEmpty())
null
else
allTranscriptions.joinToString()
return WordTeacherWord(resultWord, resultTranscription, allDefinitions, allTypes)
}
override fun getErrorText(res: Resource<*>): StringDesc? {
val hasConnection = connectivityManager.isDeviceOnline
val hasResponse = true // TODO: handle error server response
return res.getErrorString(hasConnection, hasResponse)
}
// card sets
override val cardSets = cardSetsRepository.cardSets.map {
Logger.v("build view items")
it.copyWith(buildCardSetViewItems(it.data() ?: emptyList()))
}.stateIn(viewModelScope, SharingStarted.Eagerly, Resource.Uninitialized())
private fun buildCardSetViewItems(cardSets: List<ShortCardSet>): List<BaseViewItem<*>> {
val items = mutableListOf<BaseViewItem<*>>()
cardSets.forEach {
items.add(CardSetViewItem(it.id, it.name, ""))
}
return listOf(
*items.toTypedArray(),
OpenCardSetViewItem(
text = StringDesc.Resource(MR.strings.definitions_open_cardsets)
)
)
}
override fun onOpenCardSets(item: OpenCardSetViewItem) {
router.openCardSets()
}
override fun onAddDefinitionInSet(
wordDefinitionViewItem: WordDefinitionViewItem,
cardSetViewItem: CardSetViewItem
) {
val viewData = wordDefinitionViewItem.data as WordDefinitionViewData
viewModelScope.launch {
cardSetsRepository.addCard(
setId = cardSetViewItem.id,
term = viewData.word.word,
definitions = viewData.def.definitions,
partOfSpeech = viewData.partOfSpeech,
transcription = viewData.word.transcription,
synonyms = viewData.def.synonyms,
examples = viewData.def.examples
)
}
}
}
data class ShowPartsOfSpeechFilterDialogEvent(
val partsOfSpeech: List<WordTeacherWord.PartOfSpeech>,
val selectedPartsOfSpeech: List<WordTeacherWord.PartOfSpeech>,
override var isHandled: Boolean = false
): Event {
override fun markAsHandled() {
isHandled = true
}
}
private data class WordDefinitionViewData(
val word: WordTeacherWord,
val partOfSpeech: WordTeacherWord.PartOfSpeech,
val def: WordTeacherDefinition
) | 0 | null | 1 | 3 | d853cd31e7a609777bffb6ceef18461cccf8222d | 16,003 | WordTeacher | MIT License |
src/commonMain/kotlin/pw/binom/lua/StdOut.kt | caffeine-mgn | 432,464,938 | false | {"C": 836370, "Kotlin": 167159, "C++": 1216, "JavaScript": 194, "HTML": 84} | package pw.binom.lua
object StdOut {
internal var func: ((String) -> Unit)? = null
fun info(txt: String) {
func?.invoke(txt)
}
}
| 0 | C | 0 | 1 | 302f8855c6a2bf0cc2e3f015ca79475e811d8230 | 150 | klua | Apache License 2.0 |
src/main/kotlin/com/faendir/zachtronics/bot/discord/LinkConverter.kt | F43nd1r | 290,065,466 | false | null | /*
* Copyright (c) 2021
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.faendir.zachtronics.bot.discord
import com.faendir.discord4j.command.parse.OptionConverter
import com.faendir.discord4j.command.parse.SingleParseResult
import com.faendir.zachtronics.bot.utils.isValidLink
import discord4j.common.util.Snowflake
import discord4j.core.`object`.entity.Message
import discord4j.core.`object`.reaction.ReactionEmoji
import discord4j.core.event.domain.interaction.ChatInputInteractionEvent
import reactor.core.publisher.Flux
import java.time.Instant
private val regex = Regex("m(?<message>\\d{1,2})(\\.(?<attachment>\\d{1,2}))?")
class LinkConverter : OptionConverter<String, String> {
override fun fromValue(context: ChatInputInteractionEvent, value: String): SingleParseResult<String> {
return findLink(
value.trim(),
context.interaction.channel.flatMapMany { it.getMessagesBefore(it.lastMessageId.orElseGet { Snowflake.of(Instant.now()) }) }
.filter { it.author.isPresent && it.author.get() == context.interaction.user })
}
private fun findLink(input: String, messages: Flux<Message>): SingleParseResult<String> {
val link = regex.matchEntire(input)?.let { match ->
val num = match.groups["message"]!!.value.toInt()
val attachment = match.groups["attachment"]?.value?.toInt()
val message = messages.elementAt(num - 1).block()!!
message.attachments.getOrNull(attachment?.minus(1) ?: 0)?.url?.also { message.addReaction(ReactionEmoji.unicode("\uD83D\uDC4D"/* 👍 */)).block() }
?: return SingleParseResult.Failure(
"https://discord.com/channels/${
message.guild.block()!!.id.asLong().toString().ifEmpty { "@me" }
}/${message.channelId.asLong()}/${message.id.asLong()} had no attachments"
)
} ?: input
if (!isValidLink(link)) {
return SingleParseResult.Failure("\"$link\" is not a valid link")
}
return SingleParseResult.Success(link)
}
} | 3 | null | 1 | 2 | 6ed66aa90151f585a20f8ce8e31aae7f4c1701e4 | 2,630 | zachtronics-leaderboard-bot | Apache License 2.0 |
src/main/kotlin/com/faendir/zachtronics/bot/discord/LinkConverter.kt | F43nd1r | 290,065,466 | false | null | /*
* Copyright (c) 2021
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.faendir.zachtronics.bot.discord
import com.faendir.discord4j.command.parse.OptionConverter
import com.faendir.discord4j.command.parse.SingleParseResult
import com.faendir.zachtronics.bot.utils.isValidLink
import discord4j.common.util.Snowflake
import discord4j.core.`object`.entity.Message
import discord4j.core.`object`.reaction.ReactionEmoji
import discord4j.core.event.domain.interaction.ChatInputInteractionEvent
import reactor.core.publisher.Flux
import java.time.Instant
private val regex = Regex("m(?<message>\\d{1,2})(\\.(?<attachment>\\d{1,2}))?")
class LinkConverter : OptionConverter<String, String> {
override fun fromValue(context: ChatInputInteractionEvent, value: String): SingleParseResult<String> {
return findLink(
value.trim(),
context.interaction.channel.flatMapMany { it.getMessagesBefore(it.lastMessageId.orElseGet { Snowflake.of(Instant.now()) }) }
.filter { it.author.isPresent && it.author.get() == context.interaction.user })
}
private fun findLink(input: String, messages: Flux<Message>): SingleParseResult<String> {
val link = regex.matchEntire(input)?.let { match ->
val num = match.groups["message"]!!.value.toInt()
val attachment = match.groups["attachment"]?.value?.toInt()
val message = messages.elementAt(num - 1).block()!!
message.attachments.getOrNull(attachment?.minus(1) ?: 0)?.url?.also { message.addReaction(ReactionEmoji.unicode("\uD83D\uDC4D"/* 👍 */)).block() }
?: return SingleParseResult.Failure(
"https://discord.com/channels/${
message.guild.block()!!.id.asLong().toString().ifEmpty { "@me" }
}/${message.channelId.asLong()}/${message.id.asLong()} had no attachments"
)
} ?: input
if (!isValidLink(link)) {
return SingleParseResult.Failure("\"$link\" is not a valid link")
}
return SingleParseResult.Success(link)
}
} | 3 | null | 1 | 2 | 6ed66aa90151f585a20f8ce8e31aae7f4c1701e4 | 2,630 | zachtronics-leaderboard-bot | Apache License 2.0 |
app/src/androidTest/java/com/miguelrr/capsshop/ExampleInstrumentedTest.kt | MiguelRom3ro | 776,249,721 | false | {"Kotlin": 70546} | package com.miguelrr.capsshop
import androidx.test.platform.app.InstrumentationRegistry
import androidx.test.ext.junit.runners.AndroidJUnit4
import org.junit.Test
import org.junit.runner.RunWith
import org.junit.Assert.*
/**
* Instrumented test, which will execute on an Android device.
*
* See [testing documentation](http://d.android.com/tools/testing).
*/
@RunWith(AndroidJUnit4::class)
class ExampleInstrumentedTest {
@Test
fun useAppContext() {
// Context of the app under test.
val appContext = InstrumentationRegistry.getInstrumentation().targetContext
assertEquals("com.miguelrr.capsshop", appContext.packageName)
}
} | 0 | Kotlin | 0 | 0 | 4474d1d07f629efe0cb3c45427d999ca972a7fbd | 669 | CapsShop | MIT License |
projects/unpaid-work-and-delius/src/dev/kotlin/uk/gov/justice/digital/hmpps/data/generator/ContactTypeGenerator.kt | ministryofjustice | 500,855,647 | false | {"Kotlin": 4362222, "HTML": 70066, "D2": 44286, "Ruby": 25921, "Shell": 19356, "SCSS": 6370, "HCL": 2712, "Dockerfile": 2447, "JavaScript": 1372, "Python": 268} | package uk.gov.justice.digital.hmpps.data.generator
import uk.gov.justice.digital.hmpps.integrations.common.entity.contact.type.ContactType
import uk.gov.justice.digital.hmpps.integrations.common.entity.contact.type.ContactTypeCode
object ContactTypeGenerator {
val DEFAULT = generate()
fun generate(id: Long = IdGenerator.getAndIncrement()) = ContactType(id, ContactTypeCode.UPW_ASSESSMENT.code)
}
| 4 | Kotlin | 0 | 2 | 9f6663d820fb8123d915107edfa9abc5f82d3fb6 | 410 | hmpps-probation-integration-services | MIT License |
examples/getting-started-compose/composeApp/src/jvmMain/kotlin/Platform.jvm.kt | jeffdgr8 | 518,984,559 | false | null | package com.example
class JvmPlatform : Platform {
override val name: String = "JVM ${ System.getProperty("java.version")}"
}
actual fun getPlatform(): Platform = JvmPlatform() | 181 | null | 5748 | 67 | 339bea038018dff346cbfe0e4f8309c653b9f3b1 | 182 | kotbase | Apache License 2.0 |
src/main/kotlin/org/dripto/githubissuetracker/service/HelloService.kt | driptaroop | 260,482,930 | false | null | package org.dripto.githubissuetracker.service
import org.springframework.stereotype.Service
@Service
class HelloService {
fun doAddition(vararg i: Int) = i.fold(0) { a, b -> a + b }
fun subtraction(i: Int, j: Int) = i - j
}
| 1 | Kotlin | 0 | 1 | 8ccd5be84b5de68140dbd1e741698031e7bfc22c | 235 | github-issue-tracker | MIT License |
app/src/main/java/com/kcteam/features/reimbursement/api/reimbursementshopapi/ReimbursementShopApi.kt | DebashisINT | 558,234,039 | false | null | package com.chittchorefsm.features.reimbursement.api.reimbursementshopapi
import com.chittchorefsm.app.NetworkConstant
import com.chittchorefsm.features.reimbursement.model.reimbursement_shop.ReimbursementShopResponseModel
import io.reactivex.Observable
import retrofit2.Retrofit
import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory
import retrofit2.converter.gson.GsonConverterFactory
import retrofit2.http.Field
import retrofit2.http.FormUrlEncoded
import retrofit2.http.POST
/**
* Created by Saikat on 31-05-2019.
*/
interface ReimbursementShopApi {
@FormUrlEncoded
@POST("Reimbursement/ReimbursementShop")
fun getReimbursementShop(@Field("user_id") user_id: String, @Field("session_token") session_token: String,
@Field("date") date: String, @Field("isEditable") isEditable: Boolean,
@Field("Expense_mapId") Expense_mapId: String, @Field("Subexpense_MapId") Subexpense_MapId: String): Observable<ReimbursementShopResponseModel>
@FormUrlEncoded
@POST("Reimbursement/LocationCaptureList")
fun getReimbursementLoc(@Field("user_id") user_id: String, @Field("session_token") session_token: String,
@Field("date") date: String): Observable<ReimbursementShopResponseModel>
/**
* Companion object to create the GithubApiService
*/
companion object Factory {
fun create(): ReimbursementShopApi {
val retrofit = Retrofit.Builder()
.client(NetworkConstant.setTimeOut())
.addCallAdapterFactory(RxJava2CallAdapterFactory.create())
.addConverterFactory(GsonConverterFactory.create())
.baseUrl(NetworkConstant.BASE_URL)
.build()
return retrofit.create(ReimbursementShopApi::class.java)
}
}
} | 0 | null | 1 | 1 | e6114824d91cba2e70623631db7cbd9b4d9690ed | 1,867 | NationalPlastic | Apache License 2.0 |
src/test/kotlin/no/nav/helper/AltinnProxyContainer.kt | navikt | 644,356,194 | false | {"Kotlin": 83975, "Dockerfile": 214} | package no.nav.fia.arbeidsgiver.helper
import com.github.tomakehurst.wiremock.WireMockServer
import com.github.tomakehurst.wiremock.client.WireMock
import com.github.tomakehurst.wiremock.core.WireMockConfiguration
import org.apache.http.protocol.HTTP.CONTENT_TYPE
import org.testcontainers.Testcontainers
class AltinnProxyContainer {
companion object {
val ALTINN_ORGNR_1 = "311111111"
val ALTINN_ORGNR_2 = "322222222"
val ORGNR_UTEN_TILKNYTNING = "300000000"
val ALTINN_OVERORDNET_ORGNR = "400000000"
}
private val wireMock = WireMockServer(WireMockConfiguration.options().dynamicPort()).also {
it.stubFor(
WireMock.get(WireMock.urlPathEqualTo("/altinn/v2/organisasjoner"))
.willReturn(
WireMock.ok()
.withHeader(CONTENT_TYPE, "application/json")
.withBody(
"""[
{
"Name": "<NAME>",
"Type": "Business",
"OrganizationNumber": "$ALTINN_ORGNR_1",
"ParentOrganizationNumber": "$ALTINN_OVERORDNET_ORGNR",
"OrganizationForm": "BEDR",
"Status": "Active"
},
{
"Name": "FIKTIVIA",
"Type": "Business",
"OrganizationNumber": "$ALTINN_ORGNR_2",
"ParentOrganizationNumber": "$ALTINN_OVERORDNET_ORGNR",
"OrganizationForm": "BEDR",
"Status": "Active"
}
]""".trimMargin()
)
)
)
if (!it.isRunning) {
it.start()
}
println("Starter Wiremock på port ${it.port()}")
Testcontainers.exposeHostPorts(it.port())
}
fun getEnv() = mapOf(
"ALTINN_RETTIGHETER_PROXY_URL" to "http://host.testcontainers.internal:${wireMock.port()}/altinn",
"ALTINN_RETTIGHETER_PROXY_CLIENT_ID" to "hei",
)
}
| 0 | Kotlin | 0 | 0 | 7cbc469c0fe892d304938a0011e5fd46e0aa9ff9 | 2,364 | fia-arbeidsgiver | MIT License |
octicons/src/commonMain/kotlin/compose/icons/octicons/CheckCircle24.kt | DevSrSouza | 311,134,756 | false | {"Kotlin": 36719092} | package compose.icons.octicons
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.PathFillType.Companion.EvenOdd
import androidx.compose.ui.graphics.PathFillType.Companion.NonZero
import androidx.compose.ui.graphics.SolidColor
import androidx.compose.ui.graphics.StrokeCap
import androidx.compose.ui.graphics.StrokeCap.Companion.Butt
import androidx.compose.ui.graphics.StrokeJoin
import androidx.compose.ui.graphics.StrokeJoin.Companion.Miter
import androidx.compose.ui.graphics.vector.ImageVector
import androidx.compose.ui.graphics.vector.ImageVector.Builder
import androidx.compose.ui.graphics.vector.path
import androidx.compose.ui.unit.dp
import compose.icons.Octicons
public val Octicons.CheckCircle24: ImageVector
get() {
if (_checkCircle24 != null) {
return _checkCircle24!!
}
_checkCircle24 = Builder(name = "CheckCircle24", defaultWidth = 24.0.dp, defaultHeight =
24.0.dp, viewportWidth = 24.0f, viewportHeight = 24.0f).apply {
path(fill = SolidColor(Color(0xFF000000)), stroke = null, strokeLineWidth = 0.0f,
strokeLineCap = Butt, strokeLineJoin = Miter, strokeLineMiter = 4.0f,
pathFillType = NonZero) {
moveTo(17.28f, 9.28f)
arcToRelative(0.75f, 0.75f, 0.0f, false, false, -1.06f, -1.06f)
lineToRelative(-5.97f, 5.97f)
lineToRelative(-2.47f, -2.47f)
arcToRelative(0.75f, 0.75f, 0.0f, false, false, -1.06f, 1.06f)
lineToRelative(3.0f, 3.0f)
arcToRelative(0.75f, 0.75f, 0.0f, false, false, 1.06f, 0.0f)
lineToRelative(6.5f, -6.5f)
close()
}
path(fill = SolidColor(Color(0xFF000000)), stroke = null, strokeLineWidth = 0.0f,
strokeLineCap = Butt, strokeLineJoin = Miter, strokeLineMiter = 4.0f,
pathFillType = EvenOdd) {
moveTo(12.0f, 1.0f)
curveTo(5.925f, 1.0f, 1.0f, 5.925f, 1.0f, 12.0f)
reflectiveCurveToRelative(4.925f, 11.0f, 11.0f, 11.0f)
reflectiveCurveToRelative(11.0f, -4.925f, 11.0f, -11.0f)
reflectiveCurveTo(18.075f, 1.0f, 12.0f, 1.0f)
close()
moveTo(2.5f, 12.0f)
arcToRelative(9.5f, 9.5f, 0.0f, true, true, 19.0f, 0.0f)
arcToRelative(9.5f, 9.5f, 0.0f, false, true, -19.0f, 0.0f)
close()
}
}
.build()
return _checkCircle24!!
}
private var _checkCircle24: ImageVector? = null
| 17 | Kotlin | 25 | 571 | a660e5f3033e3222e3553f5a6e888b7054aed8cd | 2,643 | compose-icons | MIT License |
packages/expo-updates/android/src/main/java/expo/modules/updates/loader/LoaderTask.kt | betomoedano | 462,599,485 | false | null | package expo.modules.updates.loader
import android.content.Context
import android.os.AsyncTask
import android.os.Handler
import android.os.HandlerThread
import android.util.Log
import expo.modules.updates.UpdatesConfiguration
import expo.modules.updates.UpdatesUtils
import expo.modules.updates.db.DatabaseHolder
import expo.modules.updates.db.Reaper
import expo.modules.updates.db.entity.AssetEntity
import expo.modules.updates.db.entity.UpdateEntity
import expo.modules.updates.launcher.DatabaseLauncher
import expo.modules.updates.launcher.Launcher
import expo.modules.updates.launcher.Launcher.LauncherCallback
import expo.modules.updates.loader.Loader.LoaderCallback
import expo.modules.updates.manifest.EmbeddedManifest
import expo.modules.updates.manifest.ManifestMetadata
import expo.modules.updates.manifest.UpdateManifest
import expo.modules.updates.selectionpolicy.SelectionPolicy
import org.json.JSONObject
import java.io.File
import java.util.Date
/**
* Controlling class that handles the complex logic that needs to happen each time the app is cold
* booted. From a high level, this class does the following:
*
* - Immediately starts an instance of [EmbeddedLoader] to load the embedded update into SQLite.
* This does nothing if SQLite already has the embedded update or a newer one, but we have to do
* this on each cold boot, as we have no way of knowing if a new build was just installed (which
* could have a new embedded update).
* - If the app is configured for automatic update downloads (most apps), starts a timer based on
* the `launchWaitMs` value in [UpdatesConfiguration].
* - Again if the app is configured for automatic update downloads, starts an instance of
* [RemoteLoader] to check for and download a new update if there is one.
* - Once the download succeeds, fails, or the timer runs out (whichever happens first), creates an
* instance of [DatabaseLauncher] and signals that the app is ready to be launched with the newest
* update available locally at that time (which may not be the newest update if the download is
* still in progress).
* - If the download succeeds or fails after this point, fires a callback which causes an event to
* be sent to JS.
*/
class LoaderTask(
private val configuration: UpdatesConfiguration,
private val databaseHolder: DatabaseHolder,
private val directory: File?,
private val fileDownloader: FileDownloader,
private val selectionPolicy: SelectionPolicy,
private val callback: LoaderTaskCallback
) {
enum class RemoteUpdateStatus {
ERROR, NO_UPDATE_AVAILABLE, UPDATE_AVAILABLE
}
sealed class RemoteCheckResult(private val status: Status) {
private enum class Status {
NO_UPDATE_AVAILABLE,
UPDATE_AVAILABLE,
ROLL_BACK_TO_EMBEDDED
}
class NoUpdateAvailable : RemoteCheckResult(Status.NO_UPDATE_AVAILABLE)
class UpdateAvailable(val manifest: JSONObject) : RemoteCheckResult(Status.UPDATE_AVAILABLE)
class RollBackToEmbedded(val commitTime: Date) : RemoteCheckResult(Status.ROLL_BACK_TO_EMBEDDED)
}
interface LoaderTaskCallback {
fun onFailure(e: Exception)
/**
* This method gives the calling class a backdoor option to ignore the cached update and force
* a remote load if it decides the cached update is not runnable. Returning false from this
* callback will force a remote load, overriding the timeout and configuration settings for
* whether or not to check for a remote update. Returning true from this callback will make
* LoaderTask proceed as usual.
*/
fun onCachedUpdateLoaded(update: UpdateEntity): Boolean
fun onRemoteUpdateManifestResponseManifestLoaded(updateManifest: UpdateManifest)
fun onSuccess(launcher: Launcher, isUpToDate: Boolean)
fun onRemoteCheckForUpdateStarted() {}
fun onRemoteCheckForUpdateFinished(result: RemoteCheckResult) {}
fun onRemoteUpdateLoadStarted() {}
fun onRemoteUpdateAssetLoaded(asset: AssetEntity, successfulAssetCount: Int, failedAssetCount: Int, totalAssetCount: Int) {}
fun onRemoteUpdateFinished(
status: RemoteUpdateStatus,
update: UpdateEntity?,
exception: Exception?
)
}
private interface Callback {
fun onFailure(e: Exception)
fun onSuccess()
}
var isRunning = false
private set
// success conditions
private var isReadyToLaunch = false
private var timeoutFinished = false
private var hasLaunched = false
private var isUpToDate = false
private val handlerThread: HandlerThread = HandlerThread("expo-updates-timer")
private var candidateLauncher: Launcher? = null
private var finalizedLauncher: Launcher? = null
fun start(context: Context) {
if (!configuration.isEnabled) {
callback.onFailure(Exception("LoaderTask was passed a configuration object with updates disabled. You should load updates from an embedded source rather than calling LoaderTask, or enable updates in the configuration."))
return
}
if (configuration.updateUrl == null) {
callback.onFailure(Exception("LoaderTask was passed a configuration object with a null URL. You must pass a nonnull URL in order to use LoaderTask to load updates."))
return
}
if (directory == null) {
throw AssertionError("LoaderTask directory must be nonnull.")
}
isRunning = true
val shouldCheckForUpdate = UpdatesUtils.shouldCheckForUpdateOnLaunch(configuration, context)
val delay = configuration.launchWaitMs
if (delay > 0 && shouldCheckForUpdate) {
handlerThread.start()
Handler(handlerThread.looper).postDelayed({ timeout() }, delay.toLong())
} else {
timeoutFinished = true
}
launchFallbackUpdateFromDisk(
context,
object : Callback {
private fun launchRemoteUpdate() {
launchRemoteUpdateInBackground(
context,
object : Callback {
override fun onFailure(e: Exception) {
finish(e)
isRunning = false
runReaper()
}
override fun onSuccess() {
synchronized(this@LoaderTask) { isReadyToLaunch = true }
finish(null)
isRunning = false
runReaper()
}
}
)
}
override fun onFailure(e: Exception) {
// An unexpected failure has occurred here, or we are running in an environment with no
// embedded update and we have no update downloaded (e.g. Expo client).
// What to do in this case depends on whether or not we're trying to load a remote update.
// If we are, then we should wait for the task to finish. If not, we need to fail here.
if (!shouldCheckForUpdate) {
finish(e)
isRunning = false
} else {
launchRemoteUpdate()
}
Log.e(TAG, "Failed to launch embedded or launchable update", e)
}
override fun onSuccess() {
if (candidateLauncher!!.launchedUpdate != null &&
!callback.onCachedUpdateLoaded(candidateLauncher!!.launchedUpdate!!)
) {
// ignore timer and other settings and force launch a remote update
stopTimer()
candidateLauncher = null
launchRemoteUpdate()
} else {
synchronized(this@LoaderTask) {
isReadyToLaunch = true
maybeFinish()
}
if (shouldCheckForUpdate) {
launchRemoteUpdate()
} else {
isRunning = false
runReaper()
}
}
}
}
)
}
/**
* This method should be called at the end of the LoaderTask. Whether or not the task has
* successfully loaded an update to launch, the timer will stop and the appropriate callback
* function will be fired.
*/
@Synchronized
private fun finish(e: Exception?) {
if (hasLaunched) {
// we've already fired once, don't do it again
return
}
hasLaunched = true
finalizedLauncher = candidateLauncher
if (!isReadyToLaunch || finalizedLauncher == null || finalizedLauncher!!.launchedUpdate == null) {
callback.onFailure(
e
?: Exception("LoaderTask encountered an unexpected error and could not launch an update.")
)
} else {
callback.onSuccess(finalizedLauncher!!, isUpToDate)
}
if (!timeoutFinished) {
stopTimer()
}
if (e != null) {
Log.e(TAG, "Unexpected error encountered while loading this app", e)
}
}
/**
* This method should be called to conditionally fire the callback. If the task has successfully
* loaded an update to launch and the timer isn't still running, the appropriate callback function
* will be fired. If not, no callback will be fired.
*/
@Synchronized
private fun maybeFinish() {
if (!isReadyToLaunch || !timeoutFinished) {
// too early, bail out
return
}
finish(null)
}
@Synchronized
private fun stopTimer() {
timeoutFinished = true
handlerThread.quitSafely()
}
@Synchronized
private fun timeout() {
if (!timeoutFinished) {
timeoutFinished = true
maybeFinish()
}
stopTimer()
}
private fun launchFallbackUpdateFromDisk(context: Context, diskUpdateCallback: Callback) {
val database = databaseHolder.database
val launcher = DatabaseLauncher(configuration, directory, fileDownloader, selectionPolicy)
candidateLauncher = launcher
val launcherCallback: LauncherCallback = object : LauncherCallback {
override fun onFailure(e: Exception) {
databaseHolder.releaseDatabase()
diskUpdateCallback.onFailure(e)
}
override fun onSuccess() {
databaseHolder.releaseDatabase()
diskUpdateCallback.onSuccess()
}
}
if (configuration.hasEmbeddedUpdate) {
// if the embedded update should be launched (e.g. if it's newer than any other update we have
// in the database, which can happen if the app binary is updated), load it into the database
// so we can launch it
val embeddedUpdate = EmbeddedManifest.get(context, configuration)!!.updateEntity
val launchableUpdate = launcher.getLaunchableUpdate(database, context)
val manifestFilters = ManifestMetadata.getManifestFilters(database, configuration)
if (selectionPolicy.shouldLoadNewUpdate(embeddedUpdate, launchableUpdate, manifestFilters)) {
EmbeddedLoader(context, configuration, database, directory).start(object : LoaderCallback {
override fun onFailure(e: Exception) {
Log.e(TAG, "Unexpected error copying embedded update", e)
launcher.launch(database, context, launcherCallback)
}
override fun onSuccess(loaderResult: Loader.LoaderResult) {
launcher.launch(database, context, launcherCallback)
}
override fun onAssetLoaded(
asset: AssetEntity,
successfulAssetCount: Int,
failedAssetCount: Int,
totalAssetCount: Int
) {
// do nothing
}
override fun onUpdateResponseLoaded(updateResponse: UpdateResponse): Loader.OnUpdateResponseLoadedResult {
return Loader.OnUpdateResponseLoadedResult(shouldDownloadManifestIfPresentInResponse = true)
}
})
} else {
launcher.launch(database, context, launcherCallback)
}
} else {
launcher.launch(database, context, launcherCallback)
}
}
private fun launchRemoteUpdateInBackground(context: Context, remoteUpdateCallback: Callback) {
AsyncTask.execute {
val database = databaseHolder.database
callback.onRemoteCheckForUpdateStarted()
RemoteLoader(context, configuration, database, fileDownloader, directory, candidateLauncher?.launchedUpdate)
.start(object : LoaderCallback {
override fun onFailure(e: Exception) {
databaseHolder.releaseDatabase()
remoteUpdateCallback.onFailure(e)
callback.onRemoteUpdateFinished(RemoteUpdateStatus.ERROR, null, e)
Log.e(TAG, "Failed to download remote update", e)
}
override fun onAssetLoaded(
asset: AssetEntity,
successfulAssetCount: Int,
failedAssetCount: Int,
totalAssetCount: Int
) {
callback.onRemoteUpdateAssetLoaded(asset, successfulAssetCount, failedAssetCount, totalAssetCount)
}
override fun onUpdateResponseLoaded(updateResponse: UpdateResponse): Loader.OnUpdateResponseLoadedResult {
val updateDirective = updateResponse.directiveUpdateResponsePart?.updateDirective
if (updateDirective != null) {
return when (updateDirective) {
is UpdateDirective.RollBackToEmbeddedUpdateDirective -> {
isUpToDate = true
callback.onRemoteCheckForUpdateFinished(RemoteCheckResult.RollBackToEmbedded(updateDirective.commitTime))
Loader.OnUpdateResponseLoadedResult(shouldDownloadManifestIfPresentInResponse = false)
}
is UpdateDirective.NoUpdateAvailableUpdateDirective -> {
isUpToDate = true
callback.onRemoteCheckForUpdateFinished(RemoteCheckResult.NoUpdateAvailable())
Loader.OnUpdateResponseLoadedResult(shouldDownloadManifestIfPresentInResponse = false)
}
}
}
val updateManifest = updateResponse.manifestUpdateResponsePart?.updateManifest
if (updateManifest == null) {
isUpToDate = true
callback.onRemoteCheckForUpdateFinished(RemoteCheckResult.NoUpdateAvailable())
return Loader.OnUpdateResponseLoadedResult(shouldDownloadManifestIfPresentInResponse = false)
}
return if (selectionPolicy.shouldLoadNewUpdate(
updateManifest.updateEntity,
candidateLauncher?.launchedUpdate,
updateResponse.responseHeaderData?.manifestFilters
)
) {
isUpToDate = false
callback.onRemoteUpdateManifestResponseManifestLoaded(updateManifest)
callback.onRemoteCheckForUpdateFinished(RemoteCheckResult.UpdateAvailable(updateManifest.manifest.getRawJson()))
callback.onRemoteUpdateLoadStarted()
Loader.OnUpdateResponseLoadedResult(shouldDownloadManifestIfPresentInResponse = true)
} else {
isUpToDate = true
callback.onRemoteCheckForUpdateFinished(RemoteCheckResult.NoUpdateAvailable())
Loader.OnUpdateResponseLoadedResult(shouldDownloadManifestIfPresentInResponse = false)
}
}
override fun onSuccess(loaderResult: Loader.LoaderResult) {
RemoteLoader.processSuccessLoaderResult(
context,
configuration,
database,
selectionPolicy,
directory,
candidateLauncher?.launchedUpdate,
loaderResult
) { availableUpdate, _ ->
launchUpdate(availableUpdate)
}
}
private fun launchUpdate(availableUpdate: UpdateEntity?) {
// a new update (or null update because onUpdateResponseLoaded returned false or it was just a directive) has loaded successfully;
// we need to launch it with a new Launcher and replace the old Launcher so that the callback fires with the new one
val newLauncher = DatabaseLauncher(configuration, directory, fileDownloader, selectionPolicy)
newLauncher.launch(
database, context,
object : LauncherCallback {
override fun onFailure(e: Exception) {
databaseHolder.releaseDatabase()
remoteUpdateCallback.onFailure(e)
Log.e(TAG, "Loaded new update but it failed to launch", e)
}
override fun onSuccess() {
databaseHolder.releaseDatabase()
val hasLaunchedSynchronized = synchronized(this@LoaderTask) {
if (!hasLaunched) {
candidateLauncher = newLauncher
isUpToDate = true
}
hasLaunched
}
remoteUpdateCallback.onSuccess()
if (hasLaunchedSynchronized) {
if (availableUpdate == null) {
callback.onRemoteUpdateFinished(
RemoteUpdateStatus.NO_UPDATE_AVAILABLE,
null,
null
)
} else {
callback.onRemoteUpdateFinished(
RemoteUpdateStatus.UPDATE_AVAILABLE,
availableUpdate,
null
)
}
}
}
}
)
}
})
}
}
private fun runReaper() {
AsyncTask.execute {
synchronized(this@LoaderTask) {
if (finalizedLauncher != null && finalizedLauncher!!.launchedUpdate != null) {
val database = databaseHolder.database
Reaper.reapUnusedUpdates(
configuration,
database,
directory,
finalizedLauncher!!.launchedUpdate,
selectionPolicy
)
databaseHolder.releaseDatabase()
}
}
}
}
companion object {
private val TAG = LoaderTask::class.java.simpleName
}
}
| 668 | null | 5226 | 4 | 52d6405570a39a87149648d045d91098374f4423 | 17,844 | expo | MIT License |
kotlin/src/src/main/java/com/techlabcamp/neuronet/ui/frag/CertificateDetailsFrag.kt | dimske-sys | 610,048,630 | false | null | package com.techlabcamp.neuronet.ui.frag
import android.Manifest
import android.content.pm.PackageManager
import android.graphics.drawable.Drawable
import android.os.Build
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.activity.result.ActivityResultLauncher
import androidx.activity.result.contract.ActivityResultContracts
import androidx.core.app.ActivityCompat
import androidx.core.content.FileProvider
import com.bumptech.glide.Glide
import com.bumptech.glide.load.DataSource
import com.bumptech.glide.load.engine.GlideException
import com.bumptech.glide.request.RequestListener
import com.bumptech.glide.request.target.Target
import com.techlabcamp.neuronet.R
import com.techlabcamp.neuronet.databinding.FragCertificateDetailsBinding
import com.techlabcamp.neuronet.manager.App
import com.techlabcamp.neuronet.manager.BuildVars
import com.techlabcamp.neuronet.manager.ToastMaker
import com.techlabcamp.neuronet.manager.Utils
import com.techlabcamp.neuronet.manager.adapter.CertStudentRvAdapter
import com.techlabcamp.neuronet.manager.listener.ItemCallback
import com.techlabcamp.neuronet.manager.net.observer.NetworkObserverFragment
import com.techlabcamp.neuronet.model.Quiz
import com.techlabcamp.neuronet.model.QuizResult
import com.techlabcamp.neuronet.model.ToolbarOptions
import com.techlabcamp.neuronet.presenter.Presenter
import com.techlabcamp.neuronet.presenterImpl.CertificateDetailsPresenterImpl
import com.techlabcamp.neuronet.ui.MainActivity
import com.techlabcamp.neuronet.ui.widget.ProgressiveLoadingDialog
import java.io.File
import java.lang.Exception
class CertificateDetailsFrag : NetworkObserverFragment(), View.OnClickListener {
private lateinit var mBinding: FragCertificateDetailsBinding
private var mResult: QuizResult? = null
private lateinit var mQuiz: Quiz
private var mSavedCertPath: String? = null
private lateinit var mCertStudents: ArrayList<QuizResult>
private lateinit var mStoragePermissionResultLauncher: ActivityResultLauncher<Array<String>>
private lateinit var mPresenter: Presenter.CertificateDetailsPresenter
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
mStoragePermissionResultLauncher =
registerForActivityResult(ActivityResultContracts.RequestMultiplePermissions()) { permissions ->
if (permissions[Manifest.permission.WRITE_EXTERNAL_STORAGE] == true &&
permissions[Manifest.permission.READ_EXTERNAL_STORAGE] == true
) {
onClick(mBinding.certificateDetailsDownloadBtn)
}
}
}
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View {
mBinding = FragCertificateDetailsBinding.inflate(inflater, container, false)
return mBinding.root
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
init()
}
private fun init() {
val toolbarOptions = ToolbarOptions()
toolbarOptions.startIcon = ToolbarOptions.Icon.BACK
(activity as MainActivity).showToolbar(toolbarOptions, R.string.certificate_overview)
when (val parcelable: Any = requireArguments().getParcelable(App.CERTIFICATE)!!) {
is QuizResult -> {
mResult = parcelable
mQuiz = mResult!!.quiz
mPresenter = CertificateDetailsPresenterImpl(this)
if (mResult!!.certificate == null) {
mBinding.certificateDetailsImg.setImageResource(R.drawable.cert_default)
} else {
Glide.with(requireContext()).load(mResult!!.certificate!!.img)
.into(mBinding.certificateDetailsImg)
}
initResultCertMarks()
if (!mQuiz.authCanDownloadCertificate) {
mBinding.certificateDetailsBtnsContainer.visibility = View.GONE
}
if (!App.loggedInUser!!.isUser()) {
mPresenter.getStudents()
}
}
is Quiz -> {
mQuiz = parcelable
mBinding.certificateDetailsBtnsContainer.visibility = View.GONE
initQuizCertMarks()
if (mQuiz.course.img != null) {
Glide.with(requireContext()).load(mQuiz.course.img)
.addListener(object : RequestListener<Drawable> {
override fun onLoadFailed(
e: GlideException?,
model: Any?,
target: Target<Drawable>?,
isFirstResource: Boolean
): Boolean {
return false
}
override fun onResourceReady(
resource: Drawable?,
model: Any?,
target: Target<Drawable>?,
dataSource: DataSource?,
isFirstResource: Boolean
): Boolean {
mBinding.certificateDetailsImgOverlay.visibility = View.VISIBLE
return false
}
}).into(mBinding.certificateDetailsImg)
}
mBinding.certificateDetailsShareTv.text = getString(R.string.certificate_overview)
mBinding.certificateDetailsShareDescTv.text =
getString(R.string.certificate_overview_desc)
}
else -> {
return
}
}
mBinding.certificateDetailsTitleTv.text = mQuiz.title
mBinding.certificateDetailsDescTv.text = mQuiz.course.title
mBinding.certificateDetailsDownloadBtn.setOnClickListener(this)
mBinding.certificateDetailsShareBtn.setOnClickListener(this)
}
private fun initQuizCertMarks() {
mBinding.certificateDetailsGradeKeyTv.text = getString(R.string.grade)
mBinding.certificateDetailsGradeTv.text = mQuiz.passMark.toString()
mBinding.certificateDetailsPassGradeImg.setImageResource(R.drawable.ic_chart)
mBinding.certificateDetailsPassGradeKeyTv.text = getString(R.string.average)
mBinding.certificateDetailsPassGradeTv.text = mQuiz.averageGrade.toString()
mBinding.certificateDetailsTakenDateImg.setImageResource(R.drawable.ic_user)
mBinding.certificateDetailsTakenDateKeyTv.text = getString(R.string.total_students)
mBinding.certificateDetailsTakenDateTv.text = mQuiz.participatedCount.toString()
mBinding.certificateDetailsCertIdImg.setImageResource(R.drawable.ic_calendar)
mBinding.certificateDetailsCertIdKeyTv.text = getString(R.string.date_created)
mBinding.certificateDetailsCertIdTv.text =
Utils.getDateFromTimestamp(mQuiz.course.createdAt)
}
private fun initResultCertMarks() {
mBinding.certificateDetailsGradeKeyTv.text = getString(R.string.your_grade)
mBinding.certificateDetailsGradeTv.text = mResult!!.userGrade.toString()
mBinding.certificateDetailsPassGradeImg.setImageResource(R.drawable.ic_done)
mBinding.certificateDetailsPassGradeKeyTv.text = getString(R.string.pass_grade)
mBinding.certificateDetailsPassGradeTv.text = mQuiz.passMark.toString()
mBinding.certificateDetailsTakenDateImg.setImageResource(R.drawable.ic_calendar)
mBinding.certificateDetailsTakenDateKeyTv.text = getString(R.string.taken_date)
mBinding.certificateDetailsTakenDateTv.text = Utils.getDateFromTimestamp(mQuiz.createdAt)
mBinding.certificateDetailsCertIdImg.setImageResource(R.drawable.ic_more_circle)
mBinding.certificateDetailsCertIdKeyTv.text = getString(R.string.cert_id)
if (mResult!!.certificate != null) {
mBinding.certificateDetailsCertIdTv.text = mResult!!.certificate!!.id.toString()
} else {
mBinding.certificateDetailsCertIdTv.text = "-"
}
}
override fun onClick(v: View?) {
when (v?.id) {
R.id.certificateDetailsDownloadBtn -> {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M && ActivityCompat.checkSelfPermission(
requireContext(),
Manifest.permission.READ_EXTERNAL_STORAGE
) != PackageManager.PERMISSION_GRANTED || ActivityCompat.checkSelfPermission(
requireContext(),
Manifest.permission.WRITE_EXTERNAL_STORAGE
) != PackageManager.PERMISSION_GRANTED
) {
mStoragePermissionResultLauncher.launch(
arrayOf(
Manifest.permission.WRITE_EXTERNAL_STORAGE,
Manifest.permission.READ_EXTERNAL_STORAGE
)
)
} else {
downloadCert(true)
}
}
R.id.certificateDetailsShareBtn -> {
if (mSavedCertPath != null) {
try {
Utils.shareFile(
requireContext(),
getString(R.string.share_certificate_with),
FileProvider.getUriForFile(
requireContext(),
requireContext().packageName + ".provider",
File(mSavedCertPath!!)
)
)
} catch (ex: Exception) {
}
} else {
downloadCert(false)
}
}
R.id.certificateDetailsLatestStdViewAllBtn -> {
val bundle = Bundle()
bundle.putParcelableArrayList(App.RESULT, mCertStudents)
val frag = CertStudentsFrag()
frag.arguments = bundle
(activity as MainActivity).transact(frag)
}
}
}
private fun downloadCert(toDownloads: Boolean) {
val bundle = Bundle()
if (mResult!!.certificate == null) {
bundle.putString(
App.URL,
BuildVars.CERT_DOWNLOAD_URL.replace("{}", mResult!!.id.toString())
)
bundle.putBoolean(App.FILE_NAME_FROM_HEADER, true)
} else {
bundle.putString(App.URL, mResult!!.certificate!!.img)
}
bundle.putString(App.DIR, App.Companion.Directory.CERTIFICATE.value())
bundle.putBoolean(App.TO_DOWNLOADS, toDownloads)
val loadingDialog = ProgressiveLoadingDialog()
loadingDialog.setOnFileSavedListener(object : ItemCallback<String> {
override fun onItem(filePath: String, vararg args: Any) {
mSavedCertPath = filePath
if (mResult!!.certificate == null) {
onFileSaved(mSavedCertPath!!)
}
if (toDownloads) {
ToastMaker.show(
requireContext(),
getString(R.string.success),
getString(R.string.file_saved_in_your_downloads),
ToastMaker.Type.SUCCESS
)
} else {
onClick(mBinding.certificateDetailsShareBtn)
}
}
})
loadingDialog.arguments = bundle
loadingDialog.show(childFragmentManager, null)
}
fun onStudentsReceived(data: List<QuizResult>) {
if (data.isNotEmpty()) {
mBinding.certificateDetailsLatestStdRv.adapter = CertStudentRvAdapter(data)
mBinding.certificateDetailsLatestStdTv.visibility = View.VISIBLE
mBinding.certificateDetailsLatestStdRv.visibility = View.VISIBLE
if (data.size > 5) {
mCertStudents = data as ArrayList<QuizResult>
mBinding.certificateDetailsLatestStdViewAllBtn.setOnClickListener(this)
mBinding.certificateDetailsLatestStdViewAllBtn.visibility = View.VISIBLE
}
}
}
fun onFileSaved(filePath: String) {
Glide.with(requireContext()).load(File(filePath))
.into(mBinding.certificateDetailsImg)
}
}
| 0 | Kotlin | 0 | 0 | 0f4cc0534a3c77a8edfb0fa043fb2ed7e2707250 | 12,772 | neuronet | Apache License 2.0 |
app/src/main/java/co/nimblehq/data/model/AuthData.kt | minhnimble | 295,922,281 | false | {"Kotlin": 251393, "Java": 6013, "XSLT": 1824, "Ruby": 753} | package co.nimblehq.data.model
import co.nimblehq.data.api.response.auth.OAuthResponse
data class AuthData(
val accessToken: String = "",
val createdAt: Long = 0,
val expiresIn: Long = 0,
val refreshToken: String = "",
val tokenType: String = ""
) {
val isValid: Boolean
get() = accessToken.isNotEmpty() && tokenType.isNotEmpty() && refreshToken.isNotEmpty()
val isExpired: Boolean
get() = System.currentTimeMillis() / 1000 >= createdAt + expiresIn
}
fun OAuthResponse.toAuthData() = with(data.attributes) {
AuthData(
accessToken,
createdAt,
expiresIn,
refreshToken,
tokenType
)
}
| 1 | Kotlin | 1 | 1 | 98266e2455f5f5c5f532830faab19402e56e71cc | 677 | internal-certification-surveys-android | MIT License |
pstatus-notifications-workflow-ktor/src/main/kotlin/cache/InMemoryCache.kt | CDCgov | 679,761,337 | false | {"Kotlin": 644056, "Python": 14605, "TypeScript": 7647, "Java": 4266, "JavaScript": 2382} | package gov.cdc.ocio.processingnotifications.cache
import gov.cdc.ocio.processingnotifications.model.*
import java.util.concurrent.locks.ReentrantReadWriteLock
import kotlin.collections.HashMap
/**
* This class represents InMemoryCache to maintain state of the data at any given point for
* subscription of rules and subscriber for the rules
*/
object InMemoryCache {
private val readWriteLock = ReentrantReadWriteLock()
/*
Cache to store "SubscriptionId -> Subscriber Info (Email or Url and type of subscription)"
subscriberCache = HashMap<String, NotificationSubscriber>()
*/
private val subscriberCache = HashMap<String, MutableList<NotificationSubscriptionResponse>>()
/**
* If Success, this method updates Two Caches for New Subscription:
* a. First Cache with subscription Rule and respective subscriptionId,
* if it doesn't exist,or it returns existing subscription id.
* b. Second cache is subscriber cache where the subscription id is mapped to emailId of subscriber
* or websocket url with the type of subscription
*
* @return String
*/
fun updateCacheForSubscription(workflowId:String, baseSubscription: BaseSubscription): WorkflowSubscriptionResult {
// val uuid = generateUniqueSubscriptionId()
try {
updateSubscriberCache(workflowId,
NotificationSubscriptionResponse(subscriptionId = workflowId, subscription = baseSubscription))
return WorkflowSubscriptionResult(subscriptionId = workflowId, message = "Successfully subscribed for $workflowId", deliveryReference = baseSubscription.deliveryReference)
}
catch (e: Exception){
return WorkflowSubscriptionResult(subscriptionId = workflowId, message = e.message, deliveryReference = baseSubscription.deliveryReference)
}
}
fun updateCacheForUnSubscription(workflowId:String): WorkflowSubscriptionResult {
try {
unsubscribeSubscriberCache(workflowId)
return WorkflowSubscriptionResult(subscriptionId = workflowId, message = "Successfully unsubscribed Id = $workflowId", deliveryReference = "")
}
catch (e: Exception){
return WorkflowSubscriptionResult(subscriptionId = workflowId, message = e.message,"")
}
}
/**
* This method adds to the subscriber cache the new entry of subscriptionId to the NotificationSubscriber
*
* @param subscriptionId String
*/
private fun updateSubscriberCache(subscriptionId: String,
notificationSubscriptionResponse: NotificationSubscriptionResponse) {
//logger.debug("Subscriber added in subscriber cache")
readWriteLock.writeLock().lock()
try {
subscriberCache.putIfAbsent(subscriptionId, mutableListOf())
subscriberCache[subscriptionId]?.add(notificationSubscriptionResponse)
} finally {
readWriteLock.writeLock().unlock()
}
}
/**
* This method unsubscribes the subscriber from the subscriber cache
* by removing the Map<K,V>[subscriptionId, NotificationSubscriber]
* entry from cache but keeps the susbscriptionRule in subscription
* cache for any other existing subscriber needs.
*
* @param subscriptionId String
* @return Boolean
*/
private fun unsubscribeSubscriberCache(subscriptionId: String): Boolean {
if (subscriberCache.containsKey(subscriptionId)) {
val subscribers = subscriberCache[subscriptionId]?.filter { it.subscriptionId == subscriptionId }.orEmpty().toMutableList()
readWriteLock.writeLock().lock()
try {
subscriberCache.remove(subscriptionId, subscribers)
} finally {
readWriteLock.writeLock().unlock()
}
return true
} else {
throw Exception("Subscription doesn't exist")
}
}
} | 8 | Kotlin | 0 | 2 | dc4faece607e12726e0bbc09159ca808e7909c13 | 4,008 | data-exchange-processing-status | Apache License 2.0 |
src/test/kotlin/fr/o80/aoc/day03/part1/Day03Part1UnitTest.kt | olivierperez | 310,899,127 | false | null | package fr.o80.aoc.day03.part1
import fr.o80.aoc.day03.Day03
import org.junit.jupiter.api.Assertions.*
import org.junit.jupiter.params.ParameterizedTest
import org.junit.jupiter.params.provider.Arguments
import org.junit.jupiter.params.provider.MethodSource
import java.util.stream.Stream
internal class Day03Part1UnitTest {
private val day = Day03()
@ParameterizedTest
@MethodSource("provide")
fun computePart1(input: String, expectedOutput: Int) {
// when
val result = day.part1(day.parse1(input))
// then
assertEquals(expectedOutput, result)
}
companion object {
@JvmStatic
fun provide(): Stream<Arguments> {
return Stream.of(
Arguments.of(input_d3_p1_1, result_d3_p1_1),
Arguments.of(input_d3_p1_2, result_d3_p1_2),
Arguments.of(input_d3_p1_3, result_d3_p1_3),
Arguments.of(exercise_d3_p1, -1),
)
}
}
}
| 0 | Kotlin | 1 | 2 | c92001b5d4651e67e17c20eb8ddc2ac62b14f2c2 | 987 | AdventOfCode-KotlinStarterKit | Apache License 2.0 |
protocol/src/commonMain/kotlin/com/sourceplusplus/protocol/artifact/trace/Trace.kt | kaizhiyu | 327,907,510 | true | {"Kotlin": 571623, "Java": 10932, "CSS": 8168, "JavaScript": 3693, "HTML": 2027} | package com.sourceplusplus.protocol.artifact.trace
import com.sourceplusplus.protocol.Serializers
import kotlinx.datetime.Instant
import kotlinx.serialization.Serializable
/**
* todo: description.
*
* @since 0.1.0
* @author [Brandon Fergerson](mailto:[email protected])
*/
@Serializable
data class Trace(
val key: String? = null,
val operationNames: List<String>,
val duration: Int,
@Serializable(with = Serializers.InstantKSerializer::class)
val start: Instant,
val error: Boolean? = null,
val traceIds: List<String>,
val prettyDuration: String? = null,
val partial: Boolean = false,
val segmentId: String? = null
)
| 0 | null | 0 | 0 | f5f1549c1e0d5a65bf1745bbbef69702854e99ee | 668 | SourceMarker | Apache License 2.0 |
app/src/main/java/ar/com/play2play/model/Loading.kt | UTN-FRBA-Mobile | 365,641,042 | false | null | package ar.com.play2play.model
open class LoadingScreen(val isLoading: Boolean)
class VisibleLoadingScreen(val waitingText: String): LoadingScreen(isLoading = true)
object HiddenLoadingScreen: LoadingScreen(isLoading = false)
| 0 | Kotlin | 1 | 0 | 3212cb762824af2e12d3a7492ef66cc72326f3d0 | 229 | Play2Play | MIT License |
app/src/main/java/com/ls/localsky/ui/components/HourlyWeatherForecast.kt | TULocalSky | 747,823,407 | false | {"Kotlin": 90231} | package com.ls.localsky.ui.components
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.lazy.LazyRow
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material3.Card
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.BlurredEdgeTreatment
import androidx.compose.ui.draw.blur
import androidx.compose.ui.draw.clip
import androidx.compose.ui.draw.shadow
import androidx.compose.ui.graphics.Brush
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import com.ls.localsky.viewmodels.WeatherViewModelLS
@Composable
fun HourlyWeatherForecast(
viewModel: WeatherViewModelLS,
){
viewModel.weatherDataState.weatherData?.hourly?.let { hourly ->
Card(
modifier = Modifier
.clip(shape = RoundedCornerShape(0.dp, 20.dp, 0.dp, 20.dp))
.padding(16.dp)
// .blur(
// radiusX = 10.dp,
// radiusY = 10.dp,
// edgeTreatment = BlurredEdgeTreatment(RoundedCornerShape(8.dp))
// )
.shadow(
elevation = 10.dp,
shape = RoundedCornerShape(8.dp)
)
) {
Column(
modifier = Modifier
.fillMaxWidth()
.background(brush = Brush.linearGradient(
listOf(MaterialTheme.colorScheme.primary, MaterialTheme.colorScheme.secondary)))
.padding(16.dp),
verticalArrangement = Arrangement.SpaceBetween
) {
Text(
text = "Hourly Forecast",
fontSize = 18.sp,
)
Spacer(modifier = Modifier.height(12.dp))
LazyRow(content = {
items(12) { weatherDataIndex ->
HourlyWeatherDisplay(
weatherData = hourly.data[weatherDataIndex],
modifier = Modifier
.height(120.dp)
.padding(horizontal = 16.dp)
.background(Color.Transparent)
)
}
})
}
}
}
} | 9 | Kotlin | 0 | 0 | b993227f0f545bc45c8a9a73dc5f9cf91204dcfc | 2,816 | localsky | MIT License |
app/src/main/java/com/tompee/arctictern/main/MainActivity.kt | tompee26 | 405,841,505 | false | {"Kotlin": 140845, "Shell": 288} | package com.tompee.arctictern.main
import androidx.activity.ComponentActivity
class MainActivity : ComponentActivity()
| 0 | Kotlin | 0 | 1 | 5d9ae7abe4ba62a9936fac8406c164f2616adb92 | 121 | arctic-tern | MIT License |
src/main/kotlin/me/melijn/melijnbot/database/role/SelfRoleWrapper.kt | ToxicMushroom | 107,187,088 | false | null | package me.melijn.melijnbot.database.role
import com.fasterxml.jackson.module.kotlin.readValue
import me.melijn.melijnbot.database.HIGHER_CACHE
import me.melijn.melijnbot.database.NORMAL_CACHE
import me.melijn.melijnbot.objectMapper
import net.dv8tion.jda.api.utils.data.DataArray
class SelfRoleWrapper(private val selfRoleDao: SelfRoleDao) {
// guildId -> <selfRoleGroupName -> emotejiInfo (see SelfRoleDao for example)
suspend fun getMap(guildId: Long): Map<String, DataArray> {
val result = selfRoleDao.getCacheEntry(guildId, HIGHER_CACHE)?.let { map ->
objectMapper.readValue<Map<String, String>>(map).mapValues {
DataArray.fromJson(it.value)
}
}
if (result != null) return result
val map = selfRoleDao.getMap(guildId)
selfRoleDao.setCacheEntry(
guildId,
objectMapper.writeValueAsString(map.mapValues { it.value.toString() }),
NORMAL_CACHE
)
return map
}
suspend fun set(guildId: Long, groupName: String, emoteji: String, roleId: Long, chance: Int = 100) {
val map = getMap(guildId)
.toMutableMap()
val data = map.getOrDefault(groupName, DataArray.empty())
var containsEmoteji = false
for (i in 0 until data.length()) {
val entryData = data.getArray(i)
if (entryData.getString(0) == emoteji) {
containsEmoteji = true
val rolesArr = entryData.getArray(2)
for (j in 0 until rolesArr.length()) {
val roleInfoArr = rolesArr.getArray(j)
if (roleInfoArr.getLong(1) == roleId) {
rolesArr.remove(j)
break
}
}
rolesArr.add(
DataArray.empty()
.add(chance)
.add(roleId)
)
entryData.remove(2)
val boolValue = entryData.getBoolean(2)
entryData.remove(2)
entryData.add(rolesArr)
entryData.add(boolValue)
data.remove(i)
data.add(entryData)
break
}
}
if (!containsEmoteji) {
data.add(
DataArray.empty()
.add(emoteji)
.add("")
.add(
DataArray.empty().add(
DataArray.empty()
.add(chance)
.add(roleId)
)
).add(true)
)
}
map[groupName] = data
selfRoleDao.set(guildId, groupName, data.toString())
selfRoleDao.setCacheEntry(
guildId,
objectMapper.writeValueAsString(map.mapValues { it.value.toString() }), NORMAL_CACHE
)
}
suspend fun remove(guildId: Long, groupName: String, emoteji: String, roleId: Long) {
// map
val map = getMap(guildId)
.toMutableMap()
// layer1
val data = map.getOrDefault(groupName, DataArray.empty())
// inner list
for (i in 0 until data.length()) {
val entryData = data.getArray(i)
if (entryData.getString(0) == emoteji) {
val rolesArr = entryData.getArray(2)
for (j in 0 until rolesArr.length()) {
val roleInfoArr = rolesArr.getArray(j)
if (roleInfoArr.getLong(1) == roleId) {
rolesArr.remove(j)
break
}
}
// reconstruct array
entryData.remove(2)
val boolValue = entryData.getBoolean(2)
entryData.remove(2)
entryData.add(rolesArr)
entryData.add(boolValue)
data.remove(i)
data.add(entryData)
break
}
}
// putting pairs into map
map[groupName] = data
selfRoleDao.set(guildId, groupName, data.toString())
selfRoleDao.setCacheEntry(
guildId,
objectMapper.writeValueAsString(map.mapValues { it.value.toString() }),
NORMAL_CACHE
)
}
suspend fun remove(guildId: Long, groupName: String, emoteji: String) {
// map
val map = getMap(guildId)
.toMutableMap()
// layer1
val data = map.getOrDefault(groupName, DataArray.empty())
// inner list
for (i in 0 until data.length()) {
val entryData = data.getArray(i)
if (entryData.getString(0) == emoteji) {
data.remove(i)
break
}
}
// putting pairs into map
map[groupName] = data
selfRoleDao.set(guildId, groupName, data.toString())
selfRoleDao.setCacheEntry(
guildId,
objectMapper.writeValueAsString(map.mapValues { it.value.toString() }),
NORMAL_CACHE
)
}
suspend fun update(guildId: Long, groupName: String, data: DataArray) {
// map
val map = getMap(guildId)
.toMutableMap()
map[groupName] = data
selfRoleDao.set(guildId, groupName, data.toString())
selfRoleDao.setCacheEntry(
guildId,
objectMapper.writeValueAsString(map.mapValues { it.value.toString() }),
NORMAL_CACHE
)
}
suspend fun changeName(guildId: Long, name1: String, name2: String) {
val map = getMap(guildId).toMutableMap()
val data = map[name1]
data?.let {
map.remove(name1)
map[name2] = it
}
selfRoleDao.changeName(guildId, name1, name2)
selfRoleDao.setCacheEntry(
guildId,
objectMapper.writeValueAsString(map.mapValues { it.value.toString() }),
NORMAL_CACHE
)
}
} | 5 | null | 22 | 80 | 01107bbaad0e343d770b1e4124a5a9873b1bb5bd | 6,116 | Melijn | MIT License |
skiko/src/jvmMain/kotlin/org/jetbrains/skija/ImageFilter.kt | pa-dieter | 403,520,837 | true | {"Kotlin": 949848, "C++": 483039, "Objective-C++": 20299, "Dockerfile": 2368, "JavaScript": 1202, "Shell": 555} | @file:Suppress("NESTED_EXTERNAL_DECLARATION")
package org.jetbrains.skia
import org.jetbrains.skia.impl.Library.Companion.staticLoad
import org.jetbrains.skia.impl.RefCnt
import org.jetbrains.skia.impl.Native
import org.jetbrains.skia.impl.Stats
import org.jetbrains.skia.impl.reachabilityBarrier
import kotlin.jvm.JvmStatic
class ImageFilter internal constructor(ptr: Long) : RefCnt(ptr) {
companion object {
fun makeAlphaThreshold(
r: Region?,
innerMin: Float,
outerMax: Float,
input: ImageFilter?,
crop: IRect?
): ImageFilter {
return try {
Stats.onNativeCall()
ImageFilter(
_nMakeAlphaThreshold(
getPtr(
r
), innerMin, outerMax, getPtr(input), crop
)
)
} finally {
reachabilityBarrier(r)
reachabilityBarrier(input)
}
}
fun makeArithmetic(
k1: Float,
k2: Float,
k3: Float,
k4: Float,
enforcePMColor: Boolean,
bg: ImageFilter?,
fg: ImageFilter?,
crop: IRect?
): ImageFilter {
return try {
Stats.onNativeCall()
ImageFilter(
_nMakeArithmetic(
k1,
k2,
k3,
k4,
enforcePMColor,
getPtr(bg),
getPtr(fg),
crop
)
)
} finally {
reachabilityBarrier(bg)
reachabilityBarrier(fg)
}
}
fun makeBlend(blendMode: BlendMode, bg: ImageFilter?, fg: ImageFilter?, crop: IRect?): ImageFilter {
return try {
Stats.onNativeCall()
ImageFilter(
_nMakeBlend(
blendMode.ordinal,
getPtr(bg),
getPtr(fg),
crop
)
)
} finally {
reachabilityBarrier(bg)
reachabilityBarrier(fg)
}
}
fun makeBlur(
sigmaX: Float,
sigmaY: Float,
mode: FilterTileMode,
input: ImageFilter? = null,
crop: IRect? = null
): ImageFilter {
return try {
Stats.onNativeCall()
ImageFilter(
_nMakeBlur(
sigmaX,
sigmaY,
mode.ordinal,
getPtr(input),
crop
)
)
} finally {
reachabilityBarrier(input)
}
}
fun makeColorFilter(f: ColorFilter?, input: ImageFilter?, crop: IRect?): ImageFilter {
return try {
Stats.onNativeCall()
ImageFilter(
_nMakeColorFilter(
getPtr(
f
), getPtr(input), crop
)
)
} finally {
reachabilityBarrier(f)
reachabilityBarrier(input)
}
}
fun makeCompose(outer: ImageFilter?, inner: ImageFilter?): ImageFilter {
return try {
Stats.onNativeCall()
ImageFilter(
_nMakeCompose(
getPtr(
outer
), getPtr(inner)
)
)
} finally {
reachabilityBarrier(outer)
reachabilityBarrier(inner)
}
}
fun makeDisplacementMap(
x: ColorChannel,
y: ColorChannel,
scale: Float,
displacement: ImageFilter?,
color: ImageFilter?,
crop: IRect?
): ImageFilter {
return try {
Stats.onNativeCall()
ImageFilter(
_nMakeDisplacementMap(
x.ordinal,
y.ordinal,
scale,
getPtr(displacement),
getPtr(color),
crop
)
)
} finally {
reachabilityBarrier(displacement)
reachabilityBarrier(color)
}
}
fun makeDropShadow(
dx: Float,
dy: Float,
sigmaX: Float,
sigmaY: Float,
color: Int,
input: ImageFilter? = null,
crop: IRect? = null
): ImageFilter {
return try {
Stats.onNativeCall()
ImageFilter(
_nMakeDropShadow(
dx,
dy,
sigmaX,
sigmaY,
color,
getPtr(input),
crop
)
)
} finally {
reachabilityBarrier(input)
}
}
fun makeDropShadowOnly(
dx: Float,
dy: Float,
sigmaX: Float,
sigmaY: Float,
color: Int,
input: ImageFilter? = null,
crop: IRect? = null
): ImageFilter {
return try {
Stats.onNativeCall()
ImageFilter(
_nMakeDropShadowOnly(
dx,
dy,
sigmaX,
sigmaY,
color,
getPtr(input),
crop
)
)
} finally {
reachabilityBarrier(input)
}
}
fun makeImage(image: Image): ImageFilter {
val r: Rect = Rect.makeWH(image.width.toFloat(), image.height.toFloat())
return makeImage(image, r, r, SamplingMode.DEFAULT)
}
fun makeImage(image: Image?, src: Rect, dst: Rect, mode: SamplingMode): ImageFilter {
return try {
Stats.onNativeCall()
ImageFilter(
_nMakeImage(
getPtr(
image
),
src.left,
src.top,
src.right,
src.bottom,
dst.left,
dst.top,
dst.right,
dst.bottom,
mode._pack()
)
)
} finally {
reachabilityBarrier(image)
}
}
fun makeMagnifier(r: Rect, inset: Float, input: ImageFilter?, crop: IRect?): ImageFilter {
return try {
Stats.onNativeCall()
ImageFilter(
_nMakeMagnifier(
r.left,
r.top,
r.right,
r.bottom,
inset,
getPtr(input),
crop
)
)
} finally {
reachabilityBarrier(input)
}
}
fun makeMatrixConvolution(
kernelW: Int,
kernelH: Int,
kernel: FloatArray?,
gain: Float,
bias: Float,
offsetX: Int,
offsetY: Int,
tileMode: FilterTileMode,
convolveAlpha: Boolean,
input: ImageFilter?,
crop: IRect?
): ImageFilter {
return try {
Stats.onNativeCall()
ImageFilter(
_nMakeMatrixConvolution(
kernelW,
kernelH,
kernel,
gain,
bias,
offsetX,
offsetY,
tileMode.ordinal,
convolveAlpha,
getPtr(input),
crop
)
)
} finally {
reachabilityBarrier(input)
}
}
fun makeMatrixTransform(matrix: Matrix33, mode: SamplingMode, input: ImageFilter?): ImageFilter {
return try {
Stats.onNativeCall()
ImageFilter(
_nMakeMatrixTransform(
matrix.mat,
mode._pack(),
getPtr(input)
)
)
} finally {
reachabilityBarrier(input)
}
}
fun makeMerge(filters: Array<ImageFilter?>, crop: IRect?): ImageFilter {
return try {
Stats.onNativeCall()
val filterPtrs = LongArray(filters.size)
filterPtrs.forEachIndexed { i: Int, _: Long -> getPtr(filters[i]) }
ImageFilter(_nMakeMerge(filterPtrs, crop))
} finally {
reachabilityBarrier(filters)
}
}
fun makeOffset(dx: Float, dy: Float, input: ImageFilter?, crop: IRect?): ImageFilter {
return try {
Stats.onNativeCall()
ImageFilter(
_nMakeOffset(
dx,
dy,
getPtr(input),
crop
)
)
} finally {
reachabilityBarrier(input)
}
}
fun makePaint(paint: Paint?, crop: IRect?): ImageFilter {
return try {
Stats.onNativeCall()
ImageFilter(
_nMakePaint(
getPtr(
paint
), crop
)
)
} finally {
reachabilityBarrier(paint)
}
}
fun makeTile(src: Rect, dst: Rect, input: ImageFilter?): ImageFilter {
return try {
Stats.onNativeCall()
ImageFilter(
_nMakeTile(
src.left,
src.top,
src.right,
src.bottom,
dst.left,
dst.top,
dst.right,
dst.bottom,
getPtr(input)
)
)
} finally {
reachabilityBarrier(input)
}
}
fun makeDilate(rx: Float, ry: Float, input: ImageFilter?, crop: IRect?): ImageFilter {
return try {
Stats.onNativeCall()
ImageFilter(
_nMakeDilate(
rx,
ry,
getPtr(input),
crop
)
)
} finally {
reachabilityBarrier(input)
}
}
fun makeErode(rx: Float, ry: Float, input: ImageFilter?, crop: IRect?): ImageFilter {
return try {
Stats.onNativeCall()
ImageFilter(
_nMakeErode(
rx,
ry,
getPtr(input),
crop
)
)
} finally {
reachabilityBarrier(input)
}
}
fun makeDistantLitDiffuse(
x: Float,
y: Float,
z: Float,
lightColor: Int,
surfaceScale: Float,
kd: Float,
input: ImageFilter?,
crop: IRect?
): ImageFilter {
return try {
Stats.onNativeCall()
ImageFilter(
_nMakeDistantLitDiffuse(
x,
y,
z,
lightColor,
surfaceScale,
kd,
getPtr(input),
crop
)
)
} finally {
reachabilityBarrier(input)
}
}
fun makePointLitDiffuse(
x: Float,
y: Float,
z: Float,
lightColor: Int,
surfaceScale: Float,
kd: Float,
input: ImageFilter?,
crop: IRect?
): ImageFilter {
return try {
Stats.onNativeCall()
ImageFilter(
_nMakePointLitDiffuse(
x,
y,
z,
lightColor,
surfaceScale,
kd,
getPtr(input),
crop
)
)
} finally {
reachabilityBarrier(input)
}
}
fun makeSpotLitDiffuse(
x0: Float,
y0: Float,
z0: Float,
x1: Float,
y1: Float,
z1: Float,
falloffExponent: Float,
cutoffAngle: Float,
lightColor: Int,
surfaceScale: Float,
kd: Float,
input: ImageFilter?,
crop: IRect?
): ImageFilter {
return try {
Stats.onNativeCall()
ImageFilter(
_nMakeSpotLitDiffuse(
x0,
y0,
z0,
x1,
y1,
z1,
falloffExponent,
cutoffAngle,
lightColor,
surfaceScale,
kd,
getPtr(input),
crop
)
)
} finally {
reachabilityBarrier(input)
}
}
fun makeDistantLitSpecular(
x: Float,
y: Float,
z: Float,
lightColor: Int,
surfaceScale: Float,
ks: Float,
shininess: Float,
input: ImageFilter?,
crop: IRect?
): ImageFilter {
return try {
Stats.onNativeCall()
ImageFilter(
_nMakeDistantLitSpecular(
x,
y,
z,
lightColor,
surfaceScale,
ks,
shininess,
getPtr(input),
crop
)
)
} finally {
reachabilityBarrier(input)
}
}
fun makePointLitSpecular(
x: Float,
y: Float,
z: Float,
lightColor: Int,
surfaceScale: Float,
ks: Float,
shininess: Float,
input: ImageFilter?,
crop: IRect?
): ImageFilter {
return try {
Stats.onNativeCall()
ImageFilter(
_nMakePointLitSpecular(
x,
y,
z,
lightColor,
surfaceScale,
ks,
shininess,
getPtr(input),
crop
)
)
} finally {
reachabilityBarrier(input)
}
}
fun makeSpotLitSpecular(
x0: Float,
y0: Float,
z0: Float,
x1: Float,
y1: Float,
z1: Float,
falloffExponent: Float,
cutoffAngle: Float,
lightColor: Int,
surfaceScale: Float,
ks: Float,
shininess: Float,
input: ImageFilter?,
crop: IRect?
): ImageFilter {
return try {
Stats.onNativeCall()
ImageFilter(
_nMakeSpotLitSpecular(
x0,
y0,
z0,
x1,
y1,
z1,
falloffExponent,
cutoffAngle,
lightColor,
surfaceScale,
ks,
shininess,
getPtr(input),
crop
)
)
} finally {
reachabilityBarrier(input)
}
}
@JvmStatic
external fun _nMakeAlphaThreshold(
regionPtr: Long,
innerMin: Float,
outerMax: Float,
input: Long,
crop: IRect?
): Long
@JvmStatic external fun _nMakeArithmetic(
k1: Float,
k2: Float,
k3: Float,
k4: Float,
enforcePMColor: Boolean,
bg: Long,
fg: Long,
crop: IRect?
): Long
@JvmStatic external fun _nMakeBlend(blendMode: Int, bg: Long, fg: Long, crop: IRect?): Long
@JvmStatic external fun _nMakeBlur(sigmaX: Float, sigmaY: Float, tileMode: Int, input: Long, crop: IRect?): Long
@JvmStatic external fun _nMakeColorFilter(colorFilterPtr: Long, input: Long, crop: IRect?): Long
@JvmStatic external fun _nMakeCompose(outer: Long, inner: Long): Long
@JvmStatic external fun _nMakeDisplacementMap(
xChan: Int,
yChan: Int,
scale: Float,
displacement: Long,
color: Long,
crop: IRect?
): Long
@JvmStatic external fun _nMakeDropShadow(
dx: Float,
dy: Float,
sigmaX: Float,
sigmaY: Float,
color: Int,
input: Long,
crop: IRect?
): Long
@JvmStatic external fun _nMakeDropShadowOnly(
dx: Float,
dy: Float,
sigmaX: Float,
sigmaY: Float,
color: Int,
input: Long,
crop: IRect?
): Long
@JvmStatic external fun _nMakeImage(
image: Long,
l0: Float,
t0: Float,
r0: Float,
b0: Float,
l1: Float,
t1: Float,
r1: Float,
b1: Float,
samplingMode: Long
): Long
@JvmStatic external fun _nMakeMagnifier(
l: Float,
t: Float,
r: Float,
b: Float,
inset: Float,
input: Long,
crop: IRect?
): Long
@JvmStatic external fun _nMakeMatrixConvolution(
kernelW: Int,
kernelH: Int,
kernel: FloatArray?,
gain: Float,
bias: Float,
offsetX: Int,
offsetY: Int,
tileMode: Int,
convolveAlpha: Boolean,
input: Long,
crop: IRect?
): Long
@JvmStatic external fun _nMakeMatrixTransform(matrix: FloatArray?, samplingMode: Long, input: Long): Long
@JvmStatic external fun _nMakeMerge(filters: LongArray?, crop: IRect?): Long
@JvmStatic external fun _nMakeOffset(dx: Float, dy: Float, input: Long, crop: IRect?): Long
@JvmStatic external fun _nMakePaint(paint: Long, crop: IRect?): Long
@JvmStatic external fun _nMakePicture(picture: Long, l: Float, t: Float, r: Float, b: Float): Long
@JvmStatic external fun _nMakeTile(
l0: Float,
t0: Float,
r0: Float,
b0: Float,
l1: Float,
t1: Float,
r1: Float,
b1: Float,
input: Long
): Long
@JvmStatic external fun _nMakeDilate(rx: Float, ry: Float, input: Long, crop: IRect?): Long
@JvmStatic external fun _nMakeErode(rx: Float, ry: Float, input: Long, crop: IRect?): Long
@JvmStatic external fun _nMakeDistantLitDiffuse(
x: Float,
y: Float,
z: Float,
lightColor: Int,
surfaceScale: Float,
kd: Float,
input: Long,
crop: IRect?
): Long
@JvmStatic external fun _nMakePointLitDiffuse(
x: Float,
y: Float,
z: Float,
lightColor: Int,
surfaceScale: Float,
kd: Float,
input: Long,
crop: IRect?
): Long
@JvmStatic external fun _nMakeSpotLitDiffuse(
x0: Float,
y0: Float,
z0: Float,
x1: Float,
y1: Float,
z1: Float,
falloffExponent: Float,
cutoffAngle: Float,
lightColor: Int,
surfaceScale: Float,
kd: Float,
input: Long,
crop: IRect?
): Long
@JvmStatic external fun _nMakeDistantLitSpecular(
x: Float,
y: Float,
z: Float,
lightColor: Int,
surfaceScale: Float,
ks: Float,
shininess: Float,
input: Long,
crop: IRect?
): Long
@JvmStatic external fun _nMakePointLitSpecular(
x: Float,
y: Float,
z: Float,
lightColor: Int,
surfaceScale: Float,
ks: Float,
shininess: Float,
input: Long,
crop: IRect?
): Long
@JvmStatic external fun _nMakeSpotLitSpecular(
x0: Float,
y0: Float,
z0: Float,
x1: Float,
y1: Float,
z1: Float,
falloffExponent: Float,
cutoffAngle: Float,
lightColor: Int,
surfaceScale: Float,
ks: Float,
shininess: Float,
input: Long,
crop: IRect?
): Long
init {
staticLoad()
}
}
} | 0 | null | 0 | 0 | c9dda21dea90abfa68db1fdf8932d8f12141c1f8 | 23,308 | skiko | Apache License 2.0 |
app/src/main/java/com/donfreddy/troona/domain/model/Album.kt | donfreddy | 736,820,576 | false | {"Kotlin": 215077} | /*
=============
Author: <NAME>
Github: https://github.com/donfreddy
Website: https://donfreddy.com
=============
Application: Troona - Music Player
Homepage: https://github.com/donfreddy/troona
License: https://github.com/donfreddy/troona/blob/main/LICENSE
Copyright: © 2023, <NAME>. All rights reserved.
=============
*/
package com.donfreddy.troona.domain.model
import kotlinx.datetime.LocalDateTime
data class Album(
val id: Long,
val songs: List<Song>,
) {
val title: String
get() = safeGetFirstSong().albumName
val artistId: Long
get() = safeGetFirstSong().artistId
val artistName: String
get() = safeGetFirstSong().artistName
val year: Int?
get() = safeGetFirstSong().year
val dateModified: LocalDateTime?
get() = safeGetFirstSong().dateModified
val numberOfSongs: Int
get() = songs.size
val albumArtist: String?
get() = safeGetFirstSong().albumArtist
fun safeGetFirstSong(): Song {
return songs.firstOrNull() ?: Song.EMPTY
}
companion object {
val EMPTY = Album(
id = -1,
songs = emptyList(),
)
}
}
| 0 | Kotlin | 0 | 0 | d91b051907a5f4b365e04fa6c959a07827c9fd54 | 1,097 | troona | MIT License |
buildSrc/src/main/kotlin/utils/PropertiesUtil.kt | ForteScarlet | 535,336,835 | false | null | package utils
import org.gradle.api.provider.Property
import java.time.Duration
import java.util.concurrent.TimeUnit
fun systemProperty(propKey: String, envKey: String = propKey): String? {
return System.getProperty(propKey, System.getenv(envKey))
}
infix fun <T> Property<T>.by(value: T) {
set(value)
}
infix fun Property<Duration>.by(value: Long): DurationHolder = DurationHolder(this, value)
data class DurationHolder(private val property: Property<Duration>, private val time: Long) {
infix fun unit(unit: TimeUnit) {
if (unit == TimeUnit.SECONDS) {
property.set(Duration.ofSeconds(time))
} else {
property.set(Duration.ofMillis(unit.toMillis(time)))
}
}
}
/**
* 是否发布 release
*/
fun isRelease(): Boolean = systemProperty("RELEASE").toBoolean()
/**
* 是否在CI中
*/
fun isCi(): Boolean = systemProperty("CI").toBoolean()
/**
* 是否自动配置gradle的发布
*/
fun isAutomatedGradlePluginPublishing(): Boolean = isCi() && systemProperty("PLUGIN_AUTO").toBoolean()
val isLinux: Boolean = systemProperty("os.name")?.contains("linux", true) ?: false
/**
* 如果在 CI 中,则必须是 linux 平台才运作。
* 如果不在 CI 中,始终运作。
*
*/
fun isMainPublishable(): Boolean = !isCi() || (isCi() && isLinux)
| 3 | null | 3 | 7 | c00c14897262a4dea87b6371695e83143d797911 | 1,236 | kotlin-suspend-transform-compiler-plugin | MIT License |
HTTPShortcuts/app/src/main/kotlin/ch/rmy/android/http_shortcuts/http/RequestUtil.kt | Waboodoo | 34,525,124 | false | {"Kotlin": 1970466, "HTML": 200869, "CSS": 2316, "Python": 1548} | package ch.rmy.android.http_shortcuts.http
import ch.rmy.android.http_shortcuts.exceptions.InvalidContentTypeException
import okhttp3.MediaType
import okhttp3.MediaType.Companion.toMediaType
import java.net.URLEncoder
object RequestUtil {
const val FORM_MULTIPART_BOUNDARY = "----53014704754052338"
const val FORM_MULTIPART_CONTENT_TYPE = "multipart/form-data; boundary=${FORM_MULTIPART_BOUNDARY}"
const val FORM_URLENCODE_CONTENT_TYPE = "application/x-www-form-urlencoded; charset=UTF-8"
private const val DEFAULT_CONTENT_TYPE = "text/plain"
private const val PARAMETER_ENCODING = "UTF-8"
fun encode(text: String): String =
URLEncoder.encode(text, PARAMETER_ENCODING)
fun sanitize(text: String): String =
text.replace("\"", "")
fun getMediaType(contentType: String?): MediaType =
try {
(contentType ?: DEFAULT_CONTENT_TYPE).toMediaType()
} catch (e: IllegalArgumentException) {
throw InvalidContentTypeException(contentType!!)
}
} | 31 | Kotlin | 87 | 999 | 34ec1652d431d581c3c275335eb4dbcf24ced9f5 | 1,035 | HTTP-Shortcuts | MIT License |
src/main/kotlin/org/arend/module/starter/ArendStarterInitialStep.kt | JetBrains | 96,068,447 | false | null | // Copyright 2000-2021 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.ide.starters.local.wizard
import com.intellij.ide.starters.JavaStartersBundle
import com.intellij.ide.starters.local.*
import com.intellij.ide.starters.shared.*
import com.intellij.ide.wizard.withVisualPadding
import com.intellij.openapi.Disposable
import com.intellij.openapi.application.PathManager
import com.intellij.openapi.application.impl.ApplicationInfoImpl
import com.intellij.openapi.diagnostic.logger
import com.intellij.openapi.roots.ui.configuration.validateJavaVersion
import com.intellij.openapi.ui.DialogPanel
import com.intellij.openapi.util.Disposer
import com.intellij.openapi.util.JDOMUtil
import com.intellij.openapi.util.io.FileUtil
import com.intellij.openapi.util.registry.Registry
import com.intellij.ui.SimpleListCellRenderer
import com.intellij.ui.dsl.builder.*
import com.intellij.util.concurrency.AppExecutorUtil
import com.intellij.util.concurrency.annotations.RequiresBackgroundThread
import com.intellij.util.io.HttpRequests
import com.intellij.util.io.exists
import com.intellij.util.text.nullize
import com.intellij.util.ui.UIUtil.invokeLaterIfNeeded
import org.jdom.Element
import java.io.File
import java.net.SocketTimeoutException
import java.nio.file.Files
import java.nio.file.Path
import javax.swing.DefaultComboBoxModel
import javax.swing.JComponent
open class StarterInitialStep(contextProvider: StarterContextProvider) : CommonStarterInitialStep(
contextProvider.wizardContext,
contextProvider.starterContext,
contextProvider.moduleBuilder,
contextProvider.parentDisposable,
contextProvider.settings
) {
protected val moduleBuilder: StarterModuleBuilder = contextProvider.moduleBuilder
protected val starterContext: StarterContext = contextProvider.starterContext
private val starterPackProvider: () -> StarterPack = contextProvider.starterPackProvider
private val contentPanel: DialogPanel by lazy { createComponent() }
protected lateinit var languageRow: Row
@Volatile
private var isDisposed: Boolean = false
override fun getHelpId(): String? = moduleBuilder.getHelpId()
init {
Disposer.register(parentDisposable, Disposable {
isDisposed = true
})
}
override fun updateDataModel() {
starterContext.projectType = projectTypeProperty.get()
starterContext.language = languageProperty.get()
starterContext.group = groupId
starterContext.artifact = artifactId
starterContext.testFramework = testFrameworkProperty.get()
starterContext.includeExamples = exampleCodeProperty.get()
starterContext.gitIntegration = gitProperty.get()
wizardContext.projectName = entityName
wizardContext.setProjectFileDirectory(FileUtil.join(location, entityName))
val sdk = sdkProperty.get()
moduleBuilder.moduleJdk = sdk
if (wizardContext.project == null) {
wizardContext.projectJdk = sdk
}
}
override fun getComponent(): JComponent {
return contentPanel
}
private fun createComponent(): DialogPanel {
entityNameProperty.dependsOn(artifactIdProperty) { artifactId }
artifactIdProperty.dependsOn(entityNameProperty) { entityName }
// query dependencies from builder, called only once
val starterPack = starterPackProvider.invoke()
starterContext.starterPack = starterPack
updateStartersDependencies(starterPack)
return panel {
addProjectLocationUi()
addFieldsBefore(this)
if (starterSettings.applicationTypes.isNotEmpty()) {
row(JavaStartersBundle.message("title.project.app.type.label")) {
val applicationTypesModel = DefaultComboBoxModel<StarterAppType>()
applicationTypesModel.addAll(starterSettings.applicationTypes)
comboBox(applicationTypesModel, SimpleListCellRenderer.create("", StarterAppType::title))
.bindItem(applicationTypeProperty)
.columns(COLUMNS_MEDIUM)
bottomGap(BottomGap.SMALL)
}
}
if (starterSettings.languages.size > 1) {
row(JavaStartersBundle.message("title.project.language.label")) {
languageRow = this
segmentedButton(starterSettings.languages, StarterLanguage::title)
.bind(languageProperty)
bottomGap(BottomGap.SMALL)
}
}
if (starterSettings.projectTypes.isNotEmpty()) {
val messages = starterSettings.customizedMessages
row(messages?.projectTypeLabel ?: JavaStartersBundle.message("title.project.build.system.label")) {
segmentedButton(starterSettings.projectTypes, StarterProjectType::title, StarterProjectType::description)
.bind(projectTypeProperty)
bottomGap(BottomGap.SMALL)
}
}
if (starterSettings.testFrameworks.size > 1) {
row(JavaStartersBundle.message("title.project.test.framework.label")) {
segmentedButton(starterSettings.testFrameworks, StarterTestRunner::title)
.bind(testFrameworkProperty)
bottomGap(BottomGap.SMALL)
}
}
addGroupArtifactUi()
addSdkUi()
addSampleCodeUi()
addFieldsAfter(this)
}.withVisualPadding(topField = true)
}
override fun validate(): Boolean {
if (!validateFormFields(component, contentPanel, validatedTextComponents)) {
return false
}
if (!validateJavaVersion(sdkProperty, moduleBuilder.getMinJavaVersionInternal()?.toFeatureString(), moduleBuilder.presentableName)) {
return false
}
return true
}
private fun updateStartersDependencies(starterPack: StarterPack) {
val starters = starterPack.starters
AppExecutorUtil.getAppExecutorService().submit {
checkDependencyUpdates(starters)
}
}
@RequiresBackgroundThread
private fun checkDependencyUpdates(starters: List<Starter>) {
for (starter in starters) {
val localUpdates = loadStarterDependencyUpdatesFromFile(starter.id)
if (localUpdates != null) {
setStarterDependencyUpdates(starter.id, localUpdates)
return
}
val externalUpdates = loadStarterDependencyUpdatesFromNetwork(starter.id) ?: return
val (dependencyUpdates, resourcePath) = externalUpdates
if (isDisposed) return
val dependencyConfig = StarterUtils.parseDependencyConfig(dependencyUpdates, resourcePath)
if (isDisposed) return
saveStarterDependencyUpdatesToFile(starter.id, dependencyUpdates)
setStarterDependencyUpdates(starter.id, dependencyConfig)
}
}
@RequiresBackgroundThread
private fun loadStarterDependencyUpdatesFromFile(starterId: String): DependencyConfig? {
val configUpdateDir = File(PathManager.getTempPath(), getDependencyConfigUpdatesDirLocation(starterId))
val configUpdateFile = File(configUpdateDir, getPatchFileName(starterId))
if (!configUpdateFile.exists()
|| StarterUtils.isDependencyUpdateFileExpired(configUpdateFile)) {
return null
}
val resourcePath = configUpdateFile.absolutePath
return try {
StarterUtils.parseDependencyConfig(JDOMUtil.load(configUpdateFile), resourcePath)
}
catch (e: Exception) {
logger<StarterInitialStep>().warn("Failed to load starter dependency updates from file: $resourcePath. The file will be deleted.")
FileUtil.delete(configUpdateFile)
null
}
}
@RequiresBackgroundThread
private fun loadStarterDependencyUpdatesFromNetwork(starterId: String): Pair<Element, String>? {
val url = buildStarterPatchUrl(starterId) ?: return null
return try {
val content = HttpRequests.request(url)
.accept("application/xml")
.readString()
return JDOMUtil.load(content) to url
}
catch (e: Exception) {
if (e is HttpRequests.HttpStatusException
&& (e.statusCode == 403 || e.statusCode == 404)) {
logger<StarterInitialStep>().debug("No updates for $starterId: $url")
}
else if (e is SocketTimeoutException) {
logger<StarterInitialStep>().debug("Socket timeout for $starterId: $url")
}
else {
logger<StarterInitialStep>().warn("Unable to load external starter $starterId dependency updates from: $url", e)
}
null
}
}
@RequiresBackgroundThread
private fun saveStarterDependencyUpdatesToFile(starterId: String, dependencyConfigUpdate: Element) {
val configUpdateDir = Path.of(PathManager.getTempPath(), getDependencyConfigUpdatesDirLocation(starterId))
if (!configUpdateDir.exists()) {
Files.createDirectories(configUpdateDir)
}
val configUpdateFile = configUpdateDir.resolve(getPatchFileName(starterId))
JDOMUtil.write(dependencyConfigUpdate, configUpdateFile)
}
private fun setStarterDependencyUpdates(starterId: String, dependencyConfigUpdate: DependencyConfig) {
invokeLaterIfNeeded {
if (isDisposed) return@invokeLaterIfNeeded
starterContext.startersDependencyUpdates[starterId] = dependencyConfigUpdate
}
}
private fun buildStarterPatchUrl(starterId: String): String? {
val host = Registry.stringValue("starters.dependency.update.host").nullize(true) ?: return null
val ideVersion = ApplicationInfoImpl.getShadowInstance().let { "${it.majorVersion}.${it.minorVersion}" }
val patchFileName = getPatchFileName(starterId)
return "$host/starter/$starterId/$ideVersion/$patchFileName"
}
private fun getDependencyConfigUpdatesDirLocation(starterId: String): String = "framework-starters/$starterId/"
private fun getPatchFileName(starterId: String): String = "${starterId}_patch.pom"
} | 54 | null | 4912 | 90 | 7a6608a2e44369e11c5baad3ef2928d6f9c971b2 | 9,639 | intellij-arend | Apache License 2.0 |
vector/src/main/java/im/vector/app/features/crypto/recover/BootstrapViewState.kt | tchapgouv | 340,329,238 | false | null | /*
* Copyright (c) 2020 New Vector Ltd
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package im.vector.app.features.crypto.recover
import com.airbnb.mvrx.Async
import com.airbnb.mvrx.MavericksState
import com.airbnb.mvrx.Uninitialized
import com.nulabinc.zxcvbn.Strength
import im.vector.app.core.platform.WaitingViewData
import org.matrix.android.sdk.api.session.securestorage.SsssKeyCreationInfo
data class BootstrapViewState(
val setupMode: SetupMode,
val step: BootstrapStep = BootstrapStep.CheckingMigration,
val passphrase: String? = null,
val migrationRecoveryKey: String? = null,
val passphraseRepeat: String? = null,
val crossSigningInitialization: Async<Unit> = Uninitialized,
val passphraseStrength: Async<Strength> = Uninitialized,
val passphraseConfirmMatch: Async<Unit> = Uninitialized,
val recoveryKeyCreationInfo: SsssKeyCreationInfo? = null,
val initializationWaitingViewData: WaitingViewData? = null,
val recoverySaveFileProcess: Async<Unit> = Uninitialized
) : MavericksState {
constructor(args: BootstrapBottomSheet.Args) : this(setupMode = args.setUpMode)
}
| 91 | Kotlin | 418 | 9 | a2c060c687b0aa69af681138c5788d6933d19860 | 1,692 | tchap-android | Apache License 2.0 |
src/backend/archive/biz-archive/src/main/kotlin/com/tencent/bkrepo/archive/listener/StorageCompressListener.kt | TencentBlueKing | 548,243,758 | false | {"Kotlin": 13657594, "Vue": 1261332, "JavaScript": 683823, "Shell": 124343, "Lua": 100415, "SCSS": 34137, "Python": 25877, "CSS": 17382, "HTML": 13052, "Dockerfile": 4483, "Smarty": 3661, "Java": 423} | package com.tencent.bkrepo.archive.listener
import com.tencent.bkrepo.archive.constant.DEFAULT_KEY
import com.tencent.bkrepo.archive.event.StorageFileCompressedEvent
import com.tencent.bkrepo.archive.event.StorageFileUncompressedEvent
import com.tencent.bkrepo.archive.metrics.ArchiveMetrics
import com.tencent.bkrepo.common.api.constant.StringPool
import com.tencent.bkrepo.common.api.util.HumanReadable
import org.slf4j.LoggerFactory
import org.springframework.context.event.EventListener
import org.springframework.stereotype.Component
/**
* 存储压缩事件监听器
* */
@Component
class StorageCompressListener(val archiveMetrics: ArchiveMetrics) {
/**
* 压缩存储文件
* */
@EventListener(StorageFileCompressedEvent::class)
fun compress(event: StorageFileCompressedEvent) {
val key = event.storageCredentialsKey ?: DEFAULT_KEY
with(event) {
logger.info("Success to compress file $sha256 on $storageCredentialsKey,$throughput.")
if (compressed != -1L) {
val ratio = StringPool.calculateRatio(uncompressed, compressed)
val uncompressedSize = HumanReadable.size(uncompressed)
val compressedSize = HumanReadable.size(compressed)
val freeSize = uncompressed - compressed
val compressInfo = "$uncompressedSize->$compressedSize,${HumanReadable.size(freeSize)},ratio:$ratio"
logger.info("File[$sha256] compress info: $compressInfo.")
// 释放存储
archiveMetrics.getSizeCounter(ArchiveMetrics.Action.STORAGE_FREE, key).increment(freeSize.toDouble())
}
archiveMetrics.getCounter(ArchiveMetrics.Action.COMPRESSED, key).increment() // 压缩个数
archiveMetrics.getSizeCounter(ArchiveMetrics.Action.COMPRESSED, key)
.increment(throughput.bytes.toDouble()) // 压缩吞吐
archiveMetrics.getTimer(ArchiveMetrics.Action.COMPRESSED, key).record(throughput.duration) // 压缩时长
}
}
/**
* 解压存储文件
* */
@EventListener(StorageFileUncompressedEvent::class)
fun uncompress(event: StorageFileUncompressedEvent) {
with(event) {
logger.info("Success to uncompress file $sha256 on $storageCredentialsKey,$throughput")
val key = event.storageCredentialsKey ?: DEFAULT_KEY
val allocateSize = uncompressed - compressed
archiveMetrics.getSizeCounter(ArchiveMetrics.Action.STORAGE_ALLOCATE, key)
.increment(allocateSize.toDouble()) // 新增存储
archiveMetrics.getCounter(ArchiveMetrics.Action.UNCOMPRESSED, key).increment() // 解压个数
archiveMetrics.getSizeCounter(ArchiveMetrics.Action.UNCOMPRESSED, key)
.increment(throughput.bytes.toDouble()) // 解压吞吐
archiveMetrics.getTimer(ArchiveMetrics.Action.UNCOMPRESSED, key).record(throughput.duration) // 解压时长
}
}
companion object {
private val logger = LoggerFactory.getLogger(StorageCompressListener::class.java)
}
}
| 363 | Kotlin | 38 | 70 | 54b0c7ab20ddbd988387bac6c9143b594681e73c | 3,031 | bk-repo | MIT License |
sdk/src/main/kotlin/io/rover/sdk/ui/blocks/button/ButtonBlockViewModel.kt | RoverPlatform | 55,724,334 | false | null | package io.rover.sdk.ui.blocks.button
import io.rover.sdk.ui.blocks.concerns.background.BackgroundViewModelInterface
import io.rover.sdk.ui.blocks.concerns.border.BorderViewModelInterface
import io.rover.sdk.ui.layout.ViewType
import io.rover.sdk.ui.blocks.concerns.layout.BlockViewModelInterface
import io.rover.sdk.ui.blocks.concerns.text.TextViewModelInterface
internal class ButtonBlockViewModel(
blockViewModel: BlockViewModelInterface,
private val borderViewModel: BorderViewModelInterface,
private val backgroundViewModel: BackgroundViewModelInterface,
private val textViewModel: TextViewModelInterface
) : ButtonBlockViewModelInterface,
BlockViewModelInterface by blockViewModel,
BorderViewModelInterface by borderViewModel,
BackgroundViewModelInterface by backgroundViewModel,
TextViewModelInterface by textViewModel {
override val viewType: ViewType = ViewType.Button
}
| 16 | null | 13 | 6 | 1b6e627a1e4b3651d0cc9f6e78f995ed9e4a821a | 918 | rover-android | Apache License 2.0 |
sdk/src/main/kotlin/io/rover/sdk/ui/blocks/button/ButtonBlockViewModel.kt | RoverPlatform | 55,724,334 | false | null | package io.rover.sdk.ui.blocks.button
import io.rover.sdk.ui.blocks.concerns.background.BackgroundViewModelInterface
import io.rover.sdk.ui.blocks.concerns.border.BorderViewModelInterface
import io.rover.sdk.ui.layout.ViewType
import io.rover.sdk.ui.blocks.concerns.layout.BlockViewModelInterface
import io.rover.sdk.ui.blocks.concerns.text.TextViewModelInterface
internal class ButtonBlockViewModel(
blockViewModel: BlockViewModelInterface,
private val borderViewModel: BorderViewModelInterface,
private val backgroundViewModel: BackgroundViewModelInterface,
private val textViewModel: TextViewModelInterface
) : ButtonBlockViewModelInterface,
BlockViewModelInterface by blockViewModel,
BorderViewModelInterface by borderViewModel,
BackgroundViewModelInterface by backgroundViewModel,
TextViewModelInterface by textViewModel {
override val viewType: ViewType = ViewType.Button
}
| 16 | null | 13 | 6 | 1b6e627a1e4b3651d0cc9f6e78f995ed9e4a821a | 918 | rover-android | Apache License 2.0 |
app/src/main/java/com/skythrew/kattpad/api/Authentication.kt | Skythrew | 841,580,801 | false | {"Kotlin": 83254} | package com.skythrew.kattpad.api
import io.ktor.http.parameters
import io.ktor.http.setCookie
open class Authentication : com.skythrew.kattpad.api.config.Request() {
var loggedIn = false
suspend fun login(username: String, password: String) {
val loginResponse = this.simplePost("https://www.wattpad.com/login", parameters {
append("username", username)
append("password", <PASSWORD>)
})
val cookies = loginResponse.setCookie()
for (cookie in cookies) {
if (cookie.name == "token") {
loggedIn = true
break
}
}
}
} | 2 | Kotlin | 0 | 3 | 5b4b40b7e36ba07c3aa225e71fe766784acf4f3d | 650 | kattpad | MIT License |
corbind-swiperefreshlayout/src/main/kotlin/ru/ldralighieri/corbind/swiperefreshlayout/SwipeRefreshLayoutRefreshes.kt | LDRAlighieri | 201,738,972 | false | null | /*
* Copyright 2019 Vladimir Raupov
*
* 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 ru.ldralighieri.corbind.swiperefreshlayout
import androidx.annotation.CheckResult
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.channels.Channel
import kotlinx.coroutines.channels.ReceiveChannel
import kotlinx.coroutines.channels.actor
import kotlinx.coroutines.channels.awaitClose
import kotlinx.coroutines.coroutineScope
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.channelFlow
import kotlinx.coroutines.isActive
import ru.ldralighieri.corbind.internal.corbindReceiveChannel
/**
* Perform an action on refresh events on [SwipeRefreshLayout].
*
* *Warning:* The created actor uses [SwipeRefreshLayout.setOnRefreshListener]. Only one actor can
* be used at a time.
*
* @param scope Root coroutine scope
* @param capacity Capacity of the channel's buffer (no buffer by default)
* @param action An action to perform
*/
fun SwipeRefreshLayout.refreshes(
scope: CoroutineScope,
capacity: Int = Channel.RENDEZVOUS,
action: suspend () -> Unit
) {
val events = scope.actor<Unit>(Dispatchers.Main.immediate, capacity) {
for (ignored in channel) action()
}
setOnRefreshListener(listener(scope, events::trySend))
events.invokeOnClose { setOnRefreshListener(null) }
}
/**
* Perform an action on refresh events on [SwipeRefreshLayout], inside new [CoroutineScope].
*
* *Warning:* The created actor uses [SwipeRefreshLayout.setOnRefreshListener]. Only one actor can
* be used at a time.
*
* @param capacity Capacity of the channel's buffer (no buffer by default)
* @param action An action to perform
*/
suspend fun SwipeRefreshLayout.refreshes(
capacity: Int = Channel.RENDEZVOUS,
action: suspend () -> Unit
) = coroutineScope {
refreshes(this, capacity, action)
}
/**
* Create a channel of refresh events on [SwipeRefreshLayout].
*
* *Warning:* The created channel uses [SwipeRefreshLayout.setOnRefreshListener]. Only one channel
* can be used at a time.
*
* Example:
*
* ```
* launch {
* swipeRefreshLayout.refreshes(scope)
* .consumeEach { /* handle refresh */ }
* }
* ```
*
* @param scope Root coroutine scope
* @param capacity Capacity of the channel's buffer (no buffer by default)
*/
@CheckResult
fun SwipeRefreshLayout.refreshes(
scope: CoroutineScope,
capacity: Int = Channel.RENDEZVOUS
): ReceiveChannel<Unit> = corbindReceiveChannel(capacity) {
setOnRefreshListener(listener(scope, ::trySend))
invokeOnClose { setOnRefreshListener(null) }
}
/**
* Create a flow of refresh events on [SwipeRefreshLayout].
*
* *Warning:* The created flow uses [SwipeRefreshLayout.setOnRefreshListener]. Only one flow can be
* used at a time.
*
* Example:
*
* ```
* swipeRefreshLayout.refreshes()
* .onEach { /* handle refresh */ }
* .launchIn(lifecycleScope) // lifecycle-runtime-ktx
* ```
*/
@CheckResult
fun SwipeRefreshLayout.refreshes(): Flow<Unit> = channelFlow {
setOnRefreshListener(listener(this, ::trySend))
awaitClose { setOnRefreshListener(null) }
}
@CheckResult
private fun listener(
scope: CoroutineScope,
emitter: (Unit) -> Unit
) = SwipeRefreshLayout.OnRefreshListener {
if (scope.isActive) { emitter(Unit) }
}
| 8 | null | 24 | 501 | 603a988f18f981c56a42d0712ab04bbfc7b50535 | 3,917 | Corbind | Apache License 2.0 |
uast/uast-kotlin-base/src/org/jetbrains/uast/kotlin/expressions/KotlinUImplicitReturnExpression.kt | JetBrains | 278,369,660 | false | null | /*
* Copyright 2010-2021 JetBrains s.r.o. and Kotlin Programming Language contributors.
* Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file.
*/
package org.jetbrains.uast.kotlin
import com.intellij.psi.PsiElement
import org.jetbrains.uast.UElement
import org.jetbrains.uast.UExpression
import org.jetbrains.uast.UReturnExpression
import org.jetbrains.uast.kotlin.internal.KotlinFakeUElement
class KotlinUImplicitReturnExpression(
givenParent: UElement?,
) : KotlinAbstractUExpression(givenParent), UReturnExpression, KotlinUElementWithType, KotlinFakeUElement {
override val psi: PsiElement?
get() = null
override lateinit var returnExpression: UExpression
override fun unwrapToSourcePsi(): List<PsiElement> {
return returnExpression.toSourcePsiFakeAware()
}
}
| 0 | Kotlin | 29 | 71 | b6789690db56407ae2d6d62746fb69dc99d68c84 | 867 | intellij-kotlin | Apache License 2.0 |
client/android/webrtc/src/main/java/com/qifan/webrtc/extensions/rtc/AudioExt.kt | underwindfall | 264,275,893 | false | null | /**
* Copyright (C) 2020 by Qifan YANG (@underwindfall)
*
* 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.qifan.webrtc.extensions.rtc
import android.content.Context
import com.qifan.webrtc.constants.LOCAL_AUDIO_TRACK_ID
import org.webrtc.AudioSource
import org.webrtc.AudioTrack
import org.webrtc.MediaConstraints
import org.webrtc.PeerConnectionFactory
import org.webrtc.audio.AudioDeviceModule
import org.webrtc.audio.JavaAudioDeviceModule
private const val AUDIO_ECHO_CANCELLATION_CONSTRAINT = "googEchoCancellation"
private const val AUDIO_AUTO_GAIN_CONTROL_CONSTRAINT = "googAutoGainControl"
private const val AUDIO_HIGH_PASS_FILTER_CONSTRAINT = "googHighpassFilter"
private const val AUDIO_NOISE_SUPPRESSION_CONSTRAINT = "googNoiseSuppression"
private const val AUDIO_LEVEL_CONTROL_CONSTRAINT = "levelControl"
/**
* create audio source
* @param constraints of audio source
*/
fun createAudioSource(
peerConnectionFactory: PeerConnectionFactory,
constraints: MediaConstraints = buildMediaConstraints()
): AudioSource {
return peerConnectionFactory.createAudioSource(constraints)
}
private fun buildMediaConstraints(): MediaConstraints {
return MediaConstraints().apply {
mandatory.add(MediaConstraints.KeyValuePair(AUDIO_ECHO_CANCELLATION_CONSTRAINT, "true"))
mandatory.add(MediaConstraints.KeyValuePair(AUDIO_AUTO_GAIN_CONTROL_CONSTRAINT, "true"))
mandatory.add(MediaConstraints.KeyValuePair(AUDIO_HIGH_PASS_FILTER_CONSTRAINT, "true"))
mandatory.add(MediaConstraints.KeyValuePair(AUDIO_NOISE_SUPPRESSION_CONSTRAINT, "true"))
mandatory.add(MediaConstraints.KeyValuePair(AUDIO_LEVEL_CONTROL_CONSTRAINT, "true"))
}
}
/**
* attach audio source to audio track
* @param id identifier of AudioTrack
* @param audioSource source of audio
*/
fun createAudioTrack(
peerConnectionFactory: PeerConnectionFactory,
id: String = LOCAL_AUDIO_TRACK_ID,
audioSource: AudioSource
): AudioTrack {
return peerConnectionFactory.createAudioTrack(id, audioSource)
}
/**
* Create Java audio device
*
* @param context context
* @return well configured audio device
*/
fun createJavaAudioDevice(context: Context): AudioDeviceModule {
// Set audio record error callbacks
val audioRecordErrorCallback = object : JavaAudioDeviceModule.AudioRecordErrorCallback {
override fun onWebRtcAudioRecordInitError(p0: String?) {
error(message = "onWebRtcAudioRecordInitError $p0")
}
override fun onWebRtcAudioRecordError(p0: String?) {
error(message = "onWebRtcAudioRecordError $p0")
}
override fun onWebRtcAudioRecordStartError(
p0: JavaAudioDeviceModule.AudioRecordStartErrorCode?,
p1: String?
) {
error(message = "onWebRtcAudioRecordStartError code => $p0 message=> $p1 ")
}
}
// Set audio track error callbacks
val audioTrackErrorCallback = object : JavaAudioDeviceModule.AudioTrackErrorCallback {
override fun onWebRtcAudioTrackError(p0: String?) {
error(message = "onWebRtcAudioTrackError $p0")
}
override fun onWebRtcAudioTrackStartError(
p0: JavaAudioDeviceModule.AudioTrackStartErrorCode?,
p1: String?
) {
error(message = "onWebRtcAudioTrackStartError code => $p0 message=> $p1")
}
override fun onWebRtcAudioTrackInitError(p0: String?) {
error(message = "onWebRtcAudioTrackInitError $p0")
}
}
return JavaAudioDeviceModule.builder(context)
.setUseHardwareAcousticEchoCanceler(true)
.setUseHardwareNoiseSuppressor(true)
.setAudioRecordErrorCallback(audioRecordErrorCallback)
.setAudioTrackErrorCallback(audioTrackErrorCallback)
.createAudioDeviceModule()
}
| 6 | Kotlin | 0 | 9 | 077bb037c7935845125c6cee48403dba65a81ac1 | 4,166 | webrtcsamples | Apache License 2.0 |
libraries/stdlib/native-wasm/src/kotlin/Exceptions.kt | JetBrains | 3,432,266 | false | {"Kotlin": 79571273, "Java": 6776465, "Swift": 4063829, "C": 2609744, "C++": 1957654, "Objective-C++": 175279, "JavaScript": 130754, "Python": 59855, "Shell": 34920, "Objective-C": 21463, "Lex": 21452, "Batchfile": 11382, "CSS": 11368, "Ruby": 10470, "Dockerfile": 9907, "Groovy": 7092, "EJS": 5241, "CMake": 4473, "HTML": 2699, "Puppet": 1698, "FreeMarker": 1393, "Roff": 725, "Scala": 80} | /*
* Copyright 2010-2024 JetBrains s.r.o. and Kotlin Programming Language contributors.
* Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file.
*/
package kotlin
public expect open class OutOfMemoryError : Error {
public constructor()
public constructor(message: String?)
} | 181 | Kotlin | 5748 | 49,172 | 33eb9cef3d146062c103f9853d772f0a1da0450e | 345 | kotlin | Apache License 2.0 |
kotlin-frontend/src/main/kotlin/org/jetbrains/kotlin/gradle/frontend/rollup/GenerateRollupConfigTask.kt | Kotlin | 74,062,359 | false | null | package org.jetbrains.kotlin.gradle.frontend.rollup
import groovy.json.*
import org.gradle.api.*
import org.gradle.api.tasks.*
import org.jetbrains.kotlin.gradle.frontend.util.*
import org.jetbrains.kotlin.gradle.frontend.webpack.GenerateWebPackConfigTask.Companion.handleFile
open class GenerateRollupConfigTask : DefaultTask() {
@Input
val projectDir = project.projectDir
@get:OutputFile
val configFile by lazy { project.buildDir.resolve(RollupConfigFileName) }
@get:Nested
val bundle by lazy { project.frontendExtension.bundles().filterIsInstance<RollupExtension>().singleOrNull() ?: throw GradleException("Only one rollup bundle is supported") }
@get:Input
val bundleFrom by lazy { kotlinOutput(project).absolutePath!! }
@get:Input
val destination by lazy { handleFile(project, project.frontendExtension.bundlesDirectory).resolve("${bundle.bundleName}.bundle.js").absolutePath!! }
@TaskAction
fun generate() {
configFile.bufferedWriter().use { out ->
out.appendln("""
import resolve from 'rollup-plugin-node-resolve';
import commonjs from 'rollup-plugin-commonjs';
export default {
entry: ${JsonOutput.toJson(bundleFrom)},
dest: ${JsonOutput.toJson(destination)},
format: 'iife',
moduleName: '${kotlinOutput(project).nameWithoutExtension}',
//sourceMap: 'inline',
plugins: [
resolve({
jsnext: true,
main: true,
browser: true,
}),
commonjs(),
],
};
""".trimIndent())
}
}
companion object {
val RollupConfigFileName = "rollup.config.js"
}
} | 86 | null | 69 | 573 | 6c10cc4f46df9ea419db282e3d2bb32d392f139e | 1,845 | kotlin-frontend-plugin | Apache License 2.0 |
app/src/main/java/com/borabor/movieapp/presentation/adapter/PersonAdapter.kt | bbor98 | 510,432,451 | false | null | package com.borabor.movieapp.presentation.adapter
import android.view.LayoutInflater
import android.view.ViewGroup
import androidx.databinding.DataBindingUtil
import androidx.recyclerview.widget.DiffUtil
import androidx.recyclerview.widget.ListAdapter
import androidx.recyclerview.widget.RecyclerView
import com.borabor.movieapp.R
import com.borabor.movieapp.databinding.ItemPersonBinding
import com.borabor.movieapp.domain.model.Person
class PersonAdapter(
private val isGrid: Boolean = false,
private val isCast: Boolean = false,
) : ListAdapter<Person, PersonAdapter.ViewHolder>(DIFF_CALLBACK) {
inner class ViewHolder(val view: ItemPersonBinding) : RecyclerView.ViewHolder(view.root) {
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
return ViewHolder(DataBindingUtil.inflate(LayoutInflater.from(parent.context), R.layout.item_person, parent, false))
}
override fun onBindViewHolder(holder: ViewHolder, position: Int) {
holder.view.apply {
isGrid = [email protected]
isCast = [email protected]
person = getItem(position)
}
}
companion object {
private val DIFF_CALLBACK = object : DiffUtil.ItemCallback<Person>() {
override fun areItemsTheSame(oldItem: Person, newItem: Person): Boolean {
return oldItem.id == newItem.id
}
override fun areContentsTheSame(oldItem: Person, newItem: Person): Boolean {
return oldItem == newItem
}
}
}
} | 0 | null | 4 | 15 | 369393ac387ed6c1c30939831b60c78b51f6f56a | 1,589 | movieapp-mvvm-clean-architecture | MIT License |
src/main/kotlin/io/github/kryszak/gwatlin/clients/achievements/AchievementsClient.kt | Kryszak | 214,791,260 | false | {"Kotlin": 443350, "Shell": 665} | package io.github.kryszak.gwatlin.clients.achievements
import io.github.kryszak.gwatlin.api.achievement.model.Achievement
import io.github.kryszak.gwatlin.api.achievement.model.category.AchievementCategory
import io.github.kryszak.gwatlin.api.achievement.model.daily.DailyAchievementList
import io.github.kryszak.gwatlin.api.achievement.model.group.AchievementGroup
import io.github.kryszak.gwatlin.http.BaseHttpClient
internal class AchievementsClient : BaseHttpClient() {
private val baseEndpoint: String = "achievements"
private val dailyEndpoint: String = "$baseEndpoint/daily"
private val dailyTomorrowEndpoint: String = "$dailyEndpoint/tomorrow"
private val groupEndpoint: String = "$baseEndpoint/groups"
private val categoryEndpoint: String = "$baseEndpoint/categories"
fun getAchievementIdsList(): List<Int> {
return getRequest(baseEndpoint)
}
fun getAchievementsByIds(ids: List<Int>): List<Achievement> {
val params = ids.joinToString(",")
return getRequest("$baseEndpoint?ids=$params")
}
fun getDailyAchievements(): DailyAchievementList {
return getRequest(dailyEndpoint)
}
fun getTomorrowDailyAchievements(): DailyAchievementList {
return getRequest(dailyTomorrowEndpoint)
}
fun getAchievementGroupIds(): List<String> {
return getRequest(groupEndpoint)
}
fun getAchievementGroup(id: String): AchievementGroup {
return getRequest("$groupEndpoint/$id")
}
fun getAchievementCategoryIds(): List<Int> {
return getRequest(categoryEndpoint)
}
fun getAchievementCategory(id: Int): AchievementCategory {
return getRequest("$categoryEndpoint/$id")
}
}
| 2 | Kotlin | 1 | 6 | 8bbcac5c1b44620abfc2db626b6af89f1f4e650a | 1,724 | gwatlin | MIT License |
platform/platform-impl/src/com/intellij/ide/gdpr/ui/Styles.kt | ingokegel | 284,920,751 | false | null | // Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.ide.gdpr.ui
import com.intellij.ui.JBColor
import com.intellij.ui.scale.JBUIScale
import com.intellij.util.ui.StartupUiUtil
import java.awt.Color
import javax.swing.text.SimpleAttributeSet
import javax.swing.text.StyleConstants
object Styles {
private val foregroundColor: Color = JBColor.BLACK
private val hintColor: Color = JBColor.GRAY
private val headerColor: Color = JBColor.BLACK
private val linkColor = Color(74, 120, 194)
private val lineSpacing = 0.1f
private val fontSize = StartupUiUtil.getLabelFont().size
private val h1FontSize = JBUIScale.scale(24)
private val h2FontSize = JBUIScale.scale(18)
val H1 = SimpleAttributeSet().apply {
StyleConstants.setForeground(this, headerColor)
StyleConstants.setFontSize(this, h1FontSize)
StyleConstants.setBold(this, true)
StyleConstants.setSpaceBelow(this, h1FontSize * 0.6f)
}
val H2 = SimpleAttributeSet().apply {
StyleConstants.setForeground(this, headerColor)
StyleConstants.setFontSize(this, h2FontSize)
StyleConstants.setBold(this, true)
StyleConstants.setSpaceAbove(this, h2FontSize * 0.8f)
}
val REGULAR = SimpleAttributeSet().apply {
StyleConstants.setForeground(this, foregroundColor)
StyleConstants.setFontSize(this, fontSize)
StyleConstants.setBold(this, false)
}
val BOLD = SimpleAttributeSet().apply {
StyleConstants.setForeground(this, foregroundColor)
StyleConstants.setBold(this, true)
}
val SUP = SimpleAttributeSet().apply {
StyleConstants.setForeground(this, foregroundColor)
StyleConstants.setSuperscript(this, true)
}
val LINK = SimpleAttributeSet().apply {
StyleConstants.setForeground(this, linkColor)
}
val PARAGRAPH = SimpleAttributeSet().apply {
StyleConstants.setForeground(this, foregroundColor)
StyleConstants.setLineSpacing(this, lineSpacing)
StyleConstants.setFontSize(this, fontSize)
StyleConstants.setSpaceAbove(this, fontSize * 0.6f)
}
val HINT = SimpleAttributeSet().apply {
StyleConstants.setForeground(this, hintColor)
StyleConstants.setLineSpacing(this, lineSpacing)
StyleConstants.setFontSize(this, fontSize)
StyleConstants.setSpaceAbove(this, fontSize * 0.6f)
}
} | 214 | null | 4829 | 2 | dc846ecb926c9d9589c1ed8a40fdb20e47874db9 | 2,511 | intellij-community | Apache License 2.0 |
compiler/testData/diagnostics/tests/multiplatform/actualClassifierMustHasTheSameMembersAsNonFinalExpectClassifierChecker/memberScopeMismatch_oldLanguageVersion.kt | JetBrains | 3,432,266 | false | null | // MODULE: m1-common
// FILE: common.kt
expect open class Foo {
fun existingMethod()
val existingParam: Int
}
// MODULE: m2-jvm()()(m1-common)
// FILE: jvm.kt
actual open class Foo {
actual fun existingMethod() {}
actual val existingParam: Int = 904
protected fun injectedMethod() {} // accidential override can happen with this injected fun. That's why it's prohibited
}
| 181 | null | 5748 | 49,172 | 33eb9cef3d146062c103f9853d772f0a1da0450e | 396 | kotlin | Apache License 2.0 |
data_content/src/main/java/com/cmj/wanandroid/data/content/ContentListAdapter.kt | mikechenmj | 590,477,705 | false | null | package com.cmj.wanandroid.content.home
import android.content.Context
import android.text.Html
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import androidx.core.view.isVisible
import androidx.paging.PagingDataAdapter
import androidx.recyclerview.widget.DiffUtil
import androidx.recyclerview.widget.RecyclerView.ViewHolder
import com.cmj.wanandroid.R
import com.cmj.wanandroid.content.home.ContentListAdapter.ContentAdapterHolder
import com.cmj.wanandroid.databinding.ContentItemBinding
import com.cmj.wanandroid.network.bean.Content
import kotlinx.android.synthetic.main.content_item.view.star
class ContentListAdapter constructor(
val context: Context,
val contentConfig: ContentConfig,
private val onItemClick: (Content) -> Unit = {},
private val onStarClick: (Content, View) -> Unit = {_, _ ->}
) : PagingDataAdapter<Content, ContentAdapterHolder>(object : DiffUtil.ItemCallback<Content>() {
override fun areItemsTheSame(oldItem: Content, newItem: Content): Boolean {
return oldItem.id == newItem.id
}
override fun areContentsTheSame(oldItem: Content, newItem: Content): Boolean {
return oldItem == newItem
}
}) {
override fun onBindViewHolder(holder: ContentAdapterHolder, position: Int) {
getItem(position)?.also {
holder.bind(it, position)
}
}
override fun getItemViewType(position: Int): Int {
return R.layout.content_item
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ContentAdapterHolder {
val binding = ContentItemBinding.inflate(LayoutInflater.from(parent.context), parent, false)
val holder = ContentAdapterHolder(binding)
binding.root.setOnClickListener {
val item = getItem(holder.bindingAdapterPosition) ?: return@setOnClickListener
onItemClick(item)
}
binding.star.setOnClickListener {
val item = getItem(holder.bindingAdapterPosition) ?: return@setOnClickListener
if (item.collect == it.star.isSelected) onStarClick(item, it)
it.star.isSelected = !it.star.isSelected
}
binding.tags.isVisible = contentConfig.tags
binding.date.isVisible = contentConfig.date
binding.authorOrShareUser.isVisible = contentConfig.authorOrShareUser
binding.star.isVisible = contentConfig.star
return holder
}
inner class ContentAdapterHolder constructor(private val binding: ContentItemBinding) : ViewHolder(binding.root) {
private val context = binding.root.context
fun bind(content: Content, position: Int) {
binding.title.text = Html.fromHtml(content.title).toString()
if (contentConfig.star) binding.star.isSelected = content.collect
if (contentConfig.authorOrShareUser) binding.authorOrShareUser.text = context.getString(
R.string.author_label,
Html.fromHtml(content.validAuthor()).toString()
)
if (contentConfig.date) binding.date.text = context.getString(R.string.date_label,
content.niceDate.ifBlank { content.niceShareDate })
if (contentConfig.tags) handleTag(content, position)
}
private fun handleTag(content: Content, position: Int) {
binding.tags.removeAllViews()
if (content.fresh) binding.tags.addView(
TextView(context, null, 0, R.style.ColorRedTipLabelStyle).apply { setText(R.string.fresh_label) }
)
if (content.top) {
binding.tags.addView(
TextView(context, null, 0, R.style.ColorRedTipLabelStyle).apply {
setText(R.string.top_label)
}
)
}
content.tags.forEach {
binding.tags.addView(
TextView(context, null, 0, R.style.ColorPrimaryLabelStyle).apply { text = it.name }
)
}
}
}
data class ContentConfig(
val tags: Boolean = true,
val authorOrShareUser: Boolean = true,
val date: Boolean = true,
val star: Boolean = true,
)
}
| 0 | Kotlin | 0 | 0 | b6ba391b5925a5ebff3040575a813ce9e140cbd3 | 4,261 | WanAndroid | Apache License 2.0 |
app/ui/src/main/java/foo/bar/clean/ui/common/widget/MaxMinIndicator.kt | erdo | 371,918,666 | false | null | package foo.bar.clean.ui.common.widget
import android.animation.AnimatorSet
import android.animation.ObjectAnimator
import android.animation.ValueAnimator
import android.content.Context
import android.util.AttributeSet
import android.view.View
import android.widget.FrameLayout
import foo.bar.clean.ui.R
import foo.bar.clean.ui.common.anim.CustomEasing
import foo.bar.clean.ui.common.anim.allowAnimationOutsideParent
import kotlinx.android.synthetic.main.widget_maxminindicator.view.*
class MaxMinIndicator @JvmOverloads constructor(
context: Context,
attrs: AttributeSet? = null,
defStyleAttr: Int = 0
) : FrameLayout(context, attrs, defStyleAttr) {
private val maxAnimSet = AnimatorSet()
private val minAnimSet = AnimatorSet()
private var maxObjectAnimator: ObjectAnimator? = null
private var minObjectAnimator: ObjectAnimator? = null
private var maxPercent = 0f
private var minPercent = 0f
private val animDurationMax: Long = 1000
private val animDurationMin: Long = 1200
init {
inflate(context, R.layout.widget_maxminindicator, this)
maxmin_max.allowAnimationOutsideParent()
maxmin_min.allowAnimationOutsideParent()
maxAnimSet.apply {
duration = animDurationMax
interpolator = CustomEasing.hardBounceOut
}
minAnimSet.apply {
duration = animDurationMin
interpolator = CustomEasing.hardBounceOut
}
}
override fun onSizeChanged(w: Int, h: Int, oldw: Int, oldh: Int) {
super.onSizeChanged(w, h, oldw, oldh)
reRunAnimations()
}
override fun onLayout(changed: Boolean, left: Int, top: Int, right: Int, bottom: Int) {
super.onLayout(changed, left, top, right, bottom)
reRunAnimations()
}
private fun reRunAnimations() {
maxObjectAnimator = animateToPercent(minPercent, maxmin_min, minObjectAnimator, minAnimSet)
maxObjectAnimator = animateToPercent(maxPercent, maxmin_max, maxObjectAnimator, maxAnimSet)
}
fun setMinPercent(percent: Float) {
if (minPercent != percent) {
minPercent = minOf(maxOf(percent, 0F), 100F)
minObjectAnimator =
animateToPercent(minPercent, maxmin_min, minObjectAnimator, minAnimSet)
}
}
fun setMaxPercent(percent: Float) {
if (maxPercent != percent) {
maxPercent = minOf(maxOf(percent, 0F), 100F)
maxObjectAnimator =
animateToPercent(maxPercent, maxmin_max, maxObjectAnimator, maxAnimSet)
}
}
private fun animateToPercent(
percent: Float,
targetView: View,
animator: ValueAnimator?,
animatorSet: AnimatorSet
): ObjectAnimator? {
var newAnimator: ObjectAnimator? = null
if (height != 0 && targetView.height != 0) {
val currentPosition = animator?.animatedValue?.let {
if (it is Float) it.toFloat() else 0F
} ?: 0F
val targetPosition = -((height - targetView.height) * percent / 100)
if (targetPosition != currentPosition) {
newAnimator = ObjectAnimator.ofFloat(
targetView,
"translationY",
currentPosition, targetPosition
)
animatorSet.cancel()
animatorSet.playTogether(
newAnimator
)
animatorSet.start()
}
}
return newAnimator
}
}
| 0 | Kotlin | 1 | 5 | 93b02cb8f02d9fd71cb17ec3b46f6fcd7e127c4c | 3,556 | clean-modules-sample | Apache License 2.0 |
src/jsMain/kotlin/id/walt/sdjwt/SimpleJWTCryptoProvider.kt | walt-id | 645,414,701 | false | null | package id.walt.sdjwt
import kotlinx.serialization.json.JsonObject
actual class SimpleJWTCryptoProvider : JWTCryptoProvider {
override fun sign(payload: JsonObject, keyID: String?): String {
TODO("Not yet implemented")
}
override fun verify(jwt: String): Boolean {
TODO("Not yet implemented")
}
} | 0 | Kotlin | 0 | 2 | 45d5eee9dcc413b609ee82bf88ff387ae719ee0d | 315 | waltid-sd-jwt | Apache License 2.0 |
ktor-samples/ktor-samples-async/src/org/jetbrains/ktor/samples/async/AsyncApplication.kt | hallefy | 94,839,121 | false | null | package org.jetbrains.ktor.samples.async
import kotlinx.coroutines.experimental.*
import kotlinx.html.*
import org.jetbrains.ktor.application.*
import org.jetbrains.ktor.features.*
import org.jetbrains.ktor.html.*
import org.jetbrains.ktor.logging.*
import org.jetbrains.ktor.pipeline.*
import org.jetbrains.ktor.routing.*
import java.util.*
fun Application.main() {
install(DefaultHeaders)
install(CallLogging)
install(Routing) {
get("/{...}") {
val start = System.currentTimeMillis()
defer(executor.toCoroutineDispatcher()) {
call.handleLongCalculation(start)
}.await()
}
}
}
private suspend fun ApplicationCall.handleLongCalculation(start: Long) {
val queue = System.currentTimeMillis() - start
var number = 0
val random = Random()
for (index in 0..300) {
delay(10)
number += random.nextInt(100)
}
val time = System.currentTimeMillis() - start
respondHtml {
head {
title { +"Async World" }
}
body {
h1 {
+"We calculated this after ${time}ms (${queue}ms in queue): $number"
}
}
}
}
| 0 | null | 0 | 1 | b5dcbe5b740c2d25c7704104e01e0a01bf53d675 | 1,204 | ktor | Apache License 2.0 |
examples/app/delete/deleteAnApp/main.kt | GWT-M3O-TEST | 485,009,715 | false | null |
package examples.app.delete
import com.m3o.m3okotlin.M3O
import com.m3o.m3okotlin.services.app
suspend fun main() {
M3O.initialize(System.getenv("M3O_API_TOKEN"))
val req = AppDeleteRequest(Name = "helloworld",)
try {
val response = AppServ.delete(req)
println(response)
} catch (e: Exception) {
println(e)
}
}
| 1 | Kotlin | 1 | 0 | 54158b584ba47bd7323a484804dcd78c55ef7f69 | 346 | m3o-kotlin | Apache License 2.0 |
features/settings/src/main/java/ir/mehdiyari/krypt/setting/di/SettingsModule.kt | mehdiyari | 459,064,107 | false | {"Kotlin": 470699, "Java": 87170} | package ir.mehdiyari.krypt.setting.di
import dagger.Binds
import dagger.Module
import dagger.hilt.InstallIn
import dagger.hilt.components.SingletonComponent
import ir.mehdiyari.krypt.setting.data.repositories.SettingsRepository
import ir.mehdiyari.krypt.setting.data.repositories.SettingsRepositoryImpl
@Module
@InstallIn(SingletonComponent::class)
internal abstract class SettingsBindingModule {
@Binds
abstract fun bindSettingsRepository(impl: SettingsRepositoryImpl): SettingsRepository
} | 17 | Kotlin | 1 | 3 | e25bd222787ed7312ca4f0f78974fdee5d3148e0 | 501 | krypt | Apache License 2.0 |
plugins/core/jetbrains-community/src/migration/software/aws/toolkits/jetbrains/core/credentials/profiles/ProfileWatcher.kt | aws | 91,485,909 | false | null | // Copyright 2024 Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
package migration.software.aws.toolkits.jetbrains.core.credentials.profiles
import com.intellij.openapi.components.service
interface ProfileWatcher {
fun addListener(listener: () -> Unit)
fun forceRefresh() {}
companion object {
fun getInstance() = service<ProfileWatcher>()
}
}
| 519 | null | 220 | 757 | a81caf64a293b59056cef3f8a6f1c977be46937e | 421 | aws-toolkit-jetbrains | Apache License 2.0 |
internal-publish-plugins/maven-publish-plugin/src/main/kotlin/com/bselzer/gradle/internal/maven/publish/plugin/LocalProperty.kt | Woody230 | 638,902,833 | false | {"Kotlin": 80247} | package com.bselzer.gradle.internal.maven.publish.plugin
internal object LocalProperty {
const val SONATYPE_USERNAME = "sonatype.username"
const val SONATYPE_PASSWORD = "<PASSWORD>"
const val SIGNING_KEY_ID = "signing.keyId"
const val SIGNING_KEY = "signing.key"
const val SIGNING_PASSWORD = "<PASSWORD>"
} | 0 | Kotlin | 0 | 0 | 420226a7409d19a056831908280aac27c613993d | 327 | GradleExtensions | Apache License 2.0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.