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
examples/weather/forecast/forecastWeather/main.kt
GWT-M3O-TEST
485,009,715
false
null
package examples.weather.forecast import com.m3o.m3okotlin.M3O import com.m3o.m3okotlin.services.weather suspend fun main() { M3O.initialize(System.getenv("M3O_API_TOKEN")) val req = WeatherForecastRequest(Days = 2, Location = "London",) try { val response = WeatherServ.forecast(req) println(response) } catch (e: Exception) { println(e) } }
1
Kotlin
1
0
54158b584ba47bd7323a484804dcd78c55ef7f69
378
m3o-kotlin
Apache License 2.0
src/main/kotlin/io/github/controleagenda/controller/SubSegmentController.kt
mpontoc
509,843,324
false
null
package io.github.controleagenda.controller import io.github.controleagenda.model.SubSegment import io.github.controleagenda.model.dto.SubSegmentDTO import io.github.controleagenda.repository.SubSegmentRepository import io.github.controleagenda.services.SubSegmentService import io.github.controleagenda.util.Util import org.springframework.beans.factory.annotation.Autowired import org.springframework.http.HttpStatus import org.springframework.http.ResponseEntity import org.springframework.web.bind.annotation.* import org.springframework.web.util.UriComponentsBuilder import javax.validation.Valid @RestController @RequestMapping("/user/{userId}/segmentos/{segmentId}/sub-segmentos") class SubSegmentController { @Autowired lateinit var subSegmentService: SubSegmentService @Autowired lateinit var subSegmentRepository: SubSegmentRepository val util = Util() @PostMapping fun createSubSegment( @PathVariable userId: Long, @PathVariable segmentId: Long, @RequestBody @Valid subSegment: SubSegment, uriBuilder: UriComponentsBuilder ): ResponseEntity<*> { val idSequence = util.idSequenceSubSegment(subSegmentRepository) subSegment.id = idSequence val response = subSegmentService.createSubSegment(userId, segmentId, subSegment) val uri = uriBuilder.path("segmentos/${idSequence}/").build().toUri() return ResponseEntity.created(uri).body(response) } @PutMapping fun editSubSegment( @PathVariable userId: Long, @PathVariable segmentId: Long, @RequestBody subSegment: SubSegment ): ResponseEntity<SubSegmentDTO> { return ResponseEntity.ok(subSegmentService.updateSubSegment(userId, subSegment)) } @DeleteMapping("/{subSegmentId}") @ResponseStatus(HttpStatus.NO_CONTENT) fun deleteSubSegment( @PathVariable userId: Long, @PathVariable segmentId: Long, @PathVariable subSegmentId: Long, ) { subSegmentService.deleteSubSegment(userId, segmentId, subSegmentId) } }
0
Kotlin
0
0
ab4a24dcf85f46eeeb5bcb86a13458f580149d71
2,078
controle-agenda
MIT License
compose/snippets/src/main/java/com/example/compose/snippets/touchinput/Interactions.kt
android
138,043,025
false
{"Kotlin": 1093210, "Java": 5240}
/* * Copyright 2024 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.example.compose.snippets.touchinput import androidx.compose.animation.AnimatedVisibility import androidx.compose.animation.core.Animatable import androidx.compose.animation.core.animateFloatAsState import androidx.compose.animation.core.spring import androidx.compose.animation.core.tween import androidx.compose.foundation.BorderStroke import androidx.compose.foundation.IndicationNodeFactory import androidx.compose.foundation.background import androidx.compose.foundation.border import androidx.compose.foundation.clickable import androidx.compose.foundation.focusable import androidx.compose.foundation.hoverable import androidx.compose.foundation.interaction.DragInteraction import androidx.compose.foundation.interaction.Interaction import androidx.compose.foundation.interaction.InteractionSource import androidx.compose.foundation.interaction.MutableInteractionSource import androidx.compose.foundation.interaction.PressInteraction import androidx.compose.foundation.interaction.collectIsPressedAsState import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.PaddingValues import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.RowScope import androidx.compose.foundation.layout.Spacer import androidx.compose.foundation.layout.defaultMinSize import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.size import androidx.compose.foundation.shape.CircleShape import androidx.compose.material.icons.Icons import androidx.compose.material.icons.filled.ShoppingCart import androidx.compose.material.ripple import androidx.compose.material3.Button import androidx.compose.material3.ButtonColors import androidx.compose.material3.ButtonDefaults import androidx.compose.material3.ButtonElevation import androidx.compose.material3.Icon import androidx.compose.material3.MaterialTheme import androidx.compose.material3.Text import androidx.compose.runtime.Composable import androidx.compose.runtime.LaunchedEffect import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateListOf import androidx.compose.runtime.remember import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.draw.scale import androidx.compose.ui.geometry.Offset import androidx.compose.ui.geometry.Size import androidx.compose.ui.geometry.center import androidx.compose.ui.graphics.Brush import androidx.compose.ui.graphics.Brush.Companion.linearGradient import androidx.compose.ui.graphics.Color import androidx.compose.ui.graphics.Shape import androidx.compose.ui.graphics.SolidColor import androidx.compose.ui.graphics.drawOutline import androidx.compose.ui.graphics.drawscope.ContentDrawScope import androidx.compose.ui.graphics.drawscope.Stroke import androidx.compose.ui.graphics.drawscope.scale import androidx.compose.ui.node.DelegatableNode import androidx.compose.ui.node.DrawModifierNode import androidx.compose.ui.unit.Dp import androidx.compose.ui.unit.dp import kotlin.math.abs import kotlin.math.sign import kotlinx.coroutines.Job import kotlinx.coroutines.flow.collectLatest import kotlinx.coroutines.launch @Composable private fun InteractionsSnippet1() { // [START android_compose_interactions_interaction_state] val interactionSource = remember { MutableInteractionSource() } val isPressed by interactionSource.collectIsPressedAsState() Button( onClick = { /* do something */ }, interactionSource = interactionSource ) { Text(if (isPressed) "Pressed!" else "Not pressed") } // [END android_compose_interactions_interaction_state] } // [START android_compose_interactions_interaction_source_input] fun Modifier.focusBorder(interactionSource: InteractionSource): Modifier { // [START_EXCLUDE] return this // [END_EXCLUDE] } // [END android_compose_interactions_interaction_source_input] // [START android_compose_interactions_mutable_interaction_source_input] fun Modifier.hover(interactionSource: MutableInteractionSource, enabled: Boolean): Modifier { // [START_EXCLUDE] return this // [END_EXCLUDE] } // [END android_compose_interactions_mutable_interaction_source_input] // [START android_compose_interactions_high_level_component] @Composable fun Button( onClick: () -> Unit, modifier: Modifier = Modifier, enabled: Boolean = true, // exposes MutableInteractionSource as a parameter interactionSource: MutableInteractionSource? = null, elevation: ButtonElevation? = ButtonDefaults.elevatedButtonElevation(), shape: Shape = MaterialTheme.shapes.small, border: BorderStroke? = null, colors: ButtonColors = ButtonDefaults.buttonColors(), contentPadding: PaddingValues = ButtonDefaults.ContentPadding, content: @Composable RowScope.() -> Unit ) { /* content() */ } // [END android_compose_interactions_high_level_component] @Composable fun HoverExample() { // [START android_compose_interactions_hoverable] // This InteractionSource will emit hover interactions val interactionSource = remember { MutableInteractionSource() } Box( Modifier .size(100.dp) .hoverable(interactionSource = interactionSource), contentAlignment = Alignment.Center ) { Text("Hello!") } // [END android_compose_interactions_hoverable] } @Composable fun FocusableExample() { // [START android_compose_interactions_focusable] // This InteractionSource will emit hover and focus interactions val interactionSource = remember { MutableInteractionSource() } Box( Modifier .size(100.dp) .hoverable(interactionSource = interactionSource) .focusable(interactionSource = interactionSource), contentAlignment = Alignment.Center ) { Text("Hello!") } // [END android_compose_interactions_focusable] } @Composable fun ClickableExample() { // [START android_compose_interactions_clickable] // This InteractionSource will emit hover, focus, and press interactions val interactionSource = remember { MutableInteractionSource() } Box( Modifier .size(100.dp) .clickable( onClick = {}, interactionSource = interactionSource, // Also show a ripple effect indication = ripple() ), contentAlignment = Alignment.Center ) { Text("Hello!") } // [END android_compose_interactions_clickable] } @Composable private fun InteractionsSnippet2() { // [START android_compose_interactions_flow_apis] val interactionSource = remember { MutableInteractionSource() } val interactions = remember { mutableStateListOf<Interaction>() } LaunchedEffect(interactionSource) { interactionSource.interactions.collect { interaction -> when (interaction) { is PressInteraction.Press -> { interactions.add(interaction) } is DragInteraction.Start -> { interactions.add(interaction) } } } } // [END android_compose_interactions_flow_apis] } @Composable private fun InteractionsSnippet3() { // [START android_compose_interactions_add_remove] val interactionSource = remember { MutableInteractionSource() } val interactions = remember { mutableStateListOf<Interaction>() } LaunchedEffect(interactionSource) { interactionSource.interactions.collect { interaction -> when (interaction) { is PressInteraction.Press -> { interactions.add(interaction) } is PressInteraction.Release -> { interactions.remove(interaction.press) } is PressInteraction.Cancel -> { interactions.remove(interaction.press) } is DragInteraction.Start -> { interactions.add(interaction) } is DragInteraction.Stop -> { interactions.remove(interaction.start) } is DragInteraction.Cancel -> { interactions.remove(interaction.start) } } } } // [END android_compose_interactions_add_remove] // [START android_compose_interactions_is_pressed_or_dragged] val isPressedOrDragged = interactions.isNotEmpty() // [END android_compose_interactions_is_pressed_or_dragged] // [START android_compose_interactions_last] val lastInteraction = when (interactions.lastOrNull()) { is DragInteraction.Start -> "Dragged" is PressInteraction.Press -> "Pressed" else -> "No state" } // [END android_compose_interactions_last] } @Composable private fun InteractionsSnippet4() { // [START android_compose_interactions_batched] val interactionSource = remember { MutableInteractionSource() } val isPressed by interactionSource.collectIsPressedAsState() Button(onClick = { /* do something */ }, interactionSource = interactionSource) { Text(if (isPressed) "Pressed!" else "Not pressed") } // [END android_compose_interactions_batched] } // [START android_compose_interactions_press_icon_button] @Composable fun PressIconButton( onClick: () -> Unit, icon: @Composable () -> Unit, text: @Composable () -> Unit, modifier: Modifier = Modifier, interactionSource: MutableInteractionSource? = null ) { val isPressed = interactionSource?.collectIsPressedAsState()?.value ?: false Button( onClick = onClick, modifier = modifier, interactionSource = interactionSource ) { AnimatedVisibility(visible = isPressed) { if (isPressed) { Row { icon() Spacer(Modifier.size(ButtonDefaults.IconSpacing)) } } } text() } } // [END android_compose_interactions_press_icon_button] @Composable fun PressIconButtonUsage() { // [START android_compose_interactions_press_icon_button_usage] PressIconButton( onClick = {}, icon = { Icon(Icons.Filled.ShoppingCart, contentDescription = null) }, text = { Text("Add to cart") } ) // [END android_compose_interactions_press_icon_button_usage] } @Composable fun InteractionsSnippet5() { // [START android_compose_interactions_indication] val interactionSource = remember { MutableInteractionSource() } val isPressed by interactionSource.collectIsPressedAsState() val scale by animateFloatAsState(targetValue = if (isPressed) 0.9f else 1f, label = "scale") Button( modifier = Modifier.scale(scale), onClick = { }, interactionSource = interactionSource ) { Text(if (isPressed) "Pressed!" else "Not pressed") } // [END android_compose_interactions_indication] } // [START android_compose_interactions_scale_node] private class ScaleNode(private val interactionSource: InteractionSource) : Modifier.Node(), DrawModifierNode { var currentPressPosition: Offset = Offset.Zero val animatedScalePercent = Animatable(1f) private suspend fun animateToPressed(pressPosition: Offset) { currentPressPosition = pressPosition animatedScalePercent.animateTo(0.9f, spring()) } private suspend fun animateToResting() { animatedScalePercent.animateTo(1f, spring()) } override fun onAttach() { coroutineScope.launch { interactionSource.interactions.collectLatest { interaction -> when (interaction) { is PressInteraction.Press -> animateToPressed(interaction.pressPosition) is PressInteraction.Release -> animateToResting() is PressInteraction.Cancel -> animateToResting() } } } } override fun ContentDrawScope.draw() { scale( scale = animatedScalePercent.value, pivot = currentPressPosition ) { this@draw.drawContent() } } } // [END android_compose_interactions_scale_node] // [START android_compose_interactions_scale_node_factory] object ScaleIndication : IndicationNodeFactory { override fun create(interactionSource: InteractionSource): DelegatableNode { return ScaleNode(interactionSource) } override fun equals(other: Any?): Boolean = other === ScaleIndication override fun hashCode() = 100 } // [END android_compose_interactions_scale_node_factory] @Composable fun InteractionSnippets6() { // [START android_compose_interactions_button_indication] Box( modifier = Modifier .size(100.dp) .clickable( onClick = {}, indication = ScaleIndication, interactionSource = null ) .background(Color.Blue), contentAlignment = Alignment.Center ) { Text("Hello!", color = Color.White) } // [END android_compose_interactions_button_indication] } // [START android_compose_interactions_scale_button] @Composable fun ScaleButton( onClick: () -> Unit, modifier: Modifier = Modifier, enabled: Boolean = true, interactionSource: MutableInteractionSource? = null, shape: Shape = CircleShape, content: @Composable RowScope.() -> Unit ) { Row( modifier = modifier .defaultMinSize(minWidth = 76.dp, minHeight = 48.dp) .clickable( enabled = enabled, indication = ScaleIndication, interactionSource = interactionSource, onClick = onClick ) .border(width = 2.dp, color = Color.Blue, shape = shape) .padding(horizontal = 16.dp, vertical = 8.dp), horizontalArrangement = Arrangement.Center, verticalAlignment = Alignment.CenterVertically, content = content ) } // [END android_compose_interactions_scale_button] @Composable fun ScaleButtonExample() { // [START android_compose_interactions_scale_button_example] ScaleButton(onClick = {}) { Icon(Icons.Filled.ShoppingCart, "") Spacer(Modifier.padding(10.dp)) Text(text = "Add to cart!") } // [END android_compose_interactions_scale_button_example] } // [START android_compose_interactions_neon_node] private class NeonNode( private val shape: Shape, private val borderWidth: Dp, private val interactionSource: InteractionSource ) : Modifier.Node(), DrawModifierNode { var currentPressPosition: Offset = Offset.Zero val animatedProgress = Animatable(0f) val animatedPressAlpha = Animatable(1f) var pressedAnimation: Job? = null var restingAnimation: Job? = null private suspend fun animateToPressed(pressPosition: Offset) { // Finish any existing animations, in case of a new press while we are still showing // an animation for a previous one restingAnimation?.cancel() pressedAnimation?.cancel() pressedAnimation = coroutineScope.launch { currentPressPosition = pressPosition animatedPressAlpha.snapTo(1f) animatedProgress.snapTo(0f) animatedProgress.animateTo(1f, tween(450)) } } private fun animateToResting() { restingAnimation = coroutineScope.launch { // Wait for the existing press animation to finish if it is still ongoing pressedAnimation?.join() animatedPressAlpha.animateTo(0f, tween(250)) animatedProgress.snapTo(0f) } } override fun onAttach() { coroutineScope.launch { interactionSource.interactions.collect { interaction -> when (interaction) { is PressInteraction.Press -> animateToPressed(interaction.pressPosition) is PressInteraction.Release -> animateToResting() is PressInteraction.Cancel -> animateToResting() } } } } override fun ContentDrawScope.draw() { val (startPosition, endPosition) = calculateGradientStartAndEndFromPressPosition( currentPressPosition, size ) val brush = animateBrush( startPosition = startPosition, endPosition = endPosition, progress = animatedProgress.value ) val alpha = animatedPressAlpha.value drawContent() val outline = shape.createOutline(size, layoutDirection, this) // Draw overlay on top of content drawOutline( outline = outline, brush = brush, alpha = alpha * 0.1f ) // Draw border on top of overlay drawOutline( outline = outline, brush = brush, alpha = alpha, style = Stroke(width = borderWidth.toPx()) ) } /** * Calculates a gradient start / end where start is the point on the bounding rectangle of * size [size] that intercepts with the line drawn from the center to [pressPosition], * and end is the intercept on the opposite end of that line. */ private fun calculateGradientStartAndEndFromPressPosition( pressPosition: Offset, size: Size ): Pair<Offset, Offset> { // Convert to offset from the center val offset = pressPosition - size.center // y = mx + c, c is 0, so just test for x and y to see where the intercept is val gradient = offset.y / offset.x // We are starting from the center, so halve the width and height - convert the sign // to match the offset val width = (size.width / 2f) * sign(offset.x) val height = (size.height / 2f) * sign(offset.y) val x = height / gradient val y = gradient * width // Figure out which intercept lies within bounds val intercept = if (abs(y) <= abs(height)) { Offset(width, y) } else { Offset(x, height) } // Convert back to offsets from 0,0 val start = intercept + size.center val end = Offset(size.width - start.x, size.height - start.y) return start to end } private fun animateBrush( startPosition: Offset, endPosition: Offset, progress: Float ): Brush { if (progress == 0f) return TransparentBrush // This is *expensive* - we are doing a lot of allocations on each animation frame. To // recreate a similar effect in a performant way, it would be better to create one large // gradient and translate it on each frame, instead of creating a whole new gradient // and shader. The current approach will be janky! val colorStops = buildList { when { progress < 1 / 6f -> { val adjustedProgress = progress * 6f add(0f to Blue) add(adjustedProgress to Color.Transparent) } progress < 2 / 6f -> { val adjustedProgress = (progress - 1 / 6f) * 6f add(0f to Purple) add(adjustedProgress * MaxBlueStop to Blue) add(adjustedProgress to Blue) add(1f to Color.Transparent) } progress < 3 / 6f -> { val adjustedProgress = (progress - 2 / 6f) * 6f add(0f to Pink) add(adjustedProgress * MaxPurpleStop to Purple) add(MaxBlueStop to Blue) add(1f to Blue) } progress < 4 / 6f -> { val adjustedProgress = (progress - 3 / 6f) * 6f add(0f to Orange) add(adjustedProgress * MaxPinkStop to Pink) add(MaxPurpleStop to Purple) add(MaxBlueStop to Blue) add(1f to Blue) } progress < 5 / 6f -> { val adjustedProgress = (progress - 4 / 6f) * 6f add(0f to Yellow) add(adjustedProgress * MaxOrangeStop to Orange) add(MaxPinkStop to Pink) add(MaxPurpleStop to Purple) add(MaxBlueStop to Blue) add(1f to Blue) } else -> { val adjustedProgress = (progress - 5 / 6f) * 6f add(0f to Yellow) add(adjustedProgress * MaxYellowStop to Yellow) add(MaxOrangeStop to Orange) add(MaxPinkStop to Pink) add(MaxPurpleStop to Purple) add(MaxBlueStop to Blue) add(1f to Blue) } } } return linearGradient( colorStops = colorStops.toTypedArray(), start = startPosition, end = endPosition ) } companion object { val TransparentBrush = SolidColor(Color.Transparent) val Blue = Color(0xFF30C0D8) val Purple = Color(0xFF7848A8) val Pink = Color(0xFFF03078) val Orange = Color(0xFFF07800) val Yellow = Color(0xFFF0D800) const val MaxYellowStop = 0.16f const val MaxOrangeStop = 0.33f const val MaxPinkStop = 0.5f const val MaxPurpleStop = 0.67f const val MaxBlueStop = 0.83f } } // [END android_compose_interactions_neon_node] // [START android_compose_interactions_neon_indication] data class NeonIndication(private val shape: Shape, private val borderWidth: Dp) : IndicationNodeFactory { override fun create(interactionSource: InteractionSource): DelegatableNode { return NeonNode( shape, // Double the border size for a stronger press effect borderWidth * 2, interactionSource ) } } // [END android_compose_interactions_neon_indication]
14
Kotlin
169
666
514653c318c747c557f70e32aad2cc7051d44115
22,970
snippets
Apache License 2.0
app/src/main/java/me/rosuh/easywatermark/ui/adapter/PhotoListPreviewAdapter.kt
rosuH
281,094,148
false
null
package me.rosuh.easywatermark.ui.adapter import android.annotation.SuppressLint import android.content.Context import android.view.ViewGroup import android.widget.ImageView import androidx.core.view.isVisible import androidx.recyclerview.widget.AsyncListDiffer import androidx.recyclerview.widget.DiffUtil import androidx.recyclerview.widget.RecyclerView import com.bumptech.glide.Glide import me.rosuh.easywatermark.MyApp import me.rosuh.easywatermark.data.model.ImageInfo import me.rosuh.easywatermark.ui.base.BaseViewHolder import me.rosuh.easywatermark.ui.widget.PhotoPreviewItem import me.rosuh.easywatermark.utils.VibrateHelper class PhotoListPreviewAdapter( private val context: Context ) : RecyclerView.Adapter<PhotoListPreviewAdapter.ImageHolder>() { val data: List<ImageInfo> get() = differ.currentList private val differ: AsyncListDiffer<ImageInfo> by lazy { AsyncListDiffer(this, differCallback) } private val differCallback: DiffUtil.ItemCallback<ImageInfo> by lazy { object : DiffUtil.ItemCallback<ImageInfo>() { override fun areItemsTheSame(oldItem: ImageInfo, newItem: ImageInfo): Boolean { return oldItem == newItem } override fun areContentsTheSame(oldItem: ImageInfo, newItem: ImageInfo): Boolean { return oldItem == newItem } } } @SuppressLint("ClickableViewAccessibility") override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ImageHolder { val rootView = PhotoPreviewItem(context) return ImageHolder(rootView) } override fun onBindViewHolder( holder: ImageHolder, position: Int, payloads: MutableList<Any> ) { super.onBindViewHolder(holder, position, payloads) if (payloads.isNullOrEmpty()) { onBindViewHolder(holder, position) return } processUI(holder, position, isPayLoad = true) } override fun onBindViewHolder(holder: ImageHolder, position: Int) { processUI(holder, position) } private fun processUI(holder: ImageHolder, position: Int, isPayLoad: Boolean = false) { if (position < 0 || position >= differ.currentList.size) { return } (holder.itemView as PhotoPreviewItem).apply { onRemove { VibrateHelper.get().doVibrate(holder.itemView) remove(holder.bindingAdapterPosition) } onRemovePreview { VibrateHelper.get().doVibrate(holder.itemView) } } with(differ.currentList[position]) { Glide.with(MyApp.instance) .load(this.uri) .into(holder.ivIcon) when { isPayLoad -> { holder.ivIcon.animate().alpha(1f).setDuration(100).start() holder.ivRemove .animate() .alpha(0f) .setDuration(100) .withEndAction { holder.ivRemove.isVisible = false } .start() } else -> { holder.ivIcon.apply { isVisible = true alpha = 1f } holder.ivRemove.apply { isVisible = false alpha = 0f } } } } } override fun getItemCount(): Int { return differ.currentList.count() } override fun getItemId(position: Int): Long { return position.toLong() } fun submitList(imageInfoList: List<ImageInfo>, block: () -> Unit) { differ.submitList(imageInfoList) { block.invoke() } } fun getItem(pos: Int): ImageInfo? { return differ.currentList.getOrNull(pos) } var selectedPos: Int = 0 private var doOnRemoveItem: (ImageInfo?) -> Unit = {} fun onRemove(block: (ImageInfo?) -> Unit = {}) { this.doOnRemoveItem = block } private fun remove(removePos: Int) { if (removePos < 0 || removePos >= itemCount || itemCount <= 1) { return } doOnRemoveItem.invoke(getItem(removePos)) } class ImageHolder(view: PhotoPreviewItem) : BaseViewHolder(view) { val ivIcon: ImageView = view.ivIcon val ivRemove: ImageView = view.ivDel.apply { this.isVisible = false } } }
24
null
91
885
b9c0b54eb98c1568b7a793630c98e5d0f0d055a1
4,569
EasyWatermark
MIT License
app/src/main/java/org/simple/clinic/summary/teleconsultation/contactdoctor/ContactDoctorSheet.kt
simpledotorg
132,515,649
false
null
package org.simple.clinic.summary.teleconsultation.contactdoctor import android.content.Context import android.content.Intent import android.os.Bundle import io.github.inflationx.viewpump.ViewPumpContextWrapper import io.reactivex.Observable import io.reactivex.rxkotlin.ofType import kotlinx.android.synthetic.main.sheet_contact_doctor.* import org.simple.clinic.ClinicApp import org.simple.clinic.R import org.simple.clinic.ReportAnalyticsEvents import org.simple.clinic.di.InjectorProviderContextWrapper import org.simple.clinic.mobius.MobiusDelegate import org.simple.clinic.summary.PatientTeleconsultationInfo import org.simple.clinic.summary.teleconsultation.messagebuilder.LongTeleconsultMessageBuilder import org.simple.clinic.summary.teleconsultation.messagebuilder.ShortTeleconsultMessageBuilder import org.simple.clinic.summary.teleconsultation.sync.MedicalOfficer import org.simple.clinic.util.LocaleOverrideContextWrapper import org.simple.clinic.util.messagesender.SmsMessageSender import org.simple.clinic.util.messagesender.WhatsAppMessageSender import org.simple.clinic.util.unsafeLazy import org.simple.clinic.util.wrap import org.simple.clinic.widgets.BottomSheetActivity import org.simple.clinic.widgets.DividerItemDecorator import org.simple.clinic.widgets.ItemAdapter import org.simple.clinic.widgets.UiEvent import org.simple.clinic.widgets.dp import java.util.Locale import java.util.UUID import javax.inject.Inject class ContactDoctorSheet : BottomSheetActivity(), ContactDoctorUi, ContactDoctorUiActions { companion object { private const val EXTRA_PATIENT_UUID = "patientUuid" fun intent(context: Context, patientUuid: UUID): Intent { return Intent(context, ContactDoctorSheet::class.java).apply { putExtra(EXTRA_PATIENT_UUID, patientUuid) } } } @Inject lateinit var effectHandlerFactory: ContactDoctorEffectHandler.Factory @Inject lateinit var locale: Locale @Inject lateinit var longTeleconsultMessageBuilder: LongTeleconsultMessageBuilder @Inject lateinit var shortTeleconsultMessageBuilder: ShortTeleconsultMessageBuilder @Inject lateinit var whatsAppMessageSender: WhatsAppMessageSender @Inject lateinit var smsMessageSender: SmsMessageSender private val itemAdapter = ItemAdapter(DoctorListItem.DiffCallback()) private val events by unsafeLazy { Observable .merge( whatsAppButtonClicks(), smsButtonClicks() ) .compose(ReportAnalyticsEvents()) } private val delegate by unsafeLazy { val uiRenderer = ContactDoctorUiRenderer(this) val patientUuid = intent.getSerializableExtra(EXTRA_PATIENT_UUID) as UUID MobiusDelegate.forActivity( events = events.ofType(), defaultModel = ContactDoctorModel.create(patientUuid), init = ContactDoctorInit(), update = ContactDoctorUpdate(), effectHandler = effectHandlerFactory.create(this).build(), modelUpdateListener = uiRenderer::render ) } private lateinit var component: ContactDoctorComponent override fun onStart() { super.onStart() delegate.start() } override fun onStop() { delegate.stop() super.onStop() } override fun onSaveInstanceState(outState: Bundle) { super.onSaveInstanceState(outState) delegate.onSaveInstanceState(outState) } override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.sheet_contact_doctor) delegate.onRestoreInstanceState(savedInstanceState) doctorsRecyclerView.adapter = itemAdapter doctorsRecyclerView.addItemDecoration(DividerItemDecorator( context = this, marginStart = 16.dp, marginEnd = 16.dp )) } override fun showMedicalOfficers(medicalOfficers: List<MedicalOfficer>) { itemAdapter.submitList(DoctorListItem.from(medicalOfficers)) } override fun sendTeleconsultMessage(teleconsultInfo: PatientTeleconsultationInfo, messageTarget: MessageTarget) { when (messageTarget) { MessageTarget.WHATSAPP -> sendWhatsAppMessage(teleconsultInfo) MessageTarget.SMS -> sendSmsMessage(teleconsultInfo) } } private fun sendWhatsAppMessage(teleconsultInfo: PatientTeleconsultationInfo) { val message = longTeleconsultMessageBuilder.message(teleconsultInfo) whatsAppMessageSender.send(teleconsultInfo.doctorPhoneNumber!!, message) } private fun sendSmsMessage(teleconsultInfo: PatientTeleconsultationInfo) { val message = shortTeleconsultMessageBuilder.message(teleconsultInfo) smsMessageSender.send(teleconsultInfo.doctorPhoneNumber!!, message) } override fun attachBaseContext(baseContext: Context) { setupDiGraph() val wrappedContext = baseContext .wrap { LocaleOverrideContextWrapper.wrap(it, locale) } .wrap { InjectorProviderContextWrapper.wrap(it, component) } .wrap { ViewPumpContextWrapper.wrap(it) } super.attachBaseContext(wrappedContext) } private fun whatsAppButtonClicks(): Observable<UiEvent> { return itemAdapter .itemEvents .ofType<DoctorListItem.Event.WhatsAppClicked>() .map { WhatsAppButtonClicked(it.doctorId, it.phoneNumber) } } private fun smsButtonClicks(): Observable<UiEvent> { return itemAdapter .itemEvents .ofType<DoctorListItem.Event.SmsClicked>() .map { SmsButtonClicked(it.doctorId, it.phoneNumber) } } private fun setupDiGraph() { component = ClinicApp.appComponent .contactDoctorComponent() .activity(this) .build() component.inject(this) } }
13
null
73
236
ff699800fbe1bea2ed0492df484777e583c53714
5,624
simple-android
MIT License
ui/src/test/kotlin/io/rippledown/main/OpenRDRUITest.kt
TimLavers
513,037,911
false
{"Kotlin": 1137574, "Gherkin": 76663}
package io.rippledown.main import androidx.compose.ui.test.junit4.createComposeRule import androidx.compose.ui.test.onNodeWithTag import io.mockk.coEvery import io.mockk.coVerify import io.mockk.mockk import io.rippledown.appbar.assertKbNameIs import io.rippledown.casecontrol.* import io.rippledown.constants.main.APPLICATION_BAR_ID import io.rippledown.interpretation.addNewComment import io.rippledown.interpretation.clickAddCommentMenu import io.rippledown.interpretation.clickChangeInterpretationButton import io.rippledown.interpretation.requireInterpretation import io.rippledown.model.* import io.rippledown.model.condition.ConditionList import io.rippledown.model.condition.EpisodicCondition import io.rippledown.model.condition.edit.FixedSuggestedCondition import io.rippledown.model.condition.episodic.predicate.Normal import io.rippledown.model.condition.episodic.signature.Current import io.rippledown.model.rule.CornerstoneStatus import io.rippledown.rule.clickCancelRuleButton import io.rippledown.rule.clickFinishRuleButton import io.rippledown.utils.applicationFor import kotlinx.coroutines.ExperimentalCoroutinesApi import kotlinx.coroutines.test.runTest import org.junit.Before import org.junit.Rule import kotlin.test.Test class OpenRDRUITest { @get:Rule val composeTestRule = createComposeRule() lateinit var handler: Handler lateinit var api: Api @Before fun setUp() { api = mockk<Api>(relaxed = true) handler = mockk<Handler>(relaxed = true) coEvery { handler.api } returns api coEvery { handler.isClosing } returns { true } } @OptIn(ExperimentalCoroutinesApi::class) @Test fun `should show OpenRDR UI`() = runTest { with(composeTestRule) { setContent { OpenRDRUI(handler) } onNodeWithTag(testTag = APPLICATION_BAR_ID).assertExists() } } @Test fun `should show the first project if there is one`() = runTest { coEvery { handler.api.kbList() } returns listOf(KBInfo("Bondi"), KBInfo("Malabar")) with(composeTestRule) { setContent { OpenRDRUI(handler) } assertKbNameIs("Bondi") } } @Test fun `should show the interpretation of the first case`() = runTest { val caseA = "case A" val caseB = "case B" val caseId1 = CaseId(id = 1, name = caseA) val caseId2 = CaseId(id = 2, name = caseB) val caseIds = listOf(caseId1, caseId2) val bondiComment = "Go to Bondi" val case = createCaseWithInterpretation(caseA, 1, listOf(bondiComment)) coEvery { handler.api.waitingCasesInfo() } returns CasesInfo(caseIds) coEvery { handler.api.getCase(1) } returns case with(composeTestRule) { setContent { OpenRDRUI(handler) } //Given requireNumberOfCasesOnCaseList(2) requireNamesToBeShowingOnCaseList(caseA, caseB) //When waitForCaseToBeShowing(caseA) //Then requireInterpretation(bondiComment) } } @Test fun `should show case list for several cases`() = runTest { val caseIds = (1..10).map { i -> val caseId = CaseId(id = i.toLong(), name = "case $i") coEvery { handler.api.getCase(caseId.id!!) } returns createCase(caseId) caseId } coEvery { handler.api.waitingCasesInfo() } returns CasesInfo(caseIds) val caseName1 = "case 1" val caseName10 = "case 10" with(composeTestRule) { setContent { OpenRDRUI(handler) } //Given waitForCaseToBeShowing(caseName1) //When selectCaseByName(caseName10) //Then waitForCaseToBeShowing(caseName10) } } @Test fun `should show a case when its case name is clicked`() = runTest { val caseNameA = "case A" val caseNameB = "case B" val caseNameC = "case C" val caseId1 = CaseId(id = 1, name = caseNameA) val caseId2 = CaseId(id = 2, name = caseNameB) val caseId3 = CaseId(id = 3, name = caseNameC) val threeCaseIds = listOf(caseId1, caseId2, caseId3) val caseA = createCase(caseId1) val caseB = createCase(caseId2) coEvery { handler.api.getCase(1) } returns caseA coEvery { handler.api.getCase(2) } returns caseB coEvery { handler.api.waitingCasesInfo() } returns CasesInfo(threeCaseIds) with(composeTestRule) { setContent { OpenRDRUI(handler) } //Given requireNumberOfCasesOnCaseList(3) requireNamesToBeShowingOnCaseList(caseNameA, caseNameB, caseNameC) //When selectCaseByName(caseNameB) //Then waitForCaseToBeShowing(caseNameB) } } @Test fun `should list case names`() = runTest { val caseA = "case a" val caseB = "case b" val caseId1 = CaseId(id = 1, name = caseA) val caseId2 = CaseId(id = 2, name = caseB) val twoCaseIds = listOf( caseId1, caseId2 ) val case = createCase(caseId1) coEvery { handler.api.getCase(1) } returns case coEvery { handler.api.waitingCasesInfo() } returns CasesInfo(twoCaseIds) with(composeTestRule) { setContent { OpenRDRUI(handler) } requireNumberOfCasesOnCaseList(2) requireNamesToBeShowingOnCaseList(caseA, caseB) } } @Test fun `should update the interpretation when a case is selected`() = runTest { val caseA = "case A" val caseB = "case B" val caseId1 = CaseId(id = 1, name = caseA) val caseId2 = CaseId(id = 2, name = caseB) val caseIds = listOf(caseId1, caseId2) val bondiComment = "Go to Bondi" val malabarComment = "Go to Malabar" val viewableCaseA = createCaseWithInterpretation( name = caseA, id = 1, conclusionTexts = listOf(bondiComment) ) val viewableCaseB = createCaseWithInterpretation( name = caseB, id = 2, conclusionTexts = listOf(malabarComment) ) coEvery { handler.api.waitingCasesInfo() } returns CasesInfo(caseIds) coEvery { handler.api.getCase(caseId1.id!!) } returns viewableCaseA coEvery { handler.api.getCase(caseId2.id!!) } returns viewableCaseB with(composeTestRule) { setContent { OpenRDRUI(handler) } //Given requireNumberOfCasesOnCaseList(2) requireNamesToBeShowingOnCaseList(caseA, caseB) waitForCaseToBeShowing(caseA) requireInterpretation(bondiComment) //When selectCaseByName(caseB) //Then waitForCaseToBeShowing(caseB) requireInterpretation(malabarComment) } } @Test fun `should update the condition hints when a case is selected`() = runTest { val caseA = "case A" val caseB = "case B" val caseId1 = CaseId(id = 1, name = caseA) val caseId2 = CaseId(id = 2, name = caseB) val caseIds = listOf(caseId1, caseId2) val bondiComment = "Go to Bondi" val malabarComment = "Go to Malabar" val viewableCaseA = createCaseWithInterpretation( name = caseA, id = 1, conclusionTexts = listOf(bondiComment) ) val viewableCaseB = createCaseWithInterpretation( name = caseB, id = 2, conclusionTexts = listOf(malabarComment) ) val normalTSH = EpisodicCondition(null, Attribute(1, "tsh"), Normal, Current) val normalFT3 = EpisodicCondition(null, Attribute(2, "ft3"), Normal, Current) coEvery { handler.api.waitingCasesInfo() } returns CasesInfo(caseIds) coEvery { handler.api.getCase(caseId1.id!!) } returns viewableCaseA coEvery { handler.api.getCase(caseId2.id!!) } returns viewableCaseB coEvery { handler.api.conditionHints(caseId1.id!!) } returns ConditionList(listOf(FixedSuggestedCondition(normalTSH))) coEvery { handler.api.conditionHints(caseId2.id!!) } returns ConditionList(listOf(FixedSuggestedCondition(normalFT3))) with(composeTestRule) { setContent { OpenRDRUI(handler) } //Given requireNumberOfCasesOnCaseList(2) requireNamesToBeShowingOnCaseList(caseA, caseB) waitForCaseToBeShowing(caseA) coVerify { handler.api.conditionHints(caseId1.id!!) } //When selectCaseByName(caseB) //Then coVerify { handler.api.conditionHints(caseId2.id!!) } } } @Test fun `should not show case selector when a rule session is started`() = runTest { val caseName = "case a" val caseId = CaseId(id = 1, name = caseName) val case = createCase(caseId) coEvery { handler.api.getCase(1) } returns case coEvery { handler.api.waitingCasesInfo() } returns CasesInfo(listOf(caseId)) with(composeTestRule) { setContent { OpenRDRUI(handler) } //Given waitForCaseToBeShowing(caseName) requireCaseSelectorToBeDisplayed() clickChangeInterpretationButton() //When clickAddCommentMenu() addNewComment("Go to Bondi") //Then requireCaseSelectorNotToBeDisplayed() } } @Test fun `should call handler to widen the window when a cornerstone case is shown`() = runTest { val caseName = "case a" val cornerstoneName = "case b" val caseId = CaseId(id = 1, name = caseName) val cornerstoneId = CaseId(id = 2, name = cornerstoneName) val case = createCase(caseId) val cornerstone = createCase(cornerstoneId) coEvery { handler.api.getCase(1) } returns case coEvery { handler.api.waitingCasesInfo() } returns CasesInfo(listOf(caseId)) coEvery { handler.api.startRuleSession(any()) } returns CornerstoneStatus(cornerstone, 0, 1) coEvery { handler.api.selectCornerstone(any()) } returns cornerstone with(composeTestRule) { setContent { OpenRDRUI(handler) } //Given waitForCaseToBeShowing(caseName) clickChangeInterpretationButton() coVerify { handler.showingCornerstone(false) } //When clickAddCommentMenu() addNewComment("Go to Bondi") //Then coVerify { handler.showingCornerstone(true) } } } @Test fun `should call handler to set the window to default size when a rule session is cancelled`() = runTest { val caseName = "case a" val cornerstoneName = "case b" val caseId = CaseId(id = 1, name = caseName) val cornerstoneId = CaseId(id = 2, name = cornerstoneName) val case = createCase(caseId) val cornerstone = createCase(cornerstoneId) coEvery { handler.api.getCase(1) } returns case coEvery { handler.api.waitingCasesInfo() } returns CasesInfo(listOf(caseId)) coEvery { handler.api.startRuleSession(any()) } returns CornerstoneStatus(cornerstone, 0, 1) coEvery { handler.api.selectCornerstone(any()) } returns cornerstone with(composeTestRule) { setContent { OpenRDRUI(handler) } //Given waitForCaseToBeShowing(caseName) clickChangeInterpretationButton() clickAddCommentMenu() addNewComment("Go to Bondi") coVerify { handler.showingCornerstone(true) } //When clickCancelRuleButton() //Then coVerify { handler.showingCornerstone(false) } } } @Test fun `should call handler to set the window to default size when a rule session is finished`() = runTest { val caseName = "case a" val cornerstoneName = "case b" val caseId = CaseId(id = 1, name = caseName) val cornerstoneId = CaseId(id = 2, name = cornerstoneName) val case = createCase(caseId) val cornerstone = createCase(cornerstoneId) coEvery { handler.api.getCase(1) } returns case coEvery { handler.api.waitingCasesInfo() } returns CasesInfo(listOf(caseId)) coEvery { handler.api.startRuleSession(any()) } returns CornerstoneStatus(cornerstone, 0, 1) coEvery { handler.api.selectCornerstone(any()) } returns cornerstone with(composeTestRule) { setContent { OpenRDRUI(handler) } //Given waitForCaseToBeShowing(caseName) clickChangeInterpretationButton() clickAddCommentMenu() addNewComment("Go to Bondi") waitForIdle() coVerify { handler.showingCornerstone(true) } //When Thread.sleep(1000) clickFinishRuleButton() //Then coVerify { handler.showingCornerstone(false) } } } } fun main() { val caseIds = (1..100).map { i -> CaseId(id = i.toLong(), name = "case $i") } val handler = mockk<Handler>(relaxed = true) val api = mockk<Api>(relaxed = true) coEvery { handler.api } returns api coEvery { handler.isClosing() } returns false coEvery { api.waitingCasesInfo() } returns CasesInfo(caseIds) coEvery { api.getCase(any()) } returns createCaseWithInterpretation("case A", 1, listOf("Go to Bondi")) applicationFor { OpenRDRUI(handler) } }
1
Kotlin
0
0
eea6fbed258d90d320ba3da2c05e8bfbb683a311
14,037
OpenRDR
MIT License
libraries/splitInstall/src/main/java/com/escodro/splitinstall/SplitInstall.kt
igorescodro
116,942,964
false
null
@file:Suppress("Filename") package com.escodro.splitinstall import android.content.Context import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.size import androidx.compose.material3.AlertDialog import androidx.compose.material3.CircularProgressIndicator import androidx.compose.material3.Text import androidx.compose.runtime.Composable import androidx.compose.runtime.DisposableEffect import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.runtime.saveable.rememberSaveable import androidx.compose.runtime.setValue import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.res.stringResource import androidx.compose.ui.unit.dp import com.escodro.designsystem.components.AlkaaDialog import com.escodro.designsystem.components.DialogArguments import com.escodro.splitinstall.SplitInstallState.Downloading import com.escodro.splitinstall.SplitInstallState.FeatureReady import com.escodro.splitinstall.SplitInstallState.RequestDownload import com.google.android.play.core.splitinstall.SplitInstallManager import com.google.android.play.core.splitinstall.SplitInstallManagerFactory import com.google.android.play.core.splitinstall.SplitInstallRequest import com.google.android.play.core.splitinstall.SplitInstallStateUpdatedListener import com.google.android.play.core.splitinstall.model.SplitInstallSessionStatus import logcat.logcat /** * Composable to handle the all the operations to open a Dynamic Feature Module. This Composable * handles the user request, download and notifies the caller when the feature is ready to be * opened. If the feature is already installed, it will open the feature right away. * * There is a workaround in this code because the Jetpack Navigation Compose does not support * Dynamic Feature properly. Once Alkaa needs to open a new Activity, the Composable/Dialog needed * to do so needs to be manually removed from the stack. Hopefully this hack will not be needed * when the proper support is launched. * * @param context the application context * @param featureName the dynamic feature name * @param onDismiss the action to dismiss the current composable * @param onFeatureReady function called when the feature is ready to be opened */ @Composable fun LoadFeature( context: Context, featureName: String, onDismiss: () -> Unit, onFeatureReady: () -> Unit, ) { require(featureName.isNotEmpty()) { "Feature name not provided" } val manager = remember(featureName) { SplitInstallManagerFactory.create(context) } val isFeatureReady = remember(featureName) { isFeatureInstalled(manager = manager, featureName = featureName) } val initialState = remember(featureName) { if (isFeatureReady) FeatureReady else RequestDownload } var state by rememberSaveable(featureName) { mutableStateOf(initialState) } when (state) { RequestDownload -> RequestDownload(onDismiss = onDismiss, setState = { state = it }) Downloading -> DownloadFeature( featureName = featureName, manager = manager, onDismiss = onDismiss, setState = { state = it }, ) FeatureReady -> { onDismiss() onFeatureReady() } } } private fun isFeatureInstalled( manager: SplitInstallManager, featureName: String, ): Boolean { val isFeatureInstalled = manager.installedModules.contains(featureName) logcat(TAG) { "load = [$featureName] - isFeatureInstalled = $isFeatureInstalled" } return isFeatureInstalled } @Composable private fun RequestDownload(setState: (SplitInstallState) -> Unit, onDismiss: () -> Unit) { var isDialogOpen by rememberSaveable { mutableStateOf(true) } val arguments = DialogArguments( title = stringResource(id = R.string.split_confirmation_install_title), text = stringResource(id = R.string.split_confirmation_install_description), confirmText = stringResource(id = R.string.split_confirmation_install_accept), dismissText = stringResource(id = R.string.split_confirmation_install_deny), onConfirmAction = { setState(Downloading) }, ) AlkaaDialog( arguments = arguments, isDialogOpen = isDialogOpen, onDismissRequest = { isDialogOpen = false onDismiss() }, ) } @Composable private fun DownloadFeature( featureName: String, manager: SplitInstallManager, onDismiss: () -> Unit, setState: (SplitInstallState) -> Unit, ) { var isDialogOpen by rememberSaveable { mutableStateOf(true) } DisposableEffect(featureName) { val request = SplitInstallRequest.newBuilder() .addModule(featureName) .build() val listener = SplitInstallStateUpdatedListener { logcat { "${it.status()}" } when (it.status()) { SplitInstallSessionStatus.PENDING -> isDialogOpen = true SplitInstallSessionStatus.INSTALLED -> { isDialogOpen = false setState(FeatureReady) onDismiss() } else -> logcat { "${it.status()}" } } } manager.registerListener(listener) manager.startInstall(request) onDispose { manager.unregisterListener(listener) } } if (isDialogOpen) { DownloadDialog() } } @Composable private fun DownloadDialog() { AlertDialog( onDismissRequest = { /* Does not close */ }, title = { Text(text = stringResource(id = R.string.split_downloading_title)) }, text = { Column { Text(text = stringResource(id = R.string.split_downloading_description)) Box( contentAlignment = Alignment.Center, modifier = Modifier .fillMaxWidth() .padding(top = 32.dp), ) { CircularProgressIndicator(modifier = Modifier.size(64.dp)) } } }, confirmButton = { /* Shows nothing */ }, dismissButton = { /* Shows nothing */ }, ) } private const val TAG = "SplitInstall"
8
Kotlin
83
999
e64a652c6b62dd5ca80c2c128186ef4b8bf6cf63
6,518
alkaa
Apache License 2.0
app/src/main/java/rg/info/storagelocator/ui/components/container/ContainerFABComponent.kt
guillaumer63
582,988,544
false
{"Kotlin": 42998}
package rg.info.storagelocator.ui.components.container import androidx.compose.foundation.layout.padding import androidx.compose.material.icons.Icons import androidx.compose.material.icons.filled.Add import androidx.compose.material3.AlertDialog import androidx.compose.material3.Button import androidx.compose.material3.ButtonDefaults import androidx.compose.material3.FloatingActionButton import androidx.compose.material3.Icon import androidx.compose.material3.OutlinedButton import androidx.compose.material3.Text import androidx.compose.runtime.Composable import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.ui.Modifier import androidx.compose.ui.graphics.Color import androidx.compose.ui.unit.dp import rg.info.storagelocator.data.Containers import java.util.UUID @Composable fun ContainerFABComponent(uuid: UUID, onContainerChanged: () -> Unit) { val addDialog = remember { mutableStateOf(false) } val container = Containers.getContainer(uuid) if (addDialog.value) { val (newItemName, onNewItemNameChange) = remember { mutableStateOf("") } AlertDialog( onDismissRequest = { addDialog.value = false }, icon = { Icon(Icons.Filled.Add, contentDescription = "Add") }, title = { Text("Ajouter un objet") }, text = { InputComponent( value = newItemName, onValueChange = onNewItemNameChange, "Nom" ) }, confirmButton = { Button( onClick = { container.addItem(newItemName) addDialog.value = false // refresh container onContainerChanged() }, // green color colors = ButtonDefaults.buttonColors( contentColor = Color.White, containerColor = Color.Green.copy(alpha = 0.5f), ), modifier = Modifier.padding(bottom = 10.dp) ) { Text("Ajouter") } }, dismissButton = { OutlinedButton( onClick = { addDialog.value = false }, // align the button to the end of the dialog modifier = Modifier.padding( // to the left start = 16.dp, ) ) { Text("Annuler") } } ) } FloatingActionButton( onClick = { addDialog.value = true }, modifier = Modifier.padding(bottom = 10.dp) ) { Icon(Icons.Filled.Add, contentDescription = "Ajouter") } }
0
Kotlin
0
1
beac4d4104f82e8afcc992caa8cd57e8360aa5ae
2,904
storage-locator
Apache License 2.0
src/main/kotlin/dev/mizarc/bellclaims/api/ClaimWorldService.kt
mizarc
694,771,936
false
{"Kotlin": 469240}
package dev.mizarc.bellclaims.api import dev.mizarc.bellclaims.api.enums.ClaimCreationResult import dev.mizarc.bellclaims.api.enums.ClaimMoveResult import dev.mizarc.bellclaims.domain.claims.Claim import org.bukkit.Location import org.bukkit.OfflinePlayer /** * A service that handles the existence of claims in the world. Actions involve the physical manipulations of claims * that depend on partition checks. */ interface ClaimWorldService { /** * Checks to see if a new claim can be created in a location based on the existence of a claim bell and whether a * partition can be created in the surrounding space. * * @param location The location to query. * @return True if the queried location is valid. */ fun isNewLocationValid(location: Location): Boolean /** * Checks to see if an existing claim can be moved to a location based on whether the new location exists in the * boundaries of the claim partition. * * @param claim The existing claim. * @param location The location to query. * @return True if the queried location is valid. */ fun isMoveLocationValid(claim: Claim, location: Location): Boolean /** * Gets a claim by the location in the world. * * @param location The Location to query * @return The found claim or null if not found. */ fun getByLocation(location: Location): Claim? /** * Creates a claim and its associated partition in the selection location. * * @param name The name of the claim. * @param location The location to query. * @param player The player to assign the claim to. * @return The enum result of the creation action. */ fun create(name: String, location: Location, player: OfflinePlayer): ClaimCreationResult /** * Moves the position of the claim block to a different location. The new location must be in an area that the claim * partition boundaries occupy. * * @param claim The existing claim. * @param location The location to move the claim block to. * @return The enum result of the move action. */ fun move(claim: Claim, location: Location): ClaimMoveResult }
7
Kotlin
4
9
8eb7a8a325e91136f36cd236f490694311df47a2
2,216
bell-claims
MIT License
library/src/main/kotlin/de/eternalwings/focus/Reference.kt
kumpelblase2
259,880,502
false
null
package de.eternalwings.focus /** * A reference to another element in the store. In many cases this is the reference to the parent element. */ data class Reference( /** * The ID of the referenced element. This may be null to explicitly indicate "no reference", which * helps knowing if it should be included in the resulting changeset as there needs to be some way to * differentiate "no change" and "change to no parent/reference". `null` alone would not suffice, which * is why this ID may be `null` too to indicate this "no reference" situation. */ val id: String? = null ) internal fun Reference?.mergeInto(other: Reference?): Reference? { return when { this == null -> other this.id == null -> null else -> this } } fun String.asReference() = Reference(this)
1
Kotlin
0
5
80ed810a66a954739219ac73af3d1e626f55c58c
834
focus
Apache License 2.0
library/src/main/kotlin/de/eternalwings/focus/Reference.kt
kumpelblase2
259,880,502
false
null
package de.eternalwings.focus /** * A reference to another element in the store. In many cases this is the reference to the parent element. */ data class Reference( /** * The ID of the referenced element. This may be null to explicitly indicate "no reference", which * helps knowing if it should be included in the resulting changeset as there needs to be some way to * differentiate "no change" and "change to no parent/reference". `null` alone would not suffice, which * is why this ID may be `null` too to indicate this "no reference" situation. */ val id: String? = null ) internal fun Reference?.mergeInto(other: Reference?): Reference? { return when { this == null -> other this.id == null -> null else -> this } } fun String.asReference() = Reference(this)
1
Kotlin
0
5
80ed810a66a954739219ac73af3d1e626f55c58c
834
focus
Apache License 2.0
kotlin/ktor/pokedex/src/main/kotlin/com/pradyotprkshpokedex/domain/modal/GenerationI.kt
pradyotprksh
385,586,594
false
{"Kotlin": 2946772, "Dart": 1066884, "Python": 321205, "Rust": 180589, "Swift": 149624, "C++": 113494, "JavaScript": 103891, "CMake": 94132, "HTML": 57188, "Go": 45704, "CSS": 18615, "SCSS": 17864, "Less": 17245, "Ruby": 13609, "Dockerfile": 9772, "C": 8043, "Shell": 7657, "PowerShell": 3045, "Nix": 2616, "Makefile": 1480, "PHP": 1241, "Objective-C": 380, "Handlebars": 354}
package com.pradyotprkshpokedex.domain.modal import kotlinx.serialization.SerialName import kotlinx.serialization.Serializable @Serializable data class GenerationI( @SerialName("red-blue") val redBlue: RedBlue? = RedBlue(), @SerialName("yellow") val yellow: Yellow? = Yellow() )
0
Kotlin
11
24
da2054de505260bdfa5ffa6d67674f0fa5ba8d3c
290
development_learning
MIT License
mobile/src/main/java/uk/co/appsbystudio/geoshare/utils/ui/SettingsActivity.kt
zacdevil10
50,067,543
false
null
package uk.co.appsbystudio.geoshare.utils.ui import android.content.Intent import android.content.SharedPreferences import android.os.Bundle import android.preference.PreferenceManager import android.support.v7.app.AppCompatActivity import android.support.v7.widget.Toolbar import com.google.firebase.auth.FirebaseAuth import com.google.firebase.auth.FirebaseUser import com.google.firebase.auth.UserProfileChangeRequest import com.google.firebase.database.FirebaseDatabase import uk.co.appsbystudio.geoshare.R import uk.co.appsbystudio.geoshare.utils.ProfileSelectionResult import uk.co.appsbystudio.geoshare.utils.firebase.UserInformation class SettingsActivity : AppCompatActivity(), SharedPreferences.OnSharedPreferenceChangeListener { private var user: FirebaseUser? = null public override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_settings) val toolbar = findViewById<Toolbar>(R.id.toolbar_manager) setSupportActionBar(toolbar) if (supportActionBar != null) supportActionBar!!.setDisplayHomeAsUpEnabled(true) fragmentManager.beginTransaction().replace(R.id.frame_content_main, SettingsFragment()).commit() PreferenceManager.getDefaultSharedPreferences(applicationContext).registerOnSharedPreferenceChangeListener(this) user = FirebaseAuth.getInstance().currentUser } override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) { ProfileSelectionResult().profilePictureResult(this, requestCode, resultCode, data, user?.uid) } override fun onSharedPreferenceChanged(sharedPreferences: SharedPreferences, key: String) { if (key == "display_name") { val name = sharedPreferences.getString(key, "DEFAULT") val userInfo = UserInformation(name, name.toLowerCase()) if (user != null) FirebaseDatabase.getInstance().reference.child("users").child(user!!.uid).setValue(userInfo) val profileChangeRequest = UserProfileChangeRequest.Builder().setDisplayName(name).build() user?.updateProfile(profileChangeRequest) } } override fun onDestroy() { super.onDestroy() PreferenceManager.getDefaultSharedPreferences(applicationContext).unregisterOnSharedPreferenceChangeListener(this) } }
5
Kotlin
1
1
f66aa94d7f44c8dbf81a6a67a4e0504bbf7e2d32
2,381
GeoShare_Android
Apache License 2.0
tbs/src/main/java/com/angcyo/tbs/core/TbsWebFragment.kt
angcyo
229,037,684
false
null
package com.angcyo.tbs.core import android.content.ComponentName import android.graphics.Color import android.net.Uri import android.os.Bundle import android.view.View import android.view.ViewGroup import android.view.WindowManager import android.widget.TextView import com.angcyo.base.dslAHelper import com.angcyo.base.dslFHelper import com.angcyo.core.component.fileSelector import com.angcyo.core.fragment.BaseTitleFragment import com.angcyo.dialog.configBottomDialog import com.angcyo.dialog.dslDialog import com.angcyo.download.download import com.angcyo.download.downloadNotify import com.angcyo.dsladapter.renderItemList import com.angcyo.image.dslitem.DslSubSamplingImageItem import com.angcyo.library.L import com.angcyo.library.component.DslIntent import com.angcyo.library.component.DslNotify import com.angcyo.library.component.dslIntentShare import com.angcyo.library.ex.* import com.angcyo.library.model.loadUri import com.angcyo.library.toastQQ import com.angcyo.loader.singleImage import com.angcyo.loader.singleVideo import com.angcyo.media.dslitem.DslTextureVideoItem import com.angcyo.picker.dslPicker import com.angcyo.tablayout.screenWidth import com.angcyo.tbs.DslTbs import com.angcyo.tbs.R import com.angcyo.tbs.TbsImagePager import com.angcyo.tbs.core.dslitem.DslBaseWebMenuItem import com.angcyo.tbs.core.inner.TbsWeb import com.angcyo.tbs.core.inner.TbsWebView import com.angcyo.widget.DslViewHolder import com.angcyo.widget.bar import com.angcyo.widget.base.* import com.angcyo.widget.span.span import com.tencent.smtt.sdk.QbSdk import com.tencent.smtt.sdk.TbsReaderView /** * file:///android_asset/webpage/fileChooser.html * * TBS内核调试界面 * https://debugtbs.qq.com/ * * Email:<EMAIL> * @author angcyo * @date 2020/03/01 */ open class TbsWebFragment : BaseTitleFragment() { companion object { const val KEY_CONFIG = "key_config" const val LOADING_TITLE = "加载中..." const val DEBUG_TBS_URL = "https://debugtbs.qq.com" } init { contentLayoutId = R.layout.layout_tbs_web_content contentOverlayLayoutId = R.layout.layout_tbs_web_content_overlay fragmentTitle = null enableTitleBarHideBehavior } override fun onCreateBackItem(): View? { return super.onCreateBackItem()?.apply { find<TextView>(R.id.lib_text_view)?.run { text = span { drawable { backgroundDrawable = loadDrawable(R.drawable.lib_back) .colorFilter(fragmentConfig.titleItemIconColor) } } } } } var webConfig = TbsWebConfig() override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) arguments?.getParcelable<TbsWebConfig>(KEY_CONFIG)?.run { webConfig = this if (title != null) { fragmentTitle = title } this@TbsWebFragment.enableTitleBarHideBehavior = enableTitleBarHideBehavior } } override fun onActivityCreated(savedInstanceState: Bundle?) { super.onActivityCreated(savedInstanceState) //开启硬件加速 activity?.window?.addFlags(WindowManager.LayoutParams.FLAG_HARDWARE_ACCELERATED) } //<editor-fold desc="根据不同的类型, 填充不同的布局"> override fun onCreateViewAfter(savedInstanceState: Bundle?) { super.onCreateViewAfter(savedInstanceState) initTbsWebLayout() } open fun initTbsWebLayout() { _vh.tv(R.id.lib_title_text_view)?.run { setWidth(width = screenWidth - 180 * dpi) setSingleLineMode() } val wrapLayout = _vh.group(R.id.tbs_wrap_layout) val uri = webConfig.uri val data = webConfig.data if (data != null) { //加载数据 attachTbsWebView(wrapLayout, null, data) } else if (uri == null) { toastQQ("Uri异常", fContext(), R.drawable.lib_ic_error) } else if (wrapLayout == null) { toastQQ("布局异常", fContext(), R.drawable.lib_ic_error) } else { val loadUrl = uri.loadUrl() val mimeType = loadUrl.mimeType() ?: webConfig.mimeType L.d("TBS:$uri $loadUrl $mimeType") if (mimeType.isVideoMimeType()) { if (DslTbs.canUseTbsPlayer()) { DslTbs.openVideo(fContext(), loadUrl!!) dslAHelper { finish() } } else { attachVideoView(wrapLayout, uri) } } else if (uri.isHttpScheme() || mimeType.isHttpMimeType()) { //打开网页 loadTbsWebTitleLayout() attachTbsWebView(wrapLayout, loadUrl!!) } else if (uri.isFileScheme()) { val fileExt = loadUrl!!.ext() fragmentTitle = loadUrl.file().name val readerView = TbsReaderView(fContext()) { actionType, args, result -> hideLoadingView() L.d("Tbs type:$actionType args:$args result:$result") } when { //如果tbs支持打开文件, 一般是文档格式 DslTbs.canOpenFileTbs(readerView, fileExt) -> attachTbsReaderView( readerView, wrapLayout, loadUrl ) mimeType.isImageMimeType() -> attachImageView(wrapLayout, uri) else -> showLoadingView("无法打开文件\n$uri") } } else if (mimeType.isTextMimeType()) { attachTextView(wrapLayout, uri) } else { //其他类型 showLoadingView("不支持的类型\n$uri") } } } /**加载网页类型的标题栏*/ open fun loadTbsWebTitleLayout() { //有些网页, 无法回退. 添加强制关闭按钮 appendLeftItem(ico = R.drawable.tbs_ic_close, action = { id = R.id.lib_close_view visibility = View.GONE updateMarginParams { leftMargin = -6 * dpi } }) { close() } if (webConfig.showRightMenu) { //更多 appendRightItem(ico = R.drawable.tbs_ic_more) { showWebMenuDialog() } } } /**显示网页菜单对话框*/ open fun showWebMenuDialog() { fContext().tbsWebMenuDialog { val url = _tbsWebView?._loadUrl webHost = url?.toUri()?.host if (isDebug()) { webDes = span { append(_tbsWebView?.settings?.userAgentString) appendln() append(url) } } line1Items = renderItemList { DslBaseWebMenuItem()() { menuText = "刷新" menuIcon = R.drawable.tbs_ic_refresh itemClick = { _dialog?.dismiss() _tbsWebView?.loadUrl(url) } } DslBaseWebMenuItem()() { menuText = "复制链接" menuIcon = R.drawable.tbs_ic_copy itemClick = { _dialog?.dismiss() url?.copy() } } DslBaseWebMenuItem()() { menuText = "分享" menuIcon = R.drawable.tbs_ic_share itemClick = { _dialog?.dismiss() dslIntentShare { shareTitle = _tbsWebView?.title shareText = url } } } DslBaseWebMenuItem()() { menuText = "浏览器打开" menuIcon = R.drawable.tbs_ic_browser itemClick = { _dialog?.dismiss() DslIntent.openUrl(fContext(), url) } } if (isDebug()) { DslBaseWebMenuItem()() { menuText = "X5内核测试" menuIcon = R.drawable.tbs_ic_x5 itemClick = { _dialog?.dismiss() _tbsWebView?.loadUrl(DEBUG_TBS_URL) } } } } } } var _tbsWebView: TbsWebView? = null /**追加[TbsWebView], 用于打开网页*/ open fun attachTbsWebView(parent: ViewGroup?, url: String?, data: String? = null) { //host提示 if (_vh.view(R.id.lib_host_tip_view) == null) { rootControl().group(R.id.lib_coordinator_wrap_layout)?.apply { addView(inflate(R.layout.tbs_host_tip_layout, false), 0) } } val webView = TbsWebView(fContext()) webView.apply { id = R.id.tbs_web_view _tbsWebView = this onInitTbsWebView(this) //标题回调 receivedTitleAction = { if (webConfig.title.isNullOrEmpty()) { fragmentTitle = it } updateHost(_tbsWebView?.originalUrl) } //进度回调 progressChangedAction = { url, progress -> // L.d("$url $progress") if (webConfig.showLoading) { _vh.bar(R.id.lib_progress_bar)?.setProgress(progress) } //加载框 if (progress == 0) { if (fragmentTitle.isNullOrEmpty()) { fragmentTitle = LOADING_TITLE } } else if (progress == 100) { if (webView.receivedTitle.isNullOrEmpty()) { receivedTitleAction(webView.title) } } checkCloseView() if (progress >= 80) { hideLoadingView() } } //下载回调 downloadAction = { url, userAgent, contentDisposition, mime, length -> fContext().dslDialog { configBottomDialog() dialogLayoutId = R.layout.dialog_tbs_file_download onDialogInitListener = { dialog, dialogViewHolder -> val fileName = TbsWeb.getFileName(url, contentDisposition) dialogViewHolder.tv(R.id.target_url_view)?.text = url dialogViewHolder.tv(R.id.file_name_view)?.text = fileName dialogViewHolder.tv(R.id.file_size_view)?.text = if (length > 0) length.fileSizeString() else "未知大小" dialogViewHolder.tv(R.id.file_type_view)?.text = mime dialogViewHolder.longClick(R.id.target_url_view) { url.copy() toastQQ("下载地址已复制") } dialogViewHolder.click(R.id.download_button) { dialog.dismiss() url.downloadNotify() url.download { onConfigTask = { it.setFilename(fileName) } } } } } } //打开其他应用回调 openAppAction = { url, activityInfo, appBean -> fContext().dslDialog { configBottomDialog() dialogLayoutId = R.layout.dialog_tbs_open_app onDialogInitListener = { dialog, dialogViewHolder -> dialogViewHolder.tv(R.id.lib_text_view)?.text = appBean.appName dialogViewHolder.tv(R.id.lib_sub_text_view)?.text = url dialogViewHolder.img(R.id.lib_image_view)?.setImageDrawable(appBean.appIcon) dialogViewHolder.click(R.id.lib_reject_button) { dialog.dismiss() } dialogViewHolder.click(R.id.lib_open_button) { dialog.dismiss() dslAHelper { start( url.urlIntent( ComponentName( activityInfo.packageName, activityInfo.name ) ) ) } } } } } //选择文件回调 fileChooseAction = { when { it.mimeType.isNullOrEmpty() -> { //选择文件 dslFHelper { fileSelector { it?.run { onFileChooseResult(arrayOf(fileUri)) } ?: onFileChooseResult(null) } } } it.mimeType.isImageMimeType() -> { //image dslPicker({ singleImage() maxSelectorLimit = it.multiLimit }) { it?.let { onFileChooseResultList(it.mapTo(ArrayList()) { it.loadUri() }) } ?: onFileChooseResult(null) } } it.mimeType.isVideoMimeType() -> { //video dslPicker({ singleVideo() maxSelectorLimit = it.multiLimit }) { it?.let { onFileChooseResultList(it.mapTo(ArrayList()) { it.loadUri() }) } ?: onFileChooseResult(null) } } } } //注入图片预览回调 TbsImagePager.register(this@TbsWebFragment, this) //加载url if (data.isNullOrEmpty()) { loadUrl(url) } else { loadDataWithBaseURL2(data) } } parent?.addView(webView, -1, -1) } open fun onInitTbsWebView(webView: TbsWebView) { } fun updateHost(url: String?) { val host = url?.toUri()?.host _vh.tv(R.id.lib_host_tip_view)?.text = span { if (!host.isNullOrEmpty()) { append("网页由 $host 提供") if (DslTbs.isX5Core) { appendln() drawable { backgroundDrawable = _drawable(DslNotify.DEFAULT_NOTIFY_ICON)?.setBounds(18 * dpi, 18 * dpi) } append("腾讯x5内核支持") } } } } var _tbsReaderView: TbsReaderView? = null /**追加[TbsReaderView], 用于打开文档格式*/ open fun attachTbsReaderView(readerView: TbsReaderView, parent: ViewGroup, path: String) { val extName = path.ext() val param = Bundle() //param.putString("fileExt", extName) param.putString(TbsReaderView.KEY_FILE_PATH, path) param.putString(TbsReaderView.KEY_TEMP_PATH, context.externalCacheDir?.absolutePath) //默认不设置,是全屏dialog显示文件内容, //param.putInt("windowType",2); //设置windowType = 2,进入view显示文件内容, 文件内容会挂到设置的layout上。 //FILE_READER_WINDOW_TYPE_DEFAULT 全屏样式, 自己的标题栏会无法显示. //param.putInt("windowType", TbsFileInterfaceImpl.FILE_READER_WINDOW_TYPE_DEFAULT) readerView.apply { _tbsReaderView = this if (preOpen(extName, false)) { openFile(param) } } parent.addView(readerView, -1, -1) // //新接口方式, 都会带有默认的标题栏 // TbsFileInterfaceImpl.getInstance() // .openFileReader(fContext(), param, { actionType, args, result -> // hideLoadingView() // // L.d("Tbs type:$actionType args:$args result:$result") // // if (ITbsReader.OPEN_FILEREADER_PLUGIN_SUCCESS == actionType) { // L.w("Tbs plugin success") // } else if (ITbsReader.OPEN_FILEREADER_PLUGIN_FAILED == actionType) { // L.w("Tbs plugin failed") // } // }, parent as FrameLayout) } var _dslVideoHolder: DslViewHolder? = null var _dslVideoItem: DslTextureVideoItem? = null /**加载视频*/ open fun attachVideoView(parent: ViewGroup, uri: Uri) { parent.setBackgroundColor(Color.BLACK) hideLoadingView() val dslVideoItem = DslTextureVideoItem().apply { _dslVideoItem = this itemData = uri itemVideoUri = uri itemDownloadStart = { itemHolder, task -> onDownloadStart(itemHolder, task) showLoadingView("下载中...") } itemDownloadFinish = { itemHolder, task, cause, error -> onDownloadFinish(itemHolder, task, cause, error) hideLoadingView() } } _dslVideoHolder = parent.appendDslItem(dslVideoItem) } var _dslSubSamplingItem: DslSubSamplingImageItem? = null /**加载大图*/ open fun attachImageView(parent: ViewGroup, uri: Uri) { parent.setBackgroundColor(Color.BLACK) hideLoadingView() val dslSubSamplingItem = DslSubSamplingImageItem().apply { _dslSubSamplingItem = this itemData = uri itemLoadUri = uri itemDownloadStart = { itemHolder, task -> onDownloadStart(itemHolder, task) showLoadingView("下载中...") } itemDownloadFinish = { itemHolder, task, cause, error -> onDownloadFinish(itemHolder, task, cause, error) hideLoadingView() } } _dslVideoHolder = parent.appendDslItem(dslSubSamplingItem) } /**加载文本*/ open fun attachTextView(parent: ViewGroup, uri: Uri) { hideLoadingView() parent.inflate(R.layout.tbs_text_layout).apply { find<TextView>(R.id.lib_text_view)?.text = uri.toString() } } //</editor-fold desc="根据不同的类型, 填充不同的布局"> //<editor-fold desc="生命周期操作"> override fun onFragmentShow(bundle: Bundle?) { super.onFragmentShow(bundle) _tbsWebView?.resumeTimers() } override fun onFragmentHide() { super.onFragmentHide() _tbsWebView?.pauseTimers() _dslVideoItem?.itemViewDetachedToWindow?.invoke(_dslVideoHolder!!, 0) _dslSubSamplingItem?.itemViewDetachedToWindow?.invoke(_dslVideoHolder!!, 0) } override fun onDestroy() { super.onDestroy() _tbsWebView?.destroy() _tbsReaderView?.onStop() _dslVideoItem?.itemViewRecycled?.invoke(_dslVideoHolder!!, 0) _dslSubSamplingItem?.itemViewRecycled?.invoke(_dslVideoHolder!!, 0) //TbsFileInterfaceImpl.getInstance().closeFileReader() QbSdk.closeFileReader(fContext()) QbSdk.clear(fContext()) } override fun onBackPressed(): Boolean { val webView = _tbsWebView if (webView != null && webView.canGoBack()) { webView.goBack() checkCloseView() return false } return true } //</editor-fold desc="生命周期操作"> //<editor-fold desc="其他操作"> /**动态判断是否要显示强制关闭按钮*/ open fun checkCloseView() { val webView = _tbsWebView if (webView?.canGoBack() == true) { leftControl()?.run { visible(R.id.lib_close_view) } } else { leftControl()?.run { gone(R.id.lib_close_view) } } } open fun close() { dslFHelper { remove(this@TbsWebFragment) } } fun showLoadingView(tip: CharSequence? = null) { if (webConfig.showLoading) { _vh.visible(R.id.lib_arc_loading_view) _vh.visible(R.id.lib_tip_view, tip != null) } _vh.tv(R.id.lib_tip_view)?.text = tip } fun hideLoadingView() { _vh.gone(R.id.lib_arc_loading_view) _vh.gone(R.id.lib_tip_view) } //</editor-fold desc="其他操作"> }
0
null
4
3
80afa7c9371c4db9a52c38f719336303d4911963
20,954
UICoreEx
MIT License
packages/proto/proto-flatbuffers/src/main/kotlin/elide/assets/EmbeddedScriptMetadata.kt
elide-dev
506,113,888
false
null
// automatically generated by the FlatBuffers compiler, do not modify package elide.assets import java.nio.* import kotlin.math.sign import com.google.flatbuffers.* @Suppress("unused") class EmbeddedScriptMetadata : Table() { fun __init(_i: Int, _bb: ByteBuffer) { __reset(_i, _bb) } fun __assign(_i: Int, _bb: ByteBuffer) : EmbeddedScriptMetadata { __init(_i, _bb) return this } val metadata : elide.assets.EmbeddedScriptMetadata_.LanguageSpecificMetadata? get() = metadata(elide.assets.EmbeddedScriptMetadata_.LanguageSpecificMetadata()) fun metadata(obj: elide.assets.EmbeddedScriptMetadata_.LanguageSpecificMetadata) : elide.assets.EmbeddedScriptMetadata_.LanguageSpecificMetadata? { val o = __offset(4) return if (o != 0) { obj.__assign(__indirect(o + bb_pos), bb) } else { null } } companion object { fun validateVersion() = Constants.FLATBUFFERS_22_12_06() fun getRootAsEmbeddedScriptMetadata(_bb: ByteBuffer): EmbeddedScriptMetadata = getRootAsEmbeddedScriptMetadata(_bb, EmbeddedScriptMetadata()) fun getRootAsEmbeddedScriptMetadata(_bb: ByteBuffer, obj: EmbeddedScriptMetadata): EmbeddedScriptMetadata { _bb.order(ByteOrder.LITTLE_ENDIAN) return (obj.__assign(_bb.getInt(_bb.position()) + _bb.position(), _bb)) } fun createEmbeddedScriptMetadata(builder: FlatBufferBuilder, metadataOffset: Int) : Int { builder.startTable(1) addMetadata(builder, metadataOffset) return endEmbeddedScriptMetadata(builder) } fun startEmbeddedScriptMetadata(builder: FlatBufferBuilder) = builder.startTable(1) fun addMetadata(builder: FlatBufferBuilder, metadata: Int) = builder.addOffset(0, metadata, 0) fun endEmbeddedScriptMetadata(builder: FlatBufferBuilder) : Int { val o = builder.endTable() return o } } }
36
Kotlin
4
33
91800dbbf291e65a91d451ed50c9673d82efd174
1,988
elide
MIT License
app/src/test/java/com/rikucherry/artworkespresso/feature_authentication/domain/util/AuthenticationUtilTest.kt
rikucherry1993
416,754,722
false
{"Kotlin": 235546}
package com.rikucherry.artworkespresso.feature_authentication.domain.util import android.content.Intent import android.net.Uri import com.rikucherry.artworkespresso.common.Constants import org.junit.Assert.assertEquals import org.junit.Assert.assertNull import org.junit.Test import org.junit.runner.RunWith import org.robolectric.RobolectricTestRunner import org.robolectric.annotation.Config import java.util.* @RunWith(RobolectricTestRunner::class) class AuthenticationUtilTest { @Test @Config(manifest=Config.NONE) fun `FormAuthorizeUri_FullParameters_GetExpectedUri`() { //Given val redirectUri = Uri.encode("http://myapp.example/cb") val parameters = "response_type=code&client_id=0" + "&redirect_uri=$redirectUri" + "&scope=basic" + "&state=mysessionid&view=login" val expect = Constants.BASE_URL + Constants.BASE_AUTH_PATH + "?" + parameters //When val actual = AuthenticationUtil.formAuthorizeUri( responseType = "code", clientId = "0", redirectUri = "http://myapp.example/cb", scope = "basic", state = "mysessionid", view = "login" ).toString() //Then assertEquals(expect, actual) } @Test @Config(manifest=Config.NONE) fun `RetrieveAuthorizeCode_Normal_GetAuthorizeCode`() { //Given val intent = Intent(Intent.ACTION_VIEW) val code = UUID.randomUUID().toString() val state = UUID.randomUUID().toString() intent.data = Uri.parse("http://test.com?state=$state&code=$code") //When val resultCode = AuthenticationUtil.retrieveAuthorizeCode(intent, state) //Then assertEquals(resultCode, code) } @Test @Config(manifest=Config.NONE) fun `RetrieveAuthorizeCode_IntentIsNull_ReturnNull`() { //Given val state = UUID.randomUUID().toString() //When val resultCode = AuthenticationUtil.retrieveAuthorizeCode(null, state) //Then assertNull(resultCode) } @Test @Config(manifest=Config.NONE) fun `RetrieveAuthorizeCode_WrongIntentAction_ReturnNull`() { //Given val intent = Intent() val code = UUID.randomUUID().toString() val state = UUID.randomUUID().toString() intent.data = Uri.parse("http://test.com?state=$state&code=$code") //When val resultCode = AuthenticationUtil.retrieveAuthorizeCode(intent, state) //Then assertNull(resultCode) } @Test @Config(manifest=Config.NONE) fun `RetrieveAuthorizeCode_StateInconsistent_ReturnNull`() { //Given val intent = Intent(Intent.ACTION_VIEW) val code = UUID.randomUUID().toString() val state = UUID.randomUUID().toString() intent.data = Uri.parse("http://test.com?state=$state&code=$code") //When val resultCode = AuthenticationUtil.retrieveAuthorizeCode(intent, "1234") //Then assertNull(resultCode) } }
0
Kotlin
0
0
0a9c264c5323a1bb9bbc801008ab8cbc6bd0c323
3,103
artwork-espresso
MIT License
library/src/main/java/com/kodmap/app/library/adapter/PopupSliderAdapter.kt
batorshih
159,349,980
true
{"Gradle": 4, "Java Properties": 2, "Shell": 1, "Ignore List": 3, "Batchfile": 1, "Markdown": 1, "Proguard": 2, "Kotlin": 29, "XML": 27, "Java": 3}
package com.kodmap.app.library.adapter import android.support.v4.view.PagerAdapter import android.view.View import android.view.ViewGroup import android.widget.ImageView import com.kodmap.app.library.R import com.kodmap.app.library.constant.ScaleType import com.kodmap.app.library.model.BaseItem import com.kodmap.app.library.ui.KmRelativeLayout import com.kodmap.app.library.ui.zoomableImaveView.KmZoomableImageView import com.kodmap.app.library.ui.zoomableImaveView.Util.enableTls12OnPreLollipop import com.squareup.picasso.Callback import com.squareup.picasso.OkHttp3Downloader import com.squareup.picasso.Picasso import okhttp3.Cache import okhttp3.Interceptor import java.util.* import okhttp3.OkHttpClient import okhttp3.Response import java.io.IOException class PopupSliderAdapter : PagerAdapter() { private var mImageScaleType: ImageView.ScaleType = ScaleType.FIT_CENTER private var mIsZoomable: Boolean = false lateinit var mLoadingView: View private val itemList = ArrayList<BaseItem>() fun setItemList(itemList: List<BaseItem>) { this.itemList.clear() this.itemList.addAll(itemList) notifyDataSetChanged() } override fun getCount(): Int { return itemList.size } override fun isViewFromObject(view: View, obj: Any): Boolean { return view == obj } override fun instantiateItem(container: ViewGroup, position: Int): Any { val itemView = View.inflate(container.context, R.layout.item_slider, null) as KmRelativeLayout val imageView = itemView.findViewById<KmZoomableImageView>(R.id.km_iv_item_slider) if (::mLoadingView.isInitialized) { itemView.addLoadingLayout(mLoadingView) imageView.setLoadingLayout(mLoadingView) imageView.enableLoading() } imageView.scaleType = mImageScaleType imageView.isZoomable = mIsZoomable var okHttpClient = OkHttpClient.Builder() val okHttpDownloader = OkHttp3Downloader(enableTls12OnPreLollipop(okHttpClient).build()) val picasso = Picasso.Builder(container.context).downloader(okHttpDownloader).build() if (itemList[position].imageUrl == null) { picasso .load(itemList[position].drawableId!!) .into(imageView, object : Callback { override fun onSuccess() { imageView.disableLoading() } override fun onError(e: java.lang.Exception?) { imageView.disableLoading() } }) } else { picasso.load(itemList[position].imageUrl) .into(imageView, object : Callback { override fun onSuccess() { imageView.disableLoading() } override fun onError(e: java.lang.Exception?) { imageView.disableLoading() } }) } container.addView(itemView) return itemView } override fun destroyItem(container: ViewGroup, position: Int, obj: Any) { container.removeView(obj as View) } fun setScaleType(type: ImageView.ScaleType) { mImageScaleType = type } fun setLoadingView(mLoadingView: View?) { if (mLoadingView != null) { this.mLoadingView = mLoadingView } } fun setIsZoomable(bool: Boolean) { mIsZoomable = bool } }
0
Kotlin
0
0
c893f87a03c7103bcbfcbcd2157dadf7bbfc4e5c
3,589
KM-Popup-Image-Slider
The Unlicense
core/domain/src/main/kotlin/org/michaelbel/movies/domain/exceptions/DeleteSessionException.kt
michaelbel
115,437,864
false
null
package org.michaelbel.movies.domain.exceptions object DeleteSessionException: Exception()
4
Kotlin
21
81
00b1cd807a4e7c894b0792ebb668e4cbcedc5605
91
movies
Apache License 2.0
ok-blogs-transport-mp/src/commonMain/kotlin/ru/otus/kotlin/blogs/transport/kmp/models/categories/MpRequestCategoryRead.kt
otuskotlin
327,215,631
false
null
package ru.otus.kotlin.blogs.transport.kmp.models.categories import kotlinx.serialization.SerialName import kotlinx.serialization.Serializable import ru.otus.kotlin.blogs.transport.kmp.models.common.IMpDebug import ru.otus.kotlin.blogs.transport.kmp.models.common.IMpRequest import ru.otus.kotlin.blogs.transport.kmp.models.common.MpMessage import ru.otus.kotlin.blogs.transport.kmp.models.common.MpWorkModeDto @Serializable @SerialName("MpRequestCategoryDelete") data class MpRequestCategoryDelete( override val requestId: String? = null, override val onResponse: String? = null, override val startTime: String? = null, override val debug: IMpDebug? = null, val categoryId: String? ): IMpRequest, MpMessage() { @Serializable data class Debug( override val mode: MpWorkModeDto? ) : IMpDebug }
1
Kotlin
0
0
a23a05a80ee90c6c02a200f4dc6acde31b80bc76
835
otuskotlin-202012-blogs-sa
MIT License
app/src/main/java/study/me/please/ui/session/lobby/SessionLobbyRepository.kt
Let-s-build-something
683,485,839
false
{"Kotlin": 999288}
package study.me.please.ui.session.lobby import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.withContext import study.me.please.data.io.SessionIO import study.me.please.data.room.PreferencesDao import study.me.please.data.room.SessionDao import study.me.please.ui.components.preference_chooser.PreferencePackRepository import javax.inject.Inject /** Proxy for calling network end points */ class SessionLobbyRepository @Inject constructor( private val sessionDao: SessionDao, override val preferencesDao: PreferencesDao ): PreferencePackRepository { /** returns all sessions and calculates the amount of questions in each */ suspend fun getAllSessions(): List<SessionIO>? { return withContext(Dispatchers.IO) { val sessions = sessionDao.getAllSessions() withContext(Dispatchers.Default) { sessions?.forEach { session -> //TODO /*session.questionCount = session.collectionUidList.sumOf { it.questionUidList.size } .plus(session.questionUidList.size)*/ } } sessions } } /** saves a session */ suspend fun saveSession(session: SessionIO) { return withContext(Dispatchers.IO) { sessionDao.insertSession(session) } } /** deletes sessions based on their uid [uids] */ suspend fun deleteSessions(uids: Set<String>) { return withContext(Dispatchers.IO) { sessionDao.deleteSessions(uids) } } }
0
Kotlin
0
0
4fec69fa87b4cf60f490c7150420d9cc677ecff9
1,561
Study-me-please
Apache License 2.0
app/src/main/java/com/greenart7c3/nostrsigner/ui/components/AppTitle.kt
greenart7c3
671,206,453
false
{"Kotlin": 189104, "Shell": 1310}
package com.greenart7c3.nostrsigner.ui.components import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.material3.Text import androidx.compose.runtime.Composable import androidx.compose.ui.Modifier import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.text.style.TextAlign @Composable fun AppTitle(appName: String) { Text( modifier = Modifier.fillMaxWidth(), text = appName, fontWeight = FontWeight.Bold, textAlign = TextAlign.Center ) }
1
Kotlin
3
55
c3cc32857e79e7ea8dac98f1960038e38bef7471
526
Amber
MIT License
feature/accounts/src/main/java/org/expenny/feature/accounts/overview/contract/AccountOverviewContract.kt
expenny-application
712,607,222
false
{"Kotlin": 1032337}
package org.expenny.feature.accounts.overview.contract import androidx.compose.runtime.Stable import kotlinx.collections.immutable.ImmutableList import kotlinx.collections.immutable.toImmutableList import org.expenny.core.common.types.AccountTrendType import org.expenny.core.common.types.IntervalType import org.expenny.core.ui.data.AmountUi import org.expenny.core.ui.data.CategoryStatementUi import org.expenny.core.ui.data.ItemUi import org.expenny.core.ui.data.SingleSelectionUi import org.expenny.core.ui.reducers.IntervalTypeStateReducer import org.expenny.feature.accounts.overview.model.AccountOverviewChartUi @Stable data class AccountOverviewState( val overviewChart: AccountOverviewChartUi = AccountOverviewChartUi(), val totalValue: AmountUi? = null, val trendType: AccountTrendType = AccountTrendType.Balance, val trendTypes: ImmutableList<AccountTrendType> = AccountTrendType.values().toList().toImmutableList(), val intervalState: IntervalTypeStateReducer.State = IntervalTypeStateReducer.State(), val statements: List<CategoryStatementUi> = emptyList(), val dialog: Dialog? = null, ) { sealed interface Dialog { data class IntervalTypesDialog( val data: List<ItemUi<IntervalType>>, val selection: SingleSelectionUi<IntervalType> ) : Dialog } } sealed interface AccountOverviewAction { sealed interface Dialog : AccountOverviewAction { class OnIntervalTypeSelect(val selection: SingleSelectionUi<IntervalType>) : Dialog data object OnDialogDismiss : Dialog } class OnTrendTypeChange(val type: AccountTrendType) : AccountOverviewAction data object OnSelectIntervalClick : AccountOverviewAction data object OnNextIntervalClick : AccountOverviewAction data object OnPreviousIntervalClick : AccountOverviewAction } sealed interface AccountOverviewEvent { }
0
Kotlin
3
40
8d4b02fdbcae0fbb8ce3d1910020b4e251866925
1,889
expenny-android
Apache License 2.0
app/src/main/kotlin/com/gcode/imaker/ui/model/Communicate.kt
SakurajimaMaii
321,078,799
false
{"Kotlin": 129160}
/* * MIT License * * Copyright (c) 2021 码上夏雨 * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package com.gcode.imaker.ui.model import androidx.annotation.DrawableRes import androidx.compose.animation.AnimatedVisibility import androidx.compose.animation.ExperimentalAnimationApi import androidx.compose.foundation.Image import androidx.compose.foundation.clickable import androidx.compose.foundation.layout.* import androidx.compose.material.MaterialTheme import androidx.compose.material.Text import androidx.compose.runtime.* import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.res.painterResource import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.sp import com.gcode.imaker.R import com.google.accompanist.coil.rememberCoilPainter /** *作者:created by HP on 2021/9/9 15:15 *邮箱:sakurajimamai2020@qq.com */ class Communicate( @DrawableRes val communicateIconId:Int, val communicateName:String, val communicateContent:String ) val communicates = listOf( Communicate( R.drawable.ic_github, "github", "https://github.com/SakurajimaMaii" ), Communicate( R.drawable.ic_twitter, "twitter", "https://twitter.com/Sakuraj61377782" ), Communicate( R.drawable.ic_csdn, "csdn", "https://blog.csdn.net/weixin_43699716" ) ) @ExperimentalAnimationApi @Composable fun CommunicateItem(communicate: Communicate){ var clickEvent by remember{ mutableStateOf(false) } Row( modifier = Modifier .fillMaxWidth() .clickable { clickEvent = !clickEvent }, verticalAlignment = Alignment.CenterVertically ){ Image( painter = painterResource(id = communicate.communicateIconId), contentDescription = null ) Column( modifier = Modifier.padding(10.dp, 5.dp) ) { Text( text = communicate.communicateName, fontWeight = FontWeight.Bold, fontSize = 20.sp, color = MaterialTheme.colors.onPrimary ) Text( text = communicate.communicateContent, fontSize = 10.sp, color = MaterialTheme.colors.onPrimary ) } } }
2
Kotlin
0
7
3d6a166dfeb6ba13e1eeb420225a9463f877f83d
3,462
Maker-Compose-Samples
MIT License
compiler/testData/debug/stepping/callWithCallInArguments.kt
JetBrains
3,432,266
false
null
// FILE: test.kt class A fun bar(a: A) = A() fun box() { val a = A() bar( bar( bar(a) ) ) } // EXPECTATIONS // test.kt:8 box // test.kt:3 <init> // test.kt:8 box // test.kt:11 box // test.kt:5 bar // test.kt:3 <init> // test.kt:5 bar // test.kt:10 box // test.kt:5 bar // test.kt:3 <init> // test.kt:5 bar // test.kt:9 box // test.kt:5 bar // test.kt:3 <init> // test.kt:5 bar // test.kt:9 box // test.kt:14 box
132
null
5074
40,992
57fe6721e3afb154571eb36812fd8ef7ec9d2026
472
kotlin
Apache License 2.0
feature/tasks/model/src/main/java/app/taskify/feature/tasks/model/CategoryDisplayModel.kt
usdaves
656,260,254
false
null
/* * Copyright 2023 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and limitations under the License. */ package app.taskify.feature.tasks.model import androidx.annotation.DrawableRes data class CategoryDisplayModel( val id: Long?, val name: String, val isCheckable: Boolean, val isChecked: Boolean, @DrawableRes val categoryIcon: Int?, val onCategoryClicked: () -> Unit, )
0
Kotlin
0
0
4830b61fec44b2913ea80594ccff189da2d70ba8
897
Taskify
Apache License 2.0
data/src/main/java/com/criticalgnome/data/service/JsonPlaceholderService.kt
CriticalGnome
624,905,580
false
{"Kotlin": 128644}
package com.criticalgnome.data.service import com.criticalgnome.data.entity.AlbumData import com.criticalgnome.data.entity.CommentData import com.criticalgnome.data.entity.PhotoData import com.criticalgnome.data.entity.PostData import com.criticalgnome.data.entity.TodoData import com.criticalgnome.data.entity.UserData import retrofit2.Response import retrofit2.http.Body import retrofit2.http.DELETE import retrofit2.http.GET import retrofit2.http.POST import retrofit2.http.PUT import retrofit2.http.Path interface JsonPlaceholderService { // region posts @GET("/posts") suspend fun getPosts(): Response<List<PostData>> @GET("/posts/{id}") suspend fun getPost(@Path("id") id: Int): Response<PostData> @GET("/post/{id}/comments") suspend fun getPostComments(@Path("id") id: Int): Response<List<CommentData>> @POST("/posts") suspend fun postPosts(@Body posts: List<PostData>): Response<List<PostData>> @PUT("/posts/{id}") suspend fun putPost(@Path("id") id: Int, @Body post: PostData): Response<PostData> @DELETE("/posts/{id}") suspend fun deletePost(@Path("id") id: Int): Response<Unit> // endregion // region comments @GET("/comments") suspend fun getComments(): Response<List<CommentData>> @GET("/comments/{id}") suspend fun getComment(@Path("id") id: Int): Response<CommentData> // endregion // region users @GET("/users") suspend fun getUsers(): Response<List<UserData>> @GET("/users/{id}") suspend fun getUser(@Path("id") id: Int): Response<UserData> // endregion // region todos @GET("/todos") suspend fun getTodos(): Response<List<TodoData>> @GET("/todos/{id}") suspend fun getTodo(@Path("id") id: Int): Response<TodoData> // endregion // region photos @GET("/photos") suspend fun getPhotos(): Response<List<PhotoData>> @GET("/photos/{id}") suspend fun getPhoto(@Path("id") id: Int): Response<PhotoData> // endregion // region albums @GET("/albums") suspend fun getAlbums(): Response<List<AlbumData>> @GET("/albums/{id}") suspend fun getAlbum(@Path("id") id: Int): Response<AlbumData> // endregion companion object { const val BASE_URL = "https://jsonplaceholder.typicode.com" } }
0
Kotlin
1
0
9d0cdaf4147042d3a5d63d8fd8f75e273ce55cc7
2,313
CleanArchitectureDemo
Apache License 2.0
clientprotocol/src/commonMain/generated/org/inthewaves/kotlinsignald/clientprotocol/v1/structures/IdentityKey.kt
inthewaves
398,221,861
false
null
// File is generated by ./gradlew generateSignaldClasses --- do not edit unless reformatting package org.inthewaves.kotlinsignald.clientprotocol.v1.structures import kotlinx.serialization.SerialName import kotlinx.serialization.Serializable @Serializable public data class IdentityKey( /** * the first time this identity key was seen */ public val added: Long? = null, /** * Example: "373453558586758076680580548714989751943247272727416091564451" */ @SerialName("safety_number") public val safetyNumber: String? = null, /** * base64-encoded QR code data */ @SerialName("qr_code_data") public val qrCodeData: String? = null, /** * One of TRUSTED_UNVERIFIED, TRUSTED_VERIFIED or UNTRUSTED */ @SerialName("trust_level") public val trustLevel: String? = null )
11
Kotlin
1
2
6f48a612fc307c08e44af25f826bb627e3e4f499
843
kotlin-signald
MIT License
modules/mockk/src/commonTest/kotlin/io/mockk/ManyAnswersAnswerTest.kt
mockk
107,331,132
false
null
package io.mockk import kotlin.test.Test import kotlin.test.assertEquals class ManyAnswersAnswerTest { @Test fun simpleList() { val many = many(1, 2, 3) assertEquals(listOf(1, 2, 3), many.toList()) } @Test fun nestedList() { val many = many(many(1, 2, 3), many(4, 5, 6)) assertEquals(listOf(1, 2, 3, 4, 5, 6), many.toList()) } @Test fun mixedList() { val many = many( const(0), many(1, 2, 3), const(4), many(5, 6, 7), const(8) ) assertEquals(listOf(0, 1, 2, 3, 4, 5, 6, 7, 8), many.toList()) } private fun <T> many(vararg args: T) = many(*args.map { const(it) }.toTypedArray()) private fun <T> many(vararg args: Answer<T>) = ManyAnswersAnswer(listOf(*args)) private fun <T> const(value: T) = ConstantAnswer(value) private fun <T> ManyAnswersAnswer<T>.toList(): List<T> { val res = mutableListOf<T>() while (hasMore) { res.add(answer(mockk())) } return res.toList() } }
296
null
344
5,426
79abc96d3235710d61beaf677ea1349ba12eea0c
1,095
mockk
Apache License 2.0
adam/src/main/kotlin/com/malinskiy/adam/request/sync/v2/ListFileRequest.kt
Malinskiy
200,235,738
false
{"Kotlin": 770806, "Shell": 1553, "Java": 1414}
/* * 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.malinskiy.adam.request.sync.v2 import com.malinskiy.adam.Const import com.malinskiy.adam.annotation.Features import com.malinskiy.adam.extension.toInt import com.malinskiy.adam.extension.toLong import com.malinskiy.adam.extension.toUInt import com.malinskiy.adam.extension.toULong import com.malinskiy.adam.extension.writeSyncRequest import com.malinskiy.adam.request.ComplexRequest import com.malinskiy.adam.request.Feature import com.malinskiy.adam.request.ValidationResponse import com.malinskiy.adam.request.sync.model.FileEntryV2 import com.malinskiy.adam.transport.Socket import com.malinskiy.adam.transport.withDefaultBuffer import java.time.Instant @Features(Feature.LS_V2) class ListFileRequest( private val remotePath: String, private val supportedFeatures: List<Feature> ) : ComplexRequest<List<FileEntryV2>>() { override fun validate(): ValidationResponse { val response = super.validate() return if (!response.success) { response } else if (remotePath.length > Const.MAX_REMOTE_PATH_LENGTH) { ValidationResponse(false, ValidationResponse.pathShouldNotBeLong()) } else if (!supportedFeatures.contains(Feature.LS_V2)) { ValidationResponse(false, ValidationResponse.missingFeature(Feature.LS_V2)) } else { ValidationResponse.Success } } override suspend fun readElement(socket: Socket): List<FileEntryV2> { socket.writeSyncRequest(Const.Message.LIST_V2, remotePath) withDefaultBuffer { val data = array() // val bytes = ByteArray(72) val result = mutableListOf<FileEntryV2>() loop@ while (true) { socket.readFully(data, 0, 4) when { data.copyOfRange(0, 4).contentEquals(Const.Message.DENT_V2) -> { socket.readFully(data, 0, 72) val nameLength = data.copyOfRange(68, 72).toInt() val error = data.copyOfRange(0, 4).toUInt() val dev = data.copyOfRange(4, 12).toULong() val ino = data.copyOfRange(12, 20).toULong() val mode = data.copyOfRange(20, 24).toUInt() val nlink = data.copyOfRange(24, 28).toUInt() val uid = data.copyOfRange(28, 32).toUInt() val gid = data.copyOfRange(32, 36).toUInt() val size = data.copyOfRange(36, 44).toULong() val atime = Instant.ofEpochSecond(data.copyOfRange(44, 52).toLong()) val mtime = Instant.ofEpochSecond(data.copyOfRange(52, 60).toLong()) val ctime = Instant.ofEpochSecond(data.copyOfRange(60, 68).toLong()) socket.readFully(data, 0, nameLength) result.add( FileEntryV2( error = error, dev = dev, ino = ino, mode = mode, nlink = nlink, uid = uid, gid = gid, size = size, atime = atime, mtime = mtime, ctime = ctime, name = String(data, 0, nameLength, Const.DEFAULT_TRANSPORT_ENCODING) ) ) } data.copyOfRange(0, 4).contentEquals(Const.Message.DONE) -> break@loop else -> break@loop } } return result } } override fun serialize() = createBaseRequest("sync:") }
3
Kotlin
31
441
f206bc96e4927ce07e5421f9ac2449b34ac3027c
4,491
adam
Apache License 2.0
GeoQ/app/src/main/java/com/example/geoq/mvps/views/QuestInformationView.kt
iShamSLam
211,938,667
false
{"YAML": 3, "Text": 1, "Gradle": 3, "Java Properties": 2, "Shell": 1, "Ignore List": 2, "Batchfile": 1, "JSON": 1, "Proguard": 1, "Kotlin": 62, "XML": 56, "Java": 1}
package com.example.geoq.mvps.views import com.arellomobile.mvp.MvpView import com.example.geoq.OtherClasses.StepItem interface QuestInformationView : MvpView { fun showInformation() fun deleteQuest() fun subcribeToQuest() }
1
null
1
1
84a852b3184ddcdfed891c6dea9cbe41d2e815cd
238
GeoQ
Apache License 2.0
src/main/kotlin/me/xiaozhangup/picturelogin/data/table/SQLTable.kt
HAPPYLAND-Dev
624,488,865
false
{"INI": 2, "Gradle Kotlin DSL": 2, "Shell": 1, "Markdown": 1, "Batchfile": 1, "Kotlin": 5, "Java": 8}
package me.xiaozhangup.picturelogin.data.table import me.xiaozhangup.picturelogin.data.DatabaseManager import taboolib.module.database.Host import taboolib.module.database.SQL import taboolib.module.database.Table interface SQLTable { val table: Table<Host<SQL>, SQL> fun createTable() { table.createTable(DatabaseManager.dataSource) } }
1
null
1
1
651418a00508f6a3234e13780dabfee60a577694
363
PictureLogin-Taboo
Creative Commons Zero v1.0 Universal
app/src/test/java/com/primeholding/primesampleapp/TestSchedulerRule.kt
StanevPrime
165,937,983
false
null
package com.primeholding.primesampleapp import io.reactivex.android.plugins.RxAndroidPlugins import io.reactivex.plugins.RxJavaPlugins import io.reactivex.schedulers.TestScheduler import org.junit.rules.TestRule import org.junit.runner.Description import org.junit.runners.model.Statement class TestSchedulerRule : TestRule { val thread = TestScheduler() get() = field override fun apply(base: Statement, description: Description?): Statement { return object : Statement() { @Throws(Throwable::class) override fun evaluate() { RxJavaPlugins.setIoSchedulerHandler { thread } RxJavaPlugins.setComputationSchedulerHandler { thread } RxJavaPlugins.setNewThreadSchedulerHandler { thread } RxAndroidPlugins.setInitMainThreadSchedulerHandler { thread } try { base.evaluate() } finally { RxJavaPlugins.reset() RxAndroidPlugins.reset() } } } } }
1
Kotlin
1
2
1e5610489d2f8439e5b857a285f2a01ccf38fa7e
1,085
PrimeHoldingAndroidTemplatesSample
MIT License
plugins/kotlin/idea/tests/testData/quickfix/replaceWithSafeCall/lineBreak.kt
JetBrains
2,489,216
false
null
// "Replace with safe (?.) call" "true" // WITH_STDLIB fun foo(a: String?) { val b = a .<caret>length }
233
null
4912
15,461
9fdd68f908db0b6bb6e08dc33fafb26e2e4712af
120
intellij-community
Apache License 2.0
materialintro/src/main/java/com/codertainment/materialintro/view/MaterialIntroView.kt
shripal17
238,678,867
false
null
package com.codertainment.materialintro.view import android.annotation.TargetApi import android.app.Activity import android.content.Context import android.graphics.* import android.graphics.drawable.Drawable import android.os.Build import android.os.Handler import android.util.AttributeSet import android.util.TypedValue import android.view.* import android.widget.ImageView import android.widget.RelativeLayout import android.widget.TextView import androidx.annotation.ColorInt import androidx.annotation.DrawableRes import androidx.annotation.LayoutRes import androidx.cardview.widget.CardView import com.codertainment.materialintro.MaterialIntroConfiguration import com.codertainment.materialintro.R import com.codertainment.materialintro.animation.AnimationFactory import com.codertainment.materialintro.animation.AnimationListener import com.codertainment.materialintro.animation.MaterialIntroListener import com.codertainment.materialintro.sequence.SkipLocation import com.codertainment.materialintro.shape.* import com.codertainment.materialintro.shape.Circle import com.codertainment.materialintro.shape.Rect import com.codertainment.materialintro.target.Target import com.codertainment.materialintro.target.ViewTarget import com.codertainment.materialintro.utils.Constants import com.codertainment.materialintro.utils.Utils import com.codertainment.materialintro.utils.preferencesManager import com.google.android.material.button.MaterialButton class MaterialIntroView : RelativeLayout { /** * Mask color */ var maskColor = Constants.DEFAULT_MASK_COLOR /** * MaterialIntroView will start * showing after delayMillis seconds * passed */ var delayMillis = Constants.DEFAULT_DELAY_MILLIS /** * We don't draw MaterialIntroView * until isReady field set to true */ private var isReady = false /** * Show MaterialIntroView * with fade in animation if * this is enabled. */ var isFadeInAnimationEnabled = true /** * Dismiss MaterialIntroView * with fade out animation if * this is enabled. */ var isFadeOutAnimationEnabled = true /** * Animation duration */ var fadeAnimationDurationMillis = Constants.DEFAULT_FADE_DURATION /** * targetShape focus on target * and clear circle to focus */ private lateinit var targetShape: Shape /** * Focus Type */ var focusType = Focus.ALL /** * FocusGravity type */ var focusGravity = FocusGravity.CENTER /** * Target View */ private lateinit var myTargetView: Target /** * Eraser */ private lateinit var eraser: Paint /** * Handler will be used to * delay MaterialIntroView */ private lateinit var myHandler: Handler /** * All views will be drawn to * this bitmap and canvas then * bitmap will be drawn to canvas */ private var bitmap: Bitmap? = null private var canvas: Canvas? = null /** * Circle padding */ var padding = Constants.DEFAULT_TARGET_PADDING /** * Radius for the Rectangular shape */ var radius = Constants.DEFAULT_RADIUS /** * Layout myWidth/myHeight */ private var myWidth = 0 private var myHeight = 0 /** * Dismiss on touch any where */ var dismissOnTouch = false /** * Info card view container */ private lateinit var infoView: RelativeLayout /** * Info CardView */ private lateinit var infoCardView: CardView /** * Info TextView */ private lateinit var infoTextView: TextView /** * Info dialog will be shown * If this value true */ var isInfoEnabled = true /** * Info Text */ var infoText: CharSequence = "" /** * Info Text Color */ @ColorInt var infoTextColor: Int? = null /** * Info Text Size in sp */ var infoTextSize: Float? = null /** * Info Text Alignment, Use View.TEXT_ALIGNMENT_ */ var infoTextAlignment: Int = View.TEXT_ALIGNMENT_CENTER /** * Info Text Custom Typeface */ var infoTextTypeface: Typeface? = null /** * Card View Background Color */ @ColorInt var infoCardBackgroundColor: Int? = null /** * Help Dialog Icon */ private lateinit var helpIconView: ImageView /** * Help Icon will be shown if this is true */ var isHelpIconEnabled = true /** * Drawable resource to set as help icon */ @DrawableRes var helpIconResource: Int? = null /** * Drawable to set as help icon */ var helpIconDrawable: Drawable? = null /** * Tint Help Icon */ @ColorInt var helpIconColor: Int? = null /** * Custom View for info card */ var infoCustomView: View? = null /** * Layout Resource for custom view */ @LayoutRes var infoCustomViewRes: Int? = null /** * Dot view will appear center of * cleared target area */ private lateinit var dotView: ImageView /** * Dot View will be shown if * this is true */ var isDotViewEnabled = true /** * Dot View animated with zoom in & zoom out animation if this is true */ var isDotAnimationEnabled = true /** * Tint Dot Icon */ @ColorInt var dotIconColor: Int? = null /** * Check using this Id whether user learned * or not. */ var viewId: String = "" /** * When layout completed, we set this true * Otherwise onGlobalLayoutListener stuck on loop. */ private var isLayoutCompleted = false /** * Notify user when MaterialIntroView is dismissed */ var materialIntroListener: MaterialIntroListener? = null /** * Perform click operation to target * if this is true */ var isPerformClick = false /** * Show MIV only once */ var showOnlyOnce = true /** * Mark view as displayed only when user clicks */ var userClickAsDisplayed = true /** * Shape of target */ var shapeType = ShapeType.CIRCLE /** * Use custom shape */ var customShape: Shape? = null internal var showSkip = false /** * Location of the skip button */ var skipLocation: SkipLocation = SkipLocation.BOTTOM_LEFT /** * Text for skip button */ private var skipText: CharSequence = "Skip" /** * Apply custom styling to the skip button */ private var skipButtonStyling: MaterialButton.() -> Unit = {} lateinit var skipButton: MaterialButton private var statusBarHeight = 0 var skipButtonMargin = Utils.dpToPx(16) private var dismissed = false constructor(context: Context) : super(context) { init() } constructor(context: Context, attrs: AttributeSet) : super(context, attrs) { init() } constructor(context: Context, attrs: AttributeSet, defStyleAttr: Int) : super(context, attrs, defStyleAttr) { init() } @TargetApi(Build.VERSION_CODES.LOLLIPOP) constructor(context: Context, attrs: AttributeSet, defStyleAttr: Int, defStyleRes: Int) : super(context, attrs, defStyleAttr, defStyleRes) { init() } private fun init() { setWillNotDraw(false) visibility = INVISIBLE /** * initialize objects */ skipButton = MaterialButton(context) myHandler = Handler() eraser = Paint().apply { color = -0x1 xfermode = PorterDuffXfermode(PorterDuff.Mode.CLEAR) flags = Paint.ANTI_ALIAS_FLAG } fitsSystemWindows = true } override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) { super.onMeasure(widthMeasureSpec, heightMeasureSpec) myWidth = measuredWidth myHeight = measuredHeight } override fun onDraw(canvas: Canvas) { super.onDraw(canvas) if (!isReady) return if (bitmap == null) { bitmap?.recycle() bitmap = Bitmap.createBitmap(myWidth, myHeight, Bitmap.Config.ARGB_8888) this.canvas = Canvas(bitmap!!) } /** * Draw mask */ this.canvas?.drawColor(Color.TRANSPARENT, PorterDuff.Mode.CLEAR) this.canvas?.drawColor(maskColor) /** * Clear focus area */ targetShape.draw(this.canvas!!, eraser, radius) canvas.drawBitmap(bitmap!!, 0f, 0f, null) } /** * Perform click operation when user * touches on target circle. * * @param event * @return */ override fun onTouchEvent(event: MotionEvent): Boolean { val xT = event.x val yT = event.y val isTouchOnFocus = targetShape.isTouchOnFocus(xT.toDouble(), yT.toDouble()) when (event.action) { MotionEvent.ACTION_DOWN -> { if (isTouchOnFocus && isPerformClick) { myTargetView.view.apply { isPressed = true invalidate() } } return true } MotionEvent.ACTION_UP -> { if (isTouchOnFocus || dismissOnTouch) { dismiss() } if (isTouchOnFocus && isPerformClick) { myTargetView.view.apply { performClick() isPressed = true invalidate() isPressed = false invalidate() } } return true } } return super.onTouchEvent(event) } var targetView get() = myTargetView.view set(value) { if (value.tag is String) { value.tag?.toString()?.let { viewId = it } } myTargetView = ViewTarget(value) } /** * Shows material view with fade in * animation * * @param activity */ fun show(activity: Activity) { if (context.preferencesManager.isDisplayed(viewId)) { materialIntroListener?.onIntroDone(false, viewId) return } if (!::targetShape.isInitialized) { targetShape = when { customShape != null -> { customShape!! } shapeType == ShapeType.CIRCLE -> { Circle(myTargetView, focusType, focusGravity, padding) } else -> { Rect(myTargetView, focusType, focusGravity, padding) } } } if (isInfoEnabled) { infoView = LayoutInflater.from(context).inflate(R.layout.material_intro_card, null) as RelativeLayout infoCardView = infoView.findViewById(R.id.info_card_view) infoTextView = infoView.findViewById(R.id.info_text) helpIconView = infoView.findViewById(R.id.info_icon) if (infoCustomViewRes != null || infoCustomView != null) { infoCustomViewRes?.let { infoCustomView = LayoutInflater.from(context).inflate(it, infoCardView, false) } infoCardView.removeAllViews() infoCardView.addView(infoCustomView) } else { infoCardBackgroundColor?.let { infoCardView.setCardBackgroundColor(it) } infoTextView.text = infoText infoTextView.textAlignment = infoTextAlignment infoTextView.typeface = infoTextTypeface infoTextSize?.let { infoTextView.setTextSize(TypedValue.COMPLEX_UNIT_SP, it) } infoTextColor?.let { infoTextView.setTextColor(it) } if (isHelpIconEnabled) { helpIconResource?.let { helpIconView.setImageResource(it) } helpIconDrawable?.let { helpIconView.setImageDrawable(it) } helpIconColor?.let { helpIconView.setColorFilter(it) } } } } if (isDotViewEnabled) { dotView = LayoutInflater.from(context).inflate(R.layout.dot_view, null) as ImageView dotView.measure(MeasureSpec.UNSPECIFIED, MeasureSpec.UNSPECIFIED) dotIconColor?.let { dotView.setColorFilter(it, PorterDuff.Mode.SRC_IN) } } if (showSkip) { val rect = android.graphics.Rect() activity.window.decorView.getWindowVisibleDisplayFrame(rect) statusBarHeight = rect.top } viewTreeObserver.addOnGlobalLayoutListener(object : ViewTreeObserver.OnGlobalLayoutListener { override fun onGlobalLayout() { targetShape.reCalculateAll() if (targetShape.point.y != 0 && !isLayoutCompleted) { if (isInfoEnabled) { setInfoLayout() } if (isDotViewEnabled) { setDotViewLayout() } if (showSkip) { setSkipButtonLayout() } removeOnGlobalLayoutListener(this@MaterialIntroView, this) } } }) (activity.window.decorView as ViewGroup).addView(this) isReady = true myHandler.postDelayed( { if (isFadeInAnimationEnabled) AnimationFactory.animateFadeIn( this@MaterialIntroView, fadeAnimationDurationMillis, object : AnimationListener.OnAnimationStartListener { override fun onAnimationStart() { visibility = VISIBLE } }) else visibility = VISIBLE }, delayMillis ) if (showOnlyOnce && !userClickAsDisplayed) { context.preferencesManager.setDisplayed(viewId) } } /** * Dismiss Material Intro View */ fun dismiss() { //prevent from firing dismiss() method multiple times when quickly clicking the layer if (dismissed) { return } dismissed = true if (showOnlyOnce && userClickAsDisplayed) { context.preferencesManager.setDisplayed(viewId) } if (isFadeOutAnimationEnabled) { AnimationFactory.animateFadeOut(this, fadeAnimationDurationMillis, object : AnimationListener.OnAnimationEndListener { override fun onAnimationEnd() { removeSelf() } }) } else { removeSelf() } } private fun removeSelf() { visibility = GONE removeMaterialView() materialIntroListener?.onIntroDone(true, viewId) } private fun removeMaterialView() { if (parent != null) (parent as ViewGroup).removeView(this) } /** * locate info card view above/below the * circle. If circle's Y coordinate is bigger than * Y coordinate of root view, then locate cardview * above the circle. Otherwise locate below. */ private fun setInfoLayout() { myHandler.post { isLayoutCompleted = true infoParent?.removeView(infoView) val infoDialogParams = LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.FILL_PARENT) if (targetShape.point.y < myHeight / 2) { infoView.gravity = Gravity.TOP infoDialogParams.setMargins( 0, targetShape.point.y + targetShape.height / 2, 0, 0 ) } else { infoView.gravity = Gravity.BOTTOM infoDialogParams.setMargins( 0, 0, 0, myHeight - (targetShape.point.y + targetShape.height / 2) + 2 * targetShape.height / 2 ) } infoView.layoutParams = infoDialogParams infoView.postInvalidate() addView(infoView) if (!isHelpIconEnabled) { helpIconView.visibility = GONE } infoView.visibility = VISIBLE } } private fun setDotViewLayout() { myHandler.post { dotParent?.removeView(dotView) val dotViewLayoutParams = LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT) dotViewLayoutParams.height = Utils.dpToPx(Constants.DEFAULT_DOT_SIZE) dotViewLayoutParams.width = Utils.dpToPx(Constants.DEFAULT_DOT_SIZE) dotViewLayoutParams.setMargins( targetShape.point.x - (dotViewLayoutParams.width / 2), targetShape.point.y - (dotViewLayoutParams.height / 2), 0, 0 ) dotView.layoutParams = dotViewLayoutParams dotView.postInvalidate() addView(dotView) dotView.visibility = VISIBLE if (isDotAnimationEnabled) { AnimationFactory.performAnimation(dotView) } } } private fun setSkipButtonLayout() { myHandler.post { val s = Point() skipButton.text = skipText skipButton.apply { skipButtonStyling() } display.getSize(s) skipButton.measure(s.x, s.y) val skipButtonLayoutParams = LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT) var topMargin = 0 var leftMargin = 0 val defaultMargin = skipButtonMargin when (skipLocation) { SkipLocation.BOTTOM_LEFT -> { leftMargin = defaultMargin topMargin = s.y - skipButton.measuredHeight - defaultMargin } SkipLocation.BOTTOM_RIGHT -> { leftMargin = s.x - skipButton.measuredWidth - defaultMargin topMargin = s.y - skipButton.measuredHeight - defaultMargin } SkipLocation.TOP_LEFT -> { leftMargin = defaultMargin topMargin = defaultMargin + statusBarHeight } SkipLocation.TOP_RIGHT -> { leftMargin = s.x - skipButton.measuredWidth - defaultMargin topMargin = defaultMargin + statusBarHeight } } skipButtonLayoutParams.setMargins(leftMargin, topMargin, 0, 0) skipButton.layoutParams = skipButtonLayoutParams skipButton.postInvalidate() addView(skipButton) } } fun withConfig(config: MaterialIntroConfiguration?) { if (config == null) return this.maskColor = config.maskColor this.delayMillis = config.delayMillis this.isFadeInAnimationEnabled = config.isFadeInAnimationEnabled this.isFadeOutAnimationEnabled = config.isFadeOutAnimationEnabled this.fadeAnimationDurationMillis = config.fadeAnimationDurationMillis this.focusType = config.focusType this.focusGravity = config.focusGravity this.padding = config.padding this.radius = config.radius this.dismissOnTouch = config.dismissOnTouch this.isInfoEnabled = config.isInfoEnabled this.infoText = config.infoText this.infoTextColor = config.infoTextColor this.infoTextSize = config.infoTextSize this.infoTextAlignment = config.infoTextAlignment this.infoTextTypeface = config.infoTextTypeface this.infoCardBackgroundColor = config.infoCardBackgroundColor this.isHelpIconEnabled = config.isHelpIconEnabled this.helpIconResource = config.helpIconResource this.helpIconDrawable = config.helpIconDrawable this.helpIconColor = config.helpIconColor this.infoCustomView = config.infoCustomView this.infoCustomViewRes = config.infoCustomViewRes this.isDotViewEnabled = config.isDotViewEnabled this.isDotAnimationEnabled = config.isDotAnimationEnabled this.dotIconColor = config.dotIconColor config.viewId?.let { this.viewId = it } config.targetView?.let { this.targetView = it } this.isPerformClick = config.isPerformClick this.showOnlyOnce = config.showOnlyOnce this.userClickAsDisplayed = config.userClickAsDisplayed this.shapeType = config.shapeType this.customShape = config.customShape this.materialIntroListener = config.materialIntroListener this.skipLocation = config.skipLocation this.skipText = config.skipText this.skipButtonStyling = config.skipButtonStyling } private val infoParent get() = infoView.parent as ViewGroup? private val dotParent get() = dotView.parent as ViewGroup? companion object { @TargetApi(Build.VERSION_CODES.JELLY_BEAN) fun removeOnGlobalLayoutListener(v: View, listener: ViewTreeObserver.OnGlobalLayoutListener) { v.viewTreeObserver.removeOnGlobalLayoutListener(listener) } } }
7
null
11
53
6ae490d1cd089262cd87221d0092892be301129f
19,298
MaterialIntroView-v2
Apache License 2.0
MaterialMotionAnimationExample/app/src/main/java/com/velmurugan/materialmotionanimationexample/HomeDetailFragment.kt
velmurugan-murugesan
159,637,287
false
null
package com.velmurugan.materialmotionanimationexample import android.graphics.Color import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.fragment.app.Fragment import androidx.navigation.fragment.navArgs import com.bumptech.glide.Glide import com.bumptech.glide.request.RequestOptions import com.google.android.material.transition.MaterialContainerTransform import com.velmurugan.materialmotionanimationexample.databinding.HomeDetailFragmentBinding import com.velmurugan.materialmotionanimationexample.databinding.HomeFragmentBinding class HomeDetailFragment : Fragment() { lateinit var homeDetailBinding: HomeDetailFragmentBinding private val args: HomeDetailFragmentArgs by navArgs() private val movie: Movie by lazy { args.movie } override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View { homeDetailBinding = HomeDetailFragmentBinding.inflate(layoutInflater, container, false) return homeDetailBinding.root } override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) sharedElementEnterTransition = MaterialContainerTransform().apply { // Scope the transition to a view in the hierarchy so we know it will be added under // the bottom app bar but over the elevation scale of the exiting HomeFragment. drawingViewId = R.id.navController duration = ENTER_ANIM_DURATION scrimColor = Color.TRANSPARENT } } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) Glide.with(requireContext()).load(movie.imageUrl) .apply( RequestOptions() ) .centerCrop() .into(homeDetailBinding.imgMovie) homeDetailBinding.textTitle.text = movie.name homeDetailBinding.textTag.text = movie.category homeDetailBinding.textDesc.text = movie.desc } }
1
Java
1
6
8c2e8b2a0e8f33b5e8c0ea66890756e02577fa54
2,126
AndriodSamples
Apache License 2.0
app/src/main/java/ca/josephroque/bowlingcompanion/statistics/impl/series/HighSeriesOf9Statistic.kt
autoreleasefool
28,992,199
false
null
package ca.josephroque.bowlingcompanion.statistics.impl.series import android.os.Parcel import android.os.Parcelable import ca.josephroque.bowlingcompanion.R import ca.josephroque.bowlingcompanion.common.interfaces.parcelableCreator /** * Copyright (C) 2018 Joseph Roque * * Highest series of 3 games. */ class HighSeriesOf3Statistic(value: Int = 0) : HighSeriesStatistic(value) { // MARK: Overrides override val seriesSize = 3 override val titleId = Id override val id = Id.toLong() // MARK: Parcelable companion object { /** Creator, required by [Parcelable]. */ @Suppress("unused") @JvmField val CREATOR = parcelableCreator(::HighSeriesOf3Statistic) /** Unique ID for the statistic. */ const val Id = R.string.statistic_high_series_of_3 } /** * Construct this statistic from a [Parcel]. */ private constructor(p: Parcel): this(value = p.readInt()) }
30
Kotlin
5
6
be42ac42d6c842b3126a8841990e5f9c8c6af232
951
bowling-companion
Apache License 2.0
litho-widget-kotlin/src/test/kotlin/com/facebook/litho/widget/ExperimentalCardShadowTest.kt
dthabata
508,393,331
false
{"Java Properties": 51, "Markdown": 75, "Shell": 20, "Batchfile": 12, "Java": 1903, "Kotlin": 381, "C": 2, "C++": 44, "CMake": 2, "JavaScript": 7, "HTML": 1188, "CSS": 1, "Proguard": 9, "Haskell": 1}
/* * Copyright (c) Meta Platforms, Inc. and affiliates. * * 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.facebook.litho.kotlin.widget import com.facebook.litho.Style import com.facebook.litho.core.height import com.facebook.litho.core.width import com.facebook.litho.px import com.facebook.litho.testing.LithoViewRule import com.facebook.litho.testing.testrunner.LithoTestRunner import junit.framework.Assert.assertNotNull import org.assertj.core.api.Assertions.assertThat import org.junit.Rule import org.junit.Test import org.junit.runner.RunWith import org.robolectric.annotation.LooperMode /** Tests for [ExperimentalCardShadow] */ @LooperMode(LooperMode.Mode.LEGACY) @RunWith(LithoTestRunner::class) class ExperimentalCardShadowTest { @Rule @JvmField val lithoViewRule = LithoViewRule() @Test fun `ExperimentalCardShadow should render`() { val testLithoView = lithoViewRule.render { ExperimentalCardShadow(style = Style.width(100.px).height(100.px)) } // should find an ExperimentalCardShadow in the tree assertNotNull(testLithoView.findComponent(ExperimentalCardShadow::class)) // should mount an ExperimentalCardShadow assertThat(testLithoView.lithoView.mountItemCount).isEqualTo(1) } }
1
null
1
1
9d79ef8c8687cb4b85cf4f83cc1e945951fbaa31
1,763
litho
Apache License 2.0
src/main/java/eu/mshade/enderchest/listener/packet/MinecraftPacketToggleFlyingListener.kt
MSh4de
377,134,599
false
{"Java": 188452, "Kotlin": 133231, "Dockerfile": 140}
package eu.mshade.enderchest.listener.packet import eu.mshade.enderframe.entity.metadata.FlyingEntityMetadata import eu.mshade.enderframe.packetevent.MinecraftPacketToggleFlyingEvent import eu.mshade.mwork.event.EventListener class MinecraftPacketToggleFlyingListener : EventListener<MinecraftPacketToggleFlyingEvent> { override fun onEvent(event: MinecraftPacketToggleFlyingEvent) { val player = event.player val metadataKeyValueBucket = player.metadataKeyValueBucket metadataKeyValueBucket.setMetadataKeyValue(FlyingEntityMetadata(event.isFlying)) } }
1
null
1
1
dd53d29546e6c42f620e11493523799182357435
589
EnderChest
MIT License
app/src/main/java/org/stepik/android/view/course/mapper/DisplayPriceMapper.kt
StepicOrg
42,045,161
false
null
package org.stepik.android.view.course.mapper import android.content.Context import android.text.SpannedString import androidx.core.text.buildSpannedString import androidx.core.text.scale import androidx.core.text.strikeThrough import org.stepic.droid.R import javax.inject.Inject class DisplayPriceMapper @Inject constructor( private val context: Context ) { companion object { private const val RUB_FORMAT = "RUB" private const val USD_FORMAT = "USD" } fun mapToDisplayPriceWithCurrency(currencyCode: String, price: String): String = when (currencyCode) { RUB_FORMAT -> context.getString(R.string.rub_format, price.substringBefore('.')) USD_FORMAT -> context.getString(R.string.usd_format, price) else -> "$price $currencyCode" } fun mapToDiscountedDisplayPriceSpannedString(originalDisplayPrice: String, promoPrice: String, currencyCode: String = ""): SpannedString { val promoDisplayPrice = if (currencyCode.isNotEmpty()) { mapToDisplayPriceWithCurrency(currencyCode, promoPrice) } else { promoPrice } return buildSpannedString { append(context.getString(R.string.course_payments_purchase_in_web_with_price_promo)) append(promoDisplayPrice) append(" ") scale(0.9f) { strikeThrough { append(originalDisplayPrice) } } } } }
13
null
54
189
dd12cb96811a6fc2a7addcd969381570e335aca7
1,544
stepik-android
Apache License 2.0
fir-low-level-api-ide-impl/testData/outOfBlockProjectWide/funInCompanionObject.kt
JetBrains
278,369,660
false
null
class X { companion object { fun x() { a<caret> } } } // OUT_OF_BLOCK: false
0
Kotlin
29
71
b6789690db56407ae2d6d62746fb69dc99d68c84
114
intellij-kotlin
Apache License 2.0
app/src/main/kotlin/com/absinthe/libchecker/view/BaseBottomSheetDialogFragment.kt
fengyeshu
311,004,729
false
null
package com.absinthe.libchecker.view import android.os.Bundle import android.view.View import com.absinthe.libchecker.R import com.absinthe.libraries.utils.utils.UiUtils import com.google.android.material.bottomsheet.BottomSheetDialogFragment open class BaseBottomSheetDialogFragment : BottomSheetDialogFragment() { override fun onStart() { super.onStart() dialog?.window?.let { it.findViewById<View>(com.google.android.material.R.id.container).fitsSystemWindows = false UiUtils.setSystemBarStyle(it) } } override fun onActivityCreated(savedInstanceState: Bundle?) { super.onActivityCreated(savedInstanceState) dialog?.window?.attributes?.windowAnimations = R.style.DialogAnimation } }
1
null
1
1
342658fda785211dd38c07e1f146bf264038f4cc
770
LibChecker
Apache License 2.0
src/main/kotlin/com/tm/config/Data.kt
simonNozaki
270,195,018
false
null
package com.tm.config /** * データクラス宣言アノテーションクラス */ annotation class Data
1
null
1
1
9fc02da0db5529d34698dea0ed2ce810845b96d6
74
parallel-api
Apache License 2.0
Correctness/ValidFragment/src/main/java/net/twisterrob/lints/correctness/ValidFragmentViolationNonStaticKt.kt
TWiStErRob
169,976,671
false
{"Gradle": 120, "Java Properties": 1, "Shell": 1, "Text": 7, "Ignore List": 1, "Batchfile": 1, "Git Attributes": 1, "Markdown": 5, "XML": 108, "Java": 40, "Kotlin": 33, "TOML": 1, "INI": 3, "JSON5": 1, "YAML": 1, "Gradle Kotlin DSL": 1, "Proguard": 1}
package net.twisterrob.lints.correctness import android.app.Fragment class ValidFragmentViolationNonStaticKt { inner class Inner : Fragment() }
2
Java
0
5
b76f63bac73d284bf39184dd2490440973b00946
147
android-lint-examples
The Unlicense
app/src/main/java/memoizrlabs/com/tdd_playground/HeroScreenPresenter.kt
memoizr
64,115,089
false
{"Gradle": 4, "Java Properties": 2, "Shell": 1, "Text": 1, "Ignore List": 3, "Batchfile": 1, "Markdown": 1, "Proguard": 1, "Kotlin": 10, "XML": 8, "Java": 2}
package memoizrlabs.com.tdd_playground class HeroScreenPresenter(private val transactionRepository: TransactionRepository, private val transactionPrinter: TransactionPrinter) { fun onViewAttached(view: View) { transactionPrinter.printTransactions(transactionRepository.getAllTransactions(), view) } interface View: Printer {} }
0
Kotlin
0
0
1eefc316c33f4a7f0429bc9cf7876537f52fa729
378
tdd-playground-android
Apache License 2.0
app/src/main/java/uagrm/soe/awesomelogin/service/WebService.kt
kevinsubieta
177,921,637
false
{"Gradle": 3, "XML": 30, "Java Properties": 3, "Shell": 1, "Text": 1, "Batchfile": 1, "Markdown": 1, "Proguard": 1, "Ignore List": 1, "Kotlin": 20, "Java": 1}
package integgre.ma_volvo.api.service import integgre.ma_volvo.constanst.Constants import okhttp3.OkHttpClient import retrofit2.Call import retrofit2.Response import retrofit2.Retrofit import retrofit2.converter.gson.GsonConverterFactory import java.util.concurrent.TimeUnit import com.google.gson.GsonBuilder import com.google.gson.Gson import okhttp3.Credentials import okhttp3.Interceptor class WebService { private object Holder { val webInstance = getInstance() } companion object { val CONNECT_TIME_OUT = 90 val CONNECT_WRITE_OUT = 90 val TIME_OUT = 90 val USER_AUTH = "<KEY> val TOKEN_AUTH = "<KEY>" fun getInstance(): WebServiceInterface? { var stringToken = Credentials.basic(USER_AUTH, TOKEN_AUTH) var interceptor = AuthenticationInterceptor(stringToken) val gson = GsonBuilder() .setDateFormat("yyyy-MM-dd HH:mm:ss.SSS") .create() if (Holder.webInstance == null) { val okHttpClient = OkHttpClient.Builder().readTimeout(TIME_OUT.toLong(), TimeUnit.SECONDS) .connectTimeout(CONNECT_TIME_OUT.toLong(), TimeUnit.SECONDS) .writeTimeout(CONNECT_WRITE_OUT.toLong(), TimeUnit.SECONDS) .addInterceptor(interceptor) .build() val retrofit = Retrofit.Builder() .baseUrl(Constants.WEB_URI) .client(okHttpClient) .addConverterFactory(GsonConverterFactory.create(gson)) .build() return retrofit.create(WebServiceInterface::class.java) } return Holder.webInstance } } @Throws(Throwable::class) private fun prepareRequest(call: Call<*>): Response<*> { call.request() return call.execute() } @Throws(Throwable::class) fun consumeGetLoginUserWithService(userName: String, password: String) { } }
0
Kotlin
1
0
43718919c5b8dc5eacbf3af21b3378c4b9cf1743
2,082
BiometricPromptExample
The Unlicense
src/app/src/main/java/com/huawei/training/kotlin/utils/video/Constants.kt
huaweicodelabs
368,851,944
false
null
/** * Copyright 2020. Huawei Technologies Co., Ltd. All rights reserved. * * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * * http://www.apache.org/licenses/LICENSE-2.0 * * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.huawei.training.kotlin.utils.video /** * @author Huawei DTSE India * @since 2020 */ object Constants { /** * The constant PUSH_TOKEN. */ var PUSH_TOKEN = "push_token" /** * The constant COURSE_NAME. */ const val COURSE_NAME = "course_name" /** * The constant COURSE_DOCUMENTURL. */ const val COURSE_DOCUMENTURL = "course_documenturl" /** * The constant COURSE_ID. */ const val COURSE_ID = "course-id" /** * The constant VIDEO_PLAY_DATA. */ const val VIDEO_PLAY_DATA = "video_play_data" /** * The constant REQUEST_SIGN_IN_LOGIN_CODE. */ const val REQUEST_SIGN_IN_LOGIN_CODE = 1003 /** * The constant UID. */ const val UID = "UID" const val PRICE = "500" const val PROGRESS = 100 const val AD_TIMEOUT = 5000 const val MSG_AD_TIMEOUT = 1001 /** * The constant DELAY_MILLIS_500. */ // The delay time const val DELAY_MILLIS_500: Long = 500 /** * The constant DELAY_MILLIS_3000. */ const val DELAY_MILLIS_3000: Long = 3000 const val SLIDER_DELAY: Long = 4000 const val SLIDER_PERIOD: Long = 6000 /** * The constant DELAY_MILLIS_1000. */ const val DELAY_MILLIS_1000: Long = 1000 /** * The constant HEIGHT_DP. */ // Under the vertical screen SurfaceView height const val HEIGHT_DP = 300f /** * The constant PLAYING_WHAT. */ // present Current Position const val PLAYING_WHAT = 1 /** * The constant UPDATE_PLAY_STATE. */ // After the completion of the play status update button const val UPDATE_PLAY_STATE = 4 /** * The constant PLAY_ERROR_FINISH. */ // Receive the onError news out of the current page const val PLAY_ERROR_FINISH = 5 /** * The constant PLAYER_SWITCH_STOP_REQUEST_STREAM. */ // Switch bitrate const val PLAYER_SWITCH_STOP_REQUEST_STREAM = 7 /** * The constant MSG_SETTING. */ // Setting const val MSG_SETTING = 8 /** * The constant PLAYER_SWITCH_PLAY_SPEED. */ // Switch speed const val PLAYER_SWITCH_PLAY_SPEED = 9 /** * The constant PLAYER_SWITCH_BITRATE. */ // Switch bitrate const val PLAYER_SWITCH_BITRATE = 10 /** * The constant PLAYER_SWITCH_AUTO_DESIGNATED. */ // Smooth/Designated cutting rate const val PLAYER_SWITCH_AUTO_DESIGNATED = 11 /** * The constant PLAYER_SWITCH_BANDWIDTH_MODE. */ // Set the bandwidth adaptive switch const val PLAYER_SWITCH_BANDWIDTH_MODE = 12 /** * The constant PLAYER_SWITCH_PLAY_MODE. */ // Switch the audio and video const val PLAYER_SWITCH_PLAY_MODE = 13 /** * The constant PLAYER_SWITCH_LOOP_PLAY_MODE. */ // Set the looping const val PLAYER_SWITCH_LOOP_PLAY_MODE = 14 /** * The constant PLAYER_SWITCH_VIDEO_MUTE_MODE. */ // Set the mute const val PLAYER_SWITCH_VIDEO_MUTE_MODE = 15 /** * The constant PLAYER_SWITCH_VIDEO_MODE. */ // Set the video type const val PLAYER_SWITCH_VIDEO_MODE = 0 /** * The constant PLAYER_SWITCH_VIDEO_VIEW. */ // Set the play View const val PLAYER_SWITCH_VIDEO_VIEW = 1 /** * The constant PLAYER_SWITCH_VIDEO_MUTE. */ // Set the mute const val PLAYER_SWITCH_VIDEO_MUTE = 3 /** * The constant PLAYER_SWITCH_VIDEO_PLAY. */ // Set the play mode const val PLAYER_SWITCH_VIDEO_PLAY = 4 /** * The constant PLAYER_SWITCH_BANDWIDTH. */ // Set the bandwidth adaptive const val PLAYER_SWITCH_BANDWIDTH = 5 /** * The constant PLAYER_SWITCH_INIT_BANDWIDTH. */ // Set the bitrate const val PLAYER_SWITCH_INIT_BANDWIDTH = 6 /** * The constant PLAYER_SWITCH_CLOSE_LOGO. */ // Set off the logo const val PLAYER_SWITCH_CLOSE_LOGO = 7 /** * The constant PLAYER_SWITCH_CLOSE_LOGO_EFFECT. */ // Close the logo under the influence of all the sources or sources const val PLAYER_SWITCH_CLOSE_LOGO_EFFECT = 8 /** * The constant DIALOG_INDEX_ONE. */ // The first options dialog const val DIALOG_INDEX_ONE = 0 /** * The constant DIALOG_INDEX_TWO. */ // The second options dialog const val DIALOG_INDEX_TWO = 1 /** * The constant VIDEO_TYPE_LIVE. */ // Set play type live const val VIDEO_TYPE_LIVE = 1 /** * The constant VIDEO_TYPE_ON_DEMAND. */ // Set play type demand const val VIDEO_TYPE_ON_DEMAND = 0 /** * The constant SCORE_CORRECT. */ const val SCORE_CORRECT = "score_correct" /** * The constant SCORE_WRONG. */ const val SCORE_WRONG = "score_wrong" /** * The constant TOTAL_QUESTIONS. */ const val TOTAL_QUESTIONS = "total_questions" /** * The constant FINISHSTATUS. */ const val FINISHSTATUS = "finishstatus" /** * The type Url type. */ // Url type object UrlType { /** * The constant URL. */ // A single play address const val URL = 0 /** * The constant URL_MULTIPLE. */ // Multiple play address const val URL_MULTIPLE = 1 /** * The constant URL_JSON. */ // Huawei managed video address const val URL_JSON = 2 } }
1
null
1
1
9e038c432077d2bf0b0749f5c12cf8f58dbe5454
6,158
HMS-Learning-Application
Apache License 2.0
src/main/kotlin/org/opensearch/indexmanagement/transform/util/TransformUtils.kt
opensearch-project
354,094,562
false
null
/* * Copyright OpenSearch Contributors * SPDX-License-Identifier: Apache-2.0 */ package org.opensearch.indexmanagement.transform.util import org.opensearch.common.time.DateFormatter import java.time.ZoneId const val DEFAULT_DATE_FORMAT = "strict_date_optional_time||epoch_millis" private const val DATE_FORMAT = "uuuu-MM-dd'T'HH:mm:ss.SSSZZ" private val timezone: ZoneId = ZoneId.of("UTC") private val dateFormatter = DateFormatter.forPattern(DATE_FORMAT).withZone(timezone) fun formatMillis( dateTimeInMillis: Long, ): String = dateFormatter.formatMillis(dateTimeInMillis)
138
null
110
53
c0942eb60921070385d1b10c7453eee5e148e44f
585
index-management
Apache License 2.0
src/main/kotlin/uk/cmdrnorthpaw/kinventory/inventory/SerializableSimpleInventory.kt
CmdrNorthpaw
356,551,514
false
{"Kotlin": 19404}
package uk.cmdrnorthpaw.kinventory.inventory import kotlinx.serialization.Serializable import net.minecraft.inventory.SimpleInventory import uk.cmdrnorthpaw.kinventory.model.SerializableInventory import uk.cmdrnorthpaw.kinventory.model.SerializableItemStack import uk.cmdrnorthpaw.kinventory.model.SerializableItemStack.Companion.serializable import uk.cmdrnorthpaw.kinventory.serializers.SimpleInventorySerializer import uk.cmdrnorthpaw.kinventory.utils.items @Serializable class SerializableSimpleInventory( private val itemList: List<SerializableItemStack> ) : SerializableInventory<@Serializable(SimpleInventorySerializer::class) SimpleInventory>(itemList) { override fun toInventory(): SimpleInventory = SimpleInventory(*items.map { it.toItemStack() }.toTypedArray()) companion object : SerializableInventoryCompanion<SimpleInventory, SerializableSimpleInventory> { override fun getSerializable(from: SimpleInventory): SerializableSimpleInventory { val stacks = from.items return SerializableSimpleInventory(stacks.toList().map { it.serializable() }) } fun SimpleInventory.serializable() = getSerializable(this) } }
0
Kotlin
0
2
b451f256b0392f90ba9df1a9424ddb6a66bbf674
1,188
KInventory
MIT License
app/src/main/java/com/sisiame/wordal/MainActivity.kt
sisiame
519,347,612
false
null
package com.sisiame.wordal import androidx.appcompat.app.AppCompatActivity import android.os.Bundle import android.text.Spannable import android.text.SpannableString import android.text.style.ForegroundColorSpan import android.widget.* import android.view.View /** * This program is a simple clone of the popular New York Times game, * Wordle. Players have 3 chances to guess a random 4 letter word. * * @author <NAME> * */ class MainActivity : AppCompatActivity() { companion object { private const val BLANK_LETTER: Int = 0 private const val INVALID_CHARACTER: Int = 1 } // each individual letter is a separate input, with every EditText stored in the inputs array private lateinit var inputs: Array<EditText> // when valid guesses are submitted, the words are displayed using these TextViews private lateinit var outputs: Array<TextView> private lateinit var winLoseText: TextView // the randomly selected word for the round private lateinit var wordToGuess: String private lateinit var submitButton: ImageButton private lateinit var restartButton: ImageButton // the number of guesses the player has used so far private var numGuesses: Int = 0 override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) // gets each indiviudal EditText for each input's letter for the inputs array inputs = arrayOf(findViewById(R.id.input1), findViewById(R.id.input2), findViewById(R.id.input3), findViewById(R.id.input4)) // gets each individual TextView for each output's letter for the outputs array outputs = arrayOf(findViewById(R.id.guess1), findViewById(R.id.guess2), findViewById(R.id.guess3)) // finds views and assigns them to fields winLoseText = findViewById(R.id.winLoseText) submitButton = findViewById(R.id.submit) restartButton = findViewById(R.id.restart) // sets click listeners for buttons submitButton.setOnClickListener { submitGuess() } restartButton.setOnClickListener { startGame() } // initializes the game startGame() } /** * Initializes the game. */ private fun startGame() { // resets number of guesses numGuesses = 0 // hides the restart button restartButton.visibility = View.GONE // resets the game status text winLoseText.text = "" // resets outputs for(output in outputs) { output.text = getString(R.string.output_placeholder) } // selects a new word wordToGuess = FourLetterWordList.getRandomFourLetterWord() } /** * Submits the player's guess if the input is valid. */ private fun submitGuess() { if(validateGuessInput()) { var outputString = "" // puts together the output string using each letter input for(letter in inputs) { val input = letter.text.toString() outputString = "$outputString$input" letter.clearFocus() letter.text.clear() } outputs[numGuesses].text = outputString // increases number of guesses each time the player submits a valid guess numGuesses++ checkWin(outputString) } } /** * Checks if inputs are valid. * Inputs are valid if they contain only letters. * * @return whether the inputs are valid or not */ private fun validateGuessInput(): Boolean { // loops through each letter inputted for(letterInput in inputs) { // convert Editable to String for use with String functions val letter = letterInput.text.toString() // checks if any inputs are blank or empty if(letter.isBlank()) { showErrorMessage(BLANK_LETTER) return false } // checks if any inputs are not letters if((letter !in "A".."Z" && letter !in "a".."z")) { showErrorMessage(INVALID_CHARACTER) return false } } return true } /** * Displays an error message as a toast. * Intended for use with input validator. * * @param errorCode the number code associated with the error * */ private fun showErrorMessage(errorCode: Int) { if(errorCode == BLANK_LETTER) { // shows message if one of the inputs are blank Toast.makeText(this, "You're missing letters!", Toast.LENGTH_SHORT).show() } else if(errorCode == INVALID_CHARACTER) { // shows message if one of the inputs is not a letter Toast.makeText(this, "You can only enter letters!", Toast.LENGTH_SHORT).show() } } /** * Checks if the player won the game. * * @param guess the player's inputted word */ private fun checkWin(guess: String) { if(guess == wordToGuess) { winGame() } else if(numGuesses >= 3) { loseGame() } setLetterColors(guess) } /** * Displays a victory message and ends the game. */ private fun winGame() { winLoseText.setTextColor(getColor(R.color.green)) winLoseText.text = resources.getStringArray(R.array.win)[numGuesses - 1] restartButton.visibility = View.VISIBLE } /** * Displays a failure message and ends the game. */ private fun loseGame() { winLoseText.setTextColor(getColor(R.color.red)) // shows what the correct word was meant to be winLoseText.text = String.format(getString(R.string.lose), wordToGuess) restartButton.visibility = View.VISIBLE } /** * Sets the colors of the outputs' letters based on correctness. * Green represents a correctly placed letter. * Red represents an incorrectly placed letter. * * @param guess the player's inputted word */ private fun setLetterColors(guess: String) { // creates a SpannableString with the guessed word to color each individual letter val outputSpannable = SpannableString(guess) // colors correctly placed letters green and incorrectly placed letters red for(letter in 0..3) { if(wordToGuess.contains(guess[letter], true)) { if(wordToGuess[letter].equals(guess[letter], true)) { outputSpannable.setSpan( ForegroundColorSpan(getColor(R.color.green)), letter, letter + 1, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE) } else { outputSpannable.setSpan( ForegroundColorSpan(getColor(R.color.red)), letter, letter + 1, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE) } } } outputs[numGuesses - 1].text = outputSpannable } /** * Stores all the 4 letter words to be selected at random for * the game. * * @author calren, <NAME> * */ object FourLetterWordList { // List of most common 4 letter words from: https://7esl.com/4-letter-words/ private const val fourLetterWords = "Area,Army,Baby,Back,Ball,Band,Bank,Base,Bill,Body,Book,Call,Card,Care,Case,Cash,City,Club,Cost,Date,Deal,Door,Duty,East,Edge,Face,Fact,Farm,Fear,File,Film,Fire,Firm,Fish,Food,Foot,Form,Fund,Game,Girl,Goal,Gold,Hair,Half,Hall,Hand,Head,Help,Hill,Home,Hope,Hour,Idea,Jack,John,Kind,King,Lack,Lady,Land,Life,Line,List,Look,Lord,Loss,Love,Mark,Mary,Mind,Miss,Move,Name,Need,News,Note,Page,Pain,Pair,Park,Part,Past,Path,Paul,Plan,Play,Post,Race,Rain,Rate,Rest,Rise,Risk,Road,Rock,Role,Room,Rule,Sale,Seat,Shop,Show,Side,Sign,Site,Size,Skin,Sort,Star,Step,Task,Team,Term,Test,Text,Time,Tour,Town,Tree,Turn,Type,Unit,User,View,Wall,Week,West,Wife,Will,Wind,Wine,Wood,Word,Work,Year,Bear,Beat,Blow,Burn,Call,Care,Cast,Come,Cook,Cope,Cost,Dare,Deal,Deny,Draw,Drop,Earn,Face,Fail,Fall,Fear,Feel,Fill,Find,Form,Gain,Give,Grow,Hang,Hate,Have,Head,Hear,Help,Hide,Hold,Hope,Hurt,Join,Jump,Keep,Kill,Know,Land,Last,Lead,Lend,Lift,Like,Link,Live,Look,Lose,Love,Make,Mark,Meet,Mind,Miss,Move,Must,Name,Need,Note,Open,Pass,Pick,Plan,Play,Pray,Pull,Push,Read,Rely,Rest,Ride,Ring,Rise,Risk,Roll,Rule,Save,Seek,Seem,Sell,Send,Shed,Show,Shut,Sign,Sing,Slip,Sort,Stay,Step,Stop,Suit,Take,Talk,Tell,Tend,Test,Turn,Vary,View,Vote,Wait,Wake,Walk,Want,Warn,Wash,Wear,Will,Wish,Work,Able,Back,Bare,Bass,Blue,Bold,Busy,Calm,Cold,Cool,Damp,Dark,Dead,Deaf,Dear,Deep,Dual,Dull,Dumb,Easy,Evil,Fair,Fast,Fine,Firm,Flat,Fond,Foul,Free,Full,Glad,Good,Grey,Grim,Half,Hard,Head,High,Holy,Huge,Just,Keen,Kind,Last,Late,Lazy,Like,Live,Lone,Long,Loud,Main,Male,Mass,Mean,Mere,Mild,Nazi,Near,Neat,Next,Nice,Okay,Only,Open,Oral,Pale,Past,Pink,Poor,Pure,Rare,Real,Rear,Rich,Rude,Safe,Same,Sick,Slim,Slow,Soft,Sole,Sore,Sure,Tall,Then,Thin,Tidy,Tiny,Tory,Ugly,Vain,Vast,Very,Vice,Warm,Wary,Weak,Wide,Wild,Wise,Zero,Ably,Afar,Anew,Away,Back,Dead,Deep,Down,Duly,Easy,Else,Even,Ever,Fair,Fast,Flat,Full,Good,Half,Hard,Here,High,Home,Idly,Just,Late,Like,Live,Long,Loud,Much,Near,Nice,Okay,Once,Only,Over,Part,Past,Real,Slow,Solo,Soon,Sure,That,Then,This,Thus,Very,When,Wide" /** * Returns all the 4 letter words as a list. */ private fun getAllFourLetterWords(): List<String> { return fourLetterWords.split(",") } /** * Selects a random word from the list of 4 letter words. * * @return a word from the list of 4 letter words * */ fun getRandomFourLetterWord(): String { val allWords = getAllFourLetterWords() val randomNumber = (allWords.indices).random() return allWords[randomNumber].uppercase() } } }
0
Kotlin
0
0
668ff14ecaba743739c465ce325dcb74e77a70e7
10,106
Wordal
Apache License 2.0
app/src/main/java/com/example/flixterv2/DetailActivity.kt
xyzcv979
699,905,787
false
{"Kotlin": 9812}
package com.example.flixterv2 import androidx.appcompat.app.AppCompatActivity import android.os.Bundle import android.widget.ImageView import android.widget.TextView import android.widget.VideoView import com.bumptech.glide.Glide class DetailActivity : AppCompatActivity() { private lateinit var detail_image: ImageView private lateinit var detail_title: TextView private lateinit var detail_overview: TextView private lateinit var detail_release_date: TextView private lateinit var detail_popularity: TextView private lateinit var detail_vote_average: TextView override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_detail) detail_image = findViewById(R.id.detail_image) detail_title = findViewById(R.id.detail_title) detail_overview = findViewById(R.id.detail_overview) detail_release_date = findViewById(R.id.detail_release_date) detail_popularity = findViewById(R.id.detail_popularity) detail_vote_average = findViewById(R.id.detail_vote_average) var movie_path = getIntent().getStringExtra("image") detail_title.text = getIntent().getStringExtra("title") detail_overview.text = getIntent().getStringExtra("overview") detail_release_date.text = "Release date: " + getIntent().getStringExtra("release_date") detail_popularity.text = "Popularity: " + getIntent().getStringExtra("popularity") detail_vote_average.text = "Vote Average: " + getIntent().getStringExtra("vote_average") //Load the media image Glide.with(this) .load("https://image.tmdb.org/t/p/w500" + movie_path) .centerInside() .into(detail_image) } }
1
Kotlin
0
0
f506113481c277c4cad582057755ddab11497d42
1,788
FlixterV2
Apache License 2.0
ComposePdfViewer/app/src/main/java/dev/seabat/android/composepdfviewer/MainActivity.kt
seabat
685,948,686
false
{"Kotlin": 60541}
package dev.seabat.android.composepdfviewer import android.annotation.SuppressLint import android.os.Bundle import androidx.activity.ComponentActivity import androidx.activity.compose.setContent import androidx.activity.viewModels import androidx.compose.material.BottomNavigation import androidx.compose.material.BottomNavigationItem import androidx.compose.material.Icon import androidx.compose.material.IconButton import androidx.compose.material.Scaffold import androidx.compose.material.Text import androidx.compose.material.TopAppBar import androidx.compose.material.icons.Icons import androidx.compose.material.icons.filled.Close import androidx.compose.material3.MaterialTheme import androidx.compose.runtime.Composable import androidx.compose.runtime.State import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.ui.res.stringResource import androidx.hilt.navigation.compose.hiltViewModel import androidx.navigation.NavDestination.Companion.hierarchy import androidx.navigation.NavGraph.Companion.findStartDestination import androidx.navigation.NavHostController import androidx.navigation.NavType import androidx.navigation.compose.NavHost import androidx.navigation.compose.composable import androidx.navigation.compose.currentBackStackEntryAsState import androidx.navigation.compose.rememberNavController import androidx.navigation.navArgument import dagger.hilt.android.AndroidEntryPoint import dev.seabat.android.composepdfviewer.domain.entity.PdfEntity import dev.seabat.android.composepdfviewer.ui.screen.Screen import dev.seabat.android.composepdfviewer.ui.screen.all.AllListScreen import dev.seabat.android.composepdfviewer.ui.screen.all.AllListViewModel import dev.seabat.android.composepdfviewer.ui.screen.favorite.FavoriteScreen import dev.seabat.android.composepdfviewer.ui.screen.getScreen import dev.seabat.android.composepdfviewer.ui.screen.pdfviewer.PdfViewerScreen import dev.seabat.android.composepdfviewer.ui.screen.pdfviewer.PdfViewerViewModel import dev.seabat.android.composepdfviewer.ui.screen.recentness.RecentnessScreen import dev.seabat.android.composepdfviewer.ui.screen.recentness.RecentnessViewModel import dev.seabat.android.composepdfviewer.ui.theme.ComposePdfViewerTheme import java.io.File import java.util.Date @AndroidEntryPoint class MainActivity : ComponentActivity() { val viewModel: MainViewModel by viewModels() override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContent { ComposePdfViewerTheme { PdfViewerApp() } } viewModel.copyPdfToInternalStorage() } } @SuppressLint("UnusedMaterialScaffoldPaddingParameter") @Composable fun PdfViewerApp() { val navController = rememberNavController() val backStackEntry by navController.currentBackStackEntryAsState() val currentScreen = getScreen( backStackEntry?.destination?.route ?: Screen.Favorite.route ) val scaffoldState = remember { mutableStateOf( ScaffoldState( shouldShowTop = true, shouldShowTopClose = false, shouldShowBottom = true ) ) } Scaffold( topBar = { if (scaffoldState.value.shouldShowTop) { PdfViewerAppBar( navController = navController, currentScreen = currentScreen, scaffoldState = scaffoldState ) } }, bottomBar = { if (scaffoldState.value.shouldShowBottom) { PdfViewerBottomNavigation( navController = navController, ) } } ) { PdfViewerNavHost( navController = navController, onChangeScaffoldState = { state -> scaffoldState.value = state }, ) } } @Composable fun PdfViewerNavHost( navController: NavHostController, onChangeScaffoldState: (ScaffoldState) -> Unit, ) { NavHost( navController = navController, startDestination = "favorite", ) { composable("recentness") { val viewModel = hiltViewModel<RecentnessViewModel>() RecentnessScreen( viewModel = viewModel, onClick = { navController.navigate("all") } ) onChangeScaffoldState( ScaffoldState( shouldShowTop = true, shouldShowTopClose = false, shouldShowBottom = true ) ) } composable("favorite") { FavoriteScreen( onClick = { navController.navigate("recentness") } ) onChangeScaffoldState( ScaffoldState( shouldShowTop = false, shouldShowTopClose = false, shouldShowBottom = true ) ) } composable("all") { val viewModel = hiltViewModel<AllListViewModel>() AllListScreen( viewModel = viewModel, navigateToPdfViewer = { pdf -> //TODO: pdf を JSON データに変換する navController.navigate("pdf_viewer" + "/?pdf=" + "pdfのJSONデータ") } ) onChangeScaffoldState( ScaffoldState( shouldShowTop = true, shouldShowTopClose = false, shouldShowBottom = true ) ) } composable( route = "pdf_viewer/?pdf={pdf}", arguments = listOf(navArgument("pdf") { type = NavType.StringType }), ) {backStackEntry -> val pdfJson = backStackEntry.arguments?.getString("pdf") pdfJson?.let { //TODO: pdfJson を PDF オブジェクトに変換する val viewModel = hiltViewModel<PdfViewerViewModel>() PdfViewerScreen( viewModel = viewModel, pdf = PdfEntity("title1", "desc1", 178, Date()), ) } onChangeScaffoldState( ScaffoldState( shouldShowTop = true, shouldShowTopClose = true, shouldShowBottom = false ) ) } } } @Composable fun PdfViewerBottomNavigation( navController: NavHostController, ) { val screenItems = listOf( Screen.Recentness, Screen.Favorite, Screen.AllList ) BottomNavigation( backgroundColor = MaterialTheme.colorScheme.primary, contentColor = MaterialTheme.colorScheme.onPrimary ) { val navBackStackEntry by navController.currentBackStackEntryAsState() val currentDestination = navBackStackEntry?.destination screenItems.forEach { screen -> BottomNavigationItem( icon = { Icon(screen.image, contentDescription = null) }, label = { Text( stringResource(screen.bottomLabelResId ?: throw IllegalStateException("BottomNavigationのラベルが設定されていません")) ) }, selected = currentDestination?.hierarchy?.any { it.route == screen.route } == true, onClick = { navController.navigate(screen.route) { // Pop up to the start destination of the graph to // avoid building up a large stack of destinations // on the back stack as users select items popUpTo(navController.graph.findStartDestination().id) { saveState = true } // Avoid multiple copies of the same destination when // reselecting the same item launchSingleTop = true // Restore state when reselecting a previously selected item restoreState = false // NOTE: true にすると画面が再生成されず、ViewModel の初期化も実行されない } } ) } } } @Composable fun PdfViewerAppBar( navController: NavHostController, currentScreen: Screen, scaffoldState: State<ScaffoldState>, ) { TopAppBar( title = { Text( text = stringResource(id = currentScreen.appBarTitleResId), color = MaterialTheme.colorScheme.onPrimary ) }, backgroundColor = MaterialTheme.colorScheme.primary, navigationIcon = if (scaffoldState.value.shouldShowTopClose) { { IconButton( onClick = { navController.navigateUp() } ) { Icon(Icons.Default.Close, contentDescription = "") } } } else { null } ) } data class ScaffoldState( val shouldShowTop: Boolean, val shouldShowTopClose: Boolean, val shouldShowBottom: Boolean )
0
Kotlin
0
0
db31efa1a3a7f235941652618d21a555e8c9256e
9,382
pdf_viewer
Apache License 2.0
src/main/kotlin/grd/kotlin/authapi/extensions/BasicExtensions.kt
gardehal
708,548,046
false
{"Kotlin": 54861, "Shell": 612, "HTML": 331}
package grd.kotlin.authapi.extensions import grd.kotlin.authapi.enums.* import java.time.* import java.util.* import kotlin.reflect.KProperty import kotlin.reflect.jvm.javaField class BasicExtensions /** * Check if a nullable value is null. * @param this value to check * @return True if null **/ fun Any?.isNull(): Boolean { return this == null } /** * Check if a nullable value is not null. * @param this value to check * @return True if not null **/ fun Any?.isNotNull(): Boolean { return this != null } /** * Check if [this] Class has [annotationClass] given. * @param this value to check * @param annotationClass Class of annotation * @return True if present **/ fun Any.hasAnnotation(annotationClass: Class<out Annotation>): Boolean { return this.javaClass.isAnnotationPresent(annotationClass) } /** * Check if [this] KProperty has [annotationClass] given. * @param this value to check * @param annotationClass Class of annotation * @return True if present **/ fun KProperty<*>.hasAnnotation(annotationClass: Class<out Annotation>): Boolean { val annotation = this.javaField!!.getDeclaredAnnotation(annotationClass) return !annotation.isNull() }
0
Kotlin
0
0
e4be0bf711bdd8dbd3dad876bd20babd88559aca
1,196
kotlin-auth-api
MIT License
nlp/front/storage-mongo/target/generated-sources/kapt/compile/fr/vsct/tock/nlp/front/shared/parser/ParseQuery_Serializer.kt
cooksane
151,793,390
true
{"Kotlin": 2507910, "TypeScript": 358055, "HTML": 140949, "CSS": 33484, "JavaScript": 5174, "Shell": 1591}
package fr.vsct.tock.nlp.front.shared.parser import com.fasterxml.jackson.core.JsonGenerator import com.fasterxml.jackson.databind.SerializerProvider import com.fasterxml.jackson.databind.module.SimpleModule import com.fasterxml.jackson.databind.ser.std.StdSerializer import org.litote.jackson.JacksonModuleServiceLoader class ParseQuery_Serializer : StdSerializer<ParseQuery>(ParseQuery::class.java), JacksonModuleServiceLoader { override fun module() = SimpleModule().addSerializer(this) override fun serialize( value: ParseQuery, gen: JsonGenerator, serializers: SerializerProvider ) { gen.writeStartObject() gen.writeFieldName("queries") val _queries_ = value.queries serializers.defaultSerializeValue(_queries_, gen) gen.writeFieldName("namespace") val _namespace_ = value.namespace gen.writeString(_namespace_) gen.writeFieldName("applicationName") val _applicationName_ = value.applicationName gen.writeString(_applicationName_) gen.writeFieldName("context") val _context_ = value.context serializers.defaultSerializeValue(_context_, gen) gen.writeFieldName("state") val _state_ = value.state serializers.defaultSerializeValue(_state_, gen) gen.writeFieldName("intentsSubset") val _intentsSubset_ = value.intentsSubset serializers.defaultSerializeValue(_intentsSubset_, gen) gen.writeEndObject() } }
0
Kotlin
0
0
cd5c55e99cda91b5f7d790503de88137d3a3cc3c
1,530
tock
Apache License 2.0
src/main/kotlin/daniel/mybank/model/request/Request.kt
DanFonseca
602,188,054
false
null
package daniel.mybank.model.request import java.math.BigDecimal open class Request ( open val accountId: Long, open val amount: BigDecimal ) { }
0
Kotlin
0
0
b327cd4e8d7735b269708580d02bf865904109b8
170
mybank
MIT License
src/main/kotlin/com/github/woojiahao/style/elements/Link.kt
omnius-project
164,745,084
false
null
package com.github.woojiahao.style.elements import com.github.woojiahao.style.Settings import com.github.woojiahao.utility.c class Link(settings: Settings) : Element("a", settings) { init { textColor.value = c("448AFF") } }
6
Kotlin
0
17
9ab611d0f72d39ebe20223be5161b45dede6d30b
233
kMD2PDF
MIT License
app/src/main/java/com/noto/app/util/EpoxyUtils.kt
alialbaali
245,781,254
false
null
package com.noto.app.util import android.content.Context import com.airbnb.epoxy.EpoxyController import com.airbnb.epoxy.EpoxyRecyclerView import com.noto.app.R import com.noto.app.components.headerItem import com.noto.app.components.progressIndicatorItem import com.noto.app.domain.model.Folder import com.noto.app.domain.model.Grouping import com.noto.app.domain.model.NotoColor import com.noto.app.folder.NoteItemModel fun EpoxyRecyclerView.setupProgressIndicator(color: NotoColor? = null) { withModels { progressIndicatorItem { id("loading") color(color) } } } inline fun EpoxyController.buildNotesModels( context: Context, folder: Folder, notes: List<NoteItemModel>, crossinline onCreateClick: (List<Long>) -> Unit, content: (List<NoteItemModel>) -> Unit, ) { when (folder.grouping) { Grouping.Default -> { val pinnedNotes = notes.filter { it.note.isPinned }.sorted(folder.sortingType, folder.sortingOrder) val notPinnedNotes = notes.filterNot { it.note.isPinned }.sorted(folder.sortingType, folder.sortingOrder) if (pinnedNotes.isNotEmpty()) { headerItem { id("pinned") title(context.stringResource(R.string.pinned)) color(folder.color) } content(pinnedNotes) if (notPinnedNotes.isNotEmpty()) headerItem { id("notes") title(context.stringResource(R.string.notes)) color(folder.color) } } content(notPinnedNotes) } Grouping.CreationDate -> { notes.groupByCreationDate(folder.sortingType, folder.sortingOrder, folder.groupingOrder).forEach { (date, notes) -> headerItem { id(date.dayOfYear) title(date.format()) color(folder.color) } content(notes) } } Grouping.Label -> { notes.groupByLabels(folder.sortingType, folder.sortingOrder, folder.groupingOrder).forEach { (labels, notes) -> if (labels.isEmpty()) headerItem { id("without_label") title(context.stringResource(R.string.without_label)) color(folder.color) onCreateClickListener { _ -> onCreateClick(emptyList()) } } else headerItem { id(*labels.map { it.id }.toTypedArray()) title(labels.joinToString(" • ") { it.title }) color(folder.color) onCreateClickListener { _ -> onCreateClick(labels.map { it.id }) } } content(notes) } } Grouping.AccessDate -> { notes.groupByAccessDate(folder.sortingType, folder.sortingOrder, folder.groupingOrder).forEach { (date, notes) -> headerItem { id(date.dayOfYear) title(date.format()) color(folder.color) } content(notes) } } } } inline fun EpoxyController.buildFoldersModels( context: Context, folders: List<Pair<Folder, Int>>, content: (List<Pair<Folder, Int>>) -> Unit, ) { val pinnedFolders = folders.filter { it.first.isPinned } val notPinnedFolders = folders.filterNot { it.first.isPinned } if (pinnedFolders.isNotEmpty()) { headerItem { id("pinned") title(context.stringResource(R.string.pinned)) } content(pinnedFolders) if (notPinnedFolders.isNotEmpty()) headerItem { id("libraries") title(context.stringResource(R.string.folders)) } } content(notPinnedFolders) }
60
null
9
90
ac844512dc95572e6845a154fe339919588d460a
4,069
Noto
Apache License 2.0
xml-parser-api/src/main/kotlin/com/valb3r/bpmn/intellij/plugin/bpmn/api/BpmnObjectFactory.kt
valb3r
261,109,342
false
null
package com.valb3r.bpmn.intellij.plugin.bpmn.api import com.valb3r.bpmn.intellij.plugin.bpmn.api.bpmn.elements.BpmnSequenceFlow import com.valb3r.bpmn.intellij.plugin.bpmn.api.bpmn.elements.WithBpmnId import com.valb3r.bpmn.intellij.plugin.bpmn.api.diagram.elements.WithDiagramId import com.valb3r.bpmn.intellij.plugin.bpmn.api.info.Property import com.valb3r.bpmn.intellij.plugin.bpmn.api.info.PropertyType import kotlin.reflect.KClass interface BpmnObjectFactory { fun <T: WithBpmnId> newBpmnObject(clazz: KClass<T>): T fun <T: WithBpmnId> newOutgoingSequence(obj: T): BpmnSequenceFlow fun <T: WithBpmnId> propertiesOf(obj: T): Map<PropertyType, Property> fun <T: WithDiagramId> newDiagramObject(clazz: KClass<T>, forBpmnObject: WithBpmnId): T }
76
null
20
81
760efb3d7e48970545d0d7622687d67c2b9b9693
767
flowable-bpmn-intellij-plugin
MIT License
app/src/main/java/com/sergiop/aparcamientos/ui/activitys/home/screens/allListAllParking/AllListParkingState.kt
SerPamplona
440,244,808
false
{"Kotlin": 157611}
package com.sergiop.aparcamientos.ui.activitys.home.screens.allListAllParking import com.sergiop.aparcamientos.model.Garaje data class AllListParkingState ( val loadingList: Boolean = false, val list: List<Garaje>? = null, val error: Boolean = false, val messageError : String = "" )
0
Kotlin
0
0
771a5913cd407463c66653382117b94e5cf5fad6
301
aparcamientosDisca
Apache License 2.0
core/framework/src/main/java/com/jojalvo/framework/base/jetpack/RememberFlow.kt
jose-ojalvo
619,971,179
false
null
package com.jojalvo.framework.base.jetpack import androidx.compose.runtime.Composable import androidx.compose.runtime.remember import androidx.compose.ui.platform.LocalLifecycleOwner import androidx.lifecycle.Lifecycle import androidx.lifecycle.flowWithLifecycle import kotlinx.coroutines.flow.Flow /** * @author jojalvo * @since 30/4/23 * @email <EMAIL> */ @Composable fun <T> rememberFlowWithLifecycle( flow: Flow<T>, lifecycle: Lifecycle = LocalLifecycleOwner.current.lifecycle, minActiveState: Lifecycle.State = Lifecycle.State.STARTED ): Flow<T> = remember(flow, lifecycle) { flow.flowWithLifecycle( lifecycle = lifecycle, minActiveState = minActiveState ) }
0
Kotlin
0
0
1e8528c9868aec7d08e6c3bee5ffbae07d0c769e
711
MobileChallenge
Apache License 2.0
core/framework/src/main/java/com/jojalvo/framework/base/jetpack/RememberFlow.kt
jose-ojalvo
619,971,179
false
null
package com.jojalvo.framework.base.jetpack import androidx.compose.runtime.Composable import androidx.compose.runtime.remember import androidx.compose.ui.platform.LocalLifecycleOwner import androidx.lifecycle.Lifecycle import androidx.lifecycle.flowWithLifecycle import kotlinx.coroutines.flow.Flow /** * @author jojalvo * @since 30/4/23 * @email <EMAIL> */ @Composable fun <T> rememberFlowWithLifecycle( flow: Flow<T>, lifecycle: Lifecycle = LocalLifecycleOwner.current.lifecycle, minActiveState: Lifecycle.State = Lifecycle.State.STARTED ): Flow<T> = remember(flow, lifecycle) { flow.flowWithLifecycle( lifecycle = lifecycle, minActiveState = minActiveState ) }
0
Kotlin
0
0
1e8528c9868aec7d08e6c3bee5ffbae07d0c769e
711
MobileChallenge
Apache License 2.0
prefixes-api/src/main/kotlin/app/simplecloud/plugin/prefixes/api/impl/PrefixesActorBlankImpl.kt
theSimpleCloud
728,784,970
false
{"Kotlin": 33787}
package app.simplecloud.plugin.prefixes.api.impl import app.simplecloud.plugin.prefixes.api.PrefixesActor import app.simplecloud.plugin.prefixes.api.PrefixesGroup import net.kyori.adventure.text.Component import java.util.* class PrefixesActorBlankImpl : PrefixesActor { override fun applyGroup(target: UUID, group: PrefixesGroup) { throw NotImplementedError("You need to define a PrefixesActor to use this") } override fun setPrefix(target: UUID, prefix: Component) { throw NotImplementedError("You need to define a PrefixesActor to use this") } override fun setSuffix(target: UUID, suffix: Component) { throw NotImplementedError("You need to define a PrefixesActor to use this") } override fun setColor(target: UUID, color: String) { throw NotImplementedError("You need to define a PrefixesActor to use this") } override fun formatMessage(target: UUID, format: String, message: Component): Component { throw NotImplementedError("You need to define a PrefixesActor to use this") } override fun remove(target: UUID) { throw NotImplementedError("You need to define a PrefixesActor to use this") } }
0
Kotlin
0
0
365bff6e4fcfc776b3df2b03226d8d51cd5bc145
1,201
prefixes-plugin
Apache License 2.0
intellij-plugin/educational-core/testSrc/com/jetbrains/edu/learning/command/validation/TestServiceMessageConsumer.kt
JetBrains
43,696,115
false
null
package com.jetbrains.edu.learning.command.validation import com.intellij.execution.testframework.sm.ServiceMessageBuilder import com.intellij.execution.testframework.sm.ServiceMessageUtil import jetbrains.buildServer.messages.serviceMessages.* import kotlin.test.assertEquals class TestServiceMessageConsumer : ServiceMessageConsumer { private val roots: MutableList<TestNode> = mutableListOf() private var currentTestSuites: MutableList<TestSuite> = mutableListOf() private var currentTestCase: TestCase? = null // This implementation assumes that all tests are executed sequentially override fun consume(message: ServiceMessageBuilder) { when (val parsedMessage = ServiceMessageUtil.parse(message.toString(), true)) { is TestSuiteStarted -> { currentTestSuites += TestSuite(parsedMessage.suiteName) } is TestSuiteFinished -> { val currentTestSuite = currentTestSuites.lastOrNull() if (currentTestSuite == null) error("`${parsedMessage.suiteName}` test suite didn't start") val currentTestCase = currentTestCase if (currentTestCase != null) error("`${currentTestCase.name}` test case is not finished yet") assertEquals(currentTestSuite.name, parsedMessage.suiteName) currentTestSuites.removeLast() val parentChildren = currentTestSuites.lastOrNull()?.children ?: roots parentChildren += currentTestSuite } is TestStarted -> { val currentTestCase = currentTestCase if (currentTestCase != null) error("`${currentTestCase.name}` test case is not finished yet") this.currentTestCase = TestCase(parsedMessage.testName) } is TestIgnored -> { val currentTestCase = currentTestCase if (currentTestCase == null) error("`${parsedMessage.testName}` test case didn't start") assertEquals(currentTestCase.name, parsedMessage.testName) this.currentTestCase = TestCase(parsedMessage.testName, TestStatus.IGNORED) } is TestFailed -> { val currentTestCase = currentTestCase if (currentTestCase == null) error("`${parsedMessage.testName}` test case didn't start") assertEquals(currentTestCase.name, parsedMessage.testName) this.currentTestCase = TestCase(parsedMessage.testName, TestStatus.FAILED) } is TestFinished -> { val currentTestCase = currentTestCase if (currentTestCase == null) error("`${parsedMessage.testName}` test case didn't start") assertEquals(currentTestCase.name, parsedMessage.testName) val parentChildren = currentTestSuites.lastOrNull()?.children ?: roots parentChildren += currentTestCase this.currentTestCase = null } else -> error("Unexpected test event: ") } } fun assertTestTreeEquals(expected: String) { val builder = StringBuilder() roots.print(0, builder) assertEquals(expected.trimIndent().trimEnd(), builder.toString().trimEnd()) } private fun List<TestNode>.print(level: Int, out: StringBuilder) { for (node in this) { when (node) { is TestCase -> { out.append(" ".repeat(level)) out.appendLine("- ${node.name}: ${node.status}") } is TestSuite -> { out.append(" ".repeat(level)) out.appendLine("- ${node.name}:") node.children.print(level + 1, out) } } } } } private sealed interface TestNode { val name: String } private class TestSuite(override val name: String) : TestNode { val children: MutableList<TestNode> = mutableListOf() } private class TestCase(override val name: String, val status: TestStatus = TestStatus.SUCCESS) : TestNode private enum class TestStatus { SUCCESS, IGNORED, FAILED; override fun toString(): String = name.lowercase() }
7
null
49
150
9cec6c97d896f4485e76cf9a2a95f8a8dd21c982
3,822
educational-plugin
Apache License 2.0
RBeacon/app/src/main/java/adapter/MessageAdapter.kt
rheyansh
155,546,134
false
null
package adapter import android.content.Context import android.support.v7.widget.RecyclerView import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.TextView import java.util.* import com.info.rajsharma.rbeacon.* import kotlinx.android.synthetic.main.my_message.view.* internal const val VIEW_TYPE_MY_MESSAGE = 1 class MessageAdapter (val context: Context) : RecyclerView.Adapter<MessageViewHolder>() { private val messages: ArrayList<String> = ArrayList() override fun onBindViewHolder(holder: MessageViewHolder, position: Int) { val message = messages.get(position) holder?.bind(message) } override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): MessageViewHolder { return MyMessageViewHolder(LayoutInflater.from(context).inflate(R.layout.my_message, parent, false)) } fun addMessage(message: String) { addMessages(arrayListOf(message)) } fun removeAllMessages() { messages.removeAll(messages) notifyDataSetChanged() } fun addMessages(msgs: java.util.ArrayList<String>){ messages.addAll(msgs) notifyDataSetChanged() } override fun getItemCount(): Int { return messages.size } override fun getItemViewType(position: Int): Int { return VIEW_TYPE_MY_MESSAGE } inner class MyMessageViewHolder (view: View) : MessageViewHolder(view) { private var messageText: TextView = view.txtMyMessage override fun bind(message: String) { messageText.text = "${adapterPosition}:- " + message } } }
0
Kotlin
0
2
2999a2f46da4c15f9a7151be7030c00570c4206c
1,648
RBeacon
MIT License
app/src/main/java/com/example/movieapp/api/MoviesServices.kt
ahmedsamir9
308,115,212
false
null
package com.example.movieapp.api import com.example.movieapp.model.ActorResponse import com.example.movieapp.model.MovieActorResponse import com.example.movieapp.model.MovieDetails.Credits.MovieCredits import com.example.movieapp.model.MovieDetails.MovieDetails import com.example.movieapp.model.MovieDetails.Trailer.TrailerResponse import com.example.movieapp.model.MovieResponse import com.example.movieapp.model.searchmodel.people.PeopleSearchResponse import com.example.movieapp.utils.Constant import com.example.movieapp.utils.Constant.API_KEY import com.example.movieapp.utils.Constant.LANGUAGE import retrofit2.http.GET import retrofit2.http.Path import retrofit2.http.Query interface MoviesServices { @GET("movie/popular") suspend fun getPopularMovies(@Query("api_key")apiKey :String = API_KEY, @Query("language")language:String = LANGUAGE , @Query("page") page:Int = 1):MovieResponse @GET("movie/top_rated") suspend fun getTopRatedMovies(@Query("api_key")apiKey :String = API_KEY, @Query("language")language:String = LANGUAGE , @Query("page") page:Int):MovieResponse @GET("movie/now_playing") suspend fun getPlayingNowMovies(@Query("api_key")apiKey :String = API_KEY, @Query("language")language:String = LANGUAGE , @Query("page") page:Int):MovieResponse @GET("movie/upcoming") suspend fun getUpComingMovies(@Query("api_key")apiKey :String = API_KEY, @Query("language")language:String = LANGUAGE , @Query("page") page:Int):MovieResponse @GET("movie/{movie_id}") suspend fun getMovieDetails(@Path("movie_id") id :Int,@Query("api_key")apiKey :String = API_KEY , @Query("language")language:String = LANGUAGE):MovieDetails @GET("movie/{movie_id}/credits") suspend fun getMovieDetailsCredits(@Path("movie_id") id :Int,@Query("api_key")apiKey :String = API_KEY , @Query("language")language:String = LANGUAGE):MovieCredits @GET("movie/{movie_id}/videos") suspend fun getMovieDetailsVideos(@Path("movie_id") id :Int,@Query("api_key")apiKey :String = API_KEY , @Query("language")language:String = LANGUAGE):TrailerResponse @GET("movie/{movie_id}/recommendations") suspend fun getSimilarMovies(@Path("movie_id") id :Int,@Query("api_key")apiKey :String = API_KEY , @Query("language")language:String = LANGUAGE,@Query("page") page:Int = 1):MovieResponse @GET("search/person") suspend fun searchForPeople(@Query("query") word :String, @Query("api_key")apiKey :String = API_KEY , @Query("language")language:String = LANGUAGE, @Query("page") page:Int = 1):PeopleSearchResponse @GET("search/movie") suspend fun searchForMovies(@Query("query") word :String, @Query("api_key")apiKey :String = API_KEY , @Query("language")language:String = LANGUAGE, @Query("page") page:Int = 1):MovieResponse @GET("person/{person_id}") suspend fun getActor(@Path("person_id") id:Int, @Query("api_key")apiKey :String = API_KEY , @Query("language")language:String = LANGUAGE):ActorResponse @GET("person/{person_id}/movie_credits") suspend fun getActorMovies(@Path("person_id") id:Int, @Query("api_key")apiKey :String = API_KEY , @Query("language")language:String = LANGUAGE):MovieActorResponse }
0
Kotlin
3
6
5d9b73b2f62fc8fc3730335c7d69aae2efac6238
3,564
MovieAppKotlin
Apache License 2.0
app/src/main/java/com/github/lotaviods/linkfatec/di/LoginModules.kt
lotaviods
598,320,816
false
null
package com.github.lotaviods.linkfatec.di import com.github.lotaviods.linkfatec.data.repository.UserRepositoryImpl import com.github.lotaviods.linkfatec.data.remote.client.LoginWebClient import com.github.lotaviods.linkfatec.data.remote.repository.LoginRepositoryImpl import com.github.lotaviods.linkfatec.data.repository.interfaces.LoginRepository import com.github.lotaviods.linkfatec.data.repository.interfaces.UserRepository import com.github.lotaviods.linkfatec.ui.login.viewmodel.LoginScreenViewModel import org.koin.android.ext.koin.androidApplication import org.koin.androidx.viewmodel.dsl.viewModel import org.koin.core.module.Module import org.koin.dsl.module val loginModules: List<Module> = listOf( module { viewModel { LoginScreenViewModel(get(), get()) } single<UserRepository> { UserRepositoryImpl(androidApplication(), get()) } single<LoginRepository> { LoginRepositoryImpl(get(), get()) } single { LoginWebClient() } } )
0
Kotlin
0
0
8db3f167bea63711bcc25496261200a990a95d64
979
link-fatec-android-app
MIT License
app/src/main/java/com/vobbla16/mesh/common/localDateTimeToStr.kt
x3lfyn
654,997,267
false
{"Kotlin": 369716}
package com.vobbla16.mesh.common import kotlinx.datetime.LocalDateTime fun LocalDateTime.toStr() = "${this.date.dayOfMonth.toString().padStart(2, '0')}.${this.date.monthNumber.toString().padStart(2, '0')}.${this.date.year} ${this.time.hour.toString().padStart(2, '0')}:${this.time.minute.toString().padStart(2, '0')}"
5
Kotlin
1
6
f7120e47b483dc1da21125274f34c9570d1fd8b4
319
libremesh
MIT License
video-sdk/src/test/java/com/kaleyra/video_sdk/ui/chat/DayHeaderTest.kt
KaleyraVideo
686,975,102
false
{"Kotlin": 3508517, "Shell": 7470, "Python": 6756, "Java": 1213}
/* * Copyright 2023 Kaleyra @ https://www.kaleyra.com * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.kaleyra.video_sdk.chat import androidx.activity.ComponentActivity import androidx.compose.runtime.collectAsState import androidx.compose.ui.test.assertIsDisplayed import androidx.compose.ui.test.junit4.createAndroidComposeRule import androidx.compose.ui.test.onNodeWithText import androidx.test.ext.junit.runners.AndroidJUnit4 import com.kaleyra.video_sdk.R import com.kaleyra.video_sdk.chat.conversation.view.item.DayHeaderItem import kotlinx.coroutines.flow.MutableStateFlow import org.junit.Before import org.junit.Rule import org.junit.Test import org.junit.runner.RunWith import java.time.Instant import java.time.temporal.ChronoUnit @RunWith(AndroidJUnit4::class) class DayHeaderTest { @get:Rule val composeTestRule = createAndroidComposeRule<ComponentActivity>() private val time = MutableStateFlow<Long>(0) @Before fun setUp() { composeTestRule.setContent { DayHeaderItem(timestamp = time.collectAsState().value) } } @Test fun nowTime_todayIsDisplayed() { time.value = Instant.now().toEpochMilli() val today = composeTestRule.activity.getString(R.string.kaleyra_today) composeTestRule.onNodeWithText(today).assertIsDisplayed() } @Test fun yesterdayTime_yesterdayIsDisplayed() { time.value = Instant.now().minus(1, ChronoUnit.DAYS).toEpochMilli() val yesterday = composeTestRule.activity.getString(R.string.kaleyra_yesterday) composeTestRule.onNodeWithText(yesterday).assertIsDisplayed() } }
0
Kotlin
0
1
cddad1557475a5326f29bed3ad8926bbef27d79d
2,160
VideoAndroidSDK
Apache License 2.0
TemplateMethod/src/main/kotlin/AbstractClass.kt
AaronChuang
208,242,423
false
null
// 定義完整演算法各步驟及執行順序 abstract class AbstractClass { fun templateMethod(){ primitiveOperation1() primitiveOperation2() } abstract fun primitiveOperation1() abstract fun primitiveOperation2() }
0
Kotlin
0
0
9e31b8065a7b98e30d93033fae92d0381c17ef34
221
Kotlin-DesignPatternExample
MIT License
buildSrc/src/main/kotlin/BuildConstants.kt
lukwol
562,428,336
false
null
import org.gradle.api.JavaVersion.VERSION_17 object BuildConstants { const val Group = "io.github.lukwol" const val VersionName = "1.1.0" val JavaVersion = VERSION_17 object Modules { const val NavigationScreens = "navigation-screens" const val NavigationScreensViewModel = "navigation-screens-viewmodel" const val NavigationWindows = "navigation-windows" val String.Namespace get() = "${Group}.${replace("-", ".")}" } object Android { const val ApplicationId = "$Group.app.android" const val MinSdk = 29 const val TargetSdk = 34 const val CompileSdk = TargetSdk const val TestInstrumentationRunner = "androidx.test.runner.AndroidJUnitRunner" } }
2
null
0
8
7a66b5e71be5f7b076b20098aa54e3d52714c39c
752
navigation
MIT License
core/world/src/main/kotlin/app/logdate/core/world/ActivityLocationProvider.kt
WillieCubed
187,304,507
false
{"Kotlin": 458147, "Java": 1084}
package app.logdate.core.world import app.logdate.core.world.model.LogdateActivity /** * A location provider that fuses activity and location data. * * This domain-layer provider is the interface for observing the current activity and location. * Data is updated in the background and can be observed by the client. */ interface ActivityLocationProvider : LogdateLocationProvider { fun getCurrentActivity(): LogdateActivity fun observeActivity(onActivityUpdate: (newActivity: LogdateActivity) -> Unit) fun updateActivity(activity: LogdateActivity) }
0
Kotlin
0
0
51a51bd8c264aecc9190f67ec1fbb56e37b7e9fc
568
logdate-mobile
MIT License
app/src/main/java/com/example/assecoapp/ui/fragments/CustomerDetailsFragment.kt
forceindia712
598,618,103
false
null
package com.example.assecoapp.ui.fragments import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.fragment.app.Fragment import androidx.fragment.app.activityViewModels import androidx.navigation.fragment.findNavController import com.example.assecoapp.R import com.example.assecoapp.databinding.FragmentCustomerDetailsBinding import com.example.assecoapp.model.item.Customer import com.example.assecoapp.model.item.CustomerClasisfication import com.example.assecoapp.viewmodel.CustomerViewModel class CustomerDetailsFragment : Fragment() { val TAG = "CustomerDetailsFragment" private lateinit var binding: FragmentCustomerDetailsBinding private val viewModel: CustomerViewModel by activityViewModels() private var currentItem = Customer() private var currentClassificationItem = CustomerClasisfication() override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View { binding = FragmentCustomerDetailsBinding.inflate(inflater, container, false) return binding.root } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) observeUI() initUI() } private fun observeUI() { viewModel.currentItem.observe(viewLifecycleOwner) { currentItem = it initUI() } viewModel.currentClassificationItem.observe(viewLifecycleOwner) { currentClassificationItem = it initUI() } } private fun initUI() { binding.cancel.setOnClickListener { findNavController().navigate(R.id.action_customerDetailsFragment_to_mainFragment) } binding.name.text = currentItem.CustomerName binding.nip.text = currentItem.CustomerNIP binding.city.text = currentItem.CustomerNIP binding.date.text = currentItem.DateTime binding.classificationName.text = currentClassificationItem.ClassificationName binding.classificationDescription.text = currentClassificationItem.ClassificationDescription } }
0
Kotlin
0
0
06568b80b55b655ed87e724134312e62a3d1cea6
2,214
CustomerApp
Apache License 2.0
app/src/main/java/com/cisco/or/activity/login/SelectSigningServiceActivity.kt
CiscoDevNet
304,088,246
false
null
package com.cisco.or.activity.login import android.content.Intent import android.os.Bundle import android.util.Log import androidx.appcompat.app.AlertDialog import androidx.appcompat.app.AppCompatActivity import com.cisco.or.R import com.cisco.or.activity.HomeActivity import com.cisco.or.sdk.OpenRoaming import com.cisco.or.sdk.enums.SigningServiceName import com.cisco.or.sdk.enums.SigningState import com.cisco.or.sdk.exceptions.Hotspot2NotSupportedException import com.cisco.or.utils.Constant import com.cisco.or.utils.FirebaseMessagingService import kotlinx.android.synthetic.main.activity_select_signing_service.* class SelectSigningServiceActivity : AppCompatActivity() { companion object { private val TAG = SelectSigningServiceActivity::class.java.name } private lateinit var serviceName:String override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_select_signing_service) this.supportActionBar?.hide() val firebaseMessagingService = FirebaseMessagingService() firebaseMessagingService.registerPush(this) try { OpenRoaming.registerSdk(this, Constant.ApplicationId, Constant.dnaSpacesKey) { signingState -> if (signingState == SigningState.SIGNED) { val intent = Intent(this, HomeActivity::class.java) startActivity(intent) finish() Log.d(TAG, "OpenRoaming is initialized. signingState == SigningState.SIGNED") } else{ Log.d(TAG, "OpenRoaming is initialized. signingState == SigningState.UNSIGNED") } } } catch (e: Hotspot2NotSupportedException){ AlertDialog.Builder(this) .setMessage(e.message) .setNeutralButton(getText(android.R.string.ok)){ _,_-> finish() } .setCancelable(false) .show() Log.e(TAG, e.message) } buttonGoogleSignIn.setOnClickListener { login(SigningServiceName.GOOGLE.value) } buttonAppleSignIn.setOnClickListener { login(SigningServiceName.APPLE.value) } buttonOAuthAuthentication.setOnClickListener { val intent = Intent(this, ServerAuthCodeAuthenticationActivity::class.java) startActivity(intent) } buttonLoyaltyProgram.setOnClickListener { val intent = Intent(this, UserIdAuthenticationActivity::class.java) startActivity(intent) } } private fun login(serviceName: String){ this.serviceName = serviceName val intent = Intent(baseContext, SigningActivity::class.java) intent.putExtra("service", serviceName) startActivity(intent) } }
0
Kotlin
0
0
82c4141188133bb7197cecf6008fe7b171afb706
2,930
DNASpacesSDKSampleApp-Android
Apache License 2.0
shared/src/iosMain/kotlin/com.thomaskioko.tvmaniac.shared/IosViewPresenterComponent.kt
thomaskioko
361,393,353
false
{"Kotlin": 599244, "Swift": 126057}
package com.thomaskioko.tvmaniac.shared import com.arkivanov.decompose.ComponentContext import com.thomaskioko.tvmaniac.navigation.RootNavigationPresenter import com.thomaskioko.tvmaniac.traktauth.implementation.TraktAuthManagerComponent import com.thomaskioko.tvmaniac.util.scope.ActivityScope import me.tatarka.inject.annotations.Component import me.tatarka.inject.annotations.Provides @Component @ActivityScope abstract class IosViewPresenterComponent( @get:Provides val componentContext: ComponentContext, @Component val applicationComponent: ApplicationComponent, ) : TraktAuthManagerComponent { abstract val presenter: RootNavigationPresenter companion object }
5
Kotlin
21
162
5e04de4c0ac091c370ec62e5ced6efaba66e2400
687
tv-maniac
Apache License 2.0
src/main/kotlin/me/honkling/mhplus/ktmixins/KTMinecraftClientMixin.kt
honkling
443,187,122
false
{"Kotlin": 17858, "Java": 3511}
package me.honkling.mhplus.ktmixins import me.honkling.mhplus.MHPlus class KTMinecraftClientMixin { companion object { @JvmStatic fun close() { MHPlus.instance.settings.write() } } }
1
Kotlin
3
4
b3f1223e95204213e02c004c58dfc552365da9d8
228
MHPlus-Mod
MIT License
app/src/main/java/com/zhugeng/materialdesign/activity/menu/DrawerNewsActivity.kt
duxiu-chen
204,873,161
false
null
package com.zhugeng.materialdesign.activity.menu import android.app.Activity import android.graphics.Color import android.graphics.ColorFilter import android.graphics.PorterDuff import android.graphics.drawable.Drawable import android.os.Bundle import android.support.design.widget.NavigationView import android.support.v7.app.AppCompatActivity import com.zhugeng.materialdesign.R import kotlinx.android.synthetic.main.title_bar.* import com.zhugeng.materialdesign.R.id.toolbar import android.support.v4.widget.DrawerLayout import android.support.v7.app.ActionBarDrawerToggle import android.support.v7.widget.LinearLayoutManager import android.support.v7.widget.Toolbar import android.view.Gravity.START import android.view.MenuItem import kotlinx.android.synthetic.main.activity_menu_drawer_news.* import android.widget.Toast import com.zhugeng.materialdesign.adapter.BottomSheetBasicAdapter import com.zhugeng.materialdesign.beans.BottomSheetBasicBean import java.util.* class DrawerNewsActivity:AppCompatActivity(), NavigationView.OnNavigationItemSelectedListener { private var datas: LinkedList<BottomSheetBasicBean> = LinkedList() private lateinit var adapter: BottomSheetBasicAdapter private val resIds: Array<Int> = arrayOf(R.drawable.photo_female_1, R.drawable.photo_female_2,R.drawable.photo_male_1 , R.drawable.photo_female_3, R.drawable.photo_male_2, R.drawable.photo_male_3, R.drawable.photo_female_4, R.drawable.photo_female_5, R.drawable.photo_female_6, R.drawable.photo_male_4, R.drawable.photo_male_5, R.drawable.photo_male_6, R.drawable.photo_female_7, R.drawable.photo_male_7, R.drawable.photo_female_8) private val names : Array<String> = arrayOf("Sarah Scott", "Susan Lee", "Anderson Thomas", "Betty C", "Roberts", "Adams Green", "Mary Jackson", "Betty L", "Elizabeth", "Kevin John", "Evans Collins", "Roberts Turner", "Garcia Lewis", "Miller Wilson", "Laura Michelle") override fun onNavigationItemSelected(item: MenuItem): Boolean { Toast.makeText(this, "Selected :${item.title}", Toast.LENGTH_SHORT).show() toolbar.title = item.title drawerLayout.closeDrawers() return true } override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_menu_drawer_news) initView() initListener() } private fun initListener() { design_navigation_view.setNavigationItemSelectedListener(this@DrawerNewsActivity) adapter.setOnClickListener(object : BottomSheetBasicAdapter.OnClickListent{ override fun onClick(pos: Int, data: BottomSheetBasicBean) { } }) } private fun initView() { toolbar.title = "Drawer News" drawerLayout.openDrawer(START) var toggle = ActionBarDrawerToggle( this, drawerLayout, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close) drawerLayout.addDrawerListener(toggle) toggle.syncState() for (item in names.withIndex()){ var bean :BottomSheetBasicBean = BottomSheetBasicBean() bean.name = item.value; bean.resId = resIds[item.index] datas.add(bean) } adapter = BottomSheetBasicAdapter(this, datas) recyclerView.layoutManager = LinearLayoutManager(this) recyclerView.adapter = adapter } }
1
null
1
7
3a744d27abd7b147d081ce980c96599e7b511eab
3,461
Material-Elements
MIT License
dsl/src/main/kotlin/com/faendir/awscdkkt/generated/services/ec2/VpnConnectionDsl.kt
F43nd1r
643,016,506
false
null
package com.faendir.awscdkkt.generated.services.ec2 import com.faendir.awscdkkt.AwsCdkDsl import javax.`annotation`.Generated import kotlin.String import kotlin.Unit import software.amazon.awscdk.services.ec2.VpnConnection import software.amazon.awscdk.services.ec2.VpnConnectionProps import software.constructs.Construct @Generated public fun Construct.vpnConnection(id: String, props: VpnConnectionProps): VpnConnection = VpnConnection(this, id, props) @Generated public fun Construct.vpnConnection( id: String, props: VpnConnectionProps, initializer: @AwsCdkDsl VpnConnection.() -> Unit, ): VpnConnection = VpnConnection(this, id, props).apply(initializer) @Generated public fun Construct.buildVpnConnection(id: String, initializer: @AwsCdkDsl VpnConnection.Builder.() -> Unit): VpnConnection = VpnConnection.Builder.create(this, id).apply(initializer).build()
1
Kotlin
0
0
e9a0ff020b0db2b99e176059efdb124bf822d754
886
aws-cdk-kt
Apache License 2.0
android/app/src/main/java/com/deange/mechnotifier/compose/Empty.kt
christiandeange
341,023,692
false
null
package com.deange.mechnotifier.compose import androidx.compose.foundation.layout.Spacer import androidx.compose.foundation.layout.size import androidx.compose.runtime.Composable import androidx.compose.ui.Modifier import androidx.compose.ui.unit.dp @Composable fun Empty() { Spacer(modifier = Modifier.size(0.dp)) }
0
Kotlin
0
2
5b87d8134ff0ce3e1634b895f82eb018950020ba
320
mechnotifier
MIT License
app/src/main/kotlin/org/skyfaced/noti/database/dao/BaseDao.kt
SkyfaceD
515,664,120
false
null
package org.skyfaced.noti.database.dao import androidx.room.Delete import androidx.room.Insert import androidx.room.OnConflictStrategy import androidx.room.Update abstract class BaseDao<T> { @Insert(onConflict = OnConflictStrategy.REPLACE) abstract suspend fun insert(entity: T): Long @Insert(onConflict = OnConflictStrategy.REPLACE) abstract suspend fun insert(entities: List<T>): LongArray @Update abstract suspend fun update(entity: T): Int @Update abstract suspend fun update(entities: List<T>): Int @Delete abstract suspend fun delete(entity: T): Int @Delete abstract suspend fun delete(entities: List<T>): Int }
0
Kotlin
0
0
877068a566b7af9a8d28dd2103801c517f882ac2
672
noti
MIT License
app/src/main/java/io/github/wellingtoncosta/customviews/domain/exception/NetworkException.kt
wellingtoncosta
240,489,091
false
null
package io.github.wellingtoncosta.customviews.domain.exception import java.lang.RuntimeException class NetworkException : RuntimeException("Could not make the http call due an unexpected error.")
0
Kotlin
0
2
8a966f718acc687150134c1dee6cca168a721576
198
android-custom-views
MIT License
impl/misskey/src/main/kotlin/dev/usbharu/multim/misskey/v12/common/MisskeyTimeline.kt
multim-dev
591,652,793
false
null
package dev.usbharu.multim.misskey.v12.common import dev.usbharu.multim.misskey.v12.model.StreamRequest import dev.usbharu.multim.model.Timeline data class MisskeyTimeline( val id: String, override val name: String, val channel: StreamRequest.ConnectRequest.Body.Channel ) : Timeline(name)
8
Kotlin
0
7
daad2d142ae6fa7414acdb6704832a4d477dc41f
304
multim
Apache License 2.0
test-util-android/src/main/java/org/fnives/test/showcase/android/testutil/activity/ActivityScenarioExtensions.kt
fknives
356,982,481
false
null
package org.fnives.test.showcase.android.testutil.activity import android.app.Activity import androidx.test.core.app.ActivityScenario /** * Workaround for issue: https://github.com/android/android-test/issues/676. * * Call this instead of ActivityScenario.close(). */ fun <T : Activity> ActivityScenario<T>.safeClose() { workaroundForActivityScenarioCLoseLockingUp() close() } /** * This should not be needed, we shouldn't use sleep basically ever. * However, it seems to be and issue described here: https://github.com/android/android-test/issues/676 * * If an activity is finished in code, the ActivityScenario.close() can hang 30 to 45 seconds. * This sleep let's the Activity finish it's state change and unlocks the ActivityScenario. * * As soon as that issue is closed, this should be removed as well. */ private fun workaroundForActivityScenarioCLoseLockingUp() { Thread.sleep(1000L) }
9
Kotlin
2
5
5bf503d90e8a13daf5626afc0cdf8bff523d2b94
920
AndroidTest-ShowCase
Apache License 2.0
src/main/kotlin/com/fetchapi/files/ApplicationProperties.kt
Alameyo
422,626,413
false
{"Kotlin": 10166}
package com.fetchapi.files import java.util.Properties class ApplicationProperties { private val inputStream = this::class.java.getResourceAsStream("/app.properties") private val properties = Properties().apply { load(inputStream) } fun getValue(propertyName:String) = properties[propertyName] as String }
0
Kotlin
0
0
7bbbdeb4b5099eefe6a0df86a8186692d4436091
332
FetchApi
MIT License
intellij-plugin-structure/tests/src/test/kotlin/com/jetbrains/plugin/structure/teamcity/action/TestData.kt
JetBrains
3,686,654
false
{"Kotlin": 2524497, "Java": 253600, "CSS": 1454, "JavaScript": 692}
package com.jetbrains.plugin.structure.teamcity.action import com.fasterxml.jackson.annotation.JsonProperty import com.jetbrains.plugin.structure.teamcity.action.TeamCityActionSpec.ActionDescription import com.jetbrains.plugin.structure.teamcity.action.TeamCityActionSpec.ActionInputDefault import com.jetbrains.plugin.structure.teamcity.action.TeamCityActionSpec.ActionInputDescription import com.jetbrains.plugin.structure.teamcity.action.TeamCityActionSpec.ActionInputLabel import com.jetbrains.plugin.structure.teamcity.action.TeamCityActionSpec.ActionInputOptions import com.jetbrains.plugin.structure.teamcity.action.TeamCityActionSpec.ActionInputRequired import com.jetbrains.plugin.structure.teamcity.action.TeamCityActionSpec.ActionInputType import com.jetbrains.plugin.structure.teamcity.action.TeamCityActionSpec.ActionInputs import com.jetbrains.plugin.structure.teamcity.action.TeamCityActionSpec.ActionName import com.jetbrains.plugin.structure.teamcity.action.TeamCityActionSpec.ActionRequirementType import com.jetbrains.plugin.structure.teamcity.action.TeamCityActionSpec.ActionRequirementValue import com.jetbrains.plugin.structure.teamcity.action.TeamCityActionSpec.ActionRequirements import com.jetbrains.plugin.structure.teamcity.action.TeamCityActionSpec.ActionSpecVersion import com.jetbrains.plugin.structure.teamcity.action.TeamCityActionSpec.ActionStepName import com.jetbrains.plugin.structure.teamcity.action.TeamCityActionSpec.ActionStepParams import com.jetbrains.plugin.structure.teamcity.action.TeamCityActionSpec.ActionStepScript import com.jetbrains.plugin.structure.teamcity.action.TeamCityActionSpec.ActionStepWith import com.jetbrains.plugin.structure.teamcity.action.TeamCityActionSpec.ActionSteps import com.jetbrains.plugin.structure.teamcity.action.TeamCityActionSpec.ActionVersion object Actions { val someAction = TeamCityActionBuilder( specVersion = "1.0.0", name = "action_name", version = "1.2.3", description = "some description", steps = listOf( ActionStepBuilder( stepName = "step name", with = "runner/someRunnerName", ) ), ) } object Inputs { val someActionTextInput = ActionInputBuilder( type = "text", ) val someBooleanTextInput = ActionInputBuilder( type = "boolean", ) val someSelectTextInput = ActionInputBuilder( type = "select", selectOptions = listOf("option 1", "option 2"), ) } object Requirements { val someExistsRequirement = ActionRequirementBuilder( type = "exists", ) } object Steps { val someWithStep = ActionStepBuilder( stepName = "some step", with = "runner/some_runner" ) val someScriptStep = ActionStepBuilder( stepName = "some step", script = "echo \"hello world\"" ) } data class TeamCityActionBuilder( @JsonProperty(ActionSpecVersion.NAME) var specVersion: String? = null, @JsonProperty(ActionName.NAME) var name: String? = null, @JsonProperty(ActionVersion.NAME) var version: String? = null, @JsonProperty(ActionDescription.NAME) var description: String? = null, @JsonProperty(ActionInputs.NAME) var inputs: List<Map<String, ActionInputBuilder>> = emptyList(), @JsonProperty(ActionRequirements.NAME) var requirements: List<Map<String, ActionRequirementBuilder>> = emptyList(), @JsonProperty(ActionSteps.NAME) var steps: List<ActionStepBuilder> = emptyList(), ) data class ActionInputBuilder( @JsonProperty(ActionInputType.NAME) var type: String? = null, @JsonProperty(ActionInputRequired.NAME) var required: String? = null, @JsonProperty(ActionInputLabel.NAME) var label: String? = null, @JsonProperty(ActionInputDescription.NAME) var description: String? = null, @JsonProperty(ActionInputDefault.NAME) var defaultValue: String? = null, @JsonProperty(ActionInputOptions.NAME) var selectOptions: List<String> = emptyList(), ) data class ActionRequirementBuilder( @JsonProperty(ActionRequirementType.NAME) var type: String? = null, @JsonProperty(ActionRequirementValue.NAME) var value: String? = null, ) data class ActionStepBuilder( @JsonProperty(ActionStepName.NAME) var stepName: String? = null, @JsonProperty(ActionStepWith.NAME) var with: String? = null, @JsonProperty(ActionStepScript.NAME) var script: String? = null, @JsonProperty(ActionStepParams.NAME) var params: Map<String, String> = emptyMap(), ) fun randomAlphanumeric(len: Int): String { val allowedChars = ('A'..'Z') + ('a'..'z') + ('0'..'9') return (1..len) .map { allowedChars.random() } .joinToString("") }
6
Kotlin
38
178
8be19a2c67854545d719fe56f3677122481b372f
4,566
intellij-plugin-verifier
Apache License 2.0
libraries/tools/kotlin-gradle-plugin/src/main/kotlin/org/jetbrains/kotlin/gradle/incremental/ClasspathSnapshotter.kt
fobo66
403,491,284
false
{"Markdown": 111, "Gradle": 446, "Gradle Kotlin DSL": 558, "Java Properties": 21, "Shell": 52, "Ignore List": 21, "Batchfile": 28, "Git Attributes": 9, "Kotlin": 38553, "Protocol Buffer": 14, "Java": 2601, "Proguard": 13, "Text": 12908, "INI": 178, "XML": 540, "Roff": 217, "Roff Manpage": 38, "AsciiDoc": 1, "YAML": 6, "EditorConfig": 1, "OpenStep Property List": 16, "JSON": 184, "C": 119, "Objective-C": 72, "C++": 209, "LLVM": 1, "Swift": 70, "Pascal": 1, "Python": 5, "CMake": 2, "HTML": 15, "JavaScript": 269, "Objective-C++": 12, "Groovy": 21, "Dockerfile": 4, "Diff": 1, "EJS": 1, "CSS": 6, "Ruby": 6, "JSON with Comments": 9, "JFlex": 2, "Ant Build System": 53, "JAR Manifest": 1, "Graphviz (DOT)": 81, "Maven POM": 78, "Scala": 1}
/* * Copyright 2010-2021 JetBrains s.r.o. and Kotlin Programming Language contributors. * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ package org.jetbrains.kotlin.gradle.incremental import org.jetbrains.kotlin.incremental.* import org.jetbrains.kotlin.name.ClassId import java.io.File import java.util.zip.ZipInputStream /** Computes a [ClasspathEntrySnapshot] of a classpath entry (directory or jar). */ @Suppress("SpellCheckingInspection") object ClasspathEntrySnapshotter { private val DEFAULT_CLASS_FILTER = { unixStyleRelativePath: String, isDirectory: Boolean -> !isDirectory && unixStyleRelativePath.endsWith(".class", ignoreCase = true) && !unixStyleRelativePath.endsWith("module-info.class", ignoreCase = true) && !unixStyleRelativePath.startsWith("meta-inf", ignoreCase = true) } fun snapshot(classpathEntry: File): ClasspathEntrySnapshot { val classes = DirectoryOrJarContentsReader.read(classpathEntry, DEFAULT_CLASS_FILTER) .map { (unixStyleRelativePath, contents) -> ClassFileWithContents(ClassFile(classpathEntry, unixStyleRelativePath), contents) } val snapshots = ClassSnapshotter.snapshot(classes) val relativePathsToSnapshotsMap = classes.map { it.classFile.unixStyleRelativePath }.zip(snapshots).toMap(LinkedHashMap()) return ClasspathEntrySnapshot(relativePathsToSnapshotsMap) } } /** Creates [ClassSnapshot]s of classes. */ @Suppress("SpellCheckingInspection") object ClassSnapshotter { /** * Creates [ClassSnapshot]s of the given classes. * * Note that for Java (non-Kotlin) classes, creating a [ClassSnapshot] for a nested class will require accessing the outer class (and * possibly vice versa). Therefore, outer classes and nested classes must be passed together in one invocation of this method. */ fun snapshot(classes: List<ClassFileWithContents>): List<ClassSnapshot> { // Snapshot Kotlin classes first val kotlinClassSnapshots: Map<ClassFile, KotlinClassSnapshot?> = classes.associate { it.classFile to trySnapshotKotlinClass(it) } // Snapshot Java classes in one invocation val javaClasses: List<ClassFileWithContents> = classes.filter { kotlinClassSnapshots[it.classFile] == null } val snapshots: List<JavaClassSnapshot> = snapshotJavaClasses(javaClasses) val javaClassSnapshots: Map<ClassFile, JavaClassSnapshot> = javaClasses.map { it.classFile }.zip(snapshots).toMap() // Return a snapshot for each class return classes.map { kotlinClassSnapshots[it.classFile] ?: javaClassSnapshots[it.classFile]!! } } /** Creates [KotlinClassSnapshot] of the given class, or returns `null` if the class is not a Kotlin class. */ private fun trySnapshotKotlinClass(clazz: ClassFileWithContents): KotlinClassSnapshot? { return KotlinClassInfo.tryCreateFrom(clazz.contents)?.let { KotlinClassSnapshot(it) } } /** * Creates [JavaClassSnapshot]s of the given Java classes. * * Note that creating a [JavaClassSnapshot] for a nested class will require accessing the outer class (and possibly vice versa). * Therefore, outer classes and nested classes must be passed together in one invocation of this method. */ private fun snapshotJavaClasses(classes: List<ClassFileWithContents>): List<JavaClassSnapshot> { val classFiles = classes.map { it.classFile } val classesContents = classes.map { it.contents } val classNames = classesContents.map { JavaClassName.compute(it) } val classIds = computeJavaClassIds(classNames) // Snapshot special cases first // Map a class index to its snapshot, or `null` if it will be created later val specialCaseSnapshots: Map<Int, JavaClassSnapshot?> = classFiles.indices.associateWith { index -> val className = classNames[index] val classId = classIds[index] if (classId.isLocal) { // A local class can't be referenced from other source files, so any changes in a local class will not cause recompilation // of other source files. Therefore, the snapshot of a local class is empty. // In that regard, a nested class of a local class is also considered local (which matches the definition of // ClassId.isLocal, see ClassId's kdoc). Therefore, we checked `classId.isLocal`, which is a super set of `className is // LocalClass`. EmptyJavaClassSnapshot } else if (className is NestedNonLocalClass && (className.isAnonymous || className.isSynthetic)) { // An anonymous or synthetic class also can't be referenced from other source files, so its snapshot is also empty. EmptyJavaClassSnapshot } else { null } } // Snapshot the remaining classes in one invocation val remainingClassesIndices: List<Int> = classFiles.indices.filter { specialCaseSnapshots[it] == null } val remainingClassIds: List<ClassId> = remainingClassesIndices.map { classIds[it] } val remainingClassesContents: List<ByteArray> = remainingClassesIndices.map { classes[it].contents } val snapshots: List<JavaClassSnapshot> = JavaClassDescriptorCreator.create(remainingClassIds, remainingClassesContents).map { RegularJavaClassSnapshot(it.toSerializedJavaClass()) } val remainingSnapshots: Map<Int, JavaClassSnapshot> /* maps a class index to its snapshot */ = remainingClassesIndices.zip(snapshots).toMap() // Return a snapshot for each class return classFiles.indices.map { specialCaseSnapshots[it] ?: remainingSnapshots[it]!! } } } /** Utility to read the contents of a directory or jar. */ private object DirectoryOrJarContentsReader { /** * Returns a map from Unix-style relative paths of entries to their contents. The paths are relative to the container (directory or * jar). * * The map entries need to satisfy the given filter. * * The map entries are sorted based on their Unix-style relative paths (to ensure deterministic results across filesystems). * * Note: If a jar has duplicate entries, only one of them will be used (there is no guarantee which one will be used). */ fun read( directoryOrJar: File, entryFilter: ((unixStyleRelativePath: String, isDirectory: Boolean) -> Boolean)? = null ): LinkedHashMap<String, ByteArray> { return if (directoryOrJar.isDirectory) { readDirectory(directoryOrJar, entryFilter) } else { check(directoryOrJar.isFile && directoryOrJar.path.endsWith(".jar", ignoreCase = true)) readJar(directoryOrJar, entryFilter) } } private fun readDirectory( directory: File, entryFilter: ((unixStyleRelativePath: String, isDirectory: Boolean) -> Boolean)? = null ): LinkedHashMap<String, ByteArray> { val relativePathsToContents: MutableList<Pair<String, ByteArray>> = mutableListOf() directory.walk().forEach { file -> val unixStyleRelativePath = file.relativeTo(directory).invariantSeparatorsPath if (entryFilter == null || entryFilter(unixStyleRelativePath, file.isDirectory)) { relativePathsToContents.add(unixStyleRelativePath to file.readBytes()) } } return relativePathsToContents.sortedBy { it.first }.toMap(LinkedHashMap()) } private fun readJar( jarFile: File, entryFilter: ((unixStyleRelativePath: String, isDirectory: Boolean) -> Boolean)? = null ): LinkedHashMap<String, ByteArray> { val relativePathsToContents: MutableList<Pair<String, ByteArray>> = mutableListOf() ZipInputStream(jarFile.inputStream().buffered()).use { zipInputStream -> while (true) { val entry = zipInputStream.nextEntry ?: break val unixStyleRelativePath = entry.name if (entryFilter == null || entryFilter(unixStyleRelativePath, entry.isDirectory)) { relativePathsToContents.add(unixStyleRelativePath to zipInputStream.readBytes()) } } } return relativePathsToContents.sortedBy { it.first }.toMap(LinkedHashMap()) } }
1
null
1
1
b71b7abc2bb4c169c826b46abca9f526eaffc284
8,616
kotlin
Apache License 2.0
compiler/testData/codegen/box/jvm8/defaults/nonDefaultInheritance/simple2.kt
JetBrains
3,432,266
false
null
// TARGET_BACKEND: JVM // IGNORE_BACKEND_FIR: JVM_IR // FULL_JDK // JVM_TARGET: 1.8 // WITH_STDLIB // MODULE: lib // !JVM_DEFAULT_MODE: all // FILE: Foo.kt interface Foo { fun toOverride(): List<String> = null!! fun nonOverride(): List<String> = Thread.currentThread().getStackTrace().map { it.className + "." + it.methodName } } // MODULE: main(lib) // !JVM_DEFAULT_MODE: disable // !JVM_DEFAULT_ALLOW_NON_DEFAULT_INHERITANCE // FILE: main.kt interface Derived : Foo { override fun toOverride() = Thread.currentThread().getStackTrace().map { it.className + "." + it.methodName } } class DerivedClass : Derived fun box(): String { val override = DerivedClass().toOverride() if (override[1] != "Derived\$DefaultImpls.toOverride") return "fail 1: ${override[1]}" if (override[2] != "DerivedClass.toOverride") return "fail 2: ${override[2]}" if (override[3] != "MainKt.box") return "fail 3: ${override[3]}" val nonOverride = DerivedClass().nonOverride() if (nonOverride[1] != "Foo.nonOverride") return "fail 3: ${nonOverride[1]}" if (nonOverride[2] != "MainKt.box") return "fail 4: ${nonOverride[2]}" return "OK" }
34
null
5748
49,172
33eb9cef3d146062c103f9853d772f0a1da0450e
1,170
kotlin
Apache License 2.0
VolleySampleApp/app/src/main/java/com/lazypotato/volleysampleapp/data/model/LocalUser.kt
eishon
346,190,149
false
null
package com.lazypotato.volleysampleapp.data.model data class LocalUser(var name: String)
1
Kotlin
1
1
5bb1c98644ee46c9ce108c9e8af7f3b4ba55fdcf
90
Android-Samples
MIT License
octicons/src/commonMain/kotlin/compose/icons/octicons/History24.kt
DevSrSouza
311,134,756
false
null
package com.woowla.compose.icon.collections.octicons.octicons import androidx.compose.ui.graphics.Color import androidx.compose.ui.graphics.PathFillType import androidx.compose.ui.graphics.PathFillType.Companion.NonZero import androidx.compose.ui.graphics.SolidColor import androidx.compose.ui.graphics.StrokeCap import androidx.compose.ui.graphics.StrokeCap.Companion.Butt import androidx.compose.ui.graphics.StrokeJoin import androidx.compose.ui.graphics.StrokeJoin.Companion.Miter import androidx.compose.ui.graphics.vector.ImageVector import androidx.compose.ui.graphics.vector.ImageVector.Builder import androidx.compose.ui.graphics.vector.path import androidx.compose.ui.unit.dp import com.woowla.compose.icon.collections.octicons.Octicons public val Octicons.History24: ImageVector get() { if (_history24 != null) { return _history24!! } _history24 = Builder(name = "History24", defaultWidth = 24.0.dp, defaultHeight = 24.0.dp, viewportWidth = 24.0f, viewportHeight = 24.0f).apply { path(fill = SolidColor(Color(0xFF000000)), stroke = null, strokeLineWidth = 0.0f, strokeLineCap = Butt, strokeLineJoin = Miter, strokeLineMiter = 4.0f, pathFillType = NonZero) { moveTo(11.998f, 2.5f) arcTo(9.503f, 9.503f, 0.0f, false, false, 3.378f, 8.0f) horizontalLineTo(5.75f) arcToRelative(0.75f, 0.75f, 0.0f, false, true, 0.0f, 1.5f) horizontalLineTo(2.0f) arcToRelative(1.0f, 1.0f, 0.0f, false, true, -1.0f, -1.0f) verticalLineTo(4.75f) arcToRelative(0.75f, 0.75f, 0.0f, false, true, 1.5f, 0.0f) verticalLineToRelative(1.697f) arcTo(10.997f, 10.997f, 0.0f, false, true, 11.998f, 1.0f) curveTo(18.074f, 1.0f, 23.0f, 5.925f, 23.0f, 12.0f) reflectiveCurveToRelative(-4.926f, 11.0f, -11.002f, 11.0f) curveTo(6.014f, 23.0f, 1.146f, 18.223f, 1.0f, 12.275f) arcToRelative(0.75f, 0.75f, 0.0f, false, true, 1.5f, -0.037f) arcToRelative(9.5f, 9.5f, 0.0f, false, false, 9.498f, 9.262f) curveToRelative(5.248f, 0.0f, 9.502f, -4.253f, 9.502f, -9.5f) reflectiveCurveToRelative(-4.254f, -9.5f, -9.502f, -9.5f) close() } path(fill = SolidColor(Color(0xFF000000)), stroke = null, strokeLineWidth = 0.0f, strokeLineCap = Butt, strokeLineJoin = Miter, strokeLineMiter = 4.0f, pathFillType = NonZero) { moveTo(12.5f, 7.25f) arcToRelative(0.75f, 0.75f, 0.0f, false, false, -1.5f, 0.0f) verticalLineToRelative(5.5f) curveToRelative(0.0f, 0.27f, 0.144f, 0.518f, 0.378f, 0.651f) lineToRelative(3.5f, 2.0f) arcToRelative(0.75f, 0.75f, 0.0f, false, false, 0.744f, -1.302f) lineTo(12.5f, 12.315f) verticalLineTo(7.25f) close() } } .build() return _history24!! } private var _history24: ImageVector? = null
17
null
25
571
a660e5f3033e3222e3553f5a6e888b7054aed8cd
3,222
compose-icons
MIT License
library/src/main/java/com/bigcreate/library/Network.kt
lihongwen1
277,768,492
true
{"Kotlin": 631709, "Java": 1099}
package com.bigcreate.library import android.annotation.TargetApi import android.app.Application import android.app.DownloadManager import android.content.Context import android.net.ConnectivityManager import android.net.NetworkCapabilities import android.net.NetworkInfo import android.net.wifi.WifiManager import androidx.core.content.ContextCompat.getSystemService import com.google.gson.Gson import okhttp3.* import java.net.Inet4Address import java.net.NetworkInterface val Application.serverAdress:String get() = "192.168.199.1" val Context.ipAddress: String? get() { val connectivityManager = getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager if (connectivityManager.activeNetworkInfo != null && connectivityManager.activeNetworkInfo.isConnected){ val networkCapabilities = connectivityManager.getNetworkCapabilities(connectivityManager.activeNetwork) when(networkCapabilities.connectType){ NetworkCapabilities.TRANSPORT_CELLULAR -> { for (networkInterface in NetworkInterface.getNetworkInterfaces()) { for (item in networkInterface.inetAddresses) if (item.isLoopbackAddress.not() && item is Inet4Address) return item.hostAddress } } NetworkCapabilities.TRANSPORT_WIFI -> { val wifiManager = applicationContext.getSystemService(Context.WIFI_SERVICE) as WifiManager val intIP = wifiManager.connectionInfo.ipAddress return ((intIP and 0xff).toString() + "." + (intIP shr 8 and 0xff) + "." + (intIP shr 16 and 0xff) + "." + (intIP shr 24 and 0xff)) } } } return null } val Context.isConnected:Boolean get() { val info = (getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager).activeNetworkInfo return info!= null && info.isConnected } val NetworkCapabilities.connectType:Int? get() { if (hasTransport(NetworkCapabilities.TRANSPORT_WIFI)) return NetworkCapabilities.TRANSPORT_WIFI if (hasTransport(NetworkCapabilities.TRANSPORT_BLUETOOTH)) return NetworkCapabilities.TRANSPORT_BLUETOOTH if (hasTransport(NetworkCapabilities.TRANSPORT_CELLULAR)) return NetworkCapabilities.TRANSPORT_CELLULAR return null } fun OkHttpClient.getRequest(url:String):ResponseBody?{ return try { val request = Request.Builder() .get() .url(url) .build() newCall(request).execute().body() }catch (e: Exception){ null } } fun OkHttpClient.postRequest(url:String,mediaType:MediaType?,data:String): ResponseBody?{ return try { val requestBody = RequestBody.create(mediaType,data) val request = Request.Builder() .url(url) .post(requestBody) .build() newCall(request).execute().body() }catch (e:Exception){ null } } val Context.isNetworkActive:Boolean get(){ return true }
0
null
0
0
1daecfa286190935a6c9b8eef46ec13911cce830
3,174
ProjectZYFW
Apache License 2.0
extension-overlay/src/main/kotlin/fr/o80/twitck/overlay/events/EventsHolder.kt
olivierperez
283,750,838
false
null
package fr.o80.twitck.overlay.events import fr.o80.twitck.overlay.model.LwjglEvent import java.util.* class EventsHolder( private val maxSize: Int ) { private val _events = LinkedList<LwjglEvent>() val events: List<LwjglEvent> get() = _events.toList() fun record(event: LwjglEvent) { if (_events.size == maxSize) _events.pollFirst() _events.offerLast(event) } }
0
Kotlin
1
5
bb2828260ae6837f87ebb71bce11e383be514f53
415
TwitckBot
Apache License 2.0
specs/spring-cloud-contract-spec-kotlin/src/main/kotlin/org/springframework/cloud/contract/spec/internal/CommonDsl.kt
spring-cloud
60,979,397
false
null
/* * Copyright 2013-2020 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * 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 org.springframework.cloud.contract.spec.internal import java.io.File import java.net.URISyntaxException import java.nio.charset.Charset import java.util.regex.Pattern /** * Composed out of common variables and funtions. * * @author <NAME> * @since 2.2.0 */ open class CommonDsl { /* HELPER VARIABLES */ /* REGEX */ val onlyAlphaUnicode: RegexProperty get() = RegexPatterns.onlyAlphaUnicode() val alphaNumeric: RegexProperty get() = RegexPatterns.alphaNumeric() val number: RegexProperty get() = RegexPatterns.number() val positiveInt: RegexProperty get() = RegexPatterns.positiveInt() val anyBoolean: RegexProperty get() = RegexPatterns.anyBoolean() val anInteger: RegexProperty get() = RegexPatterns.anInteger() val aDouble: RegexProperty get() = RegexPatterns.aDouble() val ipAddress: RegexProperty get() = RegexPatterns.ipAddress() val hostname: RegexProperty get() = RegexPatterns.hostname() val email: RegexProperty get() = RegexPatterns.email() val anUrl: RegexProperty get() = RegexPatterns.url() val anHttpsUrl: RegexProperty get() = RegexPatterns.httpsUrl() val uuid: RegexProperty get() = RegexPatterns.uuid() val isoDate: RegexProperty get() = RegexPatterns.isoDate() val isoDateTime: RegexProperty get() = RegexPatterns.isoDateTime() val isoTime: RegexProperty get() = RegexPatterns.isoTime() val iso8601WithOffset: RegexProperty get() = RegexPatterns.iso8601WithOffset() val nonEmpty: RegexProperty get() = RegexPatterns.nonEmpty() val nonBlank: RegexProperty get() = RegexPatterns.nonBlank() /* HELPER FUNCTIONS */ /** * Helper method to provide a better name for the consumer side. * @param clientValue client value * @return client dsl property */ fun client(clientValue: Any?) = ClientDslProperty(clientValue) /** * Helper method to provide a better name for the consumer side. * @param clientValue client value * @return client dsl property */ fun c(clientValue: Any?) = ClientDslProperty(clientValue) /** * Helper method to provide a better name for the consumer side. * @param clientValue client value * @return client dsl property */ fun consumer(clientValue: Any?) = ClientDslProperty(clientValue) /** * Helper method to provide a better name for the consumer side. * @param clientValue client value * @return client dsl property */ fun stub(clientValue: Any?) = ClientDslProperty(clientValue) /** * Helper method to provide a better name for the server side. * @param serverValue server value * @return server dsl property */ fun server(serverValue: Any?) = ServerDslProperty(serverValue) /** * Helper method to provide a better name for the server side. * @param serverValue server value * @return server dsl property */ fun p(serverValue: Any?) = ServerDslProperty(serverValue) /** * Helper method to provide a better name for the server side. * @param serverValue server value * @return server dsl property */ fun producer(serverValue: Any?) = ServerDslProperty(serverValue) /** * Helper method to provide a better name for the server side. * @param serverValue server value * @return server dsl property */ fun test(serverValue: Any?) = ServerDslProperty(serverValue) /** * Helper method to indicate an optional property. * @param value the optional property value * @return optional dsl property */ fun optional(value: Any?) = OptionalProperty(value) /** * Helper method to indicate that a method needs to be executed during testing. * @param commandToExecute the name of the method to execute * @return execution dsl property */ fun execute(commandToExecute: String) = ExecutionProperty(commandToExecute) /** * Read file contents as String. * @param relativePath of the file to read * @return String file contents */ fun file(relativePath: String) = file(relativePath, Charset.defaultCharset()) /** * Read file contents as String with the given Charset. * @param relativePath of the file to read * @param charset to use for converting the bytes to String * @return String file contents */ fun file(relativePath: String, charset: Charset) = FromFileProperty(fileLocation(relativePath), String::class.java, charset) /** * Read file contents as String with the given Charset. * @param relativePath of the file to read * @param charset to use for converting the bytes to String * @return String file contents */ fun fileAsBytes(relativePath: String) = FromFileProperty(fileLocation(relativePath), ByteArray::class.java) /** * Read file contents as String using a default charset (mostly UTF-8). * @param relativePath of the file to read * @return Body DSL property with the content of the file as String */ fun bodyFromFile(relativePath: String) = bodyFromFile(relativePath, Charset.defaultCharset()) /** * Read file contents as String using the provided file encoding. * @param relativePath of the file to read * @param charset of the file's encoding * @return Body the body with the String as its content */ fun bodyFromFile(relativePath: String, charset: Charset) = Body(FromFileProperty(fileLocation(relativePath), String::class.java, charset)) /** * Read file contents as bytes[]. * @param relativePath of the file to read * @return Body the body with the byte array as its content */ fun bodyFromFileAsBytes(relativePath: String) = Body(FromFileProperty(fileLocation(relativePath), ByteArray::class.java)) /** * Read file contents as array of bytes. * @param relativePath of the file to read * @return file contents as an array of bytes */ private fun fileLocation(relativePath: String): File { val resource = Thread.currentThread().contextClassLoader .getResource(relativePath) ?: throw IllegalStateException("File [$relativePath] is not present") try { return File(resource.toURI()) } catch (ex: URISyntaxException) { throw IllegalStateException(ex) } } fun named(name: DslProperty<Any>, value: DslProperty<Any>) = NamedProperty(name, value) fun named(name: DslProperty<Any>, value: DslProperty<Any>, contentType: DslProperty<Any>) = NamedProperty(name, value, contentType) fun named(namedMap: Map<String, DslProperty<Any>>) = NamedProperty(namedMap) /* REGEX FUNCTIONS */ fun regexProperty(value: Any) = RegexProperty(value) fun regex(regex: String) = regexProperty(Pattern.compile(regex)) fun regex(regex: Pattern) = regexProperty(regex) fun regex(regex: RegexProperty) = regex }
84
null
438
719
011719228a07f9826f3a993cd20f793a281fb7ed
7,752
spring-cloud-contract
Apache License 2.0
alertview/src/main/java/com/irozon/alertview/enums/AlertActionStyle.kt
Hamadakram
125,224,240
false
null
package co.utils.alertview.enums /** * Created by hammad.akram on 3/14/18. */ enum class AlertActionStyle { POSITIVE, NEGATIVE, DEFAULT }
14
null
48
268
7bbfade45258d8afeb0a514bc3462f900ab352c2
152
AlertView
Apache License 2.0
nebulosa-phd2-client/src/main/kotlin/nebulosa/phd2/client/event/GuidingStopped.kt
tiagohm
568,578,345
false
null
package nebulosa.phd2.client.event object GuidingStopped : PHD2Event
2
Kotlin
0
2
9ccdfa8049d8ff034d282c065e71aec1a6ea6ab8
70
nebulosa
MIT License
app/src/main/java/com/stocksexchange/android/database/tables/AlertPriceTable.kt
nscoincommunity
277,168,471
true
{"Kotlin": 2814235}
package com.stocksexchange.android.database.tables import com.stocksexchange.android.database.daos.AlertPriceDao import com.stocksexchange.android.database.model.DatabaseAlertPrice import com.stocksexchange.android.database.tables.base.BaseTable import com.stocksexchange.android.mappings.mapToDatabaseAlertPriceList import com.stocksexchange.android.mappings.mapToAlertPriceList import com.stocksexchange.android.mappings.mapToDatabaseAlertPrice import com.stocksexchange.api.model.rest.AlertPrice import com.stocksexchange.api.model.rest.AlertPriceDeleteResponse import com.stocksexchange.api.model.rest.parameters.AlertPriceParameters import com.stocksexchange.core.model.Result class AlertPriceTable( private val alertPriceDao: AlertPriceDao ) : BaseTable() { @Synchronized fun save(priceAlert: List<AlertPrice>) { alertPriceDao.insert(priceAlert.mapToDatabaseAlertPriceList()) } @Synchronized fun save(priceAlert: AlertPrice): Result<AlertPrice> { alertPriceDao.insert(priceAlert.mapToDatabaseAlertPrice()) return Result.Success(priceAlert) } @Synchronized fun deleteAll() { alertPriceDao.deleteAll() } @Synchronized fun get(params: AlertPriceParameters): Result<List<AlertPrice>> { return alertPriceDao.get().toResult( List<DatabaseAlertPrice>::mapToAlertPriceList ) } @Synchronized fun getByPairId(id: Int): Result<List<AlertPrice>> { return alertPriceDao.getAlertPriceByPairId(id).toResult( List<DatabaseAlertPrice>::mapToAlertPriceList ) } @Synchronized fun delete(id: Int): Result<AlertPriceDeleteResponse> { alertPriceDao.delete(id) return Result.Success(AlertPriceDeleteResponse("ok")) } }
0
null
0
0
52766afab4f96506a2d9ed34bf3564b6de7af8c3
1,799
Android-app
MIT License
app/src/main/java/com/hegesoftware/snookerscore/domain/usecases/GetPlayerInTurn.kt
Henkkagg
611,836,646
false
null
package com.hegesoftware.snookerscore.domain.usecases import com.hegesoftware.snookerscore.data.BreakDb import javax.inject.Inject class GetPlayerInTurn @Inject constructor() { operator fun invoke(breakDb: BreakDb): Int { return if (breakDb.breakId % 2 == 1) 1 else 2 } }
0
Kotlin
0
0
4c2a96c64c9edea1f44689e75697a8af3cb47588
291
SnookerScore
Apache License 2.0
core/src/jvmMain/kotlin/live/MutableLive.kt
aSoft-Ltd
345,266,100
false
null
package live import functions.Function1 import live.internal.DEFAULT_HISTORY_CAPACITY import kotlin.jvm.JvmOverloads import kotlin.jvm.JvmStatic import kotlin.jvm.JvmSynthetic @Deprecated("use cinematic instead") actual interface MutableLive<S> : Live<S> { actual override val history: MutableList<S> actual override var value: S actual fun undo() actual fun redo() /** * Transforms this live to another live */ @JvmSynthetic actual override fun <R> map(transformer: (S) -> R): MutableLive<R> override fun <R> map(transformer: Function1<S, R>): MutableLive<R> /** * Notify the watchers without changing the underlying value */ actual fun dispatch(value: S) actual fun dispatch() companion object { @JvmStatic @JvmOverloads fun <S> of(value: S, capacity: Int = DEFAULT_HISTORY_CAPACITY): MutableLive<S> = mutableLiveOf(value, capacity) } }
0
null
1
2
c71ec769818d33593298482002d4b11c7b3f1c66
944
live
MIT License
app/src/main/java/com/franzliszt/magicmusic/bean/search/HotSearch.kt
FranzLiszt-1847
753,088,527
false
{"Kotlin": 879960, "Java": 1923}
package com.franzliszt.magicmusic.bean.search data class HotSearch( val first: String, val iconType: Int, val second: Int, val third: Any )
0
Kotlin
1
1
dcbc4c0cb9c0478e617423812712659df52a3b7d
156
MagicPlayer
Apache License 2.0
src/main/kotlin/com/github/kyzylsy/cryptography/rsa/model/RSAKeyPair.kt
kyzylsy
133,613,780
false
null
package com.github.kyzylsy.cryptography.rsa.model import java.security.PrivateKey import java.security.PublicKey import java.util.* /** * @author LSteven * @date 2018/5/16 下午4:15. */ class RSAKeyPair constructor(val publicKey: PublicKey, val privateKey: PrivateKey) { fun binaryPublicKey() = publicKey.encoded fun binaryPrivateKey() = privateKey.encoded fun stringPublicKey() = Base64.getEncoder().encodeToString(binaryPublicKey()) fun stringPrivateKey() = Base64.getEncoder().encodeToString(binaryPrivateKey()) }
0
Kotlin
0
0
c27ca8731504010f79793178812cb1280f5c1a98
565
cryptography-helper
MIT License
src/Day01.kt
Tiebe
579,377,778
false
{"Kotlin": 17146}
fun main() { fun part1(input: List<String>): MutableList<Int> { val sumList = mutableListOf(0) var index = 0 input.forEach { if (it == "") { index++; sumList.add(0) } else { sumList[index] += it.toInt() } } return sumList } fun part2(input: List<String>): Int { val sumList = part1(input) var sum = 0 repeat(3) { sum += sumList.maxOrNull() ?: 0 sumList.remove(sumList.maxOrNull() ?: 0) } return sum } // test if implementation meets criteria from the description, like: val testInput = readInput("Day01_test") check((part1(testInput).maxOrNull() ?: 0) == 24000) check(part2(testInput) == 45000) val input = readInput("Day01") (part1(input).maxOrNull() ?: 0).println() part2(input).println() }
1
Kotlin
0
0
afe9ac46b38e45bd400e66d6afd4314f435793b3
900
advent-of-code
Apache License 2.0
build-logic/conventions/src/main/kotlin/modulecheck/builds/DependencyGuardConventionPlugin.kt
rickbusarow
316,627,145
false
null
/* * Copyright (C) 2021-2023 Rick Busarow * 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 modulecheck.builds import com.dropbox.gradle.plugins.dependencyguard.DependencyGuardPluginExtension import com.rickbusarow.kgx.EagerGradleApi import com.rickbusarow.kgx.applyOnce import com.rickbusarow.kgx.dependsOn import com.rickbusarow.kgx.matchingName import org.gradle.api.Plugin import org.gradle.api.Project import org.gradle.api.tasks.Delete import org.gradle.language.base.plugins.LifecycleBasePlugin abstract class DependencyGuardConventionPlugin : Plugin<Project> { override fun apply(target: Project) { if (target == target.rootProject) { return } target.plugins.applyOnce("org.jetbrains.kotlin.jvm") target.plugins.applyOnce("com.dropbox.dependency-guard") target.extensions.configure(DependencyGuardPluginExtension::class.java) { extension -> extension.configuration("runtimeClasspath") { it.modules = false } } target.tasks.named(LifecycleBasePlugin.CHECK_TASK_NAME) .dependsOn(DEPENDENCY_GUARD_CHECK_TASK_NAME) // Delete any existing dependency files/directories before recreating with a new baseline task. val dependencyGuardDeleteBaselines = target.tasks .register("dependencyGuardDeleteBaselines", Delete::class.java) { it.delete("dependencies") it.mustRunAfter(DEPENDENCY_GUARD_BASELINE_TASK_NAME) } @OptIn(EagerGradleApi::class) target.tasks.named(DEPENDENCY_GUARD_BASELINE_TASK_NAME) { it.finalizedBy( target.rootProject.tasks.matchingName(DependencyGuardAggregatePlugin.AGGREGATE_TASK_NAME) ) } @OptIn(EagerGradleApi::class) target.tasks.named(DEPENDENCY_GUARD_CHECK_TASK_NAME) { it.dependsOn( target.rootProject.tasks.matchingName(DependencyGuardAggregatePlugin.EXPLODE_TASK_NAME) ) it.finalizedBy(dependencyGuardDeleteBaselines) } } companion object { const val DEPENDENCY_GUARD_CHECK_TASK_NAME = "dependencyGuard" const val DEPENDENCY_GUARD_BASELINE_TASK_NAME = "dependencyGuardBaseline" } }
76
null
7
129
5934de0bc8edc688b088324437b05a974073267e
2,622
ModuleCheck
Apache License 2.0
app/src/main/java/com/example/custom_snackbar/ui/MainActivity.kt
kishandonga
170,486,665
false
{"Kotlin": 30328, "Java": 135}
package com.example.custom_snackbar.ui import android.content.Intent import android.os.Bundle import androidx.appcompat.app.AppCompatActivity import com.example.custom_snackbar.databinding.ActivityMainBinding import com.example.custom_snackbar.utils.themeConst class MainActivity : AppCompatActivity() { private lateinit var binding: ActivityMainBinding override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) binding = ActivityMainBinding.inflate(layoutInflater) setContentView(binding.root) binding.btnWithCL.setOnClickListener { startNewActivity(CoordinatorLayoutAct::class.java) } binding.btnWithoutCL.setOnClickListener { startNewActivity(SimpleAct::class.java) } binding.btnCustomView.setOnClickListener { startNewActivity(CustomViewAct::class.java) } binding.btnDrawableAct.setOnClickListener { startNewActivity(DrawableAct::class.java) } } private fun startNewActivity(cls: Class<*>) { val theme = if (binding.rbAppCompact.isChecked) 0 else 1 val intent = Intent(this, cls).apply { putExtra(themeConst, theme) } startActivity(intent) } }
1
Kotlin
1
12
fb9fe9f7c0ba0626520b510f545633581726fd06
1,287
custom-snackbar
Apache License 2.0