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
src/test/java/com/github/greennick/properties/generic/FirePropertyTest.kt
green-nick
170,363,475
false
null
package com.github.greennick.properties.generic import com.github.greennick.properties.firePropertyOf import org.junit.Test class FirePropertyTest { @Test fun `listener triggered only once`() { var calls = 0 val property = firePropertyOf("Hello") property.subscribe { calls++ } property.subscribe { calls++ } assert(calls == 1) } @Test fun `listener triggered after new assignment`() { var calls = 0 val property = firePropertyOf("Hello") property.subscribe { calls++ } property.value = "new" assert(calls == 2) } @Test fun `listener triggered on equal values assignment`() { val initValue = "Hello" val property = firePropertyOf(initValue) var calls = 0 property.subscribe { calls++ } property.value = initValue assert(calls == 2) } @Test fun `only last subscription is active`() { val property = firePropertyOf("Hello") val firstSubscription = property.subscribe { } val secondSubscription = property.subscribe { } assert(secondSubscription.subscribed) assert(!firstSubscription.subscribed) } }
0
Kotlin
0
8
969741bf9750634e7c5a673c7551746fc4a1e1ab
1,243
properties
MIT License
src/main/kotlin/archives/tater/netherarchives/Utils.kt
JosiahFu
711,624,418
false
{"Kotlin": 54202, "Java": 9054}
package archives.tater.netherarchives import net.minecraft.util.math.BlockPos import net.minecraft.util.math.random.Random // iterateInSquare uses the same blockPos object and mutates it, so we need this to use proper collection operations fun Iterable<BlockPos>.listCopy(): List<BlockPos> = map(BlockPos::mutableCopy) fun <T> Iterable<T>.draw(random: Random, count: Int = 1): List<T> { val pool = this.toMutableList() return (0 until count.coerceAtMost(pool.size)) .map { pool.removeAt(random.nextInt(pool.size)) } }
0
Kotlin
0
0
e6f81c0ddc5d06ad6ff4101a15b72c8ef7cadbce
537
NetherArchives
Creative Commons Zero v1.0 Universal
app/src/main/java/com/example/electrorui/ui/adapters/FamiliaAdapter.kt
Christian9324
699,140,999
false
{"Kotlin": 328590}
package com.example.electrorui.ui.adapters import android.view.LayoutInflater import android.view.ViewGroup import androidx.recyclerview.widget.RecyclerView import com.example.electrorui.databinding.ViewFamiliasItemBinding import com.example.electrorui.databinding.ViewRegistroItemBinding import com.example.electrorui.usecase.model.Iso import com.example.electrorui.usecase.model.RegistroFamilias class FamiliaAdapter( var registroByFamilia : List<Int>, private val familiasClickedListener: (Int, Int) -> Unit // se modifico esta linea labda ) : RecyclerView.Adapter<FamiliaAdapter.ViewHolder>() { override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder { val binding = ViewFamiliasItemBinding.inflate( LayoutInflater.from(parent.context), parent, false ) return ViewHolder(binding) } override fun onBindViewHolder(holder: ViewHolder, position: Int) { val registro = registroByFamilia[position] holder.bind(registro) holder.itemView.setOnClickListener { familiasClickedListener(registro, position) // Se modifico esta linea lambda } } override fun getItemCount() = registroByFamilia.size class ViewHolder(private val binding: ViewFamiliasItemBinding) : RecyclerView.ViewHolder(binding.root){ fun bind(registro : Int){ binding.tvTotal.text = registro.toString() } } }
0
Kotlin
0
0
0f764b77a7f70e6be41a357e9c1f9cfee8a79a3e
1,466
RUIElectronicoA
The Unlicense
cobalt.core/src/commonMain/kotlin/org/hexworks/cobalt/databinding/api/collection/ObservableListBinding.kt
ethanmdavidson
408,243,027
true
{"Kotlin": 203396}
package org.hexworks.cobalt.databinding.api.collection import kotlinx.collections.immutable.PersistentList import org.hexworks.cobalt.databinding.api.binding.Binding import org.hexworks.cobalt.databinding.api.event.ListChange interface ObservableListBinding<T : Any> : ObservableList<T>, Binding<PersistentList<T>>
0
Kotlin
0
0
80b98772607ff80eb6a6f60fcaec09fdb262649a
317
cobalt
Apache License 2.0
klinechart/src/main/java/com/liihuu/klinechart/model/WrModel.kt
liihuu
163,390,765
false
null
package com.liihuu.klinechart.model import android.os.Parcelable import kotlinx.android.parcel.Parcelize /** * @Author lihu <EMAIL> * @Date 2019-05-14-19:13 */ @Parcelize data class WrModel( val wr1: Double?, val wr2: Double?, val wr3: Double? ): Parcelable
5
Kotlin
13
60
67625eda0b9709078e007d713c2de26f29e03184
274
KLineChartAndroid
MIT License
src/main/kotlin/mcpc/tedo627/commandshortcut/gui/ShortcutSettingGui.kt
tedo0627
458,543,279
false
{"Kotlin": 14978}
package mcpc.tedo627.commandshortcut.gui import mcpc.tedo627.commandshortcut.Shortcut import mcpc.tedo627.commandshortcut.ShortcutManager import net.minecraft.client.Minecraft import net.minecraft.client.gui.FontRenderer import net.minecraft.client.gui.screen.Screen import net.minecraft.client.gui.widget.TextFieldWidget import net.minecraft.client.gui.widget.Widget import net.minecraft.client.gui.widget.button.Button import net.minecraft.client.resources.I18n import net.minecraft.client.util.InputMappings import net.minecraft.util.text.StringTextComponent class ShortcutSettingGui(private val manager: ShortcutManager) : Screen(StringTextComponent("shortcut settings gui")) { companion object { const val VISIBLE_COUNT = 6 } private var scrollStep = 0 private val scrolls = mutableListOf<ScrollItem>() override fun init() { scrolls.clear() val list = manager.all for (shortcut in list) addScroll(ScrollItem(this, font, width, height, manager, shortcut)) addButton(Button(width / 2 - 20, height / 5 + 200, 40, 20, "add") { manager.add() this@ShortcutSettingGui.scrollStep = this@ShortcutSettingGui.scrolls.size + 1 - VISIBLE_COUNT init() }) } private fun addScroll(item: ScrollItem) { val buttons = item.buttons for (i in 0 until buttons.size) addButton(buttons[i]) scrolls.add(item) } override fun render(arg1: Int, arg2: Int, arg3: Float) { renderBackground() font.drawString("command", (width / 10).toFloat(), 50f, 0xFFFFFF) font.drawString("key1", (width / 10 + 120).toFloat(), 50f, 0xFFFFFF) font.drawString("key2", (width / 10 + 240).toFloat(), 50f, 0xFFFFFF) font.drawString("key3", (width / 10 + 360).toFloat(), 50f, 0xFFFFFF) font.drawString("enable", (width / 10 + 485).toFloat(), 50f, 0xFFFFFF) val size = scrolls.size for (i in 0 until size) { if (VISIBLE_COUNT >= size) { scrolls[i].render(i, i) scrolls[i].visible() continue } if (scrollStep <= i && i < scrollStep + VISIBLE_COUNT) { scrolls[i].render(i - scrollStep, i) scrolls[i].visible() continue } scrolls[i].invisible() } super.render(arg1, arg2, arg3) } override fun mouseScrolled(arg1: Double, arg2: Double, arg3: Double): Boolean { scrollStep -= arg3.toInt() if (scrollStep > scrolls.size - VISIBLE_COUNT) scrollStep = scrolls.size - VISIBLE_COUNT if (scrollStep < 0) scrollStep = 0 return super.mouseScrolled(arg1, arg2, arg3) } override fun onClose() { manager.save() super.onClose() } class ScrollItem( private val screen: Screen, private val font: FontRenderer, private val width: Int, private val height: Int, private val manager: ShortcutManager, private val shortcut: Shortcut ) { val buttons = mutableListOf<Widget>() init { buttons.add(TextFieldWidget(font, width / 10, height / 5, 100, 20, "").run { text = shortcut.command setValidator { shortcut.command = it true } this }) buttons.add(Button(width / 10 + 120, height / 5, 100, 20, getKeyName(shortcut.key1)) { Minecraft.getInstance().displayGuiScreen(SelectKeyGui(screen, shortcut, 1)) }) buttons.add(Button(width / 10 + 240, height / 5, 100, 20, getKeyName(shortcut.key2)) { Minecraft.getInstance().displayGuiScreen(SelectKeyGui(screen, shortcut, 2)) }) buttons.add(Button(width / 10 + 360, height / 5, 100, 20, getKeyName(shortcut.key3)) { Minecraft.getInstance().displayGuiScreen(SelectKeyGui(screen, shortcut, 3)) }) buttons.add(Button(width / 10 + 480, height / 5, 50, 20, if (shortcut.enabled) "§aenabled" else "§cdisabled") { shortcut.enabled = !shortcut.enabled it.message = if (shortcut.enabled) "§aenabled" else "§cdisabled" }) buttons.add(Button(width / 10 + 540, height / 5, 20, 20, "§4x") { manager.remove(shortcut) Minecraft.getInstance().displayGuiScreen(screen) }) } fun visible() { for (i in 0 until buttons.size) { buttons[i].visible = true } } fun invisible() { for (i in 0 until buttons.size) { buttons[i].visible = false } } fun render(step: Int, index: Int) { for (i in 0 until buttons.size) { val button = buttons[i] button.y = (height / 5) + (30 * step) } font.drawString("${index + 1}:", (width / 10 - 20).toFloat(), ((height / 5) + (30 * step) + 6).toFloat(), 0xFFFFFF) font.drawString("+", (width / 10 + 230 - 2).toFloat(), ((height / 5) + (30 * step) + 6).toFloat(), 0xFFFFFF) font.drawString("+", (width / 10 + 350 - 2).toFloat(), ((height / 5) + (30 * step) + 6).toFloat(), 0xFFFFFF) } private fun getKeyName(name: String): String { val input = InputMappings.getInputByName(name) val keyName = InputMappings.getKeynameFromKeycode(input.keyCode) if (keyName != null) return keyName if (I18n.hasKey(name)) return I18n.format(name) return I18n.format("key.mouse", name.removePrefix("key.mouse.")) } } }
0
Kotlin
0
0
3119d3f10def24503d346b159dd0f2c3911a0ff2
5,780
CommandShortcut
MIT License
src/test/kotlin/no/nav/samordning/hendelser/feed/FeedControllerTest.kt
navikt
156,209,069
false
{"Kotlin": 62825, "Dockerfile": 88}
package no.nav.samordning.hendelser.feed import io.zonky.test.db.AutoConfigureEmbeddedDatabase import no.nav.pensjonsamhandling.maskinporten.validation.test.AutoConfigureMaskinportenValidator import no.nav.pensjonsamhandling.maskinporten.validation.test.MaskinportenValidatorTokenGenerator import no.nav.samordning.hendelser.security.support.SCOPE_SAMORDNING import org.junit.jupiter.api.Test import org.junit.jupiter.params.ParameterizedTest import org.junit.jupiter.params.provider.CsvSource import org.junit.jupiter.params.provider.ValueSource import org.springframework.beans.factory.annotation.Autowired import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc import org.springframework.boot.test.context.SpringBootTest import org.springframework.http.MediaType import org.springframework.test.web.servlet.* @SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT) @AutoConfigureMaskinportenValidator @AutoConfigureEmbeddedDatabase(provider = AutoConfigureEmbeddedDatabase.DatabaseProvider.ZONKY) @AutoConfigureMockMvc internal class FeedControllerTest { @Autowired private lateinit var maskinportenValidatorTokenGenerator: MaskinportenValidatorTokenGenerator @Autowired private lateinit var mockMvc: MockMvc @ParameterizedTest(name = "Valid requests returns ok with content") @ValueSource(strings = [URL_VEDTAK, URL_TP_YTELSER]) fun `valid requests returns ok with content`(url: String) { mockMvc.get(url) { headers { setBearerAuth(maskinportenValidatorTokenGenerator.generateToken(SCOPE_SAMORDNING, "889640782").serialize()) } }.andDo { print() } .andExpect { status { isOk() } content { contentType(MediaType.APPLICATION_JSON) } } } @ParameterizedTest(name = "Service should not accept too large requests") @ValueSource(strings = [URL_VEDTAK, URL_TP_YTELSER]) fun `service shouldnt accept too large requests`(url: String) { mockMvc.get(url) { headers { setBearerAuth(maskinportenValidatorTokenGenerator.generateToken(SCOPE_SAMORDNING, "889640782").serialize()) } param("antall", "10001") }.andDo { print() }.andExpect { status { is4xxClientError() } } } @ParameterizedTest(name = "Should return message from service with first record") @CsvSource("$URL_VEDTAK, 01016600000", "$URL_TP_YTELSER, 14087459887") fun `should return message from service with first record`(url: String, expected: String) { mockMvc.get("$url&antall=1") { headers { setBearerAuth(maskinportenValidatorTokenGenerator.generateToken(SCOPE_SAMORDNING, "889640782").serialize()) } }.andExpect { jsonPath("$.hendelser[0].identifikator") { value(expected) } }.andDo { print() } } @ParameterizedTest(name = "Should return message from service with size check") @CsvSource("/hendelser/vedtak?tpnr=4000&side=0&antall=5, 3", "$URL_TP_YTELSER&antall=5, 2") fun `should return message from service with size check`(url: String, expected: String) { mockMvc.get(url) { headers { setBearerAuth(maskinportenValidatorTokenGenerator.generateToken(SCOPE_SAMORDNING, "889640782").serialize()) } }.andExpect { jsonPath("$.hendelser.size()") { value(expected.toInt()) } } } @Test fun bad_parameters_return_400() { mockMvc.get("/hendelser?tpnr=4000&side=-1") { headers { setBearerAuth(maskinportenValidatorTokenGenerator.generateToken(SCOPE_SAMORDNING, "889640782").serialize()) } }.andDo { print() } .andExpect { status { isBadRequest() } } } companion object { private const val URL_VEDTAK = "/hendelser/vedtak?tpnr=1000" private const val URL_TP_YTELSER = "/hendelser/ytelser?tpnr=3010" } }
4
Kotlin
0
1
94b652018725327dcc71be4d9dde03b64406bced
4,086
samordning-hendelse-api
MIT License
draftsman/src/main/kotlin/com/gojek/draftsman/internal/drawer/ModernDrawerLayout.kt
gojek
457,289,341
false
{"Kotlin": 81164}
package com.gojek.draftsman.internal.drawer import android.animation.Animator import android.animation.AnimatorSet import android.animation.ObjectAnimator import android.animation.ValueAnimator import android.content.Context import android.graphics.* import android.graphics.Paint.ANTI_ALIAS_FLAG import android.graphics.drawable.ColorDrawable import android.graphics.drawable.Drawable import android.util.AttributeSet import android.view.MotionEvent import android.view.MotionEvent.* import android.view.View import android.view.View.MeasureSpec.* import android.view.ViewGroup import android.view.animation.AccelerateDecelerateInterpolator import com.gojek.draftsman.R import kotlin.math.abs import kotlin.math.min private val TAG = ModernDrawerLayout::class.java.simpleName internal class ModernDrawerLayout @JvmOverloads constructor( context: Context, attributeSet: AttributeSet? = null, defStyleRes: Int = 0 ) : ViewGroup( context, attributeSet, defStyleRes ) { private val sliderShapeDimension = dpToPx(72, resources) private var orientation = Orientation.HORIZONTAL_RIGHT private var peekDistance = 0f private var bgDrawable: Drawable = ColorDrawable(Color.LTGRAY) private var sliderBitmap: Bitmap? = null private var expanded = false private val bitmapStartingPoint = PointF() private val touchArea = RectF() private val sliderIconRect = Rect() private var drawerOpenIcon: Drawable? = null private var drawerCloseIcon: Drawable? = null private var drawerIcon: Drawable? = null private var previousX = 0f private var maxTranslation = 0f private var animator: Animator? = null private var motionDownTime: Long = 0 private var sliderPath = Path() private val shadowPaint = Paint(ANTI_ALIAS_FLAG).apply { color = Color.WHITE setShadowLayer(dpToPx(8, context.resources), 0f, 0f, Color.LTGRAY) } private val overlayPaint = Paint(ANTI_ALIAS_FLAG).apply { color = Color.parseColor("#999999") alpha = 0 } init { setWillNotDraw(false) attributeSet?.let(::initAttrs) } fun setIcons(openIcon: Drawable, closeIcon: Drawable) { drawerOpenIcon = openIcon drawerCloseIcon = closeIcon drawerIcon = drawerOpenIcon } fun collapse() { if (expanded) { collapseDrawer() } } override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) { require(childCount <= 1) { "ModernDrawerLayout can have only one child" } var width = getSize(widthMeasureSpec) var height = getSize(heightMeasureSpec) var widthMeasureMode = getMode(widthMeasureSpec) var heightMeasureMode = getMode(heightMeasureSpec) if (widthMeasureMode != EXACTLY && heightMeasureMode != EXACTLY) { if (isInEditMode) { if (widthMeasureMode == AT_MOST) { widthMeasureMode = EXACTLY } else if (widthMeasureMode == UNSPECIFIED) { widthMeasureMode = EXACTLY width = 300 } if (heightMeasureMode == AT_MOST) { heightMeasureMode = EXACTLY } else if (heightMeasureMode == UNSPECIFIED) { heightMeasureMode = EXACTLY height = 300 } } else { throw IllegalArgumentException("ModernDrawerLayout has to be measured exactly") } } if (orientation == Orientation.HORIZONTAL_LEFT || orientation == Orientation.HORIZONTAL_RIGHT ) { width += resources.displayMetrics.widthPixels - peekDistance.toInt() } else { height += resources.displayMetrics.heightPixels - peekDistance.toInt() } setMeasuredDimension(width, height) val childLp = getChildAt(0).layoutParams val childWidthMeasureSpec = getChildMeasureSpec(widthMeasureSpec, paddingLeft + paddingRight, childLp.width) val childHeightMeasureSpec = getChildMeasureSpec(heightMeasureSpec, paddingTop + paddingBottom, childLp.height) getChildAt(0).measure(childWidthMeasureSpec, childHeightMeasureSpec) maxTranslation = -min( width - resources.displayMetrics.widthPixels - peekDistance - sliderShapeDimension, getChildAt(0).measuredWidth - peekDistance ) } override fun onLayout(changed: Boolean, p1: Int, p2: Int, p3: Int, p4: Int) { val child = getChildAt(0) child.layout( resources.displayMetrics.widthPixels - peekDistance.toInt(), paddingTop, resources.displayMetrics.widthPixels - peekDistance.toInt() + child.measuredWidth, paddingTop + measuredHeight ) if (changed) { generateSliderBitmap() } } override fun dispatchDraw(canvas: Canvas) { canvas.apply { drawPaint(overlayPaint) val count = save() translate(bitmapStartingPoint.x, bitmapStartingPoint.y) drawPath(sliderPath, shadowPaint) drawBitmap(sliderBitmap!!, 0f, 0f, null) restoreToCount(count) } drawerIcon?.bounds = sliderIconRect drawerIcon?.draw(canvas) super.dispatchDraw(canvas) } override fun onTouchEvent(event: MotionEvent): Boolean { return when (event.actionMasked) { ACTION_DOWN -> { motionDownTime = System.currentTimeMillis() touchArea.contains(event.x, event.y) } ACTION_UP -> { if (System.currentTimeMillis() - motionDownTime <= 300) { toggleState() } else { expandOrCollapse() } previousX = 0f true } ACTION_MOVE -> { moveDrawer(event.rawX) false } else -> false } } override fun onDetachedFromWindow() { if (animator?.isRunning == true) { animator?.cancel() } super.onDetachedFromWindow() } private fun generateSliderBitmap() { bitmapStartingPoint.x = resources.displayMetrics.widthPixels - peekDistance - sliderShapeDimension bitmapStartingPoint.y = 0f val result = DrawerPathGenerator( height, resources, sliderShapeDimension, peekDistance ).getPath( orientation, getChildAt(0).measuredWidth ) sliderBitmap = Bitmap.createBitmap( getChildAt(0).measuredWidth + sliderShapeDimension.toInt(), height, Bitmap.Config.ARGB_8888 ) if (null != background) { if (bgDrawable != background) { bgDrawable = background setBackgroundResource(0) } else { bgDrawable = ColorDrawable(Color.WHITE) } } bgDrawable.bounds = Rect( 0, 0, getChildAt(0).measuredWidth + sliderShapeDimension.toInt(), height ) val canvas = Canvas(sliderBitmap!!).apply { clipPath(result.first) } bgDrawable.draw(canvas) touchArea.set(result.second) calculateIconDrawRect() sliderPath = result.first } private fun expandDrawer() { val expandAnimation = ObjectAnimator.ofFloat( this, View.TRANSLATION_X, maxTranslation ).apply { duration = 500 interpolator = AccelerateDecelerateInterpolator() addListener(object : DefaultAnimationListener() { override fun onAnimationEnd(animation: Animator?) { expanded = true onStateChanged() } }) } val overlayAnimation = ValueAnimator.ofInt(overlayPaint.alpha, 127).apply { duration = 500 interpolator = AccelerateDecelerateInterpolator() addUpdateListener { overlayPaint.alpha = it.animatedValue as Int postInvalidate() } } animator = AnimatorSet().apply { playTogether(overlayAnimation, expandAnimation) start() } expanded = true } private fun collapseDrawer() { val collapseAnimation = ObjectAnimator.ofFloat( this, View.TRANSLATION_X, 0f ).apply { duration = 500 interpolator = AccelerateDecelerateInterpolator() addListener(object : DefaultAnimationListener() { override fun onAnimationEnd(animation: Animator?) { expanded = false onStateChanged() } }) } val overlayAnimation = ValueAnimator.ofInt(overlayPaint.alpha, 0).apply { duration = 500 interpolator = AccelerateDecelerateInterpolator() addUpdateListener { overlayPaint.alpha = it.animatedValue as Int postInvalidate() } } animator = AnimatorSet().apply { playTogether(overlayAnimation, collapseAnimation) start() } expanded = false } private fun toggleState() { if (expanded) { collapseDrawer() } else { expandDrawer() } } private fun calculateIconDrawRect() { val vCenter = (touchArea.top + (touchArea.bottom - touchArea.top) / 2).toInt() val hCenter = (touchArea.left + (touchArea.right - touchArea.left) / 2).toInt() val iconDimensionHalf = dpToPx(16, resources).toInt() sliderIconRect.apply { top = vCenter - iconDimensionHalf bottom = vCenter + iconDimensionHalf left = hCenter - iconDimensionHalf right = hCenter + iconDimensionHalf } } private fun initAttrs(attributeSet: AttributeSet) { val typedArray = context.obtainStyledAttributes(attributeSet, R.styleable.ModernDrawerLayout) peekDistance = typedArray.getDimension(R.styleable.ModernDrawerLayout_peekDistance, peekDistance) drawerOpenIcon = typedArray.getDrawable(R.styleable.ModernDrawerLayout_drawerOpenIcon) drawerCloseIcon = typedArray.getDrawable(R.styleable.ModernDrawerLayout_drawerCloseIcon) typedArray.recycle() drawerIcon = drawerOpenIcon } private fun onStateChanged() { drawerIcon = if (expanded) drawerCloseIcon else drawerOpenIcon invalidate() } private fun moveDrawer(x: Float) { if (previousX != 0f) { val dx = x - previousX previousX = x var newTranslationX = translationX + dx if (newTranslationX < maxTranslation) { newTranslationX = maxTranslation } else if (newTranslationX > 0) { newTranslationX = 0f } translationX = newTranslationX overlayPaint.alpha = (127 * abs(newTranslationX / maxTranslation)).toInt() postInvalidate() } else { previousX = x } } private fun expandOrCollapse() { if (translationX != 0f || translationX != maxTranslation) { val distanceToExpand = maxTranslation - translationX if (abs(distanceToExpand) > abs(translationX)) { collapseDrawer() } else { expandDrawer() } } } }
2
Kotlin
18
254
b0909fb15abad702dd8b8a985f7c60e2f92bdbf0
11,849
draftsman
Apache License 2.0
app/src/main/java/com/santi/rickymortyapi/data/CharacterPagingSource.kt
GedankenExperiment
425,820,755
false
{"Kotlin": 29159}
package com.santi.rickymortyapi.data import android.net.Uri import android.util.Log import androidx.paging.PagingSource import androidx.paging.PagingState import com.santi.rickymortyapi.model.FullCharacter import com.santi.rickymortyapi.model.FullLocation import com.santi.rickymortyapi.network.RetrofitService import java.lang.Exception class CharacterPagingSource (private val retrofitService: RetrofitService) : PagingSource<Int, FullCharacter>() { override fun getRefreshKey(state: PagingState<Int, FullCharacter>): Int? { return state.anchorPosition } override suspend fun load(params: LoadParams<Int>): LoadResult<Int, FullCharacter> { return try { val nextPage : Int = params.key ?: FIRST_PAGE_INDEX val response = retrofitService.getCharacters(nextPage) var nextPageNumber : Int? = null if (response.info.next != null){ val uri = Uri.parse(response.info.next) val nextPageQuery = uri.getQueryParameter("page") nextPageNumber = nextPageQuery?.toInt() } LoadResult.Page(data = response.results, prevKey = null, nextKey = nextPageNumber) }catch(e: Exception){ LoadResult.Error(e) } } companion object{ private const val FIRST_PAGE_INDEX = 1 } // Character by ID suspend fun getLocation(locationUrl: String): FullLocation { return try { val response = retrofitService.getLocation(locationUrl.replace("https://rickandmortyapi.com/api/location/", "")) FullLocation(created = response.created, dimension = response.dimension, id = response.id, name = response.name, type = response.type, url = response.url) }catch(e: Exception){ FullLocation("error", "error", -1, "name", "error", "error") } } }
0
Kotlin
0
0
1034530cf9471bda930700c2b86870e451534532
1,977
RickyMorty
Apache License 2.0
module/parser/src/jsMain/kotlin/org/cru/godtools/tool/JsParserConfig.kt
CruGlobal
310,338,913
false
null
package org.cru.godtools.tool import org.cru.godtools.tool.model.DeviceType internal actual val DEFAULT_SUPPORTED_DEVICE_TYPES = setOf(DeviceType.WEB)
4
Kotlin
1
0
d5ed4bd5446a994124b281070ab565feb6f33cc4
153
kotlin-mpp-godtools-tool-parser
MIT License
http-api-client/src/commonTest/kotlin/au/com/redcrew/apisdkcreator/httpclient/matchers/matchers.kt
RedCrewOS
370,915,550
false
null
package au.com.redcrew.apisdkcreator.httpclient.matchers import arrow.core.* import io.kotest.matchers.Matcher import io.kotest.matchers.MatcherResult fun <T> notEqual(expected: T, actual: T): Boolean = expected != actual fun <T> MatcherResult.Companion.test(predicate: (T, T) -> Boolean, expected: T, actual: T): Option<MatcherResult> = when (predicate(expected, actual)) { true -> MatcherResult.failure(expected, actual).some() false -> none() } fun <T> MatcherResult.Companion.failure(expected: T, actual: T): MatcherResult = MatcherResult( false, { "$actual should be $expected" }, { "$actual should not be $expected" } ) fun Matcher.Companion.tests(results: List<Option<MatcherResult>>): MatcherResult = results.sequenceOption().fold( { MatcherResult(true, { "value matches expected" }, { "value does not match expected" } ) }, List<MatcherResult>::first ) fun Matcher.Companion.tests(vararg results: Option<MatcherResult>): MatcherResult = Matcher.tests(results.asList())
0
HTML
0
1
33e3f58c55ef61e4b4124223b5c77c32ee0f0412
1,072
api-sdk-creator-kotlin
MIT License
app/src/main/java/com/example/pd/register/RegisterFragment.kt
notjl
573,363,827
false
{"Kotlin": 14534}
package com.example.pd.register import android.os.Bundle import android.view.* import androidx.fragment.app.Fragment import android.widget.Toast import androidx.fragment.app.activityViewModels import androidx.navigation.findNavController import androidx.navigation.fragment.findNavController import androidx.navigation.ui.NavigationUI import com.example.pd.MainApplication import com.example.pd.R import com.example.pd.databinding.FragmentRegisterBinding class RegisterFragment : Fragment() { private val viewModel: RegisterViewModel by activityViewModels { RegisterViewModelFactory( (activity?.application as MainApplication).database .userDao() ) } private var _binding: FragmentRegisterBinding? = null private val binding get() = _binding!! override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View? { _binding = FragmentRegisterBinding.inflate(inflater, container, false) setHasOptionsMenu(true) return binding.root } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) binding.registerButton.setOnClickListener { addNewUser() } } private fun isEntryValid(): Boolean { return viewModel.isEntryValid( username = binding.username.text.toString(), password = binding.password.text.toString(), confirmPassword = binding.confirmPassword.text.toString() ) } private fun isPasswordSimilar(): Boolean { return viewModel.isPasswordSimilar( password = binding.password.text.toString(), confirmPassword = binding.confirmPassword.text.toString() ) } private fun addNewUser() { if (isEntryValid()) if (isPasswordSimilar()) { viewModel.addNewUser( username = binding.username.text.toString(), password = binding.password.text.toString() ) Toast.makeText(requireActivity(), "Added ${binding.username.text}", Toast.LENGTH_LONG).show() val action = RegisterFragmentDirections.actionRegisterFragmentToLoginFragment() findNavController().navigate(action) } else Toast.makeText(requireActivity(), "Password is not the same", Toast.LENGTH_LONG).show() else Toast.makeText(requireActivity(), "Missing information", Toast.LENGTH_LONG).show() } override fun onCreateOptionsMenu(menu: Menu, inflater: MenuInflater) { super.onCreateOptionsMenu(menu, inflater) inflater.inflate(R.menu.options_menu, menu) } override fun onOptionsItemSelected(item: MenuItem): Boolean { return NavigationUI.onNavDestinationSelected(item, requireView().findNavController()) || super.onOptionsItemSelected(item) } }
0
Kotlin
0
0
e60704f8ed9c6f9886c363bc39e07f81e16cd306
3,030
BioPin-Companion-App
MIT License
lse-reference/src/jsMain/kotlin/game/Item.kt
Cdm2883
755,032,373
false
{"Kotlin": 98556}
// https://github.com/LiteLDev/LegacyScriptEngine/blob/main/src/legacy/api/ItemAPI.cpp external class LLSE_Item(nullptr: Nothing) {} typealias Item = LLSE_Item
0
Kotlin
0
3
7b643091e4bd6f8c0c62ddf00d458a0af9fbea3a
161
levilamina-kotlin-js-plugin-template
Apache License 2.0
app/src/main/java/com/sama/integration/google/calendar/domain/Exceptions.kt
sama-app
363,692,054
false
null
package com.sama.integration.google.calendar.domain import java.util.UUID class ChannelClosedException(channelId: UUID) : RuntimeException("Channel#$channelId is already closed")
0
Kotlin
1
2
a73319e26a22bf09aeb6bcc1cc2feaf3723ba0b9
180
sama-service
Apache License 2.0
app/src/main/java/com/filippoengidashet/johnlewis/mvvm/data/model/dto/AdditionalServices.kt
filippoengidashet
457,080,903
false
{"Kotlin": 45679}
package com.filippoengidashet.johnlewis.mvvm.data.model.dto /** * @author <NAME> * @version 1.0.0 * @since Tue, 08/02/2022 at 13:17. */ class AdditionalServices(val includedServices: List<String>?)
0
Kotlin
0
0
656c9b6e072453e525256da0d2815c157713eeba
203
John-Lewis-Products
Apache License 2.0
producer/src/main/kotlin/streams/procedures/StreamsProcedures.kt
F-Guardian
218,759,208
true
{"Kotlin": 869548, "Python": 4123}
package streams.procedures import kotlinx.coroutines.runBlocking import kotlinx.coroutines.sync.Mutex import kotlinx.coroutines.sync.withLock import org.neo4j.graphdb.GraphDatabaseService import org.neo4j.kernel.internal.GraphDatabaseAPI import org.neo4j.logging.Log import org.neo4j.procedure.Context import org.neo4j.procedure.Description import org.neo4j.procedure.Mode import org.neo4j.procedure.Name import org.neo4j.procedure.Procedure import streams.StreamsEventRouter import streams.StreamsTransactionEventHandler import streams.events.StreamsEventBuilder import streams.events.StreamsPluginStatus import streams.utils.StreamsUtils import java.util.concurrent.ConcurrentHashMap import java.util.stream.Stream class StreamsProcedures { @JvmField @Context var log: Log? = null @JvmField @Context var db: GraphDatabaseService? = null @Procedure(mode = Mode.READ, name = "streams.publish.sync") @Description("streams.publish.sync(topic, payload, config) - Allows custom synchronous streaming from Neo4j to the configured stream environment") fun sync(@Name("topic") topic: String?, @Name("payload") payload: Any?, @Name(value = "config", defaultValue = "{}") config: Map<String, Any>?): Stream<StreamPublishResult> { checkEnabled() if (isTopicNullOrEmpty(topic)) { return Stream.empty() } checkPayloadNotNull(payload) val streamsEvent = buildStreamEvent(topic!!, payload!!) return getEventRouter(db!!)?.sendEventsSync(topic, listOf(streamsEvent), config ?: emptyMap()) ?.map { StreamPublishResult(it) } .orEmpty() .stream() } @Procedure(mode = Mode.READ, name = "streams.publish") @Description("streams.publish(topic, payload, config) - Allows custom streaming from Neo4j to the configured stream environment") fun publish(@Name("topic") topic: String?, @Name("payload") payload: Any?, @Name(value = "config", defaultValue = "{}") config: Map<String, Any>?) { checkEnabled() if (isTopicNullOrEmpty(topic)) { return } checkPayloadNotNull(payload) val streamsEvent = buildStreamEvent(topic!!, payload!!) getEventRouter(db!!)?.sendEvents(topic, listOf(streamsEvent), config ?: emptyMap()) } private fun isTopicNullOrEmpty(topic: String?): Boolean { return if (topic.isNullOrEmpty()) { log?.info("Topic empty, no message sent") true } else { false } } private fun checkEnabled() { if (getEventRouter(db!!)?.eventRouterConfiguration?.proceduresEnabled == false) { throw RuntimeException("In order to use the procedure you must set streams.procedures.enabled=true") } } private fun checkPayloadNotNull(payload: Any?) { if (payload == null) { log?.error("Payload empty, no message sent") throw RuntimeException("Payload may not be null") } } private fun buildStreamEvent(topic: String, payload: Any) = StreamsEventBuilder() .withPayload(payload) .withNodeRoutingConfiguration(getEventRouter(db!!)?.eventRouterConfiguration ?.nodeRouting ?.filter { it.topic == topic } ?.firstOrNull()) .withRelationshipRoutingConfiguration(getEventRouter(db!!)?.eventRouterConfiguration ?.relRouting ?.filter { it.topic == topic } ?.firstOrNull()) .withTopic(topic) .build() companion object { private val cache = ConcurrentHashMap<String, Pair<StreamsEventRouter, StreamsTransactionEventHandler>>() private fun getEventRouter(db: GraphDatabaseService) = cache[StreamsUtils.getName(db as GraphDatabaseAPI)]?.first fun registerEventRouter(db: GraphDatabaseAPI, pair: Pair<StreamsEventRouter, StreamsTransactionEventHandler>) = cache .put(StreamsUtils.getName(db), pair) fun unregisterEventRouter(db: GraphDatabaseAPI) = cache.remove(StreamsUtils.getName(db)) fun hasStatus(db: GraphDatabaseAPI, status: StreamsPluginStatus) = cache[StreamsUtils.getName(db)]?.second?.status() == status fun isRegistered(db: GraphDatabaseAPI) = getEventRouter(db) != null } }
0
Kotlin
0
1
a1f6db9dab305bd5d15827ee81f3020f8cf1362e
4,403
neo4j-streams
Apache License 2.0
app/src/main/java/com/tommannson/familycooking/ui/screens/recipe/create/state/steps/RecipeExtractionStep.kt
TomMannson
742,552,338
false
{"Kotlin": 194627}
package com.tommannson.familycooking.ui.screens.recipe.create.state.steps import androidx.compose.runtime.Stable import androidx.compose.runtime.derivedStateOf import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.setValue import com.tommannson.familycooking.ui.screens.recipe.create.state.RecipeCreationState import com.tommannson.familycooking.ui.screens.recipe.create.state.UIEffect import com.tommannson.familycooking.ui.screens.recipe.create.state.data.CollectedData import com.tommannson.familycooking.ui.screens.recipe.create.state.data.TextExtraction import com.tommannson.familycooking.ui.state.ScreenProperties import com.tommannson.familycooking.ui.state.UiAction import com.tommannson.familycooking.ui.state.finishErrorRestartable import com.tommannson.familycooking.ui.state.finishSuccessfully import com.tommannson.familycooking.ui.state.startAction interface AcceptingImageStep { fun acceptImageForProcessing(): List<AcceptingUiEffect> fun notifyProcessingResult(result: Result<String>): AcceptingUiEffect? } interface Restartable { fun restart(): List<AcceptingUiEffect> } @Stable class RecipeExtractionStep( dataConfig: CollectedData, override val screenInfo: ScreenProperties = ScreenProperties.initial(), textRecognitionActionConfig: UiAction, tryAgainActionConfig: UiAction, ) : RecipeCreationState, Restartable, AcceptingImageStep { override var data by mutableStateOf(dataConfig) private set var textRecognitionAction by mutableStateOf(textRecognitionActionConfig) private set var tryAgainAction by mutableStateOf(tryAgainActionConfig) private set override val progressActive: Boolean by derivedStateOf { textRecognitionAction.state is UiAction.State.InProgress || tryAgainAction.state is UiAction.State.InProgress } // override fun restart() { // manager.dispatchEffects(listOf(RecipeExtractionEffects.Restarted)) // } // // fun loadImageAgain() { // manager.dispatchEffects(listOf(RecipeExtractionEffects.Restarted)) // } // // fun acceptImage() { // manager.dispatchEffects(listOf(RecipeExtractionEffects.Restarted)) // } override fun restart(): List<AcceptingUiEffect> { return buildList { if (textRecognitionAction.canBeExecuted()) { add(AcceptingUiEffect.Restarted) } } } override fun acceptImageForProcessing(): List<AcceptingUiEffect> { return buildList { // if (textRecognitionAction.canBeExecuted()) { textRecognitionAction = textRecognitionAction.startAction() add(AcceptingUiEffect.AcceptanceTrigger) // } } } override fun notifyProcessingResult(result: Result<String>): AcceptingUiEffect? { if (textRecognitionAction.isWaitingForResult()) { result.onSuccess { loadedRecipeText -> val extractedTextInfo = data.extractedText?.copy(loadedRecipeText) ?: TextExtraction(loadedRecipeText) textRecognitionAction.finishSuccessfully() data = data.copy(extractedText = extractedTextInfo) return AcceptingUiEffect.AcceptanceFinishedCorrectly }.onFailure { textRecognitionAction.finishErrorRestartable(15) } } return null } } sealed interface AcceptingUiEffect : UIEffect { data object Restarted : AcceptingUiEffect data object AcceptanceTrigger : AcceptingUiEffect data object AcceptanceFinishedCorrectly : AcceptingUiEffect }
0
Kotlin
0
0
b18a988014fd7875d525479f3bd350a219e0cbce
3,743
CookMe
MIT License
src/main/kotlin/app/domain/entities/values/Password.kt
bed72
664,335,364
false
{"Kotlin": 19877}
package app.domain.entities.values import arrow.core.Nel import arrow.core.right import arrow.core.Either import arrow.core.leftNel import app.domain.entities.Message @JvmInline value class Password private constructor(val value: String) { operator fun invoke() = value companion object { operator fun invoke(value: String?): Either<Nel<Message>, Password> = when { value == null -> Message("A senha não pode ser nula.").leftNel() value.length <= 4 -> Message("A senha precisa conter mais que 4 caracteres.").leftNel() value.length >= 16 -> Message("A senha precisa conter mamenos que 16 caracteres.").leftNel() isValid(value) -> Password(value).right() else -> Message("Preencha uma senha válida.").leftNel() } private fun isValid(value: String): Boolean { val regex = Regex("^(?=.*[a-z])(?=.*[A-Z])(?=.*\\d).+") return regex.matches(value) } } }
0
Kotlin
0
0
7d4d93f97afcb3dbfc8406fbb5997073bbe1cc5f
1,019
KingsCross
Apache License 2.0
modules/query-es/src/main/kotlin/com/farcsal/query/es/EBooleanField.kt
fzoli
541,286,565
false
{"Kotlin": 369907, "ANTLR": 1659}
/* * Copyright 2022 <NAME> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.farcsal.query.es import com.farcsal.query.api.BooleanField import com.farcsal.query.api.Criteria class EBooleanField(private val fieldName: String) : BooleanField { override fun not(): Criteria { return isFalse() } override fun and(right: Criteria): Criteria { return isTrue().and(right) } override fun or(right: Criteria): Criteria { return isTrue().or(right) } override fun isNull(): Criteria { return ECriteria(isNull(fieldName)) } override fun isNotNull(): Criteria { return ECriteria(isNotNull(fieldName)) } override fun isTrue(): Criteria { return ECriteria(equalsGeneral(fieldName, true)) } override fun isFalse(): Criteria { return ECriteria(equalsGeneral(fieldName, false)) } }
0
Kotlin
0
1
f15a2fa71eedb13057331d1b59433adb2e437e19
1,411
dql-kotlin
Apache License 2.0
src/main/kotlin/com/booleworks/kjobs/control/polling/LongPollManager.kt
booleworks
627,499,254
false
{"Kotlin": 348126}
package com.booleworks.kjobs.control.polling import com.booleworks.kjobs.control.polling.NopLongPollManager.subscribe import com.booleworks.kjobs.data.JobStatus import com.booleworks.kjobs.data.PollStatus import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Deferred import kotlin.time.Duration /** * Interface for classes which can handle the "backend mechanism" of long polls. * * A long poll manager implements a mechanism which is very similar to the publish-subscribe pattern. * It must offer the possibility to publish [successful][publishSuccess] and [unsuccessful][publishFailure] * results and pass this information to all subscribers. * * **Note that the implementation is not trivial in applications with multiple instances**. * A naive implementation for multiple instances would be to constantly query the persistence layer * for updates on the subscribed UUIDs. * The [RedisLongPollManager] uses the pub/sub mechanism of Redis for the implementation of this task. */ interface LongPollManager { /** * This method is called when the job with the given [uuid] was successfully computed, i.e. is now in status * [JobStatus.SUCCESS] and the result is ready to be retrieved. * The implementing method should pass this information to all [subscribed][subscribe] clients, preferably * (but depending on the implementation concept) on all instances of the application. */ fun publishSuccess(uuid: String) /** * This method is called when the job with the given [uuid] was computed with error, i.e. is now in status * [JobStatus.FAILURE] and the error message is ready to be retrieved. * The implementing method should pass this information to all [subscribed][subscribe] clients, preferably * (but depending on the implementation concept) on all instances of the application. */ fun publishFailure(uuid: String) /** * Allows the caller to subscribe to a [uuid]. The result should be a [deferred value][Deferred] providing * a [PollStatus]. If [publishSuccess] with the respective [uuid] is called within the given [timeout], * the deferred value should return [PollStatus.SUCCESS]. If [publishFailure] with the respective [uuid] * is called within the given [timeout], the deferred value should return [PollStatus.FAILURE]. * * If no relevant publish call is encountered within the given timeout, the deferred value should return * [PollStatus.TIMEOUT]. * * The method is expected to return quickly. Especially it should not wait for the corresponding `publish` * call for the uuid. Instead, the caller must [wait for][Deferred.await] the poll to finish. * * The [CoroutineScope] context object can be used to launch the coroutines required for waiting for the * result. * * Note that cleanup at the end of the call can be scheduled using [Deferred.invokeOnCompletion]. * * If the subscription is not required anymore, the returned Deferred object will be * [cancelled][kotlinx.coroutines.cancelAndJoin]. * * Returning [PollStatus.ABORTED] is not intended right now, since it is only used if the status of the * job is [JobStatus.CANCELLED] or [JobStatus.CANCEL_REQUESTED] at the beginning of the poll. */ fun CoroutineScope.subscribe(uuid: String, timeout: Duration): Deferred<PollStatus> } /** * Dummy implementation of a long poll manager. It ignores publish calls and throws an error on [subscribe] * calls, thus it is used as default implementation when long polling is not enabled (which has the advantage * that we can publish results whether or not long polling is enabled). */ internal object NopLongPollManager : LongPollManager { override fun publishSuccess(uuid: String) { // Do nothing } override fun publishFailure(uuid: String) { // Do nothing } override fun CoroutineScope.subscribe(uuid: String, timeout: Duration): Deferred<PollStatus> { error("Long Polling not supported") } }
0
Kotlin
0
3
c0c9e66cc5987ac0dc9a8f0e262dfd24547efad7
4,070
kjobs
MIT License
app/src/main/kotlin/com/adriangl/pokeapi_mvvm/utils/injection/KodeinUtils.kt
davidbaena
209,520,325
true
{"Kotlin": 47564}
package com.adriangl.pokeapi_mvvm.utils.injection import androidx.annotation.MainThread import androidx.fragment.app.Fragment import androidx.fragment.app.FragmentActivity import androidx.lifecycle.ViewModel import androidx.lifecycle.ViewModelProvider import androidx.lifecycle.ViewModelProviders import mini.Store import org.kodein.di.DKodein import org.kodein.di.Kodein import org.kodein.di.KodeinAware import org.kodein.di.bindings.NoArgBindingKodein import org.kodein.di.bindings.NoArgSimpleBindingKodein import org.kodein.di.direct import org.kodein.di.generic.* /** * Work based on: https://proandroiddev.com/android-viewmodel-dependency-injection-with-kodein-249f80f083c9 */ /** * Binds a store in a Kodein module, assuming that it's a singleton dependency. */ inline fun <reified T : Store<*>> Kodein.Builder.bindStore(noinline creator: NoArgSimpleBindingKodein<*>.() -> T) { bind<T>() with singleton(creator = creator) bind<Store<*>>().inSet() with singleton { instance<T>() } } /** * Binds a ViewModel to a Kotlin module, assuming that it's a provided dependency. */ inline fun <reified T : ViewModel> Kodein.Builder.bindViewModel(overrides: Boolean? = null, noinline creator: NoArgBindingKodein<*>.() -> T) { bind<T>(T::class.java.simpleName, overrides) with provider(creator) } /** * [ViewModelProvider.Factory] implementation that relies in Kodein injector to retrieve ViewModel * instances. * * Optionally you can decide if you want all instances to be force-provided by module bindings or * if you allow creating new instances of them via [Class.newInstance] with [allowNewInstance]. * The default is true to mimic the default behaviour of [ViewModelProviders.of]. */ class KodeinViewModelFactory( private val injector: DKodein, private val allowNewInstance: Boolean = true ) : ViewModelProvider.Factory { @Suppress("UNCHECKED_CAST") override fun <T : ViewModel> create(modelClass: Class<T>): T { return injector.instanceOrNull<ViewModel>(tag = modelClass.simpleName) as T? ?: if (allowNewInstance) { modelClass.newInstance() } else { throw RuntimeException("The class ${modelClass.name} cannot be provided as no Kodein bindings could be found") } } } /** * Injects a [ViewModel] into a [FragmentActivity] that implements [KodeinAware]. */ @MainThread inline fun <reified VM : ViewModel, T> T.viewModel(): Lazy<VM> where T : KodeinAware, T : FragmentActivity { return lazy { ViewModelProviders.of(this, direct.instance()).get(VM::class.java) } } /** * Injects a [ViewModel] into a [Fragment] that implements [KodeinAware]. */ @MainThread inline fun <reified VM : ViewModel, T> T.viewModel(): Lazy<VM> where T : KodeinAware, T : Fragment { return lazy { ViewModelProviders.of(this, direct.instance()).get(VM::class.java) } }
0
null
0
0
964c0254c243102d92fa3c29f32863700c2e8b09
2,902
PokeApiMiniMVVM
Apache License 2.0
app/src/main/java/com/example/deamhome/presentation/detail/ProductDetailActivity.kt
S-OSTeam
686,905,420
false
{"Kotlin": 67631}
package com.example.deamhome.presentation.detail import android.os.Bundle import androidx.lifecycle.lifecycleScope import com.example.deamhome.R import com.example.deamhome.app.DeamHomeApplication import com.example.deamhome.common.base.BindingActivity import com.example.deamhome.databinding.ActivityProductDetailBinding import kotlinx.coroutines.launch class ProductDetailActivity : BindingActivity<ActivityProductDetailBinding>(R.layout.activity_product_detail) { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) binding.tv.setOnClickListener { lifecycleScope.launch { DeamHomeApplication.container.authRepository.removeToken() } } } }
0
Kotlin
0
0
753cf19f1ad7e492876b3ed31c96150bd17050e5
756
shop-app
MIT License
jvm/word-finder/src/main/kotlin/net/maelbrancke/filip/service/ApplicationStarter.kt
filipmaelbrancke
597,192,385
false
{"Rust": 268793, "Kotlin": 47518, "Shell": 17239, "Dockerfile": 478, "PLpgSQL": 238}
package net.maelbrancke.filip.service import arrow.core.Either import arrow.core.raise.either import net.maelbrancke.filip.DomainError import net.maelbrancke.filip.WordCombination import net.maelbrancke.filip.logger import net.maelbrancke.filip.repo.WordPersistence interface ApplicationStarter { suspend fun insertProvidedData(): Either<DomainError, List<WordCombination>> } fun providedDataLoader( wordPersistence: WordPersistence, wordsLoader: WordsLoader ): ApplicationStarter = object : ApplicationStarter { val logger = logger() override suspend fun insertProvidedData(): Either<DomainError, List<WordCombination>> = either { logger.info("Loading sample data") val wordCombinations = wordsLoader.gatherInputWords().bind() wordPersistence.deleteAll() wordPersistence.insertAll(wordCombinations) wordCombinations } }
0
Rust
0
0
cc93acb760ec3d2b5ec150d8ef545869704d36a4
969
playground
MIT License
sdk/src/main/kotlin/com/tpay/sdk/server/dto/parts/PayerUrlDTO.kt
tpay-com
702,885,281
false
{"Kotlin": 521890}
package com.tpay.sdk.server.dto.parts import androidx.annotation.Keep import org.json.JSONObject @Keep internal class PayerUrlDTO : JSONObject() { var success: String? = null set(value) { put("success", value) field = value } var error: String? = null set(value) { put("error", value) field = value } }
0
Kotlin
1
0
b75aa85efa7cabbd628e95111b770d9b2cc2b639
393
tpay-android
MIT License
kotunil/src/commonTest/kotlin/eu/sirotin/kotunil/currency/TurkishLiraTest.kt
vsirotin
542,600,036
false
{"Kotlin": 1297267, "Java": 163060, "JavaScript": 67657, "HTML": 7913}
package eu.sirotin.kotunil.currency import kotlin.test.Test import kotlin.test.assertEquals internal class TurkishLiraTest { @Test fun testCreation() { assertEquals(TRY, TurkishLira()) assertEquals(12.TRY, TurkishLira(12.0)) } @Test fun testUnitSymbols() { val s = TRY.unitSymbols() assertEquals("TRY", s) } @Test fun testCategorySymbols() { val s = TRY.categorySymbols() assertEquals("`₺`", s) } @Test fun getDimensions() { val s = TRY.dimensions.factors.first().specification.unitSymbol assertEquals("TRY", s) } }
15
Kotlin
4
95
6283b7edc3b39e1275f7a7111ecc709e8ae5c402
637
si-units
Apache License 2.0
src/main/kotlin/br/com/zup/edu/pix/registra/NovaChavePixService.kt
matheuscosantos
346,376,080
true
{"Kotlin": 58754, "Dockerfile": 167}
package br.com.zup.edu.pix.registra import br.com.zup.edu.integration.bcb.BancoCentralClient import br.com.zup.edu.integration.bcb.CreatePixKeyRequest import br.com.zup.edu.integration.itau.ContasDeClientesNoItauClient import br.com.zup.edu.pix.ChavePix import br.com.zup.edu.pix.ChavePixExistenteException import br.com.zup.edu.pix.ChavePixRepository import io.micronaut.http.HttpStatus import io.micronaut.validation.Validated import org.slf4j.LoggerFactory import javax.inject.Inject import javax.inject.Singleton import javax.transaction.Transactional import javax.validation.Valid @Validated @Singleton class NovaChavePixService( @Inject val repository: ChavePixRepository, @Inject val itauClient: ContasDeClientesNoItauClient, @Inject val bcbClient: BancoCentralClient, ) { private val LOGGER = LoggerFactory.getLogger(this::class.java) @Transactional fun registra(@Valid novaChave: NovaChavePix): ChavePix { if (repository.existsByChave(novaChave.chave)) throw ChavePixExistenteException("Chave Pix '${novaChave.chave}' existente") val response = itauClient.buscaContaPorTipo(novaChave.clienteId!!, novaChave.tipoDeConta!!.name) val conta = response.body()?.toModel() ?: throw IllegalStateException("Cliente não encontrado no Itau") val chave = novaChave.toModel(conta) repository.save(chave) val bcbRequest = CreatePixKeyRequest.of(chave).also { LOGGER.info("Registrando chave Pix no Banco Central do Brasil (BCB): $it") } val bcbResponse = bcbClient.create(bcbRequest) if (bcbResponse.status != HttpStatus.CREATED) throw IllegalStateException("Erro ao registrar chave Pix no Banco Central do Brasil (BCB)") chave.atualiza(bcbResponse.body()!!.key) return chave } }
0
Kotlin
0
0
5b6de3b5cd71fab021762c2a20c1bba672456197
1,837
orange-talents-01-template-pix-keymanager-grpc
Apache License 2.0
shared/src/commonMain/kotlin/ScreenBComponent.kt
UmairSiddique1
731,106,413
false
{"Kotlin": 36148, "Swift": 592, "Shell": 228}
import com.arkivanov.decompose.ComponentContext class ScreenBComponent(val text:String, componentContext: ComponentContext):ComponentContext by componentContext{ }
0
Kotlin
0
0
59ffca81cd6cbb68ed0987a78a2721c43abc35b4
164
CMM-Second
Apache License 2.0
app/src/main/java/com/flexcode/authenticationapp/data/remote/response/AuthResponse.kt
Felix-Kariuki
507,851,744
false
{"Kotlin": 44611}
package com.flexcode.authenticationapp.data.remote.response import com.google.gson.annotations.SerializedName data class AuthResponse( @SerializedName("token") val token : String )
0
Kotlin
4
21
a64e76f4e9c9da81d904b5b9eb4c62672d405dec
191
Authentication
MIT License
app/src/main/kotlin/com.jdamcd.sudoku/browse/PuzzleListFragment.kt
jasmineleon
290,962,146
true
{"Kotlin": 214884}
package com.jdamcd.sudoku.browse import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.recyclerview.widget.SimpleItemAnimator import com.jdamcd.sudoku.R import com.jdamcd.sudoku.base.BaseFragment import com.jdamcd.sudoku.repository.Level import com.jdamcd.sudoku.repository.Puzzle import com.jdamcd.sudoku.view.OffsetDecoration import javax.inject.Inject import kotlinx.android.synthetic.main.fragment_recycler_puzzles.* class PuzzleListFragment : BaseFragment(), PuzzleListPresenter.View { @Inject internal lateinit var presenter: PuzzleListPresenter @Inject internal lateinit var adapter: PuzzleAdapter override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View { return inflater.inflate(R.layout.fragment_recycler_puzzles, container, false) } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { recycler_view.addItemDecoration(OffsetDecoration(requireContext(), R.dimen.half_gutter)) (recycler_view.itemAnimator as SimpleItemAnimator).supportsChangeAnimations = false presenter.start(this) } override fun showPuzzles(puzzles: List<Puzzle>) { adapter.submitList(puzzles) if (recycler_view.adapter == null) { recycler_view.adapter = adapter } empty.visibility = if (puzzles.isEmpty()) View.VISIBLE else View.GONE loading.visibility = View.GONE } override fun onPuzzleClicked() = adapter.itemClicked() override fun getLevel() = requireArguments()[PARAM_KEY_LEVEL] as Level override fun onDestroyView() { super.onDestroyView() presenter.stop() } companion object { private const val PARAM_KEY_LEVEL = "level" fun create(level: Level): PuzzleListFragment { val f = PuzzleListFragment() val args = Bundle() args.putSerializable(PARAM_KEY_LEVEL, level) f.arguments = args return f } } }
0
null
0
0
463f9abaa5a996b1d971ab4ec72912c6d7b55a36
2,080
material-sudoku
Apache License 2.0
lib_image_picker/src/main/java/crocodile8/image_picker_plus/provider/GalleryProvider.kt
Andrew0000
631,278,281
false
{"Kotlin": 36719}
package crocodile8.image_picker_plus.provider import android.app.Activity import android.content.Intent import android.net.Uri import android.os.Bundle import androidx.activity.ComponentActivity import androidx.core.net.toUri import crocodile8.image_picker_plus.PickRequest import crocodile8.image_picker_plus.TypeFilter import crocodile8.image_picker_plus.utils.Logger import crocodile8.image_picker_plus.utils.FileUtils.copyUriContentToFile import crocodile8.image_picker_plus.utils.FileUtils.createEmptyLocalUniqueFile import crocodile8.image_picker_plus.utils.getExtOrJpeg // https://developer.android.com/training/data-storage/shared/documents-files#bitmap class GalleryProvider( activity: ComponentActivity, request: PickRequest, onResult: (Uri?, Throwable?) -> Unit, ) : Provider(activity, request, onResult) { override fun onActivityResult(resultCode: Int, intent: Intent?) { val uri = intent?.data Logger.i("GalleryProvider uri: $uri") if (resultCode == Activity.RESULT_OK && uri != null) { // Copy content of public Uri to a local file val tmpFile = createEmptyLocalUniqueFile(context, uri.getExtOrJpeg(context)) Logger.i("GalleryProvider tmpFile: $tmpFile") if (tmpFile == null) { Logger.e("GalleryProvider null tmpFile") onError() } else { try { copyUriContentToFile(context, uri, tmpFile) onSuccess(tmpFile.toUri()) } catch (e: Exception) { Logger.e("", e) onError() } } } else { Logger.e("GalleryProvider result error: ${resultCode}, uri: $uri") onError() } } override fun onCreate(savedInstanceState: Bundle?) { if (savedInstanceState != null) { // Don't react on activity recreation return } launch() } private fun launch() { val intent = createPickIntent(request.filter) if (intent.resolveActivity(packageManager) != null) { Logger.i("GalleryProvider intent resolveActivity OK") launcher.launch(intent) } else { Logger.e("GalleryProvider intent resolveActivity error") onError() } } private fun createPickIntent(filter: TypeFilter): Intent { val intent = Intent(Intent.ACTION_OPEN_DOCUMENT).apply { type = filter.mimeType if (filter.subTypes.isNotEmpty()) { putExtra(Intent.EXTRA_MIME_TYPES, filter.subTypes.toTypedArray()) } } intent.addCategory(Intent.CATEGORY_OPENABLE) intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION) return intent } }
2
Kotlin
0
5
bb57c7c43f582f9cae52775f39369b4f03924647
2,830
ImagePickerPlus
Apache License 2.0
src/test/kotlin/uk/gov/justice/digital/hmpps/pecs/jpc/controller/JourneyPriceCatalogueControllerTest.kt
ministryofjustice
292,861,912
false
{"Kotlin": 875203, "HTML": 131707, "Shell": 20530, "CSS": 19037, "Mustache": 4593, "Dockerfile": 1328}
package uk.gov.justice.digital.hmpps.pecs.jpc.controller import org.junit.jupiter.api.Test import org.junit.jupiter.api.extension.ExtendWith import org.mockito.kotlin.whenever import org.springframework.beans.factory.annotation.Autowired import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc import org.springframework.boot.test.context.SpringBootTest import org.springframework.boot.test.mock.mockito.MockBean import org.springframework.mock.web.MockHttpSession import org.springframework.security.test.context.support.WithMockUser import org.springframework.test.context.ActiveProfiles import org.springframework.test.context.ContextConfiguration import org.springframework.test.web.servlet.get import org.springframework.test.web.servlet.setup.MockMvcBuilders import org.springframework.web.context.WebApplicationContext import uk.gov.justice.digital.hmpps.pecs.jpc.TestConfig import uk.gov.justice.digital.hmpps.pecs.jpc.config.TimeSource import uk.gov.justice.digital.hmpps.pecs.jpc.domain.price.Supplier import uk.gov.justice.digital.hmpps.pecs.jpc.service.FakeAuthentication import java.time.LocalDate import java.time.LocalDateTime @SpringBootTest @AutoConfigureMockMvc @ActiveProfiles("test") @ContextConfiguration(classes = [TestConfig::class]) @ExtendWith(FakeAuthentication::class) class JourneyPriceCatalogueControllerTest(@Autowired private val wac: WebApplicationContext) { private val mockMvc = MockMvcBuilders.webAppContextSetup(wac).build() private val mockSession = MockHttpSession(wac.servletContext) @MockBean private lateinit var timeSource: TimeSource @Test @WithMockUser(roles = ["PECS_JPC"]) fun `can generate spreadsheet with correct name for Serco`() { whenever(timeSource.dateTime()).thenReturn(LocalDateTime.of(2020, 10, 13, 15, 25)) whenever(timeSource.date()).thenReturn(LocalDate.of(2020, 10, 13)) mockSession.addSupplierAndDateAttributes(Supplier.SERCO, LocalDate.of(2020, 10, 1)) mockMvc.get("/generate-prices-spreadsheet") { session = mockSession } .andExpect { status { isOk() } content { contentType("application/vnd.ms-excel") } header { string( "Content-Disposition", "attachment;filename=Journey_Variable_Payment_Output_SERCO_2020-10-13_15_25.xlsx", ) } } } @Test @WithMockUser(roles = ["PECS_JPC"]) fun `can generate spreadsheet with correct name for Geoamey`() { whenever(timeSource.dateTime()).thenReturn(LocalDateTime.of(2020, 10, 13, 15, 25)) whenever(timeSource.date()).thenReturn(LocalDate.of(2020, 10, 13)) mockSession.addSupplierAndDateAttributes(Supplier.GEOAMEY, LocalDate.of(2020, 10, 1)) mockMvc.get("/generate-prices-spreadsheet") { session = mockSession } .andExpect { status { isOk() } content { contentType("application/vnd.ms-excel") } header { string( "Content-Disposition", "attachment;filename=Journey_Variable_Payment_Output_GEOAMEY_2020-10-13_15_25.xlsx", ) } } } @Test @WithMockUser(roles = ["PECS_JPC"]) fun `no content when supplier not present on the session`() { mockSession.addSupplierAndDateAttributes(null, LocalDate.of(2020, 10, 1)) mockMvc.get("/generate-prices-spreadsheet") { session = mockSession } .andExpect { status { isNoContent() } } } @Test @WithMockUser(roles = ["PECS_JPC"]) fun `no content when date not present on the session`() { mockSession.addSupplierAndDateAttributes(Supplier.GEOAMEY, null) mockMvc.get("/generate-prices-spreadsheet") { session = mockSession } .andExpect { status { isNoContent() } } } private fun MockHttpSession.addSupplierAndDateAttributes(supplier: Supplier?, date: LocalDate?) { this.setAttribute("supplier", supplier) this.setAttribute("date", date) } }
1
Kotlin
2
3
f53ee728d5bea3453a5cde02d8751a13069cc335
3,970
calculate-journey-variable-payments
MIT License
app/src/main/java/com/primalabs/primavreme/MainActivity.kt
zprima
354,273,921
false
null
package com.primalabs.primavreme import android.os.Bundle import android.util.Log import androidx.activity.compose.setContent import androidx.appcompat.app.AppCompatActivity import androidx.compose.animation.* import androidx.compose.foundation.* import androidx.compose.foundation.layout.* import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.material.* import androidx.compose.material.icons.Icons import androidx.compose.material.icons.filled.* import androidx.compose.runtime.* import androidx.compose.runtime.livedata.observeAsState import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.draw.clip import androidx.compose.ui.graphics.Brush import androidx.compose.ui.graphics.Color import androidx.compose.ui.graphics.vector.ImageVector import androidx.compose.ui.layout.ContentScale import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.text.SpanStyle import androidx.compose.ui.text.buildAnnotatedString import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.text.style.BaselineShift import androidx.compose.ui.text.withStyle import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.sp import androidx.lifecycle.* import androidx.lifecycle.viewmodel.compose.viewModel import coil.ImageLoader import coil.decode.SvgDecoder import com.google.accompanist.coil.CoilImage import com.google.accompanist.coil.LocalImageLoader import com.primalabs.primavreme.ui.theme.PrimaVremeTheme import com.squareup.moshi.Json import com.squareup.moshi.Moshi import retrofit2.Retrofit import retrofit2.converter.moshi.MoshiConverterFactory import com.squareup.moshi.kotlin.reflect.KotlinJsonAdapterFactory import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.launch import kotlinx.coroutines.withContext import retrofit2.Response import retrofit2.http.GET import retrofit2.http.Headers import retrofit2.http.Query import java.time.LocalDate import java.time.LocalDateTime import java.time.format.DateTimeFormatter import java.util.* const val LOG_TAG = "vremetag" const val ARSO_WEATHER_IMAGE_URL = "https://vreme.arso.gov.si/app/common/images/svg/weather/" // Helpful logging to see http body content //internal val baseOkHttpClient: OkHttpClient = OkHttpClient // .Builder() // .addInterceptor(HttpLoggingInterceptor().apply { level = HttpLoggingInterceptor.Level.BODY }) // .build() val moshi = Moshi.Builder() .addLast(KotlinJsonAdapterFactory()) .build() var retrofit = Retrofit.Builder() .baseUrl("https://vreme.arso.gov.si/api/1.0/") .addConverterFactory(MoshiConverterFactory.create(moshi)) .build() interface ArsoService { @Headers("content-type: application/json") @GET("locations/") suspend fun findLocation(@Query("loc") loc: String): Response<ArsoLocationsResult> @Headers("content-type: application/json") @GET("location/") suspend fun getLocationWeather( @Query("lang") lang: String = "sl", @Query("location") location: String ): Response<ArsoLocationResult> } var arsoService = retrofit.create(ArsoService::class.java) data class ArsoLocationsResult( @Json(name = "features") val features: List<ArsoLocationFeature> ) data class ArsoLocationFeature( @Json(name = "geometry") val geometry: ArsoLocationGeometry, @Json(name = "properties") val properties: ArsoLocationFeatureProperty ) data class ArsoLocationGeometry( @Json(name = "coordinates") val coordinates: List<Float> ) data class ArsoLocationFeatureProperty( @Json(name = "country") val country: String, @Json(name = "title") val title: String, @Json(name = "id") val id: String, @Json(name = "days") val days: List<ArsoLocationFeaturePropertyDay> ) data class ArsoLocationFeaturePropertyDay( @Json(name = "date") val date: String, @Json(name = "timeline") val timeline: List<ArsoLocationFeaturePropertyDayTimeline> ) data class ArsoLocationFeaturePropertyDayTimeline( @Json(name = "t") val t: String?, @Json(name = "tnsyn") val tMin: String?, @Json(name = "txsyn") val tMax: String?, @Json(name = "clouds_icon_wwsyn_icon") val iconName: String, @Json(name = "clouds_shortText") val description: String, @Json(name = "ff_shortText") val windDescription: String, @Json(name = "ff_val") val windSpeed: String, @Json(name = "rh_shortText") val humidityDescription: String, @Json(name = "rh") val humidityPercent: String, @Json(name = "valid") val validForDateTime: String ) data class ArsoLocationResult( @Json(name="observation") val observation: ArsoForecast, @Json(name="forecast1h") val forecast1h: ArsoForecast, @Json(name="forecast24h") val forecast24h: ArsoForecast ) data class ArsoForecast( @Json(name="features") val features: List<ArsoLocationFeature> ) const val STATE_LOCATION_SELECTED_NAME = "location.state.selected.name" class ArsoWeatherRepository(){ suspend fun callTriggerSearch(searchInput: String): Response<ArsoLocationsResult>{ return withContext(Dispatchers.IO){ arsoService.findLocation(searchInput) } } suspend fun callLocationForecast(location: String): Response<ArsoLocationResult>{ return withContext(Dispatchers.IO){ arsoService.getLocationWeather(location = location) } } } class WeatherViewModel(private val savedStateHandle: SavedStateHandle): ViewModel(){ val arsoLocations = MutableLiveData<List<ArsoLocationFeature>>(emptyList()) val selectedLocationWeather = MutableLiveData<ArsoLocationResult>(null) val repository = ArsoWeatherRepository() suspend fun triggerSearch(searchInput: String){ if(searchInput.length >= 2) { viewModelScope.launch() { val result = repository.callTriggerSearch(searchInput) arsoLocations.value = result.body()?.features } } else { arsoLocations.value = listOf() } } suspend fun onSearchLocationClicked(location: String){ savedStateHandle.set(STATE_LOCATION_SELECTED_NAME, location) viewModelScope.launch(){ val result = repository.callLocationForecast(location) selectedLocationWeather.value = result.body() arsoLocations.value = listOf() } } private fun triggerLocationWeatherFetch(location: String){ viewModelScope.launch { onSearchLocationClicked(location = location) } } init { savedStateHandle.get<String>(STATE_LOCATION_SELECTED_NAME)?.let { Log.d(LOG_TAG, it) triggerLocationWeatherFetch(it) } triggerLocationWeatherFetch("Celje") } } @ExperimentalAnimationApi class MainActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContent { PrimaVremeTheme(false) { // A surface container using the 'background' color from the theme Surface(color = MaterialTheme.colors.background) { App() } } } } } @ExperimentalAnimationApi @Composable fun App(){ val vm: WeatherViewModel = viewModel() val extendSearch = remember { mutableStateOf(false) } val imageLoader = ImageLoader.Builder(LocalContext.current) .componentRegistry { add(SvgDecoder(LocalContext.current)) } .build() CompositionLocalProvider(LocalImageLoader provides imageLoader) { Scaffold( modifier = Modifier, content = { WeatherAppContent(vm) }, topBar = { TopAppBar( title = { AnimatedVisibility( visible = extendSearch.value, enter = slideInHorizontally(initialOffsetX = { it * 2 }), exit = slideOutHorizontally(targetOffsetX = { it * 2 }) ) { Text("Search", modifier = Modifier.fillMaxWidth()) } }, elevation = 0.dp, navigationIcon = { IconButton(onClick = { /*TODO*/ }) { Icon(imageVector = Icons.Default.Menu, contentDescription = null) } }, actions = { IconButton(onClick = { extendSearch.value = !extendSearch.value }) { Icon(imageVector = Icons.Default.Search, contentDescription = null) } } ) } ) } } @Composable private fun WeatherAppContent(vm: WeatherViewModel) { val locationForecastData = vm.selectedLocationWeather.observeAsState(null) if(locationForecastData.value == null){ Text("Loading...") } else { val forecastValue = locationForecastData.value!! Column( Modifier .padding(16.dp) .verticalScroll(rememberScrollState()) ) { Column { CurrentForecast(forecastData = forecastValue.observation) Spacer(Modifier.height(16.dp)) Forecast1h(forecast1hData = forecastValue.forecast1h) Spacer(Modifier.height(24.dp)) Forecast24h(forecast24hData = forecastValue.forecast24h) } } } } @Composable private fun CurrentForecast(forecastData: ArsoForecast){ val properties = forecastData.features.first().properties val todaysForecast = properties.days.first() val todaysForecastDate = LocalDate.parse(todaysForecast.date, DateTimeFormatter.ISO_DATE) val todaysTimeline = todaysForecast.timeline.first() val forecastImgUrl = "${ARSO_WEATHER_IMAGE_URL}${todaysTimeline.iconName}.svg" CurrentForecastMain( locationName = properties.title, forecastDate = todaysForecastDate, forecastImgUrl = forecastImgUrl, temparature = todaysTimeline.t ?: "", description = todaysTimeline.description ) CurrentForecastDetails( windText = todaysTimeline.windDescription, windValue = "${todaysTimeline.windSpeed} km/h", humidityText = todaysTimeline.humidityDescription, humidityValue = "${todaysTimeline.humidityPercent} %" ) } @Composable private fun CurrentForecastMain(locationName: String, forecastDate: LocalDate, forecastImgUrl: String, temparature: String, description: String) { val formatter = DateTimeFormatter.ofPattern("eeee, d. L y") val formattedForecastDate = forecastDate.format(formatter) Text( text = locationName.toUpperCase(Locale.ROOT), style = MaterialTheme.typography.h2, color = MaterialTheme.colors.onPrimary, modifier = Modifier.paddingFromBaseline(bottom = 16.dp) ) Text( text = formattedForecastDate.capitalize(), style = MaterialTheme.typography.subtitle2, color = MaterialTheme.colors.onSecondary ) Spacer(Modifier.height(16.dp)) Row{ CoilImage( data = forecastImgUrl, contentDescription = null, error = { Text(it.throwable.message!!) }, modifier = Modifier .height(150.dp) .fillMaxWidth(.5f), contentScale = ContentScale.Crop, shouldRefetchOnSizeChange = { _, _ -> false } ) Column { Text( buildAnnotatedString { append(temparature) withStyle( SpanStyle( baselineShift = BaselineShift.Superscript, fontSize = 20.sp, fontWeight = FontWeight.Normal ) ) { append("°C") } }, style = MaterialTheme.typography.h1 ) Text( text = description, color = MaterialTheme.colors.onPrimary ) } } } @Composable fun CurrentForecastDetails(windText: String, windValue: String, humidityText: String, humidityValue: String){ Row( modifier = Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.SpaceEvenly ){ CurrentForecastDetailItem( detailText = windText, detailValue = windValue, icon = Icons.Default.Air, iconBackgroundColor = Color(0xFFe4f4e5), iconColor = Color(0xFF98d2a5)) CurrentForecastDetailItem( detailText = humidityText, detailValue = humidityValue,Icons.Default.Bloodtype, iconBackgroundColor = Color(0xFFe0eff6), iconColor = Color(0xFF7dc1e5) ) } } @Composable private fun CurrentForecastDetailItem(detailText: String, detailValue: String, icon: ImageVector, iconBackgroundColor: Color, iconColor: Color) { Row(modifier = Modifier.padding(8.dp)){ Box(modifier = Modifier .clip(RoundedCornerShape(10.dp)) .size(40.dp) .background(color = iconBackgroundColor), contentAlignment = Alignment.Center ) { Icon(icon, contentDescription = null, tint = iconColor) } Spacer(modifier = Modifier.width(8.dp)) Column() { Text(detailText, fontSize = 14.sp) Text(detailValue, fontSize = 12.sp) } } } @Composable private fun Forecast1h(forecast1hData: ArsoForecast){ val features = forecast1hData.features val properties = features.first().properties val todaysForecast = properties.days.first() Text("Danes", modifier = Modifier.padding(bottom = 8.dp)) Row(modifier = Modifier.horizontalScroll(rememberScrollState()) ){ todaysForecast.timeline.forEach { Forecast1hCard(it) } } } @Composable private fun Forecast1hCard(forecastData: ArsoLocationFeaturePropertyDayTimeline) { val forecastDate = LocalDateTime.parse(forecastData.validForDateTime, DateTimeFormatter.ISO_DATE_TIME) val forecastImgUrl = "${ARSO_WEATHER_IMAGE_URL}${forecastData.iconName}.svg" Forecast1hCardItem( forecastDate = forecastDate, forecastImgUrl = forecastImgUrl, temparature = forecastData.t ?: "", windSpeed = "${forecastData.windSpeed} km/h", humidityPercent = "${forecastData.humidityPercent} %", active = forecastDate.hour == LocalDateTime.now().hour ) } @Composable private fun Forecast1hCardItem(forecastDate: LocalDateTime, forecastImgUrl: String, temparature: String, windSpeed: String, humidityPercent: String, active: Boolean = false){ val roundShape = RoundedCornerShape(10) val hourFormatter = DateTimeFormatter.ofPattern("HH:mm") var modifier = Modifier .clip(roundShape) .border(BorderStroke(1.dp, Color(0xFFe8e9ec)), roundShape) if(active){ modifier = modifier.background( brush = Brush.verticalGradient( colors = listOf( Color(0xffa5c6fd), Color(0xff5a95fb) ) ) ) } val textColor = if(active) MaterialTheme.colors.primary else MaterialTheme.colors.onSecondary Column( modifier = modifier.padding(8.dp), horizontalAlignment = Alignment.CenterHorizontally ) { Text( text = forecastDate.format(hourFormatter), color = textColor, fontSize = 14.sp, fontWeight = FontWeight.Normal ) CoilImage( data = forecastImgUrl, contentDescription = null, error = { Text(it.throwable.message!!) }, modifier = Modifier.size(50.dp) ) Text(buildAnnotatedString { append(temparature) withStyle(SpanStyle(baselineShift = BaselineShift.Superscript, fontSize = 10.sp, fontWeight = FontWeight.Normal)){ append("c") } }, fontWeight = FontWeight.Bold, color = textColor) Text(windSpeed, fontSize = 12.sp, color = textColor) Text(humidityPercent, fontSize = 12.sp, color = textColor) } Spacer(modifier = Modifier.width(16.dp)) } @Composable private fun Forecast24h(forecast24hData: ArsoForecast){ val features = forecast24hData.features val properties = features.first().properties Text("Naslednjih 10 dni", modifier = Modifier.padding(bottom = 8.dp)) Column(){ properties.days.drop(1).forEach { Forecast24Card(it) } } } @Composable private fun Forecast24Card(forecastDayData: ArsoLocationFeaturePropertyDay) { val dayNameFormatter = DateTimeFormatter.ofPattern("eeee") val dateFormatter = DateTimeFormatter.ofPattern("d.MM.yyyy") val date = LocalDate.parse(forecastDayData.date) val timeline = forecastDayData.timeline.first() val maxTemparature = timeline.tMax ?: "" val minTemparature = timeline.tMin ?: "" val description = timeline.description val forecastImgUrl = "${ARSO_WEATHER_IMAGE_URL}${timeline.iconName}.svg" Row( modifier = Modifier .fillMaxWidth() .padding(vertical = 16.dp), horizontalArrangement = Arrangement.SpaceEvenly ) { Column(Modifier.width(100.dp)) { Text( text = date.format(dayNameFormatter).toUpperCase(Locale.ROOT), fontSize = 14.sp ) Text( text = date.format(dateFormatter), fontSize = 12.sp, color = MaterialTheme.colors.onSecondary ) } Text( text = buildAnnotatedString { withStyle(SpanStyle(fontSize = 20.sp)){ append(maxTemparature) } append(" / ") append(minTemparature) withStyle(SpanStyle(baselineShift = BaselineShift.Superscript, fontSize = 12.sp)){ append(" c") } }, fontSize = 16.sp, modifier = Modifier.width(70.dp) ) Text( text = description, fontSize = 12.sp, color = MaterialTheme.colors.onSecondary, modifier = Modifier.width(100.dp) ) CoilImage( data = forecastImgUrl, contentDescription = null, error = { Text(it.throwable.message!!) }, modifier = Modifier.size(30.dp) ) } } // //@Composable //fun SearchPart(vm: WeatherViewModel) { // val scope = rememberCoroutineScope() // var searchInput by remember { mutableStateOf("") } // val locations by vm.arsoLocations.observeAsState() // // fun triggerSearch() { // scope.launch() { // vm.triggerSearch(searchInput) // } // } // // fun triggerLocationSearch(locationName: String){ // scope.launch { // vm.onSearchLocationClicked(locationName) // } // } // // Row(Modifier.fillMaxWidth()) { // OutlinedTextField( // value = searchInput, // onValueChange = { searchInput = it; triggerSearch(); }, // modifier = Modifier.fillMaxWidth(), // leadingIcon = { Icon(imageVector = Icons.Default.Search, contentDescription = null) }, // singleLine = true // ) // // DropdownMenu( // expanded = locations?.size ?: 0 > 0, // onDismissRequest = { }, // properties = PopupProperties(focusable = false), // modifier = Modifier // .fillMaxWidth() // .height(240.dp) // ) { // locations?.forEach { // val locationTemp: String = it.properties.days.first().timeline.first().t!! // val locationName: String = it.properties.title // // DropdownMenuItem(onClick = { triggerLocationSearch(locationName) }) { // Row() { // Text(locationTemp, modifier = Modifier.width(20.dp)) // Spacer(Modifier.width(16.dp)) // Text(locationName) // } // } // } // } // } //} // //@Composable //fun DetailsPart(vm: WeatherViewModel){ // val locationForecast by vm.selectedLocationWeather.observeAsState() // // if(locationForecast != null){ // LocationWeatherDetailsPart(locationForecast!!) // } // // LocationWeatherDetailsPart(null) // //} // //@Composable //fun LocationWeatherDetailsPart(locationForecast: ArsoLocationResult?){ //// val locationName: String = locationForecast.observation.features.first().properties.title //// val currentTemp: String = locationForecast.observation.features.first().properties.days.first().timeline.first().t!! // // val locationName = "CELJE" // val currentTemp = "12" // val imgUrl = "${ARSO_WEATHER_IMAGE_URL}prevCloudy_day.svg" // // Column(modifier = Modifier){ // Text(locationName, fontSize = 17.sp, fontWeight = FontWeight.Bold, color = Color(0xFF384555)) // Text("Sobota, 10. April, 2021", style = MaterialTheme.typography.subtitle1) // // Spacer(Modifier.height(32.dp)) // // Row( // horizontalArrangement = Arrangement.Center, // verticalAlignment = Alignment.CenterVertically, // modifier = Modifier // .fillMaxWidth() // .height(150.dp) // ){ // // CoilImage( // data = imgUrl, // contentDescription = null, // error = { // Text(it.throwable.message!!) // }, // modifier = Modifier // .fillMaxHeight() // .fillMaxWidth(.5f) // .offset(x = 10.dp), // alignment = Alignment.CenterEnd // ) // // Column( // modifier = Modifier // .fillMaxHeight() // .fillMaxWidth(), // verticalArrangement = Arrangement.Top // ){ // Spacer(Modifier.height(16.dp)) // // Text(text = buildAnnotatedString { // append(currentTemp) // // withStyle(style = SpanStyle( // fontSize = 12.sp, // fontWeight = FontWeight.Light, // baselineShift = BaselineShift.Superscript, // color = Color(0xFFadb4bc) // )){ // append("C") // } // }, style = MaterialTheme.typography.h1) // Text("Delno Oblačno") // } // } // // Spacer(Modifier.height(8.dp)) // // Row( // horizontalArrangement = Arrangement.SpaceEvenly, // modifier = Modifier.fillMaxWidth() // ){ // Column( // horizontalAlignment = Alignment.CenterHorizontally, // modifier = Modifier.width(100.dp) // ){ // Box(modifier = Modifier // .size(50.dp) // .background(color = Color(0xFFe4f4e7)), // contentAlignment = Alignment.Center // ){ // Icon(imageVector = Icons.Default.PlayArrow, contentDescription = null, tint = Color(0xFF48725f)) // } // Text("9km/h") // } // // Column( // horizontalAlignment = Alignment.CenterHorizontally, // modifier = Modifier.width(100.dp) // ){ // Box(modifier = Modifier // .size(50.dp) // .background(color = Color(0xFFe1f0f7)),contentAlignment = Alignment.Center){ // Icon(imageVector = Icons.Default.PlayArrow, contentDescription = null, tint = Color(0xFF5cabe9)) // } // Text("43%") // } // // Column( // horizontalAlignment = Alignment.CenterHorizontally, // modifier = Modifier.width(100.dp) // ){ // Box(modifier = Modifier // .size(50.dp) // .background(color = Color(0xFFf2e1e7)), contentAlignment = Alignment.Center){ // Icon(imageVector = Icons.Default.PlayArrow, contentDescription = null, tint = Color(0xFFd16083)) // } // Text("5%") // } // } // // Spacer(Modifier.height(32.dp)) // // Text("Urni pregled") // // Spacer(Modifier.height(8.dp)) // // Row(modifier = // Modifier.horizontalScroll(rememberScrollState()) // ){ // Forecast12Card(imgUrl) // Forecast12Card(imgUrl) // Forecast12Card(imgUrl) // Forecast12Card(imgUrl) // Forecast12Card(imgUrl) // Forecast12Card(imgUrl) // Forecast12Card(imgUrl) // Forecast12Card(imgUrl) // Forecast12Card(imgUrl) // } // // Spacer(Modifier.height(16.dp)) // // Text("<NAME>") // // Spacer(Modifier.height(8.dp)) // // Column(){ // Forecast24Card() // Forecast24Card() // Forecast24Card() // Forecast24Card() // Forecast24Card() // Forecast24Card() // Forecast24Card() // Forecast24Card() // Forecast24Card() // Forecast24Card() // Forecast24Card() // Forecast24Card() // Forecast24Card() // Forecast24Card() // } // } //} // //@Composable //private fun Forecast12Card(imgUrl: String) { // Column( // modifier = Modifier // .clip(RoundedCornerShape(20f)) // .background( // brush = Brush.verticalGradient( // colors = listOf( // Color(0xffa6c7fc), // Color(0xff5c97fd) // ) // ) // ) // .padding(8.dp), // horizontalAlignment = Alignment.CenterHorizontally // ) { // Text("11:00", color = Color.White, fontSize = 14.sp) // // CoilImage( // data = imgUrl, // contentDescription = null, // error = { // Text(it.throwable.message!!) // }, // modifier = Modifier.size(50.dp) // ) // // Text("20c", fontWeight = FontWeight.Bold, color = Color.White) // } // // Spacer(modifier = Modifier.width(16.dp)) //}
0
Kotlin
0
0
fe5f67c1bace18107689afa4e27b6f9ab3c2defc
27,276
prima-vreme
Apache License 2.0
persistence/src/test/kotlin/com/github/jactor/persistence/guestbook/GuestBookEntryRepositoryTest.kt
jactor-rises
463,152,761
false
{"Kotlin": 274265, "HTML": 10548, "Gherkin": 4063, "CSS": 2049}
package com.github.jactor.persistence.guestbook import org.junit.jupiter.api.Test import com.github.jactor.persistence.AbstractSpringBootNoDirtyContextTest import com.github.jactor.persistence.address.AddressModel import com.github.jactor.persistence.person.PersonModel import com.github.jactor.persistence.user.UserModel import com.github.jactor.persistence.address.AddressBuilder import com.github.jactor.persistence.person.PersonBuilder import com.github.jactor.persistence.user.UserBuilder import com.github.jactor.persistence.user.UserEntity import assertk.assertAll import assertk.assertThat import assertk.assertions.hasSize import assertk.assertions.isEqualTo import assertk.assertions.isNotNull internal class GuestBookEntryRepositoryTest : AbstractSpringBootNoDirtyContextTest() { @Test fun `should save then read guest book entry entity`() { val addressDto = AddressBuilder.new( addressModel = AddressModel( zipCode = "1001", addressLine1 = "Test Boulevard 1", city = "Testington" ) ).addressModel val personDto = PersonBuilder.new(personModel = PersonModel(address = addressDto, surname = "AA")) .personModel val userDto = UserBuilder.new( userDto = UserModel( person = personDto, emailAddress = "<EMAIL>", username = "causual" ) ).userDto val savedUser = userRepository.save(UserEntity(userDto)) var guestBookData = GuestBookBuilder.new( GuestBookModel( entries = emptySet(), title = "home sweet home", user = savedUser.toModel() ) ) savedUser.setGuestBook(guestBookData.buildGuestBookEntity()) val savedGuestBook = guestBookRepository.save(savedUser.guestBook!!) guestBookData = guestBookData.withEntry( GuestBookEntryModel( guestBook = savedUser.guestBook?.toModel(), creatorName = "Harry", entry = "Draco Dormiens Nunquam Tittilandus" ) ) flush { guestBookEntryRepository.save(guestBookData.buildGuestBookEntryEntity()) } val entriesByGuestBook = guestBookEntryRepository.findByGuestBook(savedGuestBook) assertThat(entriesByGuestBook).hasSize(1) val entry = entriesByGuestBook.iterator().next() assertAll { assertThat(entry.creatorName).isEqualTo("Harry") assertThat(entry.entry).isEqualTo("Draco Dormiens Nunquam Tittilandus") } } @Test fun `should save then modify and read guest book entry entity`() { val addressDto = AddressBuilder.new( addressModel = AddressModel( zipCode = "1001", addressLine1 = "Test Boulevard 1", city = "Testington" ) ).addressModel val personDto = PersonBuilder.new(personModel = PersonModel(address = addressDto, surname = "AA")) .personModel val userDto = UserBuilder.new( userDto = UserModel( person = personDto, emailAddress = "<EMAIL>", username = "causual" ) ).userDto val savedUser = userRepository.save(UserEntity(userDto)) val guestBookData = GuestBookBuilder.new( GuestBookModel( entries = emptySet(), title = "home sweet home", user = savedUser.toModel() ) ) val savedGuestBook = guestBookRepository.save(guestBookData.buildGuestBookEntity()) flush { guestBookEntryRepository.save( guestBookData.withEntry( GuestBookEntryModel( guestBook = savedGuestBook.toModel(), creatorName = "Harry", entry = "Draco Dormiens Nunquam Tittilandus" ) ).buildGuestBookEntryEntity() ) } val entriesByGuestBook = guestBookEntryRepository.findByGuestBook(savedGuestBook) assertThat(entriesByGuestBook).hasSize(1) entriesByGuestBook.iterator().next().modify("Willie", "On the road again") flush { guestBookEntryRepository.save<GuestBookEntryEntity>(entriesByGuestBook.iterator().next()) } val modifiedEntriesByGuestBook = guestBookEntryRepository.findByGuestBook(savedGuestBook) assertThat(modifiedEntriesByGuestBook).hasSize(1) val entry = modifiedEntriesByGuestBook.iterator().next() assertAll { assertThat(entry.creatorName).isEqualTo("Willie") assertThat(entry.entry).isEqualTo("On the road again") } } @Test fun `should write two entries to two different guest books and then find one entry`() { val addressDto = AddressBuilder.new( addressModel = AddressModel( zipCode = "1001", addressLine1 = "Test Boulevard 1", city = "Testington" ) ).addressModel val personDto = PersonBuilder.new(personModel = PersonModel(address = addressDto, surname = "AA")) .personModel val userDto = UserBuilder.new( userDto = UserModel( person = personDto, emailAddress = "<EMAIL>", username = "causual" ) ).userDto val savedUser = userRepository.save(UserEntity(userDto)) val guestBookData = GuestBookBuilder.new( GuestBookModel( entries = emptySet(), title = "home sweet home", user = savedUser.toModel() ) ) val savedGuestBook = guestBookRepository.save(guestBookData.buildGuestBookEntity()) guestBookEntryRepository.save( guestBookData.withEntry( GuestBookEntryModel( guestBook = savedGuestBook.toModel(), creatorName = "somone", entry = "jadda" ) ).buildGuestBookEntryEntity() ) val anotherUserDto = UserBuilder.new( userDto = UserModel( person = personDto, emailAddress = "<EMAIL>", username = "hidden" ) ).userDto userRepository.save(UserEntity(anotherUserDto)) val anotherGuestBookData = GuestBookBuilder.new( guestBookModel = GuestBookModel( entries = emptySet(), title = "home sweet home", user = savedUser.toModel() ) ) val anotherSavedGuestBook = guestBookRepository.save(guestBookData.buildGuestBookEntity()) val anotherEntry = anotherGuestBookData.withEntry( guestBookEntryModel = GuestBookEntryModel( guestBook = anotherSavedGuestBook.toModel(), creatorName = "shrek", entry = "far far away" ) ).buildGuestBookEntryEntity() flush { guestBookEntryRepository.save(anotherEntry) } val lastEntry = guestBookRepository.findAll().toList() .flatMap { it.getEntries() } .firstOrNull { it.id == anotherEntry.id } assertAll { assertThat(lastEntry).isNotNull() assertThat(lastEntry?.creatorName).isEqualTo("shrek") assertThat(lastEntry?.entry).isEqualTo("far far away") } } }
0
Kotlin
0
0
56174905dd9c2eb6f4b9ea8c15869231e62549bb
7,525
jactor-modules
MIT License
dsl/src/main/kotlin/com/faendir/awscdkkt/generated/services/glue/ActionPropertyDsl.kt
F43nd1r
643,016,506
false
null
package com.faendir.awscdkkt.generated.services.glue import com.faendir.awscdkkt.AwsCdkDsl import javax.`annotation`.Generated import kotlin.Unit import software.amazon.awscdk.services.glue.CfnTrigger @Generated public fun buildActionProperty(initializer: @AwsCdkDsl CfnTrigger.ActionProperty.Builder.() -> Unit): CfnTrigger.ActionProperty = CfnTrigger.ActionProperty.Builder().apply(initializer).build()
1
Kotlin
0
0
451a1e42282de74a9a119a5716bd95b913662e7c
415
aws-cdk-kt
Apache License 2.0
android/app/src/main/kotlin/com/example/conversation_ranking_app/MainActivity.kt
ashwinpilgaonkar
423,558,260
false
{"Dart": 68403, "HTML": 4942, "Ruby": 1592, "Swift": 404, "Kotlin": 141, "Objective-C": 38}
package com.example.conversation_ranking_app import io.flutter.embedding.android.FlutterActivity class MainActivity: FlutterActivity() { }
0
Dart
0
0
53ec5d57fc6012cb1bef2596da4cea6398c78352
141
conversation-ranking-app
MIT License
parser/src/main/kotlin/com/theeasiestway/entities/RssEntity.kt
theeasiestway
198,079,594
false
null
package com.theeasiestway.entities open class RssEntity { var title: String? = null private set var link: String? = null private set var description: String? = null private set var pubDate: String? = null private set open fun setTitle(title: String?) : RssEntity { this.title = title return this } open fun setLink(link: String?) : RssEntity { this.link = link return this } open fun setDescription(description: String?) : RssEntity { this.description = description return this } open fun setPubDate(pubDate: String?) : RssEntity { this.pubDate = pubDate return this } override fun toString(): String { return String.format( "title: %s\n" + "link: %s\n" + "description: %s\n" + "pubDate: %s\n", title, link, description, pubDate) } }
0
Kotlin
0
0
ea00b772b92e111f5a5b6a221119b3d3b52954fa
1,030
rss-parser-kotlin
Apache License 2.0
src/main/java/com/example/workmanager/WorkerRenameFactory.kt
vshpyrka
755,524,995
false
{"Kotlin": 28365, "CMake": 920, "C++": 440}
package com.example.workmanager import android.content.Context import androidx.work.CoroutineWorker import androidx.work.ListenableWorker import androidx.work.WorkerFactory import androidx.work.WorkerParameters class WorkerRenameFactory : WorkerFactory() { override fun createWorker( appContext: Context, workerClassName: String, workerParameters: WorkerParameters ): ListenableWorker? { return when (workerClassName) { "OldWorker" -> TempNewWorker(appContext, workerParameters) else -> null } } } class TempNewWorker( appContext: Context, workerParameters: WorkerParameters ) : CoroutineWorker(appContext, workerParameters) { override suspend fun doWork(): Result { TODO("Not yet implemented") } }
0
Kotlin
0
0
22ce6b8484269ed8f9af967056bb550a794997bb
804
android-workmanager-example
Apache License 2.0
common-dependencies/src/main/kotlin/com/github/komamj/util/ProjectExt.kt
componentization-architechture
316,873,838
false
null
package com.github.komamj.util import org.gradle.api.Project import org.gradle.kotlin.dsl.dependencies fun Project.addCoroutines(configurationName: String = "implementation") { dependencies { add(configurationName, "org.jetbrains.kotlinx:kotlinx-coroutines-core:$COROUTINES") add(configurationName, "org.jetbrains.kotlinx:kotlinx-coroutines-android:$COROUTINES") } }
0
Kotlin
0
1
caee137fcb29792c62ad56761016706456369170
392
gradle-plugin
Apache License 2.0
src/main/kotlin/com/charleskorn/kaml/YamlConfiguration.kt
EdwarDDay
207,233,135
true
{"Kotlin": 256402, "Batchfile": 7582, "Shell": 3988}
/* Copyright 2018-2019 Charles Korn. 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.charleskorn.kaml /** * Configuration options for parsing YAML text and serialising objects to YAML. * * [encodeDefaults]: set to false to not write default property values to YAML (defaults to true) * [strictMode]: set to true to throw an exception when reading an object that has an unknown property, or false to ignore unknown properties (defaults to true) * [extensionDefinitionPrefix]: prefix used on root-level keys (where document root is an object) to define extensions that can later be merged (defaults to null, which disables extensions altogether). See https://batect.charleskorn.com/config/Overview.html#anchors-aliases-extensions-and-merging for example. */ data class YamlConfiguration constructor( internal val encodeDefaults: Boolean = true, internal val strictMode: Boolean = true, internal val extensionDefinitionPrefix: String? = null )
0
Kotlin
0
1
f5db1c77f3f8795d3ba0da4da6274eeabe65e393
1,485
kaml
Apache License 2.0
modules/core/src/main/java/de/deutschebahn/bahnhoflive/ui/accessibility/SpokenFeedbackAccessibilityLiveData.kt
dbbahnhoflive
267,806,942
false
{"Kotlin": 1166808, "Java": 919061, "HTML": 43851}
package de.deutschebahn.bahnhoflive.ui.accessibility import android.content.Context import android.view.accessibility.AccessibilityManager import androidx.lifecycle.LiveData import de.deutschebahn.bahnhoflive.util.accessibility.accessibilityManager import de.deutschebahn.bahnhoflive.util.accessibility.isSpokenFeedbackAccessibilityEnabled class SpokenFeedbackAccessibilityLiveData(context: Context) : LiveData<Boolean>() { private val applicationContext = context.applicationContext private val accessibilityStateChangeListener = AccessibilityManager.AccessibilityStateChangeListener { updateValue() } override fun onActive() { super.onActive() updateValue() applicationContext.accessibilityManager?.addAccessibilityStateChangeListener( accessibilityStateChangeListener ) } private fun updateValue() { value = applicationContext.isSpokenFeedbackAccessibilityEnabled } override fun onInactive() { applicationContext.accessibilityManager?.removeAccessibilityStateChangeListener( accessibilityStateChangeListener ) super.onInactive() } }
0
Kotlin
4
33
ae72e13b97a60ca942b63ff36f8b982ea0a7bb4f
1,193
dbbahnhoflive-android
Apache License 2.0
06-security-best-practices/starter/app/src/main/java/com/raywenderlich/android/organizedsimplenotes/MainActivityViewModel.kt
raywenderlich
273,212,706
false
null
package com.raywenderlich.android.organizedsimplenotes import android.app.Application import androidx.lifecycle.AndroidViewModel import androidx.lifecycle.LiveData import androidx.lifecycle.MutableLiveData private const val ENCRYPTED_PREFS = "ENCRYPTED_PREFS" private const val ENCRYPTED_PREFS_ENCRYPTION_KEY = "ENCRYPTED_PREFS_ENCRYPTION_KEY" class MainActivityViewModel(application: Application) : AndroidViewModel(application) { val snackbar: LiveData<String?> get() = _snackbar private val _snackbar = MutableLiveData<String?>() private val context by lazy { getApplication<Application>().applicationContext } fun onSnackbarShown() { _snackbar.value = null } fun getEncryptionKey(): String? { // TODO return null } fun setEncryptionKey(current: String?, new: String?) { if (current != getEncryptionKey()) { _snackbar.value = context.getString(R.string.error_current_encryption_key_incorrect) return } } }
10
Kotlin
1
2
2a5967a21b6f5fc5019b478f2819acc5d7c7ea22
973
paps-materials
Apache License 2.0
cache/src/main/kotlin/com/cinema/entract/cache/repository/CinemaCacheRepo.kt
StephaneBg
147,789,207
false
null
/* * Copyright 2019 <NAME> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.cinema.entract.cache.repository import com.cinema.entract.cache.mapper.DateRangeMapper import com.cinema.entract.cache.mapper.MovieMapper import com.cinema.entract.cache.mapper.WeekMapper import com.cinema.entract.cache.model.DateRangeCache import com.cinema.entract.cache.model.MovieCache import com.cinema.entract.cache.model.WeekCache import com.cinema.entract.data.model.DateRangeData import com.cinema.entract.data.model.MovieData import com.cinema.entract.data.model.WeekData import com.cinema.entract.data.repository.CacheRepo class CinemaCacheRepo( private val movieMapper: MovieMapper, private val weekMapper: WeekMapper, private val dateRangeMapper: DateRangeMapper ) : CacheRepo { private val moviesMap = mutableMapOf<String, List<MovieCache>>() private var schedule: List<WeekCache>? = null private var dateRange: DateRangeCache? = null private var promotionalUrl: String? = null override fun getMovies(date: String): List<MovieData>? = moviesMap[date]?.let { it.map { movie -> movieMapper.mapToData(movie) } } override fun cacheMovies(date: String, movies: List<MovieData>): List<MovieData> = movies.also { moviesMap[date] = movies.map { movieMapper.mapFromData(it) } } override fun getSchedule(): List<WeekData>? = schedule?.map { weekMapper.mapToData(it) } override fun cacheSchedule(weeks: List<WeekData>): List<WeekData> = weeks.also { schedule = weeks.map { weekMapper.mapFromData(it) } } override fun getDateRange(): DateRangeData? = dateRange?.let { dateRangeMapper.mapToData(it) } override fun cacheDateRange(range: DateRangeData?): DateRangeData? = range.also { range?.let { dateRange = dateRangeMapper.mapFromData(it) } } override fun getPromotionalUrl(): String? = promotionalUrl override fun cachePromotionalUrl(url: String): String = url.also { promotionalUrl = url } }
0
Kotlin
0
6
4453e5f02a0b2c6683cbbab4f8a8c551258930d6
2,525
entract-cinema-android
Apache License 2.0
AzurLaneLibrary/src/main/kotlin/DataVersion.kt
AdorableParker
519,499,809
false
null
package org.nymph import net.mamoe.mirai.console.command.* import org.nymph.AzurLaneLibrary.SQLiteLink object DataVersion : SimpleCommand( AzurLaneLibrary, "DataVersion", "数据版本", description = "数据库数据版本" ) { override val usage = "${CommandManager.commandPrefix}数据版本\t#$description" @Handler suspend fun MemberCommandSenderOnMessage.main() { if (group.botMuteRemaining > 0) return sendMessage(getVersion()) } @Handler suspend fun FriendCommandSenderOnMessage.main() { sendMessage(getVersion()) } @Handler suspend fun GroupTempCommandSenderOnMessage.main() { sendMessage(getVersion()) } @Handler suspend fun ConsoleCommandSender.main() { sendMessage(getVersion()) } private fun getVersion():String{ val result = SQLiteLink.executeDQLorDCL<LastModifiedTime>("SELECT * FROM LastModifiedTime") return when { result.error != null -> result.error!! result.data.isEmpty() -> "没有获取到 AzurLaneLibrary 的版本信息" else -> "${result.data[0].value}" } } }
0
Kotlin
0
0
34ca0d5d5ab303b4d30bbd9415e1d17f2849bab7
1,111
MiraiConsolePlugins
Apache License 2.0
ProjectAudioAssets/app/src/main/java/me/liuqingwen/android/projectaudioassets/MainActivity.kt
spkingr
99,180,956
false
null
package me.liuqingwen.android.projectaudioassets import android.media.AudioAttributes import android.media.AudioManager import android.media.SoundPool import android.os.Build import android.support.v7.app.AppCompatActivity import android.os.Bundle import android.support.v7.widget.GridLayoutManager import android.support.v7.widget.RecyclerView import org.jetbrains.anko.* import org.jetbrains.anko.recyclerview.v7.recyclerView class MainActivity : AppCompatActivity() { companion object { const val COLUMN_COUNT = 3 const val MAX_SOUND_POOL = 5 private const val ASSETS_FOLDER = "carton" } private val dataList by lazy(LazyThreadSafetyMode.NONE) { arrayListOf<Sound>() } private val adapter by lazy(LazyThreadSafetyMode.NONE) { CustomAdapter(this.dataList, this::clickAction) } private val layoutManager by lazy(LazyThreadSafetyMode.NONE) { GridLayoutManager(this, MainActivity.COLUMN_COUNT) } private lateinit var recyclerView:RecyclerView private val soundPool by lazy(LazyThreadSafetyMode.NONE) { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) SoundPool.Builder() .setMaxStreams(MainActivity.MAX_SOUND_POOL) .setAudioAttributes(AudioAttributes.Builder() .setContentType(AudioAttributes.CONTENT_TYPE_MUSIC) .setUsage(AudioAttributes.USAGE_GAME) .build()) .build() else SoundPool(MainActivity.MAX_SOUND_POOL, AudioManager.STREAM_MUSIC, 0) } override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) frameLayout { lparams(width = matchParent, height = matchParent) padding = dip(4) this@MainActivity.recyclerView = recyclerView{ adapter = this@MainActivity.adapter layoutManager = this@MainActivity.layoutManager } } this.init() } private fun init() { this.loadData() } private fun clickAction(sound: Sound) { sound.id?.let { this.soundPool.play(it, 1.0f, 1.0f, 1, 0, 1.0f) } } private fun loadData() { val list = this.assets.list(MainActivity.ASSETS_FOLDER) list.forEach { val path = "${MainActivity.ASSETS_FOLDER}/$it" val name = it.removeSuffix(".wav") val id = try { this.assets.openFd(path).run { this@MainActivity.soundPool.load(this, 1) } } catch (e:Exception) { null } this.dataList.add(Sound(id, name, path)) } //this.adapter.notifyDataSetChanged() } override fun onDestroy() { this.soundPool.release() super.onDestroy() } }
0
Kotlin
30
94
43756ad5107521e8156b0e5afa9e83fd0c20092a
2,914
50-android-kotlin-projects-in-100-days
MIT License
app/src/main/java/com/sebastijanzindl/galore/presentation/screens/generateCocktailLoading/GenerateCocktailLoadingScreen.kt
m1thrandir225
743,270,603
false
{"Kotlin": 400176}
package com.sebastijanzindl.galore.presentation.screens.generateCocktailLoading import androidx.compose.foundation.background import androidx.compose.foundation.border import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.height import androidx.compose.foundation.layout.padding import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.material3.MaterialTheme import androidx.compose.material3.Text import androidx.compose.runtime.Composable import androidx.compose.runtime.LaunchedEffect import androidx.compose.runtime.collectAsState import androidx.compose.runtime.getValue import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.draw.clip import androidx.compose.ui.text.style.TextAlign import androidx.compose.ui.unit.dp import com.airbnb.lottie.compose.LottieAnimation import com.airbnb.lottie.compose.LottieCompositionSpec import com.airbnb.lottie.compose.LottieConstants import com.airbnb.lottie.compose.rememberLottieComposition import com.sebastijanzindl.galore.R import com.sebastijanzindl.galore.presentation.viewmodels.GenerateCocktailViewModel @Composable fun GenerateLoadingScreen ( modifier: Modifier, sharedGenerateCocktailViewModel: GenerateCocktailViewModel, navigateToGenerateCocktailDetailsScreen: (cocktailId: String) -> Unit, ) { val composition by rememberLottieComposition(spec = LottieCompositionSpec.RawRes(R.raw.generate_cocktail_loading)) val isGenerating by sharedGenerateCocktailViewModel.isGenerating.collectAsState() val generatedCocktailId by sharedGenerateCocktailViewModel.generatedCocktailId.collectAsState() LaunchedEffect(Unit, generatedCocktailId) { sharedGenerateCocktailViewModel.generateCocktail() if(generatedCocktailId != null) { navigateToGenerateCocktailDetailsScreen(generatedCocktailId!!) } } if(isGenerating) { Column ( modifier = modifier .fillMaxSize() .padding(24.dp), horizontalAlignment = Alignment.CenterHorizontally, verticalArrangement = Arrangement.Center ) { Column( modifier = Modifier .clip(shape = RoundedCornerShape(12.dp)) .border( 2.dp, MaterialTheme.colorScheme.onPrimaryContainer, shape = RoundedCornerShape(12.dp) ) .background(MaterialTheme.colorScheme.primaryContainer) .padding(12.dp), verticalArrangement = Arrangement.spacedBy(24.dp) ) { Text( text = "Hold on, cocktail mastery in progress...", textAlign = TextAlign.Center, style = MaterialTheme.typography.headlineMedium, color = MaterialTheme.colorScheme.onSurface, ) LottieAnimation( modifier = Modifier .fillMaxWidth() .height(300.dp), composition = composition, iterations = LottieConstants.IterateForever ) } } } }
0
Kotlin
0
0
f578b800dbc6be3ab7421662176d8f4b7d652c03
3,487
galore-android
MIT License
nebulosa-indi-protocol/src/main/kotlin/nebulosa/indi/protocol/parser/INDIProtocolParser.kt
tiagohm
568,578,345
false
{"Kotlin": 2712371, "TypeScript": 513759, "HTML": 249483, "JavaScript": 120539, "SCSS": 11332, "Python": 2817, "Makefile": 445}
package nebulosa.indi.protocol.parser import nebulosa.indi.protocol.io.INDIInputStream interface INDIProtocolParser : INDIProtocolHandler, AutoCloseable { val input: INDIInputStream? val isClosed: Boolean }
29
Kotlin
2
4
723ede857d8fbf608562e93030719ae26dd0aad1
219
nebulosa
MIT License
health/connect/connect-client/src/main/java/androidx/health/connect/client/records/SwimmingStrokesRecord.kt
KOLANICH-libs
445,548,183
true
{"Kotlin": 68310818, "Java": 60327498, "C++": 9028407, "Python": 292398, "AIDL": 264519, "Shell": 174895, "HTML": 21175, "ANTLR": 19860, "CMake": 12136, "TypeScript": 7599, "C": 7083, "Swift": 3153, "JavaScript": 1343}
/* * Copyright (C) 2022 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package androidx.health.connect.client.records import androidx.annotation.IntDef import androidx.annotation.RestrictTo import androidx.health.connect.client.records.metadata.Metadata import java.time.Instant import java.time.ZoneOffset /** Captures the number of swimming strokes. Type of swimming stroke must be provided. */ public class SwimmingStrokesRecord( override val startTime: Instant, override val startZoneOffset: ZoneOffset?, override val endTime: Instant, override val endZoneOffset: ZoneOffset?, /** * Swimming style. Required field. Allowed values: [SwimmingType]. * * @see SwimmingType */ @property:SwimmingTypes public val type: Int, /** Count of strokes. Optional field. Valid range: 1-1000000. */ public val count: Long = 0, override val metadata: Metadata = Metadata.EMPTY, ) : IntervalRecord { init { requireNonNegative(value = count, name = "count") count.requireNotMore(other = 1000_000, name = "count") require(startTime.isBefore(endTime)) { "startTime must be before endTime." } } override fun equals(other: Any?): Boolean { if (this === other) return true if (other !is SwimmingStrokesRecord) return false if (count != other.count) return false if (type != other.type) return false if (startTime != other.startTime) return false if (startZoneOffset != other.startZoneOffset) return false if (endTime != other.endTime) return false if (endZoneOffset != other.endZoneOffset) return false if (metadata != other.metadata) return false return true } override fun hashCode(): Int { var result = 0 result = 31 * result + count.hashCode() result = 31 * result + type.hashCode() result = 31 * result + (startZoneOffset?.hashCode() ?: 0) result = 31 * result + endTime.hashCode() result = 31 * result + (endZoneOffset?.hashCode() ?: 0) result = 31 * result + metadata.hashCode() return result } companion object { const val SWIMMING_TYPE_OTHER = 0 const val SWIMMING_TYPE_FREESTYLE = 1 const val SWIMMING_TYPE_BACKSTROKE = 2 const val SWIMMING_TYPE_BREASTSTROKE = 3 const val SWIMMING_TYPE_BUTTERFLY = 4 const val SWIMMING_TYPE_MIXED = 5 /** Internal mappings useful for interoperability between integers and strings. */ @RestrictTo(RestrictTo.Scope.LIBRARY) @JvmField val SWIMMING_TYPE_STRING_TO_INT_MAP: Map<String, Int> = mapOf( SwimmingType.FREESTYLE to SWIMMING_TYPE_FREESTYLE, SwimmingType.BACKSTROKE to SWIMMING_TYPE_BACKSTROKE, SwimmingType.BREASTSTROKE to SWIMMING_TYPE_BREASTSTROKE, SwimmingType.BUTTERFLY to SWIMMING_TYPE_BUTTERFLY, SwimmingType.MIXED to SWIMMING_TYPE_MIXED, ) @RestrictTo(RestrictTo.Scope.LIBRARY) @JvmField val SWIMMING_TYPE_INT_TO_STRING_MAP = SWIMMING_TYPE_STRING_TO_INT_MAP.reverse() } /** List of Swimming styles. */ internal object SwimmingType { const val FREESTYLE = "freestyle" const val BACKSTROKE = "backstroke" const val BREASTSTROKE = "breaststroke" const val BUTTERFLY = "butterfly" const val MIXED = "mixed" const val OTHER = "other" } /** * Swimming styles. * @suppress */ @Retention(AnnotationRetention.SOURCE) @IntDef( value = [ SWIMMING_TYPE_FREESTYLE, SWIMMING_TYPE_BACKSTROKE, SWIMMING_TYPE_BREASTSTROKE, SWIMMING_TYPE_BUTTERFLY, SWIMMING_TYPE_MIXED, SWIMMING_TYPE_OTHER, ] ) @RestrictTo(RestrictTo.Scope.LIBRARY) annotation class SwimmingTypes }
0
Kotlin
0
0
c542b3a7cf2c46dfe3e071ca57956761e90aaff3
4,533
androidx
Apache License 2.0
r2dbc-mysql/src/main/java/JasyncDatabaseException.kt
mirromutth
176,066,212
true
{"Kotlin": 679473, "Java": 15957, "Shell": 3740}
package com.github.jasync.r2dbc.mysql import io.r2dbc.spi.R2dbcException class JasyncDatabaseException(reason: String, sqlState: String, errorCode: Int, cause: Throwable): R2dbcException(reason, sqlState, errorCode, cause)
0
Kotlin
0
2
76854b2df7ba39c4843d8c372343403721c4c8b7
315
jasync-sql
Apache License 2.0
app/src/main/kotlin/com/awesome/un/ui/post/PostViewModel.kt
stanfit
230,573,240
false
{"Kotlin": 18638}
package com.awesome.un.ui.post import androidx.lifecycle.AndroidViewModel import androidx.lifecycle.liveData import com.awesome.un.App import com.awesome.un.domain.usecase.PostUseCase import kotlinx.coroutines.delay import timber.log.Timber /** * Post List Screen's ViewModel. [AndroidViewModel] subclass. * * @property post UseCase of post */ class PostViewModel(app: App, private val post: PostUseCase) : AndroidViewModel(app) { /** * Posts */ val posts = liveData { Result .runCatching { // FIXME: delay for debug delay(3000) post.fetchPosts() } .onSuccess { emit(it) } .onFailure { Timber.e(it) } } }
0
Kotlin
0
0
fa67068d66e6d821a02aa50610a5c6a7bbfc8c43
794
android-clean-architecture
MIT License
domain/src/main/java/org/commcare/dalvik/domain/repositories/TranslationRepository.kt
dimagi
531,775,811
false
null
package org.commcare.dalvik.domain.repositories import org.commcare.dalvik.domain.model.TranslationModel interface TranslationRepository { suspend fun getTranslationData(langCode:String) :TranslationModel? }
0
Kotlin
1
0
e5e4c7f57f1eebfe12c8fcf4af2f160acf3f6d46
213
abdm-app
Apache License 2.0
src/main/kotlin/gameWindows.kt
lwd1815
105,521,563
false
null
import business.Blockable import business.Movable import enums.DIrections import javafx.scene.input.KeyCode import javafx.scene.input.KeyCodeCombination import javafx.scene.input.KeyEvent import model.Tank import org.itheima.kotlin.game.core.Window import org.lwd.game.Config import org.lwd.game.model.* import java.io.File class gameWindows:Window(title = "坦克大战",icon = "img/logo.jpg", width = Config.gameWidth ,height = Config.gameHeight ){ private val views:ArrayList<View> = arrayListOf<View>() //晚点创建爱你 private lateinit var tank :Tank override fun onCreate() { val file = File(javaClass.getResource("/map/1.map").path) //读取文件当中的行 val lines: List<String> = file.readLines() var lineNum=0 lines.forEach{line-> var columnNum=0 line.toCharArray().forEach { column-> when(column){ '砖'->views.add(Wall(columnNum*Config.block,lineNum*Config.block)) '铁'->views.add(Steel(columnNum*Config.block,lineNum*Config.block)) '草'->views.add(Grass(columnNum*Config.block,lineNum*Config.block)) '水'->views.add(Water(columnNum*Config.block,lineNum*Config.block)) } columnNum++ } lineNum++ } //添加我方的坦克 tank= Tank(Config.block * 10, Config.block * 12) views.add(tank) } override fun onDisplay() { views.forEach{ it.draw() } } override fun onKeyPressed(event: KeyEvent) { //用户操作时 println("1111111") when(event.code){ KeyCode.W->{tank.move(DIrections.UP)} KeyCode.S->{tank.move(DIrections.DOWN)} KeyCode.A->{tank.move(DIrections.LEFT)} KeyCode.D->{tank.move(DIrections.RITHT)} } } override fun onRefresh() { //做业务耗时的逻辑,判断运动的物体和阻塞物体是否发生碰撞 //1,找到运动的物体 views.filter { it is Movable }.forEach{move-> //2.找到阻塞的物体 move as Movable var badDirection:DIrections?=null var badBlock:Blockable?=null views.filter { it is Blockable }.forEach blockTag@{block-> //3,根据运动物体和阻塞物体的方位做一些判断,遍历集合找到是否发生碰撞 block as Blockable val willCollision :DIrections?= move.willCollision(block) //.let 表示不为空,为空时不走此方法 willCollision?.let{ badDirection=willCollision badBlock=block //移动的发现碰撞,跳出当前循环 return@blockTag } } //找到和move碰撞的阻塞快和找到会碰撞的方向 //通知可以移动的物体会在那个方向和那个物体碰撞 move.notifyCollision(badDirection,badBlock) } } }
0
Kotlin
0
3
b7689ee0bb3f781f56ad80c535fd9f577b828615
2,809
TankDZ
Apache License 2.0
app/src/main/java/com/goms/goms_android_v2/GomsApplication.kt
team-haribo
740,096,241
false
{"Kotlin": 621219}
package com.goms.goms_android_v2 import android.app.Application import dagger.hilt.android.HiltAndroidApp @HiltAndroidApp class GomsApplication : Application() {}
5
Kotlin
0
9
32b6b960f997e282a05c8409d6e045e6f95822d5
164
GOMS-Android-V2
MIT License
app/src/main/java/ru/terrakok/gitlabclient/presentation/project/files/ProjectFileDestination.kt
dector
341,706,824
false
null
package ru.terrakok.gitlabclient.presentation.project.files import android.os.Bundle class ProjectFileDestination { var defaultPath: String = "" private set var branchName: String = "" private set val paths = arrayListOf<String>() interface Callback { fun onMoveForward(fromRoot: Boolean) fun onMoveBack(fromRoot: Boolean) fun onBranchChange(branchName: String) } private var callback: Callback? = null fun setCallback(callback: Callback) { this.callback = callback } fun init(defaultPath: String, branchName: String) { this.defaultPath = defaultPath this.branchName = branchName } fun saveState(outState: Bundle) { outState.putString(KEY_DEFAULT_PATH, defaultPath) outState.putString(KEY_BRANCH_NAME, branchName) outState.putStringArrayList(KEY_PATHS, paths) } fun restoreState(savedState: Bundle) { defaultPath = savedState.getString(KEY_DEFAULT_PATH)!! branchName = savedState.getString(KEY_BRANCH_NAME)!! paths.addAll(savedState.getStringArrayList(KEY_PATHS)!!) } fun isInitiated() = defaultPath.isNotEmpty() && branchName.isNotEmpty() && paths.isNotEmpty() fun moveToRoot() { if (!isInitiated()) { paths.add(ROOT_PATH) } callback?.onMoveForward(true) } fun moveForward(path: String) { val fromRoot = isInRoot() paths.add(path) callback?.onMoveForward(fromRoot) } fun moveBack() { val fromRoot = isInRoot() if (!fromRoot) { paths.removeAt(paths.lastIndex) } callback?.onMoveBack(fromRoot) } fun isInRoot() = paths.size <= 1 fun changeBranch(newBranchName: String) { if (branchName != newBranchName) { branchName = newBranchName paths.clear() paths.add(ROOT_PATH) callback?.onBranchChange(newBranchName) } } companion object { private const val ROOT_PATH = "" private const val KEY_BRANCH_NAME = "key branch name" private const val KEY_PATHS = "key paths" private const val KEY_DEFAULT_PATH = "key default path" } }
0
Kotlin
0
1
7258eb2bc4ca9fcd1ebf3029217d80d6fd2de4b9
2,252
gitfox-mirror
Apache License 2.0
src/test/kotlin/game/GameTest.kt
danieldinter
563,899,846
false
{"Kotlin": 89806}
package game import gg.dani.chess.game.Checkmate import gg.dani.chess.game.Game import gg.dani.chess.helpers.Color import io.kotest.core.spec.style.StringSpec import io.kotest.matchers.shouldBe class GameKotest : StringSpec({ val game = Game() "fools mate" { val board = game.board val f2 = board.getSquare("f2") val f3 = board.getSquare("f3") val e7 = board.getSquare("e7") val e6 = board.getSquare("e6") val g2 = board.getSquare("g2") val g4 = board.getSquare("g4") val d8 = board.getSquare("d8") val h4 = board.getSquare("h4") // f2 -> f3 game.playersTurn.color shouldBe Color.WHITE game.movePiece(f2.piece!!, f3) noCheck(board.cm) // e7 -> e6 game.playersTurn.color shouldBe Color.BLACK game.movePiece(e7.piece!!, e6) noCheck(board.cm) // g2 -> g4 game.playersTurn.color shouldBe Color.WHITE game.movePiece(g2.piece!!, g4) noCheck(board.cm) // d8 -> h4 game.playersTurn.color shouldBe Color.BLACK game.movePiece(d8.piece!!, h4) board.cm.isBlackChecked() shouldBe false board.cm.isBlackCheckmated() shouldBe false board.cm.isWhiteChecked() shouldBe true board.cm.isWhiteCheckmated() shouldBe true } }) fun noCheck(cm: Checkmate) { cm.isBlackChecked() shouldBe false cm.isBlackCheckmated() shouldBe false cm.isWhiteChecked() shouldBe false cm.isWhiteCheckmated() shouldBe false }
0
Kotlin
0
0
5ed082dbdc03c2342958b5ded0d85ea41c3c7673
1,551
kotlin-chess
MIT License
libraries/push/impl/src/test/kotlin/io/element/android/libraries/push/impl/notifications/fake/FakeActiveNotificationsProvider.kt
element-hq
546,522,002
false
{"Kotlin": 8692554, "Python": 57175, "Shell": 39911, "JavaScript": 20399, "Java": 9607, "HTML": 9416, "CSS": 2519, "Ruby": 44}
/* * Copyright (c) 2024 New Vector Ltd * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.element.android.libraries.push.impl.notifications.fake import android.service.notification.StatusBarNotification import io.element.android.libraries.matrix.api.core.RoomId import io.element.android.libraries.matrix.api.core.SessionId import io.element.android.libraries.push.impl.notifications.ActiveNotificationsProvider class FakeActiveNotificationsProvider( private val getMessageNotificationsForRoomResult: (SessionId, RoomId) -> List<StatusBarNotification> = { _, _ -> emptyList() }, private val getNotificationsForSessionResult: (SessionId) -> List<StatusBarNotification> = { emptyList() }, private val getMembershipNotificationForSessionResult: (SessionId) -> List<StatusBarNotification> = { emptyList() }, private val getMembershipNotificationForRoomResult: (SessionId, RoomId) -> List<StatusBarNotification> = { _, _ -> emptyList() }, private val getSummaryNotificationResult: (SessionId) -> StatusBarNotification? = { null }, private val countResult: (SessionId) -> Int = { 0 }, ) : ActiveNotificationsProvider { override fun getMessageNotificationsForRoom(sessionId: SessionId, roomId: RoomId): List<StatusBarNotification> { return getMessageNotificationsForRoomResult(sessionId, roomId) } override fun getNotificationsForSession(sessionId: SessionId): List<StatusBarNotification> { return getNotificationsForSessionResult(sessionId) } override fun getMembershipNotificationForSession(sessionId: SessionId): List<StatusBarNotification> { return getMembershipNotificationForSessionResult(sessionId) } override fun getMembershipNotificationForRoom(sessionId: SessionId, roomId: RoomId): List<StatusBarNotification> { return getMembershipNotificationForRoomResult(sessionId, roomId) } override fun getSummaryNotification(sessionId: SessionId): StatusBarNotification? { return getSummaryNotificationResult(sessionId) } override fun count(sessionId: SessionId): Int { return countResult(sessionId) } }
263
Kotlin
129
955
31d0621fa15fe153bfd36104e560c9703eabe917
2,649
element-x-android
Apache License 2.0
user-agent/src/main/kotlin/ru/touchin/ua/devices/DevicePlatformFactory.kt
TouchInstinct
256,563,788
false
null
package ru.touchin.ua.devices import ru.touchin.common.devices.enums.DevicePlatform import ua_parser.Parser as UaParser class DevicePlatformFactory { fun fromUserAgent(userAgent: String): DevicePlatform { val client = UaParser().parse(userAgent) if (client.device.family.matches(HUAWEI_DEVICE_FAMILY_REGEX)) { return DevicePlatform.Huawei } return when (client.os.family) { "iOS" -> DevicePlatform.Apple "Android" -> DevicePlatform.Android else -> DevicePlatform.Web } } private companion object { val HUAWEI_DEVICE_FAMILY_REGEX = Regex( "ALP-|AMN-|ANA-|ANE-|ANG-|AQM-|ARS-|ART-|ATU-|BAC-|BLA-|BRQ-|CAG-|CAM-|CAN-|CAZ-|CDL-|CDY-|CLT-" + "|CRO-|CUN-|DIG-|DRA-|DUA-|DUB-|DVC-|ELE-|ELS-|EML-|EVA-|EVR-|FIG-|FLA-|FRL-|GLK-|HMA-|HW-|HWI-|INE-" + "|JAT-|JEF-|JER-|JKM-|JNY-|JSC-|LDN-|LIO-|LON-|LUA-|LYA-|LYO-|MAR-|MED-|MHA-|MLA-|MRD-|MYA-|NCE-|NEO-" + "|NOH-|NOP-|OCE-|PAR-|PIC-|POT-|PPA-|PRA-|RNE-|SEA-|SLA-|SNE-|SPN-|STK-|TAH-|TAS-|TET-|TRT-|VCE-|VIE-" + "|VKY-|VNS-|VOG-|VTR-|WAS-|WKG-|WLZ-|YAL" ) } }
1
Kotlin
1
3
c8ed908656dc5d28b77961131188ef5b65a98e0d
1,204
Backend-common
Apache License 2.0
domain/src/main/java/com/oguzdogdu/domain/usecase/favorites/GetDeleteFromFavoritesUseCase.kt
oguzsout
616,912,430
false
{"Kotlin": 456497}
package com.oguzdogdu.domain.usecase.favorites import com.oguzdogdu.domain.model.favorites.FavoriteImages interface GetDeleteFromFavoritesUseCase { suspend operator fun invoke(favoriteImage: FavoriteImages?) }
0
Kotlin
0
8
88456612d6a87b23a253f5b1df495d1c7ca0449a
215
Wallies
MIT License
app/src/main/java/com/jetpackcomposedemo/ui/room/ui/TodoViewModel.kt
manipatel30
605,739,159
false
null
package com.jetpackcomposedemo.ui.room.ui import android.util.Log import androidx.compose.runtime.MutableState import androidx.compose.runtime.mutableStateOf import androidx.lifecycle.ViewModel import androidx.lifecycle.viewModelScope import com.jetpackcomposedemo.ui.room.TodoRepository import com.jetpackcomposedemo.ui.room.model.ToDo import dagger.hilt.android.lifecycle.HiltViewModel import kotlinx.coroutines.flow.catch import kotlinx.coroutines.flow.collect import kotlinx.coroutines.launch import javax.inject.Inject @HiltViewModel class TodoViewModel @Inject constructor(private val todoRepository: TodoRepository) : ViewModel() { val response: MutableState<List<ToDo>> = mutableStateOf(listOf()) init { getAllTodos() } fun insert(toDo: ToDo) = viewModelScope.launch { todoRepository.insert(toDo) } fun getAllTodos() = viewModelScope.launch { todoRepository.getAllTodos() .catch { e -> Log.e("Main", e.message.toString()) }.collect { response.value = it } } }
0
Kotlin
0
0
dea6eca1cc40ec05c842d123efa21d718683ffe5
1,094
composedemo
Apache License 2.0
src/main/kotlin/com/github/dixtdf/archive/manager/action/PackGroupAction.kt
dixtdf
724,939,196
false
{"Kotlin": 68786}
package com.github.dixtdf.archive.manager.action import com.github.dixtdf.archive.manager.action.utils.MessageUtils import com.intellij.openapi.actionSystem.ActionGroup import com.intellij.openapi.actionSystem.AnAction import com.intellij.openapi.actionSystem.AnActionEvent import com.intellij.openapi.actionSystem.DefaultActionGroup class PackGroupAction : DefaultActionGroup() { override fun update(e: AnActionEvent) { e.presentation.text = MessageUtils().messages("packGroupActionText") super.update(e) } }
0
Kotlin
1
1
e70199fec53cca094549ef73acb0084cb2c213e5
538
ArchiveManager
Apache License 2.0
app/src/main/java/com/ksnk/radio/di/modules/ActivityModules.kt
Ksnk-dm
482,930,083
false
null
package com.ksnk.radio.di.modules import com.ksnk.radio.ui.main.MainActivity import dagger.Module import dagger.android.ContributesAndroidInjector @Module abstract class ActivityModules { @ContributesAndroidInjector abstract fun bindMainActivity(): MainActivity? }
2
Kotlin
1
0
eee36f663a8165d0769ae60243afee0a0b068035
274
Radio
Apache License 2.0
kmpp/src/iosMain/kotlin/com/piasy/kmpp/api/Logger.kt
Piasy
211,461,023
false
{"Objective-C": 70662, "C": 17733, "Kotlin": 7604, "C++": 6154, "Swift": 4053, "Shell": 694, "Batchfile": 505}
package com.piasy.kmpp.api import platform.Foundation.NSLog import platform.Foundation.NSThread /** * Created by Piasy{github.com/Piasy} on 2019/10/7. */ actual class Logger { actual fun info(tag: String, content: String) { NSLog("$tag: $content @ ${NSThread.currentThread.description}") } }
0
Objective-C
0
6
02c4e01f22887deac73fc07c12004c6e7a24f202
312
KmppBootstrap
MIT License
app/src/main/java/com/example/project3/MathScreen.kt
pascalkoj
693,393,119
false
{"Kotlin": 17075}
package com.example.project3 import android.os.Bundle import androidx.fragment.app.Fragment import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.Button import android.widget.TextView import androidx.navigation.fragment.NavHostFragment import androidx.navigation.fragment.findNavController import com.google.android.material.textfield.TextInputEditText // TODO: Rename parameter arguments, choose names that match // the fragment initialization parameters, e.g. ARG_ITEM_NUMBER private const val ARG_PARAM1 = "param1" private const val ARG_PARAM2 = "param2" /** * A simple [Fragment] subclass. * Use the [MathScreen.newInstance] factory method to * create an instance of this fragment. */ class MathScreen : Fragment() { // TODO: Rename and change types of parameters private var param1: String? = null private var param2: String? = null override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) arguments?.let { param1 = it.getString(ARG_PARAM1) param2 = it.getString(ARG_PARAM2) } } fun ToEndScreen() { val fm = parentFragmentManager if (fm != null) { val startScreen = fm.findFragmentById(R.id.nav_host_fragment) as MathScreen val navController = startScreen.findNavController() navController.navigate(R.id.action_mathScreen_to_mathEndScreen) } } override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View? { // Inflate the layout for this fragment val view = inflater.inflate(R.layout.fragment_math_screen, container, false) val answerText = view.findViewById<TextInputEditText>(R.id.textInputEditText) val operand1Text = view.findViewById<TextView>(R.id.textOp1) val operand2Text = view.findViewById<TextView>(R.id.textOp2) val operationText = view.findViewById<TextView>(R.id.textOperation) val mathapp = MathApp.instance val firstOpPair = mathapp.operandList.last() operand1Text.setText(firstOpPair.first.toString()) operand2Text.setText(firstOpPair.second.toString()) var operationStr = "" if (mathapp.operationMode == OperationMode.ADDITION) operationStr = "+" if (mathapp.operationMode == OperationMode.MULTIPLICATION) operationStr = "*" if (mathapp.operationMode == OperationMode.DIVISION) operationStr = "/" if (mathapp.operationMode == OperationMode.SUBTRACTION) operationStr = "-" operationText.setText(operationStr) // end this screen val doneButton = view.findViewById<Button>(R.id.bDone) doneButton.setOnClickListener { if (mathapp.ProcessAnswer(answerText.text.toString())) { ToEndScreen() } else { val nextOperands = mathapp.operandList.last() operand1Text.setText(nextOperands.first.toString()) operand2Text.setText(nextOperands.second.toString()) } answerText.setText("") } return view } companion object { /** * Use this factory method to create a new instance of * this fragment using the provided parameters. * * @param param1 Parameter 1. * @param param2 Parameter 2. * @return A new instance of fragment MathScreen. */ // TODO: Rename and change types and number of parameters @JvmStatic fun newInstance(param1: String, param2: String) = MathScreen().apply { arguments = Bundle().apply { putString(ARG_PARAM1, param1) putString(ARG_PARAM2, param2) } } } }
0
Kotlin
0
0
c524c8929b09eb8d4f5ede8710e5076376b98721
3,930
project3
Apache License 2.0
src/commonMain/kotlin/main.kt
ryopei
215,591,957
false
null
import com.soywiz.klock.seconds import com.soywiz.korau.sound.nativeSoundProvider import com.soywiz.korau.sound.readNativeSound import com.soywiz.korge.* import com.soywiz.korge.animate.AnLibrary import com.soywiz.korge.animate.AnMovieClip import com.soywiz.korge.animate.serialization.readAni import com.soywiz.korge.input.* import com.soywiz.korge.scene.Module import com.soywiz.korge.scene.Scene import com.soywiz.korge.scene.sceneContainer import com.soywiz.korge.tween.* import com.soywiz.korge.view.* import com.soywiz.korim.bitmap.NativeImage import com.soywiz.korim.color.ColorTransform import com.soywiz.korim.color.Colors import com.soywiz.korim.color.RGBA import com.soywiz.korim.font.BitmapFontGenerator import com.soywiz.korim.font.ttf.TtfFont import com.soywiz.korim.font.ttf.fillText import com.soywiz.korim.vector.Context2d import com.soywiz.korinject.AsyncFactory import com.soywiz.korinject.AsyncInjector import com.soywiz.korio.async.async import com.soywiz.korio.async.launchImmediately import com.soywiz.korio.file.std.* import com.soywiz.korio.stream.openSync import com.soywiz.korma.geom.degrees import com.soywiz.korma.geom.vector.rect import com.soywiz.korma.geom.vector.roundRect import com.soywiz.korma.interpolation.Easing import kotlinx.coroutines.awaitAll import kotlin.reflect.KClass object MyModule : Module() { override val mainScene: KClass<out Scene> = TitleScene::class override suspend fun AsyncInjector.configure() { mapPrototype { TitleScene() } mapPrototype { TitleScene2() } } } suspend fun main() = Korge(config = Korge.Config(module = MyModule)) class TitleScene : Scene() { override suspend fun Container.sceneInit() { val t = text("Mouse Position:", color = Colors.WHITE) graphics { stroke(Colors.RED, Context2d.StrokeInfo(3.0)) { roundRect(100.0, 100.0, 300.0, 300.0, 10, 10) } fill(Colors.YELLOW) { roundRect(300.0, 300.0, 300.0, 300.0, 10, 10) } onClick { launchImmediately { sceneContainer.changeTo(TitleScene2::class, time = 1.5.seconds) } } } onMove { t.text = "Mouse Position:" + it.currentPos } } override suspend fun sceneAfterInit() { super.sceneAfterInit() } } class TitleScene2 : Scene() { lateinit var kurage:AnMovieClip override suspend fun Container.sceneInit() { var mainLibrary: AnLibrary = resourcesVfs["chara_kurage.ani"].readAni(views) kurage = mainLibrary.createMainTimeLine().apply { position(3 * this.width/2, this.height*3) scale(3.0, 3.0) onClick { launchImmediately { sceneContainer.changeTo(TitleScene::class, time = 1.5.seconds) } } } kurage.symbol.states.forEach { println(it.value.name) } addChild(kurage) kurage.timelineRunner.gotoAndStop("stop_back") } override suspend fun sceneAfterInit() { super.sceneAfterInit() async { kurage.timelineRunner.gotoAndPlay("walk_left") kurage.timelineRunner.gotoAndPlay("walk_left") kurage.timelineRunner.gotoAndPlay("walk_left") kurage.timelineRunner.gotoAndPlay("walk_left") kurage.timelineRunner.gotoAndPlay("walk_left") kurage.timelineRunner.gotoAndPlay("walk_left") }.await() } }
0
Kotlin
0
0
a25e5f9a7dd3080a7aa286a940b5ca8d63bdfe19
3,559
korge-hello-world
MIT License
android/src/main/kotlin/com/pravera/flutter_secure_keyboard/FlutterSecureKeyboardPluginChannel.kt
Dev-hwang
325,221,130
false
{"Dart": 50456, "Kotlin": 3294, "Swift": 2524, "Ruby": 2247, "Objective-C": 804}
package com.pravera.flutter_secure_keyboard import android.app.Activity import io.flutter.plugin.common.BinaryMessenger /** FlutterSecureKeyboardPluginChannel */ interface FlutterSecureKeyboardPluginChannel { fun init(messenger: BinaryMessenger) fun setActivity(activity: Activity?) fun dispose() }
1
Dart
8
28
79f548228ee3863ea0a36fdde744e9a0aa56f772
304
flutter_secure_keyboard
MIT License
src/main/kotlin/com/nuc/evaluate/vo/TitleVO.kt
codacy-badger
163,490,462
true
{"Kotlin": 54712}
package com.nuc.evaluate.vo import com.nuc.evaluate.po.Title /** * @author 杨晓辉 2018/2/4 10:26 * 返回到页面的试题视图 */ class TitleVO { var id: Long = 0 lateinit var num: String lateinit var title: String lateinit var category: String var difficulty: String? = null var score: Double = 0.0 var completeTime: Long = 0 var sectionA: String? = null var sectionB: String? = null var sectionC: String? = null var sectionD: String? = null var blankNum: Int = 0 fun setSection(category: String, title: Title) { when (category) { // 单选题 "1" -> { sectionA = title.sectiona sectionB = title.sectionb sectionC = title.sectionc sectionD = title.sectiond } // 填空题 "3" -> { val sb = StringBuilder() val titleList = this.title.split("_{1,10}_".toRegex()) for (i in 0 until titleList.size - 1) { sb.append(titleList[i]) sb.append("【 】") } sb.append(titleList.last()) this.title = sb.toString().trim() blankNum = titleList.size - 1 } else -> { } } } override fun toString(): String { return "TitleVO(id=$id, num='$num', title='$title', category='$category', difficulty=$difficulty, score=$score, completeTime=$completeTime, sectionA=$sectionA, sectionB=$sectionB, sectionC=$sectionC, sectionD=$sectionD, blankNum=$blankNum)" } }
0
Kotlin
0
0
51d5745fb54ea0c7fa70abb7cc2d71f2dcf23cac
1,604
evaluate
Apache License 2.0
app/src/main/java/com/example/composepokemonapp/data/remote/response/GenerationI.kt
NimeshVasani
640,294,775
false
{"Kotlin": 40899}
package com.example.composepokemonapp.data.remote.response data class GenerationI( val red_blue: RedBlue, val yellow: Yellow )
0
Kotlin
0
1
b98f14534e10895b0cb91177edcb43f78400681e
135
Compose-Pokemon-App
Info-ZIP License
core/src/main/java/com/rahmadev/hamba/core/presentation/adapter/QuranAdapter.kt
rahmadnoorikhsan
729,571,011
false
{"Kotlin": 78137, "Java": 3429}
package com.rahmadev.hamba.core.presentation.adapter import android.view.LayoutInflater import android.view.ViewGroup import androidx.recyclerview.widget.DiffUtil import androidx.recyclerview.widget.ListAdapter import androidx.recyclerview.widget.RecyclerView import com.rahmadev.hamba.core.R import com.rahmadev.hamba.core.databinding.ItemSurahBinding import com.rahmadev.hamba.core.domain.model.quran.Quran class QuranAdapter(val id: (Int) -> Unit) : ListAdapter<Quran, QuranAdapter.QuranViewHolder>(DIFF_CALLBACK) { override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): QuranViewHolder { val binding = ItemSurahBinding.inflate(LayoutInflater.from(parent.context), parent, false) return QuranViewHolder(binding) } override fun onBindViewHolder(holder: QuranViewHolder, position: Int) = holder.bind(getItem(position)) inner class QuranViewHolder(private val binding: ItemSurahBinding) : RecyclerView.ViewHolder(binding.root) { fun bind(quran: Quran) { binding.apply { tvNumber.text = quran.number.toString() tvArabic.text = quran.name tvIndonesian.text = quran.latin tvType.text = itemView.context.getString( R.string.surah_type, quran.type, quran.translate ) } itemView.setOnClickListener { quran.number?.let { id.invoke(it) } } } } companion object { val DIFF_CALLBACK = object : DiffUtil.ItemCallback<Quran>() { override fun areItemsTheSame(oldItem: Quran, newItem: Quran) = oldItem == newItem override fun areContentsTheSame(oldItem: Quran, newItem: Quran) = oldItem == newItem } } }
0
Kotlin
0
0
ad589c072d95ffe43c5a6274219550e9742969e7
1,805
Hamba
MIT License
src/main/kotlin/me/fzzyhmstrs/amethyst_imbuement/spells/WitheringBoltAugment.kt
fzzyhmstrs
461,338,617
false
null
package me.fzzyhmstrs.amethyst_imbuement.spells import me.fzzyhmstrs.amethyst_core.augments.ScepterAugment import me.fzzyhmstrs.amethyst_core.augments.base.ProjectileAugment import me.fzzyhmstrs.amethyst_core.augments.data.AugmentDatapoint import me.fzzyhmstrs.amethyst_core.augments.paired.AugmentType import me.fzzyhmstrs.amethyst_core.augments.paired.PairedAugments import me.fzzyhmstrs.amethyst_core.modifier.AugmentEffect import me.fzzyhmstrs.amethyst_core.scepter.LoreTier import me.fzzyhmstrs.amethyst_core.scepter.ScepterTier import me.fzzyhmstrs.amethyst_core.scepter.SpellType import me.fzzyhmstrs.amethyst_imbuement.AI import me.fzzyhmstrs.amethyst_imbuement.entity.PlayerWitherSkullEntity import me.fzzyhmstrs.amethyst_imbuement.spells.pieces.SpellAdvancementChecks import me.fzzyhmstrs.fzzy_core.coding_util.PerLvlI import net.minecraft.entity.LivingEntity import net.minecraft.entity.projectile.ProjectileEntity import net.minecraft.item.Items import net.minecraft.server.network.ServerPlayerEntity import net.minecraft.sound.SoundEvent import net.minecraft.sound.SoundEvents import net.minecraft.text.Text import net.minecraft.util.Identifier import net.minecraft.util.math.MathHelper import net.minecraft.world.World class WitheringBoltAugment: ProjectileAugment(ScepterTier.TWO, AugmentType.BALL){ override val augmentData: AugmentDatapoint = AugmentDatapoint(AI.identity("withering_bolt"),SpellType.FURY, PerLvlI(30,-2),13, 11,5,1,2,LoreTier.LOW_TIER, Items.WITHER_SKELETON_SKULL) //ml 5 override val baseEffect: AugmentEffect get() = super.baseEffect.withDamage(7.5f,0.5f) override fun appendDescription(description: MutableList<Text>, other: ScepterAugment, othersType: AugmentType) { TODO("Not yet implemented") } override fun provideArgs(pairedSpell: ScepterAugment): Array<Text> { return arrayOf(pairedSpell.provideAdjective(this)) } override fun onPaired(player: ServerPlayerEntity, pair: PairedAugments) { if (pair.spellsAreEqual()){ SpellAdvancementChecks.grant(player, SpellAdvancementChecks.DOUBLE_TRIGGER) } if (pair.spellsAreUnique()){ SpellAdvancementChecks.grant(player, SpellAdvancementChecks.UNIQUE_TRIGGER) } SpellAdvancementChecks.grant(player, SpellAdvancementChecks.EXPLODES_TRIGGER) } override fun entityClass(world: World, user: LivingEntity, level: Int, effects: AugmentEffect): ProjectileEntity { val yaw = user.yaw val pitch = user.pitch val roll = user.roll val speed = 4.0F val f = (-MathHelper.sin(yaw * (Math.PI.toFloat() / 180)) * MathHelper.cos(pitch * (Math.PI.toFloat() / 180)) * speed) + user.velocity.x val g = (-MathHelper.sin((pitch + roll) * (Math.PI.toFloat() / 180)) * speed) + user.velocity.y val h = (MathHelper.cos(yaw * (Math.PI.toFloat() / 180)) * MathHelper.cos(pitch * (Math.PI.toFloat() / 180)) * speed) + user.velocity.z val wse = PlayerWitherSkullEntity(world,user,f,g,h) wse.passEffects(effects, level) wse.setPos(user.x,user.eyeY-0.2,user.z) wse.isCharged = false wse.setAugment(this) return wse } override fun soundEvent(): SoundEvent { return SoundEvents.ENTITY_WITHER_SHOOT } }
14
Kotlin
7
3
2614d0138c139d378c27e460d9a141799565920c
3,332
ai
MIT License
src/day11/Day11.kt
commanderpepper
574,647,779
false
null
package day11 import readInput fun main (){ val day11Input = readInput("day11") val monkeysListPartOne = parseInput(day11Input) val monkeysListPartTwo = parseInput(day11Input) println(monkeyBusiness(monkeys = monkeysListPartOne, rounds = 20, worryDivisor = 3L)) println(monkeyBusiness(monkeys = monkeysListPartTwo, rounds = 10000, worryDivisor = 0L)) } // Using the solution from Todd Ginsberg solution for day 11 fun List<Monkey>.getTestProduct(): Long { var product = 1L this.forEach { monkey -> product *= monkey.testCondition } return product } private fun monkeyBusiness(monkeys: List<Monkey>, rounds: Int = 20, worryDivisor: Long = 3L): Long { repeat(rounds) { monkeys.forEach { monkey -> // Monkey to move to - index of item to move val itemsToMove = mutableListOf<Pair<Int, Int>>() monkey.items.forEachIndexed { index, _ -> // Make the human worried val product = monkeys.getTestProduct() monkey.updateWorryLevel(index, product) // Monkey inspects item monkey.inspectItem(index, worryDivisor) // Monkey decided who it's going to throw to if (monkey.isTheHumanWorried(index)) { itemsToMove.add(monkey.trueMonkey to index) } else { itemsToMove.add(monkey.falseMonkey to index) } } // Monkey throws the items itemsToMove.forEach { val otherMonkey = monkeys[it.first] otherMonkey.items.add(monkey.items[it.second]) } monkey.itemsInspected += monkey.items.size monkey.items.clear() } } // monkeys.forEach(::println) val deviousMonkeys = monkeys.sortedByDescending { it.itemsInspected } return deviousMonkeys[0].itemsInspected * deviousMonkeys[1].itemsInspected } data class Monkey(val items: MutableList<Long>, val operation: Operation, val testCondition: Long, val trueMonkey: Int, val falseMonkey: Int, var itemsInspected: Long = 0L){ fun inspectItem(itemIndex: Int, divisor : Long = 3L){ if(divisor > 0) { items[itemIndex] = items[itemIndex] / divisor } } fun updateWorryLevel(itemIndex: Int){ val item = items[itemIndex] items[itemIndex] = operation.operate(item) } // Using the solution from Todd Ginsberg solution for day 11 fun updateWorryLevel(itemIndex: Int, testProduct : Long){ val item = items[itemIndex] items[itemIndex] = operation.operate(item) % testProduct } fun isTheHumanWorried(itemIndex: Int): Boolean { val item = items[itemIndex] return item % testCondition == 0L } } data class Operation(private val type: String, private val amount: Long, val useOld: Boolean){ fun operate(item: Long): Long { return if(useOld){ when(type){ "*" -> item * item else -> item + item } } else { when(type){ "*" -> item * amount else -> item + amount } } } } fun parseInput(input: List<String>): List<Monkey> { val monkeys = mutableListOf<Monkey>() var i = 0 while(i < input.size){ // If the input is M I assume it's a Monkey if(input[i].isNotEmpty() && input[i].first() == 'M'){ val startItemInputStartIndex = input[i + 1].indexOfFirst { it.isDigit() } val startingItems = input[i + 1].slice(startItemInputStartIndex until input[i + 1].length).split(",").map(String::trim).map(String::toLong) // println(startingItems) val operationStartIndex = if(input[i + 2].contains("*")) input[i + 2].indexOf("*") else input[i + 2].indexOf("+") val operationList = input[i + 2].slice(operationStartIndex until input[i + 2].length).split(" ") val operation = Operation(type = operationList.first(), useOld = operationList.last() == "old", amount = if(operationList.last() == "old") 1L else operationList.last().toLong()) // println(operation) val testStartIndex = input[i + 3].indexOfFirst { it.isDigit() } val testAmount = input[i + 3].slice(testStartIndex until input[i + 3].length).toLong() // println(testAmount) val trueStartIndex = input[i + 4].indexOfFirst { it.isDigit() } val trueMonkey = input[i + 4].slice(trueStartIndex until input[i + 4].length).toInt() // println(trueMonkey) val falseStartIndex = input[i + 5].indexOfFirst { it.isDigit() } val falseMonkey = input[i + 5].slice(falseStartIndex until input[i + 5].length).toInt() // println(falseMonkey) val monkey = Monkey(items = startingItems.toMutableList(), operation = operation, testCondition = testAmount, trueMonkey = trueMonkey, falseMonkey = falseMonkey) monkeys.add(monkey) i += 5 } i++ } return monkeys }
0
Kotlin
0
1
fef291c511408c1a6f34a24ed7070ceabc0894a1
5,134
advent-of-code-kotlin-2022
Apache License 2.0
example-app/src/commonMain/kotlin/com/lightningkite/mppexampleapp/InfiniteImagesScreen.kt
lightningkite
778,386,343
false
{"Kotlin": 2224994, "Swift": 7449, "Ruby": 4925, "CSS": 4562, "HTML": 4084, "HCL": 880, "JavaScript": 302, "Objective-C": 142, "C": 104, "Shell": 49}
package com.lightningkite.mppexampleapp import com.lightningkite.kiteui.views.ViewWriter import com.lightningkite.kiteui.* import com.lightningkite.kiteui.models.* import com.lightningkite.kiteui.navigation.Screen import com.lightningkite.kiteui.navigation.dialogScreenNavigator import com.lightningkite.kiteui.navigation.screenNavigator import com.lightningkite.kiteui.reactive.* import com.lightningkite.kiteui.views.* import com.lightningkite.kiteui.views.direct.* import kotlinx.coroutines.delay @Routable("recycler-view-infinite-images") object InfiniteImagesScreen : Screen { override val title: Readable<String> get() = super.title object ReturnIndexList: List<Int>{ override val size: Int get() = 10_000 override fun get(index: Int): Int = index override fun isEmpty(): Boolean = false override fun iterator(): Iterator<Int> = (0..<10_000).iterator() override fun listIterator(): ListIterator<Int> = object: ListIterator<Int> { var n = -1 override fun hasNext(): Boolean = n < 10_000 override fun hasPrevious(): Boolean = n > 0 override fun next(): Int = ++n override fun nextIndex(): Int = ++n override fun previous(): Int = --n override fun previousIndex(): Int = --n } override fun listIterator(index: Int): ListIterator<Int> = object: ListIterator<Int> { var n = index - 1 override fun hasNext(): Boolean = n < 10_000 override fun hasPrevious(): Boolean = n > 0 override fun next(): Int = ++n override fun nextIndex(): Int = ++n override fun previous(): Int = --n override fun previousIndex(): Int = --n } override fun subList(fromIndex: Int, toIndex: Int): List<Int> = (fromIndex..<toIndex).toList() override fun lastIndexOf(element: Int): Int = element override fun indexOf(element: Int): Int = element override fun containsAll(elements: Collection<Int>): Boolean = true override fun contains(element: Int): Boolean = true } override fun ViewWriter.render() { recyclerView { columns = 4 children(Constant(ReturnIndexList)) { unpadded - button { ::transitionId { it().toString() } sizeConstraints(aspectRatio = 1.0) - image { viewDebugTarget = this scaleType = ImageScaleType.Crop ::source { ImageRemote("https://picsum.photos/seed/${it()}/100/100") } } onClick { dialogScreenNavigator.navigate(ImageViewPager(it.await())) } } } } } } class ImageViewPager(val initialIndex: Int) : Screen { val currentPage = Property(initialIndex) override fun ViewWriter.render() { stack { val rv: ViewPager viewPager { rv = this children(Constant(InfiniteImagesScreen.ReturnIndexList)) { currImage -> val renders = Property(0) stack { ::transitionId { currImage().toString() } spacing = 0.25.rem zoomableImage { reactiveScope { renders.value++ val index = currImage() source = ImageRemote("https://picsum.photos/seed/${index}/100/100") async(index) { delay(1) } source = ImageRemote("https://picsum.photos/seed/${index}/1000/1000") } scaleType = ImageScaleType.Fit } centered - h2 { ::content { renders().toString() } } } } index bind currentPage } gravity(Align.End, Align.Start) - button { icon { source = Icon.close } onClick { screenNavigator.dismiss() } } atBottomCenter - row { text { ::content { "currentPage ${currentPage()}" } } text { content = "I never update because I'm a loser" ::content { "rv.index ${rv.index()}" } } } atBottomStart - button { text("jump to #20") onClick { currentPage.set(20) } } } in themeFromLast { it.copy(background = Color.black, foreground = Color.white) } } }
3
Kotlin
0
2
58ee76ab3e8e7cab71e65a18c302367c6a641da5
4,880
kiteui
Apache License 2.0
trec-service/src/main/kotlin/eu/jrie/put/trec/domain/index/index.kt
jakubriegel
323,860,098
false
null
package eu.jrie.put.trec.domain.index import eu.jrie.put.trec.api.IndexAlgorithm import eu.jrie.put.trec.api.IndexEngine import eu.jrie.put.trec.api.IndexEngine.ELASTICSEARCH import eu.jrie.put.trec.api.IndexEngine.TERRIER import eu.jrie.put.trec.domain.Article import eu.jrie.put.trec.domain.query.Topic import eu.jrie.put.trec.domain.query.TopicRepository import kotlinx.coroutines.FlowPreview import kotlinx.coroutines.ObsoleteCoroutinesApi import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.asFlow import kotlinx.coroutines.flow.map import kotlinx.coroutines.newFixedThreadPoolContext data class ArticleMatch ( val rank: Int, val score: Float, val article: Article ) @ObsoleteCoroutinesApi class IndexService { private val esContext = newFixedThreadPoolContext(3, "esContext") private val terrierContext = newFixedThreadPoolContext(3, "terrierContext") private val repositories = mapOf( ELASTICSEARCH to ElasticsearchRepository(esContext), TERRIER to TerrierRepository(terrierContext) ) private val topicRepository = TopicRepository() suspend fun find(query: String, engine: IndexEngine, algorithm: IndexAlgorithm): Flow<ArticleMatch> { return repositories.getValue(engine) .find(query, algorithm) } private suspend fun find(topic: Topic, engine: IndexEngine, algorithm: IndexAlgorithm): Flow<ArticleMatch> { return find(topic.asText(), engine, algorithm) } suspend fun findByTopic(topicId: Int, topicSet: String, engine: IndexEngine, algorithm: IndexAlgorithm): Pair<Topic, Flow<ArticleMatch>> { val topic = topicRepository.get(topicId, topicSet) return topic to find(topic.asText(), engine, algorithm) } @FlowPreview suspend fun findForAllTopics(topicSet: String, engine: IndexEngine, algorithm: IndexAlgorithm): Flow<Pair<Int, Flow<ArticleMatch>>> { return topicRepository.getAll(topicSet) .asFlow() .map { it.id to find(it, engine, algorithm) } } private companion object { fun Topic.asText() = "$disease $gene $treatment" } }
0
Kotlin
0
0
a96c16aabb83766e0da88264b3b61e4d3b1d1f44
2,137
trec-analyzer
MIT License
app/src/main/java/xyz/fairportstudios/popularin/enums/PointType.kt
rgxcp
277,228,278
false
null
package xyz.fairportstudios.popularin.enums enum class PointType { FAVORITE, REVIEW, WATCHLIST }
0
Kotlin
0
0
ac82b65d5f43d07b64aa5010218c663983c839cb
101
PopularinKotlin
MIT License
Fabric/src/main/kotlin/mod/master_bw3/hexui/fabric/networking/MsgSetScreenS2C.kt
Master-Bw3
838,004,671
false
{"Kotlin": 53480, "Java": 2260}
package mod.master_bw3.hexui.fabric.networking import at.petrak.hexcasting.api.casting.iota.Iota import at.petrak.hexcasting.api.casting.iota.IotaType import at.petrak.hexcasting.api.casting.iota.ListIota import at.petrak.hexcasting.api.utils.putCompound import dev.architectury.networking.NetworkManager.PacketContext import mod.master_bw3.hexui.HexUI import mod.master_bw3.hexui.fabric.api.casting.iota.ComponentIota import mod.master_bw3.hexui.fabric.api.componentBuilder.ComponentBuilder import mod.master_bw3.hexui.fabric.api.componentBuilder.ComponentBuilderType import net.minecraft.nbt.NbtCompound import net.minecraft.network.PacketByteBuf import java.util.function.Supplier @JvmRecord data class MsgSetScreenS2C(val view: ComponentBuilder<*>) { constructor(buf: PacketByteBuf) : this(ComponentBuilderType.deserialize(buf.readNbt()!!)) fun encode(buf: PacketByteBuf) { buf.writeNbt(ComponentBuilderType.serialize(view)) } }
0
Kotlin
0
0
eedc226cdf514ef3f6d17fa6a4b3fd5a1f950fcd
958
hex-ui
MIT License
app/src/main/java/com/hypertrack/android/utils/GoogleServicesUtils.kt
hypertrack
241,723,736
false
null
package com.hypertrack.android.utils import com.google.android.gms.tasks.Task import kotlin.coroutines.resume import kotlin.coroutines.suspendCoroutine import com.google.android.play.core.tasks.Task as PlayTask suspend fun <T : Any> Task<T>?.toSuspendCoroutine(): Result<T> = suspendCoroutine { continuation -> if (this != null) { addOnSuccessListener { continuation.resume(it.asSuccess()) } addOnFailureListener { continuation.resume(it.asFailure()) } } else { continuation.resume(NullPointerException("Task is null").asFailure()) } } suspend fun <T> PlayTask<T>?.toSuspendCoroutine(): Result<T> = suspendCoroutine { continuation -> if (this != null) { addOnSuccessListener { continuation.resume(it.asSuccess()) } addOnFailureListener { continuation.resume(it.asFailure()) } } else { continuation.resume(NullPointerException("Task is null").asFailure()) } }
1
Kotlin
17
31
7a613e4b618043d95e101b819d903c3b1eda6773
1,014
visits-android
MIT License
vuesaxicons/src/commonMain/kotlin/moe/tlaster/icons/vuesax/vuesaxicons/bold/Cpusetting.kt
Tlaster
560,394,734
false
{"Kotlin": 25133302}
package moe.tlaster.icons.vuesax.vuesaxicons.bold 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 moe.tlaster.icons.vuesax.vuesaxicons.BoldGroup public val BoldGroup.Cpusetting: ImageVector get() { if (_cpusetting != null) { return _cpusetting!! } _cpusetting = Builder(name = "Cpusetting", defaultWidth = 24.0.dp, defaultHeight = 24.0.dp, viewportWidth = 24.0f, viewportHeight = 24.0f).apply { path(fill = SolidColor(Color(0xFF292D32)), stroke = null, strokeLineWidth = 0.0f, strokeLineCap = Butt, strokeLineJoin = Miter, strokeLineMiter = 4.0f, pathFillType = NonZero) { moveTo(4.09f, 8.08f) curveTo(4.04f, 8.38f, 4.0f, 8.68f, 4.0f, 9.0f) curveTo(4.0f, 8.69f, 4.04f, 8.38f, 4.09f, 8.08f) close() moveTo(4.0f, 15.0f) curveTo(4.0f, 15.32f, 4.04f, 15.62f, 4.09f, 15.92f) curveTo(4.04f, 15.62f, 4.0f, 15.31f, 4.0f, 15.0f) close() moveTo(8.09f, 19.91f) curveTo(8.38f, 19.96f, 8.69f, 20.0f, 9.0f, 20.0f) curveTo(8.69f, 20.0f, 8.39f, 19.96f, 8.09f, 19.91f) close() moveTo(8.09f, 4.09f) curveTo(8.39f, 4.04f, 8.69f, 4.0f, 9.0f, 4.0f) curveTo(8.69f, 4.0f, 8.38f, 4.04f, 8.09f, 4.09f) close() moveTo(15.92f, 4.09f) curveTo(15.62f, 4.04f, 15.32f, 4.0f, 15.0f, 4.0f) curveTo(15.31f, 4.0f, 15.62f, 4.04f, 15.92f, 4.09f) close() moveTo(19.91f, 8.08f) curveTo(19.96f, 8.38f, 20.0f, 8.69f, 20.0f, 9.0f) curveTo(20.0f, 8.68f, 19.96f, 8.38f, 19.91f, 8.08f) close() } path(fill = SolidColor(Color(0xFF292D32)), stroke = null, strokeLineWidth = 0.0f, strokeLineCap = Butt, strokeLineJoin = Miter, strokeLineMiter = 4.0f, pathFillType = NonZero) { moveTo(22.0f, 8.3f) curveTo(22.0f, 8.72f, 21.67f, 9.05f, 21.25f, 9.05f) horizontalLineTo(20.0f) verticalLineTo(10.8871f) curveTo(20.0f, 11.2207f, 19.638f, 11.4284f, 19.35f, 11.26f) curveTo(18.92f, 11.01f, 18.42f, 10.93f, 17.94f, 11.06f) curveTo(17.6321f, 11.1339f, 17.26f, 10.9349f, 17.26f, 10.6183f) verticalLineTo(9.74f) curveTo(17.26f, 8.09f, 15.91f, 6.74f, 14.26f, 6.74f) horizontalLineTo(9.74f) curveTo(8.09f, 6.74f, 6.74f, 8.09f, 6.74f, 9.74f) verticalLineTo(14.26f) curveTo(6.74f, 15.91f, 8.09f, 17.26f, 9.74f, 17.26f) horizontalLineTo(10.19f) curveTo(10.306f, 17.26f, 10.4f, 17.354f, 10.4f, 17.47f) curveTo(10.4f, 18.4335f, 11.0982f, 19.2436f, 12.0175f, 19.4298f) curveTo(12.1904f, 19.4648f, 12.3073f, 19.6716f, 12.25f, 19.8383f) curveTo(12.2172f, 19.9337f, 12.1302f, 20.0f, 12.0293f, 20.0f) horizontalLineTo(9.06f) verticalLineTo(21.25f) curveTo(9.06f, 21.66f, 8.72f, 22.0f, 8.31f, 22.0f) curveTo(7.89f, 22.0f, 7.56f, 21.66f, 7.56f, 21.25f) verticalLineTo(19.78f) curveTo(5.96f, 19.29f, 4.71f, 18.04f, 4.23f, 16.45f) horizontalLineTo(2.75f) curveTo(2.34f, 16.45f, 2.0f, 16.11f, 2.0f, 15.7f) curveTo(2.0f, 15.28f, 2.34f, 14.95f, 2.75f, 14.95f) horizontalLineTo(4.0f) verticalLineTo(12.75f) horizontalLineTo(2.75f) curveTo(2.34f, 12.75f, 2.0f, 12.41f, 2.0f, 12.0f) curveTo(2.0f, 11.58f, 2.34f, 11.25f, 2.75f, 11.25f) horizontalLineTo(4.0f) verticalLineTo(9.05f) horizontalLineTo(2.75f) curveTo(2.34f, 9.05f, 2.0f, 8.72f, 2.0f, 8.3f) curveTo(2.0f, 7.89f, 2.34f, 7.55f, 2.75f, 7.55f) horizontalLineTo(4.23f) curveTo(4.71f, 5.96f, 5.96f, 4.71f, 7.56f, 4.22f) verticalLineTo(2.75f) curveTo(7.56f, 2.34f, 7.89f, 2.0f, 8.31f, 2.0f) curveTo(8.72f, 2.0f, 9.06f, 2.34f, 9.06f, 2.75f) verticalLineTo(4.0f) horizontalLineTo(11.25f) verticalLineTo(2.75f) curveTo(11.25f, 2.34f, 11.59f, 2.0f, 12.0f, 2.0f) curveTo(12.41f, 2.0f, 12.75f, 2.34f, 12.75f, 2.75f) verticalLineTo(4.0f) horizontalLineTo(14.95f) verticalLineTo(2.75f) curveTo(14.95f, 2.34f, 15.29f, 2.0f, 15.7f, 2.0f) curveTo(16.11f, 2.0f, 16.45f, 2.34f, 16.45f, 2.75f) verticalLineTo(4.23f) curveTo(18.04f, 4.71f, 19.29f, 5.96f, 19.77f, 7.55f) horizontalLineTo(21.25f) curveTo(21.67f, 7.55f, 22.0f, 7.89f, 22.0f, 8.3f) close() } path(fill = SolidColor(Color(0xFF292D32)), stroke = null, strokeLineWidth = 0.0f, strokeLineCap = Butt, strokeLineJoin = Miter, strokeLineMiter = 4.0f, pathFillType = NonZero) { moveTo(20.9904f, 15.5315f) curveTo(20.3104f, 15.5315f, 19.9204f, 15.1915f, 19.9204f, 14.6915f) curveTo(19.9204f, 14.4915f, 19.9804f, 14.2615f, 20.1204f, 14.0215f) curveTo(20.4004f, 13.5415f, 20.2304f, 12.9215f, 19.7504f, 12.6515f) lineTo(18.8404f, 12.1215f) curveTo(18.4204f, 11.8715f, 17.8804f, 12.0215f, 17.6304f, 12.4415f) lineTo(17.5704f, 12.5415f) curveTo(17.0904f, 13.3715f, 16.3104f, 13.3715f, 15.8304f, 12.5415f) lineTo(15.7704f, 12.4415f) curveTo(15.5304f, 12.0215f, 14.9804f, 11.8715f, 14.5704f, 12.1215f) lineTo(13.6504f, 12.6515f) curveTo(13.3304f, 12.8315f, 13.1404f, 13.1715f, 13.1404f, 13.5215f) curveTo(13.1404f, 13.6915f, 13.1904f, 13.8615f, 13.2804f, 14.0215f) curveTo(13.4204f, 14.2615f, 13.4904f, 14.4915f, 13.4904f, 14.6915f) curveTo(13.4904f, 15.1915f, 13.0904f, 15.5315f, 12.4104f, 15.5315f) curveTo(11.8604f, 15.5315f, 11.4004f, 15.9815f, 11.4004f, 16.5315f) verticalLineTo(17.4715f) curveTo(11.4004f, 18.0215f, 11.8604f, 18.4715f, 12.4104f, 18.4715f) curveTo(13.0904f, 18.4715f, 13.4904f, 18.8115f, 13.4904f, 19.3115f) curveTo(13.4904f, 19.5115f, 13.4204f, 19.7415f, 13.2804f, 19.9815f) curveTo(13.0004f, 20.4615f, 13.1704f, 21.0815f, 13.6504f, 21.3515f) lineTo(14.5704f, 21.8815f) curveTo(14.9804f, 22.1315f, 15.5304f, 21.9815f, 15.7704f, 21.5615f) lineTo(15.8304f, 21.4615f) curveTo(16.3104f, 20.6315f, 17.0904f, 20.6315f, 17.5704f, 21.4615f) lineTo(17.6304f, 21.5615f) curveTo(17.8804f, 21.9815f, 18.4204f, 22.1315f, 18.8404f, 21.8815f) lineTo(19.7504f, 21.3515f) curveTo(20.0704f, 21.1715f, 20.2604f, 20.8315f, 20.2604f, 20.4815f) curveTo(20.2604f, 20.3115f, 20.2104f, 20.1415f, 20.1204f, 19.9815f) curveTo(19.9804f, 19.7415f, 19.9204f, 19.5115f, 19.9204f, 19.3115f) curveTo(19.9204f, 18.8115f, 20.3104f, 18.4715f, 20.9904f, 18.4715f) curveTo(21.5504f, 18.4715f, 22.0004f, 18.0215f, 22.0004f, 17.4715f) verticalLineTo(16.5315f) curveTo(22.0004f, 15.9815f, 21.5504f, 15.5315f, 20.9904f, 15.5315f) close() moveTo(16.7004f, 18.7215f) curveTo(15.7504f, 18.7215f, 14.9804f, 17.9515f, 14.9804f, 17.0015f) curveTo(14.9804f, 16.0515f, 15.7504f, 15.2815f, 16.7004f, 15.2815f) curveTo(17.6504f, 15.2815f, 18.4204f, 16.0515f, 18.4204f, 17.0015f) curveTo(18.4204f, 17.9515f, 17.6504f, 18.7215f, 16.7004f, 18.7215f) close() } path(fill = SolidColor(Color(0xFF292D32)), stroke = null, strokeLineWidth = 0.0f, strokeLineCap = Butt, strokeLineJoin = Miter, strokeLineMiter = 4.0f, pathFillType = NonZero) { moveTo(16.25f, 10.02f) verticalLineTo(10.5925f) curveTo(16.25f, 10.9266f, 15.8047f, 11.1384f, 15.48f, 11.06f) curveTo(14.98f, 10.93f, 14.48f, 11.0f, 14.07f, 11.25f) lineTo(13.16f, 11.78f) curveTo(12.53f, 12.13f, 12.14f, 12.8f, 12.14f, 13.52f) curveTo(12.14f, 13.5796f, 12.1425f, 13.6396f, 12.1475f, 13.6996f) curveTo(12.1803f, 14.0858f, 11.9103f, 14.5545f, 11.5593f, 14.7191f) curveTo(11.0767f, 14.9454f, 10.6979f, 15.3577f, 10.5165f, 15.8624f) curveTo(10.4389f, 16.0785f, 10.2496f, 16.25f, 10.02f, 16.25f) curveTo(8.76f, 16.25f, 7.75f, 15.24f, 7.75f, 13.98f) verticalLineTo(10.02f) curveTo(7.75f, 8.76f, 8.76f, 7.75f, 10.02f, 7.75f) horizontalLineTo(13.98f) curveTo(15.24f, 7.75f, 16.25f, 8.76f, 16.25f, 10.02f) close() } } .build() return _cpusetting!! } private var _cpusetting: ImageVector? = null
0
Kotlin
0
2
b8a8231e6637c2008f675ae76a3423b82ee53950
10,260
VuesaxIcons
MIT License
HIGOODS-Api/src/main/kotlin/com/higoods/api/config/jwt/JwtOIDCHelper.kt
higoods-hongik
663,934,695
false
null
package com.higoods.api.config.jwt import com.depromeet.whatnow.config.jwt.OIDCDecodePayload import com.higoods.common.annotation.Helper import com.higoods.common.const.KID import com.higoods.common.exception.custom.InvalidTokenException import io.jsonwebtoken.Claims import io.jsonwebtoken.Header import io.jsonwebtoken.Jws import io.jsonwebtoken.Jwt import io.jsonwebtoken.Jwts import java.math.BigInteger import java.security.Key import java.security.KeyFactory import java.security.spec.RSAPublicKeySpec import java.util.* @Helper class JwtOIDCHelper { fun getKidFromUnsignedTokenHeader(token: String, iss: String, aud: String): String { return getUnsignedTokenClaims(token, iss, aud).header[KID] as String } private fun getUnsignedTokenClaims(token: String, iss: String, aud: String): Jwt<Header<*>, Claims> { return JwtParseExecuter { Jwts.parserBuilder() .requireAudience(aud) .requireIssuer(iss) .build() .parseClaimsJwt(getUnsignedToken(token)) } } private fun getUnsignedToken(token: String): String { val splitToken = token.split("\\.".toRegex()) if (splitToken.size != 3) throw InvalidTokenException.EXCEPTION return splitToken[0] + "." + splitToken[1] + "." } fun getOIDCTokenJws(token: String, modulus: String, exponent: String): Jws<Claims> { return JwsParseExecuter { Jwts.parserBuilder() .setSigningKey(getRSAPublicKey(modulus, exponent)) .build() .parseClaimsJws(token) } } fun getOIDCTokenBody(token: String, modulus: String, exponent: String): OIDCDecodePayload { val body = getOIDCTokenJws(token, modulus, exponent).body return OIDCDecodePayload( body.issuer, body.audience, body.subject ) } private fun getRSAPublicKey(modulus: String, exponent: String): Key { val keyFactory = KeyFactory.getInstance("RSA") val decodeN = Base64.getUrlDecoder().decode(modulus) val decodeE = Base64.getUrlDecoder().decode(exponent) val n = BigInteger(1, decodeN) val e = BigInteger(1, decodeE) val keySpec = RSAPublicKeySpec(n, e) return keyFactory.generatePublic(keySpec) } }
6
Kotlin
0
1
22f2895454eaec7ada1c341e3b9a9371970f09ab
2,354
HIGOODS-Backend
MIT License
mobikulOC/src/main/java/webkul/opencart/mobikul/model/AddToWishlist/AddtoWishlist.kt
fortunedev223
435,488,584
false
{"Kotlin": 1128789, "Java": 655153}
package webkul.opencart.mobikul.model.AddToWishlist /** * Created by manish.choudhary on 2/8/17. */ import com.google.gson.annotations.Expose import com.google.gson.annotations.SerializedName import webkul.opencart.mobikul.model.BaseModel.BaseModel class AddtoWishlist : BaseModel() { @SerializedName("total") @Expose var total: String? = null @SerializedName("wishlist_status") @Expose val status: Boolean? = null }
0
Kotlin
0
0
fe2513dab910dc471810fa37d6c01c848712c295
449
Boutiquey_Android
MIT License
features/core/ui/viewmodel/lib/src/test/java/viewmodel/AbstractBaseViewModelDisposableTest.kt
game-x50
361,364,864
false
null
package viewmodel import com.ruslan.hlushan.core.thread.test.utils.ThreadCheckerStub import com.ruslan.hlushan.core.ui.viewmodel.test.utils.TestBaseViewModelCleanUpRule import com.ruslan.hlushan.third_party.rxjava2.test.utils.TestSchedulerCleanUpRule import io.reactivex.schedulers.TestScheduler import org.junit.Before import org.junit.Rule import viewmodel.stub.BaseViewModelTestImpl abstract class AbstractBaseViewModelDisposableTest { protected lateinit var testScheduler: TestScheduler protected lateinit var viewModel: BaseViewModelTestImpl @Rule @JvmField val testSchedulerCleanUpRule = TestSchedulerCleanUpRule { testScheduler } @Rule @JvmField val baseViewModelCleanUpRule = TestBaseViewModelCleanUpRule { viewModel } @Before fun before() { val threadChecker = ThreadCheckerStub(isNeededThread = true) testScheduler = TestScheduler() viewModel = BaseViewModelTestImpl( threadChecker = threadChecker ) } }
22
Kotlin
0
0
159a035109fab5cf777dd7a60f142a89f441df63
1,013
android_client_app
Apache License 2.0
ui/widget/src/main/kotlin/ru/maksonic/beresta/ui/widget/dialog/BaseDialog.kt
maksonic
580,058,579
false
null
package ru.maksonic.beresta.ui.widget.dialog import androidx.activity.compose.BackHandler import androidx.compose.foundation.background import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.imePadding import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.systemBarsPadding import androidx.compose.runtime.Composable import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.draw.clip import ru.maksonic.beresta.language_engine.shell.provider.text import ru.maksonic.beresta.ui.theme.Theme import ru.maksonic.beresta.ui.theme.color.scrim import ru.maksonic.beresta.ui.theme.color.secondaryContainer import ru.maksonic.beresta.ui.theme.component.Shape import ru.maksonic.beresta.ui.theme.component.dp16 import ru.maksonic.beresta.ui.theme.component.dp32 import ru.maksonic.beresta.ui.widget.button.DialogButton import ru.maksonic.beresta.ui.widget.functional.animation.AnimateFadeInOut import ru.maksonic.beresta.ui.widget.surface.SurfacePro /** * @Author maksonic on 12.07.2023 */ @Composable fun BaseDialog( isVisible: Boolean, modifier: Modifier = Modifier, alignment: Alignment = Alignment.Center, btnTitleCancel: String = text.shared.btnTitleClose, btnTitleAccept: String = text.shared.btnTitleAccept, onCancelClicked: () -> Unit, onAcceptClicked: () -> Unit, content: @Composable () -> Unit ) { if (isVisible) { BackHandler { onCancelClicked() } } AnimateFadeInOut( visible = isVisible, fadeInDuration = Theme.animVelocity.dialogVisibility, fadeOutDuration = Theme.animVelocity.dialogVisibility ) { SurfacePro(color = scrim) { Box(modifier.fillMaxSize(), contentAlignment = alignment) { Column( modifier .systemBarsPadding() .imePadding() .padding(dp32) .clip(Shape.cornerExtra) .background(secondaryContainer) .padding(dp16) ) { content() Row( modifier.padding(top = dp16), horizontalArrangement = Arrangement.spacedBy(dp16) ) { DialogButton( action = onCancelClicked, title = btnTitleCancel, isDismiss = true, modifier = Modifier.weight(1f) ) DialogButton( action = onAcceptClicked, title = btnTitleAccept, isDismiss = false, modifier = Modifier.weight(1f) ) } } } } } }
0
Kotlin
0
0
c54eb2c7e994988cea1d086c134dafb88dc5d390
3,205
Beresta
MIT License
src/main/kotlin/com/skillw/randomitem/internal/type/WeightType.kt
Glom-c
474,664,541
false
{"HTML": 1249224, "Kotlin": 91795, "JavaScript": 26016, "CSS": 21580, "Assembly": 2}
package com.skillw.randomitem.internal.type import com.skillw.pouvoir.util.StringUtils.toList import com.skillw.randomitem.api.variable.type.BaseVariableType import com.skillw.randomitem.util.ListUtils.getMultiple import taboolib.common5.Coerce import taboolib.common5.RandomList import java.util.function.Function import java.util.regex.Pattern val pattern: Pattern = Pattern.compile("(?<weight>([+\\-])?(\\d+(?:(\\.\\d+(%)?)|%)?)(-)?(\\d+(?:(\\.\\d+(%)?)|%)?)?)::(?<value>.*)") object WeightType : BaseVariableType("weight", Function { val data = it.first val context = data["${it.second}-context"] as Map<*, *> val list = data.handle(Coerce.toListOf(context["values"], String::class.java)) val weightRandom = RandomList<String>() for (str in list) { val matcher = pattern.matcher(str) if (matcher.find()) { val weight = Coerce.toInteger(matcher.group("weight")) val value = Coerce.toString(matcher.group("value")) weightRandom.add(value, weight) } } val result = weightRandom.random()!! if (result.contains("\n")) { val strList = result.toList() return@Function strList.getMultiple(data, it.second) } else return@Function result })
0
HTML
0
2
e6714dd0cb17216de38bc37058f768b2aeec5511
1,262
RandomItem-III
MIT License
app/src/main/java/com/example/snapstory/ui/onboarding/OnboardingActivity.kt
syenirasheila
804,532,533
false
{"Kotlin": 96042}
package com.example.snapstory.ui.onboarding import android.animation.AnimatorSet import android.animation.ObjectAnimator import android.content.Intent import android.os.Bundle import android.view.View import androidx.activity.OnBackPressedCallback import androidx.appcompat.app.AppCompatActivity import com.example.snapstory.databinding.ActivityOnboardingBinding import com.example.snapstory.ui.signin.SigninActivity import com.example.snapstory.ui.signup.SignupActivity @Suppress("DEPRECATION") class OnboardingActivity : AppCompatActivity() { private lateinit var binding: ActivityOnboardingBinding override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) binding = ActivityOnboardingBinding.inflate(layoutInflater) setContentView(binding.root) setupAction() playAnimation() } @Deprecated("Deprecated") override fun onBackPressed() { super.onBackPressed() onBackPressedDispatcher.onBackPressed() } private val onBackPressedCallback = object : OnBackPressedCallback(true) { override fun handleOnBackPressed() { finishAffinity() } } override fun onStart() { super.onStart() onBackPressedDispatcher.addCallback(this, onBackPressedCallback) } private fun setupAction() { binding.btnSigninOnboarding.setOnClickListener { val intent = Intent(this, SigninActivity::class.java) startActivity(intent) } binding.btnSignupOnboarding.setOnClickListener { val intent = Intent(this, SignupActivity::class.java) startActivity(intent) } } private fun playAnimation() { ObjectAnimator.ofFloat(binding.ivOnboarding, View.TRANSLATION_X, -30f, 30f).apply { duration = 6000 repeatCount = ObjectAnimator.INFINITE repeatMode = ObjectAnimator.REVERSE }.start() val btnSignin = ObjectAnimator.ofFloat(binding.btnSigninOnboarding, View.ALPHA, 1f).setDuration(100) val btnSignup = ObjectAnimator.ofFloat(binding.btnSignupOnboarding, View.ALPHA, 1f).setDuration(100) val sparkleAccent = ObjectAnimator.ofFloat(binding.ivSparkle, View.ALPHA, 1f).setDuration(100) val highlightAccent = ObjectAnimator.ofFloat(binding.ivHighlight, View.ALPHA, 1f).setDuration(100) val firstTitle = ObjectAnimator.ofFloat(binding.tvTitleOnboardingFirst, View.ALPHA, 1f).setDuration(100) val secondTitle = ObjectAnimator.ofFloat(binding.tvTitleOnboardingSecond, View.ALPHA, 1f).setDuration(100) val thirdTitle = ObjectAnimator.ofFloat(binding.tvTitleOnboardingThird, View.ALPHA, 1f).setDuration(100) val description = ObjectAnimator.ofFloat(binding.tvDescOnboarding, View.ALPHA, 1f).setDuration(100) val accentTogether = AnimatorSet().apply { playTogether(sparkleAccent, highlightAccent) } val btnTogether = AnimatorSet().apply { playTogether(btnSignin, btnSignup) } AnimatorSet().apply { playSequentially( firstTitle, secondTitle, thirdTitle, description, accentTogether, btnTogether) startDelay = 100 }.start() } }
0
Kotlin
0
0
1ace917f6e6dfc5ea19c3092cd4b1cbe7ec49baf
3,360
SnapStory
MIT License
core/android/main/kotlin/com/meowbase/toolkit/data/ColorState.kt
siylt007
336,180,880
true
{"Kotlin": 1405824, "Java": 474434, "Dart": 14190, "HTML": 70}
@file:Suppress("MemberVisibilityCanBePrivate") package com.meowbase.toolkit.data import android.annotation.SuppressLint /* * author: 凛 * date: 2020/10/1 下午16:50 * github: https://github.com/RinOrz * description: Indicates color status */ inline class ColorState(val res: Int?) { companion object { /** When default state */ val Normal = ColorState(null) /** When a view has input focus */ val Focused = ColorState(android.R.attr.state_focused) /** When a view's window has input focus */ val WindowFocused = ColorState(android.R.attr.state_window_focused) /** When a view is enabled */ val Enabled = ColorState(android.R.attr.state_enabled) /** * State identifier indicating that the object may display a check mark. * @see [Checked] for the identifier that indicates * whether it is actually checked */ val Checkable = ColorState(android.R.attr.state_checkable) /** * State identifier indicating that the object is currently checked. * @see [Checkable] for an additional identifier that can indicate * if any object may ever display a check * regardless of whether state_checked is currently set */ val Checked = ColorState(android.R.attr.state_checked) /** When a view (or one of its parents) is currently selected */ val Selected = ColorState(android.R.attr.state_selected) /** When the user is pressing down in a view */ val Pressed = ColorState(android.R.attr.state_pressed) /** * When a view or its parent has been "activated" meaning the user has currently * marked it as being of interest. * * This is an alternative representation of * [Checked] for when the state should be propagated down the view hierarchy */ val Activated = ColorState(android.R.attr.state_activated) /** * When a view or drawable is considered "active" by its host. * * Actual usage may vary between views * consult the host view documentation for details */ val Active = ColorState(android.R.attr.state_active) /** * When a view or drawable is considered "single" by its host. * * Actual usage may vary between views * consult the host view documentation for details */ val Single = ColorState(android.R.attr.state_single) /** * When a view or drawable is in the first position in an ordered set. * * Actual usage may vary between views * consult the host view documentation for details */ val First = ColorState(android.R.attr.state_first) /** * When a view or drawable is in the middle position in an ordered set. * * Actual usage may vary between views * consult the host view documentation for details */ val Middle = ColorState(android.R.attr.state_middle) /** * When a view or drawable is in the last position in an ordered set. * * Actual usage may vary between views * consult the host view documentation for details */ val Last = ColorState(android.R.attr.state_last) /** * Indicating that the Drawable is in a view that is hardware accelerated. * This means that the device can at least render a full-screen scaled * bitmap with one layer of text and bitmaps * composited on top of it at 60fps. * * When this is set the `colorBackgroundCacheHint` will be * ignored even if it specifies a solid color * since that optimization is not needed */ val Accelerated = ColorState(android.R.attr.state_accelerated) /** When a pointer is hovering over the view */ val Hovered = ColorState(android.R.attr.state_hovered) /** * Indicating that the Drawable is in a view * that is capable of accepting a drop of the content * currently being manipulated in a drag-and-drop operation */ val DragCanAccept = ColorState(android.R.attr.state_drag_can_accept) /** * Indicating that a drag operation (for which the Drawable's view is a valid recipient) * is currently positioned over the Drawable */ val DragHovered = ColorState(android.R.attr.state_drag_hovered) } } /** Means this [ColorState] is reversed */ @SuppressLint("UseValueOf") fun ColorState.reversed(): ColorState = ColorState(-res!!)
0
null
0
0
df82f0588beb13fbd22308b3d015852c25781612
4,323
toolkit
Apache License 2.0
5/PR5_3+/app/src/main/java/ru/myitschool/lab23_5_3/SettingsActivity.kt
Purpurum
580,288,282
false
null
package ru.myitschool.PR5_3 import android.content.Context.* import android.content.SharedPreferences import android.hardware.Sensor import android.hardware.SensorEvent import android.hardware.SensorEventListener import android.hardware.SensorManager import android.os.Bundle import android.widget.TextView import androidx.appcompat.app.AppCompatActivity import androidx.core.content.ContextCompat.getSystemService import androidx.preference.PreferenceFragmentCompat import androidx.preference.PreferenceManager import android.content.Context import ru.myitschool.lab23.R var pressureVar = "" var pressureNum = 0.0 fun getPressure(context: Context): Double? { val sensorManager = context.getSystemService(Context.SENSOR_SERVICE) as SensorManager val pressureSensor = sensorManager.getDefaultSensor(Sensor.TYPE_PRESSURE) if (pressureSensor == null) { return 25.0 } val sensorEventListener = object : SensorEventListener { var pressure: Double? = 25.0 override fun onSensorChanged(event: SensorEvent) { if (event.sensor.type == Sensor.TYPE_PRESSURE) { pressure = event.values[0].toDouble() sensorManager.unregisterListener(this) } } override fun onAccuracyChanged(sensor: Sensor, accuracy: Int) { // пустышка, без неё оно жалуется } } sensorManager.registerListener(sensorEventListener, pressureSensor, SensorManager.SENSOR_DELAY_GAME ) Thread.sleep(1000) return sensorEventListener.pressure } class SettingsActivity : AppCompatActivity(), SharedPreferences.OnSharedPreferenceChangeListener { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.settings_activity) if (savedInstanceState == null) { supportFragmentManager .beginTransaction() .replace(R.id.settings, SettingsFragment()) .commit() } supportActionBar?.setDisplayHomeAsUpEnabled(true) val sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this) sharedPreferences.registerOnSharedPreferenceChangeListener(this) } class SettingsFragment : PreferenceFragmentCompat() { override fun onCreatePreferences(savedInstanceState: Bundle?, rootKey: String?) { setPreferencesFromResource(R.xml.root_preferences, rootKey) } } override fun onSharedPreferenceChanged(sharedPreferences: SharedPreferences?, key: String?) { when (key) { "pressure_dropdown" ->{ val pressure_dropdown = sharedPreferences!!.getString("pressure_dropdown", "") if(pressure_dropdown == "гПа"){ pressureVar = "гПа" pressureNum = getPressure(this)?.times(1.00)!! } if(pressure_dropdown == "мм рт. ст."){ pressureVar = "мм рт. ст." pressureNum = getPressure(this)?.times(0.750063755419211)!! } } } } override fun onDestroy() { val sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this) sharedPreferences.unregisterOnSharedPreferenceChangeListener(this) super.onDestroy() } override fun onResume() { super.onResume() PreferenceManager.getDefaultSharedPreferences(this).registerOnSharedPreferenceChangeListener(this) } override fun onPause() { super.onPause() PreferenceManager.getDefaultSharedPreferences(this).unregisterOnSharedPreferenceChangeListener(this) } }
0
Kotlin
0
0
247e216e5e3e33eb0dbb25fc4e1305036df3667e
3,680
MD-NARFU
MIT License
src/jvmMain/kotlin/acidicoala/koalageddon/settings/ui/SettingsScreen.kt
acidicoala
584,899,259
false
null
package acidicoala.koalageddon.settings.ui import acidicoala.koalageddon.BuildConfig import acidicoala.koalageddon.core.model.LangString import acidicoala.koalageddon.core.model.Settings import acidicoala.koalageddon.core.ui.composable.* import acidicoala.koalageddon.core.ui.composition.LocalSettings import acidicoala.koalageddon.core.ui.composition.LocalStrings import acidicoala.koalageddon.core.ui.theme.DefaultContentPadding import acidicoala.koalageddon.core.ui.theme.DefaultMaxWidth import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.widthIn import androidx.compose.material.Divider import androidx.compose.material.icons.Icons import androidx.compose.material.icons.filled.DarkMode import androidx.compose.material.icons.filled.LightMode import androidx.compose.material.icons.filled.Translate import androidx.compose.runtime.Composable import androidx.compose.runtime.collectAsState import androidx.compose.runtime.getValue import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.unit.dp import org.kodein.di.compose.localDI import org.kodein.di.instance @Composable fun SettingsScreen() { val screenModel: SettingsScreenModel by localDI().instance() val state by screenModel.collectAsState() val settings = LocalSettings.current val strings = LocalStrings.current VerticalScrollContainer( contentAlignment = Alignment.TopCenter, ) { Column( modifier = Modifier .widthIn(max = DefaultMaxWidth) .padding(DefaultContentPadding), ) { DropdownOption( label = strings.theme, items = Settings.Theme.values(), selected = settings.theme, onSelect = screenModel::onThemeChanged, icon = when (settings.theme) { Settings.Theme.Dark -> Icons.Default.DarkMode Settings.Theme.Light -> Icons.Default.LightMode } ) DropdownOption( label = strings.language, items = Settings.Language.values(), selected = settings.language, onSelect = screenModel::onLanguageChanged, icon = Icons.Default.Translate ) SwitchOption( label = strings.downloadPreReleaseVersions, checked = settings.downloadPreReleaseVersions, onCheckedChange = screenModel::onDownloadPreReleaseVersionsChanged ) Divider(Modifier.padding(vertical = 8.dp)) ButtonOption( label = "", buttonLabel = strings.openDataDirectory, onClick = screenModel::onOpenDataDirectory ) ButtonOption( label = LangString("%0" to state.cacheSize) { cacheSize }.text, buttonLabel = strings.clearCache, onClick = screenModel::onClearCache ) Divider(Modifier.padding(vertical = 8.dp)) ButtonOption( label = LangString("%0" to BuildConfig.APP_VERSION) { version }.text, buttonLabel = strings.checkForUpdates, onClick = screenModel::onCheckForUpdates ) InfoOption( label = strings.buildTimestamp, info = state.formattedBuildTimestamp, ) } } }
3
Kotlin
21
272
4bb78260cc241069730236ccc130356357ac90e6
3,552
Koalageddon2
The Unlicense
app/src/main/java/com/krutkowski/omvice/KoinModules.kt
konradrutkowski
516,687,523
false
null
package com.krutkowski.omvice import com.krutkowski.omvice.api.networkModule import com.krutkowski.omvice.data.LocalRoomStorage import com.krutkowski.omvice.data.RoomStorage import com.krutkowski.omvice.data.stream.StreamDataSource import com.krutkowski.omvice.data.stream.StreamRepository import com.krutkowski.omvice.data.stream.local.StreamLocal import com.krutkowski.omvice.data.stream.remote.StreamRemote import com.krutkowski.omvice.streams.StreamsViewModel import com.krutkowski.omvice.video.VideoViewModel import org.koin.android.ext.koin.androidApplication import org.koin.androidx.viewmodel.dsl.viewModel import org.koin.dsl.module /** * Created by <NAME> on 21/07/2022 */ class KoinModules { private val viewModelsModule = module { viewModel { StreamsViewModel(get()) } viewModel { VideoViewModel() } } private val repositoriesModule = module { single<StreamDataSource> { val local = StreamLocal(get()) val remote = StreamRemote(get()) StreamRepository(local, remote) } } private val storagesModule = module { single<RoomStorage> { LocalRoomStorage(androidApplication()) } } fun getAllModules() = listOf( storagesModule, networkModule, repositoriesModule, viewModelsModule ) }
0
Kotlin
0
0
c25f2d1c2e109ec69b7365efe066ae732703d705
1,357
omvice
Apache License 2.0
src/main/kotlin/therealfarfetchd/powerline/common/api/block/FluidPipeContainer.kt
Darkstrumn
131,374,601
true
{"Kotlin": 369119, "Assembly": 52301, "Shell": 2306, "GLSL": 1113}
package therealfarfetchd.powerline.common.api.block import net.minecraft.util.EnumFacing import net.minecraftforge.fluids.Fluid import net.minecraftforge.fluids.FluidRegistry import therealfarfetchd.quacklib.common.api.INeighborSupport import therealfarfetchd.quacklib.common.api.extensions.mapWithCopy import therealfarfetchd.quacklib.common.api.util.QNBTCompound class FluidPipeContainer(val ns: INeighborSupport<FluidPipeContainer>) { var fluid: Fluid? = null var amount: Int = 0 var acqAmount: Int = 0 val totalAmount: Int get() = amount + acqAmount var capacity: Int = 500 var pressure: Double = 0.0 fun update() { val neighbors = EnumFacing.VALUES.mapWithCopy(ns::getNeighborAt).filter { it.second != null }.map { it.first to it.second!! }.toMap() val pressureWants = neighbors.mapValues { (_, it) -> (pressure - it.pressure) / (2 * neighbors.size) } amount += acqAmount acqAmount = 0 if (amount == 0) { fluid = null } else if (fluid == null) { amount = 0 acqAmount = 0 } for ((f, n) in neighbors) { val d = pressureWants.getValue(f) n.pressure += d pressure -= d val fluid = this.fluid ?: n.fluid if (fluid != null && this.fluid ?: fluid == n.fluid ?: fluid) { val transferAmtMax = (d * 10).toInt() val transferAmount = maxOf(-1, minOf(transferAmtMax, 1)) * minOf(Math.abs(n.accept(transferAmtMax, fluid, simulate = true)), Math.abs(accept(-transferAmtMax, fluid, simulate = true))) if (transferAmount != 0) { n.accept(transferAmount, fluid, applyPressure = false) accept(-transferAmount, fluid, applyPressure = false) } } } } fun canAccept(amt: Int, fluidIn: Fluid): Boolean { if (fluid == null) { amount = 0 acqAmount = 0 } else if (fluidIn != fluid) return false return totalAmount + amt in 0..capacity } fun accept(amt: Int, fluidIn: Fluid, applyPressure: Boolean = true, simulate: Boolean = false): Int { if (fluid == null) { amount = 0 acqAmount = 0 } else if (fluidIn != fluid) return 0 val accepted = maxOf(-totalAmount, minOf(amt, capacity - totalAmount)) if (!simulate && accepted != 0) { acqAmount += accepted if (fluid == null) fluid = fluidIn if (applyPressure) pressure += accepted / 10.0 } return accepted } fun save(nbt: QNBTCompound) { if (fluid != null) nbt.string["Fluid"] = FluidRegistry.getFluidName(fluid) nbt.int["Amount"] = amount nbt.int["AcqAmt"] = acqAmount nbt.double["Pressure"] = pressure } fun load(nbt: QNBTCompound) { if ("Fluid" in nbt) fluid = FluidRegistry.getFluid(nbt.string["Fluid"]) amount = nbt.int["Amount"] acqAmount = nbt.int["AcqAmt"] pressure = nbt.double["Pressure"] } }
0
Kotlin
0
0
9c5f4d614eb7af91dec06400a658b0c6eb9fb656
2,829
HCTM
MIT License
app/src/main/java/org/task/manager/data/network/model/request/BookRequest.kt
Steampunk1453
279,327,096
false
null
package org.task.manager.data.network.model.request import com.google.gson.annotations.SerializedName import org.task.manager.domain.model.Book data class BookRequest( @SerializedName("id") val id: Long?, @SerializedName("title") val title: String, @SerializedName("author") var author: String, @SerializedName("genre") var genre: String, @SerializedName("editorial") var editorial: String, @SerializedName("editorialUrl") var editorialUrl: String, @SerializedName("bookshop") var bookshop: String, @SerializedName("bookshopUrl") var bookshopUrl: String, @SerializedName("startDate") val startDate: String, @SerializedName("deadline") val deadline: String, @SerializedName("check") val check: Int, @SerializedName("user") val userIdRequest: UserIdRequest? ) fun Book.toRequest(): BookRequest = BookRequest( id, title, author, genre, editorial, editorialUrl, bookshop, bookshopUrl, startDate, deadline, check, user?.toUserIdRequest() )
0
Kotlin
1
9
612c7a0a3c3a86d0a7f185e88273d6cccd991a03
1,052
todo-task-manager-android
Apache License 2.0
compiler-plugin/src/main/kotlin/com/lhwdev/ktui/plugin/compiler/util/irStdlibUtils.kt
ppwasin
328,231,754
true
{"Kotlin": 516602}
package com.lhwdev.ktui.plugin.compiler.util import org.jetbrains.kotlin.ir.util.kotlinPackageFqn fun IrElementScope.irError(message: String) = irCall(irFunctionSymbol(kotlinPackageFqn, "error", 1), valueArguments = listOf(irString(message)))
0
null
0
0
a2559a1c036d72eb2b2a26616bef1df07dcf7671
247
kt-ui
Apache License 2.0
src/cipher/encipher.kt
ginestra
122,474,609
false
null
package cipher /** * Takes a string and rotates each character contained within the English * alphabet to the next character using the offset (must be between 0 and 25). * * @throws IllegalArgumentException if offset is not between 0 and 25 */ fun encipher(str: String, offset: Int): String { // Enforce a range on the offset value if (offset !in 0..25) { throw IllegalArgumentException("offset must be between 0 and 25") } // Get the first Char in the String var char = str.get(0) // Builder for storing the resulting rotated characters val builder = StringBuilder() // Retrieve the Int value of the Char var charI = char.toInt() /* - Int range for capital characters in the English alphabet is [65-90]. - Int range for capital characters in the English alphabet is [97-122]. Source: https://www.cs.cmu.edu/~pattis/15-1XX/common/handouts/ascii.html */ val isCapital = (charI in 65..90) if (isCapital || (charI in 97..122)) { // Rotate the first character using the offset charI -= if (isCapital) 65 else 97 charI = (charI + offset) % 26 charI += if (isCapital) 65 else 97 // Cast the Int value of the resulting rotated character to Char char = charI.toChar() } builder.append(char) if (str.length > 1) { /* Call this function again but drop the first character and append the return to our builder, this will recursively work on each character in turn and build up the final rotated string. */ builder.append(encipher(str.substring(1), offset)) } return builder.toString() }
0
Kotlin
0
1
4cc03407e8c3cd17c2cca390d3bc0d3b2ee9b716
1,703
sdp-cw2
MIT License
src/main/kotlin/bagguley/knes/papu/ChannelNoise.kt
bagguley
669,578,913
false
null
package bagguley.knes.papu class ChannelNoise(val papu: Papu) { var isEnabled:Boolean = false set(value) { field = value if (!value) { lengthCounter = 0 } updateSampleValue() } var envDecayDisable:Boolean = false var envDecayLoopEnable:Boolean = false var lengthCounterEnable:Boolean = false var envReset:Boolean = false var shiftNow: Boolean = false var lengthCounter:Int = 0 var progTimerCount:Int = 0 var progTimerMax:Int = 0 var envDecayRate:Int = 0 var envDecayCounter:Int = 0 var envVolume:Int = 0 var masterVolume:Int = 0 var shiftReg = 1 shl 14 var randomBit:Int = 0 var randomMode:Int = 0 var sampleValue:Int = 0 var accValue:Int = 0 var accCount:Int = 1 var tmp:Int = 0 init { reset() } fun reset() { progTimerCount = 0 progTimerMax = 0 isEnabled = false lengthCounter = 0 lengthCounterEnable = false envDecayDisable = false envDecayLoopEnable = false shiftNow = false envDecayRate = 0 envDecayCounter = 0 envVolume = 0 masterVolume = 0 shiftReg = 1 randomBit = 0 randomMode = 0 sampleValue = 0 tmp = 0 } fun clockLengthCounter() { if (lengthCounterEnable && lengthCounter > 0) { lengthCounter -= 1 if (lengthCounter == 0) { updateSampleValue() } } } fun clockEnvDecay() { if (envReset) { // Reset envelope: envReset = false envDecayCounter = envDecayRate + 1 envVolume = 0xF } else { envDecayCounter -= 1 if (envDecayCounter <= 0) { // Normal handling: envDecayCounter = envDecayRate + 1 if (envVolume > 0) { envVolume -= 1 } else { envVolume = if (envDecayLoopEnable) 0xF else 0 } } } masterVolume = if (envDecayDisable) envDecayRate else envVolume updateSampleValue() } fun updateSampleValue() { if (isEnabled && lengthCounter > 0) { sampleValue = randomBit * masterVolume } } fun writeReg(address:Int, value:Int) { when (address) { 0x400C -> { // Volume/Envelope decay: envDecayDisable = ((value and 0x10) != 0) envDecayRate = value and 0xF envDecayLoopEnable = ((value and 0x20) != 0) lengthCounterEnable = ((value and 0x20) == 0) masterVolume = if (envDecayDisable) envDecayRate else envVolume } 0x400E -> { // Programmable timer: progTimerMax = papu.getNoiseWaveLength(value and 0xF) randomMode = value shr 7 } 0x400F -> { // Length counter lengthCounter = papu.getLengthMax(value and 248) envReset = true } } // Update: //updateSampleValue() } /*fun setEnabled(value:Boolean) { isEnabled = value if (!value) { lengthCounter = 0 } updateSampleValue() }*/ // WB fun getLengthStatus() = if (lengthCounter==0 || !isEnabled) 0 else 1 }
0
Kotlin
0
0
45cd840d014d7474be7959364638bf9221646ba0
3,499
knes
MIT License
src/main/kotlin/org/sonatype/maven/polyglot/kotlin/model/Plugin.kt
slezhnin
74,742,614
false
null
package org.sonatype.maven.polyglot.kotlin.model data class Plugin( val gav: Gav, val extensions: Boolean = false, val executions: Sequence<Execution> = emptySequence(), val dependencies: Sequence<Dependency> = emptySequence(), val inherited: Boolean = true, val configuration: Config? = null )
0
Kotlin
0
0
5eabd5fbedb1a67c1fc6ee6d0b29502ed9fed134
344
polyglot-kotlin
Apache License 2.0
src/main/kotlin/com/hj/leetcode/kotlin/problem931/Solution.kt
hj-core
534,054,064
false
{"Kotlin": 800976}
package com.hj.leetcode.kotlin.problem931 /** * LeetCode page: [931. Minimum Falling Path Sum](https://leetcode.com/problems/minimum-falling-path-sum/description/); */ class Solution { /* Complexity: * Time O(MN) and Space O(N) where M and N are the number of rows and * columns of matrix; */ fun minFallingPathSum(matrix: Array<IntArray>): Int { // dp[c]@r::= the minimum falling path sum to matrix[r][c]; val dp = matrix[0].clone() for (r in 1..<matrix.size) { var leftLastDp = Int.MAX_VALUE for (c in matrix[r].indices) { val result = matrix[r][c] + minOf( leftLastDp, dp[c], dp.getOrElse(c + 1) { Int.MAX_VALUE } ) leftLastDp = dp[c] dp[c] = result } } return dp.min() } }
0
Kotlin
0
2
ffe7cea0e532ecc27682cb534c0a76e2d0bd756d
907
hj-leetcode-kotlin
Apache License 2.0
core/src/main/java/com/github/grishberg/profiler/plugins/stages/methods/StageRelatedToMethods.kt
Grigory-Rylov
256,819,360
false
null
package com.github.grishberg.profiler.plugins.stages.methods import com.github.grishberg.profiler.plugins.stages.Stage /** * @param name - method name * @param index - index of called method [name] */ data class MethodWithIndex( val name: String, val index: Int? = null ) { fun getMethodIndex(): Int { return index ?: 0 } } /** * Represents Application running stage. * Starts after [methods]. */ class StageRelatedToMethods( override val name: String, val methods: List<MethodWithIndex>, val color: String? = null ) : Stage { override fun equals(other: Any?): Boolean { if (other is StageRelatedToMethods) { return name == other.name } return false } override fun toString(): String { return name } }
19
Kotlin
3
97
e0ba609640cea72c301ff1537dc9cdd9b67bfe4c
808
android-methods-profiler
Apache License 2.0
src/main/kotlin/com/fwdekker/randomness/ui/JSpinnerHelper.kt
FWDekker
96,791,256
false
null
package com.fwdekker.randomness.ui import com.fwdekker.randomness.Bundle import javax.swing.JSpinner /** * Binds two spinners that form a range of valid values together. * * This function adds listeners to the spinners so that if one spinner's value is adjusted, the other's value is also * adjusted if not doing so would make the range invalid. Specifically, this function guarantees that the minimum value * never becomes larger than the maximum value, and guarantees that the difference between the minimum and the maximum * never exceeds [maxRange]. * * @param min the [JSpinner] that represents the minimum value * @param max the [JSpinner] that represents the maximum value * @param maxRange the maximum difference between `min` and `max` */ fun bindSpinners(min: JSpinner, max: JSpinner, maxRange: Double? = null) { if (maxRange != null) require(maxRange >= 0) { Bundle("helpers.error.max_range_must_be_positive") } min.addChangeListener { val minValue = (min.value as Number).toDouble() val maxValue = (max.value as Number).toDouble() if (minValue > maxValue) max.value = minValue if (maxRange != null && maxValue - minValue > maxRange) max.value = minValue + maxRange } max.addChangeListener { val minValue = (min.value as Number).toDouble() val maxValue = (max.value as Number).toDouble() if (maxValue < minValue) min.value = maxValue if (maxRange != null && maxValue - minValue > maxRange) min.value = maxValue - maxRange } }
14
Kotlin
7
39
bbeac32f79a2ceff802a87329e712f98ec0b82c1
1,546
intellij-randomness
MIT License
simplified-ui-catalog/src/test/kotlin/org/nypl/simplified/ui/catalog/CatalogBookDetailFragmentTest.kt
NYPL-Simplified
30,199,881
false
{"Kotlin": 2986168, "Java": 384210, "HTML": 109577, "Shell": 3481, "Ruby": 356}
package org.nypl.simplified.ui.catalog import androidx.core.os.bundleOf import androidx.fragment.app.testing.FragmentScenario import androidx.fragment.app.testing.launchFragmentInContainer import androidx.test.espresso.Espresso.onView import androidx.test.espresso.assertion.ViewAssertions.matches import androidx.test.espresso.matcher.ViewMatchers import androidx.test.espresso.matcher.ViewMatchers.withEffectiveVisibility import androidx.test.espresso.matcher.ViewMatchers.withId import androidx.test.espresso.matcher.ViewMatchers.withText import androidx.test.ext.junit.runners.AndroidJUnit4 import io.mockk.MockKAnnotations import io.mockk.every import io.mockk.impl.annotations.MockK import io.mockk.mockkConstructor import io.mockk.mockkObject import org.junit.After import org.junit.Before import org.junit.Test import org.junit.runner.RunWith import org.librarysimplified.services.api.Services import org.nypl.simplified.accounts.api.AccountID import org.nypl.simplified.books.covers.BookCoverProviderType import org.nypl.simplified.buildconfig.api.BuildConfigurationServiceType import org.nypl.simplified.listeners.api.FragmentListenerFinder import org.nypl.simplified.listeners.api.FragmentListenerType import org.nypl.simplified.ui.screen.ScreenSizeInformationType import java.net.URI @RunWith(AndroidJUnit4::class) class CatalogBookDetailFragmentTest { private lateinit var scenario: FragmentScenario<CatalogBookDetailFragment> @MockK private lateinit var mockBookCoversProvider: BookCoverProviderType @MockK private lateinit var mockScreenInformation: ScreenSizeInformationType @MockK private lateinit var mockBuildConfigService: BuildConfigurationServiceType @MockK private lateinit var mockCatalogBorrowViewModel: CatalogBorrowViewModel @MockK private lateinit var mockCatalogBookDetailViewModel: CatalogBookDetailViewModel @MockK private lateinit var mockCatalogBookDetailEventListener: FragmentListenerType<CatalogBookDetailEvent> @Before fun setUp() { MockKAnnotations.init(this, relaxed = true) // Mock service directory to return mocked services mockkObject(Services) every { Services.serviceDirectory().requireService(BookCoverProviderType::class.java) } returns mockBookCoversProvider every { Services.serviceDirectory().requireService(ScreenSizeInformationType::class.java) } returns mockScreenInformation every { Services.serviceDirectory().requireService(BuildConfigurationServiceType::class.java) } returns mockBuildConfigService // Mock ViewModel creation mockkConstructor(CatalogBorrowViewModelFactory::class) every { anyConstructed<CatalogBorrowViewModelFactory>().create(CatalogBorrowViewModel::class.java) } returns mockCatalogBorrowViewModel mockkConstructor(CatalogBookDetailViewModelFactory::class) every { anyConstructed<CatalogBookDetailViewModelFactory>().create(CatalogBookDetailViewModel::class.java) } returns mockCatalogBookDetailViewModel // Mock ListenerFinder rather than traversing upwards towards a stubbed listener "repository" mockkObject(FragmentListenerFinder) every { FragmentListenerFinder.findListener(any(), CatalogBookDetailEvent::class.java) } returns mockCatalogBookDetailEventListener val args = CatalogFeedArguments.CatalogFeedArgumentsRemote( "title", CatalogFeedOwnership.OwnedByAccount(AccountID.generate()), URI.create("feedUri"), false ) val params = CatalogBookDetailFragmentParameters( CatalogTestUtils.buildTestFeedEntryOPDS(), args ) scenario = launchFragmentInContainer( fragmentArgs = bundleOf(CatalogBookDetailFragment.PARAMETERS_ID to params), themeResId = R.style.SimplifiedTheme_NoActionBar ) } @After fun tearDown() { scenario.close() } @Test fun `details show format label when required by build configuration`() { every { mockBuildConfigService.showFormatLabel } returns true scenario.recreate() onView(withId(R.id.bookDetailFormat)).check(matches(withText("eBook"))) } @Test fun `details hides book format label when required by build configuration`() { every { mockBuildConfigService.showFormatLabel } returns false scenario.recreate() onView(withId(R.id.bookDetailFormat)).check(matches(withEffectiveVisibility(ViewMatchers.Visibility.GONE))) } }
109
Kotlin
21
32
781e4e2122f1528253a6cf17931083944f91ceba
4,398
Simplified-Android-Core
Apache License 2.0
proteus-compiler-kotlin/src/main/kotlin/lang/proteus/binding/BoundBreakStatement.kt
julian-hartl
584,782,799
false
null
package lang.proteus.binding internal class BoundBreakStatement: BoundStatement() { }
1
Kotlin
0
0
4ac2a1e2c7867d449de053e1be958c81e619a4f9
87
proteus
MIT License
kotlinflexiblesearch/kotlinsrc/com/github/listemanuel95/flexiblesearch/tests/BasicTests.kt
listemanuel95
678,568,346
false
null
package com.github.listemanuel95.flexiblesearch.tests import com.github.listemanuel95.flexiblesearch.utils.* import de.hybris.platform.core.model.product.UnitModel import kotlin.test.Test import kotlin.test.assertEquals class BasicTests { @Test fun `Simple Query Test`() { val query = buildQuery("${selectFrom(product::class)}") assertEquals(0, query.queryParameters.size, TestUtils.Messages.PARAMS_DONT_MATCH) assertEquals( "SELECT {PK} FROM {Product}", query.query, TestUtils.Messages.QUERY_DOES_NOT_MATCH ) } @Test fun `Simple Fields Query Test`() { val query = buildQuery( "${ selectFieldsFrom( product::class, field(product.CODE, String::class.java), field(product.UNIT, UnitModel::class.java) ) }" ) assertEquals( listOf(String::class.java, UnitModel::class.java), query.getResultClassList(), TestUtils.Messages.SEARCH_RESULTS_DONT_MATCH ) assertEquals(0, query.queryParameters.size, TestUtils.Messages.PARAMS_DONT_MATCH) assertEquals( "SELECT {code}, {unit} FROM {Product}", query.query, TestUtils.Messages.QUERY_DOES_NOT_MATCH ) } @Test fun `Simple Distinct Query Test`() { val query = buildQuery("${selectFrom(product::class, distinct = true)}") assertEquals(0, query.queryParameters.size, TestUtils.Messages.PARAMS_DONT_MATCH) assertEquals( "SELECT DISTINCT {PK} FROM {Product}", query.query, TestUtils.Messages.QUERY_DOES_NOT_MATCH ) } @Test fun `Simple Aliased Query Test`() { val p = alias("p") val query = buildQuery("${selectFrom(product::class `as` p, distinct = true)}") assertEquals(0, query.queryParameters.size, TestUtils.Messages.PARAMS_DONT_MATCH) assertEquals( "SELECT DISTINCT {p:PK} FROM {Product AS p}", query.query, TestUtils.Messages.QUERY_DOES_NOT_MATCH ) } }
0
Kotlin
0
0
f5046118aa84117d1c0e4fdf3a3a92149616f6cc
2,200
kotlinflexiblesearch
MIT License
app/src/main/java/cloud/my_task/mytaskandroid/data/TaskRepository.kt
Hellsos
152,995,590
false
null
package cloud.my_task.mytaskandroid.data class TaskRepository private constructor(private val taskDAO: TaskDAO) { fun addTask(task: Task) { taskDAO.addTask(task) } fun getTasks() = taskDAO.getTasks() fun setCurrentTask(task: Task) { taskDAO.setCurrentTask(task) } fun getCurrentTask() = taskDAO.getCurrentTask() fun clearTasks() = taskDAO.clearTasks() companion object { @Volatile private var instance: TaskRepository? = null fun getInstance(taskDAO: TaskDAO) = instance ?: synchronized(this) { instance ?: TaskRepository(taskDAO).also { instance = it } } } }
0
Kotlin
0
0
3c28c644b737462a8377ce42b4a06a2b60827269
691
my-task-android
MIT License
app/features/chat/src/main/java/com/can_apps/chat/data/MessageDto.kt
Canato
287,899,145
false
null
package com.can_apps.chat.data import java.util.Locale data class NewMessageDto( val text: MessageTextDto, val holder: MessageHolderEnumDto ) data class MessageDto( val id: MessageIdDto, val text: MessageTextDto, val timestamp: MessageTimestampDto, val holder: MessageHolderEnumDto, val hasTail: MessageTailDto ) @JvmInline value class MessageIdDto(val value: Long) @JvmInline value class MessageTextDto(val value: String) @JvmInline value class MessageTimestampDto(val value: Long) @JvmInline value class MessageTailDto(val value: Boolean) enum class MessageHolderEnumDto(val value: String) { MY("my"), OTHER("other"); companion object { fun fromString(string: String): MessageHolderEnumDto? = values().find { string.lowercase(Locale.getDefault()) == it.value } } }
4
Kotlin
2
19
141112bdf6dfe80faf31154b03061ce909d12300
837
showcase
Freetype Project License
app/src/main/java/ru/aasmc/weather/util/BindingAdapter.kt
aasmc
537,532,336
false
{"Kotlin": 115025}
package ru.aasmc.weather.util import android.widget.TextView import androidx.databinding.BindingAdapter import com.github.pwittchen.weathericonview.WeatherIconView import ru.aasmc.weather.R @BindingAdapter("setIcon") fun WeatherIconView.showIcon(condition: String?) { val context = this.context WeatherIconGenerator.getIconResources(context, this, condition) } fun TextView.setTemperature(double: Double, temperatureUnit: String) { val context = this.context if (temperatureUnit == context.getString(R.string.temp_unit_fahrenheit)) { this.text = "${double}${context.resources.getString(R.string.temp_symbol_fahrenheit)}" } else { this.text = "$double${context.resources.getString(R.string.temp_symbol_celsius)}" } }
0
Kotlin
0
0
c362fe35c672a5204b89820875d80310e2563814
766
Weather
MIT License