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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
examples/widgets-gallery/common/src/commonMain/kotlin/org/jetbrains/compose/demo/widgets/ui/screens/Loaders.kt
|
JetBrains
| 293,498,508
| false
| null |
package org.jetbrains.compose.demo.widgets.ui.screens
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.material.CircularProgressIndicator
import androidx.compose.material.LinearProgressIndicator
import androidx.compose.material.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.unit.dp
@Composable
internal fun Loaders() {
AlignedColumn {
CircularProgressIndicator()
}
AlignedColumn {
CircularProgressIndicator(strokeWidth = 8.dp)
}
AlignedColumn {
LinearProgressIndicator()
}
AlignedColumn {
LinearProgressIndicator()
Text(text = "Loading with text...", modifier = Modifier.padding(8.dp))
}
}
@Composable
private fun AlignedColumn(content: @Composable () -> Unit) {
Column(
modifier = Modifier.fillMaxWidth().padding(16.dp)
) {
content()
}
}
| 934
|
Kotlin
|
826
| 9,090
|
97266a0ac8c0d7a8ad8d19ead1c925751a00ff1c
| 1,120
|
compose-jb
|
Apache License 2.0
|
alibaba-rsocket/src/main/kotlin/org/microjservice/rsocket/alibaba/RSocketBrokerHealthIndicator.kt
|
MicroJService
| 382,655,227
| false
| null |
package org.microjservice.rsocket.alibaba
import com.alibaba.rsocket.upstream.UpstreamManager
import io.micronaut.management.health.indicator.HealthIndicator
import com.alibaba.rsocket.health.RSocketServiceHealth
import io.micronaut.management.health.indicator.HealthResult
import com.alibaba.rsocket.events.AppStatusEvent
import io.micronaut.health.HealthStatus
import com.alibaba.rsocket.invocation.RSocketRemoteServiceBuilder
import org.reactivestreams.Publisher
/**
* RSocket Broker health indicator
*
* @author CoderYellow
*/
class RSocketBrokerHealthIndicator(
private val rsocketEndpoint: RSocketEndpoint,
upstreamManager: UpstreamManager?,
brokers: String
) : HealthIndicator {
private val rsocketServiceHealth: RSocketServiceHealth
private val brokers: String
init {
rsocketServiceHealth = RSocketRemoteServiceBuilder
.client(RSocketServiceHealth::class.java)
.nativeImage()
.upstreamManager(upstreamManager)
.build()
this.brokers = brokers
}
companion object {
private const val RSOCKET_HEALTH_INDICATOR_NAME = "RSocket_Service_Health"
private val OUT_OF_SERVICE = HealthStatus(
"OUT_OF_SERVICE",
"indicating that the component or subsystem has been taken out of service and should not be used.",
false,
999
)
}
override fun getResult(): Publisher<HealthResult> {
return rsocketServiceHealth.check(null)
.map { result: Int? ->
val brokerAlive = result != null && result == 1
val localServicesAlive = rsocketEndpoint.rsocketServiceStatus != AppStatusEvent.STATUS_STOPPED
val builder = if (brokerAlive && localServicesAlive) HealthResult.builder(
RSOCKET_HEALTH_INDICATOR_NAME,
HealthStatus.UP
) else HealthResult.builder(
RSOCKET_HEALTH_INDICATOR_NAME, OUT_OF_SERVICE
)
builder.details(
mapOf(
"brokers" to brokers,
"localServiceStatus" to AppStatusEvent.statusText(rsocketEndpoint.rsocketServiceStatus)
)
)
builder.build()
}
.onErrorReturn(
HealthResult
.builder(RSOCKET_HEALTH_INDICATOR_NAME, HealthStatus.DOWN)
.details(mapOf("brokers" to brokers))
.build()
)
}
}
| 0
|
Kotlin
|
0
| 0
|
e6e155b6af3be8f502f57497c8959bb066ec038d
| 2,576
|
micronaut-rsocket
|
Apache License 2.0
|
app-presentation/src/main/java/me/dmba/teamworkboards/screens/boards/adapter/CardViewHolderWithAttachments.kt
|
dmba
| 141,046,741
| false
|
{"Kotlin": 86040}
|
package me.dmba.teamworkboards.screens.boards.adapter
import android.view.ViewGroup
import com.squareup.inject.assisted.Assisted
import com.squareup.inject.assisted.AssistedInject
import com.squareup.picasso.Picasso
import kotlinx.android.synthetic.main.column_item_with_attachments.view.*
import me.dmba.teamworkboards.R
import me.dmba.teamworkboards.data.model.entity.Card
class CardViewHolderWithAttachments @AssistedInject constructor(
private val picasso: Picasso,
@Assisted parent: ViewGroup
) : CardViewHolder(R.layout.column_item_with_attachments, R.id.column_item_layout, parent) {
@AssistedInject.Factory
interface Factory : CardViewHolderFactory {
override fun create(parent: ViewGroup): CardViewHolderWithAttachments
}
override fun onBind(model: Card) = itemView.run {
cardTitle.text = model.name
picasso.load("https://ksr-ugc.imgix.net/assets/016/597/308/5c42126bb290529a1cb36ca98afbb9f0_original.jpg?crop=faces&w=1552&h=873&fit=crop&v=1494344727&auto=format&q=92&s=4ed0aab6c3ed57d95ec5bbde85dda21c")
.into(attachmentImage)
}
}
| 3
|
Kotlin
|
0
| 0
|
a3d31225ebad80ae15158ca18ca0780b81c5726f
| 1,114
|
teamwork-boards
|
Apache License 2.0
|
jipp-pdl/src/main/kotlin/com/hp/jipp/pdl/OutputSettings.kt
|
GladeDiviney
| 204,985,808
| true
|
{"Kotlin": 630166, "Java": 314175, "Python": 38779, "Shell": 1417}
|
// Copyright 2018 HP Development Company, L.P.
// SPDX-License-Identifier: MIT
package com.hp.jipp.pdl
import com.hp.jipp.model.MediaSource
import com.hp.jipp.model.PrintQuality
import com.hp.jipp.model.Sides
/** Generic output settings which may be required for any Page Description Language. */
data class OutputSettings(
/** Color space. */
val colorSpace: ColorSpace = ColorSpace.Rgb,
/** Two-sided printing selection, a keyword from [Sides]. */
val sides: String = Sides.oneSided,
/** The media source to use, a keyword from [MediaSource]. */
val source: String = MediaSource.auto,
/** The level of print quality to use, or null for default. */
val quality: PrintQuality? = null,
/** True if page order should be reversed. */
val reversed: Boolean = false
)
| 1
|
Kotlin
|
0
| 0
|
a339430999383f9a4d8044fed1d402b764fd0a1f
| 810
|
jipp
|
MIT License
|
kotlin-mui/src/main/generated/mui/base/MultiSelectUnstyledProps.kt
|
JetBrains
| 93,250,841
| false
| null |
// Automatically generated - do not modify!
package mui.base
import kotlinx.js.ReadonlyArray
external interface MultiSelectUnstyledProps<TValue> : react.Props {
/**
* The default selected values. Use when the component is not controlled.
* @default []
*/
var defaultValue: ReadonlyArray<TValue>?
/**
* Callback fired when an option is selected.
*/
var onChange: ((value: ReadonlyArray<TValue>) -> Unit)?
/**
* Function that customizes the rendering of the selected values.
*/
var renderValue: ((option: ReadonlyArray<SelectOption<TValue>>) -> react.ReactNode)?
/**
* The selected values.
* Set to an empty array to deselect all options.
*/
var value: ReadonlyArray<TValue>?
}
external interface MultiSelectUnstyledOwnerState<TValue> : MultiSelectUnstyledProps<TValue> {
var active: Boolean
var disabled: Boolean
var open: Boolean
var focusVisible: Boolean
}
| 10
|
Kotlin
|
145
| 983
|
7ef1028ba3e0982dc93edcdfa6ee1edb334ddf35
| 966
|
kotlin-wrappers
|
Apache License 2.0
|
src/main/kotlin/chapter6/Anagram.kt
|
jatzuk
| 147,863,745
| false
| null |
package chapter6
import chapter6.ValuesHolder.count
import chapter6.ValuesHolder.length
/*
* Created with passion and love
* for project DataStructuresAndAlgorithmsInJava(Lafore)
* by Jatzuk on 23.09.2018
* *_____*
* *_*****_*
* *_(O)_(O)_*
* **____V____**
* **_________**
* **_________**
* *_________*
* ***___***
*/
object ValuesHolder {
val arr = "kotlin".toCharArray()
val length = arr.size
var count = 0
}
fun anagram(size: Int = ValuesHolder.length) {
if (size == 1) return
for (i in 0 until size) {
anagram(size - 1)
if (size == 2) displayWord()
rotate(size)
}
}
fun rotate(size: Int) {
val pos = ValuesHolder.length - size
val ch = ValuesHolder.arr[pos]
for (i in pos + 1 until length) ValuesHolder.arr[i - 1] = ValuesHolder.arr[i]
ValuesHolder.arr[length - 1] = ch
}
fun displayWord() {
if (count < 99) print(" ")
if (count < 9) print(" ")
print("${++count}.")
for (i in 0 until length) print(ValuesHolder.arr[i])
print(" ")
if (count % 6 == 0) println()
}
| 0
|
Kotlin
|
0
| 0
|
3b4d740b4ff1787e18c0f6d466004536926a31de
| 1,411
|
DataStructuresAndAlgorithmsInJava
|
MIT License
|
app/src/main/java/com/breezeshankar/features/nearbyshops/api/updateaddress/ShopAddressUpdateRepo.kt
|
DebashisINT
| 851,529,165
| false
|
{"Kotlin": 15698684, "Java": 1025747}
|
package com.breezeshankar.features.nearbyshops.api.updateaddress
import com.breezeshankar.base.BaseResponse
import com.breezeshankar.features.nearbyshops.model.updateaddress.AddressUpdateRequest
import io.reactivex.Observable
/**
* Created by Pratishruti on 05-02-2018.
*/
class ShopAddressUpdateRepo (val apiService: ShopAddressUpdateApi) {
fun getShopAddressUpdate(shopAddressUpdate:AddressUpdateRequest): Observable<BaseResponse> {
return apiService.getShopAddressUpdate(shopAddressUpdate)
}
}
| 0
|
Kotlin
|
0
| 0
|
d382b7af0064e3965a2a89789c42731687d911f5
| 516
|
SHANKARMG
|
Apache License 2.0
|
src/main/kotlin/io/github/divinespear/plugin/extension.kt
|
ragnor
| 261,009,136
| true
|
{"Kotlin": 70558, "Groovy": 55123, "Java": 11988}
|
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you 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.github.divinespear.plugin
import org.gradle.api.Action
import org.gradle.api.NamedDomainObjectContainer
import java.io.File
open class JpaSchemaGenerationProperties(val name: String?,
val options: MutableMap<String, Any?>) {
constructor(name: String?) : this(name, mutableMapOf("properties" to mapOf<String, String>(),
"packageToScan" to setOf<String>()))
var skip: Boolean? by options
var format: Boolean? by options
var scanTestClasses: Boolean? by options
var persistenceXml: String? by options
var persistenceUnitName: String? by options
var databaseAction: String? by options
var scriptAction: String? by options
var outputDirectory: File? by options
var createOutputFileName: String? by options
var dropOutputFileName: String? by options
var createSourceMode: String? by options
var createSourceFile: File? by options
var dropSourceMode: String? by options
var dropSourceFile: File? by options
var jdbcDriver: String? by options
var jdbcUrl: String? by options
var jdbcUser: String? by options
var jdbcPassword: String? by options
var databaseProductName: String? by options
var databaseMajorVersion: Int? by options
var databaseMinorVersion: Int? by options
var properties: Map<String, String> by options
var vendor: String? by options
var addNullDataSource: Boolean? by options
var packageToScan: Set<String> by options
var lineSeparator: String? by options
val defaultCreateOutputFileName = if (name == null) "create.sql" else "$name-create.sql"
val defaultDropOutputFileName = if (name == null) "drop.sql" else "$name-drop.sql"
internal fun provider() = vendor?.let { PERSISTENCE_PROVIDER_MAP[it.toLowerCase()] } ?: vendor
internal fun isDatabaseTarget() = !JAVAX_SCHEMA_GENERATION_NONE_ACTION.equals(databaseAction, true)
internal fun isScriptTarget() = !JAVAX_SCHEMA_GENERATION_NONE_ACTION.equals(scriptAction, true)
}
open class JpaSchemaGenerationExtension : JpaSchemaGenerationProperties(null) {
lateinit var defaultOutputDirectory: File
lateinit var targets: NamedDomainObjectContainer<JpaSchemaGenerationProperties>
fun targets(action: Action<NamedDomainObjectContainer<JpaSchemaGenerationProperties>>) {
action.execute(targets)
}
fun extend(other: JpaSchemaGenerationProperties?) = JpaSchemaGenerationProperties(other?.name, merge(this, other))
}
private val MERGE_EXCLUDE_PROPERTIES = listOf("properties", "packageToScan")
private val PROPERTY_DEFAULT_VALUES = mapOf("skip" to false,
"format" to false,
"scanTestClasses" to false,
"persistenceUnitName" to DEFAULT_PERSISTENCE_UNIT_NAME,
"databaseAction" to JAVAX_SCHEMA_GENERATION_NONE_ACTION,
"scriptAction" to JAVAX_SCHEMA_GENERATION_NONE_ACTION,
"createSourceMode" to JAVAX_SCHEMA_GENERATION_METADATA_SOURCE,
"dropSourceMode" to JAVAX_SCHEMA_GENERATION_METADATA_SOURCE)
private fun merge(base: JpaSchemaGenerationExtension, target: JpaSchemaGenerationProperties? = null): MutableMap<String, Any?> {
val map = mutableMapOf<String, Any?>()
var properties = mapOf<String, String>()
var packageToScan = setOf<String>()
// merge extensions
arrayOf(base, target).filterNotNull().forEach {
map.putAll(it.options.filterKeys { !MERGE_EXCLUDE_PROPERTIES.contains(it) })
properties += it.properties
packageToScan += it.packageToScan
}
map["properties"] = properties
map["packageToScan"] = packageToScan
// default
PROPERTY_DEFAULT_VALUES.forEach {
if (map[it.key] == null) map[it.key] = it.value
}
if (map["outputDirectory"] == null) map["outputDirectory"] = base.defaultOutputDirectory
if (map["createOutputFileName"] == null) map["createOutputFileName"] = (target ?: base).defaultCreateOutputFileName
if (map["dropOutputFileName"] == null) map["dropOutputFileName"] = (target ?: base).defaultDropOutputFileName
return map.withDefault { _ -> null }
}
| 0
| null |
0
| 0
|
972a3c50516d58e87c388bce3ccee6e78ea17fda
| 5,080
|
jpa-schema-gradle-plugin
|
Apache License 2.0
|
src/commonMain/kotlin/animatedledstrip/animations/predefined/smooth_fade.kt
|
AnimatedLEDStrip
| 168,790,414
| false
|
{"Kotlin": 844872, "Python": 9025, "Shell": 8325}
|
/*
* Copyright (c) 2018-2021 AnimatedLEDStrip
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package animatedledstrip.animations.predefined
import animatedledstrip.animations.Animation
import animatedledstrip.animations.AnimationParameter
import animatedledstrip.animations.DefinedAnimation
import animatedledstrip.animations.Dimensionality
import animatedledstrip.leds.colormanagement.setStripProlongedColor
import kotlinx.coroutines.delay
val smoothFade = DefinedAnimation(
Animation.AnimationInfo(
name = "Smooth Fade",
abbr = "SMF",
description = "Like a [Smooth Chase](Smooth-Chase) animation, but the " +
"whole strip is the same color while fading through `colors[0]`.",
runCountDefault = -1,
minimumColors = 1,
unlimitedColors = false,
dimensionality = Dimensionality.anyDimensional,
intParams = listOf(AnimationParameter("interColorChangeDelay", "Delay between color changes", 50),
AnimationParameter("colorsToFadeThrough",
"Number of colors to fade through (used to prepare the ColorContainer)",
100)),
)
) { leds, params, _ ->
val colorsToFadeThrough = params.intParams.getValue("colorsToFadeThrough")
val color = params.colors[0].originalColorContainer().prepare(colorsToFadeThrough)
val interColorChangeDelay = params.intParams.getValue("interColorChangeDelay").toLong()
leds.apply {
for (i in 0 until colorsToFadeThrough) {
setStripProlongedColor(color[i])
delay(interColorChangeDelay)
}
}
}
| 10
|
Kotlin
|
3
| 9
|
77a61846dbf723686633827a5690d57c4a451723
| 2,716
|
AnimatedLEDStrip
|
MIT License
|
compiler/backend/src/org/jetbrains/kotlin/codegen/coroutines/SuspendFunctionGenerationStrategy.kt
|
JakeWharton
| 99,388,807
| false
| null |
/*
* Copyright 2010-2019 JetBrains s.r.o. and Kotlin Programming Language contributors.
* Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file.
*/
package org.jetbrains.kotlin.codegen.coroutines
import org.jetbrains.kotlin.backend.common.CodegenUtil
import org.jetbrains.kotlin.codegen.*
import org.jetbrains.kotlin.codegen.binding.CodegenBinding
import org.jetbrains.kotlin.codegen.inline.addFakeContinuationConstructorCallMarker
import org.jetbrains.kotlin.codegen.inline.coroutines.SurroundSuspendLambdaCallsWithSuspendMarkersMethodVisitor
import org.jetbrains.kotlin.codegen.state.GenerationState
import org.jetbrains.kotlin.config.JVMConstructorCallNormalizationMode
import org.jetbrains.kotlin.config.LanguageVersionSettings
import org.jetbrains.kotlin.config.languageVersionSettings
import org.jetbrains.kotlin.descriptors.ClassDescriptor
import org.jetbrains.kotlin.descriptors.FunctionDescriptor
import org.jetbrains.kotlin.psi.KtFunction
import org.jetbrains.kotlin.psi.psiUtil.getElementTextWithContext
import org.jetbrains.kotlin.resolve.jvm.diagnostics.OtherOrigin
import org.jetbrains.kotlin.resolve.jvm.jvmSignature.JvmMethodSignature
import org.jetbrains.kotlin.types.typeUtil.isUnit
import org.jetbrains.kotlin.utils.addToStdlib.safeAs
import org.jetbrains.kotlin.utils.sure
import org.jetbrains.org.objectweb.asm.MethodVisitor
import org.jetbrains.org.objectweb.asm.Opcodes
import org.jetbrains.org.objectweb.asm.Type
import org.jetbrains.org.objectweb.asm.tree.MethodNode
open class SuspendFunctionGenerationStrategy(
state: GenerationState,
protected val originalSuspendDescriptor: FunctionDescriptor,
protected val declaration: KtFunction,
protected val containingClassInternalName: String,
private val constructorCallNormalizationMode: JVMConstructorCallNormalizationMode,
protected val functionCodegen: FunctionCodegen
) : FunctionGenerationStrategy.CodegenBased(state) {
private lateinit var codegen: ExpressionCodegen
private val languageVersionSettings: LanguageVersionSettings = state.configuration.languageVersionSettings
private val classBuilderForCoroutineState by lazy {
state.factory.newVisitor(
OtherOrigin(declaration, originalSuspendDescriptor),
CodegenBinding.asmTypeForAnonymousClass(state.bindingContext, originalSuspendDescriptor),
declaration.containingFile
).also {
val coroutineCodegen =
CoroutineCodegenForNamedFunction.create(it, codegen, originalSuspendDescriptor, declaration)
coroutineCodegen.generate()
}
}
override fun wrapMethodVisitor(mv: MethodVisitor, access: Int, name: String, desc: String): MethodVisitor {
if (access and Opcodes.ACC_ABSTRACT != 0) return mv
val stateMachineBuilder = createStateMachineBuilder(mv, access, name, desc)
val forInline = state.bindingContext[CodegenBinding.CAPTURES_CROSSINLINE_LAMBDA, originalSuspendDescriptor] == true
// Both capturing and inline functions share the same suffix, however, inline functions can also be capturing
// they are already covered by SuspendInlineFunctionGenerationStrategy, thus, if we generate yet another copy,
// we will get name+descriptor clash
return if (forInline && !originalSuspendDescriptor.isInline)
AddConstructorCallForCoroutineRegeneration(
MethodNodeCopyingMethodVisitor(
SurroundSuspendLambdaCallsWithSuspendMarkersMethodVisitor(
stateMachineBuilder,
access, name, desc, containingClassInternalName,
isCapturedSuspendLambda = {
isCapturedSuspendLambda(
functionCodegen.closure.sure {
"Anonymous object should have closure"
},
it.name,
state.bindingContext
)
}
), access, name, desc,
newMethod = { origin, newAccess, newName, newDesc ->
functionCodegen.newMethod(origin, newAccess, newName, newDesc, null, null)
}
), access, name, desc, null, null, this::classBuilderForCoroutineState,
containingClassInternalName,
originalSuspendDescriptor.dispatchReceiverParameter != null,
containingClassInternalNameOrNull(),
languageVersionSettings
) else stateMachineBuilder
}
protected fun createStateMachineBuilder(
mv: MethodVisitor,
access: Int,
name: String,
desc: String
): CoroutineTransformerMethodVisitor {
return CoroutineTransformerMethodVisitor(
mv, access, name, desc, null, null, containingClassInternalName, this::classBuilderForCoroutineState,
isForNamedFunction = true,
reportSuspensionPointInsideMonitor = { reportSuspensionPointInsideMonitor(declaration, state, it) },
lineNumber = CodegenUtil.getLineNumberForElement(declaration, false) ?: 0,
sourceFile = declaration.containingKtFile.name,
shouldPreserveClassInitialization = constructorCallNormalizationMode.shouldPreserveClassInitialization,
needDispatchReceiver = originalSuspendDescriptor.dispatchReceiverParameter != null,
internalNameForDispatchReceiver = containingClassInternalNameOrNull(),
languageVersionSettings = languageVersionSettings,
disableTailCallOptimizationForFunctionReturningUnit = originalSuspendDescriptor.returnType?.isUnit() == true &&
originalSuspendDescriptor.overriddenDescriptors.isNotEmpty() &&
!originalSuspendDescriptor.allOverriddenFunctionsReturnUnit()
)
}
private fun FunctionDescriptor.allOverriddenFunctionsReturnUnit(): Boolean {
val visited = mutableSetOf<FunctionDescriptor>()
fun bfs(descriptor: FunctionDescriptor): Boolean {
if (!visited.add(descriptor)) return true
if (descriptor.original.returnType?.isUnit() != true) return false
for (parent in descriptor.overriddenDescriptors) {
if (!bfs(parent)) return false
}
return true
}
return bfs(this)
}
private fun containingClassInternalNameOrNull() =
originalSuspendDescriptor.containingDeclaration.safeAs<ClassDescriptor>()?.let(state.typeMapper::mapClass)?.internalName
override fun doGenerateBody(codegen: ExpressionCodegen, signature: JvmMethodSignature) {
this.codegen = codegen
codegen.returnExpression(declaration.bodyExpression ?: error("Function has no body: " + declaration.getElementTextWithContext()))
}
// When we generate named suspend function for the use as inline site, we do not generate state machine.
// So, there will be no way to remember the name of generated continuation in such case.
// In order to keep generated continuation for named suspend function, we just generate construction call, which is going to be
// removed during inlining.
// The continuation itself will be regenerated and used as a container for the coroutine's locals.
private class AddConstructorCallForCoroutineRegeneration(
delegate: MethodVisitor,
access: Int,
name: String,
desc: String,
signature: String?,
exceptions: Array<out String>?,
obtainClassBuilderForCoroutineState: () -> ClassBuilder,
private val containingClassInternalName: String,
private val needDispatchReceiver: Boolean,
private val internalNameForDispatchReceiver: String?,
private val languageVersionSettings: LanguageVersionSettings
) : TransformationMethodVisitor(delegate, access, name, desc, signature, exceptions) {
private val classBuilderForCoroutineState: ClassBuilder by lazy(obtainClassBuilderForCoroutineState)
override fun performTransformations(methodNode: MethodNode) {
val objectTypeForState = Type.getObjectType(classBuilderForCoroutineState.thisName)
methodNode.instructions.insert(withInstructionAdapter {
addFakeContinuationConstructorCallMarker(this, true)
generateContinuationConstructorCall(
objectTypeForState,
methodNode,
needDispatchReceiver,
internalNameForDispatchReceiver,
containingClassInternalName,
classBuilderForCoroutineState,
languageVersionSettings
)
addFakeContinuationConstructorCallMarker(this, false)
pop() // Otherwise stack-transformation breaks
})
}
}
}
| 12
| null |
28
| 83
|
4383335168338df9bbbe2a63cb213a68d0858104
| 9,044
|
kotlin
|
Apache License 2.0
|
src/test/kotlin/nl/jackploeg/aoc/_2023/calendar/day03/Day03Test.kt
|
jackploeg
| 736,755,380
| false
|
{"Kotlin": 318734}
|
package nl.jackploeg.aoc._2023.calendar.day03
import javax.inject.Inject
import nl.jackploeg.aoc._2023.DaggerTestDayComponent
import org.junit.jupiter.api.Assertions.assertEquals
import org.junit.jupiter.api.BeforeEach
import org.junit.jupiter.api.Test
internal class Day03Test {
@Inject
lateinit var day03: Day03
@BeforeEach
fun setup() {
DaggerTestDayComponent.create().inject(this)
}
@Test
fun testDay03PartOneTestInput() {
assertEquals(4361, day03.partOne(DAY_03_TEST))
}
@Test
fun testDay03PartTwoTestInput() {
assertEquals(467835, day03.partTwo(DAY_03_TEST))
}
@Test
fun testDay03PartOne() {
assertEquals(532331, day03.partOne(DAY_03))
}
@Test
fun testDay03PartTwo() {
assertEquals(82301120, day03.partTwo(DAY_03))
}
companion object {
private const val DAY_03: String = "advent-of-code-input/2023/day03.input"
private const val DAY_03_TEST: String = "advent-of-code-input/2023/day03.test"
}
}
| 0
|
Kotlin
|
0
| 0
|
f2b873b6cf24bf95a4ba3d0e4f6e007b96423b76
| 976
|
advent-of-code
|
MIT License
|
app/src/main/java/com/pengxh/secretkey/ui/GestureSetActivity.kt
|
frankjiayounuli
| 361,637,014
| true
|
{"Kotlin": 230011, "HTML": 4389, "CSS": 303}
|
package com.pengxh.secretkey.ui
import android.os.Handler
import com.pengxh.app.multilib.utils.SaveKeyValues
import com.pengxh.secretkey.BaseActivity
import com.pengxh.secretkey.R
import com.pengxh.secretkey.extention.covertColor
import com.pengxh.secretkey.utils.Constant
import com.pengxh.secretkey.widgets.gesture.GestureLockLayout
import com.pengxh.secretkey.widgets.gesture.GestureLockLayout.OnLockResetListener
import kotlinx.android.synthetic.main.activity_gesture_set.*
import kotlinx.android.synthetic.main.include_base_title.*
/**
* @author: Pengxh
* @email: 290677893@qq.com
* @date: 2020/7/28 22:29
*/
class GestureSetActivity : BaseActivity() {
override fun initLayoutView(): Int = R.layout.activity_gesture_set
override fun initData() {
}
override fun setupTopBarLayout() {
titleView.text = "设置手势解锁密码"
}
override fun initEvent() {
//设置提示view 每行每列点的个数
displayView.setDotCount(3)
//设置提示view 选中状态的颜色
displayView.setDotSelectedColor(R.color.mainThemeColor.covertColor(this))
//设置手势解锁view 每行每列点的个数
gestureLockLayout.setDotCount(3)
//设置手势解锁view 最少连接数
gestureLockLayout.setMinCount(4)
//设置手势解锁view 模式为重置密码模式
gestureLockLayout.setMode(GestureLockLayout.RESET_MODE)
gestureLockLayout.setOnLockResetListener(object : OnLockResetListener {
override fun onConnectCountUnmatched(connectCount: Int, minCount: Int) {
//连接数小于最小连接数时调用
settingHint.text = "最少连接" + minCount + "个点"
resetGesture()
}
override fun onFirstPasswordFinished(answerList: MutableList<Int>) {
//第一次绘制手势成功时调用
settingHint.text = "确认解锁图案"
//将答案设置给提示view
displayView.setAnswer(answerList)
//重置
resetGesture()
}
override fun onSetPasswordFinished(isMatched: Boolean, answerList: MutableList<Int>) {
//第二次密码绘制成功时调用
if (isMatched) {
//两次答案一致,保存
SaveKeyValues.putValue("gesturePassword", answerList.toString())
SaveKeyValues.putValue(Constant.PASSWORD_MODE, "gestureSwitch")
finish()
} else {
resetGesture()
}
}
})
}
private val mHandler: Handler = Handler()
private fun resetGesture() {
mHandler.postDelayed({ gestureLockLayout.resetGesture() }, 200)
}
override fun onDestroy() {
super.onDestroy()
mHandler.removeCallbacksAndMessages(null)
}
}
| 0
| null |
0
| 0
|
d17b1bf0de88d41619b408665e3c30bd45029971
| 2,678
|
SecretKey
|
Apache License 2.0
|
src/main/kotlin/me/jason5lee/ktpost/getUser/api.kt
|
Jason5Lee
| 489,935,868
| false
| null |
package me.jason5lee.ktpost.getUser
import io.vertx.ext.web.RoutingContext
import me.jason5lee.ktpost.common.*
import me.jason5lee.resukt.getOrElse
internal fun getUserApi(getUser: GetUser) = api(
path = { get("/user/:userId") },
) { ctx ->
val input = UserId(
parseId(ctx.pathParam("userId") ?: return@api ctx.respondNoUserId())
.getOrElse { return@api ctx.respondUserNotFound() }
)
val output = getUser(input).getOrElse {
return@api when (it) {
Failure.UserNotFound -> ctx.respondUserNotFound()
}
}
@Suppress("unused")
class ResponseDto(
val userName: String,
val creationTime: Long,
)
ctx.json(
ResponseDto(
userName = output.name.value,
creationTime = output.creation.utc,
)
)
}
suspend fun RoutingContext.respondUserNotFound() = respondJson(404, FailureBody(reason = "user not found"))
suspend fun RoutingContext.respondNoUserId(): Unit =
respondJson(
statusCode = 400, // Bad Request
FailureBody(
reason = "parameter userId not provided"
)
)
| 0
|
Kotlin
|
0
| 1
|
b76c9ecb2777e266c2ac054a73b74d22e232237c
| 1,048
|
ktpost
|
Apache License 2.0
|
src/main/kotlin/com/nftco/flow/sdk/crypto/Crypto.kt
|
the-nft-company
| 355,268,322
| false
| null |
package org.onflow.sdk.crypto
import org.bouncycastle.jce.ECNamedCurveTable
import org.bouncycastle.jce.ECPointUtil
import org.bouncycastle.jce.interfaces.ECPrivateKey
import org.bouncycastle.jce.interfaces.ECPublicKey
import org.bouncycastle.jce.provider.BouncyCastleProvider
import org.bouncycastle.jce.spec.ECNamedCurveSpec
import org.bouncycastle.jce.spec.ECPrivateKeySpec
import org.onflow.sdk.HashAlgorithm
import org.onflow.sdk.Hasher
import org.onflow.sdk.SignatureAlgorithm
import org.onflow.sdk.Signer
import org.onflow.sdk.bytesToHex
import org.onflow.sdk.hexToBytes
import java.math.BigInteger
import java.security.KeyFactory
import java.security.KeyPairGenerator
import java.security.MessageDigest
import java.security.SecureRandom
import java.security.Security
import java.security.Signature
import java.security.spec.ECGenParameterSpec
import java.security.spec.ECPublicKeySpec
import kotlin.experimental.and
import kotlin.math.max
data class KeyPair(
val private: PrivateKey,
val public: PublicKey
)
data class PrivateKey(
val key: java.security.PrivateKey,
val ecCoupleComponentSize: Int,
val hex: String
)
data class PublicKey(
val key: java.security.PublicKey,
val hex: String
)
object Crypto {
init {
Security.addProvider(BouncyCastleProvider())
}
@JvmStatic
@JvmOverloads
fun generateKeyPair(algo: SignatureAlgorithm = SignatureAlgorithm.ECDSA_P256): KeyPair {
val generator = KeyPairGenerator.getInstance("EC", "BC")
generator.initialize(ECGenParameterSpec(algo.curve), SecureRandom())
val keyPair = generator.generateKeyPair()
val privateKey = keyPair.private
val publicKey = keyPair.public
return KeyPair(
private = PrivateKey(
key = keyPair.private,
ecCoupleComponentSize = if (privateKey is ECPrivateKey) {
privateKey.parameters.n.bitLength() / 8
} else {
0
},
hex = if (privateKey is ECPrivateKey) {
privateKey.d.toByteArray().bytesToHex()
} else {
throw IllegalArgumentException("PrivateKey must be an ECPublicKey")
}
),
public = PublicKey(
key = publicKey,
hex = if (publicKey is ECPublicKey) {
(publicKey.q.xCoord.encoded + publicKey.q.yCoord.encoded).bytesToHex()
} else {
throw IllegalArgumentException("PublicKey must be an ECPublicKey")
}
)
)
}
@JvmStatic
@JvmOverloads
fun decodePrivateKey(key: String, algo: SignatureAlgorithm = SignatureAlgorithm.ECDSA_P256): PrivateKey {
val ecParameterSpec = ECNamedCurveTable.getParameterSpec(algo.curve)
val keyFactory = KeyFactory.getInstance(algo.algorithm, "BC")
val ecPrivateKeySpec = ECPrivateKeySpec(BigInteger(key, 16), ecParameterSpec)
val pk = keyFactory.generatePrivate(ecPrivateKeySpec)
return PrivateKey(
key = pk,
ecCoupleComponentSize = if (pk is ECPrivateKey) {
pk.parameters.n.bitLength() / 8
} else {
0
},
hex = if (pk is ECPrivateKey) {
pk.d.toByteArray().bytesToHex()
} else {
throw IllegalArgumentException("PrivateKey must be an ECPublicKey")
}
)
}
@JvmStatic
@JvmOverloads
fun decodePublicKey(key: String, algo: SignatureAlgorithm = SignatureAlgorithm.ECDSA_P256): PublicKey {
val ecParameterSpec = ECNamedCurveTable.getParameterSpec(algo.curve)
val keyFactory = KeyFactory.getInstance("EC", "BC")
val params = ECNamedCurveSpec(
algo.curve,
ecParameterSpec.curve, ecParameterSpec.g, ecParameterSpec.n
)
val point = ECPointUtil.decodePoint(params.curve, byteArrayOf(0x04) + key.hexToBytes())
val pubKeySpec = ECPublicKeySpec(point, params)
val publicKey = keyFactory.generatePublic(pubKeySpec)
return PublicKey(
key = publicKey,
hex = if (publicKey is ECPublicKey) {
(publicKey.q.xCoord.encoded + publicKey.q.yCoord.encoded).bytesToHex()
} else {
throw IllegalArgumentException("PublicKey must be an ECPublicKey")
}
)
}
@JvmStatic
@JvmOverloads
fun getSigner(privateKey: PrivateKey, hashAlgo: HashAlgorithm = HashAlgorithm.SHA3_256): Signer {
return SignerImpl(privateKey, hashAlgo)
}
@JvmStatic
@JvmOverloads
fun getHasher(hashAlgo: HashAlgorithm = HashAlgorithm.SHA3_256): Hasher {
return HasherImpl(hashAlgo)
}
}
internal class HasherImpl(
private val hashAlgo: HashAlgorithm
) : Hasher {
override fun hash(bytes: ByteArray): ByteArray {
val digest = MessageDigest.getInstance(hashAlgo.algorithm)
return digest.digest(bytes)
}
}
internal class SignerImpl(
private val privateKey: PrivateKey,
private val hashAlgo: HashAlgorithm,
override val hasher: Hasher = HasherImpl(hashAlgo)
) : Signer {
override fun sign(bytes: ByteArray): ByteArray {
val ecdsaSign = Signature.getInstance(hashAlgo.id)
ecdsaSign.initSign(privateKey.key)
ecdsaSign.update(bytes)
val signature = ecdsaSign.sign()
if (privateKey.ecCoupleComponentSize <= 0) {
return signature
}
val (r, s) = extractRS(signature)
val nLen = privateKey.ecCoupleComponentSize
val paddedSignature = ByteArray(2 * nLen)
val rBytes = r.toByteArray()
val sBytes = s.toByteArray()
// occasionally R/S bytes representation has leading zeroes, so make sure we trim them appropriately
rBytes.copyInto(paddedSignature, max(nLen - rBytes.size, 0), max(0, rBytes.size - nLen))
sBytes.copyInto(paddedSignature, max(2 * nLen - sBytes.size, nLen), max(0, sBytes.size - nLen))
return paddedSignature
}
private fun extractRS(signature: ByteArray): Pair<BigInteger, BigInteger> {
val startR = if ((signature[1] and 0x80.toByte()) != 0.toByte()) 3 else 2
val lengthR = signature[startR + 1].toInt()
val startS = startR + 2 + lengthR
val lengthS = signature[startS + 1].toInt()
return Pair(
BigInteger(signature.copyOfRange(startR + 2, startR + 2 + lengthR)),
BigInteger(signature.copyOfRange(startS + 2, startS + 2 + lengthS))
)
}
}
| 6
|
Kotlin
|
5
| 8
|
9f5181d89e8bc3fc44292e372e577427cb657705
| 6,660
|
flow-jvm-sdk
|
Apache License 2.0
|
navigation/core/src/commonMain/kotlin/com/taetae98/diary/navigation/core/more/MoreEntry.kt
|
taetae98coding
| 704,066,572
| false
|
{"Kotlin": 306928, "Swift": 1582, "HTML": 230}
|
package com.taetae98.diary.navigation.core.more
import com.arkivanov.decompose.ComponentContext
import com.arkivanov.decompose.router.stack.ChildStack
import com.arkivanov.decompose.router.stack.StackNavigation
import com.arkivanov.decompose.router.stack.childStack
import com.arkivanov.decompose.value.Value
import com.arkivanov.essenty.parcelable.Parcelable
import com.taetae98.diary.navigation.core.Entry
import com.taetae98.diary.navigation.core.Graph
import com.taetae98.diary.navigation.core.Route
import com.taetae98.diary.navigation.core.memo.list.MemoListRoute
import com.taetae98.diary.navigation.core.more.list.MoreListEntry
public class MoreEntry(
context: ComponentContext,
) : Entry(context), Graph {
private val navigation = StackNavigation<Route>()
override val stack: Value<ChildStack<Parcelable, Entry>> = childStack(
source = navigation,
initialConfiguration = MemoListRoute,
handleBackButton = true,
) { parcelable, context ->
when (parcelable) {
MemoListRoute -> MoreListEntry(context = context)
else -> error("Illegal Route : $parcelable")
}
}
}
| 0
|
Kotlin
|
0
| 0
|
5f30a80de82f1c162ea666e6260fdd78fb299137
| 1,155
|
Diary
|
Apache License 2.0
|
src/main/kotlin/days/Day6.kt
|
tpepper0408
| 317,612,203
| false
| null |
package days
class Day6 : Day<Int>(6) {
override fun partOne(): Int {
return inputList.joinToString("\n")
.split("\n\n")
.map {
it.replace("\n", "")
.toCharArray()
.toSet()
.count()
}
.reduce { acc, i -> acc + i }
}
override fun partTwo(): Int {
return inputList.joinToString("\n")
.split("\n\n")
.map {
val rows = it.split("\n")
var foundCharacters = rows[0].toCharArray().toSet()
for (otherRow in 1..rows.indices.last) {
foundCharacters = HashSet(foundCharacters.intersect(rows[otherRow].toCharArray().toSet()))
}
foundCharacters
}
.map { it.count() }
.reduce { acc, i -> acc + i }
}
}
| 0
|
Kotlin
|
0
| 0
|
67c65a9e93e85eeb56b57d2588844e43241d9319
| 905
|
aoc2020
|
Creative Commons Zero v1.0 Universal
|
tmp/arrays/youTrackTests/9918.kt
|
DaniilStepanov
| 228,623,440
| false
|
{"Git Config": 1, "Gradle": 6, "Text": 3, "INI": 5, "Shell": 2, "Ignore List": 3, "Batchfile": 2, "Markdown": 2, "Kotlin": 15942, "JavaScript": 4, "ANTLR": 2, "XML": 12, "Java": 4}
|
// Original bug: KT-10175
open class Base
class Derived : Base() {
fun bar() {}
}
fun foo(b: Base?) {
if (b is Derived?) {
// b: smart cast to <?>
b?.bar()
}
}
| 1
| null |
1
| 1
|
602285ec60b01eee473dcb0b08ce497b1c254983
| 190
|
bbfgradle
|
Apache License 2.0
|
.teamcity/settings.kts
|
devcon5io
| 171,551,382
| false
|
{"Java": 97459, "Kotlin": 6373}
|
import jetbrains.buildServer.configs.kotlin.v2018_2.BuildType
import jetbrains.buildServer.configs.kotlin.v2018_2.DslContext
import jetbrains.buildServer.configs.kotlin.v2018_2.buildSteps.maven
import jetbrains.buildServer.configs.kotlin.v2018_2.project
import jetbrains.buildServer.configs.kotlin.v2018_2.triggers.vcs
import jetbrains.buildServer.configs.kotlin.v2018_2.version
/*
The settings script is an entry point for defining a TeamCity
project hierarchy. The script should contain a single call to the
project() function with a Project instance or an init function as
an argument.
VcsRoots, BuildTypes, Templates, and subprojects can be
registered inside the project using the vcsRoot(), buildType(),
template(), and subProject() methods respectively.
To debug settings scripts in command-line, run the
mvnDebug org.jetbrains.teamcity:teamcity-configs-maven-plugin:generate
command and attach your debugger to the port 8000.
To debug in IntelliJ Idea, open the 'Maven Projects' tool window (View
-> Tool Windows -> Maven Projects), find the generate task node
(Plugins -> teamcity-configs -> teamcity-configs:generate), the
'Debug' option is available in the context menu for the task.
*/
version = "2018.2"
project {
buildType(Build)
}
object Build : BuildType({
name = "Build vertx-patterns"
artifactRules = "**/target/*.jar"
params {
//disable tool options, otherwise java 8 jvm flags would be applied to jdk 11, which do not work
param("env.JAVA_TOOL_OPTIONS", "")
param("env.JAVA_HOME", "/usr/lib/jvm/jdk-11/")
}
vcs {
root(DslContext.settingsRoot)
}
steps {
maven {
goals = "clean install -T 1C -e"
mavenVersion = defaultProvidedVersion()
jdkHome = "/usr/lib/jvm/jdk-11/"
//enable graal compiler
jvmArgs = "-XX:+UnlockExperimentalVMOptions -XX:+EnableJVMCI -XX:+UseJVMCICompiler"
param("org.jfrog.artifactory.selectedDeployableServer.defaultModuleVersionConfiguration", "GLOBAL")
param("org.jfrog.artifactory.selectedDeployableServer.deployArtifacts", "true")
param("org.jfrog.artifactory.selectedDeployableServer.envVarsExcludePatterns", "*password*,*secret*")
param("org.jfrog.artifactory.selectedDeployableServer.publishBuildInfo", "true")
param("org.jfrog.artifactory.selectedDeployableServer.targetRepo", "libs-release-local")
param("org.jfrog.artifactory.selectedDeployableServer.targetSnapshotRepo", "libs-snapshot-local")
param("org.jfrog.artifactory.selectedDeployableServer.urlId", "0")
param("org.jfrog.artifactory.selectedDeployableServer.gitReleaseBranchNamePrefix", "REL-BRANCH-")
param("org.jfrog.artifactory.selectedDeployableServer.enableReleaseManagement", "true")
param("org.jfrog.artifactory.selectedDeployableServer.vcsTagsBaseUrlOrName", "v")
param("org.jfrog.artifactory.selectedDeployableServer.deployIncludePatterns", "*.jar *.pom")
}
step {
type = "sonar-plugin"
param("sonarProjectBinaries", "target/classes")
param("sonarProjectModules", "vertx-actors,vertx-caching,vertx-codec,vertx-services")
param("sonarProjectSources", "src/main/java")
param("sonarProjectTests", "src/test/java")
param("sonarServer", "7ba1e2c4-b91a-4c29-bd83-7948b20ea366")
param("target.jdk.home", "%env.JDK_18_x64%")
}
}
triggers {
vcs {
perCheckinTriggering = true
}
}
})
| 1
| null |
1
| 1
|
78dedb5f4c861a1667eadbc0dd00418b83b3ccca
| 3,622
|
vertx-patterns
|
Apache License 2.0
|
next/kmp/browser/src/commonMain/kotlin/org/dweb_browser/browser/desk/DesktopWindowController.kt
|
BioforestChain
| 594,577,896
| false
|
{"Kotlin": 2620314, "TypeScript": 690065, "Swift": 350138, "Vue": 143774, "SCSS": 39030, "Objective-C": 17350, "Shell": 11193, "HTML": 10444, "JavaScript": 3998, "CSS": 818}
|
package org.dweb_browser.browser.desk
import org.dweb_browser.sys.window.core.WindowController
import org.dweb_browser.sys.window.core.WindowState
import org.dweb_browser.sys.window.core.WindowsManager
class DesktopWindowController(
manager: DesktopWindowsManager,
state: WindowState,
) : WindowController(state, manager) {
override val manager get() = _manager as DesktopWindowsManager
override val viewBox = manager.viewBox
override val lifecycleScope get() = viewBox.lifecycleScope
override fun upsetManager(manager: WindowsManager<*>?) {
when (val deskManager = manager) {
is DesktopWindowsManager -> {
super.upsetManager(deskManager)
state.observable.coroutineScope =
deskManager.viewController.lifecycleScope
}
else -> throw Exception("invalid type $manager should be DesktopWindowsManager")
}
}
}
| 47
|
Kotlin
|
4
| 11
|
b9b39e294badbb02eeb3a3a6d1851fd5105bd09f
| 872
|
dweb_browser
|
MIT License
|
app/src/main/java/com/marvastsi/mediaplayer/MediaFragment.kt
|
marvastsi
| 565,363,373
| false
| null |
package com.marvastsi.mediaplayer
import android.net.Uri
import android.os.Bundle
import android.support.v4.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.AdapterView
import android.widget.ArrayAdapter
import android.widget.MediaController
import androidx.navigation.fragment.findNavController
import com.marvastsi.mediaplayer.databinding.FragmentVideoBinding
class MediaFragment : Fragment(), AdapterView.OnItemSelectedListener {
private lateinit var mediaController: MediaController
private var _binding: FragmentVideoBinding? = null
private val binding get() = _binding!!
private var mediaPath: String? = null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
println("onCreate()")
}
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View {
_binding = FragmentVideoBinding.inflate(inflater, container, false)
val uriString = mediaPath ?: getMediaPath("Video")
val uri = Uri.parse(uriString)
val mVideoView = binding.mediaView
val spinner = binding.filesSpinner
ArrayAdapter.createFromResource(
requireContext(),
R.array.media_array,
android.R.layout.simple_spinner_item
).also { adapter ->
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item)
spinner.adapter = adapter
}
spinner.onItemSelectedListener = this
mediaController = MediaController(activity)
mediaController.setAnchorView(mVideoView)
mVideoView.setMediaController(mediaController)
mVideoView.setVideoURI(uri)
mVideoView.requestFocus()
mVideoView.start()
mVideoView.setOnCompletionListener {
navigateBack()
}
return binding.root
}
private fun navigateBack() {
findNavController().navigate(R.id.action_VideoFragment_to_FirstFragment)
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
println("onViewCreated()")
}
override fun onDestroyView() {
super.onDestroyView()
_binding = null
}
override fun onItemSelected(parent: AdapterView<*>?, view: View?, position: Int, id: Long) {
val selectedItemText = parent?.getItemAtPosition(position)
if(position > 0)
mediaPath = getMediaPath(selectedItemText)
}
private fun getMediaPath(item: Any?): String {
// Should use position (index) instead itemText (value)
val packageName = javaClass.getPackage()?.name
return when (item) {
"Video" -> "android.resource://$packageName/${R.raw.video}"
"Song" -> "android.resource://$packageName/${R.raw.song}"
"YouTube" -> "https://www.youtube.com/watch?v=jxV_8zb_YD8"
else -> "android.resource://$packageName/${R.raw.video}"
}
}
override fun onNothingSelected(parent: AdapterView<*>?) {
TODO("Not yet implemented")
}
}
| 0
|
Kotlin
|
0
| 0
|
c935dc9d3fd6ac4f3e6f3344a5a4acc67ca3a762
| 3,227
|
media-player-android
|
MIT License
|
src/test/kotlin/ControllerTestExtensions.kt
|
paulmiddelkoop
| 456,872,687
| false
| null |
package se.pamisoft.theinvoice
import org.springframework.http.MediaType.APPLICATION_JSON
import org.springframework.test.web.servlet.ResultActionsDsl
fun ResultActionsDsl.thenJsonResultIs(jsonContent: String) {
andExpect {
status { isOk() }
content {
contentType(APPLICATION_JSON)
json(jsonContent, strict = true)
}
}
}
| 2
|
Kotlin
|
0
| 0
|
4e15d1e75e9db730dbf0d887a5b9618811e4827b
| 378
|
the-invoice
|
MIT License
|
src/test/kotlin/moe/irony/simplepc/monad_laws/TrampolineMonadTest.kt
|
kokoro-aya
| 398,263,839
| false
| null |
package moe.irony.simplepc.monad_laws
class TrampolineMonadTest {
// TODO: 21/08/2021 "Not yet completed"
}
| 0
|
Kotlin
|
0
| 0
|
3fc718f6c525b79ecd07b5f86264e5a18d5ee20d
| 112
|
NekoBinator
|
MIT License
|
lib/src/main/kotlin/com/monkopedia/konstructor/lib/ScriptServiceImpl.kt
|
Monkopedia
| 418,215,448
| false
| null |
/*
* Copyright 2022 <NAME>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.monkopedia.konstructor.lib
import com.monkopedia.hauler.Shipper
import com.monkopedia.hauler.attach
import com.monkopedia.kcsg.KcsgScript
import com.monkopedia.konstructor.lib.TargetStatus.NONE
import java.io.File
import kotlin.system.exitProcess
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.SupervisorJob
import kotlinx.coroutines.sync.Mutex
import kotlinx.coroutines.sync.withLock
import kotlinx.coroutines.withContext
class ScriptServiceImpl(private val script: KcsgScript, private val exec: KcsgScript.() -> Unit) : ScriptService {
private var shipper: Shipper? = null
private val serviceCache = mutableMapOf<String, BuildServiceImpl>()
private val statusCache = mutableMapOf<String, TargetStatus>()
private val job = SupervisorJob()
private val scope = CoroutineScope(job + Dispatchers.IO)
private val dispatchThread = BlockableThread("SingleThreadScript").also { dispatcher ->
job.invokeOnCompletion {
dispatcher.close()
}
}
private val lock = Mutex()
private lateinit var outputDirectory: File
private var isInitialized = false
override suspend fun initializeHostServices(hostService: HostService) {
script.host = KcsgRemoteHostImpl(hostService, dispatchThread)
}
override suspend fun initialize(config: ScriptConfiguration) {
if (isInitialized) {
throw IllegalArgumentException("Already initialized")
}
outputDirectory = File(config.outputDirectory)
if (!outputDirectory.exists() && !outputDirectory.mkdirs()) {
throw IllegalArgumentException("Can't write to ${outputDirectory.absolutePath}")
}
shipper?.requestDockPickup()?.attach(scope, config.loggingDeliveryRates.asDeliveryRates)
lock.withLock {
script.exec()
}
isInitialized = true
if (config.eagerExport) {
for (target in listTargets(onlyExports = true)) {
buildTarget(target.name)
}
}
}
override suspend fun setShipper(shipper: Shipper) {
this.shipper = shipper
}
override suspend fun listTargets(onlyExports: Boolean): List<ScriptTargetInfo> {
val targets = withContext(dispatchThread.dispatcher) {
if (onlyExports) script.exports() else script.targets()
}
lock.withLock {
return targets.map { target ->
ScriptTargetInfo(
target,
serviceCache[target]?.getStatus() ?: statusCache[target] ?: NONE
)
}
}
}
override suspend fun buildTarget(name: String): BuildService {
lock.withLock {
return serviceCache.getOrPut(name) {
BuildServiceImpl(
scope,
dispatchThread.dispatcher,
script,
name,
outputDirectory
) { status ->
lock.withLock {
statusCache[name] = status
serviceCache.remove(name)
}
}
}
}
}
override suspend fun closeService(u: Unit) {
try {
job.cancel()
} finally {
exitProcess(0)
}
}
override suspend fun close() = closeService()
}
| 0
|
Kotlin
|
0
| 0
|
597c1c7b193734451ad9846e9010d98e1de3f1d5
| 4,043
|
Konstructor
|
Apache License 2.0
|
compiler/fir/analysis-tests/testData/resolve/implicitTypeInFakeOverride.kt
|
JetBrains
| 3,432,266
| false
| null |
fun <K> extract(x: Out<K>) = x.get()
class Out<out T>(val x: T) {
fun get() = x
}
fun test(out: Out<String>) {
<!DEBUG_INFO_EXPRESSION_TYPE("kotlin.String")!>extract(out)<!>
}
| 181
| null |
5748
| 49,172
|
33eb9cef3d146062c103f9853d772f0a1da0450e
| 186
|
kotlin
|
Apache License 2.0
|
shared-elements/src/main/java/com/mxalbert/sharedelements/MaterialArcMotion.kt
|
chachako
| 342,547,917
| false
|
{"Kotlin": 141013}
|
/*
* Copyright 2021 The Android Open Source Project
* Copyright 2021 RinOrz (凛)
*
* 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.
* Github home page: https://github.com/RinOrz
*/
package com.mxalbert.sharedelements
import androidx.compose.ui.geometry.Offset
class MaterialArcMotion : KeyframeBasedMotion() {
override fun getKeyframes(start: Offset, end: Offset): Pair<FloatArray, LongArray> =
QuadraticBezier.approximate(
start,
if (start.y > end.y) Offset(end.x, start.y) else Offset(start.x, end.y),
end,
0.5f
)
}
val MaterialArcMotionFactory: PathMotionFactory = { MaterialArcMotion() }
| 1
|
Kotlin
|
1
| 8
|
566e88f637b73fd85ddd93039c1f666890fd5c1b
| 1,141
|
compose-kitty
|
Apache License 2.0
|
src/main/kotlin/com/theonlytails/ketex/anchors.kt
|
TheOnlyTails
| 481,508,642
| false
|
{"Kotlin": 28647}
|
package com.theonlytails.ketex
/**
* Append a start anchor (`^`) to the regex.
*
* > Matches the beginning of the string, or the beginning of a line if the multiline flag (`m`) is enabled.
* > This matches a position, not a character.
*/
context(KetexBuilder)
@KetexMarker
val start by token("^")
/**
* Append an ending anchor (`$`) to the regex.
*
* > Matches the end of the string, or the end of a line if the multiline flag (`m`) is enabled.
* > This matches a position, not a character.
*/
context(KetexBuilder)
@KetexMarker
val end by token("$")
/**
* Append a word boundary anchor (`\b`) to the regex.
*
* > Matches a word boundary position between a word character and non-word character or position (start / end of string).
* > See the word character class ([\w][word]) for more info.
*/
context(KetexBuilder)
@KetexMarker
val wordBoundary by token("\\b")
| 0
|
Kotlin
|
1
| 26
|
e9a12f3d6d7f233ad2a2e39347447fbeff2be6b5
| 882
|
ketex
|
MIT License
|
compiler/tests-common-new/tests/org/jetbrains/kotlin/test/frontend/fir/FirOutputArtifact.kt
|
JetBrains
| 3,432,266
| false
|
{"Kotlin": 79571273, "Java": 6776465, "Swift": 4063829, "C": 2609744, "C++": 1957654, "Objective-C++": 175279, "JavaScript": 130754, "Python": 59855, "Shell": 34920, "Objective-C": 21463, "Lex": 21452, "Batchfile": 11382, "CSS": 11368, "Ruby": 10470, "Dockerfile": 9907, "Groovy": 7092, "EJS": 5241, "CMake": 4473, "HTML": 2699, "Puppet": 1698, "FreeMarker": 1393, "Roff": 725, "Scala": 80}
|
/*
* Copyright 2010-2020 JetBrains s.r.o. and Kotlin Programming Language contributors.
* Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file.
*/
package org.jetbrains.kotlin.test.frontend.fir
import org.jetbrains.kotlin.fir.AbstractFirAnalyzerFacade
import org.jetbrains.kotlin.fir.FirSession
import org.jetbrains.kotlin.fir.declarations.FirFile
import org.jetbrains.kotlin.test.model.FrontendKinds
import org.jetbrains.kotlin.test.model.ResultingArtifact
import org.jetbrains.kotlin.test.model.TestFile
import org.jetbrains.kotlin.test.model.TestModule
// Only MPP contains several parts inside FirOutputArtifact, other projects only contain single part.
data class FirOutputPartForDependsOnModule(
val module: TestModule,
val session: FirSession,
val firAnalyzerFacade: AbstractFirAnalyzerFacade,
val firFiles: Map<TestFile, FirFile>
)
abstract class FirOutputArtifact(val partsForDependsOnModules: List<FirOutputPartForDependsOnModule>) : ResultingArtifact.FrontendOutput<FirOutputArtifact>() {
val allFirFiles: Map<TestFile, FirFile> = partsForDependsOnModules.fold(emptyMap()) { acc, part -> acc + part.firFiles }
override val kind: FrontendKinds.FIR
get() = FrontendKinds.FIR
val mainFirFiles: Map<TestFile, FirFile> by lazy { allFirFiles.filterKeys { !it.isAdditional } }
}
class FirOutputArtifactImpl(parts: List<FirOutputPartForDependsOnModule>) : FirOutputArtifact(parts)
| 181
|
Kotlin
|
5748
| 49,172
|
33eb9cef3d146062c103f9853d772f0a1da0450e
| 1,488
|
kotlin
|
Apache License 2.0
|
build-logic/src/main/kotlin/com/squareup/convention/AppConvention.kt
|
square
| 554,372,622
| false
| null |
package com.squareup.convention
import com.squareup.convention.publishing.Publishing
import org.gradle.api.Plugin
import org.gradle.api.Project
/**
* This plugin is applied to our JVM app projects.
* ```
* plugins {
* id("com.squareup.app")
* }
* ```
*/
@Suppress("unused")
class AppConvention : Plugin<Project> {
override fun apply(target: Project): Unit = target.run {
with(pluginManager) {
apply(BaseConvention::class.java)
apply("application")
apply("com.github.johnrengelman.shadow")
}
Publishing.setup(this)
}
}
| 24
|
Kotlin
|
6
| 91
|
b4d6f06bfde50680ad694769312de583e8fe0444
| 565
|
gradle-dependencies-sorter
|
Apache License 2.0
|
build-logic/src/main/kotlin/com/squareup/convention/AppConvention.kt
|
square
| 554,372,622
| false
| null |
package com.squareup.convention
import com.squareup.convention.publishing.Publishing
import org.gradle.api.Plugin
import org.gradle.api.Project
/**
* This plugin is applied to our JVM app projects.
* ```
* plugins {
* id("com.squareup.app")
* }
* ```
*/
@Suppress("unused")
class AppConvention : Plugin<Project> {
override fun apply(target: Project): Unit = target.run {
with(pluginManager) {
apply(BaseConvention::class.java)
apply("application")
apply("com.github.johnrengelman.shadow")
}
Publishing.setup(this)
}
}
| 24
|
Kotlin
|
6
| 91
|
b4d6f06bfde50680ad694769312de583e8fe0444
| 565
|
gradle-dependencies-sorter
|
Apache License 2.0
|
ui/src/main/java/io/snabble/sdk/ui/payment/externalbilling/ui/widgets/SubjectAlertDialog.kt
|
snabble
| 124,525,499
| false
| null |
package io.snabble.sdk.ui.payment.externalbilling.ui.widgets
import android.app.Activity
import android.app.Dialog
import android.content.Context
import android.graphics.Color
import android.graphics.drawable.ColorDrawable
import android.os.Bundle
import android.text.InputFilter
import android.view.ViewGroup.LayoutParams
import android.view.inputmethod.EditorInfo
import android.view.inputmethod.InputMethodManager
import android.widget.EditText
import androidx.core.widget.addTextChangedListener
import com.google.android.material.button.MaterialButton
import com.google.android.material.textfield.TextInputLayout
import io.snabble.sdk.ui.R
class SubjectAlertDialog(context: Context, private val maxSubjectLength: Int? = null) : Dialog(context) {
private var subjectMessageClickListener: SubjectMessageClickListener? = null
private var skipClick: SubjectClickListener? = null
private var onCancelClick: SubjectClickListener? = null
override fun onCreate(savedInstanceState: Bundle?) {
setContentView(R.layout.snabble_subject_alert_dialog)
window?.setLayout(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT)
window?.setBackgroundDrawable(ColorDrawable(Color.TRANSPARENT))
val input = findViewById<TextInputLayout>(R.id.text_input_subject)
val editTextField = findViewById<EditText>(R.id.text_edit_subject)
val add = findViewById<MaterialButton>(R.id.subject_add)
val skip = findViewById<MaterialButton>(R.id.subject_skip)
editTextField.multilineDone {
val inputMethodManager: InputMethodManager =
context.getSystemService(Activity.INPUT_METHOD_SERVICE) as InputMethodManager
inputMethodManager.hideSoftInputFromWindow(input.windowToken, 0)
}
editTextField.addTextChangedListener {
add.isEnabled = it?.isNotEmpty() == true
}
editTextField.filters = arrayOf(InputFilter.LengthFilter(maxSubjectLength ?: 150))
add.setOnClickListener {
subjectMessageClickListener?.onClick(input.editText?.text.toString())
dismiss()
}
skip.setOnClickListener {
skipClick?.onClick()
dismiss()
}
}
private fun EditText.multilineIme(action: Int) {
imeOptions = action
inputType = EditorInfo.TYPE_TEXT_FLAG_MULTI_LINE
setHorizontallyScrolling(false)
maxLines = EDIT_TEXT_MAX_LINES
}
private fun EditText.multilineDone(callback: (() -> Unit)? = null) {
val action = EditorInfo.IME_ACTION_DONE
multilineIme(action)
setOnEditorActionListener { _, actionId, _ ->
if (action == actionId) {
callback?.invoke()
}
false
}
}
override fun dismiss() {
super.dismiss()
onCancelClick?.onClick()
}
fun setOnCanceledListener(onClick: SubjectClickListener) = apply {
onCancelClick = onClick
}
fun addMessageClickListener(onClick: SubjectMessageClickListener): SubjectAlertDialog = apply {
subjectMessageClickListener = onClick
}
fun addSkipClickListener(click: SubjectClickListener): SubjectAlertDialog = apply {
skipClick = click
}
companion object {
const val EDIT_TEXT_MAX_LINES = 5
}
}
fun interface SubjectMessageClickListener {
fun onClick(message: String)
}
fun interface SubjectClickListener {
fun onClick()
}
| 2
| null |
1
| 6
|
8fc301be7512714e127eb12566a905b59e2eed9d
| 3,481
|
Android-SDK
|
MIT License
|
app/src/main/java/org/ageage/eggplant/feed/FeedFragment.kt
|
jageishi
| 175,018,359
| false
| null |
package org.ageage.eggplant.feed
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.Fragment
import kotlinx.android.synthetic.main.fragment_feed.*
import org.ageage.eggplant.R
import org.ageage.eggplant.common.enums.Category
import org.ageage.eggplant.common.enums.Mode
private const val MODE = "mode"
class FeedFragment : Fragment() {
private lateinit var mode: Mode
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
arguments?.let {
mode = it.getSerializable(MODE) as Mode
}
}
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_feed, container, false)
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
val adapter = FeedCategoryPagerAdapter(childFragmentManager, context)
Category.values().forEach { adapter.addContent(mode, it) }
categoryViewPager.adapter = adapter
categoryTab.setupWithViewPager(categoryViewPager)
}
companion object {
@JvmStatic
fun newInstance(mode: Mode) =
FeedFragment().also { f ->
f.arguments = Bundle().also { b ->
b.putSerializable(MODE, mode)
}
}
}
}
| 17
|
Kotlin
|
0
| 3
|
612f4d5d14863795ab4bd5acf52a34d00b6bb0ba
| 1,574
|
Eggplant
|
Apache License 2.0
|
app/src/main/kotlin/com/matthewemes/things/kotlinthing/MainActivity.kt
|
memes
| 106,347,873
| false
| null |
package com.matthewemes.things.kotlinthing
import android.support.v7.app.AppCompatActivity
import android.os.Bundle
import android.os.Handler
import com.google.android.things.pio.Gpio
import com.google.android.things.pio.PeripheralManagerService
import timber.log.Timber
import kotlinx.android.synthetic.main.activity_main.*
class MainActivity : AppCompatActivity() {
companion object {
val GPIO_PIN_NAME = "BCM6"
val BLINK_INTERVAL_MS = 1000L
}
private val handler = Handler()
private var gpio: Gpio? = null
private var blinker: Runnable? = null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
welcomeText.text = "Using Kotlin android extensions!"
val service = PeripheralManagerService()
try {
gpio = service.openGpio(GPIO_PIN_NAME)
gpio?.setDirection(Gpio.DIRECTION_OUT_INITIALLY_LOW)
if (blinker == null) {
blinker = Runnable {
if (gpio != null) {
try {
gpio!!.value = !gpio!!.value
handler.postDelayed(blinker, BLINK_INTERVAL_MS)
} catch (t: Throwable) {
Timber.e(t, "Caught an exception in blinker runnable")
}
}
}
}
handler.post(blinker)
} catch (t: Throwable) {
Timber.e(t, "Caught exception setting up GPIO")
}
Timber.d("onCreate: exit")
}
override fun onDestroy() {
Timber.d("onDestroy: enter")
super.onDestroy()
handler.removeCallbacks(blinker)
try {
gpio?.value = false
gpio?.close()
gpio = null
} catch (t: Throwable) {
Timber.e(t, "Caught an exception shutting off GPIO")
}
Timber.d("onDestroy: exit")
}
}
| 0
|
Kotlin
|
0
| 0
|
428795b6d599c900f8ffa70ac42f90737763b158
| 2,027
|
kotlinthing
|
MIT License
|
idea/src/org/jetbrains/kotlin/idea/KotlinPluginUpdater.kt
|
mikiyakitahara
| 49,639,828
| false
| null |
/*
* Copyright 2010-2015 JetBrains s.r.o.
*
* 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.jetbrains.kotlin.idea
import com.intellij.ide.plugins.IdeaPluginDescriptor
import com.intellij.ide.plugins.PluginManager
import com.intellij.ide.plugins.PluginManagerMain
import com.intellij.ide.plugins.RepositoryHelper
import com.intellij.ide.util.PropertiesComponent
import com.intellij.notification.NotificationDisplayType
import com.intellij.notification.NotificationGroup
import com.intellij.notification.NotificationType
import com.intellij.openapi.Disposable
import com.intellij.openapi.application.ApplicationInfo
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.components.ServiceManager
import com.intellij.openapi.diagnostic.Logger
import com.intellij.openapi.extensions.PluginId
import com.intellij.openapi.progress.ProgressIndicator
import com.intellij.openapi.progress.ProgressManager
import com.intellij.openapi.progress.Task
import com.intellij.openapi.updateSettings.impl.PluginDownloader
import com.intellij.openapi.updateSettings.impl.UpdateChecker
import com.intellij.openapi.util.JDOMUtil
import com.intellij.openapi.util.SystemInfo
import com.intellij.openapi.vfs.CharsetToolkit
import com.intellij.util.Alarm
import com.intellij.util.io.HttpRequests
import com.intellij.util.text.VersionComparatorUtil
import java.net.URLEncoder
import java.util.concurrent.TimeUnit
class KotlinPluginUpdater(val propertiesComponent: PropertiesComponent) : Disposable {
private val INITIAL_UPDATE_DELAY = 5000L
private var updateDelay = INITIAL_UPDATE_DELAY
private val alarm = Alarm(Alarm.ThreadToUse.POOLED_THREAD, this)
@Volatile private var checkQueued = false
private val notificationGroup = NotificationGroup("Kotlin plugin updates", NotificationDisplayType.STICKY_BALLOON, true)
fun kotlinFileEdited() {
val lastUpdateTime = java.lang.Long.parseLong(propertiesComponent.getValue(PROPERTY_NAME, "0"))
if (lastUpdateTime == 0L || System.currentTimeMillis() - lastUpdateTime > TimeUnit.DAYS.toMillis(1)) {
queueUpdateCheck()
}
}
private fun queueUpdateCheck() {
if (ApplicationManager.getApplication().isUnitTestMode) return
ApplicationManager.getApplication().assertIsDispatchThread()
if (!checkQueued) {
checkQueued = true
alarm.addRequest({ updateCheck() }, updateDelay)
updateDelay *= 2 // exponential backoff
}
}
private fun updateCheck() {
try {
checkQueued = false
var (mainRepoUpdateSuccess, latestVersionInRepository) = getPluginVersionFromMainRepository()
var descriptorToInstall: IdeaPluginDescriptor? = null
var hostToInstallFrom: String? = null
for (host in RepositoryHelper.getPluginHosts().filterNotNull()) {
val plugins = try {
RepositoryHelper.loadPlugins(host, null)
}
catch(e: Exception) {
LOG.info("Checking custom plugin reposityory $host failed", e)
continue
}
val kotlinPlugin = plugins.find { it.pluginId.toString() == "org.jetbrains.kotlin" }
if (kotlinPlugin != null && VersionComparatorUtil.compare(kotlinPlugin.version, latestVersionInRepository) > 0) {
latestVersionInRepository = kotlinPlugin.version
descriptorToInstall = kotlinPlugin
hostToInstallFrom = host
}
}
if (mainRepoUpdateSuccess || latestVersionInRepository != null) {
recordSuccessfulUpdateCheck()
if (latestVersionInRepository != null && VersionComparatorUtil.compare(latestVersionInRepository, JetPluginUtil.getPluginVersion()) > 0) {
ApplicationManager.getApplication().invokeLater {
notifyPluginUpdateAvailable(latestVersionInRepository!!, descriptorToInstall, hostToInstallFrom)
}
}
}
else {
ApplicationManager.getApplication().invokeLater { queueUpdateCheck() }
}
}
catch(e: Exception) {
LOG.info("Kotlin plugin update check failed", e)
checkQueued = false
queueUpdateCheck()
}
}
data class RepositoryCheckResult(val success: Boolean, val newVersion: String?)
fun getPluginVersionFromMainRepository(): RepositoryCheckResult {
val buildNumber = ApplicationInfo.getInstance().build.asString()
val pluginVersion = JetPluginUtil.getPluginVersion()
val os = URLEncoder.encode(SystemInfo.OS_NAME + " " + SystemInfo.OS_VERSION, CharsetToolkit.UTF8)
val uid = UpdateChecker.getInstallationUID(propertiesComponent)
val url = "https://plugins.jetbrains.com/plugins/list?pluginId=6954&build=$buildNumber&pluginVersion=$pluginVersion&os=$os&uuid=a$uid"
val responseDoc = HttpRequests.request(url).connect {
JDOMUtil.load(it.inputStream)
}
if (responseDoc.name != "plugin-repository") {
LOG.info("Unexpected plugin repository response: ${JDOMUtil.writeElement(responseDoc, "\n")}")
return RepositoryCheckResult(false, null)
}
if (responseDoc.children.isEmpty()) {
// No plugin version compatible with current IDEA build; don't retry updates
return RepositoryCheckResult(true, null)
}
val version = responseDoc.getChild("category")?.getChild("idea-plugin")?.getChild("version")?.text
if (version == null) {
LOG.info("Couldn't find plugin version in repository response: ${JDOMUtil.writeElement(responseDoc, "\n")}")
return RepositoryCheckResult(false, null)
}
return RepositoryCheckResult(true, version)
}
private fun recordSuccessfulUpdateCheck() {
propertiesComponent.setValue(PROPERTY_NAME, System.currentTimeMillis().toString())
updateDelay = INITIAL_UPDATE_DELAY
}
private fun notifyPluginUpdateAvailable(newVersion: String,
descriptorToInstall: IdeaPluginDescriptor?,
hostToInstallFrom: String?) {
val notification = notificationGroup.createNotification(
"Kotlin",
"A new version $newVersion of the Kotlin plugin is available. <b><a href=\"#\">Install</a></b>",
NotificationType.INFORMATION) { notification, event ->
val descriptor = descriptorToInstall ?: PluginManager.getPlugin(PluginId.getId("org.jetbrains.kotlin"))
if (descriptor != null) {
notification.expire()
val pluginDownloader = PluginDownloader.createDownloader(descriptor, hostToInstallFrom, null)
ProgressManager.getInstance().run(object : Task.Backgroundable(null, "Downloading plugins", true) {
override fun run(indicator: ProgressIndicator) {
if (pluginDownloader.prepareToInstall(indicator)) {
val pluginDescriptor = pluginDownloader.getDescriptor()
if (pluginDescriptor != null) {
pluginDownloader.install()
ApplicationManager.getApplication().invokeLater {
notification.expire()
PluginManagerMain.notifyPluginsUpdated(null)
}
}
}
}
override fun onCancel() {
notifyPluginUpdateAvailable(newVersion, descriptorToInstall, hostToInstallFrom)
}
})
}
}
notification.notify(null)
}
override fun dispose() {
}
companion object {
private val PROPERTY_NAME = "kotlin.lastUpdateCheck"
private val LOG = Logger.getInstance(KotlinPluginUpdater::class.java)
fun getInstance(): KotlinPluginUpdater = ServiceManager.getService(KotlinPluginUpdater::class.java)
}
}
| 1
| null |
1
| 1
|
ff00bde607d605c4eba2d98fbc9e99af932accb6
| 8,844
|
kotlin
|
Apache License 2.0
|
kmp-nativecoroutines-compiler/src/test/kotlin/com/rickclephas/kmp/nativecoroutines/compiler/GenerateTests.kt
|
rickclephas
| 374,341,212
| false
|
{"Kotlin": 199302, "Swift": 40082, "Ruby": 2852, "Java": 2203}
|
package com.rickclephas.kmp.nativecoroutines.compiler
import com.rickclephas.kmp.nativecoroutines.compiler.runners.AbstractDiagnosticsTest
import org.jetbrains.kotlin.generators.generateTestGroupSuiteWithJUnit5
fun main() {
generateTestGroupSuiteWithJUnit5 {
testGroup(testDataRoot = "src/testData", testsRoot = "src/test/generated") {
testClass<AbstractDiagnosticsTest> {
model("diagnostics")
}
}
}
}
| 15
|
Kotlin
|
29
| 846
|
77dca3f4b23b377caa65a9f24285eaf6e09a3bcf
| 468
|
KMP-NativeCoroutines
|
MIT License
|
src/test/kotlin/org/rustSlowTests/lang/resolve/CustomTargetCfgResolveTest.kt
|
intellij-rust
| 42,619,487
| false
|
{"Gradle Kotlin DSL": 2, "Java Properties": 5, "Markdown": 11, "TOML": 19, "Shell": 2, "Text": 124, "Ignore List": 1, "Batchfile": 1, "EditorConfig": 1, "XML": 140, "Kotlin": 2284, "INI": 3, "ANTLR": 1, "Rust": 362, "YAML": 131, "RenderScript": 1, "JSON": 6, "HTML": 198, "SVG": 136, "JFlex": 1, "Java": 1, "Python": 37}
|
/*
* Use of this source code is governed by the MIT license that can be
* found in the LICENSE file.
*/
package org.rustSlowTests.lang.resolve
import org.rust.MinRustcVersion
import org.rust.cargo.RsWithToolchainTestBase
import org.rust.cargo.toolchain.tools.rustc
import org.rust.cargo.util.parseSemVer
import org.rust.lang.core.psi.RsPath
class CustomTargetCfgResolveTest : RsWithToolchainTestBase() {
@MinRustcVersion("1.52.0")
fun `test custom build-in compiler target`() {
buildProject {
toml("Cargo.toml", """
[package]
name = "foo"
version = "0.1.0"
authors = []
""")
dir(".cargo") {
toml("config", """
[build]
target = "wasm32-unknown-unknown"
""")
}
dir("src") {
rust("main.rs", """
#[cfg(not(target_arch = "wasm32"))]
mod disabled;
#[cfg(target_arch = "wasm32")]
mod enabled;
#[cfg(not(target_arch = "wasm32"))]
pub use disabled::function_under_cfg;
#[cfg(target_arch = "wasm32")]
pub use enabled::function_under_cfg;
fn main() {
function_under_cfg();
//^
}
""")
rust("disabled.rs", """
pub fn function_under_cfg() {}
""")
rust("enabled.rs", """
pub fn function_under_cfg() {}
""")
}
}.checkReferenceIsResolved<RsPath>("src/main.rs", toFile = ".../src/enabled.rs")
}
@MinRustcVersion("1.52.0")
fun `test custom json target`() {
buildProject {
toml("Cargo.toml", """
[package]
name = "foo"
version = "0.1.0"
authors = []
""")
dir(".cargo") {
toml("config", """
[build]
target = "custom-target.json"
""")
}
file("custom-target.json", """
{
"llvm-target": "aarch64-unknown-none",
"data-layout": "e-m:e-i64:64-f80:128-n8:16:32:64-S128",
"arch": "aarch64",
"target-endian": "little",
"target-pointer-width": "64",
"target-c-int-width": "32",
"os": "none",
"executables": true,
"linker-flavor": "ld.lld",
"linker": "rust-lld",
"panic-strategy": "abort",
"disable-redzone": true,
"features": "-mmx,-sse,+soft-float"
}
""")
dir("src") {
rust("main.rs", """
#[cfg(not(target_arch = "aarch64"))]
mod disabled;
#[cfg(target_arch = "aarch64")]
mod enabled;
#[cfg(not(target_arch = "aarch64"))]
pub use disabled::function_under_cfg;
#[cfg(target_arch = "aarch64")]
pub use enabled::function_under_cfg;
fn main() {
function_under_cfg();
//^
}
""")
rust("disabled.rs", """
pub fn function_under_cfg() {}
""")
rust("enabled.rs", """
pub fn function_under_cfg() {}
""")
}
}.checkReferenceIsResolved<RsPath>("src/main.rs", toFile = ".../src/enabled.rs")
}
// BACKCOMPAT: Rust 1.51. Drop it
// Checks that our integration doesn't fail for Rust below 1.52
fun `test custom compiler target with rust below 1_52`() {
val rustcVersion = rustupFixture.toolchain!!.rustc().queryVersion() ?: return
if (rustcVersion.semver > "1.51.0".parseSemVer()) return
buildProject {
toml("Cargo.toml", """
[package]
name = "foo"
version = "0.1.0"
authors = []
""")
dir(".cargo") {
toml("config", """
[build]
target = "wasm32-unknown-unknown"
""")
}
dir("src") {
rust("main.rs", """
#[cfg(not(target_arch = "wasm32"))]
mod disabled;
#[cfg(target_arch = "wasm32")]
mod enabled;
#[cfg(not(target_arch = "wasm32"))]
pub use disabled::function_under_cfg;
#[cfg(target_arch = "wasm32")]
pub use enabled::function_under_cfg;
fn main() {
function_under_cfg();
//^
}
""")
rust("disabled.rs", """
pub fn function_under_cfg() {}
""")
rust("enabled.rs", """
pub fn function_under_cfg() {}
""")
}
}.checkReferenceIsResolved<RsPath>("src/main.rs", toFile = ".../src/disabled.rs")
}
}
| 1,841
|
Kotlin
|
380
| 4,528
|
c6657c02bb62075bf7b7ceb84d000f93dda34dc1
| 5,565
|
intellij-rust
|
MIT License
|
jvm/jvm-analysis-java-tests/testSrc/com/intellij/jvm/analysis/JavaJvmAnalysisTestUtil.kt
|
ingokegel
| 72,937,917
| true
| null |
package com.intellij.jvm.analysis
object JavaJvmAnalysisTestUtil {
const val TEST_DATA_PROJECT_RELATIVE_BASE_PATH = "${JvmAnalysisTestUtil.MODULE_PATH}/jvm-analysis-java-tests/testData"
}
| 1
| null |
1
| 2
|
b07eabd319ad5b591373d63c8f502761c2b2dfe8
| 190
|
intellij-community
|
Apache License 2.0
|
app/src/main/java/college/wyk/app/model/Stackable.kt
|
WYKCode
| 81,462,363
| false
| null |
package college.wyk.app.model
interface Stackable
| 1
|
Kotlin
|
1
| 7
|
4205693ca71267b2d149380588bb94a334104435
| 50
|
WYK-Android
|
MIT License
|
src/main/kotlin/com/github/vhromada/catalog/domain/CheatData.kt
|
vhromada
| 23,755,847
| false
| null |
package com.github.vhromada.catalog.domain
import com.github.vhromada.common.entity.Audit
import javax.persistence.Entity
import javax.persistence.GeneratedValue
import javax.persistence.GenerationType
import javax.persistence.Id
import javax.persistence.SequenceGenerator
import javax.persistence.Table
/**
* A class represents cheat's data.
*
* @author <NAME>
*/
@Entity
@Table(name = "cheat_data")
@Suppress("JpaDataSourceORMInspection")
data class CheatData(
/**
* ID
*/
@Id
@SequenceGenerator(name = "cheat_data_generator", sequenceName = "cheat_data_sq", allocationSize = 1)
@GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "cheat_data_generator")
var id: Int?,
/**
* Action
*/
var action: String,
/**
* Description
*/
var description: String
) : Audit() {
/**
* Merges cheat's data.
*
* @param cheatData cheat's data
*/
fun merge(cheatData: CheatData) {
action = cheatData.action
description = cheatData.description
}
}
| 0
|
Kotlin
|
0
| 0
|
43511beaf8b774e415b87307ea9bbd3c857db163
| 1,066
|
Catalog
|
MIT License
|
src/main/kotlin/_0053_MaximumSubarray.kt
|
ryandyoon
| 664,493,186
| false
| null |
import kotlin.math.max
// https://leetcode.com/problems/maximum-subarray
fun maxSubArray(nums: IntArray): Int {
var maxSum = nums[0]
var currentSum = maxSum
for (index in 1..nums.lastIndex) {
currentSum = max(currentSum + nums[index], nums[index])
maxSum = max(maxSum, currentSum)
}
return maxSum
}
| 0
|
Kotlin
|
0
| 0
|
7f75078ddeb22983b2521d8ac80f5973f58fd123
| 336
|
leetcode-kotlin
|
MIT License
|
plugins/groovy/groovy-psi/src/org/jetbrains/plugins/groovy/lang/psi/impl/auxiliary/modifiers/modifiers.kt
|
androidports
| 115,100,208
| false
| null |
/*
* Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
*/
@file:JvmName("GrModifierListUtil")
package org.jetbrains.plugins.groovy.lang.psi.impl.auxiliary.modifiers
import com.intellij.psi.JavaPsiFacade
import com.intellij.psi.PsiModifier
import org.jetbrains.annotations.NonNls
import org.jetbrains.plugins.groovy.config.GroovyConfigUtils
import org.jetbrains.plugins.groovy.lang.psi.api.auxiliary.modifiers.GrModifier.GrModifierConstant
import org.jetbrains.plugins.groovy.lang.psi.api.auxiliary.modifiers.GrModifierFlags
import org.jetbrains.plugins.groovy.lang.psi.api.auxiliary.modifiers.GrModifierList
import org.jetbrains.plugins.groovy.lang.psi.api.auxiliary.modifiers.annotation.GrAnnotation
import org.jetbrains.plugins.groovy.lang.psi.api.auxiliary.modifiers.annotation.GrAnnotationArrayInitializer
import org.jetbrains.plugins.groovy.lang.psi.api.statements.GrVariableDeclaration
import org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.GrReferenceExpression
import org.jetbrains.plugins.groovy.lang.psi.api.statements.typedef.GrEnumTypeDefinition
import org.jetbrains.plugins.groovy.lang.psi.api.statements.typedef.GrTypeDefinition
import org.jetbrains.plugins.groovy.lang.psi.api.statements.typedef.GrTypeDefinitionBody
import org.jetbrains.plugins.groovy.lang.psi.api.statements.typedef.members.GrEnumConstant
import org.jetbrains.plugins.groovy.lang.psi.api.statements.typedef.members.GrMethod
import org.jetbrains.plugins.groovy.lang.psi.impl.PsiImplUtil
import org.jetbrains.plugins.groovy.lang.psi.impl.auxiliary.modifiers.GrModifierListImpl.NAME_TO_MODIFIER_FLAG_MAP
import org.jetbrains.plugins.groovy.lang.psi.impl.findDeclaredDetachedValue
import org.jetbrains.plugins.groovy.lang.psi.util.GrTraitUtil.isInterface
private val visibilityModifiers = setOf(PsiModifier.PUBLIC, PsiModifier.PROTECTED, PsiModifier.PACKAGE_LOCAL, PsiModifier.PRIVATE)
private val explicitVisibilityModifiersMask = GrModifierFlags.PUBLIC_MASK or GrModifierFlags.PRIVATE_MASK or GrModifierFlags.PROTECTED_MASK
private val packageScopeAnno = "groovy.transform.PackageScope"
private val packageScopeTarget = "groovy.transform.PackageScopeTarget"
fun Int.hasMaskModifier(@GrModifierConstant @NonNls name: String): Boolean {
return and(NAME_TO_MODIFIER_FLAG_MAP[name]) != 0
}
internal fun hasExplicitVisibilityModifiers(modifierList: GrModifierList): Boolean {
return explicitVisibilityModifiersMask and modifierList.modifierFlags != 0
}
internal fun hasExplicitModifier(modifierList: GrModifierList, @GrModifierConstant @NonNls name: String): Boolean {
return modifierList.modifierFlags.hasMaskModifier(name)
}
internal fun hasModifierProperty(modifierList: GrModifierList, @GrModifierConstant @NonNls name: String): Boolean {
return hasExplicitModifier(modifierList, name) || hasImplicitModifier(modifierList, name)
}
private fun hasImplicitModifier(modifierList: GrModifierList, @GrModifierConstant @NonNls name: String): Boolean {
return when (name) {
PsiModifier.ABSTRACT -> modifierList.isAbstract()
PsiModifier.FINAL -> modifierList.isFinal()
PsiModifier.STATIC -> modifierList.isStatic()
else -> name in visibilityModifiers && name == modifierList.getImplicitVisiblity()
}
}
private fun GrModifierList.isAbstract(): Boolean {
val owner = parent
return when (owner) {
is GrMethod -> owner.isAbsractMethod()
is GrTypeDefinition -> owner.isAbstractClass()
else -> false
}
}
private fun GrMethod.isAbsractMethod(): Boolean = containingClass?.isInterface ?: false
private fun GrTypeDefinition.isAbstractClass(): Boolean {
if (isEnum) {
if (GroovyConfigUtils.getInstance().isVersionAtLeast(this, GroovyConfigUtils.GROOVY2_0)) {
return codeMethods.any { it.modifierList.hasExplicitModifier(PsiModifier.ABSTRACT) }
}
}
return isInterface
}
private fun GrModifierList.isFinal(): Boolean {
val owner = parent
return when (owner) {
is GrTypeDefinition -> owner.isFinalClass()
is GrVariableDeclaration -> owner.isFinalField(this)
else -> false
}
}
private fun GrTypeDefinition.isFinalClass(): Boolean {
return isEnum && codeFields.none { it is GrEnumConstant && it.initializingClass != null }
}
private fun GrVariableDeclaration.isFinalField(modifierList: GrModifierList): Boolean {
val containingClass = containingClass
return isInterface(containingClass)
|| !modifierList.hasExplicitVisibilityModifiers()
&& (containingClass?.modifierList?.let(PsiImplUtil::hasImmutableAnnotation) ?: false)
}
private fun GrModifierList.isStatic(): Boolean {
val owner = parent
val containingClass = when (owner) {
is GrTypeDefinition -> owner.containingClass
is GrVariableDeclaration -> owner.containingClass
else -> null
}
return containingClass != null && (owner is GrEnumTypeDefinition || isInterface(containingClass))
}
private fun GrModifierList.getImplicitVisiblity(): String? {
if (hasExplicitVisibilityModifiers(this)) return null
val owner = parent
when (owner) {
is GrTypeDefinition -> return if (hasPackageScope(owner, "CLASS")) PsiModifier.PACKAGE_LOCAL else PsiModifier.PUBLIC
is GrMethod -> {
val containingClass = owner.containingClass as? GrTypeDefinition ?: return null
if (isInterface(containingClass)) return PsiModifier.PUBLIC
val targetName = if (owner.isConstructor) "CONSTRUCTORS" else "METHODS"
return if (hasPackageScope(containingClass, targetName)) PsiModifier.PACKAGE_LOCAL else PsiModifier.PUBLIC
}
is GrVariableDeclaration -> {
val containingClass = owner.containingClass ?: return null
if (isInterface(containingClass)) return PsiModifier.PUBLIC
return if (hasPackageScope(containingClass, "FIELDS")) PsiModifier.PACKAGE_LOCAL else PsiModifier.PRIVATE
}
else -> return null
}
}
private fun GrModifierList.hasPackageScope(clazz: GrTypeDefinition?, targetName: String): Boolean {
if (hasOwnEmptyPackageScopeAnnotation()) return true
val annotation = clazz?.modifierList?.findAnnotation(packageScopeAnno) as? GrAnnotation ?: return false
val value = annotation.findDeclaredDetachedValue(null) ?: return false // annotation without value
val scopeTargetEnum = JavaPsiFacade.getInstance(project).findClass(packageScopeTarget, resolveScope) ?: return false
val scopeTarget = scopeTargetEnum.findFieldByName(targetName, false) ?: return false
val resolved = when (value) {
is GrReferenceExpression -> value.resolve()?.let { listOf(it) } ?: emptyList()
is GrAnnotationArrayInitializer -> value.initializers.mapNotNull {
(it as? GrReferenceExpression)?.resolve()
}
else -> emptyList()
}
return scopeTarget in resolved
}
private fun GrModifierList.hasOwnEmptyPackageScopeAnnotation(): Boolean {
val annotation = findAnnotation(packageScopeAnno) ?: return false
val value = annotation.findDeclaredDetachedValue(null) ?: return true
return value is GrAnnotationArrayInitializer && value.initializers.isEmpty()
}
private val GrVariableDeclaration.containingClass get() = (parent as? GrTypeDefinitionBody)?.parent as? GrTypeDefinition
| 6
| null |
1
| 4
|
6e4f7135c5843ed93c15a9782f29e4400df8b068
| 7,202
|
intellij-community
|
Apache License 2.0
|
app/src/main/java/com/example/orangetrainingcenterandroid/domain/quizz/model/VoteDomainModel.kt
|
zwayten
| 662,213,656
| false
| null |
package com.example.orangetrainingcenterandroid.domain.quizz.model
data class VoteDomainModel(
val score: Int,
)
| 0
|
Kotlin
|
0
| 0
|
545afc0b9e4f17cc08cd2bc462af8f3fd71a6356
| 118
|
OTC-Android
|
MIT License
|
app/src/main/java/com/harr1424/listmaker/BaseApplication.kt
|
harr1424
| 467,743,859
| false
| null |
package com.harr1424.listmaker
import android.app.Application
import com.harr1424.listmaker.data.AppDatabase
/**
* An application class that inherits from [Application], allows for the creation of a singleton
* instance of the AppDatabase
*/
class BaseApplication : Application() {
val database: AppDatabase by lazy { AppDatabase.getDatabase(this) }
}
| 0
|
Kotlin
|
0
| 4
|
1e3a8ba126e3b64f331891d98eb5032895ee48d9
| 360
|
ListMaker-Android
|
MIT License
|
common/src/commonMain/kotlin/com/artemchep/keyguard/feature/home/vault/add/AddScreen.kt
|
AChep
| 669,697,660
| false
|
{"Kotlin": 5020574, "HTML": 45314}
|
@file:OptIn(ExperimentalMaterial3Api::class)
package com.artemchep.keyguard.feature.home.vault.add
import androidx.compose.animation.Crossfade
import androidx.compose.foundation.BorderStroke
import androidx.compose.foundation.LocalIndication
import androidx.compose.foundation.background
import androidx.compose.foundation.clickable
import androidx.compose.foundation.interaction.MutableInteractionSource
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.ColumnScope
import androidx.compose.foundation.layout.ExperimentalLayoutApi
import androidx.compose.foundation.layout.FlowRow
import androidx.compose.foundation.layout.PaddingValues
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.RowScope
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.heightIn
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.layout.widthIn
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.foundation.text.KeyboardActionScope
import androidx.compose.foundation.text.KeyboardActions
import androidx.compose.foundation.text.KeyboardOptions
import androidx.compose.foundation.verticalScroll
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.outlined.Add
import androidx.compose.material.icons.outlined.ArrowDropDown
import androidx.compose.material.icons.outlined.Clear
import androidx.compose.material.icons.outlined.CloudDone
import androidx.compose.material.icons.outlined.FileUpload
import androidx.compose.material.icons.outlined.Folder
import androidx.compose.material.icons.outlined.Key
import androidx.compose.material.icons.outlined.Password
import androidx.compose.material.icons.outlined.Save
import androidx.compose.material3.Checkbox
import androidx.compose.material3.DropdownMenu
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.LocalContentColor
import androidx.compose.material3.LocalTextStyle
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Surface
import androidx.compose.material3.Text
import androidx.compose.material3.TextButton
import androidx.compose.material3.TopAppBarDefaults
import androidx.compose.runtime.*
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.alpha
import androidx.compose.ui.draw.clip
import androidx.compose.ui.focus.FocusDirection
import androidx.compose.ui.focus.FocusRequester
import androidx.compose.ui.focus.focusRequester
import androidx.compose.ui.focus.onFocusChanged
import androidx.compose.ui.graphics.graphicsLayer
import androidx.compose.ui.graphics.vector.ImageVector
import androidx.compose.ui.input.nestedscroll.nestedScroll
import androidx.compose.ui.platform.LocalDensity
import androidx.compose.ui.platform.LocalFocusManager
import androidx.compose.ui.semantics.Role
import androidx.compose.ui.text.SpanStyle
import androidx.compose.ui.text.font.FontStyle
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.input.ImeAction
import androidx.compose.ui.text.input.KeyboardType
import androidx.compose.ui.text.input.PasswordVisualTransformation
import androidx.compose.ui.text.input.VisualTransformation
import androidx.compose.ui.unit.dp
import arrow.core.partially1
import com.artemchep.keyguard.common.model.Loadable
import com.artemchep.keyguard.common.model.UsernameVariationIcon
import com.artemchep.keyguard.common.model.fold
import com.artemchep.keyguard.common.model.getOrNull
import com.artemchep.keyguard.common.model.titleH
import com.artemchep.keyguard.common.service.logging.LogRepository
import com.artemchep.keyguard.feature.auth.common.TextFieldModel2
import com.artemchep.keyguard.feature.auth.common.VisibilityState
import com.artemchep.keyguard.feature.auth.common.VisibilityToggle
import com.artemchep.keyguard.feature.filepicker.FilePickerEffect
import com.artemchep.keyguard.feature.home.vault.component.FlatItemTextContent2
import com.artemchep.keyguard.feature.home.vault.component.Section
import com.artemchep.keyguard.feature.home.vault.component.VaultViewTotpBadge2
import com.artemchep.keyguard.feature.navigation.LocalNavigationController
import com.artemchep.keyguard.feature.navigation.NavigationIcon
import com.artemchep.keyguard.feature.navigation.NavigationIntent
import com.artemchep.keyguard.feature.qr.ScanQrButton
import com.artemchep.keyguard.res.Res
import com.artemchep.keyguard.ui.AutofillButton
import com.artemchep.keyguard.ui.BiFlatContainer
import com.artemchep.keyguard.ui.BiFlatTextField
import com.artemchep.keyguard.ui.BiFlatTextFieldLabel
import com.artemchep.keyguard.ui.BiFlatValueHeightMin
import com.artemchep.keyguard.ui.DefaultEmphasisAlpha
import com.artemchep.keyguard.ui.DefaultFab
import com.artemchep.keyguard.ui.DisabledEmphasisAlpha
import com.artemchep.keyguard.ui.DropdownMenuItemFlat
import com.artemchep.keyguard.ui.DropdownMinWidth
import com.artemchep.keyguard.ui.DropdownScopeImpl
import com.artemchep.keyguard.ui.EmailFlatTextField
import com.artemchep.keyguard.ui.ExpandedIfNotEmpty
import com.artemchep.keyguard.ui.ExpandedIfNotEmptyForRow
import com.artemchep.keyguard.ui.FabState
import com.artemchep.keyguard.ui.FlatDropdown
import com.artemchep.keyguard.ui.FlatItem
import com.artemchep.keyguard.ui.FlatItemAction
import com.artemchep.keyguard.ui.FlatItemLayout
import com.artemchep.keyguard.ui.FlatItemTextContent
import com.artemchep.keyguard.ui.FlatSimpleNote
import com.artemchep.keyguard.ui.FlatTextField
import com.artemchep.keyguard.ui.FlatTextFieldBadge
import com.artemchep.keyguard.ui.LeMOdelBottomSheet
import com.artemchep.keyguard.ui.MediumEmphasisAlpha
import com.artemchep.keyguard.ui.OptionsButton
import com.artemchep.keyguard.ui.PasswordFlatTextField
import com.artemchep.keyguard.ui.PasswordPwnedBadge
import com.artemchep.keyguard.ui.PasswordStrengthBadge
import com.artemchep.keyguard.ui.ScaffoldColumn
import com.artemchep.keyguard.ui.SimpleNote
import com.artemchep.keyguard.ui.UrlFlatTextField
import com.artemchep.keyguard.ui.button.FavouriteToggleButton
import com.artemchep.keyguard.ui.icons.IconBox
import com.artemchep.keyguard.ui.icons.KeyguardAttachment
import com.artemchep.keyguard.ui.icons.KeyguardCollection
import com.artemchep.keyguard.ui.icons.KeyguardOrganization
import com.artemchep.keyguard.ui.icons.KeyguardTwoFa
import com.artemchep.keyguard.ui.icons.KeyguardWebsite
import com.artemchep.keyguard.ui.icons.icon
import com.artemchep.keyguard.ui.markdown.MarkdownText
import com.artemchep.keyguard.ui.shimmer.shimmer
import com.artemchep.keyguard.ui.skeleton.SkeletonText
import com.artemchep.keyguard.ui.skeleton.SkeletonTextField
import com.artemchep.keyguard.ui.text.annotatedResource
import com.artemchep.keyguard.ui.theme.Dimens
import com.artemchep.keyguard.ui.theme.combineAlpha
import com.artemchep.keyguard.ui.theme.isDark
import com.artemchep.keyguard.ui.theme.monoFontFamily
import com.artemchep.keyguard.ui.toolbar.LargeToolbar
import com.artemchep.keyguard.ui.util.DividerColor
import com.artemchep.keyguard.ui.util.HorizontalDivider
import com.artemchep.keyguard.ui.util.VerticalDivider
import dev.icerock.moko.resources.compose.stringResource
import kotlinx.coroutines.flow.launchIn
import kotlinx.coroutines.flow.map
import kotlinx.coroutines.flow.onEach
import org.kodein.di.compose.rememberInstance
@Composable
fun AddScreen(
args: AddRoute.Args,
) {
val loadableState = produceAddScreenState(
args = args,
)
val state = loadableState.getOrNull()
if (state != null) {
FilePickerEffect(
flow = state.sideEffects.filePickerIntentFlow,
)
}
val addScreenScope = remember {
val addScreenBehavior = args.behavior
AddScreenScope(
initialFocusRequested = !addScreenBehavior.autoShowKeyboard,
)
}
AddScreenContent(
addScreenScope = addScreenScope,
loadableState = loadableState,
)
}
@OptIn(ExperimentalMaterial3Api::class, ExperimentalLayoutApi::class, ExperimentalLayoutApi::class)
@Composable
private fun AddScreenContent(
addScreenScope: AddScreenScope,
loadableState: Loadable<AddState>,
) {
val scrollBehavior = TopAppBarDefaults.exitUntilCollapsedScrollBehavior()
ScaffoldColumn(
modifier = Modifier
.nestedScroll(scrollBehavior.nestedScrollConnection),
topAppBarScrollBehavior = scrollBehavior,
topBar = {
LargeToolbar(
title = {
val title = loadableState.getOrNull()?.title
if (title != null) {
Text(title)
} else {
SkeletonText(
modifier = Modifier
.fillMaxWidth(0.4f),
)
}
},
navigationIcon = {
NavigationIcon()
},
actions = {
val fav = loadableState.getOrNull()?.favourite
val checked = fav?.checked == true
val onChange = fav?.onChange
FavouriteToggleButton(
modifier = Modifier
.then(
loadableState.fold(
ifLoading = {
Modifier
.shimmer()
},
ifOk = {
Modifier
},
),
),
favorite = checked,
onChange = onChange,
)
val actions = loadableState.getOrNull()?.actions.orEmpty()
OptionsButton(
actions = actions,
)
},
scrollBehavior = scrollBehavior,
)
},
floatingActionState = run {
val fabOnClick = loadableState.getOrNull()?.onSave
val fabState = if (fabOnClick != null) {
FabState(
onClick = fabOnClick,
model = null,
)
} else {
null
}
rememberUpdatedState(newValue = fabState)
},
floatingActionButton = {
DefaultFab(
icon = {
Icon(
imageVector = Icons.Outlined.Save,
contentDescription = null,
)
},
text = {
Text(
text = stringResource(Res.strings.save),
)
},
)
},
columnVerticalArrangement = Arrangement.spacedBy(8.dp),
) {
populateItems(
addScreenScope = addScreenScope,
loadableState = loadableState,
)
}
}
private class AddScreenScope(
initialFocusRequested: Boolean = false,
) {
val initialFocusRequestedState = mutableStateOf(initialFocusRequested)
@Composable
fun initialFocusRequesterEffect(): FocusRequester {
val focusRequester = remember { FocusRequester() }
// Auto focus the text field
// on launch.
LaunchedEffect(focusRequester) {
var initialFocusRequested by initialFocusRequestedState
if (!initialFocusRequested) {
focusRequester.requestFocus()
// do not request it the second time
initialFocusRequested = true
}
}
return focusRequester
}
}
@Composable
private fun ColumnScope.populateItems(
addScreenScope: AddScreenScope,
loadableState: Loadable<AddState>,
) = loadableState.fold(
ifLoading = {
populateItemsSkeleton(
addScreenScope = addScreenScope,
)
},
ifOk = { state ->
populateItemsContent(
addScreenScope = addScreenScope,
state = state,
)
},
)
@Composable
private fun ColumnScope.populateItemsSkeleton(
addScreenScope: AddScreenScope,
) {
Column(
modifier = Modifier
.fillMaxWidth()
.padding(
horizontal = 8.dp,
vertical = 2.dp,
)
.padding(vertical = 8.dp),
verticalArrangement = Arrangement.spacedBy(8.dp, Alignment.CenterVertically),
) {
Row(
modifier = Modifier
.fillMaxWidth()
.padding(end = 8.dp),
horizontalArrangement = Arrangement.spacedBy(8.dp),
) {
ToolbarContentItemErrSkeleton(
modifier = Modifier
.weight(1.5f),
fraction = 0.5f,
)
Spacer(modifier = Modifier.width(8.dp))
ToolbarContentItemErrSkeleton(
modifier = Modifier
.weight(1f)
.padding(end = 8.dp),
fraction = 0.75f,
)
}
ToolbarContentItemErrSkeleton(
modifier = Modifier
.padding(end = 8.dp),
fraction = 0.35f,
)
}
Section()
Spacer(Modifier.height(24.dp))
SkeletonTextField(
modifier = Modifier
.fillMaxWidth()
.padding(horizontal = Dimens.horizontalPadding),
)
SkeletonTextField(
modifier = Modifier
.fillMaxWidth()
.padding(horizontal = Dimens.horizontalPadding),
)
SkeletonText(
modifier = Modifier
.fillMaxWidth(0.75f)
.padding(horizontal = Dimens.horizontalPadding),
style = MaterialTheme.typography.labelMedium,
)
SkeletonText(
modifier = Modifier
.fillMaxWidth(0.4f)
.padding(horizontal = Dimens.horizontalPadding),
style = MaterialTheme.typography.labelMedium,
)
}
@Composable
private fun ColumnScope.populateItemsContent(
addScreenScope: AddScreenScope,
state: AddState,
) {
ToolbarContent(
modifier = Modifier,
account = state.ownership.account,
organization = state.ownership.organization,
collection = state.ownership.collection,
folder = state.ownership.folder,
onClick = state.ownership.onClick,
)
Section()
if (state.merge != null) {
ExpandedIfNotEmpty(
valueOrNull = state.merge.note,
) { note ->
FlatSimpleNote(
modifier = Modifier,
note = note,
)
}
FlatItemLayout(
leading = {
Checkbox(
checked = state.merge.removeOrigin.checked,
onCheckedChange = null,
)
},
content = {
Text(
text = stringResource(Res.strings.additem_merge_remove_origin_ciphers_title),
)
},
onClick = {
val newValue = !state.merge.removeOrigin.checked
state.merge.removeOrigin.onChange?.invoke(newValue)
},
)
Section()
}
Spacer(Modifier.height(24.dp))
val logRepository by rememberInstance<LogRepository>()
remember(state) {
logRepository.post("Foo3", "rendered state ${state.items.size} items")
}
state.items.forEach {
key(it.id) {
AnyField(
modifier = Modifier,
addScreenScope = addScreenScope,
item = it,
)
}
}
}
@Composable
private fun AnyField(
modifier: Modifier = Modifier,
addScreenScope: AddScreenScope,
item: AddStateItem,
) {
when (item) {
is AddStateItem.Title -> {
val localState by item.state.flow.collectAsState()
NameTextField(
modifier = modifier,
addScreenScope = addScreenScope,
field = localState,
)
}
is AddStateItem.Username -> {
val localState by item.state.flow.collectAsState()
UsernameTextField(modifier, localState)
}
is AddStateItem.Password -> {
val localState by item.state.flow.collectAsState()
PasswordTextField(modifier, localState)
}
is AddStateItem.Totp -> {
val localState by item.state.flow.collectAsState()
TotpTextField(modifier, localState)
}
is AddStateItem.Url -> {
UrlTextField(modifier, item)
}
is AddStateItem.Attachment -> {
AttachmentTextField(modifier, item)
}
is AddStateItem.Passkey -> {
PasskeyField(modifier, item)
}
is AddStateItem.Note -> {
val localState by item.state.flow.collectAsState()
NoteTextField(modifier, localState, markdown = item.markdown)
}
is AddStateItem.Text -> {
val localState by item.state.flow.collectAsState()
TextTextField(modifier, localState)
}
is AddStateItem.DateMonthYear -> {
DateMonthYearField(
modifier = modifier,
item = item,
)
}
is AddStateItem.Switch -> {
SwitchField(
modifier = modifier,
item = item,
)
}
is AddStateItem.Suggestion -> {
SuggestionItem(
modifier = modifier,
item = item,
)
}
is AddStateItem.Enum -> {
val localState by item.state.flow.collectAsState()
EnumItem(
modifier = modifier,
icon = item.icon,
label = item.label,
title = localState.value,
dropdown = localState.dropdown,
)
}
is AddStateItem.Field -> {
Box(
modifier = modifier,
) {
val logRepository by rememberInstance<LogRepository>()
remember(item) {
logRepository.post("Foo3", "im rendering a field! ${item.id}")
}
val localState = remember {
mutableStateOf<AddStateItem.Field.State?>(null)
}
LaunchedEffect(item.state.flow) {
item.state.flow
.map { a ->
a.withOptions(a.options + item.options)
}
.onEach {
localState.value = it
logRepository.post("Foo3", "im on emit a field! ${it}")
}
.launchIn(this)
}
// val localState = remember(item.state.flow) {
// item.state.flow
// .map { a ->
// a.withOptions(a.options + item.options)
// }
// .onEach {
// logRepository.post("Foo3", "im on emit a field! ${it}")
// }
// }.collectAsState(null)
when (val l = localState.value) {
is AddStateItem.Field.State.Text -> {
FieldTextField(Modifier, l)
}
is AddStateItem.Field.State.Switch -> {
FieldSwitchField(Modifier, l)
}
is AddStateItem.Field.State.LinkedId -> {
FieldLinkedIdField(Modifier, l)
}
null -> {
// Do nothing.
}
}
}
}
is AddStateItem.Section -> {
SectionItem(modifier, item.text)
}
// Modifiers
is AddStateItem.Add -> {
Column(
modifier = modifier,
) {
val dropdownShownState = remember { mutableStateOf(false) }
if (item.actions.isEmpty()) {
dropdownShownState.value = false
}
// Inject the dropdown popup to the bottom of the
// content.
val onDismissRequest = remember(dropdownShownState) {
// lambda
{
dropdownShownState.value = false
}
}
val contentColor = MaterialTheme.colorScheme.primary
FlatItem(
leading = {
Icon(Icons.Outlined.Add, null, tint = contentColor)
},
title = {
Text(
text = item.text,
color = contentColor,
)
DropdownMenu(
modifier = Modifier
.widthIn(min = DropdownMinWidth),
expanded = dropdownShownState.value,
onDismissRequest = onDismissRequest,
) {
val scope = DropdownScopeImpl(this, onDismissRequest = onDismissRequest)
with(scope) {
item.actions.forEachIndexed { index, action ->
DropdownMenuItemFlat(
action = action,
)
}
}
}
},
onClick = {
if (item.actions.size == 1) {
item.actions.first()
.onClick?.invoke()
} else {
dropdownShownState.value = true
}
},
)
}
}
}
}
@Composable
private fun NameTextField(
modifier: Modifier = Modifier,
addScreenScope: AddScreenScope,
field: TextFieldModel2,
) {
val focusManager = LocalFocusManager.current
val keyboardOnNext: KeyboardActionScope.() -> Unit = {
focusManager.moveFocus(FocusDirection.Down)
}
val focusRequester = addScreenScope.initialFocusRequesterEffect()
FlatTextField(
modifier = modifier
.padding(horizontal = Dimens.horizontalPadding),
fieldModifier = Modifier
.focusRequester(focusRequester),
label = stringResource(Res.strings.generic_name),
singleLine = true,
value = field,
keyboardOptions = KeyboardOptions(
imeAction = ImeAction.Next,
),
keyboardActions = KeyboardActions(
onNext = keyboardOnNext,
),
)
}
@Composable
private fun UsernameTextField(
modifier: Modifier = Modifier,
field: AddStateItem.Username.State,
) {
EmailFlatTextField(
modifier = modifier
.padding(horizontal = Dimens.horizontalPadding),
label = stringResource(Res.strings.username),
value = field.value,
leading = {
Crossfade(
targetState = field.type,
) { variation ->
UsernameVariationIcon(
usernameVariation = variation,
)
}
},
trailing = {
AutofillButton(
key = "username",
username = true,
onValueChange = {
field.value.onChange?.invoke(it)
},
)
},
)
}
@OptIn(ExperimentalLayoutApi::class)
@Composable
private fun PasswordTextField(
modifier: Modifier = Modifier,
field: TextFieldModel2,
) = Column {
PasswordFlatTextField(
modifier = modifier
.padding(horizontal = Dimens.horizontalPadding),
value = field,
leading = {
IconBox(
main = Icons.Outlined.Password,
)
},
trailing = {
AutofillButton(
key = "password",
password = true,
onValueChange = {
field.onChange?.invoke(it)
},
)
},
content = {
ExpandedIfNotEmpty(
valueOrNull = Unit.takeIf { field.state.value.isNotEmpty() && field.error == null },
) {
FlowRow(
modifier = Modifier
.fillMaxWidth()
.padding(
top = 8.dp,
bottom = 8.dp,
),
verticalArrangement = Arrangement.spacedBy(8.dp),
horizontalArrangement = Arrangement.spacedBy(8.dp),
) {
PasswordStrengthBadge(
password = field.state.value,
)
PasswordPwnedBadge(
password = field.state.value,
)
}
}
},
)
Text(
modifier = Modifier
.padding(horizontal = Dimens.horizontalPadding)
.padding(
top = Dimens.topPaddingCaption,
bottom = Dimens.topPaddingCaption,
),
style = MaterialTheme.typography.bodyMedium,
text = stringResource(Res.strings.generator_password_note, 16),
color = LocalContentColor.current
.combineAlpha(alpha = MediumEmphasisAlpha),
)
}
@Composable
private fun TotpTextField(
modifier: Modifier = Modifier,
state: AddStateItem.Totp.State,
) {
FlatTextField(
modifier = modifier
.padding(horizontal = Dimens.horizontalPadding),
label = stringResource(Res.strings.one_time_password_authenticator_key),
value = state.value,
textStyle = LocalTextStyle.current.copy(
fontFamily = monoFontFamily,
),
singleLine = true,
maxLines = 1,
trailing = {
ScanQrButton(
onValueChange = state.value.onChange,
)
},
leading = {
IconBox(
main = Icons.Outlined.KeyguardTwoFa,
)
},
)
ExpandedIfNotEmpty(
modifier = Modifier
.fillMaxWidth(),
valueOrNull = state.totpToken,
) { totpToken ->
Box {
VaultViewTotpBadge2(
modifier = Modifier
.padding(top = 8.dp)
.padding(start = 16.dp),
copyText = state.copyText,
totpToken = totpToken,
)
}
}
}
@Composable
private fun NoteTextField(
modifier: Modifier = Modifier,
field: TextFieldModel2,
markdown: Boolean,
) = Column(
modifier = modifier,
) {
var isAutofillWindowShowing by remember {
mutableStateOf(false)
}
if (!markdown) {
isAutofillWindowShowing = false
}
FlatTextField(
modifier = Modifier
.padding(horizontal = Dimens.horizontalPadding),
label = stringResource(Res.strings.note),
value = field,
content = if (markdown) {
// composable
{
ExpandedIfNotEmpty(
Unit.takeIf { field.text.isNotEmpty() },
) {
TextButton(
onClick = {
isAutofillWindowShowing = true
},
) {
Text(
text = stringResource(Res.strings.additem_markdown_render_preview),
)
}
}
}
} else {
null
},
// TODO: Long note moves a lot when you focus then field, because
// the clear button suddenly appears. We might move the button
// to the footer or something to keep the functionality.
clearButton = false,
)
if (markdown) {
val description = annotatedResource(
Res.strings.additem_markdown_note,
stringResource(Res.strings.additem_markdown_note_italic)
.let { "*$it*" } to SpanStyle(
fontStyle = FontStyle.Italic,
),
stringResource(Res.strings.additem_markdown_note_bold)
.let { "**$it**" } to SpanStyle(
fontWeight = FontWeight.Bold,
),
)
Row(
modifier = Modifier
.padding(horizontal = Dimens.horizontalPadding)
.padding(top = Dimens.topPaddingCaption),
) {
val navigationController = LocalNavigationController.current
Text(
modifier = Modifier
.weight(1f),
text = description,
style = MaterialTheme.typography.bodyMedium,
color = LocalContentColor.current.combineAlpha(alpha = MediumEmphasisAlpha),
)
Spacer(
modifier = Modifier
.width(16.dp),
)
TextButton(
onClick = {
val intent = NavigationIntent.NavigateToBrowser(
url = "https://www.markdownguide.org/basic-syntax/",
)
navigationController.queue(intent)
},
) {
Text(
text = stringResource(Res.strings.learn_more),
)
}
}
}
// Inject the dropdown popup to the bottom of the
// content.
val onDismissRequest = {
isAutofillWindowShowing = false
}
LeMOdelBottomSheet(
visible = isAutofillWindowShowing,
onDismissRequest = onDismissRequest,
) { contentPadding ->
Column(
modifier = Modifier
.verticalScroll(rememberScrollState())
.padding(contentPadding),
) {
Text(
modifier = Modifier
.padding(
horizontal = 16.dp,
vertical = 8.dp,
),
text = "Markdown",
style = MaterialTheme.typography.titleLarge,
)
MarkdownText(
modifier = Modifier
.padding(
horizontal = Dimens.horizontalPadding,
vertical = Dimens.verticalPadding,
),
markdown = field.text,
)
}
}
}
@Composable
private fun UrlTextField(
modifier: Modifier = Modifier,
item: AddStateItem.Url,
) {
val state by item.state.flow.collectAsState()
UrlFlatTextField(
modifier = modifier
.padding(horizontal = Dimens.horizontalPadding),
label = stringResource(Res.strings.uri),
value = state.text,
leading = {
IconBox(
main = Icons.Outlined.KeyguardWebsite,
)
},
trailing = {
val actions = remember(
state.options,
item.options,
) {
state.options + item.options
}
OptionsButton(
actions = actions,
)
},
content = {
ExpandedIfNotEmpty(
valueOrNull = state.matchTypeTitle,
) { matchType ->
FlatTextFieldBadge(
type = TextFieldModel2.Vl.Type.INFO,
text = matchType,
)
}
},
)
}
@Composable
private fun AttachmentTextField(
modifier: Modifier = Modifier,
item: AddStateItem.Attachment,
) {
val state by item.state.flow.collectAsState()
FlatTextField(
modifier = modifier
.padding(horizontal = Dimens.horizontalPadding),
label = "File",
placeholder = "File name",
value = state.name,
keyboardOptions = KeyboardOptions(
autoCorrect = false,
keyboardType = KeyboardType.Text,
),
singleLine = true,
maxLines = 1,
leading = {
Box {
Icon(
imageVector = Icons.Outlined.KeyguardAttachment,
contentDescription = null,
)
Row(
modifier = Modifier
.align(Alignment.BottomEnd)
.background(
MaterialTheme.colorScheme.tertiaryContainer,
MaterialTheme.shapes.extraSmall,
),
) {
if (state.synced) {
Icon(
modifier = Modifier
.size(16.dp)
.padding(1.dp),
imageVector = Icons.Outlined.CloudDone,
tint = MaterialTheme.colorScheme.onTertiaryContainer,
contentDescription = null,
)
}
if (!state.synced) {
Icon(
modifier = Modifier
.size(16.dp)
.padding(1.dp),
imageVector = Icons.Outlined.FileUpload,
tint = MaterialTheme.colorScheme.onTertiaryContainer,
contentDescription = null,
)
}
}
}
},
content = {
ExpandedIfNotEmpty(
valueOrNull = state.size,
) { fileSize ->
Column {
Spacer(Modifier.height(8.dp))
HorizontalDivider()
Spacer(Modifier.height(8.dp))
Text(
text = fileSize,
style = MaterialTheme.typography.labelSmall,
)
}
}
},
trailing = {
OptionsButton(
actions = item.options,
)
},
)
}
@Composable
private fun PasskeyField(
modifier: Modifier = Modifier,
item: AddStateItem.Passkey,
) {
val state by item.state.flow.collectAsState()
FlatItemLayout(
modifier = modifier,
leading = icon<RowScope>(Icons.Outlined.Key),
contentPadding = PaddingValues(
horizontal = 16.dp,
vertical = 8.dp,
),
content = {
val passkey = state.passkey
if (passkey != null) {
FlatItemTextContent(
title = {
Text(
text = passkey.userDisplayName.orEmpty(),
)
},
text = {
Text(
text = passkey.rpName,
)
},
)
} else {
FlatItemTextContent(
title = {
Text(
text = stringResource(Res.strings.passkey),
)
},
)
}
},
trailing = {
OptionsButton(
actions = item.options,
)
},
enabled = true,
)
}
@Composable
private fun TextTextField(
modifier: Modifier = Modifier,
state: AddStateItem.Text.State,
) {
FlatTextField(
modifier = modifier
.padding(horizontal = Dimens.horizontalPadding),
label = state.label,
value = state.value,
singleLine = state.singleLine,
keyboardOptions = state.keyboardOptions,
visualTransformation = state.visualTransformation,
)
}
@Composable
private fun FieldTextField(
modifier: Modifier = Modifier,
field: AddStateItem.Field.State.Text,
) {
val visibilityState = remember(field.hidden) {
VisibilityState(
isVisible = !field.hidden,
)
}
BiFlatTextField(
modifier = modifier
.padding(horizontal = Dimens.horizontalPadding),
label = field.label,
value = field.text,
valueVisualTransformation = if (visibilityState.isVisible || !field.hidden) {
VisualTransformation.None
} else {
PasswordVisualTransformation()
},
trailing = {
ExpandedIfNotEmptyForRow(
valueOrNull = Unit.takeIf { field.hidden },
) {
VisibilityToggle(
visibilityState = visibilityState,
)
}
OptionsButton(
actions = field.options,
)
},
)
}
@Composable
private fun FieldSwitchField(
modifier: Modifier = Modifier,
field: AddStateItem.Field.State.Switch,
) {
FlatTextField(
modifier = modifier
.padding(horizontal = Dimens.horizontalPadding),
value = field.label,
trailing = {
Checkbox(
checked = field.checked,
onCheckedChange = field.onCheckedChange,
)
OptionsButton(
actions = field.options,
)
},
)
}
@Composable
private fun FieldLinkedIdField(
modifier: Modifier = Modifier,
field: AddStateItem.Field.State.LinkedId,
) {
val label = field.label
val labelInteractionSource = remember { MutableInteractionSource() }
val valueInteractionSource = remember { MutableInteractionSource() }
val isError = remember(
label.error,
) {
derivedStateOf {
label.error != null
}
}
val hasFocusState = remember {
mutableStateOf(false)
}
val isEmpty = remember(
label.state,
) {
derivedStateOf {
label.state.value.isBlank()
}
}
val dropdownShownState = remember { mutableStateOf(false) }
if (field.actions.isEmpty()) {
dropdownShownState.value = false
}
// Inject the dropdown popup to the bottom of the
// content.
val onDismissRequest = remember(dropdownShownState) {
// lambda
{
dropdownShownState.value = false
}
}
BiFlatContainer(
modifier = modifier
.padding(horizontal = Dimens.horizontalPadding)
.onFocusChanged { state ->
hasFocusState.value = state.hasFocus
},
contentModifier = Modifier
.clickable(
indication = LocalIndication.current,
interactionSource = valueInteractionSource,
role = Role.Button,
) {
dropdownShownState.value = true
},
isError = isError,
isFocused = hasFocusState,
isEmpty = isEmpty,
label = {
BiFlatTextFieldLabel(
label = label,
interactionSource = labelInteractionSource,
)
},
content = {
Row {
val textColor =
if (field.value != null) {
LocalContentColor.current
} else {
LocalContentColor.current
.combineAlpha(MediumEmphasisAlpha)
}
Text(
modifier = Modifier
.heightIn(min = BiFlatValueHeightMin)
.weight(1f, fill = false),
text = (field.value?.titleH() ?: Res.strings.select_linked_type)
.let { stringResource(it) },
color = textColor,
)
Spacer(
modifier = Modifier
.width(4.dp),
)
Icon(
modifier = Modifier
.alpha(MediumEmphasisAlpha),
imageVector = Icons.Outlined.ArrowDropDown,
contentDescription = null,
)
}
DropdownMenu(
modifier = Modifier
.widthIn(min = DropdownMinWidth),
expanded = dropdownShownState.value,
onDismissRequest = onDismissRequest,
) {
val scope = DropdownScopeImpl(this, onDismissRequest = onDismissRequest)
with(scope) {
field.actions.forEachIndexed { index, action ->
DropdownMenuItemFlat(
action = action,
)
}
}
}
},
trailing = {
OptionsButton(
actions = field.options,
)
},
)
}
@Composable
private fun SwitchField(
modifier: Modifier = Modifier,
item: AddStateItem.Switch,
) {
val localState by item.state.flow.collectAsState()
FlatItem(
modifier = modifier,
leading = {
Checkbox(
checked = localState.checked,
enabled = localState.onChange != null,
onCheckedChange = null,
)
},
title = {
Text(
text = item.title,
)
},
text = if (item.text != null) {
// composable
{
Text(
text = item.text,
)
}
} else {
null
},
onClick = localState.onChange?.partially1(!localState.checked),
)
}
@Composable
private fun DateMonthYearField(
modifier: Modifier = Modifier,
item: AddStateItem.DateMonthYear,
) {
val localState by item.state.flow.collectAsState()
BiFlatContainer(
modifier = modifier
.padding(horizontal = Dimens.horizontalPadding),
contentModifier = Modifier
.clickable(
indication = LocalIndication.current,
interactionSource = remember {
MutableInteractionSource()
},
role = Role.Button,
) {
localState.onClick.invoke()
},
isError = rememberUpdatedState(newValue = false),
isFocused = rememberUpdatedState(newValue = false),
isEmpty = rememberUpdatedState(newValue = false),
label = {
Text(
text = item.label,
style = MaterialTheme.typography.bodySmall,
)
},
content = {
val density = LocalDensity.current
Row(
modifier = Modifier
.graphicsLayer {
translationY = 12f + density.density
},
) {
Row(
modifier = Modifier
.heightIn(min = BiFlatValueHeightMin)
.weight(1f, fill = false),
horizontalArrangement = Arrangement.spacedBy(2.dp),
) {
val month = localState.month.text.ifBlank { "--" }
val year = localState.year.text.ifBlank { "----" }
Text(
text = month,
)
Text(
text = "/",
color = LocalContentColor.current
.combineAlpha(DisabledEmphasisAlpha),
)
Text(
text = year,
)
}
// Spacer(
// modifier = Modifier
// .width(4.dp),
// )
// Icon(
// modifier = Modifier
// .alpha(MediumEmphasisAlpha),
// imageVector = Icons.Outlined.ArrowDropDown,
// contentDescription = null,
// )
}
},
trailing = {
val isEmpty = localState.month.state.value.isEmpty() &&
localState.year.state.value.isEmpty()
ExpandedIfNotEmptyForRow(
valueOrNull = Unit.takeUnless { isEmpty },
) {
Row(
verticalAlignment = Alignment.CenterVertically,
) {
Spacer(
modifier = Modifier
.width(8.dp),
)
VerticalDivider(
modifier = Modifier
.height(24.dp),
)
Spacer(
modifier = Modifier
.width(8.dp),
)
IconButton(
enabled = true,
onClick = {
localState.month.state.value = ""
localState.year.state.value = ""
},
) {
Icon(
imageVector = Icons.Outlined.Clear,
contentDescription = null,
)
}
}
}
},
)
}
@Composable
private fun EnumItem(
modifier: Modifier = Modifier,
icon: ImageVector,
label: String,
title: String,
dropdown: List<FlatItemAction>,
) {
FlatDropdown(
modifier = modifier,
content = {
FlatItemTextContent2(
title = {
Text(label)
},
text = {
Text(title)
},
)
},
leading = {
Icon(icon, null)
},
dropdown = dropdown,
)
}
@Composable
private fun SectionItem(
modifier: Modifier = Modifier,
title: String?,
) {
Section(
modifier = modifier,
text = title,
)
}
@OptIn(ExperimentalMaterial3Api::class, ExperimentalLayoutApi::class)
@Composable
private fun SuggestionItem(
modifier: Modifier = Modifier,
item: AddStateItem.Suggestion,
) {
val localState by item.state.flow.collectAsState()
FlowRow(
modifier = modifier
.padding(horizontal = Dimens.horizontalPadding),
horizontalArrangement = Arrangement.spacedBy(8.dp),
verticalArrangement = Arrangement.spacedBy(8.dp),
) {
localState.items.forEach { item ->
key(item.key) {
SuggestionItemChip(
modifier = Modifier,
item = item,
)
}
}
}
}
@Composable
private fun SuggestionItemChip(
modifier: Modifier = Modifier,
item: AddStateItem.Suggestion.Item,
) {
val backgroundColor =
if (item.selected) MaterialTheme.colorScheme.primaryContainer else MaterialTheme.colorScheme.surface
Surface(
modifier = modifier,
border = if (item.selected) null else BorderStroke(0.dp, DividerColor),
color = backgroundColor,
shape = MaterialTheme.shapes.small,
) {
val contentColor = LocalContentColor.current
.let { color ->
if (item.onClick != null) {
color // enabled
} else {
color.combineAlpha(DisabledEmphasisAlpha)
}
}
CompositionLocalProvider(
LocalContentColor provides contentColor,
) {
Column(
modifier = Modifier
.then(
if (item.onClick != null) {
Modifier
.clickable(role = Role.Button) {
item.onClick.invoke()
}
} else {
Modifier
},
)
.padding(
horizontal = 12.dp,
vertical = 8.dp,
),
) {
Text(
text = item.text,
style = MaterialTheme.typography.bodyMedium,
)
Text(
text = item.source,
style = MaterialTheme.typography.bodySmall,
color = LocalContentColor.current
.combineAlpha(MediumEmphasisAlpha),
)
}
}
}
}
//
// Ownership
//
@Composable
private fun ToolbarContentItem(
element: AddState.SaveToElement,
) {
element.items.forEach {
key(it.key) {
Column(
modifier = Modifier
.heightIn(min = 32.dp),
verticalArrangement = Arrangement.Center,
) {
Text(
text = it.title,
style = MaterialTheme.typography.bodyMedium,
)
if (it.text != null) {
Text(
text = it.text,
color = LocalContentColor.current
.combineAlpha(MediumEmphasisAlpha),
style = MaterialTheme.typography.bodySmall,
)
}
}
}
}
}
@Composable
private fun ToolbarContentItemErr(
modifier: Modifier = Modifier,
icon: ImageVector,
element: AddState.SaveToElement,
) {
ToolbarContentItemErr(
modifier = modifier,
leading = {
Icon(
imageVector = icon,
contentDescription = null,
)
},
element = element,
)
}
@OptIn(ExperimentalLayoutApi::class)
@Composable
private fun ToolbarContentItemErr(
modifier: Modifier = Modifier,
leading: @Composable () -> Unit,
element: AddState.SaveToElement,
) {
val alpha = if (!element.readOnly) DefaultEmphasisAlpha else DisabledEmphasisAlpha
Row(
modifier = modifier
.heightIn(min = 32.dp)
.alpha(alpha),
) {
Box(
modifier = Modifier
.size(32.dp),
contentAlignment = Alignment.Center,
) {
Box(
modifier = Modifier
.size(16.dp),
) {
leading()
}
}
Spacer(modifier = Modifier.width(14.dp))
FlowRow(
horizontalArrangement = Arrangement.spacedBy(8.dp),
verticalArrangement = Arrangement.spacedBy(8.dp),
) {
ToolbarContentItem(element = element)
}
}
}
@OptIn(ExperimentalLayoutApi::class)
@Composable
private fun ToolbarContentItemErrSkeleton(
modifier: Modifier = Modifier,
fraction: Float = 1f,
) {
Row(
modifier = modifier
.heightIn(min = 32.dp),
) {
Box(
modifier = Modifier
.size(32.dp),
contentAlignment = Alignment.Center,
) {
val contentColor = LocalContentColor.current
.combineAlpha(DisabledEmphasisAlpha)
Box(
modifier = Modifier
.shimmer()
.size(16.dp)
.clip(MaterialTheme.shapes.small)
.background(contentColor),
)
}
Spacer(modifier = Modifier.width(14.dp))
FlowRow(
horizontalArrangement = Arrangement.spacedBy(8.dp),
verticalArrangement = Arrangement.spacedBy(8.dp),
) {
Column(
modifier = Modifier
.heightIn(min = 32.dp),
verticalArrangement = Arrangement.Center,
) {
SkeletonText(
modifier = Modifier
.fillMaxWidth(fraction),
style = MaterialTheme.typography.bodyMedium,
)
}
}
}
}
@Composable
private fun ToolbarContent(
modifier: Modifier = Modifier,
account: AddState.SaveToElement? = null,
organization: AddState.SaveToElement? = null,
collection: AddState.SaveToElement? = null,
folder: AddState.SaveToElement? = null,
onClick: (() -> Unit)? = null,
) {
Column(
modifier = modifier
.fillMaxWidth()
.padding(
horizontal = 8.dp,
vertical = 2.dp,
)
.clip(MaterialTheme.shapes.medium)
.then(
if (onClick != null) {
Modifier
.clickable(
role = Role.Button,
onClick = onClick,
)
} else {
Modifier
},
)
.padding(vertical = 8.dp),
verticalArrangement = Arrangement.spacedBy(8.dp, Alignment.CenterVertically),
) {
Row(
modifier = Modifier
.fillMaxWidth()
.padding(end = 8.dp),
horizontalArrangement = Arrangement.spacedBy(8.dp),
) {
if (account != null) {
ToolbarContentItemErr(
modifier = Modifier
.weight(1.5f),
leading = {
val accentColors = account.items.firstOrNull()
?.accentColors
?: return@ToolbarContentItemErr
val backgroundColor = if (MaterialTheme.colorScheme.isDark) {
accentColors.dark
} else {
accentColors.light
}
Box(
modifier = Modifier
.size(24.dp)
.background(backgroundColor, CircleShape),
)
},
element = account,
)
Spacer(modifier = Modifier.width(8.dp))
}
if (folder != null) {
ToolbarContentItemErr(
modifier = Modifier
.weight(1f)
.padding(end = 8.dp),
icon = Icons.Outlined.Folder,
element = folder,
)
}
}
ExpandedIfNotEmpty(
valueOrNull = organization,
) { org ->
ToolbarContentItemErr(
modifier = Modifier
.padding(end = 8.dp),
icon = Icons.Outlined.KeyguardOrganization,
element = org,
)
}
ExpandedIfNotEmpty(
valueOrNull = collection,
) { col ->
ToolbarContentItemErr(
modifier = Modifier
.padding(end = 8.dp),
icon = Icons.Outlined.KeyguardCollection,
element = col,
)
}
}
}
| 43
|
Kotlin
|
21
| 490
|
df7db9bccab9f86410954799cc8b65b434b8f485
| 56,751
|
keyguard-app
|
Linux Kernel Variant of OpenIB.org license
|
common/src/commonMain/kotlin/tk/zwander/commonCompose/util/StateUtils.kt
|
zacharee
| 342,079,605
| false
|
{"Kotlin": 344512, "AIDL": 84}
|
package tk.zwander.commonCompose.util
import androidx.compose.runtime.Composable
import androidx.compose.runtime.MutableState
import dev.icerock.moko.mvvm.flow.compose.collectAsMutableState
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.flow.MutableStateFlow
// TODO: Keep an eye on BasicTextField2 API so we can remove this: https://proandroiddev.com/basictextfield2-a-textfield-of-dreams-1-2-0103fd7cc0ec.
@Composable
fun <T> MutableStateFlow<T>.collectAsImmediateMutableState(): MutableState<T> = collectAsMutableState(Dispatchers.Main.immediate)
| 8
|
Kotlin
|
96
| 939
|
6a61a0b1f596ca143f1ec4a7989d0a5632f9685c
| 569
|
SamloaderKotlin
|
MIT License
|
library/src/linuxX64Main/kotlin/com/mrwhoknows/countries/kmp/library/fibiprops.linuxX64.kt
|
mrwhoknows55
| 796,037,431
| false
|
{"Kotlin": 1866}
|
package com.mrwhoknows.countries.kmp.library
actual val firstElement: Int = 3
actual val secondElement: Int = 5
| 0
|
Kotlin
|
0
| 0
|
a12fd50a3d447f2886f298f0dca0b3dd4cae49f6
| 112
|
countries-kmp
|
Apache License 2.0
|
app/src/main/java/com/github/amazingweather/di/module/ActivityBindingModule.kt
|
Edydaoud
| 264,558,030
| false
|
{"Gradle": 4, "Java Properties": 2, "Shell": 1, "Ignore List": 3, "Batchfile": 1, "Markdown": 1, "Proguard": 1, "Kotlin": 73, "XML": 44, "Java": 1, "Gradle Kotlin DSL": 1, "JAR Manifest": 1, "INI": 1, "Text": 2, "SQL": 1, "YAML": 1}
|
package com.github.amazingweather.di.module
import com.github.amazingweather.di.scope.ActivityScoped
import com.github.amazingweather.presentation.ui.activity.FragmentContainerActivity
import dagger.Module
import dagger.android.ContributesAndroidInjector
@Module
abstract class ActivityBindingModule {
@ActivityScoped
@ContributesAndroidInjector(modules = [FragmentContainerModule::class])
internal abstract fun fragmentContainerActivity(): FragmentContainerActivity
}
| 0
|
Kotlin
|
0
| 1
|
5f974711242a596d8cf46ff4f16a4104f4e341ba
| 482
|
AmazingWeather
|
Apache License 2.0
|
src/jvmMain/kotlin/model/states/particularStates/IState.kt
|
DaniiLBez
| 659,158,302
| false
| null |
package model.states.particularStates
interface IState {
fun nextStep()
fun backStep()
fun startAlgorithm()
fun finishAlgorithm()
fun resetAlgorithm()
fun mousePressed(posX: Double, posY: Double, cell: Any?)
fun mouseReleased(posX: Double, posY: Double, cell: Any?)
val status: String?
fun close()
}
| 0
|
Kotlin
|
0
| 2
|
63f4c707869c10f941bde3b5e072a92e3cf068c3
| 311
|
stud_practice
|
MIT License
|
security/src/test/java/com/root/security/EncodingModuleTest.kt
|
adessoTurkey
| 246,803,496
| false
|
{"Kotlin": 262786, "Shell": 866}
|
package com.root.security
import com.root.security.encoding.hex.HexDecoder
import com.root.security.encoding.hex.HexEncoder
import org.junit.Assert
import org.junit.Test
/**
* @author haci
* @version 0.0.1
* @since 0.0.1
* Adesso Security Module.
* created on 21.11.2021
*/
class EncodingModuleTest {
private val hexValue = "6c6f72656dc59e7073756d646f6c6f722073c4b074616d6574"
private val plainText = "loremŞpsumdolor sİtamet"
@Test
fun test_hex_encoder() {
// given
val encoder = HexEncoder()
// when
val encoded = encoder.encode(plainText.toByteArray())
// then
Assert.assertEquals(hexValue, encoded)
}
@Test
fun test_hex_decoder() {
// given
val decoder = HexDecoder()
// when
val decoded = decoder.decode(hexValue)
// then
Assert.assertEquals(plainText, String(decoded, Charsets.UTF_8))
}
}
| 31
|
Kotlin
|
13
| 35
|
b34346a815204c966311f0c879b66e05a10eab13
| 938
|
android-sample-app
|
Apache License 2.0
|
PushNotification/app/src/main/java/com/juhwan/anyang_yi/present/views/home/keyword/KeywordViewModel.kt
|
juhwankim-dev
| 324,930,598
| false
| null |
package com.juhwan.anyang_yi.present.views.home.keyword
import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.juhwan.anyang_yi.data.model.KeywordEntity
import com.juhwan.anyang_yi.domain.usecase.keyword.DeleteKeywordUseCase
import com.juhwan.anyang_yi.domain.usecase.keyword.ReadKeywordListUseCase
import com.juhwan.anyang_yi.domain.usecase.keyword.WriteKeywordUseCase
import com.juhwan.anyang_yi.domain.usecase.univ.HasSearchResultUseCase
import com.juhwan.anyang_yi.present.config.SingleLiveEvent
import com.juhwan.anyang_yi.present.utils.Result
import com.juhwan.anyang_yi.present.utils.Status
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.launch
import javax.inject.Inject
@HiltViewModel
class KeywordViewModel @Inject constructor(
private val deleteKeywordUseCase: DeleteKeywordUseCase,
private val readKeywordListUseCase: ReadKeywordListUseCase,
private val writeKeywordUseCase: WriteKeywordUseCase,
private val hasSearchResultUseCase: HasSearchResultUseCase
): ViewModel() {
private val keywordList: LiveData<List<KeywordEntity>> = readKeywordListUseCase.invoke()
private val _searchResult = SingleLiveEvent<Boolean>()
val searchResult: LiveData<Boolean> get() = _searchResult
private val _problem = MutableLiveData<Result<Any>>()
val problem: LiveData<Result<Any>> get() = _problem
fun deleteKeyword(keyword: String) {
viewModelScope.launch {
try {
deleteKeywordUseCase.invoke(keyword)
} catch (e: Exception) {
_problem.postValue(Result(Status.FAIL, null, null))
}
}
}
fun readKeywordList(): LiveData<List<KeywordEntity>> {
return keywordList
}
fun writeKeyword(keyword: String) {
viewModelScope.launch {
val result = writeKeywordUseCase.invoke(keyword)
if(result.status == Status.ERROR) {
_problem.postValue(result)
}
}
}
fun getSearchResult(keyword: String) {
viewModelScope.launch {
val result = hasSearchResultUseCase(keyword)
if(result.status == Status.SUCCESS) {
result.data.let { _searchResult.postValue(it) }
} else {
_problem.postValue(result)
}
}
}
}
| 1
|
Kotlin
|
1
| 5
|
ae17bf81ec4bdf7a8704710b742b44cfc84a6b04
| 2,442
|
pushNotificationApp
|
Apache License 2.0
|
exposed-jdbc/src/main/kotlin/org/jetbrains/exposed/sql/statements/jdbc/JdbcPreparedStatementImpl.kt
|
JetBrains
| 11,765,017
| false
| null |
package org.jetbrains.exposed.sql.statements.jdbc
import org.jetbrains.exposed.sql.BinaryColumnType
import org.jetbrains.exposed.sql.BlobColumnType
import org.jetbrains.exposed.sql.IColumnType
import org.jetbrains.exposed.sql.statements.StatementResult
import org.jetbrains.exposed.sql.statements.api.PreparedStatementApi
import org.jetbrains.exposed.sql.vendors.SQLiteDialect
import org.jetbrains.exposed.sql.vendors.currentDialect
import java.io.InputStream
import java.sql.PreparedStatement
import java.sql.ResultSet
import java.sql.Statement
import java.sql.Types
/**
* Class representing a precompiled SQL [statement].
*
* The result set generated by executing this statement contains auto-generated keys based on the value of
* [wasGeneratedKeysRequested] and if the JDBC driver implementation [supportsGetGeneratedKeys].
*/
class JdbcPreparedStatementImpl(
val statement: PreparedStatement,
val wasGeneratedKeysRequested: Boolean,
private val supportsGetGeneratedKeys: Boolean
) : PreparedStatementApi {
override val resultSet: ResultSet?
get() = when {
!wasGeneratedKeysRequested -> statement.resultSet
supportsGetGeneratedKeys -> statement.generatedKeys
currentDialect is SQLiteDialect -> {
statement.connection.prepareStatement("select last_insert_rowid();").executeQuery()
}
else -> statement.resultSet
}
override var fetchSize: Int?
get() = statement.fetchSize
set(value) {
value?.let { statement.fetchSize = value }
}
override var timeout: Int?
get() = statement.queryTimeout
set(value) {
value?.let { statement.queryTimeout = it }
}
override fun addBatch() {
statement.addBatch()
}
override fun executeQuery(): ResultSet = statement.executeQuery()
override fun executeUpdate(): Int = statement.executeUpdate()
override fun executeMultiple(): List<StatementResult> {
// execute() returns true only if first result is a ResultSet
return if (statement.execute()) {
listOf(StatementResult.Object(statement.resultSet))
} else {
// getMoreResults() returns true only if next result is a ResultSet
while (!statement.getMoreResults(Statement.CLOSE_CURRENT_RESULT)) {
if (statement.updateCount == -1) return emptyList()
}
listOf(StatementResult.Object(statement.resultSet))
}
}
override fun set(index: Int, value: Any) {
statement.setObject(index, value)
}
override fun setNull(index: Int, columnType: IColumnType) {
if (columnType is BinaryColumnType || (columnType is BlobColumnType && !columnType.useObjectIdentifier)) {
statement.setNull(index, Types.LONGVARBINARY)
} else {
statement.setObject(index, null)
}
}
override fun setInputStream(index: Int, inputStream: InputStream, setAsBlobObject: Boolean) {
if (setAsBlobObject) {
statement.setBlob(index, inputStream)
} else {
statement.setBinaryStream(index, inputStream, inputStream.available())
}
}
override fun setArray(index: Int, type: String, array: Array<*>) {
statement.setArray(index, statement.connection.createArrayOf(type, array))
}
override fun closeIfPossible() {
if (!statement.isClosed) statement.close()
}
override fun executeBatch(): List<Int> {
return statement.executeBatch().map {
when (it) {
Statement.SUCCESS_NO_INFO -> 1
Statement.EXECUTE_FAILED -> 0
else -> it
}
}
}
override fun cancel() {
if (!statement.isClosed) statement.cancel()
}
}
| 217
| null |
663
| 7,851
|
f396d8ae6cf8923f574d2a6a1f098c88452957b6
| 3,843
|
Exposed
|
Apache License 2.0
|
src/main/kotlin/ie/setu/domain/RecommendedDailyAllowance.kt
|
MartinDevStudent
| 698,647,357
| false
|
{"Kotlin": 189074, "Vue": 70899, "HTML": 1950}
|
package ie.setu.domain
data class RecommendedDailyAllowance(
val calories: Double,
val fatTotalG: Double,
val fatSaturatedG: Double,
val proteinG: Double,
val sodiumMg: Int,
val potassiumMg: Int,
val cholesterolMg: Int,
val carbohydratesTotalG: Double,
val fiberG: Double,
val sugarG: Double,
)
| 0
|
Kotlin
|
0
| 0
|
374d29450d72287f8b3ab5125f12fa4fe351bd64
| 336
|
healthtrackerrest
|
PostgreSQL License
|
libraries/arch/src/main/java/com/fappslab/rickandmortygraphql/libraries/arch/testing/rules/FragmentTestRule.kt
|
F4bioo
| 628,097,763
| false
| null |
package com.fappslab.rickandmortygraphql.libraries.arch.testing.rules
import android.os.Bundle
import androidx.annotation.StyleRes
import androidx.annotation.VisibleForTesting
import androidx.fragment.app.Fragment
import androidx.fragment.app.testing.FragmentScenario
import androidx.lifecycle.Lifecycle
import com.google.android.material.R
import org.junit.runner.Description
import java.lang.reflect.Modifier
import kotlin.reflect.KClass
@VisibleForTesting(otherwise = Modifier.PRIVATE)
abstract class FragmentTestRule<F : Fragment>(
private val fragmentKClass: KClass<F>,
private val fragmentArgs: Bundle? = null,
@StyleRes private val themeResId: Int = R.style.Theme_MaterialComponents_Light_DarkActionBar,
private val lifecycleInitState: Lifecycle.State = Lifecycle.State.RESUMED
) : KoinTestRule() {
private var scenario: FragmentScenario<F>? = null
override fun finished(description: Description) {
super.finished(description)
cleanupTestRule()
}
protected fun launchFragment(fragment: (F) -> Unit) {
scenario = FragmentScenario.launchInContainer(
fragmentClass = fragmentKClass.java,
fragmentArgs = fragmentArgs,
themeResId = themeResId,
initialState = lifecycleInitState
).apply {
stateScenarioHandler(scenario = this)
}.onFragment(fragment)
}
private fun stateScenarioHandler(scenario: FragmentScenario<F>) {
if (lifecycleInitState != Lifecycle.State.RESUMED) {
scenario.moveToState(Lifecycle.State.RESUMED)
}
}
private fun closeFragmentScenario() {
scenario?.apply {
moveToState(Lifecycle.State.DESTROYED)
close()
}
}
private fun cleanupTestRule() {
closeFragmentScenario()
}
}
| 0
|
Kotlin
|
0
| 0
|
d3e0405eae2038ea13c352daa8bc976da85914a4
| 1,833
|
faurecia-aptoide-challenge
|
MIT License
|
libraries/arch/src/main/java/com/fappslab/rickandmortygraphql/libraries/arch/testing/rules/FragmentTestRule.kt
|
F4bioo
| 628,097,763
| false
| null |
package com.fappslab.rickandmortygraphql.libraries.arch.testing.rules
import android.os.Bundle
import androidx.annotation.StyleRes
import androidx.annotation.VisibleForTesting
import androidx.fragment.app.Fragment
import androidx.fragment.app.testing.FragmentScenario
import androidx.lifecycle.Lifecycle
import com.google.android.material.R
import org.junit.runner.Description
import java.lang.reflect.Modifier
import kotlin.reflect.KClass
@VisibleForTesting(otherwise = Modifier.PRIVATE)
abstract class FragmentTestRule<F : Fragment>(
private val fragmentKClass: KClass<F>,
private val fragmentArgs: Bundle? = null,
@StyleRes private val themeResId: Int = R.style.Theme_MaterialComponents_Light_DarkActionBar,
private val lifecycleInitState: Lifecycle.State = Lifecycle.State.RESUMED
) : KoinTestRule() {
private var scenario: FragmentScenario<F>? = null
override fun finished(description: Description) {
super.finished(description)
cleanupTestRule()
}
protected fun launchFragment(fragment: (F) -> Unit) {
scenario = FragmentScenario.launchInContainer(
fragmentClass = fragmentKClass.java,
fragmentArgs = fragmentArgs,
themeResId = themeResId,
initialState = lifecycleInitState
).apply {
stateScenarioHandler(scenario = this)
}.onFragment(fragment)
}
private fun stateScenarioHandler(scenario: FragmentScenario<F>) {
if (lifecycleInitState != Lifecycle.State.RESUMED) {
scenario.moveToState(Lifecycle.State.RESUMED)
}
}
private fun closeFragmentScenario() {
scenario?.apply {
moveToState(Lifecycle.State.DESTROYED)
close()
}
}
private fun cleanupTestRule() {
closeFragmentScenario()
}
}
| 0
|
Kotlin
|
0
| 0
|
d3e0405eae2038ea13c352daa8bc976da85914a4
| 1,833
|
faurecia-aptoide-challenge
|
MIT License
|
src/main/kotlin/uk/gov/justice/digital/hmpps/nomisprisonerapi/core/PrisonService.kt
|
ministryofjustice
| 444,895,409
| false
|
{"Kotlin": 2060121, "PLSQL": 263407, "Dockerfile": 1112}
|
package uk.gov.justice.digital.hmpps.nomisprisonerapi.core
import jakarta.transaction.Transactional
import org.springframework.data.repository.findByIdOrNull
import org.springframework.stereotype.Service
import uk.gov.justice.digital.hmpps.nomisprisonerapi.data.NotFoundException
import uk.gov.justice.digital.hmpps.nomisprisonerapi.jpa.repository.AgencyLocationRepository
import uk.gov.justice.digital.hmpps.nomisprisonerapi.jpa.repository.AvailablePrisonIepLevelRepository
@Service
@Transactional
class PrisonService(
private val agencyLocationRepository: AgencyLocationRepository,
private val availablePrisonIepLevelRepository: AvailablePrisonIepLevelRepository,
) {
fun getPrisonIepLevels(prisonId: String): List<IncentiveLevel> =
agencyLocationRepository.findByIdOrNull(prisonId)
?.let { availablePrisonIepLevelRepository.findAllByAgencyLocationAndActive(it) }
?.map { IncentiveLevel(it.id, it.iepLevel.description) }
?: throw NotFoundException("Prison $prisonId does not exist")
}
| 1
|
Kotlin
|
2
| 0
|
79cdfc08c0c75ef37324473406fdc71e77ec96e5
| 1,017
|
hmpps-nomis-prisoner-api
|
MIT License
|
app/src/main/java/com/example/weatherapp/model/CurrentWeatherData.kt
|
kushaldhengole
| 667,028,478
| false
| null |
package com.example.weatherapp.model
data class CurrentWeatherData(val condition: String,val temp:String,
val humidity:String,val wind:String,val image: String,val locationName:String,val country:String)
| 0
|
Kotlin
|
0
| 0
|
b602a676f1c3eaaaa1acebe5079e1830ef407e41
| 205
|
WeatherAPP
|
Apache License 2.0
|
src/es/pelisplushd/src/eu/kanade/tachiyomi/animeextension/es/pelisplushd/Pelisplusph.kt
|
tonmoyislam250
| 705,795,259
| false
| null |
package eu.kanade.tachiyomi.animeextension.es.pelisplushd
import androidx.preference.ListPreference
import androidx.preference.PreferenceScreen
import eu.kanade.tachiyomi.animeextension.es.pelisplushd.extractors.FilemoonExtractor
import eu.kanade.tachiyomi.animeextension.es.pelisplushd.extractors.StreamlareExtractor
import eu.kanade.tachiyomi.animesource.model.AnimeFilter
import eu.kanade.tachiyomi.animesource.model.AnimeFilterList
import eu.kanade.tachiyomi.animesource.model.SAnime
import eu.kanade.tachiyomi.animesource.model.SEpisode
import eu.kanade.tachiyomi.animesource.model.Video
import eu.kanade.tachiyomi.lib.doodextractor.DoodExtractor
import eu.kanade.tachiyomi.lib.okruextractor.OkruExtractor
import eu.kanade.tachiyomi.lib.streamsbextractor.StreamSBExtractor
import eu.kanade.tachiyomi.lib.voeextractor.VoeExtractor
import eu.kanade.tachiyomi.lib.youruploadextractor.YourUploadExtractor
import eu.kanade.tachiyomi.network.GET
import eu.kanade.tachiyomi.util.asJsoup
import kotlinx.serialization.decodeFromString
import kotlinx.serialization.json.Json
import kotlinx.serialization.json.JsonObject
import kotlinx.serialization.json.jsonPrimitive
import okhttp3.Request
import okhttp3.Response
import org.jsoup.nodes.Document
import org.jsoup.nodes.Element
import uy.kohesive.injekt.injectLazy
class Pelisplusph(override val name: String, override val baseUrl: String) : Pelisplushd(name, baseUrl) {
private val json: Json by injectLazy()
override val supportsLatest = false
override fun popularAnimeSelector(): String = ".items-peliculas .item-pelicula"
override fun popularAnimeNextPageSelector(): String = ".items-peliculas > a"
override fun popularAnimeRequest(page: Int): Request = GET("$baseUrl/peliculas?page=$page")
override fun popularAnimeFromElement(element: Element): SAnime {
val anime = SAnime.create()
anime.setUrlWithoutDomain(baseUrl + element.selectFirst("a")?.attr("href"))
anime.title = element.select("a .item-detail > p").text()
anime.thumbnail_url = baseUrl + element.select("a .item-picture img").attr("src")
return anime
}
override fun animeDetailsParse(document: Document): SAnime {
val anime = SAnime.create()
anime.title = document.selectFirst(".info-content h1")!!.text()
document.select(".info-content p").map { p ->
if (p.select(".content-type").text().contains("Sinópsis:")) {
anime.description = p.select(".sinopsis")!!.text()
}
if (p.select(".content-type").text().contains("Géneros:")) {
anime.genre = p.select(".content-type-a a").joinToString { it.text() }
}
if (p.select(".content-type").text().contains("Reparto:")) {
anime.artist = p.select(".content-type ~ span").text().substringBefore(",")
}
}
anime.status = if (document.location().contains("/serie/")) SAnime.UNKNOWN else SAnime.COMPLETED
return anime
}
override fun episodeListParse(response: Response): List<SEpisode> {
val episodes = mutableListOf<SEpisode>()
val jsoup = response.asJsoup()
if (response.request.url.toString().contains("/pelicula/")) {
val episode = SEpisode.create().apply {
episode_number = 1F
name = "PELÍCULA"
}
episode.setUrlWithoutDomain(response.request.url.toString())
episodes.add(episode)
} else {
var index = 0
jsoup.select(".item-season").reversed().mapIndexed { idxSeas, season ->
val seasonNumber = try {
getNumberFromString(season.selectFirst(".item-season-title")!!.ownText())
} catch (_: Exception) { idxSeas + 1 }
season.select(".item-season-episodes a").reversed().mapIndexed { idx, ep ->
index += 1
val noEp = try {
getNumberFromString(ep.ownText())
} catch (_: Exception) { idx + 1 }
val episode = SEpisode.create()
episode.episode_number = index.toFloat()
episode.name = "T$seasonNumber - E$noEp - ${ep.ownText()}"
episode.setUrlWithoutDomain(baseUrl + ep.attr("href"))
episodes.add(episode)
}
}
}
return episodes.reversed()
}
override fun searchAnimeRequest(page: Int, query: String, filters: AnimeFilterList): Request {
val filterList = if (filters.isEmpty()) getFilterList() else filters
val genreFilter = filterList.find { it is GenreFilter } as GenreFilter
return when {
query.isNotBlank() -> GET("$baseUrl/search/$query", headers)
genreFilter.state != 0 -> GET("$baseUrl/${genreFilter.toUriPart()}?page=$page")
else -> popularAnimeRequest(page)
}
}
override fun videoListParse(response: Response): List<Video> {
val document = response.asJsoup()
val videoList = mutableListOf<Video>()
document.select("[class*=server-item-]").map {
val langIdx = getNumberFromString(it.attr("class").substringAfter("server-item-"))
val langItem = document.select("li[data-id=\"$langIdx\"] a").text()
val lang = if (langItem.contains("Subtitulado")) "[Sub]" else if (langItem.contains("Latino")) "[Lat]" else "[Cast]"
it.select("li.tab-video").map { servers ->
val url = servers.attr("data-video")
loadExtractor(url, lang).let { videos ->
videoList.addAll(videos)
}
}
}
return videoList
}
private fun loadExtractor(url: String, prefix: String = ""): List<Video> {
val videoList = mutableListOf<Video>()
val embedUrl = url.lowercase()
if (embedUrl.contains("tomatomatela")) {
try {
val mainUrl = url.substringBefore("/embed.html#").substringAfter("https://")
val headers = headers.newBuilder()
.set("authority", mainUrl)
.set("accept", "application/json, text/javascript, */*; q=0.01")
.set("accept-language", "es-MX,es-419;q=0.9,es;q=0.8,en;q=0.7")
.set("sec-ch-ua", "\"Chromium\";v=\"106\", \"Google Chrome\";v=\"106\", \"Not;A=Brand\";v=\"99\"")
.set("sec-ch-ua-mobile", "?0")
.set("sec-ch-ua-platform", "Windows")
.set("sec-fetch-dest", "empty")
.set("sec-fetch-mode", "cors")
.set("sec-fetch-site", "same-origin")
.set("x-requested-with", "XMLHttpRequest")
.build()
val token = url.substringAfter("/embed.html#")
val urlRequest = "https://$mainUrl/details.php?v=$token"
val response = client.newCall(GET(urlRequest, headers = headers)).execute().asJsoup()
val bodyText = response.select("body").text()
val json = json.decodeFromString<JsonObject>(bodyText)
val status = json["status"]!!.jsonPrimitive!!.content
val file = json["file"]!!.jsonPrimitive!!.content
if (status == "200") { videoList.add(Video(file, "$prefix Tomatomatela", file, headers = null)) }
} catch (e: Exception) { }
}
if (embedUrl.contains("yourupload")) {
val videos = YourUploadExtractor(client).videoFromUrl(url, headers = headers)
videoList.addAll(videos)
}
if (embedUrl.contains("doodstream") || embedUrl.contains("dood.")) {
DoodExtractor(client).videoFromUrl(url, "$prefix DoodStream", false)
?.let { videoList.add(it) }
}
if (embedUrl.contains("sbembed.com") || embedUrl.contains("sbembed1.com") || embedUrl.contains("sbplay.org") ||
embedUrl.contains("sbvideo.net") || embedUrl.contains("streamsb.net") || embedUrl.contains("sbplay.one") ||
embedUrl.contains("cloudemb.com") || embedUrl.contains("playersb.com") || embedUrl.contains("tubesb.com") ||
embedUrl.contains("sbplay1.com") || embedUrl.contains("embedsb.com") || embedUrl.contains("watchsb.com") ||
embedUrl.contains("sbplay2.com") || embedUrl.contains("japopav.tv") || embedUrl.contains("viewsb.com") ||
embedUrl.contains("sbfast") || embedUrl.contains("sbfull.com") || embedUrl.contains("javplaya.com") ||
embedUrl.contains("ssbstream.net") || embedUrl.contains("p1ayerjavseen.com") || embedUrl.contains("sbthe.com") ||
embedUrl.contains("vidmovie.xyz") || embedUrl.contains("sbspeed.com") || embedUrl.contains("streamsss.net") ||
embedUrl.contains("sblanh.com") || embedUrl.contains("sbbrisk.com") || embedUrl.contains("lvturbo.com")
) {
runCatching {
StreamSBExtractor(client).videosFromUrl(url, headers, prefix = prefix)
}.getOrNull()?.let { videoList.addAll(it) }
}
if (embedUrl.contains("okru") || embedUrl.contains("ok.ru")) {
videoList.addAll(
OkruExtractor(client).videosFromUrl(url, prefix, true),
)
}
if (embedUrl.contains("voe")) {
VoeExtractor(client).videoFromUrl(url, "$prefix VoeCDN")?.let { videoList.add(it) }
}
if (embedUrl.contains("filemoon") || embedUrl.contains("moonplayer")) {
FilemoonExtractor(client).videoFromUrl(url, prefix)?.let {
videoList.addAll(it)
}
}
if (embedUrl.contains("streamlare")) {
StreamlareExtractor(client).videosFromUrl(url)?.let { videoList.add(it) }
}
return videoList
}
override fun getFilterList(): AnimeFilterList = AnimeFilterList(
AnimeFilter.Header("La busqueda por genero ignora los otros filtros"),
GenreFilter(),
)
private class GenreFilter : UriPartFilter(
"Géneros",
arrayOf(
Pair("<selecionar>", ""),
Pair("Peliculas", "peliculas"),
Pair("Series", "series"),
Pair("Estrenos", "estrenos"),
Pair("Acción", "genero/accion"),
Pair("Artes marciales", "genero/artes-marciales"),
Pair("Asesinos en serie", "genero/asesinos-en-serie"),
Pair("Aventura", "genero/aventura"),
Pair("Baile", "genero/baile"),
Pair("Bélico", "genero/belico"),
Pair("Biografico", "genero/biografico"),
Pair("Catástrofe", "genero/catastrofe"),
Pair("Ciencia Ficción", "genero/ciencia-ficcion"),
Pair("Cine Adolescente", "genero/cine-adolescente"),
Pair("Cine LGBT", "genero/cine-lgbt"),
Pair("Cine Negro", "genero/cine-negro"),
Pair("Cine Policiaco", "genero/cine-policiaco"),
Pair("Clásicas", "genero/clasicas"),
Pair("Comedia", "genero/comedia"),
Pair("Comedia Negra", "genero/comedia-negra"),
Pair("Crimen", "genero/crimen"),
Pair("DC Comics", "genero/dc-comics"),
Pair("Deportes", "genero/deportes"),
Pair("Desapariciones", "genero/desapariciones"),
Pair("Disney", "genero/disney"),
Pair("Documental", "genero/documental"),
Pair("Drama", "genero/drama"),
Pair("Familiar", "genero/familiar"),
Pair("Fantasía", "genero/fantasia"),
Pair("Historia", "genero/historia"),
Pair("Horror", "genero/horror"),
Pair("Infantil", "genero/infantil"),
Pair("Intriga", "genero/intriga"),
Pair("live action", "genero/live-action"),
Pair("Marvel Comics", "genero/marvel-comics"),
Pair("Misterio", "genero/misterio"),
Pair("Música", "genero/musica"),
Pair("Musical", "genero/musical"),
Pair("Policial", "genero/policial"),
Pair("Político", "genero/politico"),
Pair("Psicológico", "genero/psicologico"),
Pair("Reality Tv", "genero/reality-tv"),
Pair("Romance", "genero/romance"),
Pair("Secuestro", "genero/secuestro"),
Pair("Slasher", "genero/slasher"),
Pair("Sobrenatural", "genero/sobrenatural"),
Pair("Stand Up", "genero/stand-up"),
Pair("Superhéroes", "genero/superheroes"),
Pair("Suspenso", "genero/suspenso"),
Pair("Terror", "genero/terror"),
Pair("Thriller", "genero/thriller"),
Pair("Tokusatsu", "genero/tokusatsu"),
Pair("TV Series", "genero/tv-series"),
Pair("Western", "genero/western"),
Pair("Zombie", "genero/zombie"),
Pair("Acción", "genero/accion"),
Pair("Artes marciales", "genero/artes-marciales"),
Pair("Asesinos en serie", "genero/asesinos-en-serie"),
Pair("Aventura", "genero/aventura"),
Pair("Baile", "genero/baile"),
Pair("Bélico", "genero/belico"),
Pair("Biografico", "genero/biografico"),
Pair("Catástrofe", "genero/catastrofe"),
Pair("Ciencia Ficción", "genero/ciencia-ficcion"),
Pair("Cine Adolescente", "genero/cine-adolescente"),
Pair("Cine LGBT", "genero/cine-lgbt"),
Pair("Cine Negro", "genero/cine-negro"),
Pair("Cine Policiaco", "genero/cine-policiaco"),
Pair("Clásicas", "genero/clasicas"),
Pair("Comedia", "genero/comedia"),
Pair("Comedia Negra", "genero/comedia-negra"),
Pair("Crimen", "genero/crimen"),
Pair("DC Comics", "genero/dc-comics"),
Pair("Deportes", "genero/deportes"),
Pair("Desapariciones", "genero/desapariciones"),
Pair("Disney", "genero/disney"),
Pair("Documental", "genero/documental"),
Pair("Drama", "genero/drama"),
Pair("Familiar", "genero/familiar"),
Pair("Fantasía", "genero/fantasia"),
Pair("Historia", "genero/historia"),
Pair("Horror", "genero/horror"),
Pair("Infantil", "genero/infantil"),
Pair("Intriga", "genero/intriga"),
Pair("live action", "genero/live-action"),
Pair("Marvel Comics", "genero/marvel-comics"),
Pair("Misterio", "genero/misterio"),
Pair("Música", "genero/musica"),
Pair("Musical", "genero/musical"),
Pair("Policial", "genero/policial"),
Pair("Político", "genero/politico"),
Pair("Psicológico", "genero/psicologico"),
Pair("Reality Tv", "genero/reality-tv"),
Pair("Romance", "genero/romance"),
Pair("Secuestro", "genero/secuestro"),
Pair("Slasher", "genero/slasher"),
Pair("Sobrenatural", "genero/sobrenatural"),
Pair("Stand Up", "genero/stand-up"),
Pair("Superhéroes", "genero/superheroes"),
Pair("Suspenso", "genero/suspenso"),
Pair("Terror", "genero/terror"),
Pair("Thriller", "genero/thriller"),
Pair("Tokusatsu", "genero/tokusatsu"),
Pair("TV Series", "genero/tv-series"),
Pair("Western", "genero/western"),
Pair("Zombie", "genero/zombie"),
),
)
override fun setupPreferenceScreen(screen: PreferenceScreen) {
val qualities = arrayOf(
"StreamSB:1080p", "StreamSB:720p", "StreamSB:480p", "StreamSB:360p", "StreamSB:240p", "StreamSB:144p", // StreamSB
"Fembed:1080p", "Fembed:720p", "Fembed:480p", "Fembed:360p", "Fembed:240p", "Fembed:144p", // Fembed
"DoodStream",
)
val videoQualityPref = ListPreference(screen.context).apply {
key = "preferred_quality"
title = "Preferred quality"
entries = qualities
entryValues = qualities
setDefaultValue("Voex")
summary = "%s"
setOnPreferenceChangeListener { _, newValue ->
val selected = newValue as String
val index = findIndexOfValue(selected)
val entry = entryValues[index] as String
preferences.edit().putString(key, entry).commit()
}
}
screen.addPreference(videoQualityPref)
}
}
| 0
|
Kotlin
|
0
| 0
|
9532b590e370b53206cfe1d31874e6ce549a509e
| 16,593
|
aniyomi-extensions
|
Apache License 2.0
|
org.librarysimplified.audiobook.audioengine/src/main/java/org/librarysimplified/audiobook/audioengine/FindawayPlayerPlaybackStatus.kt
|
ThePalaceProject
| 379,956,255
| false
|
{"Kotlin": 710862, "Java": 2392}
|
package org.librarysimplified.audiobook.audioengine
/**
* The playback status of the player.
*/
enum class FindawayPlayerPlaybackStatus {
/**
* The player is in the initialized state.
*/
INITIAL,
/**
* The player is currently buffering audio and can't play.
*/
BUFFERING,
/**
* The player is currently playing audio.
*/
PLAYING,
/**
* The player is currently paused.
*/
PAUSED,
/**
* The chapter the player was playing has ended.
*/
CHAPTER_ENDED
}
/**
* The player transitioned from one playback state to another.
*/
data class FindawayPlayerPlaybackStatusTransition(
val oldState: FindawayPlayerPlaybackStatus,
val newState: FindawayPlayerPlaybackStatus
)
| 1
|
Kotlin
|
1
| 1
|
1ed86aae92d0e51070b63da5da20670a7e4a084d
| 730
|
android-audiobook
|
Apache License 2.0
|
kotlin-js/src/jsMain/kotlin/js/symbol/PrimitiveHint.kt
|
JetBrains
| 93,250,841
| false
| null |
@file:Suppress(
"NESTED_CLASS_IN_EXTERNAL_INTERFACE",
)
package js.symbol
import seskar.js.JsValue
import seskar.js.JsVirtual
@JsVirtual
sealed external interface PrimitiveHint {
companion object {
@JsValue("number")
val number: PrimitiveHint
@JsValue("string")
val string: PrimitiveHint
@JsValue("default")
val default: PrimitiveHint
}
}
| 34
| null |
174
| 1,294
|
5aaa9938ea3bee8a9bed5be39f8ab0729421d715
| 404
|
kotlin-wrappers
|
Apache License 2.0
|
workmanager/src/main/java/worker/s06/ConstraintsFragment.kt
|
siarhei-luskanau
| 78,451,961
| false
| null |
package worker.s06
import android.content.Context
import androidx.work.Constraints
import androidx.work.Data
import androidx.work.NetworkType
import androidx.work.OneTimeWorkRequestBuilder
import androidx.work.WorkManager
import androidx.work.WorkerParameters
import kotlinx.coroutines.delay
import siarhei.luskanau.example.workmanager.BaseBeginCancelWorkFragment
import siarhei.luskanau.example.workmanager.BaseWorker
import siarhei.luskanau.example.workmanager.monitor.WorkManagerConstants
private const val SLEEP_MILLIS = 30 * 1000L
class ConstraintsFragment : BaseBeginCancelWorkFragment() {
override fun onBeginButtonPressed() {
val constraints = Constraints.Builder()
.setRequiredNetworkType(NetworkType.UNMETERED)
.build()
WorkManager.getInstance(requireContext())
.beginWith(
OneTimeWorkRequestBuilder<ConstraintsWorker>()
.setConstraints(constraints)
.addTag(WorkManagerConstants.TAG_ALL)
.build(),
).enqueue()
}
override fun onCancelButtonPressed() {
WorkManager.getInstance(requireContext())
.cancelAllWorkByTag(ConstraintsWorker::class.java.name)
}
}
class ConstraintsWorker(
context: Context,
workerParams: WorkerParameters,
) : BaseWorker(
context,
workerParams,
) {
override suspend fun doWorkDelegate(outputDataBuilder: Data.Builder): Result {
delay(SLEEP_MILLIS)
return Result.success()
}
}
| 0
|
Kotlin
|
0
| 1
|
fb8776d3a32ea222c90a6ae5f576abd923a33465
| 1,532
|
android-samples
|
MIT License
|
library/core-extentions/src/main/java/io/github/mayconcardoso/mvvm/core/ktx/ActivityExtention.kt
|
MayconCardoso
| 257,414,651
| false
| null |
package io.github.mayconcardoso.mvvm.core.ktx
import android.view.LayoutInflater
import androidx.appcompat.app.AppCompatActivity
import androidx.lifecycle.LiveData
import androidx.lifecycle.lifecycleScope
import androidx.viewbinding.ViewBinding
import io.github.mayconcardoso.mvvm.core.BaseViewModel
import io.github.mayconcardoso.mvvm.core.ViewCommand
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.collectLatest
import kotlinx.coroutines.flow.stateIn
import kotlinx.coroutines.launch
/**
* Called to observe any state flow from your view model.
*/
inline fun <T> AppCompatActivity.bindState(
observable: StateFlow<T>,
crossinline block: (result: T) -> Unit,
) = lifecycleScope.launch {
observable
.stateIn(lifecycleScope)
.collectLatest {
block(it)
}
}
/**
* Called to observe any live data from your view model.
*/
inline fun <T> AppCompatActivity.bindState(
observable: LiveData<T>,
crossinline block: (result: T) -> Unit,
) = lifecycleScope.launch {
observable
.observe(this@bindState) {
block(it)
}
}
/**
* Called to observe all commands sent from your view mode.
*/
fun AppCompatActivity.bindCommand(
viewModel: BaseViewModel,
block: (result: ViewCommand) -> Unit,
) {
commandObserver(
lifecycle = this@bindCommand,
viewModel = viewModel,
block = block,
)
}
/**
* Called to observe only the first command sent from your view mode.
*/
fun AppCompatActivity.bindAutoDisposableCommand(
viewModel: BaseViewModel,
block: (result: ViewCommand) -> Unit,
) {
autoDisposeCommandObserver(
lifecycle = this@bindAutoDisposableCommand,
viewModel = viewModel,
block = block,
)
}
/**
* Delegate to bind the view of an activity. It can be used from [AppCompatActivity.onCreate] to
* [AppCompatActivity.onDestroy] (inclusive).
*
* Sample usage:
* ```
* class SampleActivity : AppCompatActivity() {
* private val binding by viewBinding(ActivitySampleBinding::inflate)
*
* override fun onCreate(savedInstanceState: Bundle?) {
* super.onCreate(savedInstanceState)
* setContentView(binding.root)
* // binding is ready to use
* }
* }
* ```
*/
inline fun <T : ViewBinding> AppCompatActivity.viewBinding(
crossinline factory: (LayoutInflater) -> T,
): Lazy<T> = lazy(LazyThreadSafetyMode.NONE) {
factory(layoutInflater)
}
| 0
|
Kotlin
|
1
| 14
|
41cc945107a819b442e1d0312e8c91ac060eb699
| 2,365
|
Mvvm-Architecture-Toolkit
|
Apache License 2.0
|
src/kotlin-services/services/catalog/src/main/kotlin/com/example/app/catalog/application/usecase/CommandUseCases.kt
|
codejsha
| 628,340,197
| false
| null |
package com.example.app.catalog.application.usecase
import com.example.app.catalog.domain.dto.ActorAddRequestDto
import com.example.app.catalog.domain.dto.ActorNameUpdateRequestDto
import com.example.app.catalog.domain.dto.MovieAddRequestDto
import com.example.app.catalog.domain.dto.MovieUpdateRequestDto
import com.example.app.catalog.domain.entity.ActorAggregate
import com.example.app.catalog.domain.entity.MovieAggregate
import reactor.core.publisher.Mono
interface ActorManagementUseCase {
fun addActor(actorAddRequestDto: ActorAddRequestDto): Mono<ActorAggregate>
fun updateActorName(id: Int, actorNameUpdateRequestDto: ActorNameUpdateRequestDto): Mono<ActorAggregate>
fun deleteActor(id: Int): Mono<Boolean>
}
interface MovieManagementUseCase {
fun addMovie(movieAddRequestDto: MovieAddRequestDto): Mono<MovieAggregate>
fun updateMovie(id: Int, movieUpdateRequestDto: MovieUpdateRequestDto): Mono<MovieAggregate>
fun deleteMovie(id: Int): Mono<Boolean>
}
interface MovieActorManagementUseCase {
fun includeActorInMovieActor(movieId: Int, actorId: Int): Mono<Boolean>
fun excludeActorFromMovieActor(movieId: Int, actorId: Int): Mono<Boolean>
}
| 0
|
Kotlin
|
0
| 0
|
b3fe748930f4372e09648ad626a5ad08382b5bd3
| 1,187
|
sakila-microservices
|
Apache License 2.0
|
android/app/src/main/java/cloud/multipos/pos/views/CustomerTenderLine.kt
|
multipos-app
| 773,180,579
| false
|
{"Kotlin": 548453, "Java": 306036}
|
/**
* Copyright (C) 2023 multiPOS, LLC
*
* 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 cloud.multipos.pos.views
import cloud.multipos.pos.R
import cloud.multipos.pos.Pos
import cloud.multipos.pos.models.TicketItem
import cloud.multipos.pos.models.TicketTender
import cloud.multipos.pos.util.*
import android.content.Context
import android.util.AttributeSet
import androidx.core.content.ContextCompat
import androidx.core.widget.TextViewCompat
import android.widget.LinearLayout
import android.widget.LinearLayout.LayoutParams
import java.util.Optional
import android.view.View
import android.view.MotionEvent
class CustomerTenderLine (context: Context, tt: TicketTender, pos: Int): LinearLayout (context) {
init {
Pos.app.inflater.inflate (R.layout.customer_ticket_tender_line, this);
var ta = this.findViewById (R.id.customer_ticket_tender_total) as PosText
var pa = this.findViewById (R.id.customer_ticket_tender_paid) as PosText
var ra = this.findViewById (R.id.customer_ticket_tender_returned) as PosText
ta.setText (Strings.currency (tt.getDouble ("amount"), false))
pa.setText (Strings.currency (tt.getDouble ("tendered_amount"), false))
ra.setText (Strings.currency (tt.getDouble ("returned_amount"), false))
if (pos % 2 == 1) {
setBackgroundResource (R.color.odd_bg)
}
else {
setBackgroundResource (R.color.even_bg)
}
}
}
| 0
|
Kotlin
|
1
| 7
|
119bb0c86a5f9589e0219249b02f0f56d43120f7
| 1,946
|
pos
|
Apache License 2.0
|
백준/제로.kt
|
jisungbin
| 382,889,087
| false
| null |
import java.io.BufferedReader
import java.io.BufferedWriter
import java.io.InputStreamReader
import java.io.OutputStreamWriter
fun main() {
val br = BufferedReader(InputStreamReader(System.`in`))
val bw = BufferedWriter(OutputStreamWriter(System.out))
val deque = ArrayDeque<Int>()
List(br.readLine().toInt()) { br.readLine()!!.toInt() }.forEach { number ->
if (number == 0) {
deque.removeLastOrNull()
} else {
deque.addLast(number)
}
}
bw.write("${deque.sum()}\n")
br.close()
bw.flush()
bw.close()
}
| 0
|
Kotlin
|
1
| 9
|
215a0b0087f6ddbb65c7ac231a749f8e7d8bd827
| 588
|
algorithm-code
|
MIT License
|
android/anc/src/test/java/org/smartregister/fhircore/anc/ui/details/careplan/CarePlanDetailsFragmentTest.kt
|
issyzac
| 420,960,297
| true
|
{"Kotlin": 1058894}
|
/*
* Copyright 2021 Ona Systems, Inc
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* 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.smartregister.fhircore.anc.ui.details.careplan
import android.view.View
import android.widget.TextView
import androidx.arch.core.executor.testing.InstantTaskExecutorRule
import androidx.fragment.app.Fragment
import androidx.fragment.app.FragmentFactory
import androidx.fragment.app.testing.FragmentScenario
import androidx.fragment.app.testing.launchFragmentInContainer
import androidx.lifecycle.Lifecycle
import androidx.recyclerview.widget.RecyclerView
import com.google.android.fhir.FhirEngine
import io.mockk.coEvery
import io.mockk.every
import io.mockk.mockk
import io.mockk.spyk
import io.mockk.verify
import kotlinx.coroutines.ExperimentalCoroutinesApi
import kotlinx.coroutines.test.runBlockingTest
import org.junit.Assert
import org.junit.Before
import org.junit.Rule
import org.junit.Test
import org.robolectric.Robolectric
import org.robolectric.annotation.Config
import org.robolectric.util.ReflectionHelpers
import org.smartregister.fhircore.anc.R
import org.smartregister.fhircore.anc.coroutine.CoroutineTestRule
import org.smartregister.fhircore.anc.data.model.AncPatientDetailItem
import org.smartregister.fhircore.anc.data.model.AncPatientItem
import org.smartregister.fhircore.anc.data.model.CarePlanItem
import org.smartregister.fhircore.anc.data.model.UpcomingServiceItem
import org.smartregister.fhircore.anc.data.patient.PatientRepository
import org.smartregister.fhircore.anc.robolectric.FragmentRobolectricTest
import org.smartregister.fhircore.anc.shadow.AncApplicationShadow
import org.smartregister.fhircore.anc.ui.details.PatientDetailsActivity
import org.smartregister.fhircore.anc.ui.details.adapter.CarePlanAdapter
import org.smartregister.fhircore.anc.ui.details.adapter.UpcomingServicesAdapter
@ExperimentalCoroutinesApi
@Config(shadows = [AncApplicationShadow::class])
internal class CarePlanDetailsFragmentTest : FragmentRobolectricTest() {
private lateinit var fhirEngine: FhirEngine
private lateinit var patientDetailsViewModel: CarePlanDetailsViewModel
private lateinit var patientDetailsActivity: PatientDetailsActivity
private lateinit var patientRepository: PatientRepository
private lateinit var fragmentScenario: FragmentScenario<CarePlanDetailsFragment>
private lateinit var patientDetailsFragment: CarePlanDetailsFragment
private lateinit var carePlanAdapter: CarePlanAdapter
private lateinit var upcomingServicesAdapter: UpcomingServicesAdapter
@get:Rule var coroutinesTestRule = CoroutineTestRule()
@get:Rule var instantTaskExecutorRule = InstantTaskExecutorRule()
private val patientId = "samplePatientId"
var ancPatientDetailItem = spyk<AncPatientDetailItem>()
@Before
fun setUp() {
fhirEngine = mockk(relaxed = true)
patientRepository = mockk()
carePlanAdapter = mockk()
upcomingServicesAdapter = mockk()
every { carePlanAdapter.submitList(any()) } returns Unit
every { upcomingServicesAdapter.submitList(any()) } returns Unit
every { ancPatientDetailItem.patientDetails } returns
AncPatientItem(patientId, "<NAME>", "M", "26")
every { ancPatientDetailItem.patientDetailsHead } returns AncPatientItem()
coEvery { patientRepository.fetchDemographics(patientId) } returns ancPatientDetailItem
patientDetailsViewModel =
spyk(
CarePlanDetailsViewModel(
patientRepository,
coroutinesTestRule.testDispatcherProvider,
patientId
)
)
patientDetailsActivity =
Robolectric.buildActivity(PatientDetailsActivity::class.java).create().get()
fragmentScenario =
launchFragmentInContainer(
factory =
object : FragmentFactory() {
override fun instantiate(classLoader: ClassLoader, className: String): Fragment {
val fragment = spyk(CarePlanDetailsFragment.newInstance())
every { fragment.activity } returns patientDetailsActivity
fragment.ancDetailsViewModel = patientDetailsViewModel
return fragment
}
}
)
fragmentScenario.onFragment {
patientDetailsFragment = it
ReflectionHelpers.setField(patientDetailsFragment, "carePlanAdapter", carePlanAdapter)
ReflectionHelpers.setField(
patientDetailsFragment,
"upcomingServicesAdapter",
upcomingServicesAdapter
)
}
}
@Test
fun testHandleCarePlanShouldVerifyExpectedCalls() {
ReflectionHelpers.callInstanceMethod<Any>(
patientDetailsFragment,
"handleCarePlan",
ReflectionHelpers.ClassParameter(List::class.java, listOf<CarePlanItem>())
)
// No CarePlan available text displayed
val noVaccinesTextView =
patientDetailsFragment.view?.findViewById<TextView>(R.id.txtView_noCarePlan)
// CarePlan list is not displayed
val immunizationsListView =
patientDetailsFragment.view?.findViewById<RecyclerView>(R.id.carePlanListView)
Assert.assertEquals(View.VISIBLE, noVaccinesTextView?.visibility)
Assert.assertEquals(View.GONE, immunizationsListView?.visibility)
ReflectionHelpers.callInstanceMethod<Any>(
patientDetailsFragment,
"handleCarePlan",
ReflectionHelpers.ClassParameter(
List::class.java,
listOf(CarePlanItem("1111", "", due = true, overdue = false))
)
)
Assert.assertEquals(View.GONE, noVaccinesTextView?.visibility)
Assert.assertEquals(View.VISIBLE, immunizationsListView?.visibility)
verify(exactly = 1) { carePlanAdapter.submitList(any()) }
}
@Test
fun testHandleEncounterShouldVerifyExpectedCalls() {
ReflectionHelpers.callInstanceMethod<Any>(
patientDetailsFragment,
"handleEncounters",
ReflectionHelpers.ClassParameter(List::class.java, listOf<UpcomingServiceItem>())
)
// No CarePlan available text displayed
val noVaccinesTextView =
patientDetailsFragment.view?.findViewById<TextView>(R.id.txtView_noUpcomingServices)
// CarePlan list is not displayed
val immunizationsListView =
patientDetailsFragment.view?.findViewById<RecyclerView>(R.id.upcomingServicesListView)
Assert.assertEquals(View.VISIBLE, noVaccinesTextView?.visibility)
Assert.assertEquals(View.GONE, immunizationsListView?.visibility)
ReflectionHelpers.callInstanceMethod<Any>(
patientDetailsFragment,
"handleEncounters",
ReflectionHelpers.ClassParameter(
List::class.java,
listOf(UpcomingServiceItem("1111", "ABC", "2020-02-01"))
)
)
Assert.assertEquals(View.GONE, noVaccinesTextView?.visibility)
Assert.assertEquals(View.VISIBLE, immunizationsListView?.visibility)
verify(exactly = 1) { upcomingServicesAdapter.submitList(any()) }
}
override fun getFragmentScenario(): FragmentScenario<out Fragment> {
return fragmentScenario
}
override fun getFragment(): Fragment {
return patientDetailsFragment
}
@Test
fun testThatCarePlansAreUpdated() {
coroutinesTestRule.runBlockingTest { fragmentScenario.moveToState(Lifecycle.State.RESUMED) }
}
}
| 0
| null |
0
| 0
|
c4eb29dc58e6232dcee2431a77e082af7ed60421
| 7,651
|
fhircore
|
Apache License 2.0
|
app/src/main/kotlin/cz/covid19cz/erouska/ui/contacts/event/ContactsCommandEvent.kt
|
covid19cz
| 247,683,648
| false
| null |
package cz.covid19cz.erouska.ui.contacts.event
sealed class ContactsEvent {
data class ContactLinkClicked(val link: String) : ContactsEvent()
}
| 0
|
Kotlin
|
57
| 205
|
23064413869fe7ba3d083beb9e6c639b59abfbcc
| 148
|
erouska-android
|
MIT License
|
app/src/main/java/com/brimanning/mydatabinding/MainViewModel.kt
|
brimanning
| 243,368,764
| false
| null |
package com.brimanning.mydatabinding
import androidx.annotation.StringRes
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
class MainViewModel : ViewModel() {
val count = MutableLiveData<Int>()
val entryValue = MutableLiveData<String>()
val flipFlop = MutableLiveData<@StringRes Int>()
val flipFlopModel = MutableLiveData<FlipFlopModel>()
init {
count.value = 0
flipOrFlop()
}
fun incrementCount() {
count.value = count.value?.inc()
}
private fun flipOrFlop() {
if (flipFlop.value == R.string.flip) {
flipFlop.value = R.string.flop
} else {
flipFlop.value = R.string.flip
}
if (flipFlopModel.value?.flipFlopString == R.string.flop) {
flipFlopModel.value = FlipFlopModel(R.string.flip)
} else {
flipFlopModel.value = FlipFlopModel(R.string.flop)
}
viewModelScope.launch {
delay(5000)
flipOrFlop()
}
}
data class FlipFlopModel(
@StringRes val flipFlopString: Int
)
}
| 0
|
Kotlin
|
0
| 0
|
07277ff013759756a90d592ff272a935ecc91398
| 1,225
|
databinding-examples
|
MIT License
|
Aquarium/src/example/myapp/main.kt
|
kaden-kykim
| 227,464,379
| false
| null |
package example.myapp
fun buildAquarium() {
makeFish()
val aquarium1 = Aquarium()
aquarium1.printSize()
val aquarium2 = Aquarium(width = 55)
aquarium2.printSize()
val aquarium3 = Aquarium(width = 60, height = 200, length = 400)
aquarium3.printSize()
val aquarium4 = Aquarium(numberOfFish = 100)
aquarium4.printSize()
aquarium4.volume = 70
aquarium4.printSize()
val tower1 = TowerTank(diameter = 25, height = 40)
tower1.printSize()
}
fun makeFish() {
val shark = Shark()
val placo = Plecostomus()
println("Shark: ${shark.color}")
shark.eat()
println("Plecostoms: ${placo.color}")
placo.eat()
}
fun main() {
buildAquarium()
}
| 0
|
Kotlin
|
0
| 0
|
6d301ae88287ab9fb7cf71c15da3170aca8f1209
| 709
|
CICCC-Android-Kotlin
|
MIT License
|
app/src/main/kotlin/net/kivitro/kittycat/view/activity/MainActivity.kt
|
maiktheknife
| 53,694,959
| false
| null |
package net.kivitro.kittycat.view.activity
import android.app.Activity
import android.content.Context
import android.content.Intent
import android.os.Bundle
import android.os.Parcelable
import android.preference.PreferenceManager
import android.support.v4.widget.SwipeRefreshLayout
import android.support.v7.app.AppCompatActivity
import android.support.v7.widget.DefaultItemAnimator
import android.support.v7.widget.StaggeredGridLayoutManager
import android.support.v7.widget.Toolbar
import android.view.Menu
import android.view.MenuItem
import android.view.View
import android.widget.AdapterView
import kotlinx.android.synthetic.main.ac_main.*
import kotlinx.android.synthetic.main.view_content.*
import kotlinx.android.synthetic.main.view_error.*
import kotlinx.android.synthetic.main.view_loading.*
import net.kivitro.kittycat.R
import net.kivitro.kittycat.model.Cat
import net.kivitro.kittycat.model.Category
import net.kivitro.kittycat.presenter.MainPresenter
import net.kivitro.kittycat.snack
import net.kivitro.kittycat.view.MainView
import net.kivitro.kittycat.view.adapter.CategoryAdapter
import net.kivitro.kittycat.view.adapter.KittyAdapter
import timber.log.Timber
class MainActivity : AppCompatActivity(), MainView, SwipeRefreshLayout.OnRefreshListener {
private lateinit var presenter: MainPresenter
private lateinit var layoutManager: StaggeredGridLayoutManager
private lateinit var adapter: KittyAdapter
private lateinit var spinnerAdapter: CategoryAdapter
private var spinnerInit = false
private var firstLoad = true
private var isGridView = true
private var selectedNavItem = 0
private var kittens: List<Cat>? = null
private var categories: List<Category>? = null
private enum class State {
LOADING, ERROR, CONTENT
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.ac_main)
setSupportActionBar(findViewById<Toolbar>(R.id.toolbar))
presenter = MainPresenter()
presenter.attachView(this)
ac_main_swipeLayout.apply {
setOnRefreshListener(this@MainActivity)
setColorSchemeResources(R.color.colorAccent, R.color.colorPrimary)
}
ac_main_error_btn.setOnClickListener { loadKittiesIfPossible(favourites = intent.extras?.getString("shortcut") == "favourites") }
ac_bottom_navigation.setOnNavigationItemReselectedListener { }
ac_bottom_navigation.setOnNavigationItemSelectedListener { menuItem ->
when (menuItem.itemId) {
R.id.action_random -> {
Timber.d("bottom nav select action_random")
selectedNavItem = 0
ac_main_spinner.visibility = View.VISIBLE
loadKittiesIfPossible(false)
true
}
R.id.action_favorites -> {
Timber.d("bottom nav select action_favorites")
selectedNavItem = 1
ac_main_spinner.visibility = View.INVISIBLE
loadKittiesIfPossible(true)
true
}
R.id.action_settings -> {
Timber.d("bottom nav select action_settings")
presenter.onSettingsClicked()
false
}
else -> false
}
}
spinnerAdapter = CategoryAdapter()
ac_main_spinner.adapter = spinnerAdapter
ac_main_spinner.onItemSelectedListener = object : AdapterView.OnItemSelectedListener {
override fun onItemSelected(parent: AdapterView<*>?, view: View?, position: Int, id: Long) {
Timber.d("onItemSelected")
if (spinnerInit) {
loadKittiesIfPossible()
} else {
spinnerInit = true
}
}
override fun onNothingSelected(parent: AdapterView<*>?) {
Timber.d("onNothingSelected")
}
}
initRecyclerView(presenter)
val preferences = PreferenceManager.getDefaultSharedPreferences(this)
var sub_id = preferences.getInt(PREF_SUB_ID, -1)
if (sub_id == -1) {
sub_id = (Math.random() * 10000000).toInt()
preferences.edit().putInt(PREF_SUB_ID, sub_id).apply()
}
Timber.d("sub_id %s", sub_id)
if (savedInstanceState != null) {
Timber.d("onCreate with savedState")
firstLoad = false
showState(State.CONTENT)
onKittensLoaded(savedInstanceState.getParcelableArrayList<Parcelable>(EXTRA_KITTENS) as List<Cat>)
onCategoriesLoaded(savedInstanceState.getParcelableArrayList<Parcelable>(EXTRA_CATEGORIES) as List<Category>)
} else {
Timber.d("onCreate without savedState")
val fromFavoritesShortcut = intent.extras?.getString("shortcut") == "favourites"
loadKittiesIfPossible(favourites = fromFavoritesShortcut)
selectedNavItem = if (fromFavoritesShortcut) 1 else 0
ac_bottom_navigation.menu.getItem(selectedNavItem).isChecked = true
}
}
override fun onSaveInstanceState(outState: Bundle) {
super.onSaveInstanceState(outState)
Timber.d("onSaveInstanceState")
kittens?.let {
outState.putParcelableArrayList(EXTRA_KITTENS, it as ArrayList<Cat>)
}
categories?.let {
outState.putParcelableArrayList(EXTRA_CATEGORIES, it as ArrayList<Category>)
}
}
override fun onStart() {
super.onStart()
presenter.attachView(this)
}
override fun onStop() {
super.onStop()
presenter.detachView()
}
override fun onCreateOptionsMenu(menu: Menu): Boolean {
menuInflater.inflate(R.menu.menu_main, menu)
return true
}
override fun onOptionsItemSelected(item: MenuItem) = when (item.itemId) {
R.id.action_toggle -> {
toggleView(item)
true
}
else -> super.onOptionsItemSelected(item)
}
private fun toggleView(item: MenuItem) {
if (isGridView) {
layoutManager.spanCount = SPAN_LIST
item.setIcon(R.mipmap.ic_action_grid)
isGridView = false
} else {
layoutManager.spanCount = SPAN_GRID
item.setIcon(R.mipmap.ic_action_list)
isGridView = true
}
}
private fun initRecyclerView(presenter: MainPresenter) {
ac_main_recyclerView.setHasFixedSize(true)
ac_main_recyclerView.itemAnimator = DefaultItemAnimator()
layoutManager = StaggeredGridLayoutManager(SPAN_GRID, StaggeredGridLayoutManager.VERTICAL)
ac_main_recyclerView.layoutManager = layoutManager
adapter = KittyAdapter(presenter)
ac_main_recyclerView.adapter = adapter
}
private fun loadKittiesIfPossible(favourites: Boolean = false) {
if (firstLoad) {
showState(State.LOADING)
presenter.loadCategories()
}
if (favourites) {
presenter.loadFavourites()
} else {
val category = ac_main_spinner.selectedItem as Category?
if (Category.ALL == category) {
presenter.loadKittens(null)
} else {
presenter.loadKittens(category?.name)
}
}
}
private fun showState(state: State) {
Timber.d("showState %s", state)
when (state) {
State.LOADING -> {
ac_main_loading_view.visibility = View.VISIBLE
ac_main_error_layout.visibility = View.GONE
ac_main_swipeLayout.visibility = View.GONE
}
State.ERROR -> {
ac_main_loading_view.visibility = View.GONE
ac_main_error_layout.visibility = View.VISIBLE
ac_main_swipeLayout.visibility = View.GONE
}
State.CONTENT -> {
ac_main_loading_view.visibility = View.GONE
ac_main_error_layout.visibility = View.GONE
ac_main_swipeLayout.visibility = View.VISIBLE
}
}
}
/* @{link SwipeRefreshLayout.OnRefreshListener}*/
override fun onRefresh() {
Timber.d("onRefresh")
loadKittiesIfPossible(favourites = selectedNavItem == 1)
}
/* @{link MainView} */
override val activity: Activity
get() = this
override fun onKittensLoaded(kittens: List<Cat>) {
Timber.d("onKittensLoaded %d", kittens.size)
this.firstLoad = false
this.kittens = kittens
adapter.addItems(kittens)
ac_main_swipeLayout.isRefreshing = false
showState(State.CONTENT)
}
override fun onKittensLoadError(message: String) {
Timber.d("onKittensLoadError %s", message)
ac_main_container.snack("Loading Error: $message")
ac_main_swipeLayout.isRefreshing = false
showState(State.ERROR)
}
override fun onCategoriesLoaded(categories: List<Category>) {
Timber.d("onCategoriesLoaded %d", categories.size)
this.categories = categories
spinnerAdapter.addItems(categories)
}
override fun onCategoriesLoadError(message: String) {
Timber.d("onCategoriesLoadError %s", message)
ac_main_container.snack("Loading Error: $message")
ac_main_swipeLayout.isRefreshing = false
}
override fun showNoConnection() {
Timber.d("showNoConnection")
ac_main_container.snack("No Connection")
ac_main_swipeLayout.isRefreshing = false
showState(State.ERROR)
}
companion object {
private const val EXTRA_KITTENS = "extra_kittens"
private const val EXTRA_CATEGORIES = "extra_categories"
private const val PREF_SUB_ID = "sub_id"
private const val SPAN_GRID = 2
private const val SPAN_LIST = 1
fun getStarterIntent(context: Context) = Intent(context, MainActivity::class.java)
}
}
| 0
|
Kotlin
|
0
| 0
|
a9c74da77e226817c7f7b5ad9d58d2389d936b8d
| 8,602
|
KittyCat
|
MIT License
|
im-commons/im-commons-api/src/main/kotlin/city/smartb/im/commons/utils/AddressUtils.kt
|
smartbcity
| 651,445,390
| false
| null |
package city.smartb.im.commons.utils
import city.smartb.im.commons.model.Address
fun Address?.orEmpty() = this ?: Address(
street = "",
postalCode = "",
city = ""
)
| 0
|
Kotlin
|
0
| 0
|
a85f09c5416ce211b671c14b13d25fbbe9804f3a
| 179
|
connect-im
|
Apache License 2.0
|
app/src/main/java/com/mozhimen/pagingk/test/crud/CrudActivity.kt
|
mozhimen
| 747,018,353
| false
|
{"Kotlin": 163458}
|
package com.mozhimen.pagingk.test.crud
import android.os.Bundle
import androidx.lifecycle.Observer
import androidx.recyclerview.widget.LinearLayoutManager
import com.mozhimen.basick.elemk.androidx.appcompat.bases.databinding.BaseActivityVDBVM
import com.mozhimen.pagingk.test.databinding.ActivityCrudBinding
class CrudActivity : BaseActivityVDBVM<ActivityCrudBinding, SampleViewModel>() {
private val sampleAdapter by lazy { SampleAdapter(vm) }
override fun initView(savedInstanceState: Bundle?) {
vdb.rvItems.apply {
layoutManager = LinearLayoutManager(this@CrudActivity)
adapter = sampleAdapter.withLoadStateFooter(DefaultLoadStateAdapter())
}
vdb.swipeRefreshLayout.apply {
setOnRefreshListener {
sampleAdapter.refresh()
isRefreshing = false
}
}
vdb.btInsertHeaderItem.setOnClickListener {
vm.onViewEvent(SampleViewEvents.InsertItemHeader)
}
vdb.btInsertFooterItem.setOnClickListener {
vm.onViewEvent(SampleViewEvents.InsertItemFooter)
}
}
override fun initObserver() {
vm.pagingDataViewStates.observe(this, Observer { pagingData ->
sampleAdapter.submitData(this.lifecycle, pagingData)
})
}
override fun bindViewVM(vb: ActivityCrudBinding) {
}
}
| 0
|
Kotlin
|
2
| 2
|
c9489f45b7f053e7778c3b40cc62041f3e54e80c
| 1,380
|
APagingKit
|
Apache License 2.0
|
base/media/medialib/src/main/kotlin/com/flammky/musicplayer/dump/mediaplayer/helper/external/providers/DocumentProviderHelper.kt
|
flammky
| 462,795,948
| false
| null |
package com.flammky.musicplayer.dump.mediaplayer.helper.external.providers
import android.content.ContentResolver
import android.content.ContentUris
import android.content.Context
import android.net.Uri
import android.os.Environment
import android.provider.DocumentsContract
import android.provider.MediaStore
import android.provider.OpenableColumns
import com.flammky.android.kotlin.coroutine.AndroidCoroutineDispatchers
import dev.dexsr.klio.core.sdk.AndroidAPI
import dev.dexsr.klio.core.sdk.AndroidBuildVersion.hasQ
import dev.dexsr.klio.core.sdk.AndroidBuildVersion.hasR
import kotlinx.coroutines.withContext
import timber.log.Timber
import java.io.File
import java.net.URLDecoder
import kotlin.coroutines.coroutineContext
// TODO: Organize This Better
object DocumentProviderHelper {
const val auth_provider_externalStorage = "com.android.externalstorage"
const val auth_provider_media = "com.android.providers.media"
const val auth_provider_download = "com.android.providers.downloads"
const val contentScheme = ContentResolver.SCHEME_CONTENT
const val fileScheme = ContentResolver.SCHEME_FILE
@JvmStatic
val extStoragePath: File?
get() = Environment.getExternalStorageDirectory()
@JvmStatic
val extStoragePathString
get() = extStoragePath?.toString() ?: "/storage/emulated/0"
@JvmStatic
val storagePath
get() = if (AndroidAPI.hasR()) {
Environment.getStorageDirectory().toString()
} else {
"/storage"
}
@Suppress("BlockingMethodInNonBlockingContext")
suspend fun decodeUrl(url: String, enc: String = "UTF-8"): String {
return withContext(coroutineContext) { URLDecoder.decode(url, enc) }
}
private val dispatchers = AndroidCoroutineDispatchers.DEFAULT
suspend fun getAudioPathFromContentUri(
context: Context,
uri: Uri
): String {
return try {
require(DocumentsContract.isDocumentUri(context, uri))
val fileName = withContext(dispatchers.io) {
context.contentResolver.query(uri, null, null, null, null)
?.use { cursor ->
cursor.moveToFirst()
val dataIndex = cursor.getColumnIndex(MediaStore.Audio.AudioColumns.DATA)
val nameIndex = cursor.getColumnIndexOrThrow(OpenableColumns.DISPLAY_NAME)
if (dataIndex > -1) {
val data = cursor.getString(dataIndex)
if (File(data).exists()) return@withContext data
}
cursor.getString(nameIndex)
}
}
requireNotNull(fileName)
if (fileName.startsWith(storagePath) && File(fileName).exists()) {
return fileName
}
val tries = when {
uri.authority!!.startsWith(auth_provider_externalStorage) -> {
tryExternalStorageProvider(fileName, uri)
}
uri.authority!!.startsWith(auth_provider_download) -> {
tryDownloadProvider(context, fileName, uri)
}
uri.authority!!.startsWith(auth_provider_media) -> {
tryMediaProvider(context, fileName, uri)
}
else -> null
}
if (tries != null) {
if ((tries.endsWith(fileName) && File(tries).exists())
|| tries.startsWith(MediaStore.Audio.Media.EXTERNAL_CONTENT_URI.toString())
) {
Timber.d("DocumentProviders returned $tries")
return tries
}
}
""
} catch (e: Exception) {
Timber.e(e)
""
}
}
private suspend fun tryExternalStorageProvider(fileName: String, uri: Uri): String {
require(fileName.isNotBlank())
val builder = StringBuilder()
val uriString = uri.toString()
val decodedUriString = decodeUrl(uriString)
val split2F = uriString.split("/")
val split3A = uriString.split(":")
val dSplit2F = decodedUriString.split("/")
val dSplit3A = decodedUriString.split(":")
/* primary:Directory is the common result*/
val prim = run {
val bPrim = StringBuilder()
if (dSplit3A.size > 1) {
// there is ":" other than "content:" in decoded Url
if (split2F.size > 4) {
// plain split "/" url has index 4
// which is likely to be storage path in case of document provider
if (dSplit3A[1].endsWith(dSplit2F[4].split(":").first())) {
// decoded split ":" second index which after content://
// does ends with the starting string of decoded "/"
bPrim.append(dSplit2F[4])
}
}
}
bPrim.toString()
}
when {
prim.isNotEmpty() -> {
val primPrefix = prim.split(":")[0]
val primSuffix = prim.split(":")[1]
val directory = dSplit3A[2]
if (primPrefix == "primary") {
if (directory.endsWith(fileName)) {
builder.append("$extStoragePathString/$directory")
}
} else {
if (directory.endsWith(fileName)) {
builder.append("$storagePath/$primPrefix/$directory")
}
}
}
}
return builder.toString()
}
private suspend fun tryDownloadProvider(context: Context, fileName: String, uri: Uri): String {
require(fileName.isNotBlank())
val stringBuilder = StringBuilder()
val uriString = uri.toString()
val decodedUriString = decodeUrl(uriString)
val dSplit2F = decodedUriString.split("/")
val dSplit3A = decodedUriString.split(":")
return withContext(dispatchers.io) {
if (dSplit3A[2].startsWith(extStoragePathString) && dSplit2F.last() == fileName) {
return@withContext dSplit3A[2]
}
val fUri = when {
AndroidAPI.hasQ() && dSplit2F.last().startsWith("msf") -> {
val mime = context.contentResolver.query(uri, null, null, null, null)
?.use { cursor ->
cursor.moveToFirst()
cursor.getString(cursor.getColumnIndexOrThrow(MediaStore.MediaColumns.MIME_TYPE))
}
if (mime?.startsWith("audio") == true) {
val extContentUri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI
ContentUris.withAppendedId(extContentUri, dSplit2F.last().filter(Char::isDigit).toLong())
} else {
uri
}
}
else -> uri
}
context.contentResolver.query(fUri, null, null, null, null)
?.use { cursor ->
cursor.moveToFirst()
val dataIndex = cursor.getColumnIndex(MediaStore.MediaColumns.DATA)
val nameIndex = cursor.getColumnIndexOrThrow(OpenableColumns.DISPLAY_NAME)
if (dataIndex > -1) {
val data = cursor.getString(dataIndex)
if (data.endsWith(fileName)) stringBuilder.append(data)
} else {
val name = cursor.getString(nameIndex)
if (fileName == name) {
stringBuilder.append("$extStoragePathString/${Environment.DIRECTORY_DOWNLOADS}/$name")
}
}
}
stringBuilder.toString()
}
}
private suspend fun tryMediaProvider(context: Context, filename: String, uri: Uri): String {
val stringBuilder = StringBuilder()
val id = withContext(dispatchers.io) {
context.contentResolver.query(uri, null, null, null, null)
?.use { cursor ->
cursor.moveToFirst()
val i = cursor.getColumnIndex(DocumentsContract.Document.COLUMN_DOCUMENT_ID)
cursor.getString(i)
}
}
if (id != null) {
val fUri = ContentUris.withAppendedId(
MediaStore.Audio.Media.EXTERNAL_CONTENT_URI,
id.filter(Char::isDigit).toLong()
)
context.contentResolver.query(fUri, null, null, null, null)
?.use { cursor ->
cursor.moveToFirst()
val name = cursor.getString(cursor.getColumnIndexOrThrow(OpenableColumns.DISPLAY_NAME))
if (name == filename) stringBuilder.append(fUri)
}
}
return stringBuilder.toString()
}
@JvmStatic fun isStoragePath(path: String) = path.startsWith("$storagePath/")
@JvmStatic fun isStoragePathExist(path: String) = isStoragePath(path) && File(path).exists()
@JvmStatic
fun isExternalStoragePath(path: String) = path.startsWith("$extStoragePathString/")
@JvmStatic
fun isExternalStoragePathExist(path: String) = isExternalStoragePath(path) && File(path).exists()
}
| 0
| null |
6
| 56
|
a452c453815851257462623be704559d306fb383
| 8,148
|
Music-Player
|
Apache License 2.0
|
src/main/kotlin/com/helltar/artific_intellig_bot/commands/admin/ChatAsVoiceCommand.kt
|
Helltar
| 591,327,331
| false
| null |
package com.helltar.artific_intellig_bot.commands.admin
import com.github.kotlintelegrambot.Bot
import com.github.kotlintelegrambot.entities.Message
import com.helltar.artific_intellig_bot.DIR_DB
import com.helltar.artific_intellig_bot.Strings
import com.helltar.artific_intellig_bot.commands.BotCommand
import com.helltar.artific_intellig_bot.commands.Commands.cmdChatAsText
import com.helltar.artific_intellig_bot.commands.Commands.cmdChatAsVoice
import org.slf4j.LoggerFactory
import java.io.File
import java.io.IOException
class ChatAsVoiceCommand(bot: Bot, message: Message) : BotCommand(bot, message) {
override fun run() {
File(DIR_DB + cmdChatAsText).run {
if (exists())
try {
delete()
File(DIR_DB + cmdChatAsVoice).createNewFile()
sendMessage(Strings.chat_as_voice_ok)
} catch (e: IOException) {
sendMessage("❌ <code>${e.message}</code>")
LoggerFactory.getLogger(javaClass).error(e.message)
}
else
sendMessage(Strings.chat_as_voice_already_enabled)
}
}
}
| 0
|
Kotlin
|
0
| 5
|
a2946eeb658feb8755e7ba5a3c7c0662a43c9adb
| 1,179
|
artific_intellig_bot
|
MIT License
|
app/src/main/java/com/movie/app/shared/data/model/Movie.kt
|
ShabanKamell
| 203,558,411
| false
| null |
package com.movie.app.shared.data.model
import com.google.gson.annotations.SerializedName
data class Movie(
@SerializedName("poster_path")
var posterPath: String?,
@field:SerializedName("adult")
var isAdult: Boolean,
@field:SerializedName("overview")
var overview: String?,
@field:SerializedName("release_date")
var releaseDate: String?,
@field:SerializedName("genre_ids")
var genreIds: List<Int>?,
@field:SerializedName("id")
var id: Int?,
@field:SerializedName("original_title")
var originalTitle: String?,
@field:SerializedName("original_language")
var originalLanguage: String?,
@field:SerializedName("title")
var title: String?,
@field:SerializedName("backdrop_path")
var backdropPath: String?,
@field:SerializedName("popularity")
var popularity: Double?,
@field:SerializedName("vote_count")
var voteCount: Int?,
@field:SerializedName("video")
var video: Boolean?,
@field:SerializedName("vote_average")
var voteAverage: Double?,
@Transient var latPage: Int = 0
)
{
fun poster(): String? {
if (posterPath == null) return null
return "https://image.tmdb.org/t/p/w500$posterPath"
}
override fun toString(): String = title ?: ""
}
| 1
|
Kotlin
|
1
| 1
|
fc6a5382d9ba85e5313c8286a1150787d2f9a512
| 1,438
|
Movies
|
Apache License 2.0
|
presentation/src/main/java/com/sarangmorde/mycv/view/adapter/EducationListAdapter.kt
|
sarangmorde
| 206,545,844
| false
| null |
package com.sarangmorde.mycv.view.adapter
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.recyclerview.widget.RecyclerView
import com.sarangmorde.mycv.R
import com.sarangmorde.mycv.domain.model.Education
import com.sarangmorde.mycv.view.adapter.viewholder.MyCvViewHolder
import kotlinx.android.synthetic.main.layout_education_item.view.text_area
import kotlinx.android.synthetic.main.layout_education_item.view.text_courses
import kotlinx.android.synthetic.main.layout_education_item.view.text_gpa
import kotlinx.android.synthetic.main.layout_education_item.view.text_institution
import kotlinx.android.synthetic.main.layout_education_item.view.text_period
import kotlinx.android.synthetic.main.layout_education_item.view.text_study_type
class EducationListAdapter : RecyclerView.Adapter<MyCvViewHolder<Education?>>() {
var educationList = mutableListOf<Education?>()
set(value) {
field = value
notifyDataSetChanged()
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): MyCvViewHolder<Education?> =
ProfileListViewHolder(
LayoutInflater.from(parent.context).inflate(
R.layout.layout_education_item,
parent,
false
)
)
override fun getItemCount(): Int = educationList.size
override fun onBindViewHolder(holder: MyCvViewHolder<Education?>, position: Int) {
holder.setData(educationList[position])
}
class ProfileListViewHolder(itemView: View) : MyCvViewHolder<Education?>(itemView) {
override fun setData(data: Education?) {
data ?: return
itemView.run {
text_institution.text = data.institution
text_area.text = data.area
text_study_type.text = data.studyType
text_period.text =
resources.getString(R.string.period, data.startDate, data.endDate)
text_gpa.text = resources.getString(R.string.gpa, data.gpa)
text_courses.text =
resources.getString(R.string.courses, data.courses?.joinToString { it ?: "" })
}
}
}
}
| 0
|
Kotlin
|
0
| 0
|
fe50e51460435c0d06d5fda0ebc502859267b2c2
| 2,244
|
My-CV
|
MIT License
|
uast/uast-kotlin-base/src/org/jetbrains/uast/kotlin/BaseKotlinUastResolveProviderService.kt
|
JetBrains
| 278,369,660
| false
| null |
/*
* Copyright 2010-2021 JetBrains s.r.o. and Kotlin Programming Language contributors.
* Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file.
*/
package org.jetbrains.uast.kotlin
import com.intellij.psi.PsiClass
import com.intellij.psi.PsiElement
import com.intellij.psi.PsiMethod
import com.intellij.psi.PsiType
import org.jetbrains.kotlin.psi.*
import org.jetbrains.kotlin.types.typeUtil.TypeNullability
import org.jetbrains.uast.UElement
import org.jetbrains.uast.UExpression
import org.jetbrains.uast.UNamedExpression
import org.jetbrains.uast.UastCallKind
interface BaseKotlinUastResolveProviderService {
fun isJvmElement(psiElement: PsiElement): Boolean
// ----------
// Conversion
// ----------
val baseKotlinConverter: BaseKotlinConverter
fun convertParent(uElement: UElement): UElement?
fun convertParent(uElement: UElement, parent: PsiElement?): UElement?
fun convertValueArguments(ktCallElement: KtCallElement, parent: UElement): List<UNamedExpression>?
fun findDefaultValueForAnnotationAttribute(ktCallElement: KtCallElement, name: String): KtExpression?
fun getArgumentForParameter(ktCallElement: KtCallElement, index: Int, parent: UElement): UExpression?
fun getImplicitReturn(ktLambdaExpression: KtLambdaExpression, parent: UElement): KotlinUImplicitReturnExpression?
fun getImplicitParameters(ktLambdaExpression: KtLambdaExpression, parent: UElement): List<KotlinUParameter>
// ----------
// Resolution
// ----------
fun getReferenceVariants(ktExpression: KtExpression, nameHint: String): Sequence<PsiElement>
fun resolveCall(ktElement: KtElement): PsiMethod?
fun isResolvedToExtension(ktCallElement: KtCallElement): Boolean
fun resolvedFunctionName(ktCallElement: KtCallElement): String?
fun qualifiedAnnotationName(ktCallElement: KtCallElement): String?
fun callKind(ktCallElement: KtCallElement): UastCallKind
fun isAnnotationConstructorCall(ktCallElement: KtCallElement): Boolean
fun resolveToClassIfConstructorCall(ktCallElement: KtCallElement, source: UElement): PsiClass?
fun resolveToClass(ktAnnotationEntry: KtAnnotationEntry): PsiClass?
fun resolveToDeclaration(ktExpression: KtExpression): PsiElement?
fun resolveToType(ktTypeReference: KtTypeReference, source: UElement): PsiType?
// ----------
// Types
// ----------
fun getReceiverType(ktCallElement: KtCallElement, source: UElement): PsiType?
fun getDoubleColonReceiverType(ktDoubleColonExpression: KtDoubleColonExpression, source: UElement): PsiType?
fun getCommonSupertype(left: KtExpression, right: KtExpression, uExpression: UExpression): PsiType?
fun getType(ktExpression: KtExpression, parent: UElement): PsiType?
fun getType(ktDeclaration: KtDeclaration, parent: UElement): PsiType?
fun getFunctionType(ktFunction: KtFunction, parent: UElement): PsiType?
fun getFunctionalInterfaceType(uLambdaExpression: KotlinULambdaExpression): PsiType?
fun nullability(psiElement: PsiElement): TypeNullability?
// ----------
// Evaluation
// ----------
fun evaluate(uExpression: UExpression): Any?
}
| 0
| null |
29
| 71
|
b6789690db56407ae2d6d62746fb69dc99d68c84
| 3,238
|
intellij-kotlin
|
Apache License 2.0
|
wiki-webview/app/src/main/java/work/wander/wikiview/framework/toast/Toaster.kt
|
awallace87
| 797,502,762
| false
|
{"Kotlin": 642774}
|
package work.wander.wikiview.framework.toast
import android.content.Context
import android.widget.Toast
import dagger.hilt.android.qualifiers.ApplicationContext
import javax.inject.Inject
/**
* Interface to show toast messages.
*/
interface Toaster {
/**
* Show a toast message.
*
* @param message The message to be displayed.
* @param duration The duration of the toast message.
*/
fun showToast(message: String, duration: Int = Toast.LENGTH_SHORT)
}
/**
* Default implementation of the [Toaster] interface.
*/
class DefaultToaster @Inject constructor(
@ApplicationContext private val context: Context
) : Toaster {
override fun showToast(message: String, duration: Int) {
Toast.makeText(context, message, duration).show()
}
}
| 0
|
Kotlin
|
0
| 0
|
96d8356effa540198259646b87f751c3e08fc8bc
| 789
|
android-sample-apps
|
Apache License 2.0
|
common/src/main/java/io/github/pelmenstar1/digiDict/common/EmptyArray.kt
|
pelmenstar1
| 512,710,767
| false
|
{"Kotlin": 1238378, "Python": 531}
|
package io.github.pelmenstar1.digiDict.common
object EmptyArray {
@JvmField
val BYTE = ByteArray(0)
@JvmField
val LONG = LongArray(0)
@JvmField
val INT = IntArray(0)
@JvmField
val STRING = emptyArray<String>()
}
| 6
|
Kotlin
|
0
| 3
|
62f9519a065f1b9f27d200636b07e11d88a270f6
| 247
|
DigiDictionary
|
MIT License
|
fluxo-core/src/commonMain/kotlin/kt/fluxo/core/strategy/LifoInputStrategy.kt
|
fluxo-kt
| 566,869,438
| false
| null |
package kt.fluxo.core.strategy
import kotlinx.coroutines.channels.BufferOverflow
import kotlinx.coroutines.channels.Channel
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.collectLatest
import kt.fluxo.core.InputStrategy
import kt.fluxo.core.dsl.InputStrategyScope
/**
* `Last-in, first-out` - strategy optimized for lots of events (e.g. user actions).
* Provides more responsiveness comparing to [Fifo][FifoInputStrategy], but can lose some intents!
*
* **IMPORTANT:** Cancels previous unfinished intents when receives new one!
*
* Consider [Parallel][ParallelInputStrategy] if you steel need more responsiveness, but without dropping of any event.
*/
internal object LifoInputStrategy : InputStrategy() {
override fun <Request> createQueue(onUndeliveredElement: ((Request) -> Unit)?): Channel<Request> {
return Channel(
capacity = Channel.CONFLATED,
onBufferOverflow = BufferOverflow.SUSPEND,
onUndeliveredElement = onUndeliveredElement,
)
}
override val resendUndelivered: Boolean get() = false
override suspend fun <Request> (InputStrategyScope<Request>).processRequests(queue: Flow<Request>) {
queue.collectLatest(this)
}
}
| 3
|
Kotlin
|
0
| 5
|
475f65186b273f02e875c59176dd3a4af0b0365f
| 1,240
|
fluxo-mvi
|
Apache License 2.0
|
evervault-common/src/test/java/com/evervault/sdk/common/handlers/DictionaryHandlerTest.kt
|
evervault
| 650,073,299
| false
|
{"Kotlin": 326964, "Java": 1240, "Shell": 273}
|
package com.evervault.sdk.common.handlers
import org.junit.Assert.assertEquals
import org.junit.Assert.assertFalse
import org.junit.Assert.assertNotNull
import org.junit.Assert.assertTrue
import org.junit.Before
import org.junit.Test
import org.mockito.kotlin.anyOrNull
import org.mockito.kotlin.doAnswer
import org.mockito.kotlin.eq
import org.mockito.kotlin.mock
import org.mockito.kotlin.never
import org.mockito.kotlin.times
import org.mockito.kotlin.verify
internal class DictionaryHandlerTest {
private lateinit var contextMock: DataHandlerContext
private lateinit var handler: DictionaryHandler
@Before
fun setUp() {
contextMock = mock<DataHandlerContext> {
onGeneric { encrypt(anyOrNull(), anyOrNull()) } doAnswer { it.arguments.first() }
}
handler = DictionaryHandler()
}
@Test
fun testCanEncrypt() {
assertTrue(handler.canEncrypt(emptyMap<String, String>()))
assertTrue(handler.canEncrypt(mapOf("a" to "A", "b" to "B")))
assertTrue(handler.canEncrypt(mapOf(1 to 10, 2 to 20)))
assertTrue(handler.canEncrypt(mapOf("a" to 1, 2 to "b")))
assertTrue(handler.canEncrypt(mapOf("z" to mapOf("a" to 1, "b" to "B"), 2 to true)))
}
@Test
fun testCannotEncrypt() {
assertFalse(handler.canEncrypt("String value"))
assertFalse(handler.canEncrypt(1))
assertFalse(handler.canEncrypt(true))
assertFalse(handler.canEncrypt(false))
assertFalse(handler.canEncrypt(emptyList<String>()))
}
@Test
fun testEncryptEmptyStringDictionary() {
assertEquals(emptyMap<String, String>(), handler.encrypt(emptyMap<String, String>(), contextMock, "test-role"))
verify(contextMock, never()).encrypt(anyOrNull(), eq("test-role"))
}
@Test
fun testEncryptStringDictionary() {
assertEquals(mapOf("a" to "A", "b" to "B"), handler.encrypt(mapOf("a" to "A", "b" to "B"), contextMock, "test-role"))
verify(contextMock, times(2)).encrypt(anyOrNull(), eq("test-role"))
}
@Test
fun testEncryptNumbersDictionary() {
assertEquals(mapOf(1 to 10, 2 to 20), handler.encrypt(mapOf(1 to 10, 2 to 20), contextMock, "test-role"))
verify(contextMock, times(2)).encrypt(anyOrNull(), eq("test-role"))
}
@Test
fun testEncryptMixedDictionary() {
val result = handler.encrypt(mapOf("a" to 1, 2 to "b"), contextMock, "test-role") as Map<Any?, Any?>
assertNotNull(result)
assertEquals(2, result.size)
assertEquals(1, result["a"])
assertEquals("b", result[2])
verify(contextMock, times(2)).encrypt(anyOrNull(), eq("test-role"))
}
@Test
fun testEncryptMixedMultidimensionalDictionary() {
val result = handler.encrypt(mapOf("z" to mapOf("a" to 1, "b" to "B"), 2 to true), contextMock, "test-role") as Map<Any?, Any?>
assertNotNull(result)
assertEquals(2, result.size)
val inner = result["z"] as Map<String, Any>?
assertNotNull(inner)
assertEquals(1, inner!!["a"])
assertEquals("B", inner["b"])
assertEquals(true, result[2])
verify(contextMock, times(2)).encrypt(anyOrNull(), eq("test-role"))
}
}
| 3
|
Kotlin
|
1
| 4
|
8b2cad55423df98d5e18f33f39ac0f47f3a50402
| 3,240
|
evervault-android
|
MIT License
|
lib/sisyphus-grpc/src/main/kotlin/com/bybutter/sisyphus/rpc/CallOptionsInterceptor.kt
|
ButterCam
| 264,589,207
| false
|
{"Kotlin": 1182594, "ANTLR": 12352}
|
package com.bybutter.sisyphus.rpc
import io.grpc.CallOptions
import io.grpc.MethodDescriptor
interface CallOptionsInterceptor {
fun intercept(method: MethodDescriptor<*, *>, options: CallOptions): CallOptions
}
| 9
|
Kotlin
|
10
| 83
|
5622e1ffd5983d0a1478593f04fae2fa3ae125b5
| 217
|
sisyphus
|
MIT License
|
kmm/data/src/commonMain/kotlin/com/yao/tmdb/data/model/ProductionCompany.kt
|
yao-xie-kinto
| 598,494,975
| false
| null |
package com.yao.tmdb.data.model
import kotlinx.serialization.Serializable
@Serializable
data class ProductionCompany(
val id: Int? = 0,
val logo_path: String? = null,
val name: String? = null,
val origin_country: String? = null
)
| 0
|
Kotlin
|
0
| 0
|
8a0a36cf99e807c6dfd870a0f9e2e1db37c03f04
| 247
|
TMDB_KMM
|
MIT License
|
app/src/main/java/fr/openium/auvergnewebcams/ui/main/ViewModelMain.kt
|
openium
| 84,578,399
| false
| null |
package fr.openium.auvergnewebcams.ui.main
import android.app.Application
import fr.openium.auvergnewebcams.base.AbstractViewModel
import fr.openium.auvergnewebcams.model.entity.Section
import fr.openium.auvergnewebcams.model.entity.Webcam
import fr.openium.auvergnewebcams.repository.SectionRepository
import fr.openium.auvergnewebcams.repository.WebcamRepository
import fr.openium.rxtools.ext.fromIOToMain
import io.reactivex.Completable
import io.reactivex.Single
import org.kodein.di.generic.instance
import timber.log.Timber
import java.util.concurrent.TimeUnit
class ViewModelMain(app: Application) : AbstractViewModel(app) {
private val sectionRepository: SectionRepository by instance()
private val webcamRepository: WebcamRepository by instance()
companion object {
const val MINIMUM_SECONDS_TO_WAIT = 2L
}
// Update all the data the app needs
fun updateData(): Completable =
Completable.timer(MINIMUM_SECONDS_TO_WAIT, TimeUnit.SECONDS).mergeWith(
sectionRepository.fetch().doOnSuccess {
Timber.d("Loading from network: OK")
}.doOnError {
Timber.e(it, "Loading from network: KO")
}.ignoreElement()
).fromIOToMain()
fun getSectionsSingle(): Single<List<Section>> = sectionRepository.getSectionsSingle()
fun getWebcamsSingle(): Single<List<Webcam>> = webcamRepository.getWebcamsSingle()
}
| 0
|
Kotlin
|
1
| 2
|
e7e41eb2c021b895377b4a9933b2f5092640ae14
| 1,427
|
auvergne-webcams-droid
|
MIT License
|
src/main/kotlin/me/ezeh/copper/lang/operation/binary/CopperLogicalOr.kt
|
dignissimus
| 117,887,289
| false
| null |
package me.ezeh.copper.lang.operation.binary
import me.ezeh.copper.lang.CopperExpression
import me.ezeh.copper.lang.CopperProgramme
class CopperLogicalOr(programme: CopperProgramme, left: CopperExpression, right: CopperExpression) : CopperBinaryOperation("logicalOr", programme, left, right)
| 10
|
Kotlin
|
0
| 0
|
b5b7fb666ef3283e004da51d2114e8a2ebc037c3
| 293
|
Copper
|
Apache License 2.0
|
app/src/main/java/ch/nevis/exampleapp/ui/home/HomeFragment.kt
|
nevissecurity
| 602,532,842
| false
| null |
/**
* Nevis Mobile Authentication SDK Example App
*
* Copyright © 2023. Nevis Security AG. All rights reserved.
*/
package ch.nevis.exampleapp.ui.home
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.viewModels
import androidx.navigation.fragment.findNavController
import ch.nevis.exampleapp.NavigationGraphDirections
import ch.nevis.exampleapp.R
import ch.nevis.exampleapp.databinding.FragmentHomeBinding
import ch.nevis.exampleapp.ui.base.BaseFragment
import ch.nevis.exampleapp.ui.base.model.ViewData
import ch.nevis.exampleapp.ui.home.model.HomeViewData
import ch.nevis.exampleapp.ui.util.handleDispatchTokenResponse
import dagger.hilt.android.AndroidEntryPoint
/**
* [androidx.fragment.app.Fragment] implementation of home view. This view is the start/home view of the application.
* It can handle an out-of-band payload or Auth Cloud API registration, in-band authentication,
* in-band registration. change PIN, change device information, or deregistration can be started from here.
*/
@AndroidEntryPoint
class HomeFragment : BaseFragment() {
//region Properties
/**
* UI component bindings.
*/
private var _binding: FragmentHomeBinding? = null
private val binding get() = _binding!!
/**
* View model for this view.
*/
override val viewModel: HomeViewModel by viewModels()
//endregion
//region Fragment
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View {
_binding = FragmentHomeBinding.inflate(inflater, container, false)
return binding.root
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
val navController = findNavController()
binding.qrCodeButton.setOnClickListener {
val action = NavigationGraphDirections.actionGlobalQrReaderFragment()
navController.navigate(action)
}
binding.inBandAuthenticationButton.setOnClickListener {
viewModel.inBandAuthentication()
}
binding.deregisterButton.setOnClickListener {
viewModel.deregister()
}
binding.changePinButton.setOnClickListener {
viewModel.changePin()
}
binding.changeDeviceInformationButton.setOnClickListener {
val action = NavigationGraphDirections.actionGlobalChangeDeviceInformationFragment()
navController.navigate(action)
}
binding.authCloudRegistrationButton.setOnClickListener {
val action = NavigationGraphDirections.actionGlobalAuthCloudRegistrationFragment()
navController.navigate(action)
}
binding.inBandRegistrationButton.setOnClickListener {
val action = NavigationGraphDirections.actionGlobalUserNamePasswordLoginFragment()
navController.navigate(action)
}
}
override fun onStart() {
super.onStart()
viewModel.initClient()
}
override fun onDestroyView() {
super.onDestroyView()
_binding = null
}
//endregion
//region BaseFragment
override fun updateView(viewData: ViewData) {
super.updateView(viewData)
val homeViewData = viewData as? HomeViewData ?: return
binding.titleTextView.text = context?.getString(
R.string.home_registered_accounts,
homeViewData.numberOfRegisteredAccounts
)
// This is the point when we can be sure the client successfully initialized and
// the dispatch token handling can be started.
handleDispatchTokenResponse {
viewModel.decodeOutOfBandPayload(it)
}
}
//endregion
}
| 1
| null |
0
| 2
|
1b3854ef8d1e5dbf80b4f89b166145f0b757ceaa
| 3,857
|
nevis-mobile-authentication-sdk-example-app-android
|
MIT License
|
app/src/main/java/prieto/fernando/spacex/presentation/vm/LaunchesViewModel.kt
|
ferPrieto
| 226,459,777
| false
| null |
package prieto.fernando.spacex.presentation.vm
import androidx.lifecycle.viewModelScope
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.CoroutineExceptionHandler
import kotlinx.coroutines.flow.catch
import kotlinx.coroutines.flow.collect
import kotlinx.coroutines.launch
import prieto.fernando.spacex.presentation.vm.base.BaseViewModel
import prieto.fernando.domain.usecase.GetLaunches
import prieto.fernando.spacex.presentation.screens.launches.LaunchesContract
import prieto.fernando.spacex.presentation.screens.launches.LinksUiModel
import prieto.fernando.spacex.presentation.vm.mapper.LaunchesDomainToUiModelMapper
import timber.log.Timber
import javax.inject.Inject
@HiltViewModel
class LaunchesViewModel @Inject constructor(
private val getLaunches: GetLaunches,
private val launchesDomainToUiModelMapper: LaunchesDomainToUiModelMapper
) : BaseViewModel<LaunchesContract.Event, LaunchesContract.State, LaunchesContract.Effect>() {
private val errorHandler = CoroutineExceptionHandler { _, exception ->
Timber.e(exception)
setState {
copy(
isLoading = false,
isError = true
)
}
}
init {
launches()
}
override fun setInitialState(): LaunchesContract.State =
LaunchesContract.State(
launchUiModels = emptyList(),
isLoading = true,
isError = false
)
override fun handleEvents(event: LaunchesContract.Event) {
when (event) {
is LaunchesContract.Event.LinkClicked -> setEffect {
LaunchesContract.Effect.LinkClicked(
event.link
)
}
is LaunchesContract.Event.ClickableLinks ->
setEffect { getClickableLink(event.linksUiModel) }
is LaunchesContract.Event.Filter -> {
val filteredYear = if (event.year.isNotBlank()) event.year.toInt() else 0
launches(filteredYear, event.orderedChecked)
}
}
}
fun launches(yearFilterCriteria: Int = 0, ascendantOrder: Boolean = false) {
viewModelScope.launch(errorHandler) {
try {
getLaunches.execute(yearFilterCriteria, ascendantOrder)
.catch { throwable ->
handleExceptions(throwable)
}
.collect { launchesDomainModel ->
launchesDomainToUiModelMapper.toUiModel(launchesDomainModel)
.let { launches ->
setState {
copy(
launchUiModels = launches,
isLoading = false
)
}
}
}
} catch (throwable: Throwable) {
handleExceptions(throwable)
}
}
}
private fun handleExceptions(throwable: Throwable) {
Timber.e(throwable)
setState {
copy(
isLoading = false,
isError = true
)
}
}
private fun getClickableLink(linksUiModel: LinksUiModel): LaunchesContract.Effect.ClickableLink =
when {
linksUiModel.wikipedia.isNotBlank() && linksUiModel.videoLink.isNotBlank() -> {
LaunchesContract.Effect.ClickableLink.All(
linksUiModel.videoLink,
linksUiModel.wikipedia
)
}
linksUiModel.wikipedia.isNotBlank() && linksUiModel.videoLink.isBlank() -> {
LaunchesContract.Effect.ClickableLink.Wikipedia(linksUiModel.wikipedia)
}
linksUiModel.wikipedia.isBlank() && linksUiModel.videoLink.isNotBlank() -> {
LaunchesContract.Effect.ClickableLink.Youtube(linksUiModel.videoLink)
}
else -> {
LaunchesContract.Effect.ClickableLink.None
}
}
}
| 0
|
Kotlin
|
40
| 306
|
f7f0aa5538f282c4a7bb0cb08387c72bab990c07
| 4,144
|
Coroutines-Flows-Modularised
|
Apache License 2.0
|
retriever-runtime/src/commonMain/kotlin/com/ustadmobile/retriever/checksumproviders/KnownSha256ChecksumProvider.kt
|
UstadMobile
| 439,850,316
| false
| null |
package com.ustadmobile.retriever.checksumproviders
import com.ustadmobile.retriever.ChecksumProvider
import com.ustadmobile.retriever.ChecksumType
class KnownSha256ChecksumProvider(val knownChecksum: ByteArray) : ChecksumProvider{
override suspend fun getExpectedChecksum(url: String, checksumType: ChecksumType): ByteArray? {
if(checksumType != ChecksumType.SHA256)
throw IllegalArgumentException("Only supports SHA256")
return knownChecksum
}
}
| 0
|
Kotlin
|
0
| 0
|
aa5c73a7b09d50fa596fad938d031bdb27dc9982
| 487
|
retriever
|
MIT License
|
scalechain-proto-codec/src/test/kotlin/io/scalechain/blockchain/proto/codec/messages/BlockSpec.kt
|
ScaleChain
| 45,332,311
| false
| null |
package io.scalechain.blockchain.proto.codec.messages
import io.kotlintest.KTestJUnitRunner
import io.netty.buffer.Unpooled
import io.scalechain.blockchain.proto.*
import io.scalechain.blockchain.proto.codec.*
import io.scalechain.io.HexFileLoader
import io.scalechain.util.HexUtil.bytes
import org.junit.runner.RunWith
import java.io.File
/**
<Bitcoin Core Packets Captured>
<NET> recv; header:
<Header> Magic:ù¾´Ù, Command:block, Size:231721, Checksum:-2127760196
dumping data len : 24
00000000 f9 be b4 d9 62 6c 6f 63 6b 00 00 00 00 00 00 00 ù¾´Ùblock.......
00000010 29 89 03 00 bc f4 2c 81 )<89>..¼ô,<81>
dumping data len : 231721
00000000 04 00 00 00 33 52 85 50 87 a8 a9 03 78 96 a9 22 ....3R<85>P<87>¨©.x<96>©"
00000010 aa c6 ff ab c9 73 15 a5 88 a7 b2 03 00 00 00 00 ªÆÿ«És.¥<88>§².....
00000020 00 00 00 00 b1 a7 95 87 8d a6 e1 e0 92 4f 71 8d ....±§<95><87><8d>¦áà<92>Oq<8d>
... omitted .............. full data at /block-size231721.hex
*/
@RunWith(KTestJUnitRunner::class)
class BlockSpec : EnvelopeTestSuite<Block>() {
override val codec = BlockCodec
override val envelopeHeader = bytes(
"""
f9 be b4 d9 62 6c 6f 63 6b 00 00 00 00 00 00 00
29 89 03 00 bc f4 2c 81
""")
override val payload = HexFileLoader.load("../data/unittest/codec/block-size231721.hex")
override val envelope = BitcoinMessageEnvelope(
Magic.MAIN,
"block",
payload.size,
Checksum.fromHex("bc f4 2c 81"),
Unpooled.wrappedBuffer(payload)
)
// Do not test
override val message = null
}
| 11
|
Kotlin
|
67
| 234
|
e39b789928256b75c18acee847ccc2c2dc2dec5a
| 1,591
|
scalechain
|
Intel Open Source License
|
app/src/main/java/com/akinci/doggoappcompose/ui/components/PageNavigator.kt
|
AttilaAKINCI
| 440,251,794
| false
|
{"Kotlin": 127722}
|
package com.akinci.doggoappcompose.ui.components
import androidx.compose.foundation.layout.*
import androidx.compose.material.Button
import androidx.compose.material.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import com.akinci.doggoappcompose.ui.theme.DoggoAppComposeTheme
import com.akinci.doggoappcompose.R
@Composable
fun PageNavigator(
navigatorMessageId: Int = R.string.welcome_message,
navigateButtonMessageId: Int = R.string.button_next_page,
onClick : ()->Unit
) {
Column(
Modifier
.padding(30.dp)
.fillMaxWidth(),
horizontalAlignment = Alignment.CenterHorizontally
){
Text(text = stringResource(id = navigatorMessageId))
Spacer(Modifier.size(30.dp))
Button(
onClick = onClick
) {
Text(text = stringResource(id = navigateButtonMessageId))
}
}
}
@Preview(showBackground = true)
@Composable
fun PreviewPageNavigator() {
DoggoAppComposeTheme {
PageNavigator(onClick = { })
}
}
| 0
|
Kotlin
|
0
| 1
|
c523cabc81059ba00ac46305052101b5d37024fb
| 1,238
|
Doggo
|
Apache License 2.0
|
src/main/kotlin/com/imma/utils/EnvMode.kt
|
Indexical-Metrics-Measure-Advisory
| 344,732,013
| false
| null |
package com.imma.utils
import io.ktor.application.*
val Application.envKind get() = environment.config.property(EnvConstants.ENV_MODE).getString()
val Application.isDev get() = envKind == EnvConstants.ENV_MODE_DEV
val Application.isProd get() = envKind == EnvConstants.ENV_MODE_PROD
| 0
|
Kotlin
|
0
| 1
|
c42a959826e72ac8cea7a8390ccc7825f047a591
| 284
|
watchmen-ktor
|
MIT License
|
kork-plugins/src/main/kotlin/com/netflix/spinnaker/kork/plugins/update/internal/Front50Service.kt
|
spinnaker
| 19,836,152
| false
|
{"Java": 1564018, "Kotlin": 594876, "Groovy": 107785, "Shell": 969, "JavaScript": 595, "HTML": 394}
|
/*
* Copyright 2020 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* 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.netflix.spinnaker.kork.plugins.update.internal
import retrofit2.Call
import retrofit2.http.Body
import retrofit2.http.GET
import retrofit2.http.PUT
import retrofit2.http.Path
import retrofit2.http.Query
/**
* List and get plugin info objects from Front50. Used in conjunction with [Front50UpdateRepository]
* to populate a services plugin info cache to determine which plugins to load.
*/
interface Front50Service {
@GET("/pluginInfo/{id}")
fun getById(@Path("id") id: String): Call<SpinnakerPluginInfo>
@GET("/pluginInfo")
fun listAll(): Call<Collection<SpinnakerPluginInfo>>
@PUT("/pluginVersions/{serverGroupName}")
fun pinVersions(
@Path("serverGroupName") serverGroupName: String,
@Query("serviceName") serviceName: String,
@Query("location") location: String,
@Body versions: Map<String, String>
): Call<PinnedVersions>
}
typealias PinnedVersions = Map<String, SpinnakerPluginInfo.SpinnakerPluginRelease>
| 16
|
Java
|
175
| 41
|
5baf9d8d228733f8d045d42e2eb9d2f4d663cc82
| 1,558
|
kork
|
Apache License 2.0
|
src/main/kotlin/com/akkih/dusk/extension/ExMenu.kt
|
akkkih
| 762,714,072
| false
|
{"Kotlin": 41563}
|
package com.akkih.dusk.extension
import com.akkih.dusk.menu.Menu
import net.kyori.adventure.text.Component
import org.bukkit.entity.Player
import org.bukkit.event.inventory.InventoryClickEvent
import org.bukkit.event.inventory.InventoryCloseEvent
import org.bukkit.event.inventory.InventoryOpenEvent
import org.bukkit.event.inventory.InventoryType
/**
* Open a [Menu] for the player.
*
* @param menu The menu to be opened for the player.
*/
fun Player.openMenu(menu: Menu) = menu.open(this)
/**
* Creates a menu with the specified title, inventory type, and callback function.
*
* @param title The title of the menu.
* @param type The inventory type of the menu.
* @param callback The callback function to be executed when the menu is created.
* @return A Menu instance.
*/
fun menu(title: String,
type: InventoryType,
callback: Menu.() -> Unit) =
menu(title.toComponent(), type, callback)
/**
* Creates a menu with the specified title, inventory type, and callback function.
*
* @param title The title of the menu.
* @param type The inventory type of the menu.
* @param callback The callback function to be executed when the menu is created.
* @return A Menu instance.
*/
fun menu(title: Component, type: InventoryType, callback: Menu.() -> Unit): Menu {
return object : Menu(title, type) {
fun onOpen(event: InventoryOpenEvent) {
onOpenAction(event)
}
fun onClose(event: InventoryCloseEvent) {
onCloseAction(event)
}
fun onClick(event: InventoryClickEvent) {
onClickAction(event)
}
}.also(callback)
}
/**
* Creates a menu with the specified title, number of rows, and callback function.
*
* @param title The title of the menu.
* @param rows The number of rows in the menu.
* @param callback The callback function to be executed when the menu is created.
* @return A Menu instance.
*/
fun menu(title: String,
rows: Int,
callback: Menu.() -> Unit) =
menu(title.toComponent(), rows, callback)
/**
* Creates a menu with the specified title, number of rows, and callback function.
*
* @param title The title of the menu.
* @param rows The number of rows in the menu.
* @param callback The callback function to be executed when the menu is created.
* @return A Menu instance.
*/
fun menu(title: Component, rows: Int, callback: Menu.() -> Unit): Menu {
return object : Menu(title, rows) {
fun onOpen(event: InventoryOpenEvent) {
onOpenAction(event)
}
fun onClose(event: InventoryCloseEvent) {
onCloseAction(event)
}
fun onClick(event: InventoryClickEvent) {
onClickAction(event)
}
}.also(callback)
}
| 0
|
Kotlin
|
0
| 1
|
93bbad943028454fe6abe0c2268cc7bc0d095308
| 2,764
|
dusk
|
MIT License
|
screenshot_testing/src/test/java/com/costular/atomtasks/screenshottesting/designsystem/ScreenSubheaderSnapshotTest.kt
|
costular
| 379,913,052
| false
| null |
package com.costular.atomtasks.screenshottesting.designsystem
import app.cash.paparazzi.Paparazzi
import com.costular.atomtasks.screenshottesting.utils.FontSize
import com.costular.atomtasks.screenshottesting.utils.PaparazziFactory
import com.costular.atomtasks.screenshottesting.utils.Theme
import com.costular.atomtasks.screenshottesting.utils.asFloat
import com.costular.atomtasks.screenshottesting.utils.isDarkTheme
import com.costular.atomtasks.screenshottesting.utils.screenshot
import com.costular.commonui.components.ScreenSubheader
import com.google.testing.junit.testparameterinjector.TestParameter
import com.google.testing.junit.testparameterinjector.TestParameterInjector
import org.junit.Rule
import org.junit.Test
import org.junit.runner.RunWith
@RunWith(TestParameterInjector::class)
class ScreenSubheaderSnapshotTest {
@TestParameter
private lateinit var fontScale: FontSize
@TestParameter
private lateinit var themeMode: Theme
@get:Rule
val paparazzi: Paparazzi = PaparazziFactory.create()
@Test
fun subheader() {
paparazzi.screenshot(
isDarkTheme = themeMode.isDarkTheme(),
fontScale = fontScale.asFloat(),
) {
ScreenSubheader(text = "Screen subheader")
}
}
}
| 2
| null |
0
| 9
|
8c81c3a3a9198e57bca0cdf8b399c89f01f28f84
| 1,281
|
atom-tasks
|
Apache License 2.0
|
buildSrc/src/main/kotlin/com/orange/ouds/gradle/FileExt.kt
|
Orange-OpenSource
| 817,725,638
| false
| null |
/*
* Software Name: Orange Design System
* SPDX-FileCopyrightText: Copyright (c) Orange SA
* SPDX-License-Identifier: MIT
*
* This software is distributed under the MIT licence,
* the text of which is available at https://opensource.org/license/MIT/
* or see the "LICENSE" file for more details.
*
* Software description: Android library of reusable graphical components
*/
import java.io.File
fun File.replace(regex: Regex, replacement: String) {
val text = readText()
writeText(text.replace(regex, replacement))
}
fun File.replace(regex: Regex, transform: (MatchResult) -> CharSequence) {
val text = readText()
writeText(text.replace(regex, transform))
}
| 77
| null |
7
| 6
|
7fd1842d28ff258367499e7afa4016b10f821ea0
| 686
|
ouds-android
|
MIT License
|
src/main/kotlin/cloud/openerrands/opennlp/SupportedLanguage.kt
|
openerrands
| 308,100,126
| false
| null |
package cloud.openerrands.opennlp
import opennlp.tools.postag.POSModel
import opennlp.tools.postag.POSTaggerME
import opennlp.tools.sentdetect.SentenceDetectorME
import opennlp.tools.sentdetect.SentenceModel
import opennlp.tools.stemmer.snowball.SnowballStemmer
import opennlp.tools.stemmer.snowball.SnowballStemmer.ALGORITHM
import opennlp.tools.tokenize.TokenizerME
import opennlp.tools.tokenize.TokenizerModel
import java.io.InputStream
private const val MODEL_LOCATION = "opennlp/models/"
/**
* Supported Languages have models for sentences, tokens, parts of speech, and support for Snowball stemming.
*/
enum class SupportedLanguage(
private val snowballAlgorithm: ALGORITHM,
private var sentenceModel: SentenceModel? = null,
private var tokenizerModel: TokenizerModel? = null,
private var posModel: POSModel? = null
) {
DA(ALGORITHM.DANISH),
DE(ALGORITHM.DUTCH),
EN(ALGORITHM.ENGLISH),
NL(ALGORITHM.NORWEGIAN),
PT(ALGORITHM.PORTUGUESE)
;
init {
sentenceModel = getModelAsStream("sent").use { SentenceModel(it) }
tokenizerModel = getModelAsStream("token").use { TokenizerModel(it) }
posModel = getModelAsStream("pos-maxent").use { POSModel(it) }
}
fun buildSnowballStemmer() = SnowballStemmer(snowballAlgorithm)
fun toSnowballStem(word: String): String {
return buildSnowballStemmer().stem(word)?.toString() ?: ""
}
fun toSentences(text: String): Array<String> {
return SentenceDetectorME(sentenceModel).sentDetect(text)
}
fun toTokens(sentence: String, replacements: List<Pair<Regex, String>> = emptyList()): Array<String> {
var result = sentence
for (pair in replacements) {
result = result.replace(pair.first, pair.second)
}
return TokenizerME(tokenizerModel).tokenize(result.toLowerCase())
}
fun toPOSTags(words: Array<String>): Array<Pair<String, String>> {
return words.zip(POSTaggerME(posModel).tag(words)).toTypedArray()
}
private fun getModelAsStream(suffix: String): InputStream? {
return SupportedLanguage::class.java.classLoader.getResourceAsStream(
"${MODEL_LOCATION}${this.name.toLowerCase()}-${suffix}.bin"
)
}
}
| 0
|
Kotlin
|
0
| 0
|
1c3a33b6f4d598443bf9759d5c534af52cab751a
| 2,257
|
openerrands-category-parser-lib
|
Apache License 2.0
|
src/main/kotlin/com/intellij/aws/cloudformation/CloudFormationPsiUtils.kt
|
sampritavh
| 69,634,585
| true
|
{"Kotlin": 91697, "HTML": 354}
|
package com.intellij.aws.cloudformation
import com.intellij.json.psi.JsonLiteral
import com.intellij.json.psi.JsonObject
import com.intellij.json.psi.JsonProperty
import com.intellij.json.psi.JsonStringLiteral
import com.intellij.openapi.util.text.StringUtil
import com.intellij.psi.PsiElement
import com.intellij.psi.PsiFile
object CloudFormationPsiUtils {
fun isCloudFormationFile(element: PsiElement): Boolean =
element.containingFile.fileType === CloudFormationFileType.INSTANCE
fun getRootExpression(file: PsiFile): JsonObject? {
var cur: PsiElement? = file.firstChild
while (cur != null) {
if (cur is JsonObject) {
return cur
}
cur = cur.nextSibling
}
return null
}
fun getObjectLiteralExpressionChild(parent: JsonObject?, childName: String): JsonObject? {
val property = parent?.findProperty(childName) ?: return null
return property.value as? JsonObject
}
fun isResourceTypeValuePosition(position: PsiElement): Boolean {
val valueExpression = position as? JsonLiteral ?: return false
val typeProperty = valueExpression.parent as? JsonProperty
if (typeProperty == null ||
typeProperty.value !== valueExpression ||
CloudFormationConstants.TypePropertyName != typeProperty.name) {
return false
}
val resourceExpression = typeProperty.parent as? JsonObject ?: return false
val resourceProperty = resourceExpression.parent as? JsonProperty ?: return false
val resourcesExpression = resourceProperty.parent as? JsonObject ?: return false
val resourcesProperty = resourcesExpression.parent as? JsonProperty
if (resourcesProperty == null || CloudFormationSections.Resources != StringUtil.stripQuotesAroundValue(resourcesProperty.name)) {
return false
}
val root = CloudFormationPsiUtils.getRootExpression(resourceProperty.containingFile)
return root === resourcesProperty.parent
}
fun isResourcePropertyNamePosition(position: PsiElement): Boolean {
val resourceProperty = getResourceElementFromPropertyName(position) ?: return false
val resourcesExpression = resourceProperty.parent as? JsonObject ?: return false
val resourcesProperty = resourcesExpression.parent as? JsonProperty
if (resourcesProperty == null ||
resourcesProperty.name.isEmpty() ||
CloudFormationSections.Resources != StringUtil.stripQuotesAroundValue(resourcesProperty.name)) {
return false
}
val root = CloudFormationPsiUtils.getRootExpression(resourceProperty.containingFile)
return root === resourcesProperty.parent
}
fun getResourceElementFromPropertyName(position: PsiElement): JsonProperty? {
val propertyName = position as? JsonStringLiteral ?: return null
val property = propertyName.parent as? JsonProperty
if (property == null || property.nameElement !== propertyName) {
return null
}
val propertiesExpression = property.parent as? JsonObject ?: return null
val properties = propertiesExpression.parent as? JsonProperty
if (properties == null ||
properties.value !== propertiesExpression ||
CloudFormationConstants.PropertiesPropertyName != properties.name) {
return null
}
val resourceExpression = properties.parent as? JsonObject ?: return null
return resourceExpression.parent as? JsonProperty
}
}
| 0
|
Kotlin
|
0
| 0
|
bff496adf7a9f46b0264fc3929b2d866e671f7e7
| 3,374
|
idea-cloudformation
|
Apache License 2.0
|
app/src/main/java/com/example/mvvm_dagger_kotlin_3_10_19/database/UserDao.kt
|
parthpitorda
| 228,543,452
| false
| null |
package com.example.mvvm_dagger_kotlin_3_10_19.database
import androidx.room.Dao
import androidx.room.Insert
import androidx.room.Query
@Dao
interface UserDao {
@get:Query("SELECT * FROM User")
val getAllUser:List<User>
@Insert
fun insertAll(vararg user: User)
}
| 0
| null |
0
| 5
|
5f37522edf20450aa96f1cc65133bdc00d406583
| 281
|
kotlin_mvvm_dagger2
|
MIT License
|
server/src/main/com/broll/gainea/server/core/objects/buffs/BuffProcessor.kt
|
Rolleander
| 253,573,579
| false
|
{"Kotlin": 426720, "Java": 265966, "HTML": 1714, "CSS": 1069, "JavaScript": 24}
|
package com.broll.gainea.server.core.objects.buffs
import com.broll.gainea.server.core.Game
import com.broll.gainea.server.core.objects.MapObject
import com.broll.gainea.server.core.objects.Unit
import com.broll.gainea.server.core.player.Player
import com.broll.gainea.server.core.player.isNeutral
import com.broll.gainea.server.core.processing.GameUpdateReceiverAdapter
import com.broll.gainea.server.core.utils.UnitControl.kill
import com.broll.gainea.server.core.utils.UnitControl.update
import org.apache.commons.collections4.map.MultiValueMap
class BuffProcessor(private val game: Game) : GameUpdateReceiverAdapter() {
private var currentTurnCount = 0
private val timedBuffs = MultiValueMap<Int, Buff<*>>()
private val globalBuffs: MutableMap<Buff<*>, GlobalBuff> = HashMap()
init {
game.updateReceiver.register(this)
}
override fun turnStarted(player: Player) {
currentTurnCount++
timedBuffs.keys.flatMap { timedBuffs.getCollection(it) }.forEach { it.turnsActive += 1 }
timedBuffs.getCollection(currentTurnCount)?.let { timedout ->
timedout.forEach { timedout(it) }
timedBuffs.remove(currentTurnCount)
}
}
private fun timedout(buff: Buff<*>) {
val affectedObjects = ArrayList(buff.affectedObjects)
buff.remove()
globalBuffs.remove(buff)
//check if any unit died because of removal of buffs
val update = mutableListOf<MapObject>()
for (target in affectedObjects) {
if (target is Unit) {
if (target.dead) {
game.kill(target)
} else {
update.add(target)
}
}
}
game.update(update)
}
fun timeoutBuff(buff: Buff<*>, rounds: Int) {
val timeoutTurn = currentTurnCount + game.allPlayers.size * Math.max(1, rounds)
timedBuffs[timeoutTurn] = buff
}
fun addGlobalBuff(globalBuff: GlobalBuff, effect: Int) {
globalBuffs[globalBuff.buff] = globalBuff
//apply directly to all existing units for the targets
globalBuff.targets.forEach { player ->
val units = if (player.isNeutral()) {
game.objects.filterIsInstance<Unit>()
} else {
player.units
}
units.forEach { globalBuff.apply(it) }
game.update(units)
}
}
fun applyGlobalBuffs(unit: Unit) =
globalBuffs.values.filter { it.targets.contains(unit.owner) }.forEach {
it.apply(unit)
}
}
| 0
|
Kotlin
|
1
| 3
|
f77dc6ff9c27b7067227eca1205ab3c4ff873625
| 2,610
|
Gainea
|
MIT License
|
src/main/kotlin/no/nav/dagpenger/doh/monitor/VedtakfattetMonitor.kt
|
navikt
| 267,513,319
| false
|
{"Kotlin": 57658, "Dockerfile": 189}
|
package no.nav.dagpenger.doh.monitor
import mu.KotlinLogging
import mu.withLoggingContext
import no.nav.dagpenger.doh.Kibana
import no.nav.dagpenger.doh.slack.VedtakBot
import no.nav.helse.rapids_rivers.JsonMessage
import no.nav.helse.rapids_rivers.MessageContext
import no.nav.helse.rapids_rivers.RapidsConnection
import no.nav.helse.rapids_rivers.River
import no.nav.helse.rapids_rivers.asLocalDateTime
import java.time.format.DateTimeFormatter
internal class VedtakfattetMonitor(rapidsConnection: RapidsConnection, private val vedtakBot: VedtakBot?) :
River.PacketListener {
init {
River(rapidsConnection).apply {
validate {
it.requireValue("@event_name", "vedtak_fattet")
it.requireKey("behandlingId", "utfall", "gjelderDato")
it.interestedIn("@opprettet")
}
}.register(this)
}
private companion object {
val logger = KotlinLogging.logger { }
}
override fun onPacket(
packet: JsonMessage,
context: MessageContext,
) {
val behandlingId = packet["behandlingId"].asText()
withLoggingContext(mapOf("behandlingId" to behandlingId)) {
val utfall = packet["utfall"].asBoolean()
vedtakBot?.postVedtak(utfall, behandlingId, packet["@opprettet"].asLocalDateTime())
logger.info { "Vi har fattet vedtak med $utfall" + "(slackbot er konfiguert? ${vedtakBot != null})" }
}
}
}
| 0
|
Kotlin
|
0
| 1
|
56a9225626a56f8fc16dbfce2ebd58912d8dcbac
| 1,476
|
dp-doh
|
MIT License
|
app/src/main/java/com/breezedishanfarm/features/dailyPlan/model/GetPlanListResponseModel.kt
|
DebashisINT
| 877,855,159
| false
|
{"Kotlin": 16013696, "Java": 1030008}
|
package com.breezedishanfarm.features.dailyPlan.model
import com.breezedishanfarm.base.BaseResponse
import java.io.Serializable
/**
* Created by Saikat on 24-12-2019.
*/
class GetPlanListResponseModel : BaseResponse(), Serializable {
var update_plan_list: ArrayList<GetPlanListDataModel>? = null
}
| 0
|
Kotlin
|
0
| 0
|
b59226c15f309bceee6069969a82f930d3a3897f
| 305
|
DISHANFARMS
|
Apache License 2.0
|
compiler/testData/codegen/boxInline/reified/arrayConstructor.kt
|
JetBrains
| 3,432,266
| false
|
{"Kotlin": 79571273, "Java": 6776465, "Swift": 4063829, "C": 2609744, "C++": 1957654, "Objective-C++": 175279, "JavaScript": 130754, "Python": 59855, "Shell": 34920, "Objective-C": 21463, "Lex": 21452, "Batchfile": 11382, "CSS": 11368, "Ruby": 10470, "Dockerfile": 9907, "Groovy": 7092, "EJS": 5241, "CMake": 4473, "HTML": 2699, "Puppet": 1698, "FreeMarker": 1393, "Roff": 725, "Scala": 80}
|
// FILE: 1.kt
package test
inline fun <reified T> f(x : () -> T): Array<T> = Array(1) { x() }
// FILE: 2.kt
import test.*
fun box(): String = f { "OK" }[0]
| 181
|
Kotlin
|
5748
| 49,172
|
33eb9cef3d146062c103f9853d772f0a1da0450e
| 160
|
kotlin
|
Apache License 2.0
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.