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/org/wcode/sentency/ui/theme/Font.kt
wcode-software
383,625,732
false
null
package org.wcode.sentency.ui.theme import androidx.compose.ui.text.font.Font import androidx.compose.ui.text.font.FontFamily import org.wcode.sentency.R object Fonts { val sacramentoFamily = FontFamily( Font(R.font.sacramento_regular) ) }
0
Kotlin
0
0
1f4c38719bbe6f54a01140c74b056f03c9a97d8a
257
sentency-android
MIT License
src/test/kotlin/com/codeperfection/shipit/service/shipping/ShippingManagementServiceTest.kt
codeperfection
730,719,882
false
{"Kotlin": 106653, "Dockerfile": 567}
package com.codeperfection.shipit.service.shipping import com.codeperfection.shipit.dto.common.PageDto import com.codeperfection.shipit.dto.common.PaginationFilterDto import com.codeperfection.shipit.dto.shipping.ShippingDto import com.codeperfection.shipit.exception.clienterror.NotFoundException import com.codeperfection.shipit.fixture.SHIPPING_ID import com.codeperfection.shipit.fixture.USER_ID import com.codeperfection.shipit.fixture.createShippingFixture import com.codeperfection.shipit.fixture.shippingDtoFixture import com.codeperfection.shipit.repository.ShippingRepository import com.codeperfection.shipit.service.AuthorizationService import org.assertj.core.api.Assertions.assertThat import org.junit.jupiter.api.AfterEach import org.junit.jupiter.api.Test import org.junit.jupiter.api.assertThrows import org.junit.jupiter.api.extension.ExtendWith import org.mockito.InjectMocks import org.mockito.Mock import org.mockito.junit.jupiter.MockitoExtension import org.mockito.kotlin.verify import org.mockito.kotlin.verifyNoMoreInteractions import org.mockito.kotlin.whenever import org.springframework.data.domain.PageImpl import org.springframework.data.domain.PageRequest import org.springframework.data.domain.Sort @ExtendWith(MockitoExtension::class) class ShippingManagementServiceTest { @Mock private lateinit var shippingRepository: ShippingRepository @Mock private lateinit var authorizationService: AuthorizationService @InjectMocks private lateinit var underTest: ShippingManagementService @AfterEach fun tearDown() { verifyNoMoreInteractions(shippingRepository, authorizationService) } private val shippingFixture = createShippingFixture() @Test fun `GIVEN pagination filter, WHEN getting empty shippings, THEN an empty shippings page is returned`() { val pageRequest = PageRequest.of(0, 100, Sort.by("createdAt")) whenever(shippingRepository.findByUserId(USER_ID, pageRequest)).thenReturn(PageImpl(emptyList())) val shippingsPage = underTest.getShippings(USER_ID, PaginationFilterDto()) assertThat(shippingsPage).isEqualTo( PageDto<ShippingDto>( totalElements = 0, totalPages = 1, elements = emptyList() ) ) verify(authorizationService).checkReadAccess(USER_ID) verify(shippingRepository).findByUserId(USER_ID, pageRequest) } @Test fun `GIVEN pagination filter, WHEN getting shippings, THEN shippings page is returned`() { val pageRequest = PageRequest.of(0, 100, Sort.by("createdAt")) whenever(shippingRepository.findByUserId(USER_ID, pageRequest)).thenReturn(PageImpl(listOf(shippingFixture))) val shippingsPage = underTest.getShippings(USER_ID, PaginationFilterDto()) assertThat(shippingsPage).isEqualTo( PageDto(totalElements = 1, totalPages = 1, elements = listOf(shippingDtoFixture)) ) verify(authorizationService).checkReadAccess(USER_ID) verify(shippingRepository).findByUserId(USER_ID, pageRequest) } @Test fun `GIVEN shipping with id and user id doesn't exist, WHEN getting shipping, THEN exception is thrown`() { whenever(shippingRepository.findByIdAndUserId(SHIPPING_ID, USER_ID)).thenReturn(null) assertThrows<NotFoundException> { underTest.getShipping(USER_ID, SHIPPING_ID) } verify(authorizationService).checkReadAccess(USER_ID) verify(shippingRepository).findByIdAndUserId(SHIPPING_ID, USER_ID) } @Test fun `GIVEN shipping with id and user id exists, WHEN getting shipping, THEN it is returned`() { whenever(shippingRepository.findByIdAndUserId(SHIPPING_ID, USER_ID)).thenReturn(shippingFixture) val shippingDto = underTest.getShipping(USER_ID, SHIPPING_ID) assertThat(shippingDto).isEqualTo(shippingDtoFixture) verify(authorizationService).checkReadAccess(USER_ID) verify(shippingRepository).findByIdAndUserId(SHIPPING_ID, USER_ID) } @Test fun `GIVEN shipping with id and user id doesn't exist, WHEN deleting shipping, THEN exception is thrown`() { whenever(shippingRepository.findByIdAndUserId(SHIPPING_ID, USER_ID)).thenReturn(null) assertThrows<NotFoundException> { underTest.deleteShipping(USER_ID, SHIPPING_ID) } verify(authorizationService).checkWriteAccess(USER_ID) verify(shippingRepository).findByIdAndUserId(SHIPPING_ID, USER_ID) } @Test fun `GIVEN shipping with id and user id exists, WHEN deleting shipping, THEN it is deleted`() { whenever(shippingRepository.findByIdAndUserId(SHIPPING_ID, USER_ID)).thenReturn(shippingFixture) underTest.deleteShipping(USER_ID, SHIPPING_ID) verify(authorizationService).checkWriteAccess(USER_ID) verify(shippingRepository).findByIdAndUserId(SHIPPING_ID, USER_ID) verify(shippingRepository).delete(shippingFixture) } }
0
Kotlin
0
0
fbc1dc3aed31cf83d40fff3f988ca53b4033e0ac
5,032
ship-it
MIT License
identity-flow/src/main/java/com/android/identity/flow/client/FlowNotifiable.kt
openwallet-foundation-labs
248,844,077
false
{"Kotlin": 4132186, "Java": 591756, "JavaScript": 33071, "Swift": 28030, "HTML": 12029, "Shell": 372, "CSS": 200, "C": 104}
package com.android.identity.flow.client import kotlinx.coroutines.flow.SharedFlow interface FlowNotifiable<NotificationT>: FlowBase { val notifications: SharedFlow<NotificationT> }
99
Kotlin
83
163
e6bf25766985521b9a39d4ed7999f22d57064db5
187
identity-credential
Apache License 2.0
dsl/src/main/kotlin/com/faendir/awscdkkt/generated/services/stepfunctions/tasks/MonitoringDsl.kt
F43nd1r
643,016,506
false
null
package com.faendir.awscdkkt.generated.services.stepfunctions.tasks import com.faendir.awscdkkt.AwsCdkDsl import javax.`annotation`.Generated import kotlin.Unit import software.amazon.awscdk.services.stepfunctions.tasks.Monitoring @Generated public fun buildMonitoring(initializer: @AwsCdkDsl Monitoring.Builder.() -> Unit): Monitoring = Monitoring.Builder().apply(initializer).build()
1
Kotlin
0
0
a1cf8fbfdfef9550b3936de2f864543edb76348b
392
aws-cdk-kt
Apache License 2.0
composeApp/src/commonMain/kotlin/ui/home/transcripts/TranscriptsScreenModel.kt
abdallahmehiz
830,308,163
false
{"Kotlin": 449026, "Swift": 621}
package ui.home.transcripts import cafe.adriel.voyager.core.model.ScreenModel import cafe.adriel.voyager.core.model.screenModelScope import kotlinx.collections.immutable.ImmutableMap import kotlinx.collections.immutable.toImmutableMap import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.IO import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.asStateFlow import kotlinx.coroutines.flow.update import kotlinx.coroutines.launch import mehiz.abdallah.progres.domain.TranscriptUseCase import mehiz.abdallah.progres.domain.models.AcademicDecisionModel import mehiz.abdallah.progres.domain.models.TranscriptModel import presentation.utils.RequestState class TranscriptsScreenModel( private val transcriptUseCase: TranscriptUseCase, ) : ScreenModel { private val _transcripts = MutableStateFlow<RequestState<ImmutableMap<String, Pair<AcademicDecisionModel?, List<TranscriptModel>>>>>( RequestState.Loading, ) val transcripts = _transcripts.asStateFlow() private val _isRefreshing = MutableStateFlow(false) val isRefreshing = _isRefreshing.asStateFlow() init { screenModelScope.launch(Dispatchers.IO) { _transcripts.update { _ -> try { RequestState.Success(getData(false)) } catch (e: Exception) { RequestState.Error(e) } } } } suspend fun refresh() { _transcripts.update { RequestState.Success(getData(true)) } } private suspend fun getData(refresh: Boolean): ImmutableMap<String, Pair<AcademicDecisionModel?, List<TranscriptModel>>> { val decisions = transcriptUseCase.getAllAcademicDecisions(refresh, refresh).sortedBy { it.id } val transcripts = transcriptUseCase.getAllTranscripts(refresh, false).sortedBy { it.id } val decisionsByYear = decisions.groupBy { it.period.academicYearCode } val transcriptsByYear = transcripts.groupBy { it.period.academicYearCode } return transcriptsByYear.mapValues { (year, yearTranscripts) -> val decisionForYear = decisionsByYear[year]?.firstOrNull() Pair(decisionForYear, yearTranscripts) }.toImmutableMap() } }
1
Kotlin
0
8
331d3c6c8caa126fdc7df033f2574cd3aa8f8e80
2,135
progres
MIT License
src/test/kotlin/com/github/suhininalex/codefinder/leveldb/KeyValueIndexTest.kt
suhininalex
130,993,598
false
null
package com.github.suhininalex.codefinder.leveldb import org.assertj.core.api.Assertions.assertThat import org.fusesource.leveldbjni.JniDBFactory.factory import org.iq80.leveldb.Options import org.junit.After import org.junit.Before import org.junit.Test import java.io.File class KeyValueIndexTest { private val pathToDb = File("src/test/data/leveldb") private val tablePrefix = 0x01 private fun useTestIndex(body:(KeyValueIndex<Int, String>)->Unit){ val db = factory.open(pathToDb, Options()) val index = KeyValueIndex(db, tablePrefix, IntExternalizer, StringExternalizer) body(index) db.close() } @Before fun setUp(){ useTestIndex { index -> entriesDB.forEach { entry -> index.put(entry.key, entry.value) } } } @After fun cleanUp(){ factory.destroy(pathToDb, Options()) } private val entriesDB = listOf( Entry(3, "three"), Entry(4, "four") ) @Test fun `test put get chain`() { useTestIndex { index -> assertThat(index.get(3)).isEqualTo("three") assertThat(index.contains(3)).isTrue() assertThat(index.get(0)).isNull() assertThat(index.contains(0)).isFalse() val extractedEntries = index.useEntries { it.toList() } assertThat(entriesDB).isEqualTo(extractedEntries) } } @Test fun `test remove`() { useTestIndex { index -> index.remove(3) assertThat(index.contains(4)).isTrue() assertThat(index.contains(3)).isFalse() } } }
0
Kotlin
0
0
3db164d2145817c7ef8106b65a8d437ba0aa1b69
1,657
CodeFinder
MIT License
5 Architecture components/GuessTheWord-Starter/app/src/main/java/com/example/android/guesstheword/screens/game/GameFragment.kt
Android-SrA-2020
232,581,619
false
null
/* * Copyright (C) 2019 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.example.android.guesstheword.screens.game import android.hardware.camera2.TotalCaptureResult import android.os.Bundle import android.util.Log import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.Toast import androidx.databinding.DataBindingUtil import androidx.fragment.app.Fragment import androidx.lifecycle.Observer import androidx.lifecycle.ViewModelProvider import androidx.navigation.fragment.NavHostFragment import com.example.android.guesstheword.R import com.example.android.guesstheword.databinding.GameFragmentBinding /** * Fragment where the game is played */ class GameFragment : Fragment() { //REF to game fragment so we can access methods in props in it private lateinit var viewModel: GameViewModel; private lateinit var binding: GameFragmentBinding override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? { //YOU CAN USE EXTENSION METHOD INSTEAD OF VIEW MODEL PROVIDER //val viewModel by viewModels<GameViewModel>() - needs add gradle dependency //INIT VIEW MODEL viewModel = ViewModelProvider(this).get(GameViewModel::class.java) // Inflate view and obtain an instance of the binding class binding = DataBindingUtil.inflate( inflater, R.layout.game_fragment, container, false ) //Pass value of viewModel to binding data to xml view binding.gameViewModelVar = viewModel; // Specify the fragment view as the lifecycle owner of the binding. // This is used so that the binding can observe LiveData updates binding.lifecycleOwner = viewLifecycleOwner //ATTACH OBSERVERS TO OBSERVABLE // viewModel.score.observe(viewLifecycleOwner, Observer { newScore -> // binding.scoreText.text = newScore.toString(); // // }) // viewModel.word.observe(viewLifecycleOwner, Observer { word -> // binding.wordText.text = word; // }) //Observer that will move to the score if no more questions left viewModel.eventGameFinished.observe(viewLifecycleOwner, Observer<Boolean> { gameIsNotPlaying -> if (gameIsNotPlaying) gameFinished(); }) //AFTER ATTACHING BINDING LISTENERS WE NO LONGER NEED THIS BINDINGS // binding.correctButton.setOnClickListener { onCorrect() } // binding.skipButton.setOnClickListener { onSkip() } // binding.endGameButton.setOnClickListener { onEndGame() } return binding.root } /** Methods for buttons presses **/ // private fun onSkip() { // viewModel.onSkip() // } // private fun onCorrect() { // viewModel.onCorrect() // } // // private fun onEndGame() { // // gameFinished(); // } /** * Moves to the next word in the list */ /** Methods for updating the UI **/ private fun gameFinished() { Toast.makeText(activity, "Game has just finished", Toast.LENGTH_SHORT).show(); val action = GameFragmentDirections.actionGameToScore(); //Add arguments to action to pass to view action.score = viewModel.score.value ?: 0; NavHostFragment.findNavController(this).navigate(action); viewModel.onGameFinishedComplete() } }
0
Kotlin
0
0
3485b68bb943613f1642c351d31762a9f6baa39f
4,053
homework-romanplkh
MIT License
src/main/kotlin/com/panzersoft/antiaircraft/visual/Aircraft.kt
pinkjersey
96,307,437
false
null
package com.panzersoft.antiaircraft.visual import com.panzersoft.antiaircraft.GameParameters.aircraftSpeed import com.panzersoft.antiaircraft.GameParameters.makeAircraft import com.panzersoft.antiaircraft.GameParameters.realHeight import com.panzersoft.antiaircraft.models.Aircraft import com.panzersoft.antiaircraft.visual.GameObject import java.awt.Color import java.awt.Graphics /** * Created by mdozturk on 7/4/17. */ class Aircraft() : GameObject() { internal var model = makeAircraft() override fun paintComponent(g: Graphics) { g.color = Color.BLACK val p = model.location.toPoint() g.fillRect(p.x, p.y, 6, 6) } /** * @param elapsedTime time elapsed in milliseconds */ override fun move(elapsedTime: Long) { model.move(elapsedTime) } }
0
Kotlin
0
0
14a94988e3a2452eb7abcf7e1c528935a9839d01
815
antiaircraft
MIT License
zycle/src/main/java/com/coenvk/android/zycle/adapter/observer/AdapterDataObserver.kt
coenvk
250,287,306
false
null
package com.coenvk.android.zycle.adapter.observer abstract class AdapterDataObserver { open fun onChanged() = Unit open fun onItemRangeChanged(positionStart: Int, itemCount: Int) = Unit open fun onItemRangeChanged(positionStart: Int, itemCount: Int, payload: Any?) = onItemRangeChanged(positionStart, itemCount) open fun onItemRangeInserted(positionStart: Int, itemCount: Int) = Unit open fun onItemRangeRemoved(positionStart: Int, itemCount: Int) = Unit open fun onItemRangeMoved(fromPosition: Int, toPosition: Int, itemCount: Int) = Unit }
0
null
0
1
413f03793295eaeeddf42c44697affe04ad442a8
577
zycle
Apache License 2.0
TeamCode/src/main/java/org/firstinspires/ftc/teamcode/TeleOpMode.kt
titanium-knights
228,481,344
false
{"Gradle": 7, "INI": 2, "Shell": 1, "Ignore List": 1, "Batchfile": 1, "Markdown": 7, "HTML": 387, "CSS": 2, "JavaScript": 1, "Text": 6, "YAML": 2, "XML": 19, "Java": 57, "Kotlin": 27}
package org.firstinspires.ftc.teamcode import com.qualcomm.robotcore.eventloop.opmode.TeleOp import com.qualcomm.robotcore.util.ElapsedTime import io.github.titanium_knights.stunning_waddle.* import org.firstinspires.ftc.robotcore.external.navigation.DistanceUnit import org.firstinspires.ftc.teamcode.movement.Arm import org.firstinspires.ftc.teamcode.movement.FoundationClamps import org.firstinspires.ftc.teamcode.movement.Grabber import org.firstinspires.ftc.teamcode.movement.MecanumDrive import org.firstinspires.ftc.teamcode.sensors.StandardSensors import org.firstinspires.ftc.teamcode.util.Vector2D import org.firstinspires.ftc.teamcode.util.plusAssign import org.firstinspires.ftc.teamcode.util.rem import kotlin.math.max /* Gamepad 1: LEFT STICK - Move & strafe RIGHT STICK - Turn LEFT BUMPER - Clamps down RIGHT BUMPER - Clamps up Gamepad 2: LEFT STICK - Arm up/down RIGHT STICK - Arm left/right LEFT BUMPER - Grabber down RIGHT BUMPER - Grabber up Y - Bypass software limits DPAD DOWN - Auto down */ @TeleOp(name = "Tele Op Mode (final)", group = "* Main") class TeleOpMode: EventOpMode({ val drive = MecanumDrive.standard(hardwareMap) val clamps = FoundationClamps.standard(hardwareMap) val grabber = Grabber.standard(hardwareMap) val arm = Arm.standard(hardwareMap) val sensors = StandardSensors(hardwareMap) val armDistance = sensors.armDistanceSensor val armTouch = sensors.armTouchSensor val elapsedTime = ElapsedTime() var armMode = ArmState.MANUAL var armModeStartTime = elapsedTime.milliseconds() fun setArmMode(newMode: ArmState) { if (armMode == newMode) { armMode = ArmState.MANUAL } else { armMode = newMode armModeStartTime = elapsedTime.milliseconds() } } var bypass = false registerLoopHook { bypass = gamepad1.y || gamepad2.y } var isSlow = false registerLoopHook { val vector = Vector2D(gamepad1.left_stick_x.toDouble(), -gamepad1.left_stick_y.toDouble()) val turn = gamepad1.right_stick_x.toDouble() val power = if (isSlow) 0.3 else 1.0 drive.move(power, vector, turn * power, MecanumDrive.TurnBehavior.ADDSUBTRACT) telemetry += "=== DRIVE ===" telemetry += "(%.2f, %.2f) @ %.2f, Turn = %.2f" % arrayOf(vector.x, vector.y, power, turn) telemetry += "" } doWhen(gamepad1::x.pressed) { isSlow = true } doWhen(gamepad1::b.pressed) { isSlow = false } doWhen( makeButton(gamepad1::left_bumper).pushed then { clamps.moveDown() }, makeButton(gamepad1::right_bumper).pushed then { clamps.moveUp() } ) doWhen( makeButton(gamepad2::left_bumper).pushed then { grabber.grab() }, makeButton(gamepad2::right_bumper).pushed then { grabber.lift() } ) doWhen( makeButton(gamepad2::dpad_down).pushed then { setArmMode(ArmState.MOVE_DOWN) }, makeButton(gamepad2::dpad_up).pushed then { setArmMode(ArmState.MOVE_UP) }, makeButton(gamepad2::dpad_right).pushed then { setArmMode(ArmState.MOVE_TO_TOUCH_SENSOR) } ) registerLoopHook { if (elapsedTime.milliseconds() - armModeStartTime > 3 || gamepad2.left_stick_y > 0 || gamepad2.right_stick_x > 0) { armMode = ArmState.MANUAL } if (when (armMode) { ArmState.MOVE_DOWN -> armDistance.getDistance(DistanceUnit.INCH) < 4.2 ArmState.MOVE_UP -> armDistance.getDistance(DistanceUnit.INCH) > 6.5 ArmState.MOVE_TO_TOUCH_SENSOR -> armTouch.isPressed else -> true }) { armMode = ArmState.MANUAL } val horizontal = when (armMode) { ArmState.MOVE_TO_TOUCH_SENSOR -> 0.65 else -> gamepad2.right_stick_x.toDouble() } val vertical = when (armMode) { ArmState.MOVE_UP -> 0.8 ArmState.MOVE_DOWN -> -1.0 else -> { if (!bypass && armDistance.getDistance(DistanceUnit.INCH) < 4.2) { max(0.0, -gamepad2.left_stick_y.toDouble()) } else { -gamepad2.left_stick_y.toDouble() } } } arm.setPowers(horizontal, vertical) telemetry += "=== ARM ===" telemetry += "Mode: ${when (armMode) { ArmState.MOVE_UP -> "Auto Up" ArmState.MOVE_DOWN -> "Auto Down" ArmState.MOVE_TO_TOUCH_SENSOR -> "Auto Right" ArmState.MANUAL -> "Manual" }}" telemetry += "" telemetry += "Horizontal: %.2f" % arrayOf(horizontal) telemetry += "Vertical: %.2f" % arrayOf(vertical) telemetry += "" telemetry += if (armTouch.isPressed) "โ€ข Arm" else " Arm" telemetry += "(%06.2f in)" % arrayOf(armDistance.getDistance(DistanceUnit.INCH)) telemetry += " Floor " } }) { enum class ArmState { MANUAL, MOVE_DOWN, MOVE_UP, MOVE_TO_TOUCH_SENSOR } }
1
null
1
1
9bdb373baa0e61f9d18660d4aeaa1c56dd1201d5
5,080
team-a-2019-2020
MIT License
common/src/watchMain/kotlin/com/surrus/common/repository/actual.kt
mvarnagiris
307,750,812
true
{"Kotlin": 32295, "Swift": 16184, "Ruby": 2200, "HTML": 366}
package com.surrus.common.repository import com.squareup.sqldelight.drivers.native.NativeSqliteDriver import com.surrus.peopleinspace.db.PeopleInSpaceDatabase import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.GlobalScope import kotlinx.coroutines.launch actual fun createDb(): PeopleInSpaceDatabase? { val driver = NativeSqliteDriver(PeopleInSpaceDatabase.Schema, "peopleinspace.db") return PeopleInSpaceDatabase(driver) }
0
null
0
0
6888c40356dc811e49d4f8275eb15b8021d81b5f
448
PeopleInSpace
Apache License 2.0
gradle-plugin/src/main/kotlin/io/github/nickacpt/patchify/gradle/PatchifyGradlePlugin.kt
NickAcPT
287,130,022
false
null
package io.github.nickacpt.patchify.gradle import io.github.nickacpt.patchify.gradle.extension.PatchifyExtension import org.gradle.api.Plugin import org.gradle.api.Project class PatchifyGradlePlugin : Plugin<Project> { override fun apply(target: Project) { val patchifyExtension = target.extensions.create("patchify", PatchifyExtension::class.java).apply { project = target } target.afterEvaluate { p -> patchifyExtension.buildWorkspaces() PatchifyGradle.initialize(p) } } }
0
Kotlin
0
5
b9753014e7b553bcbee9a596dedc321aa0409f49
534
Patchify
MIT License
lib/basic/src/main/java/com/dinesh/basic/formatting/CurrencyInputWatcher.kt
Dinesh2811
745,880,179
false
{"Kotlin": 1200547, "Java": 206284, "JavaScript": 20260}
package com.dinesh.basic.formatting import android.text.Editable import android.text.InputType import android.text.TextWatcher import android.widget.EditText import android.widget.TextView import java.math.BigDecimal import java.math.RoundingMode import java.text.DecimalFormat import java.text.DecimalFormatSymbols import java.text.NumberFormat import java.util.Currency import java.util.Locale private val localeCurrencyFormat = Locale.US class CurrencyInputWatcher(private val editText: EditText, private val afterTextChangedAction: (String, BigDecimal) -> Unit) : TextWatcher { private val formatter = NumberFormat.getCurrencyInstance(localeCurrencyFormat) private val maxAmount = BigDecimal(1000000) init { (formatter as? java.text.DecimalFormat)?.apply { currency = Currency.getInstance(localeCurrencyFormat) maximumFractionDigits = 2 minimumFractionDigits = 2 } editText.inputType = InputType.TYPE_CLASS_NUMBER or InputType.TYPE_NUMBER_FLAG_DECIMAL } override fun afterTextChanged(editable: Editable) { val amountWithPrefix = editable.toString().replace(Regex("[^0-9]"), "") var doubleValue = amountWithPrefix.toDoubleOrNull() ?: 0.0 var number = BigDecimal(doubleValue / 100) if (number > maxAmount) { number = maxAmount } val formattedValue = formatter.format(number) editText.removeTextChangedListener(this) editText.setText(formattedValue) editText.setSelection(formattedValue.length) editText.addTextChangedListener(this) afterTextChangedAction(formattedValue, editText.getNumericCurrencyValue()) } override fun beforeTextChanged(charSequence: CharSequence, start: Int, count: Int, after: Int) {} override fun onTextChanged(charSequence: CharSequence, start: Int, before: Int, count: Int) {} } fun TextView.getNumericCurrencyValue(setScale: Int = 2): BigDecimal { val amountWithPrefix = text.toString() val cleanedAmount = amountWithPrefix.replace(Regex("[^0-9]"), "") val doubleValue = cleanedAmount.toDoubleOrNull() ?: 0.0 return BigDecimal(doubleValue / 100).setScale(setScale, RoundingMode.HALF_UP) } fun currencyFormat(amount: String): String { return try { val number = amount.toDouble() val formatter = DecimalFormat("###,###,##0.00", DecimalFormatSymbols.getInstance(localeCurrencyFormat)) formatter.format(number) } catch (e: Exception) { e.printStackTrace() "0.00" } }
0
Kotlin
0
1
d5b4b55728848196c71c351c186df7e57ad4e8c2
2,564
Android101
Apache License 2.0
ktor/client/src/commonMain/kotlin/dev/inmo/micro_utils/ktor/client/BodyOrNull.kt
InsanusMokrassar
295,712,640
false
null
package dev.inmo.micro_utils.ktor.client import io.ktor.client.call.body import io.ktor.client.statement.HttpResponse import io.ktor.http.HttpStatusCode suspend inline fun <reified T : Any> HttpResponse.bodyOrNull() = takeIf { status == HttpStatusCode.OK } ?.body<T>()
6
Kotlin
0
19
551d8ec480b477d8ed064ee18b4d6b014860a1f1
275
MicroUtils
Apache License 2.0
karibu-dsl-v10/src/test/kotlin/com/github/mvysny/karibudsl/v10/HtmlTest.kt
tcbuddy
203,060,835
true
{"Kotlin": 478202, "HTML": 14434, "CSS": 3191, "JavaScript": 463}
package com.github.mvysny.karibudsl.v10 import com.github.mvysny.dynatest.DynaTest import com.github.mvysny.kaributesting.v10.MockVaadin import com.vaadin.flow.component.UI class HtmlTest : DynaTest({ beforeEach { MockVaadin.setup() } afterEach { MockVaadin.tearDown() } test("smoke test") { UI.getCurrent()!!.apply { div() h1() h2() h3() h4() h5() h6() hr() p() em() span() anchor() image() label() input() nativeButton() strong() } } })
0
Kotlin
0
0
2ed5de1c779e56ad3fdbf363de7c29d8bfbfd974
677
karibu-dsl
MIT License
src/me/anno/video/MissingFrameException.kt
AntonioNoack
266,471,164
false
null
package me.anno.video import me.anno.io.files.FileReference import me.anno.objects.Transform import java.io.File class MissingFrameException(msg: String) : RuntimeException(msg) { constructor(src: FileReference?) : this(src.toString()) constructor(src: Transform) : this(toString(src)) constructor(src: File) : this(src.toString()) companion object { fun toString(src: Transform): String { val str = src.toString() return str.ifEmpty { src.className } } } }
0
Kotlin
1
8
e5f0bb17202552fa26c87c230e31fa44cd3dd5c6
520
RemsStudio
Apache License 2.0
app/src/main/java/jp/co/yumemi/dynamictextsample/data/RepositoryModule.kt
Seo-4d696b75
661,718,129
false
null
package jp.co.yumemi.dynamictextsample.data import dagger.Binds import dagger.Module import dagger.hilt.InstallIn import dagger.hilt.components.SingletonComponent import jp.co.yumemi.dynamictextsample.domain.DisplayLanguageRepository import javax.inject.Singleton @Module @InstallIn(SingletonComponent::class) interface RepositoryModule { @Binds @Singleton fun bindDisplayLanguageManager(impl: DisplayLanguageRepositoryImpl): DisplayLanguageRepository }
0
Kotlin
0
0
6801b2a6319b4e5b1b29bbf0c6fb1e8975a51ca8
468
dynamic-text-compose
MIT License
kotlin-get-started/src/main/kotlin/reflection/util.kt
kochetkov-ma
284,747,386
false
null
package reflection fun main() { val l644: Double = 1.00 + 4.00 + 1.84 + 5.48 + 1.58 val l854: Double = 1.00 + 1.60 + 3.14 + 6.22 + 4.39 + 6.40 println("ะŸัƒั‚ัŒ ะดะพ 644: $l644") println("ะŸัƒั‚ัŒ ะดะพ 854: $l854") println("854 / 644:" + (l854 / l644)) println("644 / 854:" + (l644 / l854)) }
0
Kotlin
2
7
cf6a49bc5d18ac0c690a508d048f7a246b41087d
307
pump-samples
Apache License 2.0
app/src/main/java/com/klim/koinsample/ui/home/mappers/PostEntity_PostView_Map.kt
makstron
349,967,030
false
{"Gradle": 3, "Java Properties": 2, "Shell": 1, "Text": 1, "Ignore List": 3, "Batchfile": 1, "Markdown": 1, "JSON": 1, "Proguard": 1, "Kotlin": 30, "XML": 31, "Java": 1}
package com.klim.koinsample.ui.home.mappers import com.klim.koinsample.domain.entity.PostEntity import com.klim.koinsample.ui.home.PostView fun List<PostEntity>.mapToPostView(): List<PostView> { return this.map { it.map() } } fun PostEntity.map(): PostView { return PostView( id = this.id, title = this.title, body = this.body, ) }
0
Kotlin
0
0
86493f318e76f0f9a3d177f66fcb57937aafe934
370
KoinSample
Apache License 2.0
app/src/test/java/studio/mandysa/music/ExcludeJavaTest.kt
ZXHHYJ
575,649,635
false
null
package studio.mandysa.music import org.junit.Test import java.io.File import java.io.FileReader import java.util.* class DisablePackageImport { @Test fun checkup() { val path = "${System.getProperty("user.dir")}\\src\\main\\java\\studio\\mandysa\\music" exclude(path, "androidx.compose.material3.Text") } private fun exclude(path: String, key: String) { val regex = "(.*)${key}(.*)".toRegex() val file = File(path) val fs = file.listFiles() for (f in fs!!) { if (f.isDirectory) { exclude(f.path, key) continue } Scanner(FileReader(f)).use { sc -> while (sc.hasNextLine()) { val line = sc.nextLine() if (line.matches(regex)) { throw RuntimeException("${f}ๅญ˜ๅœจ${key}") } } } } } }
0
Kotlin
0
2
db3678f535f249ee16aeceedb7a7eb9331cfdf71
953
MandySa-Music
Apache License 2.0
multisrc/overrides/madara/mangaowlus/src/MangaOwlUs.kt
kevin01523
612,636,298
false
null
package eu.kanade.tachiyomi.extension.en.mangaowlus import eu.kanade.tachiyomi.multisrc.madara.Madara class MangaOwlUs : Madara("MangaOwl.us (unoriginal)", "https://mangaowl.us", "en") { override val useNewChapterEndpoint = true override fun searchPage(page: Int): String = if (page == 1) "" else "page/$page/" }
9
null
99
9
8ca7f06a4fdfbfdd66520a4798c8636274263428
324
tachiyomi-extensions
Apache License 2.0
Corona-Warn-App/src/test/java/de/rki/coronawarnapp/worker/DiagnosisKeyRetrievalTimeCalculatorTest.kt
pocmo
271,262,274
true
{"Kotlin": 774972, "HTML": 159992}
package de.sj4.coronapartyapp.worker import org.hamcrest.CoreMatchers.`is` import org.hamcrest.MatcherAssert.assertThat import org.hamcrest.Matchers.greaterThanOrEqualTo import org.hamcrest.Matchers.lessThanOrEqualTo import org.hamcrest.core.IsEqual.equalTo import org.joda.time.DateTime import org.junit.Test class DiagnosisKeyRetrievalTimeCalculatorTest { @Test fun getDatetimeRangeForDelayInWindow() { val timeNow = DateTime() .withHourOfDay(8) .withMinuteOfHour(0) .withSecondOfMinute(0) val timeNowPlusMaxDelay = timeNow.plusMinutes(BackgroundConstants.DIAGNOSIS_KEY_RETRIEVAL_MAX_DELAY) val result = DiagnosisKeyRetrievalTimeCalculator.getPossibleSchedulingTimes(timeNow) val todayMidnight = DateTime().withTimeAtStartOfDay() val windowMin = todayMidnight.plusMinutes(BackgroundConstants.TIME_RANGE_MIN) val windowMax = todayMidnight.plusMinutes(BackgroundConstants.TIME_RANGE_MAX) assertThat(result.first, `is`(equalTo(timeNow))) assertThat(result.second, `is`(equalTo(timeNowPlusMaxDelay))) assertThat(result.first, `is`(greaterThanOrEqualTo(windowMin))) assertThat(result.second, `is`(lessThanOrEqualTo(windowMax))) } @Test fun getDatetimeRangeForDelayInWindowStartTimeBeforeWindow() { val timeNow = DateTime() .withHourOfDay(5) .withMinuteOfHour(20) .withSecondOfMinute(0) val result = DiagnosisKeyRetrievalTimeCalculator.getPossibleSchedulingTimes(timeNow) val todayMidnight = DateTime().withTimeAtStartOfDay() val windowMin = todayMidnight.plusMinutes(BackgroundConstants.TIME_RANGE_MIN) val windowMinPlusTimeRangeMax = windowMin.plusMinutes(BackgroundConstants.DIAGNOSIS_KEY_RETRIEVAL_MAX_DELAY) assertThat(result.first, `is`(equalTo(windowMin))) assertThat(result.second, `is`(lessThanOrEqualTo(windowMinPlusTimeRangeMax))) } @Test fun getDatetimeRangeForDelayInWindowEndimeAfterWindow() { val timeNow = DateTime() .withHourOfDay(23) .withMinuteOfHour(20) .withSecondOfMinute(0) val result = DiagnosisKeyRetrievalTimeCalculator.getPossibleSchedulingTimes(timeNow) val todayMidnight = DateTime().withTimeAtStartOfDay() val windowMax = todayMidnight.plusMinutes(BackgroundConstants.TIME_RANGE_MAX) assertThat(result.first, `is`(equalTo(timeNow))) assertThat(result.second, `is`(lessThanOrEqualTo(windowMax))) } }
0
Kotlin
0
2
7043609ea79b8ee062c2e1e6542d4c7391350424
2,592
cwa-app-android
Apache License 2.0
commons/src/main/java/net/xpece/android/content/Resources.kt
consp1racy
29,105,747
false
null
@file:JvmName("XpContext") @file:JvmMultifileClass package net.xpece.android.content import android.content.Context import android.graphics.Point import net.xpece.android.app.windowManager private val TL_POINT = object : ThreadLocal<Point>() { override fun initialValue() = Point() } @Suppress("NULLABILITY_MISMATCH_BASED_ON_JAVA_ANNOTATIONS") private val point: Point get() = TL_POINT.get() val Context.windowWidth: Int get() = point.apply(windowManager.defaultDisplay::getSize).x val Context.smallestWindowWidth: Int get() = point.apply(windowManager.defaultDisplay::getSize).let { minOf(it.x, it.y) }
3
Java
3
20
3cd3d5cf7b2bfc1fb5ce9404d3b6fa3670ba9a42
626
android-commons
Apache License 2.0
conduit-frontend/frontend-decompose-logic/src/iosMain/kotlin/mikufan/cx/conduit/frontend/logic/repo/kstore/setup.ios.kt
CXwudi
826,482,545
false
{"Kotlin": 139400, "HTML": 1266, "CSS": 274}
package mikufan.cx.conduit.frontend.logic.repo.kstore import io.github.xxfast.kstore.KStore import io.github.xxfast.kstore.file.storeOf import kotlinx.io.files.Path //import platform.Foundation.NSDocumentDirectory //import platform.Foundation.NSFileManager //import platform.Foundation.NSStringFromClass //import platform.Foundation.NSURL //import platform.Foundation.NSUserDomainMask fun getAppDirectories(): AppStoreDirectories { // val fileManager:NSFileManager = NSFileManager.defaultManager // val documentsUrl: NSURL = fileManager.URLForDirectory( // directory = NSDocumentDirectory, // appropriateForURL = null, // create = false, // inDomain = NSUserDomainMask, // error = null // )!! // // val cachesUrl:NSURL = fileManager.URLForDirectory( // directory = NSCachesDirectory, // appropriateForURL = null, // create = false, // inDomain = NSUserDomainMask, // error = null // )!! // // return AppStoreDirectories( // files = Path(documentsUrl.path), // caches = Path(cachesUrl.path), // ) TODO("Uncomment above when in a mac machine") } fun setupPersistedConfigKStore(appStoreDirectories: AppStoreDirectories): KStore<PersistedConfig> { return storeOf( file = Path(appStoreDirectories.files, "persisted-config.json"), default = PersistedConfig(), ) }
3
Kotlin
0
0
84cf2d53625faea1bf3918f6eb129b335e1f56f0
1,319
realworld-compose-http4k-example-app
MIT License
app/src/main/java/com/android/itrip/adapters/BucketAdapter.kt
UTN-FRBA-Mobile
210,464,697
false
{"Gradle": 3, "Java Properties": 3, "Shell": 2, "Text": 1, "Ignore List": 2, "Batchfile": 2, "Markdown": 1, "JSON": 1, "Proguard": 1, "Kotlin": 73, "XML": 65, "Java": 2}
package com.android.itrip.adapters import android.view.LayoutInflater import android.view.ViewGroup import androidx.databinding.DataBindingUtil import androidx.databinding.ViewDataBinding import androidx.lifecycle.Lifecycle import androidx.lifecycle.LifecycleOwner import androidx.lifecycle.LifecycleRegistry import androidx.recyclerview.widget.RecyclerView import com.android.itrip.R import com.android.itrip.databinding.BucketEmptyItemBinding import com.android.itrip.databinding.BucketItemBinding import com.android.itrip.models.ActividadARealizar import com.android.itrip.util.ActivityType import com.android.itrip.viewModels.ScheduleViewModel import com.squareup.picasso.Picasso class BucketAdapter( private val scheduleViewModel: ScheduleViewModel, private val addActivityToBucketCallback: (ActividadARealizar) -> Unit, private val showActivityDetailsCallback: (ActividadARealizar) -> Unit ) : RecyclerView.Adapter<BucketAdapter.ActivitiesHolder>() { private var actividadARealizar = scheduleViewModel.actividadesARealizar.value ?: emptyList() init { scheduleViewModel.actividadesARealizar.observeForever { replaceItems(it) } } override fun getItemViewType(position: Int): Int { return when (getItem(position).id) { 0L -> ActivityType.EMPTY else -> ActivityType.ACTIVITY } } private fun replaceItems(_activities: List<ActividadARealizar>) { actividadARealizar = _activities notifyDataSetChanged() } override fun onBindViewHolder(holder: ActivitiesHolder, position: Int) { holder.bind( getItem(position), addActivityToBucketCallback, showActivityDetailsCallback ) } private fun getItem(position: Int): ActividadARealizar { return actividadARealizar[position] } override fun getItemId(position: Int): Long { return actividadARealizar[position].id } override fun getItemCount(): Int { return actividadARealizar.size } override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ActivitiesHolder { lateinit var binding: ViewDataBinding when (viewType) { ActivityType.ACTIVITY -> { binding = DataBindingUtil.inflate( LayoutInflater.from(parent.context), R.layout.bucket_item, parent, false ) } else -> { binding = DataBindingUtil.inflate( LayoutInflater.from(parent.context), R.layout.bucket_empty_item, parent, false ) } } parent.invalidate() return ActivitiesHolder(binding) } fun remove(position: Int) { scheduleViewModel.deleteToDoActivity(getItem(position)) } class ActivitiesHolder( private val binding: ViewDataBinding ) : RecyclerView.ViewHolder(binding.root), LifecycleOwner { private val lifecycleRegistry = LifecycleRegistry(this) override fun getLifecycle(): Lifecycle { return lifecycleRegistry } fun bind( item: ActividadARealizar, addActivityToBucketCallback: (ActividadARealizar) -> Unit, showActivityDetailsCallback: (ActividadARealizar) -> Unit ) { when (itemViewType) { ActivityType.ACTIVITY -> bindActivity(item, showActivityDetailsCallback) ActivityType.EMPTY -> bindingEmpty(item, addActivityToBucketCallback) } } private fun bindActivity( item: ActividadARealizar, showActivityDetailsCallback: (ActividadARealizar) -> Unit ) { (binding as BucketItemBinding).apply { actividadARealizar = item var height = bucketItemConstraintLayout.context.resources.displayMetrics.heightPixels / 8 * item.detalle_actividad.duracion if (item.detalle_actividad.duracion > 1) { height += 8 * item.detalle_actividad.duracion bucketItemImageView.layoutParams.height = height bucketItemImageView.requestLayout() item.detalle_actividad.imagen?.let { Picasso.get() .load(it) .resize( bucketItemConstraintLayout.context.resources.displayMetrics.widthPixels, height + item.detalle_actividad.duracion * 15 ) .centerCrop() .into(bucketItemImageView) } } else { bucketItemImageView.layoutParams.height = height bucketItemImageView.requestLayout() item.detalle_actividad.imagen?.let { Picasso.get() .load(it) .resize( bucketItemConstraintLayout.context.resources.displayMetrics.widthPixels, height + 10 ) .centerCrop() .into(bucketItemImageView) } } bucketItemConstraintLayout.setOnClickListener { showActivityDetailsCallback(item) } } } private fun bindingEmpty( item: ActividadARealizar, addActivityToBucketCallback: (ActividadARealizar) -> Unit ) { (binding as BucketEmptyItemBinding).bucketEmptyItemImageButton.apply { layoutParams.height = context.resources.displayMetrics.heightPixels / 8 * item.detalle_actividad.duracion requestLayout() setOnClickListener { addActivityToBucketCallback(item) } } } } }
1
null
1
1
eedae3ec26b590677c6495d894b24ab5c6439461
6,254
iTrip
MIT License
kamel-core/src/commonMain/kotlin/io/kamel/core/ImageLoading.kt
alialbaali
327,244,529
false
null
package io.kamel.core import androidx.compose.ui.graphics.ImageBitmap import androidx.compose.ui.graphics.painter.Painter import androidx.compose.ui.graphics.vector.ImageVector import io.kamel.core.cache.Cache import io.kamel.core.config.KamelConfig import io.kamel.core.config.ResourceConfig import io.kamel.core.decoder.Decoder import io.kamel.core.fetcher.Fetcher import io.kamel.core.mapper.Mapper import io.kamel.core.utils.findDecoderFor import io.kamel.core.utils.findFetcherFor import io.kamel.core.utils.mapInput import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.emitAll import kotlinx.coroutines.flow.flow import kotlinx.coroutines.flow.map /** * Loads an [ImageBitmap]. This includes mapping, fetching, decoding and caching the image resource. * @see Fetcher * @see Decoder * @see Mapper * @see Cache */ public fun KamelConfig.loadImageBitmapResource( data: Any, resourceConfig: ResourceConfig ): Flow<Resource<ImageBitmap>> = flow { try { val output = mapInput(data) when (val imageBitmap = imageBitmapCache[output]) { null -> emitAll(requestImageBitmapResource(output, resourceConfig)) else -> emit(Resource.Success(imageBitmap)) } } catch (exception: Throwable) { emit(Resource.Failure(exception)) } } /** * Loads an [ImageVector]. This includes mapping, fetching, decoding and caching the image resource. * @see Fetcher * @see Decoder * @see Mapper * @see Cache */ public fun KamelConfig.loadImageVectorResource( data: Any, resourceConfig: ResourceConfig ): Flow<Resource<ImageVector>> = flow { try { val output = mapInput(data) when (val imageVector = imageVectorCache[output]) { null -> emitAll(requestImageVectorResource(output, resourceConfig)) else -> emit(Resource.Success(imageVector)) } } catch (exception: Throwable) { emit(Resource.Failure(exception)) } } /** * Loads SVG [Painter]. This includes mapping, fetching, decoding and caching the image resource. * @see Fetcher * @see Decoder * @see Mapper * @see Cache */ public fun KamelConfig.loadSvgResource( data: Any, resourceConfig: ResourceConfig ): Flow<Resource<Painter>> = flow { try { val output = mapInput(data) when (val imageBitmap = svgCache[output]) { null -> emitAll(requestSvgResource(output, resourceConfig)) else -> emit(Resource.Success(imageBitmap)) } } catch (exception: Throwable) { emit(Resource.Failure(exception)) } } private fun KamelConfig.requestImageBitmapResource( output: Any, resourceConfig: ResourceConfig ): Flow<Resource<ImageBitmap>> { val fetcher = findFetcherFor(output) val decoder = findDecoderFor<ImageBitmap>() return fetcher.fetch(output, resourceConfig) .map { resource -> resource.map { channel -> decoder.decode(channel, resourceConfig) .apply { imageBitmapCache[output] = this } } } } private fun KamelConfig.requestImageVectorResource( output: Any, resourceConfig: ResourceConfig ): Flow<Resource<ImageVector>> { val fetcher = findFetcherFor(output) val decoder = findDecoderFor<ImageVector>() return fetcher.fetch(output, resourceConfig) .map { resource -> resource.map { channel -> decoder.decode(channel, resourceConfig) .apply { imageVectorCache[output] = this } } } } private fun KamelConfig.requestSvgResource( output: Any, resourceConfig: ResourceConfig ): Flow<Resource<Painter>> { val fetcher = findFetcherFor(output) val decoder = findDecoderFor<Painter>() return fetcher.fetch(output, resourceConfig) .map { resource -> resource.map { channel -> decoder.decode(channel, resourceConfig) .apply { svgCache[output] = this } } } }
9
Kotlin
8
99
c851524fe6fc9f5ed8922eb8625bd63b12d6abed
4,015
Kamel
Apache License 2.0
src/main/kotlin/io/sirix/ktsirix/Resource.kt
sirixdb
227,461,894
false
{"Kotlin": 29854}
package io.sirix.ktsirix import com.fasterxml.jackson.core.type.TypeReference class Resource( private val dbName: String, private val dbType: DbType, private val resourceName: String, private val client: ApiClient, private val authManager: AuthenticationManager ) { fun create(data: String, hashType: String = "ROLLING"): String? = client.createResource(dbName, dbType, resourceName, data, authManager.getAccessToken(), hashType) fun read( nodeId: Int? = null, revision: Revision? = null, revisionRange: Pair<Revision, Revision>? = null, maxLevel: Int? = null, topLevelLimit: Int? = null, topLevelSkipLastNode: Int? = null, metadataType: MetadataType? = null ): String? { val params: Map<String, String> = mapOf( "nodeId" to nodeId?.toString(), "maxLevel" to maxLevel?.toString(), "nextTopLevelNodes" to topLevelLimit?.toString(), "lastTopLevelNodeKey" to topLevelSkipLastNode?.toString(), "revision" to revision?.revisionNumber?.toString(), "revision-timestamp" to revision?.revisionTimestamp?.toString(), "start-revision" to revisionRange?.first?.revisionNumber?.toString(), "start-revision-timestamp" to revisionRange?.first?.revisionTimestamp?.toString(), "end-revision" to revisionRange?.second?.revisionNumber?.toString(), "end-revision-timestamp" to revisionRange?.second?.revisionTimestamp?.toString(), "withMetadata" to metadataType?.value ).toMapNotNull() return client.readResourceAsString(dbName, dbType, resourceName, params, authManager.getAccessToken()) } fun exists(): Boolean = client.resourceExists(dbName, dbType, resourceName, authManager.getAccessToken()) fun history(): List<Commit> = client.history(dbName, dbType, resourceName, authManager.getAccessToken(), object : TypeReference<HistoryCommit>() {}).history fun diff(revisionPair: Pair<Revision, Revision>, nodeId: Int?, maxDepth: Int?): List<Map<String, Any>> { val params: Map<String, String> = mapOf( "first-revision" to revisionPair.first.revisionNumber?.toString(), "first-revision-timestamp" to revisionPair.first.revisionTimestamp?.toString(), "end-revision" to revisionPair.second.revisionNumber?.toString(), "end-revision-timestamp" to revisionPair.second.revisionTimestamp?.toString(), "startNodeKey" to nodeId?.toString(), "maxDepth" to maxDepth?.toString() ).toMapNotNull() return client.diff(dbName, resourceName, params, authManager.getAccessToken(), object : TypeReference<DiffQueryResult>() {}).diffs } fun getEtag(nodeId: Int): String? = client.getEtag(dbName, dbType, resourceName, nodeId, authManager.getAccessToken()) fun update(nodeId: Int, data: String, insert: Insert = Insert.CHILD, etag: String? = null): String? = client.update(dbName, dbType, resourceName, nodeId, data, insert, etag, authManager.getAccessToken()) fun query(query: String, startResultSeqIndex: Int?, endResultSeqIndex: Int?): String? { val params = mapOf( "query" to query, "startResultSeqIndex" to startResultSeqIndex?.toString(), "endResultSeqIndex" to endResultSeqIndex?.toString() ).toMapNotNull() return client.readResourceAsString(dbName, dbType, resourceName, params, authManager.getAccessToken()) } private fun Map<String, String?>.toMapNotNull(): Map<String, String> = mapNotNull { (k, v) -> v?.let { k to it } }.toMap() fun delete(nodeId: Int? = null, etag: String? = null) { client.deleteResource(dbName, dbType, resourceName, nodeId, etag, authManager.getAccessToken()) } }
1
Kotlin
2
3
02a6bd089f4b01030b57d4e5c77ed9b5fe19dc78
3,833
sirix-kotlin-client
MIT License
src/main/kotlin/com/tang/hwplib/tools/control/equation/extensions/engine/Deletes.kt
accforaus
169,677,219
false
null
package com.tang.hwplib.tools.control.equation.extensions.engine import com.tang.hwplib.tools.control.equation.extensions.utils.* import com.tang.hwplib.tools.control.equation.extensions.utils.oneParSize import com.tang.hwplib.tools.control.equation.extensions.utils.oneParameter import com.tang.hwplib.tools.control.equation.extensions.utils.twoParSize import com.tang.hwplib.tools.control.equation.extensions.utils.twoParameter /** * Delete Over Used Par function * @receiver StringBuilder * @return StringBuilder */ fun StringBuilder.deleteOverUsedPar() : StringBuilder { val builder = this var parLev = 0 val positions = arrayListOf<Int>() val parNums = arrayListOf<Int>() for (index in 1 until builder.length) { if (builder[index].`is`('{') && !builder[index - 1].`is`('\\')) { positions.push(index) if (parLev >= parNums.size || parNums[parLev] == 0) parNums.push(0) ++parLev } else if (builder[index].`is`('}') && !builder[index - 1].`is`('\\')) { var deletePar = true val start = positions[--parLev] val end = index positions.pop() if (parNums[parLev] == 0) { parNums.pop() var j = start - 1 j = builder.indexOf(j, true) { it.`is`(' ') } if (builder[j].`is`(']')) { var bigParLev = 1 var midParLev = 0 --j while (j >= 0) { when (builder[j]) { '[' -> --bigParLev ']' -> ++bigParLev '{' -> if(!builder[j - 1].`is`('\\')) --midParLev '}' -> if(!builder[j - 1].`is`('\\')) ++midParLev } if (bigParLev == 0 || midParLev < 0) break j-- } if (j == -1) deletePar = false else { --j j = builder.indexOf(j, true) { it.`is`(' ') } } } if (deletePar && builder[j].isAlphaBet()) { --j j = builder.indexOf(j, true) { it.isAlphaBet() } if (builder[j].`is`('\\')) { for (k in 0 until oneParSize) { if (builder.indexOf(oneParameter[k], j) == j) { deletePar = false break } } for (k in 0 until twoParSize) { if (builder.indexOf(twoParameter[k], j) == j) { parNums.push(1) deletePar = false break } } } } else if (deletePar && (builder[j].`is`('_') || builder[j].`is`('^'))) { var k = start + 1 k = indexOf(k) { it.`is`(' ') } if (k != end) deletePar = false else builder[j] = ' ' } } else { if (--parNums[parLev] == 0) parNums.pop() deletePar = false } if (deletePar) { builder[start] = ' ' builder[end] = ' ' } } } return builder } /** * delete multiple space * @receiver StringBuilder * @return StringBuilder */ fun StringBuilder.deleteMultipleSpace() : StringBuilder { var builder = this var index = builder.length - 1 while (index > 0) { if (builder[index].`is`(' ') && builder[index - 1].`is`(' ')) { var j = index - 1 j = builder.indexOf(j, true) { it.`is`(' ') } builder = builder.erase(j + 2, index - j - 1) index = j } index-- } return builder }
0
Kotlin
7
22
b828271f12a885dece5af5aa6281a1b2cf84d459
4,105
libhwp
Apache License 2.0
app/src/main/java/com/android/inputmethod/ui/personaldictionary/addworddialog/AddWordDialogNavArg.kt
divvun
24,789,155
false
{"Java": 1703101, "Kotlin": 616713}
package com.android.inputmethod.ui.personaldictionary.addworddialog import android.os.Parcelable import kotlinx.parcelize.Parcelize @Parcelize data class AddWordDialogNavArg( val languageId: Long ) : Parcelable
22
Java
6
9
5e71829dd991105f19aaec1d65dfff06c65b946a
220
giellakbd-android
Apache License 2.0
src/main/kotlin/one/mixin/handsaw/platform.kt
MixinNetwork
318,370,389
false
null
package one.mixin.handsaw sealed class Platform { object Android : Platform() object IOS : Platform() object Desktop: Platform() object IOSAuthorization: Platform() object AppStore: Platform() override fun toString(): String = when(this) { Android -> "Android" IOS -> "iOS" Desktop -> "Desktop" IOSAuthorization -> "iOSAuthorization" AppStore -> "AppStore" } } fun Collection<String>.containsIgnoreCase(text: String) = any { it.trim().equals(text, true) }
2
Kotlin
0
0
78f704e5ee96de3c5f129606abded92fa17d830d
558
handsaw
MIT License
ecommerce/src/main/kotlin/com/cuttage/ecommerce/repositories/UserRepository.kt
cuttage
641,319,984
false
null
package com.cuttage.ecommerce.repositories import com.cuttage.ecommerce.domain.User import org.springframework.data.mongodb.repository.MongoRepository interface UserRepository : MongoRepository<User, String> { fun findByEmail(email: String): User? }
0
Kotlin
0
0
d012d393adc608c9a6119658d0217f8fb0592c63
257
Backend-E-commerce-with-Kotlin-Spring-Boot-and-MongoDB
MIT License
app/src/test/java/br/com/joaovq/mydailypet/reminder/presentation/viewmodel/AddPetReminderViewModelTest.kt
joaovq
650,739,082
false
{"Kotlin": 326547, "Ruby": 1076}
package br.com.joaovq.mydailypet.reminder.presentation.viewmodel import br.com.joaovq.mydailypet.reminder.presentation.viewintent.AddReminderEvents import br.com.joaovq.mydailypet.reminder.presentation.viewstate.AddReminderUiState import br.com.joaovq.mydailypet.testrule.MainDispatcherRule import br.com.joaovq.mydailypet.testutil.TestUtilPet import br.com.joaovq.mydailypet.testutil.TestUtilReminder import br.com.joaovq.pet_domain.usecases.GetAllPetsUseCase import br.com.joaovq.reminder_domain.model.Reminder import br.com.joaovq.reminder_domain.usecases.CreateReminderUseCase import br.com.joaovq.reminder_domain.usecases.ValidateDateTimeReminderUseCase import br.com.joaovq.reminder_domain.usecases.ValidateFieldText import io.mockk.MockKAnnotations import io.mockk.coEvery import io.mockk.coJustAwait import io.mockk.impl.annotations.MockK import io.mockk.impl.annotations.RelaxedMockK import io.mockk.junit4.MockKRule import junit.framework.TestCase.assertEquals import kotlinx.coroutines.ExperimentalCoroutinesApi import kotlinx.coroutines.test.runTest import org.junit.Before import org.junit.Rule import org.junit.Test @OptIn(ExperimentalCoroutinesApi::class) class AddPetReminderViewModelTest { @get:Rule val testDispatcherRule = MainDispatcherRule() @get:Rule val mockkRule = MockKRule(this) private lateinit var reminderViewModel: AddPetReminderViewModel @MockK(relaxed = true) private lateinit var getAllPetsUseCase: GetAllPetsUseCase @RelaxedMockK private lateinit var createReminderUseCase: CreateReminderUseCase @RelaxedMockK private lateinit var validateTimerUseCase: ValidateDateTimeReminderUseCase @RelaxedMockK private lateinit var validateFieldText: ValidateFieldText private val submitActionSuccess = AddReminderEvents.SubmitData( TestUtilReminder.reminder.name, TestUtilReminder.reminder.description, TestUtilReminder.reminder.toDate, TestUtilReminder.reminder.pet, ) @Before fun setUp() { MockKAnnotations.init(this, relaxed = true) reminderViewModel = AddPetReminderViewModel( getAllPetsUseCase, createReminderUseCase, validateTimerUseCase, validateFieldText, testDispatcherRule.testDispatcher, ) } @Test fun `GIVEN intent Submit WHEN dispatch intent THEN exception`() = runTest { coEvery { validateFieldText.invoke(TestUtilReminder.reminder.name) } returns TestUtilPet.successfulValidateState coEvery { validateFieldText.invoke(TestUtilReminder.reminder.description) } returns TestUtilPet.successfulValidateState coEvery { validateTimerUseCase.invoke(TestUtilReminder.reminder.toDate) } returns TestUtilPet.successfulValidateState val exception = Exception() coEvery { createReminderUseCase.invoke( ofType(br.com.joaovq.reminder_domain.model.Reminder::class), ) } throws exception reminderViewModel.dispatchIntent(submitActionSuccess) assertEquals( AddReminderUiState.Error( exception = exception, ), reminderViewModel.state.value, ) } @Test fun `GIVEN intent Submit WHEN dispatch intent THEN state SubmittedSuccess`() = runTest { coEvery { validateFieldText.invoke(TestUtilReminder.reminder.name) } returns TestUtilPet.successfulValidateState coEvery { validateFieldText.invoke(TestUtilReminder.reminder.description) } returns TestUtilPet.successfulValidateState coEvery { validateTimerUseCase.invoke(TestUtilReminder.reminder.toDate) } returns TestUtilPet.successfulValidateState reminderViewModel.dispatchIntent(submitActionSuccess) coJustAwait { createReminderUseCase.invoke(ofType(Reminder::class)) } assertEquals( AddReminderUiState.SubmittedSuccess, reminderViewModel.state.value, ) } @Test fun `GIVEN intent Submit WHEN createReminder() THEN state SubmittedSuccess`() = runTest { coEvery { validateFieldText.invoke(TestUtilReminder.reminder.name) } returns TestUtilPet.successfulValidateState coEvery { validateFieldText.invoke(TestUtilReminder.reminder.description) } returns TestUtilPet.successfulValidateState coEvery { validateTimerUseCase.invoke(TestUtilReminder.reminder.toDate) } returns TestUtilPet.successfulValidateState reminderViewModel.dispatchIntent(submitActionSuccess) coJustAwait { createReminderUseCase.invoke(ofType(br.com.joaovq.reminder_domain.model.Reminder::class)) } assertEquals( AddReminderUiState.SubmittedSuccess, reminderViewModel.state.value, ) } }
1
Kotlin
0
0
ce80c4b481c996fc02c0f22689954edf8154d588
4,984
MyDailyPet
MIT License
src/main/kotlin/creativeDSLs/chapter_04/curryingSnippet.kt
DanielGronau
521,419,278
false
{"Kotlin": 132813, "CSS": 27709, "Java": 2033}
package creativeDSLs.chapter_04 fun someFun(i: Int, s: String): String = s.repeat(i) val <A, B, R> ((A, B) -> R).curry: (A) -> (B) -> R get() = { a -> { b -> this@curry(a, b) } } fun main() { val sf3 = ::someFun.curry(3) println(sf3("Abc")) println(sf3("x")) val sf3Fun = ::someFun.curryFun()(3) println(sf3Fun("Abc")) println(sf3Fun("x")) } fun <A, B, R> ((A, B) -> R).curryFun(): (A) -> (B) -> R = { a -> { b -> this@curryFun(a, b) } }
0
Kotlin
0
0
d165ef95d4b75036ce1703880d23899386d11d6e
477
creativeDSLs
MIT License
domain/src/main/java/com/oguzdogdu/domain/usecase/auth/GetSignInCheckGoogleUseCaseImpl.kt
oguzsout
616,912,430
false
{"Kotlin": 488557}
package com.oguzdogdu.domain.usecase.auth import com.oguzdogdu.domain.repository.Authenticator import com.oguzdogdu.domain.wrapper.Resource import com.oguzdogdu.domain.wrapper.toResource import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.flow import javax.inject.Inject class GetSignInCheckGoogleUseCaseImpl @Inject constructor( private val repository: Authenticator, ) : GetSignInCheckGoogleUseCase { override suspend fun invoke(): Flow<Boolean> = flow { emit(repository.isUserAuthenticatedWithGoogle()) } }
0
Kotlin
6
61
ddd410404ffd346e221fcd183226496411d8aa43
546
Wallies
MIT License
utils/multibase/src/main/kotlin/io/bluetape4k/multibase/internal/Base16.kt
debop
625,161,599
false
{"Kotlin": 7504333, "HTML": 502995, "Java": 2273, "JavaScript": 1351, "Shell": 1301, "CSS": 444, "Dockerfile": 121, "Mustache": 82}
package io.bluetape4k.multibase.internal object Base16 { fun decode(hex: String): ByteArray { require(hex.length % 2 != 1) { "Must have an even number of hex digits to convert to bytes!" } val res = ByteArray(hex.length / 2) for (i in res.indices) res[i] = hex.substring(2 * i, 2 * i + 2).toInt(16).toByte() return res } fun encode(data: ByteArray): String { return bytesToHex(data) } private val HEX_DIGITS = arrayOf( "0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "a", "b", "c", "d", "e", "f" ) private val HEX = Array(256) { HEX_DIGITS[(it shr 4) and 0xF] + HEX_DIGITS[it and 0xF] } fun byteToHex(b: Byte): String? { return HEX[b.toInt() and 0xFF] } fun bytesToHex(data: ByteArray): String = buildString { data.forEach { append(byteToHex(it)) } } }
0
Kotlin
0
1
ce3da5b6bddadd29271303840d334b71db7766d2
902
bluetape4k
MIT License
data/slack-jackson-dto/src/main/kotlin/io/hndrs/slack/api/contract/jackson/group/users/GetPresence.kt
hndrs
168,710,332
false
null
package com.kreait.slack.api.contract.jackson.group.users import com.fasterxml.jackson.annotation.JsonProperty import com.fasterxml.jackson.annotation.JsonSubTypes import com.fasterxml.jackson.annotation.JsonTypeInfo import com.kreait.slack.api.contract.jackson.UserPresence import com.kreait.slack.api.contract.jackson.util.JacksonDataClass /** * https://api.slack.com/methods/users.getPresence */ @JsonTypeInfo(use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.PROPERTY, property = "ok", visible = true) @JsonSubTypes( JsonSubTypes.Type(value = SuccessfulGetPresenceResponse::class, name = "true"), JsonSubTypes.Type(value = ErrorGetPresenceResponse::class, name = "false") ) @JacksonDataClass sealed class GetPresenceResponse constructor(@JsonProperty("ok") open val ok: Boolean) /** * Success-response of this request. * * @property ok will be true * @property presence the presence information of the user * @property isOnline true when the user is currently online * @property autoAway auto_away will be true if slacks servers haven't detected any activity from the user in the last 30 minutes. * @property manualAway will be true if the user has manually set their presence to away. * @property connectionCount gives a count of total connections. * @property lastActivity indicates the last activity seen by our servers. If a user has no connected clients then this property will be absent */ data class SuccessfulGetPresenceResponse constructor( override val ok: Boolean, @JsonProperty("presence") val presence: UserPresence, @JsonProperty("online") val isOnline: Boolean?, @JsonProperty("auto_away") val autoAway: Boolean?, @JsonProperty("manual_away") val manualAway: Boolean?, @JsonProperty("connection_count") val connectionCount: Int?, @JsonProperty("last_activity") val lastActivity: String? ) : GetPresenceResponse(ok) { companion object } /** * Failure-response of this request * * @property ok will be false * @property error contains the error description */ @JacksonDataClass data class ErrorGetPresenceResponse constructor( override val ok: Boolean, @JsonProperty("error") val error: String ) : GetPresenceResponse(ok) { companion object } /** * Gets user presence information. * * @property user User to get presence info on. Defaults to the authed user. */ data class GetPresenceRequest(@JsonProperty("user") val user: String) { fun toRequestMap() = mutableMapOf("user" to user) companion object }
57
null
13
16
89c5a6ddd0cbac522dd9cd4324901bf2907369a8
2,513
slack-spring-boot-starter
MIT License
dev-resources/design/composeApp/src/commonMain/kotlin/OpenNeptuneScreen.kt
OpenNeptune3D
835,222,248
false
{"Kotlin": 116872, "Python": 103578, "Shell": 35786}
import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.height import androidx.compose.foundation.layout.width import androidx.compose.material3.MaterialTheme import androidx.compose.material3.darkColorScheme import androidx.compose.runtime.Composable import androidx.compose.ui.Modifier import androidx.compose.ui.unit.dp @Composable fun OpenNeptuneScreen(modifier: Modifier = Modifier, content: @Composable () -> Unit) { MaterialTheme(colorScheme = darkScheme) { Box(modifier = modifier.width(272.dp).height(480.dp)) { content() } } }
0
Kotlin
1
2
d969fb53489f0be4b079a24d5271ed2976925cf5
606
display_firmware
MIT License
engine/game/src/main/kotlin/org/rsmod/game/interact/Interaction.kt
rsmod
293,875,986
false
{"Kotlin": 1817705}
package org.rsmod.game.interact import org.rsmod.game.entity.Npc import org.rsmod.game.entity.PathingEntity import org.rsmod.game.loc.BoundLocInfo import org.rsmod.game.obj.Obj public sealed class Interaction( public val opSlot: Int, public val hasOpTrigger: Boolean, public val hasApTrigger: Boolean, public var apRange: Int, public var persistent: Boolean, public var apRangeCalled: Boolean = false, public var interacted: Boolean = false, ) { override fun toString(): String = "Interaction(" + "opSlot=$opSlot, " + "hasOpTrigger=$hasOpTrigger, " + "hasApTrigger=$hasApTrigger, " + "apRange=$apRange, " + "persistent=$persistent, " + "apRangeCalled=$apRangeCalled, " + "interacted=$interacted" + ")" } public class InteractionLoc( public val target: BoundLocInfo, opSlot: Int, hasOpTrigger: Boolean, hasApTrigger: Boolean, startApRange: Int = PathingEntity.DEFAULT_AP_RANGE, persistent: Boolean = false, ) : Interaction(opSlot, hasOpTrigger, hasApTrigger, startApRange, persistent) public class InteractionNpc( public val target: Npc, opSlot: Int, hasOpTrigger: Boolean, hasApTrigger: Boolean, startApRange: Int = PathingEntity.DEFAULT_AP_RANGE, persistent: Boolean = false, ) : Interaction(opSlot, hasOpTrigger, hasApTrigger, startApRange, persistent) public class InteractionObj( public val target: Obj, opSlot: Int, hasOpTrigger: Boolean, hasApTrigger: Boolean, startApRange: Int = PathingEntity.DEFAULT_AP_RANGE, persistent: Boolean = false, ) : Interaction(opSlot, hasOpTrigger, hasApTrigger, startApRange, persistent)
0
Kotlin
64
95
3ba446ed70bcde0870ef431e1a8527efc6837d6c
1,739
rsmod
ISC License
jvm/physical-plan/src/main/kotlin/ScanExec.kt
andygrove
333,252,270
false
null
// Copyright 2020 <NAME> // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package io.andygrove.kquery.physical import io.andygrove.kquery.datasource.DataSource import io.andygrove.kquery.datatypes.RecordBatch import io.andygrove.kquery.datatypes.Schema /** Scan a data source with optional push-down projection. */ class ScanExec(val ds: DataSource, val projection: List<String>) : PhysicalPlan { override fun schema(): Schema { return ds.schema().select(projection) } override fun children(): List<PhysicalPlan> { return listOf() } override fun execute(): Sequence<RecordBatch> { return ds.scan(projection); } override fun toString(): String { return "ScanExec: schema=${schema()}, projection=$projection" } }
3
Kotlin
12
72
9c27d475b62e3a4eccec4236e2fe60eb3f13e757
1,255
how-query-engines-work
Apache License 2.0
src/main/java/com/longforus/kotlincodesorter/action/NameSortAction.kt
longforus
149,744,808
false
{"Kotlin": 9167, "Java": 1227}
package com.longforus.kotlincodesorter.action import com.longforus.kotlincodesorter.sort.ISorter import com.longforus.kotlincodesorter.sort.NameSorter import org.jetbrains.kotlin.psi.KtClassOrObject /** * Created by <NAME> on 9/21/2018 5:06 PM. * Description : */ class NameSortAction : BaseSortAction() { override fun getSort(clazz: KtClassOrObject): ISorter = NameSorter(clazz) }
4
Kotlin
8
29
75ddaccf14a9169e04fa5ef317f09da6701ab737
397
KotlinCodeSorter
MIT License
android/src/main/java/com/sunmi/utils/SunmiUtils.kt
ianlgnk
831,077,190
false
{"Kotlin": 9479, "Java": 7149, "TypeScript": 6787, "JavaScript": 2074}
package com.plugpag.utils import android.os.Build class SunmiUtils { companion object { fun isSunmiP2(): Boolean { return Build.MODEL.equals("P2-B", true) } fun resolveRFIDBySerialNumber(value: String): String { val length = value.length val n = StringBuilder() n.append(value.substring(0, 2)).append("-") if (length >= 4) { n.append(value.substring(2, 4)) if (length > 4) n.append("-") } if (length >= 6) { n.append(value.substring(4, 6)) if (length > 6) n.append("-") } if (length >= 8) { n.append(value.substring(6, 8)) if (length > 8) n.append("-") } if (length >= 10) { n.append(value.substring(6, 10)) } val split = n.toString().split("-") val splitSize = split.size val nova = StringBuilder() when (splitSize) { 4 -> nova.append(split[3]).append(split[2]).append(split[1]).append(split[0]) 3 -> nova.append(split[2]).append(split[1]).append(split[0]) 2 -> nova.append(split[1]).append(split[0]) else -> {} } val hexResult = nova.toString() val converted = hexResult.toLong(16) var id = converted.toString() if (id.length < 10) { id = "0$converted" if (id.length < 10) id = "00$converted" if (id.length < 10) id = "000$converted" } return id } } }
0
Kotlin
0
0
e305c0a844d6426e31139edc5a3622f0a6779930
1,438
react-native-plugpag
MIT License
app/src/main/java/com/pdm/to_do_compose/di/AppModule.kt
pablin202
758,340,732
false
{"Kotlin": 91343}
package com.pdm.to_do_compose.di import android.app.Application import android.content.Context import android.content.SharedPreferences import com.pdm.to_do_compose.data.preferences.DefaultPreferences import com.pdm.to_do_compose.domain.preferences.Preferences import com.pdm.to_do_compose.util.AppDispatchers import dagger.Module import dagger.Provides import dagger.hilt.InstallIn import dagger.hilt.components.SingletonComponent import kotlinx.coroutines.Dispatchers import javax.inject.Singleton @Module @InstallIn(SingletonComponent::class) object AppModule { @Provides fun provideSlimeDispatchers(): AppDispatchers { return AppDispatchers( default = Dispatchers.Default, main = Dispatchers.Main, io = Dispatchers.IO ) } @Provides @Singleton fun provideSharedPreferences( app: Application ): SharedPreferences { return app.getSharedPreferences("shared_pref", Context.MODE_PRIVATE) } @Provides @Singleton fun providePreferences( sharedPreferences: SharedPreferences ): Preferences { return DefaultPreferences( sharedPreferences ) } }
0
Kotlin
0
0
79527721fb7e9a853c9554622f5e39366e8d2ec5
1,198
to-do-compose
MIT License
client/src/main/kotlin/com/ecwid/upsource/rpc/fileordirectorycontent/FileReferenceCodeMarkupDTO.kt
turchenkoalex
266,583,029
false
null
// Generated by the codegen. Please DO NOT EDIT! // source: message.ftl package com.ecwid.upsource.rpc.fileordirectorycontent /** * @param markup See ReferenceCodeMarkupItemDTO parameters * @param navigationPointsTable See MarkupNavigationPointDTO parameters * @param fileNameTable See FileInRevisionDTO parameters * @param localDeclarationRanges See LocalDeclarationRangeDTO parameters */ @Suppress("unused") data class FileReferenceCodeMarkupDTO( /** * See ReferenceCodeMarkupItemDTO parameters (repeated) * * @see com.ecwid.upsource.rpc.fileordirectorycontent.ReferenceCodeMarkupItemDTO */ val markup: List<ReferenceCodeMarkupItemDTO> = emptyList(), /** * See MarkupNavigationPointDTO parameters (repeated) * * @see com.ecwid.upsource.rpc.fileordirectorycontent.MarkupNavigationPointDTO */ val navigationPointsTable: List<MarkupNavigationPointDTO> = emptyList(), /** * See FileInRevisionDTO parameters (repeated) * * @see com.ecwid.upsource.rpc.ids.FileInRevisionDTO */ val fileNameTable: List<com.ecwid.upsource.rpc.ids.FileInRevisionDTO> = emptyList(), /** * See LocalDeclarationRangeDTO parameters (repeated) * * @see com.ecwid.upsource.rpc.fileordirectorycontent.LocalDeclarationRangeDTO */ val localDeclarationRanges: List<LocalDeclarationRangeDTO> = emptyList() )
0
Kotlin
1
3
bc93adb930157cd77b6955ed86b3b2fc7f78f6a2
1,323
upsource-rpc
Apache License 2.0
app/src/androidTest/java/dev/jatzuk/servocontroller/ui/HomeFragmentTest.kt
jatzuk
287,108,596
false
null
package dev.jatzuk.servocontroller.ui import android.content.Context import androidx.test.espresso.Espresso.onView import androidx.test.espresso.assertion.ViewAssertions.matches import androidx.test.espresso.matcher.ViewMatchers.withId import androidx.test.espresso.matcher.ViewMatchers.withText import androidx.test.platform.app.InstrumentationRegistry import dagger.hilt.android.testing.HiltAndroidRule import dagger.hilt.android.testing.HiltAndroidTest import dev.jatzuk.servocontroller.LottieAnimationViewDrawableMatcher.hasAnimationResource import dev.jatzuk.servocontroller.R import dev.jatzuk.servocontroller.launchFragmentInHiltContainer import kotlinx.coroutines.ExperimentalCoroutinesApi import org.junit.Before import org.junit.Rule import org.junit.Test @ExperimentalCoroutinesApi @HiltAndroidTest class HomeFragmentTest { @get:Rule var hiltRule = HiltAndroidRule(this) private lateinit var context: Context @Before fun setUp() { launchFragmentInHiltContainer<HomeFragment>() hiltRule.inject() context = InstrumentationRegistry.getInstrumentation().targetContext } @Test fun whenConnectionTypeUnsupported_thenShowChangeConnectionTypeTitleOnButton() { onView(withId(R.id.button)) .check(matches(withText(context.getString(R.string.change_connection_type)))) } @Test fun whenConnectionTypeUnsupported_thenShowUnsupportedAnimation() { onView(withId(R.id.lav)) .check(matches(hasAnimationResource(R.raw.animation_connection_type_unsupported))) } }
0
Kotlin
0
0
dad579a72fc66dd4934c7425cc121060e19a49c4
1,576
Servo-Controller
Apache License 2.0
presentation/src/main/java/io/iamjosephmj/presentation/mvi/mvibase/MVIView.kt
iamjosephmj
350,452,121
false
null
/* * MIT License * * Copyright (c) 2021 Joseph James * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. * */ package io.iamjosephmj.presentation.mvi.mvibase import io.reactivex.Observable /** * @author Joseph James */ interface MVIView<I : MVIIntent, S : MVIViewState> { /** * Intents from the ViewModel */ fun intents(): Observable<I> /** * State to be rendered in the UI. */ fun render(state: S) }
0
Kotlin
0
1
615501a57e0c8771ed41340babed61dc2bb09a28
1,447
MVI-Clean-Rx
MIT License
app/src/main/java/com/jnj/vaccinetracker/sync/domain/services/MasterDataSyncService.kt
johnsonandjohnson
503,902,626
false
{"Kotlin": 1690434}
package com.jnj.vaccinetracker.sync.domain.services import com.jnj.vaccinetracker.common.data.database.typealiases.dateNow import com.jnj.vaccinetracker.common.data.helpers.delaySafe import com.jnj.vaccinetracker.common.domain.entities.MasterDataFile import com.jnj.vaccinetracker.common.exceptions.NoNetworkException import com.jnj.vaccinetracker.common.helpers.* import com.jnj.vaccinetracker.config.Counters import com.jnj.vaccinetracker.sync.data.helpers.ServerPollUtil import com.jnj.vaccinetracker.sync.data.models.MasterDataUpdateEntryDto import com.jnj.vaccinetracker.sync.data.models.MasterDataUpdatesResponse import com.jnj.vaccinetracker.sync.data.models.SyncDate import com.jnj.vaccinetracker.sync.data.network.VaccineTrackerSyncApiDataSource import com.jnj.vaccinetracker.sync.domain.entities.MasterSyncStatus import com.jnj.vaccinetracker.sync.domain.entities.SyncErrorMetadata import com.jnj.vaccinetracker.sync.domain.factories.SyncMasterDataUseCaseFactory import com.jnj.vaccinetracker.sync.domain.helpers.SyncLogger import com.jnj.vaccinetracker.sync.domain.helpers.SyncSettingsObserver import com.jnj.vaccinetracker.sync.domain.usecases.masterdata.GetLocalMasterDataModifiedUseCase import com.jnj.vaccinetracker.sync.domain.usecases.masterdata.GetMasterDataHashUseCase import kotlinx.coroutines.* import javax.inject.Inject import javax.inject.Singleton /** * to be used in foreground service */ @Singleton class MasterDataSyncService @Inject constructor( private val dispatchers: AppCoroutineDispatchers, private val api: VaccineTrackerSyncApiDataSource, private val networkConnectivity: NetworkConnectivity, private val syncMasterDataUseCaseFactory: SyncMasterDataUseCaseFactory, private val getLocalMasterDataModifiedUseCase: GetLocalMasterDataModifiedUseCase, private val getMasterDataHashUseCase: GetMasterDataHashUseCase, private val syncSettingsObserver: SyncSettingsObserver, private val serverPollUtil: ServerPollUtil, private val syncLogger: SyncLogger, ) { private val MasterDataFile.localDateModified: SyncDate? get() = getLocalMasterDataModifiedUseCase.getMasterDataSyncDate(this) private val job = SupervisorJob() private val scope get() = CoroutineScope(dispatchers.mainImmediate + job) private var pollServerJob: Job? = null companion object { private val counter = Counters.MasterDataSync } fun start() { if (pollServerJob?.isActive != true) { pollServerJob = scope.launch(dispatchers.io) { pollServerPeriodically() } } } private suspend fun MasterDataFile.calcSyncStatus(updateEntry: MasterDataUpdateEntryDto?): MasterSyncStatus { val masterDataFile = this logInfo("calcSyncStatus $masterDataFile $updateEntry") if (updateEntry?.dateModified != null) { val localDateModified = masterDataFile.localDateModified logInfo("calcSyncStatus $masterDataFile localDateModified:$localDateModified") return when (localDateModified) { null -> MasterSyncStatus.EMPTY updateEntry.dateModified -> MasterSyncStatus.OK else -> MasterSyncStatus.STALE } } if (updateEntry?.hash != null) { val localHash = getMasterDataHashUseCase.getMasterDataHash(masterDataFile) logInfo("calcSyncStatus $masterDataFile localHash:$localHash") return when (localHash) { null -> MasterSyncStatus.EMPTY updateEntry.hash -> MasterSyncStatus.OK else -> MasterSyncStatus.STALE } } val defaultMasterSyncStatus = MasterSyncStatus.EMPTY logWarn("calcSyncStatus invalid MasterDataUpdateEntryDto, both hash and dateModified are null $masterDataFile $updateEntry $defaultMasterSyncStatus") return defaultMasterSyncStatus } private suspend fun storeIfOutOfSync(masterDataFile: MasterDataFile, updateEntry: MasterDataUpdateEntryDto?) { suspend fun calcSyncStatus() = masterDataFile.calcSyncStatus(updateEntry).also { syncLogger.logMasterSyncStatus(masterDataFile, it, SyncDate(dateNow())) } val syncStatus = calcSyncStatus() logInfo("storeIfOutOfSync $syncStatus $masterDataFile $updateEntry") if (syncStatus == MasterSyncStatus.OK) { return } val useCase = syncMasterDataUseCaseFactory.create(masterDataFile) networkConnectivity.awaitFastInternet(debugLabel()) syncSettingsObserver.awaitSyncCredentialsAvailable(debugLabel()) val dateModified = updateEntry?.dateModified ?: SyncDate(dateNow()) try { useCase.sync(dateModified).also { //update sync date calcSyncStatus() //notify get master data use case that it should update memory cache syncLogger.logMasterDataPersisted(masterDataFile) } } catch (ex: Throwable) { if (!networkConnectivity.isConnectedAccurate()) { logWarn("error occurred trying to sync due to bad internet: $masterDataFile", ex) return storeIfOutOfSync(masterDataFile, updateEntry) } else logError("error occurred trying to sync: $masterDataFile", ex) // can't rely on network connectivity state // in case we don't have file stored for this master data then wait for a short while and try again if (syncStatus == MasterSyncStatus.EMPTY) { val delay = counter.FIRST_INIT_ERROR_RETRY_DELAY logInfo("We don't have an existing $masterDataFile, try again after $delay ms") delaySafe(delay) return storeIfOutOfSync(masterDataFile, updateEntry) } } } private fun CoroutineScope.launchDownloadTask(masterDataFile: MasterDataFile, entry: MasterDataUpdateEntryDto?) = launch { storeIfOutOfSync(masterDataFile, entry) } private suspend fun storeData(masterDataUpdatesResponse: MasterDataUpdatesResponse) = coroutineScope { MasterDataFile.values().forEach { masterDataFile -> // the coroutineScope will wait until all launched jobs are completed. launchDownloadTask(masterDataFile, masterDataUpdatesResponse.find { masterDataFile.syncName == it.name }) } } private suspend fun fetchUpdates(): MasterDataUpdatesResponse { return api.getMasterDataUpdates() } private suspend fun doSync() { logInfo("pollServer") networkConnectivity.awaitFastInternet(debugLabel()) syncSettingsObserver.awaitSyncCredentialsAvailable(debugLabel()) val syncErrorMetadata = SyncErrorMetadata.MasterDataUpdatesCall() val updates = try { fetchUpdates().also { syncLogger.clearSyncError(syncErrorMetadata) } } catch (ex: NoNetworkException) { logWarn("no network to poll server for master data updates, trying again") return doSync() } catch (ex: Throwable) { if (!networkConnectivity.isConnectedAccurate()) { logWarn("no network to poll server for master data updates, trying again", ex) return doSync() } syncLogger.logSyncError(syncErrorMetadata, ex) logError("something went wrong fetch master data updates", ex) return } storeData(updates) } private suspend fun pollServer() { try { syncLogger.logMasterDataSyncInProgress(true) doSync() } finally { syncLogger.logMasterDataSyncInProgress(false) } } private suspend fun pollServerPeriodically() { serverPollUtil.pollServerPeriodically(delayMs = counter.DELAY, debugLabel = debugLabel(), skipDelayWhenSyncCredentialsChanged = true, skipDelayWhenSyncSettingsChanged = false) { pollServer(); true } } fun cancel() { scope.cancel() } }
2
Kotlin
1
1
dbf657c7fb7cb1233ed5c26bc554a1032afda3e0
8,136
vxnaid
Apache License 2.0
app/src/main/java/com/dicoding/restaurantreview/ui/main/SplashActivity.kt
Jesjsssi
784,332,105
false
{"Kotlin": 45156}
package com.dicoding.restaurantreview.ui.main import android.content.Intent import android.os.Bundle import android.os.Handler import androidx.activity.enableEdgeToEdge import androidx.appcompat.app.AppCompatActivity import androidx.core.view.ViewCompat import androidx.core.view.WindowInsetsCompat import com.dicoding.restaurantreview.R class SplashActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_splash) supportActionBar?.hide() Handler().postDelayed({ val intent = Intent(this, MainActivity::class.java) startActivity(intent) finish() }, 2000) } }
0
Kotlin
0
1
d04313aeccaae3e3f61fa06f2fbc6b190734a8de
743
AplikasiGithub
MIT License
app/src/main/java/com/rishabh/highschooldirectory/di/networkModule.kt
rishabharora3
510,886,111
false
{"Kotlin": 38586, "Java": 167}
package com.rishabh.highschooldirectory.di import com.rishabh.highschooldirectory.data.providers.RetrofitProvider import org.koin.dsl.module private const val BASE_URL = "https://data.cityofnewyork.us/resource/" /** * Module for providing Retrofit instances */ val networkModule = module { single { RetrofitProvider(get(), BASE_URL).provide() } }
0
Kotlin
0
0
7ce5039fac4c28efc7257b8b24a8e69cfb8e7fc4
367
HighSchoolDirectory
Apache License 2.0
app/src/main/java/com/github/oheger/locationteller/map/LocationFileState.kt
oheger
192,119,380
false
null
/* * Copyright 2019-2022 The Developers. * * Licensed under the Apache License, Version 2.0 (the "License") * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.github.oheger.locationteller.map import com.github.oheger.locationteller.server.LocationData import com.google.android.gms.maps.model.LatLng /** * A data class storing information about a marker on a map. */ data class MarkerData( /** The [LocationData] object associated with the marker. */ val locationData: LocationData, /** The position of the marker as [LatLng] object. */ val position: LatLng ) /** * A class storing information about the location files that are currently available on the server. * * This class is used to display a map with the locations recorded and to update this map when new data arrives. */ data class LocationFileState( /** The current list of location files on the server. */ val files: List<String>, /** A map assigning a [MarkerData] object to a file path. */ val markerData: Map<String, MarkerData> ) { companion object { /** * Constant for an empty state. This constant can be used as initial state when loading data from the server. */ val EMPTY = LocationFileState(emptyList(), emptyMap()) } /** * Check this state against the given list of [new location files][newFiles] and return a flag whether the list * has changed. If this function returns *true*, the map view needs to be updated. */ fun stateChanged(newFiles: List<String>): Boolean = newFiles != files /** * Return the most recent [MarkerData] object. This is the marker that corresponds to the latest location file * uploaded to the server. If the state is empty, result is *null*. */ fun recentMarker(): MarkerData? = files.lastOrNull()?.let(markerData::get) /** * Return a list that contains only the files from the passed in list that are not contained in this state. * For these [newFiles] no location information is available and has to be retrieved first from the server. */ fun filterNewFiles(newFiles: List<String>): List<String> = newFiles.filterNot(markerData::containsKey) /** * Return a mutable map that contains all the marker data for the specified [newFiles] that are contained in this * state object. This function can be used when an updated state has been retrieved from the server; then the * data for files already known can be reused. */ fun getKnownMarkers(newFiles: List<String>): MutableMap<String, MarkerData> { val result = mutableMapOf<String, MarkerData>() newFiles.filter(markerData::containsKey) .forEach { file -> result[file] = markerData.getValue(file) } return result } }
0
Kotlin
1
1
b5ab4bc3a65a48d4fff7dbb9c72d7ff8f79db424
3,253
LocationTeller
Apache License 2.0
communication/connection/src/main/kotlin/io/github/mmolosay/datalayercommunication/communication/connection/ConnectionCheckExecutor.kt
mmolosay
594,482,339
false
null
package io.github.mmolosay.datalayercommunication.communication.connection /** * Executes a one-shot connection check between current node and one, specified by implementation. */ fun interface ConnectionCheckExecutor { /** * @return whether nodese are connected or not. */ suspend fun areNodesConnected(): Boolean }
0
Kotlin
1
6
d2514282228dd1cdee2838cf8ed17a512c899099
338
DataLayerCommunication
Apache License 2.0
src/main/kotlin/br/com/zupacademy/shared/KeyManagerGrpcFactory.kt
CharlesRodrigues-01
395,076,592
true
{"Kotlin": 36191, "Smarty": 1872, "Dockerfile": 183}
package br.com.zupacademy.shared import br.com.zupacademy.KeyManagerCarregaGrpcServiceGrpc import br.com.zupacademy.KeyManagerListaGrpcServiceGrpc import br.com.zupacademy.KeyManagerRegistraGrpcServiceGrpc import br.com.zupacademy.KeyManagerRemoveGrpcServiceGrpc import io.grpc.ManagedChannel import io.micronaut.context.annotation.Factory import io.micronaut.grpc.annotation.GrpcChannel import javax.inject.Singleton @Factory class KeyManagerGrpcFactory(@GrpcChannel("keyManager") val channel: ManagedChannel) { @Singleton fun registraChave() : KeyManagerRegistraGrpcServiceGrpc.KeyManagerRegistraGrpcServiceBlockingStub? { return KeyManagerRegistraGrpcServiceGrpc.newBlockingStub(channel) } @Singleton fun deletaChave() : KeyManagerRemoveGrpcServiceGrpc.KeyManagerRemoveGrpcServiceBlockingStub? { return KeyManagerRemoveGrpcServiceGrpc.newBlockingStub(channel) } @Singleton fun carregaChave() : KeyManagerCarregaGrpcServiceGrpc.KeyManagerCarregaGrpcServiceBlockingStub? { return KeyManagerCarregaGrpcServiceGrpc.newBlockingStub(channel) } @Singleton fun listaChave() : KeyManagerListaGrpcServiceGrpc.KeyManagerListaGrpcServiceBlockingStub? { return KeyManagerListaGrpcServiceGrpc.newBlockingStub(channel) } }
0
Kotlin
0
0
6088a94a68ec987b108aac2ff39d7c5edb448d4a
1,296
orange-talents-06-template-pix-keymanager-rest
Apache License 2.0
app/src/main/java/me/cyber/nukleos/ui/control/SensorStuffPresenter.kt
mduisenov
190,605,640
true
{"Kotlin": 173954, "Java": 21369, "Shell": 183}
package me.cyber.nukleos.ui.control import io.reactivex.android.schedulers.AndroidSchedulers import io.reactivex.disposables.Disposable import io.reactivex.schedulers.Schedulers import me.cyber.nukleos.bluetooth.BluetoothConnector import me.cyber.nukleos.dagger.PeripheryManager import me.cyber.nukleos.sensors.Status class SensorStuffPresenter(override val view: SensorControlInterface.View, private val mBluetoothConnector: BluetoothConnector, private val mPeripheryManager: PeripheryManager) : SensorControlInterface.Presenter(view) { private var mSensorStatusSubscription: Disposable? = null private var mSensorControlSubscription: Disposable? = null override fun create() {} override fun start() { with(view) { val selectedSensor = mPeripheryManager.getLastSelectedSensor() if (selectedSensor == null) { disableConnectButton() return } showSensorStuffInformation(selectedSensor.name, selectedSensor.address) enableConnectButton() selectedSensor.apply { mSensorStatusSubscription = this.statusObservable() .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .subscribe { when (it) { Status.CONNECTING -> { showConnectionLoader() showConnecting() showNotScan() } Status.STREAMING -> { hideConnectionLoader() showConnected() showScan() } else -> { hideConnectionLoader() showDisconnected() disableControlPanel() showNotScan() } } } } } } override fun destroy() { mSensorStatusSubscription?.dispose() mSensorControlSubscription?.dispose() } override fun onConnectionButtonClicked() { mPeripheryManager.getLastSelectedSensor()?.apply { if (!isConnected()) { connect() } else { disconnect() } } } override fun onProgressSelected(progress: Int) { val sensor = mPeripheryManager.getLastSelectedSensor() ?: return val availableFrequencies = sensor.getAvailableFrequencies() val selectedFrequency = if (progress >= 0 && progress < availableFrequencies.size) availableFrequencies[progress] else availableFrequencies.last() sensor.setFrequency(selectedFrequency) view.showScanFrequency(selectedFrequency) } override fun onVibrationClicked(vibrationDuration: Int) { mPeripheryManager.getLastSelectedSensor()?.apply { vibration(vibrationDuration) } } }
0
Kotlin
0
0
9ac073e2ccc4419f060fdd3bae643179dd8a7038
3,506
nukleos
Apache License 2.0
src/main/java/org/openwilma/kotlin/classes/courses/WilmaCourseExam.kt
OpenWilma
533,496,981
false
{"Kotlin": 129825}
package org.openwilma.kotlin.classes.courses import java.util.* data class WilmaCourseExam ( val id: Int, val date: Date, val caption: String?, val topic: String?, val timeStart: Date?, val timeEnd: Date?, val grade: String?, val verbalGrade: String? )
0
Kotlin
1
5
52066c9cc2ba77ea37c52c8c0c724e56c1ce7ff2
286
openwilma.kotlin
Apache License 2.0
server/server-app/src/main/kotlin/projektor/notification/NotificationConfig.kt
craigatk
226,096,594
false
null
package projektor.notification import io.ktor.server.config.ApplicationConfig data class NotificationConfig(val serverBaseUrl: String?) { companion object { fun createNotificationConfig(applicationConfig: ApplicationConfig): NotificationConfig { val serverBaseUrl = applicationConfig.propertyOrNull("ktor.notification.serverBaseUrl")?.getString() return NotificationConfig(serverBaseUrl) } } }
14
null
15
47
c6e05fe91deb611f9c56607afb1d1804b0686537
445
projektor
MIT License
src/main/kotlin/org/valkyrienskies/core/networking/ServerHandler.kt
ValkyrienSkies
329,044,944
false
null
package org.valkyrienskies.core.networking import org.valkyrienskies.core.game.IPlayer fun interface ServerHandler { fun handlePacket(packet: Packet, player: IPlayer) }
2
Kotlin
0
1
a9623e844643f6fa3cb38cbaed6ef1f349aaa205
175
vs-core
Apache License 2.0
src/main/java/com/nextcloud/common/IPv4FallbackInterceptor.kt
vince-bourgmayer
483,639,200
true
{"Java Properties": 3, "YAML": 12, "Text": 3, "Gradle": 4, "Shell": 13, "Markdown": 2, "Batchfile": 2, "Ignore List": 2, "XML": 20, "Java": 180, "Ruby": 1, "Kotlin": 66}
/* * Nextcloud Android Library is available under MIT license * * @author รlvaro Brey Vilas * Copyright (C) 2022 รlvaro Brey Vilas * Copyright (C) 2022 Nextcloud GmbH * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS * BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN * ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package com.nextcloud.common import com.owncloud.android.lib.common.utils.Log_OC import okhttp3.ConnectionPool import okhttp3.Interceptor import okhttp3.Request import okhttp3.Response import java.net.ConnectException import java.net.SocketTimeoutException class IPv4FallbackInterceptor(private val connectionPool: ConnectionPool) : Interceptor { companion object { private const val TAG = "IPv4FallbackInterceptor" private val SERVER_ERROR_RANGE = 500..599 } @Suppress("TooGenericExceptionCaught") override fun intercept(chain: Interceptor.Chain): Response { val request = chain.request() val response = chain.proceed(request) val hostname = request.url.host return try { if (response.code in SERVER_ERROR_RANGE && DNSCache.isIPV6First(hostname)) { Log_OC.d(TAG, "Response error with IPv6, trying IPv4") retryWithIPv4(hostname, chain, request) } else { response } } catch (e: Exception) { if (DNSCache.isIPV6First(hostname) && (e is SocketTimeoutException || e is ConnectException)) { return retryWithIPv4(hostname, chain, request) } throw e } } private fun retryWithIPv4( hostname: String, chain: Interceptor.Chain, request: Request ): Response { Log_OC.d(TAG, "Error with IPv6, trying IPv4") DNSCache.setIPVersionPreference(hostname, true) connectionPool.evictAll() return chain.proceed(request) } }
0
null
0
0
f8105d37e8a0217e3f3d985aee2c91a604585cc7
2,872
android-library
MIT License
src/main/kotlin/com/haulmont/astronomy/model/Spaceport.kt
JetBrains
397,227,150
false
{"Kotlin": 28593}
package com.haulmont.astronomy.model import com.haulmont.astronomy.model.basemodel.BaseEntity import org.hibernate.Hibernate import javax.persistence.* @Table(name = "spaceport") @Entity class Spaceport : BaseEntity() { @Column(name = "name") var name: String? = null @ManyToOne(fetch = FetchType.LAZY) @JoinColumn(name = "planet_id") var planet: Planet? = null @ManyToOne(fetch = FetchType.LAZY) @JoinColumn(name = "moon_id") var moon: Moon? = null @Column(name = "is_default") var isDefault: Boolean? = null @Embedded var coordinates: Coordinates? = null @ManyToMany(mappedBy = "spaceports", cascade = [CascadeType.PERSIST, CascadeType.MERGE]) var carriers: MutableSet<Carrier> = mutableSetOf() override fun equals(other: Any?): Boolean { if (this === other) return true if (other == null || Hibernate.getClass(this) != Hibernate.getClass(other)) return false other as Spaceport return id != null && id == other.id } override fun hashCode(): Int = 1790982374 }
0
Kotlin
1
0
7f5041a25af3c1ad22366676f3df62f2dd365897
1,072
jpa-buddy-astronomy-flyway-kt
Apache License 2.0
common/src/commonMain/kotlin/nl/vanparerensoftwaredevelopment/saltthepassmanager/common/ui/components/FormTextField.kt
EwoudVanPareren
682,550,040
false
{"Kotlin": 151573}
@file:OptIn(ExperimentalMaterial3Api::class) package nl.vanparerensoftwaredevelopment.saltthepassmanager.common.ui.components import androidx.compose.foundation.text.KeyboardOptions import androidx.compose.material3.* import androidx.compose.runtime.Composable import androidx.compose.ui.Modifier import androidx.compose.ui.text.input.ImeAction import androidx.compose.ui.text.input.KeyboardType import androidx.compose.ui.text.input.VisualTransformation /** * The app's standard text field, with some convenience methods * to reduce duplication/boilerplate in the codebase. */ object FormTextField { @Composable operator fun invoke( label: String? = null, value: String, onValueChange: (String) -> Unit, singleLine: Boolean = true, readOnly: Boolean = false, keyboardType: KeyboardType = KeyboardType.Text, imeAction: ImeAction = ImeAction.Next, trailingIcon: (@Composable () -> Unit)? = null, visualTransformation: VisualTransformation = VisualTransformation.None, modifier: Modifier = Modifier ) { OutlinedTextField( label = label?.let { { Text(it) } }, value = value, singleLine = singleLine, readOnly = readOnly, keyboardOptions = KeyboardOptions( autoCorrect = false, keyboardType = keyboardType, imeAction = imeAction ), visualTransformation = visualTransformation, trailingIcon = trailingIcon, onValueChange = onValueChange, modifier = modifier ) } @Composable fun ReadOnly( label: String? = null, value: String, singleLine: Boolean = true, keyboardType: KeyboardType = KeyboardType.Text, imeAction: ImeAction = ImeAction.Next, trailingIcon: (@Composable () -> Unit)? = null, visualTransformation: VisualTransformation = VisualTransformation.None, modifier: Modifier = Modifier ) { FormTextField( label = label, value = value, onValueChange = { }, singleLine = singleLine, readOnly = true, keyboardType = keyboardType, visualTransformation = visualTransformation, imeAction = imeAction, trailingIcon = trailingIcon, modifier = modifier ) } }
7
Kotlin
0
0
5a8f1baa96ce111e3b65bb3ac8a6343b6f650ed5
2,452
SaltThePassManager
MIT License
app/src/main/java/com/bikram/practice/fragments/PermissionsFragment.kt
Bmg09
597,787,010
false
{"Gradle": 3, "Java Properties": 2, "Shell": 1, "Ignore List": 3, "Batchfile": 1, "Markdown": 1, "YAML": 1, "JSON": 6, "Proguard": 1, "Java": 31, "XML": 67, "Kotlin": 5}
package com.bikram.practice.fragments import android.Manifest import android.content.Context import android.content.pm.PackageManager import android.os.Bundle import android.widget.Toast import androidx.activity.result.contract.ActivityResultContracts import androidx.core.content.ContextCompat import androidx.fragment.app.Fragment import androidx.lifecycle.lifecycleScope import androidx.navigation.Navigation import com.bikram.practice.R private val PERMISSIONS_REQUIRED = arrayOf(Manifest.permission.CAMERA) class PermissionsFragment : Fragment() { private val requestPermissionLauncher = registerForActivityResult( ActivityResultContracts.RequestPermission() ) { isGranted: Boolean -> if (isGranted) { Toast.makeText(context, "Permission request granted", Toast.LENGTH_LONG).show() navigateToCamera() } else { Toast.makeText(context, "Permission request denied", Toast.LENGTH_LONG).show() } } override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) when (PackageManager.PERMISSION_GRANTED) { ContextCompat.checkSelfPermission( requireContext(), Manifest.permission.CAMERA ) -> { navigateToCamera() } else -> { requestPermissionLauncher.launch( Manifest.permission.CAMERA) } } } private fun navigateToCamera() { lifecycleScope.launchWhenStarted { Navigation.findNavController(requireActivity(), R.id.fragment_container).navigate( PermissionsFragmentDirections.actionPermissionsToCamera()) } } companion object { /** Convenience method used to check if all permissions required by this app are granted */ fun hasPermissions(context: Context) = PERMISSIONS_REQUIRED.all { ContextCompat.checkSelfPermission(context, it) == PackageManager.PERMISSION_GRANTED } } }
0
Java
0
0
980a748b12601bc6a0d3bc019bdd67d40a2534d9
2,098
sign-language-interpreter
The Unlicense
templates/pages/OrdersPageTemplate.kt
joychen03
604,384,582
false
null
package itb.jiafumarc.street.templates.pages import io.ktor.server.html.* import itb.jiafumarc.street.models.Order import itb.jiafumarc.street.models.User import itb.jiafumarc.street.templates.share.FooterTemplate import itb.jiafumarc.street.templates.share.HeadTemplate import itb.jiafumarc.street.templates.share.NavBarTemplate import kotlinx.html.* class OrdersPageTemplate(val user : User) : Template<HTML> { var orders : List<Order> = emptyList() override fun HTML.apply() { head { title{ +"Street - Mis pedidos" } insert(HeadTemplate(), TemplatePlaceholder()) link { href = "/static/css/orders.css" rel = "stylesheet" } } body { insert(NavBarTemplate(user), TemplatePlaceholder()) main { div("container py-5 h-100") { div("row d-flex justify-content-center align-items-center") { orders.forEach { div("col-12 mb-4") { div("card card-stepper") { style = "border-radius: 10px" div("card-body p-4") { div("d-flex justify-content-between align-items-center") { div("d-flex flex-column") { span("small text-muted") { +"""Order ID:""" } span("fs-4 fw-bold") { +"${it.id}" } } div("d-flex flex-column") { span("small text-muted") { +"""Cantidad articulos""" } span("fs-4") { +"${it.lines.count()}" } } div("d-flex flex-column") { span("small text-muted") { +"""Fecha de creaciรณn""" } span("fs-4") { +"${it.createDate?.date}" } } div("d-flex flex-column") { span("small text-muted") { +"""Precio total""" } span("fs-4") { +"${it.totalPrice}โ‚ฌ" } } div { a(classes = "btn btn-primary") { href = "/orders/my-orders/id/${it.id}" +"""Ver detalles""" } } } hr("my-4") { } div("d-flex flex-row justify-content-between align-items-center align-content-center") { span("dot") { } hr("flex-fill track-line") { } span("dot") { } hr("flex-fill track-line") { } span("d-flex justify-content-center align-items-center big-dot dot") { i("fa fa-check text-white") { } } } div("d-flex flex-row justify-content-between align-items-center") { div("col-4 d-flex flex-column align-items-start") { span("text-muted small") { +"${it.createDate?.date}" } span("fw-bold") { +"""Preparando""" } } div("col-4 d-flex flex-column align-items-center") { span("text-muted small") { +"${it.createDate?.date}" } span("fw-bold") { +"""Enviado""" } } div("col-4 d-flex flex-column align-items-end") { span("text-muted small") { +"${it.createDate?.date}" } span("fw-bold") { +"""Entregado""" } } } } } } } } } } insert(FooterTemplate(), TemplatePlaceholder()) } } }
0
Kotlin
0
0
db8b66c1517baf6f4587de6f45edeba5ee30c60f
5,415
street
MIT License
app/src/main/java/juniojsv/minimum/models/Application.kt
JunioJsv
168,070,569
false
{"Kotlin": 63876}
package juniojsv.minimum.models import android.content.Intent import java.util.UUID data class Application( override val label: String, val packageName: String, val launchIntent: Intent, val isNew: Boolean = false, val isPinned: Boolean = false, val group: UUID? = null ) : ApplicationBase(label) { override val priority: Int get() = if (isPinned) 1 else 0 }
1
Kotlin
6
21
3221bd16f1d1495acc166ebd8cb671273a1fedc7
396
minimum
MIT License
inappmessaging/src/test/java/com/rakuten/tech/mobile/inappmessaging/runtime/utils/BuildVersionCheckerSpec.kt
rakutentech
253,402,688
false
null
package com.rakuten.tech.mobile.inappmessaging.runtime.utils import android.os.Build import org.amshove.kluent.shouldBeFalse import org.amshove.kluent.shouldBeTrue import org.junit.Test import org.robolectric.util.ReflectionHelpers class BuildVersionCheckerSpec { @Test fun `should return correctly when calling isNougatAndAbove()`() { setSdkInt(Build.VERSION_CODES.N) BuildVersionChecker.isNougatAndAbove().shouldBeTrue() setSdkInt(Build.VERSION_CODES.N + 1) BuildVersionChecker.isNougatAndAbove().shouldBeTrue() setSdkInt(Build.VERSION_CODES.N - 1) BuildVersionChecker.isNougatAndAbove().shouldBeFalse() } @Test fun `should return correctly when calling isAndroidQAndAbove()`() { setSdkInt(Build.VERSION_CODES.Q) BuildVersionChecker.isAndroidQAndAbove().shouldBeTrue() setSdkInt(Build.VERSION_CODES.Q + 1) BuildVersionChecker.isAndroidQAndAbove().shouldBeTrue() setSdkInt(Build.VERSION_CODES.Q - 1) BuildVersionChecker.isAndroidQAndAbove().shouldBeFalse() } @Test fun `should return correctly when calling isAndroidOAndAbove()`() { setSdkInt(Build.VERSION_CODES.O) BuildVersionChecker.isAndroidOAndAbove().shouldBeTrue() setSdkInt(Build.VERSION_CODES.O + 1) BuildVersionChecker.isAndroidOAndAbove().shouldBeTrue() setSdkInt(Build.VERSION_CODES.O - 1) BuildVersionChecker.isAndroidOAndAbove().shouldBeFalse() } @Test fun `should return correctly when calling isAndroidTAndAbove()`() { setSdkInt(Build.VERSION_CODES.TIRAMISU) BuildVersionChecker.isAndroidTAndAbove().shouldBeTrue() setSdkInt(Build.VERSION_CODES.TIRAMISU + 1) BuildVersionChecker.isAndroidTAndAbove().shouldBeTrue() setSdkInt(Build.VERSION_CODES.TIRAMISU - 1) BuildVersionChecker.isAndroidTAndAbove().shouldBeFalse() } private fun setSdkInt(sdkInt: Int) { ReflectionHelpers.setStaticField(Build.VERSION::class.java, "SDK_INT", sdkInt) } }
0
null
10
7
4a4ffbaee9aa522c0745b6b334f7b5c045de4feb
2,076
android-inappmessaging
MIT License
src/main/kotlin/io/kotest/plugin/intellij/implicits/SpecImplicitUsageProvider.kt
xiaodongw
271,406,256
true
{"Kotlin": 187326, "HTML": 454}
package io.kotest.plugin.intellij.implicits import com.intellij.codeInsight.daemon.ImplicitUsageProvider import com.intellij.psi.PsiElement import io.kotest.plugin.intellij.psi.isSubclassOfSpec import org.jetbrains.kotlin.asJava.classes.KtLightClass import org.jetbrains.kotlin.psi.KtClassOrObject /** * Allows to disable highlighting of certain elements as unused when such elements are not referenced * from the code but are referenced in some other way. * * This [ImplicitUsageProvider] will mark spec classes / objects as used, because a test class * is never referenced by anything but is used. */ class SpecImplicitUsageProvider : ImplicitUsageProvider { override fun isImplicitWrite(element: PsiElement?): Boolean = false override fun isImplicitRead(element: PsiElement?): Boolean = false override fun isImplicitUsage(element: PsiElement?): Boolean { val ktclass = when (element) { is KtClassOrObject -> element is KtLightClass -> element.kotlinOrigin else -> null } return ktclass?.isSubclassOfSpec() ?: false } }
0
null
0
0
6cfe7ef420b55f58f8e7bd1dadfa57c17871b08c
1,089
kotest-intellij-plugin
Apache License 2.0
testerum-backend/testerum-runner/testerum-runner-cmdline/src/main/kotlin/com/testerum/runner_cmdline/runner_tree/builder/factory/RunnerTreeNodeFactory.kt
testerum
241,460,788
false
{"Text": 47, "Gradle Kotlin DSL": 62, "Shell": 17, "Batchfile": 16, "Maven POM": 71, "Java Properties": 2, "Ignore List": 8, "Git Attributes": 1, "EditorConfig": 5, "Markdown": 8, "Kotlin": 1089, "Java": 27, "JSON": 161, "INI": 3, "XML": 30, "JavaScript": 36, "Gherkin": 1, "HTML": 232, "JSON with Comments": 11, "Browserslist": 4, "SVG": 4, "SCSS": 222, "CSS": 12, "YAML": 2, "Dotenv": 1, "Groovy": 1, "Ant Build System": 1}
package com.testerum.runner_cmdline.runner_tree.builder.factory import com.testerum.model.feature.Feature import com.testerum.model.feature.hooks.HookPhase import com.testerum.model.infrastructure.path.HasPath import com.testerum.model.infrastructure.path.Path import com.testerum.model.util.new_tree_builder.ContainerTreeNode import com.testerum.model.util.new_tree_builder.TreeNode import com.testerum.model.util.new_tree_builder.TreeNodeFactory import com.testerum.runner_cmdline.runner_tree.builder.TestWithFilePath import com.testerum.runner_cmdline.runner_tree.builder.factory.impl.RunnerFeatureNodeFactory import com.testerum.runner_cmdline.runner_tree.builder.factory.impl.RunnerParametrizedTestNodeFactory import com.testerum.runner_cmdline.runner_tree.builder.factory.impl.RunnerSuiteNodeFactory import com.testerum.runner_cmdline.runner_tree.builder.factory.impl.RunnerTestNodeFactory import com.testerum.runner_cmdline.runner_tree.nodes.RunnerTreeNode import com.testerum.runner_cmdline.runner_tree.nodes.feature.RunnerFeature import com.testerum.runner_cmdline.runner_tree.nodes.hook.RunnerBasicHook import com.testerum.runner_cmdline.runner_tree.nodes.suite.RunnerSuite import com.testerum.scanner.step_lib_scanner.model.hooks.HookDef class RunnerTreeNodeFactory( hooks: Collection<HookDef>, private val executionName: String?, private val glueClassNames: List<String> ) : TreeNodeFactory<RunnerSuite, RunnerFeature> { private val beforeEachTestBasicHooks: List<RunnerBasicHook> = hooks.sortedBasicHooksForPhase(HookPhase.BEFORE_EACH_TEST) private val afterEachTestBasicHooks: List<RunnerBasicHook> = hooks.sortedBasicHooksForPhase(HookPhase.AFTER_EACH_TEST) private val beforeAllTestsBasicHooks: List<RunnerBasicHook> = hooks.sortedBasicHooksForPhase(HookPhase.BEFORE_ALL_TESTS) private val afterAllTestsBasicHooks: List<RunnerBasicHook> = hooks.sortedBasicHooksForPhase(HookPhase.AFTER_ALL_TESTS) override fun createRootNode(item: HasPath?): RunnerSuite { return RunnerSuiteNodeFactory.create( item, executionName, glueClassNames, beforeAllTestsBasicHooks, afterAllTestsBasicHooks ) } override fun createVirtualContainer(parentNode: ContainerTreeNode, path: Path): RunnerFeature { val parent: RunnerTreeNode = parentNode as? RunnerTreeNode ?: throw IllegalArgumentException("unexpected parent note type [${parentNode.javaClass}]: [$parentNode]") return RunnerFeature( parent = parent, path = path, featureName = path.directories.last(), tags = emptyList(), feature = Feature( name = "", path = Path.EMPTY, ) ) } override fun createNode(parentNode: ContainerTreeNode, item: HasPath): TreeNode { if (parentNode !is RunnerTreeNode) { throw IllegalStateException("unexpected parent type: [${parentNode.javaClass}]: [$parentNode]") } val indexInParent = parentNode.childrenCount return when (item) { is Feature -> RunnerFeatureNodeFactory.create(parentNode, item) is TestWithFilePath -> { val isParametrizedTest = item.test.scenarios.isNotEmpty() if (isParametrizedTest) { RunnerParametrizedTestNodeFactory.create(item, parentNode, indexInParent, beforeEachTestBasicHooks, afterEachTestBasicHooks) } else { RunnerTestNodeFactory.create(item, parentNode, indexInParent, beforeEachTestBasicHooks, afterEachTestBasicHooks) } } else -> throw IllegalArgumentException("unexpected item type [${item.javaClass}]: [$item]") } } private fun Collection<HookDef>.sortedBasicHooksForPhase(phase: HookPhase): List<RunnerBasicHook> { return this.asSequence() .filter { it.phase == phase } .sortedBy { it.order } .map { RunnerBasicHook(it) } .toList() } }
33
Kotlin
3
22
0a53c71b5f659e41282114127f595aad5ab1e4fb
4,098
testerum
Apache License 2.0
app/src/main/java/com/nafanya/tuturutest/model/LocalStorageProvider.kt
AlexSoWhite
470,762,969
false
{"Kotlin": 21314}
package com.nafanya.tuturutest.model import android.content.Context import com.orhanobut.hawk.Hawk class LocalStorageProvider(context: Context) { init { Hawk.init(context).build() } fun put(value: List<Anime>) { Hawk.put("cached", value) } fun get(): List<Anime> { return Hawk.get("cached", listOf()) } }
0
Kotlin
0
0
ef3c51d9ba6a954aa0cc9e1ff01e94f137183832
358
tutu-ru-mibile-internship-test
MIT License
replica-devtools-client/src/main/kotlin/me/aartikov/replica/devtools/client/ObserverIcon.kt
aartikov
438,253,231
false
{"HTML": 3233987, "Kotlin": 685239, "CSS": 29063, "JavaScript": 19875}
package me.aartikov.replica.devtools.client import androidx.compose.runtime.Composable import me.aartikov.replica.devtools.client.view_data.ObserverType import org.jetbrains.compose.web.css.height import org.jetbrains.compose.web.css.marginLeft import org.jetbrains.compose.web.css.px import org.jetbrains.compose.web.css.width @Composable fun ObserverIcon(type: ObserverType) { Container( attrs = { style { marginLeft(16.px) height(24.px) width(24.px) } } ) { when (type) { ObserverType.Active -> ThemedImg("ic_eye_24_black.png") ObserverType.Inactive -> ThemedImg("ic_closed_eye_24_black.png") ObserverType.None -> { // Nothing } } } }
0
HTML
1
33
dc55d0cb727b6854224ceb8b1a1d0d87c7faaddf
819
Replica
MIT License
dsl/src/main/kotlin/io/cloudshiftdev/awscdkdsl/services/quicksight/CfnAnalysisLocalNavigationConfigurationPropertyDsl.kt
cloudshiftinc
667,063,030
false
{"Kotlin": 63959868}
@file:Suppress( "RedundantVisibilityModifier", "RedundantUnitReturnType", "RemoveRedundantQualifierName", "unused", "UnusedImport", "ClassName", "REDUNDANT_PROJECTION", "DEPRECATION" ) package cloudshift.awscdk.dsl.services.quicksight import cloudshift.awscdk.common.CdkDslMarker import kotlin.String import software.amazon.awscdk.services.quicksight.CfnAnalysis /** * The navigation configuration for `CustomActionNavigationOperation` . * * Example: * ``` * // The code below shows an example of how to instantiate this type. * // The values are placeholders you should change. * import software.amazon.awscdk.services.quicksight.*; * LocalNavigationConfigurationProperty localNavigationConfigurationProperty = * LocalNavigationConfigurationProperty.builder() * .targetSheetId("targetSheetId") * .build(); * ``` * * [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-quicksight-analysis-localnavigationconfiguration.html) */ @CdkDslMarker public class CfnAnalysisLocalNavigationConfigurationPropertyDsl { private val cdkBuilder: CfnAnalysis.LocalNavigationConfigurationProperty.Builder = CfnAnalysis.LocalNavigationConfigurationProperty.builder() /** @param targetSheetId The sheet that is targeted for navigation in the same analysis. */ public fun targetSheetId(targetSheetId: String) { cdkBuilder.targetSheetId(targetSheetId) } public fun build(): CfnAnalysis.LocalNavigationConfigurationProperty = cdkBuilder.build() }
3
Kotlin
0
3
c59c6292cf08f0fc3280d61e7f8cff813a608a62
1,554
awscdk-dsl-kotlin
Apache License 2.0
app/app/src/main/java/com/example/genshin_wiki/database/entities/CharacterPortraitEntity.kt
SlavaPerryAyeKruchkovenko
600,055,723
false
null
package com.example.genshin_wiki.database.entities import androidx.room.ColumnInfo import androidx.room.Entity import androidx.room.PrimaryKey @Entity data class CharacterPortraitEntity ( @ColumnInfo(name = "portrait_id") @PrimaryKey val id: String, @ColumnInfo(name = "portrait_image")val image: String, val location: String, val sex: Boolean, val birthday: String, @ColumnInfo(name = "portrait_description")val description: String, val normalAttack: String, val elementalSkill: String, val elementalBurst: String, )
0
Kotlin
0
0
bd98b658211d3a73f12c96a356af3ad95f18ddd4
555
Genshin_Wiki
MIT License
plot-core/src/commonMain/kotlin/org/jetbrains/letsPlot/core/commons/time/interval/MonthInterval.kt
JetBrains
176,771,727
false
null
/* * Copyright (c) 2023. JetBrains s.r.o. * Use of this source code is governed by the MIT license that can be found in the LICENSE file. */ package org.jetbrains.letsPlot.core.commons.time.interval import org.jetbrains.letsPlot.commons.intern.datetime.Date import org.jetbrains.letsPlot.commons.intern.datetime.DateTime import org.jetbrains.letsPlot.commons.intern.datetime.Month internal class MonthInterval(count: Int) : MeasuredInDays(count) { override val tickFormatPattern: String get() = "%b" override fun getFirstDayContaining(instant: DateTime): Date { var firstDay = instant.date firstDay = Date.firstDayOf(firstDay.year, firstDay.month) return firstDay } override fun addInterval(toInstant: DateTime): DateTime { var result = toInstant for (i in 0 until count) { result = addMonth(result) } return result } private fun addMonth(toInstant: DateTime): DateTime { var year = toInstant.year val month = toInstant.month var next = month.next() if (next == null) { next = Month.JANUARY year++ } return DateTime(Date.firstDayOf(year, next)) } }
93
Kotlin
47
889
2fb1fe8e812ed0b84cd32954331a76775e75d4d2
1,235
lets-plot
MIT License
core-data/src/main/java/edts/base/android/core_data/source/remote/InvoiceRemoteDataSource.kt
abahadilah
651,759,726
false
null
package edts.base.android.core_data.source.remote import edts.base.android.core_data.source.remote.network.InvoiceApiService import edts.base.android.core_data.source.remote.request.InvoiceDetailRequest import edts.base.android.core_data.source.remote.request.InvoiceRequest import id.co.edtslib.data.BaseDataSource class InvoiceRemoteDataSource( private val invoiceApiService: InvoiceApiService ) : BaseDataSource() { suspend fun get(id: Long, status: String) = getResult { invoiceApiService.get(InvoiceRequest( partnerId = id, status = status )) } suspend fun getDetail(id: Long) = getResult { invoiceApiService.getDetail(InvoiceDetailRequest( id = id )) } suspend fun getPayments(id: Long, status: String) = getResult { invoiceApiService.getPayments(InvoiceRequest( partnerId = id, status = status )) } }
0
Kotlin
0
0
9d97e941f3dd0b99127dee9218c4c78056f10c52
936
jgo
MIT License
yama-raft/src/main/java/com/song/yama/raft/wal/CommitLog.kt
aCoder2013
161,024,583
false
{"Maven POM": 8, "Text": 1, "Ignore List": 1, "Markdown": 2, "Batchfile": 1, "Shell": 1, "Java": 52, "INI": 1, "Kotlin": 46, "Protocol Buffer": 2, "Java Properties": 1}
/* * Copyright 2018 acoder2013 * * 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. */ /* * Copyright 2018 acoder2013 * * 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.song.yama.raft.wal import com.song.yama.common.utils.Result import com.song.yama.raft.protobuf.RaftProtoBuf import com.song.yama.raft.protobuf.RaftProtoBuf.Entry import com.song.yama.raft.protobuf.RaftProtoBuf.HardState import com.song.yama.raft.protobuf.WALRecord import java.io.Closeable /** * a storage interface for write ahead log WAL is a logical representation of the stable storage. WAL is either in read * mode or append mode but not both. A newly created WAL is in append mode, and ready for appending records. A just * opened WAL is in read mode, and ready for reading records. The WAL will be ready for appending after reading out all * the previous records. */ interface CommitLog : Closeable { fun save(hardState: HardState, ents: List<Entry>): Result<Void> fun saveSnap(snapshot: WALRecord.Snapshot): Result<Void> fun readAll(snapshot: RaftProtoBuf.Snapshot): Result<RaftStateRecord> }
1
null
1
1
fde639d37d2be7fde6cdc8ad845135966e9d335b
2,141
yama
Apache License 2.0
app/src/main/java/eu/kanade/tachiyomi/ui/extension/ExtensionGroupHolder.kt
BakaTekku
357,046,364
true
{"Kotlin": 2259680, "Shell": 1179}
package eu.kanade.tachiyomi.ui.extension import android.annotation.SuppressLint import android.view.View import androidx.recyclerview.widget.RecyclerView import eu.davidea.flexibleadapter.FlexibleAdapter import eu.davidea.flexibleadapter.items.IFlexible import eu.kanade.tachiyomi.databinding.ExtensionCardHeaderBinding import eu.kanade.tachiyomi.ui.base.holder.BaseFlexibleViewHolder class ExtensionGroupHolder(view: View, adapter: FlexibleAdapter<IFlexible<RecyclerView.ViewHolder>>) : BaseFlexibleViewHolder(view, adapter) { private val binding = ExtensionCardHeaderBinding.bind(view) @SuppressLint("SetTextI18n") fun bind(item: ExtensionGroupItem) { binding.title.text = item.name } }
0
null
0
0
e93627c9ecbe917ed2fb36c9c3088ef9e226106d
721
tachiyomiJ2K
Apache License 2.0
app/src/main/java/top/xjunz/tasker/autostart/AutoStartUtil.kt
xjunz
651,527,105
false
{"Kotlin": 1063774, "Java": 386865, "HTML": 67262, "C": 29461, "JavaScript": 16670, "C++": 12159, "AIDL": 4190, "CMake": 1764}
/* * Copyright (c) 2022 xjunz. All rights reserved. */ package top.xjunz.tasker.autostart import android.content.ComponentName import android.content.pm.IPackageManager import android.content.pm.PackageManager import android.system.Os import rikka.shizuku.ShizukuBinderWrapper import rikka.shizuku.ShizukuProvider.MANAGER_APPLICATION_ID import rikka.shizuku.SystemServiceHelper import top.xjunz.tasker.BuildConfig import top.xjunz.tasker.R import top.xjunz.tasker.app import top.xjunz.tasker.ktx.toast import top.xjunz.tasker.service.isPremium import top.xjunz.tasker.util.ShizukuUtil /** * @author xjunz 2021/8/16 */ object AutoStartUtil { private val packageManager get() = app.packageManager private val shizukuAutoStartComponentName by lazy { ComponentName(MANAGER_APPLICATION_ID, "moe.shizuku.manager.starter.BootCompleteReceiver") } private val myAutoStartComponentName by lazy { ComponentName(BuildConfig.APPLICATION_ID, AutoStarter::class.java.name) } private fun enableShizukuAutoStart() = runCatching { val ipm = IPackageManager.Stub.asInterface( ShizukuBinderWrapper(SystemServiceHelper.getSystemService("package")) ) ipm.setComponentEnabledSetting( shizukuAutoStartComponentName, PackageManager.COMPONENT_ENABLED_STATE_ENABLED, PackageManager.DONT_KILL_APP, Os.getuid() / 100_000 ) }.isSuccess val isAutoStartEnabled get() = isPremium && isComponentEnabled( myAutoStartComponentName, false ) && isShizukuAutoStartEnabled fun toggleAutoStart(enabled: Boolean) { if (isAutoStartEnabled == enabled) return if (enabled && !isShizukuAutoStartEnabled && (!ShizukuUtil.isShizukuAvailable || !enableShizukuAutoStart())) { toast(R.string.tip_enable_shizuku_auto_start) ShizukuUtil.launchShizukuManager() return } val newState = if (enabled) { PackageManager.COMPONENT_ENABLED_STATE_ENABLED } else { PackageManager.COMPONENT_ENABLED_STATE_DISABLED } packageManager.setComponentEnabledSetting( myAutoStartComponentName, newState, PackageManager.DONT_KILL_APP ) } private inline val isShizukuAutoStartEnabled get() = isComponentEnabled(shizukuAutoStartComponentName, true) private fun isComponentEnabled(componentName: ComponentName, def: Boolean): Boolean { return try { when (packageManager.getComponentEnabledSetting(componentName)) { PackageManager.COMPONENT_ENABLED_STATE_DISABLED -> false PackageManager.COMPONENT_ENABLED_STATE_ENABLED -> true PackageManager.COMPONENT_ENABLED_STATE_DEFAULT -> def else -> false } } catch (t: Throwable) { false } } }
0
Kotlin
6
23
82893d0db2b13e12d8bee86b4cae0f16abd0e2f4
2,916
AutoTask
Apache License 2.0
app/src/main/kotlin/pl/elpassion/elspace/common/CurrentTimeProvider.kt
cfirmo33
81,125,644
true
{"Kotlin": 230680, "Shell": 2592}
package pl.elpassion.elspace.common object CurrentTimeProvider : Provider<Long>({ System.currentTimeMillis() })
0
Kotlin
0
0
0ba70341d526bff4e9fe73827970a0dbf11c0270
112
el-peon-android
Apache License 2.0
app/src/main/java/com/space/arch/playground/domain/components/details/store/DetailsStoreFactory.kt
atom1cx
872,576,892
false
{"Kotlin": 31849}
package com.space.arch.playground.domain.components.details.store import com.arkivanov.mvikotlin.core.store.Store import com.arkivanov.mvikotlin.core.store.StoreFactory import com.arkivanov.mvikotlin.extensions.coroutines.CoroutineBootstrapper import com.space.arch.playground.domain.components.details.store.DetailsStore.Intent import com.space.arch.playground.domain.components.details.store.DetailsStore.Label import com.space.arch.playground.domain.components.details.store.DetailsStore.State import com.space.arch.playground.domain.repositories.ItemsRepository import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.flow.catch import kotlinx.coroutines.flow.flowOn import kotlinx.coroutines.launch class DetailsStoreFactory( private val storeFactory: StoreFactory, private val repository: ItemsRepository ) { fun create(id: Long): DetailsStore { return DetailsStoreImpl(id) } private inner class DetailsStoreImpl( private val id: Long ) : DetailsStore, Store<Intent, State, Label> by storeFactory.create( name = "DetailsStore", initialState = State.Loading, bootstrapper = DetailsBootstrapper( id = id, repository = repository ), executorFactory = { DetailsExecutor( id = id, repository = repository ) }, reducer = DetailsReducer ) private inner class DetailsBootstrapper( private val id: Long, private val repository: ItemsRepository ) : CoroutineBootstrapper<DetailsStore.Action>() { override fun invoke() { scope.launch { repository.getItem(id) .flowOn(Dispatchers.Default) .catch { dispatch(DetailsStore.Action.PostLoadFailed(it)) } .collect { dispatch(DetailsStore.Action.DataLoaded(it)) } } } } }
0
Kotlin
0
0
32b3edda469c158f1ed431a4f1cffcfdcb8d4f01
2,019
ArchPlayground
MIT License
app/src/main/java/com/bogdan/codeforceswatcher/components/compose/NavigationBar.kt
xorum-io
208,440,935
true
null
package com.bogdan.codeforceswatcher.components.compose import androidx.compose.material.* import androidx.compose.runtime.Composable import androidx.compose.ui.Modifier import androidx.compose.ui.res.painterResource import androidx.compose.ui.unit.dp import com.bogdan.codeforceswatcher.R @Composable fun NavigationBar( modifier: Modifier = Modifier, title: String = "", navigationIcon: Int = R.drawable.ic_path, navigationIconDescription: String? = null, onClick: () -> Unit ) { TopAppBar( title = { Text( text = title, style = MaterialTheme.typography.h6 ) }, navigationIcon = { IconButton( onClick = { onClick() } ) { Icon( painter = painterResource(navigationIcon), contentDescription = navigationIconDescription ) } }, backgroundColor = MaterialTheme.colors.primary, elevation = 0.dp, modifier = modifier ) }
41
Kotlin
15
74
9c87542fc342140bf6d2cb56bd5f41784602b205
1,080
codeforces_watcher
MIT License
core/model/src/commonMain/kotlin/com/rbrauwers/newsapp/model/HeadlinesResponse.kt
rbrauwers
715,620,789
false
{"Kotlin": 102653, "Swift": 781}
package com.rbrauwers.newsapp.model import kotlinx.serialization.Serializable @Serializable data class HeadlinesResponse( val status: String, val totalResults: Int, val articles: List<Article> )
0
Kotlin
0
0
e3c5677dec0b51a6b48587b5ebf97c19240918bf
209
news-app-multiplatform
Apache License 2.0
analysis/analysis-api/testData/components/expressionInfoProvider/isUsedAsExpression/doubleColonClassLHS.kt
JetBrains
3,432,266
false
null
class C { val length = 54 } fun test(): Int { return (<expr>C</expr>::length).get(C()) }
181
null
5748
49,172
33eb9cef3d146062c103f9853d772f0a1da0450e
98
kotlin
Apache License 2.0
samples/sample-core/shared/src/commonMain/kotlin/io/github/vinceglb/sample/core/MainViewModel.kt
vinceglb
782,211,616
false
{"Kotlin": 109013}
package io.github.vinceglb.sample.core import com.rickclephas.kmm.viewmodel.KMMViewModel import com.rickclephas.kmm.viewmodel.coroutineScope import io.github.vinceglb.picker.core.PickerSelectionMode import io.github.vinceglb.picker.core.PickerSelectionType import io.github.vinceglb.picker.core.Picker import io.github.vinceglb.picker.core.PlatformDirectory import io.github.vinceglb.picker.core.PlatformFile import io.github.vinceglb.picker.core.baseName import io.github.vinceglb.picker.core.extension import io.github.vinceglb.picker.core.pickFile import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.StateFlow import kotlinx.coroutines.flow.update import kotlinx.coroutines.launch class MainViewModel : KMMViewModel() { private val _uiState: MutableStateFlow<MainUiState> = MutableStateFlow(MainUiState()) val uiState: StateFlow<MainUiState> = _uiState fun pickImage() = executeWithLoading { // Pick a file val file = Picker.pickFile( type = PickerSelectionType.Image, title = "Custom title here", initialDirectory = downloadDirectoryPath() ) // Add file to the state if (file != null) { val newFiles = _uiState.value.files + file _uiState.update { it.copy(files = newFiles) } } } fun pickImages() = executeWithLoading { // Pick files val files = Picker.pickFile( type = PickerSelectionType.Image, mode = PickerSelectionMode.Multiple ) // Add files to the state if (files != null) { // Add files to the state val newFiles = _uiState.value.files + files _uiState.update { it.copy(files = newFiles) } } } fun pickFile() = executeWithLoading { // Pick a file val file = Picker.pickFile( type = PickerSelectionType.File(extensions = listOf("png")), ) // Add file to the state if (file != null) { val newFiles = _uiState.value.files + file _uiState.update { it.copy(files = newFiles) } } } fun pickFiles() = executeWithLoading { // Pick files val files = Picker.pickFile( type = PickerSelectionType.File(extensions = listOf("png")), mode = PickerSelectionMode.Multiple ) // Add files to the state if (files != null) { val newFiles = _uiState.value.files + files _uiState.update { it.copy(files = newFiles) } } } fun pickDirectory() = executeWithLoading { // Pick a directory val directory = Picker.pickDirectory() // Update the state if (directory != null) { _uiState.update { it.copy(directory = directory) } } } fun saveFile(file: PlatformFile) = executeWithLoading { // Save a file val newFile = Picker.saveFile( bytes = file.readBytes(), baseName = file.baseName, extension = file.extension ) // Add file to the state if (newFile != null) { val newFiles = _uiState.value.files + newFile _uiState.update { it.copy(files = newFiles) } } } private fun executeWithLoading(block: suspend () -> Unit) { viewModelScope.coroutineScope.launch { _uiState.update { it.copy(loading = true) } block() _uiState.update { it.copy(loading = false) } } } } data class MainUiState( val files: Set<PlatformFile> = emptySet(), // Set instead of List to avoid duplicates val directory: PlatformDirectory? = null, val loading: Boolean = false ) { // Used by SwiftUI code constructor() : this(emptySet(), null, false) } expect fun downloadDirectoryPath(): String?
4
Kotlin
0
9
49daeeeb19be8d60a8de2585a2bcd56ff90030ba
3,881
PickerKotlin
MIT License
app/src/main/java/vukan/com/apursp/adapters/CommentsAdapter.kt
Vukan-Markovic
350,144,485
false
null
package vukan.com.apursp.adapters import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.RatingBar import android.widget.TextView import androidx.recyclerview.widget.RecyclerView import vukan.com.apursp.R import vukan.com.apursp.adapters.CommentsAdapter.CommentsViewHolder import vukan.com.apursp.models.Comment class CommentsAdapter(private val comments: List<Comment>) : RecyclerView.Adapter<CommentsViewHolder>() { override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): CommentsViewHolder { return CommentsViewHolder( LayoutInflater.from(parent.context).inflate(R.layout.rating_comment, parent, false) ) } override fun onBindViewHolder(holder: CommentsViewHolder, position: Int) { holder.bind(position) } override fun getItemCount(): Int { return comments.size } inner class CommentsViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) { val comment: TextView = itemView.findViewById(R.id.comment) private val ratingBar: RatingBar = itemView.findViewById(R.id.ratingBar) fun bind(index: Int) { comment.text = comments[index].comment ratingBar.rating = comments[index].grade } } }
0
Kotlin
0
0
ddc120c6be8b5e4069e49b14c4d5c9abf036a454
1,304
Saleroom-converted
MIT License
feature/home/src/main/java/com/reddity/app/home/listing/body/ItemBodyAwardsView.kt
fatih-ozturk
501,051,682
false
null
/* * Copyright 2022 <NAME> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.reddity.app.home.listing.body import androidx.compose.foundation.layout.height import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.width import androidx.compose.foundation.lazy.LazyRow import androidx.compose.foundation.shape.CircleShape import androidx.compose.material.MaterialTheme import androidx.compose.material.Text import androidx.compose.runtime.Composable import androidx.compose.ui.Modifier import androidx.compose.ui.draw.clip import androidx.compose.ui.unit.dp import coil.compose.AsyncImage import com.reddity.app.ui.commons.LocalReddityTextCreator @Composable fun ItemBodyAwardsView( awardList: List<String>, awardCount: Int ) { if (awardList.isEmpty()) return val textCreator = LocalReddityTextCreator.current LazyRow(modifier = Modifier.padding(start = 16.dp), content = { awardList.take(4).forEach { awardImageUrl -> item { AsyncImage( model = awardImageUrl, modifier = Modifier .padding(end = 4.dp) .width(16.dp) .height(16.dp) .clip(CircleShape), contentDescription = "Award" ) } } item { Text( modifier = Modifier.padding(start = 4.dp), text = textCreator.awardCount(awardCount), style = MaterialTheme.typography.caption, color = MaterialTheme.colors.onBackground ) } }) }
2
Kotlin
0
9
173317f3185aad4414e826ea2a34e62c2c210965
2,194
Reddity
Apache License 2.0
app/src/main/java/com/elpet/kaizen/util/extensions/DateTimeExtensions.kt
elpetksa
680,056,870
false
null
package com.elpet.kaizen.util.extensions import android.text.format.DateUtils import java.time.* import java.time.format.DateTimeFormatter import java.time.format.FormatStyle import java.time.temporal.ChronoUnit import java.util.* // โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ” // โ†’ CONVERSION FUNCTIONS // โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜ /** * Converts ISO date string to a [ZonedDateTime] object. This means that date string can contain * offset information. Given string must gave the [style] provider in order to be parsed * successfully. * * This is a `null` and exception safe operation. This means that if this string is an * empty string or not a valid date string, [ZonedDateTime] of `0` timestamp time is returned. * * Notice that this requires a date time zoned string. To parse a single date string, consider * using [toLocalDateTime]. * * @param style Date time format of this string to parse and format. * @param truncateAt Formatter used to format this date to. * * @return A [ZonedDateTime] representing this date string or an object of `0` timestamp time if * parsing failed. */ fun String.toDateTime(style: DateTimeFormatter, truncateAt: ChronoUnit = ChronoUnit.SECONDS): ZonedDateTime { return try { ZonedDateTime .parse(this, style) .truncatedTo(truncateAt) } catch (cause: Throwable) { ZonedDateTime.ofInstant(Instant.ofEpochMilli(0), ZoneId.systemDefault()) } } /** * Converts ISO date string to a [LocalDate] object. This means that date string can contain * offset information. Given string must gave the [style] provider in order to be parsed * successfully. * * This is a `null` and exception safe operation. This means that if this string is an * empty string or not a valid date string, [ZonedDateTime] of `0` timestamp time is returned. * * To parse a zoned date time string, consider using [toDateTime]. * * @param style Date time format of this string to parse and format. * * @return A [ZonedDateTime] representing this date string or an object of `0` timestamp time if * parsing failed. */ fun String.toLocalDateTime(style: DateTimeFormatter): LocalDate { return try { LocalDate .parse(this, style) } catch (cause: Throwable) { LocalDate.now() } } // โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ” // โ†’ STRING FUNCTIONS // โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜ /** * Converts ISO date string to a string using given [formatter]. Given string must have the [style] * provided in order to be parsed successfully. Parsing uses current locale as set in * [JPBApplication.currentLocale] in order to localize returned string and format it * properly. You do not need to set locale or zone to given [formatter]. * * This is a `null` and exception safe operation. This means that if this string is an * empty string or not a valid date string, this string is returned. * * @param style Date time format of this string to parse and format. * @param formatter Formatter used to format this date to. * @param truncateAt [ChronoUnit] to truncate returned string at. * * @return A localized string formatted with given formatter representing this ISO date. Empty * string if this string is `null` or empty or not in valid date format. */ fun String.dateToString(style: DateTimeFormatter, formatter: DateTimeFormatter, truncateAt: ChronoUnit = ChronoUnit.SECONDS): String { return try { this.toDateTime(style, truncateAt) .toString(formatter) } catch (cause: Throwable) { this } } // โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ” // โ†’ LOCAL DATE FUNCTIONS // โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜ /** * Formats this [LocalDate] using the given [formatter]. Parsing uses [Locale.ENGLISH] in * order to localize returned string and format it * properly. You do not need to set locale or zone to given [formatter]. * * @param formatter Formatter used to format this date to. * * @return A localized string formatted with given formatter representing this ISO date. */ fun LocalDate.toString(formatter: DateTimeFormatter): String { return this.format(formatter .withZone(ZoneId.systemDefault()) .withLocale(Locale.ENGLISH)) } fun LocalDate.toMillis(): Long { return this.atStartOfDay(ZoneId.systemDefault()).toInstant().toEpochMilli() } // โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ” // โ†’ ZONED DATETIME FUNCTIONS // โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜ /** * Formats this [ZonedDateTime] using the given [formatter]. Parsing uses [Locale.ENGLISH] in * order to localize returned string and format it * properly. You do not need to set locale or zone to given [formatter]. * * @param formatter Formatter used to format this date to. * * @return A localized string formatted with given formatter representing this ISO date. */ fun ZonedDateTime.toString(formatter: DateTimeFormatter): String { return this.format(formatter .withZone(ZoneId.systemDefault()) .withLocale(Locale.ENGLISH)) } /** * Converts [ZonedDateTime] object to time localized string. This is actually a short call of * [toString] using [DateTimeFormatter.ofLocalizedTime] with [FormatStyle.SHORT] style. * * @return Localized string of this [ZonedDateTime] object. */ fun ZonedDateTime.toShortTime(): String { return this.toString(DateTimeFormatter.ofLocalizedTime(FormatStyle.SHORT)) } /** * Converts [ZonedDateTime] object to time localized string. This is actually a short call of * [toString] using [DateTimeFormatter.ofLocalizedTime] with [FormatStyle.MEDIUM] style. * * @return Localized string of this [ZonedDateTime] object. */ fun ZonedDateTime.toMediumTime(): String { return this.toString(DateTimeFormatter.ofLocalizedTime(FormatStyle.MEDIUM)) } /** * Converts [ZonedDateTime] object to date localized string. This is actually a short call of * [toString] using [DateTimeFormatter.ofLocalizedDate] with [FormatStyle.SHORT] style. * * @return Localized string of this [ZonedDateTime] object. */ fun ZonedDateTime.toShortDate(): String { return this.toString(DateTimeFormatter.ofLocalizedDate(FormatStyle.SHORT)) } /** * Converts [ZonedDateTime] object to date localized string. This is actually a short call of * [toString] using [DateTimeFormatter.ofLocalizedDate] with [FormatStyle.MEDIUM] style. * * @return Localized string of this [ZonedDateTime] object. */ fun ZonedDateTime.toMediumDate(): String { return this.toString(DateTimeFormatter.ofLocalizedDate(FormatStyle.MEDIUM)) } /** * Converts [ZonedDateTime] object to date & time localized string. This is actually a short call of * [toString] using [DateTimeFormatter.ofLocalizedDateTime] with [FormatStyle.SHORT] style. * * @return Localized string of this [ZonedDateTime] object. */ fun ZonedDateTime.toShortDateTime(): String { return this.toString(DateTimeFormatter.ofLocalizedDateTime(FormatStyle.SHORT)) } /** * Converts [ZonedDateTime] object to date & time localized string. This is actually a short call of * [toString] using [DateTimeFormatter.ofLocalizedDateTime] with [FormatStyle.MEDIUM] style. * * @return Localized string of this [ZonedDateTime] object. */ fun ZonedDateTime.toMediumDateTime(): String { return this.toString(DateTimeFormatter.ofLocalizedDateTime(FormatStyle.MEDIUM)) } // โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ” // โ†’ UTIL FUNCTIONS // โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜ /** * Converts ISO date string to timestamp in milliseconds. Given string must have the [style] * provided in order to be parsed successfully. * * This is a `null` and exception safe operation. This means that if this string is `null`, an * empty string or not a valid date string, `0` will be returned. * * @param style Date time format of this string to parse and format. * * @return This date as timestamp in milliseconds. `0` if parsing failed. */ fun String.toMillis(style: DateTimeFormatter): Long { return this.toDateTime(style).toInstant().toEpochMilli() } /** * Converts this timestamp in millis to a [ZonedDateTime]. * * @return A [ZonedDateTime] converted from this timestamp. */ fun Long.toZonedDateTime(): ZonedDateTime { return ZonedDateTime.ofInstant(Instant.ofEpochMilli(this), ZoneId.systemDefault()) } /** * Defines if this [ZonedDateTime] represents this day. This means that the date of this object and * [LocalDate.now] are equal. * * @return `true` if this [ZonedDateTime] is today. `false` otherwise. */ fun ZonedDateTime.isToday(): Boolean { return DateUtils.isToday(this.toInstant().toEpochMilli()) } /** * Defines if this [ZonedDateTime] represents the day after today. This means that the date of this * object and [LocalDate.plusDays] +1 are equal. * * @return `true` if this [ZonedDateTime] is tomorrow. `false` otherwise. */ fun ZonedDateTime.isTomorrow(): Boolean { return DateUtils.isToday(this.toInstant().toEpochMilli() - DateUtils.DAY_IN_MILLIS) } /** * Defines how many units the period between now and this [ZonedDateTime] object has. For example, * if you want to get the seconds between this [ZonedDateTime] object and now object, you can * invoke this function with a unit of [ChronoUnit.SECONDS]. * * @param unit Unit to get the difference between this [ZonedDateTime] and now. * * @return Difference in given [unit] between this [ZonedDateTime] and now. */ fun ZonedDateTime.fromNow(unit: ChronoUnit): Long { return ZonedDateTime.now().until(this, unit) } /** * Defines how many units the period between now and this [LocalDate] object has. For example, * if you want to get the seconds between this [LocalDate] object and now object, you can * invoke this function with a unit of [ChronoUnit.SECONDS]. * * @param unit Unit to get the difference between this [LocalDate] and now. * * @return Difference in given [unit] between this [LocalDate] and now. */ fun LocalDate.fromNow(unit: ChronoUnit): Long { return LocalDate.now().until(this, unit) }
0
Kotlin
0
0
01748377980ca11de2061a9726ff7fb6a2a3b78a
10,669
Kaizen
Apache License 2.0
carioca-report/report-android-compose/src/main/kotlin/com/rubensousa/carioca/report/android/compose/DumpComposeHierarchyInterceptor.kt
rubensousa
853,775,838
false
{"Kotlin": 336232}
/* * Copyright 2019 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /* * Copyright 2024 <NAME> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.rubensousa.carioca.report.android.compose import android.util.Log import com.rubensousa.carioca.report.android.interceptor.CariocaInstrumentedInterceptor import com.rubensousa.carioca.report.android.stage.InstrumentedTestReport import com.rubensousa.carioca.report.runtime.ExecutionMetadata import com.rubensousa.carioca.report.runtime.StageAttachment /** * A [CariocaInstrumentedInterceptor] that dumps the compose hierarchy on test failures * * @param useUnmergedTree Find within merged composables like Buttons */ class DumpComposeHierarchyInterceptor( private val useUnmergedTree: Boolean = true, ) : CariocaInstrumentedInterceptor { override fun onTestFailed(test: InstrumentedTestReport) { super.onTestFailed(test) dump(test) } private fun dump(stage: InstrumentedTestReport) { try { val filename = getFilename(stage.getExecutionMetadata()) val dump = ComposeHierarchyInspector.dump(useUnmergedTree) if (dump.isBlank()) { // No compose hierarchies found, do nothing return } val outputStream = stage.getAttachmentOutputStream(filename) outputStream.use { outputStream.bufferedWriter().apply { write(dump) flush() } } stage.attach( StageAttachment( description = "Compose hierarchy dump", path = filename, mimeType = "text/plain", keepOnSuccess = false ) ) } catch (exception: Exception) { Log.e( "ComposeHierarchyDump", "Failed to dump compose hierarchy", exception ) } } private fun getFilename(metadata: ExecutionMetadata): String { return metadata.uniqueId + "_compose_hierarchy.txt" } }
2
Kotlin
0
1
bc33dbf0f8b288e1950483c5711eebc1c910f8ac
3,182
Carioca
Apache License 2.0
video-sdk/src/main/java/com/kaleyra/video_sdk/call/bottomsheet/BottomSheetContent.kt
KaleyraVideo
686,975,102
false
{"Kotlin": 3462882, "Shell": 7470, "Python": 6756, "Java": 1213}
/* * Copyright 2023 Kaleyra @ https://www.kaleyra.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.kaleyra.video_sdk.call.bottomsheet import androidx.compose.animation.* import androidx.compose.animation.core.tween import androidx.compose.foundation.layout.* import androidx.compose.runtime.* import androidx.compose.runtime.saveable.Saver import androidx.compose.runtime.saveable.rememberSaveable import androidx.compose.ui.Modifier import androidx.compose.ui.graphics.Color import androidx.compose.ui.graphics.toArgb import androidx.compose.ui.platform.testTag import androidx.compose.ui.res.stringResource import androidx.compose.ui.unit.dp import com.kaleyra.video_sdk.call.audiooutput.AudioOutputComponent import com.kaleyra.video_sdk.call.callactions.CallActionsComponent import com.kaleyra.video_sdk.call.callactions.model.CallAction import com.kaleyra.video_sdk.call.fileshare.FileShareComponent import com.kaleyra.video_sdk.call.screenshare.ScreenShareComponent import com.kaleyra.video_sdk.call.virtualbackground.VirtualBackgroundComponent import com.kaleyra.video_sdk.call.whiteboard.WhiteboardComponent import com.kaleyra.video_sdk.R /** * Call Actions Component tag */ const val CallActionsComponentTag = "CallActionsComponentTag" /** * Screen Share Component Tag */ const val ScreenShareComponentTag = "ScreenShareComponentTag" /** * Audio Output Component tag */ const val AudioOutputComponentTag = "AudioOutputComponentTag" /** * File Share Component tag */ const val FileShareComponentTag = "FileShareComponentTag" /** * Whiteboard Component Tag */ const val WhiteboardComponentTag = "WhiteboardComponentTag" /** * Virtual Background Component Tag */ const val VirtualBackgroundComponentTag = "VirtualBackgroundComponentTag" internal enum class BottomSheetComponent { CallActions, AudioOutput, ScreenShare, FileShare, Whiteboard, VirtualBackground } internal class BottomSheetContentState( initialComponent: BottomSheetComponent, initialLineState: LineState ) { var currentComponent: BottomSheetComponent by mutableStateOf(initialComponent) private set var currentLineState: LineState by mutableStateOf(initialLineState) private set fun navigateToComponent(component: BottomSheetComponent) { currentComponent = component } fun expandLine() { currentLineState = LineState.Expanded } fun collapseLine(color: Color? = null) { currentLineState = LineState.Collapsed(argbColor = color?.toArgb()) } companion object { fun Saver(): Saver<BottomSheetContentState, *> = Saver( save = { Pair(it.currentComponent, it.currentLineState) }, restore = { BottomSheetContentState(it.first, it.second) } ) } } @Composable internal fun rememberBottomSheetContentState( initialSheetComponent: BottomSheetComponent, initialLineState: LineState ) = rememberSaveable(saver = BottomSheetContentState.Saver()) { BottomSheetContentState(initialSheetComponent, initialLineState) } @OptIn(ExperimentalAnimationApi::class) @Composable internal fun BottomSheetContent( contentState: BottomSheetContentState, modifier: Modifier = Modifier, onLineClick: () -> Unit = { }, onCallActionClick: (CallAction) -> Unit = { }, onAudioDeviceClick: () -> Unit = { }, onScreenShareTargetClick: () -> Unit = { }, onVirtualBackgroundClick: () -> Unit = {}, contentVisible: Boolean = true, isDarkTheme: Boolean = false, isTesting: Boolean = false ) { Column(modifier) { Line( state = contentState.currentLineState, onClickLabel = stringResource(id = R.string.kaleyra_call_show_buttons), onClick = onLineClick ) AnimatedVisibility( visible = contentVisible, enter = fadeIn(), exit = fadeOut() ) { AnimatedContent( targetState = contentState.currentComponent, transitionSpec = { fadeIn(animationSpec = tween(220, delayMillis = 90)) with fadeOut(animationSpec = tween(90)) }, label = "bottomSheetContent" ) { target -> when (target) { BottomSheetComponent.CallActions -> { CallActionsComponent( onItemClick = { action -> contentState.navigateToComponent( component = when (action) { is CallAction.Audio -> BottomSheetComponent.AudioOutput is CallAction.ScreenShare -> BottomSheetComponent.ScreenShare is CallAction.FileShare -> BottomSheetComponent.FileShare is CallAction.Whiteboard -> BottomSheetComponent.Whiteboard is CallAction.VirtualBackground -> BottomSheetComponent.VirtualBackground else -> BottomSheetComponent.CallActions } ) onCallActionClick(action) }, isDarkTheme = isDarkTheme, modifier = Modifier.testTag(CallActionsComponentTag) ) } BottomSheetComponent.AudioOutput -> { AudioOutputComponent( onDeviceConnected = onAudioDeviceClick, onCloseClick = { contentState.navigateToComponent(BottomSheetComponent.CallActions) }, modifier = Modifier.testTag(AudioOutputComponentTag), isTesting = isTesting ) } BottomSheetComponent.ScreenShare -> { ScreenShareComponent( onItemClick = { onScreenShareTargetClick() }, onCloseClick = { contentState.navigateToComponent(BottomSheetComponent.CallActions) }, modifier = Modifier.testTag(ScreenShareComponentTag) ) } BottomSheetComponent.FileShare -> { FileShareComponent( modifier = Modifier .padding(top = 12.dp) .testTag(FileShareComponentTag), isTesting = isTesting ) } BottomSheetComponent.Whiteboard -> { WhiteboardComponent( modifier = Modifier .padding(top = 12.dp) .testTag(WhiteboardComponentTag) ) } BottomSheetComponent.VirtualBackground -> { VirtualBackgroundComponent( onItemClick = { onVirtualBackgroundClick() }, onCloseClick = { contentState.navigateToComponent(BottomSheetComponent.CallActions) }, modifier = Modifier .testTag(VirtualBackgroundComponentTag) ) } } } } } }
1
Kotlin
0
1
7f916f3eb2ae9157c35125711625a43f3223fd00
8,098
VideoAndroidSDK
Apache License 2.0
data/src/main/java/com/pp/moviefy/data/di/RepositoriesModule.kt
pauloaapereira
356,418,263
false
null
/* * Copyright 2021 <NAME> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * 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.pp.moviefy.data.di import com.pp.moviefy.data.repositories.AuthRepository import com.pp.moviefy.data.repositories.MoviesRepository import com.pp.moviefy.domain.repositories.IAuthRepository import com.pp.moviefy.domain.repositories.IMoviesRepository import dagger.Binds import dagger.Module import dagger.hilt.InstallIn import dagger.hilt.components.SingletonComponent @Module @InstallIn(SingletonComponent::class) interface RepositoriesModule { @Binds fun bindAuthRepository( authRepository: AuthRepository ): IAuthRepository @Binds fun bindMoviesRepository( moviesRepository: MoviesRepository ): IMoviesRepository }
0
Kotlin
0
0
e174b88ab2397720c47f81c06603794e142bd91f
1,264
Moviefy
Apache License 2.0
app/src/main/java/org/simple/clinic/registration/phone/PhoneNumberValidator.kt
pratul
151,071,054
false
null
package org.simple.clinic.registration.phone interface PhoneNumberValidator { fun isValid(number: String): Boolean } class IndianPhoneNumberValidator : PhoneNumberValidator { override fun isValid(number: String): Boolean { return number.length == 10 } }
0
Kotlin
0
1
fa311d989cac0a167070f2e1e466191919b659b8
267
citest
MIT License
src/main/kotlin/com/nahum/spotifyclient/service/SpotifyClientService.kt
nahumrahim
432,862,596
false
{"Kotlin": 7491}
package com.nahum.spotifyclient.service import org.apache.hc.core5.http.ParseException import org.springframework.beans.factory.annotation.Autowired import org.springframework.beans.factory.annotation.Value import org.springframework.stereotype.Service import se.michaelthelin.spotify.SpotifyApi import se.michaelthelin.spotify.exceptions.SpotifyWebApiException import se.michaelthelin.spotify.model_objects.specification.Track import java.io.IOException import javax.annotation.PostConstruct @Service class SpotifyClientService { private var clientId: String? = null private var clientSecret: String? = null private var spotifyApi: SpotifyApi? = null @Autowired constructor( @Value("\${spotify.client-id}") pClientId:String, @Value("\${spotify.client-secret}") pClientSecret: String ) { this.clientId = pClientId this.clientSecret = pClientSecret } @PostConstruct private fun postConstructInit() { this.spotifyApi = SpotifyApi.Builder() .setClientId(clientId) .setClientSecret(clientSecret) .build() } /** * Get remote Spotify credentials and set access token * * @return */ private fun clientCredentialsSync() { try { val clientCredentialsRequest = this.spotifyApi?.clientCredentials() ?.build() val clientCredentials = clientCredentialsRequest?.execute() this.spotifyApi?.accessToken = clientCredentials?.accessToken println("Expires in: " + clientCredentials?.expiresIn) } catch (e: IOException) { println("Error: " + e.message) } catch (e: SpotifyWebApiException) { println("Error: " + e.message) } catch (e: ParseException) { println("Error: " + e.message) } } /** * Retrieve the first track that matches to a query on Spotify * * @return a remote Spotify Track or null */ fun searchTracksSync(q: String): Track? { // Call everytime and set a new token clientCredentialsSync(); try { val searchTracksRequest = this.spotifyApi?.searchTracks("isrc:$q") ?.build() val trackPaging = searchTracksRequest?.execute() if (trackPaging != null && trackPaging.total > 0) { println("Total: " + trackPaging.total) return trackPaging.items[0] } else { return null; } } catch (e: IOException) { println("Error: " + e.message) } catch (e: SpotifyWebApiException) { println("Error: " + e.message) } catch (e: ParseException) { println("Error: " + e.message) } return null; } }
0
Kotlin
0
0
aecbd5d26f245f65efc44ad6f2a870c73ecc8f68
2,819
spring-boot-spotify-client
MIT License
libs/pandautils/src/androidTest/java/com/instructure/pandautils/room/offline/daos/FileFolderDaoTest.kt
instructure
179,290,947
false
null
/* * Copyright (C) 2023 - present Instructure, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * */ package com.instructure.pandautils.room.offline.daos import android.content.Context import androidx.room.Room import androidx.test.core.app.ApplicationProvider import com.instructure.canvasapi2.models.Course import com.instructure.canvasapi2.models.FileFolder import com.instructure.pandautils.room.offline.OfflineDatabase import com.instructure.pandautils.room.offline.entities.CourseEntity import com.instructure.pandautils.room.offline.entities.CourseSyncSettingsEntity import com.instructure.pandautils.room.offline.entities.FileFolderEntity import com.instructure.pandautils.room.offline.entities.FileSyncSettingsEntity import com.instructure.pandautils.room.offline.entities.LocalFileEntity import junit.framework.TestCase.assertEquals import kotlinx.coroutines.ExperimentalCoroutinesApi import kotlinx.coroutines.test.runTest import org.junit.Before import org.junit.Test import java.util.Date @ExperimentalCoroutinesApi class FileFolderDaoTest { private lateinit var db: OfflineDatabase private lateinit var fileFolderDao: FileFolderDao private lateinit var localFileDao: LocalFileDao private lateinit var fileSyncSettingsDao: FileSyncSettingsDao private lateinit var courseDao: CourseDao private lateinit var courseSyncSettingsDao: CourseSyncSettingsDao @Before fun setUp() = runTest { val context = ApplicationProvider.getApplicationContext<Context>() db = Room.inMemoryDatabaseBuilder(context, OfflineDatabase::class.java).build() fileFolderDao = db.fileFolderDao() localFileDao = db.localFileDao() fileSyncSettingsDao = db.fileSyncSettingsDao() courseDao = db.courseDao() courseSyncSettingsDao = db.courseSyncSettingsDao() } @Test fun testInsertReplace() = runTest { val fileFolder = FileFolderEntity(FileFolder(id = 1L, name = "original")) val updated = FileFolderEntity(FileFolder(id = 1L, name = "updated")) fileFolderDao.insert(fileFolder) fileFolderDao.insert(updated) val result = fileFolderDao.findById(1L) assertEquals(updated, result) } @Test fun testDeleteAll() = runTest { val files = listOf( FileFolderEntity(FileFolder(id = 1L, name = "original1")), FileFolderEntity(FileFolder(id = 2L, name = "original2")) ) fileFolderDao.insertAll(files) fileFolderDao.deleteAllByCourseId(1L) val result = fileFolderDao.findAllFilesByCourseId(1L) assertEquals(emptyList<FileFolderEntity>(), result) } @Test fun testFindAllByCourseId() = runTest { val folders = listOf( FileFolderEntity( FileFolder( id = 1L, contextId = 1L, contextType = "Course", name = "folder", parentFolderId = 0 ) ), FileFolderEntity( FileFolder( id = 2L, contextId = 1L, contextType = "Course", name = "folder2", parentFolderId = 0 ) ), FileFolderEntity( FileFolder( id = 3L, contextId = 2L, contextType = "Course", name = "folder2", parentFolderId = 0 ) ) ) val files = listOf( FileFolderEntity(FileFolder(id = 4L, name = "file1", folderId = 1L)), FileFolderEntity(FileFolder(id = 5L, name = "file2", folderId = 2L)), FileFolderEntity(FileFolder(id = 6L, name = "file3", folderId = 3L)) ) fileFolderDao.insertAll(folders) fileFolderDao.insertAll(files) val result = fileFolderDao.findAllFilesByCourseId(1L) assertEquals(files.subList(0, 2), result) } @Test fun testFindById() = runTest { val files = listOf( FileFolderEntity(FileFolder(id = 1L, name = "file1")), FileFolderEntity(FileFolder(id = 2L, name = "file2")) ) fileFolderDao.insertAll(files) val result = fileFolderDao.findById(1L) assertEquals(files[0], result) } @Test fun testFindFoldersByParentId() = runTest { val folders = listOf( FileFolderEntity(FileFolder(id = 1L, name = "folder1", parentFolderId = 0)), FileFolderEntity(FileFolder(id = 2L, name = "folder2", parentFolderId = 0)), FileFolderEntity(FileFolder(id = 3L, name = "folder3", parentFolderId = 1L)), FileFolderEntity(FileFolder(id = 4L, name = "folder4", parentFolderId = 1L)), FileFolderEntity(FileFolder(id = 5L, name = "folder5", parentFolderId = 2L)), FileFolderEntity(FileFolder(id = 6L, name = "folder6", parentFolderId = 2L)) ) fileFolderDao.insertAll(folders) val result = fileFolderDao.findFoldersByParentId(1L) assertEquals(folders.subList(2, 4), result) } @Test fun testFindFilesByFolderId() = runTest { val folders = listOf( FileFolderEntity(FileFolder(id = 1L, name = "folder1", parentFolderId = 0)), FileFolderEntity(FileFolder(id = 2L, name = "folder2", parentFolderId = 0)) ) val files = listOf( FileFolderEntity(FileFolder(id = 3L, name = "file1", folderId = 1L)), FileFolderEntity(FileFolder(id = 4L, name = "file2", folderId = 1L)), FileFolderEntity(FileFolder(id = 5L, name = "file3", folderId = 2L)), FileFolderEntity(FileFolder(id = 6L, name = "file4", folderId = 2L)) ) fileFolderDao.insertAll(folders) fileFolderDao.insertAll(files) val result = fileFolderDao.findFilesByFolderId(1L) assertEquals(files.subList(0, 2), result) } @Test fun testFindRootFolderForContext() = runTest { val folders = listOf( FileFolderEntity( FileFolder( id = 1L, name = "folder1", parentFolderId = 0, contextId = 1L, contextType = "Course" ) ), FileFolderEntity( FileFolder( id = 2L, name = "folder2", parentFolderId = 0, contextId = 2L, contextType = "Course" ) ), ) fileFolderDao.insertAll(folders) val result = fileFolderDao.findRootFolderForContext(1L) assertEquals(folders[0], result) } @Test fun testReplaceAll() = runTest { val files = listOf( FileFolderEntity(FileFolder(id = 1L, name = "file1", folderId = 1L, contextId = 1L)), FileFolderEntity(FileFolder(id = 2L, name = "file2", folderId = 1L, contextId = 1L)) ) val newFiles = listOf( FileFolderEntity(FileFolder(id = 3L, name = "file3", folderId = 1L, contextId = 1L)), FileFolderEntity(FileFolder(id = 4L, name = "file4", folderId = 1L, contextId = 1L)) ) fileFolderDao.insertAll(files) fileFolderDao.replaceAll(newFiles, 1L) val result = fileFolderDao.findFilesByFolderId(1L) assertEquals(newFiles, result) } @Test fun testFindFilesToSyncCreatedDate() = runTest { courseDao.insert(CourseEntity(Course(id = 1L, name = "course1"))) courseDao.insert(CourseEntity(Course(id = 2L, name = "course2"))) val localFiles = listOf( LocalFileEntity(id = 3L, path = "file1", courseId = 1L, createdDate = Date(1)), LocalFileEntity(id = 4L, path = "file2", courseId = 1L, createdDate = Date(1)), LocalFileEntity(id = 5L, path = "file3", courseId = 2L, createdDate = Date(1000)), LocalFileEntity(id = 6L, path = "file4", courseId = 2L, createdDate = Date(1000)) ) localFiles.forEach { localFileDao.insert(it) } val folders = listOf( FileFolderEntity( FileFolder( id = 1L, name = "folder1", parentFolderId = 0, contextId = 1L, contextType = "Course" ) ), FileFolderEntity( FileFolder( id = 2L, name = "folder2", parentFolderId = 0, contextId = 2L, contextType = "Course" ) ), ) fileFolderDao.insertAll(folders) val remoteFiles = listOf( FileFolderEntity(FileFolder(id = 3L, name = "file1", folderId = 1L, createdDate = Date(2))), FileFolderEntity(FileFolder(id = 4L, name = "file2", folderId = 1L, createdDate = Date(1))), FileFolderEntity(FileFolder(id = 5L, name = "file3", folderId = 2L, createdDate = Date(1000))), FileFolderEntity(FileFolder(id = 6L, name = "file4", folderId = 2L, createdDate = Date(1000))) ) fileFolderDao.insertAll(remoteFiles) val result = fileFolderDao.findFilesToSync(1L, true) assertEquals(listOf(remoteFiles[0]), result) } @Test fun testFindFilesToSyncUpdatedDate() = runTest { courseDao.insert(CourseEntity(Course(id = 1L, name = "course1"))) courseDao.insert(CourseEntity(Course(id = 2L, name = "course2"))) val localFiles = listOf( LocalFileEntity(id = 3L, path = "file1", courseId = 1L, createdDate = Date(1)), LocalFileEntity(id = 4L, path = "file2", courseId = 1L, createdDate = Date(1)), LocalFileEntity(id = 5L, path = "file3", courseId = 2L, createdDate = Date(1000)), LocalFileEntity(id = 6L, path = "file4", courseId = 2L, createdDate = Date(1000)) ) localFiles.forEach { localFileDao.insert(it) } val folders = listOf( FileFolderEntity( FileFolder( id = 1L, name = "folder1", parentFolderId = 0, contextId = 1L, contextType = "Course" ) ), FileFolderEntity( FileFolder( id = 2L, name = "folder2", parentFolderId = 0, contextId = 2L, contextType = "Course" ) ), ) fileFolderDao.insertAll(folders) val remoteFiles = listOf( FileFolderEntity(FileFolder(id = 3L, name = "file1", folderId = 1L, updatedDate = Date(2))), FileFolderEntity(FileFolder(id = 4L, name = "file2", folderId = 1L, updatedDate = Date(1))), FileFolderEntity(FileFolder(id = 5L, name = "file3", folderId = 2L, updatedDate = Date(1000))), FileFolderEntity(FileFolder(id = 6L, name = "file4", folderId = 2L, updatedDate = Date(1000))) ) fileFolderDao.insertAll(remoteFiles) val result = fileFolderDao.findFilesToSync(1L, true) assertEquals(listOf(remoteFiles[0]), result) } @Test fun testFindFilesToSyncNoLocalFiles() = runTest { courseDao.insert(CourseEntity(Course(id = 1L, name = "course1"))) courseDao.insert(CourseEntity(Course(id = 2L, name = "course2"))) val folders = listOf( FileFolderEntity( FileFolder( id = 1L, name = "folder1", parentFolderId = 0, contextId = 1L, contextType = "Course" ) ), FileFolderEntity( FileFolder( id = 2L, name = "folder2", parentFolderId = 0, contextId = 2L, contextType = "Course" ) ), ) fileFolderDao.insertAll(folders) val remoteFiles = listOf( FileFolderEntity(FileFolder(id = 3L, name = "file1", folderId = 1L, createdDate = Date(1))), FileFolderEntity(FileFolder(id = 4L, name = "file2", folderId = 1L, createdDate = Date(1))), FileFolderEntity(FileFolder(id = 5L, name = "file3", folderId = 2L, createdDate = Date(1000))), FileFolderEntity(FileFolder(id = 6L, name = "file4", folderId = 2L, createdDate = Date(1000))) ) fileFolderDao.insertAll(remoteFiles) val result = fileFolderDao.findFilesToSync(2L, true) assertEquals(remoteFiles.subList(2, 4), result) } @Test fun testFindFilesToSyncSyncSettingsNoLocalFiles() = runTest { courseDao.insert(CourseEntity(Course(id = 1L, name = "course1"))) val courseSyncSettings = CourseSyncSettingsEntity(courseId = 1L, courseName = "Course 1", fullContentSync = true) courseSyncSettingsDao.insert(courseSyncSettings) val fileSyncSettings = FileSyncSettingsEntity(id = 3L, courseId = 1L, fileName = "file1", url = "url1") fileSyncSettingsDao.insert(fileSyncSettings) val folders = listOf( FileFolderEntity( FileFolder( id = 1L, name = "folder1", parentFolderId = 0, contextId = 1L, contextType = "Course" ) ) ) fileFolderDao.insertAll(folders) val remoteFiles = listOf( FileFolderEntity(FileFolder(id = 3L, name = "file1", folderId = 1L, createdDate = Date(1))), FileFolderEntity(FileFolder(id = 4L, name = "file2", folderId = 1L, createdDate = Date(1))) ) fileFolderDao.insertAll(remoteFiles) val result = fileFolderDao.findFilesToSync(1L, false) assertEquals(listOf(remoteFiles[0]), result) } @Test fun testFindFileToSyncFull() = runTest { courseDao.insert(CourseEntity(Course(id = 1L, name = "course1"))) courseDao.insert(CourseEntity(Course(id = 2L, name = "course2"))) val localFiles = listOf( LocalFileEntity(id = 3L, path = "createAt", courseId = 1L, createdDate = Date(1)), LocalFileEntity(id = 4L, path = "no update", courseId = 1L, createdDate = Date(1)), LocalFileEntity(id = 5L, path = "updatedAt", courseId = 1L, createdDate = Date(1)), LocalFileEntity(id = 7L, path = "file4", courseId = 2L, createdDate = Date(1000)), LocalFileEntity(id = 8L, path = "file5", courseId = 2L, createdDate = Date(1000)) ) localFiles.forEach { localFileDao.insert(it) } val folders = listOf( FileFolderEntity( FileFolder( id = 1L, name = "folder1", parentFolderId = 0, contextId = 1L, contextType = "Course" ) ), FileFolderEntity( FileFolder( id = 2L, name = "folder2", parentFolderId = 0, contextId = 2L, contextType = "Course" ) ), ) fileFolderDao.insertAll(folders) val remoteFiles = listOf( FileFolderEntity(FileFolder(id = 3L, name = "createdAt", folderId = 1L, createdDate = Date(2))), FileFolderEntity(FileFolder(id = 4L, name = "no update", folderId = 1L, createdDate = Date(1))), FileFolderEntity(FileFolder(id = 5L, name = "updatedAt", folderId = 1L, updatedDate = Date(2))), FileFolderEntity(FileFolder(id = 6L, name = "not synced", folderId = 1L, updatedDate = Date(1))), FileFolderEntity(FileFolder(id = 7L, name = "file4", folderId = 2L, createdDate = Date(1000))), FileFolderEntity(FileFolder(id = 8L, name = "file5", folderId = 2L, createdDate = Date(1000))) ) fileFolderDao.insertAll(remoteFiles) val result = fileFolderDao.findFilesToSync(1L, true) assertEquals(listOf(remoteFiles[0], remoteFiles[2], remoteFiles[3]), result) } @Test fun testFindFileToSyncSelected() = runTest { courseDao.insert(CourseEntity(Course(id = 1L, name = "course1"))) courseDao.insert(CourseEntity(Course(id = 2L, name = "course2"))) val courseSyncSettings = CourseSyncSettingsEntity(courseId = 1L, courseName = "Course 1", fullContentSync = false) courseSyncSettingsDao.insert(courseSyncSettings) val fileSyncSettings = listOf( FileSyncSettingsEntity(id = 3L, courseId = 1L, fileName = "file1", url = "url1"), FileSyncSettingsEntity(id = 4L, courseId = 1L, fileName = "file3", url = "url3"), FileSyncSettingsEntity(id = 6L, courseId = 1L, fileName = "file4", url = "url4"), ) fileSyncSettingsDao.insertAll(fileSyncSettings) val localFiles = listOf( LocalFileEntity(id = 3L, path = "createAt", courseId = 1L, createdDate = Date(1)), LocalFileEntity(id = 4L, path = "no update", courseId = 1L, createdDate = Date(1)), LocalFileEntity(id = 5L, path = "updatedAt", courseId = 1L, createdDate = Date(1)), LocalFileEntity(id = 7L, path = "file4", courseId = 2L, createdDate = Date(1000)), LocalFileEntity(id = 8L, path = "file5", courseId = 2L, createdDate = Date(1000)) ) localFiles.forEach { localFileDao.insert(it) } val folders = listOf( FileFolderEntity( FileFolder( id = 1L, name = "folder1", parentFolderId = 0, contextId = 1L, contextType = "Course" ) ), FileFolderEntity( FileFolder( id = 2L, name = "folder2", parentFolderId = 0, contextId = 2L, contextType = "Course" ) ), ) fileFolderDao.insertAll(folders) val remoteFiles = listOf( FileFolderEntity(FileFolder(id = 3L, name = "createdAt", folderId = 1L, createdDate = Date(2))), FileFolderEntity(FileFolder(id = 4L, name = "no update", folderId = 1L, createdDate = Date(1))), FileFolderEntity(FileFolder(id = 5L, name = "updatedAt", folderId = 1L, updatedDate = Date(2))), FileFolderEntity(FileFolder(id = 6L, name = "not synced", folderId = 1L, updatedDate = Date(1))), FileFolderEntity(FileFolder(id = 7L, name = "file4", folderId = 2L, createdDate = Date(1000))), FileFolderEntity(FileFolder(id = 8L, name = "file5", folderId = 2L, createdDate = Date(1000))) ) fileFolderDao.insertAll(remoteFiles) val result = fileFolderDao.findFilesToSync(1L, false) assertEquals(listOf(remoteFiles[0], remoteFiles[3]), result) } @Test fun testFindByIds() = runTest { val files = listOf( FileFolderEntity(FileFolder(id = 1L, name = "file1")), FileFolderEntity(FileFolder(id = 2L, name = "file2")), FileFolderEntity(FileFolder(id = 3L, name = "file3")) ) fileFolderDao.insertAll(files) val result = fileFolderDao.findByIds(setOf(1, 2)) assertEquals(listOf(files[0], files[1]), result) } @Test fun testDeleteAllByCourseIdDeleteFilesWhereParentFolderHasCourseId() = runTest { val files = listOf( FileFolderEntity(FileFolder(id = 1L, name = "file1", folderId = 1L, contextId = 1L)), FileFolderEntity(FileFolder(id = 2L, name = "file2", folderId = 1L)), FileFolderEntity(FileFolder(id = 3L, name = "file2", folderId = 2L)), ) fileFolderDao.insertAll(files) fileFolderDao.deleteAllByCourseId(1L) val result = fileFolderDao.findByIds(setOf(1, 2, 3)) assertEquals(listOf(files[2]), result) } }
7
null
91
127
ca6e2aeaeedb851003af5497e64c22e02dbf0db8
21,060
canvas-android
Apache License 2.0
src/main/kotlin/com/github/flagshipio/jetbrain/toolWindow/flagsInFile/FileNodeViewModel.kt
flagship-io
691,142,277
false
{"Kotlin": 285241}
package com.github.flagshipio.jetbrain.toolWindow.flagsInFile import com.github.flagshipio.jetbrain.dataClass.FileAnalyzed class FileNodeViewModel( val file: FileAnalyzed, ) { var fileName = file.file var flagInFile = file.results }
2
Kotlin
0
0
969ae2d62b2dd73e9082d95e0f427b066207b07c
247
flagship-jetbrain
Apache License 2.0
HelloKotlin/app/src/main/java/com/mjiayou/hellokotlin/view/MovieFragment.kt
treason258
64,649,980
false
null
package com.mjiayou.hellokotlin.view import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.databinding.DataBindingUtil import androidx.fragment.app.Fragment import androidx.recyclerview.widget.DefaultItemAnimator import androidx.recyclerview.widget.LinearLayoutManager import com.mjiayou.hellokotlin.R import com.mjiayou.hellokotlin.databinding.FragmentMovieBinding import com.mjiayou.hellokotlin.viewmodel.MovieViewModel class MovieFragment : Fragment() { lateinit var mMovieAdapter: MovieAdapter lateinit var mBinding: FragmentMovieBinding companion object { private val INSTANCE = MovieFragment() fun getInstance(): MovieFragment { return INSTANCE } } override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? { mBinding = DataBindingUtil.inflate(inflater, R.layout.fragment_movie, container, false) mMovieAdapter = MovieAdapter(context) mBinding.rvMusic.layoutManager = LinearLayoutManager(context, LinearLayoutManager.VERTICAL, false) mBinding.rvMusic.itemAnimator = DefaultItemAnimator() mBinding.rvMusic.adapter = mMovieAdapter mBinding.viewModel = MovieViewModel(mMovieAdapter) return mBinding.root } }
9
null
1
1
ccf463763518e40696a2cb7e7b95d6a7644fcf6b
1,364
TreLibrary
Apache License 2.0
app/src/main/java/com/boringdroid/systemui/data/Control.kt
openfde
777,502,927
false
{"Kotlin": 278662, "Java": 116706, "C++": 8520, "CMake": 1647, "AIDL": 1167}
package com.boringdroid.systemui.data open class Control(val control :Int, val iconUnCheck: Int, val iconChecked: Int, val name : Int, val controlUnCheck :Int, val controlChecked :Int,val checked: Boolean)
0
Kotlin
0
0
b8a1d052e90ca5cd7c655c51884e321b03266db8
225
boringdroidsystemui
Apache License 2.0
ui/src/commonMain/kotlin/com/popalay/barnee/ui/screen/drink/DrinkScreen.kt
Popalay
349,051,151
false
null
/* * Copyright (c) 2023 <NAME> * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package com.popalay.barnee.ui.screen.drink import androidx.compose.animation.AnimatedVisibility import androidx.compose.animation.Crossfade import androidx.compose.animation.core.animateIntAsState import androidx.compose.animation.fadeIn import androidx.compose.animation.fadeOut import androidx.compose.animation.slideInVertically import androidx.compose.foundation.background import androidx.compose.foundation.clickable import androidx.compose.foundation.interaction.MutableInteractionSource import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.BoxWithConstraints import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.ExperimentalLayoutApi import androidx.compose.foundation.layout.FlowRow import androidx.compose.foundation.layout.PaddingValues import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.Spacer import androidx.compose.foundation.layout.WindowInsets import androidx.compose.foundation.layout.aspectRatio import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.height import androidx.compose.foundation.layout.offset import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.size import androidx.compose.foundation.layout.width import androidx.compose.foundation.layout.windowInsetsBottomHeight import androidx.compose.foundation.lazy.LazyColumn import androidx.compose.foundation.lazy.LazyListState import androidx.compose.foundation.lazy.rememberLazyListState import androidx.compose.foundation.shape.CircleShape import androidx.compose.material.ButtonDefaults import androidx.compose.material.Card import androidx.compose.material.ContentAlpha import androidx.compose.material.Divider import androidx.compose.material.Icon import androidx.compose.material.IconButton import androidx.compose.material.LocalContentAlpha import androidx.compose.material.LocalContentColor import androidx.compose.material.MaterialTheme import androidx.compose.material.Surface import androidx.compose.material.Text import androidx.compose.material.TextButton import androidx.compose.material.icons.Icons import androidx.compose.material.icons.filled.PlayArrow import androidx.compose.material.icons.filled.Share import androidx.compose.runtime.Composable import androidx.compose.runtime.CompositionLocalProvider import androidx.compose.runtime.derivedStateOf import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.runtime.saveable.rememberSaveable import androidx.compose.runtime.setValue import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.draw.alpha import androidx.compose.ui.draw.clip import androidx.compose.ui.draw.rotate import androidx.compose.ui.graphics.BlendMode import androidx.compose.ui.graphics.Color import androidx.compose.ui.graphics.ColorFilter import androidx.compose.ui.platform.LocalDensity import androidx.compose.ui.text.style.TextOverflow import androidx.compose.ui.unit.IntOffset import androidx.compose.ui.unit.dp import com.moriatsushi.insetsx.navigationBars import com.moriatsushi.insetsx.statusBars import com.moriatsushi.insetsx.statusBarsPadding import com.popalay.barnee.data.model.Category import com.popalay.barnee.data.model.Drink import com.popalay.barnee.data.model.DrinkMinimumData import com.popalay.barnee.data.model.FullDrinkResponse import com.popalay.barnee.data.model.Ingredient import com.popalay.barnee.data.model.Instruction import com.popalay.barnee.domain.Action import com.popalay.barnee.domain.Result import com.popalay.barnee.domain.Success import com.popalay.barnee.domain.drink.DrinkAction import com.popalay.barnee.domain.drink.DrinkState import com.popalay.barnee.domain.drink.DrinkStateMachine import com.popalay.barnee.domain.drinkitem.DrinkItemAction import com.popalay.barnee.domain.drinkitem.DrinkItemStateMachine import com.popalay.barnee.domain.navigation.AppScreens import com.popalay.barnee.domain.navigation.NavigateBackAction import com.popalay.barnee.domain.navigation.NavigateToAction import com.popalay.barnee.domain.navigation.ScreenWithInputAsKey import com.popalay.barnee.domain.navigation.ScreenWithTransition import com.popalay.barnee.ui.common.ActionsAppBar import com.popalay.barnee.ui.common.ActionsAppBarHeight import com.popalay.barnee.ui.common.AnimatedHeartButton import com.popalay.barnee.ui.common.AsyncImage import com.popalay.barnee.ui.common.BackButton import com.popalay.barnee.ui.common.CollapsingScaffold import com.popalay.barnee.ui.common.ErrorAndRetryStateView import com.popalay.barnee.ui.common.LoadingStateView import com.popalay.barnee.ui.common.StateLayout import com.popalay.barnee.ui.common.YouTubePlayer import com.popalay.barnee.ui.common.rememberCollapsingScaffoldState import com.popalay.barnee.ui.extensions.injectStateMachine import com.popalay.barnee.ui.icons.ChevronLeft import com.popalay.barnee.ui.icons.Cross import com.popalay.barnee.ui.icons.LightOff import com.popalay.barnee.ui.icons.LightOn import com.popalay.barnee.ui.platform.collectAsStateWithLifecycle import com.popalay.barnee.ui.screen.drinklist.DrinkHorizontalList import com.popalay.barnee.ui.theme.DefaultAspectRatio import com.popalay.barnee.ui.theme.LightGrey import com.popalay.barnee.ui.theme.SquircleShape import com.popalay.barnee.util.asStateFlow import com.popalay.barnee.util.calories import com.popalay.barnee.util.collection import com.popalay.barnee.util.displayRatingWithMax import com.popalay.barnee.util.displayStory import com.popalay.barnee.util.displayText import com.popalay.barnee.util.isGenerated import com.popalay.barnee.util.keywords import com.popalay.barnee.util.videoId import io.matthewnelson.component.parcelize.IgnoredOnParcel import io.matthewnelson.component.parcelize.Parcelize import org.koin.core.parameter.parametersOf import kotlin.math.min import kotlin.math.roundToInt @Parcelize data class DrinkScreen(override val input: DrinkMinimumData) : ScreenWithInputAsKey<DrinkMinimumData> { @IgnoredOnParcel override val transition: ScreenWithTransition.Transition = ScreenWithTransition.Transition.SlideVertical @Composable override fun Content() { val stateMachine = injectStateMachine<DrinkStateMachine>(parameters = { parametersOf(input) }) val state by stateMachine.stateFlow.asStateFlow().collectAsStateWithLifecycle() val drinkItemStateMachine = injectStateMachine<DrinkItemStateMachine>() DrinkScreen(state, stateMachine::dispatch, drinkItemStateMachine::dispatch) } } @Composable private fun DrinkScreen( state: DrinkState, onAction: (Action) -> Unit, onItemAction: (DrinkItemAction) -> Unit ) { BoxWithConstraints(Modifier.fillMaxSize()) { val screenWidthPx = constraints.maxWidth val toolbarHeightPx = screenWidthPx / DefaultAspectRatio val collapsedToolbarHeightPx = with(LocalDensity.current) { ActionsAppBarHeight.toPx() + WindowInsets.statusBars.getTop(this) } val listState = rememberLazyListState() val collapsingScaffoldState = rememberCollapsingScaffoldState( minHeight = collapsedToolbarHeightPx, maxHeight = toolbarHeightPx ) CollapsingScaffold( state = collapsingScaffoldState, isEnabled = state.drinkWithRelated is Success, topBar = { DrinkAppBar( state = state, onAction = onAction, onDrinkAction = onItemAction, scrollFraction = collapsingScaffoldState.fraction, offset = IntOffset(0, collapsingScaffoldState.topBarOffset.roundToInt()), modifier = Modifier.offset { IntOffset(0, collapsingScaffoldState.topBarOffset.roundToInt()) } ) } ) { contentPadding -> DrinkScreenBody( drinkWithRelated = state.drinkWithRelated, listState = listState, contentPadding = contentPadding, onRetryClicked = { onAction(DrinkAction.Retry) }, onCategoryClicked = { onAction(NavigateToAction(AppScreens.DrinksByTag(it.text))) }, onMoreRecommendedDrinksClicked = { onAction(NavigateToAction(AppScreens.SimilarDrinksTo(state.drinkMinimumData))) } ) } } } @Composable private fun DrinkScreenBody( drinkWithRelated: Result<FullDrinkResponse>, listState: LazyListState, onRetryClicked: () -> Unit, onCategoryClicked: (Category) -> Unit, onMoreRecommendedDrinksClicked: () -> Unit, modifier: Modifier = Modifier, contentPadding: PaddingValues = PaddingValues() ) { LazyColumn( state = listState, contentPadding = contentPadding, modifier = modifier ) { item { StateLayout( value = drinkWithRelated, loadingState = { LoadingStateView( modifier = Modifier.padding(top = 32.dp) ) }, errorState = { ErrorAndRetryStateView( onRetry = onRetryClicked, modifier = Modifier.padding(top = 32.dp) ) } ) { value -> Column { Spacer(modifier = Modifier.height(32.dp)) if (value.drink.displayStory.isNotBlank()) { Story( story = value.drink.displayStory, modifier = Modifier.padding(start = 24.dp, end = 16.dp) ) Divider(modifier = Modifier.padding(vertical = 24.dp)) } Ingredients( ingredient = value.drink.ingredients, modifier = Modifier.padding(horizontal = 24.dp) ) Divider(modifier = Modifier.padding(vertical = 24.dp)) Steps( instruction = value.drink.instruction, modifier = Modifier.padding(horizontal = 24.dp) ) if (value.drink.keywords.isNotEmpty()) { Divider(modifier = Modifier.padding(vertical = 24.dp)) Keywords( keywords = value.drink.keywords, onClick = { onCategoryClicked(it) }, modifier = Modifier.padding(horizontal = 16.dp) ) } if (value.relatedDrinks.isNotEmpty()) { Divider(modifier = Modifier.padding(vertical = 24.dp)) RecommendedDrinks( data = value.relatedDrinks, onShowMoreClick = onMoreRecommendedDrinksClicked, ) } Spacer( modifier = Modifier .windowInsetsBottomHeight(WindowInsets.navigationBars) .padding(bottom = 16.dp) ) } } } } } @Composable private fun DrinkAppBar( state: DrinkState, onAction: (Action) -> Unit, onDrinkAction: (DrinkItemAction) -> Unit, scrollFraction: Float, offset: IntOffset, modifier: Modifier = Modifier, ) { val drink by remember(state.drinkWithRelated) { derivedStateOf { state.drinkWithRelated()?.drink } } val hasVideo by remember(drink) { derivedStateOf { !drink?.videoId.isNullOrBlank() } } val titleMaxLines by remember(hasVideo) { derivedStateOf { if (hasVideo) 3 else 6 } } val contentAlpha by remember(state, scrollFraction) { derivedStateOf { if (state.isPlaying) 0F else 1 - (scrollFraction * 1.5F).coerceAtMost(1F) } } Card( elevation = 4.dp, shape = SquircleShape( curveTopStart = 0F, curveTopEnd = 0F, curveBottomStart = 0.1F * (1 - scrollFraction), curveBottomEnd = 0.1F * (1 - scrollFraction) ), modifier = modifier .fillMaxWidth() .aspectRatio(DefaultAspectRatio) ) { Crossfade(state.isPlaying, label = "player-content") { isPlaying -> if (isPlaying) { YouTubePlayer( videoId = drink?.videoId.orEmpty(), modifier = Modifier .fillMaxSize() .background(Color.Black) .padding(bottom = 16.dp) ) } else { AsyncImage( imageUrl = state.displayImage, modifier = Modifier.fillMaxSize(), colorFilter = ColorFilter.tint(Color.Black.copy(alpha = ContentAlpha.disabled), BlendMode.SrcAtop) ) } } Box( modifier = Modifier .fillMaxSize() .alpha(scrollFraction) .background(MaterialTheme.colors.background) ) Box { CompositionLocalProvider(LocalContentAlpha provides contentAlpha) { Column( verticalArrangement = Arrangement.spacedBy(8.dp), modifier = Modifier.align(Alignment.TopStart) ) { CompositionLocalProvider(LocalContentAlpha provides 1F) { DrinkActionBar( title = state.displayName, titleAlpha = 1 - contentAlpha, isActionsVisible = drink != null, isScreenKeptOn = state.isScreenKeptOn, onBackCLick = { onAction(NavigateBackAction) }, onKeepScreenOnClicked = { onAction(DrinkAction.KeepScreenOnClicked) }, onShareClicked = { onAction(DrinkAction.ShareClicked) }, modifier = Modifier .fillMaxWidth() .offset { -offset } ) } Column( verticalArrangement = Arrangement.spacedBy(8.dp), modifier = Modifier.fillMaxWidth() ) { Text( text = state.displayName, style = MaterialTheme.typography.h1, maxLines = titleMaxLines, overflow = TextOverflow.Ellipsis, modifier = Modifier .fillMaxWidth(0.7F) .padding(start = 24.dp) ) Row( verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(24.dp) ) { Text( text = drink?.calories.orEmpty(), style = MaterialTheme.typography.h3, modifier = Modifier.padding(start = 24.dp) ) CollectionBanner( collection = state.drinkWithRelated()?.drink?.collection, onCollectionClick = { onAction(NavigateToAction(AppScreens.SingleCollection(it))) }, modifier = Modifier.padding(end = 24.dp) ) } AnimatedVisibility( visible = !drink?.videoId.isNullOrBlank(), enter = fadeIn(), exit = fadeOut(), modifier = Modifier .padding(top = 16.dp) .align(Alignment.CenterHorizontally) ) { PlayButton(onClick = { onAction(DrinkAction.TogglePlaying) }) } } } AnimatedVisibility( visible = drink != null, enter = slideInVertically { it }, modifier = Modifier .align(Alignment.BottomStart) .fillMaxWidth() .padding(bottom = 16.dp, start = 24.dp, end = 8.dp) ) { Row( verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.SpaceBetween, ) { Text( text = if (drink?.isGenerated == true) "AI โœจ" else drink?.displayRatingWithMax.orEmpty(), style = MaterialTheme.typography.h2, ) if (drink?.isGenerated == false) { AnimatedHeartButton( onToggle = { onDrinkAction(DrinkItemAction.ToggleFavorite(requireNotNull(drink))) }, isSelected = drink?.collection != null, iconSize = 32.dp, ) } } } } } } } @Composable private fun DrinkActionBar( title: String, titleAlpha: Float, isActionsVisible: Boolean, isScreenKeptOn: Boolean, onKeepScreenOnClicked: () -> Unit, onShareClicked: () -> Unit, onBackCLick: () -> Unit, modifier: Modifier = Modifier ) { ActionsAppBar( title = { Text( text = title, color = LocalContentColor.current.copy(alpha = titleAlpha), maxLines = 1, overflow = TextOverflow.Ellipsis ) }, leadingButtons = { BackButton(onClick = onBackCLick, icon = Icons.Cross) }, trailingButtons = { AnimatedVisibility(isActionsVisible) { Row { IconButton(onClick = onKeepScreenOnClicked) { Icon( imageVector = if (isScreenKeptOn) Icons.LightOff else Icons.LightOn, contentDescription = "Keep screen on", ) } IconButton(onClick = onShareClicked) { Icon( imageVector = Icons.Default.Share, contentDescription = "Share drink", ) } } } }, modifier = modifier.statusBarsPadding() ) } @Composable private fun PlayButton( onClick: () -> Unit, modifier: Modifier = Modifier ) { Surface( shape = CircleShape, color = LocalContentColor.current.copy(alpha = min(ContentAlpha.disabled, LocalContentAlpha.current)), modifier = modifier .clip(CircleShape) .clickable(onClick = onClick) .size(72.dp) ) { Icon( imageVector = Icons.Default.PlayArrow, contentDescription = "Play", modifier = Modifier.fillMaxSize() ) } } @Composable private fun Ingredients( ingredient: List<Ingredient>, modifier: Modifier = Modifier ) { Column(modifier = modifier) { Text( text = "Ingredients", style = MaterialTheme.typography.subtitle1, ) Spacer(modifier = Modifier.height(16.dp)) ingredient.forEachIndexed { index, item -> if (index > 0) Spacer(modifier = Modifier.height(8.dp)) Text( text = item.text, style = MaterialTheme.typography.body1, color = LightGrey ) } } } @Composable private fun Story( story: String, modifier: Modifier = Modifier ) { var isTextCollapsed by rememberSaveable { mutableStateOf(true) } val textLength by animateIntAsState(if (isTextCollapsed) 100 else story.length, label = "textLength") val arrowRotation by animateIntAsState(if (isTextCollapsed) 270 else 90, label = "arrowRotation") Column( modifier = modifier.clickable( onClick = { isTextCollapsed = !isTextCollapsed }, interactionSource = remember { MutableInteractionSource() }, indication = null ) ) { Row(verticalAlignment = Alignment.CenterVertically) { Text( text = "Story", style = MaterialTheme.typography.subtitle1, modifier = Modifier .fillMaxWidth() .weight(1F) ) TextButton( onClick = { isTextCollapsed = !isTextCollapsed }, colors = ButtonDefaults.textButtonColors(contentColor = MaterialTheme.colors.onBackground) ) { Text( text = if (isTextCollapsed) "More" else "Less", style = MaterialTheme.typography.subtitle2, ) Spacer(modifier = Modifier.width(8.dp)) Icon( imageVector = Icons.ChevronLeft, tint = MaterialTheme.colors.onSurface, contentDescription = if (isTextCollapsed) "More" else "Less", modifier = Modifier .size(8.dp) .rotate(arrowRotation.toFloat()) ) } } Spacer(modifier = Modifier.height(16.dp)) Text( text = story.take(textLength) + if (isTextCollapsed) "..." else "", style = MaterialTheme.typography.body2, ) } } @Composable private fun Steps( instruction: Instruction, modifier: Modifier = Modifier ) { Column(modifier = modifier) { Text( text = "Steps", style = MaterialTheme.typography.subtitle1, ) Spacer(modifier = Modifier.height(16.dp)) instruction.steps.forEachIndexed { index, item -> if (index > 0) Spacer(modifier = Modifier.height(8.dp)) Row { Text( text = item.text, style = MaterialTheme.typography.body1, color = MaterialTheme.colors.primary, modifier = Modifier .fillMaxWidth() .weight(1F) ) Spacer(modifier = Modifier.width(8.dp)) Text( text = (index + 1).toString().padStart(2, '0'), style = MaterialTheme.typography.body2, color = MaterialTheme.colors.primary, ) } } } } @OptIn(ExperimentalLayoutApi::class) @Composable private fun Keywords( keywords: List<Category>, onClick: (Category) -> Unit, modifier: Modifier = Modifier ) { Column(modifier = modifier) { Text( text = "Categories", style = MaterialTheme.typography.subtitle1, modifier = Modifier.padding(horizontal = 8.dp) ) Spacer(modifier = Modifier.padding(top = 16.dp)) FlowRow { keywords.forEach { item -> Text( text = item.displayText, style = MaterialTheme.typography.body2, color = MaterialTheme.colors.primaryVariant, modifier = Modifier .clip(CircleShape) .clickable { onClick(item) } .padding(vertical = 4.dp) .padding(horizontal = 8.dp) ) } } } } @Composable private fun RecommendedDrinks( data: List<Drink>, onShowMoreClick: () -> Unit, modifier: Modifier = Modifier ) { Column(modifier = modifier) { Row( verticalAlignment = Alignment.CenterVertically, modifier = Modifier.padding(start = 24.dp, end = 16.dp) ) { Text( text = "Recommended", style = MaterialTheme.typography.subtitle1, ) Spacer( modifier = Modifier .fillMaxSize() .weight(1F) ) TextButton( onClick = onShowMoreClick, colors = ButtonDefaults.textButtonColors(contentColor = MaterialTheme.colors.onBackground), ) { Text( text = "More", style = MaterialTheme.typography.subtitle2, ) Spacer(modifier = Modifier.width(8.dp)) Icon( imageVector = Icons.ChevronLeft, tint = MaterialTheme.colors.onSurface, contentDescription = "More", modifier = Modifier .size(8.dp) .rotate(180F) ) } } DrinkHorizontalList( data = data, contentPadding = PaddingValues(horizontal = 24.dp, vertical = 16.dp) ) } }
21
Kotlin
3
15
0d25ca9033065ff4c9b6f044550f7c02f96f97bd
27,016
Barnee
MIT License
examples/coroutines/src/test/kotlin/io/bluetape4k/examples/coroutines/guide/FlowExamples.kt
debop
625,161,599
false
{"Kotlin": 7504333, "HTML": 502995, "Java": 2273, "JavaScript": 1351, "Shell": 1301, "CSS": 444, "Dockerfile": 121, "Mustache": 82}
package io.bluetape4k.examples.coroutines.guide import io.bluetape4k.coroutines.flow.extensions.log import io.bluetape4k.logging.KLogging import io.bluetape4k.logging.debug import kotlinx.coroutines.delay import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.asFlow import kotlinx.coroutines.flow.collect import kotlinx.coroutines.flow.launchIn import kotlinx.coroutines.flow.onEach import kotlinx.coroutines.test.runTest import org.junit.jupiter.api.Nested import org.junit.jupiter.api.Test import kotlin.random.Random class FlowExamples { companion object: KLogging() @Nested inner class Flow35 { private fun events(): Flow<Int> = (1..3).asFlow().onEach { delay(Random.nextLong(100)) } @Test fun `collect without any code`() = runTest { events() .log("events") .collect() log.debug { "Done!" } } } @Nested inner class Flow36 { private fun events(): Flow<Int> = (1..3).asFlow().onEach { delay(Random.nextLong(100)) } @Test fun `launch flow in a separate coroutine scope`() = runTest { events() .log("event") .launchIn(this) // CoroutineScope ๋‚ด์˜ ๋‹ค์Œ ์ž‘์—…๊ณผ ๋™์‹œ์— ์ง„ํ–‰๋œ๋‹ค log.debug { "Done!" } } } }
0
Kotlin
0
1
ce3da5b6bddadd29271303840d334b71db7766d2
1,344
bluetape4k
MIT License
idea/tests/testData/intentions/convertNullablePropertyToLateinit/topLevelLegacy.kt
JetBrains
278,369,660
false
null
// IS_APPLICABLE: false // LANGUAGE_VERSION: 1.1 <caret>var foo: String? = null
0
Kotlin
30
82
cc81d7505bc3e9ad503d706998ae8026c067e838
79
intellij-kotlin
Apache License 2.0
app/src/main/java/com/bumantra/mystoryapp/model/UserModel.kt
raafihilmi
804,690,636
false
{"Kotlin": 80018}
package com.bumantra.mystoryapp.model data class UserModel( val name: String, val token: String, val isLogin: Boolean = false )
0
Kotlin
0
0
b2e2f45ffee2748858b2472c9c977acc65cfad3f
141
MyStoryApp
MIT License
app/src/main/java/info/moevm/moodle/model/CardsViewModel.kt
moevm
297,595,021
false
null
package info.moevm.moodle.model import androidx.compose.runtime.* import androidx.lifecycle.ViewModel import androidx.lifecycle.viewModelScope import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.StateFlow import kotlinx.coroutines.launch @Immutable // Optimization for Compose data class ExpandableCardModel(val id: Int, val title: String) const val EXPAND_ANIMATION_DURATION = 500 const val FADE_IN_ANIMATION_DURATION = 500 const val FADE_OUT_ANIMATION_DURATION = 500 const val COLLAPSE_ANIMATION_DURATION = 500 class CardsViewModel(titles: List<String>?) : ViewModel() { private val _cards = MutableStateFlow(listOf<ExpandableCardModel>()) val cards: StateFlow<List<ExpandableCardModel>> get() = _cards private val _expandedCardIdsList = MutableStateFlow(listOf<Int>()) val expandedCardIdsList: StateFlow<List<Int>> get() = _expandedCardIdsList init { viewModelScope.launch(Dispatchers.Default) { val tempTitles = titles ?: emptyList() val testList = arrayListOf<ExpandableCardModel>() var cnt = 0 for (title in tempTitles) { testList += ExpandableCardModel(id = cnt++, title = title) } _cards.emit(testList) } } fun onCardClicked(cardId: Int) { _expandedCardIdsList.value = _expandedCardIdsList.value.toMutableList().also { list -> if (list.contains(cardId)) list.remove(cardId) else list.add(cardId) } } }
18
Kotlin
0
0
d7104800cb4cdb94fb6b651abb268ef850bc4575
1,546
mse_android_app_for_moodle
MIT License
informacoes-cadastrais/src/main/kotlin/br/elakc/informacoescadastrais/HelloWorldController.kt
evandroabukamel
390,905,764
false
null
package br.elakc.informacoescadastrais import org.springframework.web.bind.annotation.GetMapping import org.springframework.web.bind.annotation.RequestMapping import org.springframework.web.bind.annotation.RestController @RestController @RequestMapping("/") class HelloWorldController { @GetMapping fun home(): String { return "Hello World" } }
0
Kotlin
0
0
3449afd67917bd526bb7eff42b1cae22711b4cf6
367
puc-asd-tcc
MIT License
app-refresh/src/main/java/com/androidessence/cashcaretaker/addaccount/AddAccountViewModel.kt
SagarDep
157,524,573
true
{"Kotlin": 114354, "Java": 1366}
package com.androidessence.cashcaretaker.addaccount import android.database.sqlite.SQLiteConstraintException import androidx.lifecycle.MutableLiveData import com.androidessence.cashcaretaker.R import com.androidessence.cashcaretaker.account.Account import com.androidessence.cashcaretaker.base.BaseViewModel import com.androidessence.cashcaretaker.data.CCRepository import io.reactivex.Single import io.reactivex.android.schedulers.AndroidSchedulers import io.reactivex.schedulers.Schedulers import io.reactivex.subjects.PublishSubject import timber.log.Timber class AddAccountViewModel(private val repository: CCRepository) : BaseViewModel() { val accountInserted: PublishSubject<Long> = PublishSubject.create() val accountNameError = MutableLiveData<Int>() val accountBalanceError = MutableLiveData<Int>() /** * Checks that the information passed in is valid, and inserts an account if it is. */ fun addAccount(name: String?, balanceString: String?) { if (name == null || name.isEmpty()) { accountNameError.value = R.string.err_account_name_invalid return } val balance = balanceString?.toDoubleOrNull() if (balance == null) { accountBalanceError.value = R.string.err_account_balance_invalid return } val account = Account(name, balance) Single.fromCallable { repository.insertAccount(account) } .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .subscribe( accountInserted::onNext ) { error -> if (error is SQLiteConstraintException) { accountNameError.value = R.string.err_account_name_exists } else { Timber.e(error) } } .addToComposite() } }
0
Kotlin
0
0
4a1076c96788f9e1854a492f334b49e590643b45
1,942
CashCaretaker
MIT License
app/src/main/java/mx/itesm/appdibujandounmanana/model/Proyecto.kt
Maikindustries
402,613,254
false
null
package mx.itesm.appdibujandounmanana.model import com.google.gson.annotations.SerializedName import java.io.Serializable // Clase especial, genera toString, get/set, equals, data class Proyecto ( @SerializedName("Nombre") val nombre: String, @SerializedName("Estado") val estado: Boolean ) : Serializable // Pasara entre fragmentos
1
Kotlin
0
0
11c0b496883cbab40c1090c1feca46a329ce94ca
355
AppDibujandoUnManana
MIT License
plugins/kotlin/idea/tests/testData/intentions/addAnnotationUseSiteTarget/qualifiedAnnotationDoesNotLoseQualifier.1.kt
ingokegel
72,937,917
true
null
package p annotation class A
1
null
1
2
b07eabd319ad5b591373d63c8f502761c2b2dfe8
30
intellij-community
Apache License 2.0