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
Project/src-ParserV3/edu.citadel.cprl/src/edu/citadel/cprl/ast/InitialDecl.kt
SoftMoore
525,070,814
false
{"Kotlin": 345664, "Assembly": 85379, "Batchfile": 6123, "Shell": 5812, "Java": 675}
package edu.citadel.cprl.ast import edu.citadel.cprl.Token import edu.citadel.cprl.Type /** * Base class for all initial declarations. * * @constructor Construct an initial declaration with its identifier and type. */ abstract class InitialDecl(identifier : Token, declType : Type) : Declaration(identifier, declType)
0
Kotlin
1
1
c315bcabc550b6e03f39119d8ead66c39c706068
328
CPRL-Kt-2nd
The Unlicense
integration/javafx/src/test/kotlin/com/github/jcornaz/miop/javafx/SubscriptionsTest.kt
jcornaz
127,796,891
false
null
package com.github.jcornaz.miop.javafx import com.github.jcornaz.collekt.api.PersistentList import com.github.jcornaz.miop.test.ManualTimer import com.github.jcornaz.miop.test.runTest import com.nhaarman.mockitokotlin2.any import com.nhaarman.mockitokotlin2.doAnswer import com.nhaarman.mockitokotlin2.doReturn import com.nhaarman.mockitokotlin2.mock import javafx.application.Platform import javafx.beans.value.ChangeListener import javafx.beans.value.ObservableValue import javafx.collections.FXCollections import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.channels.ReceiveChannel import kotlinx.coroutines.javafx.JavaFx import kotlinx.coroutines.launch import kotlinx.coroutines.runBlocking import kotlinx.coroutines.withContext import org.junit.After import org.junit.Before import org.junit.Test import kotlin.test.assertEquals import kotlin.test.assertTrue class SubscriptionsTest { private lateinit var timer: ManualTimer @Before fun setupTimer() { timer = ManualTimer() } @After fun terminateTimer() = runBlocking { timer.terminate() } @Test(timeout = 10_000) @Suppress("UNCHECKED_CAST") fun `ObservableValue#openSubscription should add listener to the observable value`() = runBlocking { val context = coroutineContext + Dispatchers.JavaFx val observable = mock<ObservableValue<Int>> { on { value } doReturn 42 on { addListener(any<ChangeListener<in Int>>()) }.thenAnswer { invocation -> val listener = invocation.getArgument(0) as ChangeListener<in Int> launch(context) { timer.await(1) listener.changed(invocation.mock as ObservableValue<out Int>, 42, 1) timer.await(2) listener.changed(invocation.mock as ObservableValue<out Int>, 1, 2) } } } val subscription = observable.openValueSubscription() assertEquals(42, subscription.receive()) timer.advanceTo(1) assertEquals(1, subscription.receive()) timer.advanceTo(2) assertEquals(2, subscription.receive()) } @Test // (timeout = 10_000) fun `cancelling the subscription returned by ObservableValue#openSubscription should remove the listener from the observable value`() = runBlocking { val observable = mock<ObservableValue<Int>> { on { value } doReturn 0 on { addListener(any<ChangeListener<in Int>>()) } doAnswer { timer.advanceTo(1) } on { removeListener(any<ChangeListener<in Int>>()) } doAnswer { timer.advanceTo(2) } } val sub = observable.openValueSubscription() timer.await(1) sub.cancel() timer.await(2) } @Test fun `ObservableValue#openSubscription should access the observable from the JavaFx thread`() = runBlocking { val observable = mock<ObservableValue<Int>> { on { value } doAnswer { assertTrue(Platform.isFxApplicationThread()); 0 } on { addListener(any<ChangeListener<in Int>>()) } doAnswer { assertTrue(Platform.isFxApplicationThread()); timer.advanceTo(1) } on { removeListener(any<ChangeListener<in Int>>()) } doAnswer { assertTrue(Platform.isFxApplicationThread()); timer.advanceTo(2) } } val sub = observable.openValueSubscription() timer.await(1) sub.cancel() timer.await(2) } @Test fun testObservableListSubscription() = runTest { val observable = FXCollections.observableArrayList<String>("Hello", "world") val sub: ReceiveChannel<PersistentList<String>> = observable.openListSubscription() launch(coroutineContext) { assertEquals(listOf("Hello", "world"), sub.receive()) timer.advanceTo(1) timer.await(2) assertEquals(listOf("Hello", "Kotlin"), sub.receive()) timer.advanceTo(3) timer.await(4) assertEquals(listOf("Monday", "Tuesday", "Wednesday", "Thursday", "Friday"), sub.receive()) timer.advanceTo(5) } timer.await(1) withContext(Dispatchers.JavaFx) { observable[1] = "Kotlin" } timer.advanceTo(2) timer.await(3) withContext(Dispatchers.JavaFx) { observable.clear() observable.addAll("one", "two") observable.remove("one") observable[0] = "Monday" } withContext(Dispatchers.JavaFx) { observable.addAll("Tuesday", "Wednesday", "Thursday", "Friday") } timer.advanceTo(4) timer.await(5) } @Test fun testObservableListSubscriptionWithSorting() = runTest { val observable = FXCollections.observableArrayList<Char>('a', 'x', 'd', 'b', 'c', 'y', 'z') val sub: ReceiveChannel<PersistentList<Char>> = observable.openListSubscription() launch(coroutineContext) { assertEquals(listOf('a', 'x', 'd', 'b', 'c', 'y', 'z'), sub.receive()) timer.advanceTo(1) timer.await(2) assertEquals(listOf('a', 'b', 'c', 'd', 'x', 'y', 'z'), sub.receive()) } timer.await(1) withContext(Dispatchers.JavaFx) { observable.sort() } timer.advanceTo(2) } @Test fun testObservableListSubscriptionWithInsert() = runTest { val observable = FXCollections.observableArrayList<Char>('a', 'd', 'e') val sub: ReceiveChannel<PersistentList<Char>> = observable.openListSubscription() launch(coroutineContext) { assertEquals(listOf('a', 'd', 'e'), sub.receive()) timer.advanceTo(1) timer.await(2) assertEquals(listOf('a', 'b', 'c', 'd', 'e'), sub.receive()) } timer.await(1) withContext(Dispatchers.JavaFx) { observable.add(1, 'c') observable.add(1, 'b') } timer.advanceTo(2) } }
22
Kotlin
0
2
07e44179af49b084c2740ab0f614b7f773cd7da5
6,007
miop
MIT License
.teamcity/OpenSourceProjects_Storybook/patches/buildTypes/2b9c73e2-0a6e-47ca-95ae-729cac42be2b.kts
BR0kEN-
145,834,281
true
{"JavaScript": 826352, "HTML": 122954, "Kotlin": 44970, "TypeScript": 30133, "Shell": 12179, "Vue": 11106, "Objective-C": 8846, "Python": 3468, "Java": 2658, "CSS": 2646, "Boo": 463}
package OpenSourceProjects_Storybook.patches.buildTypes import jetbrains.buildServer.configs.kotlin.v2017_2.* import jetbrains.buildServer.configs.kotlin.v2017_2.triggers.RetryBuildTrigger import jetbrains.buildServer.configs.kotlin.v2017_2.triggers.retryBuild import jetbrains.buildServer.configs.kotlin.v2017_2.ui.* /* This patch script was generated by TeamCity on settings change in UI. To apply the patch, change the buildType with uuid = '2b9c73e2-0a6e-47ca-95ae-729cac42be2b' (id = 'OpenSourceProjects_Storybook_Build_2') accordingly, and delete the patch script. */ changeBuildType("2b9c73e2-0a6e-47ca-95ae-729cac42be2b") { triggers { val trigger1 = find<RetryBuildTrigger> { retryBuild { delaySeconds = 60 } } trigger1.apply { enabled = false } } }
0
JavaScript
0
0
16fd0890049066b73554db95611ae40010e978c0
852
storybook
MIT License
adaptive-core/src/jsMain/kotlin/hu/simplexion/adaptive/css/AdaptiveCssStyle.kt
spxbhuhb
788,711,010
false
{"Kotlin": 1058159, "CSS": 47382, "Java": 18012, "HTML": 2759, "JavaScript": 896}
/* * Copyright © 2020-2024, Simplexion, Hungary and contributors. Use of this source code is governed by the Apache 2.0 license. */ package hu.simplexion.adaptive.css import hu.simplexion.adaptive.base.marker.AdaptiveStyle class AdaptiveCssStyle( val name: String ) : AdaptiveStyle
1
Kotlin
0
0
75ec9b0c6a9f89359a08ce992affab493475ca4c
290
adaptive
Apache License 2.0
fluent-icons-extended/src/commonMain/kotlin/com/konyaco/fluent/icons/filled/VideoAdd.kt
Konyaco
574,321,009
false
null
package com.konyaco.fluent.icons.filled import androidx.compose.ui.graphics.vector.ImageVector import com.konyaco.fluent.icons.Icons import com.konyaco.fluent.icons.fluentIcon import com.konyaco.fluent.icons.fluentPath public val Icons.Filled.VideoAdd: ImageVector get() { if (_videoAdd != null) { return _videoAdd!! } _videoAdd = fluentIcon(name = "Filled.VideoAdd") { fluentPath { moveTo(16.0f, 16.25f) curveToRelative(0.0f, 1.8f, -1.46f, 3.25f, -3.25f, 3.25f) horizontalLineToRelative(-0.06f) arcTo(6.5f, 6.5f, 0.0f, false, false, 2.0f, 12.81f) lineTo(2.0f, 7.75f) curveTo(2.0f, 5.95f, 3.46f, 4.5f, 5.25f, 4.5f) horizontalLineToRelative(7.5f) curveToRelative(1.8f, 0.0f, 3.25f, 1.46f, 3.25f, 3.25f) verticalLineToRelative(8.5f) close() moveTo(21.76f, 5.89f) arcToRelative(1.0f, 1.0f, 0.0f, false, true, 0.24f, 0.65f) verticalLineToRelative(10.92f) arcToRelative(1.0f, 1.0f, 0.0f, false, true, -1.65f, 0.76f) lineTo(17.0f, 15.37f) lineTo(17.0f, 8.63f) lineToRelative(3.35f, -2.85f) arcToRelative(1.0f, 1.0f, 0.0f, false, true, 1.41f, 0.11f) close() moveTo(12.0f, 17.5f) arcToRelative(5.5f, 5.5f, 0.0f, true, false, -11.0f, 0.0f) arcToRelative(5.5f, 5.5f, 0.0f, false, false, 11.0f, 0.0f) close() moveTo(7.0f, 18.0f) verticalLineToRelative(2.5f) arcToRelative(0.5f, 0.5f, 0.0f, true, true, -1.0f, 0.0f) lineTo(6.0f, 18.0f) lineTo(3.5f, 18.0f) arcToRelative(0.5f, 0.5f, 0.0f, false, true, 0.0f, -1.0f) lineTo(6.0f, 17.0f) verticalLineToRelative(-2.5f) arcToRelative(0.5f, 0.5f, 0.0f, true, true, 1.0f, 0.0f) lineTo(7.0f, 17.0f) horizontalLineToRelative(2.5f) arcToRelative(0.5f, 0.5f, 0.0f, false, true, 0.0f, 1.0f) lineTo(7.0f, 18.0f) close() } } return _videoAdd!! } private var _videoAdd: ImageVector? = null
1
Kotlin
3
83
9e86d93bf1f9ca63a93a913c990e95f13d8ede5a
2,393
compose-fluent-ui
Apache License 2.0
vtextview/src/main/java/jp/gr/aqua/vtextviewer/Preferences.kt
jiro-aqua
79,621,172
false
null
package jp.gr.aqua.vtextviewer import android.content.Context import android.content.SharedPreferences import androidx.preference.PreferenceManager class Preferences(context: Context){ companion object { const val KEY_ABOUT ="app_about" const val KEY_USAGE="app_usage" const val KEY_FONT_KIND="font_kind" const val KEY_FONT_SIZE="font_size" const val KEY_CHAR_MAX_PORT="char_max_port" const val KEY_CHAR_MAX_LAND="char_max_land" const val KEY_IPA="about_ipa" const val KEY_ABOUT_MORISAWA_MINCHO="about_morisawa_mincho" const val KEY_ABOUT_MORISAWA_GOTHIC="about_morisawa_gothic" const val KEY_WRITING_PAPER="writing_paper" const val KEY_BACKGROUND_BLACK="background_black" const val KEY_YOKOGAKI="yokogaki" const val KEY_USE_DARK_MODE="use_dark_mode" } private val sp : SharedPreferences = PreferenceManager.getDefaultSharedPreferences(context) private val listeners = ArrayList<(()->Unit)>() init { sp.registerOnSharedPreferenceChangeListener { _, _ -> listeners.forEach { it() } } } fun getFontKind() : String { return sp.getString(KEY_FONT_KIND,null) ?: "mincho" } fun getFontSize() : Int { val fontsize = sp.getString(KEY_FONT_SIZE,null) ?: "16" return fontsize.toInt() } fun getCharMaxPort() : Int { return (sp.getString(KEY_CHAR_MAX_PORT,null) ?: "0").toIntSafety() } fun getCharMaxLand() : Int { return ( sp.getString(KEY_CHAR_MAX_LAND,null) ?: "0").toIntSafety() } fun isWritingPaperMode() : Boolean { return sp.getBoolean(KEY_WRITING_PAPER,false) } fun isBackgroundBlack() : Boolean { return sp.getBoolean(KEY_BACKGROUND_BLACK,false) } fun isYokogaki() : Boolean { return sp.getBoolean(KEY_YOKOGAKI,false) } fun isUseDarkMode() : Boolean { return sp.getBoolean(KEY_USE_DARK_MODE,false) } private fun String.toIntSafety() : Int = if ( this.isEmpty() ) 0 else this.toInt() fun addChangedListener(listener:()->Unit){ listeners.add(listener) } fun removeChangedListener(listener:()->Unit){ listeners.remove(listener) } }
5
Kotlin
1
4
dbfb7ea2015e6bad681b654a49751cddc291b0a5
2,330
vertical-text-viewer
Apache License 2.0
typescript-kotlin/src/main/kotlin/typescript/isIfStatement.fun.kt
turansky
393,199,102
false
null
// Automatically generated - do not modify! @file:JsModule("typescript") @file:JsNonModule package typescript external fun isIfStatement(node: Node): Boolean /* node is IfStatement */
0
Kotlin
1
10
bcf03704c0e7670fd14ec4ab01dff8d7cca46bf0
187
react-types-kotlin
Apache License 2.0
typescript-kotlin/src/main/kotlin/typescript/isIfStatement.fun.kt
turansky
393,199,102
false
null
// Automatically generated - do not modify! @file:JsModule("typescript") @file:JsNonModule package typescript external fun isIfStatement(node: Node): Boolean /* node is IfStatement */
0
Kotlin
1
10
bcf03704c0e7670fd14ec4ab01dff8d7cca46bf0
187
react-types-kotlin
Apache License 2.0
app/src/main/java/com/anyandroid/letstrain/SplashScreenFragment.kt
dmc0001
640,368,535
false
null
package com.anyandroid.letstrain import android.os.Bundle import androidx.fragment.app.Fragment import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import com.anyandroid.letstrain.databinding.FragmentSplashScreenBinding class SplashScreenFragment : Fragment() { private lateinit var binding: FragmentSplashScreenBinding override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View? { // Inflate the layout for this fragment binding= FragmentSplashScreenBinding.inflate(inflater, container, false) //I wanna after 3 seconds go to HomeFragment val thread = Thread { Thread.sleep(5000) val fragment = HomeFragment() val fragmentManager = activity?.supportFragmentManager val fragmentTransaction = fragmentManager?.beginTransaction() fragmentTransaction?.replace(R.id.fragment_container, fragment) fragmentTransaction?.addToBackStack(null) fragmentTransaction?.commit() } thread.start() return binding.root } }
0
Kotlin
0
0
d3e711dbef41b420f9c3ce45f8ae48addf227b1a
1,168
Home-work
MIT License
dao/src/main/kotlin/tables/runs/repository/PackageConfigurationsPathExcludesTable.kt
eclipse-apoapsis
760,319,414
false
{"Kotlin": 2994047, "Dockerfile": 24090, "Shell": 6277}
/* * Copyright (C) 2023 The ORT Server Authors (See <https://github.com/eclipse-apoapsis/ort-server/blob/main/NOTICE>) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * SPDX-License-Identifier: Apache-2.0 * License-Filename: LICENSE */ package org.eclipse.apoapsis.ortserver.dao.tables.runs.repository import org.jetbrains.exposed.sql.Table /** * An intermediate table to store references from [PackageConfigurationsTable] and [PathExcludesTable]. */ object PackageConfigurationsPathExcludesTable : Table("package_configurations_path_excludes") { val packageConfigurationId = reference("package_configuration_id", PackageConfigurationsTable) val pathExcludeId = reference("path_exclude_id", PathExcludesTable) override val primaryKey: PrimaryKey get() = PrimaryKey(packageConfigurationId, pathExcludeId, name = "${tableName}_pkey") }
18
Kotlin
2
9
0af70d6382a86f0ebc35d9b377f4229c6a71637a
1,378
ort-server
Apache License 2.0
server/libs/src/main/kotlin/email/Email.kt
fzuleta
98,181,797
false
null
package email import org.apache.velocity.app.VelocityEngine import org.apache.velocity.runtime.RuntimeConstants import org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader import org.springframework.mail.javamail.MimeMessageHelper import org.springframework.ui.velocity.VelocityEngineUtils import javax.mail.MessagingException import javax.mail.Session import javax.mail.internet.InternetAddress import javax.mail.internet.MimeMessage object Email { var primaryEmail_user = "" var primaryEmail_pass = "" var from = "" var server = "" var port = "587" fun sendHTMLEmail(subject: String, to: String, template: String, hTemplateVariables: MutableMap<String, Any>) { try { // Step 1 val mailServerProperties = System.getProperties() mailServerProperties.put("mail.smtp.from", from) mailServerProperties.put("mail.smtp.user", primaryEmail_user) mailServerProperties.put("mail.smtp.password", primaryEmail_pass) mailServerProperties.put("mail.smtp.host", server) mailServerProperties.put("mail.smtp.port", port) mailServerProperties.put("mail.smtp.auth", "true") mailServerProperties.put("mail.smtp.starttls.enable", "true") val getMailSession = Session.getDefaultInstance(mailServerProperties, null) val message = MimeMessage(getMailSession) message.subject = subject val helper: MimeMessageHelper helper = MimeMessageHelper(message, true) helper.setFrom(InternetAddress(from)) helper.setTo(InternetAddress(to)) val velocityEngine = VelocityEngine() velocityEngine.setProperty(RuntimeConstants.RESOURCE_LOADER, "classpath") velocityEngine.setProperty("classpath.resource.loader.class", ClasspathResourceLoader::class.java.name) velocityEngine.init() val text = VelocityEngineUtils.mergeTemplateIntoString( velocityEngine, template, hTemplateVariables) helper.setText(text, true) val transport = getMailSession.getTransport("smtp") transport.connect( Email.server, Email.primaryEmail_user, Email.primaryEmail_pass ) transport.sendMessage(message, message.allRecipients) transport.close() } catch (ex: MessagingException) { ex.printStackTrace() } } }
0
Kotlin
1
0
e0e7c8e361abc88c332ffc2fca3e8778b69c30d2
2,585
user-login-flow
Apache License 2.0
tedkeyboardobserver/src/main/java/gun0912/tedkeyboardobserver/TedRxKeyboardObserver.kt
ParkSangGwon
172,735,461
false
null
package gun0912.tedkeyboardobserver import android.app.Activity import io.reactivex.Observable import io.reactivex.subjects.BehaviorSubject class TedRxKeyboardObserver(activity: Activity) : BaseKeyboardObserver(activity) { private val behaviorSubject: BehaviorSubject<Boolean> = BehaviorSubject.create() fun listen(): Observable<Boolean> { internalListen(object : OnKeyboardListener { override fun onKeyboardChange(isShow: Boolean) { behaviorSubject.onNext(isShow) } }) return behaviorSubject } override fun onActivityDestroyed() { super.onActivityDestroyed() if (behaviorSubject.hasObservers()) { behaviorSubject.onComplete() } } }
3
Kotlin
9
96
8af706ef3e6fe1a21859e9c26d7b7e1e891b3860
760
TedKeyboardObserver
Apache License 2.0
app/src/main/java/com/mooveit/kotlin/kotlintemplateproject/presentation/view/home/HomePresenter.kt
gusaaaaa
90,760,396
false
null
package com.mooveit.kotlin.kotlintemplateproject.presentation.view.home import android.support.annotation.NonNull import android.view.View import com.mooveit.kotlin.kotlintemplateproject.data.entity.Pet import com.mooveit.kotlin.kotlintemplateproject.domain.interactor.DeletePet import com.mooveit.kotlin.kotlintemplateproject.domain.interactor.GetPetList import com.mooveit.kotlin.kotlintemplateproject.presentation.common.presenter.Presenter import com.mooveit.kotlin.kotlintemplateproject.presentation.internal.di.scope.PerActivity import io.reactivex.observers.DisposableObserver import retrofit2.Response import javax.inject.Inject @PerActivity class HomePresenter @Inject constructor(private val mGetPetListUseCase: GetPetList, private val mDeletePetUseCase: DeletePet) : Presenter(mGetPetListUseCase, mDeletePetUseCase) { private var mHomeView: HomeView? = null override fun onResume(view: View) { super.onResume(view) setView(view as HomeView) } override fun onDestroy() { super.onPause() this.mHomeView = null } fun setView(@NonNull homeView: HomeView) { this.mHomeView = homeView } fun fetchPets() { mHomeView!!.showProgress() mGetPetListUseCase.execute(PetListObserver(), null) } fun deletePet(pet: Pet) { mDeletePetUseCase.execute(PetDeleteObserver(), pet.externalId) } private fun onObserverError(error: Throwable) { error.message?.let { mHomeView!!.showError(it) } } private inner class PetListObserver : DisposableObserver<List<Pet>>() { override fun onNext(pets: List<Pet>) { mHomeView!!.hideProgress() mHomeView!!.showPets(pets) } override fun onComplete() { } override fun onError(error: Throwable) { mHomeView!!.hideProgress() onObserverError(error) mHomeView!!.showPets() } } private inner class PetDeleteObserver : DisposableObserver<Response<Void>>() { override fun onNext(void: Response<Void>) { mHomeView!!.showPets() } override fun onComplete() { } override fun onError(error: Throwable) { onObserverError(error) } } }
0
Kotlin
6
0
b3d8e577e995fad4160b6a6efa6953dbd86b5c68
2,328
android-kotlin-architecture
MIT License
Array/yanghao/kotlin/Algorithm6_15.kt
JessonYue
268,215,243
false
null
package staudy import java.util.* class Algorithm6_15 { fun isValid(s: String): Boolean { if (s.length % 2 == 1) return false val stack:Stack<Char> = Stack() s.toCharArray().forEach{c -> if (c == '{' || c == '[' || c == '('){ stack.push(c) }else{ if (stack.isEmpty()){ return false } val preChar = stack.peek() if ((preChar == '{' && c == '}') || (preChar == '(' && c == ')') || (preChar == '[' && c == ']')) stack.pop() else return false } } return stack.isEmpty() } } fun main(args: Array<String>) { print(Algorithm6_15().isValid("{}")) }
0
C
19
39
3c22a4fcdfe8b47f9f64b939c8b27742c4e30b79
749
LeetCodeLearning
MIT License
src/test/kotlin/day7/TestDay7.kt
chezbazar
728,404,822
false
{"Kotlin": 54427}
package day7 import fr.chezbazar.aoc21.day7.minimumFuel import fr.chezbazar.aoc21.day7.minimumFuelAdjusted import kotlin.test.Test import kotlin.test.assertEquals class TestDay7 { val crabs = listOf(16,1,2,0,4,2,7,1,2,14) @Test fun testCrabs() { assertEquals(37, crabs.minimumFuel()) assertEquals(168, crabs.minimumFuelAdjusted()) } }
0
Kotlin
0
0
223f19d3345ed7283f4e2671bda8ac094341061a
371
adventofcode
MIT License
plugin/src/main/kotlin/ru/astrainteractive/telegrambridge/commands/EmpireTabCompleter.kt
Astra-Interactive
584,452,095
false
null
package ru.astrainteractive.telegrambridge.commands import CommandManager import ru.astrainteractive.astralibs.AstraLibs import ru.astrainteractive.astralibs.commands.registerTabCompleter import ru.astrainteractive.astralibs.utils.withEntry import ru.astrainteractive.telegrambridge.TelegramBridge /** * Tab completer for your plugin which is called when player typing commands */ fun CommandManager.tabCompleter() = TelegramBridge.instance.registerTabCompleter("atemp") { if (args.isEmpty()) return@registerTabCompleter listOf("atemp", "atempreload") if (args.size == 1) return@registerTabCompleter listOf("atemp", "atempreload").withEntry(args.last()) return@registerTabCompleter listOf<String>() }
0
Kotlin
0
0
20de113860a51863fd77e88e8332601de8a9de9f
737
TelegramBridge
MIT License
src/commonMain/kotlin/com/lehaine/game/Assets.kt
LeHaine
360,954,566
false
null
package com.lehaine.game import com.lehaine.kiwi.korge.view.EnhancedSpriteAnimation import com.lehaine.kiwi.korge.view.getEnhancedSpriteAnimation import com.soywiz.klock.milliseconds import com.soywiz.korau.sound.* import com.soywiz.korge.view.Views import com.soywiz.korim.atlas.Atlas import com.soywiz.korim.atlas.readAtlas import com.soywiz.korim.font.Font import com.soywiz.korim.font.TtfFont import com.soywiz.korio.async.launch import com.soywiz.korio.file.std.resourcesVfs object Assets { lateinit var tiles: Atlas lateinit var pixelFont: Font lateinit var bossIdle: EnhancedSpriteAnimation lateinit var bossRun: EnhancedSpriteAnimation lateinit var bossAttack: EnhancedSpriteAnimation lateinit var heroIdle: EnhancedSpriteAnimation lateinit var heroRun: EnhancedSpriteAnimation lateinit var heroSleep: EnhancedSpriteAnimation lateinit var heroBroomAttack1: EnhancedSpriteAnimation lateinit var heroBroomAttack2: EnhancedSpriteAnimation lateinit var heroBroomAttack3: EnhancedSpriteAnimation lateinit var heroSlingShot: EnhancedSpriteAnimation lateinit var heroRoll: EnhancedSpriteAnimation lateinit var heroDie: EnhancedSpriteAnimation lateinit var longArmIdle: EnhancedSpriteAnimation lateinit var longArmSwing: EnhancedSpriteAnimation lateinit var longArmStunned: EnhancedSpriteAnimation lateinit var longArmWalk: EnhancedSpriteAnimation lateinit var sheepIdle: EnhancedSpriteAnimation lateinit var sheepAttack: EnhancedSpriteAnimation lateinit var sheepStunned: EnhancedSpriteAnimation lateinit var sheepWalk: EnhancedSpriteAnimation lateinit var dustBunnyIdle: EnhancedSpriteAnimation lateinit var dustBunnyJump: EnhancedSpriteAnimation lateinit var dustBunnyAttack: EnhancedSpriteAnimation lateinit var ghoulBob: EnhancedSpriteAnimation lateinit var ghoulAttack: EnhancedSpriteAnimation lateinit var stunIcon: EnhancedSpriteAnimation lateinit var sleepIcon: EnhancedSpriteAnimation object Sfx { lateinit var views: Views lateinit var hit: List<Sound> lateinit var swing: List<Sound> lateinit var strongSwing: List<Sound> lateinit var shoot: Sound lateinit var land: Sound lateinit var footstep: Sound lateinit var bossYell: Sound lateinit var ghoulAnticipation: Sound lateinit var ghoulSwing: Sound lateinit var teleport: Sound lateinit var roll: Sound lateinit var longArmSwing: Sound lateinit var music: Sound lateinit var musicChannel: SoundChannel suspend fun init(views: Views) { this.views = views // define sounds here hit = loadSoundsByPrefix("hit", 3, volume = 0.6) swing = loadSoundsByPrefix("swing", 6, volume = 0.8) strongSwing = loadSoundsByPrefix("strongSwing", 4, volume = 0.8) bossYell = loadSound("bossYell0") footstep = loadSound("footstep0") land = loadSound("land0") shoot = loadSound("shoot0") teleport = loadSound("teleport0") ghoulAnticipation = loadSound("ghoulAnticipation0") ghoulSwing = loadSound("ghoulSwing0") roll = loadSound("roll0") longArmSwing = loadSound("longArmSwing0") music = resourcesVfs["sfx/music.mp3"].readMusic() } suspend fun playMusic() { musicChannel = music.playForever() musicChannel.volume = 0.1 } private suspend fun loadSoundsByPrefix( prefix: String, total: Int = 1, dir: String = "sfx/", fileType: String = ".wav", volume: Double = 1.0 ): List<Sound> { val sounds = mutableListOf<Sound>() for (i in 0 until total) { sounds += resourcesVfs["$dir$prefix$i$fileType"].readSound().apply { this.volume = volume } } return sounds.toList() } private suspend fun loadSound( file: String, dir: String = "sfx/", fileType: String = ".wav", volume: Double = 1.0 ) = resourcesVfs["$dir$file$fileType"].readSound().apply { this.volume = volume } fun play(sound: Sound, times: PlaybackTimes = 1.playbackTimes) { views.launch { sound.play(times) } } fun List<Sound>.playSfx(times: PlaybackTimes = 1.playbackTimes) { play(this.random(), times) } fun Sound.playSfx(times: PlaybackTimes = 1.playbackTimes) { play(this, times) } } suspend fun init(views: Views) { tiles = resourcesVfs["tiles.atlas.json"].readAtlas() pixelFont = TtfFont(resourcesVfs["m5x7.ttf"].readAll()) bossIdle = tiles.getEnhancedSpriteAnimation("bossIdle", 500.milliseconds) bossAttack = tiles.getEnhancedSpriteAnimation("bossAttack", 150.milliseconds) bossRun = tiles.getEnhancedSpriteAnimation("bossRun", 100.milliseconds) // define animations and other assets here heroIdle = tiles.getEnhancedSpriteAnimation("heroIdle", 500.milliseconds) heroRun = tiles.getEnhancedSpriteAnimation("heroRun", 100.milliseconds) heroSleep = tiles.getEnhancedSpriteAnimation("heroSleep", 500.milliseconds) heroBroomAttack1 = tiles.getEnhancedSpriteAnimation("heroBroomAttack1", 100.milliseconds) heroBroomAttack2 = tiles.getEnhancedSpriteAnimation("heroBroomAttack2", 100.milliseconds) heroBroomAttack3 = tiles.getEnhancedSpriteAnimation("heroBroomAttack3", 100.milliseconds) heroSlingShot = tiles.getEnhancedSpriteAnimation("heroSlingShot", 100.milliseconds) heroRoll = tiles.getEnhancedSpriteAnimation("heroRoll", 100.milliseconds) heroDie = tiles.getEnhancedSpriteAnimation("heroDie", 100.milliseconds) longArmIdle = tiles.getEnhancedSpriteAnimation("longArmIdle", 500.milliseconds) longArmSwing = tiles.getEnhancedSpriteAnimation("longArmSwing", 100.milliseconds) longArmStunned = tiles.getEnhancedSpriteAnimation("longArmStunned", 500.milliseconds) longArmWalk = tiles.getEnhancedSpriteAnimation("longArmWalk", 100.milliseconds) dustBunnyIdle = tiles.getEnhancedSpriteAnimation("dustBunnyIdle", 500.milliseconds) dustBunnyJump = tiles.getEnhancedSpriteAnimation("dustBunnyJump", 100.milliseconds) dustBunnyAttack = tiles.getEnhancedSpriteAnimation("dustBunnyAttack", 100.milliseconds) sheepIdle = tiles.getEnhancedSpriteAnimation("sheepIdle", 500.milliseconds) sheepAttack = tiles.getEnhancedSpriteAnimation("sheepAttack", 100.milliseconds) sheepStunned = tiles.getEnhancedSpriteAnimation("sheepStunned", 500.milliseconds) sheepWalk = tiles.getEnhancedSpriteAnimation("sheepWalk", 100.milliseconds) ghoulBob = tiles.getEnhancedSpriteAnimation("ghoulBob", 500.milliseconds) ghoulAttack = tiles.getEnhancedSpriteAnimation("ghoulAttack", 100.milliseconds) stunIcon = tiles.getEnhancedSpriteAnimation("stunIcon", 200.milliseconds) sleepIcon = tiles.getEnhancedSpriteAnimation("sleepIcon", 150.milliseconds) Sfx.init(views) } }
0
Kotlin
0
9
2687bb6553df324bc68bc67ba9b301169a05cf43
7,321
ld48-sweet-dreams
MIT License
applications/data-collector-server/src/main/kotlin/io/initialcapacity/collector/App.kt
patat
793,524,335
false
{"Kotlin": 30990, "CSS": 7773, "JavaScript": 4296, "FreeMarker": 1041, "Dockerfile": 854, "Procfile": 336, "Shell": 267}
package io.initialcapacity.collector import io.initialcapacity.queue.MessageQueue import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.launch import kotlinx.coroutines.runBlocking import org.slf4j.Logger import java.net.URI import org.slf4j.LoggerFactory fun CoroutineScope.listenForCollectMoviesRequests( collectMoviesQueue: MessageQueue, worker: CollectMoviesWorker, logger: Logger ) { launch { logger.info("listening for collect movies requests") collectMoviesQueue.listenToMessages { logger.info("received collect movies request") worker.execute() } } } fun main() { runBlocking { val logger = LoggerFactory.getLogger(this.javaClass) val rabbitUrl = System.getenv("CLOUDAMQP_URL")?.let(::URI) ?: throw RuntimeException("Please set the CLOUDAMQP_URL environment variable") val dbUrl = System.getenv("JDBC_DATABASE_URL") ?: throw RuntimeException("Please set the JDBC_DATABASE_URL environment variable") val dbConfig = DatabaseConfiguration(dbUrl = dbUrl) val collectMoviesQueue = MessageQueue( rabbitUrl = rabbitUrl, exchangeName = "collect-movies-exchange", queueName = "collect-movies-queue" ) listenForCollectMoviesRequests( collectMoviesQueue, worker = CollectMoviesWorker(dbConfig.db), logger, ) } }
0
Kotlin
0
0
5cb947b241b64b9f4f4beacc3b49bcc87f676340
1,496
mbapp
Apache License 2.0
app/src/main/java/com/illis/awsiotcoremqtt/presentation/viewmodel/mqtt/MqttViewModel.kt
12121s
518,880,215
false
{"Kotlin": 11859}
package com.illis.awsiotcoremqtt.presentation.viewmodel.mqtt import android.app.Application import androidx.lifecycle.AndroidViewModel import androidx.lifecycle.MutableLiveData enum class MqttState { MQTT_COMPLETE, MQTT_FAIL } class MqttViewModel( app : Application, /*private val subscribeMqttUseCase: SubscribeMqttUseCase, private val publishMqttUseCase: PublishMqttUseCase*/ ) : AndroidViewModel(app) { var initTestValue = MutableLiveData("초기값") val mqttStatus : MutableLiveData<MqttState> = MutableLiveData() init { initTestValue.postValue("init 설정값") } /*fun publish(msg : String, type: PublishMqttUseCase.MqttType, delay: Int) = viewModelScope.launch(Dispatchers.IO) { publishMqttUseCase.publish(msg, type, delay).get() subscribe() } private fun subscribe() = viewModelScope.launch(Dispatchers.IO) { val subscribe = subscribeMqttUseCase.subscribeResponse() try { val result = subscribe.get(7, TimeUnit.SECONDS) if (result == "ok") mqttStatus.postValue(MqttState.MQTT_COMPLETE) else { mqttStatus.postValue(MqttState.MQTT_FAIL) } } catch (e: Exception) { mqttStatus.postValue(MqttState.MQTT_FAIL) } }*/ }
0
Kotlin
0
0
6f454764b1a032673a98d6e4ce52cb06ee05b13d
1,315
kotlin-aws-iot-core-mqtt-app
Apache License 2.0
src/main/kotlin/uk/gov/justice/digital/hmpps/hmppsppudautomationapi/controller/OffenderController.kt
ministryofjustice
709,230,604
false
{"Kotlin": 99495, "Dockerfile": 1375, "Shell": 77}
package uk.gov.justice.digital.hmpps.hmppsppudautomationapi.controller import jakarta.validation.Valid import jakarta.validation.ValidationException import org.slf4j.LoggerFactory import org.springframework.http.HttpStatus import org.springframework.http.MediaType import org.springframework.http.ResponseEntity import org.springframework.web.bind.annotation.PathVariable import org.springframework.web.bind.annotation.PostMapping import org.springframework.web.bind.annotation.RequestBody import org.springframework.web.bind.annotation.RequestMapping import org.springframework.web.bind.annotation.RestController import org.springframework.web.context.annotation.RequestScope import uk.gov.justice.digital.hmpps.hmppsppudautomationapi.domain.CreateRecallRequest import uk.gov.justice.digital.hmpps.hmppsppudautomationapi.domain.CreateRecallResponse import uk.gov.justice.digital.hmpps.hmppsppudautomationapi.domain.OffenderSearchRequest import uk.gov.justice.digital.hmpps.hmppsppudautomationapi.domain.OffenderSearchResponse import uk.gov.justice.digital.hmpps.hmppsppudautomationapi.ppud.PpudClient import java.util.* @RestController @RequestScope @RequestMapping(produces = [MediaType.APPLICATION_JSON_VALUE]) internal class OffenderController(private val ppudClient: PpudClient) { companion object { private val log = LoggerFactory.getLogger(this::class.java) } @PostMapping("/offender/search") suspend fun search( @Valid @RequestBody(required = true) criteria: OffenderSearchRequest, ): ResponseEntity<OffenderSearchResponse> { log.info("Offender search endpoint hit") ensureSearchCriteriaProvided(criteria) val results = ppudClient.searchForOffender(criteria.croNumber, criteria.nomsId, criteria.familyName, criteria.dateOfBirth) return ResponseEntity(OffenderSearchResponse(results), HttpStatus.OK) } @PostMapping("/offender/{offenderId}/recall") suspend fun createRecall( @PathVariable(required = true) offenderId: String, @Valid @RequestBody(required = true) createRecallRequest: CreateRecallRequest, ): ResponseEntity<CreateRecallResponse> { log.info("Offender recall endpoint hit") val recall = ppudClient.createRecall(offenderId, createRecallRequest) return ResponseEntity(CreateRecallResponse(recall), HttpStatus.CREATED) } private fun ensureSearchCriteriaProvided(criteria: OffenderSearchRequest) { if (!criteria.containsCriteria) { throw ValidationException("Valid search criteria must be specified") } } }
1
Kotlin
0
1
67f863a4c0716366c1756e90cdccd46b2b7e3eec
2,533
hmpps-ppud-automation-api
MIT License
src/main/kotlin/dev/mcabsan/markdown/Footnote.kt
myugen
609,135,540
false
null
package dev.mcabsan.markdown data class Footnote private constructor(private val anchors: Map<Tag, URL>) { fun asMarkdownText(): String { return anchors.entries.joinToString("\n") { (tag, url) -> "${tag.value}: ${url.value}" } } fun anchorTagFor(url: URL): String { return anchors.entries.find { (_, u) -> u == url }?.key?.value ?: throw IllegalArgumentException("Link is not in the footnote") } companion object { fun from(links: List<Link>): Footnote { val anchors = links.map { it.url }.distinct().mapIndexed { index, url -> val tag = Tag("[^anchor${index + 1}]") tag to url }.toMap() return Footnote(anchors) } } }
2
Kotlin
0
1
1459e34f80c2f4d50e7eb43befaedecb71e7a5b7
778
kata-markdown-kotlin
MIT License
packages/experimental/Drawer/android/src/main/java/com/microsoft/frnandroid/drawer/DrawerPackage.kt
microsoft
196,270,726
false
null
package com.microsoft.frnandroid.drawer import com.facebook.react.ReactPackage import com.facebook.react.bridge.NativeModule import com.facebook.react.bridge.ReactApplicationContext import com.facebook.react.uimanager.ViewGroupManager import java.util.* import kotlin.collections.ArrayList class DrawerPackage: ReactPackage { override fun createNativeModules(reactContext: ReactApplicationContext): List<NativeModule> { val modules = ArrayList<NativeModule>() modules.add(DrawerModule(reactContext)) return modules } override fun createViewManagers(reactContext: ReactApplicationContext): List<ViewGroupManager<*>> { return listOf(DrawerViewManager()) } }
78
TypeScript
137
903
066be5483c68c12a18e5256da500e10726419b25
709
fluentui-react-native
MIT License
src/main/kotlin/fr/phast/cql/services/helpers/UsingHelper.kt
phast-fr
424,529,437
false
{"Kotlin": 69053}
/* * MIT License * * Copyright (c) 2021 PHAST * * 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 fr.phast.cql.services.helpers import org.apache.commons.lang3.tuple.Triple import org.cqframework.cql.elm.execution.Library object UsingHelper { // Returns a list of (Model, Version, Url) for the usings in library. The // "System" using is excluded. fun getUsingUrlAndVersion(usings: Library.Usings?): List<Triple<String, String, String>> { if (usings == null || usings.def == null) { return emptyList() } val usingDefs = mutableListOf<Triple<String, String, String>>() for (def in usings.def) { if (def.localIdentifier == "System") continue usingDefs.add( Triple.of( def.localIdentifier, def.version, urlsByModelName[def.localIdentifier] ) ) } return usingDefs } private val urlsByModelName: Map<String, String> = mapOf( "FHIR" to "http://hl7.org/fhir", "QDM" to "urn:healthit-gov:qdm:v5_4" ) }
0
Kotlin
0
0
b8e3da27d0b7e76eb85596ae8a217e597a074d35
2,145
cql-services
MIT License
src/main/kotlin/brain/BigBrain.kt
qmoth
442,862,996
true
{"Kotlin": 8402}
package brain import memory.sourceObjectIds import screeps.api.* class BigBrain { private val roomsIOwn = mutableListOf<Room>() init { for (roomObject in Game.rooms.values) { if (roomObject.controller != null && roomObject.controller!!.my ) { roomsIOwn.add(roomObject) } } } /** * We want this function to store the value of a source object that is found in a room we own */ fun findSources() { for(currentRoom in roomsIOwn) { val returnedSources = currentRoom.find(FIND_SOURCES) for(sourceObjects in returnedSources) { if(!currentRoom.memory.sourceObjectIds.contains(sourceObjects.id)) { currentRoom.memory.sourceObjectIds = currentRoom.memory.sourceObjectIds.plus(sourceObjects.id) } } } } }
0
Kotlin
0
0
8b0369e7baa9cc84b4cbb678314bac2562ecee1d
893
screeps-kotlin-starter
MIT License
pumps-old/src/main/kotlin/fund/cyber/pump/ethereum_classic/EthereumClassicMigrations.kt
GoodforGod
129,151,733
true
{"Kotlin": 332422, "Shell": 139}
package fund.cyber.pump.ethereum_classic import fund.cyber.cassandra.migration.CqlFileBasedMigration import fund.cyber.cassandra.migration.ElasticHttpMigration import fund.cyber.node.common.Chain.ETHEREUM_CLASSIC import fund.cyber.pump.cassandra.chainApplicationId import fund.cyber.pump.ethereum.GenesisMigration object EthereumClassicMigrations { private val applicationId = ETHEREUM_CLASSIC.chainApplicationId val migrations = listOf( CqlFileBasedMigration(0, applicationId, "/migrations/ethereum_classic/0_initial.cql"), ElasticHttpMigration(1, applicationId, "/migrations/ethereum_classic/1_create-tx-index.json"), ElasticHttpMigration(2, applicationId, "/migrations/ethereum_classic/2_create-tx-type.json"), ElasticHttpMigration(3, applicationId, "/migrations/ethereum_classic/3_create-block-index.json"), ElasticHttpMigration(4, applicationId, "/migrations/ethereum_classic/4_create-block-type.json"), ElasticHttpMigration(5, applicationId, "/migrations/ethereum_classic/5_create-address-index.json"), ElasticHttpMigration(6, applicationId, "/migrations/ethereum_classic/6_create-address-type.json"), GenesisMigration(7, applicationId, ETHEREUM_CLASSIC, "/migrations/ethereum_classic/7_genesis.json"), ElasticHttpMigration(8, applicationId, "/migrations/ethereum_classic/8_create-uncle-index.json"), ElasticHttpMigration(9, applicationId, "/migrations/ethereum_classic/9_create-uncle-type.json") ) }
0
Kotlin
0
1
dcf7f09463cd76674326caf87509e048882b4176
1,543
cyber-search
MIT License
releases-hub-gradle-plugin/src/main/java/com/releaseshub/gradle/plugin/artifacts/ArtifactUpgrade.kt
jmfayard
212,313,901
true
{"Kotlin": 63594, "Java": 1986, "Shell": 1802}
package com.releaseshub.gradle.plugin.artifacts class ArtifactUpgrade { var name: String? = null var groupId: String? = null var artifactId: String? = null var fromVersion: String? = null var toVersion: String? = null var sourceCodeUrl: String? = null var releaseNotesUrl: String? = null var documentationUrl: String? = null lateinit var artifactUpgradeStatus: ArtifactUpgradeStatus constructor() { } constructor(groupId: String, artifactId: String, fromVersion: String) { this.groupId = groupId this.artifactId = artifactId this.fromVersion = fromVersion } fun match(includes: List<String>, excludes: List<String>): Boolean { val includeMatches = includes.isEmpty() || includes.find { match(it) } != null return if (includeMatches) { excludes.find { match(it) } == null } else { false } } private fun match(expression: String): Boolean { val split = expression.split(":") val groupIdToMatch = split[0] val artifactIdToMatch = if (split.size > 1) split[1] else null return groupIdToMatch == groupId && (artifactIdToMatch == null || artifactIdToMatch == artifactId) } override fun toString(): String { return "$groupId:$artifactId" } override fun equals(other: Any?): Boolean { if (this === other) return true if (javaClass != other?.javaClass) return false other as ArtifactUpgrade if (groupId != other.groupId) return false if (artifactId != other.artifactId) return false return true } override fun hashCode(): Int { var result = super.hashCode() result = 31 * result + (groupId?.hashCode() ?: 0) result = 31 * result + (artifactId?.hashCode() ?: 0) return result } }
0
null
0
0
bab72528de60e1ee7a87a0c70752d99f6b970bd2
1,870
releases-hub-gradle-plugin
Apache License 2.0
feature/search/src/main/java/com/quintallabs/feature/search/di/initialization/SearchInitialization.kt
thiagoalexb
739,844,654
false
{"Kotlin": 77090}
package com.quintallabs.feature.search.di.initialization import com.quintallabs.common.baseapp.di.modules.ModuleInitialization import com.quintallabs.feature.search.di.searchModules import org.koin.core.module.Module class SearchInitialization : ModuleInitialization() { override fun init(): List<Module> { return listOf( searchModules ) } }
0
Kotlin
0
0
e139dd7beefd6cef3d7cc2ee6b49ca6a5e06475f
361
randomDrink
Apache License 2.0
src/main/java/tripway/server/models/api/ProfileResponse.kt
NikitaBurtelov
362,575,706
false
{"Kotlin": 44262, "HTML": 1638, "Java": 949}
package tripway.server.models.api import com.fasterxml.jackson.annotation.JsonProperty import tripway.server.models.Trip import java.sql.Timestamp data class ProfileResponse( val id: String, val trips: List<TripDto>, val nickname: String, @JsonProperty("subscribers_count") val subscribersCount: Int, @JsonProperty("subscriptions_count") val subscriptionsCount: Int, @JsonProperty("is_own") val ownProfile: Boolean, @JsonProperty("is_subscription") val subscription: Boolean // val avatar: String ) { data class TripDto( val id: Long, val tripname: String, @JsonProperty("is_completed") val isCompleted: Boolean, @JsonProperty("first_point_name") val firstPointName: String, @JsonProperty("last_point_name") val lastPointName: String, val photo: String, val updated: Timestamp ) companion object { fun List<Trip>.mapToListDto() = map { TripDto( it.id, it.tripname, it.isCompleted, it.firstPointName, it.lastPointName, it.photo!!, it.updated ) } } }
0
Kotlin
0
0
a2b4434a9b75631772d84f3f5ddda96c6a899415
1,260
Tripway-backend
Apache License 2.0
src/examples/sampleProject/src/main/kotlin/Main.kt
rbraumandl
334,713,478
false
null
fun main(args: Array<String>) { println("Hello world ${args.size}") } const val myConstVal : Int = 100 val c : Int = 6 class MyClass (intMember : Int) { var iMember : Int = intMember val t : Int = 5 fun increment() { iMember = iMember + myConstVal } }
0
Kotlin
0
0
68d921bb6eb17994cf5c56b8d298d267d6925f14
280
kotlin-tutorial
Creative Commons Zero v1.0 Universal
buildSrc/src/main/kotlin/live/ditto/gradle/BuildSrcPlugin.kt
getditto
810,358,862
false
{"Kotlin": 40109, "Ruby": 2357, "Just": 1109, "Swift": 609}
package live.ditto.gradle class BuildSrcPlugin
0
Kotlin
0
2
c4da0e4deeae0001fc7e63681e38c91f906a13d6
48
demoapp-kmp
ISC License
mongodb/src/test/kotlin/io/qalipsis/plugins/mongodb/save/MongoDbSaveStepIntegrationTest.kt
qalipsis
428,401,101
false
{"Kotlin": 185635}
/* * Copyright 2022 AERIS IT Solutions GmbH * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing * permissions and limitations under the License. */ package io.qalipsis.plugins.mongodb.save import assertk.all import assertk.assertThat import assertk.assertions.hasSize import assertk.assertions.index import assertk.assertions.isEqualTo import assertk.assertions.isInstanceOf import assertk.assertions.isNotNull import assertk.assertions.key import com.mongodb.reactivestreams.client.MongoClient import com.mongodb.reactivestreams.client.MongoClients import io.micrometer.core.instrument.Counter import io.micrometer.core.instrument.Tags import io.micrometer.core.instrument.Timer import io.mockk.confirmVerified import io.mockk.every import io.mockk.verify import io.qalipsis.api.context.StepStartStopContext import io.qalipsis.api.events.EventsLogger import io.qalipsis.api.meters.CampaignMeterRegistry import io.qalipsis.api.sync.SuspendedCountLatch import io.qalipsis.plugins.mongodb.Constants.DOCKER_IMAGE import io.qalipsis.test.assertk.prop import io.qalipsis.test.coroutines.TestDispatcherProvider import io.qalipsis.test.mockk.WithMockk import io.qalipsis.test.mockk.relaxedMockk import java.time.Duration import java.util.concurrent.TimeUnit import kotlin.math.pow import org.bson.Document import org.junit.jupiter.api.AfterAll import org.junit.jupiter.api.BeforeAll import org.junit.jupiter.api.Test import org.junit.jupiter.api.Timeout import org.junit.jupiter.api.assertThrows import org.reactivestreams.Subscriber import org.reactivestreams.Subscription import org.testcontainers.containers.MongoDBContainer import org.testcontainers.containers.wait.strategy.Wait import org.testcontainers.junit.jupiter.Container import org.testcontainers.junit.jupiter.Testcontainers import org.testcontainers.utility.DockerImageName /** * * @author <NAME> */ @Testcontainers @WithMockk internal class MongoDbSaveStepIntegrationTest { private lateinit var client: MongoClient val testDispatcherProvider = TestDispatcherProvider() @BeforeAll fun init() { client = MongoClients.create("mongodb://localhost:${mongodb.getMappedPort(27017)}/?streamType=netty") } @AfterAll fun shutDown() { client.close() } private val timeToResponse = relaxedMockk<Timer>() private val recordsCount = relaxedMockk<Counter>() private val failureCounter = relaxedMockk<Counter>() private val eventsLogger = relaxedMockk<EventsLogger>() @Test @Timeout(10) fun `should succeed when sending query with single results`() = testDispatcherProvider.run { val metersTags = relaxedMockk<Tags>() val meterRegistry = relaxedMockk<CampaignMeterRegistry> { every { counter("mongodb-save-saving-records", refEq(metersTags)) } returns recordsCount every { timer("mongodb-save-time-to-response", refEq(metersTags)) } returns timeToResponse } val startStopContext = relaxedMockk<StepStartStopContext> { every { toMetersTags() } returns metersTags } val countLatch = SuspendedCountLatch(1) val results = ArrayList<Document>() val document = Document("key1", "val1") val saveClient = MongoDbSaveQueryClientImpl( ioCoroutineScope = this, clientBuilder = { client }, meterRegistry = meterRegistry, eventsLogger = eventsLogger ) val tags: Map<String, String> = emptyMap() saveClient.start(startStopContext) val resultOfExecute = saveClient.execute("db1", "col1", listOf(document), tags) assertThat(resultOfExecute).isInstanceOf(MongoDbSaveQueryMeters::class.java).all { prop("savedRecords").isEqualTo(1) prop("failedRecords").isEqualTo(0) prop("failedRecords").isNotNull() } fetchResult(client, "db1", "col1", results, countLatch) countLatch.await() assertThat(results).all { hasSize(1) index(0).all { key("key1").isEqualTo("val1") } } verify { eventsLogger.debug("mongodb.save.saving-records", 1, any(), tags = tags) timeToResponse.record(more(0L), TimeUnit.NANOSECONDS) recordsCount.increment(1.0) eventsLogger.info("mongodb.save.time-to-response", any<Duration>(), any(), tags = tags) eventsLogger.info("mongodb.save.saved-records", any<Array<*>>(), any(), tags = tags) } confirmVerified(timeToResponse, recordsCount, eventsLogger) } @Test @Timeout(10) fun `should throw an exception when sending invalid documents`(): Unit = testDispatcherProvider.run { val metersTags = relaxedMockk<Tags>() val meterRegistry = relaxedMockk<CampaignMeterRegistry> { every { counter("mongodb-save-failures", refEq(metersTags)) } returns failureCounter } val startStopContext = relaxedMockk<StepStartStopContext> { every { toMetersTags() } returns metersTags } val saveClient = MongoDbSaveQueryClientImpl( ioCoroutineScope = this, clientBuilder = { client }, meterRegistry = meterRegistry, eventsLogger = eventsLogger ) val tags: Map<String, String> = emptyMap() saveClient.start(startStopContext) assertThrows<Exception> { saveClient.execute( "db2", "col2", listOf(Document("key1", Duration.ZERO)), // Duration is not supported. tags ) } verify { failureCounter.increment(1.0) } confirmVerified(failureCounter) } private fun fetchResult( client: MongoClient, database: String, collection: String, results: ArrayList<Document>, countLatch: SuspendedCountLatch ) { client.run { getDatabase(database) .getCollection(collection) .find(Document()) .subscribe( object : Subscriber<Document> { override fun onSubscribe(s: Subscription) { s.request(Long.MAX_VALUE) } override fun onNext(document: Document) { results.add(document) countLatch.blockingDecrement() } override fun onError(error: Throwable) {} override fun onComplete() {} } ) } } companion object { @Container @JvmStatic val mongodb = MongoDBContainer(DockerImageName.parse(DOCKER_IMAGE)) .apply { waitingFor(Wait.forListeningPort().withStartupTimeout(Duration.ofSeconds(30))) withCreateContainerCmdModifier { cmd -> cmd.hostConfig!!.withMemory(512 * 1024.0.pow(2).toLong()).withCpuCount(2) } } } }
0
Kotlin
0
0
98298338867a9c1959414ceaa5daaa0ac5b6be2f
7,578
qalipsis-plugin-mongodb
Apache License 2.0
dsl/src/main/kotlin/com/faendir/awscdkkt/generated/services/apigatewayv2/IntegrationOverridesPropertyDsl.kt
F43nd1r
643,016,506
false
null
package com.faendir.awscdkkt.generated.services.apigatewayv2 import com.faendir.awscdkkt.AwsCdkDsl import javax.`annotation`.Generated import kotlin.Unit import software.amazon.awscdk.services.apigatewayv2.CfnApiGatewayManagedOverrides @Generated public fun buildIntegrationOverridesProperty(initializer: @AwsCdkDsl CfnApiGatewayManagedOverrides.IntegrationOverridesProperty.Builder.() -> Unit): CfnApiGatewayManagedOverrides.IntegrationOverridesProperty = CfnApiGatewayManagedOverrides.IntegrationOverridesProperty.Builder().apply(initializer).build()
1
Kotlin
0
0
e08d201715c6bd4914fdc443682badc2ccc74bea
567
aws-cdk-kt
Apache License 2.0
app/src/main/java/com/flexcode/jetweather/data/models/Alert.kt
Felix-Kariuki
503,790,694
false
{"Kotlin": 61879}
package com.flexcode.jetweather.data.models import com.google.gson.annotations.SerializedName data class Alert( @SerializedName("headline") var headline: String? = null, @SerializedName("msgtype") var msgtype: String? = null, @SerializedName("severity") var severity: String? = null, @SerializedName("urgency") var urgency: String? = null, @SerializedName("areas") var areas: String? = null, @SerializedName("category") var category: String? = null, @SerializedName("certainty") var certainty: String? = null, @SerializedName("event") var event: String? = null, @SerializedName("note") var note: String? = null, @SerializedName("effective") var effective: String? = null, @SerializedName("expires") var expires: String? = null, @SerializedName("desc") var desc: String? = null, @SerializedName("instruction") var instruction: String? = null )
1
Kotlin
0
7
d307a4d9a0c874c90f8e6e14bf1428237eb7b077
951
JetWeather
MIT License
app/src/main/java/com/chenqianhe/lohasfarm/ui/main/nav/Destinations.kt
chenqianhe
512,742,106
false
null
package com.chenqianhe.lohasfarm.ui.main.nav object Destinations { const val MAIN_ROUTE = "main_page_route" const val FARM_ROUTE = "farm_page_route" const val ACTIVITY_ROUTE = "activity_route" const val MESSAGE_ROUTE = "message_route" const val PERSONAL_ROUTE = "personal_route" const val LOGIN_ROUTE = "login_route" const val WEB_PAGE_ROUTE = "web_page_route" const val DETAIL_MESSAGE_ROUTE = "detail_message_route" const val PERSONAL_INFO_ROUTE = "personal_info_route" const val OTHERS_LAND_ROUTE = "others_land_route" const val MINE_LAND_ROUTE = "mine_land_route" const val MINE_LAND_INFO_ROUTE = "mine_land_info_route" const val TUTOR_ROUTE = "tutor_route" const val CROP_MANGE_ROUTE = "crop_mange_route" }
0
Kotlin
0
1
5e15aeab1693a1e242c29901171b08ee165e8eb4
768
LOHAS-Farm-Android
MIT License
components/faphub/report/impl/src/main/kotlin/com/flipperdevices/faphub/report/impl/composable/main/ComposableReportItem.kt
flipperdevices
288,258,832
false
{"Kotlin": 4167715, "FreeMarker": 10352, "CMake": 1780, "C++": 1152, "Fluent": 21}
package com.flipperdevices.faphub.report.impl.composable.main import androidx.annotation.DrawableRes import androidx.annotation.StringRes import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.size import androidx.compose.material.Icon import androidx.compose.material.Text import androidx.compose.runtime.Composable import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier 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 com.flipperdevices.core.ui.theme.FlipperThemeInternal import com.flipperdevices.core.ui.theme.LocalTypography import com.flipperdevices.faphub.report.impl.R import com.flipperdevices.core.ui.res.R as DesignSystem @Composable fun ComposableReportItem( @StringRes textId: Int, @DrawableRes iconId: Int, modifier: Modifier = Modifier ) = Row( modifier = modifier, verticalAlignment = Alignment.CenterVertically ) { Icon( modifier = Modifier .padding(start = 12.dp, top = 12.dp, bottom = 12.dp) .size(18.dp), painter = painterResource(iconId), contentDescription = stringResource(textId) ) Text( modifier = Modifier .padding(horizontal = 8.dp) .weight(1f), text = stringResource(textId), style = LocalTypography.current.bodyM14 ) Icon( modifier = Modifier .padding(bottom = 12.dp, top = 12.dp, end = 12.dp) .size(16.dp), painter = painterResource(DesignSystem.drawable.ic_forward), contentDescription = null ) } @Preview( showSystemUi = true, showBackground = true ) @Composable private fun ComposableReportItemPreview() { FlipperThemeInternal { ComposableReportItem( textId = R.string.fap_report_main_report_bug, iconId = R.drawable.ic_bug ) } }
21
Kotlin
174
1,528
8f293e596741a6c97409acbc8de10c7ae6e8d8b0
2,049
Flipper-Android-App
MIT License
app/src/main/java/dev/ramprasad/bloom/feature/login/SignUpScreen.kt
rramprasad
353,971,685
false
null
/* * Created by <NAME> on 29/06/21, 2:44 PM * Copyright (c) 2021. All rights reserved * Last modified 29/06/21, 2:44 PM */ package dev.ramprasad.bloom.feature.login import android.content.res.Configuration import androidx.compose.foundation.background import androidx.compose.foundation.layout.* import androidx.compose.foundation.text.KeyboardOptions import androidx.compose.material.* import androidx.compose.runtime.Composable import androidx.compose.runtime.MutableState import androidx.compose.runtime.collectAsState import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.saveable.rememberSaveable import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.res.stringResource import androidx.compose.ui.text.input.KeyboardType import androidx.compose.ui.text.input.PasswordVisualTransformation import androidx.compose.ui.text.style.TextAlign import androidx.compose.ui.tooling.preview.Devices import androidx.compose.ui.tooling.preview.Preview import androidx.compose.ui.unit.dp import androidx.hilt.navigation.compose.hiltViewModel import dev.ramprasad.bloom.R import dev.ramprasad.bloom.theme.BloomTheme @Composable fun SignUpScreen(loginViewModel: LoginViewModel = hiltViewModel(), onSignUpSuccess: () -> Unit) { Surface( modifier = Modifier .fillMaxSize() .background(MaterialTheme.colors.background) ) { Column( modifier = Modifier.fillMaxWidth(), verticalArrangement = Arrangement.Center, horizontalAlignment = Alignment.CenterHorizontally ) { val currentContext = LocalContext.current // Title SignUpTitle() Spacer(modifier = Modifier.size(16.dp)) // Email val emailState = rememberSaveable { mutableStateOf("") } val emailErrorState = rememberSaveable { mutableStateOf(currentContext.getString(R.string.email_address_label)) } SignUpEmailTextField(emailState, emailErrorState) Spacer(modifier = Modifier.size(8.dp)) // Password val passwordState = rememberSaveable { mutableStateOf("") } val passwordErrorState = rememberSaveable { mutableStateOf(currentContext.getString(R.string.password_label)) } SignUpPasswordTextField(passwordState, passwordErrorState) Spacer(modifier = Modifier.size(16.dp)) // Confirm Password val confirmPasswordState = rememberSaveable { mutableStateOf("") } val confirmPasswordErrorState = rememberSaveable { mutableStateOf(currentContext.getString(R.string.confirm_password_label)) } SignUpConfirmPasswordTextField(confirmPasswordState, confirmPasswordErrorState) Spacer(modifier = Modifier.size(16.dp)) // Sign Up Button SignUpButton { if (emailState.value.isEmpty()) { emailErrorState.value = currentContext.getString(R.string.required_field_empty_message) } if (passwordState.value.isEmpty()) { passwordErrorState.value = currentContext.getString(R.string.required_field_empty_message) } if (confirmPasswordState.value.isEmpty()) { confirmPasswordErrorState.value = currentContext.getString(R.string.required_field_empty_message) } if (emailState.value.isNotEmpty() && passwordState.value.isNotEmpty() && confirmPasswordState.value.isNotEmpty()) { if (passwordState.value == confirmPasswordState.value) { loginViewModel.onSignUp(emailState.value, passwordState.value) } else { confirmPasswordErrorState.value = currentContext.getString(R.string.password_not_matched) } } } val signUpSuccess = loginViewModel.signUpResultState.collectAsState().value if (signUpSuccess) { onSignUpSuccess() } else { // DO NOTHING } } } } @Composable fun SignUpTitle() { Text( text = stringResource(id = R.string.sign_up_with_email), modifier = Modifier .fillMaxWidth() .padding(16.dp, 0.dp, 16.dp, 0.dp), style = MaterialTheme.typography.h1, color = MaterialTheme.colors.onPrimary, textAlign = TextAlign.Center ) } @Composable fun SignUpEmailTextField(emailState: MutableState<String>, emailErrorState: MutableState<String>) { val currentContext = LocalContext.current OutlinedTextField( value = emailState.value, onValueChange = { emailState.value = it }, label = { Text(emailErrorState.value) }, isError = emailErrorState.value != currentContext.getString(R.string.email_address_label), placeholder = { Text( text = stringResource(id = R.string.email_address), color = MaterialTheme.colors.onPrimary ) }, enabled = true, modifier = Modifier .fillMaxWidth() .padding(16.dp, 0.dp, 16.dp, 0.dp), singleLine = true, keyboardOptions = KeyboardOptions( keyboardType = KeyboardType.Email ), textStyle = MaterialTheme.typography.body1, colors = TextFieldDefaults.textFieldColors( backgroundColor = MaterialTheme.colors.background, textColor = MaterialTheme.colors.onPrimary, focusedIndicatorColor = MaterialTheme.colors.onPrimary, focusedLabelColor = MaterialTheme.colors.onPrimary, cursorColor = MaterialTheme.colors.onPrimary ) ) } @Composable fun SignUpPasswordTextField( passwordState: MutableState<String>, passwordErrorState: MutableState<String> ) { val currentContext = LocalContext.current OutlinedTextField( value = passwordState.value, onValueChange = { passwordState.value = it }, label = { Text(passwordErrorState.value) }, placeholder = { Text( text = stringResource(id = R.string.password), color = MaterialTheme.colors.onPrimary ) }, isError = passwordErrorState.value != currentContext.getString(R.string.password_label), enabled = true, modifier = Modifier .fillMaxWidth() .padding(16.dp, 0.dp, 16.dp, 0.dp), keyboardOptions = KeyboardOptions( keyboardType = KeyboardType.Password ), singleLine = true, visualTransformation = PasswordVisualTransformation(), textStyle = MaterialTheme.typography.body1, colors = TextFieldDefaults.textFieldColors( backgroundColor = MaterialTheme.colors.background, textColor = MaterialTheme.colors.onPrimary, focusedIndicatorColor = MaterialTheme.colors.onPrimary, focusedLabelColor = MaterialTheme.colors.onPrimary, cursorColor = MaterialTheme.colors.onPrimary ) ) } @Composable fun SignUpConfirmPasswordTextField( confirmPasswordState: MutableState<String>, confirmPasswordErrorState: MutableState<String> ) { val currentContext = LocalContext.current OutlinedTextField( value = confirmPasswordState.value, onValueChange = { confirmPasswordState.value = it }, label = { Text(confirmPasswordErrorState.value) }, placeholder = { Text( text = stringResource(id = R.string.confirm_password), color = MaterialTheme.colors.onPrimary ) }, isError = confirmPasswordErrorState.value != currentContext.getString(R.string.confirm_password_label), enabled = true, modifier = Modifier .fillMaxWidth() .padding(16.dp, 0.dp, 16.dp, 0.dp), keyboardOptions = KeyboardOptions( keyboardType = KeyboardType.Password ), singleLine = true, visualTransformation = PasswordVisualTransformation(), textStyle = MaterialTheme.typography.body1, colors = TextFieldDefaults.textFieldColors( backgroundColor = MaterialTheme.colors.background, textColor = MaterialTheme.colors.onPrimary, focusedIndicatorColor = MaterialTheme.colors.onPrimary, focusedLabelColor = MaterialTheme.colors.onPrimary, cursorColor = MaterialTheme.colors.onPrimary ) ) } @Composable fun SignUpButton(onSignUpButtonClicked: () -> Unit) { Button( colors = ButtonDefaults.buttonColors( backgroundColor = MaterialTheme.colors.secondary, contentColor = MaterialTheme.colors.onSecondary, ), shape = MaterialTheme.shapes.medium, onClick = { onSignUpButtonClicked() }, modifier = Modifier .fillMaxWidth() .height(48.dp) .padding(16.dp, 0.dp, 16.dp, 0.dp) ) { Text( text = stringResource(R.string.signup), style = MaterialTheme.typography.button, color = MaterialTheme.colors.onSecondary ) } } @Preview( device = Devices.PIXEL_4_XL, uiMode = Configuration.UI_MODE_TYPE_NORMAL, widthDp = 360, heightDp = 640, name = "BasePreview" ) @Composable fun PreviewDarkLoginScreen() { BloomTheme(true) { SignUpScreen { } } }
0
Kotlin
0
1
52e4205f5d19cf08afbd58ea16967e5fbd65a5c7
10,044
BloomApp
MIT License
src/test/kotlin/com/example/Application.kt
dtorannpu
667,205,378
false
{"Kotlin": 38673}
package com.example import com.example.config.AppConfig import com.example.config.setupConfig import com.example.dao.TodoDao import com.example.dao.TodoDaoImpl import com.example.database.DatabaseFactory import com.example.plugins.configStatusPages import com.example.plugins.configureHTTP import com.example.plugins.configureJWTTest import com.example.plugins.configureRouting import com.example.plugins.configureSerialization import com.example.plugins.configureValidation import io.ktor.server.application.Application import io.ktor.server.application.install import org.koin.core.module.Module import org.koin.dsl.module import org.koin.ktor.ext.inject import org.koin.ktor.plugin.Koin import org.koin.logger.slf4jLogger @Suppress("unused") fun Application.testModule(koinModules: List<Module> = listOf(appTestModule)) { install(Koin) { slf4jLogger() modules(koinModules) } setupConfig() val databaseFactory by inject<DatabaseFactory>() databaseFactory.connect() configureHTTP() configureJWTTest() configureSerialization() configureValidation() configStatusPages() configureRouting() } val appTestModule = module { single { AppConfig() } factory<DatabaseFactory> { DatabaseFactoryForServerTest(get()) } single<TodoDao> { TodoDaoImpl() } }
0
Kotlin
0
0
6bbdd54751ca5929f8b817869533232e56e59425
1,339
todo-service
MIT License
3ds2/src/main/java/com/adyen/checkout/adyen3ds2/internal/ui/model/Adyen3DS2ComponentParams.kt
Adyen
91,104,663
false
null
/* * Copyright (c) 2023 Adyen N.V. * * This file is open source and available under the MIT license. See the LICENSE file for more info. * * Created by josephj on 24/3/2023. */ package com.adyen.checkout.adyen3ds2.internal.ui.model import com.adyen.checkout.components.core.Amount import com.adyen.checkout.components.core.internal.ui.model.ComponentParams import com.adyen.checkout.core.Environment import com.adyen.threeds2.customization.UiCustomization import kotlinx.parcelize.Parcelize import java.util.Locale @Parcelize internal data class Adyen3DS2ComponentParams( override val shopperLocale: Locale, override val environment: Environment, override val clientKey: String, override val isAnalyticsEnabled: Boolean, override val isCreatedByDropIn: Boolean, override val amount: Amount, val uiCustomization: UiCustomization?, val threeDSRequestorAppURL: String, ) : ComponentParams
31
null
61
96
1f000e27e07467f3a30bb3a786a43de62be003b2
927
adyen-android
MIT License
app/src/main/java/com/example/kolejarz/cook/FavouriteRecipeFragment.kt
Kolejarzyk
156,083,019
false
null
package com.example.kolejarz.cook import android.os.Bundle import android.support.v4.app.Fragment import android.support.v4.app.FragmentManager import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import com.example.kolejarz.Adapter.RecipeAdapter import com.example.kolejarz.DAO.AppDatabase import com.example.kolejarz.model.Recipe import kotlinx.android.synthetic.main.favourite_recipe_fragment.view.* /** * Class responsible for services and funcionality of FavouriteRecipe fragment. */ class FavouriteRecipeFragment : Fragment() { /** * LayoutInflater is one of the Android System Services * that is responsible for taking your XML files that define a layout, * and converting them into View objects. * @return A view of the fragment. */ override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? { val view : View = inflater.inflate(R.layout.favourite_recipe_fragment,container,false) /** * Reaches out to database to get all recipes. */ var recipeList : MutableList<Recipe> = AppDatabase.recipeDao.getRecipes() /** * Connects with Recipe adapter. */ val adapter = RecipeAdapter(this.context,recipeList,this) view.recipe_list_view.adapter = adapter return view } }
0
Kotlin
0
0
bbf564846386c403954057c46b7aba573bcf756d
1,395
ProjectCook
MIT License
easyadapter-compiler/src/main/java/com/amrdeveloper/easyadapter/compiler/parser/AdapterKspParser.kt
AmrDeveloper
436,362,549
false
null
package com.amrdeveloper.easyadapter.compiler.parser import com.amrdeveloper.easyadapter.adapter.* import com.amrdeveloper.easyadapter.bind.* import com.amrdeveloper.easyadapter.compiler.data.adapter.* import com.amrdeveloper.easyadapter.compiler.data.bind.* import com.amrdeveloper.easyadapter.compiler.data.listener.* import com.amrdeveloper.easyadapter.option.ListenerType import com.google.devtools.ksp.KspExperimental import com.google.devtools.ksp.getAnnotationsByType import com.google.devtools.ksp.getDeclaredProperties import com.google.devtools.ksp.isAnnotationPresent import com.google.devtools.ksp.processing.KSPLogger import com.google.devtools.ksp.symbol.KSClassDeclaration import com.squareup.kotlinpoet.ksp.KotlinPoetKspPreview import com.squareup.kotlinpoet.ksp.toTypeName class AdapterKspParser(private val logger: KSPLogger) { @OptIn(KspExperimental::class, KotlinPoetKspPreview::class) fun parseRecyclerAdapter(classDeclaration: KSClassDeclaration): RecyclerAdapterData { val className = classDeclaration.simpleName.getShortName() val adapterPackageName = classDeclaration.packageName.asString() val annotation = classDeclaration.getAnnotationsByType(RecyclerAdapter::class).first() val appPackageName = annotation.appPackageName val layoutId = annotation.layoutId val generateUpdateData = annotation.generateUpdateData val adapterClassName = annotation.customClassName.ifEmpty { "${className}RecyclerAdapter" } val viewBindingDataList = parseAdapterBindingList(classDeclaration) val adapterListeners = parseAdapterListeners(classDeclaration) return RecyclerAdapterData( appPackageName, adapterPackageName, adapterClassName, className, layoutId, viewBindingDataList, adapterListeners, generateUpdateData, ) } @OptIn(KspExperimental::class, KotlinPoetKspPreview::class) fun parseListAdapter(classDeclaration: KSClassDeclaration): ListAdapterData { val className = classDeclaration.simpleName.getShortName() val adapterPackageName = classDeclaration.packageName.asString() val annotation = classDeclaration.getAnnotationsByType(ListAdapter::class).first() val appPackageName = annotation.appPackageName val layoutId = annotation.layoutId val diffUtilContent = annotation.diffUtilContent val adapterClassName = annotation.customClassName.ifEmpty { "${className}ListAdapter" } val viewBindingDataList = parseAdapterBindingList(classDeclaration) val adapterListeners = parseAdapterListeners(classDeclaration) return ListAdapterData( appPackageName, adapterPackageName, adapterClassName, className, layoutId, viewBindingDataList, adapterListeners, diffUtilContent, ) } @OptIn(KspExperimental::class, KotlinPoetKspPreview::class) fun parsePagingDataAdapter(classDeclaration: KSClassDeclaration): PagingAdapterData { val className = classDeclaration.simpleName.getShortName() val adapterPackageName = classDeclaration.packageName.asString() val annotation = classDeclaration.getAnnotationsByType(PagingDataAdapter::class).first() val appPackageName = annotation.appPackageName val layoutId = annotation.layoutId val diffUtilContent = annotation.diffUtilContent val adapterClassName = annotation.customClassName.ifEmpty { "${className}PagingDataAdapter" } val viewBindingDataList = parseAdapterBindingList(classDeclaration) val adapterListeners = parseAdapterListeners(classDeclaration) return PagingAdapterData( appPackageName, adapterPackageName, adapterClassName, className, layoutId, viewBindingDataList, adapterListeners, diffUtilContent, ) } @OptIn(KspExperimental::class, KotlinPoetKspPreview::class) fun parsePagedListAdapter(classDeclaration: KSClassDeclaration): PagedListAdapterData { val className = classDeclaration.simpleName.getShortName() val adapterPackageName = classDeclaration.packageName.asString() val annotation = classDeclaration.getAnnotationsByType(PagedListAdapter::class).first() val appPackageName = annotation.appPackageName val layoutId = annotation.layoutId val diffUtilContent = annotation.diffUtilContent val adapterClassName = annotation.customClassName.ifEmpty { "${className}PagedListAdapter" } val viewBindingDataList = parseAdapterBindingList(classDeclaration) val adapterListeners = parseAdapterListeners(classDeclaration) return PagedListAdapterData( appPackageName, adapterPackageName, adapterClassName, className, layoutId, viewBindingDataList, adapterListeners, diffUtilContent, ) } @OptIn(KspExperimental::class, KotlinPoetKspPreview::class) fun parseArrayAdapter(classDeclaration: KSClassDeclaration): ArrayAdapterData { val className = classDeclaration.simpleName.getShortName() val adapterPackageName = classDeclaration.packageName.asString() val annotation = classDeclaration.getAnnotationsByType(ArrayAdapter::class).first() val appPackageName = annotation.appPackageName val layoutId = annotation.layoutId val adapterClassName = annotation.customClassName.ifEmpty { "${className}ArrayAdapter" } val viewBindingDataList = parseAdapterBindingList(classDeclaration) val adapterListeners = parseAdapterListeners(classDeclaration) return ArrayAdapterData( appPackageName, adapterPackageName, adapterClassName, className, layoutId, viewBindingDataList, adapterListeners, ) } @OptIn(KspExperimental::class, KotlinPoetKspPreview::class) fun parseExpandableAdapter(classDeclaration: KSClassDeclaration, expandableMap : Map<String, BindExpandableData>) : ExpandableAdapterData { val className = classDeclaration.simpleName.getShortName() val adapterPackageName = classDeclaration.packageName.asString() val annotation = classDeclaration.getAnnotationsByType(ExpandableAdapter::class).first() val appPackageName = annotation.appPackageName val adapterClassName = annotation.customClassName.ifEmpty { "${className}ExpandableAdapter" } for(property in classDeclaration.getDeclaredProperties()) { if (property.isAnnotationPresent(BindExpandableMap::class)) { val annotatedType = property.type.toTypeName().toString() if (annotatedType.startsWith("kotlin.collections.Map").not()) { logger.error("BindExpandableMap used only with Map class", classDeclaration) } val dataTypeArguments = property.type.element?.typeArguments dataTypeArguments?.let { val expandableGroupType = dataTypeArguments[0] var expandableGroupClassName = expandableGroupType.toTypeName().toString() expandableGroupClassName = expandableGroupClassName.replace("`", "") val groupExpandableData = expandableMap[expandableGroupClassName] if (groupExpandableData == null) { logger.error("Can't find expandable group class with name $expandableGroupClassName", classDeclaration) return@let } val expandableItemType = dataTypeArguments[1] val expandableItemList = expandableItemType.type?.element var expandableItemClassName = expandableItemList?.typeArguments?.first()?.toTypeName().toString() expandableItemClassName = expandableItemClassName.replace("`", "") val itemExpandableData = expandableMap[expandableItemClassName] if (itemExpandableData == null) { logger.error("Can't find expandable item class with name $itemExpandableData", classDeclaration) return@let } return ExpandableAdapterData( appPackageName, adapterPackageName, adapterClassName, groupExpandableData, itemExpandableData ) } } } error("Can't find expandable classes to build the ExpandableAdapter") } @OptIn(KspExperimental::class, KotlinPoetKspPreview::class) fun parseBindExpandableClass(classDeclaration: KSClassDeclaration) : BindExpandableData { val className = classDeclaration.simpleName.getShortName() val classPackageName = classDeclaration.packageName.asString() val annotation = classDeclaration.getAnnotationsByType(BindExpandable::class).first() val layoutId = annotation.layoutId val viewBindingDataList = parseAdapterBindingList(classDeclaration) val adapterListeners = parseAdapterListeners(classDeclaration) return BindExpandableData( className, classPackageName, layoutId, viewBindingDataList, adapterListeners, ) } @OptIn(KspExperimental::class, KotlinPoetKspPreview::class) fun parseAdapterBindingList(classDeclaration: KSClassDeclaration): List<BindingData> { val viewBindingDataList = mutableListOf<BindingData>() classDeclaration.getDeclaredProperties().forEach { val elementName = it.qualifiedName?.getShortName().toString() val elementType = it.type.toString() if (it.isAnnotationPresent(BindText::class)) { val annotation = it.getAnnotationsByType(BindText::class).first() val binding = BindingTextData(elementName, annotation.viewId) viewBindingDataList.add(binding) } if (it.isAnnotationPresent(BindImageRes::class)) { if (elementType != "Int") { logger.error("@BindImageRes can used only with Int data type", it) } val annotation = it.getAnnotationsByType(BindImageRes::class).first() val binding = BindImageResData(elementName, annotation.viewId) viewBindingDataList.add(binding) } if (it.isAnnotationPresent(BindBackgroundRes::class)) { if (elementType != "Int") { logger.error("@BindBackgroundRes can used only with Int data type", it) } val annotation = it.getAnnotationsByType(BindBackgroundRes::class).first() val binding = BindBackgroundResData(elementName, annotation.viewId) viewBindingDataList.add(binding) } if (it.isAnnotationPresent(BindBackgroundColor::class)) { if (elementType != "Int") { logger.error("@BindBackgroundColor can used only with Int data type", it) } val annotation = it.getAnnotationsByType(BindBackgroundColor::class).first() val binding = BindBackgroundColorData(elementName, annotation.viewId) viewBindingDataList.add(binding) } if (it.isAnnotationPresent(BindVisibility::class)) { if (elementType != "Int") { logger.error("@BindVisibility can used only with Int data type", it) } val annotation = it.getAnnotationsByType(BindVisibility::class).first() val binding = BindVisibilityData(elementName, annotation.viewId) viewBindingDataList.add(binding) } if (it.isAnnotationPresent(BindImage::class)) { if (elementType != "String") { logger.error("@BindImage can used only with String data type", it) } val annotation = it.getAnnotationsByType(BindImage::class).first() val binding = BindImageData(elementName, annotation.viewId, annotation.loader) viewBindingDataList.add(binding) } if (it.isAnnotationPresent(BindGif::class)) { if (elementType != "Int") { logger.error("@BindGif can used only with integer data type", it) } val annotation = it.getAnnotationsByType(BindGif::class).first() val binding = BindGifData(elementName, annotation.viewId, annotation.loader) viewBindingDataList.add(binding) } if (it.isAnnotationPresent(BindAlpha::class)) { if (elementType != "Float") { logger.error("@BindAlpha can used only with float data type", it) } val annotation = it.getAnnotationsByType(BindAlpha::class).first() val binding = BindAlphaData(elementName, annotation.viewId) viewBindingDataList.add(binding) } } return viewBindingDataList } @OptIn(KspExperimental::class, KotlinPoetKspPreview::class) fun parseAdapterListeners(classDeclaration: KSClassDeclaration): Set<ListenerData> { val modelName = classDeclaration.simpleName.getShortName() val listeners = mutableSetOf<ListenerData>() classDeclaration.getAnnotationsByType(BindListener::class).forEach { val listener = when (it.listenerType) { ListenerType.OnClick -> ClickListenerData(modelName, it.viewId) ListenerType.OnLongClick -> LongClickListenerData(modelName, it.viewId) ListenerType.OnTouch -> TouchListenerData(modelName, it.viewId) ListenerType.OnHover -> HoverListenerData(modelName, it.viewId) ListenerType.OnCheckedChange -> CheckedListenerData(modelName, it.viewId) ListenerType.OnTextChange -> TextChangedListenerData(modelName, it.viewId) } val isUnique = listeners.add(listener) if (isUnique.not()) { logger.warn ( "You have declared ${it.listenerType} Listener more than one time in the same class", classDeclaration ) } } return listeners } }
2
null
5
77
22a727c2a71f50c5b2274c8b3f1593cc8f11c7ce
14,812
EasyAdapter
MIT License
src/main/kotlin/mazerunner/MazeLeaderboard.kt
devcsrj
170,037,724
false
null
/** * Copyright © 2018 <NAME> (<EMAIL>) * * 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 mazerunner import mazerunner.Leaderboard.Entry import org.slf4j.LoggerFactory import reactor.core.publisher.Flux import reactor.core.publisher.TopicProcessor import reactor.core.publisher.toFlux import java.util.concurrent.ConcurrentHashMap class MazeLeaderboard(eventPublisher: TopicProcessor<MazeMovementEvent>, goal: Point) : Leaderboard { private val logger = LoggerFactory.getLogger(MazeLeaderboard::class.java) private val scores = ConcurrentHashMap<Tag, Entry>() init { eventPublisher.filter { it.runner.jump().current == goal } .map { it.runner } .doOnNext { scores[it.tag()] = Entry(it.tag(), it.steps()) } .subscribe { logger.info("Runner '$it' reached goal '$goal' after ${it.steps()} move(s)") } } override fun scores(): Flux<Entry> = scores.values .sortedBy { it.moves } .toFlux() .take(20L) }
1
Kotlin
2
6
c5db6a86f1d65a366e6ce1978d73a5b5f04b9cc6
1,593
mazerunner
Apache License 2.0
src/main/kotlin/org/example/projectnu/common/exception/custom/InternalServerErrorException.kt
hsyoon2261
810,274,541
false
{"Kotlin": 117256, "Dockerfile": 111}
package org.example.projectnu.common.exception.custom import org.example.projectnu.common.`object`.ResultCode class InternalServerErrorException : BasicException { constructor() : super(ResultCode.INTERNAL_SERVER_ERROR) constructor(errorMessage: String) : super(ResultCode.INTERNAL_SERVER_ERROR, errorMessage) }
0
Kotlin
0
0
fbd21a364286c8b5fce5f9b068baa8340d86d047
323
ProjectNU
MIT License
ktx-core/src/commonMain/kotlin/com/makeevrserg/mobilex/core/platform/PlatformConfiguration.kt
makeevrserg
540,605,844
false
null
package com.makeevrserg.mobilex.core.platform expect interface PlatformConfiguration { val type: PlatformConfigurationType }
0
Kotlin
0
1
14885150113d8d79c4afacfcaf2ed32b3d578f60
130
MobileX
Apache License 2.0
ontrack-repository-impl/src/test/java/net/nemerosa/ontrack/repository/AbstractRepositoryTestSupport.kt
nemerosa
19,351,480
false
{"Kotlin": 9640276, "JavaScript": 3232252, "Java": 1029918, "HTML": 507415, "Groovy": 372843, "CSS": 137546, "Less": 35335, "Dockerfile": 6298, "Shell": 5086}
package net.nemerosa.ontrack.repository import net.nemerosa.ontrack.it.AbstractITTestSupport import net.nemerosa.ontrack.model.structure.Branch import net.nemerosa.ontrack.model.structure.Branch.Companion.of import net.nemerosa.ontrack.model.structure.Project import net.nemerosa.ontrack.model.structure.Project.Companion.of import org.springframework.beans.factory.annotation.Autowired abstract class AbstractRepositoryTestSupport : AbstractITTestSupport() { @Autowired protected lateinit var structureRepository: StructureRepository protected fun do_create_project(): Project { return structureRepository.newProject(of(nameDescription())) } protected fun do_create_branch(): Branch { return structureRepository.newBranch(of(do_create_project(), nameDescription())) } }
49
Kotlin
25
96
53c2b0df210aec3a2f57ca778d65393a7a95e719
816
ontrack
MIT License
basick/src/main/java/com/mozhimen/basick/utilk/UtilKEncryptAES.kt
mozhimen
353,952,154
false
null
package com.mozhimen.basick.utilk import android.util.Base64 import android.util.Log import java.io.UnsupportedEncodingException import java.nio.charset.Charset import java.nio.charset.StandardCharsets import java.security.InvalidAlgorithmParameterException import java.security.InvalidKeyException import java.security.NoSuchAlgorithmException import javax.crypto.BadPaddingException import javax.crypto.Cipher import javax.crypto.IllegalBlockSizeException import javax.crypto.NoSuchPaddingException import javax.crypto.spec.IvParameterSpec import javax.crypto.spec.SecretKeySpec /** * @ClassName AESUtil * @Description AESUtil.require("xxx","xxx").encrypt("xxx") * @Author Kolin Zhao * @Date 2021/10/14 15:13 * @Version 1.0 */ object UtilKEncryptAES { private val TAG = "UtilKAES>>>>>" //加密算法 private const val KEY_ALGORITHM = "AES" //AES 的 密钥长度,32 字节,范围:16 - 32 字节 private const val SECURE_KEY_LENGTH = 16 //秘钥长度不足 16 个字节时,默认填充位数 private const val DEFAULT_FILL = "0" //字符编码 private val CHARSET_UTF8 = StandardCharsets.UTF_8 //加解密算法/工作模式/填充方式 private const val CIPHER_ALGORITHM = "AES/CBC/PKCS5Padding" private var _keyAlgorithm = KEY_ALGORITHM private var _secureKeyLength = SECURE_KEY_LENGTH private var _defaultFill = DEFAULT_FILL private var _charset = CHARSET_UTF8 private var _cipherAlgorithm = CIPHER_ALGORITHM //key private var _secretKey: String? = null //IV private var _ivString: String? = null /** * 默认参数配置 * @param secretKey String 需要16位 * @param ivString String 需要16位 * @param keyAlgorithm String * @param secureKeyLength Int * @param defaultFill String * @param charset Charset * @param cipherAlgorithm String * @return UtilKAESProvider */ fun require( secretKey: String, ivString: String = secretKey, keyAlgorithm: String = KEY_ALGORITHM, secureKeyLength: Int = SECURE_KEY_LENGTH, defaultFill: String = DEFAULT_FILL, charset: Charset = CHARSET_UTF8, cipherAlgorithm: String = CIPHER_ALGORITHM ): UtilKAESProvider { this._secretKey = secretKey this._ivString = ivString this._keyAlgorithm = keyAlgorithm this._secureKeyLength = secureKeyLength this._defaultFill = defaultFill this._charset = charset this._cipherAlgorithm = cipherAlgorithm return UtilKAESProvider } object UtilKAESProvider { /** * 采用AES128加密 * @param content String 要加密的内容 * @return String? */ fun encrypt(content: String): String? { require(_secretKey != null && _ivString != null) { "secureKey or _ivString must not be null" } Log.d(TAG, "UtilKAESProvider encrypt content $content") try { // 获得密匙数据 val rawKeyData = getAESKey(_secretKey!!) // 从原始密匙数据创建KeySpec对象 val key = SecretKeySpec(rawKeyData, _keyAlgorithm) // Cipher对象实际完成加密操作 val cipher = Cipher.getInstance(_cipherAlgorithm) // 用密匙初始化Cipher对象 val ivParameterSpec = IvParameterSpec(_ivString!!.toByteArray()) cipher.init(Cipher.ENCRYPT_MODE, key, ivParameterSpec) // 正式执行加密操作 val encryptByte = cipher.doFinal(content.toByteArray()) Log.d(TAG, "UtilKAESProvider encrypt success") return Base64.encodeToString(encryptByte, Base64.NO_WRAP) } catch (e: UnsupportedEncodingException) { e.printStackTrace() } catch (e: NoSuchAlgorithmException) { e.printStackTrace() } catch (e: NoSuchPaddingException) { e.printStackTrace() } catch (e: InvalidAlgorithmParameterException) { e.printStackTrace() } catch (e: InvalidKeyException) { e.printStackTrace() } catch (e: IllegalBlockSizeException) { e.printStackTrace() } catch (e: BadPaddingException) { e.printStackTrace() } return null } /** * 采用AES128解密,API>=19 * @param encryptContent String * @return String? */ fun decrypt(encryptContent: String): String? { require(_secretKey != null && _ivString != null) { "_secretKey or _ivString must not be null" } val data: ByteArray = Base64.decode(encryptContent, Base64.NO_WRAP) try { // 获得密匙数据 val rawKeyData = getAESKey(_secretKey!!) // secureKey.getBytes(); // 从原始密匙数据创建一个KeySpec对象 val key = SecretKeySpec(rawKeyData, _keyAlgorithm) // Cipher对象实际完成解密操作 val cipher = Cipher.getInstance(_cipherAlgorithm) // 用密匙初始化Cipher对象 val initParam = _ivString!!.toByteArray() val ivParameterSpec = IvParameterSpec(initParam) cipher.init(Cipher.DECRYPT_MODE, key, ivParameterSpec) val result = String(cipher.doFinal(data), _charset) Log.d(TAG, "UtilKAESProvider decrypt success result $result") return result } catch (e: UnsupportedEncodingException) { e.printStackTrace() } catch (e: NoSuchAlgorithmException) { e.printStackTrace() } catch (e: NoSuchPaddingException) { e.printStackTrace() } catch (e: InvalidKeyException) { e.printStackTrace() } catch (e: InvalidAlgorithmParameterException) { e.printStackTrace() } catch (e: IllegalBlockSizeException) { e.printStackTrace() } catch (e: BadPaddingException) { e.printStackTrace() } return null } /** * API>=19 * @param key String * @return ByteArray * @throws UnsupportedEncodingException */ @Throws(UnsupportedEncodingException::class) fun getAESKey(key: String): ByteArray { val keyBytes: ByteArray = key.toByteArray(_charset) val keyBytes16 = ByteArray(_secureKeyLength) System.arraycopy( keyBytes, 0, keyBytes16, 0, keyBytes.size.coerceAtMost(_secureKeyLength) ) return keyBytes16 } } }
0
Kotlin
0
1
d5b6f4a180302d6abfa56c8fe3d6217dca93141b
6,633
SwiftMK
Apache License 2.0
conclave-init/src/test/kotlin/com/r3/conclave/init/template/JavaClassValidationTest.kt
R3Conclave
526,690,075
false
null
package com.r3.conclave.init.template import org.junit.jupiter.api.assertDoesNotThrow import org.junit.jupiter.api.assertThrows import org.junit.jupiter.params.ParameterizedTest import org.junit.jupiter.params.provider.MethodSource class JavaClassValidationTest { companion object { @JvmStatic fun allowedClassNames(): List<String> = listOf( "MegaEnclave", "megaEnclave", "megaenclave", "i3", "αρετη", "MAX_VALUE", "isLetterOrDigit", ) @JvmStatic fun invalidClassNames(): List<String> = listOf( "1MegaEnclave", "Mega@Enclave", "mega-enclave" ) } @ParameterizedTest @MethodSource("allowedClassNames") fun `allowed class names`(name: String) { assertDoesNotThrow { JavaClass(name) } } @ParameterizedTest @MethodSource("invalidClassNames") fun `invalid class names`(name: String) { assertThrows<IllegalArgumentException> { JavaClass(name) } } }
0
C++
8
41
9b49a00bb33a22f311698d7ed8609a189f38d6ae
1,071
conclave-core-sdk
Apache License 2.0
presentation/src/main/java/ng/mathemandy/housematez/presentation/mvi/IntentProcessor.kt
mathemandy
272,941,393
false
null
package ng.mathemandy.housematez.presentation.mvi import kotlinx.coroutines.flow.Flow interface IntentProcessor<out R : ViewResult> { fun intentToResult(viewIntent: ViewIntent): Flow<R> } class InvalidViewIntentException(private val viewIntent: ViewIntent) : IllegalArgumentException() { override val message: String? get() = "Invalid intent $viewIntent" }
0
Kotlin
0
0
4778a45b0a100606681ce59cbfa9fc47c765d96a
375
Housematez
MIT License
features/details/src/main/java/com/fappslab/features/details/presentation/extension/ViewExtension.kt
F4bioo
628,097,763
false
null
package com.fappslab.features.details.presentation.extension import com.airbnb.lottie.LottieAnimationView import com.facebook.shimmer.ShimmerFrameLayout internal fun ShimmerFrameLayout.animHandle(shouldAnim: Boolean) { if (shouldAnim) { startShimmer() } else stopShimmer() } internal fun LottieAnimationView.animHandle(shouldAnim: Boolean) { if (shouldAnim) { resumeAnimation() } else pauseAnimation() }
0
Kotlin
0
0
d3e0405eae2038ea13c352daa8bc976da85914a4
439
faurecia-aptoide-challenge
MIT License
app/src/main/java/sma/tripper/dao/TripWithEventsDao.kt
ameteo
232,404,147
false
null
package sma.tripper.dao import androidx.room.Dao import androidx.room.Query import androidx.room.Transaction import sma.tripper.entity.TripWithEventsEntity @Dao interface TripWithEventsDao { @Transaction @Query("SELECT * FROM trips") fun getTripsWithEvents(): List<TripWithEventsEntity> }
0
Kotlin
0
0
9bafbfcbe13b218d80c0f8c5457ba224a629af83
302
sma-tripper
MIT License
src/main/kotlin/org/n27/routes/ResultRoutes.kt
Narsuf
600,254,893
false
null
package org.n27.routes import io.ktor.http.* import io.ktor.server.application.* import io.ktor.server.request.* import io.ktor.server.response.* import io.ktor.server.routing.* import io.ktor.server.util.* import org.n27.dao.DAOFacade import org.n27.dao.DAOResult import org.n27.models.Result import org.n27.models.wrappers.ResultList fun Route.resultRouting() { val dao: DAOFacade<Result> = DAOResult() route("/result") { get { val results = dao.all() if (results.isNotEmpty()) { call.respond(ResultList(results)) } else { call.respondText("No results found.", status = HttpStatusCode.NotFound) } } get("{id}") { val id = call.parameters.getOrFail<Int>("id").toInt() val result = dao.get(id) ?: return@get call.respondText( "No result with id $id.", status = HttpStatusCode.NotFound ) call.respond(result) } post { val result = call.receive<Result>() dao.add(result)?.let { call.respondRedirect("/result/${it.id}") } } post("{id}") { val id = call.parameters.getOrFail<Int>("id").toInt() val result = call.receive<Result>().apply { this.id = id } dao.edit(result) call.respondRedirect("/result/$id") } delete("{id}") { val id = call.parameters.getOrFail<Int>("id").toInt() if (dao.delete(id)) { call.respondText("Result removed correctly.", status = HttpStatusCode.Accepted) } else { call.respondText("No result with id $id.", status = HttpStatusCode.NotFound) } } } }
0
Kotlin
0
1
2f0aaee9da2682d2b4cf900cdea0eb1e9d8c872b
1,786
Kthor
Apache License 2.0
attribution/src/main/java/com/affise/attribution/parameters/DeviceManufacturerProvider.kt
affise
496,592,599
false
null
package com.affise.attribution.parameters import com.affise.attribution.build.BuildConfigPropertiesProvider import com.affise.attribution.parameters.base.StringPropertyProvider /** * Provider for parameter [Parameters.DEVICE_MANUFACTURER] * * @property propertiesProvider provider for Build properties */ class DeviceManufacturerProvider( private val propertiesProvider: BuildConfigPropertiesProvider ) : StringPropertyProvider() { override fun provide(): String? = propertiesProvider.getManufacturer() }
0
Kotlin
0
3
ed6209e9eff536569c2ce618945365e63c9419fd
520
sdk-android
The Unlicense
zettai_step3_events/src/test/kotlin/com/ubertob/fotf/zettai/commands/ToDoListCommandsTest.kt
uberto
654,026,766
false
null
package com.ubertob.fotf.zettai.commands import com.ubertob.fotf.zettai.domain.* import com.ubertob.fotf.zettai.events.* import org.junit.jupiter.api.Test import strikt.api.expectThat import strikt.assertions.isA import strikt.assertions.isEqualTo import strikt.assertions.isNull internal class ToDoListCommandsTest { val noopFetcher = object : ToDoListUpdatableFetcher { override fun assignListToUser(user: User, list: ToDoList): ToDoList? = null //do nothing override fun get(user: User, listName: ListName): ToDoList? = TODO("not implemented") override fun getAll(user: User): List<ListName>? = TODO("not implemented") } val streamer = ToDoListEventStreamerInMemory() val eventStore = ToDoListEventStore(streamer) val handler = ToDoListCommandHandler(eventStore, noopFetcher) fun handle(cmd: ToDoListCommand): List<ToDoListEvent>? = handler(cmd)?.let(eventStore) val name = randomListName() val user = randomUser() @Test fun `CreateToDoList generate the correct event`() { val cmd = CreateToDoList(randomUser(), randomListName()) val entityRetriever: ToDoListRetriever = object : ToDoListRetriever { override fun retrieveByName(user: User, listName: ListName) = InitialState } val handler = ToDoListCommandHandler(entityRetriever, noopFetcher) val res = handler(cmd)?.single() expectThat(res).isEqualTo(ListCreated(cmd.id, cmd.user, cmd.name)) } @Test fun `Add list fails if the user has already a list with same name`() { val cmd = CreateToDoList(user, name) val res = handle(cmd)?.single() expectThat(res).isA<ListCreated>() val duplicatedRes = handle(cmd) expectThat(duplicatedRes).isNull() } @Test fun `Add items fails if the list doesn't exists`() { val cmd = AddToDoItem(user, name, randomItem()) val res = handle(cmd) expectThat(res).isNull() } }
0
Kotlin
0
2
2f80b8f4022cacbf6d7a92919224f98d37453a4d
2,001
fotf
MIT License
cottontaildb-dbms/src/main/kotlin/org/vitrivr/cottontail/dbms/execution/operators/sources/EntitySampleOperator.kt
vitrivr
160,775,368
false
{"Kotlin": 2317843, "Dockerfile": 548}
package org.vitrivr.cottontail.dbms.execution.operators.sources import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.flow import org.slf4j.Logger import org.slf4j.LoggerFactory import org.vitrivr.cottontail.core.basics.Record import org.vitrivr.cottontail.core.database.ColumnDef import org.vitrivr.cottontail.core.queries.GroupId import org.vitrivr.cottontail.core.queries.binding.Binding import org.vitrivr.cottontail.dbms.entity.Entity import org.vitrivr.cottontail.dbms.entity.EntityTx import org.vitrivr.cottontail.dbms.execution.operators.basics.Operator import org.vitrivr.cottontail.dbms.execution.transactions.TransactionContext import org.vitrivr.cottontail.dbms.queries.context.DefaultQueryContext import java.util.* /** * An [Operator.SourceOperator] that samples an [Entity] and streams all [Record]s found within. * * @author <NAME> * @version 1.6.0 */ class EntitySampleOperator(groupId: GroupId, val entity: EntityTx, val fetch: List<Pair<Binding.Column, ColumnDef<*>>>, val p: Float, val seed: Long) : Operator.SourceOperator(groupId) { companion object { /** [Logger] instance used by [EntitySampleOperator]. */ private val LOGGER: Logger = LoggerFactory.getLogger(EntitySampleOperator::class.java) } /** The [ColumnDef] fetched by this [EntitySampleOperator]. */ override val columns: List<ColumnDef<*>> = this.fetch.map { it.first.column } /** * Converts this [EntitySampleOperator] to a [Flow] and returns it. * * @param context The [DefaultQueryContext] used for execution. * @return [Flow] representing this [EntitySampleOperator]. */ override fun toFlow(context: TransactionContext): Flow<Record> { val fetch = this.fetch.map { it.second }.toTypedArray() val columns = this.fetch.map { it.first.column }.toTypedArray() val random = SplittableRandom([email protected]) return flow { val cursor = [email protected](fetch) var read = 0 while (cursor.moveNext()) { if (random.nextDouble(0.0, 1.0) <= [email protected]) { val record = cursor.value() for ((i,c) in columns.withIndex()) { /* Replace column designations. */ record.columns[i] = c } [email protected]().first.context.update(record) /* Important: Make new record available to binding context. */ emit(record) read += 1 } } cursor.close() LOGGER.debug("Read $read entries from ${[email protected]}.") } } }
16
Kotlin
18
26
50cc8526952f637d685da9d18f4b1630b782f1ff
2,756
cottontaildb
MIT License
app/src/main/java/com/bqliang/nfushortcuts/model/Weather.kt
bqliang
371,436,812
false
null
package com.bqliang.nfushortcuts.model data class Weather(val realtime: RealtimeResponse.Realtime) { }
0
Kotlin
0
1
d7e9dabf1ab054f1aed25ba29fcd235c8b5bacd2
103
NFU-shortcuts
Apache License 2.0
app/src/main/java/com/kirakishou/photoexchange/di/module/GsonModule.kt
chanyaz
143,974,243
true
{"Kotlin": 639219}
package com.kirakishou.photoexchange.di.module import com.google.gson.Gson import com.google.gson.GsonBuilder import com.kirakishou.photoexchange.helper.gson.MyGson import com.kirakishou.photoexchange.helper.gson.MyGsonImpl import dagger.Module import dagger.Provides import retrofit2.converter.gson.GsonConverterFactory import javax.inject.Singleton /** * Created by kirakishou on 3/17/2018. */ @Module class GsonModule { @Singleton @Provides fun provideGson(): Gson { return GsonBuilder() .excludeFieldsWithoutExposeAnnotation() .setPrettyPrinting() .create() } @Singleton @Provides fun provideGsonConverterFactory(gson: Gson): GsonConverterFactory { return GsonConverterFactory.create(gson) } @Singleton @Provides fun provideMyGson(gson: Gson): MyGson { return MyGsonImpl(gson) } }
0
Kotlin
0
0
078a56b34b84f7121cac7ffac5ac7d6a0e39fb9a
899
photoexchange-android
Do What The F*ck You Want To Public License
app/src/main/java/io/github/joaogouveia89/checkmarket/core/presentation/topBars/CheckMarketAppBar.kt
joaogouveia89
842,192,758
false
{"Kotlin": 66023}
package io.github.joaogouveia89.checkmarket.core.presentation.topBars import androidx.annotation.StringRes import androidx.compose.material3.ExperimentalMaterial3Api import androidx.compose.material3.Text import androidx.compose.material3.TopAppBar import androidx.compose.runtime.Composable import androidx.compose.ui.Modifier import androidx.compose.ui.graphics.Color import androidx.compose.ui.graphics.Color.Companion.White import androidx.compose.ui.res.stringResource import androidx.compose.ui.tooling.preview.Preview import io.github.joaogouveia89.checkmarket.R @OptIn(ExperimentalMaterial3Api::class) @Composable fun CheckMarketAppBar( modifier: Modifier = Modifier, @StringRes title: Int, textColor: Color = White ) { TopAppBar( modifier = modifier, title = { Text( text = stringResource(id = title), color = textColor ) }, colors = checkMarketTopBarColors(), ) } @Preview(showBackground = true) @Composable fun CheckMarketAppBarPreview() { CheckMarketAppBar(title = R.string.app_name_top_bar_title) }
0
Kotlin
0
0
deb745cc649b00ac56955fc1d6a2e4a39ecaaa58
1,127
CheckMarket
MIT License
KotlinQuiz/app/src/main/java/es/sublimestudio/kotlinquiz/views/QuestionsFragment.kt
albertogparrado
381,375,674
false
null
package es.sublimestudio.kotlinquiz.views import android.os.Bundle import android.os.CountDownTimer import android.os.Handler import android.os.Looper import android.util.Log import androidx.fragment.app.Fragment import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.Button import android.widget.Toast import androidx.core.content.ContextCompat import es.sublimestudio.kotlinquiz.DataHolder import es.sublimestudio.kotlinquiz.R import es.sublimestudio.kotlinquiz.databinding.FragmentQuestionsBinding import es.sublimestudio.kotlinquiz.models.Answer import es.sublimestudio.kotlinquiz.models.Question class QuestionsFragment : Fragment() { private var _binding: FragmentQuestionsBinding? = null private val b get() = _binding!! //VARIABLES val TIME_MAX = 10000 val allQuestions: ArrayList<Question> = arrayListOf() var pos = 0 val allButtons: ArrayList<Button> = arrayListOf() var currentPoints = TIME_MAX lateinit var timer: CountDownTimer override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View { _binding = FragmentQuestionsBinding.inflate(inflater, container, false) val view = b.root return view } fun initData() { DataHolder.points = 0 allQuestions.addAll(DataHolder.questions.questions) } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) initData() b.progressTime.max = TIME_MAX b.progressTime.progress = TIME_MAX startProgress() nextQuestion() b.btn1.setOnClickListener { checkAnswer(b.btn1) } b.btn2.setOnClickListener { checkAnswer(b.btn2) } b.btn3.setOnClickListener { checkAnswer(b.btn3) } b.btn4.setOnClickListener { checkAnswer(b.btn4) } } ///////////////////////////////// FUNCIONES //////////////////////////////////////// //Barra de progreso fun startProgress() { timer = object : CountDownTimer(TIME_MAX.toLong(), 50) { override fun onTick(millisUntilFinished: Long) { currentPoints = millisUntilFinished.toInt() b.progressTime.setProgress(millisUntilFinished.toInt(), true) } override fun onFinish() { b.progressTime.setProgress(0, true) pos++ nextQuestion() } } timer.start() } //Siguiente pregunta -> cambiar pregunta + botones + asignar TAGs a bt fun nextQuestion() { if (allQuestions.size > pos) { val currQuestion = allQuestions[pos] b.titleQuestion.text = currQuestion.title b.btn1.text = currQuestion.answers[0].title b.btn1.tag = 0 b.btn2.text = currQuestion.answers[1].title b.btn2.tag = 1 b.btn3.text = currQuestion.answers[2].title b.btn3.tag = 2 b.btn4.text = currQuestion.answers[3].title b.btn4.tag = 3 allButtons.clear() allButtons.add(b.btn1) allButtons.add(b.btn2) allButtons.add(b.btn3) allButtons.add(b.btn4) resetButtons() timer.start() } else { Log.v("DALE", "Ya no hay más preguntas") Toast.makeText(requireContext(), "Has terminado la partida", Toast.LENGTH_LONG).show() requireActivity().supportFragmentManager.beginTransaction().replace(R.id.mainContainer, ReviewFragment()).commit() } } //Pregunta correcta -> Al tocar una respuesta -> parar tiempo + comprobar Correcta + cambio color + cancel other bt fun checkAnswer(btnSelected: Button) { timer.cancel() Handler(Looper.getMainLooper()).postDelayed({ pos++ nextQuestion() }, 2000) val currQuestion = allQuestions[pos] val isCorrect = currQuestion.answers[btnSelected.tag as Int].isCorrect if (isCorrect) { DataHolder.points += currentPoints btnSelected.setBackgroundColor( ContextCompat.getColor( requireContext(), R.color.success ) ) } else { btnSelected.setBackgroundColor( ContextCompat.getColor( requireContext(), R.color.failure ) ) } disableButtons(btnSelected) } //Desactivar bt -> otros bt poner en ver o gris fun disableButtons(btnSelected: Button) { allButtons.forEach { currentButton -> currentButton.isClickable = false val currQuestion = allQuestions[pos] val isCorrect = currQuestion.answers[currentButton.tag as Int].isCorrect if (btnSelected != currentButton) { if (isCorrect) { currentButton.setBackgroundColor( ContextCompat.getColor( requireContext(), R.color.success ) ) } else { currentButton.setBackgroundColor( ContextCompat.getColor( requireContext(), R.color.grey ) ) } } } } //Resetear bt -> poner clickables + color original fun resetButtons() { allButtons.forEach { button -> button.isClickable = true button.setBackgroundColor(ContextCompat.getColor(requireContext(), R.color.purple_500)) } } override fun onDestroyView() { super.onDestroyView() _binding = null } }
0
Kotlin
0
0
0d8d41b373c2b376315ea76a45dfc1926563b054
6,067
kotlinQuiz
MIT License
services/tmdb/src/main/kotlin/com/illiarb/tmdbclient/services/tmdb/di/NetworkInterceptor.kt
ilya-rb
152,124,194
false
null
package com.illiarb.tmdbclient.services.tmdb.di import javax.inject.Qualifier @Qualifier @Retention(AnnotationRetention.RUNTIME) annotation class NetworkInterceptor
0
null
1
5
2a316e72c6ce68759627e52a749b7f02d91b2787
166
Tmdb-Client
MIT License
notary-btc-integration-test/src/integration-test/kotlin/integration/btc/environment/BtcNotaryTestEnvironment.kt
d3ledger
183,226,939
false
null
/* * Copyright D3 Ledger, Inc. All Rights Reserved. * SPDX-License-Identifier: Apache-2.0 */ package integration.btc.environment import com.d3.btc.config.BitcoinConfig import com.d3.btc.deposit.config.BTC_DEPOSIT_SERVICE_NAME import com.d3.btc.deposit.config.BtcDepositConfig import com.d3.btc.deposit.expansion.DepositServiceExpansion import com.d3.btc.deposit.handler.NewBtcChangeAddressDepositHandler import com.d3.btc.deposit.init.BtcNotaryInitialization import com.d3.btc.deposit.service.BtcWalletListenerRestartService import com.d3.btc.handler.NewBtcClientRegistrationHandler import com.d3.btc.peer.SharedPeerGroup import com.d3.btc.provider.BtcChangeAddressProvider import com.d3.btc.provider.BtcRegisteredAddressesProvider import com.d3.btc.provider.network.BtcRegTestConfigProvider import com.d3.btc.storage.BtcAddressStorage import com.d3.btc.wallet.WalletInitializer import com.d3.btc.wallet.loadAutoSaveWallet import com.d3.chainadapter.client.RMQConfig import com.d3.chainadapter.client.ReliableIrohaChainListener import com.d3.commons.config.loadRawLocalConfigs import com.d3.commons.expansion.ServiceExpansion import com.d3.commons.model.IrohaCredential import com.d3.commons.notary.NotaryImpl import com.d3.commons.registration.NotaryRegistrationConfig import com.d3.commons.sidechain.SideChainEvent import com.d3.commons.sidechain.iroha.util.impl.IrohaQueryHelperImpl import com.d3.commons.util.createPrettySingleThreadPool import com.d3.reverse.adapter.ReverseChainAdapter import com.d3.reverse.client.ReliableIrohaConsumerImpl import com.d3.reverse.client.ReverseChainAdapterClientConfig import com.d3.reverse.config.ReverseChainAdapterConfig import integration.helper.BtcIntegrationHelperUtil import io.reactivex.Observable import io.reactivex.subjects.PublishSubject import jp.co.soramitsu.bootstrap.changelog.ChangelogInterface import jp.co.soramitsu.iroha.java.IrohaAPI import jp.co.soramitsu.iroha.java.Utils import org.bitcoinj.wallet.Wallet import java.io.Closeable import java.io.File /** * Bitcoin notary service testing environment */ class BtcNotaryTestEnvironment( private val integrationHelper: BtcIntegrationHelperUtil, private val registrationConfig: NotaryRegistrationConfig, testName: String = "", val notaryConfig: BtcDepositConfig = integrationHelper.configHelper.createBtcDepositConfig( testName ), val bitcoinConfig: BitcoinConfig = integrationHelper.configHelper.createBitcoinConfig(testName), private val notaryCredential: IrohaCredential = IrohaCredential( notaryConfig.notaryCredential.accountId, Utils.parseHexKeypair( notaryConfig.notaryCredential.pubkey, notaryConfig.notaryCredential.privkey ) ) ) : Closeable { private val reverseAdapterConfig = loadRawLocalConfigs( "reverse-chain-adapter", ReverseChainAdapterConfig::class.java, "reverse-chain-adapter.properties" ) private val reverseChainAdapterClientConfig = object : ReverseChainAdapterClientConfig { override val rmqHost = reverseAdapterConfig.rmqHost override val rmqPort = reverseAdapterConfig.rmqPort override val transactionQueueName = reverseAdapterConfig.transactionQueueName } private val irohaAPI = IrohaAPI(notaryConfig.iroha.hostname, notaryConfig.iroha.port) private val queryHelper = IrohaQueryHelperImpl(irohaAPI, notaryCredential.accountId, notaryCredential.keyPair) private val btcRegisteredAddressesProvider = BtcRegisteredAddressesProvider( queryHelper, notaryConfig.registrationAccount, notaryConfig.notaryCredential.accountId ) val btcAddressGenerationConfig = integrationHelper.configHelper.createBtcAddressGenerationConfig(registrationConfig, 0) private val btcNetworkConfigProvider = BtcRegTestConfigProvider() private val transferWallet by lazy { loadAutoSaveWallet(notaryConfig.btcTransferWalletPath) } private val rmqConfig = loadRawLocalConfigs("rmq", RMQConfig::class.java, "rmq.properties") private val depositReliableIrohaChainListener = ReliableIrohaChainListener( rmqConfig, notaryConfig.irohaBlockQueue, consumerExecutorService = createPrettySingleThreadPool( BTC_DEPOSIT_SERVICE_NAME, "rmq-consumer" ), autoAck = true ) val btcAddressStorage by lazy { BtcAddressStorage(btcRegisteredAddressesProvider, btcChangeAddressProvider) } private val depositHandlers by lazy { listOf( NewBtcClientRegistrationHandler( btcNetworkConfigProvider, transferWallet, btcAddressStorage, notaryConfig.registrationAccount ), NewBtcChangeAddressDepositHandler(btcAddressStorage, notaryConfig) ) } private val peerGroup by lazy { createPeerGroup(transferWallet) } private val btcChangeAddressProvider = BtcChangeAddressProvider( queryHelper, notaryConfig.mstRegistrationAccount, notaryConfig.changeAddressesStorageAccount ) private val walletInitializer by lazy { WalletInitializer(btcRegisteredAddressesProvider, btcChangeAddressProvider) } fun createPeerGroup(transferWallet: Wallet): SharedPeerGroup { return integrationHelper.getPeerGroup( transferWallet, btcNetworkConfigProvider, bitcoinConfig.blockStoragePath, BitcoinConfig.extractHosts(bitcoinConfig), walletInitializer ) } private val confidenceExecutorService = createPrettySingleThreadPool(BTC_DEPOSIT_SERVICE_NAME, "tx-confidence-listener") private val btcEventsSource = PublishSubject.create<SideChainEvent.PrimaryBlockChainEvent>() private val btcEventsObservable: Observable<SideChainEvent.PrimaryBlockChainEvent> = btcEventsSource private val reverseChainAdapterDelegate = lazy { ReverseChainAdapter(reverseAdapterConfig, irohaAPI) } val reverseChainAdapter by reverseChainAdapterDelegate private val reliableIrohaNotaryConsumer = ReliableIrohaConsumerImpl(reverseChainAdapterClientConfig, notaryCredential, irohaAPI, fireAndForget = true) private val notary = NotaryImpl( reliableIrohaNotaryConsumer, notaryCredential, btcEventsObservable ) private val btcWalletListenerRestartService by lazy { BtcWalletListenerRestartService( btcAddressStorage, bitcoinConfig, confidenceExecutorService, peerGroup, btcEventsSource ) } val btcNotaryInitialization by lazy { BtcNotaryInitialization( peerGroup, transferWallet, notaryConfig, bitcoinConfig, notary, btcEventsSource, btcWalletListenerRestartService, confidenceExecutorService, btcNetworkConfigProvider, DepositServiceExpansion( irohaAPI, ServiceExpansion( integrationHelper.accountHelper.expansionTriggerAccount.accountId, ChangelogInterface.superuserAccountId, irohaAPI ), notaryCredential ), depositReliableIrohaChainListener, btcAddressStorage, depositHandlers ) } override fun close() { if (reverseChainAdapterDelegate.isInitialized()) { reverseChainAdapter.close() } integrationHelper.close() irohaAPI.close() confidenceExecutorService.shutdownNow() depositReliableIrohaChainListener.close() //Clear bitcoin blockchain folder File(bitcoinConfig.blockStoragePath).deleteRecursively() btcNotaryInitialization.close() } }
2
Kotlin
4
3
f1b4b11e740951f3e2ab9e8dc958c5d8ce22f536
7,944
d3-btc
Apache License 2.0
libCommon/src/main/java/com/tobery/lib/util/navigation/FragmentNavigatorHideShow.kt
Tobeyr1
505,471,556
false
{"Gradle": 4, "Java Properties": 2, "Shell": 1, "Text": 1, "Ignore List": 4, "Batchfile": 1, "Markdown": 1, "Proguard": 2, "Java": 88, "XML": 102, "HTML": 1, "INI": 1, "Kotlin": 6}
package com.tobery.lib.util.navigation import android.content.Context import android.util.Log import androidx.annotation.IdRes import androidx.fragment.app.Fragment import androidx.fragment.app.FragmentManager import androidx.lifecycle.Lifecycle import androidx.navigation.NavBackStackEntry import androidx.navigation.NavOptions import androidx.navigation.Navigator import androidx.navigation.fragment.FragmentNavigator @Navigator.Name("fragment_keep") class FragmentNavigatorHideShow( private val mContext: Context, private val mFragmentManager: FragmentManager, private val mContainerId: Int ) : FragmentNavigator(mContext, mFragmentManager, mContainerId) { private var savedIds: MutableSet<String>? = null init { try { val field = FragmentNavigator::class.java.getDeclaredField("savedIds") field.isAccessible = true savedIds = field[this] as MutableSet<String> } catch (e: Exception) { Log.d(TAG, "反射获取SavedIds失败: ${e.toString()}") } } override fun navigate( entries: List<NavBackStackEntry>, navOptions: NavOptions?, navigatorExtras: Navigator.Extras? ) { if (mFragmentManager.isStateSaved) { Log.i( TAG, "Ignoring navigate() call: FragmentManager has already saved its state" ) return } for (entry in entries) { navigate(entry, navOptions, navigatorExtras) } } private fun navigate( entry: NavBackStackEntry, navOptions: NavOptions?, navigatorExtras: Navigator.Extras? ) { val backStack = state.backStack.value val initialNavigation = backStack.isEmpty() val restoreState = ( navOptions != null && !initialNavigation && navOptions.shouldRestoreState() && savedIds?.remove(entry.id) == true ) if (restoreState) { // Restore back stack does all the work to restore the entry mFragmentManager.restoreBackStack(entry.id) state.push(entry) return } val destination = entry.destination as Destination val args = entry.arguments var className = destination.className if (className[0] == '.') { className = mContext.packageName + className } //Modify 修改 //val frag = mFragmentManager.fragmentFactory.instantiate(mContext.classLoader, className) val ft = mFragmentManager.beginTransaction() var enterAnim = navOptions?.enterAnim ?: -1 var exitAnim = navOptions?.exitAnim ?: -1 var popEnterAnim = navOptions?.popEnterAnim ?: -1 var popExitAnim = navOptions?.popExitAnim ?: -1 if (enterAnim != -1 || exitAnim != -1 || popEnterAnim != -1 || popExitAnim != -1) { enterAnim = if (enterAnim != -1) enterAnim else 0 exitAnim = if (exitAnim != -1) exitAnim else 0 popEnterAnim = if (popEnterAnim != -1) popEnterAnim else 0 popExitAnim = if (popExitAnim != -1) popExitAnim else 0 ft.setCustomAnimations(enterAnim, exitAnim, popEnterAnim, popExitAnim) } //region 添加的代码 var frag: Fragment? = mFragmentManager.primaryNavigationFragment if (frag != null) { ft.setMaxLifecycle(frag, Lifecycle.State.STARTED) ft.hide(frag) } val tag = destination.id.toString() frag = mFragmentManager.findFragmentByTag(tag) if (frag != null) { ft.setMaxLifecycle(frag, Lifecycle.State.RESUMED) ft.show(frag) } else { frag = mFragmentManager.fragmentFactory.instantiate(mContext.classLoader, className) frag.arguments = args ft.add(mContainerId, frag, tag) } //endregion //Modify 修改 //ft.replace(mContainerId, frag) ft.setPrimaryNavigationFragment(frag) @IdRes val destId = destination.id // TODO Build first class singleTop behavior for fragments val isSingleTopReplacement = ( navOptions != null && !initialNavigation && navOptions.shouldLaunchSingleTop() && backStack.last().destination.id == destId ) val isAdded = when { initialNavigation -> { true } isSingleTopReplacement -> { // Single Top means we only want one instance on the back stack if (backStack.size > 1) { // If the Fragment to be replaced is on the FragmentManager's // back stack, a simple replace() isn't enough so we // remove it from the back stack and put our replacement // on the back stack in its place mFragmentManager.popBackStack( entry.id, FragmentManager.POP_BACK_STACK_INCLUSIVE ) ft.addToBackStack(entry.id) } false } else -> { ft.addToBackStack(entry.id) true } } if (navigatorExtras is Extras) { for ((key, value) in navigatorExtras.sharedElements) { ft.addSharedElement(key, value) } } ft.setReorderingAllowed(true) ft.commit() // The commit succeeded, update our view of the world if (isAdded) { state.push(entry) } } companion object { private const val TAG = "HSFragmentNavigator" } }
0
Java
1
13
541bcfb0504dfb810d4113bfca647129419a5052
5,768
JianYiMusic
Apache License 2.0
src/main/java/com/better/alarm/background/KlaxonServiceDelegate.kt
imidhun
113,416,052
true
{"INI": 1, "YAML": 1, "Shell": 1, "Markdown": 1, "Batchfile": 1, "Gradle": 1, "Ignore List": 1, "Kotlin": 10, "Java": 81, "XML": 126, "Java Properties": 1}
package com.rafali.alarm.background import android.content.Context import android.content.Intent import android.content.res.Resources import android.media.AudioManager import android.media.MediaPlayer import android.media.RingtoneManager import android.net.Uri import android.os.PowerManager import android.telephony.TelephonyManager import com.rafali.alarm.R import com.rafali.alarm.interfaces.Alarm import com.rafali.alarm.interfaces.IAlarmsManager import com.rafali.alarm.interfaces.Intents import com.rafali.alarm.logger.Logger import com.rafali.alarm.wakelock.WakeLockManager import io.reactivex.Observable import io.reactivex.Scheduler import io.reactivex.disposables.CompositeDisposable import io.reactivex.disposables.Disposable import io.reactivex.disposables.Disposables import io.reactivex.functions.BiFunction import java.util.concurrent.TimeUnit import kotlin.properties.Delegates /** * Created by Yuriy on 20.08.2017. */ class KlaxonServiceDelegate( private val log: Logger, pm: PowerManager, private val wakeLocks: WakeLockManager, private val alarms: IAlarmsManager, private val context: Context, private val resources: Resources, private val callState: Observable<Int>, private val prealarmVolume: Observable<Int>, private val fadeInTimeInSeconds: Observable<Int>, private val callback: KlaxonServiceCallback, private val scheduler: Scheduler ) : KlaxonService.KlaxonDelegate { private val disposables = CompositeDisposable() private var volume: Volume by Delegates.notNull() private var wakeLock: PowerManager.WakeLock by Delegates.notNull() private var player: MediaPlayer? = null var callStateSub: Disposable = Disposables.disposed() init { volume = Volume() player = null wakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "KlaxonService") wakeLock.acquire() } override fun onDestroy() { player?.stopAndCleanup() disposables.dispose() wakeLock.release() log.d("Service destroyed") } override fun onStartCommand(intent: Intent): Boolean { wakeLocks.releasePartialWakeLock(intent) val action: String = intent.action log.d(intent.action) when (action) { Intents.ALARM_ALERT_ACTION, Intents.ALARM_PREALARM_ACTION -> { val alarm = alarms.getAlarm(intent.getIntExtra(Intents.EXTRA_ID, -1)) val type = if (action == Intents.ALARM_PREALARM_ACTION) Type.PREALARM else Type.NORMAL // Listen for incoming calls to kill the alarm. callStateSub.dispose() callStateSub = callState .map { it != TelephonyManager.CALL_STATE_IDLE } .distinctUntilChanged() .skip(1)//ignore the first one .subscribe { callActive -> if (callActive) { log.d("Call has started. Mute.") volume.mute() } else { log.d("Call has ended. fadeInFast.") if (!alarm.isSilent) { initializePlayer(alarm.getAlertOrDefault()) volume.fadeInFast() } } } onAlarm(alarm, type) } Intents.ACTION_START_PREALARM_SAMPLE -> onStartAlarmSample() Intents.ACTION_MUTE -> volume.mute() Intents.ACTION_DEMUTE -> volume.fadeInFast() else -> { volume.mute() callback.stopSelf() } } return when (action) { Intents.ALARM_ALERT_ACTION, Intents.ALARM_PREALARM_ACTION, Intents.ACTION_START_PREALARM_SAMPLE, Intents.ACTION_MUTE, Intents.ACTION_DEMUTE -> true else -> false } } private fun onAlarm(alarm: Alarm, type: Type) { volume.mute() volume.type = type if (!alarm.isSilent) { initializePlayer(alarm.getAlertOrDefault()) volume.fadeInAsSetInSettings() } } private fun onStartAlarmSample() { volume.mute() volume.type = Type.PREALARM // if already playing do nothing. In this case signal continues. if (player == null || !player!!.isPlaying) { initializePlayer(callback.getDefaultUri(RingtoneManager.TYPE_ALARM)) } volume.apply() } /** * Inits player and sets volume to 0 * @param alert */ private fun initializePlayer(alert: Uri) { // stop() checks to see if we are already playing. player?.stopAndCleanup() player = callback.createMediaPlayer().apply { setOnErrorListener { mp, what, extra -> log.e("Error occurred while playing audio.") volume.mute() mp.stop() mp.release() player = null true } } volume.mute() callState.map { it != TelephonyManager.CALL_STATE_IDLE }.firstOrError().subscribe { inCall -> // Check if we are in a call. If we are, use the in-call alarm // resource at a low targetVolume to not disrupt the call. if (inCall) { log.d("Using the in-call alarm") player?.setDataSourceFromResource(resources, R.raw.in_call_alarm) player?.startAlarm() } else { player?.run { try { setDataSource(context, alert) startAlarm() } catch (ex: Exception) { log.w("Using the fallback ringtone") // The alert may be on the sd card which could be busy right // now. Use the fallback ringtone. // Must reset the media player to clear the error state. reset() setDataSourceFromResource(resources, R.raw.fallbackring) startAlarm() } } } } } private fun Alarm.getAlertOrDefault(): Uri { // Fall back on the default alarm if the database does not have an // alarm stored. return if (alert == null) { val default: Uri? = callback.getDefaultUri(RingtoneManager.TYPE_ALARM) log.d("Using default alarm: " + default.toString()) //TODO("Check this") default!! } else { alert } } // Do the common stuff when starting the alarm. @Throws(java.io.IOException::class, IllegalArgumentException::class, IllegalStateException::class) private fun MediaPlayer.startAlarm() { // do not play alarms if stream targetVolume is 0 // (typically because ringer mode is silent). //if (audioManager.getStreamVolume(AudioManager.STREAM_ALARM) != 0) { setAudioStreamType(AudioManager.STREAM_ALARM) isLooping = true prepare() start() //} } @Throws(java.io.IOException::class) private fun MediaPlayer.setDataSourceFromResource(resources: Resources, res: Int) { resources.openRawResourceFd(res)?.run { setDataSource(fileDescriptor, startOffset, length) close() } } private fun MediaPlayer.setPerceptedVolume(percepted: Float) { val volume = percepted.squared() //log.d("volume=$volume") setVolume(volume, volume) } /** * Stops alarm audio */ private fun MediaPlayer.stopAndCleanup() { log.d("stopping media player") try { if (isPlaying) stop() release() } finally { player = null } } enum class Type { NORMAL, PREALARM } private inner class Volume internal constructor() { private val FAST_FADE_IN_TIME = 5000 private val FADE_IN_STEPS = 100 // Volume suggested by media team for in-call alarms. private val IN_CALL_VOLUME = 0.125f private val SILENT = 0f internal var type = Type.NORMAL private var timer: Disposable = Disposables.disposed() /** * Instantly apply the targetVolume. To fade in use [.fadeInAsSetInSettings] */ fun apply() { fadeIn(250) } /** * Fade in to set targetVolume */ fun fadeInAsSetInSettings() { fadeInTimeInSeconds.firstOrError().subscribe(this::fadeIn) } fun fadeInFast() { fadeIn(FAST_FADE_IN_TIME) } fun mute() { player?.setPerceptedVolume(SILENT) timer.dispose() } private fun fadeIn(time: Int) { val fadeInTime: Long = time.toLong() mute() player?.setPerceptedVolume(SILENT) val fadeInStep: Long = fadeInTime / FADE_IN_STEPS val fadeIn = Observable.interval(fadeInStep, TimeUnit.MILLISECONDS, scheduler) .map { it * fadeInStep } .takeWhile { it <= fadeInTime } .map { elapsed -> elapsed.toFloat() / fadeInTime } .map { fraction -> fraction.squared() } .doOnComplete { log.d("Completed fade-in in $time milliseconds") } timer = Observable.combineLatest( observeVolume(type), fadeIn, BiFunction<Float, Float, Float> { targetVolume, frqs -> frqs * targetVolume }) .subscribe { perceptedVolume -> player?.setPerceptedVolume(perceptedVolume) } } /** * Gets 1f doe NORMAL and a fraction of 0.5f for PREALARM */ private fun observeVolume(type: Type): Observable<Float> { val MAX_VOLUME = 11 return if (type == Type.NORMAL) Observable.just(1f) else prealarmVolume.map { it .plus(1)//0 is 1 .coerceAtMost(MAX_VOLUME) .toFloat() .div(MAX_VOLUME) .div(2) .apply { log.d("targetVolume=$this") } } } } fun Float.squared() = this * this }
0
Java
0
1
7a9b32e5573eac2f90f0710a58ee2eb1a547222c
10,760
AlarmClock
Apache License 2.0
MyJetPackApplication/businesses/business-gesture/src/main/java/com/example/myjetpackapplication/business/gesture/GestureViewModel.kt
seelikes
154,868,585
false
{"Markdown": 4, "Batchfile": 11, "Ignore List": 58, "JSON": 5, "Text": 1, "Gradle": 72, "reStructuredText": 1, "Java Properties": 14, "Shell": 8, "Proguard": 42, "Java": 57, "XML": 265, "INI": 29, "Kotlin": 311, "C++": 1, "CMake": 1, "Groovy": 26, "Fluent": 40, "FreeMarker": 11}
package com.example.myjetpackapplication.business.gesture import androidx.databinding.ObservableField import androidx.databinding.ObservableInt import androidx.lifecycle.Observer import androidx.lifecycle.ViewModelProviders import com.example.myjetpackapplication.business.gesture.R import com.example.myjetpackapplication.business.gesture.databinding.ActivityGestureBinding import com.example.myjetpackapplication.business.gesture.info.GestureInfo import com.github.seelikes.android.mvvm.basic.BasicHostViewModel class GestureViewModel(host: GestureActivity, binding: ActivityGestureBinding) : BasicHostViewModel<GestureViewModel, GestureActivity, ActivityGestureBinding>(host, binding) { val title = ObservableInt(R.string.gesture_title) val history = ObservableField<String>() init { ViewModelProviders.of(host).get(GestureDataModel::class.java).history.observe(host, Observer<List<GestureInfo>> { history.set(it.joinToString( separator = "\n", transform = { gestureInfo -> String.format("%s %s", gestureInfo.time, gestureInfo.gesture) } )) }) } }
1
null
1
1
7b3bc00c2e98f11b0798a97474a28fb63c0b53ae
1,177
MyAndroidSet
MIT License
src/main/java/org/mitallast/queue/crdt/routing/Resource.kt
mitallast
23,783,024
false
null
package org.mitallast.queue.crdt.routing import org.mitallast.queue.common.codec.Codec import org.mitallast.queue.common.codec.Message enum class ResourceType { LWWRegister, GCounter, GSet, OrderedGSet } class Resource(val id: Long, val type: ResourceType) : Message { companion object { val codec = Codec.of( ::Resource, Resource::id, Resource::type, Codec.longCodec(), Codec.enumCodec(ResourceType::class.java) ) } }
5
null
6
22
05161d99d10f6cd9c1d8c69ae5d88d5993297a28
510
netty-queue
MIT License
app/src/main/java/com/tglt/notepad/di/NotepadModule.kt
vietnux
460,743,350
false
null
/* Copyright 2021 <NAME> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.tglt.notepad.di import android.content.Context import androidx.room.Room import com.tglt.notepad.data.NotepadDatabase import dagger.Module import dagger.Provides import dagger.hilt.InstallIn import dagger.hilt.android.qualifiers.ApplicationContext import dagger.hilt.components.SingletonComponent @InstallIn(SingletonComponent::class) @Module class NotepadModule { @Provides fun provideDatabase(@ApplicationContext context: Context) = Room.databaseBuilder(context, NotepadDatabase::class.java, "notepad").build() @Provides fun provideDAO(db: NotepadDatabase) = db.getDAO() }
1
null
1
1
9fd4e5a0baa5a8c5b863a1c0d2976c4712236966
1,203
Notepad
Apache License 2.0
app/src/main/java/com/afi/minby/home/settings/SettingsAdapter.kt
safall
241,105,061
false
null
package com.afi.minby.home.settings import android.view.View import android.view.ViewGroup import androidx.recyclerview.widget.RecyclerView import com.afi.minby.R import com.afi.minby.core.inflate import com.afi.minby.home.homemenu.AdapterCallback import kotlinx.android.synthetic.main.settings_item_text.view.* class SettingsAdapter(var items: List<SettingsItem>, private var itemCallback: AdapterCallback) : RecyclerView.Adapter<SettingsAdapter.SettingsItemViewHolder>() { override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): SettingsItemViewHolder { return SettingsItemViewHolder( parent.context.inflate(R.layout.settings_item_text, parent, false), itemCallback ) } override fun onBindViewHolder(holder: SettingsItemViewHolder, position: Int) { holder.bind(items[position]) } override fun getItemCount(): Int { return items.size } class SettingsItemViewHolder(val view: View, private val itemCallback: AdapterCallback) : RecyclerView.ViewHolder(view) { fun bind(item: SettingsItem) { itemView.title.text = itemView.context.getText(item.title) itemView.setOnClickListener { itemCallback.onItemClicked(item) } } } }
10
null
1
1
51e9b15d643de1571a6382584bfb0e37f587bf47
1,305
minby
Apache License 2.0
compose-designer/testSrc/com/android/tools/idea/compose/pickers/preview/property/DeviceConfigTest.kt
JetBrains
60,701,247
false
null
/* * Copyright (C) 2021 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.android.tools.idea.compose.pickers.preview.property import com.android.tools.preview.config.DeviceConfig import com.android.tools.preview.config.DimUnit import com.android.tools.preview.config.MutableDeviceConfig import com.android.tools.preview.config.Orientation import com.android.tools.preview.config.Shape import com.android.tools.preview.config.toMutableConfig import org.junit.Assert.assertEquals import org.junit.Assert.assertFalse import org.junit.Assert.assertNull import org.junit.Assert.assertTrue import org.junit.Test import kotlin.test.assertNotNull internal class DeviceConfigTest { @Test fun parseTest() { var config = parseDeviceSpec(null) assertNull(config) config = parseDeviceSpec("spec:shape=Normal,width=120,height=240,unit=px,dpi=480") assertNotNull(config) assertNull(config.deviceId) assertEquals(120f, config.width) assertEquals(240f, config.height) assertEquals(DimUnit.px, config.dimUnit) assertEquals(480, config.dpi) assertEquals(Orientation.portrait, config.orientation) config = parseDeviceSpec("spec:shape=Round,width=240,height=120,unit=px,dpi=480") assertNotNull(config) assertNull(config.deviceId) assertEquals(Orientation.landscape, config.orientation) assertEquals(Shape.Round, config.shape) // Additional parameters ignored, should be handled by Inspections assertNotNull( parseDeviceSpec("spec:id=myId,shape=Round,width=240,height=120,unit=px,dpi=480,foo=bar") ) // Invalid values in known parameters assertNull(parseDeviceSpec("spec:shape=Round,width=invalid,height=1920,unit=px,dpi=invalid")) // Missing required parameters assertNull(parseDeviceSpec("spec:shape=Round,width=240,height=120")) } @Test fun parseTestDeviceSpecLanguage() { var config = parseDeviceSpec( "spec:width=1080.1px,height=1920.2px,dpi=320,isRound=true,chinSize=50.3px,orientation=landscape" ) assertNotNull(config) assertEquals(1080.1f, config.width) assertEquals(1920.2f, config.height) assertEquals(320, config.dpi) assertTrue(config.isRound) assertEquals(50.3f, config.chinSize) assertEquals(DimUnit.px, config.dimUnit) assertEquals(Orientation.landscape, config.orientation) config = parseDeviceSpec("spec:width=200.4dp,height=300.5dp,chinSize=10.6dp") assertNotNull(config) assertEquals(200.4f, config.width) assertEquals(300.5f, config.height) assertEquals(420, config.dpi) assertTrue(config.isRound) assertEquals(10.6f, config.chinSize) assertEquals(DimUnit.dp, config.dimUnit) // Verify default values config = parseDeviceSpec("spec:width=300dp,height=200dp") assertNotNull(config) assertEquals(420, config.dpi) assertFalse(config.isRound) assertEquals(0f, config.chinSize) assertEquals(Orientation.landscape, config.orientation) // orientation implied config = parseDeviceSpec("spec:width=100dp,height=200dp") assertNotNull(config) assertEquals(Orientation.portrait, config.orientation) // orientation implied // Width & height required assertNull(parseDeviceSpec("spec:width=100dp")) assertNull(parseDeviceSpec("spec:height=100dp")) // Width & height should have matching units assertNull(parseDeviceSpec("spec:width=100dp,height=1920px")) // Width, height & chinSize (when present) should have matching units assertNull(parseDeviceSpec("spec:width=100dp,height=200dp,chinSize=200px")) assertNull(parseDeviceSpec("spec:width=100px,height=200px,chinSize=200dp")) // Old syntax has no effect, these types of issues should be highlighted by Inspections assertEquals(DimUnit.px, parseDeviceSpec("spec:width=1080px,height=1920px,unit=dp")!!.dimUnit) } @Test fun modificationsTest() { val config = MutableDeviceConfig() assertEquals(411f, config.width) assertEquals(891f, config.height) config.dimUnit = DimUnit.px assertEquals(1078.875f, config.width) assertEquals(2338.875f, config.height) // We change the dpi, which should result in different dimensions in dp (half pixel density = // twice as the length on each dimension) config.dpi = config.dpi / 2 config.dimUnit = DimUnit.dp assertEquals(822f, config.width) assertEquals(1782f, config.height) assertEquals(Orientation.portrait, config.orientation) val temp = config.width config.width = config.height config.height = temp // Have to manually change the orientation assertEquals(Orientation.portrait, config.orientation) val tempW = config.width val tempH = config.height // After orientation change, width and height should remain the same config.orientation = Orientation.landscape assertEquals(tempW, config.width) assertEquals(tempH, config.height) } @Test fun deviceSpecLanguageString() { // For usage with DeviceSpec Language var config = DeviceConfig( width = 100f, height = 200f, dimUnit = DimUnit.dp, dpi = 300, shape = Shape.Round, chinSize = 40f, ) assertEquals( "spec:width=100dp,height=200dp,dpi=300,isRound=true,chinSize=40dp", config.deviceSpec(), ) // Orientation change is reflected as a parameter with the DeviceSpec Language assertEquals( "spec:width=100dp,height=200dp,dpi=300,isRound=true,chinSize=40dp,orientation=landscape", config.toMutableConfig().apply { orientation = Orientation.landscape }.deviceSpec(), ) // Implied Orientation of width/height is not reflected in spec config = DeviceConfig(width = 200f, height = 100f, orientation = Orientation.landscape) assertEquals("spec:width=200dp,height=100dp", config.deviceSpec()) config = DeviceConfig(width = 200f, height = 100f, orientation = Orientation.portrait) assertEquals("spec:width=200dp,height=100dp,orientation=portrait", config.deviceSpec()) // Parameters with default values are not shown (except for width & height) // Default dpi not shown config = DeviceConfig( width = 100f, height = 200f, dimUnit = DimUnit.dp, dpi = 420, shape = Shape.Round, chinSize = 40f, ) assertEquals("spec:width=100dp,height=200dp,isRound=true,chinSize=40dp", config.deviceSpec()) // Default chinSize not shown config = DeviceConfig( width = 100f, height = 200f, dimUnit = DimUnit.dp, dpi = 420, shape = Shape.Round, chinSize = 0f, ) assertEquals("spec:width=100dp,height=200dp,isRound=true", config.deviceSpec()) // Default isRound not shown, chinSize is dependent on device being round config = DeviceConfig( width = 100f, height = 200f, dimUnit = DimUnit.dp, dpi = 420, shape = Shape.Normal, chinSize = 40f, ) assertEquals("spec:width=100dp,height=200dp", config.deviceSpec()) // For DeviceSpec Language, one decimal for floating point supported assertEquals( "spec:width=123.5dp,height=567.9dp", DeviceConfig(width = 123.45f, height = 567.89f).deviceSpec(), ) } @Test fun testReferenceDevicesIdInjection() { assertEquals( "_device_class_phone", parseDeviceSpec("spec:id=reference_phone,shape=Normal,width=411,height=891,unit=dp,dpi=420")!! .deviceId, ) assertEquals( "_device_class_foldable", parseDeviceSpec( "spec:id=reference_foldable,shape=Normal,width=673,height=841,unit=dp,dpi=420" )!! .deviceId, ) assertEquals( "_device_class_tablet", parseDeviceSpec( "spec:id=reference_tablet,shape=Normal,width=1280,height=800,unit=dp,dpi=240" )!! .deviceId, ) assertEquals( "_device_class_desktop", parseDeviceSpec( "spec:id=reference_desktop,shape=Normal,width=1920,height=1080,unit=dp,dpi=160" )!! .deviceId, ) } } private fun parseDeviceSpec(deviceSpec: String?): DeviceConfig? { return DeviceConfig.toDeviceConfigOrNull(deviceSpec, emptyList()) }
3
null
225
931
73586cd8f1d76fa2396c9179bda1c53710a18be5
8,790
android
Apache License 2.0
bernoulli/src/main/java/co/yuganka/bernoulli/desilting/AskPermissionSet.kt
Yuganka
360,411,239
false
{"Java": 50502, "Kotlin": 18125}
package co.yuganka.bernoulli.desilting import android.os.Build import co.yuganka.bernoulli.Constants import co.yuganka.bernoulli.CurrentScreen /** * Helper class that works as starting point for asking for permissions if the PermissionDisabledPolicy for a * particular RequiresPermission annotation is PermissionDisabledPolicy.ASK_IF_MISSING. */ internal class AskPermissionSet( /** * Encapsulates the conditions associated with a stream's flow. */ private val dam: Dam ) { /** * Start asking for permissions for a specific method */ fun begin() { if (Build.VERSION.SDK_INT >= Constants.MIN_API_LEVEL_RUNTIME_PERMISSIONS) CurrentScreen.currentActivity?.let { it.askPermissions( permissionStringArray, dam.permissionRequestCode ) } } /** * Returns an array of permissions in the format in which they are asked from the OS */ private val permissionStringArray: Array<String?> get() { val permArray = arrayOfNulls<String>(dam.askPermissions.size) for (i in dam.askPermissions.indices) permArray[i] = dam.askPermissions[i].permission.permissionName return permArray } }
1
Java
1
2
f4d1efe45142344f9d8b17f6b793d51e41984df3
1,332
Bernoulli
Apache License 2.0
src/main/kotlin/org/fretron/user/manager/resource/UserResource.kt
Vishal1297
318,499,464
false
{"Java": 16530, "Kotlin": 10381}
package org.fretron.user.manager.resource import com.fasterxml.jackson.databind.ObjectMapper import org.fretron.user.manager.model.User import org.fretron.user.manager.service.UserServiceImpl import javax.inject.Inject import javax.inject.Named import javax.ws.rs.* import javax.ws.rs.core.MediaType import javax.ws.rs.core.Response @Path("/user/v1") class UserResource @Inject constructor( @Named("objectMapper") private val objectMapper: ObjectMapper, @Named("userService") private val userService: UserServiceImpl ) { @GET @Path("/status") @Produces(MediaType.TEXT_PLAIN) fun status(): Response { return Response.status(Response.Status.ACCEPTED).entity("User API Running...").build() } @POST @Path("/user") @Produces(MediaType.TEXT_PLAIN) @Consumes(MediaType.APPLICATION_JSON) fun addUser(user: String): Response { val person = objectMapper.readValue(user, User::class.java) return if (userService.addUser(person)) Response.ok("User Added!!").build() else Response.status(Response.Status.INTERNAL_SERVER_ERROR).build() } @GET @Path("/user") @Produces(MediaType.APPLICATION_JSON) fun getUser(@QueryParam("id") id: String): Response { val person = userService.getUser(id) ?: return Response.status(Response.Status.NOT_FOUND).build() return Response.ok(person.toString()).build() } @GET @Path("/users") @Produces(MediaType.APPLICATION_JSON) fun getAllUsers(): Response { val personsList = userService.getAllUsers() return Response.ok(personsList.toString()).build() } @PUT @Path("/user") @Produces(MediaType.TEXT_PLAIN) @Consumes(MediaType.APPLICATION_JSON) fun updateUser(@QueryParam("id") id: String, user: String): Response { val person = objectMapper.readValue(user, User::class.java) return if (person != null) { if (userService.updateUser(id, person)) Response.ok("User Updated!!").build() else Response.status(Response.Status.INTERNAL_SERVER_ERROR).build() } else { Response.status(Response.Status.NOT_MODIFIED).build() } } @DELETE @Path("/user") @Produces(MediaType.TEXT_PLAIN) fun deleteUser(@QueryParam("id") id: String): Response { return if (userService.deleteUser(id)) Response.ok("User Deleted!!").build() else Response.status(Response.Status.NOT_MODIFIED).build() } }
1
null
1
1
99367b0898829a6f8f07bf5ba831c04508f68207
2,477
user-manager
Creative Commons Zero v1.0 Universal
app/src/main/java/com/hjq/gson/factory/demo/bean/KotlinPerson.kt
cocomikes
356,097,732
false
null
package com.hjq.gson.factory.demo.bean import com.google.gson.annotations.SerializedName /** * Created by LiYunLong at 2021/11/22 09:01 * ================================================ * ================================================ */ data class KotlinPerson( @SerializedName(value = "status", alternate = ["code"]) var status : Int = 0, var arg : Int = 0 )
1
null
1
1
4d9a9e19c52c0798e65fe88e1b0e4d59ca1723e5
381
power-gson
Apache License 2.0
idea/testData/inspectionsLocal/removeToStringInStringTemplate/caretInReceiver.kt
JakeWharton
99,388,807
true
null
// PROBLEM: none fun foo(a: Int, b: Int) = a + b fun test(): String { return "Foo: ${<caret>foo(0, 4).toString()}" }
0
Kotlin
28
83
4383335168338df9bbbe2a63cb213a68d0858104
122
kotlin
Apache License 2.0
kotlin-native/Interop/Runtime/src/native/kotlin/kotlinx/cinterop/ForeignException.kt
JetBrains
3,432,266
false
null
/* * Copyright 2010-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license * that can be found in the LICENSE file. */ package kotlinx.cinterop import kotlin.native.internal.ExportForCppRuntime import kotlin.native.internal.GCUnsafeCall public class ForeignException internal constructor(val nativeException: Any?): Exception() { override val message: String = nativeException?.let { kotlin_ObjCExport_ExceptionDetails(nativeException) }?: "" // Current implementation expects NSException type only, which is ensured by CodeGenerator. @GCUnsafeCall("Kotlin_ObjCExport_ExceptionDetails") private external fun kotlin_ObjCExport_ExceptionDetails(nativeException: Any): String? } @ExportForCppRuntime internal fun CreateForeignException(payload: NativePtr): Throwable = ForeignException(interpretObjCPointerOrNull<Any?>(payload))
151
null
5478
44,267
7545472dd3b67d2ac5eb8024054e3e6ff7795bf6
898
kotlin
Apache License 2.0
app/src/main/java/com/iboism/gpxrecorder/recording/waypoint/CreateWaypointDialogActivity.kt
BradPatras
111,255,193
false
null
package com.iboism.gpxrecorder.recording.waypoint import android.annotation.SuppressLint import android.app.PendingIntent import android.graphics.Color import android.graphics.drawable.ColorDrawable import android.os.Build import android.os.Bundle import androidx.appcompat.app.AppCompatActivity import com.google.android.gms.location.LocationRequest import com.google.android.gms.location.LocationServices import com.google.android.gms.location.Priority import com.iboism.gpxrecorder.Keys import com.iboism.gpxrecorder.R import com.iboism.gpxrecorder.databinding.ActivityCreateWaypointDialogBinding import com.iboism.gpxrecorder.model.GpxContent import com.iboism.gpxrecorder.util.Alerts import com.iboism.gpxrecorder.util.PermissionHelper import io.realm.Realm private const val DRAFT_TITLE_KEY = "CreateWaypointDialog_draftTitle" private const val DRAFT_NOTE_KEY = "CreateWaypointDialog_draftNote" class CreateWaypointDialogActivity : AppCompatActivity() { private lateinit var binding: ActivityCreateWaypointDialogBinding private val fusedLocation by lazy { LocationServices.getFusedLocationProviderClient(this@CreateWaypointDialogActivity) } private val locationConfiguration by lazy { LocationRequest.Builder(1000) .setPriority(Priority.PRIORITY_HIGH_ACCURACY) .setMaxUpdates(1) .setMaxUpdateDelayMillis(2500) .build() } override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) binding = ActivityCreateWaypointDialogBinding.inflate(layoutInflater) setContentView(binding.root) window?.setBackgroundDrawable(ColorDrawable(Color.TRANSPARENT)) val bundle = intent.extras ?: return waypointError() val gpxId = checkNotNull(bundle[Keys.GpxId] as? Long) { waypointError() } binding.doneButton.setOnClickListener { startWaypointService(gpxId, binding.titleEditText.text.toString(), binding.noteEditText.text.toString()) } val realm = Realm.getDefaultInstance() realm.executeTransaction { val gpxContent = GpxContent.withId(gpxId, it) val dist = gpxContent?.trackList?.first()?.segments?.first()?.distance?.toDouble() ?: 0.0 binding.noteEditText.text.insert(0, "@%.2fkm".format(dist)) } realm.close() restoreInstanceState(savedInstanceState) } override fun onSaveInstanceState(outState: Bundle) { super.onSaveInstanceState(outState) outState.putString(DRAFT_TITLE_KEY, binding.titleEditText.text.toString()) outState.putString(DRAFT_NOTE_KEY, binding.noteEditText.text.toString()) } private fun restoreInstanceState(outState: Bundle?) { outState?.getString(DRAFT_TITLE_KEY)?.let { draftTitle -> binding.titleEditText.text.clear() binding.titleEditText.text.append(draftTitle) } outState?.getString(DRAFT_NOTE_KEY)?.let { draftNote -> binding.noteEditText.text.clear() binding.noteEditText.text.append(draftNote) } } private fun waypointError() { Alerts(applicationContext) .genericError(R.string.cannot_create_waypoint) { finish() } .show() } @SuppressLint("MissingPermission") private fun startWaypointService(gpxId: Long, title: String, note: String) { val intentFlags = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) { PendingIntent.FLAG_MUTABLE } else { 0 } val waypointIntent = CreateWaypointService.startServiceIntent(applicationContext, gpxId, title, note) val waypointPendingIntent = PendingIntent.getBroadcast(applicationContext, 0, waypointIntent, intentFlags) PermissionHelper.getInstance(this@CreateWaypointDialogActivity) .checkLocationPermissions { fusedLocation.requestLocationUpdates(locationConfiguration, waypointPendingIntent) finish() } } }
1
null
5
32
b7927713772dc7ca51d7fb428e3462e330313969
4,054
gpx-recorder
MIT License
kanashi-server/src/main/java/ink/anur/engine/processor/DataHandler.kt
anurnomeru
242,305,129
false
null
package ink.anur.engine.processor import ink.anur.engine.trx.manager.TransactionManageService import ink.anur.engine.trx.watermark.WaterMarkRegistry import ink.anur.engine.trx.watermark.common.WaterMarker import ink.anur.exception.WaterMarkCreationException import ink.anur.inject.Nigate import ink.anur.inject.NigateInject import ink.anur.log.common.EngineProcessEntry import ink.anur.pojo.log.ByteBufferKanashiEntry import ink.anur.pojo.log.KanashiCommand import ink.anur.pojo.log.base.LogItem import ink.anur.pojo.log.common.CommandTypeEnum import ink.anur.pojo.log.common.TransactionTypeEnum import java.rmi.UnexpectedException /** * Created by <NAME> on 2019/12/3 * * 数据控制,需要用到很多数据,进入数据引擎是 LogItem(持有一个 kanashiCommand),持久化后又是 kanashiEntry * * 那么如何节省内存,实际上就是这个类所做的事情 */ class DataHandler(private val engineProcessEntry: EngineProcessEntry) { @NigateInject private lateinit var waterMarkRegistry: WaterMarkRegistry @NigateInject private lateinit var transactionManageService: TransactionManageService /////////////////////////////////////////// init private val logItem = engineProcessEntry.logItem val gao = engineProcessEntry.GAO /** * 从 LogItem 中直接获取 key */ val key = logItem.getKey() /** * 如果是短事务,操作完就直接提交 * * 如果是长事务,则如果没有激活过事务,需要进行事务的激活(创建快照) */ val shortTransaction = logItem.getKanashiCommand().transactionType == TransactionTypeEnum.SHORT /** * 短事务不需要快照,长事务则是有快照就用快照,没有就创建一个快照 */ var waterMarker: WaterMarker /** * 从 kanashiCommand 中的 byteBuffer 中获取额外的参数(第一个参数以外的参数) */ val extraParams: MutableList<String> /** * kanashi Entry,里面存储着数据本身的类型(str,还是其他的,是否被删除,以及 value) */ private var byteBufferKanashiEntry: ByteBufferKanashiEntry init { Nigate.injectOnly(this) val trxId = getTrxId() if (trxId == KanashiCommand.NON_TRX) { waterMarker = WaterMarker.NONE } else { waterMarker = waterMarkRegistry.findOut(trxId) // 如果没有水位快照,代表此事务从未激活过,需要去激活一下 if (waterMarker == WaterMarker.NONE) { if (shortTransaction) { transactionManageService.activateTrx(trxId, false) } else { transactionManageService.activateTrx(trxId, true) // 从事务控制器申请激活该事务 waterMarker = waterMarkRegistry.findOut(trxId) if (waterMarker == WaterMarker.NONE) { throw WaterMarkCreationException("事务 [$trxId] 创建事务快照失败") } } } } // 取出额外参数 extraParams = logItem.getKanashiCommand().extraParams byteBufferKanashiEntry = logItem.getKanashiCommand().kanashiEntry // 这后面的内存可以释放掉了 logItem.getKanashiCommand().content.limit(KanashiCommand.TransactionSignOffset) } // ================================ ↓↓↓↓↓↓↓ 直接访问 byteBuffer 拉取数据 /** * 从 kanashiCommand 中的 byteBuffer 中获取 trxId */ fun getTrxId(): Long = logItem.getKanashiCommand().trxId /** * 从 kanashiCommand 中的 byteBuffer 中获取 commandType */ fun getCommandType() = logItem.getKanashiCommand().commandType /** * 从 kanashiCommand 中的 byteBuffer 中获取具体请求的 api */ fun getApi() = logItem.getKanashiCommand().api /** * 在正式操作引擎之前将值设置为被删除 */ fun markKanashiEntryAsDeleteBeforeOperate() { byteBufferKanashiEntry = ByteBufferKanashiEntry.allocateEmptyKanashiEntry() } @Synchronized fun getKanashiEntry(): ByteBufferKanashiEntry { return byteBufferKanashiEntry } /** * 释放内存 */ fun destroy() { } }
1
Kotlin
1
5
27db6442ef9d4abc594d7e7719a8c772f03e61b6
3,717
kanashi
MIT License
samples/kaspresso-sample/src/androidTest/kotlin/com/kaspersky/kaspressample/dsl_tests/data/Owner.kt
KasperskyLab
208,070,025
false
{"Kotlin": 736940, "Shell": 1880, "Makefile": 387}
package com.kaspersky.kaspressample.dsl_tests.data data class Owner( var firstName: String? = null, var secondName: String? = null, var country: String? = null )
55
Kotlin
150
1,784
9c94128c744d640dcd646b86de711d2a1b9c3aa1
175
Kaspresso
Apache License 2.0
solutions-kotlin/CalculatorWebService/app/src/main/java/ro/pub/cs/systems/eim/calculatorwebservice/CalculatorViewModel.kt
eim-lab
122,610,946
false
{"Text": 2, "Ignore List": 28, "Markdown": 1, "Gradle": 51, "Java Properties": 20, "Shell": 12, "Batchfile": 12, "XML": 104, "Proguard": 12, "Java": 130, "INI": 6, "Makefile": 1, "Maven POM": 1, "Ant Build System": 1, "PHP": 2, "Gradle Kotlin DSL": 3, "TOML": 1, "Kotlin": 9}
package ro.pub.cs.systems.eim.calculatorwebservice import androidx.lifecycle.LiveData import androidx.lifecycle.MutableLiveData import androidx.lifecycle.ViewModel import androidx.lifecycle.viewModelScope import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.launch import retrofit2.Response import retrofit2.Retrofit import retrofit2.converter.gson.GsonConverterFactory class CalculatorViewModel : ViewModel() { companion object { private const val BASE_URL = "http://jepi.cs.pub.ro/" } private val _result = MutableLiveData<String>() val result: LiveData<String> = _result // Create a Retrofit instance to handle the communication with the web service. private val retrofit = Retrofit.Builder() .baseUrl(BASE_URL) .addConverterFactory(GsonConverterFactory.create()) .build() private val calculatorService: CalculatorService = retrofit.create(CalculatorService::class.java) /** * Calculate the result of the operation. * * @param operator1 the first operator * @param operator2 the second operator * @param operation the operation to be performed * @param method the method to be used (0 for GET, 1 for POST) */ fun calculate( operator1: String, operator2: String, operation: String, method: Int ) { viewModelScope.launch(Dispatchers.IO) { try { val response: Response<String> = if (method == 0) { calculatorService.getOperation(operation, operator1, operator2).execute() } else { calculatorService.postOperation(operation, operator1, operator2).execute() } // Update the result LiveData with the response body or an error message. if (response.isSuccessful) { _result.postValue(response.body() ?: "No result") } else { _result.postValue("Error: ${response.message()}") } } catch (e: Exception) { _result.postValue("Failed to fetch data: ${e.message}") } } } }
0
Java
1
0
54b61b0066f560020167212931543bdc55a03305
2,183
Laborator07
Apache License 2.0
myhairdiary/app/src/main/java/com/example/myhairdiary/designers/Dimgs.kt
sungdoolim
238,624,065
false
null
package com.example.myhairdiary.designers data class Dimgs(val dimg1 : String, val dimg2 : String,val dimg3:String)
1
null
1
1
dc08834dafcef20209ba15bcff114f9f55775913
116
android_practice
Apache License 2.0
plugins/kotlin/idea/tests/testData/multiplatform/differentKindsOfDependencies/a-common/a.kt
ingokegel
72,937,917
false
null
expect class <!LINE_MARKER("descr='Has actuals in [a-js, a-jvm] modules'")!>A<!>
1
null
1
2
b07eabd319ad5b591373d63c8f502761c2b2dfe8
81
intellij-community
Apache License 2.0
buttonskt/src/main/java/io/jmdg/buttonskt/ButtonsKtView.kt
joshuadeguzman
141,821,600
false
{"Gradle": 4, "Java Properties": 1, "Shell": 1, "Text": 2, "Ignore List": 3, "Batchfile": 1, "YAML": 1, "Markdown": 1, "INI": 1, "Proguard": 2, "Kotlin": 9, "XML": 18, "Java": 2}
package io.jmdg.buttonskt import android.content.Context import android.content.res.TypedArray import android.graphics.drawable.GradientDrawable import android.util.AttributeSet import io.jmdg.buttonskt.entities.ButtonsKt import android.content.res.ColorStateList import android.graphics.drawable.RippleDrawable import android.graphics.drawable.Drawable import android.os.Build import android.annotation.TargetApi import android.graphics.Color import android.graphics.drawable.StateListDrawable import android.util.TypedValue import android.widget.ImageView import android.widget.LinearLayout import android.widget.RelativeLayout import android.widget.TextView import io.jmdg.buttonskt.internal.helpers.ResolutionUtil import android.graphics.Typeface import android.view.Gravity import io.jmdg.buttonskt.internal.ButtonKtSingleton /** * Created by <NAME> on 21/07/2018. */ class ButtonsKtView : LinearLayout { private val tag = ButtonsKtView::class.java.simpleName private var attrs: AttributeSet? = null private var config = ButtonsKt() constructor(context: Context, buttonsKtConfig: ButtonsKt) : super(context) { this.config = buttonsKtConfig initButtonAttributes() initBuilderAttributes() } constructor(context: Context, attrs: AttributeSet) : super(context, attrs) { this.attrs = attrs initButtonAttributes() initXMLAttributes() } private fun defaultConfig(init: ButtonsKt.() -> Unit) { config.init() } private fun initBuilderAttributes() { renderBuilderConfigurations() renderBackground() } private fun initXMLAttributes() { val typedArray: TypedArray = context!!.obtainStyledAttributes(attrs, R.styleable.ButtonsKtView, 0, 0) loadAttributes(typedArray) typedArray.recycle() renderXMLBuilderConfigurations() } private fun initButtonAttributes() { this.isClickable = true this.isFocusable = true } private fun renderXMLBuilderConfigurations() { // Override padding if (config.padding > 0) { this.setPadding(config.padding, config.padding, config.padding, config.padding) } else { this.setPadding(config.paddingLeft, config.paddingTop, config.paddingRight, config.paddingBottom) } } private fun loadAttributes(typedArray: TypedArray) { // Override default configurations when attributes is set via XML defaultConfig { // Configuration isEnabled = typedArray.getBoolean(R.styleable.ButtonsKtView_bkt_isEnabled, true) isRippleEffectEnabled = typedArray.getBoolean(R.styleable.ButtonsKtView_bkt_isRippleEffectEnabled, true) // Icon Resource iconResource = typedArray.getInteger(R.styleable.ButtonsKtView_bkt_iconResource, -1) iconDrawable = typedArray.getResourceId(R.styleable.ButtonsKtView_bkt_iconDrawable, -1) iconTint = typedArray.getColor(R.styleable.ButtonsKtView_bkt_iconTint, config.iconTint) iconArea = typedArray.getDimension(R.styleable.ButtonsKtView_bkt_iconArea, config.iconArea) // Icon Margin iconMargin = typedArray.getDimension(R.styleable.ButtonsKtView_bkt_iconMargin, config.iconMargin.toFloat()).toInt() iconMarginLeft = typedArray.getDimension(R.styleable.ButtonsKtView_bkt_iconMarginLeft, config.iconMarginLeft.toFloat()).toInt() iconMarginTop = typedArray.getDimension(R.styleable.ButtonsKtView_bkt_iconMarginTop, config.iconMarginTop.toFloat()).toInt() iconMarginRight = typedArray.getDimension(R.styleable.ButtonsKtView_bkt_iconMarginRight, config.iconMarginRight.toFloat()).toInt() iconMarginBottom = typedArray.getDimension(R.styleable.ButtonsKtView_bkt_iconMarginBottom, config.iconMarginBottom.toFloat()).toInt() // Icon Padding iconPadding = typedArray.getDimension(R.styleable.ButtonsKtView_bkt_iconPadding, config.iconPadding.toFloat()).toInt() iconPaddingLeft = typedArray.getDimension(R.styleable.ButtonsKtView_bkt_iconPaddingLeft, config.iconPaddingLeft.toFloat()).toInt() iconPaddingTop = typedArray.getDimension(R.styleable.ButtonsKtView_bkt_iconPaddingTop, config.iconPaddingTop.toFloat()).toInt() iconPaddingRight = typedArray.getDimension(R.styleable.ButtonsKtView_bkt_iconPaddingRight, config.iconPaddingRight.toFloat()).toInt() iconPaddingBottom = typedArray.getDimension(R.styleable.ButtonsKtView_bkt_iconPaddingBottom, config.iconPaddingBottom.toFloat()).toInt() // Text text = if (typedArray.getString(R.styleable.ButtonsKtView_bkt_text) != null) { typedArray.getString(R.styleable.ButtonsKtView_bkt_text) } else { tag } textSize = typedArray.getDimension(R.styleable.ButtonsKtView_bkt_textSize, config.textSize) textColor = typedArray.getColor(R.styleable.ButtonsKtView_bkt_textColor, config.textColor) disabledTextColor = typedArray.getColor(R.styleable.ButtonsKtView_bkt_disabledTextColor, config.disabledTextColor) textGravity = typedArray.getInteger(R.styleable.ButtonsKtView_bkt_textGravity, config.textGravity) textPosition = typedArray.getInteger(R.styleable.ButtonsKtView_bkt_textPosition, config.textPosition) isTextAllCaps = typedArray.getBoolean(R.styleable.ButtonsKtView_bkt_textAllCaps, false) textStyle = typedArray.getInteger(R.styleable.ButtonsKtView_bkt_textStyle, config.textStyle) textDefaultFont = typedArray.getInteger(R.styleable.ButtonsKtView_bkt_defaultFont, config.textDefaultFont) // Background defaultBackgroundColor = typedArray.getColor(R.styleable.ButtonsKtView_bkt_defaultBackgroundColor, config.defaultBackgroundColor) focusedBackgroundColor = typedArray.getColor(R.styleable.ButtonsKtView_bkt_focusedBackgroundColor, config.focusedBackgroundColor) disabledBackgroundColor = typedArray.getColor(R.styleable.ButtonsKtView_bkt_disabledBackgroundColor, config.disabledBackgroundColor) // Border borderWidth = typedArray.getDimension(R.styleable.ButtonsKtView_bkt_borderWidth, config.borderWidth.toFloat()).toInt() defaultBorderColor = typedArray.getColor(R.styleable.ButtonsKtView_bkt_defaultBorderColor, config.defaultBorderColor) focusedBorderColor = typedArray.getColor(R.styleable.ButtonsKtView_bkt_focusedBorderColor, config.focusedBorderColor) disabledBorderColor = typedArray.getColor(R.styleable.ButtonsKtView_bkt_disabledBorderColor, config.disabledBorderColor) // Padding padding = typedArray.getDimension(R.styleable.ButtonsKtView_bkt_padding, config.padding.toFloat()).toInt() paddingLeft = typedArray.getDimension(R.styleable.ButtonsKtView_bkt_paddingLeft, config.paddingLeft.toFloat()).toInt() paddingTop = typedArray.getDimension(R.styleable.ButtonsKtView_bkt_paddingTop, config.paddingTop.toFloat()).toInt() paddingRight = typedArray.getDimension(R.styleable.ButtonsKtView_bkt_paddingRight, config.paddingRight.toFloat()).toInt() paddingBottom = typedArray.getDimension(R.styleable.ButtonsKtView_bkt_paddingBottom, config.paddingBottom.toFloat()).toInt() // Radius cornerRadius = typedArray.getDimension(R.styleable.ButtonsKtView_bkt_cornerRadius, ResolutionUtil.dpToPx(context, config.cornerRadius).toFloat()) cornerRadiusTopLeft = typedArray.getDimension(R.styleable.ButtonsKtView_bkt_cornerRadiusTopLeft, ResolutionUtil.dpToPx(context, config.cornerRadiusTopLeft).toFloat()) cornerRadiusTopRight = typedArray.getDimension(R.styleable.ButtonsKtView_bkt_cornerRadiusTopRight, ResolutionUtil.dpToPx(context, config.cornerRadiusTopRight).toFloat()) cornerRadiusBottomLeft = typedArray.getDimension(R.styleable.ButtonsKtView_bkt_cornerRadiusBottomLeft, ResolutionUtil.dpToPx(context, config.cornerRadiusBottomLeft).toFloat()) cornerRadiusBottomRight = typedArray.getDimension(R.styleable.ButtonsKtView_bkt_cornerRadiusBottomRight, ResolutionUtil.dpToPx(context, config.cornerRadiusBottomRight).toFloat()) } this.isEnabled = isEnabled renderBackground() } private fun renderBuilderConfigurations() { // Override layoutParams val layoutParams = RelativeLayout.LayoutParams(config.width, config.height) // Margin if (config.margin > 0) { layoutParams.setMargins(config.margin, config.margin, config.margin, config.margin) } else { layoutParams.setMargins(config.marginLeft, config.marginTop, config.marginRight, config.marginBottom) } // Padding if (config.padding > 0) { this.setPadding(config.padding, config.padding, config.padding, config.padding) } else { this.setPadding(config.paddingLeft, config.paddingTop, config.paddingRight, config.paddingBottom) } // Render set layoutParams this.layoutParams = layoutParams } private fun renderBackground() { val defaultDrawable = GradientDrawable() val focusedDrawable = GradientDrawable() val disabledDrawable = GradientDrawable() renderRadius(defaultDrawable) renderRadius(focusedDrawable) renderRadius(disabledDrawable) renderBorder(defaultDrawable, false) renderBorder(disabledDrawable, true) defaultDrawable.setColor(config.defaultBackgroundColor) focusedDrawable.setColor(config.focusedBackgroundColor) disabledDrawable.setColor(config.disabledBackgroundColor) renderBackground(defaultDrawable, focusedDrawable, disabledDrawable) renderSubViews() } private fun renderSubViews() { if (config.iconResource != -1) { renderFontAwesomeResourceView() } else { renderIconView() } renderTextView() } private fun renderFontAwesomeResourceView() { val layoutParams = LinearLayout.LayoutParams(ResolutionUtil.dpToPx(context, config.iconArea), ResolutionUtil.dpToPx(context, config.iconArea)) layoutParams.gravity = Gravity.CENTER_VERTICAL // Icon Margin if (config.iconMargin > 0) { layoutParams.setMargins(config.iconMargin, config.iconMargin, config.iconMargin, config.iconMargin) } else { layoutParams.setMargins(config.iconMarginLeft, config.iconMarginTop, config.iconMarginRight, config.iconMarginBottom) } val iconView = TextView(context) iconView.layoutParams = layoutParams // Icon Padding if (config.iconPadding > 0) { iconView.setPadding(config.iconPadding, config.iconPadding, config.iconPadding, config.iconPadding) } else { iconView.setPadding(config.iconPaddingLeft, config.iconPaddingTop, config.iconPaddingRight, config.iconPaddingBottom) } iconView.setTextSize(TypedValue.COMPLEX_UNIT_SP, config.textSize) iconView.setTextColor(config.textColor) // Render TypeFace // Font Awesome if (ButtonKtSingleton.typeface == null) { ButtonKtSingleton.typeface = Typeface.createFromAsset(context.assets, "fontawesome_solid.ttf") } iconView.typeface = ButtonKtSingleton.typeface iconView.gravity = Gravity.CENTER // Load icon val iconsArray = resources.getStringArray(R.array.FontAwesome) iconView.text = iconsArray[config.iconResource] addView(iconView) } private fun renderIconView() { if (config.iconDrawable != -1 && config.iconResource == -1) { val layoutParams = LinearLayout.LayoutParams(ResolutionUtil.dpToPx(context, config.iconArea), ResolutionUtil.dpToPx(context, config.iconArea)) layoutParams.gravity = Gravity.CENTER_VERTICAL // Icon Margin if (config.iconMargin > 0) { layoutParams.setMargins(config.iconMargin, config.iconMargin, config.iconMargin, config.iconMargin) } else { layoutParams.setMargins(config.iconMarginLeft, config.iconMarginTop, config.iconMarginRight, config.iconMarginBottom) } val imageView = ImageView(context) imageView.layoutParams = layoutParams imageView.scaleType = ImageView.ScaleType.FIT_XY imageView.setImageResource(config.iconDrawable) imageView.setColorFilter(config.iconTint) // Icon Padding if (config.iconPadding > 0) { imageView.setPadding(config.iconPadding, config.iconPadding, config.iconPadding, config.iconPadding) } else { imageView.setPadding(config.iconPaddingLeft, config.iconPaddingTop, config.iconPaddingRight, config.iconPaddingBottom) } // If disabled if (!config.isEnabled) { imageView.setColorFilter(config.disabledIconTint) } addView(imageView) } } private fun renderTextView() { if (config.isTextAllCaps) { config.text = config.text.toUpperCase() } val layoutParams = LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT) layoutParams.gravity = config.textGravity if (config.iconDrawable != -1) { layoutParams.setMargins(15, 0, 0, 0) } val textView = TextView(context) textView.layoutParams = layoutParams textView.text = config.text textView.setTextSize(TypedValue.COMPLEX_UNIT_SP, config.textSize) textView.setTextColor(config.textColor) if (!config.isEnabled) { textView.setTextColor(config.disabledTextColor) } // Render font textView.typeface = getTypeFace(textView) addView(textView) } private fun renderBackground(defaultDrawable: GradientDrawable, focusedDrawable: GradientDrawable, disabledDrawable: GradientDrawable) { if (config.isRippleEffectEnabled && Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { this.background = getBackgroundWithRipple(defaultDrawable, focusedDrawable, disabledDrawable) } else { val stateListDrawable = StateListDrawable() stateListDrawable.addState(intArrayOf(android.R.attr.state_pressed), focusedDrawable) stateListDrawable.addState(intArrayOf(android.R.attr.state_focused), focusedDrawable) stateListDrawable.addState(intArrayOf(-android.R.attr.state_enabled), disabledDrawable) stateListDrawable.addState(intArrayOf(), defaultDrawable) this.background = stateListDrawable } } private fun renderRadius(gradientDrawable: GradientDrawable) { if (config.cornerRadius > 0) { gradientDrawable.cornerRadius = config.cornerRadius } else { gradientDrawable.cornerRadii = floatArrayOf( config.cornerRadiusTopLeft, config.cornerRadiusTopLeft, config.cornerRadiusTopRight, config.cornerRadiusTopRight, config.cornerRadiusBottomRight, config.cornerRadiusBottomRight, config.cornerRadiusBottomLeft, config.cornerRadiusBottomLeft) } } private fun renderBorder(gradientDrawable: GradientDrawable, isDisabled: Boolean) { if (config.borderWidth > 0) { if (isDisabled) { gradientDrawable.setStroke(config.borderWidth, Color.TRANSPARENT) } else { val states = arrayOf( intArrayOf(android.R.attr.state_pressed), intArrayOf(android.R.attr.state_focused), intArrayOf(android.R.attr.enabled), intArrayOf(-android.R.attr.state_pressed)) val colors = intArrayOf(config.focusedBorderColor, config.focusedBorderColor, config.defaultBorderColor, config.defaultBorderColor) if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { gradientDrawable.setStroke(config.borderWidth, ColorStateList(states, colors)) } else { gradientDrawable.setStroke(config.borderWidth, config.defaultBorderColor) } } } } private fun getTypeFace(textView: TextView): Typeface { val fontsArray = resources.getStringArray(R.array.DefaultFontResource) if (fontsArray.isEmpty()) { return Typeface.create(textView.typeface, config.textStyle) } return Typeface.createFromAsset(context.assets, fontsArray[config.textDefaultFont]) } @TargetApi(Build.VERSION_CODES.LOLLIPOP) private fun getBackgroundWithRipple(defaultDrawable: Drawable, focusDrawable: Drawable, disabledDrawable: Drawable): Drawable { return if (!config.isEnabled) { disabledDrawable } else { RippleDrawable(ColorStateList.valueOf(config.focusedBackgroundColor), defaultDrawable, focusDrawable) } } }
0
Kotlin
1
4
598b14fea2f4da41eb3c5ada1f43768fad113224
17,389
ButtonsKt
MIT License
SKIE/compiler/kotlin-plugin/src/kgp_common/kotlin/co/touchlab/skie/swiftmodel/callable/property/regular/KotlinRegularPropertySetterSwiftModel.kt
touchlab
685,579,240
false
{"Kotlin": 1061981, "Swift": 24501, "Shell": 183}
package co.touchlab.skie.swiftmodel.callable.property.regular interface KotlinRegularPropertySetterSwiftModel { val isThrowing: Boolean }
8
Kotlin
4
409
73e41b4240fabfa05cddfcd30a08adb213c74064
144
SKIE
Apache License 2.0
core/src/integrationTest/kotlin/com/katanox/tabour/TabourTest.kt
katanox
375,699,718
false
null
package com.katanox.tabour import com.katanox.tabour.configuration.core.tabour import com.katanox.tabour.configuration.sqs.sqsConsumer import com.katanox.tabour.configuration.sqs.sqsConsumerConfiguration import com.katanox.tabour.configuration.sqs.sqsProducer import com.katanox.tabour.configuration.sqs.sqsRegistry import com.katanox.tabour.configuration.sqs.sqsRegistryConfiguration import com.katanox.tabour.sqs.production.FifoQueueData import com.katanox.tabour.sqs.production.NonFifoQueueData import java.net.URL import java.time.Duration import kotlin.test.assertEquals import kotlin.test.assertTrue import kotlinx.coroutines.ExperimentalCoroutinesApi import kotlinx.coroutines.test.UnconfinedTestDispatcher import kotlinx.coroutines.test.runTest import org.awaitility.kotlin.await import org.awaitility.kotlin.withPollDelay import org.awaitility.kotlin.withPollInterval import org.junit.jupiter.api.AfterAll import org.junit.jupiter.api.BeforeAll import org.junit.jupiter.api.Tag import org.junit.jupiter.api.Test import org.junit.jupiter.api.TestInstance import org.testcontainers.containers.localstack.LocalStackContainer import org.testcontainers.utility.DockerImageName import software.amazon.awssdk.auth.credentials.AwsBasicCredentials import software.amazon.awssdk.auth.credentials.StaticCredentialsProvider import software.amazon.awssdk.regions.Region import software.amazon.awssdk.services.sqs.SqsClient import software.amazon.awssdk.services.sqs.model.CreateQueueRequest import software.amazon.awssdk.services.sqs.model.DeleteQueueRequest import software.amazon.awssdk.services.sqs.model.PurgeQueueRequest import software.amazon.awssdk.services.sqs.model.QueueAttributeName import software.amazon.awssdk.services.sqs.model.ReceiveMessageRequest @ExperimentalCoroutinesApi @TestInstance(TestInstance.Lifecycle.PER_CLASS) class TabourTest { private val localstack = LocalStackContainer(DockerImageName.parse("localstack/localstack:2.2.0")) .withServices(LocalStackContainer.Service.SQS) .withReuse(true) private val credentials = AwsBasicCredentials.create(localstack.accessKey, localstack.secretKey) private lateinit var sqsClient: SqsClient private lateinit var nonFifoQueueUrl: String private lateinit var fifoQueueUrl: String @BeforeAll fun setup() { localstack.start() sqsClient = SqsClient.builder() .credentialsProvider(StaticCredentialsProvider.create(credentials)) .endpointOverride(localstack.getEndpointOverride(LocalStackContainer.Service.SQS)) .region(Region.of(localstack.region)) .build() nonFifoQueueUrl = sqsClient .createQueue(CreateQueueRequest.builder().queueName("my-queue").build()) .queueUrl() fifoQueueUrl = sqsClient .createQueue( CreateQueueRequest.builder() .attributes( mutableMapOf( QueueAttributeName.FIFO_QUEUE to "TRUE", QueueAttributeName.CONTENT_BASED_DEDUPLICATION to "TRUE", ) ) .queueName("my-queue.fifo") .build() ) .queueUrl() } @AfterAll fun cleanup() { sqsClient.deleteQueue(DeleteQueueRequest.builder().queueUrl(nonFifoQueueUrl).build()) sqsClient.deleteQueue(DeleteQueueRequest.builder().queueUrl(fifoQueueUrl).build()) } @Test @Tag("sqs-consumer-test") fun `consume messages`() = runTest(UnconfinedTestDispatcher()) { val container = tabour { numOfThreads = 1 } val config = sqsRegistryConfiguration( "test-registry", StaticCredentialsProvider.create(credentials), Region.of(localstack.region) ) { this.endpointOverride = localstack.getEndpointOverride(LocalStackContainer.Service.SQS) } val sqsRegistry = sqsRegistry(config) var counter = 0 val producer = sqsProducer(URL(nonFifoQueueUrl), "test-producer") { onError = { println(it) } } val consumer = sqsConsumer(URL(nonFifoQueueUrl)) { this.onSuccess = { counter++ true } this.onError = ::println this.config = sqsConsumerConfiguration { sleepTime = Duration.ofMillis(200) consumeWhile = { counter < 1 } } } sqsRegistry.addConsumer(consumer).addProducer(producer) container.register(sqsRegistry) container.start() container.produceMessage("test-registry", "test-producer") { NonFifoQueueData("this is a test message") } // after 2 seconds, assert that we fetched the 1 message we produced earlier await.withPollDelay(Duration.ofSeconds(2)).untilAsserted { assertEquals(1, counter) } purgeQueue(nonFifoQueueUrl) } @Test @Tag("sqs-consumer-test") fun `consume messages with multi concurrency`() = runTest(UnconfinedTestDispatcher()) { val container = tabour { numOfThreads = 1 } val config = sqsRegistryConfiguration( "test-registry", StaticCredentialsProvider.create(credentials), Region.of(localstack.region) ) { this.endpointOverride = localstack.getEndpointOverride(LocalStackContainer.Service.SQS) } val sqsRegistry = sqsRegistry(config) var counter = 0 val producer = sqsProducer(URL(nonFifoQueueUrl), "test-producer") { onError = { println(it) } } val consumer = sqsConsumer(URL(nonFifoQueueUrl)) { this.onSuccess = { counter++ true } this.onError = ::println this.config = sqsConsumerConfiguration { sleepTime = Duration.ofMillis(200) consumeWhile = { counter < 50 } concurrency = 5 maxMessages = 10 } } sqsRegistry.addConsumer(consumer).addProducer(producer) container.register(sqsRegistry) container.start() repeat(50) { container.produceMessage("test-registry", "test-producer") { NonFifoQueueData("this is a test message - $it") } } // we assert that in 1 second all (50) messages will be consumed by 5 workers await.withPollDelay(Duration.ofSeconds(1)).untilAsserted { assertEquals(50, counter) } } @Test @Tag("sqs-producer-test") fun `produce a message to a non fifo queue`() = runTest(UnconfinedTestDispatcher()) { val container = tabour { numOfThreads = 1 } val config = sqsRegistryConfiguration( "test-registry", StaticCredentialsProvider.create(credentials), Region.of(localstack.region) ) { this.endpointOverride = localstack.getEndpointOverride(LocalStackContainer.Service.SQS) } val sqsRegistry = sqsRegistry(config) val producer = sqsProducer(URL(nonFifoQueueUrl), "test-producer") { onError = { println(it) } } sqsRegistry.addProducer(producer) container.register(sqsRegistry) container.start() container.produceMessage("test-registry", "test-producer") { NonFifoQueueData("this is a test message") } await .withPollInterval(Duration.ofMillis(500)) .timeout(Duration.ofSeconds(5)) .untilAsserted { val receiveMessagesResponse = sqsClient.receiveMessage( ReceiveMessageRequest.builder() .queueUrl(nonFifoQueueUrl) .maxNumberOfMessages(5) .build() ) assertTrue(receiveMessagesResponse.messages().isNotEmpty()) assertEquals( receiveMessagesResponse.messages().first().body(), "this is a test message" ) } purgeQueue(nonFifoQueueUrl) } @Test @Tag("sqs-producer-test") fun `produce a message to a fifo queue`() = runTest(UnconfinedTestDispatcher()) { val container = tabour { numOfThreads = 1 } val config = sqsRegistryConfiguration( "test-registry", StaticCredentialsProvider.create(credentials), Region.of(localstack.region) ) { this.endpointOverride = localstack.getEndpointOverride(LocalStackContainer.Service.SQS) } val sqsRegistry = sqsRegistry(config) val producer = sqsProducer(URL(fifoQueueUrl), "fifo-test-producer") { onError = { println(it) } } sqsRegistry.addProducer(producer) container.register(sqsRegistry) container.start() container.produceMessage("test-registry", "fifo-test-producer") { FifoQueueData("this is a fifo test message", "group1") } await .withPollInterval(Duration.ofMillis(500)) .timeout(Duration.ofSeconds(5)) .untilAsserted { val receiveMessagesResponse = sqsClient.receiveMessage( ReceiveMessageRequest.builder() .queueUrl(fifoQueueUrl) .maxNumberOfMessages(5) .build() ) assertTrue(receiveMessagesResponse.messages().isNotEmpty()) assertEquals( receiveMessagesResponse.messages().first().body(), "this is a fifo test message" ) } purgeQueue(fifoQueueUrl) } private fun purgeQueue(url: String) { sqsClient.purgeQueue(PurgeQueueRequest.builder().queueUrl(url).build()) } }
13
Kotlin
1
6
1a5e1e0ddf8472ca2610e0e4b4e6f9b9c5d64646
11,131
tabour
Apache License 2.0
core/src/integrationTest/kotlin/com/katanox/tabour/TabourTest.kt
katanox
375,699,718
false
null
package com.katanox.tabour import com.katanox.tabour.configuration.core.tabour import com.katanox.tabour.configuration.sqs.sqsConsumer import com.katanox.tabour.configuration.sqs.sqsConsumerConfiguration import com.katanox.tabour.configuration.sqs.sqsProducer import com.katanox.tabour.configuration.sqs.sqsRegistry import com.katanox.tabour.configuration.sqs.sqsRegistryConfiguration import com.katanox.tabour.sqs.production.FifoQueueData import com.katanox.tabour.sqs.production.NonFifoQueueData import java.net.URL import java.time.Duration import kotlin.test.assertEquals import kotlin.test.assertTrue import kotlinx.coroutines.ExperimentalCoroutinesApi import kotlinx.coroutines.test.UnconfinedTestDispatcher import kotlinx.coroutines.test.runTest import org.awaitility.kotlin.await import org.awaitility.kotlin.withPollDelay import org.awaitility.kotlin.withPollInterval import org.junit.jupiter.api.AfterAll import org.junit.jupiter.api.BeforeAll import org.junit.jupiter.api.Tag import org.junit.jupiter.api.Test import org.junit.jupiter.api.TestInstance import org.testcontainers.containers.localstack.LocalStackContainer import org.testcontainers.utility.DockerImageName import software.amazon.awssdk.auth.credentials.AwsBasicCredentials import software.amazon.awssdk.auth.credentials.StaticCredentialsProvider import software.amazon.awssdk.regions.Region import software.amazon.awssdk.services.sqs.SqsClient import software.amazon.awssdk.services.sqs.model.CreateQueueRequest import software.amazon.awssdk.services.sqs.model.DeleteQueueRequest import software.amazon.awssdk.services.sqs.model.PurgeQueueRequest import software.amazon.awssdk.services.sqs.model.QueueAttributeName import software.amazon.awssdk.services.sqs.model.ReceiveMessageRequest @ExperimentalCoroutinesApi @TestInstance(TestInstance.Lifecycle.PER_CLASS) class TabourTest { private val localstack = LocalStackContainer(DockerImageName.parse("localstack/localstack:2.2.0")) .withServices(LocalStackContainer.Service.SQS) .withReuse(true) private val credentials = AwsBasicCredentials.create(localstack.accessKey, localstack.secretKey) private lateinit var sqsClient: SqsClient private lateinit var nonFifoQueueUrl: String private lateinit var fifoQueueUrl: String @BeforeAll fun setup() { localstack.start() sqsClient = SqsClient.builder() .credentialsProvider(StaticCredentialsProvider.create(credentials)) .endpointOverride(localstack.getEndpointOverride(LocalStackContainer.Service.SQS)) .region(Region.of(localstack.region)) .build() nonFifoQueueUrl = sqsClient .createQueue(CreateQueueRequest.builder().queueName("my-queue").build()) .queueUrl() fifoQueueUrl = sqsClient .createQueue( CreateQueueRequest.builder() .attributes( mutableMapOf( QueueAttributeName.FIFO_QUEUE to "TRUE", QueueAttributeName.CONTENT_BASED_DEDUPLICATION to "TRUE", ) ) .queueName("my-queue.fifo") .build() ) .queueUrl() } @AfterAll fun cleanup() { sqsClient.deleteQueue(DeleteQueueRequest.builder().queueUrl(nonFifoQueueUrl).build()) sqsClient.deleteQueue(DeleteQueueRequest.builder().queueUrl(fifoQueueUrl).build()) } @Test @Tag("sqs-consumer-test") fun `consume messages`() = runTest(UnconfinedTestDispatcher()) { val container = tabour { numOfThreads = 1 } val config = sqsRegistryConfiguration( "test-registry", StaticCredentialsProvider.create(credentials), Region.of(localstack.region) ) { this.endpointOverride = localstack.getEndpointOverride(LocalStackContainer.Service.SQS) } val sqsRegistry = sqsRegistry(config) var counter = 0 val producer = sqsProducer(URL(nonFifoQueueUrl), "test-producer") { onError = { println(it) } } val consumer = sqsConsumer(URL(nonFifoQueueUrl)) { this.onSuccess = { counter++ true } this.onError = ::println this.config = sqsConsumerConfiguration { sleepTime = Duration.ofMillis(200) consumeWhile = { counter < 1 } } } sqsRegistry.addConsumer(consumer).addProducer(producer) container.register(sqsRegistry) container.start() container.produceMessage("test-registry", "test-producer") { NonFifoQueueData("this is a test message") } // after 2 seconds, assert that we fetched the 1 message we produced earlier await.withPollDelay(Duration.ofSeconds(2)).untilAsserted { assertEquals(1, counter) } purgeQueue(nonFifoQueueUrl) } @Test @Tag("sqs-consumer-test") fun `consume messages with multi concurrency`() = runTest(UnconfinedTestDispatcher()) { val container = tabour { numOfThreads = 1 } val config = sqsRegistryConfiguration( "test-registry", StaticCredentialsProvider.create(credentials), Region.of(localstack.region) ) { this.endpointOverride = localstack.getEndpointOverride(LocalStackContainer.Service.SQS) } val sqsRegistry = sqsRegistry(config) var counter = 0 val producer = sqsProducer(URL(nonFifoQueueUrl), "test-producer") { onError = { println(it) } } val consumer = sqsConsumer(URL(nonFifoQueueUrl)) { this.onSuccess = { counter++ true } this.onError = ::println this.config = sqsConsumerConfiguration { sleepTime = Duration.ofMillis(200) consumeWhile = { counter < 50 } concurrency = 5 maxMessages = 10 } } sqsRegistry.addConsumer(consumer).addProducer(producer) container.register(sqsRegistry) container.start() repeat(50) { container.produceMessage("test-registry", "test-producer") { NonFifoQueueData("this is a test message - $it") } } // we assert that in 1 second all (50) messages will be consumed by 5 workers await.withPollDelay(Duration.ofSeconds(1)).untilAsserted { assertEquals(50, counter) } } @Test @Tag("sqs-producer-test") fun `produce a message to a non fifo queue`() = runTest(UnconfinedTestDispatcher()) { val container = tabour { numOfThreads = 1 } val config = sqsRegistryConfiguration( "test-registry", StaticCredentialsProvider.create(credentials), Region.of(localstack.region) ) { this.endpointOverride = localstack.getEndpointOverride(LocalStackContainer.Service.SQS) } val sqsRegistry = sqsRegistry(config) val producer = sqsProducer(URL(nonFifoQueueUrl), "test-producer") { onError = { println(it) } } sqsRegistry.addProducer(producer) container.register(sqsRegistry) container.start() container.produceMessage("test-registry", "test-producer") { NonFifoQueueData("this is a test message") } await .withPollInterval(Duration.ofMillis(500)) .timeout(Duration.ofSeconds(5)) .untilAsserted { val receiveMessagesResponse = sqsClient.receiveMessage( ReceiveMessageRequest.builder() .queueUrl(nonFifoQueueUrl) .maxNumberOfMessages(5) .build() ) assertTrue(receiveMessagesResponse.messages().isNotEmpty()) assertEquals( receiveMessagesResponse.messages().first().body(), "this is a test message" ) } purgeQueue(nonFifoQueueUrl) } @Test @Tag("sqs-producer-test") fun `produce a message to a fifo queue`() = runTest(UnconfinedTestDispatcher()) { val container = tabour { numOfThreads = 1 } val config = sqsRegistryConfiguration( "test-registry", StaticCredentialsProvider.create(credentials), Region.of(localstack.region) ) { this.endpointOverride = localstack.getEndpointOverride(LocalStackContainer.Service.SQS) } val sqsRegistry = sqsRegistry(config) val producer = sqsProducer(URL(fifoQueueUrl), "fifo-test-producer") { onError = { println(it) } } sqsRegistry.addProducer(producer) container.register(sqsRegistry) container.start() container.produceMessage("test-registry", "fifo-test-producer") { FifoQueueData("this is a fifo test message", "group1") } await .withPollInterval(Duration.ofMillis(500)) .timeout(Duration.ofSeconds(5)) .untilAsserted { val receiveMessagesResponse = sqsClient.receiveMessage( ReceiveMessageRequest.builder() .queueUrl(fifoQueueUrl) .maxNumberOfMessages(5) .build() ) assertTrue(receiveMessagesResponse.messages().isNotEmpty()) assertEquals( receiveMessagesResponse.messages().first().body(), "this is a fifo test message" ) } purgeQueue(fifoQueueUrl) } private fun purgeQueue(url: String) { sqsClient.purgeQueue(PurgeQueueRequest.builder().queueUrl(url).build()) } }
13
Kotlin
1
6
1a5e1e0ddf8472ca2610e0e4b4e6f9b9c5d64646
11,131
tabour
Apache License 2.0
src/main/kotlin/org/mvnsearch/plugins/prql/lang/lexer/PrqlLexerAdapter.kt
PRQL
585,777,521
false
{"Kotlin": 59236, "Lex": 7695, "HTML": 156}
package org.mvnsearch.plugins.prql.lang.lexer import com.intellij.lexer.FlexAdapter class PrqlLexerAdapter : FlexAdapter(PrqlLexer())
1
Kotlin
0
5
f5599b695e45f479d97c3e72bbe8665796d5f6e6
135
prql-jetbrains
Apache License 2.0
src/test/kotlin/g1701_1800/s1748_sum_of_unique_elements/SolutionTest.kt
javadev
190,711,550
false
{"Kotlin": 4909193, "TypeScript": 50446, "Python": 3646, "Shell": 994}
package g1701_1800.s1748_sum_of_unique_elements import org.hamcrest.CoreMatchers.equalTo import org.hamcrest.MatcherAssert.assertThat import org.junit.jupiter.api.Test internal class SolutionTest { @Test fun sumOfUnique() { assertThat(Solution().sumOfUnique(intArrayOf(1, 2, 3, 2)), equalTo(4)) } @Test fun sumOfUnique2() { assertThat(Solution().sumOfUnique(intArrayOf(1, 1, 1, 1, 1)), equalTo(0)) } @Test fun sumOfUnique3() { assertThat(Solution().sumOfUnique(intArrayOf(1, 2, 3, 4, 5)), equalTo(15)) } }
0
Kotlin
20
43
62708bc4d70ca2bfb6942e4bbfb4c64641e598e8
570
LeetCode-in-Kotlin
MIT License
androidApp/src/main/java/com/ragnorak/marvelcdb/ui/navigation/MarvelAppDestination.kt
ragnorak-dev
648,329,484
false
{"Kotlin": 89597, "Swift": 4924}
package com.ragnorak.marvelcdb.ui.navigation import androidx.compose.material3.MaterialTheme import androidx.compose.runtime.Composable import androidx.compose.ui.graphics.Color import androidx.compose.ui.graphics.vector.ImageVector import androidx.compose.ui.res.vectorResource import androidx.navigation.NavBackStackEntry import com.ragnorak.marvelcdb.android.R import kotlinx.serialization.Serializable interface Route @Serializable object HeroesList : Route @Serializable data class HeroDetails(val heroCode: String) : Route @Serializable object Favorites : Route data class MarvelTopLevelDestination( val route: Route, val icon: ImageVector, val selectedColor: Color, val unselectedColor: Color, val iconTextId: Int ) @Composable fun getTopDestinations() = listOf( MarvelTopLevelDestination( route = HeroesList, icon = ImageVector.vectorResource(id = R.drawable.hero_icon), selectedColor = MaterialTheme.colorScheme.primary, unselectedColor = MaterialTheme.colorScheme.secondary, iconTextId = R.string.menu_heroes ), MarvelTopLevelDestination( route = Favorites, icon =ImageVector.vectorResource(id = R.drawable.favorite_icon), selectedColor = MaterialTheme.colorScheme.primary, unselectedColor = MaterialTheme.colorScheme.secondary, iconTextId = R.string.menu_favorites ) )
0
Kotlin
1
2
df4e02d191aab19aad3447b5dad48fd9e31b8db9
1,400
Marvel_CDB_KMM
MIT License
tabler/src/commonMain/kotlin/com/woowla/compose/icon/collections/tabler/tabler/outline/TextWrapDisabled.kt
walter-juan
868,046,028
false
{"Kotlin": 20416825}
package com.woowla.compose.icon.collections.tabler.tabler.outline import androidx.compose.ui.graphics.Color import androidx.compose.ui.graphics.PathFillType.Companion.NonZero import androidx.compose.ui.graphics.SolidColor import androidx.compose.ui.graphics.vector.ImageVector import androidx.compose.ui.graphics.vector.ImageVector.Builder import androidx.compose.ui.graphics.vector.path import androidx.compose.ui.unit.dp import com.woowla.compose.icon.collections.tabler.tabler.OutlineGroup import androidx.compose.ui.graphics.StrokeCap.Companion.Round as strokeCapRound import androidx.compose.ui.graphics.StrokeJoin.Companion.Round as strokeJoinRound public val OutlineGroup.TextWrapDisabled: ImageVector get() { if (_textWrapDisabled != null) { return _textWrapDisabled!! } _textWrapDisabled = Builder(name = "TextWrapDisabled", defaultWidth = 24.0.dp, defaultHeight = 24.0.dp, viewportWidth = 24.0f, viewportHeight = 24.0f).apply { path(fill = SolidColor(Color(0x00000000)), stroke = SolidColor(Color(0xFF000000)), strokeLineWidth = 2.0f, strokeLineCap = strokeCapRound, strokeLineJoin = strokeJoinRound, strokeLineMiter = 4.0f, pathFillType = NonZero) { moveTo(4.0f, 6.0f) lineToRelative(10.0f, 0.0f) } path(fill = SolidColor(Color(0x00000000)), stroke = SolidColor(Color(0xFF000000)), strokeLineWidth = 2.0f, strokeLineCap = strokeCapRound, strokeLineJoin = strokeJoinRound, strokeLineMiter = 4.0f, pathFillType = NonZero) { moveTo(4.0f, 18.0f) lineToRelative(10.0f, 0.0f) } path(fill = SolidColor(Color(0x00000000)), stroke = SolidColor(Color(0xFF000000)), strokeLineWidth = 2.0f, strokeLineCap = strokeCapRound, strokeLineJoin = strokeJoinRound, strokeLineMiter = 4.0f, pathFillType = NonZero) { moveTo(4.0f, 12.0f) horizontalLineToRelative(17.0f) lineToRelative(-3.0f, -3.0f) moveToRelative(0.0f, 6.0f) lineToRelative(3.0f, -3.0f) } } .build() return _textWrapDisabled!! } private var _textWrapDisabled: ImageVector? = null
0
Kotlin
0
1
b037895588c2f62d069c724abe624b67c0889bf9
2,358
compose-icon-collections
MIT License
src/main/java/org/kman/clearview/core/AuthInfo.kt
aimlessness99
403,481,863
true
{"Kotlin": 180297}
package org.kman.clearview.core import android.content.Context import androidx.preference.PreferenceManager data class AuthInfo( val server: String, val username: String?, val password: String? ) { companion object { private const val PREFS_KEY_SERVER = "auth_server" private const val PREFS_KEY_USERNAME = "auth_username" private const val PREFS_KEY_PASSWORD = "<PASSWORD>" fun loadSavedAuthInfo(context: Context): AuthInfo? { val prefs = PreferenceManager.getDefaultSharedPreferences(context) return prefs.let { val server = it.getString(PREFS_KEY_SERVER, null) val username = it.getString(PREFS_KEY_USERNAME, null) val password = it.getString(PREFS_KEY_PASSWORD, null) if (server.isNullOrEmpty()) { null } else { AuthInfo(server, username, password) } } } fun clearSavedAuthInfo(context: Context) { val prefs = PreferenceManager.getDefaultSharedPreferences(context) prefs.edit().also { it.remove(PREFS_KEY_SERVER) it.remove(PREFS_KEY_USERNAME) it.remove(PREFS_KEY_PASSWORD) }.apply() } fun saveAuthInfo(context: Context, authInfo: AuthInfo) { val prefs = PreferenceManager.getDefaultSharedPreferences(context) prefs.edit().also { it.putString(PREFS_KEY_SERVER, authInfo.server) it.putString(PREFS_KEY_USERNAME, authInfo.username) it.putString(PREFS_KEY_PASSWORD, authInfo.password) }.apply() } } }
0
null
0
0
1dfc4d8f1bb9e1e05b52a4d3eca23fd35ab00f43
1,740
clearview-android
Apache License 2.0
tokenization/src/main/java/com/paysafe/android/tokenization/data/mapper/AuthenticationResponseMapper.kt
paysafegroup
739,327,660
false
{"Kotlin": 637209, "Shell": 912}
/* * Copyright (c) 2024 Paysafe Group */ package com.paysafe.android.tokenization.data.mapper import com.paysafe.android.tokenization.data.entity.cardadapter.AuthenticationResponseSerializable import com.paysafe.android.tokenization.data.entity.cardadapter.FinalizeAuthenticationResponseSerializable import com.paysafe.android.tokenization.domain.model.cardadapter.AuthenticationResponse import com.paysafe.android.tokenization.domain.model.cardadapter.AuthenticationStatus import com.paysafe.android.tokenization.domain.model.cardadapter.FinalizeAuthenticationResponse internal fun AuthenticationResponseSerializable.toDomain() = AuthenticationResponse( sdkChallengePayload = sdkChallengePayload, status = AuthenticationStatus.fromString(status) ) internal fun FinalizeAuthenticationResponseSerializable.toDomain() = FinalizeAuthenticationResponse( status = AuthenticationStatus.fromString(status) )
0
Kotlin
0
0
d0f16d72ef051fc4bc6245a6204ede659f308e05
918
paysafe_sdk_android_payments_api
MIT License
kotlin-multiplatform/common/src/commonMain/kotlin/com.artemchep.playground.kotlin_multiplatform_common/viewmodel/ViewModel.kt
AChep
190,457,280
false
null
package com.artemchep.playground.kotlin_multiplatform_common.viewmodel /** * @author Artem Chepurnoy */ expect abstract class ViewModel() { abstract fun onDestroy() }
0
Kotlin
0
1
f09f6fbb14892e8025c0709deb54b7b765a650cf
174
playground
Apache License 2.0
test/org/jetbrains/android/dsl/functional/GeneratedLayoutsTest.kt
team55
29,602,286
true
{"Kotlin": 484392, "Java": 9672, "Shell": 175}
package org.jetbrains.android.dsl.functional import org.jetbrains.android.dsl.* import org.testng.annotations.Test public class LayoutsTest : AbstractFunctionalTest() { private val testDataFile = "LayoutsTest.kt" override fun initSettings(settings: BaseGeneratorConfiguration) { settings.files.add(KoanFile.LAYOUTS) } [Test] public fun testLayoutsTestFor21() { runFunctionalTest(testDataFile, KoanFile.LAYOUTS, "21") } [Test] public fun testLayoutsTestFor21s() { runFunctionalTest(testDataFile, KoanFile.LAYOUTS, "21s") } }
0
Kotlin
0
0
68886b864e19d6523b77151d34450b802eb2e6e7
576
koan
Apache License 2.0
app/src/main/java/com/example/mvvm_newsapp/data/di/DataModule.kt
burhankamran0076
672,768,086
false
null
package com.example.mvvm_newsapp.data.di import com.example.mvvm_newsapp.constants.Constants import com.example.mvvm_newsapp.data.network.ApiService import com.example.mvvm_newsapp.data.repository.NewsRepoImpl import dagger.Module import dagger.Provides import dagger.hilt.InstallIn import dagger.hilt.components.SingletonComponent import retrofit2.Retrofit import retrofit2.converter.gson.GsonConverterFactory @InstallIn(SingletonComponent::class) @Module object DataModule { @Provides fun provideApiService(): ApiService { return Retrofit.Builder().baseUrl(Constants.BASE_URL).addConverterFactory( GsonConverterFactory.create() ) .build().create(ApiService::class.java) } }
0
Kotlin
0
0
996d17882876744fdf697facaebdca1d02dac2d9
736
Clean-Architecture-Android
MIT License
ktgram/src/main/kotlin/ru/lavafrai/ktgram/client/service/factories/MediaGroupBodyFactory.kt
lavaFrai
812,095,309
false
{"Kotlin": 477598}
package ru.lavafrai.ktgram.client.service.factories import kotlinx.serialization.encodeToString import kotlinx.serialization.json.Json import okhttp3.MultipartBody import ru.lavafrai.ktgram.types.inputfile.FileIdInputFile import ru.lavafrai.ktgram.types.inputfile.URLInputFile import ru.lavafrai.ktgram.types.media.inputmedia.InputMedia class MediaGroupBodyFactory(val json: Json) { suspend fun createMediaGroupBody(media: List<InputMedia>): List<MultipartBody.Part> { val mediaGroupBody = mutableListOf<MultipartBody.Part>() val processedMedia = mutableListOf<InputMedia>() media.forEach { when (it.mediaFile) { is URLInputFile, is FileIdInputFile -> { processedMedia.add(it) } else -> { val mediaName = it.media val processedIt = it.copy(media = "attach://$mediaName") processedMedia.add(processedIt) mediaGroupBody.add(it.mediaFile!!.getMultiPartBodyPart(mediaName)) } } } val mediaJson = json.encodeToString(processedMedia) mediaGroupBody.add(MultipartBody.Part.createFormData("media", mediaJson)) return mediaGroupBody } }
0
Kotlin
0
3
3b8e3d8aeb8a60445a84a57aaf91fda7baf038ea
1,284
ktgram
Apache License 2.0
feature/home/home-impl/src/main/java/com/timothy/themoviedb/home_impl/ui/HomeActivity.kt
harrytmthy
565,863,027
false
null
/* * Copyright 2022 harrytmthy * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.timothy.themoviedb.home_impl.ui import androidx.activity.viewModels import com.timothy.themoviedb.common.ext.addLoadMoreListener import com.timothy.themoviedb.home_impl.R import com.timothy.themoviedb.home_impl.databinding.ActivityHomeBinding import com.timothy.themoviedb.home_impl.ui.HomeNavigation.MovieDetail import com.timothy.themoviedb.home_impl.ui.detail.MovieDetailActivity.Companion.createIntent import com.timothy.themoviedb.ui.base.BaseActivity import com.timothy.themoviedb.ui.base.Navigation import com.timothy.themoviedb.ui.ext.viewBinding import com.timothy.themoviedb.ui.handler.ViewStateHandler import dagger.hilt.android.AndroidEntryPoint @AndroidEntryPoint class HomeActivity : BaseActivity() { override val binding by viewBinding(ActivityHomeBinding::inflate) override val viewModel by viewModels<HomeViewModel>() private val controller by lazy { HomeEpoxyController(viewModel::navigateToMovieDetail) } override val viewStateHandler = object : ViewStateHandler<HomeViewState> { override fun onViewStateUpdated(viewState: HomeViewState) { binding.srlContent.isEnabled = !viewState.loading binding.srlContent.isRefreshing = viewState.refreshing controller.setData(viewState) } } override fun setupUi() { binding.toolbar.bind(this, R.string.home_title) binding.srlContent.setOnRefreshListener(viewModel::refresh) binding.rvContent.addLoadMoreListener( canLoadMore = { viewModel.viewState.value.canLoadMore() }, onLoadMore = viewModel::getNextPage ) binding.rvContent.setController(controller) } override fun onNavigate(navigation: Navigation) { when (navigation) { is MovieDetail -> startActivity(createIntent(this, navigation.movieId)) } } }
0
Kotlin
0
0
2e0efb3ff55f558886fa6ac99d06c9e8e96c8cc1
2,456
TheMovieDB
Apache License 2.0
tabler/src/commonMain/kotlin/com/woowla/compose/icon/collections/tabler/tabler/outline/DatabaseLeak.kt
walter-juan
868,046,028
false
{"Kotlin": 20416825}
package com.woowla.compose.icon.collections.tabler.tabler.outline import androidx.compose.ui.graphics.Color import androidx.compose.ui.graphics.PathFillType.Companion.NonZero import androidx.compose.ui.graphics.SolidColor import androidx.compose.ui.graphics.vector.ImageVector import androidx.compose.ui.graphics.vector.ImageVector.Builder import androidx.compose.ui.graphics.vector.path import androidx.compose.ui.unit.dp import com.woowla.compose.icon.collections.tabler.tabler.OutlineGroup import androidx.compose.ui.graphics.StrokeCap.Companion.Round as strokeCapRound import androidx.compose.ui.graphics.StrokeJoin.Companion.Round as strokeJoinRound public val OutlineGroup.DatabaseLeak: ImageVector get() { if (_databaseLeak != null) { return _databaseLeak!! } _databaseLeak = Builder(name = "DatabaseLeak", defaultWidth = 24.0.dp, defaultHeight = 24.0.dp, viewportWidth = 24.0f, viewportHeight = 24.0f).apply { path(fill = SolidColor(Color(0x00000000)), stroke = SolidColor(Color(0xFF000000)), strokeLineWidth = 2.0f, strokeLineCap = strokeCapRound, strokeLineJoin = strokeJoinRound, strokeLineMiter = 4.0f, pathFillType = NonZero) { moveTo(4.0f, 6.0f) curveToRelative(0.0f, 1.657f, 3.582f, 3.0f, 8.0f, 3.0f) reflectiveCurveToRelative(8.0f, -1.343f, 8.0f, -3.0f) reflectiveCurveToRelative(-3.582f, -3.0f, -8.0f, -3.0f) reflectiveCurveToRelative(-8.0f, 1.343f, -8.0f, 3.0f) } path(fill = SolidColor(Color(0x00000000)), stroke = SolidColor(Color(0xFF000000)), strokeLineWidth = 2.0f, strokeLineCap = strokeCapRound, strokeLineJoin = strokeJoinRound, strokeLineMiter = 4.0f, pathFillType = NonZero) { moveTo(4.0f, 6.0f) verticalLineToRelative(12.0f) curveToRelative(0.0f, 1.657f, 3.582f, 3.0f, 8.0f, 3.0f) reflectiveCurveToRelative(8.0f, -1.343f, 8.0f, -3.0f) verticalLineToRelative(-12.0f) } path(fill = SolidColor(Color(0x00000000)), stroke = SolidColor(Color(0xFF000000)), strokeLineWidth = 2.0f, strokeLineCap = strokeCapRound, strokeLineJoin = strokeJoinRound, strokeLineMiter = 4.0f, pathFillType = NonZero) { moveTo(4.0f, 15.0f) arcToRelative(2.4f, 2.4f, 0.0f, false, false, 2.0f, -1.0f) arcToRelative(2.4f, 2.4f, 0.0f, false, true, 2.0f, -1.0f) arcToRelative(2.4f, 2.4f, 0.0f, false, true, 2.0f, 1.0f) arcToRelative(2.4f, 2.4f, 0.0f, false, false, 2.0f, 1.0f) arcToRelative(2.4f, 2.4f, 0.0f, false, false, 2.0f, -1.0f) arcToRelative(2.4f, 2.4f, 0.0f, false, true, 2.0f, -1.0f) arcToRelative(2.4f, 2.4f, 0.0f, false, true, 2.0f, 1.0f) arcToRelative(2.4f, 2.4f, 0.0f, false, false, 2.0f, 1.0f) } } .build() return _databaseLeak!! } private var _databaseLeak: ImageVector? = null
0
Kotlin
0
1
b037895588c2f62d069c724abe624b67c0889bf9
3,172
compose-icon-collections
MIT License
src/main/kotlin/org/beckn/one/sandbox/bap/client/shared/dtos/DeliveryAddressRequestDto.kt
OSSVerse
853,138,400
false
{"Kotlin": 651081, "Jinja": 3324}
package org.beckn.one.sandbox.bap.client.shared.dtos import org.beckn.one.sandbox.bap.message.entities.AddressDao import org.beckn.one.sandbox.bap.message.entities.DescriptorDao import org.beckn.protocol.schemas.Default import org.beckn.protocol.schemas.ProtocolLocation data class DeliveryAddressRequestDto @Default constructor( val descriptor: DescriptorDao? = null, val gps: String? = null, val default: Boolean? = true, val address: AddressDao? = null )
0
Kotlin
0
8
b3ca6a6455f41b9d53bbb35f5c01e31c1fde2638
469
OSSVerse-buyer-app
Apache License 2.0
src/main/kotlin/org/sathe/json/JsonLexer.kt
asathe
87,023,052
false
null
package org.sathe.json import java.io.InputStream import java.io.InputStreamReader import java.lang.StringBuilder import java.math.BigDecimal import java.math.BigInteger class JsonLexer(stream: InputStream) : Iterator<Any?> { private val reader = InputStreamReader(stream).buffered() private val tokenBuilder = StringBuilder() private var currentChar: Char = '\u0000' init { nextChar() } override fun hasNext(): Boolean = currentChar != '\uffff' override fun next(): Any? { while (currentChar.isWhitespace()) { nextChar() } return when (currentChar) { '{' -> readAndReturn("{") '[' -> readAndReturn("[") '"' -> stringValue() '}' -> readAndReturn("}") ']' -> readAndReturn("]") ',' -> readAndReturn(",") ':' -> readAndReturn(":") 't' -> booleanValue("true") 'f' -> booleanValue("false") 'n' -> nullValue() else -> numericValue() } } private fun nextChar(): Char { currentChar = reader.read().toChar() return currentChar } private fun readAndReturn(token: String): String { nextChar() return token } private fun appendAndFetchNext() { tokenBuilder.append(currentChar) nextChar() } private fun numericValue(): Number { var isDecimal = false tokenBuilder.setLength(0) fun addDigits(firstIsMandatory: Boolean) { assertThat(!firstIsMandatory || currentChar.isDigit()) { "Invalid numeric format. Current capture '$tokenBuilder', was not expecting '$currentChar'" } while (currentChar.isDigit()) { appendAndFetchNext() } } fun addExponent() { if (currentChar == 'e' || currentChar == 'E') { isDecimal = true appendAndFetchNext() assertThat(currentChar == '-' || currentChar == '+' || currentChar.isDigit()) { "Invalid numeric format. Expecting +, - or digit for exponent" } val signed = currentChar appendAndFetchNext() addDigits(signed == '-' || signed == '+') } } fun addNegativeSign() { if (currentChar == '-') { appendAndFetchNext() } } fun addDecimalPlace() { if (currentChar == '.') { isDecimal = true appendAndFetchNext() addDigits(true) } addDigits(false) } addNegativeSign() addDigits(true) addDecimalPlace() addExponent() return if (isDecimal) BigDecimal(tokenBuilder.toString()) else BigInteger(tokenBuilder.toString()) } private fun booleanValue(expected: String): Boolean { val token = knownWord(expected.length) assertThat(token == expected) { "Expecting boolean value but got $token" } return token.toBoolean() } private fun nullValue(): Any? { val token = knownWord(4) assertThat(token == "null") { "Expecting null value but got $token" } return null } private fun knownWord(length: Int): String { tokenBuilder.setLength(0) tokenBuilder.append(currentChar) repeat(length - 1) { tokenBuilder.append(nextChar()) } nextChar() return tokenBuilder.toString() } private fun stringValue(): String { tokenBuilder.setLength(0) fun hexValue(char: Char): Int { return when (char) { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9' -> char - '0' 'a', 'b', 'c', 'd', 'e', 'f' -> char - 'W' 'A', 'B', 'C', 'D', 'E', 'F' -> char - '7' else -> throw JsonException("Non-hexadecimal character '$char' found") } } fun unicodeCharacter(): Char { var value = hexValue(nextChar()) value = (value shl 4) + hexValue(nextChar()) value = (value shl 4) + hexValue(nextChar()) value = (value shl 4) + hexValue(nextChar()) return value.toChar() } fun escapedCharacter() { when (nextChar()) { '"' -> tokenBuilder.append('"') 't' -> tokenBuilder.append('\t') 'r' -> tokenBuilder.append('\r') 'n' -> tokenBuilder.append('\n') 'b' -> tokenBuilder.append('\b') 'f' -> tokenBuilder.append('\u000C') '\\' -> tokenBuilder.append('\\') 'u' -> tokenBuilder.append(unicodeCharacter()) } } while (nextChar() != '"') { assertThat(currentChar != '\uFFFF') { "Unterminated string found" } when (currentChar) { '\\' -> escapedCharacter() else -> tokenBuilder.append(currentChar) } } nextChar() return tokenBuilder.toString() } private fun assertThat(expression: Boolean, message: () -> String) { if (!expression) { throw JsonException(message()) } } }
0
Kotlin
0
0
342c8b79384ab7fc61a4a9fa4d3b69ac83a5bf5c
5,266
jsonlin
Apache License 2.0
src/main/kotlin/uk/gov/justice/digital/hmpps/hmppsresettlementpassportapi/data/prisonersapi/PrisonersSearch.kt
ministryofjustice
665,659,688
false
null
package uk.gov.justice.digital.hmpps.hmppsresettlementpassportapi.data.prisonersapi import java.time.LocalDate data class PrisonersSearch( val prisonerNumber: String, val firstName: String, val middleNames: String? = null, val lastName: String, val releaseDate: LocalDate? = null, val nonDtoReleaseDateType: String? = null, ) data class PrisonerRequest( val earliestReleaseDate: String, val latestReleaseDate: String, val prisonIds: List<String>, ) data class PrisonersSearchList( val content: List<PrisonersSearch>?, val pageSize: Int?, val page: Int?, val sortName: String?, val totalElements: Int?, val last: Boolean, )
0
Kotlin
1
0
b0d88b947d9583c34860f8474871409dd121da79
656
hmpps-resettlement-passport-api
MIT License
common/src/iosMain/kotlin/io/github/thisisthepy/pycomposeui/test/common/ViewController.kt
thisisthepy
714,603,401
false
{"Kotlin": 25450, "Python": 13873, "HTML": 1245, "Java": 1207, "Swift": 540, "CSS": 173}
package io.github.thisisthepy.pycomposeui.test.common import androidx.compose.ui.window.ComposeUIViewController import platform.UIKit.UIViewController fun MainViewController(): UIViewController = ComposeUIViewController { App() }
0
Kotlin
0
0
144fa6b996ef2db8b6ce063ffec5844486fb2e6a
237
PyComposeUITest
MIT License
domain/src/main/java/com/synrgyacademy/domain/usecase/airport/GetHistorySearchingByIdUseCase.kt
Synrgy-Academy-Final-Project
738,116,027
false
{"Kotlin": 429514, "Ruby": 1824}
package com.synrgyacademy.domain.usecase.airport import com.synrgyacademy.common.Resource import com.synrgyacademy.domain.model.airport.HistoryDataModel import com.synrgyacademy.domain.repository.AirportRepository import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.flow import kotlinx.coroutines.flow.flowOn import javax.inject.Inject class GetHistorySearchingByIdUseCase @Inject constructor( private val repository: AirportRepository ) { operator fun invoke(id: Int): Flow<Resource<HistoryDataModel>> = flow { emit(Resource.Loading) try { val result = repository.getHistorySearchingById(id) emit(Resource.Success(result)) } catch (e: Exception) { emit(Resource.Error(e.localizedMessage ?: "An unexpected error occurred")) } }.flowOn(Dispatchers.IO) }
0
Kotlin
0
0
d7fefca1200efd6eae4a33a34ef0511d90dfd54a
887
Android
MIT License
app/src/main/java/dev/leonlatsch/photok/settings/ui/compose/ConfigCompositionLocal.kt
leonlatsch
287,088,448
false
{"Kotlin": 470806, "HTML": 1049}
/* * Copyright 2020-2024 <NAME> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * 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 dev.leonlatsch.photok.settings.ui.compose import androidx.compose.runtime.ProvidableCompositionLocal import androidx.compose.runtime.compositionLocalOf import dev.leonlatsch.photok.settings.data.Config val LocalConfig: ProvidableCompositionLocal<Config> = compositionLocalOf { error("Config no provided") }
43
Kotlin
52
523
f31156f75af892f03c77b4ff45ad907e2e25f7c2
937
Photok
Apache License 2.0
app/src/main/java/com/fridaytech/dex/core/IAppConfiguration.kt
5daytech
198,758,400
false
null
package com.fridaytech.dex.core import com.fridaytech.dex.core.model.Coin import com.fridaytech.zrxkit.ZrxKit import com.fridaytech.zrxkit.model.AssetItem import com.fridaytech.zrxkit.relayer.model.Relayer import io.horizontalsystems.ethereumkit.core.EthereumKit interface IAppConfiguration { val testMode: Boolean val networkType: EthereumKit.NetworkType val zrxNetworkType: ZrxKit.NetworkType val etherscanKey: String val infuraCredentials: EthereumKit.InfuraCredentials val infuraProjectId: String? val infuraProjectSecret: String? val appShareUrl: String val companySiteUrl: String val transactionExploreBaseUrl: String val ipfsId: String val ipfsMainGateway: String val ipfsFallbackGateway: String val allCoins: List<Coin> val defaultCoinCodes: List<String> val allExchangePairs: List<Pair<AssetItem, AssetItem>> val fixedCoinCodes: List<String> val relayers: List<Relayer> }
0
Kotlin
13
21
50200c97a9a7a456b588cf132fdb901141efb1d1
959
udex-app-android
MIT License