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
Notebook/app/src/main/java/com/example/notebook/viewmodel/NoteViewModel.kt
BennyZhang-Canviz
255,919,665
false
null
package com.example.notebook.viewmodel import androidx.lifecycle.LiveData import androidx.lifecycle.ViewModel import androidx.lifecycle.viewModelScope import com.example.notebook.data.Note import com.example.notebook.data.NoteRepository import kotlinx.coroutines.launch import java.util.* class NoteViewModel ( var id: Long, private val noteRepository: NoteRepository ) : ViewModel() { var note:LiveData<Note> =noteRepository.getNoteById(id) fun delete(){ viewModelScope.launch { note.value?.let { noteRepository.delete(it) } } } fun update( title: String, content: String){ viewModelScope.launch { var noteToUpdate = Note(id, title, content, modified = Calendar.getInstance()) noteRepository.update(noteToUpdate) } } fun create( title: String, content: String) { viewModelScope.launch { var noteToUpdate = Note(title = title, content = content,created = Calendar.getInstance(), modified = Calendar.getInstance()) noteRepository.insert(noteToUpdate) } } }
0
Kotlin
0
0
55ae049d5c880b67251e40cf658c4535d52cd017
1,123
Android
Apache License 2.0
app/src/main/java/com/danielefavaro/spacex/main/ui/LaunchDetailFragment.kt
dfavaro
349,760,654
false
null
package com.danielefavaro.spacex.main.ui import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import com.danielefavaro.spacex.SpaceXApp import com.danielefavaro.spacex.base.ktx.load import com.danielefavaro.spacex.base.ui.BaseBottomSheetDialogFragment import com.danielefavaro.spacex.base.util.Constants import com.danielefavaro.spacex.databinding.LaunchDetailFragmentBinding import com.danielefavaro.spacex.main.ui.model.LaunchModelUI class LaunchDetailFragment : BaseBottomSheetDialogFragment() { private var _binding: LaunchDetailFragmentBinding? = null private val binding get() = _binding!! override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View = LaunchDetailFragmentBinding.inflate(inflater, container, false).apply { _binding = this }.root override fun setupDI() { (activity?.application as? SpaceXApp)?.appComponent?.mainFactory()?.create()?.inject(this) } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) arguments?.getParcelable<LaunchModelUI>(Constants.SHARED_LAUNCH)?.let { launchModelUI -> binding.rocketName.text = launchModelUI.name binding.date.text = launchModelUI.date binding.launchImage.load(launchModelUI.imageUrl) binding.details.text = launchModelUI.details } } override fun onDestroyView() { super.onDestroyView() _binding = null } }
0
Kotlin
0
0
0483fdfbd8b0e5bf2c0f3ddfbe5dfce17078d933
1,625
spacex-android
MIT License
player/playback-engine/src/main/kotlin/com/tidal/sdk/player/playbackengine/quality/VideoQualityRepository.kt
tidal-music
806,866,286
false
{"Kotlin": 1775374, "Shell": 9881, "Python": 7380, "Mustache": 911}
package com.tidal.sdk.player.playbackengine.quality import com.tidal.sdk.player.common.model.VideoQuality import com.tidal.sdk.player.streamingapi.playbackinfo.model.PlaybackInfo /** * Repository for getting the [VideoQuality] to be used in a specific request for [PlaybackInfo]. */ internal class VideoQualityRepository { val streamingQuality = VideoQuality.HIGH }
27
Kotlin
0
23
1f654552133ef7794fe9bb7677bc7fc94c713aa3
375
tidal-sdk-android
Apache License 2.0
lib/src/main/java/com/cexdirect/lib/util/ValidationUtils.kt
decent-finance
190,219,501
false
{"Gradle": 7, "Shell": 3, "Java Properties": 2, "Ignore List": 3, "Batchfile": 1, "YAML": 3, "Markdown": 1, "Proguard": 3, "XML": 144, "Kotlin": 231, "Java": 6, "JSON": 5}
/* * Copyright 2019 CEX.​IO Ltd (UK) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ @file:Suppress("MatchingDeclarationName", "MaxLineLength") package com.cexdirect.lib.util import java.util.regex.Pattern val emailPattern = Pattern.compile( "^(?:(?:\\r\\n)?[ \\t])*(?:(?:(?:[^()<>@,;:\\\\\".\\[\\] \\000-\\031]+(?:(?:(?:\\r\\n)?[ \\t])+|\\Z|(?=[\\[\"()<>@,;:\\\\\".\\[\\]]))|\"(?:[^\\\"\\r\\\\]|\\\\.|(?:(?:\\r\\n)?[ \\t]))*\"(?:(?:\\r\\n)?[ \\t])*)(?:\\.(?:(?:\\r\\n)?[ \\t])*(?:[^()<>@,;:\\\\\".\\[\\] \\000-\\031]+(?:(?:(?:\\r\\n)?[ \\t])+|\\Z|(?=[\\[\"()<>@,;:\\\\\".\\[\\]]))|\"(?:[^\\\"\\r\\\\]|\\\\.|(?:(?:\\r\\n)?[ \\t]))*\"(?:(?:\\r\\n)?[ \\t])*))*@(?:(?:\\r\\n)?[ \\t])*(?:[^()<>@,;:\\\\\".\\[\\] \\000-\\031]+(?:(?:(?:\\r\\n)?[ \\t])+|\\Z|(?=[\\[\"()<>@,;:\\\\\".\\[\\]]))|\\[([^\\[\\]\\r\\\\]|\\\\.)*\\](?:(?:\\r\\n)?[ \\t])*)(?:\\.(?:(?:\\r\\n)?[ \\t])*(?:[^()<>@,;:\\\\\".\\[\\] \\000-\\031]+(?:(?:(?:\\r\\n)?[ \\t])+|\\Z|(?=[\\[\"()<>@,;:\\\\\".\\[\\]]))|\\[([^\\[\\]\\r\\\\]|\\\\.)*\\](?:(?:\\r\\n)?[ \\t])*))*|(?:[^()<>@,;:\\\\\".\\[\\] \\000-\\031]+(?:(?:(?:\\r\\n)?[ \\t])+|\\Z|(?=[\\[\"()<>@,;:\\\\\".\\[\\]]))|\"(?:[^\\\"\\r\\\\]|\\\\.|(?:(?:\\r\\n)?[ \\t]))*\"(?:(?:\\r\\n)?[ \\t])*)*\\<(?:(?:\\r\\n)?[ \\t])*(?:@(?:[^()<>@,;:\\\\\".\\[\\] \\000-\\031]+(?:(?:(?:\\r\\n)?[ \\t])+|\\Z|(?=[\\[\"()<>@,;:\\\\\".\\[\\]]))|\\[([^\\[\\]\\r\\\\]|\\\\.)*\\](?:(?:\\r\\n)?[ \\t])*)(?:\\.(?:(?:\\r\\n)?[ \\t])*(?:[^()<>@,;:\\\\\".\\[\\] \\000-\\031]+(?:(?:(?:\\r\\n)?[ \\t])+|\\Z|(?=[\\[\"()<>@,;:\\\\\".\\[\\]]))|\\[([^\\[\\]\\r\\\\]|\\\\.)*\\](?:(?:\\r\\n)?[ \\t])*))*(?:,@(?:(?:\\r\\n)?[ \\t])*(?:[^()<>@,;:\\\\\".\\[\\] \\000-\\031]+(?:(?:(?:\\r\\n)?[ \\t])+|\\Z|(?=[\\[\"()<>@,;:\\\\\".\\[\\]]))|\\[([^\\[\\]\\r\\\\]|\\\\.)*\\](?:(?:\\r\\n)?[ \\t])*)(?:\\.(?:(?:\\r\\n)?[ \\t])*(?:[^()<>@,;:\\\\\".\\[\\] \\000-\\031]+(?:(?:(?:\\r\\n)?[ \\t])+|\\Z|(?=[\\[\"()<>@,;:\\\\\".\\[\\]]))|\\[([^\\[\\]\\r\\\\]|\\\\.)*\\](?:(?:\\r\\n)?[ \\t])*))*)*:(?:(?:\\r\\n)?[ \\t])*)?(?:[^()<>@,;:\\\\\".\\[\\] \\000-\\031]+(?:(?:(?:\\r\\n)?[ \\t])+|\\Z|(?=[\\[\"()<>@,;:\\\\\".\\[\\]]))|\"(?:[^\\\"\\r\\\\]|\\\\.|(?:(?:\\r\\n)?[ \\t]))*\"(?:(?:\\r\\n)?[ \\t])*)(?:\\.(?:(?:\\r\\n)?[ \\t])*(?:[^()<>@,;:\\\\\".\\[\\] \\000-\\031]+(?:(?:(?:\\r\\n)?[ \\t])+|\\Z|(?=[\\[\"()<>@,;:\\\\\".\\[\\]]))|\"(?:[^\\\"\\r\\\\]|\\\\.|(?:(?:\\r\\n)?[ \\t]))*\"(?:(?:\\r\\n)?[ \\t])*))*@(?:(?:\\r\\n)?[ \\t])*(?:[^()<>@,;:\\\\\".\\[\\] \\000-\\031]+(?:(?:(?:\\r\\n)?[ \\t])+|\\Z|(?=[\\[\"()<>@,;:\\\\\".\\[\\]]))|\\[([^\\[\\]\\r\\\\]|\\\\.)*\\](?:(?:\\r\\n)?[ \\t])*)(?:\\.(?:(?:\\r\\n)?[ \\t])*(?:[^()<>@,;:\\\\\".\\[\\] \\000-\\031]+(?:(?:(?:\\r\\n)?[ \\t])+|\\Z|(?=[\\[\"()<>@,;:\\\\\".\\[\\]]))|\\[([^\\[\\]\\r\\\\]|\\\\.)*\\](?:(?:\\r\\n)?[ \\t])*))*\\>(?:(?:\\r\\n)?[ \\t])*)|(?:[^()<>@,;:\\\\\".\\[\\] \\000-\\031]+(?:(?:(?:\\r\\n)?[ \\t])+|\\Z|(?=[\\[\"()<>@,;:\\\\\".\\[\\]]))|\"(?:[^\\\"\\r\\\\]|\\\\.|(?:(?:\\r\\n)?[ \\t]))*\"(?:(?:\\r\\n)?[ \\t])*)*:(?:(?:\\r\\n)?[ \\t])*(?:(?:(?:[^()<>@,;:\\\\\".\\[\\] \\000-\\031]+(?:(?:(?:\\r\\n)?[ \\t])+|\\Z|(?=[\\[\"()<>@,;:\\\\\".\\[\\]]))|\"(?:[^\\\"\\r\\\\]|\\\\.|(?:(?:\\r\\n)?[ \\t]))*\"(?:(?:\\r\\n)?[ \\t])*)(?:\\.(?:(?:\\r\\n)?[ \\t])*(?:[^()<>@,;:\\\\\".\\[\\] \\000-\\031]+(?:(?:(?:\\r\\n)?[ \\t])+|\\Z|(?=[\\[\"()<>@,;:\\\\\".\\[\\]]))|\"(?:[^\\\"\\r\\\\]|\\\\.|(?:(?:\\r\\n)?[ \\t]))*\"(?:(?:\\r\\n)?[ \\t])*))*@(?:(?:\\r\\n)?[ \\t])*(?:[^()<>@,;:\\\\\".\\[\\] \\000-\\031]+(?:(?:(?:\\r\\n)?[ \\t])+|\\Z|(?=[\\[\"()<>@,;:\\\\\".\\[\\]]))|\\[([^\\[\\]\\r\\\\]|\\\\.)*\\](?:(?:\\r\\n)?[ \\t])*)(?:\\.(?:(?:\\r\\n)?[ \\t])*(?:[^()<>@,;:\\\\\".\\[\\] \\000-\\031]+(?:(?:(?:\\r\\n)?[ \\t])+|\\Z|(?=[\\[\"()<>@,;:\\\\\".\\[\\]]))|\\[([^\\[\\]\\r\\\\]|\\\\.)*\\](?:(?:\\r\\n)?[ \\t])*))*|(?:[^()<>@,;:\\\\\".\\[\\] \\000-\\031]+(?:(?:(?:\\r\\n)?[ \\t])+|\\Z|(?=[\\[\"()<>@,;:\\\\\".\\[\\]]))|\"(?:[^\\\"\\r\\\\]|\\\\.|(?:(?:\\r\\n)?[ \\t]))*\"(?:(?:\\r\\n)?[ \\t])*)*\\<(?:(?:\\r\\n)?[ \\t])*(?:@(?:[^()<>@,;:\\\\\".\\[\\] \\000-\\031]+(?:(?:(?:\\r\\n)?[ \\t])+|\\Z|(?=[\\[\"()<>@,;:\\\\\".\\[\\]]))|\\[([^\\[\\]\\r\\\\]|\\\\.)*\\](?:(?:\\r\\n)?[ \\t])*)(?:\\.(?:(?:\\r\\n)?[ \\t])*(?:[^()<>@,;:\\\\\".\\[\\] \\000-\\031]+(?:(?:(?:\\r\\n)?[ \\t])+|\\Z|(?=[\\[\"()<>@,;:\\\\\".\\[\\]]))|\\[([^\\[\\]\\r\\\\]|\\\\.)*\\](?:(?:\\r\\n)?[ \\t])*))*(?:,@(?:(?:\\r\\n)?[ \\t])*(?:[^()<>@,;:\\\\\".\\[\\] \\000-\\031]+(?:(?:(?:\\r\\n)?[ \\t])+|\\Z|(?=[\\[\"()<>@,;:\\\\\".\\[\\]]))|\\[([^\\[\\]\\r\\\\]|\\\\.)*\\](?:(?:\\r\\n)?[ \\t])*)(?:\\.(?:(?:\\r\\n)?[ \\t])*(?:[^()<>@,;:\\\\\".\\[\\] \\000-\\031]+(?:(?:(?:\\r\\n)?[ \\t])+|\\Z|(?=[\\[\"()<>@,;:\\\\\".\\[\\]]))|\\[([^\\[\\]\\r\\\\]|\\\\.)*\\](?:(?:\\r\\n)?[ \\t])*))*)*:(?:(?:\\r\\n)?[ \\t])*)?(?:[^()<>@,;:\\\\\".\\[\\] \\000-\\031]+(?:(?:(?:\\r\\n)?[ \\t])+|\\Z|(?=[\\[\"()<>@,;:\\\\\".\\[\\]]))|\"(?:[^\\\"\\r\\\\]|\\\\.|(?:(?:\\r\\n)?[ \\t]))*\"(?:(?:\\r\\n)?[ \\t])*)(?:\\.(?:(?:\\r\\n)?[ \\t])*(?:[^()<>@,;:\\\\\".\\[\\] \\000-\\031]+(?:(?:(?:\\r\\n)?[ \\t])+|\\Z|(?=[\\[\"()<>@,;:\\\\\".\\[\\]]))|\"(?:[^\\\"\\r\\\\]|\\\\.|(?:(?:\\r\\n)?[ \\t]))*\"(?:(?:\\r\\n)?[ \\t])*))*@(?:(?:\\r\\n)?[ \\t])*(?:[^()<>@,;:\\\\\".\\[\\] \\000-\\031]+(?:(?:(?:\\r\\n)?[ \\t])+|\\Z|(?=[\\[\"()<>@,;:\\\\\".\\[\\]]))|\\[([^\\[\\]\\r\\\\]|\\\\.)*\\](?:(?:\\r\\n)?[ \\t])*)(?:\\.(?:(?:\\r\\n)?[ \\t])*(?:[^()<>@,;:\\\\\".\\[\\] \\000-\\031]+(?:(?:(?:\\r\\n)?[ \\t])+|\\Z|(?=[\\[\"()<>@,;:\\\\\".\\[\\]]))|\\[([^\\[\\]\\r\\\\]|\\\\.)*\\](?:(?:\\r\\n)?[ \\t])*))*\\>(?:(?:\\r\\n)?[ \\t])*)(?:,\\s*(?:(?:[^()<>@,;:\\\\\".\\[\\] \\000-\\031]+(?:(?:(?:\\r\\n)?[ \\t])+|\\Z|(?=[\\[\"()<>@,;:\\\\\".\\[\\]]))|\"(?:[^\\\"\\r\\\\]|\\\\.|(?:(?:\\r\\n)?[ \\t]))*\"(?:(?:\\r\\n)?[ \\t])*)(?:\\.(?:(?:\\r\\n)?[ \\t])*(?:[^()<>@,;:\\\\\".\\[\\] \\000-\\031]+(?:(?:(?:\\r\\n)?[ \\t])+|\\Z|(?=[\\[\"()<>@,;:\\\\\".\\[\\]]))|\"(?:[^\\\"\\r\\\\]|\\\\.|(?:(?:\\r\\n)?[ \\t]))*\"(?:(?:\\r\\n)?[ \\t])*))*@(?:(?:\\r\\n)?[ \\t])*(?:[^()<>@,;:\\\\\".\\[\\] \\000-\\031]+(?:(?:(?:\\r\\n)?[ \\t])+|\\Z|(?=[\\[\"()<>@,;:\\\\\".\\[\\]]))|\\[([^\\[\\]\\r\\\\]|\\\\.)*\\](?:(?:\\r\\n)?[ \\t])*)(?:\\.(?:(?:\\r\\n)?[ \\t])*(?:[^()<>@,;:\\\\\".\\[\\] \\000-\\031]+(?:(?:(?:\\r\\n)?[ \\t])+|\\Z|(?=[\\[\"()<>@,;:\\\\\".\\[\\]]))|\\[([^\\[\\]\\r\\\\]|\\\\.)*\\](?:(?:\\r\\n)?[ \\t])*))*|(?:[^()<>@,;:\\\\\".\\[\\] \\000-\\031]+(?:(?:(?:\\r\\n)?[ \\t])+|\\Z|(?=[\\[\"()<>@,;:\\\\\".\\[\\]]))|\"(?:[^\\\"\\r\\\\]|\\\\.|(?:(?:\\r\\n)?[ \\t]))*\"(?:(?:\\r\\n)?[ \\t])*)*\\<(?:(?:\\r\\n)?[ \\t])*(?:@(?:[^()<>@,;:\\\\\".\\[\\] \\000-\\031]+(?:(?:(?:\\r\\n)?[ \\t])+|\\Z|(?=[\\[\"()<>@,;:\\\\\".\\[\\]]))|\\[([^\\[\\]\\r\\\\]|\\\\.)*\\](?:(?:\\r\\n)?[ \\t])*)(?:\\.(?:(?:\\r\\n)?[ \\t])*(?:[^()<>@,;:\\\\\".\\[\\] \\000-\\031]+(?:(?:(?:\\r\\n)?[ \\t])+|\\Z|(?=[\\[\"()<>@,;:\\\\\".\\[\\]]))|\\[([^\\[\\]\\r\\\\]|\\\\.)*\\](?:(?:\\r\\n)?[ \\t])*))*(?:,@(?:(?:\\r\\n)?[ \\t])*(?:[^()<>@,;:\\\\\".\\[\\] \\000-\\031]+(?:(?:(?:\\r\\n)?[ \\t])+|\\Z|(?=[\\[\"()<>@,;:\\\\\".\\[\\]]))|\\[([^\\[\\]\\r\\\\]|\\\\.)*\\](?:(?:\\r\\n)?[ \\t])*)(?:\\.(?:(?:\\r\\n)?[ \\t])*(?:[^()<>@,;:\\\\\".\\[\\] \\000-\\031]+(?:(?:(?:\\r\\n)?[ \\t])+|\\Z|(?=[\\[\"()<>@,;:\\\\\".\\[\\]]))|\\[([^\\[\\]\\r\\\\]|\\\\.)*\\](?:(?:\\r\\n)?[ \\t])*))*)*:(?:(?:\\r\\n)?[ \\t])*)?(?:[^()<>@,;:\\\\\".\\[\\] \\000-\\031]+(?:(?:(?:\\r\\n)?[ \\t])+|\\Z|(?=[\\[\"()<>@,;:\\\\\".\\[\\]]))|\"(?:[^\\\"\\r\\\\]|\\\\.|(?:(?:\\r\\n)?[ \\t]))*\"(?:(?:\\r\\n)?[ \\t])*)(?:\\.(?:(?:\\r\\n)?[ \\t])*(?:[^()<>@,;:\\\\\".\\[\\] \\000-\\031]+(?:(?:(?:\\r\\n)?[ \\t])+|\\Z|(?=[\\[\"()<>@,;:\\\\\".\\[\\]]))|\"(?:[^\\\"\\r\\\\]|\\\\.|(?:(?:\\r\\n)?[ \\t]))*\"(?:(?:\\r\\n)?[ \\t])*))*@(?:(?:\\r\\n)?[ \\t])*(?:[^()<>@,;:\\\\\".\\[\\] \\000-\\031]+(?:(?:(?:\\r\\n)?[ \\t])+|\\Z|(?=[\\[\"()<>@,;:\\\\\".\\[\\]]))|\\[([^\\[\\]\\r\\\\]|\\\\.)*\\](?:(?:\\r\\n)?[ \\t])*)(?:\\.(?:(?:\\r\\n)?[ \\t])*(?:[^()<>@,;:\\\\\".\\[\\] \\000-\\031]+(?:(?:(?:\\r\\n)?[ \\t])+|\\Z|(?=[\\[\"()<>@,;:\\\\\".\\[\\]]))|\\[([^\\[\\]\\r\\\\]|\\\\.)*\\](?:(?:\\r\\n)?[ \\t])*))*\\>(?:(?:\\r\\n)?[ \\t])*))*)?;\\s*)$", Pattern.CASE_INSENSITIVE )!! fun checkEmailStatus(email: String?) = if (email.isNullOrBlank()) { FieldStatus.EMPTY } else { if (emailPattern.matcher(email).matches()) { FieldStatus.VALID } else { FieldStatus.INVALID } } val ssnPattern = Pattern.compile("^(?!000|666)[0-8][0-9]{2}-(?!00)[0-9]{2}-(?!0000)[0-9]{4}\$")!! fun checkSsnStatus(ssn: String?) = if (ssn.isNullOrBlank()) { FieldStatus.EMPTY } else { if (ssnPattern.matcher(ssn).matches()) { FieldStatus.VALID } else { FieldStatus.INVALID } } enum class FieldStatus { EMPTY, INVALID, VALID }
1
null
1
1
0701a5be69007b1c9ffb3d03775410e413629417
9,245
direct-android
Apache License 2.0
src/test/kotlin/com/epam/brn/controller/UserSubGroupStatisticControllerTest.kt
Brain-up
216,092,521
false
{"Kotlin": 1057933, "Handlebars": 512629, "TypeScript": 401203, "JavaScript": 168755, "HTML": 45401, "CSS": 30742, "SCSS": 27412, "RAML": 22982, "Makefile": 545, "Shell": 405, "Dockerfile": 185}
package com.epam.brn.controller import com.epam.brn.dto.BaseResponseDto import com.epam.brn.dto.response.SubGroupStatisticResponse import com.epam.brn.dto.statistic.DayStudyStatistic import com.epam.brn.dto.statistic.MonthStudyStatistic import com.epam.brn.service.statistic.UserPeriodStatisticService import com.epam.brn.service.statistic.UserStatisticService import io.mockk.every import io.mockk.impl.annotations.InjectMockKs import io.mockk.impl.annotations.MockK import io.mockk.junit5.MockKExtension import io.mockk.verify import org.apache.http.HttpStatus import org.junit.jupiter.api.DisplayName import org.junit.jupiter.api.Test import org.junit.jupiter.api.extension.ExtendWith import kotlin.test.assertEquals @ExtendWith(MockKExtension::class) @DisplayName("UserStatisticController test using MockK") internal class UserStatisticControllerTest { @InjectMockKs private lateinit var userStatisticController: UserStatisticController @MockK private lateinit var userStatisticService: UserStatisticService<SubGroupStatisticResponse> @MockK private lateinit var userDayStatisticService: UserPeriodStatisticService<DayStudyStatistic> @MockK private lateinit var userMonthStatisticService: UserPeriodStatisticService<MonthStudyStatistic> @MockK private lateinit var subGroupStatisticResponse: SubGroupStatisticResponse @Test fun `should get user sub group statistic`() { // GIVEN val subGroupStatisticDtoList = listOf(subGroupStatisticResponse) val ids = listOf(1L, 2L, 3L) // WHEN every { userStatisticService.getSubGroupStatistic(ids) } returns subGroupStatisticDtoList val userSubGroupStatistic = userStatisticController.getUserSubGroupStatistic(ids) // THEN verify(exactly = 1) { userStatisticService.getSubGroupStatistic(ids) } assertEquals(HttpStatus.SC_OK, userSubGroupStatistic.statusCodeValue) assertEquals(subGroupStatisticDtoList, (userSubGroupStatistic.body as BaseResponseDto).data) } }
76
Kotlin
26
61
310cfcae2b9780740554396271444388258ce8da
2,045
brn
Creative Commons Zero v1.0 Universal
compose/foundation/foundation/src/desktopMain/kotlin/androidx/compose/foundation/Clickable.desktop.kt
RikkaW
389,105,112
false
null
/* * Copyright 2021 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package androidx.compose.foundation import androidx.compose.foundation.gestures.forEachGesture import androidx.compose.foundation.interaction.MutableInteractionSource import androidx.compose.runtime.Immutable import androidx.compose.runtime.remember import androidx.compose.runtime.rememberUpdatedState import androidx.compose.ui.Modifier import androidx.compose.ui.composed import androidx.compose.ui.input.pointer.AwaitPointerEventScope import androidx.compose.ui.input.pointer.PointerButtons import androidx.compose.ui.input.pointer.PointerEvent import androidx.compose.ui.input.pointer.PointerInputScope import androidx.compose.ui.input.pointer.PointerKeyboardModifiers import androidx.compose.ui.input.pointer.changedToDown import androidx.compose.ui.input.pointer.changedToUp import androidx.compose.ui.input.pointer.consumeDownChange import androidx.compose.ui.input.pointer.isOutOfBounds import androidx.compose.ui.input.pointer.pointerInput import androidx.compose.ui.platform.debugInspectorInfo import androidx.compose.ui.semantics.Role import androidx.compose.ui.util.fastAll import kotlinx.coroutines.coroutineScope // TODO: b/168524931 - should this depend on the input device? internal actual val TapIndicationDelay: Long = 0L @Immutable @ExperimentalFoundationApi class MouseClickScope constructor( val buttons: PointerButtons, val keyboardModifiers: PointerKeyboardModifiers ) @ExperimentalFoundationApi internal val EmptyClickContext = MouseClickScope( PointerButtons(0), PointerKeyboardModifiers(0) ) /** * Creates modifier similar to [Modifier.clickable] but provides additional context with * information about pressed buttons and keyboard modifiers * */ @ExperimentalFoundationApi fun Modifier.mouseClickable( enabled: Boolean = true, onClickLabel: String? = null, role: Role? = null, onClick: MouseClickScope.() -> Unit ) = composed( factory = { val onClickState = rememberUpdatedState(onClick) val gesture = if (enabled) { Modifier.pointerInput(Unit) { detectTapWithContext( onTap = { down, _ -> onClickState.value.invoke( MouseClickScope( down.buttons, down.keyboardModifiers ) ) } ) } } else { Modifier } Modifier .genericClickableWithoutGesture( gestureModifiers = gesture, enabled = enabled, onClickLabel = onClickLabel, role = role, onLongClickLabel = null, onLongClick = null, indication = null, interactionSource = remember { MutableInteractionSource() }, onClick = { onClick(EmptyClickContext) } ) }, inspectorInfo = debugInspectorInfo { name = "clickable" properties["enabled"] = enabled properties["onClickLabel"] = onClickLabel properties["role"] = role properties["onClick"] = onClick } ) @OptIn(ExperimentalFoundationApi::class) internal suspend fun PointerInputScope.detectTapWithContext( onTap: ((PointerEvent, PointerEvent) -> Unit)? = null ) { forEachGesture { coroutineScope { awaitPointerEventScope { val down = awaitEventFirstDown().also { it.changes.forEach { it.consumeDownChange() } } val up = waitForFirstInboundUp() if (up != null) { up.changes.forEach { it.consumeDownChange() } onTap?.invoke(down, up) } } } } } private suspend fun AwaitPointerEventScope.awaitEventFirstDown(): PointerEvent { var event: PointerEvent do { event = awaitPointerEvent() } while ( !event.changes.fastAll { it.changedToDown() } ) return event } private suspend fun AwaitPointerEventScope.waitForFirstInboundUp(): PointerEvent? { while (true) { val event = awaitPointerEvent() val change = event.changes[0] if (change.changedToUp()) { return if (change.isOutOfBounds(size, extendedTouchPadding)) { null } else { event } } } }
6
null
937
7
6d53f95e5d979366cf7935ad7f4f14f76a951ea5
5,088
androidx
Apache License 2.0
src/main/kotlin/me/znepb/roadworks/block/signals/impl/ThreeHeadTrafficSignalRight.kt
znepb
674,486,233
false
{"Kotlin": 264114, "Java": 1022}
package me.znepb.roadworks.block.signals.impl import me.znepb.roadworks.Registry import me.znepb.roadworks.block.signals.AbstractOneHeadSignal import me.znepb.roadworks.block.signals.AbstractTrafficSignalBlockEntity import net.minecraft.block.BlockState import net.minecraft.block.entity.BlockEntity import net.minecraft.block.entity.BlockEntityTicker import net.minecraft.block.entity.BlockEntityType import net.minecraft.world.World class OneHeadTrafficSignalYellow(settings: Settings) : AbstractOneHeadSignal<OneHeadTrafficSignalYellowBlockEntity> (settings, ::OneHeadTrafficSignalYellowBlockEntity) { override fun <T : BlockEntity?> getTicker( world: World, state: BlockState, type: BlockEntityType<T>? ): BlockEntityTicker<T>? { if (world.isClient) return null return checkType( type, Registry.ModBlockEntities.ONE_HEAD_TRAFFIC_SIGNAL_YELLOW_BLOCK_ENTITY, AbstractTrafficSignalBlockEntity.Companion::onTick ) } }
0
Kotlin
1
6
c14b96b0c0c3e10aada1b2d56d72e0ce531e6731
1,023
roadworks
MIT License
app/src/main/java/com/hoc/weatherapp/data/models/apiresponse/currentweatherapiresponse/CurrentWeatherResponse.kt
hoc081098
146,096,095
false
null
package com.hoc.weatherapp.data.models.apiresponse.currentweatherapiresponse import com.hoc.weatherapp.data.models.apiresponse.Clouds import com.hoc.weatherapp.data.models.apiresponse.Coord import com.hoc.weatherapp.data.models.apiresponse.Rain import com.hoc.weatherapp.data.models.apiresponse.Snow import com.hoc.weatherapp.data.models.apiresponse.WeatherModel import com.hoc.weatherapp.data.models.apiresponse.Wind import com.squareup.moshi.Json class CurrentWeatherResponse( @Json(name = "coord") val coord: Coord? = null, @Json(name = "weather") val weather: List<WeatherModel>? = null, @Json(name = "base") val base: String? = null, @Json(name = "main") val main: Main? = null, @Json(name = "visibilityKm") val visibility: Double? = null, @Json(name = "wind") val wind: Wind? = null, @Json(name = "clouds") val clouds: Clouds? = null, @Json(name = "dt") val dt: Long? = null, @Json(name = "sys") val sys: Sys? = null, @Json(name = "id") val id: Long? = null, @Json(name = "name") val name: String? = null, @Json(name = "cod") val cod: Long? = null, @Json(name = "rain") val rain: Rain? = null, @Json(name = "snow") val snow: Snow? = null )
7
null
16
71
577cab95c896c68e02d337315e69749b9f55be0f
1,204
WeatherApp_MVI_sample
MIT License
tests/input/src/test/kotlin/test/InputTest.kt
apollographql
69,469,299
false
null
package test import com.apollographql.apollo3.api.Optional import com.example.CreateUser2Query import com.example.CreateUserQuery import com.example.type.FindUserInput import com.example.type.UserInput import org.junit.Test import kotlin.test.assertEquals import kotlin.test.assertFailsWith class InputTest { @Test fun simple() { val input = UserInput.Builder() .name("<NAME>") .email("<EMAIL>") .build() assertEquals("Test User", input.name) assertEquals(Optional.present("<EMAIL>"), input.email) val query1 = CreateUserQuery.Builder() .input(input) .build() assertEquals("Test User", query1.input.name) val query2 = CreateUser2Query.Builder() .input(input) .build() assertEquals("Test User", query2.input?.name) } @Test fun oneOfWithConstructor() { FindUserInput(email = Optional.present("<EMAIL>")) var e = assertFailsWith<IllegalArgumentException> { FindUserInput( email = Optional.present("<EMAIL>"), name = Optional.present("<NAME>"), ) } assertEquals("@oneOf input must have one field set (got 2)", e.message) e = assertFailsWith<IllegalArgumentException> { FindUserInput() } assertEquals("@oneOf input must have one field set (got 0)", e.message) e = assertFailsWith<IllegalArgumentException> { FindUserInput(email = Optional.present(null)) } assertEquals("The value set on @oneOf input field must be non-null", e.message) e = assertFailsWith<IllegalArgumentException> { FindUserInput( email = Optional.present(null), name = Optional.present("<NAME>") ) } assertEquals("@oneOf input must have one field set (got 2)", e.message) } @Test fun oneOfWithBuilder() { FindUserInput.Builder() .email("<EMAIL>") .build() var e = assertFailsWith<IllegalArgumentException> { FindUserInput.Builder() .email("<EMAIL>") .name("<NAME>") .build() } assertEquals("@oneOf input must have one field set (got 2)", e.message) e = assertFailsWith<IllegalArgumentException> { FindUserInput.Builder() .build() } assertEquals("@oneOf input must have one field set (got 0)", e.message) e = assertFailsWith<IllegalArgumentException> { FindUserInput.Builder() .email(null) .build() } assertEquals("The value set on @oneOf input field must be non-null", e.message) e = assertFailsWith<IllegalArgumentException> { FindUserInput.Builder() .email(null) .name("<NAME>") .build() } assertEquals("@oneOf input must have one field set (got 2)", e.message) } }
164
null
651
3,750
174cb227efe76672cf2beac1affc7054f6bb2892
2,759
apollo-kotlin
MIT License
plugins/github/src/org/jetbrains/plugins/github/api/data/pullrequest/GHPullRequestShort.kt
JetBrains
2,489,216
false
null
// Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.plugins.github.api.data.pullrequest import com.fasterxml.jackson.annotation.JsonIgnore import com.fasterxml.jackson.annotation.JsonProperty import com.intellij.collaboration.api.dto.GraphQLFragment import com.intellij.collaboration.api.dto.GraphQLNodesDTO import com.intellij.openapi.util.NlsSafe import org.jetbrains.plugins.github.api.data.* import org.jetbrains.plugins.github.pullrequest.data.GHPRIdentifier import java.util.* @GraphQLFragment("/graphql/fragment/pullRequestInfoShort.graphql") open class GHPullRequestShort(id: String, val url: String, val number: Long, @NlsSafe val title: String, val state: GHPullRequestState, val isDraft: Boolean, val author: GHActor?, val createdAt: Date, val updatedAt: Date, @JsonProperty("assignees") assignees: GraphQLNodesDTO<GHUser>, @JsonProperty("labels") labels: GraphQLNodesDTO<GHLabel>, @JsonProperty("reviewRequests") reviewRequests: GraphQLNodesDTO<GHPullRequestReviewRequest>, @JsonProperty("reviewThreads") reviewThreads: GraphQLNodesDTO<ReviewThreadDetails>, @JsonProperty("reviews") reviews: GraphQLNodesDTO<GHPullRequestReview>, val mergeable: GHPullRequestMergeableState, val viewerCanUpdate: Boolean, val viewerCanReact: Boolean, val viewerDidAuthor: Boolean, override val reactions: GHReactable.ReactionConnection) : GHNode(id), GHReactable { val prId = GHPRIdentifier(id, number) @JsonIgnore val assignees = assignees.nodes @JsonIgnore val labels = labels.nodes @JsonIgnore val reviewRequests = reviewRequests.nodes @JsonIgnore val unresolvedReviewThreadsCount = reviewThreads.nodes.count { !it.isResolved && !it.isOutdated } @JsonIgnore val reviews: List<GHPullRequestReview> = reviews.nodes override fun toString(): String = "#$number $title" override fun equals(other: Any?): Boolean { if (this === other) return true if (javaClass != other?.javaClass) return false if (!super.equals(other)) return false other as GHPullRequestShort if (url != other.url) return false if (number != other.number) return false if (title != other.title) return false if (state != other.state) return false if (isDraft != other.isDraft) return false if (author != other.author) return false if (createdAt != other.createdAt) return false if (updatedAt != other.updatedAt) return false if (mergeable != other.mergeable) return false if (viewerCanUpdate != other.viewerCanUpdate) return false if (viewerDidAuthor != other.viewerDidAuthor) return false if (prId != other.prId) return false if (assignees != other.assignees) return false if (labels != other.labels) return false if (reviewRequests != other.reviewRequests) return false if (unresolvedReviewThreadsCount != other.unresolvedReviewThreadsCount) return false if (reviews != other.reviews) return false return true } override fun hashCode(): Int { var result = super.hashCode() result = 31 * result + url.hashCode() result = 31 * result + number.hashCode() result = 31 * result + title.hashCode() result = 31 * result + state.hashCode() result = 31 * result + isDraft.hashCode() result = 31 * result + (author?.hashCode() ?: 0) result = 31 * result + createdAt.hashCode() result = 31 * result + updatedAt.hashCode() result = 31 * result + mergeable.hashCode() result = 31 * result + viewerCanUpdate.hashCode() result = 31 * result + viewerDidAuthor.hashCode() result = 31 * result + prId.hashCode() result = 31 * result + assignees.hashCode() result = 31 * result + labels.hashCode() result = 31 * result + reviewRequests.hashCode() result = 31 * result + unresolvedReviewThreadsCount result = 31 * result + reviews.hashCode() return result } class ReviewThreadDetails(val isResolved: Boolean, val isOutdated: Boolean) }
284
null
5162
16,707
def6433a5dd9f0a984cbc6e2835d27c97f2cb5f0
4,541
intellij-community
Apache License 2.0
compat/agp/src/main/kotlin/net/twisterrob/gradle/common/AGPVersions.kt
TWiStErRob
116,494,236
false
null
package net.twisterrob.gradle.common import org.jetbrains.annotations.TestOnly /** * Version constants for the Android Gradle Plugin. */ object AGPVersions { @Throws(IllegalStateException::class) fun olderThan4NotSupported(version: AGPVersion): Nothing { error("AGP ${version} is not supported, because it's older than ${v4xx}") } @Throws(IllegalStateException::class) fun olderThan7NotSupported(version: AGPVersion): Nothing { error("AGP ${version} is not supported, because it's older than ${v7xx}") } @Throws(IllegalStateException::class) fun otherThan4NotSupported(version: AGPVersion): Nothing { error("AGP ${version} is not supported, because it's not compatible with ${v4xx}") } /** * The version AGP on the classpath of the build running this plugin. * Not to be confused with the one used to compile this plugin, which is the latest supported. * In tests, the one on classpath comes from `testImplementation` or `testRuntimeOnly`, use [UNDER_TEST] in that case. * * @see com.android.Version * @throws IllegalStateException if there's no AGP on the classpath. * @throws IllegalStateException when the version number is not recognized. */ val CLASSPATH: AGPVersion @Throws(IllegalStateException::class) get() = AGPVersion.parse(ANDROID_GRADLE_PLUGIN_VERSION) /** * The test framework is executed with a specific AGP version. * Used for backwards compatibility testing. */ val UNDER_TEST: AGPVersion @TestOnly get() = AGPVersion.parse( System.getProperty("net.twisterrob.test.android.pluginVersion") ?: error("Property 'net.twisterrob.test.android.pluginVersion' is not set.") ) val v32x: AGPVersion = AGPVersion(3, 2, null, null) val v33x: AGPVersion = AGPVersion(3, 3, null, null) val v34x: AGPVersion = AGPVersion(3, 4, null, null) val v36x: AGPVersion = AGPVersion(3, 6, null, null) val v4xx: AGPVersion = AGPVersion(4, null, null, null) val v40x: AGPVersion = AGPVersion(4, 0, null, null) val v41x: AGPVersion = AGPVersion(4, 1, null, null) val v42x: AGPVersion = AGPVersion(4, 2, null, null) val v7xx: AGPVersion = AGPVersion(7, null, null, null) val v70x: AGPVersion = AGPVersion(7, 0, null, null) val v71x: AGPVersion = AGPVersion(7, 1, null, null) /** * Is there an Android Gradle Plugin on the classpath? * * If so, it must have a version, and [CLASSPATH] is usable. * * @see CLASSPATH */ val isAvailable: Boolean get() = try { ANDROID_GRADLE_PLUGIN_VERSION true } catch (ex: IllegalStateException) { false } /** * Determines the version of Android Gradle Plugin on the classpath. * AGP Version keeps moving around between versions. * * @throws IllegalStateException if there's no AGP on the classpath. */ private val ANDROID_GRADLE_PLUGIN_VERSION: String @Throws(IllegalStateException::class) get() { val versionClass: Class<*> = // Cannot use compatibility AGPVersions.CLASSPATH to create a `when` in this one, as this is defining it. kotlin .runCatching { // Introduced in AGP 3.6.x. Class.forName("com.android.Version") } .recoverCatching { // Deprecated in AGP 3.6.x and removed in AGP 4.x. Class.forName("com.android.builder.model.Version") } .recoverCatching { error("Cannot find AGP Version class on the classpath") } .getOrThrow() return versionClass.getDeclaredField("ANDROID_GRADLE_PLUGIN_VERSION").get(null) as String } }
46
Kotlin
1
7
b207c0bce0c0f7f3405fb54d10071547f60a0eb4
3,474
net.twisterrob.gradle
MIT License
src/commonMain/kotlin/api/resources/Playlists.kt
kotlinfunc
565,100,240
false
null
package api.resources import io.ktor.resources.* import kotlinx.serialization.Serializable @Serializable @Resource("/playlists/list") class Playlists(val playlistIds: List<String>)
0
null
0
0
4ac5e027fb2f63eb7235ce2add8be6d36002d711
182
yandex-music-kotlin
Do What The F*ck You Want To Public License
app/src/main/java/dev/vengateshm/dribbox/presentation/home/components/Home.kt
vengateshm
446,151,154
false
{"Kotlin": 39209}
package dev.vengateshm.dribbox.presentation.home.components import androidx.compose.foundation.* import androidx.compose.foundation.layout.* import androidx.compose.foundation.lazy.GridCells import androidx.compose.foundation.lazy.LazyVerticalGrid import androidx.compose.foundation.lazy.items import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.foundation.text.BasicTextField import androidx.compose.material.Icon import androidx.compose.material.IconButton import androidx.compose.material.Text import androidx.compose.runtime.Composable import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.graphics.Color import androidx.compose.ui.res.painterResource import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.sp import dev.vengateshm.dribbox.R import dev.vengateshm.dribbox.presentation.home.Folder import dev.vengateshm.dribbox.ui.theme.TextColor1 @ExperimentalFoundationApi @Composable fun Home(folderList: List<Folder>, onHeaderMenuClick: () -> Unit) { Column { Header(onHeaderMenuClick) SearchBar() Filter() FolderGrid(folderList) } } @Composable fun Header(onHeaderMenuClick: () -> Unit) { Row( modifier = Modifier .fillMaxWidth() .padding(16.dp) .padding(end = 8.dp), horizontalArrangement = Arrangement.SpaceBetween, verticalAlignment = Alignment.CenterVertically ) { Text( text = "Your Dribbox", color = TextColor1, fontSize = 24.sp, fontWeight = FontWeight(600) ) Image( painter = painterResource(id = R.drawable.ic_header_icon), contentDescription = "Header icon", modifier = Modifier.clickable { onHeaderMenuClick() } ) } } @Composable fun SearchBar() { Box( modifier = Modifier .fillMaxWidth() .padding(16.dp) ) { Row( modifier = Modifier .fillMaxWidth() .border( width = 1.dp, color = Color(0XFFEEF2FE), shape = RoundedCornerShape(10.dp) ) .padding(16.dp), verticalAlignment = Alignment.CenterVertically ) { Image( painter = painterResource(id = R.drawable.ic_search), contentDescription = "Search icon" ) Spacer(modifier = Modifier.width(8.dp)) Box { BasicTextField( value = "", onValueChange = {}, singleLine = true, modifier = Modifier .fillMaxWidth() ) Text( text = "Search Folder", fontWeight = FontWeight(500), fontSize = 16.sp, color = TextColor1 ) } } } } @Composable fun Filter() { Row( modifier = Modifier .fillMaxWidth() .padding(16.dp), horizontalArrangement = Arrangement.SpaceBetween, verticalAlignment = Alignment.CenterVertically ) { Text( text = "Recent", color = TextColor1, fontSize = 15.sp, fontWeight = FontWeight(600) ) IconButton(onClick = { /*TODO*/ }) { Icon( painter = painterResource(id = R.drawable.ic_filter_arrow_down), contentDescription = "Filter arrow down icon" ) } Spacer(modifier = Modifier.weight(1f)) IconButton(onClick = { /*TODO*/ }) { Icon( painter = painterResource(id = R.drawable.ic_list_view), contentDescription = "List view icon" ) } Spacer(modifier = Modifier.width(8.dp)) IconButton(onClick = { /*TODO*/ }) { Icon( painter = painterResource(id = R.drawable.ic_grid_view), contentDescription = "List view icon" ) } } } @ExperimentalFoundationApi @Composable fun FolderGrid(folderList: List<Folder>) { LazyVerticalGrid( cells = GridCells.Fixed(2), contentPadding = PaddingValues(4.dp) ) { items(folderList) { folder -> FolderItem(folder = folder) } } } @Composable fun FolderItem(folder: Folder) { Box(modifier = Modifier .fillMaxWidth() .padding(4.dp)) { Row( modifier = Modifier .fillMaxWidth() .background( color = folder.backgroundColor!!, shape = RoundedCornerShape(20.dp) ) .padding(16.dp), horizontalArrangement = Arrangement.SpaceBetween ) { Column { Image( painter = painterResource(id = folder.folderIconRes!!), contentDescription = "Folder image" ) Spacer(modifier = Modifier.height(8.dp)) Text( text = folder.name, fontSize = 15.sp, fontWeight = FontWeight(500), color = folder.textColor!! ) Text( text = folder.date, fontSize = 10.sp, fontWeight = FontWeight(400), color = folder.textColor ) } IconButton( onClick = { /*TODO*/ }, modifier = Modifier.align(Alignment.Top) ) { Icon( painter = painterResource(id = R.drawable.ic_more_option), contentDescription = "More icon", tint = folder.textColor!! ) } } } }
0
Kotlin
0
0
b420205453e4e3f365830dd52e0ccfd67a8a8282
6,089
jetpack_compose_cloud_storage_manager
Apache License 2.0
kotlin-analysis-api/src/main/kotlin/com/google/devtools/ksp/impl/symbol/kotlin/KSValueParameterLiteImpl.kt
google
297,744,725
false
null
package com.google.devtools.ksp.impl.symbol.kotlin import com.google.devtools.ksp.common.IdKeyPair import com.google.devtools.ksp.common.KSObjectCache import com.google.devtools.ksp.common.impl.KSNameImpl import com.google.devtools.ksp.impl.symbol.kotlin.resolved.KSTypeReferenceResolvedImpl import com.google.devtools.ksp.symbol.* import org.jetbrains.kotlin.analysis.api.types.KaType class KSValueParameterLiteImpl private constructor(ktType: KaType, override val parent: KSNode) : KSValueParameter { companion object : KSObjectCache<IdKeyPair<KaType, KSNode>, KSValueParameter>() { fun getCached(ktType: KaType, parent: KSNode): KSValueParameter = cache.getOrPut(IdKeyPair(ktType, parent)) { KSValueParameterLiteImpl(ktType, parent) } } // preferably maybe use empty name to match compiler, but use underscore to match FE1.0 implementation. override val name: KSName = KSNameImpl.getCached("_") override val type: KSTypeReference = KSTypeReferenceResolvedImpl.getCached(ktType) override val isVararg: Boolean = false override val isNoInline: Boolean = false override val isCrossInline: Boolean = false override val isVal: Boolean = false override val isVar: Boolean = false override val hasDefault: Boolean = false override val annotations: Sequence<KSAnnotation> = emptySequence() override val origin: Origin = parent.origin override val location: Location = parent.location override fun <D, R> accept(visitor: KSVisitor<D, R>, data: D): R { return visitor.visitValueParameter(this, data) } }
370
null
268
2,854
a977fb96b05ec9c3e15b5a0cf32e8e7ea73ab3b3
1,615
ksp
Apache License 2.0
app/src/main/java/ru/glindaqu/ejournal/viewModel/implementation/HomeViewModel.kt
glindaqu
789,473,966
false
{"Kotlin": 8175}
package ru.glindaqu.ejournal.viewModel.implementation import android.app.Application import androidx.lifecycle.AndroidViewModel import ru.glindaqu.ejournal.viewModel.api.IHomeViewModel class HomeViewModel(application: Application) : IHomeViewModel, AndroidViewModel(application) { }
0
Kotlin
0
0
ce70079f47af3f75208d269e56d059bc68acccb1
284
EJournal
MIT License
services/csm.cloud.project.project/src/main/kotlin/com/bosch/pt/iot/smartsite/project/download/repository/DownloadBlobStorageRepository.kt
boschglobal
805,348,245
false
{"Kotlin": 13156190, "HTML": 274761, "Go": 184388, "HCL": 158560, "Shell": 117666, "Java": 52634, "Python": 51306, "Dockerfile": 10348, "Vim Snippet": 3969, "CSS": 344}
/* * ************************************************************************ * * Copyright: <NAME> Power Tools GmbH, 2018 - 2022 * * ************************************************************************ */ package com.bosch.pt.iot.smartsite.project.download.repository import com.bosch.pt.csm.cloud.common.ExcludeFromCodeCoverage import com.bosch.pt.iot.smartsite.application.config.DownloadBlobStorageProperties import com.bosch.pt.iot.smartsite.application.security.SecurityContextHelper import com.azure.storage.blob.BlobContainerClient import com.azure.storage.blob.models.BlobHttpHeaders import com.azure.storage.blob.models.BlobStorageException import com.azure.storage.blob.sas.BlobContainerSasPermission import com.azure.storage.blob.sas.BlobServiceSasSignatureValues import java.io.BufferedOutputStream import java.io.IOException import java.io.OutputStream import java.lang.Boolean.FALSE import java.net.MalformedURLException import java.net.URL import java.time.OffsetDateTime import java.util.UUID import java.util.UUID.randomUUID import org.springframework.beans.factory.annotation.Qualifier import org.springframework.stereotype.Component @Component class DownloadBlobStorageRepository( @Qualifier("downloadContainerClient") private val blobContainerClient: BlobContainerClient, private val properties: DownloadBlobStorageProperties, ) { @ExcludeFromCodeCoverage fun save( fileContent: ByteArray, fileName: String, mimeType: String, metadata: Map<String, String> ): UUID { return uploadBlobStream(fileName, mimeType, metadata) { os -> fileContent.inputStream().use { it.copyTo(os, BUFFER_SIZE) } } } fun uploadBlobStream( fileName: String, mimeType: String, metadata: Map<String, String>, uploadBlock: (OutputStream) -> Unit ): UUID { val documentId = randomUUID() val fileNameSanitized = fileName.replace("[^a-zA-Z0-9.]+".toRegex(), "_") try { val blockBlobClient = blobContainerClient.getBlobClient(generateBlobName(documentId)).blockBlobClient BufferedOutputStream(blockBlobClient.blobOutputStream, BUFFER_SIZE).use { bos -> uploadBlock.invoke(bos) } blockBlobClient.setHttpHeaders( BlobHttpHeaders() .setContentType(mimeType) .setContentDisposition("attachment; filename=\"$fileNameSanitized\"")) blockBlobClient.setMetadata(metadata + ("filename" to fileNameSanitized)) } catch (e: IOException) { error(e) } catch (e: BlobStorageException) { error(e) } return documentId } @ExcludeFromCodeCoverage fun generateSignedUrl(documentId: UUID): URL { val blockBlobClient = blobContainerClient.getBlobClient(generateBlobName(documentId)).blockBlobClient if (FALSE == blockBlobClient.exists()) { throw IllegalStateException("Blob does not exists") } return try { OffsetDateTime.now() .plusSeconds(properties.sharedAccessExpiryTimeSeconds) .let { BlobServiceSasSignatureValues(it, BlobContainerSasPermission.parse("r")) } .let { blockBlobClient.generateSas(it) } .let { URL("${blockBlobClient.blobUrl}?$it") } } catch (e: MalformedURLException) { throw IllegalStateException(e) } } private fun generateBlobName(identifier: UUID) = "${SecurityContextHelper.getInstance().getCurrentUser().identifier}/$identifier}" companion object { /** * Stream buffer size: needs to be reasonably high for upload speed to the blob store, but not * too high to avoid memory pressure on the service. 4MB is enough to upload most attachments in * a single step. */ const val BUFFER_SIZE = 4 * 1024 * 1024 // 4MB } }
0
Kotlin
3
9
9f3e7c4b53821bdfc876531727e21961d2a4513d
3,778
bosch-pt-refinemysite-backend
Apache License 2.0
client/android/div/src/main/java/com/yandex/div/core/view2/animations/Utils.kt
divkit
523,491,444
false
{"Kotlin": 7327303, "Swift": 5164616, "Svelte": 1148832, "TypeScript": 912803, "Dart": 630920, "Python": 536031, "Java": 507940, "JavaScript": 152546, "CSS": 37870, "HTML": 23434, "C++": 20911, "CMake": 18677, "Shell": 8895, "PEG.js": 7210, "Ruby": 3723, "C": 1425, "Objective-C": 38}
package com.yandex.div.core.view2.animations import android.graphics.drawable.Drawable import android.graphics.drawable.LayerDrawable import android.view.MotionEvent import android.view.View import android.view.ViewGroup import android.view.animation.AlphaAnimation import android.view.animation.Animation import android.view.animation.AnimationSet import android.view.animation.ScaleAnimation import androidx.core.content.ContextCompat import androidx.transition.Transition import androidx.transition.TransitionValues import com.yandex.div.R import com.yandex.div.core.animation.reversed import com.yandex.div.core.util.androidInterpolator import com.yandex.div.core.util.isActuallyLaidOut import com.yandex.div.json.expressions.Expression import com.yandex.div.json.expressions.ExpressionResolver import com.yandex.div2.DivAnimation private const val MIN_ALPHA_VALUE = 0.0f private const val MAX_ALPHA_VALUE = 1.0f private const val DEFAULT_ALPHA_START_VALUE = 1f private const val DEFAULT_ALPHA_END_VALUE = 0.6f private const val MIN_SCALE_VALUE = 0.0f private const val DEFAULT_SCALE_START_VALUE = 1f private const val DEFAULT_SCALE_END_VALUE = 0.95f private const val SCALE_PIVOT_VALUE = 0.5f internal val DEFAULT_CLICK_ANIMATION = DivAnimation( duration = Expression.constant(100), endValue = Expression.constant(0.6), name = Expression.constant(DivAnimation.Name.FADE), startValue = Expression.constant(1.0) ) internal fun Transition.getViewForAnimate( view: View, sceneRoot: ViewGroup, values: TransitionValues, positionKey: String ): View { val startViewIsOverlayView = values.view == view /* * If start animation view is equals to overlay animation view, that means that * `androidx.transition.Visibility#onDisappear` expect to see real view as an overlay (cause * start view has no parents). * * If we get the copy and set it as `save_overlay_view` tag to get copy on next animation applying, * the tag will be anyway replaced by `androidx.transition.Visibility#onDisappear` with start view * so when applying second animation, we get our start view from `save_overlay_view` tag, * and so we will apply the first animation to the copied view and all future to the real view. */ return if (!startViewIsOverlayView && view.isActuallyLaidOut) { createOrGetVisualCopy(view, sceneRoot, this, values.values[positionKey] as IntArray) } else { view } } internal fun capturePosition(transitionValues: TransitionValues, savePosition: (IntArray) -> Unit) { val view = transitionValues.view val position = IntArray(2) view.getLocationOnScreen(position) savePosition(position) } internal fun DivAnimation.asTouchListener( expressionResolver: ExpressionResolver, view: View ): ((View, MotionEvent) -> Unit)? { val directAnimation = toAnimation(expressionResolver, view = view) val reverseAnimation = toAnimation(expressionResolver, reverse = true) if (directAnimation == null && reverseAnimation == null) { return null } return { v, event -> if (v.isEnabled && v.isClickable && v.hasOnClickListeners()) { when (event.action) { MotionEvent.ACTION_DOWN -> directAnimation?.let { v.startAnimation(it) } MotionEvent.ACTION_CANCEL, MotionEvent.ACTION_UP -> reverseAnimation?.let { v.startAnimation(it) } } } } } private fun DivAnimation.toAnimation( resolver: ExpressionResolver, reverse: Boolean = false, view: View? = null ): Animation? { val animationName = name.evaluate(resolver) val animation = when (animationName) { DivAnimation.Name.SET -> AnimationSet(false).apply { items?.forEach { divAnimation -> val animation = divAnimation.toAnimation(resolver, reverse, view) animation?.let { addAnimation(it) } } } DivAnimation.Name.SCALE -> if (reverse) { createScaleAnimation( endValue?.evaluate(resolver).scaleValue() ?: DEFAULT_SCALE_END_VALUE, startValue?.evaluate(resolver).scaleValue() ?: DEFAULT_SCALE_START_VALUE ) } else { createScaleAnimation( startValue?.evaluate(resolver).scaleValue() ?: DEFAULT_SCALE_START_VALUE, endValue?.evaluate(resolver).scaleValue() ?: DEFAULT_SCALE_END_VALUE ) } DivAnimation.Name.NATIVE -> { if (view != null) { val layers = view.background as? LayerDrawable val shouldAddAnimation = layers == null || (0 until layers.numberOfLayers).none { layers.getId(it) == R.drawable.native_animation_background } if (shouldAddAnimation) { val drawables = mutableListOf<Drawable>() layers?.let { for (i in 0 until it.numberOfLayers) { drawables.add(it.getDrawable(i)) } } ?: drawables.add(view.background) val animation = ContextCompat.getDrawable( view.context, R.drawable.native_animation_background ) animation?.let { drawables.add(it) } val layerDrawable = LayerDrawable(drawables.toTypedArray()) layerDrawable.setId( drawables.size - 1, R.drawable.native_animation_background ) //mark background has animation view.background = layerDrawable } } null } DivAnimation.Name.NO_ANIMATION -> null else -> if (reverse) { AlphaAnimation( endValue?.evaluate(resolver).alphaValue() ?: DEFAULT_ALPHA_END_VALUE, startValue?.evaluate(resolver).alphaValue() ?: DEFAULT_ALPHA_START_VALUE ) } else { AlphaAnimation( startValue?.evaluate(resolver).alphaValue() ?: DEFAULT_ALPHA_START_VALUE, endValue?.evaluate(resolver).alphaValue() ?: DEFAULT_ALPHA_END_VALUE ) } } if (animationName != DivAnimation.Name.SET) { animation?.interpolator = if (reverse) { interpolator.evaluate(resolver).androidInterpolator.reversed() } else { interpolator.evaluate(resolver).androidInterpolator } animation?.duration = duration.evaluate(resolver) } animation?.startOffset = startDelay.evaluate(resolver) animation?.fillAfter = true return animation } private fun createScaleAnimation(startValue: Float, endValue: Float) = ScaleAnimation( startValue, endValue, startValue, endValue, Animation.RELATIVE_TO_SELF, SCALE_PIVOT_VALUE, Animation.RELATIVE_TO_SELF, SCALE_PIVOT_VALUE ) private fun Double?.alphaValue(): Float? { return this?.toFloat()?.coerceIn(MIN_ALPHA_VALUE, MAX_ALPHA_VALUE) } private fun Double?.scaleValue(): Float? { return this?.toFloat()?.coerceAtLeast(MIN_SCALE_VALUE) }
5
Kotlin
128
2,240
dd102394ed7b240ace9eaef9228567f98e54d9cf
7,400
divkit
Apache License 2.0
MonsterLabTechnicalTest/app/src/main/java/com/monsterlab/technicaltest/network/APIHelperImpl.kt
aliahmedbd
430,296,526
false
null
package com.monsterlab.technicaltest.network import com.monsterlab.technicaltest.model.ImagesModel import com.monsterlab.technicaltest.network.APIHelper import com.monsterlab.technicaltest.network.APIInterface import javax.inject.Inject /** * Created by <NAME>, mail: <EMAIL> */ class ApiHelperImpl @Inject constructor(private val apiService: APIInterface) : APIHelper { override suspend fun getImageList(page: Int?): List<ImagesModel> { return apiService.getImageList(page) } }
0
Kotlin
0
0
ecc17bf7f4e2491ce4f85b8b1de4ddafe6c725a3
500
MonsterLabTechnicalTest
Apache License 2.0
code/app/src/main/java/vn/eazy/base/mvp/example/mvp/di/module/UserModule.kt
harrylefit
93,927,281
false
null
package vn.eazy.base.mvp.example.mvp.di.module import dagger.Module import dagger.Provides import vn.eazy.base.mvp.di.scope.ActivityScope import vn.eazy.base.mvp.example.mvp.contract.UserContract import vn.eazy.base.mvp.example.mvp.model.UserModel /** * Created by harryle on 6/17/17. */ @Module class UserModule(private val mView: UserContract.View) { @ActivityScope @Provides internal fun provideUserView(): UserContract.View { return this.mView } @ActivityScope @Provides internal fun provideUserModel(model: UserModel): UserContract.Model { return model } }
1
Java
3
10
30abe4877baae4e7fb53c72eae304246cffe25d6
616
EazyBaseMVP
Apache License 2.0
apps/mobile-app/src/main/kotlin/dev/marlonlom/apps/cappajv/ui/navigation/MainNavHost.kt
marlonlom
766,685,767
false
{"Kotlin": 238268}
/* * Copyright 2024 Marlonlom * SPDX-License-Identifier: Apache-2.0 */ package dev.marlonlom.apps.cappajv.ui.navigation import androidx.compose.foundation.ExperimentalFoundationApi import androidx.compose.foundation.layout.ExperimentalLayoutApi import androidx.compose.material3.ExperimentalMaterial3Api import androidx.compose.runtime.Composable import androidx.navigation.NavGraphBuilder import androidx.navigation.compose.NavHost import androidx.navigation.compose.composable import dev.marlonlom.apps.cappajv.features.catalog_favorites.FavoriteProductsRoute import dev.marlonlom.apps.cappajv.features.catalog_list.CatalogListRoute import dev.marlonlom.apps.cappajv.features.catalog_search.CatalogSearchRoute import dev.marlonlom.apps.cappajv.ui.main.AppContentCallbacks import dev.marlonlom.apps.cappajv.ui.main.CappajvAppState /** * Main navigation host composable ui. * * @author marlonlom * * @param appState Application ui state. * @param appContentCallbacks Application content callbacks. */ @ExperimentalFoundationApi @ExperimentalMaterial3Api @ExperimentalLayoutApi @Composable fun MainNavHost( appState: CappajvAppState, appContentCallbacks: AppContentCallbacks, ) { NavHost( navController = appState.navController, startDestination = CatalogDestination.CatalogList.route, ) { catalogListDestination(appState) catalogFavoritesDestination(appState) catalogSearchDestination(appState) } } /** * Catalog list destination composable extension for navigation graph builder. * * @author marlonlom * * @param appState Application ui state. */ @ExperimentalFoundationApi @ExperimentalMaterial3Api @ExperimentalLayoutApi internal fun NavGraphBuilder.catalogListDestination( appState: CappajvAppState, ) { composable(CatalogDestination.CatalogList.route) { CatalogListRoute(appState) } } /** * Favorites products destination composable extension for navigation graph builder. * * @author marlonlom * * @param appState Application ui state. */ internal fun NavGraphBuilder.catalogFavoritesDestination( appState: CappajvAppState, ) { composable(CatalogDestination.FavoriteProducts.route) { FavoriteProductsRoute(appState) } } /** * Search catalog destination composable extension for navigation graph builder. * * @author marlonlom * * @param appState Application ui state. */ @ExperimentalFoundationApi internal fun NavGraphBuilder.catalogSearchDestination( appState: CappajvAppState, ) { composable(CatalogDestination.SearchProducts.route) { CatalogSearchRoute(appState) } }
0
Kotlin
0
0
669e0b66b8f8822a67ab6e820c2f632137f81f3b
2,571
cappajv
Apache License 2.0
app/src/main/java/com/example/android/trackmysleepquality/Util.kt
st0rmg0d
461,144,266
false
null
package com.example.android.trackmysleepquality import android.annotation.SuppressLint import android.content.res.Resources import java.text.SimpleDateFormat fun convertNumericQualityToString(quality: Int, resources: Resources): String { var qualityString = resources.getString(R.string.three_ok) when (quality) { -1 -> qualityString = "--" 0 -> qualityString = resources.getString(R.string.zero_very_bad) 1 -> qualityString = resources.getString(R.string.one_poor) 2 -> qualityString = resources.getString(R.string.two_soso) 4 -> qualityString = resources.getString(R.string.four_pretty_good) 5 -> qualityString = resources.getString(R.string.five_excellent) } return qualityString } @SuppressLint("SimpleDateFormat") fun convertLongToDateString(systemTime: Long): String { return SimpleDateFormat("EEEE MMM-dd-yyyy' Time: 'HH:mm") .format(systemTime).toString() }
0
Kotlin
1
0
5b27b3430a2f4a43ab59fa4c284607d86b365501
951
homework-camillebalima
MIT License
app/src/main/java/com/example/returnpals/services/SettingsViewModel.kt
BC-CS481-Capstone
719,299,432
false
{"Kotlin": 327246, "Java": 57406}
import android.util.Log import androidx.lifecycle.ViewModel import androidx.lifecycle.viewModelScope import com.amplifyframework.api.graphql.model.ModelQuery import com.amplifyframework.auth.AuthException import com.amplifyframework.auth.AuthSession import com.amplifyframework.auth.result.AuthResetPasswordResult import com.amplifyframework.core.Amplify import com.amplifyframework.datastore.generated.model.Address import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.StateFlow import kotlinx.coroutines.launch import com.amplifyframework.api.graphql.GraphQLResponse import com.amplifyframework.core.Consumer import com.amplifyframework.api.ApiException import com.amplifyframework.api.graphql.PaginatedResult import com.amplifyframework.api.graphql.model.ModelMutation import kotlin.random.Random class SettingsViewModel : ViewModel() { private val _operationStatus = MutableStateFlow<String?>(null) val operationStatus: StateFlow<String?> = _operationStatus private val _userEmail = MutableStateFlow<String?>(null) val userEmail: StateFlow<String?> = _userEmail private val _userAddresses = MutableStateFlow<List<SimpleAddress>>(emptyList()) val userAddresses: StateFlow<List<SimpleAddress>> = _userAddresses private val _addresses = MutableStateFlow<Map<Int, String>>(mapOf()) val addresses: StateFlow<Map<Int, String>> = _addresses private val _selectedAddressId = MutableStateFlow<Int?>(null) val selectedAddressId: StateFlow<Int?> = _selectedAddressId fun selectAddress(id: Int) { _selectedAddressId.value = id } fun addAddress(id: Int, address: String) { _addresses.value = _addresses.value.toMutableMap().apply { put(id, address) } } init { fetchUserEmail() fetchAddresses() } private fun fetchUserEmail() { viewModelScope.launch { try { Amplify.Auth.fetchAuthSession( { authSession: AuthSession -> if (authSession.isSignedIn) { // Now fetch user attributes since the user is signed in Amplify.Auth.fetchUserAttributes( { attributes -> val emailAttribute = attributes.firstOrNull { it.key.keyString == "email" } _userEmail.value = emailAttribute?.value }, { error: AuthException -> _operationStatus.value = "Error fetching user email: ${error.localizedMessage}" } ) } else { _operationStatus.value = "User is not signed in" } }, { error: AuthException -> _operationStatus.value = "Error fetching auth session: ${error.localizedMessage}" } ) } catch (e: AuthException) { _operationStatus.value = "Error fetching user info: ${e.localizedMessage}" } } } fun resetPassword(newPassword: String) { val email = _userEmail.value if (email.isNullOrEmpty()) { _operationStatus.value = "Error: No email found for the user." return } viewModelScope.launch { try { Amplify.Auth.resetPassword( email, { result: AuthResetPasswordResult -> if (result.isPasswordReset) { _operationStatus.value = "Password reset email sent successfully." } else { _operationStatus.value = "Password reset initiated. Please check your email for the confirmation code." } }, { error: AuthException -> _operationStatus.value = "Error resetting password: ${error.localizedMessage}" } ) } catch (e: AuthException) { _operationStatus.value = "Error resetting password: ${e.localizedMessage}" } } } fun confirmResetPassword(newPassword: String, confirmationCode: String) { viewModelScope.launch { try { val userEmail = _userEmail.value ?: return@launch // Get the user email or exit if null Amplify.Auth.confirmResetPassword( userEmail, // or username newPassword, confirmationCode, { // This is the success callback _operationStatus.value = "Password has been reset successfully." }, { error -> // This is the error handling callback _operationStatus.value = "Error confirming password reset: ${error.localizedMessage}" } ) } catch (e: AuthException) { _operationStatus.value = "Error confirming password reset: ${e.localizedMessage}" } } } fun fetchAddresses() { viewModelScope.launch { Amplify.API.query( ModelQuery.list(Address::class.java), // Correct Model class reference { response: GraphQLResponse<PaginatedResult<Address>> -> // Correct lambda parameter type if (response.hasData()) { Log.d("MyAmplifyApp", "Addresses fetched: ${response.data.items} found") val filteredAddresses = response.data.items.map { address -> SimpleAddress(address.address) } _userAddresses.value = filteredAddresses } else if (response.hasErrors()) { Log.e("MyAmplifyApp", "Error fetching addresses: ${response.errors.first().message}") } }, { error: ApiException -> // Correct error handling lambda parameter type Log.e("MyAmplifyApp", "Query failed: ${error.localizedMessage}", error) } ) } } data class SimpleAddress(val address: String,) fun addNewAddress(address: String) { val userId = generateRandomUserId() viewModelScope.launch { val newAddress = Address.builder() .address(address) .userId(userId) .build() try { Amplify.API.mutate( ModelMutation.create(newAddress), { response -> Log.i("MyAmplifyApp", "Address created: ${response.data.id}") fetchAddresses() // Optionally refresh addresses after adding _operationStatus.value = "Address added successfully with ID: ${response.data.id}" }, { error -> Log.e("MyAmplifyApp", "Failed to add address", error) _operationStatus.value = "Error adding address: ${error.localizedMessage}" } ) } catch (e: ApiException) { Log.e("MyAmplifyApp", "API Exception when trying to add address", e) _operationStatus.value = "Exception when adding address: ${e.localizedMessage}" } } } fun generateRandomUserId(): String { return Random.nextInt(100000, 999999).toString() // Generate a random number between 100000 and 999999 } }
26
Kotlin
0
0
b893f3998fc29477e9fc6b154b8b5acfa4f520f0
8,104
ReturnPalsApp
MIT License
libs/serialization/serialization-amqp/src/main/kotlin/net/corda/internal/serialization/amqp/custom/YearSerializer.kt
corda
346,070,752
false
{"Kotlin": 20585419, "Java": 308202, "Smarty": 115357, "Shell": 54409, "Groovy": 30246, "PowerShell": 6470, "TypeScript": 5826, "Solidity": 2024, "Batchfile": 244}
package net.corda.internal.serialization.amqp.custom import net.corda.serialization.BaseProxySerializer import java.time.Year /** * A serializer for [Year] that uses a proxy object to write out the integer form. */ class YearSerializer : BaseProxySerializer<Year, YearSerializer.YearProxy>() { override val type: Class<Year> get() = Year::class.java override val proxyType: Class<YearProxy> get() = YearProxy::class.java override val withInheritance: Boolean get() = false override fun toProxy(obj: Year): YearProxy = YearProxy(obj.value) override fun fromProxy(proxy: YearProxy): Year = Year.of(proxy.year) data class YearProxy(val year: Int) }
11
Kotlin
27
69
d478e119ab288af663910f9a2df42a7a7b9f5bce
693
corda-runtime-os
Apache License 2.0
sample/src/main/java/com/hieupt/standalonescrollbar/sample/HorizontalScrollViewActivity.kt
I3eyonder
318,128,746
false
null
package com.hieupt.standalonescrollbar.sample import android.os.Bundle import androidx.appcompat.app.AppCompatActivity import com.hieupt.android.standalonescrollbar.attachTo import com.hieupt.standalonescrollbar.R import kotlinx.android.synthetic.main.activity_horizontal_scroll_view.* class HorizontalScrollViewActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_horizontal_scroll_view) title = "Horizontal Scroll View" verticalScrollbar.apply { attachTo(horizontalScrollView) } horizontalScrollbar.apply { attachTo(horizontalScrollView) } } }
2
Kotlin
4
7
fca84c13279aca5f8de14981a1940e328c260056
736
android-standalone-scroll-bar
Apache License 2.0
feature-account-api/src/main/java/jp/co/soramitsu/account/api/presentation/account/AddressDisplayUseCase.kt
soramitsu
278,060,397
false
{"Kotlin": 5738459, "Java": 18796}
package jp.co.soramitsu.account.api.presentation.account import jp.co.soramitsu.account.api.domain.interfaces.AccountRepository import jp.co.soramitsu.shared_utils.extensions.fromHex import jp.co.soramitsu.shared_utils.ss58.SS58Encoder.toAccountId import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.withContext // TODO adopt for meta account logic class AddressDisplayUseCase( private val accountRepository: AccountRepository ) { class Identifier(private val addressToName: Map<String, String?>) { fun nameOrAddress(address: String): String { return addressToName[address] ?: address } } suspend operator fun invoke(address: String): String? { return withContext(Dispatchers.Default) { val accountId = kotlin.runCatching { address.toAccountId() }.getOrNull() ?: address.fromHex() accountRepository.findMetaAccount(accountId)?.name } } suspend fun createIdentifier(): Identifier = withContext(Dispatchers.Default) { val accounts = accountRepository.getAccounts().associateBy( keySelector = { it.address }, valueTransform = { it.name } ) Identifier(accounts) } }
15
Kotlin
30
89
1de6dfa7c77d4960eca2d215df2bdcf71a2ef5f2
1,225
fearless-Android
Apache License 2.0
core/common/src/main/kotlin/org/michaelbel/movies/common/coroutines/Dispatcher.kt
michaelbel
115,437,864
false
null
package org.michaelbel.movies.common.coroutines import javax.inject.Qualifier @Qualifier @Retention(AnnotationRetention.RUNTIME) annotation class Dispatcher( val dispatcher: MoviesDispatchers )
4
Kotlin
21
81
00b1cd807a4e7c894b0792ebb668e4cbcedc5605
199
movies
Apache License 2.0
composeUi/src/commonMain/kotlin/com/darkrockstudios/apps/hammer/common/encyclopedia/CreateEntryUi.kt
Wavesonics
499,367,913
false
null
package com.darkrockstudios.apps.hammer.common.encyclopedia import androidx.compose.foundation.background import androidx.compose.foundation.border import androidx.compose.foundation.layout.* import androidx.compose.foundation.rememberScrollState import androidx.compose.foundation.verticalScroll import androidx.compose.material.icons.Icons import androidx.compose.material.icons.filled.Delete import androidx.compose.material3.* import androidx.compose.runtime.Composable import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.saveable.rememberSaveable import androidx.compose.runtime.setValue import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.graphics.Color import androidx.compose.ui.text.input.TextFieldValue import androidx.compose.ui.unit.dp import com.arkivanov.decompose.extensions.compose.jetbrains.subscribeAsState import com.darkrockstudios.apps.hammer.MR import com.darkrockstudios.apps.hammer.common.components.encyclopedia.CreateEntry import com.darkrockstudios.apps.hammer.common.compose.* import com.darkrockstudios.apps.hammer.common.compose.moko.get import com.darkrockstudios.apps.hammer.common.data.encyclopediarepository.EncyclopediaRepository import com.darkrockstudios.apps.hammer.common.data.encyclopediarepository.EntryError import com.darkrockstudios.apps.hammer.common.data.encyclopediarepository.entry.EntryType import com.darkrockstudios.apps.hammer.common.getHomeDirectory import com.darkrockstudios.libraries.mpfilepicker.FilePicker import com.darkrockstudios.libraries.mpfilepicker.MPFile import io.github.aakira.napier.Napier import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.launch @OptIn(ExperimentalMaterial3Api::class) @Composable internal fun CreateEntryUi( component: CreateEntry, scope: CoroutineScope, snackbarHostState: SnackbarHostState, modifier: Modifier, close: () -> Unit ) { val state by component.state.subscribeAsState() val strRes = rememberStrRes() var newEntryNameText by rememberSaveable { mutableStateOf("") } var newEntryContentText by rememberSaveable(stateSaver = TextFieldValue.Saver) { mutableStateOf(TextFieldValue("")) } var newTagsText by rememberSaveable { mutableStateOf("") } var selectedType by rememberSaveable { mutableStateOf(EntryType.PERSON) } val types = rememberSaveable { EntryType.values().toList() } var showFilePicker by rememberSaveable { mutableStateOf(false) } var imagePath by rememberSaveable { mutableStateOf<MPFile<Any>?>(null) } BoxWithConstraints( modifier = Modifier.fillMaxSize(), contentAlignment = Alignment.Center ) { Card(modifier = Modifier.heightIn(0.dp, maxHeight).verticalScroll(rememberScrollState())) { Column( modifier = modifier.padding(Ui.Padding.XL) .widthIn(128.dp, 420.dp) ) { Text( MR.strings.encyclopedia_create_entry_header.get(), modifier = Modifier.padding(PaddingValues(bottom = Ui.Padding.XL)), style = MaterialTheme.typography.displayMedium ) Text( MR.strings.encyclopedia_create_entry_type_label.get(), style = MaterialTheme.typography.titleMedium, modifier = Modifier.padding(bottom = Ui.Padding.M) ) ExposedDropDown( modifier = Modifier.fillMaxWidth(), padding = Ui.Padding.XL, items = types, defaultIndex = types.indexOf(EntryType.PERSON) ) { item -> if (item != null) { selectedType = item } else { Napier.w { "EntryType cannot be null" } } } TextField( modifier = Modifier.fillMaxWidth() .padding(PaddingValues(top = Ui.Padding.XL, bottom = Ui.Padding.L)), value = newEntryNameText, onValueChange = { newEntryNameText = it }, placeholder = { Text(MR.strings.encyclopedia_create_entry_name_label.get()) } ) TextField( modifier = Modifier.fillMaxWidth().padding(PaddingValues(bottom = Ui.Padding.L)), value = newTagsText, onValueChange = { newTagsText = it }, placeholder = { Text(MR.strings.encyclopedia_create_entry_tags_label.get()) } ) OutlinedTextField( value = newEntryContentText, onValueChange = { newEntryContentText = it }, modifier = Modifier.fillMaxWidth().padding(PaddingValues(bottom = Ui.Padding.L)), placeholder = { Text(text = MR.strings.encyclopedia_create_entry_body_hint.get()) }, maxLines = 10, ) Spacer(modifier = Modifier.size(Ui.Padding.L)) Box( modifier = Modifier.fillMaxWidth() .border(width = 1.dp, color = MaterialTheme.colorScheme.outline), contentAlignment = Alignment.Center ) { if (imagePath != null) { Box(modifier = Modifier.width(IntrinsicSize.Min).height(IntrinsicSize.Min)) { ImageItem( modifier = Modifier.size(128.dp).background(Color.LightGray), path = imagePath?.path ) Button( modifier = Modifier .padding(PaddingValues(start = Ui.Padding.XL)) .align(Alignment.TopEnd), onClick = { imagePath = null } ) { Icon( Icons.Default.Delete, MR.strings.encyclopedia_create_entry_remove_image_button.get() ) } } } else { Button(onClick = { showFilePicker = true }) { Text(MR.strings.encyclopedia_create_entry_select_image_button.get()) } } } Spacer(modifier = Modifier.size(Ui.Padding.XL)) Row(modifier = Modifier.fillMaxWidth()) { Button( modifier = Modifier.weight(1f).padding(PaddingValues(end = Ui.Padding.XL)), onClick = { scope.launch { val result = component.createEntry( name = newEntryNameText, type = selectedType, text = newEntryContentText.text, tags = newTagsText.splitToSequence(" ").toList(), imagePath = imagePath?.path ) when (result.error) { EntryError.NAME_TOO_LONG -> scope.launch { snackbarHostState.showSnackbar( strRes.get( MR.strings.encyclopedia_create_entry_toast_too_long, EncyclopediaRepository.MAX_NAME_SIZE ) ) } EntryError.NAME_INVALID_CHARACTERS -> scope.launch { snackbarHostState.showSnackbar( strRes.get(MR.strings.encyclopedia_create_entry_toast_invalid_name) ) } EntryError.TAG_TOO_LONG -> scope.launch { snackbarHostState.showSnackbar( strRes.get( MR.strings.encyclopedia_create_entry_toast_tag_too_long, EncyclopediaRepository.MAX_TAG_SIZE ) ) } EntryError.NONE -> { newEntryNameText = "" close() scope.launch { snackbarHostState.showSnackbar(strRes.get(MR.strings.encyclopedia_create_entry_toast_success)) } } } } } ) { Text(MR.strings.encyclopedia_create_entry_create_button.get()) } Button( modifier = Modifier.weight(1f).padding(PaddingValues(start = Ui.Padding.XL)), onClick = { component.confirmClose() } ) { Text(MR.strings.encyclopedia_create_entry_cancel_button.get()) } } } } } FilePicker( show = showFilePicker, fileExtensions = listOf("jpg"), initialDirectory = getHomeDirectory() ) { path -> imagePath = path showFilePicker = false } if (state.showConfirmClose) { SimpleConfirm( title = MR.strings.encyclopedia_create_entry_discard_title.get(), onDismiss = { component.dismissConfirmClose() } ) { component.dismissConfirmClose() close() } } }
8
null
7
99
2feba4da350977e6eac5fdf07b3be644ee255b7a
7,614
hammer-editor
MIT License
app/src/main/java/com/msc/someweather/utilities/UnitUtils.kt
danding1207
146,581,858
false
{"Gradle": 3, "Java Properties": 2, "Markdown": 2, "Shell": 1, "Text": 1, "Ignore List": 2, "Batchfile": 1, "Git Attributes": 1, "YAML": 2, "Proguard": 1, "Kotlin": 92, "XML": 59, "Java": 12, "JSON": 1}
package com.msc.someweather.utilities import android.content.Context import android.graphics.drawable.Drawable import android.support.v4.content.ContextCompat import android.util.DisplayMetrics import android.view.WindowManager import com.msc.someweather.R import com.orhanobut.logger.Logger import java.text.ParseException import java.text.SimpleDateFormat import java.util.* object UnitUtils { /** * dp转换为px * * @param context * @param dpValue * dp值 * @return 转换后px值 */ fun dipTopx(context: Context, dpValue: Float): Int { val scale = context.resources.displayMetrics.density return (dpValue * scale + 0.5f).toInt() } /** * px转换为dp * * @param context * @param pxValue * px值 * @return 转换后dp值 */ fun pxTodip(context: Context, pxValue: Float): Int { val scale = context.resources.displayMetrics.density return (pxValue / scale + 0.5f).toInt() } /** * 将px值转换为sp值,保证文字大小不变   * * @param pxValue * @param fontScale * (DisplayMetrics类中属性scaledDensity) * @return           */ fun px2sp(context: Context, pxValue: Float): Int { val fontScale = context.resources.displayMetrics.scaledDensity return (pxValue / fontScale + 0.5f).toInt() } /** * 将sp值转换为px值,保证文字大小不变          * * @param spValue *           * @param fontScale * (DisplayMetrics类中属性scaledDensity) * @return           */ fun sp2px(context: Context, spValue: Float): Int { val fontScale = context.resources.displayMetrics.scaledDensity return (spValue * fontScale + 0.5f).toInt() } fun skyconToCh(skycon: String): String { return when (skycon) { "HAZE" -> "霾" "RAIN" -> "雨" "CLEAR_NIGHT" -> "晴夜" "PARTLY_CLOUDY_NIGHT" -> "阴夜" "PARTLY_CLOUDY_DAY" -> "阴天" "CLOUDY" -> "多云" "CLEAR_DAY" -> "晴天" else -> "未知" } } fun skyconToColor(context: Context, skycon: String): Int { return when (skycon) { "HAZE" -> ContextCompat.getColor(context, R.color.aqi_1) "RAIN" -> ContextCompat.getColor(context, R.color.aqi_1) "CLEAR_NIGHT" -> ContextCompat.getColor(context, R.color.aqi_1) "PARTLY_CLOUDY_NIGHT" -> ContextCompat.getColor(context, R.color.aqi_1) "PARTLY_CLOUDY_DAY" -> ContextCompat.getColor(context, R.color.aqi_1) "CLOUDY" -> ContextCompat.getColor(context, R.color.aqi_1) "CLEAR_DAY" -> ContextCompat.getColor(context, R.color.aqi_1) else -> ContextCompat.getColor(context, R.color.aqi_1) } } fun skyconToDrawable(context: Context, skycon: String): Drawable { return when (skycon) { "HAZE" -> ContextCompat.getDrawable(context, R.drawable.haze)!! "RAIN" -> ContextCompat.getDrawable(context, R.drawable.rain)!! "CLEAR_NIGHT" -> ContextCompat.getDrawable(context, R.drawable.clear_night)!! "PARTLY_CLOUDY_NIGHT" -> ContextCompat.getDrawable(context, R.drawable.partly_cloudy_night)!! "PARTLY_CLOUDY_DAY" -> ContextCompat.getDrawable(context, R.drawable.partly_cloudy_day)!! "CLOUDY" -> ContextCompat.getDrawable(context, R.drawable.cloudy)!! "CLEAR_DAY" -> ContextCompat.getDrawable(context, R.drawable.clear_day)!! else -> ContextCompat.getDrawable(context, R.drawable.clear_day)!! } } fun windToCh(wind: Double): String { return when (Math.round(wind / 22.5).toInt()) { 0 -> "北风" 1 -> "北东北风" 2 -> "东北风" 3 -> "东东北风" 4 -> "东风" 5 -> "东东南风" 6 -> "东南风" 7 -> "南东南风" 8 -> "南风" 9 -> "南西南风" 10 -> "西南风" 11 -> "西西南风" 12 -> "西风" 13 -> "西西北风" 14 -> "西北风" 15 -> "北西北风" else -> "北风" } } fun windToAngle(wind: Double): Int { return when { wind < 22.5 || wind >= 337.5 -> 180 wind >= 22.5 && wind < 67.5 -> 225 wind >= 67.5 && wind < 112.5 -> 270 wind >= 112.5 && wind < 157.5 -> 315 wind >= 157.5 && wind < 202.5 -> 0 wind >= 202.5 && wind < 247.5 -> 45 wind >= 247.5 && wind < 292.5 -> 90 wind >= 292.5 && wind < 337.5 -> 135 else -> 0 } } fun windToLevel(wind: Double): Int { return when { wind < 1 -> 0 5 < wind && wind < 1 -> 1 6 < wind && wind < 11 -> 2 12 < wind && wind < 19 -> 3 20 < wind && wind < 28 -> 4 29 < wind && wind < 38 -> 5 39 < wind && wind < 49 -> 6 50 < wind && wind < 61 -> 7 62 < wind && wind < 74 -> 8 75 < wind && wind < 88 -> 9 89 < wind && wind < 102 -> 10 103 < wind && wind < 116 -> 11 117 < wind && wind < 133 -> 12 134 < wind && wind < 149 -> 13 150 < wind && wind < 166 -> 14 167 < wind && wind < 183 -> 15 184 < wind && wind < 201 -> 16 202 < wind && wind < 220 -> 17 221 < wind -> 17 else -> 0 } } fun aqiToCh(aqi: Double): String { return when { aqi >= 0 && aqi < 50 -> "优" aqi >= 50 && aqi < 100 -> "良" aqi >= 100 && aqi < 150 -> "轻度" aqi >= 150 && aqi < 200 -> "中度" aqi >= 200 && aqi < 300 -> "重度" aqi >= 300 -> "严重" else -> "优" } } fun aqiToColor(context: Context, aqi: Double): Int { return when { aqi >= 0 && aqi < 50 -> ContextCompat.getColor(context, R.color.aqi_1) aqi >= 50 && aqi < 100 -> ContextCompat.getColor(context, R.color.aqi_2) aqi >= 100 && aqi < 150 -> ContextCompat.getColor(context, R.color.aqi_3) aqi >= 150 && aqi < 200 -> ContextCompat.getColor(context, R.color.aqi_4) aqi >= 200 && aqi < 300 -> ContextCompat.getColor(context, R.color.aqi_5) aqi >= 300 -> ContextCompat.getColor(context, R.color.aqi_6) else -> ContextCompat.getColor(context, R.color.aqi_1) } } fun getAndroiodScreenProperty(context: Context): List<Float> { val wm = context.getSystemService(Context.WINDOW_SERVICE) as WindowManager val dm = DisplayMetrics() wm.defaultDisplay.getMetrics(dm) val width: Int = dm.widthPixels // 屏幕宽度(像素) val height: Int = dm.heightPixels // 屏幕高度(像素) val density: Float = dm.density // 屏幕密度(0.75 / 1.0 / 1.5) // val densityDpi = dm.densityDpi // 屏幕密度dpi(120 / 160 / 240) // // 屏幕宽度算法:屏幕宽度(像素)/屏幕密度 // val screenWidth = (width / density).toInt() // 屏幕宽度(dp) // val screenHeight = (height / density).toInt()// 屏幕高度(dp) // Logger.d("h_bl", "屏幕宽度(像素):$width") // Logger.d("h_bl", "屏幕高度(像素):$height") // Logger.d("h_bl", "屏幕密度(0.75 / 1.0 / 1.5):$density") // Logger.d("h_bl", "屏幕密度dpi(120 / 160 / 240):$densityDpi") // Logger.d("h_bl", "屏幕宽度(dp):$screenWidth") // Logger.d("h_bl", "屏幕高度(dp):$screenHeight") return listOf(width.toFloat(), height.toFloat(), density) } /** * 判断是否为今天(效率比较高) * * @param day 传入的 时间 "2016-06-28 10:10:30" "2016-06-28" 都可以 * @return true今天 false不是 * @throws ParseException */ @Throws(ParseException::class) fun isToday(day: String): Boolean { val pre = Calendar.getInstance() val predate = Date(System.currentTimeMillis()) pre.time = predate val cal = Calendar.getInstance() val date = getDateFormat().parse(day) cal.time = date if (cal.get(Calendar.YEAR) == pre.get(Calendar.YEAR)) { val diffDay = cal.get(Calendar.DAY_OF_YEAR) - pre.get(Calendar.DAY_OF_YEAR) if (diffDay == 0) { return true } } return false } /** * 判断是否为昨天(效率比较高) * * @param day 传入的 时间 "2016-06-28 10:10:30" "2016-06-28" 都可以 * @return true今天 false不是 * @throws ParseException */ @Throws(ParseException::class) fun isYesterday(day: String): Boolean { val pre = Calendar.getInstance() val predate = Date(System.currentTimeMillis()) pre.time = predate val cal = Calendar.getInstance() val date = getDateFormat().parse(day) cal.time = date if (cal.get(Calendar.YEAR) == pre.get(Calendar.YEAR)) { val diffDay = cal.get(Calendar.DAY_OF_YEAR) - pre.get(Calendar.DAY_OF_YEAR) if (diffDay == -1) { return true } } return false } /** * Date转换为中文 * * @param day 传入的 时间 "2016-06-28 10:10:30" "2016-06-28" 都可以 * @return 中文:9月8日 * @throws ParseException */ fun dateToCh(day: String): String { val cal = Calendar.getInstance() val date = getDateFormat().parse(day) cal.time = date return "${cal.get(Calendar.MONTH)+1}月${cal.get(Calendar.DAY_OF_MONTH)}日" } /** * Date转换为中文星期 * * @param day 传入的 时间 "2016-06-28 10:10:30" "2016-06-28" 都可以 * @return 中文星期:周一 * @throws ParseException */ fun dateToWeekCh(day: String): String { val cal = Calendar.getInstance() val date = getDateFormat().parse(day) cal.time = date return when(cal.get(Calendar.DAY_OF_WEEK)) { 1-> "周日" 2-> "周一" 3-> "周二" 4-> "周三" 5-> "周四" 6-> "周五" 7-> "周六" else -> "错误" } } private fun getDateFormat(): SimpleDateFormat { if (null == DateLocal.get()) { DateLocal.set(SimpleDateFormat("yyyy-MM-dd", Locale.CHINA)) } return DateLocal.get() } private val DateLocal = ThreadLocal<SimpleDateFormat>() /** * 计算两个日期型的时间相差多少时间 * @param startDate 开始日期 * @param endDate 结束日期 * @return */ fun twoDateDistance(startDate: Date?, endDate: Date?): String? { if (startDate == null || endDate == null) { return null } var timeLong = endDate.time - startDate.time when { timeLong < 1000 -> return (timeLong).toString() + "毫秒前" timeLong < 60 * 1000 -> return (timeLong / 1000).toString() + "秒前" timeLong < 60 * 60 * 1000 -> { timeLong = timeLong / 1000 / 60 return timeLong.toString() + "分钟前" } timeLong < 60 * 60 * 24 * 1000 -> { timeLong = timeLong / 60 / 60 / 1000 return timeLong.toString() + "小时前" } timeLong < 60 * 60 * 24 * 1000 * 7 -> { timeLong = timeLong / 1000 / 60 / 60 / 24 return timeLong.toString() + "天前" } timeLong < 60 * 60 * 24 * 1000 * 7 * 4 -> { timeLong = timeLong / 1000 / 60 / 60 / 24 / 7 return timeLong.toString() + "周前" } else -> { val sdf = SimpleDateFormat("yyyy-MM-dd HH:mm:ss") sdf.timeZone = TimeZone.getTimeZone("GMT+08:00") return sdf.format(startDate) } } } }
0
Kotlin
0
0
65cda4c473fd094f4662a973362d0161a325870a
11,610
android-Jetpack-demo
Apache License 2.0
core/src/main/java/de/dseelp/kommon/command/arguments/UUIDArgument.kt
KelpFramework
211,553,334
false
null
package de.dseelp.kommon.command.arguments import de.dseelp.kommon.command.CommandContext import java.util.* /** * @author DSeeLP */ class UUIDArgument<S: Any>(name: String, val completer: CommandContext<S>.() -> Array<UUID> = { arrayOf() }) : Argument<S, UUID>(name) { constructor(name: String): this(name, { arrayOf() }) override fun get(value: String): UUID? = value.toUUIDOrNull() override fun getErrorMessage(): String = "%s is not a UUID" override fun complete(context: CommandContext<S>, value: String): Array<String> = completer.invoke(context).map { it.toString() }.filter { value.startsWith(it, true) }.toTypedArray() } fun String.toUUIDOrNull(): UUID? = try { UUID.fromString(this) }catch (ex: IllegalArgumentException) { null }
6
Java
7
50
1b7a876472457043a9430a2b0e2b28a234bab8b8
769
kelp
MIT License
src/Day03.kt
camina-apps
572,935,546
false
{"Kotlin": 7782}
import kotlin.math.floor import kotlin.math.roundToInt fun main() { fun priorityOfItem(letter: Char): Int { val offset = if (letter.isUpperCase()) 38 else 96 return letter.code - offset } fun findDuplicate(rucksack: String): Char { val half = (rucksack.length / 2.0).roundToInt() val firstCompartment = rucksack.slice(0 until half).toList() val secondCompartment = rucksack.slice(half until rucksack.length).toList() val duplicate = firstCompartment.intersect(secondCompartment) return duplicate.first() } fun findDuplicateBetweenElves(elvesRucksacks: List<String>): Char { val firstRucksack = elvesRucksacks.first().map { it.toChar() } val secondRucksack = elvesRucksacks[1].map { it.toChar() } val thirdRucksack = elvesRucksacks.last().map { it.toChar() } val intersection = firstRucksack.intersect(secondRucksack) val secondIntersection = thirdRucksack.intersect(intersection) return secondIntersection.first() } fun part1(input: List<String>): Int { return input.sumOf { val item = findDuplicate(it) priorityOfItem(item) } } fun part2(input: List<String>): Int { return input .chunked(3) .sumOf { val badge = findDuplicateBetweenElves(it) priorityOfItem(badge) } } val testInput = readInput("Day03_test") check(part1(testInput) == 157) check(part2(testInput) == 70) val input = readInput("Day03") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
fb6c6176f8c127e9d36aa0b7ae1f0e32b5c31171
1,639
aoc_2022
Apache License 2.0
graphics/src/main/java/com/gamapp/custom/ViewNumberPicker.kt
aliHosseinNezhad
507,626,994
false
null
package com.gamapp.custom import android.annotation.SuppressLint import android.content.Context import android.util.AttributeSet import android.util.Log import android.view.* import android.widget.* import androidx.core.view.GestureDetectorCompat import kotlinx.coroutines.* import kotlin.math.abs import kotlin.math.exp abstract class ViewNumberPicker<holder : ViewNumberPicker.ItemHolder> @JvmOverloads constructor( context: Context, attrs: AttributeSet? = null, ) : FrameLayout(context, attrs), GestureDetector.OnGestureListener { private val fling = CancelableCoroutine(CoroutineScope(Dispatchers.Main + Job())) private val visibleCount = 3 private val horizontal: Boolean = true private val frames = generateFrameLayouts() private var mDetector: GestureDetectorCompat = GestureDetectorCompat(context, this) private val maxIndex get() = getCount() - 1 private val bound get() = if (horizontal) width else height private val ih get() = if (horizontal) height else height / visibleCount private val iw get() = if (horizontal) width / visibleCount else width private val iBound get() = if (horizontal) iw else ih private fun View.scale(value: Float) { val scale = value * 1 + (1 - value) * 0.5f scaleX = scale scaleY = scale } private val onScrollEnd = CancelableCoroutine(CoroutineScope(Dispatchers.Main + Job())) private var setOnSelectedItemChange: ((position: Int) -> Unit)? = null var selectedIndex: Int = 0 set(value) { field = value setOnSelectedItemChange?.let { it(value) } } fun setOnSelectedItemChangeListener(listener: (position: Int) -> Unit) { setOnSelectedItemChange = listener } private fun generateFrameLayouts(): MutableList<ItemHolder> { val list = mutableListOf<ItemHolder>() (0..visibleCount + 1).forEach { list += onCreateHolder(context, this) } return list } private fun getIndex(size: Int, index: Int): Int { if (size < abs(index)) throw Exception("") return if (index < 0) size + index + 1 else index } init { layoutParams = LayoutParams(-1, -1) frames.forEach { addView(it.content) } post { setOnSelectedItemChange?.let { it(selectedIndex) } val iterator = frames.iterator() var count = -((visibleCount + 2) / 2) while (iterator.hasNext()) { val item = iterator.next() item.content.layoutParams = LayoutParams(iw, ih) item.content.setMargin(iBound * (count + visibleCount/2)) item.index = getIndex(maxIndex,count) item.content.alpha = 1f count++ } alphaOnViews() } } abstract fun onCreateHolder(context: Context, parent: ViewGroup): ItemHolder abstract fun getCount(): Int @SuppressLint("ClickableViewAccessibility") override fun onTouchEvent(event: MotionEvent): Boolean { event.run { when (action) { MotionEvent.ACTION_UP -> { if (!fling.inProgress) { onScrollEnd() } } } } return mDetector.onTouchEvent(event) } private fun startFling(initialVelocity: Float) { fling.start { var v = initialVelocity var count = 0 val s = initialVelocity.let { if (it > 0) 1f else -1f } while (true) { v = (exp(-count / 10000.0) * v).toFloat() count++ delay(1) if ((abs(v) * 1000) / bound < 0.15f) break scrollViews(-v * 1.5f) } onScrollEnd() } } fun topView(): ItemHolder? { val min = frames.toList().minOf { it.content.margin() } val views = frames.toList().filter { it.content.margin() == min } return views.firstOrNull() } private fun bottomView(): ItemHolder? { val max = frames.toList().maxOf { it.content.margin() } val views = frames.toList().filter { it.content.margin() == max } return views.firstOrNull() } private fun printMargins(): String { return frames.toList().map { it.content.margin().toString() }.joinToString { it } } private fun scrollViewI(df: Int) { val iterator = frames.iterator() val bottomView = bottomView()!! val topView = topView()!! if (topView.content.margin() + df > -iBound / 2) { Log.i("OnRecycle", "scrollViews: top start, ${printMargins()}") val value = (topView).index - 1 (bottomView).index = if (value < 0) maxIndex else value bottomView.content.setMargin(topView.content.margin() - iBound) Log.i("OnRecycle", "scrollViews: top after, ${printMargins()}") } else if (bottomView.content.margin() + iBound <= bound + iBound / 2) { Log.i("OnRecycle", "scrollViews: bottom before, ${printMargins()}") val value = (bottomView).index + 1 (topView).index = if (value <= maxIndex) value else 0 topView.content.setMargin(bottomView.content.margin() + iBound) Log.i("OnRecycle", "scrollViews: bottom after, ${printMargins()}") } while (iterator.hasNext()) { val view = iterator.next() view.content.setMargin(view.content.margin() + df) } alphaOnViews() } private fun scrollViews(_df: Float) { val count = _df.toInt() / (iBound / 2) val p = _df.toInt() % (iBound / 2) scrollViewI(p) for (i in 0 until count) { scrollViewI(iBound / 2) } } private fun alphaOnViews() { val total = (visibleCount+2) * iBound val iterator = frames.map { it.content }.iterator() while (iterator.hasNext()) { val view = iterator.next() val dy = bound / 2 - (view.margin() + iBound / 2) val alpha = 2 * abs(dy) / (total.toFloat()) val value = alpha.coerceIn(0f, 1f) view.alpha = exp(-value * value * 6f).coerceIn(0.1f, 1f) view.scale(view.alpha) } } override fun onDown(p0: MotionEvent): Boolean { return true } override fun onShowPress(p0: MotionEvent) {} override fun onSingleTapUp(p0: MotionEvent): Boolean { return true } override fun onScroll( p0: MotionEvent, p1: MotionEvent, distanceX: Float, distanceY: Float ): Boolean { onScrollEnd.stop() fling.stop() val d = if (horizontal) distanceX else distanceY scrollViews(-d) return true } private fun onScrollEnd() { val middleView = frames.minByOrNull { abs(bound / 2 - (it.content.margin() + iBound / 2)) } middleView?.let { view -> val df = bound / 2 - (view.content.margin() + iBound / 2) onScrollEnd.start { var count = 0 val s = if (df > 0) 1f else -1f while (count < abs(df)) { scrollViews(s * abs(df / 50).coerceAtLeast(1).toFloat()) delay(1) count += abs(df / 50).coerceAtLeast(1) } setOnSelectedItemChange?.let { it(view.index) } } } } override fun onLongPress(p0: MotionEvent) { } override fun onFling( p0: MotionEvent, p1: MotionEvent, velocityX: Float, velocityY: Float ): Boolean { val velocity = if (horizontal) velocityX else velocityY if (abs(velocity) / bound.toFloat() >= 0.2f) { startFling(-velocity / 1000f) } return false } abstract class ItemHolder constructor( val content: View, ) { var index = 0 set(value) { field = value onViewChanged(value) } abstract fun onViewChanged(position: Int) } private fun View.setMargin(margin: Int) { layoutParams = layoutParams.apply { this as LayoutParams if (horizontal) leftMargin = margin else topMargin = margin } } private fun View.margin(): Int { return (layoutParams as LayoutParams).let { if (horizontal) it.leftMargin else it.topMargin } } }
0
Kotlin
0
2
8eddbdbcd5706072262ed7bd2cf6b2d0a6df6ada
8,752
DMPlayer_public
MIT License
app/src/main/java/com/alejandromr/kontacts/domain/model/NameModel.kt
alejandromr92
396,426,398
false
null
package com.alejandromr.kontacts.domain.model import java.io.Serializable data class NameModel( val first: String, val last: String ) : Serializable
0
Kotlin
0
1
2bf4e49db7061fa7aa47ccecf091da2656e4f0bd
159
Kontacts
Apache License 2.0
app/src/test/java/org/simple/clinic/bp/entry/BpValidatorTest.kt
eco4ndly
244,967,563
false
{"Gradle": 9, "Shell": 4, "Markdown": 26, "Java Properties": 2, "Text": 1, "Ignore List": 8, "Batchfile": 1, "YAML": 3, "Kotlin": 1176, "XML": 237, "INI": 2, "Proguard": 2, "JSON": 62, "Java": 1, "SVG": 1}
package org.simple.clinic.bp.entry import com.google.common.truth.Truth.assertThat import org.junit.Test class BpValidatorTest { private val bpValidator = BpValidator() @Test fun `when systolic is less than diastolic, return error`() { val systolic = "90" val diastolic = "140" val result = bpValidator.validate(systolic, diastolic) assertThat(result).isEqualTo(BpValidator.Validation.ErrorSystolicLessThanDiastolic) } @Test fun `when systolic is less than minimum possible, return error`() { val systolic = "55" val diastolic = "55" val result = bpValidator.validate(systolic, diastolic) assertThat(result).isEqualTo(BpValidator.Validation.ErrorSystolicTooLow) } @Test fun `when systolic is more than maximum possible, return error`() { val systolic = "333" val diastolic = "88" val result = bpValidator.validate(systolic, diastolic) assertThat(result).isEqualTo(BpValidator.Validation.ErrorSystolicTooHigh) } @Test fun `when diastolic is less than minimum possible, return error`() { val systolic = "110" val diastolic = "33" val result = bpValidator.validate(systolic, diastolic) assertThat(result).isEqualTo(BpValidator.Validation.ErrorDiastolicTooLow) } @Test fun `when diastolic is more than maximum possible, return error`() { val systolic = "233" val diastolic = "190" val result = bpValidator.validate(systolic, diastolic) assertThat(result).isEqualTo(BpValidator.Validation.ErrorDiastolicTooHigh) } @Test fun `when systolic is empty, return error`() { val systolic = "" val diastolic = "190" val result = bpValidator.validate(systolic, diastolic) assertThat(result).isEqualTo(BpValidator.Validation.ErrorSystolicEmpty) } @Test fun `when diastolic is empty, return error`() { val systolic = "120" val diastolic = "" val result = bpValidator.validate(systolic, diastolic) assertThat(result).isEqualTo(BpValidator.Validation.ErrorDiastolicEmpty) } }
1
null
1
1
c0bb3139dada4f34206928ec81f1e5f6f056134b
2,030
simple-android
MIT License
game/plugins/src/main/kotlin/gg/rsmod/plugins/content/quests/impl/DoricsQuest.kt
2011Scape
578,880,245
false
{"Kotlin": 8904349, "Dockerfile": 1354}
package gg.rsmod.plugins.content.quests.impl import gg.rsmod.game.model.entity.Player import gg.rsmod.game.model.item.Item import gg.rsmod.plugins.api.Skills import gg.rsmod.plugins.api.cfg.Items import gg.rsmod.plugins.api.ext.getVarp import gg.rsmod.plugins.api.ext.setVarp import gg.rsmod.plugins.content.quests.* /** * @author Alycia <https://github.com/alycii> */ object DoricsQuest : Quest( name = "Doric's Quest", startPoint = "Talk to Doric at his home north of Falador.", requirements = emptyList(), requiredItems = "None, but a Mining level of 15 would be useful.", combat = "None.", rewards = "1 Quest Point, 1,300 Mining XP, 180 Coins, use of Doric's anvils.", pointReward = 1, varbit = 31, spriteId = 4431, slot = 3, stages = 2 ) { init { addQuest(this) } override fun getObjective(player: Player, stage: Int): QuestStage = when (stage) { 1 -> QuestStage( objectives = listOf( "I have spoken to ${red("Doric")}", "I need to collect some items and bring them to ${red("Doric")}", "", if (player.inventory.contains(Item(Items.CLAY, 6))) striked("6 Clay") else red("6 Clay"), if (player.inventory.contains(Item(Items.COPPER_ORE, 4))) striked("4 Copper Ore") else red("4 Copper Ore"), if (player.inventory.contains(Item(Items.IRON_ORE, 2))) striked("2 Iron Ore") else red("2 Iron Ore"), ) ) 2, 100 -> QuestStage( objectives = listOf( striked(text = "I have spoken to ${red("Doric")}"), striked(text = "I have collected some ${red("Clay")}, ${red("Copper Ore")}, and ${red("Iron Ore")}"), striked(text = "${red("Doric")} rewarded me for all my hard work"), striked(text = "I can now use ${red("Doric's Anvils")} whenever I want"), "", questCompleteText ) ) else -> TODO() } override fun finishQuest(player: Player) { player.advanceToNextStage(this, 99) player.inventory.remove(Items.CLAY, 6) player.inventory.remove(Items.COPPER_ORE, 4) player.inventory.remove(Items.IRON_ORE, 2) player.inventory.add(Items.COINS_995, 180) player.addXp(Skills.MINING, 1300.0) player.setVarp(QUEST_POINT_VARP, player.getVarp(QUEST_POINT_VARP).plus(pointReward)) player.buildQuestFinish( this, item = Items.STEEL_PICKAXE, rewards = arrayOf("1 Quest Point", "1,300 Mining XP", "180 Coins", "Use of Doric's Anvils") ) } }
39
Kotlin
79
34
e5400cc71bfa087164153d468979c5a3abc24841
2,683
game
Apache License 2.0
src/main/kotlin/uk/gov/justice/digital/hmpps/nomisuserrolesapi/resource/UserAccountResource.kt
ministryofjustice
407,125,432
false
null
package uk.gov.justice.digital.hmpps.nomisuserrolesapi.resource import io.swagger.v3.oas.annotations.Operation import io.swagger.v3.oas.annotations.media.Content import io.swagger.v3.oas.annotations.media.Schema import io.swagger.v3.oas.annotations.responses.ApiResponse import io.swagger.v3.oas.annotations.security.SecurityRequirement import jakarta.validation.Valid import jakarta.validation.constraints.Size import org.springframework.http.HttpStatus import org.springframework.http.MediaType import org.springframework.security.access.prepost.PreAuthorize import org.springframework.validation.annotation.Validated import org.springframework.web.bind.annotation.PathVariable import org.springframework.web.bind.annotation.PostMapping import org.springframework.web.bind.annotation.RequestBody import org.springframework.web.bind.annotation.RequestMapping import org.springframework.web.bind.annotation.ResponseStatus import org.springframework.web.bind.annotation.RestController import uk.gov.justice.digital.hmpps.nomisuserrolesapi.config.ErrorResponse import uk.gov.justice.digital.hmpps.nomisuserrolesapi.data.CreateAdminUserRequest import uk.gov.justice.digital.hmpps.nomisuserrolesapi.data.CreateGeneralUserRequest import uk.gov.justice.digital.hmpps.nomisuserrolesapi.data.CreateLinkedAdminUserRequest import uk.gov.justice.digital.hmpps.nomisuserrolesapi.data.CreateLinkedGeneralUserRequest import uk.gov.justice.digital.hmpps.nomisuserrolesapi.data.CreateLinkedLocalAdminUserRequest import uk.gov.justice.digital.hmpps.nomisuserrolesapi.data.CreateLocalAdminUserRequest import uk.gov.justice.digital.hmpps.nomisuserrolesapi.data.StaffDetail import uk.gov.justice.digital.hmpps.nomisuserrolesapi.data.UserDetail import uk.gov.justice.digital.hmpps.nomisuserrolesapi.service.UserService @RestController @Validated @RequestMapping("/users", produces = [MediaType.APPLICATION_JSON_VALUE]) class UserAccountResource( private val userService: UserService, ) { @PreAuthorize("hasRole('ROLE_CREATE_USER')") @PostMapping("/general-account") @ResponseStatus(HttpStatus.CREATED) @Operation( summary = "Create general user account", description = "Creates general user account, oracle schema and staff user information. Requires role ROLE_CREATE_USER", security = [SecurityRequirement(name = "CREATE_USER")], requestBody = io.swagger.v3.oas.annotations.parameters.RequestBody( content = [ Content( mediaType = "application/json", schema = Schema(implementation = CreateGeneralUserRequest::class), ), ], ), responses = [ ApiResponse( responseCode = "201", description = "General user information returned", ), ApiResponse( responseCode = "400", description = "Incorrect request to create user information", content = [Content(mediaType = "application/json", schema = Schema(implementation = ErrorResponse::class))], ), ApiResponse( responseCode = "401", description = "Unauthorized to access this endpoint", content = [Content(mediaType = "application/json", schema = Schema(implementation = ErrorResponse::class))], ), ApiResponse( responseCode = "403", description = "Incorrect permissions to create a user", content = [Content(mediaType = "application/json", schema = Schema(implementation = ErrorResponse::class))], ), ], ) fun createGeneralUser( @RequestBody @Valid createUserRequest: CreateGeneralUserRequest, ): UserDetail { val user = userService.createGeneralUser(createUserRequest) return userService.findByUsername(username = user.username) } @PreAuthorize("hasRole('ROLE_CREATE_USER')") @PostMapping("/local-admin-account") @ResponseStatus(HttpStatus.CREATED) @Operation( summary = "Create local admin user account", description = "Creates local admin user account, oracle schema and staff user information. Requires role ROLE_CREATE_USER", security = [SecurityRequirement(name = "CREATE_USER")], requestBody = io.swagger.v3.oas.annotations.parameters.RequestBody( content = [ Content( mediaType = "application/json", schema = Schema(implementation = CreateLocalAdminUserRequest::class), ), ], ), responses = [ ApiResponse( responseCode = "201", description = "Local Admin user information returned", ), ApiResponse( responseCode = "400", description = "Incorrect request to create user information", content = [Content(mediaType = "application/json", schema = Schema(implementation = ErrorResponse::class))], ), ApiResponse( responseCode = "401", description = "Unauthorized to access this endpoint", content = [Content(mediaType = "application/json", schema = Schema(implementation = ErrorResponse::class))], ), ApiResponse( responseCode = "403", description = "Incorrect permissions to create a user", content = [Content(mediaType = "application/json", schema = Schema(implementation = ErrorResponse::class))], ), ], ) fun createLocalAdminUser( @RequestBody @Valid createLocalAdminUserRequest: CreateLocalAdminUserRequest, ): UserDetail { val user = userService.createLocalAdminUser(createLocalAdminUserRequest) return userService.findByUsername(username = user.username) } @PreAuthorize("hasRole('ROLE_CREATE_USER')") @PostMapping("/admin-account") @ResponseStatus(HttpStatus.CREATED) @Operation( summary = "Create admin user account", description = "Creates admin user account, oracle schema and staff user information. Requires role ROLE_CREATE_USER", security = [SecurityRequirement(name = "CREATE_USER")], requestBody = io.swagger.v3.oas.annotations.parameters.RequestBody( content = [ Content( mediaType = "application/json", schema = Schema(implementation = CreateAdminUserRequest::class), ), ], ), responses = [ ApiResponse( responseCode = "201", description = "Admin user account information returned", ), ApiResponse( responseCode = "400", description = "Incorrect request to create user information", content = [Content(mediaType = "application/json", schema = Schema(implementation = ErrorResponse::class))], ), ApiResponse( responseCode = "401", description = "Unauthorized to access this endpoint", content = [Content(mediaType = "application/json", schema = Schema(implementation = ErrorResponse::class))], ), ApiResponse( responseCode = "403", description = "Incorrect permissions to create a user", content = [Content(mediaType = "application/json", schema = Schema(implementation = ErrorResponse::class))], ), ], ) fun createAdminUser( @RequestBody @Valid createUserRequest: CreateAdminUserRequest, ): UserDetail { val user = userService.createAdminUser(createUserRequest) return userService.findByUsername(username = user.username) } @PreAuthorize("hasRole('ROLE_CREATE_USER')") @PostMapping("/link-general-account/{linkedUsername}") @ResponseStatus(HttpStatus.CREATED) @Operation( summary = "Link a general user account to an existing admin account.", description = "Can only be linked to an admin account. Can only be linked to an account that doesn't already have one general account. Requires role ROLE_CREATE_USER", security = [SecurityRequirement(name = "CREATE_USER")], requestBody = io.swagger.v3.oas.annotations.parameters.RequestBody( content = [ Content( mediaType = "application/json", schema = Schema(implementation = CreateLinkedGeneralUserRequest::class), ), ], ), responses = [ ApiResponse( responseCode = "201", description = "Staff account information returned", ), ApiResponse( responseCode = "400", description = "Incorrect request to link general account", content = [Content(mediaType = "application/json", schema = Schema(implementation = ErrorResponse::class))], ), ApiResponse( responseCode = "401", description = "Unauthorized to access this endpoint", content = [Content(mediaType = "application/json", schema = Schema(implementation = ErrorResponse::class))], ), ApiResponse( responseCode = "403", description = "Incorrect permissions to link a general account", content = [Content(mediaType = "application/json", schema = Schema(implementation = ErrorResponse::class))], ), ], ) fun linkGeneralAccount( @Schema(description = "Attach account to an existing admin user account", example = "testuser2", required = true) @PathVariable @Size(max = 30, min = 1, message = "Username must be between 1 and 30") linkedUsername: String, @RequestBody @Valid linkedGeneralUserRequest: CreateLinkedGeneralUserRequest, ): StaffDetail { val linkedUser = userService.linkGeneralAccount(linkedUsername, linkedGeneralUserRequest) return userService.findByStaffId(linkedUser.staffId) } @PreAuthorize("hasRole('ROLE_CREATE_USER')") @PostMapping("/link-local-admin-account/{linkedUsername}") @ResponseStatus(HttpStatus.CREATED) @Operation( summary = "Link a local admin user account to an existing general account.", description = "Can only be linked to an general account. Can only be linked to an account that doesn't already have one admin account. Requires role ROLE_CREATE_USER", security = [SecurityRequirement(name = "CREATE_USER")], requestBody = io.swagger.v3.oas.annotations.parameters.RequestBody( content = [ Content( mediaType = "application/json", schema = Schema(implementation = CreateLinkedLocalAdminUserRequest::class), ), ], ), responses = [ ApiResponse( responseCode = "201", description = "Staff local admin account information returned", ), ApiResponse( responseCode = "400", description = "Incorrect request to link local admin account", content = [Content(mediaType = "application/json", schema = Schema(implementation = ErrorResponse::class))], ), ApiResponse( responseCode = "401", description = "Unauthorized to access this endpoint", content = [Content(mediaType = "application/json", schema = Schema(implementation = ErrorResponse::class))], ), ApiResponse( responseCode = "403", description = "Incorrect permissions to link a local admin account", content = [Content(mediaType = "application/json", schema = Schema(implementation = ErrorResponse::class))], ), ], ) fun linkLocalAdminAccount( @Schema(description = "Attach account to an existing general user account", example = "testuser2", required = true) @PathVariable @Size(max = 30, min = 1, message = "Username must be between 1 and 30") linkedUsername: String, @RequestBody @Valid linkedLocalAdminUserRequest: CreateLinkedLocalAdminUserRequest, ): StaffDetail { val linkedUser = userService.linkLocalAdminAccount(linkedUsername, linkedLocalAdminUserRequest) return userService.findByStaffId(linkedUser.staffId) } @PreAuthorize("hasRole('ROLE_CREATE_USER')") @PostMapping("/link-admin-account/{linkedUsername}") @ResponseStatus(HttpStatus.CREATED) @Operation( summary = "Link an admin account to an existing general account.", description = "Can only be linked to an general account. Can only be linked to an account that doesn't already have one Admin account. Requires role ROLE_CREATE_USER", security = [SecurityRequirement(name = "CREATE_USER")], requestBody = io.swagger.v3.oas.annotations.parameters.RequestBody( content = [ Content( mediaType = "application/json", schema = Schema(implementation = CreateLinkedAdminUserRequest::class), ), ], ), responses = [ ApiResponse( responseCode = "201", description = "Staff account information returned", ), ApiResponse( responseCode = "400", description = "Incorrect request to link admin account", content = [Content(mediaType = "application/json", schema = Schema(implementation = ErrorResponse::class))], ), ApiResponse( responseCode = "401", description = "Unauthorized to access this endpoint", content = [Content(mediaType = "application/json", schema = Schema(implementation = ErrorResponse::class))], ), ApiResponse( responseCode = "403", description = "Incorrect permissions to link an admin account", content = [Content(mediaType = "application/json", schema = Schema(implementation = ErrorResponse::class))], ), ], ) fun linkAdminAccount( @Schema(description = "Attach account to an existing general account", example = "testuser2", required = true) @PathVariable @Size(max = 30, min = 1, message = "Username must be between 1 and 30") linkedUsername: String, @RequestBody @Valid linkedUserRequest: CreateLinkedAdminUserRequest, ): StaffDetail { val linkedUser = userService.linkAdminAccount(linkedUsername, linkedUserRequest) return userService.findByStaffId(linkedUser.staffId) } }
3
null
0
1
3eb25d393778a24dc4c5800f06a9a6d25d79c1d4
13,593
nomis-user-roles-api
MIT License
app/src/main/java/com/theophiluskibet/koin/playground/presentation/screens/list/CharacterListScreen.kt
kibettheophilus
811,054,900
false
{"Kotlin": 41923}
/* * Copyright 2024 Theophilus Kibet * * 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.theophiluskibet.koin.playground.presentation.screens.list import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.lazy.LazyColumn import androidx.compose.foundation.lazy.items import androidx.compose.material3.CircularProgressIndicator import androidx.compose.material3.Scaffold import androidx.compose.material3.Text import androidx.compose.runtime.Composable import androidx.compose.runtime.collectAsState import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import org.koin.androidx.compose.koinViewModel @Composable fun CharacterListScreen( modifier: Modifier = Modifier, onCharacterClick: (String) -> Unit, viewModel: CharacterListViewModel = koinViewModel(), ) { val uiState = viewModel.uiState.collectAsState().value Scaffold(modifier = Modifier.fillMaxSize()) { innerPadding -> when (uiState) { is UiState.Loading -> CircularProgressIndicator(modifier = Modifier) is UiState.Error -> { Text(text = uiState.message) } is UiState.Success -> { LazyColumn( modifier = Modifier.fillMaxSize(), verticalArrangement = Arrangement.Center, horizontalAlignment = Alignment.CenterHorizontally, ) { items(uiState.data) { character -> Text(text = character.name) } } } } } }
4
Kotlin
0
2
6ee4c0f796c98bdbd3ce4b6009d5c71da9359987
2,180
koin-playground
Apache License 2.0
diktat-rules/src/main/kotlin/com/saveourtool/diktat/ruleset/constants/Chapters.kt
saveourtool
275,879,956
false
null
package org.cqfn.diktat.ruleset.constants import org.cqfn.diktat.common.config.rules.RulesConfig import org.cqfn.diktat.common.config.rules.getCommonConfiguration import org.cqfn.diktat.ruleset.utils.isDigits import org.jetbrains.kotlin.org.jline.utils.Levenshtein /** * This class represents the chapters that are in our code style. * * @property number - number of chapter * @property title name of chapter */ @Suppress("WRONG_DECLARATIONS_ORDER") enum class Chapters(val number: String, val title: String) { DUMMY("0", "Dummy"), NAMING("1", "Naming"), COMMENTS("2", "Comments"), TYPESETTING("3", "General"), VARIABLES("4", "Variables"), FUNCTIONS("5", "Functions"), CLASSES("6", "Classes"), ; } /** * Function checks if warning from enable chapter * * @param configRules list of rules configuration * @return is warning from enable chapter */ fun Warnings.isRuleFromActiveChapter(configRules: List<RulesConfig>): Boolean { val chapterFromRule = getChapterByWarning() val configuration = configRules.getCommonConfiguration() val disabledChapters = configuration.disabledChapters ?.takeIf { it.isNotBlank() } ?.split(",") ?.map { it.trim() } ?.mapNotNull { chap -> if (chap.isDigits()) { Chapters.values().find { chap == it.number } } else { validate(chap) Chapters.values().find { it.title == chap } } } return disabledChapters?.let { return chapterFromRule !in it } ?: true } /** * Function get chapter by warning * * @return chapter to which warning refers */ @Suppress("UnsafeCallOnNullableType") fun Warnings.getChapterByWarning() = Chapters.values().find { it.number == this.ruleId.first().toString() }!! private fun validate(chapter: String) = require(chapter in Chapters.values().map { it.title }) { val closestMatch = Chapters.values().minByOrNull { Levenshtein.distance(it.title, chapter) } "Chapter name <$chapter> in configuration file is invalid, did you mean <$closestMatch>?" }
93
null
39
535
9e73d811d9fd9900af5917ba82ddeed0177ac52e
2,125
diktat
MIT License
app/src/main/java/com/payamgr/qrcodemaker/data/model/event/ContentFormEffect.kt
PayamGerackoohi
737,574,318
false
{"Kotlin": 278463, "C++": 90697, "CMake": 2467, "Shell": 1537}
package com.payamgr.qrcodemaker.data.model.event sealed class ContentFormEffect { object ClosePage : ContentFormEffect() }
0
Kotlin
0
0
8e4e2ff12778c4c52a2476eb588f4f7047d7140a
128
QRCodeMaker
MIT License
sample/src/test/java/com.vicpin.sample.testjvm/ViewHolderLifecycleTests.kt
vicpinm
74,609,838
false
null
package com.vicpin.sample.testjvm import androidx.recyclerview.widget.LinearLayoutManager import androidx.recyclerview.widget.RecyclerView import androidx.test.core.app.launchActivity import androidx.test.ext.junit.runners.AndroidJUnit4 import com.nhaarman.mockitokotlin2.* import com.vicpin.kpresenteradapter.PresenterAdapter import com.vicpin.sample.R import com.vicpin.sample.di.Injector import com.vicpin.sample.model.Country import com.vicpin.sample.model.IRepository import com.vicpin.sample.view.presenter.CountryPresenter import com.vicpin.sample.view.activity.ManualBindingActivity import org.junit.Before import org.junit.Test import org.junit.runner.RunWith @RunWith(AndroidJUnit4::class) class ViewHolderLifecycleTests { private val TEST_PAGE_SIZE = 10 private var testRepository = TestRepository(TEST_PAGE_SIZE) private lateinit var countryPresenter: CountryPresenter @Before fun setUp() { //We will use a spied injector, in order to return a specific presenter instance when requested Injector.set(spy(Injector.get())) Injector.get().setCountryRepository(testRepository) //We sill use a spied country presenter to verify lifecycle method invocations countryPresenter = spy(CountryPresenter()) whenever(Injector.get().getCountryPresenter()).thenReturn(countryPresenter) } @Test fun when_thereIsNoData_then_headerShowsNoItems() { //Given some items val itemsSize = 5 initRepositoryWihtCountries(itemsSize) //When: activity starts launchActivity<ManualBindingActivity>().onActivity { //Then: oncreate and onattached methods are called one time per item verify(countryPresenter, times(itemsSize)).onCreate() verify(countryPresenter, times(itemsSize)).onAttach() } } @Test fun when_scroll_then_onDetachedAndOnDestroyIsCalled() { //Given a large amount of items val itemsSize = 50 initRepositoryWihtCountries(itemsSize) //When: activity starts launchActivity<ManualBindingActivity>().onActivity { //Calculate visible amount of items when activity starts val recycler = it.findViewById<RecyclerView>(R.id.recycler) val lastPosition = (recycler.layoutManager as LinearLayoutManager).findLastVisibleItemPosition() val totalVisibleItems = lastPosition - (recycler.adapter as PresenterAdapter<Country>).getHeadersCount() + 1 //Then: verify that onCreate and onAttached is called for each item verify(countryPresenter, times(totalVisibleItems)).onCreate() verify(countryPresenter, times(totalVisibleItems)).onAttach() //After: scroll to second group of visible items onViewId(R.id.recycler).scrollTo(totalVisibleItems * 2) //Then: verify that onCreate and onAttached is called for each item again verify(countryPresenter, times(totalVisibleItems * 2)).onCreate() verify(countryPresenter, times(totalVisibleItems * 2)).onAttach() //Verify that onDetached is called for no visible items verify(countryPresenter, times(totalVisibleItems)).onDetach() //Verify that onDestroy is called at leas once (we cannot assure how many times is going to be called) verify(countryPresenter, atLeastOnce()).onDestroy() } } fun initRepositoryWihtCountries(size: Int) { testRepository.items = List(size) { Country("Country $it", R.mipmap.ic_launcher) } } } class TestRepository(pageSize: Int): IRepository<Country> { override val PAGE_SIZE = pageSize override var items = listOf<Country>() }
0
Kotlin
1
7
8390626c1eab6082a46626f77b550906a2f98a43
3,757
KPresenterAdapter
Apache License 2.0
Corona-Warn-App/src/main/java/de/rki/coronawarnapp/exception/reporting/ErrorReportReceiver.kt
covid-be-app
281,650,940
false
null
package de.rki.coronawarnapp.exception.reporting import android.app.Activity import android.content.BroadcastReceiver import android.content.Context import android.content.Intent import android.util.Log import de.rki.coronawarnapp.CoronaWarnApplication import de.rki.coronawarnapp.R import de.rki.coronawarnapp.exception.ExceptionCategory import de.rki.coronawarnapp.util.DialogHelper import java.util.Locale class ErrorReportReceiver(private val activity: Activity) : BroadcastReceiver() { companion object { private val TAG: String = ErrorReportReceiver::class.java.simpleName } override fun onReceive(context: Context, intent: Intent) { val category = ExceptionCategory .valueOf(intent.getStringExtra(ReportingConstants.ERROR_REPORT_CATEGORY_EXTRA) ?: "") val errorCode = intent.getIntExtra( ReportingConstants.ERROR_REPORT_CODE_EXTRA, ReportingConstants.ERROR_REPORT_UNKNOWN_ERROR ) val prefix = intent.getStringExtra(ReportingConstants.ERROR_REPORT_PREFIX_EXTRA) val suffix = intent.getStringExtra(ReportingConstants.ERROR_REPORT_SUFFIX_EXTRA) // set the message of the dialog: default is technical var message = intent.getStringExtra(ReportingConstants.ERROR_REPORT_MESSAGE_EXTRA) ?: context.resources.getString(R.string.errors_generic_text_unknown_error_cause) // if we have a res id we set that message if (intent.hasExtra(ReportingConstants.ERROR_REPORT_RES_ID)) { val resId = intent.getIntExtra(ReportingConstants.ERROR_REPORT_RES_ID, 0) message = context.resources.getString(resId) } val stack = intent.getStringExtra(ReportingConstants.ERROR_REPORT_STACK_EXTRA) val title = context.resources.getString(R.string.errors_generic_headline) val confirm = context.resources.getString(R.string.errors_generic_button_positive) val details = context.resources.getString(R.string.errors_generic_button_negative) val detailsTitle = context.resources.getString(R.string.errors_generic_details_headline) val errorTitle = context.resources.getString(R.string.errors_generic_details_headline) .toUpperCase(Locale.ROOT) if (CoronaWarnApplication.isAppInForeground) { DialogHelper.showDialog( DialogHelper.DialogInstance( activity, "$errorTitle: $errorCode\n$title", message, confirm, details, null, {}, { DialogHelper.showDialog( DialogHelper.DialogInstance( activity, title, "$detailsTitle:\n$stack", confirm ) ).run {} } )) } Log.e( TAG, "[$category]${(prefix ?: "")} $message${(suffix ?: "")}" ) } }
5
null
3
55
d556b0b9f29e76295b59be2a1ba89bc4cf6ec33b
3,155
cwa-app-android
Apache License 2.0
src/main/kotlin/de/bybackfish/avomod/util/Transformer.kt
byBackfish
510,866,399
false
{"Kotlin": 65429, "Java": 1232}
package de.bybackfish.avomod.util
0
Kotlin
0
0
d82639e486fc5d892890038f0c41b15a8854ce7b
35
AvoMod-Recode
MIT License
codebase/android/feature/transactions/src/main/java/com/makeappssimple/abhimanyu/financemanager/android/feature/transactions/transactions/screen/TransactionsScreenUIEvent.kt
Abhimanyu14
429,663,688
false
{"Kotlin": 1459939, "Dart": 102426}
package com.makeappssimple.abhimanyu.financemanager.android.feature.transactions.transactions.screen import androidx.compose.runtime.Immutable import com.makeappssimple.abhimanyu.financemanager.android.core.model.feature.Filter import com.makeappssimple.abhimanyu.financemanager.android.core.model.feature.SortOption import com.makeappssimple.abhimanyu.financemanager.android.core.ui.base.ScreenUIEvent @Immutable sealed class TransactionsScreenUIEvent : ScreenUIEvent { data object ClearSelectedTransactions : TransactionsScreenUIEvent() data object NavigateToAddTransactionScreen : TransactionsScreenUIEvent() data object NavigateUp : TransactionsScreenUIEvent() data object SelectAllTransactions : TransactionsScreenUIEvent() data class AddToSelectedTransactions( val transactionId: Int, ) : TransactionsScreenUIEvent() data class NavigateToViewTransactionScreen( val transactionId: Int, ) : TransactionsScreenUIEvent() data class RemoveFromSelectedTransactions( val transactionId: Int, ) : TransactionsScreenUIEvent() data class ToggleTransactionSelection( val transactionId: Int, ) : TransactionsScreenUIEvent() data class UpdateSearchText( val updatedSearchText: String, ) : TransactionsScreenUIEvent() data class UpdateSelectedFilter( val updatedSelectedFilter: Filter, ) : TransactionsScreenUIEvent() data class UpdateSelectedSortOption( val updatedSelectedSortOption: SortOption, ) : TransactionsScreenUIEvent() data class UpdateTransactionForValuesInTransactions( val updatedTransactionForValues: Int, ) : TransactionsScreenUIEvent() }
11
Kotlin
0
1
433728cb7a9003e38ea9f579d561e4e27b47ef76
1,700
finance-manager
Apache License 2.0
app/src/main/java/com/romandevyatov/bestfinance/viewmodels/foreachmodel/IncomeHistoryViewModel.kt
RomanDevyatov
587,557,441
false
null
package com.romandevyatov.bestfinance.viewmodels.foreachmodel import androidx.lifecycle.LiveData import androidx.lifecycle.ViewModel import androidx.lifecycle.viewModelScope import com.romandevyatov.bestfinance.db.entities.IncomeHistory import com.romandevyatov.bestfinance.db.entities.relations.IncomeHistoryWithIncomeSubGroupAndWallet import com.romandevyatov.bestfinance.repositories.IncomeHistoryRepository import dagger.hilt.android.lifecycle.HiltViewModel import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.launch import javax.inject.Inject @HiltViewModel class IncomeHistoryViewModel @Inject constructor( private val incomeHistoryRepository: IncomeHistoryRepository ) : ViewModel() { val incomeHistoryLiveData: LiveData<List<IncomeHistory>> = incomeHistoryRepository.getAllIncomeHistory() fun insertIncomeHistory(incomeHistory: IncomeHistory) = viewModelScope.launch(Dispatchers.IO) { incomeHistoryRepository.insertIncomeHistory(incomeHistory) } fun updateIncomeHistory(incomeHistory: IncomeHistory) = viewModelScope.launch(Dispatchers.IO) { incomeHistoryRepository.updateIncomeHistory(incomeHistory) } fun deleteIncomeHistory(incomeHistory: IncomeHistory) = viewModelScope.launch(Dispatchers.IO) { incomeHistoryRepository.deleteIncomeHistory(incomeHistory) } val allIncomeHistoryWithIncomeGroupAndWalletLiveData: LiveData<List<IncomeHistoryWithIncomeSubGroupAndWallet>> = incomeHistoryRepository.getAllIncomeHistoryWithIncomeGroupAndWallet() }
0
Kotlin
0
1
bacad4ca4c12fdef63d1e1e746439751cb891776
1,533
BestFinance
Apache License 2.0
app/src/main/java/com/skeleton/roomdagger2/data/prefs/PrefsHelper.kt
IQBALAGUNG
142,387,988
false
null
package com.skeleton.roomdagger2.data.prefs /** * Created by <NAME> on 24/07/2018. */ interface PrefsHelper { }
0
Kotlin
0
0
3f741803ffc70eb5979d07966d3258ddc8faa9fe
115
RoomDagger2
MIT License
straight/src/commonMain/kotlin/me/localx/icons/straight/outline/LightCeiling.kt
localhostov
808,861,591
false
{"Kotlin": 79430321, "HTML": 331, "CSS": 102}
package me.localx.icons.straight.outline import androidx.compose.ui.graphics.Color import androidx.compose.ui.graphics.PathFillType.Companion.NonZero import androidx.compose.ui.graphics.SolidColor import androidx.compose.ui.graphics.StrokeCap.Companion.Butt import androidx.compose.ui.graphics.StrokeJoin.Companion.Miter import androidx.compose.ui.graphics.vector.ImageVector import androidx.compose.ui.graphics.vector.ImageVector.Builder import androidx.compose.ui.graphics.vector.path import androidx.compose.ui.unit.dp import me.localx.icons.straight.Icons public val Icons.Outline.LightCeiling: ImageVector get() { if (_lightCeiling != null) { return _lightCeiling!! } _lightCeiling = Builder(name = "LightCeiling", defaultWidth = 24.0.dp, defaultHeight = 24.0.dp, viewportWidth = 24.0f, viewportHeight = 24.0f).apply { path(fill = SolidColor(Color(0xFF000000)), stroke = null, strokeLineWidth = 0.0f, strokeLineCap = Butt, strokeLineJoin = Miter, strokeLineMiter = 4.0f, pathFillType = NonZero) { moveToRelative(24.0f, 18.0f) curveToRelative(0.0f, -6.279f, -4.85f, -11.438f, -11.0f, -11.949f) lineTo(13.0f, 0.0f) horizontalLineToRelative(-2.0f) verticalLineToRelative(6.051f) curveTo(4.85f, 6.562f, 0.0f, 11.721f, 0.0f, 18.0f) verticalLineToRelative(2.024f) horizontalLineToRelative(8.002f) curveToRelative(0.013f, 2.194f, 1.8f, 3.976f, 3.998f, 3.976f) reflectiveCurveToRelative(3.984f, -1.782f, 3.998f, -3.976f) horizontalLineToRelative(8.002f) verticalLineToRelative(-2.024f) close() moveTo(12.0f, 22.0f) curveToRelative(-1.094f, 0.0f, -1.984f, -0.884f, -1.998f, -1.976f) horizontalLineToRelative(3.995f) curveToRelative(-0.013f, 1.092f, -0.903f, 1.976f, -1.998f, 1.976f) close() moveTo(2.0f, 18.024f) verticalLineToRelative(-0.024f) curveToRelative(0.0f, -5.514f, 4.486f, -10.0f, 10.0f, -10.0f) reflectiveCurveToRelative(10.0f, 4.486f, 10.0f, 10.0f) lineToRelative(-20.0f, 0.024f) close() } } .build() return _lightCeiling!! } private var _lightCeiling: ImageVector? = null
1
Kotlin
0
5
cbd8b510fca0e5e40e95498834f23ec73cc8f245
2,517
icons
MIT License
library/src/main/kotlin/com/gabrielfeo/gradle/enterprise/api/extension/BuildsApiExtensions.kt
gabrielfeo
579,131,355
false
null
@file:Suppress("unused") package com.gabrielfeo.gradle.enterprise.api.extension import com.gabrielfeo.gradle.enterprise.api.BuildsApi import com.gabrielfeo.gradle.enterprise.api.internal.API_MAX_BUILDS import com.gabrielfeo.gradle.enterprise.api.internal.operator.pagedUntilLastBuild import com.gabrielfeo.gradle.enterprise.api.internal.operator.withGradleAttributes import com.gabrielfeo.gradle.enterprise.api.model.* import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.DelicateCoroutinesApi import kotlinx.coroutines.GlobalScope import kotlinx.coroutines.flow.* /** * Gets builds on demand from the API, in as many requests as necessary. It allows * for queries of any size, as opposed to [BuildsApi.getBuilds] which is limited by the * API itself to 1000. * * - Will request from the API until results end or an error occurs. * - Use [Sequence.take] and similar functions to stop collecting early. * - A subset of `getBuilds` params are supported */ fun BuildsApi.getBuildsFlow( since: Long = 0, sinceBuild: String? = null, fromInstant: Long? = null, fromBuild: String? = null, buildsPerPage: Int = API_MAX_BUILDS, ): Flow<Build> { val api = this return flow { val firstBuilds = getBuilds( since = since, sinceBuild = sinceBuild, fromInstant = fromInstant, fromBuild = fromBuild, maxBuilds = buildsPerPage, ) val pagedBuilds = firstBuilds.asFlow().pagedUntilLastBuild(api, buildsPerPage) emitAll(pagedBuilds) } } /** * Gets [GradleAttributes] of all builds from a given date. Queries [BuildsApi.getBuilds] * first, since it's the only endpoint providing a timeline of builds, then maps each to * [BuildsApi.getGradleAttributes]. * * Don't expect client-side filtering to be efficient. Will request up to [Int.MAX_VALUE] * builds and their attributes concurrently and eagerly, with a buffer, in coroutines started in * [scope]. For other params, see [getBuildsFlow] and [BuildsApi.getBuilds]. * * @param scope CoroutineScope in which to create coroutines. Defaults to [GlobalScope]. */ @OptIn(DelicateCoroutinesApi::class) fun BuildsApi.getGradleAttributesFlow( since: Long = 0, sinceBuild: String? = null, fromInstant: Long? = null, fromBuild: String? = null, scope: CoroutineScope = GlobalScope, ): Flow<GradleAttributes> = getBuildsFlow( since = since, sinceBuild = sinceBuild, fromInstant = fromInstant, fromBuild = fromBuild ).withGradleAttributes(scope, api = this).map { (_, attrs) -> attrs }
1
null
0
8
3b49efb0c91b2b7572c53239b665821f2fa0d565
2,635
gradle-enterprise-api-kotlin
MIT License
promptfx/src/main/kotlin/tri/promptfx/ui/DocumentListView.kt
aplpolaris
663,584,917
false
{"Kotlin": 952445, "Java": 7792, "CSS": 2840}
/*- * #%L * tri.promptfx:promptfx * %% * Copyright (C) 2023 - 2024 Johns Hopkins University Applied Physics Laboratory * %% * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * #L% */ package tri.promptfx.ui import de.jensd.fx.glyphs.fontawesome.FontAwesomeIcon import javafx.application.HostServices import javafx.collections.ObservableList import javafx.geometry.Pos import javafx.scene.image.ImageView import javafx.scene.layout.Priority import tornadofx.* import tri.ai.text.chunks.BrowsableSource import tri.promptfx.docs.DocumentOpenInViewer import tri.util.ui.DocumentUtils import tri.util.ui.graphic /** * Display a list of documents. * Clicking on the document name will open the document in a viewer. */ class DocumentListView(docs: ObservableList<BrowsableSource>, hostServices: HostServices) : Fragment("Document List") { override val root = listview(docs) { vgrow = Priority.ALWAYS cellFormat { graphic = hyperlink(it.shortNameWithoutExtension, graphic = it.icon()) { val thumb = DocumentUtils.documentThumbnail(it, DOC_THUMBNAIL_SIZE) if (thumb != null) { tooltip { graphic = ImageView(thumb) } } action { DocumentOpenInViewer(it, hostServices).open() } } } } companion object { const val DOC_THUMBNAIL_SIZE = 240 //** Return an icon for the document based on its file extension. */ fun BrowsableSource.icon() = when (path.substringAfterLast('.')) { "pdf" -> FontAwesomeIcon.FILE_PDF_ALT.graphic "doc", "docx" -> FontAwesomeIcon.FILE_WORD_ALT.graphic "csv", "xls", "xlsx" -> FontAwesomeIcon.FILE_EXCEL_ALT.graphic "ppt", "pptx" -> FontAwesomeIcon.FILE_POWERPOINT_ALT.graphic "txt" -> FontAwesomeIcon.FILE_TEXT_ALT.graphic "html", "htm" -> FontAwesomeIcon.GLOBE.graphic else -> { if (path.startsWith("html") || path.startsWith("html")) FontAwesomeIcon.GLOBE.graphic else FontAwesomeIcon.FILE_ALT.graphic } } } }
39
Kotlin
1
16
95b240c7d32f22b9af3833b9ca1d0d9f1fc85357
2,694
promptfx
Apache License 2.0
app/src/main/java/com/babakbelur/studiary/core/data/remote/response/user/DataUserResponse.kt
Babak-Belur
396,693,139
false
null
package com.babakbelur.studiary.core.data.remote.response.user import com.google.gson.annotations.SerializedName data class DataUserResponse( @SerializedName("id_user") val idUser: Int = 0, @SerializedName("name") val name: String? = "", @SerializedName("role") val role: String? = "", @SerializedName("username") val username: String? = "", @SerializedName("password") val password: String? = "" )
0
Kotlin
0
0
cc7d86e6fd132e24478a0abafb86258c7da087eb
444
android-app
Apache License 2.0
platform/platform-api/src/com/intellij/ui/tabs/newImpl/TabsHeightController.kt
mobproinu
196,253,481
true
null
// Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.ui.tabs.impl import com.intellij.openapi.Disposable import com.intellij.openapi.util.Disposer import com.intellij.ui.tabs.TabsUtil import com.intellij.util.ui.JBUI import com.jetbrains.rd.swing.sizeProperty import com.jetbrains.rd.util.lifetime.Lifetime import com.jetbrains.rd.util.lifetime.LifetimeDefinition import com.jetbrains.rd.util.reactive.Property import com.jetbrains.rd.util.reactive.ViewableMap import com.intellij.openapi.rd.createLifetime import com.intellij.openapi.rd.createNestedDisposable import javax.swing.JComponent class TabsHeightController { companion object { private val heightMap = ViewableMap<JComponent, Int>() private val adjectives = ViewableMap<JComponent, (Int) -> Unit>() private var ld = LifetimeDefinition() private val toolWindowHeightProperty = Property(TabsUtil.getTabsHeight(JBUI.CurrentTheme.ToolWindow.tabVerticalPadding())) init { heightMap.advise(ld) { val value = heightMap.maxBy { it.value }?.value value?.let { toolWindowHeightProperty.set(if(it > 0) it else TabsUtil.getTabsHeight(JBUI.CurrentTheme.ToolWindow.tabVerticalPadding())) } } toolWindowHeightProperty.advise(ld) { for (entry in adjectives) { entry.value(it) } } } @JvmStatic fun registerActive(comp: JComponent, parentDisposable: Disposable) { val lifetime = createNestedLifeTime(parentDisposable) lifetime.bracket({ comp.sizeProperty().advise(lifetime) { heightMap[comp] = it.height } if (comp.height > 0) heightMap[comp] = comp.height }, { heightMap.remove(comp) }) } @JvmStatic fun registerAdjective(comp: JComponent, update: (Int) -> Unit, parentDisposable: Disposable) { val lifetime = createNestedLifeTime(parentDisposable) lifetime.bracket({ adjectives[comp] = update update(toolWindowHeightProperty.value) }, { adjectives.remove(comp) }) } private fun createNestedLifeTime(parentDisposable: Disposable): Lifetime { val ds = Disposer.newDisposable() val nestedDisposable = ld.createNestedDisposable() Disposer.register(nestedDisposable, ds) Disposer.register(parentDisposable, nestedDisposable) return ds.createLifetime() } } }
1
null
1
1
c4f0b566e6b2ec410fb3c785e12dab9c6d20ac26
2,686
intellij-community
Apache License 2.0
src/main/kotlin/io/github/serpro69/kfaker/provider/ProgrammingLanguage.kt
jianfang-kso
204,592,729
true
{"Kotlin": 189205, "Groovy": 1142}
package io.github.serpro69.kfaker.provider import io.github.serpro69.kfaker.* import io.github.serpro69.kfaker.dictionary.* /** * [FakeDataProvider] implementation for [CategoryName.PROGRAMMING_LANGUAGE] category. */ class ProgrammingLanguage internal constructor(fakerService: FakerService) : AbstractFakeDataProvider(fakerService) { override val categoryName = CategoryName.PROGRAMMING_LANGUAGE val name = resolve { fakerService.resolve(Faker, it, "name") } val creator = resolve { fakerService.resolve(Faker, it, "creator") } }
0
Kotlin
0
0
36a77fb520f82a1a0b43cf6cd08c54c2c7b9d6d6
548
kotlin-faker
MIT License
packages/nasi-lemak-carrier-services/android/src/main/java/org/nasi/lemak/carrierservices/ESimBridge.kt
diaozheng999
213,815,778
false
{"TypeScript": 204860, "Python": 6815, "Kotlin": 6064, "JavaScript": 3032, "Shell": 81}
package org.nasi.lemak.carrierservices import android.annotation.TargetApi import android.app.PendingIntent import android.content.BroadcastReceiver import android.content.Context import android.content.Intent import android.content.IntentFilter import android.telephony.euicc.DownloadableSubscription import android.telephony.euicc.EuiccManager import com.facebook.react.bridge.Promise import com.facebook.react.bridge.ReactApplicationContext import com.facebook.react.bridge.ReactContextBaseJavaModule import com.facebook.react.bridge.ReactMethod val ACTION_DOWNLOAD_SUBSCRIPTION = "org.nasi.lemak.carrierservices.download_subscription" @TargetApi(28) class ESimBridge constructor( context: ReactApplicationContext ) : ReactContextBaseJavaModule(context) { val manager: EuiccManager = context.getSystemService(EuiccManager::class.java) val executor = MainThreadExecutor() override fun getName() = "NLMESimBridge" @ReactMethod fun deviceSupportsESimInstallation(promise: Promise) = promise.resolve(manager.isEnabled) @ReactMethod fun installESimProfile( @Suppress("unused") __unused_address: String?, @Suppress("unused") __unused_confirmationCode: String?, @Suppress("unused") _unused_eid: String?, @Suppress("unused") __unused_iccid: String?, @Suppress("unused") __unused_matchingId: String?, @Suppress("unused") __unused_oid: String?, profile: String, promise: Promise) { val receiver = object : BroadcastReceiver() { override fun onReceive(context: Context, intent: Intent) { executor.execute { when (resultCode) { EuiccManager.EMBEDDED_SUBSCRIPTION_RESULT_RESOLVABLE_ERROR -> { manager.startResolutionActivity( reactApplicationContext.currentActivity, 0, intent, PendingIntent.getBroadcast( reactApplicationContext.currentActivity, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT )) } EuiccManager.EMBEDDED_SUBSCRIPTION_RESULT_OK -> { promise.resolve(ESimProfileStatus.SUCCESS.value) reactApplicationContext.currentActivity!!.unregisterReceiver(this) } EuiccManager.EMBEDDED_SUBSCRIPTION_RESULT_ERROR -> { promise.resolve(ESimProfileStatus.FAIL.value) reactApplicationContext.currentActivity!!.unregisterReceiver(this) } else -> { promise.resolve(ESimProfileStatus.UNKNOWN.value) reactApplicationContext.currentActivity!!.unregisterReceiver(this) } } } } } val intent = Intent(ACTION_DOWNLOAD_SUBSCRIPTION) executor.execute { reactApplicationContext.currentActivity!!.registerReceiver( receiver, IntentFilter(ACTION_DOWNLOAD_SUBSCRIPTION)) manager.downloadSubscription( DownloadableSubscription.forActivationCode(profile), false, PendingIntent.getBroadcast( reactApplicationContext.currentActivity, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT)) } } }
90
TypeScript
2
3
2dc41f1e58fcf00d1200e94514d4488cd03cf902
3,927
nasi-lemak
MIT License
feature/explore/src/main/java/com/peonlee/explore/ExploreActivity.kt
YAPP-Github
634,125,265
false
null
package com.peonlee.explore import android.content.Context import android.content.Intent import androidx.activity.viewModels import androidx.core.view.isVisible import androidx.core.widget.addTextChangedListener import com.peonlee.core.ui.base.BaseActivity import com.peonlee.core.ui.base.ProductSearchableViewModel import com.peonlee.core.ui.extensions.hideKeyboard import com.peonlee.core.ui.extensions.trim import com.peonlee.explore.databinding.ActivityExploreActivityBinding import com.peonlee.product.ProductFragment import dagger.hilt.android.AndroidEntryPoint @AndroidEntryPoint class ExploreActivity : BaseActivity<ActivityExploreActivityBinding>() { private val exploreViewModel: ProductSearchableViewModel by viewModels { ExploreViewModel.ExploreViewModelFactory() } override fun bindingFactory(): ActivityExploreActivityBinding = ActivityExploreActivityBinding.inflate(layoutInflater) override fun initViews() = with(binding) { println(exploreViewModel) attachProductFragment() etExploreBar.addTextChangedListener { input -> ivTextCleaer.isVisible = input?.isNotEmpty() ?: false } tvExploreCancel.setOnClickListener { finish() } ivTextCleaer.setOnClickListener { etExploreBar.setText("") } ivSearch.setOnClickListener { layoutSearchProduct.isVisible = true (exploreViewModel as? ExploreViewModel)?.setKeyword(etExploreBar.trim()) etExploreBar.hideKeyboard() } } private fun attachProductFragment() { supportFragmentManager.beginTransaction() .replace(R.id.layout_search_product, ProductFragment.getInstance()) .commit() } companion object { fun startActivity(context: Context) { context.startActivity( Intent(context, ExploreActivity::class.java) ) } } }
3
Kotlin
0
7
2b10d9192bc6c72ad6e890ba794a7a62d3e9f633
1,885
pyeonlee-aos
Apache License 2.0
src/test/kotlin/uk/gov/justice/digital/hmpps/approvedpremisesapi/util/JwtAuthHelper.kt
ministryofjustice
515,276,548
false
null
package uk.gov.justice.digital.hmpps.approvedpremisesapi.util import io.jsonwebtoken.Jwts import io.jsonwebtoken.SignatureAlgorithm import org.springframework.context.annotation.Bean import org.springframework.context.annotation.Primary import org.springframework.security.oauth2.jwt.JwtDecoder import org.springframework.security.oauth2.jwt.NimbusJwtDecoder import org.springframework.stereotype.Component import java.security.KeyPair import java.security.KeyPairGenerator import java.security.interfaces.RSAPublicKey import java.time.Duration import java.util.Date import java.util.UUID @Component class JwtAuthHelper { private val keyPair: KeyPair init { val gen = KeyPairGenerator.getInstance("RSA") gen.initialize(2048) keyPair = gen.generateKeyPair() } @Bean @Primary fun jwtDecoder(): JwtDecoder = NimbusJwtDecoder.withPublicKey(keyPair.public as RSAPublicKey).build() internal fun createValidClientCredentialsJwt() = createClientCredentialsJwt( expiryTime = Duration.ofMinutes(2), roles = listOf("ROLE_COMMUNITY"), ) internal fun createExpiredClientCredentialsJwt() = createClientCredentialsJwt( expiryTime = Duration.ofMinutes(-2), roles = listOf("ROLE_COMMUNITY"), ) internal fun createClientCredentialsJwt( username: String? = null, scope: List<String>? = listOf(), roles: List<String>? = listOf(), authSource: String = if (username == null) "none" else "delius", expiryTime: Duration = Duration.ofHours(1), jwtId: String = UUID.randomUUID().toString(), ): String = mutableMapOf<String, Any>() .also { it["user_name"] = username ?: "integration-test-client-id" } .also { it["client_id"] = "integration-test-client-id" } .also { it["grant_type"] = "client_credentials" } .also { it["auth_source"] = authSource } .also { roles?.let { roles -> it["authorities"] = roles } } .also { scope?.let { scope -> it["scope"] = scope } } .let { Jwts.builder() .setId(jwtId) .setSubject(username ?: "integration-test-client-id") .addClaims(it.toMap()) .setExpiration(Date(System.currentTimeMillis() + expiryTime.toMillis())) .signWith(SignatureAlgorithm.RS256, keyPair.private) .compact() } internal fun createValidNomisAuthorisationCodeJwt(username: String = "username") = createAuthorizationCodeJwt( subject = username, authSource = "nomis", roles = listOf("ROLE_PRISON"), ) internal fun createValidAuthorizationCodeJwt(username: String = "username") = createAuthorizationCodeJwt( subject = username, authSource = "delius", roles = listOf("ROLE_PROBATION"), ) internal fun createAuthorizationCodeJwt( subject: String, scope: List<String>? = listOf(), roles: List<String>? = listOf(), authSource: String = "delius", expiryTime: Duration = Duration.ofHours(1), jwtId: String = UUID.randomUUID().toString(), ): String = mutableMapOf<String, Any>() .also { it["auth_source"] = authSource } .also { it["user_id"] = UUID.randomUUID().toString() } .also { roles?.let { roles -> it["authorities"] = roles } } .also { scope?.let { scope -> it["scope"] = scope } } .let { Jwts.builder() .setId(jwtId) .setSubject(subject) .addClaims(it.toMap()) .setExpiration(Date(System.currentTimeMillis() + expiryTime.toMillis())) .signWith(SignatureAlgorithm.RS256, keyPair.private) .compact() } }
6
null
2
5
b1468c08a6153621abff4deb0df1988d446c56ce
3,561
hmpps-approved-premises-api
MIT License
src/main/kotlin/endpoints/pages/Pages.kt
basic-mission
480,688,737
false
{"Kotlin": 97001}
package endpoints.pages import endpoints.pages.dto.request.PageRetrieveRequest import endpoints.pages.dto.response.PageResponse import io.ktor.client.* import io.ktor.client.call.* import io.ktor.client.request.* import mu.KotlinLogging open class Pages( private val ktorClient: HttpClient, ) { private val logger = KotlinLogging.logger {} suspend fun retrieve(request: PageRetrieveRequest): PageResponse? = try { ktorClient.get("/v1/pages/${request.pageId}").body<PageResponse>() } catch (error: Exception) { logger.error { "[Pages.retrieve] ${error.message}" } null } }
0
Kotlin
0
0
265a648d8e56fe2d2c4c2f6adee182d8a9b25112
586
notion-sdk-jvm
MIT License
src/main/kotlin/endpoints/pages/Pages.kt
basic-mission
480,688,737
false
{"Kotlin": 97001}
package endpoints.pages import endpoints.pages.dto.request.PageRetrieveRequest import endpoints.pages.dto.response.PageResponse import io.ktor.client.* import io.ktor.client.call.* import io.ktor.client.request.* import mu.KotlinLogging open class Pages( private val ktorClient: HttpClient, ) { private val logger = KotlinLogging.logger {} suspend fun retrieve(request: PageRetrieveRequest): PageResponse? = try { ktorClient.get("/v1/pages/${request.pageId}").body<PageResponse>() } catch (error: Exception) { logger.error { "[Pages.retrieve] ${error.message}" } null } }
0
Kotlin
0
0
265a648d8e56fe2d2c4c2f6adee182d8a9b25112
586
notion-sdk-jvm
MIT License
app/src/main/java/jp/co/soramitsu/app/di/deps/ComponentDependenciesModule.kt
ModeNode
300,518,840
true
{"Kotlin": 57393}
package jp.co.soramitsu.app.di.deps import dagger.Binds import dagger.Module import dagger.multibindings.IntoMap import jp.co.soramitsu.app.di.app.AppComponent import jp.co.soramitsu.app.di.main.MainDependencies @Module interface ComponentDependenciesModule { @Binds @IntoMap @ComponentDependenciesKey(MainDependencies::class) fun provideMainDependencies(component: AppComponent): ComponentDependencies }
0
null
0
0
15d40658cc79c518e038f40531f56917cd9233e7
423
fearless-Android
Apache License 2.0
solana-kotlin/src/commonTest/kotlin/net/avianlabs/solana/domain/program/AssociatedTokenProgramTest.kt
avianlabs
653,085,616
false
{"Kotlin": 91997}
package net.avianlabs.solana.domain.program import net.avianlabs.solana.domain.randomKey import net.avianlabs.solana.tweetnacl.ed25519.PublicKey import kotlin.test.Test import kotlin.test.assertEquals class AssociatedTokenProgramTest { @Test fun testFindProgramAddress() { for (i in 0..1000) { val programId = randomKey().publicKey println("programId: $programId") val seeds = listOf( "Lil'".encodeToByteArray(), "Bits".encodeToByteArray(), ) val address = Program.findProgramAddress( seeds = seeds, programId = programId, ) println("address: $address") val created = Program.createProgramAddress( seeds = seeds + byteArrayOf(address.nonce.toByte()), programId = programId, ) println("created: $created") assertEquals(address.address, created) } } @Test fun testKnownAddress() { val knownGoodPairs = listOf( "<KEY>" to "<KEY>", "<KEY>" to "<KEY>", ) val mint = PublicKey.fromBase58("<KEY>") for ((wallet, expectedAssociated) in knownGoodPairs) { val wallet = PublicKey.fromBase58(wallet) val associated = wallet.associatedTokenAddress(mint) println(associated) val expectedAssociated = PublicKey.fromBase58(expectedAssociated) assertEquals(expectedAssociated, associated.address) } } }
3
Kotlin
0
2
01bbc31b30b5484d23512ed8aeb3451b25bdf63d
1,394
solana-kotlin
MIT License
src/main/kotlin/io/github/dockyardmc/events/PlayerSprintToggleEvent.kt
DockyardMC
650,731,309
false
{"Kotlin": 1019371}
package io.github.dockyardmc.events import io.github.dockyardmc.annotations.EventDocumentation import io.github.dockyardmc.player.Player @EventDocumentation("when player changes sprinting state", false) class PlayerSprintToggleEvent(val player: Player, val sprinting: Boolean): Event
6
Kotlin
7
55
9a0eb8f3184123b79b835356ddde526d9eb6df65
285
Dockyard
MIT License
app/src/main/java/com/mozhimen/taskk/provider/test/MainActivity.kt
mozhimen
737,202,327
false
{"Kotlin": 348381, "Java": 6683}
package com.mozhimen.taskk.provider.test import android.annotation.SuppressLint import android.os.Bundle import com.mozhimen.basick.elemk.androidx.appcompat.bases.viewbinding.BaseActivityVB import com.mozhimen.basick.elemk.commons.I_Listener import com.mozhimen.basick.lintk.optins.OApiInit_InApplication import com.mozhimen.basick.lintk.optins.permission.OPermission_INTERNET import com.mozhimen.basick.lintk.optins.permission.OPermission_MANAGE_EXTERNAL_STORAGE import com.mozhimen.basick.lintk.optins.permission.OPermission_READ_EXTERNAL_STORAGE import com.mozhimen.basick.lintk.optins.permission.OPermission_WRITE_EXTERNAL_STORAGE import com.mozhimen.basick.utilk.android.util.UtilKLogWrapper import com.mozhimen.manifestk.xxpermissions.XXPermissionsCheckUtil import com.mozhimen.manifestk.xxpermissions.XXPermissionsRequestUtil import com.mozhimen.taskk.provider.apk.utils.AppTaskUtil import com.mozhimen.taskk.provider.basic.cons.CState import com.mozhimen.taskk.provider.basic.cons.STaskFinishType import com.mozhimen.taskk.provider.basic.db.AppTask import com.mozhimen.taskk.provider.basic.db.AppTaskDaoManager import com.mozhimen.taskk.provider.basic.impls.TaskException import com.mozhimen.taskk.provider.basic.interfaces.ITasks import com.mozhimen.taskk.provider.test.databinding.ActivityMain2Binding /** * An example full-screen activity that shows and hides the system UI (i.e. * status bar and navigation/system bar) with user interaction. */ class MainActivity : BaseActivityVB<ActivityMain2Binding>(), ITasks { var appTask = AppTask( "0", CState.STATE_TASK_CREATE, "https://cf-lele-res.lelejoy.com/lelejoy.apk", true, "", true, "", R.drawable.ic_launcher_foreground, "lelejoy.apk", "com.ty.lelejoy", 38, "1.8.8" ) @OptIn(OPermission_INTERNET::class, OApiInit_InApplication::class) override fun initView(savedInstanceState: Bundle?) { appTask = AppTaskUtil.generateAppTask_ofDb_installed_version(MainTaskManager, appTask) UtilKLogWrapper.d(TAG, "initView: get_ofTaskId ${AppTaskDaoManager.get_ofTaskId(appTask.taskId)}") UtilKLogWrapper.d(TAG, "initView: get_ofApkPackageName_ApkVersionCode ${AppTaskDaoManager.get_ofApkPackageName_ApkVersionCode(appTask.apkPackageName, appTask.apkVersionCode)}") UtilKLogWrapper.d(TAG, "initView: get_ofTaskId_ApkPackageName_ApkVersionCode ${AppTaskDaoManager.get_ofTaskId_ApkPackageName_ApkVersionCode(appTask.taskId, appTask.apkPackageName, appTask.apkVersionCode)}") UtilKLogWrapper.d(TAG, "initView: gets_ofApkPackageName ${AppTaskDaoManager.gets_ofApkPackageName(appTask.apkPackageName)}") UtilKLogWrapper.d(TAG, "initView: gets_ofApkPackageName_satisfyApkVersionCode ${AppTaskDaoManager.gets_ofApkPackageName_satisfyApkVersionCode(appTask.apkPackageName, appTask.apkVersionCode)}") vb.mainTxt.text = appTask.getStrTaskState() vb.mainBtn.setOnClickListener { requestPermissionStorage { if (appTask.isTaskProcess() && appTask.isAnyTasking()) { MainTaskManager.taskPause(appTask) } else if (!appTask.isTaskProcess() || appTask.isAnyTaskPause() || appTask.isAnyTaskSuccess()) { MainTaskManager.taskStart(appTask) } } } vb.mainBtn.setOnLongClickListener { requestPermissionStorage { MainTaskManager.taskCancel(appTask) } true } MainTaskManager.registerTaskListener(this) } @OptIn(OPermission_READ_EXTERNAL_STORAGE::class, OPermission_WRITE_EXTERNAL_STORAGE::class, OPermission_MANAGE_EXTERNAL_STORAGE::class) @SuppressLint("MissingPermission") private fun requestPermissionStorage(block: I_Listener) { if (XXPermissionsCheckUtil.hasReadWritePermission(this)) { block.invoke() } else { XXPermissionsRequestUtil.requestReadWritePermission(this, onGranted = { block.invoke() }, onDenied = { }) } } override fun onDestroy() { MainTaskManager.unregisterTaskListener(this) super.onDestroy() } override fun onTaskDownloading(appTask: AppTask, progress: Int, currentIndex: Long, totalIndex: Long, offsetIndexPerSeconds: Long) { vb.mainTxt.text = appTask.getStrTaskState() this.appTask = appTask } override fun onTaskFinish(appTask: AppTask, finishType: STaskFinishType) { vb.mainTxt.text = appTask.getStrTaskState() this.appTask = appTask } override fun onTaskUnavailable(appTask: AppTask) { vb.mainTxt.text = appTask.getStrTaskState() this.appTask = appTask } override fun onTaskInstallSuccess(appTask: AppTask) { vb.mainTxt.text = appTask.getStrTaskState() this.appTask = appTask } override fun onTaskDownloadCancel(appTask: AppTask) { vb.mainTxt.text = appTask.getStrTaskState() this.appTask = appTask } override fun onTaskDownloadPause(appTask: AppTask) { vb.mainTxt.text = appTask.getStrTaskState() this.appTask = appTask } override fun onTaskDownloadSuccess(appTask: AppTask) { vb.mainTxt.text = appTask.getStrTaskState() this.appTask = appTask } override fun onTaskInstallCancel(appTask: AppTask) { vb.mainTxt.text = appTask.getStrTaskState() this.appTask = appTask } override fun onTaskInstallPause(appTask: AppTask) { vb.mainTxt.text = appTask.getStrTaskState() this.appTask = appTask } override fun onTaskOpenCancel(appTask: AppTask) { vb.mainTxt.text = appTask.getStrTaskState() this.appTask = appTask } override fun onTaskOpenPause(appTask: AppTask) { vb.mainTxt.text = appTask.getStrTaskState() this.appTask = appTask } override fun onTaskOpenSuccess(appTask: AppTask) { vb.mainTxt.text = appTask.getStrTaskState() this.appTask = appTask } override fun onTaskUninstallCancel(appTask: AppTask) { vb.mainTxt.text = appTask.getStrTaskState() this.appTask = appTask } override fun onTaskUninstallPause(appTask: AppTask) { vb.mainTxt.text = appTask.getStrTaskState() this.appTask = appTask } override fun onTaskUninstallSuccess(appTask: AppTask) { vb.mainTxt.text = appTask.getStrTaskState() this.appTask = appTask } override fun onTaskUnzipCancel(appTask: AppTask) { vb.mainTxt.text = appTask.getStrTaskState() this.appTask = appTask } override fun onTaskUnzipPause(appTask: AppTask) { vb.mainTxt.text = appTask.getStrTaskState() this.appTask = appTask } override fun onTaskUnzipSuccess(appTask: AppTask) { vb.mainTxt.text = appTask.getStrTaskState() this.appTask = appTask } override fun onTaskVerifyCancel(appTask: AppTask) { vb.mainTxt.text = appTask.getStrTaskState() this.appTask = appTask } override fun onTaskVerifyPause(appTask: AppTask) { vb.mainTxt.text = appTask.getStrTaskState() this.appTask = appTask } override fun onTaskVerifySuccess(appTask: AppTask) { vb.mainTxt.text = appTask.getStrTaskState() this.appTask = appTask } override fun onTaskDownloadFail(appTask: AppTask, exception: TaskException) { vb.mainTxt.text = appTask.getStrTaskState() this.appTask = appTask } override fun onTaskCreate(appTask: AppTask, isUpdate: Boolean) { vb.mainTxt.text = appTask.getStrTaskState() this.appTask = appTask } override fun onTaskInstallFail(appTask: AppTask, exception: TaskException) { vb.mainTxt.text = appTask.getStrTaskState() this.appTask = appTask } override fun onTaskOpenFail(appTask: AppTask, exception: TaskException) { vb.mainTxt.text = appTask.getStrTaskState() this.appTask = appTask } override fun onTaskUninstallFail(appTask: AppTask, exception: TaskException) { vb.mainTxt.text = appTask.getStrTaskState() this.appTask = appTask } override fun onTaskUnzipFail(appTask: AppTask, exception: TaskException) { vb.mainTxt.text = appTask.getStrTaskState() this.appTask = appTask } override fun onTaskVerifyFail(appTask: AppTask, exception: TaskException) { vb.mainTxt.text = appTask.getStrTaskState() this.appTask = appTask } override fun onTaskInstalling(appTask: AppTask, progress: Int, currentIndex: Long, totalIndex: Long, offsetIndexPerSeconds: Long) { vb.mainTxt.text = appTask.getStrTaskState() this.appTask = appTask } override fun onTaskOpening(appTask: AppTask, progress: Int, currentIndex: Long, totalIndex: Long, offsetIndexPerSeconds: Long) { vb.mainTxt.text = appTask.getStrTaskState() this.appTask = appTask } override fun onTaskUninstalling(appTask: AppTask, progress: Int, currentIndex: Long, totalIndex: Long, offsetIndexPerSeconds: Long) { vb.mainTxt.text = appTask.getStrTaskState() this.appTask = appTask } override fun onTaskUnziping(appTask: AppTask, progress: Int, currentIndex: Long, totalIndex: Long, offsetIndexPerSeconds: Long) { vb.mainTxt.text = appTask.getStrTaskState() this.appTask = appTask } override fun onTaskVerifying(appTask: AppTask, progress: Int, currentIndex: Long, totalIndex: Long, offsetIndexPerSeconds: Long) { vb.mainTxt.text = appTask.getStrTaskState() this.appTask = appTask } // private lateinit var binding: ActivityMainBinding // private lateinit var fullscreenContent: TextView // private lateinit var fullscreenContentControls: LinearLayout // private val hideHandler = Handler(Looper.myLooper()!!) // // private val hidePart2Runnable = Runnable { // // Delayed removal of status and navigation bar // if (Build.VERSION.SDK_INT >= 30) { // fullscreenContent.windowInsetsController?.hide(WindowInsets.Type.statusBars() or WindowInsets.Type.navigationBars()) // } else { // // Note that some of these constants are new as of API 16 (Jelly Bean) // // and API 19 (KitKat). It is safe to use them, as they are inlined // // at compile-time and do nothing on earlier devices. // fullscreenContent.systemUiVisibility = // View.SYSTEM_UI_FLAG_LOW_PROFILE or // View.SYSTEM_UI_FLAG_FULLSCREEN or // View.SYSTEM_UI_FLAG_LAYOUT_STABLE or // View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY or // View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION or // View.SYSTEM_UI_FLAG_HIDE_NAVIGATION // } // } // private val showPart2Runnable = Runnable { // // Delayed display of UI elements // supportActionBar?.show() // fullscreenContentControls.visibility = View.VISIBLE // } // private var isFullscreen: Boolean = false // // private val hideRunnable = Runnable { hide() } // // /** // * Touch listener to use for in-layout UI controls to delay hiding the // * system UI. This is to prevent the jarring behavior of controls going away // * while interacting with activity UI. // */ // private val delayHideTouchListener = View.OnTouchListener { view, motionEvent -> // when (motionEvent.action) { // MotionEvent.ACTION_DOWN -> if (AUTO_HIDE) { // delayedHide(AUTO_HIDE_DELAY_MILLIS) // } // // MotionEvent.ACTION_UP -> view.performClick() // else -> { // } // } // false // } // // @SuppressLint("ClickableViewAccessibility") // override fun onCreate(savedInstanceState: Bundle?) { // super.onCreate(savedInstanceState) // // binding = ActivityMainBinding.inflate(layoutInflater) // setContentView(binding.root) // // supportActionBar?.setDisplayHomeAsUpEnabled(true) // // isFullscreen = true // // // Set up the user interaction to manually show or hide the system UI. // fullscreenContent = binding.fullscreenContent // fullscreenContent.setOnClickListener { toggle() } // // fullscreenContentControls = binding.fullscreenContentControls // // // Upon interacting with UI controls, delay any scheduled hide() // // operations to prevent the jarring behavior of controls going away // // while interacting with the UI. // binding.dummyButton.setOnTouchListener(delayHideTouchListener) // } // // override fun onPostCreate(savedInstanceState: Bundle?) { // super.onPostCreate(savedInstanceState) // // // Trigger the initial hide() shortly after the activity has been // // created, to briefly hint to the user that UI controls // // are available. // delayedHide(100) // } // // private fun toggle() { // if (isFullscreen) { // hide() // } else { // show() // } // } // // private fun hide() { // // Hide UI first // supportActionBar?.hide() // fullscreenContentControls.visibility = View.GONE // isFullscreen = false // // // Schedule a runnable to remove the status and navigation bar after a delay // hideHandler.removeCallbacks(showPart2Runnable) // hideHandler.postDelayed(hidePart2Runnable, UI_ANIMATION_DELAY.toLong()) // } // // private fun show() { // // Show the system bar // if (Build.VERSION.SDK_INT >= 30) { // fullscreenContent.windowInsetsController?.show(WindowInsets.Type.statusBars() or WindowInsets.Type.navigationBars()) // } else { // fullscreenContent.systemUiVisibility = // View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN or // View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION // } // isFullscreen = true // // // Schedule a runnable to display UI elements after a delay // hideHandler.removeCallbacks(hidePart2Runnable) // hideHandler.postDelayed(showPart2Runnable, UI_ANIMATION_DELAY.toLong()) // } // // /** // * Schedules a call to hide() in [delayMillis], canceling any // * previously scheduled calls. // */ // private fun delayedHide(delayMillis: Int) { // hideHandler.removeCallbacks(hideRunnable) // hideHandler.postDelayed(hideRunnable, delayMillis.toLong()) // } // // companion object { // /** // * Whether or not the system UI should be auto-hidden after // * [AUTO_HIDE_DELAY_MILLIS] milliseconds. // */ // private const val AUTO_HIDE = true // // /** // * If [AUTO_HIDE] is set, the number of milliseconds to wait after // * user interaction before hiding the system UI. // */ // private const val AUTO_HIDE_DELAY_MILLIS = 3000 // // /** // * Some older devices needs a small delay between UI widget updates // * and a change of the status and navigation bar. // */ // private const val UI_ANIMATION_DELAY = 300 // } }
0
Kotlin
0
3
b67256826bd4e4aeefccf495b23d3ba7b1497a1a
15,410
ATaskKit_Provider
Apache License 2.0
xposed/src/main/java/moe/fuqiuluo/xposed/hooks/blindhook/BlindHookLocation.kt
fuqiuluo
870,496,630
false
{"Kotlin": 280032, "AIDL": 21153, "Java": 3777}
package moe.fuqiuluo.xposed.hooks.blindhook import android.location.Location import de.robv.android.xposed.XposedBridge import moe.fuqiuluo.xposed.BaseLocationHook import moe.fuqiuluo.xposed.utils.FakeLoc import moe.fuqiuluo.xposed.utils.Logger object BlindHookLocation: BaseLocationHook() { operator fun invoke(clazz: Class<*>): Int { return BlindHook(clazz) { method, location: Location? -> if (location == null || !FakeLoc.enable) return@BlindHook location val newLoc = injectLocation(location) if (FakeLoc.enableDebugLog) { Logger.debug("${method.name} injected: $newLoc") } newLoc } } }
0
Kotlin
1
8
ded8017653fb6535cc71e421175d22867d2f12a2
696
Portal
Apache License 2.0
annotation-processor/test-cases/1/input/json/decoding/AutomaticSecondaryConstructorPrimaryInaccessible.kt
fluidsonic
105,949,984
false
null
package json.decoding import io.fluidsonic.json.* @Json( decoding = Json.Decoding.automatic ) class AutomaticSecondaryConstructorPrimaryExcluded @Json.Excluded constructor( val value: String ) { constructor(value: Int) : this(value.toString()) }
9
Kotlin
6
29
f71b7aa99df3cbb5dba194b8ee071490150b2277
253
fluid-json
Apache License 2.0
modules/bridge/src/main/kotlin/ru/astrainteractive/discordbot/module/bridge/WebSocketClient.kt
Astra-Interactive
584,452,095
false
{"Kotlin": 44477}
package ru.astrainteractive.discordbot.module.bridge import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.cancel import kotlinx.coroutines.delay import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.MutableSharedFlow import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.asSharedFlow import kotlinx.coroutines.flow.filter import kotlinx.coroutines.flow.update import kotlinx.coroutines.launch import kotlinx.coroutines.sync.Mutex import kotlinx.coroutines.sync.withLock import kotlinx.serialization.decodeFromString import kotlinx.serialization.encodeToString import okhttp3.OkHttpClient import okhttp3.Request import okhttp3.Response import okhttp3.WebSocket import okhttp3.WebSocketListener import okio.ByteString import ru.astrainteractive.astralibs.async.CoroutineFeature import ru.astrainteractive.astralibs.logging.JUtiltLogger import ru.astrainteractive.astralibs.logging.Logger import ru.astrainteractive.discordbot.module.bridge.model.AtomicList import ru.astrainteractive.discordbot.module.bridge.model.MessageData import ru.astrainteractive.discordbot.module.bridge.model.SocketMessage import ru.astrainteractive.discordbot.module.bridge.model.SocketMessageFormat import ru.astrainteractive.discordbot.module.bridge.model.send import java.util.concurrent.atomic.AtomicLong import kotlin.time.Duration.Companion.seconds import kotlin.time.toJavaDuration @Suppress("TooManyFunctions") internal class WebSocketClient( private val host: String, private val port: Int ) : WebSocketListener(), Logger by JUtiltLogger("WebSocketClient") { private val client: OkHttpClient get() = OkHttpClient.Builder() .readTimeout(RECONNECT_DELAY.div(2).toJavaDuration()) .build() private val request: Request get() = Request.Builder() .url("ws://$host:$port") .build() private val scope = CoroutineFeature.Default(Dispatchers.IO) private val mutex = Mutex() private val webSocketFlow: MutableStateFlow<WebSocket?> = MutableStateFlow(null) private val pendingMessages = AtomicList<SocketMessage>() private val counter = AtomicLong(0) private val _messageFlow = MutableSharedFlow<SocketMessage>() val messageFlow = _messageFlow.asSharedFlow() fun tryOpenConnection() = scope.launch { info { "#openConnection" } if (webSocketFlow.value != null) return@launch mutex.withLock { kotlin.runCatching { client.newWebSocket(request, this@WebSocketClient) } .onFailure { error { "#openConnection ${it.message} ${it.cause?.message}" } } .getOrNull() } } private suspend fun send( message: SocketMessage, ): Flow<SocketMessage> { // pendingMessages.add(message) val socket = webSocketFlow.value val encoded = SocketMessageFormat.encodeToString(message) socket?.send(encoded) return messageFlow.filter { it.id == message.id } } suspend fun send(data: MessageData): Flow<SocketMessage> { val message = SocketMessage.Data( id = counter.incrementAndGet(), data = data ) return send(message) } suspend fun ping() = send(SocketMessage.Ping(counter.incrementAndGet())) override fun onOpen(webSocket: WebSocket, response: Response) { info { "#onOpen: $webSocket" } webSocketFlow.update { webSocket } pendingMessages .toList() .forEach { webSocket.send(it) } } override fun onMessage(webSocket: WebSocket, text: String) { scope.launch { info { "#onMessage: $webSocket $text" } val decodedMessage = kotlin.runCatching { SocketMessageFormat.decodeFromString<SocketMessage>(text) }.getOrNull() ?: kotlin.runCatching { SocketMessageFormat.decodeFromString<SocketMessage.Data>(text) }.getOrThrow() val removed = pendingMessages.removeWhere { listMessage -> listMessage.id == decodedMessage.id } if (removed != null) counter.decrementAndGet() _messageFlow.emit(decodedMessage) } } override fun onMessage(webSocket: WebSocket, bytes: ByteString) { info { "#onMessage: $webSocket ${bytes.hex()} but not supported" } } private suspend fun reconnectIfNeed(code: Int?) { if (code != EXIT_CODE) { scope.launch { delay(RECONNECT_DELAY) tryOpenConnection() } } } override fun onClosing(webSocket: WebSocket, code: Int, reason: String) { info { "#onClosing: $webSocket $code $reason" } scope.launch { mutex.withLock { webSocket.cancel() webSocketFlow.update { null } } reconnectIfNeed(code) } } override fun onFailure(webSocket: WebSocket, t: Throwable, response: Response?) { info { "#onFailure: $webSocket ${t.message} ${t.cause?.message}" } scope.launch { mutex.withLock { webSocket.cancel() webSocketFlow.update { null } } reconnectIfNeed(response?.code) } } suspend fun close() { info { "#close" } mutex.withLock { webSocketFlow.value?.close(EXIT_CODE, null) webSocketFlow.value?.cancel() client.dispatcher.cancelAll() client.dispatcher.executorService.shutdown() webSocketFlow.update { null } scope.cancel() } } companion object { private const val EXIT_CODE = -222 private val RECONNECT_DELAY = 5.seconds } }
2
Kotlin
0
0
8ebededeb5876e7275850548e921aa464abc23b0
5,775
TelegramBridge
MIT License
module-about/src/main/java/com/orange/ods/module/about/domain/OdsAboutDomainModule.kt
Orange-OpenSource
440,548,737
false
{"Kotlin": 1041275, "HTML": 26065, "CSS": 14905, "Shell": 587, "JavaScript": 197}
/* * Software Name: Orange Design System * SPDX-FileCopyrightText: Copyright (c) Orange SA * SPDX-License-Identifier: MIT * * This software is distributed under the MIT licence, * the text of which is available at https://opensource.org/license/MIT/ * or see the "LICENSE" file for more details. * * Software description: Android library of reusable graphical components */ package com.orange.ods.module.about.domain import com.orange.ods.module.about.domain.appnews.AppNewsRepository import com.orange.ods.module.about.domain.appnews.AppNewsService import com.orange.ods.module.about.domain.appnews.AppNewsServiceImpl import dagger.Module import dagger.Provides import dagger.hilt.InstallIn import dagger.hilt.components.SingletonComponent import javax.inject.Singleton @Module @InstallIn(SingletonComponent::class) internal object OdsAboutDomainModule { @Singleton @Provides fun provideAppNewsService(appNewsRepository: AppNewsRepository): AppNewsService = AppNewsServiceImpl(appNewsRepository) }
77
Kotlin
9
17
a0f69bea2bc10e8af4a1e50dcf34cff74adc4ff3
1,025
ods-android
MIT License
app/src/main/java/com/admin/ozieats_app/ui/home/cart/CartItemAdapter.kt
chetan532
602,176,592
false
{"Kotlin": 547623, "Java": 49451}
package com.admin.ozieats_app.ui.home.cart import android.app.Activity import android.content.Context import android.view.LayoutInflater import android.view.ViewGroup import android.view.WindowManager import android.widget.ImageView import android.widget.TextView import androidx.databinding.DataBindingUtil import androidx.recyclerview.widget.RecyclerView import com.admin.ozieats_app.R import com.admin.ozieats_app.data.CartRepository import com.admin.ozieats_app.data.LocationRepository import com.admin.ozieats_app.databinding.CartItemLayoutBinding import com.admin.ozieats_app.model.CartButtons import com.admin.ozieats_app.model.CartItemModel import com.admin.ozieats_app.model.CartModel import com.admin.ozieats_app.utils.* import com.bumptech.glide.Glide class CartItemAdapter( private var context: Context, private var cartItems: ArrayList<CartItemModel>, private var cartModel: CartModel, private var cartViewModel: CartViewModel, private var onAddTotal: CartRepository.OnTotalPriceCount, private var onTotalCount: LocationRepository.CartItemTotalGet ) : RecyclerView.Adapter<CartItemAdapter.CartItemViewHolder>() { private var layoutInflater: LayoutInflater? = null //var cartItemTotal:Int=0 override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): CartItemViewHolder { if (layoutInflater == null) { layoutInflater = LayoutInflater.from(parent.context) } val binding: CartItemLayoutBinding = DataBindingUtil.inflate( LayoutInflater.from(parent.context), R.layout.cart_item_layout, parent, false ) binding.cartItemListener = cartViewModel return CartItemViewHolder(context, binding) } override fun getItemCount(): Int { return cartItems.size } override fun onBindViewHolder(holder: CartItemViewHolder, position: Int) { holder.itemviewCartItems.cartItemModel = cartItems[position] holder.itemviewCartItems.cartModel = cartModel cartModel.cartItems = cartItems cartItems[position].amount = (cartItems[position].itemQuantity * cartItems[position].itemPrice) cartModel.totalAmount = cartItems.map { cartItemModel: CartItemModel -> cartItemModel.amount }.sum() cartModel.total = cartModel.restaurant_tax + cartModel.totalAmount onAddTotal.onPriceCount(cartModel.totalAmount, cartModel.total) Glide.with(context).asBitmap().load(cartItems[position].itemImage) .into(holder.itemviewCartItems.cartItemImage) if (cartItems[position].itemQuantity == 1) { holder.itemviewCartItems.minusButton.setImageResource(R.drawable.qty_minus) } else { holder.itemviewCartItems.minusButton.setImageResource(R.drawable.qty_minus_active) } holder.itemviewCartItems.plusButton.setOnClickListener { cartItemIncrement( holder.itemviewCartItems.textViewItemCount, cartItems[position], cartModel, holder.itemviewCartItems.minusButton ) } holder.itemviewCartItems.minusButton.setOnClickListener { cartItemDecrement( holder.itemviewCartItems.textViewItemCount, cartItems[position], cartModel, holder.itemviewCartItems.minusButton ) } holder.itemviewCartItems.imageViewItemRemove.setOnClickListener { val cartBUttons = CartButtons() cartBUttons.user_id = getUserFromPreference(context).id cartBUttons.food_id = cartItems[holder.adapterPosition].item_id cartBUttons.quantity = 0 val loader = Loader(context, android.R.style.Theme_Translucent_NoTitleBar) loader.show() loader.setCancelable(false) loader.setCanceledOnTouchOutside(false) (context as Activity).window.clearFlags(WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE) cartViewModel.cartRepository.reduceFromCart(cartBUttons).observeForever { val cartItemTotal = SharedPrefsManager.newInstance(context).getInt(Preference.CART_COUNT, 0) val cartTotal = cartItemTotal - cartItems[holder.adapterPosition].itemQuantity onTotalCount.getItemTotal(cartTotal) cartItems.remove(cartItems[holder.adapterPosition]) notifyItemRemoved(holder.adapterPosition) cartModel.totalAmount = cartModel.cartItems?.map { cartItemModel -> cartItemModel.amount }!!.sum() cartModel.total = cartModel.totalAmount + cartModel.restaurant_tax onAddTotal.onPriceCount(cartModel.totalAmount, cartModel.total) if (cartTotal == 0) { onAddTotal.onAllItemRemove() } SharedPrefsManager.newInstance(context).putInt(Preference.CART_COUNT, cartTotal) loader.cancel() } } } class CartItemViewHolder( val context: Context, cartItemsLayouts: CartItemLayoutBinding ) : RecyclerView.ViewHolder(cartItemsLayouts.root) { val itemviewCartItems: CartItemLayoutBinding = cartItemsLayouts } private fun cartItemIncrement( view: TextView, cart: CartItemModel, cartModel: CartModel, minusImage: ImageView) { val cartBUttons = CartButtons() cartBUttons.user_id = getUserFromPreference(context).id cartBUttons.food_id = cart.item_id cartBUttons.quantity = 1 val loader = Loader(context, android.R.style.Theme_Translucent_NoTitleBar) loader.show() loader.setCancelable(false) loader.setCanceledOnTouchOutside(false) (context as Activity).window.clearFlags(WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE) cartViewModel.cartRepository.incrementToCart(cartBUttons).observeForever { loader.cancel() if (it.status == Result.Status.SUCCESS) { val cartItemTotal = SharedPrefsManager.newInstance(context).getInt(Preference.CART_COUNT, 0) SharedPrefsManager.newInstance(context) .putInt(Preference.CART_COUNT, cartItemTotal + 1) onTotalCount.getItemTotal(cartItemTotal + 1) val itemCount = cart.itemQuantity + 1 view.text = itemCount.toString() cart.amount = (cart.itemQuantity * cart.itemPrice) cartModel.totalAmount = cartModel.cartItems?.map { cartItemModel -> cartItemModel.amount }!!.sum() cartModel.total = cartModel.totalAmount + cartModel.restaurant_tax onAddTotal.onPriceCount(cartModel.totalAmount, cartModel.total) if (itemCount > 1) { minusImage.setImageResource(R.drawable.qty_minus_active) } else { minusImage.setImageResource(R.drawable.qty_minus) } } else { showAlert(context, it.message.toString()) } } } fun cartItemDecrement( view: TextView, cart: CartItemModel, cartModel: CartModel, minusImage: ImageView ) { if (cart.itemQuantity > 1) { var cartBUttons = CartButtons() cartBUttons.user_id = getUserFromPreference(context).id cartBUttons.food_id = cart.item_id cartBUttons.quantity = 1 val loader = Loader(context, android.R.style.Theme_Translucent_NoTitleBar) loader.show() loader.setCancelable(false) loader.setCanceledOnTouchOutside(false) (context as Activity).window.clearFlags(WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE) cartViewModel.cartRepository.reduceFromCart(cartBUttons).observeForever { loader.cancel() if (it.status == Result.Status.SUCCESS) { val cartItemTotal = SharedPrefsManager.newInstance(context).getInt(Preference.CART_COUNT, 0) SharedPrefsManager.newInstance(context) .putInt(Preference.CART_COUNT, cartItemTotal - 1) onTotalCount.getItemTotal(cartItemTotal - 1) var itemCount = cart.itemQuantity - 1 view.text = itemCount.toString() cart.amount = (cart.itemQuantity * cart.itemPrice) cartModel.totalAmount = cartModel.cartItems?.map { cartItemModel -> cartItemModel.amount }!!.sum() //var mainFinal=cartModel.totalAmount+cartModel.restaurant_tax cartModel.total = cartModel.restaurant_tax + cartModel.totalAmount onAddTotal.onPriceCount(cartModel.totalAmount, cartModel.total) if (itemCount > 1) { minusImage.setImageResource(R.drawable.qty_minus_active) } else { minusImage.setImageResource(R.drawable.qty_minus) } } else { showAlert(context, it.message.toString()) } } } } }
0
Kotlin
0
0
4fd3704a83c8e3ad7026bfda167c9b9b654384b1
9,439
ozieats
MIT License
tools/simulator/src/main/kotlin/io/libp2p/simulate/stream/Libp2pConnectionImpl.kt
libp2p
189,293,403
false
null
package io.libp2p.simulate.stream import io.libp2p.core.PeerId import io.libp2p.core.crypto.PubKey import io.libp2p.core.multiformats.Multiaddr import io.libp2p.core.security.SecureChannel import io.libp2p.simulate.util.DummyChannel import io.libp2p.simulate.util.NullTransport import io.libp2p.transport.implementation.ConnectionOverNetty class Libp2pConnectionImpl( val remoteAddr: Multiaddr, isInitiator: Boolean, localPubkey: PubKey, remotePubkey: PubKey, ) : ConnectionOverNetty( DummyChannel(), NullTransport(), isInitiator ) { init { setSecureSession( SecureChannel.Session( PeerId.fromPubKey(localPubkey), PeerId.fromPubKey(remotePubkey), remotePubkey, null ) ) } override fun remoteAddress() = remoteAddr }
30
null
75
265
7cf9e990c77be65f549ecfe9d4e908f59796c2dc
867
jvm-libp2p
Apache License 2.0
integration/camunda-bpm/engine-client/src/test/kotlin/io/holunda/camunda/client/task/TaskEventHandlerTest.kt
margue
384,111,593
true
{"Kotlin": 647631}
package io.holunda.camunda.client.task import io.holunda.camunda.client.CamundaEngineClientProperties import io.holunda.camunda.taskpool.api.task.* import org.camunda.bpm.engine.TaskService import org.camunda.bpm.extension.mockito.QueryMocks import org.camunda.bpm.extension.mockito.task.TaskFake import org.junit.jupiter.api.BeforeEach import org.junit.jupiter.api.Test import org.junit.jupiter.api.extension.ExtendWith import org.mockito.Mock import org.mockito.junit.jupiter.MockitoExtension import org.mockito.kotlin.verify import org.mockito.kotlin.verifyNoMoreInteractions import java.util.* @ExtendWith(MockitoExtension::class) class TaskEventHandlerTest { private val properties = CamundaEngineClientProperties(applicationName = "myApplication") private val processReference = ProcessReference( instanceId = UUID.randomUUID().toString(), name = "My Process", applicationName = properties.applicationName, definitionId = "PROCESS:001", definitionKey = "PROCESS", executionId = UUID.randomUUID().toString() ) @Mock private lateinit var taskService: TaskService private lateinit var taskEventHandlers: TaskEventHandlers private lateinit var now: Date @BeforeEach fun init() { taskEventHandlers = TaskEventHandlers(taskService, properties) now = Date() } @Test fun `should ignore event if not addressed to current application`() { val otherReference = ProcessReference( instanceId = UUID.randomUUID().toString(), name = "My Process", applicationName = "another application", definitionId = "PROCESS:001", definitionKey = "PROCESS", executionId = UUID.randomUUID().toString() ) taskEventHandlers.on(TaskClaimedEvent(id = "4711", taskDefinitionKey = "TASK-001", sourceReference = otherReference, assignee = "kermit", formKey = null)) taskEventHandlers.on(TaskUnclaimedEvent(id = "4711", taskDefinitionKey = "TASK-001", sourceReference = otherReference, formKey = null)) taskEventHandlers.on(TaskDeferredEvent(id = "4711", taskDefinitionKey = "TASK-001", sourceReference = otherReference, followUpDate = now, formKey = null)) taskEventHandlers.on(TaskUndeferredEvent(id = "4711", taskDefinitionKey = "TASK-001", sourceReference = otherReference, formKey = null)) taskEventHandlers.on(TaskToBeCompletedEvent(id = "4711", taskDefinitionKey = "TASK-001", sourceReference = otherReference, formKey = null)) verifyNoMoreInteractions(taskService) } @Test fun `should claim`() { val taskFake = TaskFake.builder().id("4711").build() QueryMocks.mockTaskQuery(taskService).singleResult(taskFake) taskEventHandlers.on(TaskClaimedEvent(id = taskFake.id, taskDefinitionKey = "TASK-001", sourceReference = processReference, assignee = "kermit", formKey = null)) verify(taskService).createTaskQuery() verify(taskService).setAssignee("4711", "kermit") verifyNoMoreInteractions(taskService) } }
0
null
0
0
d5797861e5d7126dcdfd5e5b9cca8478f887cf68
2,952
camunda-bpm-taskpool
Apache License 2.0
src/main/kotlin/com/freewill/repository/jpa/ProfileRepository.kt
free-wiII
685,840,987
false
{"Kotlin": 117508, "HTML": 76338}
package com.freewill.repository.jpa import com.freewill.entity.Profile import com.freewill.entity.User import org.springframework.data.jpa.repository.JpaRepository import org.springframework.stereotype.Repository @Repository interface ProfileRepository : JpaRepository<Profile, Long> { fun findByUser(user: User): Profile? }
0
Kotlin
0
2
1dfee10b9bcd740abaaa418e9be71e11bf11f4da
331
synergy-be
MIT License
src/main/kotlin/com/geogrind/geogrindbackend/repositories/sessions/SessionsRepository.kt
GeoGrind
703,185,030
false
{"Kotlin": 355636, "Shell": 2624, "HTML": 1687, "Dockerfile": 488, "Java": 302}
package com.geogrind.geogrindbackend.repositories.sessions import com.geogrind.geogrindbackend.models.sessions.Sessions import com.geogrind.geogrindbackend.models.user_profile.UserProfile import org.springframework.data.jpa.repository.JpaRepository import org.springframework.stereotype.Repository import java.util.Optional import java.util.UUID @Repository interface SessionsRepository : JpaRepository<Sessions, UUID> { fun findByProfile(userProfile: UserProfile): Optional<Sessions> }
13
Kotlin
0
2
b1d44aac6e304f5c97ba233882c0dca42eddf3f7
492
GeoGrind-Backend
Apache License 2.0
meistercharts-api/meistercharts-easy-api/src/jsMain/kotlin/com/meistercharts/api/line/LineChartSimpleConverter.kt
Neckar-IT
599,079,962
false
{"Kotlin": 5819931, "HTML": 87784, "JavaScript": 1378, "CSS": 1114}
/** * Copyright 2023 Neckar IT GmbH, Mössingen, Germany * * 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.meistercharts.api.line import com.meistercharts.algorithms.layers.linechart.LineStyle as ModelLineStyle import com.meistercharts.api.LineStyle as JsLineStyle import com.meistercharts.algorithms.painter.DirectLinePainter import com.meistercharts.algorithms.painter.SplineLinePainter import com.meistercharts.api.PointConnectionStyle import com.meistercharts.api.PointConnectionType import com.meistercharts.api.PointType import com.meistercharts.api.toColor import com.meistercharts.api.toModel import com.meistercharts.painter.CategoryLinePainter import com.meistercharts.painter.CategoryPointPainter import com.meistercharts.painter.CircleCategoryPointPainter import com.meistercharts.painter.Cross45DegreesCategoryPointPainter import com.meistercharts.painter.CrossCategoryPointPainter import com.meistercharts.painter.DotCategoryPointPainter import com.meistercharts.painter.XyCategoryLinePainter import com.meistercharts.painter.emptyCategoryLinePainter import com.meistercharts.painter.emptyCategoryPointPainter import it.neckar.open.charting.api.sanitizing.sanitize import it.neckar.open.collections.fastMapIndexed import it.neckar.open.kotlin.lang.getModuloOrElse import it.neckar.open.kotlin.lang.getModuloOrNull import it.neckar.open.provider.MultiProvider /** * Converter for the line chart */ object LineChartSimpleConverter { fun <IndexContext> toPointPainters(jsLineStyles: Array<LineChartLineStyle?>): MultiProvider<IndexContext, CategoryPointPainter> { val categoryPointPainters = jsLineStyles.map { toCategoryPointPainter(it) } return MultiProvider.forListModulo(categoryPointPainters, emptyCategoryPointPainter) } private fun toCategoryPointPainter(jsLineStyle: LineChartLineStyle?): CategoryPointPainter { if (jsLineStyle == null) { return emptyCategoryPointPainter } val pointTypes = jsLineStyle.pointType?.map { it?.let { it.sanitize() } } ?: emptyList() val pointColors1 = jsLineStyle.pointColor1?.map { it?.let { it.toColor() } } ?: emptyList() val pointColors2 = jsLineStyle.pointColor2?.map { it?.let { it.toColor() } } ?: emptyList() val pointSizes = jsLineStyle.pointSize?.toList() ?: emptyList() val pointLineWidths = jsLineStyle.pointLineWidth?.toList() ?: emptyList() val categoryPointPainters = pointTypes.fastMapIndexed { index, pointType -> when (pointType) { PointType.None -> { emptyCategoryPointPainter } PointType.Dot -> { DotCategoryPointPainter(snapXValues = false, snapYValues = false).apply { pointColors1.getModuloOrNull(index)?.let { pointStylePainter.color = it } pointSizes.getModuloOrNull(index)?.let { pointStylePainter.pointSize = it } pointLineWidths.getModuloOrNull(index)?.let { pointStylePainter.lineWidth = it } } } PointType.Cross -> { CrossCategoryPointPainter(snapXValues = false, snapYValues = false).apply { pointColors1.getModuloOrNull(index)?.let { pointStylePainter.color = it } pointSizes.getModuloOrNull(index)?.let { pointStylePainter.pointSize = it } pointLineWidths.getModuloOrNull(index)?.let { pointStylePainter.lineWidth = it } } } PointType.Cross45 -> { Cross45DegreesCategoryPointPainter(snapXValues = false, snapYValues = false).apply { pointColors1.getModuloOrNull(index)?.let { pointStylePainter.color = it } pointSizes.getModuloOrNull(index)?.let { pointStylePainter.pointSize = it } pointLineWidths.getModuloOrNull(index)?.let { pointStylePainter.lineWidth = it } } } PointType.Circle -> { CircleCategoryPointPainter(snapXValues = false, snapYValues = false).apply { pointColors1.getModuloOrNull(index)?.let { circlePointPainter.fill = it } pointColors2.getModuloOrNull(index)?.let { circlePointPainter.stroke = it } pointSizes.getModuloOrNull(index)?.let { circlePointPainter.pointSize = it } } } null -> { emptyCategoryPointPainter } } } return CategoryPointPainter { gc, x, y, categoryIndex, seriesIndex, value -> val categoryPointPainter = categoryPointPainters.getModuloOrElse(categoryIndex.value, emptyCategoryPointPainter) categoryPointPainter.paintPoint(gc, x, y, categoryIndex, seriesIndex, value) } } fun <IndexContext> toLinePainters(jsLineStyles: Array<LineChartLineStyle?>): MultiProvider<IndexContext, CategoryLinePainter> { val categoryLinePainters = jsLineStyles.map { toCategoryLinePainter(it?.lineStyle) } return MultiProvider.forListModulo(categoryLinePainters, emptyCategoryLinePainter) } private fun toCategoryLinePainter(jsLineStyle: JsLineStyle?): CategoryLinePainter { if (jsLineStyle == null) { return emptyCategoryLinePainter } if (jsLineStyle.type?.sanitize() == PointConnectionStyle.None) { return emptyCategoryLinePainter } return XyCategoryLinePainter(snapXValues = false, snapYValues = false) } fun <IndexContext> toLineStyles(jsLineStyles: Array<LineChartLineStyle?>): MultiProvider<IndexContext, ModelLineStyle> { val categoryLineStyles = jsLineStyles.map { toCategoryLineStyle(it?.lineStyle) } return MultiProvider.forListModulo(categoryLineStyles, ModelLineStyle()) } private fun toCategoryLineStyle(jsLineStyle: JsLineStyle?): ModelLineStyle { if (jsLineStyle == null) { return ModelLineStyle.Continuous } return jsLineStyle.toModel() } fun <IndexContext> toLinePainters(oldLinePainters: MultiProvider<IndexContext, CategoryLinePainter>, jsLineStyles: Array<LineChartLineStyle?>): MultiProvider<IndexContext, CategoryLinePainter> { val linePainters = jsLineStyles.mapIndexed { index, jsLineStyle -> //Workaround to fix enum val pointConnectionType: PointConnectionType? = jsLineStyle?.pointConnectionType?.let { PointConnectionType.valueOf(it.toString()) } when (pointConnectionType) { PointConnectionType.Direct -> XyCategoryLinePainter(false, false, DirectLinePainter(false, false)) PointConnectionType.Spline -> XyCategoryLinePainter(false, false, SplineLinePainter(false, false)) null -> oldLinePainters.valueAt(index) } } return MultiProvider.forListModulo(linePainters) } }
3
Kotlin
3
5
ed849503e845b9d603598e8d379f6525a7a92ee2
7,032
meistercharts
Apache License 2.0
confluence-plugin/src/main/java/com/networkedassets/git4c/boundary/inbound/RequestedFile.kt
rpaasche
321,741,515
true
{"Kotlin": 798728, "JavaScript": 351426, "Java": 109291, "Groovy": 55451, "CSS": 37375, "ANTLR": 19544, "Gherkin": 15007, "HTML": 14268, "Shell": 4490, "Ruby": 1378, "Batchfile": 1337, "PowerShell": 716}
package com.networkedassets.git4c.boundary.inbound data class RequestedFile( val file: String )
0
Kotlin
0
0
e55391b33cb70d66bbf5f36ba570fb8822f10953
104
git4c
Apache License 2.0
shell/src/main/java/com/stewemetal/takehometemplate/shell/domain/usecase/GetItemUseCase.kt
stewemetal
782,690,916
false
{"Kotlin": 80236}
package com.stewemetal.takehometemplate.shell.domain.usecase import com.stewemetal.takehometemplate.shell.architecture.DispatcherProvider import com.stewemetal.takehometemplate.shell.domain.model.Item import com.stewemetal.takehometemplate.shell.domain.model.ItemId import com.stewemetal.takehometemplate.shell.repository.ItemsRepository import kotlinx.coroutines.withContext import org.koin.core.annotation.Singleton @Singleton class GetItemUseCase( private val itemsRepository: ItemsRepository, private val dispatcherProvider: DispatcherProvider, ) { suspend fun getItem(id: ItemId): Item = withContext(dispatcherProvider.io) { itemsRepository.getItem(id) } }
0
Kotlin
0
0
ee39c12d7a1a6bce3364f0d857bab6a2ac7de51c
704
locationmockery
Apache License 2.0
app/src/main/java/com/kevalpatel2106/ci/greenbuild/main/AccountsAdapter.kt
kevalpatel2106
129,620,378
false
null
/* * Copyright 2018 <NAME>. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0. * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.kevalpatel2106.ci.greenbuild.main import android.support.v7.widget.RecyclerView import android.view.ViewGroup import com.kevalpatel2106.grrenbuild.entities.Account /** * Created by Kevalpatel2106 on 30-Apr-18. * * @author <a href="https://github.com/kevalpatel2106">kevalpatel2106</a> */ internal class AccountsAdapter(private val accounts: ArrayList<Account>, private val listener: AccountClickListener) : RecyclerView.Adapter<AccountsViewHolder>() { override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): AccountsViewHolder { return AccountsViewHolder.create(parent) } override fun getItemCount(): Int = accounts.size override fun onBindViewHolder(holder: AccountsViewHolder, position: Int) { holder.bind(accounts[position], { listener.onAccountClick(it) }) } }
6
Kotlin
14
75
da9f2e64cd09848528f313d0e3188b7c40f4b3f7
1,448
green-build
Apache License 2.0
src/main/kotlin/dev/tmsoft/lib/openapi/spec/Components.kt
turbomates
496,384,184
false
null
package dev.tmsoft.lib.openapi.spec import kotlinx.serialization.Contextual import kotlinx.serialization.Serializable import kotlinx.serialization.json.JsonElement @Serializable data class Components( val schemas: Map<String, SchemaObject>, val responses: Map<String, ResponseObject>, val parameters: Map<String, ParameterObject>, val examples: Map<String, ExampleObject>, val requestBodies: Map<String, RequestBodyObject>, val headers: Map<String, HeaderObject>, val securitySchemes: Map<String, SecuritySchemaObject>, val links: Map<String, LinkObject>, val callbacks: Map<String, CallbackObject> ) @Serializable data class SchemaObject( val nullable: Boolean? = null, val discriminator: DiscriminatorObject? = null, val readOnly: Boolean? = null, val writeOnly: Boolean? = null, val `$ref`: String? = null, // val xml: XMLObject, val externalDocs: ExternalDocumentationObject? = null, val example: JsonElement? = null, val type: String? = null, val properties: Map<String, SchemaObject>? = null, val additionalProperties: SchemaObject? = null, val items: SchemaObject? = null, val deprecated: Boolean? = null, val enum: List<String>? = null ) @Serializable data class ResponseObject( val description: String? = null, val headers: Map<String, HeaderObject>? = null, val content: Map<String, MediaTypeObject>? = null, val links: Map<String, LinkObject>? = null ) @Serializable data class ParameterObject( val name: String, val `in`: String? = null, val description: String? = null, val required: Boolean? = null, val deprecated: Boolean? = null, val allowEmptyValue: Boolean? = null, val style: String? = null, val explode: Boolean? = null, val allowReserved: Boolean? = null, val schema: SchemaObject, @Contextual val example: Any? = null, val examples: Map<String, ExampleObject>? = null ) @Serializable data class ExampleObject( val summary: String?, val description: String?, @Contextual val value: Any?, val externalValue: String? ) @Serializable data class RequestBodyObject( val description: String? = null, val content: Map<String, MediaTypeObject>, val required: Boolean? = null ) @Serializable data class DiscriminatorObject(val propertyName: String, val mapping: Map<String, String>) @Serializable data class MediaTypeObject( val schema: SchemaObject? = null, @Contextual val example: Any? = null, val examples: Map<String, ExampleObject>? = null, val encoding: Map<String, EncodingObject>? = null ) typealias HeaderObject = ParameterObject @Serializable data class SecuritySchemaObject( val type: String, val description: String?, val name: String, val `in`: String, val scheme: String, val bearerFormat: String?, val flows: OAuthFlowsObject, val openIdConnectUrl: String ) @Serializable data class OAuthFlowsObject( val authorizationUrl: String, val tokenUrl: String, val refreshUrl: String, val scopes: Map<String, String> ) @Serializable data class LinkObject( val operationRef: String?, val operationId: String?, val parameters: Map<String, @Contextual Any>?, @Contextual val requestBody: Any?, val description: String?, val server: ServerObject? ) @Serializable data class CallbackObject(val pathObject: PathsObject) @Serializable data class PathsObject(val path: PathItemObject) @Serializable data class PathItemObject( var `$ref`: String? = null, var summary: String? = null, var description: String? = null, var get: OperationObject? = null, var post: OperationObject? = null, var delete: OperationObject? = null, var options: OperationObject? = null, var head: OperationObject? = null, var patch: OperationObject? = null, var trace: OperationObject? = null, var servers: OperationObject? = null, var parameters: List<ParameterObject>? = null ) @Serializable data class OperationObject( val responses: Map<Int, ResponseObject>, val tags: List<String>? = null, val summary: String? = null, val description: String? = null, val externalDocs: ExternalDocumentationObject? = null, val operationId: String? = null, val parameters: List<ParameterObject>? = null, val requestBody: RequestBodyObject? = null, val callbacks: Map<String, CallbackObject>? = null, val deprecated: Boolean? = null, val securitySchemaObject: Map<String, List<String>>? = null, val server: ServerObject? = null ) @Serializable data class ExternalDocumentationObject(val description: String?, val url: String) @Serializable data class EncodingObject( val contentType: String?, val headers: Map<String, HeaderObject>?, val style: String?, val explode: Boolean?, val allowReserved: Boolean? )
0
Kotlin
0
0
f7d0c9ec3216d56e35d18108b708c468d5980d9e
4,887
ktor-open-api
MIT License
java/service-transport-ipc/src/main/java/one/tesseract/service/transport/ipc/IPCTransport.kt
tesseract-one
515,723,398
false
{"Rust": 115074, "Kotlin": 30237}
package one.tesseract.service.transport.ipc import one.tesseract.service.transport.BoundTransport import one.tesseract.service.transport.JavaTransport import one.tesseract.service.transport.Processor class IPCTransport(private val channel: String = "default"): JavaTransport { companion object { @JvmStatic fun default(): IPCTransport = IPCTransport() } override fun bind(processor: Processor): BoundTransport = IPCBoundTransport(Channel.create(channel, processor)) }
4
Rust
2
2
22efca1fd784e71137473d85c4b2343a5d36cec0
506
Tesseract.android
Apache License 2.0
app/src/main/java/com/stevenschoen/putionew/files/FileDownloadMaintenance.kt
DSteve595
5,757,119
false
null
package com.stevenschoen.putionew.files import android.app.Activity import android.app.DownloadManager import android.app.job.JobParameters import android.app.job.JobService import android.content.Context import android.os.AsyncTask import androidx.annotation.WorkerThread import com.stevenschoen.putionew.putioApp class FileDownloadsMaintenanceService : JobService() { companion object { const val FILE_DOWNLOADS_MAINTENANCE_JOB_ID = 1 } override fun onStartJob(job: JobParameters): Boolean { if (job.jobId != FILE_DOWNLOADS_MAINTENANCE_JOB_ID) return false val fileDownloads = putioApp.fileDownloadDatabase.fileDownloadsDao() AsyncTask.execute { fileDownloads.getAllByStatus(FileDownload.Status.Downloaded) .forEach { fileDownload -> if (!isFileDownloaded(this, fileDownload)) { fileDownloads.delete(fileDownload) } } } return true } override fun onStopJob(job: JobParameters?) = false } @WorkerThread fun isFileDownloaded(context: Context, fileId: Long): Boolean { val fileDownload = putioApp(context).fileDownloadDatabase.fileDownloadsDao().getByFileIdSynchronous(fileId) ?: return false return isFileDownloaded(context, fileDownload) } @WorkerThread fun isFileDownloaded(context: Context, fileDownload: FileDownload): Boolean { if (fileDownload.downloadId == null || fileDownload.uri == null) return false val status = queryDownloadStatus(context, fileDownload) return status == DownloadManager.STATUS_SUCCESSFUL } @WorkerThread fun isFileDownloadedOrDownloading(context: Context, fileDownload: FileDownload): Boolean { if (fileDownload.downloadId == null) return false val status = queryDownloadStatus(context, fileDownload) return when (status) { DownloadManager.STATUS_PENDING, DownloadManager.STATUS_RUNNING, DownloadManager.STATUS_SUCCESSFUL -> true else -> false } } private fun queryDownloadStatus(context: Context, fileDownload: FileDownload): Int { val downloadManager = context.getSystemService(Activity.DOWNLOAD_SERVICE) as DownloadManager downloadManager.query( DownloadManager.Query() .setFilterById(fileDownload.downloadId!!) ).use { query -> if (query.moveToFirst()) { return query.getInt(query.getColumnIndex(DownloadManager.COLUMN_STATUS)) } else { return DownloadManager.STATUS_FAILED } } } @WorkerThread fun markFileNotDownloaded(context: Context, fileId: Long) { putioApp(context).fileDownloadDatabase.fileDownloadsDao().getByFileIdSynchronous(fileId)?.let { markFileNotDownloaded(context, it) } } @WorkerThread fun markFileNotDownloaded(context: Context, fileDownload: FileDownload) { putioApp(context).fileDownloadDatabase.fileDownloadsDao().update(fileDownload.apply { status = FileDownload.Status.NotDownloaded uri = null downloadId = null }) } @WorkerThread fun markFileDownloaded(context: Context, fileId: Long) { putioApp(context).fileDownloadDatabase.fileDownloadsDao().getByFileIdSynchronous(fileId)?.let { markFileDownloaded(context, it) } } @WorkerThread fun markFileDownloaded(context: Context, fileDownload: FileDownload) { putioApp(context).fileDownloadDatabase.fileDownloadsDao().update(fileDownload.apply { status = FileDownload.Status.Downloaded }) }
19
Kotlin
30
142
42a2196ee8e80cce3b8582f18fe38594d3f6b7ce
3,334
Put.io
MIT License
app/src/main/java/com/neoapps/skijahorina/features/skicenter/weather/WeatherFragment.kt
MilosVulic
872,651,256
false
{"Kotlin": 120456}
package com.neoapps.skijahorina.features.skicenter.weather import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.TextView import androidx.fragment.app.Fragment import androidx.navigation.fragment.navArgs import androidx.recyclerview.widget.LinearLayoutManager import com.neoapps.skijahorina.R import com.neoapps.skijahorina.common.IconWeatherSetter import com.neoapps.skijahorina.databinding.FragmentWeatherInfoBinding import com.neoapps.skijahorina.databinding.IncludeEmptyListPlaceholderBinding import com.neoapps.skijahorina.main.MainActivity class WeatherFragment : Fragment() { private var bindingProp: FragmentWeatherInfoBinding? = null private val binding get() = bindingProp!! private var bindingPropEmptyState: IncludeEmptyListPlaceholderBinding? = null private val bindingEmptyState get() = bindingPropEmptyState!! private val temperature: WeatherFragmentArgs by navArgs() private val wind: WeatherFragmentArgs by navArgs() private val snow: WeatherFragmentArgs by navArgs() private val currentWeatherIcon: WeatherFragmentArgs by navArgs() private val forecast: WeatherFragmentArgs by navArgs() override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View { bindingProp = FragmentWeatherInfoBinding.inflate(inflater, container, false) bindingPropEmptyState = bindingProp!!.includeEmptylistPlaceholder setUpFragmentName() binding.forecastRecyclerView.layoutManager = LinearLayoutManager(context) if (forecast.forecast.isNotEmpty()) { val forecastList = forecast.forecast.split('|').map { val values = it.split(',') ForecastDay(values[0], values[1], values[2], values[3], values[4], values[5]) } val listAdapter = ForecastAdapter(forecastList) binding.forecastRecyclerView.adapter = listAdapter binding.snowValue.text = snow.snow binding.windValue.text = wind.wind binding.temperatureValue.text = temperature.temperature IconWeatherSetter.displayImage(currentWeatherIcon.currentWeatherIcon, binding.temperatureIcon) } if (forecast.forecast.isEmpty()) { bindingEmptyState.emptyListState.visibility = View.VISIBLE binding.forecastRecyclerView.visibility = View.GONE binding.cardViewTemperature.visibility = View.GONE binding.cardViewWind.visibility = View.GONE binding.cardViewSnow.visibility = View.GONE } else { bindingEmptyState.emptyListState.visibility = View.GONE binding.forecastRecyclerView.visibility = View.VISIBLE binding.cardViewTemperature.visibility = View.VISIBLE binding.cardViewWind.visibility = View.VISIBLE binding.cardViewSnow.visibility = View.VISIBLE } return binding.root } private fun setUpFragmentName() { (activity as MainActivity).supportActionBar?.title = "" val title1TextView = (activity as MainActivity).findViewById<TextView>(R.id.title1) if (title1TextView != null) { title1TextView.visibility = View.VISIBLE title1TextView.text = resources.getText(R.string.weather_lowercase) } } override fun onDestroyView() { super.onDestroyView() bindingProp = null bindingPropEmptyState = null } }
0
Kotlin
0
0
58cd580894db16d14b8a849048299887fc790f24
3,559
Ski-Jahorina
MIT License
app/src/main/kotlin/ir/erfansn/nsmavpn/data/util/NetworkUsageTracker.kt
erfansn
547,180,309
false
{"Kotlin": 611093, "HTML": 313045}
/* * Copyright 2024 Erfan Sn * * 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 ir.erfansn.nsmavpn.data.util import android.app.AppOpsManager import android.app.usage.NetworkStats.Bucket import android.app.usage.NetworkStatsManager import android.content.Context import android.net.ConnectivityManager import android.os.Build import android.os.Process import androidx.core.content.getSystemService import dagger.hilt.android.qualifiers.ApplicationContext import ir.erfansn.nsmavpn.data.model.NetworkUsage import ir.erfansn.nsmavpn.di.IoDispatcher import kotlinx.coroutines.CoroutineDispatcher import kotlinx.coroutines.delay import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.flow import kotlinx.coroutines.flow.flowOn import javax.inject.Inject import kotlin.time.Duration.Companion.seconds interface NetworkUsageTracker { val isUsageAccessPermissionGrant: Boolean fun trackUsage(startEpochTime: Long): Flow<NetworkUsage> } class DefaultNetworkUsageTracker @Inject constructor( @ApplicationContext private val context: Context, @IoDispatcher private val ioDispatcher: CoroutineDispatcher ) : NetworkUsageTracker { private val networkStatsManager = context.getSystemService<NetworkStatsManager>() override val isUsageAccessPermissionGrant: Boolean get() { val appOps = context.getSystemService<AppOpsManager>() ?: return false val mode = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) { appOps.unsafeCheckOpNoThrow(AppOpsManager.OPSTR_GET_USAGE_STATS, Process.myUid(), context.packageName) } else { appOps.checkOpNoThrow(AppOpsManager.OPSTR_GET_USAGE_STATS, Process.myUid(), context.packageName) } return mode == AppOpsManager.MODE_ALLOWED } override fun trackUsage(startEpochTime: Long): Flow<NetworkUsage> = flow { while (true) { val wifiStatsBucket = queryWifiStatsBucket(startEpochTime) val mobileStatsBucket = queryMobileStatsBucket(startEpochTime) emit( value = NetworkUsage( received = wifiStatsBucket.rxBytes + mobileStatsBucket.rxBytes, transmitted = wifiStatsBucket.txBytes + mobileStatsBucket.txBytes, ) ) delay(1.seconds) } }.flowOn(ioDispatcher) private fun queryWifiStatsBucket(startEpochTime: Long) = queryStatsBucket( networkType = ConnectivityManager.TYPE_WIFI, startEpochTime = startEpochTime, ) private fun queryMobileStatsBucket(startEpochTime: Long) = queryStatsBucket( networkType = ConnectivityManager.TYPE_MOBILE, startEpochTime = startEpochTime, ) private fun queryStatsBucket( networkType: Int, startEpochTime: Long, ): Bucket { checkNotNull(networkStatsManager) { "Cannot access to NetworkStatsManager!" } return networkStatsManager.querySummaryForDevice( networkType, null, startEpochTime, Long.MAX_VALUE, ) ?: run { error("GetUsageAccess permission doesn't permitted or internal error occurred") } } }
13
Kotlin
1
35
230181bfc03b19bd5bb52818ee0b8b19078a4ec1
3,796
NsmaVPN
Apache License 2.0
livekit-android-test/src/main/java/livekit/org/webrtc/MockPeerConnectionFactory.kt
livekit
339,892,560
false
null
/* * Copyright 2023-2024 LiveKit, 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 livekit.org.webrtc import io.livekit.android.test.mock.MockPeerConnection import io.livekit.android.test.mock.MockVideoSource import io.livekit.android.test.mock.MockVideoStreamTrack class MockPeerConnectionFactory : PeerConnectionFactory(1L) { override fun createPeerConnectionInternal( rtcConfig: PeerConnection.RTCConfiguration, constraints: MediaConstraints?, observer: PeerConnection.Observer?, sslCertificateVerifier: SSLCertificateVerifier?, ): PeerConnection { return MockPeerConnection(rtcConfig, observer) } override fun createVideoSource(isScreencast: Boolean, alignTimestamps: Boolean): VideoSource { return MockVideoSource() } override fun createVideoSource(isScreencast: Boolean): VideoSource { return MockVideoSource() } override fun createVideoTrack(id: String, source: VideoSource?): VideoTrack { return MockVideoStreamTrack(id = id) } override fun getRtpSenderCapabilities(mediaType: MediaStreamTrack.MediaType): RtpCapabilities { return RtpCapabilities( listOf( RtpCapabilities.CodecCapability().apply { name = "VP8" mimeType = "video/VP8" kind = MediaStreamTrack.MediaType.MEDIA_TYPE_VIDEO parameters = emptyMap() }, RtpCapabilities.CodecCapability().apply { name = "H264" mimeType = "video/H264" kind = MediaStreamTrack.MediaType.MEDIA_TYPE_VIDEO parameters = mapOf("profile-level-id" to "640c1f") }, RtpCapabilities.CodecCapability().apply { name = "H264" mimeType = "video/H264" kind = MediaStreamTrack.MediaType.MEDIA_TYPE_VIDEO parameters = mapOf("profile-level-id" to "42e01f") }, RtpCapabilities.CodecCapability().apply { name = "AV1" mimeType = "video/AV1" kind = MediaStreamTrack.MediaType.MEDIA_TYPE_VIDEO parameters = emptyMap() }, RtpCapabilities.CodecCapability().apply { name = "VP9" mimeType = "video/VP9" kind = MediaStreamTrack.MediaType.MEDIA_TYPE_VIDEO parameters = mapOf("profile-id" to "0") }, ), emptyList(), ) } }
62
null
69
176
b2858976de9ea0c91fd0d29432e8a2a7f973e30b
3,194
client-sdk-android
Apache License 2.0
yapp-auth/src/main/kotlin/auth/BasicAuthUtils.kt
IgorPerikov
131,679,239
false
null
package auth import io.ktor.auth.Principal import io.ktor.auth.UserIdPrincipal import io.ktor.auth.UserPasswordCredential import io.ktor.util.encodeBase64 import io.ktor.util.getDigestFunction import org.jetbrains.exposed.sql.and import org.jetbrains.exposed.sql.transactions.transaction object BasicAuthUtils { private val passwordSalt = System.getenv("PASSWORD_SALT") ?: "this_is_default_password_salt" private val digestFunction = getDigestFunction("SHA-256", passwordSalt) fun isUsernameAlreadyTaken(name: String) = transaction { !UserEntity.find { UsersTable.username eq name }.empty() } fun authenticateByPassword(credential: UserPasswordCredential): Principal? { val hashedPassword = hashAndEncodePassword(credential.password) val userId: Int? = transaction { val find = UserEntity.find { (UsersTable.username eq credential.name) and (UsersTable.password eq hashedPassword) } if (find.empty()) { null } else { find.first().id.value } } return userId?.let { UserIdPrincipal(it.toString()) } } fun hashAndEncodePassword(password: String) = encodeBase64(digestFunction.invoke(password)) }
0
Kotlin
0
1
4a34a924bb25c0872d83e044763e604a0e46d469
1,250
yapp
MIT License
authentication-service/api/src/main/kotlin/org/amogus/authenticationservice/api/requests/AuthenticationRequest.kt
Doremi203
805,741,239
false
{"Kotlin": 87060, "Dockerfile": 15}
package org.amogus.authenticationservice.api.requests import jakarta.validation.constraints.Email import jakarta.validation.constraints.NotBlank data class AuthenticationRequest( @get:NotBlank(message = "Email is required") @get:Email(message = "Invalid email") val email: String, @get:NotBlank(message = "Password is required") val password: String, )
0
Kotlin
0
0
55c044cfed78fb7e35d17bb9a973622df5ef5db0
376
TicketsMicroservices
MIT License
src/main/kotlin/us/frollo/frollosdk/model/coredata/reports/ReportDateFormat.kt
frollous
261,670,220
false
null
/* * Copyright 2019 Frollo * * 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 us.frollo.frollosdk.model.coredata.reports /** Date format patterns to convert date from stored date string to user's current locale */ class ReportDateFormat { companion object { /** Date format to convert daily date from stored date string to user's current locale */ const val DAILY = "yyyy-MM-dd" /** Date format to convert monthly date from stored date string to user's current locale */ const val MONTHLY = "yyyy-MM" /** * Date formatter to convert weekly date from stored date string to user's current locale. * * NOTE: W = week of month (1-5) (the first week starts on the first day of the month) */ const val WEEKLY = "yyyy-MM-W" /** Date formatter pattern for the dates in the request query */ const val DATE_PATTERN_FOR_REQUEST = "yyyy-MM-dd" } }
5
Kotlin
0
2
3eed44186c366a9d47252779d11433157403db94
1,468
frollo-android-sdk
Apache License 2.0
svg-to-compose/src/commonMain/kotlin/dev/tonholo/s2c/domain/avg/gradient/AvgGradientType.kt
rafaeltonholo
659,782,425
false
{"Kotlin": 518715, "Shell": 5365}
package dev.tonholo.s2c.domain.avg.gradient import dev.tonholo.s2c.logger.warn enum class AvgGradientType { Linear, Radial, Sweep, ; override fun toString(): String = name.lowercase() companion object { operator fun invoke(value: String): AvgGradientType = when (value) { Linear.toString() -> Linear Radial.toString() -> Radial Sweep.toString() -> Sweep else -> { warn( "'$value' is an unsupported type of type for ${AvgGradient.TAG_NAME} tag. " + "Using default to '$Linear", ) Linear } } } }
5
Kotlin
2
61
b3e7c5ffa041d5d31c686d72b9119661b5e4ce7b
694
svg-to-compose
MIT License
alice-ktx/src/main/kotlin/com/github/alice/ktx/api/common/Response.kt
danbeldev
833,612,985
false
{"Kotlin": 63137}
package com.github.alice.ktx.api.common /** * Запечатанный интерфейс, представляющий ответ, который может быть либо успешным, либо неудачным. * * @param T Тип данных, возвращаемых в успешном ответе. */ sealed interface Response<T> { /** * Представляет неудачный ответ. * * @param T Тип данных, которые были бы возвращены в успешном ответе. * @param message Сообщение об ошибке, объясняющее причину неудачи. */ data class Failed<T>(val message: String): Response<T> /** * Представляет успешный ответ. * * @param T Тип данных, возвращаемых в ответе. * @param data Данные, возвращаемые в успешном ответе. */ data class Success<T>(val data: T): Response<T> }
0
Kotlin
0
3
11a47be88a2fe3aeede7300c1daf122ddf56cdf8
728
alice-ktx
MIT License
indy-utils/src/test/kotlin/com/luxoft/blockchainlab/hyperledger/indy/AnoncredsDemoTest.kt
advata
153,336,525
true
{"Kotlin": 208863, "Dockerfile": 1875, "Shell": 281}
package com.luxoft.blockchainlab.hyperledger.indy import com.luxoft.blockchainlab.hyperledger.indy.utils.LedgerService import com.luxoft.blockchainlab.hyperledger.indy.utils.PoolManager import com.luxoft.blockchainlab.hyperledger.indy.utils.SerializationUtils import com.luxoft.blockchainlab.hyperledger.indy.utils.StorageUtils import junit.framework.Assert.assertFalse import org.hyperledger.indy.sdk.did.Did import org.hyperledger.indy.sdk.did.DidResults import org.hyperledger.indy.sdk.pool.Pool import org.hyperledger.indy.sdk.wallet.Wallet import org.junit.* import org.junit.Assert.assertEquals import org.junit.Assert.assertTrue class AnoncredsDemoTest : IndyIntegrationTest() { private val masterSecretId = "masterSecretId" private val gvtCredentialValues = GVT_CRED_VALUES private val xyzCredentialValues = """{"status":{"raw":"partial","encoded":"51792877103171595686471452153480627530895"},"period":{"raw":"8","encoded":"8"}}""" private val issuerWalletConfig = SerializationUtils.anyToJSON(WalletConfig("issuerWallet")) private val issuer2WalletConfig = SerializationUtils.anyToJSON(WalletConfig("issuer2Wallet")) private val proverWalletConfig = SerializationUtils.anyToJSON(WalletConfig("proverWallet")) private lateinit var issuerWallet: Wallet private lateinit var issuer2Wallet: Wallet private lateinit var proverWallet: Wallet private lateinit var issuerDidInfo: DidResults.CreateAndStoreMyDidResult private lateinit var issuer2DidInfo: DidResults.CreateAndStoreMyDidResult private lateinit var proverDidInfo: DidResults.CreateAndStoreMyDidResult private lateinit var issuer1: IndyUser private lateinit var issuer2: IndyUser private lateinit var prover: IndyUser companion object { private lateinit var pool: Pool private lateinit var poolName: String @JvmStatic @BeforeClass fun setUpTest() { // Create and Open Pool poolName = PoolManager.DEFAULT_POOL_NAME pool = PoolManager.openIndyPool(PoolManager.defaultGenesisResource, poolName) } @JvmStatic @AfterClass fun tearDownTest() { // Close pool pool.closePoolLedger().get() Pool.deletePoolLedgerConfig(poolName) } } @Before @Throws(Exception::class) fun setUp() { // Clean indy stuff StorageUtils.cleanupStorage() // Issuer Create and Open Wallet Wallet.createWallet(issuerWalletConfig, CREDENTIALS).get() issuerWallet = Wallet.openWallet(issuerWalletConfig, CREDENTIALS).get() Wallet.createWallet(issuer2WalletConfig, CREDENTIALS).get() issuer2Wallet = Wallet.openWallet(issuer2WalletConfig, CREDENTIALS).get() // Prover Create and Open Wallet Wallet.createWallet(proverWalletConfig, CREDENTIALS).get() proverWallet = Wallet.openWallet(proverWalletConfig , CREDENTIALS).get() val trusteeDidInfo = createTrusteeDid(issuerWallet) issuerDidInfo = createDid(issuerWallet) linkIssuerToTrustee(trusteeDidInfo.did, issuerWallet, issuerDidInfo) issuer2DidInfo = createDid(issuer2Wallet) linkIssuerToTrustee(trusteeDidInfo.did, issuerWallet, issuer2DidInfo) proverDidInfo = createDid(proverWallet) linkProverToIssuer(issuerDidInfo.did, issuerWallet, proverDidInfo) issuer1 = IndyUser(pool, issuerWallet, issuerDidInfo.did) issuer2 = IndyUser(pool, issuer2Wallet, issuer2DidInfo.did) prover = IndyUser(pool, proverWallet, proverDidInfo.did) } @After @Throws(Exception::class) fun tearDown() { // Issuer Remove Wallet issuerWallet.closeWallet().get() Wallet.deleteWallet(issuerWalletConfig, CREDENTIALS).get() issuer2Wallet.closeWallet().get() Wallet.deleteWallet(issuer2WalletConfig, CREDENTIALS).get() // Prover Remove Wallet proverWallet.closeWallet().get() Wallet.deleteWallet(proverWalletConfig, CREDENTIALS).get() // Clean indy stuff StorageUtils.cleanupStorage() } private fun createTrusteeDid(wallet: Wallet) = Did.createAndStoreMyDid(wallet, """{"seed":"$TRUSTEE_SEED"}""").get() private fun createDid(wallet: Wallet) = Did.createAndStoreMyDid(wallet, "{}").get() private fun linkIssuerToTrustee(trusteeDid: String, issuerWallet: Wallet, issuerDidInfo: DidResults.CreateAndStoreMyDidResult) { val target = IndyUser.IdentityDetails(issuerDidInfo.did, issuerDidInfo.verkey, null, "TRUSTEE") LedgerService.addNym(trusteeDid, pool, issuerWallet, target) } private fun linkProverToIssuer(issuerDid: String, issuerWallet: Wallet, proverDidInfo: DidResults.CreateAndStoreMyDidResult) { val target = IndyUser.IdentityDetails(proverDidInfo.did, proverDidInfo.verkey, null, null) LedgerService.addNym(issuerDid, pool, issuerWallet, target) } @Test @Throws(Exception::class) fun `revocation works fine`() { val gvtSchema = issuer1.createSchema(GVT_SCHEMA_NAME, SCHEMA_VERSION, GVT_SCHEMA_ATTRIBUTES) val credDef = issuer1.createClaimDefinition(gvtSchema.id, true) val revRegInfo = issuer1.createRevocationRegistry(credDef.id) prover.createMasterSecret(masterSecretId) val credOffer = issuer1.createClaimOffer(credDef.id) val credReq = prover.createClaimRequest(prover.did, credOffer, masterSecretId) val claimInfo = issuer1.issueClaim(credReq, gvtCredentialValues, credOffer, revRegInfo.definition.id) prover.receiveClaim(claimInfo, credReq, credOffer) Thread.sleep(3000) val field_name = CredFieldRef("name", gvtSchema.id, credDef.id) val field_sex = CredFieldRef("sex", gvtSchema.id, credDef.id) val field_age = CredFieldRef("age", gvtSchema.id, credDef.id) val proofReq = IndyUser.createProofRequest( attributes = listOf(field_name, field_sex), predicates = listOf(CredPredicate(field_age, 18)), nonRevoked = Interval.recent() ) val proof = prover.createProof(proofReq, masterSecretId) val usedData = IndyUser.getDataUsedInProof(DID_MY1, pool, proofReq, proof) assertEquals("Alex", proof.proofData.requestedProof.revealedAttrs["name"]!!.raw) assertTrue(IndyUser.verifyProof(proofReq, proof, usedData)) issuer1.revokeClaim(claimInfo.claim.revRegId!!, claimInfo.credRevocId!!) Thread.sleep(3000) val proofReqAfterRevocation = IndyUser.createProofRequest( attributes = listOf(field_name, field_sex), predicates = listOf(CredPredicate(field_age, 18)), nonRevoked = Interval.recent() ) val proofAfterRevocation = prover.createProof(proofReqAfterRevocation, masterSecretId) val usedDataAfterRevocation = IndyUser.getDataUsedInProof(DID_MY1, pool, proofReqAfterRevocation, proofAfterRevocation) assertFalse(IndyUser.verifyProof(proofReqAfterRevocation, proofAfterRevocation, usedDataAfterRevocation)) } @Test @Throws(Exception::class) fun `1 issuer 1 prover 1 claim setup works fine`() { val gvtSchema = issuer1.createSchema(GVT_SCHEMA_NAME, SCHEMA_VERSION, GVT_SCHEMA_ATTRIBUTES) val credDef = issuer1.createClaimDefinition(gvtSchema.id, false) prover.createMasterSecret(masterSecretId) val credOffer = issuer1.createClaimOffer(credDef.id) val credReq = prover.createClaimRequest(prover.did, credOffer, masterSecretId) val claimInfo = issuer1.issueClaim(credReq, gvtCredentialValues, credOffer, null) prover.receiveClaim(claimInfo, credReq, credOffer) val field_name = CredFieldRef("name", gvtSchema.id, credDef.id) val field_sex = CredFieldRef("sex", gvtSchema.id, credDef.id) val field_age = CredFieldRef("age", gvtSchema.id, credDef.id) val proofReq = IndyUser.createProofRequest( attributes = listOf(field_name, field_sex), predicates = listOf(CredPredicate(field_age, 18)), nonRevoked = null ) val proof = prover.createProof(proofReq, masterSecretId) val usedData = IndyUser.getDataUsedInProof(DID_MY1, pool, proofReq, proof) assertEquals("Alex", proof.proofData.requestedProof.revealedAttrs["name"]!!.raw) assertTrue(IndyUser.verifyProof(proofReq, proof, usedData)) } @Test @Throws(Exception::class) fun `2 issuers 1 prover 2 claims setup works fine`() { val schema1 = issuer1.createSchema(GVT_SCHEMA_NAME, SCHEMA_VERSION, GVT_SCHEMA_ATTRIBUTES) val credDef1 = issuer1.createClaimDefinition(schema1.id, false) val schema2 = issuer2.createSchema(XYZ_SCHEMA_NAME, SCHEMA_VERSION, XYZ_SCHEMA_ATTRIBUTES) val credDef2 = issuer2.createClaimDefinition(schema2.id, false) prover.createMasterSecret(masterSecretId) val gvtCredOffer = issuer1.createClaimOffer(credDef1.id) val xyzCredOffer = issuer2.createClaimOffer(credDef2.id) val gvtCredReq = prover.createClaimRequest(prover.did, gvtCredOffer, masterSecretId) val gvtCredential = issuer1.issueClaim(gvtCredReq, gvtCredentialValues, gvtCredOffer, null) prover.receiveClaim(gvtCredential, gvtCredReq, gvtCredOffer) val xyzCredReq = prover.createClaimRequest(prover.did, xyzCredOffer, masterSecretId) val xyzCredential = issuer2.issueClaim(xyzCredReq, xyzCredentialValues, xyzCredOffer, null) prover.receiveClaim(xyzCredential, xyzCredReq, xyzCredOffer) val field_name = CredFieldRef("name", schema1.id, credDef1.id) val field_age = CredFieldRef("age", schema1.id, credDef1.id) val field_status = CredFieldRef("status", schema2.id, credDef2.id) val field_period = CredFieldRef("period", schema2.id, credDef2.id) val proofReq = IndyUser.createProofRequest( attributes = listOf(field_name, field_status), predicates = listOf(CredPredicate(field_age, 18), CredPredicate(field_period, 5)), nonRevoked = null ) val proof = prover.createProof(proofReq, masterSecretId) // Verifier verify Proof val revealedAttr0 = proof.proofData.requestedProof.revealedAttrs["name"]!! assertEquals("Alex", revealedAttr0.raw) val revealedAttr1 = proof.proofData.requestedProof.revealedAttrs["status"]!! assertEquals("partial", revealedAttr1.raw) val usedData = prover.getDataUsedInProof(proofReq, proof) assertTrue(IndyUser.verifyProof(proofReq, proof, usedData)) } @Test @Throws(Exception::class) fun `1 issuer 1 prover 2 claims setup works fine`() { val gvtSchema = issuer1.createSchema(GVT_SCHEMA_NAME, SCHEMA_VERSION, GVT_SCHEMA_ATTRIBUTES) val gvtCredDef = issuer1.createClaimDefinition(gvtSchema.id, false) val xyzSchema = issuer1.createSchema(XYZ_SCHEMA_NAME, SCHEMA_VERSION, XYZ_SCHEMA_ATTRIBUTES) val xyzCredDef = issuer1.createClaimDefinition(xyzSchema.id, false) prover.createMasterSecret(masterSecretId) val gvtCredOffer = issuer1.createClaimOffer(gvtCredDef.id) val xyzCredOffer = issuer1.createClaimOffer(xyzCredDef.id) val gvtCredReq = prover.createClaimRequest(prover.did, gvtCredOffer, masterSecretId) val gvtCredential = issuer1.issueClaim(gvtCredReq, gvtCredentialValues, gvtCredOffer, null) prover.receiveClaim(gvtCredential, gvtCredReq, gvtCredOffer) val xyzCredReq = prover.createClaimRequest(prover.did, xyzCredOffer, masterSecretId) val xyzCredential = issuer1.issueClaim(xyzCredReq, xyzCredentialValues, xyzCredOffer, null) prover.receiveClaim(xyzCredential, xyzCredReq, xyzCredOffer) val field_name = CredFieldRef("name", gvtSchema.id, gvtCredDef.id) val field_age = CredFieldRef("age", gvtSchema.id, gvtCredDef.id) val field_status = CredFieldRef("status", xyzSchema.id, xyzCredDef.id) val field_period = CredFieldRef("period", xyzSchema.id, xyzCredDef.id) val proofReq = IndyUser.createProofRequest( attributes = listOf(field_name, field_status), predicates = listOf(CredPredicate(field_age, 18), CredPredicate(field_period, 5)), nonRevoked = null ) val proof = prover.createProof(proofReq, masterSecretId) // Verifier verify Proof val revealedAttr0 = proof.proofData.requestedProof.revealedAttrs["name"]!! assertEquals("Alex", revealedAttr0.raw) val revealedAttr1 = proof.proofData.requestedProof.revealedAttrs["status"]!! assertEquals("partial", revealedAttr1.raw) val usedData = prover.getDataUsedInProof(proofReq, proof) assertTrue(IndyUser.verifyProof(proofReq, proof, usedData)) } }
0
Kotlin
0
0
cea4bf85c125693455d739d8b4f74b0e3c4bb321
12,977
Lumedic-cordentity
Apache License 2.0
main/src/test/java/org/fnives/android/test/dockerfile/configuration/ConfigurationParserTest.kt
fknives
528,731,489
false
{"Kotlin": 46734, "Dockerfile": 8624, "Shell": 6926}
package org.fnives.android.test.dockerfile.configuration import org.fnives.android.test.dockerfile.util.resourceFileAsInputStream import org.junit.jupiter.api.Assertions import org.junit.jupiter.api.BeforeEach import org.junit.jupiter.api.Test class ConfigurationParserTest { private lateinit var parser: ConfigurationParser @BeforeEach fun setUp() { parser = ConfigurationParser() } @Test fun example() { val expectedConfiguration = Configuration( buildTools = setOf("33.0.0", "32.0.0", "31.0.0", "30.0.3", "30.0.2"), sdks = setOf(30, 31, 32, 33), commandlineTools = "8512546_latest", gradleVersion = "7.3.3", output = "outputs", dockerRepository = "fknives", dockerNamespace = "android-test-img", dockerTagPrefix = "1.0.0", apiLevelVariations = setOf(21, 22, 23) ) val rawConfiguration = resourceFileAsInputStream("example_configuration.toml") val actual = parser.invoke(rawConfiguration) Assertions.assertEquals(expectedConfiguration, actual) } @Test fun singleConfiguration() { val expectedConfiguration = Configuration( buildTools = setOf("33.0.0", "32.0.0", "31.0.0"), sdks = setOf(32, 33), commandlineTools = "8512546_latest", gradleVersion = "7.3.3", output = "outputs", dockerRepository = "fknives", dockerNamespace = "android-test-img", dockerTagPrefix = "1.0.0", apiLevelVariations = emptySet() ) val rawConfiguration = resourceFileAsInputStream("single_configuration.toml") val actual = parser.invoke(rawConfiguration) Assertions.assertEquals(expectedConfiguration, actual) } }
0
Kotlin
1
0
e478a4c83617907acba43ecdb60569efa9ea0e73
1,843
AndroidEmuTestImg
Apache License 2.0
keyboard-kt/src/jsTest/kotlin/com/github/animeshz/keyboard/TestUtils.kt
Animeshz
318,761,308
false
null
package com.github.animeshz.keyboard import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.GlobalScope import kotlinx.coroutines.promise actual fun runBlockingTest(block: suspend CoroutineScope.() -> Unit): dynamic = GlobalScope.promise { this.block() }
5
Kotlin
2
49
2d17241a61179c29f2dd1f48137cfbb1bc1d12f4
273
keyboard-mouse-kt
MIT License
app/src/main/java/ch/dreipol/rezhycle/utils/ReminderUtils.kt
terrakok
334,467,384
true
{"Kotlin": 145354, "Swift": 99066, "Ruby": 16325, "Shell": 483}
package ch.dreipol.rezhycle.utils import android.content.BroadcastReceiver import android.content.Context import android.content.Intent import androidx.work.* import ch.dreipol.multiplatform.reduxsample.shared.database.* import java.util.concurrent.TimeUnit import kotlin.time.ExperimentalTime import kotlinx.datetime.Clock import kotlinx.datetime.TimeZone import kotlinx.datetime.toInstant @ExperimentalTime fun updateReminders(context: Context, reminders: List<Reminder>) { val workManager = WorkManager.getInstance(context) workManager.cancelAllWorkByTag(ReminderWorker.WORKER_TAG_NAME) if (reminders.isEmpty()) { return } reminders.forEach { val workRequest = ReminderWorker.createWorkRequest(context, it) workManager.enqueue(workRequest) } } @ExperimentalTime fun setNextReminders(context: Context) { val settingsDataStore = SettingsDataStore() val zip = settingsDataStore.getSettings()?.zip ?: return val notification = settingsDataStore.getNotificationSettings().firstOrNull() ?: return val reminders = notification.getNextReminders(zip) updateReminders(context, reminders) } class ReminderWorker(context: Context, workerParams: WorkerParameters) : Worker(context, workerParams) { companion object { const val WORKER_TAG_NAME = "REMINDER_WORKER" private const val DISPOSAL_TYPES = "DISPOSAL_TYPES" private const val NOTIFICATION_TEXTS = "NOTIFICATION_TEXTS" @ExperimentalTime fun createWorkRequest(context: Context, reminder: Reminder): OneTimeWorkRequest { val initialDelay = reminder.remindDateTime.toInstant(TimeZone.currentSystemDefault()).minus(Clock.System.now()) val data = Data.Builder() .putStringArray(DISPOSAL_TYPES, reminder.disposals.map { it.disposalType.name }.toTypedArray()) .putStringArray( NOTIFICATION_TEXTS, reminder.disposals.map { getReminderNotificationText(context, it) }.toTypedArray() ) .build() return OneTimeWorkRequestBuilder<ReminderWorker>() .setInitialDelay(initialDelay.toLongMilliseconds(), TimeUnit.MILLISECONDS) .setInputData(data) .addTag(WORKER_TAG_NAME) .build() } } @ExperimentalTime override fun doWork(): Result { val disposalTypes = inputData.getStringArray(DISPOSAL_TYPES)?.map { DisposalType.valueOf(it) } ?: return Result.failure() val notificationTexts = inputData.getStringArray(NOTIFICATION_TEXTS)?.toList() ?: return Result.failure() for (i in disposalTypes.indices) { showReminderNotification(applicationContext, disposalTypes[i], notificationTexts[i]) } setNextReminders(applicationContext) return Result.success() } } class BootReceiver : BroadcastReceiver() { @ExperimentalTime override fun onReceive(context: Context, intent: Intent) { if (intent.action != Intent.ACTION_BOOT_COMPLETED) { return } setNextReminders(context) } }
0
Kotlin
0
1
d35f0034f3fa870c00dd783d692dc586c8785614
3,150
multiplatform-redux-sample
MIT License
src/main/kotlin/io/github/stream29/streamlin/Functional.kt
Stream29
859,505,101
false
{"Kotlin": 60065}
package io.github.stream29.streamlin /** * Filters a value based on a predicate. * * @param predicate A function that returns true if the value should be kept, false otherwise. * @return The value if the predicate returns true, null otherwise. */ inline fun <T : Any> T.filter(crossinline predicate: T.() -> Boolean) = if (predicate()) this else null /** * Filters a value based on a predicate. * * @param predicate A function that returns true if the value should be kept, false otherwise. * @return The value if the predicate returns true, null otherwise. */ @JvmName("filterNullable") inline fun <T : Any> T?.filter(crossinline predicate: T.() -> Boolean) = if (this != null && predicate()) this else null
0
Kotlin
0
3
a364da159a0a3b5f73baf261490112271433d599
728
Streamlin
Apache License 2.0
fundamentals/android/auth-sign-in-with-google/Notes/app/src/main/java/com/notes/app/screens/account_center/AccountCenterButtons.kt
FirebaseExtended
467,490,083
false
{"Swift": 584690, "Kotlin": 163332, "JavaScript": 48493, "CSS": 41317, "Vue": 5664, "HTML": 3230}
package com.notes.app.screens.account_center import android.util.Log import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.padding import androidx.compose.material.icons.Icons import androidx.compose.material.icons.filled.Delete import androidx.compose.material.icons.filled.Edit import androidx.compose.material.icons.filled.ExitToApp import androidx.compose.material3.AlertDialog import androidx.compose.material3.Button import androidx.compose.material3.ButtonDefaults import androidx.compose.material3.Card import androidx.compose.material3.ExperimentalMaterial3Api import androidx.compose.material3.Icon import androidx.compose.material3.Text import androidx.compose.material3.TextField import androidx.compose.runtime.Composable import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.runtime.rememberCoroutineScope import androidx.compose.runtime.setValue import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.graphics.vector.ImageVector import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.res.painterResource import androidx.compose.ui.res.stringResource import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.sp import androidx.credentials.Credential import androidx.credentials.CredentialManager import androidx.credentials.GetCredentialRequest import androidx.credentials.exceptions.GetCredentialException import com.google.android.libraries.identity.googleid.GetGoogleIdOption import com.notes.app.ERROR_TAG import com.notes.app.R import com.notes.app.ui.theme.Purple40 import kotlinx.coroutines.launch @Composable @OptIn(ExperimentalMaterial3Api::class) fun DisplayNameCard(displayName: String, onUpdateDisplayNameClick: (String) -> Unit) { var showDisplayNameDialog by remember { mutableStateOf(false) } var newDisplayName by remember { mutableStateOf(displayName) } val cardTitle = displayName.ifBlank { stringResource(R.string.profile_name) } AccountCenterCard(cardTitle, Icons.Filled.Edit, Modifier.card()) { newDisplayName = displayName showDisplayNameDialog = true } if (showDisplayNameDialog) { AlertDialog( title = { Text(stringResource(R.string.profile_name)) }, text = { Column { TextField( value = newDisplayName, onValueChange = { newDisplayName = it } ) } }, dismissButton = { Button(onClick = { showDisplayNameDialog = false }) { Text(text = stringResource(R.string.cancel)) } }, confirmButton = { Button(onClick = { onUpdateDisplayNameClick(newDisplayName) showDisplayNameDialog = false }) { Text(text = stringResource(R.string.update)) } }, onDismissRequest = { showDisplayNameDialog = false } ) } } @Composable @OptIn(ExperimentalMaterial3Api::class) fun AccountCenterCard( title: String, icon: ImageVector, modifier: Modifier = Modifier, onCardClick: () -> Unit ) { Card( modifier = modifier, onClick = onCardClick ) { Row( verticalAlignment = Alignment.CenterVertically, modifier = Modifier .fillMaxWidth() .padding(16.dp) ) { Column(modifier = Modifier.weight(1f)) { Text(title) } Icon(icon, contentDescription = "Icon") } } } fun Modifier.card(): Modifier { return this.padding(16.dp, 0.dp, 16.dp, 8.dp) } @Composable fun ExitAppCard(onSignOutClick: () -> Unit) { var showExitAppDialog by remember { mutableStateOf(false) } AccountCenterCard(stringResource(R.string.sign_out), Icons.Filled.ExitToApp, Modifier.card()) { showExitAppDialog = true } if (showExitAppDialog) { AlertDialog( title = { Text(stringResource(R.string.sign_out_title)) }, text = { Text(stringResource(R.string.sign_out_description)) }, dismissButton = { Button(onClick = { showExitAppDialog = false }) { Text(text = stringResource(R.string.cancel)) } }, confirmButton = { Button(onClick = { onSignOutClick() showExitAppDialog = false }) { Text(text = stringResource(R.string.sign_out)) } }, onDismissRequest = { showExitAppDialog = false } ) } } @Composable fun RemoveAccountCard(onRemoveAccountClick: () -> Unit) { var showRemoveAccDialog by remember { mutableStateOf(false) } AccountCenterCard(stringResource(R.string.delete_account), Icons.Filled.Delete, Modifier.card()) { showRemoveAccDialog = true } if (showRemoveAccDialog) { AlertDialog( title = { Text(stringResource(R.string.delete_account_title)) }, text = { Text(stringResource(R.string.delete_account_description)) }, dismissButton = { Button(onClick = { showRemoveAccDialog = false }) { Text(text = stringResource(R.string.cancel)) } }, confirmButton = { Button(onClick = { onRemoveAccountClick() showRemoveAccDialog = false }) { Text(text = stringResource(R.string.delete_account)) } }, onDismissRequest = { showRemoveAccDialog = false } ) } } @Composable fun AuthenticationButton( buttonText: Int, onGetCredentialResponse: (Credential) -> Unit ) { val context = LocalContext.current val coroutineScope = rememberCoroutineScope() val credentialManager = CredentialManager.create(context) Button( onClick = { val googleIdOption = GetGoogleIdOption.Builder() .setFilterByAuthorizedAccounts(false) .setServerClientId(context.getString(R.string.default_web_client_id)) .build() val request = GetCredentialRequest.Builder() .addCredentialOption(googleIdOption) .build() coroutineScope.launch { try { val result = credentialManager.getCredential( request = request, context = context ) onGetCredentialResponse(result.credential) } catch (e: GetCredentialException) { Log.d(ERROR_TAG, e.message.orEmpty()) } } }, colors = ButtonDefaults.buttonColors(containerColor = Purple40), modifier = Modifier .fillMaxWidth() .padding(16.dp, 0.dp) ) { Icon( painter = painterResource(id = R.drawable.google_g), modifier = Modifier.padding(horizontal = 16.dp), contentDescription = "Google logo" ) Text( text = stringResource(buttonText), fontSize = 16.sp, modifier = Modifier.padding(0.dp, 6.dp) ) } }
23
Swift
114
98
8e0e8bc0d62924c8f9176a7036f58d92572f6f54
7,650
firebase-video-samples
Apache License 2.0
android/src/main/java/com/google/samples/apps/iosched/gcm/command/NotificationCommand.kt
brentwatson
70,599,432
true
{"Gradle": 11, "Java Properties": 9, "Shell": 3, "Ignore List": 6, "Batchfile": 2, "Text": 10, "YAML": 2, "Markdown": 11, "HTML": 24, "CSS": 4, "JavaScript": 3, "Java": 206, "XML": 277, "JSON": 1, "Kotlin": 172, "SVG": 3, "Makefile": 2, "Ant Build System": 1, "INI": 7, "Maven POM": 2}
/* * Copyright 2014 Google Inc. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * 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.google.samples.apps.iosched.gcm.command import android.app.NotificationManager import android.app.PendingIntent import android.content.Context import android.content.Intent import android.net.Uri import android.support.v4.app.NotificationCompat import android.text.TextUtils import com.google.gson.Gson import com.google.samples.apps.iosched.R import com.google.samples.apps.iosched.gcm.GCMCommand import com.google.samples.apps.iosched.myschedule.MyScheduleActivity import com.google.samples.apps.iosched.settings.SettingsUtils import com.google.samples.apps.iosched.util.LogUtils.* import com.google.samples.apps.iosched.util.TimeUtils import com.google.samples.apps.iosched.util.UIUtils class NotificationCommand : GCMCommand() { private class NotificationCommandModel { internal var format: String? = null internal var audience: String? = null internal var minVersion: String? = null internal var maxVersion: String? = null internal var title: String? = null internal var message: String? = null internal var expiry: String? = null internal var dialogTitle: String? = null internal var dialogText: String? = null internal var dialogYes: String? = null internal var dialogNo: String? = null internal var url: String? = null } override fun execute(context: Context, type: String, payload: String?) { LOGI(TAG, "Received GCM message: " + type) LOGI(TAG, "Parsing GCM notification command: " + payload) val gson = Gson() val command: NotificationCommandModel? try { command = gson.fromJson(payload, NotificationCommandModel::class.java) if (command == null) { LOGE(TAG, "Failed to parse command (gson returned null).") return } LOGD(TAG, "Format: " + command.format!!) LOGD(TAG, "Audience: " + command.audience!!) LOGD(TAG, "Title: " + command.title!!) LOGD(TAG, "Message: " + command.message!!) LOGD(TAG, "Expiry: " + command.expiry!!) LOGD(TAG, "URL: " + command.url!!) LOGD(TAG, "Dialog title: " + command.dialogTitle!!) LOGD(TAG, "Dialog text: " + command.dialogText!!) LOGD(TAG, "Dialog yes: " + command.dialogYes!!) LOGD(TAG, "Dialog no: " + command.dialogNo!!) LOGD(TAG, "Min version code: " + command.minVersion!!) LOGD(TAG, "Max version code: " + command.maxVersion!!) } catch (ex: Exception) { ex.printStackTrace() LOGE(TAG, "Failed to parse GCM notification command.") return } LOGD(TAG, "Processing notification command.") processCommand(context, command) } private fun processCommand(context: Context, command: NotificationCommandModel) { // Check format if ("1.0.00" != command.format) { LOGW(TAG, "GCM notification command has unrecognized format: " + command.format!!) return } // Check app version if (!TextUtils.isEmpty(command.minVersion) || !TextUtils.isEmpty(command.maxVersion)) { LOGD(TAG, "Command has version range.") var minVersion = 0 var maxVersion = Integer.MAX_VALUE try { if (!TextUtils.isEmpty(command.minVersion)) { minVersion = Integer.parseInt(command.minVersion) } if (!TextUtils.isEmpty(command.maxVersion)) { maxVersion = Integer.parseInt(command.maxVersion) } LOGD(TAG, "Version range: $minVersion - $maxVersion") val pinfo = context.packageManager.getPackageInfo(context.packageName, 0) LOGD(TAG, "My version code: " + pinfo.versionCode) if (pinfo.versionCode < minVersion) { LOGD(TAG, "Skipping command because our version is too old, " + pinfo.versionCode + " < " + minVersion) return } if (pinfo.versionCode > maxVersion) { LOGD(TAG, "Skipping command because our version is too new, " + pinfo.versionCode + " > " + maxVersion) return } } catch (ex: NumberFormatException) { LOGE(TAG, "Version spec badly formatted: min=" + command.minVersion + ", max=" + command.maxVersion) return } catch (ex: Exception) { LOGE(TAG, "Unexpected problem doing version check.", ex) return } } // Check if we are the right audience LOGD(TAG, "Checking audience: " + command.audience!!) if ("remote" == command.audience) { if (SettingsUtils.isAttendeeAtVenue(context)) { LOGD(TAG, "Ignoring notification because audience is remote and attendee is on-site") return } else { LOGD(TAG, "Relevant (attendee is remote).") } } else if ("local" == command.audience) { if (!SettingsUtils.isAttendeeAtVenue(context)) { LOGD(TAG, "Ignoring notification because audience is on-site and attendee is remote.") return } else { LOGD(TAG, "Relevant (attendee is local).") } } else if ("all" == command.audience) { LOGD(TAG, "Relevant (audience is 'all').") } else { LOGE(TAG, "Invalid audience on GCM notification command: " + command.audience!!) return } // Check if it expired val expiry = if (command.expiry == null) null else TimeUtils.parseTimestamp(command.expiry!!) if (expiry == null) { LOGW(TAG, "Failed to parse expiry field of GCM notification command: " + command.expiry!!) return } else if (expiry.time < UIUtils.getCurrentTime(context)) { LOGW(TAG, "Got expired GCM notification command. Expiry: " + expiry.toString()) return } else { LOGD(TAG, "Message is still valid (expiry is in the future: " + expiry.toString() + ")") } // decide the intent that will be fired when the user clicks the notification val intent: Intent if (TextUtils.isEmpty(command.dialogText)) { // notification leads directly to the URL, no dialog if (TextUtils.isEmpty(command.url)) { intent = Intent(context, MyScheduleActivity::class.java).setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP or Intent.FLAG_ACTIVITY_SINGLE_TOP) } else { intent = Intent(Intent.ACTION_VIEW, Uri.parse(command.url)) } } else { // use a dialog intent = Intent(context, MyScheduleActivity::class.java).setFlags( Intent.FLAG_ACTIVITY_CLEAR_TOP or Intent.FLAG_ACTIVITY_SINGLE_TOP or Intent.FLAG_ACTIVITY_CLEAR_TASK) intent.putExtra(MyScheduleActivity.EXTRA_DIALOG_TITLE, if (command.dialogTitle == null) "" else command.dialogTitle) intent.putExtra(MyScheduleActivity.EXTRA_DIALOG_MESSAGE, if (command.dialogText == null) "" else command.dialogText) intent.putExtra(MyScheduleActivity.EXTRA_DIALOG_YES, if (command.dialogYes == null) "OK" else command.dialogYes) intent.putExtra(MyScheduleActivity.EXTRA_DIALOG_NO, if (command.dialogNo == null) "" else command.dialogNo) intent.putExtra(MyScheduleActivity.EXTRA_DIALOG_URL, if (command.url == null) "" else command.url) } val title = if (TextUtils.isEmpty(command.title)) context.getString(R.string.app_name) else command.title val message = if (TextUtils.isEmpty(command.message)) "" else command.message // fire the notification (context.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager).notify(0, NotificationCompat.Builder(context).setWhen(System.currentTimeMillis()).setSmallIcon(R.drawable.ic_stat_notification).setTicker(command.message).setContentTitle(title).setContentText(message).setContentIntent(PendingIntent.getActivity(context, 0, intent, PendingIntent.FLAG_CANCEL_CURRENT))//.setColor(context.getResources().getColor(R.color.theme_primary)) // Note: setColor() is available in the support lib v21+. // We commented it out because we want the source to compile // against support lib v20. If you are using support lib // v21 or above on Android L, uncomment this line. .setAutoCancel(true).build()) } companion object { private val TAG = makeLogTag("NotificationCommand") } }
0
Kotlin
0
0
e6f4a8ad4d1c84f55bfb5c3140c171af1792343b
9,731
iosched
Apache License 2.0
bookingservice-mappers/src/main/kotlin/mapper/MapperSlotFromTransport.kt
akopovab
638,664,041
false
null
package ru.otuskotlin.public.bookingservice.mappers.mapper import ru.otuskotlin.public.bookingservice.api.models.* import ru.otuskotlin.public.bookingservice.common.context.Impl.BsSlotContext import ru.otuskotlin.public.bookingservice.common.models.BsRequestId import ru.otuskotlin.public.bookingservice.common.models.meeting.BsEmployeeId import ru.otuskotlin.public.bookingservice.common.models.slot.BsSlotCommand import ru.otuskotlin.public.bookingservice.mappers.exception.UnknownRequestClass fun BsSlotContext.fromTransportSlot(request: ISlotRequest) = when (request) { is SlotSearchRequest -> fromTransport(request) else -> throw UnknownRequestClass(request.javaClass) } private fun String?.toEmployeeId() = this?.let { BsEmployeeId(it) } ?: BsEmployeeId.NONE fun BsSlotContext.fromTransport(request: SlotSearchRequest) { command = BsSlotCommand.SEARCH requestId = request.requestId() slotRequest = request.employeeId.toEmployeeId() workMode = request.debug.transportToWorkMode() stub = request.debug.transportToStubCase() } private fun ISlotRequest.requestId() = this.requestId?.let { BsRequestId(it) } ?: BsRequestId.NONE
1
Kotlin
0
0
5fcf69608ec26f746e13c006420d5f353d391ffe
1,162
ok-bookingservice
Apache License 2.0
src/cds/src/main/kotlin/org/icpclive/cds/cms/model/Team.kt
icpc
447,849,919
false
{"Kotlin": 494337, "JavaScript": 246365, "HTML": 76741, "TypeScript": 30915, "Python": 2450, "SCSS": 1034, "CSS": 466, "Dockerfile": 406, "Shell": 344, "Batchfile": 199}
package org.icpclive.cds.cms.model import kotlinx.serialization.Serializable @Serializable internal data class Team(val name: String)
17
Kotlin
11
36
e3cb0165d86f7dc0d1232cb35988743d44fe80c9
135
live-v3
MIT License
src/commonMain/kotlin/com/ditchoom/mqtt5/controlpacket/properties/ServerReference.kt
DitchOoM
422,091,819
false
null
package com.ditchoom.mqtt5.controlpacket.properties import com.ditchoom.buffer.WriteBuffer data class ServerReference(val otherServer: String) : Property(0x1C, Type.UTF_8_ENCODED_STRING) { override fun write(buffer: WriteBuffer): Int = write(buffer, otherServer) override fun size(): Int = size(otherServer) }
0
Kotlin
0
0
eb45a9961e1873dd4bd3abb7446d25f96e14f7cf
324
mqtt-5-models
Apache License 2.0
src/main/kotlin/com/fluxtah/ask/app/commanding/commands/ListRunSteps.kt
fluxtah
794,032,032
false
null
/* * Copyright (c) 2024 <NAME> * Released under the MIT license * https://opensource.org/licenses/MIT */ package com.fluxtah.ask.app.commanding.commands import com.fluxtah.ask.api.clients.openai.assistants.AssistantsApi import com.fluxtah.ask.api.clients.openai.assistants.model.AssistantRunStepList import com.fluxtah.ask.app.UserProperties import kotlinx.serialization.encodeToString class ListRunSteps(private val assistantsApi: AssistantsApi, private val userProperties: UserProperties) : Command() { override val requiresApiKey: Boolean = true override suspend fun execute() { val threadId = userProperties.getThreadId() if (threadId.isEmpty()) { println("You need to create a thread first. Use /thread-new") return } val runId = userProperties.getRunId() if (runId.isEmpty()) { println("No last run") return } println(JSON.encodeToString<AssistantRunStepList>(assistantsApi.runs.listRunSteps(threadId, runId))) } }
4
null
0
8
c59cfeee7b7034e08b64a0bf31d770b0b123f875
1,048
ask
MIT License
app/src/main/java/com/wavesplatform/wallet/v2/injection/module/NetworkModule.kt
wavesplatform
98,419,999
false
null
/* * Created by Eduard Zaydel on 1/4/2019 * Copyright © 2019 Waves Platform. All rights reserved. */ package com.wavesplatform.wallet.v2.injection.module import android.content.Context import android.util.Log import com.google.gson.FieldNamingPolicy import com.google.gson.Gson import com.google.gson.GsonBuilder import com.ihsanbal.logging.Level import com.ihsanbal.logging.LoggingInterceptor import com.wavesplatform.wallet.BuildConfig import com.wavesplatform.wallet.v2.data.Constants import com.wavesplatform.wallet.v2.data.manager.ErrorManager import com.wavesplatform.wallet.v2.data.remote.* import com.wavesplatform.wallet.v2.injection.qualifier.ApplicationContext import com.wavesplatform.wallet.v2.util.EnvironmentManager import com.wavesplatform.wallet.v2.util.PrefsUtil import com.wavesplatform.wallet.v2.util.formatBaseUrl import dagger.Module import dagger.Provides import okhttp3.Cache import okhttp3.Interceptor import okhttp3.OkHttpClient import ren.yale.android.retrofitcachelibrx2.RetrofitCache import ren.yale.android.retrofitcachelibrx2.intercept.CacheForceInterceptorNoNet import ren.yale.android.retrofitcachelibrx2.intercept.CacheInterceptorOnNet import retrofit2.Retrofit import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory import retrofit2.converter.gson.GsonConverterFactory import retrofit2.converter.scalars.ScalarsConverterFactory import java.io.File import java.util.concurrent.TimeUnit import javax.inject.Named import javax.inject.Singleton @Module class NetworkModule { @Provides @Singleton internal fun provideCache(@ApplicationContext context: Context): Cache { val cacheSize = 200 * 1024 * 1024 val cacheDirectory = File(context.cacheDir, "httpcache") return Cache(cacheDirectory, cacheSize.toLong()) } @Provides @Singleton @Named("ReceivedCookiesInterceptor") internal fun receivedCookiesInterceptor(prefsUtil: PrefsUtil): Interceptor { return Interceptor { chain -> val originalResponse = chain.proceed(chain.request()) if (originalResponse.request().url().url().toString() .contains(EnvironmentManager.servers.nodeUrl) && originalResponse.headers("Set-Cookie").isNotEmpty() && prefsUtil.getGlobalValue(PrefsUtil.KEY_GLOBAL_NODE_COOKIES).isEmpty()) { val cookies = originalResponse.headers("Set-Cookie") .toHashSet() prefsUtil.setGlobalValue(PrefsUtil.KEY_GLOBAL_NODE_COOKIES, cookies) } originalResponse } } @Provides @Singleton @Named("AddCookiesInterceptor") internal fun addCookiesInterceptor(prefsUtil: PrefsUtil): Interceptor { return Interceptor { chain -> val cookies = prefsUtil.getGlobalValue(PrefsUtil.KEY_GLOBAL_NODE_COOKIES) if (cookies.isNotEmpty() && chain.request().url().url().toString() .contains(EnvironmentManager.servers.nodeUrl)) { val builder = chain.request().newBuilder() cookies.forEach { builder.addHeader("Cookie", it) } chain.proceed(builder.build()) } else { chain.proceed(chain.request()) } } } @Singleton @Provides internal fun provideOkHttpClient( cache: Cache, @Named("timeout") timeout: Int, @Named("ReceivedCookiesInterceptor") receivedCookiesInterceptor: Interceptor, @Named("AddCookiesInterceptor") addCookiesInterceptor: Interceptor ): OkHttpClient { return OkHttpClient.Builder() .cache(cache) .readTimeout(timeout.toLong(), TimeUnit.SECONDS) .writeTimeout(timeout.toLong(), TimeUnit.SECONDS) .addInterceptor(receivedCookiesInterceptor) .addInterceptor(addCookiesInterceptor) .addInterceptor(CacheForceInterceptorNoNet()) .addInterceptor(EnvironmentManager.createGateWayHostInterceptor()) .addNetworkInterceptor(CacheInterceptorOnNet()) .addInterceptor(LoggingInterceptor.Builder() .loggable(BuildConfig.DEBUG) .setLevel(Level.BASIC) .log(Log.INFO) .request("Request") .response("Response") .build()) .build() } @Provides @Singleton internal fun provideGson(): Gson { return GsonBuilder() .setLenient() .setPrettyPrinting() .setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES) // if filed status_code need as statusCode .setDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'") .create() } @Singleton @Named("GatewayRetrofit") @Provides internal fun provideGatewayRetrofit(gson: Gson, httpClient: OkHttpClient, errorManager: ErrorManager): Retrofit { val url = if (EnvironmentManager.servers.gatewayUrl.isNotEmpty()) EnvironmentManager.servers.gatewayUrl else EnvironmentManager.getDefaultConfig()?.servers?.gatewayUrl ?: "" val retrofit = Retrofit.Builder() .baseUrl(url.formatBaseUrl()) .client(httpClient) .addConverterFactory(GsonConverterFactory.create(gson)) .addCallAdapterFactory(RxJava2CallAdapterFactory.create()) .build() RetrofitCache.getInstance().addRetrofit(retrofit) return retrofit } @Singleton @Named("GithubRetrofit") @Provides internal fun provideGithubRetrofit(gson: Gson, httpClient: OkHttpClient, errorManager: ErrorManager): Retrofit { val retrofit = Retrofit.Builder() .baseUrl(Constants.URL_GITHUB_PROXY.formatBaseUrl()) .client(httpClient) .addConverterFactory(ScalarsConverterFactory.create()) .addConverterFactory(GsonConverterFactory.create(gson)) .addCallAdapterFactory(RxJava2CallAdapterFactory.create()) .build() RetrofitCache.getInstance().addRetrofit(retrofit) return retrofit } @Singleton @Named("CoinomatRetrofit") @Provides internal fun provideCoinomatRetrofit(gson: Gson, httpClient: OkHttpClient, errorManager: ErrorManager): Retrofit { val retrofit = Retrofit.Builder() .baseUrl(Constants.URL_COINOMAT.formatBaseUrl()) .client(httpClient) .addConverterFactory(ScalarsConverterFactory.create()) .addConverterFactory(GsonConverterFactory.create(gson)) .addCallAdapterFactory(RxJava2CallAdapterFactory.create()) .build() RetrofitCache.getInstance().addRetrofit(retrofit) return retrofit } @Singleton @Provides internal fun provideGithubService(@Named("GithubRetrofit") retrofit: Retrofit): GithubService { return retrofit.create(GithubService::class.java) } @Singleton @Provides internal fun provideCoinomatService(@Named("CoinomatRetrofit") retrofit: Retrofit): CoinomatService { return retrofit.create(CoinomatService::class.java) } @Singleton @Provides internal fun provideGatewayService(@Named("GatewayRetrofit") retrofit: Retrofit): GatewayService { return retrofit.create(GatewayService::class.java) } @Named("timeout") @Provides internal fun provideTimeoutConstant(): Int { return 30 } }
2
null
52
55
5f4106576dc4fe377a355d045f638e7469cd6abe
7,727
WavesWallet-android
MIT License
ToolBarBorder/src/main/kotlin/example/App.kt
aterai
158,348,575
false
{"Kotlin": 4358653, "JavaScript": 241284, "Java": 14467, "HTML": 378}
package example import java.awt.* import javax.swing.* import javax.swing.plaf.metal.MetalBorders fun makeUI(): Component { val toolBar1 = object : JToolBar("Customized ToolBarBorder") { override fun updateUI() { super.updateUI() border = ToolBarDragBorder() } }.also { it.add(JLabel("<- Customized Border")) it.addSeparator() it.add(JRadioButton("JRadioButton")) it.add(JToggleButton("JToggleButton")) } val toolBar2 = JToolBar("default").also { it.add(JLabel("<- Default Border")) it.addSeparator() it.add(JCheckBox("JCheckBox")) it.add(JButton("JButton")) } return JPanel(BorderLayout()).also { it.add(toolBar1, BorderLayout.NORTH) it.add(toolBar2, BorderLayout.SOUTH) it.add(JScrollPane(JTextArea())) val mb = JMenuBar() mb.add(LookAndFeelUtils.createLookAndFeelMenu()) EventQueue.invokeLater { it.rootPane.jMenuBar = mb } it.preferredSize = Dimension(320, 240) } } private class ToolBarDragBorder : MetalBorders.ToolBarBorder() { override fun paintBorder( c: Component, g: Graphics, x: Int, y: Int, w: Int, h: Int, ) { val tb = c as? JToolBar ?: return if (tb.isFloatable) { if (tb.orientation == HORIZONTAL) { val cy = (h - DRAG_ICON.iconHeight) / 2 DRAG_ICON.paintIcon(c, g, x, y + cy) } else { // vertical super.paintBorder(c, g, x, y, w, h) } } } companion object { private val DRAG_ICON = ToolBarDragIcon() } } private class ToolBarDragIcon : Icon { override fun paintIcon( c: Component, g: Graphics, x: Int, y: Int, ) { val g2 = g.create() as? Graphics2D ?: return g2.translate(x, y) g2.paint = Color.GRAY val x2 = iconWidth / 2 - 1 val y2 = iconHeight / 2 - 1 g2.fillRect(x2, y2 - 6, 2, 2) g2.fillRect(x2, y2 - 2, 2, 2) g2.fillRect(x2, y2 + 2, 2, 2) g2.fillRect(x2, y2 + 6, 2, 2) g2.dispose() } override fun getIconWidth() = 14 override fun getIconHeight() = 16 } private object LookAndFeelUtils { private var lookAndFeel = UIManager.getLookAndFeel().javaClass.name fun createLookAndFeelMenu(): JMenu { val menu = JMenu("LookAndFeel") val buttonGroup = ButtonGroup() for (info in UIManager.getInstalledLookAndFeels()) { val b = JRadioButtonMenuItem(info.name, info.className == lookAndFeel) initLookAndFeelAction(info, b) menu.add(b) buttonGroup.add(b) } return menu } fun initLookAndFeelAction( info: UIManager.LookAndFeelInfo, b: AbstractButton, ) { val cmd = info.className b.text = info.name b.actionCommand = cmd b.hideActionText = true b.addActionListener { setLookAndFeel(cmd) } } @Throws( ClassNotFoundException::class, InstantiationException::class, IllegalAccessException::class, UnsupportedLookAndFeelException::class, ) private fun setLookAndFeel(newLookAndFeel: String) { val oldLookAndFeel = lookAndFeel if (oldLookAndFeel != newLookAndFeel) { UIManager.setLookAndFeel(newLookAndFeel) lookAndFeel = newLookAndFeel updateLookAndFeel() } } private fun updateLookAndFeel() { for (window in Window.getWindows()) { SwingUtilities.updateComponentTreeUI(window) } } } fun main() { EventQueue.invokeLater { runCatching { UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()) }.onFailure { it.printStackTrace() Toolkit.getDefaultToolkit().beep() } JFrame().apply { defaultCloseOperation = WindowConstants.EXIT_ON_CLOSE contentPane.add(makeUI()) pack() setLocationRelativeTo(null) isVisible = true } } }
0
Kotlin
6
28
433dfe2513f1016eeb1fdc0c42551623a8cfaadf
3,729
kotlin-swing-tips
MIT License
gradle-plugin/src/main/kotlin/dev/schlaubi/mikbot/gradle/extension/Extensions.kt
DRSchlaubi
409,332,765
false
null
package dev.schlaubi.mikbot.gradle.extension import dev.schlaubi.mikbot.gradle.BuildRepositoryExtension import org.gradle.api.Project import org.gradle.api.plugins.ExtensionAware import org.gradle.api.plugins.ExtensionContainer const val pluginExtensionName = "mikbotPlugin" private const val pluginPublishingExtensionName = "pluginPublishing" // This is just there for usage in the Plugin, users of the plugin should use Gradle's generated // accessors internal val Project.mikbotPluginExtension: PluginExtension get() = findExtension(pluginExtensionName) ?: error("Missing MikBot plugin in :path") // This is just there for usage in the Plugin, users of the plugin should use Gradle's generated accessors internal val Project.pluginPublishingExtension: BuildRepositoryExtension get() = findExtension(pluginPublishingExtensionName) ?: error("Missing MikBot plugin in :path") fun Project.createExtensions() { extensions.create<PluginExtension>(pluginExtensionName).apply { if (parent != null) { val base = rootProject.findExtension<PluginExtension>(pluginExtensionName) ?: return@apply pluginId.convention(base.pluginId) requires.convention(base.requires) description.convention(base.description) provider.convention(base.provider) license.convention(base.license) ignoreDependencies.convention(base.ignoreDependencies) pluginMainFileLocation.convention(base.pluginMainFileLocation) bundle.convention(base.bundle) enableKordexProcessor .convention(base.enableKordexProcessor.convention(false)) .convention(false) } } extensions.create<BuildRepositoryExtension>(pluginPublishingExtensionName).apply { if (parent != null) { val base = rootProject.findExtension<BuildRepositoryExtension>(pluginPublishingExtensionName) ?: return@apply targetDirectory.convention(base.targetDirectory) currentRepository.convention(base.currentRepository) repositoryUrl.convention(base.repositoryUrl) projectUrl.convention(base.projectUrl) } } } private inline fun <reified T> ExtensionContainer.create(name: String) = create(name, T::class.java) internal inline fun <reified T> ExtensionAware.findExtension(name: String) = extensions.findByName(name) as T?
17
null
12
36
5b57b3e6e8a06324da478231f6bd7035a0c1feb2
2,433
mikbot
MIT License
app/src/main/java/com/yenaly/han1meviewer/util/Versions.kt
YenalyLiew
524,046,895
false
{"Kotlin": 721116, "Java": 88900}
package com.yenaly.han1meviewer.util import android.content.Context import android.content.Intent import android.graphics.Typeface import androidx.appcompat.app.AlertDialog import androidx.core.content.FileProvider import com.google.android.material.dialog.MaterialAlertDialogBuilder import com.itxca.spannablex.spannable import com.yenaly.han1meviewer.BuildConfig import com.yenaly.han1meviewer.FILE_PROVIDER_AUTHORITY import com.yenaly.han1meviewer.R import com.yenaly.han1meviewer.logic.model.github.Latest import com.yenaly.han1meviewer.worker.HUpdateWorker import com.yenaly.yenaly_libs.utils.showShortToast import java.io.File fun checkNeedUpdate(versionName: String): Boolean { val latestVersionCode = versionName.substringAfter("+", "").toIntOrNull() ?: Int.MAX_VALUE return BuildConfig.VERSION_CODE < latestVersionCode } fun isPreReleaseVersion(versionName: String): Boolean { return "pre" in versionName } suspend fun Context.showUpdateDialog(latest: Latest) { val activity = this.toComponentActivity() val spannable = spannable { getString(R.string.new_version_found).span { style(Typeface.BOLD) relativeSize(1.2f) } newline() latest.version.text() newline() getString(R.string.update_content).span { style(Typeface.BOLD) relativeSize(1.2f) } newline() latest.changelog.text() } val dialog = MaterialAlertDialogBuilder(activity).setTitle(R.string.new_version_found) .setMessage(spannable) .setCancelable(false).create() val res = dialog.await( positiveText = getString(R.string.update), negativeText = getString(R.string.cancel), ) if (res == AlertDialog.BUTTON_POSITIVE) { requestPostNotificationPermission() HUpdateWorker.enqueue(this, latest.downloadLink) showShortToast(R.string.update_download_background) } dialog.dismiss() } suspend fun Context.installApkPackage(file: File) { val canInstall = requestInstallPermission() if (canInstall) { val uri = FileProvider.getUriForFile(this, FILE_PROVIDER_AUTHORITY, file) val intent = Intent(Intent.ACTION_VIEW).apply { addFlags(Intent.FLAG_ACTIVITY_NEW_TASK) addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION) setDataAndType(uri, "application/vnd.android.package-archive") } startActivity(intent) } }
15
Kotlin
54
815
3db1537f3893a57d68af11e02818d39dc947180c
2,483
Han1meViewer
Apache License 2.0
goldeneye/src/main/java/co/infinum/goldeneye/GoldenEye1Impl.kt
infinum
54,713,189
false
null
@file:Suppress("DEPRECATION") package co.infinum.goldeneye import android.annotation.SuppressLint import android.app.Activity import android.graphics.Bitmap import android.hardware.Camera import android.os.Build import android.view.TextureView import co.infinum.goldeneye.config.CameraConfig import co.infinum.goldeneye.config.CameraInfo import co.infinum.goldeneye.config.camera1.* import co.infinum.goldeneye.extensions.ifNotNull import co.infinum.goldeneye.extensions.onSurfaceUpdate import co.infinum.goldeneye.gesture.GestureManager import co.infinum.goldeneye.gesture.ZoomHandlerImpl import co.infinum.goldeneye.gesture.camera1.FocusHandlerImpl import co.infinum.goldeneye.models.CameraApi import co.infinum.goldeneye.models.CameraProperty import co.infinum.goldeneye.models.CameraState import co.infinum.goldeneye.models.Facing import co.infinum.goldeneye.recorders.PictureRecorder import co.infinum.goldeneye.recorders.VideoRecorder import co.infinum.goldeneye.utils.AsyncUtils import co.infinum.goldeneye.utils.CameraUtils import co.infinum.goldeneye.utils.Intrinsics import co.infinum.goldeneye.utils.LogDelegate import co.infinum.goldeneye.utils.LogDelegate.log import java.io.File internal class GoldenEye1Impl @JvmOverloads constructor( private val activity: Activity, private val advancedFeaturesEnabled: Boolean, private val onZoomChangedCallback: OnZoomChangedCallback?, private val onFocusChangedCallback: OnFocusChangedCallback?, private val pictureTransformation: PictureTransformation?, logger: Logger? = null ) : BaseGoldenEyeImpl(CameraApi.VERSION_1) { private var camera: Camera? = null private var textureView: TextureView? = null private var gestureHandler: GestureManager? = null private var videoRecorder: VideoRecorder? = null private var pictureRecorder: PictureRecorder? = null private var configUpdateHandler: ConfigUpdateHandler? = null private val onConfigUpdateListener: (CameraProperty) -> Unit = { configUpdateHandler?.onPropertyUpdated(it) } private val _availableCameras = mutableListOf<Camera1ConfigImpl>() override val availableCameras: List<CameraInfo> = _availableCameras private lateinit var _config: Camera1ConfigImpl override val config: CameraConfig? get() = if (isConfigAvailable) _config else null init { LogDelegate.logger = logger initAvailableCameras() } override fun open(textureView: TextureView, cameraInfo: CameraInfo, callback: InitCallback) { Intrinsics.checkCameraPermission(activity) state = CameraState.INITIALIZING AsyncUtils.startBackgroundThread() try { releaseInternal() _config = _availableCameras.first { it.id == cameraInfo.id } openCamera(_config) state = CameraState.READY initGestureManager(camera, textureView) initRecorders(camera) initConfigUpdateHandler(camera, textureView) callback.onReady(_config) this.textureView = textureView textureView.onSurfaceUpdate( onAvailable = { startPreview(callback) }, onSizeChanged = { startPreview() } ) } catch (t: Throwable) { releaseInternal() callback.onError(t) } } override fun release() { releaseInternal() AsyncUtils.stopBackgroundThread() } private fun releaseInternal() { state = CameraState.CLOSED videoRecorder?.release() pictureRecorder?.release() gestureHandler?.release() gestureHandler = null videoRecorder = null pictureRecorder = null try { camera?.stopPreview() camera?.release() } catch (t: Throwable) { log("Failed to release camera.", t) } finally { camera = null } } override fun takePicture(callback: PictureCallback) { if (state != CameraState.ACTIVE) { callback.onError(CameraNotActiveException()) return } state = CameraState.TAKING_PICTURE pictureRecorder?.takePicture(object : PictureCallback() { override fun onPictureTaken(picture: Bitmap) { resetCameraPreview() callback.onPictureTaken(picture) } override fun onError(t: Throwable) { resetCameraPreview() callback.onError(t) } private fun resetCameraPreview() { state = CameraState.ACTIVE camera?.startPreview() } }) } override fun startRecording(file: File, callback: VideoCallback) { if (state != CameraState.ACTIVE) { callback.onError(CameraNotActiveException()) return } state = CameraState.RECORDING_VIDEO applyConfig() startPreview() camera?.unlock() videoRecorder?.startRecording(file, object : VideoCallback { override fun onVideoRecorded(file: File) { resetCameraPreview() callback.onVideoRecorded(file) } override fun onError(t: Throwable) { resetCameraPreview() callback.onError(t) } @SuppressLint("MissingPermission") private fun resetCameraPreview() { state = CameraState.CLOSED open(textureView!!, _config, onError = {}) } }) } override fun stopRecording() { videoRecorder?.stopRecording() } @Throws(CameraFailedToOpenException::class) private fun initConfigUpdateHandler(camera: Camera?, textureView: TextureView?) { if (camera == null || textureView == null) throw CameraFailedToOpenException this.configUpdateHandler = ConfigUpdateHandler( camera = camera, config = _config, restartPreview = { textureView.onSurfaceUpdate( onAvailable = { startPreview() }, onSizeChanged = { startPreview() } ) } ) } @Throws(CameraFailedToOpenException::class) private fun initGestureManager(camera: Camera?, textureView: TextureView?) { if (camera == null || textureView == null) throw CameraFailedToOpenException val zoomHandler = ZoomHandlerImpl( activity = activity, config = _config ) val focusHandler = FocusHandlerImpl( activity = activity, camera = camera, textureView = textureView, config = _config, onFocusChanged = { onFocusChangedCallback?.onFocusChanged(it) } ) this.gestureHandler = GestureManager( activity = activity, textureView = textureView, zoomHandler = zoomHandler, focusHandler = focusHandler ) } @Throws(CameraFailedToOpenException::class) private fun initRecorders(camera: Camera?) { if (camera == null) throw CameraFailedToOpenException this.videoRecorder = VideoRecorder(activity, camera, _config) this.pictureRecorder = PictureRecorder(activity, camera, _config, pictureTransformation) } @Throws(Throwable::class) private fun openCamera(config: Camera1ConfigImpl) { Camera.open(config.id.toInt())?.also { this.camera = it _config = config _config.characteristics = it.parameters } } private fun startPreview(initCallback: InitCallback? = null) { try { ifNotNull(camera, textureView) { camera, textureView -> camera.apply { stopPreview() setPreviewTexture(textureView.surfaceTexture) applyConfig() textureView.setTransform(CameraUtils.calculateTextureMatrix(activity, textureView, _config)) setDisplayOrientation(CameraUtils.calculateDisplayOrientation(activity, _config)) startPreview() } state = CameraState.ACTIVE initCallback?.onActive() } } catch (t: Throwable) { releaseInternal() initCallback?.onError(t) } } private fun applyConfig() { camera?.apply { parameters = parameters.apply { val pictureSize = _config.pictureSize setPictureSize(pictureSize.width, pictureSize.height) val previewSize = _config.previewSize setPreviewSize(previewSize.width, previewSize.height) jpegQuality = _config.pictureQuality if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH_MR1 && _config.isVideoStabilizationSupported) { videoStabilization = _config.videoStabilizationEnabled } if (_config.supportedFocusModes.contains(_config.focusMode)) { focusMode = _config.focusMode.toCamera1() } if (_config.supportedFlashModes.contains(_config.flashMode)) { flashMode = _config.flashMode.toCamera1() } if (_config.supportedAntibandingModes.contains(_config.antibandingMode)) { antibanding = _config.antibandingMode.toCamera1() } if (_config.supportedColorEffectModes.contains(_config.colorEffectMode)) { colorEffect = _config.colorEffectMode.toCamera1() } if (_config.supportedWhiteBalanceModes.contains(_config.whiteBalanceMode)) { whiteBalance = _config.whiteBalanceMode.toCamera1() } if (parameters.isZoomSupported) { zoom = zoomRatios.indexOf(_config.zoom) } } } } private fun initAvailableCameras() { for (id in 0 until Camera.getNumberOfCameras()) { val info = Camera.CameraInfo() Camera.getCameraInfo(id, info) val facing = if (info.facing == Camera.CameraInfo.CAMERA_FACING_BACK) Facing.BACK else Facing.FRONT val cameraInfo = object : CameraInfo { override val id = id.toString() override val orientation = info.orientation override val facing = facing } val videoConfig = VideoConfigImpl(id.toString(), onConfigUpdateListener) _availableCameras.add( Camera1ConfigImpl( cameraInfo = cameraInfo, videoConfig = videoConfig, basicFeatureConfig = BasicFeatureConfigImpl(onConfigUpdateListener), advancedFeatureConfig = AdvancedFeatureConfigImpl(advancedFeaturesEnabled, onConfigUpdateListener), sizeConfig = SizeConfigImpl(cameraInfo, videoConfig, onConfigUpdateListener), zoomConfig = ZoomConfigImpl(onConfigUpdateListener, onZoomChangedCallback) ) ) } } }
15
Kotlin
52
374
5f9a7106043b68013aa65c65f8e552f64a46e8c5
11,297
Android-GoldenEye
Apache License 2.0
examples/src/test/kotlin/examples/onnx/cv/OnnxResNetTestSuite.kt
JetBrains
249,948,572
false
null
/* * Copyright 2020 JetBrains s.r.o. and Kotlin Deep Learning project contributors. All Rights Reserved. * Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE.txt file. */ package examples.onnx.cv import examples.onnx.cv.custom.resnet50CustomPrediction import examples.onnx.cv.custom.resnet50additionalTraining import examples.onnx.cv.efficicentnet.efficientNet4LitePrediction import examples.onnx.cv.resnet.* import examples.onnx.cv.runImageRecognitionPrediction import org.jetbrains.kotlinx.dl.api.inference.onnx.ONNXModels import org.junit.jupiter.api.Test class OnnxResNetTestSuite { @Test fun resnet18predictionTest() { resnet18prediction() } @Test fun resnet18easyPredictionTest() { resnet18easyPrediction() } @Test fun resnet18v2predictionTest() { runImageRecognitionPrediction(ONNXModels.CV.ResNet18v2()) } @Test fun resnet34predictionTest() { runImageRecognitionPrediction(ONNXModels.CV.ResNet34()) } @Test fun resnet34v2predictionTest() { runImageRecognitionPrediction(ONNXModels.CV.ResNet34v2()) } @Test fun resnet50predictionTest() { runImageRecognitionPrediction(ONNXModels.CV.ResNet50()) } @Test fun resnet50v2predictionTest() { runImageRecognitionPrediction(ONNXModels.CV.ResNet50v2()) } @Test fun resnet50additionalTrainingTest() { resnet50additionalTraining() } @Test fun resnet50CustomPredictionTest() { resnet50CustomPrediction() } @Test fun resnet101predictionTest() { runImageRecognitionPrediction(ONNXModels.CV.ResNet101()) } @Test fun resnet101v2predictionTest() { runImageRecognitionPrediction(ONNXModels.CV.ResNet101v2()) } @Test fun resnet152predictionTest() { runImageRecognitionPrediction(ONNXModels.CV.ResNet152()) } @Test fun resnet152v2predictionTest() { runImageRecognitionPrediction(ONNXModels.CV.ResNet152v2()) } @Test fun efficientNet4LitePredictionTest(){ efficientNet4LitePrediction() } }
81
null
79
806
efaa1ebdf7bf9a131826d3ded42e1eb178e4fd19
2,168
KotlinDL
Apache License 2.0