path
stringlengths
4
280
owner
stringlengths
2
39
repo_id
int64
21.1k
879M
is_fork
bool
2 classes
languages_distribution
stringlengths
13
1.95k
content
stringlengths
7
482k
issues
int64
0
13.9k
main_language
stringclasses
121 values
forks
stringlengths
1
5
stars
int64
0
111k
commit_sha
stringlengths
40
40
size
int64
7
482k
name
stringlengths
1
100
license
stringclasses
93 values
app/src/main/java/com/aljaldak/culmix/feature/join/common/BlueButton.kt
alzaltak
579,247,462
false
{"Kotlin": 126895}
package com.aljaldak.culmix.feature.join.common import androidx.compose.foundation.background import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.size import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.runtime.Composable import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.unit.dp import com.aljaldak.culmix.core.theme.Blue import com.aljaldak.culmix.core.theme.Body1 import com.aljaldak.culmix.core.theme.LightenBlue import com.aljaldak.culmix.core.theme.Sub import com.aljaldak.culmix.core.util.simClickable @Composable internal fun BlueButton( onClick: () -> Unit, ) { Box( modifier = Modifier .size(90.dp, 36.dp) .background( color = LightenBlue, shape = RoundedCornerShape(6.dp), ) .simClickable { onClick() }, contentAlignment = Alignment.Center, ) { Body1( text = "우편번호 검색", color = Blue, ) } }
0
Kotlin
0
3
396e9867e99f354b5cb4cff36c1cbb292dc076d5
1,100
appjam_android
Apache License 2.0
app/src/main/java/org/rfcx/incidents/view/guardian/GuardianDeploymentActivity.kt
rfcx
104,899,135
false
{"Kotlin": 1176262, "Java": 1049}
package org.rfcx.incidents.view.guardian import android.annotation.SuppressLint import android.content.Context import android.content.Intent import android.content.SharedPreferences import android.net.wifi.ScanResult import android.os.Bundle import android.view.Menu import android.view.MenuItem import android.view.View import androidx.appcompat.app.AppCompatActivity import androidx.fragment.app.Fragment import androidx.lifecycle.lifecycleScope import androidx.preference.Preference import kotlinx.coroutines.flow.StateFlow import kotlinx.coroutines.launch import org.koin.androidx.viewmodel.ext.android.viewModel import org.rfcx.incidents.R import org.rfcx.incidents.data.remote.common.Result import org.rfcx.incidents.databinding.ActivityGuardianDeploymentBinding import org.rfcx.incidents.entity.stream.Stream import org.rfcx.incidents.view.guardian.checklist.GuardianCheckListFragment import org.rfcx.incidents.view.guardian.checklist.audio.GuardianAudioParameterFragment import org.rfcx.incidents.view.guardian.checklist.checkin.GuardianCheckInTestFragment import org.rfcx.incidents.view.guardian.checklist.classifierupload.ClassifierUploadFragment import org.rfcx.incidents.view.guardian.checklist.communication.CommunicationFragment import org.rfcx.incidents.view.guardian.checklist.microphone.GuardianMicrophoneFragment import org.rfcx.incidents.view.guardian.checklist.network.NetworkTestFragment import org.rfcx.incidents.view.guardian.checklist.photos.AddPhotosFragment import org.rfcx.incidents.view.guardian.checklist.photos.Image import org.rfcx.incidents.view.guardian.checklist.powerdiagnostic.PowerDiagnosticFragment import org.rfcx.incidents.view.guardian.checklist.preference.GuardianPreferenceFragment import org.rfcx.incidents.view.guardian.checklist.registration.GuardianRegisterFragment import org.rfcx.incidents.view.guardian.checklist.site.GuardianSiteSelectFragment import org.rfcx.incidents.view.guardian.checklist.site.GuardianSiteSetFragment import org.rfcx.incidents.view.guardian.checklist.site.MapPickerFragment import org.rfcx.incidents.view.guardian.checklist.softwareupdate.SoftwareUpdateFragment import org.rfcx.incidents.view.guardian.checklist.storage.GuardianStorageFragment import org.rfcx.incidents.view.guardian.connect.GuardianConnectFragment class GuardianDeploymentActivity : AppCompatActivity(), GuardianDeploymentEventListener { lateinit var binding: ActivityGuardianDeploymentBinding private val viewModel: GuardianDeploymentViewModel by viewModel() private var currentScreen = GuardianScreen.CHECKLIST private val passedScreen = arrayListOf<GuardianScreen>() private lateinit var stream: Stream private var isNewSite = false private var _savedImages = listOf<Image>() private var menu: Menu? = null private var prefs: List<Preference> = listOf() private var prefsChanges = "" private var prefsEditor: SharedPreferences.Editor? = null override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) // Binding view binding = ActivityGuardianDeploymentBinding.inflate(layoutInflater) setContentView(binding.root) setupToolbar() // Show guardian connect screen first changeScreen(GuardianScreen.CONNECT) } @SuppressLint("ResourceAsColor") override fun onCreateOptionsMenu(menu: Menu): Boolean { this.menu = menu val inflater = menuInflater inflater.inflate(R.menu.preference_menu, menu) return super.onCreateOptionsMenu(menu) } override fun onOptionsItemSelected(item: MenuItem): Boolean { when (item.itemId) { R.id.preference -> onThreeDotsClicked() } return super.onOptionsItemSelected(item) } private fun onThreeDotsClicked() { changeScreen(GuardianScreen.PREFERENCE) } private fun showScreen(screen: GuardianScreen) { when (screen) { GuardianScreen.CONNECT -> startFragment(GuardianConnectFragment.newInstance()) GuardianScreen.CHECKLIST -> startFragment(GuardianCheckListFragment.newInstance()) GuardianScreen.SOFTWARE_UPDATE -> startFragment(SoftwareUpdateFragment.newInstance()) GuardianScreen.CLASSIFIER_UPLOAD -> startFragment(ClassifierUploadFragment.newInstance()) GuardianScreen.POWER_DIAGNOSTIC -> startFragment(PowerDiagnosticFragment.newInstance()) GuardianScreen.COMMUNICATION -> startFragment(CommunicationFragment.newInstance()) GuardianScreen.REGISTER -> startFragment(GuardianRegisterFragment.newInstance()) GuardianScreen.NETWORK_TEST -> startFragment(NetworkTestFragment.newInstance()) GuardianScreen.AUDIO_PARAMETER -> startFragment(GuardianAudioParameterFragment.newInstance()) GuardianScreen.MICROPHONE -> startFragment(GuardianMicrophoneFragment.newInstance()) GuardianScreen.STORAGE -> startFragment(GuardianStorageFragment.newInstance()) GuardianScreen.SITE -> startFragment(GuardianSiteSelectFragment.newInstance()) GuardianScreen.SITE_SET -> startFragment(GuardianSiteSetFragment.newInstance()) GuardianScreen.MAP_PICKER -> startFragment(GuardianSiteSetFragment.newInstance()) GuardianScreen.PHOTO -> startFragment(AddPhotosFragment.newInstance()) GuardianScreen.CHECKIN -> startFragment(GuardianCheckInTestFragment.newInstance()) GuardianScreen.PREFERENCE -> startFragment(GuardianPreferenceFragment.newInstance()) } } private fun startFragment(fragment: Fragment) { supportFragmentManager.beginTransaction() .replace(binding.contentContainer.id, fragment) .commit() } override fun setupToolbar() { setSupportActionBar(binding.toolbarLayout.toolbarDefault) supportActionBar?.apply { setDisplayShowTitleEnabled(true) setDisplayHomeAsUpEnabled(true) setDisplayShowHomeEnabled(true) } } override fun showToolbar() { binding.toolbarLayout.toolbarDefault.visibility = View.VISIBLE } override fun hideToolbar() { binding.toolbarLayout.toolbarDefault.visibility = View.GONE } override fun showThreeDots() { this.menu?.findItem(R.id.preference)?.isVisible = true } override fun hideThreeDots() { this.menu?.findItem(R.id.preference)?.isVisible = false } override fun setToolbarTitle(title: String) { supportActionBar?.apply { this.title = title } } override fun setToolbarSubTitle(subTitle: String) { supportActionBar?.apply { this.subtitle = subTitle } } override fun isAbleToDeploy(): Boolean { if (!passedScreen.contains(GuardianScreen.REGISTER)) return false if (!passedScreen.contains(GuardianScreen.NETWORK_TEST)) return false if (!passedScreen.contains(GuardianScreen.AUDIO_PARAMETER)) return false if (!passedScreen.contains(GuardianScreen.MICROPHONE)) return false if (!passedScreen.contains(GuardianScreen.STORAGE)) return false if (!passedScreen.contains(GuardianScreen.SITE)) return false return true } override fun changeScreen(screen: GuardianScreen) { currentScreen = screen showScreen(screen) } override fun setPassedScreen(screen: GuardianScreen) { passedScreen.add(screen) } override fun back() { when (currentScreen) { GuardianScreen.CONNECT -> finish() GuardianScreen.CHECKLIST -> { viewModel.disconnectWifi() viewModel.onDestroy() changeScreen(GuardianScreen.CONNECT) } GuardianScreen.SOFTWARE_UPDATE -> changeScreen(GuardianScreen.CHECKLIST) GuardianScreen.CLASSIFIER_UPLOAD -> changeScreen(GuardianScreen.CHECKLIST) GuardianScreen.POWER_DIAGNOSTIC -> changeScreen(GuardianScreen.CHECKLIST) GuardianScreen.COMMUNICATION -> changeScreen(GuardianScreen.CHECKLIST) GuardianScreen.REGISTER -> changeScreen(GuardianScreen.CHECKLIST) GuardianScreen.NETWORK_TEST -> changeScreen(GuardianScreen.CHECKLIST) GuardianScreen.AUDIO_PARAMETER -> changeScreen(GuardianScreen.CHECKLIST) GuardianScreen.MICROPHONE -> changeScreen(GuardianScreen.CHECKLIST) GuardianScreen.STORAGE -> changeScreen(GuardianScreen.CHECKLIST) GuardianScreen.SITE -> changeScreen(GuardianScreen.CHECKLIST) GuardianScreen.SITE_SET -> changeScreen(GuardianScreen.CHECKLIST) GuardianScreen.PHOTO -> changeScreen(GuardianScreen.CHECKLIST) GuardianScreen.CHECKIN -> changeScreen(GuardianScreen.CHECKLIST) GuardianScreen.MAP_PICKER -> { currentScreen = GuardianScreen.SITE_SET startFragment(GuardianSiteSetFragment.newInstance(this.stream, this.isNewSite)) } GuardianScreen.PREFERENCE -> { // Need to remove guardian prefs before adding news removeGuardianPrefs() changeScreen(GuardianScreen.CHECKLIST) } } } override fun next() { passedScreen.add(currentScreen) // Need to remove guardian prefs before adding news if (currentScreen == GuardianScreen.PREFERENCE) { removeGuardianPrefs() } changeScreen(GuardianScreen.CHECKLIST) } override fun finishDeploy() { super.finish() } override fun goToSiteSetScreen(stream: Stream, isNewSite: Boolean) { currentScreen = GuardianScreen.SITE_SET this.stream = stream this.isNewSite = isNewSite startFragment(GuardianSiteSetFragment.newInstance(stream, isNewSite)) } override fun goToMapPickerScreen(stream: Stream) { this.stream = stream startFragment(MapPickerFragment.newInstance(stream)) } override fun getPassedScreen(): List<GuardianScreen> = passedScreen override fun nextWithStream(stream: Stream) { currentScreen = GuardianScreen.SITE this.stream = stream passedScreen.add(currentScreen) changeScreen(GuardianScreen.CHECKLIST) } override fun connectHotspot(hotspot: ScanResult?) { lifecycleScope.launch { viewModel.connectWifi(hotspot) } } override fun getHotspotConnectionState(): StateFlow<Result<Boolean>?> { return viewModel.connectionState } override fun initSocket() { viewModel.initSocket() } override fun sendHeartBeatSocket() { viewModel.sendHeartbeatSignalPeriodic() } override fun getInitSocketState(): StateFlow<Result<Boolean>?> { return viewModel.initSocketState } override fun getSocketMessageState(): StateFlow<Result<List<String>>?> { return viewModel.socketMessageState } override fun closeSocket() { viewModel.onDestroy() } override fun getSavedStream(): Stream { return stream } override fun getSavedImages(): List<Image> { return _savedImages } override fun setSavedImages(images: List<Image>) { _savedImages = images } override fun setGuardianPrefs(prefs: List<Preference>) { this.prefs = prefs } override fun setChangedPrefs(prefs: String) { this.prefsChanges = prefs } override fun getChangedPrefs(): String { return this.prefsChanges } private fun removeGuardianPrefs() { this.prefs.forEach { this.prefsEditor!!.remove(it.key)!!.apply() } } override fun setEditor(editor: SharedPreferences.Editor?) { this.prefsEditor = editor } override fun onDestroy() { super.onDestroy() viewModel.onDestroy() this.prefsEditor?.clear()?.apply() } override fun onBackPressed() { back() } override fun onSupportNavigateUp(): Boolean { back() return true } companion object { fun startActivity(context: Context) { val intent = Intent(context, GuardianDeploymentActivity::class.java) context.startActivity(intent) } } }
29
Kotlin
0
0
804d56b8c7475e51299db5fde9207ae783820bf9
12,359
guardian-app-android
Apache License 2.0
libraries/tools/kotlin-gradle-plugin/src/test/kotlin/org/jetbrains/kotlin/gradle/targets/js/internal/NodeJsStackTraceParserKtTest.kt
JetBrains
3,432,266
false
null
/* * Copyright 2010-2019 JetBrains s.r.o. 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.gradle.targets.js.internal import org.junit.Test import kotlin.test.assertEquals class NodeJsStackTraceParserKtTest { @Test fun parseNodeJsStackTrace() { val parsed = parseNodeJsStackTrace( """ AssertionError: Expected value to be true. at AssertionError_init_0 (/Users/jetbrains/IdeaProjects/mpplib2/build/tmp/expandedArchives/kotlin-stdlib-js-1.3-SNAPSHOT.jar_730a1b227513cf16a9b639e009a985fc/kotlin/exceptions.kt:102:37) at DefaultJsAsserter.failWithMessage_0 (/Users/jetbrains/IdeaProjects/mpplib2/build/tmp/expandedArchives/kotlin-test-js-1.3-SNAPSHOT.jar_d60f1e6d0dd94843a03bf98a569bbb73/src/main/kotlin/kotlin/test/DefaultJsAsserter.kt:80:19) at DefaultJsAsserter.assertTrue_o10pc4${'$'} (/Users/jetbrains/IdeaProjects/mpplib2/build/tmp/expandedArchives/kotlin-test-js-1.3-SNAPSHOT.jar_d60f1e6d0dd94843a03bf98a569bbb73/src/main/kotlin/kotlin/test/DefaultJsAsserter.kt:60:13) at DefaultJsAsserter.assertTrue_4mavae${'$'} (/Users/jetbrains/IdeaProjects/mpplib2/build/tmp/expandedArchives/kotlin-test-js-1.3-SNAPSHOT.jar_d60f1e6d0dd94843a03bf98a569bbb73/src/main/kotlin/kotlin/test/DefaultJsAsserter.kt:67:9) at assertTrue_0 (/Users/jetbrains/IdeaProjects/mpplib2/build/tmp/expandedArchives/kotlin-test-js-1.3-SNAPSHOT.jar_d60f1e6d0dd94843a03bf98a569bbb73/Assertions.kt:36:21) at DeepPackageTest${'$'}Inner${'$'}Inner2${'$'}Inner3.testHello (/Users/jetbrains/IdeaProjects/mpplib2/src/commonTest/kotlin/sample/a/DeepPackageTest.kt:16:13) at /Users/jetbrains/IdeaProjects/mpplib2/build/js_test_node_modules/mpplib2_test.js:93:48 at Object.fn [as test] (/Users/jetbrains/IdeaProjects/mpplib2/build/tmp/expandedArchives/src/KotlinTestRunner.ts:12:25) at Object.test (/Users/jetbrains/IdeaProjects/mpplib2/build/tmp/expandedArchives/src/KotlinTestTeamCityReporter.ts:80:28) at test (/Users/jetbrains/IdeaProjects/mpplib2/build/tmp/expandedArchives/kotlin-test-js-1.3-SNAPSHOT.jar_d60f1e6d0dd94843a03bf98a569bbb73/src/main/kotlin/kotlin/test/TestApi.kt:57:15) """.trimIndent() ).toString() assertEquals( """ NodeJsStackTrace( message="AssertionError: Expected value to be true.", stacktrace=[ NodeJsStackTraceElement(className=AssertionError, methodName=init, fileName=/Users/jetbrains/IdeaProjects/mpplib2/build/tmp/expandedArchives/kotlin-stdlib-js-1.3-SNAPSHOT.jar_730a1b227513cf16a9b639e009a985fc/kotlin/exceptions.kt, lineNumber=102, colNumber=37) NodeJsStackTraceElement(className=DefaultJsAsserter, methodName=failWithMessage, fileName=/Users/jetbrains/IdeaProjects/mpplib2/build/tmp/expandedArchives/kotlin-test-js-1.3-SNAPSHOT.jar_d60f1e6d0dd94843a03bf98a569bbb73/src/main/kotlin/kotlin/test/DefaultJsAsserter.kt, lineNumber=80, colNumber=19) NodeJsStackTraceElement(className=DefaultJsAsserter, methodName=assertTrue, fileName=/Users/jetbrains/IdeaProjects/mpplib2/build/tmp/expandedArchives/kotlin-test-js-1.3-SNAPSHOT.jar_d60f1e6d0dd94843a03bf98a569bbb73/src/main/kotlin/kotlin/test/DefaultJsAsserter.kt, lineNumber=60, colNumber=13) NodeJsStackTraceElement(className=DefaultJsAsserter, methodName=assertTrue, fileName=/Users/jetbrains/IdeaProjects/mpplib2/build/tmp/expandedArchives/kotlin-test-js-1.3-SNAPSHOT.jar_d60f1e6d0dd94843a03bf98a569bbb73/src/main/kotlin/kotlin/test/DefaultJsAsserter.kt, lineNumber=67, colNumber=9) NodeJsStackTraceElement(className=null, methodName=assertTrue, fileName=/Users/jetbrains/IdeaProjects/mpplib2/build/tmp/expandedArchives/kotlin-test-js-1.3-SNAPSHOT.jar_d60f1e6d0dd94843a03bf98a569bbb73/Assertions.kt, lineNumber=36, colNumber=21) NodeJsStackTraceElement(className=Inner3, methodName=testHello, fileName=/Users/jetbrains/IdeaProjects/mpplib2/src/commonTest/kotlin/sample/a/DeepPackageTest.kt, lineNumber=16, colNumber=13) NodeJsStackTraceElement(className=null, methodName=null, fileName=/Users/jetbrains/IdeaProjects/mpplib2/build/js_test_node_modules/mpplib2_test.js, lineNumber=93, colNumber=48) NodeJsStackTraceElement(className=Object, methodName=test, fileName=/Users/jetbrains/IdeaProjects/mpplib2/build/tmp/expandedArchives/src/KotlinTestRunner.ts, lineNumber=12, colNumber=25) NodeJsStackTraceElement(className=Object, methodName=test, fileName=/Users/jetbrains/IdeaProjects/mpplib2/build/tmp/expandedArchives/src/KotlinTestTeamCityReporter.ts, lineNumber=80, colNumber=28) NodeJsStackTraceElement(className=null, methodName=test, fileName=/Users/jetbrains/IdeaProjects/mpplib2/build/tmp/expandedArchives/kotlin-test-js-1.3-SNAPSHOT.jar_d60f1e6d0dd94843a03bf98a569bbb73/src/main/kotlin/kotlin/test/TestApi.kt, lineNumber=57, colNumber=15) ]) """.trim(), parsed ) } }
181
null
5748
49,172
33eb9cef3d146062c103f9853d772f0a1da0450e
4,854
kotlin
Apache License 2.0
client/android/div/src/main/java/com/yandex/div/core/expression/variables/LocalVariableController.kt
divkit
523,491,444
false
null
package com.yandex.div.core.expression.variables import com.yandex.div.core.view2.errors.ErrorCollector import com.yandex.div.data.Variable internal class LocalVariableController( private val delegate: VariableController, private val localVariables: VariableSource ) : VariableController { override fun subscribeToVariablesChange( names: List<String>, invokeOnSubscription: Boolean, observer: (Variable) -> Unit ) = delegate.subscribeToVariablesChange(names, invokeOnSubscription, observer) override fun subscribeToVariableChange( name: String, errorCollector: ErrorCollector?, invokeOnSubscription: Boolean, observer: (Variable) -> Unit ) = delegate.subscribeToVariableChange(name, errorCollector, invokeOnSubscription, observer) override fun addSource(source: VariableSource) = delegate.addSource(source) override fun getMutableVariable(name: String) = localVariables.getMutableVariable(name) ?: delegate.getMutableVariable(name) override fun declare(variable: Variable) = delegate.declare(variable) override fun setOnAnyVariableChangeCallback(callback: (Variable) -> Unit) = delegate.setOnAnyVariableChangeCallback(callback) override fun cleanupSubscriptions() = delegate.cleanupSubscriptions() override fun restoreSubscriptions() = delegate.restoreSubscriptions() }
5
null
122
2,205
9d28bdb64c24c32b1d6cb4d9d0c61a84dbe38e0d
1,400
divkit
Apache License 2.0
compose/ui/ui/src/commonMain/kotlin/androidx/compose/ui/ComposedModifier.kt
JetBrains
351,708,598
false
null
/* * Copyright 2020 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package androidx.compose.ui import androidx.compose.runtime.Composable import androidx.compose.runtime.Composer import androidx.compose.runtime.Stable import androidx.compose.ui.platform.InspectorInfo import androidx.compose.ui.platform.InspectorValueInfo import androidx.compose.ui.platform.NoInspectorInfo /** * Declare a just-in-time composition of a [Modifier] that will be composed for each element it * modifies. [composed] may be used to implement **stateful modifiers** that have * instance-specific state for each modified element, allowing the same [Modifier] instance to be * safely reused for multiple elements while maintaining element-specific state. * * If [inspectorInfo] is specified this modifier will be visible to tools during development. * Specify the name and arguments of the original modifier. * * Example usage: * @sample androidx.compose.ui.samples.InspectorInfoInComposedModifierSample * @sample androidx.compose.ui.samples.InspectorInfoInComposedModifierWithArgumentsSample * * [materialize] must be called to create instance-specific modifiers if you are directly * applying a [Modifier] to an element tree node. */ fun Modifier.composed( inspectorInfo: InspectorInfo.() -> Unit = NoInspectorInfo, factory: @Composable Modifier.() -> Modifier ): Modifier = this.then(ComposedModifier(inspectorInfo, factory)) /** * Declare a just-in-time composition of a [Modifier] that will be composed for each element it * modifies. [composed] may be used to implement **stateful modifiers** that have * instance-specific state for each modified element, allowing the same [Modifier] instance to be * safely reused for multiple elements while maintaining element-specific state. * * When keys are provided, [composed] produces a [Modifier] that will compare [equals] to * another modifier constructed with the same keys in order to take advantage of caching and * skipping optimizations. [fullyQualifiedName] should be the fully-qualified `import` name for * your modifier factory function, e.g. `com.example.myapp.ui.fancyPadding`. * * If [inspectorInfo] is specified this modifier will be visible to tools during development. * Specify the name and arguments of the original modifier. * * Example usage: * @sample androidx.compose.ui.samples.InspectorInfoInComposedModifierSample * @sample androidx.compose.ui.samples.InspectorInfoInComposedModifierWithArgumentsSample * * [materialize] must be called to create instance-specific modifiers if you are directly * applying a [Modifier] to an element tree node. */ @ExperimentalComposeUiApi fun Modifier.composed( fullyQualifiedName: String, key1: Any?, inspectorInfo: InspectorInfo.() -> Unit = NoInspectorInfo, factory: @Composable Modifier.() -> Modifier ): Modifier = this.then( KeyedComposedModifier1(fullyQualifiedName, key1, inspectorInfo, factory) ) /** * Declare a just-in-time composition of a [Modifier] that will be composed for each element it * modifies. [composed] may be used to implement **stateful modifiers** that have * instance-specific state for each modified element, allowing the same [Modifier] instance to be * safely reused for multiple elements while maintaining element-specific state. * * When keys are provided, [composed] produces a [Modifier] that will compare [equals] to * another modifier constructed with the same keys in order to take advantage of caching and * skipping optimizations. [fullyQualifiedName] should be the fully-qualified `import` name for * your modifier factory function, e.g. `com.example.myapp.ui.fancyPadding`. * * If [inspectorInfo] is specified this modifier will be visible to tools during development. * Specify the name and arguments of the original modifier. * * Example usage: * @sample androidx.compose.ui.samples.InspectorInfoInComposedModifierSample * @sample androidx.compose.ui.samples.InspectorInfoInComposedModifierWithArgumentsSample * * [materialize] must be called to create instance-specific modifiers if you are directly * applying a [Modifier] to an element tree node. */ @ExperimentalComposeUiApi fun Modifier.composed( fullyQualifiedName: String, key1: Any?, key2: Any?, inspectorInfo: InspectorInfo.() -> Unit = NoInspectorInfo, factory: @Composable Modifier.() -> Modifier ): Modifier = this.then( KeyedComposedModifier2(fullyQualifiedName, key1, key2, inspectorInfo, factory) ) /** * Declare a just-in-time composition of a [Modifier] that will be composed for each element it * modifies. [composed] may be used to implement **stateful modifiers** that have * instance-specific state for each modified element, allowing the same [Modifier] instance to be * safely reused for multiple elements while maintaining element-specific state. * * When keys are provided, [composed] produces a [Modifier] that will compare [equals] to * another modifier constructed with the same keys in order to take advantage of caching and * skipping optimizations. [fullyQualifiedName] should be the fully-qualified `import` name for * your modifier factory function, e.g. `com.example.myapp.ui.fancyPadding`. * * If [inspectorInfo] is specified this modifier will be visible to tools during development. * Specify the name and arguments of the original modifier. * * Example usage: * @sample androidx.compose.ui.samples.InspectorInfoInComposedModifierSample * @sample androidx.compose.ui.samples.InspectorInfoInComposedModifierWithArgumentsSample * * [materialize] must be called to create instance-specific modifiers if you are directly * applying a [Modifier] to an element tree node. */ @ExperimentalComposeUiApi fun Modifier.composed( fullyQualifiedName: String, key1: Any?, key2: Any?, key3: Any?, inspectorInfo: InspectorInfo.() -> Unit = NoInspectorInfo, factory: @Composable Modifier.() -> Modifier ): Modifier = this.then( KeyedComposedModifier3(fullyQualifiedName, key1, key2, key3, inspectorInfo, factory) ) /** * Declare a just-in-time composition of a [Modifier] that will be composed for each element it * modifies. [composed] may be used to implement **stateful modifiers** that have * instance-specific state for each modified element, allowing the same [Modifier] instance to be * safely reused for multiple elements while maintaining element-specific state. * * When keys are provided, [composed] produces a [Modifier] that will compare [equals] to * another modifier constructed with the same keys in order to take advantage of caching and * skipping optimizations. [fullyQualifiedName] should be the fully-qualified `import` name for * your modifier factory function, e.g. `com.example.myapp.ui.fancyPadding`. * * If [inspectorInfo] is specified this modifier will be visible to tools during development. * Specify the name and arguments of the original modifier. * * Example usage: * @sample androidx.compose.ui.samples.InspectorInfoInComposedModifierSample * @sample androidx.compose.ui.samples.InspectorInfoInComposedModifierWithArgumentsSample * * [materialize] must be called to create instance-specific modifiers if you are directly * applying a [Modifier] to an element tree node. */ @ExperimentalComposeUiApi fun Modifier.composed( fullyQualifiedName: String, vararg keys: Any?, inspectorInfo: InspectorInfo.() -> Unit = NoInspectorInfo, factory: @Composable Modifier.() -> Modifier ): Modifier = this.then(KeyedComposedModifierN(fullyQualifiedName, keys, inspectorInfo, factory)) private open class ComposedModifier( inspectorInfo: InspectorInfo.() -> Unit, val factory: @Composable Modifier.() -> Modifier ) : Modifier.Element, InspectorValueInfo(inspectorInfo) @Stable private class KeyedComposedModifier1( val fqName: String, val key1: Any?, inspectorInfo: InspectorInfo.() -> Unit, factory: @Composable Modifier.() -> Modifier ) : ComposedModifier(inspectorInfo, factory) { override fun equals(other: Any?) = other is KeyedComposedModifier1 && fqName == other.fqName && key1 == other.key1 override fun hashCode(): Int = 31 * fqName.hashCode() + key1.hashCode() } @Stable private class KeyedComposedModifier2( val fqName: String, val key1: Any?, val key2: Any?, inspectorInfo: InspectorInfo.() -> Unit, factory: @Composable Modifier.() -> Modifier ) : ComposedModifier(inspectorInfo, factory) { override fun equals(other: Any?) = other is KeyedComposedModifier2 && fqName == other.fqName && key1 == other.key1 && key2 == other.key2 override fun hashCode(): Int { var result = fqName.hashCode() result = 31 * result + key1.hashCode() result = 31 * result + key2.hashCode() return result } } @Stable private class KeyedComposedModifier3( val fqName: String, val key1: Any?, val key2: Any?, val key3: Any?, inspectorInfo: InspectorInfo.() -> Unit, factory: @Composable Modifier.() -> Modifier ) : ComposedModifier(inspectorInfo, factory) { override fun equals(other: Any?) = other is KeyedComposedModifier3 && fqName == other.fqName && key1 == other.key1 && key2 == other.key2 && key3 == other.key3 override fun hashCode(): Int { var result = fqName.hashCode() result = 31 * result + key1.hashCode() result = 31 * result + key2.hashCode() result = 31 * result + key3.hashCode() return result } } @Stable private class KeyedComposedModifierN( val fqName: String, val keys: Array<out Any?>, inspectorInfo: InspectorInfo.() -> Unit, factory: @Composable Modifier.() -> Modifier ) : ComposedModifier(inspectorInfo, factory) { override fun equals(other: Any?) = other is KeyedComposedModifierN && fqName == other.fqName && keys.contentEquals(other.keys) override fun hashCode() = 31 * fqName.hashCode() + keys.contentHashCode() } /** * Materialize any instance-specific [composed modifiers][composed] for applying to a raw tree node. * Call right before setting the returned modifier on an emitted node. * You almost certainly do not need to call this function directly. */ @Suppress("ModifierFactoryExtensionFunction") fun Composer.materialize(modifier: Modifier): Modifier { if (modifier.all { it !is ComposedModifier }) return modifier // This is a fake composable function that invokes the compose runtime directly so that it // can call the element factory functions from the non-@Composable lambda of Modifier.foldIn. // It would be more efficient to redefine the Modifier type hierarchy such that the fold // operations could be inlined or otherwise made cheaper, which could make this unnecessary. // Random number for fake group key. Chosen by fair die roll. startReplaceableGroup(0x48ae8da7) val result = modifier.foldIn<Modifier>(Modifier) { acc, element -> acc.then( if (element is ComposedModifier) { @kotlin.Suppress("UNCHECKED_CAST") val factory = element.factory as Modifier.(Composer, Int) -> Modifier val composedMod = factory(Modifier, this, 0) materialize(composedMod) } else element ) } endReplaceableGroup() return result }
10
null
16
59
e18ad812b77fc8babb00aacfcea930607b0794b5
11,905
androidx
Apache License 2.0
app/src/main/kotlin/com/wiley/fordummies/androidsdk/tictactoe/model/ContactLiveData.kt
acchampion
157,287,910
false
null
package com.wiley.fordummies.androidsdk.tictactoe.model import android.content.Context import androidx.lifecycle.MutableLiveData class ContactLiveData(private val mContext: Context) : MutableLiveData<List<Contact?>?>() { private val classTag = javaClass.simpleName }
0
Kotlin
2
2
596641228844e8a2daef9607ba8f001f157ee19d
271
TicTacToeKotlin
Apache License 2.0
packages/audioplayers_android/android/src/main/kotlin/xyz/luan/audioplayers/player/Player.kt
bluefireteam
107,827,192
false
null
package xyz.luan.audioplayers.player import xyz.luan.audioplayers.AudioContextAndroid import xyz.luan.audioplayers.source.Source interface Player { fun getDuration(): Int? fun getCurrentPosition(): Int? fun isLiveStream(): Boolean fun start() fun pause() fun stop() fun seekTo(position: Int) fun release() fun setVolume(leftVolume: Float, rightVolume: Float) fun setRate(rate: Float) fun setLooping(looping: Boolean) fun updateContext(context: AudioContextAndroid) fun setSource(source: Source) fun prepare() fun reset() }
183
null
839
1,967
f284cc99038881abaf40b9f1961321b695dbc3e2
588
audioplayers
MIT License
02_control_flow/04.Range.kt
alidehkhodaei
617,526,016
false
null
package `02_control_flow` fun main() { // Ranges for (i in 0..3) { print(i) } for (i in 0 until 3) { print(i) } for (i in 2..8 step 2) { print(i) } for (i in 3 downTo 0) { print(i) } for (c in 'a'..'d') { print(c) } if (2 in 1..5) { print("x is in range from 1 to 5") } }
0
Kotlin
4
55
a9c9fe2922d5a8c6ad839de2064e56582a851bfc
379
kotlin-cheatsheet
MIT License
app/src/main/java/com/xuexiang/templateproject/fragment/other/SettingsFragment.kt
xuexiangjys
443,728,025
false
null
/* * Copyright (C) 2021 xuexiangjys(xuexiangjys@163.com) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.xuexiang.templateproject.fragment.other import android.content.DialogInterface import android.view.LayoutInflater import android.view.ViewGroup import com.xuexiang.templateproject.R import com.xuexiang.templateproject.core.BaseFragment import com.xuexiang.templateproject.databinding.FragmentSettingsBinding import com.xuexiang.templateproject.utils.TokenUtils.handleLogoutSuccess import com.xuexiang.xaop.annotation.SingleClick import com.xuexiang.xpage.annotation.Page import com.xuexiang.xui.utils.XToastUtils import com.xuexiang.xui.widget.dialog.DialogLoader import com.xuexiang.xui.widget.textview.supertextview.SuperTextView import com.xuexiang.xui.widget.textview.supertextview.SuperTextView.OnSuperTextViewClickListener import com.xuexiang.xutil.XUtil /** * @author xuexiang * @since 2019-10-15 22:38 */ @Page(name = "设置") class SettingsFragment : BaseFragment<FragmentSettingsBinding?>(), OnSuperTextViewClickListener { override fun viewBindingInflate( inflater: LayoutInflater, container: ViewGroup?, attachToRoot: Boolean ): FragmentSettingsBinding { return FragmentSettingsBinding.inflate(inflater, container, attachToRoot) } override fun initViews() { binding?.menuCommon?.setOnSuperTextViewClickListener(this) binding?.menuPrivacy?.setOnSuperTextViewClickListener(this) binding?.menuPush?.setOnSuperTextViewClickListener(this) binding?.menuHelper?.setOnSuperTextViewClickListener(this) binding?.menuChangeAccount?.setOnSuperTextViewClickListener(this) binding?.menuLogout?.setOnSuperTextViewClickListener(this) } @SingleClick override fun onClick(superTextView: SuperTextView) { val id = superTextView.id if (id == R.id.menu_common || id == R.id.menu_privacy || id == R.id.menu_push || id == R.id.menu_helper) { XToastUtils.toast(superTextView.leftString) } else if (id == R.id.menu_change_account) { XToastUtils.toast(superTextView.centerString) } else if (id == R.id.menu_logout) { DialogLoader.getInstance().showConfirmDialog( context, getString(R.string.lab_logout_confirm), getString(R.string.lab_yes), { dialog: DialogInterface, _: Int -> dialog.dismiss() XUtil.getActivityLifecycleHelper().exit() handleLogoutSuccess() }, getString(R.string.lab_no) ) { dialog: DialogInterface, _: Int -> dialog.dismiss() } } } }
1
null
18
52
551bef56697c628628d42a857db37658c7670f8d
3,235
TemplateAppProject-kotlin
Apache License 2.0
hacktoberfest_issues/app/src/main/java/io/henrikhorbovyi/hacktoberfestissues/ui/components/IssueView.kt
aadityamp01
275,898,636
false
null
package io.henrikhorbovyi.hacktoberfestissues.ui.components import androidx.compose.foundation.clickable import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.Spacer import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.padding import androidx.compose.material.Card import androidx.compose.material.Text import androidx.compose.runtime.Composable import androidx.compose.ui.Modifier import androidx.compose.ui.graphics.Color import androidx.compose.ui.text.TextStyle import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.tooling.preview.Preview import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.sp import io.henrikhorbovyi.hacktoberfestissues.ui.entity.issues.Issue @Composable fun IssueView(issue: Issue, onClicked: (Issue) -> Unit = {}) { Card( modifier = Modifier .fillMaxWidth() .padding(vertical = 8.dp, horizontal = 16.dp) .clickable { onClicked(issue) }, elevation = 8.dp ) { Column(modifier = Modifier.padding(8.dp)) { Text( issue.title, style = TextStyle( fontSize = 22.sp, fontWeight = FontWeight.Bold ) ) Text( issue.repositoryName(), style = TextStyle( fontSize = 18.sp, fontWeight = FontWeight.Bold, color = Color.DarkGray ) ) Spacer(modifier = Modifier.padding(top = 8.dp)) Text( issue.toString(), style = TextStyle( fontSize = 14.sp, color = Color.DarkGray ) ) } } } @Composable @Preview("IssueViewPreview", showBackground = true, showSystemUi = true) fun IssueViewPreview() { IssueView(issue = Issue.mock) }
1
null
57
76
d047d5b4c3321df85c6523c0725028986c898b14
2,044
Androapps
MIT License
app/src/main/java/com/yangbw/libtest/module/common/MainActivity.kt
yangbangwei
287,162,841
false
null
package com.yangbw.libtest.ui.activity import android.content.Context import android.content.Intent import android.os.Bundle import android.view.View import androidx.databinding.ViewDataBinding import androidx.fragment.app.FragmentTransaction import com.blankj.utilcode.util.ToastUtils import com.library.common.base.BaseActivity import com.library.common.extension.setOnClickListener import com.yangbw.libtest.R import com.yangbw.libtest.common.CommonViewModel import com.yangbw.libtest.ui.dialog.CouponDialog import com.yangbw.libtest.ui.fragment.DiscoverFragment import com.yangbw.libtest.ui.fragment.GoodsFragment import com.yangbw.libtest.ui.fragment.HomeFragment import com.yangbw.libtest.ui.fragment.MineFragment import kotlinx.android.synthetic.main.activity_main.* import kotlinx.android.synthetic.main.layout_bottom_navigation_bar.* /** * 首页 * * @author yangbw * @date 2020/9/1 */ class MainActivity : BaseActivity<CommonViewModel, ViewDataBinding>() { companion object { fun launch(context: Context) { context.startActivity(Intent().apply { setClass(context, MainActivity::class.java) }) } } private var mBackPressTime = 0L private var mHomeFragment: HomeFragment? = null private var mGoodsFragment: GoodsFragment? = null private var mDiscoverFragment: DiscoverFragment? = null private var mMineFragment: MineFragment? = null override fun getLayoutId() = R.layout.activity_main override fun getReplaceView(): View = homeActivityFragContainer override fun init(savedInstanceState: Bundle?) { setOnClickListener(btnHome, btnDiscover, btnMine, btnGoods, btnMenu) { if (this.id == btnMenu.id) { MenuActivity.launch(mActivity) } else { setTabSelection(this.id) } } //选中首页 setTabSelection(btnHome.id) //显示弹窗 val couponDialog = CouponDialog.newInstance() couponDialog.setOnOkClickListener { showToast(getString(R.string.congratulation)) } couponDialog.show(supportFragmentManager, CouponDialog::javaClass.name) } /** * 切换tab */ private fun setTabSelection(index: Int) { clearAllSelected() supportFragmentManager.beginTransaction().apply { hideFragments(this) when (index) { btnHome.id -> { ivHome.isSelected = true tvHome.isSelected = true if (mHomeFragment == null) { mHomeFragment = HomeFragment.newInstance() add(R.id.homeActivityFragContainer, mHomeFragment!!) } else { show(mHomeFragment!!) } } btnGoods.id -> { ivGoods.isSelected = true tvGoods.isSelected = true if (mGoodsFragment == null) { mGoodsFragment = GoodsFragment.newInstance() add(R.id.homeActivityFragContainer, mGoodsFragment!!) } else { show(mGoodsFragment!!) } } btnDiscover.id -> { ivDiscover.isSelected = true tvDiscover.isSelected = true if (mDiscoverFragment == null) { mDiscoverFragment = DiscoverFragment.newInstance() add(R.id.homeActivityFragContainer, mDiscoverFragment!!) } else { show(mDiscoverFragment!!) } } btnMine.id -> { ivMine.isSelected = true tvMine.isSelected = true if (mMineFragment == null) { mMineFragment = MineFragment.newInstance() add(R.id.homeActivityFragContainer, mMineFragment!!) } else { show(mMineFragment!!) } } } }.commitAllowingStateLoss() } /** * 隐藏其他tab */ private fun hideFragments(transaction: FragmentTransaction) { transaction.run { if (mHomeFragment != null) hide(mHomeFragment!!) if (mGoodsFragment != null) hide(mGoodsFragment!!) if (mDiscoverFragment != null) hide(mDiscoverFragment!!) if (mMineFragment != null) hide(mMineFragment!!) } } /** * 清空选中效果 */ private fun clearAllSelected() { ivHome.isSelected = false tvHome.isSelected = false ivGoods.isSelected = false tvGoods.isSelected = false ivDiscover.isSelected = false tvDiscover.isSelected = false ivMine.isSelected = false tvMine.isSelected = false } /** * 退出提醒 */ override fun onBackPressed() { val now = System.currentTimeMillis() if (now - mBackPressTime > 2000) { ToastUtils.showShort(R.string.out_tip) mBackPressTime = now } else { super.onBackPressed() } } }
0
null
3
9
d3791cfa3586c7430b5fb8d9870fcb71fab9d8f1
5,276
MvvmLib
Apache License 2.0
composeApp/src/commonMain/kotlin/components/CharacterTraceTree/AbundanceTraceTree.kt
Coding-band
612,426,050
false
{"Kotlin": 866087, "Swift": 675}
package components.CharacterTraceTree import androidx.compose.foundation.Image import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.aspectRatio import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.size import androidx.compose.runtime.Composable import androidx.compose.runtime.MutableState import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.unit.Dp import androidx.compose.ui.unit.dp import files.AbundanceTraceTree import files.Res import kotlinx.serialization.json.JsonElement import kotlinx.serialization.json.int import kotlinx.serialization.json.jsonArray import kotlinx.serialization.json.jsonObject import kotlinx.serialization.json.jsonPrimitive import org.jetbrains.compose.resources.painterResource import types.Constants import types.Path //(x,y) base on Figma, no need to handly calculate val abundanceOffsetList = arrayListOf( (0 to 0),//Empty (56 to 169),//普攻 (219 to 169),//戰技 (135 to 113),//終結技 (135 to 197),//天賦 (135 to 277),//祕技 (215 to 287), (52 to 287), (131 to 0), (84 to 372), (265 to 237), (293 to 187), (275 to 138), (28 to 237), (0 to 187), (22 to 138), (216 to 28), (84 to 28), (216 to 372), ) @Composable fun AbundanceTraceTree(infoJson: JsonElement, displayWidth: Dp, selectedId: MutableState<Int>, charFileName: String){ val displayHeight = displayWidth.times(Constants.TRACE_TREE_BASE_HEIGHT / Constants.TRACE_TREE_BASE_WIDTH) val selectedId = remember { mutableStateOf(0) } val skillTreePointsArray = infoJson.jsonObject["skillTreePoints"]!!.jsonArray.sortedBy { it.jsonObject["anchor"]!!.jsonPrimitive.int } val skillTreeCoreArray = infoJson.jsonObject["skills"]!!.jsonArray val groupNormalATK = jsonArrayToIntArrayList(infoJson.jsonObject["skillGrouping"]!!.jsonArray[0].jsonArray) val groupSkill = jsonArrayToIntArrayList(infoJson.jsonObject["skillGrouping"]!!.jsonArray[1].jsonArray) val groupUltimate = jsonArrayToIntArrayList(infoJson.jsonObject["skillGrouping"]!!.jsonArray[2].jsonArray) val groupTalent = jsonArrayToIntArrayList(infoJson.jsonObject["skillGrouping"]!!.jsonArray[3].jsonArray) val groupSpecial = jsonArrayToIntArrayList(infoJson.jsonObject["skillGrouping"]!!.jsonArray[4].jsonArray) val pointNormalATK = getDataFromSkills(skillTreeCoreArray.filter { obj -> groupNormalATK.indexOf(obj.jsonObject["id"]!!.jsonPrimitive.int) != -1 } as ArrayList<JsonElement>, charFileName, 1, infoJson) //普攻 val pointSkill = getDataFromSkills(skillTreeCoreArray.filter { obj -> groupSkill.indexOf(obj.jsonObject["id"]!!.jsonPrimitive.int) != -1 } as ArrayList<JsonElement>, charFileName, 2, infoJson) //戰技 val pointUltimate = getDataFromSkills(skillTreeCoreArray.filter { obj -> groupUltimate.indexOf(obj.jsonObject["id"]!!.jsonPrimitive.int) != -1 } as ArrayList<JsonElement>, charFileName, 3, infoJson) //終結技 val pointTalent = getDataFromSkills(skillTreeCoreArray.filter { obj -> groupTalent.indexOf(obj.jsonObject["id"]!!.jsonPrimitive.int) != -1 } as ArrayList<JsonElement>, charFileName, 4, infoJson) //天賦 val pointSpecial = getDataFromSkills(skillTreeCoreArray.filter { obj -> groupSpecial.indexOf(obj.jsonObject["id"]!!.jsonPrimitive.int) != -1 } as ArrayList<JsonElement>, charFileName, 6, infoJson) //祕技 val point6 = getDataFromSkillTreePoints(skillTreePointsArray[0].jsonObject, infoJson) val point10 = getDataFromSkillTreePoints(skillTreePointsArray[0].jsonObject["children"]!!.jsonArray[0].jsonObject, infoJson) val point11 = getDataFromSkillTreePoints(skillTreePointsArray[0].jsonObject["children"]!!.jsonArray[0].jsonObject["children"]!!.jsonArray[0].jsonObject, infoJson) val point12 = getDataFromSkillTreePoints(skillTreePointsArray[0].jsonObject["children"]!!.jsonArray[0].jsonObject["children"]!!.jsonArray[0].jsonObject["children"]!!.jsonArray[0].jsonObject, infoJson) val point7 = getDataFromSkillTreePoints(skillTreePointsArray[1].jsonObject, infoJson) val point13 = getDataFromSkillTreePoints(skillTreePointsArray[1].jsonObject["children"]!!.jsonArray[0].jsonObject, infoJson) val point14 = getDataFromSkillTreePoints(skillTreePointsArray[1].jsonObject["children"]!!.jsonArray[0].jsonObject["children"]!!.jsonArray[0].jsonObject, infoJson) val point15 = getDataFromSkillTreePoints(skillTreePointsArray[1].jsonObject["children"]!!.jsonArray[0].jsonObject["children"]!!.jsonArray[0].jsonObject["children"]!!.jsonArray[0].jsonObject, infoJson) val point8 = getDataFromSkillTreePoints(skillTreePointsArray[2].jsonObject, infoJson) val point16 = getDataFromSkillTreePoints(skillTreePointsArray[2].jsonObject["children"]!!.jsonArray[0].jsonObject, infoJson) val point17 = getDataFromSkillTreePoints(skillTreePointsArray[2].jsonObject["children"]!!.jsonArray[1].jsonObject, infoJson) val point9 = getDataFromSkillTreePoints(skillTreePointsArray[3].jsonObject, infoJson) val point18 = getDataFromSkillTreePoints(skillTreePointsArray[4].jsonObject, infoJson) Box(modifier = Modifier.size(displayWidth,displayHeight)){ Image(painterResource(Path.Abundance.iconAbyss), modifier = Modifier.aspectRatio(1f).fillMaxSize().padding(start = 12.dp, end = 12.dp).align( Alignment.BottomCenter ), contentDescription = "Path's Icon", alpha = 0.2f) Image(painterResource(Res.drawable.AbundanceTraceTree), contentDescription = "Abundance Trace Tree", modifier = Modifier .size(displayWidth,displayHeight) ) TraceTreeBtn(selectedId, 1, pointNormalATK, displayWidth, offset = abundanceOffsetList) TraceTreeBtn(selectedId, 2, pointSkill, displayWidth, offset = abundanceOffsetList) TraceTreeBtn(selectedId, 3, pointUltimate, displayWidth, offset = abundanceOffsetList) TraceTreeBtn(selectedId, 4, pointTalent, displayWidth, offset = abundanceOffsetList) TraceTreeBtn(selectedId, 5, pointSpecial, displayWidth, offset = abundanceOffsetList) TraceTreeBtn(selectedId, 6, arrayListOf(point6), displayWidth, offset = abundanceOffsetList) TraceTreeBtn(selectedId, 7, arrayListOf(point7), displayWidth, offset = abundanceOffsetList) TraceTreeBtn(selectedId, 8, arrayListOf(point8), displayWidth, offset = abundanceOffsetList) TraceTreeBtn(selectedId, 9, arrayListOf(point9), displayWidth, offset = abundanceOffsetList) TraceTreeBtn(selectedId, 10, arrayListOf(point10), displayWidth, offset = abundanceOffsetList) TraceTreeBtn(selectedId, 11, arrayListOf(point11), displayWidth, offset = abundanceOffsetList) TraceTreeBtn(selectedId, 12, arrayListOf(point12), displayWidth, offset = abundanceOffsetList) TraceTreeBtn(selectedId, 13, arrayListOf(point13), displayWidth, offset = abundanceOffsetList) TraceTreeBtn(selectedId, 14, arrayListOf(point14), displayWidth, offset = abundanceOffsetList) TraceTreeBtn(selectedId, 15, arrayListOf(point15), displayWidth, offset = abundanceOffsetList) TraceTreeBtn(selectedId, 16, arrayListOf(point16), displayWidth, offset = abundanceOffsetList) TraceTreeBtn(selectedId, 17, arrayListOf(point17), displayWidth, offset = abundanceOffsetList) TraceTreeBtn(selectedId, 18, arrayListOf(point18), displayWidth, offset = abundanceOffsetList) } }
0
Kotlin
2
19
f378eaa1ab23d4a761543d61fe547c0ad9de26f6
7,615
Honkai-Stargazer
Apache License 2.0
data/report/src/main/java/com/hankki/data/report/repositoryimpl/ReportRepositoryImpl.kt
Team-Hankki
816,081,730
false
{"Kotlin": 597927}
package com.hankki.data.report.repositoryimpl import android.content.Context import android.net.Uri import com.hankki.core.common.utill.ContentUriRequestBody import com.hankki.data.report.datasource.ReportDataSource import com.hankki.data.report.dto.request.ReportOtherSchoolStoreRequestDto import com.hankki.data.report.dto.request.toDto import com.hankki.data.report.dto.response.toEntity import com.hankki.domain.report.entity.CategoryEntity import com.hankki.domain.report.entity.CountEntity import com.hankki.domain.report.entity.LocationEntity import com.hankki.domain.report.entity.request.ReportStoreRequestEntity import com.hankki.domain.report.entity.request.ValidateStoreRequestEntity import com.hankki.domain.report.entity.response.GeneratedStoreResponseEntity import com.hankki.domain.report.entity.response.JogboResponseEntity import com.hankki.domain.report.entity.response.StoreValidateResponseEntity import com.hankki.domain.report.entity.response.UniversityResponseEntity import com.hankki.domain.report.entity.response.UserInfoResponseEntity import com.hankki.domain.report.repository.ReportRepository import dagger.hilt.android.qualifiers.ApplicationContext import kotlinx.serialization.encodeToString import kotlinx.serialization.json.Json import okhttp3.MediaType.Companion.toMediaType import okhttp3.RequestBody.Companion.toRequestBody import javax.inject.Inject class ReportRepositoryImpl @Inject constructor( @ApplicationContext private val context: Context, private val reportDataSource: ReportDataSource, ) : ReportRepository { override suspend fun getStoreLocation(search: String): Result<List<LocationEntity>> = runCatching { reportDataSource.getLocations(search).data.toEntity() } override suspend fun getReportCount(): Result<CountEntity> = runCatching { reportDataSource.getReportsCount().data.toEntity() } override suspend fun getStoreValidate(body: ValidateStoreRequestEntity): Result<StoreValidateResponseEntity> = runCatching { reportDataSource.getStoreValidate(body.toDto()).data.toEntity() } override suspend fun getCategories(): Result<List<CategoryEntity>> = runCatching { reportDataSource.getCategories().data.toEntity() } override suspend fun postReport( image: String?, request: ReportStoreRequestEntity, ): Result<GeneratedStoreResponseEntity> { val contentRequestBody = Json.encodeToString(request.toDto()).toRequestBody("application/json".toMediaType()) return runCatching { reportDataSource.postReport( image = if (image == null) image else ContentUriRequestBody( context, Uri.parse(image) ).toFormData("image"), request = contentRequestBody ).data.toEntity() } } override suspend fun postUniversityStore(storeId: Long, universityId: Long): Result<Unit> = runCatching { reportDataSource.postUniversityStore( ReportOtherSchoolStoreRequestDto( storeId, universityId ) ) } override suspend fun getMyUniversity(): Result<UniversityResponseEntity> = runCatching { reportDataSource.getMyUniversity().data.toEntity() } override suspend fun getUserInfo(): Result<UserInfoResponseEntity> = runCatching { reportDataSource.getUserInfo().data.toEntity() } override suspend fun getFavorites(storeId: Long): Result<List<JogboResponseEntity>> = runCatching { reportDataSource.getMyJogbo(storeId).data.toEntity() } override suspend fun addStoreAtJogbo(favoriteId: Long, storeId: Long): Result<Unit> = runCatching { reportDataSource.addStoreAtJogbo(favoriteId, storeId) } }
9
Kotlin
0
43
959b647e3b42fe1ae96d85c87ea7cc7ebfb74266
3,924
hankki-android
Apache License 2.0
generator/src/main/java/api/openevent/annotations/WriteOnly.kt
iamareebjamal
123,676,070
false
null
package api.openevent.annotations @Target(AnnotationTarget.FIELD) @MustBeDocumented annotation class WriteOnly
0
Kotlin
0
0
c38fe0877ba53aec9581e9995f0a71c7a2f2025f
111
openevent-java
Apache License 2.0
src/main/kotlin/no/nav/familie/ks/sak/kjerne/behandling/steg/vedtak/feilutbetaltvaluta/FeilutbetaltValutaService.kt
navikt
533,308,075
false
{"Kotlin": 3922933, "Gherkin": 197637, "Shell": 1839, "Dockerfile": 467}
package no.nav.familie.ks.sak.kjerne.behandling.steg.vedtak.feilutbetaltvaluta import no.nav.familie.ks.sak.api.dto.FeilutbetaltValutaDto import no.nav.familie.ks.sak.common.exception.Feil import no.nav.familie.ks.sak.common.util.tilDagMånedÅr import no.nav.familie.ks.sak.kjerne.logg.LoggService import no.nav.familie.ks.sak.kjerne.personopplysninggrunnlag.PersonopplysningGrunnlagService import no.nav.familie.ks.sak.kjerne.personopplysninggrunnlag.domene.Målform import org.springframework.stereotype.Service import org.springframework.transaction.annotation.Transactional @Service class FeilutbetaltValutaService( private val feilutbetaltValutaRepository: FeilutbetaltValutaRepository, private val loggService: LoggService, private val personopplysningGrunnlagService: PersonopplysningGrunnlagService, ) { fun hentFeilutbetaltValuta(id: Long): FeilutbetaltValuta = feilutbetaltValutaRepository.finnFeilutbetaltValuta(id) ?: throw Feil("Finner ikke feilutbetalt valuta med id=$id") @Transactional fun leggTilFeilutbetaltValuta(feilutbetaltValuta: FeilutbetaltValuta): FeilutbetaltValuta { val lagretFeilutbetaltValuta = feilutbetaltValutaRepository.save(feilutbetaltValuta) loggService.opprettFeilutbetaltValutaLagtTilLogg( feilutbetaltValuta = lagretFeilutbetaltValuta, ) return lagretFeilutbetaltValuta } @Transactional fun fjernFeilutbetaltValuta(id: Long) { loggService.opprettFeilutbetaltValutaFjernetLogg(feilutbetaltValuta = hentFeilutbetaltValuta(id)) feilutbetaltValutaRepository.deleteById(id) } fun hentAlleFeilutbetaltValutaForBehandling(behandlingId: Long) = feilutbetaltValutaRepository.finnFeilutbetalteValutaForBehandling(behandlingId = behandlingId) @Transactional fun oppdaterFeilutbetaltValuta( oppdatertFeilutbetaltValuta: FeilutbetaltValutaDto, id: Long, ): FeilutbetaltValuta { val feilutbetaltValuta = hentFeilutbetaltValuta(id) feilutbetaltValuta.fom = oppdatertFeilutbetaltValuta.fom feilutbetaltValuta.tom = oppdatertFeilutbetaltValuta.tom feilutbetaltValuta.feilutbetaltBeløp = oppdatertFeilutbetaltValuta.feilutbetaltBeløp return feilutbetaltValuta } fun beskrivPerioderMedFeilutbetaltValuta(behandlingId: Long): Set<String>? { val målform = personopplysningGrunnlagService.hentSøkersMålform(behandlingId = behandlingId) val fra = if (målform == Målform.NB) "Fra" else "Frå" val mye = if (målform == Målform.NB) "mye" else "mykje" return feilutbetaltValutaRepository .finnFeilutbetalteValutaForBehandling(behandlingId) .map { val fom = it.fom.tilDagMånedÅr() val tom = it.tom.tilDagMånedÅr() "$fra $fom til $tom er det utbetalt ${it.feilutbetaltBeløp} kroner for $mye." }.toSet() .takeIf { it.isNotEmpty() } } }
8
Kotlin
1
2
a77d04a2e987aa1722b85a2165d48cc72ca46d34
2,996
familie-ks-sak
MIT License
demo/problem-demo/main/main.kt
HoshinoTented
152,888,590
false
null
import org.hoshino9.luogu.LuoGu import org.hoshino9.luogu.LuoGuClient import org.hoshino9.luogu.page.maxPageCount import org.hoshino9.luogu.problem.BaseProblem import org.hoshino9.luogu.problem.problemList suspend fun main() { val lg = LuoGuClient() val max = lg.problemList().maxPageCount val seq = sequence { (1..max).forEach { yieldAll(lg.problemList(it).result) } } seq.forEach { println(it.pid) } }
12
Kotlin
0
34
28523e9057462aca5ac2eb0af375fb220069dbe8
420
LuoGuAPI
MIT License
app/src/main/java/com/umairadil/androidjetpack/di/FragmentScope.kt
umair13adil
139,688,287
false
null
package com.umairadil.androidjetpack.di import javax.inject.Scope @Scope @kotlin.annotation.Retention annotation class ActivityScope
0
Kotlin
4
11
2cf74f50df7329c33cda543a84540c97860c4452
134
AndroidJetpackTemplate
The Unlicense
app/src/main/java/com/ellison/demo/recognition/service/provider/RecognitionProvider.kt
ellisonchan
642,878,126
false
null
package com.ellison.demo.recognition.service.provider object RecognitionProvider { fun provideRecognition(): IRecognitionEngine = CerenceRecognitionEngine() }
0
Kotlin
0
5
20aa9c75715f36f038c98227863e72ba2ce06be4
163
AndroidUDemo
MIT License
SampleProject/app/src/main/java/projects/ealmikeew/pagingrecyclersampleproject/MainActivity.kt
EgorAlmikeev
244,010,001
false
null
package projects.ealmikeew.pagingrecyclersampleproject import android.os.Bundle import android.support.v7.app.AppCompatActivity import android.support.v7.widget.RecyclerView import android.view.View import android.widget.SearchView import android.widget.TextView class MainActivity : AppCompatActivity() { // paging list item class MyViewHolder(view: View) : RecyclerView.ViewHolder(view) { var title: TextView = view.findViewById(R.id.title) var description: TextView = view.findViewById(R.id.description) } // creates an instance of MyViewHolder private fun myViewHolderCreator(view: View) = MyViewHolder(view) // passes data from model to a view private fun myViewHolderBinder(holder: MyViewHolder, model: MyModel) { holder.apply { title.text = model.title description.text = model.description } } private lateinit var paging: PagingRecyclerView<MyViewHolder, MyModel> private lateinit var search: SearchView override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) setupViews() paging.loadNextPage() } private fun setupViews() { search = findViewById(R.id.search) paging = findViewById(R.id.paging) // Searching and filtering search.setOnQueryTextListener(object : SearchView.OnQueryTextListener { override fun onQueryTextSubmit(query: String?): Boolean { // set up a condition MyDataManager.updateSearchText(query) // restart paging since the list is going to change since the condition paging.restartPaging() // load first page with applied condition paging.loadNextPage() return true } override fun onQueryTextChange(query: String?) = true }) search.setOnCloseListener { // disable the condition MyDataManager.updateSearchText(null) // restart paging since the list is going to change since the condition disabled paging.restartPaging() // load first page without a condition paging.loadNextPage() true } paging.dataLoader = MyDataManager::myDataLoader paging.dataProvider = MyDataManager::myDataProvider paging.adapter = PagingRecyclerView.PagingAdapter( R.layout.my_list_item, ::myViewHolderCreator, ::myViewHolderBinder ) } }
0
Kotlin
0
0
b53d328adce899e54117889d5c9a4da0df75c0f7
2,620
PagingRecyclerView
MIT License
apollo-gradle-plugin/src/main/kotlin/com/apollographql/apollo/gradle/api/ApolloSourceSetExtension.kt
iwalker7
245,958,640
true
{"INI": 15, "YAML": 1, "Gradle Kotlin DSL": 19, "TOML": 1, "Shell": 4, "JSON": 76, "Markdown": 23, "Batchfile": 2, "Text": 1, "Ignore List": 9, "XML": 47, "Proguard": 1, "GraphQL": 91, "Kotlin": 243, "Java": 356, "Gradle": 9, "CODEOWNERS": 1, "JavaScript": 1, "Redirect Rules": 2, "MDX": 1, "SVG": 1, "ANTLR": 1, "Groovy": 16}
package com.apollographql.apollo.gradle.api import org.gradle.api.Project import org.gradle.api.model.ObjectFactory import javax.inject.Inject /** * @Deprecated * * This class is only there for backward compatibility reasons with the old groovy plugin */ @Deprecated("please use services instead") open class ApolloSourceSetExtension @Inject constructor(objects: ObjectFactory) { val schemaFile = objects.property(String::class.java) val exclude = objects.listProperty(String::class.java) fun setSchemaFile(schemaFile: String) { this.schemaFile.set(schemaFile) } fun setExclude(exclude: List<String>) { this.exclude.set(exclude) } fun setExclude(exclude: String) { this.exclude.set(listOf(exclude)) } }
0
null
0
1
e73e283c6bd9600db8c26ed00b3f5a0f929d9563
740
apollo-android
MIT License
app/shared/state-machine/ui/public/src/commonMain/kotlin/build/wallet/statemachine/recovery/cloud/FullAccountCloudBackupRestorationUiStateMachineImpl.kt
proto-at-block
761,306,853
false
null
package build.wallet.statemachine.recovery.cloud import androidx.compose.runtime.Composable import androidx.compose.runtime.LaunchedEffect import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.runtime.setValue import build.wallet.analytics.events.EventTracker import build.wallet.analytics.events.screen.context.NfcEventTrackerScreenIdContext.UNSEAL_CLOUD_BACKUP import build.wallet.analytics.events.screen.id.CloudEventTrackerScreenId import build.wallet.analytics.v1.Action.ACTION_APP_CLOUD_RECOVERY_KEY_RECOVERED import build.wallet.auth.AccountAuthenticator import build.wallet.auth.AuthKeyRotationManager import build.wallet.auth.AuthTokenDao import build.wallet.auth.AuthTokenScope import build.wallet.auth.logAuthFailure import build.wallet.bitcoin.AppPrivateKeyDao import build.wallet.bitkey.app.AppAuthKey import build.wallet.bitkey.f8e.FullAccountId import build.wallet.bitkey.socrec.EndorsedTrustedContact import build.wallet.cloud.backup.CloudBackupV2 import build.wallet.cloud.backup.FullAccountCloudBackupRestorer import build.wallet.cloud.backup.FullAccountCloudBackupRestorer.AccountRestoration import build.wallet.cloud.backup.SocRecV1BackupFeatures import build.wallet.cloud.backup.csek.Csek import build.wallet.cloud.backup.csek.CsekDao import build.wallet.cloud.backup.local.CloudBackupDao import build.wallet.cloud.backup.socRecDataAvailable import build.wallet.cloud.backup.v2.FullAccountFields import build.wallet.cloud.backup.v2.FullAccountKeys import build.wallet.cloud.backup.v2.SocRecV1AccountFeatures import build.wallet.crypto.PublicKey import build.wallet.crypto.SymmetricKeyImpl import build.wallet.f8e.F8eEnvironment import build.wallet.keybox.KeyboxDao import build.wallet.keybox.wallet.AppSpendingWalletProvider import build.wallet.logging.logFailure import build.wallet.notifications.DeviceTokenManager import build.wallet.platform.device.DeviceInfoProvider import build.wallet.platform.random.UuidGenerator import build.wallet.recovery.RecoverySyncer import build.wallet.recovery.socrec.PostSocRecTaskRepository import build.wallet.recovery.socrec.SocRecChallengeRepository import build.wallet.recovery.socrec.SocRecRelationshipsRepository import build.wallet.recovery.socrec.SocRecStartedChallengeDao import build.wallet.recovery.socrec.toActions import build.wallet.statemachine.core.ButtonDataModel import build.wallet.statemachine.core.ErrorData import build.wallet.statemachine.core.ErrorFormBodyModel import build.wallet.statemachine.core.LoadingBodyModel import build.wallet.statemachine.core.ScreenModel import build.wallet.statemachine.core.ScreenPresentationStyle.Root import build.wallet.statemachine.nfc.NfcSessionUIStateMachine import build.wallet.statemachine.nfc.NfcSessionUIStateMachineProps import build.wallet.statemachine.recovery.RecoverySegment import build.wallet.statemachine.recovery.cloud.CloudBackupRestorationUiState.CloudBackupFoundUiState import build.wallet.statemachine.recovery.cloud.CloudBackupRestorationUiState.CompletingCloudRecoveryUiState import build.wallet.statemachine.recovery.cloud.CloudBackupRestorationUiState.RecoveryAuthenticationState import build.wallet.statemachine.recovery.cloud.CloudBackupRestorationUiState.RestoringFromBackupFailureUiState import build.wallet.statemachine.recovery.cloud.CloudBackupRestorationUiState.RestoringFromBackupUiState import build.wallet.statemachine.recovery.cloud.CloudBackupRestorationUiState.SocRecChallengeState import build.wallet.statemachine.recovery.cloud.CloudBackupRestorationUiState.SocRecRestorationFailedState import build.wallet.statemachine.recovery.cloud.CloudBackupRestorationUiState.SocRecRestorationState import build.wallet.statemachine.recovery.cloud.CloudBackupRestorationUiState.SocialRecoveryExplanationState import build.wallet.statemachine.recovery.cloud.CloudBackupRestorationUiState.UnsealingCsek import build.wallet.statemachine.recovery.socrec.challenge.RecoveryChallengeUiProps import build.wallet.statemachine.recovery.socrec.challenge.RecoveryChallengeUiStateMachine import build.wallet.toByteString import build.wallet.toUByteList import com.github.michaelbull.result.Result import com.github.michaelbull.result.coroutines.coroutineBinding import com.github.michaelbull.result.flatMap import com.github.michaelbull.result.map import com.github.michaelbull.result.mapError import com.github.michaelbull.result.onFailure import com.github.michaelbull.result.onSuccess import kotlinx.collections.immutable.ImmutableList import kotlinx.collections.immutable.toImmutableList internal const val START_SOCIAL_RECOVERY_MESSAGE = "Starting Recovery..." // TODO(W-3756): migrate this logic to RecoveringAppFromCloudBackupDataStateMachineImpl. class FullAccountCloudBackupRestorationUiStateMachineImpl( private val accountAuthenticator: AccountAuthenticator, private val appSpendingWalletProvider: AppSpendingWalletProvider, private val authTokenDao: AuthTokenDao, private val appPrivateKeyDao: AppPrivateKeyDao, private val backupRestorer: FullAccountCloudBackupRestorer, private val cloudBackupDao: CloudBackupDao, private val csekDao: CsekDao, private val deviceInfoProvider: DeviceInfoProvider, private val deviceTokenManager: DeviceTokenManager, private val eventTracker: EventTracker, private val keyboxDao: KeyboxDao, private val nfcSessionUIStateMachine: NfcSessionUIStateMachine, private val recoveryChallengeStateMachine: RecoveryChallengeUiStateMachine, private val recoverySyncer: RecoverySyncer, private val socRecChallengeRepository: SocRecChallengeRepository, private val socialRelationshipsRepository: SocRecRelationshipsRepository, private val postSocRecTaskRepository: PostSocRecTaskRepository, private val socRecStartedChallengeDao: SocRecStartedChallengeDao, private val uuidGenerator: UuidGenerator, private val authKeyRotationManager: AuthKeyRotationManager, ) : FullAccountCloudBackupRestorationUiStateMachine { @Composable override fun model(props: FullAccountCloudBackupRestorationUiProps): ScreenModel { var uiState: CloudBackupRestorationUiState by remember { mutableStateOf(CloudBackupFoundUiState) } // Reusable model for a loading screen while completing multiple restoration steps. val loadingRestoringFromBackupModel = LoadingBodyModel( message = "Restoring from backup...", onBack = { uiState = CloudBackupFoundUiState }, id = CloudEventTrackerScreenId.LOADING_RESTORING_FROM_CLOUD_BACKUP ).asRootScreen() return when (val state = uiState) { is RecoveryAuthenticationState -> { RecoveryAuthenticationEffect(state, setState = { uiState = it }) LoadingBodyModel( message = START_SOCIAL_RECOVERY_MESSAGE, onBack = { uiState = SocialRecoveryExplanationState }, id = CloudEventTrackerScreenId.CLOUD_RECOVERY_AUTHENTICATION ).asRootScreen() } is SocRecRestorationState -> { SocRecRestoreEffect(props, state, setState = { uiState = it }) loadingRestoringFromBackupModel } is SocRecChallengeState -> { recoveryChallengeStateMachine.model( RecoveryChallengeUiProps( accountId = state.accountId, f8eEnvironment = state.f8eEnvironment, actions = socRecChallengeRepository.toActions( state.accountId, state.f8eEnvironment, state.isUsingSocRecFakes ), endorsedTrustedContacts = state.contacts, relationshipIdToSocRecPkekMap = state.accountFeatures.socRecSealedDekMap .mapValues { it.value }, sealedPrivateKeyMaterial = state.accountFeatures.socRecSealedFullAccountKeys, onExit = { uiState = CloudBackupFoundUiState }, onKeyRecovered = { uiState = SocRecRestorationState( accountId = state.accountId, it ) } ) ) } is CloudBackupFoundUiState -> CloudBackupFoundModel( devicePlatform = deviceInfoProvider.getDeviceInfo().devicePlatform, onBack = props.onExit, onRestore = { uiState = UnsealingCsek }, showSocRecButton = props.backup.socRecDataAvailable, onLostBitkeyClick = { uiState = SocialRecoveryExplanationState } ).asRootScreen() SocialRecoveryExplanationState -> { SocialRecoveryExplanationModel( onBack = { uiState = CloudBackupFoundUiState }, onContinue = { val backup = props.backup as? CloudBackupV2 val account = backup?.fullAccountFields as? SocRecV1AccountFeatures uiState = if (account == null) { RestoringFromBackupFailureUiState( errorData = ErrorData( segment = RecoverySegment.SocRec.ProtectedCustomer.Restoration, actionDescription = "Reading full account from backup", cause = Error("Backup did not contain data for full account") ), onBack = { uiState = SocialRecoveryExplanationState } ) } else { RecoveryAuthenticationState( f8eEnvironment = backup.f8eEnvironment, accountFeatures = account, backupFeatures = backup ) } } ).asRootScreen() } is UnsealingCsek -> { val sealedCsek = when (props.backup) { is CloudBackupV2 -> (props.backup.fullAccountFields as FullAccountFields).sealedHwEncryptionKey } nfcSessionUIStateMachine.model( NfcSessionUIStateMachineProps( session = { session, commands -> Csek( SymmetricKeyImpl( commands.unsealKey(session, sealedCsek.toUByteList()).toByteString() ) ) }, onSuccess = { unsealedCsek -> csekDao.set( key = sealedCsek, value = unsealedCsek ) uiState = RestoringFromBackupUiState }, onCancel = { uiState = CloudBackupFoundUiState }, isHardwareFake = props.fullAccountConfig.isHardwareFake, screenPresentationStyle = Root, eventTrackerContext = UNSEAL_CLOUD_BACKUP, segment = RecoverySegment.CloudBackup.FullAccount.Restoration, actionDescription = "Unsealing CSEK for full account cloud restoration" ) ) } is RestoringFromBackupUiState -> { RestoringFromBackupEffect(props, setState = { uiState = it }) loadingRestoringFromBackupModel } is CompletingCloudRecoveryUiState -> { CompleteCloudRecoveryEffect(props, state, setState = { uiState = it }) loadingRestoringFromBackupModel } is RestoringFromBackupFailureUiState -> ErrorFormBodyModel( title = "We were unable to restore your wallet from a backup", primaryButton = ButtonDataModel( text = "Back", onClick = { uiState = SocialRecoveryExplanationState } ), eventTrackerScreenId = CloudEventTrackerScreenId.FAILURE_RESTORE_FROM_CLOUD_BACKUP, errorData = state.errorData ).asRootScreen() is SocRecRestorationFailedState -> ErrorFormBodyModel( title = "We were unable to complete your restoration", secondaryButton = ButtonDataModel(text = "Back", onClick = props.onExit), primaryButton = ButtonDataModel( text = "Retry", onClick = { uiState = SocRecRestorationState( accountId = state.accountId, fullAccountKeys = state.fullAccountKeys ) } ), eventTrackerScreenId = CloudEventTrackerScreenId.FAILURE_RESTORE_FROM_CLOUD_BACKUP, errorData = ErrorData( segment = RecoverySegment.SocRec.ProtectedCustomer.Restoration, actionDescription = "Restoring full account from backup", cause = state.cause ) ).asRootScreen() } } @Composable private fun RestoringFromBackupEffect( props: FullAccountCloudBackupRestorationUiProps, setState: (CloudBackupRestorationUiState) -> Unit, ) { LaunchedEffect("restoring-from-backup") { backupRestorer .restoreFromBackup(cloudBackup = props.backup) .logFailure { "Error restoring keybox from cloud backup" } .onFailure { setState( RestoringFromBackupFailureUiState( errorData = ErrorData( segment = RecoverySegment.CloudBackup.FullAccount.Restoration, actionDescription = "Restoring full account from backup", cause = it ), onBack = props.onExit ) ) } .onSuccess { accountRestoration -> setState(CompletingCloudRecoveryUiState(accountRestoration)) } } } @Composable private fun CompleteCloudRecoveryEffect( props: FullAccountCloudBackupRestorationUiProps, state: CompletingCloudRecoveryUiState, setState: (CloudBackupRestorationUiState) -> Unit, ) { LaunchedEffect("completing-cloud-recovery") { handleCloudKeyRecovered(props, state.accountRestoration) .onFailure { setState( RestoringFromBackupFailureUiState( errorData = ErrorData( segment = RecoverySegment.CloudBackup.FullAccount.Restoration, actionDescription = "Authenticating with new app auth key and applying cloud backup", cause = it ), onBack = props.onExit ) ) } .onSuccess { authKeyRotationManager.recommendKeyRotation() keyboxDao .saveKeyboxAsActive(state.accountRestoration.asKeybox(uuidGenerator.random(), it)) .onFailure { dbError -> setState( RestoringFromBackupFailureUiState( errorData = ErrorData( segment = RecoverySegment.CloudBackup.FullAccount.Restoration, actionDescription = "Saving keybox as active", cause = dbError ), onBack = props.onExit ) ) } } } } @Composable private fun SocRecRestoreEffect( props: FullAccountCloudBackupRestorationUiProps, state: SocRecRestorationState, setState: (CloudBackupRestorationUiState) -> Unit, ) { LaunchedEffect("complete-socrec-restore") { coroutineBinding { val restoration = backupRestorer.restoreFromBackupWithDecryptedKeys( cloudBackup = props.backup, keysInfo = state.fullAccountKeys ).bind() // Set the flag to show the replace hardware card nudge // this flag is used by the MoneyHomeCardsUiStateMachine // and toggled off by the RecoveryInProgressDataStateMachine postSocRecTaskRepository.setHardwareReplacementNeeded(true).bind() // Remove the completed SocRec Challenge from the database socRecStartedChallengeDao.clear() // Put us into a state where we can start the hardware recovery flow val accountId = handleCloudKeyRecovered(props, restoration).bind() keyboxDao .saveKeyboxAsActive( restoration.asKeybox( keyboxId = uuidGenerator.random(), fullAccountId = accountId ) ) .bind() }.onFailure { setState( SocRecRestorationFailedState( accountId = state.accountId, fullAccountKeys = state.fullAccountKeys, cause = it ) ) } } } private suspend fun handleCloudKeyRecovered( props: FullAccountCloudBackupRestorationUiProps, accountRestoration: AccountRestoration, ): Result<FullAccountId, Error> = coroutineBinding { eventTracker.track(ACTION_APP_CLOUD_RECOVERY_KEY_RECOVERED) // Authenticate with f8e using recovered app [Global] authentication key. val globalAuthData = authenticateWithF8eAndStoreAuthTokens( f8eEnvironment = props.fullAccountConfig.f8eEnvironment, appAuthPublicKey = accountRestoration.activeAppKeyBundle.authKey, tokenScope = AuthTokenScope.Global ).bind() val accountId = FullAccountId(globalAuthData.accountId) // Authenticate with f8e using recovered app [Recovery] authentication key. authenticateWithF8eAndStoreAuthTokens( f8eEnvironment = props.fullAccountConfig.f8eEnvironment, appAuthPublicKey = accountRestoration.activeAppKeyBundle.recoveryAuthKey, tokenScope = AuthTokenScope.Recovery ).bind() // TODO(W-1535): this should be prompted by a notification prompt deviceTokenManager .addDeviceTokenIfPresentForAccount( fullAccountId = accountId, f8eEnvironment = props.fullAccountConfig.f8eEnvironment, authTokenScope = AuthTokenScope.Global ) cloudBackupDao .set(accountId.serverId, accountRestoration.cloudBackupForLocalStorage) .bind() // Clear out ongoing Lost Hardware DN recovery, if any. recoverySyncer .clear() .bind() // Attempt to sync social relationships before completing the recovery to ensure that // the background refresh doesn't delete existing TCs. But don't bind any failures. socialRelationshipsRepository.syncAndVerifyRelationships( accountId = accountId, f8eEnvironment = props.fullAccountConfig.f8eEnvironment, appAuthKey = accountRestoration.activeAppKeyBundle.authKey, hwAuthPublicKey = accountRestoration.activeHwKeyBundle.authKey ) // Attempt to sync the new wallet before completing the recovery and showing // Money Home (saving the keybox as active will complete and update UI), but // don't bind any failures. appSpendingWalletProvider.getSpendingWallet(accountRestoration.activeSpendingKeyset) .onSuccess { it.sync() } accountId } /** * Performs auth with f8e using the given [AppAuthPublicKey] and stores the resulting * tokens in [AuthTokenDao] keyed by the given [AuthTokenScope] */ private suspend fun authenticateWithF8eAndStoreAuthTokens( appAuthPublicKey: PublicKey<out AppAuthKey>, f8eEnvironment: F8eEnvironment, tokenScope: AuthTokenScope, ): Result<AccountAuthenticator.AuthData, Error> { return coroutineBinding { val authData = accountAuthenticator .appAuth( f8eEnvironment = f8eEnvironment, appAuthPublicKey = appAuthPublicKey, authTokenScope = tokenScope ) .logAuthFailure { "Error authenticating with new app auth key after recovery completed." } .bind() val fullAccountId = FullAccountId(authData.accountId) authTokenDao .setTokensOfScope(fullAccountId, authData.authTokens, tokenScope) .mapError { Error(it) } .bind() authData } } @Composable private fun RecoveryAuthenticationEffect( state: RecoveryAuthenticationState, setState: (CloudBackupRestorationUiState) -> Unit, ) { LaunchedEffect("lost-bitkey-auth") { appPrivateKeyDao.storeAppKeyPair(state.backupFeatures.appRecoveryAuthKeypair) .onFailure { setState( RestoringFromBackupFailureUiState( errorData = ErrorData( segment = RecoverySegment.SocRec.ProtectedCustomer.Restoration, actionDescription = "Storing app recovery auth key", cause = it ), onBack = { setState(SocialRecoveryExplanationState) } ) ) return@LaunchedEffect } authenticateWithF8eAndStoreAuthTokens( f8eEnvironment = state.f8eEnvironment, appAuthPublicKey = state.backupFeatures.appRecoveryAuthKeypair.publicKey, tokenScope = AuthTokenScope.Recovery ).flatMap { authData -> socialRelationshipsRepository .getRelationshipsWithoutSyncing( accountId = FullAccountId(authData.accountId), f8eEnvironment = state.f8eEnvironment ) .map { Pair(authData, it) } }.onSuccess { (authData, relationships) -> setState( SocRecChallengeState( accountId = FullAccountId(authData.accountId), f8eEnvironment = state.f8eEnvironment, contacts = relationships.endorsedTrustedContacts.toImmutableList(), isUsingSocRecFakes = state.backupFeatures.isUsingSocRecFakes, accountFeatures = state.accountFeatures, backupFeatures = state.backupFeatures ) ) }.onFailure { setState( RestoringFromBackupFailureUiState( errorData = ErrorData( segment = RecoverySegment.SocRec.ProtectedCustomer.Restoration, actionDescription = "Authenticating with new app recovery auth key, storing tokens, and syncing socrec relationships", cause = it ), onBack = { setState(SocialRecoveryExplanationState) } ) ) } } } } private sealed interface CloudBackupRestorationUiState { /** * Initial state – found wallet backup on the cloud storage. Confirm with user they want to restore. */ data object CloudBackupFoundUiState : CloudBackupRestorationUiState /** * Customer has chosen to restore. Show NFC prompt to unseal the CSEK. */ data object UnsealingCsek : CloudBackupRestorationUiState /** * Restoring the account from the backup using the CSEK. * We also track the hw authentication key since it's needed * if the customer wishes to rotate the authentication keys after the * cloud backup restoration. */ data object RestoringFromBackupUiState : CloudBackupRestorationUiState /** * Failure when restoring the account from the backup. */ data class RestoringFromBackupFailureUiState( val errorData: ErrorData, val onBack: () -> Unit, ) : CloudBackupRestorationUiState /** * Used at the end of the Cloud restoration flow * to rotate the auth keys so the device is now the active device */ data class CompletingCloudRecoveryUiState( val accountRestoration: AccountRestoration, ) : CloudBackupRestorationUiState data object SocialRecoveryExplanationState : CloudBackupRestorationUiState /** * Uses the recovery key to authenticate and restore an account from * a cloud backup. */ data class RecoveryAuthenticationState( val f8eEnvironment: F8eEnvironment, val accountFeatures: SocRecV1AccountFeatures, val backupFeatures: SocRecV1BackupFeatures, ) : CloudBackupRestorationUiState /** * Starts the Social Recovery challenge flow for restoring * using trusted contacts instead of hardware. */ data class SocRecChallengeState( val accountId: FullAccountId, val f8eEnvironment: F8eEnvironment, val contacts: ImmutableList<EndorsedTrustedContact>, val isUsingSocRecFakes: Boolean, val accountFeatures: SocRecV1AccountFeatures, val backupFeatures: SocRecV1BackupFeatures, ) : CloudBackupRestorationUiState /** * Starts restoring account data after a successful social recovery. */ data class SocRecRestorationState( val accountId: FullAccountId, val fullAccountKeys: FullAccountKeys, ) : CloudBackupRestorationUiState /** * The restoration process after a social recovery challenge failed * to complete. */ data class SocRecRestorationFailedState( val accountId: FullAccountId, val fullAccountKeys: FullAccountKeys, val cause: Error, ) : CloudBackupRestorationUiState }
3
null
6
98
1f9f2298919dac77e6791aa3f1dbfd67efe7f83c
24,529
bitkey
MIT License
composeApp/src/commonMain/kotlin/ru/slartus/boostbuddy/utils/VersionsComparer.kt
slartus
767,913,639
false
{"Kotlin": 239809, "Swift": 1264}
package ru.slartus.boostbuddy.utils internal object VersionsComparer { fun String.greaterThan(version2: String): Boolean = compareVersions(this, version2) == 1 /** * Если первая версия больше второй, то мы возвращаем 1. * Если вторая версия больше первой, то мы возвращаем -1 * 0 - равны */ fun compareVersions(version1: String, version2: String): Int { if (version1.isEmpty()) { return if (version2.isEmpty()) 0 else -1 } if (version2.isEmpty()) { return 1 } val v1 = version1.split(".") val v2 = version2.split(".") val len = maxOf(v1.size, v2.size) for (i in 0 until len) { val num1 = if (i < v1.size) v1[i].takeWhile { it.isDigit() }.toInt() else 0 val num2 = if (i < v2.size) v2[i].takeWhile { it.isDigit() }.toInt() else 0 if (num1 > num2) return 1 if (num1 < num2) return -1 } return 0 } }
0
Kotlin
0
5
a90d10683c4ce6b410c59f1413da36287bed0efd
990
BoostBuddy
Apache License 2.0
app/src/main/java/com/mantequilla/jetpackcomposetemplate/ui/theme/Theme.kt
bagussubagja
837,977,036
false
{"Kotlin": 60374}
package com.mantequilla.jetpackcomposetemplate.ui.theme import android.app.Activity import android.os.Build import androidx.compose.foundation.isSystemInDarkTheme import androidx.compose.material3.MaterialTheme import androidx.compose.material3.darkColorScheme import androidx.compose.material3.dynamicDarkColorScheme import androidx.compose.material3.dynamicLightColorScheme import androidx.compose.material3.lightColorScheme import androidx.compose.runtime.Composable import androidx.compose.runtime.SideEffect import androidx.compose.ui.graphics.toArgb import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.platform.LocalView import androidx.core.view.WindowCompat private val DarkColorScheme = darkColorScheme( primary = greenPrimary, secondary = greenSecondary, tertiary = greenTertiary ) private val LightColorScheme = lightColorScheme( primary = greenPrimary, secondary = greenSecondary, tertiary = greenTertiary, /* Other default colors to override background = Color(0xFFFFFBFE), surface = Color(0xFFFFFBFE), onPrimary = Color.White, onSecondary = Color.White, onTertiary = Color.White, onBackground = Color(0xFF1C1B1F), onSurface = Color(0xFF1C1B1F), */ ) @Composable fun JetpackComposeTemplateTheme( darkTheme: Boolean = isSystemInDarkTheme(), dynamicColor: Boolean = true, content: @Composable () -> Unit ) { MaterialTheme( typography = Typography, content = content ) }
0
Kotlin
0
0
ffdc4a31c39324e585ff938ea81fcb2431b03092
1,505
jetpack-compose-template
MIT License
Corona-Warn-App/src/main/java/de/rki/coronawarnapp/datadonation/analytics/server/DataDonationAnalyticsServer.kt
corona-warn-app
268,027,139
false
null
package de.rki.coronawarnapp.datadonation.analytics.server import dagger.Lazy import de.rki.coronawarnapp.datadonation.analytics.AnalyticsException import de.rki.coronawarnapp.server.protocols.internal.ppdd.PpaDataRequestAndroid import timber.log.Timber import javax.inject.Inject import javax.inject.Singleton @Singleton class DataDonationAnalyticsServer @Inject constructor( private val api: Lazy<DataDonationAnalyticsApiV1> ) { suspend fun uploadAnalyticsData(ppaDataRequestAndroid: PpaDataRequestAndroid.PPADataRequestAndroid) { val response = api.get().submitAndroidAnalytics(ppaDataRequestAndroid) val code = response.code().also { Timber.d("Response code: %d", it) } return when (code) { 204 -> Timber.d("Analytics upload completed successfully") 400, 401, 403 -> { val explanation = response.body()?.errorCode ?: "Unknown clientside error" throw AnalyticsException(message = explanation).also { Timber.w(it, "Analytics upload failed with 40X") } } else -> { throw AnalyticsException(message = "An unknown error occurred during the request").also { Timber.e(it, "Analytics upload failed due to a unknown error") } } } } }
6
Kotlin
514
2,495
d3833a212bd4c84e38a1fad23b282836d70ab8d5
1,378
cwa-app-android
Apache License 2.0
Kotlin/ToDo_List/app/src/main/java/com/example/todo_list/MainActivity.kt
InvisiblePro
543,933,754
false
null
package com.example.todo_list import androidx.appcompat.app.AppCompatActivity import android.os.Bundle import android.widget.Button import android.widget.EditText import androidx.appcompat.app.AppCompatDelegate import androidx.recyclerview.widget.LinearLayoutManager import androidx.recyclerview.widget.RecyclerView class MainActivity : AppCompatActivity() { lateinit var rvTodoItems : RecyclerView lateinit var todoAdapter: TodoAdapter lateinit var addTodo : Button lateinit var deletedTidi : Button lateinit var edText : EditText override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_NO); initializer() todoAdapter = TodoAdapter(mutableListOf()) rvTodoItems.adapter = todoAdapter rvTodoItems.layoutManager = LinearLayoutManager(this) addTodo.setOnClickListener { val todotitle = edText.text.toString() if (todotitle.isNotEmpty()){ val todo = Todo(todotitle) todoAdapter.addTodo(todo) edText.text.clear() } } deletedTidi.setOnClickListener { todoAdapter.deleteDoneTodos() } } fun initializer(){ rvTodoItems = findViewById(R.id.rvTodoList) addTodo = findViewById(R.id.btAddTodo) deletedTidi = findViewById(R.id.btDeleteDoneTodos) edText = findViewById(R.id.etTodoTitle) } }
0
null
129
31
6feb387e06540ccd398e3921d13edbb4a5681ef1
1,574
Hacktoberfest-2022
MIT License
buildSrc/src/main/kotlin/copyright.kt
android
263,405,600
false
null
/* * Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license * that can be found in the license/LICENSE.txt file. */ package tasks import groovy.util.Node import groovy.util.XmlParser import org.gradle.api.DefaultTask import org.gradle.api.Project import org.gradle.api.tasks.Input import org.gradle.api.tasks.InputFile import org.gradle.api.tasks.OutputFile import org.gradle.api.tasks.TaskAction import java.io.File import java.util.* open class WriteCopyrightToFile : DefaultTask() { @InputFile var path = project.file("${project.rootDir}/.idea/copyright/apache.xml") @OutputFile var outputFile: File? = null @Input var commented: Boolean = true @TaskAction fun write() { if (commented) { outputFile!!.writeText(project.readCopyrightCommented()) } else { outputFile!!.writeText(project.readCopyright()) } } fun Project.readCopyright(): String { val file = rootDir.resolve(".idea/copyright/apache.xml") assert(file.exists()) { "File $file with copyright not found" } val xmlParser = XmlParser() val node = xmlParser.parse(file) assert(node.attribute("name") == "CopyrightManager") { "Format changed occasionally?" } val copyrightBlock = node.children().filterIsInstance<Node>().single() val noticeNode = copyrightBlock.children().filterIsInstance<Node>().single { it.attribute("name") == "notice" } return noticeNode.attribute("value").toString().replace("&#36;today.year", GregorianCalendar()[Calendar.YEAR].toString()) } fun Project.readCopyrightCommented(): String { return "/*\n" + readCopyright().prependIndent(" * ") + "\n */" } }
0
null
37
316
74126637a097f5e6b099a7b7a4263468ecfda144
1,813
kotlin
Apache License 2.0
src/main/kotlin/me/syari/ss/core/time/TimeScheduler.kt
willritch87
268,227,777
true
{"Kotlin": 148932}
package me.syari.ss.core.time import me.syari.ss.core.Main.Companion.corePlugin import me.syari.ss.core.auto.Event import me.syari.ss.core.auto.OnEnable import me.syari.ss.core.scheduler.CustomScheduler.runLater import me.syari.ss.core.time.event.NextDayEvent import me.syari.ss.core.time.event.NextHourEvent import me.syari.ss.core.time.event.NextMinuteEvent import org.bukkit.event.EventHandler import java.time.DayOfWeek import java.time.LocalDateTime object TimeScheduler : OnEnable, Event { private val everyWeekScheduler = mutableMapOf<ScheduleTimeEveryWeek, MutableSet<() -> Unit>>() private val everyDayScheduler = mutableMapOf<ScheduleTimeEveryDay, MutableSet<() -> Unit>>() private val everyHourScheduler = mutableMapOf<ScheduleTimeEveryHour, MutableSet<() -> Unit>>() /** * 毎週決まった時間に実行されます * @param dayOfWeek 曜日 * @param hour 時間 * @param minute 分 * @param run その時間に実行する処理 */ fun scheduleEveryWeekAt(dayOfWeek: DayOfWeek, hour: Int, minute: Int, run: () -> Unit) { everyWeekScheduler.getOrPut(ScheduleTimeEveryWeek.create(dayOfWeek, hour, minute)) { mutableSetOf() }.add(run) } /** * 毎日決まった時間に実行されます * @param hour 時間 * @param minute 分 * @param run その時間に実行する処理 */ fun scheduleEveryDayAt(hour: Int, minute: Int, run: () -> Unit) { everyDayScheduler.getOrPut(ScheduleTimeEveryDay.create(hour, minute)) { mutableSetOf() }.add(run) } /** * 毎時決まった時間に実行されます * @param minute 分 * @param run その時間に実行する処理 */ fun scheduleEveryHourAt(minute: Int, run: () -> Unit) { everyHourScheduler.getOrPut(ScheduleTimeEveryHour.create(minute)) { mutableSetOf() }.add(run) } /** * XX:XXというフォーマットの時間を取得します * @param hour 時間 * @param minute 分 * @return [String] */ fun getFormatTime(hour: Int, minute: Int): String { return "${String.format("%2d", hour)}:${String.format("%2d", minute)}" } /** * プラグインが有効になった時に現在時間を更新します */ override fun onEnable() { val now = LocalDateTime.now() runLater(corePlugin, (60 - now.second).toLong()) { nextMinute(ScheduleTimeEveryWeek.create(now.dayOfWeek, now.hour, now.minute + 1)) } } private fun nextMinute(time: ScheduleTimeEveryWeek) { if (time.minute == 0) { if (time.hour == 0) { NextDayEvent(time.dayOfWeek) } else { NextHourEvent(time.dayOfWeek, time.hour) } } else { NextMinuteEvent(time.dayOfWeek, time.hour, time.minute) }.callEvent() runLater(corePlugin, 60 * 20) { nextMinute(time.getNextMinute()) } } @EventHandler fun onNextMinute(e: NextMinuteEvent) { val everyWeek = e.scheduleTime everyWeekScheduler[everyWeek]?.forEach { it.invoke() } val everyDay = everyWeek.everyDay everyDayScheduler[everyDay]?.forEach { it.invoke() } val everyHour = everyDay.everyHour everyHourScheduler[everyHour]?.forEach { it.invoke() } } }
0
Kotlin
0
0
0c15a57bb791844d91c60aa9e6f7c4e160e9f43b
3,105
SS-Core
Apache License 2.0
anto/src/main/java/com/example/anto/ValueEventListener.kt
tanawatnunnak
213,522,627
false
null
package com.example.anto interface ValueEventListener { fun onDataChange(responseAnto: ResponseAnto) fun onCancelled(dataBaseError: String) }
0
Kotlin
0
0
bb4658b6d62a90fc72ce697245fd764a1a74bd38
150
Android-AntoLibrary
MIT License
sample/src/main/java/com/github/qingmei2/sample/ui/main/home/HomeIntent.kt
qingmei2
167,174,767
false
null
package com.github.qingmei2.sample.ui.main.home import com.github.qingmei2.mvi.base.intent.IIntent sealed class HomeIntent : IIntent { object InitialIntent : HomeIntent() object RefreshIntent : HomeIntent() object ScrollToTopIntent : HomeIntent() data class ScrollStateChangedIntent(val state: Int) : HomeIntent() }
4
Kotlin
25
170
6fce8ebc0b123bec8684f90f9b11fa606d469c42
337
MVI-Architecture
Apache License 2.0
app/src/main/java/com/guoyi/listeninglove/api/music/MusicApi.kt
GuoyiZhang
242,757,044
false
null
package com.cyl.musiclake.api.music import com.cyl.musicapi.bean.SongComment import com.cyl.musiclake.api.music.baidu.BaiduApiServiceImpl import com.cyl.musiclake.bean.Music import com.cyl.musiclake.common.Constants import com.cyl.musiclake.api.net.ApiManager import com.cyl.musiclake.api.net.RequestCallBack import com.cyl.musiclake.utils.FileUtils import com.cyl.musiclake.utils.LogUtil import com.cyl.musiclake.utils.SPUtils import com.cyl.musiclake.utils.ToastUtils import io.reactivex.Observable import io.reactivex.ObservableOnSubscribe object MusicApi { private val TAG = "MusicApi" fun getLyricInfo(music: Music): Observable<String>? { return when (music.type) { Constants.BAIDU -> { if (music.lyric != null) { BaiduApiServiceImpl.getBaiduLyric(music) } else { BaiduApiServiceImpl.getTingSongInfo(music).flatMap { result -> music.lyric = result.lyric BaiduApiServiceImpl.getBaiduLyric(music) } } } Constants.LOCAL -> { MusicApiServiceImpl.getLocalLyricInfo(music) } else -> { MusicApiServiceImpl.getLyricInfo(music) } } } fun getMusicInfo(music: Music): Observable<Music> { //获取默认音质 var quality = SPUtils.getAnyByKey(Constants.SP_KEY_SONG_QUALITY, music.quality) //判断是否当前音质 if (music.quality != quality) { quality = when { quality >= 999000 && music.sq -> 999000 quality >= 320000 && music.hq -> 320000 quality >= 192000 && music.high -> 192000 quality >= 128000 -> 128000 else -> 128000 } } val cachePath = FileUtils.getMusicCacheDir() + music.artist + " - " + music.title + "(" + quality + ")" val downloadPath = FileUtils.getMusicDir() + music.artist + " - " + music.title + ".mp3" if (FileUtils.exists(cachePath)) { return Observable.create { music.uri = cachePath if (music.uri != null) { it.onNext(music) it.onComplete() } else { it.onError(Throwable("")) } } } else if (FileUtils.exists(downloadPath)) { return Observable.create { music.uri = downloadPath if (music.uri != null) { it.onNext(music) it.onComplete() } else { it.onError(Throwable("")) } } } return when (music.type) { Constants.BAIDU -> BaiduApiServiceImpl.getTingSongInfo(music).flatMap { result -> Observable.create(ObservableOnSubscribe<Music> { music.uri = result.uri music.lyric = result.lyric if (music.uri != null) { it.onNext(music) it.onComplete() } else { it.onError(Throwable("")) } }) } else -> { MusicApiServiceImpl.getMusicUrl(music.type ?: Constants.LOCAL, music.mid ?: "", quality).flatMap { result -> Observable.create(ObservableOnSubscribe<Music> { music.uri = result if (music.uri != null) { it.onNext(music) it.onComplete() } else { it.onError(Throwable("")) } }) } } } } fun getMusicDownloadUrl(music: Music, isCache: Boolean = false): Observable<String>? { return when (music.type) { Constants.BAIDU -> BaiduApiServiceImpl.getTingSongInfo(music).flatMap { result -> Observable.create(ObservableOnSubscribe<String> { if (result.uri != null) { it.onNext(result.uri!!) it.onComplete() } else { it.onError(Throwable("")) } }) } else -> { val br = if (isCache) music.quality else 128000 MusicApiServiceImpl.getMusicUrl(music.type!!, music.mid!!, br).flatMap { result -> Observable.create(ObservableOnSubscribe<String> { if (result.isNotEmpty()) { it.onNext(result) it.onComplete() } else { it.onError(Throwable("")) } }) } } } } fun getMusicCommentInfo(music: Music, success: (MutableList<SongComment>?) -> Unit, fail: (() -> Unit?)? = null) { if (music.type == null || music.mid == null) { fail?.invoke() return } val observable = MusicApiServiceImpl.getMusicComment(music.type!!, music.mid!!) if (observable == null) { fail?.invoke() return } ApiManager.request(observable, object : RequestCallBack<MutableList<SongComment>> { override fun success(result: MutableList<SongComment>?) { success.invoke(result) } override fun error(msg: String?) { LogUtil.e("getMusicAlbumPic", msg) fail?.invoke() } }) } fun getMusicAlbumPic(info: String, success: (String?) -> Unit, fail: (() -> Unit?)? = null) { ApiManager.request(MusicApiServiceImpl.getAlbumUrl(info), object : RequestCallBack<String> { override fun success(result: String?) { if (result == null) { fail?.invoke() } else { success.invoke(result) } } override fun error(msg: String?) { LogUtil.e("getMusicAlbumPic", msg) fail?.invoke() } }) } fun getLocalLyricInfo(path: String?): Observable<String> { return Observable.create { emitter -> try { val lyric = FileUtils.readFile(path) emitter.onNext(lyric) emitter.onComplete() } catch (e: Exception) { emitter.onError(e) } } } fun loadSongDetailInfo(vendor: String, mid: String, success: ((Music?) -> Unit)?) { val observable = MusicApiServiceImpl.getSongDetail(vendor, mid) ApiManager.request(observable, object : RequestCallBack<Music> { override fun success(result: Music) { success?.invoke(result) } override fun error(msg: String) { ToastUtils.show(msg) } }) } }
4
null
503
5
6d9442bad15910fe6d813bdf556fe1562d950947
7,252
077-Android-ListeningLove
Apache License 2.0
android-plugins/src/main/kotlin/io/github/lyxnx/gradle/android/catalogs/firebase/FirebasePlugin.kt
Lyxnx
608,846,624
false
{"Kotlin": 30504}
package io.github.lyxnx.gradle.android.catalogs.firebase import io.github.lyxnx.gradle.android.catalogs.base.CatalogsBasePlugin import io.github.lyxnx.gradle.android.catalogs.base.firebaseCatalog import io.github.lyxnx.gradle.android.catalogs.internal.GMS_PLUGIN import io.github.lyxnx.gradle.android.catalogs.internal.ensureLibrary import io.github.lyxnx.gradle.android.catalogs.internal.ensurePlugin import io.github.lyxnx.gradle.android.catalogs.internal.implementation import org.gradle.api.Project import org.gradle.api.internal.plugins.PluginRegistry import org.gradle.kotlin.dsl.apply import org.gradle.kotlin.dsl.dependencies import javax.inject.Inject /** * Configures Firebase for a module * * This will apply the `com.google.gms.google-services` plugin and add the Firebase BOM as a dependency, so the only * thing left to do is add the needed Firebase libraries */ public class FirebasePlugin @Inject constructor( private val pluginRegistry: PluginRegistry, ) : CatalogsBasePlugin() { override fun Project.configureCatalogPlugin() { pluginRegistry.ensurePlugin("Google GMS", GMS_PLUGIN) apply(plugin = GMS_PLUGIN) val catalog = firebaseCatalog dependencies { implementation(platform(catalog.ensureLibrary("bom"))) } } }
1
Kotlin
0
3
867faf734618a481736df7860aa626264f3deddf
1,306
android-gradle-catalogs
Apache License 2.0
androidApp/src/main/java/earth/levi/sage/android/viewmodel/DevicePhotosViewModel.kt
levibostian
510,489,739
false
null
package earth.levi.sage.android.viewmodel import android.Manifest import android.content.Context import android.content.Intent import android.net.Uri import android.provider.Settings import androidx.activity.result.ActivityResultLauncher import androidx.activity.result.contract.ActivityResultContracts import androidx.core.content.ContextCompat.startActivity import androidx.fragment.app.Fragment import androidx.lifecycle.ViewModel import androidx.lifecycle.viewModelScope import earth.levi.sage.db.Folder import earth.levi.sage.repository.FilesRepository import earth.levi.sage.service.AndroidHostingService import earth.levi.sage.store.LocalPhotosStore import earth.levi.sage.type.Photo import earth.levi.sage.type.RuntimePermission import earth.levi.sage.util.PermissionUtil import earth.levi.sage.util.SamplePhotosUtil import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.StateFlow import kotlinx.coroutines.flow.emptyFlow import kotlinx.coroutines.launch import kotlinx.coroutines.withContext import java.lang.ref.WeakReference class DevicePhotosViewModel( private val permissionUtil: PermissionUtil, private val localPhotosStore: LocalPhotosStore, private val samplePhotosUtil: SamplePhotosUtil ): ViewModel() { private val _devicePhotos = MutableStateFlow(emptyList<Photo>()) val devicePhotos: StateFlow<List<Photo>> = _devicePhotos private val _localPhotosPermission = MutableStateFlow(LocalFilesPermissionResult()) val localPhotosPermission: StateFlow<LocalFilesPermissionResult> = _localPhotosPermission private lateinit var requestPermissionLauncher: ActivityResultLauncher<String> private val _selectedPhoto = MutableStateFlow<Photo?>(null) val observeSelectedPhoto: StateFlow<Photo?> = _selectedPhoto var selectedPhoto: Photo? get() = _selectedPhoto.value set(value) { _selectedPhoto.value = value } private lateinit var fragment: WeakReference<Fragment> // this probably wont work because we are sharing viewmodel instance between multiple fragments..... fun initialize(fragment: Fragment) { this.fragment = WeakReference(fragment) checkPermissionStatus() requestPermissionLauncher = fragment.registerForActivityResult(ActivityResultContracts.RequestPermission()) { isGranted -> checkPermissionStatus() } } fun fetchLocalPhotos() { viewModelScope.launch { _devicePhotos.value = localPhotosStore.fetchLocalPhotos() } } fun fetchSamplePhotos() { _devicePhotos.value = samplePhotosUtil.getSamplePhotos(randomOrder = false) } fun checkPermissionStatus() { fragment.get()?.let { fragment -> val hasNeverAsked = fragment.shouldShowRequestPermissionRationale(Manifest.permission.READ_EXTERNAL_STORAGE) val hasPermission = permissionUtil.doesHavePermission(fragment.requireContext(), RuntimePermission.ACCESS_PHOTOS) _localPhotosPermission.value = LocalFilesPermissionResult(hasNeverAsked = hasNeverAsked, hasPermission = hasPermission) } } fun openAppSettings() { fragment.get()?.let { fragment -> val intent = Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS) intent.data = Uri.parse("package:${fragment.requireContext().packageName}") fragment.startActivity(intent) } } fun askPermissionLocalFiles() { requestPermissionLauncher.launch(Manifest.permission.READ_EXTERNAL_STORAGE) } data class LocalFilesPermissionResult( val hasNeverAsked: Boolean = true, val hasPermission: Boolean = false ) }
5
Kotlin
1
0
515a3418935e33fa62b994aab4cb8b3085e366c0
3,756
Sage
MIT License
compose/ui/ui/src/desktopMain/kotlin/androidx/compose/ui/res/vector/DesktopXmlVectorParser.desktop.kt
RikkaW
389,105,112
false
null
/* * Copyright 2020 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package androidx.compose.ui.res.vector import androidx.compose.ui.geometry.Offset import androidx.compose.ui.graphics.Color import androidx.compose.ui.graphics.Brush import androidx.compose.ui.graphics.PathFillType import androidx.compose.ui.graphics.SolidColor import androidx.compose.ui.graphics.StrokeCap import androidx.compose.ui.graphics.StrokeJoin import androidx.compose.ui.graphics.TileMode import androidx.compose.ui.graphics.vector.DefaultPivotX import androidx.compose.ui.graphics.vector.DefaultPivotY import androidx.compose.ui.graphics.vector.DefaultRotation import androidx.compose.ui.graphics.vector.DefaultScaleX import androidx.compose.ui.graphics.vector.DefaultScaleY import androidx.compose.ui.graphics.vector.DefaultTranslationX import androidx.compose.ui.graphics.vector.DefaultTranslationY import androidx.compose.ui.graphics.vector.EmptyPath import androidx.compose.ui.graphics.vector.ImageVector import androidx.compose.ui.graphics.vector.addPathNodes import androidx.compose.ui.res.vector.BuildContext.Group import androidx.compose.ui.unit.Density import org.w3c.dom.Element import org.w3c.dom.Node import java.util.LinkedList // Parsing logic is the same as in Android implementation // (compose/ui/ui/src/androidMain/kotlin/androidx/compose/ui/graphics/vector/compat/XmlVectorParser.kt) // // Except there is no support for linking with external resources // (for example, we can't reference to color defined in another file) // // Specification: // https://developer.android.com/reference/android/graphics/drawable/VectorDrawable private const val ANDROID_NS = "http://schemas.android.com/apk/res/android" private const val AAPT_NS = "http://schemas.android.com/aapt" private class BuildContext { val currentGroups = LinkedList<Group>() enum class Group { /** * Group that exists in xml file */ Real, /** * Group that doesn't exist in xml file. We add it manually when we see <clip-path> node. * It will be automatically popped when the real group will be popped. */ Virtual } } internal fun Element.parseVectorRoot(density: Density): ImageVector { val context = BuildContext() val builder = ImageVector.Builder( defaultWidth = attributeOrNull(ANDROID_NS, "width").parseDp(density), defaultHeight = attributeOrNull(ANDROID_NS, "height").parseDp(density), viewportWidth = attributeOrNull(ANDROID_NS, "viewportWidth")?.toFloat() ?: 0f, viewportHeight = attributeOrNull(ANDROID_NS, "viewportHeight")?.toFloat() ?: 0f ) parseVectorNodes(builder, context) return builder.build() } private fun Element.parseVectorNodes(builder: ImageVector.Builder, context: BuildContext) { childrenSequence .filterIsInstance<Element>() .forEach { it.parseVectorNode(builder, context) } } private fun Element.parseVectorNode(builder: ImageVector.Builder, context: BuildContext) { when (nodeName) { "path" -> parsePath(builder) "clip-path" -> parseClipPath(builder, context) "group" -> parseGroup(builder, context) } } private fun Element.parsePath(builder: ImageVector.Builder) { builder.addPath( pathData = addPathNodes(attributeOrNull(ANDROID_NS, "pathData")), pathFillType = attributeOrNull(ANDROID_NS, "fillType") ?.let(::parseFillType) ?: PathFillType.NonZero, name = attributeOrNull(ANDROID_NS, "name") ?: "", fill = attributeOrNull(ANDROID_NS, "fillColor")?.let(::parseStringBrush) ?: apptAttr(ANDROID_NS, "fillColor")?.let(Element::parseElementBrush), fillAlpha = attributeOrNull(ANDROID_NS, "fillAlpha")?.toFloat() ?: 1.0f, stroke = attributeOrNull(ANDROID_NS, "strokeColor")?.let(::parseStringBrush) ?: apptAttr(ANDROID_NS, "strokeColor")?.let(Element::parseElementBrush), strokeAlpha = attributeOrNull(ANDROID_NS, "strokeAlpha")?.toFloat() ?: 1.0f, strokeLineWidth = attributeOrNull(ANDROID_NS, "strokeWidth")?.toFloat() ?: 1.0f, strokeLineCap = attributeOrNull(ANDROID_NS, "strokeLineCap") ?.let(::parseStrokeCap) ?: StrokeCap.Butt, strokeLineJoin = attributeOrNull(ANDROID_NS, "strokeLineJoin") ?.let(::parseStrokeJoin) ?: StrokeJoin.Miter, strokeLineMiter = attributeOrNull(ANDROID_NS, "strokeMiterLimit")?.toFloat() ?: 1.0f, trimPathStart = attributeOrNull(ANDROID_NS, "trimPathStart")?.toFloat() ?: 0.0f, trimPathEnd = attributeOrNull(ANDROID_NS, "trimPathEnd")?.toFloat() ?: 1.0f, trimPathOffset = attributeOrNull(ANDROID_NS, "trimPathOffset")?.toFloat() ?: 0.0f ) } private fun Element.parseClipPath(builder: ImageVector.Builder, context: BuildContext) { builder.addGroup( name = attributeOrNull(ANDROID_NS, "name") ?: "", clipPathData = addPathNodes(attributeOrNull(ANDROID_NS, "pathData")) ) context.currentGroups.addLast(Group.Virtual) } private fun Element.parseGroup(builder: ImageVector.Builder, context: BuildContext) { builder.addGroup( attributeOrNull(ANDROID_NS, "name") ?: "", attributeOrNull(ANDROID_NS, "rotation")?.toFloat() ?: DefaultRotation, attributeOrNull(ANDROID_NS, "pivotX")?.toFloat() ?: DefaultPivotX, attributeOrNull(ANDROID_NS, "pivotY")?.toFloat() ?: DefaultPivotY, attributeOrNull(ANDROID_NS, "scaleX")?.toFloat() ?: DefaultScaleX, attributeOrNull(ANDROID_NS, "scaleY")?.toFloat() ?: DefaultScaleY, attributeOrNull(ANDROID_NS, "translateX")?.toFloat() ?: DefaultTranslationX, attributeOrNull(ANDROID_NS, "translateY")?.toFloat() ?: DefaultTranslationY, EmptyPath ) context.currentGroups.addLast(Group.Real) parseVectorNodes(builder, context) do { val removedGroup = context.currentGroups.removeLastOrNull() builder.clearGroup() } while (removedGroup == Group.Virtual) } private fun parseStringBrush(str: String) = SolidColor(Color(parseColorValue(str))) private fun Element.parseElementBrush(): Brush? = childrenSequence .filterIsInstance<Element>() .find { it.nodeName == "gradient" } ?.parseGradient() private fun Element.parseGradient(): Brush? { return when (attributeOrNull(ANDROID_NS, "type")) { "linear" -> parseLinearGradient() "radial" -> parseRadialGradient() "sweep" -> parseSweepGradient() else -> null } } @Suppress("CHANGING_ARGUMENTS_EXECUTION_ORDER_FOR_NAMED_VARARGS") private fun Element.parseLinearGradient() = Brush.linearGradient( colorStops = parseColorStops(), start = Offset( attributeOrNull(ANDROID_NS, "startX")?.toFloat() ?: 0f, attributeOrNull(ANDROID_NS, "startY")?.toFloat() ?: 0f ), end = Offset( attributeOrNull(ANDROID_NS, "endX")?.toFloat() ?: 0f, attributeOrNull(ANDROID_NS, "endY")?.toFloat() ?: 0f ), tileMode = attributeOrNull(ANDROID_NS, "tileMode")?.let(::parseTileMode) ?: TileMode.Clamp ) @Suppress("CHANGING_ARGUMENTS_EXECUTION_ORDER_FOR_NAMED_VARARGS") private fun Element.parseRadialGradient() = Brush.radialGradient( colorStops = parseColorStops(), center = Offset( attributeOrNull(ANDROID_NS, "centerX")?.toFloat() ?: 0f, attributeOrNull(ANDROID_NS, "centerY")?.toFloat() ?: 0f ), radius = attributeOrNull(ANDROID_NS, "gradientRadius")?.toFloat() ?: 0f, tileMode = attributeOrNull(ANDROID_NS, "tileMode")?.let(::parseTileMode) ?: TileMode.Clamp ) @Suppress("CHANGING_ARGUMENTS_EXECUTION_ORDER_FOR_NAMED_VARARGS") private fun Element.parseSweepGradient() = Brush.sweepGradient( colorStops = parseColorStops(), center = Offset( attributeOrNull(ANDROID_NS, "centerX")?.toFloat() ?: 0f, attributeOrNull(ANDROID_NS, "centerY")?.toFloat() ?: 0f, ) ) private fun Element.parseColorStops(): Array<Pair<Float, Color>> { val items = childrenSequence .filterIsInstance<Element>() .filter { it.nodeName == "item" } .toList() val colorStops = items.mapIndexedNotNullTo(mutableListOf()) { index, item -> item.parseColorStop(defaultOffset = index.toFloat() / items.lastIndex.coerceAtLeast(1)) } if (colorStops.isEmpty()) { val startColor = attributeOrNull(ANDROID_NS, "startColor")?.let(::parseColorValue) val centerColor = attributeOrNull(ANDROID_NS, "centerColor")?.let(::parseColorValue) val endColor = attributeOrNull(ANDROID_NS, "endColor")?.let(::parseColorValue) if (startColor != null) { colorStops.add(0f to Color(startColor)) } if (centerColor != null) { colorStops.add(0.5f to Color(centerColor)) } if (endColor != null) { colorStops.add(1f to Color(endColor)) } } return colorStops.toTypedArray() } private fun Element.parseColorStop(defaultOffset: Float): Pair<Float, Color>? { val offset = attributeOrNull(ANDROID_NS, "offset")?.toFloat() ?: defaultOffset val color = attributeOrNull(ANDROID_NS, "color")?.let(::parseColorValue) ?: return null return offset to Color(color) } private fun Element.attributeOrNull(namespace: String, name: String): String? { val value = getAttributeNS(namespace, name) return if (value.isNotBlank()) value else null } /** * Attribute of an element can be represented as a separate child: * * <path ...> * <aapt:attr name="android:fillColor"> * <gradient ... * ... * </gradient> * </aapt:attr> * </path> * * instead of: * * <path android:fillColor="red" ... /> */ private fun Element.apptAttr( namespace: String, name: String ): Element? { val prefix = lookupPrefix(namespace) ?: return null return childrenSequence .filterIsInstance<Element>() .find { it.namespaceURI == AAPT_NS && it.localName == "attr" && it.getAttribute("name") == "$prefix:$name" } } private val Element.childrenSequence get() = sequence<Node> { for (i in 0 until childNodes.length) { yield(childNodes.item(i)) } }
9
null
950
7
6d53f95e5d979366cf7935ad7f4f14f76a951ea5
10,794
androidx
Apache License 2.0
app/src/main/java/com/android/mvvm/entity/NumberResponse.kt
chenkaik
292,511,076
false
null
package com.android.mvvm.entity import com.android.mvvm.https.response.BaseResponse /** * date: 2020/9/25 * desc: */ data class NumberResponse( val MSG_BODY: MSGBODY ) : BaseResponse(){ data class MSGBODY( val Result: String ) }
0
Kotlin
0
0
63fe66d8a92ec6699a0ea09711236847e6ec5db6
257
AndroidMVVM
Apache License 2.0
app/src/main/java/org/stepik/android/presentation/profile_detail/ProfileDetailView.kt
StepicOrg
42,045,161
false
{"Kotlin": 4281147, "Java": 1001895, "CSS": 5482, "Shell": 618}
package org.stepik.android.presentation.profile_detail import org.stepik.android.domain.profile.model.ProfileData interface ProfileDetailView { fun setState(profileData: ProfileData?) }
13
Kotlin
54
189
dd12cb96811a6fc2a7addcd969381570e335aca7
191
stepik-android
Apache License 2.0
WeatherAppKotlin/app/src/main/java/com/guido/weatherappkotlin/Utilities/ApiUtilities.kt
santiagoguido
506,688,823
false
null
package com.guido.weatherappkotlin.Utilities import retrofit2.Retrofit import retrofit2.converter.gson.GsonConverterFactory object ApiUtilities { private var retrofit:Retrofit?=null var BASE_URL="https://api.openweathermap.org/data/2.5/"; fun getApiInterface():ApiInterface?{ if(retrofit==null) { retrofit=Retrofit.Builder().baseUrl(BASE_URL).addConverterFactory(GsonConverterFactory.create()).build() } return retrofit!!.create(ApiInterface::class.java) } }
0
null
1
1
0168d1754ddfe870c4b18911fefbc9a333fb7d10
521
WeatherAppKotlin-Complete
Apache License 2.0
android-test-framework/testSrc/com/android/tools/idea/testing/ProjectServiceRule.kt
JetBrains
60,701,247
false
{"Kotlin": 53054415, "Java": 43443054, "Starlark": 1332164, "HTML": 1218044, "C++": 507658, "Python": 191041, "C": 71660, "Lex": 70302, "NSIS": 58238, "AIDL": 35382, "Shell": 29838, "CMake": 27103, "JavaScript": 18437, "Smali": 7580, "Batchfile": 7357, "RenderScript": 4411, "Clean": 3522, "Makefile": 2495, "IDL": 19}
/* * Copyright (C) 2022 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.android.tools.idea.testing import com.intellij.openapi.util.Disposer import com.intellij.testFramework.ProjectRule import com.intellij.testFramework.registerOrReplaceServiceInstance import org.junit.rules.ExternalResource /** A rule that installs a temporary project service in a test. */ class ProjectServiceRule<T : Any>( private val projectRule: ProjectRule, private val serviceInterface: Class<T>, private val instanceProvider: () -> T, ) : ExternalResource() { private val disposable = Disposer.newDisposable("ProjectServiceRule") override fun before() { projectRule.project.registerOrReplaceServiceInstance(serviceInterface, instanceProvider(), disposable) } override fun after() { Disposer.dispose(disposable) } companion object { operator fun <T : Any> invoke(projectRule: ProjectRule, serviceInterface: Class<T>, instance: T): ProjectServiceRule<T> { return ProjectServiceRule(projectRule, serviceInterface) { instance } } } }
5
Kotlin
227
948
10110983c7e784122d94c7467e9d243aba943bf4
1,616
android
Apache License 2.0
analysis/analysis-api-fir/src/org/jetbrains/kotlin/analysis/api/fir/symbols/pointers/KtFirEnumEntryInitializerSymbolPointer.kt
JetBrains
3,432,266
false
{"Kotlin": 78346118, "Java": 6692370, "Swift": 4062767, "C": 2609482, "C++": 1962762, "Objective-C++": 169966, "JavaScript": 138328, "Python": 59488, "Shell": 35024, "TypeScript": 22800, "Lex": 18369, "Groovy": 17400, "Objective-C": 15578, "Batchfile": 11746, "CSS": 11368, "Ruby": 10470, "Dockerfile": 9857, "EJS": 5241, "HTML": 4877, "CMake": 4448, "Pascal": 1698, "FreeMarker": 1393, "Roff": 725, "LLVM": 395, "Scala": 80}
/* * Copyright 2010-2022 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.api.fir.symbols.pointers import org.jetbrains.kotlin.analysis.api.KtAnalysisSession import org.jetbrains.kotlin.analysis.api.fir.KtFirAnalysisSession import org.jetbrains.kotlin.analysis.api.fir.symbols.KtFirEnumEntryInitializerSymbol import org.jetbrains.kotlin.analysis.api.fir.symbols.KtFirEnumEntrySymbol import org.jetbrains.kotlin.analysis.api.symbols.KtSymbol import org.jetbrains.kotlin.analysis.api.symbols.pointers.KtSymbolPointer internal class KtFirEnumEntryInitializerSymbolPointer( private val ownerPointer: KtSymbolPointer<KtFirEnumEntrySymbol>, ) : KtSymbolPointer<KtFirEnumEntryInitializerSymbol>() { @Deprecated("Consider using org.jetbrains.kotlin.analysis.api.KtAnalysisSession.restoreSymbol") override fun restoreSymbol(analysisSession: KtAnalysisSession): KtFirEnumEntryInitializerSymbol? { require(analysisSession is KtFirAnalysisSession) val owner = with(analysisSession) { ownerPointer.restoreSymbol() } return owner?.enumEntryInitializer } override fun pointsToTheSameSymbolAs(other: KtSymbolPointer<KtSymbol>): Boolean = this === other || other is KtFirEnumEntryInitializerSymbolPointer && other.ownerPointer.pointsToTheSameSymbolAs(ownerPointer) }
182
Kotlin
5617
47,637
d257153a50bdaa761d54bbc9fd1c5d78a3769f0f
1,515
kotlin
Apache License 2.0
app/src/main/java/com/example/shrinecompose/ui/theme/Type.kt
c5inco
388,989,613
false
null
@file:Suppress("MagicNumber") package io.petros.movies.corecompose.ui import androidx.compose.material.Typography import androidx.compose.ui.text.TextStyle import androidx.compose.ui.text.font.FontFamily import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.unit.sp object LightTypography { val typography = Typography( defaultFontFamily = FontFamily.Default, h1 = TextStyle( fontWeight = FontWeight.Light, fontSize = 96.sp, letterSpacing = (-1.5).sp, ), h2 = TextStyle( fontWeight = FontWeight.Light, fontSize = 60.sp, letterSpacing = (-0.5).sp, ), h3 = TextStyle( fontWeight = FontWeight.Normal, fontSize = 48.sp, letterSpacing = 0.sp, ), h4 = TextStyle( fontWeight = FontWeight.Normal, fontSize = 34.sp, letterSpacing = 0.25.sp, ), h5 = TextStyle( fontWeight = FontWeight.Normal, fontSize = 24.sp, letterSpacing = 0.sp, ), h6 = TextStyle( fontWeight = FontWeight.Medium, fontSize = 20.sp, letterSpacing = 0.15.sp, ), subtitle1 = TextStyle( fontWeight = FontWeight.Normal, fontSize = 16.sp, letterSpacing = 0.15.sp, ), subtitle2 = TextStyle( fontWeight = FontWeight.Medium, fontSize = 14.sp, letterSpacing = 0.1.sp, ), body1 = TextStyle( fontWeight = FontWeight.Normal, fontSize = 16.sp, letterSpacing = 0.5.sp, ), body2 = TextStyle( fontWeight = FontWeight.Normal, fontSize = 14.sp, letterSpacing = 0.25.sp, ), button = TextStyle( fontWeight = FontWeight.Medium, fontSize = 14.sp, letterSpacing = 1.25.sp, ), caption = TextStyle( fontWeight = FontWeight.Normal, fontSize = 12.sp, letterSpacing = 0.4.sp, ), overline = TextStyle( fontWeight = FontWeight.Normal, fontSize = 10.sp, letterSpacing = 1.5.sp, ), ) } object DarkTypography { val typography = Typography( h1 = TextStyle( fontWeight = FontWeight.Light, fontSize = 96.sp, letterSpacing = (-1.5).sp, ), h2 = TextStyle( fontWeight = FontWeight.Light, fontSize = 60.sp, letterSpacing = (-0.5).sp, ), h3 = TextStyle( fontWeight = FontWeight.Normal, fontSize = 48.sp, letterSpacing = 0.sp, ), h4 = TextStyle( fontWeight = FontWeight.Normal, fontSize = 34.sp, letterSpacing = 0.25.sp, ), h5 = TextStyle( fontWeight = FontWeight.Normal, fontSize = 24.sp, letterSpacing = 0.sp, ), h6 = TextStyle( fontWeight = FontWeight.Medium, fontSize = 20.sp, letterSpacing = 0.15.sp, ), subtitle1 = TextStyle( fontWeight = FontWeight.Normal, fontSize = 16.sp, letterSpacing = 0.15.sp, ), subtitle2 = TextStyle( fontWeight = FontWeight.Medium, fontSize = 14.sp, letterSpacing = 0.1.sp, ), body1 = TextStyle( fontWeight = FontWeight.Normal, fontSize = 16.sp, letterSpacing = 0.5.sp, ), body2 = TextStyle( fontWeight = FontWeight.Normal, fontSize = 14.sp, letterSpacing = 0.25.sp, ), button = TextStyle( fontWeight = FontWeight.Medium, fontSize = 14.sp, letterSpacing = 1.25.sp, ), caption = TextStyle( fontWeight = FontWeight.Normal, fontSize = 12.sp, letterSpacing = 0.4.sp, ), overline = TextStyle( fontWeight = FontWeight.Normal, fontSize = 10.sp, letterSpacing = 1.5.sp, ), ) }
4
null
3
5
2275e7332f7d2eacb24dcc10dc6c21e98f4cdb97
4,324
Shrine-Compose-Stream
Apache License 2.0
kgraphql/src/test/kotlin/com/apurebase/kgraphql/specification/language/SelectionSetsSpecificationTest.kt
stuebingerb
872,399,797
false
null
package com.apurebase.kgraphql.specification.language import com.apurebase.kgraphql.Actor import com.apurebase.kgraphql.Specification import com.apurebase.kgraphql.defaultSchema import com.apurebase.kgraphql.deserialize import com.apurebase.kgraphql.extract import org.hamcrest.CoreMatchers.equalTo import org.hamcrest.MatcherAssert.assertThat import org.junit.Test @Specification("2.4 Selection Sets") class SelectionSetsSpecificationTest { val age = 432 val schema = defaultSchema { query("actor") { resolver { -> Actor("<NAME>", age) } } } @Test fun `operation selects the set of information it needs`() { val response = deserialize(schema.executeBlocking("{actor{name, age}}")) val map = response.extract<Map<String, Any>>("data/actor") assertThat(map, equalTo(mapOf("name" to "<NAME>", "age" to age))) } @Test fun `operation selects the set of information it needs 2`() { val response = deserialize(schema.executeBlocking("{actor{name}}")) val map = response.extract<Map<String, Any>>("data/actor") assertThat(map, equalTo(mapOf<String, Any>("name" to "<NAME>"))) } @Test fun `operation selects the set of information it needs 3`() { val response = deserialize(schema.executeBlocking("{actor{age}}")) val map = response.extract<Map<String, Any>>("data/actor") assertThat(map, equalTo(mapOf<String, Any>("age" to age))) } }
17
null
1
3
f15b4e5327aff0bf3e011211405aa4b6dc8f36f1
1,484
KGraphQL
MIT License
src/main/java/dev/chieppa/wrapper/util/TemporalAccessor.kt
nrc4867
368,734,815
false
null
package dev.chieppa.wrapper.util import kotlinx.serialization.ExperimentalSerializationApi import kotlinx.serialization.KSerializer import kotlinx.serialization.builtins.MapSerializer import kotlinx.serialization.builtins.serializer import kotlinx.serialization.descriptors.PrimitiveKind import kotlinx.serialization.descriptors.PrimitiveSerialDescriptor import kotlinx.serialization.descriptors.SerialDescriptor import kotlinx.serialization.encoding.Decoder import kotlinx.serialization.encoding.Encoder import java.security.InvalidKeyException import java.time.temporal.ChronoField import java.time.temporal.TemporalAccessor import java.time.temporal.TemporalField import java.time.temporal.WeekFields import java.util.* private val weekBasedYear = WeekFields.SUNDAY_START.weekBasedYear() private val AO3WrapperSupportedAccessors = setOf(ChronoField.DAY_OF_MONTH, ChronoField.MONTH_OF_YEAR, weekBasedYear) private class AO3TemporalAccessor(val day: Long, val month: Long, val year: Long): TemporalAccessor { override fun isSupported(field: TemporalField?): Boolean { return AO3WrapperSupportedAccessors.contains(field) } override fun getLong(field: TemporalField?): Long { return when(field) { ChronoField.DAY_OF_MONTH -> day ChronoField.MONTH_OF_YEAR -> month weekBasedYear -> year else -> {0} } } } class TemporalFieldSerializer : KSerializer<TemporalField> { override val descriptor: SerialDescriptor = PrimitiveSerialDescriptor("Field", PrimitiveKind.STRING) override fun deserialize(decoder: Decoder): TemporalField { return when(val field = decoder.decodeString()) { "DAY" -> ChronoField.DAY_OF_MONTH "MONTH" -> ChronoField.MONTH_OF_YEAR "YEAR" -> weekBasedYear else -> throw InvalidKeyException(field) } } override fun serialize(encoder: Encoder, value: TemporalField) { when(value) { ChronoField.DAY_OF_MONTH -> encoder.encodeString("DAY") ChronoField.MONTH_OF_YEAR -> encoder.encodeString("MONTH") weekBasedYear -> encoder.encodeString("YEAR") else -> encoder.encodeString("UNKNOWN_${value.getDisplayName(Locale.ENGLISH)}") } } } class TemporalAccessorSerializer : KSerializer<TemporalAccessor> { private val delegateDescriptor = MapSerializer(TemporalFieldSerializer(), Int.serializer()) @OptIn(ExperimentalSerializationApi::class) override val descriptor: SerialDescriptor = SerialDescriptor("TemporalAccessor", delegateDescriptor.descriptor) override fun deserialize(decoder: Decoder): TemporalAccessor { val decoded = decoder.decodeSerializableValue(delegateDescriptor) return AO3TemporalAccessor( day = decoded[ChronoField.DAY_OF_MONTH]?.toLong() ?: 1, month = decoded[ChronoField.MONTH_OF_YEAR]?.toLong() ?: 1, year = decoded[weekBasedYear]?.toLong() ?: 2000 ) } override fun serialize(encoder: Encoder, value: TemporalAccessor) { val encoding = mapOf<TemporalField, Int>( Pair(ChronoField.DAY_OF_MONTH, value.get(ChronoField.DAY_OF_MONTH)), Pair(ChronoField.MONTH_OF_YEAR, value.get(ChronoField.MONTH_OF_YEAR)), Pair(weekBasedYear, value.get(weekBasedYear)) ) encoder.encodeSerializableValue(delegateDescriptor, encoding) } }
0
Kotlin
0
0
0c57cf295e806feb5ec5a96b55f1108329a203d0
3,443
AO3-Parser
MIT License
app/src/androidTest/java/yodeput/android/sample/app/MainActivityTest.kt
yodeput
460,309,812
false
{"Kotlin": 197975}
package yodeput.android.sample.app import androidx.test.ext.junit.rules.ActivityScenarioRule import androidx.test.ext.junit.runners.AndroidJUnit4 import org.junit.Rule import org.junit.Test import org.junit.runner.RunWith import yodeput.mobile.banking.MainActivity @RunWith(AndroidJUnit4::class) class MainActivityTest { @Rule @JvmField val activityTestRule = ActivityScenarioRule(MainActivity::class.java) @Test fun shouldBeAbleToLaunchMainScreen() { } @Test fun shouldBeAbleToDisplayDetailScreen() { } }
0
Kotlin
0
16
e7f9766817c9a83a779251ce35dc9ea395b513e3
549
jetpack-compose-modular-mobile-banking
The Unlicense
sdk/android/src/main/java/com/reactnativehypertracksdk/common/SdkMethod.kt
hypertrack
189,071,581
false
null
package com.reactnativehypertracksdk.common /** * The list of available methods in the SDK API. * It is used to match method calls in some wrappers (like Flutter) * Enum naming convention is ignored to make datatype sync across platforms easier. * Using Swift naming convention. */ internal enum class SdkMethod { addGeotag, getDeviceID, getDynamicPublishableKey, getErrors, getIsAvailable, getIsTracking, getLocation, getMetadata, getName, locate, setDynamicPublishableKey, setIsAvailable, setIsTracking, setMetadata, setName, }
2
null
8
7
b2923837857bee29c3c933f00be3daedd6da8078
596
sdk-react-native
MIT License
src/test/kotlin/no/nav/personbruker/dittnav/eventaggregator/oppgave/testOppgaveQueries.kt
navikt
189,239,389
false
null
package no.nav.personbruker.dittnav.eventaggregator.oppgave import no.nav.personbruker.dittnav.eventaggregator.common.database.util.list import no.nav.personbruker.dittnav.eventaggregator.common.database.util.singleResult import java.sql.Connection fun Connection.getAllOppgave(): List<Oppgave> = prepareStatement("""SELECT * FROM oppgave""") .use { it.executeQuery().list { toOppgave() } } fun Connection.getAllOppgaveByAktiv(aktiv: Boolean): List<Oppgave> = prepareStatement("""SELECT * FROM oppgave WHERE aktiv = ?""") .use { it.setBoolean(1, aktiv) it.executeQuery().list { toOppgave() } } fun Connection.getOppgaveByFodselsnummer(fodselsnummer: String): List<Oppgave> = prepareStatement("""SELECT * FROM oppgave WHERE fodselsnummer = ?""") .use { it.setString(1, fodselsnummer) it.executeQuery().list { toOppgave() } } fun Connection.getOppgaveById(id: Int): Oppgave = prepareStatement("""SELECT * FROM oppgave WHERE id = ?""") .use { it.setInt(1, id) it.executeQuery().singleResult { toOppgave() } } fun Connection.getOppgaveByEventId(eventId: String): Oppgave = prepareStatement("""SELECT * FROM oppgave WHERE eventId = ?""") .use { it.setString(1, eventId) it.executeQuery().singleResult { toOppgave() } } fun Connection.deleteAllOppgave() = prepareStatement("""DELETE FROM OPPGAVE""") .use {it.execute()} fun Connection.deleteOppgaveWithEventId(eventId: String) = prepareStatement("""DELETE FROM OPPGAVE WHERE eventId = ?""") .use { it.setString(1, eventId) it.execute() }
0
Kotlin
0
1
a55db5d4c4f754454890cdd54d472227fa91a05d
1,942
dittnav-event-aggregator
MIT License
inpertio-client-kotlin/src/test/kotlin/tech/harmonysoft/oss/inpertio/client/factory/impl/KotlinConfigProviderFactoryTest.kt
inpertio
792,802,600
false
null
package tech.harmonysoft.oss.inpertio.client.factory.impl import org.assertj.core.api.Assertions.assertThat import org.junit.jupiter.api.BeforeEach import org.junit.jupiter.api.Test import tech.harmonysoft.oss.inpertio.client.context.Context import tech.harmonysoft.oss.inpertio.client.context.ContextProvider import tech.harmonysoft.oss.inpertio.client.event.ConfigChangedEvent import tech.harmonysoft.oss.inpertio.client.factory.ConfigProviderFactory internal class KotlinConfigProviderFactoryTest { private lateinit var data: MutableMap<String, Any> private lateinit var eventManager: TestConfigEventManager private lateinit var factory: ConfigProviderFactory @BeforeEach fun setUp() { data = mutableMapOf() eventManager = TestConfigEventManager() factory = KotlinConfigProviderFactory(object : ContextProvider { override val context = Context.builder { data[it] }.build() }, eventManager) } @Test fun `when raw2public config is built then it is cached`() { data["data1"] = "first" val configProvider = factory.build(Config1::class.java) { Config2(it.data1) } assertThat(configProvider.data.data2).isEqualTo("first") data["data"] = "second" assertThat(configProvider.data.data2).isEqualTo("first") } @Test fun `when raw2public config is built then probe shows the actual data`() { data["data1"] = "first" val configProvider = factory.build(Config1::class.java) { Config2(it.data1) } assertThat(configProvider.data.data2).isEqualTo("first") data["data1"] = "second" assertThat(configProvider.probe().data2).isEqualTo("second") assertThat(configProvider.data.data2).isEqualTo("first") } @Test fun `when refresh is performed on raw2public config provider then it works as expected`() { data["data1"] = "first" val configProvider = factory.build(Config1::class.java) { Config2(it.data1) } assertThat(configProvider.data.data2).isEqualTo("first") data["data1"] = "second" configProvider.refresh() assertThat(configProvider.data.data2).isEqualTo("second") } @Test fun `when row2public config is changed then the change event is fired`() { data["data1"] = "1" val configProvider = factory.build(Config1::class.java) { Config2(it.data1 + (it.data1.toInt() + 1)) } assertThat(configProvider.data.data2).isEqualTo("12") data["data1"] = "2" configProvider.refresh() assertThat(eventManager.firedEvents).containsOnly(ConfigChangedEvent(Config2("12"), Config2("23"))) } @Test fun `when low level config is changed then its derived configs are changed`() { data["data1"] = "1" val configProvider1 = factory.build(Config1::class.java) { Config2(it.data1 + (it.data1.toInt() + 1)) } val configProvider2 = factory.build(listOf(configProvider1)) { source -> val data2 = source.get(Config2::class.java) Config3(data2.data2 + (data2.data2.toInt() + 1)) } data["data1"] = "2" configProvider1.refresh() assertThat(configProvider2.data.data3).isEqualTo("2324") } } data class Config1( val data1: String ) data class Config2( val data2: String ) data class Config3( val data3: String )
1
Kotlin
0
0
bff79f31c8e87c68e8f3dfcf1c80217c757ebc78
3,514
configurario-client-jvm
MIT License
src/main/kotlin/net/papierkorb2292/command_crafter/editor/debugger/server/breakpoints/UnparsedServerBreakpoint.kt
Papierkorb2292
584,879,864
false
{"Kotlin": 714339, "Java": 422878, "TypeScript": 32500, "JavaScript": 2311, "SCSS": 1936}
package net.papierkorb2292.command_crafter.editor.debugger.server.breakpoints import net.papierkorb2292.command_crafter.editor.debugger.helper.copy import org.eclipse.lsp4j.debug.SourceBreakpoint data class UnparsedServerBreakpoint( val id: Int, val sourceReference: Int?, val sourceBreakpoint: SourceBreakpoint, val originBreakpointId: Int? = null ) { fun copy() = UnparsedServerBreakpoint( id, sourceReference, sourceBreakpoint.copy(), originBreakpointId ) }
1
Kotlin
0
7
ae01c01e8c69a1930d87557c0eefa7b76dd39c52
518
CommandCrafter
MIT License
rxloaderextensions/src/main/java/io/carlol/android/rxloaderextensions/module/ViewRxLoaderModule.kt
carlol
214,839,472
false
null
package io.carlol.rxloaderextensions.module import android.view.View import io.carlol.rxloaderextensions.module.interfaces.IRxLoaderModule /** * Created on 2019-10-02. */ open class ViewRxLoaderModule(protected val view: View) : IRxLoaderModule { override fun startLoader() { view.visibility = View.VISIBLE } override fun stopLoader() { view.visibility = View.GONE } }
0
Kotlin
0
0
b5701537971a1989c1408fc6929d2e394096933d
411
RxLoaderExtensions
MIT License
app/src/main/java/com/skyyo/template/application/repositories/auth/AuthRepository.kt
Skyyo
325,519,535
false
null
package com.skyyo.template.application.repositories.auth import com.skyyo.template.application.CODE_200 import com.skyyo.template.application.models.remote.SignInRequest import com.skyyo.template.application.models.remote.SignUpRequest import com.skyyo.template.application.models.remote.SocialSignInRequest import com.skyyo.template.application.network.calls.AuthCalls import com.skyyo.template.application.persistance.DataStoreManager import com.skyyo.template.utils.extensions.tryOrNull import javax.inject.Inject import javax.inject.Singleton @Singleton class AuthRepository @Inject constructor( private val authCalls: AuthCalls, private val dataStoreManager: DataStoreManager ) { suspend fun signIn(request: SignInRequest): SignInResult { val response = tryOrNull { authCalls.signIn(request) } return when { response?.code() == CODE_200 -> { // TODO do conversions/store tokens etc. when { response.body()!!.firstLogin -> SignInResult.SuccessFirstTime else -> SignInResult.Success } } else -> SignInResult.NetworkError } } suspend fun signUp(signUpRequest: SignUpRequest): SignUpResult { val response = tryOrNull { authCalls.signUp(signUpRequest) } // TODO do conversions/store tokens etc. return when { response?.code() == CODE_200 -> SignUpResult.Success else -> SignUpResult.NetworkError } } suspend fun authGoogle(request: SocialSignInRequest): SocialSignInResult { val response = tryOrNull { authCalls.authGoogle(request) } response ?: return SocialSignInResult.NetworkError // TODO do conversions/store tokens etc. return if (response.firstLogin) SocialSignInResult.SuccessFirstTime else SocialSignInResult.Success } suspend fun authApple(request: SocialSignInRequest): SocialSignInResult { val response = tryOrNull { authCalls.authApple(request) } response ?: return SocialSignInResult.NetworkError // TODO do conversions/store tokens etc. return if (response.firstLogin) SocialSignInResult.SuccessFirstTime else SocialSignInResult.Success } suspend fun authFacebook(request: SocialSignInRequest): SocialSignInResult { val response = tryOrNull { authCalls.authFacebook(request) } response ?: return SocialSignInResult.NetworkError // TODO do conversions/store tokens etc. return if (response.firstLogin) SocialSignInResult.SuccessFirstTime else SocialSignInResult.Success } }
0
Kotlin
6
21
e56cd417b29334be2ed1487042b4d89d923bf027
2,643
android-template
MIT License
MeetingRefApp/src/main/java/com/visionable/meetingrefapp/recyclerview/adapters/VideoRecyclerViewAdapter.kt
visionable-public
369,285,170
false
null
package com.visionable.meetingrefapp.recyclerview.adapters import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.fragment.app.FragmentActivity import androidx.recyclerview.widget.RecyclerView import com.visionable.meetingrefapp.data.VideoStreamItem import com.visionable.meetingrefapp.databinding.VideoStreamCardBinding import com.visionable.meetingrefapp.fragments.MeetingFragment import com.visionable.meetingrefapp.fragments.SiteInfoDialogFragment /** * Custom [RecyclerView.Adapter] to display the video streams available for the call * * @property videoStreamList -> [List<VideoStreamItem>]: Full list of items to display * @property activity -> [FragmentActivity]: Used to display the Site Info Dialog (Context needed) */ class VideoRecyclerViewAdapter( private val videoStreamList: List<VideoStreamItem>, private val activity: FragmentActivity? ) : RecyclerView.Adapter<VideoRecyclerViewAdapter.VideoRecyclerViewHolder>() { init { /** * IMPORTANT: Adding this line will prevent the RecyclerView from recycling the video views * and shuffling them as you scroll */ setHasStableIds(true) } inner class VideoRecyclerViewHolder( val binding: VideoStreamCardBinding ) : RecyclerView.ViewHolder(binding.root) override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): VideoRecyclerViewHolder { val itemView = VideoStreamCardBinding.inflate(LayoutInflater.from(parent.context), parent, false) itemView.root.layoutParams.height = parent.measuredHeight / 4 return VideoRecyclerViewHolder(itemView) } /** * Function used in order to not trigger the full re-rendering of the item through the normal * onBindViewHolder function * * @param holder * @param position * @param payloads -> List of payloads sent along with notifyItemChanged(index, payload) */ override fun onBindViewHolder( holder: VideoRecyclerViewHolder, position: Int, payloads: MutableList<Any> ) { // If no payloads, call normal onBindViewHolder function and re-render item if (payloads.isEmpty()) { super.onBindViewHolder(holder, position, payloads) return } holder.binding.apply { for (payload in payloads) { when (payload) { MeetingFragment.Companion.INotificationCases.PARTICIPANT_MUTED -> videoStreamMuteIcon.visibility = View.VISIBLE MeetingFragment.Companion.INotificationCases.PARTICIPANT_UNMUTED -> videoStreamMuteIcon.visibility = View.GONE } } } } override fun onBindViewHolder(holder: VideoRecyclerViewHolder, position: Int) { with(videoStreamList[position]) { holder.binding.apply { // Determine whether the participant video has already been displayed if (!isInitialized) { this@with.isInitialized = true videoStreamContainer.addView(this@with.videoView) // todo provide isMuted function to audio info model // videoStreamMuteIcon.visibility = if (participant.isMuted) View.VISIBLE else View.GONE } // Outside of if statement in order to constantly update `position` videoStreamInfoIcon.setOnClickListener { activity?.let { SiteInfoDialogFragment(this@with).show( it.supportFragmentManager, SiteInfoDialogFragment::class.java.canonicalName ) } } } } } override fun getItemCount(): Int { return videoStreamList.size } /** * Important for the item to have a unique item ID in order for the recycler item to not get recycled * as the user scrolls through multiple items * * @param position * @return */ override fun getItemId(position: Int): Long { return videoStreamList[position].uuid.mostSignificantBits } /** * Important for the item to have a unique item view type in order for the recycler item to not get recycled * as the user scrolls through multiple items * * @param position * @return */ override fun getItemViewType(position: Int): Int { return videoStreamList[position].uuid.mostSignificantBits.toInt() } }
0
Kotlin
0
1
956ba604afd51d71e8625b18672c7f33040dce07
4,645
AndroidMeetingSDK
MIT License
app/src/main/java/com/br/agile_github/agilegithubapi/model/User.kt
methob
122,432,870
false
null
package com.br.agile_github.agilegithubapi.model import android.os.Parcel import android.os.Parcelable import com.google.gson.annotations.SerializedName data class User( var id: Int? = null, var login: String? = null, var email: String? = null, @SerializedName("avatar_url") var avatarURL: String? = null ) : Parcelable { constructor(parcel: Parcel) : this() { id = parcel.readValue(Int::class.java.classLoader) as? Int login = parcel.readString() email = parcel.readString() avatarURL = parcel.readString() } override fun writeToParcel(parcel: Parcel, flags: Int) { parcel.writeValue(id) parcel.writeString(login) parcel.writeString(email) parcel.writeString(avatarURL) } override fun describeContents(): Int { return 0 } companion object CREATOR : Parcelable.Creator<User> { override fun createFromParcel(parcel: Parcel): User { return User(parcel) } override fun newArray(size: Int): Array<User?> { return arrayOfNulls(size) } } }
0
Kotlin
1
0
b394f6676c042f815154baf22573441ee98224f5
1,147
github_api_android_mvvm
MIT License
src/main/kotlin/icu/windea/pls/lang/util/ParadoxInlineScriptManager.kt
DragonKnightOfBreeze
328,104,626
false
null
package icu.windea.pls.lang import com.intellij.openapi.application.* import com.intellij.openapi.progress.* import com.intellij.openapi.project.* import com.intellij.openapi.util.* import com.intellij.openapi.vfs.* import com.intellij.psi.* import com.intellij.psi.util.* import icu.windea.pls.config.* import icu.windea.pls.config.config.* import icu.windea.pls.config.configGroup.* import icu.windea.pls.config.expression.* import icu.windea.pls.core.* import icu.windea.pls.core.collections.* import icu.windea.pls.core.expression.* import icu.windea.pls.core.search.* import icu.windea.pls.core.search.selector.* import icu.windea.pls.core.util.* import icu.windea.pls.lang.CwtConfigMatcher.Options import icu.windea.pls.lang.config.* import icu.windea.pls.lang.expression.* import icu.windea.pls.model.expressionInfo.* import icu.windea.pls.script.psi.* object ParadoxInlineScriptHandler { const val inlineScriptKey = "inline_script" const val inlineScriptExpressionOptionName = "inline_script_expression" const val inlineScriptPathExpressionString = "filepath[common/inline_scripts/,.txt]" val inlineScriptPathExpression = CwtValueExpression.resolve(inlineScriptPathExpressionString) val cachedInlineScriptUsageInfoKey = createKey<CachedValue<ParadoxInlineScriptUsageInfo>>("paradox.cached.inlineScriptUsageInfo") fun getUsageInfo(element: ParadoxScriptProperty): ParadoxInlineScriptUsageInfo? { val name = element.name.lowercase() if(name != inlineScriptKey) return null return doGetUsageInfoFromCache(element) } private fun doGetUsageInfoFromCache(element: ParadoxScriptProperty): ParadoxInlineScriptUsageInfo? { return CachedValuesManager.getCachedValue(element, cachedInlineScriptUsageInfoKey) { ProgressManager.checkCanceled() val file = element.containingFile ?: return@getCachedValue null val value = runReadAction { doGetUsageInfo(element, file) } //invalidated on file modification CachedValueProvider.Result.create(value, file) } } private fun doGetUsageInfo(element: ParadoxScriptProperty, file: PsiFile = element.containingFile): ParadoxInlineScriptUsageInfo? { //这里不能调用CwtConfigHandler.getConfigs,因为需要处理内联的情况,会导致StackOverflow val fileInfo = file.fileInfo ?: return null val gameType = fileInfo.rootInfo.gameType val project = file.project val configGroup = getConfigGroup(project, gameType) val inlineConfigs = configGroup.inlineConfigGroup[inlineScriptKey] ?: return null val propertyValue = element.propertyValue ?: return null val matchOptions = Options.SkipIndex or Options.SkipScope val inlineConfig = inlineConfigs.find { val expression = ParadoxDataExpression.resolve(propertyValue, matchOptions) CwtConfigMatcher.matches(propertyValue, expression, it.config.valueExpression, it.config, configGroup).get(matchOptions) } if(inlineConfig == null) return null val expression = getInlineScriptExpressionFromInlineConfig(element, inlineConfig) ?: return null if(expression.isParameterized()) return null val elementOffset = element.startOffset return ParadoxInlineScriptUsageInfo(expression, elementOffset, gameType) } fun getInlineScriptFile(expression: String, contextElement: PsiElement, project: Project): ParadoxScriptFile? { val filePath = getInlineScriptFilePath(expression) val selector = fileSelector(project, contextElement).contextSensitive() return ParadoxFilePathSearch.search(filePath, null, selector).find()?.toPsiFile(project)?.castOrNull() } fun processInlineScriptFile(expression: String, contextElement: PsiElement, project: Project, onlyMostRelevant: Boolean = false, processor: (ParadoxScriptFile) -> Boolean): Boolean { val filePath = getInlineScriptFilePath(expression) val selector = fileSelector(project, contextElement).contextSensitive() return ParadoxFilePathSearch.search(filePath, null, selector).processQueryAsync(onlyMostRelevant) p@{ ProgressManager.checkCanceled() val file = it.toPsiFile(project)?.castOrNull<ParadoxScriptFile>() ?: return@p true processor(file) true } } fun getInlineScriptFilePath(pathReference: String): String? { val configExpression = inlineScriptPathExpression return ParadoxPathReferenceExpressionSupport.get(configExpression)?.resolvePath(configExpression, pathReference.normalizePath())?.firstOrNull() } fun getInlineScriptExpression(file: VirtualFile): String? { val fileInfo = file.fileInfo ?: return null val filePath = fileInfo.pathToEntry.path val configExpression = inlineScriptPathExpression return ParadoxPathReferenceExpressionSupport.get(configExpression)?.extract(configExpression, null, filePath)?.orNull() } fun getInlineScriptExpression(file: PsiFile): String? { if(file !is ParadoxScriptFile) return null val vFile = selectFile(file) ?: return null return getInlineScriptExpression(vFile) } fun getInlineScriptExpressionFromInlineConfig(element: ParadoxScriptProperty, inlineConfig: CwtInlineConfig): String? { if(element.name.lowercase() != inlineScriptKey) return null if(inlineConfig.name != inlineScriptKey) return null val expressionLocation = inlineConfig.config.findOption { it.key == inlineScriptExpressionOptionName }?.stringValue ?: return null val expressionElement = element.findByPath(expressionLocation, ParadoxScriptValue::class.java) val expression = expressionElement?.stringValue() ?: return null return expression } fun getExpressionElement(contextReferenceElement: ParadoxScriptProperty): ParadoxScriptValue? { if(contextReferenceElement.name.lowercase() != inlineScriptKey) return null val config = CwtConfigHandler.getConfigs(contextReferenceElement).firstOrNull() ?: return null val inlineConfig = config.inlineableConfig?.castOrNull<CwtInlineConfig>() ?: return null if(inlineConfig.name != inlineScriptKey) return null val expressionLocation = inlineConfig.config.findOption { it.key == inlineScriptExpressionOptionName }?.stringValue ?: return null val expressionElement = contextReferenceElement.findByPath(expressionLocation, ParadoxScriptValue::class.java) ?: return null return expressionElement } fun getContextReferenceElement(expressionElement: PsiElement): ParadoxScriptProperty? { if(expressionElement !is ParadoxScriptValue) return null var contextReferenceElement = expressionElement.findParentProperty()?.castOrNull<ParadoxScriptProperty>() ?: return null if(contextReferenceElement.name.lowercase() != inlineScriptKey) { contextReferenceElement = contextReferenceElement.findParentProperty()?.castOrNull<ParadoxScriptProperty>() ?: return null } if(contextReferenceElement.name.lowercase() != inlineScriptKey) return null val config = CwtConfigHandler.getConfigs(contextReferenceElement).firstOrNull() ?: return null val inlineConfig = config.inlineableConfig?.castOrNull<CwtInlineConfig>() ?: return null if(inlineConfig.name != inlineScriptKey) return null val expressionLocation = inlineConfig.config.findOption { it.key == inlineScriptExpressionOptionName }?.stringValue ?: return null val expressionElement0 = contextReferenceElement.findByPath(expressionLocation, ParadoxScriptValue::class.java) ?: return null if(expressionElement0 != expressionElement) return null return contextReferenceElement } fun getInferredContextConfigs(contextElement: ParadoxScriptMemberElement, inlineScriptExpression: String, context: CwtConfigContext, matchOptions: Int): List<CwtMemberConfig<*>> { if(!getSettings().inference.inlineScriptConfig) return emptyList() return withRecursionGuard("icu.windea.pls.lang.ParadoxInlineScriptHandler.getInferredContextConfigs") { withCheckRecursion(inlineScriptExpression) { context.inlineScriptHasConflict = false context.inlineScriptHasRecursion = false doGetInferredContextConfigs(contextElement, context, inlineScriptExpression, matchOptions) } } ?: run { context.inlineScriptHasRecursion = true emptyList() } } private fun doGetInferredContextConfigs(contextElement: ParadoxScriptMemberElement, context: CwtConfigContext, inlineScriptExpression: String, matchOptions: Int): List<CwtMemberConfig<*>> { val fromConfig = doGetInferredContextConfigsFromConfig(contextElement, context, inlineScriptExpression, matchOptions) if(fromConfig.isNotEmpty()) return fromConfig return doGetInferredContextConfigsFromUsages(contextElement, context, inlineScriptExpression, matchOptions) } private fun doGetInferredContextConfigsFromConfig(contextElement: ParadoxScriptMemberElement, context: CwtConfigContext, inlineScriptExpression: String, matchOptions: Int): List<CwtMemberConfig<*>> { val configGroup = context.configGroup val config = configGroup.inlineScripts.getByTemplate(inlineScriptExpression, contextElement, configGroup, matchOptions) ?: return emptyList() return config.getContextConfigs() } private fun doGetInferredContextConfigsFromUsages(contextElement: ParadoxScriptMemberElement, context: CwtConfigContext, inlineScriptExpression: String, matchOptions: Int): List<CwtMemberConfig<*>> { // infer & merge val result = Ref.create<List<CwtMemberConfig<*>>>() val project = context.configGroup.project val selector = inlineScriptSelector(project, contextElement) ParadoxInlineScriptUsageSearch.search(inlineScriptExpression, selector).processQueryAsync p@{ info -> ProgressManager.checkCanceled() val file = info.virtualFile?.toPsiFile(project) ?: return@p true val e = file.findElementAt(info.elementOffset) ?: return@p true val p = e.parentOfType<ParadoxScriptProperty>() ?: return@p true if(!p.name.equals(inlineScriptKey, true)) return@p true val memberElement = p.parentOfType<ParadoxScriptMemberElement>() ?: return@p true val usageConfigContext = CwtConfigHandler.getConfigContext(memberElement) ?: return@p true val usageConfigs = usageConfigContext.getConfigs(matchOptions).orNull() // merge result.mergeValue(usageConfigs) { v1, v2 -> CwtConfigManipulator.mergeConfigs(v1, v2) }.also { if(it) return@also context.inlineScriptHasConflict = true result.set(null) } } return result.get().orEmpty() } }
9
null
5
41
99e8660a23f19642c7164c6d6fcafd25b5af40ee
11,076
Paradox-Language-Support
MIT License
app/src/main/java/com/touhidroid/spycammetrics/LoggerService.kt
touhiDroid
121,783,332
false
null
package com.touhidroid.spycammetrics import android.annotation.SuppressLint import android.app.ActivityManager import android.app.Service import android.content.Context import android.content.Intent import android.net.TrafficStats import android.os.Environment import android.os.Handler import android.os.IBinder import android.util.Log import java.io.* /** * Created by touhid on 2/18/2018. * bismillah :) */ class LoggerService : Service() { override fun onBind(p0: Intent?): IBinder? { Log.d(TAG, "onHandleIntent : intent=$p0") return null /*object : IBinder{ override fun getInterfaceDescriptor(): String { TODO("not implemented") //To change body of created functions use File | Settings | File Templates. } override fun isBinderAlive(): Boolean { TODO("not implemented") //To change body of created functions use File | Settings | File Templates. } override fun linkToDeath(p0: IBinder.DeathRecipient?, p1: Int) { TODO("not implemented") //To change body of created functions use File | Settings | File Templates. } override fun queryLocalInterface(p0: String?): IInterface { TODO("not implemented") //To change body of created functions use File | Settings | File Templates. } override fun transact(p0: Int, p1: Parcel?, p2: Parcel?, p3: Int): Boolean { TODO("not implemented") //To change body of created functions use File | Settings | File Templates. } override fun dumpAsync(p0: FileDescriptor?, p1: Array<out String>?) { TODO("not implemented") //To change body of created functions use File | Settings | File Templates. } override fun dump(p0: FileDescriptor?, p1: Array<out String>?) { TODO("not implemented") //To change body of created functions use File | Settings | File Templates. } override fun unlinkToDeath(p0: IBinder.DeathRecipient?, p1: Int): Boolean { TODO("not implemented") //To change body of created functions use File | Settings | File Templates. } override fun pingBinder(): Boolean { TODO("not implemented") //To change body of created functions use File | Settings | File Templates. } }*/ } override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int { return Service.START_NOT_STICKY } override fun onCreate() { super.onCreate() dumpLog() } private val TAG = LoggerService::class.java.simpleName private val sysDir = File(Environment.getExternalStorageDirectory(), "SpyCamMetrics/sys") private val netsDir = File(Environment.getExternalStorageDirectory(), "SpyCamMetrics/nets") // private val handler = Handler() // private val lastSentNetMap = HashMap<Int, Long>() // private val lastRecvNetMap = HashMap<Int, Long>() private val logger = Runnable { dumpLog() } private fun dumpLog() { if (!sysDir.exists()) sysDir.mkdirs() if (!netsDir.exists()) netsDir.mkdirs() netLogger() sysLogger() Handler().postDelayed({ stopSelf() }, 2 * 1000) // handler.postDelayed(logger, 5 * 60 * 1000) } private fun sysLogger() { try { // Executes the command. val process = Runtime.getRuntime().exec("adb shell dumpsys batterystats --checkin") process.waitFor() // Reads stdout. // NOTE: You can write to stdin of the command using // process.getOutputStream(). // val strBuffer = StringBuffer() val writer = BufferedWriter(FileWriter(File(sysDir, "${System.currentTimeMillis()}.csv"))) val reader = BufferedReader(InputStreamReader(process.inputStream)) var line = reader.readLine() while (line != null) { writer.append(line + "\n") line = reader.readLine() } writer.flush() writer.close() reader.close() // Waits for the command to finish. } catch (e: IOException) { e.printStackTrace() } catch (e: InterruptedException) { e.printStackTrace() } } @SuppressLint("SetTextI18n") private fun netLogger() { val manager = getSystemService(Context.ACTIVITY_SERVICE) as ActivityManager val runningApps = manager.runningAppProcesses Log.d(TAG, "Number of running apps: ${runningApps.size}") val bfos = BufferedOutputStream( FileOutputStream(File(netsDir, "${System.currentTimeMillis()}.csv"))) val pm = packageManager val apps = pm.getInstalledApplications(0) for (app in apps) { // Get UID of the selected process val uid = app.uid// (getListAdapter().getItem(position) as RunningAppProcessInfo).uid // Get traffic data val received = TrafficStats.getUidRxBytes(uid) val sent = TrafficStats.getUidTxBytes(uid) val dr = received // - (lastRecvNetMap[uid] ?: 0) val ds = sent // - (lastSentNetMap[uid] ?: 0) try { bfos.write("$uid,${pm.getApplicationLabel(app)},$dr,$ds\n".toByteArray()) } catch (e: IOException) { e.printStackTrace() } catch (e: InterruptedException) { e.printStackTrace() } // lastSentNetMap.put(uid, sent) // lastRecvNetMap.put(uid, received) val s = "$uid : ${pm.getApplicationLabel(app)} ::-> Send : $sent, Received : $received" // tvNetStat.text = "${tvNetStat.text}\n$s" Log.v(TAG, s) } try { bfos.flush() bfos.close() } catch (e: IOException) { e.printStackTrace() } catch (e: InterruptedException) { e.printStackTrace() } } }
0
Kotlin
0
0
c0305dbfc85777b80187c0c815cfda3f25e4baab
6,162
SpyCamMetrics
Apache License 2.0
src/test/kotlin/no/nav/helse/spion/web/integration/AuthorizationTests.kt
navikt
219,727,169
false
null
package no.nav.helse.spion.web.integration import com.fasterxml.jackson.databind.ObjectMapper import io.ktor.http.ContentType import io.ktor.http.HttpHeaders import io.ktor.http.HttpMethod import io.ktor.http.HttpStatusCode import io.ktor.server.testing.setBody import io.ktor.util.KtorExperimentalAPI import no.nav.helse.spion.web.dto.PersonOppslagDto import no.nav.helse.spion.web.spionModule import org.junit.jupiter.api.Test import org.koin.core.component.get import kotlin.test.assertEquals @KtorExperimentalAPI class AuthorizationTests : ControllerIntegrationTestBase() { val noAccessToThisOrg = PersonOppslagDto("20015001543", "123456785") val hasAccessToThisOrg = PersonOppslagDto("20015001543", "910020102") @Test fun `saksOppslag when logged in but unauthorized for the given Virksomhet returns 403 Forbidden`() { configuredTestApplication({ spionModule() }) { doAuthenticatedRequest(HttpMethod.Post, "/api/v1/ytelsesperioder/oppslag") { val objectMapper = get<ObjectMapper>() addHeader(HttpHeaders.ContentType, ContentType.Application.Json.toString()) setBody(objectMapper.writeValueAsString(noAccessToThisOrg)) }.apply { assertEquals(HttpStatusCode.Forbidden, response.status()) } } } @Test fun `saksOppslag when logged in and authorized for the given Virksomhet returns 200 OK`() { configuredTestApplication({ spionModule() }) { doAuthenticatedRequest(HttpMethod.Post, "/api/v1/ytelsesperioder/oppslag") { val objectMapper = get<ObjectMapper>() addHeader(HttpHeaders.ContentType, ContentType.Application.Json.toString()) setBody(objectMapper.writeValueAsString(hasAccessToThisOrg)) }.apply { assertEquals(HttpStatusCode.OK, response.status()) } } } }
7
null
1
1
a9a17796ca9e40aff1532101f30d3399877271fc
1,973
helse-spion
MIT License
packages/graalvm/src/main/kotlin/elide/runtime/intrinsics/sqlite/SQLiteTransaction.kt
elide-dev
506,113,888
false
{"Kotlin": 4156801, "Rust": 130170, "Java": 51233, "Python": 7851, "JavaScript": 6037, "Ruby": 2474, "C": 1926, "RenderScript": 578, "Shell": 160, "Pkl": 102, "TypeScript": 78, "Swift": 23}
/* * Copyright (c) 2024 Elide Technologies, Inc. * * Licensed under the MIT license (the "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * https://opensource.org/license/mit/ * * 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 elide.runtime.intrinsics.sqlite import io.micronaut.core.annotation.ReflectiveAccess import org.graalvm.polyglot.Value import org.graalvm.polyglot.proxy.ProxyExecutable import org.graalvm.polyglot.proxy.ProxyObject import java.util.concurrent.Future import elide.annotations.API import elide.vm.annotations.Polyglot // Properties and methods surfaced to guest code for an SQLite transaction via the object interface. private val SQLITE_TRANSACTION_PROPS_AND_METHODS = arrayOf( "deferred", "immediate", "exclusive", ) /** * # SQLite Transaction * * Describes a transaction which is bound to an [SQLiteTransactor] function, and which is under execution via the SQLite * engine against an active database; the transaction may be invoked one or more times, and may be adjusted via the * mode methods provided ([deferred], [immediate], and [exclusive]). * * If no transaction mode is declared explicitly via the methods provided, the connection's default transaction mode is * used. * * &nbsp; * * ## Transaction Behavior * * Transaction functions may be executed more than once in order to facilitate retry or rollback logic; the transaction * function is expected to be idempotent. * * The return value (type [R]) provided by the [SQLiteTransactor], if any, is returned by this transaction object, via * [invoke]. * * &nbsp; * * ## Object Interop & Cancellation * * Transactions are directly executable, either host-side (via [invoke]), or guest-side (via [ProxyExecutable]). * Transactions can also be used as [Future] objects which yield their result when the transaction completes. * * Cancelling a transaction will make a best-effort attempt to interrupt it (if allowed), by raising an exception within * the thread executing the transaction. * * Transaction cancellation then propagates to the caller instead of providing a value. * * [SQLite Transaction Docs](https://www.sqlite.org/lang_transaction.html) * @param R Return value type. * @see SQLiteDatabase Database API * @see SQLiteStatement Statement API * @see SQLiteTransactor Transactor Interface */ @API @ReflectiveAccess public interface SQLiteTransaction<R>: ProxyExecutable, ProxyObject, Future<R> { /** Indicate the type of this transaction; see [SQLiteTransactionType] for options. */ public val type: SQLiteTransactionType /** * ## Transaction Mode: Deferred * * Applies `DEFERRED` mode to this transaction; another transaction object is returned (a copy), applying this mode, * but with the same properties otherwise. * * [SQLite documentation](https://www.sqlite.org/lang_transaction.html) describes `DEFERRED`-mode transactions as: * * "`DEFERRED` means that the transaction does not actually start until the database is first accessed. Internally, * the `BEGIN DEFERRED` statement merely sets a flag on the database connection that turns off the automatic commit * that would normally occur when the last statement finishes. This causes the transaction that is automatically * started to persist until an explicit `COMMIT` or `ROLLBACK` or until a rollback is provoked by an error or an * `ON CONFLICT ROLLBACK` clause. If the first statement after `BEGIN DEFERRED` is a `SELECT`, then a read transaction * is started. Subsequent write statements will upgrade the transaction to a write transaction if possible, or return * `SQLITE_BUSY`. If the first statement after `BEGIN DEFERRED` is a write statement, then a write transaction is * started." */ @Polyglot public fun deferred(): SQLiteTransaction<R> /** * ## Transaction Mode: Immediate * * Applies `IMMEDIATE` mode to this transaction; another transaction object is returned (a copy), applying this mode, * but with the same properties otherwise. * * [SQLite documentation](https://www.sqlite.org/lang_transaction.html) describes `IMMEDIATE`-mode transactions as: * * "`IMMEDIATE` causes the database connection to start a new write immediately, without waiting for a write * statement. The `BEGIN IMMEDIATE` might fail with `SQLITE_BUSY` if another write transaction is already active on * another database connection." */ @Polyglot public fun immediate(): SQLiteTransaction<R> /** * ## Transaction Mode: Exclusive * * Applies `EXCLUSIVE` mode to this transaction; another transaction object is returned (a copy), applying this mode, * but with the same properties otherwise. * * [SQLite documentation](https://www.sqlite.org/lang_transaction.html) describes `EXCLUSIVE`-mode transactions as: * * "`EXCLUSIVE` is similar to `IMMEDIATE` in that a write transaction is started immediately. `EXCLUSIVE` and * `IMMEDIATE` are the same in WAL mode, but in other journaling modes, `EXCLUSIVE` prevents other database * connections from reading the database while the transaction is underway." */ @Polyglot public fun exclusive(): SQLiteTransaction<R> // Polyglot execution delegates to `invoke`. override fun execute(vararg arguments: Value?): Any = invoke(*arguments) as Any /** * Execute this transaction, invoking the associated [SQLiteTransactor] function. * * @param args Arguments to pass to the transactor function. * @return the result of the transactor function. */ @Polyglot public operator fun invoke(vararg args: Any?): R override fun getMemberKeys(): Array<String> = SQLITE_TRANSACTION_PROPS_AND_METHODS override fun hasMember(key: String?): Boolean = key != null && key in SQLITE_TRANSACTION_PROPS_AND_METHODS override fun cancel(mayInterruptIfRunning: Boolean): Boolean = false override fun putMember(key: String?, value: Value?) { // no-op } }
39
Kotlin
16
97
652036fb4e8394e8ad1aced2f4bbfaa9e00a5181
6,286
elide
MIT License
app/src/main/java/com/kgurgul/cpuinfo/data/provider/GpuDataProvider.kt
kamgurgul
105,620,694
false
null
package com.kgurgul.cpuinfo.data.provider import android.app.ActivityManager import javax.inject.Inject class GpuDataProvider @Inject constructor( private val activityManager: ActivityManager ) { fun getGlEsVersion(): String { return activityManager.deviceConfigurationInfo.glEsVersion } }
27
Kotlin
74
369
341e5485cbae9e8f0fcd66837183ab64f1fdc86c
316
cpu-info
Apache License 2.0
app/src/main/java/com/playground/navigationwithtabs/ui/AddTabFragment.kt
pjkarels
328,534,271
false
null
package com.playground.navigationwithtabs.ui import android.app.Activity import androidx.lifecycle.ViewModelProvider import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.view.inputmethod.EditorInfo import android.view.inputmethod.InputMethodManager import android.widget.Button import android.widget.EditText import androidx.fragment.app.DialogFragment import androidx.navigation.findNavController import com.google.android.material.textfield.TextInputLayout import com.playground.navigationwithtabs.R class AddTabFragment : DialogFragment() { override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? { return inflater.inflate(R.layout.fragment_add_tab, container, false) } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { val tabNameEntry: EditText = view.findViewById(R.id.addTab_entry_name) val addTabButton: Button = view.findViewById(R.id.addTab_button_add) tabNameEntry.setOnEditorActionListener { v, actionId, _ -> return@setOnEditorActionListener when (actionId) { EditorInfo.IME_ACTION_DONE -> { addAndReturn(v) true } else -> false } } addTabButton.setOnClickListener { addAndReturn(view) } tabNameEntry.requestFocus() showKeyboard(tabNameEntry) } private fun addAndReturn(rootView: View) { val tabNameEntry: EditText = rootView.findViewById(R.id.addTab_entry_name) val vm = ViewModelProvider(this).get(AddTabViewModel::class.java) vm.nameErrorMsg.observe(viewLifecycleOwner) { errorMsg -> rootView.findViewById<TextInputLayout>(R.id.addTab_entry_layout)?.error = errorMsg } if (vm.addTab(tabNameEntry.text.toString())) { hideKeyboard(tabNameEntry) rootView.findNavController().popBackStack() } } private fun hideKeyboard(v: View) { val imm = v.context.getSystemService(Activity.INPUT_METHOD_SERVICE) as InputMethodManager imm.hideSoftInputFromWindow(v.windowToken, 0) } private fun showKeyboard(v: View) { val imm = v.context.getSystemService(Activity.INPUT_METHOD_SERVICE) as InputMethodManager imm.showSoftInput(v, 0) } }
0
Kotlin
0
1
9a8d768153e16f60811d7856c1c1ad2f17f1b8f5
2,448
SimpleLists
MIT License
src/main/java/io/github/alexiscomete/lapinousecond/view/ui/longuis/inv/InvInfosUI.kt
Alexiscomete
377,132,555
false
null
package io.github.alexiscomete.lapinousecond.view.ui.longuis.inv import io.github.alexiscomete.lapinousecond.view.ui.interactionui.InteractionStyle import io.github.alexiscomete.lapinousecond.view.ui.interactionui.SimpleInteractionUICustomUI import io.github.alexiscomete.lapinousecond.view.ui.playerui.PlayerUI import io.github.alexiscomete.lapinousecond.view.ui.longuis.StaticUI import java.awt.image.BufferedImage class InvInfosUI(playerUI: PlayerUI) : StaticUI( interactionUICustomUILists = listOf( listOf( SimpleInteractionUICustomUI( "inv_resources", "Ressources", "Ouvrir l'inventaire des ressources", InteractionStyle.NORMAL, { playerUI.setLongCustomUI(InvResourcesUI(playerUI)) return@SimpleInteractionUICustomUI null }, null ), SimpleInteractionUICustomUI( "inv_items", "Items", "Ouvrir l'inventaire des items", InteractionStyle.NORMAL, { playerUI.setLongCustomUI(InvItemsUI(playerUI)) return@SimpleInteractionUICustomUI null }, null ), SimpleInteractionUICustomUI( "inv_effects", "Effets", "Ouvrir la liste des effets en cours", InteractionStyle.NORMAL, { playerUI.setLongCustomUI(InvEffectsUI(playerUI)) return@SimpleInteractionUICustomUI null }, null ) ) ), playerUI ) { override fun getTitle(): String { return "Informations sur le joueur" } override fun getDescription(): String { return "Serveur actuel : ${if (currentUI.getPlayer()["serv"] == "") "serveur inconnu, utilisez -hub" else currentUI.getPlayer()["serv"]}" } override fun getFields(): List<Pair<String, String>> { val player = currentUI.getPlayer() return listOf( Pair("Position", player.positionToString()), Pair("Niveau", player.level.toString()), Pair("Pixel", """ Compte sur le bot de Sylicium : ${if (player["has_account"] == "1") "oui" else "non"} Vérification : ${if (player["is_verify"] == "1") "oui" else "non"} Pixel : ${if (player["x"] == "" || player["x"].toInt() == -1) "pixel inconnu" else "[" + player["x"] + ":" + player["y"] + "]"} """.trimIndent()) ) } override fun getLinkedImage(): String { return "https://cdn.discordapp.com/attachments/854322477152337920/924612939879702588/unknown.png" } override fun getBufferedImage(): BufferedImage? { return null } override fun getUnderString(): String? { return null } }
55
null
0
9
463451ddf5df27085bf6cf60a0b7d9da9b4d14f2
2,939
A-Discord-Adventure
MIT License
presentation/src/main/java/com/team_ia/idea_archive_android/utils/formatTimeDeference.kt
Idea-Archive
613,424,839
false
null
package com.team_ia.idea_archive_android.utils import java.time.LocalDateTime import java.time.format.DateTimeFormatter import java.time.temporal.ChronoUnit fun String.formatTimeDifference(): String { val regTime = this val currentDateTime = LocalDateTime.now() val formatter = DateTimeFormatter.ISO_DATE_TIME val regDateTime = LocalDateTime.parse(regTime, formatter) val diffMinutes = ChronoUnit.MINUTES.between(regDateTime, currentDateTime) if (diffMinutes < 1) { return "방금 전" } else if (diffMinutes < 60) { return "${diffMinutes}분 전" } val diffHours = ChronoUnit.HOURS.between(regDateTime, currentDateTime) if (diffHours < 24) { return "${diffHours}시간 전" } val diffDays = ChronoUnit.DAYS.between(regDateTime, currentDateTime) if (diffDays < 30) { return "${diffDays}일 전" } val diffMonths = (diffDays / 30).toInt() if (diffMonths < 12) { return "${diffMonths}달 전" } val diffYears = (diffDays / 365).toInt() return "${diffYears}년 전" }
6
Kotlin
0
9
bb44bca1d4c86987563fe15c645b254775c88dd9
1,061
Idea-Archive-Android
MIT License
src/main/kotlin/com/skillw/pouvoir/internal/feature/hologram/impl/PouDecentHologramsLine.kt
Glom-c
396,683,163
false
null
package com.skillw.pouvoir.internal.feature.hologram.impl import com.skillw.pouvoir.internal.feature.hologram.PouHolo import eu.decentsoftware.holograms.api.DHAPI import org.bukkit.Bukkit import org.bukkit.Location import org.bukkit.entity.Player import java.util.* /** * @className PouHolographicDisplaysLine * * @author Glom * @date 2022/7/31 19:02 Copyright 2022 user. */ internal class PouDecentHologramsLine(location: Location, line: String, vararg viewers: Player) : PouHolo { init { viewers.forEach { visible(it, true) } } companion object { val enable by lazy { Bukkit.getPluginManager().isPluginEnabled("DecentHolograms") } } private val hologram = DHAPI.createHologram(UUID.randomUUID().toString(), location, false, listOf(line)) override val isDeleted: Boolean get() = !hologram.isEnabled override fun destroy() { hologram.destroy() } override fun respawn() { hologram.updateAll() } override fun spawn(location: Location) { DHAPI.moveHologram(hologram, location) } override fun teleport(location: Location) { DHAPI.moveHologram(hologram, location) } override fun delete() { hologram.hideAll() hologram.disable() hologram.delete() hologram.destroy() } override fun visible(viewer: Player, visible: Boolean) { if (visible) hologram.show(viewer, 0) else hologram.hide(viewer) } override fun update(line: String) { DHAPI.setHologramLine(hologram, 0, line) } }
3
Kotlin
8
9
35b93485f5f4c2d5c534a2765ff7cfb8f34dd737
1,648
Pouvoir
MIT License
core/java/androidx/test/core/view/ViewCapture.kt
android
41,148,494
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. */ @file:JvmName("ViewCapture") package androidx.test.core.view import android.annotation.SuppressLint import android.graphics.Bitmap import android.graphics.Canvas import android.graphics.Rect import android.os.Build import android.os.Handler import android.os.Looper import android.util.Log import android.view.PixelCopy import android.view.Surface import android.view.SurfaceView import android.view.View import android.view.ViewTreeObserver.OnDrawListener import android.view.WindowManager import androidx.annotation.RequiresApi import androidx.annotation.RestrictTo import androidx.test.core.internal.os.HandlerExecutor import androidx.test.internal.platform.ServiceLoaderWrapper import androidx.test.internal.platform.os.ControlledLooper import androidx.test.internal.platform.reflect.ReflectiveField import androidx.test.internal.platform.reflect.ReflectiveMethod import androidx.test.internal.util.Checks.checkState import androidx.test.platform.graphics.HardwareRendererCompat import com.google.common.util.concurrent.ListenableFuture import java.util.function.Consumer import kotlin.coroutines.resume import kotlin.coroutines.resumeWithException import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.suspendCancellableCoroutine /** * Suspend function for capturing an image of the underlying view into a [Bitmap]. * * For devices below [Build.VERSION_CODES#O], the image is obtained using [View#draw]. Otherwise, * [PixelCopy] is used. Note when PixelCopy is used, the resulting image will be taken from the * View's window, then cropped to the approximate location of the View in the window. So depending * on window content you may see content from other View's within the resulting image. * * This method will also enable [HardwareRendererCompat#setDrawingEnabled(boolean)] if required. * * This API is primarily intended for use in lower layer libraries or frameworks. For test authors, * it's recommended to use Espresso's captureToBitmap action or Compose's captureToImage. * * If a rect is supplied, this will further crop locally from the bounds of the given view. For * example, if the given view is at (10, 10 - 30, 30) and the rect is (5, 5 - 10, 10), the final * bitmap will be a 5x5 bitmap that spans (15, 15 - 20, 20). This is particularly useful for * Compose, which only has a singular view that contains a hierarchy of nodes. * * This API must be called on the View's handler thread. If you're calling this from another * context, eg directly from the test thread, you can use something like * <pre>{@code * runBlocking(view.handler.asCoroutineDispatcher()) { * withTimeout(10.seconds) { * view.captureToBitmap(rect) * } * } * }</pre> * * The resulting image is captured after forcing the View to redraw, and waiting for the draw to * operation complete. This is done as a means to improve the stability of the resulting image - * especially in cases where hardware rendering drawing is off initially. */ suspend fun View.captureToBitmap(rect: Rect? = null): Bitmap { checkState(isAttachedToWindow, "View must be attached to a window") checkState( handler.looper.isCurrentThread, "Must be called from view's handler thread. Current: ${Thread.currentThread().name}, view handler: ${handler.looper.thread.name}", ) var bitmap: Bitmap? = null val hardwareDrawingEnabled = HardwareRendererCompat.isDrawingEnabled() HardwareRendererCompat.setDrawingEnabled(true) try { forceRedraw() bitmap = generateBitmap(rect) } finally { HardwareRendererCompat.setDrawingEnabled(hardwareDrawingEnabled) } return bitmap!! } private fun getControlledLooper(): ControlledLooper { return ServiceLoaderWrapper.loadSingleService(ControlledLooper::class.java) { ControlledLooper.NO_OP_CONTROLLED_LOOPER } } /** A ListenableFuture variant of captureToBitmap intended for use from Java. */ fun View.captureToBitmapAsync(rect: Rect? = null): ListenableFuture<Bitmap> { return SuspendToFutureAdapter.launchFuture(Dispatchers.Main) { captureToBitmap(rect) } } /** * Trigger a redraw of the given view. * * Should only be called on UI thread. * * @hide */ @RestrictTo(RestrictTo.Scope.LIBRARY_GROUP) suspend fun View.forceRedraw() { checkState(handler.looper.isCurrentThread, "Must be called from view's handler thread") if (!getControlledLooper().areDrawCallbacksSupported()) { Log.i("ViewCapture", "Skipping forceRedraw as it is not supported") return } var drawListener: OnDrawListener? = null try { return suspendCancellableCoroutine<Unit> { cont -> if (Build.VERSION.SDK_INT >= 29 && isHardwareAccelerated) { viewTreeObserver.registerFrameCommitCallback() { Log.i("forceRedraw", "FrameCommitCallback complete") cont.resume(Unit) } } else { drawListener = object : OnDrawListener { var handled = false override fun onDraw() { if (!handled) { handled = true cont.resume(Unit) } } } viewTreeObserver.addOnDrawListener(drawListener) } invalidate() } } finally { if (drawListener != null) { // post as async event to avoid 'cannot remove on draw listener inside of onDraw' error handler.post { viewTreeObserver.removeOnDrawListener(drawListener) } } } } private suspend fun View.generateBitmap(rect: Rect? = null): Bitmap { val rectWidth = rect?.width() ?: width val rectHeight = rect?.height() ?: height val destBitmap = Bitmap.createBitmap(rectWidth, rectHeight, Bitmap.Config.ARGB_8888) return when { Build.VERSION.SDK_INT < 26 -> generateBitmapFromDraw(destBitmap, rect) Build.VERSION.SDK_INT >= 34 -> generateBitmapFromPixelCopy(destBitmap, rect) this is SurfaceView -> generateBitmapFromSurfaceViewPixelCopy(destBitmap, rect) else -> generateBitmapFromPixelCopy(this.getSurface(), destBitmap, rect) } } @RequiresApi(Build.VERSION_CODES.O) private suspend fun SurfaceView.generateBitmapFromSurfaceViewPixelCopy( destBitmap: Bitmap, rect: Rect?, ): Bitmap { return suspendCancellableCoroutine<Bitmap> { cont -> val onCopyFinished = PixelCopy.OnPixelCopyFinishedListener { result -> if (result == PixelCopy.SUCCESS) { cont.resume(destBitmap) } else { cont.resumeWithException(RuntimeException(String.format("PixelCopy failed: %d", result))) } } PixelCopy.request(this, rect, destBitmap, onCopyFinished, handler) } } internal fun View.generateBitmapFromDraw(destBitmap: Bitmap, rect: Rect?): Bitmap { destBitmap.density = resources.displayMetrics.densityDpi computeScroll() val canvas = Canvas(destBitmap) canvas.translate((-scrollX).toFloat(), (-scrollY).toFloat()) if (rect != null) { canvas.translate((-rect.left).toFloat(), (-rect.top).toFloat()) } draw(canvas) return destBitmap } /** * Generates a bitmap from the given surface using [PixelCopy]. * * This method is effectively the backwards compatibility version of android U's * [PixelCopy.ofWindow(View)], and will be called when running on Android API levels O to T. */ @RequiresApi(Build.VERSION_CODES.O) private suspend fun View.generateBitmapFromPixelCopy( surface: Surface, destBitmap: Bitmap, rect: Rect?, ): Bitmap { return suspendCancellableCoroutine<Bitmap> { cont -> var bounds = getBoundsInSurface() if (rect != null) { bounds = Rect(rect).apply { offset(bounds.left, bounds.top) } } val onCopyFinished = PixelCopy.OnPixelCopyFinishedListener { result -> if (result == PixelCopy.SUCCESS) { cont.resume(destBitmap) } else { cont.resumeWithException(RuntimeException("PixelCopy failed: $result")) } } PixelCopy.request(surface, bounds, destBitmap, onCopyFinished, Handler(Looper.getMainLooper())) } } /** Returns the Rect indicating the View's coordinates within its containing window. */ private fun View.getBoundsInWindow(): Rect { val locationInWindow = intArrayOf(0, 0) getLocationInWindow(locationInWindow) val x = locationInWindow[0] val y = locationInWindow[1] return Rect(x, y, x + width, y + height) } /** Returns the Rect indicating the View's coordinates within its containing surface. */ private fun View.getBoundsInSurface(): Rect { val locationInSurface = intArrayOf(0, 0) if (Build.VERSION.SDK_INT < 29) { reflectivelyGetLocationInSurface(locationInSurface) } else { getLocationInSurface(locationInSurface) } val x = locationInSurface[0] val y = locationInSurface[1] val bounds = Rect(x, y, x + width, y + height) Log.d("ViewCapture", "getBoundsInSurface $bounds") return bounds } private fun View.getSurface(): Surface { // copy the implementation of API 34's PixelCopy.ofWindow to get the surface from view val viewRootImpl = ReflectiveMethod<Any>(View::class.java, "getViewRootImpl").invoke(this) return ReflectiveField<Surface>("android.view.ViewRootImpl", "mSurface").get(viewRootImpl) } /** * The backwards compatible version of API 29's [View.getLocationInSurface]. * * It makes a best effort attempt to replicate the API 29 logic. */ @SuppressLint("NewApi") private fun View.reflectivelyGetLocationInSurface(locationInSurface: IntArray) { // copy the implementation of API 29+ getLocationInSurface getLocationInWindow(locationInSurface) if (Build.VERSION.SDK_INT < 28) { val viewRootImpl = ReflectiveMethod<Any>(View::class.java, "getViewRootImpl").invoke(this) val windowAttributes = ReflectiveField<WindowManager.LayoutParams>("android.view.ViewRootImpl", "mWindowAttributes") .get(viewRootImpl) val surfaceInsets = ReflectiveField<Rect>(WindowManager.LayoutParams::class.java, "surfaceInsets") .get(windowAttributes) locationInSurface[0] += surfaceInsets.left locationInSurface[1] += surfaceInsets.top } else { // ART restrictions introduced in API 29 disallow reflective access to mWindowAttributes Log.w( "ViewCapture", "Could not calculate offset of view in surface on API 28, resulting image may have incorrect positioning", ) } } @RequiresApi(34) private suspend fun View.generateBitmapFromPixelCopy( destBitmap: Bitmap, rect: Rect? = null, ): Bitmap { val boundsInWindow = getBoundsInWindow() val sourceRect = if (rect != null) { Rect(rect).apply { offset(boundsInWindow.left, boundsInWindow.top) } } else { boundsInWindow } return suspendCancellableCoroutine<Bitmap> { cont -> val request = PixelCopy.Request.Builder.ofWindow(this) .setSourceRect(sourceRect) .setDestinationBitmap(destBitmap) .build() val onCopyFinished = Consumer<PixelCopy.Result> { result -> if (result.status == PixelCopy.SUCCESS) { cont.resume(result.bitmap) } else { cont.resumeWithException(RuntimeException("PixelCopy failed: $(result.status)")) } } PixelCopy.request(request, HandlerExecutor(handler), onCopyFinished) } }
313
null
306
1,139
b33f54cee515b6f3c087eb2157b3be7e93e4997f
11,767
android-test
Apache License 2.0
business/home/src/main/java/com/komamj/business/home/HomeViewModel.kt
komamj
367,612,961
false
null
/* * Copyright 2021 komamj * * 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.komamj.business.home import com.komamj.business.common.presentation.BaseViewModel import dagger.hilt.android.lifecycle.HiltViewModel import javax.inject.Inject @HiltViewModel class HomeViewModel @Inject constructor() : BaseViewModel()
0
null
0
2
fe61e2fb464730043164e083e31a4edc42c0183d
841
android-pedestal
MIT License
src/main/kotlin/org/elm/workspace/VersionUtil.kt
intellij-elm
104,530,474
false
null
package org.elm.workspace import com.fasterxml.jackson.core.JsonParser import com.fasterxml.jackson.databind.DeserializationContext import com.fasterxml.jackson.databind.annotation.JsonDeserialize import com.fasterxml.jackson.databind.deser.std.StdDeserializer /** * A version number according to the [SemVer spec](https://semver.org) */ @JsonDeserialize(using = VersionDeserializer::class) data class Version( val x: Int, val y: Int, val z: Int, val preReleaseFields: List<String> = emptyList(), val buildFields: List<String> = emptyList() ) : Comparable<Version> { override fun toString(): String { val str = StringBuilder("$x.$y.$z") if (preReleaseFields.isNotEmpty()) str.append(preReleaseFields.joinToString(".", prefix = "-")) if (buildFields.isNotEmpty()) str.append(buildFields.joinToString(".", prefix = "+")) return str.toString() } override fun compareTo(other: Version) = when { x != other.x -> x.compareTo(other.x) y != other.y -> y.compareTo(other.y) z != other.z -> z.compareTo(other.z) preReleaseFields != other.preReleaseFields -> compareSemVerFields(preReleaseFields, other.preReleaseFields) else -> 0 } /** * Returns a "loose" form that ignores suffixes like alpha, rc-1, etc. */ val xyz: Version by lazy { Version(x, y, z) } companion object { val UNKNOWN: Version = Version(0, 0, 0) /** A weak definition of the version format defined in [the SemVer spec](https://semver.org) */ private val PATTERN = Regex("""(\d+)\.(\d+)\.(\d+)(-[0-9A-Za-z\-.]+)?(\+[0-9A-Za-z\-.]+)?""") fun parse(text: String): Version { val result = PATTERN.find(text) ?: throw ParseException("expected a version number, got '$text'") val (x, y, z, preReleaseInfo, buildInfo) = result.destructured return Version(x.toInt(), y.toInt(), z.toInt(), preReleaseFields = preReleaseInfo.parseExtraParts(), buildFields = buildInfo.parseExtraParts() ) } private fun String.parseExtraParts(): List<String> = takeIf { it.isNotEmpty() }?.drop(1)?.split(".") ?: emptyList() fun parseOrNull(text: String): Version? = try { parse(text) } catch (e: ParseException) { null } } } private fun compareSemVerFields(leftFields: List<String>, rightFields: List<String>): Int { // First, handle differences between normal versions and pre-release versions. // A normal version always has higher precedence than its pre-release versions. if (leftFields.isEmpty()) return 1 if (rightFields.isEmpty()) return -1 // Compare fields pair-wise for ((a, b) in leftFields.zip(rightFields)) { val result = compareSemVerField(a, b) if (result != 0) return result } // All pair-wise fields are the same: tie-breaker on number of fields return leftFields.size.compareTo(rightFields.size) } private fun compareSemVerField(a: String, b: String): Int { val a2 = a.toIntOrNull() val b2 = b.toIntOrNull() return when { a2 == null && b2 == null -> a.compareTo(b) // both fields are strings a2 == null && b2 != null -> 1 // numeric field has lower precedence than non-numeric field a2 != null && b2 == null -> -1 // ditto a2 != null && b2 != null -> a2.compareTo(b2) // both fields are integers else -> error("cannot happen") } } private class VersionDeserializer : StdDeserializer<Version>(Version::class.java) { override fun deserialize(p: JsonParser, ctxt: DeserializationContext) = try { Version.parse(p.text) } catch (e: ParseException) { throw ctxt.weirdStringException(p.text, Version::class.java, e.message) } } // CONSTRAINT ON VERSION NUMBERS @JsonDeserialize(using = ConstraintDeserializer::class) data class Constraint( val low: Version, val high: Version, val lowOp: Op, val highOp: Op ) { enum class Op { LESS_THAN, LESS_THAN_OR_EQUAL; override fun toString(): String = when (this) { LESS_THAN -> "<" LESS_THAN_OR_EQUAL -> "<=" } fun evaluate(left: Version, right: Version): Boolean = when (this) { LESS_THAN -> left < right LESS_THAN_OR_EQUAL -> left <= right } companion object { fun parse(text: String): Op = when (text) { "<" -> LESS_THAN "<=" -> LESS_THAN_OR_EQUAL else -> throw ParseException("expected '<' or '<=', got '$text'") } } } /** * Returns true if the constraint is satisfied using SemVer ordering (namely "1.0-beta" < "1.0") */ fun semVerContains(version: Version): Boolean = (lowOp.evaluate(low, version) && highOp.evaluate(version, high)) /** * Returns true if the constraint is satisfied solely by comparing x.y.z (so "1.0-beta" == "1.0") */ operator fun contains(version: Version): Boolean = copy(low = low.xyz, high = high.xyz).semVerContains(version.xyz) /** * Returns the intersection with [other] or null if the intersection is empty. */ infix fun intersect(other: Constraint): Constraint? { fun merge(op1: Op, op2: Op) = if (Op.LESS_THAN in listOf(op1, op2)) Op.LESS_THAN else Op.LESS_THAN_OR_EQUAL val (newLo, newLop) = when (low.compareTo(other.low)) { -1 -> other.low to other.lowOp 0 -> low to merge(lowOp, other.lowOp) 1 -> low to lowOp else -> error("unexpected compare result") } val (newHi, newHop) = when (high.compareTo(other.high)) { -1 -> high to highOp 0 -> high to merge(highOp, other.highOp) 1 -> other.high to other.highOp else -> error("unexpected compare result") } if (newLo >= newHi) return null return Constraint(newLo, newHi, newLop, newHop) } override fun toString() = "$low $lowOp v $highOp $high" companion object { fun parse(text: String): Constraint { val parts = text.split(" ") if (parts.size != 5) throw ParseException("expected something like '1.0.0 <= v < 2.0.0', got '$text'") val low = Version.parse(parts[0]) val lowOp = Op.parse(parts[1]) if (parts[2] != "v") throw ParseException("expected 'v', got '${parts[2]}'") val highOp = Op.parse(parts[3]) val high = Version.parse(parts[4]) return Constraint(low = low, lowOp = lowOp, highOp = highOp, high = high) } } } private class ConstraintDeserializer : StdDeserializer<Constraint>(Constraint::class.java) { override fun deserialize(p: JsonParser, ctxt: DeserializationContext) = try { Constraint.parse(p.text) } catch (e: ParseException) { throw ctxt.weirdStringException(p.text, Constraint::class.java, e.message) } } // MISC class ParseException(msg: String) : RuntimeException(msg)
171
null
70
390
c6b56241eb293e0ba327a91059c57286bae9bf7e
7,582
intellij-elm
MIT License
features/dedicatedip/src/main/java/com/kape/dedicatedip/domain/GetSignupDipToken.kt
pia-foss
808,533,574
false
{"Kotlin": 1196252}
package com.kape.dedicatedip.domain import com.kape.dip.DipPrefs class GetSignupDipToken( private val dipPrefs: DipPrefs, ) { operator fun invoke(): String = dipPrefs.getPurchasedSignupDipToken() }
3
Kotlin
0
1
11b0122d560459506e6ed3752043b3d5d4f55bdb
215
mobile-android
MIT License
src/main/kotlin/dev/akif/dependencyfinder/data/Dependency.kt
makiftutuncu
404,801,871
false
null
package dev.akif.dependencyfinder.data import dev.akif.dependencyfinder.firstMatching /** * Represents a dependency. * * @param name Name of the dependency */ data class Dependency(val name: String) { private val dependencies: MutableSet<Dependency> = mutableSetOf() /** * Finds a direct or transitive dependency with given name. * * @param name Name of the dependency to find * * @return Found dependency or null if it is not found */ fun find(name: String): Dependency? = if (this.name == name) { this } else { dependencies.firstMatching { it.find(name) } } /** * Lists transitive dependencies of this dependency. * * @return Transitive dependencies of this dependency as a set */ fun list(): Set<String> = mutableSetOf<String>().apply { dependencies.forEach { dependency -> add(dependency.name) addAll(dependency.list()) } } /** * Makes this dependency depend transitively on given dependency. * * @param existing An existing dependency to depend on transitively */ fun dependsOn(existing: Dependency) { dependencies.add(existing) } override fun toString(): String = if (dependencies.isEmpty()) { "[$name]" } else { "[$name -> ${dependencies.joinToString(", ")}]" } }
1
Kotlin
0
3
b60b1bc7da6aba1fd17de06bad8e918975d5a706
1,463
dependency-finder
MIT License
src/commonMain/kotlin/io/konform/validation/ValidationBuilder.kt
konform-kt
124,291,072
false
{"Kotlin": 78847}
package io.konform.validation import io.konform.validation.internal.ArrayValidation import io.konform.validation.internal.IterableValidation import io.konform.validation.internal.MapValidation import io.konform.validation.internal.OptionalValidation import io.konform.validation.internal.RequiredValidation import io.konform.validation.internal.ValidationBuilderImpl import kotlin.jvm.JvmName import kotlin.reflect.KFunction1 import kotlin.reflect.KProperty1 @DslMarker private annotation class ValidationScope @ValidationScope public abstract class ValidationBuilder<T> { public abstract fun build(): Validation<T> public abstract fun addConstraint( errorMessage: String, vararg templateValues: String, test: (T) -> Boolean, ): Constraint<T> public abstract infix fun Constraint<T>.hint(hint: String): Constraint<T> internal abstract fun <R> onEachIterable( name: String, prop: (T) -> Iterable<R>, init: ValidationBuilder<R>.() -> Unit, ) internal abstract fun <R> onEachArray( name: String, prop: (T) -> Array<R>, init: ValidationBuilder<R>.() -> Unit, ) internal abstract fun <K, V> onEachMap( name: String, prop: (T) -> Map<K, V>, init: ValidationBuilder<Map.Entry<K, V>>.() -> Unit, ) @JvmName("onEachIterable") public infix fun <R> KProperty1<T, Iterable<R>>.onEach(init: ValidationBuilder<R>.() -> Unit): Unit = onEachIterable(name, this, init) @JvmName("onEachIterable") public infix fun <R> KFunction1<T, Iterable<R>>.onEach(init: ValidationBuilder<R>.() -> Unit): Unit = onEachIterable("$name()", this, init) @JvmName("onEachArray") public infix fun <R> KProperty1<T, Array<R>>.onEach(init: ValidationBuilder<R>.() -> Unit): Unit = onEachArray(name, this, init) @JvmName("onEachArray") public infix fun <R> KFunction1<T, Array<R>>.onEach(init: ValidationBuilder<R>.() -> Unit): Unit = onEachArray("$name()", this, init) @JvmName("onEachMap") public infix fun <K, V> KProperty1<T, Map<K, V>>.onEach(init: ValidationBuilder<Map.Entry<K, V>>.() -> Unit): Unit = onEachMap(name, this, init) @JvmName("onEachMap") public infix fun <K, V> KFunction1<T, Map<K, V>>.onEach(init: ValidationBuilder<Map.Entry<K, V>>.() -> Unit): Unit = onEachMap("$name()", this, init) public operator fun <R> KProperty1<T, R>.invoke(init: ValidationBuilder<R>.() -> Unit): Unit = validate(name, this, init) public operator fun <R> KFunction1<T, R>.invoke(init: ValidationBuilder<R>.() -> Unit): Unit = validate("$name()", this, init) public infix fun <R> KProperty1<T, R?>.ifPresent(init: ValidationBuilder<R>.() -> Unit): Unit = ifPresent(name, this, init) public infix fun <R> KFunction1<T, R?>.ifPresent(init: ValidationBuilder<R>.() -> Unit): Unit = ifPresent("$name()", this, init) public infix fun <R> KProperty1<T, R?>.required(init: ValidationBuilder<R>.() -> Unit): Unit = required(name, this, init) public infix fun <R> KFunction1<T, R?>.required(init: ValidationBuilder<R>.() -> Unit): Unit = required("$name()", this, init) /** * Calculate a value from the input and run a validation on it. * @param name The name that should be reported in validation errors. Must be a valid kotlin name, optionally followed by (). * @param f The function for which you want to validate the result of * @see run */ public abstract fun <R> validate( name: String, f: (T) -> R, init: ValidationBuilder<R>.() -> Unit, ) /** * Calculate a value from the input and run a validation on it, but only if the value is not null. */ public abstract fun <R> ifPresent( name: String, f: (T) -> R?, init: ValidationBuilder<R>.() -> Unit, ) /** * Calculate a value from the input and run a validation on it, and give an error if the result is null. */ public abstract fun <R> required( name: String, f: (T) -> R?, init: ValidationBuilder<R>.() -> Unit, ) /** Run an arbitrary other validation. */ public abstract fun run(validation: Validation<T>) public abstract val <R> KProperty1<T, R>.has: ValidationBuilder<R> public abstract val <R> KFunction1<T, R>.has: ValidationBuilder<R> } /** * Run a validation if the property is not-null, and allow nulls. */ public fun <T : Any> ValidationBuilder<T?>.ifPresent(init: ValidationBuilder<T>.() -> Unit) { val builder = ValidationBuilderImpl<T>() init(builder) run(OptionalValidation(builder.build())) } /** * Run a validation on a nullable property, giving an error on nulls. */ public fun <T : Any> ValidationBuilder<T?>.required(init: ValidationBuilder<T>.() -> Unit) { val builder = ValidationBuilderImpl<T>() init(builder) run(RequiredValidation(builder.build())) } @JvmName("onEachIterable") public fun <S, T : Iterable<S>> ValidationBuilder<T>.onEach(init: ValidationBuilder<S>.() -> Unit) { val builder = ValidationBuilderImpl<S>() init(builder) @Suppress("UNCHECKED_CAST") run(IterableValidation(builder.build()) as Validation<T>) } @JvmName("onEachArray") public fun <T> ValidationBuilder<Array<T>>.onEach(init: ValidationBuilder<T>.() -> Unit) { val builder = ValidationBuilderImpl<T>() init(builder) run(ArrayValidation(builder.build())) } @JvmName("onEachMap") public fun <K, V, T : Map<K, V>> ValidationBuilder<T>.onEach(init: ValidationBuilder<Map.Entry<K, V>>.() -> Unit) { val builder = ValidationBuilderImpl<Map.Entry<K, V>>() init(builder) @Suppress("UNCHECKED_CAST") run(MapValidation(builder.build()) as Validation<T>) }
19
Kotlin
39
668
bc43e34a0d3d36c78a2dba5807cc3b990c9cbb67
5,754
konform
MIT License
layout-inspector/src/com/android/tools/idea/layoutinspector/snapshots/SnapshotMetadata.kt
JetBrains
60,701,247
false
null
/* * Copyright (C) 2021 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.android.tools.idea.layoutinspector.snapshots import com.google.wireless.android.sdk.stats.DynamicLayoutInspectorSnapshotInfo import com.intellij.openapi.application.ApplicationInfo import layoutinspector.snapshots.Metadata import java.awt.Dimension /** * Metadata about a layout inspector snapshot that's included in the snapshot itself. Can be used * for metrics logging. */ class SnapshotMetadata( val snapshotVersion: ProtocolVersion, val apiLevel: Int? = null, val processName: String? = null, var containsCompose: Boolean? = null, val liveDuringCapture: Boolean? = null, val source: Metadata.Source? = null, val sourceVersion: String? = null, var saveDuration: Long? = null, var loadDuration: Long? = null, var dpi: Int? = null, var fontScale: Float? = null, var screenDimension: Dimension? = null, var folderConfig: String? = null, var theme: String? = null, ) { /** Convert to the proto used by metrics. */ fun toSnapshotInfo(): DynamicLayoutInspectorSnapshotInfo? = DynamicLayoutInspectorSnapshotInfo.newBuilder() .apply { snapshotVersion = this@SnapshotMetadata.snapshotVersion.toInt() saveSource = when (source) { Metadata.Source.STUDIO -> DynamicLayoutInspectorSnapshotInfo.SaveSource.STUDIO else -> DynamicLayoutInspectorSnapshotInfo.SaveSource.UNKNOWN } sourceVersion?.let { saveVersion = it } liveDuringCapture?.let { liveWhenSaved = it } saveDuration?.let { saveDurationMs = it.toInt() } loadDuration?.let { loadDurationMs = it.toInt() } } .build() /** Convert to the proto saved in a snapshot. */ fun toProto(): Metadata = Metadata.newBuilder() .apply { this@SnapshotMetadata.apiLevel?.let { apiLevel = it } this@SnapshotMetadata.processName?.let { processName = it } this@SnapshotMetadata.containsCompose?.let { containsCompose = it } this@SnapshotMetadata.liveDuringCapture?.let { liveDuringCapture = it } source = this@SnapshotMetadata.source sourceVersion = ApplicationInfo.getInstance().fullVersion this@SnapshotMetadata.dpi?.let { dpi = it } this@SnapshotMetadata.fontScale?.let { fontScale = it } this@SnapshotMetadata.screenDimension?.let { screenWidth = it.width screenHeight = it.height } this@SnapshotMetadata.folderConfig?.let { folderConfig = it } this@SnapshotMetadata.theme?.let { theme = it } } .build() } /** Convert from the proto saved in a snapshot to a normal object. */ fun Metadata.convert(version: ProtocolVersion) = SnapshotMetadata( version, apiLevel, processName, containsCompose, liveDuringCapture, source, sourceVersion, dpi = dpi, fontScale = fontScale, screenDimension = if (screenWidth > 0 && screenHeight > 0) Dimension(screenWidth, screenHeight) else null, folderConfig = folderConfig, theme = theme, ) fun ProtocolVersion.toInt() = when (this) { ProtocolVersion.Version1 -> 1 ProtocolVersion.Version2 -> 2 ProtocolVersion.Version3 -> 3 ProtocolVersion.Version4 -> 4 }
5
null
230
948
10110983c7e784122d94c7467e9d243aba943bf4
3,826
android
Apache License 2.0
clashJ/src/test/kotlin/io/github/maicolantali/http/RequestHandlerTest.kt
MaicolAntali
665,565,216
false
{"Kotlin": 214209}
package io.github.maicolantali.http import io.github.maicolantali.exception.BadGatewayException import io.github.maicolantali.exception.ClashJException import io.github.maicolantali.exception.HttpException import io.github.maicolantali.exception.InvalidCredentialException import io.github.maicolantali.exception.MaintenanceException import io.github.maicolantali.http.option.RequestOptions import io.github.maicolantali.types.internal.configuration.ClientConfiguration import io.github.maicolantali.types.internal.configuration.HttpConfiguration import io.github.maicolantali.util.Credential import io.github.maicolantali.util.DEV_SITE_BASE_URL import io.ktor.client.engine.mock.MockEngine import io.ktor.client.engine.mock.respond import io.ktor.client.engine.mock.respondBadRequest import io.ktor.client.engine.mock.respondError import io.ktor.client.plugins.HttpRequestTimeoutException import io.ktor.http.HttpHeaders import io.ktor.http.HttpStatusCode import io.ktor.http.headers import kotlinx.coroutines.runBlocking import org.assertj.core.api.Assertions.assertThat import org.junit.jupiter.api.Nested import org.junit.jupiter.api.Test import org.junit.jupiter.api.assertThrows import java.io.File class RequestHandlerTest { @Nested inner class Login { @Test fun `should throw an InvalidCredentialException`() { runBlocking { val mockEngine = MockEngine { _ -> respondError(HttpStatusCode.Forbidden) } val requestHandler = getRequestHandlerMocked(mockEngine) assertThrows<InvalidCredentialException> { requestHandler.login() } } } @Test fun `should throw an ClashJException - Exist too many keys`() { runBlocking { val mockEngine = MockEngine { request -> when (request.url.toString()) { "$DEV_SITE_BASE_URL/login" -> { respond( content = File("src/test/resources/json/tooManyKeysLogin.json").readText(), status = HttpStatusCode.OK, headers = headers { append("set-cookie", "{session=123}") append(HttpHeaders.ContentType, "application/json") }, ) } "$DEV_SITE_BASE_URL/apikey/list" -> { respond( content = File("src/test/resources/json/tooManyKeysList.json").readText(), status = HttpStatusCode.OK, headers = headers { append(HttpHeaders.ContentType, "application/json") }, ) } else -> { respondBadRequest() } } } val requestHandler = getRequestHandlerMocked(mockEngine) assertThrows<ClashJException> { requestHandler.login() } } } } @Nested inner class Request { @Test fun `should throw an ClashJException`() { runBlocking { val mockEngine = MockEngine { _ -> // Http error didn't handle by the `request` fun respondError(HttpStatusCode.NotImplemented) } val requestHandler = getRequestHandlerMocked(mockEngine) val e = assertThrows<ClashJException> { requestHandler.request<String>("url", RequestOptions()) } assertThat(e).hasMessageContaining("Unable to handle this response") } } @Test fun `should throw a BadGatewayException - Caused by RequestTimeoutException`() { runBlocking { val mockEngine = MockEngine { _ -> throw HttpRequestTimeoutException("url", 1000) } val requestHandler = RequestHandler( Credential("email", "password"), ClientConfiguration(httpClient = HttpConfiguration(engine = mockEngine, requestTimeout = 1_000)), ) val e = assertThrows<BadGatewayException> { requestHandler.request<String>("url", RequestOptions()) } assertThat(e).hasMessageContaining("The API timed out waiting for the request") } } @Test fun `should throw a HttpException - Caused by TooManyRequests`() { runBlocking { val mockEngine = MockEngine { _ -> respondError(HttpStatusCode.TooManyRequests) } val requestHandler = getRequestHandlerMocked(mockEngine) val e = assertThrows<HttpException> { requestHandler.request<String>("url", RequestOptions()) } assertThat(e).hasMessageContaining("Reached maximum rate-limits") } } @Test fun `should throw a MaintenanceException`() { runBlocking { val mockEngine = MockEngine { _ -> respondError(HttpStatusCode.ServiceUnavailable) } val requestHandler = getRequestHandlerMocked(mockEngine) val e = assertThrows<MaintenanceException> { requestHandler.request<String>("url", RequestOptions()) } assertThat(e).hasMessageContaining("The API is in maintenance") } } } private fun getRequestHandlerMocked(mockEngine: MockEngine) = RequestHandler( Credential("email", "password"), ClientConfiguration(httpClient = HttpConfiguration(engine = mockEngine)), ) }
0
Kotlin
0
0
2e0d9805caf2cb3a0070b684fb2447c725d0a580
6,441
clashJ
MIT License
app/src/main/java/hinl/android/kotlin/databasehelper/example/database/Database.kt
gtomato
113,853,259
false
null
package hinl.android.kotlin.databasehelper.example.database import android.content.Context import android.database.sqlite.SQLiteDatabase import hinl.kotlin.database.helper.SQLiteDatabaseHelper class DatabaseHelper(context: Context): SQLiteDatabaseHelper( context = context, name = "ExampleDatabase.db", factory = null, version = 1) { override fun onCreate(db: SQLiteDatabase?) { } override fun onUpgrade(db: SQLiteDatabase?, oldVersion: Int, newVersion: Int) { } }
0
Kotlin
1
2
ea8f301187cc479f8974e1c9e56c6334ce91c7d8
520
Android-Kotlin-SQLiteHelper
MIT License
src/main/java/com/futao/springbootdemo/service/impl/KotlinTestServiceImpl.kt
FutaoSmile
165,509,051
false
null
package com.futao.springbootdemo.service.impl import com.futao.springbootdemo.foundation.LogicException import com.futao.springbootdemo.foundation.mq.rocket.RocketMqProducerOnOff import com.futao.springbootdemo.model.system.ErrorMessage import com.futao.springbootdemo.service.KotlinTestService import org.apache.rocketmq.client.producer.DefaultMQProducer import org.apache.rocketmq.common.message.Message import org.slf4j.LoggerFactory import org.springframework.context.annotation.Conditional import org.springframework.stereotype.Service import javax.annotation.Resource /** * 实现Condition接口,重写matches()方法,不需要打@Service注解,否则matches无效 * matches()返回为true时Spring会实例化这个类 * 使用: * 可以在其他类上打上@Condition(K::class)注解,会根据K类是否被实例化再来实例化自己 * * @author futao */ @Conditional(RocketMqProducerOnOff::class) @Service open class KotlinTestServiceImpl : KotlinTestService { val logger = LoggerFactory.getLogger(KotlinTestServiceImpl::class.java)!! override fun t(): String { return "test" } override fun exception() { throw LogicException.le(ErrorMessage.LogicErrorMessage.LOGIC_EXCEPTION) } @Resource lateinit var producer: DefaultMQProducer override fun send() { producer.send(Message("niubiTopic", "niubiTag", "我是消息本体了".toByteArray())) } }
1
null
4
20
b67fb35c93238c9067ed0f922a7e97a0a9cdc057
1,303
SpringBootIntegration
MIT License
test/wow-tck/src/main/kotlin/me/ahoo/wow/tck/modeling/command/CommandDispatcherSpec.kt
Ahoo-Wang
628,167,080
false
null
/* * Copyright [2021-present] [<NAME> <<EMAIL>> (https://github.com/Ahoo-Wang)]. * 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 me.ahoo.wow.tck.modeling.command import com.google.common.hash.BloomFilter import com.google.common.hash.Funnels import me.ahoo.wow.command.CommandBus import me.ahoo.wow.command.CommandGateway import me.ahoo.wow.command.DefaultCommandGateway import me.ahoo.wow.command.InMemoryCommandBus import me.ahoo.wow.command.ServerCommandExchange import me.ahoo.wow.command.toCommandMessage import me.ahoo.wow.command.wait.LocalCommandWaitNotifier import me.ahoo.wow.command.wait.ProcessedNotifierFilter import me.ahoo.wow.command.wait.SimpleCommandWaitEndpoint import me.ahoo.wow.command.wait.SimpleWaitStrategyRegistrar import me.ahoo.wow.event.DomainEventBus import me.ahoo.wow.event.InMemoryDomainEventBus import me.ahoo.wow.eventsourcing.EventSourcingStateAggregateRepository import me.ahoo.wow.eventsourcing.EventStore import me.ahoo.wow.eventsourcing.InMemoryEventStore import me.ahoo.wow.eventsourcing.snapshot.InMemorySnapshotRepository import me.ahoo.wow.eventsourcing.snapshot.SnapshotRepository import me.ahoo.wow.filter.FilterChainBuilder import me.ahoo.wow.id.GlobalIdGenerator import me.ahoo.wow.infra.idempotency.BloomFilterIdempotencyChecker import me.ahoo.wow.infra.idempotency.DefaultAggregateIdempotencyCheckerProvider import me.ahoo.wow.infra.idempotency.IdempotencyChecker import me.ahoo.wow.ioc.ServiceProvider import me.ahoo.wow.ioc.SimpleServiceProvider import me.ahoo.wow.metrics.Metrics.metrizable import me.ahoo.wow.modeling.annotation.aggregateMetadata import me.ahoo.wow.modeling.command.AggregateProcessorFactory import me.ahoo.wow.modeling.command.AggregateProcessorFilter import me.ahoo.wow.modeling.command.CommandAggregateFactory import me.ahoo.wow.modeling.command.CommandDispatcher import me.ahoo.wow.modeling.command.DefaultCommandHandler import me.ahoo.wow.modeling.command.RetryableAggregateProcessorFactory import me.ahoo.wow.modeling.command.SendDomainEventStreamFilter import me.ahoo.wow.modeling.command.SimpleCommandAggregateFactory import me.ahoo.wow.modeling.materialize import me.ahoo.wow.modeling.state.ConstructorStateAggregateFactory import me.ahoo.wow.modeling.state.StateAggregateFactory import me.ahoo.wow.modeling.state.StateAggregateRepository import me.ahoo.wow.tck.metrics.LoggingMeterRegistryInitializer import me.ahoo.wow.tck.mock.MockChangeAggregate import me.ahoo.wow.tck.mock.MockCommandAggregate import me.ahoo.wow.tck.mock.MockCreateAggregate import me.ahoo.wow.tck.mock.MockStateAggregate import org.hamcrest.MatcherAssert.* import org.hamcrest.Matchers.* import org.junit.jupiter.api.BeforeEach import org.junit.jupiter.api.Test import org.junit.jupiter.api.extension.ExtendWith import reactor.core.publisher.Mono import reactor.core.scheduler.Schedulers import reactor.kotlin.core.publisher.toFlux import reactor.kotlin.test.test import java.time.Duration import java.util.concurrent.ThreadLocalRandom @ExtendWith(LoggingMeterRegistryInitializer::class) abstract class CommandDispatcherSpec { protected val aggregateMetadata = aggregateMetadata<MockCommandAggregate, MockStateAggregate>() protected val serviceProvider: ServiceProvider = SimpleServiceProvider() protected val idempotencyChecker: IdempotencyChecker = BloomFilterIdempotencyChecker( Duration.ofSeconds(1), ) { BloomFilter.create(Funnels.stringFunnel(Charsets.UTF_8), 10000000) } protected val stateAggregateFactory: StateAggregateFactory = ConstructorStateAggregateFactory protected val waitStrategyRegistrar = SimpleWaitStrategyRegistrar protected lateinit var aggregateProcessorFactory: AggregateProcessorFactory protected lateinit var commandBus: CommandBus protected lateinit var commandGateway: CommandGateway protected lateinit var eventStore: EventStore protected lateinit var snapshotRepository: SnapshotRepository protected lateinit var stateAggregateRepository: StateAggregateRepository protected lateinit var commandAggregateFactory: CommandAggregateFactory protected lateinit var domainEventBus: DomainEventBus @BeforeEach open fun setup() { // Schedulers.enableMetrics() commandBus = createCommandBus().metrizable() commandGateway = DefaultCommandGateway( commandWaitEndpoint = SimpleCommandWaitEndpoint(""), commandBus = commandBus, idempotencyCheckerProvider = DefaultAggregateIdempotencyCheckerProvider { idempotencyChecker }, waitStrategyRegistrar = waitStrategyRegistrar, ) eventStore = createEventStore().metrizable() snapshotRepository = createSnapshotRepository().metrizable() stateAggregateRepository = createStateAggregateRepository(stateAggregateFactory, snapshotRepository, eventStore) commandAggregateFactory = createCommandAggregateFactory(eventStore) aggregateProcessorFactory = RetryableAggregateProcessorFactory(stateAggregateFactory, stateAggregateRepository, commandAggregateFactory) domainEventBus = createEventBus().metrizable() } protected open fun createCommandBus(): CommandBus { return InMemoryCommandBus() } protected open fun createEventBus(): DomainEventBus { return InMemoryDomainEventBus() } protected open fun createEventStore(): EventStore { return InMemoryEventStore() } protected open fun createSnapshotRepository(): SnapshotRepository { return InMemorySnapshotRepository() } protected fun createStateAggregateRepository( stateAggregateFactory: StateAggregateFactory, snapshotRepository: SnapshotRepository, eventStore: EventStore ): StateAggregateRepository { return EventSourcingStateAggregateRepository(stateAggregateFactory, snapshotRepository, eventStore) } protected fun createCommandAggregateFactory( eventStore: EventStore ): CommandAggregateFactory { return SimpleCommandAggregateFactory(eventStore) } protected open fun onCommandSeek(): Mono<Void> = Mono.empty() val concurrency: Int = 100 val aggregateCount: Int = 200 @Test fun run() { val chain = FilterChainBuilder<ServerCommandExchange<*>>() .addFilter(AggregateProcessorFilter) .addFilter(SendDomainEventStreamFilter(domainEventBus)) .addFilter(ProcessedNotifierFilter(LocalCommandWaitNotifier(waitStrategyRegistrar))) .build() val commandDispatcher = CommandDispatcher( namedAggregates = setOf(aggregateMetadata.materialize()), commandBus = commandBus, aggregateProcessorFactory = aggregateProcessorFactory, commandHandler = DefaultCommandHandler(chain).metrizable(), serviceProvider = serviceProvider, ) commandDispatcher.use { it.run() onCommandSeek().block() warmUp() orchestra() commandBus.close() } } private fun warmUp() { val mockCreateAggregate = MockCreateAggregate( id = GlobalIdGenerator.generateAsString(), data = GlobalIdGenerator.generateAsString(), ) commandGateway .sendAndWaitForProcessed(mockCreateAggregate.toCommandMessage()) .then() .test() .verifyComplete() } @Suppress("LongMethod") private fun orchestra() { val creates = buildList { repeat(aggregateCount) { add( MockCreateAggregate( id = GlobalIdGenerator.generateAsString(), data = GlobalIdGenerator.generateAsString(), ), ) } } assertThat( creates.distinctBy { it.id }.size, equalTo(aggregateCount), ) println("------------- CreateAggregate -------------") val createdDuration = creates.toFlux() .subscribeOn(Schedulers.single()) .name("test.create-aggregate") .metrics() .flatMap({ // 生成聚合 commandGateway .sendAndWaitForProcessed(it!!.toCommandMessage()) }, Int.MAX_VALUE).doOnNext { assertThat(it.succeeded, equalTo(true)) } .timeout(Duration.ofMinutes(1)) .then() .test() .verifyComplete() println( "------------- Aggregate Created Duration:[$createdDuration] Throughput:[${creates.size.toDouble() / createdDuration.toMillis() * 1000}/s]-------------", ) LoggingMeterRegistryInitializer.publishMeters() /* * 模拟聚合命令乱序 */ val changedDuration = buildList { repeat(concurrency) { val randomCreate = creates[ThreadLocalRandom.current().nextInt(0, aggregateCount)] add( MockChangeAggregate( randomCreate.id, GlobalIdGenerator.generateAsString(), ), ) } }.toFlux() .subscribeOn(Schedulers.single()) .flatMap({ commandGateway.sendAndWaitForProcessed(it.toCommandMessage()) }, Int.MAX_VALUE) .doOnNext { assertThat(it.succeeded, equalTo(true)) } .timeout(Duration.ofSeconds(30)) .then() .test() .verifyComplete() println( "------- Aggregate Changed Duration:[$changedDuration] Throughput:[${concurrency.toDouble() / changedDuration.toMillis() * 1000}/s]-------", ) LoggingMeterRegistryInitializer.publishMeters() } }
8
null
8
98
eed438bab2ae009edf3a1db03396de402885c681
10,427
Wow
Apache License 2.0
liveness/src/main/java/com/amplifyframework/ui/liveness/camera/FrameAnalyzer.kt
aws-amplify
490,439,616
false
null
/* * Copyright 2023 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file 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.amplifyframework.ui.liveness.camera import android.content.Context import android.graphics.Bitmap import android.util.Size import androidx.camera.core.ImageAnalysis import androidx.camera.core.ImageProxy import com.amplifyframework.ui.liveness.ml.FaceDetector import com.amplifyframework.ui.liveness.ml.FaceOval import com.amplifyframework.ui.liveness.state.LivenessState import org.tensorflow.lite.DataType import org.tensorflow.lite.support.common.ops.NormalizeOp import org.tensorflow.lite.support.image.ImageProcessor import org.tensorflow.lite.support.image.TensorImage import org.tensorflow.lite.support.image.ops.ResizeOp import org.tensorflow.lite.support.image.ops.Rot90Op internal class FrameAnalyzer( context: Context, private val livenessState: LivenessState ) : ImageAnalysis.Analyzer { private val tfLite = FaceDetector.loadModel(context) private val tfImageBuffer = TensorImage(DataType.UINT8) private var tfImageProcessor: ImageProcessor? = null private var cachedBitmap: Bitmap? = null private var faceDetector = FaceDetector(livenessState) override fun analyze(image: ImageProxy) { if (cachedBitmap == null) { cachedBitmap = Bitmap.createBitmap( image.width, image.height, Bitmap.Config.ARGB_8888 ) } image.use { cachedBitmap?.let { bitmap -> bitmap.copyPixelsFromBuffer(it.planes[0].buffer) if (livenessState.onFrameAvailable()) { val outputLocations = arrayOf( Array(FaceDetector.NUM_BOXES) { FloatArray(FaceDetector.NUM_COORDS) } ) val outputScores = arrayOf(Array(FaceDetector.NUM_BOXES) { FloatArray(1) }) val outputMap = mapOf(0 to outputLocations, 1 to outputScores) val tensorImage = tfImageBuffer.apply { load(cachedBitmap) } val tfImage = getImageProcessor(it.imageInfo.rotationDegrees) .process(tensorImage) tfLite.runForMultipleInputsOutputs(arrayOf(tfImage.buffer), outputMap) val facesFound = faceDetector.getBoundingBoxes(outputLocations, outputScores) livenessState.onFrameFaceCountUpdate(facesFound.size) if (facesFound.size > 1) return facesFound.firstOrNull()?.let { detectedFace -> val mirrorRectangle = FaceOval.convertMirroredRectangle( detectedFace.location, LivenessCoordinator.TARGET_WIDTH ) val mirroredLeftEye = FaceOval.convertMirroredLandmark( detectedFace.leftEye, LivenessCoordinator.TARGET_WIDTH ) val mirroredRightEye = FaceOval.convertMirroredLandmark( detectedFace.rightEye, LivenessCoordinator.TARGET_WIDTH ) val mirroredMouth = FaceOval.convertMirroredLandmark( detectedFace.mouth, LivenessCoordinator.TARGET_WIDTH ) livenessState.onFrameFaceUpdate( mirrorRectangle, mirroredLeftEye, mirroredRightEye, mirroredMouth ) } } } } } private fun getImageProcessor(imageRotationDegrees: Int): ImageProcessor { val existingImageProcessor = tfImageProcessor if (existingImageProcessor != null) return existingImageProcessor val tfInputSize = tfLite.getInputTensor(0).shape().let { Size(it[2], it[1]) } val imageProcessor = ImageProcessor.Builder() .add( ResizeOp( tfInputSize.height, tfInputSize.width, ResizeOp.ResizeMethod.NEAREST_NEIGHBOR ) ) .add(Rot90Op(-imageRotationDegrees / 90)) .add(NormalizeOp(0f, 255f)) // transform RGB values from [-255, 255] to [-1, 1] .build() this.tfImageProcessor = imageProcessor return imageProcessor } }
6
null
5
9
23ee414bc1e13e03ea38c5ea85c8c0d580dd7edc
5,151
amplify-ui-android
Apache License 2.0
fetch2/src/main/java/com/tonyodev/fetch2/FetchGroup.kt
Kutikov
731,088,336
true
{"Java Properties": 3, "YAML": 1, "Gradle": 11, "Shell": 1, "Markdown": 1, "Batchfile": 1, "Text": 4, "Ignore List": 9, "Proguard": 8, "XML": 140, "Kotlin": 127, "Java": 42, "JSON": 109}
package com.tonyodev.fetch2 import com.tonyodev.fetch2core.FetchObserver /** * An immutable object which contains a current snapshot of all the information * about a specific download group managed by Fetch. * */ interface FetchGroup { /** * The group id. * */ val id: Int /** * The Fetch namespace this group belongs to. * */ val namespace: String /** * All downloads belonging to this group. * */ val downloads: List<Download> /** * All queued downloads belonging to this group. * */ val queuedDownloads: List<Download> /** * All added downloads belonging to this group. * */ val addedDownloads: List<Download> /** * All paused downloads belonging to this group. * */ val pausedDownloads: List<Download> /** * All downloading downloads belonging to this group. * */ val downloadingDownloads: List<Download> /** * All completed downloads belonging to this group. * */ val completedDownloads: List<Download> /** * All cancelled downloads belonging to this group. * */ val cancelledDownloads: List<Download> /** * All failed downloads belonging to this group. * */ val failedDownloads: List<Download> /** * All deleted downloads belonging to this group. * */ val deletedDownloads: List<Download> /** * All removed downloads belonging to this group. * */ val removedDownloads: List<Download> /** * The groups downloading progress. * */ val groupDownloadProgress: Int /** * The set of FetchObservers attached to this FetchGroup. * */ val observers: Set<FetchObserver<List<Download>>> /** * Adds FetchGroupObservers that will be notified when the downloads in this group * has been updated or changed. FetchGroupObservers are not lifecycle aware. * @param fetchGroupObservers the fetch group observers. * */ fun addFetchGroupObservers(vararg fetchGroupObservers: FetchGroupObserver) /** * Removes FetchGroupObservers attached to this fetch group. * @param fetchGroupObservers to be removed. * */ fun removeFetchGroupObservers(vararg fetchGroupObservers: FetchGroupObserver) }
122
null
342
6
c450f681035ed47d2bd6e5e2b7cf4b921665e669
2,297
fetch2-android
Apache License 2.0
core/src/main/java/com/alamkanak/weekview/WeekView.kt
vivekkjha
293,217,587
true
{"Kotlin": 206682}
package com.alamkanak.weekview import android.annotation.SuppressLint import android.content.Context import android.graphics.Canvas import android.graphics.RectF import android.graphics.Typeface import android.os.Parcelable import android.util.AttributeSet import android.view.MotionEvent import android.view.View import android.view.accessibility.AccessibilityManager import androidx.core.view.ViewCompat import java.util.Calendar import kotlin.math.min import kotlin.math.roundToInt class WeekView @JvmOverloads constructor( context: Context, attrs: AttributeSet? = null, defStyleAttr: Int = 0 ) : View(context, attrs, defStyleAttr) { private val viewState: ViewState by lazy { ViewState.make(context, attrs) } private val eventChipsCache = EventChipsCache() private val touchHandler = WeekViewTouchHandler(viewState) private val gestureHandler = WeekViewGestureHandler( context = context, viewState = viewState, eventChipsCache = eventChipsCache, touchHandler = touchHandler, onInvalidation = { ViewCompat.postInvalidateOnAnimation(this) } ) private var accessibilityTouchHelper = WeekViewAccessibilityTouchHelper( view = this, viewState = viewState, gestureHandler = gestureHandler, touchHandler = touchHandler, eventChipsCache = eventChipsCache ) private val scroller = ValueAnimator() private val renderers: List<Renderer> = listOf( TimeColumnRenderer(viewState), CalendarRenderer(viewState, eventChipsCache), HeaderRenderer(viewState, eventChipsCache) ) init { val accessibilityManager = context.getSystemService(Context.ACCESSIBILITY_SERVICE) as AccessibilityManager val isAccessibilityEnabled = accessibilityManager.isEnabled val isExploreByTouchEnabled = accessibilityManager.isTouchExplorationEnabled val isAccessibilityHelperActive = isAccessibilityEnabled && isExploreByTouchEnabled if (isAccessibilityHelperActive) { ViewCompat.setAccessibilityDelegate(this, accessibilityTouchHelper) } setLayerType(LAYER_TYPE_SOFTWARE, null) } override fun onDraw(canvas: Canvas) { super.onDraw(canvas) performPendingScrolls() updateDataHolders() notifyScrollListeners() refreshEvents() performRendering(canvas) } private fun performPendingScrolls() { val pendingDateScroll = viewState.scrollToDate viewState.scrollToDate = null pendingDateScroll?.let { date -> goToDate(date) } val pendingHourScroll = viewState.scrollToHour viewState.scrollToHour = null pendingHourScroll?.let { hour -> goToHour(hour) } } private fun updateDataHolders() { viewState.update() } private fun refreshEvents() { if (isInEditMode) { return } val pagedAdapter = adapter as? PagingAdapter ?: return pagedAdapter.loadPeriodsIfNecessary() } private fun performRendering(canvas: Canvas) { for (renderer in renderers) { renderer.render(canvas) } } override fun onSaveInstanceState(): Parcelable? { val superState = super.onSaveInstanceState() return superState?.let { SavedState(it, viewState.numberOfVisibleDays, viewState.firstVisibleDate) } } override fun onRestoreInstanceState(state: Parcelable) { val savedState = state as SavedState super.onRestoreInstanceState(savedState.superState) if (this.viewState.restoreNumberOfVisibleDays) { this.viewState.numberOfVisibleDays = savedState.numberOfVisibleDays } goToDate(savedState.firstVisibleDate) } override fun onSizeChanged(width: Int, height: Int, oldWidth: Int, oldHeight: Int) { super.onSizeChanged(width, height, oldWidth, oldHeight) viewState.onSizeChanged(width, height) renderers.forEach { it.onSizeChanged(width, height) } // TODO: Fix broken scrolling after orientation change } private fun notifyScrollListeners() { val oldFirstVisibleDay = viewState.firstVisibleDate val totalDayWidth = viewState.totalDayWidth val visibleDays = viewState.numberOfVisibleDays val daysScrolled = viewState.currentOrigin.x / totalDayWidth val delta = daysScrolled.roundToInt() * (-1) val firstVisibleDate = today() + Days(delta) viewState.firstVisibleDate = firstVisibleDate val hasFirstVisibleDayChanged = oldFirstVisibleDay.toEpochDays() != firstVisibleDate.toEpochDays() if (hasFirstVisibleDayChanged) { val lastVisibleDate = firstVisibleDate + Days(visibleDays - 1) adapter?.onRangeChanged(firstVisibleDate, lastVisibleDate) } } override fun invalidate() { viewState.invalidate() super.invalidate() } /* *********************************************************************************************** * * Calendar configuration * *********************************************************************************************** */ /** * Returns the first day of the week. Possible values are [java.util.Calendar.SUNDAY], * [java.util.Calendar.MONDAY], [java.util.Calendar.TUESDAY], * [java.util.Calendar.WEDNESDAY], [java.util.Calendar.THURSDAY], * [java.util.Calendar.FRIDAY], [java.util.Calendar.SATURDAY]. */ @PublicApi var firstDayOfWeek: Int get() = viewState.firstDayOfWeek set(value) { viewState.firstDayOfWeek = value invalidate() } /** * Returns the number of visible days. */ @PublicApi var numberOfVisibleDays: Int get() = viewState.numberOfVisibleDays set(value) { viewState.updateNumberOfVisibleDays(value) dateTimeInterpreter.onSetNumberOfDays(value) renderers.filterIsInstance(DateFormatterDependent::class.java).forEach { it.onDateFormatterChanged(viewState.dateFormatter) } invalidate() } /** * Returns whether the first day of the week should be displayed at the left-most position * when WeekView is displayed for the first time. */ @PublicApi var isShowFirstDayOfWeekFirst: Boolean get() = viewState.showFirstDayOfWeekFirst set(value) { viewState.showFirstDayOfWeekFirst = value } /* *********************************************************************************************** * * Header bottom line * *********************************************************************************************** */ @PublicApi var isShowHeaderRowBottomLine: Boolean /** * Returns whether a horizontal line should be displayed at the bottom of the header row. */ get() = viewState.showHeaderRowBottomLine /** * Sets whether a horizontal line should be displayed at the bottom of the header row. */ set(value) { viewState.showHeaderRowBottomLine = value invalidate() } @PublicApi var headerRowBottomLineColor: Int /** * Returns the color of the horizontal line at the bottom of the header row. */ get() = viewState.headerRowBottomLinePaint.color /** * Sets the color of the horizontal line at the bottom of the header row. Whether the line * is displayed, is determined by [isShowHeaderRowBottomLine] */ set(value) { viewState.headerRowBottomLinePaint.color = value invalidate() } @PublicApi var headerRowBottomLineWidth: Int /** * Returns the stroke width of the horizontal line at the bottom of the header row. */ get() = viewState.headerRowBottomLinePaint.strokeWidth.toInt() /** * Sets the stroke width of the horizontal line at the bottom of the header row. Whether the * line is displayed, is determined by [isShowHeaderRowBottomLine] */ set(value) { viewState.headerRowBottomLinePaint.strokeWidth = value.toFloat() invalidate() } /* *********************************************************************************************** * * Time column * *********************************************************************************************** */ /** * Returns the padding in the time column to the left and right side of the time label. */ @PublicApi var timeColumnPadding: Int get() = viewState.timeColumnPadding set(value) { viewState.timeColumnPadding = value invalidate() } /** * Returns the text color of the labels in the time column. */ @PublicApi var timeColumnTextColor: Int get() = viewState.timeColumnTextColor set(value) { viewState.timeColumnTextColor = value invalidate() } /** * Returns the background color of the time column. */ @PublicApi var timeColumnBackgroundColor: Int get() = viewState.timeColumnBackgroundColor set(value) { viewState.timeColumnBackgroundColor = value invalidate() } /** * Returns the text size of the labels in the time column. */ @PublicApi var timeColumnTextSize: Int get() = viewState.timeColumnTextSize set(value) { viewState.timeColumnTextSize = value invalidate() } /** * Returns whether the label for the midnight hour is displayed in the time column. This setting * is only considered if [isShowTimeColumnHourSeparator] is set to true. */ @PublicApi var isShowMidnightHour: Boolean get() = viewState.showMidnightHour set(value) { viewState.showMidnightHour = value invalidate() } /** * Returns whether a horizontal line is displayed for each hour in the time column. */ @PublicApi var isShowTimeColumnHourSeparator: Boolean get() = viewState.showTimeColumnHourSeparator set(value) { viewState.showTimeColumnHourSeparator = value invalidate() } /** * Returns the interval in which time labels are displayed in the time column. */ @PublicApi var timeColumnHoursInterval: Int get() = viewState.timeColumnHoursInterval set(value) { viewState.timeColumnHoursInterval = value invalidate() } /* *********************************************************************************************** * * Time column separator * *********************************************************************************************** */ /** * Returns whether a vertical line is displayed at the end of the time column. */ @PublicApi var isShowTimeColumnSeparator: Boolean get() = viewState.showTimeColumnSeparator set(value) { viewState.showTimeColumnSeparator = value invalidate() } /** * Returns the color of the time column separator. */ @PublicApi var timeColumnSeparatorColor: Int get() = viewState.timeColumnSeparatorColor set(value) { viewState.timeColumnSeparatorColor = value invalidate() } /** * Returns the stroke width of the time column separator. */ @PublicApi var timeColumnSeparatorWidth: Int get() = viewState.timeColumnSeparatorStrokeWidth set(value) { viewState.timeColumnSeparatorStrokeWidth = value invalidate() } /* *********************************************************************************************** * * Header row * *********************************************************************************************** */ /** * Returns the header row padding, which is applied above and below the all-day event chips. */ @PublicApi var headerRowPadding: Int get() = viewState.headerRowPadding set(value) { viewState.headerRowPadding = value invalidate() } /** * Returns the header row background color. */ @PublicApi var headerRowBackgroundColor: Int get() = viewState.headerRowBackgroundColor set(value) { viewState.headerRowBackgroundColor = value invalidate() } /** * Returns the text color used for all date labels except today. */ @PublicApi var headerRowTextColor: Int get() = viewState.headerRowTextColor set(value) { viewState.headerRowTextColor = value invalidate() } /** * Returns the text color used for today's date label. */ @PublicApi var todayHeaderTextColor: Int get() = viewState.todayHeaderTextColor set(value) { viewState.todayHeaderTextColor = value invalidate() } /** * Returns the text size of all date labels. */ @PublicApi var headerRowTextSize: Int get() = viewState.headerRowTextSize set(value) { viewState.headerRowTextSize = value invalidate() } /* *********************************************************************************************** * * Event chips * *********************************************************************************************** */ /** * Returns the corner radius of an [EventChip]. */ @PublicApi var eventCornerRadius: Int get() = viewState.eventCornerRadius set(value) { viewState.eventCornerRadius = value invalidate() } /** * Returns the text size of a single-event [EventChip]. */ @PublicApi var eventTextSize: Int get() = viewState.eventTextPaint.textSize.toInt() set(value) { viewState.eventTextPaint.textSize = value.toFloat() invalidate() } /** * Returns whether the text size of the [EventChip] is adapting to the [EventChip] height. */ @PublicApi var isAdaptiveEventTextSize: Boolean get() = viewState.adaptiveEventTextSize set(value) { viewState.adaptiveEventTextSize = value invalidate() } /** * Returns the text size of an all-day [EventChip]. */ @PublicApi var allDayEventTextSize: Int get() = viewState.allDayEventTextPaint.textSize.toInt() set(value) { viewState.allDayEventTextPaint.textSize = value.toFloat() invalidate() } /** * Returns the default text color of an [EventChip]. */ @PublicApi var defaultEventTextColor: Int get() = viewState.eventTextPaint.color set(value) { viewState.eventTextPaint.color = value invalidate() } /** * Returns the horizontal padding within an [EventChip]. */ @PublicApi var eventPaddingHorizontal: Int get() = viewState.eventPaddingHorizontal set(value) { viewState.eventPaddingHorizontal = value invalidate() } /** * Returns the vertical padding within an [EventChip]. */ @PublicApi var eventPaddingVertical: Int get() = viewState.eventPaddingVertical set(value) { viewState.eventPaddingVertical = value invalidate() } /** * Returns the default text color of an [EventChip]. */ @PublicApi var defaultEventColor: Int get() = viewState.defaultEventColor set(value) { viewState.defaultEventColor = value invalidate() } /* *********************************************************************************************** * * Event margins * *********************************************************************************************** */ /** * Returns the column gap at the end of each day. */ @PublicApi var columnGap: Int get() = viewState.columnGap set(value) { viewState.columnGap = value invalidate() } /** * Returns the horizontal gap between overlapping [EventChip]s. */ @PublicApi var overlappingEventGap: Int get() = viewState.overlappingEventGap set(value) { viewState.overlappingEventGap = value invalidate() } /** * Returns the vertical margin of an [EventChip]. */ @PublicApi var eventMarginVertical: Int get() = viewState.eventMarginVertical set(value) { viewState.eventMarginVertical = value invalidate() } /** * Returns the horizontal margin of an [EventChip]. This margin is only applied in single-day * view and if there are no overlapping events. */ @PublicApi var eventMarginHorizontal: Int get() = viewState.eventMarginHorizontal set(value) { viewState.eventMarginHorizontal = value invalidate() } /* *********************************************************************************************** * * Colors * *********************************************************************************************** */ /** * Returns the background color of a day. */ @PublicApi var dayBackgroundColor: Int get() = viewState.dayBackgroundPaint.color set(value) { viewState.dayBackgroundPaint.color = value invalidate() } /** * Returns the background color of the current date. */ @PublicApi var todayBackgroundColor: Int get() = viewState.todayBackgroundPaint.color set(value) { viewState.todayBackgroundPaint.color = value invalidate() } /** * Returns whether weekends should have a background color different from [dayBackgroundColor]. * * The weekend background colors can be defined by [pastWeekendBackgroundColor] and * [futureWeekendBackgroundColor]. */ @PublicApi var isShowDistinctWeekendColor: Boolean get() = viewState.showDistinctWeekendColor set(value) { viewState.showDistinctWeekendColor = value invalidate() } /** * Returns whether past and future days should have background colors different from * [dayBackgroundColor]. * * The past and future day colors can be defined by [pastBackgroundColor] and * [futureBackgroundColor]. */ @PublicApi var isShowDistinctPastFutureColor: Boolean get() = viewState.showDistinctPastFutureColor set(value) { viewState.showDistinctPastFutureColor = value invalidate() } /** * Returns the background color for past dates. If not explicitly set, WeekView will used * [dayBackgroundColor]. */ @PublicApi var pastBackgroundColor: Int get() = viewState.pastBackgroundPaint.color set(value) { viewState.pastBackgroundPaint.color = value invalidate() } /** * Returns the background color for past weekend dates. If not explicitly set, WeekView will * used [pastBackgroundColor]. */ @PublicApi var pastWeekendBackgroundColor: Int get() = viewState.pastWeekendBackgroundPaint.color set(value) { viewState.pastWeekendBackgroundPaint.color = value invalidate() } /** * Returns the background color for future dates. If not explicitly set, WeekView will used * [dayBackgroundColor]. */ @PublicApi var futureBackgroundColor: Int get() = viewState.futureBackgroundPaint.color set(value) { viewState.futureBackgroundPaint.color = value invalidate() } /** * Returns the background color for future weekend dates. If not explicitly set, WeekView will * used [futureBackgroundColor]. */ @PublicApi var futureWeekendBackgroundColor: Int get() = viewState.futureWeekendBackgroundPaint.color set(value) { viewState.futureWeekendBackgroundPaint.color = value invalidate() } /* *********************************************************************************************** * * Hour height * *********************************************************************************************** */ /** * Returns the current height of an hour. */ @PublicApi var hourHeight: Float get() = viewState.hourHeight set(value) { viewState.newHourHeight = value invalidate() } /** * Returns the minimum height of an hour. */ @PublicApi var minHourHeight: Int get() = viewState.minHourHeight set(value) { viewState.minHourHeight = value invalidate() } /** * Returns the maximum height of an hour. */ @PublicApi var maxHourHeight: Int get() = viewState.maxHourHeight set(value) { viewState.maxHourHeight = value invalidate() } /** * Returns whether the complete day should be shown, in which case [hourHeight] automatically * adjusts to accommodate all hours between [minHour] and [maxHour]. */ @PublicApi var isShowCompleteDay: Boolean get() = viewState.showCompleteDay set(value) { viewState.showCompleteDay = value invalidate() } /* *********************************************************************************************** * * Now line * *********************************************************************************************** */ /** * Returns whether a horizontal line should be displayed at the current time. */ @PublicApi var isShowNowLine: Boolean get() = viewState.showNowLine set(value) { viewState.showNowLine = value invalidate() } /** * Returns the color of the horizontal "now" line. */ @PublicApi var nowLineColor: Int get() = viewState.nowLinePaint.color set(value) { viewState.nowLinePaint.color = value invalidate() } /** * Returns the stroke width of the horizontal "now" line. */ @PublicApi var nowLineStrokeWidth: Int get() = viewState.nowLinePaint.strokeWidth.toInt() set(value) { viewState.nowLinePaint.strokeWidth = value.toFloat() invalidate() } /** * Returns whether a dot at the start of the "now" line is displayed. The dot is only displayed * if [isShowNowLine] is set to true. */ @PublicApi var isShowNowLineDot: Boolean get() = viewState.showNowLineDot set(value) { viewState.showNowLineDot = value invalidate() } /** * Returns the color of the dot at the start of the "now" line. */ @PublicApi var nowLineDotColor: Int get() = viewState.nowDotPaint.color set(value) { viewState.nowDotPaint.color = value invalidate() } /** * Returns the radius of the dot at the start of the "now" line. */ @PublicApi var nowLineDotRadius: Int get() = viewState.nowDotPaint.strokeWidth.toInt() set(value) { viewState.nowDotPaint.strokeWidth = value.toFloat() invalidate() } /* *********************************************************************************************** * * Hour separators * *********************************************************************************************** */ @PublicApi var isShowHourSeparators: Boolean get() = viewState.showHourSeparators set(value) { viewState.showHourSeparators = value invalidate() } @PublicApi var hourSeparatorColor: Int get() = viewState.hourSeparatorPaint.color set(value) { viewState.hourSeparatorPaint.color = value invalidate() } @PublicApi var hourSeparatorStrokeWidth: Int get() = viewState.hourSeparatorPaint.strokeWidth.toInt() set(value) { viewState.hourSeparatorPaint.strokeWidth = value.toFloat() invalidate() } /* *********************************************************************************************** * * Day separators * *********************************************************************************************** */ /** * Returns whether vertical lines are displayed as separators between dates. */ @PublicApi var isShowDaySeparators: Boolean get() = viewState.showDaySeparators set(value) { viewState.showDaySeparators = value invalidate() } /** * Returns the color of the separators between dates. */ @PublicApi var daySeparatorColor: Int get() = viewState.daySeparatorPaint.color set(value) { viewState.daySeparatorPaint.color = value invalidate() } /** * Returns the stroke color of the separators between dates. */ @PublicApi var daySeparatorStrokeWidth: Int get() = viewState.daySeparatorPaint.strokeWidth.toInt() set(value) { viewState.daySeparatorPaint.strokeWidth = value.toFloat() invalidate() } /* *********************************************************************************************** * * Date range * *********************************************************************************************** */ /** * Returns the minimum date that [WeekView] will display, or null if none is set. Events before * this date will not be shown. */ @PublicApi var minDate: Calendar? get() = viewState.minDate?.copy() set(value) { val maxDate = viewState.maxDate if (maxDate != null && value != null && value.isAfter(maxDate)) { throw IllegalArgumentException("Can't set a minDate that's after maxDate") } viewState.minDate = value invalidate() } /** * Returns the maximum date that [WeekView] will display, or null if none is set. Events after * this date will not be shown. */ @PublicApi var maxDate: Calendar? get() = viewState.maxDate?.copy() set(value) { val minDate = viewState.minDate if (minDate != null && value != null && value.isBefore(minDate)) { throw IllegalArgumentException("Can't set a maxDate that's before minDate") } viewState.maxDate = value invalidate() } /* *********************************************************************************************** * * Time range * *********************************************************************************************** */ /** * Returns the minimum hour that [WeekView] will display. Events before this time will not be * shown. */ @PublicApi var minHour: Int get() = viewState.minHour set(value) { if (value < 0 || value > viewState.maxHour) { throw IllegalArgumentException("minHour must be between 0 and maxHour.") } viewState.minHour = value invalidate() } /** * Returns the maximum hour that [WeekView] will display. Events before this time will not be * shown. */ @PublicApi var maxHour: Int get() = viewState.maxHour set(value) { if (value > 24 || value < viewState.minHour) { throw IllegalArgumentException("maxHour must be between minHour and 24.") } viewState.maxHour = value invalidate() } /* *********************************************************************************************** * * Scrolling * *********************************************************************************************** */ /** * Returns the scrolling speed factor in horizontal direction. */ @PublicApi @Deprecated("This value is no longer being taken into account.") var xScrollingSpeed: Float get() = viewState.xScrollingSpeed set(value) { viewState.xScrollingSpeed = value } /** * Returns whether WeekView can fling horizontally. */ @PublicApi @Deprecated( message = "Use isHorizontalScrollingEnabled instead.", replaceWith = ReplaceWith("isHorizontalScrollingEnabled") ) var isHorizontalFlingEnabled: Boolean get() = viewState.horizontalFlingEnabled set(value) { viewState.horizontalFlingEnabled = value } /** * Returns whether WeekView can scroll horizontally. */ @PublicApi var isHorizontalScrollingEnabled: Boolean get() = viewState.horizontalScrollingEnabled set(value) { viewState.horizontalScrollingEnabled = value } /** * Returns whether WeekView can fling vertically. */ @Deprecated("This value is no longer being taken into account.") @PublicApi var isVerticalFlingEnabled: Boolean get() = viewState.verticalFlingEnabled set(value) { viewState.verticalFlingEnabled = value } @PublicApi @Deprecated("This value is no longer being taken into account.") var scrollDuration: Int get() = viewState.scrollDuration set(value) { viewState.scrollDuration = value } @SuppressLint("ClickableViewAccessibility") override fun onTouchEvent(event: MotionEvent): Boolean = gestureHandler.onTouchEvent(event) /* *********************************************************************************************** * * Date methods * *********************************************************************************************** */ /** * Returns the first visible date. */ @PublicApi val firstVisibleDate: Calendar get() = viewState.firstVisibleDate.copy() /** * Returns the last visible date. */ @PublicApi val lastVisibleDate: Calendar get() = viewState.firstVisibleDate.copy() + Days(viewState.numberOfVisibleDays - 1) /** * Shows the current date. */ @PublicApi fun goToToday() { goToDate(today()) } /** * Shows the current date and time. */ @PublicApi fun goToCurrentTime() { now().apply { goToDate(this) goToHour(hour) } } /** * Shows a specific date. If it is before [minDate] or after [maxDate], these will be shown * instead. * * @param date The date to show. */ @PublicApi fun goToDate(date: Calendar) { val adjustedDate = viewState.getDateWithinDateRange(date) gestureHandler.forceScrollFinished() val isWaitingToBeLaidOut = ViewCompat.isLaidOut(this).not() if (viewState.areDimensionsInvalid || isWaitingToBeLaidOut) { // If the view's dimensions have just changed or if it hasn't been laid out yet, we // postpone the action until onDraw() is called the next time. viewState.scrollToDate = adjustedDate return } val destinationOffset = viewState.getXOriginForDate(date) val adjustedDestinationOffset = destinationOffset.limit( minValue = viewState.minX, maxValue = viewState.maxX ) scroller.animate( fromValue = viewState.currentOrigin.x, toValue = adjustedDestinationOffset, onUpdate = { viewState.currentOrigin.x = it invalidate() } ) // val diff = adjustedDate.daysFromToday // viewState.currentOrigin.x = diff.toFloat() * (-1f) * viewState.totalDayWidth // invalidate() } /** * Scrolls to a specific hour. * * @param hour The hour to scroll to, in 24-hour format. Supported values are 0-24. * * @throws IllegalArgumentException Throws exception if the provided hour is smaller than * [minHour] or larger than [maxHour]. */ @PublicApi fun goToHour(hour: Int) { if (viewState.areDimensionsInvalid) { viewState.scrollToHour = hour return } if (hour !in viewState.minHour..viewState.maxHour) { throw IllegalArgumentException( "The provided hour ($hour) is outside of the set time range " + "(${viewState.minHour} – ${viewState.maxHour})" ) } val hourHeight = viewState.hourHeight val desiredOffset = hourHeight * (hour - viewState.minHour) // We make sure that WeekView doesn't "over-scroll" by limiting the offset to the total day // height minus the height of WeekView, which would result in scrolling all the way to the // bottom. val maxOffset = viewState.totalDayHeight - height val finalOffset = min(maxOffset, desiredOffset) * (-1) scroller.animate( fromValue = viewState.currentOrigin.y, toValue = finalOffset, onUpdate = { viewState.currentOrigin.y = it invalidate() } ) } /** * Returns the first hour that is visible on the screen. */ @PublicApi val firstVisibleHour: Double get() = (viewState.currentOrigin.y * -1 / viewState.hourHeight).toDouble() /* *********************************************************************************************** * * Typeface * *********************************************************************************************** */ /** * Returns the typeface used for events, time labels and date labels. */ @PublicApi var typeface: Typeface get() = viewState.typeface set(value) { viewState.typeface = value invalidate() } /* *********************************************************************************************** * * Adapter * *********************************************************************************************** */ private var internalAdapter: Adapter<*>? = null var adapter: Adapter<*>? get() = internalAdapter set(value) { setAdapterInternal(value) } private fun setAdapterInternal(adapter: Adapter<*>?) { if (adapter == null) { internalAdapter?.unregisterObserver() touchHandler.adapter = null return } adapter.eventChipsCache = eventChipsCache internalAdapter = adapter touchHandler.adapter = adapter internalAdapter?.registerObserver(this) } @PublicApi @Deprecated("Use setDateFormatter() and setTimeFormatter() instead.") var dateTimeInterpreter: DateTimeInterpreter get() = object : DateTimeInterpreter { override fun interpretDate(date: Calendar): String = viewState.dateFormatter(date) override fun interpretTime(hour: Int): String = viewState.timeFormatter(hour) } set(value) { setDateFormatter { value.interpretDate(it) } setTimeFormatter { value.interpretTime(it) } invalidate() } @PublicApi fun setDateFormatter(formatter: DateFormatter) { viewState.dateFormatter = formatter renderers.filterIsInstance(DateFormatterDependent::class.java).forEach { it.onDateFormatterChanged(formatter) } invalidate() } @PublicApi fun setTimeFormatter(formatter: TimeFormatter) { viewState.timeFormatter = formatter renderers.filterIsInstance(TimeFormatterDependent::class.java).forEach { it.onTimeFormatterChanged(formatter) } invalidate() } override fun dispatchHoverEvent(event: MotionEvent): Boolean { if (accessibilityTouchHelper.dispatchHoverEvent(event)) { return true } return super.dispatchHoverEvent(event) } /** * An abstract base class for an adapter used with [WeekView]. * * An adapter allows interaction with [WeekView]. It provides optional methods for being * notified about clicks, long-clicks and scrolling events. * * @param T The type of elements that are displayed in the corresponding [WeekView]. */ abstract class Adapter<T> { internal abstract val eventsCache: EventsCache<T> private val eventChipsFactory = EventChipsFactory() internal lateinit var eventChipsCache: EventChipsCache internal val eventsDiffer: EventsDiffer<T> by lazy { EventsDiffer( context = context, eventsCache = eventsCache, eventChipsCache = eventChipsCache, eventChipsFactory = eventChipsFactory ) } internal var weekView: WeekView? = null private set val context: Context get() = checkNotNull(weekView).context internal fun handleClick(x: Float, y: Float): Boolean { val eventChip = findHitEvent(x, y) ?: return false val data = findEventData(id = eventChip.eventId) ?: return false onEventClick(data) eventChip.bounds?.let { bounds -> onEventClick(data, bounds) } return true } internal fun handleEmptyViewClick(time: Calendar) { onEmptyViewClick(time) } internal fun handleLongClick(x: Float, y: Float): Boolean { val eventChip = findHitEvent(x, y) ?: return false val data = findEventData(id = eventChip.eventId) ?: return false onEventLongClick(data) eventChip.bounds?.let { bounds -> onEventLongClick(data, bounds) } return true } internal fun handleEmptyViewLongClick(time: Calendar) { onEmptyViewLongClick(time) } private fun findHitEvent(x: Float, y: Float): EventChip? { val candidates = eventChipsCache.allEventChips.filter { it.isHit(x, y) } return when { candidates.isEmpty() -> null // Two events hit. This is most likely because an all-day event was clicked, but a // single event is rendered underneath it. We return the all-day event. candidates.size == 2 -> candidates.first { it.event.isAllDay } else -> candidates.first() } } internal fun registerObserver(weekView: WeekView) { this.weekView = weekView } internal fun updateObserver() { weekView?.invalidate() } internal fun unregisterObserver() { weekView = null } internal fun onEventClick(id: Long) { val event = eventsCache[id] ?: return onEventClick(data = event.data) } internal fun onEventLongClick(id: Long) { val event = eventsCache[id] ?: return onEventLongClick(data = event.data) } private fun findEventData(id: Long): T? = eventsCache[id]?.data /** * Returns the data of the [WeekViewEvent] that the user clicked on. * * @param data The data of the [WeekViewEvent] */ open fun onEventClick(data: T) = Unit /** * Returns the data of the [WeekViewEvent] that the user clicked on as well as the bounds * of the [EventChip] in which it is displayed. * * @param data The data of the [WeekViewEvent] * @param bounds The [RectF] representing the bounds of the event's [EventChip] */ open fun onEventClick(data: T, bounds: RectF) = Unit /** * Returns the data of the [WeekViewEvent] that the user long-clicked on. * * @param data The data of the [WeekViewEvent] */ open fun onEventLongClick(data: T) = Unit /** * Returns the data of the [WeekViewEvent] that the user long-clicked on as well as the * bounds of the [EventChip] in which it is displayed. * * @param data The data of the [WeekViewEvent] * @param bounds The [RectF] representing the bounds of the event's [EventChip] */ open fun onEventLongClick(data: T, bounds: RectF) = Unit /** * Returns the date and time of the location that the user clicked on. * * @param time A [Calendar] with the date and time */ open fun onEmptyViewClick(time: Calendar) = Unit /** * Returns the date and time of the location that the user long-clicked on. * * @param time A [Calendar] with the date and time */ open fun onEmptyViewLongClick(time: Calendar) = Unit /** * Called whenever the range of dates visible in [WeekView] changes. The list of dates is * typically as long as [numberOfVisibleDays], though it might contain an additional date * if [WeekView] is currently scrolling. * * @param firstVisibleDate A [Calendar] representing the first visible date * @param lastVisibleDate A [Calendar] representing the last visible date */ open fun onRangeChanged(firstVisibleDate: Calendar, lastVisibleDate: Calendar) = Unit } /** * An implementation of [WeekView.Adapter] that allows to submit a list of new elements to * [WeekView]. * * Newly submitted events are processed on a background thread and then presented in * [WeekView]. Previously submitted events are replaced completely. If you require a paginated * approach, you might want to use [WeekView.PagingAdapter]. * * @param T The type of elements that are displayed in the corresponding [WeekView]. */ open class SimpleAdapter<T> : Adapter<T>() { override val eventsCache = SimpleEventsCache<T>() /** * Submits a new list of [WeekViewDisplayable] elements to the adapter. These events are * processed on a background thread and then presented in [WeekView]. Previously submitted * events are replaced completely. * * @param events The [WeekViewDisplayable] elements that are to be displayed in [WeekView] */ @PublicApi fun submit(events: List<WeekViewDisplayable<T>>) { val viewState = weekView?.viewState ?: return eventsDiffer.submit(events, viewState, onFinished = this::updateObserver) } } /** * An implementation of [WeekView.Adapter] that allows to submit a list of new elements to * [WeekView] in a paginated way. * * This adapter keeps a cache of [WeekViewDisplayable] elements grouped by month. Whenever the * user scrolls to a different month, this adapter will check whether that month's events are * present in the cache. If not, it will dispatch a callback to [onLoadMore] with the start and * end dates of the months that need to be fetched. * * Newly submitted events are processed on a background thread and then presented in * [WeekView]. To clear the cache and thus refresh all events, you can call [refresh]. * * @param T The type of elements that are displayed in the corresponding [WeekView]. */ open class PagingAdapter<T> : Adapter<T>() { override val eventsCache = PagedEventsCache<T>() /** * Submits a new list of [WeekViewDisplayable] elements to the adapter. These events are * processed on a background thread and then presented in [WeekView]. Previously submitted * events of the same month are replaced completely. * * @param events The [WeekViewDisplayable] elements that are to be displayed in [WeekView] */ @PublicApi fun submit(events: List<WeekViewDisplayable<T>>) { val viewState = weekView?.viewState ?: return eventsDiffer.submit(events, viewState, onFinished = this::updateObserver) } /** * Called whenever [WeekView] needs to fetch [WeekViewDisplayable] elements of a given * month in order to allow for a smooth scrolling experience. * * This adapter caches [WeekViewDisplayable] elements of the current month as well as its * previous and next month. If [WeekView] scrolls to a new month, that month as well as its * surrounding months need to potentially be fetched. * * @param startDate A [Calendar] of the first date of the month that needs to be fetched * @param endDate A [Calendar] of the last date of the month that needs to be fetched */ @PublicApi open fun onLoadMore(startDate: Calendar, endDate: Calendar) = Unit /** * Refreshes the [WeekViewDisplayable] elements presented by this adapter. All cached * elements will be removed and a call to [onLoadMore] will be triggered. */ @PublicApi fun refresh() { eventsCache.clear() weekView?.invalidate() } internal fun loadPeriodsIfNecessary() { val firstVisibleDate = weekView?.viewState?.firstVisibleDate ?: return val fetchRange = FetchRange.create(firstVisibleDate) if (fetchRange in eventsCache) { return } val periodsToFetch = eventsCache.determinePeriodsToFetch(fetchRange) if (periodsToFetch.isNotEmpty()) { fetchPeriods(periodsToFetch) } } private fun fetchPeriods(periods: List<Period>) { val grouped = periods.groupConsecutivePeriods() for (period in periods) { // We add an empty list for the periods to avoid multiple fetch attempts. eventsCache.reserve(period) } for (group in grouped) { val first = group.first() val last = group.last() onLoadMore(first.startDate, last.endDate) } } private fun List<Period>.groupConsecutivePeriods(): List<List<Period>> { val emptyList = mutableListOf<MutableList<Period>>() return fold(emptyList) { accumulator, period -> val lastPeriodInList = accumulator.lastOrNull()?.last() val isConsecutive = lastPeriodInList?.next == period if (accumulator.isEmpty() || !isConsecutive) { accumulator.add(mutableListOf(period)) } else { accumulator.last().add(period) } accumulator } } } }
0
null
0
0
f0af8e1db5a49752c40cac14e089d45ebc3c70fb
48,458
Android-Week-View
Apache License 2.0
src/jsMain/kotlin/com/palantir/blueprintjs/select/popoverSharedProps.module_@blueprintjs_core.kt
HoffiMuc
322,618,517
false
null
@file:Suppress("INTERFACE_WITH_SUPERCLASS", "OVERRIDING_FINAL_MEMBER", "RETURN_TYPE_MISMATCH_ON_OVERRIDE", "CONFLICTING_OVERLOADS") @file:JsModule("@blueprintjs/select") @file:JsNonModule package com.palantir.blueprintjs.select import org.khronos.webgl.* import org.w3c.dom.* import org.w3c.dom.events.* import org.w3c.dom.parsing.* import org.w3c.dom.svg.* import org.w3c.dom.url.* import org.w3c.fetch.* import org.w3c.files.* import org.w3c.notifications.* import org.w3c.performance.* import org.w3c.workers.* import org.w3c.xhr.* import kotlin.js.* external interface IPopoverSharedProps : IOverlayableProps, IProps { var boundary: Boundary? get() = definedExternally set(value) = definedExternally var captureDismiss: Boolean? get() = definedExternally set(value) = definedExternally var defaultIsOpen: Boolean? get() = definedExternally set(value) = definedExternally var disabled: Boolean? get() = definedExternally set(value) = definedExternally var hoverCloseDelay: Number? get() = definedExternally set(value) = definedExternally var hoverOpenDelay: Number? get() = definedExternally set(value) = definedExternally var inheritDarkTheme: Boolean? get() = definedExternally set(value) = definedExternally var isOpen: Boolean? get() = definedExternally set(value) = definedExternally var minimal: Boolean? get() = definedExternally set(value) = definedExternally var modifiers: Modifiers? get() = definedExternally set(value) = definedExternally var onInteraction: ((nextOpenState: Boolean, e: Event) -> Unit)? get() = definedExternally set(value) = definedExternally var openOnTargetFocus: Boolean? get() = definedExternally set(value) = definedExternally var popoverClassName: String? get() = definedExternally set(value) = definedExternally var position: Any? get() = definedExternally set(value) = definedExternally var targetClassName: String? get() = definedExternally set(value) = definedExternally var targetProps: Any? get() = definedExternally set(value) = definedExternally var targetTagName: Any? get() = definedExternally set(value) = definedExternally override var usePortal: Boolean? get() = definedExternally set(value) = definedExternally var wrapperTagName: Any? get() = definedExternally set(value) = definedExternally }
0
Kotlin
0
0
45d2438e7b26e4124df70bf7ed08774ee3fb0cb8
2,630
web-app-react-kotlin-js-gradle
Apache License 2.0
app/src/main/java/com/example/kfp_movies/ui/single_recommended_movie/SingleRecommendedMovieViewModel.kt
adids1221
654,955,299
false
null
package com.example.kfp_movies.ui.single_recommended_movie import androidx.lifecycle.* import com.example.kfp_movies.data.models.FavoriteMovie import com.example.kfp_movies.data.repository.MovieRepository import dagger.hilt.android.lifecycle.HiltViewModel import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.launch import kotlinx.coroutines.withContext import javax.inject.Inject @HiltViewModel class SingleRecommendedMovieViewModel @Inject constructor( private val movieRepository: MovieRepository ) : ViewModel() { private val _id = MutableLiveData<Int>() val movie = _id.switchMap { movieRepository.getRecommendedMovie(it) } fun setId(id: Int) { _id.value = id } fun addToFavorites(favoriteMovie: FavoriteMovie) { viewModelScope.launch { movieRepository.insertFavoriteMovie(favoriteMovie) } } fun removeFromFavorites(favoriteMovie: FavoriteMovie) { viewModelScope.launch { movieRepository.deleteFavoriteMovie(favoriteMovie) } } fun isFavoriteMovie(id: Int?): LiveData<Boolean> { val resultLiveData = MutableLiveData<Boolean>() viewModelScope.launch { movieRepository.isFavoriteMovie(id) val isFavorite = withContext(Dispatchers.IO) { movieRepository.isFavoriteMovie(id) } resultLiveData.postValue(isFavorite ) } return resultLiveData } }
0
Kotlin
0
0
d6b853d68b478a8f5310ba0f4f3d951c5bc456f0
1,460
kotlin-final-project
MIT License
shared/src/commonMain/kotlin/com/multiplatformkickstarter/app/extensions/KtorExtensions.kt
MultiplatformKickstarter
713,325,823
false
{"HTML": 589554, "Kotlin": 392992, "Swift": 596, "Dockerfile": 295}
package com.myprojectname.app.extensions import io.ktor.client.HttpClient import io.ktor.client.call.body import io.ktor.client.plugins.ClientRequestException import io.ktor.client.plugins.ResponseException import io.ktor.client.plugins.ServerResponseException import io.ktor.client.request.HttpRequestBuilder import io.ktor.client.request.request import io.ktor.utils.io.errors.IOException import kotlinx.serialization.SerializationException suspend fun <T> HttpClient.requestAndCatch( block: suspend HttpClient.() -> T, errorHandler: suspend ResponseException.() -> T ): T = runCatching { block() } .getOrElse { when (it) { is ResponseException -> it.errorHandler() else -> throw it } } suspend inline fun <reified T, reified E> HttpClient.safeRequest( block: HttpRequestBuilder.() -> Unit ): ApiResponse<T, E> = try { val response = request { block() } ApiResponse.Success(response.body()) } catch (e: ClientRequestException) { ApiResponse.Error.HttpError(e.response.status.value, e.errorBody()) } catch (e: ServerResponseException) { ApiResponse.Error.HttpError(e.response.status.value, e.errorBody()) } catch (e: IOException) { ApiResponse.Error.NetworkError } catch (e: SerializationException) { ApiResponse.Error.SerializationError } suspend inline fun <reified E> ResponseException.errorBody(): E? = try { response.body() } catch (e: SerializationException) { null } sealed class ApiResponse<out T, out E> { /** * Represents successful network responses (2xx). */ data class Success<T>(val body: T) : ApiResponse<T, Nothing>() sealed class Error<E> : ApiResponse<Nothing, E>() { /** * Represents server (50x) and client (40x) errors. */ data class HttpError<E>(val code: Int, val errorBody: E?) : Error<E>() /** * Represent IOExceptions and connectivity issues. */ data object NetworkError : Error<Nothing>() /** * Represent SerializationExceptions. */ data object SerializationError : Error<Nothing>() } }
2
HTML
7
96
3cd6e38e97065d3f511878f419fa636c91553c40
2,211
Adoptme
Apache License 2.0
shared/src/commonMain/kotlin/com/multiplatformkickstarter/app/extensions/KtorExtensions.kt
MultiplatformKickstarter
713,325,823
false
{"HTML": 589554, "Kotlin": 392992, "Swift": 596, "Dockerfile": 295}
package com.myprojectname.app.extensions import io.ktor.client.HttpClient import io.ktor.client.call.body import io.ktor.client.plugins.ClientRequestException import io.ktor.client.plugins.ResponseException import io.ktor.client.plugins.ServerResponseException import io.ktor.client.request.HttpRequestBuilder import io.ktor.client.request.request import io.ktor.utils.io.errors.IOException import kotlinx.serialization.SerializationException suspend fun <T> HttpClient.requestAndCatch( block: suspend HttpClient.() -> T, errorHandler: suspend ResponseException.() -> T ): T = runCatching { block() } .getOrElse { when (it) { is ResponseException -> it.errorHandler() else -> throw it } } suspend inline fun <reified T, reified E> HttpClient.safeRequest( block: HttpRequestBuilder.() -> Unit ): ApiResponse<T, E> = try { val response = request { block() } ApiResponse.Success(response.body()) } catch (e: ClientRequestException) { ApiResponse.Error.HttpError(e.response.status.value, e.errorBody()) } catch (e: ServerResponseException) { ApiResponse.Error.HttpError(e.response.status.value, e.errorBody()) } catch (e: IOException) { ApiResponse.Error.NetworkError } catch (e: SerializationException) { ApiResponse.Error.SerializationError } suspend inline fun <reified E> ResponseException.errorBody(): E? = try { response.body() } catch (e: SerializationException) { null } sealed class ApiResponse<out T, out E> { /** * Represents successful network responses (2xx). */ data class Success<T>(val body: T) : ApiResponse<T, Nothing>() sealed class Error<E> : ApiResponse<Nothing, E>() { /** * Represents server (50x) and client (40x) errors. */ data class HttpError<E>(val code: Int, val errorBody: E?) : Error<E>() /** * Represent IOExceptions and connectivity issues. */ data object NetworkError : Error<Nothing>() /** * Represent SerializationExceptions. */ data object SerializationError : Error<Nothing>() } }
2
HTML
7
96
3cd6e38e97065d3f511878f419fa636c91553c40
2,211
Adoptme
Apache License 2.0
core/ui/src/main/kotlin/com/t8rin/imagetoolboxlite/core/ui/widget/value/ValueText.kt
T8RIN
767,600,774
false
{"Kotlin": 3806441}
/* * ImageToolbox is an image editor for android * Copyright (c) 2024 T8RIN (<NAME>) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * You should have received a copy of the Apache License * along with this program. If not, see <http://www.apache.org/licenses/LICENSE-2.0>. */ package ru.tech.imageresizershrinker.core.ui.widget.value import androidx.compose.animation.AnimatedContent import androidx.compose.animation.core.tween import androidx.compose.animation.fadeIn import androidx.compose.animation.fadeOut import androidx.compose.animation.togetherWith import androidx.compose.foundation.clickable import androidx.compose.foundation.layout.padding import androidx.compose.foundation.shape.CircleShape import androidx.compose.material3.LocalContentColor import androidx.compose.material3.Text import androidx.compose.runtime.Composable import androidx.compose.ui.Modifier import androidx.compose.ui.draw.clip import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.sp import ru.tech.imageresizershrinker.core.domain.utils.trimTrailingZero @Composable fun ValueText( modifier: Modifier = Modifier.padding( top = 8.dp, end = 8.dp ), value: Number, enabled: Boolean = true, valueSuffix: String = "", onClick: () -> Unit ) { AnimatedContent( targetState = value, transitionSpec = { fadeIn(tween(100)) togetherWith fadeOut(tween(100)) } ) { Text( text = "${it.toString().trimTrailingZero()}$valueSuffix", color = LocalContentColor.current.copy(0.5f), modifier = modifier .clip(CircleShape) .clickable(enabled = enabled, onClick = onClick) .padding(horizontal = 16.dp, vertical = 6.dp), lineHeight = 18.sp ) } }
8
Kotlin
172
8
f8fe322c2bde32544e207b49a01cfeac92c187ce
2,228
ImageToolboxLite
Apache License 2.0
lib/android/app/src/main/java/com/reactnativenavigation/views/element/animators/ReactViewRotationAnimator.kt
wix
53,662,249
false
null
package com.reactnativenavigation.views.element.animators import android.animation.Animator import android.animation.ObjectAnimator import android.view.View import com.facebook.react.views.view.ReactViewGroup import com.reactnativenavigation.options.SharedElementTransitionOptions class ReactViewRotationAnimator(from: View, to: View) : PropertyAnimatorCreator<ReactViewGroup>(from, to) { private val fromRotation = from.rotation private val toRotation = to.rotation override fun shouldAnimateProperty(fromChild: ReactViewGroup, toChild: ReactViewGroup): Boolean { return fromRotation != toRotation && fromChild.childCount == 0 && toChild.childCount == 0 } override fun create(options: SharedElementTransitionOptions): Animator { to.rotation = fromRotation to.pivotX = 0f to.pivotY = 0f return ObjectAnimator.ofFloat(to, View.ROTATION, fromRotation, toRotation) } }
279
null
2674
13,023
8c64969f09657918e5840dca4f9ab8162f3bf356
965
react-native-navigation
MIT License
app/src/main/java/com/androidvip/hebf/utils/SettingsUtils.kt
Lennoard
61,443,609
false
{"Kotlin": 764483, "Java": 86252, "Shell": 19253, "HTML": 2302}
package com.androidvip.hebf.utils import android.content.ContentResolver import android.content.Context import android.os.Build import android.provider.Settings /** * Helper class for reading / writing on System settings * This class will not be able to write "Secure" or "Global" settings * * @param applicationContext non-null */ class SettingsUtils(val applicationContext: Context?) { private val cr: ContentResolver private val canWriteSettings: Boolean init { requireNotNull(applicationContext) { "Context may not be null" } cr = applicationContext.contentResolver canWriteSettings = Build.VERSION.SDK_INT < 23 || Settings.System.canWrite(applicationContext) } /** * Updates a system setting as an integer (or creates if it is not already present * * @param setting The setting to modify / create * @param value The integer value to set * @return true if the operation is successfully complete, false otherwise */ fun putInt(setting: String, value: Int): Boolean { return if (canWriteSettings) { Settings.System.putInt(cr, setting, value) } else false // We are not allowed to do this operation, return false } /** * Retrieves a system settings value as an integer. * * @param setting The setting to retrieve * @param defaultValue Value to return if the setting is not defined. * @return The setting's current value, or {@param defaultValue} if it is not defined * or not a valid integer. */ fun getInt(setting: String, defaultValue: Int): Int { return Settings.System.getInt(cr, setting, defaultValue) } /** * Updates a system setting as a String (or creates if it is not already present * * @param setting The setting to modify / create * @param value The String value to set * @return true if the operation is successfully complete, false otherwise */ fun putString(setting: String, value: String): Boolean { return if (canWriteSettings) { Settings.System.putString(cr, setting, value) } else false // We are not allowed to do this operation, return false } /** * Retrieves a system settings value as a String. * * @param setting The setting to retrieve * @return The setting's current value */ fun getString(setting: String): String { return Settings.System.getString(cr, setting) } /** * Changes the screen backlight brightness * * @param level the screen brightness level * @return true if the operation was successfully completed, false otherwise * @throws IllegalArgumentException if the level is not between 0 and 255 */ fun changeBrightness(level: Int = 150): Boolean { // Check level values before start if (level < 0 || level > 255) { Logger.logWarning("The brightness level must be between 0 and 255. Got $level.", applicationContext) } // Check if the brightness is on auto mode, and if so, change to manual val brightnessMode = Settings.System.getInt(cr, Settings.System.SCREEN_BRIGHTNESS_MODE, 0) if (brightnessMode == Settings.System.SCREEN_BRIGHTNESS_MODE_AUTOMATIC) { if (!putInt(Settings.System.SCREEN_BRIGHTNESS_MODE, Settings.System.SCREEN_BRIGHTNESS_MODE_MANUAL)) { // Couldn't change brightness mode, finish returning false return false } } return putInt(Settings.System.SCREEN_BRIGHTNESS, level) } }
0
Kotlin
30
50
12781b0de2b62baed994159748279d2c33abe390
3,613
hebf-android
Apache License 2.0
app/src/androidTest/java/com/steleot/jetpackcompose/playground/compose/constraintlayout/JsonConstraintSetScreenTest.kt
Vivecstel
338,792,534
false
{"Kotlin": 1538487}
package com.steleot.jetpackcompose.playground.compose.constraintlayout import androidx.compose.ui.test.junit4.createComposeRule import com.steleot.jetpackcompose.playground.compose.theme.TestTheme import org.junit.Rule import org.junit.Test class JsonConstraintSetScreenTest { @get:Rule val composeTestRule = createComposeRule() @Test fun testJsonConstraintSetScreen() { composeTestRule.setContent { TestTheme { JsonConstraintSetScreen() } } // todo } }
1
Kotlin
46
346
0161d9c7bf2eee53270ba2227a61d71ba8292ad0
541
Jetpack-Compose-Playground
Apache License 2.0
app/src/main/java/com/osayande/todolist/DetailsActivity.kt
WanjaMIKE
501,626,960
false
{"Kotlin": 14013}
package com.osayande.todolist import androidx.appcompat.app.AppCompatActivity import android.os.Bundle import android.widget.Toast import androidx.activity.viewModels import androidx.databinding.DataBindingUtil import com.osayande.todolist.business.Task import com.osayande.todolist.databinding.ActivityDetailBinding class DetailsActivity : AppCompatActivity() { private lateinit var binding:ActivityDetailBinding private val todoViewModel: ToDoViewModel by viewModels { ToDoViewModelFactory((application as ToDoApplication).todorepository) } override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) binding = DataBindingUtil.setContentView(this, R.layout.activity_detail) var title = intent?.getStringExtra("title") var description = intent?.getStringExtra("desc") var id = intent.getIntExtra("id",0) var color = intent.getIntExtra("color",0) binding.titletxtview.text = title binding.desctextview.text = description var task = Task(title.toString(), description.toString(), false, System.currentTimeMillis(), color, id) binding.deletebtn.setOnClickListener { //deleting from db todoViewModel.deleteNote(task) Toast.makeText(this,"Item deleted",Toast.LENGTH_SHORT).show() finish() } binding.markasdonebtn.setOnClickListener { //updating the complete bool value as true todoViewModel.updateNote( Task(title.toString(), description.toString(), true, System.currentTimeMillis(), color, id)) } } }
0
Kotlin
0
2
5ac4a180f29f60948c61918a2285643b6102e610
1,644
todolistapp
MIT License
components/crypto/crypto-service-impl/src/main/kotlin/net/corda/crypto/service/impl/bus/HSMRegistrationBusProcessor.kt
corda
346,070,752
false
null
package net.corda.crypto.service.impl.bus import net.corda.configuration.read.ConfigChangedEvent import net.corda.crypto.config.impl.hsmRegistrationBusProcessor import net.corda.crypto.config.impl.toCryptoConfig import net.corda.crypto.impl.retrying.BackoffStrategy import net.corda.crypto.impl.retrying.CryptoRetryingExecutor import net.corda.crypto.service.HSMService import net.corda.data.crypto.wire.CryptoNoContentValue import net.corda.data.crypto.wire.CryptoRequestContext import net.corda.data.crypto.wire.CryptoResponseContext import net.corda.data.crypto.wire.hsm.registration.HSMRegistrationRequest import net.corda.data.crypto.wire.hsm.registration.HSMRegistrationResponse import net.corda.data.crypto.wire.hsm.registration.commands.AssignSoftHSMCommand import net.corda.data.crypto.wire.hsm.registration.queries.AssignedHSMQuery import net.corda.messaging.api.processor.RPCResponderProcessor import net.corda.utilities.debug import org.slf4j.Logger import org.slf4j.LoggerFactory import java.time.Instant import java.util.concurrent.CompletableFuture class HSMRegistrationBusProcessor( private val hsmService: HSMService, event: ConfigChangedEvent ) : RPCResponderProcessor<HSMRegistrationRequest, HSMRegistrationResponse> { companion object { private val logger: Logger = LoggerFactory.getLogger(this::class.java.enclosingClass) } private val config = event.config.toCryptoConfig().hsmRegistrationBusProcessor() private val executor = CryptoRetryingExecutor( logger, BackoffStrategy.createBackoff(config.maxAttempts, config.waitBetweenMills) ) override fun onNext(request: HSMRegistrationRequest, respFuture: CompletableFuture<HSMRegistrationResponse>) { try { logger.info("Handling {} for tenant {}", request.request::class.java.name, request.context.tenantId) val response = executor.executeWithRetry { handleRequest(request.request, request.context) } val result = HSMRegistrationResponse(createResponseContext(request), response) logger.debug { "Handled ${request.request::class.java.name} for tenant ${request.context.tenantId} with" + " ${if (result.response != null) result.response::class.java.name else "null"}" } respFuture.complete(result) } catch (e: Throwable) { logger.error("Failed to handle ${request.request::class.java} for tenant ${request.context.tenantId}", e) respFuture.completeExceptionally(e) } } private fun handleRequest(request: Any, context: CryptoRequestContext): Any { return when (request) { is AssignSoftHSMCommand -> hsmService.assignSoftHSM(context.tenantId, request.category) is AssignedHSMQuery -> hsmService.findAssignedHSM(context.tenantId, request.category) ?: CryptoNoContentValue() else -> throw IllegalArgumentException("Unknown request type ${request::class.java.name}") } } private fun createResponseContext(request: HSMRegistrationRequest) = CryptoResponseContext( request.context.requestingComponent, request.context.requestTimestamp, request.context.requestId, Instant.now(), request.context.tenantId, request.context.other ) }
96
null
9
69
0766222eb6284c01ba321633e12b70f1a93ca04e
3,360
corda-runtime-os
Apache License 2.0
src/main/kotlin/com/github/mohamead/spiderlog/setting/SettingState.kt
mohamead
475,413,657
false
{"Kotlin": 20434}
package com.github.mohamead.spiderlog.setting import com.github.mohamead.spiderlog.enum.FontName import com.github.mohamead.spiderlog.enum.FontStyle import com.intellij.openapi.application.ApplicationManager import com.intellij.openapi.components.PersistentStateComponent import com.intellij.openapi.components.State import com.intellij.openapi.components.Storage import com.intellij.util.xmlb.XmlSerializerUtil @State( name = "com.github.mohamead.spiderlog.settings.SpiderlogSettingsState", storages = [Storage("SdkSettingsPlugin.xml")] ) internal class SettingState : PersistentStateComponent<SettingState> { var fontName: String = FontName.JETBRAINS_MONO.value var fontStyle: FontStyle = FontStyle.PLAIN var fontSize = 13 fun getInstance(): SettingState { return ApplicationManager.getApplication().getService(SettingState::class.java)!! } override fun getState(): SettingState { return this } override fun loadState(state: SettingState) { XmlSerializerUtil.copyBean(state, this) } }
0
Kotlin
0
3
d0282d415cbbc01feff0013bb30f71538e5522b3
1,062
spiderlog
Apache License 2.0
src/main/kotlin/com/github/mohamead/spiderlog/setting/SettingState.kt
mohamead
475,413,657
false
{"Kotlin": 20434}
package com.github.mohamead.spiderlog.setting import com.github.mohamead.spiderlog.enum.FontName import com.github.mohamead.spiderlog.enum.FontStyle import com.intellij.openapi.application.ApplicationManager import com.intellij.openapi.components.PersistentStateComponent import com.intellij.openapi.components.State import com.intellij.openapi.components.Storage import com.intellij.util.xmlb.XmlSerializerUtil @State( name = "com.github.mohamead.spiderlog.settings.SpiderlogSettingsState", storages = [Storage("SdkSettingsPlugin.xml")] ) internal class SettingState : PersistentStateComponent<SettingState> { var fontName: String = FontName.JETBRAINS_MONO.value var fontStyle: FontStyle = FontStyle.PLAIN var fontSize = 13 fun getInstance(): SettingState { return ApplicationManager.getApplication().getService(SettingState::class.java)!! } override fun getState(): SettingState { return this } override fun loadState(state: SettingState) { XmlSerializerUtil.copyBean(state, this) } }
0
Kotlin
0
3
d0282d415cbbc01feff0013bb30f71538e5522b3
1,062
spiderlog
Apache License 2.0
shuttle/onboarding/presentation/src/main/kotlin/shuttle/onboarding/presentation/ui/OnboardingWidgetPage.kt
4face-studi0
462,194,990
false
null
package shuttle.onboarding.presentation.ui import androidx.compose.runtime.Composable import androidx.compose.ui.tooling.preview.Preview import shuttle.apps.domain.sample.AppNameSample import shuttle.design.model.WidgetPreviewAppUiModel import shuttle.design.model.WidgetPreviewUiModel import shuttle.design.sample.DrawableSample import shuttle.design.theme.ShuttleTheme import shuttle.design.ui.LoadingSpinner import shuttle.design.ui.WidgetPreview import shuttle.onboarding.presentation.model.OnboardingWidgetPreviewState import shuttle.onboarding.presentation.viewmodel.OnboardingViewModel import studio.forface.shuttle.design.R.string @Composable internal fun OnboardingWidgetPage(state: OnboardingWidgetPreviewState, actions: OnboardingPage.NavigationActions) { OnboardingPageContent( index = OnboardingPage.Index.WIDGET, title = string.onboarding_widget_title, image = { when (state) { OnboardingWidgetPreviewState.Loading -> LoadingSpinner() is OnboardingWidgetPreviewState.Data -> WidgetPreview( model = state.widgetPreview ) } }, description = string.onboarding_widget_description, navigationActions = actions ) } @Composable @Preview(showSystemUi = true) private fun OnboardingWidgetPagePreview() { val state = OnboardingWidgetPreviewState.Data( widgetPreview = WidgetPreviewUiModel( layout = OnboardingViewModel.WidgetLayout, apps = listOf( WidgetPreviewAppUiModel(AppNameSample.Shuttle.value, DrawableSample.Empty), WidgetPreviewAppUiModel(AppNameSample.CineScout.value, DrawableSample.Empty), WidgetPreviewAppUiModel(AppNameSample.MovieBase.value, DrawableSample.Empty), WidgetPreviewAppUiModel(AppNameSample.Slack.value, DrawableSample.Empty) ) ) ) val actions = OnboardingPage.NavigationActions(onPrevious = {}, onNext = {}, onComplete = {}) ShuttleTheme { OnboardingWidgetPage(state = state, actions = actions) } }
11
Kotlin
0
14
55ab90f13bb96e10add14d45cd3117ada38262ed
2,126
Shuttle
Apache License 2.0
src/main/kotlin/uk/gov/justice/digital/hmpps/visitscheduler/dto/CreateLegacyDataRequestDto.kt
ministryofjustice
409,259,375
false
null
package uk.gov.justice.digital.hmpps.visitscheduler.dto import io.swagger.v3.oas.annotations.media.Schema import jakarta.validation.constraints.NotNull data class CreateLegacyDataRequestDto( @Schema(description = "NOMIS lead visitor ID", example = "1234556", required = true) @field:NotNull val leadVisitorId: Long, )
3
Kotlin
2
6
e2166e8bf546d8792c56ecb3d8d4d838ce63a7c2
327
visit-scheduler
MIT License
kotlin-cdk-wrapper/src/main/kotlin/io/cloudshiftdev/awscdk/services/ecs/patterns/NetworkMultipleTargetGroupsFargateServiceProps.kt
cloudshiftinc
667,063,030
false
{"Kotlin": 137826907}
@file:Suppress("RedundantVisibilityModifier","RedundantUnitReturnType","RemoveRedundantQualifierName","unused","UnusedImport","ClassName","REDUNDANT_PROJECTION","DEPRECATION") package io.cloudshiftdev.awscdk.services.ecs.patterns import io.cloudshiftdev.awscdk.Duration import io.cloudshiftdev.awscdk.common.CdkDslMarker import io.cloudshiftdev.awscdk.common.CdkObject import io.cloudshiftdev.awscdk.common.CdkObjectWrappers import io.cloudshiftdev.awscdk.services.ec2.ISecurityGroup import io.cloudshiftdev.awscdk.services.ec2.IVpc import io.cloudshiftdev.awscdk.services.ec2.SubnetSelection import io.cloudshiftdev.awscdk.services.ecs.CapacityProviderStrategy import io.cloudshiftdev.awscdk.services.ecs.CloudMapOptions import io.cloudshiftdev.awscdk.services.ecs.DeploymentCircuitBreaker import io.cloudshiftdev.awscdk.services.ecs.DeploymentController import io.cloudshiftdev.awscdk.services.ecs.FargatePlatformVersion import io.cloudshiftdev.awscdk.services.ecs.FargateTaskDefinition import io.cloudshiftdev.awscdk.services.ecs.ICluster import io.cloudshiftdev.awscdk.services.ecs.PropagatedTagSource import io.cloudshiftdev.awscdk.services.ecs.RuntimePlatform import io.cloudshiftdev.awscdk.services.elasticloadbalancingv2.INetworkLoadBalancer import io.cloudshiftdev.awscdk.services.elasticloadbalancingv2.IpAddressType import io.cloudshiftdev.awscdk.services.route53.IHostedZone import kotlin.Boolean import kotlin.Number import kotlin.String import kotlin.Unit import kotlin.collections.List import kotlin.jvm.JvmName /** * The properties for the NetworkLoadBalancedFargateService service. * * Example: * * ``` * Vpc vpc; * SecurityGroup securityGroup; * NetworkLoadBalancedFargateService queueProcessingFargateService = * NetworkLoadBalancedFargateService.Builder.create(this, "Service") * .vpc(vpc) * .memoryLimitMiB(512) * .taskImageOptions(NetworkLoadBalancedTaskImageOptions.builder() * .image(ContainerImage.fromRegistry("amazon/amazon-ecs-sample")) * .build()) * .securityGroups(List.of(securityGroup)) * .build(); * ``` */ public interface NetworkLoadBalancedFargateServiceProps : NetworkLoadBalancedServiceBaseProps, FargateServiceBaseProps { /** * Determines whether the service will be assigned a public IP address. * * Default: false */ public fun assignPublicIp(): Boolean? = unwrap(this).getAssignPublicIp() /** * The security groups to associate with the service. * * If you do not specify a security group, a new security group is created. * * Default: - A new security group is created. */ public fun securityGroups(): List<ISecurityGroup> = unwrap(this).getSecurityGroups()?.map(ISecurityGroup::wrap) ?: emptyList() /** * The subnets to associate with the service. * * Default: - Public subnets if `assignPublicIp` is set, otherwise the first available one of * Private, Isolated, Public, in that order. */ public fun taskSubnets(): SubnetSelection? = unwrap(this).getTaskSubnets()?.let(SubnetSelection::wrap) /** * A builder for [NetworkLoadBalancedFargateServiceProps] */ @CdkDslMarker public interface Builder { /** * @param assignPublicIp Determines whether the service will be assigned a public IP address. */ public fun assignPublicIp(assignPublicIp: Boolean) /** * @param capacityProviderStrategies A list of Capacity Provider strategies used to place a * service. */ public fun capacityProviderStrategies(capacityProviderStrategies: List<CapacityProviderStrategy>) /** * @param capacityProviderStrategies A list of Capacity Provider strategies used to place a * service. */ public fun capacityProviderStrategies(vararg capacityProviderStrategies: CapacityProviderStrategy) /** * @param circuitBreaker Whether to enable the deployment circuit breaker. * If this property is defined, circuit breaker will be implicitly * enabled. */ public fun circuitBreaker(circuitBreaker: DeploymentCircuitBreaker) /** * @param circuitBreaker Whether to enable the deployment circuit breaker. * If this property is defined, circuit breaker will be implicitly * enabled. */ @kotlin.Suppress("INAPPLICABLE_JVM_NAME") @JvmName("8c87126170e08060b1f7b1520c11123b02d7578e1e51565ba1e83c613514e971") public fun circuitBreaker(circuitBreaker: DeploymentCircuitBreaker.Builder.() -> Unit) /** * @param cloudMapOptions The options for configuring an Amazon ECS service to use service * discovery. */ public fun cloudMapOptions(cloudMapOptions: CloudMapOptions) /** * @param cloudMapOptions The options for configuring an Amazon ECS service to use service * discovery. */ @kotlin.Suppress("INAPPLICABLE_JVM_NAME") @JvmName("3c673de5d7b969ccb7f05067bf36991060f7b724063a5eac047a2aa6f4348ec0") public fun cloudMapOptions(cloudMapOptions: CloudMapOptions.Builder.() -> Unit) /** * @param cluster The name of the cluster that hosts the service. * If a cluster is specified, the vpc construct should be omitted. Alternatively, you can omit * both cluster and vpc. */ public fun cluster(cluster: ICluster) /** * @param cpu The number of cpu units used by the task. * Valid values, which determines your range of valid values for the memory parameter: * * 256 (.25 vCPU) - Available memory values: 0.5GB, 1GB, 2GB * * 512 (.5 vCPU) - Available memory values: 1GB, 2GB, 3GB, 4GB * * 1024 (1 vCPU) - Available memory values: 2GB, 3GB, 4GB, 5GB, 6GB, 7GB, 8GB * * 2048 (2 vCPU) - Available memory values: Between 4GB and 16GB in 1GB increments * * 4096 (4 vCPU) - Available memory values: Between 8GB and 30GB in 1GB increments * * 8192 (8 vCPU) - Available memory values: Between 16GB and 60GB in 4GB increments * * 16384 (16 vCPU) - Available memory values: Between 32GB and 120GB in 8GB increments * * This default is set in the underlying FargateTaskDefinition construct. */ public fun cpu(cpu: Number) /** * @param deploymentController Specifies which deployment controller to use for the service. * For more information, see * [Amazon ECS Deployment * Types](https://docs.aws.amazon.com/AmazonECS/latest/developerguide/deployment-types.html) */ public fun deploymentController(deploymentController: DeploymentController) /** * @param deploymentController Specifies which deployment controller to use for the service. * For more information, see * [Amazon ECS Deployment * Types](https://docs.aws.amazon.com/AmazonECS/latest/developerguide/deployment-types.html) */ @kotlin.Suppress("INAPPLICABLE_JVM_NAME") @JvmName("a9416e17ae45e3727f05946adc96a46aef340941eb4cefe974d42ee75e1ac504") public fun deploymentController(deploymentController: DeploymentController.Builder.() -> Unit) /** * @param desiredCount The desired number of instantiations of the task definition to keep * running on the service. * The minimum value is 1 */ public fun desiredCount(desiredCount: Number) /** * @param domainName The domain name for the service, e.g. "api.example.com.". */ public fun domainName(domainName: String) /** * @param domainZone The Route53 hosted zone for the domain, e.g. "example.com.". */ public fun domainZone(domainZone: IHostedZone) /** * @param enableEcsManagedTags Specifies whether to enable Amazon ECS managed tags for the tasks * within the service. * For more information, see * [Tagging Your Amazon ECS * Resources](https://docs.aws.amazon.com/AmazonECS/latest/developerguide/ecs-using-tags.html) */ public fun enableEcsManagedTags(enableEcsManagedTags: Boolean) /** * @param enableExecuteCommand Whether ECS Exec should be enabled. */ public fun enableExecuteCommand(enableExecuteCommand: Boolean) /** * @param ephemeralStorageGiB The amount (in GiB) of ephemeral storage to be allocated to the * task. * The minimum supported value is `21` GiB and the maximum supported value is `200` GiB. * * Only supported in Fargate platform version 1.4.0 or later. */ public fun ephemeralStorageGiB(ephemeralStorageGiB: Number) /** * @param healthCheckGracePeriod The period of time, in seconds, that the Amazon ECS service * scheduler ignores unhealthy Elastic Load Balancing target health checks after a task has first * started. */ public fun healthCheckGracePeriod(healthCheckGracePeriod: Duration) /** * @param ipAddressType The type of IP addresses to use. * If you want to add a UDP or TCP_UDP listener to the load balancer, * you must choose IPv4. */ public fun ipAddressType(ipAddressType: IpAddressType) /** * @param listenerPort Listener port of the network load balancer that will serve traffic to the * service. */ public fun listenerPort(listenerPort: Number) /** * @param loadBalancer The network load balancer that will serve traffic to the service. * If the load balancer has been imported, the vpc attribute must be specified * in the call to fromNetworkLoadBalancerAttributes(). * * [disable-awslint:ref-via-interface] */ public fun loadBalancer(loadBalancer: INetworkLoadBalancer) /** * @param maxHealthyPercent The maximum number of tasks, specified as a percentage of the Amazon * ECS service's DesiredCount value, that can run in a service during a deployment. */ public fun maxHealthyPercent(maxHealthyPercent: Number) /** * @param memoryLimitMiB The amount (in MiB) of memory used by the task. * This field is required and you must use one of the following values, which determines your * range of valid values * for the cpu parameter: * * 512 (0.5 GB), 1024 (1 GB), 2048 (2 GB) - Available cpu values: 256 (.25 vCPU) * * 1024 (1 GB), 2048 (2 GB), 3072 (3 GB), 4096 (4 GB) - Available cpu values: 512 (.5 vCPU) * * 2048 (2 GB), 3072 (3 GB), 4096 (4 GB), 5120 (5 GB), 6144 (6 GB), 7168 (7 GB), 8192 (8 GB) - * Available cpu values: 1024 (1 vCPU) * * Between 4096 (4 GB) and 16384 (16 GB) in increments of 1024 (1 GB) - Available cpu values: * 2048 (2 vCPU) * * Between 8192 (8 GB) and 30720 (30 GB) in increments of 1024 (1 GB) - Available cpu values: * 4096 (4 vCPU) * * Between 16384 (16 GB) and 61440 (60 GB) in increments of 4096 (4 GB) - Available cpu values: * 8192 (8 vCPU) * * Between 32768 (32 GB) and 122880 (120 GB) in increments of 8192 (8 GB) - Available cpu * values: 16384 (16 vCPU) * * This default is set in the underlying FargateTaskDefinition construct. */ public fun memoryLimitMiB(memoryLimitMiB: Number) /** * @param minHealthyPercent The minimum number of tasks, specified as a percentage of the Amazon * ECS service's DesiredCount value, that must continue to run and remain healthy during a * deployment. */ public fun minHealthyPercent(minHealthyPercent: Number) /** * @param platformVersion The platform version on which to run your service. * If one is not specified, the LATEST platform version is used by default. For more * information, see * [AWS Fargate Platform * Versions](https://docs.aws.amazon.com/AmazonECS/latest/developerguide/platform_versions.html) * in the Amazon Elastic Container Service Developer Guide. */ public fun platformVersion(platformVersion: FargatePlatformVersion) /** * @param propagateTags Specifies whether to propagate the tags from the task definition or the * service to the tasks in the service. * Tags can only be propagated to the tasks within the service during service creation. */ public fun propagateTags(propagateTags: PropagatedTagSource) /** * @param publicLoadBalancer Determines whether the Load Balancer will be internet-facing. */ public fun publicLoadBalancer(publicLoadBalancer: Boolean) /** * @param recordType Specifies whether the Route53 record should be a CNAME, an A record using * the Alias feature or no record at all. * This is useful if you need to work with DNS systems that do not support alias records. */ public fun recordType(recordType: NetworkLoadBalancedServiceRecordType) /** * @param runtimePlatform The runtime platform of the task definition. */ public fun runtimePlatform(runtimePlatform: RuntimePlatform) /** * @param runtimePlatform The runtime platform of the task definition. */ @kotlin.Suppress("INAPPLICABLE_JVM_NAME") @JvmName("3343dede43e22a7290d2529e00891542cc56d99ec80d51f818b846b200476b07") public fun runtimePlatform(runtimePlatform: RuntimePlatform.Builder.() -> Unit) /** * @param securityGroups The security groups to associate with the service. * If you do not specify a security group, a new security group is created. */ public fun securityGroups(securityGroups: List<ISecurityGroup>) /** * @param securityGroups The security groups to associate with the service. * If you do not specify a security group, a new security group is created. */ public fun securityGroups(vararg securityGroups: ISecurityGroup) /** * @param serviceName The name of the service. */ public fun serviceName(serviceName: String) /** * @param taskDefinition The task definition to use for tasks in the service. TaskDefinition or * TaskImageOptions must be specified, but not both. * [disable-awslint:ref-via-interface] */ public fun taskDefinition(taskDefinition: FargateTaskDefinition) /** * @param taskImageOptions The properties required to create a new task definition. * One of taskImageOptions or taskDefinition must be specified. */ public fun taskImageOptions(taskImageOptions: NetworkLoadBalancedTaskImageOptions) /** * @param taskImageOptions The properties required to create a new task definition. * One of taskImageOptions or taskDefinition must be specified. */ @kotlin.Suppress("INAPPLICABLE_JVM_NAME") @JvmName("14595e5312bec52c2db42c2cdd19048324cd311054dd81a9e90b3b178524833d") public fun taskImageOptions(taskImageOptions: NetworkLoadBalancedTaskImageOptions.Builder.() -> Unit) /** * @param taskSubnets The subnets to associate with the service. */ public fun taskSubnets(taskSubnets: SubnetSelection) /** * @param taskSubnets The subnets to associate with the service. */ @kotlin.Suppress("INAPPLICABLE_JVM_NAME") @JvmName("718ed021fa9e4945bea92d5ec5c86d38dbe222c78fe74771c70882e44e22456c") public fun taskSubnets(taskSubnets: SubnetSelection.Builder.() -> Unit) /** * @param vpc The VPC where the container instances will be launched or the elastic network * interfaces (ENIs) will be deployed. * If a vpc is specified, the cluster construct should be omitted. Alternatively, you can omit * both vpc and cluster. */ public fun vpc(vpc: IVpc) } private class BuilderImpl : Builder { private val cdkBuilder: software.amazon.awscdk.services.ecs.patterns.NetworkLoadBalancedFargateServiceProps.Builder = software.amazon.awscdk.services.ecs.patterns.NetworkLoadBalancedFargateServiceProps.builder() /** * @param assignPublicIp Determines whether the service will be assigned a public IP address. */ override fun assignPublicIp(assignPublicIp: Boolean) { cdkBuilder.assignPublicIp(assignPublicIp) } /** * @param capacityProviderStrategies A list of Capacity Provider strategies used to place a * service. */ override fun capacityProviderStrategies(capacityProviderStrategies: List<CapacityProviderStrategy>) { cdkBuilder.capacityProviderStrategies(capacityProviderStrategies.map(CapacityProviderStrategy.Companion::unwrap)) } /** * @param capacityProviderStrategies A list of Capacity Provider strategies used to place a * service. */ override fun capacityProviderStrategies(vararg capacityProviderStrategies: CapacityProviderStrategy): Unit = capacityProviderStrategies(capacityProviderStrategies.toList()) /** * @param circuitBreaker Whether to enable the deployment circuit breaker. * If this property is defined, circuit breaker will be implicitly * enabled. */ override fun circuitBreaker(circuitBreaker: DeploymentCircuitBreaker) { cdkBuilder.circuitBreaker(circuitBreaker.let(DeploymentCircuitBreaker.Companion::unwrap)) } /** * @param circuitBreaker Whether to enable the deployment circuit breaker. * If this property is defined, circuit breaker will be implicitly * enabled. */ @kotlin.Suppress("INAPPLICABLE_JVM_NAME") @JvmName("8c87126170e08060b1f7b1520c11123b02d7578e1e51565ba1e83c613514e971") override fun circuitBreaker(circuitBreaker: DeploymentCircuitBreaker.Builder.() -> Unit): Unit = circuitBreaker(DeploymentCircuitBreaker(circuitBreaker)) /** * @param cloudMapOptions The options for configuring an Amazon ECS service to use service * discovery. */ override fun cloudMapOptions(cloudMapOptions: CloudMapOptions) { cdkBuilder.cloudMapOptions(cloudMapOptions.let(CloudMapOptions.Companion::unwrap)) } /** * @param cloudMapOptions The options for configuring an Amazon ECS service to use service * discovery. */ @kotlin.Suppress("INAPPLICABLE_JVM_NAME") @JvmName("3c673de5d7b969ccb7f05067bf36991060f7b724063a5eac047a2aa6f4348ec0") override fun cloudMapOptions(cloudMapOptions: CloudMapOptions.Builder.() -> Unit): Unit = cloudMapOptions(CloudMapOptions(cloudMapOptions)) /** * @param cluster The name of the cluster that hosts the service. * If a cluster is specified, the vpc construct should be omitted. Alternatively, you can omit * both cluster and vpc. */ override fun cluster(cluster: ICluster) { cdkBuilder.cluster(cluster.let(ICluster.Companion::unwrap)) } /** * @param cpu The number of cpu units used by the task. * Valid values, which determines your range of valid values for the memory parameter: * * 256 (.25 vCPU) - Available memory values: 0.5GB, 1GB, 2GB * * 512 (.5 vCPU) - Available memory values: 1GB, 2GB, 3GB, 4GB * * 1024 (1 vCPU) - Available memory values: 2GB, 3GB, 4GB, 5GB, 6GB, 7GB, 8GB * * 2048 (2 vCPU) - Available memory values: Between 4GB and 16GB in 1GB increments * * 4096 (4 vCPU) - Available memory values: Between 8GB and 30GB in 1GB increments * * 8192 (8 vCPU) - Available memory values: Between 16GB and 60GB in 4GB increments * * 16384 (16 vCPU) - Available memory values: Between 32GB and 120GB in 8GB increments * * This default is set in the underlying FargateTaskDefinition construct. */ override fun cpu(cpu: Number) { cdkBuilder.cpu(cpu) } /** * @param deploymentController Specifies which deployment controller to use for the service. * For more information, see * [Amazon ECS Deployment * Types](https://docs.aws.amazon.com/AmazonECS/latest/developerguide/deployment-types.html) */ override fun deploymentController(deploymentController: DeploymentController) { cdkBuilder.deploymentController(deploymentController.let(DeploymentController.Companion::unwrap)) } /** * @param deploymentController Specifies which deployment controller to use for the service. * For more information, see * [Amazon ECS Deployment * Types](https://docs.aws.amazon.com/AmazonECS/latest/developerguide/deployment-types.html) */ @kotlin.Suppress("INAPPLICABLE_JVM_NAME") @JvmName("a9416e17ae45e3727f05946adc96a46aef340941eb4cefe974d42ee75e1ac504") override fun deploymentController(deploymentController: DeploymentController.Builder.() -> Unit): Unit = deploymentController(DeploymentController(deploymentController)) /** * @param desiredCount The desired number of instantiations of the task definition to keep * running on the service. * The minimum value is 1 */ override fun desiredCount(desiredCount: Number) { cdkBuilder.desiredCount(desiredCount) } /** * @param domainName The domain name for the service, e.g. "api.example.com.". */ override fun domainName(domainName: String) { cdkBuilder.domainName(domainName) } /** * @param domainZone The Route53 hosted zone for the domain, e.g. "example.com.". */ override fun domainZone(domainZone: IHostedZone) { cdkBuilder.domainZone(domainZone.let(IHostedZone.Companion::unwrap)) } /** * @param enableEcsManagedTags Specifies whether to enable Amazon ECS managed tags for the tasks * within the service. * For more information, see * [Tagging Your Amazon ECS * Resources](https://docs.aws.amazon.com/AmazonECS/latest/developerguide/ecs-using-tags.html) */ override fun enableEcsManagedTags(enableEcsManagedTags: Boolean) { cdkBuilder.enableEcsManagedTags(enableEcsManagedTags) } /** * @param enableExecuteCommand Whether ECS Exec should be enabled. */ override fun enableExecuteCommand(enableExecuteCommand: Boolean) { cdkBuilder.enableExecuteCommand(enableExecuteCommand) } /** * @param ephemeralStorageGiB The amount (in GiB) of ephemeral storage to be allocated to the * task. * The minimum supported value is `21` GiB and the maximum supported value is `200` GiB. * * Only supported in Fargate platform version 1.4.0 or later. */ override fun ephemeralStorageGiB(ephemeralStorageGiB: Number) { cdkBuilder.ephemeralStorageGiB(ephemeralStorageGiB) } /** * @param healthCheckGracePeriod The period of time, in seconds, that the Amazon ECS service * scheduler ignores unhealthy Elastic Load Balancing target health checks after a task has first * started. */ override fun healthCheckGracePeriod(healthCheckGracePeriod: Duration) { cdkBuilder.healthCheckGracePeriod(healthCheckGracePeriod.let(Duration.Companion::unwrap)) } /** * @param ipAddressType The type of IP addresses to use. * If you want to add a UDP or TCP_UDP listener to the load balancer, * you must choose IPv4. */ override fun ipAddressType(ipAddressType: IpAddressType) { cdkBuilder.ipAddressType(ipAddressType.let(IpAddressType.Companion::unwrap)) } /** * @param listenerPort Listener port of the network load balancer that will serve traffic to the * service. */ override fun listenerPort(listenerPort: Number) { cdkBuilder.listenerPort(listenerPort) } /** * @param loadBalancer The network load balancer that will serve traffic to the service. * If the load balancer has been imported, the vpc attribute must be specified * in the call to fromNetworkLoadBalancerAttributes(). * * [disable-awslint:ref-via-interface] */ override fun loadBalancer(loadBalancer: INetworkLoadBalancer) { cdkBuilder.loadBalancer(loadBalancer.let(INetworkLoadBalancer.Companion::unwrap)) } /** * @param maxHealthyPercent The maximum number of tasks, specified as a percentage of the Amazon * ECS service's DesiredCount value, that can run in a service during a deployment. */ override fun maxHealthyPercent(maxHealthyPercent: Number) { cdkBuilder.maxHealthyPercent(maxHealthyPercent) } /** * @param memoryLimitMiB The amount (in MiB) of memory used by the task. * This field is required and you must use one of the following values, which determines your * range of valid values * for the cpu parameter: * * 512 (0.5 GB), 1024 (1 GB), 2048 (2 GB) - Available cpu values: 256 (.25 vCPU) * * 1024 (1 GB), 2048 (2 GB), 3072 (3 GB), 4096 (4 GB) - Available cpu values: 512 (.5 vCPU) * * 2048 (2 GB), 3072 (3 GB), 4096 (4 GB), 5120 (5 GB), 6144 (6 GB), 7168 (7 GB), 8192 (8 GB) - * Available cpu values: 1024 (1 vCPU) * * Between 4096 (4 GB) and 16384 (16 GB) in increments of 1024 (1 GB) - Available cpu values: * 2048 (2 vCPU) * * Between 8192 (8 GB) and 30720 (30 GB) in increments of 1024 (1 GB) - Available cpu values: * 4096 (4 vCPU) * * Between 16384 (16 GB) and 61440 (60 GB) in increments of 4096 (4 GB) - Available cpu values: * 8192 (8 vCPU) * * Between 32768 (32 GB) and 122880 (120 GB) in increments of 8192 (8 GB) - Available cpu * values: 16384 (16 vCPU) * * This default is set in the underlying FargateTaskDefinition construct. */ override fun memoryLimitMiB(memoryLimitMiB: Number) { cdkBuilder.memoryLimitMiB(memoryLimitMiB) } /** * @param minHealthyPercent The minimum number of tasks, specified as a percentage of the Amazon * ECS service's DesiredCount value, that must continue to run and remain healthy during a * deployment. */ override fun minHealthyPercent(minHealthyPercent: Number) { cdkBuilder.minHealthyPercent(minHealthyPercent) } /** * @param platformVersion The platform version on which to run your service. * If one is not specified, the LATEST platform version is used by default. For more * information, see * [AWS Fargate Platform * Versions](https://docs.aws.amazon.com/AmazonECS/latest/developerguide/platform_versions.html) * in the Amazon Elastic Container Service Developer Guide. */ override fun platformVersion(platformVersion: FargatePlatformVersion) { cdkBuilder.platformVersion(platformVersion.let(FargatePlatformVersion.Companion::unwrap)) } /** * @param propagateTags Specifies whether to propagate the tags from the task definition or the * service to the tasks in the service. * Tags can only be propagated to the tasks within the service during service creation. */ override fun propagateTags(propagateTags: PropagatedTagSource) { cdkBuilder.propagateTags(propagateTags.let(PropagatedTagSource.Companion::unwrap)) } /** * @param publicLoadBalancer Determines whether the Load Balancer will be internet-facing. */ override fun publicLoadBalancer(publicLoadBalancer: Boolean) { cdkBuilder.publicLoadBalancer(publicLoadBalancer) } /** * @param recordType Specifies whether the Route53 record should be a CNAME, an A record using * the Alias feature or no record at all. * This is useful if you need to work with DNS systems that do not support alias records. */ override fun recordType(recordType: NetworkLoadBalancedServiceRecordType) { cdkBuilder.recordType(recordType.let(NetworkLoadBalancedServiceRecordType.Companion::unwrap)) } /** * @param runtimePlatform The runtime platform of the task definition. */ override fun runtimePlatform(runtimePlatform: RuntimePlatform) { cdkBuilder.runtimePlatform(runtimePlatform.let(RuntimePlatform.Companion::unwrap)) } /** * @param runtimePlatform The runtime platform of the task definition. */ @kotlin.Suppress("INAPPLICABLE_JVM_NAME") @JvmName("3343dede43e22a7290d2529e00891542cc56d99ec80d51f818b846b200476b07") override fun runtimePlatform(runtimePlatform: RuntimePlatform.Builder.() -> Unit): Unit = runtimePlatform(RuntimePlatform(runtimePlatform)) /** * @param securityGroups The security groups to associate with the service. * If you do not specify a security group, a new security group is created. */ override fun securityGroups(securityGroups: List<ISecurityGroup>) { cdkBuilder.securityGroups(securityGroups.map(ISecurityGroup.Companion::unwrap)) } /** * @param securityGroups The security groups to associate with the service. * If you do not specify a security group, a new security group is created. */ override fun securityGroups(vararg securityGroups: ISecurityGroup): Unit = securityGroups(securityGroups.toList()) /** * @param serviceName The name of the service. */ override fun serviceName(serviceName: String) { cdkBuilder.serviceName(serviceName) } /** * @param taskDefinition The task definition to use for tasks in the service. TaskDefinition or * TaskImageOptions must be specified, but not both. * [disable-awslint:ref-via-interface] */ override fun taskDefinition(taskDefinition: FargateTaskDefinition) { cdkBuilder.taskDefinition(taskDefinition.let(FargateTaskDefinition.Companion::unwrap)) } /** * @param taskImageOptions The properties required to create a new task definition. * One of taskImageOptions or taskDefinition must be specified. */ override fun taskImageOptions(taskImageOptions: NetworkLoadBalancedTaskImageOptions) { cdkBuilder.taskImageOptions(taskImageOptions.let(NetworkLoadBalancedTaskImageOptions.Companion::unwrap)) } /** * @param taskImageOptions The properties required to create a new task definition. * One of taskImageOptions or taskDefinition must be specified. */ @kotlin.Suppress("INAPPLICABLE_JVM_NAME") @JvmName("14595e5312bec52c2db42c2cdd19048324cd311054dd81a9e90b3b178524833d") override fun taskImageOptions(taskImageOptions: NetworkLoadBalancedTaskImageOptions.Builder.() -> Unit): Unit = taskImageOptions(NetworkLoadBalancedTaskImageOptions(taskImageOptions)) /** * @param taskSubnets The subnets to associate with the service. */ override fun taskSubnets(taskSubnets: SubnetSelection) { cdkBuilder.taskSubnets(taskSubnets.let(SubnetSelection.Companion::unwrap)) } /** * @param taskSubnets The subnets to associate with the service. */ @kotlin.Suppress("INAPPLICABLE_JVM_NAME") @JvmName("718ed021fa9e4945bea92d5ec5c86d38dbe222c78fe74771c70882e44e22456c") override fun taskSubnets(taskSubnets: SubnetSelection.Builder.() -> Unit): Unit = taskSubnets(SubnetSelection(taskSubnets)) /** * @param vpc The VPC where the container instances will be launched or the elastic network * interfaces (ENIs) will be deployed. * If a vpc is specified, the cluster construct should be omitted. Alternatively, you can omit * both vpc and cluster. */ override fun vpc(vpc: IVpc) { cdkBuilder.vpc(vpc.let(IVpc.Companion::unwrap)) } public fun build(): software.amazon.awscdk.services.ecs.patterns.NetworkLoadBalancedFargateServiceProps = cdkBuilder.build() } private class Wrapper( cdkObject: software.amazon.awscdk.services.ecs.patterns.NetworkLoadBalancedFargateServiceProps, ) : CdkObject(cdkObject), NetworkLoadBalancedFargateServiceProps { /** * Determines whether the service will be assigned a public IP address. * * Default: false */ override fun assignPublicIp(): Boolean? = unwrap(this).getAssignPublicIp() /** * A list of Capacity Provider strategies used to place a service. * * Default: - undefined */ override fun capacityProviderStrategies(): List<CapacityProviderStrategy> = unwrap(this).getCapacityProviderStrategies()?.map(CapacityProviderStrategy::wrap) ?: emptyList() /** * Whether to enable the deployment circuit breaker. * * If this property is defined, circuit breaker will be implicitly * enabled. * * Default: - disabled */ override fun circuitBreaker(): DeploymentCircuitBreaker? = unwrap(this).getCircuitBreaker()?.let(DeploymentCircuitBreaker::wrap) /** * The options for configuring an Amazon ECS service to use service discovery. * * Default: - AWS Cloud Map service discovery is not enabled. */ override fun cloudMapOptions(): CloudMapOptions? = unwrap(this).getCloudMapOptions()?.let(CloudMapOptions::wrap) /** * The name of the cluster that hosts the service. * * If a cluster is specified, the vpc construct should be omitted. Alternatively, you can omit * both cluster and vpc. * * Default: - create a new cluster; if both cluster and vpc are omitted, a new VPC will be * created for you. */ override fun cluster(): ICluster? = unwrap(this).getCluster()?.let(ICluster::wrap) /** * The number of cpu units used by the task. * * Valid values, which determines your range of valid values for the memory parameter: * * 256 (.25 vCPU) - Available memory values: 0.5GB, 1GB, 2GB * * 512 (.5 vCPU) - Available memory values: 1GB, 2GB, 3GB, 4GB * * 1024 (1 vCPU) - Available memory values: 2GB, 3GB, 4GB, 5GB, 6GB, 7GB, 8GB * * 2048 (2 vCPU) - Available memory values: Between 4GB and 16GB in 1GB increments * * 4096 (4 vCPU) - Available memory values: Between 8GB and 30GB in 1GB increments * * 8192 (8 vCPU) - Available memory values: Between 16GB and 60GB in 4GB increments * * 16384 (16 vCPU) - Available memory values: Between 32GB and 120GB in 8GB increments * * This default is set in the underlying FargateTaskDefinition construct. * * Default: 256 */ override fun cpu(): Number? = unwrap(this).getCpu() /** * Specifies which deployment controller to use for the service. * * For more information, see * [Amazon ECS Deployment * Types](https://docs.aws.amazon.com/AmazonECS/latest/developerguide/deployment-types.html) * * Default: - Rolling update (ECS) */ override fun deploymentController(): DeploymentController? = unwrap(this).getDeploymentController()?.let(DeploymentController::wrap) /** * The desired number of instantiations of the task definition to keep running on the service. * * The minimum value is 1 * * Default: - The default is 1 for all new services and uses the existing service's desired * count * when updating an existing service. */ override fun desiredCount(): Number? = unwrap(this).getDesiredCount() /** * The domain name for the service, e.g. "api.example.com.". * * Default: - No domain name. */ override fun domainName(): String? = unwrap(this).getDomainName() /** * The Route53 hosted zone for the domain, e.g. "example.com.". * * Default: - No Route53 hosted domain zone. */ override fun domainZone(): IHostedZone? = unwrap(this).getDomainZone()?.let(IHostedZone::wrap) /** * Specifies whether to enable Amazon ECS managed tags for the tasks within the service. * * For more information, see * [Tagging Your Amazon ECS * Resources](https://docs.aws.amazon.com/AmazonECS/latest/developerguide/ecs-using-tags.html) * * Default: false */ override fun enableECSManagedTags(): Boolean? = unwrap(this).getEnableECSManagedTags() /** * Whether ECS Exec should be enabled. * * Default: - false */ override fun enableExecuteCommand(): Boolean? = unwrap(this).getEnableExecuteCommand() /** * The amount (in GiB) of ephemeral storage to be allocated to the task. * * The minimum supported value is `21` GiB and the maximum supported value is `200` GiB. * * Only supported in Fargate platform version 1.4.0 or later. * * Default: Undefined, in which case, the task will receive 20GiB ephemeral storage. */ override fun ephemeralStorageGiB(): Number? = unwrap(this).getEphemeralStorageGiB() /** * The period of time, in seconds, that the Amazon ECS service scheduler ignores unhealthy * Elastic Load Balancing target health checks after a task has first started. * * Default: - defaults to 60 seconds if at least one load balancer is in-use and it is not * already set */ override fun healthCheckGracePeriod(): Duration? = unwrap(this).getHealthCheckGracePeriod()?.let(Duration::wrap) /** * The type of IP addresses to use. * * If you want to add a UDP or TCP_UDP listener to the load balancer, * you must choose IPv4. * * Default: IpAddressType.IPV4 * * [Documentation](https://docs.aws.amazon.com/elasticloadbalancing/latest/network/load-balancer-ip-address-type.html) */ override fun ipAddressType(): IpAddressType? = unwrap(this).getIpAddressType()?.let(IpAddressType::wrap) /** * Listener port of the network load balancer that will serve traffic to the service. * * Default: 80 */ override fun listenerPort(): Number? = unwrap(this).getListenerPort() /** * The network load balancer that will serve traffic to the service. * * If the load balancer has been imported, the vpc attribute must be specified * in the call to fromNetworkLoadBalancerAttributes(). * * [disable-awslint:ref-via-interface] * * Default: - a new load balancer will be created. */ override fun loadBalancer(): INetworkLoadBalancer? = unwrap(this).getLoadBalancer()?.let(INetworkLoadBalancer::wrap) /** * The maximum number of tasks, specified as a percentage of the Amazon ECS service's * DesiredCount value, that can run in a service during a deployment. * * Default: - 100 if daemon, otherwise 200 */ override fun maxHealthyPercent(): Number? = unwrap(this).getMaxHealthyPercent() /** * The amount (in MiB) of memory used by the task. * * This field is required and you must use one of the following values, which determines your * range of valid values * for the cpu parameter: * * 512 (0.5 GB), 1024 (1 GB), 2048 (2 GB) - Available cpu values: 256 (.25 vCPU) * * 1024 (1 GB), 2048 (2 GB), 3072 (3 GB), 4096 (4 GB) - Available cpu values: 512 (.5 vCPU) * * 2048 (2 GB), 3072 (3 GB), 4096 (4 GB), 5120 (5 GB), 6144 (6 GB), 7168 (7 GB), 8192 (8 GB) - * Available cpu values: 1024 (1 vCPU) * * Between 4096 (4 GB) and 16384 (16 GB) in increments of 1024 (1 GB) - Available cpu values: * 2048 (2 vCPU) * * Between 8192 (8 GB) and 30720 (30 GB) in increments of 1024 (1 GB) - Available cpu values: * 4096 (4 vCPU) * * Between 16384 (16 GB) and 61440 (60 GB) in increments of 4096 (4 GB) - Available cpu values: * 8192 (8 vCPU) * * Between 32768 (32 GB) and 122880 (120 GB) in increments of 8192 (8 GB) - Available cpu * values: 16384 (16 vCPU) * * This default is set in the underlying FargateTaskDefinition construct. * * Default: 512 */ override fun memoryLimitMiB(): Number? = unwrap(this).getMemoryLimitMiB() /** * The minimum number of tasks, specified as a percentage of the Amazon ECS service's * DesiredCount value, that must continue to run and remain healthy during a deployment. * * Default: - 0 if daemon, otherwise 50 */ override fun minHealthyPercent(): Number? = unwrap(this).getMinHealthyPercent() /** * The platform version on which to run your service. * * If one is not specified, the LATEST platform version is used by default. For more * information, see * [AWS Fargate Platform * Versions](https://docs.aws.amazon.com/AmazonECS/latest/developerguide/platform_versions.html) * in the Amazon Elastic Container Service Developer Guide. * * Default: Latest */ override fun platformVersion(): FargatePlatformVersion? = unwrap(this).getPlatformVersion()?.let(FargatePlatformVersion::wrap) /** * Specifies whether to propagate the tags from the task definition or the service to the tasks * in the service. * * Tags can only be propagated to the tasks within the service during service creation. * * Default: - none */ override fun propagateTags(): PropagatedTagSource? = unwrap(this).getPropagateTags()?.let(PropagatedTagSource::wrap) /** * Determines whether the Load Balancer will be internet-facing. * * Default: true */ override fun publicLoadBalancer(): Boolean? = unwrap(this).getPublicLoadBalancer() /** * Specifies whether the Route53 record should be a CNAME, an A record using the Alias feature * or no record at all. * * This is useful if you need to work with DNS systems that do not support alias records. * * Default: NetworkLoadBalancedServiceRecordType.ALIAS */ override fun recordType(): NetworkLoadBalancedServiceRecordType? = unwrap(this).getRecordType()?.let(NetworkLoadBalancedServiceRecordType::wrap) /** * The runtime platform of the task definition. * * Default: - If the property is undefined, `operatingSystemFamily` is LINUX and * `cpuArchitecture` is X86_64 */ override fun runtimePlatform(): RuntimePlatform? = unwrap(this).getRuntimePlatform()?.let(RuntimePlatform::wrap) /** * The security groups to associate with the service. * * If you do not specify a security group, a new security group is created. * * Default: - A new security group is created. */ override fun securityGroups(): List<ISecurityGroup> = unwrap(this).getSecurityGroups()?.map(ISecurityGroup::wrap) ?: emptyList() /** * The name of the service. * * Default: - CloudFormation-generated name. */ override fun serviceName(): String? = unwrap(this).getServiceName() /** * The task definition to use for tasks in the service. TaskDefinition or TaskImageOptions must * be specified, but not both. * * [disable-awslint:ref-via-interface] * * Default: - none */ override fun taskDefinition(): FargateTaskDefinition? = unwrap(this).getTaskDefinition()?.let(FargateTaskDefinition::wrap) /** * The properties required to create a new task definition. * * One of taskImageOptions or taskDefinition must be specified. * * Default: - none */ override fun taskImageOptions(): NetworkLoadBalancedTaskImageOptions? = unwrap(this).getTaskImageOptions()?.let(NetworkLoadBalancedTaskImageOptions::wrap) /** * The subnets to associate with the service. * * Default: - Public subnets if `assignPublicIp` is set, otherwise the first available one of * Private, Isolated, Public, in that order. */ override fun taskSubnets(): SubnetSelection? = unwrap(this).getTaskSubnets()?.let(SubnetSelection::wrap) /** * The VPC where the container instances will be launched or the elastic network interfaces * (ENIs) will be deployed. * * If a vpc is specified, the cluster construct should be omitted. Alternatively, you can omit * both vpc and cluster. * * Default: - uses the VPC defined in the cluster or creates a new VPC. */ override fun vpc(): IVpc? = unwrap(this).getVpc()?.let(IVpc::wrap) } public companion object { public operator fun invoke(block: Builder.() -> Unit = {}): NetworkLoadBalancedFargateServiceProps { val builderImpl = BuilderImpl() return Wrapper(builderImpl.apply(block).build()) } internal fun wrap(cdkObject: software.amazon.awscdk.services.ecs.patterns.NetworkLoadBalancedFargateServiceProps): NetworkLoadBalancedFargateServiceProps = CdkObjectWrappers.wrap(cdkObject) as? NetworkLoadBalancedFargateServiceProps ?: Wrapper(cdkObject) internal fun unwrap(wrapped: NetworkLoadBalancedFargateServiceProps): software.amazon.awscdk.services.ecs.patterns.NetworkLoadBalancedFargateServiceProps = (wrapped as CdkObject).cdkObject as software.amazon.awscdk.services.ecs.patterns.NetworkLoadBalancedFargateServiceProps } }
4
Kotlin
0
4
eb3eef728b34da593a3e55dc423d4f5fa3668e9c
44,571
kotlin-cdk-wrapper
Apache License 2.0
app/src/main/java/com/suellen/colangelo/notes/domain/usecase/GetNoteUseCase.kt
SuellenAc
638,717,392
false
null
package com.suellen.colangelo.notes.domain.usecase import com.suellen.colangelo.notes.domain.NoteRepository import com.suellen.colangelo.notes.domain.model.Note import javax.inject.Inject interface GetNoteUseCase { suspend operator fun invoke(id: String): Note? } class GetNoteUseCaseImpl @Inject constructor( private val repository: NoteRepository ) : GetNoteUseCase { override suspend fun invoke(id: String): Note? = repository.getNote(id) }
0
Kotlin
0
0
833eb14624f71e634fcdbda618c95a6a0246fa48
466
SimpleNotesApp
Apache License 2.0
app/src/main/java/org/myspecialway/ui/login/GeneralErrorDialog.kt
myspecialway
133,219,843
false
null
package org.myspecialway.ui.login import android.app.Activity import android.app.AlertDialog import android.content.Context import android.support.v4.app.Fragment import android.view.LayoutInflater import android.view.View import android.widget.TextView import kotlinx.android.synthetic.main.login_dialog_error.view.* import org.myspecialway.R import org.myspecialway.common.BaseDialog class GeneralErrorDialog(context: Context) : BaseDialog() { override val dialogView: View by lazy { LayoutInflater.from(context).inflate(R.layout.general_error_dialog, null) } val content: TextView by lazy { dialogView.findViewById<TextView>(R.id.content) } override val builder: AlertDialog.Builder = AlertDialog.Builder(context).setView(dialogView) fun closeButtonClickListener(func: (() -> Unit)? = null) = with(dialogView.closeButton) { setClickListenerToDialogIcon(func) } private fun View.setClickListenerToDialogIcon(func: (() -> Unit)?) = setOnClickListener { func?.invoke() } } inline fun Activity.showGeneralErrorDialog(func: GeneralErrorDialog.() -> Unit): Unit = GeneralErrorDialog(this).apply { func() }.create().show() inline fun Fragment.showGeneralErrorDialog(func: GeneralErrorDialog.() -> Unit): AlertDialog = GeneralErrorDialog(this.context!!).apply { func() }.create()
20
null
6
3
9914c25016a1fb19b535c8fe47a1642f791b5d44
1,463
my-special-way-android
MIT License
src/Day02.kt
Svikleren
572,637,234
false
null
fun main() { val valuesForPart1 = mapOf( Pair("AX", 4), Pair("AY", 8), Pair("AZ", 3), Pair("BX", 1), Pair("BY", 5), Pair("BZ", 9), Pair("CX", 7), Pair("CY", 2), Pair("CZ", 6), ) val valuesForPart2 = mapOf( Pair("AX", 3), Pair("AY", 4), Pair("AZ", 8), Pair("BX", 1), Pair("BY", 5), Pair("BZ", 9), Pair("CX", 2), Pair("CY", 6), Pair("CZ", 7), ) fun compareChars(firstPlayer: String, secondPlayer: String, values: Map<String, Int>): Int { return values.get(firstPlayer + secondPlayer)?.or(0) ?: 0 } fun countOneRound(oneRound: List<String>, values: Map<String, Int>): Int { val firstPlayer = oneRound.get(0) val secondPlayer = oneRound.get(1) return compareChars(firstPlayer, secondPlayer, values) } fun countAllRounds(input: List<String>, values: Map<String, Int>): Int { var totalSum = 0 for (oneInput: String in input) { totalSum += countOneRound(oneInput.split(" "), values) } return totalSum } fun part1(input: List<String>): Int { return countAllRounds(input, valuesForPart1) } fun part2(input: List<String>): Int { return countAllRounds(input, valuesForPart2) } val input = readInput("Day02") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
e63be3f83b96a73543bf9bc00c22dc71b6aa0f57
1,455
advent-of-code-2022
Apache License 2.0
kotlin-mui-icons/src/main/generated/mui/icons/material/LocalMovies.kt
JetBrains
93,250,841
false
null
// Automatically generated - do not modify! @file:JsModule("@mui/icons-material/LocalMovies") package mui.icons.material @JsName("default") external val LocalMovies: SvgIconComponent
10
null
5
983
7ef1028ba3e0982dc93edcdfa6ee1edb334ddf35
186
kotlin-wrappers
Apache License 2.0
app/shared-common/src/commonMain/kotlin/com/gmail/jiangyang5157/shared/common/data/dlx/DlxNode.kt
jiangyang5157
553,993,370
false
null
package com.gmail.jiangyang5157.shared.common.data.dlx open class DlxNode( var up: DlxNode? = null, var down: DlxNode? = null, var left: DlxNode? = null, var right: DlxNode? = null, ) { override fun equals(other: Any?): Boolean { if (this === other) return true if (other !is DlxNode) return false if (this.up != other.up) return false if (this.down != other.down) return false if (this.left != other.left) return false if (this.right != other.right) return false return true } override fun hashCode(): Int { var hashCode = 31 hashCode += 31 * this.up.hashCode() hashCode += 31 * this.down.hashCode() hashCode += 31 * this.left.hashCode() hashCode += 31 * this.right.hashCode() return hashCode } } inline fun <reified T : DlxNode> DlxNode.up(): T? = up as? T inline fun <reified T : DlxNode> DlxNode.down(): T? = down as? T inline fun <reified T : DlxNode> DlxNode.left(): T? = left as? T inline fun <reified T : DlxNode> DlxNode.right(): T? = right as? T
0
Kotlin
0
0
e514a86bbe149504508cc2ee23bf21c0984d3f48
1,095
kotlin-multiplatform-mobile
MIT License
source/app/src/main/java/com/apion/apionhome/base/BindingFragmentPickImage.kt
viet06061999
471,421,323
true
{"Kotlin": 161735, "Java": 51216}
package com.apion.apionhome.base import android.app.Activity import android.content.Intent import androidx.activity.result.ActivityResult import androidx.viewbinding.ViewBinding import com.apion.apionhome.utils.getRealPath abstract class BindingFragmentPickImage<T : ViewBinding> (inflate: Inflate<T>) : BindingFragment<T>(inflate) { override fun onPermissionResult(permissions: MutableMap<String, Boolean>) { super.onPermissionResult(permissions) if (hasPermission(android.Manifest.permission.READ_EXTERNAL_STORAGE)) { pickImage() } } override fun onActivityResult(result: ActivityResult) { super.onActivityResult(result) if (result.resultCode == Activity.RESULT_OK) { val images = mutableListOf<String>() val data = result.data if (data?.clipData != null) { val count = data.clipData?.itemCount ?: 0 for (i in 0 until count) { val imageUri = data.clipData?.getItemAt(i)?.uri images.add(imageUri?.getRealPath(requireContext()) ?: "") } } else { val imageUri = data?.data images.add(imageUri?.getRealPath(requireContext()) ?: "") } if (images.isNotEmpty()) { println(images) onImagesSelect(images) } } } abstract fun onImagesSelect(images: List<String>) fun pickImageSafety() { if (hasPermission(android.Manifest.permission.READ_EXTERNAL_STORAGE)) { pickImage() } else { requestPermissionsSafely(arrayListOf(android.Manifest.permission.READ_EXTERNAL_STORAGE)) } } fun pickImage() { val intent = Intent() intent.type = "image/*" intent.putExtra(Intent.EXTRA_ALLOW_MULTIPLE, true) intent.action = Intent.ACTION_GET_CONTENT startActivityForResultSafely(Intent.createChooser(intent, "Chọn ảnh")) } }
0
null
0
0
24ddb088ffd985dcd34e3e8deeb5edcc1d717558
2,028
apion_home
Apache License 2.0
app/src/main/java/com/gdurmaz/mvvmmvipractice/data/remote/interfaces/api/ProductCatalogApiHelperImpl.kt
GokhanDurmaz
483,927,833
false
null
package com.gdurmaz.mvvmmvipractice.data.remote.interfaces.api import retrofit2.Response import javax.inject.Inject /** * Created by gokhan on 4/21/22. */ class ProductCatalogApiHelperImpl @Inject constructor( private val productCatalogApiService: ProductCatalogApiService ) : ProductCatalogApiHelper { override suspend fun getCatalogData(body: String, contentType: String): Response<Any> = productCatalogApiService.getCatalogData(contentType) override suspend fun getCatalogDetailData(body: String, contentType: String): Response<Any> = productCatalogApiService.getCatalogDetailData(contentType) }
0
Kotlin
0
0
0c54f2e9c93cbe853877d3e05c5d752e1675527f
632
MVVM_MVI_Practice
Apache License 2.0
rpc_min3/src/main/kotlin/org/kethereum/rpc/min3/model/IN3Node.kt
komputing
92,780,266
false
{"Kotlin": 776856}
package org.kethereum.rpc.min3.model import com.squareup.moshi.JsonClass @JsonClass(generateAdapter = true) data class IN3Node( val url: String, val address: String, val index: Int, val deposit: String, val props: String, val timeout: Int, val registerTime: Int, val weight: Int )
43
Kotlin
82
333
1f42cede2d31cb5d3c488bd74eeb8480ec47c919
346
KEthereum
MIT License
library/src/commonMain/kotlin/us/q3q/fidok/ctap/commands/LargeBlobKeyExtension.kt
BryanJacobs
684,573,020
false
{"Kotlin": 780971}
package us.q3q.fidok.ctap.commands import us.q3q.fidok.crypto.KeyAgreementPlatformKey import us.q3q.fidok.crypto.PinUVProtocol /** * Allows for getting a key to store/retrieve authenticator "large blobs" * * Requires no parameters; on each [makeCredential][us.q3q.fidok.ctap.CTAPClient.makeCredential] * or [getAssertion][us.q3q.fidok.ctap.CTAPClient.getAssertions] operation, will retrieve the * corresponding `largeBlobKey` if available. * * Note that each call to [getKey] removes one accumulated entry, and entries are added by * (and shared between) both `makeCredential` and `getAssertion`. * * @sample largeBlobKeyExample */ class LargeBlobKeyExtension : Extension { private val NAME = "largeBlobKey" init { ExtensionSetup.register(NAME) } private var largeBlobKeys: ArrayDeque<ByteArray?> = ArrayDeque() fun getKey(): ByteArray? = largeBlobKeys.removeFirst() override fun getName(): ExtensionName { return NAME } override fun makeCredential(keyAgreement: KeyAgreementPlatformKey?, pinUVProtocol: PinUVProtocol?): ExtensionParameters? { return BooleanExtensionParameter(true) } override fun makeCredentialResponse(response: MakeCredentialResponse) { // Note: doesn't come from extension results per se largeBlobKeys.addLast(response.largeBlobKey) } override fun getAssertion(keyAgreement: KeyAgreementPlatformKey?, pinUVProtocol: PinUVProtocol?): ExtensionParameters { return BooleanExtensionParameter(true) } override fun getAssertionResponse(response: GetAssertionResponse) { largeBlobKeys.addLast(response.largeBlobKey) } override fun checkSupport(info: GetInfoResponse): Boolean { if (!super.checkSupport(info)) { return false } if (info.options?.contains("largeBlobs") != true) { // largeBlobKey requires largeBlobs option return false } return true } } internal fun largeBlobKeyExample() { val client = Examples.getCTAPClient() val largeBlobKeyExtension = LargeBlobKeyExtension() val credential = client.makeCredential( rpId = "some.neat.example", extensions = ExtensionSetup(listOf(largeBlobKeyExtension)), ) val largeBlobKey = largeBlobKeyExtension.getKey() }
0
Kotlin
1
9
459274c1808bd5d733757c371e927f6d806ab7bb
2,337
FIDOk
MIT License
src/com/payam/learn/solid/srp/IEmailContent.kt
payamfaryadras
250,200,722
false
{"Kotlin": 2166, "Dockerfile": 113}
package com.payam.learn.solid.srp interface IEmailContent
2
Kotlin
0
0
851e7135f5eb46e5be6b758c1d9b53f8e70f89ae
60
SOLID-Principles
MIT License
native/native.tests/testData/klib/dump-metadata/data_class.kt
JetBrains
3,432,266
false
null
// FIR_IDENTICAL // MUTED_WHEN: K1 package test data class DataClass( val intProp: Int, val stringProp: String ) { val nonConstructorProp: Int = 0 } data object DataObject
181
null
5748
49,172
33eb9cef3d146062c103f9853d772f0a1da0450e
185
kotlin
Apache License 2.0
app/src/main/java/com/oliverspryn/android/oauthbiometrics/model/StartViewModel.kt
oliverspryn
468,386,599
false
{"Kotlin": 116365}
package com.oliverspryn.android.oauthbiometrics.model import androidx.fragment.app.FragmentActivity import androidx.lifecycle.ViewModel import androidx.lifecycle.viewModelScope import com.oliverspryn.android.oauthbiometrics.di.factories.RxJavaFactory import com.oliverspryn.android.oauthbiometrics.domain.exceptions.cryptography.UnableToDecryptData import com.oliverspryn.android.oauthbiometrics.domain.exceptions.cryptography.UnableToInitializeCipher import com.oliverspryn.android.oauthbiometrics.domain.exceptions.storage.UnableToDecodePersistentAuthState import com.oliverspryn.android.oauthbiometrics.domain.usecases.biometrics.BiometricResult import com.oliverspryn.android.oauthbiometrics.domain.usecases.biometrics.CreateBiometricPromptInfoToPerformBiometricLoginUseCase import com.oliverspryn.android.oauthbiometrics.domain.usecases.biometrics.ObtainStrongestAvailableAuthenticationTypeForCryptographyUseCase import com.oliverspryn.android.oauthbiometrics.domain.usecases.biometrics.PresentBiometricPromptForCipherUseCase import com.oliverspryn.android.oauthbiometrics.domain.usecases.biometrics.StrongestAvailableAuthenticationTypeForCryptography import com.oliverspryn.android.oauthbiometrics.domain.usecases.oauth.InitializeOAuthLoginFlowUseCase import com.oliverspryn.android.oauthbiometrics.domain.usecases.oauth.LaunchOAuthLoginFlowUseCase import com.oliverspryn.android.oauthbiometrics.domain.usecases.storage.GetPersistentAuthStateUseCase import com.oliverspryn.android.oauthbiometrics.domain.usecases.storage.HasBiometricLoginEnabledUseCase import com.oliverspryn.android.oauthbiometrics.domain.usecases.storage.LogoutUseCase import com.oliverspryn.android.oauthbiometrics.utils.AuthStateManager import com.oliverspryn.android.oauthbiometrics.utils.security.CryptographyManager import com.oliverspryn.android.oauthbiometrics.utils.security.EncryptedData import dagger.hilt.android.lifecycle.HiltViewModel import io.reactivex.rxjava3.core.Observable import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.SharingStarted import kotlinx.coroutines.flow.stateIn import kotlinx.coroutines.flow.update import net.openid.appauth.AuthorizationRequest import javax.inject.Inject @HiltViewModel class StartViewModel @Inject constructor( private val authStateManager: AuthStateManager, private val createBiometricPromptInfoToPerformBiometricLoginUseCase: CreateBiometricPromptInfoToPerformBiometricLoginUseCase, private val cryptographyManager: CryptographyManager, private val getPersistentAuthStateUseCase: GetPersistentAuthStateUseCase, private val hasBiometricLoginEnabledUseCase: HasBiometricLoginEnabledUseCase, private val initializeOAuthLoginFlowUseCase: InitializeOAuthLoginFlowUseCase, private val launchOAuthLoginFlowUseCase: LaunchOAuthLoginFlowUseCase, private val logoutUseCase: LogoutUseCase, private val presentBiometricPromptForCipherUseCase: PresentBiometricPromptForCipherUseCase, private val rxJavaFactory: RxJavaFactory, private val strongestAvailableAuthenticationTypeUseCase: ObtainStrongestAvailableAuthenticationTypeForCryptographyUseCase ) : ViewModel() { private var authRequest: AuthorizationRequest? = null private val viewModelState = MutableStateFlow(StartUiState()) val uiState = viewModelState .stateIn( viewModelScope, SharingStarted.Eagerly, StartUiState() ) init { initializeOAuthLoginFlow() updateBiometricLoginButton() } fun dismissBiometricLockoutRationalePrompt() { viewModelState.update { it.copy( showBiometricLockoutRationalePrompt = false ) } } fun dismissWebLoginRationalePrompt() { viewModelState.update { it.copy( showWebLoginRationalePrompt = false ) } } fun doBiometricLogin(activity: FragmentActivity, onLoginSuccess: () -> Unit) { getPersistentAuthStateUseCase() .subscribeOn(rxJavaFactory.io) .observeOn(rxJavaFactory.ui) .flatMapObservable { encryptedData -> val cipher = cryptographyManager.getInitializedCipherForDecryption(encryptedData.iv) val promptInfo = createBiometricPromptInfoToPerformBiometricLoginUseCase() presentBiometricPromptForCipherUseCase( activity = activity, promptInfo = promptInfo, cipher = cipher ).flatMap { biometricResult -> Observable.just( BiometricLoginPayload( biometricResult = biometricResult, encryptedData = encryptedData ) ) } } .observeOn(rxJavaFactory.io) .flatMap { biometricLoginPayload -> if (biometricLoginPayload.biometricResult is BiometricResult.Success) { val cipher = biometricLoginPayload.biometricResult.result.cryptoObject?.cipher ?: return@flatMap Observable.error(UnableToInitializeCipher()) val authStateCipherText = biometricLoginPayload.encryptedData.cipherText val authStatePlainText = cryptographyManager.decryptData(authStateCipherText, cipher) authStateManager.serializedAuthState = authStatePlainText } Observable.just(biometricLoginPayload.biometricResult) } .observeOn(rxJavaFactory.ui) .subscribe({ // Can react here for something like a successful or bad fingerprint // Not yet a terminating condition }, { error -> val isBiometricError = error is BiometricResult.Error && error.isBiometricLockout val isCipherError = error is UnableToDecryptData || error is UnableToInitializeCipher val isDecodeError = error is UnableToDecodePersistentAuthState if (isBiometricError) { disableBiometricLoginButton() showBiometricLockoutRationalePrompt() } else if (isCipherError || isDecodeError) { disableBiometricLoginButton() doLogout() showWebLoginRationalePrompt() } }, { onLoginSuccess() }) } fun doWebLogin() { authRequest?.let { request -> launchOAuthLoginFlowUseCase(request) } } fun updateBiometricLoginButton() { val biometricsAvailableFromSystem = strongestAvailableAuthenticationTypeUseCase() is StrongestAvailableAuthenticationTypeForCryptography.Available hasBiometricLoginEnabledUseCase() .subscribeOn(rxJavaFactory.io) .observeOn(rxJavaFactory.ui) .subscribe({ appBiometricLoginEnabled -> viewModelState.update { it.copy( isBiometricLoginEnabled = biometricsAvailableFromSystem && appBiometricLoginEnabled ) } }, { doLogout() // In case biometrics were previously available, user logged in, then removed biometrics viewModelState.update { it.copy( isBiometricLoginEnabled = false ) } }) } private fun disableBiometricLoginButton() { viewModelState.update { it.copy(isBiometricLoginEnabled = false) } } private fun disableWebLoginButton() { viewModelState.update { it.copy( isWebLoginEnabled = false ) } } private fun doLogout() { logoutUseCase(false) .subscribeOn(rxJavaFactory.io) .observeOn(rxJavaFactory.ui) .subscribe({ // Best effort }, { // Ignore the outcomes :) }) } private fun enableWebLoginButton() { viewModelState.update { it.copy( isWebLoginEnabled = true ) } } private fun initializeOAuthLoginFlow() { initializeOAuthLoginFlowUseCase() .subscribeOn(rxJavaFactory.io) .doOnSubscribe { disableWebLoginButton() setIsLoading() } .doOnSuccess { enableWebLoginButton() setIsLoadingComplete() } .doOnError { enableWebLoginButton() setIsLoadingComplete() } .subscribe({ authRequest = it }, { }) } private fun setIsLoading() { viewModelState.update { it.copy( isLoading = true ) } } private fun setIsLoadingComplete() { viewModelState.update { it.copy( isLoading = false ) } } private fun showBiometricLockoutRationalePrompt() { viewModelState.update { it.copy( showBiometricLockoutRationalePrompt = true ) } } private fun showWebLoginRationalePrompt() { viewModelState.update { it.copy( showWebLoginRationalePrompt = true ) } } } data class StartUiState( val isBiometricLoginEnabled: Boolean = false, val isLoading: Boolean = true, val isWebLoginEnabled: Boolean = false, val showBiometricLockoutRationalePrompt: Boolean = false, val showWebLoginRationalePrompt: Boolean = false ) private data class BiometricLoginPayload( val biometricResult: BiometricResult, val encryptedData: EncryptedData )
0
Kotlin
0
2
b7a1da9b4260122fca64d7141653deb7f794e250
10,070
android-oauth-biometrics
MIT License