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
feature/profile/src/main/java/com/niyaj/profile/ProfileScreen.kt
skniyajali
644,752,474
false
{"Kotlin": 5076894, "Shell": 16584, "Ruby": 1461, "Java": 232}
/* * Copyright 2024 <NAME> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * 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. * */ @file:Suppress("DEPRECATION") package com.niyaj.profile import androidx.activity.compose.BackHandler import androidx.activity.compose.rememberLauncherForActivityResult import androidx.activity.result.PickVisualMediaRequest import androidx.activity.result.contract.ActivityResultContracts import androidx.annotation.VisibleForTesting import androidx.compose.foundation.background import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.Spacer import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.height import androidx.compose.foundation.layout.padding import androidx.compose.foundation.lazy.LazyColumn import androidx.compose.foundation.lazy.rememberLazyListState import androidx.compose.material3.ExperimentalMaterial3Api import androidx.compose.material3.Icon import androidx.compose.material3.IconButton import androidx.compose.material3.MaterialTheme import androidx.compose.material3.Scaffold import androidx.compose.material3.SnackbarHost import androidx.compose.material3.SnackbarHostState import androidx.compose.material3.Text import androidx.compose.material3.TopAppBar import androidx.compose.material3.TopAppBarDefaults import androidx.compose.material3.contentColorFor import androidx.compose.runtime.Composable import androidx.compose.runtime.LaunchedEffect import androidx.compose.runtime.SideEffect import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.runtime.rememberCoroutineScope import androidx.compose.runtime.saveable.rememberSaveable import androidx.compose.runtime.setValue import androidx.compose.ui.Modifier import androidx.compose.ui.graphics.Color import androidx.hilt.navigation.compose.hiltViewModel import androidx.lifecycle.compose.collectAsStateWithLifecycle import com.google.accompanist.systemuicontroller.rememberSystemUiController import com.niyaj.common.tags.ProfileTestTags.PRINT_LOGO_NOTE import com.niyaj.common.tags.ProfileTestTags.PROFILE_SCREEN import com.niyaj.common.tags.ProfileTestTags.RES_LOGO_NOTE import com.niyaj.designsystem.icon.PoposIcons import com.niyaj.designsystem.theme.LightColor6 import com.niyaj.designsystem.theme.PoposRoomTheme import com.niyaj.designsystem.theme.SpaceMini import com.niyaj.designsystem.theme.SpaceSmall import com.niyaj.model.Account import com.niyaj.model.Profile import com.niyaj.profile.components.AccountInfo import com.niyaj.profile.components.RestaurantCard import com.niyaj.profile.destinations.ChangePasswordScreenDestination import com.niyaj.profile.destinations.UpdateProfileScreenDestination import com.niyaj.ui.components.NoteCard import com.niyaj.ui.components.SettingsCard import com.niyaj.ui.utils.DevicePreviews import com.niyaj.ui.utils.Screens import com.niyaj.ui.utils.TrackScreenViewEvent import com.niyaj.ui.utils.TrackScrollJank import com.niyaj.ui.utils.UiEvent import com.ramcosta.composedestinations.annotation.Destination import com.ramcosta.composedestinations.annotation.RootNavGraph import com.ramcosta.composedestinations.navigation.DestinationsNavigator import com.ramcosta.composedestinations.result.NavResult import com.ramcosta.composedestinations.result.ResultRecipient import kotlinx.coroutines.launch /** * Profile Screen Composable * @author <NAME> * */ @RootNavGraph(start = true) @Destination(route = Screens.PROFILE_SCREEN) @Composable fun ProfileScreen( navigator: DestinationsNavigator, resultRecipient: ResultRecipient<UpdateProfileScreenDestination, String>, modifier: Modifier = Modifier, viewModel: ProfileViewModel = hiltViewModel(), ) { val snackbarHostState = remember { SnackbarHostState() } val scope = rememberCoroutineScope() val systemUiController = rememberSystemUiController() val statusBarColor = MaterialTheme.colorScheme.primary SideEffect { systemUiController.setStatusBarColor( color = statusBarColor, darkIcons = false, ) } val info = viewModel.info.collectAsStateWithLifecycle().value val accountInfo = viewModel.accountInfo.collectAsStateWithLifecycle().value val resLogoLauncher = rememberLauncherForActivityResult( contract = ActivityResultContracts.PickVisualMedia(), ) { uri -> uri?.let { viewModel.changeRestaurantLogo(it) } } val printLogoLauncher = rememberLauncherForActivityResult( contract = ActivityResultContracts.PickVisualMedia(), ) { uri -> uri?.let { viewModel.changePrintLogo(it) } } LaunchedEffect(key1 = true) { viewModel.eventFlow.collect { event -> when (event) { is UiEvent.OnSuccess -> { snackbarHostState.showSnackbar( message = event.successMessage, ) } is UiEvent.OnError -> { snackbarHostState.showSnackbar( message = event.errorMessage, ) } } } } resultRecipient.onNavResult { result -> when (result) { is NavResult.Canceled -> {} is NavResult.Value -> { scope.launch { snackbarHostState.showSnackbar(result.value) } } } } BackHandler { navigator.popBackStack() } TrackScreenViewEvent(screenName = Screens.PROFILE_SCREEN) ProfileScreenContent( modifier = modifier, profile = info, accountInfo = accountInfo, onBackClick = navigator::popBackStack, onClickEditProfile = { navigator.navigate(UpdateProfileScreenDestination(it)) }, onClickChangePassword = { navigator.navigate(ChangePasswordScreenDestination(it)) }, onClickChangeResLogo = { resLogoLauncher.launch( PickVisualMediaRequest(ActivityResultContracts.PickVisualMedia.ImageOnly), ) }, onClickChangePrintLogo = { printLogoLauncher.launch( PickVisualMediaRequest(ActivityResultContracts.PickVisualMedia.ImageOnly), ) }, statusBarColor = statusBarColor, snackbarHostState = snackbarHostState, ) } @VisibleForTesting @OptIn(ExperimentalMaterial3Api::class) @Composable internal fun ProfileScreenContent( profile: Profile, onBackClick: () -> Unit, onClickEditProfile: (Int) -> Unit, onClickChangePassword: (Int) -> Unit, onClickChangeResLogo: () -> Unit, onClickChangePrintLogo: () -> Unit, modifier: Modifier = Modifier, accountInfo: Account? = null, statusBarColor: Color = MaterialTheme.colorScheme.primary, snackbarHostState: SnackbarHostState = remember { SnackbarHostState() }, ) { val lazyListState = rememberLazyListState() var showPrintLogo by rememberSaveable { mutableStateOf(false) } Scaffold( modifier = modifier .fillMaxSize(), snackbarHost = { SnackbarHost(hostState = snackbarHostState) }, topBar = { TopAppBar( title = { Text(text = PROFILE_SCREEN) }, navigationIcon = { IconButton( onClick = onBackClick, ) { Icon( imageVector = PoposIcons.ArrowBack, contentDescription = "Navigate Back", ) } }, actions = { IconButton( onClick = { onClickEditProfile(profile.restaurantId) }, ) { Icon( imageVector = PoposIcons.Edit, contentDescription = "Edit Profile", ) } }, colors = TopAppBarDefaults.topAppBarColors( containerColor = statusBarColor, titleContentColor = contentColorFor(backgroundColor = statusBarColor), actionIconContentColor = contentColorFor(backgroundColor = statusBarColor), navigationIconContentColor = contentColorFor(backgroundColor = statusBarColor), ), ) }, ) { TrackScrollJank(scrollableState = lazyListState, stateName = "ProfileScreen::State") LazyColumn( modifier = Modifier .fillMaxSize() .padding(it) .background(LightColor6), state = lazyListState, verticalArrangement = Arrangement.spacedBy(SpaceSmall), ) { item("Restaurant Info") { Column( modifier = Modifier.fillMaxWidth(), ) { RestaurantCard( info = profile, showPrintLogo = showPrintLogo, onClickChangeResLogo = onClickChangeResLogo, onClickChangePrintLogo = onClickChangePrintLogo, onClickViewPrintLogo = { showPrintLogo = !showPrintLogo }, ) NoteCard(text = RES_LOGO_NOTE) Spacer(modifier = Modifier.height(SpaceMini)) NoteCard(text = PRINT_LOGO_NOTE) } } item("Account Info") { accountInfo?.let { AccountInfo( modifier = Modifier.padding(horizontal = SpaceSmall), account = accountInfo, ) } } item("Change Password") { SettingsCard( modifier = Modifier.padding(SpaceSmall), title = "Change Password", subtitle = "Click here to change password", icon = PoposIcons.Password, containerColor = Color.White, onClick = { onClickChangePassword(profile.restaurantId) }, ) Spacer(modifier = Modifier.height(SpaceSmall)) } } } } @DevicePreviews @Composable private fun ProfileScreenContentPreview( modifier: Modifier = Modifier, profile: Profile = Profile.defaultProfileInfo, account: Account = Account.defaultAccount, ) { PoposRoomTheme { ProfileScreenContent( modifier = modifier, profile = profile, accountInfo = account, onBackClick = {}, onClickEditProfile = {}, onClickChangePassword = {}, onClickChangeResLogo = {}, onClickChangePrintLogo = {}, ) } }
42
Kotlin
0
1
a38d8d1551726195cab9c65595de0a4fa34e893b
11,776
PoposRoom
Apache License 2.0
straight/src/commonMain/kotlin/me/localx/icons/straight/outline/DiagramProject.kt
localhostov
808,861,591
false
{"Kotlin": 79430321, "HTML": 331, "CSS": 102}
package me.localx.icons.straight.outline import androidx.compose.ui.graphics.Color import androidx.compose.ui.graphics.PathFillType.Companion.NonZero import androidx.compose.ui.graphics.SolidColor import androidx.compose.ui.graphics.StrokeCap.Companion.Butt import androidx.compose.ui.graphics.StrokeJoin.Companion.Miter import androidx.compose.ui.graphics.vector.ImageVector import androidx.compose.ui.graphics.vector.ImageVector.Builder import androidx.compose.ui.graphics.vector.path import androidx.compose.ui.unit.dp import me.localx.icons.straight.Icons public val Icons.Outline.DiagramProject: ImageVector get() { if (_diagramProject != null) { return _diagramProject!! } _diagramProject = Builder(name = "DiagramProject", defaultWidth = 512.0.dp, defaultHeight = 512.0.dp, viewportWidth = 24.0f, viewportHeight = 24.0f).apply { path(fill = SolidColor(Color(0xFF000000)), stroke = null, strokeLineWidth = 0.0f, strokeLineCap = Butt, strokeLineJoin = Miter, strokeLineMiter = 4.0f, pathFillType = NonZero) { moveTo(24.0f, 9.0f) lineTo(24.0f, 3.5f) curveToRelative(0.0f, -1.379f, -1.122f, -2.5f, -2.5f, -2.5f) horizontalLineToRelative(-3.0f) curveToRelative(-1.378f, 0.0f, -2.5f, 1.121f, -2.5f, 2.5f) verticalLineToRelative(0.5f) lineTo(8.0f, 4.0f) verticalLineToRelative(-0.5f) curveToRelative(0.0f, -1.379f, -1.122f, -2.5f, -2.5f, -2.5f) lineTo(2.5f, 1.0f) curveTo(1.122f, 1.0f, 0.0f, 2.121f, 0.0f, 3.5f) verticalLineToRelative(5.5f) lineTo(5.928f, 9.0f) lineToRelative(4.339f, 7.377f) curveToRelative(-0.171f, 0.338f, -0.268f, 0.719f, -0.268f, 1.123f) verticalLineToRelative(5.5f) horizontalLineToRelative(8.0f) verticalLineToRelative(-5.5f) curveToRelative(0.0f, -1.379f, -1.122f, -2.5f, -2.5f, -2.5f) horizontalLineToRelative(-3.0f) curveToRelative(-0.232f, 0.0f, -0.456f, 0.032f, -0.669f, 0.091f) lineToRelative(-3.831f, -6.513f) verticalLineToRelative(-2.578f) horizontalLineToRelative(8.0f) verticalLineToRelative(3.0f) horizontalLineToRelative(8.0f) close() moveTo(2.0f, 3.5f) curveToRelative(0.0f, -0.275f, 0.224f, -0.5f, 0.5f, -0.5f) horizontalLineToRelative(3.0f) curveToRelative(0.276f, 0.0f, 0.5f, 0.225f, 0.5f, 0.5f) verticalLineToRelative(3.5f) lineTo(2.0f, 7.0f) lineTo(2.0f, 3.5f) close() moveTo(15.5f, 17.0f) curveToRelative(0.276f, 0.0f, 0.5f, 0.225f, 0.5f, 0.5f) verticalLineToRelative(3.5f) horizontalLineToRelative(-4.0f) verticalLineToRelative(-3.5f) curveToRelative(0.0f, -0.275f, 0.224f, -0.5f, 0.5f, -0.5f) horizontalLineToRelative(3.0f) close() moveTo(18.0f, 3.5f) curveToRelative(0.0f, -0.275f, 0.224f, -0.5f, 0.5f, -0.5f) horizontalLineToRelative(3.0f) curveToRelative(0.276f, 0.0f, 0.5f, 0.225f, 0.5f, 0.5f) verticalLineToRelative(3.5f) horizontalLineToRelative(-4.0f) lineTo(18.0f, 3.5f) close() } } .build() return _diagramProject!! } private var _diagramProject: ImageVector? = null
1
Kotlin
0
5
cbd8b510fca0e5e40e95498834f23ec73cc8f245
3,789
icons
MIT License
app/src/main/java/com/sakethh/linkora/ui/screens/collections/allLinks/LinkTypeSelection.kt
sakethpathike
648,784,316
false
{"Kotlin": 1590874}
package com.sakethh.linkora.ui.screens.collections.allLinks import androidx.compose.runtime.MutableState import com.sakethh.linkora.data.local.links.LinkType data class LinkTypeSelection( val linkType: LinkType, val isChecked: MutableState<Boolean> )
9
Kotlin
11
307
ebbd4669a8e762587267560f60d0ec3339e9e75f
260
Linkora
MIT License
dpadrecyclerview/src/main/java/com/rubensousa/dpadrecyclerview/layoutmanager/focus/DefaultFocusInterceptor.kt
rubensousa
530,412,665
false
{"Kotlin": 1169718, "Shell": 2774}
/* * Copyright 2022 <NAME> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.rubensousa.dpadrecyclerview.layoutmanager.focus import android.view.FocusFinder import android.view.View import com.rubensousa.dpadrecyclerview.DpadRecyclerView import com.rubensousa.dpadrecyclerview.FocusableDirection import com.rubensousa.dpadrecyclerview.layoutmanager.LayoutConfiguration import com.rubensousa.dpadrecyclerview.layoutmanager.layout.LayoutInfo /** * Implementation for [FocusableDirection.STANDARD] */ internal class DefaultFocusInterceptor( private val layoutInfo: LayoutInfo, private val configuration: LayoutConfiguration, private val focusFinder: FocusFinder = FocusFinder.getInstance() ) : FocusInterceptor { override fun findFocus( recyclerView: DpadRecyclerView, focusedView: View, position: Int, direction: Int ): View? { val focusAbsoluteDirection = FocusDirection.getAbsoluteDirection( direction = direction, isVertical = configuration.isVertical(), reverseLayout = layoutInfo.shouldReverseLayout() ) // Exit early if the focus finder can't find focus already val nextFocusFinderView = focusFinder.findNextFocus( recyclerView, focusedView, focusAbsoluteDirection ) ?: return null val currentViewHolder = layoutInfo.getChildViewHolder(focusedView) val nextViewHolder = layoutInfo.getChildViewHolder(nextFocusFinderView) /** * Check if the focus finder has found another focusable view for the same ViewHolder * This might happen when sub positions are used */ if (nextViewHolder === currentViewHolder && nextFocusFinderView !== focusedView) { return nextFocusFinderView } return if (configuration.spanCount == 1) { val relativeFocusDirection = FocusDirection.from( direction, isVertical = configuration.isVertical(), reverseLayout = configuration.reverseLayout ) ?: return nextFocusFinderView /** * If the layout is looping, let the focus finder find the next focusable view * if we're searching for focus in the layout direction */ if (layoutInfo.isLoopingAllowed && relativeFocusDirection.isPrimary()) { return nextFocusFinderView } findNextLinearChild(position, relativeFocusDirection) } else { return nextFocusFinderView } } private fun findNextLinearChild(position: Int, direction: FocusDirection): View? { // We only support the main direction if (direction.isSecondary()) { return null } val positionIncrement = layoutInfo.getPositionIncrement( goingForward = direction == FocusDirection.NEXT_ROW || direction == FocusDirection.NEXT_COLUMN ) val nextPosition = position + positionIncrement // Jump early if we're going out of bounds if (nextPosition < 0 || nextPosition == layoutInfo.getItemCount()) { return null } return findNextFocusableView( fromPosition = nextPosition, positionIncrement = positionIncrement ) } private fun findNextFocusableView( fromPosition: Int, positionIncrement: Int ): View? { var currentPosition = fromPosition while (currentPosition >= 0 && currentPosition < layoutInfo.getItemCount()) { // Exit early if we've exhausted the current layout structure val view = layoutInfo.findViewByPosition(currentPosition) ?: return null if (layoutInfo.isViewFocusable(view)) { return view } currentPosition += positionIncrement } return null } }
1
Kotlin
17
135
ef7df356ad9fbc5a2427c8447af35a0810573207
4,438
DpadRecyclerView
Apache License 2.0
src/k_02_estructuraIF/Ejemplo4.kt
lizarragadev
206,426,905
false
{"Kotlin": 81555}
package k_02_estructuraIF /** * @author <NAME> * @date 26/09/2019 * * Ejercicio aplicando lectura de datos de teclado, if else y operadores matemáticos. * * */ fun main() { print("Ingrese el primer valor: ") val valor1 = readLine()!!.toInt() print("Ingrese el segundo valor: ") val valor2 = readLine()!!.toInt() if (valor1 < valor2) { val suma = valor1.plus(valor2) val resta = valor1.minus(valor2) println("La suma de los dos valores es: $suma") println("La resta de los dos valores es: $resta") } else { val producto = valor1.times(valor2) val division = valor1.div(valor2) println("El producto de los dos valores es: $producto") println("La división de los dos valores es: $division") } }
0
Kotlin
2
1
1d24b475e84b88099036988402f9e072a8187535
791
KotlinStudyJam
MIT License
integration-tests/src/test/kotlin/com/testapp/tests/payments/flows/paylater/PayLaterDEFailureTest.kt
klarna
200,860,800
false
null
package com.testapp.tests.payments.flows.paylater import com.testapp.network.KlarnaApi import com.testapp.utils.BillingAddressTestHelper import com.testapp.utils.SessionHelper import org.junit.Test internal class PayLaterDEFailureTest: BasePayLaterTest() { @Test fun `test payment pay later germany failure flow`() { val session = KlarnaApi.getSessionInfo(SessionHelper.getRequestDE())?.session testPayLater(false, session, BillingAddressTestHelper.getBillingInfoDE()) } }
33
Kotlin
16
18
80558df356a2160dea8a8e498cf04fcea80d06e2
503
react-native-klarna-inapp-sdk
Apache License 2.0
app/src/main/java/com/github/gpspilot/UiRequest.kt
vslomakin
168,400,945
false
null
package com.github.gpspilot import android.app.Activity import android.app.AlertDialog import android.content.Context import android.content.DialogInterface import android.content.pm.PackageManager import android.os.Bundle import android.view.ActionMode import android.view.Menu import android.view.MenuItem import android.widget.Toast import androidx.annotation.StringRes import androidx.core.app.ActivityCompat import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.ObsoleteCoroutinesApi import kotlinx.coroutines.channels.ReceiveChannel import kotlinx.coroutines.channels.consumeEach import kotlinx.coroutines.launch import kotlin.reflect.KClass /** * Abstraction to request some view actions from viewmodel. */ sealed class UiRequest { data class Toast(@StringRes val text: Int, val length: Length) : UiRequest() { enum class Length(val value: Int) { SHORT(android.widget.Toast.LENGTH_SHORT), LONG(android.widget.Toast.LENGTH_LONG) } } data class Dialog( @StringRes val text: Int, @StringRes val positiveBtn: Int, @StringRes val negativeBtn: Int, val positiveCallback: (() -> Unit)? = null, val negativeCallback: (() -> Unit)? = null ) : UiRequest() data class StartActivity( val activity: KClass<out Activity>, val data: Bundle? = null, val requestCode: Int? = null ) : UiRequest() object FinishActivity : UiRequest() data class StartActionMode( @StringRes val title: String? = null, val onClose: (() -> Unit)? = null ) : UiRequest() object StopActionMode : UiRequest() data class Permission(val permission: String) : UiRequest() } fun Context.showToast(vo: UiRequest.Toast) { Toast.makeText(this, vo.text, vo.length.value).show() } fun UiRequest.Dialog.buildDialog(ctx: Context): AlertDialog { val builder = AlertDialog.Builder(ctx).apply { setMessage(text) setPositiveButton(positiveBtn, positiveCallback?.toDialogClickListener()) setNegativeButton(negativeBtn, negativeCallback?.toDialogClickListener()) setCancelable(false) } return builder.create() } private fun (() -> Unit).toDialogClickListener() = DialogInterface.OnClickListener { _, _ -> invoke() } fun KClass<out Activity>.toRequest() = UiRequest.StartActivity(this) private class CABController(private val activity: Activity) { private var actionMode: ActionMode? = null fun start(req: UiRequest.StartActionMode) { if (actionMode == null) { actionMode = activity.startActionMode(Callback(req)) } } fun stop() { actionMode?.apply { finish() } } private inner class Callback(private val req: UiRequest.StartActionMode) : ActionMode.Callback { override fun onActionItemClicked(mode: ActionMode?, item: MenuItem?) = true override fun onCreateActionMode(mode: ActionMode?, menu: Menu?) = true override fun onPrepareActionMode(mode: ActionMode, menu: Menu): Boolean { req.title?.let { mode.title = it } return false } override fun onDestroyActionMode(mode: ActionMode?) { actionMode = null req.onClose?.invoke() } } } private fun Activity.requestPermission(permission: String) { ActivityCompat.requestPermissions( this, arrayOf(permission), 0 ) } /** * Convenient holder for permission result. */ data class PermissionResult(val permission: String, val granted: Boolean) /** * Creates list of [PermissionResult] for further iteration. * Assumed to be called from [Activity.onRequestPermissionsResult]. */ fun permissionResults(permissions: Array<out String>, granted: IntArray): List<PermissionResult> { return List(permissions.size) { i -> PermissionResult( permission = permissions[i], granted = granted[i] == PackageManager.PERMISSION_GRANTED ) } } @ObsoleteCoroutinesApi fun <T> T.handleUiRequests(vos: ReceiveChannel<UiRequest>) where T : Activity, T : CoroutineScope { val cabController = CABController(this) launch(Dispatchers.Main) { vos.consumeEach { when (it) { is UiRequest.Toast -> showToast(it) is UiRequest.Dialog -> it.buildDialog(this@handleUiRequests).show() is UiRequest.StartActivity -> start(it.activity, it.requestCode, it.data) is UiRequest.FinishActivity -> finish() is UiRequest.StartActionMode -> cabController.start(it) is UiRequest.StopActionMode -> cabController.stop() is UiRequest.Permission -> requestPermission(it.permission) }.exhaustive } } }
1
Kotlin
0
1
f5ed889d1b9d36a7e1e14e9e95a4768eb065282e
4,843
gpspilot
The Unlicense
android/AndroidX_Test/app/src/main/java/ca/six/demo/utest2/ui/rv/OneAdapter.kt
songzhw
220,994,423
false
{"Text": 3, "Ignore List": 2, "Markdown": 1, "YAML": 3, "JSON with Comments": 2, "JSON": 13, "HTML": 2, "robots.txt": 1, "SVG": 1, "TSX": 20, "CSS": 1, "JavaScript": 22, "Kotlin": 55, "Java": 9, "Objective-C": 21, "OpenStep Property List": 10, "XML": 27, "Gradle": 6, "Java Properties": 2, "Proguard": 1, "INI": 2, "Shell": 1, "Dotenv": 1, "Git Attributes": 1, "Starlark": 1, "Ruby": 1}
package ca.six.advk.utils.rv import android.view.ViewGroup import androidx.recyclerview.widget.RecyclerView import java.util.ArrayList abstract class OneAdapter<T> : RecyclerView.Adapter<RvViewHolder> { var layoutResId: Int = 0 var data: List<T>? = null constructor(layoutResId: Int) { this.layoutResId = layoutResId data = ArrayList() } constructor(layoutResId: Int, data: List<T>) { this.layoutResId = layoutResId this.data = data } override fun getItemCount(): Int { return if (data == null) 0 else data!!.size } override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): RvViewHolder { // System.out.println("szw onCreateViewHolder()"); return RvViewHolder.createViewHolder(parent, layoutResId) } override fun onBindViewHolder(holder: RvViewHolder, position: Int) { // System.out.println("szw onBindViewHolder( "+position+" )"); if (data != null && data!!.size > position) { apply(holder, data!![position], position) } } protected abstract fun apply(vh: RvViewHolder, value: T, position: Int) } /* 在不同的type 的时候 如果该 type 所对应的 viewHolder 还没被初始化的时候,会重新调用 onCreateViewHolder 的, 而其他的还是会只调用 onBindViewHolder。 即: onCreateViewHolder(ViewGroup parent, int viewType)的参数里没有position, 只有viewType 上下滑动时, onBindViewHolder(vh, position)会被反复调用. 这个有点像ListView.getAdapter()中的getView() */
26
Kotlin
0
0
b40f71d3c00a268694cf3ca468c6d2ccaa020a0e
1,453
TestDemos
Apache License 2.0
recurve/src/main/java/com/recurve/core/ui/creator/ext/CollapsingToolbarLayoutExt.kt
Tangpj
146,057,917
false
null
/* * Copyright (C) 2018 Tang * * 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.recurve.core.ui.creator.ext import android.view.LayoutInflater import android.view.View import androidx.annotation.ColorInt import androidx.annotation.ColorRes import androidx.annotation.DrawableRes import com.google.android.material.appbar.CollapsingToolbarLayout class CollapsingToolbarLayoutExt{ @DrawableRes var contentScrimDrawable: Int = -1 @ColorRes var contentScrimColor: Int = -1 @ColorInt var contentScrimColorInt: Int = -1 var expandedTitleGravity: String? = "" var expandedTitleMargin = 0F var expandedTitleMarginStart = 0F var expandedTitleMarginTop = 0F var expandedTitleMarginEnd = 0F var expandedTitleMarginBottom = 0F var collapsingCreator : ((inflater: LayoutInflater, CollapsingToolbarLayout) -> View)? = null fun collapsingView(collapsingCreator : ((inflater: LayoutInflater, CollapsingToolbarLayout) -> View)?){ this.collapsingCreator = collapsingCreator } internal fun configExpandedTitleMargin(collapsingToolbarLayout: CollapsingToolbarLayout){ when{ expandedTitleMargin > 0 -> collapsingToolbarLayout.setExpandedTitleMargin( expandedTitleMargin.toInt(), expandedTitleMargin.toInt(), expandedTitleMargin.toInt(), expandedTitleMargin.toInt() ) expandedTitleMarginStart > 0 -> collapsingToolbarLayout.expandedTitleMarginStart = expandedTitleMarginStart.toInt() expandedTitleMarginTop > 0 -> collapsingToolbarLayout.expandedTitleMarginTop = expandedTitleMarginTop.toInt() expandedTitleMarginEnd > 0 -> collapsingToolbarLayout.expandedTitleMarginEnd = expandedTitleMarginEnd.toInt() expandedTitleMarginBottom > 0 -> collapsingToolbarLayout.expandedTitleMarginBottom = expandedTitleMarginBottom.toInt() } } }
0
null
9
56
5b724cb9cf914be26c44f2a6bcca5b672a5e30b7
2,591
MVVMRecurve
Apache License 2.0
worldwind/src/commonMain/kotlin/earth/worldwind/layer/TiledImageLayer.kt
WorldWindEarth
488,505,165
false
{"Kotlin": 2674262, "JavaScript": 459619, "HTML": 108593, "CSS": 8778}
package earth.worldwind.layer expect abstract class TiledImageLayer(name: String): AbstractTiledImageLayer
24
Kotlin
9
70
107a29c8bd02de61204b301549da77783ff6252c
107
WorldWindKotlin
Apache License 2.0
image-source-api/src/main/java/com/stefang/image/source/api/ImageSourceApi.kt
stef-ang
652,432,695
false
null
package com.stefang.image.source.api import android.net.Uri import androidx.activity.ComponentActivity interface ImageSourceApi { fun initLauncher( componentActivity: ComponentActivity, onResult: (Uri) -> Unit ) fun runLauncher() companion object { const val EXTRA_PHOTO_URI = "extra_photo_uri" } }
0
Kotlin
0
0
e7b0dd4c071c3ec5c662d601672ff467b6b937df
348
ScanMeCalculator
Apache License 2.0
samples/src/test/kotlin/io/polymorphicpanda/kspec/samples/IncludeFilter.kt
jasonm23
57,346,529
true
{"Kotlin": 85751}
package io.polymorphicpanda.kspec.samples import com.natpryce.hamkrest.assertion.assertThat import com.natpryce.hamkrest.equalTo import io.polymorphicpanda.kspec.KSpec import io.polymorphicpanda.kspec.config.KSpecConfig import io.polymorphicpanda.kspec.describe import io.polymorphicpanda.kspec.it import io.polymorphicpanda.kspec.junit.JUnitKSpecRunner import io.polymorphicpanda.kspec.tag.Tag import org.junit.runner.RunWith /** * @author <NAME> */ @RunWith(JUnitKSpecRunner::class) class ExcludeFilter: KSpec() { val tag = Tag("bar") override fun configure(config: KSpecConfig) { config.filter.exclude(tag) } override fun spec() { describe("a group") { it("some example") { assertThat(true, equalTo(true)) } it("i should be ignored", tag) { assertThat(true, equalTo(false)) } } } }
0
Kotlin
0
0
617186c30f6eacaa6f96f380f4e1d03035674275
916
kspec
MIT License
app/src/main/java/com/mafqud/android/myAccountEdit/name/AccountRepository.kt
MafQud
483,257,198
false
null
package com.mafqud.android.myAccountEdit.name import com.mafqud.android.base.BaseRepository import com.mafqud.android.myAccountEdit.name.models.ChangeNameBody import com.mafqud.android.util.network.Result import com.mafqud.android.util.network.safeApiCall import kotlinx.coroutines.coroutineScope import javax.inject.Inject import kotlinx.coroutines.launch class AccountRepository @Inject constructor() : BaseRepository() { suspend fun changeUserName(userName: String): Result<Any> { return safeApiCall { return@safeApiCall coroutineScope { launch { val result = remoteDataManager.changeUserName( userID = getCurrentUserID(), ChangeNameBody(name = userName) ) saveNewUserName(userName) } } } } private suspend fun saveNewUserName(userName: String) { setUserName(userName) } private suspend fun getCurrentUserID() = getUserID() suspend fun getCurrentName() = getUserName() }
0
Kotlin
6
35
309e82d51d6c1c776365643ef48ecb78fd243c23
1,095
MafQud-Android
MIT License
src/main/kotlin/graphs/primitives/Vertex.kt
spbu-coding-2023
790,907,560
false
{"Kotlin": 145908}
package graphs.primitives interface Vertex { var element: Long var data: String? }
1
Kotlin
0
20
bdec50482e48e3dbc3e29475841e2d02c288b6a4
92
graphs-graph-10
MIT License
app/src/main/java/com/archeros/roadmap/database/Database.kt
Nicholas-Ferreira
296,177,511
false
null
package com.archeros.roadmap.database import androidx.room.Database import androidx.room.RoomDatabase import com.archeros.roadmap.database.dao.BranchDAO import com.archeros.roadmap.database.dao.RepositorioDAO import com.archeros.roadmap.database.dao.UserDAO import com.archeros.roadmap.entity.Branch import com.archeros.roadmap.entity.Repositorio import com.archeros.roadmap.entity.User @Database(entities = [ User::class, Branch::class, Repositorio::class ], version = 1) abstract class Database: RoomDatabase() { abstract fun userDAO(): UserDAO abstract fun repositorioDAO(): RepositorioDAO abstract fun branchDAO(): BranchDAO }
0
Kotlin
0
0
bc0cedd22ff49c6c061f1f203e6ca8964ac5b1bf
656
aplicativo-kotlin-roadmap
MIT License
theme-contract/src/main/java/com/orange/ouds/theme/OudsBorderModifier.kt
Orange-OpenSource
817,725,638
false
{"Kotlin": 254051, "HTML": 14555, "CSS": 1404, "JavaScript": 197}
/* * Software Name: OUDS Android * SPDX-FileCopyrightText: Copyright (c) Orange SA * SPDX-License-Identifier: MIT * * This software is distributed under the MIT license, * the text of which is available at https://opensource.org/license/MIT/ * or see the "LICENSE" file for more details. * * Software description: Android library of reusable graphical components */ package com.orange.ouds.theme import androidx.compose.ui.Modifier import androidx.compose.ui.draw.drawWithContent import androidx.compose.ui.geometry.Offset import androidx.compose.ui.geometry.Rect import androidx.compose.ui.geometry.Size import androidx.compose.ui.graphics.Color import androidx.compose.ui.graphics.Path import androidx.compose.ui.graphics.PathEffect import androidx.compose.ui.graphics.RectangleShape import androidx.compose.ui.graphics.Shape import androidx.compose.ui.graphics.SolidColor import androidx.compose.ui.graphics.StampedPathEffectStyle import androidx.compose.ui.graphics.drawOutline import androidx.compose.ui.graphics.drawscope.Stroke import androidx.compose.ui.graphics.drawscope.translate import androidx.compose.ui.unit.Dp /** * Modify element to add a dashed border styled with appearance specified with a [width], a [color] and a [shape], and clip it. * * @param width Thickness of the border in dp * @param color Color to paint the border with * @param shape Shape of the border */ fun Modifier.dashedBorder( width: Dp, color: Color, shape: Shape = RectangleShape, ) = drawWithContent { val innerSize = Size(size.width - width.toPx(), size.height - width.toPx()) val outline = shape.createOutline(innerSize, layoutDirection, density = this) val dashedStroke = Stroke( width = width.toPx(), pathEffect = PathEffect.dashPathEffect( intervals = floatArrayOf(width.toPx() * 2f, width.toPx() * 2f) ) ) drawContent() translate(width.toPx() / 2f, width.toPx() / 2f) { drawOutline( outline = outline, style = dashedStroke, brush = SolidColor(color) ) } } /** * Modify element to add a dotted border styled with appearance specified with a [width], a [color] and a [shape], and clip it. * * @param width Thickness of the border in dp * @param color Color to paint the border with * @param shape Shape of the border */ fun Modifier.dottedBorder( width: Dp, color: Color, shape: Shape = RectangleShape, ) = drawWithContent { val dotRadius = width / 2 val circle = Path() circle.addOval(Rect(center = Offset.Zero, radius = dotRadius.toPx())) val innerSize = Size(size.width - width.toPx(), size.height - width.toPx()) val outline = shape.createOutline(innerSize, layoutDirection, density = this) val dottedStroke = Stroke( width = width.toPx(), pathEffect = PathEffect.stampedPathEffect( shape = circle, advance = (dotRadius * 2).toPx() * 2f, phase = 0f, style = StampedPathEffectStyle.Translate ) ) drawContent() translate(width.toPx() / 2f, width.toPx() / 2f) { drawOutline( outline = outline, style = dottedStroke, brush = SolidColor(color) ) } } /** * Modify element to add an outer border (drawn outside the element) with appearance specified with a [width], a [color] and a [shape]. * * @param width Thickness of the border in dp * @param color Color to paint the border with * @param shape Shape of the border */ fun Modifier.outerBorder( width: Dp, color: Color, shape: Shape = RectangleShape ) = drawWithContent { val outerSize = Size(size.width + width.toPx(), size.height + width.toPx()) val outline = shape.createOutline(outerSize, layoutDirection, density = this) val stroke = Stroke(width = width.toPx()) drawContent() translate(-width.toPx() / 2f, -width.toPx() / 2f) { drawOutline( outline = outline, style = stroke, brush = SolidColor(color) ) } }
24
Kotlin
1
6
fc7bbf1f042348d6fb9d2308dd2827df62f13ffb
4,088
ouds-android
MIT License
psiSection/editingPsiElementsLesson/renameFunctionProgrammingTask/test/org/jetbrains/academy/plugin/course/dev/edit/Tests.kt
jetbrains-academy
691,965,440
false
{"Kotlin": 75549}
package org.jetbrains.academy.plugin.course.dev.edit import com.intellij.psi.util.PsiTreeUtil import com.intellij.testFramework.fixtures.BasePlatformTestCase import org.jetbrains.kotlin.psi.KtNamedFunction abstract class BaseEditFunctionNameTest : BasePlatformTestCase() { private fun getResourceFileContent(relativePath: String) = EditFunctionNameTest::class.java.getResourceAsStream(BASE_PATH + relativePath)?.bufferedReader()?.use { it.readText() } ?: "" private fun getFile(fileContent: String) = myFixture.configureByText("MyClass.kt", fileContent) ?: error("Internal course error!") fun doTest(relativePath: String) { val fileContent = getResourceFileContent(relativePath) val file = getFile(fileContent) val functions = PsiTreeUtil.findChildrenOfType(file, KtNamedFunction::class.java) for (function in functions) { val snakeCaseFunctionName = function.name ?: continue val expectedCamelCaseFunctionName = snakeCaseFunctionName.snakeToCamelCase() functionNameSnakeToCamelCase(function) val actualCamelCaseFunctionName = function.name ?: error("Can not get function name after case change!!!") assertTrue( "For the function with name $snakeCaseFunctionName " + "the function functionNameSnakeToCamelCase should rename " + "$snakeCaseFunctionName function into camel case, " + "but we got $actualCamelCaseFunctionName which is not camel case!", expectedCamelCaseFunctionName == actualCamelCaseFunctionName ) } } private fun String.snakeToCamelCase(): String { return this.split('_').withIndex().joinToString("") { (index, it) -> if (index == 0) it.lowercase() else it.lowercase().replaceFirstChar(Char::titlecase) } } companion object { private const val BASE_PATH = "/backUpProjects/sort-methods-project/src/main/kotlin/org/jetbrains/academy/plugin/course/dev/project/examples/" } } class EditFunctionNameTest : BaseEditFunctionNameTest() { fun testSolution() { doTest("SnakeCaseFunctions.kt") } }
0
Kotlin
1
2
b31a4a8a32bd59b3e3aa96fd842b50f39fc989d8
2,228
intellij-platform-plugin-course
MIT License
easyadapter-sample/src/main/java/ru/surfstudio/android/easyadapter/sample/ui/screen/main/MainActivityView.kt
llOldmenll
153,600,669
true
{"Kotlin": 965498, "Java": 812179, "FreeMarker": 79263, "Groovy": 8783}
package ru.surfstudio.android.easyadapter.sample.ui.screen.main import android.os.Bundle import android.os.PersistableBundle import android.support.annotation.IdRes import kotlinx.android.synthetic.main.activity_main.* import ru.surfstudio.android.core.mvp.activity.BaseRenderableActivityView import ru.surfstudio.android.core.mvp.presenter.CorePresenter import ru.surfstudio.android.easyadapter.sample.R import ru.surfstudio.android.easyadapter.sample.ui.base.configurator.CustomActivityScreenConfigurator import javax.inject.Inject /** * Вью главного экрана */ class MainActivityView : BaseRenderableActivityView<MainScreenModel>() { override fun getScreenName(): String = "MainActivity" @Inject internal lateinit var presenter: MainPresenter @IdRes override fun getContentView(): Int = R.layout.activity_main override fun onCreate(savedInstanceState: Bundle?, persistentState: PersistableBundle?, viewRecreated: Boolean) { super.onCreate(savedInstanceState, persistentState, viewRecreated) show_multitype_list_btn.setOnClickListener { presenter.showMultitypeList() } show_paginationable_list.setOnClickListener { presenter.showPagintationList() } } override fun renderInternal(screenModel: MainScreenModel) {} override fun getPresenters(): Array<CorePresenter<*>> = arrayOf(presenter) override fun createConfigurator(): CustomActivityScreenConfigurator = MainScreenConfigurator(intent) }
0
Kotlin
0
0
039e659bea18fae9e7254b5c2a341b59d0442cc0
1,518
SurfAndroidStandard
Apache License 2.0
app/src/androidTest/java/com/ndipatri/solarmonitor/container/UITestObjectGraph.kt
ndipatri
93,703,045
false
null
package com.ndipatri.solarmonitor.container import android.content.Context import com.ndipatri.solarmonitor.MainActivityMockUserTest import com.ndipatri.solarmonitor.MainActivityUnitTest import com.ndipatri.solarmonitor.activities.MainActivity import com.ndipatri.solarmonitor.activities.MainActivityViewModel import com.ndipatri.solarmonitor.container.modules.MockViewModelModule import com.ndipatri.solarmonitor.fragments.ConfigDialogFragment import com.ndipatri.solarmonitor.fragments.ConfigDialogFragmentViewModel import com.ndipatri.solarmonitor.providers.panelScan.PanelProvider import dagger.Component import javax.inject.Singleton // NJD TODO - can we get rid of ServiceModule here? @Singleton @Component(modules = arrayOf(ServiceModule::class, HardwareModule::class, MockViewModelModule::class)) interface UITestObjectGraph : ObjectGraph { override fun inject(thingy: MainActivity) override fun inject(thingy: MainActivityViewModel) override fun inject(thingy: ConfigDialogFragmentViewModel) override fun inject(fragment: ConfigDialogFragment) override fun inject(thingy: PanelProvider) fun inject(userTest: MainActivityMockUserTest) fun inject(test: MainActivityUnitTest) object Initializer { fun init(context: Context): UITestObjectGraph { return DaggerUITestObjectGraph.builder() .serviceModule(ServiceModule(context)) .hardwareModule(HardwareModule(context)) .mockViewModelModule(MockViewModelModule(context)) .build() } } }
1
Kotlin
2
6
97a17cd3fc0475b522208ad512a0093f3006d387
1,586
solarMonitor
Apache License 2.0
feature/common/src/main/kotlin/com/gorkem/common/domain/interactor/FavouriteProgramDeleteUseCase.kt
gkaradagan
339,672,368
false
null
package com.gorkem.common.domain.interactor import com.gorkem.common.data.repository.FavouriteProgramRepository import com.gorkem.core.domain.interactor.NoResultUseCase import com.gorkem.core.util.AppCoroutineDispatchers import kotlinx.coroutines.CoroutineDispatcher class FavouriteProgramDeleteUseCase( private val appCoroutineDispatchers: AppCoroutineDispatchers, private val repository: FavouriteProgramRepository, ) : NoResultUseCase<FavouriteProgramDeleteUseCase.Parameter>() { override val dispatcher: CoroutineDispatcher get() = appCoroutineDispatchers.default override suspend fun execute(parameters: Parameter) { repository.delete(parameters.id.toString()) } data class Parameter( val id: Int ) }
1
Kotlin
1
2
77af4a7fdebf97677c324b724ec8853ca300ac73
767
TheMovie
Apache License 2.0
one.irradia.opds1_2.tests/src/test/java/one/irradia/opds1_2/tests/local/OPDS12FeedEntryDublinParsersTest.kt
irradia
177,828,518
false
{"Gradle": 12, "INI": 12, "Shell": 1, "Ignore List": 1, "Batchfile": 1, "Text": 1, "YAML": 1, "Markdown": 1, "XML": 36, "Kotlin": 61, "Java": 8}
package one.irradia.opds1_2.tests.local import one.irradia.opds1_2.parser.api.OPDS12FeedEntryParserProviderType import one.irradia.opds1_2.parser.vanilla.OPDS12FeedEntryParsers import one.irradia.opds1_2.tests.OPDS12FeedEntryDublinParserProviderContract import org.slf4j.Logger import org.slf4j.LoggerFactory class OPDS12FeedEntryDublinParsersTest : OPDS12FeedEntryDublinParserProviderContract() { override fun logger(): Logger { return LoggerFactory.getLogger(OPDS12FeedEntryDublinParsersTest::class.java) } override fun parsers(): OPDS12FeedEntryParserProviderType { return OPDS12FeedEntryParsers() } }
1
null
1
1
78596ee9c5e528ec4810472f1252d844abdf7fe3
626
one.irradia.opds1_2
BSD Zero Clause License
app/src/main/java/com/example/physicsformulas/DatabaseHelper.kt
GooseKIller
651,993,211
false
null
package com.example.physicsformulas import android.content.Context import android.database.Cursor import android.database.sqlite.SQLiteDatabase import android.database.sqlite.SQLiteOpenHelper import android.util.Log import java.io.File import java.io.FileOutputStream import java.io.InputStream class DatabaseHelper(val context: Context) : SQLiteOpenHelper(context, DATABASE_NAME, null, DATABASE_VERSION) { override fun onCreate(db: SQLiteDatabase) { db.execSQL( "CREATE TABLE IF NOT EXISTS wordle_words (_id INTEGER PRIMARY KEY AUTOINCREMENT, word TEXT, len INTEGER);" ) } override fun onUpgrade(db: SQLiteDatabase, oldVersion: Int, newVersion: Int) { db.execSQL("DROP TABLE IF EXISTS wordle_words;") onCreate(db) } fun getDataNames(sqlRequest:String = ""): ArrayList<TerminDataModel>{ val db = this.readDatabaseFromAssets(this.context) val dataList = ArrayList<TerminDataModel>() val cursor: Cursor = db.rawQuery(sqlRequest, null) if(cursor.moveToFirst()){ do { val nameDataModel = TerminDataModel( id = cursor.getInt(cursor.getColumnIndexOrThrow("id")), name = cursor.getString(cursor.getColumnIndexOrThrow("name")) ) dataList.add(nameDataModel) } while (cursor.moveToNext()) } return dataList } fun getDataTermin(sqlRequest: String = ""): TerminDataModel { val db: SQLiteDatabase = this.readDatabaseFromAssets(this.context) val cursor: Cursor = db.rawQuery(sqlRequest, null) val terminDataModel = TerminDataModel() if(cursor.moveToFirst()){ terminDataModel.id = cursor.getInt(cursor.getColumnIndexOrThrow("id")) terminDataModel.name = cursor.getString(cursor.getColumnIndexOrThrow("name")) terminDataModel.unit = cursor.getString(cursor.getColumnIndexOrThrow("unit")) terminDataModel.description = cursor.getString(cursor.getColumnIndexOrThrow("description")) terminDataModel.formulas = cursor.getString(cursor.getColumnIndexOrThrow("formulas")) } return terminDataModel } fun getDataFormulas(sqlRequest: String = ""): ArrayList<FormulaDataModel> { val db:SQLiteDatabase = this.readDatabaseFromAssets(this.context) val dataList = ArrayList<FormulaDataModel>() db.rawQuery("PRAGMA case_sensitive_like=ON;", null) val cursor: Cursor = db.rawQuery(sqlRequest, null) if(cursor.moveToFirst()){ do { val formulaDataModel = FormulaDataModel( id = cursor.getInt(cursor.getColumnIndexOrThrow("id")), name = cursor.getString(cursor.getColumnIndexOrThrow("name")), formula = cursor.getString(cursor.getColumnIndexOrThrow("formula")), termins = cursor.getString(cursor.getColumnIndexOrThrow("termins")) ) dataList.add(formulaDataModel) }while (cursor.moveToNext()) } return dataList } fun readDatabaseFromAssets(context: Context):SQLiteDatabase { var stream: InputStream? = null val assetManager = context.assets stream = assetManager.open("formulas.db") //open("formulas.db") val file = File.createTempFile("prefix", "") val fileOutput = FileOutputStream(file) val buffer = ByteArray(1024) var size: Int = stream.read(buffer) while (size > 0) { fileOutput.write(buffer, 0, size) size = stream.read(buffer) } fileOutput.flush() fileOutput.close() stream?.close() var db: SQLiteDatabase = SQLiteDatabase.openDatabase(file.absolutePath, null, SQLiteDatabase.OPEN_READWRITE) return db } companion object { private const val DATABASE_VERSION:Int = 1 private const val DATABASE_NAME:String = "formulas.db" } class FormulaDataModel(var id: Int = 0, var name:String = "", var formula: String = "", var termins:String = "") class TerminDataModel(var id: Int = 0, var name:String = "", var unit:String = "", var description:String = "", var formulas:String = "") //class NamesDataModel(var id:Int = 0, var names:String = "") }
0
Kotlin
0
0
e6fe807d239600ffb36647175ea99f9bc328e79d
4,368
PocketPhysic
The Unlicense
app/src/main/java/com/sweetheart/android/ui/weather/WeatherActivity.kt
Ciel-oss
318,430,471
false
null
package com.sweetheart.android.ui.weather import android.content.Context import android.graphics.Color import android.os.Build import androidx.appcompat.app.AppCompatActivity import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.inputmethod.InputMethodManager import android.widget.ImageView import android.widget.TextView import android.widget.Toast import androidx.annotation.RequiresApi import androidx.core.view.GravityCompat import androidx.drawerlayout.widget.DrawerLayout import androidx.lifecycle.Observer import androidx.lifecycle.ViewModelProvider import com.sweetheart.android.R import com.sweetheart.android.logic.model.Weather import com.sweetheart.android.logic.model.getSky import kotlinx.android.synthetic.main.activity_weather.* import kotlinx.android.synthetic.main.astro.* import kotlinx.android.synthetic.main.forecast.* import kotlinx.android.synthetic.main.life_index.* import kotlinx.android.synthetic.main.now.* import kotlinx.android.synthetic.main.professional_data.* import java.text.SimpleDateFormat import java.util.* class WeatherActivity : AppCompatActivity() { val viewModel by lazy { ViewModelProvider(this).get(WeatherViewModel::class.java) } override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) //将背景图和状态栏融合到一起 val decorView = window.decorView decorView.systemUiVisibility = View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN or View.SYSTEM_UI_FLAG_LAYOUT_STABLE if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { window.statusBarColor = Color.TRANSPARENT } setContentView(R.layout.activity_weather) if (viewModel.locationLng.isEmpty()){ viewModel.locationLng = intent.getStringExtra("location_lng") ?: "" } if (viewModel.locationLat.isEmpty()){ viewModel.locationLat = intent.getStringExtra("location_lat") ?: "" } if (viewModel.placeName.isEmpty()){ viewModel.placeName = intent.getStringExtra("place_name") ?: "" } viewModel.weatherLiveData.observe(this, Observer { result -> val weather = result.getOrNull() if (weather != null){ showWeatherInfo(weather) }else{ Toast.makeText(this,"无法成功获取天气信息",Toast.LENGTH_SHORT).show() result.exceptionOrNull()?.printStackTrace() } swipeRefresh.isRefreshing = false }) swipeRefresh.setColorSchemeResources(R.color.colorPrimary) refreshWeather() swipeRefresh.setOnRefreshListener { refreshWeather() } navBtn.setOnClickListener { drawerLayout.openDrawer(GravityCompat.START) } drawerLayout.addDrawerListener(object : DrawerLayout.DrawerListener { override fun onDrawerSlide(drawerView: View, slideOffset: Float) { } override fun onDrawerOpened(drawerView: View) { } override fun onDrawerClosed(drawerView: View) { //当滑动菜单被隐藏时,同时隐藏输入法 val manager = getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager manager.hideSoftInputFromWindow(drawerView.windowToken, InputMethodManager.HIDE_NOT_ALWAYS) } override fun onDrawerStateChanged(newState: Int) { } }) } fun refreshWeather(){ viewModel.refreshWeather(viewModel.locationLng,viewModel.locationLat) swipeRefresh.isRefreshing = true } //从Weather对象中获取数据,显示到相应的控件上 private fun showWeatherInfo(weather: Weather){ placeName.text = viewModel.placeName val realtime = weather.realtime val daily = weather.daily //填充now.xml布局中的数据 val currentTempText = "${realtime.temperature.toInt()} ℃" currentTemp.text = currentTempText val currentApparentTempText = "体感温度 ${realtime.apparent_temperature.toInt()} ℃" currentApparentTemp.text = currentApparentTempText currentSky.text = getSky(realtime.skycon).info val currentPM25Text = "空气指数 ${realtime.airQuality.aqi.chn.toInt()} ${realtime.airQuality.description.chn}" currentAQI.text = currentPM25Text nowLayout.setBackgroundResource(getSky(realtime.skycon).bg) //填充forecast.xml布局中的数据 forecastLayout.removeAllViews() val days = daily.skycon.size for (i in 0 until days){ val skycon = daily.skycon[i] val temperature = daily.temperature[i] val view = LayoutInflater.from(this).inflate(R.layout.forecast_item,forecastLayout,false) val dateInfo = view.findViewById(R.id.dateInfo) as TextView val skyIcon = view.findViewById<ImageView>(R.id.skyIcon) val skyInfo = view.findViewById<TextView>(R.id.skyInfo) val temperatureInfo = view.findViewById<TextView>(R.id.temperatureInfo) val simpleDateFormat = SimpleDateFormat("yyyy-MM-dd",Locale.getDefault()) dateInfo.text = simpleDateFormat.format(skycon.date) val sky = getSky(skycon.value) skyIcon.setImageResource(sky.icon) skyInfo.text = sky.info val tempText = "${temperature.min.toInt()} ~ ${temperature.max.toInt()} ℃" temperatureInfo.text = tempText forecastLayout.addView(view) } //填充professional_data.xml布局中的数据 val pressure = "${daily.pressure[0].avg.toInt()/100} 百帕" pressureText.text = pressure val cloudrate = "${(daily.cloudrate[0].avg*100).toInt()}%" cloudrateText.text = cloudrate val visibility = "${daily.visibility[0].avg} 公里" visibilityText.text = visibility val humidity = "${(daily.humidity[0].avg*100).toInt()}%" humidityText.text = humidity val precipitation = "${daily.precipitation[0].avg.toInt()} mm/h" precipitationText.text = precipitation val dswrf = "${daily.dswrf[0].avg} W/㎡" dswrfText.text = dswrf //填充life_index.xml布局中的数据 val lifeIndex = daily.lifeIndex coldRiskText.text = lifeIndex.coldRisk[0].desc dressingText.text = lifeIndex.dressing[0].desc ultravioletText.text = lifeIndex.ultraviolet[0].desc carWashingText.text = lifeIndex.carWashing[0].desc //填充astro.xml布局中的数据 sunriseText.text = daily.astro[0].sunrise.time sunsetText.text = daily.astro[0].sunset.time weatherLayout.visibility = View.VISIBLE } }
0
Kotlin
0
0
07df717b2e8e0021626d8286f8339c2833a4b91c
6,604
Sweetheart
Apache License 2.0
app/src/main/java/com/weatherknow/android/logic/model/Weather.kt
tian-g2333
285,995,913
false
null
package com.weatherknow.android.logic.model data class Weather(val realtime: RealtimeResponse.Realtime, val daily:DailyResponse.Daily)
0
Kotlin
0
0
fff89d2d83a59691e13869a743dad5721feecf93
135
WeatherKnow
Apache License 2.0
data/src/main/java/com/sedsoftware/yaptalker/data/mappers/UserProfileMapper.kt
alerm-sml
123,927,915
true
{"Kotlin": 509954, "IDL": 1260, "Shell": 1229, "Prolog": 939, "Java": 823, "CSS": 50}
package com.sedsoftware.yaptalker.data.mappers import com.sedsoftware.yaptalker.data.parsed.UserProfileParsed import com.sedsoftware.yaptalker.domain.entity.BaseEntity import com.sedsoftware.yaptalker.domain.entity.base.UserProfile import io.reactivex.functions.Function import javax.inject.Inject /** * Mapper class used to transform parsed user profile from the data layer into BaseEntity in the domain layer. */ class UserProfileMapper @Inject constructor() : Function<UserProfileParsed, BaseEntity> { override fun apply(from: UserProfileParsed): BaseEntity = UserProfile( nickname = from.nickname, avatar = from.avatar, photo = from.photo, group = from.group, status = from.status, uq = from.uq.toInt(), signature = from.signature, rewards = from.rewards, registerDate = from.registerDate, timeZone = from.timeZone, website = from.website, birthDate = from.birthDate, location = from.location, interests = from.interests, sex = from.sex, messagesCount = from.messagesCount, messsagesPerDay = from.messsagesPerDay, bayans = from.bayans, todayTopics = from.todayTopics, email = from.email, icq = from.icq ) }
0
Kotlin
0
0
6c06171d2af44b0bb9b7809221b2f594d2354102
1,252
YapTalker
Apache License 2.0
immutable-arrays/transformations-to-standard-collections/src/test/kotlin/com/danrusu/pods4k/immutableArrays/TransformationsToListTest.kt
daniel-rusu
774,714,857
false
{"Kotlin": 620287}
package com.danrusu.pods4k.immutableArrays import org.junit.jupiter.api.Test import strikt.api.expectThat import strikt.assertions.isEqualTo class TransformationsToListTest { @Test fun `toList validation`() { // empty with(emptyImmutableArray<String>()) { expectThat(toList()).isEqualTo(emptyList()) } with(emptyImmutableIntArray()) { expectThat(toList()).isEqualTo(emptyList()) } // 1 element with(immutableArrayOf("Bob")) { expectThat(toList()) .isEqualTo(listOf("Bob")) } with(immutableArrayOf(7)) { expectThat(toList()) .isEqualTo(listOf(7)) } // multiple elements with(immutableArrayOf("Bob", "Jill", "Jane")) { expectThat(toList()) .isEqualTo(listOf("Bob", "Jill", "Jane")) } with(immutableArrayOf(7, 15, 100)) { expectThat(toList()) .isEqualTo(listOf(7, 15, 100)) } } @Test fun `toMutableList validation`() { // empty with(emptyImmutableArray<String>()) { expectThat(toMutableList()).isEqualTo(mutableListOf()) } with(emptyImmutableIntArray()) { expectThat(toMutableList()).isEqualTo(mutableListOf()) } // 1 element with(immutableArrayOf("Bob")) { expectThat(toMutableList()) .isEqualTo(mutableListOf("Bob")) } with(immutableArrayOf(7)) { expectThat(toMutableList()) .isEqualTo(mutableListOf(7)) } // multiple elements with(immutableArrayOf("Bob", "Jill", "Jane")) { expectThat(toMutableList()) .isEqualTo(mutableListOf("Bob", "Jill", "Jane")) } with(immutableArrayOf(7, 15, 100)) { expectThat(toMutableList()) .isEqualTo(mutableListOf(7, 15, 100)) } } }
0
Kotlin
0
3
c106c7d9570035edbd3f0913501110db32d62c32
2,001
pods4k
Apache License 2.0
app/src/main/java/org/rakulee/buup/fragments/jobseeker/JobSeekerOnBoarding3.kt
rakuleethomas
392,158,334
false
null
package org.rakulee.buup.fragments.jobseeker import android.content.Context import android.content.Intent import android.content.pm.PackageManager import android.os.Bundle import androidx.fragment.app.Fragment import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.Toast import androidx.core.content.ContextCompat import androidx.databinding.DataBindingUtil import androidx.navigation.NavDirections import androidx.navigation.fragment.findNavController import com.google.android.gms.location.* import dagger.hilt.android.AndroidEntryPoint import org.rakulee.buup.R import org.rakulee.buup.databinding.FragmentJobSeekerOnBoarding3Binding import org.rakulee.buup.screens.LoginActivity import org.rakulee.buup.screens.PartTimeJobSeekerActivity import java.util.jar.Manifest // TODO: Rename parameter arguments, choose names that match // the fragment initialization parameters, e.g. ARG_ITEM_NUMBER private const val ARG_PARAM1 = "param1" private const val ARG_PARAM2 = "param2" /** * A simple [Fragment] subclass. * Use the [JobSeekerOnBoarding3.newInstance] factory method to * create an instance of this fragment. */ @AndroidEntryPoint class JobSeekerOnBoarding3 : Fragment() { // TODO: Rename and change types of parameters private var param1: String? = null private var param2: String? = null private val permissions = arrayOf( android.Manifest.permission.ACCESS_FINE_LOCATION, android.Manifest.permission.ACCESS_COARSE_LOCATION ) lateinit var binding : FragmentJobSeekerOnBoarding3Binding override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) arguments?.let { param1 = it.getString(ARG_PARAM1) param2 = it.getString(ARG_PARAM2) } } override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View? { // Inflate the layout for this fragment binding = DataBindingUtil.inflate(inflater, R.layout.fragment_job_seeker_on_boarding3, container, false) binding.lifecycleOwner = this binding.onBoarding3 = this // binding.btnDone.setOnClickListener{ // val intent = Intent(context, PartTimeJobSeekerActivity::class.java) // startActivity(intent) // activity?.finish() // } binding.fab.setOnClickListener{ val direction : NavDirections = JobSeekerOnBoarding3Directions.actionJobSeekerOnBoarding3ToJobSeekerOnBoarding4() findNavController().navigate(direction) } if (!checkPermission(permissions)){ requestPermissions(permissions, REQUEST_CODE_PERMISSION) } return binding.root } private fun checkPermission(permission: Array<String>) : Boolean { return permissions.all { ContextCompat.checkSelfPermission(requireContext(), it) == PackageManager.PERMISSION_GRANTED } } companion object { const val REQUEST_CODE_PERMISSION = 1001 /** * Use this factory method to create a new instance of * this fragment using the provided parameters. * * @param param1 Parameter 1. * @param param2 Parameter 2. * @return A new instance of fragment JobSeekerOnBoarding3. */ // TODO: Rename and change types and number of parameters @JvmStatic fun newInstance(param1: String, param2: String) = JobSeekerOnBoarding3().apply { arguments = Bundle().apply { putString(ARG_PARAM1, param1) putString(ARG_PARAM2, param2) } } } }
0
Kotlin
0
1
25cd37e90bd8539f1735b2cc8f28f27b62471973
3,776
Bu-up
MIT License
airin-gradle-android/src/main/kotlin/io/morfly/airin/module/JvmLibraryModule.kt
Morfly
368,910,388
false
{"Kotlin": 118695}
/* * Copyright 2023 <NAME> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.morfly.airin.module import io.morfly.airin.ModuleComponent import io.morfly.airin.GradleModule import io.morfly.airin.ModuleContext import org.gradle.api.Project abstract class JvmLibraryModule : ModuleComponent() { override fun canProcess(project: Project): Boolean { return false } override fun ModuleContext.onInvoke(module: GradleModule) { } }
1
Kotlin
3
32
710d4dc95d4d61a55d8ce027f1442979125b4b47
975
airin
Apache License 2.0
packages/turbo/android/src/main/java/com/reactnativeturbowebview/RNSessionManager.kt
software-mansion-labs
507,842,137
false
{"TypeScript": 35846, "Kotlin": 33452, "EJS": 27248, "CSS": 17101, "Java": 15832, "Swift": 13055, "JavaScript": 7946, "C++": 7313, "Objective-C++": 4456, "Objective-C": 3859, "Ruby": 3057, "Starlark": 602, "CMake": 283, "C": 103}
package com.reactnativeturbowebview import com.facebook.react.bridge.ReactApplicationContext object RNSessionManager { private val sessions: MutableMap<String, RNSession> = mutableMapOf() fun findOrCreateSession( reactContext: ReactApplicationContext, sessionHandle: String, applicationNameForUserAgent: String? = null ): RNSession = sessions.getOrPut(sessionHandle) { RNSession(reactContext, sessionHandle, applicationNameForUserAgent) } }
9
TypeScript
9
72
e5a61f5ada83c7cdae1e3ce7b56411cda6c0bb8f
470
react-native-turbo-demo
MIT License
src/main/kotlin/com/hraps/ianserver/mapper/CardMapper.kt
HRan2004
509,540,442
false
{"Kotlin": 15689}
package com.hraps.ianserver.mapper import com.hraps.ianserver.entity.Card import org.apache.ibatis.annotations.Mapper import org.apache.ibatis.annotations.Select import org.apache.ibatis.annotations.Update @Mapper interface CardMapper: BaseMapper<Card> { @Select("SELECT * FROM card WHERE value = #{value} AND aid = #{aid}") fun selectByValueAndAid (value: String, aid: Int): List<Card> @Select("SELECT * FROM card WHERE aid = #{aid} ORDER BY id DESC") fun selectByAid (aid: Int): List<Card> @Update("UPDATE card SET status = #{status} WHERE id = #{id}") fun updateStatusById (id: Int, status: Int): Integer @Select("SELECT * FROM card WHERE value = #{value}") fun selectByValue(card: String): List<Card> }
0
Kotlin
0
0
b795b1f32f5bbfecc078e55f9bf594a69862318d
745
IAN-Server
Apache License 2.0
src/main/kotlin/org/gamekins/questtask/QuestTask.kt
jenkinsci
452,610,454
false
{"Kotlin": 914430, "JavaScript": 40463, "Java": 2405, "CSS": 1712, "HTML": 777}
/* * Copyright 2023 Gamekins 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 org.gamekins.questtask import hudson.model.Run import hudson.model.TaskListener import hudson.model.User import org.gamekins.GameUserProperty import org.gamekins.challenge.Challenge import org.gamekins.CustomAPI import org.gamekins.util.Constants /** * A [QuestTask] is a task with progress based on different gamification elements that Gamekins offers. * * @author Philipp Straubinger * @since 0.6 */ abstract class QuestTask(val numberGoal: Int) { val created = System.currentTimeMillis() var currentNumber: Int = 0 var solved: Long = 0 /** * Needed for [CustomAPI] */ var title: String? get() = toString() set(value) {} /** * Gets completed percentage of the progress of the [QuestTask]. */ fun getCompletedPercentage(): Int { val percentage = currentNumber.toDouble() / numberGoal.toDouble() * 100 return if (percentage > 100) 100 else percentage.toInt() } /** * Returns the score of the [QuestTask]. */ abstract fun getScore(): Int /** * Returns the number of solved challenges since a specific time (normally the creation time of the [QuestTask]. */ fun getSolvedChallengesOfUserSince( user: User, project: String, since: Long, type: Class<out Challenge> = Challenge::class.java ): ArrayList<Challenge> { val property = user.getProperty(GameUserProperty::class.java) if (property != null) { return ArrayList(property.getCompletedChallenges(project).filter { it.getSolved() >= since }.filterIsInstance(type)) } return arrayListOf() } /** * Returns the number of solved challenges since the last rejection. */ fun getSolvedChallengesOfUserSinceLastRejection(user: User, project: String, since: Long): ArrayList<Challenge> { val property = user.getProperty(GameUserProperty::class.java) val challenges = arrayListOf<Challenge>() if (property != null) { val rejectedChallenges = property.getRejectedChallenges(project) if (rejectedChallenges.isNotEmpty()) { val lastRejectedChallenge = rejectedChallenges.last().first challenges.addAll( property.getCompletedChallenges(project) .toList() .filter { it.getSolved() >= since } .filter { it.getSolved() >= lastRejectedChallenge.getSolved() }) } else { challenges.addAll(property.getCompletedChallenges(project).toList().filter { it.getSolved() >= since }) } } return challenges } /** * Checks whether the [QuestTask] is solved. */ abstract fun isSolved(parameters: Constants.Parameters, run: Run<*, *>, listener: TaskListener, user: User): Boolean /** * Returns the XML representation of the quest. */ abstract fun printToXML(indentation: String): String }
0
Kotlin
3
4
5ca3967af14b5e85b10a31fecf947967f644542f
3,605
gamekins-plugin
Apache License 2.0
kotlin/432.All O`one Data Structure(全 O(1) 的数据结构).kt
learningtheory
141,790,045
false
{"Python": 4025652, "C++": 1999023, "Java": 1995266, "JavaScript": 1990554, "C": 1979022, "Ruby": 1970980, "Scala": 1925110, "Kotlin": 1917691, "Go": 1898079, "Swift": 1827809, "HTML": 124958, "Shell": 7944}
/** <p>Implement a data structure supporting the following operations:</p> <p> <ol> <li>Inc(Key) - Inserts a new key <Key> with value 1. Or increments an existing key by 1. Key is guaranteed to be a <b>non-empty</b> string.</li> <li>Dec(Key) - If Key's value is 1, remove it from the data structure. Otherwise decrements an existing key by 1. If the key does not exist, this function does nothing. Key is guaranteed to be a <b>non-empty</b> string.</li> <li>GetMaxKey() - Returns one of the keys with maximal value. If no element exists, return an empty string <code>""</code>.</li> <li>GetMinKey() - Returns one of the keys with minimal value. If no element exists, return an empty string <code>""</code>.</li> </ol> </p> <p> Challenge: Perform all these in O(1) time complexity. </p><p>实现一个数据结构支持以下操作:</p> <ol> <li>Inc(key) - 插入一个新的值为 1 的 key。或者使一个存在的 key 增加一,保证 key 不为空字符串。</li> <li>Dec(key) - 如果这个 key 的值是 1,那么把他从数据结构中移除掉。否者使一个存在的 key 值减一。如果这个 key 不存在,这个函数不做任何事情。key 保证不为空字符串。</li> <li>GetMaxKey() - 返回 key 中值最大的任意一个。如果没有元素存在,返回一个空字符串<code>&quot;&quot;</code>。</li> <li>GetMinKey() - 返回 key 中值最小的任意一个。如果没有元素存在,返回一个空字符串<code>&quot;&quot;</code>。</li> </ol> <p>挑战:以 O(1) 的时间复杂度实现所有操作。</p> <p>实现一个数据结构支持以下操作:</p> <ol> <li>Inc(key) - 插入一个新的值为 1 的 key。或者使一个存在的 key 增加一,保证 key 不为空字符串。</li> <li>Dec(key) - 如果这个 key 的值是 1,那么把他从数据结构中移除掉。否者使一个存在的 key 值减一。如果这个 key 不存在,这个函数不做任何事情。key 保证不为空字符串。</li> <li>GetMaxKey() - 返回 key 中值最大的任意一个。如果没有元素存在,返回一个空字符串<code>&quot;&quot;</code>。</li> <li>GetMinKey() - 返回 key 中值最小的任意一个。如果没有元素存在,返回一个空字符串<code>&quot;&quot;</code>。</li> </ol> <p>挑战:以 O(1) 的时间复杂度实现所有操作。</p> **/ class AllOne() { /** Initialize your data structure here. */ /** Inserts a new key <Key> with value 1. Or increments an existing key by 1. */ fun inc(key: String) { } /** Decrements an existing key by 1. If Key's value is 1, remove it from the data structure. */ fun dec(key: String) { } /** Returns one of the keys with maximal value. */ fun getMaxKey(): String { } /** Returns one of the keys with Minimal value. */ fun getMinKey(): String { } } /** * Your AllOne object will be instantiated and called as such: * var obj = AllOne() * obj.inc(key) * obj.dec(key) * var param_3 = obj.getMaxKey() * var param_4 = obj.getMinKey() */
0
Python
1
3
6731e128be0fd3c0bdfe885c1a409ac54b929597
2,355
leetcode
MIT License
multisrc/src/main/java/eu/kanade/tachiyomi/multisrc/magapoke/WeeklyDto.kt
beerpiss
639,230,444
false
null
package eu.kanade.tachiyomi.multisrc.magapoke import kotlinx.serialization.Serializable @Serializable data class WeeklyDto( val title_id_list: List<Int>, val weekday_index: Int, val feature_title_id: Int, val bonus_point_title_id: List<Int>, val popular_title_id_list: List<Int>, val new_title_id_list: List<Int>, )
0
null
0
4
5fd484c0c7049bc0fc899c60aa8e3b7aabaebacb
342
tachiyomi-unofficial-extensions
Apache License 2.0
app/src/main/java/ua/glebm/smartwaste/domain/usecase/core/ResultSuspendUseCase.kt
glebushkaa
718,610,042
false
{"Kotlin": 241649}
package ua.glebm.smartwaste.domain.usecase.core import ua.glebm.smartwaste.session.api.SessionStatusHandler /** * Created by gle.bushkaa email([email protected]) on 10/26/2023 */ abstract class ResultSuspendUseCase<Type : Any, in Params : UseCase.Params>( private val useCaseLogger: UseCaseLogger, private val sessionStatusHandler: SessionStatusHandler ) : UseCase<Type, Params> { abstract suspend operator fun invoke(params: Params): Result<Type> @Suppress("TooGenericExceptionCaught") suspend fun <T, P> T.runCatching(block: suspend T.() -> P): Result<P> { return try { Result.success(block()) } catch (throwable: Throwable) { useCaseLogger.logException(javaClass.simpleName, throwable) sessionStatusHandler.validateException(throwable) Result.failure(throwable) } } }
0
Kotlin
0
1
be94eb8f216d5bfae8259611145511661f78ea4e
878
smart-waste-android
MIT License
src/main/kotlin/com/springKotlinAuthentication/demo/authentication/jwt/service/JwtServiceImpl.kt
Kenato254
854,587,987
false
{"Kotlin": 93453, "Shell": 1143}
package com.springKotlinAuthentication.demo.authentication.jwt.service import com.springKotlinAuthentication.demo.authentication.authorization.Role import com.springKotlinAuthentication.demo.authentication.constant.Constant import com.springKotlinAuthentication.demo.authentication.entity.User import com.springKotlinAuthentication.demo.authentication.exception.execeptions.ExpiredJwtException import com.springKotlinAuthentication.demo.authentication.jwt.config.JwtProperties import com.springKotlinAuthentication.demo.authentication.jwt.entity.Token import com.springKotlinAuthentication.demo.authentication.jwt.repository.TokenRepository import com.springKotlinAuthentication.demo.authentication.service.CustomUserDetailService import io.jsonwebtoken.Claims import io.jsonwebtoken.Jwts import io.jsonwebtoken.MalformedJwtException import io.jsonwebtoken.io.Decoders import io.jsonwebtoken.security.Keys import jakarta.servlet.http.HttpServletRequest import org.springframework.http.HttpHeaders import org.springframework.security.core.userdetails.UserDetails import org.springframework.stereotype.Service import org.springframework.transaction.annotation.Transactional import java.util.* import java.util.function.Function import javax.crypto.SecretKey @Service class JwtServiceImpl( private val jwtProperties: JwtProperties, private val tokenRepository: TokenRepository, private val customUserDetailService: CustomUserDetailService ) : JwtService { override val expiresIn: Long? get() = jwtProperties.jwtExpiration override val tokenType: String? get() = "Bearer" private val signingKey: SecretKey get() = Keys.hmacShaKeyFor(Decoders.BASE64.decode(jwtProperties.jwtSecret)) override fun generateToken( extraClaims: Map<String, Role?>, user: User ): String? { return buildToken(extraClaims, user, jwtProperties.jwtExpiration) } override fun generateRefreshToken( extraClaims: Map<String, Role?>, user: User ): String { return buildToken(extraClaims, user, jwtProperties.refreshTokenExpiration) } private fun buildToken( extraClaims: Map<String, Role?>?, user: User, expiration: Long ): String { return Jwts.builder() .header().add(mapOf("typ" to "Bearer")).and() .subject(user.email) .claim("name", user.getFullName()) .claim("id", user.id.toString()) .claims(extraClaims) .issuedAt(Date()) .expiration(Date(System.currentTimeMillis() + expiration)) .signWith(signingKey) .compact() } override fun isTokenValid(token: String): Boolean { return try { getClaimsFromToken(token) ?: throw MalformedJwtException(Constant.JWT_MALFORMED) true } catch (e: Exception) { false } } override fun isTokenExpired(token: String): Boolean { return extractExpiration(token)?.before(Date()) == true } override fun isTokenUserValid( userDetails: UserDetails, token: String ): Boolean { val username = extractUsername(token) ?: throw MalformedJwtException(Constant.JWT_MALFORMED) return username == userDetails.username } override fun <T> extractClaim( token: String, claimResolver: Function<Claims, T> ): T { val claims = getClaimsFromToken(token) ?: throw MalformedJwtException(Constant.JWT_MALFORMED) return claimResolver.apply(claims) } override fun getClaimsFromToken(token: String): Claims? { return try { Jwts.parser() .verifyWith(signingKey) .build() .parseSignedClaims(token) .payload } catch (e: Exception) { null } } override fun extractUsername(token: String): String? { return extractClaim(token) { it.subject } } override fun extractExpiration(token: String): Date? { return extractClaim(token) { it.expiration } } override fun extractJwtFromHeader(request: HttpServletRequest): String? { val bearerToken = request.getHeader(HttpHeaders.AUTHORIZATION) return if ( bearerToken != null && bearerToken.startsWith("Bearer ") ) { bearerToken.substring(7) } else { null } } override fun refreshToken(request: HttpServletRequest): String? { val userDetails = extractUserDetailFromRequest(request).first val token = extractUserDetailFromRequest(request).second val roles = (userDetails as User).role return if (isTokenUserValid(userDetails, token)) { generateToken(mapOf("roles" to roles), userDetails) } else { null } } @Transactional(readOnly = true) override fun extractUserDetailFromRequest( request: HttpServletRequest ): Pair<UserDetails, String> { val token = extractJwtFromHeader(request) ?: throw MalformedJwtException(Constant.JWT_MALFORMED) if (isTokenExpired(token)) { throw ExpiredJwtException(Constant.JWT_EXPIRED) } if (!isTokenValid(token)) { throw MalformedJwtException(Constant.JWT_MALFORMED) } val username = extractUsername(token) ?: throw MalformedJwtException(Constant.JWT_MALFORMED) val userDetails = customUserDetailService.loadUserByUsername(username) return Pair(userDetails, token) } @Transactional override fun saveRefreshToken(user: UserDetails, token: String) { val userEntity = customUserDetailService.loadUserByEmail(user.username) val tokenHash = Token.encryptToken(token) tokenRepository.save( Token(token = tokenHash, user = userEntity) ) } @Transactional override fun revokeAllTokenByUser(user: User) { val tokens = tokenRepository.findAllValidTokensByUser(user.id!!) tokens.forEach { token -> token.run { isRevoked = true } } tokenRepository.saveAll(tokens) } @Transactional(readOnly = true) override fun getTokenByUser(user: User): Token? { return tokenRepository.findFirstByUserAndIsExpiredFalse(user) } @Transactional(readOnly = true) override fun getAllTokensByUser(userId: UUID): List<Token> { return tokenRepository.findAllValidTokensByUser(userId) } }
0
Kotlin
0
0
463f79638fde7e6f9f9db27119b6d5a888ea37eb
6,611
spring-kotlin-authentication-demo
MIT License
game/src/main/java/com/reco1l/rimu/ui/views/ViewGroups.kt
Reco1I
730,791,679
false
{"Kotlin": 360557}
package com.reco1l.rimu.ui.views import android.view.View import android.view.ViewGroup import androidx.core.view.doOnAttach import com.reco1l.rimu.IWithContext import com.reco1l.rimu.MainContext import com.reco1l.rimu.ui.IScalable import com.reco1l.rimu.ui.IScalableWithDimensions import com.reco1l.rimu.ui.ISkinnable import com.reco1l.rimu.ui.ISkinnableWithRules import android.widget.LinearLayout as AndroidLinearLayout import androidx.constraintlayout.widget.ConstraintLayout as AndroidConstraintLayout // ConstraintLayout open class ConstraintLayout(override val ctx: MainContext) : AndroidConstraintLayout(ctx), IWithContext, ISkinnableWithRules<ConstraintLayout, ViewSkinningRules<ConstraintLayout>>, IScalableWithDimensions<ConstraintLayout, ViewDimensions<ConstraintLayout>> { override val dimensions by lazy { ViewDimensions<ConstraintLayout>() } override val skinningRules by lazy { ViewSkinningRules<ConstraintLayout>() } override fun onAttachedToWindow() { super.onAttachedToWindow() invalidateSkin() invalidateScale() } override fun onViewAdded(view: View) { super.onViewAdded(view) if (view is IWithContext && view is ISkinnable && view is IScalable) view.doOnAttach { view.invalidateScale() view.invalidateSkin() } } } // LinearLayout open class LinearLayout(override val ctx: MainContext) : AndroidLinearLayout(ctx), IWithContext, ISkinnableWithRules<LinearLayout, ViewSkinningRules<LinearLayout>>, IScalableWithDimensions<LinearLayout, ViewDimensions<LinearLayout>> { override val dimensions by lazy { ViewDimensions<LinearLayout>() } override val skinningRules by lazy { ViewSkinningRules<LinearLayout>() } override fun onAttachedToWindow() { super.onAttachedToWindow() invalidateSkin() invalidateScale() } override fun onViewAdded(view: View) { super.onViewAdded(view) if (view is IWithContext) view.doOnAttach { if (view is IScalable) view.invalidateScale() if (view is ISkinnable) view.invalidateSkin() } } }
0
Kotlin
1
3
611c6224060baeb242ecc2422449cdf1ba13b78a
2,227
rimu
Apache License 2.0
app/src/main/java/co/nimblehq/data/model/QuestionResponsesEntity.kt
minhnimble
295,922,281
false
{"Gemfile.lock": 1, "Gradle": 6, "Java Properties": 2, "YAML": 1, "Shell": 1, "Text": 1, "Ignore List": 3, "Batchfile": 1, "Markdown": 4, "Ruby": 2, "Proguard": 2, "XML": 90, "XSLT": 1, "JSON": 5, "Kotlin": 185, "INI": 1, "Java": 2}
package co.nimblehq.data.model import co.nimblehq.data.api.request.AnswerRequest import co.nimblehq.data.api.request.QuestionResponsesRequest data class QuestionResponsesEntity( val id: String, var answers: List<AnswerEntity> ) data class AnswerEntity( val id: String, var answer: String? = null ) fun QuestionResponsesEntity.toQuestionRequest() = QuestionResponsesRequest( id = id, answers = answers.toAnswerRequests() ) fun List<QuestionResponsesEntity>.toQuestionRequests() = this.map { it.toQuestionRequest() } fun AnswerEntity.toAnswerRequest() = AnswerRequest( id = id, answer = answer ) fun List<AnswerEntity>.toAnswerRequests() = this.map { it.toAnswerRequest() }
1
null
1
1
98266e2455f5f5c5f532830faab19402e56e71cc
711
internal-certification-surveys-android
MIT License
src/main/kotlin/br/com/zup/edu/pix/service/ListarChaveService.kt
tiagoalcantara
346,376,184
true
{"Kotlin": 70499, "Dockerfile": 164}
package br.com.zup.edu.pix.service import br.com.zup.edu.ListarChaveResponse import br.com.zup.edu.TipoChave import br.com.zup.edu.TipoConta import br.com.zup.edu.pix.exception.ObjetoNaoEncontradoException import br.com.zup.edu.pix.model.Chave import br.com.zup.edu.pix.repository.ChaveRepository import br.com.zup.edu.pix.validacoes.ValidUUID import com.google.protobuf.Timestamp import io.micronaut.validation.Validated import java.time.ZoneId import java.util.* import javax.inject.Inject import javax.inject.Singleton import javax.validation.constraints.NotBlank @Singleton @Validated class ListarChaveService( @Inject private val chaveRepository: ChaveRepository, ) { fun listar( @NotBlank @ValidUUID idCliente: String ): List<Chave> { return chaveRepository.findByIdCliente(UUID.fromString(idCliente)) } }
0
Kotlin
0
0
a41383eabbc8029f17f7c4ac1ac6320e7f8d2dbe
846
orange-talents-01-template-pix-keymanager-grpc
Apache License 2.0
src/test/java/leetcode/mergeintervals/SolutionTest.kt
thuytrinh
106,045,038
false
{"Gradle": 1, "Shell": 1, "Text": 1, "Ignore List": 1, "Batchfile": 1, "Markdown": 8, "Java Properties": 1, "Kotlin": 60, "Java": 40}
package leetcode.mergeintervals import leetcode.meetingrooms.Interval import org.amshove.kluent.shouldEqual import org.junit.Test class SolutionTest { @Test fun test() { Solution().merge(listOf( Interval(1, 3), Interval(2, 6), Interval(8, 10), Interval(15, 18) )).shouldEqual(listOf( Interval(1, 6), Interval(8, 10), Interval(15, 18) )) Solution().merge(listOf( Interval(1, 4), Interval(2, 3) )).shouldEqual(listOf( Interval(1, 4) )) Solution().merge(listOf( Interval(1, 3) )).shouldEqual(listOf( Interval(1, 3) )) } }
0
Kotlin
0
1
23da0286a88f855dcab1999bcd7174343ccc1164
659
algorithms
MIT License
feature/main/src/main/java/com/ku_stacks/ku_ring/main/setting/compose/components/ChevronIcon.kt
ku-ring
412,458,697
false
{"Kotlin": 664645}
package com.ku_stacks.ku_ring.main.setting.compose.components import androidx.compose.foundation.layout.size import androidx.compose.material.Icon import androidx.compose.runtime.Composable import androidx.compose.ui.Modifier import androidx.compose.ui.res.painterResource import androidx.compose.ui.unit.dp import com.ku_stacks.ku_ring.designsystem.kuringtheme.KuringTheme import com.ku_stacks.ku_ring.main.R @Composable internal fun ChevronIcon(modifier: Modifier = Modifier) { Icon( painter = painterResource(id = R.drawable.ic_chevron_v2), contentDescription = null, modifier = modifier.size(20.dp), tint = KuringTheme.colors.gray300, ) }
6
Kotlin
1
23
c9313594e274caad6400b419da1edd4f81784e28
684
KU-Ring-Android
Apache License 2.0
app/src/main/java/com/arun/cryptojuno/ui/viewmodel/CryptoViewModel.kt
Arun-08
564,830,122
false
null
package com.arun.cryptojuno.ui.viewmodel import androidx.lifecycle.LiveData import androidx.lifecycle.ViewModel import com.arun.cryptojuno.data.model.CryptoData import com.arun.cryptojuno.data.repository.CryptoRepo import com.arun.cryptojuno.ui.view.adapter.RecentTransactionAdapter import com.arun.cryptojuno.utils.AppResource class CryptoViewModel : ViewModel() { var pageState : Int = 0 lateinit var transactionAdapter : RecentTransactionAdapter var currentBalance : String = "0" fun makeRequest(): LiveData<AppResource<CryptoData>> { val repo = CryptoRepo() return if (pageState == 0) repo.requestEmptyState() else repo.requestValueState() } }
0
Kotlin
0
0
d55a9f3fed783ec91973cf631e619feb1c7ef2b5
690
CryptoJuno
Apache License 2.0
core/src/bara/game/input/InputManager.kt
thealexhoar
138,129,142
false
{"Kotlin": 59333, "Java": 17004, "GLSL": 555}
package bara.game.input class InputManager( val inputController: InputController = KeyboardController() ){ fun getXAxis(): Float { return inputController.getXAxis() } fun getYAxis(): Float { return inputController.getYAxis() } fun inputDown(binding: InputBinding): Boolean { return inputController.inputDown(binding) } fun inputUp(binding: InputBinding): Boolean { return inputController.inputUp(binding) } fun inputPressed(binding: InputBinding): Boolean { return inputController.inputPressed(binding) } fun inputReleased(binding: InputBinding): Boolean { return inputController.inputReleased(binding) } fun update() { inputController.update() } //TODO: add mouse input handling }
0
Kotlin
0
0
d8a4b66b6948e11bed3cb7138625ed0868e6c838
810
bara
MIT License
app/src/main/java/me/anon/controller/adapter/GardenActionAdapter.kt
7LPdWcaW
40,006,856
false
{"Java": 442948, "Kotlin": 228652}
package me.anon.controller.adapter import android.text.Html import android.text.TextUtils import android.text.format.DateFormat import android.view.Gravity import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.TextView import androidx.appcompat.widget.PopupMenu import androidx.recyclerview.widget.RecyclerView import me.anon.grow.R import me.anon.lib.TempUnit import me.anon.lib.ext.formatWhole import me.anon.lib.ext.getColor import me.anon.lib.ext.resolveColor import me.anon.model.* import me.anon.view.ActionHolder import java.util.* class GardenActionAdapter : RecyclerView.Adapter<ActionHolder>() { public var items: ArrayList<Action> = arrayListOf() set(values) { field.clear() values.asReversed().forEach { field.add(it) } notifyDataSetChanged() } private var dateFormat: java.text.DateFormat? = null private var timeFormat: java.text.DateFormat? = null private var tempUnit: TempUnit? = null public var editListener: (Action) -> Unit = {} public var deleteListener: (Action) -> Unit = {} override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ActionHolder { return ActionHolder(LayoutInflater.from(parent.context).inflate(R.layout.action_item, parent, false)) } override fun getItemCount(): Int = items.size override fun onBindViewHolder(holder: ActionHolder, position: Int) { val action = items[position] val tempUnit = tempUnit ?: TempUnit.getSelectedTemperatureUnit(holder.itemView.context).also { tempUnit = it } val dateFormat = dateFormat ?: DateFormat.getDateFormat(holder.itemView.context).also { dateFormat = it } val timeFormat = timeFormat ?: DateFormat.getTimeFormat(holder.itemView.context).also { timeFormat = it } var dateDay: TextView = holder.dateDay // plant date & stage val actionDate = Date(action.date) val actionCalendar = GregorianCalendar.getInstance() actionCalendar.time = actionDate val fullDateStr = dateFormat.format(actionDate) + " " + timeFormat.format(actionDate) val dateDayStr = actionCalendar.get(Calendar.DAY_OF_MONTH).toString() + " " + actionCalendar.getDisplayName(Calendar.MONTH, Calendar.SHORT, Locale.getDefault()) var lastDateStr = "" if (position - 1 >= 0) { val lastActionDate = Date(items[position - 1].date) val lastActionCalendar = GregorianCalendar.getInstance() lastActionCalendar.time = lastActionDate lastDateStr = lastActionCalendar.get(Calendar.DAY_OF_MONTH).toString() + " " + lastActionCalendar.getDisplayName(Calendar.MONTH, Calendar.SHORT, Locale.getDefault()) } holder.card.setCardBackgroundColor(R.attr.colorSurface.resolveColor(holder.itemView.context)) holder.fullDate.text = Html.fromHtml(fullDateStr) var summary = "" when (action) { is TemperatureChange -> { holder.name.setText(R.string.temperature_title) summary += TempUnit.CELCIUS.to(tempUnit, action.temp).formatWhole() + "°" + tempUnit.label holder.card.setCardBackgroundColor(-0x654c6225) } is HumidityChange -> { holder.name.setText(R.string.humidity) summary += action.humidity?.formatWhole() + "%" holder.card.setCardBackgroundColor(R.color.light_blue.getColor(holder.itemView.context)) } is NoteAction -> { holder.name.setText(R.string.note) holder.card.setCardBackgroundColor(R.color.light_grey.getColor(holder.itemView.context)) } is LightingChange -> { holder.name.setText(R.string.lighting_title) holder.card.setCardBackgroundColor(R.color.light_yellow.getColor(holder.itemView.context)) summary += "<b>" + holder.itemView.context.getString(R.string.lights_on) + ":</b> " summary += action.on + "<br/>" summary += "<b>" + holder.itemView.context.getString(R.string.lights_off) + ":</b> " summary += action.off } } if (action.notes?.isNotEmpty() == true) { summary += if (summary.isNotEmpty()) "<br/><br/>" else "" summary += action.notes } if (summary.endsWith("<br/>")) { summary = summary.substring(0, summary.length - "<br/>".length) } if (!TextUtils.isEmpty(summary)) { holder.summary.text = Html.fromHtml(summary) holder.summary.visibility = View.VISIBLE } holder.overflow.visibility = View.VISIBLE holder.overflow.setOnClickListener(View.OnClickListener { v -> val menu = PopupMenu(v.context, v, Gravity.BOTTOM) menu.inflate(R.menu.event_overflow) menu.menu.removeItem(R.id.duplicate) menu.menu.removeItem(R.id.copy) if (action is LightingChange) { menu.menu.removeItem(R.id.edit) } menu.setOnMenuItemClickListener(PopupMenu.OnMenuItemClickListener { item -> when (item.itemId) { R.id.edit -> { editListener(action) return@OnMenuItemClickListener true } R.id.delete -> { deleteListener(action) return@OnMenuItemClickListener true } } false }) menu.show() }) if (!lastDateStr.equals(dateDayStr, ignoreCase = true)) { dateDay.text = Html.fromHtml(dateDayStr) dateDay.visibility = View.VISIBLE } else { dateDay.visibility = View.GONE } } }
21
Java
31
147
61dea1bd9c5d618b5530725d817c30b20b267959
5,102
GrowTracker-Android
Apache License 2.0
rxpermission_sample/src/main/java/com/rxpermission_sample/MainActivity.kt
HaowenLee
88,925,044
false
null
package com.rxpermission_sample import android.Manifest import android.app.Activity import android.os.Bundle import android.util.Log import com.rxpermission.RxPermission import kotlinx.android.synthetic.main.activity_main.* class MainActivity : Activity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) btnRequestPermission.setOnClickListener { requestPermission() } } private fun requestPermission() { RxPermission(this) .request(Manifest.permission.RECORD_AUDIO, Manifest.permission.WRITE_EXTERNAL_STORAGE) .subscribe { granted -> if (granted) { Log.e("Rx", "granted") } else { Log.e("Rx", "not granted") } } } }
0
Kotlin
0
3
a6e2e8fa4eab83ba8c66a60ee52ae1b979cec903
925
RxPermission
Apache License 2.0
jtextadventure/src/main/java/ro/dobrescuandrei/jtextadventure/IConsoleEmulator.kt
andob
238,633,448
false
null
package ro.dobrescuandrei.jtextadventure interface IConsoleEmulator { fun write(message : String) fun promptButtons(vararg buttons : String) fun read() : String fun dispose() }
0
null
0
2
9c177fc4d8d5d2049d4326df2436e2b9db8e6aa0
196
JTextAdventure
Apache License 2.0
weather-app/src/androidTest/java/org/rcgonzalezf/weather/espresso/navigation/WeatherListUi.kt
rcgonzalezf
43,210,997
false
{"Java": 139401, "Kotlin": 114455}
package org.rcgonzalezf.weather.espresso.navigation import androidx.test.espresso.Espresso import androidx.test.espresso.Espresso.onIdle import androidx.test.espresso.Espresso.onView import androidx.test.espresso.action.ViewActions import androidx.test.espresso.assertion.ViewAssertions.matches import androidx.test.espresso.matcher.ViewMatchers import androidx.test.espresso.matcher.ViewMatchers.hasDescendant import androidx.test.espresso.matcher.ViewMatchers.withId import androidx.test.espresso.matcher.ViewMatchers.withText import org.hamcrest.Matchers import org.rcgonzalezf.weather.espresso.utils.RecyclerViewMatcher import rcgonzalezf.org.weather.R class WeatherListUi { class Navigations { internal fun openDialog() { val floatingActionButton = Espresso.onView( Matchers.allOf( ViewMatchers.withId(R.id.main_fab), childAtPosition( Matchers.allOf(ViewMatchers.withId(R.id.content), childAtPosition( ViewMatchers.withId(R.id.drawer_layout), 0)), 3), ViewMatchers.isDisplayed())) floatingActionButton.perform(ViewActions.click()) } } class Verifications { internal fun checkWeatherResultCity(expectedCity: String) { Thread.sleep(1000) onView(withId(R.id.main_recycler_view)) onView(RecyclerViewMatcher(R.id.main_recycler_view).atPosition(1)) .check(matches(hasDescendant(withText(expectedCity)))) } } }
19
null
1
1
8302404110d044845412dff658d172991768350a
1,761
weather-app-demo
MIT License
networkmodule/src/main/java/com/test/networkmodule/exceptions/SDKNotInitializedException.kt
NayaneshGupte
196,730,583
false
null
package com.test.networkmodule.exceptions class SDKNotInitializedException(message: String) : RuntimeException(message)
1
null
1
1
077764040c04650245e221ec434539239dccf53c
121
MVVM-Demo
Apache License 2.0
rsocket-transport-netty/src/main/kotlin/io/rsocket/kotlin/transport/netty/server/WebsocketServerTransport.kt
mostroverkhov
190,571,918
true
{"Kotlin": 445206, "Shell": 894}
/* * Copyright 2015-2018 the original author or authors. * * 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.rsocket.android.transport.netty.server import io.reactivex.Single import io.rsocket.android.transport.ServerTransport import io.rsocket.android.transport.TransportHeaderAware import io.rsocket.android.transport.netty.WebsocketDuplexConnection import io.rsocket.android.transport.netty.toSingle import reactor.ipc.netty.http.server.HttpServer class WebsocketServerTransport private constructor(internal var server: HttpServer) : ServerTransport<NettyContextCloseable>, TransportHeaderAware { private var transportHeaders: () -> Map<String, String> = { emptyMap() } override fun start(acceptor: ServerTransport.ConnectionAcceptor) : Single<NettyContextCloseable> { return server .newHandler { _, response -> transportHeaders() .forEach { name, value -> response.addHeader(name, value) } response.sendWebsocket { inbound, outbound -> val connection = WebsocketDuplexConnection( inbound, outbound, inbound.context()) acceptor(connection).subscribe() outbound.neverComplete() } }.toSingle().map { NettyContextCloseable(it) } } override fun setTransportHeaders(transportHeaders: () -> Map<String, String>) { this.transportHeaders = transportHeaders } companion object { fun create(bindAddress: String, port: Int): WebsocketServerTransport { val httpServer = HttpServer.create(bindAddress, port) return create(httpServer) } fun create(port: Int): WebsocketServerTransport { val httpServer = HttpServer.create(port) return create(httpServer) } fun create(server: HttpServer): WebsocketServerTransport { return WebsocketServerTransport(server) } } }
0
Kotlin
0
0
b0759755c09fb45de64b0227bc2f47f56ec4b40e
2,693
rsocket-kotlin
Apache License 2.0
android/app/src/main/java/com/androidpi/app/fragment/VideoFragment.kt
epicmars
109,362,171
false
{"Java": 552905, "Kotlin": 240657, "JavaScript": 236312, "HTML": 30295, "CSS": 14348, "CMake": 1715, "C++": 263}
package com.androidpi.app.fragment import android.app.Activity import android.content.Context import android.media.AudioManager import android.os.Bundle import android.support.v4.media.MediaDescriptionCompat import android.support.v4.media.session.MediaSessionCompat import android.view.View import com.androidpi.app.R import com.androidpi.app.base.ui.BaseFragment import com.androidpi.app.base.ui.BindLayout import com.androidpi.app.databinding.FragmentVideoBinding import com.androidpi.app.libmedia.MediaCatalog import com.androidpi.app.libmedia.PlayerHolder import com.androidpi.app.libmedia.PlayerState import com.google.android.exoplayer2.Player import com.google.android.exoplayer2.ext.mediasession.MediaSessionConnector import com.google.android.exoplayer2.ext.mediasession.TimelineQueueNavigator import com.google.android.exoplayer2.ui.PlayerView import org.jetbrains.anko.AnkoLogger /** * Created by jastrelax on 2018/8/19. */ @BindLayout(R.layout.fragment_video) class VideoFragment : BaseFragment<FragmentVideoBinding>(), AnkoLogger { private val mediaSession: MediaSessionCompat by lazy { createMediaSession() } private val mediaSessionConnector: MediaSessionConnector by lazy { createMediaSessionConnector() } private val playerState by lazy { PlayerState() } private lateinit var playerHolder: PlayerHolder lateinit var playerView: PlayerView init { retainInstance = true } // Android lifecycle hooks. override fun onAttach(context: Context?) { super.onAttach(context) // While the user is in the app, the volume controls should adjust the music volume. (context as Activity).volumeControlStream = AudioManager.STREAM_MUSIC } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) view.viewTreeObserver.addOnWindowFocusChangeListener { hasFocus -> if (hasFocus) { hideSystemUI() } } playerView = binding.playerView createMediaSession() createPlayer() } override fun onStart() { super.onStart() startPlayer() activateMediaSession() } override fun onStop() { super.onStop() stopPlayer() deactivateMediaSession() } override fun onDestroy() { super.onDestroy() releasePlayer() releaseMediaSession() } // MediaSession related functions. private fun createMediaSession(): MediaSessionCompat = MediaSessionCompat(context, context?.packageName) private fun createMediaSessionConnector(): MediaSessionConnector = MediaSessionConnector(mediaSession).apply { // If QueueNavigator isn't set, then mediaSessionConnector will not handle following // MediaSession actions (and they won't show up in the minimized PIP activity): // [ACTION_SKIP_PREVIOUS], [ACTION_SKIP_NEXT], [ACTION_SKIP_TO_QUEUE_ITEM] setQueueNavigator(object : TimelineQueueNavigator(mediaSession) { override fun getMediaDescription(player: Player?, windowIndex: Int): MediaDescriptionCompat { return MediaCatalog[windowIndex] } }) } // MediaSession related functions. private fun activateMediaSession() { // Note: do not pass a null to the 3rd param below, it will cause a NullPointerException. // To pass Kotlin arguments to Java varargs, use the Kotlin spread operator `*`. mediaSessionConnector.setPlayer(playerHolder.audioFocusPlayer, null) mediaSession.isActive = true } private fun deactivateMediaSession() { mediaSessionConnector.setPlayer(null, null) mediaSession.isActive = false } private fun releaseMediaSession() { mediaSession.release() } // ExoPlayer related functions. private fun createPlayer() { playerHolder = PlayerHolder(context!!, playerState, playerView) } private fun startPlayer() { playerHolder.start() } private fun stopPlayer() { playerHolder.stop() } private fun releasePlayer() { playerHolder.release() } // // Picture in Picture related functions. // override fun onUserLeaveHint() { // if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { // activity?.enterPictureInPictureMode( // with(PictureInPictureParams.Builder()) { // val width = 16 // val height = 9 // setAspectRatio(Rational(width, height)) // build() // }) // } // } // // override fun onPictureInPictureModeChanged(isInPictureInPictureMode: Boolean, // newConfig: Configuration?) { // playerView.useController = !isInPictureInPictureMode // } private fun hideSystemUI() { // Enables regular immersive mode. // For "lean back" mode, remove SYSTEM_UI_FLAG_IMMERSIVE. // Or for "sticky immersive," replace it with SYSTEM_UI_FLAG_IMMERSIVE_STICKY val decorView = activity?.window?.decorView decorView?.systemUiVisibility = ( View.SYSTEM_UI_FLAG_IMMERSIVE // Set the content to appear under the system bars so that the // content doesn't resize when the system bars reset and show. or View.SYSTEM_UI_FLAG_LAYOUT_STABLE or View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION or View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN // Hide the nav bar and status bar or View.SYSTEM_UI_FLAG_HIDE_NAVIGATION or View.SYSTEM_UI_FLAG_FULLSCREEN ) } // Shows the system bars by removing all the flags // except for the ones that make the content appear under the system bars. private fun showSystemUI() { val decorView = activity?.window?.decorView decorView?.systemUiVisibility = (View.SYSTEM_UI_FLAG_LAYOUT_STABLE or View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION or View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN) } companion object { fun newInstance(): VideoFragment { val args = Bundle() val fragment = VideoFragment() fragment.arguments = args return fragment } } }
1
null
1
1
10e3ed8af2321c042714e42a4aacf84d1ac99fc1
6,553
AndroidPi
MIT License
app/src/main/java/com/zheng/home/injection/module/NetworkModule.kt
dzzheng3
128,493,315
false
{"Gradle": 4, "JSON": 3, "Java Properties": 2, "Shell": 1, "Ignore List": 2, "Batchfile": 1, "Markdown": 1, "Proguard": 1, "XML": 14, "Kotlin": 53, "Java": 3}
package com.zheng.home.injection.module import android.content.Context import android.os.Build import android.support.annotation.RequiresApi import com.facebook.stetho.okhttp3.StethoInterceptor import com.google.gson.FieldNamingPolicy import com.google.gson.Gson import com.google.gson.GsonBuilder import com.readystatesoftware.chuck.ChuckInterceptor import com.zheng.home.BuildConfig import dagger.Module import dagger.Provides import okhttp3.Cache import okhttp3.OkHttpClient import okhttp3.logging.HttpLoggingInterceptor import retrofit2.Retrofit import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory import retrofit2.converter.scalars.ScalarsConverterFactory import timber.log.Timber import javax.inject.Singleton @Module class NetworkModule(private val context: Context) { var cacheSize: Long = 10 * 1024 * 1024 // 10 MB @RequiresApi(Build.VERSION_CODES.LOLLIPOP) var cache = Cache(context.codeCacheDir, cacheSize) @Provides @Singleton internal fun provideQuizRetrofit(okHttpClient: OkHttpClient): Retrofit { return Retrofit.Builder() .baseUrl(BuildConfig.QUIZ_API_URL) .client(okHttpClient) .addConverterFactory(ScalarsConverterFactory.create()) .addCallAdapterFactory(RxJava2CallAdapterFactory.create()) .build() } @Provides @Singleton internal fun provideOkHttpClient(httpLoggingInterceptor: HttpLoggingInterceptor, chuckInterceptor: ChuckInterceptor, stethoInterceptor: StethoInterceptor): OkHttpClient { return OkHttpClient.Builder() .addInterceptor(httpLoggingInterceptor) .addInterceptor(chuckInterceptor) .addNetworkInterceptor(stethoInterceptor) .cache(cache) .build() } @Provides @Singleton internal fun provideHttpLoggingInterceptor(): HttpLoggingInterceptor { return HttpLoggingInterceptor { message -> Timber.d(message) }.setLevel(HttpLoggingInterceptor.Level.BODY) } @Provides @Singleton internal fun provideChuckInterceptor(): ChuckInterceptor { return ChuckInterceptor(context) } @Provides @Singleton internal fun provideStetho(): StethoInterceptor { return StethoInterceptor() } @Provides @Singleton internal fun provideGson(): Gson { return GsonBuilder() .setDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'") .setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES) .create() } }
0
Kotlin
0
0
c11dbf778a4a76bc88dca7009adf61247f5a0bcc
2,683
mvp_quiz_kotlin
The Unlicense
viewpager/src/main/java/com/donfyy/viewpager/lazyloading/LazyMainActivity.kt
donfyy
229,222,253
false
{"Gradle": 28, "Java Properties": 2, "Shell": 2, "Text": 5, "Ignore List": 29, "Batchfile": 3, "Markdown": 30, "Proguard": 23, "Kotlin": 160, "XML": 299, "Java": 258, "INI": 3, "C": 20, "C++": 19, "JSON": 9, "AIDL": 1, "HTML": 50, "SCSS": 30, "Less": 30, "JavaScript": 99, "SVG": 3, "CSS": 2, "Protocol Buffer": 2}
package com.donfyy.viewpager.lazyloading import android.os.Bundle import androidx.appcompat.app.AppCompatActivity import androidx.viewpager.widget.ViewPager.OnPageChangeListener import com.donfyy.viewpager.R import com.google.android.material.bottomnavigation.BottomNavigationView import java.util.* class LazyMainActivity : AppCompatActivity() { private lateinit var mViewPager: androidx.viewpager.widget.ViewPager private lateinit var bottomNavigationView: BottomNavigationView override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main_lazy) mViewPager = findViewById(R.id.viewPager) bottomNavigationView = findViewById(R.id.bottomNavigationView) bottomNavigationView.setOnNavigationItemSelectedListener(onNavigationItemSelectedListener) val fragmentList = ArrayList<androidx.fragment.app.Fragment>() fragmentList.add(MyFragment.newInstance(1)) fragmentList.add(MyFragment.newInstance(2)) fragmentList.add(MyFragment.newInstance(3)) fragmentList.add(MyFragment.newInstance(4)) fragmentList.add(MyFragment.newInstance(5)) val adapter = MyFragmentPagerAdapter(supportFragmentManager, fragmentList) mViewPager.adapter = adapter mViewPager.offscreenPageLimit = 2 mViewPager.setOnPageChangeListener(viewpagerChangeListener) } private var viewpagerChangeListener: OnPageChangeListener = object : OnPageChangeListener { override fun onPageScrolled(i: Int, v: Float, i1: Int) {} override fun onPageSelected(i: Int) { var itemId = R.id.fragment_1 when (i) { 0 -> itemId = R.id.fragment_1 1 -> itemId = R.id.fragment_2 2 -> itemId = R.id.fragment_3 3 -> itemId = R.id.fragment_4 4 -> itemId = R.id.fragment_5 } bottomNavigationView.selectedItemId = itemId } override fun onPageScrollStateChanged(i: Int) {} } private var onNavigationItemSelectedListener = BottomNavigationView.OnNavigationItemSelectedListener { item -> when (item.itemId) { R.id.fragment_1 -> { mViewPager.setCurrentItem(0, true) return@OnNavigationItemSelectedListener true } R.id.fragment_2 -> { mViewPager.setCurrentItem(1, true) return@OnNavigationItemSelectedListener true } R.id.fragment_3 -> { mViewPager.setCurrentItem(2, true) return@OnNavigationItemSelectedListener true } R.id.fragment_4 -> { mViewPager.setCurrentItem(3, true) return@OnNavigationItemSelectedListener true } R.id.fragment_5 -> { mViewPager.setCurrentItem(4, true) return@OnNavigationItemSelectedListener true } } false } }
0
JavaScript
1
3
932ebabf9b38b6c403560532fc5328cd82902eeb
3,047
AndroidCrowds
Apache License 2.0
src/com/jovial/blog/model/DependencyManager.kt
zathras
73,012,336
false
{"Shell": 5, "Text": 3, "Ignore List": 3, "Git Attributes": 1, "EditorConfig": 1, "Markdown": 13, "JSON": 3, "Kotlin": 67, "Java": 19, "SVG": 16, "XML": 18, "CSS": 16, "JavaScript": 18, "Gradle": 3, "Java Properties": 2, "Batchfile": 1, "Proguard": 1, "JAR Manifest": 1, "HTML": 12}
package com.jovial.blog.model import com.jovial.util.JsonIO import java.io.* import java.util.* /** * A dependency manaager records the assets that each of the generated products depends on. This is done so that * we can avoid re-generating files needlessly. Images take a long time to re-generate. We also avoid * re-generating HTML files if there are no changes, so that the timestamp of the HTML file reflects when * the current version actually needed to be generated. * * Created by billf on 11/18/16. */ class DependencyManager (inputDir : File, dependencyFileName : String) { private val dependencyFile = File(inputDir, dependencyFileName) private var generatedAssets = mutableMapOf<File, AssetDependencies>() /** * Get the object that describes the things the provided generated asset depends on. */ fun get(asset: File) : AssetDependencies { assert(asset.path == asset.canonicalPath); val result = generatedAssets.get(asset) if (result != null) { return result } else { val v = AssetDependencies(asset) generatedAssets.put(asset, v) return v } } /** * Check to see if there is a dependencies object for the given asset, but if there isn't, * don't create one. */ fun check(asset: File) : AssetDependencies? { assert(asset.path == asset.canonicalPath); return generatedAssets.get(asset) } /** * Remove the given dependencies object, if it exists */ fun remove(asset: File) { generatedAssets.remove(asset) } /** * Read our state from dependencyFile, if it exists. If not, do nothing. */ fun read() { assert(generatedAssets.size == 0) if (dependencyFile.exists()) { val input = dependencyFile.bufferedReader() @Suppress("UNCHECKED_CAST") val json = JsonIO.readJSON(input) as HashMap<String, Any> input.close() if (json["version"] != "1.0") { throw IOException("Version mismatch: got ${json["version"]}") } @Suppress("UNCHECKED_CAST") val readAssets = json["generatedAssets"] as List<HashMap<String, Any>> for (readAsset in readAssets) { val a = AssetDependencies(readAsset) assert(a.generatedAsset.path == a.generatedAsset.canonicalPath); generatedAssets[a.generatedAsset] = a } } } /** * Write our state out to dependencyFile, for a permanent record. */ fun write() { val json = HashMap<Any, Any>() json["version"] = "1.0" json["generatedAssets"] = generatedAssets.values.map { it.asJsonValue() } val output = dependencyFile.bufferedWriter() JsonIO.writeJSON(output, json) output.close() } }
1
null
1
1
f3124403377480bfed27e86b645f445dccc86445
2,912
corpsblog
MIT License
app/src/main/java/ws/idroid/worldstatus/ui/overview/DashboardViewModel.kt
mabualzait
250,814,252
false
null
package ws.idroid.worldstatus.ui.overview import androidx.lifecycle.LiveData import androidx.lifecycle.MutableLiveData import io.reactivex.Observable import io.reactivex.functions.Function3 import ws.idroid.worldstatus.R import ws.idroid.worldstatus.data.model.CovidDaily import ws.idroid.worldstatus.data.model.CovidDetail import ws.idroid.worldstatus.data.model.CovidOverview import ws.idroid.worldstatus.data.repository.Repository import ws.idroid.worldstatus.data.repository.Result import ws.idroid.worldstatus.ui.adapter.viewholders.ErrorStateItem import ws.idroid.worldstatus.ui.adapter.viewholders.LoadingStateItem import ws.idroid.worldstatus.ui.adapter.viewholders.TextItem import ws.idroid.worldstatus.ui.base.BaseViewItem import ws.idroid.worldstatus.ui.base.BaseViewModel import ws.idroid.worldstatus.util.Constant import ws.idroid.worldstatus.util.SingleLiveEvent import ws.idroid.worldstatus.util.ext.addTo import ws.idroid.worldstatus.util.rx.SchedulerProvider /** * <NAME> */ class DashboardViewModel( private val appRepository: Repository, private val schedulerProvider: SchedulerProvider ) : BaseViewModel() { private val _loading = MutableLiveData<Boolean>() val loading: LiveData<Boolean> get() = _loading private val _toastMessage = SingleLiveEvent<String>() val toastMessage: LiveData<String> get() = _toastMessage private val _liveItems = MutableLiveData<List<BaseViewItem>>() val items: LiveData<List<BaseViewItem>> get() = _liveItems private fun showLoadingState(){ _loading.value = true if(_liveItems.value?.isEmpty() == null || _liveItems.value?.firstOrNull { it is ErrorStateItem } != null){ _liveItems.value = listOf(LoadingStateItem()) } } private fun showErrorState(throwable: Throwable){ _loading.value = false if(_liveItems.value?.isEmpty() == null || _liveItems.value?.firstOrNull { it is ErrorStateItem || it is LoadingStateItem } != null){ _liveItems.value = listOf(handleThrowable(throwable)) } } fun loadDashboard() { showLoadingState() val overviewObservable = appRepository.overview() .observeOn(schedulerProvider.io()) //all stream below will be manage on io thread val dailyObservable = appRepository.daily() .observeOn(schedulerProvider.io()) val pinnedObservable = appRepository.pinnedRegion() .observeOn(schedulerProvider.io()) Observable.combineLatest( overviewObservable, dailyObservable, pinnedObservable, Function3<Result< CovidOverview>, Result<List< CovidDaily>>, Result< CovidDetail>, Pair<List<BaseViewItem>, Throwable?>> { overview, daily, pinned -> val items: MutableList<BaseViewItem> = mutableListOf() var currentThrowable: Throwable? = null with(overview){ items.add( ws.idroid.worldstatus.data.mapper.CovidOverviewDataMapper.transform(data)) error?.let { currentThrowable = it } } with(pinned){ ws.idroid.worldstatus.data.mapper.CovidPinnedDataMapper.transform(data)?.let { items.add(it) } error?.let { currentThrowable = it } } with(daily){ val dailies = ws.idroid.worldstatus.data.mapper.CovidDailyDataMapper.transform(data) if(dailies.isNotEmpty()) { items.add(TextItem(R.string.daily_updates, R.string.show_graph)) items.addAll(dailies) } error?.let { currentThrowable = it } } return@Function3 items.toList() to currentThrowable }) .observeOn(schedulerProvider.ui()) //go back to ui thread .subscribe({ (result, throwable) -> _liveItems.postValue(result) if(throwable != null) _toastMessage.value = Constant.ERROR_MESSAGE _loading.value = false }, { _toastMessage.value = Constant.ERROR_MESSAGE showErrorState(it) }).addTo(compositeDisposable) } }
0
null
0
3
958751c4a09664402317630142733f3c97bd4de9
4,520
Covid-19-Android
Apache License 2.0
analytics/src/test/java/io/appmetrica/analytics/impl/attribution/NullExternalAttributionTest.kt
appmetrica
650,662,094
false
{"Java": 5766310, "C++": 5729793, "Kotlin": 2673849, "Python": 229161, "Objective-C++": 152166, "C": 127185, "Assembly": 59003, "Emacs Lisp": 14657, "Objective-C": 10302, "Starlark": 7767, "Shell": 5746, "Go": 4930, "CMake": 3562, "CSS": 1454, "AppleScript": 1429, "AIDL": 504}
package io.appmetrica.analytics.impl.attribution import io.appmetrica.analytics.impl.protobuf.backend.ExternalAttribution.ClientExternalAttribution import io.appmetrica.analytics.protobuf.nano.MessageNano import io.appmetrica.analytics.testutils.CommonTest import io.appmetrica.analytics.testutils.MockedStaticRule import org.assertj.core.api.SoftAssertions import org.junit.Before import org.junit.Rule import org.junit.Test import org.mockito.kotlin.any import org.mockito.kotlin.argumentCaptor import org.mockito.kotlin.whenever class NullExternalAttributionTest : CommonTest() { private val provider = ExternalAttributionType.AIRBRIDGE @get:Rule val messageNanoRule = MockedStaticRule(MessageNano::class.java) @Before fun setUp() { whenever(MessageNano.toByteArray(any())).thenReturn("".toByteArray()) } @Test fun constructor() { NullExternalAttribution(provider).toBytes() val captor = argumentCaptor<ClientExternalAttribution>() messageNanoRule.staticMock.verify { MessageNano.toByteArray(captor.capture()) } val proto = captor.firstValue SoftAssertions().apply { assertThat(proto.attributionType).isEqualTo(ClientExternalAttribution.AIRBRIDGE) assertThat(String(proto.value)).isEqualTo("") assertAll() } } }
2
Java
5
54
7f7b9968291a809f653f8d8fea1ecb3eed6cb278
1,371
appmetrica-sdk-android
MIT License
samples/android-weatherapp/app/src/main/kotlin/org/koin/sampleapp/view/detail/DetailActivity.kt
Ekito
116,110,333
false
null
package org.koin.sampleapp.view.detail import android.os.Bundle import android.support.v7.app.AppCompatActivity import kotlinx.android.synthetic.main.activity_weather_detail.* import org.koin.android.ext.android.inject import org.koin.sampleapp.R import org.koin.sampleapp.di.Params.DETAIL_VIEW import org.koin.sampleapp.model.DailyForecastModel import org.koin.sampleapp.util.ext.argument import org.koin.sampleapp.view.Arguments.ARG_ADDRESS import org.koin.sampleapp.view.Arguments.ARG_WEATHER_DATE import org.koin.sampleapp.view.Arguments.ARG_WEATHER_ITEM_ID import java.util.* /** * Weather Detail View */ class DetailActivity : AppCompatActivity(), DetailContract.View { // Get all needed data private val address by argument<String>(ARG_ADDRESS) private val now by argument<Date>(ARG_WEATHER_DATE) private val detailId by argument<String>(ARG_WEATHER_ITEM_ID) override val presenter: DetailContract.Presenter by inject { mapOf(DETAIL_VIEW to this) } override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_weather_detail) } override fun onStart() { super.onStart() presenter.getDetail(detailId) } override fun onDestroy() { presenter.stop() super.onDestroy() } override fun displayDetail(weather: DailyForecastModel) { weatherTitle.text = getString(R.string.weather_title).format(address, now) weatherItemIcon.text = weather.icon weatherItemForecast.text = weather.forecastString weatherItemTemp.text = weather.temperatureString } }
2
Shell
80
212
a82add4f9ac27b93cf7ffc7c9c41bced074ecd1c
1,646
koin-samples
Apache License 2.0
gesture/src/main/kotlin/com/github/stephenvinouze/advancedrecyclerview_gesture/callbacks/GestureCallback.kt
bulbulhossenbd
58,305,944
false
null
package com.github.stephenvinouze.advancedrecyclerview.callbacks /** * Created by <NAME> on 10/11/2015. */ abstract class GestureCallback { open fun canMoveAt(position: Int): Boolean { return true } open fun canSwipeAt(position: Int): Boolean { return true } abstract fun onMove(fromPosition: Int, toPosition: Int): Boolean abstract fun onSwiped(position: Int, direction: Int) }
0
null
0
2
9a0b94a5559f4a3a75b7085971086002aa3324e4
426
AdvancedRecyclerView
Apache License 2.0
lib/data/src/main/java/com/tongsr/data/local/datastore/LocalStorageManager.kt
ujffdi
628,844,063
false
{"Java": 1874289, "Kotlin": 463042, "Groovy": 31947}
package com.tongsr.data.local.datastore import android.app.Application import androidx.annotation.NonNull import androidx.datastore.core.DataStore import androidx.datastore.preferences.core.Preferences import androidx.datastore.preferences.core.edit import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.map import kotlinx.coroutines.withContext /** * @author Tongsr * @version 1.0 * @date 2023/2/28 * @email <EMAIL> * @description LocalStorageManager */ object LocalStorageManager { private lateinit var dataStore: DataStore<Preferences> /** * 初始化 * @param context context */ fun init(context: Application) { if (this::dataStore.isInitialized) { return } dataStore = context.dataStore } suspend fun <T> put(key: Preferences.Key<T>, value: T) { dataStore.edit { preferences -> preferences[key] = value } } suspend fun <T> put(vararg pairs: Pair<Preferences.Key<T>, T>) { when (pairs.size) { 1 -> { val pair = pairs[0] put(pair.first, pair.second) } else -> { dataStore.edit { preferences -> for ((key, value) in pairs) { preferences[key] = value } } } } } fun getString(key: Preferences.Key<String>): Flow<String> = getInternal(key, "") fun getInt(key: Preferences.Key<Int>): Flow<Int> = get(key, 0) fun getBoolean(key: Preferences.Key<Boolean>): Flow<Boolean> = getInternal(key, false) fun getLong(key: Preferences.Key<Long>): Flow<Long> = getInternal(key, 0) fun getFloat(key: Preferences.Key<Float>): Flow<Float> = getInternal(key, 0F) fun getDouble(key: Preferences.Key<Double>): Flow<Double> = getInternal(key, 0.00) fun getStringSet(key: Preferences.Key<Set<String>>): Flow<Set<String>> = getInternal(key, emptySet()) fun <T> get(key: Preferences.Key<T>, defaultValue: T): Flow<T> = dataStore.data.map { preferences -> preferences[key] ?: defaultValue } private inline fun <reified T> getInternal(key: Preferences.Key<T>, defaultValue: T): Flow<T> = dataStore.data.map { preferences -> preferences[key] ?: defaultValue } suspend fun <T> remove(key: Preferences.Key<T>) { withContext(Dispatchers.IO) { dataStore.edit { settings -> settings.remove(key) } } } suspend fun clear() { withContext(Dispatchers.IO) { dataStore.edit { settings -> settings.clear() } } } }
1
null
1
1
d5004ca96f384cb26dbc610617107c3f12f05211
2,768
Eyepetizer
Apache License 2.0
app/src/main/java/radim/outfit/core/export/work/locusapiextensions/TrackEnhancements.kt
tripleSevenRada
157,741,300
false
null
package radim.outfit.core.export.work.locusapiextensions import android.util.Log import locus.api.objects.extra.Track import locus.api.objects.utils.LocationCompute import radim.outfit.DEBUG_MODE import radim.outfit.core.export.work.routePointActionsPrioritized import radim.outfit.core.export.work.routePointActionsToCoursePoints import kotlin.system.exitProcess // track does not contain null elements and is fully timestamped fun extractPointTimestampsFromPoints(track: Track): List<Long> { val mutableListOfTimestamps = mutableListOf<Long>() track.points.forEach { mutableListOfTimestamps.add(it.time) } return mutableListOfTimestamps } // track may contain null elements and is not considered fully timestamped fun assignPointTimestampsToNonNullPoints(track: Track, distances: List<Float>, speedIfNotInTrack: Float): List<Long> { val now: Long = System.currentTimeMillis() val mutableListOfTimestamps = mutableListOf<Long>() var count = 0 for (i in track.points.indices) { if (track.points[i] == null) continue // first point if (count == 0) { mutableListOfTimestamps.add(now) count = 1 continue } val dst = distances[count] val timeMilis = (dst / speedIfNotInTrack) * 1000F mutableListOfTimestamps.add(now + timeMilis.toLong()) count++ } return mutableListOfTimestamps } fun assignPointDistancesToNonNullPoints(track: Track): List<Float> { val mutableListOfDistances = mutableListOf<Float>() var firstZeroSet = false var lastPoint = track.points[0] var sum = 0F for (i in track.points.indices) { if (track.points[i] == null) continue if (!firstZeroSet) { mutableListOfDistances.add(sum) // 0F lastPoint = track.points[i] firstZeroSet = true continue } val dst = LocationCompute.computeDistanceFast( lastPoint.latitude, lastPoint.longitude, track.points[i].latitude, track.points[i].longitude ).toFloat() sum += dst mutableListOfDistances.add(sum) lastPoint = track.points[i] } return mutableListOfDistances } fun assignSpeedsToNonNullPoints(track: Track, timeBundle: TrackTimestampsBundle, dist: List<Float>): List<Float> { val speeds = mutableListOf<Float>() var index = 0 var lastTime: Long = timeBundle.pointStamps[0] var lastDist: Float = dist[0] for (i in track.points.indices) { if (track.points[i] == null) continue var timeDeltaInS: Float = ((timeBundle.pointStamps[index] - lastTime).toFloat()) / 1000F var distDeltaInM: Float = dist[index] - lastDist if (timeDeltaInS < 0F) timeDeltaInS = 0F if (distDeltaInM < 0F) distDeltaInM = 0F val speed = distDeltaInM / timeDeltaInS speeds.add(if (speed.isFinite()) speed else 0F) lastTime = timeBundle.pointStamps[index] lastDist = dist[index] index++ } if (DEBUG_MODE && (timeBundle.pointStamps.size != dist.size || dist.size != speeds.size)) { Log.e("TRACK_ENHANCEMENTS", "Data sizes - TrackEnhancements") exitProcess(-1) } return speeds } // According do docs it should be possible to position a coursepoint just using a related trackpoint's timestamp , // but I better don't trust it as Garmin itself does not use that simple approach fun mapNonNullPointsIndicesToTimestamps(track: Track, timeBundle: TrackTimestampsBundle): Map<Int, Long> { val nonNullTimestamps = timeBundle.pointStamps return mapNonNullIndicesToValues(track, nonNullTimestamps) } fun mapNonNullPointsIndicesToDistances(track: Track, distances: List<Float>): Map<Int, Float>{ return mapNonNullIndicesToValues(track, distances) } fun <V> mapNonNullIndicesToValues(track: Track, values: List<V>): Map<Int,V>{ val indicesToNonNullValues = mutableMapOf<Int, V>() var indexNonNull = 0 for (index in track.points.indices) { if (track.points[index] == null) continue indicesToNonNullValues[index] = values[indexNonNull] if (indexNonNull == values.size) throw RuntimeException("Indices messed 1 - TrackEnhancements") indexNonNull++ } if(indicesToNonNullValues.size != values.size) throw RuntimeException("Indices messed 2 - TrackEnhancements") return indicesToNonNullValues } fun ridUnsupportedRtePtActions(waypoints: List<WaypointSimplified>): List<WaypointSimplified>{ return waypoints.filter { routePointActionsToCoursePoints.keys.contains(it.rteAction) } } fun reduceWayPointsSizeTo(points: List<WaypointSimplified>, limit: Int): List<WaypointSimplified>{ var toReduce = points.toMutableList() val range = IntRange(1, routePointActionsPrioritized.size - 1) // allways keep all PASS_PLACE and UNDEFINED waypoints here for (i in range){ if (toReduce.size <= limit) break val rteActionsToRid = routePointActionsPrioritized[i] ?: listOf() toReduce = toReduce.filter { ! rteActionsToRid.contains(it.rteAction) }.toMutableList() } // now reduce even PASS_PLACE and UNDEFINED if necessary return if (toReduce.size <= limit) toReduce else { val over = toReduce.size - limit val pre: Int val post: Int if(over % 2 == 0){pre = over / 2; post = over / 2} else{pre = (over / 2) + 1; post = over/2} toReduce.subList(pre, toReduce.size - post) } } data class TrackTimestampsBundle(val startTime: Long, val pointStamps: List<Long>)
0
Kotlin
1
0
7de0a95d6743e6dc7809f9a76d7d64b263626681
5,607
OutFit
Apache License 2.0
src/main/kotlin/io/github/ruskonert/ruskit/Ruskit.kt
Ruskonert
140,462,127
false
{"Kotlin": 165766, "Java": 5810, "C++": 2625}
/* Copyright (c) 2018 ruskonert Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ package io.github.ruskonert.ruskit import io.github.ruskonert.ruskit.command.RuskitPluginCommand import io.github.ruskonert.ruskit.engine.InventoryHandler import io.github.ruskonert.ruskit.engine.plugin.CommandRegistration import io.github.ruskonert.ruskit.engine.plugin.SynchronizeReaderEngine import io.github.ruskonert.ruskit.plugin.IntegratedPlugin import io.github.ruskonert.ruskit.plugin.RuskitServerPlugin import io.github.ruskonert.ruskit.sendbox.RuskitSendboxHandler class Ruskit : IntegratedPlugin() { companion object { private var instance : RuskitServerPlugin? = null fun getInstance() : RuskitServerPlugin? = instance } var settings : Map<String, Any> = HashMap() override fun onInit(handleInstance: Any?): Any? { super.onInit(this) this.registerSustainableHandlers( // Register dynamic commands core CommandRegistration::class.java, // Register Ruskit main commands RuskitPluginCommand::class.java, // Test external libs loader RuskitSendboxHandler::class.java, // SynchronizeReader Engine SynchronizeReaderEngine::class.java, InventoryHandler::class.java ) RuskitSendboxHandler.getInstance().call("PlaySoundA", "/test.wav") this.getMessageHandler().defaultMessage("JNI Test -> WinAPI function called: PlaySoundA(test.wav)") return true } }
0
Kotlin
0
0
e68ce3997182e5ebaed10868ddefc4eaeee3a262
2,551
Ruskit
MIT License
android/app/src/main/java/com/carlospinan/jetpackexample/Example05Activity.kt
cpinan
215,833,397
false
null
package com.carlospinan.jetpackexample import android.os.Bundle import android.os.Handler import androidx.appcompat.app.AppCompatActivity import androidx.compose.* import androidx.ui.core.setContent import androidx.ui.graphics.Color import androidx.ui.layout.FlexColumn import androidx.ui.layout.LayoutSize import androidx.ui.layout.MainAxisAlignment import androidx.ui.layout.Row import androidx.ui.material.CircularProgressIndicator import androidx.ui.material.LinearProgressIndicator import androidx.ui.material.MaterialTheme class Example05Activity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContent { MaterialTheme { ProgressIndicatorDemo() } } } } @Model private class ProgressState { var progress = +state { 0.0f } var cycle = +state { 0 } fun generateColor(): Color { return when (cycle.value) { 1 -> Color.Red 2 -> Color.Green 3 -> Color.Blue // unused else -> Color.Black } } fun start() { handler.postDelayed(updateProgress, 400) } fun stop() { handler.removeCallbacks(updateProgress) } val handler = Handler() val updateProgress: Runnable = object : Runnable { override fun run() { if (progress.value == 1f) { cycle.value++ if (cycle.value > 3) { cycle.value = 1 } progress.value = 0f } else { progress.value += 0.25f } handler.postDelayed(this, 400) } } } @Composable private fun ProgressIndicatorDemo(state: ProgressState = ProgressState()) { +onActive { state.start() } +onDispose { state.stop() } FlexColumn { expanded(flex = 1f) { Row( mainAxisSize = LayoutSize.Expand, mainAxisAlignment = MainAxisAlignment.SpaceEvenly ) { // Determinate indicators LinearProgressIndicator(progress = state.progress.value) CircularProgressIndicator(progress = state.progress.value) } Row( mainAxisSize = LayoutSize.Expand, mainAxisAlignment = MainAxisAlignment.SpaceEvenly ) { // Fancy colours! LinearProgressIndicator( progress = (state.progress.value), color = state.generateColor() ) CircularProgressIndicator( progress = (state.progress.value), color = state.generateColor() ) } Row( mainAxisSize = LayoutSize.Expand, mainAxisAlignment = MainAxisAlignment.SpaceEvenly ) { // Indeterminate indicators LinearProgressIndicator() CircularProgressIndicator() } } } }
1
Kotlin
1
3
a4298de63f0cb4848269a9fe5b6a5ab59d68a4e5
3,115
Android-Jetpack-Composer
Apache License 2.0
src/main/kotlin/no/nav/modiapersonoversikt/storage/JdbcStorageProvider.kt
navikt
179,552,047
false
{"Kotlin": 15784, "Shell": 313, "Dockerfile": 137}
package no.nav.modiapersonoversikt.storage import kotlinx.coroutines.runBlocking import kotliquery.Session import kotliquery.queryOf import no.nav.modiapersonoversikt.model.UserSettings import no.nav.modiapersonoversikt.model.UserSettingsMap import no.nav.personoversikt.common.utils.SelftestGenerator import java.time.LocalDateTime import javax.sql.DataSource import kotlin.concurrent.fixedRateTimer import kotlin.time.Duration.Companion.seconds private const val innstillingerTable = "innstillinger" private const val sistOppdatertTable = "sist_oppdatert" class JdbcStorageProvider(private val dataSource: DataSource) : StorageProvider { private val selftest = SelftestGenerator.Reporter("Database", true) init { fixedRateTimer("Database check", daemon = true, initialDelay = 0, period = 10.seconds.inWholeMilliseconds) { runBlocking { selftest.ping { getData("Z999999") } } } } override suspend fun getData(ident: String): UserSettings { return transactional(dataSource) { tx -> getData(tx, ident) } } override suspend fun storeData(ident: String, settings: UserSettingsMap): UserSettings { return transactional(dataSource) { tx -> deleteData(tx, ident) settings.forEach { (navn, verdi) -> tx.run( queryOf( "INSERT INTO $innstillingerTable (ident, navn, verdi) VALUES(?, ?, ?)", ident, navn, verdi ).asUpdate ) } tx.run( queryOf("INSERT INTO $sistOppdatertTable (ident) VALUES(?)", ident).asUpdate ) getData(tx, ident) } } override suspend fun clearData(ident: String): UserSettings { return transactional(dataSource) { tx -> deleteData(tx, ident) getData(tx, ident) } } private fun getData(tx: Session, ident: String): UserSettings { val sistLagret: LocalDateTime = tx.run( queryOf("SELECT tidspunkt FROM $sistOppdatertTable WHERE ident = ?", ident) .map { row -> row.localDateTime("tidspunkt") } .asSingle ) ?: LocalDateTime.now() val innstillinger = tx.run( queryOf("SELECT navn, verdi FROM $innstillingerTable WHERE ident = ?", ident) .map { row -> Pair(row.string("navn"), row.string("verdi")) } .asList ).toMap() return UserSettings(sistLagret, innstillinger) } private fun deleteData(tx: Session, ident: String) { tx.run(queryOf("DELETE FROM $innstillingerTable WHERE ident = ?", ident).asUpdate) tx.run(queryOf("DELETE FROM $sistOppdatertTable WHERE ident = ?", ident).asUpdate) } }
0
Kotlin
0
0
9ec57c78cf71e8fc942aff6f8ff4b31d082dfe5d
2,916
modiapersonoversikt-innstillinger
MIT License
demo/plot/shared/src/main/kotlin/plotSpec/FacetWrapSpec.kt
JetBrains
571,767,875
false
{"Kotlin": 175627}
/* * Copyright (c) 2023 JetBrains s.r.o. * Use of this source code is governed by the MIT license that can be found in the LICENSE file. */ package plotSpec import demoData.AutoMpg import org.jetbrains.letsPlot.Figure import org.jetbrains.letsPlot.facet.facetWrap import org.jetbrains.letsPlot.geom.geomPoint import org.jetbrains.letsPlot.intern.Plot import org.jetbrains.letsPlot.letsPlot import org.jetbrains.letsPlot.themes.themeGrey class FacetWrapSpec : PlotDemoSpec { override fun createFigureList(): List<Figure> { val oneFacetDef = commonSpecs() + facetWrap(facets = "number of cylinders", format = "{d} cyl") val oneFacet3cols = commonSpecs() + facetWrap(facets = "number of cylinders", ncol = 3, format = "{d} cyl") val oneFacet4rows = commonSpecs() + facetWrap(facets = "number of cylinders", ncol = 4, dir = "v", format = "{d} cyl") val twoFacets = commonSpecs() + facetWrap( facets = listOf("origin of car", "number of cylinders"), ncol = 5, format = listOf(null, "{d} cyl") ) val twoFacetsCylindersOrderDesc = commonSpecs() + facetWrap( facets = listOf("origin of car", "number of cylinders"), ncol = 5, order = listOf(null, -1), format = listOf(null, "{d} cyl") ) return listOf( oneFacetDef, oneFacet3cols, oneFacet4rows, twoFacets, twoFacetsCylindersOrderDesc, ) } private fun commonSpecs(): Plot { return letsPlot(AutoMpg.map()) { x = "engine horsepower" y = "miles per gallon" color = "origin of car" } + geomPoint() + themeGrey() } }
3
Kotlin
2
88
1649c1d8232895073ad31baea0625bf29f925b17
1,757
lets-plot-skia
MIT License
src/main/kotlin/com/sbl/sulmun2yong/survey/dto/request/SurveySaveRequest.kt
SUIN-BUNDANG-LINE
819,257,518
false
{"Kotlin": 442215}
package com.sbl.sulmun2yong.survey.dto.request import com.sbl.sulmun2yong.survey.domain.SurveyStatus import com.sbl.sulmun2yong.survey.domain.question.QuestionType import com.sbl.sulmun2yong.survey.domain.question.choice.Choice import com.sbl.sulmun2yong.survey.domain.question.choice.Choices import com.sbl.sulmun2yong.survey.domain.question.impl.StandardMultipleChoiceQuestion import com.sbl.sulmun2yong.survey.domain.question.impl.StandardSingleChoiceQuestion import com.sbl.sulmun2yong.survey.domain.question.impl.StandardTextQuestion import com.sbl.sulmun2yong.survey.domain.reward.Reward import com.sbl.sulmun2yong.survey.domain.reward.RewardSetting import com.sbl.sulmun2yong.survey.domain.reward.RewardSettingType import com.sbl.sulmun2yong.survey.domain.routing.RoutingStrategy import com.sbl.sulmun2yong.survey.domain.routing.RoutingType import com.sbl.sulmun2yong.survey.domain.section.Section import com.sbl.sulmun2yong.survey.domain.section.SectionId import com.sbl.sulmun2yong.survey.domain.section.SectionIds import java.util.Date import java.util.UUID data class SurveySaveRequest( val title: String, val description: String, // TODO: 섬네일의 URL이 우리 서비스의 S3 URL인지 확인하기 val thumbnail: String?, val finishMessage: String, val isVisible: Boolean, val isResultOpen: Boolean, val rewardSetting: RewardSettingResponse, val sections: List<SectionCreateRequest>, ) { fun List<SectionCreateRequest>.toDomain() = if (isEmpty()) { listOf() } else { val sectionIds = SectionIds.from(this.map { SectionId.Standard(it.sectionId) }) this.map { Section( id = SectionId.Standard(it.sectionId), title = it.title, description = it.description, routingStrategy = it.getRoutingStrategy(), questions = it.questions.map { question -> question.toDomain() }, sectionIds = sectionIds, ) } } data class RewardSettingResponse( val type: RewardSettingType, val rewards: List<RewardCreateRequest>, val targetParticipantCount: Int?, val finishedAt: Date?, ) { fun toDomain(surveyStatus: SurveyStatus) = RewardSetting.of( type, rewards.map { Reward(it.name, it.category, it.count) }, targetParticipantCount, finishedAt, surveyStatus, ) } data class RewardCreateRequest( val name: String, val category: String, val count: Int, ) data class SectionCreateRequest( val sectionId: UUID, val title: String, val description: String, val questions: List<QuestionCreateRequest>, val routeDetails: RouteDetailsCreateRequest, ) { fun getRoutingStrategy() = when (routeDetails.type) { RoutingType.NUMERICAL_ORDER -> RoutingStrategy.NumericalOrder RoutingType.SET_BY_USER -> RoutingStrategy.SetByUser(SectionId.from(routeDetails.nextSectionId)) RoutingType.SET_BY_CHOICE -> RoutingStrategy.SetByChoice( keyQuestionId = routeDetails.keyQuestionId!!, routingMap = routeDetails.sectionRouteConfigs!!.associate { Choice.from(it.content) to SectionId.from(it.nextSectionId) }, ) } } data class RouteDetailsCreateRequest( val type: RoutingType, val nextSectionId: UUID?, val keyQuestionId: UUID?, val sectionRouteConfigs: List<RoutingConfigCreateRequest>?, ) data class RoutingConfigCreateRequest( val content: String?, val nextSectionId: UUID?, ) data class QuestionCreateRequest( val questionId: UUID, val type: QuestionType, val title: String, val description: String, val isRequired: Boolean, val isAllowOther: Boolean, val choices: List<String>?, ) { fun toDomain() = when (type) { QuestionType.TEXT_RESPONSE -> StandardTextQuestion( id = questionId, title = title, description = description, isRequired = isRequired, ) QuestionType.SINGLE_CHOICE -> StandardSingleChoiceQuestion( id = questionId, title = title, description = description, isRequired = isRequired, choices = Choices( standardChoices = choices!!.map { Choice.Standard(it) }, isAllowOther = isAllowOther, ), ) QuestionType.MULTIPLE_CHOICE -> StandardMultipleChoiceQuestion( id = questionId, title = title, description = description, isRequired = isRequired, choices = Choices( standardChoices = choices!!.map { Choice.Standard(it) }, isAllowOther = isAllowOther, ), ) } } }
1
Kotlin
1
3
e2203ff721fcde4bcdcc7e21b8aeb0c849dae17d
5,682
Backend
MIT License
libs/membership/membership-impl/src/test/kotlin/net/corda/membership/lib/impl/converter/NotaryInfoConverterTest.kt
corda
346,070,752
false
null
package net.corda.membership.lib.impl.converter import net.corda.crypto.cipher.suite.KeyEncodingService import net.corda.crypto.core.CompositeKeyProvider import net.corda.crypto.impl.converter.PublicKeyConverter import net.corda.layeredpropertymap.testkit.LayeredPropertyMapMocks import net.corda.v5.base.exceptions.ValueNotFoundException import net.corda.v5.base.types.MemberX500Name import net.corda.v5.crypto.CompositeKeyNodeAndWeight import net.corda.v5.membership.NotaryInfo import org.assertj.core.api.Assertions.assertThat import org.assertj.core.api.SoftAssertions.assertSoftly import org.junit.jupiter.api.Test import org.junit.jupiter.api.assertThrows import org.mockito.kotlin.doReturn import org.mockito.kotlin.eq import org.mockito.kotlin.mock import java.security.PublicKey import java.util.SortedMap class NotaryInfoConverterTest { @Suppress("SpreadOperator") private companion object { val notaryService = MemberX500Name.parse("O=NotaryService,L=London,C=GB") const val NOTARY_PLUGIN = "testPlugin" const val NAME = "name" const val PLUGIN = "plugin" const val KEYS = "keys.%s" const val KEY_VALUE = "encoded_key" val key: PublicKey = mock() val keyEncodingService: KeyEncodingService = mock { on { encodeAsString(key) } doReturn KEY_VALUE on { decodePublicKey(KEY_VALUE) } doReturn key } val notaryKeys = listOf(key, key) val compositeKeyForNonEmptyKeys: PublicKey = mock() val compositeKeyForEmptyKeys: PublicKey = mock() val weightedKeys = notaryKeys.map { CompositeKeyNodeAndWeight(it, 1) } val compositeKeyProvider: CompositeKeyProvider = mock { on { create(eq(weightedKeys), eq(null)) } doReturn compositeKeyForNonEmptyKeys on { create(eq(emptyList()), eq(null)) } doReturn compositeKeyForEmptyKeys } val correctContext = sortedMapOf( NAME to notaryService.toString(), PLUGIN to NOTARY_PLUGIN, *convertNotaryKeys().toTypedArray() ) val contextWithoutName = sortedMapOf( PLUGIN to NOTARY_PLUGIN, *convertNotaryKeys().toTypedArray() ) val contextWithoutPlugin = sortedMapOf( NAME to notaryService.toString(), *convertNotaryKeys().toTypedArray() ) val contextWithoutKeys = sortedMapOf( NAME to notaryService.toString(), PLUGIN to NOTARY_PLUGIN ) val converters = listOf( NotaryInfoConverter(compositeKeyProvider), PublicKeyConverter(keyEncodingService) ) fun convertNotaryKeys(): List<Pair<String, String>> = notaryKeys.mapIndexed { i, notaryKey -> String.format( KEYS, i ) to keyEncodingService.encodeAsString(notaryKey) } } private fun convertToNotaryInfo(context: SortedMap<String, String>): NotaryInfo = converters.find { it.type == NotaryInfo::class.java }?.convert( LayeredPropertyMapMocks.createConversionContext<LayeredContextImpl>( context, converters, "" ) ) as NotaryInfo @Test fun `converter converts notary service info successfully`() { val result = convertToNotaryInfo(correctContext) assertSoftly { it.assertThat(result.name).isEqualTo(notaryService) it.assertThat(result.pluginClass).isEqualTo(NOTARY_PLUGIN) it.assertThat(result.publicKey).isEqualTo(compositeKeyForNonEmptyKeys) } } @Test fun `converter converts notary service info successfully even if the notary keys are empty`() { val result = convertToNotaryInfo(contextWithoutKeys) assertSoftly { it.assertThat(result.name).isEqualTo(notaryService) it.assertThat(result.pluginClass).isEqualTo(NOTARY_PLUGIN) it.assertThat(result.publicKey).isEqualTo(compositeKeyForEmptyKeys) } } @Test fun `exception is thrown when notary service's name is missing`() { val ex = assertThrows<ValueNotFoundException> { convertToNotaryInfo(contextWithoutName) } assertThat(ex.message).contains("name") } @Test fun `exception is thrown when notary service's plugin type is missing`() { val ex = assertThrows<ValueNotFoundException> { convertToNotaryInfo(contextWithoutPlugin) } assertThat(ex.message).contains("plugin") } }
82
Kotlin
7
24
17f5d2e5585a8ac56e559d1c099eaee414e6ec5a
4,658
corda-runtime-os
Apache License 2.0
src/Demo.kt
VaibhavMojidra
635,056,182
false
null
class Student(public val name: String,private val age: Int){ fun printName(){ println("Name: $name") } fun printAge(){ println("Age: $age") } } class Teacher(val _name:String,val _age:Int){ var name:String var age:Int init{ name=_name age=_age } fun printName(){ println("Name: $name") } fun printAge(){ println("Age: $age") } } fun main(args: Array<String>) { var student1=Student("Vaibhav",23) //student1.age this will give error as its private student1.printName() student1.printAge() var teacher=Teacher("Dhanraj",40) teacher.printName() teacher.printAge() }
0
Kotlin
0
0
be5710e6fb857493bafe8dd9b4b6356ec0ca19ae
610
Kotlin---Demo-Primary-Constructor
MIT License
src/test/kotlin/com/melardev/spring/microservicezuulcrud/MicroserviceZuulCrudApplicationTests.kt
melardev
190,732,888
false
null
package com.melardev.spring.microservicezuulcrud import org.junit.Test import org.junit.runner.RunWith import org.springframework.boot.test.context.SpringBootTest import org.springframework.test.context.junit4.SpringRunner @RunWith(SpringRunner::class) @SpringBootTest class MicroserviceZuulCrudApplicationTests { @Test fun contextLoads() { } }
0
Kotlin
0
0
e39bb2374c85c8e3539f9de97f5c4a31a024b61a
352
KotlinSpringBootZuulRestApiPaginatedCrud
MIT License
src/main/kotlin/dev/jonpoulton/dexter/config/KtlintConfigurer.kt
jonapoul
635,922,249
false
null
package dev.jonpoulton.dexter.config import org.gradle.api.Project import org.gradle.api.provider.Provider import org.gradle.kotlin.dsl.apply import org.gradle.kotlin.dsl.configure import org.jlleitschuh.gradle.ktlint.KtlintExtension import org.jlleitschuh.gradle.ktlint.reporter.ReporterType class KtlintConfigurer( private val ktlintVersion: Provider<String>? = null, ) : DexterConfigurer { override fun applyPlugin(project: Project) { project.allprojects { apply(plugin = "org.jlleitschuh.gradle.ktlint") } } override fun applyConfig(project: Project) { project.allprojects { extensions.configure<KtlintExtension> { ktlintVersion?.let { version.set(it.get()) } reporters { reporter(ReporterType.HTML) } } } } }
0
Kotlin
0
0
742195e0beb476d4b27c47c66e40185502bc4098
795
dexter-gradle-plugin
Apache License 2.0
src/main/kotlin/br/com/zupacademy/shared/exception/ChavePixNaoEncontradaExceptionHandler.kt
CharlesRodrigues-01
393,033,826
true
{"Kotlin": 72390, "Smarty": 1872, "Dockerfile": 184}
package br.com.zupacademy.shared.exception import br.com.zupacademy.shared.exception.interceptor.ExceptionHandler import io.grpc.Status import javax.inject.Singleton @Singleton class ChavePixNaoEncontradaExceptionHandler : ExceptionHandler<ChavePixNaoEncontradaException> { override fun handle(e: Exception): ExceptionHandler.StatusWithDetails { return ExceptionHandler.StatusWithDetails(Status.NOT_FOUND.withDescription(e.message).withCause(e)) } override fun supports(e: Exception): Boolean { return e is ChavePixNaoEncontradaException } }
0
Kotlin
0
0
3e482e6eb1798501329ae0148326f398dc9e6318
577
orange-talents-06-template-pix-keymanager-grpc
Apache License 2.0
domain/domain-usecase/src/main/java/com/odogwudev/example/domain_usecase/helper/movie/topRated/GetTopRatedMoviesFlowUseCase.kt
odogwudev
592,877,753
false
null
package com.odogwudev.example.domain_usecase.helper.movie.topRated import com.odogwudev.example.movie_api.MovieService import kotlinx.coroutines.flow.filterNotNull class GetTopRatedMoviesFlowUseCase(private val movieService: MovieService) { operator fun invoke() = movieService.topRatedMovies.filterNotNull() }
0
Kotlin
0
4
82791abdcf1554d2a2cd498a19cd93952f90e53e
317
CinephilesCompanion
MIT License
app/src/main/java/com/danhdueexoictif/androidgenericadapter/utils/theme/ThemeHelper.kt
DanhDue
251,030,651
false
null
package com.danhdueexoictif.androidgenericadapter.utils.theme import android.app.Activity import androidx.annotation.IntDef interface ThemeHelper { fun changeToTheme(activity: Activity, @ThemeDef theme: Int) fun onActivityCreateSetTheme(activity: Activity, @ThemeDef theme: Int) companion object { const val DEFAULT_THEME = 0 const val JAPANESE_THEME = 1 @IntDef( DEFAULT_THEME, JAPANESE_THEME ) @Retention(AnnotationRetention.SOURCE) annotation class ThemeDef } }
0
null
5
7
02e0d14f09140531c8911ff6af46ee5d8eda4941
559
AndroidGenericAdapter
Apache License 2.0
src/main/kotlin/org/ocpp/server/entities/transaction/TransactionService.kt
NLCProject
497,246,900
false
null
package org.ocpp.server.entities.transaction import eu.chargetime.ocpp.model.core.Reason import org.isc.utils.genericCrudl.models.Aspects import org.isc.utils.genericCrudl.services.EntityService import org.isc.utils.models.CurrentUser import org.isc.utils.services.dateTime.interfaces.IDateConversionService import org.isc.utils.tests.CurrentUserFactory import org.ocpp.client.application.Organisation import org.ocpp.server.dtos.TransactionModel import org.ocpp.server.entities.connectors.ConnectorEntity import org.ocpp.server.entities.connectors.ConnectorRepository import org.ocpp.server.entities.meterValue.MeterValueService import org.ocpp.server.enums.TransactionStatus import org.slf4j.LoggerFactory import org.springframework.beans.factory.annotation.Autowired import org.springframework.stereotype.Service import java.lang.Exception import java.time.ZonedDateTime @Service class TransactionService @Autowired constructor( private val dateConversionService: IDateConversionService, private val repositoryService: TransactionRepository, private val connectorRepository: ConnectorRepository, private val meterValueService: MeterValueService ) : EntityService<TransactionModel, TransactionEntity>( entityClass = TransactionEntity::class.java, repositoryService = repositoryService ) { private val logger = LoggerFactory.getLogger(this::class.java) /** * Creates transaction entity. * * @param connector Connector to which this entity belongs. * @param transactionId . * @param reservationId . * @param timestamp . * @param currentUser . * @return Created entity. */ fun createTransaction( connector: ConnectorEntity, transactionId: Int, reservationId: Int, timestamp: ZonedDateTime, currentUser: CurrentUser ): TransactionEntity { logger.info("Saving new transaction") val transaction = TransactionModel() transaction.connectorId = connector.id transaction.dateTimeStarted = dateConversionService.buildDateTimeString(date = timestamp) transaction.externalId = transactionId transaction.reservationId = reservationId return saveEntity(model = transaction, currentUser = currentUser) } /** * Update transaction entity. * * @param transactionId . * @param timestamp . * @param reason . * @param status . * @param currentUser . * @return Updated entity. */ fun updateTransaction( transactionId: Int, timestamp: ZonedDateTime, reason: Reason, status: TransactionStatus, currentUser: CurrentUser ): TransactionEntity { logger.info("Updating transaction ID '$transactionId'") val optional = repositoryService.findByExternalId(externalId = transactionId) if (!optional.isPresent) throw Exception("Transaction with external ID '$transactionId' not found") val transaction = optional.get() transaction.dateTimeStopped = dateConversionService.buildDateTimeString(date = timestamp) transaction.reasonToStop = reason transaction.status = TransactionStatus.Finished return repositoryService.save(entity = transaction, currentUser = currentUser) } /** * Close all ongoing transactions. Optional a single connector can be defined for which the transactions shall be * closed. * * @param connectorId If null, all ongoing transactions are closed. If not, only ongoing transactions of the given * connector are closed. */ fun closeAllOngoingTransactions(connectorId: Int? = null) { logger.info("Closing all ongoing transaction") val currentUser = CurrentUserFactory.getCurrentUser(organisationId = Organisation.id) repositoryService .findByStatus(status = TransactionStatus.Ongoing) .filter { if (connectorId == null) true else it.connector.externalId == connectorId } .toList() .forEach { logger.info("Setting status of transaction ID '${it.id}' to '${TransactionStatus.Finished}'") it.status = TransactionStatus.Finished repositoryService.save(entity = it, currentUser = currentUser) } } override fun preSave( model: TransactionModel, entity: TransactionEntity, isPresent: Boolean, aspects: Aspects, currentUser: CurrentUser ) { if (!isPresent) entity.connector = connectorRepository.findById(id = model.connectorId, currentUser = currentUser) } override fun afterSave( model: TransactionModel, entity: TransactionEntity, wasPresent: Boolean, aspects: Aspects, currentUser: CurrentUser ) { } override fun preDelete(entity: TransactionEntity, currentUser: CurrentUser) { entity.meterValues.forEach { meterValueService.deleteEntity(id = it.id, currentUser = currentUser) } } override fun afterDelete(entity: TransactionEntity, currentUser: CurrentUser) { } override fun checkModelAndThrow(currentUser: CurrentUser, model: TransactionModel) { } }
0
Kotlin
0
0
8014bacd913760ea2d58e9a29006ad248c449728
5,225
OcppServer
ISC License
app/src/main/java/io/deus/wallet/modules/market/topnftcollections/TopNftCollectionsModule.kt
DeusWallet
810,708,619
false
{"Kotlin": 5009329, "Shell": 6095, "Ruby": 1350}
package io.deus.wallet.modules.market.topnftcollections import androidx.lifecycle.ViewModel import androidx.lifecycle.ViewModelProvider import io.deus.wallet.core.App import io.deus.wallet.modules.market.SortingField import io.deus.wallet.modules.market.TimeDuration import io.deus.wallet.ui.compose.Select import io.horizontalsystems.marketkit.models.BlockchainType import java.math.BigDecimal object TopNftCollectionsModule { class Factory(val sortingField: SortingField, val timeDuration: TimeDuration) : ViewModelProvider.Factory { @Suppress("UNCHECKED_CAST") override fun <T : ViewModel> create(modelClass: Class<T>): T { val topNftCollectionsRepository = TopNftCollectionsRepository(App.marketKit) val service = TopNftCollectionsService(sortingField, timeDuration, topNftCollectionsRepository) val topNftCollectionsViewItemFactory = TopNftCollectionsViewItemFactory(App.numberFormatter) return TopNftCollectionsViewModel(service, topNftCollectionsViewItemFactory) as T } } } data class Menu( val sortingFieldSelect: Select<SortingField>, val timeDurationSelect: Select<TimeDuration> ) data class TopNftCollectionViewItem( val blockchainType: BlockchainType, val uid: String, val name: String, val imageUrl: String?, val volume: String, val volumeDiff: BigDecimal, val order: Int, val floorPrice: String )
0
Kotlin
0
0
f4c5e0fadbf2955edf7ba35d4617f148c191c02b
1,437
deus-wallet-android
MIT License
workflows/src/main/kotlin/net/corda/example/flows/FiatCurrencyIssueFlow.kt
Mark-yl-LIU
389,356,426
false
null
package net.corda.example.flows import co.paralleluniverse.fibers.Suspendable //import com.r3.corda.lib.tokens.contracts.internal.schemas.FungibleTokenSchema import com.r3.corda.lib.tokens.contracts.states.FungibleToken import com.r3.corda.lib.tokens.contracts.types.IssuedTokenType import com.r3.corda.lib.tokens.contracts.types.TokenType import com.r3.corda.lib.tokens.contracts.utilities.issuedBy import com.r3.corda.lib.tokens.money.FiatCurrency import com.r3.corda.lib.tokens.workflows.flows.rpc.IssueTokens import net.corda.core.contracts.Amount import net.corda.core.flows.* import net.corda.core.identity.Party import net.corda.core.utilities.ProgressTracker // ********* // * Flows * // ********* @StartableByRPC class FiatCurrencyIssueFlow(val currency: String, val amount: Long, val recipient: Party) : FlowLogic<String>() { override val progressTracker = ProgressTracker() @Suspendable override fun call():String { /* Create an instance of the fiat currency token */ val token = FiatCurrency.Companion.getInstance(currency) /* Create an instance of IssuedTokenType for the fiat currency */ val issuedTokenType = token issuedBy ourIdentity /* Create an instance of FungibleToken for the fiat currency to be issued */ val fungibleToken = FungibleToken(Amount(amount,issuedTokenType),recipient) val stx = subFlow(IssueTokens(listOf(fungibleToken), listOf<Party>(recipient))) return "Issued $amount $currency token(s) to ${recipient.name.organisation}" } }
0
null
0
0
19251c646aea9acd26f4868a1a77ee853d9765f2
1,608
DRTokenDemo
Apache License 2.0
app/src/main/java/com/ebanx/swipebutton/MainActivity.kt
simplec-dev
163,561,145
true
{"Java": 217239, "Kotlin": 56455}
package com.ebanx.swipebutton import android.os.Bundle import android.support.v4.content.ContextCompat import android.support.v7.app.AppCompatActivity import android.widget.Toast import kotlinx.android.synthetic.main.content_main.* class MainActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) swipeBtnEnabled.background = ContextCompat.getDrawable(this, R.drawable.shape_button2) swipeBtnEnabled.setSlidingButtonBackground(ContextCompat.getDrawable(this, R.drawable.shape_rounded2)) swipeBtnEnabled.setOnStateChangeListener { active -> Toast.makeText(this@MainActivity, "State: " + active, Toast.LENGTH_SHORT).show() if (active) { swipeBtnEnabled.setButtonBackground(ContextCompat.getDrawable(this@MainActivity, R.drawable.shape_button)) } else { swipeBtnEnabled.setButtonBackground(ContextCompat.getDrawable(this@MainActivity, R.drawable.shape_button3)) } } // swipeBtnDisabled.setDisabledStateNotAnimated() swipeBtnEnabled.setEnabledStateNotAnimated() swipeNoState.setOnActiveListener { Toast.makeText(this@MainActivity, "Active!", Toast.LENGTH_SHORT).show() } toggleBtn.setOnClickListener { if (!swipeBtnEnabled.isActive) { swipeBtnEnabled.toggleState() } } } }
0
Java
0
0
d5ce41b98c2ce1569d2c413fdce90ea718f72b8d
1,499
video-quickstart-android
MIT License
shared/neew/src/main/java/me/pitok/neew/di/NeewsComponentBuilder.kt
hamedsj
287,844,014
false
null
package me.pitok.neew.di import me.pitok.dependencyinjection.ComponentBuilder import me.pitok.neew.di.components.DaggerNeewsComponent import me.pitok.neew.di.components.NeewsComponent import me.pitok.neew.di.modules.NeewApiModule import me.pitok.networking.di.NetworkComponentBuilder object NeewsComponentBuilder: ComponentBuilder<NeewsComponent>() { override fun initComponent(): NeewsComponent { return DaggerNeewsComponent .builder() .neewApiModule(NeewApiModule()) .networkComponent(NetworkComponentBuilder.getComponent()) .build() } }
0
Kotlin
3
11
c94f16608febecb17edeb4bd6798dbe6b741d56c
605
GoodNews
Apache License 2.0
android/app/src/main/java/com/readdle/weather/core/WeatherRepository.kt
CleverSwift
292,673,225
true
{"Swift": 30299, "Kotlin": 20160}
package com.readdle.weather.core import com.readdle.codegen.anotation.SwiftFunc import com.readdle.codegen.anotation.SwiftReference @SwiftReference class WeatherRepository private constructor() { // Swift JNI private native pointer private val nativePointer = 0L // Swift JNI release method external fun release() external fun loadSavedLocations() @SwiftFunc("addLocationToSaved(location:)") external fun addLocationToSaved(location: Location) @SwiftFunc("removeSavedLocation(location:)") external fun removeSavedLocation(location: Location) @SwiftFunc("searchLocations(query:)") external fun searchLocations(query: String?) companion object { @JvmStatic @SwiftFunc("init(db:provider:delegate:)") external fun init(db: JSONStorage, provider: MetaWeatherProvider, delegate: WeatherRepositoryDelegateAndroid): WeatherRepository } }
0
null
0
0
1544b693c5ece59f2de3f1d81e2fb0ec53a7193e
968
swift-weather-app
MIT License
Morpho/composeApp/src/commonTest/kotlin/com/morpho/app/Test.kt
morpho-app
752,463,268
false
{"Kotlin": 791660, "Swift": 594}
package com.morpho.app
14
Kotlin
2
18
68cee539a1359d0273614390e46f0bdae55ab992
24
Morpho
Apache License 2.0
app/src/main/java/br202/androidtodo/views/authentication/fragments/RegisterFragment.kt
brandon-julio-t
351,159,898
false
null
package br202.androidtodo.views.authentication.fragments import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.Toast import androidx.fragment.app.Fragment import androidx.navigation.fragment.findNavController import br202.androidtodo.databinding.FragmentRegisterBinding import br202.androidtodo.services.AuthService class RegisterFragment : Fragment() { private var _binding: FragmentRegisterBinding? = null private val binding get() = _binding!! override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?, ): View { _binding = FragmentRegisterBinding.inflate(inflater, container, false) return binding.root } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) binding.registerButton.setOnClickListener { onRegister() } binding.registerToLogin.setOnClickListener { goToLogin() } } private fun onRegister() { val email = binding.registerEmail.text.toString() val password = binding.registerPassword.text.toString() if (email.isEmpty()) { Toast.makeText(activity, "Email must not be empty.", Toast.LENGTH_SHORT).show() return } if (password.isEmpty()) { Toast.makeText(activity, "Password must not be empty.", Toast.LENGTH_SHORT).show() return } AuthService.register(requireActivity(), email, password) { goToLogin() } } private fun goToLogin() { findNavController().navigate(RegisterFragmentDirections.actionRegisterToLogin()) } }
0
Kotlin
0
1
17b668a88ed135ebf953ce1846ecac76172df4af
1,752
AndroidTodo
MIT License
src/main/kotlin/org/example/projectnu/account/service/AccountService.kt
hsyoon2261
810,274,541
false
{"Kotlin": 117256, "Dockerfile": 111}
package org.example.projectnu.account.service import org.example.projectnu.account.dto.request.RegisterAccountRequestDto import org.example.projectnu.account.dto.request.SignInRequestDto import org.example.projectnu.account.dto.response.AccountResponseDto import org.example.projectnu.account.dto.response.SignInResponseDto import org.example.projectnu.account.entity.Account import org.example.projectnu.account.repository.AccountRepository import org.example.projectnu.account.service.internal.AccountCore import org.example.projectnu.account.status.UserRole import org.example.projectnu.common.exception.custom.BadRequestException import org.example.projectnu.common.security.JwtTokenProvider import org.example.projectnu.common.service.SlackService import org.example.projectnu.common.util.mapper.Authorize import org.springframework.stereotype.Service @Service class AccountService( private val accountRepository: AccountRepository, private val slackService: SlackService, private val jwtTokenProvider: JwtTokenProvider ) { private val core = AccountCore(accountRepository) fun register(accountDto: RegisterAccountRequestDto): AccountResponseDto { core.validateDuplicateAccount(accountDto.loginId, accountDto.email) val account = Account.createMemberSimple(accountDto) val savedAccount = accountRepository.save(account) return Account.toResponseDto(savedAccount) } fun sendSlackMessageToAdmin(message: String) { val adminAccounts = accountRepository.findByRole(UserRole.ADMIN) if (adminAccounts.isEmpty()) { throw BadRequestException("No ADMIN user found") } adminAccounts.forEach { adminAccount -> val channel = "@${adminAccount.loginId}" slackService.sendMessage(channel, message) } } fun issueToken(account: Account, jSessionId: String): String { return jwtTokenProvider.generateToken(Authorize.getCustomUserDetails(account, jSessionId)) } fun getAdminToken(): String { val adminAccount = accountRepository.findByRole(UserRole.ADMIN).firstOrNull() ?: throw BadRequestException("No ADMIN user found") return issueToken(adminAccount, "ALL_PASS") } fun getAccountByUserName(username: String): Account? { return accountRepository.findByLoginId(username) } fun signIn(signInRequest: SignInRequestDto, jSessionId: String): SignInResponseDto { val account = getAccountByUserName(signInRequest.loginId) ?: throw BadRequestException("Account with login ID '${signInRequest.loginId}' does not exist") val decryptedPassword = core.getDecryptedPassword(account) if (decryptedPassword != signInRequest.password) { throw BadRequestException("Invalid password") } val jwtToken = issueToken(account, jSessionId) return SignInResponseDto(jwtToken = jwtToken) } }
0
Kotlin
0
0
fbd21a364286c8b5fce5f9b068baa8340d86d047
2,954
ProjectNU
MIT License
app/src/main/java/com/skdev/ytlivevideo/ui/broadcastPreview/ViewModel.kt
SKrotkih
296,559,252
false
null
package com.skdev.ytlivevideo.ui.broadcastPreview import androidx.lifecycle.ViewModel class ViewModel : ViewModel() { var broadcastId: String? = null companion object { private val TAG = ViewModel::class.java.name } }
2
null
4
6
d8f1ba000b3da50ca374359ca8f25b1154a12fd1
241
YTLiveVideo-Android
MIT License
app/src/main/java/com/test/project/data/remote/entity/ApiEvent.kt
Petrov-Daniil
568,047,081
false
null
package com.test.project.data.remote.entity import com.test.project.domain.entity.Event import com.squareup.moshi.Json import com.squareup.moshi.JsonClass @JsonClass(generateAdapter = true) data class ApiEvent( @Json(name = "id") val id: Int?, @Json(name = "title") val title: String?, @Json(name = "date") val date: String?, @Json(name = "place") val place: String?, @Json(name = "description") val description: String?, @Json(name = "imageUrl") val imageUrl: String?, @Json(name = "firebaseId") val firebaseId: String?, ) fun ApiEvent.toEvents() = Event( id = this.id ?: -1, title = this.title ?: "", date = this.date ?: "", place = this.place ?: "", description = this.description ?: "", imageUrl = this.imageUrl ?: "", firebaseId = this.firebaseId ?: "", ) fun ApiEvent.toApiEventsDatabase() = ApiEventDatabase( id = this.id ?: -1, title = this.title ?: "", date = this.date ?: "", place = this.place ?: "", description = this.description ?: "", imageUrl = this.imageUrl ?: "", firebaseId = this.firebaseId ?: "", )
0
Kotlin
0
0
1533fce24e71c4702b9555cf1c8e79557163d31a
1,136
Events
MIT License
AndroidXCI/ftlModelBuilder/src/main/kotlin/dev/androidx/ci/codegen/Dtos.kt
androidx
363,980,005
false
{"Kotlin": 385292}
/* * Copyright 2021 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package dev.androidx.ci.codegen import com.squareup.moshi.Json import com.squareup.moshi.JsonAdapter import com.squareup.moshi.JsonReader import com.squareup.moshi.JsonWriter import com.squareup.moshi.Moshi import com.squareup.moshi.Types import java.lang.reflect.ParameterizedType import java.lang.reflect.Type import java.util.SortedMap import java.util.TreeMap // see: https://developers.google.com/discovery/v1/reference/apis /** * The root discovery class */ internal class DiscoveryDto( val schemas: SortedMap<String, SchemaDto> ) /** * Represents the Schema for a single model */ internal data class SchemaDto( val id: String, /** * https://tools.ietf.org/html/draft-zyp-json-schema-03#section-5.1 */ val type: String, val description: String? = null, // discovery documents are not stable hence we keep properties // sorted by name. val properties: SortedMap<String, PropertyDto>? = null ) { fun isObject() = type == "object" } internal data class PropertyDto( val description: String? = null, val type: String?, @Json(name = "\$ref") val ref: String? = null, val enum: List<String>? = null, val enumDescriptions: List<String>? = null, val items: PropertyDto? = null, val format: String? = null ) /** * A moshi adapter for generic SortedMaps that delegates to moshi's map * adapter. */ internal class SortedMapAdapter<K, V>( private val mapAdapter: JsonAdapter<Map<K, V>> ) : JsonAdapter<SortedMap<K, V>>() { override fun fromJson(reader: JsonReader): SortedMap<K, V>? { val map = mapAdapter.fromJson(reader) ?: return null return TreeMap(map) } override fun toJson(writer: JsonWriter, value: SortedMap<K, V>?) { mapAdapter.toJson(value) } companion object { val FACTORY = object : Factory { override fun create( type: Type, annotations: MutableSet<out Annotation>, moshi: Moshi ): JsonAdapter<*>? { if (annotations.isNotEmpty()) return null val rawType: Class<*> = Types.getRawType(type) if (rawType != SortedMap::class.java) return null if (type is ParameterizedType) { val key = type.actualTypeArguments[0] val value = type.actualTypeArguments[1] val mapType = Types.newParameterizedType( Map::class.java, key, value ) return SortedMapAdapter<Any, Any>(moshi.adapter(mapType)) } return null } } } }
5
Kotlin
5
15
7b847e142b1068482450bc3fd9e35349b154884d
3,339
androidx-ci-action
Apache License 2.0
app/src/main/java/com/hd/charts/app/demo/pie/PieChartStyleItems.kt
dautovicharis
738,676,725
false
{"Kotlin": 177440}
package com.hd.charts.app.demo.pie import androidx.compose.runtime.Composable import com.hd.charts.app.ui.composable.TableItems import com.hd.charts.app.ui.composable.getTableItems import com.hd.charts.style.PieChartDefaults import com.hd.charts.style.PieChartStyle object PieChartStyleItems { @Composable fun default(): TableItems { val style = PieChartDefaults.style() return pieChartTableItems(style) } @Composable fun custom(): TableItems { val style = PieChartDemoStyle.custom() return pieChartTableItems(style) } } @Composable private fun pieChartTableItems(currentStyle: PieChartStyle): TableItems { return getTableItems( currentStyle = currentStyle, defaultStyle = PieChartDefaults.style(), ) }
7
Kotlin
4
88
e250bdfc52a3d91b3b8ef254261f69027c3f6b82
787
Charts
MIT License
app/src/main/java/eu/kanade/presentation/more/onboarding/StorageStep.kt
mihonapp
743,704,912
false
{"Kotlin": 2940843}
package eu.kanade.presentation.more.onboarding import android.content.ActivityNotFoundException import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.padding import androidx.compose.material3.HorizontalDivider import androidx.compose.material3.MaterialTheme import androidx.compose.material3.Text import androidx.compose.runtime.Composable import androidx.compose.runtime.LaunchedEffect import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.setValue import androidx.compose.ui.Modifier import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.platform.LocalUriHandler import androidx.compose.ui.unit.dp import eu.kanade.presentation.more.settings.screen.SettingsDataScreen import eu.kanade.tachiyomi.util.system.toast import kotlinx.coroutines.flow.collectLatest import tachiyomi.domain.storage.service.StoragePreferences import tachiyomi.i18n.MR import tachiyomi.presentation.core.components.material.Button import tachiyomi.presentation.core.components.material.padding import tachiyomi.presentation.core.i18n.stringResource import uy.kohesive.injekt.Injekt import uy.kohesive.injekt.api.get internal class StorageStep : OnboardingStep { private val storagePref = Injekt.get<StoragePreferences>().baseStorageDirectory() private var _isComplete by mutableStateOf(false) override val isComplete: Boolean get() = _isComplete @Composable override fun Content() { val context = LocalContext.current val handler = LocalUriHandler.current val pickStorageLocation = SettingsDataScreen.storageLocationPicker(storagePref) Column( modifier = Modifier.padding(16.dp), verticalArrangement = Arrangement.spacedBy(MaterialTheme.padding.small), ) { Text( stringResource( MR.strings.onboarding_storage_info, stringResource(MR.strings.app_name), SettingsDataScreen.storageLocationText(storagePref), ), ) Button( modifier = Modifier.fillMaxWidth(), onClick = { try { pickStorageLocation.launch(null) } catch (e: ActivityNotFoundException) { context.toast(MR.strings.file_picker_error) } }, ) { Text(stringResource(MR.strings.onboarding_storage_action_select)) } HorizontalDivider( modifier = Modifier.padding(vertical = 8.dp), color = MaterialTheme.colorScheme.onPrimaryContainer, ) Text(stringResource(MR.strings.onboarding_storage_help_info, stringResource(MR.strings.app_name))) Button( modifier = Modifier.fillMaxWidth(), onClick = { handler.openUri(SettingsDataScreen.HELP_URL) }, ) { Text(stringResource(MR.strings.onboarding_storage_help_action)) } } LaunchedEffect(Unit) { storagePref.changes() .collectLatest { _isComplete = storagePref.isSet() } } } }
280
Kotlin
447
9,867
f3a2f566c8a09ab862758ae69b43da2a2cd8f1db
3,412
mihon
Apache License 2.0
app/src/main/java/com/example/bookdiscover/result/ResultFragment.kt
Tyler-CY
509,632,541
false
null
package com.example.bookdiscover.result import android.os.Bundle import androidx.fragment.app.Fragment import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.TextView import androidx.constraintlayout.widget.ConstraintSet import androidx.core.view.isVisible import androidx.fragment.app.activityViewModels import com.example.bookdiscover.databinding.FragmentResultBinding /** * The main fragment used in ResultActivity */ class ResultFragment : Fragment() { // ResultViewModel shared by other volume fragments and ResultActivity private val sharedViewModel: ResultViewModel by activityViewModels() override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View { // Data-binding with XML val binding = FragmentResultBinding.inflate(inflater) binding.apply { // ResultViewModel determines the lifecycle of the binding. lifecycleOwner = viewLifecycleOwner viewModel = sharedViewModel } sharedViewModel.items.observe(this) { val dataset = sharedViewModel.items.value!! if (dataset.isNotEmpty()){ binding.resultLayout.removeViewAt(0) val recyclerView = binding.recyclerView binding.recyclerView.isVisible = true recyclerView.adapter = ResultAdapter([email protected]!!, dataset) recyclerView.setHasFixedSize(true) } else { binding.recyclerView.isVisible = false val textView = TextView(activity!!) textView.id = View.generateViewId() textView.text = "Loading..." textView.textSize = 24F binding.resultLayout.addView(textView, 0) // Sets the textView to the middle by using ConstraintSet val constraintSet = ConstraintSet() constraintSet.clone(binding.resultLayout) constraintSet.connect(textView.id, ConstraintSet.TOP, binding.resultLayout.id, ConstraintSet.TOP) constraintSet.connect(textView.id, ConstraintSet.START, binding.resultLayout.id, ConstraintSet.START) constraintSet.connect(textView.id, ConstraintSet.END, binding.resultLayout.id, ConstraintSet.END) constraintSet.connect(textView.id, ConstraintSet.BOTTOM, binding.resultLayout.id, ConstraintSet.BOTTOM) constraintSet.applyTo(binding.resultLayout) } } // Inflate the layout for this fragment return binding.root } }
0
Kotlin
0
0
7f6febfe9c7aefc9aa6bfeee52a0607df5504175
2,709
Book-Discover
MIT License
z2-schematic-kotlin-plugin/src/hu/simplexion/z2/schematic/kotlin/ir/util/SchematicFunctionCache.kt
spxbhuhb
665,349,157
false
null
package hu.simplexion.z2.schematic.kotlin.ir.util import hu.simplexion.z2.schematic.kotlin.ir.FDF_ANNOTATION_FIELD_CLASS_INDEX import hu.simplexion.z2.schematic.kotlin.ir.SchematicPluginContext import org.jetbrains.kotlin.ir.expressions.IrCall import org.jetbrains.kotlin.ir.expressions.IrClassReference import org.jetbrains.kotlin.ir.expressions.IrConstructorCall import org.jetbrains.kotlin.ir.symbols.IrConstructorSymbol import org.jetbrains.kotlin.ir.symbols.IrSimpleFunctionSymbol import org.jetbrains.kotlin.ir.symbols.IrSymbol import org.jetbrains.kotlin.ir.types.IrType import org.jetbrains.kotlin.ir.types.getClass import org.jetbrains.kotlin.ir.util.primaryConstructor /** * A cache that stores the type of each function the plugin encounters. * This hopefully speeds up the compilation as we don't have to check * the annotations on each function again and again. */ class SchematicFunctionCache( val pluginContext: SchematicPluginContext ) { val types = mutableMapOf<IrSymbol, SchematicFunctionType>() val fieldClasses = mutableMapOf<IrSymbol, FieldClassEntry>() class FieldClassEntry( val type : IrType, val constructor : IrConstructorSymbol ) operator fun get(call: IrCall): SchematicFunctionType = get(call.symbol) operator fun get(symbol: IrSimpleFunctionSymbol): SchematicFunctionType { return types.getOrPut(symbol) { add(symbol) } } fun getFieldClass(symbol : IrSymbol) : FieldClassEntry { return checkNotNull(fieldClasses[symbol]) { "missing field class for $symbol"} } fun add(symbol: IrSimpleFunctionSymbol): SchematicFunctionType { val function = symbol.owner val annotations = function.annotations if (annotations.isEmpty()) return SchematicFunctionType.Other for (annotation in function.annotations) { when (annotation.symbol) { pluginContext.fdfAnnotationConstructor -> return add(symbol, annotation) pluginContext.dtfAnnotationConstructor -> return SchematicFunctionType.DefinitionTransform pluginContext.safAnnotationConstructor -> return SchematicFunctionType.SchematicAccess } } return SchematicFunctionType.Other } fun add(symbol: IrSimpleFunctionSymbol, annotation: IrConstructorCall): SchematicFunctionType { val fieldClassExpression = annotation.getValueArgument(FDF_ANNOTATION_FIELD_CLASS_INDEX) check(fieldClassExpression is IrClassReference) { "FDF annotation parameter is not a class reference" } val classType = fieldClassExpression.classType val constructor = checkNotNull(classType.getClass()?.primaryConstructor?.symbol) { "missing field class constructor for $classType" } fieldClasses[symbol] = FieldClassEntry(classType, constructor) return SchematicFunctionType.FieldDefinition } }
0
Kotlin
0
0
2276929941f1b87f8070e1c3e6e7d346470bc872
2,902
z2-schematic
Apache License 2.0
z2-schematic-kotlin-plugin/src/hu/simplexion/z2/schematic/kotlin/ir/util/SchematicFunctionCache.kt
spxbhuhb
665,349,157
false
null
package hu.simplexion.z2.schematic.kotlin.ir.util import hu.simplexion.z2.schematic.kotlin.ir.FDF_ANNOTATION_FIELD_CLASS_INDEX import hu.simplexion.z2.schematic.kotlin.ir.SchematicPluginContext import org.jetbrains.kotlin.ir.expressions.IrCall import org.jetbrains.kotlin.ir.expressions.IrClassReference import org.jetbrains.kotlin.ir.expressions.IrConstructorCall import org.jetbrains.kotlin.ir.symbols.IrConstructorSymbol import org.jetbrains.kotlin.ir.symbols.IrSimpleFunctionSymbol import org.jetbrains.kotlin.ir.symbols.IrSymbol import org.jetbrains.kotlin.ir.types.IrType import org.jetbrains.kotlin.ir.types.getClass import org.jetbrains.kotlin.ir.util.primaryConstructor /** * A cache that stores the type of each function the plugin encounters. * This hopefully speeds up the compilation as we don't have to check * the annotations on each function again and again. */ class SchematicFunctionCache( val pluginContext: SchematicPluginContext ) { val types = mutableMapOf<IrSymbol, SchematicFunctionType>() val fieldClasses = mutableMapOf<IrSymbol, FieldClassEntry>() class FieldClassEntry( val type : IrType, val constructor : IrConstructorSymbol ) operator fun get(call: IrCall): SchematicFunctionType = get(call.symbol) operator fun get(symbol: IrSimpleFunctionSymbol): SchematicFunctionType { return types.getOrPut(symbol) { add(symbol) } } fun getFieldClass(symbol : IrSymbol) : FieldClassEntry { return checkNotNull(fieldClasses[symbol]) { "missing field class for $symbol"} } fun add(symbol: IrSimpleFunctionSymbol): SchematicFunctionType { val function = symbol.owner val annotations = function.annotations if (annotations.isEmpty()) return SchematicFunctionType.Other for (annotation in function.annotations) { when (annotation.symbol) { pluginContext.fdfAnnotationConstructor -> return add(symbol, annotation) pluginContext.dtfAnnotationConstructor -> return SchematicFunctionType.DefinitionTransform pluginContext.safAnnotationConstructor -> return SchematicFunctionType.SchematicAccess } } return SchematicFunctionType.Other } fun add(symbol: IrSimpleFunctionSymbol, annotation: IrConstructorCall): SchematicFunctionType { val fieldClassExpression = annotation.getValueArgument(FDF_ANNOTATION_FIELD_CLASS_INDEX) check(fieldClassExpression is IrClassReference) { "FDF annotation parameter is not a class reference" } val classType = fieldClassExpression.classType val constructor = checkNotNull(classType.getClass()?.primaryConstructor?.symbol) { "missing field class constructor for $classType" } fieldClasses[symbol] = FieldClassEntry(classType, constructor) return SchematicFunctionType.FieldDefinition } }
0
Kotlin
0
0
2276929941f1b87f8070e1c3e6e7d346470bc872
2,902
z2-schematic
Apache License 2.0
app/src/main/kotlin/br/pedroso/citieslist/features/citiessearch/CitiesSearchViewModelEvent.kt
felipepedroso
393,728,785
false
{"Kotlin": 58545}
package br.pedroso.citieslist.features.citiessearch import br.pedroso.citieslist.domain.entities.City sealed class CitiesSearchViewModelEvent { data class NavigateToMapScreen(val cityToFocus: City) : CitiesSearchViewModelEvent() }
0
Kotlin
0
0
be93f2f25932882616c817c7dd5c66b254e1a9f7
237
countries-list
MIT License
app/src/main/java/io/github/wulkanowy/ui/modules/timetable/completed/CompletedLessonsErrorHandler.kt
mafineeek
297,426,962
true
{"Kotlin": 940566, "Shell": 220}
package io.github.wulkanowy.ui.modules.timetable.completed import android.content.res.Resources import com.chuckerteam.chucker.api.ChuckerCollector import io.github.wulkanowy.sdk.scrapper.exception.FeatureDisabledException import io.github.wulkanowy.ui.base.ErrorHandler import javax.inject.Inject class CompletedLessonsErrorHandler @Inject constructor( resources: Resources, chuckerCollector: ChuckerCollector ) : ErrorHandler(resources, chuckerCollector) { var onFeatureDisabled: () -> Unit = {} override fun proceed(error: Throwable) { when (error) { is FeatureDisabledException -> onFeatureDisabled() else -> super.proceed(error) } } override fun clear() { super.clear() onFeatureDisabled = {} } }
0
null
0
0
b0b3ccfd530e2b450804c194365b4e4fe225c754
791
wulkanowy
Apache License 2.0
src/main/kotlin/CConnection_A_A.kt
argcc
777,572,651
false
{"Kotlin": 606554}
package org.example var Connection_A_A: CConnection_A_A? = null class CConnection_A_A(param_1: Int) : CConnection_A() { init { field_0x4 = 0xdec0ad07u FUN_004142f0() FUN_004377d0(0, C_0079b270.GetTypeId(C_0073bbf8::class), ::FUN_0041adb0) FUN_004377d0(1, C_0079b270.GetTypeId(C_0073bbf8::class), ::FUN_0041ad80) FUN_004377d0(2, C_0079b270.GetTypeId(C_0073bbf8::class), ::FUN_0041b0c0) FUN_004377d0(0, C_0079b270.GetTypeId(C_0073bc28::class), ::FUN_0041b1c0) FUN_004377d0(0, C_0079b270.GetTypeId(C_0073bc40::class), ::FUN_0041b2a0) FUN_004377d0(0, C_0079b270.GetTypeId(C_0073bc58::class), ::FUN_0041b690) FUN_004377d0(2, C_0079b270.GetTypeId(C_0073bc58::class), ::FUN_0041b720) FUN_004377d0(0, C_0079b270.GetTypeId(C_0073bdd0::class), ::FUN_0041b7a0) FUN_004377d0(1, C_0079b270.GetTypeId(C_0073bdd0::class), ::FUN_0041b970) FUN_004377d0(2, C_0079b270.GetTypeId(C_0073bdd0::class), ::FUN_0041ba30) FUN_004377d0(0, C_0079b270.GetTypeId(C_0073bd78::class), ::FUN_0041ba20) FUN_004377d0(1, C_0079b270.GetTypeId(C_0073bd78::class), ::FUN_0041ba20) field_0x2588 = 0 field_0x25e0 = param_1 field_0x25dc = 8 FUN_00418530()//TODO field_0x256c = 0.0f field_0x2570 = 0 field_0x2574 = 0 field_0x25e4 = 0 field_0x25e8 = 0 field_0x25ec = 0 field_0x25f0 = 0 field_0x25f4 = 0 } override fun HandleMessages(delta: Double) { super.HandleMessages(delta) list_12.forEach { //TODO } list_9.forEach { //TODO } if (field_0x2570.toInt() != 0) { field_0x256c -= delta.toFloat() if (field_0x256c < 0.0f) { field_0x256c = 20.0f if (Settings.MasterServerName.isNotEmpty()) { FUN_0041aa10()//TODO } } } } fun FUN_00418530() { //TODO } fun FUN_0041aa10() { //TODO } } fun FUN_0041adb0(param_1: Any?, param_2: Any?) {} //TODO fun FUN_0041ad80(param_1: Any?, param_2: Any?) {} //TODO fun FUN_0041b0c0(param_1: Any?, param_2: Any?) {} //TODO fun FUN_0041b1c0(param_1: Any?, param_2: Any?) {} //TODO fun FUN_0041b2a0(param_1: Any?, param_2: Any?) {} //TODO fun FUN_0041b690(param_1: Any?, param_2: Any?) {} //TODO fun FUN_0041b720(param_1: Any?, param_2: Any?) {} //TODO fun FUN_0041b7a0(param_1: Any?, param_2: Any?) {} //TODO fun FUN_0041b970(param_1: Any?, param_2: Any?) {} //TODO fun FUN_0041ba30(param_1: Any?, param_2: Any?) {} //TODO fun FUN_0041ba20(param_1: Any?, param_2: Any?) {} //TODO
0
Kotlin
0
0
61ecbe17303609df33cc7593051b6300417f9bd7
2,712
ei_reverse_consp
MIT License
shared/src/commonMain/kotlin/com/mocoding/pokedex/ui/theme/Color.kt
MohamedRejeb
606,436,499
false
null
package app.duss.easyproject.presentation.theme import androidx.compose.ui.graphics.Color val Black = Color(0xFF090f0b) val Green300 = Color(0xFF2EB688) val Green400 = Color(0xFF145526) val Green500 = Color(0xFF046D4A) val Red300 = Color(0xFFF33736) val Red400 = Color(0xFFcb290b) val Red500 = Color(0xFF9C2221) val Blue300 = Color(0xFF54B1DF) val Blue500 = Color(0xFF1E3DA8) val Yellow300 = Color(0xFFF1A22C) val Yellow400 = Color(0xFFfaae41) val Yellow500 = Color(0xFFCB5C0D) val Blue400 = Color(0xFF4572E8) val LightGray400 = Color(0xFFb8b6b3) val DarkGray400 = Color(0xFF3e4047) val Gray400 = Color(0xFF595C61) val Bug = Color(0xFF179A55) val Dark = Color(0xFF040706) val Dragon = Color(0xFF378A94) val Electric = Color(0xFFE0E64B) val Fairy = Color(0xFF9E1A44) val Fire = Color(0xFFB22328) val Flying = Color(0xFF90B1C5) val Ghost = Color(0xFF363069) val Ice = Color(0xFF7ECFF2) val Poison = Color(0xFF642785) val Psychic = Color(0xFFAC296B) val Rock = Color(0xFF4B190E) val Steel = Color(0xFF5C756D) val Water = Color(0xFF2648DC) val Fighting = Color(0xFF9F422A) val Grass = Color(0xFF007C42) val Ground = Color(0xFFAD7235)
4
null
48
569
e13c46fdcff7b21353019da9a85438e2088c529d
1,140
Pokedex
Apache License 2.0
FinalProject/app/src/main/java/com/example/finalproject/adapters/AutocompleteListAdapter.kt
omercanbaltaci
425,016,312
false
{"Kotlin": 53999}
package com.example.finalproject.adapters import android.content.Context import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.ArrayAdapter import androidx.annotation.LayoutRes import androidx.databinding.DataBindingUtil import com.example.finalproject.R import com.example.finalproject.base.BaseViewItemClickListener import com.example.finalproject.databinding.AutocompleteListItemBinding import com.example.finalproject.ui.weatherapp.model.Autocomplete open class AutocompleteListAdapter( context: Context, list: List<Autocomplete> ) : ArrayAdapter<Autocomplete>( context, ViewHolder.LAYOUT, list ) { private var itemClickListener: BaseViewItemClickListener<Autocomplete>? = null constructor( context: Context, list: List<Autocomplete>, itemClickListener: BaseViewItemClickListener<Autocomplete> ) : this(context, list) { this.itemClickListener = itemClickListener } override fun getView(position: Int, convertView: View?, parent: ViewGroup): View { return onBindView(parent, position) } override fun getDropDownView(position: Int, convertView: View?, parent: ViewGroup): View { return onBindView(parent, position) } private fun onBindView(parent: ViewGroup, position: Int): View { val autocomplete = getItem(position) val dataBinding: AutocompleteListItemBinding = DataBindingUtil.inflate( LayoutInflater.from(context), ViewHolder.LAYOUT, parent, false ) dataBinding.autocomplete = autocomplete dataBinding.root.setOnClickListener { if (autocomplete != null) { itemClickListener!!.onItemClicked(autocomplete, it.id) } } dataBinding.add.setOnClickListener { if (autocomplete != null) { itemClickListener!!.onItemClicked(autocomplete, it.id) } } dataBinding.info.setOnClickListener { if (autocomplete != null) { itemClickListener!!.onItemClicked(autocomplete, it.id) } } return dataBinding.root } private class ViewHolder { companion object { @LayoutRes val LAYOUT = R.layout.autocomplete_list_item } } }
0
Kotlin
0
4
598512407c648fb7b7dc455b418d03bb3fc7159b
2,385
weather-app
MIT License
app/src/main/java/com/pandacorp/timeui/presentation/utils/countdownview/Utils.kt
MrRuslanYT
502,582,674
false
null
package com.pandacorp.timeui.presentation.utils.countdownview import android.content.Context internal object Utils { fun dp2px(context: Context?, dpValue: Float): Int { if (dpValue <= 0) return 0 val scale = context!!.resources.displayMetrics.density return (dpValue * scale + 0.5f).toInt() } fun sp2px(context: Context?, spValue: Float): Float { if (spValue <= 0) return 0f val scale = context!!.resources.displayMetrics.scaledDensity return spValue * scale } fun formatNum(time: Int): String { return if (time < 10) "0$time" else time.toString() } fun formatMillisecond(millisecond: Int): String { val retMillisecondStr: String = if (millisecond > 99) { (millisecond / 10).toString() } else if (millisecond <= 9) { "0$millisecond" } else { millisecond.toString() } return retMillisecondStr } }
0
Kotlin
0
0
8c9c0bf9c699074e6a8fb8b8bea108a5ceda0ce1
964
TimeUI
Apache License 2.0
kaspresso/src/test/java/com/kaspersky/kaspresso/flakysafety/scalpel/ScalpelSwitcherTest.kt
KasperskyLab
208,070,025
false
null
package com.kaspersky.kaspresso.flakysafety.scalpel import com.google.common.truth.Truth.assertThat import org.junit.Test class ScalpelSwitcherTest { @Test fun commonTest() { val scalpelSwitcher = ScalpelSwitcher() var takeScalpCount = 0 scalpelSwitcher.attemptTakeScalp( actionToDetermineScalp = { false }, actionToTakeScalp = { takeScalpCount++ } ) assertThat(takeScalpCount).isEqualTo(0) scalpelSwitcher.attemptTakeScalp( actionToDetermineScalp = { true }, actionToTakeScalp = { takeScalpCount++ } ) scalpelSwitcher.attemptTakeScalp( actionToDetermineScalp = { true }, actionToTakeScalp = { takeScalpCount++ } ) assertThat(takeScalpCount).isEqualTo(1) scalpelSwitcher.attemptTakeScalp( actionToDetermineScalp = { false }, actionToTakeScalp = { takeScalpCount++ } ) assertThat(takeScalpCount).isEqualTo(1) scalpelSwitcher.attemptRestoreScalp { takeScalpCount-- } scalpelSwitcher.attemptRestoreScalp { takeScalpCount-- } assertThat(takeScalpCount).isEqualTo(0) scalpelSwitcher.attemptTakeScalp( actionToDetermineScalp = { false }, actionToTakeScalp = { takeScalpCount++ } ) assertThat(takeScalpCount).isEqualTo(0) scalpelSwitcher.attemptTakeScalp( actionToDetermineScalp = { true }, actionToTakeScalp = { takeScalpCount++ } ) assertThat(takeScalpCount).isEqualTo(1) scalpelSwitcher.attemptTakeScalp( actionToDetermineScalp = { true }, actionToTakeScalp = { takeScalpCount++ } ) assertThat(takeScalpCount).isEqualTo(1) scalpelSwitcher.attemptRestoreScalp { takeScalpCount-- } assertThat(takeScalpCount).isEqualTo(0) scalpelSwitcher.attemptRestoreScalp { takeScalpCount-- } assertThat(takeScalpCount).isEqualTo(0) scalpelSwitcher.attemptTakeScalp( actionToDetermineScalp = { false }, actionToTakeScalp = { takeScalpCount++ } ) assertThat(takeScalpCount).isEqualTo(0) } }
55
null
150
1,784
9c94128c744d640dcd646b86de711d2a1b9c3aa1
2,322
Kaspresso
Apache License 2.0
simple-icons/src/commonMain/kotlin/compose/icons/simpleicons/Appletv.kt
DevSrSouza
311,134,756
false
null
package compose.icons.simpleicons 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 compose.icons.SimpleIcons public val SimpleIcons.Appletv: ImageVector get() { if (_appletv != null) { return _appletv!! } _appletv = Builder(name = "Appletv", defaultWidth = 24.0.dp, defaultHeight = 24.0.dp, viewportWidth = 24.0f, viewportHeight = 24.0f).apply { path(fill = SolidColor(Color(0xFF000000)), stroke = null, strokeLineWidth = 0.0f, strokeLineCap = Butt, strokeLineJoin = Miter, strokeLineMiter = 4.0f, pathFillType = NonZero) { moveTo(20.57f, 17.735f) horizontalLineToRelative(-1.815f) lineToRelative(-3.34f, -9.203f) horizontalLineToRelative(1.633f) lineToRelative(2.02f, 5.987f) curveToRelative(0.075f, 0.231f, 0.273f, 0.9f, 0.586f, 2.012f) lineToRelative(0.297f, -0.997f) lineToRelative(0.33f, -1.006f) lineToRelative(2.094f, -6.004f) lineTo(24.0f, 8.524f) close() moveTo(15.226f, 17.669f) arcToRelative(5.76f, 5.76f, 0.0f, false, true, -1.55f, 0.207f) curveToRelative(-1.23f, 0.0f, -1.84f, -0.693f, -1.84f, -2.087f) lineTo(11.836f, 9.646f) horizontalLineToRelative(-1.063f) lineTo(10.773f, 8.532f) horizontalLineToRelative(1.121f) lineTo(11.894f, 7.081f) lineToRelative(1.476f, -0.602f) verticalLineToRelative(2.062f) horizontalLineToRelative(1.707f) verticalLineToRelative(1.113f) lineTo(13.38f, 9.654f) verticalLineToRelative(5.805f) curveToRelative(0.0f, 0.446f, 0.074f, 0.75f, 0.214f, 0.932f) curveToRelative(0.14f, 0.182f, 0.396f, 0.264f, 0.75f, 0.264f) curveToRelative(0.207f, 0.0f, 0.495f, -0.041f, 0.883f, -0.115f) close() moveTo(7.936f, 12.326f) curveToRelative(0.017f, 1.764f, 1.55f, 2.358f, 1.567f, 2.366f) curveToRelative(-0.017f, 0.042f, -0.248f, 0.842f, -0.808f, 1.658f) curveToRelative(-0.487f, 0.71f, -0.99f, 1.418f, -1.79f, 1.435f) curveToRelative(-0.783f, 0.016f, -1.03f, -0.462f, -1.93f, -0.462f) curveToRelative(-0.89f, 0.0f, -1.17f, 0.445f, -1.913f, 0.478f) curveToRelative(-0.758f, 0.025f, -1.344f, -0.775f, -1.838f, -1.484f) curveToRelative(-0.998f, -1.451f, -1.765f, -4.098f, -0.734f, -5.88f) curveToRelative(0.51f, -0.89f, 1.426f, -1.451f, 2.416f, -1.46f) curveToRelative(0.75f, -0.016f, 1.468f, 0.512f, 1.93f, 0.512f) curveToRelative(0.461f, 0.0f, 1.327f, -0.627f, 2.234f, -0.536f) curveToRelative(0.38f, 0.016f, 1.452f, 0.157f, 2.136f, 1.154f) curveToRelative(-0.058f, 0.033f, -1.278f, 0.743f, -1.27f, 2.219f) moveTo(6.468f, 7.988f) curveToRelative(0.404f, -0.495f, 0.685f, -1.18f, 0.61f, -1.864f) curveToRelative(-0.585f, 0.025f, -1.294f, 0.388f, -1.723f, 0.883f) curveToRelative(-0.38f, 0.437f, -0.71f, 1.138f, -0.619f, 1.806f) curveToRelative(0.652f, 0.05f, 1.328f, -0.338f, 1.732f, -0.825f) close() } } .build() return _appletv!! } private var _appletv: ImageVector? = null
17
null
25
571
a660e5f3033e3222e3553f5a6e888b7054aed8cd
4,063
compose-icons
MIT License
examples/server/ktor-server/src/main/kotlin/com/expediagroup/graphql/examples/server/ktor/GraphQLModule.kt
innertech
460,123,996
true
{"Kotlin": 2138595, "HTML": 20196, "JavaScript": 8667, "CSS": 297, "Dockerfile": 155}
/* * Copyright 2023 Expedia, Inc * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * 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.expediagroup.graphql.examples.server.ktor import com.expediagroup.graphql.dataloader.KotlinDataLoaderRegistryFactory import com.expediagroup.graphql.examples.server.ktor.schema.BookQueryService import com.expediagroup.graphql.examples.server.ktor.schema.CourseQueryService import com.expediagroup.graphql.examples.server.ktor.schema.HelloQueryService import com.expediagroup.graphql.examples.server.ktor.schema.LoginMutationService import com.expediagroup.graphql.examples.server.ktor.schema.UniversityQueryService import com.expediagroup.graphql.examples.server.ktor.schema.dataloaders.BookDataLoader import com.expediagroup.graphql.examples.server.ktor.schema.dataloaders.CourseDataLoader import com.expediagroup.graphql.examples.server.ktor.schema.dataloaders.UniversityDataLoader import com.expediagroup.graphql.server.ktor.GraphQL import io.ktor.server.application.Application import io.ktor.server.application.install fun Application.graphQLModule() { install(GraphQL) { schema { packages = listOf("com.expediagroup.graphql.examples.server") queries = listOf( HelloQueryService(), BookQueryService(), CourseQueryService(), UniversityQueryService(), ) mutations = listOf( LoginMutationService() ) } engine { dataLoaderRegistryFactory = KotlinDataLoaderRegistryFactory( UniversityDataLoader, CourseDataLoader, BookDataLoader ) } server { contextFactory = CustomGraphQLContextFactory() } } }
0
Kotlin
0
0
5149be9dc46a512ff6ff11119470e7d116d77655
2,254
graphql-kotlin
Apache License 2.0
plugin/src/org/jetbrains/cabal/psi/FullVersionConstraint.kt
ysnrkdm
22,723,736
true
{"Kotlin": 416930, "Java": 156242, "Haskell": 4316}
package org.jetbrains.cabal.psi import com.intellij.lang.ASTNode import com.intellij.extapi.psi.ASTWrapperPsiElement import org.jetbrains.cabal.psi.PropertyValue public class FullVersionConstraint(node: ASTNode) : ASTWrapperPsiElement(node), PropertyValue { public fun getBaseName() : String = getFirstChild()!!.getText()!! public fun getConstraint() : ComplexVersionConstraint? { var nodes = getChildren() for (node in nodes) { if (node is ComplexVersionConstraint) { return node } } return null } }
0
Kotlin
0
0
74b1055a5207d5910a05e68073fd4384eb4b44a3
588
haskell-idea-plugin
Apache License 2.0
library/src/main/java/com/bluesir9/asutil/library/ui/snackbar/SnackbarViewModel.kt
Bluesir9
235,258,656
false
null
package com.bluesir9.asutil.library.ui.snackbar import com.bluesir9.asutil.library.core.platform_element.AsutilViewModel class SnackbarViewModel : AsutilViewModel<SnackbarUiModel?>(initPlatformModel = null), Snackbar { override fun show(message: String, length: SnackbarVisibilityLength) { updateModel(SnackbarUiModel(message, length)) } fun onShown() { updateModel(null) } }
0
Kotlin
0
0
c555e4c87afab660ec06ac8a3c150dacf743473b
395
asutil
MIT License
library/src/main/java/com/bluesir9/asutil/library/ui/snackbar/SnackbarViewModel.kt
Bluesir9
235,258,656
false
null
package com.bluesir9.asutil.library.ui.snackbar import com.bluesir9.asutil.library.core.platform_element.AsutilViewModel class SnackbarViewModel : AsutilViewModel<SnackbarUiModel?>(initPlatformModel = null), Snackbar { override fun show(message: String, length: SnackbarVisibilityLength) { updateModel(SnackbarUiModel(message, length)) } fun onShown() { updateModel(null) } }
0
Kotlin
0
0
c555e4c87afab660ec06ac8a3c150dacf743473b
395
asutil
MIT License
newm-server/src/main/kotlin/io/newm/server/features/song/model/SongReceipt.kt
projectNEWM
447,979,150
false
{"Kotlin": 2056034, "HTML": 138371, "Shell": 2775, "Dockerfile": 2535, "Procfile": 60}
package io.newm.server.features.song.model import io.newm.shared.serialization.LocalDateTimeSerializer import io.newm.shared.serialization.UUIDSerializer import kotlinx.serialization.Serializable import java.time.LocalDateTime import java.util.UUID @Serializable data class SongReceipt( @Serializable(with = UUIDSerializer::class) val id: UUID? = null, @Serializable(with = LocalDateTimeSerializer::class) val createdAt: LocalDateTime, @Serializable(with = UUIDSerializer::class) val songId: UUID, val adaPrice: Long, val usdPrice: Long, val adaDspPrice: Long, val usdDspPrice: Long, val adaMintPrice: Long, val usdMintPrice: Long, val adaCollabPrice: Long, val usdCollabPrice: Long, val usdAdaExchangeRate: Long, )
0
Kotlin
4
9
23c0c46b779345bbeb239ad43e33bead2312ab49
778
newm-server
Apache License 2.0