path
stringlengths
4
280
owner
stringlengths
2
39
repo_id
int64
21.1k
879M
is_fork
bool
2 classes
languages_distribution
stringlengths
13
1.95k
content
stringlengths
7
482k
issues
int64
0
13.9k
main_language
stringclasses
121 values
forks
stringlengths
1
5
stars
int64
0
111k
commit_sha
stringlengths
40
40
size
int64
7
482k
name
stringlengths
1
100
license
stringclasses
93 values
app/src/main/java/kittentrate/game/GameContract.kt
noloman
85,389,125
false
null
package kittentrate.game import android.widget.ViewFlipper import kittentrate.data.repository.model.PhotoEntity import kittentrate.data.viewmodel.NetworkViewState import kittentrate.score.PlayerScore /** * Created by <NAME> on 21/03/2017. */ interface GameContract { interface View { var networkViewState: NetworkViewState fun showLoadingView() fun hideLoadingView() fun turnCardsOver() fun notifyAdapterItemChanged(pos: Int) fun notifyAdapterItemRemoved(id: String) fun setAdapterData(photoEntityList: List<PhotoEntity>) fun removeViewFlipper() fun showErrorView() fun shouldDispatchTouchEvent(): Boolean fun onScoreChanged(gameScore: Int) fun checkGameFinished() } interface Presenter { fun onItemClicked(position: Int, card: Card, viewFlipper: ViewFlipper) fun removeCardsFromMaps() fun start() fun onScoredEntered(playerScore: PlayerScore) fun notifyAdapterItemChanged(key: Int?) fun onTurnCardsOver() fun removeViewFlipper() fun onGameScoreChanged(gameScore: Int) fun notifyAdapterItemRemoved(id: String) fun onKittensMenuItemClicked() fun onPuppiesMenuItemClicked() } }
4
null
1
1
faf94cc9027ea530f7f98f8999fc150320c2f9cd
1,304
kittentrate
Apache License 2.0
android_commons_view/src/main/kotlin/kr/ac/snu/hcil/android/common/view/container/ManualViewPager.kt
yghokim
62,933,149
false
null
package kr.ac.snu.hcil.android.common.view.container import android.content.Context import android.util.AttributeSet import android.view.MotionEvent import android.view.animation.DecelerateInterpolator import android.widget.Scroller import androidx.viewpager.widget.ViewPager /** * Created by <NAME> on 2016-08-31. * * http://stackoverflow.com/questions/9650265/how-do-disable-paging-by-swiping-with-finger-in-viewpager-but-still-be-able-to-s */ class ManualViewPager : ViewPager { constructor(context: Context) : super(context) constructor(context: Context, attrs: AttributeSet?) : super(context, attrs) init { setMyScroller() } override fun onInterceptTouchEvent(event: MotionEvent): Boolean { // Never allow swiping to switch between pages return false } override fun onTouchEvent(event: MotionEvent): Boolean { return false } //down one is added for smooth scrolling private fun setMyScroller() { try { val viewpager = ViewPager::class.java val scroller = viewpager.getDeclaredField("mScroller") scroller.isAccessible = true scroller.set(this, MyScroller(context)) } catch (e: Exception) { e.printStackTrace() } } inner class MyScroller(context: Context) : Scroller(context, DecelerateInterpolator()) { override fun startScroll(startX: Int, startY: Int, dx: Int, dy: Int, duration: Int) { super.startScroll(startX, startY, dx, dy, 250 /*1 secs*/) } } }
9
Kotlin
4
8
f13e5c157d5646c3f9493c4fdc25ed3b1fc2e296
1,567
omnitrack_android
MIT License
stream_component/src/main/java/com/xyoye/stream_component/ui/dialog/FTPLoginDialog.kt
kaedei
395,177,024
false
null
package com.xyoye.stream_component.ui.dialog import android.text.method.HideReturnsTransformationMethod import android.text.method.PasswordTransformationMethod import androidx.core.view.isGone import androidx.lifecycle.MutableLiveData import com.xyoye.common_component.extension.setTextColorRes import com.xyoye.common_component.weight.ToastCenter import com.xyoye.common_component.weight.dialog.BaseBottomDialog import com.xyoye.data_component.entity.MediaLibraryEntity import com.xyoye.data_component.enums.MediaType import com.xyoye.stream_component.R import com.xyoye.stream_component.databinding.DialogFtpLoginBinding import java.nio.charset.Charset /** * Created by xyoye on 2021/1/28. */ class FTPLoginDialog : BaseBottomDialog<DialogFtpLoginBinding> { private var originalStorage: MediaLibraryEntity? = null private lateinit var addMediaStorage: (MediaLibraryEntity) -> Unit private lateinit var testConnect: (MediaLibraryEntity) -> Unit private lateinit var testConnectResult: MutableLiveData<Boolean> private lateinit var binding: DialogFtpLoginBinding constructor() : super() constructor( originalStorage: MediaLibraryEntity?, addMediaStorage: (MediaLibraryEntity) -> Unit, testConnect: (MediaLibraryEntity) -> Unit, testConnectResult: MutableLiveData<Boolean> ) : super(true) { this.originalStorage = originalStorage this.addMediaStorage = addMediaStorage this.testConnect = testConnect this.testConnectResult = testConnectResult } override fun getChildLayoutId() = R.layout.dialog_ftp_login override fun initView(binding: DialogFtpLoginBinding) { this.binding = binding val isEditStorage = originalStorage != null setTitle(if (isEditStorage) "编辑FTP帐号" else "添加FTP帐号") val serverData = originalStorage ?: MediaLibraryEntity( 0, "", "", MediaType.FTP_SERVER, null, null, false, 21 ) binding.serverData = serverData //编辑模式下,选中匿名 if (isEditStorage && originalStorage!!.isAnonymous) { setAnonymous(true) } else { setAnonymous(serverData.isAnonymous) } setActive(serverData.isActiveFTP) binding.serverTestConnectTv.setOnClickListener { if (checkParams(serverData)) { testConnect.invoke(serverData) } } testConnectResult.observe(mOwnerActivity!!, { if (it) { binding.serverStatusTv.text = "连接成功" binding.serverStatusTv.setTextColorRes(R.color.text_blue) } else { binding.serverStatusTv.text = "连接失败" binding.serverStatusTv.setTextColorRes(R.color.text_red) } }) binding.anonymousTv.setOnClickListener { serverData.isAnonymous = true setAnonymous(true) } binding.accountTv.setOnClickListener { serverData.isAnonymous = false setAnonymous(false) } binding.activeTv.setOnClickListener { serverData.isActiveFTP = true setActive(true) } binding.passiveTv.setOnClickListener { serverData.isActiveFTP = false setActive(false) } binding.passwordToggleIv.setOnClickListener { if (binding.passwordToggleIv.isSelected) { binding.passwordToggleIv.isSelected = false binding.passwordEt.transformationMethod = PasswordTransformationMethod.getInstance() } else { binding.passwordToggleIv.isSelected = true binding.passwordEt.transformationMethod = HideReturnsTransformationMethod.getInstance() } } setPositiveListener { if (checkParams(serverData)) { addMediaStorage.invoke(serverData) dismiss() mOwnerActivity?.finish() } } setNegativeListener { dismiss() mOwnerActivity?.finish() } } private fun checkParams(serverData: MediaLibraryEntity): Boolean { if (serverData.ftpAddress.isEmpty()) { ToastCenter.showWarning("请填写FTP地址") return false } if (serverData.ftpEncoding.isEmpty()) { ToastCenter.showWarning("请填写编码格式") return false } if (!Charset.isSupported(serverData.ftpEncoding)) { ToastCenter.showWarning("不支持的编码格式") return false } if (!serverData.isAnonymous) { if (serverData.account.isNullOrEmpty()) { ToastCenter.showWarning("请填写帐号") return false } if (serverData.password.isNullOrEmpty()) { ToastCenter.showWarning("请填写密码") return false } } return true } private fun setAnonymous(isAnonymous: Boolean) { binding.anonymousTv.isSelected = isAnonymous binding.anonymousTv.setTextColorRes( if (isAnonymous) R.color.text_white else R.color.text_black ) binding.accountTv.isSelected = !isAnonymous binding.accountTv.setTextColorRes( if (!isAnonymous) R.color.text_white else R.color.text_black ) binding.accountEt.isGone = isAnonymous binding.passwordEt.isGone = isAnonymous binding.passwordFl.isGone = isAnonymous if (isAnonymous) { binding.accountEt.setText("") binding.passwordEt.setText("") } } private fun setActive(isActive: Boolean) { binding.activeTv.isSelected = isActive binding.activeTv.setTextColorRes( if (isActive) R.color.text_white else R.color.text_black ) binding.passiveTv.isSelected = !isActive binding.passiveTv.setTextColorRes( if (!isActive) R.color.text_white else R.color.text_black ) } }
0
null
1
8
1e2bbe520287c3ebf056ffdb3d00c07edf7946fb
6,163
DanDanPlayForAndroid
Apache License 2.0
src/main/kotlin/name/valery1707/problem/e/olymp/Problem1000K.kt
valery1707
541,970,894
false
{"Java": 144219, "Kotlin": 119280}
package name.valery1707.problem.e.olymp /** * # Задача a + b * * Вычислите сумму `a` + `b`. * * ## Входные данные * * В каждой строке задано два целых числа `a` и `b` (`|a|, |b| ≤ 30000`). * * ## Выходные данные * * Для каждого теста выведите сумму `a + b` в отдельной строке. * * @see <a href="https://www.eolymp.com/ru/problems/1000">Задача a + b</a> */ interface Problem1000K : ProblemConsole { @Suppress("EnumEntryName", "unused") enum class Implementation : Problem1000K { sequence { override fun main(args: Array<String>) { generateSequence(::readlnOrNull) .map { it.splitToSequence(' ').map(String::toInt).reduce(Int::plus) } .forEach(::println) } }, } }
3
null
1
1
55f9cb65499168735277131e2fbe44a918ec86ca
785
problem-solving
MIT License
app/src/main/java/com/jesperqvarfordt/listn/common/view/shuffletogglebutton/ShuffleToggleButtonContract.kt
JesperQv
122,033,035
false
null
package com.jesperqvarfordt.listn.common.view.shuffletogglebutton import com.jesperqvarfordt.listn.common.base.BasePresenter import com.jesperqvarfordt.listn.common.base.BaseView interface ShuffleToggleButtonContract { interface View : BaseView { fun toggleView(shuffling: Boolean) } interface Presenter : BasePresenter<View> { fun shuffleClicked() } }
1
Kotlin
9
97
68b97f2d5437d1bab06df39b9eaf754d7941c520
388
Listn
MIT License
core/src/main/java/com/caseyjbrooks/scorekeeper/core/db/CoreRoomDB.kt
cjbrooks12
115,218,851
false
null
package com.caseyjbrooks.scorekeeper.core.db import android.arch.persistence.room.Database import android.arch.persistence.room.RoomDatabase import com.caseyjbrooks.scorekeeper.core.db.users.* @Database( entities = [ User::class, Game::class, GameUser::class ], version = 2, exportSchema = false ) abstract class CoreRoomDB : RoomDatabase() { abstract fun userDao(): UserDAO abstract fun gameDao(): GameDAO abstract fun gameUserDao(): GameUserDAO }
0
Kotlin
0
0
0801efc7b9a55060f07d7124245a78ccca9f4a55
536
KotlinScoreKeeper
Creative Commons Attribution 3.0 Unported
app/src/main/java/com/faldez/shachi/ui/comment/CommentAdapter.kt
faldez
457,580,136
false
null
package com.faldez.shachi.ui.comment 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.faldez.shachi.databinding.CommentItemBinding import com.faldez.shachi.data.model.Comment class CommentAdapter : ListAdapter<Comment, CommentViewHolder>(COMPARATOR) { override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): CommentViewHolder { val binding = CommentItemBinding.inflate(LayoutInflater.from(parent.context), parent, false) return CommentViewHolder(binding) } override fun onBindViewHolder(holder: CommentViewHolder, position: Int) { val item = getItem(position) holder.bind(item) } companion object { private val COMPARATOR = object : DiffUtil.ItemCallback<Comment>() { override fun areContentsTheSame(oldItem: Comment, newItem: Comment): Boolean = oldItem.id == newItem.id override fun areItemsTheSame(oldItem: Comment, newItem: Comment): Boolean = oldItem == newItem } } } class CommentViewHolder(val binding: CommentItemBinding) : RecyclerView.ViewHolder(binding.root) { fun bind(item: Comment) { binding.creatorTextView.text = item.creator binding.dateTextView.text = item.createdAt?.toString() binding.bodyTextView.text = item.body } }
8
Java
1
20
6491f53f06ae2aeb6cd786fb9f4fe7cb21958540
1,485
shachi
Apache License 2.0
app/src/main/java/com/movie/app/room/entities/MovieGenreJoin.kt
hmedat
129,792,251
false
{"Java": 108682, "Kotlin": 85626}
package com.movie.app.room.entities import android.arch.persistence.room.ColumnInfo import android.arch.persistence.room.Entity import android.arch.persistence.room.ForeignKey import android.arch.persistence.room.Index import com.movie.app.modules.Genre import com.movie.app.modules.Movie @Entity( tableName = "movie_genre_join", primaryKeys = ["movie_id", "genre_id"], foreignKeys = [(ForeignKey( entity = Movie::class, parentColumns = arrayOf("id"), childColumns = arrayOf("movie_id") )), (ForeignKey( entity = Genre::class, parentColumns = arrayOf("id"), childColumns = arrayOf("genre_id") ))], indices = [Index("genre_id")] ) data class MovieGenreJoin( @ColumnInfo(name = "movie_id") var movieId: Long, @ColumnInfo(name = "genre_id") var genreId: Long )
1
null
1
1
6290b3e4d5ed74c98d7e732b4b1339a406cb08e0
820
SampleMovieApp
Apache License 2.0
platform/platform-impl/src/com/intellij/ide/ProtocolHandler.kt
ingokegel
72,937,917
false
null
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. package com.intellij.ide interface ProtocolHandler { companion object { /** * This exit code tells the platform that it shouldn't display the welcome screen, * because the handler wants to take full care of the UI (not applicable if URI is handled by an already running instance). */ const val PLEASE_NO_UI: Int = -1 /** * This exit code tells the platform that it should shut itself down (not applicable if URI is handled by an already running instance). */ const val PLEASE_QUIT: Int = -2 /** * This exit code tells the platform that it should not focus IDE windows, the handler will manage the focus * (applicable only if URI is handled by an already running instance). */ const val PLEASE_DO_NOT_FOCUS: Int = -3 } val scheme: String suspend fun process(query: String): CliResult }
1
null
1
2
b07eabd319ad5b591373d63c8f502761c2b2dfe8
982
intellij-community
Apache License 2.0
app/src/main/kotlin/com/kotlinextension/data/db/DatabaseAnnotation.kt
Krunal-Kevadiya
162,451,184
false
null
package com.kotlinextension.data.db class DatabaseAnnotation { companion object { const val DATABASE_VERSION = 1 const val DATABASE_NAME = "AppDatabase" const val TABLE_USER = "users" const val ID = "id" const val USER_NAME = "username" const val GENDER = "gender" const val EMAIL = "email" const val PASSWORD = "<PASSWORD>" const val DOB = "dob" const val REGISTERED = "registered" const val PHONE = "phone" const val CELL = "cell" const val PICTURE = "picture" const val NAT = "nat" const val TABLE_LOCATION = "locations" const val USER_ID = "user_id" const val STREET = "street" const val CITY = "city" const val STATE = "state" const val POSTCODE = "postcode" } }
0
Kotlin
2
3
6b556c47887cd2ded327783b63a92f76aee5cffc
840
kotlin-extension
Apache License 2.0
idea/idea-gradle/src/org/jetbrains/kotlin/idea/utils.kt
damenez
176,209,431
true
{"Markdown": 56, "Gradle": 497, "Gradle Kotlin DSL": 215, "Java Properties": 12, "Shell": 11, "Ignore List": 10, "Batchfile": 9, "Git Attributes": 1, "Protocol Buffer": 12, "Java": 5238, "Kotlin": 43905, "Proguard": 7, "XML": 1594, "Text": 9172, "JavaScript": 239, "JAR Manifest": 2, "Roff": 209, "Roff Manpage": 34, "INI": 95, "AsciiDoc": 1, "SVG": 30, "HTML": 462, "Groovy": 31, "JSON": 17, "JFlex": 3, "Maven POM": 94, "CSS": 1, "Ant Build System": 50, "C": 1, "ANTLR": 1, "Scala": 1}
/* * Copyright 2010-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license * that can be found in the license/LICENSE.txt file. */ package org.jetbrains.kotlin.idea import com.intellij.openapi.module.Module import com.intellij.openapi.roots.DependencyScope import com.intellij.openapi.roots.ModifiableRootModel fun addModuleDependencyIfNeeded( rootModel: ModifiableRootModel, dependeeModule: Module, testScope: Boolean ) { val dependencyScope = if (testScope) DependencyScope.TEST else DependencyScope.COMPILE val existingEntry = rootModel.findModuleOrderEntry(dependeeModule) if (existingEntry != null) { val existingScope = existingEntry.scope if (existingScope == DependencyScope.COMPILE || existingScope == dependencyScope) return if (dependencyScope == DependencyScope.COMPILE) { rootModel.removeOrderEntry(existingEntry) } } rootModel.addModuleOrderEntry(dependeeModule).also { it.scope = dependencyScope } }
0
Kotlin
0
2
9a2178d96bd736c67ba914b0f595e42d1bba374d
1,025
kotlin
Apache License 2.0
src/test/kotlin/com/leetcode/P560Test.kt
antop-dev
229,558,170
false
{"Maven POM": 1, "Text": 4, "Ignore List": 1, "Markdown": 1, "Java": 233, "Kotlin": 832, "Python": 10}
package com.leetcode import org.hamcrest.MatcherAssert.assertThat import org.hamcrest.Matchers.`is` import org.junit.jupiter.api.Test class P560Test { private val sut = P560() @Test fun `example 01`() { assertThat(sut.subarraySum(intArrayOf(1, 1, 1), 2), `is`(2)) } @Test fun `example 02`() { assertThat(sut.subarraySum(intArrayOf(1, 2, 3), 3), `is`(2)) } @Test fun `example 03`() { assertThat(sut.subarraySum(intArrayOf(1), 1), `is`(1)) } @Test fun `example 04`() { assertThat(sut.subarraySum(intArrayOf(2, 4, 7, 2, -3, 1, 4, 2), 7), `is`(3)) } }
1
Kotlin
0
0
a9dd7cfa4f6cfc5186a86f6e2c8aefc489f5c028
639
algorithm
MIT License
src/main/kotlin/com/github/projectsandstone/api/event/player/PlayerEvent.kt
ProjectSandstone
65,579,594
false
{"Gradle": 4, "XML": 1, "INI": 2, "Markdown": 5, "Shell": 2, "Text": 1, "Ignore List": 1, "Batchfile": 1, "Java": 14, "Kotlin": 192}
/* * SandstoneAPI - Minecraft Server Modding API * * The MIT License (MIT) * * Copyright (c) Sandstone <https://github.com/ProjectSandstone/> * Copyright (c) contributors * * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package com.github.projectsandstone.api.event.player import com.github.projectsandstone.api.entity.living.player.Player import com.github.koresframework.eventsys.event.Event /** * Base extension of all events which has a related player. * * Please note that no one event extend this interface. This interface is dynamically extended * with [Event extension][com.github.koresframework.eventsys.ap.EventExtension]. */ interface PlayerEvent : Event { /** * Player related to event. */ val player: Player }
6
Kotlin
0
2
02d1d0fcc44c8e05741798af5b6f7408ebf48670
1,887
SandstoneAPI
MIT License
TeamCode/src/main/java/org/firstinspires/ftc/teamcode/utilities/BetterCommandOpMode.kt
GoldEnter21
705,399,695
false
{"Java Properties": 2, "Gradle": 6, "Shell": 1, "HTML": 2, "Markdown": 6, "Batchfile": 1, "Text": 4, "Ignore List": 1, "XML": 16, "Java": 96, "Kotlin": 100}
package org.firstinspires.ftc.teamcode.utilities import com.arcrobotics.ftclib.command.* import com.qualcomm.robotcore.eventloop.opmode.LinearOpMode abstract class BetterCommandOpMode: LinearOpMode(){ /** * Cancels all previous commands */ fun reset() { CommandScheduler.getInstance().reset() } /** * Runs the [CommandScheduler] instance */ fun run() { CommandScheduler.getInstance().run() } /** * Schedules [com.arcrobotics.ftclib.command.Command] objects to the scheduler */ fun schedule(vararg commands: Command?) { CommandScheduler.getInstance().schedule(*commands) } /** * Registers [com.arcrobotics.ftclib.command.Subsystem] objects to the scheduler */ fun register(vararg subsystems: Subsystem?) { CommandScheduler.getInstance().registerSubsystem(*subsystems) } @Throws(InterruptedException::class) override fun runOpMode() { initialize() waitForStart() // run the scheduler while (!isStopRequested && opModeIsActive()) { run() } reset() } abstract fun preinit() abstract fun initialize() fun disable() { Robot.disable() } fun enable() { Robot.enable() } }
1
null
1
1
a696b287ee27a77a02288b105f2148c123a6e612
1,310
RoboknightsOffSeasonCopy
BSD 3-Clause Clear License
platforms/android/Dezel/dezel/src/main/java/ca/logaritm/dezel/view/ContentImageView.kt
logaritmdev
174,257,253
false
null
package ca.logaritm.dezel.view import android.content.Context import android.graphics.* import android.util.SizeF import android.view.View import ca.logaritm.dezel.extension.Delegates import ca.logaritm.dezel.extension.ceiled import ca.logaritm.dezel.extension.clamp import ca.logaritm.dezel.view.graphic.Color import ca.logaritm.dezel.view.type.ImageFilter /** * @class ContentImageView * @since 0.1.0 * @hidden */ open class ContentImageView(context: Context) : View(context), Clippable { override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) { super.onMeasure(widthMeasureSpec, heightMeasureSpec) } //-------------------------------------------------------------------------- // Properties //-------------------------------------------------------------------------- /** * The image view's image. * @property image * @since 0.1.0 */ open var image: Bitmap? by Delegates.OnSetOptional<Bitmap>(null) { this.invalidate() } /** * The image view's image top position. * @property imageTop * @since 0.1.0 */ open var imageTop: Float by Delegates.OnSet(0f) { this.invalidate() } /** * The image view's image left position. * @property imageLeft * @since 0.1.0 */ open var imageLeft: Float by Delegates.OnSet(0f) { this.invalidate() } /** * The image view's image width. * @property imageWidth * @since 0.1.0 */ open var imageWidth: Float by Delegates.OnSet(0f) { this.invalidate() } /** * The image view's image height. * @property imageHeight * @since 0.1.0 */ open var imageHeight: Float by Delegates.OnSet(0f) { this.invalidate() } /** * The image view's image filter. * @property imageFilter * @since 0.5.0 */ open var imageFilter: ImageFilter by Delegates.OnSet(ImageFilter.NONE) { this.invalidate() } /** * The image view's image color. * @property imageTint * @since 0.1.0 */ open var imageTint: Int by Delegates.OnSet(Color.TRANSPARENT) { this.invalidate() } /** * @property srcRect * @since 0.1.0 * @hidden */ private var srcRect: Rect = Rect() /** * @property dstRect * @since 0.1.0 * @hidden */ private var dstRect: Rect = Rect() /** * @property paint * @since 0.1.0 * @hidden */ private var paint: Paint = Paint() /** * @property grayscaleColorMatrix * @since 0.1.0 * @hidden */ private val grayscaleColorMatrix: ColorMatrix /** * @property grayscaleColorMatrixFilter * @since 0.1.0 * @hidden */ private val grayscaleColorMatrixFilter: ColorMatrixColorFilter //-------------------------------------------------------------------------- // Methods //-------------------------------------------------------------------------- /** * @constructor * @since 0.1.0 */ init { this.setLayerType(android.view.View.LAYER_TYPE_HARDWARE, null) this.grayscaleColorMatrix = ColorMatrix() this.grayscaleColorMatrix.setSaturation(0f) this.grayscaleColorMatrixFilter = ColorMatrixColorFilter(this.grayscaleColorMatrix) } /** * Measures the natural size of this view. * @method measure * @since 0.1.0 */ open fun measure(bounds: SizeF, min: SizeF, max: SizeF): SizeF { val image = this.image if (image == null) { return SizeF(0f, 0f) } val frameW = bounds.width val frameH = bounds.height val imageW = image.width.toFloat() val imageH = image.height.toFloat() val scaleW = imageW / imageH val scaleH = imageH / imageW if (frameW == 0f && frameH == 0f) { return SizeF(imageW, imageH).clamp(min, max) } if (frameW == 0f) return SizeF(frameH * scaleW, frameH).clamp(min, max) if (frameH == 0f) return SizeF(frameW, frameW * scaleH).clamp(min, max) return bounds.ceiled() } /** * @method onDraw * @since 0.1.0 * @hidden */ override fun onDraw(canvas: Canvas) { val image = this.image if (image == null) { return } val imageT = this.imageTop.toInt() val imageL = this.imageLeft.toInt() val imageW = this.imageWidth.toInt() val imageH = this.imageHeight.toInt() this.srcRect.set(0, 0, image.width, image.height) this.dstRect.set( imageL, imageT, imageL + imageW, imageT + imageH ) val tint = this.imageTint if (tint == Color.TRANSPARENT) { this.paint.colorFilter = null } else { this.paint.colorFilter = PorterDuffColorFilter(tint, PorterDuff.Mode.SRC_IN) } if (this.imageFilter == ImageFilter.GRAYSCALE) { // This is not perfect because it will override the color filter, It would be nice // to be able to apply both this.paint.colorFilter = this.grayscaleColorMatrixFilter } canvas.save() canvas.clipRect(0, 0, this.width, this.height) canvas.drawBitmap( image, this.srcRect, this.dstRect, this.paint ) canvas.restore() } }
6
Kotlin
1
1
507022b806e0ffb91bfe87336c6642634c5123a0
4,778
dezel
MIT License
RxUI/src/main/java/com/tamsiree/rxui/view/colorpicker/slider/AlphaSlider.kt
Tamsiree
69,093,112
false
null
package com.tamsiree.rxui.view.colorpicker.slider import android.content.Context import android.graphics.Canvas import android.graphics.PorterDuff import android.util.AttributeSet import com.tamsiree.rxkit.RxImageTool.getAlphaPercent import com.tamsiree.rxui.view.colorpicker.ColorPickerView import com.tamsiree.rxui.view.colorpicker.builder.PaintBuilder /** * @author tamsiree * @date 2018/6/11 11:36:40 整合修改 */ class AlphaSlider : AbsCustomSlider { var colorS = 0 private val alphaPatternPaint = PaintBuilder.newPaint().build() private val barPaint = PaintBuilder.newPaint().build() private val solid = PaintBuilder.newPaint().build() private val clearingStroke = PaintBuilder.newPaint().color(-0x1).xPerMode(PorterDuff.Mode.CLEAR).build() private var colorPicker: ColorPickerView? = null constructor(context: Context?) : super(context) constructor(context: Context?, attrs: AttributeSet?) : super(context, attrs) constructor(context: Context?, attrs: AttributeSet?, defStyleAttr: Int) : super(context, attrs, defStyleAttr) override fun createBitmaps() { super.createBitmaps() alphaPatternPaint.shader = PaintBuilder.createAlphaPatternShader(barHeight / 2) } override fun drawBar(barCanvas: Canvas) { val width = barCanvas.width val height = barCanvas.height barCanvas.drawRect(0f, 0f, width.toFloat(), height.toFloat(), alphaPatternPaint) val l = Math.max(2, width / 256) var x = 0 while (x <= width) { val alpha = x.toFloat() / (width - 1) barPaint.color = colorS barPaint.alpha = Math.round(alpha * 255) barCanvas.drawRect(x.toFloat(), 0f, x + l.toFloat(), height.toFloat(), barPaint) x += l } } override fun onValueChanged(value: Float) { if (colorPicker != null) { colorPicker!!.setAlphaValue(value) } } override fun drawHandle(canvas: Canvas, x: Float, y: Float) { solid.color = colorS solid.alpha = Math.round(value * 255) canvas.drawCircle(x, y, handleRadius.toFloat(), clearingStroke) if (value < 1) { canvas.drawCircle(x, y, handleRadius * 0.75f, alphaPatternPaint) } canvas.drawCircle(x, y, handleRadius * 0.75f, solid) } fun setColorPicker(colorPicker: ColorPickerView?) { this.colorPicker = colorPicker } fun setColor(color: Int) { this.colorS = color value = getAlphaPercent(color) if (bar != null) { updateBar() invalidate() } } }
70
null
2855
12,025
fa5f88c24594a562c2a9047c40ceeb94de297428
2,627
RxTool
Apache License 2.0
parser_output/Region.kt
Tarik-B
572,524,394
false
{"Kotlin": 188925, "Python": 91692}
package fr.amazer.pokechu.enums /* ************************************************************************** */ /* WARNING! Auto-generated file, all manual changes made will be lost! */ /* ************************************************************************** */ enum class Region { NATIONAL, // 0 KANTO, // 1 KANTO_PE, // 2 JOHTO, // 3 JOHTO_HGSS, // 4 HOENN, // 5 HOENN_ORAS, // 6 SINNOH, // 7 SINNOH_PT, // 8 UNOVA, // 9 UNOVA_B2W2, // 10 KALOS, // 11 ALOLA, // 12 ALOLA_USUM, // 13 GALAR, // 14 ISLE_ARMOR, // 15 CROWN_TUNDRA, // 16 HISUI, // 17 PALDEA, // 18 }
1
Kotlin
0
1
034768c6d702ee55c0faa6d71be8b1f5e555e8ff
687
pokechu
MIT License
app/src/main/java/org/wikipedia/dataclient/wikidata/Search.kt
greatfire
460,298,221
false
null
package org.wikipedia.dataclient.wikidata import kotlinx.serialization.SerialName import kotlinx.serialization.Serializable import org.wikipedia.dataclient.mwapi.MwResponse @Serializable class Search : MwResponse() { @SerialName("search") val results: List<SearchResult> = emptyList() @Serializable class SearchResult { val id: String = "" val label: String = "" val description: String = "" } }
2
null
4
38
8c8de602274b0132fc5d22b394a2c47fcd0bf2eb
444
apps-android-wikipedia-envoy
Apache License 2.0
app/src/main/java/com/example/mywaycompose/presentation/theme/Font.kt
larkes-cyber
739,078,285
false
{"Kotlin": 575045}
package com.example.mywaycompose.presentation.theme import androidx.compose.ui.text.font.Font import androidx.compose.ui.text.font.FontFamily import androidx.compose.ui.text.font.FontWeight import com.example.mywaycompose.R val monsterrat = FontFamily( Font(R.font.monsterbold, FontWeight.Bold), Font(R.font.monsterratsemibold, FontWeight.SemiBold), Font(R.font.monstermedium, FontWeight.Medium), Font(R.font.monsterregular, FontWeight.Normal), Font(R.font.monsterextrabold, FontWeight.ExtraBold) ) val gilory = FontFamily( Font(R.font.giloryregular, FontWeight.Normal), Font(R.font.gilorymedium, FontWeight.Medium), Font(R.font.gilorybold, FontWeight.Bold), Font(R.font.giloryextrabold, FontWeight.ExtraBold) )
0
Kotlin
0
1
81ff3952a4aa8d83269a349ff52f8afb6a1156ff
750
PlannerApp
Apache License 2.0
projetos/aula08-20/app/src/main/java/br/com/koruthos/cursoandroid/network/NetworkManager.kt
chaua
517,803,177
false
null
package br.com.koruthos.cursoandroid.networks import br.com.koruthos.cursoandroid.network.ApiService import okhttp3.OkHttpClient import okhttp3.logging.HttpLoggingInterceptor import retrofit2.Retrofit import retrofit2.converter.gson.GsonConverterFactory // URL do endpoint da API (precisa do / no final) // - ngrok: https://ngrok.com/download private val URL = "https://rickandmortyapi.com/api/" object NetworkManager { lateinit var client: OkHttpClient val service: ApiService by lazy { val interceptor = HttpLoggingInterceptor() interceptor.level = HttpLoggingInterceptor.Level.BODY client = OkHttpClient.Builder().addInterceptor(interceptor).build() val retrofit = Retrofit.Builder() .baseUrl(URL) .client(client) .addConverterFactory(GsonConverterFactory.create()) .build() return@lazy retrofit.create(ApiService::class.java) } fun stop() { client.dispatcher().cancelAll() } }
0
Kotlin
1
2
232d4f85e1ab4ce777f24690dcac906eef53927c
1,006
programacao-mobile
MIT License
app/src/main/java/com/realitix/nectar/repository/ShoppingListRepository.kt
Nectar-Project
247,032,480
false
null
package com.realitix.nectar.repository import android.content.Context import com.realitix.nectar.database.NectarDatabase import com.realitix.nectar.database.entity.* import com.realitix.nectar.util.EntityType import com.realitix.nectar.util.NectarUtil class ShoppingListRepository(val context: Context, updater: EntityUpdaterInterface<ShoppingListRaw> = Updater(context)): GenericGetUuidRepository<ShoppingListRaw, ShoppingList>(updater) { override fun getDao() = NectarDatabase.getInstance(context).shoppingListDao() class Updater(context: Context): GenericEntityUpdater<ShoppingListRaw>(context) { override fun getUuidType(entity: ShoppingListRaw): Pair<String, EntityType> = Pair(entity.uuid, EntityType.SHOPPING_LIST) } }
2
Kotlin
0
0
f220b9007fc5d3faf1d3fd9a842154de2a7d0cdf
752
nectar-android
Apache License 2.0
protocol/osrs-223/src/main/kotlin/net/rsprox/protocol/game/outgoing/decoder/codec/camera/CamTargetDecoder.kt
blurite
822,339,098
false
{"Kotlin": 1453055}
package net.rsprox.protocol.game.outgoing.decoder.codec.camera import net.rsprot.buffer.JagByteBuf import net.rsprot.protocol.ClientProt import net.rsprot.protocol.metadata.Consistent import net.rsprox.protocol.ProxyMessageDecoder import net.rsprox.protocol.game.outgoing.decoder.prot.GameServerProt import net.rsprox.protocol.game.outgoing.model.camera.CamTarget import net.rsprox.protocol.session.Session @Consistent public class CamTargetDecoder : ProxyMessageDecoder<CamTarget> { override val prot: ClientProt = GameServerProt.CAM_TARGET override fun decode( buffer: JagByteBuf, session: Session, ): CamTarget { val type = buffer.g1() val index = buffer.g2() val cameraLockedPlayerIndex = buffer.g2() return CamTarget( when (type) { 0 -> CamTarget.PlayerCamTarget(index) 1 -> CamTarget.NpcCamTarget(index) 2 -> CamTarget.WorldEntityTarget( index, cameraLockedPlayerIndex, ) else -> throw IllegalStateException("Unknown type: $type") }, ) } }
2
Kotlin
4
9
41535908e6ccb633c8f2564e8961efa771abd6de
1,237
rsprox
MIT License
app/src/main/java/com/nikola/jakshic/dagger/stream/Stream.kt
google0593
258,759,268
true
{"Kotlin": 175036}
package com.nikola.jakshic.dagger.stream import com.squareup.moshi.Json import com.squareup.moshi.JsonClass @JsonClass(generateAdapter = true) class StreamBox(@Json(name = "data") val stream: List<Stream>) @JsonClass(generateAdapter = true) data class Stream( @Json(name = "user_name") val userName: String, @Json(name = "title") val title: String, @Json(name = "viewer_count") val viewerCount: Long, @Json(name = "thumbnail_url") val thumbnailUrl: String )
0
null
0
1
6cb7322f77e041745d6b5a3ba702a3685a141704
476
dagger
MIT License
app/src/main/java/com/nide/pocketpass/domain/usecase/SaveNewCategoryUseCase.kt
IamDebashis
536,854,826
false
null
package com.nide.pocketpass.domain.usecase import com.nide.pocketpass.data.module.Category import com.nide.pocketpass.domain.repository.CategoryRepository class SaveNewCategoryUseCase(private val categoryRepository: CategoryRepository) { fun execute(category: Category) { categoryRepository.insertCategory(category) } }
0
Kotlin
0
0
3166737fa1d45beb78a09cd8b4490bd3334cbcd2
340
pocketpass
MIT License
fashion-tryon-compose/src/main/kotlin/com/aiuta/fashionsdk/tryon/compose/ui/internal/screens/onboarding/components/best/BestResultPageContent.kt
aiuta-com
759,918,511
false
{"Kotlin": 674266, "Shell": 1462}
package com.aiuta.fashionsdk.tryon.compose.ui.internal.screens.onboarding.components.best import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.Spacer import androidx.compose.foundation.layout.aspectRatio import androidx.compose.foundation.layout.fillMaxHeight import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.height import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.width import androidx.compose.runtime.Composable import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.unit.dp import com.aiuta.fashionsdk.tryon.compose.ui.internal.controller.composition.LocalAiutaTryOnStringResources import com.aiuta.fashionsdk.tryon.compose.ui.internal.screens.onboarding.components.common.CentredTextBlock import com.aiuta.fashionsdk.tryon.compose.ui.internal.screens.onboarding.controller.state.BestResultPage @Composable internal fun BestResultPageContent( modifier: Modifier = Modifier, state: BestResultPage, ) { val stringResources = LocalAiutaTryOnStringResources.current Column( modifier = modifier, verticalArrangement = Arrangement.spacedBy(6.dp), ) { BestImagesBlock( modifier = Modifier .weight(0.7f) .fillMaxWidth() .padding(horizontal = 32.dp), state = state, ) CentredTextBlock( modifier = Modifier .weight(0.3f) .fillMaxWidth(), title = stringResources.onboardingPageBestResultTopic, subtitle = stringResources.onboardingPageBestResultSubtopic, ) } } @Composable private fun BestImagesBlock( modifier: Modifier = Modifier, state: BestResultPage, ) { val cardModifier = Modifier.fillMaxHeight().aspectRatio(0.55f) Column( modifier = modifier, horizontalAlignment = Alignment.CenterHorizontally, ) { Row( modifier = Modifier.fillMaxWidth().weight(1f), horizontalArrangement = Arrangement.Center, ) { state.goodImages.forEachIndexed { index, image -> BestResultPageItem( modifier = cardModifier, image = image, isGoodImage = true, ) if (index != state.goodImages.lastIndex) { Spacer(Modifier.width(6.dp)) } } } Spacer(Modifier.height(6.dp)) Row( modifier = Modifier.fillMaxWidth().weight(1f), horizontalArrangement = Arrangement.Center, ) { state.badImages.forEachIndexed { index, image -> BestResultPageItem( modifier = cardModifier, image = image, isGoodImage = false, ) if (index != state.goodImages.lastIndex) { Spacer(Modifier.width(6.dp)) } } } } }
6
Kotlin
0
2
6e17d89bf031feff027315f1cc49ed0dd818708e
3,282
android-sdk
Apache License 2.0
core/domain/src/main/java/org/the_chance/honeymart/domain/usecase/UpdateProductDetailsUseCase.kt
TheChance101
647,400,117
false
{"Kotlin": 1218713}
package org.the_chance.honeymart.domain.usecase import org.the_chance.honeymart.domain.repository.HoneyMartRepository import javax.inject.Inject class UpdateProductDetailsUseCase @Inject constructor( private val honeyMartRepository: HoneyMartRepository ) { suspend operator fun invoke( id: Long, name: String, price: Double, description: String ): String { return honeyMartRepository.updateProduct(id, name, price, description) } }
3
Kotlin
7
21
50200e0ec0802cdadc282b09074a19c96df3220c
489
Honey-Mart-Android-Client
Apache License 2.0
injection/src/main/java/com/edreams/android/workshops/kotlin/injection/common/MapperModule.kt
nico-gonzalez
105,786,885
false
null
package com.edreams.android.workshops.kotlin.injection.common import com.edreams.android.workshops.kotlin.data.venues.cache.entity.VenueEntity import com.edreams.android.workshops.kotlin.data.venues.mapper.VenueEntityMapper import com.edreams.android.workshops.kotlin.data.venues.mapper.VenueMapper import com.edreams.android.workshops.kotlin.data.venues.remote.response.VenueResponse import com.edreams.android.workshops.kotlin.domain.mapper.Mapper import com.edreams.android.workshops.kotlin.domain.model.VenueModel import com.edreams.android.workshops.kotlin.presentation.mapper.VenuesUiModelMapper import com.edreams.android.workshops.kotlin.presentation.venues.model.VenueUiModel import dagger.Binds import dagger.Module @Module abstract class MapperModule { @Binds abstract fun bindVenueUiModelMapper( mapper: VenuesUiModelMapper): Mapper<VenueModel, VenueUiModel> @Binds abstract fun bindVenueModelMapper( mapper: VenueMapper): Mapper<VenueResponse, VenueEntity> @Binds abstract fun bindVenueEntityMapper( mapper: VenueEntityMapper): Mapper<VenueEntity, VenueModel> }
1
Kotlin
1
6
4e81ba01ef1a379088cfe2c296be1c4bb336c9b3
1,109
K-Places
Apache License 2.0
app/src/main/java/com/example/homepage/plaza/Adapter/PlazaAdapter.kt
piru72
516,901,454
false
null
package com.example.homepage.plaza.Adapter import android.content.Intent import android.net.Uri import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.Button import android.widget.TextView import androidx.appcompat.app.AppCompatActivity import androidx.recyclerview.widget.RecyclerView import com.example.homepage.R import com.example.homepage.plaza.DialogViewDetails import com.example.homepage.plaza.Model.Announcements class PlazaAdapter : RecyclerView.Adapter<PlazaAdapter.AnnouncementViewHolder>() { private val announcements = ArrayList<Announcements>() // Attaching the layout that will hold the announcements and populate them in the recyclerview override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): AnnouncementViewHolder { val inflater = LayoutInflater.from(parent.context) val view = inflater.inflate(R.layout.card_announcements ,parent, false) return AnnouncementViewHolder(view) } // Attaching the data with the card override fun onBindViewHolder(holder: AnnouncementViewHolder, position: Int) { val currentItem = announcements[position] val context = holder.itemView.context holder.announcersName.text = currentItem.sellersDetails?.split(" ")?.get(1) holder.announcementsTopic.text = currentItem.productAuthor holder.announcementDate.text = currentItem.productName holder.announcementDetails.text = currentItem.productDetails val sellersContactNo = currentItem.sellersDetails?.split(" ")?.get(0) holder.detailsButton.setOnClickListener { v -> val activity = v!!.context as AppCompatActivity val addAnnouncementBottomSheetFragment = DialogViewDetails(currentItem.sellersDetails) addAnnouncementBottomSheetFragment.show(activity.supportFragmentManager, addAnnouncementBottomSheetFragment.tag) } holder.callButton.setOnClickListener { val i = Intent(Intent.ACTION_DIAL, Uri.parse("tel:$sellersContactNo")) context.startActivity(i) } } // Total child override fun getItemCount(): Int { return announcements.size } // Realtime update of the announcements fun updateAnnouncementList(materials: List<Announcements>) { this.announcements.clear() this.announcements.addAll(materials) notifyDataSetChanged() } // Class to hold the items of the card class AnnouncementViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) { val announcersName: TextView = itemView.findViewById(R.id.productNameCard) val announcementsTopic: TextView = itemView.findViewById(R.id.productAuthorNameCard) val announcementDate: TextView = itemView.findViewById(R.id.productCategoryCard) val announcementDetails: TextView= itemView.findViewById(R.id.announcementDetails) val callButton: Button = itemView.findViewById(R.id.callSellerButton) val detailsButton: Button = itemView.findViewById(R.id.showDetailsButton) } }
10
Kotlin
2
8
91bb0273f56ce7784aa07671461924f05a25dc3e
3,113
AUST_buddy
MIT License
korge-core/src@wasmJs/korlibs/io/lang/UTF8.kt
korlibs
80,095,683
false
{"WebAssembly": 14293935, "Kotlin": 9728800, "C": 77092, "C++": 20878, "TypeScript": 12397, "HTML": 6043, "Python": 4296, "Swift": 1371, "JavaScript": 328, "Shell": 254, "CMake": 202, "CSS": 66, "Batchfile": 41}
package korlibs.io.lang import korlibs.memory.* import org.khronos.webgl.* actual val UTF8: Charset = UTC8CharsetBase("UTF-8") /** * This won't support streaming decoding */ val JS_UTF8 = object : UTC8CharsetBase("UTF-8") { val textDecoder: TextDecoder? = try { TextDecoder("utf-8") } catch (e: dynamic) { null } // Do not fail if not supported! val textEncoder: TextEncoder? = try { TextEncoder("utf-8") } catch (e: dynamic) { null } // Do not fail if not supported! override fun decode(out: StringBuilder, src: ByteArray, start: Int, end: Int): Int { if (textDecoder != null) { val srcBuffer = src.unsafeCast<Int8Array>() out.append(textDecoder.decode(Int8Array(srcBuffer.buffer, start, end - start))) } else { super.decode(out, src, start, end) } return end - start } override fun encode(out: ByteArrayBuilder, src: CharSequence, start: Int, end: Int) { if (textEncoder != null) { val ba = textEncoder.encode(src.substring(start, end)) out.append(Int8Array(ba.buffer).unsafeCast<ByteArray>()) } else { super.encode(out, src, start, end) } } }
444
WebAssembly
121
2,207
dc3d2080c6b956d4c06f4bfa90a6c831dbaa983a
1,110
korge
Apache License 2.0
feature/src/main/java/com/example/feature/data/DataProvider.kt
Ahabdelhak
535,852,545
false
{"Kotlin": 113352, "Ruby": 2223}
/* * Copyright 2022 <NAME>. All rights reserved. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.example.feature.data import com.example.feature.R import com.example.feature.data.model.Crypto object DataProvider { val crypto = Crypto( id = 1, title = "Bitcoin", price = "$13131.0", CryptoImageId = R.drawable.ic_launcher_background ) val cryptoList = listOf( crypto, Crypto( id = 2, title = "Ethereum", price = "$13131.0", CryptoImageId = R.drawable.ic_launcher_background ), Crypto( id = 3, title = "BNB", price = "$13131.0", CryptoImageId = R.drawable.ic_launcher_background ), Crypto( id = 4, title = "DeFi", price = "$13131.0", CryptoImageId = R.drawable.ic_launcher_background ), Crypto( id = 5, title = "Binance", price = "$13131.0", CryptoImageId = R.drawable.ic_launcher_background ), Crypto( id = 6, title = "Bitcoin", price = "$13131.0", CryptoImageId = R.drawable.ic_launcher_background ), Crypto( id = 7, title = "DeFi Coin", price = "$13131.0", CryptoImageId = R.drawable.ic_launcher_background ), Crypto( id = 8, title = "Binance", price = "$13131.0", CryptoImageId = R.drawable.ic_launcher_background ), Crypto( id = 9, title = "Bitcoin", price = "$13131.0", CryptoImageId = R.drawable.ic_launcher_background ), Crypto( id = 10, title = "BNB", price = "$13131.0", CryptoImageId = R.drawable.ic_launcher_background ), Crypto( id = 11, title = "USD Coin", price = "$13131.0", CryptoImageId = R.drawable.ic_launcher_background ), Crypto( id = 12, title = "Binance", price = "$13131.0", CryptoImageId = R.drawable.ic_launcher_background ), ) }
0
Kotlin
1
4
1a25d95040f62d956c16088ba72badea52f0f5b6
2,860
InstaCrypto
Apache License 2.0
vector/src/main/java/im/vector/app/features/voicebroadcast/VoiceBroadcastExtensions.kt
watcha-fr
558,303,557
false
null
/* * Copyright (c) 2022 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 im.vector.app.features.voicebroadcast import im.vector.app.features.voicebroadcast.model.VoiceBroadcastChunk import org.matrix.android.sdk.api.session.events.model.Content import org.matrix.android.sdk.api.session.events.model.getRelationContent import org.matrix.android.sdk.api.session.events.model.toModel import org.matrix.android.sdk.api.session.room.model.message.MessageAudioEvent fun MessageAudioEvent?.isVoiceBroadcast() = this?.root?.getClearContent()?.get(VoiceBroadcastConstants.VOICE_BROADCAST_CHUNK_KEY) != null fun MessageAudioEvent.getVoiceBroadcastEventId(): String? = if (isVoiceBroadcast()) root.getRelationContent()?.eventId else null fun MessageAudioEvent.getVoiceBroadcastChunk(): VoiceBroadcastChunk? { @Suppress("UNCHECKED_CAST") return (root.getClearContent()?.get(VoiceBroadcastConstants.VOICE_BROADCAST_CHUNK_KEY) as? Content).toModel<VoiceBroadcastChunk>() } val MessageAudioEvent.sequence: Int? get() = getVoiceBroadcastChunk()?.sequence
41
Kotlin
0
0
4b7f030dfc1adc9524fe39b14c29cc6e533bc713
1,591
watcha-android
Apache License 2.0
build-logic/src/main/kotlin/design/rakuten/rex/icons/svgconverter/SvgConverterResPlugin.kt
EC-Mobile
765,562,331
false
{"Kotlin": 87686}
/* * Copyright 2024 Rakuten Group, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package design.rakuten.rex.icons.svgconverter import com.android.build.api.variant.AndroidComponentsExtension import org.gradle.api.Plugin import org.gradle.api.Project import org.gradle.kotlin.dsl.getByType class SvgConverterResPlugin : Plugin<Project> { override fun apply(target: Project): Unit = with(target) { val task = registerPrepareVectorDrawablesTask(ProjectType.RES) extensions.getByType(AndroidComponentsExtension::class).onVariants { variant -> variant.sources.res?.addGeneratedSourceDirectory(task, PrepareVectorDrawables::dstDir) } } }
0
Kotlin
0
0
8c14a7b54c1110c3c85611e526016d8f9c38a4e2
1,204
rex-icons-android
Apache License 2.0
loader/src/main/java/com/xueqiu/image/loader/transform/BaseTransformer.kt
snowman-team
200,222,108
false
{"Java": 53467, "Kotlin": 53009}
package com.xueqiu.image.loader.transform import android.graphics.Bitmap import com.facebook.cache.common.CacheKey import com.facebook.cache.common.SimpleCacheKey import com.facebook.imagepipeline.request.BasePostprocessor abstract class BaseTransformer : BasePostprocessor() { protected var mCacheKey: CacheKey? = null abstract fun transform(bitmap: Bitmap?) abstract fun getCacheKey(): String override fun process(bitmap: Bitmap?) { transform(bitmap) } override fun getPostprocessorCacheKey(): CacheKey? { if (null == mCacheKey) { mCacheKey = SimpleCacheKey(getCacheKey()) } return mCacheKey } }
1
null
1
1
67b3480d57d21a41a78fc5a5f074b9deefaf2e26
676
ImageLoader
Apache License 2.0
feature-home/src/main/java/com/globant/feature/home/model/PersonModel.kt
johannfjs
716,976,358
false
{"Kotlin": 77752}
package com.globant.feature.home.model import com.globant.domain.model.KnownFor import com.globant.domain.model.Person data class PersonModel( val name: String, val popularity: Double, val profilePath: String, val id: Int, val knownFor: List<KnownForModel>, ) data class KnownForModel( val title: String?, val overview: String, val posterPath: String, val releaseDate: String?, val popularity: Double, ) fun Person.toModel(): PersonModel = PersonModel( name = name, popularity = popularity, profilePath = "https://image.tmdb.org/t/p/w500/$profilePath", id = id, knownFor = knownFor.map { it.toModel() }, ) fun KnownFor.toModel(): KnownForModel = KnownForModel( title = title, overview = overview, posterPath = "https://image.tmdb.org/t/p/w500/$posterPath", releaseDate = releaseDate, popularity = popularity, )
0
Kotlin
0
0
37729c911f39a355f8d0724e6a62de0f958b113e
952
MovieDbChallenge
Apache License 2.0
csstype-kotlin/src/jsMain/kotlin/web/cssom/PaddingBlockStart.kt
karakum-team
393,199,102
false
{"Kotlin": 6272741}
// Automatically generated - do not modify! package web.cssom typealias PaddingBlockStart = LengthProperty
0
Kotlin
8
36
95b065622a9445caf058ad2581f4c91f9e2b0d91
109
types-kotlin
Apache License 2.0
foundation/featuretoggles/datasource-overrides/src/main/kotlin/ru/pixnews/foundation/featuretoggles/datasource/overrides/OverridesDataSource.kt
illarionov
305,333,284
false
{"Kotlin": 1309325, "FreeMarker": 2734, "Shell": 855, "Fluent": 72}
/* * Copyright (c) 2023, the Pixnews project authors and contributors. Please see the AUTHORS file for details. * Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. */ package ru.pixnews.foundation.featuretoggles.datasource.overrides import android.content.Context import androidx.datastore.core.DataStore import arrow.core.Either import arrow.core.flatMap import arrow.core.left import arrow.core.right import co.touchlab.kermit.Logger import kotlinx.coroutines.CoroutineDispatcher import kotlinx.coroutines.CoroutineExceptionHandler import kotlinx.coroutines.CoroutineName import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Job import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.SharingStarted import kotlinx.coroutines.flow.StateFlow import kotlinx.coroutines.flow.first import kotlinx.coroutines.flow.flowOn import kotlinx.coroutines.flow.map import kotlinx.coroutines.flow.stateIn import kotlinx.coroutines.launch import ru.pixnews.foundation.featuretoggles.ExperimentKey import ru.pixnews.foundation.featuretoggles.ExperimentVariant import ru.pixnews.foundation.featuretoggles.ExperimentVariantSerializer import ru.pixnews.foundation.featuretoggles.FeatureToggleException import ru.pixnews.foundation.featuretoggles.internal.DataSourceResult import ru.pixnews.foundation.featuretoggles.internal.FeatureToggleDataSource import ru.pixnews.foundation.featuretoggles.internal.FeatureToggleDataSourceError import ru.pixnews.foundation.featuretoggles.internal.FeatureToggleDataSourceError.DataSourceError import ru.pixnews.foundation.featuretoggles.internal.FeatureToggleDataSourceError.ExperimentNotFound import ru.pixnews.library.coroutines.asRequestStatus import ru.pixnews.library.coroutines.newChildSupervisorScope import ru.pixnews.library.functional.RequestStatus import ru.pixnews.library.functional.RequestStatus.Loading import ru.pixnews.library.functional.completeFailure import ru.pixnews.library.functional.mapComplete @Suppress("MaxLineLength") public class OverridesDataSource constructor( private val dataStore: DataStore<Overrides>, private val serializers: Map<ExperimentKey, ExperimentVariantSerializer>, rootCoroutineScope: CoroutineScope, private val backgroundDispatcher: CoroutineDispatcher, logger: Logger, ) : FeatureToggleDataSource { private val log = logger.withTag(TAG) private val exceptionHandler = CoroutineExceptionHandler { _, throwable -> log.e(throwable) { "Unhandled coroutine exception in $TAG" } } private val scope: CoroutineScope = rootCoroutineScope.newChildSupervisorScope( backgroundDispatcher + exceptionHandler + CoroutineName("$TAG scope"), ) private val overridesFlow: StateFlow<RequestStatus<Throwable, Overrides>> = dataStore.data .asRequestStatus() .stateIn( scope = scope, started = SharingStarted.Eagerly, initialValue = Loading, ) private val initJob: Job = scope.launch { val result = overridesFlow .first { status -> status != Loading } log.v { "Initialization complete. Status: $result" } } public constructor( context: Context, serializers: Map<ExperimentKey, ExperimentVariantSerializer>, rootCoroutineScope: CoroutineScope, backgroundDispatcher: CoroutineDispatcher, logger: Logger, ) : this( context.applicationContext.overridesDataStore, serializers, rootCoroutineScope, backgroundDispatcher, logger, ) override fun getAssignedVariant(experimentKey: ExperimentKey): Flow<DataSourceResult<ExperimentVariant>> { return overridesFlow.map { loadingOrComplete -> loadingOrComplete.mapComplete { result: Either<Throwable, Overrides> -> result .mapLeft(::DataSourceError) .flatMap { overrides -> deserializeVariant(overrides, experimentKey) } } } } public fun getOverrides(): Flow<RequestStatus<Throwable, Map<ExperimentKey, ExperimentVariant>>> { return overridesFlow.map { loadingOrComplete -> loadingOrComplete.mapComplete { result: Either<Throwable, Overrides> -> result.flatMap { overrides -> Either.catch { overrides.deserialize() } } } }.flowOn(backgroundDispatcher) } private fun deserializeVariant( overrides: Overrides, experimentKey: ExperimentKey, ): Either<FeatureToggleDataSourceError, ExperimentVariant> { val variant = overrides.toggles[experimentKey.stringValue] ?: return ExperimentNotFound.completeFailure() return try { variant.deserialize(experimentKey).right() } catch (toggleException: FeatureToggleException) { DataSourceError(toggleException).left() } } private fun Overrides.deserialize(): Map<ExperimentKey, ExperimentVariant> { return this.toggles .map { (key, value) -> val experimentKey = ExperimentKey(key) experimentKey to value.deserialize(experimentKey) } .toMap() } private fun VariantPayload.deserialize(experimentKey: ExperimentKey): ExperimentVariant { return serializers[experimentKey]?.fromString(experimentKey, this.payload) ?: throw FeatureToggleException("No serializer for experiment `$experimentKey` found") } public suspend fun setOverride(experimentKey: ExperimentKey, variant: ExperimentVariant?) { dataStore.updateData { overrides -> if (variant != null) { val payload: String = serializers[experimentKey]?.toString(experimentKey, variant) ?: throw FeatureToggleException("No serializer for experiment `$experimentKey` found") overrides.copy( toggles = overrides.toggles + (experimentKey.stringValue to VariantPayload(payload)), ) } else { overrides.copy( toggles = overrides.toggles - experimentKey.stringValue, ) } } } public suspend fun clearOverrides() { dataStore.updateData { Overrides() } } override suspend fun awaitUntilInitialized() { initJob.join() } private companion object { private const val TAG: String = "OverridesDataSource" } }
0
Kotlin
0
2
8912bf1116dd9fe94d110162ff9a302e93af1509
6,600
Pixnews
Apache License 2.0
platform/src/test/kotlin/com/samsung/healthcare/platform/adapter/persistence/project/task/ItemDatabaseAdapterTest.kt
S-HealthStack
520,365,362
false
null
package com.samsung.healthcare.platform.adapter.persistence.project.task import com.samsung.healthcare.platform.NEGATIVE_TEST import com.samsung.healthcare.platform.adapter.persistence.entity.project.task.ItemEntity import io.mockk.coEvery import io.mockk.mockk import kotlinx.coroutines.flow.flowOf import kotlinx.coroutines.flow.toList import kotlinx.coroutines.test.runTest import org.junit.jupiter.api.Tag import org.junit.jupiter.api.Test import org.junit.jupiter.api.assertThrows @kotlinx.coroutines.ExperimentalCoroutinesApi internal class ItemDatabaseAdapterTest { private val itemRepository = mockk<ItemRepository>() private val itemDatabaseAdapter = ItemDatabaseAdapter(itemRepository) @Test @Tag(NEGATIVE_TEST) fun `findByRevisionIdAndTaskId should raise error with wrong task type`() = runTest { coEvery { itemRepository.findByRevisionIdAndTaskId(any(), any()) } returns flowOf( ItemEntity( id = null, revisionId = 1, taskId = "uuid", name = "name", contents = emptyMap(), type = "WRONG_TYPE", sequence = 1, ) ) assertThrows<IllegalArgumentException> { itemDatabaseAdapter.findByRevisionIdAndTaskId(0, "taskId").toList() } } }
2
Kotlin
2
7
8600eaa7c1d10734a0c90fe396eaf42ffdc10e73
1,330
backend-system
Apache License 2.0
src/commonMain/kotlin/choliver/nespot/nes/VideoSink.kt
oliver-charlesworth
251,006,755
false
null
package choliver.nespot.nes interface VideoSink { enum class ColorPackingMode( val convert: (Rgb) -> List<Int> // Output is big-endian ) { BGRA({ listOf(it.b, it.g, it.r, 255) }), ABGR({ listOf(255, it.b, it.g, it.r) }) } data class Rgb( val r: Int, val g: Int, val b: Int ) val colorPackingMode: ColorPackingMode get() = ColorPackingMode.ABGR // Don't care fun put(color: Int) {} }
14
Kotlin
0
1
e5d251b82e11f2986e8a732d55298c2ab0de3191
426
nespot
MIT License
sample/src/main/java/com/drake/brv/sample/ui/fragment/home/GameFragment.kt
liangjingkanji
206,460,689
false
null
package com.drake.brv.sample.ui.fragment.home import com.drake.brv.sample.R import com.drake.brv.sample.constants.Api import com.drake.brv.sample.databinding.FragmentGameBinding import com.drake.brv.sample.model.GameModel import com.drake.brv.utils.dividerSpace import com.drake.brv.utils.setup import com.drake.engine.base.EngineFragment import com.drake.engine.utils.dp import com.drake.net.Get import com.drake.net.utils.TipUtils.toast import com.drake.net.utils.scope import com.drake.serialize.intent.bundle import java.util.* class GameFragment : EngineFragment<FragmentGameBinding>(R.layout.fragment_game) { private val categoryId: Long by bundle() override fun initView() { binding.rv.dividerSpace(10.dp).setup { addType<GameModel.Data>(R.layout.item_game) R.id.item.onClick { toast("点击: 游戏详情(${getModel<GameModel.Data>().name})") } } } override fun initData() { binding.page.onRefresh { scope { val res = Get<GameModel>(Api.GAME) { param("categoryId", categoryId) }.await() addData(res.list.shuffled(Random(categoryId))) { // shuffled() 为随机打乱列表顺序 itemCount < res.total } } }.showLoading() } }
18
null
327
2,576
7120b68fd39f5b88b9ac4316b31a9311ccaf3e49
1,338
BRV
MIT License
src/main/kotlin/network/handler/GroupMessagesHandler.kt
KatiumDev
488,028,614
false
null
/* * Copyright 2022 Katium 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 katium.client.qq.network.handler import katium.client.qq.network.event.QQPacketReceivedEvent import katium.client.qq.network.event.QQReceivedRawMessageEvent import katium.client.qq.network.packet.chat.PushGroupMessagesPacket import katium.core.util.event.Subscribe import katium.core.util.event.post import java.util.* object GroupMessagesHandler : QQClientHandler { override val id: String get() = "group_messages_handler" @Subscribe suspend fun onPacket(event: QQPacketReceivedEvent) { val (_, client, packet) = event if (packet is PushGroupMessagesPacket) { val response = packet.response val message = response.message val groupCode = message.header.groupInfo!! .groupCode client.getGroups()[groupCode]!!.lastReadSequence.set(message.header.sequence.toLong()) client.synchronzier.recordUnreadGroupMessage(groupCode) client.bot.post(QQReceivedRawMessageEvent(client, message)) } } }
0
Kotlin
0
6
996181191d9a01fd58c0cee055e582d173f6b6d9
1,607
katium-client-tencent-qq
Apache License 2.0
app/src/main/java/com/example/weatherapp/extension/ViewExtensions.kt
jhwsx
178,877,854
false
{"Kotlin": 33040}
package com.example.weatherapp.extension import android.content.Context import android.view.View import android.widget.TextView /** * * @author wzc * @date 2019\4\3 */ // 扩展属性的用法:必须定义 get() 方法。 val View.ctx: Context get() = context var TextView.textColor: Int get() = currentTextColor set(value) { setTextColor(value) } fun View.slideExit() { if (translationY == 0F) animate().translationY(-height.toFloat()) } fun View.slideEnter() { if (translationY < 0f) animate().translationY(0f) }
0
Kotlin
0
0
6b9924a63b7abc315c96641d83c5779f9ea6a69a
528
WeatherApp
MIT License
presentation/src/commonMain/kotlin/kosh/presentation/transaction/rememberNextNonce.kt
niallkh
855,100,709
false
{"Kotlin": 1942525, "Swift": 25802}
package kosh.presentation.transaction import androidx.compose.runtime.Composable import kosh.domain.failure.Web3Failure import kosh.domain.models.Address import kosh.domain.models.ChainId import kosh.domain.repositories.TransactionRepo import kosh.presentation.core.di import kosh.presentation.rememberLoad @Composable fun rememberNextNonce( chainId: ChainId, account: Address, transactionRepo: TransactionRepo = di { appRepositoriesComponent.transactionRepo }, ): NextNonceState { val nonce = rememberLoad(chainId, account) { transactionRepo.nextNonce(chainId, account) } return NextNonceState( nonce = nonce.result?.getOrNull(), loading = nonce.loading, failure = nonce.result?.leftOrNull(), retry = { nonce() } ) } data class NextNonceState( val nonce: ULong?, val loading: Boolean, val failure: Web3Failure?, val retry: () -> Unit, )
0
Kotlin
0
3
c08a9f32c0f12bf01eeb366c471b079923ac73ff
926
kosh
MIT License
geotabdrivesdk/src/main/java/com/geotab/mobile/sdk/module/appearance/AppearanceAdapter.kt
Geotab
333,267,573
false
{"Kotlin": 387965, "JavaScript": 23897}
package com.geotab.mobile.sdk.module.appearance import com.geotab.mobile.sdk.models.enums.AppearanceType interface AppearanceAdapter { fun startMonitoringAppearance(onAppearanceChange: (result: AppearanceType) -> Unit) fun stopMonitoringAppearance() }
1
Kotlin
2
2
9d2b6363c999fde1064f315479b69e450e637a30
262
mobile-sdk-android
MIT License
src/day4.kts
AfzalivE
317,962,201
false
null
println("Start") val requiredFields = listOf("byr", "iyr", "eyr", "hgt", "hcl", "ecl", "pid") val input = readInput("day4.txt").readText() val validNum = input.split("\n\n") .asSequence() .map { passport -> val fullString = passport.replace("\n", " ") return@map if (requiredFields.all { fullString.contains(it) }) { fullString } else { null } } .filter { it != null && Passport.fromString(it).isValid() } .toList() .size println("$validNum valid passports") data class Passport( val byr: Int, val iyr: Int, val eyr: Int, val hgt: String, val hcl: String, val ecl: String, val pid: String, val cid: Int? ) { private val eyeColors = listOf("amb", "blu", "brn", "gry", "grn", "hzl", "oth") fun isValid(): Boolean { return byr in 1920..2002 && iyr in 2010..2020 && eyr in 2020..2030 && isValidHeight() && hcl.matches(Regex("#[0-9a-f]{6}")) && ecl in eyeColors && pid.length == 9 } private fun isValidHeight(): Boolean { return when { hgt.matches(Regex("\\d{3}cm")) -> hgt.substring(0, 3).toInt() in 150..193 hgt.matches(Regex("\\d{2}in")) -> hgt.substring(0, 2).toInt() in 59..76 else -> false } } companion object { fun fromString(str: String): Passport { val propMap = str.trim().split(" ").map { val (key, value) = it.split(":") return@map (key to value) }.toMap() return Passport( propMap["byr"]!!.toInt(), propMap["iyr"]!!.toInt(), propMap["eyr"]!!.toInt(), propMap["hgt"]!!, propMap["hcl"]!!, propMap["ecl"]!!, propMap["pid"]!!, propMap["cid"]?.toInt(), ) } } }
0
Kotlin
0
0
cc5998bfcaadc99e933fb80961be9a20541e105d
2,049
AdventOfCode2020
Apache License 2.0
mui-icons-kotlin/src/jsMain/kotlin/mui/icons/material/CommentsDisabledRounded.kt
karakum-team
387,062,541
false
{"Kotlin": 3079611, "TypeScript": 2249, "HTML": 724, "CSS": 86}
// Automatically generated - do not modify! @file:JsModule("@mui/icons-material/CommentsDisabledRounded") package mui.icons.material @JsName("default") external val CommentsDisabledRounded: SvgIconComponent
0
Kotlin
5
35
60404a8933357df15ecfd8caf6e83258962ca909
210
mui-kotlin
Apache License 2.0
multisrc/overrides/animestream/animetitans/src/AnimeTitans.kt
aniyomiorg
360,630,872
false
{"Kotlin": 4099794}
package eu.kanade.tachiyomi.animeextension.ar.animetitans import eu.kanade.tachiyomi.animeextension.ar.animetitans.extractors.AnimeTitansExtractor import eu.kanade.tachiyomi.animeextension.ar.animetitans.extractors.SharedExtractor import eu.kanade.tachiyomi.animeextension.ar.animetitans.extractors.VidYardExtractor import eu.kanade.tachiyomi.animesource.model.SAnime import eu.kanade.tachiyomi.animesource.model.Video import eu.kanade.tachiyomi.lib.gdriveplayerextractor.GdrivePlayerExtractor import eu.kanade.tachiyomi.lib.mp4uploadextractor.Mp4uploadExtractor import eu.kanade.tachiyomi.lib.vidbomextractor.VidBomExtractor import eu.kanade.tachiyomi.multisrc.animestream.AnimeStream import java.text.SimpleDateFormat import java.util.Locale class AnimeTitans : AnimeStream( "ar", "AnimeTitans", "https://animetitans.com", ) { override val dateFormatter by lazy { SimpleDateFormat("MMMM d, yyyy", Locale("ar")) } // =========================== Anime Details ============================ override val animeArtistText = "الاستديو" override val animeStatusText = "الحالة" override val animeAuthorText = "المخرج" override val animeAltNamePrefix = " :أسماء أخرى" override fun parseStatus(statusString: String?): Int { return when (statusString?.trim()?.lowercase()) { "مكتمل" -> SAnime.COMPLETED "مستمر", "publishing" -> SAnime.ONGOING else -> SAnime.UNKNOWN } } // ============================== Episodes ============================== override val episodePrefix = "الحلقة" // ============================ Video Links ============================= override val prefQualityValues = arrayOf("1080p", "720p", "480p", "360p", "Mp4Upload", "4shared") override val prefQualityEntries = prefQualityValues override val prefQualityDefault = "1080p" override val videoSortPrefDefault = prefQualityDefault override fun getVideoList(url: String, name: String): List<Video> { val vidbomDomains = listOf( "vidbom.com", "vidbem.com", "vidbm.com", "vedpom.com", "vedbom.com", "vedbom.org", "vadbom.com", "vidbam.org", "myviid.com", "myviid.net", "myvid.com", "vidshare.com", "vedsharr.com", "vedshar.com", "vedshare.com", "vadshar.com", "vidshar.org", ) return when { baseUrl in url -> AnimeTitansExtractor(client).videosFromUrl(url, headers, baseUrl) vidbomDomains.any(url::contains) -> VidBomExtractor(client).videosFromUrl(url) "vidyard" in url -> VidYardExtractor(client).videosFromUrl(url, headers) "mp4upload" in url -> Mp4uploadExtractor(client).videosFromUrl(url, headers) "4shared" in url -> SharedExtractor(client).videoFromUrl(url, name) ?.let(::listOf) ?: emptyList() "drive.google" in url -> { val gdriveUrl = "https://gdriveplayer.to/embed2.php?link=$url" GdrivePlayerExtractor(client).videosFromUrl(gdriveUrl, name, headers) } else -> emptyList() } } }
375
Kotlin
138
342
e4eb7cdf6379102c903338402d2b8b96b42d3fa7
3,243
aniyomi-extensions
Apache License 2.0
0984.String Without AAA or BBB.kt
sarvex
842,260,390
false
{"Kotlin": 1775678, "PowerShell": 418}
internal class Solution { fun strWithout3a3b(a: Int, b: Int): String { var a = a var b = b val ans = StringBuilder() while (a > 0 && b > 0) { if (a > b) { ans.append("aab") a -= 2 b -= 1 } else if (a < b) { ans.append("bba") a -= 1 b -= 2 } else { ans.append("ab") --a --b } } if (a > 0) { ans.append("a".repeat(a)) } if (b > 0) { ans.append("b".repeat(b)) } return ans.toString() } }
0
Kotlin
0
0
17a80985d970c8316fb694e4952692e598d700af
537
kotlin-leetcode
MIT License
ledger/src/main/kotlin/org/knowledger/ledger/adapters/AdapterCollection.kt
fakecoinbase
282,563,487
false
null
package org.knowledger.ledger.adapters import org.knowledger.ledger.core.adapters.AbstractStorageAdapter import org.knowledger.ledger.data.LedgerData import org.knowledger.ledger.data.adapters.PhysicalDataStorageAdapter import org.knowledger.ledger.database.adapters.SchemaProvider import org.knowledger.ledger.service.adapters.ChainHandleStorageAdapter import org.knowledger.ledger.service.adapters.PoolTransactionStorageAdapter import org.knowledger.ledger.service.adapters.TransactionPoolStorageAdapter import org.knowledger.ledger.service.adapters.TransactionWithBlockHashStorageLoadable import org.knowledger.ledger.storage.adapters.BlockHeaderStorageAdapter import org.knowledger.ledger.storage.adapters.BlockStorageAdapter import org.knowledger.ledger.storage.adapters.CoinbaseStorageAdapter import org.knowledger.ledger.storage.adapters.MerkleTreeStorageAdapter import org.knowledger.ledger.storage.adapters.TransactionOutputStorageAdapter import org.knowledger.ledger.storage.adapters.TransactionStorageAdapter import org.knowledger.ledger.storage.adapters.WitnessStorageAdapter internal interface AdapterCollection { //Storage Adapters val blockStorageAdapter: BlockStorageAdapter val blockHeaderStorageAdapter: BlockHeaderStorageAdapter val coinbaseStorageAdapter: CoinbaseStorageAdapter val merkleTreeStorageAdapter: MerkleTreeStorageAdapter val physicalDataStorageAdapter: PhysicalDataStorageAdapter val transactionStorageAdapter: TransactionStorageAdapter val transactionOutputStorageAdapter: TransactionOutputStorageAdapter val transactionWithBlockHashStorageLoadable: TransactionWithBlockHashStorageLoadable val witnessStorageAdapter: WitnessStorageAdapter //Service Adapters val poolTransactionStorageAdapter: PoolTransactionStorageAdapter val transactionPoolStorageAdapter: TransactionPoolStorageAdapter val chainHandleStorageAdapter: ChainHandleStorageAdapter //Data Adapters val dataAdapters: Set<AbstractStorageAdapter<out LedgerData>> val defaultSchemas: MutableSet<SchemaProvider> val allSchemaProviders: Set<SchemaProvider> get() = defaultSchemas + dataAdapters }
0
Kotlin
0
0
8bc64987e1ab4d26663064da06393de6befc30ae
2,173
SeriyinslashKnowLedger
MIT License
src/jvmMain/kotlin/org/hildan/chrome/devtools/domains/page/PageExtensionsJvm.kt
joffrey-bion
304,337,222
false
{"Kotlin": 162062, "HTML": 933}
package org.hildan.chrome.devtools.domains.page import java.nio.file.Path import kotlin.io.path.writeBytes /** * Captures a screenshot of the current page based on the given [options], and stores the resulting image into a new * file at the given [outputImagePath]. If the file already exists, it is overwritten. */ suspend fun PageDomain.captureScreenshotToFile( outputImagePath: Path, options: CaptureScreenshotRequest.Builder.() -> Unit = {}, ) { val capture = captureScreenshot(options) val imageBytes = capture.decodeData() outputImagePath.writeBytes(imageBytes) }
5
Kotlin
8
45
e21a3901ce344cf7f8b1e69756ee298f47d308e2
595
chrome-devtools-kotlin
MIT License
app/src/main/kotlin/com/juniperphoton/myersplash/activity/EditActivity.kt
JuniperPhoton
67,424,471
false
null
package com.juniperphoton.myersplash.activity import android.animation.ValueAnimator import android.annotation.SuppressLint import android.app.WallpaperManager import android.content.Intent import android.graphics.* import android.graphics.drawable.Animatable import android.net.Uri import android.os.Bundle import android.view.View import android.view.animation.LinearInterpolator import android.widget.SeekBar import androidx.annotation.WorkerThread import androidx.appcompat.app.AlertDialog import androidx.core.content.FileProvider import com.facebook.drawee.backends.pipeline.Fresco import com.facebook.drawee.backends.pipeline.PipelineDraweeController import com.facebook.imagepipeline.common.ResizeOptions import com.facebook.imagepipeline.image.ImageInfo import com.facebook.imagepipeline.request.ImageRequestBuilder import com.juniperphoton.flipperlayout.FlipperLayout import com.juniperphoton.myersplash.App import com.juniperphoton.myersplash.R import com.juniperphoton.myersplash.di.AppComponent import com.juniperphoton.myersplash.extension.getScreenHeight import com.juniperphoton.myersplash.extension.updateIndex import com.juniperphoton.myersplash.utils.* import kotlinx.android.synthetic.main.activity_edit.* import kotlinx.coroutines.* import java.io.File import java.io.FileOutputStream import kotlin.math.max class EditActivity : BaseActivity(), CoroutineScope by MainScope() { companion object { private const val TAG = "EditActivity" private const val SAVED_FILE_NAME = "final_dim_image.jpg" } private var fileUri: Uri? = null private var showingPreview: Boolean = false set(value) { field = value homePreview.alpha = if (value) 1f else 0f } override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_edit) loadImage() initView() editConfirmFab.setOnClickListener(this) editPreviewFab.setOnClickListener(this) handleIntent(intent) updateStatusBar(false) } override fun onNewIntent(intent: Intent?) { super.onNewIntent(intent) this.intent = intent Pasteur.info(TAG, "on new intent") loadImage() handleIntent(intent) } private fun handleIntent(intent: Intent?) { intent ?: return val id = intent.getIntExtra(NotificationUtils.EXTRA_NOTIFICATION_ID, Int.MIN_VALUE) if (id != Int.MIN_VALUE) { NotificationUtils.cancelNotification(id) } } override fun onResume() { super.onResume() // Reset to the initial state anyway flipperLayout.updateIndex(0) } override fun onClickView(v: View) { when (v.id) { R.id.editConfirmFab -> { onClickConfirm() } R.id.editPreviewFab -> { onClickPreview() } } } private fun onClickConfirm() { AppComponent.instance.analysisHelper.logApplyEdit(brightnessSeekBar.progress > 0) composeMask() } private fun onClickPreview() { if (!showingPreview) { AppComponent.instance.analysisHelper.logEditShowPreview() } showingPreview = !showingPreview } private fun loadImage() { previewImageView.post { updatePreviewImage() } } private fun initView() { brightnessSeekBar.setOnSeekBarChangeListener(object : SimpleOnSeekBarChangeListener() { override fun onProgressChanged(seekBar: SeekBar, progress: Int, fromUser: Boolean) { maskView.alpha = progress * 1f / 100 } }) val valueAnimator = ValueAnimator.ofFloat(0f, 360f) valueAnimator.addUpdateListener { animation -> progressView.rotation = animation.animatedValue as Float } valueAnimator.interpolator = LinearInterpolator() valueAnimator.duration = 1200 valueAnimator.repeatMode = ValueAnimator.RESTART valueAnimator.repeatCount = ValueAnimator.INFINITE valueAnimator.start() } private fun updatePreviewImage() { var width = previewImageView.width var height = previewImageView.height if (width == 0) { width = previewImageView.measuredWidth } if (height == 0) { height = previewImageView.measuredHeight } if (width == 0 || height == 0) { return } fileUri = intent.getParcelableExtra(Intent.EXTRA_STREAM) as? Uri ?: intent.data val resize = max(width, height) val request = ImageRequestBuilder.newBuilderWithSource(fileUri) .setResizeOptions(ResizeOptions(resize, resize)) .build() val controller = Fresco.newDraweeControllerBuilder() .setOldController(previewImageView.controller) .setImageRequest(request) .setControllerListener(object : SimpleControllerListener() { override fun onFinalImageSet( id: String?, imageInfo: ImageInfo?, animatable: Animatable? ) { val rect = RectF() previewImageView.hierarchy.getActualImageBounds(rect) previewDraweeLayout.updateContentScale(rect) } }) .build() as PipelineDraweeController previewImageView.controller = controller } private fun setAsWallpaper(file: File) { Pasteur.d(TAG, "set as, file path:${file.absolutePath}") val uri = FileProvider.getUriForFile( App.instance, App.instance.getString(R.string.authorities), file, file.name ) try { val intent = IntentUtils.getSetAsWallpaperIntent(uri) startActivity(intent) } catch (e: IllegalArgumentException) { Pasteur.w(TAG, "error on setting wallpaper by intent $e, uri $uri") setAsWallpaperByFallback(file) } } private fun setAsWallpaperByFallback(file: File) = launch { val dialog = AlertDialog.Builder(this@EditActivity) .setMessage(getString(R.string.setting_wallpaper)) .create() dialog.show() try { val bm = withContext(Dispatchers.IO) { Uri.fromFile(file).getBitmap() } ?: return@launch WallpaperManager.getInstance(this@EditActivity).setBitmap(bm) } finally { dialog.dismiss() } } private fun Uri.getBitmap(): Bitmap? { return try { contentResolver.openInputStream(this)?.use { BitmapFactory.decodeStream(it) } } catch (e: Exception) { null } } private fun composeMask() = launch { flipperLayout.next() val file = withContext(Dispatchers.IO) { composeMaskInternal() } ?: run { flipperLayout.next() return@launch } delay(FlipperLayout.DEFAULT_DURATION_MILLIS * 2) flipperLayout.next() delay(FlipperLayout.DEFAULT_DURATION_MILLIS * 3) setAsWallpaper(file) } override fun onApplySystemInsets(top: Int, bottom: Int) { bottomBar.setPadding(0, 0, 0, bottomBar.paddingBottom + bottom) } override fun onDestroy() { super.onDestroy() cancel() } @SuppressLint("WrongThread") @WorkerThread private fun composeMaskInternal(): File? { fileUri ?: return null val opt = BitmapFactory.Options() opt.inJustDecodeBounds = true // First decode bounds to get width and height val inputStream = contentResolver.openInputStream(fileUri!!) inputStream.use { BitmapFactory.decodeStream(inputStream, null, opt) } val originalHeight = opt.outHeight val screenHeight = getScreenHeight() opt.inSampleSize = originalHeight / screenHeight opt.inJustDecodeBounds = false opt.inMutable = true // Decode file with specified sample size val bm = decodeBitmapFromFile(fileUri, opt) ?: throw IllegalStateException("Can't decode file") Pasteur.d( TAG, "file decoded, sample size:${opt.inSampleSize}, " + "originalHeight=$originalHeight, screenH=$screenHeight" ) Pasteur.d(TAG, "decoded size: ${bm.width} x ${bm.height}") val c = Canvas(bm) val paint = Paint() paint.isDither = true val alpha = maskView.alpha paint.color = Color.argb((255 * alpha).toInt(), 0, 0, 0) paint.style = Paint.Style.FILL // Draw the mask c.drawRect(0f, 0f, bm.width.toFloat(), bm.height.toFloat(), paint) Pasteur.d(TAG, "final bitmap drawn") val finalFile = File(FileUtils.downloadOutputDir, SAVED_FILE_NAME) val fos = FileOutputStream(finalFile) fos.use { bm.compress(Bitmap.CompressFormat.JPEG, 100, it) } bm.recycle() inputStream?.close() return finalFile } private fun decodeBitmapFromFile(fileUri: Uri?, opt: BitmapFactory.Options?): Bitmap? { fileUri ?: return null val inputStream = contentResolver.openInputStream(fileUri) var bm: Bitmap? inputStream.use { bm = BitmapFactory.decodeStream(inputStream, null, opt) } return bm } }
27
Kotlin
23
93
d2e6da91c20b638445c60b089e9aa789c646d22b
9,617
MyerSplash.Android
MIT License
gui/src/main/kotlin/org/goo/controllers/CurrenSessionMemoryWrapper.kt
kostya05983
186,656,239
false
null
package org.goo.controllers import org.goo.debugger.Debugger import org.goo.interpreter.Interpreter import org.goo.view.Editor import java.io.PipedOutputStream class CurrentSessionMemoryWrapper(val editor: Editor, val outputStrategy: OutputToConsoleWindow) { var out: PipedOutputStream? = null val currentStopPoints = mutableListOf<Int>() var debugger: Debugger? = null var interpreter: Interpreter? = null var debuggerThread: Thread? = null var interpreterThread: Thread? = null }
0
Kotlin
0
0
bf945ed8c88627ef0183144a9734826b8cfca457
541
GooTest
MIT License
test/com/shopping/service/JWTAuthServiceTest.kt
alialbaali
285,645,104
false
{"Kotlin": 224319}
package com.shopping.service import com.shopping.* import com.shopping.domain.dto.customer.request.SignInRequest import com.shopping.domain.dto.customer.request.SignUpRequest import com.shopping.domain.service.AuthService import io.kotest.assertions.throwables.shouldNotThrowAny import io.kotest.assertions.throwables.shouldThrow import io.kotest.assertions.throwables.shouldThrowAny import io.kotest.matchers.nulls.shouldNotBeNull import io.kotest.matchers.string.shouldNotBeEmpty import org.koin.test.inject class JWTAuthServiceTest : DefaultSpec(testServiceModule, helperModule, fakeRepositoryModule) { private val authService by inject<AuthService>() init { Given("a valid sign up request") { When("calling auth service sign up method") { Then("it should return a token response with a valid access and refresh token") { val tokenResponse = authService.signUpTestCustomer() tokenResponse.shouldNotBeNull() tokenResponse.accessToken.shouldNotBeEmpty() tokenResponse.refreshToken.shouldNotBeEmpty() } } } Given("an invalid sign up request") { When("calling auth service sign up method") { Then("it should throw an API Error exception") { shouldThrow<APIError> { authService.signUpTestCustomer(name = "John", email = "<EMAIL>", password = "<PASSWORD>") } } } } Given("a valid sign in request") { When("calling auth service sign in method") { Then("it should return a token response with a valid access and refresh token") { shouldNotThrowAny { authService.signUpTestCustomer(email = "<EMAIL>") } val signInRequest = SignInRequest( "<EMAIL>", "<PASSWORD>" ) val tokenResponse = authService.signIn(signInRequest) tokenResponse.shouldNotBeNull() tokenResponse.accessToken.shouldNotBeEmpty() tokenResponse.refreshToken.shouldNotBeEmpty() } } } Given("an invalid sign in request") { When("calling auth service sign in method") { Then("it should throw an API Error exception") { val signInRequest = SignInRequest( "<EMAIL>", "pass" ) shouldThrow<APIError> { authService.signIn(signInRequest) } } } } Given("a two customers with the same email") { When("calling auth service sign up method on each of them") { Then("it should throw an Authentication Error exception") { authService.signUpTestCustomer(email = "<EMAIL>") shouldThrowAny { authService.signUpTestCustomer(email = "<EMAIL>") } } } } Given("a new customer") { When("calling auth service sign in method") { Then("it should throw an Authentication Error exception") { val signInRequest = SignInRequest( "<EMAIL>", "<PASSWORD>" ) shouldThrowAny { authService.signIn(signInRequest) } } } } Given("a valid Id") { When("calling auth service refresh token method") { Then("it should return a Token Response with access and refresh tokens") { val response = authService.signUpTestCustomer(email = "<EMAIL>") val tokenResponse = authService.refreshToken(response.customerId) tokenResponse.shouldNotBeNull() tokenResponse.accessToken.shouldNotBeEmpty() tokenResponse.refreshToken.shouldNotBeEmpty() } } } Given("an invalid Id") { When("calling auth service refresh token method") { Then("it should throw an Authentication Error exception") { val id = "3232-43209423-43242-3223" shouldThrowAny { authService.refreshToken(id) } } } } } }
0
Kotlin
0
1
e8d003386bfff065c9a775b4a808c2d7dd9acd87
4,704
Shopally
Apache License 2.0
home/src/main/java/com/poke/montty/home/ui/model/pokemon/list/PokemonListUI.kt
EmmanuelMontt
794,394,638
false
{"Kotlin": 45452}
package com.poke.montty.home.ui.model.pokemon.list data class PokemonListUI( val count: Int, val next: String? = null, val previous: String? = null, val results: List<PokemonListItemUI> )
0
Kotlin
0
0
e1deb42609212827949ecf48f7f27098f13882dd
205
poke-home
Apache License 2.0
app/src/main/java/com/syleiman/myfootprints/presentationLayer/activities/createAndEdit/editFootprintActivity/IEditFootprintActivityPresenterExt.kt
AlShevelev
116,675,999
false
null
package com.syleiman.myfootprints.presentationLayer.activities.createAndEdit.editFootprintActivity import com.syleiman.myfootprints.common.files.IFileSingleOperation /** * EditFootprintActivityPresenter interface for other presenters */ interface IEditFootprintActivityPresenterExt { /** Show photos grid */ fun switchToPhotoGrid() /** Show second step - create fragment */ fun switchToEditStepPhotoFromPhotoGrid() /** Switch to map */ fun switchToEditStepMapFromPhoto() /** Switch to photo */ fun switchToEditStepPhotoFromMap() /** * Finish activity * @param saved true if footprint was saved */ fun close(saved: Boolean) /** Show Photo editor */ fun showEditPhotoActivity(photo: IFileSingleOperation) /** Update photo after edit by EditPhotoActivity */ fun updatePhotoAfterEdit(photo: IFileSingleOperation) }
1
null
1
2
11a243900f3a33b4b3aab358d4a2b08f9759dd8e
897
MyFootprints
MIT License
src/main/kotlin/br/com/zup/edu/keymanager/register/NewPixKey.kt
gabrielBrandaoZp
407,622,233
true
{"Kotlin": 66381, "Dockerfile": 163}
package br.com.zup.edu.keymanager.register import br.com.zup.edu.shared.validation.ValidPixKey import br.com.zup.edu.shared.validation.ValidUUID import io.micronaut.core.annotation.Introspected import java.util.* import javax.validation.Valid import javax.validation.constraints.NotBlank import javax.validation.constraints.NotNull import javax.validation.constraints.Size @ValidPixKey @Introspected data class NewPixKey( @field:ValidUUID @field:NotBlank val userId: String?, @field:NotNull val pixType: PixType?, @field:Size(max = 77) val pixId: String?, @field:NotNull val accountType: AccountType?, ) { fun toModel(account: Account): Pix { return Pix( pixId = if (this.pixType == PixType.CHAVE_ALEATORIA) "" else this.pixId!!, userId = UUID.fromString(this.userId), pixType = PixType.valueOf(this.pixType!!.name), accountType = AccountType.valueOf(accountType!!.name), account = account ) } }
0
Kotlin
1
0
8eacd111c45dd665cdce7910a73c4cfc1dcd7e0e
1,023
orange-talents-07-template-pix-keymanager-grpc
Apache License 2.0
cinescout/database/src/commonMain/kotlin/cinescout/database/adapter/TmdbAuthStateValueAdapter.kt
4face-studi0
280,630,732
false
null
package cinescout.database.adapter import app.cash.sqldelight.ColumnAdapter import cinescout.database.model.DatabaseTmdbAuthStateValue val TmdbAuthStateValueAdapter = object : ColumnAdapter<DatabaseTmdbAuthStateValue, String> { override fun decode(databaseValue: String): DatabaseTmdbAuthStateValue = DatabaseTmdbAuthStateValue.values().first { it.name.lowercase() == databaseValue } override fun encode(value: DatabaseTmdbAuthStateValue) = value.name.lowercase() }
19
Kotlin
2
3
d64398507d60a20a445db1451bdd8be23d65c9aa
485
CineScout
Apache License 2.0
module_first/src/main/java/com/aleyn/module_first/ui/ResultActivity.kt
aleyn97
676,459,265
false
{"Kotlin": 120849, "Java": 2660}
package com.aleyn.module_first.ui import android.annotation.SuppressLint import android.content.Intent import androidx.appcompat.app.AppCompatActivity import android.os.Bundle import android.view.View import com.aleyn.annotation.Route import com.aleyn.module_first.R @Route("/First/ActivityLaunch") class ResultActivity : AppCompatActivity() { @SuppressLint("MissingInflatedId") override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_result) findViewById<View>(R.id.btn_back).setOnClickListener { val intent = Intent() intent.putExtra("Result", "Back Success") setResult(RESULT_OK, intent) finish() } } }
2
Kotlin
3
41
6d71b13d4bed4399bb398c7b97b83090fff6bb1e
766
router
Apache License 2.0
feature/episodes/src/main/kotlin/app/rickandmorty/episodes/navigation/EpisodesNavigation.kt
simonlebras
628,022,976
false
null
package app.rickandmorty.episodes.navigation import androidx.navigation.NavGraphBuilder import androidx.navigation.NavHostController import androidx.navigation.NavOptionsBuilder import androidx.navigation.compose.composable import app.rickandmorty.episodes.details.EpisodeDetailsScreen import app.rickandmorty.episodes.list.EpisodeListScreen import com.microsoft.device.dualscreen.twopanelayout.Screen import com.microsoft.device.dualscreen.twopanelayout.TwoPaneNavScope import com.microsoft.device.dualscreen.twopanelayout.twopanelayoutnav.composable as twopanelayoutComposable public const val episodeListRoute: String = "episodeList" private const val episodeDetailsRoute = "episodeDetails" public fun NavHostController.navigateToEpisodeList(builder: NavOptionsBuilder.() -> Unit = {}) { navigate( route = episodeListRoute, builder = builder, ) } context(TwoPaneNavScope) public fun NavHostController.navigateToEpisodeDetails( launchScreen: Screen, builder: NavOptionsBuilder.() -> Unit = {}, ) { navigateTo( route = episodeDetailsRoute, launchScreen = launchScreen, builder = builder, ) } public fun NavGraphBuilder.episodeList() { composable(route = episodeListRoute) { EpisodeListScreen() } } public fun NavGraphBuilder.episodeDetails() { twopanelayoutComposable(route = episodeDetailsRoute) { EpisodeDetailsScreen() } }
2
Kotlin
0
0
e99d940482cf1a2678d8748938f3810d917ce0b0
1,429
rickandmorty
MIT License
app/src/main/java/com/anna/mindhealth/data/model/TherapistProfile.kt
AnnaL001
440,538,513
false
{"Kotlin": 142965}
package com.anna.mindhealth.data.model import android.os.Parcelable import kotlinx.parcelize.Parcelize @Parcelize data class TherapistProfile( var short_desc: String = "", var country: String = "", var gender: String = "", var concerns: ArrayList<String> = arrayListOf(), var helping_approach: String = "", var services_provided: ArrayList<String> = arrayListOf(), var working_ages: HashMap<String, Boolean> = hashMapOf(), var languages: HashMap<String, Boolean> = hashMapOf(), var office_address: String = "" ): Parcelable
0
Kotlin
0
0
32de5de74002717d1a7337ccbc03eb5929d8f28c
561
aad-practice-project-mindhealth
The Unlicense
RetenoSdkPush/src/test/java/com/reteno/push/interceptor/click/IntentHandlerTest.kt
reteno-com
545,381,514
false
{"Kotlin": 1360551, "Java": 159640, "HTML": 17807, "Shell": 379}
package com.reteno.push.interceptor.click import android.content.Context import android.content.Intent import android.content.pm.ActivityInfo import android.content.pm.ResolveInfo import android.net.Uri import android.os.Bundle import com.reteno.core.util.getResolveInfoList import com.reteno.push.Constants.KEY_ES_LINK_UNWRAPPED import com.reteno.push.Constants.KEY_ES_LINK_WRAPPED import com.reteno.push.base.robolectric.BaseRobolectricTest import io.mockk.every import io.mockk.mockk import io.mockk.mockkStatic import io.mockk.unmockkStatic import junit.framework.TestCase import junit.framework.TestCase.* import org.junit.AfterClass import org.junit.BeforeClass import org.junit.Test import org.robolectric.Shadows import org.robolectric.annotation.Config @Config(sdk = [26]) class IntentHandlerTest : BaseRobolectricTest() { // region constants ---------------------------------------------------------------------------- companion object { private const val DEEPLINK_WRAPPED = "https://wrapped.com" private const val DEEPLINK_UNWRAPPED = "https://unwrapped.com" @JvmStatic @BeforeClass fun beforeClass() { mockkStatic(Context::getResolveInfoList) } @JvmStatic @AfterClass fun afterClass() { unmockkStatic(Context::getResolveInfoList) } } // endregion constants ------------------------------------------------------------------------- @Test fun givenUnwrappedDeeplink_whenGetDeeplinkIntent_thenAppLaunchIntentWithUnwrappedDeeplinkReturned() { // Given val bundle = Bundle().apply { putString(KEY_ES_LINK_WRAPPED, DEEPLINK_WRAPPED) putString(KEY_ES_LINK_UNWRAPPED, DEEPLINK_UNWRAPPED) } val expectedIntent = Intent(Intent.ACTION_VIEW, Uri.parse(DEEPLINK_UNWRAPPED)).apply { putExtras(bundle) flags = Intent.FLAG_ACTIVITY_NEW_TASK } // When val actualIntent = IntentHandler.getDeepLinkIntent(bundle) // Then assertNotNull(actualIntent) assertEquals(expectedIntent.toString(), actualIntent.toString()) } @Test fun givenWrappedDeeplink_whenGetDeeplinkIntent_thenAppLaunchIntentWithWrappedDeeplinkReturned() { // Given val bundle = Bundle().apply { putString(KEY_ES_LINK_WRAPPED, DEEPLINK_WRAPPED) } val expectedIntent = Intent(Intent.ACTION_VIEW, Uri.parse(DEEPLINK_WRAPPED)).apply { putExtras(bundle) flags = Intent.FLAG_ACTIVITY_NEW_TASK } // When val actualIntent = IntentHandler.getDeepLinkIntent(bundle) // Then assertNotNull(actualIntent) assertEquals(expectedIntent.toString(), actualIntent.toString()) } @Test fun givenNullForDeeplink_whenGetDeeplinkIntent_thenNullReturned() { // Given val bundle = Bundle() // When val actualIntent = IntentHandler.getDeepLinkIntent(bundle) // Then assertNull(actualIntent) } @Test fun givenAppInstalled_whenResolveAppLaunchIntent_thenAppLaunchIntentStartsApplication() { // Given val injectedIntent = injectAppLaunchIntent() // When val appLaunchIntent = IntentHandler.AppLaunchIntent.getAppLaunchIntent(application) application.startActivity(appLaunchIntent) val shadow = Shadows.shadowOf(application) val actualIntent = shadow.peekNextStartedActivity() TestCase.assertNotNull(actualIntent) // Then assertEquals(injectedIntent.`package`, actualIntent.`package`) assertEquals(injectedIntent.categories, actualIntent.categories) assertEquals(injectedIntent.action, actualIntent.action) } // region helper methods ----------------------------------------------------------------------- private fun injectAppLaunchIntent(): Intent { val launchIntent = Intent(Intent.ACTION_MAIN) launchIntent.addCategory(Intent.CATEGORY_LAUNCHER) launchIntent.setPackage(application.packageName) val resolveInfo = ResolveInfo() val activityInfo = ActivityInfo() activityInfo.packageName = application.packageName activityInfo.name = "MainActivity" resolveInfo.activityInfo = activityInfo val shadowPackageManager = Shadows.shadowOf(application.packageManager) shadowPackageManager.addResolveInfoForIntent(launchIntent, resolveInfo) return launchIntent } // endregion helper methods -------------------------------------------------------------------- }
1
Kotlin
2
1
8be261c2b571a7a6124c62c038dfcf97b1ccad3f
4,664
reteno-mobile-android-sdk
MIT License
infra/src/main/kotlin/fr/sacane/jmanager/infrastructure/rest/Exception.kt
Sacane
531,082,439
false
{"Kotlin": 95099, "Vue": 34463, "TypeScript": 16890, "JavaScript": 602, "CSS": 134}
package fr.sacane.jmanager.infrastructure.rest data class ErrorMessage( var status: Int, var message: String ) class ForbiddenException(override val message: String) : RuntimeException(message) class TimeOutException(override val message: String) : RuntimeException(message) class NotFoundException(override val message: String) : RuntimeException(message) class InvalidRequestException(override val message: String) : RuntimeException(message) class UnauthorizedRequestException(override val message: String): RuntimeException(message)
0
Kotlin
0
0
5ba090de7425ba78eacc2cd2c21c13424278eb4e
546
JManager
MIT License
kotest-framework/kotest-framework-engine/src/jvmTest/kotlin/com/sksamuel/kotest/engine/coroutines/InheritedTestCoroutineDispatcherTest.kt
kotest
47,071,082
false
null
package com.sksamuel.kotest.engine.coroutines import io.kotest.core.spec.style.FunSpec import io.kotest.matchers.shouldBe import kotlinx.coroutines.CoroutineDispatcher @ExperimentalStdlibApi class InheritedTestCoroutineDispatcherTest : FunSpec() { init { testCoroutineDispatcher = true context("a context with a test dispatcher should be inherited by nested tests") { val dispatcher = coroutineContext[CoroutineDispatcher] test("nest me!") { coroutineContext[CoroutineDispatcher] shouldBe dispatcher } } } }
143
null
632
4,372
551bd92c0311ff3bf02975fb00e8b9b674fc9cd1
573
kotest
Apache License 2.0
data/impl/src/main/kotlin/io/morfly/streaming/data/impl/ReviewsRemoteMediator.kt
Morfly
398,528,749
false
null
package io.morfly.streaming.data.impl import androidx.paging.ExperimentalPagingApi import androidx.paging.LoadType import androidx.paging.PagingState import androidx.paging.RemoteMediator import androidx.room.withTransaction import dagger.assisted.Assisted import dagger.assisted.AssistedInject import io.morfly.streaming.data.impl.mapping.DataMapper import io.morfly.streaming.data.impl.network.MovieDbApi import io.morfly.streaming.data.impl.storage.AppDatabase import io.morfly.streaming.data.impl.storage.entity.ReviewRemoteKeys import io.morfly.streaming.data.impl.storage.entity.StoredReview import retrofit2.HttpException import java.io.IOException private const val FIRST_PAGE = 1 private const val SECOND_PAGE = 2 @OptIn(ExperimentalPagingApi::class) class ReviewsRemoteMediator @AssistedInject constructor( @Assisted private val movieId: Int, private val networkService: MovieDbApi, private val database: AppDatabase, private val mapper: DataMapper ) : RemoteMediator<Int, StoredReview>() { private val reviewsDao = database.reviewsDao() private val reviewRemoteKeysDao = database.reviewRemoteKeysDao() override suspend fun load( loadType: LoadType, state: PagingState<Int, StoredReview> ): MediatorResult { return try { val loadKey = when (loadType) { LoadType.REFRESH -> FIRST_PAGE LoadType.PREPEND -> return MediatorResult.Success(endOfPaginationReached = true) LoadType.APPEND -> { val lastItemRemoteKeys = findRemoteKeysForLastItem(state) if (lastItemRemoteKeys?.nextKey == null) { if (state.pages.isNotEmpty() && state.pages.lastOrNull { it.data.isNotEmpty() } == null) SECOND_PAGE else return MediatorResult.Success(endOfPaginationReached = true) } else { lastItemRemoteKeys.nextKey } } } val movies = networkService.reviews(movieId, page = loadKey).results .map { item -> mapper.networkToStorage(item, movieId) } val endOfPaginationReached = movies.isEmpty() val prevKey = if (loadKey == FIRST_PAGE) null else loadKey - 1 val nextKey = if (endOfPaginationReached) null else loadKey + 1 val remoteKeys = movies.map { ReviewRemoteKeys(it.id, prevKey, nextKey) } writeToDatabase(movies, remoteKeys) MediatorResult.Success(endOfPaginationReached) } catch (exception: IOException) { MediatorResult.Error(exception) } catch (exception: HttpException) { MediatorResult.Error(exception) } } private suspend fun writeToDatabase( movies: List<StoredReview>, remoteKeys: List<ReviewRemoteKeys> ) { database.withTransaction { reviewsDao.insertAll(movies) reviewRemoteKeysDao.insertAll(remoteKeys) } } private fun findLastItem(state: PagingState<Int, StoredReview>): StoredReview? { return state.pages .lastOrNull { it.data.isNotEmpty() } ?.data ?.lastOrNull() } private suspend fun findRemoteKeysForLastItem(state: PagingState<Int, StoredReview>): ReviewRemoteKeys? = findLastItem(state) ?.let { review -> reviewRemoteKeysDao.reviewRemoteKeys(review.id) } }
2
Kotlin
11
97
9b97a86f0931060dcbb62384f959c2e511a8786f
3,470
MultiModuleMovies
MIT License
svg-to-compose/src/commonMain/kotlin/dev/tonholo/s2c/domain/PathNodes.kt
rafaeltonholo
659,782,425
false
{"Kotlin": 337368, "Shell": 5369}
// Suppressing MagicNumber in this file since we need to use array positions to access the proper value // while parsing the commands. @file:Suppress("MagicNumber") package dev.tonholo.s2c.domain import dev.tonholo.s2c.domain.PathNodes.ArcTo import dev.tonholo.s2c.domain.PathNodes.CurveTo import dev.tonholo.s2c.domain.PathNodes.HorizontalLineTo import dev.tonholo.s2c.domain.PathNodes.LineTo import dev.tonholo.s2c.domain.PathNodes.MoveTo import dev.tonholo.s2c.domain.PathNodes.QuadTo import dev.tonholo.s2c.domain.PathNodes.ReflectiveCurveTo import dev.tonholo.s2c.domain.PathNodes.ReflectiveQuadTo import dev.tonholo.s2c.domain.PathNodes.VerticalLineTo import dev.tonholo.s2c.extensions.indented import dev.tonholo.s2c.extensions.removeTrailingZero import dev.tonholo.s2c.extensions.toInt /** * PathNodes is a sealed class that contains multiple classes to represent * different commands of an SVG/AVG path. * These classes include: [MoveTo], [ArcTo], [VerticalLineTo], [HorizontalLineTo], * [LineTo], [CurveTo], [ReflectiveCurveTo], [QuadTo] and [ReflectiveQuadTo]. * * @property values - The list of elements representing the parameters of the command. * @property isRelative - Boolean to determine if the command is relative or not. * @property command - An instance of PathCommand representing the type of the SVG/AVG command. * @property minified - A Boolean value indicating if the output should be minified. */ sealed class PathNodes( val values: List<String>, val isRelative: Boolean, val command: PathCommand, val minified: Boolean, ) { val shouldClose = values[command.size - 1].last().lowercaseChar() == PathCommand.Close.value protected val realCommand = if (isRelative) command else command.uppercaseChar() /** * Visible for Test only. */ internal abstract fun buildParameters(): Set<String> abstract fun materialize(): String private fun closeCommand(): String = if (shouldClose) { """ |close() | """.trimMargin() } else { "" } override fun toString(): String = if (shouldClose) { PathCommand.Close.value.toString() } else { "" } fun String.removeTrailingZeroConsiderCloseCommand(): String = this.removeTrailingZero() .replace("\\.0z\\b".toRegex(), PathCommand.Close.value.toString()) /** * Materializes the commands on the Compose path functions.` * By default, it prints in pretty mode, adding a comment explaining * the path command where the parameters were taken and in case of more * than two parameters, separate them on new line. * * @param fnName The function name to be used in the SVG/AVG command. * @param forceInline A flag indicating whether the command parameters * should be inlined or not. By default, it's set to `false. * @return The function representation of the SVG/AVG command. */ protected fun materialize( fnName: String, forceInline: Boolean = false, ): String = """ |${if (minified) "" else "// ${toString().removeTrailingZeroConsiderCloseCommand()}"} |$fnName${if (isRelative) "Relative" else ""}(${buildParameters().toParameters(forceInline)}) |${closeCommand()} """.trimMargin().let { if (minified) it.trim() else it } /** * A helper function that helps in indenting parameters, adding * separators, and wrapping without initial and end separators * if required as per minified or forceInline flags. * * @param forceInline A boolean flag indicating whether the parameters * should be in a single line ignoring minification. * @return The formatted parameter string. */ private fun Set<String>.toParameters(forceInline: Boolean = false): String { val indentSize = if (minified || forceInline) 0 else 4 val separator = if (minified || forceInline) "" else "\n" val scape = if (minified || forceInline) " " else "|" return joinToString(separator) { "$scape${it.indented(indentSize)}," }.let { if (minified || forceInline) it.substring(1, it.length - 1) else "\n$it\n" } } /** * The [MoveTo] represents the SVG/AVG command to move the pen to a new location. * * It's a type of [PathNodes] which holds SVG/AVG command parameters. * * The new location is determined using the specified `x` and `y` coordinates. * The unit of these coordinates is determined based on the `isRelative` value. * If [isRelative] is `true`, the [x] and [y] are treated as relative coordinates * otherwise they are treated as absolute coordinates. * * The class contains an overridden [materialize] function which returns a * [String] representation of the SVG/AVG command in the form required by * the Compose path functions. * * @property values A List of string values specifying the parameters of the * [MoveTo] command. * @property isRelative A boolean value indicating whether the move command * is relative. * @property minified A boolean value indicating whether the output of * [materialize] should be minified. */ class MoveTo( values: List<String>, isRelative: Boolean, minified: Boolean, ) : PathNodes( values = values, isRelative = isRelative, command = PathCommand.MoveTo, minified = minified, ) { val x = values.first().lowercase().removePrefix(command.toString()).toFloat() val y = values[1] .lowercase() .removeSuffix(PathCommand.Close) .toFloat() override fun buildParameters(): Set<String> { val relativePrefix = if (isRelative) "d" else "" return setOf( "${relativePrefix}x = ${x}f", "${relativePrefix}y = ${y}f", ) } override fun materialize(): String { return materialize( fnName = "moveTo", forceInline = true, ) } override fun toString(): String = "$realCommand $x $y" + super.toString() } /** * The [ArcTo] class represents the SVG/AVG "arc" command which is used to create * an arc. * * It's a type of [PathNodes] which holds SVG/AVG command parameters. * * The class has several properties which denote the parameters of SVG/AVG "arc" * command: horizontal ellipse radius [a], vertical ellipse radius [b], rotation * [theta], large arc flag [isMoreThanHalf], sweep flag [isPositiveArc], ending * point coordinates [x] and [y]. * * The class contains an overridden [materialize] function which returns a * [String] representation of the SVG/AVG command in the form required by * the Compose path functions. * * @property values A List of string values specifying the parameters of the [MoveTo] * command. * @property isRelative A boolean value indicating whether the move command is * relative. * @property minified A boolean value indicating whether the output of [materialize] * should be minified. */ class ArcTo( values: List<String>, isRelative: Boolean, minified: Boolean, ) : PathNodes( values = values, isRelative = isRelative, command = PathCommand.ArcTo, minified = minified, ) { /** * rx */ val a = values.first().lowercase().removePrefix(command.toString()).toFloat() /** * ry */ val b = values[1].toFloat() /** * x-axis-rotation */ val theta = values[2].toFloat() /** * large-arc-flag */ val isMoreThanHalf = values[3] == "1" /** * sweep flag */ val isPositiveArc = values[4] == "1" val x = values[5].toFloat() val y = values[6] .lowercase() .removeSuffix(PathCommand.Close) .toFloat() override fun buildParameters(): Set<String> { val relativePrefix = if (isRelative) "d" else "" val a = (if (isRelative) "a" else "horizontalEllipseRadius") + " = ${this.a}f" val b = (if (isRelative) "b" else "verticalEllipseRadius") + " = ${this.b}f" return setOf( a, b, "theta = ${theta}f", "isMoreThanHalf = $isMoreThanHalf", "isPositiveArc = $isPositiveArc", "${relativePrefix}x1 = ${x}f", "${relativePrefix}y1 = ${y}f", ) } override fun materialize(): String { return materialize( fnName = "arcTo", ) } override fun toString(): String = "$realCommand ${this.a} ${this.b} $theta ${isMoreThanHalf.toInt()} ${isPositiveArc.toInt()} $x $y" + super.toString() } /** * The [VerticalLineTo] class represents the SVG/AVG "vertical line to" command, * which instructs the pen to move vertically by the specified amount. * * A type of [PathNodes], it holds the given SVG/AVG command parameters. * * The vertical position where the pen should move to is denoted by [y], the * first value stripped of the command prefix and the [PathCommand.Close] suffix. * * Depending on the [isRelative] flag, the [y] value is considered either as * an absolute coordinate (if false) or as a distance from the current * position (if true). * * The class contains an overridden [materialize] function which returns a * [String] representation of the SVG/AVG command in the form required by * the Compose path functions. * * @property values A List of parameter strings for the [VerticalLineTo] command. * @property isRelative A Boolean flag indicating if the command is relative. * @property minified A Boolean flag indicating whether the output of [materialize] * should be minified. * @property y The new y-coordinate to which the line extends. */ class VerticalLineTo( values: List<String>, isRelative: Boolean, minified: Boolean, ) : PathNodes( values = values, isRelative = isRelative, command = PathCommand.VerticalLineTo, minified = minified, ) { val y = values .first() .lowercase() .removePrefix(command.toString()) .removeSuffix(PathCommand.Close) .toFloat() override fun buildParameters(): Set<String> { val relativePrefix = if (isRelative) "d" else "" return setOf("${relativePrefix}y = ${y}f") } override fun materialize(): String { return materialize( fnName = "verticalLineTo", forceInline = true, ) } override fun toString(): String { return "$realCommand $y" + super.toString() } } /** * The [HorizontalLineTo] class represents the SVG/AVG "horizontal line to" command * which is used to draw a horizontal line from the current point to a new point. * * It's a type of [PathNodes] which holds SVG/AVG command parameters. * * The class contains an overridden [materialize] function which returns a * [String] representation of the SVG/AVG command in the form required by * the Compose path functions. * * @property values A List of string values specifying the parameters of the * [HorizontalLineTo] command. * @property isRelative A boolean value indicating whether the move command is * relative to the current position. * @property minified A boolean value indicating whether the output of [materialize] * should be minified or not. * @property x The new x-coordinate to which the line extends. */ class HorizontalLineTo( values: List<String>, isRelative: Boolean, minified: Boolean, ) : PathNodes( values = values, isRelative = isRelative, command = PathCommand.HorizontalLineTo, minified = minified, ) { val x = values .first() .lowercase() .removePrefix(command.toString()) .removeSuffix(PathCommand.Close) .toFloat() override fun buildParameters(): Set<String> { val relativePrefix = if (isRelative) "d" else "" return setOf("${relativePrefix}x = ${x}f") } override fun materialize(): String { return materialize( fnName = "horizontalLineTo", forceInline = true, ) } override fun toString(): String { return "$realCommand $x" + super.toString() } } /** * The [LineTo] class represents the SVG/AVG "line to" command used for * creating a straight line. * * It's a type of [PathNodes] which holds SVG/AVG command parameters. * * The line is defined by destination point coordinates [x] and [y]. The * origin of these coordinates can be absolute or relative based on the * [isRelative] flag. If [isRelative] is `true`, [x] and [y] are treated * as relative coordinates. Otherwise, they are treated as absolute. * * The class contains an overridden [materialize] function which returns a * [String] representation of the SVG/AVG command in the form required by * the Compose path functions. * * @property values A List of string values specifying the parameters of * the [LineTo] command. * @property isRelative A boolean value indicating whether the move command * is relative to the current position. * @property minified A boolean value indicating whether the output of * [materialize] should be minified or not. * @property x The new x-coordinate to which the line extends. * @property y The new y-coordinate to which the line extends. */ class LineTo( values: List<String>, isRelative: Boolean, minified: Boolean, ) : PathNodes( values = values, isRelative = isRelative, command = PathCommand.LineTo, minified = minified, ) { val x = values .first() .lowercase() .removePrefix(command.toString()) .toFloat() val y = values[1] .lowercase() .removeSuffix(PathCommand.Close) .toFloat() override fun buildParameters(): Set<String> { val relativePrefix = if (isRelative) "d" else "" return setOf( "${relativePrefix}x = ${x}f", "${relativePrefix}y = ${y}f", ) } override fun materialize(): String { return materialize( fnName = "lineTo", forceInline = true, ) } override fun toString(): String { return "$realCommand $x $y" + super.toString() } } /** * The [CurveTo] class represents the SVG/AVG "curve to" command which is used * to create a cubic Bézier curve. * * It's a type of [PathNodes] which holds SVG/AVG command parameters. * * This class contains several properties representing the command parameters. * In particular, [values] defines a set of values that represent the * [[x1], [y1]], [[x2], [y2]], and [[x3], [y3]] coordinates of the first, second * control points, and the end point of the curve. * * The class contains an overridden [materialize] function which returns a * [String] representation of the SVG/AVG command in the form required by * the Compose path functions. * * @property values A List of string values specifying the parameters of the * [CurveTo] command. * @property isRelative A boolean value indicating whether the move command is * relative to the current position. * @property minified A boolean value indicating whether the output of [materialize] * should be minified or not. */ class CurveTo( values: List<String>, isRelative: Boolean, minified: Boolean, ) : PathNodes( values = values, isRelative = isRelative, command = PathCommand.CurveTo, minified = minified, ) { val x1 = values.first().lowercase().removePrefix(command.toString()).toFloat() val y1 = values[1].toFloat() val x2 = values[2].toFloat() val y2 = values[3].toFloat() val x3 = values[4].toFloat() val y3 = values[5] .lowercase() .removeSuffix(PathCommand.Close) .toFloat() override fun buildParameters(): Set<String> { val relativePrefix = if (isRelative) "d" else "" return setOf( "${relativePrefix}x1 = ${x1}f", "${relativePrefix}y1 = ${y1}f", "${relativePrefix}x2 = ${x2}f", "${relativePrefix}y2 = ${y2}f", "${relativePrefix}x3 = ${x3}f", "${relativePrefix}y3 = ${y3}f", ) } override fun materialize(): String { return materialize( fnName = "curveTo", ) } override fun toString(): String { return "$realCommand $x1 $y1 $x2 $y2 $x3 $y3" + super.toString() } } /** * The [ReflectiveCurveTo] represents the SVG/AVG "smooth cubic Bézier" * command. * * This command creates a smooth curve between two points using a reflection * of the control point used in previous commands. * * The [x1], [y1] coordinates represent the first control point for the curve, * while [x2], [y2] represent the endpoint of the curve. * * The class contains an overridden [materialize] function which returns a * [String] representation of the SVG/AVG command in the form required by * the Compose path functions. * * @property values A List of string values specifying the parameters of the * [ReflectiveCurveTo] command. * @property isRelative A boolean value indicating whether the curve command * is relative. * @property minified A boolean value indicating whether the output of * [materialize] should be minified. * @property x1 The x-coordinate for the first control point. * @property y1 The y-coordinate for the first control point. * @property x2 The x-coordinate for the second control point. * @property y2 The y-coordinate for the second control point. */ class ReflectiveCurveTo( values: List<String>, isRelative: Boolean, minified: Boolean, ) : PathNodes( values = values, isRelative = isRelative, command = PathCommand.ReflectiveCurveTo, minified = minified, ) { val x1 = values.first().lowercase().removePrefix(command.toString()).toFloat() val y1 = values[1].toFloat() val x2 = values[2].toFloat() val y2 = values[3] .lowercase() .removeSuffix(PathCommand.Close) .toFloat() override fun buildParameters(): Set<String> { val relativePrefix = if (isRelative) "d" else "" return setOf( "${relativePrefix}x1 = ${x1}f", "${relativePrefix}y1 = ${y1}f", "${relativePrefix}x2 = ${x2}f", "${relativePrefix}y2 = ${y2}f", ) } override fun materialize(): String { return materialize( fnName = "reflectiveCurveTo", ) } override fun toString(): String { return "$realCommand $x1 $y1 $x2 $y2" + super.toString() } } /** * The [QuadTo] class represents the SVG/AVG "quadratic Bézier curve" command * * It's a type of [PathNodes] which holds SVG/AVG command parameters. * * The [x1], [y1] coordinates represent the control point for the curve, * while [x2], [y2] represent the endpoint of the curve. * * The class contains an overridden [materialize] function which returns a * [String] representation of the SVG/AVG command in the form required by * the Compose path functions. * * @property values A List of string values specifying the parameters of the * [QuadTo] command. * @property isRelative A boolean value indicating whether the curve command * is relative. * @property minified A boolean value indicating whether the output of * [materialize] should be minified. * @property x1 The x-coordinate for the first control point. * @property y1 The y-coordinate for the first control point. * @property x2 The x-coordinate for the second control point. * @property y2 The y-coordinate for the second control point. */ class QuadTo( values: List<String>, isRelative: Boolean, minified: Boolean, ) : PathNodes( values = values, isRelative = isRelative, command = PathCommand.QuadTo, minified = minified, ) { val x1 = values.first().lowercase().removePrefix(command.toString()).toFloat() val y1 = values[1].toFloat() val x2 = values[2].toFloat() val y2 = values[3] .lowercase() .removeSuffix(PathCommand.Close) .toFloat() override fun buildParameters(): Set<String> { val relativePrefix = if (isRelative) "d" else "" return setOf( "${relativePrefix}x1 = ${x1}f", "${relativePrefix}y1 = ${y1}f", "${relativePrefix}x2 = ${x2}f", "${relativePrefix}y2 = ${y2}f", ) } override fun materialize(): String { return materialize( fnName = "quadTo", ) } override fun toString(): String { return "$realCommand $x1 $y1 $x2 $y2" + super.toString() } } /** * The [ReflectiveQuadTo] represents the SVG/AVG "reflective quadratic Bézier * curve to" command, which is used to create a smooth quadratic Bézier curve. * * It's a type of [PathNodes] which holds SVG/AVG command parameters. * * The curve is reflective of the control point of the previous command for * creating a smooth curve. The curve ends at the point denoted by the * coordinates ([x1], [y1]), with the control point being the reflection of * the control point on the previous command relative to the starting point. * * The class contains an overridden [materialize] function which returns a * [String] representation of the SVG/AVG command in the form required by * the Compose path functions. * * @property values A List of string values specifying the parameters of the * [ReflectiveQuadTo] command. * @property isRelative A Boolean value. If `true`, the [x1] and [y1] parameters * will be treated as relative coordinates. Otherwise, they will be treated as * absolute coordinates. * @property minified A boolean value indicating whether the output of * [materialize] should be minified. * @property x1 represents the x-coordinate for the ending point of the curve * @property y1 signifies the y-coordinate for the ending point of the curve */ class ReflectiveQuadTo( values: List<String>, isRelative: Boolean, minified: Boolean, ) : PathNodes( values = values, isRelative = isRelative, command = PathCommand.ReflectiveQuadTo, minified = minified, ) { val x1 = values.first().lowercase().removePrefix(command.toString()).toFloat() val y1 = values[1] .lowercase() .removeSuffix(PathCommand.Close) .toFloat() override fun buildParameters(): Set<String> { val relativePrefix = if (isRelative) "d" else "" return setOf( "${relativePrefix}x1 = ${x1}f", "${relativePrefix}y1 = ${y1}f", ) } override fun materialize(): String { return materialize( fnName = "reflectiveQuadTo", ) } override fun toString(): String { return "$realCommand $x1 $y1" + super.toString() } } }
4
Kotlin
1
45
551441e87ba7bd62523754dd105a9edc925017b1
24,842
svg-to-compose
MIT License
app/src/main/java/com/neurowhai/pews/PewsFirebaseMessagingService.kt
NeuroWhAI
275,617,402
false
null
package com.neurowhai.pews import android.Manifest import android.app.NotificationChannel import android.app.NotificationManager import android.app.PendingIntent import android.content.Context import android.content.Intent import android.content.pm.PackageManager import android.graphics.Bitmap import android.graphics.Canvas import android.graphics.Color import android.graphics.Paint import android.location.Location import android.media.RingtoneManager import android.os.Build import android.util.Log import androidx.core.app.ActivityCompat import androidx.core.app.NotificationCompat import com.google.android.gms.location.FusedLocationProviderClient import com.google.android.gms.location.LocationServices import com.google.firebase.messaging.FirebaseMessaging import com.google.firebase.messaging.FirebaseMessagingService import com.google.firebase.messaging.RemoteMessage import java.io.ByteArrayOutputStream import java.util.zip.Inflater import kotlin.math.round class PewsFirebaseMessagingService : FirebaseMessagingService() { private lateinit var topicName: String private lateinit var fusedLocationClient: FusedLocationProviderClient override fun onCreate() { super.onCreate() topicName = if (BuildConfig.DEBUG) { "test" } else { "eqk" } fusedLocationClient = LocationServices.getFusedLocationProviderClient(this) FirebaseMessaging.getInstance().subscribeToTopic(topicName) .addOnCompleteListener { task -> if (task.isSuccessful) { Log.d(TAG, "$topicName 구독 성공") } else { Log.d(TAG, "$topicName 구독 실패") } } } override fun onMessageReceived(remoteMessage: RemoteMessage) { Log.d(TAG, "From: ${remoteMessage.from}") if (remoteMessage.from == "/topics/$topicName" && remoteMessage.data.isNotEmpty()) { Log.d(TAG, "Message data payload: " + remoteMessage.data) val data = remoteMessage.data val msg = data["msg"] ?: "" val scale = data["scale"] ?: "" val mmi = data["mmi"] ?: "" val defaultMsg = "규모 $scale 최대진도 ${mmi}의 지진 발생." if (ActivityCompat.checkSelfPermission( this, Manifest.permission.ACCESS_COARSE_LOCATION ) == PackageManager.PERMISSION_GRANTED ) { fusedLocationClient.lastLocation .addOnSuccessListener { loc : Location? -> if (loc != null) { var intensity = getIntensity(data["grid"] ?: "", loc.latitude, loc.longitude) val intensityStr = if (intensity < 0) { intensity = 0 "불명" } else { intensity.toString() } val locationMsg = "$defaultMsg 내 위치 예상진도 ${intensityStr}." sendNotification(msg, locationMsg, intensity) } else { sendNotification(msg, defaultMsg, 0) } } .addOnFailureListener { sendNotification(msg, defaultMsg, 0) } .addOnCanceledListener { sendNotification(msg, defaultMsg, 0) } } else { sendNotification(msg, defaultMsg, 0) } } } private fun sendNotification(title: String, messageBody: String, mmi: Int) { var mmiRanged = mmi if (mmiRanged < 0) { mmiRanged = 0 } else if (mmiRanged >= MmiColors.size) { mmiRanged = MmiColors.size - 1 } val bitmap = Bitmap.createBitmap(128, 128, Bitmap.Config.ARGB_8888) val canvas = Canvas(bitmap) canvas.drawColor(0xff000000.toInt() or MmiColors[mmiRanged]) val pnt = Paint() pnt.color = if (mmiRanged <= 5) { Color.BLACK } else { Color.WHITE } pnt.textSize = 64.0f pnt.textAlign = Paint.Align.CENTER canvas.drawText(MmiChar[mmiRanged], 64.0f, 64.0f - (pnt.descent() + pnt.ascent()) / 2, pnt) val intent = Intent(this, MainActivity::class.java) intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP) val pendingIntent = PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_ONE_SHOT) val channelId = "pews_eqk" val defaultSoundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION) val notificationBuilder = NotificationCompat.Builder(this, channelId) .setSmallIcon(R.mipmap.ic_launcher) .setContentTitle(title) .setContentText(messageBody) .setLargeIcon(bitmap) .setStyle(NotificationCompat.BigTextStyle() .bigText("${messageBody}\n내 위치에서 ${MmiDescription[mmiRanged]}")) .setAutoCancel(true) .setSound(defaultSoundUri) .setContentIntent(pendingIntent) val notificationManager = getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { val channel = NotificationChannel(channelId, "지진 정보", NotificationManager.IMPORTANCE_HIGH) notificationManager.createNotificationChannel(channel) } notificationManager.notify(0, notificationBuilder.build()) } private fun getIntensity(gridData: String, latitude: Double, longitude: Double): Int { if (gridData.isEmpty()) { return -1 } val compressedBytes = ByteArray(gridData.length / 2) { gridData.substring(it * 2, it * 2 + 2).toInt(16).toByte() } val outputStream = ByteArrayOutputStream(gridData.length) val decompresser = Inflater() decompresser.setInput(compressedBytes, 0, compressedBytes.size) val buffer = ByteArray(1024) while (!decompresser.finished()) { val count = decompresser.inflate(buffer) outputStream.write(buffer, 0, count) } decompresser.end() val gridBytes = outputStream.toByteArray() val sizeX = ((132.05 - 124.5) / 0.05).toInt() val y = round((38.85 - latitude) / 0.05).toInt() val x = round((longitude - 124.5) / 0.05).toInt() val index: Int = y * sizeX + x return if (y >= 0 && x >= 0 && x < sizeX && index >= 0 && index / 2 < gridBytes.size ) { if (index % 2 == 0) { gridBytes[index / 2] / 16 } else { gridBytes[index / 2] % 16 } } else { -1 } } companion object { private const val TAG = "PewsFCMService" private val MmiColors: Array<Int> = arrayOf(0xffffff, 0xffffff, 0xa0e6ff, 0x92d050, 0xffff00, 0xffc000, 0xff0000, 0xa32777, 0x632523, 0x4c2600, 0x000000) private val MmiChar: Array<String> = arrayOf("?", "Ⅰ", "Ⅱ", "Ⅲ", "Ⅳ", "Ⅴ", "Ⅵ", "Ⅶ", "Ⅷ", "Ⅸ", "Ⅹ") private val MmiDescription: Array<String> = arrayOf( "진도 Ⅰ 미만 혹은 불명.", "대부분 사람들은 느낄 수 없으나, 지진계에는 기록된다.", "조용한 상태나 건물 위층에 있는 소수의 사람만 느낀다.", "실내, 특히 건물 위층에 있는 사람이 현저하게 느끼며, 정지하고 있는 차가 약간 흔들린다.", "실내에서 많은 사람이 느끼고, 밤에는 잠에서 깨기도 하며, 그릇과 창문 등이 흔들린다.", "거의 모든 사람이 진동을 느끼고, 그릇, 창문 등이 깨지기도 하며, 불안정한 물체는 넘어진다.", "모든 사람이 느끼고, 일부 무거운 가구가 움직이며, 벽의 석회가 떨어지기도 한다.", "일반 건물에 약간의 피해가 발생하며, 부실한 건물에는 상당한 피해가 발생한다.", "일반 건물에 부분적 붕괴 등 상당한 피해가 발생하며, 부실한 건물에는 심각한 피해가 발생한다.", "잘 설계된 건물에도 상당한 피해가 발생하며, 일반 건축물에는 붕괴 등 큰 피해가 발생한다.", "대부분의 석조 및 골조 건물이 파괴되고, 기차선로가 휘어진다." ) } }
0
Kotlin
1
2
013468724e7b2b14e282df2ff1b64712889bc515
8,211
PersonalEarthquakeAlarm
MIT License
analysis/low-level-api-fir/src/org/jetbrains/kotlin/analysis/low/level/api/fir/providers/LLFirCombinedKotlinSymbolProvider.kt
JetBrains
3,432,266
false
null
/* * Copyright 2010-2023 JetBrains s.r.o. and Kotlin Programming Language contributors. * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ package org.jetbrains.kotlin.analysis.low.level.api.fir.providers import com.intellij.openapi.project.Project import org.jetbrains.kotlin.analysis.low.level.api.fir.caches.NullableCaffeineCache import org.jetbrains.kotlin.analysis.low.level.api.fir.sessions.LLFirSession import org.jetbrains.kotlin.analysis.project.structure.KtModule import org.jetbrains.kotlin.analysis.providers.KotlinDeclarationProvider import org.jetbrains.kotlin.analysis.providers.mergeDeclarationProviders import org.jetbrains.kotlin.fir.FirSession import org.jetbrains.kotlin.fir.resolve.providers.FirCompositeCachedSymbolNamesProvider import org.jetbrains.kotlin.fir.resolve.providers.FirSymbolNamesProvider import org.jetbrains.kotlin.fir.resolve.providers.FirSymbolProvider import org.jetbrains.kotlin.fir.resolve.providers.FirSymbolProviderInternals import org.jetbrains.kotlin.fir.symbols.impl.FirCallableSymbol import org.jetbrains.kotlin.fir.symbols.impl.FirClassLikeSymbol import org.jetbrains.kotlin.fir.symbols.impl.FirNamedFunctionSymbol import org.jetbrains.kotlin.fir.symbols.impl.FirPropertySymbol import org.jetbrains.kotlin.name.CallableId import org.jetbrains.kotlin.name.ClassId import org.jetbrains.kotlin.name.FqName import org.jetbrains.kotlin.name.Name import org.jetbrains.kotlin.psi.KtCallableDeclaration /** * [LLFirCombinedKotlinSymbolProvider] combines multiple [LLFirKotlinSymbolProvider]s with the following advantages: * * - The combined symbol provider can combine the "names in package" sets built by individual providers. The name set can then be checked * once instead of for each subordinate symbol provider. Because Kotlin symbol providers are ordered first in * [LLFirDependenciesSymbolProvider], this check is especially fruitful. * - For a given class or callable ID, indices can be accessed once to get relevant PSI elements. Then the correct symbol provider(s) to * call can be found out via the PSI element's [KtModule]s. This avoids the need to call every single subordinate symbol provider. * - A small Caffeine cache can avoid most index accesses for classes, because many names are requested multiple times, with a minor memory * footprint. * * [declarationProvider] must have a scope which combines the scopes of the individual [providers]. */ internal class LLFirCombinedKotlinSymbolProvider private constructor( session: FirSession, project: Project, providers: List<LLFirKotlinSymbolProvider>, private val declarationProvider: KotlinDeclarationProvider, ) : LLFirSelectingCombinedSymbolProvider<LLFirKotlinSymbolProvider>(session, project, providers) { override val symbolNamesProvider: FirSymbolNamesProvider = FirCompositeCachedSymbolNamesProvider.fromSymbolProviders(session, providers) private val classifierCache = NullableCaffeineCache<ClassId, FirClassLikeSymbol<*>> { it.maximumSize(500) } override fun getClassLikeSymbolByClassId(classId: ClassId): FirClassLikeSymbol<*>? { if (!symbolNamesProvider.mayHaveTopLevelClassifier(classId)) return null return classifierCache.get(classId) { computeClassLikeSymbolByClassId(it) } } @OptIn(FirSymbolProviderInternals::class) private fun computeClassLikeSymbolByClassId(classId: ClassId): FirClassLikeSymbol<*>? { val candidates = declarationProvider.getAllClassesByClassId(classId) + declarationProvider.getAllTypeAliasesByClassId(classId) val (ktClass, provider) = selectFirstElementInClasspathOrder(candidates) { it } ?: return null return provider.getClassLikeSymbolByClassId(classId, ktClass) } @FirSymbolProviderInternals override fun getTopLevelCallableSymbolsTo(destination: MutableList<FirCallableSymbol<*>>, packageFqName: FqName, name: Name) { forEachCallableProvider( packageFqName, name, declarationProvider::getTopLevelCallables, ) { callableId, callables -> getTopLevelCallableSymbolsTo(destination, callableId, callables) } } @FirSymbolProviderInternals override fun getTopLevelFunctionSymbolsTo(destination: MutableList<FirNamedFunctionSymbol>, packageFqName: FqName, name: Name) { forEachCallableProvider(packageFqName, name, declarationProvider::getTopLevelFunctions) { callableId, functions -> getTopLevelFunctionSymbolsTo(destination, callableId, functions) } } @FirSymbolProviderInternals override fun getTopLevelPropertySymbolsTo(destination: MutableList<FirPropertySymbol>, packageFqName: FqName, name: Name) { forEachCallableProvider(packageFqName, name, declarationProvider::getTopLevelProperties) { callableId, properties -> getTopLevelPropertySymbolsTo(destination, callableId, properties) } } /** * Calls [provide] on those providers which can contribute a callable of the given name. */ private inline fun <A : KtCallableDeclaration> forEachCallableProvider( packageFqName: FqName, name: Name, getCallables: (CallableId) -> Collection<A>, provide: LLFirKotlinSymbolProvider.(CallableId, Collection<A>) -> Unit, ) { if (!symbolNamesProvider.mayHaveTopLevelCallable(packageFqName, name)) return val callableId = CallableId(packageFqName, name) getCallables(callableId) .groupBy { getModule(it) } .forEach { (ktModule, callables) -> // If `ktModule` cannot be found in the map, `callables` cannot be processed by any of the available providers, because none // of them belong to the correct module. We can skip in that case, because iterating through all providers wouldn't lead to // any results for `callables`. val provider = providersByKtModule[ktModule] ?: return@forEach provider.provide(callableId, callables) } } override fun getPackage(fqName: FqName): FqName? = providers.firstNotNullOfOrNull { it.getPackage(fqName) } companion object { fun merge(session: LLFirSession, project: Project, providers: List<LLFirKotlinSymbolProvider>): FirSymbolProvider? = if (providers.size > 1) { val declarationProvider = project.mergeDeclarationProviders(providers.map { it.declarationProvider }) LLFirCombinedKotlinSymbolProvider(session, project, providers, declarationProvider) } else providers.singleOrNull() } } /** * Callables are provided very rarely (compared to functions/properties individually), so it's okay to hit indices twice here. */ private fun KotlinDeclarationProvider.getTopLevelCallables(callableId: CallableId): List<KtCallableDeclaration> = getTopLevelFunctions(callableId) + getTopLevelProperties(callableId)
155
null
5608
45,423
2db8f31966862388df4eba2702b2f92487e1d401
7,005
kotlin
Apache License 2.0
cloud/aws/src/main/java/com/nimbusframework/nimbusaws/clients/websocket/ServerlessFunctionWebSocketClientApiGateway.kt
thomasjallerton
163,180,980
false
{"Kotlin": 1124638, "Java": 130052, "JavaScript": 12405, "CSS": 297, "Dockerfile": 148}
package com.nimbusframework.nimbusaws.clients.websocket import com.nimbusframework.nimbuscore.clients.JacksonClient import com.nimbusframework.nimbuscore.clients.websocket.ServerlessFunctionWebSocketClient import software.amazon.awssdk.core.SdkBytes import software.amazon.awssdk.services.apigatewaymanagementapi.ApiGatewayManagementApiClientBuilder import software.amazon.awssdk.services.apigatewaymanagementapi.model.PostToConnectionRequest import java.net.URI import java.nio.ByteBuffer internal class ServerlessFunctionWebSocketClientApiGateway( private val apiGatewayManagementApiBuilder: ApiGatewayManagementApiClientBuilder ): ServerlessFunctionWebSocketClient { private val env = System.getenv() private val endpoint = if (env.containsKey("WEBSOCKET_ENDPOINT")) env["WEBSOCKET_ENDPOINT"]!! else "" private val apiGatewayManagementApi by lazy { apiGatewayManagementApiBuilder.endpointOverride(URI.create(endpoint)).build() } override fun sendToConnection(connectionId: String, data: ByteBuffer) { val postToConnectionRequest = PostToConnectionRequest.builder() .connectionId(connectionId) .data(SdkBytes.fromByteBuffer(data)) .build() apiGatewayManagementApi.postToConnection(postToConnectionRequest) } override fun sendToConnectionConvertToJson(connectionId: String, data: Any) { val json = JacksonClient.writeValueAsBytes(data) val postToConnectionRequest = PostToConnectionRequest.builder() .connectionId(connectionId) .data(SdkBytes.fromByteArray(json)) .build() apiGatewayManagementApi.postToConnection(postToConnectionRequest) } }
4
Kotlin
4
39
5c3325caaf3fe9de9ffad130fd1e773c6f680e89
1,708
nimbus-framework
MIT License
app/src/test/java/org/who/ddccverifier/CQLEvaluatorTest.kt
WorldHealthOrganization
430,942,275
false
{"Kotlin": 240670, "HTML": 6961, "CSS": 3544, "Procfile": 68}
package org.who.ddccverifier import androidx.test.core.app.ApplicationProvider import ca.uhn.fhir.context.FhirContext import ca.uhn.fhir.context.FhirVersionEnum import com.google.android.fhir.FhirEngine import com.google.android.fhir.FhirEngineProvider import kotlinx.coroutines.runBlocking import org.hl7.fhir.r4.model.* import org.junit.Assert.* import org.junit.Before import org.junit.Rule import org.junit.Test import org.junit.runner.RunWith import org.robolectric.RobolectricTestRunner import org.who.ddccverifier.services.cql.CqlBuilder import org.who.ddccverifier.services.cql.FhirOperator import org.who.ddccverifier.test.BaseTrustRegistryTest import java.util.* import kotlin.system.measureTimeMillis @RunWith(RobolectricTestRunner::class) class CQLEvaluatorTest: BaseTrustRegistryTest() { @get:Rule val fhirEngineProviderRule = FhirEngineProviderTestRule() private val fhirContext = FhirContext.forCached(FhirVersionEnum.R4) private val jSONParser = fhirContext.newJsonParser() private lateinit var fhirEngine: FhirEngine private lateinit var fhirOperator: FhirOperator private val ddccPass = CqlBuilder.compileAndBuild(inputStream("TestPass-1.0.0.cql")!!) @Before fun setUp() = runBlocking { val elapsed = measureTimeMillis { fhirEngine = FhirEngineProvider.getInstance(ApplicationProvider.getApplicationContext()) fhirOperator = FhirOperator(fhirContext, fhirEngine) fhirOperator.loadLib(ddccPass) TimeZone.setDefault(TimeZone.getTimeZone("GMT")) } println("TIME: Test Initialized in $elapsed") } private suspend fun loadBundle(bundle: Bundle?) { checkNotNull(bundle) for (entry in bundle.entry) { when (entry.resource.resourceType) { ResourceType.Library -> fhirOperator.loadLib(entry.resource as Library) ResourceType.Bundle -> Unit else -> fhirEngine.create(entry.resource) } } } private fun patId(bundle: Bundle?): String { checkNotNull(bundle) return bundle.entry.filter { it.resource is Patient }.first().resource.id.removePrefix("Patient/") } @Test fun evaluateTestPassAsCQLOnQR1FromBundleTest() = runBlocking { val asset = jSONParser.parseResource(open("WHOQR1FHIRBundle.json")) as Bundle loadBundle(asset) val results = fhirOperator.evaluateLibrary( "http://localhost/Library/TestPass|1.0.0", patId(asset), setOf("CompletedImmunization", "GetFinalDose", "GetSingleDose", "GetAllModerna", "ModernaProtocol")) as Parameters assertEquals(Collections.EMPTY_LIST, results.getParameters("GetFinalDose")) assertEquals(Collections.EMPTY_LIST, results.getParameters("GetSingleDose")) assertEquals(Collections.EMPTY_LIST, results.getParameters("GetAllModerna")) assertEquals(false, results.getParameterBool("ModernaProtocol")) assertEquals(false, results.getParameterBool("CompletedImmunization")) } @Test fun evaluateTestPassAsJSONOnQR1FromBundleTest() = runBlocking { val asset = jSONParser.parseResource(open("WHOQR1FHIRBundle.json")) as Bundle loadBundle(asset) val results = fhirOperator.evaluateLibrary( "http://localhost/Library/TestPass|1.0.0", patId(asset), setOf("CompletedImmunization", "GetFinalDose", "GetSingleDose", "GetAllModerna", "ModernaProtocol")) as Parameters assertEquals(Collections.EMPTY_LIST, results.getParameters("GetFinalDose")) assertEquals(false, results.getParameterBool("CompletedImmunization")) } @Test fun evaluateTestPassAsCQLOnQR2FromBundleTest() = runBlocking { val asset = jSONParser.parseResource(open("WHOQR2FHIRBundle.json")) as Bundle loadBundle(asset) val results = fhirOperator.evaluateLibrary( "http://localhost/Library/TestPass|1.0.0", patId(asset), setOf("CompletedImmunization", "GetFinalDose", "GetSingleDose", "GetAllModerna", "ModernaProtocol")) as Parameters assertNotEquals(Collections.EMPTY_LIST, results.getParameters("GetSingleDose")) assertEquals(Collections.EMPTY_LIST, results.getParameters("GetFinalDose")) assertEquals(true, results.getParameterBool("CompletedImmunization")) } @Test fun evaluateTestPassAsJSONOnQR2FromBundleTest() = runBlocking { val asset = jSONParser.parseResource(open("WHOQR2FHIRBundle.json")) as Bundle loadBundle(asset) val results = fhirOperator.evaluateLibrary( "http://localhost/Library/TestPass|1.0.0", patId(asset), setOf("CompletedImmunization", "GetFinalDose", "GetSingleDose", "GetAllModerna", "ModernaProtocol")) as Parameters assertNotEquals(Collections.EMPTY_LIST, results.getParameters("GetSingleDose")) assertEquals(Collections.EMPTY_LIST, results.getParameters("GetFinalDose")) assertEquals(true, results.getParameterBool("CompletedImmunization")) } @Test fun evaluateTestPassAsCQLOnSHCQR1FromBundleTest() = runBlocking { val asset = jSONParser.parseResource(open("SHCQR1FHIRBundle.json")) as Bundle loadBundle(asset) val results = fhirOperator.evaluateLibrary( "http://localhost/Library/TestPass|1.0.0", patId(asset), setOf("CompletedImmunization", "GetFinalDose", "GetSingleDose", "GetAllModerna", "ModernaProtocol")) as Parameters assertEquals(Collections.EMPTY_LIST, results.getParameters("GetSingleDose")) assertEquals(Collections.EMPTY_LIST, results.getParameters("GetFinalDose")) assertNotEquals(Collections.EMPTY_LIST, results.getParameters("GetAllModerna")) assertEquals(true, results.getParameterBool("ModernaProtocol")) assertEquals(true, results.getParameterBool("CompletedImmunization")) } }
0
Kotlin
3
9
0dc9d8b67da73ce6b93a62ee406f98ac7e2af9ce
6,071
ddcc-validator
Apache License 2.0
app/src/main/java/com/github/petrchatrny/puzzle8/view/SettingsFragment.kt
petrchatrny
360,829,380
false
null
package com.github.petrchatrny.puzzle8.view import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.ArrayAdapter import androidx.databinding.DataBindingUtil import androidx.fragment.app.Fragment import androidx.lifecycle.ViewModelProvider import com.github.petrchatrny.puzzle8.R import com.github.petrchatrny.puzzle8.databinding.SettingsFragmentBinding import com.github.petrchatrny.puzzle8.viewModel.SettingsViewModel class SettingsFragment : Fragment() { private lateinit var viewModel: SettingsViewModel private lateinit var binding: SettingsFragmentBinding override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View { binding = DataBindingUtil.inflate(inflater, R.layout.settings_fragment, container, false) binding.lifecycleOwner = this return binding.root } override fun onActivityCreated(savedInstanceState: Bundle?) { super.onActivityCreated(savedInstanceState) viewModel = ViewModelProvider(this).get(SettingsViewModel::class.java) binding.vm = viewModel // default setting setupSpinner() } private fun setupSpinner() { val layouts = resources.getStringArray(R.array.layout) val arrayAdapter = ArrayAdapter( requireContext(), R.layout.support_simple_spinner_dropdown_item, layouts ) binding.dropdownLayoutType.setAdapter(arrayAdapter) } }
0
Kotlin
0
0
82ef601d4f196f0bb0ac63f8ec5c51df12d4b3fc
1,572
puzzle8
MIT License
core/src/main/java/com/crocodic/core/base/viewmodel/CoreViewModel.kt
yzzzd
392,866,678
false
null
package com.crocodic.core.base.viewmodel import androidx.lifecycle.MutableLiveData import androidx.lifecycle.ViewModel import com.crocodic.core.api.ApiResponse import com.crocodic.core.base.activity.CoreActivity import kotlinx.coroutines.Job import org.greenrobot.eventbus.EventBus abstract class CoreViewModel : ViewModel() { val apiResponse = MutableLiveData<ApiResponse>() abstract fun apiRenewToken(): Job abstract fun apiLogout(): Job protected fun tokenSuccess() { EventBus.getDefault().post(CoreActivity.Companion.EVENT.RENEW_TOKEN) } protected fun logoutSuccess() { EventBus.getDefault().post(CoreActivity.Companion.EVENT.LOGGED_OUT) } }
0
Kotlin
3
2
c6ba04e78668497cac12d322bf46bf7cd65321ef
695
androidcore
Apache License 1.1
app/src/main/java/com/hotmail/or_dvir/appsfactory_lastfm/model/server_wrappers/ServerWrapperArtistsSearch.kt
or-dvir
380,747,630
false
null
package com.hotmail.or_dvir.appsfactory_lastfm.model.server_wrappers import com.hotmail.or_dvir.appsfactory_lastfm.model.Artist import com.squareup.moshi.Json import com.squareup.moshi.JsonClass /** * A wrapper class for the servers' response for retrieving search results for artists */ @JsonClass(generateAdapter = true) class ServerWrapperArtistsSearch( @Json(name = "results") val result: Result? ) { /** * returns the list of [Artist]s contained in this [ServerWrapperArtistsSearch] */ fun getArtistsSearchResults() = result?.matches?.artists /** * a helper class which represent part of the servers' structure of results when * searching for an [Artist] */ @JsonClass(generateAdapter = true) class Result( @Json(name = "artistmatches") val matches: ArtistMatches? ) /** * a helper class which represent part of the servers' structure of results when * searching for an [Artist]. This class holds teh actual list of [Artist]s */ @JsonClass(generateAdapter = true) class ArtistMatches( @Json(name = "artist") val artists: List<Artist> = listOf() ) }
0
Kotlin
0
1
1071c4177bbd64dce942364ecfd451675566ff0d
1,179
AppsFactory_LastFM
Apache License 2.0
app/src/main/java/com/xm/question/ui/question/model/QuestionItem.kt
jakal23
802,523,117
false
{"Kotlin": 46423}
package com.xm.question.ui.question.model data class QuestionItem( val id: Int, val question: String, val answer: String )
1
Kotlin
0
0
57c5ad8ca1d788c5f2bbff8e3bdd0625922dbf7e
136
XmQuestion
MIT License
dsl/src/main/kotlin/io/cloudshiftdev/awscdkdsl/services/qldb/CfnLedgerDsl.kt
cloudshiftinc
667,063,030
false
null
@file:Suppress( "RedundantVisibilityModifier", "RedundantUnitReturnType", "RemoveRedundantQualifierName", "unused", "UnusedImport", "ClassName", "REDUNDANT_PROJECTION", "DEPRECATION" ) package io.cloudshiftdev.awscdkdsl.services.qldb import io.cloudshiftdev.awscdkdsl.CfnTagDsl import io.cloudshiftdev.awscdkdsl.common.CdkDslMarker import kotlin.Boolean import kotlin.String import kotlin.Unit import kotlin.collections.Collection import kotlin.collections.MutableList import software.amazon.awscdk.CfnTag import software.amazon.awscdk.IResolvable import software.amazon.awscdk.services.qldb.CfnLedger import software.constructs.Construct /** * The `AWS::QLDB::Ledger` resource specifies a new Amazon Quantum Ledger Database (Amazon QLDB) * ledger in your AWS account . * * Amazon QLDB is a fully managed ledger database that provides a transparent, immutable, and * cryptographically verifiable transaction log owned by a central trusted authority. You can use * QLDB to track all application data changes, and maintain a complete and verifiable history of * changes over time. * * For more information, see * [CreateLedger](https://docs.aws.amazon.com/qldb/latest/developerguide/API_CreateLedger.html) in * the *Amazon QLDB API Reference* . * * Example: * ``` * // The code below shows an example of how to instantiate this type. * // The values are placeholders you should change. * import software.amazon.awscdk.services.qldb.*; * CfnLedger cfnLedger = CfnLedger.Builder.create(this, "MyCfnLedger") * .permissionsMode("permissionsMode") * // the properties below are optional * .deletionProtection(false) * .kmsKey("kmsKey") * .name("name") * .tags(List.of(CfnTag.builder() * .key("key") * .value("value") * .build())) * .build(); * ``` * * [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-qldb-ledger.html) */ @CdkDslMarker public class CfnLedgerDsl( scope: Construct, id: String, ) { private val cdkBuilder: CfnLedger.Builder = CfnLedger.Builder.create(scope, id) private val _tags: MutableList<CfnTag> = mutableListOf() /** * Specifies whether the ledger is protected from being deleted by any user. * * If not defined during ledger creation, this feature is enabled ( `true` ) by default. * * If deletion protection is enabled, you must first disable it before you can delete the * ledger. You can disable it by calling the `UpdateLedger` operation to set this parameter to * `false` . * * [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-qldb-ledger.html#cfn-qldb-ledger-deletionprotection) * * @param deletionProtection Specifies whether the ledger is protected from being deleted by any * user. */ public fun deletionProtection(deletionProtection: Boolean) { cdkBuilder.deletionProtection(deletionProtection) } /** * Specifies whether the ledger is protected from being deleted by any user. * * If not defined during ledger creation, this feature is enabled ( `true` ) by default. * * If deletion protection is enabled, you must first disable it before you can delete the * ledger. You can disable it by calling the `UpdateLedger` operation to set this parameter to * `false` . * * [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-qldb-ledger.html#cfn-qldb-ledger-deletionprotection) * * @param deletionProtection Specifies whether the ledger is protected from being deleted by any * user. */ public fun deletionProtection(deletionProtection: IResolvable) { cdkBuilder.deletionProtection(deletionProtection) } /** * The key in AWS Key Management Service ( AWS KMS ) to use for encryption of data at rest in * the ledger. * * For more information, see * [Encryption at rest](https://docs.aws.amazon.com/qldb/latest/developerguide/encryption-at-rest.html) * in the *Amazon QLDB Developer Guide* . * * Use one of the following options to specify this parameter: * * `AWS_OWNED_KMS_KEY` : Use an AWS KMS key that is owned and managed by AWS on your behalf. * * *Undefined* : By default, use an AWS owned KMS key. * * *A valid symmetric customer managed KMS key* : Use the specified symmetric encryption KMS * key in your account that you create, own, and manage. * * Amazon QLDB does not support asymmetric keys. For more information, see * [Using symmetric and asymmetric keys](https://docs.aws.amazon.com/kms/latest/developerguide/symmetric-asymmetric.html) * in the *AWS Key Management Service Developer Guide* . * * To specify a customer managed KMS key, you can use its key ID, Amazon Resource Name (ARN), * alias name, or alias ARN. When using an alias name, prefix it with `"alias/"` . To specify a * key in a different AWS account , you must use the key ARN or alias ARN. * * For example: * * Key ID: `<KEY>` * * Key ARN: `arn:aws:kms:us-east-2:111122223333:key/<KEY>` * * Alias name: `alias/ExampleAlias` * * Alias ARN: `arn:aws:kms:us-east-2:111122223333:alias/ExampleAlias` * * For more information, see * [Key identifiers (KeyId)](https://docs.aws.amazon.com/kms/latest/developerguide/concepts.html#key-id) * in the *AWS Key Management Service Developer Guide* . * * [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-qldb-ledger.html#cfn-qldb-ledger-kmskey) * * @param kmsKey The key in AWS Key Management Service ( AWS KMS ) to use for encryption of data * at rest in the ledger. */ public fun kmsKey(kmsKey: String) { cdkBuilder.kmsKey(kmsKey) } /** * The name of the ledger that you want to create. * * The name must be unique among all of the ledgers in your AWS account in the current Region. * * Naming constraints for ledger names are defined in * [Quotas in Amazon QLDB](https://docs.aws.amazon.com/qldb/latest/developerguide/limits.html#limits.naming) * in the *Amazon QLDB Developer Guide* . * * [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-qldb-ledger.html#cfn-qldb-ledger-name) * * @param name The name of the ledger that you want to create. */ public fun name(name: String) { cdkBuilder.name(name) } /** * The permissions mode to assign to the ledger that you want to create. * * This parameter can have one of the following values: * * `ALLOW_ALL` : A legacy permissions mode that enables access control with API-level * granularity for ledgers. * * This mode allows users who have the `SendCommand` API permission for this ledger to run all * PartiQL commands (hence, `ALLOW_ALL` ) on any tables in the specified ledger. This mode * disregards any table-level or command-level IAM permissions policies that you create for the * ledger. * * `STANDARD` : ( *Recommended* ) A permissions mode that enables access control with finer * granularity for ledgers, tables, and PartiQL commands. * * By default, this mode denies all user requests to run any PartiQL commands on any tables in * this ledger. To allow PartiQL commands to run, you must create IAM permissions policies for * specific table resources and PartiQL actions, in addition to the `SendCommand` API permission * for the ledger. For information, see * [Getting started with the standard permissions mode](https://docs.aws.amazon.com/qldb/latest/developerguide/getting-started-standard-mode.html) * in the *Amazon QLDB Developer Guide* . * * We strongly recommend using the `STANDARD` permissions mode to maximize the security of your * ledger data. * * [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-qldb-ledger.html#cfn-qldb-ledger-permissionsmode) * * @param permissionsMode The permissions mode to assign to the ledger that you want to create. */ public fun permissionsMode(permissionsMode: String) { cdkBuilder.permissionsMode(permissionsMode) } /** * An array of key-value pairs to apply to this resource. * * For more information, see * [Tag](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-resource-tags.html) * . * * [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-qldb-ledger.html#cfn-qldb-ledger-tags) * * @param tags An array of key-value pairs to apply to this resource. */ public fun tags(tags: CfnTagDsl.() -> Unit) { _tags.add(CfnTagDsl().apply(tags).build()) } /** * An array of key-value pairs to apply to this resource. * * For more information, see * [Tag](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-resource-tags.html) * . * * [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-qldb-ledger.html#cfn-qldb-ledger-tags) * * @param tags An array of key-value pairs to apply to this resource. */ public fun tags(tags: Collection<CfnTag>) { _tags.addAll(tags) } public fun build(): CfnLedger { if (_tags.isNotEmpty()) cdkBuilder.tags(_tags) return cdkBuilder.build() } }
3
null
0
3
c59c6292cf08f0fc3280d61e7f8cff813a608a62
9,658
awscdk-dsl-kotlin
Apache License 2.0
infrastructure/src/main/kotlin/dev/notypie/impl/command/InteractionPayloadParser.kt
TrulyNotMalware
810,739,918
false
{"Kotlin": 122649}
package dev.notypie.impl.command import dev.notypie.domain.command.dto.interactions.InteractionPayload interface InteractionPayloadParser { fun parseStringPayload(payload: String): InteractionPayload }
0
Kotlin
0
0
56215ac26b0a955b9dba5cbb304b8f00c68c0f1a
207
CodeCompanion
MIT License
src/main/kotlin/com/order/sample/order/infrastructure/json/ObjectMapperFactory.kt
gavageovanni
800,253,604
false
{"Kotlin": 7471}
package com.order.sample.order.infrastructure.json import com.fasterxml.jackson.databind.ObjectMapper import com.fasterxml.jackson.module.kotlin.KotlinModule import org.springframework.context.annotation.Bean import org.springframework.context.annotation.Configuration @Configuration class ObjectMapperFactory { @Bean fun objectMapper(): ObjectMapper { return ObjectMapper() .registerModule(KotlinModule()) } }
0
Kotlin
0
0
a107bb85360e6c1ceb956a10594f92e2036b254a
448
order-transaction-outbox-sample
MIT License
src/main/kotlin/io/nvtc/embeddedresources/project/task/service/TaskService.kt
cschaible
366,153,662
false
null
package io.nvtc.embeddedresources.project.task.service import io.nvtc.embeddedresources.project.task.model.TaskStatusEnum import io.nvtc.embeddedresources.project.task.repository.TaskRepository import java.util.* import org.springframework.data.domain.Pageable import org.springframework.stereotype.Service import org.springframework.transaction.annotation.Transactional @Service class TaskService(private val taskRepository: TaskRepository) { @Transactional(readOnly = true) fun findAllByProjectIdentifier(projectId: UUID, pageable: Pageable) = taskRepository.findAllByProjectIdentifier(projectId, pageable) @Transactional(readOnly = true) fun findAllByProjectIdentifierIn(projectIdentifiers: List<UUID>) = taskRepository.findAllByProjectIdentifierIn(projectIdentifiers) @Transactional(readOnly = true) fun findAll(pageable: Pageable) = taskRepository.findAllWithDetailsBy(pageable) @Transactional(readOnly = true) fun findOneWithDetailsByIdentifier(identifier: UUID) = taskRepository.findOneWithDetailsByIdentifier(identifier) @Transactional fun updateStatus(identifier: UUID, status: TaskStatusEnum) = taskRepository.findOneWithDetailsByIdentifier(identifier)?.let { it.status = status taskRepository.save(it) } }
0
Kotlin
0
2
508a06dbb5940ee9ad6f406b10935c2cc8fe8593
1,290
spring-hateoas-embedded-resources
MIT License
winmdj-core/src/main/kotlin/com/github/danielchemko/winmdj/core/autoobject/stubs/StubMethodSemanticsImpl.kt
danielchemko
774,741,943
false
{"Kotlin": 284901}
package com.github.danielchemko.winmdj.core.autoobject.stubs import com.github.danielchemko.winmdj.core.MdObjectMapper import com.github.danielchemko.winmdj.core.autoobject.BaseWinMdStub import com.github.danielchemko.winmdj.core.mdspec.CLRMetadataType import com.github.danielchemko.winmdj.core.mdspec.MethodSemantics import com.github.danielchemko.winmdj.core.mdspec.WinMdStub import com.github.danielchemko.winmdj.parser.WinMdNavigator import javax.annotation.processing.Generated /** * THIS FILE IS AUTOMATICALLY GENERATED BY RegenerateSubs.kt. DO NOT EDIT IT BY HAND */ @Generated class StubMethodSemanticsImpl( objectMapper: MdObjectMapper, navigator: WinMdNavigator, index: Int ) : MethodSemantics { val stub = BaseWinMdStub(objectMapper, navigator, index) override fun toString(): String { return "MethodSemantics/${getToken()}" } override fun getStub(): WinMdStub { return stub } override fun getRowNumber(): Int { return getStub().getRowNumber() } override fun getToken(): UInt { return stub.getToken(CLRMetadataType.METHOD_SEMANTICS) } override fun getOffset(): UInt { return stub.getObjectTableOffset(CLRMetadataType.METHOD_SEMANTICS, 0).toUInt() } override fun copy(rowNum: Int): StubMethodSemanticsImpl { return StubMethodSemanticsImpl::class.constructors.first() .call(stub.getObjectMapper(), stub.getNavigator(), rowNum) } override fun getAssociation(): com.github.danielchemko.winmdj.core.mdspec.HasSemantics? { return stub.lookupInterfaceReferent( CLRMetadataType.METHOD_SEMANTICS, 2, com.github.danielchemko.winmdj.core.mdspec.HasSemantics::class ) } override fun getAttribute(): java.util.BitSet { return stub.lookupBitset(CLRMetadataType.METHOD_SEMANTICS, 0) } override fun getMethod(): com.github.danielchemko.winmdj.core.mdspec.MethodDefinition? { return stub.lookupConcreteReferent( CLRMetadataType.METHOD_SEMANTICS, 1, com.github.danielchemko.winmdj.core.mdspec.MethodDefinition::class ) } }
0
Kotlin
0
0
0d2a72ee7ea6f0dc05803b06039a8ac8bfc0dbd0
2,192
winmdj
MIT License
app/src/main/java/com/hydrofish/app/api/WaterData.kt
HydroFish-Waterloo
748,731,716
false
{"Kotlin": 273974}
package com.hydrofish.app.api import java.text.DateFormat data class WaterData( val date: String, val water_amount: Int, )
3
Kotlin
0
0
eadfc258a70804250726e316fcbde37f50265d5a
133
HydroFish
MIT License
app/src/main/java/pudans/caturday/MainActivity.kt
pudans
361,904,294
false
null
package pudans.caturday import android.content.Intent import android.os.Bundle import androidx.activity.compose.setContent import androidx.appcompat.app.AppCompatActivity import androidx.compose.animation.AnimatedVisibility import androidx.compose.animation.AnimatedVisibilityScope import androidx.compose.animation.core.MutableTransitionState import androidx.compose.animation.fadeIn import androidx.compose.animation.fadeOut import androidx.compose.animation.slideInHorizontally import androidx.compose.animation.slideOutVertically import androidx.compose.foundation.ExperimentalFoundationApi import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.padding import androidx.compose.material.BottomNavigation import androidx.compose.material.BottomNavigationItem import androidx.compose.material.Icon import androidx.compose.material.Scaffold import androidx.compose.material.Text import androidx.compose.runtime.Composable import androidx.compose.runtime.getValue import androidx.compose.runtime.remember import androidx.compose.ui.Modifier import androidx.compose.ui.graphics.Color import androidx.compose.ui.res.stringResource import androidx.navigation.compose.NavHost import androidx.navigation.compose.composable import androidx.navigation.compose.currentBackStackEntryAsState import androidx.navigation.compose.rememberNavController import com.google.accompanist.pager.ExperimentalPagerApi import dagger.hilt.android.AndroidEntryPoint import pudans.caturday.ui.FeedScreen import pudans.caturday.ui.ProfileScreen import pudans.caturday.ui.theme.CaturdayTheme @ExperimentalFoundationApi @AndroidEntryPoint @ExperimentalPagerApi class MainActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContent { val navController = rememberNavController() CaturdayTheme { Scaffold( bottomBar = { BottomNavigation( backgroundColor = Color.Black ) { val navBackStackEntry by navController.currentBackStackEntryAsState() val currentRoute = navBackStackEntry?.destination?.route Screen.ITEMS.forEach { screen -> val isSelected = currentRoute == screen.route BottomNavigationItem( selectedContentColor = Color.Black, icon = { NavigationIcon(isSelected, screen) }, label = { NavigationLAbel(isSelected, screen) }, alwaysShowLabel = false, selected = isSelected, onClick = { if (screen != Screen.UploadVideo) { navController.navigate(screen.route) { popUpTo(navController.graph.startDestinationRoute!!) { saveState = true } launchSingleTop = true restoreState = true } } else { startActivity(Intent(this@MainActivity, UploadVideoActivity::class.java), intent.extras) } } ) } } } ) { innerPadding -> Box(modifier = Modifier.padding(innerPadding)) { NavHost(navController = navController, startDestination = Screen.Feed.route) { composable(Screen.Feed.route) { FeedTransitionAnimation { FeedScreen() } } composable(Screen.Profile.route) { ProfileTransitionAnimation { ProfileScreen() } } } } } } } } } @Composable private fun NavigationIcon(isSelected: Boolean, screen: Screen) { Icon( imageVector = if (isSelected) screen.selectedIcon else screen.defaultIcon, contentDescription = "", tint = Color.White ) } @Composable private fun NavigationLAbel(isSelected: Boolean, screen: Screen) { Text( text = stringResource(screen.resourceId), color = Color.White ) } @Composable fun ProfileTransitionAnimation(content: @Composable AnimatedVisibilityScope.() -> Unit) { AnimatedVisibility( visibleState = remember { MutableTransitionState(false).apply { targetState = true } }, enter = slideInHorizontally(initialOffsetX = { 400 }) + fadeIn(), exit = slideOutVertically() + fadeOut(), content = content, ) } @Composable fun FeedTransitionAnimation(content: @Composable AnimatedVisibilityScope.() -> Unit) { AnimatedVisibility( visibleState = remember { MutableTransitionState(false).apply { targetState = true } }, enter = slideInHorizontally(initialOffsetX = { -400 }) + fadeIn(), exit = slideOutVertically() + fadeOut(), content = content, ) }
0
Kotlin
0
1
1424495b57bc08a1cfc9ff3342aae3dbc5f95a26
4,411
Caturday
MIT License
educational-core/src/com/jetbrains/edu/learning/stepik/hyperskill/HyperskillCourseUpdater.kt
telezhnaya
264,863,128
true
{"Kotlin": 2477547, "Java": 634238, "HTML": 131915, "CSS": 12844, "Python": 3994, "JavaScript": 315}
package com.jetbrains.edu.learning.stepik.hyperskill import com.google.common.annotations.VisibleForTesting import com.intellij.notification.Notification import com.intellij.notification.NotificationType import com.intellij.openapi.application.invokeAndWaitIfNeeded import com.intellij.openapi.application.runWriteAction import com.intellij.openapi.diagnostic.Logger import com.intellij.openapi.project.Project import com.jetbrains.edu.coursecreator.CCUtils import com.jetbrains.edu.learning.* import com.jetbrains.edu.learning.courseFormat.CheckStatus import com.jetbrains.edu.learning.courseFormat.FrameworkLesson import com.jetbrains.edu.learning.courseFormat.Lesson import com.jetbrains.edu.learning.courseFormat.TaskFile import com.jetbrains.edu.learning.courseFormat.ext.configurator import com.jetbrains.edu.learning.courseFormat.ext.hasChangedFiles import com.jetbrains.edu.learning.courseFormat.ext.testDirs import com.jetbrains.edu.learning.courseFormat.tasks.Task import com.jetbrains.edu.learning.courseGeneration.GeneratorUtils import com.jetbrains.edu.learning.framework.FrameworkLessonManager import com.jetbrains.edu.learning.messages.EduCoreBundle import com.jetbrains.edu.learning.stepik.UPDATE_NOTIFICATION_GROUP_ID import com.jetbrains.edu.learning.stepik.hyperskill.api.HyperskillConnector import com.jetbrains.edu.learning.stepik.hyperskill.api.HyperskillProject import com.jetbrains.edu.learning.stepik.hyperskill.courseFormat.HyperskillCourse import com.jetbrains.edu.learning.stepik.hyperskill.settings.HyperskillSettings import com.jetbrains.edu.learning.stepik.isSignificantlyAfter import com.jetbrains.edu.learning.stepik.showUpdateAvailableNotification import com.jetbrains.edu.learning.yaml.YamlFormatSynchronizer import com.jetbrains.edu.learning.yaml.getConfigDir import java.io.IOException object HyperskillCourseUpdater { private val LOG: Logger = Logger.getInstance(HyperskillCourseUpdater::class.java) private fun HyperskillProject.getCourseFromServer(): HyperskillCourse? { val connector = HyperskillConnector.getInstance() val hyperskillProject = when (val response = connector.getProject(id)) { is Err -> return null is Ok -> response.value } val languageId = HYPERSKILL_LANGUAGES[hyperskillProject.language] ?: return null val eduEnvironment = eduEnvironment ?: return null val stagesFromServer = connector.getStages(id) ?: return null return HyperskillCourse(hyperskillProject, languageId, eduEnvironment).apply { stages = stagesFromServer val lessonFromServer = connector.getLesson(this, hyperskillProject.ideFiles) addLesson(lessonFromServer) init(this, null, false) } } @JvmStatic fun updateCourse(project: Project, course: HyperskillCourse, onFinish: () -> Unit) { runInBackground(project, EduCoreBundle.message("update.check")) { val projectLesson = course.getProjectLesson() val courseFromServer = course.hyperskillProject?.getCourseFromServer() val projectLessonShouldBeUpdated = courseFromServer != null && projectLesson?.shouldBeUpdated(project, courseFromServer) ?: false val codeChallengesUpdates = course.getProblemsLesson()?.getCodeChallengesUpdates() ?: emptyList() if (projectLessonShouldBeUpdated || codeChallengesUpdates.isNotEmpty()) { if (HyperskillSettings.INSTANCE.updateAutomatically) { doUpdate(project, course, courseFromServer, codeChallengesUpdates) } else { showUpdateAvailableNotification(project) { runInBackground(project, EduCoreBundle.message("update.process"), false) { doUpdate(project, course, courseFromServer, codeChallengesUpdates) } } } } onFinish() } } @VisibleForTesting fun Lesson.shouldBeUpdated(project: Project, remoteCourse: HyperskillCourse): Boolean { val tasksFromServer = remoteCourse.getProjectLesson()?.taskList ?: return false val localTasks = taskList return when { localTasks.size > tasksFromServer.size -> false localTasks.zip(tasksFromServer).any { (task, remoteTask) -> task.id != remoteTask.id } -> false localTasks.zip(tasksFromServer).any { (task, remoteTask) -> remoteTask.updateDate.isSignificantlyAfter(task.updateDate) } -> true needUpdateCourseAdditionalFiles(project, remoteCourse.additionalFiles) -> true else -> false } } private fun Lesson.getCodeChallengesUpdates(): List<TaskUpdate> { val tasksFromServer = HyperskillConnector.getInstance().getCodeChallenges(this.course, this, taskList.map { it.id }) val result = mutableListOf<TaskUpdate>() for (taskFromServer in tasksFromServer) { val localTask = getTask(taskFromServer.id) ?: continue if (taskFromServer.updateDate.isSignificantlyAfter(localTask.updateDate)) { result.add(TaskUpdate(localTask, taskFromServer)) } } return result } class TaskUpdate(val localTask: Task, val taskFromServer: Task) private fun needUpdateCourseAdditionalFiles(project: Project, remoteFiles: List<TaskFile>): Boolean { val courseDir = project.courseDir for (remoteFile in remoteFiles) { val needToUpdate = invokeAndWaitIfNeeded { runWriteAction { if (project.isDisposed) return@runWriteAction false val file = courseDir.findFileByRelativePath(remoteFile.name) ?: return@runWriteAction true val text = try { CCUtils.loadText(file) } catch (e: IOException) { LOG.warn("Failed to load text of `${remoteFile.name}` additional file", e) return@runWriteAction true } text != remoteFile.text } } if (needToUpdate) return true } return false } @JvmStatic @VisibleForTesting fun doUpdate(project: Project, localCourse: HyperskillCourse, remoteCourse: HyperskillCourse?, codeChallengesUpdates: List<TaskUpdate>) { updateProjectLesson(project, localCourse, remoteCourse) updateCodeChallenges(project, codeChallengesUpdates) showUpdateCompletedNotification(project) } private fun updateCodeChallenges(project: Project, codeChallengesUpdates: List<TaskUpdate>) { invokeAndWaitIfNeeded { if (project.isDisposed) { return@invokeAndWaitIfNeeded } codeChallengesUpdates.forEach { val localTask = it.localTask if (localTask.status != CheckStatus.Solved) { GeneratorUtils.createTaskContent(it.taskFromServer, localTask.getDir(project)!!) } updateTaskDescription(localTask, it.taskFromServer, project) localTask.updateDate = it.taskFromServer.updateDate YamlFormatSynchronizer.saveItemWithRemoteInfo(localTask) } } } private fun updateProjectLesson(project: Project, localCourse: HyperskillCourse, remoteCourse: HyperskillCourse?): Boolean { val lesson = localCourse.getProjectLesson() ?: return true val remoteLesson = remoteCourse?.getProjectLesson() ?: return true invokeAndWaitIfNeeded { if (project.isDisposed) return@invokeAndWaitIfNeeded for ((task, remoteTask) in lesson.taskList.zip(remoteLesson.taskList)) { if (!task.updateDate.before(remoteTask.updateDate)) continue if (task.status != CheckStatus.Solved) { updateFiles(localCourse, lesson, task, remoteTask, project) } updateTaskDescription(task, remoteTask, project) task.updateDate = remoteTask.updateDate YamlFormatSynchronizer.saveItemWithRemoteInfo(task) } val courseDir = project.courseDir for (additionalFile in remoteCourse.additionalFiles) { GeneratorUtils.createChildFile(courseDir, additionalFile.name, additionalFile.text) } } return false } private fun updateTaskDescription(task: Task, remoteTask: Task, project: Project) { task.descriptionText = remoteTask.descriptionText task.descriptionFormat = remoteTask.descriptionFormat // Task Description file needs to be regenerated as it already exists GeneratorUtils.createDescriptionFile(task.getConfigDir(project), task) ?: return } private fun updateFiles(currentCourse: HyperskillCourse, lesson: FrameworkLesson, task: Task, remoteTask: Task, project: Project) { fun updateTaskFiles( task: Task, remoteTaskFiles: Map<String, TaskFile>, updateInLocalFS: Boolean ) { val taskFiles = task.taskFiles for ((path, remoteTaskFile) in remoteTaskFiles) { val taskFile = taskFiles[path] val currentTaskFile = if (taskFile != null) { taskFile.setText(remoteTaskFile.text) taskFile } else { task.addTaskFile(remoteTaskFile) remoteTaskFile } if (updateInLocalFS) { val taskDir = task.getTaskDir(project) if (taskDir != null) { GeneratorUtils.createChildFile(taskDir, path, currentTaskFile.text) } } } task.init(currentCourse, lesson, false) } val flm = FrameworkLessonManager.getInstance(project) if (lesson.currentTaskIndex != task.index - 1) { updateTaskFiles(task, remoteTask.testFiles, false) flm.updateUserChanges(task, task.taskFiles.mapValues { (_, taskFile) -> taskFile.text }) } else { // With current logic of next/prev action for hyperskill tasks // update of non test files makes sense only for first task if (task.index == 1 && !task.hasChangedFiles(project)) { updateTaskFiles(task, remoteTask.taskFiles, true) } else { updateTaskFiles(task, remoteTask.testFiles, true) } } } private fun showUpdateCompletedNotification(project: Project) { Notification(UPDATE_NOTIFICATION_GROUP_ID, EduCoreBundle.message("hyperskill.update.notification.title"), EduCoreBundle.message("hyperskill.update.notification.text", EduNames.JBA), NotificationType.INFORMATION).notify(project) } } private val Task.testFiles: Map<String, TaskFile> get() { val testDirs = lesson.course.testDirs val defaultTestName = lesson.course.configurator?.testFileName ?: "" return taskFiles.filterKeys { path -> path == defaultTestName || testDirs.any { path.startsWith(it) } } }
0
null
0
0
9f9492f7505fb86df37c9d582814c075aa3a611d
10,396
educational-plugin
Apache License 2.0
app/src/main/java/com/smartherd/msgshareapp/AppConstants.kt
AshishBhoi
152,084,574
false
null
package com.smartherd.msgshareapp object Constants { const val USER_MSG_KEY = "user_message" }
0
Kotlin
0
0
4e403bea091eaf29d096361d6a81fae5c1d9be53
99
KotlinApp1
MIT License
app/src/main/java/de/dhbw/mensaapp/ui/components/input/AnimatedChangingText.kt
SteveBinary
621,552,225
false
null
package de.dhbw.mensaapp.ui.components.input import androidx.compose.animation.* import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.material3.MaterialTheme import androidx.compose.material3.Text import androidx.compose.runtime.* import androidx.compose.runtime.saveable.rememberSaveable import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.text.style.TextAlign import androidx.compose.ui.unit.sp @OptIn(ExperimentalAnimationApi::class) @Composable fun <T : Comparable<T>> AnimatedChangingText(value: T) { var oldValue by rememberSaveable { mutableStateOf(value) } SideEffect { oldValue = value } Row( modifier = Modifier.fillMaxWidth(), verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.Center ) { val valueString = value.toString() val oldValueString = oldValue.toString() for (i in valueString.indices) { val newChar = valueString[i] val oldChar = oldValueString.getOrNull(i) val charToAnimate = if (oldChar == newChar) { oldValueString[i] } else { valueString[i] } AnimatedContent( targetState = charToAnimate, transitionSpec = { if (oldValue <= value) { slideInVertically { it } with slideOutVertically { -it } } else { slideInVertically { -it } with slideOutVertically { it } } } ) { char -> Text( text = char.toString(), textAlign = TextAlign.Center, fontWeight = FontWeight.Bold, fontSize = 20.sp, color = MaterialTheme.colorScheme.onBackground, softWrap = false ) } } } }
0
Kotlin
0
1
5e581880c96c54b0b20b2bb85e0c13c46157a822
2,171
mensa-app
MIT License
app/src/main/java/com/vension/mvp/ui/activitys/ProxyAvtivity.kt
Vension
127,116,341
false
null
package com.vension.mvp.ui.activitys import android.os.Bundle import android.support.v4.app.Fragment import android.text.TextUtils import android.view.WindowManager import com.vension.frame.base.V_BaseFragment import com.vension.frame.stacks.observers.ActivityObserver import com.vension.frame.utils.VLogUtil import com.vension.mvp.R import com.vension.mvp.base.BaseActivity import com.vension.mvp.utils.Constants /** * ======================================================== * 作 者:Vension * 日 期:2018/4/2 16:00 * 描 述:代理Activity * ======================================================== */ class ProxyAvtivity : BaseActivity() { private var mFragment: V_BaseFragment? = null override fun attachLayoutRes(): Int { return R.layout.activity_proxy } override fun initViewAndData(savedInstanceState: Bundle?) { try { window.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE) // setup main fragment val fBundle = intent.extras val fFragmentClass = fBundle.getString(Constants.AGENT_FRAGMENT_CLASS_KEY) if (!TextUtils.isEmpty(fFragmentClass)) { //状态栏是否可见 // if (!fBundle.containsKey(Constant.AGENT_TOOLBAR_DIAPLAY)) { // fBundle.putBoolean(Constant.AGENT_TOOLBAR_DIAPLAY, true) // } // //返回按钮是否显示 // if (!fBundle.containsKey(Constant.AGENT_TOOLBAR_BACK_ENABLE)) { // fBundle.putBoolean(Constant.AGENT_TOOLBAR_BACK_ENABLE, true) // } mFragment = Class.forName(fFragmentClass).newInstance() as V_BaseFragment mFragment?.arguments = fBundle mFragment?.let { setMainFragment(it) } } } catch (e: Exception) { ActivityObserver.getInstance().unregist(this)//activity出栈 finish() } } override fun requestLoadData() { } private fun setMainFragment(fragment: Fragment) { setMainFragment(fragment, 0, 0) } private fun setMainFragment(fragment: Fragment, enterAnim: Int, exitAnim: Int) { if (!this.isFinishing) { val mFragmentTransaction = supportFragmentManager.beginTransaction() if (enterAnim != 0 && exitAnim != 0) { mFragmentTransaction.setCustomAnimations(enterAnim, exitAnim) } mFragmentTransaction.replace(R.id.agent_content, fragment) mFragmentTransaction.commitAllowingStateLoss() VLogUtil.e("setMainFragment==>" + fragment) } } override fun onDestroy() { super.onDestroy() if (mFragment != null) mFragment = null } }
1
null
1
1
efa939c0325b1b05fad235a1314d87f9d3dc1338
2,738
KV-MVP-Frame
Apache License 2.0
src/test/kotlin/io/andrewohara/awsmock/dynamodb/v2/V2GetItemUnitTest.kt
oharaandrew314
276,702,915
false
{"Kotlin": 459818}
package io.andrewohara.awsmock.dynamodb.v2 import io.andrewohara.awsmock.dynamodb.DynamoFixtures import io.andrewohara.awsmock.dynamodb.DynamoUtils.createCatsTable import io.andrewohara.awsmock.dynamodb.MockDynamoDbV2 import io.andrewohara.awsmock.dynamodb.MockDynamoDbV2.Companion.toV2 import io.andrewohara.awsmock.dynamodb.backend.MockDynamoBackend import io.andrewohara.awsmock.dynamodb.backend.MockDynamoItem import io.andrewohara.awsmock.dynamodb.backend.MockDynamoValue import io.kotest.assertions.throwables.shouldThrow import io.kotest.matchers.shouldBe import org.junit.jupiter.api.Test import software.amazon.awssdk.services.dynamodb.model.AttributeValue import software.amazon.awssdk.services.dynamodb.model.GetItemResponse import software.amazon.awssdk.services.dynamodb.model.ResourceNotFoundException class V2GetItemUnitTest { private val backend = MockDynamoBackend() private val client = MockDynamoDbV2(backend) private val table = backend.createCatsTable() @Test fun `get item from missing table`() { shouldThrow<ResourceNotFoundException> { client.getItem { it.tableName("missing") it.key(DynamoFixtures.togglesKey.toV2()) } } } @Test fun `get missing item`() { client.getItem { it.tableName(table.name) it.key(DynamoFixtures.togglesKey.toV2()) } shouldBe GetItemResponse.builder() .build() } @Test fun `get item`() { table.save(DynamoFixtures.toggles) client.getItem { it.tableName(table.name) it.key(DynamoFixtures.togglesKey.toV2()) } shouldBe GetItemResponse.builder() .item(DynamoFixtures.toggles.toV2()) .build() } @Test fun `get item with null attribute`() { val item = MockDynamoItem( "ownerId" to MockDynamoValue(n = 2), "name" to MockDynamoValue(s = "Toggles"), "age" to MockDynamoValue() ) table.save(item) client.getItem { it.tableName(table.name) it.key(item.toV2()) } shouldBe GetItemResponse.builder() .item(mapOf( "ownerId" to AttributeValue.builder().n("2").build(), "name" to AttributeValue.builder().s("Toggles").build(), "age" to AttributeValue.builder().nul(true).build() )).build() } }
0
Kotlin
1
5
abd135f64f0f6e5fdfce8ae8a30f0d8dd9166751
2,463
mock-aws-java-sdk
Apache License 2.0
Android/NewsFresh/app/src/main/java/com/example/newsfresh/MainActivity.kt
PrathmeshMutke
414,063,795
false
{"Markdown": 11, "YAML": 6, "C++": 23, "Text": 2, "Ignore List": 5, "Dart": 29, "Java": 16, "C": 3, "Go": 10, "Gradle": 3, "Java Properties": 2, "Shell": 1, "Batchfile": 1, "Proguard": 1, "Kotlin": 6, "XML": 18, "JavaScript": 2, "Python": 13}
package com.example.newsfresh import android.net.Uri import androidx.appcompat.app.AppCompatActivity import android.os.Bundle import android.widget.Toast import androidx.browser.customtabs.CustomTabsIntent import androidx.recyclerview.widget.LinearLayoutManager import androidx.recyclerview.widget.RecyclerView import com.android.volley.Request import com.android.volley.Response import com.android.volley.toolbox.JsonObjectRequest import com.android.volley.toolbox.RequestFuture class MainActivity : AppCompatActivity(), NewsItemClicked { private lateinit var mAdapter: NewsListAdapter override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) val recyclerView: RecyclerView = findViewById(R.id.recycler_view) recyclerView.layoutManager = LinearLayoutManager(this) fetchData() mAdapter = NewsListAdapter(this) recyclerView.adapter = mAdapter } private fun fetchData() { val url = "https://saurav.tech/NewsAPI/top-headlines/category/health/in.json" val jsonObjectRequest = JsonObjectRequest( Request.Method.GET, url, null, { val newsJsonArray = it.getJSONArray("articles") val newsArray = ArrayList<News>() for (i in 0 until newsJsonArray.length()) { val newJsonObject = newsJsonArray.getJSONObject(i) val news = News( newJsonObject.getString("title"), newJsonObject.getString("author"), newJsonObject.getString("url"), newJsonObject.getString("urlToImage") ) newsArray.add(news) } mAdapter.updateNews(newsArray) }, { Toast.makeText(this, "Check you internet connection", Toast.LENGTH_LONG).show() } ) MySingleton.getInstance(this).addToRequestQueue(jsonObjectRequest) } override fun onItemClicked(item: News) { val builder = CustomTabsIntent.Builder(); val customTabsIntent = builder.build(); customTabsIntent.launchUrl(this, Uri.parse(item.url)); } }
1
null
1
1
8e2efde35afe81b829f78a1c279637864a70c77f
2,314
HacktoberFest-2021
MIT License
Helpers/src/main/java/com/dg/helpers/LocationHelper.kt
MilliDevX
195,803,662
true
{"Kotlin": 102081}
package com.dg.helpers @Suppress("unused") object LocationHelper { private const val R = 6371.0 private const val M_PI = Math.PI private const val DEG_TO_RAD = M_PI / 180.0 /** * Calculates the distance between the specified locations * @param latitude1 * @param longitude1 * @param latitude2 * @param longitude2 * @return Distance in kilometers */ fun getDistanceBetweenCoordinates( latitude1: Double, longitude1: Double, latitude2: Double, longitude2: Double): Double { var lat1 = latitude1 var lon1 = longitude1 var lat2 = latitude2 var lon2 = longitude2 lat1 *= DEG_TO_RAD lon1 *= DEG_TO_RAD lat2 *= DEG_TO_RAD lon2 *= DEG_TO_RAD val latDelta = lat2 - lat1 val longitudeDelta = lon2 - lon1 val a = Math.sin(latDelta / 2.0) * Math.sin(latDelta / 2.0) + Math.cos(lat1) * Math.cos(lat2) * Math.sin(longitudeDelta / 2.0) * Math.sin(longitudeDelta / 2.0) val c = 2.0 * Math.atan2(Math.sqrt(a), Math.sqrt(1.0 - a)) return R * c // Kilometers } }
0
Kotlin
0
0
bf461fd679287685bab0efe9abed5ec831cd7f1f
1,154
android-helpers
MIT License
app/src/androidTest/java/com/alishatergholi/db/ProductDaoTest.kt
alishatergholi
174,831,065
false
null
package com.alishatergholi.db import androidx.arch.core.executor.testing.InstantTaskExecutorRule import androidx.test.platform.app.InstrumentationRegistry import androidx.test.runner.AndroidJUnit4 import com.alishatergholi.db.dao.ProductDao import com.alishatergholi.utils.LiveDataTestUtil import org.junit.Assert.* import com.alishatergholi.db.TestData.Companion.product_Entity import com.alishatergholi.db.TestData.Companion.products import org.junit.* import org.junit.runner.RunWith import org.junit.runners.MethodSorters @RunWith(AndroidJUnit4::class) @FixMethodOrder(MethodSorters.NAME_ASCENDING) class ProductDaoTest { @Rule @JvmField var instant = InstantTaskExecutorRule() var database : AppDataBase? = null var productDao : ProductDao? = null @Before fun initDatabase() { database = AppDataBase.getInstance(InstrumentationRegistry.getInstrumentation().context,null,true) productDao = database!!.productDao() } @After fun closeDatabase(){ database!!.close() } @Test fun step1_getProductWhenNoProductInserted(){ productDao!!.deleteAll() val items = LiveDataTestUtil.getValue(productDao!!.loadAllProducts()) assertTrue(items.isEmpty()) } @Test fun step2_getProductAfterInserted(){ productDao!!.insertAll(products) val items = LiveDataTestUtil.getValue(productDao!!.loadAllProducts()) assertTrue(items.size == products.size) } @Test fun step3_getProductById(){ val product = productDao!!.loadProductSync(product_Entity.id) assertEquals(product.id , product_Entity.id) assertEquals(product.name , product_Entity.name) assertEquals(product.description , product_Entity.description) assertEquals(product.price , product_Entity.price) } }
1
Kotlin
1
4
abd7b47fdad17ca8fd62b79692347b35dfa42314
1,894
android-architecture-components
MIT License
anvil-design/src/gen-material-1.2.0-alpha04/kotlin/dev/inkremental/dsl/google/android/material/bottomnavigation/BottomNavigationItemView.kt
inkremental
205,363,267
true
null
@file:Suppress("DEPRECATION", "UNCHECKED_CAST", "MemberVisibilityCanBePrivate", "unused") package dev.inkremental.dsl.google.android.material.bottomnavigation import com.google.android.material.bottomnavigation.BottomNavigationItemView import dev.inkremental.Inkremental import dev.inkremental.bind import dev.inkremental.dsl.android.widget.FrameLayoutScope import dev.inkremental.dsl.google.android.material.CustomMaterialSetter import dev.inkremental.dsl.google.android.material.MaterialSetter import dev.inkremental.v import kotlin.Suppress import kotlin.Unit fun bottomNavigationItemView(configure: BottomNavigationItemViewScope.() -> Unit = {}) = v<BottomNavigationItemView>(configure.bind(BottomNavigationItemViewScope)) abstract class BottomNavigationItemViewScope : FrameLayoutScope() { companion object : BottomNavigationItemViewScope() { init { Inkremental.registerAttributeSetter(MaterialSetter) Inkremental.registerAttributeSetter(CustomMaterialSetter) } } }
20
Kotlin
5
58
6e6241a0e9ac80a1edd1f0e100ad6bf0c4f8175e
1,002
inkremental
MIT License
shared/src/commonMain/kotlin/com/rvcoding/imhere/data/local/DataStoreFactory.kt
revs87
842,125,970
false
{"Kotlin": 137015, "Swift": 621, "HTML": 332, "CSS": 102}
package com.rvcoding.imhere.data.local import androidx.datastore.core.DataStore import androidx.datastore.preferences.core.PreferenceDataStoreFactory import androidx.datastore.preferences.core.Preferences import com.rvcoding.imhere.domain.data.local.DataStoreFactory import okio.Path.Companion.toPath expect fun getDataStoreFilePath(): String class DataStoreFactoryImpl : DataStoreFactory { override fun dataStore(): DataStore<Preferences> = PreferenceDataStoreFactory.createWithPath( produceFile = { getDataStoreFilePath().toPath() } ) }
0
Kotlin
0
0
3276a4a97d5da205251e2bc4c4bb3f37d27ae773
574
imhere-cmp
Apache License 2.0
core/src/commonMain/kotlin/dev/carlsen/flagkit/flagicons/AE.kt
acarlsen
722,319,804
false
{"Kotlin": 1629077, "Batchfile": 2673, "Swift": 590}
package dev.carlsen.flagkit.flagicons import androidx.compose.ui.geometry.Offset import androidx.compose.ui.graphics.Brush.Companion.linearGradient import androidx.compose.ui.graphics.Color import androidx.compose.ui.graphics.PathFillType.Companion.EvenOdd import androidx.compose.ui.graphics.SolidColor import androidx.compose.ui.graphics.StrokeCap.Companion.Butt import androidx.compose.ui.graphics.StrokeJoin.Companion.Miter import androidx.compose.ui.graphics.vector.ImageVector import androidx.compose.ui.graphics.vector.ImageVector.Builder import androidx.compose.ui.graphics.vector.path import androidx.compose.ui.unit.dp import dev.carlsen.flagkit.FlagIcons val FlagIcons.AE: ImageVector get() { if (_ae != null) { return _ae!! } _ae = Builder(name = "Ae", defaultWidth = 21.0.dp, defaultHeight = 15.0.dp, viewportWidth = 21.0f, viewportHeight = 15.0f).apply { path(fill = linearGradient(0.0f to Color(0xFFFFFFFF), 1.0f to Color(0xFFF0F0F0), start = Offset(10.5f,0.0f), end = Offset(10.5f,15.0f)), stroke = SolidColor(Color(0x00000000)), strokeLineWidth = 1.0f, strokeLineCap = Butt, strokeLineJoin = Miter, strokeLineMiter = 4.0f, pathFillType = EvenOdd) { moveTo(0.0f, 0.0f) horizontalLineToRelative(21.0f) verticalLineToRelative(15.0f) horizontalLineToRelative(-21.0f) close() } path(fill = linearGradient(0.0f to Color(0xFF12833B), 1.0f to Color(0xFF0D7332), start = Offset(13.5f,0.0f), end = Offset(13.5f,5.0f)), stroke = SolidColor(Color(0x00000000)), strokeLineWidth = 1.0f, strokeLineCap = Butt, strokeLineJoin = Miter, strokeLineMiter = 4.0f, pathFillType = EvenOdd) { moveTo(6.0f, 0.0f) horizontalLineToRelative(15.0f) verticalLineToRelative(5.0f) horizontalLineToRelative(-15.0f) close() } path(fill = linearGradient(0.0f to Color(0xFF262626), 1.0f to Color(0xFF0D0D0D), start = Offset(13.5f,10.0f), end = Offset(13.5f,15.0f)), stroke = SolidColor(Color(0x00000000)), strokeLineWidth = 1.0f, strokeLineCap = Butt, strokeLineJoin = Miter, strokeLineMiter = 4.0f, pathFillType = EvenOdd) { moveTo(6.0f, 10.0f) horizontalLineToRelative(15.0f) verticalLineToRelative(5.0f) horizontalLineToRelative(-15.0f) close() } path(fill = linearGradient(0.0f to Color(0xFFFFFFFF), 1.0f to Color(0xFFF0F0F0), start = Offset(13.5f,5.0f), end = Offset(13.5f,10.0f)), stroke = SolidColor(Color(0x00000000)), strokeLineWidth = 1.0f, strokeLineCap = Butt, strokeLineJoin = Miter, strokeLineMiter = 4.0f, pathFillType = EvenOdd) { moveTo(6.0f, 5.0f) horizontalLineToRelative(15.0f) verticalLineToRelative(5.0f) horizontalLineToRelative(-15.0f) close() } path(fill = linearGradient(0.0f to Color(0xFFFF323E), 1.0f to Color(0xFFFD0D1B), start = Offset(3.0f,0.0f), end = Offset(3.0f,15.0f)), stroke = SolidColor(Color(0x00000000)), strokeLineWidth = 1.0f, strokeLineCap = Butt, strokeLineJoin = Miter, strokeLineMiter = 4.0f, pathFillType = EvenOdd) { moveTo(0.0f, 0.0f) horizontalLineToRelative(6.0f) verticalLineToRelative(15.0f) horizontalLineToRelative(-6.0f) close() } } .build() return _ae!! } private var _ae: ImageVector? = null
0
Kotlin
1
21
a630a5cdbb9749db3d83ad3b751740da42d84e16
3,938
kmp-flagkit
MIT License
app/src/main/java/com/github/hailouwang/demosforapi/widget/recyclerview/test8/ChildRecyclerView.kt
lichang2464
293,675,010
true
{"Java": 4039904, "Dart": 125017, "Kotlin": 101373, "HTML": 64658, "Ruby": 4167, "C": 1889, "Groovy": 1869, "Swift": 949, "Objective-C": 785, "CMake": 228}
package com.github.hailouwang.demosforapi.widget.recyclerview.test8; import android.content.Context import android.util.AttributeSet import android.util.Log import android.view.MotionEvent import androidx.recyclerview.widget.RecyclerView import com.github.hailouwang.demosforapi.widget.recyclerview.test8.helper.FlingHelper import com.github.hailouwang.demosforapi.widget.recyclerview.test8.utils.UIUtils open class ChildRecyclerView @JvmOverloads constructor(context: Context, attrs: AttributeSet? = null, defStyleAttr: Int = 0) : RecyclerView(context, attrs, defStyleAttr) { private val mFlingHelper = FlingHelper(context) private var mMaxDistance = 0 private var mVelocityY = 0 var isStartFling: Boolean = false var totalDy: Int = 0 var mParentRecyclerView:ParentRecyclerView? = null init { mMaxDistance = mFlingHelper.getVelocityByDistance((UIUtils.getScreenHeight() * 4).toDouble()) overScrollMode = RecyclerView.OVER_SCROLL_NEVER initScrollListener() } private fun initScrollListener() { addOnScrollListener(object :OnScrollListener() { override fun onScrolled(recyclerView: RecyclerView, dx: Int, dy: Int) { super.onScrolled(recyclerView, dx, dy) Log.d("hlwang", "ChildRecyclerView initScrollListener addOnScrollListener isStartFling : " + isStartFling + ", totalDy : " + totalDy); if(isStartFling) { totalDy = 0 isStartFling = false } totalDy += dy } override fun onScrollStateChanged(recyclerView: RecyclerView, newState: Int) { Log.d("hlwang", "ChildRecyclerView initScrollListener onScrollStateChanged newState : "+newState + ", newState : " + isStartFling + ", totalDy : " + totalDy); if(newState == RecyclerView.SCROLL_STATE_IDLE) { dispatchParentFling() } super.onScrollStateChanged(recyclerView, newState) } }) } private fun dispatchParentFling() { mParentRecyclerView = findParentRecyclerView() mParentRecyclerView?.run { if(isScrollTop() && mVelocityY != 0) { //当前ChildRecyclerView已经滑动到顶部,且竖直方向加速度不为0,如果有多余的需要交由父RecyclerView继续fling val flingDistance = mFlingHelper.getSplineFlingDistance(mVelocityY) Log.d("hlwang", "ChildRecyclerView dispatchParentFling flingDistance : "+flingDistance +", mVelocityY : "+mVelocityY + ", newState : " + isStartFling + ", totalDy : " + totalDy +", velY : "+mFlingHelper.getVelocityByDistance(flingDistance + totalDy)); if(flingDistance > (Math.abs(totalDy))) { fling(0,-mFlingHelper.getVelocityByDistance(flingDistance + totalDy)) } totalDy = 0 mVelocityY = 0 } } } override fun dispatchTouchEvent(ev: MotionEvent?): Boolean { if(ev != null && ev.action == MotionEvent.ACTION_DOWN) { mVelocityY = 0 } return super.dispatchTouchEvent(ev) } override fun fling(velocityX: Int, velocityY: Int): Boolean { if(isAttachedToWindow.not()) return false val fling = super.fling(velocityX, velocityY) if(!fling || velocityY >= 0) { //fling为false表示加速度达不到fling的要求,将mVelocityY重置 mVelocityY = 0 } else { //正在进行fling isStartFling = true mVelocityY = velocityY } return fling } fun isScrollTop(): Boolean { var isScrollTop:Boolean = !canScrollVertically(-1) Log.d("hlwang", "ChildRecyclerView isScrollTop isScrollTop : " + isScrollTop); //RecyclerView.canScrollVertically(-1)的值表示是否能向下滚动,false表示已经滚动到顶部 return isScrollTop } private fun findParentRecyclerView():ParentRecyclerView? { var parentView = parent while ((parentView is ParentRecyclerView).not()) { parentView = parentView.parent } return parentView as? ParentRecyclerView } }
0
null
0
1
cdd5583c6aa34414ae59528357b9b20545b36d4b
4,330
AndroidGo
Apache License 2.0
app/src/androidTest/java/com/example/android/hilt/CustomTestRunner.kt
MesumAli2
582,915,798
false
null
package com.example.android.hilt import android.app.Application import android.content.Context import androidx.test.runner.AndroidJUnit4 import androidx.test.runner.AndroidJUnitRunner import dagger.hilt.android.HiltAndroidApp import dagger.hilt.android.testing.HiltTestApplication import org.junit.runner.RunWith class CustomTestRunner : AndroidJUnitRunner() { override fun newApplication( cl: ClassLoader?, className: String?, context: Context? ): Application { return super.newApplication(cl, HiltTestApplication::class.java.name, context) } }
0
Kotlin
0
0
eda7801da47310bcd2654f565f8ce35366e79423
593
android-hilt-main
Apache License 2.0
src/main/kotlin/no/nav/syfo/metrics/MetricRegister.kt
navikt
192,487,799
false
null
package no.nav.syfo.metrics import io.prometheus.client.Counter const val METRICS_NS = "syfostorebror" val SM_OVERVAKET: Counter = Counter.build() .namespace(METRICS_NS) .name("sykmelding_overvaket_count") .help("Antall sykmeldinger talt og prosessert av syfostorebror") .register()
0
Kotlin
0
0
bd28722af77b5ceb2fa6c521fb2a7459d6badf0a
318
syfostorebror
MIT License
appupdater/src/main/java/ir/heydarii/appupdater/stores/MyketStore.kt
TrendingTechnology
206,951,842
true
{"Kotlin": 26544, "Java": 1151}
package ir.heydarii.appupdater.stores import android.content.Context import android.content.Intent import android.net.Uri import ir.heydarii.appupdater.pojomodel.Store import ir.heydarii.appupdater.pojomodel.UpdaterStoreList /** * shows apk in bazaar store */ class MyketStore : Stores() { override fun setStoreData(context: Context?, item: UpdaterStoreList) { val intent = Intent() intent.action = Intent.ACTION_VIEW intent.data = Uri.parse("myket://details?id=${item.packageName}") showStore(context, intent, item, Store.MYKET) } }
0
null
0
0
ec2c54dbef4706c2a717e0794e096ece92d83f50
577
AndroidAppUpdater
Apache License 2.0
compiler/src/main/kotlin/edu/cornell/cs/apl/viaduct/errors/UndefinedNameError.kt
apl-cornell
169,159,978
false
null
package edu.cornell.cs.apl.viaduct.errors import edu.cornell.cs.apl.prettyprinting.Document import edu.cornell.cs.apl.prettyprinting.plus import edu.cornell.cs.apl.prettyprinting.times import edu.cornell.cs.apl.viaduct.syntax.Located import edu.cornell.cs.apl.viaduct.syntax.Name import edu.cornell.cs.apl.viaduct.syntax.SourceLocation /** Thrown when a [Name] is referenced before it is defined. */ class UndefinedNameError(name: Located<Name>) : CompilationError() { private val name: Name = name.value private val location: SourceLocation = name.sourceLocation override val category: String get() = "Naming Error" override val source: String get() = location.sourcePath override val description: Document get() = // TODO: show similar names in context ("Did you mean: ...") (Document("I cannot find") * name.nameCategory * name + ":") .withSource(location) }
20
Kotlin
4
11
2352c676305c595d235bc9024770fc622efb8aa2
951
viaduct
MIT License
io/http/src/test/kotlin/io/bluetape4k/http/hc5/examples/ClientMultiThreadedExecution.kt
debop
625,161,599
false
{"Kotlin": 7504333, "HTML": 502995, "Java": 2273, "JavaScript": 1351, "Shell": 1301, "CSS": 444, "Dockerfile": 121, "Mustache": 82}
package io.bluetape4k.http.hc5.examples import io.bluetape4k.http.hc5.AbstractHc5Test import io.bluetape4k.http.hc5.classic.httpClientConnectionManager import io.bluetape4k.http.hc5.classic.httpClientOf import io.bluetape4k.junit5.concurrency.MultithreadingTester import io.bluetape4k.logging.KLogging import io.bluetape4k.logging.debug import io.bluetape4k.logging.error import org.apache.hc.client5.http.classic.methods.HttpGet import org.apache.hc.client5.http.impl.classic.CloseableHttpClient import org.apache.hc.core5.http.io.entity.EntityUtils import org.junit.jupiter.api.Test class ClientMultiThreadedExecution: AbstractHc5Test() { companion object: KLogging() // Create an HttpClient with the PoolingHttpClientConnectionManager. // This connection manager must be used if more than one thread will // be using the HttpClient. private val cm = httpClientConnectionManager { setMaxConnTotal(100) } @Test fun `execute get in multi threading`() { val httpclient = httpClientOf(cm) httpclient.use { MultithreadingTester() .numThreads(6) .roundsPerThread(2) .add { executeHttpGet(httpclient, urisToGet[0], 0) } .add { executeHttpGet(httpclient, urisToGet[1], 1) } .add { executeHttpGet(httpclient, urisToGet[2], 2) } .run() } } private fun executeHttpGet(httpclient: CloseableHttpClient, uriToGet: String, id: Int) { try { val httpget = HttpGet(uriToGet) log.debug { "get execute to get $uriToGet[$id]" } // Multi threading 환경에서 사용 시에는 response.entity 를 읽어서 원하는 수형으로 변환해서 반환해야 합니다. // 아니면 response 를 바로 반환하면, input stream 이 공유 되어버립니다. httpclient.execute(httpget) { response -> val entity = response.entity if (entity != null) { val bytes = EntityUtils.toByteArray(entity) log.debug { "$id - ${bytes.size} bytes read" } } } } catch (e: Exception) { log.error(e) { "Fail to get url. $uriToGet[$id]" } } } }
0
Kotlin
0
1
ce3da5b6bddadd29271303840d334b71db7766d2
2,304
bluetape4k
MIT License
bcmc/src/main/java/com/adyen/checkout/bcmc/BcmcOutputData.kt
leandromagnabosco
533,836,687
false
null
/* * Copyright (c) 2020 <NAME>. * * This file is open source and available under the MIT license. See the LICENSE file for more info. * * Created by caiof on 27/8/2020. */ package com.adyen.checkout.bcmc import com.adyen.checkout.card.data.ExpiryDate import com.adyen.checkout.components.base.OutputData import com.adyen.checkout.components.ui.FieldState data class BcmcOutputData internal constructor( val cardNumberField: FieldState<String>, val expiryDateField: FieldState<ExpiryDate>, val isStoredPaymentMethodEnabled: Boolean ) : OutputData { override val isValid: Boolean get() = ( cardNumberField.validation.isValid() && expiryDateField.validation.isValid() ) }
2
Kotlin
0
0
c154e989a08f1dc76cf90f6949878621cbbfa644
741
testsonarcloud
MIT License
libraries/lib-commons-core/src/main/java/com/corbellini/core/usecases/UseCase.kt
rcorbellini
409,353,869
false
null
package com.corbellini.core.usecases import kotlinx.coroutines.flow.Flow interface UseCase<T, P :UseCaseParam > { suspend fun execute(params: P): Flow<Result<T>> } abstract class UseCaseParam
0
Kotlin
0
6
3125a607a009f4caff048674b2af136665ad93c3
199
GitHubApp
Apache License 2.0
app/src/main/java/com/example/todoapps/presentation/viewModel/EditTodoViewModel.kt
Jubayed-A
743,035,596
false
{"Kotlin": 15982}
package com.example.todoapps.presentation.viewModel import androidx.lifecycle.LiveData import androidx.lifecycle.MutableLiveData import androidx.lifecycle.ViewModel import androidx.lifecycle.viewModelScope import com.example.todoapps.data.dao.TodosDao import kotlinx.coroutines.launch class EditTodoViewModel(todoId: Long, private val dao: TodosDao) : ViewModel() { val todo = dao.get(todoId) private val _navigateToList = MutableLiveData<Boolean>() val navigateToList: LiveData<Boolean> get() = _navigateToList fun updateTodoItem() { viewModelScope.launch { todo.value?.let { dao.update(it) } _navigateToList.value = true } } fun deleteTodoItem() { viewModelScope.launch { todo.value?.let { dao.delete(it) } _navigateToList.value = true } } fun onNavigatedToList() { _navigateToList.value = false } }
0
Kotlin
0
0
6cc6474513ea84939f2106ea8719cdaf4733207d
932
OIBSIP-To-Do-Apps
MIT License
src/studio/papercube/ipprobe/Main.kt
PaperCube
135,261,702
false
{"Kotlin": 12560}
package studio.papercube.ipprobe import studio.papercube.library.argparser.Parameter fun main(args: Array<String>) { val availableConfigs: MutableList<Ip4Address> = ArrayList() try { val parameter = Parameter.resolve(args) val argUnnamed = parameter.getUnnamedArg() if (argUnnamed == null || args.size < 2) { printCommandLineHelp() return } val connectionName = argUnnamed[0] val ipString = argUnnamed[1] val ipEndString = argUnnamed.getOrNull(2) val timeOutArg = parameter.getSingleValue("--timeout") ?: "20" val testHostName = parameter.getSingleValue("--test-host-name") ?: "g.cn" val timeOutSeconds: Long = timeOutArg.toLongOrNull() ?: kotlin.run { println("Invalid value for --timeout. Setting to default value 20") 20L } val ipRange = Ip4Address.parseMin(ipString)..Ip4Address.parseMax(ipEndString ?: ipString) for (ip in ipRange) { println() print("Testing $ip ") val textStatus = RewritableText() try { val configurator = SystemNetworkConfigurator(connectionName, ip) val exitCode = configurator.apply() if (exitCode != 0) { textStatus.write("Unable to set ip $ip. Do you have Administrators' privilege?") continue } } catch (e: Exception) { print("Unexpected exception raised: $e") } val connectivityTester = NetworkConnectivityTester(testHostName, timeOutSeconds * 1000) var elapsedSeconds = 0 connectivityTester.start() while (!connectivityTester.isDone()) { textStatus.write("Checking network connectivity (${elapsedSeconds++}s/${timeOutSeconds}s)") connectivityTester.waitFor(1000) } if (connectivityTester.get()) { textStatus.write("Passed.") availableConfigs.add(ip) } else textStatus.write("Connection failed.") } } catch (e: Exception) { System.err.println("FATAL: $e") } println() println("${availableConfigs.size} configs were found available") availableConfigs.forEach(::println) } fun printCommandLineHelp() { val commandLineHelp = """ |usage: |... <connection-name> <ipv4> [ipv4-end] [options] | |Options: | --test-host-name <host-name> the host name to test network connectivity against | --timeout <seconds> how long this test should be regarded invalid if network check fails """.trimMargin() println(commandLineHelp) }
0
Kotlin
0
0
39573eb71ab0fb6ba07cf2d7921420afb0794ed0
2,784
lan-ip-availability-prober
MIT License