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
jstruct_processor/src/main/kotlin/com/lingyun/lib/jstrcut/annotation/processor/ElementUtils.kt
lingyun-x
352,528,086
false
null
package com.lingyun.lib.jstrcut.annotation.processor import com.lingyun.lib.jstruct.annotation.Embed import com.lingyun.lib.jstruct.annotation.Ignore import javax.annotation.processing.ProcessingEnvironment import javax.lang.model.element.Element import javax.lang.model.element.ElementKind import javax.lang.model.element.TypeElement import javax.lang.model.element.VariableElement import javax.lang.model.type.TypeKind import javax.lang.model.type.TypeMirror import javax.tools.Diagnostic /* * Created by mc_luo on 2021/4/2 . * Copyright (c) 2021 The LingYun Authors. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ fun Element.hasAnnotation(annotationTypeMirror: TypeMirror): Boolean { return annotationMirrors.firstOrNull { it.annotationType == annotationTypeMirror } != null } fun Element.hasEmbedAnnotation(processingEnv: ProcessingEnvironment): Boolean { val embenElement: Element = processingEnv.elementUtils.getTypeElement( Embed::class.java.name ) val embenType = embenElement.asType() return hasAnnotation(embenType) } fun getElementStructFields( processingEnv: ProcessingEnvironment, type: TypeElement, ves: MutableList<VariableElement> ) { val superTypeElement = com.lingyun.lib.jstrcut.annotation.processor.getSuperclass(processingEnv, type) if (superTypeElement != null) { com.lingyun.lib.jstrcut.annotation.processor.getElementStructFields(processingEnv, superTypeElement, ves) } val ignoreElement: Element = processingEnv.elementUtils.getTypeElement( Ignore::class.java.name ) val ignoreType = ignoreElement.asType() val fieldElements = try { type.enclosedElements .filter { it.kind == ElementKind.FIELD } .filter { it is VariableElement } .filter { val annotationMirrors = it.annotationMirrors annotationMirrors.firstOrNull { it.annotationType == ignoreType } == null } } catch (e: Exception) { processingEnv.messager.printMessage( Diagnostic.Kind.NOTE, "invoke fields fail:${e} \r\n" ) throw e } ves.addAll(fieldElements.map { it as VariableElement }) } private fun getSuperclass( processingEnv: ProcessingEnvironment, type: TypeElement ): TypeElement? { return if (type.superclass.kind == TypeKind.DECLARED) { val superclass = processingEnv.getTypeUtils().asElement(type.superclass) as TypeElement //skip interface if (superclass.kind.isInterface) { return null } val name = superclass.qualifiedName.toString() if (name.startsWith("java.") || name.startsWith("javax.") || name.startsWith("android.") ) { // Skip system classes, this just degrades performance null } else { superclass } } else { null } }
0
Kotlin
0
0
0530c8bf93259b556b8b65e92d400611a03efae1
3,463
jstruct_annotation_processer
Apache License 2.0
presentation/src/main/kotlin/com/lukelorusso/presentation/ui/preview/Preview.kt
lukelorusso
277,556,469
false
{"Kotlin": 168897}
package com.lukelorusso.presentation.ui.preview import androidx.compose.foundation.* import androidx.compose.foundation.layout.* import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.material.Surface import androidx.compose.material.Text import androidx.compose.runtime.Composable import androidx.compose.runtime.getValue import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.graphics.* import androidx.compose.ui.platform.LocalDensity import androidx.compose.ui.res.* import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.text.style.TextOverflow import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.sp import androidx.lifecycle.compose.collectAsStateWithLifecycle import com.lukelorusso.presentation.R import com.lukelorusso.presentation.error.ErrorMessageFactory import com.lukelorusso.presentation.extensions.* import com.lukelorusso.presentation.ui.base.BottomSheetUpperLine import com.lukelorusso.presentation.ui.base.FAB import com.lukelorusso.presentation.ui.error.ErrorAlertDialog import com.lukelorusso.domain.model.Color as ColorModel @Composable fun Preview( viewModel: PreviewViewModel, errorMessageFactory: ErrorMessageFactory ) { val uiState by viewModel.uiState.collectAsStateWithLifecycle() if (uiState.contentState.isError) { ErrorAlertDialog( message = uiState.contentState.error ?.let { errorMessageFactory.getLocalizedMessage(it) }, dismissCallback = viewModel::dismissError ) } Surface( color = Color.Transparent // AppCardDialogFragment already implements a custom theme ) { Box( modifier = Modifier .fillMaxWidth() ) { BottomSheetUpperLine( modifier = Modifier .align(Alignment.TopCenter) ) uiState.color?.let { colorModel -> Column( modifier = Modifier .fillMaxWidth() ) { val color = colorModel.originalColorHex().parseToColor() Canvas( modifier = Modifier .fillMaxWidth() .aspectRatio(1f) .padding(64.dp) .border( 2.dp, colorResource(id = R.color.text_color), RectangleShape ), onDraw = { drawRect(color = colorModel.originalColorHex().parseToColor()) } ) val description = (stringResource(id = R.string.credits) + " " + uiState.homeUrl).let { credits -> colorModel.sharableDescription(credits) } val textPopupLabel = stringResource(id = R.string.choose_an_app) val bitmapPopupLabel = stringResource(id = R.string.share_color) val size = with(LocalDensity.current) { dimensionResource(id = R.dimen.color_picker_dimens_big).roundToPx() } BottomToolBar( colorModel = colorModel, shareText = { viewModel.shareText( text = description, popupLabel = textPopupLabel ) }, shareBitmap = { viewModel.shareBitmap( bitmap = createBitmap( size, size, color.toArgb() ), description = description, popupLabel = bitmapPopupLabel ) } ) } } } } } @Composable private fun BottomToolBar( colorModel: ColorModel, shareText: () -> Unit, shareBitmap: () -> Unit ) { Box( modifier = Modifier .fillMaxWidth() ) { Column( modifier = Modifier .fillMaxWidth() .background( color = colorResource(id = R.color.black_50), shape = RoundedCornerShape(16.dp, 16.dp) ) .padding(16.dp), horizontalAlignment = Alignment.CenterHorizontally ) { Text( modifier = Modifier .clickable(onClick = shareText), color = Color.White, fontSize = 18.sp, fontWeight = FontWeight.W500, maxLines = 1, overflow = TextOverflow.Ellipsis, text = colorModel.colorName ) Spacer(modifier = Modifier.height(2.dp)) Text( modifier = Modifier .clickable(onClick = shareText), color = Color.White, fontSize = 14.sp, maxLines = 1, overflow = TextOverflow.Ellipsis, text = colorModel.originalColorHex() ) Spacer(modifier = Modifier.height(2.dp)) Text( modifier = Modifier .clickable(onClick = shareText), color = Color.White, fontSize = 14.sp, maxLines = 1, overflow = TextOverflow.Ellipsis, text = colorModel.toRGBPercentString() ) } FAB( painter = painterResource(id = R.drawable.share_white), onClick = shareBitmap ) } }
0
Kotlin
2
4
dfc73c9a5286c8a880d3fd238737a09201605058
6,065
ColorBlindClickAndroid
Apache License 2.0
agoraui/src/main/kotlin/io/agora/uikit/impl/chat/AgoraUIChatWindow.kt
AgoraIO-Community
330,886,965
false
null
package io.agora.uikit.impl.chat import android.graphics.Color import android.graphics.Rect import android.text.TextUtils import android.util.Log import android.view.* import android.view.animation.DecelerateInterpolator import android.widget.RelativeLayout import androidx.annotation.UiThread import androidx.appcompat.widget.AppCompatEditText import androidx.appcompat.widget.AppCompatImageView import androidx.appcompat.widget.AppCompatTextView import androidx.viewpager2.widget.ViewPager2 import io.agora.educontext.* import io.agora.uicomponent.UiWidgetManager import io.agora.uikit.R import io.agora.uikit.component.RoundRectButtonStateBg import io.agora.uikit.educontext.handlers.ChatHandler import io.agora.uikit.impl.AgoraAbsWidget import io.agora.uikit.impl.chat.tabs.* import java.lang.Exception /** * This widget cannot be instantiated by constructors */ class AgoraUIChatWindow : AgoraAbsWidget() { private val tag = "AgoraUIChatWindow" private val duration = 400L private lateinit var parent: ViewGroup private var width: Int = 0 private var height: Int = 0 private var left: Int = 0 private var top: Int = 0 private var shadow: Int = 0 // Specially designed to avoid recycler view having a minus height private val minHeight = 40 private val elevation = 0 private var unReadCount = 0 private lateinit var layout: RelativeLayout private lateinit var unreadText: AppCompatTextView private lateinit var closeBtn: AppCompatImageView private lateinit var muteBtn: AppCompatImageView private lateinit var contentLayout: RelativeLayout private lateinit var titleLayout: RelativeLayout private lateinit var inputLayout: RelativeLayout private var tabConfigs: List<ChatTabConfig>? = null private lateinit var tabLayout: TabLayout private lateinit var viewPager: ViewPager2 private lateinit var tabManager: TabManager private var contentWidth: Int = 0 private var contentHeight: Int = 0 private var contentTopMargin: Int = 0 private var contentLeftMargin: Int = 0 private lateinit var hideLayout: RelativeLayout private var titleLayoutHeight: Int = 0 private var inputLayoutHeight: Int = 0 var hideIconSize = 0 @Volatile private var hidden = false private var animateListener: OnChatWindowAnimateListener? = null private lateinit var edit: AppCompatEditText private lateinit var sendBtn: AppCompatTextView private val chatHandler = object : ChatHandler() { override fun onReceiveMessage(item: EduContextChatItem) { tabManager.addMessage(TabType.Public, AgoraUIChatItem.fromContextItem(item)) if (hidden) { showUnreadMessages(true) } } override fun onReceiveChatHistory(history: List<EduContextChatItem>) { val result = mutableListOf<AgoraUIChatItem>() history.forEach { item -> result.add(AgoraUIChatItem.fromContextItem(item)) } tabManager.addMessageList(TabType.Public, result, true) } override fun onReceiveConversationMessage(item: EduContextChatItem) { tabManager.addMessage(TabType.Private, AgoraUIChatItem.fromContextItem(item)) } override fun onReceiveConversationHistory(history: List<EduContextChatItem>) { val result = mutableListOf<AgoraUIChatItem>() history.forEach { item -> result.add(AgoraUIChatItem.fromContextItem(item)) } tabManager.addMessageList(TabType.Private, result, true) } override fun onChatAllowed(allowed: Boolean) { muteBtn.post { muteBtn.isActivated = !allowed } allowChat(allowed, null) } override fun onChatAllowed(allowed: Boolean, userInfo: EduContextUserInfo, operator: EduContextUserInfo?, local: Boolean) { allowChat(null, if (local) allowed else null) } } companion object { // Temporarily record current room info and is made companion // to facilitate all tabs to access. // It is currently used to record read message ids var roomInfo: EduContextRoomInfo? = null } fun setTabConfig(tabConfigs: List<ChatTabConfig>) { this.tabConfigs = tabConfigs } override fun init(parent: ViewGroup, width: Int, height: Int, left: Int, top: Int) { this.parent = parent this.width = width this.height = height this.top = top this.left = left shadow = parent.context.resources.getDimensionPixelSize(R.dimen.shadow_width) hideIconSize = parent.context.resources.getDimensionPixelSize(R.dimen.agora_message_hide_icon_size) roomInfo = getEduContext()?.roomContext()?.roomInfo() layout = LayoutInflater.from(parent.context).inflate( R.layout.agora_chat_layout, parent, false) as RelativeLayout unreadText = layout.findViewById(R.id.agora_chat_unread_text) closeBtn = layout.findViewById(R.id.agora_chat_icon_close) muteBtn = layout.findViewById(R.id.agora_chat_mute_icon) contentLayout = layout.findViewById(R.id.agora_chat_layout) titleLayout = layout.findViewById(R.id.agora_chat_title_layout) inputLayout = layout.findViewById(R.id.agora_chat_input_layout) tabLayout = layout.findViewById(R.id.agora_chat_tabs) viewPager = layout.findViewById(R.id.agora_chat_view_pager) if (tabConfigs != null) { tabManager = TabManager(tabLayout, tabConfigs!!, viewPager, getEduContext(), object : OnTabSelectedListener { override fun onTabSelected(position: Int) { resetInputMethodState() } }) tabManager.setCurrent(0) } else { Log.w(tag, "Tab configs have not been initialized before tab is created") } unreadText.visibility = View.GONE contentLayout.clipToOutline = true contentLayout.elevation = elevation.toFloat() var params = contentLayout.layoutParams as ViewGroup.MarginLayoutParams params.setMargins(shadow, shadow, shadow, shadow) contentLeftMargin = params.leftMargin contentTopMargin = params.topMargin contentWidth = width - contentLeftMargin * 2 contentHeight = height - contentTopMargin * 2 parent.addView(layout, width, height) params = layout.layoutParams as ViewGroup.MarginLayoutParams params.topMargin = top params.leftMargin = left layout.layoutParams = params titleLayoutHeight = (titleLayout.layoutParams as ViewGroup.MarginLayoutParams).height inputLayoutHeight = (inputLayout.layoutParams as ViewGroup.MarginLayoutParams).height edit = layout.findViewById(R.id.agora_chat_message_edit) edit.setOnKeyListener { view, keyCode, event -> return@setOnKeyListener if (keyCode == KeyEvent.KEYCODE_ENTER && event.action == KeyEvent.ACTION_UP) { onSendClick(view) true } else false } sendBtn = layout.findViewById(R.id.agora_chat_send_btn) sendBtn.setTextColor(Color.WHITE) sendBtn.background = RoundRectButtonStateBg( layout.resources.getDimensionPixelSize(R.dimen.agora_message_send_btn_width), layout.resources.getDimensionPixelSize(R.dimen.agora_message_send_btn_height), layout.resources.getColor(R.color.theme_blue_light), layout.resources.getColor(R.color.theme_blue_light), layout.resources.getColor(R.color.theme_blue_gray), layout.resources.getColor(R.color.theme_blue_gray), layout.resources.getColor(R.color.theme_disable), layout.resources.getColor(R.color.theme_disable), layout.resources.getDimensionPixelSize(R.dimen.stroke_small)) sendBtn.setOnClickListener { onSendClick(it) } closeBtn.setOnClickListener { if (!hidden) { hideAnimate() } } setClosable(true) hideLayout = layout.findViewById(R.id.agora_chat_hide_icon_layout) hideLayout.visibility = View.GONE hideLayout.setOnClickListener { if (hidden) { showAnimate() } } getEduContext()?.chatContext()?.addHandler(chatHandler) getWidgetManager()?.addWidget(this) } private fun onSendClick(view: View) { val content = edit.text.toString().trim() if (TextUtils.isEmpty(content)) { return } edit.setText("") getContainer()?.hideSoftInput(parent.context, view) val timestamp = System.currentTimeMillis() sendAndInsertLocalChat(content, timestamp, tabManager.getCurrentTab()) } private fun sendAndInsertLocalChat(message: String, timestamp: Long, tab: ChatTabBase?) { sendLocalChat(message, timestamp, tab)?.let { item -> tab?.onSendLocalChat(item) } } private fun sendLocalChat(message: String, timestamp: Long, tab: ChatTabBase?) : AgoraUIChatItem? { val item = when (tab) { is PublicChatTab -> { getEduContext()?.chatContext()?.sendLocalChannelMessage(message, timestamp, object : EduContextCallback<EduContextChatItemSendResult> { override fun onSuccess(target: EduContextChatItemSendResult?) { target?.let { result -> tab.onSendResult(result.fromUserId, result.messageId, result.timestamp, true) } } override fun onFailure(error: EduContextError?) { tab.onSendResult("", "", timestamp, false) } }) } is PrivateChatTab -> { getEduContext()?.chatContext()?.sendConversationMessage(message, timestamp, object : EduContextCallback<EduContextChatItemSendResult> { override fun onSuccess(target: EduContextChatItemSendResult?) { target?.let { result -> tab.onSendResult(result.fromUserId, result.messageId, timestamp, true) } } override fun onFailure(error: EduContextError?) { tab.onSendResult("", "", timestamp, false) } }) } else -> null } return item?.let{ AgoraUIChatItem.fromContextItem(it) } } private fun hideAnimate() { contentLayout.animate().setDuration(duration) .scaleX(1.0f) .setInterpolator(DecelerateInterpolator()) .setUpdateListener { if (contentLayout.height <= minHeight) { return@setUpdateListener } val fraction = it.animatedFraction val diffWidth = contentWidth * fraction val diffHeight = contentHeight * fraction val width = contentWidth - diffWidth val height = contentHeight - diffHeight var params = contentLayout.layoutParams as ViewGroup.MarginLayoutParams params.width = width.toInt() params.height = height.toInt() params.leftMargin = diffWidth.toInt() + contentLeftMargin params.topMargin = diffHeight.toInt() + contentTopMargin contentLayout.layoutParams = params animateListener?.onChatWindowAnimate(false, fraction, params.leftMargin, params.topMargin, params.width, params.height) params = titleLayout.layoutParams as ViewGroup.MarginLayoutParams params.height = (titleLayoutHeight * (1 - fraction)).toInt() titleLayout.layoutParams = params params = inputLayout.layoutParams as ViewGroup.MarginLayoutParams params.height = (inputLayoutHeight * (1 - fraction)).toInt() inputLayout.layoutParams = params } .withStartAction { } .withEndAction { val params = layout.layoutParams as ViewGroup.MarginLayoutParams params.width = hideIconSize params.height = hideIconSize params.leftMargin = this.left + this.width - hideIconSize params.topMargin = this.top + this.height - hideIconSize layout.layoutParams = params hideLayout.visibility = View.VISIBLE contentLayout.visibility = View.GONE unreadText.visibility = View.GONE hidden = true } } private fun showAnimate() { contentLayout.animate().setDuration(duration) .scaleX(1.0f) .setInterpolator(DecelerateInterpolator()) .setUpdateListener { val fraction = it.animatedFraction val diffWidth = contentWidth * fraction val diffHeight = contentHeight * fraction val left = contentWidth - diffWidth + contentLeftMargin val top = contentHeight - diffHeight + contentTopMargin if (diffHeight <= minHeight) { return@setUpdateListener } var params = contentLayout.layoutParams as ViewGroup.MarginLayoutParams params.width = diffWidth.toInt() params.height = diffHeight.toInt() params.leftMargin = left.toInt() params.topMargin = top.toInt() contentLayout.layoutParams = params animateListener?.onChatWindowAnimate(true, fraction, params.leftMargin, params.topMargin, params.width, params.height) params = titleLayout.layoutParams as ViewGroup.MarginLayoutParams params.height = (titleLayoutHeight * fraction).toInt() titleLayout.layoutParams = params params = inputLayout.layoutParams as ViewGroup.MarginLayoutParams params.height = (inputLayoutHeight * fraction).toInt() inputLayout.layoutParams = params } .withStartAction { hideLayout.visibility = View.GONE contentLayout.visibility = View.VISIBLE val params = layout.layoutParams as ViewGroup.MarginLayoutParams params.width = width params.height = height params.topMargin = top params.leftMargin = left layout.layoutParams = params } .withEndAction { hidden = false unReadCount = 0 } } /** * Directly show the chat window, and display the last item * of the chat list */ fun show(show: Boolean) { if (show) { var params = contentLayout.layoutParams as ViewGroup.MarginLayoutParams params.width = contentWidth params.height = contentHeight params.leftMargin = contentLeftMargin params.topMargin = contentTopMargin contentLayout.layoutParams = params params = layout.layoutParams as ViewGroup.MarginLayoutParams params.width = width params.height = height params.topMargin = top params.leftMargin = left layout.layoutParams = params params = titleLayout.layoutParams as ViewGroup.MarginLayoutParams params.height = titleLayoutHeight titleLayout.layoutParams = params params = inputLayout.layoutParams as ViewGroup.MarginLayoutParams params.height = inputLayoutHeight inputLayout.layoutParams = params hideLayout.visibility = View.GONE contentLayout.visibility = View.VISIBLE hidden = false } else { var params = contentLayout.layoutParams as ViewGroup.MarginLayoutParams params.width = 0 params.height = minHeight params.leftMargin = contentLeftMargin params.topMargin = contentTopMargin contentLayout.layoutParams = params params = layout.layoutParams as ViewGroup.MarginLayoutParams params.width = hideIconSize params.height = hideIconSize params.leftMargin = this.left + this.width - hideIconSize params.topMargin = this.top + this.height - hideIconSize layout.layoutParams = params params = titleLayout.layoutParams as ViewGroup.MarginLayoutParams params.height = 0 titleLayout.layoutParams = params params = inputLayout.layoutParams as ViewGroup.MarginLayoutParams params.height = 0 inputLayout.layoutParams = params hideLayout.visibility = View.VISIBLE contentLayout.visibility = View.GONE if (unReadCount > 0) { unreadText.visibility = View.VISIBLE showUnreadMessages(false) } else { unreadText.visibility = View.GONE } hidden = true } } @UiThread private fun showUnreadMessages(add: Boolean) { unreadText.post { if (add) unReadCount++ if (unreadText.visibility == View.GONE) unreadText.visibility = View.VISIBLE unreadText.text = if (unReadCount > 99) "99+" else unReadCount.toString() } } @UiThread fun allowChat(group: Boolean?, local: Boolean?) { tabManager.allowChat(group, local) resetInputMethodState() } private fun resetInputMethodState() { var allow = true tabManager.getCurrentTab()?.let { tab -> allow = tab.chatAllowed() } sendBtn.post { sendBtn.isEnabled = allow edit.isEnabled = allow edit.hint = edit.context.getString( if (allow) R.string.agora_message_input_hint else R.string.agora_message_student_chat_mute_hint) } } fun showShadow(show: Boolean) { if (show) { contentLayout.elevation = shadow.toFloat() val params = contentLayout.layoutParams as ViewGroup.MarginLayoutParams params.setMargins(shadow, shadow, shadow, shadow) contentLeftMargin = params.leftMargin contentTopMargin = params.topMargin contentWidth = width - contentLeftMargin * 2 contentHeight = height - contentTopMargin * 2 contentLayout.layoutParams = params contentLayout.setBackgroundResource(R.drawable.agora_class_room_round_rect_bg) } else { contentLayout.elevation = 0f val params = contentLayout.layoutParams as ViewGroup.MarginLayoutParams params.setMargins(0, 0, 0, 0) contentLeftMargin = params.leftMargin contentTopMargin = params.topMargin contentWidth = width - contentLeftMargin * 2 contentHeight = height - contentTopMargin * 2 contentLayout.layoutParams = params contentLayout.setBackgroundResource(R.drawable.agora_class_room_round_rect_stroke_bg) } } fun setFullscreenRect(fullScreen: Boolean, rect: Rect) { setRect(rect) layout.post { if (fullScreen) { val params = contentLayout.layoutParams as ViewGroup.MarginLayoutParams params.width = 0 params.height = minHeight contentLayout.layoutParams = params contentLayout.visibility = View.GONE hideLayout.visibility = View.VISIBLE hidden = true } else { val params = contentLayout.layoutParams as ViewGroup.MarginLayoutParams params.width = contentWidth params.height = contentHeight params.topMargin = contentTopMargin params.leftMargin = contentLeftMargin contentLayout.layoutParams = params hideLayout.visibility = View.GONE contentLayout.visibility = View.VISIBLE hidden = false } } } override fun setRect(rect: Rect) { layout.post { val params = layout.layoutParams as ViewGroup.MarginLayoutParams params.topMargin = rect.top params.leftMargin = rect.left params.width = rect.right - rect.left params.height = rect.bottom - rect.top layout.layoutParams = params } } override fun receive(fromCompId: String, cmd: String, vararg: Any?) { } override fun release() { getWidgetManager()?.removeWidget(this) } /** * * Called when the size of unfold chat window is changed */ fun setFullDisplayRect(rect: Rect) { this.width = rect.width() this.height = rect.height() this.contentWidth = width - shadow * 2 this.contentHeight = height - shadow * 2 this.left = rect.left this.top = rect.top } @UiThread fun setClosable(closable: Boolean) { closeBtn.visibility = if (closable) View.VISIBLE else View.GONE } fun setAnimateListener(listener: OnChatWindowAnimateListener) { this.animateListener = listener } fun isShowing(): Boolean { return !hidden } } interface OnChatWindowAnimateListener { fun onChatWindowAnimate(enlarge: Boolean, fraction: Float, left: Int, top: Int, width: Int, height: Int) }
2
Kotlin
10
8
4dbaa7e4a69dce0078d4126ac866a68352a3847d
22,601
CloudClass-Android
MIT License
sample-compose/app/src/main/java/co/nimblehq/sample/compose/util/ComposableUtil.kt
nimblehq
101,353,301
false
{"Kotlin": 387666, "Ruby": 5344, "XSLT": 1824}
package co.nimblehq.sample.compose.util import android.annotation.SuppressLint import androidx.compose.runtime.Composable import androidx.compose.runtime.LaunchedEffect import androidx.compose.ui.graphics.Color import com.google.accompanist.systemuicontroller.rememberSystemUiController @SuppressLint("ComposableNaming") @Composable fun setStatusBarColor( color: Color, darkIcons: Boolean, ) { val systemUiController = rememberSystemUiController() LaunchedEffect(key1 = darkIcons) { systemUiController.setStatusBarColor( color = color, darkIcons = darkIcons, ) } }
31
Kotlin
23
94
f07941499a70b6144f4280c233edba542ab3e516
627
android-templates
MIT License
web3lib/src/commonMain/kotlin/com/sonsofcrypto/web3lib/abi/CallRow.kt
sonsofcrypto
454,978,132
false
{"Kotlin": 1330889, "Swift": 970782, "Objective-C": 77663, "Jupyter Notebook": 20914, "Go": 20697, "C": 15793, "Java": 12789, "Shell": 4282, "JavaScript": 1718}
package com.sonsofcrypto.web3lib.abi class CallRow { var type: String = "" var value: ByteArray = ByteArray(0) constructor(input: String) { type = input } }
1
Kotlin
2
6
d86df4845a1f60624dffa179ce6507ede3222186
182
web3wallet
MIT License
app/src/main/java/com/example/week6_project/FoodApplication.kt
Sentry2703
623,241,571
false
null
package com.example.week6_project import android.app.Application class FoodApplication: Application() { val db by lazy {FoodDatabase.getInstance(this)} }
1
Kotlin
0
0
bcf9625b013db1793126a9933358350a0893eced
159
AND_102_6
Apache License 2.0
app/src/main/java/com/example/zx_art/app/playLine.kt
vito-Z80
532,500,197
false
{"Kotlin": 127534}
package com.example.zx_art.app import androidx.compose.foundation.background import androidx.compose.foundation.layout.* import androidx.compose.material.Divider import androidx.compose.material.MaterialTheme import androidx.compose.material.Text import androidx.compose.runtime.* import androidx.compose.ui.Modifier import androidx.compose.ui.graphics.Color import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.text.style.TextAlign import androidx.compose.ui.unit.dp import kotlinx.coroutines.MainScope import kotlinx.coroutines.delay import kotlinx.coroutines.withContext import kotlin.time.Duration import kotlin.time.Duration.Companion.milliseconds import kotlin.time.Duration.Companion.minutes import kotlin.time.Duration.Companion.seconds @Composable fun PlayLine() { Box(modifier = Modifier // .padding(4f.dp) .height(16f.dp) // .fillMaxWidth(exo?.currentPosition?.toFloat() ?: 0f) .fillMaxWidth() .background(color = Color(33, 150, 243, 255))) { val a = 1f - ((exo?.duration ?: 0L) - MKey.playingPosition).toFloat() / (exo?.duration?.toFloat() ?: 0f) Divider(modifier = Modifier .fillMaxHeight() .fillMaxWidth(a), thickness = 16f.dp, color = Color( 1, 1, 1, 99)) Divider(modifier = Modifier .fillMaxHeight() .fillMaxWidth(1f - ((exo?.duration ?: 0L) - (exo?.bufferedPosition ?: 0L)).toFloat() / (exo?.duration?.toFloat() ?: 0f)), thickness = 16f.dp, color = Color(1, 1, 1, 62)) Row { Text(text = MKey.playingTuneTitle, style = MaterialTheme.typography.h1, textAlign = TextAlign.Center, modifier = Modifier .fillMaxWidth() .weight(1f)) val mil = (exo?.duration?.minus(MKey.playingPosition) ?: 0) / 10L % 60 val sec = (exo?.duration?.minus(MKey.playingPosition) ?: 0) / 1000L % 60 val min = (exo?.duration?.minus(MKey.playingPosition) ?: 0) / 1000L / 60 if (min >= 0L && mil >= 0L && sec >= 0L) { Text(text = String.format("%02d:%02d:%02d", min, sec, mil), modifier = Modifier.padding(end = 0f.dp), style = MaterialTheme.typography.h2, textAlign = TextAlign.Center) } else { Text(text = "00:00:00", modifier = Modifier.padding(end = 0f.dp), style = MaterialTheme.typography.h2, textAlign = TextAlign.Center) } } } }
8
Kotlin
0
0
6dd37b3e8c14602d30e23749c735e84298da84e9
2,750
ZXArt
Apache License 2.0
core/model/src/main/java/com/msg/model/param/faq/AddFrequentlyAskedQuestionsParam.kt
School-of-Company
700,744,250
false
{"Kotlin": 724178}
package com.msg.model.param.faq data class AddFrequentlyAskedQuestionsParam( val question: String, val answer: String, )
6
Kotlin
1
22
358bf40188fa2fc2baf23aa6b308b039cb3fbc8c
130
Bitgoeul-Android
MIT License
GithubBrowserSample/app/src/main/java/com/android/example/github/util/SingleFlowSource.kt
juanmendez
169,156,595
true
{"Kotlin": 402392, "Java": 259031, "Shell": 2979, "RenderScript": 2642}
package com.android.example.github.util import androidx.lifecycle.LiveData import androidx.lifecycle.MediatorLiveData import androidx.lifecycle.asLiveData import kotlinx.coroutines.flow.Flow class SingleFlowSource<T> { private val _mediator = MediatorLiveData<T>() val asLiveData: LiveData<T> get() = _mediator private var lastLiveData: LiveData<T>? = null var asFlow: Flow<T>? = null set(value) { field = value lastLiveData?.let { _mediator.removeSource(it) } value?.let { newFlow -> lastLiveData = newFlow.asLiveData().apply { _mediator.addSource(this) { _mediator.value = it } } } } fun clear() { asFlow = null } }
0
Kotlin
0
2
aee44a77043ba7a920bb65a32ad78bcb836bf635
852
android-architecture-components
Apache License 2.0
lookandfeel/src/commonMain/kotlin/com/github/alexzhirkevich/lookandfeel/util/LocalizedStrings.kt
alexzhirkevich
636,411,288
false
{"Kotlin": 480229, "Ruby": 1724, "Swift": 571, "Shell": 228}
package com.github.alexzhirkevich.lookandfeel.util import androidx.compose.runtime.Composable enum class LocalizedStrings { Cancel, Search, Back } @Composable expect fun LocalizedStrings.localized() : String
5
Kotlin
14
359
89f41414e712fc3d75bba4ef3609b04d617f2b19
214
compose-look-and-feel
Apache License 2.0
app/src/main/java/io/horizontalsystems/bankwallet/entities/EvmBlockchain.kt
horizontalsystems
142,825,178
false
null
package io.horizontalsystems.bankwallet.entities import android.os.Parcelable import io.horizontalsystems.bankwallet.R import io.horizontalsystems.marketkit.models.CoinType import io.horizontalsystems.marketkit.models.PlatformType import kotlinx.parcelize.Parcelize sealed class EvmBlockchain( val uid: String, val name: String, val shortName: String, val description: String, val icon24: Int, val baseCoinType: CoinType ): Parcelable { @Parcelize object Ethereum: EvmBlockchain("ethereum", "Ethereum", "Ethereum", "ETH, ERC20 tokens", R.drawable.logo_ethereum_24, CoinType.Ethereum) @Parcelize object BinanceSmartChain: EvmBlockchain("binance-smart-chain", "Binance Smart Chain", "BSC", "BNB, BEP20 tokens", R.drawable.logo_binancesmartchain_24, CoinType.BinanceSmartChain) @Parcelize object Polygon: EvmBlockchain("polygon", "Polygon", "Polygon", "MATIC, MRC20 tokens", R.drawable.logo_polygon_24, CoinType.Polygon) @Parcelize object Optimism: EvmBlockchain("optimism", "Optimism", "Optimism", "L2 chain", R.drawable.logo_optimism_24, CoinType.EthereumOptimism) @Parcelize object ArbitrumOne: EvmBlockchain("arbitrum-one", "Arbitrum One", "Arbitrum One", "L2 chain", R.drawable.logo_arbitrum_24, CoinType.EthereumArbitrumOne) val platformType: PlatformType get() = when (this) { ArbitrumOne -> PlatformType.ArbitrumOne BinanceSmartChain -> PlatformType.BinanceSmartChain Ethereum -> PlatformType.Ethereum Optimism -> PlatformType.Optimism Polygon -> PlatformType.Polygon } fun getEvm20CoinType(address: String) = when (this) { Ethereum -> CoinType.Erc20(address) BinanceSmartChain -> CoinType.Bep20(address) Polygon -> CoinType.Mrc20(address) Optimism -> CoinType.OptimismErc20(address) ArbitrumOne -> CoinType.ArbitrumOneErc20(address) } fun supports(coinType: CoinType) : Boolean { return when (this) { Ethereum -> (coinType == CoinType.Ethereum || coinType is CoinType.Erc20) BinanceSmartChain -> (coinType == CoinType.BinanceSmartChain || coinType is CoinType.Bep20) Polygon -> (coinType == CoinType.Polygon || coinType is CoinType.Mrc20) Optimism -> (coinType == CoinType.EthereumOptimism || coinType is CoinType.OptimismErc20) ArbitrumOne -> (coinType == CoinType.EthereumArbitrumOne || coinType is CoinType.ArbitrumOneErc20) } } }
136
Kotlin
219
402
5ce20e6e4e0f75a76496051ba6f78312bc641a51
2,559
unstoppable-wallet-android
MIT License
marker/src/main/kotlin/com/sourceplusplus/marker/source/mark/api/config/SourceMarkConfiguration.kt
chess-equality
297,668,044
false
null
package com.sourceplusplus.marker.source.mark.api.config import com.sourceplusplus.marker.source.mark.api.component.api.SourceMarkComponentProvider import com.sourceplusplus.marker.source.mark.api.filter.ApplySourceMarkFilter /** * todo: description. * * @since 0.0.1 * @author [Brandon Fergerson](mailto:bfergerson@apache.org) */ interface SourceMarkConfiguration { var applySourceMarkFilter: ApplySourceMarkFilter var activateOnKeyboardShortcut: Boolean var componentProvider: SourceMarkComponentProvider }
0
Kotlin
0
0
7c157711d11b4836d38209daf32d4ee3b3d831de
528
SourceMarker-Alpha
Apache License 2.0
client-core/src/main/kotlin/org/sinou/pydia/client/ui/system/screens/Settings.kt
bsinou
434,248,316
false
{"Kotlin": 2133584, "Java": 10237}
package org.sinou.pydia.client.ui.system.screens import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.wrapContentWidth import androidx.compose.foundation.rememberScrollState import androidx.compose.foundation.verticalScroll import androidx.compose.material3.Scaffold import androidx.compose.runtime.Composable import androidx.compose.runtime.collectAsState import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.res.dimensionResource import androidx.compose.ui.res.stringArrayResource import androidx.compose.ui.res.stringResource import org.sinou.pydia.client.R import org.sinou.pydia.client.core.db.preferences.ListPreferences import org.sinou.pydia.client.core.db.preferences.MeteredNetworkPreferences import org.sinou.pydia.client.core.db.preferences.SyncPreferences import org.sinou.pydia.client.core.db.preferences.defaultCellsPreferences import org.sinou.pydia.client.core.services.PreferencesKeys import org.sinou.pydia.client.ui.core.composables.ListSetting import org.sinou.pydia.client.ui.core.composables.PreferenceDivider import org.sinou.pydia.client.ui.core.composables.PreferenceSectionTitle import org.sinou.pydia.client.ui.core.composables.SwitchSetting import org.sinou.pydia.client.ui.core.nav.DefaultTopAppBar import org.sinou.pydia.client.ui.system.models.SettingsVM import org.koin.androidx.compose.koinViewModel // private const val LOG_TAG = "Settings.kt" @Composable fun SettingsScreen( isExpandedScreen: Boolean, openDrawer: () -> Unit, settingsVM: SettingsVM = koinViewModel(), ) { val modifier = Modifier .fillMaxWidth() .padding(vertical = dimensionResource(id = R.dimen.margin_small)) val cellsPreferences = settingsVM.cellsPreferences.collectAsState(initial = defaultCellsPreferences()) Scaffold( topBar = { DefaultTopAppBar( title = stringResource(R.string.action_settings), isExpandedScreen = isExpandedScreen, openDrawer = openDrawer, ) }, ) { innerPadding -> val scrollingState = rememberScrollState() Column( modifier = Modifier .padding(innerPadding) .padding(horizontal = dimensionResource(R.dimen.margin_medium)) .fillMaxWidth() .wrapContentWidth(Alignment.Start) .verticalScroll(scrollingState) ) { ListSection(settingsVM, cellsPreferences.value.list, modifier) PreferenceDivider(modifier) MeteredSection(settingsVM, cellsPreferences.value.meteredNetwork, modifier) PreferenceDivider(modifier) OfflineSection(settingsVM, cellsPreferences.value.sync, modifier) PreferenceDivider(modifier) TroubleshootingSection( settingsVM, cellsPreferences.value.showDebugTools, cellsPreferences.value.disablePoll, modifier ) } } } @Composable fun ListSection(settingsVM: SettingsVM, listPreferences: ListPreferences, modifier: Modifier) { PreferenceSectionTitle( stringResource(R.string.pref_category_title_recycler), modifier, ) ListSetting( stringResource(R.string.order_by_title), listPreferences.order, keys = stringArrayResource(R.array.order_by_values), labels = stringArrayResource(R.array.order_by_labels), { settingsVM.setDefaultOrder(it) }, modifier, ) ListSetting( stringResource(R.string.pref_choose_list_layout), listPreferences.layout.name, keys = stringArrayResource(R.array.list_layout_values), labels = stringArrayResource(R.array.list_layout_labels), { settingsVM.setListLayout(it) }, modifier, ) } @Composable fun MeteredSection( settingsVM: SettingsVM, netPref: MeteredNetworkPreferences, modifier: Modifier ) { PreferenceSectionTitle( stringResource(R.string.pref_category_title_metered), modifier, ) SwitchSetting( stringResource(R.string.pref_apply_metered_limits_title), stringResource(R.string.pref_apply_metered_limits_desc), netPref.applyLimits, { settingsVM.setBooleanFlag(PreferencesKeys.APPLY_METERED_LIMITATION, it) }, modifier, ) SwitchSetting( label = stringResource(R.string.pref_metered_show_warning_title), description = stringResource(R.string.pref_metered_show_warning_desc), isSelected = netPref.applyLimits && netPref.showWarning, onItemClick = { settingsVM.setBooleanFlag(PreferencesKeys.METERED_SHOW_WARNING, it) }, modifier = modifier, isEnabled = netPref.applyLimits ) SwitchSetting( label = stringResource(R.string.pref_metered_dl_thumbs_title), description = stringResource(R.string.pref_metered_dl_thumbs_desc), isSelected = netPref.dlThumbs || !netPref.applyLimits, onItemClick = { settingsVM.setBooleanFlag(PreferencesKeys.METERED_DL_THUMBS, it) }, modifier = modifier, isEnabled = netPref.applyLimits ) SwitchSetting( label = stringResource(R.string.pref_on_metered_ask_before_dl_files_title), description = null, isSelected = netPref.applyLimits && netPref.askBeforeDL, onItemClick = { settingsVM.setBooleanFlag(PreferencesKeys.METERED_ASK_B4_DL_FILES, it) }, modifier = modifier, isEnabled = netPref.applyLimits ) // Re-Enable this when the settings is really used in the app // TextSetting( // stringResource(R.string.on_metered_ask_before_dl_files_greater_than_title), // " ${netPref.sizeThreshold}", // modifier, // ) } @Composable fun OfflineSection( settingsVM: SettingsVM, syncPref: SyncPreferences, modifier: Modifier ) { PreferenceSectionTitle( stringResource(R.string.pref_category_title_offline), modifier, ) ListSetting( stringResource(R.string.pref_choose_list_offline_frequency_title), syncPref.frequency, // frequencyLabel(LocalContext.current.resources), keys = stringArrayResource(R.array.offline_frequency_values), labels = stringArrayResource(R.array.offline_frequency_labels), { settingsVM.setStringPref(PreferencesKeys.SYNC_FREQ, it) }, modifier, ) ListSetting( stringResource(R.string.pref_offline_constraint_wifi_title), syncPref.onNetworkType, keys = stringArrayResource(R.array.network_type_values), labels = stringArrayResource(R.array.network_type_labels), { settingsVM.setStringPref(PreferencesKeys.SYNC_CONST_NETWORK_TYPE, it) }, modifier, ) SwitchSetting( stringResource(R.string.pref_offline_constraint_charging_title), stringResource(R.string.pref_offline_constraint_charging_desc), syncPref.onCharging, { settingsVM.setBooleanFlag(PreferencesKeys.SYNC_CONST_ON_CHARGING, it) }, modifier, ) SwitchSetting( stringResource(R.string.pref_offline_constraint_batt_not_low_title), stringResource(R.string.pref_offline_constraint_batt_not_low_desc), syncPref.onBatteryNotLow, { settingsVM.setBooleanFlag(PreferencesKeys.SYNC_CONST_ON_BATT_NOT_LOW, it) }, modifier, ) SwitchSetting( stringResource(R.string.pref_offline_constraint_idle_title), stringResource(R.string.pref_offline_constraint_idle_desc), syncPref.onIdle, { settingsVM.setBooleanFlag(PreferencesKeys.SYNC_CONST_ON_IDLE, it) }, modifier, ) } @Composable fun TroubleshootingSection( settingsVM: SettingsVM, showRuntimeTools: Boolean, disablePoll: Boolean, modifier: Modifier ) { TroubleshootingSection( showRuntimeTools, { show -> settingsVM.setShowRuntimeToolsFlag(show) }, disablePoll, { disable -> settingsVM.setDisablePollFlag(disable) }, modifier ) } @Composable fun TroubleshootingSection( showRuntimeTools: Boolean, onShowRuntimeToolsClick: (Boolean) -> Unit, disablePoll: Boolean, onDisablePollClick: (Boolean) -> Unit, modifier: Modifier ) { PreferenceSectionTitle( stringResource(R.string.pref_category_title_troubleshooting), modifier, ) SwitchSetting( stringResource(R.string.pref_troubleshooting_show_list_title), stringResource(R.string.pref_troubleshooting_show_list_desc), showRuntimeTools, { onShowRuntimeToolsClick(!showRuntimeTools) }, modifier, ) // TODO re-enable this when ready // if (showRuntimeTools) { // SwitchSetting( // stringResource(R.string.pref_troubleshooting_disable_poll_title), // stringResource(R.string.pref_troubleshooting_disable_poll_desc), // disablePoll, // { onDisablePollClick(!disablePoll) }, // modifier, // ) // } }
0
Kotlin
0
1
51a128c49a24eedef1baf2d4f295f14aa799b5d3
9,204
pydia
Apache License 2.0
module/notification/src/main/java/me/pxq/eyepetizer/notification/repository/NotificationRepository.kt
GreatAgain-1990
312,707,589
true
{"Kotlin": 227518, "Java": 19444}
package me.pxq.eyepetizer.notification.repository import me.pxq.common.Api import me.pxq.common.ApiService import me.pxq.network.request import retrofit2.http.Url /** * Description: * Author : pxq * Date : 2020/8/23 5:17 PM */ class NotificationRepository(private val apiService: Api) { suspend fun fetchNotificationPush(@Url url: String = ApiService.NOTIFICATION_PUSH_PAGE) = apiService.fetchNotificationPush(url) }
0
null
0
0
a73b146fbd007fa92facd306c79d9c5e2bd64ab4
428
eyepetizer-kotlin
Apache License 2.0
src/main/kotlin/com/github/mkdika/refactoringspringrestapi/service/PersonServiceImpl.kt
mkdika
242,126,952
false
null
package com.github.mkdika.refactoringspringrestapi.service import com.github.mkdika.refactoringspringrestapi.model.Person import com.github.mkdika.refactoringspringrestapi.repository.PersonRepository class PersonServiceImpl(private val repository: PersonRepository) : PersonService { override fun findById(id: Int): Person { TODO("not implemented") //To change body of created functions use File | Settings | File Templates. } override fun findAll(): List<Person> { TODO("not implemented") //To change body of created functions use File | Settings | File Templates. } override fun insert(person: Person): Person { TODO("not implemented") //To change body of created functions use File | Settings | File Templates. } }
0
Kotlin
0
0
19472d3597fc344cd39178ea209c3a5f9a187ef7
770
refactor-spring-rest-api
MIT License
src/me/anno/ui/base/groups/TablePanel.kt
AntonioNoack
456,513,348
false
{"Kotlin": 9955069, "C": 235991, "Java": 6754, "Lua": 4404, "GLSL": 2698}
package me.anno.ui.base.groups import me.anno.maths.Maths import me.anno.ui.Panel import me.anno.ui.Style import me.anno.ui.base.components.AxisAlignment import me.anno.utils.structures.arrays.FloatArrayList import me.anno.utils.structures.arrays.IntArrayList import kotlin.math.max import kotlin.math.min open class TablePanel(sizeX: Int, sizeY: Int, style: Style) : PanelGroup(style) { private val placeholder = Panel(style) final override val children = ArrayList<Panel>(Maths.multiplyExact(sizeX, sizeY)) init { for (i in 0 until sizeX * sizeY) { children.add(placeholder) } placeholder.parent = this } var sizeX: Int = sizeX set(value) { if (field > value) { // size down // destroy old children for (y in 0 until sizeY) { for (x in value until field) { val oi = x + y * field val child = children[oi] if (child !== placeholder) { child.destroy() children[oi] = placeholder } } } // move children from old positions into new ones for (y in 1 until sizeY) { for (x in 0 until value) { val oi = x + y * field val ni = x + y * value children[ni] = children[oi] } } children.subList(value * sizeY, children.size).clear() field = value } else if (field < value) { // size up val size = Maths.multiplyExact(value, sizeY) children.ensureCapacity(size) for (i in children.size until size) children.add(placeholder) // move children from old positions into new ones for (y in sizeY - 1 downTo 1) { // last row is already perfect for (x in field - 1 downTo 0) { val oi = x + y * field val ni = x + y * value children[ni] = children[oi] children[oi] = placeholder } } field = value } } var sizeY: Int = sizeY set(value) { field = value val size = Maths.multiplyExact(sizeX, sizeY) children.ensureCapacity(size) for (i in children.size until size) { children.add(placeholder) } if (children.size > size) { // this works apparently children.subList(size, children.size).clear() } } operator fun get(x: Int, y: Int): Panel { return if (x in 0 until sizeX && y in 0 until sizeY) { children[getIndex(x, y)] } else placeholder } operator fun set(x: Int, y: Int, child: Panel) { if (x in 0 until sizeX && y in 0 until sizeY) { children[getIndex(x, y)] = child invalidateLayout() } } open fun getAvailableSizeX(xi: Int, yi: Int, w: Int, h: Int, child: Panel): Int { return w } open fun getAvailableSizeY(xi: Int, yi: Int, w: Int, h: Int, child: Panel): Int { return h } val xs = IntArrayList(sizeX + 1) val ys = IntArrayList(sizeY + 1) // weights along x/y-axis val wxs = FloatArrayList(sizeX) val wys = FloatArrayList(sizeY) private fun getIndex(x: Int, y: Int): Int { return x + y * sizeX } private fun calculateChildSizes(w: Int, h: Int) { for (y in 0 until sizeY) { for (x in 0 until sizeX) { val child = children[getIndex(x, y)] if (child === placeholder) continue val w2 = getAvailableSizeX(x, y, w, h, child) val h2 = getAvailableSizeY(x, y, w, h, child) child.calculateSize(w2, h2) child.width = min(w2, child.minW) child.height = min(h2, child.minH) } } } override fun calculateSize(w: Int, h: Int) { super.calculateSize(w, h) val sizeX = sizeX val sizeY = sizeY calculateChildSizes(w, h) var sumW = 0 var sumH = 0 xs.size = sizeX + 1 ys.size = sizeY + 1 wxs.size = sizeX wys.size = sizeY placeholder.width = 0 placeholder.height = 0 xs[0] = 0 for (x in 0 until sizeX) { var maxW = 0 for (y in 0 until sizeY) { maxW = max(maxW, this[x, y].width) } sumW += maxW xs[x + 1] = sumW } ys[0] = 0 for (y in 0 until sizeY) { var maxH = 0 for (x in 0 until sizeX) { maxH = max(maxH, this[x, y].height) } sumH += maxH ys[y + 1] = sumH } minW = sumW minH = sumH if (alignmentX == AxisAlignment.FILL && sumW < w) { distributeExtra(w - sumW, xs, wxs) minW = w } if (alignmentY == AxisAlignment.FILL && sumH < h) { distributeExtra(h - sumH, ys, wys) minH = h } } private fun distributeExtra(diff: Int, positions: IntArrayList, weights: FloatArrayList) { normalizeWeights(weights) val total = diff + 0.5f var sum = 0f for (i in 0 until weights.size) { sum += weights[i] positions[i + 1] += (total * sum).toInt() } } private fun normalizeWeights(weights: FloatArrayList) { val sum = weights.sum() if (sum <= 0f) weights.fill(1f / weights.size) else weights.scale(1f / sum) } override fun setPosition(x: Int, y: Int) { super.setPosition(x, y) placeholder.setPosSize(x, y, 0, 0) for (yi in 0 until sizeY) { val y0 = ys[yi] val y1 = ys[yi + 1] for (xi in 0 until sizeX) { val child = children[xi + yi * sizeX] if (child === placeholder) continue val x0 = xs[xi] val x1 = xs[xi + 1] val w = x1 - x0 val h = y1 - y0 val alignmentX = child.alignmentX val alignmentY = child.alignmentY val cw = alignmentX.getSize(w, child.minW) val ch = alignmentY.getSize(h, child.minH) val cx = x + x0 + alignmentX.getOffset(w, child.minW) val cy = y + y0 + alignmentY.getOffset(h, child.minH) child.setPosSize(cx, cy, cw, ch) } } } override fun remove(child: Panel) { if (child === placeholder) return val ix = children.indexOf(child) if (ix >= 0) { children[ix] = placeholder invalidateLayout() } } override fun invalidateLayout() { window?.addNeedsLayout(this) } }
0
Kotlin
3
21
e28df04e97033d96a43a2d9ebaa533bf5b4bde81
7,218
RemsEngine
Apache License 2.0
Compose Login/Compose_login_reto/app/src/main/java/com/example/compose_login/utils/Constants.kt
Jeanpall
672,016,160
false
null
package com.example.proyecto_dashboard.utils object Constants { const val channelId = "CanalTienda" }
0
Kotlin
0
0
2eb00712a1d8a25ff189c2b0892eaf3ef42906eb
106
Proyectos_Kotlin
MIT License
app/src/main/java/com/github/jorgecastillo/kotlinandroid/io/algebras/ui/Presentation.kt
JorgeCastilloPrz
83,796,541
false
null
package com.github.jorgecastillo.kotlinandroid.io.algebras.ui import android.content.Context import arrow.Kind import com.github.jorgecastillo.kotlinandroid.io.algebras.business.getNewsItemDetails import com.github.jorgecastillo.kotlinandroid.io.algebras.business.getNews import com.github.jorgecastillo.kotlinandroid.io.algebras.business.model.DomainError import com.github.jorgecastillo.kotlinandroid.io.algebras.business.model.NewsItem import com.github.jorgecastillo.kotlinandroid.io.algebras.ui.model.NewsItemViewState import com.github.jorgecastillo.kotlinandroid.io.runtime.context.Runtime interface NewsView { fun showLoading(): Unit fun hideLoading(): Unit fun showNotFoundError(): Unit fun showGenericError(): Unit fun showAuthenticationError(): Unit } interface NewsListView : NewsView { fun drawNews(news: List<NewsItemViewState>): Unit } interface NewsItemDetailView : NewsView { fun drawNewsItem(newsItem: NewsItemViewState) } /** * On tagless-final module we built this operations over abstract behaviors defined on top of an F * type. We'll end up running these methods using a valid F type that support Concurrent behaviors, * like IO. */ fun <F> Runtime<F>.onNewsItemClick( ctx: Context, title: String ): Kind<F, Unit> = goToNewsItemDetail(ctx, title) private fun displayErrors( view: NewsView, t: Throwable ): Unit { when (DomainError.fromThrowable(t)) { is DomainError.NotFoundError -> view.showNotFoundError() is DomainError.UnknownServerError -> view.showGenericError() is DomainError.AuthenticationError -> view.showAuthenticationError() } } fun <F> Runtime<F>.getAllNews(view: NewsListView): Kind<F, Unit> = fx.concurrent { !effect { view.showLoading() } val maybeNews = !getNews().attempt() !effect { view.hideLoading() } !effect { maybeNews.fold( ifLeft = { displayErrors(view, it) }, ifRight = { view.drawNews(it.map { newsItem -> newsItem.toViewState() }) } ) } } fun <F> Runtime<F>.getNewsItemDetails( title: String, view: NewsItemDetailView ): Kind<F, Unit> = fx.concurrent { !effect { view.showLoading() } val maybeNewsItem = !getNewsItemDetails(title).attempt() !effect { view.hideLoading() } !effect { maybeNewsItem.fold( ifLeft = { displayErrors(view, it) }, ifRight = { newsItem -> view.drawNewsItem(newsItem.toViewState()) } ) } } fun NewsItem.toViewState() = NewsItemViewState( title = title, author = author, photoUrl = urlToImage, publishedAt = publishedAt, description = description, content = content )
2
Kotlin
37
424
78f214148e0c949acf845d18b118da32a0a92bcd
2,696
ArrowAndroidSamples
Apache License 2.0
Chapter6/Exercise06.01/domain/src/test/java/com/clean/domain/usecase/UseCaseTest.kt
PacktPublishing
440,463,149
false
{"Kotlin": 629869}
package com.clean.domain.usecase import com.clean.domain.entity.Result import com.clean.domain.entity.UseCaseException import kotlinx.coroutines.ExperimentalCoroutinesApi import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.first import kotlinx.coroutines.flow.flow import kotlinx.coroutines.flow.flowOf import kotlinx.coroutines.test.TestCoroutineDispatcher import kotlinx.coroutines.test.runBlockingTest import org.junit.Assert.assertEquals import org.junit.Assert.assertTrue import org.junit.Before import org.junit.Test import org.mockito.kotlin.mock class UseCaseTest { @ExperimentalCoroutinesApi private val configuration = UseCase.Configuration(TestCoroutineDispatcher()) private val request = mock<UseCase.Request>() private val response = mock<UseCase.Response>() @ExperimentalCoroutinesApi private lateinit var useCase: UseCase<UseCase.Request, UseCase.Response> @ExperimentalCoroutinesApi @Before fun setUp() { useCase = object : UseCase<UseCase.Request, UseCase.Response>(configuration) { override fun process(request: Request): Flow<Response> { assertEquals(this@UseCaseTest.request, request) return flowOf(response) } } } @ExperimentalCoroutinesApi @Test fun testExecuteSuccess() = runBlockingTest { val result = useCase.execute(request).first() assertEquals(Result.Success(response), result) } @ExperimentalCoroutinesApi @Test fun testExecuteUserException() { useCase = object : UseCase<UseCase.Request, UseCase.Response>(configuration) { override fun process(request: Request): Flow<Response> { assertEquals(this@UseCaseTest.request, request) return flow { throw UseCaseException.UserException(Throwable()) } } } runBlockingTest { val result = useCase.execute(request).first() assertTrue((result as Result.Error).exception is UseCaseException.UserException) } } @ExperimentalCoroutinesApi @Test fun testExecutePostException() { useCase = object : UseCase<UseCase.Request, UseCase.Response>(configuration) { override fun process(request: Request): Flow<Response> { assertEquals(this@UseCaseTest.request, request) return flow { throw UseCaseException.PostException(Throwable()) } } } runBlockingTest { val result = useCase.execute(request).first() assertTrue((result as Result.Error).exception is UseCaseException.PostException) } } @ExperimentalCoroutinesApi @Test fun testExecuteUnknownException() { useCase = object : UseCase<UseCase.Request, UseCase.Response>(configuration) { override fun process(request: Request): Flow<Response> { assertEquals(this@UseCaseTest.request, request) return flow { throw Throwable() } } } runBlockingTest { val result = useCase.execute(request).first() assertTrue((result as Result.Error).exception is UseCaseException.UnknownException) } } }
0
Kotlin
19
55
0230b203b285e992742369dfc3cc24066571935a
3,354
Clean-Android-Architecture
MIT License
app/src/main/java/com/example/vindmoller/data/windturbines/WindTurbineRepository.kt
omarhaweel
676,250,796
false
null
package com.example.vindmoller.data.windturbines import kotlinx.coroutines.flow.Flow import kotlinx.datetime.Instant interface WindTurbineRepository { suspend fun getAllWindTurbines(): List<WindTurbine> suspend fun getSourceWindTurbines(sourceId: String): List<WindTurbine> suspend fun getAllWindTurbineStream(): List<WindTurbine> suspend fun insertWindTurbine(windTurbine: WindTurbine) suspend fun deleteWindTurbine(id: Int) suspend fun getWindTurbinesPlacedAfter(timestamp: Instant): List<WindTurbine> suspend fun getNewestWindTurbine(): WindTurbine? // ADDED suspend fun removeSourceTurbines(sourceId: String) //ADDED suspend fun getCountyWindTurbines(fylkeId: Int): List<WindTurbine> fun getAllWindTurbinesFlow(): Flow<List<WindTurbine>> fun getSourceWindTurbinesFlow(sourceId: String): Flow<List<WindTurbine>> fun getCountyWindTurbinesFlow(fylkeId: Int): Flow<List<WindTurbine>> suspend fun getWindTurbineCountBySource(): Map<String, Int> suspend fun getWindTurbineCountBySourceInCounty(fylkeId: Int): Map<String, Int> suspend fun getWindTurbineCountByCounty(): Map<Int, Int> suspend fun deleteAll() }
0
Kotlin
0
0
e83e6b420f742ad6822e257187948e571908df8b
1,190
kooling
Apache License 2.0
app/src/main/java/com/stanroy/pokesearch/data/api/services/PokeService.kt
stanroy
329,720,911
false
null
package com.stanroy.pokesearch.data.api.services import com.stanroy.pokesearch.data.api.responses.main.MainSearchResponse import com.stanroy.pokesearch.data.api.responses.pokemon.PokemonSearchResponse import retrofit2.Call import retrofit2.http.GET import retrofit2.http.Path import retrofit2.http.Query interface PokeService { @GET("pokemon/{pokeId}") fun getPokemon(@Path("pokeId") pokeId: Int): Call<PokemonSearchResponse> }
0
Kotlin
0
0
8d0b32fb3ba5a7975afd1aa8481c1ee406598d74
440
PokeShuffle-Android-App
MIT License
library/src/test/java/com/jaredrummler/html/DslTest.kt
jaredrummler
77,140,259
false
null
/* * Copyright (C) 2021 <NAME> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * 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.jaredrummler.html import org.junit.Assert import org.junit.Test class DslTest { @Test fun `should render a HTML element`() { val expected = """<a href="https://google.com">Google</a>""" val rendered = html { a { href = "https://google.com" text = "Google" } }.render() Assert.assertEquals(expected, rendered) } @Test fun `should render b HTML element`() { val expected = """<b>This text is bold</b>""" val rendered = html { b { text = "This text is bold" } }.render() Assert.assertEquals(expected, rendered) } @Test fun `should render big HTML element`() { val expected = """<big>That's what she said</big>""" val rendered = html { big { text = "That's what she said" } }.render() Assert.assertEquals(expected, rendered) } @Test fun `should render blockquote HTML element`() { val expected = """<blockquote>Your wife is in me DMs</blockquote>""" // Conor McGregor val rendered = html { blockquote { text = "Your wife is in me DMs" } }.render() Assert.assertEquals(expected, rendered) } @Test fun `should render br HTML element`() { val expected = """<br>""" val rendered = html { br() } .render() Assert.assertEquals(expected, rendered) } @Test fun `should render cite HTML element`() { val expected = """<cite>Italic text using HTML cite tag</cite>""" val rendered = html { cite { text = "Italic text using HTML cite tag" } }.render() Assert.assertEquals(expected, rendered) } @Test fun `should render del HTML element`() { val expected = """<del><p>This paragraph has been deleted.</p></del>""" val rendered = html { del { p { text = "This paragraph has been deleted." } } }.render() Assert.assertEquals(expected, rendered) } @Test fun `should render dfn HTML element`() { val expected = """<dfn>Italic text using HTML dfn tag</dfn>""" val rendered = html { dfn { text = "Italic text using HTML dfn tag" } }.render() Assert.assertEquals(expected, rendered) } @Test fun `should render div HTML element`() { val expected = """<div><p>This paragraph is inside a div.</p></div>""" val rendered = html { div { p { text = "This paragraph is inside a div." } } }.render() Assert.assertEquals(expected, rendered) } @Test fun `should render em HTML element`() { val expected = """<em>Italic text using HTML em tag</em>""" val rendered = html { em { text = "Italic text using HTML em tag" } }.render() Assert.assertEquals(expected, rendered) } @Test fun `should render font HTML element`() { val expected = """<font face="sans-serif-condensed-light" color="red">Text with a custom font</font>""" val rendered = html { font { face = "sans-serif-condensed-light" // RobotoCondensed-Light.ttf text = "Text with a custom font" color = "red" } }.render() Assert.assertEquals(expected, rendered) } @Test fun `should render i HTML element`() { val expected = """<i>Italic text using HTML i tag</i>""" val rendered = html { i { text = "Italic text using HTML i tag" } }.render() Assert.assertEquals(expected, rendered) } @Test fun `should render img HTML element`() { val expected = """<img src="image.png">""" val rendered = html { img { src = "image.png" } }.render() Assert.assertEquals(expected, rendered) } @Test fun `should render h1 HTML element`() { val expected = """<h1>Heading 1</h1>""" val rendered = html { h1 { text = "Heading 1" } }.render() Assert.assertEquals(expected, rendered) } @Test fun `should render h2 HTML element`() { val expected = """<h2>Heading 2</h2>""" val rendered = html { h2 { text = "Heading 2" } }.render() Assert.assertEquals(expected, rendered) } @Test fun `should render h3 HTML element`() { val expected = """<h3>Heading 3</h3>""" val rendered = html { h3 { text = "Heading 3" } }.render() Assert.assertEquals(expected, rendered) } @Test fun `should render h4 HTML element`() { val expected = """<h4>Heading 4</h4>""" val rendered = html { h4 { text = "Heading 4" } }.render() Assert.assertEquals(expected, rendered) } @Test fun `should render h5 HTML element`() { val expected = """<h5>Heading 5</h5>""" val rendered = html { h5 { text = "Heading 5" } }.render() Assert.assertEquals(expected, rendered) } @Test fun `should render h6 HTML element`() { val expected = """<h6>Heading 6</h6>""" val rendered = html { h6 { text = "Heading 6" } }.render() Assert.assertEquals(expected, rendered) } @Test fun `should render ul HTML element`() { val expected = """<ul><li>List item text with a bullet</li></ul>""" val rendered = html { ul { li { text = "List item text with a bullet" } } }.render() Assert.assertEquals(expected, rendered) } @Test fun `should render small HTML element`() { val expected = """<small>This text is scaled down by 0.8</small>""" val rendered = html { small { text = "This text is scaled down by 0.8" } }.render() Assert.assertEquals(expected, rendered) } @Test fun `should render strong HTML element`() { val expected = """<strong>This text is bold</strong>""" val rendered = html { strong { text = "This text is bold" } }.render() Assert.assertEquals(expected, rendered) } @Test fun `should render sub HTML element`() { val expected = """<sub>This text is lower</sub>""" val rendered = html { sub { text = "This text is lower" } }.render() Assert.assertEquals(expected, rendered) } @Test fun `should render sup HTML element`() { val expected = """<sup>This text is higher</sup>""" val rendered = html { sup { text = "This text is higher" } }.render() Assert.assertEquals(expected, rendered) } @Test fun `should render tt HTML element`() { val expected = """<tt>Text in monospace typeface</tt>""" val rendered = html { tt { text = "Text in monospace typeface" } }.render() Assert.assertEquals(expected, rendered) } @Test fun `should render u HTML element`() { val expected = """<u>This text has an underline.</u>""" val rendered = html { u { text = "This text has an underline." } }.render() Assert.assertEquals(expected, rendered) } }
3
Kotlin
61
534
b38aed837090e2439d328e935fb66ccf3958bfbb
8,760
HtmlDsl
Apache License 2.0
app/src/main/java/com/krygodev/appforartists/feature_image/presentation/image_details/ImageDetailsViewModel.kt
krygo-dev
422,322,080
false
{"Kotlin": 287182}
package com.krygodev.appforartists.feature_image.presentation.image_details import androidx.compose.runtime.State import androidx.compose.runtime.mutableStateOf import androidx.lifecycle.SavedStateHandle import androidx.lifecycle.ViewModel import androidx.lifecycle.viewModelScope import com.google.firebase.Timestamp import com.krygodev.appforartists.core.domain.model.ImageModel import com.krygodev.appforartists.core.domain.model.UserModel import com.krygodev.appforartists.core.domain.util.Constants import com.krygodev.appforartists.core.domain.util.Resource import com.krygodev.appforartists.core.presentation.util.LoadingState import com.krygodev.appforartists.core.presentation.util.Screen import com.krygodev.appforartists.core.presentation.util.UIEvent import com.krygodev.appforartists.feature_image.domain.model.CommentModel import com.krygodev.appforartists.feature_image.domain.use_case.image.ImageUseCases import com.krygodev.appforartists.feature_profile.domain.use_case.profile.ProfileUseCases import dagger.hilt.android.lifecycle.HiltViewModel import kotlinx.coroutines.delay import kotlinx.coroutines.flow.MutableSharedFlow import kotlinx.coroutines.flow.asSharedFlow import kotlinx.coroutines.flow.launchIn import kotlinx.coroutines.flow.onEach import kotlinx.coroutines.launch import java.util.* import javax.inject.Inject @HiltViewModel class ImageDetailsViewModel @Inject constructor( private val _imageUseCases: ImageUseCases, private val _profileUseCases: ProfileUseCases, savedStateHandle: SavedStateHandle ) : ViewModel() { private val _state = mutableStateOf(LoadingState()) val state: State<LoadingState> = _state private val _eventFlow = MutableSharedFlow<UIEvent>() val eventFlow = _eventFlow.asSharedFlow() private val _image = mutableStateOf(ImageModel()) val image: State<ImageModel> = _image private val _imageComments = mutableStateOf(listOf<CommentModel>()) val imageComments: State<List<CommentModel>> = _imageComments private val _user = mutableStateOf(UserModel()) val user: State<UserModel> = _user private val _comment = mutableStateOf(CommentModel()) val comment: State<CommentModel> = _comment private var _userImages = mutableListOf<String>() private var _userFavorites = mutableListOf<String>() private var _imageStarredBy = mutableListOf<String>() private var _imageLikedBy = mutableListOf<String>() init { savedStateHandle.get<String>(Constants.PARAM_IMAGE_ID)?.let { id -> onEvent(ImageDetailsEvent.GetImageById(id)) onEvent(ImageDetailsEvent.GetImageComments(id)) } onEvent(ImageDetailsEvent.GetUserData) } fun onEvent(event: ImageDetailsEvent) { when (event) { is ImageDetailsEvent.GetImageById -> { viewModelScope.launch { _imageUseCases.getImageById(imageId = event.id).onEach { result -> when (result) { is Resource.Loading -> { _state.value = state.value.copy( isLoading = true, error = "", result = null ) } is Resource.Success -> { _state.value = state.value.copy( isLoading = false, error = "", result = result.data ) _image.value = result.data!! _imageLikedBy = image.value.likedBy.toMutableList() _imageStarredBy = image.value.starredBy.toMutableList() } is Resource.Error -> { _state.value = state.value.copy( isLoading = false, error = result.message!!, result = null ) _eventFlow.emit(UIEvent.ShowSnackbar(result.message)) } } }.launchIn(this) } } is ImageDetailsEvent.GetImageComments -> { viewModelScope.launch { _imageUseCases.getImageComments(id = event.id).onEach { result -> when (result) { is Resource.Loading -> { _state.value = state.value.copy( isLoading = true, error = "", result = null ) } is Resource.Success -> { _state.value = state.value.copy( isLoading = false, error = "", result = result.data ) _imageComments.value = result.data!! } is Resource.Error -> { _state.value = state.value.copy( isLoading = false, error = result.message!!, result = null ) _eventFlow.emit(UIEvent.ShowSnackbar(result.message)) } } }.launchIn(this) } } is ImageDetailsEvent.GetUserData -> { viewModelScope.launch { _profileUseCases.getUserData(_profileUseCases.getCurrentUser()!!.uid).onEach { result -> when (result) { is Resource.Loading -> { _state.value = state.value.copy( isLoading = true, error = "", result = null ) } is Resource.Success -> { _state.value = state.value.copy( isLoading = false, error = "", result = result.data ) _user.value = result.data!! _userImages = user.value.images.toMutableList() _userFavorites = user.value.favorites.toMutableList() } is Resource.Error -> { _state.value = state.value.copy( isLoading = false, error = result.message!!, result = null ) _eventFlow.emit(UIEvent.ShowSnackbar(result.message)) } } }.launchIn(this) } } is ImageDetailsEvent.DeleteImage -> { viewModelScope.launch { _imageUseCases.deleteImage(image = image.value).onEach { result -> when (result) { is Resource.Loading -> { _state.value = state.value.copy( isLoading = true, error = "", result = null ) } is Resource.Success -> { _state.value = state.value.copy( isLoading = false, error = "", result = result.data ) _userImages.remove(image.value.id) _userFavorites.remove(image.value.id) _user.value = user.value.copy( images = _userImages, favorites = _userFavorites ) onEvent(ImageDetailsEvent.UpdateUserData(user.value)) _eventFlow.emit(UIEvent.ShowSnackbar("Obraz usunięty!")) delay(500) _eventFlow.emit(UIEvent.NavigateTo(Screen.ProfileScreen.route)) } is Resource.Error -> { _state.value = state.value.copy( isLoading = false, error = result.message!!, result = null ) _eventFlow.emit(UIEvent.ShowSnackbar(result.message)) } } }.launchIn(this) } } is ImageDetailsEvent.EnteredCommentContent -> { _comment.value = comment.value.copy( content = event.content ) } is ImageDetailsEvent.AddComment -> { _comment.value = comment.value.copy( authorUid = user.value.uid, authorName = user.value.username, timestamp = Timestamp(Date()) ) viewModelScope.launch { _imageUseCases.addComment( comment = comment.value, id = image.value.id!! ).onEach { result -> when (result) { is Resource.Loading -> { _state.value = state.value.copy( isLoading = true, error = "", result = null ) } is Resource.Success -> { _state.value = state.value.copy( isLoading = false, error = "", result = result.data ) _comment.value = comment.value.copy( content = "" ) onEvent(ImageDetailsEvent.GetImageComments(image.value.id!!)) } is Resource.Error -> { _state.value = state.value.copy( isLoading = false, error = result.message!!, result = null ) _eventFlow.emit(UIEvent.ShowSnackbar(result.message)) } } }.launchIn(this) } } is ImageDetailsEvent.DeleteComment -> { viewModelScope.launch { _imageUseCases.deleteComment( comment = event.comment, id = image.value.id!! ).onEach { result -> when (result) { is Resource.Loading -> { _state.value = state.value.copy( isLoading = true, error = "", result = null ) } is Resource.Success -> { _state.value = state.value.copy( isLoading = false, error = "", result = result.data ) onEvent(ImageDetailsEvent.GetImageComments(image.value.id!!)) } is Resource.Error -> { _state.value = state.value.copy( isLoading = false, error = result.message!!, result = null ) _eventFlow.emit(UIEvent.ShowSnackbar(result.message)) } } }.launchIn(this) } } is ImageDetailsEvent.AddImageToFavorites -> { _userFavorites.add(event.id) _user.value = user.value.copy( favorites = _userFavorites ) onEvent(ImageDetailsEvent.UpdateUserData(user.value)) } is ImageDetailsEvent.RemoveFromFavorites -> { _userFavorites.remove(event.id) _user.value = user.value.copy( favorites = _userFavorites ) onEvent(ImageDetailsEvent.UpdateUserData(user.value)) } is ImageDetailsEvent.LikeImage -> { _imageLikedBy.add(user.value.uid!!) _image.value = image.value.copy( likes = _imageLikedBy.size, likedBy = _imageLikedBy ) onEvent(ImageDetailsEvent.UpdateImage) } is ImageDetailsEvent.DislikeImage -> { _imageLikedBy.remove(user.value.uid!!) _image.value = image.value.copy( likes = _imageLikedBy.size, likedBy = _imageLikedBy ) onEvent(ImageDetailsEvent.UpdateImage) } is ImageDetailsEvent.UpdateImage -> { viewModelScope.launch { _imageUseCases.editImage(image = image.value).onEach { result -> when (result) { is Resource.Loading -> { _state.value = state.value.copy( isLoading = true, error = "", result = null ) } is Resource.Success -> { _state.value = state.value.copy( isLoading = false, error = "", result = result.data ) } is Resource.Error -> { _state.value = state.value.copy( isLoading = false, error = result.message!!, result = null ) _eventFlow.emit(UIEvent.ShowSnackbar(result.message)) } } }.launchIn(this) } } is ImageDetailsEvent.UpdateUserData -> { viewModelScope.launch { _profileUseCases.setOrUpdateUserData(user = event.user).onEach { result -> when (result) { is Resource.Loading -> { _state.value = state.value.copy( isLoading = true, error = "", result = null ) } is Resource.Success -> { _state.value = state.value.copy( isLoading = false, error = "", result = result.data ) } is Resource.Error -> { _state.value = state.value.copy( isLoading = false, error = result.message!!, result = null ) _eventFlow.emit(UIEvent.ShowSnackbar(result.message)) } } }.launchIn(this) } } is ImageDetailsEvent.AddStars -> { _imageStarredBy.add(user.value.uid!!) val sum = image.value.starsSum + event.count _image.value = image.value.copy( starredBy = _imageStarredBy, starsSum = sum, starsAvg = sum / _imageStarredBy.size.toFloat() ) onEvent(ImageDetailsEvent.UpdateImage) } } } }
0
Kotlin
0
0
7840bddb76687010d5282d106920c236133677e9
18,058
AppForArtists
MIT License
gi/src/commonMain/kotlin/org/anime_game_servers/multi_proto/gi/data/web_event/SetH5ActivityRedDotTimestampRsp.kt
Anime-Game-Servers
642,871,918
false
{"Kotlin": 1651536}
package org.anime_game_servers.multi_proto.gi.data.web_event import org.anime_game_servers.core.base.Version.GI_1_6_0 import org.anime_game_servers.core.base.annotations.AddedIn import org.anime_game_servers.core.base.annotations.proto.CommandType.* import org.anime_game_servers.core.base.annotations.proto.ProtoCommand import org.anime_game_servers.multi_proto.gi.data.general.Retcode @AddedIn(GI_1_6_0) @ProtoCommand(RESPONSE) internal interface SetH5ActivityRedDotTimestampRsp { var retcode: Retcode }
0
Kotlin
2
6
7639afe4f546aa5bbd9b4afc9c06c17f9547c588
512
anime-game-multi-proto
MIT License
shared/src/commonMain/kotlin/data/model/Flags.kt
dominikdoric
710,466,385
false
{"Kotlin": 11015, "Swift": 592, "Shell": 228}
package data.model import kotlinx.serialization.Serializable @Serializable data class Flags( val alt: String, val png: String, val svg: String )
0
Kotlin
0
0
dfd016d694c38df2a6fae8d475e35955cb7701aa
158
CountriesApp
Apache License 2.0
kommons-uri/src/jvmTest/kotlin/com/bkahlert/kommons/uri/DataURLStreamHandlerTest.kt
bkahlert
323,048,013
false
{"Kotlin": 1649529, "JavaScript": 540}
package com.bkahlert.kommons.uri import com.bkahlert.kommons.test.fixtures.EmojiTextDocumentFixture import io.kotest.matchers.shouldBe import org.junit.jupiter.api.Test import java.net.URL class DataURLStreamHandlerTest { private val url get() = URL(EmojiTextDocumentFixture.dataUri.toString()) @Test fun content_type() { url.openConnection().contentLength shouldBe 57 } @Test fun content_length_long() { url.openConnection().contentType shouldBe "text/plain;charset=UTF-8" } @Test fun input_stream() { url.openConnection().getInputStream().readBytes().decodeToString() shouldBe "a𝕓🫠🇩🇪👨🏾‍🦱👩‍👩‍👦‍👦" } }
5
Kotlin
0
18
747cb51cf6e6b729d574396a4938eabafbdac1fe
672
kommons
MIT License
app/src/main/java/com/example/githubviewer/util/Constants.kt
ahmedmaged3k1
749,707,365
false
{"Kotlin": 99529}
package com.example.githubviewer.util object Constants { const val USER_SETTINGS = "userSettings" const val APP_ENTRY = "appEntry" const val BASE_URL ="https://api.github.com" }
0
Kotlin
0
0
173d04920983603a956989caf0701d8b32f51e67
190
GithubViewer
MIT License
src/main/kotlin/creativeDSLs/chapter_05/classScope/modular.kt
DanielGronau
521,419,278
false
{"Kotlin": 132813, "CSS": 27709, "Java": 2033}
package creativeDSLs.chapter_05.classScope data class Modulus(val modulus: Long) { init { require(modulus > 1) } @JvmInline value class Modular(val n: Long) val Long.m get() = Modular(remainder(this)) val Int.m get() = Modular(remainder(this.toLong())) operator fun Modular.plus(that: Modular) = Modular(remainder(this.n + that.n)) operator fun Modular.minus(that: Modular) = Modular(remainder(this.n - that.n)) operator fun Modular.times(that: Modular) = Modular(remainder(this.n * that.n)) operator fun Modular.div(that: Modular) = Modular(remainder(this.n * inverse(that.n))) private fun remainder(n: Long) = when { n < 0 -> (n % modulus) + modulus else -> n % modulus } private data class GcdResult(val gcd: Long, val x: Long, val y: Long) private fun inverse(a: Long): Long = extendedGCD(a, modulus) .run { when (gcd) { 1L -> remainder(x) else -> throw ArithmeticException( "Can't divide by $a (mod $modulus)" ) } } private fun extendedGCD(a: Long, b: Long): GcdResult = when (b) { 0L -> GcdResult(a, 1, 0) else -> { val result = extendedGCD(b, a % b) val x = result.y val y = result.x - (a / b) * result.y GcdResult(result.gcd, x, y) } } } fun <R> modulus(m: Long, body: Modulus.() -> R) = with(Modulus(m)) { body() } fun main() { val x = modulus(7) { val a = 3.m + 5.m // Modular(n=1) val b = 3.m - 5.m // Modular(n=5) val c = 3.m * 5.m // Modular(n=1) val d = 3.m / 5.m // Modular(n=2) a + b + c + d } println(x) // Modular(n=2) modulus(10) { println(3.m + 5.m) println(3.m - 5.m) println(3.m * 5.m) //println(3.m / 5.m) println(3.m / 7.m) } }
0
Kotlin
0
0
d165ef95d4b75036ce1703880d23899386d11d6e
2,046
creativeDSLs
MIT License
app/src/main/kotlin/com/hana053/micropost/pages/relateduserlist/RelatedUserListService.kt
springboot-angular2-tutorial
52,337,279
false
null
package com.hana053.micropost.pages.relateduserlist import com.hana053.micropost.domain.RelatedUser import rx.Observable interface RelatedUserListService { fun listUsers(userId: Long): Observable<List<RelatedUser>> fun title(): String }
0
Kotlin
5
11
c609bfdaa867bd20a29fd4f64ab3a2b159e8c023
247
android-app
MIT License
framework/src/main/kotlin/com/kuki/framework/projector/ProjectionException.kt
akuchalskij
649,018,448
false
null
package com.kuki.framework.projector sealed class ProjectionException(message: String) : RuntimeException(message) { data class ProjectionNotFound(override val message: String) : ProjectionException(message) }
0
Kotlin
0
1
a72ecdf553a62d7d5b472362f50284e634e44207
216
kotlin-ktor-ddd-es-cqrs
Apache License 2.0
fcm-push-service/src/main/kotlin/com/icerockdev/service/fcmpush/NotificationData.kt
icerockdev
225,309,197
false
null
/* * Copyright 2019 IceRock MAG Inc. Use of this source code is governed by the Apache 2.0 license. */ package com.icerockdev.service.fcmpush data class NotificationData( val title: String, val body: String, val image: String? = null )
0
Kotlin
0
2
584a840581cb7c071da5ddd3e33e2192f03d1a2a
251
fcm-push-service
Apache License 2.0
data/src/androidTest/java/com/petrulak/cleankotlin/data/source/local/WeatherLocalSourceTest.kt
Petrulak
104,648,833
false
null
package com.petrulak.cleankotlin.data.source.local import android.arch.persistence.room.Room import android.support.test.InstrumentationRegistry import com.petrulak.cleankotlin.data.mapper.WeatherEntityMapper import com.petrulak.cleankotlin.domain.model.Weather import org.junit.After import org.junit.Assert import org.junit.Before import org.junit.Test class WeatherLocalSourceTest { lateinit var dataSource: WeatherLocalSource lateinit var database: WeatherDatabase lateinit var mapper: WeatherEntityMapper @Before fun setup() { database = Room.inMemoryDatabaseBuilder(InstrumentationRegistry.getContext(), WeatherDatabase::class.java).build() mapper = WeatherEntityMapper() dataSource = WeatherLocalSource(database, mapper) } @After @Throws(Exception::class) fun closeDb() { database.close() } @Test fun shouldInsertAndGetWeather() { val weather = Weather(30L, "Berlin", 123) dataSource.save(weather) val weatherEntity = dataSource.getWeatherForCity(weather.name).blockingFirst() Assert.assertEquals(weatherEntity.uid, weather.id) Assert.assertEquals(weatherEntity.name, weather.name) Assert.assertEquals(weatherEntity.visibility, weather.visibility) } }
0
Kotlin
10
111
51033f30ecdb9573000454f1b8890d20c2438002
1,299
android-kotlin-mvp-clean-architecture
MIT License
data/RF00026/rnartist.kts
fjossinet
449,239,232
false
{"Kotlin": 8214424}
import io.github.fjossinet.rnartist.core.* rnartist { ss { rfam { id = "RF00026" name = "consensus" use alignment numbering } } theme { details { value = 3 } color { location { 1 to 2 39 to 40 } value = "#98cca9" } color { location { 5 to 6 33 to 34 } value = "#3ed4f2" } color { location { 3 to 4 35 to 38 } value = "#cc5b75" } color { location { 7 to 32 } value = "#75ecfe" } color { location { 41 to 215 } value = "#61cba4" } } }
0
Kotlin
0
0
3016050675602d506a0e308f07d071abf1524b67
948
Rfam-for-RNArtist
MIT License
app/src/main/java/ir/dunijet/dunibazaar/ui/features/cart/CartScreen.kt
TheOriginalMehrdad
828,263,870
false
{"Kotlin": 133957}
package ir.dunijet.dunibazaar.ui.features.cart import android.content.Intent import android.content.res.Configuration import android.net.Uri import android.widget.Toast import androidx.compose.foundation.BorderStroke import androidx.compose.foundation.clickable import androidx.compose.foundation.layout.* import androidx.compose.foundation.lazy.LazyColumn import androidx.compose.material.* import androidx.compose.material.icons.Icons import androidx.compose.material.icons.filled.* import androidx.compose.runtime.Composable import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.draw.clip import androidx.compose.ui.graphics.Color import androidx.compose.ui.layout.ContentScale import androidx.compose.ui.platform.LocalConfiguration import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.res.painterResource import androidx.compose.ui.text.TextStyle import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.text.style.TextAlign import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.sp import coil.compose.AsyncImage import com.airbnb.lottie.compose.LottieAnimation import com.airbnb.lottie.compose.LottieCompositionSpec import com.airbnb.lottie.compose.LottieConstants import com.airbnb.lottie.compose.rememberLottieComposition import dev.burnoo.cokoin.navigation.getNavController import dev.burnoo.cokoin.navigation.getNavViewModel import ir.dunijet.dunibazaar.R import ir.dunijet.dunibazaar.model.data.Product import ir.dunijet.dunibazaar.ui.features.profile.AddUserLocationDataDialog import ir.dunijet.dunibazaar.ui.theme.Blue import ir.dunijet.dunibazaar.ui.theme.PriceBackground import ir.dunijet.dunibazaar.ui.theme.Shapes import ir.dunijet.dunibazaar.util.* @Composable fun CartScreen() { val context = LocalContext.current val getDataDialogState = remember { mutableStateOf(false) } val navigation = getNavController() val viewModel = getNavViewModel<CartViewModel>() viewModel.loadCartData() Box(modifier = Modifier.fillMaxSize(), contentAlignment = Alignment.BottomCenter) { Column( modifier = Modifier .fillMaxSize() .padding(bottom = 74.dp) ) { CartToolBar( onBackClicked = { navigation.popBackStack() }, onProfileClicked = { navigation.navigate(MyScreens.ProfileScreen.route) }) if (viewModel.productList.value.isNotEmpty()) { CartList( data = viewModel.productList.value, isChangingNumber = viewModel.isChangingNumber.value, onAddItemClicked = { viewModel.addItem(it) }, onRemoveItemClicked = { viewModel.removeItem(it) }, onItemClicked = { navigation.navigate(MyScreens.ProductScreen.route + "/" + it) }) } else { NoDataMainAnimation() } } PurchaseAll(totalPrice = viewModel.totalPrice.value.toString()) { if (viewModel.productList.value.isNotEmpty()) { val locationData = viewModel.getUserLocation() if (locationData.first == "click to add" || locationData.second == "click to add") { getDataDialogState.value = true } else { viewModel.purchaseAll( locationData.first, locationData.second ) { success, link -> if (success) { Toast.makeText(context, "Pay using zarinpal portal", Toast.LENGTH_SHORT) .show() viewModel.setPaymentStatus(PAYMENT_PENDING) val intent = Intent(Intent.ACTION_VIEW, Uri.parse(link)) context.startActivity(intent) } else { Toast.makeText( context, "There are some issues in payment process!", Toast.LENGTH_SHORT ).show() } } } } else { Toast.makeText(context, "Please add some stuff first!", Toast.LENGTH_SHORT).show() } } if (getDataDialogState.value) { AddUserLocationDataDialog( showSaveLocation = true, onDismiss = { getDataDialogState.value = false }, onSubmitClicked = { adress, postalCode, isChecked -> if (NetworkChecker(context).isInternetConnected) { if (isChecked) { viewModel.setUserLocation(adress, postalCode) } viewModel.purchaseAll( adress, postalCode ) { success, link -> if (success) { Toast.makeText( context, "Pay using zarinpal portal", Toast.LENGTH_SHORT ) .show() viewModel.setPaymentStatus(PAYMENT_PENDING) val intent = Intent(Intent.ACTION_VIEW, Uri.parse(link)) context.startActivity(intent) } else { Toast.makeText( context, "There are some issues in payment process!", Toast.LENGTH_SHORT ).show() } } } else { Toast.makeText( context, "Please connect to the internet first!", Toast.LENGTH_SHORT ).show() } }) } } } @Composable fun CartItem( data: Product, isChangingNumber: Pair<String, Boolean>, onAddItemClicked: (String) -> Unit, onRemoveItemClicked: (String) -> Unit, onItemClicked: (String) -> Unit ) { Card( modifier = Modifier .fillMaxSize() .padding(start = 18.dp, end = 18.dp, top = 18.dp) .clickable { onItemClicked.invoke(data.productId) }, elevation = 6.dp, shape = Shapes.large ) { Column { AsyncImage( modifier = Modifier .fillMaxWidth() .height(199.dp), model = data.imgUrl, contentDescription = null, contentScale = ContentScale.Crop ) Row( modifier = Modifier .fillMaxWidth() .padding(start = 3.dp, bottom = 9.dp), horizontalArrangement = Arrangement.SpaceBetween, ) { Column { Text( modifier = Modifier.padding(start = 6.dp, top = 6.dp), text = data.name, fontSize = 16.sp, fontWeight = FontWeight.Bold ) Text( modifier = Modifier.padding(start = 6.dp, top = 6.dp), text = "From " + data.category + " Group", fontSize = 16.sp, fontWeight = FontWeight.Bold ) Text( modifier = Modifier.padding(start = 6.dp, top = 18.dp), text = "Product Authenticity Guarantee", fontSize = 16.sp, fontWeight = FontWeight.Bold ) Text( modifier = Modifier.padding(start = 6.dp, top = 6.dp), text = "Available Stock In Ship", fontSize = 16.sp, fontWeight = FontWeight.Bold ) Surface( modifier = Modifier .padding(top = 18.dp, bottom = 6.dp) .clip(Shapes.large), color = PriceBackground ) { Text( modifier = Modifier.padding(6.dp), text = stylePrice( ((data.price.toInt()) * ((data.quantity ?: "1").toInt())).toString() ), fontSize = 13.sp, fontWeight = FontWeight.Medium ) } } Surface( modifier = Modifier .wrapContentSize() .align(Alignment.Bottom) .padding(bottom = 13.dp, end = 9.dp) ) { Card( border = BorderStroke(3.dp, Blue) ) { Row( verticalAlignment = Alignment.CenterVertically ) { if (data.quantity?.toInt() == 1) { IconButton( onClick = { onRemoveItemClicked.invoke(data.productId) }) { Icon( modifier = Modifier.padding(end = 6.dp, start = 6.dp), imageVector = Icons.Default.Delete, contentDescription = null ) } } else { IconButton( onClick = { onRemoveItemClicked.invoke(data.productId) }) { Icon( modifier = Modifier.padding(end = 6.dp, start = 6.dp), painter = painterResource(id = R.drawable.ic_minus), contentDescription = null ) } } if (isChangingNumber.first == data.productId && isChangingNumber.second) { Text( text = "...", fontSize = 18.sp, modifier = Modifier.padding(bottom = 13.dp) ) } else { Text( text = data.quantity ?: "1", fontSize = 18.sp, modifier = Modifier.padding(bottom = 3.dp) ) } IconButton( onClick = { onAddItemClicked.invoke(data.productId) }) { Icon( modifier = Modifier.padding(end = 6.dp, start = 6.dp), imageVector = Icons.Default.Add, contentDescription = null ) } } } } } } } } @Composable fun CartList( data: List<Product>, isChangingNumber: Pair<String, Boolean>, onAddItemClicked: (String) -> Unit, onRemoveItemClicked: (String) -> Unit, onItemClicked: (String) -> Unit ) { LazyColumn( modifier = Modifier.fillMaxSize(), contentPadding = PaddingValues(bottom = 18.dp) ) { items(data.size) { CartItem( data = data[it], isChangingNumber = isChangingNumber, onAddItemClicked = onAddItemClicked, onRemoveItemClicked = onRemoveItemClicked, onItemClicked = onItemClicked ) } } } @Composable fun CartToolBar( onBackClicked: () -> Unit, onProfileClicked: () -> Unit ) { TopAppBar( navigationIcon = { IconButton(onClick = { onBackClicked.invoke() }) { Icon(imageVector = Icons.Default.ArrowBack, contentDescription = null) } }, elevation = 3.dp, backgroundColor = Color.White, modifier = Modifier.fillMaxWidth(), title = { Text( text = "My Cart", textAlign = TextAlign.Center, modifier = Modifier .fillMaxWidth() .padding(end = 11.dp) ) }, actions = { IconButton(onClick = { onProfileClicked.invoke() }) { Icon(imageVector = Icons.Default.Person, contentDescription = null) } } ) } @Composable fun NoDataMainAnimation() { val composition by rememberLottieComposition(LottieCompositionSpec.RawRes(R.raw.no_data)) LottieAnimation(composition = composition, iterations = LottieConstants.IterateForever) } @Composable fun PurchaseAll( totalPrice: String, OnPurchaseClicked: () -> Unit ) { val context = LocalContext.current val configuration = LocalConfiguration.current val fraction = if (configuration.orientation == Configuration.ORIENTATION_LANDSCAPE) 0.15f else 0.07f Surface( color = Color.White, modifier = Modifier .fillMaxWidth() .fillMaxHeight(fraction) ) { Row( modifier = Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.SpaceBetween, verticalAlignment = Alignment.CenterVertically ) { Button( modifier = Modifier .padding(start = 16.dp) .size(182.dp, 40.dp), onClick = { if (NetworkChecker(context).isInternetConnected) { OnPurchaseClicked.invoke() } else { Toast.makeText(context, "please connect to internet...", Toast.LENGTH_SHORT) .show() } } ) { Text( modifier = Modifier.padding(2.dp), text = "Let's Purchase !", color = Color.White, style = TextStyle(fontSize = 16.sp, fontWeight = FontWeight.Medium) ) } Surface( modifier = Modifier .padding(end = 16.dp) .clip(Shapes.large), color = PriceBackground ) { Text( modifier = Modifier.padding( top = 6.dp, bottom = 6.dp, start = 8.dp, end = 8.dp ), text = "total : " + stylePrice(totalPrice), style = TextStyle(fontSize = 14.sp, fontWeight = FontWeight.Medium) ) } } } }
0
Kotlin
0
0
43579156ae5f596f980dc055879463853c4c3fc8
15,986
Store
MIT License
soil-query-test/src/commonMain/kotlin/soil/query/test/FakeInfiniteQueryKey.kt
soil-kt
789,648,330
false
{"Kotlin": 789346, "Makefile": 1014}
// Copyright 2024 Soil Contributors // SPDX-License-Identifier: Apache-2.0 package soil.query.test import soil.query.InfiniteQueryKey import soil.query.QueryReceiver /** * Creates a fake infinite query key that returns the result of the given [mock] function. */ class FakeInfiniteQueryKey<T, S>( private val target: InfiniteQueryKey<T, S>, private val mock: FakeInfiniteQueryFetch<T, S> ) : InfiniteQueryKey<T, S> by target { override val fetch: suspend QueryReceiver.(param: S) -> T = { mock(it) } } typealias FakeInfiniteQueryFetch<T, S> = suspend (param: S) -> T
0
Kotlin
1
109
25c3fdd81db98ea44afbaf2776421373ed2d3d05
585
soil
Apache License 2.0
src/main/kotlin/MainStyles.kt
technical-learn-room
382,007,951
false
null
import kotlinx.css.* import styled.StyleSheet object MainStyles : StyleSheet("WelcomeStyles", isStatic = true) { val toDoListTitle by css { width = 100.vw height = 10.vh backgroundColor = rgb(0, 0, 0) color = rgb(255, 255, 255) fontSize = 50.px } val todoListBody by css { width = 100.vw height = 80.vh backgroundColor = rgb(255, 255, 255) } val footer by css { width = 100.vw height = 10.vh backgroundColor = rgb(0, 0, 0) color = rgb(255, 255, 255) fontSize = 20.px } val textCenterAlignment by css { textAlign = TextAlign.center display = Display.flex alignItems = Align.center justifyContent = JustifyContent.center } }
0
Kotlin
0
9
3fc8dea83dbe1a01cd15dee7102537f5a84f3ed6
799
kotlin-react-learn
MIT License
build-logic/convention/src/test/kotlin/pl/droidsonroids/composekit/modulegenerator/GenerateComposeModuleTest.kt
DroidsOnRoids
514,214,122
false
{"Kotlin": 105234}
package pl.droidsonroids.composekit.modulegenerator import io.mockk.MockKAnnotations import io.mockk.every import io.mockk.impl.annotations.MockK import org.assertj.core.api.Assertions.assertThat import org.gradle.api.Project import org.junit.Before import org.junit.Rule import org.junit.Test import org.junit.rules.TemporaryFolder import pl.droidsonroids.composekit.modulegenerator.utils.LinuxSeparatorProvider import java.io.File internal class GenerateComposeModuleTest { @get:Rule var testFolder: TemporaryFolder = TemporaryFolder() @MockK private lateinit var project: Project private val generateComposeModule = GenerateComposeModule(provider) @Before fun setup() { MockKAnnotations.init(this) every { project.rootDir } returns testFolder.newFolder("root") } @Test fun `generate compose module structure`() = testStructureGeneration(TestData.NestedModuleTestData) @Test fun `generate compose module structure under projects root`() = testStructureGeneration(TestData.RootDirModuleTestData) private fun testStructureGeneration(testData: TestData) { generateComposeModule(project.rootDir, testData.nutshell) val basePath = project.rootDir.path val actual = project.rootDir .walkTopDown() .map { it.path.removePrefix(basePath) } .filter { it.isNotBlank() } .toList() assertThat(actual).containsExactlyInAnyOrderElementsOf(testData.expectedDirTree) assertThat(project.rootDir.findSettingsGradle()).hasContent(testData.settingsGradleContent) assertThat(project.rootDir.findBuildGradle()).hasContent(testData.buildGradleContent) } private fun File.findSettingsGradle(): File = walkTopDown().first { it.path.endsWith(SETTINGS_GRADLE_FILE_NAME) } private fun File.findBuildGradle(): File = walkTopDown().first { it.path.endsWith(BUILD_GRADLE_FILE_NAME) } companion object { val provider = LinuxSeparatorProvider private const val BUILD_GRADLE_FILE_NAME = "build.gradle.kts" private const val SETTINGS_GRADLE_FILE_NAME = "settings.gradle.kts" } private interface TestData { val nutshell: String val buildGradleContent: String val settingsGradleContent: String val androidManifestContent: String val expectedDirTree: List<String> object NestedModuleTestData : TestData { override val nutshell = "testPath.deeper.testModule" override val buildGradleContent = "plugins {\n with(libs.plugins) {\n alias(composekit.android.library)\n alias(composekit.android.library.compose)\n }\n}\n\nandroid {\n namespace = \"pl.droidsonroids.composekit.testpath.deeper.testmodule\"\n}\n\ndependencies {}" override val settingsGradleContent = "\n/* OK */ include(\":testPath:deeper:testModule\")" override val androidManifestContent = "<manifest package=\"pl.droidsonroids.composekit.testpath.deeper.testmodule\"/>" override val expectedDirTree = listOf( "/$SETTINGS_GRADLE_FILE_NAME", "/testPath", "/testPath/deeper", "/testPath/deeper/testModule", "/testPath/deeper/testModule/$BUILD_GRADLE_FILE_NAME", "/testPath/deeper/testModule/src", "/testPath/deeper/testModule/src/main", "/testPath/deeper/testModule/src/main/res", "/testPath/deeper/testModule/src/main/res/layout", "/testPath/deeper/testModule/src/main/res/values", "/testPath/deeper/testModule/src/main/kotlin", "/testPath/deeper/testModule/src/main/kotlin/pl", "/testPath/deeper/testModule/src/main/kotlin/pl/droidsonroids", "/testPath/deeper/testModule/src/main/kotlin/pl/droidsonroids/composekit", "/testPath/deeper/testModule/src/main/kotlin/pl/droidsonroids/composekit/testpath", "/testPath/deeper/testModule/src/main/kotlin/pl/droidsonroids/composekit/testpath/deeper", "/testPath/deeper/testModule/src/main/kotlin/pl/droidsonroids/composekit/testpath/deeper/testmodule", "/testPath/deeper/testModule/src/test", "/testPath/deeper/testModule/src/test/kotlin", "/testPath/deeper/testModule/src/test/kotlin/pl", "/testPath/deeper/testModule/src/test/kotlin/pl/droidsonroids", "/testPath/deeper/testModule/src/test/kotlin/pl/droidsonroids/composekit", "/testPath/deeper/testModule/src/test/kotlin/pl/droidsonroids/composekit/testpath", "/testPath/deeper/testModule/src/test/kotlin/pl/droidsonroids/composekit/testpath/deeper", "/testPath/deeper/testModule/src/test/kotlin/pl/droidsonroids/composekit/testpath/deeper/testmodule" ) } object RootDirModuleTestData : TestData { override val nutshell = "testModule" override val buildGradleContent = "plugins {\n with(libs.plugins) {\n alias(composekit.android.library)\n alias(composekit.android.library.compose)\n }\n}\n\nandroid {\n namespace = \"pl.droidsonroids.composekit.testmodule\"\n}\n\ndependencies {}" override val settingsGradleContent = "\n/* OK */ include(\":testModule\")" override val androidManifestContent = "<manifest package=\"pl.droidsonroids.composekit.testmodule\"/>" override val expectedDirTree = listOf( "/$SETTINGS_GRADLE_FILE_NAME", "/testModule", "/testModule/$BUILD_GRADLE_FILE_NAME", "/testModule/src", "/testModule/src/main", "/testModule/src/main/res", "/testModule/src/main/res/layout", "/testModule/src/main/res/values", "/testModule/src/main/kotlin", "/testModule/src/main/kotlin/pl", "/testModule/src/main/kotlin/pl/droidsonroids", "/testModule/src/main/kotlin/pl/droidsonroids/composekit", "/testModule/src/main/kotlin/pl/droidsonroids/composekit/testmodule", "/testModule/src/test", "/testModule/src/test/kotlin", "/testModule/src/test/kotlin/pl", "/testModule/src/test/kotlin/pl/droidsonroids", "/testModule/src/test/kotlin/pl/droidsonroids/composekit", "/testModule/src/test/kotlin/pl/droidsonroids/composekit/testmodule", ) } } }
29
Kotlin
0
0
61097320067374bafc35eb333c38d8e8a4497637
6,709
ComposeKit
MIT License
src/jvmMain/kotlin/com/github/doyaaaaaken/kotlincsv/client/CsvWriter.kt
jul1u5
278,604,278
true
{"Kotlin": 72584}
package com.github.doyaaaaaken.kotlincsv.client import com.github.doyaaaaaken.kotlincsv.dsl.context.CsvWriterContext import com.github.doyaaaaaken.kotlincsv.dsl.context.ICsvWriterContext import java.io.* /** * CSV Writer class, which decides where to write and returns CsvFileWriter class (class for controlling File I/O). * * @see CsvFileWriter * * @author doyaaaaaken */ actual class CsvWriter actual constructor( private val ctx: CsvWriterContext ) : ICsvWriterContext by ctx { actual fun open(targetFileName: String, append: Boolean, write: ICsvFileWriter.() -> Unit) { val targetFile = File(targetFileName) open(targetFile, append, write) } fun open(targetFile: File, append: Boolean = false, write: ICsvFileWriter.() -> Unit) { val fos = FileOutputStream(targetFile, append) open(fos, write) } fun open(ops: OutputStream, write: ICsvFileWriter.() -> Unit) { val osw = OutputStreamWriter(ops, ctx.charset) val writer = CsvFileWriter(ctx, PrintWriter(osw)) writer.use { it.write() } } /** * write all rows on assigned target file */ actual fun writeAll(rows: List<List<Any?>>, targetFileName: String, append: Boolean) { open(targetFileName, append) { writeRows(rows) } } /** * write all rows on assigned target file */ fun writeAll(rows: List<List<Any?>>, targetFile: File, append: Boolean = false) { open(targetFile, append) { writeRows(rows) } } /** * write all rows on assigned output stream */ fun writeAll(rows: List<List<Any?>>, ops: OutputStream) { open(ops) { writeRows(rows) } } }
0
null
0
0
fc1415667946e80d69fbe96c04d1bf257606bb91
1,686
kotlin-csv
Apache License 2.0
Framework/src/main/kotlin/net/milosvasic/factory/component/installer/step/certificate/GeneratePrivateKeyCommand.kt
Server-Factory
326,063,014
true
{"Kotlin": 470923, "Shell": 188}
package net.milosvasic.factory.component.installer.step.certificate import net.milosvasic.factory.terminal.TerminalCommand import net.milosvasic.factory.terminal.command.Commands import java.nio.file.InvalidPathException class GeneratePrivateKeyCommand @Throws(InvalidPathException::class) constructor(path: String, name: String) : TerminalCommand( Commands.generatePrivateKey(path, name) )
0
Kotlin
0
1
7c9a48ac22541c01d56cb7ed404348f9dbcf6d6d
402
Core-Framework
Apache License 2.0
src/main/java/ru/hollowhorizon/hollowengine/client/screen/widget/action/ProcedureWidget.kt
HollowHorizon
586,593,959
false
null
package ru.hollowhorizon.hollowengine.client.screen.widget.action import com.mojang.blaze3d.matrix.MatrixStack import com.mojang.blaze3d.systems.RenderSystem import org.lwjgl.glfw.GLFW import ru.hollowhorizon.hc.client.screens.widget.HollowWidget import ru.hollowhorizon.hc.client.utils.mc import ru.hollowhorizon.hc.client.utils.toRGBA import ru.hollowhorizon.hc.client.utils.toSTC import ru.hollowhorizon.hollowengine.HollowEngine.MODID import ru.hollowhorizon.hollowengine.client.screen.VisualEditorScreen abstract class ProcedureWidget(x: Int, y: Int, width: Int, height: Int, color: Int = 0x18CDED) : HollowWidget(x, y, width, height, "".toSTC()), IProcedureLoader { private var lineDriver: LineDrawer? = null var isLeftClicked: Boolean = false var canMove = false var isStartConnecting: Boolean = false var resizeStatus: ResizeStatus = ResizeStatus.NONE var parent: ProcedureWidget? = null var children: MutableList<ProcedureWidget> = mutableListOf() private var color = color.toRGBA() @Suppress("DEPRECATION") override fun renderButton(stack: MatrixStack, mouseX: Int, mouseY: Int, ticks: Float) { if(lineDriver != null) { lineDriver!!.render(stack, mouseX, mouseY) } drawConnections(stack) drawNodes(stack) bind(MODID, "gui/widgets/procedure_widget.png") RenderSystem.color4f(color.r, color.g, color.b, 1.0F) drawWidget(stack) RenderSystem.color4f(1f, 1f, 1f, 1f) } private fun drawConnections(stack: MatrixStack) { val drawer = LineDrawer(this.x + width, this.y + height / 2) for(child in children) { drawer.render(stack, child.x, child.y + child.height / 2) } } private fun drawNodes(stack: MatrixStack) { bind(MODID, "gui/widgets/orb.png") blit(stack, x - 5, y + height / 2 - 5, 0F, (if (parent != null) 0 else 1) * 10F, 10, 10, 10, 30) blit( stack, x + width - 5, y + height / 2 - 5, 0F, ( when (children.size) { 0 -> 1 1 -> 0 else -> 2 } ) * 10F, 10, 10, 10, 30 ) } override fun mouseClicked(mouseX: Double, mouseY: Double, button: Int): Boolean { if (button == GLFW.GLFW_MOUSE_BUTTON_LEFT && isHovered) { if(mouseX > this.x + width - 5 && mouseX < this.x + width + 5 && mouseY > this.y + height / 2 - 5 && mouseY < this.y + height / 2 + 5) { isStartConnecting = true this.lineDriver = LineDrawer(this.x + width, this.y + height / 2) return true } isLeftClicked = true calculateResizeStatus(mouseX, mouseY) return true } return super.mouseClicked(mouseX, mouseY, button) } fun calculateResizeStatus(mouseX: Double, mouseY: Double) { val x = mouseX - this.x val y = mouseY - this.y val size = 10 resizeStatus = if (x < size && y < size) { ResizeStatus.TOP_LEFT } else if (x > width - size && y < size) { ResizeStatus.TOP_RIGHT } else if (x < size && y > height - size) { ResizeStatus.BOTTOM_LEFT } else if (x > width - size && y > height - size) { ResizeStatus.BOTTOM_RIGHT } else if (x < size) { ResizeStatus.LEFT } else if (x > width - size) { ResizeStatus.RIGHT } else if (y < size) { ResizeStatus.TOP } else if (y > height - size) { ResizeStatus.BOTTOM } else { ResizeStatus.NONE } } override fun mouseMoved(mouseX: Double, mouseY: Double) { if (isLeftClicked) { val sizeX = width - mouseX.toInt() - this.x val sizeY = height - mouseY.toInt() - this.y when (resizeStatus) { ResizeStatus.TOP_LEFT -> { if (sizeX < 20 || sizeY < 20 || sizeX > 200 || sizeY > 100) return width -= mouseX.toInt() - this.x height -= mouseY.toInt() - this.y this.x = mouseX.toInt() this.y = mouseY.toInt() width = width.lerp(20, 200) height = height.lerp(20, 100) return } ResizeStatus.TOP_RIGHT -> { if (sizeX < 20 || sizeY < 20 || sizeX > 200 || sizeY > 100) return width += mouseX.toInt() - this.x - width height -= mouseY.toInt() - this.y this.y = mouseY.toInt() width = width.lerp(20, 200) height = height.lerp(20, 100) return } ResizeStatus.BOTTOM_LEFT -> { if (sizeX < 20 || sizeY < 20 || sizeX > 200 || sizeY > 100) return width -= mouseX.toInt() - this.x height += mouseY.toInt() - this.y - height this.x = mouseX.toInt() width = width.lerp(20, 200) height = height.lerp(20, 100) return } ResizeStatus.BOTTOM_RIGHT -> { width += mouseX.toInt() - this.x - width height += mouseY.toInt() - this.y - height width = width.lerp(20, 200) height = height.lerp(20, 100) return } ResizeStatus.LEFT -> { if (sizeX < 20 || sizeY < 20 || sizeX > 200 || sizeY > 100) return width -= mouseX.toInt() - this.x this.x = mouseX.toInt() width = width.lerp(20, 200) height = height.lerp(20, 100) return } ResizeStatus.RIGHT -> { width += mouseX.toInt() - this.x - width width = width.lerp(20, 200) height = height.lerp(20, 100) return } ResizeStatus.TOP -> { if (sizeX < 20 || sizeY < 20 || sizeX > 200 || sizeY > 100) return height -= mouseY.toInt() - this.y this.y = mouseY.toInt() width = width.lerp(20, 200) height = height.lerp(20, 100) return } ResizeStatus.BOTTOM -> { height += mouseY.toInt() - this.y - height width = width.lerp(20, 200) height = height.lerp(20, 100) return } else -> {} } this.setX(mouseX.toInt()-width/2) this.setY(mouseY.toInt()-height/2) } } override fun mouseReleased(mouseX: Double, mouseY: Double, button: Int): Boolean { if (button == GLFW.GLFW_MOUSE_BUTTON_LEFT) { if(isStartConnecting) { isStartConnecting = false this.lineDriver = null mc.screen?.let { if(it is VisualEditorScreen) { val widget = it.getWidgetAt(mouseX, mouseY) if(widget != null && widget != this) { this.children.add(widget) widget.parent = this } } } return true } isLeftClicked = false } return super.mouseReleased(mouseX, mouseY, button) } fun drawWidget(stack: MatrixStack) { if (width > height) { val size = height / 3 blit(stack, x, y, 0F, 0F, size, size, size * 3, size * 3) blit(stack, x + size, y, width - size * 2F, 0F, width - size * 2, size, (width - size * 2) * 3, size * 3) blit(stack, x + width - size, y, size * 2F, 0F, size, size, size * 3, size * 3) blit(stack, x, y + size, 0F, size * 1F, size, height - size * 2, size * 3, (height - size * 2) * 3) blit(stack, x + size, y + size, width - size * 2F, size * 1F, width - size * 2, height - size * 2, (width - size * 2) * 3, (height - size * 2) * 3) blit(stack,x + width - size, y + size, size * 2F, size * 1F, size, height - size * 2, size * 3, (height - size * 2) * 3) blit(stack, x, y + height - size, 0F, size * 2F, size, size, size * 3, size * 3) blit(stack, x + size, y + height - size, width - size * 2F, size * 2F, width - size * 2, size, (width - size * 2) * 3, size * 3) blit(stack, x + width - size, y + height - size, size * 2F, size * 2F, size, size, size * 3, size * 3) } else { val size = width / 3 blit(stack, x, y, 0F, 0F, size, size, size * 3, size * 3) blit(stack, x + size, y, width - size * 2F, 0F, width - size * 2, size, (width - size * 2) * 3, size * 3) blit(stack, x + width - size, y, size * 2F, 0F, size, size, size * 3, size * 3) blit(stack, x, y + size, 0F, height - size * 2F, size, height - size * 2, size * 3, (height - size * 2) * 3) blit(stack, x + size, y + size, width - size * 2F, height - size * 2F, width - size * 2, height - size * 2, (width - size * 2) * 3, (height - size * 2) * 3) blit(stack, x + width - size, y + size, size * 2F, height - size * 2F, size, height - size * 2, size * 3, (height - size * 2) * 3) blit(stack, x, y + height - size, 0F, size * 2F, size, size, size * 3, size * 3) blit(stack, x + size, y + height - size, width - size * 2F, size * 2F, width - size * 2, size, (width - size * 2) * 3, size * 3) blit(stack, x + width - size, y + height - size, size * 2F, size * 2F, size, size, size * 3, size * 3) } } enum class ResizeStatus { NONE, LEFT, RIGHT, TOP, BOTTOM, TOP_LEFT, TOP_RIGHT, BOTTOM_LEFT, BOTTOM_RIGHT } fun Int.lerp(min: Int, max: Int): Int { return if (this < min) min else if (this > max) max else this } fun canConnect(mouseX: Double, mouseY: Double): Boolean { return mouseX >= x - 5 && mouseX <= x + 5 && mouseY >= y + height / 2 - 5 && mouseY <= y + height / 2 + 5 } }
0
Kotlin
0
2
6cd5561f599ff7afc638417dfbd1582bc37e31a1
10,509
HollowEngine
MIT License
flux/src/main/java/com/wgw/flux/RxBus.kt
wanggaowan
172,438,583
false
null
package com.wgw.flux import io.reactivex.Observable import io.reactivex.subjects.PublishSubject /** * 发送Action,增加订阅 * * @author Created by 汪高皖 on 2019/2/21 0021 13:52 */ internal class RxBus { private val bus = PublishSubject.create<Any>().toSerialized() /** * 发射[Action] */ fun post(action: Action) { bus.onNext(action) } /** * return an [Observable] that emits items from the source ObservableSource of type [Action].class */ fun toObservable(): Observable<Action> { return bus.ofType(Action::class.java) } }
0
Kotlin
0
0
698934cdfbdaeb1fc6ecdf3cae735712881c6dcf
584
AndroidFluxKotlin
Apache License 2.0
mongo-config/src/main/kotlin/it/scoppelletti/mongo/config/MongoConfig.kt
dscoppelletti
385,976,384
false
null
/* * Copyright (C) 2021 <NAME>, <http://www.scoppelletti.it/>. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ @file:Suppress("RemoveRedundantQualifierName") package it.scoppelletti.mongo.config import com.mongodb.ConnectionString import com.mongodb.MongoClientSettings import com.mongodb.MongoCredential import com.squareup.moshi.JsonClass import com.squareup.moshi.Moshi import java.io.File import java.io.IOException import java.io.InputStream import mu.KotlinLogging import okio.BufferedSource import okio.Source import okio.buffer import okio.source import org.apache.commons.lang3.SystemUtils @JsonClass(generateAdapter = true) data class MongoConfig( val uri: String, val userName: String, @JsonPassword val password: CharArray, val database: String ) { internal fun toConnectionString() = ConnectionString(uri) internal fun toMongoCredential(): MongoCredential = MongoCredential.createCredential(userName, MongoConfig.DB_ADMIN, password) override fun equals(other: Any?): Boolean { val op = other as? MongoConfig ?: return false return MongoConfigDelegate.copy(this, false) == MongoConfigDelegate.copy(op, false) } override fun hashCode(): Int { return MongoConfigDelegate.copy(this, false).hashCode() } override fun toString(): String { return MongoConfigDelegate.copy(this, true).toString() } companion object { @Suppress("WeakerAccess") const val DB_ADMIN = "admin" @Suppress("WeakerAccess") const val ENV_CONFIG = "MONGO_CONFIG_FILE" @Suppress("WeakerAccess") const val FILE_CONFIG = ".scoppelletti/mongo.json" private val logger = KotlinLogging.logger { } fun load(): MongoConfig { val data: MongoConfig var stream: InputStream? = null var source: Source? = null var reader: BufferedSource? = null val moshi = Moshi.Builder() .add(CharArray::class.java, JsonPassword::class.java, PasswordAdapter()) .build() val adapter = moshi.adapter(MongoConfig::class.java) val env = SystemUtils.getEnvironmentVariable( MongoConfig.ENV_CONFIG, "") val file = if (env.isBlank()) { File(SystemUtils.getUserHome(), MongoConfig.FILE_CONFIG) } else File(env) try { stream = file.inputStream() source = stream.source() stream = null reader = source.buffer() source = null data = adapter.fromJson(reader) ?: throw IOException("Failed to read file ${file}.") } catch (ex: Exception) { throw IOException("Failed to read file ${file}.", ex) } finally { stream?.close() source?.close() reader?.close() } logger.info { "Load $data from $file." } return data } } } fun MongoClientSettings.Builder.applyConfig( config: MongoConfig ): MongoClientSettings.Builder = this .applyConnectionString(config.toConnectionString()) .credential(config.toMongoCredential()) private data class MongoConfigDelegate( val uri: String, val userName: String, val password: String, val database: String ) { companion object { fun copy(source: MongoConfig, secured: Boolean) = MongoConfigDelegate( source.uri, source.userName, if (secured) "********" else source.password.toString(), source.database) } }
0
Kotlin
0
0
7bd27e2d7fd6aa06a4d0b89b3d81aa214e1a0de5
4,236
kb
Apache License 2.0
manager/presentation/src/main/java/com/cadrikmdev/manager/presentation/screens/manager_overview/ManagerOverviewViewModel.kt
specure
873,558,864
false
{"Kotlin": 183802}
package com.cadrikmdev.manager.presentation.screens.manager_overview import android.Manifest import android.content.Context import android.media.Ringtone import android.media.RingtoneManager import android.net.Uri import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.setValue import androidx.lifecycle.ViewModel import androidx.lifecycle.viewModelScope import com.cadrikmdev.core.domain.config.Config import com.cadrikmdev.core.domain.service.BluetoothService import com.cadrikmdev.core.presentation.ui.config.AppConfig import com.cadrikmdev.intercom.domain.client.BluetoothClientService import com.cadrikmdev.intercom.domain.client.DeviceType import com.cadrikmdev.intercom.domain.message.TrackerAction import com.cadrikmdev.permissions.domain.PermissionHandler import com.cadrikmdev.permissions.presentation.appPermissions import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.flow.launchIn import kotlinx.coroutines.flow.onEach import kotlinx.coroutines.launch import timber.log.Timber class ManagerOverviewViewModel( private val appContext: Context, private val appConfig: Config, private val applicationScope: CoroutineScope, private val bluetoothService: BluetoothClientService, private val androidBluetoothService: BluetoothService, private val permissionHandler: PermissionHandler, ) : ViewModel() { var state by mutableStateOf(ManagerOverviewState()) private set init { permissionHandler.setPermissionsNeeded( appPermissions ) manageBluetoothDevices() // viewModelScope.launch { // delay(2000) // state = state.copy( // managedDevices = listOf( // TrackingDeviceUi( // "Samsung A52", // "running", // System.currentTimeMillis() // ) // ) // ) // } } private fun playAlertSound() { if (appConfig.isAlertSoundOnTestErrorEnabled()) { val alert: Uri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION) val ringtone: Ringtone = RingtoneManager.getRingtone(appContext, alert) ringtone.play() } } private fun manageBluetoothDevices() { if (permissionHandler.isPermissionGranted(Manifest.permission.BLUETOOTH_CONNECT) && state.isBluetoothAdapterEnabled) { bluetoothService.observeConnectedDevices(DeviceType.TRACKER) .onEach { devices -> state = state.copy( managedDevices = devices.values.toList() ) } .launchIn(viewModelScope) bluetoothService.trackingDevices .onEach { devices -> val previousState = state.copy() val newErrorDevices = previousState.managedDevices.filter { prevDeviceState -> devices.filter { currentDeviceState -> currentDeviceState.value.isStateChangedOnTheSameDevice(prevDeviceState) && currentDeviceState.value.isErrorState() }.isNotEmpty() } if (newErrorDevices.isNotEmpty()) { playAlertSound() } state = state.copy( managedDevices = devices.values.toList() ) } .launchIn(viewModelScope) } } fun onAction(action: ManagerOverviewAction) { when (action) { is ManagerOverviewAction.DeleteManager -> { TODO() } is ManagerOverviewAction.OnConnectClick -> { viewModelScope.launch { val result = bluetoothService.connectToDevice(action.address) Timber.d("Connect result: $result") } } is ManagerOverviewAction.OnStartClick -> { viewModelScope.launch { bluetoothService.sendActionFlow.emit(TrackerAction.StartTest(action.address)) } } is ManagerOverviewAction.OnStopClick -> { viewModelScope.launch { bluetoothService.sendActionFlow.emit(TrackerAction.StopTest(action.address)) } } ManagerOverviewAction.OnResolvePermissionClick -> { } ManagerOverviewAction.OnOpenBluetoothSettingsClick -> { androidBluetoothService.openBluetoothSettings() } else -> Unit } } fun onEvent(event: ManagerOverviewEvent) { when (event) { is ManagerOverviewEvent.OnResumed -> { updateBluetoothAdapterState() updatePermissionsState() manageBluetoothDevices() } is ManagerOverviewEvent.OnMeasurementError -> { playAlertSound() } } } private fun updatePermissionsState() { state = state.copy( isPermissionRequired = permissionHandler.getNotGrantedPermissionList().isNotEmpty(), ) } private fun updateBluetoothAdapterState() { state = state.copy( isBluetoothAdapterEnabled = androidBluetoothService.isBluetoothEnabled(), ) } }
0
Kotlin
0
0
d8312d2a8a947b8fd7e0a36fe0647fb2a5e7a881
5,526
ont-drive-test-tool-manager
Apache License 2.0
app/src/main/java/org/p2p/wallet/sdk/facade/model/solend/SolendTokenDepositFeesResponse.kt
p2p-org
306,035,988
false
null
package org.p2p.wallet.sdk.facade.model.solend import com.google.gson.annotations.SerializedName class SolendTokenDepositFeesResponse( @SerializedName("fee") val fee: Long, @SerializedName("rent") val rent: Long )
8
Kotlin
16
28
71b282491cdafd26be1ffc412a971daaa9c06c61
232
key-app-android
MIT License
runtime/observability/telemetry-api/common/src/aws/smithy/kotlin/runtime/telemetry/TelemetryConfig.kt
smithy-lang
294,823,838
false
{"Kotlin": 4171610, "Smithy": 122979, "Python": 1215}
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * SPDX-License-Identifier: Apache-2.0 */ package aws.smithy.kotlin.runtime.telemetry /** * Common configuration options for configuring telemetry of a component */ public interface TelemetryConfig { /** * The [TelemetryProvider] to instrument the component with. */ public val telemetryProvider: TelemetryProvider public interface Builder { /** * The [TelemetryProvider] to instrument the component with. */ public var telemetryProvider: TelemetryProvider? } }
36
Kotlin
26
82
ad18e2fb043f665df9add82083c17877a23f8610
601
smithy-kotlin
Apache License 2.0
sbp-users/src/main/kotlin/io/github/tiscs/sbp/controllers/CurdController.kt
Tiscs
131,112,310
false
null
package io.github.tiscs.sbp.controllers import io.github.tiscs.sbp.models.Page import io.github.tiscs.sbp.models.Query import org.springframework.http.ResponseEntity interface CurdController<M, K> { fun fetch(query: Query): ResponseEntity<Page<M>> fun fetch(id: K): ResponseEntity<M> fun delete(id: K): ResponseEntity<Void> fun create(model: M): ResponseEntity<M> fun update(model: M): ResponseEntity<M> }
0
Kotlin
1
5
b2c675662c098f2a9f6439dbfb8908a7822da2b1
428
spring-cloud-practices
MIT License
dsl/src/main/kotlin/com/faendir/awscdkkt/generated/services/emr/SpotResizingSpecificationPropertyDsl.kt
F43nd1r
643,016,506
false
{"Kotlin": 5482239}
package com.faendir.awscdkkt.generated.services.emr import com.faendir.awscdkkt.AwsCdkDsl import javax.`annotation`.Generated import kotlin.Unit import software.amazon.awscdk.services.emr.CfnInstanceFleetConfig @Generated public fun buildSpotResizingSpecificationProperty(initializer: @AwsCdkDsl CfnInstanceFleetConfig.SpotResizingSpecificationProperty.Builder.() -> Unit = {}): CfnInstanceFleetConfig.SpotResizingSpecificationProperty = CfnInstanceFleetConfig.SpotResizingSpecificationProperty.Builder().apply(initializer).build()
1
Kotlin
0
4
f1542b808f0e2cf4fcdd0d84d025a8fbaf09e90d
546
aws-cdk-kt
Apache License 2.0
src/main/kotlin/bvanseg/kotlincommons/lang/command/CommandDispatchResult.kt
bvanseg
211,717,677
false
null
package bvanseg.kotlincommons.lang.command /** * @author Boston Vanseghi * @since 2.10.4 */ enum class CommandDispatchResult { COMMAND_FIRING_CANCELLED, INVALID_INPUT, UNKNOWN_COMMAND }
0
Kotlin
0
1
f02d97922c743fffc0c520ed2be30ad6b95dd8a3
201
KotlinCommons
MIT License
src/main/kotlin/com/ryderbelserion/api/command/builders/args/builder/custom/ChannelArgument.kt
ryderbelserion
670,341,905
false
null
package com.ryderbelserion.api.command.builders.args.builder.custom class ChannelArgument { }
0
Kotlin
0
0
0ffa4642dd8341ba42944007aebc20102c7b7f34
97
Krul
MIT License
app/src/main/java/com/mehedi/tlecevideo/work/RefreshAlarmReceiver.kt
mehedidevs
798,827,696
false
{"Kotlin": 34889}
package com.mehedi.tlecevideo.work import android.content.BroadcastReceiver import android.content.Context import android.content.Intent import androidx.work.Constraints import androidx.work.NetworkType import androidx.work.OneTimeWorkRequestBuilder import androidx.work.WorkManager import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.launch class RefreshAlarmReceiver : BroadcastReceiver() { private val applicationScope = CoroutineScope(Dispatchers.Default) override fun onReceive(context: Context, intent: Intent) { applicationScope.launch { setupOneTimeWork(context) } } private fun setupOneTimeWork(context: Context) { val constraints = Constraints.Builder() .setRequiredNetworkType(NetworkType.CONNECTED) .build() val oneTimeRequest = OneTimeWorkRequestBuilder<RefreshDataWorker>() .setConstraints(constraints) .build() WorkManager.getInstance(context).enqueue(oneTimeRequest) } }
0
Kotlin
3
2
024219327f7f70c5088bc9997123d1c60e9dd4db
1,069
Play-Video-Media3
MIT License
guide/example/example-readme-03.kt
nomisRev
422,942,279
false
null
// This file was automatically generated from README.md by Knit tool. Do not edit. package example.exampleReadme03 import arrow.* import arrow.core.* import arrow.fx.coroutines.* import kotlinx.coroutines.* import io.kotest.matchers.collections.* import io.kotest.assertions.* import io.kotest.matchers.* import io.kotest.matchers.types.* import kotlin.coroutines.cancellation.CancellationException import io.kotest.property.* import io.kotest.property.arbitrary.* import arrow.core.test.generators.* suspend fun <R, A> Cont<R, A>.toEither(): Either<R, A> = fold({ Either.Left(it) }) { Either.Right(it) } suspend fun <A> Cont<None, A>.toOption(): Option<A> = fold(::identity) { Some(it) }
3
Kotlin
1
13
e729fa5ec1ac8d24cd95e4490d2e5c4dd1d2edbb
696
Continuation
Apache License 2.0
app/src/main/java/com/example/lostandfound/HomePage.kt
Atul-AI08
570,240,579
false
{"Kotlin": 62648}
package com.example.lostandfound import android.content.Intent import android.os.Bundle import android.view.Menu import android.view.MenuItem import android.widget.Button import androidx.appcompat.app.AppCompatActivity import com.google.firebase.auth.FirebaseAuth import com.google.firebase.auth.ktx.auth import com.google.firebase.ktx.Firebase class HomePage : AppCompatActivity() { private lateinit var auth: FirebaseAuth override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_home_page) val lost = findViewById<Button>(R.id.button1) val found = findViewById<Button>(R.id.button2) auth = Firebase.auth lost.setOnClickListener{ val intent = Intent(this, LostActivity::class.java) startActivity(intent) } found.setOnClickListener{ val intent = Intent(this, FoundActivity::class.java) startActivity(intent) } findViewById<Button>(R.id.button3).setOnClickListener { val intent = Intent(this, Lost_Data::class.java) startActivity(intent) } findViewById<Button>(R.id.button4).setOnClickListener{ val intent = Intent(this, Found_Data::class.java) startActivity(intent) } findViewById<Button>(R.id.button5).setOnClickListener { val intent = Intent(this, MyData::class.java) startActivity(intent) } findViewById<Button>(R.id.button6).setOnClickListener { FirebaseAuth.getInstance().signOut() val intent = Intent(this, MainActivity::class.java) startActivity(intent) } } override fun onCreateOptionsMenu(menu: Menu?): Boolean { menuInflater.inflate(R.menu.main_menu, menu) return super.onCreateOptionsMenu(menu) } public override fun onStart() { super.onStart() val currentUser = auth.currentUser if(currentUser == null) { finish() } } override fun onOptionsItemSelected(item: MenuItem): Boolean = when(item.itemId) { R.id.profile -> { val intent = Intent(this, Profile::class.java) startActivity(intent) true } else -> super.onOptionsItemSelected(item) } }
0
Kotlin
0
0
afee0cd5e24f5337eaf4793d75108e4b10150d47
2,367
Lost_and_Found
MIT License
app/src/main/java/vn/nms/sample/presentation/utils/ServiceResponseConverter.kt
minhnn2607
417,355,816
false
{"Kotlin": 220688, "Java": 5735}
package vn.nms.sample.presentation.utils import com.google.gson.Gson import okhttp3.RequestBody import okhttp3.ResponseBody import retrofit2.Converter import retrofit2.Retrofit import retrofit2.converter.gson.GsonConverterFactory import java.io.IOException import java.lang.reflect.Type import kotlin.jvm.Throws class ServiceResponseConverter( private val gSon: Gson ) : Converter.Factory() { override fun responseBodyConverter( type: Type?, annotations: Array<Annotation>, retrofit: Retrofit ): Converter<ResponseBody, *>? { return try { if (type === String::class.java) { StringResponseConverter() } else GsonConverterFactory.create(gSon).responseBodyConverter( type!!, annotations, retrofit ) } catch (ignored: OutOfMemoryError) { null } } override fun requestBodyConverter( type: Type?, parameterAnnotations: Array<Annotation>, methodAnnotations: Array<Annotation>, retrofit: Retrofit ): Converter<*, RequestBody>? { return GsonConverterFactory.create(gSon) .requestBodyConverter(type!!, parameterAnnotations, methodAnnotations, retrofit) } private class StringResponseConverter : Converter<ResponseBody, String> { @Throws(IOException::class) override fun convert(value: ResponseBody): String { return value.string() } } }
0
Kotlin
0
3
59d92211b072e1fbafe3a904883b343554127713
1,499
SampleDataList
Apache License 2.0
core/model/src/main/java/com/niyaj/model/Profile.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. * */ package com.niyaj.model const val DEFAULT_RES_ID = 1 const val RESTAURANT_LOGO_NAME = "reslogo" const val RESTAURANT_PRINT_LOGO_NAME = "printlogo" data class Profile( val restaurantId: Int = 0, val name: String, val email: String, val primaryPhone: String, val secondaryPhone: String, val tagline: String, val description: String, val address: String, val logo: String, val printLogo: String, val paymentQrCode: String, val createdAt: String, val updatedAt: String? = null, ) { companion object { private const val RESTAURANT_NAME = "Popos Highlight" private const val RESTAURANT_TAGLINE = "- Pure And Tasty -" private const val RESTAURANT_DESCRIPTION = "Multi Cuisine Veg & Non-Veg Restaurant" private const val RESTAURANT_EMAIL = "<EMAIL>" private const val RESTAURANT_SECONDARY_PHONE: String = "9597185001" private const val RESTAURANT_PRIMARY_PHONE: String = "9500825077" private const val RESTAURANT_ADDRESS = "Chinna Seeragapadi, Salem, TamilNadu, India 636308, Opp. of VIMS Hospital" private const val RESTAURANT_PAYMENT_QR_DATA = "upi://pay?pa=paytmqr281005050101zry6uqipmngr@paytm&pn=Paytm%20Merchant&paytmqr=281005050101ZRY6UQIPMNGR" val defaultProfileInfo = Profile( restaurantId = DEFAULT_RES_ID, name = RESTAURANT_NAME, email = RESTAURANT_EMAIL, primaryPhone = RESTAURANT_PRIMARY_PHONE, secondaryPhone = RESTAURANT_SECONDARY_PHONE, tagline = RESTAURANT_TAGLINE, description = RESTAURANT_DESCRIPTION, address = RESTAURANT_ADDRESS, logo = "", printLogo = "", paymentQrCode = RESTAURANT_PAYMENT_QR_DATA, createdAt = System.currentTimeMillis().toString(), updatedAt = null, ) } }
42
Kotlin
0
1
a38d8d1551726195cab9c65595de0a4fa34e893b
2,519
PoposRoom
Apache License 2.0
integration-test/compose/src/jvmTest/kotlin/com/moriatsushi/koject/integrationtest/compose/junit/UITestRunner.kt
mori-atsushi
605,139,896
false
null
package com.moriatsushi.koject.integrationtest.compose.junit import kotlin.reflect.KClass expect annotation class RunWith(val value: KClass<out Runner>) expect abstract class Runner expect class UITestRunner : Runner
13
Kotlin
2
96
c22286b39a3e6249842d148ff0a22f1fb7d37d47
219
koject
Apache License 2.0
compiler-plugin/src/main/kotlin/me/him188/kotlin/jvm/blocking/bridge/compiler/backend/ir/loweringPasses.kt
Him188
275,324,436
false
null
package me.him188.kotlin.jvm.blocking.bridge.compiler.backend.ir import me.him188.kotlin.jvm.blocking.bridge.compiler.backend.resolve.BlockingBridgeAnalyzeResult import me.him188.kotlin.jvm.blocking.bridge.compiler.extensions.IBridgeConfiguration import org.jetbrains.kotlin.backend.common.ClassLoweringPass import org.jetbrains.kotlin.backend.common.FileLoweringPass import org.jetbrains.kotlin.backend.common.extensions.IrPluginContext import org.jetbrains.kotlin.diagnostics.DiagnosticSink import org.jetbrains.kotlin.ir.declarations.IrClass import org.jetbrains.kotlin.ir.declarations.IrDeclaration import org.jetbrains.kotlin.ir.declarations.IrFile import org.jetbrains.kotlin.ir.declarations.IrSimpleFunction import org.jetbrains.kotlin.ir.util.companionObject import org.jetbrains.kotlin.ir.util.transformDeclarationsFlat /** * For top-level functions */ class JvmBlockingBridgeFileLoweringPass( private val context: IrPluginContext, private val ext: IBridgeConfiguration, ) : FileLoweringPass { override fun lower(irFile: IrFile) { irFile.transformDeclarationsFlat { declaration -> declaration.transformFlat(context, ext) } } } internal fun IrDeclaration.transformFlat( context: IrPluginContext, ext: IBridgeConfiguration, ): List<IrDeclaration> { val declaration = this if (declaration is IrSimpleFunction) { if (declaration.isGeneratedBlockingBridgeStub()) return listOf() val capability: BlockingBridgeAnalyzeResult = declaration.analyzeCapabilityForGeneratingBridges(ext) capability.createDiagnostic()?.let { diagnostic -> DiagnosticSink.THROW_EXCEPTION.report(diagnostic) } if (capability.shouldGenerate) { return declaration.followedBy(context.generateJvmBlockingBridges(declaration)) } } return listOf(declaration) } /** * For in-class functions */ class JvmBlockingBridgeClassLoweringPass( private val context: IrPluginContext, private val ext: IBridgeConfiguration, ) : ClassLoweringPass { override fun lower(irClass: IrClass) { irClass.transformDeclarationsFlat { declaration -> declaration.transformFlat(context, ext) } irClass.companionObject()?.let(::lower) } } internal fun <T> T?.followedBy(list: Collection<T>): List<T> { if (this == null) return list.toList() val new = ArrayList<T>(list.size + 1) new.add(this) new.addAll(list) return new }
0
Kotlin
6
70
c9c679a000756464c8508f575b023e8d174d263c
2,515
kotlin-jvm-blocking-bridge
Apache License 2.0
src/main/kotlin/modelo/Batalla/Batalla.kt
joaqogomez
646,572,458
false
null
package modelo.Batalla import modelo.Excepciones.AtaqueNoPermitidoError import java.util.* class Batalla { private var perdidaAtacante = 0 private var perdidaDefensor = 0 lateinit var resultadoDadoAtacante: ArrayList<Int> lateinit var resultadoDadoDefensor: ArrayList<Int> private val minimoAtacante = 1 fun atacar(ejercitoAtacante: Ejercitos, ejercitoDefensor: Ejercitos) { tirarDadoAtacante(ejercitoAtacante.getCantidadEjercitos()) tirarDadoDefensor(ejercitoDefensor.getCantidadEjercitos()) finalizarAtaque(ejercitoAtacante, ejercitoDefensor) } private fun finalizarAtaque(ejercitoAtacante: Ejercitos, ejercitoDefensor: Ejercitos) { compararResultado(resultadoDadoAtacante, resultadoDadoDefensor) ejercitoAtacante.restarEjercitos(perdidaAtacante) ejercitoDefensor.restarEjercitos(perdidaDefensor) } private fun compararResultado(resultadoDadoAtacante: ArrayList<Int>, resultadoDadoDefensor: ArrayList<Int>) { val cantidadDeDados = Math.min(resultadoDadoAtacante.size, resultadoDadoDefensor.size) - 1 for (i in 0 .. cantidadDeDados) { if (resultadoDadoAtacante[i] <= resultadoDadoDefensor[i]) { perdidaAtacante++ } else { perdidaDefensor++ } } } private fun tirarDado(cantidadDeTiros: Int): ArrayList<Int> { val dadoATirar = Dado() return dadoATirar.tirarDado(cantidadDeTiros) } private fun tirarDadoAtacante(numeroFichasAtacante: Int) { if (numeroFichasAtacante == minimoAtacante) throw AtaqueNoPermitidoError("No puedes atacar con una sola ficha") resultadoDadoAtacante = tirarDado(numeroFichasAtacante - 1) } private fun tirarDadoDefensor(numeroFichasDefensor: Int) { resultadoDadoDefensor = tirarDado(numeroFichasDefensor) } }
0
Kotlin
0
0
3af2d91168053940f8e9e52994da958a782bb9e8
1,888
75.31-TDL
MIT License
src/main/kotlin/uk/gov/justice/digital/hmpps/hmppstier/domain/enums/Mappa.kt
ministryofjustice
327,621,961
false
null
package uk.gov.justice.digital.hmpps.hmppstier.domain.enums private val mappaRelatedTypeCodes = setOf("MAPP", "M1", "M2", "M3") enum class Mappa(val registerCode: String) { M1("M1"), M2("M2"), M3("M3"); companion object { fun from(value: String?, typeCode: String?): Mappa? { return if (!mappaRelatedTypeCodes.contains(typeCode)) null else values() .firstOrNull { code -> code.registerCode.equals(value, true) } } } }
9
Kotlin
1
0
da14eb65015db93c817fa477aacdde34ca431178
452
hmpps-tier
MIT License
markdown-runtime/src/main/kotlin/land/sungbin/markdown/runtime/MarkdownApplier.kt
jisungbin
815,573,501
false
{"Kotlin": 15166}
/* * Developed by Ji Sungbin 2024. * * Licensed under the MIT. * Please see full license: https://github.com/jisungbin/compose-markdown/blob/main/LICENSE */ package land.sungbin.markdown.runtime import androidx.compose.runtime.Applier import androidx.compose.runtime.collection.MutableVector import kotlin.contracts.ExperimentalContracts import kotlin.contracts.contract import land.sungbin.markdown.runtime.node.SimpleMarkdownRoot import okio.Buffer @PublishedApi internal class MarkdownApplier(private val root: MarkdownNode.Root) : Applier<MarkdownNode> { private val stack = MutableVector<MarkdownNode>(capacity = 10).apply { add(root) } override var current: MarkdownNode = root constructor(options: MarkdownOptions, buffer: Buffer) : this(root = SimpleMarkdownRoot(options = options, buffer = buffer)) override fun insertTopDown(index: Int, instance: MarkdownNode) { assertNotNestedRoot(instance) when (val current = current) { is MarkdownNode.Group -> { assertNotNestedGroup(instance) current.insert(index, instance) } is MarkdownNode.Root -> Unit // This is handled by up(). is MarkdownNode.Text -> error("Text node cannot have children.") } } override fun down(node: MarkdownNode) { stack += node current = node } override fun up() { val tail = current check(stack.isNotEmpty()) { "empty stack" } stack.removeAt(stack.lastIndex) current = stack.last() val current = current if (current is MarkdownNode.Root && tail is MarkdownNode.Renderable) { if (current.buffer.exhausted()) { current.buffer.writeAll(tail.render(options = root.options)) } else { current.buffer.writeUtf8("\n\n").writeAll(tail.render(options = root.options)) } } } override fun move(from: Int, to: Int, count: Int) { notSupportedOperation("move") } override fun remove(index: Int, count: Int) { notSupportedOperation("remove") } override fun clear() { // Nothing to do. } override fun insertBottomUp(index: Int, instance: MarkdownNode) { // Ignored. We use TopDown. } @OptIn(ExperimentalContracts::class) private fun assertNotNestedRoot(node: MarkdownNode) { contract { returns() implies (node is MarkdownNode.Renderable) } if (node is MarkdownNode.Root) { throw NotImplementedError("Nested markdown is not supported.") } } @OptIn(ExperimentalContracts::class) private fun assertNotNestedGroup(node: MarkdownNode) { contract { returns() implies (node is MarkdownNode.Text) } if (node is MarkdownNode.Group) { throw NotImplementedError("Nested group is not supported.") } } private fun notSupportedOperation(operation: String): Nothing = throw NotImplementedError( "Operation $operation is not supported. Dynamic layouts are not currently " + "supported. (Did you try recomposition?)", ) }
1
Kotlin
0
4
316aa2a1ebd9bc01e82d30dd2eea1e4b98b4b45e
2,937
compose-markdown
MIT License
app/src/main/java/com/app/uiComponents/FloatingActionButton.kt
yash786agg
244,130,702
false
null
package com.app.uiComponents import androidx.annotation.DrawableRes import androidx.compose.Composable import androidx.ui.core.Modifier import androidx.ui.core.Text import androidx.ui.foundation.Border import androidx.ui.foundation.DrawBorder import androidx.ui.foundation.shape.corner.CornerSize import androidx.ui.foundation.shape.corner.RoundedCornerShape import androidx.ui.graphics.Color import androidx.ui.graphics.SolidColor import androidx.ui.layout.* import androidx.ui.material.FloatingActionButton import androidx.ui.text.TextStyle import androidx.ui.text.font.FontFamily import androidx.ui.text.font.FontStyle import androidx.ui.unit.TextUnit import androidx.ui.unit.dp @Composable fun FABIconText(modifier: Modifier = Modifier.None, @DrawableRes vectorResourceId: Int, onClick: () -> Unit, elevation : Int = 6, fabColor: Int, roundCorner: Int = 50, text: Any?, textColor: Int, textSize: Int = 14 ) { FloatingActionButton(modifier = modifier, elevation = elevation.dp, onClick = onClick, color = Color(color = fabColor), shape = RoundedCornerShape(corner = CornerSize(roundCorner)) // RectangleShape or CircleShape -> for Rectangle or Circle Shape ) { Row(LayoutPadding(start = 12.dp, end = 20.dp)) { VectorImage(vectorResourceId = vectorResourceId, onClick = onClick ) Spacer(LayoutWidth(12.dp)) TextViewStyling( modifier = LayoutGravity.Center, text = text.toString(), style = TextStyle( color = Color(color = textColor), fontSize = TextUnit.Sp(textSize), fontFamily = FontFamily.SansSerif, fontStyle = FontStyle.Normal ) ) } } } @Composable fun FABText(modifier: Modifier = Modifier.None, onClick: () -> Unit, elevation : Int = 6, fabColor: Int, roundCorner: Int = 50, // RectangleShape or CircleShape -> for Rectangle or Circle Shape text: Any?, textColor: Int, textSize: Int = 14 ) { FloatingActionButton(modifier = modifier, elevation = elevation.dp, onClick = onClick, color = Color(color = fabColor), shape = RoundedCornerShape(corner = CornerSize(roundCorner)) ) { Row(LayoutPadding(start = 12.dp, end = 20.dp)) { Spacer(LayoutWidth(12.dp)) Text( modifier = LayoutGravity.Center, text = text.toString(), style = TextStyle( color = Color(color = textColor), fontSize = TextUnit.Sp(textSize), fontFamily = FontFamily.SansSerif, fontStyle = FontStyle.Normal ) ) } } } @Composable fun FABIcon(modifier: Modifier = Modifier.None, @DrawableRes vectorResourceId: Int, onClick: () -> Unit, roundCorner: Int = 50, elevation : Int = 6, fabColor: Int ) { FloatingActionButton(modifier = modifier, elevation = elevation.dp, onClick = onClick, color = Color(color = fabColor), shape = RoundedCornerShape(corner = CornerSize(roundCorner)) // RectangleShape or CircleShape -> for Rectangle or Circle Shape ) { VectorImage(vectorResourceId = vectorResourceId, onClick = onClick ) } } @Composable fun FABCustomizeIcon(@DrawableRes vectorResourceId: Int, onClick: () -> Unit, roundCorner: Int = 50, strokeColor: Int, strokeWidth: Int = 0, elevation : Int = 6, fabColor: Int ) { FloatingActionButton(modifier = DrawBorder( border = Border(size = strokeWidth.dp,brush = SolidColor(Color(color = strokeColor))), shape = RoundedCornerShape(corner = CornerSize(roundCorner)) // RectangleShape or CircleShape -> for Rectangle or Circle Shape ), elevation = elevation.dp, onClick = onClick, color = Color(color = fabColor) ) { VectorImage(vectorResourceId = vectorResourceId, onClick = onClick ) } }
0
Kotlin
0
0
5c2a1f019f84da07490fdc635845306bb00b11d3
4,448
JetPack-Compose
Apache License 2.0
tools/network-bootstrapper/src/main/kotlin/net/corda/bootstrapper/cli/CommandParsers.kt
jbeetle
139,003,490
true
{"Kotlin": 6449226, "Java": 271846, "CSS": 23489, "Shell": 9940, "Gherkin": 3162, "Groovy": 2129, "Batchfile": 1367, "PowerShell": 660, "Makefile": 569}
package net.corda.bootstrapper.cli import com.microsoft.azure.management.resources.fluentcore.arm.Region import net.corda.bootstrapper.Constants import net.corda.bootstrapper.backends.Backend import picocli.CommandLine import picocli.CommandLine.Option import java.io.File open class GuiSwitch { @Option(names = ["-h", "--help"], usageHelp = true, description = ["display this help message"]) var usageHelpRequested: Boolean = false @Option(names = ["-g", "--gui"], description = ["Run in Gui Mode"]) var gui = false @CommandLine.Unmatched var unmatched = arrayListOf<String>() } open class CliParser : GuiSwitch() { @Option(names = ["-n", "--network-name"], description = ["The resource grouping to use"], required = true) lateinit var name: String @Option(names = ["-d", "--nodes-directory"], description = ["The directory to search for nodes in"]) var baseDirectory = File(System.getProperty("user.dir")) @Option(names = ["-b", "--backend"], description = ["The backend to use when instantiating nodes"]) var backendType: Backend.BackendType = Backend.BackendType.LOCAL_DOCKER @Option(names = ["-nodes"], split = ":", description = ["The number of each node to create NodeX:2 will create two instances of NodeX"]) var nodes: MutableMap<String, Int> = hashMapOf() @Option(names = ["--add", "-a"]) var nodesToAdd: MutableList<String> = arrayListOf() fun isNew(): Boolean { return nodesToAdd.isEmpty() } open fun backendOptions(): Map<String, String> { return emptyMap() } } class AzureParser : CliParser() { companion object { val regions = Region.values().map { it.name() to it }.toMap() } @Option(names = ["-r", "--region"], description = ["The azure region to use"], converter = [RegionConverter::class]) var region: Region = Region.EUROPE_WEST class RegionConverter : CommandLine.ITypeConverter<Region> { override fun convert(value: String): Region { return regions[value] ?: throw Error("Unknown azure region: $value") } } override fun backendOptions(): Map<String, String> { return mapOf(Constants.REGION_ARG_NAME to region.name()) } }
0
Kotlin
0
0
a768904e4ea1c8498e7fa6e4df0353e090f4d02a
2,234
corda
Apache License 2.0
Smartspend/app/src/main/java/com/example/smartspend/Profile.kt
MarcoMeyer1
858,674,435
false
{"Kotlin": 126588}
package com.example.smartspend import android.content.SharedPreferences import android.os.Bundle import android.util.Log import android.widget.Button import android.widget.EditText import android.widget.Toast import androidx.activity.enableEdgeToEdge import androidx.core.view.ViewCompat import androidx.core.view.WindowInsetsCompat import okhttp3.* import okhttp3.MediaType.Companion.toMediaTypeOrNull import org.json.JSONObject import java.io.IOException class Profile : BaseActivity() { private lateinit var etFirstName: EditText private lateinit var etSurname: EditText private lateinit var etEmail: EditText private lateinit var etPhoneNumber: EditText private lateinit var btnSet: Button private val client = OkHttpClient() private var userID: Int = -1 override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) enableEdgeToEdge() setContentView(R.layout.activity_profile) setActiveNavButton(R.id.profile_nav) ViewCompat.setOnApplyWindowInsetsListener(findViewById(R.id.main)) { v, insets -> val systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars()) v.setPadding(systemBars.left, systemBars.top, systemBars.right, systemBars.bottom) insets } // Initializes the UI elements etFirstName = findViewById(R.id.etFirstName) etSurname = findViewById(R.id.etSurname) etEmail = findViewById(R.id.etEmail) etPhoneNumber = findViewById(R.id.etPhoneNumber) btnSet = findViewById(R.id.btn_set) etEmail.isEnabled = false // Retrieves the user ID from SharedPreferences val sharedPreferences: SharedPreferences = getSharedPreferences("UserPrefs", MODE_PRIVATE) userID = sharedPreferences.getInt("userID", -1) if (userID != -1) { fetchUserProfile() } else { Toast.makeText(this, "User ID not found. Please log in again.", Toast.LENGTH_LONG).show() } btnSet.setOnClickListener { updateUserProfile() } } // Fetches user profile from the server private fun fetchUserProfile() { val url = "https://smartspendapi.azurewebsites.net/api/User/$userID" val request = Request.Builder() .url(url) .get() .build() // Makes the network request client.newCall(request).enqueue(object : Callback { override fun onFailure(call: Call, e: IOException) { runOnUiThread { Toast.makeText(this@Profile, "Network Error: ${e.message}", Toast.LENGTH_LONG).show() } } override fun onResponse(call: Call, response: Response) { val responseBody = response.body?.string() runOnUiThread { if (response.isSuccessful && responseBody != null) { try { val jsonResponse = JSONObject(responseBody) val firstName = jsonResponse.getString("firstName") val lastName = jsonResponse.getString("lastName") val email = jsonResponse.getString("email") val phoneNumber = jsonResponse.optString("phoneNumber", "") etFirstName.setText(firstName) etSurname.setText(lastName) etEmail.setText(email) etPhoneNumber.setText(phoneNumber) } catch (e: Exception) { Toast.makeText(this@Profile, "Error parsing user data", Toast.LENGTH_LONG).show() } } else { Toast.makeText(this@Profile, "Failed to fetch user profile", Toast.LENGTH_LONG).show() } } } }) } // Updates the user profile on the server private fun updateUserProfile() { val firstName = etFirstName.text.toString().trim() val lastName = etSurname.text.toString().trim() val phoneNumber = etPhoneNumber.text.toString().trim() if (firstName.isEmpty()) { etFirstName.error = "First name is required" etFirstName.requestFocus() return } if (lastName.isEmpty()) { etSurname.error = "Surname is required" etSurname.requestFocus() return } val json = JSONObject() json.put("userID", userID) json.put("firstName", firstName) json.put("lastName", lastName) json.put("email", etEmail.text.toString()) json.put("phoneNumber", if (phoneNumber.isNotEmpty()) phoneNumber else JSONObject.NULL) val url = "https://smartspendapi.azurewebsites.net/api/User/update" val body = RequestBody.create( "application/json; charset=utf-8".toMediaTypeOrNull(), json.toString() ) val request = Request.Builder() .url(url) .put(body) .build() // Makes the network request client.newCall(request).enqueue(object : Callback { override fun onFailure(call: Call, e: IOException) { runOnUiThread { Toast.makeText(this@Profile, "Network Error: ${e.message}", Toast.LENGTH_LONG).show() } } override fun onResponse(call: Call, response: Response) { val responseBody = response.body?.string() runOnUiThread { if (response.isSuccessful) { Toast.makeText(this@Profile, "Profile updated successfully", Toast.LENGTH_LONG).show() } else { val errorMessage = responseBody ?: "Profile update failed" Toast.makeText(this@Profile, errorMessage, Toast.LENGTH_LONG).show() } } } }) } }
0
Kotlin
0
0
756e774497fc99a11a5c0eb0a23bf908cb2d35c5
6,134
SmartSpend
MIT License
core/network/src/main/java/dev/eury/core/network/calladapter/NetworkResultCallAdapter.kt
euri16
644,636,950
false
null
package dev.eury.core.network.calladapter import retrofit2.Call import retrofit2.CallAdapter import java.lang.reflect.Type class NetworkResultCallAdapter<T : Any>( private val successType: Type ) : CallAdapter<T, Call<NetworkResponse<T>>> { override fun responseType(): Type = successType override fun adapt(call: Call<T>): Call<NetworkResponse<T>> { return NetworkResultCall(call) } }
0
Kotlin
0
0
c6bfb4b83c78f56d1635c0d2e48fc1297734dd4a
413
github-repository-explorer
MIT License
app/src/main/java/com/bubelov/coins/dagger/Injector.kt
kartikhimself
131,604,397
true
{"Kotlin": 308076}
package com.bubelov.coins.dagger import android.content.Context /** * @author <NAME> */ object Injector { lateinit var appComponent: AppComponent private set fun init(context: Context) { appComponent = DaggerAppComponent.builder().context(context).build() } }
0
Kotlin
0
0
10b9c27ffd62ff89218082ca21701113b6d168d4
289
coins-android
The Unlicense
app/src/main/java/com/aquispe/wonkainc/data/remote/model/EmployeesResponse.kt
arman-visual
674,817,363
false
null
package com.aquispe.wonkainc.data.remote.model import com.squareup.moshi.JsonClass @JsonClass(generateAdapter = true) data class EmployeesResponse( val current: Int, val results: List<EmployeeApiModel>, val total: Int )
0
Kotlin
0
0
748ecfcea8999d5f05a8784e114fd60f7c07f06e
234
WonkaInc
Apache License 2.0
examples/partiql/src/main/kotlin/io/johnedquinn/partiql/parser/PartiQLParser.kt
johnedquinn
576,195,646
false
{"Kotlin": 118865}
package io.johnedquinn.partiql.parser import io.johnedquinn.kanonic.runtime.parse.KanonicParser import io.johnedquinn.partiql.generated.PartiQLSpecification import org.partiql.lang.domains.PartiqlAst import org.partiql.lang.syntax.Parser object PartiQLParser : Parser { private val parser = KanonicParser.Builder.standard().withSpecification(PartiQLSpecification).build() private val overriddenParser = KanonicParser.Builder.standard().withSpecification(PartiQLSpecification).withLexer( OverriddenLexer ).build() override fun parseAstStatement(source: String): PartiqlAst.Statement { val ast = parser.parse(source) return PartiQLVisitor.visit(ast) } fun parseExperimental(source: String): PartiqlAst.Statement { val ast = overriddenParser.parse(source) return PartiQLVisitor.visit(ast) } }
13
Kotlin
1
5
9da9e081aee791aa6ec8c2a7aa1906beadfb72aa
864
kanonic
Apache License 2.0
app/src/main/java/com/kylix/submissionbajp3/ui/adapter/TvShowAdapter.kt
KylixEza
323,485,823
false
null
package com.kylix.submissionbajp3.ui.adapter import android.content.Context import android.content.Intent import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.recyclerview.widget.RecyclerView import com.bumptech.glide.Glide import com.kylix.submissionbajp3.R import com.kylix.submissionbajp3.model.local.entity.TvShowModel import com.kylix.submissionbajp3.ui.activities.DetailActivity import com.kylix.submissionbajp3.ui.activities.DetailActivity.Companion.TITLE import kotlinx.android.synthetic.main.item_list.view.* class TvShowAdapter(private val context: Context?) : RecyclerView.Adapter<TvShowAdapter.ViewHolder>() { private var listTvShows : List<TvShowModel> = emptyList() fun getList(tvShow: List<TvShowModel>) { this.listTvShows = tvShow notifyDataSetChanged() } override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder { return ViewHolder(LayoutInflater.from(context).inflate(R.layout.item_list, parent,false)) } override fun getItemCount(): Int { return listTvShows.size } override fun onBindViewHolder(holder: ViewHolder, position: Int) { holder.bindViewHolder(listTvShows[position]) context?.let { Glide.with(it) .load(context.resources .getIdentifier(listTvShows[position].tvShowPoster, "drawable", context.packageName)) .into(holder.poster) } holder.cardItem.setOnClickListener { val intent = Intent(context, DetailActivity::class.java) intent.putExtra("tvShowId", listTvShows[position].tvShowId) intent.apply { putExtra("tvShowId", listTvShows[position].tvShowId) putExtra(TITLE, listTvShows[position].tvShowTitle) } context?.startActivity(intent) } } class ViewHolder(itemView : View) : RecyclerView.ViewHolder(itemView) { val poster = itemView.iv_poster_list!! val cardItem = itemView.cv_list!! fun bindViewHolder(listMovies : TvShowModel){ itemView.tv_title_list.text = listMovies.tvShowTitle } } }
0
Kotlin
0
3
81841574ec752bf40946592ad333b790c5abb933
2,213
Submission-BAJP3-Dicoding
MIT License
client/client-hci/src/commonMain/kotlin/de/jlnstrk/transit/api/hci/model/him/HciHimMessageEvent.kt
jlnstrk
229,599,180
false
{"Kotlin": 729374}
@file:UseSerializers( HciLocalDateSerializer::class, HciLocalTimeSerializer::class ) package de.jlnstrk.transit.api.hci.model.him import de.jlnstrk.transit.api.hafas.HciModel import de.jlnstrk.transit.api.hci.serializer.time.HciLocalDateSerializer import de.jlnstrk.transit.api.hci.serializer.time.HciLocalTimeSerializer import de.jlnstrk.transit.util.LocalDate import de.jlnstrk.transit.util.LocalTime import kotlinx.serialization.Serializable import kotlinx.serialization.UseSerializers @HciModel("1.39") @Serializable public data class HciHimMessageEvent( public val fDate: LocalDate, public val fTime: LocalTime, public val fLocX: Int?, public val tDate: LocalDate, public val tTime: LocalTime, public val tLocX: Int?, public val isCurrent: Boolean = false, public val sectionNums: List<String> = emptyList(), )
0
Kotlin
0
0
9f700364f78ebc70b015876c34a37b36377f0d9c
858
transit
Apache License 2.0
app/src/main/java/com/fixeam/icoser/ui/main/fragment/CollectionFragment.kt
qq1790141618
748,453,146
false
{"Kotlin": 378582, "HTML": 2476}
package com.fixeam.icoser.ui.main.fragment import android.annotation.SuppressLint import android.content.res.ColorStateList import android.graphics.Color import android.graphics.PorterDuff import android.graphics.PorterDuffColorFilter import android.graphics.Typeface import android.os.Bundle import android.view.Gravity import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.view.animation.AnimationUtils import android.widget.ImageView import android.widget.TextView import android.widget.Toast import androidx.appcompat.app.AppCompatActivity import androidx.constraintlayout.widget.ConstraintLayout import androidx.fragment.app.Fragment import androidx.recyclerview.widget.LinearLayoutManager import androidx.recyclerview.widget.RecyclerView import com.bumptech.glide.Glide import com.bumptech.glide.load.engine.DiskCacheStrategy import com.bumptech.glide.load.resource.bitmap.RoundedCorners import com.fixeam.icoser.R import com.fixeam.icoser.databinding.FragmentCollectionBinding import com.fixeam.icoser.databinding.PublishItemBinding import com.fixeam.icoser.model.calculateTimeAgo import com.fixeam.icoser.model.getScreenWidth import com.fixeam.icoser.model.startAlbumActivity import com.fixeam.icoser.model.startLoginActivity import com.fixeam.icoser.model.startMediaActivity import com.fixeam.icoser.model.startModelActivity import com.fixeam.icoser.model.startSearchActivity import com.fixeam.icoser.network.accessLog import com.fixeam.icoser.network.followAlbumList import com.fixeam.icoser.network.requestFollowData import com.fixeam.icoser.network.setForbidden import com.fixeam.icoser.network.setModelFollowingById import com.fixeam.icoser.network.userToken import com.fixeam.icoser.ui.image_preview.ImagePreviewActivity class CollectionFragment : Fragment() { private lateinit var binding: FragmentCollectionBinding private var adapter: MyListAdapter? = null override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View { binding = FragmentCollectionBinding.inflate(layoutInflater) return binding.root } @SuppressLint("NotifyDataSetChanged") override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) setAppHeaderLayout() if(userToken == null){ startLoginActivity(requireContext()) } else { val imageView = binding.imageLoading imageView.startAnimation(AnimationUtils.loadAnimation(requireContext(), R.anim.loading)) imageView.visibility = View.VISIBLE requestFollowData() { imageView.clearAnimation() imageView.visibility = View.GONE setRefreshLayout() initFollowList() } } } // 设置页头函数 private fun setAppHeaderLayout(){ // 设置标题字体 val typeface = Typeface.createFromAsset(requireContext().assets, "font/JosefinSans-Regular-7.ttf") binding.appHeader.topText.typeface = typeface // 创建搜索按钮点击 val homeSearchButton = binding.appHeader.homeSearchButton homeSearchButton.setOnClickListener { startSearchActivity(requireContext()) } } // 设置下拉刷新函数 @SuppressLint("NotifyDataSetChanged") private fun setRefreshLayout(){ val refreshLayout = binding.refreshLayout refreshLayout.visibility = View.VISIBLE refreshLayout.setOnRefreshListener { requestFollowData(true){ val followList = binding.followList val adapter = followList.adapter adapter?.notifyDataSetChanged() refreshLayout.finishRefresh() Toast.makeText(requireContext(), "刷新成功", Toast.LENGTH_SHORT).show() } } refreshLayout.setOnLoadMoreListener { val index = followAlbumList.size requestFollowData() { adapter?.notifyItemInserted(index) refreshLayout.finishLoadMore() } } } private fun initFollowList() { val followList = binding.followList followList.layoutManager = LinearLayoutManager(requireContext(), LinearLayoutManager.VERTICAL, false) adapter = MyListAdapter() followList.adapter = adapter followList.addOnScrollListener(object : RecyclerView.OnScrollListener() { override fun onScrolled(recyclerView: RecyclerView, dx: Int, dy: Int) { super.onScrolled(recyclerView, dx, dy) val layoutManager = recyclerView.layoutManager as LinearLayoutManager val firstVisibleItemPosition = layoutManager.findFirstVisibleItemPosition() val lastVisibleItemPosition = layoutManager.findLastVisibleItemPosition() for (index in firstVisibleItemPosition..lastVisibleItemPosition){ if(followAlbumList[index].isNew){ followAlbumList[index].isNew = false accessLog(requireContext(), followAlbumList[index].id.toString(), "VISIT_ALBUM"){ } } } } }) } private fun setForbiddenIcon(icon: ImageView, position: Int){ icon.setOnClickListener { followAlbumList.removeAt(position) val followList = binding.followList val adapter = followList.adapter adapter?.notifyItemRemoved(position) setForbidden( requireContext(), followAlbumList[position].id, "album", { // 已经执行完移除操作 }, { // 此页面的调用不会出现未登录 } ) } } inner class MyListAdapter : RecyclerView.Adapter<MyViewHolder>() { override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): MyViewHolder { val binding = PublishItemBinding.inflate(LayoutInflater.from(parent.context), parent, false) return MyViewHolder(binding) } override fun getItemCount(): Int { return followAlbumList.size } @SuppressLint("SetTextI18n") override fun onBindViewHolder(holder: MyViewHolder, position: Int) { // 修改holder val album = followAlbumList[position] holder.itemView.setOnClickListener { startAlbumActivity(requireContext(), album.id) } // 修改上方内容 val followButton = holder.binding.following val followedButton = holder.binding.followed val closeButton = holder.binding.close if (album.type == "recommend" || album.type == "push"){ followButton.visibility = View.VISIBLE followButton.setOnClickListener { setModelFollowingById( requireContext(), album.model_id, { followButton.visibility = View.GONE followedButton.visibility = View.VISIBLE }, { startLoginActivity(requireContext()) } ) } closeButton.visibility = View.VISIBLE setForbiddenIcon(closeButton, position) } else { followButton.visibility = View.GONE followedButton.visibility = View.GONE closeButton.visibility = View.GONE } val fromIcon = holder.binding.fromIcon val fromText = holder.binding.fromText when(album.type){ "follow" -> { fromIcon.setImageResource(R.drawable.evaluate) fromText.text = getText(R.string.from_follow) } "recommend" -> { fromIcon.setImageResource(R.drawable.goods_favor) fromText.text = getText(R.string.from_collection) } else -> { fromIcon.setImageResource(R.drawable.selection) fromText.text = getText(R.string.from_push) } } // 设置模特内容 Glide.with(requireContext()) .load("${album.model_avatar_image}/short500px") .diskCacheStrategy(DiskCacheStrategy.ALL) .transform(RoundedCorners(250)) .into(holder.binding.avatar) holder.binding.modelName.text = album.model holder.binding.avatar.setOnClickListener { startModelActivity(requireContext(), album.model_id) } holder.binding.modelName.setOnClickListener { startModelActivity(requireContext(), album.model_id) } // 设置动态内容 val publishContentText = holder.binding.publishContentText publishContentText.text = album.name if(album.tags != null){ publishContentText.text = album.name + ", " + album.tags!!.joinToString(", ") } val publishContent = holder.binding.publishContentMedia publishContent.removeAllViews() val publishTime = holder.binding.publishTime publishTime.text = "发布于 ${calculateTimeAgo(album.create_time)}" // 计算动态内容宽度(3像素的容差) val contentWidth = getScreenWidth(requireContext()) - resources.displayMetrics.density * 60 - 3 val contentGap = resources.displayMetrics.density * 10 var contentItemWidth = ((contentWidth - contentGap * 2) / 3).toInt() var contentItemHeight = ((contentWidth - contentGap * 2) / 3).toInt() if(album.media != null){ if((album.images as List<*>).size + album.media!!.size == 1){ contentItemWidth *= 2 contentItemHeight *= 3 } } else { if((album.images as List<*>).size == 1){ contentItemWidth *= 2 contentItemHeight *= 3 } } // 加入视频 if(album.media != null){ for (media in album.media!!){ if(publishContent.childCount >= 6){ break } // 创建布局 val constraintLayout = ConstraintLayout(requireContext()) val layoutParams = ConstraintLayout.LayoutParams( contentItemWidth, contentItemHeight ) layoutParams.bottomMargin = contentGap.toInt() if((publishContent.childCount + 1) % 3 != 0){ layoutParams.rightMargin = contentGap.toInt() } constraintLayout.layoutParams = layoutParams // 加入封面 val coverImage = ImageView(requireContext()) coverImage.scaleType = ImageView.ScaleType.CENTER_CROP coverImage.id = View.generateViewId() coverImage.setImageResource(R.drawable.image_holder) coverImage.layoutParams = ViewGroup.LayoutParams( ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT ) constraintLayout.addView(coverImage) Glide.with(requireContext()) .load("${media.cover}/short500px") .diskCacheStrategy(DiskCacheStrategy.ALL) .into(coverImage) // 加入播放按钮 val playButtonImage = ImageView(requireContext()) playButtonImage.id = View.generateViewId() playButtonImage.setImageResource(R.drawable.video_fill) constraintLayout.addView(playButtonImage) val playButtonImageLayoutParams = ViewGroup.LayoutParams( ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT ) val paddingPx = ( contentItemWidth - 80 ) / 2 playButtonImage.setPadding(paddingPx, paddingPx, paddingPx, paddingPx) playButtonImage.layoutParams = playButtonImageLayoutParams val colorFilter = PorterDuffColorFilter(Color.parseColor("#80000000"), PorterDuff.Mode.SRC_IN) playButtonImage.colorFilter = colorFilter // 添加到内容 constraintLayout.setOnClickListener { startMediaActivity(requireContext(), media.id) } publishContent.addView(constraintLayout) } } // 加入图片 for ((index, image) in (album.images as List<String>).withIndex()){ if(publishContent.childCount >= 6){ break } if(publishContent.childCount == 5){ // 创建布局 val constraintLayout = ConstraintLayout(requireContext()) val layoutParams = ConstraintLayout.LayoutParams( contentItemWidth, contentItemHeight ) layoutParams.bottomMargin = contentGap.toInt() if((publishContent.childCount + 1) % 3 != 0){ layoutParams.rightMargin = contentGap.toInt() } constraintLayout.layoutParams = layoutParams // 加入图片 val imageDisplay = ImageView(requireContext()) imageDisplay.scaleType = ImageView.ScaleType.CENTER_CROP imageDisplay.id = View.generateViewId() imageDisplay.setImageResource(R.drawable.image_holder) constraintLayout.addView(imageDisplay) Glide.with(requireContext()) .load("${image}/short500px") .diskCacheStrategy(DiskCacheStrategy.ALL) .into(imageDisplay) // 显示更多图片按钮 val moreImageText = TextView(requireContext()) moreImageText.id = View.generateViewId() moreImageText.text = (album.images as List<*>).size.toString() + "+" moreImageText.textSize = 18F val color = ColorStateList.valueOf(Color.parseColor("#ACFFFFFF")) moreImageText.setTextColor(color) constraintLayout.addView(moreImageText) val playButtonImageLayoutParams = ViewGroup.LayoutParams( ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT ) moreImageText.layoutParams = playButtonImageLayoutParams moreImageText.gravity = Gravity.CENTER // 添加到内容 constraintLayout.setOnClickListener { val activity = requireActivity() as AppCompatActivity ImagePreviewActivity.start( activity, index, (album.images as ArrayList<String>), imageDisplay ) } publishContent.addView(constraintLayout) continue } val imageDisplay = ImageView(requireContext()) imageDisplay.scaleType = ImageView.ScaleType.CENTER_CROP imageDisplay.id = View.generateViewId() imageDisplay.setImageResource(R.drawable.image_holder) val layoutParams = ConstraintLayout.LayoutParams( contentItemWidth, contentItemHeight ) layoutParams.bottomMargin = contentGap.toInt() if((publishContent.childCount + 1) % 3 != 0){ layoutParams.rightMargin = contentGap.toInt() } imageDisplay.layoutParams = layoutParams Glide.with(requireContext()) .load("${image}/short500px") .diskCacheStrategy(DiskCacheStrategy.ALL) .into(imageDisplay) imageDisplay.setOnClickListener { val activity = requireActivity() as AppCompatActivity ImagePreviewActivity.start( activity, index, (album.images as ArrayList<String>), imageDisplay ) } publishContent.addView(imageDisplay) } } } class MyViewHolder(val binding: PublishItemBinding) : RecyclerView.ViewHolder(binding.root) }
0
Kotlin
0
0
14212926ab851d64cc6f5a157bdea7129837016f
17,259
iCoserKT
MIT License
backend/app/src/main/kotlin/io/tolgee/api/v2/hateoas/translations/TranslationHistoryModel.kt
tolgee
303,766,501
false
null
package io.tolgee.api.v2.hateoas.translations import io.swagger.v3.oas.annotations.media.Schema import io.tolgee.activity.data.PropertyModification import io.tolgee.activity.data.RevisionType import io.tolgee.api.v2.hateoas.user_account.SimpleUserAccountModel import org.springframework.hateoas.RepresentationModel import org.springframework.hateoas.server.core.Relation @Suppress("unused") @Relation(collectionRelation = "revisions", itemRelation = "revision") open class TranslationHistoryModel( @Schema(description = "Modified fields") val modifications: Map<String, PropertyModification>? = null, @Schema(description = "Unix timestamp of the revision") val timestamp: Long, @Schema(description = "Author of the change") val author: SimpleUserAccountModel?, val revisionType: RevisionType ) : RepresentationModel<TranslationHistoryModel>()
100
Kotlin
40
666
38c1064783f3ec5d60d0502ec0420698395af539
862
tolgee-platform
Apache License 2.0
app/src/main/java/com/exail/archtest/core/Extensions.kt
EduardsDenisjonoks
193,911,687
false
null
package com.exail.archtest.core import android.os.Bundle import android.view.View import androidx.annotation.IdRes import androidx.appcompat.app.AppCompatActivity import androidx.appcompat.widget.AppCompatImageView import androidx.fragment.app.Fragment import androidx.lifecycle.LiveData import androidx.lifecycle.MediatorLiveData import androidx.lifecycle.Observer import androidx.navigation.NavDirections import androidx.navigation.Navigation import androidx.navigation.fragment.NavHostFragment import com.squareup.picasso.Picasso import timber.log.Timber import java.lang.Exception //region NAVIGATION fun View.navigateTo(@IdRes destination: Int, bundle: Bundle? = null) { try { Navigation.findNavController(this).navigate(destination, bundle) } catch (ex: Exception) { Timber.e(ex, "Unable to navigate from this view") } } fun View.navigateTo(navDirections: NavDirections) { try { Navigation.findNavController(this).navigate(navDirections) } catch (ex: Exception) { Timber.e(ex, "Unable to navigate from this view") } } fun View.navigatePopUpTo(@IdRes destination: Int, inclusive: Boolean = true) { try { Navigation.findNavController(this).popBackStack(destination, inclusive) } catch (ex: Exception) { Timber.e(ex, "Unable to pop up to from this view") } } fun View.navigatePopUp() { try { Navigation.findNavController(this).popBackStack() } catch (ex: Exception) { Timber.e(ex, "Unable to pop up from this view") } } fun Fragment.navigateTo(@IdRes destination: Int) { try { NavHostFragment.findNavController(this).navigate(destination) } catch (ex: Exception) { Timber.e(ex, "Unable to navigate from this fragment") } } fun AppCompatActivity.navigateTo(@IdRes host: Int, @IdRes destination: Int) { try { Navigation.findNavController(this, host).navigate(destination) } catch (ex: Exception) { Timber.e(ex, "Unable to navigate from this activity") } } //endregion //region IMAGE VIEW fun AppCompatImageView.clearImage() { try { Picasso.get().cancelRequest(this) } catch (ex: Exception) { Timber.e(ex, "Failed to cancel picasso request") } finally { this.setImageDrawable(null) } } //endregion //region LIVE DATA fun <T> LiveData<T>.getDistinct(): LiveData<T> { val distinctLiveData = MediatorLiveData<T>() distinctLiveData.addSource(this, object : Observer<T> { private var initialized = false private var lastObj: T? = null override fun onChanged(obj: T?) { if (!initialized) { initialized = true lastObj = obj distinctLiveData.postValue(lastObj) } else if ((obj == null && lastObj != null) || obj != lastObj) { lastObj = obj distinctLiveData.postValue(lastObj) } } }) return distinctLiveData } //endregion
0
Kotlin
0
0
64308d039a5368eb70d7919fa96ed0ef45b43eac
3,010
archtest
Apache License 2.0
src/main/java/cn/monshine/commandlibrary/transformer/FloatTransformer.kt
zhusun890
852,846,440
false
{"Kotlin": 27928, "Java": 1766}
package cn.monshine.commandlibrary.transformer import cn.monshine.commandlibrary.CommandWrapper import cn.monshine.commandlibrary.ParameterTransformer import cn.monshine.commandlibrary.colorize import org.bukkit.command.CommandSender class FloatTransformer : ParameterTransformer<Float> { override fun transform( sender: CommandSender, command: CommandWrapper, args: List<String>, current: String ): Float? { try { return current.toFloat() } catch (_: NumberFormatException) { sender.sendMessage("&cPlease provide a valid integer number!".colorize()) return null } } override fun tabComplete( sender: CommandSender, command: CommandWrapper, args: List<String>, current: String ): List<String> { return emptyList() } }
0
Kotlin
0
2
c2e5a627509a16b483c5d0ddbf98518bacf8a547
876
CommandLibrary
MIT License
engine/src/main/kotlin/fi/thakki/sudokusolver/engine/service/builder/SudokuFile.kt
terohakkarainen
341,879,304
false
null
package fi.thakki.sudokusolver.engine.service.builder import fi.thakki.sudokusolver.engine.model.Cell import fi.thakki.sudokusolver.engine.model.CellCoordinates import fi.thakki.sudokusolver.engine.model.Coordinates import fi.thakki.sudokusolver.engine.model.Dimension import fi.thakki.sudokusolver.engine.model.Symbol import fi.thakki.sudokusolver.engine.model.Symbols class SudokuFile { // All fields must be public for SnakeYaml to access it. lateinit var dimension: Dimension lateinit var symbols: Set<Symbol> lateinit var givens: List<String> lateinit var regions: List<Map<Int, List<String>>> fun getGivenCells(): Set<Cell> { var bandIndex = dimension.value - 1 val result = mutableSetOf<Cell>() val processedChars = symbols.plus(CELL_NOT_GIVEN_MARKER) givens.forEach { line -> line.findAnyOf(processedChars.map { it.toString() })?.let { result.addAll( line.filter { character -> character in processedChars } .mapIndexedNotNull { index, character -> when (character) { CELL_NOT_GIVEN_MARKER -> null else -> { Cell(Coordinates(index, bandIndex), Symbols(symbols)).apply { setGiven(character) } } } } ) bandIndex-- } } return result } fun hasCustomRegions(): Boolean = this::regions.isInitialized fun getCoordinatesForRegions(): Set<CellCoordinates> = regions.map { region -> region.values.single().map { coordinatesString -> toCoordinates(coordinatesString) }.toSet() }.toSet() private fun toCoordinates(input: String): Coordinates { coordinatesPattern.find(input)?.let { matchResult -> val (x, y) = matchResult.destructured return Coordinates(x.toInt(), y.toInt()) } ?: throw IllegalArgumentException("Unable to parse coordinates from $input") } companion object { private const val CELL_NOT_GIVEN_MARKER = '.' private val coordinatesPattern = Regex("^([0-9]*),([0-9]*)$") } }
0
Kotlin
0
0
bdc74111cfc4b7425ea2c5383d93b9fdfb2628b5
2,416
sudoku-solver
MIT License
app/src/main/java/io/embry/hellowordel/presentation/views/Keyboard.kt
poppito
449,171,717
false
null
package io.embry.hellowordel.presentation.views import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.Spacer import androidx.compose.foundation.layout.height import androidx.compose.foundation.layout.size import androidx.compose.foundation.layout.width import androidx.compose.material.Button import androidx.compose.material.ButtonDefaults import androidx.compose.runtime.Composable import androidx.compose.ui.Modifier import androidx.compose.ui.res.stringResource import androidx.compose.ui.unit.dp import io.embry.hellowordel.R import io.embry.hellowordel.presentation.viewmodels.HelloWordelViewModel import io.embry.hellowordel.ui.theme.Teal200 @Composable fun Keyboard(viewModel: HelloWordelViewModel) { ControlKeys(viewModel::enterPressed, viewModel::deletePressed) } @Composable fun ControlKeys(enterPressed: () -> Unit, deletePressed: () -> Unit) { Spacer(modifier = Modifier.size(24.dp)) Row( horizontalArrangement = Arrangement.Center, modifier = Modifier.height(32.dp) ) { Button( modifier = Modifier .width(100.dp) .height(32.dp), colors = ButtonDefaults.buttonColors( backgroundColor = Teal200 ), onClick = { enterPressed.invoke() }) { ButtonLabel(label = stringResource(id = R.string.btn_enter)) } Spacer(modifier = Modifier.size(4.dp)) Button( modifier = Modifier .width(100.dp) .height(32.dp), colors = ButtonDefaults.buttonColors( backgroundColor = Teal200 ), onClick = { deletePressed.invoke() }) { ButtonLabel(label = stringResource(id = R.string.btn_del)) } } }
0
Kotlin
0
2
5fa1902e2529341b5a25cb4ebfa3d9ada83c83d7
1,921
HelloWordel
MIT License
src/main/kotlin/org/move/cli/runConfigurations/test/AptosTestRunState.kt
pontem-network
279,299,159
false
{"Kotlin": 2186749, "Move": 39898, "Lex": 5509, "HTML": 2114, "Java": 1275}
package org.move.cli.runConfigurations.test import com.intellij.execution.runners.ExecutionEnvironment import org.move.cli.runConfigurations.AptosRunStateBase import org.move.cli.runConfigurations.CommandConfigurationBase import org.move.cli.runConfigurations.aptos.AptosTestConsoleBuilder import org.move.cli.runConfigurations.aptos.cmd.AptosCommandConfiguration class AptosTestRunState( environment: ExecutionEnvironment, runConfiguration: CommandConfigurationBase, config: CommandConfigurationBase.CleanConfiguration.Ok ): AptosRunStateBase(environment, runConfiguration, config) { init { consoleBuilder = AptosTestConsoleBuilder(environment.runProfile as AptosCommandConfiguration, environment.executor) createFilters().forEach { consoleBuilder.addFilter(it) } } // override fun execute(executor: Executor, runner: ProgramRunner<*>): ExecutionResult { // val processHandler = startProcess() // val console = createConsole(executor) // console?.attachToProcess(processHandler) // return DefaultExecutionResult(console, processHandler).apply { setRestartActions(ToggleAutoTestAction()) } // } }
3
Kotlin
29
69
505651ca90cace4ba9f128d81b93d77fe3a0b94f
1,183
intellij-move
MIT License
extensions-compose-experimental/src/commonMain/kotlin/com/arkivanov/decompose/extensions/compose/experimental/BroadcastBackHandler.kt
arkivanov
437,015,897
false
{"Kotlin": 700677}
package com.arkivanov.decompose.extensions.compose.experimental import com.arkivanov.essenty.backhandler.BackCallback import com.arkivanov.essenty.backhandler.BackEvent import com.arkivanov.essenty.backhandler.BackHandler internal class BroadcastBackHandler( private val delegate: BackHandler, ) : BackCallback(), BackHandler { private var callbacks = emptyList<BackCallback>() override fun onBackStarted(backEvent: BackEvent) { callbacks.forEach { it.onBackStarted(backEvent) } } override fun onBackProgressed(backEvent: BackEvent) { callbacks.forEach { it.onBackProgressed(backEvent) } } override fun onBackCancelled() { callbacks.forEach(BackCallback::onBackCancelled) } override fun onBack() { callbacks.forEach(BackCallback::onBack) } override fun isRegistered(callback: BackCallback): Boolean = callback in callbacks override fun register(callback: BackCallback) { check(callback !in callbacks) callbacks += callback callbacks = callbacks.sortedByDescending(BackCallback::priority) priority = callback.priority if (callbacks.size == 1) { delegate.register(this) } } override fun unregister(callback: BackCallback) { check(callback in callbacks) callbacks -= callback if (callbacks.isEmpty()) { delegate.unregister(this) } } }
2
Kotlin
84
2,207
8af551e8895951a5082a5d2750335713d673f80b
1,447
Decompose
Apache License 2.0
app/src/main/java/com/example/mychat/presentation/screen/chat/ChatViewModel.kt
userddssilva
852,473,685
false
{"Kotlin": 63336}
package com.example.mychat.presentation.screen.chat import android.util.Log import androidx.compose.runtime.MutableState import androidx.compose.runtime.State import androidx.compose.runtime.mutableStateListOf import androidx.compose.runtime.mutableStateOf import androidx.lifecycle.SavedStateHandle import androidx.lifecycle.ViewModel import androidx.navigation.toRoute import com.example.mychat.domain.ChatRoom import com.example.mychat.domain.Message import com.example.mychat.navigation.Screen import com.example.mychat.util.ChatRoomTable import com.example.mychat.util.MessageTable import com.example.mychat.util.RequestState import com.example.mychat.util.mapMessages import com.parse.ParseException import com.parse.ParseObject import com.parse.ParseQuery import com.parse.ParseUser import com.parse.livequery.ParseLiveQueryClient import com.parse.livequery.SubscriptionHandling const val TAG = "ChatViewModel" class ChatViewModel(savedStateHandle: SavedStateHandle) : ViewModel() { private val chatId = savedStateHandle.toRoute<Screen.Chat>().id private var liveQueryClient: ParseLiveQueryClient? = null private var subscription: SubscriptionHandling<ParseObject>? = null private var subscription2: SubscriptionHandling<ParseObject>? = null private var _currentChat: MutableState<RequestState<ChatRoom?>> = mutableStateOf(RequestState.Loading) val currentChat: State<RequestState<ChatRoom?>> = _currentChat private var _messages = mutableStateListOf<Message>() val messages: List<Message> = _messages private var _messageInput: MutableState<String> = mutableStateOf("") var messageInput: State<String> = _messageInput private var _lastSeenMessage: MutableState<Message?> = mutableStateOf(null) var lastSeenMessage: State<Message?> = _lastSeenMessage private var _seen: MutableState<Boolean> = mutableStateOf(false) var seen: State<Boolean> = _seen init { getChatRoomById(chatId) { chatRoom, error -> if (error == null) { chatRoom?.let { _currentChat.value = RequestState.Success( ChatRoom( objectId = chatRoom.objectId ?: "0", participants = chatRoom.getList( ChatRoomTable.PARTICIPANTS ) ?: emptyList(), messages = emptyList(), lastSeenMessages = chatRoom.getMap( ChatRoomTable.LAST_SEEN_MESSAGES ) ?: emptyMap() ) ) liveQueryClient = ParseLiveQueryClient.Factory.getClient() observeChatRooms(chatRoom) observeMessages(chatRoom) val mappedMessages = mapMessages(chatRoom) _messages.addAll(mappedMessages.sortedBy { it.timestamp }) checkIfSeen(chatRoom) } } else { _currentChat.value = RequestState.Error(message = "Error fetching ChatRoom: ${error.message}") } } } fun setMessageInput(input: String) { _messageInput.value = input } private fun getChatRoomById( id: String, onComplete: (ParseObject?, ParseException?) -> Unit ) { val query = ParseQuery.getQuery<ParseObject>(ChatRoomTable.NAME) query.include(ChatRoomTable.PARTICIPANTS) query.include(ChatRoomTable.MESSAGES) query.include(ChatRoomTable.LAST_SEEN_MESSAGES) query.getInBackground(id) { chatRoom, e -> onComplete(chatRoom, e) } } private fun observeChatRooms(chatRoom: ParseObject) { val query = ParseQuery.getQuery<ParseObject>(ChatRoomTable.NAME) query.include(ChatRoomTable.PARTICIPANTS) query.include(ChatRoomTable.MESSAGES) query.include(ChatRoomTable.LAST_SEEN_MESSAGES) query.whereEqualTo("objectId", chatRoom.objectId) subscription = liveQueryClient!!.subscribe(query) subscription!!.handleSubscribe { subscription?.let { it.handleEvent(SubscriptionHandling.Event.UPDATE) { _, chatRoom -> if (chatRoom != null) { checkIfSeen(chatRoom) } else { Log.d(TAG, "ChatRoom UPDATED event Error: ChatRoom is null.") } } } } ?: Log.e(TAG, "Subscription is null.") } private fun observeMessages(chatRoom: ParseObject) { val messageQuery = ParseQuery.getQuery<ParseObject>( MessageTable.NAME ) messageQuery.whereEqualTo(MessageTable.CHAT_ROOM, chatRoom) subscription2 = liveQueryClient!!.subscribe(messageQuery) subscription2!!.handleSubscribe { if (subscription2 != null) { subscription2?.apply { handleEvent(SubscriptionHandling.Event.CREATE) { _, data -> data?.let { val newMessage = Message( objectId = it.objectId ?: "0", chatRoom = it.getParseObject(MessageTable.CHAT_ROOM) ?: ParseObject( ChatRoomTable.NAME ), owner = it.getParseUser(MessageTable.OWNER) ?: ParseUser.getCurrentUser(), text = it.getString(MessageTable.TEXT) ?: "", timestamp = it.getLong(MessageTable.TIMESTAMP) ) _messages.add(newMessage) checkIfSeen(chatRoom) } } } } else { Log.d(TAG, "Subscription is null.") } } } private fun checkIfSeen(chatRoom: ParseObject) { val otherParticipantId = chatRoom.getList<ParseUser>( ChatRoomTable.PARTICIPANTS )?.find { it.objectId != ParseUser.getCurrentUser().objectId }?.objectId val lastSeenMessageId = chatRoom.getMap<String>( ChatRoomTable.LAST_SEEN_MESSAGES )?.get(otherParticipantId) _seen.value = lastSeenMessageId == _messages.lastOrNull() ?.objectId } fun markMessageAsSeen(lastSeenMessage: Message) { getChatRoomById(chatId) { chat, chatError -> if (chat != null && chatError == null) { val lastSeenMessages = chat.getMap(ChatRoomTable.LAST_SEEN_MESSAGES) ?: mutableMapOf<String, String>() lastSeenMessages[ParseUser.getCurrentUser().objectId] = lastSeenMessage.objectId chat.put(ChatRoomTable.LAST_SEEN_MESSAGES, lastSeenMessages) chat.saveInBackground { error -> if (error == null) { _lastSeenMessage.value = lastSeenMessage } else { Log.d(TAG, "updateLastSeenMessage() Error: ${error.message}") } } } else { Log.d(TAG, "getChatRoomById() Error: ${chatError?.message}") } } } fun saveMessage(onSuccess: () -> Unit, onError: (String) -> Unit) { if (_currentChat.value is RequestState.Success) { val chatRoomId = (_currentChat.value as RequestState.Success).data?.objectId val chatRoomQuery = ParseQuery.getQuery<ParseObject>(ChatRoomTable.NAME) chatRoomQuery.getInBackground(chatRoomId) { chatRoom, chatRoomError -> if (chatRoomError == null && chatRoom != null) { val message = ParseObject(MessageTable.NAME) message.put(MessageTable.TEXT, _messageInput.value) message.put(MessageTable.OWNER, ParseUser.getCurrentUser()) message.put(MessageTable.CHAT_ROOM, chatRoom) message.put(MessageTable.TIMESTAMP, System.currentTimeMillis()) message.saveInBackground { messageError -> if (messageError == null) { chatRoom.add(ChatRoomTable.MESSAGES, message) chatRoom.saveInBackground { chatRoomSaveError -> if (chatRoomSaveError == null) { onSuccess() _messageInput.value = "" } else { onError("Error while saving a ChatRoom: ${chatRoomSaveError.message}") } } } else { onError("Error while saving a Message: ${messageError.message}") } } } else { onError("Error while retrieving ChatRoom: ${chatRoomError.message}") } } } } }
0
Kotlin
0
0
4ab54b4631092d26e495de2dd29c24a0a7765476
9,300
my-android-compose-chat
MIT License
app/src/main/java/com/aregyan/compose/ui/details/DetailsUiState.kt
aregpetrosyan
482,766,696
false
{"Kotlin": 24500}
package com.aregyan.compose.ui.details import com.aregyan.compose.domain.Details import com.aregyan.compose.util.formatDate data class DetailsUiState( val detail: Details = Details(), val offline: Boolean = false ) { val formattedUserSince = formatDate(detail.userSince) }
0
Kotlin
19
68
0fccc7bfb1d4b0174766f26acf0460149ea74760
286
Jetpack-Compose-Boilerplate
MIT License
web/src/main/kotlin/org/kotlinacademy/components/SubmitPuzzlerComponent.kt
TheLenon
126,489,458
true
{"CSS": 390884, "Kotlin": 188342, "JavaScript": 2417, "HTML": 1708, "Shell": 170}
package org.kotlinacademy.components import org.kotlinacademy.presentation.puzzler.PuzzlerPresenter import org.kotlinacademy.presentation.puzzler.PuzzlerView import org.kotlinacademy.views.errorView import org.kotlinacademy.views.loadingView import org.kotlinacademy.views.puzzlerFormView import org.kotlinacademy.views.thankYouView import react.RBuilder import react.RProps import react.ReactElement import kotlin.properties.Delegates.observable class SubmitPuzzlerComponent : BaseComponent<RProps, SubmitPuzzlerComponentState>(), PuzzlerView { private val presenter by presenter { PuzzlerPresenter(this) } override var loading: Boolean by observable(false) { _, _, n -> setState { state.loading = n } } override fun RBuilder.render(): ReactElement? = when { state.loading == true -> loadingView() state.showThankYouPage == true -> thankYouView() state.error != null -> errorView(state.error!!) else -> puzzlerFormView(onSubmit = presenter::onSubmitCommentClicked) } override fun backToNewsAndShowSuccess() { setState { showThankYouPage = true } backToRootAfterDelay(millis = 3_000) } } external interface SubmitPuzzlerComponentState : BaseState { var loading: Boolean? var showThankYouPage: Boolean? }
0
CSS
0
0
359488e94c9b2799e66ce6e58ad7eb212ac37141
1,302
KotlinAcademyApp
Apache License 2.0
sample/src/main/java/ru/evolinc/servection/androidsample/MainActivity.kt
nesterenko1pavel
771,602,079
false
{"Kotlin": 10043}
package ru.evolinc.servection.androidsample import android.os.Bundle import android.util.Log import androidx.appcompat.app.AppCompatActivity import ru.evolinc.servection.R import ru.evolinc.servection.di.DiContainer import ru.evolinc.servection.di.RootContainer import ru.evolinc.servection.di.retainContainer class MainActivity : AppCompatActivity(R.layout.activity_main), DiContainer { override val container: RootContainer by retainContainer() override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) Log.i("testapp", "onCreate: $container") if (savedInstanceState == null) { supportFragmentManager.beginTransaction() .add(android.R.id.content, MainFragment()) .commitNow() } } }
0
Kotlin
0
2
2a7d446f4ee67cb1d8e38c1a9b96bd2123ccbfad
805
servection
Apache License 2.0
domain/src/main/java/dev/zabolotskikh/authguard/domain/model/BarcodeService.kt
kanefron5
635,099,229
false
{"Kotlin": 203749, "Shell": 492}
package dev.zabolotskikh.authguard.domain.model data class BarcodeService( val alias: String, val secret: String, val issuer: String )
2
Kotlin
1
1
9b61da71f7511b4f27c5edd7c01eaaa6b8beffb1
139
authguard
MIT License
recyclerviewscreen/shot/src/androidTest/java/com/example/road/to/effective/snapshot/testing/recyclerviewscreen/shot/activity/RecyclerViewActivityWithTestParameterInjectorTest.kt
sergio-sastre
394,010,429
false
null
package com.example.road.to.effective.snapshot.testing.recyclerviewscreen.shot.activity import androidx.test.filters.SdkSuppress import com.example.road.to.effective.snapshot.testing.recyclerviewscreen.mvvm.RecyclerViewActivity import com.example.road.to.effective.snapshot.testing.testannotations.HappyPath import com.example.road.to.effective.snapshot.testing.testannotations.UnhappyPath import com.google.testing.junit.testparameterinjector.TestParameter import com.google.testing.junit.testparameterinjector.TestParameterInjector import com.karumi.shot.ScreenshotTest import org.junit.Rule import org.junit.Test import org.junit.runner.RunWith import sergio.sastre.uitesting.utils.activityscenario.activityScenarioForActivityRule /** * Example of Parameterized test with TestParameterInjector Runner. * * Unlike Parameterized Runner, the test methods admit arguments, although we do not use them here. * * On the other hand, TestParameterInjector requires API 24+ to run with instrumented tests. * It throws java.lang.NoClassDefFoundError: com.google.common.cache.CacheBuilder in lower APIs. * Parameterized Runner is compatible with instrumented test of any API level */ @SdkSuppress(minSdkVersion = 24) @RunWith(TestParameterInjector::class) class RecyclerViewActivityTestParameterHappyPathTest( @TestParameter val configItem: HappyPathTestItem, ) : ScreenshotTest { @get:Rule val activityScenarioForActivityRule = activityScenarioForActivityRule<RecyclerViewActivity>(configItem.item) @HappyPath @Test fun snapActivity() { val activity = activityScenarioForActivityRule.activity val activityView = activity.window.decorView compareScreenshot( activity = activity, heightInPx = activityView.measuredHeight, widthInPx = activityView.measuredWidth, name = "RecyclerViewActivity_${configItem.name}_TestParameter" ) } } @SdkSuppress(minSdkVersion = 24) @RunWith(TestParameterInjector::class) class RecyclerViewActivityTestParameterUnhappyPathTest( @TestParameter val configItem: UnhappyPathTestItem, ) : ScreenshotTest { @get:Rule val activityScenarioForActivityRule = activityScenarioForActivityRule<RecyclerViewActivity>(configItem.item) @UnhappyPath @Test fun snapActivity() { val activity = activityScenarioForActivityRule.activity val activityView = activity.window.decorView compareScreenshot( activity = activity, heightInPx = activityView.measuredHeight, widthInPx = activityView.measuredWidth, name = "RecyclerViewActivity_${configItem.name}_TestParameter" ) } }
3
Kotlin
11
145
56055666226fb1c3ddd8aff7f98c7979ff1aa839
2,723
Android-screenshot-testing-playground
MIT License
recyclerviewscreen/shot/src/androidTest/java/com/example/road/to/effective/snapshot/testing/recyclerviewscreen/shot/activity/RecyclerViewActivityWithTestParameterInjectorTest.kt
sergio-sastre
394,010,429
false
null
package com.example.road.to.effective.snapshot.testing.recyclerviewscreen.shot.activity import androidx.test.filters.SdkSuppress import com.example.road.to.effective.snapshot.testing.recyclerviewscreen.mvvm.RecyclerViewActivity import com.example.road.to.effective.snapshot.testing.testannotations.HappyPath import com.example.road.to.effective.snapshot.testing.testannotations.UnhappyPath import com.google.testing.junit.testparameterinjector.TestParameter import com.google.testing.junit.testparameterinjector.TestParameterInjector import com.karumi.shot.ScreenshotTest import org.junit.Rule import org.junit.Test import org.junit.runner.RunWith import sergio.sastre.uitesting.utils.activityscenario.activityScenarioForActivityRule /** * Example of Parameterized test with TestParameterInjector Runner. * * Unlike Parameterized Runner, the test methods admit arguments, although we do not use them here. * * On the other hand, TestParameterInjector requires API 24+ to run with instrumented tests. * It throws java.lang.NoClassDefFoundError: com.google.common.cache.CacheBuilder in lower APIs. * Parameterized Runner is compatible with instrumented test of any API level */ @SdkSuppress(minSdkVersion = 24) @RunWith(TestParameterInjector::class) class RecyclerViewActivityTestParameterHappyPathTest( @TestParameter val configItem: HappyPathTestItem, ) : ScreenshotTest { @get:Rule val activityScenarioForActivityRule = activityScenarioForActivityRule<RecyclerViewActivity>(configItem.item) @HappyPath @Test fun snapActivity() { val activity = activityScenarioForActivityRule.activity val activityView = activity.window.decorView compareScreenshot( activity = activity, heightInPx = activityView.measuredHeight, widthInPx = activityView.measuredWidth, name = "RecyclerViewActivity_${configItem.name}_TestParameter" ) } } @SdkSuppress(minSdkVersion = 24) @RunWith(TestParameterInjector::class) class RecyclerViewActivityTestParameterUnhappyPathTest( @TestParameter val configItem: UnhappyPathTestItem, ) : ScreenshotTest { @get:Rule val activityScenarioForActivityRule = activityScenarioForActivityRule<RecyclerViewActivity>(configItem.item) @UnhappyPath @Test fun snapActivity() { val activity = activityScenarioForActivityRule.activity val activityView = activity.window.decorView compareScreenshot( activity = activity, heightInPx = activityView.measuredHeight, widthInPx = activityView.measuredWidth, name = "RecyclerViewActivity_${configItem.name}_TestParameter" ) } }
3
Kotlin
11
145
56055666226fb1c3ddd8aff7f98c7979ff1aa839
2,723
Android-screenshot-testing-playground
MIT License
src/main/kotlin/ez/db/table/TableEx.kt
rainmanhhh
150,186,909
false
null
package ez.db.table import org.jooq.Configuration import org.jooq.Record import org.jooq.RecordMapper import org.jooq.Table /** * * @receiver Table<RECORD> * @param pojoClass Class<POJO> * @param configuration Configuration * @return RecordMapper<RECORD, POJO> */ fun <RECORD : Record, POJO : Any> Table<RECORD>.mapper( pojoClass: Class<POJO>, configuration: Configuration ): RecordMapper<RECORD, POJO> = configuration.recordMapperProvider().provide(recordType(), pojoClass)
0
Kotlin
0
0
dc9fbd97316ebfc6fd48e68098b22a7bbe92c4df
486
ez-spring
MIT License
app/src/main/java/com/simform/todo/presentation/ui/newtask/NewTaskFragment.kt
nishchal-visavadiya
572,493,980
false
null
package com.simform.todo.presentation.ui.newtask import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.fragment.app.Fragment import com.simform.todo.databinding.FragmentNewTaskBinding import com.simform.todo.presentation.ui.alert.Alerter import com.simform.todo.presentation.utils.closeSoftInputKeyboard import com.simform.todo.presentation.utils.observeEvent import com.simform.todo.presentation.utils.obtainViewModel class NewTaskFragment : Fragment() { private lateinit var mBinding: FragmentNewTaskBinding private val mAlerter by lazy { Alerter() } private val mNewTaskViewModel by lazy { requireActivity().obtainViewModel(NewTaskViewModel::class.java) } override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View { mBinding = FragmentNewTaskBinding.inflate(inflater, container, false) return mBinding.root } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) mNewTaskViewModel.setup() setupUi() } private fun setupUi() { mBinding.btnCreate.setOnClickListener { val titleEditText = mBinding.edTextTitle val descriptionEditText = mBinding.edTextDescription mNewTaskViewModel.addTask( titleEditText.text.toString(), descriptionEditText.text.toString() ) { mAlerter.showSuccess("Created", it, requireActivity()) titleEditText.text.clear() descriptionEditText.text.clear() } requireActivity().closeSoftInputKeyboard() titleEditText.clearFocus() descriptionEditText.clearFocus() } } private fun NewTaskViewModel.setup() { emptyError.observeEvent(viewLifecycleOwner) { mAlerter.showError("Empty", it.toString(), requireActivity()) } } }
0
Kotlin
0
4
6e6d6a9516988b26f09a109e1819759fc4f56de9
2,068
Sample-Android-App-Clean-architecture
MIT License
app/src/main/java/com/eajy/materialdesigndemo/activity/AboutActivity.kt
monsoon235
169,074,846
true
{"Kotlin": 89670, "Java": 7432, "HTML": 1112}
package com.eajy.materialdesigndemo.activity import android.app.Dialog import android.content.Intent import android.net.Uri import android.os.Bundle import android.support.design.widget.FloatingActionButton import android.support.v7.app.AppCompatActivity import android.support.v7.widget.Toolbar import android.view.View import android.view.animation.AlphaAnimation import android.view.animation.AnimationUtils import android.webkit.WebView import android.widget.* import com.eajy.materialdesigndemo.Constant import com.eajy.materialdesigndemo.R import com.eajy.materialdesigndemo.util.AppUtils class AboutActivity : AppCompatActivity(), View.OnClickListener { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_about) val toolbar = findViewById<Toolbar>(R.id.toolbar_about) setSupportActionBar(toolbar) supportActionBar?.setDisplayHomeAsUpEnabled(true) window.navigationBarColor = resources.getColor(R.color.colorPrimary) initView() } private fun initView() { val animation = AnimationUtils.loadAnimation(this, R.anim.anim_about_card_show) val scroll_about = findViewById<ScrollView>(R.id.scroll_about) scroll_about.startAnimation(animation) val ll_card_about_2_shop = findViewById<LinearLayout>(R.id.ll_card_about_2_shop) val ll_card_about_2_email = findViewById<LinearLayout>(R.id.ll_card_about_2_email) val ll_card_about_2_git_hub = findViewById<LinearLayout>(R.id.ll_card_about_2_git_hub) val ll_card_about_2_website = findViewById<LinearLayout>(R.id.ll_card_about_2_website) val ll_card_about_source_licenses = findViewById<LinearLayout>(R.id.ll_card_about_source_licenses) ll_card_about_2_shop.setOnClickListener(this) ll_card_about_2_email.setOnClickListener(this) ll_card_about_2_git_hub.setOnClickListener(this) ll_card_about_2_website.setOnClickListener(this) ll_card_about_source_licenses.setOnClickListener(this) val fab = findViewById<FloatingActionButton>(R.id.fab_about_share) fab.setOnClickListener(this) val alphaAnimation = AlphaAnimation(0.0f, 1.0f) alphaAnimation.duration = 300 alphaAnimation.startOffset = 600 val tv_about_version = findViewById<TextView>(R.id.tv_about_version) tv_about_version.text = AppUtils.getVersionName(this) tv_about_version.startAnimation(alphaAnimation) } override fun onClick(view: View) { val intent = Intent() when (view.id) { R.id.ll_card_about_2_shop -> { intent.data = Uri.parse(Constant.APP_URL) intent.action = Intent.ACTION_VIEW startActivity(intent) } R.id.ll_card_about_2_email -> { intent.action = Intent.ACTION_SENDTO intent.data = Uri.parse(Constant.EMAIL) intent.putExtra(Intent.EXTRA_SUBJECT, getString(R.string.about_email_intent)) //intent.putExtra(Intent.EXTRA_TEXT, "Hi,"); try { startActivity(intent) } catch (e: Exception) { Toast.makeText(this@AboutActivity, getString(R.string.about_not_found_email), Toast.LENGTH_SHORT).show() } } R.id.ll_card_about_source_licenses -> { val dialog = Dialog(this, R.style.DialogFullscreenWithTitle) dialog.setTitle(getString(R.string.about_source_licenses)) dialog.setContentView(R.layout.dialog_source_licenses) val webView = dialog.findViewById<WebView>(R.id.web_source_licenses) webView.loadUrl("file:///android_asset/open_source_license.html") val btn_source_licenses_close = dialog.findViewById<Button>(R.id.btn_source_licenses_close) btn_source_licenses_close.setOnClickListener { dialog.dismiss() } dialog.show() } R.id.ll_card_about_2_git_hub -> { intent.data = Uri.parse(Constant.GIT_HUB) intent.action = Intent.ACTION_VIEW startActivity(intent) } R.id.ll_card_about_2_website -> { intent.data = Uri.parse(Constant.MY_WEBSITE) intent.action = Intent.ACTION_VIEW startActivity(intent) } R.id.fab_about_share -> { intent.action = Intent.ACTION_SEND intent.putExtra(Intent.EXTRA_TEXT, Constant.SHARE_CONTENT) intent.type = "text/plain" startActivity(Intent.createChooser(intent, getString(R.string.share_with))) } } } }
0
Kotlin
0
0
e91ef13badec4337b5caec64c723f75837643c5c
4,832
MaterialDesignDemo
Apache License 2.0
src/main/kotlin/com/quid/loan/user/user/UserController.kt
QuiD-0
595,016,463
false
null
package com.quid.loan.user.user import com.quid.loan.counsel.dto.CounselRequest import com.quid.loan.counsel.dto.CounselResponse import com.quid.loan.counsel.dto.CounselUpdateRequest import com.quid.loan.user.dto.UserCreateRequest import com.quid.loan.user.dto.UserResponse import com.quid.loan.user.service.UserService import org.springframework.web.bind.annotation.* @RestController @RequestMapping("/user") class UserController( private val userService: UserService ) { @PostMapping fun createUser(@RequestBody userCreateRequest: UserCreateRequest): UserResponse { return userService.createUser(userCreateRequest) } @GetMapping("/counsel/{id}") fun getCounsel(@PathVariable id: Long): CounselResponse { return userService.getUserCounsel(id) } @PutMapping("/counsel/memo") fun updateCounselMemo(@RequestBody request: CounselUpdateRequest) { userService.updateCounselMemo(request) } @DeleteMapping("/counsel/{id}") fun deleteCounsel(@PathVariable id: Long) { userService.deleteCounsel(id) } @PostMapping("/counsel") fun createCounsel(@RequestBody request: CounselRequest): CounselResponse { return userService.createCounsel(request) } }
0
Kotlin
0
0
4f927ec547344ef81fd70e685234db286073dbf1
1,249
Loan
MIT License
src/main/kotlin/com/quid/loan/user/user/UserController.kt
QuiD-0
595,016,463
false
null
package com.quid.loan.user.user import com.quid.loan.counsel.dto.CounselRequest import com.quid.loan.counsel.dto.CounselResponse import com.quid.loan.counsel.dto.CounselUpdateRequest import com.quid.loan.user.dto.UserCreateRequest import com.quid.loan.user.dto.UserResponse import com.quid.loan.user.service.UserService import org.springframework.web.bind.annotation.* @RestController @RequestMapping("/user") class UserController( private val userService: UserService ) { @PostMapping fun createUser(@RequestBody userCreateRequest: UserCreateRequest): UserResponse { return userService.createUser(userCreateRequest) } @GetMapping("/counsel/{id}") fun getCounsel(@PathVariable id: Long): CounselResponse { return userService.getUserCounsel(id) } @PutMapping("/counsel/memo") fun updateCounselMemo(@RequestBody request: CounselUpdateRequest) { userService.updateCounselMemo(request) } @DeleteMapping("/counsel/{id}") fun deleteCounsel(@PathVariable id: Long) { userService.deleteCounsel(id) } @PostMapping("/counsel") fun createCounsel(@RequestBody request: CounselRequest): CounselResponse { return userService.createCounsel(request) } }
0
Kotlin
0
0
4f927ec547344ef81fd70e685234db286073dbf1
1,249
Loan
MIT License
bootgraph-core/src/main/kotlin/com/atlassian/bootgraph/api/mapper/ExternalBeanMapper.kt
atlassian-labs
249,557,725
false
null
package com.atlassian.bootgraph.api.mapper import com.atlassian.bootgraph.api.model.Node import org.springframework.beans.factory.config.BeanDefinition import org.springframework.context.ConfigurableApplicationContext import java.util.Optional /** * Maps a bean into a simple external graph node using the bean name as a graph label. Use this matcher to include beans into * the graph without any special requirements. */ class ExternalBeanMapper : BeanMapper { override fun mapToGraph(bean: Any, beanName: String, beanDefinition: BeanDefinition, applicationContext: ConfigurableApplicationContext, factory: NodeFactory): Optional<Node> { return Optional.of(factory.externalNode(beanName)) } }
2
Kotlin
1
7
8e74c8884719f2145ae80806cab5fb736cb0e5b2
716
bootgraph
Apache License 2.0
connection/src/main/java/com/thoughtworks/cconn/comm/base/CommHandler.kt
TW-Smart-CoE
562,334,431
false
null
package com.thoughtworks.cconn.comm.base import com.thoughtworks.cconn.ConnectionState import com.thoughtworks.cconn.OnConnectionStateChangeListener import com.thoughtworks.cconn.log.Logger import com.thoughtworks.cconn.utils.getInt import java.io.IOException import java.io.InputStream import java.io.OutputStream internal typealias OnCommCloseListener = (commHandler: CommHandler, isPassive: Boolean) -> Unit internal class CommHandler( private val isClient: Boolean, private val comm: Comm, private val logger: Logger, var onCommCloseListener: OnCommCloseListener? = null, var onMsgArrivedListener: OnMsgArrivedListener? = null, var onConnectionStateChangeListener: OnConnectionStateChangeListener? = null, private val recvBufferSize: Int = DEFAULT_BUFFER_SIZE ) : Runnable { private var inStream: InputStream? = null private var outStream: OutputStream? = null private val buffer: ByteArray = ByteArray(recvBufferSize) private var bufferDataStartOffset: Int = 0 private var bufferDataLen: Int = 0 private var isClose = false private var msgCompleteness = MSG_COMPLETENESS_NONE private val currentHeader = MsgHeader() private val currentMsg = Msg() override fun run() { if (isClient) { try { onConnectionStateChangeListener?.onConnectionStateChanged(ConnectionState.CONNECTING) comm.connect() } catch (e: IOException) { logger.error("Connect failed: ${e.message}") close(true) return } } try { inStream = comm.inputStream() outStream = comm.outputStream() } catch (e: IOException) { logger.error("Get input/output stream failed: ${e.message}") close(true) return } onConnectionStateChangeListener?.onConnectionStateChanged(ConnectionState.CONNECTED) isClose = false while (!isClose) { val msg = readMsgFlagFromBuffer() if (msg == null) { logger.warn("Connection is lost") close(true) isClose = true } msg?.let { if (msg.calcCheckSum() == msg.header.checkSum) { onMsgArrivedListener?.invoke(it) } msgCompleteness = MSG_COMPLETENESS_NONE } } } @Throws(IOException::class) fun send(msg: Msg) { outStream?.apply { msg.header.checkSum = msg.calcCheckSum() write(msg.toByteArray()) flush() } } fun close(isPassive: Boolean = false) { if (!isPassive) { onMsgArrivedListener = null onCommCloseListener = null } isClose = true try { comm.close() onConnectionStateChangeListener?.onConnectionStateChanged(ConnectionState.DISCONNECTED) } catch (e: IOException) { logger.error("Could not close the connection: ${e.message}") onConnectionStateChangeListener?.onConnectionStateChanged( ConnectionState.DISCONNECTED, e ) } finally { onCommCloseListener?.invoke(this, isPassive) } } private fun readFromInputStream(): Msg? { val inStream = inStream ?: return null val len = try { inStream.read(buffer, bufferDataStartOffset + bufferDataLen, bufferLeftSize()) } catch (e: IOException) { logger.warn("Stream.Read Exception: ${e.message}") return null } if (len <= 0) { logger.warn("stream.Read len == $len") return null } bufferDataLen += len return when (msgCompleteness) { MSG_COMPLETENESS_NONE -> { readMsgFlagFromBuffer() } MSG_COMPLETENESS_FLAG -> { readMsgHeaderFromBuffer() } MSG_COMPLETENESS_HEADER -> { readMsgBodyFromBuffer() } else -> { null } } } private fun readMsgFlagFromBuffer(): Msg? { var found = false for (i in bufferDataStartOffset..bufferDataStartOffset + bufferDataLen - Int.SIZE_BYTES) { if (buffer.getInt(bufferDataStartOffset) == msgFlag()) { found = true if (i != 0) { buffer.copyInto(buffer, 0, i, bufferDataStartOffset + bufferDataLen) bufferDataStartOffset = 0 bufferDataLen -= (i - bufferDataStartOffset) } break } } return if (found) { msgCompleteness = MSG_COMPLETENESS_FLAG readMsgHeaderFromBuffer() } else { // cannot find flag, reset buffer position and receive data again msgCompleteness = MSG_COMPLETENESS_NONE bufferDataStartOffset = 0 bufferDataLen = 0 readFromInputStream() } } private fun readMsgHeaderFromBuffer(): Msg? { if (bufferDataLen < MSG_HEADER_LEN) { return readFromInputStream() } val headerBuffer = ByteArray(MSG_HEADER_LEN) buffer.copyInto( headerBuffer, 0, bufferDataStartOffset, bufferDataStartOffset + MSG_HEADER_LEN ) currentHeader.fromByteArray(headerBuffer) msgCompleteness = MSG_COMPLETENESS_HEADER return readMsgBodyFromBuffer() } private fun readMsgBodyFromBuffer(): Msg? { if (bufferDataLen < MSG_HEADER_LEN + currentHeader.topicLen.toInt() + currentHeader.dataLen.toInt()) { return readFromInputStream() } val topicBuffer = ByteArray(currentHeader.topicLen.toInt()) buffer.copyInto( topicBuffer, 0, bufferDataStartOffset + MSG_HEADER_LEN, bufferDataStartOffset + MSG_HEADER_LEN + currentHeader.topicLen.toInt() ) val dataBuffer = ByteArray(currentHeader.dataLen.toInt()) buffer.copyInto( dataBuffer, 0, bufferDataStartOffset + MSG_HEADER_LEN + currentHeader.topicLen.toInt(), bufferDataStartOffset + MSG_HEADER_LEN + currentHeader.topicLen.toInt() + currentHeader.dataLen.toInt() ) currentMsg.header = currentHeader currentMsg.topic = topicBuffer currentMsg.data = dataBuffer val leftDataLen = (bufferDataLen - currentMsg.length()) buffer.copyInto( buffer, 0, bufferDataStartOffset + currentMsg.length(), bufferDataStartOffset + currentMsg.length() + leftDataLen ) bufferDataStartOffset = 0 bufferDataLen = leftDataLen return currentMsg.copyOf() } private fun bufferLeftSize(): Int { return recvBufferSize - (bufferDataStartOffset + bufferDataLen) } companion object { private const val MSG_COMPLETENESS_NONE = 0 private const val MSG_COMPLETENESS_FLAG = 1 private const val MSG_COMPLETENESS_HEADER = 2 } }
3
Kotlin
0
2
d3e73b9a4971fe02b7854d67284f70033f82adf6
7,362
cross-connection-android
Apache License 2.0
lbcglance/src/main/kotlin/studio/lunabee/compose/glance/extensions/GlanceModifierExt.kt
LunabeeStudio
472,673,596
false
{"Kotlin": 247677, "Java": 161408, "Python": 4873}
/* * Copyright (c) 2024 Lunabee Studio * * 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. * * GlanceModifierExt.kt * Lunabee Compose * * Created by Lunabee Studio / Date - 8/9/2024 - for the Lunabee Compose library. */ package studio.lunabee.compose.glance.extensions import android.graphics.drawable.ShapeDrawable import android.graphics.drawable.shapes.RoundRectShape import android.os.Build import androidx.compose.ui.graphics.Color import androidx.compose.ui.graphics.toArgb import androidx.compose.ui.unit.Dp import androidx.compose.ui.unit.DpSize import androidx.core.graphics.ColorUtils import androidx.core.graphics.drawable.toBitmap import androidx.glance.GlanceModifier import androidx.glance.ImageProvider import androidx.glance.LocalSize import androidx.glance.appwidget.cornerRadius import androidx.glance.background import androidx.glance.layout.size import kotlin.math.roundToInt /** * According to the documentation of [androidx.glance.appwidget.CornerRadiusModifier], * rounded corners are applied with [GlanceModifier.cornerRadius] method only on API S+ (31+). * For below APIs, we need to use a [ShapeDrawable] to keep our design consistency across APIs. * FIXME for Android S+, documentation advices to apply appWidgetBackground to the same view that handles corner radius. * -> But it is currently causing a flickering when the widget is moved by the user. * @param cornerRadius dimension in [Dp] of the desired corner radius. To keep your design consistency across all devices, it is mandatory, * as the default value used by Android on API31+ depends on the device. If you want to keep this behavior, you can use * [android.R.dimen.system_app_widget_background_radius] dimension. * @param color background color of your widget. * @param size size of your widget. Can be get with [LocalSize]. */ fun GlanceModifier.cornerRadiusCompat( cornerRadius: Dp, color: Color, size: DpSize, ): GlanceModifier { return if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) { size(width = size.width, height = size.height) .background(color = color) .cornerRadius(radius = cornerRadius) } else { val radii = FloatArray(size = 8) { cornerRadius.value } val bitmap = ShapeDrawable(RoundRectShape(radii, null, null)).apply { paint.color = ColorUtils.setAlphaComponent(color.toArgb(), 255) }.toBitmap(width = size.width.value.roundToInt(), height = size.height.value.roundToInt()) size(width = size.width, height = size.height) .background(imageProvider = ImageProvider(bitmap = bitmap)) } }
0
Kotlin
0
10
276b02c9abbb6424a9a84f49c24f6bd7be6583a3
3,135
Lunabee_Compose_Android
Apache License 2.0
vk-api-generated/src/main/kotlin/name/anton3/vkapi/generated/notifications/objects/Notification.kt
Anton3
159,801,334
true
{"Kotlin": 1382186}
@file:Suppress("unused", "SpellCheckingInspection") package name.anton3.vkapi.generated.notifications.objects /** * No description * * @property date Date when the event has been occurred * @property feedback No description * @property parent No description * @property reply No description * @property type Notification type */ data class Notification( val date: Long? = null, val feedback: Feedback? = null, val parent: Notification? = null, val reply: Reply? = null, val type: String? = null )
2
Kotlin
0
8
773c89751c4382a42f556b6d3c247f83aabec625
527
kotlin-vk-api
MIT License
app/src/main/java/com/smlnskgmail/jaman/deviceinfo/info/components/system/structure/SystemInfo.kt
DexterDsd
224,637,905
true
{"Kotlin": 69371}
package com.smlnskgmail.jaman.deviceinfo.info.components.system.structure import com.smlnskgmail.jaman.deviceinfo.info.defaultdata.FakeInfoStringResult interface SystemInfo { fun model(): String fun product(): String fun brand(): String fun type(): String fun manufacturer(): String fun board(): String fun hardware(): String fun releaseVersion(): String fun apiLevel(): String fun user(): String fun host(): String fun fingerprint(): String fun bootloader(): String fun arch(): String fun kernelVersion(): String fun date(): String fun codeName(): String class FakeSystemInfo : SystemInfo { private val fakeResult = FakeInfoStringResult() override fun model() = fakeResult.value() override fun product() = fakeResult.value() override fun brand() = fakeResult.value() override fun type() = fakeResult.value() override fun manufacturer() = fakeResult.value() override fun board() = fakeResult.value() override fun hardware() = fakeResult.value() override fun releaseVersion() = fakeResult.value() override fun apiLevel() = fakeResult.value() override fun user() = fakeResult.value() override fun host() = fakeResult.value() override fun fingerprint() = fakeResult.value() override fun bootloader() = fakeResult.value() override fun arch() = fakeResult.value() override fun kernelVersion() = fakeResult.value() override fun date() = fakeResult.value() override fun codeName() = fakeResult.value() } }
0
null
0
0
dee2b0d1dbf18d6c2f290ed715fed9e853f78156
1,642
android-device-info
The Unlicense
src/test/kotlin/no/nav/eessi/pensjon/integrasjonstest/saksflyt/PBuc05IntegrationTest.kt
mammut89
326,490,563
true
{"Kotlin": 644016, "Shell": 603, "Dockerfile": 254}
package no.nav.eessi.pensjon.integrasjonstest.saksflyt import no.nav.eessi.pensjon.models.Enhet.AUTOMATISK_JOURNALFORING import no.nav.eessi.pensjon.models.Enhet.ID_OG_FORDELING import no.nav.eessi.pensjon.models.Enhet.NFP_UTLAND_AALESUND import no.nav.eessi.pensjon.models.Enhet.PENSJON_UTLAND import no.nav.eessi.pensjon.models.Enhet.UFORE_UTLAND import no.nav.eessi.pensjon.models.Enhet.UFORE_UTLANDSTILSNITT import no.nav.eessi.pensjon.models.SakInformasjon import no.nav.eessi.pensjon.models.SakStatus import no.nav.eessi.pensjon.models.Tema.PENSJON import no.nav.eessi.pensjon.models.Tema.UFORETRYGD import no.nav.eessi.pensjon.models.YtelseType import no.nav.eessi.pensjon.personidentifisering.helpers.Diskresjonskode import org.junit.jupiter.api.Assertions.assertEquals import org.junit.jupiter.api.DisplayName import org.junit.jupiter.api.Nested import org.junit.jupiter.api.Test @DisplayName("P_BUC_05 - Utgående journalføring - IntegrationTest") internal class PBuc05IntegrationTest : JournalforingTestBase() { /** * P_BUC_05 DEL 1 * * Flytskjema (utgående): * https://confluence.adeo.no/pages/viewpage.action?pageId=387092731 */ /* ============================ * SCENARIO 1 * ============================ */ @Nested inner class Scenario1 { @Test fun `1 person i SED fnr finnes men ingen bestemsak Så journalføres på ID_OG_FORDELING`() { testRunner(FNR_OVER_60, saker = emptyList(), sakId = SAK_ID) { // forvent tema == PEN og enhet 4303 assertEquals(PENSJON, it.tema) assertEquals(ID_OG_FORDELING, it.journalfoerendeEnhet) } } @Test fun `1 person i SED, men fnr er feil`() { testRunner(fnr = "123456789102356878546525468432") { assertEquals(PENSJON, it.tema) assertEquals(ID_OG_FORDELING, it.journalfoerendeEnhet) } } @Test fun `1 person i SED, men fnr mangler`() { testRunner(fnr = null) { assertEquals(PENSJON, it.tema) assertEquals(ID_OG_FORDELING, it.journalfoerendeEnhet) } } } /* ============================ * SCENARIO 2 * ============================ */ @Nested inner class Scenario2 { @Test fun `2 personer i SED, fnr og rolle mangler, men saksnummer finnes`() { testRunnerFlerePersoner(fnr = null, fnrAnnenPerson = null, rolle = "01", sakId = SAK_ID) { assertEquals(PENSJON, it.tema) assertEquals(ID_OG_FORDELING, it.journalfoerendeEnhet) } } @Test fun `2 personer i SED, har fnr, mangler rolle og saksnummer`() { testRunnerFlerePersoner(FNR_VOKSEN, fnrAnnenPerson = null, rolle = null, sakId = null) { assertEquals(PENSJON, it.tema) assertEquals(ID_OG_FORDELING, it.journalfoerendeEnhet) } } @Test fun `2 personer i SED, mangler fnr og saksnummer, men rolle finnes`() { testRunnerFlerePersoner(fnr = null, fnrAnnenPerson = null, rolle = "01", sakId = null) { assertEquals(PENSJON, it.tema) assertEquals(ID_OG_FORDELING, it.journalfoerendeEnhet) } } @Test fun `2 personer i SED, mangler fnr, rolle, og sakId`() { testRunnerFlerePersoner(fnr = null, fnrAnnenPerson = null, rolle = null, sakId = null) { assertEquals(PENSJON, it.tema) assertEquals(ID_OG_FORDELING, it.journalfoerendeEnhet) } } } /* ============================ * SCENARIO 3 * ============================ */ @Nested inner class Scenario3 { @Test fun `1 person i SED fnr finnes, saktype er GENRL, men finnes flere sakstyper`() { val saker = listOf( SakInformasjon(sakId = SAK_ID, sakType = YtelseType.GENRL, sakStatus = SakStatus.TIL_BEHANDLING), SakInformasjon(sakId = "1111", sakType = YtelseType.ALDER, sakStatus = SakStatus.TIL_BEHANDLING), SakInformasjon(sakId = "2222", sakType = YtelseType.UFOREP, sakStatus = SakStatus.TIL_BEHANDLING) ) testRunner(FNR_OVER_60, saker) { assertEquals(PENSJON, it.tema) assertEquals(NFP_UTLAND_AALESUND, it.journalfoerendeEnhet) } testRunner(FNR_VOKSEN, saker) { assertEquals(PENSJON, it.tema) assertEquals(UFORE_UTLANDSTILSNITT, it.journalfoerendeEnhet) } testRunner(FNR_BARN, saker) { assertEquals(PENSJON, it.tema) assertEquals(NFP_UTLAND_AALESUND, it.journalfoerendeEnhet) } } @Test fun `1 person i SED fnr finnes, saktype er GENRL, men finnes flere sakstyper, bosatt utland`() { val saker = listOf( SakInformasjon(sakId = SAK_ID, sakType = YtelseType.GENRL, sakStatus = SakStatus.TIL_BEHANDLING), SakInformasjon(sakId = "1111", sakType = YtelseType.ALDER, sakStatus = SakStatus.TIL_BEHANDLING), SakInformasjon(sakId = "2222", sakType = YtelseType.UFOREP, sakStatus = SakStatus.TIL_BEHANDLING) ) testRunner(FNR_OVER_60, saker, land = "SWE") { assertEquals(PENSJON, it.tema) assertEquals(PENSJON_UTLAND, it.journalfoerendeEnhet) } testRunner(FNR_VOKSEN, saker, land = "SWE") { assertEquals(PENSJON, it.tema) assertEquals(UFORE_UTLAND, it.journalfoerendeEnhet) } testRunner(FNR_BARN, saker, land = "SWE") { assertEquals(PENSJON, it.tema) assertEquals(PENSJON_UTLAND, it.journalfoerendeEnhet) } } @Test fun `1 person i SED fnr finnes, saktype er GENRL`() { val saker = listOf(SakInformasjon(sakId = SAK_ID, sakType = YtelseType.GENRL, sakStatus = SakStatus.TIL_BEHANDLING)) testRunner(FNR_OVER_60, saker) { assertEquals(PENSJON, it.tema) assertEquals(AUTOMATISK_JOURNALFORING, it.journalfoerendeEnhet) } testRunner(FNR_VOKSEN, saker) { assertEquals(PENSJON, it.tema) assertEquals(AUTOMATISK_JOURNALFORING, it.journalfoerendeEnhet) } testRunner(FNR_BARN, saker) { assertEquals(PENSJON, it.tema) assertEquals(AUTOMATISK_JOURNALFORING, it.journalfoerendeEnhet) } } @Test fun `1 person i SED fnr finnes, saktype er GENRL, bosatt utland`() { val saker = listOf(SakInformasjon(sakId = SAK_ID, sakType = YtelseType.GENRL, sakStatus = SakStatus.TIL_BEHANDLING)) testRunner(FNR_OVER_60, saker, land = "SWE") { assertEquals(PENSJON, it.tema) assertEquals(AUTOMATISK_JOURNALFORING, it.journalfoerendeEnhet) } testRunner(FNR_VOKSEN, saker, land = "SWE") { assertEquals(PENSJON, it.tema) assertEquals(AUTOMATISK_JOURNALFORING, it.journalfoerendeEnhet) } testRunner(FNR_BARN, saker, land = "SWE") { assertEquals(PENSJON, it.tema) assertEquals(AUTOMATISK_JOURNALFORING, it.journalfoerendeEnhet) } } } /* ============================ * SCENARIO 4 * ============================ */ @Nested inner class Scenario4 { @Test fun `1 person i SED fnr finnes og saktype er GENRL, med flere sakstyper, person bosatt Norge`() { val saker = listOf( SakInformasjon(SAK_ID, YtelseType.GENRL, SakStatus.TIL_BEHANDLING), SakInformasjon("1240128", YtelseType.BARNEP, SakStatus.TIL_BEHANDLING) ) testRunner(FNR_VOKSEN, saker) { assertEquals(PENSJON, it.tema) assertEquals(UFORE_UTLANDSTILSNITT, it.journalfoerendeEnhet) } testRunner(FNR_OVER_60, saker) { assertEquals(PENSJON, it.tema) assertEquals(NFP_UTLAND_AALESUND, it.journalfoerendeEnhet) } testRunner(FNR_BARN, saker) { assertEquals(PENSJON, it.tema) assertEquals(NFP_UTLAND_AALESUND, it.journalfoerendeEnhet) } } @Test fun `1 person i SED fnr finnes, saktype er GENRL, med flere sakstyper, person bosatt utland`() { val saker = listOf( SakInformasjon(SAK_ID, YtelseType.GENRL, SakStatus.TIL_BEHANDLING), SakInformasjon("124123", YtelseType.BARNEP, SakStatus.TIL_BEHANDLING) ) testRunner(FNR_VOKSEN, saker, land = "SWE") { assertEquals(PENSJON, it.tema) assertEquals(UFORE_UTLAND, it.journalfoerendeEnhet) } testRunner(FNR_OVER_60, saker, land = "SWE") { assertEquals(PENSJON, it.tema) assertEquals(PENSJON_UTLAND, it.journalfoerendeEnhet) } testRunner(FNR_BARN, saker, land = "SWE") { assertEquals(PENSJON, it.tema) assertEquals(PENSJON_UTLAND, it.journalfoerendeEnhet) } } @Test fun `2 personer i SED der fnr finnes, rolle er 02, land er Sverige og bestemsak finner flere saker Så journalføres det manuelt på tema PENSJON og enhet PENSJON_UTLAND`() { val saker = listOf( SakInformasjon(sakId = SAK_ID, sakType = YtelseType.GENRL, sakStatus = SakStatus.TIL_BEHANDLING), SakInformasjon(sakId = "34234123", sakType = YtelseType.ALDER, sakStatus = SakStatus.TIL_BEHANDLING) ) testRunnerFlerePersoner(FNR_OVER_60, FNR_VOKSEN_2, saker, rolle = "02", sakId = SAK_ID, land = "SWE") { assertEquals(PENSJON, it.tema) assertEquals(PENSJON_UTLAND, it.journalfoerendeEnhet) } } @Test fun `2 personer i SED fnr finnes, rolle er 02 og bestemsak finner flere sak Så journalføres manuelt på tema PENSJON og enhet NFP_UTLAND_AALESUND`() { val saker = listOf( SakInformasjon(sakId = "34234234", sakType = YtelseType.ALDER, sakStatus = SakStatus.TIL_BEHANDLING), SakInformasjon(sakId = SAK_ID, sakType = YtelseType.GENRL, sakStatus = SakStatus.TIL_BEHANDLING), SakInformasjon(sakId = "34234123", sakType = YtelseType.UFOREP, sakStatus = SakStatus.AVSLUTTET) ) testRunnerFlerePersoner(FNR_OVER_60, FNR_VOKSEN, saker, sakId = SAK_ID, rolle = "02") { assertEquals(PENSJON, it.tema) assertEquals(NFP_UTLAND_AALESUND, it.journalfoerendeEnhet) } } } /* ============================ * SCENARIO 5 * ============================ */ @Nested inner class Scenario5 { @Test fun `1 person i SED fnr finnes og bestemsak finner sak ALDER Så journalføres automatisk på tema PENSJON`() { val saker = listOf( SakInformasjon(sakId = SAK_ID, sakType = YtelseType.ALDER, sakStatus = SakStatus.TIL_BEHANDLING), SakInformasjon(sakId = "2131123123", sakType = YtelseType.GENRL, sakStatus = SakStatus.LOPENDE) ) testRunner(FNR_OVER_60, saker) { assertEquals(PENSJON, it.tema) assertEquals(AUTOMATISK_JOURNALFORING, it.journalfoerendeEnhet) } } @Test fun `1 person i SED fnr finnes og bestemsak finner sak UFORE Så journalføres automatisk på tema UFORETRYGD`() { val saker = listOf(SakInformasjon(sakId = SAK_ID, sakType = YtelseType.UFOREP, sakStatus = SakStatus.TIL_BEHANDLING)) testRunner(FNR_VOKSEN, saker) { assertEquals(UFORETRYGD, it.tema) assertEquals(AUTOMATISK_JOURNALFORING, it.journalfoerendeEnhet) } testRunner(FNR_OVER_60, saker) { assertEquals(UFORETRYGD, it.tema) assertEquals(AUTOMATISK_JOURNALFORING, it.journalfoerendeEnhet) } testRunner(FNR_BARN, saker) { assertEquals(UFORETRYGD, it.tema) assertEquals(AUTOMATISK_JOURNALFORING, it.journalfoerendeEnhet) } } } /* ============================ * SCENARIO 6 * ============================ */ @Nested inner class Scenario6 { @Test fun `2 personer i SED, har rolle GJENLEV, fnr finnes, mangler sakInformasjon`() { val fnrAnnenPerson = FNR_BARN testRunnerFlerePersoner(FNR_OVER_60, fnrAnnenPerson, saker = emptyList(), rolle = "01", sakId = null) { // forvent tema == PEN og enhet 4303 assertEquals(PENSJON, it.tema) assertEquals(ID_OG_FORDELING, it.journalfoerendeEnhet) assertEquals(fnrAnnenPerson, it.bruker?.id) } // Har SakID, men finner ingen saker testRunnerFlerePersoner(FNR_OVER_60, fnrAnnenPerson, saker = emptyList(), rolle = "01", sakId = SAK_ID) { // forvent tema == PEN og enhet 4303 assertEquals(PENSJON, it.tema) assertEquals(ID_OG_FORDELING, it.journalfoerendeEnhet) assertEquals(fnrAnnenPerson, it.bruker?.id) } } @Test fun `2 personer i SED, har rolle GJENLEV, fnr finnes, bosatt i utland, mangler sakInformasjon`() { testRunnerFlerePersoner( fnr = FNR_OVER_60, fnrAnnenPerson = FNR_BARN, saker = emptyList(), sakId = null, rolle = "01" ) { assertEquals(PENSJON, it.tema) assertEquals(ID_OG_FORDELING, it.journalfoerendeEnhet) } } @Test fun `2 personer i SED, har rolle GJENLEV, fnr finnes, og bestemsak finner sak ALDER`() { val saker = listOf( SakInformasjon(sakId = SAK_ID, sakType = YtelseType.ALDER, sakStatus = SakStatus.AVSLUTTET), SakInformasjon(sakId = "123", sakType = YtelseType.UFOREP, sakStatus = SakStatus.LOPENDE), SakInformasjon(sakId = "34234123", sakType = YtelseType.GENRL, sakStatus = SakStatus.AVSLUTTET) ) val fnrAnnenPerson = FNR_VOKSEN testRunnerFlerePersoner(FNR_OVER_60, fnrAnnenPerson = fnrAnnenPerson, saker = saker, sakId = SAK_ID, rolle = "01") { assertEquals(PENSJON, it.tema) assertEquals(AUTOMATISK_JOURNALFORING, it.journalfoerendeEnhet) assertEquals(fnrAnnenPerson, it.bruker?.id) } } @Test fun `2 personer i SED, har rolle GJENLEV, fnr finnes, og bestemsak finner sak UFØRE`() { val saker = listOf( SakInformasjon(sakId = "34234234", sakType = YtelseType.ALDER, sakStatus = SakStatus.AVSLUTTET), SakInformasjon(sakId = SAK_ID, sakType = YtelseType.UFOREP, sakStatus = SakStatus.LOPENDE), SakInformasjon(sakId = "34234123", sakType = YtelseType.GENRL, sakStatus = SakStatus.AVSLUTTET) ) val fnrAnnenPerson = FNR_VOKSEN testRunnerFlerePersoner(FNR_OVER_60, fnrAnnenPerson = fnrAnnenPerson, saker = saker, sakId = SAK_ID, rolle = "01") { // forvent tema == PEN og enhet 9999 assertEquals(UFORETRYGD, it.tema) assertEquals(AUTOMATISK_JOURNALFORING, it.journalfoerendeEnhet) assertEquals(fnrAnnenPerson, it.bruker?.id) } } } /* ============================ * SCENARIO 7 * ============================ */ @Nested inner class Scenario7 { @Test fun `2 personer i SED, har rolle familiemedlem, fnr finnes og bestemsak finner sak UFØRE Så journalføres automatisk på tema UFORETRYGD`() { val saker = listOf( SakInformasjon(sakId = "34234234", sakType = YtelseType.ALDER, sakStatus = SakStatus.AVSLUTTET), SakInformasjon(sakId = SAK_ID, sakType = YtelseType.UFOREP, sakStatus = SakStatus.LOPENDE), SakInformasjon(sakId = "34234123", sakType = YtelseType.GENRL, sakStatus = SakStatus.AVSLUTTET) ) val forsikredeFnr = FNR_OVER_60 testRunnerFlerePersoner(forsikredeFnr, FNR_VOKSEN, saker, SAK_ID, rolle = "02") { assertEquals(UFORETRYGD, it.tema) assertEquals(AUTOMATISK_JOURNALFORING, it.journalfoerendeEnhet) assertEquals(forsikredeFnr, it.bruker?.id) } } @Test fun `2 personer i SED, har rolle familiemedlem, fnr finnes og bestemsak finner sak ALDER Så journalføres automatisk på tema PENSJON`() { val saker = listOf( SakInformasjon(sakId = SAK_ID, sakType = YtelseType.ALDER, sakStatus = SakStatus.AVSLUTTET), SakInformasjon(sakId = "123123123", sakType = YtelseType.UFOREP, sakStatus = SakStatus.LOPENDE), SakInformasjon(sakId = "34234123", sakType = YtelseType.GENRL, sakStatus = SakStatus.AVSLUTTET) ) val forsikredeFnr = FNR_OVER_60 testRunnerFlerePersoner(forsikredeFnr, FNR_VOKSEN, saker, SAK_ID, rolle = "02") { assertEquals(PENSJON, it.tema) assertEquals(AUTOMATISK_JOURNALFORING, it.journalfoerendeEnhet) assertEquals(forsikredeFnr, it.bruker?.id) } } @Test fun `2 personer i SED, har rolle familiemedlem, fnr finnes og bestemsak finner sak GENRL`() { val saker = listOf( SakInformasjon(sakId = "234123123", sakType = YtelseType.ALDER, sakStatus = SakStatus.AVSLUTTET), SakInformasjon(sakId = "123123123", sakType = YtelseType.UFOREP, sakStatus = SakStatus.LOPENDE), SakInformasjon(sakId = "98989898", sakType = YtelseType.GENRL, sakStatus = SakStatus.LOPENDE) ) val forsikredeFnr = FNR_OVER_60 testRunnerFlerePersoner(forsikredeFnr, FNR_VOKSEN, rolle = "02", sakId = SAK_ID, saker = saker) { assertEquals(PENSJON, it.tema) assertEquals(ID_OG_FORDELING, it.journalfoerendeEnhet) assertEquals(forsikredeFnr, it.bruker?.id) } } } /* ============================ * SCENARIO 8 * ============================ */ @Nested inner class Scenario8 { @Test fun `2 personer i SED, har rolle barn 03 og sak er ALDER`() { val saker = listOf( SakInformasjon(sakId = "34234234", sakType = YtelseType.GENRL, sakStatus = SakStatus.TIL_BEHANDLING), SakInformasjon(sakId = SAK_ID, sakType = YtelseType.ALDER, sakStatus = SakStatus.TIL_BEHANDLING) ) testRunnerFlerePersoner(FNR_VOKSEN, FNR_BARN, saker, rolle = "03") { assertEquals(PENSJON, it.tema) assertEquals(AUTOMATISK_JOURNALFORING, it.journalfoerendeEnhet) } testRunnerFlerePersoner(FNR_VOKSEN, FNR_BARN, saker, rolle = "03", land = "SWE") { assertEquals(PENSJON, it.tema) assertEquals(AUTOMATISK_JOURNALFORING, it.journalfoerendeEnhet) } } @Test fun `2 personer i SED, har rolle barn 03 og sak er UFORE`() { val saker = listOf( SakInformasjon(sakId = "34234234", sakType = YtelseType.GENRL, sakStatus = SakStatus.TIL_BEHANDLING), SakInformasjon(sakId = SAK_ID, sakType = YtelseType.UFOREP, sakStatus = SakStatus.TIL_BEHANDLING) ) testRunnerFlerePersoner(FNR_VOKSEN, FNR_BARN, saker, rolle = "03") { assertEquals(UFORETRYGD, it.tema) assertEquals(AUTOMATISK_JOURNALFORING, it.journalfoerendeEnhet) } testRunnerFlerePersoner(FNR_VOKSEN, FNR_BARN, saker, rolle = "03", land = "SWE") { assertEquals(UFORETRYGD, it.tema) assertEquals(AUTOMATISK_JOURNALFORING, it.journalfoerendeEnhet) } } @Test fun `2 personer i SED, har rolle barn 03 og sak er OMSORG`() { val saker = listOf( SakInformasjon(sakId = "34234234", sakType = YtelseType.GENRL, sakStatus = SakStatus.TIL_BEHANDLING), SakInformasjon(sakId = SAK_ID, sakType = YtelseType.OMSORG, sakStatus = SakStatus.TIL_BEHANDLING) ) testRunnerFlerePersoner(FNR_VOKSEN, FNR_BARN, saker, rolle = "03") { assertEquals(PENSJON, it.tema) assertEquals(AUTOMATISK_JOURNALFORING, it.journalfoerendeEnhet) } testRunnerFlerePersoner(FNR_VOKSEN, FNR_BARN, saker, rolle = "03", land = "SWE") { assertEquals(PENSJON, it.tema) assertEquals(AUTOMATISK_JOURNALFORING, it.journalfoerendeEnhet) } } @Test fun `2 personer i SED, har rolle barn 03 og sak er OMSORG, ignorerer diskresjonskode`() { val saker = listOf( SakInformasjon(sakId = "34234234", sakType = YtelseType.GENRL, sakStatus = SakStatus.TIL_BEHANDLING), SakInformasjon(sakId = SAK_ID, sakType = YtelseType.OMSORG, sakStatus = SakStatus.TIL_BEHANDLING) ) testRunnerFlerePersoner(FNR_VOKSEN, FNR_BARN, saker, rolle = "03", diskresjonkode = Diskresjonskode.SPSF) { assertEquals(PENSJON, it.tema) assertEquals(AUTOMATISK_JOURNALFORING, it.journalfoerendeEnhet) } testRunnerFlerePersoner(FNR_VOKSEN, FNR_BARN, saker, rolle = "03", land = "SWE", diskresjonkode = Diskresjonskode.SPSF) { assertEquals(PENSJON, it.tema) assertEquals(AUTOMATISK_JOURNALFORING, it.journalfoerendeEnhet) } } } /* ============================ * SCENARIO 9 * ============================ */ @Nested inner class Scenario9 { @Test fun `2 personer i SED fnr finnes og rolle er barn, og saktype er BARNEP`() { val saker = listOf( SakInformasjon(sakId = "34234234", sakType = YtelseType.OMSORG, sakStatus = SakStatus.TIL_BEHANDLING), SakInformasjon(sakId = SAK_ID, sakType = YtelseType.BARNEP, sakStatus = SakStatus.TIL_BEHANDLING) ) testRunnerFlerePersoner(FNR_VOKSEN, FNR_BARN, saker, rolle = "03") { assertEquals(PENSJON, it.tema) assertEquals(NFP_UTLAND_AALESUND, it.journalfoerendeEnhet) } testRunnerFlerePersoner(FNR_OVER_60, FNR_BARN, saker, rolle = "03") { assertEquals(PENSJON, it.tema) assertEquals(NFP_UTLAND_AALESUND, it.journalfoerendeEnhet) } testRunnerFlerePersoner(FNR_VOKSEN, FNR_BARN, saker, rolle = "03", land = "SWE") { assertEquals(PENSJON, it.tema) assertEquals(PENSJON_UTLAND, it.journalfoerendeEnhet) } testRunnerFlerePersoner(FNR_OVER_60, FNR_BARN, saker, rolle = "03", land = "SWE") { assertEquals(PENSJON, it.tema) assertEquals(PENSJON_UTLAND, it.journalfoerendeEnhet) } } @Test fun `2 personer i SED fnr finnes og rolle er barn, og saktype er GJENLEV`() { val saker = listOf( SakInformasjon(sakId = "34234234", sakType = YtelseType.ALDER, sakStatus = SakStatus.TIL_BEHANDLING), SakInformasjon(sakId = SAK_ID, sakType = YtelseType.GJENLEV, sakStatus = SakStatus.TIL_BEHANDLING) ) testRunnerFlerePersoner(FNR_VOKSEN, FNR_BARN, saker, rolle = "03") { assertEquals(PENSJON, it.tema) assertEquals(NFP_UTLAND_AALESUND, it.journalfoerendeEnhet) } testRunnerFlerePersoner(FNR_OVER_60, FNR_BARN, saker, rolle = "03") { assertEquals(PENSJON, it.tema) assertEquals(NFP_UTLAND_AALESUND, it.journalfoerendeEnhet) } testRunnerFlerePersoner(FNR_VOKSEN, FNR_BARN, saker, rolle = "03", land = "SWE") { assertEquals(PENSJON, it.tema) assertEquals(PENSJON_UTLAND, it.journalfoerendeEnhet) } testRunnerFlerePersoner(FNR_OVER_60, FNR_BARN, saker, rolle = "03", land = "SWE") { assertEquals(PENSJON, it.tema) assertEquals(PENSJON_UTLAND, it.journalfoerendeEnhet) } } @Test fun `2 personer i SED fnr finnes og rolle er barn, og saktype er GJENLEV, ignorerer Diskresjonskode 6`() { val saker = listOf( SakInformasjon(sakId = "34234234", sakType = YtelseType.ALDER, sakStatus = SakStatus.TIL_BEHANDLING), SakInformasjon(sakId = SAK_ID, sakType = YtelseType.GJENLEV, sakStatus = SakStatus.TIL_BEHANDLING) ) testRunnerFlerePersoner(FNR_VOKSEN, FNR_BARN, saker, rolle = "03", diskresjonkode = Diskresjonskode.SPSF) { assertEquals(PENSJON, it.tema) assertEquals(NFP_UTLAND_AALESUND, it.journalfoerendeEnhet) } testRunnerFlerePersoner(FNR_VOKSEN, FNR_BARN, saker, rolle = "03", land = "SWE", diskresjonkode = Diskresjonskode.SPSF) { assertEquals(PENSJON, it.tema) assertEquals(PENSJON_UTLAND, it.journalfoerendeEnhet) } } @Test fun `2 personer i SED fnr finnes og rolle er barn, og saktype er GJENLEV, ignorerer Diskresjonskode`() { val saker = listOf( SakInformasjon(sakId = "34234234", sakType = YtelseType.ALDER, sakStatus = SakStatus.TIL_BEHANDLING), SakInformasjon(sakId = SAK_ID, sakType = YtelseType.GJENLEV, sakStatus = SakStatus.TIL_BEHANDLING) ) testRunnerFlerePersoner(FNR_VOKSEN, FNR_BARN, saker, rolle = "03", diskresjonkode = Diskresjonskode.SPFO) { assertEquals(PENSJON, it.tema) assertEquals(NFP_UTLAND_AALESUND, it.journalfoerendeEnhet) } testRunnerFlerePersoner(FNR_VOKSEN, FNR_BARN, saker, rolle = "03", land = "SWE", diskresjonkode = Diskresjonskode.SPFO) { assertEquals(PENSJON, it.tema) assertEquals(PENSJON_UTLAND, it.journalfoerendeEnhet) } testRunnerFlerePersoner(FNR_VOKSEN, FNR_BARN, saker, rolle = "03", diskresjonkode = Diskresjonskode.SPSF) { assertEquals(PENSJON, it.tema) assertEquals(NFP_UTLAND_AALESUND, it.journalfoerendeEnhet) } testRunnerFlerePersoner(FNR_VOKSEN, FNR_BARN, saker, rolle = "03", land = "SWE", diskresjonkode = Diskresjonskode.SPSF) { assertEquals(PENSJON, it.tema) assertEquals(PENSJON_UTLAND, it.journalfoerendeEnhet) } } @Test fun `2 personer i SED fnr finnes og rolle er barn, og saktype mangler`() { testRunnerFlerePersoner(FNR_VOKSEN, FNR_BARN, rolle = "03") { assertEquals(PENSJON, it.tema) assertEquals(ID_OG_FORDELING, it.journalfoerendeEnhet) } testRunnerFlerePersoner(FNR_OVER_60, FNR_BARN, rolle = "03") { assertEquals(PENSJON, it.tema) assertEquals(ID_OG_FORDELING, it.journalfoerendeEnhet) } testRunnerFlerePersoner(FNR_VOKSEN, FNR_BARN, rolle = "03", land = "SWE") { assertEquals(PENSJON, it.tema) assertEquals(ID_OG_FORDELING, it.journalfoerendeEnhet) } testRunnerFlerePersoner(FNR_OVER_60, FNR_BARN, rolle = "03", land = "SWE") { assertEquals(PENSJON, it.tema) assertEquals(ID_OG_FORDELING, it.journalfoerendeEnhet) } } } }
0
Kotlin
0
0
ef973a5cc34f32fbd355fd86f5c6f318496d1d64
28,660
eessi-pensjon-journalforing
MIT License
app/src/main/java/com/fruitable/Fruitable/MainActivity.kt
ApptiveDev
535,231,127
false
{"Kotlin": 234453}
package com.fruitable.Fruitable import androidx.appcompat.app.AppCompatActivity import android.os.Bundle import android.view.Window import android.view.WindowManager import androidx.activity.compose.setContent import androidx.compose.animation.ExperimentalAnimationApi import androidx.compose.material.MaterialTheme import androidx.compose.material.Surface import androidx.navigation.compose.NavHost import androidx.navigation.compose.composable import androidx.navigation.compose.rememberNavController import com.fruitable.Fruitable.app.presentation.navigation.Screen import com.fruitable.Fruitable.app.presentation.navigation.fruitableGraph import com.fruitable.Fruitable.ui.theme.FRUITABLETheme import dagger.hilt.android.AndroidEntryPoint @AndroidEntryPoint class MainActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { requestWindowFeature(Window.FEATURE_NO_TITLE); this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN); super.onCreate(savedInstanceState) setContent { FruitableApp() } } }
0
Kotlin
3
3
70217aa3ebcf0a278fe2cb9fa9791e2621fd8f4f
1,162
apptive-17th-fruitable-frontend
MIT License
app/src/main/java/com/example/myapplication/GLES3JNILib.kt
s094392
365,131,098
false
{"C++": 6271103, "C": 723497, "Kotlin": 5838, "CMake": 2706, "Objective-C": 1343}
/* * Copyright 2013 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.example.myapplication // Wrapper for native library object GLES3JNILib { @JvmStatic external fun init(number: Int) @JvmStatic external fun resize(width: Int, height: Int) @JvmStatic external fun step(use_vuda: Boolean) init { System.loadLibrary("gles3jni") } }
0
C++
0
0
28c10d6819296bb74d6de3968638e9cb03ef8bde
930
Android-particle-collision
MIT License
src/commonMain/kotlin/com/ianrumac/redukks/actions/Dispatcher.kt
ianrumac
622,615,704
false
null
package com.ianrumac.redukks.actions import com.ianrumac.redukks.ActionDSL /** * A [Dispatcher] is a contract that allows for the dispatching of actions, implemented by the likes * of [ReduxViewModel] and [DefaultActionDispatcher]. */ interface Dispatcher<Actions> { @ActionDSL fun dispatch(value: Actions) }
0
Kotlin
1
27
b8e2895bd712954f5e48da332c4cf0b5e20e14e3
316
redukks
MIT License
src/test/kotlin/com/adrielm/aoc2020/solutions/day12/Day12Test.kt
Adriel-M
318,860,784
false
null
package com.adrielm.aoc2020.solutions.day12 import com.adrielm.aoc2020.common.FileUtils import com.adrielm.aoc2020.test_utils.BaseTest import org.assertj.core.api.Assertions.assertThat import org.koin.test.inject class Day12Test : BaseTest() { private val day12: Day12 by inject() private val instructionParser: InstructionParser by inject() override fun `example problem 1`() { val example = """ F10 N3 F7 R90 F11 """.trimIndent() val instructions = example.lines().map { instructionParser.parse(it) } assertThat(day12.solveProblem1(instructions)).isEqualTo(25) } override fun `input problem 1`() { val instructions = FileUtils.fileToList("day12.txt") { instructionParser.parse(it) } assertThat(day12.solveProblem1(instructions)).isEqualTo(904) } override fun `example problem 2`() { val example = """ F10 N3 F7 R90 F11 """.trimIndent() val instructions = example.lines().map { instructionParser.parse(it) } assertThat(day12.solveProblem2(instructions)).isEqualTo(286) } override fun `input problem 2`() { val instructions = FileUtils.fileToList("day12.txt") { instructionParser.parse(it) } assertThat(day12.solveProblem2(instructions)).isEqualTo(18747) } }
0
Kotlin
0
0
8984378d0297f7bc75c5e41a80424d091ac08ad0
1,453
advent-of-code-2020
MIT License
app/src/main/java/ru/ilyasekunov/officeapp/navigation/IdeaAuthorScreenNavigation.kt
IlyaSekunov
744,587,168
false
{"Kotlin": 649242}
package ru.ilyasekunov.officeapp.navigation import androidx.compose.runtime.Composable import androidx.compose.runtime.LaunchedEffect import androidx.hilt.navigation.compose.hiltViewModel import androidx.navigation.NavController import androidx.navigation.NavGraphBuilder import androidx.navigation.NavOptions import androidx.navigation.compose.composable import androidx.paging.compose.collectAsLazyPagingItems import kotlinx.coroutines.launch import ru.ilyasekunov.officeapp.ui.ideaauthor.IdeaAuthorScreen import ru.ilyasekunov.officeapp.ui.ideaauthor.IdeaAuthorViewModel fun NavGraphBuilder.ideaAuthorScreen( navigateToIdeaDetailsScreen: (Long) -> Unit, navigateToHomeScreen: () -> Unit, navigateToFavouriteScreen: () -> Unit, navigateToMyOfficeScreen: () -> Unit, navigateToProfileScreen: () -> Unit, navigateBack: () -> Unit ) { composable( route = Screen.IdeaAuthor.route, arguments = Screen.IdeaAuthor.arguments ) { backStackEntry -> val authorId = backStackEntry.arguments!!.getLong("authorId") val viewModel = setUpIdeaAuthorViewModel(authorId) val ideas = viewModel.authorIdeasUiState.ideas.collectAsLazyPagingItems() IdeaAuthorScreen( ideaAuthorUiState = viewModel.ideaAuthorUiState, ideas = ideas, onRetryLoadData = { viewModel.loadIdeaAuthorById(authorId) ideas.refresh() }, onPullToRefresh = { launch { launch { viewModel.refreshIdeaAuthorById(authorId) } launch { ideas.refresh() } } }, onIdeaLikeClick = viewModel::updateLike, onIdeaDislikeClick = viewModel::updateDislike, navigateToIdeaDetailsScreen = navigateToIdeaDetailsScreen, navigateToHomeScreen = navigateToHomeScreen, navigateToFavouriteScreen = navigateToFavouriteScreen, navigateToMyOfficeScreen = navigateToMyOfficeScreen, navigateToProfileScreen = navigateToProfileScreen, navigateBack = navigateBack ) } } fun NavController.navigateToIdeaAuthorScreen( authorId: Long, navOptions: NavOptions? = null ) { val destination = Screen.IdeaAuthor.route.replace("{authorId}", authorId.toString()) navigate(destination, navOptions) } @Composable private fun setUpIdeaAuthorViewModel(authorId: Long): IdeaAuthorViewModel { val viewModel = hiltViewModel<IdeaAuthorViewModel>() LaunchedEffect(Unit) { viewModel.loadIdeaAuthorById(authorId) viewModel.loadIdeasByAuthorId(authorId) } return viewModel }
0
Kotlin
0
0
4568ac889ce6054f2384585c47b2f203634b3ced
2,768
office-app
Apache License 2.0
travelmaker_android/app/src/main/java/com/gumibom/travelmaker/data/repository/myPage/MyPageRepository.kt
Leewoogun
767,396,774
false
{"Kotlin": 481004, "Java": 174550, "HTML": 4622, "Dockerfile": 516}
package com.gumibom.travelmaker.data.repository.myPage import com.gumibom.travelmaker.data.dto.response.UserResponseDTO import retrofit2.Response interface MyPageRepository { suspend fun getMyUserInfo() : Response<UserResponseDTO> suspend fun deleteMyInfo() }
0
Kotlin
0
0
04e4d7a7a2b613db4a4c9181d015b23b58ea7f70
269
TravelMaker
Apache License 1.1