path
stringlengths
4
280
owner
stringlengths
2
39
repo_id
int64
21.1k
879M
is_fork
bool
2 classes
languages_distribution
stringlengths
13
1.95k
content
stringlengths
7
482k
issues
int64
0
13.9k
main_language
stringclasses
121 values
forks
stringlengths
1
5
stars
int64
0
111k
commit_sha
stringlengths
40
40
size
int64
7
482k
name
stringlengths
1
100
license
stringclasses
93 values
app/src/main/java/com/renaisn/reader/ui/association/VerificationCodeActivity.kt
RenaisnNce
598,532,496
false
null
package com.renaisn.reader.ui.association import android.os.Bundle import com.renaisn.reader.base.BaseActivity import com.renaisn.reader.databinding.ActivityTranslucenceBinding import com.renaisn.reader.utils.showDialogFragment import com.renaisn.reader.utils.viewbindingdelegate.viewBinding /** * 验证码 */ class VerificationCodeActivity : BaseActivity<ActivityTranslucenceBinding>() { override val binding by viewBinding(ActivityTranslucenceBinding::inflate) override fun onActivityCreated(savedInstanceState: Bundle?) { intent.getStringExtra("imageUrl")?.let { val sourceOrigin = intent.getStringExtra("sourceOrigin") val sourceName = intent.getStringExtra("sourceName") showDialogFragment( VerificationCodeDialog(it, sourceOrigin, sourceName) ) } ?: finish() } }
1
Kotlin
1
4
4ac03e214e951f7f4f337d4da1f7e39fa715d1c0
866
Renaisn_Android
MIT License
kt-ascii-table/src/main/kotlin/team/yi/tools/ktables/Table.kt
ymind
774,842,109
false
{"Kotlin": 139136, "Mustache": 968}
package team.yi.tools.ktables class Table( val header: Header, val rows: List<Row>, val footer: Footer? = null, ) { private val renderer = TableRenderer(this) fun build(): String { return buildString { renderer.render(this) } } private fun maxLen(columnIndex: Int): Int { return rows.maxOf { row -> maxOf( row.cells[columnIndex].width, header.cells[columnIndex].width, ) } } internal val columnWidthMap: Map<Int, Int> by lazy { List(header.cells.size) { index -> Pair(index, maxLen(index)) }.toMap() } internal val footerWidth: Int by lazy { maxOf( footer?.width ?: 0, List(header.cells.size) { index -> columnWidthMap.getValue(index) + 3 }.sum() - 3, ) } } fun calcTextWidth(value: String): Int { return value.map { if (it.toString().toByteArray().size > 1) { 2 } else { 1 } }.sum() }
0
Kotlin
0
0
80d77118f68903939ee3f83db6abc1a7b8ade1de
1,092
rsql
MIT License
lib/src/main/kotlin/io/github/jooas/adapters/exceptions/JsonEmptyObjectException.kt
drewlakee
798,438,987
false
{"Kotlin": 38188}
package io.github.jooas.adapters.exceptions class JsonEmptyObjectException: RuntimeException()
0
Kotlin
0
0
d5a4cf3dc0a0877fac81e822c957303474cf34b2
95
json-object-openapi-schema
MIT License
typescript-kotlin/src/main/kotlin/typescript/JSDocContainer.kt
turansky
393,199,102
false
null
// Automatically generated - do not modify! package typescript external interface JSDocContainer
0
Kotlin
1
10
bcf03704c0e7670fd14ec4ab01dff8d7cca46bf0
99
react-types-kotlin
Apache License 2.0
src/commonMain/kotlin/wizard/generator.kt
terrakok
618,540,934
false
null
package wizard import wizard.files.* import wizard.files.app.* fun ProjectInfo.buildFiles() = buildList { add(Gitignore()) add(Readme(this@buildFiles)) add(GradleBat()) add(Gradlew()) add(GradleWrapperProperties(this@buildFiles)) add(GradleWrapperJar()) add(GradleProperties()) add(RootBuildGradleKts(this@buildFiles)) add(SettingsGradleKts(this@buildFiles)) add(ModuleBuildGradleKts(this@buildFiles)) add(AppThemeKt(this@buildFiles)) add(AppKt(this@buildFiles)) if ([email protected](ApolloPlugin)) { add(GraphQLSchema()) add(GraphQLQuery()) } if ([email protected]) { add(AndroidManifest()) add(AndroidThemesXml()) add(AndroidStringsXml(this@buildFiles)) add(AndroidAppKt(this@buildFiles)) } if ([email protected]) { add(DesktopAppKt(this@buildFiles)) add(DesktopMainKt(this@buildFiles)) } if ([email protected]) { add(Podspec()) add(IosAppKt(this@buildFiles)) add(IosMainKt(this@buildFiles)) add(Podfile()) add(IosAppIcon()) add(IosAccentColor()) add(IosAssets()) add(IosPreviewAssets()) add(IosAppSwift()) add(IosXcworkspace()) add(IosPbxproj(this@buildFiles)) } if ([email protected]) { add(BrowserAppKt(this@buildFiles)) add(IndexHtml(this@buildFiles)) add(BrowserMainKt(this@buildFiles)) } }
0
Kotlin
2
42
fbb5b6beabb5aa8891dcd8c6246d14ef9fa2c647
1,525
Compose-Multiplatform-Wizard
MIT License
Corona-Warn-App/src/main/java/de/rki/coronawarnapp/ui/settings/SettingsResetModule.kt
corona-warn-app
268,027,139
false
null
package de.rki.coronawarnapp.ui.settings import dagger.Binds import dagger.Module import dagger.android.ContributesAndroidInjector import dagger.multibindings.IntoMap import de.rki.coronawarnapp.util.viewmodel.CWAViewModel import de.rki.coronawarnapp.util.viewmodel.CWAViewModelFactory import de.rki.coronawarnapp.util.viewmodel.CWAViewModelKey @Module abstract class SettingsResetModule { @Binds @IntoMap @CWAViewModelKey(SettingsResetViewModel::class) abstract fun settingsResetVM( factory: SettingsResetViewModel.Factory ): CWAViewModelFactory<out CWAViewModel> @ContributesAndroidInjector abstract fun settingsResetFragment(): SettingsResetFragment }
6
Kotlin
514
2,495
d3833a212bd4c84e38a1fad23b282836d70ab8d5
694
cwa-app-android
Apache License 2.0
app/src/main/java/com/kuneosu/mintoners/ui/fragments/ProfileWithdrawFragment.kt
Kuneosu
823,904,157
false
{"Kotlin": 199162}
package com.kuneosu.mintoners.ui.fragments import android.os.Bundle import androidx.fragment.app.Fragment import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.navigation.fragment.findNavController import com.kuneosu.mintoners.R import com.kuneosu.mintoners.databinding.FragmentProfileWithdrawBinding class ProfileWithdrawFragment : Fragment() { private var _binding: FragmentProfileWithdrawBinding? = null private val binding get() = _binding!! override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View { _binding = FragmentProfileWithdrawBinding.inflate(inflater, container, false) binding.profileWithdrawWithdrawButton.setOnClickListener { findNavController().navigate(R.id.action_profileWithdrawFragment_to_profileMainFragment) } binding.profileWithdrawBackButton.setOnClickListener { findNavController().popBackStack() } return binding.root } override fun onDestroyView() { super.onDestroyView() _binding = null } }
0
Kotlin
0
0
3a290dcc803aa1d5ce1ad300c7cb3789280b1c74
1,165
Mintoners
MIT License
app/src/main/kotlin/cn/govast/vmusic/model/net/toplist/TopList.kt
SakurajimaMaii
351,469,044
false
null
/* * Copyright 2022 <NAME> <EMAIL> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package cn.govast.vmusic.model.net.toplist import cn.govast.vastadapter.AdapterItem import cn.govast.vasttools.network.base.BaseApiRsp import cn.govast.vmusic.R /** * 获取所有榜单 * * @property artistToplist * @property code * @property list */ data class TopList( val artistToplist: ArtistTopList, val code: Int, val list: List<Item> ) : BaseApiRsp { data class Item( val ToplistType: String, val adType: Int, val anonimous: Boolean, val artists: Any, val backgroundCoverId: Int, val backgroundCoverUrl: Any, val cloudTrackCount: Int, val commentThreadId: String, val coverImgId: Long, val coverImgId_str: String, val coverImgUrl: String, val createTime: Long, val creator: Any, val description: String, val englishTitle: Any, val highQuality: Boolean, val id: Long, val name: String, val newImported: Boolean, val opRecommend: Boolean, val ordered: Boolean, val playCount: Long, val privacy: Int, val recommendInfo: Any, val specialType: Int, val status: Int, val subscribed: Any, val subscribedCount: Int, val subscribers: List<Any>, val tags: List<String>, val titleImage: Int, val titleImageUrl: Any, val totalDuration: Int, val trackCount: Int, val trackNumberUpdateTime: Long, val trackUpdateTime: Long, val tracks: Any, val updateFrequency: String, val updateTime: Long, val userId: Long ):AdapterItem{ override fun getBindType(): Int { return R.layout.rv_item_top_list } } data class ArtistTopList( val coverUrl: String, val name: String, val position: Int, val upateFrequency: String, val updateFrequency: String ) }
2
Kotlin
0
8
af1cb8e620cb3e65f9ad5a0d05b240142db2608b
2,548
Music-Voice
Apache License 2.0
fmi-export/src/main/kotlin/no/ntnu/ihb/fmi4j/export/fmi2/annotations.kt
SFI-Mechatronics
339,847,408
false
null
package no.ntnu.ihb.fmi4j.export.fmi2 import no.ntnu.ihb.fmi4j.modeldescription.fmi2.Fmi2Causality import no.ntnu.ihb.fmi4j.modeldescription.fmi2.Fmi2Initial import no.ntnu.ihb.fmi4j.modeldescription.fmi2.Fmi2Variability @Target(AnnotationTarget.CLASS) @Retention(AnnotationRetention.RUNTIME) annotation class SlaveInfo( val modelName: String = "", val author: String = "", val version: String = "", val description: String = "", val copyright: String = "", val license: String = "", val canInterpolateInputs: Boolean = false, val canHandleVariableCommunicationStepSize: Boolean = true, val canBeInstantiatedOnlyOncePerProcess: Boolean = false, val needsExecutionTool: Boolean = false, ) @Target(AnnotationTarget.CLASS) @Retention(AnnotationRetention.RUNTIME) annotation class DefaultExperiment( val startTime: Double = 0.0, val stepSize: Double = -1.0, val stopTime: Double = -1.0 ) @Target(AnnotationTarget.FIELD) @Retention(AnnotationRetention.RUNTIME) annotation class ScalarVariable( val name: String = "", val description: String = "", val causality: Fmi2Causality = Fmi2Causality.local, val variability: Fmi2Variability = Fmi2Variability.continuous, val initial: Fmi2Initial = Fmi2Initial.undefined ) internal fun Variable<*>.applyAnnotation(v: ScalarVariable) { this.initial(v.initial) this.causality(v.causality) this.variability(v.variability) if (v.description.isNotEmpty()) this.description(v.description) }
0
null
0
1
23732efe282974171ab54d75cbb0791f40416a5c
1,585
FMI4j
MIT License
app/guice/oas-stub-guice-module/src/main/kotlin/io/github/ktakashi/oas/guice/services/DefaultExecutorProvider.kt
ktakashi
673,843,773
false
{"Kotlin": 395827, "Gherkin": 27347, "Groovy": 6882}
package io.github.ktakashi.oas.guice.services import io.github.ktakashi.oas.guice.configurations.OasStubGuiceConfiguration import io.github.ktakashi.oas.web.services.ExecutorProvider import jakarta.annotation.PreDestroy import jakarta.inject.Inject import jakarta.inject.Named import jakarta.inject.Singleton import java.util.concurrent.ConcurrentHashMap import java.util.concurrent.ExecutorService import java.util.concurrent.ForkJoinPool import java.util.concurrent.ForkJoinWorkerThread @Named @Singleton class DefaultExecutorProvider @Inject constructor(private val oasStubGuiceConfiguration: OasStubGuiceConfiguration): ExecutorProvider { private val executors: ConcurrentHashMap<String, ExecutorService> = ConcurrentHashMap() override fun getExecutor(name: String) = executors.computeIfAbsent(name) { _ -> ForkJoinPool(oasStubGuiceConfiguration.oasStubConfiguration.parallelism, ::WorkerThread, null, true) } @PreDestroy fun clear() { executors.forEach { (_, v) -> v.shutdown() } } } private class WorkerThread(pool: ForkJoinPool): ForkJoinWorkerThread(pool) { init { super.setContextClassLoader(WorkerThread::class.java.classLoader) } }
0
Kotlin
0
1
619eb76def52ac4eefbe8ea5e7117dc18fe298a9
1,204
oas-stub
Apache License 2.0
ast-transformations-core/src/main/kotlin/org/jetbrains/research/ml/ast/transformations/multipleOperatorComparison/MultipleOperatorComparisonVisitor.kt
JetBrains-Research
301,993,261
false
null
package org.jetbrains.research.ml.ast.transformations.multipleOperatorComparison import com.jetbrains.python.PyTokenTypes import com.jetbrains.python.psi.PyBinaryExpression import com.jetbrains.python.psi.PyElementGenerator import com.jetbrains.python.psi.PyElementVisitor import org.jetbrains.research.ml.ast.transformations.PerformedCommandStorage import org.jetbrains.research.ml.ast.transformations.PyUtils import org.jetbrains.research.ml.ast.transformations.safePerformCommand internal class MultipleOperatorComparisonVisitor(private val commandsStorage: PerformedCommandStorage?) : PyElementVisitor() { override fun visitPyBinaryExpression(node: PyBinaryExpression) { handleBinaryExpression(node) super.visitPyBinaryExpression(node) } private fun handleBinaryExpression(node: PyBinaryExpression) { if (!node.isMultipleOperatorComparison()) { return } val generator = PyElementGenerator.getInstance(node.project) val newBinaryExpression = transformMultipleComparisonExpression(node, generator) ?: return val newBracedExpression = PyUtils.braceExpression(newBinaryExpression) commandsStorage.safePerformCommand( { node.replace(newBracedExpression) }, "Replace multiple operation comparison with braced expression" ) } private fun transformMultipleComparisonExpression( node: PyBinaryExpression, generator: PyElementGenerator ): PyBinaryExpression? { if (!node.isMultipleOperatorComparison()) { return null } val leftBinaryExpression = node.leftExpression as PyBinaryExpression val leftRightExpression = leftBinaryExpression.rightExpression ?: return null val rightExpression = node.rightExpression ?: return null val nodeOperator = node.psiOperator ?: return null val newRightExpression = generator.createBinaryExpression( nodeOperator.text, leftRightExpression, rightExpression ) val newLeftBinaryExpression = transformMultipleComparisonExpression( leftBinaryExpression, generator ) ?: leftBinaryExpression return generator.createBinaryExpression("and", newLeftBinaryExpression, newRightExpression) } private fun PyBinaryExpression.isComparison(): Boolean = PyTokenTypes.COMPARISON_OPERATIONS.contains(operator) private fun PyBinaryExpression.isMultipleOperatorComparison(): Boolean { when (operator) { PyTokenTypes.AND_KEYWORD, PyTokenTypes.OR_KEYWORD -> return false else -> { val leftBinaryExpression = leftExpression as? PyBinaryExpression ?: return false return leftBinaryExpression.isComparison() && this.isComparison() } } } }
3
Kotlin
1
9
717706765a2da29087a0de768fc851698886dd65
2,863
ast-transformations
MIT License
app/src/main/java/com/sakethh/arara/unreleased/Unreleased.kt
sakethpathike
517,053,630
false
null
package com.sakethh.arara.unreleased import android.annotation.SuppressLint import android.media.AudioAttributes import android.media.AudioManager import android.media.PlaybackParams import android.os.Build import androidx.activity.compose.BackHandler import androidx.compose.animation.animateContentSize import androidx.compose.foundation.background import androidx.compose.foundation.layout.* import androidx.compose.foundation.lazy.LazyColumn import androidx.compose.foundation.lazy.items import androidx.compose.foundation.shape.CornerSize import androidx.compose.material.BottomSheetScaffoldState import androidx.compose.material.ExperimentalMaterialApi import androidx.compose.material3.* import androidx.compose.runtime.* import androidx.compose.runtime.saveable.rememberSaveable import androidx.compose.ui.Modifier import androidx.compose.ui.draw.shadow import androidx.compose.ui.unit.dp import androidx.lifecycle.viewmodel.compose.viewModel import androidx.navigation.NavController import com.google.accompanist.systemuicontroller.rememberSystemUiController import com.sakethh.arara.* import com.sakethh.arara.home.shimmer import com.sakethh.arara.ui.theme.* import com.sakethh.arara.unreleased.currentMusicScreen.CurrentMusicScreenViewModel import com.sakethh.arara.unreleased.currentMusicScreen.CurrentMusicScreenViewModel.CurrentMusicScreenUtils.isBtmSheetCollapsed import kotlinx.coroutines.flow.flow import kotlinx.coroutines.launch @OptIn(ExperimentalMaterial3Api::class, ExperimentalMaterialApi::class) @Composable fun UnreleasedScreen(bottomSheetScaffoldState: BottomSheetScaffoldState,itemOnClick: () -> Unit) { val scrollBehavior = TopAppBarDefaults.pinnedScrollBehavior( rememberTopAppBarState() ) { false } val unreleasedViewModel: UnreleasedViewModel = viewModel() val unreleasedData = unreleasedViewModel.rememberData val headerData = UnreleasedViewModel.UnreleasedUtils.rememberUnreleasedHeaderImg.value val footerData = UnreleasedViewModel.UnreleasedUtils.rememberUnreleasedFooterImg.value val musicPlayerImgURL = UnreleasedViewModel.UnreleasedUtils.rememberMusicPlayerImgURL val musicPlayerHDImgURL = UnreleasedViewModel.UnreleasedUtils.rememberMusicPlayerHDImgURL val musicPlayerTitle = UnreleasedViewModel.UnreleasedUtils.rememberMusicPlayerTitle val unreleasedLyricsForPlayer = UnreleasedViewModel.UnreleasedUtils.rememberMusicPlayerLyrics val rememberMusicPlayerDescription = UnreleasedViewModel.UnreleasedUtils.rememberMusicPlayerDescription val rememberMusicPlayerDescriptionBy = UnreleasedViewModel.UnreleasedUtils.rememberMusicPlayerDescriptionBy val rememberMusicPlayerArtworkBy = UnreleasedViewModel.UnreleasedUtils.rememberMusicPlayerArtworkBy val rememberMusicPlayerDescriptionOrigin = UnreleasedViewModel.UnreleasedUtils.rememberMusicPlayerDescriptionOrigin val audioUrl = UnreleasedViewModel.UnreleasedUtils.musicAudioURL Scaffold(topBar = { SmallTopAppBar( title = { Text( text = "Unreleased", style = MaterialTheme.typography.titleMedium, color = md_theme_dark_onTertiaryContainer ) }, scrollBehavior = scrollBehavior, colors = TopAppBarDefaults.smallTopAppBarColors(containerColor = md_theme_dark_onTertiary) ) }) { contentPadding -> LazyColumn( modifier = Modifier .background(md_theme_dark_onTertiary) .padding(bottom = 30.dp) .animateContentSize(), contentPadding = contentPadding, ) { items(headerData) { data -> ArtBoard(data.artwork) } items(unreleasedData.value) { data -> SongThing1( songName = data.songName, specificArtwork = data.imgURL, onClick = { musicPlayerImgURL.value = data.imgURL musicPlayerTitle.value = data.songName unreleasedLyricsForPlayer.value = data.lyrics rememberMusicPlayerDescription.value = data.songDescription rememberMusicPlayerDescriptionBy.value = data.descriptionBy rememberMusicPlayerDescriptionOrigin.value = data.descriptionOrigin rememberMusicPlayerArtworkBy.value = data.specificArtworkBy audioUrl.value = data.audioLink musicPlayerHDImgURL.value = data.imgURLHD itemOnClick() } ) } items(footerData) { data -> if (bottomSheetScaffoldState.bottomSheetState.isExpanded) { GIFThing( imgURL = data.footerImg, modifier = Modifier .background(md_theme_dark_surface) .padding(bottom = 150.dp) .fillMaxWidth() .height(70.dp) ) } else { GIFThing( imgURL = data.footerImg, modifier = Modifier .background(md_theme_dark_surface) .padding(bottom = 50.dp) .fillMaxWidth() .height(70.dp) ) } } } } } @OptIn(ExperimentalMaterial3Api::class, ExperimentalMaterialApi::class) @SuppressLint("UnusedMaterial3ScaffoldPaddingParameter") @Composable fun MainUnreleasedScreen(navController: NavController, bottomSheetScaffoldState: BottomSheetScaffoldState,sharedViewModel: SharedViewModel) { BackHandler { BottomNavigationBar.isBottomBarHidden.value = false navController.navigate("homeScreen") { popUpTo(0) } } val unreleasedViewModel:UnreleasedViewModel= viewModel() BottomNavigationBar.isBottomBarHidden.value = false sharedViewModel.isBottomNavVisible.value=true val systemUIController = rememberSystemUiController() val coroutineScope = rememberCoroutineScope() val scrollBehavior = TopAppBarDefaults.pinnedScrollBehavior( rememberTopAppBarState() ) { false } LaunchedEffect(key1 = coroutineScope) { coroutineScope.launch { systemUIController.setStatusBarColor(color = md_theme_dark_onTertiary) } } val musicControlBoolean = rememberSaveable { UnreleasedViewModel.UnreleasedUtils.rememberMusicPlayerControl } val rememberMusicPlayerControlImg = rememberSaveable { UnreleasedViewModel.UnreleasedUtils.rememberMusicPlayerControlImg } val currentControlIcon = rememberSaveable { mutableListOf(0, 1) } val currentAudioURL = UnreleasedViewModel.UnreleasedUtils.musicAudioURL rememberSaveable { UnreleasedViewModel.UnreleasedUtils.rememberMusicPlayerDescriptionBy } rememberSaveable { UnreleasedViewModel.UnreleasedUtils.rememberMusicPlayerDescriptionOrigin } UnreleasedViewModel.UnreleasedUtils.rememberMusicPlayerArtworkBy val currentGIFURL = rememberSaveable { UnreleasedViewModel.UnreleasedUtils.currentLoadingStatusGIFURL } if (musicControlBoolean.value) { val playIcon = rememberMusicPlayerControlImg[0] //play icon currentControlIcon[0] = playIcon } else { val pauseIcon = rememberMusicPlayerControlImg[1] //pause icon currentControlIcon[0] = pauseIcon } if (unreleasedViewModel.isDataLoaded.value) { UnreleasedScreen( bottomSheetScaffoldState= bottomSheetScaffoldState) { isBtmSheetCollapsed.value=false sharedViewModel.isBottomNavVisible.value=true coroutineScope.launch { bottomSheetScaffoldState.bottomSheetState.expand() } if (Build.VERSION.SDK_INT <= 26) { UnreleasedViewModel.UnreleasedUtils.mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC) } else { UnreleasedViewModel.UnreleasedUtils.mediaPlayer.setAudioAttributes( AudioAttributes.Builder().setContentType(AudioAttributes.CONTENT_TYPE_MUSIC) .setUsage(AudioAttributes.USAGE_MEDIA).build() ) } UnreleasedViewModel.UnreleasedUtils.mediaPlayer.stop() UnreleasedViewModel.UnreleasedUtils.mediaPlayer.reset().also { UnreleasedViewModel.UnreleasedUtils.musicCompleted.value = false UnreleasedViewModel.UnreleasedUtils.rememberMusicPlayerControl.value = false UnreleasedViewModel.UnreleasedUtils.currentSongIsPlaying.value = false currentGIFURL.value = UnreleasedViewModel.UnreleasedUtils.rememberMusicPlayerLoadingGIF.component1()[0].gifURL UnreleasedViewModel.UnreleasedUtils.musicPlayerVisibility.value = false UnreleasedViewModel.UnreleasedUtils.mediaPlayer.setDataSource(currentAudioURL.value) UnreleasedViewModel.UnreleasedUtils.mediaPlayer.prepareAsync() UnreleasedViewModel.UnreleasedUtils.mediaPlayer.setOnPreparedListener { try { it.start() } catch (e: Exception) { currentGIFURL.value = Constants.MUSIC_ERROR_GIF } if (it.isPlaying) { currentGIFURL.value = UnreleasedViewModel.UnreleasedUtils.rememberMusicPlayerPlayingGIF.component1()[0].gifURL UnreleasedViewModel.UnreleasedUtils.musicPlayerVisibility.value = true UnreleasedViewModel.UnreleasedUtils.currentSongIsPlaying.value = true } it.setOnCompletionListener { coroutineScope.launch { bottomSheetScaffoldState.bottomSheetState.collapse() } UnreleasedViewModel.UnreleasedUtils.musicCompleted.value = true UnreleasedViewModel.UnreleasedUtils.musicPlayerVisibility.value = false UnreleasedViewModel.UnreleasedUtils.currentLoadingStatusGIFURL.value = Constants.MUSIC_ERROR_GIF UnreleasedViewModel.UnreleasedUtils.currentSongIsPlaying.value = false } } } } } else { Scaffold(topBar = { SmallTopAppBar( title = { Text( text = "Unreleased", style = MaterialTheme.typography.titleMedium, color = md_theme_dark_onTertiaryContainer ) }, scrollBehavior = scrollBehavior, colors = TopAppBarDefaults.smallTopAppBarColors(containerColor = md_theme_dark_onTertiary) ) }) { contentPadding -> LazyColumn( modifier = Modifier .background(md_theme_dark_onTertiary) .padding(bottom = 30.dp), contentPadding = contentPadding, ) { item { ArtBoard( imgURL = "data.artwork", imgModifier = Modifier .size(150.dp) .shadow(2.dp) .shimmer(true) ) } items(8) { SongThing1( songName = "Broken Satellites", specificArtwork = "data.imgURL", onClick = {}, imgModifier = Modifier .padding(top = 10.dp) .requiredHeight(50.dp) .padding(start = 10.dp) .requiredWidth(50.dp) .shimmer(true), titleModifier = Modifier.shimmer(true), lyricsModifier = Modifier .padding(top = 3.dp, bottom = 3.dp) .background(color = md_theme_light_outline) .wrapContentSize() .padding(2.dp) .shimmer(true, cornerSize = CornerSize(0.dp)) ) } } } } }
0
Kotlin
0
0
d0bffe832b47f6fac7d85831192a5a26e73158c0
12,923
arara-android
MIT License
app/src/main/java/com/vengateshm/covidsummarywidget/COVIDSummaryAppWidgetProvider.kt
vengateshm
326,644,834
false
{"Kotlin": 14600}
package com.vengateshm.covidsummarywidget import android.app.* import android.appwidget.AppWidgetManager import android.appwidget.AppWidgetProvider import android.content.ComponentName import android.content.Context import android.content.Intent import android.graphics.Color import android.os.Build import android.os.IBinder import android.util.Log import android.view.View import android.widget.RemoteViews import androidx.annotation.RequiresApi import com.vengateshm.covidsummarywidget.models.SummaryResponse import com.vengateshm.covidsummarywidget.network.COVIDApiService import retrofit2.Call import retrofit2.Callback import retrofit2.Response class COVIDSummaryAppWidgetProvider : AppWidgetProvider() { private val TAG = "COVIDSummaryAppWidgetProvider" private val REFRESH_BTN_CLICK_ACTION = "refresh_button_click_action" override fun onEnabled(context: Context?) { super.onEnabled(context) Log.d(TAG, "onEnabled") } override fun onUpdate( context: Context, appWidgetManager: AppWidgetManager, appWidgetIds: IntArray ) { Log.d(TAG, "onUpdate") //startUpdateService(context); // Perform this loop procedure for each App Widget that belongs to this provider appWidgetIds.forEach { appWidgetId -> // Create an Intent to launch ExampleActivity val pendingIntent: PendingIntent = Intent(context, MainActivity::class.java) .let { intent -> PendingIntent.getActivity(context, 0, intent, 0) } // Get the layout for the App Widget and attach an on-click listener // to the button val views: RemoteViews = RemoteViews( context.packageName, R.layout.covid_summary_layout ).apply { //setOnClickPendingIntent(R.id.widgetRootLayout, pendingIntent) setOnClickPendingIntent( R.id.ivRefresh, PendingIntent.getBroadcast( context, 0, Intent(context, COVIDSummaryAppWidgetProvider::class.java).apply { action = REFRESH_BTN_CLICK_ACTION }, 0 ) ) } // Tell the AppWidgetManager to perform an update on the current app widget appWidgetManager.updateAppWidget(appWidgetId, views) } } private fun startUpdateService(context: Context) { // To prevent any ANR timeouts, we perform the update in a service if (Build.VERSION.SDK_INT < Build.VERSION_CODES.O) context.startService(Intent(context, COVIDSummaryUpdateService::class.java)) else context.startForegroundService(Intent(context, COVIDSummaryUpdateService::class.java)) } override fun onDisabled(context: Context?) { super.onDisabled(context) Log.d(TAG, "onDisabled") } override fun onDeleted(context: Context?, appWidgetIds: IntArray?) { super.onDeleted(context, appWidgetIds) Log.d(TAG, "onDeleted") } override fun onReceive(context: Context?, intent: Intent?) { super.onReceive(context, intent) Log.d(TAG, "onReceive") if (REFRESH_BTN_CLICK_ACTION == intent?.action) { context?.let { startUpdateService(it) } } } companion object { class COVIDSummaryUpdateService : Service() { private val TAG = "COVIDSummaryUpdateService" private val FOREGROUND_SERVICE_ID = 111 override fun onBind(intent: Intent?): IBinder? { return null } override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int { startNotificationForForeground() val views = RemoteViews( [email protected], R.layout.covid_summary_layout ) views.setViewVisibility(R.id.ivRefresh, View.GONE) views.setViewVisibility(R.id.progressBar, View.VISIBLE) val componentName = ComponentName( [email protected], COVIDSummaryAppWidgetProvider::class.java ) val manager = AppWidgetManager.getInstance([email protected]) manager.updateAppWidget(componentName, views) COVIDApiService.getCOVIDApi().getSummary() .enqueue(object : Callback<SummaryResponse> { override fun onResponse( call: Call<SummaryResponse>, response: Response<SummaryResponse> ) { if (response.isSuccessful && response.code() == 200) { updateWidgetWithResponse(response.body()) } else { hideProgressView() } stopService() } override fun onFailure(call: Call<SummaryResponse>, t: Throwable) { t.message?.let { Log.d(TAG, it) } hideProgressView() stopService() } }) return START_STICKY } private fun stopService() { stopForeground(true) stopSelf() } private fun updateWidgetWithResponse(summaryResponse: SummaryResponse?) { try { summaryResponse?.let { val views = RemoteViews( [email protected], R.layout.covid_summary_layout ) views.setTextViewText( R.id.tvNewConfirmedCases, "Confirmed Cases - ${summaryResponse.global.newConfirmed}" ) views.setTextViewText( R.id.tvNewDeaths, "Deaths - ${summaryResponse.global.newDeaths}" ) views.setTextViewText( R.id.tvNewRecovered, "Recovered - ${summaryResponse.global.newRecovered}" ) views.setTextViewText( R.id.tvTotalConfirmedCases, "Confirmed Cases - ${summaryResponse.global.totalConfirmed}" ) views.setTextViewText( R.id.tvTotalDeaths, "Deaths - ${summaryResponse.global.totalDeaths}" ) views.setTextViewText( R.id.tvTotalRecovered, "Recovered - ${summaryResponse.global.totalRecovered}" ) views.setViewVisibility(R.id.ivRefresh, View.VISIBLE) views.setViewVisibility(R.id.progressBar, View.GONE) val componentName = ComponentName( [email protected], COVIDSummaryAppWidgetProvider::class.java ) val manager = AppWidgetManager.getInstance([email protected]) manager.updateAppWidget(componentName, views) } } catch (e: Exception) { e.message?.let { Log.d(TAG, it) } hideProgressView() stopService() } } private fun hideProgressView() { val views = RemoteViews( [email protected], R.layout.covid_summary_layout ) views.setViewVisibility(R.id.ivRefresh, View.VISIBLE) views.setViewVisibility(R.id.progressBar, View.GONE) val componentName = ComponentName( [email protected], COVIDSummaryAppWidgetProvider::class.java ) val manager = AppWidgetManager.getInstance([email protected]) manager.updateAppWidget(componentName, views) } private fun startNotificationForForeground() { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { startForeground( FOREGROUND_SERVICE_ID, createNotification( "COVID19Service", "COVID19 Summary Channel", null, getString(R.string.foreground_not_text) ) ) } } @RequiresApi(Build.VERSION_CODES.O) private fun createNotification( channelId: String, channelName: String, contentTitle: String?, contentText: String, pendingIntent: PendingIntent? = null ): Notification { val notificationChannel = NotificationChannel(channelId, channelName, NotificationManager.IMPORTANCE_NONE) notificationChannel.description = channelId notificationChannel.setSound(null, null) notificationChannel.lightColor = Color.BLUE notificationChannel.lockscreenVisibility = Notification.VISIBILITY_PRIVATE val notificationManager = getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager notificationManager.createNotificationChannel(notificationChannel) return Notification.Builder(this, channelId).let { builder -> contentTitle?.let { builder.setContentTitle(contentTitle) } builder.setContentText(contentText) builder.setSmallIcon(R.drawable.ic_covid_19_33) pendingIntent?.let { builder.setContentIntent(it) } builder.build() } } } } }
0
Kotlin
0
1
d9e3a235c85de24d99ec378c98de0fae9642c9ab
10,874
android_appwidget_sample
Apache License 2.0
shared/common/src/commonMain/kotlin/com/gplay/core/domain/validation/FieldRule.kt
lukma
529,747,563
false
{"Kotlin": 140900, "Swift": 26911}
package com.gplay.core.domain.validation sealed class FieldRule( val onValidate: (Any) -> ValidationError?, ) { object NoFieldBlank : FieldRule(onValidate = { val value = when (it) { is String -> it is Number -> runCatching { it.toString() }.getOrElse { "" } else -> "" } if (value.isBlank()) ValidationError.FieldBlank else null }) }
0
Kotlin
0
1
06828523a53ce3e35963fd1536264e3110b8cfed
417
sample-kmm
Apache License 2.0
src/main/java/me/kotlinMod/echoing_tools/EchoingTools.kt
yotamor
847,415,596
false
{"Kotlin": 54141, "Java": 9364}
package me.kotlinMod.echoing_tools import me.kotlinMod.echoing_tools.events.* import me.kotlinMod.echoing_tools.modItems.* import me.kotlinMod.echoing_tools.modItems.ModItems.Companion.sculkArrow import me.kotlinMod.echoing_tools.worldGen.AncientMushroomPlacedFeature import net.fabricmc.api.ModInitializer import net.fabricmc.fabric.api.biome.v1.BiomeModifications import net.fabricmc.fabric.api.biome.v1.BiomeSelectors import net.fabricmc.fabric.api.event.lifecycle.v1.ServerEntityEvents import net.fabricmc.fabric.api.event.player.AttackEntityCallback import net.fabricmc.fabric.api.event.player.PlayerBlockBreakEvents import net.fabricmc.fabric.api.event.player.UseBlockCallback import net.fabricmc.fabric.api.event.player.UseItemCallback import net.fabricmc.fabric.api.item.v1.ModifyItemAttributeModifiersCallback import net.fabricmc.fabric.api.loot.v2.LootTableEvents import net.minecraft.block.DispenserBlock import net.minecraft.block.dispenser.ProjectileDispenserBehavior import net.minecraft.entity.Entity import net.minecraft.entity.player.PlayerEntity import net.minecraft.entity.projectile.PersistentProjectileEntity import net.minecraft.entity.projectile.ProjectileEntity import net.minecraft.item.ItemStack import net.minecraft.sound.SoundCategory import net.minecraft.sound.SoundEvents import net.minecraft.util.Hand import net.minecraft.util.hit.EntityHitResult import net.minecraft.util.math.BlockPos import net.minecraft.util.math.Position import net.minecraft.world.World import net.minecraft.world.biome.BiomeKeys import net.minecraft.world.gen.GenerationStep import org.slf4j.LoggerFactory import java.util.* class EchoingTools : ModInitializer { object ModID { const val modID: String = "echoing_tools" var shovelAbility: MutableMap<UUID, UByte> = emptyMap<UUID, UByte>().toMutableMap() var timesSinceSwordAbility: MutableMap<UUID, UByte> = emptyMap<UUID, UByte>().toMutableMap() val logger = LoggerFactory.getLogger(modID)!! } override fun onInitialize() { ModItems.registerGroup() registerDispenserBehaviour() generateAncientMushrooms() EffectAddCallBack.EVENT.register(EntityEffectEvent()) PlayerBlockBreakEvents.AFTER.register(PlayerMinesEvent()) AttackEntityCallback.EVENT.register { player: PlayerEntity, world: World, hand: Hand, entity: Entity, hitResult: EntityHitResult? -> EntityAttackEvent().interact(player, world, hand, entity, hitResult) } UseItemCallback.EVENT.register(PlayerRightClickEvent()) UseBlockCallback.EVENT.register(PlayerRightClickOnBlockEvent()) ModifyItemAttributeModifiersCallback.EVENT.register(ArmorAttribute()) ServerEntityEvents.ENTITY_UNLOAD.register(EntityUnloadEvent()) LootTableEvents.MODIFY.register(LootTableEvent()) } private fun registerDispenserBehaviour(): SculkArrowEntity? { DispenserBlock.registerBehavior(sculkArrow, object : ProjectileDispenserBehavior() { override fun createProjectile(world: World, position: Position, stack: ItemStack): ProjectileEntity { world.playSound(null, BlockPos(position.x.toInt(), position.y.toInt(), position.z.toInt()), SoundEvents.ENTITY_WARDEN_SONIC_BOOM, SoundCategory.HOSTILE, 0.2f, 1f) val arrowEntity = SculkArrowEntity(world, position.x, position.y, position.z) arrowEntity.pickupType = PersistentProjectileEntity.PickupPermission.ALLOWED return arrowEntity } }) return null } private fun generateAncientMushrooms() { BiomeModifications.addFeature( BiomeSelectors.includeByKey(BiomeKeys.DEEP_DARK), GenerationStep.Feature.VEGETAL_DECORATION, AncientMushroomPlacedFeature.ancientMushroomPlacedKey ) } }
0
Kotlin
0
0
cb68ddc8e721529916fb29c497719af0fbb6ce27
3,815
Echoing-Tools
MIT License
feature/filmdetails/src/main/java/tech/dalapenko/feature/filmdetails/domain/GetFilmDetailsUseCase.kt
dalapenko
739,864,810
false
{"Kotlin": 136155, "Dockerfile": 1314}
package tech.dalapenko.feature.filmdetails.domain import kotlinx.coroutines.flow.flow import tech.dalapenko.data.filmdetails.repository.DataState import tech.dalapenko.data.filmdetails.repository.FilmDetailsRepository import tech.dalapenko.feature.filmdetails.model.UiState import javax.inject.Inject class GetFilmDetailsUseCase @Inject constructor( private val filmDetailsRepository: FilmDetailsRepository ) { suspend operator fun invoke( id: Int ) = flow { emit(UiState.Loading) filmDetailsRepository.getFilmDetails(id) .collect { data -> val uiState = when(data) { is DataState.Ready -> UiState.Success(data.data) is DataState.Loading -> UiState.Loading is DataState.FetchError -> UiState.Error } emit(uiState) } } }
0
Kotlin
0
0
c1c5e965deb7216fbccf050175a66f9a07993079
895
kinosearch
Apache License 2.0
shared/src/commonMain/kotlin/me/saket/press/shared/rx/Rx.ext.kt
msasikanth
254,440,961
true
{"Kotlin": 271479, "Swift": 38924, "Java": 27798, "Ruby": 5821}
package me.saket.press.shared.rx import com.badoo.reaktive.observable.Observable import com.badoo.reaktive.observable.map import com.badoo.reaktive.observable.merge import com.badoo.reaktive.observable.observableInterval import com.badoo.reaktive.observable.withLatestFrom import com.badoo.reaktive.scheduler.Scheduler import com.soywiz.klock.TimeSpan import me.saket.press.shared.util.Optional import me.saket.press.shared.util.toOptional internal fun <T, R : Any> Observable<T>.mapToOptional(mapper: (T) -> R?): Observable<Optional<R>> { return map { mapper(it).toOptional() } } internal fun <T : Any> Observable<Optional<T>>.mapToSome(): Observable<T> { return map { (item) -> item!! } } internal fun observableInterval(interval: TimeSpan, scheduler: Scheduler): Observable<Long> { return observableInterval(interval.milliseconds.toLong(), scheduler) } internal fun <T, O> Observable<T>.withLatestFrom(other: Observable<O>): Observable<Pair<T, O>> { return withLatestFrom(other, ::Pair) } internal fun <T> Observable<T>.mergeWith(other: Observable<T>): Observable<T> { return merge(this, other) }
0
Kotlin
0
1
ed09ce3dfe7cbcdc9792b05c5a11f22bc2a2f5ea
1,116
press
Apache License 2.0
shared/src/commonMain/kotlin/org/mixdrinks/ui/widgets/Header.kt
MixDrinks
614,917,688
false
{"Kotlin": 196307, "Swift": 10681, "Ruby": 277, "Shell": 228}
package org.mixdrinks.ui.widgets import androidx.compose.foundation.Image import androidx.compose.foundation.background import androidx.compose.foundation.clickable import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.height import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.size import androidx.compose.material.Text import androidx.compose.runtime.Composable import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.unit.dp import org.jetbrains.compose.resources.ExperimentalResourceApi import org.jetbrains.compose.resources.painterResource import org.mixdrinks.app.styles.MixDrinksColors import org.mixdrinks.app.styles.MixDrinksTextStyles @OptIn(ExperimentalResourceApi::class) @Composable internal fun MixDrinksHeader(name: String, onBackClick: (() -> Unit)? = null) { Row( modifier = Modifier .background(MixDrinksColors.Main) .fillMaxWidth() .height(52.dp), ) { if (onBackClick != null) { Box( modifier = Modifier.size(52.dp) .clickable { onBackClick() } ) { Image( modifier = Modifier .align(Alignment.Center) .size(32.dp) .padding(start = 12.dp), painter = painterResource("ic_arrow_back.xml"), contentDescription = "Назад" ) } } val padding = if (onBackClick == null) 16.dp else 4.dp Text( modifier = Modifier.padding(start = padding) .align(Alignment.CenterVertically), color = MixDrinksColors.White, text = name, style = MixDrinksTextStyles.H2, softWrap = false, maxLines = 1, ) } }
14
Kotlin
1
9
182933ab91b766def2d6dfd67f63c7e4ef008ee8
2,083
Mobile
Apache License 2.0
chat-messaging-memory/src/test/kotlin/com/demo/chat/test/stream/StreamManagerTestBase.kt
marios-code-path
181,180,043
false
{"Kotlin": 924762, "Shell": 36602, "C": 3160, "HTML": 2714, "Starlark": 278}
package com.demo.chat.test.stream import com.demo.chat.convert.Converter import com.demo.chat.domain.Message import com.demo.chat.domain.MessageKey import com.demo.chat.pubsub.memory.impl.ExampleReactiveStreamManager import org.assertj.core.api.Assertions import org.junit.jupiter.api.BeforeEach import org.junit.jupiter.api.Disabled import org.junit.jupiter.api.Test import reactor.core.publisher.Flux import reactor.core.publisher.Hooks import reactor.test.StepVerifier import java.time.Duration // TODO Test for resource cleanup! @Disabled open class StreamManagerTestBase<K, V>( val streamMan: ExampleReactiveStreamManager<K, V>, val codec: Converter<Unit, K>, val valueCodec: Converter<Unit, V>) { @BeforeEach fun setUp() { Hooks.onOperatorDebug() } @Test fun `should create a stream and flux`() { val streamId = codec.convert(Unit) streamMan.getSource(streamId) Assertions .assertThat(streamMan.getSink(streamId)) .isNotNull } @Test fun `should subscribe to a stream`() { val streamId = codec.convert(Unit) val subscriber = streamMan.subscribeUpstream(streamId, Flux.empty()) Assertions .assertThat(subscriber) .isNotNull } @Test fun `should subscribe to and send data`() { val streamId = codec.convert(Unit) val dataSource = Flux .just(Message .create(MessageKey.create(codec.convert(Unit), streamId, codec.convert(Unit)), valueCodec.convert(Unit), true)) StepVerifier .create(streamMan.getSink(streamId)) .then { streamMan.subscribeUpstream(streamId, dataSource) } .assertNext { Assertions .assertThat(it) .`as`("Has state") .isNotNull() } .then { streamMan.close(streamId) } .expectComplete() .verify(Duration.ofSeconds(2)) } @Test fun `should consume stream function succeed when no data is passed`() { val streamId = codec.convert(Unit) val consumerId = codec.convert(Unit) val disposable = streamMan.subscribe(streamId, consumerId) Assertions .assertThat(disposable) .isNotNull disposable.dispose() } @Test fun `should consumer receive a subscribed stream messages`() { val streamId = codec.convert(Unit) val consumerId = codec.convert(Unit) val messageId = codec.convert(Unit) val fromId = codec.convert(Unit) val valueData = valueCodec.convert(Unit) StepVerifier .create(streamMan.getSink(consumerId)) .then { streamMan.subscribe(streamId, consumerId) streamMan.getSource(streamId) .onNext(Message.create( MessageKey.create(messageId, fromId, streamId), valueData, false)) } .assertNext { Assertions .assertThat(it) .`as`("Has state") .isNotNull() } .then { streamMan.close(consumerId) streamMan.close(streamId) } .expectComplete() .verify(Duration.ofSeconds(2L)) } @Test fun `should multiple consumers receive a subscribed streams messages`() { val streamId = codec.convert(Unit) val consumerId = codec.convert(Unit) val otherConsumerId = codec.convert(Unit) val messageId = codec.convert(Unit) val fromId = codec.convert(Unit) val valueData = valueCodec.convert(Unit) StepVerifier .create(Flux.merge(streamMan.getSink(consumerId), streamMan.getSink(otherConsumerId))) .then { streamMan.subscribe(streamId, consumerId) streamMan.subscribe(streamId, otherConsumerId) streamMan.getSource(streamId) .onNext(Message.create( MessageKey.create(messageId, fromId, streamId), valueData, false)) } .expectNextCount(2) .then { streamMan.close(otherConsumerId) streamMan.close(consumerId) streamMan.close(streamId) } .expectComplete() .verify(Duration.ofSeconds(2L)) } @Test fun `disconnected consumers should not receive messages`() { val streamId = codec.convert(Unit) val consumerId = codec.convert(Unit) val otherConsumerId = codec.convert(Unit) val messageId = codec.convert(Unit) val fromId = codec.convert(Unit) val valueData = valueCodec.convert(Unit) StepVerifier .create(Flux.merge(streamMan.getSink(consumerId), streamMan.getSink(otherConsumerId))) .then { streamMan.subscribe(streamId, consumerId) streamMan.subscribe(streamId, otherConsumerId) streamMan.getSource(streamId) .onNext(Message.create( MessageKey.create(messageId, fromId, streamId), valueData, false)) } .expectNextCount(2) .then { streamMan.close(consumerId) streamMan.getSource(streamId) .onNext(Message.create( MessageKey.create(messageId, fromId, streamId), valueData, false)) } .expectNextCount(1) .then { streamMan.close(otherConsumerId) } .expectComplete() .verify(Duration.ofSeconds(2L)) } }
2
Kotlin
1
9
2ae59375cd44e8fb58093b0f24596fc3111fd447
6,561
demo-chat
MIT License
core/ui/src/main/kotlin/ru/tech/imageresizershrinker/core/ui/shapes/ExplosionShape.kt
T8RIN
478,710,402
false
{"Kotlin": 6498864}
/* * ImageToolbox is an image editor for android * Copyright (c) 2024 T8RIN (Malik Mukhametzyanov) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * You should have received a copy of the Apache License * along with this program. If not, see <http://www.apache.org/licenses/LICENSE-2.0>. */ package ru.tech.imageresizershrinker.core.ui.shapes import ru.tech.imageresizershrinker.core.ui.utils.helper.PathShape private const val ExplosionPathData = "M24.3629 0.130582C24.0071 -0.0526879 23.5886 -0.0422153 23.2434 0.156763C21.2763 1.29304 14.6586 5.04745 13.1833 5.04745C11.9748 5.04745 6.27256 2.52356 2.91398 0.984095C1.97755 0.55472 0.988809 1.45012 1.31839 2.42407C2.57394 6.1523 4.68221 12.6505 4.30554 13.2684C3.84518 14.0224 0.873717 21.6936 0.0890009 23.7357C-0.0313222 24.0499 -0.0103964 24.3955 0.146547 24.6992C1.13529 26.579 4.72929 33.5695 4.44156 35.1299C4.20614 36.4023 2.04556 42.0941 0.790014 45.3406C0.434276 46.2622 1.3027 47.1785 2.23912 46.8801C5.82789 45.7386 12.3463 43.686 12.9217 43.686C13.6227 43.686 21.925 47.0791 23.9601 47.9116C24.2478 48.0321 24.5669 48.0268 24.8546 47.9116C26.9211 47.0476 35.4745 43.487 35.8302 43.487C36.1179 43.487 41.7417 45.6286 44.9381 46.8591C45.8379 47.2047 46.743 46.3774 46.4866 45.4506C45.5554 42.0994 43.9285 36.1143 43.9756 35.3969C44.0331 34.5225 47.1458 26.223 47.9358 24.1284C48.0508 23.8247 48.0352 23.4844 47.8887 23.1912C46.9784 21.3689 43.6512 14.5984 43.7088 12.8704C43.7558 11.5038 45.6653 5.93238 46.8738 2.53403C47.2243 1.54961 46.2094 0.633265 45.2625 1.08358C41.7731 2.75396 35.9348 5.51871 35.4221 5.51871C34.7891 5.51871 26.6072 1.29827 24.3629 0.130582Z" val ExplosionShape = PathShape(ExplosionPathData)
10
Kotlin
176
3,817
486410d4a9ea3c832fc5aa63eb5bdc7b1fab871d
2,113
ImageToolbox
Apache License 2.0
app/src/main/java/xyz/aprildown/torch/SettingsActivity.kt
DeweyReed
268,979,316
false
null
package xyz.aprildown.torch import android.content.Context import android.content.Intent import android.hardware.camera2.CameraManager import android.net.Uri import android.os.Bundle import android.provider.Settings import android.text.Editable import android.text.TextWatcher import android.view.LayoutInflater import android.view.WindowManager import android.view.inputmethod.EditorInfo import androidx.activity.result.contract.ActivityResultContracts import androidx.appcompat.app.AlertDialog import androidx.appcompat.app.AppCompatActivity import androidx.preference.Preference import androidx.preference.PreferenceFragmentCompat import androidx.preference.SwitchPreferenceCompat import com.google.android.material.dialog.MaterialAlertDialogBuilder import xyz.aprildown.torch.databinding.DialogDelayInputBinding import xyz.aprildown.torch.databinding.DialogFloatingWindowBinding class SettingsActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) if (savedInstanceState == null) { supportFragmentManager.beginTransaction() .replace(android.R.id.content, SettingsFragment()) .commit() } } } class SettingsFragment : PreferenceFragmentCompat() { private lateinit var cm: CameraManager private val manageOverlayPermissionLauncher = registerForActivityResult(ActivityResultContracts.StartActivityForResult()) {} override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) cm = requireContext().getSystemService(Context.CAMERA_SERVICE) as CameraManager } override fun onCreatePreferences(savedInstanceState: Bundle?, rootKey: String?) { setPreferencesFromResource(R.xml.settings, rootKey) val context = requireContext() findPreference<SwitchPreferenceCompat>(getString(R.string.settings_toggle_key)) ?.setOnPreferenceClickListener { FlashlightService.toggle(context) true } findPreference<Preference>(getString(R.string.shortcuts_toggle_key)) ?.setOnPreferenceClickListener { context.pinShortcut(FlashlightShortcut.Toggle) true } findPreference<Preference>(getString(R.string.shortcuts_anti_touch_key)) ?.setOnPreferenceClickListener { context.pinShortcut(FlashlightShortcut.AntiTouch) true } findPreference<Preference>(getString(R.string.shortcuts_ephemeral_anti_touch_key)) ?.setOnPreferenceClickListener { context.pinShortcut(FlashlightShortcut.EphemeralAntiTouch) true } findPreference<Preference>(getString(R.string.shortcuts_delayed_anti_touch_key)) ?.setOnPreferenceClickListener { context.requestDelay { context.pinShortcut( FlashlightShortcut.DelayedAntiTouch, delayedAntiTouchDelayInMilli = it ) } true } findPreference<Preference>(getString(R.string.shortcuts_on_off_anti_touch_key)) ?.setOnPreferenceClickListener { context.pinShortcut(FlashlightShortcut.OnOffAntiTouch) true } findPreference<Preference>(getString(R.string.shortcuts_bright_screen_key)) ?.setOnPreferenceClickListener { context.pinShortcut(FlashlightShortcut.BrightScreen) true } findPreference<Preference>(getString(R.string.shortcuts_flashbang_key)) ?.setOnPreferenceClickListener { context.pinShortcut(FlashlightShortcut.Flashbang) true } findPreference<Preference>(getString(R.string.shortcuts_floating_window_key)) ?.setOnPreferenceClickListener { if (Settings.canDrawOverlays(context)) { val binding = DialogFloatingWindowBinding.inflate(LayoutInflater.from(context)) binding.layoutTurnOnTheFlashlight.setOnClickListener { binding.switchTurnOnTheFlashlight.toggle() } binding.layoutCloseWithTheFlashlight.setOnClickListener { binding.switchCloseWithTheFlashlight.toggle() } MaterialAlertDialogBuilder(context) .setView(binding.root) .setTitle(R.string.shortcuts_floating_window_title) .setPositiveButton(android.R.string.ok) { _, _ -> context.pinShortcut( FlashlightShortcut.FloatingWindow, floatingWindowTurnOnTheFlashlight = binding.switchTurnOnTheFlashlight.isChecked, floatingWindowCloseWithTheFlashlight = binding.switchCloseWithTheFlashlight.isChecked, ) } .show() } else { manageOverlayPermissionLauncher.launch( Intent(Settings.ACTION_MANAGE_OVERLAY_PERMISSION) .setData(Uri.parse("package:${context.packageName}")) ) } true } } private val torchCallback = object : CameraManager.TorchCallback() { override fun onTorchModeChanged(cameraId: String, enabled: Boolean) { findPreference<SwitchPreferenceCompat>(getString(R.string.settings_toggle_key)) ?.isChecked = enabled } } override fun onResume() { super.onResume() cm.registerTorchCallback(torchCallback, null) } override fun onPause() { super.onPause() cm.unregisterTorchCallback(torchCallback) } } private fun Context.requestDelay(onResult: (Long) -> Unit) { val builder = MaterialAlertDialogBuilder(this) .setTitle(R.string.shortcuts_delayed_anti_touch_delay_input_title) .setPositiveButton(android.R.string.ok, null) val view = DialogDelayInputBinding.inflate(LayoutInflater.from(this)) view.editDelayInput.requestFocus() builder.setView(view.root) val dialog = builder.create() dialog.window?.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE) dialog.show() dialog.setOnDismissListener { dialog.window?.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN) } val positiveButton = dialog.getButton(AlertDialog.BUTTON_POSITIVE) view.editDelayInput.setOnEditorActionListener { _, actionId, _ -> if (actionId == EditorInfo.IME_ACTION_DONE && positiveButton.isEnabled) { positiveButton.performClick() true } else { false } } view.editDelayInput.addTextChangedListener(object : TextWatcher { override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) = Unit override fun afterTextChanged(s: Editable?) = Unit override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) { val input = s?.toString()?.toIntOrNull() if (input != null && input in 1..10) { view.inputDelayInput.error = null positiveButton.isEnabled = true } else { view.inputDelayInput.error = "1s ~ 10s" positiveButton.isEnabled = false } } }) positiveButton.setOnClickListener { dialog.dismiss() onResult.invoke((view.editDelayInput.text?.toString()?.toLongOrNull() ?: 0L) * 1_000L) } }
0
Kotlin
0
0
6701f61a4169594bb5bb1a2b248927be20fe2aef
7,906
OneClickFlashlight
Apache License 2.0
app/src/main/java/com/azhar/tambalban/view/activities/RuteActivity.kt
AzharRivaldi
392,888,909
false
null
package com.azhar.tambalban.view.activities import android.app.Activity import android.app.ProgressDialog import android.content.Intent import android.graphics.Color import android.net.Uri import android.os.Build import android.os.Bundle import android.view.MenuItem import android.view.View import android.view.WindowManager import android.widget.* import androidx.appcompat.app.AppCompatActivity import androidx.lifecycle.ViewModelProvider import androidx.lifecycle.ViewModelProvider.NewInstanceFactory import com.azhar.tambalban.R import com.azhar.tambalban.data.model.details.ModelDetail import com.azhar.tambalban.viewmodel.MainViewModel import com.google.android.gms.maps.CameraUpdateFactory import com.google.android.gms.maps.GoogleMap import com.google.android.gms.maps.OnMapReadyCallback import com.google.android.gms.maps.SupportMapFragment import com.google.android.gms.maps.model.BitmapDescriptorFactory import com.google.android.gms.maps.model.LatLng import com.google.android.gms.maps.model.MarkerOptions import im.delight.android.location.SimpleLocation import kotlinx.android.synthetic.main.activity_rute.* import java.util.* class RuteActivity : AppCompatActivity(), OnMapReadyCallback, DirectionCallback { lateinit var mapsView: GoogleMap lateinit var progressDialog: ProgressDialog lateinit var mainViewModel: MainViewModel lateinit var simpleLocation: SimpleLocation lateinit var strPlaceId: String lateinit var strNamaLokasi: String lateinit var strNamaJalan: String lateinit var strRating: String lateinit var strPhone: String lateinit var fromLatLng: LatLng lateinit var toLatLng: LatLng lateinit var strCurrentLocation: String var strCurrentLatitude = 0.0 var strLatitude = 0.0 var strCurrentLongitude = 0.0 var strLongitude = 0.0 var strOpenHour: List<String> = ArrayList() override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_rute) if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { window.decorView.systemUiVisibility = (View.SYSTEM_UI_FLAG_LAYOUT_STABLE or View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN or View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR) } if (Build.VERSION.SDK_INT >= 21) { setWindowFlag(this, WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS, false) window.statusBarColor = Color.TRANSPARENT } progressDialog = ProgressDialog(this) progressDialog.setTitle("<NAME>…") progressDialog.setCancelable(false) progressDialog.setMessage("sedang menampilkan detail rute") setSupportActionBar(toolbar) if (supportActionBar != null) { supportActionBar?.setDisplayHomeAsUpEnabled(true) supportActionBar?.setDisplayShowTitleEnabled(false) } simpleLocation = SimpleLocation(this) if (!simpleLocation.hasLocationEnabled()) { SimpleLocation.openSettings(this) } //get location strCurrentLatitude = simpleLocation.latitude strCurrentLongitude = simpleLocation.longitude //set location lat long strCurrentLocation = "$strCurrentLatitude,$strCurrentLongitude" val supportMapFragment = supportFragmentManager.findFragmentById(R.id.mapFragment) as SupportMapFragment supportMapFragment.getMapAsync(this) //get data intent from adapter val intent = intent val bundle = intent.extras if (bundle != null) { strPlaceId = bundle["placeId"] as String strLatitude = bundle["lat"] as Double strLongitude = bundle["lng"] as Double strNamaJalan = bundle["vicinity"] as String //latlong origin & destination fromLatLng = LatLng(strCurrentLatitude, strCurrentLongitude) toLatLng = LatLng(strLatitude, strLongitude) //viewmodel mainViewModel = ViewModelProvider(this, NewInstanceFactory()).get(MainViewModel::class.java) mainViewModel.setDetailLocation(strPlaceId) progressDialog.show() mainViewModel.getDetailLocation().observe(this, { modelDetail: ModelDetail -> strNamaLokasi = modelDetail.name strPhone = modelDetail.formatted_phone_number strRating = (modelDetail.rating.toString()) //rating val newValue = modelDetail.rating.toFloat() ratingBar.setNumStars(5) ratingBar.setStepSize(0.5.toDouble()) ratingBar.setRating(newValue) //set text detail location tvNamaLokasi.setText(strNamaLokasi) tvNamaJalan.setText(strNamaJalan) if (strRating == "0.0") { tvRating.setText("Tempat belum memiliki rating!") } else { tvRating.setText(strRating) } //jam operasional try { strOpenHour = modelDetail.modelOpening.weekdayText val stringBuilder = StringBuilder() for (strList in strOpenHour) { stringBuilder.append(strList) } tvJamOperasional.text = "Jam Operasional :" tvJamOperasional.setTextColor(Color.BLACK) tvJamBuka.text = stringBuilder.toString() tvJamBuka.setTextColor(Color.BLACK) imageTime.setBackgroundResource(R.drawable.ic_time) } catch (e: Exception) { e.printStackTrace() tvJamOperasional.text = "Bengkel Tutup Sementara" tvJamOperasional.setTextColor(Color.RED) tvJamBuka.visibility = View.GONE imageTime.setBackgroundResource(R.drawable.ic_block) } //intent open google maps llRoute.setOnClickListener { val intent = Intent(Intent.ACTION_VIEW, Uri.parse("http://maps.google.com/maps?daddr=$strLatitude,$strLongitude")) startActivity(intent) } //intent to call number llPhone.setOnClickListener { val intent: Intent intent = Intent(Intent.ACTION_DIAL, Uri.parse("tel:$strPhone")) startActivity(intent) } //intent to share location llShare.setOnClickListener { val strUri = "http://maps.google.com/maps?saddr=$strLatitude,$strLongitude" val intent = Intent(Intent.ACTION_SEND) intent.type = "text/plain" intent.putExtra(Intent.EXTRA_SUBJECT, strNamaLokasi) intent.putExtra(Intent.EXTRA_TEXT, strUri) startActivity(Intent.createChooser(intent, "Bagikan :")) } //show route showDirection() progressDialog.dismiss() }) } } private fun showDirection() { //get latlong for polyline GoogleDirection.withServerKey("YOUR API KEY") .from(fromLatLng) .to(toLatLng) .transportMode(TransportMode.DRIVING) .execute(this) } override fun onMapReady(googleMap: GoogleMap) { mapsView = googleMap mapsView.isMyLocationEnabled = true mapsView.setPadding(0, 60, 0, 0) mapsView.animateCamera(CameraUpdateFactory.newLatLngZoom(fromLatLng, 14f)) } override fun onDirectionSuccess(direction: Direction) { if (direction.isOK) { //show distance & duration val route = direction.routeList[0] val leg = route.legList[0] val distanceInfo = leg.distance val durationInfo = leg.duration val strDistance = distanceInfo.text val strDuration = durationInfo.text.replace("mins", "mnt") tvDistance.text = "Jarak lokasi tujuan dari rumah kamu $strDistance dan waktu tempuh sekitar $strDuration" //set marker current location mapsView.addMarker(MarkerOptions() .title("Lokasi Kamu") .position(fromLatLng) .icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_RED))) //set marker destination mapsView.addMarker(MarkerOptions() .title(strNamaLokasi) .position(toLatLng) .icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_RED))) //show polyline val directionPositionList = direction.routeList[0].legList[0].directionPoint mapsView.addPolyline(DirectionConverter.createPolyline(this, directionPositionList, 6, Color.RED)) } } override fun onDirectionFailure(t: Throwable) { Toast.makeText(this, "Oops, gagal menampilkan rute!", Toast.LENGTH_SHORT).show() } override fun onOptionsItemSelected(item: MenuItem): Boolean { if (item.itemId == android.R.id.home) { finish() return true } return super.onOptionsItemSelected(item) } companion object { fun setWindowFlag(activity: Activity, bits: Int, on: Boolean) { val window = activity.window val layoutParams = window.attributes if (on) { layoutParams.flags = layoutParams.flags or bits } else { layoutParams.flags = layoutParams.flags and bits.inv() } window.attributes = layoutParams } } }
0
null
7
9
c86d49290f44ab1b08f660f175819836362d4a0f
9,936
Tambal-Ban
Apache License 2.0
app/src/main/java/com/chalkbox/propertyfinder/property/details/content/PropertyAmenitiesPresenter.kt
RiversideOtters
250,147,724
false
null
package com.chalkbox.propertyfinder.property.details.content import android.content.Context import android.view.View import com.chalkbox.propertyfinder.R import com.chalkbox.propertyfinder.dto.pojos.PropertyAmenity import com.chalkbox.propertyfinder.views.RecyclerViewDivider import kotlinx.android.synthetic.main.property_create_unit_other_details.view.* class PropertyAmenitiesPresenter( context: Context, identifier: String, sortOrder: Int, private val amenities: List<PropertyAmenity> ) : PropertyContentPresenter<PropertyAmenity>(identifier, sortOrder) { override val showDivider: Boolean = true override val contentResId: Int = R.layout.property_create_unit_other_details override val heading: String = context.resources.getString(R.string.unit_amenities_header) private var adapter: PropertyAmenitiesAdapter<PropertyAmenity> = PropertyAmenitiesAdapter( context, amenities ) override val shouldShow: Boolean get() = !amenities.isNullOrEmpty() override fun bindView(view: View) { super.bindView(view) view.recycler_view.adapter = adapter view.recycler_view.addItemDecoration(RecyclerViewDivider(view.context)) } }
0
Kotlin
0
0
92c3be6363c19a68493fd91546e1bd373bc5ae82
1,242
PropertyFinder-Android
MIT License
src/commonMain/kotlin/matt/time/cron/cron.kt
mgroth0
532,381,128
false
null
package matt.time.cron import kotlinx.serialization.InternalSerializationApi import kotlinx.serialization.KSerializer import kotlinx.serialization.Serializable import kotlinx.serialization.encoding.Decoder import kotlinx.serialization.encoding.Encoder import kotlinx.serialization.serializer import matt.lang.anno.SeeURL @OptIn(InternalSerializationApi::class) object PosixCronSerializer: KSerializer<PosixCron> { override val descriptor by lazy { String::class.serializer().descriptor } override fun deserialize(decoder: Decoder): PosixCron { val s = decoder.decodeString() val parts = s.split(" ") return PosixCron( minutes = parts[0], hours = parts[1], dayOfMonth = parts[2], month = parts[3], dayOfWeek = parts[4] ) } override fun serialize(encoder: Encoder, value: PosixCron) { encoder.encodeString(value.format()) } } @Serializable(with = PosixCronSerializer::class) @SeeURL("https://docs.github.com/en/actions/using-workflows/events-that-trigger-workflows#schedule") @SeeURL("https://pubs.opengroup.org/onlinepubs/9699919799/utilities/crontab.html#tag_20_25_07") data class PosixCron( val minutes: String, val hours: String, val dayOfMonth: String, val month: String, val dayOfWeek: String, ) { fun format() = listOf( minutes, hours, dayOfMonth, month, dayOfWeek, ).joinToString(separator = " ") } @OptIn(InternalSerializationApi::class) object QuotedPosixCronSerializer: KSerializer<QuotedPosixCron> { internal const val quoteChar = "'" override val descriptor by lazy { String::class.serializer().descriptor } override fun deserialize(decoder: Decoder): QuotedPosixCron { val s = decoder.decodeString() val parts = s.removeSurrounding(quoteChar).split(" ") return QuotedPosixCron( PosixCron( minutes = parts[0], hours = parts[1], dayOfMonth = parts[2], month = parts[3], dayOfWeek = parts[4] ) ) } override fun serialize(encoder: Encoder, value: QuotedPosixCron) { encoder.encodeString(value.format()) } } @Serializable(with = QuotedPosixCronSerializer::class) class QuotedPosixCron(val posixCron: PosixCron) { fun format() = QuotedPosixCronSerializer.quoteChar + posixCron.format() + QuotedPosixCronSerializer.quoteChar }
0
Kotlin
0
0
d8ccb7f55c79de7135d91586364388a6d670a7d5
2,237
time
MIT License
rpistream/app/src/main/java/com/anookday/rpistream/stream/StreamService.kt
freddyshim
272,417,335
true
{"C": 4346131, "Assembly": 1351484, "C++": 793552, "HTML": 709937, "Java": 487546, "Shell": 436148, "Makefile": 361895, "Kotlin": 162210, "CMake": 49007, "CSS": 43589, "Roff": 37236, "M4": 35573, "JavaScript": 34594, "Batchfile": 8390, "Rich Text Format": 648}
package com.anookday.rpistream.stream import android.app.NotificationChannel import android.app.NotificationManager import android.app.Service import android.content.Context import android.content.Intent import android.graphics.Bitmap import android.graphics.Canvas import android.graphics.ImageFormat import android.graphics.Paint import android.hardware.usb.UsbManager import android.media.MediaCodec import android.media.MediaFormat import android.media.MediaRecorder import android.os.IBinder import android.view.SurfaceView import androidx.core.app.NotificationCompat import com.anookday.rpistream.R import com.anookday.rpistream.pi.CommandType import com.anookday.rpistream.pi.PiRouter import com.anookday.rpistream.repository.database.AudioConfig import com.anookday.rpistream.repository.database.VideoConfig import com.pedro.encoder.Frame import com.pedro.encoder.audio.AudioEncoder import com.pedro.encoder.audio.GetAacData import com.pedro.encoder.input.audio.MicrophoneManager import com.pedro.encoder.utils.yuv.YUVUtil import com.pedro.encoder.video.FormatVideoEncoder import com.pedro.encoder.video.GetVideoData import com.pedro.encoder.video.VideoEncoder import com.serenegiant.usb.USBMonitor import com.serenegiant.usb.UVCCamera import kotlinx.coroutines.* import kotlinx.coroutines.sync.Mutex import kotlinx.coroutines.sync.withLock import net.ossrs.rtmp.ConnectCheckerRtmp import net.ossrs.rtmp.SrsFlvMuxer import timber.log.Timber import java.lang.ref.WeakReference import java.net.InetAddress import java.nio.ByteBuffer import kotlin.time.ExperimentalTime import kotlin.time.measureTimedValue const val STREAM_SERVICE_NOTIFICATION_ID = 123456 const val STREAM_SERVICE_NAME = "RPi Streamer | Stream Service" /** * Service that handles streaming video output from UVCCamera and audio output from an audio input * source to a designated web server. */ class StreamService() : Service() { companion object { private var usbManager: UsbManager? = null private var camera: UVCCamera? = null private var srsFlvMuxer: SrsFlvMuxer? = null private var notificationManager: NotificationManager? = null private var streamTimer: StreamTimer? = null private var videoFormat: MediaFormat? = null private var audioFormat: MediaFormat? = null private var piRouter: PiRouter? = null private var openGLContext: OpenGLContext? = null private var renderer: StreamGLRenderer? = null private var videoEncoder: VideoEncoder? = null private var audioEncoder: AudioEncoder? = null private var connectChecker: ConnectCheckerRtmp? = null private var view: WeakReference<SurfaceView>? = null var width = 1920 var height = 1080 private var bitmap: Bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888) var videoEnabled = false var audioEnabled = false var isStreaming = false var isPreview = false var isAeEnabled = false var drawToView = false var videoBitrate: Int get() = videoEncoder?.bitRate ?: 0 set(bitrate) = videoEncoder?.setVideoBitrateOnFly(bitrate) ?: Unit /** * Microphone manager class */ private val microphoneManager: MicrophoneManager = MicrophoneManager { frame -> audioEncoder?.inputPCMData(frame) } fun init(context: Context, surfaceView: SurfaceView, connectCheckerRtmp: ConnectCheckerRtmp) { val newOpenGLContext = OpenGLContext() val newRenderer = StreamGLRenderer(newOpenGLContext, context) newOpenGLContext.setEGLContextClientVersion(3) newOpenGLContext.setRenderer(newRenderer) newOpenGLContext.renderMode = OpenGLContext.RENDERMODE_WHEN_DIRTY newOpenGLContext.surfaceCreated(null) openGLContext = newOpenGLContext renderer = newRenderer view = WeakReference<SurfaceView>(surfaceView) camera = UVCCamera() connectChecker = connectCheckerRtmp piRouter = PiRouter(context) } private fun reverseBuf(buf: ByteBuffer, width: Int, height: Int) { var i = 0 val tmp = ByteArray(width * 4) while (i++ < height / 2) { buf[tmp] System.arraycopy( buf.array(), buf.limit() - buf.position(), buf.array(), buf.position() - width * 4, width * 4 ) System.arraycopy(tmp, 0, buf.array(), buf.limit() - buf.position(), width * 4) } buf.rewind() } fun onDrawFrame(buffer: ByteBuffer, width: Int, height: Int) { reverseBuf(buffer, width, height) bitmap.copyPixelsFromBuffer(buffer) if (isStreaming) { val input = IntArray(bitmap.width * bitmap.height) bitmap.getPixels(input, 0, width, 0, 0, width, height) val yuvBuf = YUVUtil.ARGBtoYUV420SemiPlanar(input, width, height) videoEncoder?.inputYUVData(Frame(yuvBuf, 0, false, ImageFormat.NV21)) } // send buffer to SurfaceView UI if (drawToView) { view?.get()?.let { val viewWidth = if (it.width > 0) it.width else 1920 val viewHeight = if (it.height > 0) it.height else 1080 val scaledBitmap = Bitmap.createScaledBitmap(bitmap, viewWidth, viewHeight, true) val holder = it.holder var canvas: Canvas? = null canvas = holder.lockCanvas() if (canvas == null) return@let canvas.drawBitmap(scaledBitmap, 0f, 0f, Paint()) synchronized(holder) { it.onDrawForeground(canvas) } holder.unlockCanvasAndPost(canvas) } } } /** * Start camera preview if preview is currently disabled. * * @param streamWidth Width of stream output frame in px. * @param height Height of stream output frame in px. */ private fun startPreview(streamWidth: Int, streamHeight: Int, context: Context) { camera?.let { width = streamWidth height = streamHeight renderer?.startPiCameraPreview(it, width, height, context) isPreview = true Timber.v("RPISTREAM preview enabled") } } /** * Stop camera preview if preview is currently enabled. */ private fun stopPreview() { renderer?.stopPiCameraPreview() isPreview = false Timber.v("RPISTREAM preview disabled") } /** * Start camera preview if preview is currently disabled. * * @param streamWidth Width of stream output frame in px. * @param height Height of stream output frame in px. */ fun startFrontPreview(context: Context) { renderer?.showFrontCamera(context) } /** * Stop camera preview if preview is currently enabled. */ fun stopFrontPreview() { renderer?.hideFrontCamera() } fun destroyFrontCamera() { renderer?.stopFrontCameraPreview() } /** * Enable video input for streaming. */ fun enableCamera(ctrlBlock: USBMonitor.UsbControlBlock?, config: VideoConfig?, context: Context): String? { val numSkipFrames = 2 var currentFrame = 0 var currentExposure = 500 camera = UVCCamera() camera?.let { it.open(ctrlBlock) if (config != null) { it.setPreviewSize(config.width, config.height, UVCCamera.FRAME_FORMAT_MJPEG) startPreview(config.width, config.height, context) videoEnabled = true } it.setFrameCallback( { frame -> // process image if (isAeEnabled) { frame.rewind() val byteArray = ByteArray(frame.remaining()) frame.get(byteArray) if (currentFrame >= numSkipFrames) { config?.let { currentExposure = processImage(byteArray, config, currentExposure) } currentFrame = 0 } currentFrame++ } }, UVCCamera.PIXEL_FORMAT_YUV420SP ) } return camera?.deviceName } @OptIn(ExperimentalTime::class) fun processImage(byteArray: ByteArray, config: VideoConfig, currentExposure: Int): Int { val lumLimit = 255 val maxLum = 194 val minLum = 61 val targetLum = minLum + (maxLum - minLum) / 2 val exposureAbsoluteMinimum = 15 val exposureAbsoluteLimit = 1000 val alpha = 0.25f val scale = exposureAbsoluteLimit / lumLimit var exposure = currentExposure val (lum, duration) = measureTimedValue { getAverageLuminanceOfCenterBox(byteArray, config.width, config.height) //getAvgLumWithNd4j(byteArray, config.width, config.height) //getAvgLumWithMultik(byteArray, config.width, config.height) } //Timber.d("Average Luminance: $lum") //Timber.d("Average luminance calculation time (ms): ${duration.inMilliseconds}") if (lum < minLum || lum > maxLum) { exposure = (currentExposure + alpha * (scale * (targetLum - lum))).toInt() if (exposure > exposureAbsoluteLimit) exposure = exposureAbsoluteLimit else if (exposure < exposureAbsoluteMinimum) exposure = exposureAbsoluteMinimum //Timber.d("Exposure Absolute Time: $exposure") piRouter?.routeCommand(CommandType.EXPOSURE_TIME, exposure.toString()) } return exposure } //@OptIn(ExperimentalUnsignedTypes::class) //private fun getAvgLumWithNd4j( // image: ByteArray, // imageWidth: Int, // imageHeight: Int, // boxWidth: Int = 640, // boxHeight: Int = 360 //): Int { // val size = boxWidth * boxHeight // val xStart = (imageWidth - boxWidth) / 2 // val xEnd = xStart + boxWidth // val yStart = (imageHeight - boxHeight) / 2 // val yEnd = yStart + boxHeight // var list: IntArray = intArrayOf() // for (i in 0..size) { // list += image[i].toUByte().toInt() // } // val arr: INDArray = Nd4j.createFromArray(list.toTypedArray()) // val shape = intArrayOf(imageWidth, imageHeight) // arr.reshape(shape) // val box = arr.get(interval(xStart, xEnd), interval(yStart, yEnd)) // return box.sumNumber().toByte().toUByte().toInt() //} //@OptIn(ExperimentalUnsignedTypes::class) //private fun getAvgLumWithMultik( // image: ByteArray, // imageWidth: Int, // imageHeight: Int, // boxWidth: Int = 640, // boxHeight: Int = 360 //): Int { // val size = boxWidth * boxHeight // val xStart = (imageWidth - boxWidth) / 2 // val xEnd = xStart + boxWidth // val yStart = (imageHeight - boxHeight) / 2 // val yEnd = yStart + boxHeight // val img = mk.ndarray(image.toList().subList(0, size), imageWidth, imageHeight) // val box = img[xStart..xEnd, yStart..yEnd] // val sum: Byte = box.sum() // return sum.toUByte().toInt() //} /** * Returns the mean luminance value (range of 0-255) of a horizontally and vertically * centered box within an image luminance matrix. * @param image byte buffer of an image in YUV format * @param imageWidth pixel length of image * @param imageHeight pixel height of image * @param boxWidth pixel length of center box * @param boxHeight pixel height of center box */ @OptIn(ExperimentalUnsignedTypes::class) private fun getAverageLuminanceOfCenterBox( image: ByteArray, imageWidth: Int, imageHeight: Int, boxWidth: Int = 640, boxHeight: Int = 360 ): Int { val size = boxWidth * boxHeight val xStart = (imageWidth - boxWidth) / 2 val xEnd = xStart + boxWidth val yStart = (imageHeight - boxHeight) / 2 val yEnd = yStart + boxHeight var sum = 0 for (x in xStart until xEnd) { for (y in yStart until yEnd) { val index = y * imageWidth + x sum += image[index].toUByte().toInt() } } return sum / size } /** * Stop the current stream and preview. Destroy camera instance if initialized. */ fun disableCamera() { if (isPreview) stopPreview() camera?.destroy() camera = null videoEnabled = false } /** * Enable audio input for streaming. */ fun enableAudio() { audioEnabled = true } /** * Disable audio input for streaming. */ fun disableAudio() { audioEnabled = false } /** * Prepare video and audio input for streaming. Return true if at least one of them are * prepared for streaming. */ fun prepareStream(videoConfig: VideoConfig?, audioConfig: AudioConfig?): Boolean { if (isStreaming) return false srsFlvMuxer = SrsFlvMuxer(connectChecker) videoEncoder = VideoEncoder(object : GetVideoData { override fun onVideoFormat(mediaFormat: MediaFormat) { videoFormat = mediaFormat } override fun onSpsPpsVps(sps: ByteBuffer, pps: ByteBuffer, vps: ByteBuffer) { if (isStreaming) { srsFlvMuxer?.setSpsPPs(sps, pps) } } override fun onSpsPps(sps: ByteBuffer, pps: ByteBuffer) { if (isStreaming) { srsFlvMuxer?.setSpsPPs(sps, pps) } } override fun getVideoData(h264Buffer: ByteBuffer, info: MediaCodec.BufferInfo) { if (isStreaming) { srsFlvMuxer?.sendVideo(h264Buffer, info) } } }) audioEncoder = AudioEncoder(object : GetAacData { override fun onAudioFormat(mediaFormat: MediaFormat?) { audioFormat = mediaFormat } override fun getAacData(aacBuffer: ByteBuffer, info: MediaCodec.BufferInfo) { if (isStreaming && audioEnabled) { srsFlvMuxer?.sendAudio(aacBuffer, info) } } }) val videoCheck = prepareVideo(videoConfig) val audioCheck = prepareAudio(audioConfig) return videoCheck && audioCheck } /** * Start streaming to given url. * * @param uvcCamera UVC Camera module. * @param url URL of the stream's designated location (eg. rtmp://live.twitch.tv/app/{stream_key}) */ fun startStream(url: String) { startEncoders() srsFlvMuxer?.let { videoEncoder?.let { ve -> if (ve.rotation == 90 && ve.rotation == 270) { it.setVideoResolution(ve.height, ve.width) } else { it.setVideoResolution(ve.width, ve.height) } it.start(url) isStreaming = true } } } /** * Prepare encoders before streaming. */ private fun startEncoders() { videoEncoder?.start() audioEncoder?.start() microphoneManager.start() } /** * Prepare to stream video. Return true iff system is able and ready to stream video output. * * @param config Video configuration object * * @return true if success, otherwise false. */ @OptIn(ExperimentalTime::class) private fun prepareVideo(config: VideoConfig?): Boolean { if (videoEncoder == null || config == null) return false return videoEncoder!!.prepareVideoEncoder( config.width, config.height, config.fps, config.bitrate, config.rotation, config.hardwareRotation, config.iFrameInterval, FormatVideoEncoder.YUV420SEMIPLANAR ) } /** * Prepare to stream audio. Return true iff system is able and ready to stream audio output. * * @param config Audio configuration object * * @return true if success, otherwise false. */ private fun prepareAudio(config: AudioConfig?): Boolean { if (audioEncoder == null || config == null) return false microphoneManager.createMicrophone( MediaRecorder.AudioSource.MIC, config.sampleRate, config.stereo, config.echoCanceler, config.noiseSuppressor ) srsFlvMuxer?.let { it.setIsStereo(config.stereo) it.setSampleRate(config.sampleRate) } return audioEncoder!!.prepareAudioEncoder( config.bitrate, config.sampleRate, config.stereo, microphoneManager.maxInputSize ) } /** * Stops the stream. */ fun stopStream() { Timber.d("stopping stream...") if (isStreaming) { videoEncoder?.stop() audioEncoder?.stop() srsFlvMuxer?.stop() videoEncoder = null audioEncoder = null srsFlvMuxer = null isStreaming = false } streamTimer?.reset() } } override fun onCreate() { super.onCreate() Timber.v("Stream service created") usbManager = getSystemService(USB_SERVICE) as UsbManager notificationManager = getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager val channel = NotificationChannel( STREAM_SERVICE_NAME, STREAM_SERVICE_NAME, NotificationManager.IMPORTANCE_LOW ) notificationManager?.createNotificationChannel(channel) val notificationBuilder = NotificationCompat.Builder(this, STREAM_SERVICE_NAME) .setOngoing(true) .setContentTitle(STREAM_SERVICE_NAME) .setSmallIcon(R.drawable.raspi_pgb001) .setContentText("Streaming: 00:00:00") streamTimer = object : StreamTimer() { override fun updateNotification() { notificationBuilder.setContentText("Streaming: ${this.getTimeElapsedString()}") notificationManager?.notify( STREAM_SERVICE_NOTIFICATION_ID, notificationBuilder.build() ) } } startForeground(STREAM_SERVICE_NOTIFICATION_ID, notificationBuilder.build()) streamTimer?.start() } override fun onBind(p0: Intent?): IBinder? { return null } override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int { Timber.v("Stream service started") val endpoint = intent?.extras?.getString("endpoint") if (endpoint != null) { startStream(endpoint) } return START_STICKY } override fun onDestroy() { super.onDestroy() stopStream() } }
0
C
0
0
0ea1fd84a42cc77b4993ab53e81bf3ba165c682d
21,023
RPi-Video-Streamer
Apache License 2.0
app/src/main/java/com/bsuir/bsuirschedule/domain/models/EmployeeSubject.kt
Saydullin
526,953,048
false
{"Kotlin": 543814, "HTML": 7301}
package com.bsuir.bsuirschedule.domain.models import com.bsuir.bsuirschedule.data.db.entities.EmployeeTable import kotlin.collections.ArrayList data class EmployeeSubject( val id: Int, var title: String?, val firstName: String, val lastName: String, val middleName: String?, val degree: String?, val degreeAbbrev: String?, val rank: String?, val photoLink: String, val calendarId: String?, val email: String?, val department: List<String>?, var departmentsList: ArrayList<Department>?, val urlId: String, val jobPosition: String? ) { companion object { val empty = EmployeeSubject( id = -1, title = "", firstName = "", lastName = "", middleName = "", degree = "", degreeAbbrev = "", rank = "", photoLink = "", calendarId = "", email = "", department = listOf(), departmentsList = arrayListOf(), urlId = "", jobPosition = "" ) } fun toSavedSchedule() = SavedSchedule( id = id, employee = this.toEmployeeTable().toEmployee(), group = Group.empty, isGroup = false, lastUpdateTime = 0, lastUpdateDate = 0, isUpdatedSuccessfully = false, isExistExams = false ) fun toEmployeeTable() = EmployeeTable( id = id, title = title ?: "", firstName = firstName, lastName = lastName, middleName = middleName ?: "", fullName = getFullName(), degree = degree ?: "", degreeAbbrev = degreeAbbrev ?: "", rank = rank ?: "", email = email ?: "", photoLink = photoLink, calendarId = calendarId ?: "", jobPosition = jobPosition ?: "", academicDepartment = department ?: listOf(), departments = departmentsList?.map { it.toDepartmentTable() } ?: listOf(), isSaved = null, urlId = urlId, ) fun toEmployee() = Employee( id = id, title = title ?: "", firstName = firstName, lastName = lastName, middleName = middleName, degreeFull = degree, degreeAbbrev = degreeAbbrev, rank = rank, photoLink = photoLink, calendarId = calendarId, email = email, departmentsAbbrList = department, departments = departmentsList ?: arrayListOf(), urlId = urlId, isSaved = false ) fun getFullDepartments(separator: String): String { return departmentsList?.joinToString(separator) { dep -> "${dep.abbrev.replaceFirstChar { it.lowercase() }} - ${dep.name.lowercase()}" } ?: "" } fun getShortDepartments(separator: String): String { if (departmentsList.isNullOrEmpty()) return "" return departmentsList!![0].abbrev.replaceFirstChar { it.lowercase() } + if (departmentsList!!.size > 1) { ", $separator ${departmentsList!!.size - 1}" } else "" } fun getRankAndDegree() = "${degreeAbbrev ?: ""} ${rank ?: ""}".trim() fun getTitleOrFullName(): String { if (title.isNullOrEmpty()) { return getFullName() } return "${getName()} ($title)" } fun getFullName() = "$lastName $firstName $middleName" fun getName(): String { val firstNameLetter = if (firstName != "") "${firstName[0]}." else "" val middleNameLetter = if (middleName != "") "${middleName?.get(0)}" else "" return "$lastName $firstNameLetter $middleNameLetter".trim() } }
0
Kotlin
0
4
989325e764d14430d5d124efd063f7190b075f4a
3,680
BSUIR_Schedule
Creative Commons Zero v1.0 Universal
tasks-3/lib/src/main/kotlin/flows/algo/FordFulkersonMethod.kt
AzimMuradov
472,473,231
false
null
package flows.algo import flows.structures.Matrix import flows.structures.Network /** * The Ford-Fulkerson Method. */ internal inline fun <V> Network<V>.calculateFordFulkersonMethodMaxflow( findPositivePath: (Matrix<V, UInt>) -> Sequence<Pair<V, V>>, ): UInt { var maxflow = 0u val residualNetworkCapacities = Matrix.empty(keys = graph.vertices, noValue = 0u).apply { for ((v, u, cap) in graph.edges) { set(v, u, cap) } } while (true) { val path = findPositivePath(residualNetworkCapacities) val augFlow = path.minOfOrNull { (v, p) -> residualNetworkCapacities[p, v] } ?: break maxflow += augFlow for ((v, p) in path) { residualNetworkCapacities[p, v] -= augFlow residualNetworkCapacities[v, p] += augFlow } } return maxflow }
0
Kotlin
0
0
01c0c46df9dc32c2cc6d3efc48b3a9ee880ce799
856
discrete-math-spbu
Apache License 2.0
app/src/main/java/com/tsundoku/models/Website.kt
Sigrec
776,261,260
false
{"Kotlin": 181746}
package com.tsundoku.models enum class Website { ANILIST, MANGADEX }
0
Kotlin
0
0
190a4b051bb5ad5664d73a2e5dd36be713ea75a7
77
TsundokuAndroid
MIT License
src/main/kotlin/com/digitalreasoning/langpredict/util/NGramGenerator.kt
MJMalone
118,636,650
true
{"Kotlin": 44995, "Groovy": 29696}
package com.digitalreasoning.langpredict.util const val NGRAM_SIZE = 3 class NGramGenerator { fun generate(text: String): List<String> = text .map { CharacterNormalizer.normalize(it) } .joinToString("") .split(' ') .filter { it.length < 3 || it.any { !it.isUpperCase() } } .flatMap { getGrams(it) } private fun getGrams(word: String): List<String> = when (word.length) { 0 -> emptyList() 1 -> listOf(word, " $word", "$word ", " $word ") 2 -> listOf(word.substring(0,1), word.substring(1,2), " ${word[0]}", "${word[1]} ", word, " $word", "$word ") 3 -> listOf( word.substring(0,1), word.substring(1,2), word.substring(2,3), // 3 unigrams (a,b,c) " ${word[0]}", word.substring(0,2), word.substring(1,3), "${word[2]} ", // 4 bigrams (" a", "ab", "bc", "c ") " ${word.substring(0,2)}", word, "${word.substring(1,3)} " // 3 trigrams (" ab", "abc", "bc " ) else -> getInnerGrams(word) + " ${word[0]}" + " ${word[0]}${word[1]}" + // 2 leading grams (" a", " ab") "${word[word.length-1]} " + "${word[word.length-2]}${word[word.length-1]} " // 2 trailing grams ("z ", "yz ") } // Only called on words of length > 3 private fun getInnerGrams(word: String): List<String> = (3..word.length) .flatMap { end -> listOf( word.substring(end - 1, end), word.substring(end - 2, end), word.substring(end - 3, end)) } + word.substring(0,1) + word.substring(1,2) + word.substring(0,2) } internal class OLD_NGram { private var grams: StringBuffer = StringBuffer(" ") private var capitalword: Boolean = false /** * Append a character into ngram buffer. * @param ch */ fun addChar(ch: Char) { val normCh = CharacterNormalizer.normalize(ch) val lastchar = grams.last() if (lastchar == ' ') { grams = StringBuffer(" ") capitalword = false if (normCh == ' ') return } else if (grams.length >= NGRAM_SIZE) { grams.deleteCharAt(0) } grams.append(normCh) if (Character.isUpperCase(normCh)) { if (Character.isUpperCase(lastchar)) capitalword = true } else { capitalword = false } } /** * Get n-Gram * @param n length of n-gram * @return n-Gram String (null if it is invalid) */ operator fun get(n: Int): String? { if (capitalword) return null val len = grams.length if (n < 1 || n > 3 || len < n) return null if (n == 1) { val ch = grams[len - 1] return if (ch == ' ') null else Character.toString(ch) } else { return grams.substring(len - n, len) } } }
0
Kotlin
0
0
be5badebb71586a770cbda52cb223b1278537406
2,997
lang-predict
Apache License 2.0
shared/src/commonMain/kotlin/com/mocoding/pokedex/data/repository/PokemonRepository.kt
MohamedRejeb
606,436,499
false
{"Kotlin": 123809, "Swift": 6252, "Ruby": 2298}
package com.mocoding.pokedex.data.repository import com.mocoding.pokedex.core.model.Pokemon import com.mocoding.pokedex.core.model.PokemonInfo import kotlinx.coroutines.flow.Flow interface PokemonRepository { suspend fun getPokemonList(page: Long): Result<List<Pokemon>> suspend fun getPokemonFlowByName(name: String): Result<PokemonInfo> suspend fun getFavoritePokemonListFlow(): Flow<List<Pokemon>> suspend fun updatePokemonFavoriteState(name: String, isFavorite: Boolean) }
4
Kotlin
48
569
e13c46fdcff7b21353019da9a85438e2088c529d
497
Pokedex
Apache License 2.0
app/src/main/kotlin/io/armcha/ribble/presentation/navigation/Screen.kt
armcha
98,714,221
false
null
package io.armcha.ribble.presentation.navigation import android.support.v4.app.Fragment /** * Created by Chatikyan on 21.09.2017. */ data class Screen(val fragment: Fragment, val backStrategy: BackStrategy)
6
Kotlin
120
879
815beaeb7c6c3f5d7d5c32aa60172372b2e5a844
210
Ribble
Apache License 2.0
app/src/main/java/io/github/kartoffelsup/nuntius/ui/home/HomeScreen.kt
kartoffelsup
250,324,791
false
null
package io.github.kartoffelsup.nuntius.ui.home import androidx.compose.foundation.Text import androidx.compose.foundation.currentTextStyle import androidx.compose.foundation.layout.* import androidx.compose.material.Button import androidx.compose.material.MaterialTheme import androidx.compose.runtime.* import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.res.stringResource import androidx.compose.ui.text.style.TextAlign import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.sp import androidx.ui.tooling.preview.Preview import io.github.kartoffelsup.nuntius.R import io.github.kartoffelsup.nuntius.api.user.result.UserContacts import io.github.kartoffelsup.nuntius.data.message.MessageService import io.github.kartoffelsup.nuntius.data.user.UserData import io.github.kartoffelsup.nuntius.data.user.UserService import io.github.kartoffelsup.nuntius.ui.AppState import io.github.kartoffelsup.nuntius.ui.components.CenteredRow import io.github.kartoffelsup.nuntius.ui.user.UserRow import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.GlobalScope import kotlinx.coroutines.launch import kotlinx.coroutines.withContext data class MessageHolder(val message: String = "") @Composable fun HomeScreen(appState: AppState, innerPadding: InnerPadding) { val user = appState.userData var messageHolder by remember { mutableStateOf(MessageHolder()) } Column(modifier = Modifier.padding(innerPadding)) { Column { CenteredRow { Text( text = "Welcome to nuntius", style = currentTextStyle().copy( fontSize = 24.sp, textAlign = TextAlign.Center ) ) } Spacer(Modifier.preferredHeight(16.dp)) if (user != null) { CenteredRow { Button(modifier = Modifier.padding(start = 5.dp, end = 5.dp), onClick = { GlobalScope.launch { val result = MessageService.send(user.userId, "Hello There!", user) withContext(Dispatchers.Main) { messageHolder = messageHolder.copy(message = result.fold({ it }, { it.messageId })) } } }) { Text(text = "Send Test Message") } Button(onClick = { UserService.logout() }) { Text(text = stringResource(R.string.logout_button_text)) } } } CenteredRow { Text(text = messageHolder.message) } } if (user != null) { Column(Modifier.fillMaxSize().then(Modifier.wrapContentSize(Alignment.Center))) { Text( modifier = Modifier.fillMaxWidth() .then(Modifier.wrapContentSize(Alignment.Center)), text = "User", style = currentTextStyle() .copy(fontSize = 24.sp, textAlign = TextAlign.Center) ) CenteredRow { UserRow(username = user.username) } } } } } data class ContactState(var open: Boolean) @Preview @Composable fun HomePreview() { MaterialTheme { HomeScreen( AppState( userData = UserData( "", "nobody", "Nobody1", UserContacts(listOf()) ) ), InnerPadding() ) } }
0
Kotlin
0
1
805a3f9718e7dad765482bb4a249ca04a5e0c77c
3,730
nuntius-app
Apache License 2.0
idea/testData/inspectionsLocal/removeRedundantSpreadOperator/doubleArrayOf.kt
JakeWharton
99,388,807
true
null
fun foo(vararg x: Double) {} fun bar() { foo(*<caret>doubleArrayOf(1.0)) }
0
Kotlin
28
83
4383335168338df9bbbe2a63cb213a68d0858104
80
kotlin
Apache License 2.0
xml/xml-psi-impl/src/com/intellij/html/embedding/HtmlCustomEmbeddedContentTokenType.kt
ingokegel
72,937,917
false
null
// Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.html.embedding import com.intellij.embedding.EmbeddingElementType import com.intellij.lang.* import com.intellij.lexer.Lexer import com.intellij.psi.PsiElement import com.intellij.psi.impl.source.tree.LazyParseableElement import com.intellij.psi.tree.ICustomParsingType import com.intellij.psi.tree.IElementType import com.intellij.psi.tree.ILazyParseableElementTypeBase import com.intellij.psi.tree.ILightLazyParseableElementType import com.intellij.util.CharTable import com.intellij.util.diff.FlyweightCapableTreeStructure import org.jetbrains.annotations.NonNls abstract class HtmlCustomEmbeddedContentTokenType : IElementType, EmbeddingElementType, ICustomParsingType, ILazyParseableElementTypeBase, ILightLazyParseableElementType { protected constructor(@NonNls debugName: String, language: Language?) : super(debugName, language) protected constructor(@NonNls debugName: String, language: Language?, register: Boolean) : super(debugName, language, register) override fun parse(text: CharSequence, table: CharTable): ASTNode = LazyParseableElement(this, text) override fun parseContents(chameleon: ASTNode): ASTNode? = doParseContents(chameleon).treeBuilt.firstChildNode override fun parseContents(chameleon: LighterLazyParseableNode): FlyweightCapableTreeStructure<LighterASTNode> { val file = chameleon.containingFile ?: error("Let's add LighterLazyParseableNode#getProject() method") return PsiBuilderFactory.getInstance().createBuilder( file.project, chameleon, createLexer(), language, chameleon.text ) .also { parse(it) } .lightTree } protected fun doParseContents(chameleon: ASTNode): PsiBuilder = PsiBuilderFactory.getInstance().createBuilder( chameleon.psi.project, chameleon, createLexer(), language, chameleon.chars ) .also { parse(it) } protected abstract fun createLexer(): Lexer protected abstract fun parse(builder: PsiBuilder) abstract fun createPsi(node: ASTNode): PsiElement }
1
null
1
2
b07eabd319ad5b591373d63c8f502761c2b2dfe8
2,155
intellij-community
Apache License 2.0
game/src/commonMain/kotlin/io/itch/mattemade/neonghost/scene/Flight.kt
mattemade
861,406,871
false
{"Kotlin": 327781, "GLSL": 27986, "JavaScript": 6107, "HTML": 920}
package io.itch.mattemade.neonghost.scene import com.littlekt.Context import com.littlekt.graphics.MutableColor import com.littlekt.graphics.g2d.Batch import com.littlekt.graphics.g2d.shape.ShapeRenderer import com.littlekt.graphics.shader.ShaderProgram import com.littlekt.graphics.toFloatBits import io.itch.mattemade.neonghost.Assets import io.itch.mattemade.neonghost.Game import io.itch.mattemade.neonghost.character.rei.Player import io.itch.mattemade.neonghost.pixelPerfectPosition import io.itch.mattemade.neonghost.shader.ParticleFragmentShader import io.itch.mattemade.neonghost.shader.ParticleVertexShader import io.itch.mattemade.neonghost.shader.Particler import io.itch.mattemade.neonghost.touch.CombinedInput import io.itch.mattemade.utils.math.fill import kotlin.math.max import kotlin.random.Random import kotlin.time.Duration class Flight( private val player: Player, context: Context, private val assets: Assets, private val input: CombinedInput, particleShader: ShaderProgram<ParticleVertexShader, ParticleFragmentShader>, val onFirstComplete: () -> Unit, val onSecondComplete: () -> Unit, ) { private val slice = assets.animation.magicalReiAnimations.idle.run { update(Duration.ZERO) currentKeyFrame!! } val width = slice.width val height = slice.height val textureData = slice.texture.textureData val centerX = player.x * 2f val centerY = player.y * 2f val frameXOffset = (slice.width * 0.1f / Game.PPU).pixelPerfectPosition val frameYOffset = (3f / Game.PPU).pixelPerfectPosition val xOffset = centerX - width / 2f * Game.IPPU - frameXOffset * 3f - Game.IPPU val yOffset = centerY - height * 2f * Game.IPPU + frameYOffset * 1.5f + 2f * Game.IPPU private val tempColor = MutableColor() private val doubles = 1 private var tintColor = MutableColor(0f, 0f, 0f, 0f) private var isFirstStage = true private val firstParticler = Particler( context, particleShader, 0f, width * height * doubles, 11000f, 2f * Game.IPPU, interpolation = 3, fillData = { index, startColor, endColor, startPosition, endPosition, activeBetween -> val x = (index / doubles) % width val y = (index / doubles) / width val pixelColor = textureData.pixmap.get(slice.x + x, slice.y + y) if (pixelColor == 0) { startColor.fill(0f) endColor.fill(0f) startPosition.fill(0f) endPosition.fill(0f) activeBetween.fill(0f) } else { tempColor.setRgba8888(pixelColor) startColor.fill(1f, 1f, 1f, tempColor.a) //endColor.fill(1f, 1f, 1f, tempColor.a) endColor.fill(tempColor.r, tempColor.g, tempColor.b, tempColor.a) startPosition.fill( centerX + Game.visibleWorldWidth * (Random.nextFloat() - 0.5f) * 8f, centerY + Game.visibleWorldHeight * (Random.nextFloat() - 0.5f) * 8f ) endPosition.fill( xOffset + x * 2 / Game.PPU, yOffset + y * 2 / Game.PPU )//xOffset + width * 2 - x / Game.PPU, yOffset + y / Game.PPU) activeBetween[0] = /*5000f +*/ Random.nextFloat() * 2000f activeBetween[1] = activeBetween[0] + 4000f + Random.nextFloat() * 4000f } }, die = { onFirstComplete() } ) private val secondParticler = Particler( context, particleShader, 0f, width * height * doubles, 11000f, 2f * Game.IPPU, interpolation = 3, fillData = { index, startColor, endColor, startPosition, endPosition, activeBetween -> val x = (index / doubles) % width val y = (index / doubles) / width val pixelColor = textureData.pixmap.get(slice.x + x, slice.y + y) if (pixelColor == 0) { startColor.fill(0f) endColor.fill(0f) startPosition.fill(0f) endPosition.fill(0f) activeBetween.fill(0f) } else { tempColor.setRgba8888(pixelColor) startColor.fill(1f, 1f, 1f, tempColor.a) //endColor.fill(1f, 1f, 1f, tempColor.a) endColor.fill(tempColor.r, tempColor.g, tempColor.b, tempColor.a) startPosition.fill( centerX + Game.visibleWorldWidth * (Random.nextFloat() - 0.5f) * 8f, centerY + Game.visibleWorldHeight * (Random.nextFloat() - 0.5f) * 8f ) endPosition.fill( xOffset + x * 2 / Game.PPU, yOffset + y * 2 / Game.PPU )//xOffset + width * 2 - x / Game.PPU, yOffset + y / Game.PPU) activeBetween[0] = /*5000f +*/ Random.nextFloat() * 2000f activeBetween[1] = activeBetween[0] + 4000f + Random.nextFloat() * 4000f } }, die = { onSecondComplete() } ) fun nextStage() { isFirstStage = false } init { player.isFacingLeft = false } private var presses = 0 private var fadeoutDelay = 2f private var fadeInDelay = 0f fun update(seconds: Float): Boolean { if (fadeoutDelay > 0f) { fadeoutDelay = max(0f, fadeoutDelay - seconds) tintColor.a = 1f - fadeoutDelay / 2f return false } if (fadeInDelay > 0f) { fadeInDelay = max(0f, fadeInDelay - seconds) tintColor.a = fadeInDelay / 2f return false } if (isFirstStage) { firstParticler.update(Duration.ZERO, seconds * 1000f, Duration.ZERO, 0f, 0f, false) } else { secondParticler.update(Duration.ZERO, seconds * 1000f, Duration.ZERO, 0f, 0f, false) } /*if (input.pressed(GameInput.ANY_ACTION)) { presses++ if (presses > 2) { complete() return true } }*/ return false } private var shapeRenderer: ShapeRenderer? = null fun render(batch: Batch) { if (shapeRenderer == null) { shapeRenderer = ShapeRenderer(batch, assets.texture.white) } shapeRenderer?.filledRectangle( x = player.x - Game.halfVisibleWorldWidth, y = player.y - Game.halfVisibleWorldHeight, width = Game.visibleWorldWidth.toFloat(), height = Game.visibleWorldHeight.toFloat(), color = tintColor.toFloatBits() ) //player.update(Duration.ZERO, 0f, Duration.ZERO) player.render(batch) firstParticler.render(batch) } }
0
Kotlin
0
0
2fb58bb49316b6045571f2e5822150748341dfc8
6,916
neon-ghost
MIT License
faker/tvshows/src/main/kotlin/io/github/serpro69/kfaker/tv/provider/FreshPriceOfBelAir.kt
serpro69
174,969,439
false
{"Kotlin": 741942, "Shell": 6192, "Makefile": 4515, "Java": 3978, "Groovy": 1144}
package io.github.serpro69.kfaker.tv.provider import io.github.serpro69.kfaker.FakerService import io.github.serpro69.kfaker.dictionary.YamlCategory import io.github.serpro69.kfaker.provider.FakeDataProvider import io.github.serpro69.kfaker.provider.YamlFakeDataProvider import io.github.serpro69.kfaker.provider.unique.LocalUniqueDataProvider import io.github.serpro69.kfaker.provider.unique.UniqueProviderDelegate /** * [FakeDataProvider] implementation for [YamlCategory.FRESH_PRINCE_OF_BEL_AIR] category. */ @Suppress("unused") class FreshPriceOfBelAir internal constructor(fakerService: FakerService) : YamlFakeDataProvider<FreshPriceOfBelAir>(fakerService) { override val yamlCategory = YamlCategory.FRESH_PRINCE_OF_BEL_AIR override val localUniqueDataProvider = LocalUniqueDataProvider<FreshPriceOfBelAir>() override val unique by UniqueProviderDelegate(localUniqueDataProvider, fakerService) init { fakerService.load(yamlCategory) } fun characters() = resolve("characters") fun actors() = resolve("actors") fun quotes() = resolve("quotes") }
21
Kotlin
42
462
22b0f971c9f699045b30d913c6cbca02060ed9b3
1,096
kotlin-faker
MIT License
Project/Choreographer/src/main/java/zachinio/choreographer/animation/ProgressImageLoader.kt
Zachinio
159,325,927
false
null
package zachinio.choreographer.animation import android.graphics.drawable.ClipDrawable import android.os.Handler import android.view.Gravity import android.view.View import android.widget.ImageView import io.reactivex.Completable import io.reactivex.CompletableEmitter class ProgressImageLoader(private val imageView: ImageView, private val step: Int, private val direction: Direction) : Animation() { var level = 0 var drawable: ClipDrawable? = null var handler = Handler() var emitter: CompletableEmitter? = null private val animateImage = Runnable { animateLevelRunnable() } override fun animate(): Completable { return Completable.create { if (step < 0 || step > 10000) { it.onComplete() return@create } emitter = it drawable = ClipDrawable(imageView.drawable, getDirection(direction), ClipDrawable.HORIZONTAL) imageView.setImageDrawable(drawable) imageView.visibility = View.VISIBLE drawable?.level = level handler.post(animateImage) } } private fun getDirection(direction: Direction): Int { return when (direction) { Direction.TOP -> Gravity.TOP Direction.BOTTOM -> Gravity.BOTTOM Direction.LEFT -> Gravity.LEFT else -> Gravity.RIGHT } } private fun animateLevelRunnable() { level += step if (level > 10000) { stopHandler() } drawable?.level = level if (level <= 10000) { handler.postDelayed(animateImage, 10) } else { stopHandler() } } private fun stopHandler() { emitter?.onComplete() handler.removeCallbacks(animateImage) } }
0
Kotlin
13
62
734270627591dd86d340d679fe428e29119fb7a7
1,815
Choreographer
MIT License
app/src/main/java/dev/logickoder/qrpay/data/api/params/Register.kt
logickoder
477,716,253
false
null
package dev.logickoder.qrpay.data.api.params import com.google.gson.annotations.SerializedName data class RegisterRequest( val name: String ) data class RegisterResponse( val `data`: Data, val error: Boolean, val message: String ) { data class Data( @SerializedName("QrPayUid") val qrPayUid: String ) }
2
Kotlin
0
3
c63163ab961f9f778bdcd33e0ff8c2dd73548230
346
qrpay
MIT License
app/src/main/java/com/thedefiapp/usecases/mappers/ConvertToOverViewBalanceListUseCase.kt
saulmaos
459,017,062
false
null
package com.thedefiapp.usecases.mappers import com.thedefiapp.data.models.OverViewBalance import com.thedefiapp.data.remote.response.ComplexProtocolListResponse import com.thedefiapp.data.remote.response.TokenWalletResponse import com.thedefiapp.usecases.balancecalculator.CalculateBalanceAndEarningsByOverviewTypeUseCase import com.thedefiapp.usecases.balancecalculator.CalculateWalletBalanceUseCase import com.thedefiapp.usecases.utils.ConvertToFormattedNumberUseCase import com.thedefiapp.utils.* import javax.inject.Inject class ConvertToOverViewBalanceListUseCase @Inject constructor( private val convertToFormattedNumberUseCase: ConvertToFormattedNumberUseCase, private val calculateWalletBalanceUseCase: CalculateWalletBalanceUseCase, private val calculateBalanceAndEarningsByOverviewTypeUseCase: CalculateBalanceAndEarningsByOverviewTypeUseCase ) { operator fun invoke( complexProtocolListResponse: List<ComplexProtocolListResponse>, tokenWalletResponse: List<TokenWalletResponse> ): List<OverViewBalance> { val wallet: Double = calculateWalletBalanceUseCase(tokenWalletResponse) val liquidityPool = calculateBalanceAndEarningsByOverviewTypeUseCase( complexProtocolListResponse, OVERVIEW_LIQUIDITY ) val deposits = calculateBalanceAndEarningsByOverviewTypeUseCase( complexProtocolListResponse, OVERVIEW_DEPOSIT ) val farming = calculateBalanceAndEarningsByOverviewTypeUseCase( complexProtocolListResponse, OVERVIEW_FARMING ) val lending = calculateBalanceAndEarningsByOverviewTypeUseCase( complexProtocolListResponse, OVERVIEW_LENDING ) val yieldBalance = calculateBalanceAndEarningsByOverviewTypeUseCase( complexProtocolListResponse, OVERVIEW_YIELD ) val stakedBalance = calculateBalanceAndEarningsByOverviewTypeUseCase( complexProtocolListResponse, OVERVIEW_STAKED ) val insuranceBalance = calculateBalanceAndEarningsByOverviewTypeUseCase( complexProtocolListResponse, OVERVIEW_INSURANCE ) val blockedBalance = calculateBalanceAndEarningsByOverviewTypeUseCase( complexProtocolListResponse, OVERVIEW_LOCKED ) val rewardsBalance = calculateRewardsBalance(complexProtocolListResponse) val overviews = mutableListOf<OverViewBalance>() overviews.addOverView(Overview.WALLET, wallet) overviews.addOverView(Overview.LIQUIDITY, liquidityPool.first) overviews.addOverView(Overview.YIELD, yieldBalance.first) overviews.addOverView(Overview.LENDING, lending.first) overviews.addOverView(Overview.FARMING, farming.first) overviews.addOverView(Overview.DEPOSITS, deposits.first) overviews.addOverView(Overview.STAKED, stakedBalance.first) overviews.addOverView(Overview.INSURANCE, insuranceBalance.first) overviews.addOverView(Overview.LOCKED, blockedBalance.first) overviews.addOverView(Overview.REWARDS, rewardsBalance) return overviews } private fun MutableList<OverViewBalance>.addOverView(overview: Overview, balance: Double) { if (balance > 0) this.add(createOverview(overview, balance)) } private fun createOverview(overview: Overview, balance: Double): OverViewBalance { return OverViewBalance( type = overview, balance = convertToFormattedNumberUseCase(balance), dailyEarnings = EMPTY_STRING ) } private fun calculateRewardsBalance(complexProtocolListResponse: List<ComplexProtocolListResponse>): Double { val firstBalance = calculateBalanceAndEarningsByOverviewTypeUseCase( complexProtocolListResponse, OVERVIEW_REWARDS ) var secondBalance = 0.0 complexProtocolListResponse.forEach { protocol -> protocol.portfolioItems.forEach { item -> item.detail.rewardTokens?.forEach { rewardToken -> secondBalance += rewardToken.amount * rewardToken.price.orZero() } } } return firstBalance.first + secondBalance } }
0
Kotlin
1
0
b58abbc9cc98d9534a876fba4400121acb222586
4,467
thedefiapp
MIT License
app/src/test/java/com/arjun/samachar/ui/OfflineViewModelTest.kt
ArjunJadeja
826,162,538
false
{"Kotlin": 141881}
package com.arjun.samachar.ui import app.cash.turbine.test import com.arjun.samachar.data.remote.model.Headline import com.arjun.samachar.data.repository.MainRepository import com.arjun.samachar.ui.base.UiState import com.arjun.samachar.ui.headlines.offline.OfflineViewModel import com.arjun.samachar.utils.DispatcherProvider import com.arjun.samachar.utils.TestDispatcherProvider import kotlinx.coroutines.ExperimentalCoroutinesApi import kotlinx.coroutines.flow.flow import kotlinx.coroutines.flow.flowOf import kotlinx.coroutines.test.runTest import org.junit.Assert.assertEquals import org.junit.Before import org.junit.Test import org.junit.runner.RunWith import org.mockito.Mock import org.mockito.Mockito.doReturn import org.mockito.Mockito.times import org.mockito.Mockito.verify import org.mockito.junit.MockitoJUnitRunner @ExperimentalCoroutinesApi @RunWith(MockitoJUnitRunner::class) class OfflineViewModelTest { @Mock private lateinit var mainRepository: MainRepository private lateinit var dispatcherProvider: DispatcherProvider @Before fun setUp() { dispatcherProvider = TestDispatcherProvider() } @Test fun getCachedHeadlines_whenRepositoryResponseSuccess_shouldSetSuccessUiState() { runTest { doReturn(flowOf(emptyList<Headline>())) .`when`(mainRepository) .getCachedHeadlines() val viewModel = OfflineViewModel(mainRepository, dispatcherProvider) viewModel.headlineList.test { assertEquals(UiState.Success(emptyList<List<Headline>>()), awaitItem()) cancelAndIgnoreRemainingEvents() } verify(mainRepository, times(1)).getCachedHeadlines() } } @Test fun getCachedHeadlines_whenRepositoryResponseError_shouldSetErrorUiState() { runTest { val errorMessage = "Error Message For You" doReturn(flow<List<Headline>> { throw IllegalStateException(errorMessage) }).`when`(mainRepository) .getCachedHeadlines() val viewModel = OfflineViewModel(mainRepository, dispatcherProvider) viewModel.headlineList.test { assertEquals( UiState.Error(IllegalStateException(errorMessage).toString()), awaitItem() ) cancelAndIgnoreRemainingEvents() } verify(mainRepository, times(1)).getCachedHeadlines() } } }
0
Kotlin
7
50
38ea4dce5b3e32fdd9bc6d5546045800434836e5
2,525
samachar
The Unlicense
statusbar/src/main/java/com/seanghay/statusbar/StatusBarConfig.kt
seanghay
228,304,401
false
null
package com.seanghay.statusbar import androidx.annotation.ColorInt import androidx.annotation.RestrictTo @RestrictTo(RestrictTo.Scope.LIBRARY_GROUP) data class StatusBarConfig(@ColorInt var color: Int, var isLight: Boolean)
1
Kotlin
0
5
bbf20872918b6aea066148bf208ee245dd851653
226
statusbar
Apache License 2.0
app/src/main/java/ch/nevis/exampleapp/domain/interaction/DevicePasscodeUserVerifierImpl.kt
nevissecurity
602,532,842
false
{"Kotlin": 298091, "Ruby": 8543, "CSS": 427}
/** * Nevis Mobile Authentication SDK Example App * * Copyright © 2023. Nevis Security AG. All rights reserved. */ package ch.nevis.exampleapp.domain.interaction import ch.nevis.exampleapp.NavigationGraphDirections import ch.nevis.exampleapp.domain.util.titleResId import ch.nevis.exampleapp.logging.sdk import ch.nevis.exampleapp.ui.navigation.NavigationDispatcher import ch.nevis.exampleapp.ui.verifyUser.model.VerifyUserViewMode import ch.nevis.exampleapp.ui.verifyUser.parameter.VerifyUserNavigationParameter import ch.nevis.mobile.sdk.api.operation.userverification.DevicePasscodeUserVerificationContext import ch.nevis.mobile.sdk.api.operation.userverification.DevicePasscodeUserVerificationHandler import ch.nevis.mobile.sdk.api.operation.userverification.DevicePasscodeUserVerifier import timber.log.Timber /** * Default implementation of [DevicePasscodeUserVerifier] interface. It navigates to the Verify User * view with the received [DevicePasscodeUserVerificationHandler] object. * * @constructor Creates a new instance. * @param navigationDispatcher An instance of a [NavigationDispatcher] interface implementation. */ class DevicePasscodeUserVerifierImpl( private val navigationDispatcher: NavigationDispatcher ) : DevicePasscodeUserVerifier { //region DevicePasscodeUserVerifier /** @suppress */ override fun verifyDevicePasscode( context: DevicePasscodeUserVerificationContext, handler: DevicePasscodeUserVerificationHandler ) { Timber.asTree().sdk("Please start device passcode user verification.") navigationDispatcher.requestNavigation( NavigationGraphDirections.actionGlobalVerifyUserFragment( VerifyUserNavigationParameter( VerifyUserViewMode.DEVICE_PASSCODE, context.authenticator().titleResId(), devicePasscodeUserVerificationHandler = handler ) ) ) } /** @suppress */ override fun onValidCredentialsProvided() { Timber.asTree() .sdk("Valid credentials provided during device passcode verification.") } //endregion }
1
Kotlin
0
2
669d95302da63adc9d99642e5e2d65af62f14ce3
2,171
nevis-mobile-authentication-sdk-example-app-android
MIT License
app/src/main/java/org/haidy/servify/domain/model/Location.kt
HaidyAbuGom3a
805,534,454
false
{"Kotlin": 702248}
package org.haidy.servify.domain.model data class Location( val country: String, val governorate: String, val latitude: Double, val longitude: Double )
0
Kotlin
0
2
8c2ba73cea5d29cc2ef7048d832f8ecea13f34ee
169
Servify
Apache License 2.0
Android/src/main/java/com/example/vocab/vocabulary/VocabularyFragment.kt
Arduino13
599,629,871
false
null
package com.example.vocab.vocabulary import android.annotation.SuppressLint import android.graphics.PorterDuff import android.graphics.PorterDuffColorFilter import android.graphics.drawable.Drawable import android.os.Bundle import android.view.* import android.widget.TextView import androidx.core.content.ContextCompat import androidx.core.content.res.ResourcesCompat import androidx.core.os.bundleOf import androidx.core.view.GestureDetectorCompat import androidx.fragment.app.Fragment import androidx.lifecycle.Observer import androidx.navigation.findNavController import com.example.vocab.R import com.example.vocab.Tools import com.example.vocab.Tools.Companion.getScreenSizeOfDevice import com.example.vocab.database.Database import com.example.vocab.databinding.FragmentVocabularyBinding import com.example.vocab.gui.* /** * Fragment which displays lists of words, it's inherited by [StudentVocabularyFragment] and * [TeacherVocabularyFragment] */ abstract class VocabularyFragment(private val destList: Int, private val destNewList: Int): Fragment(), GestureDetector.OnGestureListener{ private lateinit var binding: FragmentVocabularyBinding private lateinit var fragmentModel: GenericVocabularyModel private var screenSize = 0.0 /** * Returns layout with round corners */ private fun getShape(w: BaseTextCell): Drawable?{ val db = Database(requireContext(), requireActivity()) val shape = ContextCompat.getDrawable(requireContext(), R.drawable.layout_circle) val shapeColor = (db.getSetting(w.text) as? Int) ?: run { val generatedColor = Colors.generateColor(resources)!! db.saveSetting( mapOf<String,Int>( w.text to generatedColor ) ) generatedColor } shape?.colorFilter = PorterDuffColorFilter(shapeColor, PorterDuff.Mode.OVERLAY) return shape } /** * Sets up list based on size of the screen */ private fun setUpList(list: List<BaseTextCell>): List<BaseItem<*>>{ val toReturn = mutableListOf<BaseItem<*>>() val height = if (screenSize>6) Tools.dp2Pixels(80, resources) else Tools.dp2Pixels(40, resources) toReturn += BaseHeader( resources.getString(R.string.vocabulary_title), height + 30 ) if (screenSize > 6) { for (w in list) { w.height = height w.alignment = BaseTextCell.wordAlign.center w.layoutShape = getShape(w) } } else{ for(w in list){ w.height = height w.alignment = BaseTextCell.wordAlign.left w.layoutShape = getShape(w) } } toReturn.addAll(list) val shape = ContextCompat.getDrawable(requireContext(), R.drawable.layout_circle) shape?.colorFilter = PorterDuffColorFilter(ResourcesCompat.getColor(resources,R.color.blue, null), PorterDuff.Mode.OVERLAY) toReturn += BaseButton( resources.getString(R.string.vocabulary_button_title), height, shape ) { binding.root.findNavController().navigate(destNewList) } return toReturn } /** * Returns used model by child objects */ abstract fun getFragmentModelObj(): GenericVocabularyModel @SuppressLint("ClickableViewAccessibility") override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View? { binding = FragmentVocabularyBinding.inflate(inflater, container, false) val view = binding.listView screenSize = getScreenSizeOfDevice(resources) val adapterT = BaseListAdapter() ResponsibleList.makeResponsible(view, resources, requireContext()) view.adapter = adapterT fragmentModel = getFragmentModelObj() fragmentModel.lists.observe(viewLifecycleOwner, Observer { new -> new?.let { adapterT.submitList(setUpList(new)) } }) val mDetector = GestureDetectorCompat(requireContext(), this) mDetector.setIsLongpressEnabled(true) binding.listView.setOnTouchListener { _, motionEvent -> mDetector.onTouchEvent(motionEvent) } return binding.root } override fun onShowPress(p0: MotionEvent?) {} override fun onSingleTapUp(p0: MotionEvent?): Boolean { p0?.let { val headerText = binding.listView.findChildViewUnder(it.x, it.y)?.findViewById<TextView>(R.id.textView)?.text headerText?.let { val bundle = bundleOf("header" to headerText) binding.root.findNavController().navigate(destList, bundle) return true } } return false } override fun onDown(p0: MotionEvent?): Boolean = false override fun onFling(p0: MotionEvent?, p1: MotionEvent?, p2: Float, p3: Float): Boolean = false override fun onScroll(p0: MotionEvent?, p1: MotionEvent?, p2: Float, p3: Float): Boolean = false override fun onLongPress(p0: MotionEvent?) { println("long") } }
0
Kotlin
0
0
5281c5b8281fd3cb06cf670dcaa7e6c858606179
5,285
3N
MIT License
core/data/src/main/kotlin/com/yjpapp/data/mapper/StockPriceMapper.kt
YoonJaePark3908
274,878,228
false
{"Kotlin": 160366}
package com.yjpapp.data.mapper import com.yjpapp.data.model.response.StockPriceData import com.yjpapp.network.model.StockPriceInfo fun StockPriceInfo.mapping(): StockPriceData = StockPriceData( basDt = this.basDt, srtnCd = this.srtnCd, isinCd = this.isinCd, itmsNm = this.itmsNm, mrktCtg = this.mrktCtg, clpr = this.clpr, vs = this.vs, fltRt = this.fltRt, mkp = this.mkp, hipr = this.hipr, lopr = this.lopr, trqu = this.trqu, trPrc = this.trPrc, lstgStCnt = this.lstgStCnt, mrktTotAmt = this.mrktTotAmt )
1
Kotlin
0
3
73213154148ed8bcde5a136d0121c0fe072c400d
634
StockPortfolio
Apache License 2.0
tga-core/src/main/kotlin/org/plan/research/tga/core/compiler/JavaCompiler.kt
plan-research
762,333,893
false
null
package org.plan.research.tga.compiler import org.vorpal.research.kthelper.KtException import java.nio.file.Path class CompilationException : KtException { constructor(message: String = "") : super(message) @Suppress("unused") constructor(message: String = "", throwable: Throwable) : super(message, throwable) } interface JavaCompiler { val classPath: List<Path> fun compile(sources: List<Path>, outputDirectory: Path): List<Path> }
0
null
1
1
37f4b93f6116baa6f954a2f15625c2e1aa71c091
459
tga-pipeline
Apache License 2.0
app/src/main/java/com/arnyminerz/paraulogic/activity/SettingsActivity.kt
Paraulogic
467,264,620
false
null
package com.arnyminerz.paraulogic.activity import android.content.pm.ActivityInfo import android.os.Bundle import androidx.activity.compose.setContent import androidx.appcompat.app.AppCompatActivity import androidx.compose.material.ExperimentalMaterialApi import androidx.compose.material3.ExperimentalMaterial3Api import androidx.compose.material3.windowsizeclass.ExperimentalMaterial3WindowSizeClassApi import androidx.compose.material3.windowsizeclass.WindowWidthSizeClass import androidx.compose.material3.windowsizeclass.calculateWindowSizeClass import com.arnyminerz.paraulogic.ui.screen.SettingsScreen import com.arnyminerz.paraulogic.ui.theme.AppTheme import com.arnyminerz.paraulogic.ui.utils.LockScreenOrientation class SettingsActivity : AppCompatActivity() { @OptIn( ExperimentalMaterial3Api::class, ExperimentalMaterialApi::class, ExperimentalMaterial3WindowSizeClassApi::class, ) override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContent { AppTheme { val windowSizeClass = calculateWindowSizeClass(this) LockScreenOrientation( when (windowSizeClass.widthSizeClass) { WindowWidthSizeClass.Compact -> ActivityInfo.SCREEN_ORIENTATION_PORTRAIT else -> ActivityInfo.SCREEN_ORIENTATION_SENSOR } ) SettingsScreen() } } } }
3
Kotlin
0
1
51def1a95decd2f0b3ed6526c63fb87edeb760a1
1,515
Android
Apache License 2.0
app/src/main/java/com/sunnyweather/android/ui/place/PlaceFragment.kt
282991955
442,030,504
false
null
package com.sunnyweather.android.ui.place import android.content.Intent import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.Toast import androidx.core.widget.addTextChangedListener import androidx.fragment.app.Fragment import androidx.lifecycle.ViewModelProvider import androidx.recyclerview.widget.LinearLayoutManager import com.sunnyweather.android.MainActivity import com.sunnyweather.android.WeatherActivity import com.sunnyweather.android.databinding.FragmentPlaceBinding class PlaceFragment : Fragment() { val viewModel by lazy { ViewModelProvider(this).get(PlaceViewModel::class.java) } private lateinit var adapter: PlaceAdapter private var _binding: FragmentPlaceBinding? = null private val binding get() = _binding!! override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View { _binding = FragmentPlaceBinding.inflate(inflater, container, false) return binding.root } override fun onActivityCreated(savedInstanceState: Bundle?) { super.onActivityCreated(savedInstanceState) // 如果SharedPreferences里面有数据,则直接跳转到那边,并且关闭当前activity,结束执行 if (activity is MainActivity && viewModel.isPlaceSaved()) { val place = viewModel.getSavedPlace() val intent = Intent(context, WeatherActivity::class.java).apply { putExtra("location_lng", place.location.lng) putExtra("location_lat", place.location.lat) putExtra("place_name", place.name) } startActivity(intent) activity?.finish() return } // 给RecycleView设置布局管理器和适配器 val linearLayoutManager = LinearLayoutManager(activity) binding.recycleView.layoutManager = linearLayoutManager adapter = PlaceAdapter(this, viewModel.placeList) binding.recycleView.adapter = adapter // 给搜索框设置文字改变的监听事件 binding.searchPlaceEdit.addTextChangedListener { val content = it.toString() if (content.isNotEmpty()) { // 如果文本不为空就改变ViewModel中的searchLiveData viewModel.searchPlace(content) } else { // 如果文本为空隐藏结果列表,显示背景图片,清空placeList且动态刷新RecycleView binding.recycleView.visibility = View.GONE binding.bgImageView.visibility = View.VISIBLE viewModel.placeList.clear() adapter.notifyDataSetChanged() } } // 监听placeLiveData,每次改变都动态获取最新数据 viewModel.placeLiveData.observe(this) { val places = it.getOrNull() if (places != null) { // 若获取的数据不为空显示结果列表隐藏背景图,动态刷新列表 binding.recycleView.visibility = View.VISIBLE binding.bgImageView.visibility = View.GONE viewModel.placeList.clear() viewModel.placeList.addAll(places) adapter.notifyDataSetChanged() } else { Toast.makeText(activity, "未能查询到任何地点", Toast.LENGTH_SHORT).show() it.exceptionOrNull()?.printStackTrace() } } } override fun onDestroyView() { super.onDestroyView() _binding = null } }
0
Kotlin
0
0
d2447d0e87a8937713b8a5860713b8b238946a33
3,352
SunnyWeather
Apache License 2.0
libraries/test-shared/src/main/java/com/prof18/filmatic/libraries/testshared/fakes/FakeConnectivyChecker.kt
prof18
189,304,492
false
null
package com.prof18.filmatic.libraries.testshared.fakes import com.prof18.filmatic.core.net.ConnectivityChecker import javax.inject.Inject class FakeConnectivityCheckReturnSuccess @Inject constructor() : ConnectivityChecker { override fun hasInternetAccess(): Boolean = true } class FakeConnectivityCheckReturnNotSuccess : ConnectivityChecker { override fun hasInternetAccess(): Boolean = false }
1
Kotlin
3
4
95175c808870c4aaa8f8d6218511f59f36b228cb
407
Filmatic
Apache License 2.0
app/src/main/java/sk/backbone/parent/ui/components/ISpinnerItemsProvider.kt
Mini849
421,757,477
true
{"Kotlin": 114905}
package sk.backbone.parent.ui.components import android.view.ViewGroup import androidx.core.view.forEach import java.lang.Exception abstract class ISpinnerItemsProvider<T> { abstract val elements: List<T> val stringValues: List<String> by lazy{ elements.map { getString(it) } } abstract fun getString(value: T): String fun getValuesAsStrings(): List<String> { return stringValues } operator fun get(string: String) : T { return elements.find { getString(it) == string }!! } operator fun get(position: Int): T { return elements[position] } fun getIndexOf(value: Any?): Int { return (value as T?)?.let { stringValues.indexOf(getString(it)) } ?: -1 } private fun GiveMeUnoOrInput(unoOrInput: Int? = 1): Int? { return unoOrInput } private fun ViewGroup.FuckOffWithAllViews(){ val viewGroup: ViewGroup = this viewGroup.forEach { view -> viewGroup.removeView(view) } } }
0
Kotlin
0
0
4075916eae850b1080516bde021d3586a5e87c61
1,002
parent
MIT License
Lib/src/main/java/biz/dreamaker/lib/android_core/components/photo_gallery/pages/gallery/fragments/PhotoGalleryFragment.kt
Dream-Maker-Inc
362,412,218
false
null
package biz.dreamaker.lib.android_core.components.photo_gallery.pages.gallery.fragments import android.app.Activity import android.content.Intent import android.graphics.Rect import android.graphics.Typeface import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.core.os.bundleOf import androidx.fragment.app.Fragment import androidx.fragment.app.viewModels import androidx.navigation.fragment.findNavController import androidx.recyclerview.widget.GridLayoutManager import androidx.recyclerview.widget.LinearLayoutManager import androidx.recyclerview.widget.RecyclerView import biz.dreamaker.lib.android_core.R import biz.dreamaker.lib.android_core.databinding.FragmentPhotoGalleryBinding import biz.dreamaker.lib.android_core.utils.functions.toPx import biz.dreamaker.lib.android_core.components.photo_gallery.pages.full_screen.fragments.PhotoFullScreenViewFragment import biz.dreamaker.lib.android_core.components.photo_gallery.pages.gallery.adapters.PhotoGalleryItemAdapter import biz.dreamaker.lib.android_core.components.photo_gallery.pages.gallery.adapters.PhotoSelectedItemAdapter import biz.dreamaker.lib.android_core.components.photo_gallery.pages.gallery.view_models.PhotoGalleryViewModel class PhotoGalleryFragment : Fragment() { companion object { const val RETURN_PHOTO_FILE = "A_PG1001" } private val vm by viewModels<PhotoGalleryViewModel>() private var binding: FragmentPhotoGalleryBinding? = null private var isInit = false override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View { return createBinding().root } private fun createBinding() = binding?.run { this } ?: run { FragmentPhotoGalleryBinding.inflate(layoutInflater).apply { binding = this } } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) if (isInit.not()) { setupUi() isInit = true } initSelectedItemRecyclerViewAdapter() initGalleryRecyclerViewAdapter() initSelectedItemRecyclerViewVisibility() initObservers() } // private val photoGalleryItemAdapter by lazy { PhotoGalleryItemAdapter( items = vm.allPhotos, checkedCallback = { if (vm.checkedDataIdPair != it) vm.checkedDataIdPair = it }, fullScreenClickCallback = { position -> navigateFullScreenPage(dataPosition = position) } ) } private fun navigateFullScreenPage(dataPosition: Int) { findNavController().navigate( R.id.action_photoGalleryFragment_to_photoFullScreenViewFragment, bundleOf( PhotoFullScreenViewFragment.PHOTO_FULL_SCREEN_VIEW_REQUEST_CODE to vm.allPhotos[dataPosition] ) ) } private val selectedItemAdapter by lazy { PhotoSelectedItemAdapter( items = vm.checkedDataList, deleteClickCallback = { vm.checkedDataIdPair = it } ).apply { registerAdapterDataObserver(object : RecyclerView.AdapterDataObserver() { override fun onItemRangeInserted(positionStart: Int, itemCount: Int) { super.onItemRangeInserted(positionStart, itemCount) initSelectedItemRecyclerViewVisibility() } override fun onItemRangeRemoved(positionStart: Int, itemCount: Int) { super.onItemRangeRemoved(positionStart, itemCount) initSelectedItemRecyclerViewVisibility() } }) } } private fun setupUi() { setupSelectedItemRecyclerView() setupGalleryRecyclerView() setupCountOfAllPhotoTextView() setupCloseGalleryButton() setupSubmitButton() } private fun setupSelectedItemRecyclerView() { binding?.rcvSelectedItems?.apply { layoutManager = LinearLayoutManager(context).apply { orientation = LinearLayoutManager.HORIZONTAL } setHasFixedSize(true) } } private fun setupGalleryRecyclerView() { binding?.rcvGalleryItems?.apply { layoutManager = GridLayoutManager(context, 3) setHasFixedSize(true) addItemDecoration(object : RecyclerView.ItemDecoration() { override fun getItemOffsets(outRect: Rect, view: View, parent: RecyclerView, state: RecyclerView.State) { super.getItemOffsets(outRect, view, parent, state) val margin = 1.toPx() outRect.set(margin, margin, margin, margin) } }) } } private fun setupCountOfAllPhotoTextView() { binding?.tvGalleryAllCount?.text = requireContext().getString(R.string.pgs_allPhotosCount, vm.allPhotos.size) } private fun setupCloseGalleryButton() { binding?.ivGalleryClose?.setOnClickListener { requireActivity().finish() } } private fun setupSubmitButton() { binding?.tvGallerySelectionComplete?.setOnClickListener { val intent = Intent().apply { putExtra( RETURN_PHOTO_FILE, vm.checkedDataList.toTypedArray() ) } requireActivity() .apply { setResult(Activity.RESULT_OK, intent) }.run { finish() } } } // private fun initSelectedItemRecyclerViewAdapter() { binding?.rcvSelectedItems?.adapter = selectedItemAdapter } private fun initGalleryRecyclerViewAdapter() { binding?.rcvGalleryItems?.adapter = photoGalleryItemAdapter } private fun initSelectedItemRecyclerViewVisibility() { if (vm.checkedDataList.isNullOrEmpty()) binding?.rcvSelectedItems?.visibility = View.GONE else binding?.rcvSelectedItems?.visibility = View.VISIBLE } // private fun updateGalleryRecyclerViewAdapterState(photoId: Long, isChecked: Boolean) { binding?.rcvGalleryItems?.let { galleryRecyclerView -> val position = vm.findIndexInAllPhotos(photoId) ?: return val viewHolder = galleryRecyclerView.findViewHolderForAdapterPosition(position) photoGalleryItemAdapter.updateUiByState(viewHolder, photoId, isChecked) } } private fun updateSelectedItemDataChange(removedItemPosition: Int, isChecked: Boolean) { selectedItemAdapter.updateDataChange( removedItemPosition, adapterLastIndex = selectedItemAdapter.itemCount, isChecked ) vm.checkedItem?.let { val index = vm.findIndexInCheckedDataList(it.id) ?: return if (index < 0) return binding?.rcvSelectedItems?.smoothScrollToPosition(index) } } private fun updateSelectionCountTextViewState() { val count = if (vm.checkedDataList.size < 1) null else vm.checkedDataList.size.toString() binding?.tvGallerySelectionCount?.text = count } private fun updateSubmitButtonState() { binding?.tvGallerySelectionComplete?.apply { when { vm.checkedDataList.isNullOrEmpty().not() -> { isEnabled = true setTypeface(null, Typeface.BOLD) } else -> { isEnabled = false setTypeface(null, Typeface.NORMAL) } } } } // private fun initObservers() { vm._checkedDataIdPair.observe(viewLifecycleOwner, { (photoId, isChecked) -> updateSelectedItemDataChange(vm.removedItemPosition, isChecked) updateGalleryRecyclerViewAdapterState(photoId, isChecked) updateSelectionCountTextViewState() updateSubmitButtonState() }) } }
0
Kotlin
0
0
cc430e4cf521660dd57263f9a9664a7dd57b2f80
8,414
DreamakerAndroidCore
Apache License 2.0
dsl/src/main/kotlin/cloudshift/awscdk/dsl/services/robomaker/CfnSimulationApplicationRenderingEnginePropertyDsl.kt
cloudshiftinc
667,063,030
false
null
@file:Suppress("RedundantVisibilityModifier","RedundantUnitReturnType","RemoveRedundantQualifierName","unused","UnusedImport","ClassName","REDUNDANT_PROJECTION","DEPRECATION") package cloudshift.awscdk.dsl.services.robomaker import cloudshift.awscdk.common.CdkDslMarker import kotlin.String import software.amazon.awscdk.services.robomaker.CfnSimulationApplication /** * Information about a rendering engine. * * Example: * * ``` * // The code below shows an example of how to instantiate this type. * // The values are placeholders you should change. * import software.amazon.awscdk.services.robomaker.*; * RenderingEngineProperty renderingEngineProperty = RenderingEngineProperty.builder() * .name("name") * .version("version") * .build(); * ``` * * [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-robomaker-simulationapplication-renderingengine.html) */ @CdkDslMarker public class CfnSimulationApplicationRenderingEnginePropertyDsl { private val cdkBuilder: CfnSimulationApplication.RenderingEngineProperty.Builder = CfnSimulationApplication.RenderingEngineProperty.builder() /** * @param name The name of the rendering engine. */ public fun name(name: String) { cdkBuilder.name(name) } /** * @param version The version of the rendering engine. */ public fun version(version: String) { cdkBuilder.version(version) } public fun build(): CfnSimulationApplication.RenderingEngineProperty = cdkBuilder.build() }
1
Kotlin
0
0
17c41bdaffb2e10d31b32eb2282b73dd18be09fa
1,522
awscdk-dsl-kotlin
Apache License 2.0
output/src/main/kotlin/com/devo/feeds/output/LoggingOutput.kt
aig787
320,055,206
true
{"Kotlin": 103776, "Dockerfile": 834}
package com.devo.feeds.output import com.typesafe.config.Config import kotlinx.serialization.encodeToString import kotlinx.serialization.json.Json import mu.KotlinLogging class LoggingOutputFactory : OutputFactory<LoggingOutput> { override fun fromConfig(config: Config): LoggingOutput = LoggingOutput() } open class LoggingOutput : Output { private val log = KotlinLogging.logger { } override suspend fun write(feed: String, eventUpdate: EventUpdate) { log.info { "feed: $feed, event: ${Json.encodeToString(eventUpdate)}" } } override fun close() { // noop } }
3
Kotlin
0
0
9c8b4c18d7c83e839af863c75e59456079d1e1e2
608
feeds
MIT License
app/src/main/java/com/example/androidweatherapp/viewmodel/ApiServiceBuilder.kt
RamziJabali
381,178,725
false
null
package com.example.androidweatherapp.viewmodel import android.annotation.SuppressLint import com.google.gson.Gson import com.google.gson.GsonBuilder import okhttp3.Interceptor import okhttp3.OkHttpClient import retrofit2.Retrofit import retrofit2.converter.gson.GsonConverterFactory import java.security.cert.X509Certificate import java.util.concurrent.TimeUnit import javax.net.ssl.* class ApiServiceBuilder<S>( private val serviceClass: Class<S> ) { companion object { const val DEFAULT_TIME_OUT_SECONDS: Long = 20L val gson: Gson = GsonBuilder() // .registerTypeHierarchyAdapter(ZonedDateTime::class.java.javaClass, ZonedDateTimeTypeAdapterFactory()) // .registerTypeAdapter(ZonedDateTime::class.java.javaClass, ZonedDateTimeTypeAdapterFactory()) .create() } private var networkInterceptor: Interceptor? = null private lateinit var apiBaseUrl: String private var authToken: String = "" private var cookie: String = "" private var timeOutDurationSeconds: Long = DEFAULT_TIME_OUT_SECONDS private var acceptAllCerts: Boolean = false fun withApiBaseUrl(baseUrl: String): ApiServiceBuilder<S> { this.apiBaseUrl = baseUrl return this } fun withHeaderAuthTokenRequests(authToken: String): ApiServiceBuilder<S> { this.authToken = authToken return this } fun withHeaderCookieRequests(cookie: String): ApiServiceBuilder<S> { this.cookie = cookie return this } fun withTimeOutDuration(timeOutInSeconds: Long): ApiServiceBuilder<S> { this.timeOutDurationSeconds = timeOutInSeconds return this } fun withAllCertsAccepted(allCertsAccepted: Boolean): ApiServiceBuilder<S> { this.acceptAllCerts = allCertsAccepted return this } fun withNetworkInterceptor(networkInterceptor: Interceptor?): ApiServiceBuilder<S> { this.networkInterceptor = networkInterceptor return this } fun build(): S { val httpClient: OkHttpClient = OkHttpClient.Builder().apply { networkInterceptor?.let { networkInterceptors().add(networkInterceptor) } readTimeout(timeOutDurationSeconds, TimeUnit.SECONDS) connectTimeout(timeOutDurationSeconds, TimeUnit.SECONDS) if (acceptAllCerts) { sslSocketFactory( getAllAcceptingSslFactory(), getAllTrustingCertManager()[0] as X509TrustManager ) hostnameVerifier(getAllAcceptingHostNameVerifier()) } }.build() val retrofit: Retrofit = Retrofit.Builder() .baseUrl(apiBaseUrl) .addConverterFactory(GsonConverterFactory.create(gson)) .client(httpClient) .build() return retrofit.create(serviceClass) } private fun getAllAcceptingSslFactory(): SSLSocketFactory { val sslContext = SSLContext.getInstance("SSL") sslContext.init(null, getAllTrustingCertManager(), java.security.SecureRandom()) return sslContext.socketFactory } @SuppressLint("TrustAllX509TrustManager") private fun getAllTrustingCertManager(): Array<TrustManager> = arrayOf(object : X509TrustManager { override fun checkClientTrusted(chain: Array<out X509Certificate>?, authType: String?) { } override fun checkServerTrusted(chain: Array<out X509Certificate>?, authType: String?) { } override fun getAcceptedIssuers(): Array<X509Certificate> { return arrayOf() } }) @SuppressLint("BadHostnameVerifier") private fun getAllAcceptingHostNameVerifier(): HostnameVerifier = object : HostnameVerifier { override fun verify(hostname: String?, session: SSLSession?): Boolean { return true } } }
0
Kotlin
0
0
30a8079e7a63d7a9a041aa644888b2c04299e081
3,952
weather-app-android
The Unlicense
IPassPlusSdk/src/main/java/com/sdk/ipassplussdk/model/response/ceon/PostCeon/Facebook.kt
yazanalqasem
808,584,767
false
{"Kotlin": 308101, "Java": 4759}
package com.sdk.ipassplussdk.model.response.ceon.PostCeon data class Facebook( val name: Any, val photo: Any, val registered: Any, val url: Any )
0
Kotlin
0
0
1fc3247607811f7f52e1d401c252b82e2c98c3a8
162
iPass2.0NativeAndroidSDK
Apple MIT License
androidApp/src/main/java/com/kashif/kmmnewsapp/android/MainActivity.kt
VishalRajora
525,011,571
false
null
package com.kashif.kmmnewsapp.android import android.os.Bundle import androidx.activity.ComponentActivity import androidx.activity.compose.setContent import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.material.MaterialTheme import androidx.compose.material.Text import androidx.compose.runtime.Composable import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import com.kashif.kmmnewsapp.android.theme.KmmNewsTheme import com.kashif.kmmnewsapp.presentation.screen.ScreenViewModel import org.koin.androidx.compose.get class MainActivity : ComponentActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContent { KmmNewsTheme { Screen() } } } } @Composable fun Screen(viewModel: ScreenViewModel = get()) { Column( modifier = Modifier.fillMaxSize(), verticalArrangement = Arrangement.Center, horizontalAlignment = Alignment.CenterHorizontally ) { Text(viewModel.getSharedMessage(), color = MaterialTheme.colors.onSurface, style = MaterialTheme.typography.h1 ) } }
0
Kotlin
0
1
0a166114757be2e11b3784e9e88400f5df327d11
1,318
KMM
Apache License 2.0
backend/src/main/kotlin/clarity/backend/controllers/ClassroomAttempsController.kt
ad-world
645,911,581
false
null
package clarity.backend.controllers import clarity.backend.entity.* import org.springframework.http.ResponseEntity import org.springframework.web.bind.annotation.* import org.springframework.web.multipart.MultipartFile @RestController @RequestMapping("/classroom") class ClassroomAttemptsController { private val classroomAttemptsEntity = ClassroomAttemptsEntity() @PostMapping("/attemptCard") fun attemptCard(@RequestParam("user_id") user_id: Int, @RequestParam("card_id") card_id: Int, @RequestParam("task_id") task_id: Int, @RequestParam("audio") audio: MultipartFile): ResponseEntity<CreateClassroomAttemptResponse> { val attempt = CreateClassroomAttemptEntity( task_id = task_id, user_id = user_id, card_id = card_id, audio = audio ) val attemptResponse = classroomAttemptsEntity.createClassroomAttempts(attempt); return if(attemptResponse.response == StatusResponse.Success) { ResponseEntity.ok(attemptResponse) } else { ResponseEntity.badRequest().body(attemptResponse) } } @GetMapping("/getTaskAttempts") fun getTaskAttempts(@RequestParam task: Int): ResponseEntity<GetTaskAttemptsResponse> { val attemptResponse = classroomAttemptsEntity.getTaskAttempts(task) return if(attemptResponse.response == StatusResponse.Success) { ResponseEntity.ok(attemptResponse) } else { ResponseEntity.badRequest().body(attemptResponse); } } @GetMapping("/getClassAttempts") fun getClassAttempts(@RequestParam classroom: String): ResponseEntity<GetClassAttemptsResponse> { val attemptResponse = classroomAttemptsEntity.getClassAttempts(classroom) return if(attemptResponse.response == StatusResponse.Success) { ResponseEntity.ok(attemptResponse) } else { ResponseEntity.badRequest().body(attemptResponse); } } @GetMapping("/getTaskProgress") fun getTaskProgress(@RequestParam task_id: Int): ResponseEntity<GetClassroomTaskProgressResponse> { val attemptResponse = classroomAttemptsEntity.getClassroomTaskProgress(GetClassroomTaskProgressRequest(task_id)); return if(attemptResponse.response == StatusResponse.Success) { ResponseEntity.ok(attemptResponse) } else { ResponseEntity.badRequest().body(attemptResponse) } } @PostMapping("/practiceAttemptCard") fun practiceAttemptCard(@RequestParam("user_id") user_id: Int, @RequestParam("card_id") card_id: Int, @RequestParam("task_id") task_id: Int, @RequestParam("audio") audio: MultipartFile): ResponseEntity<PracticeClassroomAttemptResponse> { val request = PracticeClassroomAttemptEntity( user_id = user_id, task_id = task_id, card_id = card_id, audio = audio ) val practiceResponse = classroomAttemptsEntity.practiceClassroomAttempt(request) return if(practiceResponse.response == StatusResponse.Success) { ResponseEntity.ok(practiceResponse) } else { ResponseEntity.badRequest().body(practiceResponse) } } }
0
Kotlin
0
1
2c6b958dc4f0b97e59c5ce5171ce43dc9401a4e7
3,235
clarity
MIT License
service/src/test/kotlin/io/provenance/explorer/domain/extensions/ExtenstionsKtTest.kt
provenance-io
332,035,574
false
{"Kotlin": 1058155, "PLpgSQL": 316369, "Shell": 679, "Python": 642}
package io.provenance.explorer.domain.extensions import org.junit.jupiter.api.Assertions.assertEquals import org.junit.jupiter.api.Test class ExtensionsKtTest { @Test fun `test toObjectNode properly converts json strings to objecs`() { val inputJsonWithJsonStrObj = "{\"amount\":\"1\",\"denom\":\"psa.3zlqy2ecncvalbycokxnoh.stock\",\"memo\":\"{\\\"marker\\\":{\\\"transfer-auths\\\":[\\\"tp19zf8q9swrsspkdljumwh04zjac4nkfvju6ehl9\\\",\\\"tp1tk6fqws0su7fzp090edrauaa756mdyjfdw0507\\\",\\\"tp1a53udazy8ayufvy0s434pfwjcedzqv34vfvvyc\\\"],\\\"allow-force-transfer\\\":false}}\",\"receiver\":\"tp12wyy028sd3yf3j0z950fq5p3zvzgpzgds3dqp3\",\"sender\":\"tp12wyy028sd3yf3j0z950fq5p3zvzgpzgds3dqp3\"}" val inputFormatedJsonWithJsonStrObj = "{\n" + " \"amount\": \"1\",\n" + " \"denom\": \"psa.3zlqy2ecncvalbycokxnoh.stock\",\n" + " \"memo\": \"{\\\"marker\\\":{\\\"transfer-auths\\\":[\\\"tp19zf8q9swrsspkdljumwh04zjac4nkfvju6ehl9\\\",\\\"tp1tk6fqws0su7fzp090edrauaa756mdyjfdw0507\\\",\\\"tp1a53udazy8ayufvy0s434pfwjcedzqv34vfvvyc\\\"],\\\"allow-force-transfer\\\":false}}\",\n" + " \"receiver\": \"tp12wyy028sd3yf3j0z950fq5p3zvzgpzgds3dqp3\",\n" + " \"sender\": \"tp12wyy028sd3yf3j0z950fq5p3zvzgpzgds3dqp3\"\n" + "}" val tests = mapOf( "test input with string that has json string as value for memo" to inputJsonWithJsonStrObj, "test input with formatted json and json string as value for memo" to inputFormatedJsonWithJsonStrObj ) for ((testname, json) in tests) { val actualJsonObj = json.toObjectNode() assertEquals("tp12wyy028sd3yf3j0z950fq5p3zvzgpzgds3dqp3", actualJsonObj.get("receiver").asText(), testname) assertEquals("tp12wyy028sd3yf3j0z950fq5p3zvzgpzgds3dqp3", actualJsonObj.get("sender").asText(), testname) assertEquals("1", actualJsonObj.get("amount").asText(), testname) assertEquals("psa.3zlqy2ecncvalbycokxnoh.stock", actualJsonObj.get("denom").asText(), testname) assertEquals("{\"marker\":{\"transfer-auths\":[\"tp19zf8q9swrsspkdljumwh04zjac4nkfvju6ehl9\",\"tp1tk6fqws0su7fzp090edrauaa756mdyjfdw0507\",\"tp1a53udazy8ayufvy0s434pfwjcedzqv34vfvvyc\"],\"allow-force-transfer\":false}}", actualJsonObj.get("memo").asText(), testname) } } @Test fun `test tryFromBase64 with various cases`() { val base64String = "SGVsbG8gd29ybGQ=" val expectedDecodedString = "Hello world" assertEquals(expectedDecodedString, base64String.tryFromBase64(), "Valid Base64 string should decode to 'Hello world'") val invalidBase64String = "Hello world" val expectedInvalidOutput = invalidBase64String assertEquals(expectedInvalidOutput, invalidBase64String.tryFromBase64(), "Invalid Base64 string should return the original string") val emptyString = "" val expectedEmptyOutput = emptyString assertEquals(expectedEmptyOutput, emptyString.tryFromBase64(), "Empty string should return the original string") val malformedBase64String = "SGVsbG8gd29ybGQ" val expectedMalformedOutput = malformedBase64String assertEquals(expectedMalformedOutput, malformedBase64String.tryFromBase64(), "Malformed Base64 string should return the original string") } }
31
Kotlin
3
6
671b1a02fbc93178c0e6492b75394f075994e48a
3,379
explorer-service
Apache License 2.0
app/src/main/java/com/senemyalin/sencoffee/presentation/cart/CartViewModel.kt
senemyalin
694,843,885
false
{"Kotlin": 82264}
package com.senemyalin.sencoffee.presentation.cart import androidx.lifecycle.LiveData import androidx.lifecycle.MutableLiveData import androidx.lifecycle.ViewModel import androidx.lifecycle.viewModelScope import com.senemyalin.sencoffee.common.NetworkResponse import com.senemyalin.sencoffee.data.dto.DeleteFromCartRequest import com.senemyalin.sencoffee.data.dto.Product import com.senemyalin.sencoffee.domain.usecase.remote.deletefromcart.DeleteFromCartUseCase import com.senemyalin.sencoffee.domain.usecase.remote.getcartproducts.GetCartProductsUseCase import dagger.hilt.android.lifecycle.HiltViewModel import kotlinx.coroutines.launch import javax.inject.Inject @HiltViewModel class CartViewModel @Inject constructor( private val getCartProductsUseCase: GetCartProductsUseCase, private val deleteFromCartUseCase: DeleteFromCartUseCase ) : ViewModel() { private var _cartProducts = MutableLiveData<NetworkResponse<List<Product>>?>() val cartProducts: LiveData<NetworkResponse<List<Product>>?> get() = _cartProducts private var _deleteCartProductResponse = MutableLiveData<NetworkResponse<Int>?>() val deleteCartProductResponse: LiveData<NetworkResponse<Int>?> get() = _deleteCartProductResponse fun getCartProducts(userId: String) { viewModelScope.launch { getCartProductsUseCase(userId).collect { when (it) { is NetworkResponse.Error -> { _cartProducts.postValue(it) } NetworkResponse.Loading -> Unit is NetworkResponse.Success -> { _cartProducts.postValue(it) } } } } } fun deleteCartProducts(productId: String) { viewModelScope.launch { deleteFromCartUseCase( DeleteFromCartRequest( productId.toInt() ) ).collect { when (it) { is NetworkResponse.Error -> { _deleteCartProductResponse.postValue(it) } NetworkResponse.Loading -> Unit is NetworkResponse.Success -> { _deleteCartProductResponse.postValue(it) } } } } } }
0
Kotlin
0
2
1585a2450e94732d46c10b7ac68c30a9f741be1b
2,393
SenCoffeeECommerce
The Unlicense
src/main/kotlin/github/cheng/module/opencv/OpenCV.kt
YiGuan-z
702,319,315
false
{"Kotlin": 84112}
package github.cheng.module.opencv import github.cheng.module.ShutDown import github.cheng.module.bot.basename import github.cheng.module.bot.suffix import github.cheng.module.thisLogger import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.withContext import org.bytedeco.ffmpeg.global.avcodec import org.bytedeco.ffmpeg.global.avutil import org.bytedeco.javacpp.Loader import org.bytedeco.javacv.FFmpegFrameGrabber import org.bytedeco.javacv.FFmpegFrameRecorder import org.bytedeco.javacv.Frame import org.bytedeco.javacv.OpenCVFrameConverter import org.bytedeco.opencv.opencv_java import org.opencv.core.Mat import org.opencv.imgcodecs.Imgcodecs import org.opencv.imgproc.Imgproc import java.nio.file.Path /** * * @author caseycheng * @date 2023/10/16-17:57 * @doc 不知道,不认识,第一次用,函数看上去有点见鬼是正常的。 **/ object OpenCVService { private val frameConverter = OpenCVFrameConverter.ToMat() private val logger = thisLogger<OpenCVService>() init { Loader.load(opencv_java::class.java) logger.info("opencv is ready") ShutDown.addShutDownHook("opencv") { frameConverter.close() } } suspend fun bgr2rgb(path: String): Mat { return conversion(path, Imgproc.COLOR_BGR2RGB) } suspend fun bgr2gray(path: String): Mat { return conversion(path, Imgproc.COLOR_BGR2GRAY) } /** * @param frameSpeed 数字越小 速度越快 */ suspend fun videoToGif( src: Path, savePath: Path, frameSpeed: Int = 3, ) { withContext(Dispatchers.Default) { try { if (savePath.basename().suffix().equals("GIF", true)) { FFmpegFrameGrabber(src.toFile()) .use { grabber -> grabber.start() val saveFile = savePath.toFile() if (!saveFile.exists()) { saveFile.createNewFile() } withContext(Dispatchers.IO) { saveFile.createNewFile() } FFmpegFrameRecorder(saveFile, grabber.imageWidth, grabber.imageHeight) .use { recorder -> recorder.videoCodec = avcodec.AV_CODEC_ID_GIF recorder.pixelFormat = avutil.AV_PIX_FMT_RGB8 recorder.start() //帧写入 recorder.writeFrame(grabber, frameSpeed) grabber.stop() } } } else { throw FileNotSupport("$src not is gif file") } } catch (e: Throwable) { throw e } } } suspend fun conversion( path: String, code: Int, ): Mat { val image: Mat val result = Mat() withContext(Dispatchers.IO) { image = Imgcodecs.imread(path) } withContext(Dispatchers.Default) { Imgproc.cvtColor(image, result, code) } return result } } class FileNotSupport(msg: String, cause: Throwable? = null) : RuntimeException(msg, cause) private fun FFmpegFrameRecorder.writeFrame(grabber: FFmpegFrameGrabber, frameSleep: Int) = use { recorder -> var frame: Frame? do { frame = grabber.grabImage() frame?.let { try { (0..<frameSleep).forEach { _ -> recorder.record(frame) } } catch (_: Throwable) { } } } while (frame != null) }
0
Kotlin
0
0
c6e213acebde1e41b335fee9a4d48f6244165ca9
3,818
telegram-stickers-collect-bot
MIT License
core/src/test/java/com/alessandro/core/repository/RemoteCo2RepositoryTest.kt
Alexs784
285,791,698
false
null
package com.alessandro.core.repository import com.alessandro.core.network.api.Co2API import com.alessandro.core.network.entity.Co2Entity import com.nhaarman.mockitokotlin2.given import kotlinx.coroutines.runBlocking import org.junit.Assert.assertEquals import org.junit.Before import org.junit.Test import org.junit.runner.RunWith import org.mockito.Mock import org.mockito.junit.MockitoJUnitRunner @RunWith(MockitoJUnitRunner::class) class RemoteCo2RepositoryTest() { @Mock private lateinit var co2Api: Co2API private lateinit var remoteCo2Repository: RemoteCo2Repository @Before fun setUp() { remoteCo2Repository = RemoteCo2RepositoryImpl(co2Api) } @Test fun shouldReturnLatestCo2DataOrdered() = runBlocking { val latestCo2Data = listOf( Co2Entity(0, 100, ""), Co2Entity(1, 200, "") ) given(co2Api.getLatestCo2Data()).willReturn(latestCo2Data) val result = remoteCo2Repository.getLatestCo2Data() assertEquals(latestCo2Data.reversed(), result) } }
0
Kotlin
0
0
2659c1f2109097030572a9e8f05f06cb08103f40
1,064
co2-client-android
MIT License
movie/src/main/java/com/koma/feature/movie/data/source/remote/WebService.kt
komamj
245,636,729
false
null
/* * Copyright 2020 komamj * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.koma.feature.movie.data.source.remote import com.koma.database.data.entities.Movie import com.koma.network.data.entities.DataModel import retrofit2.http.GET import retrofit2.http.POST import retrofit2.http.Path import retrofit2.http.Query interface WebService { @GET("movie/popular") suspend fun getPopularMovie(@Query("page") page: Int = 1): DataModel<Movie> @GET("movie/top_rated") suspend fun getTopRatedMovie(@Query("page") page: Int = 1): DataModel<Movie> @GET("movie/now_playing") suspend fun getNowPlayingMovie(@Query("page") page: Int = 1): DataModel<Movie> @GET("movie/upcoming") suspend fun getUpcomingMovie(@Query("page") page: Int = 1): DataModel<Movie> /** * Get a list of similar movies */ @GET("movie/{movie_id}/similar") suspend fun getSimilarMovie(@Path("movie_id") movieId: Int): DataModel<Movie> /** * Get a list of recommended movies for a movie. */ @GET("movie/{movie_id}/recommendations") suspend fun getRecommendedMovie(@Path("movie_id") movieId: Int): DataModel<Movie> @GET("movie/{movie_id}/images") suspend fun getImages(@Path("movie_id") movieId: Int) @POST("movie/{movie_id}/rating") suspend fun postRatingMovie(@Path("movie_id") movieId: Int) @GET("search/movie") suspend fun searchMovie( @Query("keyword") keyword: String, @Query("include_adult") includeAdult: Boolean = true ): DataModel<Movie> }
4
Kotlin
0
5
9e86144924bd77b0fd6d47b8243c70af4e77e56d
2,062
Movie
Apache License 2.0
app/src/main/java/com/siziksu/kotlinTicTacToe/presenter/login/LoginPresenter.kt
Siziksu
95,104,997
false
null
package com.siziksu.kotlinTicTacToe.presenter.login import android.support.design.widget.Snackbar import android.util.Log import android.view.View import com.google.firebase.auth.FirebaseAuth import com.google.firebase.auth.FirebaseAuthInvalidUserException import com.siziksu.kotlinTicTacToe.R import com.siziksu.kotlinTicTacToe.common.manager.NavigationManager import com.siziksu.kotlinTicTacToe.data.FirebaseDatabaseClient import com.siziksu.kotlinTicTacToe.view.main.MainActivity class LoginPresenter(private val view: ILoginView) : ILoginPresenter { companion object { private const val TAG: String = "LoginPresenter" } private val firebaseAuth by lazy { FirebaseAuth.getInstance() } private val firebaseDatabase by lazy { FirebaseDatabaseClient(view.getActivity()) } override fun onStart() { loadMainActivity() } override fun buttonClick(view: View) { when (view.id) { R.id.loginButton -> { signInIntoFirebase(view) } else -> return } } private fun signInIntoFirebase(view: View) { Log.i(TAG, "Trying to Sign in into Firebase") firebaseAuth?.signInWithEmailAndPassword(this.view.getEmail(), this.view.getPassword()) ?.addOnCompleteListener { if (it.isSuccessful) { loadMainActivity() } else { if (it.exception != null && it.exception is FirebaseAuthInvalidUserException) { Snackbar.make(view, it.exception?.message ?: view.context.getString(R.string.firebase_sign_in_fail), Snackbar.LENGTH_SHORT).show() Log.e(TAG, it.exception?.message, it.exception) } } } ?: nullFirebaseAuthInstance() } private fun signUpIntoFirebase(view: View) { Log.i(TAG, "Trying to Sign up into Firebase") firebaseAuth?.createUserWithEmailAndPassword(this.view.getEmail(), this.view.getPassword()) ?.addOnCompleteListener { if (it.isSuccessful) { loadMainActivity() } else { Snackbar.make(view, it.exception?.message ?: view.context.getString(R.string.firebase_sign_up_fail), Snackbar.LENGTH_SHORT).show() Log.e(TAG, it.exception?.message, it.exception) } } ?: nullFirebaseAuthInstance() } private fun nullFirebaseAuthInstance() { Log.e(TAG, view.getActivity().getString(R.string.firebase_auth_instance_null)) } private fun loadMainActivity() { val currentUser = firebaseAuth?.currentUser ?: return NavigationManager() .finishingCurrent() .putExtras(firebaseDatabase.getUserBundle(currentUser)) .goTo(view.getActivity(), MainActivity::class.java) } }
1
Kotlin
1
2
2baac27c4a4bf17f9a1d4891c270ca0f5048efbb
2,977
KotlinTicTacToeOnline
Apache License 2.0
health-services/ExerciseSample/app/src/main/java/com/example/exercise/FormattingUtils.kt
android
368,660,859
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 * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.example.exercise import android.text.style.RelativeSizeSpan import androidx.core.text.buildSpannedString import androidx.core.text.inSpans import java.time.Duration import java.util.concurrent.TimeUnit import kotlin.math.roundToInt private const val UNITS_RELATIVE_SIZE = .6f private val MINUTES_PER_HOUR = TimeUnit.HOURS.toMinutes(1) private val SECONDS_PER_MINUTE = TimeUnit.MINUTES.toSeconds(1) /** * Format an elapsed duration as `01m01s`. Hours are shown if present, e.g. `1h01m01s`. If * [includeSeconds] is `false`, seconds are omitted, e.g. `01m` or `1h01m`. */ fun formatElapsedTime(elapsedDuration: Duration, includeSeconds: Boolean) = buildSpannedString { val hours = elapsedDuration.toHours() if (hours > 0) { append(hours.toString()) inSpans(RelativeSizeSpan(UNITS_RELATIVE_SIZE)) { append("h") } } val minutes = elapsedDuration.toMinutes() % MINUTES_PER_HOUR append("%02d".format(minutes)) inSpans(RelativeSizeSpan(UNITS_RELATIVE_SIZE)) { append("m") } if (includeSeconds) { val seconds = elapsedDuration.seconds % SECONDS_PER_MINUTE append("%02d".format(seconds)) inSpans(RelativeSizeSpan(UNITS_RELATIVE_SIZE)) { append("s") } } } /** Format a distance to two decimals with a "km" suffix. */ fun formatDistanceKm(meters: Double) = buildSpannedString { append("%02.2f".format(meters / 1_000)) inSpans(RelativeSizeSpan(UNITS_RELATIVE_SIZE)) { append("km") } } /** Format calories burned to an integer with a "cal" suffix. */ fun formatCalories(calories: Double) = buildSpannedString { append(calories.roundToInt().toString()) inSpans(RelativeSizeSpan(UNITS_RELATIVE_SIZE)) { append(" cal") } }
5
Kotlin
38
58
58c3f3fe86ecea1107f66b836faead8dea4d0142
2,408
health-samples
Apache License 2.0
flux-app/src/main/kotlin/dev/buijs/vaadin/kotlin/dsl/example/app/views/accordion/AccordionPanel.kt
buijs-dev
663,918,620
false
null
package dev.buijs.vaadin.kotlin.dsl.example.app.views.accordion import com.vaadin.flow.component.details.DetailsVariant import dev.buijs.vaadin.flux.layout.Layout /** * Original Java code: * * ``` * package com.vaadin.demo.component.accordion; * * import com.vaadin.flow.component.accordion.Accordion; * import com.vaadin.flow.component.accordion.AccordionPanel; * import com.vaadin.flow.component.details.DetailsVariant; * import com.vaadin.flow.component.html.Div; * import com.vaadin.flow.component.html.Span; * import com.vaadin.flow.component.orderedlayout.VerticalLayout; * import com.vaadin.flow.router.Route; * * @Route("accordion-filled-panels") * public class AccordionFilledPanels extends Div { * * public AccordionFilledPanels() { * // tag::snippet[] * Accordion accordion = new Accordion(); * // end::snippet[] * * Span name = new Span("<NAME>"); * Span email = new Span("<EMAIL>"); * Span phone = new Span("(501) 555-9128"); * * VerticalLayout personalInformationLayout = new VerticalLayout(name, * email, phone); * personalInformationLayout.setSpacing(false); * personalInformationLayout.setPadding(false); * * // tag::snippet[] * AccordionPanel personalInfoPanel = accordion.add("Personal information", * personalInformationLayout); * personalInfoPanel.addThemeVariants(DetailsVariant.FILLED); * // end::snippet[] * * Span street = new Span("4027 Amber Lake Canyon"); * Span zipCode = new Span("72333-5884 Cozy Nook"); * Span city = new Span("Arkansas"); * * VerticalLayout billingAddressLayout = new VerticalLayout(); * billingAddressLayout.setSpacing(false); * billingAddressLayout.setPadding(false); * billingAddressLayout.add(street, zipCode, city); * * AccordionPanel billingAddressPanel = accordion.add("Billing address", * billingAddressLayout); * billingAddressPanel.addThemeVariants(DetailsVariant.FILLED); * * Span cardBrand = new Span("Mastercard"); * Span cardNumber = new Span("1234 5678 9012 3456"); * Span expiryDate = new Span("Expires 06/21"); * * VerticalLayout paymentLayout = new VerticalLayout(); * paymentLayout.setSpacing(false); * paymentLayout.setPadding(false); * paymentLayout.add(cardBrand, cardNumber, expiryDate); * * AccordionPanel paymentPanel = accordion.add("Payment", paymentLayout); * paymentPanel.addThemeVariants(DetailsVariant.FILLED); * * add(accordion); * } * * } * ``` */ class AccordionPanel(themeVariant: DetailsVariant) : Layout() { init { div { accordion { panel { + themeVariant summaryText = "Personal information" column { isSpacing = false isPadding = false span { text = "<NAME>" } span { text = "<EMAIL>" } span { text = "(501) 555-9128" } } } panel { + themeVariant summaryText = "Billing address" column { isSpacing = false isPadding = false span { text = "4027 Amber Lake Canyon" } span { text = "72333-5884 Cozy Nook" } span { text = "Arkansas" } } } panel { + themeVariant summaryText = "Payment" column { isSpacing = false isPadding = false span { text = "Mastercard" } span { text = "1234 5678 9012 3456" } span { text = "Expires 06/21" } } } } } } }
0
Kotlin
0
1
7893f53ef9c97dcfe6ac51f6a7377cb089a231c2
4,154
vaadin-flux
MIT License
app/src/androidTest/java/org/simple/clinic/sync/ProtocolSyncIntegrationTest.kt
simpledotorg
132,515,649
false
null
package org.simple.clinic.sync import com.f2prateek.rx.preferences2.Preference import com.google.common.truth.Truth.assertThat import org.junit.After import org.junit.Before import org.junit.Rule import org.junit.Test import org.junit.rules.RuleChain import org.simple.clinic.AppDatabase import org.simple.clinic.TestClinicApp import org.simple.clinic.patient.SyncStatus import org.simple.clinic.protocol.ProtocolRepository import org.simple.clinic.protocol.ProtocolSyncApi import org.simple.clinic.protocol.sync.ProtocolSync import org.simple.clinic.rules.SaveDatabaseRule import org.simple.clinic.rules.ServerAuthenticationRule import org.simple.clinic.user.UserSession import org.simple.sharedTestCode.util.Rules import java.util.Optional import javax.inject.Inject import javax.inject.Named class ProtocolSyncIntegrationTest { @Inject lateinit var appDatabase: AppDatabase @Inject lateinit var repository: ProtocolRepository @Inject @Named("last_protocol_pull_token") lateinit var lastPullToken: Preference<Optional<String>> @Inject lateinit var syncApi: ProtocolSyncApi @Inject lateinit var userSession: UserSession @Inject lateinit var syncInterval: SyncInterval @get:Rule val ruleChain: RuleChain = Rules .global() .around(ServerAuthenticationRule()) .around(SaveDatabaseRule()) private lateinit var sync: ProtocolSync private val batchSize = 3 private lateinit var config: SyncConfig @Before fun setUp() { TestClinicApp.appComponent().inject(this) resetLocalData() config = SyncConfig( syncInterval = syncInterval, pullBatchSize = batchSize, pushBatchSize = batchSize, name = "" ) sync = ProtocolSync( syncCoordinator = SyncCoordinator(), repository = repository, api = syncApi, lastPullToken = lastPullToken, config = config ) } private fun resetLocalData() { clearProtocolData() lastPullToken.delete() } private fun clearProtocolData() { appDatabase.protocolDao().clear() } @Test fun syncing_records_should_work_as_expected() { // when assertThat(repository.recordCount().blockingFirst()).isEqualTo(0) sync.pull() // then val pulledRecords = repository.recordsWithSyncStatus(SyncStatus.DONE) assertThat(pulledRecords).isNotEmpty() } }
3
null
73
236
ff699800fbe1bea2ed0492df484777e583c53714
2,371
simple-android
MIT License
app/src/main/java/com/bytemedrive/store/EventType.kt
bytemedrive
604,147,693
false
null
package com.bytemedrive.store import com.bytemedrive.file.EventFileDeleted import com.bytemedrive.file.EventFileUploaded import com.bytemedrive.folder.EventFolderCreated import com.bytemedrive.folder.EventFolderDeleted import com.bytemedrive.signup.EventCustomerSignedUp import com.bytemedrive.wallet.EventCouponRedeemed import com.fasterxml.jackson.annotation.JsonValue enum class EventType(@JsonValue val code: String, val clazz: Class<*>) { COUPON_REDEEMED("coupon-redeemed", EventCouponRedeemed::class.java), FILE_DELETED("file-deleted", EventFileDeleted::class.java), FILE_UPLOADED("file-uploaded", EventFileUploaded::class.java), FOLDER_CREATED("folder-created", EventFolderCreated::class.java), FOLDER_DELETED("folder-deleted", EventFolderDeleted::class.java), CUSTOMER_SIGNED_UP("customer-signed-up", EventCustomerSignedUp::class.java); companion object { fun of(code: String): EventType { for (value in EventType.values()) { if (value.code == code) { return value } } throw IllegalArgumentException("There is no EventType with name: $code") } fun of(clazz: Class<*>): EventType { for (value in EventType.values()) { if (value.clazz.isAssignableFrom(clazz)) { return value } } throw IllegalArgumentException("There is no EventType with class: $clazz") } } }
0
Kotlin
0
0
7ba075f31fa6d154cfcd6d8b243e8f8359d2a142
1,512
android
MIT License
src/main/kotlin/io/github/rafaeljpc/springboot/thymeleaf/dto/SomeDataDTO.kt
rafaeljpc
816,434,596
false
{"Kotlin": 3933, "HTML": 1815, "Dockerfile": 360}
package io.github.rafaeljpc.springboot.thymeleaf.dto import java.time.LocalDateTime data class SomeDataDTO( val id: Long? = null, val nome: String, val email: String, val createdAt: LocalDateTime = LocalDateTime.now() )
0
Kotlin
0
0
35c05c20d2386b6f5324586f8983896a2b5e5427
238
springboot-thymeleaf
Apache License 2.0
src/main/kotlin/dev/int21/maniac/unpacker/UnpackedFile.kt
cketti
497,712,490
false
null
package dev.int21.maniac.unpacker import okio.ByteString data class UnpackedFile( val packedData: ByteString, val header: MzHeader, val relocations: List<Relocation>, val operations: List<Operation> )
0
Kotlin
0
0
da77b2f6688f177f91b8f03ad79dec382d46b4ce
211
maniac-unpacker
Apache License 2.0
lib/src/main/kotlin/com/maltaisn/icondialog/pack/IconPackLoader.kt
maltaisn
129,983,346
false
null
/* * Copyright 2019 <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.maltaisn.icondialog.pack import android.content.Context import android.content.res.XmlResourceParser import androidx.annotation.XmlRes import com.maltaisn.icondialog.data.* import com.maltaisn.icondialog.normalize import org.xmlpull.v1.XmlPullParser import java.util.* /** * Class for loading icon packs from XML resources. * @param context Any context, needed to load the XML resources. */ class IconPackLoader(context: Context) { private val context = context.applicationContext var drawableLoader = IconDrawableLoader(context) internal set /** * Load an icon pack from XML resources for icons and tags. * * @param iconsXml XML resource containing the icons * @param tagsXml XML resource containing the tags, can be `0` if there aren't tags. * @param locales List of locales supported by the icon pack, can be empty if there are no tags. * @param parent Parent pack for inheriting data, can be `null` for none. * * @throws IconPackParseException Thrown when icons or tags XML is invalid. */ fun load(@XmlRes iconsXml: Int, @XmlRes tagsXml: Int = 0, locales: List<Locale> = emptyList(), parent: IconPack? = null): IconPack { val pack = IconPack(parent = parent, locales = locales, tagsXml = tagsXml) loadIcons(pack, iconsXml) loadTags(pack) return pack } /** * Reload the tag values of an icon [pack] and its parents, as * well as category names. This must be called whenever the application language changes. * A `BroadcastListener` should be attached to listen for this event. * * Note that since [Category] and [NamedTag] are immutable, this will change all instances. * * @throws IconPackParseException Thrown when tags XML is invalid. */ fun reloadStrings(pack: IconPack) { if (pack.parent != null) { reloadStrings(pack.parent) } // Clear and load tags pack.tags.clear() loadTags(pack) // Reload category names for ((id, category) in pack.categories) { if (category.nameRes != 0) { pack.categories[id] = category.copy(name = context.getString(category.nameRes)) } } } private fun loadIcons(pack: IconPack, @XmlRes iconsXml: Int) { val newIcons = mutableMapOf<Int, Icon>() val newCategories = mutableMapOf<Int, Category>() var categoryId = Icon.NO_CATEGORY var documentStarted = false var iconStarted = false var packWidth = 0 var packHeight = 0 val parser = context.resources.getXml(iconsXml) var eventType = parser.eventType while (eventType != XmlPullParser.END_DOCUMENT) { val element = parser.name if (eventType == XmlPullParser.START_TAG) { if (element == XML_TAG_ICONS) { documentStarted = true packWidth = parser.getPositiveInt(XML_ATTR_ICON_WIDTH) { "Invalid global icon width '$it'." } ?: 24 packHeight = parser.getPositiveInt(XML_ATTR_ICON_HEIGHT) { "Invalid global icon height '$it'." } ?: 24 } else { if (!documentStarted) parseError("Invalid root element <$element>.") if (iconStarted) parseError("Icon element cannot have body.") when (element) { XML_TAG_CATEGORY -> { if (categoryId != Icon.NO_CATEGORY) parseError("Nested category element is not allowed.") val category = parseCategory(parser, pack) categoryId = category.id if (categoryId in newCategories) { parseError("Duplicate category ID '$categoryId' in same file.") } newCategories[categoryId] = category } XML_TAG_ICON -> { val icon = parseIcon(parser, pack, categoryId, packWidth, packHeight) if (icon.id in newIcons) { parseError("Duplicate icon ID '${icon.id}' in same file.") } newIcons[icon.id] = icon iconStarted = true } else -> parseError("Unknown element <$element>.") } } } else if (eventType == XmlPullParser.END_TAG) { if (element == XML_TAG_CATEGORY) { categoryId = Icon.NO_CATEGORY } else if (element == XML_TAG_ICON) { iconStarted = false } } eventType = parser.next() } // Add new elements pack.icons += newIcons pack.categories += newCategories } private fun parseCategory(parser: XmlResourceParser, pack: IconPack): Category { val id = parser.getPositiveInt(XML_ATTR_CATG_ID) { "Invalid category ID '$it'." } ?: parseError("Category must have an ID.") val nameRes: Int val name: String val nameStr = parser.getAttributeValue(null, XML_ATTR_CATG_NAME) if (nameStr != null) { if (nameStr.startsWith('@')) { nameRes = if (nameStr.startsWith("@string/")) { // There's an AAPT bug where the string reference isn't changed to an ID // in XML resources. Resolve string resource from name. // See https://github.com/maltaisn/icondialoglib/issues/13. context.resources.getIdentifier( nameStr.substring(8), "string", context.packageName) } else { nameStr.substring(1).toIntOrNull() ?: 0 } name = context.getString(nameRes) } else { // No string resource, hardcoded string name. nameRes = 0 name = nameStr } } else { // Check if name can be inherited from overriden category. val overriden = pack.getCategory(id) if (overriden != null) { nameRes = overriden.nameRes name = overriden.name } else { parseError("Missing name for category ID $id.") } } return Category(id, name, nameRes) } private fun parseIcon(parser: XmlResourceParser, pack: IconPack, categoryId: Int, packWidth: Int, packHeight: Int): Icon { val id = parser.getPositiveInt(XML_ATTR_ICON_ID) { "Invalid icon ID '$it'." } ?: parseError("Icon must have an ID.") val overriden = pack.getIcon(id) val catgId = parser.getPositiveInt(XML_ATTR_ICON_CATG) { "Invalid icon category ID '$it'." } ?: overriden?.categoryId ?: categoryId val tagsStr = parser.getAttributeValue(null, XML_ATTR_ICON_TAGS) val tags: List<String> if (tagsStr != null) { tags = tagsStr.split(',') // Add any grouping tags to the pack. for (tag in tags) { if (tag.startsWith('_')) { pack.tags[tag] = GroupingTag(tag) } } } else { // Check if tags can be inherited from overriden icon. tags = overriden?.tags ?: emptyList() } val pathStr = parser.getAttributeValue(null, XML_ATTR_ICON_PATH) val pathData = pathStr ?: overriden?.pathData ?: "" val srcStr = parser.getAttributeValue(null, XML_ATTR_ICON_SRC) val srcId = srcStr?.let { parseDrawableId(it) } ?: overriden?.srcId if (pathData.isBlank() && srcId == null) { parseError("Icon ID $id has no path data and no drawable resource specified.") } val width = parser.getPositiveInt(XML_ATTR_ICON_WIDTH) { "Invalid icon width '$it'." } ?: packWidth val height = parser.getPositiveInt(XML_ATTR_ICON_HEIGHT) { "Invalid icon height '$it'." } ?: packHeight return Icon(id, catgId, tags, pathData, width, height, srcId) } private fun parseDrawableId(str: String) = if (str.startsWith('@')) { if (str.startsWith("@drawable/")) { context.resources.getIdentifier( str.substring(10), "drawable", context.packageName) } else { str.substring(1).toIntOrNull() } } else { null } /** * Load tags of a [pack]. */ private fun loadTags(pack: IconPack) { if (pack.tagsXml == 0) { // This icon pack has no tags. return } val newTags = mutableMapOf<String, IconTag>() var tagName: String? = null val tagValues = mutableListOf<NamedTag.Value>() var singleValueTag = false val parser = context.resources.getXml(pack.tagsXml) var documentStarted = false var aliasStarted = false var eventType = parser.eventType while (eventType != XmlPullParser.END_DOCUMENT) { val element = parser.name when (eventType) { XmlPullParser.START_TAG -> if (element == XML_TAG_TAGS) { documentStarted = true } else { if (!documentStarted) { parseError("Invalid root element <$element>.") } if (aliasStarted) { parseError("Alias cannot have nested elements.") } if (element == XML_TAG_TAG) { if (tagName != null) { parseError("Nested tag element is not allowed.") } tagName = parser.getAttributeValue(null, XML_ATTR_TAG_NAME) ?: parseError("Tag element has no name attribute.") if (tagName.startsWith('_')) { parseError("Grouping tag '$tagName' not allowed in labels XML.") } else if (tagName in newTags) { parseError("Duplicate tag '$tagName' in same file.") } singleValueTag = false } else if (element == XML_TAG_ALIAS) { if (tagName == null) { parseError("Alias element must be in tag element body.") } if (singleValueTag) { parseError("Tag cannot have both a value and aliases.") } aliasStarted = true } else { parseError("Unknown element <$element>.") } } XmlPullParser.TEXT -> { if (tagName != null) { // Tag or alias value. // Replace backtick used to imitate single quote since they cannot be escaped due to AAPT bug... val text = parser.text.replace('`', '\'') val value = NamedTag.Value(text, text.normalize()) when { aliasStarted -> { tagValues += value } tagValues.isEmpty() -> { tagValues += value singleValueTag = true } else -> { parseError("Tag cannot have both a value and aliases.") } } } } XmlPullParser.END_TAG -> if (element == XML_TAG_TAG && tagName != null) { // Add new tag newTags[tagName] = NamedTag(tagName, tagValues.toList()) tagName = null tagValues.clear() singleValueTag = false } else if (element == XML_TAG_ALIAS) { aliasStarted = false } } eventType = parser.next() } // Add new tags pack.tags += newTags } private inline fun XmlResourceParser.getPositiveInt(attr: String, error: (String) -> String): Int? { val str = getAttributeValue(null, attr) ?: return null val value = str.toIntOrNull() if (value == null || value < 0) { parseError(error(str)) } return value } companion object { // XML elements and attributes private const val XML_TAG_ICONS = "icons" private const val XML_TAG_TAGS = "tags" private const val XML_TAG_CATEGORY = "category" private const val XML_ATTR_CATG_ID = "id" private const val XML_ATTR_CATG_NAME = "name" private const val XML_TAG_ICON = "icon" private const val XML_ATTR_ICON_ID = "id" private const val XML_ATTR_ICON_CATG = "category" private const val XML_ATTR_ICON_TAGS = "tags" private const val XML_ATTR_ICON_PATH = "path" private const val XML_ATTR_ICON_WIDTH = "width" private const val XML_ATTR_ICON_HEIGHT = "height" private const val XML_ATTR_ICON_SRC = "src" private const val XML_TAG_TAG = "tag" private const val XML_TAG_ALIAS = "alias" private const val XML_ATTR_TAG_NAME = "name" } } class IconPackParseException(message: String) : Exception(message) private fun parseError(message: String): Nothing = throw IconPackParseException(message)
1
null
15
111
c561f68bf302a94626631d1930b88f4faf45528c
14,720
icondialoglib
Apache License 2.0
util/common/src/main/kotlin/org/randomcat/agorabot/util/Update.kt
randomnetcat
291,139,813
false
null
package org.randomcat.agorabot.util @PublishedApi internal object UpdateAndExtractUninit inline fun <T, V> doUpdateAndExtract(runUpdate: ((T) -> T) -> Unit, crossinline mapper: (T) -> Pair<T, V>): V { var extractedValue: Any? = UpdateAndExtractUninit runUpdate { val result = mapper(it) extractedValue = result.second result.first } // Protect against a hostile runUpdate trying to change this with a race val finalValue = extractedValue check(finalValue !== UpdateAndExtractUninit) @Suppress("UNCHECKED_CAST") // This is known to be safe. It must either be a V or UpdateAndExtractUninit, and it's been checked to not be the // latter. return finalValue as V }
0
null
3
6
6495faedfcc0cc59569c6e605c4c740633dd89c2
731
AgoraBot
MIT License
kotlin-electron/src/jsMain/generated/electron/core/DisplayTouchSupport.kt
JetBrains
93,250,841
false
{"Kotlin": 12635434, "JavaScript": 423801}
// Generated by Karakum - do not modify it manually! package electron.core @seskar.js.JsVirtual sealed external interface DisplayTouchSupport { companion object { @seskar.js.JsValue("available") val available: DisplayTouchSupport @seskar.js.JsValue("unavailable") val unavailable: DisplayTouchSupport @seskar.js.JsValue("unknown") val unknown: DisplayTouchSupport } }
40
Kotlin
165
1,347
997ed3902482883db4a9657585426f6ca167d556
429
kotlin-wrappers
Apache License 2.0
common/test-utils/src/main/java/com/mobdao/common/testutils/mockfactories/domain/SearchFilterMockFactory.kt
diegohkd
764,734,288
false
{"Kotlin": 275860}
package com.mobdao.common.testutils.mockfactories.domain import com.mobdao.domain.models.Address import com.mobdao.domain.models.SearchFilter import io.mockk.every import io.mockk.mockk object SearchFilterMockFactory { fun create( address: Address = AddressMockFactory.create(), petType: String? = "petType", ): SearchFilter = mockk { every { [email protected] } returns address every { [email protected] } returns petType } }
0
Kotlin
0
0
06b0a64f7882e3e9b95e0a517591f4dd86db0aaa
496
AdoptAPet
Apache License 2.0
src/main/kotlin/org/cdb/labwitch/models/embed/SubSubUnit.kt
CodeDrillBrigade
714,769,385
false
{"Kotlin": 35591}
package org.cdb.labwitch.models.embed import kotlinx.serialization.Serializable @Serializable data class SubSubUnit( val value: Float, val metric: Metric, )
2
Kotlin
0
0
d61c00de00a28ea260ca3b5efbfc6c2a7b56d6fc
161
LabWitchery-backend
MIT License
src/test/kotlin/com/github/kerubistan/kerub/security/AssetAccessControllerTestUtils.kt
kerubistan
19,528,622
false
null
package com.github.kerubistan.kerub.security import com.github.kerubistan.kerub.model.Asset import com.github.kerubistan.kerub.testDisk import com.nhaarman.mockito_kotlin.any import com.nhaarman.mockito_kotlin.doAnswer import com.nhaarman.mockito_kotlin.eq import com.nhaarman.mockito_kotlin.whenever fun <T : Asset> AssetAccessController.mockAccessGranted(asset: T) { doAnswer { mockInvocation -> (mockInvocation.arguments[1] as () -> Any).invoke() }.whenever(this).checkAndDo(eq(testDisk), any<() -> Any>()) doAnswer { mockInvocation -> (mockInvocation.arguments[0] as () -> T).invoke() }.whenever(this).doAndCheck(any<() -> T>()) }
109
Kotlin
4
14
99cb43c962da46df7a0beb75f2e0c839c6c50bda
644
kerub
Apache License 2.0
list_repos/app/src/main/java/com/sheraz/listrepos/data/network/GitHubNetworkDataSource.kt
sheraz-nadeem
173,899,762
false
null
package com.sheraz.listrepos.data.network import androidx.lifecycle.LiveData import com.sheraz.listrepos.data.db.entity.GitHubRepoEntity interface GitHubNetworkDataSource { val downloadedGitHubRepoList: LiveData<Result<List<GitHubRepoEntity>>> suspend fun loadGitHubRepos(page: Int, per_page: Int) companion object { const val ERROR_MESSAGE = "Error loading github repos data" } }
0
Kotlin
3
5
2b6583bb1b5895daabb17bd7c2bd6cdd4dbb8d1b
408
ListGitHubRepos
Apache License 2.0
spdx-utils/src/main/kotlin/Extensions.kt
misha-codescoop
137,860,944
true
{"Kotlin": 1166773, "JavaScript": 217268, "HTML": 12814, "Python": 8342, "CSS": 4779, "Ruby": 3694, "Dockerfile": 2091, "ANTLR": 1861, "Shell": 744, "Go": 164}
/* * Copyright (C) 2017-2019 HERE Europe B.V. * * 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. * * SPDX-License-Identifier: Apache-2.0 * License-Filename: LICENSE */ package com.here.ort.spdx import java.util.EnumSet /** * Return an [EnumSet] that contains the elements of [this] and [other]. */ operator fun <E : Enum<E>> EnumSet<E>.plus(other: EnumSet<E>): EnumSet<E> = EnumSet.copyOf(this).apply { addAll(other) }
0
Kotlin
0
0
8995d27bf952103beec93279fd4cde2bec70ee75
936
oss-review-toolkit
Apache License 2.0
src/main/kotlin/net/adikm/PersonController.kt
adikm
120,223,161
false
null
package net.adikm import mu.KLogging import org.springframework.http.HttpStatus import org.springframework.web.bind.annotation.* import reactor.core.publisher.Flux @RestController @RequestMapping("/persons") class PersonController { @GetMapping @ResponseStatus(HttpStatus.OK) fun getAll(): Flux<Person> { logger.info { "Returning list of Person objects" } return Flux.just(Person("John", "Doe", 12), Person("Amanda", "Doe", 14)) } companion object : KLogging() }
0
Kotlin
2
1
f88fbfa41840a987febef25b5fbced372d0f4f62
505
spring-boot-kotlin-maven-demo
Apache License 2.0
zircon.core/src/commonMain/kotlin/org/hexworks/zircon/api/behavior/TextHolder.kt
Xanik
282,687,897
true
{"Kotlin": 1516693, "Java": 96889}
package org.hexworks.zircon.api.behavior import org.hexworks.cobalt.databinding.api.property.Property import org.hexworks.zircon.internal.behavior.impl.DefaultTextHolder import kotlin.jvm.JvmStatic /** * Represents an object which holds [text]. */ interface TextHolder { var text: String val textProperty: Property<String> companion object { @JvmStatic fun create(initialText: String = ""): TextHolder = DefaultTextHolder(initialText) } }
1
null
1
2
bf435cddeb55f7c3a9da5dd5c29be13af8354d0f
480
zircon
Apache License 2.0
composeApp/src/desktopMain/kotlin/Platform.jvm.kt
anwar-pasaribu
716,868,825
false
{"Kotlin": 173772, "Ruby": 3031, "Swift": 568}
import config.PlatformType import java.util.Locale class JVMPlatform: Platform { override val name: String = "Java ${System.getProperty("java.version")}" override val type: PlatformType get() = PlatformType.DESKTOP } actual fun getPlatform(): Platform = JVMPlatform() actual val Double.formatNominal: String get() { return "%,.0f".format(Locale.GERMAN, this) }
0
Kotlin
0
0
4f461e0eb5cad2ccc4b08c13b159eba2bbb00047
395
Etong
MIT License
app/src/main/java/com/nsk/app/bussiness/index/IndexFragment.kt
StephenGiant
230,359,216
false
null
package com.nsk.app.bussiness.index import android.content.Context import android.content.Intent import android.databinding.DataBindingUtil import android.databinding.ViewDataBinding import android.net.Uri import android.os.Build import android.support.v4.content.FileProvider import android.support.v7.widget.GridLayoutManager import android.support.v7.widget.LinearLayoutManager import android.support.v7.widget.RecyclerView import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.webkit.URLUtil import android.widget.ImageView import android.widget.TextView import com.alibaba.android.arouter.launcher.ARouter import com.bumptech.glide.Glide import com.google.gson.Gson import com.google.gson.JsonElement import com.google.gson.reflect.TypeToken import com.nsk.app.base.BaseAdapterWithBinding import com.nsk.app.base.BaseContentFragment import com.nsk.app.base.BaseViewHolder import com.nsk.app.business.extension.parseData import com.nsk.app.bussiness.index.viewmodel.IndexInfoBean import com.nsk.app.caikangyu.BR import com.nsk.app.caikangyu.R import com.czm.library.LogUtil import com.google.gson.JsonArray import com.nsk.app.caikangyu.databinding.FragmentIndexBinding import com.nsk.app.caikangyu.databinding.ItemIndexbuttonsBinding import com.nsk.app.config.ApiConfig import com.nsk.app.config.CkyApplication import com.nsk.app.config.GlideImageLoader import com.nsk.app.config.Routers import com.nsk.app.utils.RxjavaUtils import com.nsk.app.widget.MyDividerItemDecoration import com.nsk.cky.ckylibrary.base.BaseWebActivity import com.nsk.cky.ckylibrary.utils.WebUtils import com.nsk.cky.ckylibrary.widget.RecyclerItemCLickListenner import com.scwang.smartrefresh.layout.api.RefreshLayout import com.scwang.smartrefresh.layout.listener.OnRefreshListener import com.youth.banner.Banner import com.youth.banner.listener.OnBannerListener import com.zhy.view.flowlayout.FlowLayout import com.zhy.view.flowlayout.TagAdapter import com.zhy.view.flowlayout.TagFlowLayout import java.io.File class IndexFragment :BaseContentFragment() ,OnBannerListener{ var banner :Banner?=null var index_refresh :ViewGroup?=null var bind:FragmentIndexBinding?=null var inited:Int = 0 var cardList:ArrayList<IndexInfoBean.LoanInfo>?=null var inviteList:ArrayList<IndexInfoBean.InviteInfo>?=null var bannerurls = ArrayList<String>() var banners:JsonArray?=null override fun getContentLayoutId(): Int { return R.layout.fragment_index } override fun initView(view: View) { bind = DataBindingUtil.bind<FragmentIndexBinding>(view) bind!!.ivNotify.setOnClickListener({ if(CkyApplication.getApp().hasToken()) { ARouter.getInstance().build(Routers.mynotice).navigation() }else{ ARouter.getInstance().build(Routers.login).navigation() } }) bind!!.indexRefresh.setOnRefreshListener(object :OnRefreshListener{ override fun onRefresh(refreshLayout: RefreshLayout) { bind!!.indexRefresh.finishRefresh(2000) initData() } }) //设置图片加载器 banner = view.findViewById<Banner>(R.id.banner) index_refresh = view.findViewById<ViewGroup>(R.id.index_refresh) banner!!.setImageLoader(GlideImageLoader()) banner!!.setOnBannerListener(this) banner!!.setDelayTime(6000) LogUtil.getInstance().upload(activity) val layoutManager1 = object :LinearLayoutManager(activity){ override fun canScrollVertically(): Boolean { return false } } val layoutManager2 = object :LinearLayoutManager(activity){ override fun canScrollVertically(): Boolean { return false } } val layoutManager3 = object :LinearLayoutManager(activity){ override fun canScrollVertically(): Boolean { return false } } val layoutManager4 = object :GridLayoutManager(activity,3){ override fun canScrollVertically(): Boolean { return false } } bind!!.rvCards.setHasFixedSize(true) bind!!.rvAds.setHasFixedSize(true) bind!!.rvButtons.setHasFixedSize(true) bind!!.rvYaoqing.setHasFixedSize(true) bind!!.rvAds.layoutManager = layoutManager1 bind!!.rvCards.layoutManager =layoutManager2 bind!!.rvYaoqing.layoutManager=layoutManager3 bind!!.rvButtons.layoutManager = layoutManager4 val decoration = MyDividerItemDecoration(LinearLayoutManager.VERTICAL) decoration.setDrawable(resources.getDrawable(R.drawable.spacedrawable)) bind!!.rvCards.addItemDecoration(decoration) //体检团购 // ll_medical.setOnClickListener{ // ARouter.getInstance().build(Routers.cards).navigation() // } // //医疗特需 // ll_need.setOnClickListener{ // // } // //积分兑换 // ll_exchange.setOnClickListener{ // // } } var bannerClickUrl=ArrayList<String>() override fun initData() { // ToastUtils.showLong("initData") serviceApi.getForString(ApiConfig.page_index_url+"?userId="+"").parseData(object :RxjavaUtils.CkySuccessConsumer(){ override fun onSuccess(jsonElement: JsonElement?) { val gson = Gson() val datajson = jsonElement!!.asJsonObject banners = datajson.get("layout_lunbo").asJsonArray //轮播图坑位信息 val yaoqingjsonarray = datajson.get("layout_yaoqing").asJsonArray //邀请坑位信息 val adsjsonarray = datajson.get("layout_ads").asJsonArray //广告坑位信息 val cardjsonarray = datajson.get("layout_creditOrLoan").asJsonArray//信用卡贷款坑位信息 val healthjsonarray = datajson.get("layout_yiliao").asJsonArray //医疗坑位信息 bannerurls.clear() for (i:Int in 0..banners!!.size()-1){ bannerClickUrl.add(banners!!.get(i).asJsonObject.get("n_link_value").asString) bannerurls.add(banners!!.get(i).asJsonObject.get("n_content").asString) } banner!!.setImages(bannerurls) banner!!.start() val yiliaoList = gson.fromJson<ArrayList<IndexInfoBean.YiliaoInfo>>(healthjsonarray,object :TypeToken<ArrayList<IndexInfoBean.YiliaoInfo>>(){}.type) yiliaoList.get(0).name = "体检团购" yiliaoList.get(1).name = "医疗特需" yiliaoList.get(2).name = "积分兑换" cardList = gson.fromJson<ArrayList<IndexInfoBean.LoanInfo>>(cardjsonarray,object :TypeToken<ArrayList<IndexInfoBean.LoanInfo>>(){}.type) val adlist = gson.fromJson<ArrayList<IndexInfoBean.AdInfo>>(adsjsonarray,object :TypeToken<ArrayList<IndexInfoBean.AdInfo>>(){}.type) inviteList = gson.fromJson<ArrayList<IndexInfoBean.InviteInfo>>(yaoqingjsonarray,object :TypeToken<ArrayList<IndexInfoBean.InviteInfo>>(){}.type) val adapter = object :BaseAdapterWithBinding<IndexInfoBean.YiliaoInfo>(yiliaoList){ override fun getLayoutResource(viewType: Int): Int { return R.layout.item_indexbuttons } override fun onBindViewHolder(holder: BaseViewHolder, position: Int) { super.onBindViewHolder(holder, position) val b = holder.binding as ItemIndexbuttonsBinding Glide.with(holder.itemView.context).load(yiliaoList.get(position).n_content).into(b.ivIndexbutton) val imageview = b.ivIndexbutton } override fun setVariableID(): Int { return BR.yiliaoinfo } override fun getItemCount(): Int { return 3 } } bind!!.rvButtons.adapter = adapter if(inited==0) { bind!!.rvButtons.addOnItemTouchListener(object : RecyclerItemCLickListenner(activity!!) { override fun onItemClick(view: View, position: Int) { when (position) { 0 -> { ARouter.getInstance().build(Routers.workphy).navigation() } 1 -> ARouter.getInstance().build(Routers.health_index).navigation() 2 -> { if (CkyApplication.getApp().hasToken()) { ARouter.getInstance().build(Routers.myscore).navigation() } else { ARouter.getInstance().build(Routers.login).navigation() } } } } }) } val loanAdapter = object :BaseAdapterWithBinding<IndexInfoBean.LoanInfo>(cardList!!){ override fun getLayoutResource(viewType: Int): Int { return R.layout.item_index_card } override fun setVariableID(): Int { return BR.indexcardmodel } override fun getItemCount(): Int { return cardList!!.size } } bind!!.rvCards.adapter = resetList(cardList!!) if(inited==0) { bind!!.rvCards.addOnItemTouchListener(object : RecyclerItemCLickListenner(activity!!) { override fun onItemClick(view: View, position: Int) { if (cardList!!.get(position).creditCard == null) { if(cardList!!.get(position).loan!=null) ARouter.getInstance().build(Routers.loanDetail).withString("loanid", cardList!!.get(position).loan.n_loan_id.toString()).navigation() } else { ARouter.getInstance().build(Routers.cred_cards).withString("id", cardList!!.get(position).creditCard.nsk_inner_credit_card.n_loan_id.toString()).navigation() // ARouter.getInstance().build(Routers.cred_cards).withString("id", cardList.get(position).creditCard.nsk_inner_credit_card.n_loan_id.toString()).navigation() // FinestWebView.Builder(activity as AppCompatActivity).show(cardList.get(position).creditCard.nsk_inner_credit_card.) } } }) } val adsAdapter = object :BaseAdapterWithBinding<IndexInfoBean.AdInfo>(adlist){ override fun getLayoutResource(viewType: Int): Int { return R.layout.item_index_recom } override fun setVariableID(): Int { return BR.recommodel } override fun getItemCount(): Int { return adlist.size } } bind!!.rvAds.adapter = adsAdapter if(inited==0) { bind!!.rvAds.addOnItemTouchListener(object : RecyclerItemCLickListenner(activity!!) { override fun onItemClick(view: View, position: Int) { when(adlist.get(position).n_link_type){ 1->{ val intent = Intent(activity,BaseWebActivity::class.java) if(URLUtil.isHttpUrl(adlist.get(position).n_link_value)) { intent.putExtra("url", adlist.get(position).n_link_value) startActivity(intent) } } 4->{ //一键办卡 ARouter.getInstance().build(Routers.one_key_cards).navigation() } } } }) } val inviteAdapter = object :BaseAdapterWithBinding<IndexInfoBean.InviteInfo>(inviteList!!){ override fun getLayoutResource(viewType: Int): Int { return R.layout.item_index_invite } override fun setVariableID(): Int { return BR.invitemodel } override fun getItemCount(): Int { if(inviteList!=null&&inviteList!!.size>0) { return 1 }else{ return 0 } } override fun onBindViewHolder(holder: BaseViewHolder, position: Int) { super.onBindViewHolder(holder, position) val textView = holder.itemView.findViewById<TextView>(R.id.tv_table_name) textView.text = inviteList!!.get(1).n_content } } bind!!.rvYaoqing.adapter = inviteAdapter //邀请有礼 if(inited==0) { bind!!.rvYaoqing.addOnItemTouchListener(object : RecyclerItemCLickListenner(activity!!) { override fun onItemClick(view: View, position: Int) { // FinestUtils.start(activity as Activity,inviteList[0].n_link_value) if (CkyApplication.getApp().hasToken()) { ARouter.getInstance().build(Routers.invite_activity).navigation() } else { ARouter.getInstance().build(Routers.login).navigation() } } }) } if(inited==0) { inited = 1 } } },object :RxjavaUtils.CkyErrorConsumer(){ override fun onCkyError(code: String?, message: String?) { super.onCkyError(code, message) } }) } override fun OnBannerClick(position: Int) { val jsonObject = banners!!.get(position).asJsonObject val type = jsonObject.get("n_link_type").asInt when(type){ 1->{ val intent = Intent(activity,BaseWebActivity::class.java) if(URLUtil.isHttpUrl(bannerClickUrl[position])) { intent.putExtra("url", bannerClickUrl[position]) startActivity(intent) } } 2->{ //信用卡 ARouter.getInstance().build(Routers.cred_cards).withString("id", jsonObject.get("n_link_value").asString).navigation() } 3->{ //贷款 ARouter.getInstance().build(Routers.loanDetail).withString("loanid", jsonObject.get("n_link_value").asString).navigation() } 4->{ //红包 if(CkyApplication.getApp().hasToken()){ ARouter.getInstance().build(Routers.mypacket).navigation() }else{ ARouter.getInstance().build(Routers.login).navigation() } } 5->{ //nothing // ARouter.getInstance().build(Routers.one_key_cards).navigation() } } //banner点击事件 // FinestUtils.start(index_refresh,activity as Context, bannerClickUrl[position]) } fun resetList(cardList:ArrayList<IndexInfoBean.LoanInfo>):RecyclerView.Adapter<BaseViewHolder>{ val adapter =object :RecyclerView.Adapter<BaseViewHolder>(){ override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): BaseViewHolder { if(viewType==1) { val view = LayoutInflater.from(parent.context).inflate(R.layout.item_index_creadicard, parent, false) return BaseViewHolder(view) }else{ val dataBinding = DataBindingUtil.inflate<ViewDataBinding>(LayoutInflater.from(parent.context), R.layout.item_index_card, parent, false) val holder = object : BaseViewHolder(dataBinding.root){} holder.binding = dataBinding return holder // view = LayoutInflater.from(parent.context).inflate(R.layout.item_index_card, parent, false) } } override fun getItemCount(): Int { return cardList.size } override fun onBindViewHolder(holder: BaseViewHolder, position: Int) { val type = holder.itemViewType if(type==1){ //1是信用卡 val iv = holder.itemView.findViewById<ImageView>(R.id.iv_bank) val title = holder.itemView.findViewById<TextView>(R.id.tv_title) val tv_sub_title = holder.itemView.findViewById<TextView>(R.id.tv_sub_title) val tvContent= holder.itemView.findViewById<TagFlowLayout>(R.id.tv_content) val tv_apply = holder.itemView.findViewById<TextView>(R.id.tv_apply) title.text = cardList.get(position).creditCard.nsk_inner_credit_card.n_loan_title Glide.with(holder.itemView.context).load(cardList.get(position).creditCard.nsk_inner_credit_card.n_loan_logo_url).into(iv) tv_sub_title.text = cardList.get(position).creditCard.nsk_inner_credit_card.n_loan_subheading tv_apply!!.setOnClickListener { //信用卡详情 申请 // ARouter.getInstance().build(Routers.cred_cards).withString("id", cardList.get(position).creditCard.nsk_inner_credit_card.n_loan_bankid.toString()).navigation() // ARouter.getInstance().build(Routers.cred_cards).withString("id", cardList.get(position).creditCard.nsk_inner_credit_card.n_loan_id.toString()).navigation() } tvContent!!.adapter = object : TagAdapter<String>(cardList.get(position).creditCard.n_credit_card_tags) { override fun getView(parent: FlowLayout, position: Int, s: String): View { if(position>1){ val view = View(activity) view.visibility=View.GONE return view } val tv =LayoutInflater.from(activity).inflate(R.layout.tv,tvContent, false) as TextView tv.setTextColor(resources.getColor(R.color.orange_main)) tv.text = s return tv } } }else{ //2是贷款 holder.binding!!.setVariable(BR.indexcardmodel,cardList!!.get(position)) holder.binding!!.executePendingBindings() } } override fun getItemViewType(position: Int): Int { if(cardList.get(position).creditCard==null){ return 2 }else{ return 1 } } } return adapter } fun setItemClick(){ } protected fun installApk(context: Context, apkFile: File) { val intent = Intent(Intent.ACTION_VIEW) intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK) var uri: Uri? = null if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) { intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION) uri = FileProvider.getUriForFile(context, "com.nsk.app" + ".fileprovider", apkFile) } else { uri = Uri.fromFile(apkFile) } if (uri != null) { intent.setDataAndType(uri, "application/vnd.android.package-archive") context.startActivity(intent) } } }
1
null
1
1
d4bd736b90989a2a8b774dafcc57ab8aa42aabae
20,693
fuckcky
Apache License 2.0
partial-order-app/src/main/kotlin/org/tameter/partialorder/dag/Graph.kt
PlumpMath
94,562,224
true
{"JavaScript": 815178, "Kotlin": 97713, "HTML": 427, "CSS": 295, "Batchfile": 40}
package org.tameter.partialorder.dag import org.tameter.partialorder.util.cached /** * Copyright (c) 2016 <NAME> (<EMAIL>). */ class Graph { private val _nodes: MutableMap<String, GraphNode> = mutableMapOf() private val _edges: MutableMap<Edge, GraphEdge> = mutableMapOf() val nodes: Collection<GraphNode> get() = _nodes.values val edges: Collection<GraphEdge> get() = _edges.values fun findNodeById(id: String): GraphNode? = _nodes[id] fun findEdge(edge: Edge): GraphEdge? = _edges[edge] // Map from a node to all the nodes which have a path to it. private val cachedHasPathFrom = cached { val hasPathFrom = mutableMapOf<String, MutableCollection<String>>() // .withDefault { mutableListOf() } // doesn't work in JavaScript :-( // console.info("Caching paths ...") search(SearchType.DepthFirst) { _/*index*/, _/*depth*/, node, _/*prevEdge*/, prevNode -> val hasPathFromNode = hasPathFrom.getOrPut(node._id, { mutableListOf() }) // console.log("hasPathFromNodeQ = ${hasPathFromNodeQ}") // console.log("hasPathFrom = ${hasPathFrom.entries.joinToString()}") if (prevNode != null) { hasPathFromNode.add(prevNode._id) // console.info("Path to ${node._id} from ${prevNode._id}") val hasPathsFromPrevNode = hasPathFrom[prevNode._id]!! hasPathFromNode.addAll(hasPathsFromPrevNode) // console.info("Path to ${node._id} from ${hasPathsFromPrevNode.joinToString {it._id}}") } VisitResult.Continue } // console.info("Caching paths ... done.") hasPathFrom } val hasPathFrom by cachedHasPathFrom // Map from a node to all the nodes which have a path to it. private val cachedRanks = cached { val ranks = mutableMapOf<Node, Int>() nodes.forEach { ranks[it] = 0 } console.log("Caching ranks ...") val edgesFromNode = edges.groupBy { it.from } val nodesToProcess = mutableListOf<Node>().apply { addAll(roots) } while (nodesToProcess.isNotEmpty()) { val fromNode = nodesToProcess.removeAt(0) edgesFromNode[fromNode]?.forEach { edge -> val toNode = edge.to ranks[toNode] = maxOf(ranks[toNode]!!, ranks[fromNode]!! + 1) console.log("${ranks[toNode]} '${toNode.description}' <- '${fromNode.description}'") nodesToProcess.add(toNode) } } console.log("Caching ranks ... done") ranks } val ranks by cachedRanks val maxRank: Int? get() { return ranks.values.max() } fun addNode(node: Node) { if (node is GraphNode && node.graph != this) { throw Exception("Cannot add node because it belongs to a different graph: ${node}") } cachedRanks.clear() _nodes[node._id] = node as? GraphNode ?: GraphNode(this, node) } // TODO 2016-04-02 HughG: When implementing removeNode, fail if there are connected edges. fun addEdge(edge: Edge) { if (edge is GraphEdge && edge.graph != this) { throw Exception("Cannot add edge because it belongs to a different graph: ${edge}") } // TODO 2017-06-13 HughG: Return or throw if the edge already exists. if (hasPath(edge.toId, edge.fromId)) { throw Exception("Cannot add edge because it would create a cycle: ${edge}") } // Adding a new edge will change the set of which nodes are reachable from where. // TODO 2016-04-03 HughG: Instead of just deleting the cache, update it incrementally. cachedHasPathFrom.clear() cachedRanks.clear() _edges[edge] = edge as? GraphEdge ?: GraphEdge(this, edge) } fun removeEdge(edge: GraphEdge): Boolean { if (edge.graph != this) { // throw Exception("Cannot remove edge because it belongs to a different graph: ${edge}") } val removed = (_edges.remove(edge) != null) if (removed) {// Adding a new edge will change the set of which nodes are reachable from where. // TODO 2016-04-03 HughG: Instead of just deleting the cache, update it incrementally. cachedHasPathFrom.clear() cachedRanks.clear() } return removed } // fun deepClone(): Graph { // val g = Graph() // nodes.forEach { g._nodes.add(GraphNode(g, it)) } // edges.forEach { g._edges.add(GraphEdge(g, it)) } // return g // } val roots: Collection<GraphNode> get() { // TODO 2016-04-03 HughG: Cache, or update it incrementally. val result = mutableSetOf<GraphNode>() result.addAll(nodes) edges.forEach { result.remove(it.to) } // console.info("Roots are ${result.joinToString { it._id }}") return result } fun hasPath(fromId: String, toId: String): Boolean { if (fromId == toId) { return true } return hasPathFrom[toId]?.contains(fromId) ?: false } fun hasPath(from: Node, to: Node): Boolean = hasPath(from._id, to._id) fun rank(node: Node): Int { return ranks[node] ?: throw Exception("Cannot determine rank of node not in graph: ${node}") } fun rankById(id: String): Int? { return findNodeById(id)?.let { rank(it) } } } fun Graph.getAllAddableEdges(): Set<Edge> { val allPossibleEdges = mutableSetOf<Edge>() // Find set of all possible edges for (from in nodes) { for (to in nodes) { val possibleEdge = Edge(from, to) if (!hasPath(to, from) && !edges.contains(possibleEdge)) { allPossibleEdges.add(possibleEdge) } } } return allPossibleEdges }
0
JavaScript
0
0
ed247aadc13b4445f54e7d10a44cfbfe25cc3b0c
5,913
partial-order
MIT License
kotlin-electron/src/jsMain/generated/electron/core/ResolveHostOptionsQueryType.kt
JetBrains
93,250,841
false
{"Kotlin": 11691809, "JavaScript": 168519}
package electron.core @Suppress( "NAME_CONTAINS_ILLEGAL_CHARS", "NESTED_CLASS_IN_EXTERNAL_INTERFACE", ) @JsName("""(/*union*/{A: 'A', AAAA: 'AAAA'}/*union*/)""") sealed external interface ResolveHostOptionsQueryType { companion object { val A: ResolveHostOptionsQueryType val AAAA: ResolveHostOptionsQueryType } }
32
Kotlin
174
1,252
8f788651776064a30ce1688160b7ef9c314a6fe9
348
kotlin-wrappers
Apache License 2.0
app/src/main/java/com/github/sg4yk/audioplayer/ui/fragment/FolderFragment.kt
SG4YK
263,589,223
false
null
package com.github.sg4yk.audioplayer.ui.fragment import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.fragment.app.Fragment import androidx.lifecycle.ViewModelProvider import com.github.sg4yk.audioplayer.utils.AppViewModel import com.github.sg4yk.audioplayer.R class FolderFragment : Fragment() { companion object { fun newInstance() = FolderFragment() } private lateinit var viewModel: AppViewModel override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View? { return inflater.inflate(R.layout.folder_fragment, container, false) } override fun onActivityCreated(savedInstanceState: Bundle?) { super.onActivityCreated(savedInstanceState) viewModel = activity?.run { ViewModelProvider(this).get(AppViewModel::class.java) }!! } }
0
Kotlin
0
0
9c3e9a45bfd9b65c5c67b582d8b23344833e2d7d
967
AudioPlayer
Apache License 2.0
src/main/kotlin/gdscript/parser/stmt/GdEmptyStmtParser.kt
penguinencounter
792,086,846
false
{"Kotlin": 671320, "Java": 128067, "Lex": 24468, "PHP": 15692, "GDScript": 6273, "HTML": 4726, "Python": 3568, "Makefile": 198}
package gdscript.parser.stmt import com.intellij.psi.TokenType import com.intellij.psi.tree.IElementType import gdscript.parser.GdPsiBuilder import gdscript.psi.GdTypes object GdEmptyStmtParser : GdStmtBaseParser { override val STMT_TYPE: IElementType = TokenType.WHITE_SPACE override val endWithEndStmt: Boolean = false override fun parse(b: GdPsiBuilder, l: Int, optional: Boolean): Boolean { if (!b.recursionGuard(l, "StmtEmptyLine")) return false if (b.nextTokenIs(GdTypes.NEW_LINE)) { b.remapCurrentToken(TokenType.WHITE_SPACE) b.advance() return true } return false } }
0
Kotlin
0
0
662c945adb0ee2cca4e1342a5f684ea3b8d18b75
666
gdscript
MIT License
src/test/kotlin/TestTest.kt
technical-learn-room
431,467,408
false
{"Kotlin": 1786}
import a.TestClass import org.junit.jupiter.api.Test import kotlin.test.assertEquals class TestTest { private val testClass = TestClass() @Test fun testActionTest() { val fruitName = "apple" val evaluationMessage = testClass.testAction(fruitName) assertEquals("음 좋아", evaluationMessage) } }
0
Kotlin
0
0
449b91e6017156d7641b0b77682a537dc1412f42
334
kotlinx-kover-learn
MIT License
src/test/kotlin/TestTest.kt
technical-learn-room
431,467,408
false
{"Kotlin": 1786}
import a.TestClass import org.junit.jupiter.api.Test import kotlin.test.assertEquals class TestTest { private val testClass = TestClass() @Test fun testActionTest() { val fruitName = "apple" val evaluationMessage = testClass.testAction(fruitName) assertEquals("음 좋아", evaluationMessage) } }
0
Kotlin
0
0
449b91e6017156d7641b0b77682a537dc1412f42
334
kotlinx-kover-learn
MIT License
backend.native/tests/harmony_regex/MatchResultTest2.kt
JetBrains
58,957,623
false
null
/* Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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. */ import kotlin.text.* import kotlin.test.* fun testErrorConditions2() { // Test match cursors in absence of a match val regex = Regex("(foo[0-9])(bar[a-z])") var result = regex.find("foo1barzfoo2baryfoozbar5") assertTrue(result != null) assertEquals(0, result!!.range.start) assertEquals(7, result.range.endInclusive) assertEquals(0, result.groups[0]!!.range.start) assertEquals(7, result.groups[0]!!.range.endInclusive) assertEquals(0, result.groups[1]!!.range.start) assertEquals(3, result.groups[1]!!.range.endInclusive) assertEquals(4, result.groups[2]!!.range.start) assertEquals(7, result.groups[2]!!.range.endInclusive) try { result.groups[3] fail("IndexOutOfBoundsException expected") } catch (e: IndexOutOfBoundsException) { } try { result.groupValues[3] fail("IndexOutOfBoundsException expected") } catch (e: IndexOutOfBoundsException) { } try { result.groups[-1] fail("IndexOutOfBoundsException expected") } catch (e: IndexOutOfBoundsException) { } try { result.groupValues[-1] fail("IndexOutOfBoundsException expected") } catch (e: IndexOutOfBoundsException) { } result = result.next() assertTrue(result != null) assertEquals(8, result!!.range.start) assertEquals(15, result.range.endInclusive) assertEquals(8, result.groups[0]!!.range.start) assertEquals(15, result.groups[0]!!.range.endInclusive) assertEquals(8, result.groups[1]!!.range.start) assertEquals(11, result.groups[1]!!.range.endInclusive) assertEquals(12, result.groups[2]!!.range.start) assertEquals(15, result.groups[2]!!.range.endInclusive) try { result.groups[3] fail("IndexOutOfBoundsException expected") } catch (e: IndexOutOfBoundsException) { } try { result.groupValues[3] fail("IndexOutOfBoundsException expected") } catch (e: IndexOutOfBoundsException) { } try { result.groups[-1] fail("IndexOutOfBoundsException expected") } catch (e: IndexOutOfBoundsException) { } try { result.groupValues[-1] fail("IndexOutOfBoundsException expected") } catch (e: IndexOutOfBoundsException) { } result = result.next() assertFalse(result != null) } /* * Regression test for HARMONY-997 */ fun testReplacementBackSlash() { val str = "replace me" val replacedString = "me" val substitutionString = "\\" val regex = Regex(replacedString) try { regex.replace(str, substitutionString) fail("IllegalArgumentException should be thrown") } catch (e: IllegalArgumentException) { } } fun box() { testErrorConditions2() testReplacementBackSlash() }
0
Kotlin
625
7,100
9fb0a75ab17e9d8cddd2c3d1802a1cdd83774dfa
3,602
kotlin-native
Apache License 2.0
app/src/main/java/com/papermoon/spaceapp/data/datasource/remote/launch/model/NetworkLaunch.kt
papermoon-ai
583,742,280
false
{"Kotlin": 197546}
package com.papermoon.spaceapp.data.datasource.remote.launch.model import com.google.gson.annotations.SerializedName import com.papermoon.spaceapp.data.datasource.remote.commons.model.NetworkImageWithDescription import com.papermoon.spaceapp.data.datasource.remote.commons.model.toDomainObject import com.papermoon.spaceapp.domain.model.launch.Launch import org.joda.time.DateTime import java.util.* data class NetworkLaunch( val name: String, @SerializedName("window_end") val launchDate: Date, val launchServiceProvider: String, val images: List<NetworkImageWithDescription>, val pad: NetworkPad, val mission: NetworkMission? ) fun NetworkLaunch.toDomainObject(): Launch { return Launch( name, DateTime(launchDate), launchServiceProvider, images.map { it.toDomainObject() }, pad.toDomainObject(), mission?.toDomainObject() ) } fun List<NetworkLaunch>.toDomainObject(): List<Launch> { return this.map { it.toDomainObject() } }
0
Kotlin
0
0
a0a4eb6bef933f910ef049b549a7200258b1c4d7
1,020
SpaceExplorer
MIT License
kts-engine/src/test/resources/TestInvokeFunction.kts
ostelco
112,729,477
false
null
fun add(x: Int, y: Int): Int = x + y
23
null
13
37
b072ada4aca8c4bf5c3c2f6fe0d36a5ff16c11af
36
ostelco-core
Apache License 2.0
src/main/kotlin/com/mystery2099/wooden_accents_mod/shulker_box_tooltip/ShulkerBoxTooltipPlugin.kt
Mystery2099
661,436,370
false
{"Kotlin": 278669, "Java": 16936}
package com.mystery2099.wooden_accents_mod.shulker_box_tooltip import com.misterpemodder.shulkerboxtooltip.api.ShulkerBoxTooltipApi import com.misterpemodder.shulkerboxtooltip.api.provider.BlockEntityPreviewProvider import com.misterpemodder.shulkerboxtooltip.api.provider.PreviewProviderRegistry import com.mystery2099.wooden_accents_mod.WoodenAccentsMod.toIdentifier import com.mystery2099.wooden_accents_mod.block.ModBlocks import com.mystery2099.wooden_accents_mod.block.custom.CrateBlock import com.mystery2099.wooden_accents_mod.block.custom.KitchenCabinetBlock import com.mystery2099.wooden_accents_mod.block.custom.ThinBookshelfBlock import net.minecraft.block.Block object ShulkerBoxTooltipPlugin : ShulkerBoxTooltipApi { override fun registerProviders(registry: PreviewProviderRegistry) { registry.register( "crates".toIdentifier(), CratePreviewProvider(), *(ModBlocks.blocks.filterIsInstance<CrateBlock>().map(Block::asItem).toTypedArray()) ) registry.register( "chest_like".toIdentifier(), BlockEntityPreviewProvider(27, true), *(ModBlocks.blocks.filterIsInstance<KitchenCabinetBlock>().map(Block::asItem).toTypedArray()) ) registry.register( "chiseled_bookshelf_like".toIdentifier(), BlockEntityPreviewProvider(6, true, 3), *(ModBlocks.blocks.filterIsInstance<ThinBookshelfBlock>().map(Block::asItem).toTypedArray()) ) } }
0
Kotlin
0
0
19c023639515cbed9935c8124615eaa2355d2433
1,501
WoodenAccentsMod-1.19.4
Creative Commons Zero v1.0 Universal
feature/weather-details/src/commonTest/kotlin/com/krossovochkin/kweather/weatherdetails/domain/TestDailyWeatherDataBuilder.kt
krossovochkin
266,317,132
false
null
package com.krossovochkin.kweather.weatherdetails.domain import com.krossovochkin.kweather.domain.WeatherDetails import com.krossovochkin.kweather.weatherdetails.domain.TestDefaults.DEFAULT_CONDITION_DESCRIPTION import com.krossovochkin.kweather.weatherdetails.domain.TestDefaults.DEFAULT_CONDITION_IMAGE_URL import com.krossovochkin.kweather.weatherdetails.domain.TestDefaults.DEFAULT_HUMIDITY import com.krossovochkin.kweather.weatherdetails.domain.TestDefaults.DEFAULT_LOCAL_DATE_TIME import com.krossovochkin.kweather.weatherdetails.domain.TestDefaults.DEFAULT_PRESSURE import com.krossovochkin.kweather.weatherdetails.domain.TestDefaults.DEFAULT_WIND_DEGREE import com.krossovochkin.kweather.weatherdetails.domain.TestDefaults.DEFAULT_WIND_SPEED import kotlinx.datetime.LocalDateTime class TestDailyWeatherDataBuilder { private var localDateTime: LocalDateTime = DEFAULT_LOCAL_DATE_TIME private var temperature = TestTemperatureDataBuilder().build() private var pressure: Int = DEFAULT_PRESSURE private var humidity: Int = DEFAULT_HUMIDITY private var windSpeed: Double = DEFAULT_WIND_SPEED private var windDegree: Int = DEFAULT_WIND_DEGREE private var conditionImageUrl: String = DEFAULT_CONDITION_IMAGE_URL private var conditionDescription: String = DEFAULT_CONDITION_DESCRIPTION fun build(): WeatherDetails.DailyWeatherData { return WeatherDetails.DailyWeatherData( localDateTime = localDateTime, temperature = temperature, pressure = pressure, humidity = humidity, windSpeed = windSpeed, windDegree = windDegree, conditionImageUrl = conditionImageUrl, conditionDescription = conditionDescription ) } }
0
Kotlin
2
37
727d74e19020f1be508af87ced18c53e5ee4fca2
1,767
KWeather
Apache License 2.0
z2-kotlin-plugin/testData/box/adaptive/call/withDefault.kt
spxbhuhb
665,463,766
false
{"Kotlin": 1812530, "CSS": 171914, "Java": 20900, "JavaScript": 1950, "HTML": 1854}
/* * Copyright © 2020-2021, Simplexion, Hungary and contributors. Use of this source code is governed by the Apache 2.0 license. */ package hu.simplexion.adaptive.kotlin.base.success import hu.simplexion.adaptive.base.Adaptive import hu.simplexion.adaptive.base.adaptive import hu.simplexion.adaptive.base.AdaptiveAdapterRegistry import hu.simplexion.adaptive.base.testing.* fun Adaptive.WithDefault(a : Int = 12) { T1(a) } fun box() : String { AdaptiveAdapterRegistry.register(AdaptiveTestAdapterFactory) adaptive { WithDefault() WithDefault(23) } return AdaptiveTestAdapter.assert(listOf( TraceEvent("<root>", 2, "before-Create", ""), TraceEvent("<root>", 2, "before-Patch-External", "createMask: 0xffffffff thisMask: 0xffffffff state: []"), TraceEvent("<root>", 2, "after-Patch-External", "createMask: 0xffffffff thisMask: 0xffffffff state: []"), TraceEvent("<root>", 2, "before-Patch-Internal", "createMask: 0xffffffff thisMask: 0xffffffff state: []"), TraceEvent("<root>", 2, "after-Patch-Internal", "createMask: 0x00000000 thisMask: 0x00000000 state: []"), TraceEvent("AdaptiveSequence", 3, "before-Create", ""), TraceEvent("AdaptiveSequence", 3, "before-Patch-External", "createMask: 0x00000000 thisMask: 0xffffffff state: []"), TraceEvent("AdaptiveSequence", 3, "after-Patch-External", "createMask: 0x00000000 thisMask: 0xffffffff state: [1, 2]"), TraceEvent("AdaptiveSequence", 3, "before-Patch-Internal", "createMask: 0x00000000 thisMask: 0xffffffff state: [1, 2]"), TraceEvent("AdaptiveSequence", 3, "after-Patch-Internal", "createMask: 0x00000000 thisMask: 0x00000000 state: [1, 2]"), TraceEvent("AdaptiveWithDefault", 4, "before-Create", ""), TraceEvent("AdaptiveWithDefault", 4, "before-Patch-External", "createMask: 0x00000000 thisMask: 0xffffffff state: [null]"), TraceEvent("AdaptiveWithDefault", 4, "after-Patch-External", "createMask: 0x00000000 thisMask: 0xffffffff state: [null]"), TraceEvent("AdaptiveWithDefault", 4, "before-Patch-Internal", "createMask: 0x00000000 thisMask: 0xffffffff state: [null]"), TraceEvent("AdaptiveWithDefault", 4, "after-Patch-Internal", "createMask: 0x00000000 thisMask: 0x00000000 state: [12]"), TraceEvent("AdaptiveT1", 5, "before-Create", ""), TraceEvent("AdaptiveT1", 5, "before-Patch-External", "createMask: 0x00000000 thisMask: 0xffffffff state: [null]"), TraceEvent("AdaptiveT1", 5, "after-Patch-External", "createMask: 0x00000000 thisMask: 0xffffffff state: [12]"), TraceEvent("AdaptiveT1", 5, "before-Patch-Internal", "createMask: 0x00000000 thisMask: 0xffffffff state: [12]"), TraceEvent("AdaptiveT1", 5, "after-Patch-Internal", "createMask: 0x00000000 thisMask: 0x00000000 state: [12]"), TraceEvent("AdaptiveT1", 5, "after-Create", ""), TraceEvent("AdaptiveWithDefault", 4, "after-Create", ""), TraceEvent("AdaptiveWithDefault", 8, "before-Create", ""), TraceEvent("AdaptiveWithDefault", 8, "before-Patch-External", "createMask: 0x00000000 thisMask: 0xffffffff state: [null]"), TraceEvent("AdaptiveWithDefault", 8, "after-Patch-External", "createMask: 0x00000000 thisMask: 0xffffffff state: [23]"), TraceEvent("AdaptiveWithDefault", 8, "before-Patch-Internal", "createMask: 0x00000000 thisMask: 0xffffffff state: [23]"), TraceEvent("AdaptiveWithDefault", 8, "after-Patch-Internal", "createMask: 0x00000000 thisMask: 0x00000000 state: [23]"), TraceEvent("AdaptiveT1", 9, "before-Create", ""), TraceEvent("AdaptiveT1", 9, "before-Patch-External", "createMask: 0x00000000 thisMask: 0xffffffff state: [null]"), TraceEvent("AdaptiveT1", 9, "after-Patch-External", "createMask: 0x00000000 thisMask: 0xffffffff state: [23]"), TraceEvent("AdaptiveT1", 9, "before-Patch-Internal", "createMask: 0x00000000 thisMask: 0xffffffff state: [23]"), TraceEvent("AdaptiveT1", 9, "after-Patch-Internal", "createMask: 0x00000000 thisMask: 0x00000000 state: [23]"), TraceEvent("AdaptiveT1", 9, "after-Create", ""), TraceEvent("AdaptiveWithDefault", 8, "after-Create", ""), TraceEvent("AdaptiveSequence", 3, "after-Create", ""), TraceEvent("<root>", 2, "after-Create", ""), TraceEvent("<root>", 2, "before-Mount", "bridge: 1"), TraceEvent("AdaptiveSequence", 3, "before-Mount", "bridge: 1"), TraceEvent("AdaptiveWithDefault", 4, "before-Mount", "bridge: 1"), TraceEvent("AdaptiveT1", 5, "before-Mount", "bridge: 1"), TraceEvent("AdaptiveT1", 5, "after-Mount", "bridge: 1"), TraceEvent("AdaptiveWithDefault", 4, "after-Mount", "bridge: 1"), TraceEvent("AdaptiveWithDefault", 8, "before-Mount", "bridge: 1"), TraceEvent("AdaptiveT1", 9, "before-Mount", "bridge: 1"), TraceEvent("AdaptiveT1", 9, "after-Mount", "bridge: 1"), TraceEvent("AdaptiveWithDefault", 8, "after-Mount", "bridge: 1"), TraceEvent("AdaptiveSequence", 3, "after-Mount", "bridge: 1"), TraceEvent("<root>", 2, "after-Mount", "bridge: 1") )) }
5
Kotlin
0
1
8b0b012d880918efc01d8dafd9a3dba701e90835
5,178
z2-pre
Apache License 2.0
app/src/main/java/com/snipex/shantu/assignment/adapter/ArticleAdapter.kt
ingaleashish
260,682,436
false
{"Gradle": 3, "Java Properties": 2, "Shell": 1, "Text": 1, "Ignore List": 2, "Batchfile": 1, "Markdown": 1, "Proguard": 1, "Java": 3, "XML": 17, "Kotlin": 11}
package com.snipex.shantu.assignment.adapter import android.content.Context import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.ImageView import android.widget.TextView import androidx.recyclerview.widget.RecyclerView import com.snipex.shantu.assignment.R import com.snipex.shantu.assignment.response.Entry import com.squareup.picasso.Picasso import java.util.* class ArticleAdapter(private val context: Context, internal var articleArrayList: ArrayList<Entry>) : RecyclerView.Adapter<ArticleAdapter.ViewHolder>() { override fun onCreateViewHolder(viewGroup: ViewGroup, i: Int): ArticleAdapter.ViewHolder { val view = LayoutInflater.from(viewGroup.context).inflate(R.layout.list_each_row_movie_article, viewGroup, false) return ViewHolder(view) } override fun onBindViewHolder(viewHolder: ArticleAdapter.ViewHolder, i: Int) { val article = articleArrayList[i] Picasso.with(context).load(article.imimage[2].label).placeholder(R.mipmap.ic_launcher).into(viewHolder.imgViewCover) viewHolder.tvTitle.text = article.title.label viewHolder.tvName.text = article.imname.label viewHolder.tvRights.text = article.rights.label viewHolder.tvPrice.text = article.imprice.attributes.amount + article.imprice.attributes.currency viewHolder.tvArtist.text = article.imartist.label viewHolder.tvReleaseDate.text = article.imreleaseDate.label } override fun getItemCount(): Int { return articleArrayList.size } inner class ViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) { val imgViewCover: ImageView val tvTitle: TextView val tvName: TextView val tvRights: TextView val tvPrice: TextView val tvArtist: TextView val tvReleaseDate: TextView init { imgViewCover = itemView.findViewById<View>(R.id.imgViewCover) as ImageView tvTitle = itemView.findViewById<View>(R.id.tvTitle) as TextView tvName = itemView.findViewById<View>(R.id.tvName) as TextView tvRights = itemView.findViewById<View>(R.id.tvRights) as TextView tvPrice = itemView.findViewById<View>(R.id.tvPrice) as TextView tvArtist = itemView.findViewById<View>(R.id.tvArtist) as TextView tvReleaseDate = itemView.findViewById<View>(R.id.tvReleaseDate) as TextView } } }
1
null
1
1
b5b9eb520359aaf59f1454e360e8152ea0041564
2,469
SynerzipAssignment
MIT License
wearOs/src/main/kotlin/wear/complication/RangedComplicationService.kt
thaapasa
702,418,399
false
{"Kotlin": 523798, "Swift": 661, "Shell": 262}
package fi.tuska.beerclock.wear.complication import android.app.PendingIntent import android.graphics.drawable.Icon import android.os.Build import androidx.annotation.DrawableRes import androidx.annotation.RequiresApi import androidx.annotation.StringRes import androidx.wear.watchface.complications.data.ComplicationData import androidx.wear.watchface.complications.data.ComplicationType import androidx.wear.watchface.complications.data.GoalProgressComplicationData import androidx.wear.watchface.complications.data.MonochromaticImage import androidx.wear.watchface.complications.data.PlainComplicationText import androidx.wear.watchface.complications.data.RangedValueComplicationData import androidx.wear.watchface.complications.datasource.ComplicationRequest import androidx.wear.watchface.complications.datasource.SuspendingComplicationDataSourceService import fi.tuska.beerclock.wear.CurrentBacStatus import fi.tuska.beerclock.wear.LocaleHelper import fi.tuska.beerclock.wear.getState import fi.tuska.beerclock.wear.presentation.BeerWearActivity import java.time.Instant import kotlin.math.max import kotlin.math.min abstract class RangedComplicationService( @DrawableRes private val iconRes: Int, @StringRes private val valueRes: Int, @StringRes private val labelRes: Int, ) : SuspendingComplicationDataSourceService() { abstract fun toComplicationData(state: CurrentBacStatus, currentTime: Instant): RangedData abstract fun previewData(): RangedData override fun getPreviewData(type: ComplicationType): ComplicationData? { val data = previewData() return when { Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU && type == ComplicationType.GOAL_PROGRESS -> createGoalProgressData( data ) type == ComplicationType.RANGED_VALUE -> createRangedData(data) else -> null } } override suspend fun onComplicationRequest(request: ComplicationRequest): ComplicationData? { val state = CurrentBacStatus.getState(applicationContext) state.locale?.let { LocaleHelper.setCurrentLocale(applicationContext, it) } val data = toComplicationData(state, Instant.now()) val tapAction = BeerWearActivity.getComplicationTapIntent(this, request.complicationInstanceId) if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU && request.complicationType == ComplicationType.GOAL_PROGRESS) { return createGoalProgressData(data, tapAction) } return createRangedData(data, tapAction) } @RequiresApi(Build.VERSION_CODES.TIRAMISU) private fun createGoalProgressData(data: RangedData, tapAction: PendingIntent? = null) = GoalProgressComplicationData.Builder( value = data.value, targetValue = data.max, contentDescription = createContentDescription(), ) .setTitle(createTitle(data)) .setTapAction(tapAction) .setMonochromaticImage(createMonochromaticImage()) .build() private fun createRangedData(data: RangedData, tapAction: PendingIntent? = null) = RangedValueComplicationData.Builder( value = data.value, max = max(data.value, data.max), min = min(0f, data.value), contentDescription = createContentDescription(), ) .setTitle(createTitle(data)) .setTapAction(tapAction) .setMonochromaticImage(createMonochromaticImage()) .build() private fun createTitle(data: RangedData) = PlainComplicationText.Builder(getString(valueRes, data.value)).build() private fun createMonochromaticImage() = MonochromaticImage.Builder( Icon.createWithResource(applicationContext, iconRes) ).build() private fun createContentDescription() = PlainComplicationText.Builder(getString(labelRes)).build() } data class RangedData(val value: Float, val max: Float)
0
Kotlin
0
2
13670909f5ab7a1a33b5542606e76a8fca490e24
4,029
beerclock
Apache License 2.0
src/main/kotlin/codes/som/koffee/insns/jvm/Handles.kt
char
184,816,641
false
{"Kotlin": 88664}
@file:Suppress("unused") // Receivers used to avoid scope pollution package codes.som.koffee.insns.jvm import codes.som.koffee.insns.InstructionAssembly import codes.som.koffee.types.TypeLike import codes.som.koffee.types.coerceType import codes.som.koffee.util.constructMethodDescriptor import org.objectweb.asm.Handle import org.objectweb.asm.Opcodes import org.objectweb.asm.tree.FieldNode import org.objectweb.asm.tree.MethodNode public fun InstructionAssembly.h_invokevirtual(owner: TypeLike, name: String, descriptor: String, isInterface: Boolean = false): Handle { return Handle(Opcodes.H_INVOKEVIRTUAL, coerceType(owner).internalName, name, descriptor, isInterface) } public fun InstructionAssembly.h_invokespecial(owner: TypeLike, name: String, descriptor: String, isInterface: Boolean = false): Handle { return Handle(Opcodes.H_INVOKESPECIAL, coerceType(owner).internalName, name, descriptor, isInterface) } public fun InstructionAssembly.h_invokeinterface(owner: TypeLike, name: String, descriptor: String, isInterface: Boolean = false): Handle { return Handle(Opcodes.H_INVOKEINTERFACE, coerceType(owner).internalName, name, descriptor, isInterface) } public fun InstructionAssembly.h_invokestatic(owner: TypeLike, name: String, descriptor: String, isInterface: Boolean = false): Handle { return Handle(Opcodes.H_INVOKESTATIC, coerceType(owner).internalName, name, descriptor, isInterface) } public fun InstructionAssembly.h_putfield(owner: TypeLike, name: String, descriptor: String, isInterface: Boolean = false): Handle { return Handle(Opcodes.H_PUTFIELD, coerceType(owner).internalName, name, descriptor, isInterface) } public fun InstructionAssembly.h_getfield(owner: TypeLike, name: String, descriptor: String, isInterface: Boolean = false): Handle { return Handle(Opcodes.H_GETFIELD, coerceType(owner).internalName, name, descriptor, isInterface) } public fun InstructionAssembly.h_putstatic(owner: TypeLike, name: String, descriptor: String, isInterface: Boolean = false): Handle { return Handle(Opcodes.H_PUTSTATIC, coerceType(owner).internalName, name, descriptor, isInterface) } public fun InstructionAssembly.h_getstatic(owner: TypeLike, name: String, descriptor: String, isInterface: Boolean = false): Handle { return Handle(Opcodes.H_GETSTATIC, coerceType(owner).internalName, name, descriptor, isInterface) } public fun InstructionAssembly.h_newinvokespecial(owner: TypeLike, name: String, descriptor: String, isInterface: Boolean = false): Handle { return Handle(Opcodes.H_NEWINVOKESPECIAL, coerceType(owner).internalName, name, descriptor, isInterface) } public fun InstructionAssembly.h_invokevirtual(owner: TypeLike, name: String, returnType: TypeLike, vararg parameterTypes: TypeLike, isInterface: Boolean = false): Handle { return h_invokevirtual(owner, name, constructMethodDescriptor(returnType, *parameterTypes), isInterface) } public fun InstructionAssembly.h_invokespecial(owner: TypeLike, name: String, returnType: TypeLike, vararg parameterTypes: TypeLike, isInterface: Boolean = false): Handle { return h_invokespecial(owner, name, constructMethodDescriptor(returnType, *parameterTypes), isInterface) } public fun InstructionAssembly.h_invokeinterface(owner: TypeLike, name: String, returnType: TypeLike, vararg parameterTypes: TypeLike, isInterface: Boolean = false): Handle { return h_invokeinterface(owner, name, constructMethodDescriptor(returnType, *parameterTypes), isInterface) } public fun InstructionAssembly.h_invokestatic(owner: TypeLike, name: String, returnType: TypeLike, vararg parameterTypes: TypeLike, isInterface: Boolean = false): Handle { return h_invokestatic(owner, name, constructMethodDescriptor(returnType, *parameterTypes), isInterface) } public fun InstructionAssembly.h_putfield(owner: TypeLike, name: String, type: TypeLike, isInterface: Boolean = false): Handle { return h_putfield(owner, name, coerceType(type).descriptor, isInterface) } public fun InstructionAssembly.h_getfield(owner: TypeLike, name: String, type: TypeLike, isInterface: Boolean = false): Handle { return h_getfield(owner, name, coerceType(type).descriptor, isInterface) } public fun InstructionAssembly.h_putstatic(owner: TypeLike, name: String, type: TypeLike, isInterface: Boolean = false): Handle { return h_putstatic(owner, name, coerceType(type).descriptor, isInterface) } public fun InstructionAssembly.h_getstatic(owner: TypeLike, name: String, type: TypeLike, isInterface: Boolean = false): Handle { return h_getstatic(owner, name, coerceType(type).descriptor, isInterface) } public fun InstructionAssembly.h_newinvokespecial(owner: TypeLike, name: String, returnType: TypeLike, vararg parameterTypes: TypeLike, isInterface: Boolean = false): Handle { return h_newinvokespecial(owner, name, constructMethodDescriptor(returnType, *parameterTypes), isInterface) } public fun InstructionAssembly.h_invokevirtual(owner: TypeLike, method: MethodNode, isInterface: Boolean = false): Handle { return h_invokevirtual(owner, method.name, method.desc, isInterface) } public fun InstructionAssembly.h_invokespecial(owner: TypeLike, method: MethodNode, isInterface: Boolean = false): Handle { return h_invokespecial(owner, method.name, method.desc, isInterface) } public fun InstructionAssembly.h_invokeinterface(owner: TypeLike, method: MethodNode, isInterface: Boolean = false): Handle { return h_invokeinterface(owner, method.name, method.desc, isInterface) } public fun InstructionAssembly.h_invokestatic(owner: TypeLike, method: MethodNode, isInterface: Boolean = false): Handle { return h_invokestatic(owner, method.name, method.desc, isInterface) } public fun InstructionAssembly.h_putfield(owner: TypeLike, field: FieldNode, isInterface: Boolean = false): Handle { return h_putfield(owner, field.name, field.desc, isInterface) } public fun InstructionAssembly.h_getfield(owner: TypeLike, field: FieldNode, isInterface: Boolean = false): Handle { return h_getfield(owner, field.name, field.desc, isInterface) } public fun InstructionAssembly.h_putstatic(owner: TypeLike, field: FieldNode, isInterface: Boolean = false): Handle { return h_putstatic(owner, field.name, field.desc, isInterface) } public fun InstructionAssembly.h_getstatic(owner: TypeLike, field: FieldNode, isInterface: Boolean = false): Handle { return h_getstatic(owner, field.name, field.desc, isInterface) } public fun InstructionAssembly.h_newinvokespecial(owner: TypeLike, method: MethodNode, isInterface: Boolean = false): Handle { return h_newinvokespecial(owner, method.name, method.desc, isInterface) }
1
Kotlin
7
76
3a78d8a43776bec026a8f3f64cec15c4d76505ce
6,636
Koffee
MIT License
practice_1/ecommerce/src/main/kotlin/com/api/ecommerce/dtos/responses/RegisterResponse.kt
trungung
318,070,008
false
null
package com.api.ecommerce.dtos.responses class RegisterResponse( val userName: String, val email: String, val phone: String)
0
Kotlin
0
0
27d3cefd8a49d5f168c1da6dfa8c8e00d6bd8cd2
137
spring-microservice
Apache License 2.0
cupertino-icons-extended/src/commonMain/kotlin/io/github/alexzhirkevich/cupertino/icons/outlined/Basketball.kt
alexzhirkevich
636,411,288
false
{"Kotlin": 5215549, "Ruby": 2329, "Swift": 2101, "HTML": 2071, "Shell": 868}
/* * Copyright (c) 2023-2024. Compose Cupertino project and open source contributors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package io.github.alexzhirkevich.cupertino.icons.outlined 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 io.github.alexzhirkevich.cupertino.icons.CupertinoIcons public val CupertinoIcons.Outlined.Basketball: ImageVector get() { if (_basketball != null) { return _basketball!! } _basketball = Builder(name = "Basketball", defaultWidth = 23.9062.dp, defaultHeight = 23.918.dp, viewportWidth = 23.9062f, viewportHeight = 23.918f).apply { path(fill = SolidColor(Color(0xFF000000)), stroke = null, strokeLineWidth = 0.0f, strokeLineCap = Butt, strokeLineJoin = Miter, strokeLineMiter = 4.0f, pathFillType = NonZero) { moveTo(1.2422f, 12.7734f) curveTo(4.4297f, 8.4258f, 9.3164f, 5.6836f, 14.9648f, 5.6836f) curveTo(17.2383f, 5.6836f, 19.3711f, 6.1172f, 21.3984f, 6.9844f) lineTo(21.1406f, 5.4727f) curveTo(19.2305f, 4.7695f, 17.1094f, 4.3828f, 14.9648f, 4.3828f) curveTo(8.9648f, 4.3828f, 3.6328f, 7.3594f, 0.2695f, 11.9062f) close() moveTo(21.1641f, 17.4961f) lineTo(22.4062f, 17.1328f) curveTo(20.6367f, 10.9336f, 10.4883f, 9.5859f, 10.4883f, 4.6172f) curveTo(10.4883f, 3.1289f, 11.25f, 2.0391f, 12.6445f, 1.3008f) lineTo(11.8359f, 0.2578f) curveTo(10.2305f, 1.1836f, 9.1875f, 2.7422f, 9.1875f, 4.6172f) curveTo(9.1875f, 10.6289f, 19.6172f, 12.1758f, 21.1641f, 17.4961f) close() moveTo(4.0898f, 20.2617f) lineTo(5.5898f, 20.4023f) curveTo(3.8203f, 17.0273f, 5.5664f, 12.0938f, 5.2734f, 7.8516f) curveTo(5.1914f, 6.7266f, 4.4883f, 4.6992f, 3.2227f, 4.3945f) lineTo(2.8945f, 5.6602f) curveTo(3.457f, 5.7305f, 3.9258f, 7.1719f, 3.9727f, 7.957f) curveTo(4.2305f, 11.6836f, 2.6367f, 16.4766f, 4.0898f, 20.2617f) close() moveTo(13.5352f, 23.0508f) lineTo(14.5781f, 22.2656f) curveTo(7.7109f, 13.7344f, 6.6914f, 4.4297f, 7.8164f, 1.8984f) lineTo(6.3984f, 2.0977f) curveTo(5.5195f, 5.7422f, 6.9727f, 14.8477f, 13.5352f, 23.0508f) close() moveTo(11.9531f, 23.9062f) curveTo(18.4922f, 23.9062f, 23.9062f, 18.4805f, 23.9062f, 11.9531f) curveTo(23.9062f, 5.4141f, 18.4805f, 0.0f, 11.9414f, 0.0f) curveTo(5.4141f, 0.0f, 0.0f, 5.4141f, 0.0f, 11.9531f) curveTo(0.0f, 18.4805f, 5.4258f, 23.9062f, 11.9531f, 23.9062f) close() moveTo(11.9531f, 22.3125f) curveTo(6.293f, 22.3125f, 1.5938f, 17.6133f, 1.5938f, 11.9531f) curveTo(1.5938f, 6.293f, 6.2813f, 1.5938f, 11.9414f, 1.5938f) curveTo(17.6016f, 1.5938f, 22.3125f, 6.293f, 22.3125f, 11.9531f) curveTo(22.3125f, 17.6133f, 17.6133f, 22.3125f, 11.9531f, 22.3125f) close() } } .build() return _basketball!! } private var _basketball: ImageVector? = null
18
Kotlin
31
848
54bfbb58f6b36248c5947de343567903298ee308
4,391
compose-cupertino
Apache License 2.0
src/main/kotlin/de/debuglevel/bragi/entity/EntityRepository.kt
debuglevel
282,505,005
false
null
package de.debuglevel.bragi.entity import io.micronaut.data.repository.CrudRepository import java.util.* interface EntityRepository<T> : CrudRepository<T, UUID>
13
Kotlin
0
0
7ee6040b8280ea44c780ae6842aedc464b6278bf
162
bragi
The Unlicense
firebase-installations/src/jsMain/kotlin/dev/gitlive/firebase/installations/externals/installations.kt
GitLiveApp
213,915,094
false
{"Kotlin": 660226, "Ruby": 18024, "JavaScript": 469}
@file:JsModule("firebase/installations") @file:JsNonModule package dev.gitlive.firebase.installations.externals import dev.gitlive.firebase.externals.FirebaseApp import kotlin.js.Promise external fun delete(installations: Installations): Promise<Unit> external fun getId(installations: Installations): Promise<String> external fun getInstallations(app: FirebaseApp? = definedExternally): Installations external fun getToken(installations: Installations, forceRefresh: Boolean): Promise<String> external interface Installations
83
Kotlin
147
969
e54c12e5f0b62c6b1878fdba966d6bb4b94cb676
534
firebase-kotlin-sdk
Apache License 2.0