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
sdk-library/src/main/java/pers/pslilysm/sdk_library/util/GsonUtil.kt
pslilysm
525,191,828
false
null
package pers.pslilysm.sdk_library.util import android.text.TextUtils import androidx.collection.ArraySet import com.google.gson.* import com.google.gson.internal.LinkedTreeMap import pers.pslilysm.sdk_library.annotation.GsonExclude import pers.pslilysm.sdk_library.util.reflection.ReflectionUtil /** * Miscellaneous [Gson] utility methods. * * @author pslilysm * @since 1.0.0 */ object GsonUtil { private val sPrettyGson: Gson private val sGson: Gson /** * Serialize object to json * * @param obj to serialize * @param pretty ture we'll returned a pretty json string * @return json string */ @JvmOverloads @kotlin.jvm.JvmStatic fun objToJson(obj: Any?, pretty: Boolean = false): String { return if (pretty) sPrettyGson.toJson(obj) else sGson.toJson(obj) } /** * Deserialize json to object * * @param json json string * @param tClass class of object will returned * @param <T> the type of the object returned * @return a object deserialize of json string */ @kotlin.jvm.JvmStatic fun <T> jsonToObject(json: String?, tClass: Class<T>): T? { return sGson.fromJson(json, tClass) } /** * Deserialize json to [Set] * * @param json json string * @param tClass Set's elements class * @param <T> the type of the Set's element * @return a empty Set if json is empty string or empty array */ @kotlin.jvm.JvmStatic fun <T> jsonToSet(json: String?, tClass: Class<T>?): Set<T> { val set: MutableSet<T> = ArraySet() if (!TextUtils.isEmpty(json)) { val array = JsonParser.parseString(json).asJsonArray for (elem in array) { set.add(sGson.fromJson(elem, tClass)) } } return set } /** * Deserialize json to [List] * * @param json json string * @param tClass List's elements class * @param <T> the type of the List's element * @return a empty List if json is empty string or empty array */ @kotlin.jvm.JvmStatic fun <T> jsonToList(json: String?, tClass: Class<T>?): MutableList<T> { val list: MutableList<T> = ArrayList() if (!TextUtils.isEmpty(json)) { val array = JsonParser.parseString(json).asJsonArray for (elem in array) { list.add(sGson.fromJson(elem, tClass)) } } return list } /** * Deserialize json to [Map] * * @param json json string * @param <V>> the type of the Map's value * @return a empty Map if json is empty */ @kotlin.jvm.JvmStatic fun <V> jsonToMap(json: String?, vClass: Class<V>?): MutableMap<String, V> { val result: MutableMap<String, V> = LinkedTreeMap() if (TextUtils.isEmpty(json)) { return result } val jsonObject = sGson.fromJson(json, JsonObject::class.java) try { val members = ReflectionUtil.getFieldValue<LinkedTreeMap<String, JsonElement>>( jsonObject, "members" ) members!!.forEach { (s: String, jsonElement: JsonElement?) -> result[s] = sGson.fromJson(jsonElement, vClass) } } catch (e: ReflectiveOperationException) { // never happen throw RuntimeException() } return result } /** * Pretty a json string * * @param jsonStr raw json string * @return a prettied json string */ @kotlin.jvm.JvmStatic fun prettyJson(jsonStr: String?): String { val je = JsonParser.parseString(jsonStr) return sPrettyGson.toJson(je) } init { val strategy: ExclusionStrategy = object : ExclusionStrategy { override fun shouldSkipField(f: FieldAttributes): Boolean { return f.getAnnotation(GsonExclude::class.java) != null } override fun shouldSkipClass(clazz: Class<*>): Boolean { return clazz.getAnnotation(GsonExclude::class.java) != null } } sPrettyGson = GsonBuilder().setPrettyPrinting().disableHtmlEscaping() .setExclusionStrategies(strategy).create() sGson = GsonBuilder().disableHtmlEscaping() .setExclusionStrategies(strategy).create() } }
0
Kotlin
0
1
568b38cb598be13b1c20623ef6f83d8481b37240
4,415
sdk-ktx
Apache License 2.0
tools/unit/src/main/kotlin/com/datadog/tools/unit/extensions/ProhibitLeavingStaticMocksExtension.kt
DataDog
219,536,756
false
null
/* * Unless explicitly stated otherwise all files in this repository are licensed under the Apache License Version 2.0. * This product includes software developed at Datadog (https://www.datadoghq.com/). * Copyright 2016-Present Datadog, Inc. */ package com.datadog.tools.unit.extensions import com.datadog.tools.unit.annotations.ProhibitLeavingStaticMocksIn import org.junit.jupiter.api.extension.AfterEachCallback import org.junit.jupiter.api.extension.ExtensionContext import org.mockito.internal.util.MockUtil import java.lang.reflect.Field import java.lang.reflect.Modifier import java.util.LinkedList import java.util.logging.Logger import kotlin.reflect.KClass import kotlin.reflect.KProperty1 import kotlin.reflect.full.companionObject import kotlin.reflect.full.companionObjectInstance import kotlin.reflect.full.instanceParameter import kotlin.reflect.full.memberProperties import kotlin.reflect.jvm.isAccessible import kotlin.reflect.jvm.javaField import kotlin.reflect.jvm.javaGetter import kotlin.reflect.jvm.jvmName /** * Extension which allows to see mocks left in static fields after test run. * Check [ProhibitLeavingStaticMocksIn] for more details. * * **NOTE**: JUnit extensions are executed in the declaration order for beforeXXX callbacks, but * in the reversed order for afterXXX callbacks. So since this extension relies on the afterEach, * it should be declared before TestConfigurationExtension, so that classes referenced * by TestConfiguration could be reset before running this extension. */ class ProhibitLeavingStaticMocksExtension : AfterEachCallback { private val logger = Logger.getLogger(ProhibitLeavingStaticMocksExtension::class.jvmName) override fun afterEach(context: ExtensionContext) { val annotationOnMethod = context.requiredTestMethod .getAnnotation(ProhibitLeavingStaticMocksIn::class.java) val annotationOnClass = context.requiredTestClass .getAnnotation(ProhibitLeavingStaticMocksIn::class.java) val scanRoots = mutableListOf<KClass<*>>().apply { addAll(annotationOnMethod?.value ?: emptyArray()) addAll(annotationOnClass?.value ?: emptyArray()) } val packagePrefixes = mutableListOf<String>().apply { addAll(annotationOnMethod?.packagePrefixes ?: emptyArray()) addAll(annotationOnClass?.packagePrefixes ?: emptyArray()) } scanForStaticMocksLeft(scanRoots, packagePrefixes) } internal fun scanForStaticMocksLeft( roots: List<KClass<*>>, packagePrefixes: List<String> ) { val visited = mutableSetOf<KClass<*>>() val queue = LinkedList<VisitEntry>() queue.addAll(roots.map { VisitEntry(it, emptyList()) }) while (!queue.isEmpty()) { val visitEntry = queue.pollFirst() ?: continue val visitedClass = visitEntry.clazz visited.add(visitedClass) val watchFields = findFieldsToWatch(visitedClass) for (fieldInstanceSpec in watchFields) { val value = fieldInstanceSpec.fieldValue ?: continue if (MockUtil.isMock(value)) { reportViolation( fieldInstanceSpec.fieldDescriptor, fieldInstanceSpec.hostClass, visitEntry.pathUntil, fieldInstanceSpec.isLateinit ) } if (packagePrefixes.any { value::class.java.name.startsWith(it) } && !visited.contains(value::class.java.kotlin) ) { val nextEntry = VisitEntry( value::class, pathUntil = visitEntry.pathUntil + CallStackEntry( fieldInstanceSpec.hostClass, fieldInstanceSpec.fieldDescriptor ) ) queue.add(nextEntry) } } } } private fun findFieldsToWatch(visitedClass: KClass<*>): List<FieldCallSpec> { val kotlinObjectFields = if (visitedClass.simpleName != null && visitedClass.objectInstance != null ) { findTargetFieldsInKotlin( visitedClass, visitedClass.objectInstance ) } else { emptyList() } val kotlinCompanionObjectFields = if (visitedClass.simpleName != null && visitedClass.companionObjectInstance != null ) { findTargetFieldsInKotlin( visitedClass.companionObject, visitedClass.companionObjectInstance ) } else { emptyList() } val plainStaticFields = if (kotlinObjectFields.isEmpty() && kotlinCompanionObjectFields.isEmpty()) { findTargetPlainStaticFields(visitedClass.java) } else { emptyList() } return mutableListOf<FieldCallSpec>().apply { addAll(kotlinObjectFields) addAll(kotlinCompanionObjectFields) addAll(plainStaticFields) } } @Suppress("ThrowingInternalException") // not an issue in unit tests private fun reportViolation( fieldDescriptor: FieldDescriptor, hostClass: KClass<*>, pathUntil: List<CallStackEntry>, isLateinit: Boolean ) { var message = "Unexpected mock remaining in the field" + " ${fieldDescriptor.fieldName} of ${hostClass.jvmName}." if (pathUntil.isNotEmpty()) { val callingSequence = pathUntil.reversed() .joinToString(separator = "\n") { "${it.hostClass.jvmName}.${it.fieldDescriptor.fieldName}" } message += "\nCalling sequence:\n$callingSequence" } if (isLateinit) { logger.info(message) } else { throw UnwantedStaticMockException(message) } } private fun findTargetFieldsInKotlin( clazz: KClass<*>?, hostInstance: Any? ): List<FieldCallSpec> { if (clazz == null) return emptyList() return clazz.memberProperties .filterNot { it.isConst } .map { FieldCallSpec(FieldDescriptor.Kotlin(it), it.isLateinit, hostInstance, clazz) } } private fun findTargetPlainStaticFields( clazz: Class<*> ): List<FieldCallSpec> { return clazz.declaredFields .filter { Modifier.isStatic(it.modifiers) && !Modifier.isFinal(it.modifiers) } .map { FieldCallSpec(FieldDescriptor.Java(it), false, null, clazz.kotlin) } } private data class FieldCallSpec( val fieldDescriptor: FieldDescriptor, val isLateinit: Boolean, val hostInstance: Any?, val hostClass: KClass<*> ) { val fieldValue: Any? get() { return when (fieldDescriptor) { is FieldDescriptor.Java -> { fieldDescriptor.field.isAccessible = true fieldDescriptor.field.get(hostInstance) } is FieldDescriptor.Kotlin -> { val property = fieldDescriptor.property property.isAccessible = true // this place is extremely fragile: for lateinit we cannot call getter // if property is not initialized - we get an error. Also some properties // don't require instance to get the value and it is not clear how to // understand that, thing with javaGetter check is just a quick // solution (but probably not the proper one). if (isLateinit && property.javaField?.get(hostInstance) == null) { null } else { if (property.getter.instanceParameter == null) { property.getter.call() } else { if (!hostClass.isCompanion && property.javaGetter == null) { property.getter.call() } else { property.getter.call(hostInstance) } } } } } } } private sealed class FieldDescriptor { data class Java(val field: Field) : FieldDescriptor() data class Kotlin(val property: KProperty1<*, *>) : FieldDescriptor() val fieldName: String get() { return when (this) { is Java -> this.field.name is Kotlin -> property.name } } } private data class CallStackEntry( val hostClass: KClass<*>, val fieldDescriptor: FieldDescriptor ) private data class VisitEntry(val clazz: KClass<*>, val pathUntil: List<CallStackEntry>) } /** * Exception thrown by [ProhibitLeavingStaticMocksExtension] if any mocks found in the static * fields after test run. */ class UnwantedStaticMockException(message: String) : IllegalStateException(message)
44
null
60
86
bcf0d12fd978df4e28848b007d5fcce9cb97df1c
9,559
dd-sdk-android
Apache License 2.0
browser-kotlin/src/jsMain/kotlin/web/geolocation/GeolocationPosition.kt
karakum-team
393,199,102
false
{"Kotlin": 6472581}
// Automatically generated - do not modify! package web.geolocation import js.core.EpochTimeStamp /** * Available only in secure contexts. * * [MDN Reference](https://developer.mozilla.org/docs/Web/API/GeolocationPosition) */ sealed external class GeolocationPosition { /** * [MDN Reference](https://developer.mozilla.org/docs/Web/API/GeolocationPosition/coords) */ val coords: GeolocationCoordinates /** * [MDN Reference](https://developer.mozilla.org/docs/Web/API/GeolocationPosition/timestamp) */ val timestamp: EpochTimeStamp }
0
Kotlin
6
27
e8d3760ae4b6f6dc971ca3b242bffed65af5f3d1
576
types-kotlin
Apache License 2.0
domain/src/main/java/com/gmart/domain/model/Country.kt
gimartinez17
771,233,885
false
{"Kotlin": 515365, "CMake": 1625, "C++": 259}
package com.gmart.domain.model data class Country( val country: String? = null, val englishName: String? = null, val nativeName: String? = null )
0
Kotlin
1
1
da0854981d865fb7207767ae3e6a4c8ce1f441a8
159
movies-app
MIT License
src/test/kotlin/leet/T1-array.kt
dzca
581,929,762
false
{"Kotlin": 75573}
package leet import org.junit.jupiter.api.Test import kotlin.test.assertEquals class T1{ @Test fun `minWindow`(){ val a1 = "ADOBECODEBANC" val b1 = "ABC" assertEquals("BANC", minWindow(a1, b1)) } @Test fun `longestSubStr1`(){ val a1 = "abcabcbb" val a2 = "bbbbb" val a3 = "pwwkew" val a4 = "abba" val a5 = " " assertEquals(3, longestSubStr1(a1)) assertEquals(1, longestSubStr1(a2)) assertEquals(3, longestSubStr1(a3)) assertEquals(2, longestSubStr1(a4)) assertEquals(1, longestSubStr1(a5)) } @Test fun `longestSubStr2`(){ val a1 = "abcabcbb" val a2 = "bbbbb" val a3 = "pwwkew" val a4 = "abba" val a5 = " " val a6 = "" assertEquals(3, longestSubStr2(a1)) assertEquals(1, longestSubStr1(a2)) assertEquals(3, longestSubStr1(a3)) assertEquals(2, longestSubStr2(a4)) assertEquals(1, longestSubStr2(a5)) assertEquals(0, longestSubStr2(a6)) } }
0
Kotlin
0
0
b1e7d1cb739e21ed7e8b7484d6efcd576857830f
1,088
kotlin-algrithm
MIT License
app/src/main/java/hu/kristof/nagy/hikebookclient/view/hike/TransportType.kt
Kristof1999
464,363,767
false
{"Kotlin": 405541}
package hu.kristof.nagy.hikebookclient.view.hike enum class TransportType { BICYCLE, CAR }
0
Kotlin
0
0
013501c897446b02c4b08d3d6922c2e0d6a9d902
95
HikeBookClient
Apache License 2.0
android/app/src/main/java/org/alteh/orghelper/data/CommandResult.kt
alteh-union
268,625,838
false
{"JavaScript": 836461, "Kotlin": 217464, "HTML": 1721, "CSS": 930, "SCSS": 36}
/* * Copyright (c) 2021 <NAME> (<EMAIL>) * * Licensed under the MIT License (see the root LICENSE file for details) */ package org.alteh.orghelper.data import com.google.gson.annotations.SerializedName import java.io.Serializable /** * Represents a result of a command execution on the Bot's server side. * This object is received via a web-response from the Bot's server. * Ensure that the [SerializedName] matches to what the server sends. */ class CommandResult ( @SerializedName("text") var resultText: String = "", @SerializedName("attachments") var attachments: List<CommandAttachment> = listOf(), @SerializedName("suggestions") var suggestions: List<ValueSuggestion> = listOf() ) : Serializable
26
JavaScript
3
6
122d2acaf8721752706d70489041f98eeb240c2d
736
org-helper
MIT License
data/src/test/kotlin/straightway/peerspace/data/IdTest.kt
cryptobuks
141,508,151
true
{"Kotlin": 249965}
/* * Copyright 2016 github.com/straightway * * Licensed under the Apache License, Version 2.0 (the &quot;License&quot;); * 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 &quot;AS IS&quot; 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 straightway.peerspace.data import org.junit.jupiter.api.Test import straightway.testing.bdd.Given import straightway.testing.flow.Equal import straightway.testing.flow.expect import straightway.testing.flow.is_ import straightway.testing.flow.to_ import straightway.testing.testAutoGeneratedDataClassMethods import straightway.utils.deserializeTo import straightway.utils.serializeToByteArray class IdTest { private companion object { const val identifier = "Identifier" } private val test get() = Given { object { val sut = Id(identifier) } } @Test fun `identifier is accessible`() = test when_ { sut.identifier } then { expect(it.result is_ Equal to_ identifier) } @Test fun `Id with only identifier is a data id`() { test while_ { expect(sut.type is_ Equal to_ IdType.General) } } @Test fun `auto-generated methods`() { test while_ { sut.testAutoGeneratedDataClassMethods() } } @Test fun `is serializable`() = test when_ { sut.serializeToByteArray().deserializeTo<Id>() } then { expect(it.result is_ Equal to_ sut) } @Test fun `toString of general id yields compact string`() = Given { Id(IdType.General, identifier) } when_ { toString() } then { expect(it.result is_ Equal to_ "Id($identifier)") } @Test fun `toString of non-general id yields compact string with id type`() = Given { Id(IdType.Administrative, identifier) } when_ { toString() } then { expect(it.result is_ Equal to_ "Id(Administrative::$identifier)") } @Test fun `has serialVersionUID`() = expect(Id.serialVersionUID is_ Equal to_ 1L) }
0
Kotlin
0
0
972b9d4e5827ef656d589c9cd5aee7cb3c82a766
2,601
peerspace
Apache License 2.0
android/src/main/kotlin/com/smena/flutter_varioqub/FlutterVarioqubPlugin.kt
smenateam
700,069,469
false
{"Kotlin": 5360, "Swift": 4790, "Dart": 3306, "Ruby": 3004, "Java": 607, "Objective-C": 38}
package com.smena.flutter_varioqub import android.app.Application import android.content.Context import androidx.annotation.NonNull import com.yandex.metrica.YandexMetrica import com.yandex.metrica.YandexMetricaConfig import io.flutter.embedding.engine.plugins.FlutterPlugin import io.flutter.plugin.common.MethodCall import io.flutter.plugin.common.MethodChannel import io.flutter.plugin.common.MethodChannel.MethodCallHandler import io.flutter.plugin.common.MethodChannel.Result import com.yandex.varioqub.appmetricaadapter.AppmetricaAdapter import com.yandex.varioqub.config.FetchError import com.yandex.varioqub.config.OnFetchCompleteListener import com.yandex.varioqub.config.Varioqub import com.yandex.varioqub.config.VarioqubSettings class FlutterVarioqubPlugin : FlutterPlugin, MethodCallHandler { private lateinit var channel: MethodChannel private var context: Context? = null private var application: Application? = null override fun onAttachedToEngine(@NonNull flutterPluginBinding: FlutterPlugin.FlutterPluginBinding) { context = flutterPluginBinding.applicationContext application = flutterPluginBinding.applicationContext as Application channel = MethodChannel(flutterPluginBinding.binaryMessenger, "flutter_varioqub") channel.setMethodCallHandler(this) } override fun onMethodCall(@NonNull call: MethodCall, @NonNull result: Result) { when (call.method) { "init" -> { val apiKey = call.argument<String?>("api_key") if (apiKey == null) { result.error("API key = null", null, null) } val settings = VarioqubSettings.Builder(apiKey!!).withThrottleInterval(100) .build() Varioqub.init(settings, AppmetricaAdapter(context!!), context!!) result.success(null) } "set_default" -> { val defaultMap = call.argument<Map<String, Any>?>("default_map") Varioqub.setDefaults(defaultMap!!) result.success(null) } "get_bool" -> { val boolKey = call.argument<String?>("bool_key") if (boolKey == null) { result.error("Key is null", null, null) } val value = Varioqub.getBoolean(boolKey!!) result.success(value) } "get_string" -> { val stringKey = call.argument<String?>("string_key") if (stringKey == null) { result.error("Key is null", null, null) } val value = Varioqub.getString(stringKey!!) result.success(value) } "get_double" -> { val doubleKey = call.argument<String?>("double_key") if (doubleKey == null) { result.error("Key is null", null, null) } val value = Varioqub.getDouble(doubleKey!!) result.success(value) } "get_long" -> { val longKey = call.argument<String?>("long_key") if (longKey == null) { result.error("Key is null", null, null) } val value = Varioqub.getLong(longKey!!) result.success(value) } "get_id" -> { val id = Varioqub.getId() result.success(id) } "fetch_config" -> { Varioqub.fetchConfig(object : OnFetchCompleteListener { override fun onSuccess() { result.success(null) } override fun onError(message: String, error: FetchError) { result.error(message, null, null) } }) } "activate_config" -> { Varioqub.activateConfig() result.success(null) } } } override fun onDetachedFromEngine(@NonNull binding: FlutterPlugin.FlutterPluginBinding) { channel.setMethodCallHandler(null) } }
0
Kotlin
0
0
9b2597fc16f4b2849c284cf9d5287d0b4c98036a
4,242
flutter_varioqub
MIT License
ses-plugin-server/src/main/kotlin/jetbrains/buildServer/sesPlugin/bounceHandler/BounceHandler.kt
JetBrains
105,000,686
false
{"Kotlin": 153538, "Java": 9533, "JavaScript": 6552, "CSS": 57}
package jetbrains.buildServer.sesPlugin.bounceHandler /** * Interface handling bounce events (hard ones only) */ interface BounceHandler { fun handleBounces(mails: Sequence<String>) }
4
Kotlin
4
2
defc95b475b7971ca29a43beddc31d08ff96269f
192
TeamCity.SESPlugin
Apache License 2.0
app/src/main/java/eleccionmp/redciudadana/org/eleccionmp/views/candidates/CandidatesPresenter.kt
RedCiudadana
118,052,799
false
null
package eleccionmp.redciudadana.org.eleccionmp.views.candidates import eleccionmp.redciudadana.org.eleccionmp.R import eleccionmp.redciudadana.org.eleccionmp.http.Models import eleccionmp.redciudadana.org.eleccionmp.utils.mvp.BasePresenter /** * Created by javier on 1/23/18. */ class CandidatesPresenter : BasePresenter<CandidatesContract.View>(), CandidatesContract.Presenter { override fun onViewCreated() { mView?.setTitle() mView?.showLoading() Models.getCandidates(mView!!.getContext()) { list: List<Models.Profile>?, throwable: Throwable? -> if (throwable != null) { mView?.showError(R.string.errors_could_not_load) } else { mView?.showCandidatesList(list!!) } mView?.hideLoading() } } override fun onCandidateSelected(profile: Models.Profile) { mView?.showCandidate(profile) } }
1
Kotlin
0
0
b8b7cb0d3135172e304cf140d5dcdb4883fd136c
929
EleccionMPAndroid
MIT License
server/src/main/kotlin/com/arianegraphql/ktx/Resolver.kt
arianegraphql
354,885,191
false
null
package com.arianegraphql.ktx import graphql.GraphQLContext import graphql.schema.DataFetcher import kotlinx.coroutines.runBlocking interface Resolver<S> { suspend fun resolve(arguments: Argument, source: S, context: GraphQLContext, info: Info): Any? } @JvmInline value class FunctionalResolver<S>( private val lambda: suspend (parameters: ResolverParameters<S>) -> Any? ) : Resolver<S> { override suspend fun resolve( arguments: Argument, source: S, context: GraphQLContext, info: Info ) = lambda(ResolverParameters(arguments, source, context, info)) } internal fun <S> Resolver<S>.toDataFetcher(): DataFetcher<Any?> = DataFetcher { env -> runBlocking { env.graphQlContext resolve(DataFetchingArgument(env), env.getSource(), env.graphQlContext, env) } }
1
null
0
4
d74905dc0146cf93894b0634c0c3bcd75b40e747
831
ariane-server
MIT License
network/src/main/java/org/fnives/test/showcase/network/content/ContentRemoteSource.kt
fknives
356,982,481
false
null
package org.fnives.test.showcase.network.content import org.fnives.test.showcase.model.content.Content import org.fnives.test.showcase.network.shared.exceptions.NetworkException import org.fnives.test.showcase.network.shared.exceptions.ParsingException import kotlin.jvm.Throws interface ContentRemoteSource { @Throws(NetworkException::class, ParsingException::class) suspend fun get(): List<Content> }
9
Kotlin
2
5
5bf503d90e8a13daf5626afc0cdf8bff523d2b94
414
AndroidTest-ShowCase
Apache License 2.0
guides/micronaut-rabbitmq-rpc/bookinventory/kotlin/src/main/kotlin/example/micronaut/BookInventoryService.kt
micronaut-projects
326,986,278
false
{"Java": 2207487, "Groovy": 1129386, "Kotlin": 977645, "JavaScript": 110091, "HTML": 93452, "CSS": 30567, "Shell": 5473, "AppleScript": 1063, "Python": 47}
/* * Copyright 2017-2024 original authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package example.micronaut import io.micronaut.rabbitmq.annotation.Queue import io.micronaut.rabbitmq.annotation.RabbitListener import java.util.Optional import jakarta.validation.constraints.NotBlank @RabbitListener // <1> open class BookInventoryService { @Queue("inventory") // <2> open fun stock(isbn: @NotBlank String?): Boolean? = bookInventoryByIsbn(isbn).map { (_, stock): BookInventory -> stock > 0 }.orElse(null) private fun bookInventoryByIsbn(isbn: String?): Optional<BookInventory> = if (isbn.equals("1491950358")) { Optional.of(BookInventory(isbn!!, 4)) } else if (isbn.equals("1680502395")) { Optional.of(BookInventory(isbn!!, 0)) } else { Optional.empty<Any>() as Optional<BookInventory> } }
209
Java
31
36
9f04eb978f4882e883adffb6c95d6a6928d79b29
1,401
micronaut-guides
Creative Commons Attribution 4.0 International
tabler/src/commonMain/kotlin/com/woowla/compose/icon/collections/tabler/tabler/outline/Pilcrow.kt
walter-juan
868,046,028
false
{"Kotlin": 34345428}
package com.woowla.compose.icon.collections.tabler.tabler.outline import androidx.compose.ui.graphics.Color import androidx.compose.ui.graphics.PathFillType import androidx.compose.ui.graphics.PathFillType.Companion.NonZero import androidx.compose.ui.graphics.SolidColor import androidx.compose.ui.graphics.StrokeCap import androidx.compose.ui.graphics.StrokeCap.Companion.Round import androidx.compose.ui.graphics.StrokeJoin 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 public val OutlineGroup.Pilcrow: ImageVector get() { if (_pilcrow != null) { return _pilcrow!! } _pilcrow = Builder(name = "Pilcrow", 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 = Round, strokeLineJoin = StrokeJoin.Companion.Round, strokeLineMiter = 4.0f, pathFillType = NonZero) { moveTo(13.0f, 4.0f) verticalLineToRelative(16.0f) } path(fill = SolidColor(Color(0x00000000)), stroke = SolidColor(Color(0xFF000000)), strokeLineWidth = 2.0f, strokeLineCap = Round, strokeLineJoin = StrokeJoin.Companion.Round, strokeLineMiter = 4.0f, pathFillType = NonZero) { moveTo(17.0f, 4.0f) verticalLineToRelative(16.0f) } path(fill = SolidColor(Color(0x00000000)), stroke = SolidColor(Color(0xFF000000)), strokeLineWidth = 2.0f, strokeLineCap = Round, strokeLineJoin = StrokeJoin.Companion.Round, strokeLineMiter = 4.0f, pathFillType = NonZero) { moveTo(19.0f, 4.0f) horizontalLineToRelative(-9.5f) arcToRelative(4.5f, 4.5f, 0.0f, false, false, 0.0f, 9.0f) horizontalLineToRelative(3.5f) } } .build() return _pilcrow!! } private var _pilcrow: ImageVector? = null
0
Kotlin
0
3
eca6c73337093fbbfbb88546a88d4546482cfffc
2,337
compose-icon-collections
MIT License
src/main/kotlin/org/ivcode/mvn/controllers/BasicAuthController.kt
iv-buildsystem
744,432,718
false
{"Kotlin": 46483, "FreeMarker": 1906, "Shell": 1546, "Dockerfile": 849}
package org.ivcode.mvn.controllers import org.ivcode.mvn.services.basicauth.BasicAuthService import org.ivcode.mvn.services.basicauth.model.BasicAuthUser import org.ivcode.mvn.services.basicauth.model.CreateBasicAuthUser import org.springframework.web.bind.annotation.GetMapping 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 /** * The API interface for managing Basic-Auth users. */ @RestController @RequestMapping(path = ["/api/basic-auth"]) public class BasicAuthController( private val basicAuthService: BasicAuthService ) { @GetMapping public fun listUsers(): List<BasicAuthUser> = basicAuthService.listUsers() @PostMapping public fun createUser( @RequestBody createBasicAuthUser: CreateBasicAuthUser ) { basicAuthService.createUser( createBasicAuthUser.username, createBasicAuthUser.password, createBasicAuthUser.write ) } }
0
Kotlin
0
0
fe0d469a9e250e9964d8e80258662cff03b482a9
1,127
iv-mvn
Apache License 2.0
src/main/java/it/actuallyrocks/livecoding/query/AccountSummary.kt
magnusmickelsson
185,400,815
false
{"Java": 7648, "Kotlin": 7521}
package it.actuallyrocks.livecoding.query import javax.persistence.Entity import javax.persistence.Id import javax.persistence.NamedQueries import javax.persistence.NamedQuery /** * Read model entity */ @Entity @NamedQueries( NamedQuery(name = "AccountSummary.fetch", query = "SELECT c FROM AccountSummary c WHERE c.id LIKE CONCAT(:idStartsWith, '%') ORDER BY c.id"), NamedQuery(name = "AccountSummary.count", query = "SELECT COUNT(c) FROM AccountSummary c WHERE c.id LIKE CONCAT(:idStartsWith, '%')")) data class AccountSummary(@Id var id: String, var balance: Int) { // Needed by JPA constructor() : this("", 0) }
1
null
1
1
56d659f703a3c7290035db330f2bd96c2e2093a8
651
axon-livecoding
Apache License 2.0
src/app/src/test/kotlin/org/vaccineimpact/orderlyweb/tests/unit_tests/controllers/api/ReportRunControllerTests.kt
vimc
173,126,600
false
null
package org.vaccineimpact.orderlyweb.tests.unit_tests.controllers.api import com.google.gson.Gson import com.nhaarman.mockito_kotlin.* import okhttp3.Headers import org.assertj.core.api.Assertions.assertThat import org.assertj.core.api.Assertions.assertThatThrownBy import org.junit.jupiter.api.Test import org.pac4j.core.profile.CommonProfile import org.vaccineimpact.orderlyweb.ActionContext import org.vaccineimpact.orderlyweb.OrderlyServerAPI import org.vaccineimpact.orderlyweb.PorcelainResponse import org.vaccineimpact.orderlyweb.controllers.api.ReportRunController import org.vaccineimpact.orderlyweb.db.repositories.ReportRunRepository import org.vaccineimpact.orderlyweb.errors.PorcelainError import java.time.Instant class ReportRunControllerTests : ControllerTest() { private val reportName = "report1" private val reportKey = "123" @Test fun `runs a report`() { val params = mapOf("param" to "p1") val changelog = mapOf( "message" to "test message", "type" to "test type" ) val actionContext: ActionContext = mock { on { params(":name") } doReturn reportName on { postData<Any>() } doReturn mapOf( "instances" to mapOf("instance" to "i1"), "params" to params, "changelog" to changelog, "gitBranch" to "branch1", "gitCommit" to "abc123" ) on { queryParams("timeout") } doReturn "600" on { userProfile } doReturn CommonProfile().apply { id = "a@b.com" } } val mockAPIResponseText = """{"data": {"name": "$reportName", "key": $reportKey, "path": "/status/$reportKey"}}""" val mockAPIResponse = PorcelainResponse(mockAPIResponseText, 200, Headers.headersOf()) val expectedQs = mapOf( "ref" to "abc123", "instance" to "i1", "timeout" to "600" ) val apiClient: OrderlyServerAPI = mock { on { post( eq("/v1/reports/$reportName/run/"), eq( Gson().toJson( mapOf( "params" to params, "changelog" to changelog ) ) ), eq(expectedQs), any() ) } doReturn mockAPIResponse } val mockReportRunRepo: ReportRunRepository = mock() val sut = ReportRunController(actionContext, mockReportRunRepo, apiClient, mock()) val result = sut.run() assertThat(result).isEqualTo(mockAPIResponseText) verify(mockReportRunRepo).addReportRun( eq(reportKey), eq("a@b.com"), any<Instant>(), eq(reportName), eq(mapOf("instance" to "i1")), eq(params), eq("branch1"), eq("abc123") ) } @Test fun `runs a report without arguments`() { val actionContext: ActionContext = mock { on { params(":name") } doReturn reportName on { userProfile } doReturn CommonProfile().apply { id = "a@b.com" } } val mockAPIResponseText = """{"data": {"name": "$reportName", "key": $reportKey, "path": "/status/$reportKey"}}""" val mockAPIResponse = PorcelainResponse(mockAPIResponseText, 200, Headers.headersOf()) val expectedBody = """{"params":{}}""" val apiClient: OrderlyServerAPI = mock { on { post("/v1/reports/$reportName/run/", expectedBody, mapOf()) } doReturn mockAPIResponse } val mockReportRunRepo: ReportRunRepository = mock() val sut = ReportRunController(actionContext, mockReportRunRepo, apiClient, mock()) val result = sut.run() assertThat(result).isEqualTo(mockAPIResponseText) verify(mockReportRunRepo).addReportRun( eq(reportKey), eq("a@b.com"), any<Instant>(), eq(reportName), eq(mapOf()), eq(mapOf()), eq(null), eq(null) ) } @Test fun `runs a report does not insert record on failure`() { val actionContext: ActionContext = mock { on { params(":name") } doReturn reportName } val url = "/v1/reports/$reportName/run/" val expectedBody = "{\"params\":{}}" val apiClient: OrderlyServerAPI = mock { on { post(url, expectedBody, mapOf()) } doThrow PorcelainError(url, 500, "Orderly server", listOf()) } val mockReportRunRepo: ReportRunRepository = mock() val sut = ReportRunController(actionContext, mockReportRunRepo, apiClient, mock()) assertThatThrownBy { sut.run() } .isInstanceOf(PorcelainError::class.java) .matches { (it as PorcelainError).httpStatus == 500 } verifyZeroInteractions(mockReportRunRepo) } @Test fun `gets report status`() { val actionContext: ActionContext = mock { on { params(":key") } doReturn reportKey } val mockAPIResponse = PorcelainResponse("""{"status": "running"}""", 200, Headers.headersOf()) val apiClient: OrderlyServerAPI = mock { on { get("/v1/reports/$reportKey/status/", actionContext) } doReturn mockAPIResponse } val sut = ReportRunController(actionContext, mock(), apiClient, mock()) val result = sut.status() assertThat(result).isEqualTo("""{"status": "running"}""") } @Test fun `kills a report`() { val actionContext: ActionContext = mock { on { params(":key") } doReturn reportKey } val mockAPIResponse = PorcelainResponse("okayresponse", 200, Headers.headersOf()) val apiClient: OrderlyServerAPI = mock { on { delete("/v1/reports/$reportKey/kill/", actionContext) } doReturn mockAPIResponse } val sut = ReportRunController(actionContext, mock(), apiClient, mock()) val result = sut.kill() assertThat(result).isEqualTo("okayresponse") } }
3
null
4
4
e3a2a8204a3e559e15f1d54e884e8ea1aa798cf0
6,503
orderly-web
MIT License
src/main/kotlin/com/forgerock/sapi/gateway/framework/utils/ClientAndApiParameterizedTest.kt
SecureApiGateway
795,036,493
false
{"Kotlin": 137504, "Makefile": 1388, "Dockerfile": 379}
package com.forgerock.sapi.gateway.framework.utils import com.forgerock.sapi.gateway.framework.api.ApiUnderTest import com.forgerock.sapi.gateway.framework.apiclient.ApiClient import com.forgerock.sapi.gateway.framework.configuration.ConfigurationManager import org.junit.jupiter.api.Named import org.junit.jupiter.params.provider.Arguments abstract class ClientAndApiParameterizedTest { companion object { val parameterizedTestArguments: Map<ApiClient, ApiUnderTest> @JvmStatic fun getParameterizedTestArgs(): List<Arguments> { val args: MutableList<Arguments> = mutableListOf() parameterizedTestArguments.forEach { (apiClient, apiUnderTest) -> args.add( Arguments.of( Named.of(apiClient.name, apiClient), Named.of(apiUnderTest.name, apiUnderTest) ) ) } return args } init { parameterizedTestArguments = ConfigurationManager.getApiClientsAndApisUnderTestArguments( apiClientsToUse = listOf("all"), testWithApiClientFromDevelopmentTrustedDirectory = true ) } } }
4
Kotlin
0
0
e037d89f48317bfe09005cb4fcf7c8bd36da2a2f
1,247
secure-api-gateway-functional-test-framework
Apache License 2.0
app/src/main/java/com/example/touristattractionsinbulgaria/data/RoomDb.kt
Kavertx
728,627,137
false
{"Kotlin": 15576}
package com.example.touristattractionsinbulgaria.data import android.content.Context import androidx.room.Database import androidx.room.Room import androidx.room.RoomDatabase @Database(entities = [Attraction::class, District::class], version = 1, exportSchema = false) abstract class RoomDb : RoomDatabase() { abstract fun attractionDao(): AttractionDao abstract fun districtDao(): DistrictDao companion object { @Volatile private var INSTANCE: RoomDb? = null fun getDatabase(context: Context): RoomDb { // if the INSTANCE is not null, then return it, // if it is, then create the database return INSTANCE ?: synchronized(this) { val instance = Room.databaseBuilder( context.applicationContext, RoomDb::class.java, "tourist_attraction_database" ) // Wipes and rebuilds instead of migrating if no Migration object. .fallbackToDestructiveMigration() .build() INSTANCE = instance // return instance instance } } } }
0
Kotlin
0
0
792ef8a6b24dfba4f48191e27921f3901814cc09
1,213
TouristAttractionsinBulgaria
MIT License
app/src/main/java/com/kpstv/jettweet/ui/search/SearchScreen.kt
KaustubhPatange
317,543,580
false
null
package com.kpstv.jettweet.ui.search import androidx.compose.foundation.layout.padding import androidx.compose.material.Icon import androidx.compose.material.MaterialTheme import androidx.compose.material.Scaffold import androidx.compose.runtime.Composable import androidx.compose.ui.Modifier import androidx.compose.ui.res.vectorResource import androidx.compose.ui.unit.dp import com.kpstv.jettweet.R import com.kpstv.jettweet.ui.custom.JetTweetAppBar import com.kpstv.jettweet.ui.theme.JetTweetTheme import com.kpstv.jettweet.ui.utils.Screen @Composable fun Search(onNavClick: () -> Unit) { JetTweetTheme { Scaffold( topBar = { JetTweetAppBar( screen = Screen.SEARCH, onNavigationClick = onNavClick, content = { } ) }, bodyContent = { } ) } }
0
Kotlin
0
2
44967a4f375530fd02be01992c71fb4528bfac7a
932
JetTweet
Apache License 2.0
component/component-ding/src/main/java/love/forte/simbot/component/ding/utils/DingCatUtil.kt
simple-robot
554,852,615
false
null
/* * Copyright (c) 2020. ForteScarlet All rights reserved. * Project component-ding * File DingCQUtil.kt * Date 2020/8/8 下午5:44 * You can contact the author through the following channels: * github https://github.com/ForteScarlet * gitee https://gitee.com/ForteScarlet * email <EMAIL> * QQ 1149159218 */ @file:Suppress("MemberVisibilityCanBePrivate") package love.forte.simbot.component.ding.utils import love.forte.catcode.CatCodeUtil import love.forte.catcode.CodeTemplate import love.forte.catcode.Neko import love.forte.simbot.component.ding.exception.DingSpecialMessageException import love.forte.simbot.component.ding.exception.DingUnsupportedCodeException import love.forte.simbot.component.ding.messages.* /** * 钉钉消息与CQ码之间的转化工具类 */ object DingCatUtil { /** * 将字符串消息转化为钉钉特殊消息链 */ fun msgToDing(msg: String): DingSpecialMessageChain { val splitMsg = CatCodeUtil.split(msg) val msgList = splitMsg.asSequence().map { if (msg.startsWith("[CQ:")) { catCodeToDing(Neko.of(msg)) } else msg.toDingText() }.toList() return DingSpecialMessageChain(msgList.toTypedArray()) } /** * 将[KQCode] 转化为 [DingSpecialMessage] */ fun catCodeToDing(kqCode: Neko): DingSpecialMessage { return when (kqCode.type) { "at" -> { // 获取qq参数 val codes = kqCode["qq"] ?: kqCode["code"] ?: "" return CatDingTemplate.at(codes) } "ding-markdown" -> { val title = kqCode["title"] ?: throw DingSpecialMessageException("noCqParam: markdown, title") val text = kqCode["text"] ?: "" DingMarkdown(title, text) } // type link "ding-link" -> { val title = kqCode["title"] ?: throw DingSpecialMessageException("noCqParam: link, title") val text = kqCode["text"] ?: "" val messageUrl = kqCode["messageUrl"] ?: throw DingSpecialMessageException("noCqParam: link, messageUrl") val picUrl = kqCode["picUrl"] DingLink(title, text, messageUrl, picUrl) } // actionCard // [CQ:actionCard,...btnTitle=,btnUrl=] "ding-actionCard" -> { val title = kqCode["title"] ?: throw DingSpecialMessageException("noCqParam: actionCard, title") val text = kqCode["text"] ?: "" val btnOrientation = kqCode["text"] ?: "1" val btnTitle = kqCode["btnTitle"] ?: throw DingSpecialMessageException("noCqParam: actionCard, btnTitle") val btnUrl = kqCode["btnUrl"] ?: throw DingSpecialMessageException("noCqParam: actionCard, btnUrl") val btnTitleList = btnTitle.split(",") val btnUrlList = btnUrl.split(",") if(btnTitleList.size != btnUrlList.size){ throw DingSpecialMessageException("paramErr: actionCard. btnTitle.size != btnUrl.size") } if(btnTitleList.isEmpty()){ throw DingSpecialMessageException("paramErr: actionCard. btn param is empty.") } // return if(btnTitleList.size == 1){ DingWholeActionCard(title, text, btnOrientation, btnTitleList.first(), btnUrlList.first()) }else{ val btns = btnTitleList.mapIndexed { index, btnT -> val btnU = btnUrlList[index] DingAutonomyActionCardButtons(btnT, btnU) } DingAutonomyActionCard(title, text, btnOrientation, btns.toTypedArray()) } } // "ding-feedCard" -> { // // feed card 转化为CQ还挺麻烦的, 毕竟设计到数组 // // // // } else -> DingText(kqCode.toString()) } } } @Suppress("NOTHING_TO_INLINE") internal inline fun notSupport(name: String): Nothing { throw DingUnsupportedCodeException("notSupport: $name") } /** * 钉钉消息对于[CodeTemplate]的实现,目前只支持很少的类型: * - [CatDingTemplate.at] * - [CatDingTemplate.atAll] * - [CatDingTemplate.image] * 其余消息计划均转化为text类型的消息 * */ object CatDingTemplate : CodeTemplate<DingSpecialMessage> { /** * at类型的Ding消息 * 此处如果是多个code,可以用逗号分隔 */ override fun at(code: String): DingAt { return if (code.isEmpty()) { return DingAt.empty } else at(code.split(",")) } /** * at类型的Ding消息 * 可以同时存在code和all */ fun at(code: List<String>): DingAt { val codeList = code.toMutableList() val isAtAll = codeList.remove("all") return DingAt(codeList.toTypedArray(), isAtAll) } /** * @see at(List) */ fun at(codes: Array<String>): DingAt = at(codes.asList()) /** * at all, 使用的是[DingAt.atAll]静态单例 */ override fun atAll(): DingAt = DingAt.atAll /** * 此类型将会被转化为[DingLink]类型,且跳转链接与图片链接一样 * @param file 图片的链接 * @param flash 无效参数 */ override fun image(file: String, flash: Boolean): DingLink { return DingLink("图片", "", file, file) } @Deprecated("notSupport") override fun bface(id: String): DingSpecialMessage { notSupport("bface") } override fun customMusic(url: String, audio: String, title: String, content: String?, image: String?): DingSpecialMessage { notSupport("customMusic") } override fun dice(): DingSpecialMessage { notSupport("dice") } override fun dice(type: String): DingSpecialMessage { notSupport("dice") } override fun face(id: String): DingSpecialMessage { notSupport("face") } override fun music(type: String, id: String, style: String?): DingSpecialMessage { notSupport("music") } override fun record(file: String, magic: Boolean): DingSpecialMessage { notSupport("record") } override fun rps(): DingSpecialMessage { notSupport("rps") } override fun rps(type: String): DingSpecialMessage { notSupport("rps") } override fun sface(id: String): DingSpecialMessage { notSupport("sface") } override fun shake(): DingSpecialMessage { notSupport("shake") } override fun share(url: String, title: String, content: String?, image: String?): DingSpecialMessage { notSupport("share") } }
0
Kotlin
0
3
c5d7c9ca8c81b2bddc250090739d7c7d0c110328
6,510
simple-robot-v2
Apache License 2.0
navigator/src/main/java/com/santukis/navigator/Navigator.kt
santukis
309,307,272
false
null
package com.santukis.navigator import android.content.ActivityNotFoundException import android.content.pm.ActivityInfo import android.os.Build import androidx.annotation.IdRes import androidx.appcompat.app.AppCompatActivity import androidx.fragment.app.DialogFragment import androidx.fragment.app.Fragment import androidx.fragment.app.FragmentTransaction import androidx.navigation.NavDirections import androidx.navigation.findNavController import java.lang.ref.WeakReference abstract class Navigator(activity: AppCompatActivity) { protected val activity: WeakReference<AppCompatActivity> = WeakReference(activity) /** * @param phoneOrientation must be an ActivityInfo @ScreenOrientation value * @param tabletOrientation must be an ActivityInfo @ScreenOrientation value */ fun initializeScreenOrientation( phoneOrientation: Int = ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED, tabletOrientation: Int = ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED ) { activity.get()?.apply { requestedOrientation = when(isTablet(this.applicationContext)) { true -> tabletOrientation false -> phoneOrientation } } } fun openFragment(fragmentFactory: FragmentFactory) { val fragment = getFragment(fragmentFactory) showFragment(fragmentFactory, fragment) } fun openActivity( activityFactory: ActivityFactory, onSuccess: () -> Unit = { }, onError: (String) -> Unit = { } ) { activity.get()?.apply { try { startActivity(activityFactory.getIntent(this)) activityFactory.getAnimations().apply { overridePendingTransition(enterAnimation, exitAnimation) } onSuccess() } catch (exception: ActivityNotFoundException) { onError("Error: No Activity") } } ?: onError("Error: No Context") } fun openActivityForResult( activityFactory: ActivityFactory, requestCode: Int, onError: (String) -> Unit = { } ) { activity.get()?.apply { try { startActivityForResult(activityFactory.getIntent(this), requestCode) } catch (exception: ActivityNotFoundException) { onError(exception.message ?: "Unknown Error") } } } fun openActivityForResult( fragment: Fragment, activityFactory: ActivityFactory, requestCode: Int, onError: (String) -> Unit = { } ) { try { fragment.startActivityForResult(activityFactory.getIntent(fragment.requireContext()), requestCode) } catch (exception: ActivityNotFoundException) { onError(exception.message ?: "Unknown Error") } } fun closeCurrentFragment() { when { isLastFragment() -> closeActivity() else -> try { activity.get()?.supportFragmentManager?.popBackStackImmediate() } catch (exception: Exception) { //no-op } } } fun navigateTo(@IdRes viewId: Int, destiny: NavDirections) { try { activity.get()?.findNavController(viewId)?.navigate(destiny) } catch (exception: Exception) { //no-op } } fun navigateUp(@IdRes viewId: Int) { try { activity.get()?.findNavController(viewId)?.navigateUp() } catch (exception: Exception) { //no-op } } private fun closeActivity() { if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { activity.get()?.finishAfterTransition() } else { activity.get()?.finish() } } fun closeCurrentActivity() { closeActivity() } fun isFragmentVisible(fragment: Class<out Fragment>): Boolean { activity.get()?.supportFragmentManager?.fragments?.forEach { if (it.javaClass == fragment && it.isVisible){ return true } } return false } private fun resetBackStackIfNeeded() { val size = activity.get()?.supportFragmentManager?.backStackEntryCount ?: 0 for (index in 0 until size) { activity.get()?.supportFragmentManager?.popBackStack() } activity.get()?.supportFragmentManager?.executePendingTransactions() } private fun getFragment(fragmentFactory: FragmentFactory): Fragment { val fragment = getStackedFragment(fragmentFactory) return fragment ?: fragmentFactory.create() } private fun getStackedFragment(fragmentFactory: FragmentFactory): Fragment? { val fragment = activity.get()?.supportFragmentManager ?.findFragmentByTag(fragmentFactory.getBackStackTag()) return if (fragment != null) fragmentFactory.update(fragment) else null } private fun showFragment(fragmentFactory: FragmentFactory, fragment: Fragment) { when { fragment.isVisible -> refreshFragment(fragment) fragment is DialogFragment -> showDialogFragment(fragment, fragmentFactory) else -> loadFragment(fragmentFactory, fragment) } } private fun refreshFragment(fragment: Fragment) { val transaction = activity.get()?.supportFragmentManager?.beginTransaction() if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { transaction?.setReorderingAllowed(false) } transaction?.detach(fragment)?.attach(fragment)?.commitAllowingStateLoss() } private fun showDialogFragment(fragment: DialogFragment, fragmentFactory: FragmentFactory) { activity.get()?.apply { fragment.show(supportFragmentManager, fragmentFactory.getBackStackTag()) } } private fun loadFragment(fragmentFactory: FragmentFactory, fragment: Fragment) { try { getTransaction()?.let { transaction -> getContainerFor(fragmentFactory)?.let { container -> transaction.replace(container, fragment, fragmentFactory.getBackStackTag()) setUpTransactionAnimations(transaction, fragmentFactory) setUpTransactionBackStack(transaction, fragmentFactory) transaction.commitAllowingStateLoss() } ?: resetBackStackIfNeeded() } } catch (exception: Exception) { exception.printStackTrace() resetBackStackIfNeeded() loadFragment(fragmentFactory, fragment) } } private fun getTransaction(): FragmentTransaction? = activity.get()?.supportFragmentManager?.beginTransaction() private fun setUpTransactionBackStack( transaction: FragmentTransaction, fragmentFactory: FragmentFactory ) { when(val tag = fragmentFactory.getBackStackTag()) { null -> transaction.disallowAddToBackStack() else -> transaction.addToBackStack(tag) } } private fun setUpTransactionAnimations( transaction: FragmentTransaction, fragmentFactory: FragmentFactory ) { transaction.setCustomAnimations( fragmentFactory.getAnimations().enterAnimation, fragmentFactory.getAnimations().exitAnimation, fragmentFactory.getPopAnimations().enterAnimation, fragmentFactory.getPopAnimations().exitAnimation ) } protected abstract fun getContainerFor(fragmentFactory: FragmentFactory): Int? abstract fun isLastFragment(): Boolean }
0
Kotlin
0
0
ffa23f55f81b1074cd7429ad00a5bf8a70067f2f
7,683
navigator
MIT License
app/src/test/java/com/josphat/productsapp/MockRequestDispatcher.kt
josphatmwania
859,223,290
false
{"Kotlin": 33045}
package com.josphat.productsapp import mockwebserver3.Dispatcher import mockwebserver3.MockResponse import mockwebserver3.RecordedRequest import java.io.BufferedReader import java.io.InputStreamReader import java.lang.IllegalArgumentException class MockRequestDispatcher : Dispatcher() { override fun dispatch(request: RecordedRequest): MockResponse { return when (request.path) { "/products?price=2.49" -> { MockResponse() .setResponseCode(200) // HTTP_OK .setBody(getJson("productsresponse.json")) } else -> throw IllegalArgumentException("Unknown Request Path: ${request.path}") } } /** * Create a getJson function that takes a file name and returns its content as a String. */ private fun getJson(fileName: String): String { val inputStream = this::class.java.classLoader?.getResourceAsStream(fileName) ?: throw IllegalArgumentException("File not found: $fileName") return BufferedReader(InputStreamReader(inputStream)).use { it.readText() } } }
6
Kotlin
1
0
fd2003d367759b4dec1211596463ccf93a5797cd
1,119
ProductsApp
MIT License
components-compose/src/main/java/uk/gov/hmrc/components/compose/ui/theme/Dimensions.kt
hmrc
299,591,950
false
{"Kotlin": 556987, "Ruby": 10016, "Shell": 1395}
/* * Copyright 2023 HM Revenue & Customs * * 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 uk.gov.hmrc.components.compose.ui.theme import androidx.compose.ui.unit.Dp import androidx.compose.ui.unit.dp data class Dimensions( val hmrcSpacing4: Dp, val hmrcSpacing8: Dp, val hmrcSpacing16: Dp, val hmrcIconSize24: Dp, val hmrcButtonSize48: Dp, ) val smallDimensions = Dimensions( hmrcSpacing4 = 4.dp, hmrcSpacing8 = 8.dp, hmrcSpacing16 = 16.dp, hmrcIconSize24 = 24.dp, hmrcButtonSize48 = 48.dp ) val compactDimensions = Dimensions( hmrcSpacing4 = 4.dp, hmrcSpacing8 = 8.dp, hmrcSpacing16 = 16.dp, hmrcIconSize24 = 24.dp, hmrcButtonSize48 = 48.dp ) val mediumDimensions = Dimensions( hmrcSpacing4 = 4.dp, hmrcSpacing8 = 8.dp, hmrcSpacing16 = 16.dp, hmrcIconSize24 = 24.dp, hmrcButtonSize48 = 48.dp ) val largeDimensions = Dimensions( hmrcSpacing4 = 4.dp, hmrcSpacing8 = 8.dp, hmrcSpacing16 = 16.dp, hmrcIconSize24 = 24.dp, hmrcButtonSize48 = 48.dp )
4
Kotlin
2
7
d60c3c433a57493aae22b40bb27569c50a9417b6
1,573
android-components
Apache License 2.0
util-backend-test/src/main/kotlin/team/duckie/quackquack/util/backend/test/utils.kt
duckie-team
523,387,054
false
{"Kotlin": 901061, "MDX": 51559, "JavaScript": 6871, "CSS": 1060}
/* * Designed and developed by Duckie Team 2023. * * Licensed under the MIT. * Please see full license: https://github.com/duckie-team/quack-quack-android/blob/main/LICENSE */ package team.duckie.quackquack.util.backend.test import java.io.File public fun File.findGeneratedFileOrNull(fileName: String): File? = walkTopDown().find { it.name == fileName } public fun String.removePackageLine(): String = split("\n") .toMutableList() .apply { removeIf { line -> line.startsWith("package ") } } .joinToString("\n")
45
Kotlin
8
99
24d44663cf5bea29fc73595b5f60be03b08e162b
561
quack-quack-android
MIT License
src/main/kotlin/org/axonframework/intellij/ide/plugin/resolving/handlers/searchers/DeadlineHandlerSearcher.kt
AxonFramework
10,942,246
false
{"Kotlin": 330266}
/* * Copyright (c) 2022. Axon Framework * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.axonframework.intellij.ide.plugin.resolving.handlers.searchers import com.intellij.psi.PsiClass import com.intellij.psi.PsiMethod import org.axonframework.intellij.ide.plugin.api.AxonAnnotation import org.axonframework.intellij.ide.plugin.api.Handler import org.axonframework.intellij.ide.plugin.api.MessageHandlerType import org.axonframework.intellij.ide.plugin.resolving.handlers.types.DeadlineHandler import org.axonframework.intellij.ide.plugin.util.resolveAnnotationStringValue import org.axonframework.intellij.ide.plugin.util.resolvePayloadType import org.axonframework.intellij.ide.plugin.util.toQualifiedName /** * Searches for any handlers that can handle deadlines. * If there is not payload specific, the payload is java.lang.Object as fallback. * In addition, deadline handlers have a name. * * @see org.axonframework.intellij.ide.plugin.handlers.types.DeadlineHandler */ class DeadlineHandlerSearcher : AbstractHandlerSearcher(MessageHandlerType.DEADLINE) { override fun createMessageHandler(method: PsiMethod, annotation: PsiClass?): Handler { val payloadType = method.resolvePayloadType()?.toQualifiedName() ?: "java.lang.Object" val deadlineName = method.resolveAnnotationStringValue(AxonAnnotation.DEADLINE_HANDLER, "deadlineName") return DeadlineHandler(method, payloadType, deadlineName ?: payloadType) } }
22
Kotlin
19
34
781f71ca1707df9d23e624adddefa7050a408307
1,994
IdeaPlugin
Apache License 2.0
2022/src/main/kotlin/org/suggs/adventofcode/Day09RopeBridge.kt
suggitpe
321,028,552
false
{"Kotlin": 151090}
package org.suggs.adventofcode import org.slf4j.LoggerFactory object Day09RopeBridge { private val log = LoggerFactory.getLogger(this::class.java) fun countTailPositionsFrom(data: List<String>): Int { val instructions = data.map { it.split(" ") } data.forEach { log.debug("Processing $it yields ${newPositionAfter(it, Pair(0,0))}") } return 0 } private fun newPositionAfter(instruction: String, coordinates: Pair<Int, Int>): Pair<Int, Int> { return when (instruction.substringBefore(" ")) { "R" -> Pair(coordinates.first+1, coordinates.second) "L" -> Pair(coordinates.first-1, coordinates.second) "U" -> Pair(coordinates.first, coordinates.second+1) "D" -> Pair(coordinates.first, coordinates.second-1) else -> throw IllegalStateException("Cant process $instruction") } } }
0
Kotlin
0
0
ddb1f9545ffbd4f51db1747252741cd4300e7712
920
advent-of-code
Apache License 2.0
app/src/main/kotlin/it/vfsfitvnm/vimusic/utils/RingBuffer.kt
geekeie
861,208,877
false
null
package it.vfsfitvnm.vimusic.utils class RingBuffer<T>(val size: Int, init: (index: Int) -> T) { private val list = MutableList(size, init) private var index = 0 fun getOrNull(index: Int): T? = list.getOrNull(index) fun append(element: T) = list.set(index++ % size, element) }
0
Kotlin
0
0
e8bd63bdeef64c0a001c78cc8cf0097d9628fb66
297
YMusic
MIT License
locgetter/src/main/java/com/titanium/locgetter/main/LocationGetterBuilder.kt
titanium-codes
105,818,289
false
null
package com.titanium.locgetter.main import android.content.Context import android.util.Log import com.titanium.locgetter.exception.MockLocationException /** * Used to create new instances of [LocationGetter] */ class LocationGetterBuilder(private val context: Context) { /** * Custom logger * By default all logs goes to [Log.i] */ private var logger: (String, String) -> Unit = { tag, message -> Log.d(tag, message) } /** * Defines if locations getter will accept mocked locations * If set to false, mocked locations will cause a [MockLocationException] to be thrown * By default true */ private var acceptMockLocations = true /** * Custom logger * By default all logs goes to [Log.i] */ fun logger(logger: (String, String) -> Unit): LocationGetterBuilder { this.logger = logger return this } /** * Defines if locations getter will accept mocked locations * If set to false, mocked locations will cause a [MockLocationException] to be thrown * By default true */ fun acceptMockLocations(acceptMockLocations: Boolean): LocationGetterBuilder { this.acceptMockLocations = acceptMockLocations return this } /** * Builds new instance of [LocationGetter] */ fun build(): LocationGetter = MainLocationGetter(context.applicationContext, logger, acceptMockLocations) }
1
Kotlin
6
13
12551ce979128c2393b3dd40a2d7a0d4574f1cf3
1,432
LocGetter
MIT License
app/src/main/java/fr/jonathangerbaud/ktx/TextView.kt
jonathangerbaud
155,224,184
false
null
package fr.jonathangerbaud.ktx import android.widget.TextView fun TextView.setTextOrHide(text: String?) { if (text.isNullOrBlank()) { hide() } else { this.text = text show() } }
1
null
1
1
d9857842495300aaf0b9a77820e23d5c76055405
227
AndroidCommons
MIT License
app/src/main/java/com/jrk/mood4food/recipes/selection/RecipeAdapter.kt
Honrix
369,880,093
false
null
package com.jrk.mood4food.recipes.selection import android.net.Uri import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.webkit.RenderProcessGoneDetail import android.widget.ImageView import android.widget.TextView import androidx.recyclerview.widget.RecyclerView import com.jrk.mood4food.R import com.jrk.mood4food.recipes.detail.model.RecipeEntity import com.jrk.mood4food.recipes.selection.view.RecipeClickListener class RecipeAdapter(private val dataSet: Array<RecipeEntity>, private val recipeClickListener: RecipeClickListener, private val api: Boolean) : RecyclerView.Adapter<RecipeAdapter.ViewHolder>(){ class ViewHolder(view: View) : RecyclerView.ViewHolder(view){ //Define Views which are used in "onBindViewHolder" val textView = view.findViewById<TextView>(R.id.recipe_card_title) val cardView = view.findViewById<androidx.cardview.widget.CardView>(R.id.recipe_card) val imageView = view.findViewById<ImageView>(R.id.recipe_card_image) val favView = view.findViewById<ImageView>(R.id.Fav) val nofavView = view.findViewById<ImageView>(R.id.noFav) } // Create new views (invoked by the layout manager) override fun onCreateViewHolder(viewGroup: ViewGroup, viewType: Int): ViewHolder { // Load Adapter val view = LayoutInflater.from(viewGroup.context) .inflate(R.layout.adapter_recipe, viewGroup, false) return ViewHolder(view) } // Replace the contents of a view (invoked by the layout manager) override fun onBindViewHolder(viewHolder: ViewHolder, position: Int) { // Put data into the views defined by viewHolder viewHolder.textView.text = dataSet[position].title viewHolder.cardView.setOnClickListener{ if(api){ recipeClickListener.onRecipeClickListener(dataSet[position].APIid.toString(), api) }else{ recipeClickListener.onRecipeClickListener(dataSet[position].storageAddress.toString(), api) } } viewHolder.imageView.setImageURI(Uri.parse(dataSet[position].imageUri)) if(dataSet[position].favorite){ viewHolder.nofavView.visibility = View.GONE }else{ viewHolder.favView.visibility = View.GONE } if(api){ viewHolder.nofavView.visibility = View.GONE viewHolder.favView.visibility = View.GONE } } // Return the size of your dataset (invoked by the layout manager) override fun getItemCount() = dataSet.size }
0
null
0
0
fc086543ef8993e5e43d070d8754f60c94bda003
2,644
Mood4Food
MIT License
src/test/kotlin/de/flapdoodle/statik/filetypes/TomlTest.kt
flapdoodle-oss
350,813,259
false
null
package de.flapdoodle.statik.filetypes import de.flapdoodle.statik.io.readResource import org.junit.jupiter.api.Test class TomlTest { @Test fun readSampleToml() { val sample = javaClass.readResource("sample.toml") val tree = Toml.asTree(sample) // println("tree: $tree") } }
0
Kotlin
1
0
347ea640ac74ed937f362dfe4d3b42c50c50a8c8
314
de.flapdoodle.static
Apache License 2.0
ui-lib/src/main/java/co/electriccoin/zcash/ui/screen/authentication/AndroidAuthentication.kt
Electric-Coin-Company
390,808,594
false
{"Kotlin": 1834553}
@file:Suppress("ktlint:standard:filename") package co.electriccoin.zcash.ui.screen.authentication import android.widget.Toast import androidx.activity.viewModels import androidx.compose.runtime.Composable import androidx.compose.runtime.LaunchedEffect import androidx.compose.ui.res.stringResource import androidx.lifecycle.compose.collectAsStateWithLifecycle import co.electriccoin.zcash.spackle.Twig import co.electriccoin.zcash.ui.MainActivity import co.electriccoin.zcash.ui.R import co.electriccoin.zcash.ui.common.viewmodel.AuthenticationResult import co.electriccoin.zcash.ui.common.viewmodel.AuthenticationViewModel import co.electriccoin.zcash.ui.screen.authentication.view.AppAccessAuthentication import co.electriccoin.zcash.ui.screen.authentication.view.AuthenticationErrorDialog import co.electriccoin.zcash.ui.screen.authentication.view.AuthenticationFailedDialog import kotlin.time.Duration.Companion.milliseconds private const val APP_ACCESS_TRIGGER_DELAY = 0 private const val DELETE_WALLET_TRIGGER_DELAY = 0 private const val EXPORT_PRIVATE_DATA_TRIGGER_DELAY = 0 private const val SEED_RECOVERY_TRIGGER_DELAY = 0 private const val SEND_FUNDS_DELAY = 0 private const val RETRY_TRIGGER_DELAY = 0 @Composable internal fun MainActivity.WrapAuthentication( goSupport: () -> Unit, onSuccess: () -> Unit, onCancel: () -> Unit, onFailed: () -> Unit, useCase: AuthenticationUseCase, ) { WrapAuthenticationUseCases( activity = this, goSupport = goSupport, onSuccess = onSuccess, onCancel = onCancel, onFailed = onFailed, useCase = useCase ) } @Composable @Suppress("LongParameterList") private fun WrapAuthenticationUseCases( activity: MainActivity, goSupport: () -> Unit, onSuccess: () -> Unit, onCancel: () -> Unit, onFailed: () -> Unit, useCase: AuthenticationUseCase, ) { when (useCase) { AuthenticationUseCase.AppAccess -> { Twig.debug { "App Access Authentication" } WrapAppAccessAuth( activity = activity, goToAppContent = onSuccess, goSupport = goSupport, onCancel = onCancel, onFailed = onFailed ) } AuthenticationUseCase.ExportPrivateData -> { Twig.debug { "Export Private Data Authentication" } WrapAppExportPrivateDataAuth( activity = activity, goExportPrivateData = onSuccess, goSupport = goSupport, onCancel = onCancel, onFailed = onFailed ) } AuthenticationUseCase.DeleteWallet -> { Twig.debug { "Delete Wallet Authentication" } WrapDeleteWalletAuth( activity = activity, goDeleteWallet = onSuccess, goSupport = goSupport, onCancel = onCancel, onFailed = onFailed ) } AuthenticationUseCase.SeedRecovery -> { Twig.debug { "Seed Recovery Authentication" } WrapSeedRecoveryAuth( activity = activity, goSeedRecovery = onSuccess, goSupport = goSupport, onCancel = onCancel, onFailed = onFailed ) } AuthenticationUseCase.SendFunds -> { Twig.debug { "Send Funds Authentication" } WrapSendFundsAuth( activity = activity, onSendFunds = onSuccess, goSupport = goSupport, onCancel = onCancel, onFailed = onFailed ) } } } @Composable private fun WrapDeleteWalletAuth( activity: MainActivity, goSupport: () -> Unit, goDeleteWallet: () -> Unit, onCancel: () -> Unit, onFailed: () -> Unit, ) { val authenticationViewModel by activity.viewModels<AuthenticationViewModel>() val authenticationResult = authenticationViewModel.authenticationResult .collectAsStateWithLifecycle(initialValue = AuthenticationResult.None).value when (authenticationResult) { AuthenticationResult.None -> { Twig.info { "Authentication result: initiating" } // Initial state } AuthenticationResult.Success -> { Twig.info { "Authentication result: successful" } authenticationViewModel.resetAuthenticationResult() goDeleteWallet() } AuthenticationResult.Canceled -> { Twig.info { "Authentication result: canceled" } authenticationViewModel.resetAuthenticationResult() onCancel() } AuthenticationResult.Failed -> { Twig.warn { "Authentication result: failed" } authenticationViewModel.resetAuthenticationResult() onFailed() Toast.makeText(activity, activity.getString(R.string.authentication_toast_failed), Toast.LENGTH_SHORT) .show() } is AuthenticationResult.Error -> { Twig.error { "Authentication result: error: ${authenticationResult.errorCode}: ${authenticationResult.errorMessage}" } AuthenticationErrorDialog( onDismiss = { // Reset authentication states authenticationViewModel.resetAuthenticationResult() onCancel() }, onRetry = { authenticationViewModel.resetAuthenticationResult() authenticationViewModel.authenticate( activity = activity, initialAuthSystemWindowDelay = RETRY_TRIGGER_DELAY.milliseconds, useCase = AuthenticationUseCase.DeleteWallet ) }, onSupport = { authenticationViewModel.resetAuthenticationResult() goSupport() }, reason = authenticationResult ) } } // Starting authentication LaunchedEffect(key1 = true) { authenticationViewModel.authenticate( activity = activity, initialAuthSystemWindowDelay = DELETE_WALLET_TRIGGER_DELAY.milliseconds, useCase = AuthenticationUseCase.DeleteWallet ) } } @Composable private fun WrapAppExportPrivateDataAuth( activity: MainActivity, goSupport: () -> Unit, goExportPrivateData: () -> Unit, onCancel: () -> Unit, onFailed: () -> Unit, ) { val authenticationViewModel by activity.viewModels<AuthenticationViewModel>() val authenticationResult = authenticationViewModel.authenticationResult .collectAsStateWithLifecycle(initialValue = AuthenticationResult.None).value when (authenticationResult) { AuthenticationResult.None -> { Twig.info { "Authentication result: initiating" } // Initial state } AuthenticationResult.Success -> { Twig.info { "Authentication result: successful" } authenticationViewModel.resetAuthenticationResult() goExportPrivateData() } AuthenticationResult.Canceled -> { Twig.info { "Authentication result: canceled" } authenticationViewModel.resetAuthenticationResult() onCancel() } AuthenticationResult.Failed -> { Twig.warn { "Authentication result: failed" } authenticationViewModel.resetAuthenticationResult() onFailed() Toast.makeText(activity, stringResource(id = R.string.authentication_toast_failed), Toast.LENGTH_SHORT) .show() } is AuthenticationResult.Error -> { Twig.error { "Authentication result: error: ${authenticationResult.errorCode}: ${authenticationResult.errorMessage}" } AuthenticationErrorDialog( onDismiss = { // Reset authentication states authenticationViewModel.resetAuthenticationResult() onCancel() }, onRetry = { authenticationViewModel.resetAuthenticationResult() authenticationViewModel.authenticate( activity = activity, initialAuthSystemWindowDelay = RETRY_TRIGGER_DELAY.milliseconds, useCase = AuthenticationUseCase.ExportPrivateData ) }, onSupport = { authenticationViewModel.resetAuthenticationResult() goSupport() }, reason = authenticationResult ) } } // Starting authentication LaunchedEffect(key1 = true) { authenticationViewModel.authenticate( activity = activity, initialAuthSystemWindowDelay = EXPORT_PRIVATE_DATA_TRIGGER_DELAY.milliseconds, useCase = AuthenticationUseCase.ExportPrivateData ) } } @Composable private fun WrapSeedRecoveryAuth( activity: MainActivity, goSupport: () -> Unit, goSeedRecovery: () -> Unit, onCancel: () -> Unit, onFailed: () -> Unit, ) { val authenticationViewModel by activity.viewModels<AuthenticationViewModel>() val authenticationResult = authenticationViewModel.authenticationResult .collectAsStateWithLifecycle(initialValue = AuthenticationResult.None).value when (authenticationResult) { AuthenticationResult.None -> { Twig.info { "Authentication result: initiating" } // Initial state } AuthenticationResult.Success -> { Twig.info { "Authentication result: successful" } authenticationViewModel.resetAuthenticationResult() goSeedRecovery() } AuthenticationResult.Canceled -> { Twig.info { "Authentication result: canceled" } authenticationViewModel.resetAuthenticationResult() onCancel() } AuthenticationResult.Failed -> { Twig.warn { "Authentication result: failed" } authenticationViewModel.resetAuthenticationResult() onFailed() Toast.makeText(activity, stringResource(id = R.string.authentication_toast_failed), Toast.LENGTH_SHORT) .show() } is AuthenticationResult.Error -> { Twig.error { "Authentication result: error: ${authenticationResult.errorCode}: ${authenticationResult.errorMessage}" } AuthenticationErrorDialog( onDismiss = { // Reset authentication states authenticationViewModel.resetAuthenticationResult() onCancel() }, onRetry = { authenticationViewModel.resetAuthenticationResult() authenticationViewModel.authenticate( activity = activity, initialAuthSystemWindowDelay = RETRY_TRIGGER_DELAY.milliseconds, useCase = AuthenticationUseCase.SeedRecovery ) }, onSupport = { authenticationViewModel.resetAuthenticationResult() goSupport() }, reason = authenticationResult ) } } // Starting authentication LaunchedEffect(key1 = true) { authenticationViewModel.authenticate( activity = activity, initialAuthSystemWindowDelay = SEED_RECOVERY_TRIGGER_DELAY.milliseconds, useCase = AuthenticationUseCase.SeedRecovery ) } } @Composable @Suppress("LongMethod") private fun WrapSendFundsAuth( activity: MainActivity, goSupport: () -> Unit, onSendFunds: () -> Unit, onCancel: () -> Unit, onFailed: () -> Unit, ) { val authenticationViewModel by activity.viewModels<AuthenticationViewModel>() val authenticationResult = authenticationViewModel.authenticationResult .collectAsStateWithLifecycle(initialValue = AuthenticationResult.None).value when (authenticationResult) { AuthenticationResult.None -> { Twig.info { "Authentication result: initiating" } // Initial state } AuthenticationResult.Success -> { Twig.info { "Authentication result: successful" } authenticationViewModel.resetAuthenticationResult() onSendFunds() } AuthenticationResult.Canceled -> { Twig.info { "Authentication result: canceled" } authenticationViewModel.resetAuthenticationResult() onCancel() } AuthenticationResult.Failed -> { Twig.warn { "Authentication result: failed" } authenticationViewModel.resetAuthenticationResult() onFailed() Toast.makeText(activity, stringResource(id = R.string.authentication_toast_failed), Toast.LENGTH_SHORT) .show() } is AuthenticationResult.Error -> { Twig.error { "Authentication result: error: ${authenticationResult.errorCode}: ${authenticationResult.errorMessage}" } AuthenticationErrorDialog( onDismiss = { // Reset authentication states authenticationViewModel.resetAuthenticationResult() onCancel() }, onRetry = { authenticationViewModel.resetAuthenticationResult() authenticationViewModel.authenticate( activity = activity, initialAuthSystemWindowDelay = RETRY_TRIGGER_DELAY.milliseconds, useCase = AuthenticationUseCase.SendFunds ) }, onSupport = { authenticationViewModel.resetAuthenticationResult() goSupport() }, reason = authenticationResult ) } } // Starting authentication LaunchedEffect(key1 = true) { authenticationViewModel.authenticate( activity = activity, initialAuthSystemWindowDelay = SEND_FUNDS_DELAY.milliseconds, useCase = AuthenticationUseCase.SendFunds ) } } @Composable @Suppress("LongMethod") private fun WrapAppAccessAuth( activity: MainActivity, goSupport: () -> Unit, goToAppContent: () -> Unit, onCancel: () -> Unit, onFailed: () -> Unit, ) { val authenticationViewModel by activity.viewModels<AuthenticationViewModel>() val welcomeAnimVisibility = authenticationViewModel.showWelcomeAnimation.collectAsStateWithLifecycle().value AppAccessAuthentication(welcomeAnimVisibility = welcomeAnimVisibility) val authenticationResult = authenticationViewModel.authenticationResult .collectAsStateWithLifecycle(initialValue = AuthenticationResult.None).value when (authenticationResult) { AuthenticationResult.None -> { Twig.debug { "Authentication result: initiating" } // Initial state } AuthenticationResult.Success -> { Twig.debug { "Authentication result: successful" } authenticationViewModel.resetAuthenticationResult() authenticationViewModel.setWelcomeAnimationDisplayed() goToAppContent() } AuthenticationResult.Canceled -> { Twig.info { "Authentication result: canceled: shutting down" } authenticationViewModel.resetAuthenticationResult() Toast.makeText(activity, stringResource(id = R.string.authentication_toast_canceled), Toast.LENGTH_SHORT) .show() onCancel() } AuthenticationResult.Failed -> { Twig.warn { "Authentication result: failed" } onFailed() AuthenticationFailedDialog( onDismiss = { authenticationViewModel.resetAuthenticationResult() onCancel() }, onRetry = { authenticationViewModel.resetAuthenticationResult() authenticationViewModel.authenticate( activity = activity, initialAuthSystemWindowDelay = RETRY_TRIGGER_DELAY.milliseconds, useCase = AuthenticationUseCase.AppAccess ) }, onSupport = { authenticationViewModel.resetAuthenticationResult() goSupport() } ) } is AuthenticationResult.Error -> { Twig.error { "Authentication result: error: ${authenticationResult.errorCode}: ${authenticationResult.errorMessage}" } AuthenticationErrorDialog( onDismiss = { authenticationViewModel.resetAuthenticationResult() onCancel() }, onRetry = { authenticationViewModel.resetAuthenticationResult() authenticationViewModel.authenticate( activity = activity, initialAuthSystemWindowDelay = RETRY_TRIGGER_DELAY.milliseconds, useCase = AuthenticationUseCase.AppAccess ) }, onSupport = { authenticationViewModel.resetAuthenticationResult() goSupport() }, reason = authenticationResult ) } } // Starting authentication LaunchedEffect(key1 = true) { authenticationViewModel.authenticate( activity = activity, initialAuthSystemWindowDelay = APP_ACCESS_TRIGGER_DELAY.milliseconds, useCase = AuthenticationUseCase.AppAccess ) } } sealed class AuthenticationUseCase { data object AppAccess : AuthenticationUseCase() data object SeedRecovery : AuthenticationUseCase() data object DeleteWallet : AuthenticationUseCase() data object ExportPrivateData : AuthenticationUseCase() data object SendFunds : AuthenticationUseCase() }
173
Kotlin
15
25
359d4a5eea03dfb3c1ffbc5df1baca1c6f7917a7
18,706
zashi-android
MIT License
app/src/main/java/com/goldenowl/ecommerceapp/data/OrderRepository.kt
Catelt
556,541,382
false
{"Kotlin": 398009, "Batchfile": 284}
package com.goldenowl.ecommerceapp.data import androidx.lifecycle.MutableLiveData import androidx.lifecycle.asFlow import com.goldenowl.ecommerceapp.utilities.ORDER_USER import com.goldenowl.ecommerceapp.utilities.STATUS_ORDER import com.goldenowl.ecommerceapp.utilities.TIME_CREATE import com.goldenowl.ecommerceapp.utilities.USER_FIREBASE import com.google.firebase.firestore.FirebaseFirestore import com.google.firebase.firestore.ktx.toObject import kotlinx.coroutines.flow.Flow import javax.inject.Inject import javax.inject.Singleton @Singleton class OrderRepository @Inject constructor( private val userManager: UserManager, private val db: FirebaseFirestore ) { val totalOrder = MutableLiveData(0) fun getOrderStatus(status: Int): MutableLiveData<List<Order>> { val result = MutableLiveData<List<Order>>() db.collection(USER_FIREBASE) .document(userManager.getAccessToken()) .collection(ORDER_USER) .whereEqualTo(STATUS_ORDER, status) .orderBy(TIME_CREATE, TypeSort.DESCENDING.value) .get() .addOnSuccessListener { documents -> val list = mutableSetOf<Order>() for (doc in documents) { list.add(doc.toObject()) } result.postValue(list.toList()) } return result } fun getSize() { if (userManager.isLogged()) { db.collection(USER_FIREBASE) .document(userManager.getAccessToken()) .collection(ORDER_USER) .get() .addOnSuccessListener { documents -> totalOrder.postValue(documents.size()) } } } fun getOrder(idOrder: String): Flow<Order> { val result = MutableLiveData<Order>() if (userManager.isLogged() && idOrder.isNotBlank()) { db.collection(USER_FIREBASE) .document(userManager.getAccessToken()) .collection(ORDER_USER) .document(idOrder) .get() .addOnSuccessListener { document -> result.postValue(document.toObject()) } } return result.asFlow() } fun setOrderFirebase(order: Order): MutableLiveData<Boolean> { val result = MutableLiveData(false) db.collection(USER_FIREBASE) .document(userManager.getAccessToken()) .collection(ORDER_USER) .document(order.id) .set(order) .addOnSuccessListener { result.postValue(true) } return result } }
0
Kotlin
0
0
ee67ef6cc8512fe1928050a06a034ce5829d8671
2,689
E-Commerce-Application
MIT License
data/src/main/java/com/mctech/data/quotation/model/RandomQuotationResponse.kt
MayconCardoso
198,072,780
false
null
package com.mctech.data.quotation.model import com.google.gson.annotations.SerializedName import java.util.* /** * @author <NAME> on 2019-11-06. */ class RandomQuotationResponse( @SerializedName("quote_id") val id: String, @SerializedName("appeared_at") val date: Date, @SerializedName("tags") val tags: List<String>, @SerializedName("value") val description: String, @SerializedName("_embedded") val embedded: RandomQuotationEmbeddedResponse )
0
Kotlin
4
21
7c2d04f56439c42b6bf8bc26807be25111d90dde
494
Modularized-Kotlin-Clean-Architecture-Showcase
Apache License 2.0
app/src/main/java/live/mehiz/mpvkt/ui/player/controls/components/panels/SubtitleSettingsColorsCard.kt
abdallahmehiz
799,697,356
false
null
package live.mehiz.mpvkt.ui.player.controls.components.panels import androidx.annotation.StringRes import androidx.compose.foundation.horizontalScroll import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.Spacer import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.widthIn import androidx.compose.foundation.rememberScrollState import androidx.compose.material.icons.Icons import androidx.compose.material.icons.filled.BorderColor import androidx.compose.material.icons.filled.FormatColorFill import androidx.compose.material.icons.filled.FormatColorReset import androidx.compose.material.icons.filled.FormatColorText import androidx.compose.material.icons.filled.Palette import androidx.compose.material3.Icon import androidx.compose.material3.IconToggleButton import androidx.compose.material3.MaterialTheme import androidx.compose.material3.Text import androidx.compose.material3.TextButton import androidx.compose.runtime.Composable import androidx.compose.runtime.LaunchedEffect import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableIntStateOf import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.runtime.setValue import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.graphics.Color import androidx.compose.ui.res.stringResource import androidx.core.graphics.alpha import androidx.core.graphics.blue import androidx.core.graphics.green import androidx.core.graphics.red import `is`.xyz.mpv.MPVLib import live.mehiz.mpvkt.R import live.mehiz.mpvkt.preferences.SubtitlesPreferences import live.mehiz.mpvkt.preferences.preference.Preference import live.mehiz.mpvkt.preferences.preference.collectAsState import live.mehiz.mpvkt.preferences.preference.deleteAndGet import live.mehiz.mpvkt.presentation.components.ExpandableCard import live.mehiz.mpvkt.presentation.components.TintedSliderItem import live.mehiz.mpvkt.ui.theme.spacing import org.koin.compose.koinInject @Composable fun SubtitleSettingsColorsCard( modifier: Modifier = Modifier, ) { val preferences = koinInject<SubtitlesPreferences>() var isExpanded by remember { mutableStateOf(true) } ExpandableCard( isExpanded = isExpanded, onExpand = { isExpanded = !isExpanded }, title = { Row( horizontalArrangement = Arrangement.spacedBy(MaterialTheme.spacing.medium), ) { Icon(Icons.Default.Palette, null) Text(stringResource(R.string.player_sheets_sub_colors_card_title)) } }, modifier = modifier.widthIn(max = CARDS_MAX_WIDTH), colors = panelCardsColors(), ) { Column { var currentColorType by remember { mutableStateOf(SubColorType.Text) } var currentColor by remember { mutableIntStateOf(preferences.textColor.get()) } Row( horizontalArrangement = Arrangement.Center, verticalAlignment = Alignment.CenterVertically, modifier = Modifier .fillMaxWidth() .horizontalScroll(rememberScrollState()) .padding(start = MaterialTheme.spacing.extraSmall, end = MaterialTheme.spacing.medium), ) { SubColorType.entries.forEach { type -> IconToggleButton( checked = currentColorType == type, onCheckedChange = { currentColorType = type currentColor = when (currentColorType) { SubColorType.Text -> preferences.textColor.get() SubColorType.Border -> preferences.borderColor.get() SubColorType.Background -> preferences.backgroundColor.get() } }, ) { Icon( when (type) { SubColorType.Text -> Icons.Default.FormatColorText SubColorType.Border -> Icons.Default.BorderColor SubColorType.Background -> Icons.Default.FormatColorFill }, null, ) } } Text(stringResource(currentColorType.titleRes)) Spacer(Modifier.weight(1f)) TextButton(onClick = { resetColors(preferences) }) { Row(horizontalArrangement = Arrangement.spacedBy(MaterialTheme.spacing.extraSmall)) { Icon(Icons.Default.FormatColorReset, null) Text(stringResource(R.string.generic_reset)) } } } SubtitlesColorPicker(currentColorType) } } } fun Int.copyAsArgb( alpha: Int = this.alpha, red: Int = this.red, green: Int = this.green, blue: Int = this.blue, ) = (alpha shl 24) or (red shl 16) or (green shl 8) or blue @OptIn(ExperimentalStdlibApi::class) fun Int.toColorHexString() = "#" + this.toHexString().uppercase() enum class SubColorType( @StringRes val titleRes: Int, val property: String, val preference: (SubtitlesPreferences) -> Preference<Int>, ) { Text( R.string.player_sheets_subtitles_color_text, "sub-color", preference = SubtitlesPreferences::textColor, ), Border( R.string.player_sheets_subtitles_color_border, "sub-border-color", preference = SubtitlesPreferences::borderColor, ), Background( R.string.player_sheets_subtitles_color_background, "sub-back-color", preference = SubtitlesPreferences::backgroundColor, ) } fun resetColors(preferences: SubtitlesPreferences) { MPVLib.setPropertyString("sub-color", preferences.textColor.deleteAndGet().toColorHexString()) MPVLib.setPropertyString("sub-border-color", preferences.borderColor.deleteAndGet().toColorHexString()) MPVLib.setPropertyString("sub-back-color", preferences.backgroundColor.deleteAndGet().toColorHexString()) } @Composable fun SubtitlesColorPicker(type: SubColorType) { val preferences = koinInject<SubtitlesPreferences>() val preference = type.preference(preferences) val currentColor by preference.collectAsState() LaunchedEffect(currentColor) { MPVLib.setPropertyString(type.property, currentColor.toColorHexString()) } TintedSliderItem( stringResource(R.string.player_sheets_sub_color_red), currentColor.red, currentColor.red.toString(), onChange = { preference.set(currentColor.copyAsArgb(red = it)) }, max = 255, tint = Color.Red, ) TintedSliderItem( stringResource(R.string.player_sheets_sub_color_green), currentColor.green, currentColor.green.toString(), onChange = { preference.set(currentColor.copyAsArgb(green = it)) }, max = 255, tint = Color.Green, ) TintedSliderItem( stringResource(R.string.player_sheets_sub_color_blue), currentColor.blue, currentColor.blue.toString(), onChange = { preference.set(currentColor.copyAsArgb(blue = it)) }, max = 255, tint = Color.Blue, ) TintedSliderItem( stringResource(R.string.player_sheets_sub_color_alpha), currentColor.alpha, currentColor.alpha.toString(), onChange = { preference.set(currentColor.copyAsArgb(alpha = it)) }, max = 255, tint = Color.White, ) }
6
null
2
30
8d3bfbdad09d537291e9369e45d1f6f62c8cc82a
7,203
mpvKt
Apache License 2.0
src/commonMain/kotlin/coingecko/models/coins/data/IcoData.kt
DrewCarlson
267,978,965
false
null
package coingecko.models.coins.data import kotlinx.serialization.SerialName import kotlinx.serialization.Serializable @Serializable data class IcoData( @SerialName("ico_start_date") val icoStartDate: String? = null, @SerialName("ico_end_date") val icoEndDate: String? = null, @SerialName("short_desc") val shortDesc: String? = null, val description: String? = null, val links: IcoLinks? = null, @SerialName("softcap_currency") val softcapCurrency: String? = null, @SerialName("hardcap_currency") val hardcapCurrency: String? = null, @SerialName("total_raised_currency") val totalRaisedCurrency: String? = null, @SerialName("softcap_amount") val softcapAmount: Double?, @SerialName("hardcap_amount") val hardcapAmount: Double?, @SerialName("total_raised") val totalRaised: Double?, @SerialName("quote_pre_sale_currency") val quotePreSaleCurrency: String? = null, @SerialName("base_pre_sale_amount") val basePreSaleAmount: Double?, @SerialName("quote_pre_sale_amount") val quotePreSaleAmount: Double?, @SerialName("quote_public_sale_currency") val quotePublicSaleCurrency: String? = null, @SerialName("base_public_sale_amount") val basePublicSaleAmount: String? = null, @SerialName("quote_public_sale_amount") val quotePublicSaleAmount: String? = null, @SerialName("accepting_currencies") val acceptingCurrencies: String? = null, @SerialName("country_origin") val countryOrigin: String? = null, @SerialName("pre_sale_start_date") val preSaleStartDate: String? = null, @SerialName("pre_sale_end_date") val preSaleEndDate: String? = null, @SerialName("whitelist_url") val whitelistUrl: String? = null, @SerialName("whitelist_start_date") val whitelistStartDate: String? = null, @SerialName("whitelist_end_date") val whitelistEndDate: String? = null, @SerialName("bounty_detail_url") val bountyDetailUrl: String? = null, @SerialName("amount_for_sale") val amountForSale: Double?, @SerialName("kyc_required") val kycRequired: Boolean = false, @SerialName("whitelist_available") val whitelistAvailable: Boolean?, @SerialName("pre_sale_available") val preSaleAvailable: Boolean?, @SerialName("pre_sale_ended") val preSaleEnded: Boolean = false )
5
null
9
44
64d96a5971fa9b47c2786ad6f44ceea71ab6fb5f
2,372
CoinGecko-Kotlin
MIT License
shared/src/commonMain/kotlin/utils/BaseViewModel.kt
Flop88
630,059,851
false
null
package utils import kotlinx.coroutines.CoroutineScope expect abstract class CoroutineViewModel() { val coroutineScope: CoroutineScope fun dispose() protected open fun onCleared() }
0
Kotlin
0
0
568789888436199fa5fccd1a7057bb6c3b6dbb15
197
kmp_ai_helper
Apache License 2.0
notifications/src/main/kotlin/com/amazon/opendistroforelasticsearch/notifications/action/PluginBaseAction.kt
opendistro-for-elasticsearch
294,836,105
false
null
/* * Copyright 2020 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://www.apache.org/licenses/LICENSE-2.0 * * or in the "license" file accompanying this file. This file 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.amazon.opendistroforelasticsearch.notifications.action import com.amazon.opendistroforelasticsearch.commons.ConfigConstants import com.amazon.opendistroforelasticsearch.commons.authuser.User import com.amazon.opendistroforelasticsearch.notifications.NotificationPlugin.Companion.LOG_PREFIX import com.amazon.opendistroforelasticsearch.commons.utils.logger import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.launch import org.elasticsearch.ElasticsearchSecurityException import org.elasticsearch.ElasticsearchStatusException import org.elasticsearch.action.ActionListener import org.elasticsearch.action.ActionRequest import org.elasticsearch.action.ActionResponse import org.elasticsearch.action.support.ActionFilters import org.elasticsearch.action.support.HandledTransportAction import org.elasticsearch.client.Client import org.elasticsearch.common.io.stream.Writeable import org.elasticsearch.index.IndexNotFoundException import org.elasticsearch.index.engine.VersionConflictEngineException import org.elasticsearch.indices.InvalidIndexNameException import org.elasticsearch.rest.RestStatus import org.elasticsearch.tasks.Task import org.elasticsearch.transport.TransportService import java.io.IOException internal abstract class PluginBaseAction<Request : ActionRequest, Response : ActionResponse>( name: String, transportService: TransportService, val client: Client, actionFilters: ActionFilters, requestReader: Writeable.Reader<Request> ) : HandledTransportAction<Request, Response>(name, transportService, actionFilters, requestReader) { companion object { private val log by logger(PluginBaseAction::class.java) private val scope: CoroutineScope = CoroutineScope(Dispatchers.IO) } /** * {@inheritDoc} */ @Suppress("TooGenericExceptionCaught") override fun doExecute( task: Task?, request: Request, listener: ActionListener<Response> ) { val userStr: String? = client.threadPool().threadContext.getTransient<String>(ConfigConstants.OPENDISTRO_SECURITY_USER_INFO_THREAD_CONTEXT) val user: User? = User.parse(userStr) scope.launch { try { listener.onResponse(executeRequest(request, user)) } catch (exception: ElasticsearchStatusException) { log.warn("$LOG_PREFIX:ElasticsearchStatusException:", exception) listener.onFailure(exception) } catch (exception: ElasticsearchSecurityException) { log.warn("$LOG_PREFIX:ElasticsearchSecurityException:", exception) listener.onFailure(ElasticsearchStatusException("Permissions denied: ${exception.message} - Contact administrator", RestStatus.FORBIDDEN)) } catch (exception: VersionConflictEngineException) { log.warn("$LOG_PREFIX:VersionConflictEngineException:", exception) listener.onFailure(ElasticsearchStatusException(exception.message, RestStatus.CONFLICT)) } catch (exception: IndexNotFoundException) { log.warn("$LOG_PREFIX:IndexNotFoundException:", exception) listener.onFailure(ElasticsearchStatusException(exception.message, RestStatus.NOT_FOUND)) } catch (exception: InvalidIndexNameException) { log.warn("$LOG_PREFIX:InvalidIndexNameException:", exception) listener.onFailure(ElasticsearchStatusException(exception.message, RestStatus.BAD_REQUEST)) } catch (exception: IllegalArgumentException) { log.warn("$LOG_PREFIX:IllegalArgumentException:", exception) listener.onFailure(ElasticsearchStatusException(exception.message, RestStatus.BAD_REQUEST)) } catch (exception: IllegalStateException) { log.warn("$LOG_PREFIX:IllegalStateException:", exception) listener.onFailure(ElasticsearchStatusException(exception.message, RestStatus.SERVICE_UNAVAILABLE)) } catch (exception: IOException) { log.error("$LOG_PREFIX:Uncaught IOException:", exception) listener.onFailure(ElasticsearchStatusException(exception.message, RestStatus.FAILED_DEPENDENCY)) } catch (exception: Exception) { log.error("$LOG_PREFIX:Uncaught Exception:", exception) listener.onFailure(ElasticsearchStatusException(exception.message, RestStatus.INTERNAL_SERVER_ERROR)) } } } /** * Execute the transport request * @param request the request to execute * @param user the user context given by security plugin * @return the response to return. */ abstract fun executeRequest(request: Request, user: User?): Response }
6
null
4
5
87c4b48b5550d1df77f73c3c3c2ead9a5851a9f7
5,427
notifications
Apache License 2.0
app/src/main/java/com/erplsf/scrubber/WordDefinitionDao.kt
erplsf
200,486,951
false
null
package com.erplsf.scrubber import androidx.lifecycle.LiveData import androidx.room.Dao import androidx.room.Insert import androidx.room.OnConflictStrategy import androidx.room.Query @Dao interface WordDefinitionDao { @Insert(onConflict = OnConflictStrategy.REPLACE) fun save(wordDefinition: WordDefinition) @Query("SELECT * FROM wordDefinition WHERE word = :word LIMIT 1") fun load(word: String): LiveData<WordDefinition> @Query("SELECT COUNT(*) FROM wordDefinition WHERE word = :word") fun hasWordDefinition(word: String): Boolean }
0
Kotlin
0
0
ac16ab8c5bd395d5600b611920ca0c25c56a4bae
562
scrubber
MIT License
clikt/src/jsTest/kotlin/com/github/ajalt/clikt/testing/skipDueToKT33294.kt
ajalt
128,975,548
false
null
package com.github.ajalt.clikt.testing actual val skipDueToKT33294: Boolean = true actual val skipDueToKT43490: Boolean = true
18
Kotlin
112
2,125
4c6437bbcec237c018cbf74617ac1086b694be19
128
clikt
Apache License 2.0
src/test/kotlin/com/ymoch/study/server/controller/ErrorHandlingControllerTest.kt
ymoch
150,832,195
false
null
package com.ymoch.study.server.controller import com.ymoch.study.server.record.error.ErrorRecord import com.ymoch.study.server.service.debug.DebugService import com.ymoch.study.server.service.error.ErrorService import com.ymoch.study.server.service.debug.DebugRecorder import org.hamcrest.MatcherAssert.assertThat import org.hamcrest.Matchers.equalTo import org.hamcrest.Matchers.notNullValue import org.junit.jupiter.api.BeforeEach import org.junit.jupiter.api.Nested import org.junit.jupiter.api.Test import org.mockito.Mock import org.mockito.Mockito.`when` import org.mockito.Mockito.times import org.mockito.Mockito.verify import org.mockito.MockitoAnnotations import org.springframework.context.ApplicationContext import javax.servlet.http.HttpServletResponse internal class ErrorHandlingControllerTest { @Mock private lateinit var context: ApplicationContext @Mock private lateinit var errorService: ErrorService @Mock private lateinit var debugService: DebugService @Mock private lateinit var response: HttpServletResponse private lateinit var controller: ErrorHandlingController @BeforeEach fun setUp() { MockitoAnnotations.initMocks(this) controller = ErrorHandlingController(context, errorService) `when`(context.getBean(DebugService::class.java)).thenReturn(debugService) `when`(debugService.getDebugRecorder()).thenReturn(null) } @Test fun thenSetsExceptionAndReturnsGivenErrorRecord() { val exception = Exception() `when`(errorService.createRecord(exception)) .thenReturn(ErrorRecord(403, "error", "message")) val record = controller.handleException(exception, response) assertThat(record.status, equalTo(403)) assertThat(record.error, equalTo("error")) assertThat(record.message, equalTo("message")) verify(context, times(1)).getBean(DebugService::class.java) verify(debugService, times(1)).getDebugRecorder() verify(response, times(1)).status = 403 } @Nested inner class WhenDebugging { private lateinit var debugRecorder: DebugRecorder @BeforeEach fun setUp() { debugRecorder = DebugRecorder() `when`(debugService.getDebugRecorder()).thenReturn(debugRecorder) } @Test fun then() { val exception = Exception() `when`(errorService.createRecord(exception)) .thenReturn(ErrorRecord(403, "error", "message")) controller.handleException(exception, response) val debugRecord = debugRecorder.toDebugRecord() assertThat(debugRecord.exception, notNullValue()) } } }
0
Kotlin
0
0
1d82b182c6de9c88db26f0da1bbae0ba56fb4775
2,742
kotlin-server-study
MIT License
src/main/kotlin/com/jeno/reactspringapp/configuration/SecurityConfig.kt
JenoDK
399,538,764
false
null
package com.jeno.reactspringapp.configuration import com.jeno.reactspringapp.security.CustomUserDetailsService import com.jeno.reactspringapp.security.RestAuthenticationEntryPoint import com.jeno.reactspringapp.security.TokenAuthenticationFilter import com.jeno.reactspringapp.security.oauth2.CookieOAuth2AuthorizationRequestRepository import com.jeno.reactspringapp.security.oauth2.OAuth2AuthenticationFailureHandler import com.jeno.reactspringapp.security.oauth2.OAuth2AuthenticationSuccessHandler import com.jeno.reactspringapp.security.oauth2.OAuth2UserService import org.springframework.context.annotation.Bean import org.springframework.context.annotation.Configuration import org.springframework.security.authentication.AuthenticationManager import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity import org.springframework.security.config.annotation.web.builders.HttpSecurity import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter import org.springframework.security.config.http.SessionCreationPolicy import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder import org.springframework.security.crypto.password.PasswordEncoder import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter import org.springframework.web.cors.CorsConfiguration import org.springframework.web.cors.UrlBasedCorsConfigurationSource import org.springframework.web.filter.CorsFilter @Configuration @EnableWebSecurity @EnableGlobalMethodSecurity( securedEnabled = true, jsr250Enabled = true, prePostEnabled = true ) class SecurityConfig( private val oauth2SuccessHandler: OAuth2AuthenticationSuccessHandler, private val oAuth2FailureHandler: OAuth2AuthenticationFailureHandler, private val cookieOAuth2AuthorizationRequestRepository: CookieOAuth2AuthorizationRequestRepository, private val oAuth2UserService: OAuth2UserService, private val tokenAuthenticationFilter: TokenAuthenticationFilter, private val customUserDetailsService: CustomUserDetailsService) : WebSecurityConfigurerAdapter() { override fun configure(http: HttpSecurity?) { http!! .cors() .and() .sessionManagement() .sessionCreationPolicy(SessionCreationPolicy.STATELESS) .and() .csrf().disable() .formLogin().disable() .httpBasic().disable() .exceptionHandling() .authenticationEntryPoint(RestAuthenticationEntryPoint()) .and() .authorizeRequests() .antMatchers("/", "/#", "/#/", "/#/**", "/public/**", "/api/public/**", "/static/**", "/error", "/favicon.ico", "/manifest.json", "/**/*.png", "/**/*.gif", "/**/*.svg", "/**/*.jpg", "/**/*.html", "/**/*.css", "/**/*.js") .permitAll() .antMatchers("/login/oauth2/**", "/oauth2/**") .permitAll() .anyRequest() .authenticated() .and() .oauth2Login() .successHandler(oauth2SuccessHandler) .failureHandler(oAuth2FailureHandler) .authorizationEndpoint() .authorizationRequestRepository(cookieOAuth2AuthorizationRequestRepository) .and() .userInfoEndpoint() .userService(oAuth2UserService) // .defaultSuccessUrl("/#/") // .failureUrl("/#/login") // .and() // .redirectionEndpoint() // .baseUri("/oauth2/callback/*") // .and() // .userInfoEndpoint() // .userService(customOAuth2UserService) // .and() // .successHandler(oAuth2AuthenticationSuccessHandler) // .failureHandler(oAuth2AuthenticationFailureHandler) http.addFilterAt(tokenAuthenticationFilter, UsernamePasswordAuthenticationFilter::class.java) } override fun configure(builder: AuthenticationManagerBuilder?) { builder!! .userDetailsService(customUserDetailsService) .passwordEncoder(passwordEncoder()) } @Bean override fun authenticationManagerBean(): AuthenticationManager { return super.authenticationManagerBean() } @Bean fun passwordEncoder(): PasswordEncoder { return BCryptPasswordEncoder() } // TODO see if we need CORS this open // @Bean // fun corsFilter(): CorsFilter? { // val source = UrlBasedCorsConfigurationSource() // val config = CorsConfiguration() // config.allowCredentials = true // config.setAllowedOriginPatterns(listOf("*")) // config.addAllowedHeader("*") // config.addAllowedMethod("*") // source.registerCorsConfiguration("/**", config) // return CorsFilter(source) // } }
0
Kotlin
0
1
45c8515d8ac9a28b97c186c5c488604240ba588a
4,732
react-spring-app
Apache License 2.0
crabzilla-core/src/test/java/io/github/crabzilla/example1/customer/CustomerCmdHandler.kt
MateuszNaKodach
218,310,471
true
{"Kotlin": 140231, "Java": 17754, "TSQL": 1870}
package io.github.crabzilla.example1.customer import io.github.crabzilla.framework.* import io.vertx.core.Future.succeededFuture import io.vertx.core.Promise import io.vertx.core.Promise.failedPromise import io.vertx.core.Promise.succeededPromise class CustomerCmdHandler(cmdMetadata: CommandMetadata, command: Command, snapshot: Snapshot<Customer>, stateFn: (DomainEvent, Customer) -> Customer) : EntityCommandHandler<Customer>("customer", cmdMetadata, command, snapshot, stateFn) { override fun handleCommand(): Promise<UnitOfWork> { val customer = snapshot.state val eventsPromise: Promise<List<DomainEvent>> = when (command) { is CreateCustomer -> customer.create(cmdMetadata.entityId, command.name) is ActivateCustomer -> succeededPromise(customer.activate(command.reason)) is DeactivateCustomer -> customer.deactivate(command.reason) is CreateActivateCustomer -> composed(command) else -> failedPromise("${cmdMetadata.commandName} is a unknown command") } return fromEvents(eventsPromise) } private fun composed(command: CreateActivateCustomer) : Promise<List<DomainEvent>> { val promise = Promise.promise<List<DomainEvent>>() val tracker = StateTransitionsTracker(snapshot, stateFn) tracker.currentState .create(cmdMetadata.entityId, command.name) .future() .compose { eventsList -> tracker.applyEvents(eventsList) succeededFuture(tracker.currentState.activate(command.reason)) } .compose { eventsList -> tracker.applyEvents(eventsList) promise.complete(tracker.appliedEvents) promise.future() } return promise } }
0
null
0
0
74faf7d118200f0afbf0d8d0b5d335cb5c22e58c
1,766
crabzilla
Apache License 2.0
zlauncher/src/main/java/com/inz/z/zlauncher/view/widget/LauncherPage.kt
Memory-Z
141,771,340
false
{"Java": 1063423, "Kotlin": 584610}
package com.inz.z.zlauncher.view.widget import android.content.Context import android.util.AttributeSet import android.view.ViewGroup /** * 运行页 * @author Zhenglj * @version 1.0.0 * Create by inz in 2019/12/31 14:39. */ class LauncherPage : ViewGroup { constructor(context: Context?) : super(context) constructor(context: Context?, attrs: AttributeSet?) : super(context, attrs) constructor(context: Context?, attrs: AttributeSet?, defStyleAttr: Int) : super( context, attrs, defStyleAttr ) override fun onLayout(changed: Boolean, l: Int, t: Int, r: Int, b: Int) { } }
1
null
1
1
feff01057cf308fcbf9f1ebf880b9a114badf970
623
Z_inz
Apache License 2.0
app/src/main/java/com/life4/flowpod/features/news/NewsFragment.kt
serhatkarakoca
567,899,274
false
{"Kotlin": 384571}
package com.life4.flowpod.features.news import android.os.Bundle import android.view.View import androidx.core.content.ContextCompat import androidx.fragment.app.viewModels import androidx.lifecycle.lifecycleScope import androidx.navigation.fragment.findNavController import com.life4.core.core.view.BaseFragment import com.life4.core.extensions.observe import com.life4.core.extensions.observeOnce import com.life4.flowpod.R import com.life4.flowpod.databinding.FragmentNewsBinding import com.life4.flowpod.features.main.MainActivity import com.life4.flowpod.features.news.adapter.CardNewsAdapter import com.life4.flowpod.models.rss_.RssPaginationItem import dagger.hilt.android.AndroidEntryPoint import kotlinx.coroutines.flow.collectLatest import kotlinx.coroutines.launch @AndroidEntryPoint class NewsFragment : BaseFragment<FragmentNewsBinding, NewsViewModel>(R.layout.fragment_news) { private val viewModel: NewsViewModel by viewModels() private val newsAdapter by lazy { CardNewsAdapter(::newsClickListener) } override fun setupDefinition(savedInstanceState: Bundle?) { super.setupDefinition(savedInstanceState) setupViewModel(viewModel) } override fun setupListener() { activity?.let { (it as MainActivity).getBinding().addBookmark.setOnClickListener { if (viewModel.siteAdded.value == false) viewModel.addSiteToBookmark() else viewModel.deleteSource() } } observe(viewModel.siteAdded) { (activity as MainActivity).getBinding().addBookmark.setImageDrawable( if (it) ContextCompat.getDrawable( requireContext(), R.drawable.ic_bookmark_remove ) else ContextCompat.getDrawable(requireContext(), R.drawable.ic_bookmark_add) ) } getBinding().rvNews.adapter = newsAdapter arguments?.let { val args = NewsFragmentArgs.fromBundle(it) viewModel.siteUrl = args.siteUrl viewModel.rssResponse = args.rssResponse } } private fun newsClickListener(item: RssPaginationItem) { findNavController().navigate( NewsFragmentDirections.actionNewsFragmentToNewDetailsFragment( item ) ) } override fun onResume() { super.onResume() viewModel.getSources().observeOnce(this) { it?.let { viewModel.userSources.value = it viewModel.siteAdded.value = it.sourceList?.sourceList?.firstOrNull { it.siteUrl == viewModel.siteUrl } != null } } activity?.let { (it as MainActivity).getBinding().addBookmark.visibility = View.VISIBLE } viewLifecycleOwner.lifecycleScope.launch { viewModel.getSiteData().collectLatest { newsAdapter.submitData(it) } } } override fun onDestroyView() { super.onDestroyView() (activity as MainActivity).getBinding().addBookmark.visibility = View.GONE } }
0
Kotlin
0
0
5f0df5ad62a16af45910730f88cea4cb2a133d69
3,169
Flowpod-News-Podcast
Apache License 2.0
composeApp/src/iosMain/kotlin/main.kt
Kashif-E
848,935,132
false
{"Kotlin": 30503, "Swift": 697}
import androidx.compose.ui.window.ComposeUIViewController import com.kashif.sample.App import platform.UIKit.UIViewController fun MainViewController(): UIViewController = ComposeUIViewController { App() }
0
Kotlin
1
4
25c0a9bf19d02d6e569cce859c6bd0beaa7dfbe0
206
Native-Ios-Navigation-Compose-Multiplatform
MIT License
app/shared/memfault/impl/src/commonMain/kotlin/build/wallet/memfault/MemfaultProjectKey.kt
proto-at-block
761,306,853
false
{"C": 10474259, "Kotlin": 8243078, "Rust": 2779264, "Swift": 893661, "HCL": 349246, "Python": 338898, "Shell": 136508, "TypeScript": 118945, "C++": 69203, "Meson": 64811, "JavaScript": 36398, "Just": 32977, "Ruby": 13559, "Dockerfile": 5934, "Makefile": 3915, "Open Policy Agent": 1552, "Procfile": 80}
package build.wallet.memfault /** * Project keys are not considered secrets, but IMO it's best to not release them directly. * It's still easy to reverse the app to find this. * https://docs.memfault.com/docs/platform/data-routes/ * https://docs.memfault.com/docs/ci/authentication/#project-key */ internal object MemfaultProjectKey { const val MEMFAULT_PROJECT_KEY = "<KEY>" }
3
C
16
113
694c152387c1fdb2b6be01ba35e0a9c092a81879
390
bitkey
MIT License
app/src/main/java/com/volie/wallhalla/data/model/Src.kt
harunuyan
630,386,273
false
null
package com.volie.wallhalla.data.model import android.os.Parcelable import androidx.room.Entity import androidx.room.PrimaryKey import kotlinx.parcelize.Parcelize @Entity(tableName = "src_table") @Parcelize data class Src( @PrimaryKey(autoGenerate = true) val srcId: Int? = null, val landscape: String, val large2x: String, ) : Parcelable
0
Kotlin
0
1
8b27718441a01e44d066296e369aef15a91cddf1
356
Wallhalla
The Unlicense
ktfx-commons/src/main/kotlin/ktfx/dialogs/Alerts.kt
hanggrian
102,934,147
false
null
@file:Suppress("NOTHING_TO_INLINE") package ktfx.dialogs import javafx.scene.Node import javafx.scene.control.Alert import javafx.scene.control.Alert.AlertType import javafx.scene.control.ButtonType import javafx.scene.control.ButtonType.CLOSE import javafx.scene.control.ButtonType.NO import javafx.scene.control.ButtonType.YES import javafx.scene.image.ImageView import java.util.Optional /** * Show an alert with title and graphic. * * @param title title of the dialog. * @param graphic node to be displayed in header. * @param content alert message. * @param buttonTypes alert buttons. * @param alertAction custom dialog action. * @return selected alert button. */ fun alert( title: String? = null, graphic: Node? = null, content: String = "", vararg buttonTypes: ButtonType = arrayOf(CLOSE), alertAction: (Alert.() -> Unit)? = null, ): Optional<ButtonType> = Alert(AlertType.NONE, content, *buttonTypes).also { dialog -> if (title != null) dialog.headerTitle = title when { graphic is ImageView -> dialog.graphicIcon = graphic graphic != null -> dialog.graphic = graphic } alertAction?.invoke(dialog) }.showAndWait() /** * Show an alert. * * @param content alert message. * @param buttonTypes alert buttons. * @param alertAction custom dialog action. * @return selected alert button. */ inline fun alert( content: String, vararg buttonTypes: ButtonType = arrayOf(CLOSE), noinline alertAction: (Alert.() -> Unit)? = null, ): Optional<ButtonType> = alert(null, null, content, *buttonTypes, alertAction = alertAction) /** * Show an information alert with title and graphic. * * @param title title of the dialog. * @param graphic node to be displayed in header. * @param content alert message. * @param buttonTypes alert buttons. * @param alertAction custom dialog action. * @return selected alert button. */ fun infoAlert( title: String? = null, graphic: Node? = null, content: String = "", vararg buttonTypes: ButtonType = arrayOf(CLOSE), alertAction: (Alert.() -> Unit)? = null, ): Optional<ButtonType> = Alert(AlertType.INFORMATION, content, *buttonTypes).also { dialog -> if (title != null) dialog.headerTitle = title when { graphic is ImageView -> dialog.graphicIcon = graphic graphic != null -> dialog.graphic = graphic } alertAction?.invoke(dialog) }.showAndWait() /** * Show an information alert. * * @param content alert message. * @param buttonTypes alert buttons. * @param alertAction custom dialog action. * @return selected alert button. */ inline fun infoAlert( content: String, vararg buttonTypes: ButtonType = arrayOf(CLOSE), noinline alertAction: (Alert.() -> Unit)? = null, ): Optional<ButtonType> = infoAlert(null, null, content, *buttonTypes, alertAction = alertAction) /** * Show a warning alert with title and graphic. * * @param title title of the dialog. * @param graphic node to be displayed in header. * @param content alert message. * @param buttonTypes alert buttons. * @param alertAction custom dialog action. * @return selected alert button. */ fun warningAlert( title: String? = null, graphic: Node? = null, content: String = "", vararg buttonTypes: ButtonType = arrayOf(CLOSE), alertAction: (Alert.() -> Unit)? = null, ): Optional<ButtonType> = Alert(AlertType.WARNING, content, *buttonTypes).also { dialog -> if (title != null) dialog.headerTitle = title when { graphic is ImageView -> dialog.graphicIcon = graphic graphic != null -> dialog.graphic = graphic } alertAction?.invoke(dialog) }.showAndWait() /** * Show a warning alert. * * @param content alert message. * @param buttonTypes alert buttons. * @param alertAction custom dialog action. * @return selected alert button. */ inline fun warningAlert( content: String, vararg buttonTypes: ButtonType = arrayOf(CLOSE), noinline alertAction: (Alert.() -> Unit)? = null, ): Optional<ButtonType> = warningAlert(null, null, content, *buttonTypes, alertAction = alertAction) /** * Show a confirmation alert with title and graphic. * * @param title title of the dialog. * @param graphic node to be displayed in header. * @param content alert message. * @param buttonTypes alert buttons. * @param alertAction custom dialog action. * @return selected alert button. */ fun confirmAlert( title: String? = null, graphic: Node? = null, content: String = "", vararg buttonTypes: ButtonType = arrayOf(YES, NO), alertAction: (Alert.() -> Unit)? = null, ): Optional<ButtonType> = Alert(AlertType.CONFIRMATION, content, *buttonTypes).also { dialog -> if (title != null) dialog.headerTitle = title when { graphic is ImageView -> dialog.graphicIcon = graphic graphic != null -> dialog.graphic = graphic } alertAction?.invoke(dialog) }.showAndWait() /** * Show a confirmation alert. * * @param content alert message. * @param buttonTypes alert buttons. * @param alertAction custom dialog action. * @return selected alert button. */ inline fun confirmAlert( content: String, vararg buttonTypes: ButtonType = arrayOf(YES, NO), noinline alertAction: (Alert.() -> Unit)? = null, ): Optional<ButtonType> = confirmAlert(null, null, content, *buttonTypes, alertAction = alertAction) /** * Show an error alert with title and graphic. * * @param title title of the dialog. * @param graphic node to be displayed in header. * @param content alert message. * @param buttonTypes alert buttons. * @param alertAction custom dialog action. * @return selected alert button. */ fun errorAlert( title: String? = null, graphic: Node? = null, content: String = "", vararg buttonTypes: ButtonType = arrayOf(CLOSE), alertAction: (Alert.() -> Unit)? = null, ): Optional<ButtonType> = Alert(AlertType.ERROR, content, *buttonTypes).also { dialog -> if (title != null) dialog.headerTitle = title when { graphic is ImageView -> dialog.graphicIcon = graphic graphic != null -> dialog.graphic = graphic } alertAction?.invoke(dialog) }.showAndWait() /** * Show an error alert. * * @param content alert message. * @param buttonTypes alert buttons. * @param alertAction custom dialog action. * @return selected alert button. */ inline fun errorAlert( content: String, vararg buttonTypes: ButtonType = arrayOf(CLOSE), noinline alertAction: (Alert.() -> Unit)? = null, ): Optional<ButtonType> = errorAlert(null, null, content, *buttonTypes, alertAction = alertAction)
1
null
2
18
edc15180b85065567a877254c439bb61ee07c329
6,774
ktfx
Apache License 2.0
intellij2checkstyle-core/src/test/kotlin/integration/tests/SingleProfileWithIntelliJOverridePath.kt
theodm
143,562,099
false
null
package integration.tests import de.theodm.intellij2checkstyle.Intellij2Checkstyle import de.theodm.intellij2checkstyle.convert.reporters.checkstyle.CheckstyleReporter import de.theodm.intellij2checkstyle.extensions.path.readFully import de.theodm.intellij2checkstyle.extensions.path.resolve import de.theodm.intellij2checkstyle.testExtensions.subjects.TruthExtensions import integration.extension.IntegrationTestExtension import integration.extension.ResourceLocation import integration.extension.types.IdeaFolder import integration.extension.types.OutputFolder import integration.extension.types.ProjectFolder import org.junit.jupiter.api.DisplayName import org.junit.jupiter.api.Test import org.junit.jupiter.api.extension.ExtendWith import org.redundent.kotlin.xml.xml import java.nio.file.FileSystems import java.nio.file.Path @ExtendWith(IntegrationTestExtension::class) internal class SingleProfileWithIntelliJOverridePath { @Test @ResourceLocation("single_profile") @DisplayName( "Project with single project profile which should be automatically resolved" + " and an override value for the path to the intellij instance" ) fun testAny( @IdeaFolder ideaFolder: Path, @OutputFolder outputFolder: Path, @ProjectFolder projectFolder: Path ) { // When val outputFile = outputFolder.resolve("checkstyle.xml") Intellij2Checkstyle.inspect( fileSystem = FileSystems.getDefault(), intelliJPathOverride = ideaFolder, profileOverride = null, projectFolderPath = projectFolder, scopeOverride = null, proxySettingsDir = null, keepTemp = true, reporter = listOf(CheckstyleReporter(outputFile)) ) // Then val result = outputFile.readFully() val exampleJavaPath = projectFolder.resolve( "src", "main", "java", "de", "theodm", "simple", "Example.java" ).toAbsolutePath() .normalize() val expected = xml("checkstyle") { attribute("version", "8.0") "file" { attribute("name", exampleJavaPath) "error" { attribute("line", "3") attribute("column", "1") attribute("severity", "warning") attribute("message", "Can be package-private") attribute("source", "Declaration redundancy") } "error" { attribute("line", "5") attribute("column", "1") attribute("severity", "warning") attribute( "message", "Variable &lt;code&gt;unused&lt;/code&gt; is never used" ) attribute("source", "Declaration redundancy") } } }.toString() TruthExtensions.assertThat(result).isXmlEqualTo(expected) } }
1
null
1
1
2607e1f9e4f64e7b4e8140c56918ad5d856a62eb
3,110
intellij2checkstyle
Apache License 2.0
app/src/main/java/com/mobdeve/s11/group5/shopfreemobileapp/Market.kt
TritonSaber
814,968,916
false
{"Kotlin": 58618, "Java": 1735}
package com.mobdeve.s11.group5.shopfreemobileapp data class Market ( public var mName: String, public var mLoc: String, public var mDesc: String?, public var mImage: Int )
0
Kotlin
0
0
7017813d2aa1e4a960b58b0555e3d2906470cd9f
188
MOBDEVE-S11-GROUP5
MIT License
app/common/src/androidMain/kotlin/com/denchic45/studiversity/ui/auth/AuthUI.kt
denchic45
435,895,363
false
null
package com.denchic45.studiversity.ui.auth import androidx.compose.animation.core.animateFloatAsState import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.material3.LinearProgressIndicator import androidx.compose.material3.ProgressIndicatorDefaults import androidx.compose.runtime.Composable import androidx.compose.runtime.getValue import androidx.compose.ui.Modifier import androidx.compose.ui.graphics.Color import com.arkivanov.decompose.extensions.compose.jetpack.stack.Children import com.arkivanov.decompose.extensions.compose.jetpack.stack.animation.fade import com.arkivanov.decompose.extensions.compose.jetpack.stack.animation.plus import com.arkivanov.decompose.extensions.compose.jetpack.stack.animation.slide import com.arkivanov.decompose.extensions.compose.jetpack.stack.animation.stackAnimation import com.arkivanov.decompose.extensions.compose.jetpack.subscribeAsState import com.denchic45.studiversity.domain.resource.ifSuccess import com.denchic45.studiversity.ui.theme.md_theme_dark_tertiary @Composable fun AuthScreen(component: AuthComponent) { val childStack by component.childStack.subscribeAsState() Column(Modifier.fillMaxSize()) { AuthProgress(childStack.active.instance) Children(stack = component.childStack, animation = stackAnimation(slide() + fade())) { when (val child = it.instance) { is AuthComponent.Child.Welcome -> WelcomeScreen(child.component) is AuthComponent.Child.Login -> LoginScreen(child.component) is AuthComponent.Child.Registration -> RegistrationScreen(child.component) is AuthComponent.Child.ResetPassword -> TODO() } } } } @Composable private fun AuthProgress(child: AuthComponent.Child) { val animatedProgress = animateFloatAsState( targetValue = when (child) { is AuthComponent.Child.Welcome -> 0f is AuthComponent.Child.Login -> { child.component.state.result?.ifSuccess { 1f } ?: 0.5f } is AuthComponent.Child.ResetPassword, is AuthComponent.Child.Registration, -> 0.25f }, animationSpec = ProgressIndicatorDefaults.ProgressAnimationSpec ).value LinearProgressIndicator( progress = animatedProgress, modifier = Modifier.fillMaxWidth(), color = md_theme_dark_tertiary, trackColor = Color.Transparent ) }
0
null
0
7
93947301de4c4a9cb6c3d9fa36903f857c50e6c2
2,578
Studiversity
Apache License 2.0
app/common/src/androidMain/kotlin/com/denchic45/studiversity/ui/auth/AuthUI.kt
denchic45
435,895,363
false
null
package com.denchic45.studiversity.ui.auth import androidx.compose.animation.core.animateFloatAsState import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.material3.LinearProgressIndicator import androidx.compose.material3.ProgressIndicatorDefaults import androidx.compose.runtime.Composable import androidx.compose.runtime.getValue import androidx.compose.ui.Modifier import androidx.compose.ui.graphics.Color import com.arkivanov.decompose.extensions.compose.jetpack.stack.Children import com.arkivanov.decompose.extensions.compose.jetpack.stack.animation.fade import com.arkivanov.decompose.extensions.compose.jetpack.stack.animation.plus import com.arkivanov.decompose.extensions.compose.jetpack.stack.animation.slide import com.arkivanov.decompose.extensions.compose.jetpack.stack.animation.stackAnimation import com.arkivanov.decompose.extensions.compose.jetpack.subscribeAsState import com.denchic45.studiversity.domain.resource.ifSuccess import com.denchic45.studiversity.ui.theme.md_theme_dark_tertiary @Composable fun AuthScreen(component: AuthComponent) { val childStack by component.childStack.subscribeAsState() Column(Modifier.fillMaxSize()) { AuthProgress(childStack.active.instance) Children(stack = component.childStack, animation = stackAnimation(slide() + fade())) { when (val child = it.instance) { is AuthComponent.Child.Welcome -> WelcomeScreen(child.component) is AuthComponent.Child.Login -> LoginScreen(child.component) is AuthComponent.Child.Registration -> RegistrationScreen(child.component) is AuthComponent.Child.ResetPassword -> TODO() } } } } @Composable private fun AuthProgress(child: AuthComponent.Child) { val animatedProgress = animateFloatAsState( targetValue = when (child) { is AuthComponent.Child.Welcome -> 0f is AuthComponent.Child.Login -> { child.component.state.result?.ifSuccess { 1f } ?: 0.5f } is AuthComponent.Child.ResetPassword, is AuthComponent.Child.Registration, -> 0.25f }, animationSpec = ProgressIndicatorDefaults.ProgressAnimationSpec ).value LinearProgressIndicator( progress = animatedProgress, modifier = Modifier.fillMaxWidth(), color = md_theme_dark_tertiary, trackColor = Color.Transparent ) }
0
null
0
7
93947301de4c4a9cb6c3d9fa36903f857c50e6c2
2,578
Studiversity
Apache License 2.0
thisboot/src/main/kotlin/com/brageast/blog/thisboot/security/SimpleUserDetails.kt
chenmoand
208,778,754
false
{"YAML": 3, "JSON with Comments": 2, "JSON": 5, "Text": 1, "Ignore List": 3, "Markdown": 11, "HTML": 5, "HTTP": 1, "JavaScript": 11, "TSX": 50, "XML": 1, "Less": 6, "Batchfile": 1, "Shell": 1, "Maven POM": 1, "INI": 1, "Java": 2, "Kotlin": 26}
package com.brageast.blog.thisboot.security import com.brageast.blog.thisboot.entity.User import org.springframework.security.core.GrantedAuthority import org.springframework.security.core.authority.SimpleGrantedAuthority import org.springframework.security.core.userdetails.UserDetails class SimpleUserDetails(val user: User) : UserDetails { private val isNotExpired: Boolean = user.run { if(joinTime != null && accountExpiredTime != null) // IDEA 的最新版Kotlin插件各种报错 // 我都判断不是null还在一个劲的报加!! joinTime!!.before(accountExpiredTime) else true } private val isNotBan = !user.ban override fun getAuthorities(): MutableCollection<out GrantedAuthority> = user .authorities.map { SimpleGrantedAuthority(it) }.toMutableList() override fun isEnabled(): Boolean = isNotBan override fun getUsername(): String = user.name override fun isCredentialsNonExpired(): Boolean = isNotExpired override fun getPassword(): String = <PASSWORD> override fun isAccountNonExpired(): Boolean = isNotExpired override fun isAccountNonLocked(): Boolean = isNotBan }
9
TypeScript
1
2
0819b24e15843546d0b2d338ad5673b3901dfd4d
1,177
thisme
MIT License
sdk/src/main/java/com/github/thibaultbee/streampack/utils/FileRecorder.kt
thiagooo0
417,026,830
false
{"Kotlin": 383970}
package com.github.thibaultbee.streampack.utils import android.content.Context import java.io.File import java.io.FileOutputStream import java.nio.ByteBuffer class FileRecorder { private var fileOutputStream: FileOutputStream? = null var file: File? = null set(value) { fileOutputStream = FileOutputStream(value, false) } constructor(file: File?) { this.file = file } constructor(context: Context, name: String) { file = File(context.getExternalFilesDir("video"), name) } fun write(byteBuffer: ByteBuffer) { fileOutputStream?.channel?.write(byteBuffer) } fun write(byteArray: ByteArray) { fileOutputStream?.write(byteArray) } }
0
Kotlin
0
2
4336493a3215fe727088afa08208c13cf0ffb5e2
734
StreamPack
Apache License 2.0
client/android/div/src/main/java/com/yandex/div/core/view2/CompositeLogId.kt
divkit
523,491,444
false
{"Kotlin": 7327303, "Swift": 5164616, "Svelte": 1148832, "TypeScript": 912803, "Dart": 630920, "Python": 536031, "Java": 507940, "JavaScript": 152546, "CSS": 37870, "HTML": 23434, "C++": 20911, "CMake": 18677, "Shell": 8895, "PEG.js": 7210, "Ruby": 3723, "C": 1425, "Objective-C": 38}
package com.yandex.div.core.view2 import com.yandex.div2.DivSightAction internal data class CompositeLogId( val dataTag: String, val scopeLogId: String, val actionLogId: String ) { private val compositeLogId by lazy { formatCompositeLogId() } private fun formatCompositeLogId(): String { return dataTag + (if (scopeLogId.isNotEmpty()) "#$scopeLogId" else "") + "#$actionLogId" } override fun toString() = compositeLogId } internal fun compositeLogIdOf(scope: Div2View, actionLogId: String): CompositeLogId { return CompositeLogId( dataTag = scope.dataTag.id, scopeLogId = scope.logId, actionLogId = actionLogId ) }
5
Kotlin
128
2,240
dd102394ed7b240ace9eaef9228567f98e54d9cf
689
divkit
Apache License 2.0
AndroidStudio/Unit-2/src/main/java/com/example/myapplication/BookAdapter.kt
Thienguen
567,532,175
false
{"Kotlin": 91846, "Java": 37674}
package com.example.myapplication import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.TextView import androidx.recyclerview.widget.RecyclerView class BookAdapter (private val books: List<Book>) : RecyclerView.Adapter<BookAdapter.ViewHolder>() { // Provide a direct reference to each of the views within a data item // Used to cache the views within the item layout for fast access inner class ViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) { // Your holder should contain and initialize a member variable // for any view that will be set as you render a row val authorTextView: TextView = itemView.findViewById<TextView>(R.id.author) val titleTextView: TextView = itemView.findViewById<TextView>(R.id.title) } // ... constructor and member variables // Usually involves inflating a layout from XML and returning the holder override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): BookAdapter.ViewHolder { val context = parent.context val inflater = LayoutInflater.from(context) // Inflate the custom layout val contactView = inflater.inflate(R.layout.book_item, parent, false) // Return a new holder instance return ViewHolder(contactView) } // Involves populating data into the item through holder override fun onBindViewHolder(viewHolder: BookAdapter.ViewHolder, position: Int) { // Get the data model based on position val book: Book = books[position] // Set item views based on your views and data model // val title = viewHolder.titleTextView // val author = viewHolder.authorTextView // // title.text = book.title // author.text = book.author viewHolder.authorTextView.text = book.author viewHolder.titleTextView.text = book.title } // Returns the total count of items in the list override fun getItemCount(): Int { return books.size } }
0
Kotlin
0
3
b98d163658792885f6ab088120446b11b6e22ea8
2,045
CodePath-Intermediate-Android-Development
Apache License 2.0
filepicker/src/main/java/me/rosuh/filepicker/bean/FileNavBean.kt
msdgwzhy6
159,752,398
true
{"Kotlin": 40993, "Java": 7258}
package me.rosuh.filepicker.bean import me.rosuh.filepicker.bean.IFileBean /** * * @author rosu * @date 2018/11/21 */ class FileNavBean(val dirName:String, val dirPath:String): IFileBean { override var fileName: String get() = dirName set(value) {} override var filePath: String get() = dirPath set(value) {} }
0
Kotlin
0
1
a21fcf6e1248804864d64db32aee033e450cb8dd
356
AndroidFilePicker
MIT License
src/main/kotlin/net/rentalhost/plugins/php/hammer/inspections/codeSmell/SenselessNumberFormatZeroDecimalInspection.kt
hammer-tools
509,864,102
false
null
package net.rentalhost.plugins.php.hammer.inspections.codeSmell import com.intellij.codeInspection.ProblemsHolder import com.intellij.refactoring.suggested.createSmartPointer import com.jetbrains.php.lang.inspections.PhpInspection import com.jetbrains.php.lang.psi.elements.BinaryExpression import com.jetbrains.php.lang.psi.elements.FunctionReference import com.jetbrains.php.lang.psi.elements.StringLiteralExpression import com.jetbrains.php.lang.psi.visitors.PhpElementVisitor import net.rentalhost.plugins.php.hammer.extensions.psi.isName import net.rentalhost.plugins.php.hammer.services.FactoryService import net.rentalhost.plugins.php.hammer.services.ProblemsHolderService import net.rentalhost.plugins.php.hammer.services.QuickFixService class SenselessNumberFormatZeroDecimalInspection : PhpInspection() { override fun buildVisitor(problemsHolder: ProblemsHolder, isOnTheFly: Boolean): PhpElementVisitor = object : PhpElementVisitor() { override fun visitPhpFunctionCall(element: FunctionReference) { if (!element.isName("\\number_format") || element.parameters.isEmpty()) return if (element.parameters.size < 4) return if (element.parameters[1].text != "0") return with(element.parameters[3] as? StringLiteralExpression ?: return) { if (contents != "") return } val elementParameter = element.parameters[0] ProblemsHolderService.instance.registerProblem( problemsHolder, element, "senseless number_format() using zero decimal point", QuickFixService.instance.simpleReplace( "Replace with type casting", FactoryService.createTypeCastDouble( problemsHolder.project, "string", "int", if (elementParameter is BinaryExpression) "(${elementParameter.text})" else elementParameter.text ).createSmartPointer() ) ) } } }
9
null
2
96
eb07d4f34bdd4a588251db854e6c60ca6584886a
1,945
php-hammer
Apache License 2.0
src/test/kotlin/TestDialogueManager.kt
th2-net
348,275,947
false
null
/* * Copyright 2020-2021 Exactpro (Exactpro Systems Limited) * 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. * */ import com.exactpro.th2.httpserver.server.Dialogue import com.exactpro.th2.httpserver.server.DialogueManager import org.junit.jupiter.api.Assertions import org.junit.jupiter.api.Test import rawhttp.core.RawHttpRequest import testimpl.TestSocket class TestDialogueManager { @Test fun dialogueBeforeRemove() { val delay = 1L val manager = DialogueManager(delay+1) manager.startCleaner() manager.dialogues["test"] = Dialogue(RawHttpRequest(null, null, null,null), TestSocket(true)) Thread.sleep((delay) * 1000) Assertions.assertEquals(1, manager.dialogues.size) manager.close() } @Test fun dialogueAfterRemove() { val delay = 1L val manager = DialogueManager(delay) manager.startCleaner() manager.dialogues["test"] = Dialogue(RawHttpRequest(null, null, null,null), TestSocket(true)) Thread.sleep(delay * 1100) Assertions.assertEquals(0, manager.dialogues.size) manager.close() } @Test fun dialoguePersist() { val delay = 1L val manager = DialogueManager(delay) manager.startCleaner() manager.dialogues["test"] = Dialogue(RawHttpRequest(null, null, null,null), TestSocket(false)) Thread.sleep(delay * 1100) Assertions.assertEquals(1, manager.dialogues.size) manager.close() } @Test fun dialogueCountRemove() { val delay = 2L val manager = DialogueManager(delay) manager.startCleaner() for (i in 1..2) { manager.dialogues["test$i"] = Dialogue(RawHttpRequest(null, null, null,null), TestSocket(false)) } for (i in 3..5) { manager.dialogues["test$i"] = Dialogue(RawHttpRequest(null, null, null,null), TestSocket(true)) } Thread.sleep((delay*2) * 1000) Assertions.assertEquals(2, manager.dialogues.size) manager.close() } }
1
Kotlin
0
1
6f5f8344a7e2c313ca6e18510dfbb90fa08e70e8
2,556
th2-conn-http-server
Apache License 2.0
src/test/kotlin/leetcode/uber/OptimalAccountBalancingTest.kt
Magdi
390,731,717
false
{"Gradle": 2, "INI": 2, "Shell": 1, "Text": 1, "Ignore List": 1, "Batchfile": 1, "Markdown": 1, "Kotlin": 96, "Java": 1}
package leetcode.uber import leetcode.uber.OptimalAccountBalancing import org.junit.Test import org.junit.Assert.* class OptimalAccountBalancingTest { @Test fun `minTransfers test case 1`() { val transactions = arrayOf( intArrayOf(0, 1, 10), intArrayOf(2, 0, 5), ) assertEquals(2, OptimalAccountBalancing().minTransfers(transactions)) } @Test fun `minTransfers test case 2`() { val transactions = arrayOf( intArrayOf(0, 1, 10), intArrayOf(1, 0, 1), intArrayOf(1, 2, 5), intArrayOf(2, 0, 5), ) assertEquals(1, OptimalAccountBalancing().minTransfers(transactions)) } @Test fun `minTransfers test case 3`() { val transactions = arrayOf( intArrayOf(0, 1, 10), intArrayOf(1, 0, 1), intArrayOf(1, 2, 5), intArrayOf(2, 0, 4), ) assertEquals(2, OptimalAccountBalancing().minTransfers(transactions)) } @Test fun `minTransfers test case 4`() { val transactions = arrayOf( intArrayOf(0, 1, 5), intArrayOf(2, 3, 1), intArrayOf(2, 0, 1), intArrayOf(4, 0, 2), ) assertEquals(4, OptimalAccountBalancing().minTransfers(transactions)) } }
0
Kotlin
0
0
63bc711dc8756735f210a71454144dd033e8927d
1,340
ProblemSolving
Apache License 2.0
composeApp/src/desktopMain/kotlin/com/ethossoftworks/land/PlatformDI.kt
ethossoftworks
662,813,245
false
{"Kotlin": 209395, "Swift": 14097, "Shell": 703}
package com.ethossoftworks.land import com.ethossoftworks.land.service.discovery.DesktopNSDService import com.ethossoftworks.land.service.discovery.INSDService import com.ethossoftworks.land.service.preferences.PreferencesService import com.ethossoftworks.land.service.preferences.IPreferencesService import com.ethossoftworks.land.ui.DesktopAppViewInteractor import com.outsidesource.oskitkmp.storage.DesktopKMPStorage import com.outsidesource.oskitkmp.storage.IKMPStorage import org.koin.dsl.bind import org.koin.dsl.module actual class DIPlatformContext actual fun platformModule(platformContext: DIPlatformContext) = module { factory { DesktopAppViewInteractor(get()) } single { DesktopNSDService() } bind INSDService::class single { DesktopKMPStorage("com.ethossoftworks.LANd") } bind IKMPStorage::class }
0
Kotlin
0
0
4f80493cb1ddc91b21d077c562d34fe6dbae71db
826
LANd
MIT License
app/src/main/java/com/compose/template/utils/Constants.kt
a914-gowtham
418,768,090
false
null
package com.compose.template.utils object Constants { const val GITHUB_DB_NAME = "github_db" }
0
Kotlin
0
0
93acc453d93681eed9c617628b230aa9dfdcc49e
101
github-trending-compose
Apache License 2.0
domain/src/main/kotlin/com/seanshubin/condorcet/backend/domain/Ballot.kt
SeanShubin
238,518,165
false
null
package com.seanshubin.condorcet.backend.domain import java.time.Instant data class Ballot( val voterName: String, val electionName: String, val confirmation: String, val whenCast: Instant, val rankings: List<Ranking> ) { fun makeSecret():Ballot = copy(voterName="<redacted>") companion object{ fun List<Ballot>.sortRankingsByName():List<Ballot> = map{ ballot -> ballot.copy(rankings = ballot.rankings.sortedBy { it.candidateName })} } }
0
Kotlin
0
0
ba20f6fed46eaa75ecda2329e411e748ad09125c
492
condorcet-backend
The Unlicense
app/src/main/java/com/nanamare/starter/ui/MainActivity.kt
Nanamare
639,967,746
false
null
package com.nanamare.starter.ui import android.os.Bundle import androidx.activity.viewModels import androidx.appcompat.app.AppCompatActivity import androidx.lifecycle.lifecycleScope import com.nanamare.base.ui.viewBinding import com.nanamare.base.util.UiState import com.nanamare.starter.databinding.ActivityMainBinding import dagger.hilt.android.AndroidEntryPoint import kotlinx.coroutines.flow.launchIn import kotlinx.coroutines.flow.onEach import timber.log.Timber @AndroidEntryPoint class MainActivity : AppCompatActivity() { private val binding by viewBinding(ActivityMainBinding::inflate) private val viewModel by viewModels<MainViewModel>() override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(binding.root) viewModel.testUiState.onEach { uiState -> when (val data = uiState) { is UiState.Loading -> Timber.d("Loading invoke") is UiState.Error -> Timber.e(data.exception) is UiState.Success -> Timber.d(data.toString()) } }.launchIn(lifecycleScope) } }
0
Kotlin
0
5
47ff0a09b2ffd812cd011785b2bcc73ac6da0ef8
1,135
Starter
MIT License
kzen-auto-jvm/src/main/kotlin/tech/kzen/auto/server/objects/sequence/model/ActiveSequenceModel.kt
alexoooo
131,353,826
false
null
package tech.kzen.auto.server.objects.sequence.model import tech.kzen.lib.common.model.location.ObjectLocation data class ActiveSequenceModel( val steps: MutableMap<ObjectLocation, ActiveStepModel> = mutableMapOf(), var next: ObjectLocation? = null )
0
Kotlin
0
1
0cea50ac0276398211b652ad679f42f4bb52b391
261
kzen-auto
MIT License
Postgrest/src/commonMain/kotlin/io/github/jan/supabase/postgrest/query/Columns.kt
supabase-community
495,084,592
false
null
package io.github.jan.supabase.postgrest.query import kotlin.jvm.JvmInline /** * Represents a list of columns to select * @param value The columns to select, separated by a comma */ @JvmInline value class Columns @PublishedApi internal constructor(val value: String) { companion object { /** * Select all columns */ val ALL = Columns("*") /** * Select all columns given in the [value] parameter * @param value The columns to select, separated by a comma */ fun raw(value: String) = Columns(value) /** * Select all columns given in the [columns] parameter * @param columns The columns to select */ fun list(vararg columns: String) = Columns(columns.joinToString(",")) /** * Select all columns given in the [columns] parameter * @param columns The columns to select */ fun list(columns: List<String>) = Columns(columns.joinToString(",")) /** * Select all columns of type [T]'s class properties. Example: If you specify a class 'User' with the fields 'id' and 'name', this will select 'id,name' * @param T The type of the columns to select */ inline fun <reified T> type() = Columns(T::class.simpleName!!) } }
4
null
28
269
c3c2c2f118c8821336a680c19d307be0d4f67124
1,333
supabase-kt
MIT License
app/src/main/java/no1/payamax/services/AdvertisementOriginUsabilityProcessor.kt
PayamaX
723,029,187
false
{"Kotlin": 24276}
package no1.payamax.services import no1.payamax.contracts.Payamak import no1.payamax.contracts.PayamakUsabilityRuleContract import no1.payamax.contracts.UsabilityRate import no1.payamax.hasValue class AdvertisementOriginUsabilityProcessor : PayamakUsabilityRuleContract { override val name: String get() = "Ad" override fun guess(payamak: Payamak): UsabilityRate { if (payamak.origin.contact.hasValue) return UsabilityRate(10.0) val originNumber = payamak.origin.number?.run { val textualNumber = this.toString() return@run if (textualNumber.startsWith("98")) textualNumber.substring(2) else textualNumber } ?: return UsabilityRate(5.0) return when { originNumber.startsWith("1000") -> UsabilityRate(0.0) originNumber.startsWith("2000") -> UsabilityRate(0.0) originNumber.startsWith("3000") -> UsabilityRate(0.0) originNumber.startsWith("4000") -> UsabilityRate(0.0) originNumber.startsWith("5000") -> UsabilityRate(0.0) originNumber.startsWith("6000") -> UsabilityRate(0.0) originNumber.startsWith("9000") -> UsabilityRate(0.0) originNumber.startsWith("21") -> UsabilityRate(0.0) originNumber.startsWith("26") -> UsabilityRate(0.0) originNumber.startsWith("999") -> UsabilityRate(0.0) else -> UsabilityRate(7.0) } } }
9
Kotlin
0
2
201439b5d5add3b40f469e5cd99e281ef6b93567
1,450
app
Apache License 2.0
src/commonMain/kotlin/matt/model/code/ok/ok.kt
mgroth0
532,381,019
false
{"Kotlin": 214520}
package matt.model.code.ok import kotlin.annotation.AnnotationTarget.FILE /*Because setting JvmName is messing things up for android. Basically seems like only way to have expect and actual functions and classes for android, for now I think this has not yet been made to work with Detekt because the only place it is currently being used is in a Compose module, where Detekt is still not executing as of now*/ @Target(FILE) annotation class FilePackageNameMismatchIsOk
0
Kotlin
0
0
9831d71c005a6202b30d5f9205577894812736ae
474
model
MIT License
shared/src/commonMain/kotlin/feature_person_detail/presentation/PersonDetailScreen.kt
tolgaprm
712,824,422
false
{"Kotlin": 281188, "Swift": 657, "Shell": 228}
package feature_person_detail.presentation import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.padding import androidx.compose.material3.MaterialTheme import androidx.compose.runtime.Composable import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import core.presentation.components.BackButton import core.presentation.components.ErrorView import core.presentation.components.MCircularProgressIndicator import core.presentation.theme.dimensions import feature_person_detail.presentation.components.PersonDetailSuccess @Composable fun PersonDetailScreen( modifier: Modifier = Modifier, personDetailUiState: PersonDetailUiState, onPopBackStack: () -> Unit, onEvent: (PersonDetailEvent) -> Unit ) { Box( modifier ) { when (personDetailUiState) { is PersonDetailUiState.Loading -> { MCircularProgressIndicator() } is PersonDetailUiState.Success -> { PersonDetailSuccess( modifier = Modifier.fillMaxSize(), uiState = personDetailUiState ) BackButton( modifier = Modifier .padding(MaterialTheme.dimensions.fourLevel) .align(Alignment.TopStart), onClick = onPopBackStack ) } is PersonDetailUiState.Error -> { ErrorView( modifier = Modifier.fillMaxSize() .align(Alignment.Center), errorMessage = personDetailUiState.message, onClickRetry = { onEvent(PersonDetailEvent.OnTryAgainClicked) } ) } } } }
2
Kotlin
0
0
77c22dc354b9d214ef05d1335c8e3eaefe57d002
1,899
MovaApp-compose-multiplatform
Apache License 2.0
app/src/main/java/org/fossasia/susi/ai/data/contract/IGroupWiseSkillsModel.kt
fossasia
68,798,776
false
null
package org.fossasia.susi.ai.data.contract import org.fossasia.susi.ai.rest.responses.susi.ListSkillsResponse import retrofit2.Response /** * * Created by arundhati24 on 16/07/2018. */ interface IGroupWiseSkillsModel { interface OnFetchSkillsFinishedListener { fun onSkillFetchSuccess(response: Response<ListSkillsResponse>, group: String) fun onSkillFetchFailure(t: Throwable) } fun fetchSkills(group: String, language: String, listener: OnFetchSkillsFinishedListener) fun cancelFetch() }
81
null
1131
2,391
a3409051185d4624e65f7df7847e2fca0910cebe
528
susi_android
Apache License 2.0
hello-kafka-cqrs/order-command-service/src/main/kotlin/microkafka/escqrs/orders/command/App.kt
thecodemonkey
374,150,626
false
null
package microkafka.escqrs.orders.command import org.springframework.boot.autoconfigure.SpringBootApplication import org.springframework.boot.context.properties.ConfigurationPropertiesScan import org.springframework.boot.runApplication @SpringBootApplication class App fun main(args: Array<String>) { runApplication<App>(*args) print("start order command microservice...") }
1
Kotlin
3
9
a4752cdb21d1d06bffb398fd5d128d14a87c6cec
386
kafka-microservices
MIT License
helios-core/src/main/kotlin/helios/typeclasses/KeyDecoder.kt
47degrees
118,187,374
false
null
package helios.typeclasses import arrow.core.Either import arrow.higherkind import helios.core.DecodingError import helios.core.JsString @higherkind interface KeyDecoder<out A> { fun keyDecode(value: JsString): Either<DecodingError, A> }
27
Kotlin
25
166
46c3c2e6e113257605b72761e797735e51f8f46d
241
helios
Apache License 2.0
compose/ui-unit/src/commonMain/kotlin/com/bselzer/ktx/compose/ui/unit/LocalDensityExtension.kt
Woody230
388,189,330
false
{"Kotlin": 3122765}
package com.bselzer.ktx.compose.ui.unit import androidx.compose.runtime.Composable import androidx.compose.ui.platform.LocalDensity import androidx.compose.ui.unit.Dp /** * The [Int] as [Dp]. */ @Composable fun Int.toDp(): Dp = LocalDensity.current.run { this@toDp.toDp() } /** * The [Float] as [Dp]. */ @Composable fun Float.toDp(): Dp = LocalDensity.current.run { this@toDp.toDp() } /** * The [Double] as [Dp]. */ @Composable fun Double.toDp(): Dp = toFloat().toDp() /** * The [Dp] as a [Float] pixel value. */ @Composable fun Dp.toPx(): Float = LocalDensity.current.run { this@toPx.toPx() }
2
Kotlin
0
7
5ad55d66bbb58a12bf3a8b436ea1ea4d8e9737bc
606
KotlinExtensions
Apache License 2.0
feature/src/main/java/com/thelazybattley/feature/di/DispatcherModule.kt
dellosaneil
720,658,411
false
{"Kotlin": 180336}
package com.thelazybattley.common.di import dagger.Module import dagger.Provides import dagger.hilt.InstallIn import dagger.hilt.components.SingletonComponent import kotlinx.coroutines.Dispatchers import javax.inject.Qualifier import javax.inject.Singleton @Retention @Qualifier annotation class MainDispatcher @Retention @Qualifier annotation class IoDispatcher @Retention @Qualifier annotation class DefaultDispatcher @Module @InstallIn(SingletonComponent::class) object DispatcherModule { @MainDispatcher @Singleton @Provides fun provideMainDispatcher() = Dispatchers.Main.immediate @IoDispatcher @Singleton @Provides fun provideIoDispatcher() = Dispatchers.IO @DefaultDispatcher @Singleton @Provides fun provideDefaultDispatcher() = Dispatchers.Default }
0
Kotlin
0
0
adb7ffc205a27b95b8c847ee3af6dcca373b80ca
816
weather-app
Apache License 2.0
ontrack-model/src/main/java/net/nemerosa/ontrack/model/templating/TemplatingSourceExtensions.kt
nemerosa
19,351,480
false
{"Git Config": 1, "Gradle Kotlin DSL": 67, "Markdown": 46, "Ignore List": 22, "Java Properties": 3, "Shell": 9, "Text": 3, "Batchfile": 2, "Groovy": 145, "JSON": 31, "JavaScript": 792, "JSON with Comments": 4, "GraphQL": 79, "Kotlin": 3960, "Java": 649, "HTML": 269, "PlantUML": 25, "AsciiDoc": 288, "XML": 9, "YAML": 33, "INI": 4, "Dockerfile": 7, "Less": 31, "CSS": 13, "SQL": 43, "Dotenv": 1, "Maven POM": 1, "SVG": 4}
package net.nemerosa.ontrack.model.templating fun parseTemplatingConfig(expression: String): Map<String, String> { if (expression.isBlank()) { return emptyMap() } else { val config = mutableMapOf<String, String>() val tokens = expression.split("&") tokens.forEach { token -> val values = token.split("=") if (values.size != 2) { throw TemplatingConfigFormatException(expression) } else { val (key, value) = values if (key.isNotBlank() && value.isNotBlank()) { config[key.trim()] = value.trim() } else { throw TemplatingConfigFormatException(expression) } } } return config } }
49
Kotlin
25
96
759f17484c9b507204e5a89524e07df871697e74
806
ontrack
MIT License
kotlin/app/src/main/java/tw/idv/woofdog/easyhealthrecord/network/NetFtp.kt
woofdogtw
786,333,430
false
{"Kotlin": 222661, "JavaScript": 740}
package tw.idv.woofdog.easycashaccount.network import java.io.FileInputStream import java.io.FileOutputStream import org.apache.commons.net.ftp.FTP import org.apache.commons.net.ftp.FTPClient import org.apache.commons.net.ftp.FTPSClient /** * This is a class that handles operations of synchronizing FTP. */ class NetFtp(isFtps: Boolean = false) { enum class Result { OK, ERR_NETWORK, // Network error. ERR_REJECT // Rejected by FTP site. } /** * Login to the FTP site. */ fun login(host: String, port: Int, user: String, password: String): Result { var ret: Boolean try { client.connectTimeout = 5000 client.connect(host, port) client.enterLocalPassiveMode() ret = client.login(user, password) if (!ret) { return Result.ERR_REJECT } ret = client.setFileType(FTP.BINARY_FILE_TYPE) } catch (_: Exception) { return Result.ERR_NETWORK } return if (ret) Result.OK else Result.ERR_REJECT } /** * Disconnect from the FTP site. */ fun disconnect(): Result { val ret: Boolean try { ret = client.logout() if (ret && client.isConnected) { client.disconnect() } } catch (_: Exception) { return Result.ERR_NETWORK } return if (ret) Result.OK else Result.ERR_REJECT } /** * Change the working directory. * * @param dir The path of the directory. */ fun changeDir(dir: String): Result { val path = dir.ifEmpty { "." } val ret: Boolean try { ret = client.changeWorkingDirectory(path) } catch (_: Exception) { return Result.ERR_NETWORK } return if (ret) Result.OK else Result.ERR_REJECT } /** * Download a file from the FTP site to a local file. * * @param localFile The local file to write. * @param fileName The remote file name. */ fun downloadFile(localFile: FileOutputStream, fileName: String): Result { val ret: Boolean try { ret = client.retrieveFile(fileName, localFile) localFile.close() } catch (_: Exception) { try { localFile.close() } catch (_: Exception) { } return Result.ERR_NETWORK } return if (ret) Result.OK else Result.ERR_REJECT } /** * Delete a file in the FTP site. * * @param fileName The remote file name. */ fun removeFile(fileName: String): Result { val ret: Boolean try { ret = client.deleteFile(fileName) } catch (e: Exception) { return Result.ERR_NETWORK } return if (ret) Result.OK else Result.ERR_REJECT } /** * Rename a file in the FTP site. * * @param srcFileName The source file name. * @param dstFileName The destination file name. */ fun renameFile(srcFileName: String, dstFileName: String): Result { val ret: Boolean try { ret = client.rename(srcFileName, dstFileName) } catch (_: Exception) { return Result.ERR_NETWORK } return if (ret) Result.OK else Result.ERR_REJECT } /** * Upload a file in the FTP site. * * @param localFile The file to upload. * @param fileName The remote file name. */ fun uploadFile(localFile: FileInputStream, fileName: String): Result { val ret: Boolean try { ret = client.storeFile(fileName, localFile) localFile.close() } catch (_: Exception) { try { localFile.close() } catch (_: Exception) { } return Result.ERR_NETWORK } return if (ret) Result.OK else Result.ERR_REJECT } private val client: FTPClient = if (isFtps) FTPSClient() else FTPClient() }
0
Kotlin
0
0
1d219d66d211fe167df54db1d29fd01f6c6d47ee
4,083
easyhealthrecord
MIT License
app/src/main/java/com/foodiedev/useractivitydetection/receiver/ActivityTransitionReceiver.kt
sriharsha1507
288,730,748
false
null
package com.foodiedev.useractivitydetection.receiver import android.content.BroadcastReceiver import android.content.Context import android.content.Intent import android.widget.Toast import com.foodiedev.useractivitydetection.util.ActivityTransitionsUtil import com.foodiedev.useractivitydetection.util.Constants import com.google.android.gms.location.ActivityTransitionResult import io.karn.notify.Notify import java.text.SimpleDateFormat import java.util.* class ActivityTransitionReceiver : BroadcastReceiver() { override fun onReceive(context: Context, intent: Intent) { if (ActivityTransitionResult.hasResult(intent)) { val result = ActivityTransitionResult.extractResult(intent) result?.let { result.transitionEvents.forEach { event -> //Info for debugging purposes val info = "Transition: " + ActivityTransitionsUtil.toActivityString(event.activityType) + " (" + ActivityTransitionsUtil.toTransitionType(event.transitionType) + ")" + " " + SimpleDateFormat("HH:mm:ss", Locale.US).format(Date()) Notify .with(context) .content { title = "Activity Detected" text = "I can see you are in ${ ActivityTransitionsUtil.toActivityString( event.activityType ) } state" } .show(id = Constants.ACTIVITY_TRANSITION_NOTIFICATION_ID) Toast.makeText(context, info, Toast.LENGTH_LONG).show() } } } } }
0
null
4
6
d22cb5e5bc08438ba354a14def48fbace1630138
1,887
user_activity_detection
MIT License
code/android/app/src/main/java/isel/ps/classcode/presentation/connectivityObserver/ConnectivityObserver.kt
i-on-project
607,828,295
false
null
package isel.ps.classcode.presentation.connectivityObserver import kotlinx.coroutines.flow.Flow /** * Contract for the connectivity observer. This will permit the app to be notified when the connectivity status changes. */ interface ConnectivityObserver { fun observer(): Flow<Status> enum class Status { Available, Unavailable, Losing, Lost } }
8
Kotlin
0
2
38438411f7c3e82136f2c6a2281364bb8e0f3b43
371
repohouse
Apache License 2.0
src/main/kotlin/me/s097t0r1/geminio_kotlin_dsl/recipe/predefined_features/PredefinedFeatures.kt
s097t0r1
597,690,525
false
null
package me.s097t0r1.geminio_kotlin_dsl.recipe.predefined_features import me.s097t0r1.geminio_kotlin_dsl.recipe.RecipeNode class PredefinedFeatures() : RecipeNode { private val nodes = mutableListOf<RecipeNode>() fun enableModuleCreationParams(builder: EnableModuleCreationParams.() -> Unit) { nodes += EnableModuleCreationParams().apply(builder) } override fun unwrap(): Any = nodes.map(RecipeNode::unwrap) }
0
Kotlin
0
2
0aee3788314caa9559a79f32c4719782aaaa69f4
438
geminio-kotlin-dsl
MIT License
gradle/build-logic/convention/src/main/kotlin/com/addhen/fosdem/gradle/AssetCopyTask.kt
eyedol
170,208,282
false
{"Kotlin": 553054, "Shell": 3075, "Swift": 1713}
// Copyright 2024, Addhen Limited and the FOSDEM Event app project contributors // SPDX-License-Identifier: Apache-2.0 package com.addhen.fosdem.gradle import org.gradle.api.DefaultTask import org.gradle.api.file.DirectoryProperty import org.gradle.api.file.RegularFileProperty import org.gradle.api.logging.LogLevel import org.gradle.api.provider.Property import org.gradle.api.tasks.CacheableTask import org.gradle.api.tasks.Input import org.gradle.api.tasks.InputFile import org.gradle.api.tasks.OutputDirectory import org.gradle.api.tasks.PathSensitive import org.gradle.api.tasks.PathSensitivity import org.gradle.api.tasks.TaskAction @CacheableTask abstract class AssetCopyTask : DefaultTask() { @get:OutputDirectory abstract val outputDirectory: DirectoryProperty @get:PathSensitive(PathSensitivity.RELATIVE) @get:InputFile abstract val inputFile: RegularFileProperty @get:Input abstract val outputFilename: Property<String> @TaskAction fun action() { val input = inputFile.get().asFile val output = outputDirectory.get() .file(outputFilename.get()) .asFile logger.log(LogLevel.WARN, "Copying ${input.canonicalPath} to ${output.canonicalPath}") input.copyTo(output, overwrite = true) } }
5
Kotlin
0
1
864cd44be222c86b42dec0d3f3d3635ac6720f2b
1,251
fosdem-event-app
Apache License 2.0
Toolkits/autils/src/main/java/com/atoolkit/autils/AUtils.kt
Suaix
614,829,857
false
null
package com.atoolkit.autils import android.content.Context import androidx.datastore.core.DataStore import androidx.datastore.preferences.core.Preferences import androidx.datastore.preferences.core.booleanPreferencesKey import androidx.datastore.preferences.core.doublePreferencesKey import androidx.datastore.preferences.core.edit import androidx.datastore.preferences.core.floatPreferencesKey import androidx.datastore.preferences.core.intPreferencesKey import androidx.datastore.preferences.core.longPreferencesKey import androidx.datastore.preferences.core.stringPreferencesKey import androidx.datastore.preferences.core.stringSetPreferencesKey import androidx.datastore.preferences.preferencesDataStore import com.atoolkit.common.ILog import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.first import kotlinx.coroutines.flow.map import kotlinx.coroutines.runBlocking internal lateinit var application: Context internal var useCache = true internal var aLog: ILog? = null internal const val TAG = "AUtils" internal val Context.utilsDataStore: DataStore<Preferences> by preferencesDataStore("pf-aUtils") /** * Description: AUtils提供工具类所需的基础信息,如ApplicationContext、Log等; * Author: summer * Date: 2023/3/27 19:22 * LastModifyTime: */ @JvmOverloads fun initAUtils(context: Context, log: ILog? = null, isUseLocalCache: Boolean = true) { application = context.applicationContext aLog = log useCache = isUseLocalCache } /** * Description: 同步读取DataStore里的值 * Author: summer */ internal fun <T> readValue(key: String, defaultValue: T): T { val preferencesKey = getPreferencesKey(key, defaultValue) return runBlocking { application.utilsDataStore.data.map { it[preferencesKey] ?: defaultValue }.first() } } /** * Description: 异步读取DataStore里的值,返回Flow类型 * Author: summer */ internal fun <T> readValueAsync(key: String, defaultValue: T): Flow<T> { val preferencesKey = getPreferencesKey(key, defaultValue) return application.utilsDataStore.data.map { it[preferencesKey] ?: defaultValue } } /** * Description: 向DataStore里写入指定类型的值,必须在协程中调用 * Author: summer */ internal suspend fun <T> writeValue(key: String, value: T) { val preferencesKey = getPreferencesKey(key, value) application.utilsDataStore.edit { it[preferencesKey] = value } } /** * Description: 获取从DataStore存储类型key * Author: summer */ private fun <T> getPreferencesKey(key: String, value: T): Preferences.Key<T> { val preferencesKey = when (value) { is Int -> intPreferencesKey(key) is Float -> floatPreferencesKey(key) is Double -> doublePreferencesKey(key) is Boolean -> booleanPreferencesKey(key) is String -> stringPreferencesKey(key) is Long -> longPreferencesKey(key) is Set<*> -> stringSetPreferencesKey(key) else -> throw IllegalArgumentException("The type of defaultValue($value) cannot store in DataStore") } return preferencesKey as Preferences.Key<T> }
0
Kotlin
0
2
f20df50b68ed17f17c72db73e3da5ee98635d4df
3,019
AToolkit
MIT License
src/main/kotlin/com/careem/gradle/dependencies/effectFinder.kt
careem
309,438,205
false
null
/* * Copyright Careem, an Uber Technologies Inc. company * * 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.careem.gradle.dependencies import com.careem.gradle.dependencies.common.parser.Dependency import com.careem.gradle.dependencies.common.parser.parseDependencyTree fun upgradeEffects(old: String, new: String, collapseKeys: List<String>): String { val (_, _, upgrades) = dependencyDifferences(old, new) return if (upgrades.isNotEmpty()) { val tree = parseDependencyTree(new) val sideEffects = upgrades .map { updatedDependency -> // these are the dependencies that were transparently upgraded due to this upgrade updatedDependency to tree.mapNotNull { treeDependency -> treeDependency.filterMatches { it.matches(updatedDependency.artifact) && it.requestedVersion != it.resolvedVersion } } } .map { it.first to it.second.map { dep -> dep.filterMatches { match -> match.group != "project" } ?: dep } } .filter { it.second.isNotEmpty() } // side effects are grouped by the dependency that was upgraded // collapse dependencies with the same group with each other // so that the output is more readable val collapsedSideEffects = sideEffects .groupBy { it.first.group } .flatMap { (group, effects) -> if (group in collapseKeys) { val upgradedDependency = effects.first().first val groupedUpgradedDependency = upgradedDependency.copy(artifact = "$group:*") effects.distinctBy { it.second } .map { dep -> val count = effects.count { it.second == dep.second } if (count > 1) { dep.copy(first = groupedUpgradedDependency) } else { dep } } } else { effects } } buildString { collapsedSideEffects .forEachIndexed { index, effects -> if (index > 0) { appendLine() } append("Changing ${effects.first.artifact} to ${effects.first.version} will also change:") effects.second .forEach { affectedDependency -> writeTree(affectedDependency, 1) } appendLine() } } } else { "" } } private fun Dependency.matches(target: String) = artifact == target private fun Dependency.filterMatches(lambda: (Dependency) -> Boolean): Dependency? { return if (lambda(this)) { this.copy(children = emptyList()) } else { val children = this.children.mapNotNull { it.filterMatches(lambda) } if (children.isNotEmpty()) { this.copy(children = children) } else { null } } } private fun StringBuilder.writeTree(dependency: Dependency, indent: Int) { appendLine() append(" ".repeat(indent * 4)) append(dependency.artifact) append(" (") append(dependency.resolvedVersion) append(")") dependency.children.forEach { writeTree(it, indent + 1) } }
2
Kotlin
1
35
953a1538bb812579e2c519088954bf38db3fbd12
3,987
dependency-diff-tldr
Apache License 2.0
app/src/main/java/com/mephisto17games/platzhalterpreise/Music.kt
emacholdt
173,496,732
false
null
package com.mephisto17games.platzhalterpreise import android.content.Context import android.media.MediaPlayer import android.os.Build.VERSION_CODES.M import android.preference.Preference object Music { //adding a variable to store the time of music being played. private var pos = 0 private var mp: MediaPlayer? = null fun play(context: Context, resource: Int) { stop(context) // Start music mp = MediaPlayer.create(context, resource) mp!!.isLooping = true mp!!.start() //this will continue the music from wherever it was paused mp!!.seekTo(pos) } fun stop(context: Context) { if (mp != null) { mp!!.pause()//to pause the music //to store current pause time in pos //as pos is static it will retain the value pos = mp!!.currentPosition mp!!.stop() mp!!.release() mp = null } } }
0
Kotlin
0
0
aeb9c4989c5a5003fcf4c182a2e84b6dceff5e28
988
WildcardWillies
MIT License
shared/src/androidMain/kotlin/com/mathroda/shared/Main.android.kt
MathRoda
507,060,394
false
{"Kotlin": 446115, "Swift": 4323, "Ruby": 2379, "Java": 624}
package com.mathroda.shared import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.runtime.Composable import androidx.compose.ui.Modifier @Composable fun MainView() { DashCoinApp( modifier = Modifier.fillMaxSize() ) }
0
Kotlin
41
297
cf303ba50bad35a816253bee5b27beee5ea364b8
259
DashCoin
Apache License 2.0
app/src/main/java/com/tristanwiley/chatse/chat/adapters/UsersAdapter.kt
room-15
54,795,261
false
null
package com.tristanwiley.chatse.chat.adapters import android.content.Context import android.os.Build import android.support.v7.app.AlertDialog import android.support.v7.widget.RecyclerView import android.text.Html import android.text.SpannableString import android.text.util.Linkify import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.ImageView import android.widget.LinearLayout import android.widget.TextView import com.squareup.okhttp.Request import com.tristanwiley.chatse.R import com.tristanwiley.chatse.event.EventList import com.tristanwiley.chatse.event.presenter.message.MessageEvent import com.tristanwiley.chatse.extensions.loadUrl import com.tristanwiley.chatse.network.ClientManager import org.jetbrains.anko.doAsync import org.jetbrains.anko.uiThread import org.json.JSONObject /** * Adapter to display the users in the right NavigationDrawer of the activity. * @param mContext: Context * @param events: All the events to get the users from */ class UsersAdapter(private val mContext: Context, private val events: EventList, private var users: ArrayList<MessageEvent> = ArrayList()) : RecyclerView.Adapter<UsersAdapter.UsersViewHolder>() { override fun onBindViewHolder(holder: UsersViewHolder, pos: Int) { val user = users[pos] holder.bindMessage(user) } //Used to update the list on new events fun update() { users.clear() users.addAll(events.messagePresenter.getUsersList()) this.notifyDataSetChanged() } override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): UsersViewHolder { val view = LayoutInflater.from(parent.context).inflate(R.layout.list_item_user, parent, false) return UsersAdapter.UsersViewHolder(mContext, view) } override fun getItemCount() = users.size class UsersViewHolder(private val mContext: Context, itemView: View) : RecyclerView.ViewHolder(itemView) { private val userPicture: ImageView = itemView.findViewById(R.id.user_icon) private val userName: TextView = itemView.findViewById(R.id.user_name) fun bindMessage(user: MessageEvent) { //Set the username to the TextView userName.text = user.userName userPicture.loadUrl(user.emailHash) //On click, show information about user itemView.setOnClickListener { doAsync { val client = ClientManager.client val request = Request.Builder() .url("https://chat.stackoverflow.com/users/thumbs/${user.userId}") .build() val response = client.newCall(request).execute() val result = JSONObject(response.body().string()) uiThread { //Create AlertDialog with title of their name val builder = AlertDialog.Builder(mContext) .setTitle(result.getString("name")) //Create layout val layout = LinearLayout(mContext) //Get DPI so we can add padding and look natural val dpi = mContext.resources.displayMetrics.density.toInt() layout.setPadding((19 * dpi), (5 * dpi), (14 * dpi), (5 * dpi)) val s: SpannableString //Set user message to the body of the AlertDialog and Linkify links if (!result.isNull("user_message")) { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) { s = SpannableString(Html.fromHtml(result.getString("user_message"), Html.FROM_HTML_MODE_COMPACT)) } else { @Suppress("DEPRECATION") s = SpannableString(Html.fromHtml(result.getString("user_message"))) } Linkify.addLinks(s, Linkify.ALL) } else { s = SpannableString("There's no user bio! :(") } //Set SpannableString to TextView val tv = TextView(mContext) tv.text = s //Add TextView to Layout and set Layout to AlertDialog view layout.addView(tv) builder.setView(layout) //Create cancel button to cancel dialog builder.setNegativeButton("Cancel") { dialog, _ -> dialog.cancel() } //Show Dialog builder.show() } } } } } }
18
null
17
22
4df2e99f4edc2f55da26e1c7e78ff61aca20a9d8
4,919
ChatSE
Apache License 2.0
feature/share/src/main/java/com/xinh/share/widget/common/clearable/ClearableView.kt
HuynhXinh
209,346,576
false
null
package com.xinh.share.widget.common.clearable import android.content.Context import android.util.AttributeSet import android.view.View import com.xinh.share.R import com.xinh.share.extension.showOrGone import com.xinh.share.widget.common.BaseLinearLayout import kotlinx.android.synthetic.main.view_clearable.view.* class ClearableView @JvmOverloads constructor( context: Context, attrs: AttributeSet? = null, defStyleAttr: Int = 0 ) : BaseLinearLayout(context, attrs, defStyleAttr), ClearableComponent { private var listener: (() -> Unit)? = null override fun getLayoutId(): Int { return R.layout.view_clearable } override fun onViewCreated() { ivClear.setOnClickListener { listener?.invoke() } } override fun setOnClearClickListener(listener: () -> Unit) { this.listener = listener } override fun getView(): View { return this } }
1
null
5
19
6a704f65592b2bfbb2363697885b871209775b96
939
mvvm-clean-architecture
The Unlicense
android-sdk/src/main/java/webtrekk/android/sdk/core/AppState.kt
acamarinkovic
198,233,644
true
{"Kotlin": 209891, "Java": 7560}
/* * MIT License * * Copyright (c) 2019 Webtrekk GmbH * * 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 NON INFRINGEMENT. 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 webtrekk.android.sdk.core import android.app.Activity import android.app.Application import android.content.Context import android.os.Bundle import androidx.appcompat.app.AppCompatActivity import androidx.fragment.app.Fragment import androidx.fragment.app.FragmentManager internal abstract class AppState<T : Any> : LifecycleWrapper() { lateinit var lifecycleReceiver: LifecycleReceiver<T> inline fun listenToLifeCycle(context: Context, crossinline onReceive: (T) -> Unit) { (context as? Application)?.registerActivityLifecycleCallbacks(this)?.let { lifecycleReceiver = object : LifecycleReceiver<T> { override fun onLifecycleEventReceived(event: T) { onReceive(event) } } } } fun disable(context: Context) { (context as? Application)?.unregisterActivityLifecycleCallbacks(this) } } internal interface LifecycleReceiver<in T> { fun onLifecycleEventReceived(event: T) } internal open class LifecycleWrapper : Application.ActivityLifecycleCallbacks, FragmentManager.FragmentLifecycleCallbacks() { override fun onActivityPaused(activity: Activity?) { } override fun onActivityResumed(activity: Activity?) { } override fun onActivityStarted(activity: Activity?) { } override fun onActivityDestroyed(activity: Activity?) { (activity as? AppCompatActivity)?.supportFragmentManager?.unregisterFragmentLifecycleCallbacks( this ) } override fun onActivitySaveInstanceState(activity: Activity?, outState: Bundle?) { } override fun onActivityStopped(activity: Activity?) { (activity as? AppCompatActivity)?.supportFragmentManager?.unregisterFragmentLifecycleCallbacks( this ) } override fun onActivityCreated(activity: Activity?, savedInstanceState: Bundle?) { (activity as? AppCompatActivity)?.supportFragmentManager?.registerFragmentLifecycleCallbacks( this, true ) } override fun onFragmentCreated( fm: FragmentManager, f: Fragment, savedInstanceState: Bundle? ) { super.onFragmentCreated(fm, f, savedInstanceState) } override fun onFragmentStarted(fm: FragmentManager, f: Fragment) { super.onFragmentStarted(fm, f) } override fun onFragmentStopped(fm: FragmentManager, f: Fragment) { super.onFragmentStopped(fm, f) } }
0
Kotlin
0
0
ec8c385b329921d9f027545f405da86ef3346e84
3,656
webtrekk-android-sdk-BETA
MIT License
androidtestktx/src/main/java/de/codecentric/androidtestktx/espresso/MockableTestRule.kt
codecentric
155,190,678
false
null
package de.codecentric.androidtestktx.espresso import android.app.Activity import androidx.test.rule.ActivityTestRule class MockableTestRule<A : Activity>( clazz: Class<A>, initialTouchMode: Boolean = false, launchActivity: Boolean = false, private val preStartSettings: () -> Unit = {} ) : ActivityTestRule<A>( clazz, initialTouchMode, launchActivity ) { override fun beforeActivityLaunched() { super.beforeActivityLaunched() preStartSettings() } }
7
Kotlin
7
69
d5ba52472c1bf05e8300c4387e46482ba9c80561
472
androidtestktx
Apache License 2.0
abilityk/src/main/java/com/mozhimen/abilityk/scank/ScanKQRActivity.kt
mozhimen
353,952,154
false
null
package com.mozhimen.scank_hms import android.Manifest import android.app.Activity import android.content.Intent import android.graphics.Rect import android.os.Bundle import android.text.TextUtils import android.widget.FrameLayout import com.huawei.hms.hmsscankit.RemoteView import com.huawei.hms.ml.scan.HmsScan import com.mozhimen.basick.basek.BaseKActivityVB import com.mozhimen.basick.extsk.toJson import com.mozhimen.basick.utilk.UtilKScreen import com.mozhimen.componentk.permissionk.PermissionK import com.mozhimen.componentk.permissionk.annors.PermissionKAnnor import com.mozhimen.scank_hms.databinding.ScankQrActivityBinding @PermissionKAnnor(permissions = [Manifest.permission.CAMERA,Manifest.permission.READ_EXTERNAL_STORAGE]) class ScanKQRActivity : BaseKActivityVB<ScankQrActivityBinding>() { companion object { const val SCANK_ACTIVITY_RESULT_PARAM = "SCANK_ACTIVITY_RESULT_PARAM" } private lateinit var _remoteView: RemoteView private val _detectRect = Rect() override fun initData(savedInstanceState: Bundle?) { PermissionK.initPermissions(this) { if (it) { initView(savedInstanceState) } else { PermissionK.applySetting(this) } } } override fun initView(savedInstanceState: Bundle?) { initRect() initRemoteView(savedInstanceState) } private fun initRemoteView(savedInstanceState: Bundle?) { _remoteView = RemoteView.Builder().setContext(this).setBoundingBox(_detectRect) .setFormat(HmsScan.QRCODE_SCAN_TYPE).build() _remoteView.setOnResultCallback { results -> if (results != null && results.isNotEmpty() && results[0] != null && !TextUtils.isEmpty(results[0].originalValue)) { onScanResult(results[0]) } } _remoteView.onCreate(savedInstanceState) vb.scankQrContainer.addView( _remoteView, FrameLayout.LayoutParams( FrameLayout.LayoutParams.MATCH_PARENT, FrameLayout.LayoutParams.MATCH_PARENT ) ) } private fun initRect() { val screenWidth = UtilKScreen.getScreenWidth() val screenHeight = UtilKScreen.getScreenHeight() val rectSize = vb.scankQrScan.getRectSize() _detectRect.apply { left = (screenWidth - rectSize) / 2 right = (screenWidth + rectSize) / 2 top = (screenHeight - rectSize) / 2 bottom = (screenHeight + rectSize) / 2 } } private fun onScanResult(hmsScan: HmsScan) { val intent = Intent() intent.putExtra(SCANK_ACTIVITY_RESULT_PARAM, hmsScan.toJson()) setResult(Activity.RESULT_OK, intent) finish() } override fun onStart() { super.onStart() _remoteView.onStart() } override fun onResume() { super.onResume() _remoteView.onResume() } override fun onPause() { super.onPause() _remoteView.onPause() } override fun onStop() { super.onStop() _remoteView.onStop() } override fun onDestroy() { super.onDestroy() _remoteView.onDestroy() } }
0
null
1
1
d5b6f4a180302d6abfa56c8fe3d6217dca93141b
3,238
SwiftMK
Apache License 2.0
src/main/kotlin/org/rust/lang/core/completion/RsTupleFieldCompletionProvider.kt
intellij-rust
42,619,487
false
null
/* * Use of this source code is governed by the MIT license that can be * found in the LICENSE file. */ package org.rust.lang.core.completion import com.intellij.codeInsight.completion.CompletionParameters import com.intellij.codeInsight.completion.CompletionResultSet import com.intellij.codeInsight.lookup.LookupElementBuilder import com.intellij.openapi.util.Key import com.intellij.patterns.PatternCondition import com.intellij.patterns.PlatformPatterns import com.intellij.patterns.PsiElementPattern import com.intellij.psi.PsiElement import com.intellij.util.ProcessingContext import org.rust.ide.icons.RsIcons import org.rust.lang.core.psi.RsElementTypes import org.rust.lang.core.psi.RsFieldLookup import org.rust.lang.core.psi.ext.parentDotExpr import org.rust.lang.core.psi.ext.receiver import org.rust.lang.core.psiElement import org.rust.lang.core.types.expectedTypeCoercable import org.rust.lang.core.types.ty.Ty import org.rust.lang.core.types.ty.TyTuple import org.rust.lang.core.types.type object RsTupleFieldCompletionProvider : RsCompletionProvider() { private val TUPLE_FIELD_INFO: Key<Pair<RsFieldLookup, TyTuple>> = Key.create("TUPLE_FIELD_INFO") override val elementPattern: PsiElementPattern.Capture<PsiElement> get() { val parent = psiElement<RsFieldLookup>() .with(object : PatternCondition<RsFieldLookup>("TupleType") { override fun accepts(t: RsFieldLookup, context: ProcessingContext?): Boolean { if (context == null) return false val fieldLookup = t.safeGetOriginalOrSelf() val type = fieldLookup.receiver.type as? TyTuple ?: return false context.put(TUPLE_FIELD_INFO, fieldLookup to type) return true } }) return PlatformPatterns.psiElement(RsElementTypes.IDENTIFIER).withParent(parent) } override fun addCompletions(parameters: CompletionParameters, context: ProcessingContext, result: CompletionResultSet) { val (fieldLookup, type) = context[TUPLE_FIELD_INFO] ?: return val completionContext = RsCompletionContext(fieldLookup, expectedTy = fieldLookup.parentDotExpr.expectedTypeCoercable) val elements = type.types.withIndex().map { (index, ty) -> createLookupElement(object : CompletionEntity { override val ty: Ty get() = ty override fun getBaseLookupElementProperties(context: RsCompletionContext): RsLookupElementProperties = RsLookupElementProperties(elementKind = RsLookupElementProperties.ElementKind.FIELD_DECL) override fun createBaseLookupElement(context: RsCompletionContext): LookupElementBuilder { return LookupElementBuilder .create(index) .bold() .withTypeText(ty.toString()) .withIcon(RsIcons.FIELD) } }, completionContext) } result.addAllElements(elements) } }
1,841
null
380
4,528
c6657c02bb62075bf7b7ceb84d000f93dda34dc1
3,136
intellij-rust
MIT License
src/domain/src/main/kotlin/yapp/be/domain/shelter/service/shelter/AddShelterDomainService.kt
YAPP-Github
634,126,325
false
null
package yapp.be.domain.shelter.service.shelter import org.springframework.stereotype.Service import yapp.be.model.vo.Address import yapp.be.domain.model.Shelter import yapp.be.domain.port.inbound.shelter.AddShelterUseCase import yapp.be.domain.port.outbound.shelter.ShelterCommandHandler @Service class AddShelterDomainService( private val shelterCommandHandler: ShelterCommandHandler ) : AddShelterUseCase { override fun create( name: String, description: String, phoneNumber: String, address: Address ): Shelter { val shelter = Shelter( name = name, description = description, phoneNumber = phoneNumber, address = address ) return shelterCommandHandler.create(shelter) } }
4
null
1
7
5441b296dec05fd1288895518407640dea8f8d3d
797
DangleDangle-server
Apache License 2.0
application/src/test/kotlin/rest/HttpControllersTests.kt
springbootcamp
221,077,269
false
null
package org.springbootcamp.blog.rest import com.ninjasquad.springmockk.MockkBean import io.mockk.every import org.junit.jupiter.api.Test import org.springbootcamp.blog.configuration.BlogProperties import org.springbootcamp.blog.persistence.Article import org.springbootcamp.blog.persistence.ArticleRepository import org.springbootcamp.blog.persistence.User import org.springbootcamp.blog.persistence.UserRepository import org.springframework.beans.factory.annotation.Autowired import org.springframework.boot.context.properties.EnableConfigurationProperties import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest import org.springframework.http.MediaType import org.springframework.test.web.servlet.MockMvc import org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get import org.springframework.test.web.servlet.result.MockMvcResultMatchers.* @WebMvcTest @EnableConfigurationProperties(BlogProperties::class) class HttpControllersTests(@Autowired val mockMvc: MockMvc) { @MockkBean lateinit var userRepository: UserRepository @MockkBean lateinit var articleRepository: ArticleRepository @Test fun `List articles`() { val juergen = User("springjuergen", "Juergen", "Hoeller") val spring5Article = Article("Spring Framework 5.0 goes GA", "Dear Spring community ...", "Lorem ipsum", juergen) val spring43Article = Article("Spring Framework 4.3 goes GA", "Dear Spring community ...", "Lorem ipsum", juergen) every { articleRepository.findAllByOrderByAddedAtDesc() } returns listOf(spring5Article, spring43Article) mockMvc.perform(get("/api/article/").accept(MediaType.APPLICATION_JSON)) .andExpect(status().isOk) .andExpect(content().contentType(MediaType.APPLICATION_JSON)) .andExpect(jsonPath("\$.[0].author.login").value(juergen.login)) .andExpect(jsonPath("\$.[0].slug").value(spring5Article.slug)) .andExpect(jsonPath("\$.[1].author.login").value(juergen.login)) .andExpect(jsonPath("\$.[1].slug").value(spring43Article.slug)) } @Test fun `List users`() { val juergen = User("springjuergen", "Juergen", "Hoeller") val smaldini = User("smaldini", "Stéphane", "Maldini") every { userRepository.findAll() } returns listOf(juergen, smaldini) mockMvc.perform(get("/api/user/").accept(MediaType.APPLICATION_JSON)) .andExpect(status().isOk) .andExpect(content().contentType(MediaType.APPLICATION_JSON)) .andExpect(jsonPath("\$.[0].login").value(juergen.login)) .andExpect(jsonPath("\$.[1].login").value(smaldini.login)) } }
0
Kotlin
0
0
271213236d18a016b2f95afdbe8349f8036fa9b1
2,597
springboot-testcontainers
Apache License 2.0
library/src/main/kotlin/jp/co/recruit_mp/android/lightcalendarview/CalendarKt.kt
recruit-mp
74,326,280
false
null
package jp.co.recruit_mp.android.lightcalendarview import java.util.* /** * Created by recruit-mahayash on 2017/01/13. */ class CalendarKt : GregorianCalendar() { companion object { fun getInstance(settings: CalendarSettings): Calendar = getInstance(settings.timeZone, settings.locale) } }
22
null
70
448
18aaed79bdd634dee74e23f62ccb77df765ea244
309
LightCalendarView
Apache License 2.0
patterns/src/test/kotlin/io/nullables/api/playground/patterns/State.kt
AlexRogalskiy
331,076,596
false
null
/* * Copyright (C) 2021. <NAME>. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.nullables.api.playground.patterns import org.assertj.core.api.Assertions.assertThat import org.junit.jupiter.api.Test sealed class AuthorizationState object Unauthorized : AuthorizationState() class Authorized(val userName: String) : AuthorizationState() class AuthorizationPresenter { private var state: AuthorizationState = Unauthorized val isAuthorized: Boolean get() = when (state) { is Authorized -> true is Unauthorized -> false } val userName: String get() { return when (val state = this.state) { //val enables smart casting of state is Authorized -> state.userName is Unauthorized -> "Unknown" } } fun loginUser(userName: String) { state = Authorized(userName) } fun logoutUser() { state = Unauthorized } override fun toString() = "User '$userName' is logged in: $isAuthorized" } class StateTest { @Test fun State() { val authorizationPresenter = AuthorizationPresenter() authorizationPresenter.loginUser("admin") println(authorizationPresenter) assertThat(authorizationPresenter.isAuthorized).isEqualTo(true) assertThat(authorizationPresenter.userName).isEqualTo("admin") authorizationPresenter.logoutUser() println(authorizationPresenter) assertThat(authorizationPresenter.isAuthorized).isEqualTo(false) assertThat(authorizationPresenter.userName).isEqualTo("Unknown") } }
13
Kotlin
1
2
d7173ec1d9ef227308d926e71335b530c43c92a8
2,171
gradle-kotlin-sample
Apache License 2.0
src/test/kotlin/org/opensearch/commons/notifications/model/EventSourceTests.kt
opensearch-project
354,136,133
false
null
/* * Copyright OpenSearch Contributors * SPDX-License-Identifier: Apache-2.0 */ package org.opensearch.commons.notifications.model import org.junit.jupiter.api.Assertions import org.junit.jupiter.api.Assertions.assertEquals import org.junit.jupiter.api.Test import org.opensearch.commons.notifications.NotificationConstants.FEATURE_ALERTING import org.opensearch.commons.utils.createObjectFromJsonString import org.opensearch.commons.utils.getJsonString import org.opensearch.commons.utils.recreateObject internal class EventSourceTests { @Test fun `Event source serialize and deserialize should be equal`() { val sampleEventSource = EventSource( "title", "reference_id", FEATURE_ALERTING, severity = SeverityType.INFO ) val recreatedObject = recreateObject(sampleEventSource) { EventSource(it) } assertEquals(sampleEventSource, recreatedObject) } @Test fun `Event source serialize and deserialize using json should be equal`() { val sampleEventSource = EventSource( "title", "reference_id", FEATURE_ALERTING, severity = SeverityType.INFO ) val jsonString = getJsonString(sampleEventSource) val recreatedObject = createObjectFromJsonString(jsonString) { EventSource.parse(it) } assertEquals(sampleEventSource, recreatedObject) } @Test fun `Event source should safely ignore extra field in json object`() { val sampleEventSource = EventSource( "title", "reference_id", FEATURE_ALERTING, tags = listOf("tag1", "tag2"), severity = SeverityType.INFO ) val jsonString = """ { "title":"title", "reference_id":"reference_id", "feature":"alerting", "severity":"info", "tags":["tag1", "tag2"], "extra_field_1":["extra", "value"], "extra_field_2":{"extra":"value"}, "extra_field_3":"extra value 3" } """.trimIndent() val recreatedObject = createObjectFromJsonString(jsonString) { EventSource.parse(it) } assertEquals(sampleEventSource, recreatedObject) } @Test fun `Event source should safely accepts unknown feature type in json object`() { val sampleEventSource = EventSource( "title", "reference_id", "NewFeature", tags = listOf("tag1", "tag2"), severity = SeverityType.INFO ) val jsonString = """ { "title":"title", "reference_id":"reference_id", "feature": "NewFeature", "severity":"info", "tags":["tag1", "tag2"] } """.trimIndent() val recreatedObject = createObjectFromJsonString(jsonString) { EventSource.parse(it) } assertEquals(sampleEventSource, recreatedObject) } @Test fun `Event source throw exception if name is empty`() { Assertions.assertThrows(IllegalArgumentException::class.java) { EventSource( "", "reference_id", FEATURE_ALERTING, tags = listOf("tag1", "tag2"), severity = SeverityType.INFO ) } } }
22
Kotlin
65
7
4ef49e57da90fe375dcbfcf05d0e2f865cef1583
3,375
common-utils
Apache License 2.0
kotlin-cdk-wrapper/src/main/kotlin/io/cloudshiftdev/awscdk/services/codepipeline/actions/ManualApprovalAction.kt
cloudshiftinc
667,063,030
false
{"Kotlin": 140726596}
@file:Suppress("RedundantVisibilityModifier","RedundantUnitReturnType","RemoveRedundantQualifierName","unused","UnusedImport","ClassName","REDUNDANT_PROJECTION","DEPRECATION") package io.cloudshiftdev.awscdk.services.codepipeline.actions import io.cloudshiftdev.awscdk.common.CdkDslMarker import io.cloudshiftdev.awscdk.services.iam.IGrantable import io.cloudshiftdev.awscdk.services.iam.IRole import io.cloudshiftdev.awscdk.services.sns.ITopic import kotlin.Number import kotlin.String import kotlin.Unit import kotlin.collections.List /** * Manual approval action. * * Example: * * ``` * Pipeline pipeline = new Pipeline(this, "MyPipeline"); * IStage approveStage = pipeline.addStage(StageOptions.builder().stageName("Approve").build()); * ManualApprovalAction manualApprovalAction = ManualApprovalAction.Builder.create() * .actionName("Approve") * .build(); * approveStage.addAction(manualApprovalAction); * IRole role = Role.fromRoleArn(this, "Admin", * Arn.format(ArnComponents.builder().service("iam").resource("role").resourceName("Admin").build(), * this)); * manualApprovalAction.grantManualApproval(role); * ``` */ public open class ManualApprovalAction( cdkObject: software.amazon.awscdk.services.codepipeline.actions.ManualApprovalAction, ) : Action(cdkObject) { public constructor(props: ManualApprovalActionProps) : this(software.amazon.awscdk.services.codepipeline.actions.ManualApprovalAction(props.let(ManualApprovalActionProps.Companion::unwrap)) ) public constructor(props: ManualApprovalActionProps.Builder.() -> Unit) : this(ManualApprovalActionProps(props) ) /** * grant the provided principal the permissions to approve or reject this manual approval action. * * For more info see: * https://docs.aws.amazon.com/codepipeline/latest/userguide/approvals-iam-permissions.html * * @param grantable the grantable to attach the permissions to. */ public open fun grantManualApproval(grantable: IGrantable) { unwrap(this).grantManualApproval(grantable.let(IGrantable.Companion::unwrap)) } /** * */ public open fun notificationTopic(): ITopic? = unwrap(this).getNotificationTopic()?.let(ITopic::wrap) /** * A fluent builder for * [io.cloudshiftdev.awscdk.services.codepipeline.actions.ManualApprovalAction]. */ @CdkDslMarker public interface Builder { /** * The physical, human-readable name of the Action. * * Note that Action names must be unique within a single Stage. * * @param actionName The physical, human-readable name of the Action. */ public fun actionName(actionName: String) /** * Any additional information that you want to include in the notification email message. * * @param additionalInformation Any additional information that you want to include in the * notification email message. */ public fun additionalInformation(additionalInformation: String) /** * URL you want to provide to the reviewer as part of the approval request. * * Default: - the approval request will not have an external link * * @param externalEntityLink URL you want to provide to the reviewer as part of the approval * request. */ public fun externalEntityLink(externalEntityLink: String) /** * Optional SNS topic to send notifications to when an approval is pending. * * @param notificationTopic Optional SNS topic to send notifications to when an approval is * pending. */ public fun notificationTopic(notificationTopic: ITopic) /** * A list of email addresses to subscribe to notifications when this Action is pending approval. * * If this has been provided, but not `notificationTopic`, * a new Topic will be created. * * @param notifyEmails A list of email addresses to subscribe to notifications when this Action * is pending approval. */ public fun notifyEmails(notifyEmails: List<String>) /** * A list of email addresses to subscribe to notifications when this Action is pending approval. * * If this has been provided, but not `notificationTopic`, * a new Topic will be created. * * @param notifyEmails A list of email addresses to subscribe to notifications when this Action * is pending approval. */ public fun notifyEmails(vararg notifyEmails: String) /** * The Role in which context's this Action will be executing in. * * The Pipeline's Role will assume this Role * (the required permissions for that will be granted automatically) * right before executing this Action. * This Action will be passed into your `IAction.bind` * method in the `ActionBindOptions.role` property. * * Default: a new Role will be generated * * @param role The Role in which context's this Action will be executing in. */ public fun role(role: IRole) /** * The runOrder property for this Action. * * RunOrder determines the relative order in which multiple Actions in the same Stage execute. * * Default: 1 * * [Documentation](https://docs.aws.amazon.com/codepipeline/latest/userguide/reference-pipeline-structure.html) * @param runOrder The runOrder property for this Action. */ public fun runOrder(runOrder: Number) /** * The name of the namespace to use for variables emitted by this action. * * Default: - a name will be generated, based on the stage and action names, * if any of the action's variables were referenced - otherwise, * no namespace will be set * * @param variablesNamespace The name of the namespace to use for variables emitted by this * action. */ public fun variablesNamespace(variablesNamespace: String) } private class BuilderImpl : Builder { private val cdkBuilder: software.amazon.awscdk.services.codepipeline.actions.ManualApprovalAction.Builder = software.amazon.awscdk.services.codepipeline.actions.ManualApprovalAction.Builder.create() /** * The physical, human-readable name of the Action. * * Note that Action names must be unique within a single Stage. * * @param actionName The physical, human-readable name of the Action. */ override fun actionName(actionName: String) { cdkBuilder.actionName(actionName) } /** * Any additional information that you want to include in the notification email message. * * @param additionalInformation Any additional information that you want to include in the * notification email message. */ override fun additionalInformation(additionalInformation: String) { cdkBuilder.additionalInformation(additionalInformation) } /** * URL you want to provide to the reviewer as part of the approval request. * * Default: - the approval request will not have an external link * * @param externalEntityLink URL you want to provide to the reviewer as part of the approval * request. */ override fun externalEntityLink(externalEntityLink: String) { cdkBuilder.externalEntityLink(externalEntityLink) } /** * Optional SNS topic to send notifications to when an approval is pending. * * @param notificationTopic Optional SNS topic to send notifications to when an approval is * pending. */ override fun notificationTopic(notificationTopic: ITopic) { cdkBuilder.notificationTopic(notificationTopic.let(ITopic.Companion::unwrap)) } /** * A list of email addresses to subscribe to notifications when this Action is pending approval. * * If this has been provided, but not `notificationTopic`, * a new Topic will be created. * * @param notifyEmails A list of email addresses to subscribe to notifications when this Action * is pending approval. */ override fun notifyEmails(notifyEmails: List<String>) { cdkBuilder.notifyEmails(notifyEmails) } /** * A list of email addresses to subscribe to notifications when this Action is pending approval. * * If this has been provided, but not `notificationTopic`, * a new Topic will be created. * * @param notifyEmails A list of email addresses to subscribe to notifications when this Action * is pending approval. */ override fun notifyEmails(vararg notifyEmails: String): Unit = notifyEmails(notifyEmails.toList()) /** * The Role in which context's this Action will be executing in. * * The Pipeline's Role will assume this Role * (the required permissions for that will be granted automatically) * right before executing this Action. * This Action will be passed into your `IAction.bind` * method in the `ActionBindOptions.role` property. * * Default: a new Role will be generated * * @param role The Role in which context's this Action will be executing in. */ override fun role(role: IRole) { cdkBuilder.role(role.let(IRole.Companion::unwrap)) } /** * The runOrder property for this Action. * * RunOrder determines the relative order in which multiple Actions in the same Stage execute. * * Default: 1 * * [Documentation](https://docs.aws.amazon.com/codepipeline/latest/userguide/reference-pipeline-structure.html) * @param runOrder The runOrder property for this Action. */ override fun runOrder(runOrder: Number) { cdkBuilder.runOrder(runOrder) } /** * The name of the namespace to use for variables emitted by this action. * * Default: - a name will be generated, based on the stage and action names, * if any of the action's variables were referenced - otherwise, * no namespace will be set * * @param variablesNamespace The name of the namespace to use for variables emitted by this * action. */ override fun variablesNamespace(variablesNamespace: String) { cdkBuilder.variablesNamespace(variablesNamespace) } public fun build(): software.amazon.awscdk.services.codepipeline.actions.ManualApprovalAction = cdkBuilder.build() } public companion object { public operator fun invoke(block: Builder.() -> Unit = {}): ManualApprovalAction { val builderImpl = BuilderImpl() return ManualApprovalAction(builderImpl.apply(block).build()) } internal fun wrap(cdkObject: software.amazon.awscdk.services.codepipeline.actions.ManualApprovalAction): ManualApprovalAction = ManualApprovalAction(cdkObject) internal fun unwrap(wrapped: ManualApprovalAction): software.amazon.awscdk.services.codepipeline.actions.ManualApprovalAction = wrapped.cdkObject as software.amazon.awscdk.services.codepipeline.actions.ManualApprovalAction } }
1
Kotlin
0
4
eb3eef728b34da593a3e55dc423d4f5fa3668e9c
10,995
kotlin-cdk-wrapper
Apache License 2.0
base/src/main/kotlin/de/anura/bot/teamspeak/ActivityCounter.kt
AnuraNet
112,518,939
false
null
package de.anura.bot.teamspeak import de.anura.bot.async.Scheduler import java.time.Duration import java.util.concurrent.TimeUnit object ActivityCounter { private val maxIdleTime = Duration.ofMinutes(5) private const val delay = 30L private val ts = TsBot.api init { Scheduler.scheduleAtFixedRate({ run() }, delay, delay, TimeUnit.SECONDS) } private fun run() { ts.clients.stream() .filter { client -> Duration.ofMillis(client.idleTime) < maxIdleTime } .forEach { client -> TimeManager.add(client.uniqueIdentifier, Duration.ofSeconds(delay)) } TimeManager.saveAll(false) } }
3
Kotlin
0
5
4cd14f6282f4bd84f5caa7c32959f7f05941aab9
655
AnuraBot
MIT License