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
android/app/src/main/java/com/renrenbit/rrwallet/network/ICommonApi.kt
RenrenBit-zz
239,955,382
false
null
package com.renrenbit.rrwallet.network import retrofit2.Call import retrofit2.http.* import retrofit2.http.POST /** * Created by jackQ on 2018/6/1. */ interface ICommonApi { @GET fun get(@Url relativePath: String, @HeaderMap headers: Map<String, String>): Call<String> @POST @FormUrlEncoded fun post(@Url relativePath: String, @FieldMap(encoded = true) fields: Map<String, String>, @HeaderMap headers: Map<String, String>): Call<String> @POST fun post(@Url relativePath: String, @Body data: String, @HeaderMap headers: Map<String, String>): Call<String> }
5
null
54
99
73e877a900cd48c40a03cd1b101eedb84c24e191
646
RRWallet
MIT License
src/main/kotlin/io/izzel/testunits/TestItemBuilder.kt
Bkm016
384,852,198
false
null
package io.izzel.testunits import taboolib.common.LifeCycle import taboolib.common.platform.Awake import taboolib.library.xseries.XMaterial import taboolib.module.chat.TellrawJson import taboolib.module.nms.getItemTag import taboolib.platform.util.buildItem object TestItemBuilder { @Awake(LifeCycle.ENABLE) fun init() { println(buildItem(XMaterial.STONE) { name = "测试" lore += "测试123" shiny() }.getItemTag()) } }
0
Kotlin
3
2
690a931e7886cce40164e2731c8f36c8f8186411
480
TabooLib-Test-Units
Creative Commons Zero v1.0 Universal
platform/platform-impl/src/com/intellij/platform/ProjectFrameAllocator.kt
present1001
203,810,020
true
null
// Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.platform import com.intellij.conversion.CannotConvertException import com.intellij.diagnostic.runActivity import com.intellij.ide.RecentProjectsManager import com.intellij.ide.RecentProjectsManagerBase import com.intellij.ide.impl.OpenProjectTask import com.intellij.openapi.application.ApplicationManager import com.intellij.openapi.application.TransactionGuard import com.intellij.openapi.progress.ProgressManager import com.intellij.openapi.project.Project import com.intellij.openapi.project.impl.ProjectManagerImpl import com.intellij.openapi.wm.WindowManager import com.intellij.openapi.wm.impl.IdeFrameImpl import com.intellij.openapi.wm.impl.ProjectFrameBounds import com.intellij.openapi.wm.impl.WindowManagerImpl import org.jetbrains.annotations.CalledInAwt import java.nio.file.Path internal open class ProjectFrameAllocator { open fun run(task: Runnable, file: Path): Boolean { task.run() return true } /** * Project is loaded and is initialized, project services and components can be accessed. */ open fun projectLoaded(project: Project) {} open fun projectNotLoaded(error: CannotConvertException?) { if (error != null) { ProjectManagerImpl.showCannotConvertMessage(error, null) } } open fun projectOpened(project: Project) {} } internal class ProjectUiFrameAllocator(private var options: OpenProjectTask) : ProjectFrameAllocator() { // volatile not required because created in run (before executing run task) private var ideFrame: IdeFrameImpl? = null override fun run(task: Runnable, file: Path): Boolean { var completed = false TransactionGuard.getInstance().submitTransactionAndWait { val frame = createFrame(file) completed = ProgressManager.getInstance().runProcessWithProgressSynchronously( { ApplicationManager.getApplication().invokeLater { runActivity("init frame") { initFrame(frame) } } task.run() }, "Loading Project...", true, null, frame.component) } return completed } @CalledInAwt private fun initFrame(frame: IdeFrameImpl) { val windowManager = WindowManager.getInstance() as WindowManagerImpl var frameInfo = options.frame if (frameInfo?.bounds == null) { frameInfo = windowManager.defaultFrameInfo } if (frameInfo != null) { windowManager.restoreFrameState(frame, frameInfo) } frame.preInit() frame.isVisible = true frame.init() } private fun createFrame(file: Path): IdeFrameImpl { val windowManager = WindowManager.getInstance() as WindowManagerImpl val freeRootFrame = windowManager.rootFrame if (freeRootFrame != null) { return freeRootFrame } if (options.frame?.bounds == null) { val recentProjectManager = RecentProjectsManager.getInstance() if (recentProjectManager is RecentProjectsManagerBase) { val info = recentProjectManager.getProjectMetaInfo(file) if (info != null) { options = options.copy() options.frame = info.frame options.projectWorkspaceId = info.projectWorkspaceId } } } val frame = runActivity("create a frame") { windowManager.createFrame(options) } ideFrame = frame return frame } override fun projectLoaded(project: Project) { ApplicationManager.getApplication().invokeLater { if (project.isDisposed) { return@invokeLater } val frame = ideFrame ?: return@invokeLater val windowManager = WindowManager.getInstance() as WindowManagerImpl if (options.frame?.bounds == null) { val frameInfo = ProjectFrameBounds.getInstance(project).getFrameInfoInDeviceSpace() if (frameInfo?.bounds != null) { windowManager.restoreFrameState(frame, frameInfo) } } windowManager.assignFrame(frame, project) } } override fun projectNotLoaded(error: CannotConvertException?) { ApplicationManager.getApplication().invokeLater { val frame = ideFrame ideFrame = null if (error != null) { ProjectManagerImpl.showCannotConvertMessage(error, frame) } frame?.dispose() } } override fun projectOpened(project: Project) { if (options.sendFrameBack) { ideFrame?.isAutoRequestFocus = true } } }
1
null
1
1
c029028839bd38d96f7f6916ed115a089ce6b277
4,510
intellij-community
Apache License 2.0
sdk/src/main/kotlin/io/github/wulkanowy/sdk/pojo/GradePointsStatistics.kt
wulkanowy
138,756,468
false
{"Kotlin": 705036, "HTML": 70768}
package io.github.wulkanowy.sdk.pojo data class GradePointsStatistics( val semesterId: Int, val subject: String, val others: Double, val student: Double )
9
Kotlin
5
8
340245d8ccc2790dcb75219c2839e8bdd8b448a4
172
sdk
Apache License 2.0
data/source/src/main/java/com/uxstate/source/local/converter/Converters.kt
Tonnie-Dev
518,721,038
false
{"Kotlin": 160830}
package com.uxstate.source.local.converter import androidx.room.TypeConverter /*Be ware of using "," as separator as sometimes your string may have the same character and it can be a mess.*/ class Converters { /* takes a list of string e.g. Currency list and stores it in ROOM database as a string */ @TypeConverter fun toString(currencyList: List<String>): String { return currencyList.joinToString(separator = ",") } /*takes the string stored in Room and converts it back to a String List*/ @TypeConverter fun fromString(roomString: String): List<String> { return roomString.split(",") .map { it } } //write pair to Room and store it as a String @TypeConverter fun writeFromPair(pair: Pair<Double, Double>): String { val stringList = mutableListOf<String>() stringList.add(pair.first.toString()) stringList.add(pair.second.toString()) return stringList.joinToString(separator = ",") } @TypeConverter fun readStringPair(roomString: String): Pair<Double, Double> { val stringDoublesList = roomString.split(",") return Pair( first = stringDoublesList[0].toDouble(), second = stringDoublesList[1].toDouble() ) } }
0
Kotlin
0
5
de0ed8b62b891acd6ebf87a8fabaa4c3e2ce08ef
1,317
CountriesPad
The Unlicense
app/src/main/java/org/p2p/wallet/jupiter/repository/transaction/JupiterSwapTransactionRemoteRepository.kt
p2p-org
306,035,988
false
{"Kotlin": 4517101, "HTML": 3064848, "Java": 296567, "Groovy": 1601, "Shell": 1252}
package org.p2p.wallet.jupiter.repository.transaction import kotlinx.coroutines.CancellationException import org.p2p.solanaj.utils.crypto.Base64String import org.p2p.wallet.infrastructure.dispatchers.CoroutineDispatchers import org.p2p.wallet.jupiter.api.SwapJupiterApi import org.p2p.wallet.jupiter.repository.model.JupiterSwapRoute import org.p2p.wallet.jupiter.repository.model.SwapFailure import org.p2p.wallet.utils.Base58String import kotlinx.coroutines.withContext import org.p2p.wallet.utils.retryOnException class JupiterSwapTransactionRemoteRepository( private val api: SwapJupiterApi, private val mapper: JupiterSwapTransactionMapper, private val dispatchers: CoroutineDispatchers ) : JupiterSwapTransactionRepository { override suspend fun createSwapTransactionForRoute( route: JupiterSwapRoute, userPublicKey: Base58String ): Base64String = withContext(dispatchers.io) { try { val request = mapper.toNetwork(route, userPublicKey) val response = retryOnException { api.createRouteSwapTransaction(request) } response.let(mapper::fromNetwork) } catch (cancelled: CancellationException) { throw cancelled } catch (error: Throwable) { throw SwapFailure.CreateSwapTransactionFailed(route, error) } } }
8
Kotlin
18
33
509f73eb690114a77d24d1e44298819b20351b0e
1,371
key-app-android
MIT License
common/src/main/java/com/sec/common/BaseFragment.kt
liuhuiAndroid
311,604,995
false
null
package com.sec.common import androidx.fragment.app.Fragment abstract class BaseFragment : Fragment() { }
0
Kotlin
0
1
2ccbf66a540cc4db738f9d3e0fdcc6f5db014526
108
fizz
MIT License
app/src/main/java/com/ckarthickit/mealdb/ui/MealItemsSectionAdapter.kt
ckarthickit2
198,757,650
false
null
package com.ckarthickit.mealdb.ui import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.ImageView import androidx.appcompat.widget.AppCompatTextView import androidx.recyclerview.widget.RecyclerView import com.bumptech.glide.Glide import com.bumptech.glide.load.engine.DiskCacheStrategy import com.bumptech.glide.load.resource.drawable.DrawableTransitionOptions import com.bumptech.glide.request.transition.DrawableCrossFadeFactory import com.ckarthickit.mealdb.R import com.ckarthickit.mealdb.service.model.Meal class MealItemViewHolder(view: View) : RecyclerView.ViewHolder(view) { internal val imageView: ImageView = view.findViewById(R.id.card_image) internal val label: AppCompatTextView = view.findViewById(R.id.card_label) internal val subLabel: AppCompatTextView = view.findViewById(R.id.card_sub_label) } class MealItemsSectionAdapter : RecyclerView.Adapter<MealItemViewHolder>() { private var mealItems: List<Meal> = emptyList() override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): MealItemViewHolder { val view = LayoutInflater.from(parent.context).inflate(R.layout.card_view, parent, false) return MealItemViewHolder(view) } override fun getItemCount(): Int { return mealItems.size } fun updateItems(mealItems: List<Meal>) { this.mealItems = mealItems notifyDataSetChanged() } override fun onBindViewHolder(holder: MealItemViewHolder, position: Int) { val mealItem = mealItems[position] holder.label.text = mealItem.name holder.subLabel.text = mealItem.id.toString() val crossFadeFactory = DrawableCrossFadeFactory.Builder().setCrossFadeEnabled(true).build() Glide .with(holder.itemView.context) .load(mealItem.thumbnail) .diskCacheStrategy(DiskCacheStrategy.ALL) .placeholder(R.drawable.black_gradient_top_down) .error(R.drawable.black_gradient_top_down) .transition(DrawableTransitionOptions.with(crossFadeFactory)) // .animate(R.anim.fade_in) .into(holder.imageView) } }
5
null
1
2
1124a1733382198204f99af9fd6046de5c4575d5
2,075
android-best-practices
Linux Kernel Variant of OpenIB.org license
android/app-newm/src/main/java/io/newm/utils/AndroidFeatureFlagManager.kt
projectNEWM
435,674,758
false
{"Kotlin": 562064, "Swift": 310096}
package io.newm.utils import android.app.Application import com.launchdarkly.sdk.ContextKind import com.launchdarkly.sdk.LDContext import com.launchdarkly.sdk.android.LDClient import com.launchdarkly.sdk.android.LDConfig import com.launchdarkly.sdk.android.LDConfig.Builder.AutoEnvAttributes import io.newm.shared.config.NewmSharedBuildConfig import io.newm.shared.public.featureflags.FeatureFlag import io.newm.shared.public.featureflags.FeatureFlagManager import kotlinx.coroutines.CompletableDeferred import kotlinx.coroutines.Deferred import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.withContext import java.util.concurrent.Future class AndroidFeatureFlagManager( private val application: Application, private val sharedBuildConfig: NewmSharedBuildConfig, ) : FeatureFlagManager { private val client: LDClient = buildClient() private fun buildClient(): LDClient { val context = LDContext.builder(ContextKind.DEFAULT, "anonymous") .anonymous(true) .build() val ldConfig: LDConfig = LDConfig.Builder(AutoEnvAttributes.Enabled) .mobileKey(sharedBuildConfig.launchDarklyKey) .build() return LDClient.init(application, ldConfig, context, 0) } override fun isEnabled(flag: FeatureFlag, default: Boolean): Boolean { return client.boolVariation(flag.key, default) } override suspend fun setUserId(id: String) { val ldContext = LDContext.builder(ContextKind.DEFAULT, id).build() client.identify(ldContext) .asDeferred() .await() } } private suspend fun <V> Future<V>.asDeferred(): Deferred<V> { val deferred = CompletableDeferred<V>() withContext(Dispatchers.IO) { deferred.complete(get()) } return deferred }
3
Kotlin
9
16
805eed8f6bb505e1a6b13483f33395e34a61aae9
1,812
newm-mobile
Apache License 2.0
app/src/main/java/ilkadam/ilksohbet/domain/usecase/profileScreen/LoadProfileFromFirebase.kt
ademkocamaz
803,881,747
false
{"Kotlin": 261729}
package ilkadam.ilksohbet.domain.usecase.profileScreen import ilkadam.ilksohbet.domain.repository.ProfileScreenRepository class LoadProfileFromFirebase( private val profileScreenRepository: ProfileScreenRepository ) { suspend operator fun invoke() = profileScreenRepository.loadProfileFromFirebase() }
0
Kotlin
0
0
cd06a2de124fdbc8c78085da8e9d8bcc46a74033
311
ilkMuhabbet
MIT License
app/src/main/java/com/stevesoltys/seedvault/ui/storage/StorageCheckFragment.kt
seedvault-app
104,299,796
false
null
package com.stevesoltys.seedvault.ui.storage import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.View.GONE import android.view.View.INVISIBLE import android.view.View.VISIBLE import android.view.ViewGroup import android.widget.Button import android.widget.ProgressBar import android.widget.TextView import androidx.fragment.app.Fragment import com.stevesoltys.seedvault.R private const val TITLE = "title" private const val ERROR_MSG = "errorMsg" class StorageCheckFragment : Fragment() { private lateinit var titleView: TextView private lateinit var progressBar: ProgressBar private lateinit var errorView: TextView private lateinit var backButton: Button companion object { fun newInstance(title: String, errorMsg: String? = null): StorageCheckFragment { val f = StorageCheckFragment() f.arguments = Bundle().apply { putString(TITLE, title) putString(ERROR_MSG, errorMsg) } return f } } override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?, ): View { val v: View = inflater.inflate(R.layout.fragment_storage_check, container, false) titleView = v.findViewById(R.id.titleView) progressBar = v.findViewById(R.id.progressBar) errorView = v.findViewById(R.id.errorView) backButton = v.findViewById(R.id.backButton) return v } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) titleView.text = requireArguments().getString(TITLE) val errorMsg = requireArguments().getString(ERROR_MSG) if (errorMsg != null) { view.findViewById<View>(R.id.patienceView).visibility = GONE progressBar.visibility = INVISIBLE errorView.text = errorMsg errorView.visibility = VISIBLE backButton.visibility = VISIBLE backButton.setOnClickListener { requireActivity().supportFinishAfterTransition() } } } }
98
null
9
998
2bbeece7b7a09e1b3d19f15cb037b197e7e032c6
2,186
seedvault
Apache License 2.0
src/test/kotlin/net/rentalhost/plugins/php/hammer/inspections/flowOptimization/IfSimplificationElseInspectionTestCase.kt
hammer-tools
509,864,102
false
null
package net.rentalhost.plugins.php.hammer.inspections.flowOptimization import net.rentalhost.plugins.php.hammer.services.TestCase class IfSimplificationElseInspectionTestCase : TestCase() { fun testAll(): Unit = testInspection(IfSimplificationElseInspection::class.java) }
9
null
2
96
eb07d4f34bdd4a588251db854e6c60ca6584886a
277
php-hammer
Apache License 2.0
src/main/kotlin/Main.kt
PedroDiogo
432,836,814
false
{"Kotlin": 128203}
import problems.* import java.net.URL import java.time.Duration import java.time.Instant import java.util.* fun main() { val problems: List<Problem> = listOf( Day0("problems/day0".asResource().readText()), Day1("problems/day1".asResource().readText()), Day2("problems/day2".asResource().readText()), Day3("problems/day3".asResource().readText()), Day4("problems/day4".asResource().readText()), Day5("problems/day5".asResource().readText()), Day6("problems/day6".asResource().readText()), Day7("problems/day7".asResource().readText()), Day8("problems/day8".asResource().readText()), Day9("problems/day9".asResource().readText()), Day10("problems/day10".asResource().readText()), Day11("problems/day11".asResource().readText()), Day12("problems/day12".asResource().readText()), Day13("problems/day13".asResource().readText()), Day14("problems/day14".asResource().readText()), Day15("problems/day15".asResource().readText()), Day16("problems/day16".asResource().readText()), Day17("problems/day17".asResource().readText()), Day18("problems/day18".asResource().readText()), Day19("problems/day19".asResource().readText()), Day20("problems/day20".asResource().readText()), Day21("problems/day21".asResource().readText()), Day22("problems/day22".asResource().readText()), Day23("problems/day23".asResource().readText()), Day24("problems/day24".asResource().readText()), Day25("problems/day25".asResource().readText()), ) runProblems(problems) } fun runProblems(problems: List<Problem>) { for (day in problems) { val beforeStep1 = Instant.now() val partOne = day.runPartOne() val afterStep1 = Instant.now() println("Day ${day.number}") println("Part one (took ${Duration.between(beforeStep1, afterStep1).toMillis()} ms):\n" + partOne) val beforeStep2 = Instant.now() val partTwo = day.runPartTwo() val afterStep2 = Instant.now() if (partTwo.isNotEmpty()) println("Part two (took ${Duration.between(beforeStep2, afterStep2).toMillis()} ms):\n" + partTwo) println("===============================") } } fun String.asResource() : URL { return object {}.javaClass.getResource(this) }
0
Kotlin
0
0
93363faee195d5ef90344a4fb74646d2d26176de
2,437
AdventOfCode2021
MIT License
shared/src/commonMain/kotlin/com/thomaskioko/tvmaniac/util/ExceptionHandler.kt
c0de-wizard
361,393,353
false
null
package com.thomaskioko.tvmaniac.util import io.github.aakira.napier.Napier import io.ktor.client.features.ResponseException import io.ktor.client.features.ServerResponseException import io.ktor.client.statement.HttpResponse open class ExceptionHandler( val errorMessage: String, ) : Exception() { override val message: String get() = cause.message ?: "Something went wrong" override val cause: Throwable get() = Throwable(errorMessage) companion object { fun parseException(response: HttpResponse): ExceptionHandler { return ExceptionHandler("Unexpected error. ResponseCode:: ${response.status.value}ً") } } } fun Throwable.resolveError() = when (this) { is HttpResponse -> { when (status.value) { 400 -> ExceptionHandler.parseException(this) 401 -> ExceptionHandler(errorMessage = "Authentication failed!") 502 -> ExceptionHandler(errorMessage = "Internal error!") else -> ExceptionHandler.parseException(this) } } is ServerResponseException -> ExceptionHandler(errorMessage = getErrorMessage()) is NullPointerException -> ExceptionHandler(errorMessage = getErrorMessage()) else -> ExceptionHandler(errorMessage = getErrorMessage()) } fun Throwable.getErrorMessage(): String { return if (BuildConfig().isDebug()) { Napier.e("Exception:: $message", this) message ?: "Something went wrong" } else { "Something went wrong" } } fun ResponseException.getErrorMessage(): String { return if (BuildConfig().isDebug()) { "Server Error: ${response.status.value} /n $message" } else { "Connection to server failed." } }
3
Kotlin
1
16
051aaba6359199cb8f9815feb6e96e0f5580d589
1,731
tv-maniac
Apache License 2.0
simple-icons/src/commonMain/kotlin/compose/icons/simpleicons/Curseforge.kt
DevSrSouza
311,134,756
false
null
package compose.icons.simpleicons import androidx.compose.ui.graphics.Color import androidx.compose.ui.graphics.PathFillType.NonZero import androidx.compose.ui.graphics.SolidColor import androidx.compose.ui.graphics.StrokeCap.Butt import androidx.compose.ui.graphics.StrokeJoin.Miter import androidx.compose.ui.graphics.vector.ImageVector import androidx.compose.ui.graphics.vector.ImageVector.Builder import androidx.compose.ui.graphics.vector.path import androidx.compose.ui.unit.dp import compose.icons.SimpleIcons public val SimpleIcons.Curseforge: ImageVector get() { if (_curseforge != null) { return _curseforge!! } _curseforge = Builder(name = "Curseforge", defaultWidth = 24.0.dp, defaultHeight = 24.0.dp, viewportWidth = 24.0f, viewportHeight = 24.0f).apply { path(fill = SolidColor(Color(0xFF000000)), stroke = null, strokeLineWidth = 0.0f, strokeLineCap = Butt, strokeLineJoin = Miter, strokeLineMiter = 4.0f, pathFillType = NonZero) { moveTo(6.307f, 5.581f) lineToRelative(0.391f, 1.675f) lineTo(0.0f, 7.256f) reflectiveCurveToRelative(0.112f, 0.502f, 0.167f, 0.558f) curveToRelative(0.168f, 0.279f, 0.335f, 0.614f, 0.559f, 0.837f) curveToRelative(1.06f, 1.228f, 2.902f, 1.73f, 4.409f, 2.009f) curveToRelative(1.06f, 0.224f, 2.121f, 0.28f, 3.181f, 0.335f) lineToRelative(1.228f, 3.293f) horizontalLineToRelative(0.67f) lineToRelative(0.391f, 1.061f) horizontalLineToRelative(-0.558f) lineToRelative(-0.949f, 3.07f) horizontalLineToRelative(9.321f) lineToRelative(-0.949f, -3.07f) horizontalLineToRelative(-0.558f) lineToRelative(0.39f, -1.061f) horizontalLineToRelative(0.67f) reflectiveCurveToRelative(0.558f, -3.404f, 2.288f, -4.967f) curveTo(21.935f, 7.758f, 24.0f, 7.535f, 24.0f, 7.535f) lineTo(24.0f, 5.581f) lineTo(6.307f, 5.581f) close() moveTo(15.684f, 14.009f) curveToRelative(-0.447f, 0.279f, -0.949f, 0.279f, -1.284f, 0.503f) curveToRelative(-0.223f, 0.111f, -0.335f, 0.446f, -0.335f, 0.446f) curveToRelative(-0.223f, -0.502f, -0.502f, -0.67f, -0.837f, -0.781f) curveToRelative(-0.335f, -0.112f, -0.949f, -0.056f, -1.786f, -0.782f) curveToRelative(-0.558f, -0.502f, -0.614f, -1.172f, -0.558f, -1.507f) verticalLineToRelative(-0.167f) curveToRelative(0.0f, -0.056f, 0.0f, -0.112f, 0.056f, -0.168f) curveToRelative(0.111f, -0.334f, 0.39f, -0.669f, 0.948f, -0.893f) curveToRelative(0.0f, 0.0f, -0.39f, 0.559f, 0.0f, 1.117f) curveToRelative(0.224f, 0.335f, 0.67f, 0.502f, 1.061f, 0.279f) curveToRelative(0.167f, -0.112f, 0.279f, -0.335f, 0.335f, -0.503f) curveToRelative(0.111f, -0.39f, 0.111f, -0.781f, -0.224f, -1.06f) curveToRelative(-0.502f, -0.446f, -0.613f, -1.06f, -0.279f, -1.451f) curveToRelative(0.0f, 0.0f, 0.112f, 0.502f, 0.614f, 0.446f) curveToRelative(0.335f, 0.0f, 0.335f, -0.111f, 0.224f, -0.223f) curveToRelative(-0.056f, -0.167f, -0.782f, -1.228f, 0.279f, -2.009f) curveToRelative(0.0f, 0.0f, 0.669f, -0.447f, 1.451f, -0.391f) curveToRelative(-0.447f, 0.056f, -0.949f, 0.335f, -1.116f, 0.782f) verticalLineToRelative(0.055f) curveToRelative(-0.168f, 0.447f, -0.056f, 0.949f, 0.279f, 1.396f) curveToRelative(0.223f, 0.335f, 0.502f, 0.614f, 0.614f, 1.06f) curveToRelative(-0.168f, -0.056f, -0.279f, 0.0f, -0.391f, 0.112f) arcToRelative(0.533f, 0.533f, 0.0f, false, false, -0.112f, 0.502f) curveToRelative(0.056f, 0.112f, 0.168f, 0.223f, 0.279f, 0.223f) horizontalLineToRelative(0.168f) curveToRelative(0.167f, -0.055f, 0.279f, -0.279f, 0.223f, -0.446f) curveToRelative(0.112f, 0.111f, 0.167f, 0.391f, 0.112f, 0.558f) curveToRelative(0.0f, 0.167f, -0.112f, 0.335f, -0.168f, 0.446f) curveToRelative(-0.056f, 0.112f, -0.167f, 0.224f, -0.223f, 0.335f) curveToRelative(-0.056f, 0.112f, -0.112f, 0.224f, -0.112f, 0.335f) curveToRelative(0.0f, 0.112f, 0.0f, 0.279f, 0.056f, 0.391f) curveToRelative(0.223f, 0.335f, 0.67f, 0.0f, 0.782f, -0.279f) curveToRelative(0.167f, -0.335f, 0.111f, -0.726f, -0.112f, -1.061f) curveToRelative(0.0f, 0.0f, 0.391f, 0.224f, 0.67f, 1.005f) curveToRelative(0.223f, 0.67f, -0.168f, 1.451f, -0.614f, 1.73f) close() } } .build() return _curseforge!! } private var _curseforge: ImageVector? = null
17
null
25
571
a660e5f3033e3222e3553f5a6e888b7054aed8cd
5,148
compose-icons
MIT License
core/network/src/main/java/com/msg/network/request/auth/SignUpGovernmentRequest.kt
School-of-Company
700,744,250
false
{"Kotlin": 724178}
package com.msg.network.request.auth import com.msg.model.enumdata.HighSchool import com.squareup.moshi.Json import com.squareup.moshi.JsonClass @JsonClass(generateAdapter = true) data class SignUpGovernmentRequest( @Json(name = "email") val email: String, @Json(name = "name") val name: String, @Json(name = "phoneNumber") val phoneNumber: String, @Json(name = "password") val password: String, @Json(name = "highSchool") val highSchool: HighSchool, @Json(name = "clubName") val clubName: String, @Json(name = "governmentName") val governmentName: String, @Json(name = "position") val position: String, @Json(name = "sectors") val sectors: String, )
6
Kotlin
1
22
358bf40188fa2fc2baf23aa6b308b039cb3fbc8c
689
Bitgoeul-Android
MIT License
app/src/main/java/com/example/cryptoflow/data/Tickers.kt
Naphtali-cpu
428,728,616
false
null
package com.example.cryptoflow.data class Tickers : ArrayList<TickersItem>()
0
Kotlin
1
2
c0dd08f6b534af9bd1a7349529bf40e772ae84f1
77
Crypto-View
The Unlicense
http4k-core/src/main/kotlin/org/http4k/core/ContentType.kt
http4k
86,003,479
false
null
package org.http4k.core import java.nio.charset.Charset data class ContentType(val value: String, val directives: Parameters = emptyList()) { fun withNoDirectives() = copy(directives = emptyList()) fun toHeaderValue() = ( listOf(value) + directives .map { it.first + (it.second?.let { "=$it" } ?: "") } ).joinToString("; ") fun equalsIgnoringDirectives(that: ContentType): Boolean = withNoDirectives() == that.withNoDirectives() companion object { fun Text(value: String, charset: Charset? = Charsets.UTF_8) = ContentType(value, listOfNotNull(charset?.let { "charset" to charset.name().toLowerCase() })) fun MultipartFormWithBoundary(boundary: String): ContentType = ContentType("multipart/form-data", listOf("boundary" to boundary)) fun MultipartMixedWithBoundary(boundary: String): ContentType = ContentType("multipart/mixed", listOf("boundary" to boundary)) val APPLICATION_JSON = Text("application/json") val APPLICATION_FORM_URLENCODED = Text("application/x-www-form-urlencoded") val MULTIPART_FORM_DATA = Text("multipart/form-data") val APPLICATION_XML = Text("application/xml") val APPLICATION_PDF = Text("application/pdf") val TEXT_HTML = Text("text/html") val TEXT_YAML = Text("text/yaml") val TEXT_XML = Text("text/xml") val TEXT_PLAIN = Text("text/plain") val OCTET_STREAM = ContentType("application/octet-stream") } }
34
null
249
2,615
7ad276aa9c48552a115a59178839477f34d486b1
1,506
http4k
Apache License 2.0
collector/src/test/java/com/bitmovin/analytics/data/EventDataTest.kt
bitmovin
120,633,749
false
null
package com.bitmovin.analytics.data import com.bitmovin.analytics.TestFactory import com.bitmovin.analytics.api.AnalyticsConfig import com.bitmovin.analytics.api.DefaultMetadata import com.bitmovin.analytics.api.SourceMetadata import com.bitmovin.analytics.enums.PlayerType import com.bitmovin.analytics.utils.DataSerializer import org.assertj.core.api.Assertions.assertThat import org.assertj.core.api.Assertions.fail import org.junit.Before import org.junit.Test import java.util.UUID class EventDataTest { private val licenseKey = UUID.randomUUID().toString() private val impressionId = UUID.randomUUID().toString() private val userId = UUID.randomUUID().toString() private lateinit var analyticsConfig: AnalyticsConfig @Before fun setup() { analyticsConfig = AnalyticsConfig(licenseKey = licenseKey) } @Test fun testEventDataContainsDeviceInformation() { val deviceInformation = DeviceInformation("myManufacturer", "myModel", false, "de", "package-name", 100, 200) val eventData = TestFactory.createEventDataFactory(analyticsConfig).create( impressionId, SourceMetadata(), DefaultMetadata(), deviceInformation, PlayerInfo("Android:Exoplayer", PlayerType.EXOPLAYER), ) assertThat(eventData.deviceInformation.manufacturer).isEqualTo("myManufacturer") assertThat(eventData.deviceInformation.model).isEqualTo("myModel") assertThat(eventData.deviceInformation.isTV).isFalse() assertThat(eventData.language).isEqualTo("de") assertThat(eventData.domain).isEqualTo("package-name") assertThat(eventData.screenHeight).isEqualTo(100) assertThat(eventData.screenWidth).isEqualTo(200) assertThat(eventData.platform).isEqualTo("android") } @Test fun testEventDataSetsPlatformToAndroidTVIfDeviceInformationIsTVIsTrue() { val deviceInformation = DeviceInformation("myManufacturer", "myModel", true, "de", "package-name", 100, 200) val eventData = TestFactory.createEventDataFactory(analyticsConfig).create( impressionId, SourceMetadata(), DefaultMetadata(), deviceInformation, PlayerInfo("Android:Exoplayer", PlayerType.EXOPLAYER), ) assertThat(eventData.platform).isEqualTo("androidTV") } @Test fun testEventDataSetsRandomizedUserId() { val deviceInformation = DeviceInformation("myManufacturer", "myModel", true, "de", "package-name", 100, 200) var randomizedUserIdProvider = RandomizedUserIdIdProvider() var randomizedUserIdProvider1 = RandomizedUserIdIdProvider() var eventData = TestFactory.createEventDataFactory( analyticsConfig, randomizedUserIdProvider, ).create( impressionId, SourceMetadata(), DefaultMetadata(), deviceInformation, PlayerInfo("Android:Exoplayer", PlayerType.EXOPLAYER), ) var eventData1 = TestFactory.createEventDataFactory( analyticsConfig, randomizedUserIdProvider, ).create( impressionId, SourceMetadata(), DefaultMetadata(), deviceInformation, PlayerInfo("Android:Exoplayer", PlayerType.EXOPLAYER), ) var eventData2 = TestFactory.createEventDataFactory( analyticsConfig, randomizedUserIdProvider1, ).create( impressionId, SourceMetadata(), DefaultMetadata(), deviceInformation, PlayerInfo("Android:Exoplayer", PlayerType.EXOPLAYER), ) assertThat(eventData.userId).isEqualTo(eventData1.userId) assertThat(eventData.userId).isEqualTo(randomizedUserIdProvider.userId()) assertThat(eventData2.userId).isEqualTo(randomizedUserIdProvider1.userId()) assertThat(eventData2.userId).isNotEqualTo(eventData1.userId) } @Test fun testEventDataStringIsDeserialized() { // this test ensures that we are backward compatible in case EventData class is changing // arrange val eventData1Json = """ {"ad":0,"analyticsVersion":"0.0.0-local","audioBitrate":-1,"audioCodec":"mp4a.40.2","audioLanguage":"en","buffered":0,"cdnProvider":"testCdnProvider","customData1":"systemtest","customData10":"customData10","customData11":"customData11","customData12":"customData12","customData13":"customData13","customData14":"customData14","customData15":"customData15","customData16":"customData16","customData17":"customData17","customData18":"customData18","customData19":"customData19","customData2":"customData2","customData20":"customData20","customData21":"customData21","customData22":"customData22","customData23":"customData23","customData24":"customData24","customData25":"customData25","customData26":"customData26","customData27":"customData27","customData28":"customData28","customData29":"customData29","customData3":"customData3","customData30":"customData30","customData4":"customData4","customData5":"customData5","customData6":"customData6","customData7":"customData7","customData8":"systemtest8","customData9":"customData9","customUserId":"customBitmovinUserId1","deviceInformation":{"isTV":false,"manufacturer":"Google","model":"sdk_gphone64_arm64"},"domain":"com.bitmovin.analytics.bitmovin.player.test","droppedFrames":0,"duration":3929,"experimentName":"experiment-1","impressionId":"c6e0e073-c777-49f2-a7e1-e47bc8a839cb","isCasting":false,"isLive":false,"isMuted":false,"key":"<KEY>","language":"en_US","m3u8Url":"https://bitdash-a.akamaihd.net/content/MI201109210084_1/m3u8s/f08e80da-bf1d-4e3d-8899-f0f6155f6efa.m3u8","mpdUrl":"https://test.com/mpd","pageLoadTime":0,"pageLoadType":1,"path":"/customPath/new/","paused":0,"platform":"android","played":0,"player":"bitmovin","playerKey":"dummyplayerKey","playerStartupTime":1,"playerTech":"Android:Exoplayer","progUrl":"https://test.com/prog","retryCount":0,"screenHeight":2209,"screenWidth":1080,"seeked":0,"sequenceNumber":0,"startupTime":3929,"state":"startup","streamFormat":"hls","subtitleEnabled":false,"supportedVideoCodecs":["hevc","vp9","avc"],"time":1689091210921,"userAgent":"Dalvik/2.1.0 (Linux; U; Android 13; sdk_gphone64_arm64 Build/TE1A.220922.029)","userId":"25f572b30123c015","version":"bitmovin-3.38.0","videoBitrate":628000,"videoCodec":"avc1.4D400D","videoDuration":210000,"videoId":"dummy-videoId","videoPlaybackHeight":180,"videoPlaybackWidth":320,"videoStartFailed":false,"videoStartupTime":3928,"videoTimeEnd":0,"videoTimeStart":0,"videoTitle":"offlineSession","videoWindowHeight":123,"videoWindowWidth":123} """.trimIndent() // act val eventData1 = DataSerializer.deserialize(eventData1Json, EventData::class.java) // assert if (eventData1 == null) { fail<Nothing>("eventData1Json couldn't be deserialized") return } assertThat(eventData1.ad).isEqualTo(0) assertThat(eventData1.analyticsVersion).isEqualTo("0.0.0-local") assertThat(eventData1.audioBitrate).isEqualTo(-1) assertThat(eventData1.audioCodec).isEqualTo("mp4a.40.2") assertThat(eventData1.audioLanguage).isEqualTo("en") assertThat(eventData1.buffered).isEqualTo(0) assertThat(eventData1.cdnProvider).isEqualTo("testCdnProvider") assertThat(eventData1.customData1).isEqualTo("systemtest") assertThat(eventData1.customData2).isEqualTo("customData2") assertThat(eventData1.customData3).isEqualTo("customData3") assertThat(eventData1.customData4).isEqualTo("customData4") assertThat(eventData1.customData5).isEqualTo("customData5") assertThat(eventData1.customData6).isEqualTo("customData6") assertThat(eventData1.customData7).isEqualTo("customData7") assertThat(eventData1.customData8).isEqualTo("systemtest8") assertThat(eventData1.customData9).isEqualTo("customData9") assertThat(eventData1.customData10).isEqualTo("customData10") assertThat(eventData1.customData11).isEqualTo("customData11") assertThat(eventData1.customData12).isEqualTo("customData12") assertThat(eventData1.customData13).isEqualTo("customData13") assertThat(eventData1.customData14).isEqualTo("customData14") assertThat(eventData1.customData15).isEqualTo("customData15") assertThat(eventData1.customData16).isEqualTo("customData16") assertThat(eventData1.customData17).isEqualTo("customData17") assertThat(eventData1.customData18).isEqualTo("customData18") assertThat(eventData1.customData19).isEqualTo("customData19") assertThat(eventData1.customData20).isEqualTo("customData20") assertThat(eventData1.customData21).isEqualTo("customData21") assertThat(eventData1.customData22).isEqualTo("customData22") assertThat(eventData1.customData23).isEqualTo("customData23") assertThat(eventData1.customData24).isEqualTo("customData24") assertThat(eventData1.customData25).isEqualTo("customData25") assertThat(eventData1.customData26).isEqualTo("customData26") assertThat(eventData1.customData27).isEqualTo("customData27") assertThat(eventData1.customData28).isEqualTo("customData28") assertThat(eventData1.customData29).isEqualTo("customData29") assertThat(eventData1.customData30).isEqualTo("customData30") assertThat(eventData1.customUserId).isEqualTo("customBitmovinUserId1") assertThat(eventData1.droppedFrames).isEqualTo(0) assertThat(eventData1.domain).isEqualTo("com.bitmovin.analytics.bitmovin.player.test") assertThat(eventData1.customUserId).isEqualTo("customBitmovinUserId1") assertThat(eventData1.deviceInformation.isTV).isFalse assertThat(eventData1.deviceInformation.manufacturer).isEqualTo("Google") assertThat(eventData1.deviceInformation.model).isEqualTo("sdk_gphone64_arm64") assertThat(eventData1.domain).isEqualTo("com.bitmovin.analytics.bitmovin.player.test") assertThat(eventData1.duration).isEqualTo(3929) assertThat(eventData1.experimentName).isEqualTo("experiment-1") assertThat(eventData1.impressionId).isEqualTo("c6e0e073-c777-49f2-a7e1-e47bc8a839cb") assertThat(eventData1.isCasting).isFalse assertThat(eventData1.isLive).isFalse assertThat(eventData1.isMuted).isFalse assertThat(eventData1.key).isEqualTo("<KEY>") assertThat(eventData1.language).isEqualTo("en_US") assertThat(eventData1.m3u8Url).isEqualTo("https://bitdash-a.akamaihd.net/content/MI201109210084_1/m3u8s/f08e80da-bf1d-4e3d-8899-f0f6155f6efa.m3u8") assertThat(eventData1.mpdUrl).isEqualTo("https://test.com/mpd") assertThat(eventData1.pageLoadTime).isEqualTo(0) assertThat(eventData1.pageLoadType).isEqualTo(1) assertThat(eventData1.path).isEqualTo("/customPath/new/") assertThat(eventData1.paused).isEqualTo(0) assertThat(eventData1.platform).isEqualTo("android") assertThat(eventData1.played).isEqualTo(0) assertThat(eventData1.player).isEqualTo("bitmovin") assertThat(eventData1.playerKey).isEqualTo("dummyplayerKey") assertThat(eventData1.playerStartupTime).isEqualTo(1) assertThat(eventData1.playerTech).isEqualTo("Android:Exoplayer") assertThat(eventData1.progUrl).isEqualTo("https://test.com/prog") assertThat(eventData1.retryCount).isEqualTo(0) assertThat(eventData1.screenHeight).isEqualTo(2209) assertThat(eventData1.screenWidth).isEqualTo(1080) assertThat(eventData1.seeked).isEqualTo(0) assertThat(eventData1.sequenceNumber).isEqualTo(0) assertThat(eventData1.startupTime).isEqualTo(3929) assertThat(eventData1.state).isEqualTo("startup") assertThat(eventData1.streamFormat).isEqualTo("hls") assertThat(eventData1.subtitleEnabled).isFalse assertThat(eventData1.supportedVideoCodecs).isEqualTo(listOf("hevc", "vp9", "avc")) assertThat(eventData1.time).isEqualTo(1689091210921) assertThat(eventData1.userAgent).isEqualTo("Dalvik/2.1.0 (Linux; U; Android 13; sdk_gphone64_arm64 Build/TE1A.220922.029)") assertThat(eventData1.userId).isEqualTo("25f572b30123c015") assertThat(eventData1.version).isEqualTo("bitmovin-3.38.0") assertThat(eventData1.videoBitrate).isEqualTo(628000) assertThat(eventData1.videoCodec).isEqualTo("avc1.4D400D") assertThat(eventData1.videoDuration).isEqualTo(210000) assertThat(eventData1.videoId).isEqualTo("dummy-videoId") assertThat(eventData1.videoPlaybackHeight).isEqualTo(180) assertThat(eventData1.videoPlaybackWidth).isEqualTo(320) assertThat(eventData1.videoStartFailed).isFalse assertThat(eventData1.videoStartupTime).isEqualTo(3928) assertThat(eventData1.videoTimeEnd).isEqualTo(0) assertThat(eventData1.videoTimeStart).isEqualTo(0) assertThat(eventData1.videoTitle).isEqualTo("offlineSession") assertThat(eventData1.videoWindowHeight).isEqualTo(123) assertThat(eventData1.videoWindowWidth).isEqualTo(123) } }
0
Kotlin
6
8
c593bdde3d6968b8be6263b5a79c20af2c95df0d
13,363
bitmovin-analytics-collector-android
Amazon Digital Services License
core/src/main/kotlin/ch/ergon/dope/validtype/ValidType.kt
ergon
745,483,606
false
{"Kotlin": 377965}
package ch.ergon.dope.validtype sealed interface ValidType interface ComparableType : ValidType interface BooleanType : ValidType interface NumberType : ComparableType interface StringType : ComparableType interface NullType : ValidType interface MissingType : ValidType interface ArrayType<T : ValidType> : ValidType class DopeSchemaArray<T : Any>(val schema: T, val name: String) : ValidType
7
Kotlin
0
4
76aeb7e9a2a0bb1ee74df57c6a5efdc36d90da9d
403
dope-query-builder
MIT License
app/src/main/java/ca/josephroque/bowlingcompanion/statistics/impl/overall/LeftOfMiddleHitsStatistic.kt
autoreleasefool
28,992,199
false
null
package ca.josephroque.bowlingcompanion.statistics.impl.overall import android.os.Parcel import android.os.Parcelable import ca.josephroque.bowlingcompanion.R import ca.josephroque.bowlingcompanion.common.interfaces.parcelableCreator import ca.josephroque.bowlingcompanion.games.lane.Deck import ca.josephroque.bowlingcompanion.games.lane.isHitLeftOfMiddle import ca.josephroque.bowlingcompanion.statistics.StatisticsCategory import ca.josephroque.bowlingcompanion.statistics.impl.firstball.FirstBallStatistic /** * Copyright (C) 2018 Joseph Roque * * Percentage of shots which hit left of the middle pin. */ class LeftOfMiddleHitsStatistic(numerator: Int = 0, denominator: Int = 0) : FirstBallStatistic(numerator, denominator) { // MARK: Modifiers /** @Override */ override fun isModifiedBy(deck: Deck) = deck.isHitLeftOfMiddle // MARK: Overrides override val titleId = Id override val id = Id.toLong() override val category = StatisticsCategory.Overall // MARK: Parcelable companion object { /** Creator, required by [Parcelable]. */ @Suppress("unused") @JvmField val CREATOR = parcelableCreator(::LeftOfMiddleHitsStatistic) /** Unique ID for the statistic. */ const val Id = R.string.statistic_left_of_middle } /** * Construct this statistic from a [Parcel]. */ private constructor(p: Parcel): this(numerator = p.readInt(), denominator = p.readInt()) }
30
Kotlin
5
6
be42ac42d6c842b3126a8841990e5f9c8c6af232
1,468
bowling-companion
Apache License 2.0
app/src/main/java/com/mgpersia/androidbox/common/RoundedTransformation.kt
mahsak01
596,924,815
false
null
package com.mgpersia.androidbox.common import android.graphics.* import com.squareup.picasso.Transformation class RoundedTransformation( private val radius: Int, // dp private var margin: Int ) : Transformation { override fun transform(source: Bitmap): Bitmap { val paint = Paint() paint.isAntiAlias = true paint.shader = BitmapShader( source, Shader.TileMode.CLAMP, Shader.TileMode.CLAMP ) val output = Bitmap.createBitmap( source.width, source.height, Bitmap.Config.ARGB_8888 ) val canvas = Canvas(output) canvas.drawRoundRect( RectF( margin.toFloat(), margin.toFloat(), (source.width - margin).toFloat(), (source.height - margin).toFloat() ), radius.toFloat(), radius.toFloat(), paint ) if (source != output) { source.recycle() } return output } override fun key(): String { return "rounded" } // radius is corner radii in dp // margin is the board in dp init { margin = margin } }
0
Kotlin
0
0
e1ef9a8a316f76446718489f458e3a088ae55d15
1,165
ArianaFilm
The Unlicense
app/src/main/java/com/magonxesp/randomanimepicker/domain/anime/pick/AnimePick.kt
magonxesp
741,908,674
false
{"Kotlin": 269209, "Makefile": 1027}
package com.magonxesp.randomanimepicker.domain.anime.pick import com.magonxesp.randomanimepicker.domain.anime.AnimeId data class AnimePick( val like: AnimePickLike, val pickedOn: AnimePickOn, val anime: AnimeId )
0
Kotlin
0
1
1d6738bade13a9567417d2eaba2c76d156a90d69
218
RandomAnimePicker-android
MIT License
app/src/main/java/ke/derrick/steps/ui/theme/Shape.kt
Sciederrick
607,208,726
false
null
package ke.derrick.steps.ui.theme import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.material.Shapes val RoundedShapes = Shapes( small = RoundedCornerShape(percent = 20), medium = RoundedCornerShape(percent = 40), large = RoundedCornerShape(percent = 50), )
7
Kotlin
0
0
af5508c296b3c4fb982f5c779a5ea575b3ca0c6d
304
Steps
MIT License
lithic-java-core/src/main/kotlin/com/lithic/api/services/blocking/CardProductService.kt
lithic-com
592,386,416
false
{"Kotlin": 4349340, "Java": 5023, "Shell": 1068, "Dockerfile": 305}
// File generated from our OpenAPI spec by Stainless. @file:Suppress("OVERLOADS_INTERFACE") // See https://youtrack.jetbrains.com/issue/KT-36102 package com.lithic.api.services.blocking import com.lithic.api.core.RequestOptions import com.lithic.api.models.CardProductCreditDetailParams import com.lithic.api.models.CardProductCreditDetailResponse interface CardProductService { /** Get the Credit Detail for the card product */ @JvmOverloads fun creditDetail( params: CardProductCreditDetailParams, requestOptions: RequestOptions = RequestOptions.none() ): CardProductCreditDetailResponse }
1
Kotlin
0
15
d96120bd2375c77f762f1d90f920bf7db2303798
629
lithic-java
Apache License 2.0
lithic-java-core/src/main/kotlin/com/lithic/api/services/blocking/CardProductService.kt
lithic-com
592,386,416
false
{"Kotlin": 4349340, "Java": 5023, "Shell": 1068, "Dockerfile": 305}
// File generated from our OpenAPI spec by Stainless. @file:Suppress("OVERLOADS_INTERFACE") // See https://youtrack.jetbrains.com/issue/KT-36102 package com.lithic.api.services.blocking import com.lithic.api.core.RequestOptions import com.lithic.api.models.CardProductCreditDetailParams import com.lithic.api.models.CardProductCreditDetailResponse interface CardProductService { /** Get the Credit Detail for the card product */ @JvmOverloads fun creditDetail( params: CardProductCreditDetailParams, requestOptions: RequestOptions = RequestOptions.none() ): CardProductCreditDetailResponse }
1
Kotlin
0
15
d96120bd2375c77f762f1d90f920bf7db2303798
629
lithic-java
Apache License 2.0
app/src/main/kotlin/com/numero/sojodia/ui/splash/SplashPresenter.kt
NUmeroAndDev
58,176,699
false
null
package com.numero.sojodia.ui.splash import com.numero.sojodia.core.Presenter interface SplashPresenter : Presenter
14
Kotlin
3
9
8769696e7f087a78d036956569c1d73ff0507df7
117
SojoDia-android
MIT License
src/main/kotlin/io/github/dqualizer/dqlang/types/adapter/ctk/Pauses.kt
dqualizer
610,310,524
false
{"Kotlin": 110854, "HTML": 3542, "Python": 3352}
package io.github.dqualizer.dqlang.types.adapter.ctk data class Pauses( val before: Int = 0, val after: Int = 0 )
6
Kotlin
0
0
938543c2fd0602879492bd9183c668d98d631f3c
119
dqlang
Apache License 2.0
app/src/main/java/com/challenge/android_template/ui/MainActivity.kt
merRen22
392,808,733
false
null
package com.challenge.android_template.ui import android.annotation.SuppressLint import android.graphics.drawable.TransitionDrawable import android.os.Build import android.os.Bundle import androidx.activity.viewModels import androidx.activity.compose.setContent import androidx.appcompat.app.AppCompatActivity import androidx.core.splashscreen.SplashScreen.Companion.installSplashScreen import com.challenge.android_template.R import com.challenge.android_template.base.viewmodel.SystemViewModel import dagger.hilt.android.AndroidEntryPoint import androidx.compose.animation.* import androidx.hilt.navigation.compose.hiltNavGraphViewModel import androidx.compose.runtime.* import androidx.hilt.navigation.compose.hiltViewModel import androidx.lifecycle.lifecycleScope import androidx.navigation.compose.* import com.challenge.android_template.baseui.BaseTheme import com.challenge.android_template.baseui.navigation.FeedDirections import com.challenge.android_template.baseui.navigation.NavigationManager import com.challenge.android_template.baseui.utilScreens.GenericErrorScreen import com.challenge.android_template.feed.FeedUI import com.challenge.android_template.feed.FeedViewModel import kotlinx.coroutines.delay import kotlinx.coroutines.launch import javax.inject.Inject @AndroidEntryPoint @ExperimentalAnimationApi class MainActivity : AppCompatActivity() { @Inject lateinit var navigationManager: NavigationManager private val systemViewModel: SystemViewModel by viewModels() companion object { const val splashFadeDurationMillis = 300 } override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) val splashWasDisplayed = savedInstanceState != null // check if we can make use of splash screen api for andriod 12 if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) if (!splashWasDisplayed) { displayAndroid12Animation() } else { android12AnimationAlreadyShow() } else { if (!splashWasDisplayed) { (window.decorView.background as TransitionDrawable).startTransition( splashFadeDurationMillis ) // no trigger for when animations end so coroutine is used lifecycleScope.launch { delay( splashFadeDurationMillis.toLong() + 200 ) android12AnimationAlreadyShow() } } else { android12AnimationAlreadyShow() } } } private fun displayAndroid12Animation() { val splashScreen = installSplashScreen() splashScreen.setOnExitAnimationListener { splashScreenViewProvider -> splashScreenViewProvider.iconView .animate() .setDuration(splashFadeDurationMillis.toLong()) .alpha(0f) .withEndAction { splashScreenViewProvider.remove() android12AnimationAlreadyShow() }.start() } } @SuppressLint("UnrememberedGetBackStackEntry") private fun android12AnimationAlreadyShow() { setTheme(R.style.Theme_AnimatedSplashScreen) setContent { BaseTheme { val navController = rememberNavController() navigationManager.commands.collectAsState().value.also { command -> if (command.destination.isNotEmpty()) { navController.navigate(command.destination) } } Navigation(navController = navController) } } } }
0
Kotlin
0
0
e94b54a1b9f4786315bfdf6caf81445fc89b9fab
3,415
template-android
Apache License 2.0
src/main/kotlin/com/charylin/game/model/Blast.kt
GitLqr
313,784,463
false
null
package com.charylin.game.model import com.charylin.game.Config import com.charylin.game.business.Destroyable import org.itheima.kotlin.game.core.Painter /** * @author LQR * @time 2020/11/19 * @desc 爆炸物 */ class Blast(override val x: Int, override val y: Int) : View, Destroyable { override val width: Int = Config.block override val height: Int = Config.block private val imagePaths = arrayListOf<String>() private var index: Int = 0 init { (1..32).forEach { imagePaths.add("img/blast_${it}.png") } } override fun draw() { val i = index % imagePaths.size Painter.drawImage(imagePaths[i], x, y) index++ } override fun isDestroy(): Boolean { return index >= imagePaths.size } }
0
Kotlin
0
1
437ee515e3456679b178223dcc9ef5004cf40857
787
game-tank
MIT License
applications/tools/universal-blob-inspector/src/main/kotlin/net/corda/blobinspector/amqp/DynamicDescriptorRegistry.kt
corda
346,070,752
false
{"Kotlin": 20585419, "Java": 308202, "Smarty": 115357, "Shell": 54409, "Groovy": 30246, "PowerShell": 6470, "TypeScript": 5826, "Solidity": 2024, "Batchfile": 244}
package net.corda.blobinspector.amqp import org.apache.qpid.proton.amqp.UnsignedInteger class DynamicDescriptorRegistry(private val lenientBuiltIns: Boolean = false) { private val prefix = "net.corda:" private val types: MutableMap<Descriptor, TypeHandle> = mutableMapOf() init { for (value in PredefinedDescriptorRegistry.values()) { types[Descriptor(null, value.amqpDescriptor)] = PredefinedTypeHandle(value.name) } } fun register(type: TypeNotation) { types[type.descriptor] = when (type) { is CompositeType -> CompositeTypeHandle(type) is RestrictedType -> RestrictedTypeHandle(type) } } operator fun get(descriptor: Descriptor): TypeHandle? { return types[descriptor] ?: resolveBuiltIn(descriptor) } private fun resolveBuiltIn(descriptor: Descriptor): TypeHandle? { if (descriptor.name == null || (!lenientBuiltIns && !descriptor.name.startsWith(prefix))) return null val name = descriptor.name.substring(prefix.length) return try { if (!lenientBuiltIns) Class.forName(name) val handle = CustomTypeHandle(name) types[Descriptor(name)] = handle handle } catch (e: ClassNotFoundException) { null } } interface TypeHandle { fun transform(value: Any?, referencedObjects: MutableList<Any?>): Any? } class CompositeTypeHandle(private val type: CompositeType) : TypeHandle { override fun transform(value: Any?, referencedObjects: MutableList<Any?>): Any { val list = value as List<Any?> val map: MutableMap<String, Any?> = mutableMapOf() map["_class"] = type.name type.fields.forEachIndexed { index, field -> map[field.name] = list[index] } return map } } class RestrictedTypeHandle( @Suppress("Unused") val type: RestrictedType ) : TypeHandle { override fun transform(value: Any?, referencedObjects: MutableList<Any?>): Any? { return value } } class CustomTypeHandle(private val name: String) : TypeHandle { override fun transform(value: Any?, referencedObjects: MutableList<Any?>): Any { return mapOf("_custom" to name, "_value" to value) } } class PredefinedTypeHandle(private val name: String) : TypeHandle { override fun transform(value: Any?, referencedObjects: MutableList<Any?>): Any? { return if (name == "REFERENCED_OBJECT") { val position = (value as UnsignedInteger).toInt() // println(position) // referencedObjects.forEachIndexed { index, obj -> println("$index $obj") } referencedObjects[position] } else { mapOf("_predefined" to name, "_value" to value) } } } }
11
Kotlin
27
69
d478e119ab288af663910f9a2df42a7a7b9f5bce
2,964
corda-runtime-os
Apache License 2.0
backend.native/tests/external/stdlib/text/StringTest/reverse.kt
juliuskunze
116,136,849
false
null
import kotlin.test.* fun box() { assertEquals("dcba", "abcd".reversed()) assertEquals("4321", "1234".reversed()) assertEquals("", "".reversed()) }
0
null
0
1
2e07b3f52f99b51d353a8c0e53bdf9fff86988e0
162
kotlin-native
Apache License 2.0
core/presentation/src/main/kotlin/org/cazait/presentation/ui/signin/SignInFragment.kt
CaZaIt
594,701,085
false
null
package org.cazait.presentation.ui.signin import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.databinding.DataBindingUtil import androidx.fragment.app.Fragment import androidx.fragment.app.activityViewModels import androidx.lifecycle.Lifecycle import androidx.lifecycle.lifecycleScope import androidx.lifecycle.repeatOnLifecycle import androidx.navigation.fragment.findNavController import com.google.android.material.snackbar.Snackbar import dagger.hilt.android.AndroidEntryPoint import kotlinx.coroutines.launch import org.cazait.presentation.R import org.cazait.presentation.databinding.FragmentSignInBinding @AndroidEntryPoint class SignInFragment : Fragment() { private var _binding: FragmentSignInBinding? = null private val binding get() = _binding!! private val viewModel: SignInViewModel by activityViewModels() override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View { _binding = DataBindingUtil.inflate<FragmentSignInBinding>( inflater, R.layout.fragment_sign_in, container, false ).apply { lifecycleOwner = this@SignInFragment.viewLifecycleOwner viewModel = this@SignInFragment.viewModel fragment = this@SignInFragment } return binding.root } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) observeViewModel() } override fun onDestroy() { super.onDestroy() _binding = null } private fun observeViewModel() { viewLifecycleOwner.lifecycleScope.launch { repeatOnLifecycle(Lifecycle.State.STARTED) { launch { viewModel.userPreference.collect { if (it.isLoggedIn) { navigateToStoreStatusFragment() } } } launch { viewModel.signInInfoStateFlow.collect { signInResult -> if (signInResult == null) return@collect navigateToStoreStatusFragment() } } launch { viewModel.guideMessage.collect { message -> if (message.isNotEmpty()) showMessage(message) } } } } } private fun showMessage(message: String) { Snackbar.make(requireView(), message, Snackbar.LENGTH_SHORT).show() } private fun navigateToStoreStatusFragment() { findNavController().navigate(SignInFragmentDirections.actionSignInFragmentToStoreStatusFragment()) } fun navigateToSignUpFragment() { findNavController().navigate(SignInFragmentDirections.actionSignInFragmentToSignUpFragment()) } }
2
Kotlin
0
0
31b6496d1e028fe002c146319333b3f795e4c1c3
3,067
CaZaIt-Android-Admin
Apache License 2.0
buildSrc/src/main/kotlin/korlibs/korge/gradle/targets/js/Esbuild.kt
korlibs
80,095,683
false
null
package korlibs.korge.gradle.targets.js import korlibs.korge.gradle.* import korlibs.korge.gradle.util.* import org.gradle.api.* import org.gradle.api.file.* import org.gradle.api.tasks.* import org.jetbrains.kotlin.gradle.targets.js.ir.* import java.io.* fun Project.configureEsbuild() { try { configureErrorableEsbuild() } catch (e: Throwable) { e.printStackTrace() } } fun Project.configureErrorableEsbuild() { val userGradleFolder = File(System.getProperty("user.home"), ".gradle") val wwwFolder = File(buildDir, "www") val esbuildFolder = File(if (userGradleFolder.isDirectory) userGradleFolder else rootProject.buildDir, "esbuild") val isWindows = org.apache.tools.ant.taskdefs.condition.Os.isFamily(org.apache.tools.ant.taskdefs.condition.Os.FAMILY_WINDOWS) val esbuildCommand = File(esbuildFolder, if (isWindows) "esbuild.cmd" else "bin/esbuild") val esbuildCmd = if (isWindows) listOf("cmd.exe", "/c", esbuildCommand) else listOf(esbuildCommand) val npmInstallEsbuildTaskName = "npmInstallEsbuild" val env by lazy { org.jetbrains.kotlin.gradle.targets.js.nodejs.NodeJsRootPlugin.apply(project.rootProject).requireConfigured() } val ENV_PATH by lazy { val NODE_PATH = File(env.nodeExecutable).parent val PATH_SEPARATOR = File.pathSeparator val OLD_PATH = System.getenv("PATH") "$NODE_PATH$PATH_SEPARATOR$OLD_PATH" } val npmInstallEsbuild = rootProject.tasks.findByName(npmInstallEsbuildTaskName) ?: rootProject.tasks.createThis<Exec>(npmInstallEsbuildTaskName) { dependsOn("kotlinNodeJsSetup") onlyIf { !esbuildCommand.exists() } val esbuildVersion = korge.esbuildVersion doFirst { //val nodeDir = env.nodeBinDir val nodeDir = env.dir val file1: File = File(env.nodeExecutable) val file2: File? = File(nodeDir, "lib/node_modules/npm/bin/npm-cli.js").takeIf { it.exists() } val file3: File? = File(nodeDir, "node_modules/npm/bin/npm-cli.js").takeIf { it.exists() } val npmCmd = arrayOf<File>( file1, file2 ?: file2 ?: error("Can't find npm-cli.js in ${nodeDir} standard folders") ) environment("PATH", ENV_PATH) commandLine(*npmCmd, "-g", "install", "esbuild@$esbuildVersion", "--prefix", esbuildFolder, "--scripts-prepend-node-path", "true") } } val browserEsbuildResources = tasks.createThis<Copy>("browserEsbuildResources") { val korgeProcessResourcesTaskName = getKorgeProcessResourcesTaskName("js", "main") dependsOn(korgeProcessResourcesTaskName) duplicatesStrategy = DuplicatesStrategy.EXCLUDE from(project.tasks.getByName("jsProcessResources").outputs.files) //afterEvaluate { // project.tasks.findByName(getKorgeProcessResourcesTaskName("js", "main"))?.outputs?.files?.let { // from(it) // } //} //for (sourceSet in gkotlin.js().compilations.flatMap { it.kotlinSourceSets }) from(sourceSet.resources) into(wwwFolder) //afterEvaluate { // afterEvaluate { // val korgeGeneratedTask = project.tasks.findByName(korgeProcessResourcesTaskName) as? KorgeGenerateResourcesTask? // println("korgeGeneratedTaskName=$korgeGeneratedTask : korgeProcessResourcesTaskName=$korgeProcessResourcesTaskName") // korgeGeneratedTask?.addExcludeToCopyTask(this) // } //} } val browserPrepareEsbuildPrepare = tasks.createThis<Task>("browserPrepareEsbuildPrepare") { dependsOn(browserEsbuildResources) dependsOn(npmInstallEsbuild) } val browserPrepareEsbuildDebug = tasks.createThis<Task>("browserPrepareEsbuildDebug") { dependsOn("compileDevelopmentExecutableKotlinJs") dependsOn(browserPrepareEsbuildPrepare) } val browserPrepareEsbuildRelease = tasks.createThis<Task>("browserPrepareEsbuildRelease") { dependsOn("compileProductionExecutableKotlinJs") dependsOn(browserPrepareEsbuildPrepare) } for (debug in listOf(false, true)) { val debugPrefix = if (debug) "Debug" else "Release" val productionInfix = if (debug) "Development" else "Production" val browserPrepareEsbuild = when { debug -> browserPrepareEsbuildDebug else -> browserPrepareEsbuildRelease } // browserDebugEsbuild // browserReleaseEsbuild tasks.createThis<Exec>("browser${debugPrefix}Esbuild") { group = "kotlin browser" val compileExecutableKotlinJs = tasks.getByName("compile${productionInfix}ExecutableKotlinJs") as KotlinJsIrLink dependsOn(browserPrepareEsbuild) dependsOn(compileExecutableKotlinJs) val jsBasePath = compileExecutableKotlinJs.destinationDirectory.asFile.get().absolutePath + "/" + compileExecutableKotlinJs.compilerOptions.moduleName.get() val jsPath = "$jsBasePath.js" // Normal JS val mjsPath = "$jsBasePath.mjs" // ES2015 //val finalJsPath = mjsPath val finalJsPath = jsPath val output = File(wwwFolder, "${project.name}.js") //println("jsPath=$jsPath") //println("jsPath.parentFile=${jsPath.parentFile}") //println("outputs=${compileExecutableKotlinJs.outputs.files.toList()}") inputs.files(compileExecutableKotlinJs.outputs.files) outputs.file(output) environment("PATH", ENV_PATH) doFirst { commandLine(buildList { addAll(esbuildCmd) //add("--watch",) add("--bundle") if (!debug) { add("--minify") add("--sourcemap=external") } add(finalJsPath) add("--outfile=$output") // @TODO: Close this command on CTRL+C //if (run) add("--servedir=$wwwFolder") }) } } } }
464
null
123
2,497
1a565007ab748e00a4d602fcd78f7d4032afaf0b
6,232
korge
Apache License 2.0
tehreer-android/src/main/java/com/mta/tehreer/graphics/GlyphKey.kt
Tehreer
68,520,755
false
null
/* * Copyright (C) 2023 <NAME> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.mta.tehreer.graphics internal abstract class GlyphKey { var typeface: Typeface? = null var pixelWidth = 0 // 26.6 fixed-point value. var pixelHeight = 0 // 26.6 fixed-point value. var skewX = 0 // 16.16 fixed-point value. abstract fun copy(): GlyphKey protected fun set(key: GlyphKey) { typeface = key.typeface pixelWidth = key.pixelWidth pixelHeight = key.pixelHeight skewX = key.skewX } override fun equals(other: Any?): Boolean { if (other !is GlyphKey) return false if (typeface != other.typeface) return false if (pixelWidth != other.pixelWidth) return false if (pixelHeight != other.pixelHeight) return false if (skewX != other.skewX) return false return true } override fun hashCode(): Int { var result = typeface?.hashCode() ?: 0 result = 31 * result + pixelWidth result = 31 * result + pixelHeight result = 31 * result + skewX return result } class Data : GlyphKey() { override fun copy(): Data { val key = Data() key.set(this) return key } override fun equals(other: Any?): Boolean { if (this === other) return true if (other !is Data) return false if (!super.equals(other)) return false return true } } class Color : GlyphKey() { var foregroundColor = 0 fun set(key: Data) { super.set(key) } override fun copy(): Color { val key = Color() key.set(this) key.foregroundColor = foregroundColor return key } override fun equals(other: Any?): Boolean { if (this === other) return true if (other !is Color) return false if (!super.equals(other)) return false if (foregroundColor != other.foregroundColor) return false return true } override fun hashCode(): Int { var result = super.hashCode() result = 31 * result + foregroundColor return result } } class Stroke : GlyphKey() { var lineRadius = 0 var lineCap = 0 var lineJoin = 0 var miterLimit = 0 fun set(key: Data) { super.set(key) } override fun copy(): Stroke { val key = Stroke() key.set(this) key.lineRadius = lineRadius key.lineCap = lineCap key.lineJoin = lineJoin key.miterLimit = miterLimit return key } override fun equals(other: Any?): Boolean { if (this === other) return true if (other !is Stroke) return false if (!super.equals(other)) return false if (lineRadius != other.lineRadius) return false if (lineCap != other.lineCap) return false if (lineJoin != other.lineJoin) return false if (miterLimit != other.miterLimit) return false return true } override fun hashCode(): Int { var result = super.hashCode() result = 31 * result + lineRadius result = 31 * result + lineCap result = 31 * result + lineJoin result = 31 * result + miterLimit return result } } }
2
C
16
78
74aa7286b37efe058971e3bee427214bffbc5ad5
4,069
Tehreer-Android
Apache License 2.0
src/main/java/io/acari/DDLC/themes/dark/DeletedCharacterTheme.kt
ezc
161,744,541
false
null
package io.acari.DDLC.themes.dark import com.chrisrm.ideaddlc.utils.MTAccents import io.acari.DDLC.themes.DokiDokiTheme import javax.swing.plaf.ColorUIResource /** * C̸̮͙̭̀h̷̯̯̋͊̅ä̶̠̟̝́ȑ̸̟̝̪̇a̵̞̙͝c̴̩͝t̵̳͉̆ẻ̴̫r̸̨̢͑ ̷̡̛̛͍͐n̶̡͚̻̽o̵͈͌̈͝t̴̻͚͑̏̽ ̴̰͌f̷̫͛ò̴̠̺̝ú̵̧̲̘̐̚ṅ̸̠̠̰d̵̦͎̲͠͠ */ class DeletedCharacterTheme : DokiDokiTheme("deleted.character", "Deleted Character", true, "Š̸̘͚̼͎̯̙̣̱̎̋̐͒a̴̖̟̠̳̤͙̟͂̂͑̐͜ỷ̵̧̨̞̠̖̠o̴̧͍̗̬̎̓͆̔͝ͅr̴̡̮̟͈͠ͅi̴̡̨͓͈̬̗̺̍́̃̇̓") { override fun getBackgroundColorString(): String = "0E1D31" override fun getBackgroundColorResource(): ColorUIResource = ColorUIResource(0x0e1d31) override fun getForegroundColorResource(): ColorUIResource = ColorUIResource(0x2687C6) override fun getTableSelectedColorString(): String = "26374C" override fun getAccentColor(): String { return MTAccents.CYAN.hexColor } override fun getClubMember(): String = "sayori_dark.png" override fun joyfulClubMember(): String = "sayori_dark_joy.png" override fun getSecondaryBackgroundColorString(): String = "111B28" override fun getSecondaryForegroundColorString(): String = "157174" override fun getSelectionForegroundColorString(): String = "9CF5FF" override fun getSelectionBackgroundColorString(): String = "324964" override fun getTreeSelectionBackgroundColorString(): String = "1D358C" override fun getMenuBarSelectionForegroundColorString(): String = "ffffff" override fun getMenuBarSelectionBackgroundColorString(): String = "7C081A" override fun getNotificationsColorString(): String = "335063" override fun getContrastColorString(): String = "1B323F" override fun getButtonBackgroundColor(): String = contrastColorString override fun getButtonForegroundColor(): String = "26A8E8" override fun getForegroundColorString(): String = "2687C6" override fun getTextColorString(): String = "6BB2CE" override fun getEditorTabColorString(): String = contrastColorString override fun getNonProjectFileScopeColor(): String = "102121" override fun getTestScope(): String = "0c3118" override fun getSecondBorderColorString(): String = "1B467C" override fun getDisabledColorString(): String = "232323" override fun getHighlightColorString(): String = "07356A" }
1
null
1
1
de9010c32203e5fe52cc10f550581fad081a264e
2,294
ddlc-jetbrains-theme
MIT License
sdk/src/test/java/com/stytch/sdk/consumer/network/StytchApiTest.kt
stytchauth
314,556,359
false
{"Kotlin": 1178299, "HTML": 508}
package com.stytch.sdk.consumer.network import android.app.Application import android.content.Context import com.stytch.sdk.common.DeviceInfo import com.stytch.sdk.common.EncryptionManager import com.stytch.sdk.common.StorageHelper import com.stytch.sdk.common.StytchResult import com.stytch.sdk.common.errors.StytchAPIError import com.stytch.sdk.common.errors.StytchSDKNotConfiguredError import com.stytch.sdk.common.network.InfoHeaderModel import com.stytch.sdk.common.network.StytchDataResponse import com.stytch.sdk.common.network.models.CommonRequests import com.stytch.sdk.consumer.StytchClient import com.stytch.sdk.consumer.network.models.ConsumerRequests import io.mockk.clearAllMocks import io.mockk.coEvery import io.mockk.coVerify import io.mockk.every import io.mockk.just import io.mockk.mockk import io.mockk.mockkObject import io.mockk.mockkStatic import io.mockk.runs import io.mockk.unmockkAll import java.security.KeyStore import kotlinx.coroutines.test.runTest import org.junit.After import org.junit.Before import org.junit.Test import retrofit2.HttpException internal class StytchApiTest { var mContextMock = mockk<Context>(relaxed = true) private val mockDeviceInfo = DeviceInfo( applicationPackageName = "com.stytch.test", applicationVersion = "1.0.0", osName = "Android", osVersion = "14", deviceName = "<NAME>", screenSize = "" ) @Before fun before() { val mockApplication: Application = mockk { every { registerActivityLifecycleCallbacks(any()) } just runs every { packageName } returns "Stytch" } mContextMock = mockk(relaxed = true) { every { applicationContext } returns mockApplication } mockkStatic(KeyStore::class) mockkObject(EncryptionManager) mockkObject(StytchApi) every { EncryptionManager.createNewKeys(any(), any()) } returns Unit every { KeyStore.getInstance(any()) } returns mockk(relaxed = true) mockkObject(StorageHelper) } @After fun after() { unmockkAll() clearAllMocks() } @Test fun `StytchApi isInitialized returns correctly based on configuration state`() { StytchApi.configure("publicToken", DeviceInfo()) assert(StytchApi.isInitialized) } @Test(expected = StytchSDKNotConfiguredError::class) fun `StytchApi apiService throws exception when not configured`() { every { StytchApi.isInitialized } returns false StytchApi.apiService } @Test fun `StytchApi apiService is available when configured`() { StytchClient.configure(mContextMock, "") StytchApi.apiService } // TODO every method calls safeApi @Test fun `StytchApi MagicLinks Email loginOrCreate calls appropriate apiService method`() = runTest { every { StytchApi.isInitialized } returns true coEvery { StytchApi.apiService.loginOrCreateUserByEmail(any()) } returns mockk(relaxed = true) StytchApi.MagicLinks.Email.loginOrCreate("", "", "", "", "", "") coVerify { StytchApi.apiService.loginOrCreateUserByEmail(any()) } } @Test fun `StytchApi MagicLinks Email sendPrimary calls appropriate apiService method`() = runTest { every { StytchApi.isInitialized } returns true coEvery { StytchApi.apiService.sendEmailMagicLinkPrimary(any()) } returns mockk(relaxed = true) StytchApi.MagicLinks.Email.sendPrimary("", null, null, null, null, null, null, null) coVerify { StytchApi.apiService.sendEmailMagicLinkPrimary(any()) } } @Test fun `StytchApi MagicLinks Email sendSecondar calls appropriate apiService method`() = runTest { every { StytchApi.isInitialized } returns true coEvery { StytchApi.apiService.sendEmailMagicLinkSecondary(any()) } returns mockk(relaxed = true) StytchApi.MagicLinks.Email.sendSecondary("", null, null, null, null, null, null, null) coVerify { StytchApi.apiService.sendEmailMagicLinkSecondary(any()) } } @Test fun `StytchApi MagicLinks Email authenticate calls appropriate apiService method`() = runTest { every { StytchApi.isInitialized } returns true coEvery { StytchApi.apiService.authenticate(any()) } returns mockk(relaxed = true) StytchApi.MagicLinks.Email.authenticate("", 30U, "") coVerify { StytchApi.apiService.authenticate(any()) } } @Test fun `StytchApi OTP loginOrCreateByOTPWithSMS calls appropriate apiService method`() = runTest { every { StytchApi.isInitialized } returns true coEvery { StytchApi.apiService.loginOrCreateUserByOTPWithSMS(any()) } returns mockk(relaxed = true) StytchApi.OTP.loginOrCreateByOTPWithSMS("", 30U) coVerify { StytchApi.apiService.loginOrCreateUserByOTPWithSMS(any()) } } @Test fun `StytchApi OTP sendOTPWithSMSPrimary calls appropriate apiService method`() = runTest { every { StytchApi.isInitialized } returns true coEvery { StytchApi.apiService.sendOTPWithSMSPrimary(any()) } returns mockk(relaxed = true) StytchApi.OTP.sendOTPWithSMSPrimary("", 30U) coVerify { StytchApi.apiService.sendOTPWithSMSPrimary(any()) } } @Test fun `StytchApi OTP sendOTPWithSMSSecondary calls appropriate apiService method`() = runTest { every { StytchApi.isInitialized } returns true coEvery { StytchApi.apiService.sendOTPWithSMSSecondary(any()) } returns mockk(relaxed = true) StytchApi.OTP.sendOTPWithSMSSecondary("", 30U) coVerify { StytchApi.apiService.sendOTPWithSMSSecondary(any()) } } @Test fun `StytchApi OTP loginOrCreateUserByOTPWithWhatsApp calls appropriate apiService method`() = runTest { every { StytchApi.isInitialized } returns true coEvery { StytchApi.apiService.loginOrCreateUserByOTPWithWhatsApp(any()) } returns mockk(relaxed = true) StytchApi.OTP.loginOrCreateUserByOTPWithWhatsApp("", 30U) coVerify { StytchApi.apiService.loginOrCreateUserByOTPWithWhatsApp(any()) } } @Test fun `StytchApi OTP sendByOTPWithWhatsAppPrimary calls appropriate apiService method`() = runTest { every { StytchApi.isInitialized } returns true coEvery { StytchApi.apiService.sendOTPWithWhatsAppPrimary(any()) } returns mockk(relaxed = true) StytchApi.OTP.sendOTPWithWhatsAppPrimary("", 30U) coVerify { StytchApi.apiService.sendOTPWithWhatsAppPrimary(any()) } } @Test fun `StytchApi OTP sendByOTPWithWhatsAppSecondary calls appropriate apiService method`() = runTest { every { StytchApi.isInitialized } returns true coEvery { StytchApi.apiService.sendOTPWithWhatsAppSecondary(any()) } returns mockk(relaxed = true) StytchApi.OTP.sendOTPWithWhatsAppSecondary("", 30U) coVerify { StytchApi.apiService.sendOTPWithWhatsAppSecondary(any()) } } @Test fun `StytchApi OTP loginOrCreateUserByOTPWithEmail calls appropriate apiService method`() = runTest { every { StytchApi.isInitialized } returns true coEvery { StytchApi.apiService.loginOrCreateUserByOTPWithEmail(any()) } returns mockk(relaxed = true) StytchApi.OTP.loginOrCreateUserByOTPWithEmail("", 30U, "", "") coVerify { StytchApi.apiService.loginOrCreateUserByOTPWithEmail(any()) } } @Test fun `StytchApi OTP sendOTPWithEmailPrimary calls appropriate apiService method`() = runTest { every { StytchApi.isInitialized } returns true coEvery { StytchApi.apiService.sendOTPWithEmailPrimary(any()) } returns mockk(relaxed = true) StytchApi.OTP.sendOTPWithEmailPrimary("", 30U, null, null) coVerify { StytchApi.apiService.sendOTPWithEmailPrimary(any()) } } @Test fun `StytchApi OTP sendOTPWithEmailSecondary calls appropriate apiService method`() = runTest { every { StytchApi.isInitialized } returns true coEvery { StytchApi.apiService.sendOTPWithEmailSecondary(any()) } returns mockk(relaxed = true) StytchApi.OTP.sendOTPWithEmailSecondary("", 30U, null, null) coVerify { StytchApi.apiService.sendOTPWithEmailSecondary(any()) } } @Test fun `StytchApi OTP authenticateWithOTP calls appropriate apiService method`() = runTest { every { StytchApi.isInitialized } returns true coEvery { StytchApi.apiService.authenticateWithOTP(any()) } returns mockk(relaxed = true) StytchApi.OTP.authenticateWithOTP("", "") coVerify { StytchApi.apiService.authenticateWithOTP(any()) } } @Test fun `StytchApi Passwords authenticate calls appropriate apiService method`() = runTest { every { StytchApi.isInitialized } returns true coEvery { StytchApi.apiService.authenticateWithPasswords(any()) } returns mockk(relaxed = true) StytchApi.Passwords.authenticate("", "", 30U) coVerify { StytchApi.apiService.authenticateWithPasswords(any()) } } @Test fun `StytchApi Passwords create calls appropriate apiService method`() = runTest { every { StytchApi.isInitialized } returns true coEvery { StytchApi.apiService.passwords(any()) } returns mockk(relaxed = true) StytchApi.Passwords.create("", "", 30U) coVerify { StytchApi.apiService.passwords(any()) } } @Test fun `StytchApi Passwords resetByEmailStart calls appropriate apiService method`() = runTest { every { StytchApi.isInitialized } returns true coEvery { StytchApi.apiService.resetByEmailStart(any()) } returns mockk(relaxed = true) StytchApi.Passwords.resetByEmailStart("", "", "", "", 30, "", 30, "") coVerify { StytchApi.apiService.resetByEmailStart(any()) } } @Test fun `StytchApi Passwords resetByEmail calls appropriate apiService method`() = runTest { every { StytchApi.isInitialized } returns true coEvery { StytchApi.apiService.resetByEmail(any()) } returns mockk(relaxed = true) StytchApi.Passwords.resetByEmail("", "", 30U, "") coVerify { StytchApi.apiService.resetByEmail(any()) } } @Test fun `StytchApi Passwords resetBySession calls appropriate apiService method`() = runTest { every { StytchApi.isInitialized } returns true coEvery { StytchApi.apiService.resetBySession(any()) } returns mockk(relaxed = true) StytchApi.Passwords.resetBySession(password = "", sessionDurationMinutes = 30U) coVerify { StytchApi.apiService.resetBySession(any()) } } @Test fun `StytchApi Passwords strengthCheck calls appropriate apiService method`() = runTest { every { StytchApi.isInitialized } returns true coEvery { StytchApi.apiService.strengthCheck(any()) } returns mockk(relaxed = true) StytchApi.Passwords.strengthCheck("", "") coVerify { StytchApi.apiService.strengthCheck(any()) } } @Test fun `StytchApi Sessions authenticate calls appropriate apiService method`() = runTest { every { StytchApi.isInitialized } returns true coEvery { StytchApi.apiService.authenticateSessions(any()) } returns mockk(relaxed = true) StytchApi.Sessions.authenticate(30U) coVerify { StytchApi.apiService.authenticateSessions(any()) } } @Test fun `StytchApi Sessions revoke calls appropriate apiService method`() = runTest { every { StytchApi.isInitialized } returns true coEvery { StytchApi.apiService.revokeSessions() } returns mockk(relaxed = true) StytchApi.Sessions.revoke() coVerify { StytchApi.apiService.revokeSessions() } } @Test fun `StytchApi Biometrics registerStart calls appropriate apiService method`() = runTest { every { StytchApi.isInitialized } returns true coEvery { StytchApi.apiService.biometricsRegisterStart(any()) } returns mockk(relaxed = true) StytchApi.Biometrics.registerStart("") coVerify { StytchApi.apiService.biometricsRegisterStart(any()) } } @Test fun `StytchApi Biometrics register calls appropriate apiService method`() = runTest { every { StytchApi.isInitialized } returns true coEvery { StytchApi.apiService.biometricsRegister(any()) } returns mockk(relaxed = true) StytchApi.Biometrics.register("", "", 30U) coVerify { StytchApi.apiService.biometricsRegister(any()) } } @Test fun `StytchApi Biometrics authenticateStart calls appropriate apiService method`() = runTest { every { StytchApi.isInitialized } returns true coEvery { StytchApi.apiService.biometricsAuthenticateStart(any()) } returns mockk(relaxed = true) StytchApi.Biometrics.authenticateStart("") coVerify { StytchApi.apiService.biometricsAuthenticateStart(any()) } } @Test fun `StytchApi Biometrics authenticate calls appropriate apiService method`() = runTest { every { StytchApi.isInitialized } returns true coEvery { StytchApi.apiService.biometricsAuthenticate(any()) } returns mockk(relaxed = true) StytchApi.Biometrics.authenticate("", "", 30U) coVerify { StytchApi.apiService.biometricsAuthenticate(any()) } } @Test fun `StytchApi User getUser calls appropriate apiService method`() = runTest { every { StytchApi.isInitialized } returns true coEvery { StytchApi.apiService.getUser() } returns mockk(relaxed = true) StytchApi.UserManagement.getUser() coVerify { StytchApi.apiService.getUser() } } @Test fun `StytchApi User deleteEmailById calls appropriate apiService method`() = runTest { every { StytchApi.isInitialized } returns true coEvery { StytchApi.apiService.deleteEmailById("emailAddressId") } returns mockk(relaxed = true) StytchApi.UserManagement.deleteEmailById("emailAddressId") coVerify { StytchApi.apiService.deleteEmailById("emailAddressId") } } @Test fun `StytchApi User deletePhoneNumberById calls appropriate apiService method`() = runTest { every { StytchApi.isInitialized } returns true coEvery { StytchApi.apiService.deletePhoneNumberById("phoneNumberId") } returns mockk(relaxed = true) StytchApi.UserManagement.deletePhoneNumberById("phoneNumberId") coVerify { StytchApi.apiService.deletePhoneNumberById("phoneNumberId") } } @Test fun `StytchApi User deleteBiometricRegistrationById calls appropriate apiService method`() = runTest { every { StytchApi.isInitialized } returns true coEvery { StytchApi.apiService.deleteBiometricRegistrationById("biometricsRegistrationId") } returns mockk(relaxed = true) StytchApi.UserManagement.deleteBiometricRegistrationById("biometricsRegistrationId") coVerify { StytchApi.apiService.deleteBiometricRegistrationById("biometricsRegistrationId") } } @Test fun `StytchApi User updateUser calls appropriate apiService method`() = runTest { every { StytchApi.isInitialized } returns true coEvery { StytchApi.apiService.updateUser(any()) } returns mockk(relaxed = true) StytchApi.UserManagement.updateUser(mockk(), mockk()) coVerify { StytchApi.apiService.updateUser(any()) } } @Test fun `StytchApi OAuth authenticateWithGoogleIdToken calls appropriate apiService method`() = runTest { every { StytchApi.isInitialized } returns true coEvery { StytchApi.apiService.authenticateWithGoogleIdToken(any()) } returns mockk(relaxed = true) StytchApi.OAuth.authenticateWithGoogleIdToken( idToken = "id_token", nonce = "nonce", sessionDurationMinutes = 30U ) coVerify { StytchApi.apiService.authenticateWithGoogleIdToken( ConsumerRequests.OAuth.Google.AuthenticateRequest( idToken = "id_token", nonce = "nonce", sessionDurationMinutes = 30 ) ) } } @Test fun `StytchApi OAuth authenticateWithThirdPartyToken calls appropriate apiService method`() = runTest { every { StytchApi.isInitialized } returns true coEvery { StytchApi.apiService.authenticateWithThirdPartyToken(any()) } returns mockk(relaxed = true) StytchApi.OAuth.authenticateWithThirdPartyToken( token = "id_token", sessionDurationMinutes = 30U, codeVerifier = "code_challenge" ) coVerify { StytchApi.apiService.authenticateWithThirdPartyToken( ConsumerRequests.OAuth.ThirdParty.AuthenticateRequest( token = "id_token", sessionDurationMinutes = 30, codeVerifier = "code_challenge" ) ) } } @Test fun `StytchApi Bootstrap getBootstrapData calls appropriate apiService method`() = runTest { every { StytchApi.isInitialized } returns true every { StytchApi.publicToken } returns "mock-public-token" coEvery { StytchApi.apiService.getBootstrapData("mock-public-token") } returns mockk(relaxed = true) StytchApi.getBootstrapData() coVerify { StytchApi.apiService.getBootstrapData("mock-public-token") } } @Test fun `StytchApi User searchUsers calls appropriate apiService method`() = runTest { every { StytchApi.isInitialized } returns true coEvery { StytchApi.apiService.searchUsers(any()) } returns mockk(relaxed = true) StytchApi.UserManagement.searchUsers("user@domain.com") coVerify { StytchApi.apiService.searchUsers( ConsumerRequests.User.SearchRequest( email = "user@domain.com" ) ) } } @Test fun `StytchApi Webauthn registerStart calls appropriate apiService method`() = runTest { every { StytchApi.isInitialized } returns true coEvery { StytchApi.apiService.webAuthnRegisterStart(mockk(relaxed = true)) } returns mockk(relaxed = true) StytchApi.WebAuthn.registerStart("") coVerify { StytchApi.apiService.webAuthnRegisterStart(any()) } } @Test fun `StytchApi Webauthn register calls appropriate apiService method`() = runTest { every { StytchApi.isInitialized } returns true coEvery { StytchApi.apiService.webAuthnRegister(mockk(relaxed = true)) } returns mockk(relaxed = true) StytchApi.WebAuthn.register("") coVerify { StytchApi.apiService.webAuthnRegister(any()) } } @Test fun `StytchApi Webauthn webAuthnAuthenticateStartPrimary calls appropriate apiService method`() = runTest { every { StytchApi.isInitialized } returns true coEvery { StytchApi.apiService.webAuthnAuthenticateStartPrimary(mockk(relaxed = true)) } returns mockk(relaxed = true) StytchApi.WebAuthn.authenticateStartPrimary("", false) coVerify { StytchApi.apiService.webAuthnAuthenticateStartPrimary(any()) } } @Test fun `StytchApi Webauthn webAuthnAuthenticateStartSecondary calls appropriate apiService method`() = runTest { every { StytchApi.isInitialized } returns true coEvery { StytchApi.apiService.webAuthnAuthenticateStartSecondary(mockk(relaxed = true)) } returns mockk(relaxed = true) StytchApi.WebAuthn.authenticateStartSecondary("", true) coVerify { StytchApi.apiService.webAuthnAuthenticateStartSecondary(any()) } } @Test fun `StytchApi Webauthn webAuthnAuthenticate calls appropriate apiService method`() = runTest { every { StytchApi.isInitialized } returns true coEvery { StytchApi.apiService.webAuthnAuthenticate(mockk(relaxed = true)) } returns mockk(relaxed = true) StytchApi.WebAuthn.authenticate("", 30U) coVerify { StytchApi.apiService.webAuthnAuthenticate(any()) } } @Test fun `StytchApi Webauthn webAuthnUpdate calls appropriate apiService method`() = runTest { every { StytchApi.isInitialized } returns true coEvery { StytchApi.apiService.webAuthnUpdate(any(), any()) } returns mockk(relaxed = true) StytchApi.WebAuthn.update("", "my new name") coVerify { StytchApi.apiService.webAuthnUpdate("", any()) } } @Test fun `StytchApi Events logEvent calls appropriate apiService method`() = runTest { every { StytchApi.isInitialized } returns true every { StytchApi.publicToken } returns "mock-public-token" coEvery { StytchApi.apiService.logEvent(any()) } returns mockk(relaxed = true) val details = mapOf("test-key" to "test value") val header = InfoHeaderModel.fromDeviceInfo(mockDeviceInfo) val result = StytchApi.Events.logEvent( eventId = "event-id", appSessionId = "app-session-id", persistentId = "persistent-id", clientSentAt = "ISO date string", timezone = "Timezone/Identifier", eventName = "event-name", infoHeaderModel = header, details = details, ) coVerify(exactly = 1) { StytchApi.apiService.logEvent( listOf( CommonRequests.Events.Event( telemetry = CommonRequests.Events.EventTelemetry( eventId = "event-id", appSessionId = "app-session-id", persistentId = "persistent-id", clientSentAt = "ISO date string", timezone = "Timezone/Identifier", app = CommonRequests.Events.VersionIdentifier( identifier = header.app.identifier, version = header.app.version ), os = CommonRequests.Events.VersionIdentifier( identifier = header.os.identifier, version = header.os.version ), sdk = CommonRequests.Events.VersionIdentifier( identifier = header.sdk.identifier, version = header.sdk.version ), device = CommonRequests.Events.DeviceIdentifier( model = header.device.identifier, screenSize = header.device.version ), ), event = CommonRequests.Events.EventEvent( publicToken = "mock-public-token", eventName = "event-name", details = details, ), ) ) ) } } @Test(expected = StytchSDKNotConfiguredError::class) fun `safeApiCall throws exception when StytchClient is not initialized`() = runTest { every { StytchApi.isInitialized } returns false val mockApiCall: suspend () -> StytchDataResponse<Boolean> = mockk() StytchApi.safeConsumerApiCall { mockApiCall() } } @Test fun `safeApiCall returns success when call succeeds`() = runTest { every { StytchApi.isInitialized } returns true fun mockApiCall(): StytchDataResponse<Boolean> { return StytchDataResponse(true) } val result = StytchApi.safeConsumerApiCall { mockApiCall() } assert(result is StytchResult.Success) } @Test fun `safeApiCall returns correct error for HttpException`() = runTest { every { StytchApi.isInitialized } returns true fun mockApiCall(): StytchDataResponse<Boolean> { throw HttpException( mockk(relaxed = true) { every { errorBody() } returns null } ) } val result = StytchApi.safeConsumerApiCall { mockApiCall() } assert(result is StytchResult.Error) } @Test fun `safeApiCall returns correct error for StytchErrors`() = runTest { every { StytchApi.isInitialized } returns true fun mockApiCall(): StytchDataResponse<Boolean> { throw StytchAPIError(errorType = "", message = "") } val result = StytchApi.safeConsumerApiCall { mockApiCall() } assert(result is StytchResult.Error) } @Test fun `safeApiCall returns correct error for other exceptions`() = runTest { every { StytchApi.isInitialized } returns true fun mockApiCall(): StytchDataResponse<Boolean> { error("Test") } val result = StytchApi.safeConsumerApiCall { mockApiCall() } assert(result is StytchResult.Error) } }
0
Kotlin
1
22
a2a54bc90fdfd47aca01a35e972448076c164929
24,954
stytch-android
MIT License
src/main/kotlin/kt/kotlinalgs/app/graph/KruskalMST.ws.kts
sjaindl
384,471,324
false
{"Java": 388563, "Kotlin": 302517, "Shell": 5915, "Batchfile": 3122}
package kt.kotlinalgs.app.graph println("Test") Solution().test() class Solution { fun test() { //https://www.geeksforgeeks.org/kruskals-minimum-spanning-tree-algorithm-greedy-algo-2/ val vertice0 = Vertice(0) val vertice1 = Vertice(1) val vertice2 = Vertice(2) val vertice3 = Vertice(3) val vertice4 = Vertice(4) val vertice5 = Vertice(5) val vertice6 = Vertice(6) val vertice7 = Vertice(7) val vertice8 = Vertice(8) val graph = WeightedUndirectedGraph( listOf( vertice0, vertice1, vertice2, vertice3, vertice4, vertice5, vertice6, vertice7, vertice8 ) ) graph.addEdge(vertice0, vertice1, 4) graph.addEdge(vertice0, vertice7, 8) graph.addEdge(vertice1, vertice2, 8) graph.addEdge(vertice1, vertice7, 11) graph.addEdge(vertice2, vertice3, 7) graph.addEdge(vertice2, vertice5, 4) graph.addEdge(vertice2, vertice8, 2) graph.addEdge(vertice3, vertice4, 9) graph.addEdge(vertice3, vertice5, 14) graph.addEdge(vertice4, vertice5, 10) graph.addEdge(vertice5, vertice6, 2) graph.addEdge(vertice6, vertice7, 1) graph.addEdge(vertice6, vertice8, 6) graph.addEdge(vertice7, vertice8, 7) val kruskal = Kruskal() val edges = kruskal.minimumSpanningTree(graph) println("Edges:") edges.forEach { println("${it.from.value} - ${it.to.value}: ${it.weight}") } } } // https://www.geeksforgeeks.org/union-find-algorithm-set-2-union-by-rank/ class UnionFind(size: Int) { private val parent = IntArray(size) { it } private val rank = IntArray(size) { 1 } // [0,1,2,3] fun find(component: Int): Int { //println("find: $component, ${parent[component]}") if (component == parent[component]) return component // path compression parent[component] = find(parent[component]) return parent[component] } fun union(first: Int, second: Int) { val firstComponent = find(first) val secondComponent = find(second) if (firstComponent != secondComponent) { // union by rank when { rank[firstComponent] < rank[secondComponent] -> { parent[firstComponent] = secondComponent } rank[secondComponent] < rank[firstComponent] -> { parent[secondComponent] = firstComponent } else -> { parent[secondComponent] = firstComponent rank[firstComponent]++ } } } } } data class Vertice(val value: Int) data class Edge( val from: Vertice, val to: Vertice, val weight: Int ) : Comparable<Edge> { override fun compareTo(other: Edge): Int { return weight - other.weight } } data class WeightedUndirectedGraph(val vertices: List<Vertice>) { var edges: MutableList<Edge> = mutableListOf() fun addEdge(first: Vertice, second: Vertice, weight: Int) { val edge = Edge(first, second, weight) edges.add(edge) } } class Kruskal() { fun minimumSpanningTree(graph: WeightedUndirectedGraph): MutableList<Edge> { val unionFind = UnionFind(graph.vertices.size) val output: MutableList<Edge> = mutableListOf() val edges = graph.edges.toMutableList() edges.sort() // O(E log E) var edgeIndex = 0 while (output.size < graph.vertices.size - 1 && !edgeIndex >= edges.size) { //O(V) val nextEdge = edges[edgeIndex] // O(1) edgeIndex++ // Don't allow cycles if (unionFind.find(nextEdge.from.value) != unionFind.find(nextEdge.to.value)) { unionFind.union(nextEdge.from.value, nextEdge.to.value) output.add(nextEdge) } // O(1) with path compression + weighted UF } // total loop = O(V * log E) // total = O(E log E + V) return output } }
1
null
1
1
e7ae2fcd1ce8dffabecfedb893cb04ccd9bf8ba0
4,159
KotlinAlgs
MIT License
kotlin-remix-run-router/src/main/generated/remix/run/router/AgnosticDataRouteObject.kt
JetBrains
93,250,841
false
null
@file:JsModule("@remix-run/router") @file:JsNonModule @file:Suppress( "NON_EXTERNAL_DECLARATION_IN_INAPPROPRIATE_FILE", "NAME_CONTAINS_ILLEGAL_CHARS", ) package remix.run.router /** * A data route object, which is just a RouteObject with a required unique ID */ typealias AgnosticDataRouteObject = Any /* AgnosticDataIndexRouteObject | AgnosticDataNonIndexRouteObject */
20
Kotlin
162
1,140
75827d7f288fecb503092f644abd7c49e31d639b
385
kotlin-wrappers
Apache License 2.0
src/main/kotlin/org/move/cli/runConfigurations/aptos/FunctionCallConfigurationBase.kt
pontem-network
279,299,159
false
{"Kotlin": 1720857, "Move": 30827, "Lex": 5466, "HTML": 1737}
package org.move.cli.runConfigurations.aptos import com.intellij.execution.configurations.ConfigurationFactory import com.intellij.openapi.project.Project import org.move.cli.MoveProject import org.move.cli.moveProjects abstract class FunctionCallConfigurationBase( project: Project, factory: ConfigurationFactory, val configurationHandler: CommandConfigurationHandler, ) : CommandConfigurationBase(project, factory) { var moveProject: MoveProject? get() = workingDirectory?.let { project.moveProjects.findMoveProject(it) } set(value) { workingDirectory = value?.contentRootPath } fun firstRunShouldOpenEditor(): Boolean { val moveProject = moveProject ?: return true val functionCall = configurationHandler .parseCommand(moveProject, command).unwrapOrNull()?.second ?: return true return functionCall.parametersRequired() } }
12
Kotlin
25
61
6ebc0235bfef60666b09fcf71ace86821ad15705
927
intellij-move
MIT License
wpi/src/main/kotlin/frc/team4069/saturn/lib/hid/SaturnHID.kt
FRCTeam4069
152,143,141
false
null
/* * Copyright 2019 <NAME> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package frc.team4069.saturn.lib.hid import edu.wpi.first.wpilibj.GenericHID import edu.wpi.first.wpilibj2.command.Command import frc.team4069.saturn.lib.util.BooleanSource import kotlin.properties.Delegates enum class POVSide(val angle: Int) { UP(0), DOWN(180), LEFT(270), RIGHT(90) } fun <T : GenericHID> controller(genericHID: T, block: SaturnHIDBuilder<T>.() -> Unit): SaturnHID<T> { return SaturnHIDBuilder(genericHID).apply(block).build() } class SaturnHIDBuilder<T : GenericHID>(private val genericHID: T) { private val controlBuilders = mutableListOf<SaturnHIDControlBuilder>() private val stateControlBuilders = mutableMapOf<BooleanSource, SaturnHIDBuilder<T>>() fun button(buttonId: Int, block: SaturnHIDButtonBuilder.() -> Unit = {}) = control(HIDButtonSource(genericHID, buttonId), block = block) fun axisButton( axisId: Int, threshold: Double = HIDButton.DEFAULT_THRESHOLD, block: SaturnHIDButtonBuilder.() -> Unit = {} ) = control(HIDAxisSource(genericHID, axisId), threshold, block) fun pov(angle: POVSide, block: SaturnHIDButtonBuilder.() -> Unit = {}) = pov(0, angle, block) fun pov(pov: Int, angle: POVSide, block: SaturnHIDButtonBuilder.() -> Unit = {}) = control(HIDPOVSource(genericHID, pov, angle.angle), block = block) fun state(state: BooleanSource, block: SaturnHIDBuilder<T>.() -> Unit) = stateControlBuilders.compute(state) { _, _ -> SaturnHIDBuilder(genericHID).apply(block) } fun control( source: HIDSource, threshold: Double = HIDButton.DEFAULT_THRESHOLD, block: SaturnHIDButtonBuilder.() -> Unit = {} ): SaturnHIDButtonBuilder { val builder = SaturnHIDButtonBuilder(source, threshold).apply(block) controlBuilders.add(builder) return builder } fun build(): SaturnHID<T> { val controls = controlBuilders.map { it.build() } val stateControls = stateControlBuilders.mapValues { it.value.build() } return SaturnHID(genericHID, controls, stateControls) } } abstract class SaturnHIDControlBuilder(val source: HIDSource) { abstract fun build(): HIDControl } class SaturnHIDButtonBuilder(source: HIDSource, private val threshold: Double) : SaturnHIDControlBuilder(source) { private val whileOff = mutableListOf<HIDControlListener>() private val whileOn = mutableListOf<HIDControlListener>() private val changeOn = mutableListOf<HIDControlListener>() private val changeOff = mutableListOf<HIDControlListener>() fun change(command: Command) { changeOn(command) changeOff(command) } fun changeOn(command: Command) = changeOn { command.schedule() } fun changeOff(command: Command) = changeOff { command.cancel() } fun whileOff(block: HIDControlListener) = whileOff.add(block) fun whileOn(block: HIDControlListener) = whileOn.add(block) fun changeOn(block: HIDControlListener) = changeOn.add(block) fun changeOff(block: HIDControlListener) = changeOff.add(block) override fun build() = HIDButton(source, threshold, whileOff, whileOn, changeOn, changeOff) } class SaturnHID<T : GenericHID>( private val genericHID: T, private val controls: List<HIDControl>, private val stateControls: Map<BooleanSource, SaturnHID<T>> ) { fun getRawAxis(axisId: Int): Double = genericHID.getRawAxis(axisId) fun getRawButton(buttonId: Int): Boolean = genericHID.getRawButton(buttonId) var leftRumble by Delegates.observable(0.0) { _, _, new -> genericHID.setRumble(GenericHID.RumbleType.kLeftRumble, new) } var rightRumble by Delegates.observable(0.0) { _, _, new -> genericHID.setRumble(GenericHID.RumbleType.kRightRumble, new) } fun update() { controls.forEach { it.update() } stateControls.filterKeys { it() }.values.forEach { it.update() } } }
0
Kotlin
0
5
cafa7ae6dbd39177f807d5aaa5ef17c98f057826
4,503
SaturnLibrary
Apache License 2.0
zircon.core/src/jvmTest/kotlin/org/hexworks/zircon/internal/behavior/impl/ThreadSafeLayerableTest.kt
klaushauschild1984
251,023,634
false
{"Gradle Kotlin DSL": 7, "Markdown": 7, "INI": 2, "Shell": 1, "Text": 1, "Ignore List": 1, "Batchfile": 1, "Kotlin": 730, "YAML": 2, "XML": 3, "Java": 42}
package org.hexworks.zircon.internal.behavior.impl import org.assertj.core.api.Assertions.assertThat import org.hexworks.zircon.api.CP437TilesetResources import org.hexworks.zircon.api.builder.graphics.LayerBuilder import org.hexworks.zircon.api.data.Position import org.hexworks.zircon.api.data.Size import org.hexworks.zircon.api.resource.TilesetResource import org.junit.Before import org.junit.Test class ThreadSafeLayerableTest { lateinit var target: ThreadSafeLayerable lateinit var tileset: TilesetResource @Before fun setUp() { tileset = TILESET target = ThreadSafeLayerable(SIZE) } @Test fun shouldContainLayerWhenLayerIsAdded() { val layer = LayerBuilder.newBuilder() .withSize(Size.one()) .withOffset(Position.zero()) .build() target.addLayer(layer) assertThat(target.layerStates) .isNotEmpty } @Test fun shouldNotContainLayerWhenLayerIsAddedThenRemoved() { val layer = LayerBuilder.newBuilder() .withSize(Size.one()) .withOffset(Position.zero()) .build() target.addLayer(layer) target.removeLayer(layer) assertThat(target.layerStates) .isEmpty() } @Test fun shouldNotContainLayerWhenLayerIsAddedThenPopped() { val layer = LayerBuilder.newBuilder() .withSize(Size.one()) .withOffset(Position.zero()) .build() target.addLayer(layer) target.removeLayer(layer) assertThat(target.layerStates) .isEmpty() } companion object { val TILESET = CP437TilesetResources.wanderlust16x16() val SIZE = Size.create(80, 24) } }
1
null
1
1
8b6adaadeef6931accd467dc5628027e7470075a
1,813
zircon
Apache License 2.0
src/main/java/com/sayzen/campfiresdk/models/objects/FandomParam.kt
ZeonXX
381,986,881
false
null
package com.sayzen.campfiresdk.models.objects import com.dzen.campfire.api.models.translate.Translate import com.sayzen.campfiresdk.controllers.t class FandomParam( val index: Long, private val mame: Translate ) { val name: String get() = t(mame) }
0
Kotlin
1
0
f35704dd1b362a631055fa64768decc0d612a46c
280
CampfireSDK
Apache License 2.0
app/src/main/java/com/example/androiddevchallenge/WelcomeActivity.kt
nihaolqs
347,816,950
false
null
package com.example.androiddevchallenge import android.os.Bundle import androidx.activity.compose.setContent import androidx.appcompat.app.AppCompatActivity import androidx.compose.foundation.Image import androidx.compose.foundation.background import androidx.compose.foundation.layout.* import androidx.compose.material.Surface import androidx.compose.runtime.Composable import androidx.compose.ui.Modifier import androidx.compose.ui.graphics.Color import androidx.compose.ui.res.painterResource import androidx.compose.ui.tooling.preview.Preview import androidx.compose.ui.unit.dp import com.example.androiddevchallenge.ui.theme.MyTheme import com.example.androiddevchallenge.ui.theme.pink100 class WelcomeActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContent { MyTheme() { WelcomeView() } } } } @Composable private fun WelcomeView() { Surface(color = pink100, modifier = Modifier .fillMaxHeight() .fillMaxWidth()) { Image(painterResource(id = R.drawable.light_welcome_bg), contentDescription = "", modifier = Modifier .fillMaxWidth() .fillMaxHeight()) Column() { Image( painter = painterResource(id = R.drawable.light_welcome_illos), contentDescription = "", modifier = Modifier .padding(top = 72.dp, start = 88.dp) .width(310.dp) .height(280.dp) ) Image(painter = painterResource(id = R.drawable.light_logo), contentDescription = "", modifier = Modifier .fillMaxWidth() .padding(top = 48.dp)) } } } @Preview @Composable private fun PreWelcomeView() { WelcomeView() }
0
Kotlin
0
0
d8f69069448f53454fb4cc81b81ccc60b3f16595
1,952
compose_week_3
Apache License 2.0
app/src/main/java/com/better/alarm/presenter/UiStore.kt
yuriykulikov
4,096,259
false
null
package com.better.medicalAlarm.presenter import com.better.medicalAlarm.configuration.EditedAlarm import io.reactivex.subjects.BehaviorSubject import io.reactivex.subjects.PublishSubject import io.reactivex.subjects.Subject /** Created by Yuriy on 11.08.2017. */ interface UiStore { fun editing(): BehaviorSubject<EditedAlarm> fun onBackPressed(): PublishSubject<String> fun createNewAlarm() /** createNewAlarm was called -> list updates should be ignored */ fun transitioningToNewAlarmDetails(): Subject<Boolean> fun edit(id: Int, holder: RowHolder? = null) fun hideDetails(holder: RowHolder? = null) /** Open the drawer when the activity is created. True after theme changes. */ var openDrawerOnCreate: Boolean }
53
null
157
445
533072ecd400ed6b1bf59d2535483682692c263a
738
AlarmClock
Apache License 2.0
kirc-suspending/src/main/kotlin/de/cmdjulian/kirc/client/SuspendingContainerImageClientFactory.kt
cmdjulian
524,628,199
false
null
package de.cmdjulian.kirc.client import com.github.kittinunf.fuel.core.FuelManager import de.cmdjulian.kirc.image.ContainerImageName import de.cmdjulian.kirc.impl.ContainerRegistryApi import de.cmdjulian.kirc.impl.ContainerRegistryApiImpl import de.cmdjulian.kirc.impl.SuspendingContainerImageClientImpl import de.cmdjulian.kirc.impl.SuspendingContainerImageRegistryClientImpl import de.cmdjulian.kirc.utils.InsecureSSLSocketFactory import de.cmdjulian.kirc.utils.NoopHostnameVerifier import java.net.Proxy import java.net.URL import java.security.KeyStore const val DOCKER_HUB_REGISTRY_URL = "https://registry.hub.docker.com" object SuspendingClientFactory { /** * Create a ContainerRegistryClient for a registry. If no args are supplied the client is constructed for Docker * Hub with no authentication. */ @JvmStatic fun create( url: URL = URL(DOCKER_HUB_REGISTRY_URL), credentials: RegistryCredentials? = null, proxy: Proxy? = null, skipTlsVerify: Boolean = false, keystore: KeyStore? = null, ): SuspendingContainerImageRegistryClient { require(keystore == null || !skipTlsVerify) { "can not skip tls verify if a keystore is set" } val fuel = FuelManager().apply { this.basePath = url.toString() this.proxy = proxy if (skipTlsVerify) { hostnameVerifier = NoopHostnameVerifier socketFactory = InsecureSSLSocketFactory } } val api: ContainerRegistryApi = ContainerRegistryApiImpl(fuel, credentials) return SuspendingContainerImageRegistryClientImpl(api) } @JvmStatic suspend fun create( image: ContainerImageName, credentials: RegistryCredentials? = null, proxy: Proxy? = null, insecure: Boolean = false, skipTlsVerify: Boolean = false, keystore: KeyStore? = null, ): SuspendingContainerImageClient { val url = "${if (insecure) "http://" else "https://"}${image.registry}" val client = create(URL(url), credentials, proxy, skipTlsVerify, keystore) return SuspendingContainerImageClientImpl(client, image) } }
6
Kotlin
0
10
70ce7be12985b5cb5ab9638fb4c7470670ea82c0
2,202
kirc
MIT License
remoting/src/main/kotlin/com/agmtopy/kocketmq/remoting/netty/NettyRequestProcessor.kt
agmtopy
376,882,907
false
null
package com.agmtopy.kocketmq.remoting.netty import com.agmtopy.kocketmq.remoting.RemotingCommand import io.netty.channel.ChannelHandlerContext /** * Netty请求处理器 */ interface NettyRequestProcessor { /** * 处理请求 */ @Throws(Exception::class) fun processRequest(ctx: ChannelHandlerContext?, request: RemotingCommand?): RemotingCommand? /** * 拒绝请求 */ fun rejectRequest(): Boolean }
1
null
1
1
91e15b054ff8f1784d79b96e498894065ba025f8
420
kocketmq
Apache License 2.0
src/main/kotlin/com/cognifide/gradle/common/build/Retry.kt
wttech
237,183,159
false
{"Gradle Kotlin DSL": 2, "YAML": 3, "Markdown": 1, "Shell": 2, "Java Properties": 1, "Text": 1, "Ignore List": 1, "Batchfile": 1, "Git Attributes": 1, "INI": 1, "Kotlin": 99, "Java": 6, "SVG": 1}
package com.cognifide.gradle.common.build import com.cognifide.gradle.common.CommonException import com.cognifide.gradle.common.CommonExtension import com.cognifide.gradle.common.utils.Formats import kotlin.math.max class Retry(val common: CommonExtension) { var times = 1L var delay: (Long) -> Long = { 0L } fun never() { times = 1L delay = { 0L } } fun after(times: Long, delay: (Long) -> Long) { this.delay = delay this.times = max(1, times) } fun after(times: Long, delay: Long) = after(times) { delay } fun afterSecond(times: Long) = after(times) { SECOND_MILLIS } fun afterSquaredSecond(times: Long) = after(times) { n -> n * n * SECOND_MILLIS } @Suppress("TooGenericExceptionCaught") inline fun <T, reified E> withCountdown(operation: String, block: (Long) -> T): T { lateinit var exception: Exception for (i in 0 until times) { val no = i + 1 try { return block(no) } catch (e: Exception) { exception = e if (e !is E) { throw exception } if (i < times) { val delay = delay(no) common.logger.lifecycle("Retrying ($no/$times) $operation after delay: ${Formats.duration(delay)}") common.logger.debug("Retrying due to exception", e) common.progressCountdown { time = delay timePrefix = "Retrying ($no/$times) $operation after" } } } } throw exception } fun withCountdown(operation: String, block: (Long) -> Unit) = withCountdown<Unit, CommonException>(operation, block) @Suppress("TooGenericExceptionCaught") inline fun <T, reified E> withSleep(block: (Long) -> T): T { lateinit var exception: Exception for (i in 0 until times) { val no = i + 1 try { return block(no) } catch (e: Exception) { exception = e if (e !is E) { throw exception } if (i < times) { val delay = delay(no) Thread.sleep(delay) } } } throw exception } fun withSleep(block: (Long) -> Unit) = withSleep<Unit, CommonException>(block) fun withSleepTillEnd(block: (Long) -> Unit) { for (i in 0 until times) { val no = i + 1 block(no) if (i < times) { val delay = delay(no) Thread.sleep(delay) } } } companion object { const val SECOND_MILLIS = 1000L } }
9
Kotlin
2
4
c132b8ec82e68247308070309f7f5481dc77914b
2,849
gradle-common-plugin
Apache License 2.0
compose/src/commonMain/kotlin/com/camackenzie/exvi/client/model/ComposeExerciseSet.kt
CallumMackenzie
450,286,341
false
{"Kotlin": 239407, "Swift": 582}
@file:Suppress("UNCHECKED_CAST") package com.camackenzie.exvi.client.model import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateListOf import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.setValue import com.camackenzie.exvi.core.model.* import com.camackenzie.exvi.core.util.SelfSerializable import kotlinx.serialization.KSerializer fun SingleExerciseSet.toComposable() = ComposeSingleExerciseSet( reps, weight.copy(), timing.map { it.copy() }.toTypedArray() ) fun ExerciseSet.toComposable() = ComposeExerciseSet(exercise, unit, sets.map { it.toComposable() }.toTypedArray()) open class ComposeExerciseSet( exercise: Exercise, unit: String, sets: Array<SingleExerciseSet>, ) : ExerciseSet { override val serializer: KSerializer<SelfSerializable> get() = ActualExerciseSet.serializer() as KSerializer<SelfSerializable> override var exercise: Exercise by mutableStateOf(exercise) override var sets: MutableList<SingleExerciseSet> = mutableStateListOf(*sets) override var unit: String by mutableStateOf(unit) override fun hashCode(): Int { var hash = 17 hash = hash * 23 + exercise.hashCode() hash = hash * 23 + unit.hashCode() hash = hash * 23 + sets.hashCode() return hash } } open class ComposeSingleExerciseSet( reps: Int = 0, weight: Mass = 0.kilograms, timing: Array<Time>, ) : SingleExerciseSet { override val serializer: KSerializer<SelfSerializable> get() = ActualSingleExerciseSet.serializer() as KSerializer<SelfSerializable> override var reps: Int by mutableStateOf(reps) override var timing: Array<Time> by mutableStateOf(timing) override var weight: Mass by mutableStateOf(weight) override fun deepValueCopy(): SingleExerciseSet = ComposeSingleExerciseSet( reps = reps, timing = timing.map { it.copy() }.toTypedArray(), weight = weight.copy() ) } open class ComposeActiveExercise( active: ExerciseSet, currentSet: Int, target: ExerciseSet, ) : ActiveExercise { constructor(other: ActiveExercise) : this( other.active.toActual(), other.currentSet, other.target ) override val serializer: KSerializer<SelfSerializable> get() = ActualActiveExercise.serializer() as KSerializer<SelfSerializable> override var active: ExerciseSet by mutableStateOf(active) override var currentSet: Int by mutableStateOf(currentSet) override val target: ExerciseSet = target }
1
Kotlin
0
0
033a4826b7cd6dd856fc65605414f73f56a646db
2,580
exvi-client
Apache License 2.0
src/main/kotlin/org/beckn/one/sandbox/bap/client/order/status/controllers/OnOrderStatusPollController.kt
OSSVerse
853,138,400
false
{"Kotlin": 651081, "Jinja": 3324}
package org.beckn.one.sandbox.bap.client.order.status.controllers import org.beckn.one.sandbox.bap.auth.utils.SecurityUtil import org.beckn.one.sandbox.bap.client.external.bap.ProtocolClient import org.beckn.one.sandbox.bap.client.order.status.services.OnOrderStatusService import org.beckn.one.sandbox.bap.client.shared.controllers.AbstractOnPollController import org.beckn.one.sandbox.bap.client.shared.dtos.ClientErrorResponse import org.beckn.one.sandbox.bap.client.shared.dtos.ClientOrderStatusResponse import org.beckn.one.sandbox.bap.client.shared.dtos.ClientResponse import org.beckn.one.sandbox.bap.client.shared.errors.bpp.BppError import org.beckn.one.sandbox.bap.client.shared.services.GenericOnPollService import org.beckn.one.sandbox.bap.errors.HttpError import org.beckn.one.sandbox.bap.factories.ContextFactory import org.beckn.one.sandbox.bap.message.entities.OrderDao import org.beckn.one.sandbox.bap.message.mappers.OnOrderProtocolToEntityOrder import org.beckn.protocol.schemas.ProtocolContext import org.beckn.protocol.schemas.ProtocolOnOrderStatus import org.springframework.http.ResponseEntity import org.springframework.web.bind.annotation.RequestMapping import org.springframework.web.bind.annotation.RequestParam import org.springframework.web.bind.annotation.ResponseBody import org.springframework.web.bind.annotation.RestController @RestController class OnOrderStatusPollController( onPollService: GenericOnPollService<ProtocolOnOrderStatus, ClientOrderStatusResponse>, val contextFactory: ContextFactory, val mapping: OnOrderProtocolToEntityOrder, val protocolClient: ProtocolClient, val onOrderStatusService: OnOrderStatusService ) : AbstractOnPollController<ProtocolOnOrderStatus, ClientOrderStatusResponse>(onPollService, contextFactory) { @RequestMapping("/client/v1/on_order_status") @ResponseBody fun onOrderStatusV1(@RequestParam orderId: String): ResponseEntity<out ClientResponse> = onPoll(orderId, protocolClient.getOrderByIdStatusResponsesCall(orderId)) @RequestMapping("/client/v2/on_order_status") @ResponseBody fun onOrderStatusV2(@RequestParam orderIds: String): ResponseEntity<out List<ClientResponse>> { if (orderIds.isNotEmpty() && orderIds.trim().isNotEmpty()) { val orderIdArray = orderIds.split(",") var okResponseOnOrderStatus: MutableList<ClientResponse> = ArrayList() if (SecurityUtil.getSecuredUserDetail() != null) { val user = SecurityUtil.getSecuredUserDetail() for (orderId in orderIdArray) { val messageId = contextFactory.create().messageId val bapResult = onPoll(messageId, protocolClient.getOrderByIdStatusResponsesCall(orderId)) when (bapResult.statusCode.value()) { 200 -> { val resultResponse = bapResult.body as ClientOrderStatusResponse if (resultResponse.message?.order != null) { val orderDao: OrderDao = mapping.protocolToEntity(resultResponse.message?.order!!) orderDao.transactionId = resultResponse.context.transactionId orderDao.userId = user?.uid orderDao.messageId = resultResponse.context.messageId onOrderStatusService.updateOrder(orderDao).fold( { okResponseOnOrderStatus.add( ClientErrorResponse( context = contextFactory.create(messageId = resultResponse.context.messageId), error = it.error() ) ) }, { okResponseOnOrderStatus.add(resultResponse) } ) }else{ okResponseOnOrderStatus.add( ClientErrorResponse( context = contextFactory.create(messageId = resultResponse.context.messageId), error = bapResult.body?.error ) ) } } else -> { okResponseOnOrderStatus.add( ClientErrorResponse( context = contextFactory.create(), error = bapResult.body?.error ) ) } } } }else{ return mapToErrorResponseV2(BppError.AuthenticationError) } return ResponseEntity.ok(okResponseOnOrderStatus) } else { return mapToErrorResponseV2(BppError.BadRequestError) } } private fun mapToErrorResponseV2(it: HttpError, context: ProtocolContext? = null) = ResponseEntity .status(it.status()) .body( listOf( ClientErrorResponse( context = context, error = it.error() ) ) ) }
0
Kotlin
0
8
b3ca6a6455f41b9d53bbb35f5c01e31c1fde2638
4,859
OSSVerse-buyer-app
Apache License 2.0
app/src/main/java/com/neo/fbrules/main/data/model/DataCredential.kt
Irineu333
442,610,375
false
null
package com.neo.fbrules.main.data.model data class DataCredential( val privateKey: String, val databaseKey: String )
2
Kotlin
2
4
84b17274eb8f4e823d4d205b350163494d400a97
125
DatabaseRules
MIT License
feature/listing/src/main/kotlin/com/github/felipehjcosta/marvelapp/listing/presentation/CharacterItemViewModel.kt
felipehjcosta
73,579,053
false
{"Kotlin": 164257, "Java": 7399, "Shell": 467}
package com.github.felipehjcosta.marvelapp.listing.presentation class CharacterItemViewModel(val id: Long, val name: String, val image: String)
0
Kotlin
0
16
f48c56c345622ac6dcf3fc8203c2b77114b5077b
145
marvel-app
MIT License
abstract-factory/src/main/kotlin/io/kommons/designpatterns/abstractfactory/FactoryMaker.kt
debop
235,066,649
false
null
package io.kommons.designpatterns.abstractfactory import io.kommons.designpatterns.abstractfactory.elf.ElfKingdomFactory import io.kommons.designpatterns.abstractfactory.orc.OrcKingdomFactory /** * FactoryMaker * * @author debop * @since 28/09/2019 */ object FactoryMaker { enum class KingdomType { ELF, ORC } fun makeFactory(type: KingdomType): KingdomFactory = when (type) { KingdomType.ELF -> ElfKingdomFactory() KingdomType.ORC -> OrcKingdomFactory() } }
0
Kotlin
11
53
c00bcc0542985bbcfc4652d0045f31e5c1304a70
507
kotlin-design-patterns
Apache License 2.0
app/src/main/java/com/googof/bitcointimechainwidgets/mempool/halving/NextHalvingGlanceWidgetReceiver.kt
gooGofZ
573,747,284
false
{"Kotlin": 116937}
package com.googof.bitcointimechainwidgets.mempool.halving import android.content.Context import androidx.glance.appwidget.GlanceAppWidgetReceiver class NextHalvingGlanceWidgetReceiver : GlanceAppWidgetReceiver() { override val glanceAppWidget = NextHalvingGlanceWidget() override fun onEnabled(context: Context) { super.onEnabled(context) NextHalvingWorker.enqueue(context) } override fun onDisabled(context: Context) { super.onDisabled(context) NextHalvingWorker.cancel(context) } }
1
Kotlin
2
12
1a4bbb6f1f69f21cc31ebca8beaeecdcf35e6bc9
540
BitcoinTimechainWidgets
Apache License 2.0
common/src/main/java/com/zlagi/common/exception/NetworkException.kt
Zlagi
475,379,557
false
{"Kotlin": 496613}
package com.zlagi.common.exception sealed class NetworkException : Exception() { object NetworkUnavailable : NetworkException() object Network : NetworkException() object NotFound : NetworkException() object BadRequest : NetworkException() object NotAuthorized : NetworkException() object ServiceNotWorking : NetworkException() object ServiceUnavailable : NetworkException() object NoResults : NetworkException() object Unknown : NetworkException() object UnknownError : NetworkException() }
0
Kotlin
12
63
dffd07e8533c285bb5ca9de4e9676985aa0e87cc
533
Blogfy
Apache License 2.0
gradle-plugin/plugin/src/functionalTest/kotlin/com/emergetools/android/gradle/base/EmergeGradleRunner.kt
EmergeTools
645,957,551
false
{"Kotlin": 255570}
package com.emergetools.android.gradle.base import com.emergetools.android.gradle.EmergePluginTest import okhttp3.HttpUrl import okhttp3.mockwebserver.MockWebServer import org.gradle.internal.impldep.com.google.common.io.Files import org.gradle.testkit.runner.BuildResult import org.gradle.testkit.runner.GradleRunner import org.gradle.util.internal.VersionNumber import java.io.File /** * One instance per build. */ class EmergeGradleRunner private constructor( private val projectDir: String, private val server: MockWebServer = MockWebServer(), ) { companion object { /** Must be kept in sync with the build.gradle list. */ val SUPPORTED_ANDROID_GRADLE_PLUGIN_VERSIONS = sortedSetOf( "7.0.0", "7.1.0", "7.2.0", "7.3.0", "8.0.0" ) val SUPPORTED_KOTLIN_ANDROID_GRADLE_PLUGIN_VERSIONS = sortedSetOf( "1.8.21", ) fun create(projectDir: String): EmergeGradleRunner = EmergeGradleRunner(projectDir) } private val gradleRunner = GradleRunner.create() private val baseUrl: HttpUrl get() = server.url("/") // Starts the server private var androidGradlePluginVersion = SUPPORTED_ANDROID_GRADLE_PLUGIN_VERSIONS.last() private var kotlinAndroidGradlePluginVersion = SUPPORTED_KOTLIN_ANDROID_GRADLE_PLUGIN_VERSIONS.last() var tempProjectDir: File? = null private var arguments: List<String> = emptyList() private var assertions: ((BuildResult, MockWebServer) -> Unit)? = null private var environment: Map<String, String> = emptyMap() fun withArguments(vararg arguments: String) = apply { this.arguments = arguments.toList() } fun withDebugTasks() = apply { arguments = arguments + "-PemergeDebug" } fun withGradleVersion(version: String) = apply { gradleRunner.withGradleVersion(version) } fun withAndroidGradlePluginVersion(version: String) = apply { check(version in SUPPORTED_ANDROID_GRADLE_PLUGIN_VERSIONS) { "This version of the Android Gradle Plugin is not currently supported." } androidGradlePluginVersion = version } fun withKotlinAndroidGradlePluginVersion(version: String) = apply { check(version in SUPPORTED_KOTLIN_ANDROID_GRADLE_PLUGIN_VERSIONS) { "This version of the Kotlin Android Gradle Plugin is not currently supported." } kotlinAndroidGradlePluginVersion = version } private fun withJavaVersion(version: String) = apply { val arch = if (System.getProperty("os.arch") == "aarch64") "aarch64" else "X64" val javaHomeEnvKey = "JAVA_HOME_${version}_$arch" arguments = arguments + "-Dorg.gradle.java.home=${System.getenv(javaHomeEnvKey)}" } fun withServer(serverReceiver: MockWebServer.(HttpUrl) -> Unit) = apply { server.apply { serverReceiver(baseUrl) } } fun assert(assertions: (BuildResult, MockWebServer) -> Unit) = apply { this.assertions = assertions } fun withEnvironment(vararg pairs: Pair<String, String>) = apply { this.environment = mapOf(*pairs) } private fun preBuild() { @Suppress("DEPRECATION") tempProjectDir = Files.createTempDir() testProjectDir(projectDir).copyRecursively(tempProjectDir!!) // The plugin will use the mock webserver URL rather than the real API host arguments = arguments + "-PbaseUrl=$baseUrl" arguments = arguments + "-Pandroid.useAndroidX=true" arguments = arguments + "--stacktrace" if (VersionNumber.parse(androidGradlePluginVersion).major >= 8) { withJavaVersion("17") } else { withJavaVersion("11") } val customEnvironment = mapOf( *environment.toList().toTypedArray(), // Turns off repository discovery to test projects that don't use Git "GIT_DIR" to tempProjectDir!!.path, ) gradleRunner .withProjectDir(tempProjectDir) .withArguments(arguments) .withEnvironment(System.getenv() + customEnvironment) // Must be called first in order to set the default plugin classpath. .withPluginClasspath() .withPluginClasspath( gradleRunner.pluginClasspath + androidGradlePluginClasspath(androidGradlePluginVersion) + kotlinAndroidGradlePluginClasspath(kotlinAndroidGradlePluginVersion) ) } private fun androidGradlePluginClasspath(version: String): List<File> { val resource = EmergePluginTest::class.java.getResource("/agp-classpath-$version.txt") check(resource != null) { "There is no Android Gradle Plugin classpath resource for version $version" } return File(resource.file) .readLines() .map { File(it) } } private fun kotlinAndroidGradlePluginClasspath(version: String): List<File> { val resource = EmergePluginTest::class.java.getResource("/kgp-classpath-$version.txt") check(resource != null) { "There is no Kotlin Android Gradle Plugin classpath resource for version $version" } return File(resource.file) .readLines() .map { File(it) } } private fun testProjectDir(name: String): File { val resource = EmergePluginTest::class.java.getResource("/gradle-project-dirs/$name") check(resource != null) { "There is no Gradle project directory named \"$name\"" } return File(resource.file) } private fun postBuild() { server.shutdown() tempProjectDir?.delete() tempProjectDir = null } private fun gradleRunnerBuild(buildReceiver: GradleRunner.() -> BuildResult): BuildResult { preBuild() val result = gradleRunner.buildReceiver() assertions?.invoke(result, server) postBuild() return result } fun build(): BuildResult { return gradleRunnerBuild { build() } } fun buildAndFail(): BuildResult { return gradleRunnerBuild { buildAndFail() } } }
3
Kotlin
1
9
8174b9c6e2d7791e01363aabd4d287736bfa38c4
5,737
emerge-android
Apache License 2.0
src/main/kotlin/com/peasenet/util/KeyBindUtils.kt
gavinsmod
666,761,068
false
null
/* * Copyright (c) 2022-2023. <NAME> and 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.peasenet.util import com.peasenet.mods.ModCategory import net.fabricmc.fabric.api.client.keybinding.v1.KeyBindingHelper import net.minecraft.client.option.KeyBinding import net.minecraft.client.util.InputUtil import org.lwjgl.glfw.GLFW /** * Used to get and create keybindings for different mods. * @author gt3ch1 * @version 03-02-2023 */ object KeyBindUtils { /** * Attemps to get a keybinding for a mod. * @param translationKey The translation key for the keybinding. * @param modCategory The mod category for the keybinding. * @param keyBind The keybind for the keybinding. Defaults to [GLFW.GLFW_KEY_UNKNOWN]. * * @returns a keybind */ private fun getKeyBinding( translationKey: String, modCategory: ModCategory, keyBind: Int = GLFW.GLFW_KEY_UNKNOWN ): KeyBinding { return KeyBinding( translationKey, InputUtil.Type.KEYSYM, keyBind, modCategory.keybindCategory ) } /** * Registers a keybind for a mod. * @param translationKey The translation key for the keybinding. * @param modCategory The mod category for the keybinding. * @param keyBind The keybind for the keybinding. Defaults to [GLFW.GLFW_KEY_UNKNOWN]. */ fun registerModKeybind( translationKey: String, modCategory: ModCategory, keyBind: Int = GLFW.GLFW_KEY_UNKNOWN ): KeyBinding { return KeyBindingHelper.registerKeyBinding(getKeyBinding(translationKey, modCategory,keyBind)) } }
0
Kotlin
0
0
c2c751aee401e99903fb80031f1f6e467867e30a
2,704
gemclient-core
MIT License
app/src/main/java/com/anangkur/footbalku/feature/league/LeagueActionListener.kt
anangkur
228,181,423
false
null
package com.anangkur.footbalku.feature.league import com.anangkur.footbalku.data.model.League interface LeagueActionListener { fun onClickItem(data: League) }
0
Kotlin
0
1
40e60bad7c73849114af407e1cd9c108f849674d
164
Football-Ku
MIT License
simplified-books-covers/src/main/java/org/nypl/simplified/books/covers/BookCoverBadgeOffset.kt
NatLibFi
730,988,035
false
{"Kotlin": 3601772, "JavaScript": 853788, "Java": 403841, "CSS": 65407, "HTML": 49894, "Shell": 18611, "Ruby": 7554}
package org.nypl.simplified.books.covers data class BookCoverBadgeOffset ( val x: Int, val y: Int ){ /** Determine static offsets in DP, which is then scaled to pixels in the cover image **/ companion object { @JvmStatic val OFFSET_DEFAULT: BookCoverBadgeOffset = BookCoverBadgeOffset(0,0) @JvmStatic val OFFSET_HORIZONTAL: BookCoverBadgeOffset = BookCoverBadgeOffset(0,0) @JvmStatic val OFFSET_VERTICAL: BookCoverBadgeOffset = BookCoverBadgeOffset(0,0) } }
1
Kotlin
0
0
6c3ed3c296495b86bb069dda53e3c3670a9ad101
493
ekirjasto-android-core
Apache License 2.0
chartsfeature/src/test/java/com/simtop/chart/presentation/ChartViewModelTest.kt
simtop
319,123,588
false
{"Gradle": 4, "Gradle Kotlin DSL": 2, "Java Properties": 2, "Shell": 1, "Text": 1, "Ignore List": 6, "Batchfile": 1, "Markdown": 1, "Proguard": 3, "XML": 24, "Kotlin": 51, "JSON": 2, "INI": 2, "Java": 1}
package com.simtop.chart.presentation import androidx.arch.core.executor.testing.InstantTaskExecutorRule import com.simtop.chart.presentation.chart.ChartViewState import com.simtop.chart.presentation.chart.ChartViewModel import com.simtop.chart.domain.usecases.GetMarketPriceUseCase import com.simtop.chart.utils.fakeMarketPriceModel import com.simtop.testutils.RxTestSchedulerRule import com.simtop.testutils.core.testObserver import io.mockk.coEvery import io.mockk.coVerify import io.mockk.every import io.mockk.mockk import io.reactivex.Single import org.amshove.kluent.shouldBeEqualTo import org.junit.Rule import org.junit.Test import org.junit.rules.TestRule internal class ChartViewModelTest { @get:Rule var rule: TestRule = InstantTaskExecutorRule() @get:Rule val rxJavaTestRule = RxTestSchedulerRule() private val getMarketPriceUseCase: GetMarketPriceUseCase = mockk() private lateinit var chartViewModel: ChartViewModel @Test fun `when we get market model it succeeds`() { every { getMarketPriceUseCase.execute(any()) } returns Single.just( fakeMarketPriceModel ) chartViewModel = ChartViewModel(getMarketPriceUseCase) val liveDataUnderTest = chartViewModel.chartViewState.testObserver() liveDataUnderTest.observedValues.last() shouldBeEqualTo ChartViewState.Success(fakeMarketPriceModel) } @Test fun `when we get market price model it fails and shows error`() { val errorName = "Error getting list of categories" coEvery { getMarketPriceUseCase.execute(any()) } returns Single.error( Exception(errorName) ) chartViewModel = ChartViewModel(getMarketPriceUseCase) val liveDataUnderTest = chartViewModel.chartViewState.testObserver() coVerify(exactly = 1) { getMarketPriceUseCase.execute(any()) } liveDataUnderTest.observedValues.last() shouldBeEqualTo ChartViewState.Error(errorName) } }
0
Kotlin
0
0
aed8de6a8653b185cc1904b8c466fc1ea0afbc46
2,000
BitCoinChartFeatureModulesRx
MIT License
app/src/main/java/com/babylon/wallet/android/presentation/settings/securitycenter/SecurityCenterScreen.kt
radixdlt
513,047,280
false
{"Kotlin": 4396111, "HTML": 215350, "Ruby": 2757, "Shell": 1963}
package com.babylon.wallet.android.presentation.settings.securitycenter import androidx.compose.foundation.background import androidx.compose.foundation.clickable 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.WindowInsets import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.size import androidx.compose.foundation.layout.statusBars import androidx.compose.foundation.rememberScrollState import androidx.compose.foundation.verticalScroll import androidx.compose.material3.Icon import androidx.compose.material3.Scaffold import androidx.compose.material3.Text import androidx.compose.runtime.Composable import androidx.compose.runtime.getValue import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.draw.clip import androidx.compose.ui.draw.shadow import androidx.compose.ui.graphics.Color import androidx.compose.ui.res.painterResource import androidx.compose.ui.res.stringResource import androidx.compose.ui.tooling.preview.Preview import androidx.compose.ui.unit.dp import androidx.hilt.navigation.compose.hiltViewModel import androidx.lifecycle.compose.collectAsStateWithLifecycle import com.babylon.wallet.android.R import com.babylon.wallet.android.designsystem.theme.RadixTheme import com.babylon.wallet.android.designsystem.theme.RadixWalletTheme import com.babylon.wallet.android.domain.model.SecurityProblem import com.babylon.wallet.android.presentation.ui.composables.DSR import com.babylon.wallet.android.presentation.ui.composables.RadixCenteredTopAppBar import com.radixdlt.sargon.FactorSource import com.radixdlt.sargon.annotation.UsesSampleValues import com.radixdlt.sargon.extensions.id import rdx.works.core.sargon.sample @Composable fun SecurityCenterScreen( modifier: Modifier = Modifier, securityCenterViewModel: SecurityCenterViewModel = hiltViewModel(), onBackClick: () -> Unit, onSecurityFactorsClick: () -> Unit, onBackupConfigurationClick: () -> Unit, onRecoverEntitiesClick: () -> Unit, onBackupEntities: () -> Unit, ) { val state by securityCenterViewModel.state.collectAsStateWithLifecycle() SecurityCenterContent( modifier = modifier, state = state, onBackClick = onBackClick, onSecurityFactorsClick = onSecurityFactorsClick, onBackupConfigurationClick = onBackupConfigurationClick, onRecoverEntitiesClick = onRecoverEntitiesClick, onBackupEntities = onBackupEntities ) } @Composable private fun SecurityCenterContent( modifier: Modifier = Modifier, state: SecurityCenterViewModel.SecurityCenterUiState, onBackClick: () -> Unit, onSecurityFactorsClick: () -> Unit, onBackupConfigurationClick: () -> Unit, onRecoverEntitiesClick: () -> Unit, onBackupEntities: () -> Unit ) { Scaffold( modifier = modifier.fillMaxSize(), topBar = { RadixCenteredTopAppBar( title = stringResource(id = R.string.empty), onBackClick = onBackClick, windowInsets = WindowInsets.statusBars, contentColor = RadixTheme.colors.gray1, containerColor = RadixTheme.colors.gray5 ) }, containerColor = RadixTheme.colors.gray5 ) { padding -> Column( modifier = Modifier .padding(padding) .padding(horizontal = RadixTheme.dimensions.paddingDefault) .verticalScroll(rememberScrollState()), horizontalAlignment = Alignment.Start, verticalArrangement = Arrangement.spacedBy(space = RadixTheme.dimensions.paddingDefault) ) { Text( text = stringResource(id = R.string.securityCenter_title), style = RadixTheme.typography.title, color = RadixTheme.colors.gray1 ) Text( text = stringResource(id = R.string.securityCenter_subtitle), style = RadixTheme.typography.body1Regular, color = RadixTheme.colors.gray1 ) Spacer(modifier = Modifier.size(RadixTheme.dimensions.paddingMedium)) state.securityProblems?.forEach { problem -> val title = problem.toProblemHeading() when (problem) { is SecurityProblem.EntitiesNotRecoverable -> { NotOkStatusCard( modifier = Modifier .clip(RadixTheme.shapes.roundedRectMedium) .clickable { onBackupEntities() }, title = title, subtitle = stringResource(id = R.string.securityCenter_problem3_text) ) } is SecurityProblem.EntitiesNeedRecovery -> { NotOkStatusCard( modifier = Modifier .clip(RadixTheme.shapes.roundedRectMedium) .clickable { onRecoverEntitiesClick() }, title = title, subtitle = stringResource(id = R.string.securityCenter_problem9_text) ) } SecurityProblem.BackupNotWorking -> { NotOkStatusCard( modifier = Modifier .clip(RadixTheme.shapes.roundedRectMedium) .clickable { onBackupConfigurationClick() }, title = title, subtitle = stringResource(id = R.string.securityCenter_problem6_text) ) } } } if (state.securityProblems?.isEmpty() == true) { RecoverableStatusCard(text = stringResource(id = R.string.securityCenter_goodState_heading)) } SecurityFactorsCard( onSecurityFactorsClick = onSecurityFactorsClick, needsAction = state.securityProblems?.isNotEmpty() == true ) BackupConfigurationCard( needsAction = state.securityProblems?.contains(SecurityProblem.BackupNotWorking) == true, onBackupConfigurationClick = onBackupConfigurationClick ) Spacer(modifier = Modifier.size(RadixTheme.dimensions.paddingLarge)) } } } @Composable fun RecoverableStatusCard(modifier: Modifier = Modifier, text: String) { Row( modifier = modifier .fillMaxWidth() .background(RadixTheme.colors.green1, RadixTheme.shapes.roundedRectMedium) .padding(horizontal = RadixTheme.dimensions.paddingLarge, vertical = RadixTheme.dimensions.paddingSmall), verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(space = RadixTheme.dimensions.paddingMedium) ) { Icon(painter = painterResource(id = DSR.ic_security_center), contentDescription = null, tint = RadixTheme.colors.white) Text( text = text, style = RadixTheme.typography.body1Regular, color = RadixTheme.colors.white ) } } @Composable private fun NotOkStatusCard(modifier: Modifier = Modifier, title: String, subtitle: String) { Column( modifier = modifier .fillMaxWidth() .background(RadixTheme.colors.lightOrange, RadixTheme.shapes.roundedRectMedium) ) { Row( modifier = Modifier .fillMaxWidth() .background(RadixTheme.colors.orange3, RadixTheme.shapes.roundedRectTopMedium) .padding(horizontal = RadixTheme.dimensions.paddingLarge, vertical = RadixTheme.dimensions.paddingSmall), verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(space = RadixTheme.dimensions.paddingMedium) ) { Icon(painter = painterResource(id = DSR.ic_warning_error), contentDescription = null, tint = RadixTheme.colors.white) Text( text = title, style = RadixTheme.typography.body1Header, color = RadixTheme.colors.white ) } Row( modifier = Modifier .fillMaxWidth() .padding(horizontal = RadixTheme.dimensions.paddingLarge, vertical = RadixTheme.dimensions.paddingSmall), verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(RadixTheme.dimensions.paddingMedium) ) { Text( modifier = Modifier.weight(1f), text = subtitle, style = RadixTheme.typography.body2HighImportance, color = RadixTheme.colors.orange3 ) Icon(painter = painterResource(id = DSR.ic_chevron_right), contentDescription = null, tint = RadixTheme.colors.orange3) } } } @Composable private fun SecurityFactorsCard( modifier: Modifier = Modifier, onSecurityFactorsClick: () -> Unit, needsAction: Boolean ) { Row( modifier = modifier .shadow(6.dp, shape = RadixTheme.shapes.roundedRectMedium) .clip(RadixTheme.shapes.roundedRectMedium) .clickable { onSecurityFactorsClick() } .background(RadixTheme.colors.defaultBackground, RadixTheme.shapes.roundedRectMedium) .padding(horizontal = RadixTheme.dimensions.paddingDefault, vertical = RadixTheme.dimensions.paddingLarge), verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(space = RadixTheme.dimensions.paddingMedium) ) { Icon( modifier = Modifier.size(80.dp), painter = painterResource(id = DSR.ic_security_factors), contentDescription = null, tint = Color.Unspecified ) Column( modifier = Modifier .weight(1f) .padding(horizontal = RadixTheme.dimensions.paddingSmall), verticalArrangement = Arrangement.spacedBy(space = RadixTheme.dimensions.paddingSmall, alignment = Alignment.CenterVertically) ) { Text( text = stringResource(id = R.string.securityCenter_securityFactorsItem_title), style = RadixTheme.typography.body1Header, color = RadixTheme.colors.gray1 ) Text( text = stringResource(id = R.string.securityCenter_securityFactorsItem_subtitle), style = RadixTheme.typography.body2Regular, color = RadixTheme.colors.gray2 ) Row( modifier = Modifier.fillMaxWidth(), Arrangement.spacedBy(space = RadixTheme.dimensions.paddingSmall), verticalAlignment = Alignment.CenterVertically ) { val icon = if (needsAction) DSR.ic_warning_error else DSR.ic_check_circle val color = if (needsAction) RadixTheme.colors.orange3 else RadixTheme.colors.green1 val text = if (needsAction) { stringResource(id = R.string.securityCenter_anyItem_actionRequiredStatus) } else { stringResource(id = R.string.securityCenter_securityFactorsItem_activeStatus) } Icon( painter = painterResource(id = icon), contentDescription = null, tint = color ) Text( text = text, style = RadixTheme.typography.body2HighImportance, color = color ) } } } } @Composable private fun BackupConfigurationCard(needsAction: Boolean, onBackupConfigurationClick: () -> Unit) { Row( modifier = Modifier .shadow(6.dp, shape = RadixTheme.shapes.roundedRectMedium) .clip(RadixTheme.shapes.roundedRectMedium) .clickable { onBackupConfigurationClick() } .background(RadixTheme.colors.defaultBackground, RadixTheme.shapes.roundedRectMedium) .padding(horizontal = RadixTheme.dimensions.paddingDefault, vertical = RadixTheme.dimensions.paddingLarge), verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(space = RadixTheme.dimensions.paddingMedium) ) { Icon( modifier = Modifier.size(80.dp), painter = painterResource(id = DSR.ic_configuration_backup), contentDescription = null, tint = Color.Unspecified ) Column( modifier = Modifier .weight(1f) .padding(horizontal = RadixTheme.dimensions.paddingSmall), verticalArrangement = Arrangement.spacedBy(space = RadixTheme.dimensions.paddingSmall, alignment = Alignment.CenterVertically) ) { Text( text = stringResource(id = R.string.securityCenter_configurationBackupItem_title), style = RadixTheme.typography.body1Header, color = RadixTheme.colors.gray1 ) Text( text = stringResource(id = R.string.securityCenter_configurationBackupItem_subtitle), style = RadixTheme.typography.body2Regular, color = RadixTheme.colors.gray2 ) Row( modifier = Modifier.fillMaxWidth(), Arrangement.spacedBy(space = RadixTheme.dimensions.paddingSmall), verticalAlignment = Alignment.CenterVertically ) { val icon = if (needsAction) DSR.ic_warning_error else DSR.ic_check_circle val color = if (needsAction) RadixTheme.colors.orange3 else RadixTheme.colors.green1 val text = if (needsAction) { stringResource(id = R.string.securityCenter_anyItem_actionRequiredStatus) } else { stringResource(id = R.string.securityCenter_configurationBackupItem_backedUpStatus) } Icon( painter = painterResource(id = icon), contentDescription = null, tint = color ) Text( text = text, style = RadixTheme.typography.body2HighImportance, color = color ) } } } } @Composable fun SecurityProblem.toProblemHeading(): String { return when (this) { is SecurityProblem.EntitiesNotRecoverable -> stringResource( id = R.string.securityCenter_problem3_heading, accountsNeedBackup, personasNeedBackup ) is SecurityProblem.EntitiesNeedRecovery -> stringResource(id = R.string.securityCenter_problem9_heading) SecurityProblem.BackupNotWorking -> stringResource(id = R.string.securityCenter_problem6_heading) } } @Preview(showBackground = true) @Composable fun SecurityCenterContentPreviewAllOk() { RadixWalletTheme { SecurityCenterContent( state = SecurityCenterViewModel.SecurityCenterUiState( securityProblems = emptySet() ), onBackClick = {}, onSecurityFactorsClick = {}, onBackupConfigurationClick = {}, onRecoverEntitiesClick = {}, onBackupEntities = {} ) } } @UsesSampleValues @Preview(showBackground = true) @Composable fun SecurityCenterContentPreviewAllNotOk() { RadixWalletTheme { SecurityCenterContent( state = SecurityCenterViewModel.SecurityCenterUiState( securityProblems = setOf( SecurityProblem.EntitiesNeedRecovery(FactorSource.Device.sample.invoke().id) ) ), onBackClick = {}, onSecurityFactorsClick = {}, onBackupConfigurationClick = {}, onRecoverEntitiesClick = {}, onBackupEntities = {} ) } }
7
Kotlin
11
6
c024b6ed21372d13ed8eba68ed04cef0aa73333b
16,785
babylon-wallet-android
Apache License 2.0
app/src/main/java/com/meksconway/covid/ui/fragment/home/HomeFragment.kt
meksconways
256,483,114
false
null
package com.meksconway.covid.ui.fragment.home import androidx.lifecycle.Observer import androidx.recyclerview.widget.GridLayoutManager import com.jakewharton.rxbinding3.view.clicks import com.meksconway.covid.R import com.meksconway.covid.base.BaseFragment import com.meksconway.covid.common.HomeFragmentRecyclerViewItemDecoration import com.meksconway.covid.common.extensions.addTo import com.meksconway.covid.common.extensions.injectSharedViewModel import com.meksconway.covid.common.extensions.injectViewModel import com.meksconway.covid.common.extensions.px import com.meksconway.covid.data.model.UIConfig import com.meksconway.covid.data.model.homecontent.HomeContent import com.meksconway.covid.data.model.homecontent.HomeContentType import com.meksconway.covid.ui.adapter.HomeContentAdapter import com.meksconway.covid.ui.fragment.country.CountryFragment import com.meksconway.covid.ui.fragment.country.CountryViewModel import kotlinx.android.synthetic.main.fragment_home.* import java.util.concurrent.TimeUnit class HomeFragment : BaseFragment<HomeViewModelInput, HomeViewModelOutput, HomeViewModel>() { companion object { fun newInstance() = HomeFragment() } override val currentUIConfig: UIConfig get() = UIConfig() override val viewModel: HomeViewModel? get() = injectViewModel(factory) private var countryVM: CountryViewModel? = null private val adapter: HomeContentAdapter by lazy { HomeContentAdapter() } override val layRes: Int get() = R.layout.fragment_home override fun viewDidLoad() { super.viewDidLoad() countryVM = injectSharedViewModel(factory) rvHome?.adapter = adapter rvHome?.addItemDecoration(HomeFragmentRecyclerViewItemDecoration(12.px)) btnCountry.clicks() .throttleFirst(400, TimeUnit.MILLISECONDS) .retry() .subscribe { viewModel?.input?.navigateCountrySelect() }.addTo(compositeDisposable) } override fun observeViewModel(output: HomeViewModelOutput?) { output?.homeContentOutput?.observe(viewLifecycleOwner, Observer { setAdapter(it) }) output?.navigateCountrySelectOutput?.observe(viewLifecycleOwner, Observer { navigator?.start(CountryFragment()) }) countryVM?.output?.selectedCountryOutput?.observe(viewLifecycleOwner, Observer { btnCountry?.text = it }) } private fun setAdapter(list: List<HomeContent>?) { list?.let { rvHome?.layoutManager = GridLayoutManager(context, 3).apply { this.spanSizeLookup = object : GridLayoutManager.SpanSizeLookup() { override fun getSpanSize(position: Int): Int { return when (it[position].contentType) { HomeContentType.HEADER -> 3 HomeContentType.PREVENTION -> 1 HomeContentType.YOUR_OWN_TEST -> 3 HomeContentType.TITLE -> 3 } } } } adapter.setItems(list) } } }
0
Kotlin
1
2
8feaacf6dc251b6359c19113e2dd0e2f05575d8d
3,220
Covid-19-Android
MIT License
src/main/kotlin/pistonlang/compiler/common/items/HandleTrees.kt
PistonLang
594,852,711
false
null
package pistonlang.compiler.common.items import pistonlang.compiler.common.language.SyntaxType import pistonlang.compiler.common.parser.RelativeNodeLoc import pistonlang.compiler.util.NonEmptyList import pistonlang.compiler.util.nonEmptyListOf data class HandleTree<out Type: SyntaxType>( val dataList: List<HandleData<Type>>, val nodes: List<HandleTreeNode<Type>>, ) { fun isEmpty() = nodes.isEmpty() } val emptyHandleTree = HandleTree<Nothing>(emptyList(), emptyList()) /** * The index of the handle data in a corresponding handle data list * -1 is used for invalid indices, everything else is expected to be an actual index */ typealias HandleDataIndex = Int const val invalidIndex: HandleDataIndex = -1 data class HandleTreeNode<out Type : SyntaxType>( val fullRange: RelativeNodeLoc<Type>, val index: HandleDataIndex, val children: List<HandleTreeNode<Type>> ) data class HandleData<out Type: SyntaxType>( val location: RelativeNodeLoc<Type>, val handles: NonEmptyList<ItemHandle>, ) val nullReferenceList = nonEmptyListOf(NullHandle)
0
Kotlin
0
0
ca127e4c1e79f1361a4319171177fecf608e94c0
1,082
compiler
MIT License
SDF/src/me/anno/sdf/shapes/SDFHeart.kt
AntonioNoack
456,513,348
false
null
package me.anno.ecs.components.mesh.sdf.shapes import me.anno.ecs.components.mesh.TypeValue import me.anno.ecs.components.mesh.sdf.SDFComposer.dot2 import me.anno.ecs.components.mesh.sdf.VariableCounter import me.anno.maths.Maths.SQRT2F import me.anno.maths.Maths.max import me.anno.maths.Maths.min import me.anno.maths.Maths.sq import me.anno.utils.structures.arrays.IntArrayList import org.joml.AABBf import org.joml.Vector4f import kotlin.math.abs import kotlin.math.sign import kotlin.math.sqrt @Suppress("unused") class SDFHeart : SDF2DShape() { override fun calculateBaseBounds(dst: AABBf) { dst.setMin(-0.60f, -0.55f, Float.NEGATIVE_INFINITY) dst.setMax(+0.60f, +0.55f, Float.POSITIVE_INFINITY) super.calculateBaseBounds(dst) } override fun buildShader( builder: StringBuilder, posIndex0: Int, nextVariableId: VariableCounter, dstIndex: Int, uniforms: HashMap<String, TypeValue>, functions: HashSet<String>, seeds: ArrayList<String> ) { val trans = buildTransform(builder, posIndex0, nextVariableId, uniforms, functions, seeds) functions.add(dot2) functions.add(heartSDF) smartMinBegin(builder, dstIndex) builder.append("sdHeart(") writeFuncInput(builder, trans.posIndex) builder.append(')') smartMinEnd(builder, dstIndex, nextVariableId, uniforms, functions, seeds, trans) } override fun computeSDFBase(pos: Vector4f, seeds: IntArrayList): Float { val px = abs(pos.x) val py = pos.y + 0.55f return if (px + py > 1f) sqrt(sq(px - 0.25f, py - 0.75f)) - SQRT2F * 0.25f else { val di = 0.5f * max(px + py, 0f) sqrt(min(sq(px, py - 1f), sq(px - di, py - di))) * sign(px - py) } } override fun clone(): SDFHeart { val clone = SDFHeart() copy(clone) return clone } override val className get() = "SDFHeart" companion object { // from https://www.shadertoy.com/view/Xds3zN, <NAME> private const val heartSDF = "" + "float sdHeart(vec2 p){\n" + " p.y += 0.55;\n" + // centering " p.x = abs(p.x);\n" + " if(p.y+p.x>1.0)\n" + " return sqrt(dot2(p-vec2(0.25,0.75))) - sqrt(2.0)/4.0;\n" + " return sqrt(min(dot2(p-vec2(0.00,1.00)),\n" + " dot2(p-0.5*max(p.x+p.y,0.0)))) * sign(p.x-p.y);\n" + "}\n" } }
0
null
3
9
17bbf880148cbbc81edae00494411d18e390ccd3
2,561
RemsEngine
Apache License 2.0
app/src/main/java/openfoodfacts/github/scrachx/openfood/images/ImageSize.kt
openfoodfacts
35,174,991
false
null
package openfoodfacts.github.scrachx.openfood.images /** * Image size. Warn: don't change these values: they are used to retrieve API keys */ enum class ImageSize { SMALL, DISPLAY, THUMB }
390
null
447
772
836bab540ec9e2792b692a3b25ff61e444fae045
195
openfoodfacts-androidapp
Apache License 2.0
githubApi/src/commonMain/kotlin/io/github/opletter/espul/gh/data/Team.kt
DennisTsar
739,949,683
false
{"Kotlin": 161521, "HTML": 398}
package io.github.opletter.espul.gh.data import kotlinx.serialization.SerialName import kotlinx.serialization.Serializable import kotlinx.serialization.json.JsonNull @Serializable data class Team( val description: String?, @SerialName("html_url") val htmlUrl: String, val id: Int, @SerialName("members_url") val membersUrl: String, val name: String, @SerialName("node_id") val nodeId: String, @SerialName("notification_setting") val notificationSetting: String? = null, // TeamSimple but always null val parent: JsonNull, val permission: String, // val permissions: Permissions? = null, // optional in docs val privacy: String, @SerialName("repositories_url") val repositoriesUrl: String, val slug: String, val url: String, ) //@Serializable //data class TeamSimple( // val description: String?, // @SerialName("html_url") // val htmlUrl: String, // val id: Int, // @SerialName("ldap_dn") // val ldapDn: String? = null, // @SerialName("members_url") // val membersUrl: String, // val name: String, // @SerialName("node_id") // val nodeId: String, // @SerialName("notification_setting") // val notificationSetting: String? = null, // val permission: String, // val privacy: String? = null, // @SerialName("repositories_url") // val repositoriesUrl: String, // val slug: String, // val url: String, //)
0
Kotlin
0
0
ae8b4f59abd2b593698a050baa01fa4ce3f0c5aa
1,444
Espul
Apache License 2.0
app/src/main/java/com/example/inventory/ui/home/HomeViewModel.kt
sfeng1
785,449,063
false
{"Kotlin": 33995}
/* * <NAME> * OSU * CS 492 */ package com.example.inventory.ui.home import android.util.Log import androidx.compose.material3.Text import androidx.lifecycle.ViewModel import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.setValue import com.example.inventory.data.Airport import com.example.inventory.data.AirportRepo import com.example.inventory.ui.home.HomeUiState import androidx.lifecycle.viewModelScope import com.example.inventory.data.FavAir import com.example.inventory.data.Flights import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.StateFlow import kotlinx.coroutines.flow.asStateFlow import kotlinx.coroutines.flow.update import kotlinx.coroutines.launch import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.collect /** * ViewModel to retrieve all items in the Room database. */ class HomeViewModel(private val airportRepo: AirportRepo) : ViewModel() { private val _flightUiState = MutableStateFlow(HomeUiState()) val flightUiState: StateFlow<HomeUiState> = _flightUiState.asStateFlow() // auto complete fun searchBarUpdate(query: String) { viewModelScope.launch { airportRepo.getAirports(query).collect { queryAirportList -> _flightUiState.update { currentState -> currentState.copy( filterAirportList = queryAirportList, ) } } } } // when user inputs search term fun searchFindFlights(query: String) { viewModelScope.launch { airportRepo.getAirport(query).collect { queryResult -> airportRepo.getFlights(queryResult.name).collect { queryFlightList -> _flightUiState.update { currentState -> currentState.copy( screenTitle = queryResult.name, searchQuery = queryResult, filterAirportList = emptyList(), filterFlightList = queryFlightList ) } } } } } // when user clicks autocomplete button fun searchFindFlightsBtn(airport: Airport) { viewModelScope.launch { airportRepo.getFlights(airport.name).collect { queryFlightList -> _flightUiState.update { currentState -> currentState.copy( screenTitle = airport.name, searchQuery = airport, filterAirportList = emptyList(), filterFlightList = queryFlightList ) } } } } // add a fav suspend fun addFav(flights: Flights) { airportRepo.insert(FavAir(departure_code = flights.iata_start, destination_code = flights.iata_end)) airportRepo.getAllFavs().collect{ updateFavList -> _flightUiState.update { currentState -> currentState.copy( favList = updateFavList, ) } Log.d("mytag", _flightUiState.value.favList.toString()) } } // return to home screen, reset all state vars fun returnHome() { viewModelScope.launch { _flightUiState.update { currentState -> currentState.copy( screenTitle = "Flight Search", searchQuery = null, filterFlightList = emptyList(), filterAirportList = emptyList(), ) } } } // return to home screen, reset all state vars fun favLookup(favAir: FavAir):Flights { lateinit var returnObj: Flights viewModelScope.launch { airportRepo.getFavDeets(favAir.departure_code, favAir.destination_code) .collect { favObj -> returnObj = favObj } } return returnObj } } // end
0
Kotlin
0
0
12cddf80f082f0febc4ad798d2d82fdbc8b7a2f6
4,245
flight-search
Apache License 2.0
src/commonMain/kotlin/com/jeffpdavidson/kotwords/formats/unidecode/x5c.kt
jpd236
143,651,464
false
{"Kotlin": 4427197, "HTML": 41941, "Rouge": 3731, "Perl": 1705, "Shell": 744, "JavaScript": 618}
package com.jeffpdavidson.kotwords.formats.unidecode internal val x5c = arrayOf( // 0x5c00: 尀 => Po "\u0050\u006f\u0020", // 0x5c01: 封 => Feng "\u0046\u0065\u006e\u0067\u0020", // 0x5c02: 専 => Zhuan "\u005a\u0068\u0075\u0061\u006e\u0020", // 0x5c03: 尃 => Fu "\u0046\u0075\u0020", // 0x5c04: 射 => She "\u0053\u0068\u0065\u0020", // 0x5c05: 尅 => Ke "\u004b\u0065\u0020", // 0x5c06: 将 => Jiang "\u004a\u0069\u0061\u006e\u0067\u0020", // 0x5c07: 將 => Jiang "\u004a\u0069\u0061\u006e\u0067\u0020", // 0x5c08: 專 => Zhuan "\u005a\u0068\u0075\u0061\u006e\u0020", // 0x5c09: 尉 => Wei "\u0057\u0065\u0069\u0020", // 0x5c0a: 尊 => Zun "\u005a\u0075\u006e\u0020", // 0x5c0b: 尋 => Xun "\u0058\u0075\u006e\u0020", // 0x5c0c: 尌 => Shu "\u0053\u0068\u0075\u0020", // 0x5c0d: 對 => Dui "\u0044\u0075\u0069\u0020", // 0x5c0e: 導 => Dao "\u0044\u0061\u006f\u0020", // 0x5c0f: 小 => Xiao "\u0058\u0069\u0061\u006f\u0020", // 0x5c10: 尐 => Ji "\u004a\u0069\u0020", // 0x5c11: 少 => Shao "\u0053\u0068\u0061\u006f\u0020", // 0x5c12: 尒 => Er "\u0045\u0072\u0020", // 0x5c13: 尓 => Er "\u0045\u0072\u0020", // 0x5c14: 尔 => Er "\u0045\u0072\u0020", // 0x5c15: 尕 => Ga "\u0047\u0061\u0020", // 0x5c16: 尖 => Jian "\u004a\u0069\u0061\u006e\u0020", // 0x5c17: 尗 => Shu "\u0053\u0068\u0075\u0020", // 0x5c18: 尘 => Chen "\u0043\u0068\u0065\u006e\u0020", // 0x5c19: 尙 => Shang "\u0053\u0068\u0061\u006e\u0067\u0020", // 0x5c1a: 尚 => Shang "\u0053\u0068\u0061\u006e\u0067\u0020", // 0x5c1b: 尛 => Mo "\u004d\u006f\u0020", // 0x5c1c: 尜 => Ga "\u0047\u0061\u0020", // 0x5c1d: 尝 => Chang "\u0043\u0068\u0061\u006e\u0067\u0020", // 0x5c1e: 尞 => Liao "\u004c\u0069\u0061\u006f\u0020", // 0x5c1f: 尟 => Xian "\u0058\u0069\u0061\u006e\u0020", // 0x5c20: 尠 => Xian "\u0058\u0069\u0061\u006e\u0020", // 0x5c21: 尡 => [?] "\u005b\u003f\u005d\u0020", // 0x5c22: 尢 => Wang "\u0057\u0061\u006e\u0067\u0020", // 0x5c23: 尣 => Wang "\u0057\u0061\u006e\u0067\u0020", // 0x5c24: 尤 => You "\u0059\u006f\u0075\u0020", // 0x5c25: 尥 => Liao "\u004c\u0069\u0061\u006f\u0020", // 0x5c26: 尦 => Liao "\u004c\u0069\u0061\u006f\u0020", // 0x5c27: 尧 => Yao "\u0059\u0061\u006f\u0020", // 0x5c28: 尨 => Mang "\u004d\u0061\u006e\u0067\u0020", // 0x5c29: 尩 => Wang "\u0057\u0061\u006e\u0067\u0020", // 0x5c2a: 尪 => Wang "\u0057\u0061\u006e\u0067\u0020", // 0x5c2b: 尫 => Wang "\u0057\u0061\u006e\u0067\u0020", // 0x5c2c: 尬 => Ga "\u0047\u0061\u0020", // 0x5c2d: 尭 => Yao "\u0059\u0061\u006f\u0020", // 0x5c2e: 尮 => Duo "\u0044\u0075\u006f\u0020", // 0x5c2f: 尯 => Kui "\u004b\u0075\u0069\u0020", // 0x5c30: 尰 => Zhong "\u005a\u0068\u006f\u006e\u0067\u0020", // 0x5c31: 就 => Jiu "\u004a\u0069\u0075\u0020", // 0x5c32: 尲 => Gan "\u0047\u0061\u006e\u0020", // 0x5c33: 尳 => Gu "\u0047\u0075\u0020", // 0x5c34: 尴 => Gan "\u0047\u0061\u006e\u0020", // 0x5c35: 尵 => Tui "\u0054\u0075\u0069\u0020", // 0x5c36: 尶 => Gan "\u0047\u0061\u006e\u0020", // 0x5c37: 尷 => Gan "\u0047\u0061\u006e\u0020", // 0x5c38: 尸 => Shi "\u0053\u0068\u0069\u0020", // 0x5c39: 尹 => Yin "\u0059\u0069\u006e\u0020", // 0x5c3a: 尺 => Chi "\u0043\u0068\u0069\u0020", // 0x5c3b: 尻 => Kao "\u004b\u0061\u006f\u0020", // 0x5c3c: 尼 => Ni "\u004e\u0069\u0020", // 0x5c3d: 尽 => Jin "\u004a\u0069\u006e\u0020", // 0x5c3e: 尾 => Wei "\u0057\u0065\u0069\u0020", // 0x5c3f: 尿 => Niao "\u004e\u0069\u0061\u006f\u0020", // 0x5c40: 局 => Ju "\u004a\u0075\u0020", // 0x5c41: 屁 => Pi "\u0050\u0069\u0020", // 0x5c42: 层 => Ceng "\u0043\u0065\u006e\u0067\u0020", // 0x5c43: 屃 => Xi "\u0058\u0069\u0020", // 0x5c44: 屄 => Bi "\u0042\u0069\u0020", // 0x5c45: 居 => Ju "\u004a\u0075\u0020", // 0x5c46: 屆 => Jie "\u004a\u0069\u0065\u0020", // 0x5c47: 屇 => Tian "\u0054\u0069\u0061\u006e\u0020", // 0x5c48: 屈 => Qu "\u0051\u0075\u0020", // 0x5c49: 屉 => Ti "\u0054\u0069\u0020", // 0x5c4a: 届 => Jie "\u004a\u0069\u0065\u0020", // 0x5c4b: 屋 => Wu "\u0057\u0075\u0020", // 0x5c4c: 屌 => Diao "\u0044\u0069\u0061\u006f\u0020", // 0x5c4d: 屍 => Shi "\u0053\u0068\u0069\u0020", // 0x5c4e: 屎 => Shi "\u0053\u0068\u0069\u0020", // 0x5c4f: 屏 => Ping "\u0050\u0069\u006e\u0067\u0020", // 0x5c50: 屐 => Ji "\u004a\u0069\u0020", // 0x5c51: 屑 => Xie "\u0058\u0069\u0065\u0020", // 0x5c52: 屒 => Chen "\u0043\u0068\u0065\u006e\u0020", // 0x5c53: 屓 => Xi "\u0058\u0069\u0020", // 0x5c54: 屔 => Ni "\u004e\u0069\u0020", // 0x5c55: 展 => Zhan "\u005a\u0068\u0061\u006e\u0020", // 0x5c56: 屖 => Xi "\u0058\u0069\u0020", // 0x5c57: 屗 => [?] "\u005b\u003f\u005d\u0020", // 0x5c58: 屘 => Man "\u004d\u0061\u006e\u0020", // 0x5c59: 屙 => E "\u0045\u0020", // 0x5c5a: 屚 => Lou "\u004c\u006f\u0075\u0020", // 0x5c5b: 屛 => Ping "\u0050\u0069\u006e\u0067\u0020", // 0x5c5c: 屜 => Ti "\u0054\u0069\u0020", // 0x5c5d: 屝 => Fei "\u0046\u0065\u0069\u0020", // 0x5c5e: 属 => Shu "\u0053\u0068\u0075\u0020", // 0x5c5f: 屟 => Xie "\u0058\u0069\u0065\u0020", // 0x5c60: 屠 => Tu "\u0054\u0075\u0020", // 0x5c61: 屡 => Lu "\u004c\u0075\u0020", // 0x5c62: 屢 => Lu "\u004c\u0075\u0020", // 0x5c63: 屣 => Xi "\u0058\u0069\u0020", // 0x5c64: 層 => Ceng "\u0043\u0065\u006e\u0067\u0020", // 0x5c65: 履 => Lu "\u004c\u0075\u0020", // 0x5c66: 屦 => Ju "\u004a\u0075\u0020", // 0x5c67: 屧 => Xie "\u0058\u0069\u0065\u0020", // 0x5c68: 屨 => Ju "\u004a\u0075\u0020", // 0x5c69: 屩 => Jue "\u004a\u0075\u0065\u0020", // 0x5c6a: 屪 => Liao "\u004c\u0069\u0061\u006f\u0020", // 0x5c6b: 屫 => Jue "\u004a\u0075\u0065\u0020", // 0x5c6c: 屬 => Shu "\u0053\u0068\u0075\u0020", // 0x5c6d: 屭 => Xi "\u0058\u0069\u0020", // 0x5c6e: 屮 => Che "\u0043\u0068\u0065\u0020", // 0x5c6f: 屯 => Tun "\u0054\u0075\u006e\u0020", // 0x5c70: 屰 => Ni "\u004e\u0069\u0020", // 0x5c71: 山 => Shan "\u0053\u0068\u0061\u006e\u0020", // 0x5c72: 屲 => [?] "\u005b\u003f\u005d\u0020", // 0x5c73: 屳 => Xian "\u0058\u0069\u0061\u006e\u0020", // 0x5c74: 屴 => Li "\u004c\u0069\u0020", // 0x5c75: 屵 => Xue "\u0058\u0075\u0065\u0020", // 0x5c76: 屶 => Nata "\u004e\u0061\u0074\u0061\u0020", // 0x5c77: 屷 => [?] "\u005b\u003f\u005d\u0020", // 0x5c78: 屸 => Long "\u004c\u006f\u006e\u0067\u0020", // 0x5c79: 屹 => Yi "\u0059\u0069\u0020", // 0x5c7a: 屺 => Qi "\u0051\u0069\u0020", // 0x5c7b: 屻 => Ren "\u0052\u0065\u006e\u0020", // 0x5c7c: 屼 => Wu "\u0057\u0075\u0020", // 0x5c7d: 屽 => Han "\u0048\u0061\u006e\u0020", // 0x5c7e: 屾 => Shen "\u0053\u0068\u0065\u006e\u0020", // 0x5c7f: 屿 => Yu "\u0059\u0075\u0020", // 0x5c80: 岀 => Chu "\u0043\u0068\u0075\u0020", // 0x5c81: 岁 => Sui "\u0053\u0075\u0069\u0020", // 0x5c82: 岂 => Qi "\u0051\u0069\u0020", // 0x5c83: 岃 => [?] "\u005b\u003f\u005d\u0020", // 0x5c84: 岄 => Yue "\u0059\u0075\u0065\u0020", // 0x5c85: 岅 => Ban "\u0042\u0061\u006e\u0020", // 0x5c86: 岆 => Yao "\u0059\u0061\u006f\u0020", // 0x5c87: 岇 => Ang "\u0041\u006e\u0067\u0020", // 0x5c88: 岈 => Ya "\u0059\u0061\u0020", // 0x5c89: 岉 => Wu "\u0057\u0075\u0020", // 0x5c8a: 岊 => Jie "\u004a\u0069\u0065\u0020", // 0x5c8b: 岋 => E "\u0045\u0020", // 0x5c8c: 岌 => Ji "\u004a\u0069\u0020", // 0x5c8d: 岍 => Qian "\u0051\u0069\u0061\u006e\u0020", // 0x5c8e: 岎 => Fen "\u0046\u0065\u006e\u0020", // 0x5c8f: 岏 => Yuan "\u0059\u0075\u0061\u006e\u0020", // 0x5c90: 岐 => Qi "\u0051\u0069\u0020", // 0x5c91: 岑 => Cen "\u0043\u0065\u006e\u0020", // 0x5c92: 岒 => Qian "\u0051\u0069\u0061\u006e\u0020", // 0x5c93: 岓 => Qi "\u0051\u0069\u0020", // 0x5c94: 岔 => Cha "\u0043\u0068\u0061\u0020", // 0x5c95: 岕 => Jie "\u004a\u0069\u0065\u0020", // 0x5c96: 岖 => Qu "\u0051\u0075\u0020", // 0x5c97: 岗 => Gang "\u0047\u0061\u006e\u0067\u0020", // 0x5c98: 岘 => Xian "\u0058\u0069\u0061\u006e\u0020", // 0x5c99: 岙 => Ao "\u0041\u006f\u0020", // 0x5c9a: 岚 => Lan "\u004c\u0061\u006e\u0020", // 0x5c9b: 岛 => Dao "\u0044\u0061\u006f\u0020", // 0x5c9c: 岜 => Ba "\u0042\u0061\u0020", // 0x5c9d: 岝 => Zuo "\u005a\u0075\u006f\u0020", // 0x5c9e: 岞 => Zuo "\u005a\u0075\u006f\u0020", // 0x5c9f: 岟 => Yang "\u0059\u0061\u006e\u0067\u0020", // 0x5ca0: 岠 => Ju "\u004a\u0075\u0020", // 0x5ca1: 岡 => Gang "\u0047\u0061\u006e\u0067\u0020", // 0x5ca2: 岢 => Ke "\u004b\u0065\u0020", // 0x5ca3: 岣 => Gou "\u0047\u006f\u0075\u0020", // 0x5ca4: 岤 => Xue "\u0058\u0075\u0065\u0020", // 0x5ca5: 岥 => Bei "\u0042\u0065\u0069\u0020", // 0x5ca6: 岦 => Li "\u004c\u0069\u0020", // 0x5ca7: 岧 => Tiao "\u0054\u0069\u0061\u006f\u0020", // 0x5ca8: 岨 => Ju "\u004a\u0075\u0020", // 0x5ca9: 岩 => Yan "\u0059\u0061\u006e\u0020", // 0x5caa: 岪 => Fu "\u0046\u0075\u0020", // 0x5cab: 岫 => Xiu "\u0058\u0069\u0075\u0020", // 0x5cac: 岬 => Jia "\u004a\u0069\u0061\u0020", // 0x5cad: 岭 => Ling "\u004c\u0069\u006e\u0067\u0020", // 0x5cae: 岮 => Tuo "\u0054\u0075\u006f\u0020", // 0x5caf: 岯 => Pei "\u0050\u0065\u0069\u0020", // 0x5cb0: 岰 => You "\u0059\u006f\u0075\u0020", // 0x5cb1: 岱 => Dai "\u0044\u0061\u0069\u0020", // 0x5cb2: 岲 => Kuang "\u004b\u0075\u0061\u006e\u0067\u0020", // 0x5cb3: 岳 => Yue "\u0059\u0075\u0065\u0020", // 0x5cb4: 岴 => Qu "\u0051\u0075\u0020", // 0x5cb5: 岵 => Hu "\u0048\u0075\u0020", // 0x5cb6: 岶 => Po "\u0050\u006f\u0020", // 0x5cb7: 岷 => Min "\u004d\u0069\u006e\u0020", // 0x5cb8: 岸 => An "\u0041\u006e\u0020", // 0x5cb9: 岹 => Tiao "\u0054\u0069\u0061\u006f\u0020", // 0x5cba: 岺 => Ling "\u004c\u0069\u006e\u0067\u0020", // 0x5cbb: 岻 => Chi "\u0043\u0068\u0069\u0020", // 0x5cbc: 岼 => Yuri "\u0059\u0075\u0072\u0069\u0020", // 0x5cbd: 岽 => Dong "\u0044\u006f\u006e\u0067\u0020", // 0x5cbe: 岾 => Cem "\u0043\u0065\u006d\u0020", // 0x5cbf: 岿 => Kui "\u004b\u0075\u0069\u0020", // 0x5cc0: 峀 => Xiu "\u0058\u0069\u0075\u0020", // 0x5cc1: 峁 => Mao "\u004d\u0061\u006f\u0020", // 0x5cc2: 峂 => Tong "\u0054\u006f\u006e\u0067\u0020", // 0x5cc3: 峃 => Xue "\u0058\u0075\u0065\u0020", // 0x5cc4: 峄 => Yi "\u0059\u0069\u0020", // 0x5cc5: 峅 => Kura "\u004b\u0075\u0072\u0061\u0020", // 0x5cc6: 峆 => He "\u0048\u0065\u0020", // 0x5cc7: 峇 => Ke "\u004b\u0065\u0020", // 0x5cc8: 峈 => Luo "\u004c\u0075\u006f\u0020", // 0x5cc9: 峉 => E "\u0045\u0020", // 0x5cca: 峊 => Fu "\u0046\u0075\u0020", // 0x5ccb: 峋 => Xun "\u0058\u0075\u006e\u0020", // 0x5ccc: 峌 => Die "\u0044\u0069\u0065\u0020", // 0x5ccd: 峍 => Lu "\u004c\u0075\u0020", // 0x5cce: 峎 => An "\u0041\u006e\u0020", // 0x5ccf: 峏 => Er "\u0045\u0072\u0020", // 0x5cd0: 峐 => Gai "\u0047\u0061\u0069\u0020", // 0x5cd1: 峑 => Quan "\u0051\u0075\u0061\u006e\u0020", // 0x5cd2: 峒 => Tong "\u0054\u006f\u006e\u0067\u0020", // 0x5cd3: 峓 => Yi "\u0059\u0069\u0020", // 0x5cd4: 峔 => Mu "\u004d\u0075\u0020", // 0x5cd5: 峕 => Shi "\u0053\u0068\u0069\u0020", // 0x5cd6: 峖 => An "\u0041\u006e\u0020", // 0x5cd7: 峗 => Wei "\u0057\u0065\u0069\u0020", // 0x5cd8: 峘 => Hu "\u0048\u0075\u0020", // 0x5cd9: 峙 => Zhi "\u005a\u0068\u0069\u0020", // 0x5cda: 峚 => Mi "\u004d\u0069\u0020", // 0x5cdb: 峛 => Li "\u004c\u0069\u0020", // 0x5cdc: 峜 => Ji "\u004a\u0069\u0020", // 0x5cdd: 峝 => Tong "\u0054\u006f\u006e\u0067\u0020", // 0x5cde: 峞 => Wei "\u0057\u0065\u0069\u0020", // 0x5cdf: 峟 => You "\u0059\u006f\u0075\u0020", // 0x5ce0: 峠 => Sang "\u0053\u0061\u006e\u0067\u0020", // 0x5ce1: 峡 => Xia "\u0058\u0069\u0061\u0020", // 0x5ce2: 峢 => Li "\u004c\u0069\u0020", // 0x5ce3: 峣 => Yao "\u0059\u0061\u006f\u0020", // 0x5ce4: 峤 => Jiao "\u004a\u0069\u0061\u006f\u0020", // 0x5ce5: 峥 => Zheng "\u005a\u0068\u0065\u006e\u0067\u0020", // 0x5ce6: 峦 => Luan "\u004c\u0075\u0061\u006e\u0020", // 0x5ce7: 峧 => Jiao "\u004a\u0069\u0061\u006f\u0020", // 0x5ce8: 峨 => E "\u0045\u0020", // 0x5ce9: 峩 => E "\u0045\u0020", // 0x5cea: 峪 => Yu "\u0059\u0075\u0020", // 0x5ceb: 峫 => Ye "\u0059\u0065\u0020", // 0x5cec: 峬 => Bu "\u0042\u0075\u0020", // 0x5ced: 峭 => Qiao "\u0051\u0069\u0061\u006f\u0020", // 0x5cee: 峮 => Qun "\u0051\u0075\u006e\u0020", // 0x5cef: 峯 => Feng "\u0046\u0065\u006e\u0067\u0020", // 0x5cf0: 峰 => Feng "\u0046\u0065\u006e\u0067\u0020", // 0x5cf1: 峱 => Nao "\u004e\u0061\u006f\u0020", // 0x5cf2: 峲 => Li "\u004c\u0069\u0020", // 0x5cf3: 峳 => You "\u0059\u006f\u0075\u0020", // 0x5cf4: 峴 => Xian "\u0058\u0069\u0061\u006e\u0020", // 0x5cf5: 峵 => Hong "\u0048\u006f\u006e\u0067\u0020", // 0x5cf6: 島 => Dao "\u0044\u0061\u006f\u0020", // 0x5cf7: 峷 => Shen "\u0053\u0068\u0065\u006e\u0020", // 0x5cf8: 峸 => Cheng "\u0043\u0068\u0065\u006e\u0067\u0020", // 0x5cf9: 峹 => Tu "\u0054\u0075\u0020", // 0x5cfa: 峺 => Geng "\u0047\u0065\u006e\u0067\u0020", // 0x5cfb: 峻 => Jun "\u004a\u0075\u006e\u0020", // 0x5cfc: 峼 => Hao "\u0048\u0061\u006f\u0020", // 0x5cfd: 峽 => Xia "\u0058\u0069\u0061\u0020", // 0x5cfe: 峾 => Yin "\u0059\u0069\u006e\u0020", // 0x5cff: 峿 => Yu "\u0059\u0075\u0020", )
8
Kotlin
6
25
e18e9cf0bad7497da15b40f6c81ba4234ec83917
14,627
kotwords
Apache License 2.0
app/src/main/java/dev/pimentel/marvelapp/shared/network/RequestInterceptor.kt
bfpimentel
225,730,080
false
null
package dev.pimentel.marvelapp.shared.network import android.content.Context import dev.pimentel.marvelapp.R import okhttp3.Interceptor import okhttp3.Response import java.math.BigInteger import java.security.MessageDigest import java.util.* /** * @author <NAME> on 04/12/2019 */ class RequestInterceptor( private val context: Context ) : Interceptor { override fun intercept(chain: Interceptor.Chain): Response { val originalRequest = chain.request() val originalUrl = originalRequest.url val timeStamp = Date().time.toString() val newUrl = originalUrl.newBuilder() .addQueryParameter(TIMESTAMP_NAME, timeStamp) .addQueryParameter(API_KEY_NAME, context.getString(R.string.marvel_api_public_key)) .addQueryParameter( HASH_NAME, String.format( HASH_FORMAT, timeStamp, context.getString(R.string.marvel_api_private_key), context.getString(R.string.marvel_api_public_key) ).hash() ).build() return originalRequest.newBuilder() .url(newUrl) .build() .let(chain::proceed) } private fun String.hash() = MessageDigest.getInstance(MD5).let { messageDigest -> BigInteger(1, messageDigest.digest(toByteArray())) .toString(16) .padStart(32, '0') } private companion object { private const val TIMESTAMP_NAME = "ts" private const val API_KEY_NAME = "apikey" private const val HASH_NAME = "hash" private const val MD5 = "MD5" private const val HASH_FORMAT = "%s%s%s" } }
0
Kotlin
0
0
8990a7f098e15ad35b4cf743b79be6424b5ff2c4
1,745
marvel-app
MIT License
app/src/main/java/com/example/stockmarket/data/mapper/CompanyMapper.kt
NathanP11
802,882,602
false
{"Kotlin": 37530}
package com.example.stockmarket.data.mapper import com.example.stockmarket.data.local.CompanyListingEntity import com.example.stockmarket.data.remote.dto.CompanyInfoDto import com.example.stockmarket.domain.model.CompanyInfo import com.example.stockmarket.domain.model.CompanyListing fun CompanyListingEntity.toCompanyListing() = CompanyListing(name, symbol, exchange) fun CompanyListing.toCompanyListingEntity() = CompanyListingEntity(name, symbol, exchange) fun CompanyInfoDto.toCompanyInfo() = CompanyInfo( symbol = symbol ?: "", description = description ?: "", name = name ?: "", country = country ?: "", industry = industry ?: "" )
0
Kotlin
0
0
71a830026a308be1d6719430cf66ecf81c45638d
661
stock-market-app-main
Apache License 2.0
one.irradia.mime.tests/src/main/java/one/irradia/mime/tests/MIMELexerContract.kt
irradia
177,191,881
false
{"Gradle": 6, "INI": 4, "Shell": 1, "Ignore List": 1, "Batchfile": 1, "Text": 2, "XML": 4, "YAML": 1, "Markdown": 1, "Kotlin": 18, "Java": 2, "Java Properties": 1}
package one.irradia.mime.tests import one.irradia.mime.api.MIMELexerResult import one.irradia.mime.api.MIMELexerType import one.irradia.mime.api.MIMEToken.EOF import one.irradia.mime.api.MIMEToken.Equals import one.irradia.mime.api.MIMEToken.MIMETextToken.Quoted import one.irradia.mime.api.MIMEToken.MIMETextToken.Text import one.irradia.mime.api.MIMEToken.Semicolon import one.irradia.mime.api.MIMEToken.Slash import org.junit.jupiter.api.Assertions.assertEquals import org.junit.jupiter.api.Test abstract class MIMELexerContract { abstract fun lexer(text: String): MIMELexerType @Test fun testEmpty() { val lexer = lexer("") val token = lexer.token() assertEquals(MIMELexerResult.Success(EOF(0)), token) } @Test fun testType() { val lexer = lexer("type") run { val token = lexer.token() assertEquals(MIMELexerResult.Success(Text(0, "type")), token) } run { val token = lexer.token() assertEquals(MIMELexerResult.Success(EOF(4)), token) } run { val token = lexer.token() assertEquals(MIMELexerResult.Success(EOF(4)), token) } } @Test fun testSemicolon0() { val lexer = lexer(";") run { val token = lexer.token() assertEquals(MIMELexerResult.Success(Semicolon(0)), token) } run { val token = lexer.token() assertEquals(MIMELexerResult.Success(EOF(1)), token) } run { val token = lexer.token() assertEquals(MIMELexerResult.Success(EOF(1)), token) } } @Test fun testSemicolon1() { val lexer = lexer(";;") run { val token = lexer.token() assertEquals(MIMELexerResult.Success(Semicolon(0)), token) } run { val token = lexer.token() assertEquals(MIMELexerResult.Success(Semicolon(1)), token) } run { val token = lexer.token() assertEquals(MIMELexerResult.Success(EOF(2)), token) } run { val token = lexer.token() assertEquals(MIMELexerResult.Success(EOF(2)), token) } } @Test fun testSlashSemicolon0() { val lexer = lexer("/;/") run { val token = lexer.token() assertEquals(MIMELexerResult.Success(Slash(0)), token) } run { val token = lexer.token() assertEquals(MIMELexerResult.Success(Semicolon(1)), token) } run { val token = lexer.token() assertEquals(MIMELexerResult.Success(Text(2, "/")), token) } run { val token = lexer.token() assertEquals(MIMELexerResult.Success(EOF(3)), token) } run { val token = lexer.token() assertEquals(MIMELexerResult.Success(EOF(3)), token) } } @Test fun testEquals() { val lexer = lexer("=") run { val token = lexer.token() assertEquals(MIMELexerResult.Success(Equals(0)), token) } run { val token = lexer.token() assertEquals(MIMELexerResult.Success(EOF(1)), token) } run { val token = lexer.token() assertEquals(MIMELexerResult.Success(EOF(1)), token) } } @Test fun testTypeSubtype() { val lexer = lexer("type/subtype") run { val token = lexer.token() assertEquals(MIMELexerResult.Success(Text(0, "type")), token) } run { val token = lexer.token() assertEquals(MIMELexerResult.Success(Slash(4)), token) } run { val token = lexer.token() assertEquals(MIMELexerResult.Success(Text(5, "subtype")), token) } run { val token = lexer.token() assertEquals(MIMELexerResult.Success(EOF(12)), token) } run { val token = lexer.token() assertEquals(MIMELexerResult.Success(EOF(12)), token) } } @Test fun testQuoted() { val lexer = lexer("\"type/subtype\"") run { val token = lexer.token() assertEquals(MIMELexerResult.Success(Quoted(1, "type/subtype")), token) } run { val token = lexer.token() assertEquals(MIMELexerResult.Success(EOF(14)), token) } run { val token = lexer.token() assertEquals(MIMELexerResult.Success(EOF(14)), token) } } @Test fun testTextPlain0() { val lexer = lexer("text/plain;charset=utf-8") run { val token = lexer.token() assertEquals(MIMELexerResult.Success(Text(0, "text")), token) } run { val token = lexer.token() assertEquals(MIMELexerResult.Success(Slash(4)), token) } run { val token = lexer.token() assertEquals(MIMELexerResult.Success(Text(5, "plain")), token) } run { val token = lexer.token() assertEquals(MIMELexerResult.Success(Semicolon(10)), token) } run { val token = lexer.token() assertEquals(MIMELexerResult.Success(Text(11, "charset")), token) } run { val token = lexer.token() assertEquals(MIMELexerResult.Success(Equals(18)), token) } run { val token = lexer.token() assertEquals(MIMELexerResult.Success(Text(19, "utf-8")), token) } run { val token = lexer.token() assertEquals(MIMELexerResult.Success(EOF(24)), token) } run { val token = lexer.token() assertEquals(MIMELexerResult.Success(EOF(24)), token) } } @Test fun testTextPlain1() { val lexer = lexer("text/plain;charset=\"utf-8\"") run { val token = lexer.token() assertEquals(MIMELexerResult.Success(Text(0, "text")), token) } run { val token = lexer.token() assertEquals(MIMELexerResult.Success(Slash(4)), token) } run { val token = lexer.token() assertEquals(MIMELexerResult.Success(Text(5, "plain")), token) } run { val token = lexer.token() assertEquals(MIMELexerResult.Success(Semicolon(10)), token) } run { val token = lexer.token() assertEquals(MIMELexerResult.Success(Text(11, "charset")), token) } run { val token = lexer.token() assertEquals(MIMELexerResult.Success(Equals(18)), token) } run { val token = lexer.token() assertEquals(MIMELexerResult.Success(Quoted(20, "utf-8")), token) } run { val token = lexer.token() assertEquals(MIMELexerResult.Success(EOF(26)), token) } run { val token = lexer.token() assertEquals(MIMELexerResult.Success(EOF(26)), token) } } @Test fun testOPDS0() { val lexer = lexer("text/html;profile=http://librarysimplified.org/terms/profiles/streaming-media") run { val token = lexer.token() assertEquals(MIMELexerResult.Success(Text(0, "text")), token) } run { val token = lexer.token() assertEquals(MIMELexerResult.Success(Slash(4)), token) } run { val token = lexer.token() assertEquals(MIMELexerResult.Success(Text(5, "html")), token) } run { val token = lexer.token() assertEquals(MIMELexerResult.Success(Semicolon(9)), token) } run { val token = lexer.token() assertEquals(MIMELexerResult.Success(Text(10, "profile")), token) } run { val token = lexer.token() assertEquals(MIMELexerResult.Success(Equals(17)), token) } run { val token = lexer.token() assertEquals(MIMELexerResult.Success(Text(18, "http://librarysimplified.org/terms/profiles/streaming-media")), token) } run { val token = lexer.token() assertEquals(MIMELexerResult.Success(EOF(77)), token) } run { val token = lexer.token() assertEquals(MIMELexerResult.Success(EOF(77)), token) } } @Test fun testQuotedUnexpectedEOF() { val lexer = lexer("\"") run { val token = lexer.token() assertEquals(MIMELexerResult.Failure::class.java, token.javaClass) } run { val token = lexer.token() assertEquals(MIMELexerResult.Failure::class.java, token.javaClass) } } }
1
null
1
1
a7fdefce539d5367c6f740ef8e430e71d4115274
7,891
one.irradia.mime
BSD Zero Clause License
src/main/kotlin/com/demonwav/mcdev/platform/bungeecord/inspection/BungeeCordListenerImplementedInspection.kt
Earthcomputer
240,984,777
false
null
/* * Minecraft Dev for IntelliJ * * https://minecraftdev.org * * Copyright (c) 2022 minecraft-dev * * MIT License */ package com.demonwav.mcdev.platform.bungeecord.inspection import com.demonwav.mcdev.platform.bungeecord.util.BungeeCordConstants import com.demonwav.mcdev.util.addImplements import com.demonwav.mcdev.util.extendsOrImplements import com.intellij.codeInspection.ProblemDescriptor import com.intellij.openapi.project.Project import com.intellij.psi.PsiClass import com.siyeh.ig.BaseInspection import com.siyeh.ig.BaseInspectionVisitor import com.siyeh.ig.InspectionGadgetsFix import org.jetbrains.annotations.Nls class BungeeCordListenerImplementedInspection : BaseInspection() { @Nls override fun getDisplayName() = "BungeeCord @EventHandler in class not implementing Listener" override fun buildErrorString(vararg infos: Any) = "This class contains @EventHandler methods but does not implement Listener" override fun getStaticDescription() = "All BungeeCord @EventHandler methods must reside in a class that implements Listener." override fun buildFix(vararg infos: Any): InspectionGadgetsFix? { return object : InspectionGadgetsFix() { override fun doFix(project: Project, descriptor: ProblemDescriptor) { val psiClass = infos[0] as PsiClass psiClass.addImplements(BungeeCordConstants.LISTENER_CLASS) } @Nls override fun getName() = "Implement Listener" @Nls override fun getFamilyName() = name } } override fun buildVisitor(): BaseInspectionVisitor { return object : BaseInspectionVisitor() { override fun visitClass(aClass: PsiClass) { val methods = aClass.methods val isEventHandler = methods.any { it.modifierList.findAnnotation(BungeeCordConstants.HANDLER_ANNOTATION) != null } if (!isEventHandler) { return } val inError = !aClass.extendsOrImplements(BungeeCordConstants.LISTENER_CLASS) if (inError) { registerClassError(aClass, aClass) } } } } }
204
null
2
23
ab8aaeb8804c7a8b2e439e063a73cb12d0a9d4b5
2,271
MinecraftDev
MIT License
FrenchKotlinIdeaProject/src/main/kotlin/Main.kt
TimCook314
674,810,000
false
{"Kotlin": 90309}
//fun main() { // println("Hello, World!") //} import java.io.BufferedReader import java.io.File import java.io.FileReader // --------------------------- fun main(args: Array<String>) { println("Hello World!") // Try adding program arguments via Run/Debug configuration. // Learn more about running applications: https://www.jetbrains.com/help/idea/running-applications.html. println("Program arguments: ${args.joinToString()}") readVocabData("C:\\TimCook\\FrenchLangApp\\FrenchKotlinCodeDev\\A_Vocab.txt") //readVocabData("G:\\My Drive\\French\\A_NewVocab.txt") speakIt() if ((0..1).random() > 20) { readVocabData("G:\\My Drive\\French\\TestVocab2.txt") } } private fun reportIt(txt: String) { println(txt) } private fun speakIt() { var itemsPlayed = 0 while (itemsPlayed < 10) { itemsPlayed++ val fAndEPair = getThePhrase() val toPrint = "${fAndEPair.fTxt} --> ${fAndEPair.eTxt}" reportIt(toPrint) } } //! private fun readVocalData(context: Context, uri: Uri, name: String) { private fun readVocabData( name: String) { if (name == "none") { return } println("Reading file.") try { val file = File(name) val bufferedReader = BufferedReader(FileReader(file)) val linesRead = readIt(bufferedReader) reportIt(" Lines read is $linesRead") // Close the BufferedReader bufferedReader.close() } catch (e: Exception) { reportIt("*** Error accessing file.") } } //fun addTheToStartOfNoun( noun: String, mf: String ) { // var startsWithVowel = false // // var char1 = noun.lowercase()[0] // if (char1 == 'h') { // //use second character // char1 = noun.lowercase()[1] // } // when (char1) { // 'a' -> { startsWithVowel = true } // 'e' -> { startsWithVowel = true } // 'i' -> { startsWithVowel = true } // 'o' -> { startsWithVowel = true } // 'u' -> { startsWithVowel = true } // 'é' -> { startsWithVowel = true } // 'à' -> { startsWithVowel = true } // 'è' -> { startsWithVowel = true } // 'ù' -> { startsWithVowel = true } // 'â' -> { startsWithVowel = true } // 'ê' -> { startsWithVowel = true } // 'î' -> { startsWithVowel = true } // 'ô' -> { startsWithVowel = true } // 'û' -> { startsWithVowel = true } // 'ë' -> { startsWithVowel = true } // 'ï' -> { startsWithVowel = true } // 'ü' -> { startsWithVowel = true } // } //} // -------------------- //Classes ----- enum class Perspective { Unset, First, Second, Third, } enum class Gender { Unset, M, F, Either, } enum class Quantity { Unset, Single, Plural, Either, } class Pronoun { var MFSP: String = "" var fText: String = "" var eText: String = "" var freq: Int = 1 } class Noun { var wordGender: Gender = Gender.Unset var wordQuantity: Quantity = Quantity.Unset var article: String = "" var elision: Boolean = false var fTextS: String = "" var fTextP: String = "" var eTextS: String = "" var eTextP: String = "" var meta: String = "" var weight: Float = 1.0f } class Adjective { var eAdj: String = "" var relPos: String = "" var masculine: String = "" var feminine: String = "" var masculinePlural: String = "" var femininePlural: String = "" var freq: Int = 1 } class Verb { var fInfinitive: String = "" var eBase: String = "" var e3rdPeronSingular: String = "" var Je: String = "" var Tu: String = "" var Il_Elle: String = "" var Nous: String = "" var Vous: String = "" var Ils_Elles: String = "" var freq: Int = 1 } class Phrase { var fPhrase: String = "" var ePhrase: String = "" var freq: Int = 1 } class LangData { var frenchSpeed: Float = 1.0f var frenchPauseFactor: Double = 1.0 var phrasePatterns = mutableListOf<String>() var audioPattern: String = "fef" var frenchVoice: String = "" var englishVoice: String = "" val pronoun = mutableListOf<Pronoun>() val nouns = mutableListOf<Noun>() val adjectives = mutableListOf<Adjective>() val verbs = mutableListOf<Verb>() val phrases = mutableListOf<Phrase>() } data class FAndEPair(val fTxt: String, val eTxt: String) data class ANoun(val pqg: PQG, val article: String, val fTxt: String, val eTxt: String) class PQG { var perspective: Perspective = Perspective.Unset var gender: Gender = Gender.Unset var quantity: Quantity = Quantity.Unset } class AnAdjective { var eText: String = "" var fText: String = "" var gender: Gender = Gender.M var quantity: Quantity = Quantity.Single } class Subject { var eText: String = "" var fText: String = "" var pqg: PQG = PQG() } // //enum class SubjectPerspective { // Je_Nous, sdf, WEST, EAST //} // //class SubjectPart { // var eTxt: String = "" // var fTxt: String = "" // var perspective: SubjectPerspective = SubjectPerspective.Je_Nous // var quantity: SubjectQuantity = SubjectQuantity.single // var gender: SubjectGender = SubjectGender.m //} //Data ------ private var vocabList: LangData = LangData() //Code ------------ fun readIt(bufferedReader: BufferedReader): Int { var linesRead = 0 try { // Use a loop to read each line until the end of the file var line: String? do { line = bufferedReader.readLine() linesRead++ if (line == null) { break } line = line.trim() if (line.startsWith("#")) { continue } else if (line.startsWith("@")) { //code it val parts = line.split("=") val part0 = parts[0].drop(1).trim() when (part0) { "frenchSpeed" -> { vocabList.frenchSpeed = parts[1].toFloat() } "frenchPauseFactor" -> { vocabList.frenchPauseFactor = parts[1].toDouble() } "phrasePatterns" -> { vocabList.phrasePatterns.add( parts[1].trim() ) } "audioPattern" -> { vocabList.audioPattern = parts[1].trim() } "frenchVoice" -> { vocabList.frenchVoice = parts[1].trim() } "englishVoice" -> { vocabList.englishVoice = parts[1].trim() } else -> { reportIt("*** Error parsing line $line") //code } } } else { val parts = line.split(";") val part0 = parts[0].lowercase().trim() when (part0) { "pronoun" -> { val the = Pronoun() the.fText = parts[1].trim() the.MFSP = parts[2].trim() the.eText = parts[3].trim() if (parts.size >= (4 + 1)) { the.freq = parts[4].toInt() } vocabList.pronoun.add(the) } "noun" -> { val the = Noun() the.wordGender = stringToGender(parts[1].trim()) the.wordQuantity = stringToQuantity(parts[2].trim()) the.article = parts[3].trim() the.elision = stringToElision(parts[4].trim()) var rc: Int = 0 var txt1: String = parts[5].trim() //{ var sText: String // = "error" var pText: String // = "errors" var iStart = txt1.indexOf("(") if (iStart < 0) { //Noun has the same form in the singular and the plural: fish, etc sText = txt1 pText = txt1 } else { val iEnd = txt1.indexOf(")") if (iEnd < 0) { //Found opening but no closing rc++ } sText = txt1.substring(0,iStart) pText = txt1.substring(iStart+1,iEnd) if (pText.length <= 2) { //If the plural is 2 characters or less, it is a suffix: such as: s, es pText = sText + pText } } //} the.fTextS = sText the.fTextP = pText //txt2SingleAndPluralNouns(txt1, rc, the.fTextS, the.fTextP) txt1 = parts[6].trim() //{ //sText = "error" //pText = "errors" iStart = txt1.indexOf("(") if (iStart < 0) { //Noun has the same form in the singular and the plural: fish, etc sText = txt1 pText = txt1 } else { val iEnd = txt1.indexOf(")") if (iEnd < 0) { //Found opening but no closing rc++ } sText = txt1.substring(0,iStart) pText = txt1.substring(iStart+1,iEnd) if (pText.length <= 2) { //If the plural is 2 characters or less, it is a suffix: such as: s, es pText = sText + pText } } //} the.eTextS = sText the.eTextP = pText //txt2SingleAndPluralNouns(txt2, rc, the.eTextS, the.eTextP) if ((parts.size >= (8 + 1)) && (parts[8].trim().length > 1)) { the.weight = parts[8].toFloat() } if ( rc <= 0 ) { vocabList.nouns.add(the) } } "adjective" -> { val the = Adjective() the.eAdj = parts[1].trim() the.relPos = parts[2].trim() the.masculine = parts[3].trim() the.feminine = parts[4].trim() the.masculinePlural = parts[5].trim() the.femininePlural = parts[6].trim() if (parts.size >= (7 + 1)) { the.freq = parts[7].toInt() } vocabList.adjectives.add(the) } "verb" -> { val the = Verb() the.fInfinitive = parts[1].trim() the.eBase = parts[2].trim() the.e3rdPeronSingular = parts[3].trim() the.Je = parts[4].trim() the.Tu = parts[5].trim() the.Il_Elle = parts[6].trim() the.Nous = parts[7].trim() the.Vous = parts[8].trim() the.Ils_Elles = parts[9].trim() if (parts.size >= (10 + 1)) { the.freq = parts[10].toInt() } vocabList.verbs.add(the) } "phrase" -> { val the = Phrase() the.fPhrase = parts[1].trim() the.ePhrase = parts[2].trim() if (parts.size >= (3 + 1)) { the.freq = parts[3].toInt() } vocabList.phrases.add(the) } else -> { //code } } } } while (true) // (line != null) } catch (e: Exception) { reportIt("*** Error reading file at about line $linesRead") } return linesRead } private fun getThePhrase(): FAndEPair { var fText1 = "Erreur!" var eText1 = "Error!" //Decide what to do next val pattern = vocabList.phrasePatterns.random() when (pattern) { "phrase" -> { val phrase = vocabList.phrases.random() fText1 = phrase.fPhrase eText1 = phrase.ePhrase } "noun" -> { val aNoun = getAnyNoun() fText1 = aNoun.fTxt eText1 = aNoun.eTxt } "the noun" -> { val aNoun = getAnyNoun() fText1 = if (aNoun.article.endsWith("'")) { aNoun.article + aNoun.fTxt } else { aNoun.article + " " + aNoun.fTxt } eText1 = "the ${aNoun.eTxt}" } "the noun a nouns" -> { val noun = vocabList.nouns.random() eText1 = "Nouns error" var quan: Quantity = noun.wordQuantity if (quan == Quantity.Either) { if ((1..2).random() == 1) { quan = Quantity.Single } else { quan = Quantity.Plural } } if (quan == Quantity.Single) { var unUne: String = "une" if (noun.wordGender == Gender.M) { unUne = "un" } fText1 = if (noun.elision) { noun.article + noun.fTextS + ", " + unUne + " " + noun.fTextS } else { noun.article + " " + noun.fTextS + ", " + unUne + " " + noun.fTextS } eText1 = "the ${noun.eTextS}, a ${noun.eTextS}" } else if (quan == Quantity.Plural) { fText1 = "les " + noun.fTextP + ", des " + noun.fTextP eText1 = "the ${noun.eTextP}, some ${noun.eTextP}" } } "Je suis {adjective.Masculine or adjective.Feminine}" -> { val subjectGender: Gender = Gender.values().random() val subjectQuantity: Quantity = Quantity.Single val adj2 = getAnAdjective( subjectGender, subjectQuantity ) fText1 = "Je suis ${adj2.fText}" eText1 = "I am ${adj2.eText}" } "{pronoun} are {adjective}" -> { val pronouns = listOf("Je", "Tu", "Il", "Elle", "Nous", "Vous", "Ils", "Elles") val pronoun = pronouns.random() when (pronoun) { "Je" -> { val subjectGender: Gender = Gender.values().random() val subjectQuantity: Quantity = Quantity.Single val adj2 = getAnAdjective(subjectGender, subjectQuantity) fText1 = "Je suis ${adj2.fText}" eText1 = "I am ${adj2.eText}" } "Tu" -> { val subjectGender: Gender = Gender.values().random() val subjectQuantity: Quantity = Quantity.Single val adj2 = getAnAdjective(subjectGender, subjectQuantity) fText1 = "Tu es ${adj2.fText}" eText1 = "You are ${adj2.eText}" } "Il" -> { val subjectGender: Gender = Gender.M val subjectQuantity: Quantity = Quantity.Single val adj2 = getAnAdjective(subjectGender, subjectQuantity) fText1 = "Il est ${adj2.fText}" eText1 = "He is ${adj2.eText}" } "Elle" -> { val subjectGender: Gender = Gender.F val subjectQuantity: Quantity = Quantity.Single val adj2 = getAnAdjective(subjectGender, subjectQuantity) fText1 = "Elle est ${adj2.fText}" eText1 = "She is ${adj2.eText}" } "Nous" -> { val subjectGender: Gender = Gender.values().random() val subjectQuantity: Quantity = Quantity.Plural val adj2 = getAnAdjective(subjectGender, subjectQuantity) fText1 = "Nous sommes ${adj2.fText}" eText1 = "We are ${adj2.eText}" } "Vous" -> { val subjectGender: Gender = Gender.values().random() val subjectQuantity: Quantity = Quantity.values().random() val adj2 = getAnAdjective(subjectGender, subjectQuantity) fText1 = "Vous êtes ${adj2.fText}" eText1 = if (subjectQuantity == Quantity.Single) { "You are ${adj2.eText}" } else { "Y'all are ${adj2.eText}" } } "Ils" -> { val subjectGender: Gender = Gender.M val subjectQuantity: Quantity = Quantity.Plural val adj2 = getAnAdjective(subjectGender, subjectQuantity) fText1 = "Ils sont ${adj2.fText}" eText1 = "They are ${adj2.eText}" } "Elles" -> { val subjectGender: Gender = Gender.F val subjectQuantity: Quantity = Quantity.Plural val adj2 = getAnAdjective(subjectGender, subjectQuantity) fText1 = "Elles sont ${adj2.fText}" eText1 = "They are ${adj2.eText}" } } } "{pronoun} {want/have/like/go/take} {a/the} {noun}" -> { //Get a subject pronoun //Get a verb //Get a or the //Get object (noun for now) //val subject = getASubject() //val aVerb = getAVerb( PQG ) //val anObject = getAnObject( ) val pronouns = listOf("Je", "Tu", "Il", "Elle", "Nous", "Vous", "Ils", "Elles") val pronoun = pronouns.random() } } return FAndEPair(fText1, eText1) } private fun getAnAdjective(gender: Gender, quantity: Quantity): AnAdjective { val anAdjective = AnAdjective() val adj = vocabList.adjectives.random() anAdjective.gender = gender anAdjective.quantity = quantity if ( gender == Gender.M ) { if ( quantity == Quantity.Single) { anAdjective.eText = adj.eAdj anAdjective.fText = adj.masculine } else { //quantity == Quantity.plural anAdjective.eText = adj.eAdj anAdjective.fText = adj.masculinePlural } } else { //gender == Gender.f ) { if ( quantity == Quantity.Single) { anAdjective.eText = adj.eAdj anAdjective.fText = adj.feminine } else { //quantity == Quantity.plural anAdjective.eText = adj.eAdj anAdjective.fText = adj.femininePlural } } if ((0..4).random() >=4) { anAdjective.eText = "very " + anAdjective.eText anAdjective.fText = "très " + anAdjective.fText } return anAdjective } //private fun getASubject(): Subject { // var aSubject = Subject() // // if ((0..4).random() >= 3) { // val noun = vocabList.nouns.random() // //TODO: Select if we are going to use a or the in front // //TODO: Select if we are going to make it plural // aSubject.eText = noun.eText // aSubject.fText = noun.fText // aSubject.pqg.gender = Gender.M // aSubject.pqg.perspective = Perspective.First //TODO: Fix Need a function to select or get the gender from MFSP // aSubject.pqg.quantity = Quantity.Single //TODO: Fix Need a function to select or get the gender from MFSP // aSubject.pqg.gender = Gender.M //TODO: Fix Need a function to select or get the gender from MFSP // } else { // val pronoun = vocabList.pronoun.random() // aSubject.eText = pronoun.eText // aSubject.eText = pronoun.fText // aSubject.pqg.perspective = Perspective.First //TODO: Fix Need a function to select or get the gender from MFSP // aSubject.pqg.quantity = Quantity.Single //TODO: Fix Need a function to select or get the gender from MFSP // aSubject.pqg.gender = Gender.M //TODO: Fix Need a function to select or get the gender from MFSP // } // return aSubject //} private fun getAnyNoun(): ANoun { //data class ANoun(val pqg: PQG, val article: String, val fTxt: String, val eTxt: String) val pqg: PQG = PQG() var article: String = "" var fTxt: String = "Erreur" var eTxt: String = "Error" val noun = vocabList.nouns.random() pqg.quantity = noun.wordQuantity if (pqg.quantity == Quantity.Either) { pqg.quantity = Quantity.Single if ((0..2).random() >= 2) { pqg.quantity = Quantity.Plural } } if (pqg.quantity == Quantity.Single) { pqg.quantity = Quantity.Single pqg.gender = noun.wordGender pqg.perspective = Perspective.Third article = noun.article fTxt = noun.fTextS eTxt = noun.eTextS } else if (pqg.quantity == Quantity.Plural) { pqg.quantity = Quantity.Plural pqg.gender = noun.wordGender pqg.perspective = Perspective.Third article = "les" fTxt = noun.fTextP eTxt = noun.eTextP } return ANoun(pqg, article, fTxt, eTxt) } private fun stringToGender(txt: String): Gender { val txt2 = txt.trim().lowercase() if (txt2 == "m") { return Gender.M } else if (txt2 == "f") { return Gender.F } return Gender.Unset } private fun stringToElision(txt: String): Boolean { val txt2 = txt.trim().lowercase() return txt2 == "y" } private fun stringToQuantity(txt: String): Quantity { val txt2 = txt.trim().lowercase() if (txt2 == "s") { return Quantity.Single } else if (txt2 == "p") { return Quantity.Plural } else if (txt2 == "s&p") { return Quantity.Either } else if (txt2 == "s(p)") { return Quantity.Either } return Quantity.Unset } //private fun txt2SingleAndPluralNouns(txt: String, rc: Int, sText: String, pText: String){ // sText = "error" // pText = "errors" // val iStart = txt.indexOf("(") // if (iStart < 0) { //Noun has the same form in the singular and the plural: fish, etc // sText = txt1 // pText = txt1 // } else { // val iEnd = txt1.indexOf(")") // if (iEnd < 0) { Found opening but no closing // rc++ // return // } // sText = txt1.substring(0,iStart) // if (pForm.length <= 2) { //If the plural is 2 charactes or less, it is a suffix: such as: s, es // pText = sForm + txt1.substring(iStart+1,iEnd) // } else { // pText = txt1.substring(iStart+1,iEnd) // } // } //} //private fun getArtial // var subjectPart: SubjectPart = SubjectPart() // // subjectPart.gender = SubjectGender.m // // return subjectPart //}
0
Kotlin
0
0
ba274908eb21411b614e462a7adcdc211fb8f7dd
23,904
FrenchLangApp
MIT License
tests/push-apps-unit-tests/src/test/kotlin/unit/ConfigReaderTest.kt
cloudfoundry-incubator
114,146,752
false
null
package unit import org.apache.commons.io.FilenameUtils import org.assertj.core.api.Assertions.assertThat import org.cloudfoundry.tools.pushapps.config.ConfigReader import org.cloudfoundry.tools.pushapps.config.DatabaseDriver import org.jetbrains.spek.api.Spek import org.jetbrains.spek.api.dsl.context import org.jetbrains.spek.api.dsl.describe import org.jetbrains.spek.api.dsl.it import java.nio.file.Paths class ConfigReaderTest : Spek({ fun findConfigPath(fileName: String): String { val compiledFileLocation = ConfigReaderTest::class.java.getResource("${ConfigReaderTest::class.simpleName}.class") val projectPath = Paths.get(compiledFileLocation.path.toString(), "../../../../../../src/test/kotlin/support/$fileName") .toAbsolutePath().toString() return FilenameUtils.normalize(projectPath) } describe("#parseConfig") { context("parsing a minimal config") { it("correctly defaults values that are not provided for the pushAppsConfig config") { val pushAppsConfig = ConfigReader.parseConfig(findConfigPath("minimalConfig.yml")).get() assertThat(pushAppsConfig.pushApps.operationRetryCount).isEqualTo(3) assertThat(pushAppsConfig.pushApps.maxInFlight).isEqualTo(2) assertThat(pushAppsConfig.pushApps.failedDeploymentLogLinesToShow).isEqualTo(50) assertThat(pushAppsConfig.pushApps.migrationTimeoutInMinutes).isEqualTo(15L) assertThat(pushAppsConfig.pushApps.cfOperationTimeoutInMinutes).isEqualTo(5L) } it("correctly defaults values that are not provided for the cf config") { val pushAppsConfig = ConfigReader.parseConfig(findConfigPath("minimalConfig.yml")).get() assertThat(pushAppsConfig.cf.skipSslValidation).isFalse() assertThat(pushAppsConfig.cf.dialTimeoutInMillis).isNull() } it("correctly defaults values that are not provided for the apps config") { val pushAppsConfig = ConfigReader.parseConfig(findConfigPath("minimalConfig.yml")).get() val apps = pushAppsConfig.apps assertThat(apps).hasSize(1) val app1 = apps[0] assertThat(app1.name).isEqualTo("some-name") assertThat(app1.path).isEqualTo("some-path") assertThat(app1.serviceNames).isEmpty() //this is a partial list, didn't see the need to be exhaustive assertThat(app1.buildpack).isNull() assertThat(app1.command).isNull() assertThat(app1.environment).isNull() assertThat(app1.route).isNull() } it("correctly defaults values that are not provided for the services config") { val pushAppsConfig = ConfigReader.parseConfig(findConfigPath("minimalConfig.yml")).get() val services = pushAppsConfig.services assertThat(services).hasSize(1) val service = services[0] assertThat(service.optional).isFalse() } it("correctly defaults values that are not provided for the db migration config") { val pushAppsConfig = ConfigReader.parseConfig(findConfigPath("minimalConfig.yml")).get() val migrations = pushAppsConfig.migrations assertThat(migrations).hasSize(1) val migration = migrations[0] assertThat(migration.repair).isFalse() } } it("Parses the pushAppsConfig config") { val pushAppsConfig = ConfigReader.parseConfig(findConfigPath("exampleConfig.yml")).get() assertThat(pushAppsConfig.pushApps.operationRetryCount).isEqualTo(3) assertThat(pushAppsConfig.pushApps.maxInFlight).isEqualTo(42) assertThat(pushAppsConfig.pushApps.failedDeploymentLogLinesToShow).isEqualTo(12) assertThat(pushAppsConfig.pushApps.migrationTimeoutInMinutes).isEqualTo(7L) assertThat(pushAppsConfig.pushApps.cfOperationTimeoutInMinutes).isEqualTo(3L) } it("Parses the cf config") { val pushAppsConfig = ConfigReader.parseConfig(findConfigPath("exampleConfig.yml")).get() assertThat(pushAppsConfig.cf.apiHost).isEqualTo("api.example.com") assertThat(pushAppsConfig.cf.username).isEqualTo("some-username") assertThat(pushAppsConfig.cf.password).isEqualTo("<PASSWORD>") assertThat(pushAppsConfig.cf.organization).isEqualTo("some-organization") assertThat(pushAppsConfig.cf.space).isEqualTo("some-space") assertThat(pushAppsConfig.cf.skipSslValidation).isTrue() assertThat(pushAppsConfig.cf.dialTimeoutInMillis).isEqualTo(1000) } context("Parsing the apps config") { it("correctly assigns values") { val pushAppsConfig = ConfigReader.parseConfig(findConfigPath("exampleConfig.yml")).get() val apps = pushAppsConfig.apps assertThat(apps).hasSize(2) val app1 = apps[0] assertThat(app1.name).isEqualTo("some-name") assertThat(app1.path).isEqualTo("some-path") assertThat(app1.buildpack).isEqualTo("some-buildpack") assertThat(app1.memory).isEqualTo(456) assertThat(app1.diskQuota).isEqualTo(500) assertThat(app1.stackPriority).isEqualTo(listOf("some-stack", "some-other-stack")) assertThat(app1.environment).isEqualTo(mapOf("FRUIT" to "lemons", "MISSING" to "")) assertThat(app1.serviceNames).isEqualTo(listOf("some-service-name")) assertThat(app1.route!!.hostname).isEqualTo("lemons") assertThat(app1.route!!.path).isEqualTo("/citrus") val app2 = apps[1] assertThat(app2.memory).isEqualTo(1024) assertThat(app2.diskQuota).isEqualTo(2048) assertThat(app2.stackPriority).isEqualTo(emptyList<String>()) } context("if blueGreenDeploy is true") { it("throws an error unless a route is provided or noRoute is true") { val pushAppsConfig = ConfigReader.parseConfig(findConfigPath("blueGreenDeployConfig.yml")) assertThat(pushAppsConfig).isEmpty() } } } it("Parses the services config") { val pushAppsConfig = ConfigReader.parseConfig(findConfigPath("exampleConfig.yml")).get() val services = pushAppsConfig.services assertThat(services).hasSize(1) val service = services[0] assertThat(service.name).isEqualTo("some-service-name") assertThat(service.plan).isEqualTo("a-good-one") assertThat(service.broker).isEqualTo("some-broker") assertThat(service.optional).isTrue() } it("Parses the security group config") { val pushAppsConfig = ConfigReader.parseConfig(findConfigPath("exampleConfig.yml")).get() val securityGroups = pushAppsConfig.securityGroups assertThat(securityGroups).hasSize(1) val securityGroup = securityGroups[0] assertThat(securityGroup.name).isEqualTo("some-group") assertThat(securityGroup.destination).isEqualTo("some-destination") assertThat(securityGroup.protocol).isEqualTo("all") } it("Parses the user provided services config") { val pushAppsConfig = ConfigReader.parseConfig(findConfigPath("exampleConfig.yml")).get() val userProvidedServices = pushAppsConfig.userProvidedServices assertThat(userProvidedServices).hasSize(1) val service = userProvidedServices[0] assertThat(service.name).isEqualTo("some-user-provided-service-name") assertThat(service.credentials).isEqualTo(mapOf("username" to "some-username")) } it("Parses the db migration config") { val pushAppsConfig = ConfigReader.parseConfig(findConfigPath("exampleConfig.yml")).get() val migrations = pushAppsConfig.migrations assertThat(migrations).hasSize(1) val migration = migrations[0] assertThat(migration.user).isEqualTo("user") assertThat(migration.password).isEqualTo("<PASSWORD>") assertThat(migration.driver).isInstanceOfAny(DatabaseDriver.Postgres::class.java) assertThat(migration.host).isEqualTo("10.0.0.1") assertThat(migration.port).isEqualTo("5432") assertThat(migration.schema).isEqualTo("metrics") assertThat(migration.migrationDir).isEqualTo("/all/the/cool/migrations") assertThat(migration.repair).isFalse() assertThat(migration.placeholders).isEqualTo(mapOf("SOME_PLACEHOLDER" to "foo foo")) } } })
10
Kotlin
2
1
e4971e4f85de88b9a08eccf998172842aa784666
9,081
push-apps
Apache License 2.0
config/src/main/kotlin/uk/govuk/app/config/flags/local/LocalFlagRepo.kt
alphagov
788,896,208
false
{"Kotlin": 107147}
package uk.govuk.app.config.flags.local import javax.inject.Inject class LocalFlagRepo @Inject constructor() { fun isSearchEnabled() = true }
0
Kotlin
0
1
dad64eb082223cd12bb0bb30578653752f9824d9
149
govuk-mobile-android-app
MIT License
app/src/main/java/com/wegdut/wegdut/CourseService.kt
laishere
301,439,203
false
null
package com.wegdut.wegdut import android.app.NotificationChannel import android.app.NotificationManager import android.app.PendingIntent import android.content.Context import android.content.Intent import android.content.SharedPreferences import android.os.Build import android.os.IBinder import androidx.core.app.NotificationCompat import androidx.core.app.NotificationManagerCompat import androidx.core.text.HtmlCompat import com.wegdut.wegdut.data.edu.course.Course import com.wegdut.wegdut.room.v1.edu.course.CourseDao import com.wegdut.wegdut.room.v1.kv_storage.KVDao import com.wegdut.wegdut.room.v1.kv_storage.KVEntity import com.wegdut.wegdut.ui.course_table.CourseTableActivity import com.wegdut.wegdut.utils.ApiUtils import com.wegdut.wegdut.utils.CourseUtils import com.wegdut.wegdut.utils.DateUtils import dagger.android.DaggerService import kotlinx.coroutines.* import java.util.* import javax.inject.Inject /** * CourseService有多渠道启动,比如CourseActivity和AlarmManger。 */ class CourseService : DaggerService() { @Inject lateinit var courseDao: CourseDao @Inject lateinit var kvDao: KVDao private lateinit var sharedPreferences: SharedPreferences override fun onBind(intent: Intent?): IBinder? { return null } override fun onCreate() { super.onCreate() sharedPreferences = getSharedPreferences(packageName, MODE_PRIVATE) if (!isCourseNotificationEnabled()) { stopSelf() return } createNotificationChannel() try { CoroutineScope(Dispatchers.IO).launch { val minute = 60 * 1000L var lastCourse: Course? = null while (isActive) { val firstCourse = getFirstCourse() if (firstCourse == null || lastCourse == firstCourse || !isTaskValid(firstCourse)) { MyLog.debug(this@CourseService, "没有课程或者任务重复") delay(5 * minute) // 5分钟 continue } val timeAhead = COURSE_NOTIFICATION_MINUTES_AHEAD * minute val timeToWait = firstCourse.start.time - System.currentTimeMillis() - timeAhead if (timeToWait > 0) delay(timeToWait) val courses = getCoursesToNotify() if (courses.isEmpty()) continue val firstCourse2 = courses.first() if (!isTaskValid(firstCourse2)) continue notify(courses) val lastTask = KVEntity(COURSE_LAST_TASK, ApiUtils.gson.toJson(firstCourse2), Date()) kvDao.save(lastTask) lastCourse = firstCourse2 } } } catch (e: Throwable) { MyLog.error(this, e) } } /** * 检查任务是否重复 */ private fun isTaskValid(course: Course): Boolean { val kv = kvDao.get(COURSE_LAST_TASK) ?: return true val lastCourse = ApiUtils.gson.fromJson(kv.value, Course::class.java) if (lastCourse != course) return true val now = System.currentTimeMillis() val minute = 60_000L return now - kv.updatedAt.time > COURSE_NOTIFICATION_MINUTES_AHEAD * minute } private fun isCourseNotificationEnabled(): Boolean { return sharedPreferences.getBoolean(COURSE_NOTIFICATION_KEY, false) } private fun getTodayAndTomorrowCourses(): List<Course> { val today = DateUtils.onlyDate(Date()) val courses = mutableListOf<Course>() courseDao.get(today)?.let { courses.addAll(it.course) } val calendar = Calendar.getInstance() calendar.time = today calendar.add(Calendar.DAY_OF_YEAR, 1) val tomorrow = calendar.time courseDao.get(tomorrow)?.let { courses.addAll(it.course) } return courses } private fun getFirstCourse(): Course? { val courses = getTodayAndTomorrowCourses() val now = Date() return courses.filter { it.start.after(now) }.minByOrNull { it.start } } private fun getCoursesToNotify(): List<Course> { val minute = 60 * 1000L val now = System.currentTimeMillis() val maxStartTime = now + minute * COURSE_NOTIFICATION_MINUTES_AHEAD return getTodayAndTomorrowCourses().filter { it.start.time in now..maxStartTime } .sortedBy { it.start } } private fun notify(courses: List<Course>) { if (!isCourseNotificationEnabled()) { stopSelf() return } val template = getString(R.string.course_notification_template) val style = NotificationCompat.InboxStyle() courses.forEach { val text = template.format(it.name, it.location, CourseUtils.getTime(it)) val html = HtmlCompat.fromHtml(text, HtmlCompat.FROM_HTML_MODE_COMPACT) style.addLine(html) } val intent = Intent(this, CourseTableActivity::class.java).apply { flags = Intent.FLAG_ACTIVITY_SINGLE_TOP } val contentIntent = PendingIntent.getActivity(this, 1, intent, PendingIntent.FLAG_CANCEL_CURRENT) val notification = NotificationCompat.Builder(this, CHANNEL_ID) .setSmallIcon(R.drawable.ic_wegdut_logo) .setContentTitle("${courses.size}门课程即将开始") .setStyle(style) .setPriority(NotificationCompat.PRIORITY_MAX) .setContentIntent(contentIntent) .build() with(NotificationManagerCompat.from(this)) { notify(COURSE_NOTIFICATION_ID, notification) } } private fun createNotificationChannel() { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { val name = getString(R.string.course_channel_name) val descriptionText = getString(R.string.course_channel_description) val importance = NotificationManager.IMPORTANCE_DEFAULT val channel = NotificationChannel(CHANNEL_ID, name, importance).apply { description = descriptionText } val notificationManager: NotificationManager = getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager notificationManager.createNotificationChannel(channel) } } companion object { const val CHANNEL_ID = "COURSE" const val COURSE_NOTIFICATION_ID = 1 const val COURSE_NOTIFICATION_KEY = "COURSE_NOTIFICATION_KEY" const val COURSE_NOTIFICATION_MINUTES_AHEAD = 30 const val COURSE_LAST_TASK = "COURSE_LAST_TASK" } }
0
Kotlin
2
6
b62720ce8fbe79817b9c05e6bb1eeff09f53e804
6,709
wegdut-android
MIT License
weiV/src/main/java/cn/flutterfirst/weiv/wrappers/linearlayout/weiVFlex.kt
hackware1993
493,227,143
false
{"Kotlin": 128669, "Java": 7893}
package cn.flutterfirst.weiv.wrappers.linearlayout import android.annotation.SuppressLint import android.content.Context import android.os.Build import android.view.Gravity import android.view.View import android.widget.LinearLayout import cn.flutterfirst.weiv.core.WeiV import cn.flutterfirst.weiv.core.extension.ExtensionMgr import cn.flutterfirst.weiv.core.extension.IExtensionCreator import cn.flutterfirst.weiv.core.extension.ISerializableWidget import cn.flutterfirst.weiv.core.extension.IWeiVExtension import cn.flutterfirst.weiv.core.keys.Key import cn.flutterfirst.weiv.core.others.* import cn.flutterfirst.weiv.core.widgets.ContainerRenderWidget import cn.flutterfirst.weiv.core.widgets.LeafRenderWidget import cn.flutterfirst.weiv.core.widgets.Widget import cn.flutterfirst.weiv.wrappers.InternalWidgetDesc import org.json.JSONObject open class weiVFlex<V : LinearLayout>( key: Key? = null, layoutParam: LayoutParam<*>? = null, childWidgets: ArrayList<Widget<*>> = ArrayList(), open var orientation: Int = FlexDirection.HORIZONTAL, open var gravity: Int = Gravity.START or Gravity.TOP, extra: Any? = null, ) : ContainerRenderWidget<V, weiVFlex<V>>(key, layoutParam, childWidgets, extra), IWeiVExtension, ISerializableWidget<weiVFlex<V>> { override fun createView(context: Context): V = LinearLayout(context) as V @SuppressLint("WrongConstant") override fun doParameter(view: V, first: Boolean): V { if (view.orientation != orientation) { view.orientation = orientation } if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) { if (view.gravity != gravity) { view.gravity = gravity } } else { view.gravity = gravity } return view } override fun processChildLayoutParam( parent: V, child: View, childLayoutParam: LayoutParam<*>?, ) { assert(childLayoutParam == null || childLayoutParam is FlexLayoutParam) var flexParam = childLayoutParam as FlexLayoutParam? if (flexParam == null) { flexParam = FlexLayoutParam() } if (flexParam != child.getLayoutParam<FlexLayoutParam>()) { child.setLayoutParam(flexParam) val lp = LinearLayout.LayoutParams(flexParam.width, flexParam.height) lp.gravity = flexParam.gravity lp.leftMargin = flexParam.leftMargin lp.topMargin = flexParam.topMargin lp.rightMargin = flexParam.rightMargin lp.bottomMargin = flexParam.bottomMargin lp.weight = flexParam.weight child.layoutParams = lp } } @JavaOnly open fun wOrientation(orientation: Int): weiVFlex<V> { this.orientation = orientation return this } @JavaOnly open fun wGravity(gravity: Int): weiVFlex<V> { this.gravity = gravity return this } override fun fromJson(jsonObj: JSONObject, param: Map<String, Any?>): weiVFlex<V> { orientation = (param["orientation"] as Int?) ?: FlexDirection.HORIZONTAL return this } override fun toString(): String { return "weiVFlex(orientation=$orientation, childCount=${childWidgets!!.size})" } } var creator: IExtensionCreator<weiVFlex<*>>? = null @KotlinOnly fun LeafRenderWidget<*, *>.applyFlexLayoutParams(block: FlexLayoutParam.() -> Unit) { layoutParam = FlexLayoutParam() block(layoutParam as FlexLayoutParam) } @KotlinOnly fun WeiV.Flex( key: Key? = null, layoutParam: LayoutParam<*>? = null, orientation: Int = FlexDirection.HORIZONTAL, gravity: Int = Gravity.START or Gravity.TOP, extra: Any? = null, block: WeiV.(widget: weiVFlex<*>) -> Unit, ): weiVFlex<*> { if (creator == null) { creator = ExtensionMgr.getExtension(InternalWidgetDesc.FLEX) } return addContainerRenderWidget( creator!!.createWidget( key, layoutParam, ArrayList<Widget<*>>(), orientation, gravity, extra ), block ) }
5
Kotlin
8
75
17867a038c0002e5f80ab40b4ebc6c7e8e440572
4,133
weiV
MIT License
app/src/androidTest/kotlin/jp/co/yumemi/android/code_check/TestExtensions.kt
tshion
707,962,901
false
{"Kotlin": 86653}
package jp.co.yumemi.android.code_check import androidx.test.platform.app.InstrumentationRegistry /** * リソースID の文字列表記へ変換 * * ※参考文献: [Androidテスト全書](https://peaks.cc/books/android_testing) p. 193 */ fun Int.toName(): String = InstrumentationRegistry.getInstrumentation() .targetContext .resources .getResourceName(this)
29
Kotlin
0
0
d34bc53c0aa1eca3361953246b3ce8e7a423bc2f
337
yumemi-inc_android-engineer-codecheck
Apache License 2.0
trixnity-olm/src/jsMain/kotlin/net.folivo.trixnity.olm/Pointers.kt
benkuly
330,904,570
false
{"Kotlin": 4165934, "JavaScript": 5352, "TypeScript": 2906, "CSS": 1454, "Dockerfile": 1328}
package net.folivo.trixnity.olm actual typealias OlmAccountPointer = Account actual typealias OlmInboundGroupSessionPointer = InboundGroupSession actual typealias OlmOutboundGroupSessionPointer = OutboundGroupSession actual typealias OlmPkDecryptionPointer = PkDecryption actual typealias OlmPkEncryptionPointer = PkEncryption actual typealias OlmPkSigningPointer = PkSigning actual typealias OlmSASPointer = SAS actual typealias OlmSessionPointer = Session actual typealias OlmUtilityPointer = Utility
0
Kotlin
3
30
6dfadb2efa1843a33030fba9eb6be0bfecdfb94d
503
trixnity
Apache License 2.0
app/src/main/java/com/kaboom/kidsmathgame/GameActivity.kt
frashasantoYT
800,977,604
false
{"Kotlin": 19462}
package com.kaboom.kidsmathgame import android.annotation.SuppressLint import android.content.Intent import androidx.appcompat.app.AppCompatActivity import android.os.Bundle import android.os.CountDownTimer import android.view.View import android.widget.Button import android.widget.TextView import androidx.appcompat.app.AlertDialog import androidx.constraintlayout.widget.ConstraintLayout import java.util.Random class GameActivity : AppCompatActivity() { lateinit var actionTitle: String var startBtn: Button? = null var timeTextView: TextView? = null var scoreTextView: TextView? = null var alertTextView: TextView? = null var questionTextView: TextView? = null var finalScoreTextView: TextView? = null var button0: Button? = null var button1: Button? = null var button2: Button? = null var button3: Button? = null var countDownTimer: CountDownTimer? = null var constraintLayout: ConstraintLayout? = null var lastLayout: ConstraintLayout? = null var buttonPlayAgain: Button? = null var random = Random() var a = 0 var b = 0 var indexOfCorrectAnswer = 0 var answers = ArrayList<Int>() var points = 0 var totalQuestions = 0 private var gameInProgress = false private var gameCompleted = false override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_game) actionTitle = intent.getStringExtra("actionTitle").toString() when (actionTitle) { "addition" -> supportActionBar!!.title = "Addition" "subtraction" -> supportActionBar!!.title = "Subtraction" "multiplication" -> supportActionBar!!.title = "Multiplication" "division" -> supportActionBar!!.title = "Division" } @SuppressLint("SetTextI18n") startBtn = findViewById(R.id.btnStart) timeTextView = findViewById(R.id.TimeTextView) scoreTextView = findViewById(R.id.ScoreTextView) alertTextView = findViewById(R.id.AlertTextView) questionTextView = findViewById(R.id.QuestionTextView) button0 = findViewById(R.id.button0) button1 = findViewById(R.id.button1) button2 = findViewById(R.id.button2) button3 = findViewById(R.id.button3) constraintLayout = findViewById(R.id.quizUi) lastLayout = findViewById(R.id.lastUi) lastLayout?.visibility = View.INVISIBLE constraintLayout?.visibility = View.INVISIBLE } @SuppressLint("SetTextI18n") fun nextQuestion() { a = random.nextInt(10) b = random.nextInt(10) if (actionTitle == "addition") { questionTextView!!.text = "$a+$b" indexOfCorrectAnswer = random.nextInt(4) answers.clear() for (i in 0..3) { if (indexOfCorrectAnswer == i) { answers.add(a + b) } else { var wrongAnswer = random.nextInt(20) while (wrongAnswer == a + b) { wrongAnswer = random.nextInt(20) } answers.add(wrongAnswer) } } button0!!.text = Integer.toString(answers[0]) button1!!.text = Integer.toString(answers[1]) button2!!.text = Integer.toString(answers[2]) button3!!.text = Integer.toString(answers[3]) } else if (actionTitle == "multiplication") { questionTextView!!.text = "$a x $b" indexOfCorrectAnswer = random.nextInt(4) answers.clear() for (i in 0..3) { if (indexOfCorrectAnswer == i) { answers.add(a * b) } else { var wrongAnswer = random.nextInt(20) while (wrongAnswer == a * b) { wrongAnswer = random.nextInt(20) } answers.add(wrongAnswer) } } button0!!.text = Integer.toString(answers[0]) button1!!.text = Integer.toString(answers[1]) button2!!.text = Integer.toString(answers[2]) button3!!.text = Integer.toString(answers[3]) } else if (actionTitle == "division") { // Division-specific code for values up to 100 do { // Generate random values for a and b a = random.nextInt(101) // Up to 100 (inclusive) b = random.nextInt(10) + 1 // Non-zero divisor, up to 10 } while (a % b != 0 || a / b < 0 || a / b > 100) questionTextView!!.text = "$a / $b" indexOfCorrectAnswer = random.nextInt(4) answers.clear() for (i in 0..3) { if (indexOfCorrectAnswer == i) { answers.add(a / b) } else { var wrongAnswer: Int do { wrongAnswer = random.nextInt(101) } while (wrongAnswer == a / b) answers.add(wrongAnswer) } } button0!!.text = Integer.toString(answers[0]) button1!!.text = Integer.toString(answers[1]) button2!!.text = Integer.toString(answers[2]) button3!!.text = Integer.toString(answers[3]) } else { questionTextView!!.text = "$a - $b" indexOfCorrectAnswer = random.nextInt(4) answers.clear() for (i in 0..3) { if (indexOfCorrectAnswer == i) { answers.add(a - b) } else { // Generate a random number that is not equal to a - b var wrongAnswer = random.nextInt(40) - 20 while (wrongAnswer == a - b) { wrongAnswer = random.nextInt(40) - 20 } answers.add(wrongAnswer) } } button0!!.text = Integer.toString(answers[0]) button1!!.text = Integer.toString(answers[1]) button2!!.text = Integer.toString(answers[2]) button3!!.text = Integer.toString(answers[3]) } } fun optionSelect(view: View) { totalQuestions++ if (Integer.toString(indexOfCorrectAnswer) == view.tag.toString()) { points += 1 alertTextView!!.text = "Correct" } else { alertTextView!!.text = "Wrong" } scoreTextView!!.text = "$points/$totalQuestions" nextQuestion() } fun start(view: View?) { gameInProgress = true startBtn!!.visibility = View.INVISIBLE constraintLayout!!.visibility = View.VISIBLE nextQuestion() countDownTimer = object : CountDownTimer(30000, 1000) { override fun onTick(millisUntilFinished: Long) { timeTextView!!.text = (millisUntilFinished / 1000).toString() + "s" } override fun onFinish() { if (!isFinishing) { gameInProgress = false gameCompleted = false var score = "" score = Integer.toString(points) + "/" + Integer.toString(totalQuestions) val intent = Intent(this@GameActivity, ResultsActivity::class.java) intent.putExtra("Score", score) startActivity(intent) finish() } } }.start() } override fun onBackPressed() { if (!gameInProgress || gameCompleted) { super.onBackPressed() } else { AlertDialog.Builder(this) .setTitle("Game in Progress") .setMessage("Are you sure you want to exit the game?") .setPositiveButton("Yes") { _, _ -> super.onBackPressed() } .setNegativeButton("No", null) .show() } } }
0
Kotlin
0
1
2b350b87563147d342e7340d8b0b06ee3d303d0d
8,148
Kids-Math-Game
MIT License
android/src/main/java/com/callstack/reactnativebrownfield/ReactNativeFragment.kt
callstack
196,995,247
false
null
package com.callstack.reactnativebrownfield; import android.annotation.TargetApi import android.os.Build import android.os.Bundle import androidx.fragment.app.Fragment import android.view.KeyEvent import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import com.facebook.infer.annotation.Assertions import com.facebook.react.ReactRootView import com.facebook.react.bridge.Callback import com.facebook.react.bridge.WritableMap import com.facebook.react.common.LifecycleState import com.facebook.react.devsupport.DoubleTapReloadRecognizer import com.facebook.react.modules.core.DefaultHardwareBackBtnHandler import com.facebook.react.modules.core.PermissionAwareActivity import com.facebook.react.modules.core.PermissionListener private const val MODULE_NAME = "com.callstack.reactnativebrownfield.FRAGMENT_MODULE_NAME" private const val INITIAL_PROPS = "com.callstack.reactnativebrownfield.FRAGMENT_INITIAL_PROPS" class ReactNativeFragment : Fragment(), PermissionAwareActivity { private var reactRootView: ReactRootView? = null private lateinit var doubleTapReloadRecognizer: DoubleTapReloadRecognizer private lateinit var permissionsCallback: Callback private var permissionListener: PermissionListener? = null override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) val moduleName = arguments?.getString(MODULE_NAME)!! val initialProps = arguments?.getBundle(INITIAL_PROPS) doubleTapReloadRecognizer = DoubleTapReloadRecognizer() reactRootView = ReactRootView(context) reactRootView?.startReactApplication( ReactNativeBrownfield.shared.reactNativeHost.reactInstanceManager, moduleName, initialProps ) } override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View { return reactRootView!! } override fun onResume() { super.onResume() if (ReactNativeBrownfield.shared.reactNativeHost.hasInstance()) { ReactNativeBrownfield.shared.reactNativeHost.reactInstanceManager?.onHostResume( activity, activity as DefaultHardwareBackBtnHandler ) } } override fun onPause() { super.onPause() if (ReactNativeBrownfield.shared.reactNativeHost.hasInstance()) { ReactNativeBrownfield.shared.reactNativeHost.reactInstanceManager?.onHostPause( activity ) } } override fun onDestroy() { super.onDestroy() reactRootView?.unmountReactApplication() reactRootView = null if (ReactNativeBrownfield.shared.reactNativeHost.hasInstance()) { val reactInstanceMgr = ReactNativeBrownfield.shared.reactNativeHost.reactInstanceManager if (reactInstanceMgr.lifecycleState != LifecycleState.RESUMED) { reactInstanceMgr.onHostDestroy(activity) } } } override fun onRequestPermissionsResult( requestCode: Int, permissions: Array<String>, grantResults: IntArray ) { permissionsCallback = Callback { if (permissionListener != null) { permissionListener?.onRequestPermissionsResult( requestCode, permissions, grantResults ) permissionListener = null } } } override fun checkPermission(permission: String, pid: Int, uid: Int): Int { return requireActivity().checkPermission(permission, pid, uid) } @TargetApi(Build.VERSION_CODES.M) override fun checkSelfPermission(permission: String): Int { return requireActivity().checkSelfPermission(permission) } @TargetApi(Build.VERSION_CODES.M) override fun requestPermissions( permissions: Array<String>, requestCode: Int, listener: PermissionListener ) { permissionListener = listener this.requestPermissions(permissions, requestCode) } fun onKeyUp(keyCode: Int, event: KeyEvent): Boolean { var handled = false if (ReactNativeBrownfield.shared.reactNativeHost.useDeveloperSupport && ReactNativeBrownfield.shared.reactNativeHost.hasInstance()) { if (keyCode == KeyEvent.KEYCODE_MENU) { ReactNativeBrownfield.shared.reactNativeHost.reactInstanceManager.showDevOptionsDialog() handled = true } val didDoubleTapR = activity?.currentFocus?.let { Assertions.assertNotNull(doubleTapReloadRecognizer) .didDoubleTapR(keyCode, it) } if (didDoubleTapR == true) { ReactNativeBrownfield.shared.reactNativeHost.reactInstanceManager.devSupportManager.handleReloadJS() handled = true } } return handled } fun onBackPressed(backBtnHandler: DefaultHardwareBackBtnHandler) { if(ReactNativeBrownfieldModule.shouldPopToNative) { backBtnHandler.invokeDefaultOnBackPressed() } else if (ReactNativeBrownfield.shared.reactNativeHost.hasInstance()) { ReactNativeBrownfield.shared.reactNativeHost.reactInstanceManager.onBackPressed() } } companion object { @JvmStatic @JvmOverloads fun createReactNativeFragment(moduleName: String, initialProps: Bundle? = null): ReactNativeFragment { val fragment = ReactNativeFragment() val args = Bundle() args.putString(MODULE_NAME, moduleName) if (initialProps != null) { args.putBundle(INITIAL_PROPS, initialProps) } fragment.arguments = args return fragment } @JvmStatic fun createReactNativeFragment(moduleName: String, initialProps: HashMap<String, *>): ReactNativeFragment { return createReactNativeFragment(moduleName, PropsBundle.fromHashMap(initialProps)) } @JvmStatic fun createReactNativeFragment(moduleName: String, initialProps: WritableMap): ReactNativeFragment { return createReactNativeFragment(moduleName, initialProps.toHashMap()) } } }
31
null
16
238
bf5312d853bb97968436e34bbe7df3d64efb224a
6,387
react-native-brownfield
MIT License
feature/player/src/main/kotlin/com/flammky/musicplayer/player/presentation/presenter/PlaybackObserver.kt
flammky
462,795,948
false
null
package com.flammky.musicplayer.player.presentation.presenter import com.flammky.musicplayer.base.media.playback.OldPlaybackQueue import com.flammky.musicplayer.base.media.playback.PlaybackProperties import kotlinx.coroutines.Job import kotlinx.coroutines.flow.StateFlow import kotlin.coroutines.CoroutineContext import kotlin.coroutines.EmptyCoroutineContext import kotlin.time.Duration interface PlaybackObserver { val disposed: Boolean fun createDurationCollector( collectorContext: CoroutineContext = EmptyCoroutineContext, ): DurationCollector fun createProgressionCollector( collectorContext: CoroutineContext = EmptyCoroutineContext, includeEvent: Boolean = true ): ProgressionCollector fun createQueueCollector( collectorContext: CoroutineContext = EmptyCoroutineContext, ): QueueCollector fun createPropertiesCollector( collectorContext: CoroutineContext = EmptyCoroutineContext ): PropertiesCollector /** * Dispose the observer, any ongoing job will be cancelled, and no more emission is possible */ fun dispose() sealed interface Collector { val disposed: Boolean fun dispose() } interface ProgressionCollector : Collector { val positionStateFlow: StateFlow<Duration> val bufferedPositionStateFlow: StateFlow<Duration> /** * Start the progress collector * * @return await-able Deferred of initialization value, `StateFlow's` above is guaranteed to be a * valid known value */ fun startCollectPosition(): Job fun stopCollectProgress(): Job /** * set The IntervalHandler, will cancel current IntervalHandler and [handler] will be called * immediately and then on every elapsed delay. * ** Note: CoroutineContext of `handler` is the internal event loop ** * * @param handler the handler lambda, return positive value for a valid delay, negative value to * skip collection until next event, `null` for `next-second` interval * * ** Note: Due to nature of `MediaController.position` the interval might not be accurate by * about 10ms, may be both early or late, this is on fix list, which we might just not use it ** */ fun setIntervalHandler( handler: suspend ( isEvent: Boolean, progress: Duration, duration: Duration, speed: Float ) -> Duration? ) /** * whether to also include `progress` affecting event */ fun setCollectEvent( collectEvent: Boolean /* Array<Event> ? */ ): Job /** * Dispose the collector, supervisor Job will be cancelled */ override fun dispose() } interface DurationCollector : Collector { val durationStateFlow: StateFlow<Duration> fun startCollect(): Job fun stopCollect(): Job } interface QueueCollector : Collector { /** * The current PlaybackQueue, * [OldPlaybackQueue.UNSET] if invalid */ val queueStateFlow: StateFlow<OldPlaybackQueue> /** * start observing * @return the launching Job, normal completion denoting that the request has been completed */ fun startCollect(): Job fun stopCollect(): Job } interface PropertiesCollector : Collector { val propertiesStateFlow: StateFlow<PlaybackProperties> fun startCollect(): Job fun stopCollect(): Job } }
0
null
6
56
2b8b4affab4306e351cfc8721c15a5bc7ecba908
3,198
Music-Player
Apache License 2.0
sample-simple-app-without-plugins/src/test/kotlin/com/damianchodorek/sample_simple_app_without_plugins/controller/interactor/MakeApiCallInteractorImplTest.kt
DamianChodorek
129,797,476
false
null
package com.damianchodorek.sample_simple_app_without_plugins.controller.interactor import com.damianchodorek.sample_simple_app_without_plugins.utils.RxTestRule import io.reactivex.schedulers.TestScheduler import org.junit.Rule import org.junit.Test import java.util.concurrent.TimeUnit /** * @author <NAME> */ class MakeApiCallInteractorImplTest { @Suppress("unused") @get:Rule val rxRule = RxTestRule() private val testScheduler = TestScheduler() private val interactor = MakeApiCallInteractorImpl(testScheduler) private val callDuration = 4L @Test fun makeApiCall_waitsProperTimeAndCompletes() { val testObserver = interactor.makeFakeApiCall().test() testScheduler.advanceTimeBy(callDuration, TimeUnit.SECONDS) testObserver.assertComplete() } @Test fun makeApiCall_doesNotComplete_whenProperTimeNotPassed() { val testObserver = interactor.makeFakeApiCall().test() testScheduler.advanceTimeBy(callDuration - 1, TimeUnit.SECONDS) testObserver .assertNotComplete() .assertNoErrors() } }
0
Kotlin
0
2
c72df09782cdb9483bbde3503a167f2d5bc760b4
1,124
renshi-redux
Apache License 2.0
MLKitCustom/app/src/main/java/com/google/mlkit/vision/demo/EntryChoiceActivity.kt
Rishit-dagli
284,226,663
false
null
/* * Copyright 2020 Google LLC. 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.google.mlkit.vision.demo import android.content.Intent import android.os.Bundle import androidx.appcompat.app.AppCompatActivity import android.widget.TextView import com.google.mlkit.vision.demo.java.ChooserActivity class EntryChoiceActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_vision_entry_choice) findViewById<TextView>(R.id.java_entry_point).setOnClickListener { val intent = Intent(this@EntryChoiceActivity, ChooserActivity::class.java) startActivity(intent) } // findViewById<TextView>(R.id.kotlin_entry_point).setOnClickListener { // val intent = // Intent( // this@EntryChoiceActivity, // com.google.mlkit.vision.demo.kotlin.ChooserActivity::class.java // ) // startActivity(intent) // } } }
54
null
5
73
2d25277dd1cdad4758cda70a96ccd3621088a997
1,522
ML-with-Android-11
Apache License 2.0
app/src/main/java/com/forecaster/weatherlens/data/Forecast.kt
raghulk
409,059,304
false
null
package com.forecaster.weatherlens.data import com.squareup.moshi.Json data class Forecast( val lat: Double?, val lon: Double?, val timezone: String?, @Json(name = "timezone_offset") val timezoneOffset: Int?, var daily: List<DailyForecast>?, ) { data class DailyForecast( val dt: Long?, val sunrise: Long?, val sunset: Long?, val moonrise: Long?, @Json(name = "moonset") val moonSet: Long?, @Json(name = "moon_phase") val moonPhase: Double?, val temp: Temperature?, @Json(name = "feels_like") val feelsLike: FeelsLike?, val pressure: Int?, val humidity: Int?, @Json(name = "dew_point") val dewPoint: Double?, @Json(name = "wind_speed") val windSpeed: Double?, @Json(name = "wind_deg") val windDeg: Int?, @Json(name = "wind_gust") val windGust: Double?, val weather: List<Weather>?, val clouds: Int?, val pop: Double?, val rain: Double?, val uvi: Double?, ) { data class Temperature( val day: Double?, val night: Double?, val eve: Double?, val morn: Double?, val min: Double?, val max: Double?, ) data class FeelsLike( val day: Double?, val night: Double?, val eve: Double?, val morn: Double?, ) data class Weather( val id: Int?, val main: String?, val description: String?, val icon: String?, ) } }
0
Kotlin
0
0
b3155011347e1e5b14f5b094e0a670b65d1bb38c
1,662
WeatherLens
MIT License
cams/src/main/java/com/linwei/cams/base/activity/IActivity.kt
WeiShuaiDev
390,686,269
false
null
package com.linwei.cams.base.activity import android.app.Activity import com.linwei.cams.di.component.AppComponent import com.linwei.cams.http.cache.Cache /** * --------------------------------------------------------------------- * @Author: WeiShuai * @Time: 2020/5/22 * @Contact: <EMAIL>" * @Follow: https://github.com/WeiShuaiDev * @Description: [Activity] 基类接口 *----------------------------------------------------------------------- */ interface IActivity { /** * 提供在 {@link Activity} 生命周期内的缓存容器, * 可向此 {@link Activity} 存取一些必要的数据 * @return [Cache] */ fun provideCache(): Cache<String, Any> /** * 提供给 {@link IActivity}实现类,进行{@code appComponent}依赖 * AppComponent主要提供一些单例工具 *@param appComponent [AppComponent] */ fun setUpActivityComponent(appComponent: AppComponent?){} /** * 当前Activity对象增加到内存栈,方便管理 * @param activity [Activity] */ fun addStackSingleActivity(activity: Activity?) /** * 删除内存栈中当前Activity对象 * @param activity [Activity] */ fun removeStackSingleActivity(activity: Activity?) /** * 是否使用事件总线,默认{@link Boolean}是false,内部提供RxBus、EventBus,Otto事件总线,根据Maven地址动态切换。 * 如果需要用RxBus,EventBus,Otto库,需要在项目app build.gradle的dependencies手动增加Maven地址, * 不使用就不要引入进来,减少包体积。 * @return [Boolean] true:使用;false:不使用 */ fun useEventBus(): Boolean = false /** * 是否使用Fragment,默认 [useFragment] 是false * @return [Boolean] true:使用;false:不使用 */ fun useFragment(): Boolean = false }
1
Kotlin
1
1
3c7289aae35551ee53284d91e96ad5f24c21eb50
1,542
Cams
Apache License 2.0
app/src/main/java/com/example/gamebuddy/presentation/auth/verify/VerifyState.kt
GameBuddyDevs
609,491,782
false
null
package com.example.gamebuddy.presentation.auth.verify import com.example.gamebuddy.util.Queue import com.example.gamebuddy.util.StateMessage data class VerifyState( val isLoading: Boolean = false, val verificationCode: String = "", val isVerifyCompleted: Boolean = false, val queue: Queue<StateMessage> = Queue(mutableListOf()), )
0
Kotlin
1
3
0a767229f5505e6a68e167aece41c10abb282e1b
350
GameBuddy-Android
MIT License
app/src/main/java/com/example/gamebuddy/presentation/auth/verify/VerifyState.kt
GameBuddyDevs
609,491,782
false
null
package com.example.gamebuddy.presentation.auth.verify import com.example.gamebuddy.util.Queue import com.example.gamebuddy.util.StateMessage data class VerifyState( val isLoading: Boolean = false, val verificationCode: String = "", val isVerifyCompleted: Boolean = false, val queue: Queue<StateMessage> = Queue(mutableListOf()), )
0
Kotlin
1
3
0a767229f5505e6a68e167aece41c10abb282e1b
350
GameBuddy-Android
MIT License
app/src/main/kotlin/com/cloverlab/kloveroid/repository/repositories/source/LocalDataStore.kt
dev-cloverlab
104,434,875
false
null
package com.cloverlab.kloveroid.repository.repositories.source import com.cloverlab.kloveroid.entities.FakeEntity import com.cloverlab.kloveroid.repository.repositories.IDataStore import io.reactivex.Observable /** * @author <NAME> * @since 2017/09/25 */ class LocalDataStore : IDataStore { override fun createEntity(entity: FakeEntity): Observable<FakeEntity> { TODO("not yet") } }
0
Kotlin
1
7
f558c5de219c2b5d9b015627c824997ce6c9a3c1
407
Kloveroid
MIT License
sample-library-1/src/main/java/com/bennyhuo/kotlin/mixin/sample/library1/Api1.kt
bennyhuo
426,646,493
false
null
package com.bennyhuo.kotlin.mixin.sample.library1 import com.bennyhuo.kotlin.mixin.annotations.Mixin /** * Created by benny. */ @Mixin("com.bennyhuo.kotlin.mixin.sample", "Apis") class Api1 { val url1 = "https://www.api1.com" fun getObject1(key: String): Any { return "" } fun getObjects1(keys: Array<String>): List<Any> { return emptyList() } fun save() { } fun save(key: String, value: String) { } fun save(key: String, value: Any?) { } }
0
Kotlin
0
27
61c9d5678865a309b35b10fbdade02d53b54b6ac
549
Mixin
MIT License
subprojects/kotlin-dsl/src/main/kotlin/org/gradle/kotlin/dsl/TaskContainerExtensions.kt
Verdinjoshua26
187,253,049
false
null
/* * Copyright 2018 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.gradle.kotlin.dsl import org.gradle.api.Task import org.gradle.api.tasks.TaskCollection import org.gradle.api.tasks.TaskContainer import org.gradle.api.tasks.TaskProvider import org.gradle.kotlin.dsl.support.delegates.TaskContainerDelegate import kotlin.reflect.KClass import kotlin.reflect.KProperty /** * Allows a [TaskContainer] to be configured via an augmented DSL that includes * a shorthand string notation for configuring existing tasks. * * ```kotlin * tasks { * "build" { * dependsOn("clean") * } * "clean"(Delete::class) { * delete("./build") * } * } * ``` * * @param configuration The expression to configure this [TaskContainer] with. * @return The given [TaskContainer]. */ inline operator fun TaskContainer.invoke( configuration: TaskContainerScope.() -> Unit ): TaskContainer = apply { configuration(TaskContainerScope.of(this)) } /** * Provides a [TaskProvider] delegate for the task named after the property. */ operator fun ExistingDomainObjectDelegateProvider<out TaskContainer>.provideDelegate( receiver: Any?, property: KProperty<*> ) = ExistingDomainObjectDelegate.of( delegateProvider.named(property.name) ) /** * Provides a [TaskProvider] delegate for the task named after the property after configuring it with the given action. */ operator fun ExistingDomainObjectDelegateProviderWithAction<out TaskContainer, Task>.provideDelegate( receiver: Any?, property: KProperty<*> ) = ExistingDomainObjectDelegate.of( delegateProvider.named(property.name).apply { configure(action) } ) /** * Provides a [TaskProvider] delegate for the task of the given type named after the property. */ operator fun <U : Task> ExistingDomainObjectDelegateProviderWithType<out TaskContainer, U>.provideDelegate( receiver: Any?, property: KProperty<*> ) = ExistingDomainObjectDelegate.of( delegateProvider.named(property.name, type) ) /** * Provides a [TaskProvider] delegate for the task of the given type named after the property after configuring it with the given action. */ operator fun <U : Task> ExistingDomainObjectDelegateProviderWithTypeAndAction<out TaskContainer, U>.provideDelegate( receiver: Any?, property: KProperty<*> ) = ExistingDomainObjectDelegate.of( delegateProvider.named(property.name, type).apply { configure(action) } ) /** * Registers a task and provides a delegate with the resulting [TaskProvider]. */ operator fun RegisteringDomainObjectDelegateProvider<out TaskContainer>.provideDelegate( receiver: Any?, property: KProperty<*> ) = ExistingDomainObjectDelegate.of( delegateProvider.register(property.name) ) /** * Registers a task that gets configured with the given action and provides a delegate with the resulting [TaskProvider]. */ operator fun RegisteringDomainObjectDelegateProviderWithAction<out TaskContainer, Task>.provideDelegate( receiver: Any?, property: KProperty<*> ) = ExistingDomainObjectDelegate.of( delegateProvider.register(property.name, action) ) /** * Registers a task of the given type and provides a delegate with the resulting [TaskProvider]. */ operator fun <U : Task> RegisteringDomainObjectDelegateProviderWithType<out TaskContainer, U>.provideDelegate( receiver: Any?, property: KProperty<*> ) = ExistingDomainObjectDelegate.of( delegateProvider.register(property.name, type.java) ) /** * Registers a task of the given type that gets configured with the given action and provides a delegate with the resulting [TaskProvider]. */ operator fun <U : Task> RegisteringDomainObjectDelegateProviderWithTypeAndAction<out TaskContainer, U>.provideDelegate( receiver: Any?, property: KProperty<*> ) = ExistingDomainObjectDelegate.of( delegateProvider.register(property.name, type.java, action) ) /** * Receiver for the `tasks` block providing an extended set of operators for the configuration of tasks. */ class TaskContainerScope private constructor( val container: TaskContainer ) : TaskContainerDelegate() { companion object { fun of(container: TaskContainer) = TaskContainerScope(container) } override val delegate: TaskContainer get() = container /** * Configures a task by name, without triggering its creation or configuration, failing if there is no such task. * * @see [TaskContainer.named] * @see [TaskProvider.configure] */ operator fun String.invoke(configuration: Task.() -> Unit): TaskProvider<Task> = this().apply { configure(configuration) } /** * Locates a task by name, without triggering its creation or configuration, failing if there is no such task. * * @see [TaskContainer.named] */ operator fun String.invoke(): TaskProvider<Task> = container.named(this) /** * Configures a task by name, without triggering its creation or configuration, failing if there is no such task. * * @see [TaskContainer.named] * @see [TaskProvider.configure] */ operator fun <U : Task> String.invoke(type: KClass<U>, configuration: U.() -> Unit): TaskProvider<U> = container.named(this, type, configuration) /** * Locates a task by name and type, without triggering its creation or configuration, failing if there is no such task. * * @see [TaskContainer.named] */ operator fun <U : Task> String.invoke(type: KClass<U>): TaskProvider<U> = container.named(this, type) } /** * Locates a task by name and type, without triggering its creation or configuration, failing if there is no such task. * * @see [TaskCollection.named] */ @Suppress("extension_shadowed_by_member") inline fun <reified T : Task> TaskCollection<out Task>.named(name: String): TaskProvider<T> = named(name, T::class) /** * Locates a task by name and type, without triggering its creation or configuration, failing if there is no such task. * * @see [TaskCollection.named] */ @Suppress("unchecked_cast") fun <T : Task> TaskCollection<out Task>.named(name: String, type: KClass<T>): TaskProvider<T> = (this as TaskCollection<T>).named(name, type.java) /** * Configures a task by name and type, without triggering its creation or configuration, failing if there is no such task. * * @see [TaskCollection.named] * @see [TaskProvider.configure] */ @Suppress("unchecked_cast") fun <T : Task> TaskCollection<out Task>.named(name: String, type: KClass<T>, configuration: T.() -> Unit): TaskProvider<T> = (this as TaskCollection<T>).named(name, type.java, configuration) /** * Configures a task by name and type, without triggering its creation or configuration, failing if there is no such task. * * @see [TaskCollection.named] * @see [TaskProvider.configure] */ @Suppress("unchecked_cast") inline fun <reified T : Task> TaskCollection<out Task>.named(name: String, noinline configuration: T.() -> Unit): TaskProvider<T> = (this as TaskCollection<T>).named(name, T::class.java, configuration) /** * Defines a new task, which will be created when it is required. * * @see [TaskContainer.register] */ @Suppress("extension_shadowed_by_member") inline fun <reified T : Task> TaskContainer.register(name: String): TaskProvider<T> = register(name, T::class.java) /** * Defines and configure a new task, which will be created when it is required. * * @see [TaskContainer.register] */ inline fun <reified T : Task> TaskContainer.register(name: String, noinline configuration: T.() -> Unit): TaskProvider<T> = register(name, T::class.java, configuration) /** * Defines a new task, which will be created when it is required passing the given arguments to the [javax.inject.Inject]-annotated constructor. * * @see [TaskContainer.register] */ inline fun <reified T : Task> TaskContainer.register(name: String, vararg arguments: Any): TaskProvider<T> = register(name, T::class.java, *arguments) /** * Creates a [Task] with the given [name] and type, passing the given arguments to the [javax.inject.Inject]-annotated constructor, * and adds it to this project tasks container. */ inline fun <reified T : Task> TaskContainer.create(name: String, vararg arguments: Any): T = create(name, T::class.java, *arguments)
10
null
1
2
cfeeb71d1e3159f5d10856aef854344ba92c4a0f
8,932
gradle
Apache License 2.0
features/feature_search_photo_shared/src/commonMain/kotlin/com/hoc081098/compose_multiplatform_kmpviewmodel_sample/search_photo/presentation/components/PhotoGridCell.kt
hoc081098
675,918,221
false
null
package com.hoc081098.compose_multiplatform_kmpviewmodel_sample.search_photo.presentation.components import androidx.compose.animation.core.tween import androidx.compose.foundation.clickable import androidx.compose.foundation.layout.Box import androidx.compose.material.icons.Icons import androidx.compose.material.icons.filled.Info import androidx.compose.material3.Icon import androidx.compose.runtime.Composable import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.layout.ContentScale import com.hoc081098.compose_multiplatform_kmpviewmodel_sample.common_ui.components.LoadingIndicator import com.hoc081098.compose_multiplatform_kmpviewmodel_sample.search_photo.presentation.SearchPhotoUiState.PhotoUiItem import io.kamel.image.KamelImage import io.kamel.image.asyncPainterResource @Composable internal fun PhotoGridCell( photo: PhotoUiItem, onClick: () -> Unit, modifier: Modifier = Modifier, ) { Box( modifier = modifier .clickable(onClick = onClick), ) { KamelImage( modifier = Modifier.matchParentSize(), resource = asyncPainterResource(data = photo.thumbnailUrl), contentDescription = null, contentScale = ContentScale.Crop, animationSpec = tween(), onLoading = { LoadingIndicator( modifier = Modifier.matchParentSize(), ) }, onFailure = { Icon( modifier = Modifier.align(Alignment.Center), imageVector = Icons.Default.Info, contentDescription = null, ) }, ) } }
12
null
4
8
b5ab12979e96f40ade3b64324e3f8f9f18ea806a
1,576
Compose-Multiplatform-KmpViewModel-Unsplash-Sample
Apache License 2.0
platform/platform-impl/src/com/intellij/openapi/wm/impl/customFrameDecorations/style/ComponentStyle.kt
ingokegel
284,920,751
false
null
// Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.openapi.wm.impl.customFrameDecorations.style import org.jetbrains.annotations.NonNls import java.awt.MouseInfo import java.awt.event.MouseAdapter import java.awt.event.MouseEvent import java.awt.event.MouseListener import java.beans.PropertyChangeEvent import java.beans.PropertyChangeListener import javax.swing.JComponent import javax.swing.SwingUtilities class ComponentStyle<T : JComponent>private constructor(private val default: Properties, private val styleMap: Map<ComponentStyleState, Properties>) { companion object { @NonNls const val ENABLED_PROPERTY: String = "enabled" } internal fun applyStyle(component: T) { val base = StyleProperty.getPropertiesSnapshot(component) val componentState = ComponentState(base).apply { hovered = isMouseOver(component) pressed = false } val styleListener = StyleComponentListener(component, this, componentState) component.addPropertyChangeListener(ENABLED_PROPERTY, styleListener) checkState(component, componentState, styleListener) } private fun isMouseOver(component: T): Boolean { val location = MouseInfo.getPointerInfo()?.location if (location != null) { SwingUtilities.convertPointFromScreen(location, component) return component.contains(location) } return false } fun updateStyle(component: T, componentState: ComponentState) { val properties = componentState.base.clone() properties.updateBy(default) if (!component.isEnabled) { if (ComponentStyleState.DISABLED in styleMap) properties.updateBy(styleMap[ComponentStyleState.DISABLED]!!) properties.applyTo(component) return } if (componentState.hovered && ComponentStyleState.HOVERED in styleMap) properties.updateBy(styleMap[ComponentStyleState.HOVERED]!!) if (componentState.pressed && ComponentStyleState.PRESSED in styleMap) properties.updateBy(styleMap[ComponentStyleState.PRESSED]!!) properties.applyTo(component) } private fun checkState(component: T, componentState: ComponentState, mouseListener: MouseListener) { if (component.isEnabled) { if (ComponentStyleState.HOVERED in styleMap || ComponentStyleState.PRESSED in styleMap) { componentState.hovered = isMouseOver(component) componentState.pressed = false if (mouseListener !in component.mouseListeners) component.addMouseListener(mouseListener) } } else { component.removeMouseListener(mouseListener) } updateStyle(component, componentState) } class ComponentStyleBuilder<T : JComponent>(val default: Properties) { constructor(init: Properties.() -> Unit) : this(Properties().apply { init() }) private val styleMap: HashMap<ComponentStyleState, Properties> = HashMap() fun style(state: ComponentStyleState, init: Properties.() -> Unit): ComponentStyleBuilder<T> { val prop = Properties() prop.init() styleMap[state] = prop return this } fun updateDefault(init: Properties.() -> Unit): ComponentStyleBuilder<T> { val prop = Properties() prop.init() default.updateBy(prop) return this } fun updateState(state: ComponentStyleState, init: Properties.() -> Unit): ComponentStyleBuilder<T> { val prop = Properties() prop.init() styleMap[state]?.updateBy(prop) if (styleMap[state] == null) { styleMap[state] = prop } return this } fun clone(): ComponentStyleBuilder<T> { val csb = ComponentStyleBuilder<T>(default.clone()) for ((k, v) in styleMap) { csb.styleMap[k] = v.clone() } return csb } fun build(): ComponentStyle<T> { return ComponentStyle(default.clone(), styleMap.mapValues { it.value.clone()}) } } class ComponentState(val base: Properties) { var hovered: Boolean = false var pressed: Boolean = false } class StyleComponentListener<T : JComponent>(val component: T, val style: ComponentStyle<T>, private val componentState: ComponentState) : PropertyChangeListener, MouseAdapter() { override fun mouseReleased(e: MouseEvent) { componentState.pressed = false updateStyle() } override fun mouseEntered(e: MouseEvent) { componentState.hovered = true updateStyle() } override fun mouseExited(e: MouseEvent) { componentState.hovered = false updateStyle() } override fun mousePressed(e: MouseEvent) { componentState.pressed = true updateStyle() } private fun updateStyle() { style.updateStyle(component, componentState) } override fun propertyChange(evt: PropertyChangeEvent?) { style.checkState(component, componentState, this) } fun destroy() { component.removePropertyChangeListener(this) component.removeMouseListener(this) componentState.base.applyTo(component) } } } enum class ComponentStyleState { HOVERED, PRESSED, DISABLED }
251
null
5079
2
dc846ecb926c9d9589c1ed8a40fdb20e47874db9
5,231
intellij-community
Apache License 2.0
app/src/main/java/com/muratozturk/mova/data/paging_source/MoviePagingSource.kt
muratozturk5
587,507,400
false
null
package com.hoangtien2k3.themoviedb.data.paging_source import androidx.paging.PagingSource import androidx.paging.PagingState import com.hoangtien2k3.themoviedb.common.Constants.STARTING_PAGE import com.hoangtien2k3.themoviedb.common.MovieRequestOptionsMapper import com.hoangtien2k3.themoviedb.common.enums.MovieEnum import com.hoangtien2k3.themoviedb.data.model.FilterResult import com.hoangtien2k3.themoviedb.data.model.remote.movies.Movie import com.hoangtien2k3.themoviedb.data.source.remote.MovaService import okio.IOException import retrofit2.HttpException class MoviePagingSource( private val movieService: MovaService, private val movieEnum: MovieEnum, private val searchQuery: String = "", movieRequestOptionsMapper: MovieRequestOptionsMapper, filterResult: FilterResult? = null, private val includeAdult: Boolean = false, private val movieId: Int = 0 ) : PagingSource<Int, Movie>() { private val options = movieRequestOptionsMapper.map(filterResult) override fun getRefreshKey(state: PagingState<Int, Movie>): Int? { return state.anchorPosition?.let { anchorPosition -> state.closestPageToPosition(anchorPosition)?.prevKey?.plus(1) ?: state.closestPageToPosition(anchorPosition)?.nextKey?.minus(1) } } override suspend fun load(params: LoadParams<Int>): LoadResult<Int, Movie> { val page = params.key ?: STARTING_PAGE return try { val response = when (movieEnum) { MovieEnum.DISCOVER_MOVIES -> { movieService.getDiscoverMovies( page = page, options = options ) } MovieEnum.NOW_PLAYING_MOVIES -> { movieService.getNowPlayingMovies(page = page) } MovieEnum.SEARCH_MOVIES -> { movieService.getSearchMovie( page = page, query = searchQuery, includeAdult = includeAdult ) } MovieEnum.SIMILAR_MOVIES -> { movieService.getSimilarMovies( page = page, movieId = movieId ) } } LoadResult.Page( data = response.results, prevKey = if (page == STARTING_PAGE) null else page.minus(1), nextKey = if (response.results.isEmpty()) null else page.plus(1) ) } catch (e: IOException) { LoadResult.Error(throwable = e) } catch (e: HttpException) { LoadResult.Error(throwable = e) } } }
1
Kotlin
13
96
280ced4d70d4e2f9e7c4549b5c919cc7cd821146
2,878
Mova
MIT License
src/main/kotlin/org/rust/cargo/icons/CargoIconProvider.kt
torkleyy
83,174,689
true
{"Kotlin": 1201029, "Rust": 74760, "Lex": 19046, "HTML": 8877, "Java": 586, "Shell": 523, "RenderScript": 15}
package org.rust.cargo.icons import com.intellij.ide.IconProvider import com.intellij.psi.PsiElement import com.intellij.psi.PsiFile import org.rust.cargo.CargoConstants import javax.swing.Icon public class CargoIconProvider : IconProvider() { override fun getIcon(element: PsiElement, flags: Int): Icon? { return when (element) { is PsiFile -> getFileIcon(element) else -> null } } fun getFileIcon(element: PsiFile): Icon? { return when (element.name) { CargoConstants.MANIFEST_FILE -> CargoIcons.ICON CargoConstants.LOCK_FILE -> CargoIcons.LOCK_ICON else -> null } } }
1
Kotlin
1
1
59a8df2b0a66018aea92c9454493a94bceea8f9a
717
intellij-rust
MIT License
app/src/main/java/com/halilkrkn/finderecipe/feature/presentation/onboarding/OnboardingViewModel.kt
halilkrkn
808,027,185
false
{"Kotlin": 324108}
package com.halilkrkn.finderecipe.feature.presentation.onboarding import androidx.lifecycle.ViewModel import androidx.lifecycle.viewModelScope import com.halilkrkn.finderecipe.domain.usecase.onboarding.FindeRecipeOnBoardingUseCase import dagger.hilt.android.lifecycle.HiltViewModel import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.launch import javax.inject.Inject @HiltViewModel class OnboardingViewModel @Inject constructor( private val onBoardingUseCase: FindeRecipeOnBoardingUseCase, ) : ViewModel() { fun saveOnBoardingState(completed: Boolean) { viewModelScope.launch(Dispatchers.IO) { onBoardingUseCase.saveOnBoardingState(completed) } } }
0
Kotlin
0
0
2a22bbe8c63b42cd5ae614227fa0a9b6e8746913
704
FindeRecipe
MIT License
token-client-spring/src/test/kotlin/no/nav/security/token/support/client/spring/oauth2/OAuth2ClientConfigurationWithoutCacheTest.kt
navikt
124,397,000
false
{"Kotlin": 362723}
package no.nav.security.token.support.client.spring.oauth2 import org.assertj.core.api.Assertions.assertThat import org.junit.jupiter.api.Test import org.springframework.beans.factory.annotation.Autowired import org.springframework.boot.test.context.SpringBootTest import org.springframework.boot.test.mock.mockito.MockBean import org.springframework.context.annotation.Configuration import org.springframework.test.context.ActiveProfiles import no.nav.security.token.support.client.core.oauth2.OAuth2AccessTokenService import no.nav.security.token.support.core.context.TokenValidationContextHolder @SpringBootTest(classes = [ConfigurationWithCacheEnabledFalse::class]) @ActiveProfiles("test") internal class OAuth2ClientConfigurationWithoutCacheTest { @MockBean private val tokenValidationContextHolder: TokenValidationContextHolder? = null @Autowired private lateinit var oAuth2AccessTokenService: OAuth2AccessTokenService @Test fun oAuth2AccessTokenServiceCreatedWithoutCache() { assertThat(oAuth2AccessTokenService).isNotNull assertThat(oAuth2AccessTokenService.clientCredentialsGrantCache).isNull() assertThat(oAuth2AccessTokenService.onBehalfOfGrantCache).isNull() assertThat(oAuth2AccessTokenService.exchangeGrantCache).isNull() } } @Configuration @EnableOAuth2Client internal class ConfigurationWithCacheEnabledFalse
8
Kotlin
7
15
2bdb7c2938c01184e714dd917f538c7ef7fe86af
1,389
token-support
MIT License
z2-material-cookbook/src/jsMain/kotlin/main.kt
spxbhuhb
661,566,882
false
null
/* * Copyright © 2020-2023, Simplexion, Hungary and contributors. Use of this source code is governed by the Apache 2.0 license. */ import hu.simplexion.z2.browser.css.* import hu.simplexion.z2.browser.demo.calendar.calendarDemo import hu.simplexion.z2.browser.demo.layout.containerDemo import hu.simplexion.z2.browser.demo.material.* import hu.simplexion.z2.browser.demo.pages.administration.administrationRouter import hu.simplexion.z2.browser.demo.pages.loginDemo import hu.simplexion.z2.browser.demo.pages.loginStrings import hu.simplexion.z2.browser.demo.routing.routingRouter import hu.simplexion.z2.browser.demo.strings import hu.simplexion.z2.browser.demo.table.tableDemo import hu.simplexion.z2.browser.html.* import hu.simplexion.z2.browser.layout.Content import hu.simplexion.z2.browser.material.basicIcons import hu.simplexion.z2.browser.material.basicStrings import hu.simplexion.z2.browser.material.button.iconButton import hu.simplexion.z2.browser.material.button.outlinedIconButton import hu.simplexion.z2.browser.material.navigation.navigationDrawer import hu.simplexion.z2.browser.material.px import hu.simplexion.z2.browser.material.searchbar.searchBar import hu.simplexion.z2.browser.routing.BrowserRouter import hu.simplexion.z2.browser.routing.NavRouter import hu.simplexion.z2.browser.routing.Router import hu.simplexion.z2.browser.routing.traceRouting fun main() { traceRouting = true customizeStyles() Content.defaultLayout = { router, nav, content -> defaultLayout(router, nav, content) } mainRouter.receiver = Content mainRouter.start() } @Suppress("unused") object mainRouter : BrowserRouter() { override val label = strings.main // @formatter:off val components by componentRouter val pages by pagesRouter val other by otherRouter // @formatter:on override fun default(receiver: Z2, path: List<String>) { receiver.defaultLayout(this, { navigationDrawer(targets) }) { div { } } } override fun notFound(receiver: Z2, path: List<String>) { default(receiver, path) } } @Suppress("unused") object componentRouter : NavRouter() { override val label = strings.components // @formatter:off val button by render(strings.button) { buttonDemo() } val calendar by render(strings.calendar) { calendarDemo() } val card by render(strings.card) { cardDemo() } val container by render(strings.container) { containerDemo() } val menu by render(strings.menu) { menuDemo() } val modal by render(strings.modal) { modalDemo() } val navigationDrawer by render(strings.navigationDrawer) { navigationDrawerDemo() } val popup by render(strings.popup) { popupDemo() } val snackbar by render(strings.snackbar) { snackbarDemo() } val switch by render(strings.switch) { switchDemo() } val textField by render(strings.textField) { textFieldDemo() } val table by render(strings.table) { tableDemo() } // @formatter:on } @Suppress("unused") object pagesRouter : NavRouter() { override val label = strings.pages // @formatter:off val login by render(loginStrings.login) { loginDemo() } val administration by administrationRouter // @formatter:on } @Suppress("unused") object otherRouter : NavRouter() { override val label = strings.other // @formatter:off val router by routingRouter // @formatter:on } fun Z2.defaultLayout(router: Router<Z2>, nav: Z2Builder, content: Z2Builder) { grid(wFull, hFull, pr16, pb16, boxSizingBorder) { gridTemplateRows = "min-content 1fr" gridTemplateColumns = "min-content 1fr" div(displayFlex, alignItemsCenter, h60, pl24, titleLarge) { text { strings.applicationTitle } } header() grid { gridTemplateRows = "min-content 1fr" gridTemplateColumns = "1fr" div(displayFlex, alignItemsCenter, pl24) { if (router != mainRouter) { addClass(pt8) outlinedIconButton(basicIcons.back, basicStrings.back) { router.up() } div(pl8) { text { router.parent?.label } } } } nav() } content() } } fun Z2.header() = grid { gridTemplateColumns = "1fr min-content min-content" gridTemplateRows = "60px" gridGap = 8.px div(alignSelfCenter) { searchBar() } div(alignSelfCenter) { iconButton(basicIcons.settings, basicStrings.settings, weight = 300) { } } div(displayFlex, alignSelfCenter, borderOutline, borderRadius8, bodySmall, p4, pr8) { div(pl8, whiteSpaceNoWrap, pr8, alignSelfCenter) { text { "<NAME>" } } div { style.height = 32.px style.width = 32.px style.borderRadius = 16.px style.backgroundColor = "green" } } }
1
Kotlin
0
0
5d660fdecdf0d41e3c307dd1db68108e5661504f
5,237
z2-material
Apache License 2.0
services/host-fs-service/src/main/kotlin/org/katan/service/fs/host/di/HostFsServiceDI.kt
KatanPanel
182,468,654
false
null
package org.katan.service.fs.host.di import org.katan.service.fs.FSService import org.katan.service.fs.host.HostFSService import org.koin.core.module.Module import org.koin.dsl.module val hostFsServiceDI: Module = module { single<FSService> { HostFSService( dockerClient = get(), config = get() ) } }
0
Kotlin
5
55
8e2f39310ec87bf19eed5a8a73b105518cabe7d9
351
Katan
Apache License 2.0
oneloginoidc/src/main/java/com/onelogin/oidc/session/SessionInfoError.kt
onelogin
241,972,325
false
null
package com.onelogin.oidc.session class SessionInfoError(message: String? = null, cause: Throwable? = null) : Exception(message, cause)
5
Kotlin
5
6
198284347d48c2ed1886d1c15ee233d5298a2855
137
onelogin-oidc-android
MIT License