path
stringlengths 4
280
| owner
stringlengths 2
39
| repo_id
int64 21.1k
879M
| is_fork
bool 2
classes | languages_distribution
stringlengths 13
1.95k
⌀ | content
stringlengths 7
482k
| issues
int64 0
13.9k
| main_language
stringclasses 121
values | forks
stringlengths 1
5
| stars
int64 0
111k
| commit_sha
stringlengths 40
40
| size
int64 7
482k
| name
stringlengths 1
100
| license
stringclasses 93
values |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
app/src/main/java/ru/iteco/fmhandroid/repository/newsRepository/NewsRepositoryModule.kt
|
QA-USV
| 686,582,243
| false
| null |
package ru.iteco.fmhandroid.repository.newsRepository
import dagger.Binds
import dagger.Module
import dagger.hilt.InstallIn
import dagger.hilt.components.SingletonComponent
import javax.inject.Singleton
@InstallIn(SingletonComponent::class)
@Module
abstract class NewsRepositoryModule {
@Binds
@Singleton
abstract fun bindNewsRepository(impl: NewsRepositoryImpl): NewsRepository
}
| 0
| null |
0
| 1
|
a5c2a6fe8f5deb1359017c9c13d6a20ef409f563
| 395
|
My_Final_Project
|
Apache License 2.0
|
feature/stats/view/implementation/src/main/kotlin/com/savvasdalkitsis/uhuruphotos/feature/stats/view/implementation/ui/Stats.kt
|
savvasdalkitsis
| 485,908,521
| false
| null |
/*
Copyright 2023 <NAME>
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package com.savvasdalkitsis.uhuruphotos.feature.stats.view.implementation.ui
import androidx.compose.foundation.layout.Arrangement.spacedBy
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.material.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.unit.dp
import com.savvasdalkitsis.uhuruphotos.feature.stats.view.implementation.seam.actions.StatsAction
import com.savvasdalkitsis.uhuruphotos.feature.stats.view.implementation.seam.actions.UpActionPressed
import com.savvasdalkitsis.uhuruphotos.feature.stats.view.implementation.ui.state.StatsState
import com.savvasdalkitsis.uhuruphotos.foundation.strings.api.R.string
import com.savvasdalkitsis.uhuruphotos.foundation.ui.api.ui.BackNavButton
import com.savvasdalkitsis.uhuruphotos.foundation.ui.api.ui.CommonScaffold
@Composable
internal fun Stats(
state: StatsState,
action: (StatsAction) -> Unit,
) {
CommonScaffold(
title = { Text(stringResource(string.stats)) },
navigationIcon = { BackNavButton {
action(UpActionPressed)
}}
) { contentPadding ->
Column(
modifier = Modifier
.fillMaxSize()
.padding(16.dp),
verticalArrangement = spacedBy(16.dp),
) {
Spacer(modifier = Modifier.height(contentPadding.calculateTopPadding()))
StatsMediaPerYear(state.isLoadingMediaByYear, state.mediaByYear)
// StatsTimeline(state.isLoadingTimeline, state.timeline)
}
}
}
| 51
|
Kotlin
|
16
| 258
|
5cab4fea988d3f0f077552d079a250267d8c2c97
| 2,367
|
uhuruphotos-android
|
Apache License 2.0
|
mobile/src/main/java/uk/co/appsbystudio/geoshare/setup/InitialSetupView.kt
|
zacdevil10
| 50,067,543
| false
|
{"Gradle": 4, "Java Properties": 2, "Shell": 1, "Text": 1, "Ignore List": 2, "Batchfile": 2, "Markdown": 1, "Proguard": 1, "Java": 11, "XML": 97, "JSON": 2, "Kotlin": 149}
|
package uk.co.appsbystudio.geoshare.setup
interface InitialSetupView {
fun onNext()
fun onBack()
fun onFinish(radius: Int)
fun hasPermissions(): Boolean
fun requestPermissions()
fun onShowProfileDialog()
fun showToast(message: String)
}
| 5
| null |
1
| 1
|
f66aa94d7f44c8dbf81a6a67a4e0504bbf7e2d32
| 272
|
GeoShare_Android
|
Apache License 2.0
|
kspprocessor/src/main/kotlin/com/typedpath/unittestof/processor/TestableRoots2Kotlin.kt
|
typedpath
| 565,979,433
| false
| null |
package com.typedpath.unittestof.processor
import com.typedpath.unittestof.testutil.BeanContext
import com.typedpath.unittestof.testutil.CallCentre
import com.typedpath.unittestof.testutil.ServiceProxyContext
import java.util.*
/*
class Bean1TestContext : BeanContext<Bean1>(){
import testutil.BeanContext
val service1Proxy = IService1ProxyContext()
val target = Bean1(service1Proxy.proxy)
fun setup() : Bean1 {
return Bean1(service1Proxy.proxy)
}
}
*/
fun conciseTypeString(type: String) = type.replace("java.lang.", "")
fun conciseTypeCast(type: String) : String {
val conciseTypeString = conciseTypeString(type)
return if ("Any" == conciseTypeString) "" else " as $conciseTypeString"
}
val beanContextClassName: String = BeanContext::class.java.name
val beanContextShortName = BeanContext::class.simpleName
val serviceProxyContextClassname: String = ServiceProxyContext::class.java.name
val callLogClassName: String = CallCentre::class.java.name
val callLogClassShortName = CallCentre::class.simpleName
val matcherClassName = CallCentre.Match::class.java.name.replace("$", ".")
val matchRowClassName = CallCentre.MatchRow::class.java.name.replace("$", ".")
val matchRowSimpleClassName: String = CallCentre.MatchRow::class.java.simpleName
class TestableRoots2Kotlin(private val emitJava: Boolean) {
fun textContextSource(creator: String, packagename: String, className: String, root: Model2FactoryMapper.FactoryClass) : String {
return (
"""${header(packagename, creator)}
${import(beanContextClassName)}
${if (!emitJava) "class $className : ${beanContextShortName}<${root.shortName}>() {" else
"public class $className extends ${beanContextShortName}<${root.shortName}> {"}
${root.constructorParams.joinToString (System.lineSeparator()){(
""" ${recorderDeclaration(it)}
${serviceDeclaration(it)}
"""
)}}
${if (!emitJava)" override val target = ${root.shortName}(${root.constructorParams.joinToString(", ") { "${it.name}Recorder.proxy" }})" else
""" final ${root.shortName} target= new ${root.shortName}(${root.constructorParams.joinToString(", ") { "${it.name}Recorder.getProxy()" }});
@Override
public ${root.shortName} getTarget() {
return target;
}
"""
}
}
""")
}
private fun recorderDeclaration(param: Model2FactoryMapper.FactoryClassParam) = if (!emitJava)
"""val ${param.name}Recorder = ${Interface.interfaceName2TestProxyName(param.type)}(callLog, "${param.name}")""" else
"""public final ${Interface.interfaceName2TestProxyName(param.type)} ${param.name}Recorder = new ${Interface.interfaceName2TestProxyName(param.type)}(getCallLog(), "${param.name}");"""
private fun serviceDeclaration(param: Model2FactoryMapper.FactoryClassParam) = if (!emitJava)
"""val ${param.name} = ${param.name}Recorder.proxy""" else
"""public final ${param.type} ${param.name} = ${param.name}Recorder.getProxy(); """
private fun import(target: String) = "import $target${if (emitJava) ";" else ""}"
data class Interface(val packageName: String, val shortName: String, val methods: List<Method>) {
data class Method(val name: String, val returnType: String, val params: List<Param>) {
fun methodId() = "${name}_${
params.joinToString("_") {
conciseTypeString(it.type).replace(
".",
"_"
)
}
}"
}
data class Param(val name: String, val type: String)
companion object {
fun interfaceName2TestProxyName(name: String) = "${name}ProxyContext"
}
}
fun testProxyContextSource(creator: String, packagename: String, className: String, iface: Interface) : String {
return (
"""${header(packagename, creator)}
${import(callLogClassName)}
${import(matcherClassName)}
${import(matchRowClassName)}
${proxyContextClassDeclaration(iface, className)}
${iface.methods.joinToString(System.lineSeparator()) { textProxyContextMethod(it) }}
${iface.methods.joinToString(System.lineSeparator()) { testProxyContextCaptureMethod(it) }}
}
""")
}
private fun proxyContextClassDeclaration(iface: Interface, className: String) : String {
return if (!emitJava) {
"""@Suppress("unused")
class ${className}(callCentre: ${callLogClassShortName}, id: String) : ${serviceProxyContextClassname}<${iface.shortName}>(${iface.packageName}.${iface.shortName}::class, callCentre, id) {"""
} else (
"""public class $className extends ${serviceProxyContextClassname}<${iface.shortName}> {
public ${className}(${callLogClassShortName} callCentre, String id) {
super(${iface.packageName}.${iface.shortName}.class, callCentre, id);
}""")
}
private fun textProxyContextMethod(method: Interface.Method) = if (!emitJava)
""" @Suppress("UNUSED_PARAMETER")
fun when${method.name.replaceFirstChar { it.titlecase() }}(${
method.params.joinToString(
separator = ", "
) { textProxyContextParam(it) }
} ${if (method.params.isNotEmpty()) ", " else ""} result: ${method.returnType.replace("java.lang.", "")}) {
callCentre.add(${matchRowSimpleClassName}(id, "${method.methodId()}", listOf(${
method.params.joinToString(
", "
) { it.name }
}), result))
}
""" else
""" public void when${method.name.replaceFirstChar { it.titlecase() }}(${
method.params.joinToString(
separator = ", "
) { textProxyContextParam(it) }
} ${if (method.params.isNotEmpty()) ", " else ""} ${method.returnType.replace("java.lang.", "")} result) {
getCallCentre().add(new ${matchRowSimpleClassName}(getId(), "${method.methodId()}", java.util.Arrays.asList(${
method.params.joinToString(
", "
) { it.name }
}), result));
}"""
private fun customCaptureTypeName(method: Interface.Method) = "${method.methodId()}Params"
private fun customCaptureType(method: Interface.Method) = if (!emitJava) "data class ${customCaptureTypeName(method)}( ${
method.params.joinToString(", ") {
"val ${it.name}: ${conciseTypeString(it.type)}"
}
} )" else
"""public static class ${customCaptureTypeName(method)} {
${
method.params.joinToString(System.lineSeparator()) {
" public ${conciseTypeString(it.type)} ${it.name};"
}
}
public ${customCaptureTypeName(method)} (${
method.params.joinToString(", ") {
"${conciseTypeString(it.type)} ${it.name}"
}
}) {
${
method.params.joinToString(System.lineSeparator()) {
" this.${it.name}=${it.name};"
}
}
}
}"""
private fun testProxyContextCaptureMethod(method: Interface.Method) : String {
return (
""" ${if (method.params.isEmpty()) testProxyContextCaptureMethodZeroParam(method) else if (method.params.size>1) testProxyContextCaptureMethodMultiParam(method) else testProxyContextCaptureMethodSingleParam(method)}
""")}
private fun testProxyContextCaptureMethodMultiParam(method: Interface.Method) : String {
val captureType = customCaptureTypeName(method)
return if (!emitJava)
"""${customCaptureType(method)}
@Suppress("UNUSED_PARAMETER")
fun capture${method.name.replaceFirstChar { it.titlecase() }}(${
method.params.joinToString(
separator = ", "
) { textProxyContextParam(it) }
} ) : List<${captureType}> {
return callCentre.getArgumentsByProxyIdMethodId(id, "${method.methodId()}").map { ${captureType}(${
method.params.mapIndexed { i, a -> "it[$i] ${conciseTypeCast( a.type)}" }.joinToString(",")}) }
}
""" else
"""${customCaptureType(method)}
public java.util.List<${captureType}> capture${method.name.replaceFirstChar { it.titlecase() }}(${
method.params.joinToString(
separator = ", "
) { textProxyContextParam(it) }
} ) {
return getCallCentre().getArgumentsByProxyIdMethodId(getId(), "${method.methodId()}").stream().map (it-> new ${captureType}(${
method.params.mapIndexed { i, a -> "(${conciseTypeString( a.type)}) it[$i]" }.joinToString(",")}) ).collect(java.util.stream.Collectors.toList());
}
"""}
private fun testProxyContextCaptureMethodSingleParam(method: Interface.Method) : String {
return if(!emitJava)
""" @Suppress("UNUSED_PARAMETER")
fun capture${method.name.replaceFirstChar { it.titlecase() }}(${
method.params.joinToString(
separator = ", "
) { textProxyContextParam(it) }
} ) : List<${conciseTypeString( method.params[0].type)}> {
return callCentre.getArgumentsByProxyIdMethodId(id, "${method.methodId()}").map { it[0] ${conciseTypeCast( method.params[0].type)} }
}
""" else
"""public java.util.List<${conciseTypeString( method.params[0].type)}> capture${method.name.replaceFirstChar { it.titlecase() }}(${
method.params.joinToString(
separator = ", "
) { textProxyContextParam(it) }
} ) {
return getCallCentre().getArgumentsByProxyIdMethodId(getId(), "${method.methodId()}").stream().map (it -> (${conciseTypeString( method.params[0].type)}) it[0] ).collect(java.util.stream.Collectors.toList());
} """
}
private fun testProxyContextCaptureMethodZeroParam(method: Interface.Method) : String {
return if (!emitJava)
""" @Suppress("UNUSED_PARAMETER")
fun capture${method.name.replaceFirstChar { it.titlecase() }}(${
method.params.joinToString(
separator = ", "
) { textProxyContextParam(it) }
} ) : List<Any> {
return callCentre.getArgumentsByProxyIdMethodId(id, "${method.methodId()}").map { listOf<Any>() }
}
""" else
"""java.util.List<Object> capture${method.name.replaceFirstChar { it.titlecase() }}(${
method.params.joinToString(
separator = ", "
) { textProxyContextParam(it) }
} ) : List<Any> {
return getCallCentre.getArgumentsByProxyIdMethodId(getId(), "${method.methodId()}").map { java.util.Arrays.asList() }
} """
}
private fun textProxyContextParam(param: Interface.Param) = if (!emitJava)
"""${param.name}: Match<${conciseTypeString(param.type)}>"""
else """Match<${conciseTypeString(param.type)}> ${param.name}"""
private fun header(packagename: String, creator: String) = (
"""${if (packagename.trim().isEmpty()) "" else "package $packagename${if (emitJava) ";" else ""}"}
// Factory generated on ${Date()}
// by ${javaClass.name}
// for $creator
"""
)
}
| 0
|
Kotlin
|
0
| 0
|
47500ee544412bf72a45390853fea18b48a7cbb7
| 10,349
|
unittestof
|
Apache License 2.0
|
src/maia/util/error/UnreachableCode.kt
|
waikato-maia
| 387,324,750
| false
| null |
package maia.util.error
/**
* Error thrown when code that is asserted to be unreachable,
* is, in fact, reached.
*
* @param reason The explanation of why this line should be unreachable.
*/
class UnreachableCode(
reason: String = "Code that was assumed unreachable was reached. This should not have happened."
): Error(
reason
)
/**
* Asserts that the line of code that this statement is on is unreachable.
*
* @throws UnreachableCode Always.
*/
inline fun UNREACHABLE_CODE(): Nothing = throw UnreachableCode()
/**
* Asserts that the line of code that this statement is on is unreachable.
*
* @param reason The explanation of why this line should be unreachable.
*
* @throws UnreachableCode Always.
*/
inline fun UNREACHABLE_CODE(reason: String): Nothing = throw UnreachableCode(reason)
| 0
|
Kotlin
|
0
| 0
|
63fb603dcf13d94c16c897d53082260060b68694
| 813
|
maia-util
|
Apache License 2.0
|
composites-fiberglass/src/main/kotlin/ru/ldralighieri/composites/fiberglass/column/FiberglassColumn.kt
|
LDRAlighieri
| 589,172,428
| false
|
{"Kotlin": 83209}
|
/*
* Copyright 2023 <NAME>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package ru.ldralighieri.composites.fiberglass.column
import androidx.compose.foundation.ScrollState
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.PaddingValues
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.verticalScroll
import androidx.compose.runtime.Composable
import androidx.compose.runtime.key
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.unit.dp
import ru.ldralighieri.composites.fiberglass.model.FiberglassColumnItemSlots
import ru.ldralighieri.composites.fiberglass.model.FiberglassItem
/**
* Fiberglass column Composite
*
* @param items List of [FiberglassItem] items.
* @param itemSlots FiberglassColumn [slots map][FiberglassColumnItemSlots].
* @param modifier The modifier to be applied to the Composite.
* @param scrollState Vertical scroll state.
* @param contentPadding A padding around the whole content. Negative padding is not permitted — it
* will cause IllegalArgumentException.
* @param verticalArrangement The vertical arrangement of the layout's children.
* @param horizontalAlignment The horizontal alignment of the layout's children.
*/
@Composable
fun FiberglassColumn(
items: List<FiberglassItem>,
itemSlots: FiberglassColumnItemSlots,
modifier: Modifier = Modifier,
scrollState: ScrollState? = null,
contentPadding: PaddingValues = PaddingValues(0.dp),
verticalArrangement: Arrangement.Vertical = Arrangement.Top,
horizontalAlignment: Alignment.Horizontal = Alignment.Start,
) {
Box(modifier = modifier) {
Column(
modifier = Modifier
.then(if (scrollState != null) Modifier.verticalScroll(scrollState) else Modifier)
.padding(contentPadding),
verticalArrangement = verticalArrangement,
horizontalAlignment = horizontalAlignment,
) {
items.forEach { item ->
key(item.id) {
itemSlots[item::class]?.let { it(item) }
}
}
}
}
}
| 0
|
Kotlin
|
2
| 7
|
4dcefd7a1a2a8bd24398c30499f27a1c9b0fb5ca
| 2,799
|
Composites
|
Apache License 2.0
|
stream-chat-android-client/src/main/java/io/getstream/chat/android/client/notifications/handler/NotificationHandlerFactory.kt
|
GetStream
| 177,873,527
| false
|
{"Kotlin": 8578375, "MDX": 2150736, "Java": 271477, "JavaScript": 6737, "Shell": 5229}
|
/*
* Copyright (c) 2014-2022 Stream.io Inc. All rights reserved.
*
* Licensed under the Stream License;
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://github.com/GetStream/stream-chat-android/blob/main/LICENSE
*
* 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.getstream.chat.android.client.notifications.handler
import android.annotation.SuppressLint
import android.app.Application
import android.app.NotificationChannel
import android.app.NotificationManager
import android.content.Context
import android.content.Intent
import android.os.Build
import androidx.annotation.RequiresApi
import androidx.core.app.NotificationCompat
import androidx.core.graphics.drawable.IconCompat
import io.getstream.android.push.permissions.DefaultNotificationPermissionHandler
import io.getstream.android.push.permissions.NotificationPermissionHandler
import io.getstream.chat.android.client.R
import io.getstream.chat.android.client.receivers.NotificationMessageReceiver
import io.getstream.chat.android.models.Channel
import io.getstream.chat.android.models.Message
import io.getstream.chat.android.models.User
import kotlin.reflect.full.primaryConstructor
/**
* Factory for default [NotificationHandler].
* Use it to customize an intent the user triggers when clicking on a notification.
*/
public object NotificationHandlerFactory {
/**
* Method that creates a [NotificationHandler].
*
* @param context The [Context] to build the [NotificationHandler] with.
* @param notificationConfig Configuration for push notifications.
* @param newMessageIntent Lambda expression used to generate an [Intent] to open your app
* @param notificationChannel Lambda expression used to generate a [NotificationChannel].
* Used in SDK_INT >= VERSION_CODES.O.
* @param userIconBuilder Generates [IconCompat] to be shown on notifications.
* @param permissionHandler Handles [android.Manifest.permission.POST_NOTIFICATIONS] permission lifecycle.
* @param notificationTextFormatter Lambda expression used to formats the text of the notification.
* @param actionsProvider Lambda expression used to provide actions for the notification.
*/
@SuppressLint("NewApi")
@JvmOverloads
@JvmStatic
public fun createNotificationHandler(
context: Context,
notificationConfig: NotificationConfig,
newMessageIntent: ((message: Message, channel: Channel) -> Intent) = getDefaultNewMessageIntentFun(context),
notificationChannel: (() -> NotificationChannel) = getDefaultNotificationChannel(context),
userIconBuilder: UserIconBuilder = provideDefaultUserIconBuilder(context),
permissionHandler: NotificationPermissionHandler? = provideDefaultNotificationPermissionHandler(context),
notificationTextFormatter: ((currentUser: User?, message: Message) -> CharSequence) =
getDefaultNotificationTextFormatter(notificationConfig),
actionsProvider: (notificationId: Int, channel: Channel, message: Message) -> List<NotificationCompat.Action> =
getDefaultActionsProvider(context),
): NotificationHandler = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
MessagingStyleNotificationHandler(
context = context,
newMessageIntent = newMessageIntent,
notificationChannel = notificationChannel,
userIconBuilder = userIconBuilder,
permissionHandler = permissionHandler,
notificationTextFormatter = notificationTextFormatter,
actionsProvider = actionsProvider,
)
} else {
ChatNotificationHandler(
context = context,
newMessageIntent = newMessageIntent,
notificationChannel = notificationChannel,
notificationTextFormatter = notificationTextFormatter,
actionsProvider = actionsProvider,
)
}
private fun getDefaultActionsProvider(
context: Context,
): (notificationId: Int, channel: Channel, message: Message) -> List<NotificationCompat.Action> =
{ notificationId, channel, message ->
listOf(
NotificationMessageReceiver.createReadAction(context, notificationId, channel, message),
NotificationMessageReceiver.createReplyAction(context, notificationId, channel),
)
}
private fun getDefaultNotificationTextFormatter(
notificationConfig: NotificationConfig,
): (currentUser: User?, message: Message) -> CharSequence = { currentUser, message ->
when (notificationConfig.autoTranslationEnabled) {
true -> currentUser?.language?.let { userLanguage ->
message.getTranslation(userLanguage).ifEmpty { message.text }
} ?: message.text
else -> message.text
}
}
private fun getDefaultNewMessageIntentFun(
context: Context,
): (message: Message, channel: Channel) -> Intent {
return { _, _ -> createDefaultNewMessageIntent(context) }
}
private fun createDefaultNewMessageIntent(context: Context): Intent =
context.packageManager!!.getLaunchIntentForPackage(context.packageName)!!
@RequiresApi(Build.VERSION_CODES.O)
private fun getDefaultNotificationChannel(context: Context): (() -> NotificationChannel) {
return {
NotificationChannel(
context.getString(R.string.stream_chat_notification_channel_id),
context.getString(R.string.stream_chat_notification_channel_name),
NotificationManager.IMPORTANCE_DEFAULT,
)
}
}
private fun provideDefaultUserIconBuilder(context: Context): UserIconBuilder {
// We search for the StreamCoilUserIconBuilder by reflection and this is slow - we need
// to postpone to not block the SDK initialisation
return object : UserIconBuilder {
private val builder by lazy {
val appContext = context.applicationContext
runCatching {
Class.forName(
"io.getstream.chat.android.ui.common.notifications." +
"StreamCoilUserIconBuilder",
)
.kotlin.primaryConstructor
?.call(appContext) as UserIconBuilder
}.getOrDefault(DefaultUserIconBuilder(appContext))
}
override suspend fun buildIcon(user: User): IconCompat? {
return builder.buildIcon(user)
}
}
}
private fun provideDefaultNotificationPermissionHandler(context: Context): NotificationPermissionHandler {
// We search for the SnackbarNotificationPermissionHandler by reflection and this is slow - we need
// to postpone to not block the SDK initialisation
return object : NotificationPermissionHandler {
private val handler by lazy {
val appContext = context.applicationContext
runCatching {
Class.forName(
"io.getstream.android.push.permissions.snackbar.SnackbarNotificationPermissionHandler",
).kotlin.primaryConstructor?.call(appContext) as NotificationPermissionHandler
}.getOrDefault(
DefaultNotificationPermissionHandler
.createDefaultNotificationPermissionHandler(appContext as Application),
)
}
override fun onPermissionDenied() {
handler.onPermissionDenied()
}
override fun onPermissionGranted() {
handler.onPermissionGranted()
}
override fun onPermissionRationale() {
handler.onPermissionRationale()
}
override fun onPermissionRequested() {
handler.onPermissionRequested()
}
}
}
}
| 24
|
Kotlin
|
273
| 1,451
|
8e46f46a68810d8086c48a88f0fff29faa2629eb
| 8,336
|
stream-chat-android
|
FSF All Permissive License
|
features/game/ui-logic/src/main/kotlin/io/github/japskiddin/sudoku/feature/game/ui/logic/utils/Utils.kt
|
Japskiddin
| 766,410,608
| false
|
{"Kotlin": 282363}
|
package io.github.japskiddin.sudoku.feature.game.ui.logic.utils
import io.github.japskiddin.sudoku.core.game.utils.BoardList
internal fun copyBoard(board: BoardList): BoardList = board.map { items -> items.map { item -> item.copy() } }
| 0
|
Kotlin
|
0
| 0
|
d21af36d52ba731dc70b6d50779a0efe1e5a2c44
| 238
|
SudokuGame
|
Apache License 2.0
|
plugins/kotlin/gradle/gradle-java/src/org/jetbrains/kotlin/idea/gradleJava/configuration/KotlinGradleBuildScriptSupport.kt
|
JetBrains
| 2,489,216
| false
| null |
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.kotlin.idea.configuration
import com.intellij.psi.PsiFile
import org.jetbrains.kotlin.idea.extensions.gradle.GradleBuildScriptSupport
import org.jetbrains.kotlin.idea.extensions.gradle.GradleVersionProvider
import org.jetbrains.kotlin.idea.extensions.gradle.SettingsScriptBuilder
import org.jetbrains.kotlin.psi.KtFile
class KotlinGradleBuildScriptSupport : GradleBuildScriptSupport {
override fun createManipulator(
file: PsiFile,
preferNewSyntax: Boolean,
versionProvider: GradleVersionProvider
): KotlinBuildScriptManipulator? {
if (file !is KtFile) {
return null
}
return KotlinBuildScriptManipulator(file, preferNewSyntax, versionProvider)
}
override fun createScriptBuilder(file: PsiFile): SettingsScriptBuilder<*>? {
return if (file is KtFile) KotlinSettingsScriptBuilder(file) else null
}
}
| 191
| null |
4372
| 13,319
|
4d19d247824d8005662f7bd0c03f88ae81d5364b
| 1,071
|
intellij-community
|
Apache License 2.0
|
SimpleDice/app/src/main/java/com/gmail/maxfixsoftware/simpledice/ui/FavoriteActivity.kt
|
bqfix
| 195,445,539
| false
| null |
package com.gmail.maxfixsoftware.simpledice.ui
import android.app.ActivityOptions
import android.content.Intent
import android.os.Build
import android.os.Bundle
import android.os.Handler
import android.util.Pair
import android.view.Menu
import android.view.MenuItem
import android.view.View
import android.widget.Toast
import androidx.appcompat.app.AlertDialog
import androidx.appcompat.app.AppCompatActivity
import androidx.core.view.MenuCompat
import androidx.lifecycle.ViewModelProviders
import androidx.recyclerview.widget.DividerItemDecoration
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.gmail.maxfixsoftware.simpledice.R
import com.gmail.maxfixsoftware.simpledice.database.AllDiceRollsViewModel
import com.gmail.maxfixsoftware.simpledice.database.AppDatabase
import com.gmail.maxfixsoftware.simpledice.database.AppExecutors
import com.gmail.maxfixsoftware.simpledice.utils.*
import com.google.android.gms.ads.AdRequest
import kotlinx.android.synthetic.main.activity_favorite.*
import kotlinx.android.synthetic.main.banner_ad.*
import kotlinx.android.synthetic.main.favorite_recycler_view.*
import kotlinx.android.synthetic.main.results.*
import kotlinx.android.synthetic.main.toolbar.*
import java.util.*
class FavoriteActivity : AppCompatActivity(), FavoriteDiceRollAdapter.FavoriteDiceRollClickHandler,
FavoriteDiceRollAdapter.DeleteDiceRollClickHandler, RollAsyncTask.RollAsyncPreExecute, RollAsyncTask.RollAsyncPostExecute {
private var mFavoriteDiceRollAdapter: FavoriteDiceRollAdapter? = null
private var widgetIntentHandled = false
private var mDiceRolls: MutableList<DiceRoll>? = null
private var mDatabase: AppDatabase? = null
private var mIsStillRolling : Boolean = false
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_favorite)
setSupportActionBar(toolbar)
supportActionBar!!.setDisplayHomeAsUpEnabled(true)
setTitle(R.string.favorite_activity_title)
setupAds()
restoreSavedInstanceState(savedInstanceState)
setupRecyclerView()
add_favorite_fab.setOnClickListener {
val intent = Intent(this@FavoriteActivity, AddFavoriteActivity::class.java)
startActivity(intent)
}
setupDatabaseAndViewModel()
handleWidgetIntent()
}
override fun onStart() {
super.onStart()
loadMostRecentDiceResults()
}
override fun onSaveInstanceState(outState: Bundle) {
super.onSaveInstanceState(outState)
outState.putBoolean(getString(R.string.widget_intent_handled_boolean_key), widgetIntentHandled)
}
/**
* A helper method to populate the results views with data
*
* @param diceResults to populate the views from
*/
private fun setDataToResultsViews(diceResults: DiceResults) {
results_name_tv.text = diceResults.name
results_total_tv.text = diceResults.total.toString()
results_descrip_tv.text = diceResults.descrip
}
/**
* Override of FavoriteDiceRoll click method
*
* @param favoriteDiceRoll the clicked DiceRoll to be used
*/
override fun onItemClick(favoriteDiceRoll: DiceRoll) { //If a previous roll is still going, show an error, else create a new roll
if (mIsStillRolling) {
Toast.makeText(this, R.string.async_task_still_executing, Toast.LENGTH_SHORT).show()
} else {
RollAsyncTask(this, this, this).execute(favoriteDiceRoll)
}
}
override fun onDeleteClick(favoriteDiceRoll: DiceRoll) {
val builder = AlertDialog.Builder(this)
builder.setTitle(R.string.delete_dialog_title)
.setMessage(R.string.delete_dialog_message)
.setPositiveButton(R.string.delete_dialog_positive) { dialog, which ->
AppExecutors.getInstance()!!.diskIO.execute {
mDatabase!!.diceRollDao().deleteDiceRoll(favoriteDiceRoll)
}
}
.setNegativeButton(R.string.delete_dialog_negative) { dialog, which -> dialog.cancel() }
.show()
}
/**
* Helper method to setup RecyclerView, should only be called once in onCreate
*/
private fun setupRecyclerView() {
val layoutManager = LinearLayoutManager(
this,
RecyclerView.VERTICAL,
false
)
favorite_rv.layoutManager = layoutManager
mFavoriteDiceRollAdapter = FavoriteDiceRollAdapter(this, this)
favorite_rv.adapter = mFavoriteDiceRollAdapter
favorite_rv.addItemDecoration(
DividerItemDecoration(
this,
DividerItemDecoration.VERTICAL
)
)
if (mDiceRolls == null) {
mDiceRolls = ArrayList()
}
mFavoriteDiceRollAdapter!!.setFavoriteDiceRolls(mDiceRolls!!)
}
/**
* A helper method to load the most recent dice results into the results views.
* Called in onStart, as it is cheaper than using a listener, since any new rolls occuring while this is the foreground activity will be updated directly.
*/
private fun loadMostRecentDiceResults() {
val diceResults = Utils.retrieveLatestDiceResults(this)
setDataToResultsViews(diceResults)
}
override fun onCreateOptionsMenu(menu: Menu): Boolean {
val inflater = this.menuInflater
inflater.inflate(R.menu.favorite_activity_menu, menu)
MenuCompat.setGroupDividerEnabled(menu, true)
return true
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
when (item.itemId) {
R.id.action_history -> {
val historyIntent = Intent(this@FavoriteActivity, HistoryActivity::class.java)
//Shared elements to animate (if SDK > 21), otherwise simply start activity
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
//Scroll results to start to make transition smoother
descrip_scrollview.smoothScrollTo(0, 0)
val optionsBundle = ActivityOptions.makeSceneTransitionAnimation(
this@FavoriteActivity,
Pair.create<View, String>(results_header, results_header.transitionName)
).toBundle()
startActivity(historyIntent, optionsBundle)
} else {
startActivity(historyIntent)
}
return true
}
R.id.action_settings -> {
val settingsIntent = Intent(this@FavoriteActivity, SettingsActivity::class.java)
startActivity(settingsIntent)
return true
}
android.R.id.home -> {
onBackPressed()
return true
}
else -> return super.onOptionsItemSelected(item)
}
}
/**
* A helper method to handle Intents coming from the widget that contain a DiceRoll to be rolled
* Called in onCreate, must be called after database is setup, and after savedInstanceState is restored.
*/
private fun handleWidgetIntent() {
if (!widgetIntentHandled) {
val intent = intent
val parcelableKey = getString(R.string.widget_favorites_intent_parcelable_key)
if (intent.hasExtra(parcelableKey)) { //If available, retrieve DiceRoll
val diceRoll = intent.getParcelableExtra<DiceRoll>(parcelableKey)
RollAsyncTask(this,this, this).execute(diceRoll)
}
widgetIntentHandled = true
}
}
/**
* Override to handle UI changes, etc when a roll begins executing
*/
override fun handleRollPreExecute() {
mIsStillRolling = true
/* Check again after 200ms if IsStillRolling, and show the progress bar if so.
This is to prevent blinking ProgressBars on rolls that happen almost instantly (i.e. most rolls)
*/
val handler = Handler()
handler.postDelayed({ if (mIsStillRolling){ results_progress_bar.visibility = View.VISIBLE }}, Constants.TIME_BEFORE_RESULTS_PROGRESS_BAR_DISPLAYS)
}
/** Handling for any given diceResults that occur from rolling a DiceRoll
*
* @param diceResults to use
*/
override fun handleRollResult(diceResults: DiceResults) {
mIsStillRolling = false
results_progress_bar.visibility = View.GONE
diceResults.saveToSharedPreferences(this)
setDataToResultsViews(diceResults)
AppExecutors.getInstance()!!.diskIO.execute {
mDatabase!!.diceResultsDao().insertDiceResults(diceResults)
}
}
/** A helper method for handling saved instance states in onCreate
*
* @param savedInstanceState to handle
*/
private fun restoreSavedInstanceState(savedInstanceState: Bundle?) {
if (savedInstanceState != null && !savedInstanceState.isEmpty) {
widgetIntentHandled =
savedInstanceState.getBoolean(getString(R.string.widget_intent_handled_boolean_key), false)
}
}
/**
* A helper method to setup an ad into the activity's AdView
*/
private fun setupAds() {
val adRequest = AdRequest.Builder().build()
banner_ad!!.loadAd(adRequest)
}
/**
* A helper method for preparing access to the database, and populating views relevant to it
*/
private fun setupDatabaseAndViewModel() {
mDatabase = AppDatabase.getInstance(this)
val viewModel = ViewModelProviders.of(this).get(AllDiceRollsViewModel::class.java)
viewModel.diceRolls!!.observe(this, androidx.lifecycle.Observer { diceRolls ->
//Hide Recycler and error, show ProgressBar
favorite_activity_no_favorites_tv.visibility = View.GONE
favorite_rv.visibility = View.GONE
favorite_progress_bar.visibility = View.VISIBLE
mDiceRolls = arrayListOf() //Clear and repopulate mDiceRolls
for (diceRoll in diceRolls) {
mDiceRolls!!.add(diceRoll)
}
mFavoriteDiceRollAdapter!!.setFavoriteDiceRolls(mDiceRolls!!)
Utils.updateAllWidgets(this@FavoriteActivity, mDiceRolls!!)
//Hide ProgressBar, check for favorites
favorite_progress_bar.visibility = View.GONE
if (mDiceRolls!!.isEmpty()) {
//Show error
favorite_activity_no_favorites_tv.visibility = View.VISIBLE
} else {
//Show Recycler
favorite_rv.visibility = View.VISIBLE
}
})
}
override fun onBackPressed() {
//If over version 21, scroll the results to start to make activity transitions appear smoother
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
descrip_scrollview.smoothScrollTo(0, 0)
val layoutManager = favorite_rv.layoutManager as LinearLayoutManager
layoutManager.scrollToPositionWithOffset(0, 0)
//Set the CardView's isTransitionGroup to true, to prevent blinking on return
favorite_rv_container.isTransitionGroup = true
result_container.isTransitionGroup = true
}
super.onBackPressed()
}
}
| 0
|
Kotlin
|
0
| 0
|
cec768b4f703c3c7647731c2bbfeb0f1df502015
| 11,497
|
SimpleDice
|
MIT License
|
src/main/kotlin/com/sourcegraph/cody/statusbar/CodyOpenSettingsAction.kt
|
sourcegraph
| 702,947,607
| false
|
{"Kotlin": 690009, "Java": 152855, "TypeScript": 5588, "Shell": 4631, "Nix": 1122, "JavaScript": 436, "HTML": 294}
|
package com.sourcegraph.cody.statusbar
import com.intellij.openapi.actionSystem.AnActionEvent
import com.intellij.openapi.options.ShowSettingsUtil
import com.sourcegraph.cody.config.ui.CodyConfigurable
import com.sourcegraph.common.ui.DumbAwareEDTAction
class CodyOpenSettingsAction : DumbAwareEDTAction("Open Settings") {
override fun actionPerformed(e: AnActionEvent) {
ShowSettingsUtil.getInstance().showSettingsDialog(e.project, CodyConfigurable::class.java)
}
}
| 358
|
Kotlin
|
22
| 67
|
437e3e2e53ae85edb7e445b2a0d412fbb7a54db0
| 477
|
jetbrains
|
Apache License 2.0
|
defitrack-rest/defitrack-protocol-services/defitrack-balancer/src/main/java/io/defitrack/protocol/balancer/pooling/BalancerArbitrumPoolingMarketProvider.kt
|
decentri-fi
| 426,174,152
| false
| null |
package io.defitrack.protocol.balancer.pooling
import io.defitrack.common.network.Network
import org.springframework.stereotype.Component
@Component
class BalancerArbitrumPoolingMarketProvider : BalancerPoolingMarketProvider(
listOf(
"0x7396f99B48e7436b152427bfA3DD6Aa8C7C6d05B",
"0x1c99324edc771c82a0dccb780cc7dda0045e50e7",
"0x2498A2B0d6462d2260EAC50aE1C3e03F4829BA95",
"0x7ADbdabaA80F654568421887c12F09E0C7BD9629",
"0x8eA89804145c007e7D226001A96955ad53836087",
"0xc7E5ED1054A24Ef31D827E6F86caA58B3Bc168d7",
"0x19DFEF0a828EEC0c85FbB335aa65437417390b85"
),
"0"
) {
override fun getNetwork(): Network {
return Network.ARBITRUM
}
}
| 17
|
Kotlin
|
6
| 9
|
cba6769eaa7a2700ccf5658c3ea9e3db7bdfca36
| 717
|
defi-hub
|
MIT License
|
app/src/main/java/com/mati/mimovies/utils/MovieNavigationItems.kt
|
mr-mati
| 697,450,396
| false
|
{"Kotlin": 147768}
|
package com.mati.mimovies.utils
sealed class MovieNavigationItems(val route:String){
object SignUpScreen : MovieNavigationItems("signUpScreen")
object SignInScreen : MovieNavigationItems("signInScreen")
object IntroScreen : MovieNavigationItems("introScreen")
object MovieScreen : MovieNavigationItems("movieScreen")
object MovieDetails : MovieNavigationItems("movieDetails")
object SearchScreen : MovieNavigationItems("searchScreen")
object ProfileScreen : MovieNavigationItems("profileScreen")
object ProfileEditScreen : MovieNavigationItems("profileEditScreen")
}
| 0
|
Kotlin
|
0
| 3
|
6c6d9e005b4d6af11303a8be2b7c29e90b701438
| 602
|
MiMovie
|
MIT License
|
app/src/main/java/com/prime/toolz/settings/Settings.kt
|
iZakirSheikh
| 494,154,853
| false
|
{"Kotlin": 239984, "Java": 178317}
|
package com.prime.toolz.settings
import androidx.compose.runtime.Immutable
import androidx.compose.runtime.Stable
import androidx.compose.ui.graphics.vector.ImageVector
import androidx.compose.ui.text.ExperimentalTextApi
import androidx.compose.ui.text.font.FontFamily
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.googlefonts.Font
import androidx.compose.ui.text.googlefonts.GoogleFont
import com.prime.toolz.R
import com.prime.toolz.core.NightMode
import com.primex.core.Text
import com.primex.preferences.Key
import com.primex.preferences.StringSaver
import com.primex.preferences.booleanPreferenceKey
import com.primex.preferences.intPreferenceKey
import com.primex.preferences.stringPreferenceKey
private const val TAG = "State"
/**
* Immutable data class representing a preference.
*
* @property value The value of the preference.
* @property title The title text of the preference.
* @property vector The optional vector image associated with the preference.
* @property summary The optional summary text of the preference.
* @param P The type of the preference value.
*/
@Immutable
data class Preference<out P>(
val value: P,
@JvmField val title: Text,
val vector: ImageVector? = null,
@JvmField val summery: Text? = null,
)
@OptIn(ExperimentalTextApi::class)
private val provider = GoogleFont.Provider(
"com.google.android.gms.fonts",
"com.google.android.gms",
R.array.com_google_android_gms_fonts_certs
)
@Stable
private fun FontFamily(name: String) =
FontFamily(
Font(GoogleFont(name), provider, FontWeight.Light),
Font(GoogleFont(name), provider, FontWeight.Medium),
Font(GoogleFont(name), provider, FontWeight.Normal),
Font(GoogleFont(name), provider, FontWeight.Bold),
)
/**
* Interface representing the settings.
*
* @property nightMode The state of the night mode preference.
* @property colorSystemBars The state of the color system bars preference.
* @property hideStatusBar The state of the hide status bar preference.
* @property dynamicColors The state of the dynamic colors preference.
* @property numberGroupSeparator The state of the number group separator preference.
*/
@Stable
interface Settings {
val nightMode: Preference<NightMode>
val colorSystemBars: Preference<Boolean>
val hideStatusBar: Preference<Boolean>
val dynamicColors: Preference<Boolean>
val numberGroupSeparator: Preference<Char>
/**
* Sets the value for the specified key.
*
* @param key the key for the setting
* @param value the value to be set
* @param S the type of setting
* @param O the type of value
*/
fun <S, O> set(key: Key<S, O>, value: O)
companion object {
const val route = "route_settings"
/**
* Provides the direction for the settings route.
*
* @return the route for settings
*/
fun direction() = route
/**
* Retrieves/Sets The [NightMode] Strategy
*/
val KEY_NIGHT_MODE = stringPreferenceKey(
"${TAG}_night_mode",
NightMode.FOLLOW_SYSTEM,
object : StringSaver<NightMode> {
override fun save(value: NightMode): String = value.name
override fun restore(value: String): NightMode = NightMode.valueOf(value)
},
)
val KEY_COLOR_STATUS_BAR = booleanPreferenceKey(TAG + "_color_status_bar", false)
val KEY_HIDE_STATUS_BAR = booleanPreferenceKey(TAG + "_hide_status_bar", false)
val KEY_DYNAMIC_COLORS = booleanPreferenceKey(TAG + "_dynamic_colors", true)
val KEY_GROUP_SEPARATOR =
stringPreferenceKey(
TAG + "_group_separator",
',',
object : StringSaver<Char> {
override fun restore(value: String): Char = value[0]
override fun save(value: Char): String = "$value"
}
)
val LatoFontFamily = FontFamily("Roboto")
}
}
| 0
|
Kotlin
|
0
| 3
|
de0dda2cf49d949d3e910f11569e5f6a345fd4a2
| 4,073
|
Toolz
|
Apache License 2.0
|
app/src/main/java/com/lubulwa/tddkotlin/example3/Interval.kt
|
richmahnn
| 224,686,303
| false
| null |
package com.lubulwa.tddkotlin.example3
class Interval(private val mStart: Int, private val mEnd: Int) {
init {
require(mStart < mEnd) { "Invalid interval range" }
}
fun getStart(): Int = mStart
fun getEnd(): Int = mEnd
}
| 1
| null |
1
| 1
|
96e5146283361db0c9c8c745bc93a5e11f60da2f
| 250
|
TDD-Kotlin
|
MIT License
|
data/src/main/java/app/delish/data/pref/repository/DataStoreOperations.kt
|
Elbehiry
| 349,764,209
| false
| null |
/*
* Copyright 2021 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* 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 app.food_directory.data.pref.repository
import androidx.datastore.preferences.core.Preferences
import app.food_directory.result.Result
import kotlinx.coroutines.flow.Flow
interface DataStoreOperations {
suspend fun save(key: Preferences.Key<Boolean>, value: Boolean)
fun read(key: Preferences.Key<Boolean>): Flow<Result<Boolean>>
}
| 0
| null |
60
| 399
|
2e7c8db43976e14d6967c610a2337b56c5016fb5
| 967
|
Delish
|
Apache License 2.0
|
gradle-plugins/compose/src/test/test-projects/misc/jvmOnlyResources/expected/mainResourceAccessors/me/app/jvmonlyresources/generated/resources/Drawable0.main.kt
|
JetBrains
| 293,498,508
| false
| null |
@file:OptIn(org.jetbrains.compose.resources.InternalResourceApi::class)
package me.app.jvmonlyresources.generated.resources
import kotlin.OptIn
import kotlin.String
import kotlin.collections.MutableMap
import org.jetbrains.compose.resources.DrawableResource
import org.jetbrains.compose.resources.InternalResourceApi
private object MainDrawable0 {
public val vector: DrawableResource by
lazy { init_vector() }
}
@InternalResourceApi
internal fun _collectMainDrawable0Resources(map: MutableMap<String, DrawableResource>) {
map.put("vector", MainDrawable0.vector)
}
internal val Res.drawable.vector: DrawableResource
get() = MainDrawable0.vector
private fun init_vector(): DrawableResource = org.jetbrains.compose.resources.DrawableResource(
"drawable:vector",
setOf(
org.jetbrains.compose.resources.ResourceItem(setOf(),
"composeResources/me.app.jvmonlyresources.generated.resources/drawable/vector.xml", -1, -1),
)
)
| 64
| null |
1174
| 16,150
|
7e9832f6494edf3e7967082c11417e78cfd1d9d0
| 960
|
compose-multiplatform
|
Apache License 2.0
|
lib/src/main/java/com/kirkbushman/araw/helpers/AuthScriptHelper.kt
|
KirkBushman
| 182,531,355
| false
| null |
package com.kirkbushman.araw.helpers
import android.content.Context
import com.kirkbushman.araw.RedditClient
import com.kirkbushman.auth.RedditAuth
import com.kirkbushman.auth.managers.SharedPrefsStorageManager
class AuthScriptHelper(
context: Context,
clientId: String,
clientSecret: String,
username: String,
password: String,
logging: Boolean = false,
disableLegacyEncoding: Boolean = false
) : AuthHelper(
logging = logging,
disableLegacyEncoding = disableLegacyEncoding
) {
override val auth by lazy {
RedditAuth.Builder()
.setRetrofit(RedditClient.getRetrofit(logging))
.setStorageManager(SharedPrefsStorageManager(context))
.setScriptAuthCredentials(
clientId = clientId,
clientSecret = clientSecret,
username = username,
password = password
)
.setLogging(logging)
.build()
}
override fun getRedditClient(): RedditClient? {
val savedClient = getSavedRedditClient()
if (savedClient != null) {
return savedClient
}
val bearer = auth.authenticate()
if (bearer != null) {
return RedditClient(
bearer = bearer,
disableLegacyEncoding = disableLegacyEncoding,
logging = logging
)
}
return null
}
}
| 9
| null |
9
| 84
|
aeae071fa8d2a4e378de4a71420dc2a9792591f3
| 1,447
|
ARAW
|
MIT License
|
sqldelight-idea-plugin/src/main/kotlin/app/cash/sqldelight/intellij/GradleSystemListener.kt
|
cashapp
| 44,677,680
| false
| null |
package com.squareup.sqldelight.intellij
import com.intellij.openapi.externalSystem.model.task.ExternalSystemTaskId
import com.intellij.openapi.externalSystem.model.task.ExternalSystemTaskNotificationListenerAdapter
import com.squareup.sqldelight.core.SqlDelightProjectService
import org.jetbrains.kotlin.idea.framework.GRADLE_SYSTEM_ID
class GradleSystemListener : ExternalSystemTaskNotificationListenerAdapter() {
override fun onSuccess(id: ExternalSystemTaskId) {
if (id.projectSystemId == GRADLE_SYSTEM_ID) {
// Gradle sync just finished, reset the file index.
id.findProject()?.let { project ->
SqlDelightProjectService.getInstance(project).resetIndex()
}
}
}
}
| 195
|
Kotlin
|
373
| 4,449
|
d995c74b16c826ae6dbaa899e3d9ece127ebb6fe
| 707
|
sqldelight
|
Apache License 2.0
|
day07/main.kt
|
LOZORD
| 441,007,912
| false
|
{"Kotlin": 29367, "Python": 963}
|
import java.util.Scanner
fun main(args: Array<String>) {
val initialPositions = Scanner(System.`in`)
.nextLine()
.split(',')
.map { Integer.parseInt(it) }
.toIntArray()
check(initialPositions.isNotEmpty())
if (args.contains("--part1")) {
val median = initialPositions
.sorted()
.get(initialPositions.size / 2)
val fuel = initialPositions
.map { Math.abs(it - median) }
.sum()
println("FUEL: $fuel; POSITION: $median")
return
}
val mean = Math.floor(initialPositions.sum().toDouble() / initialPositions.size.toDouble()).toInt()
val fuel = initialPositions
.map { Math.abs(it - mean) } // Distance to the mean.
.map { (it * (it+1)) / 2 } // Gauss sum formula for 1->it for new fuel rule.
.sum()
println("FUEL: $fuel; POSITION: $mean")
}
| 0
|
Kotlin
|
0
| 0
|
17dd266787acd492d92b5ed0d178ac2840fe4d57
| 918
|
aoc2021
|
MIT License
|
updater-deob/src/main/java/org/runestar/client/updater/deob/rs/mult/MultiplierFinder.kt
|
forsco
| 135,697,131
| true
|
{"Kotlin": 1058154, "Java": 4007}
|
package org.runestar.client.updater.deob.rs.mult
import com.fasterxml.jackson.databind.SerializationFeature
import com.fasterxml.jackson.module.kotlin.jacksonObjectMapper
import com.google.common.collect.Multimap
import com.google.common.collect.MultimapBuilder
import org.kxtra.slf4j.loggerfactory.getLogger
import org.objectweb.asm.Opcodes.*
import org.objectweb.asm.Type.*
import org.objectweb.asm.tree.*
import org.objectweb.asm.tree.analysis.Analyzer
import org.objectweb.asm.tree.analysis.BasicInterpreter
import org.objectweb.asm.tree.analysis.BasicValue
import org.runestar.client.updater.deob.Transformer
import org.runestar.client.updater.deob.readJar
import org.runestar.client.updater.deob.writeJar
import java.nio.file.Path
import java.util.*
import kotlin.collections.HashSet
import kotlin.math.min
object MultiplierFinder : Transformer {
private val mapper = jacksonObjectMapper().enable(SerializationFeature.INDENT_OUTPUT)
private val logger = getLogger()
override fun transform(source: Path, destination: Path) {
val classNodes = readJar(source)
val decoders = MultimapBuilder.hashKeys().arrayListValues().build<String, Const>()
val encoders = MultimapBuilder.hashKeys().arrayListValues().build<String, Const>()
val candidateFields = candidateFields(classNodes)
classNodes.forEach { c ->
c.methods.forEach { m ->
analyzeMethod(c, m, decoders, encoders)
}
}
val result = unfoldToDecoders(decoders, encoders, candidateFields)
val multFile = destination.resolveSibling(destination.fileName.toString() + ".mult.json").toFile()
mapper.writeValue(multFile, result)
if (source != destination) {
writeJar(classNodes, destination)
}
}
private fun analyzeMethod(
c: ClassNode,
m: MethodNode,
decoders: Multimap<String, Const>,
encoders: Multimap<String, Const>
) {
val a = Analyzer<BasicValue>(BasicInterpreter())
a.analyze(c.name, m)
val frames = a.frames
val insns = m.instructions.toArray()
val slots = TreeMap<Int, Slot>()
fun slotsRemove(index: Int): Slot? {
val x = slots.remove(index)
if (x is Slot.Mul.Field) {
decoders.put(x.f, Const.Direct(x.n))
}
return x
}
fun slotsPut(index: Int, s: Slot) {
slotsRemove(index)
slots[index] = s
}
out@
for (i in 0 until insns.size - 1) {
val insn = insns[i]
val op = insn.opcode
when (op) {
LDC -> {
insn as LdcInsnNode
val cst = insn.cst
if (cst is Int || cst is Long) {
slotsPut(frames[i + 1].stackSize - 1, Slot.Operand.Ldc(cst as Number))
continue@out
}
}
GETFIELD, GETSTATIC -> {
insn as FieldInsnNode
val desc = insn.desc
if (desc == INT_TYPE.descriptor || desc == LONG_TYPE.descriptor) {
val fieldName = "${insn.owner}.${insn.name}"
slotsPut(frames[i + 1].stackSize - 1, Slot.Operand.Field(fieldName))
continue@out
}
}
IMUL, LMUL -> {
val stackSize = frames[i].stackSize
val x = slotsRemove(stackSize - 2)
val y = slotsRemove(stackSize - 1)
if (x is Slot.Operand && y is Slot.Operand && x.javaClass != y.javaClass) {
val opf = x as? Slot.Operand.Field ?: y as Slot.Operand.Field
val opl = x as? Slot.Operand.Ldc ?: y as Slot.Operand.Ldc
slotsPut(stackSize - 2, Slot.Mul.Field(opl.n, opf.f))
continue@out
}
if (x is Slot.Operand.Ldc || y is Slot.Operand.Ldc) {
val opl = x as? Slot.Operand.Ldc ?: y as Slot.Operand.Ldc
slotsPut(stackSize - 2, Slot.Mul.Other(opl.n))
continue@out
}
}
PUTFIELD, PUTSTATIC -> {
insn as FieldInsnNode
val desc = insn.desc
if (desc == INT_TYPE.descriptor || desc == LONG_TYPE.descriptor) {
val stackSize = frames[i].stackSize
val x = slots.remove(stackSize - 1)
if (x != null) {
val fieldName = "${insn.owner}.${insn.name}"
if (x is Slot.Mul.Field) {
encoders.put(fieldName, Const.FieldFolded(x.n, x.f))
// decoders.put(x.f, Const.FieldFolded(x.n, fieldName))
continue@out
} else if (x is Slot.Mul.Other) {
encoders.put(fieldName, Const.Direct(x.n))
continue@out
}
}
}
}
}
val validStackSize = min(
frames[i].stackSize - insn.stackConsumed + 1,
frames[i + 1].stackSize - insn.stackProduced + 1
)
while (slots.isNotEmpty() && slots.lastKey() > validStackSize) {
slotsRemove(slots.lastKey())
}
}
while (slots.isNotEmpty()) {
slotsRemove(slots.lastKey())
}
}
private fun unfoldToDecoders(
decoders: Multimap<String, Const>,
encoders: Multimap<String, Const>,
candidateFields: Set<String>
): Map<String, Number> {
val result = TreeMap<String, Number>()
// todo
val directDecoders = MultimapBuilder.hashKeys().arrayListValues().build<String, Number>()
val indirectDecoders = MultimapBuilder.hashKeys().arrayListValues().build<String, Number>()
decoders.forEach { fieldName, cst ->
if (cst is Const.Direct) {
if (isInvertible(cst.n)) {
directDecoders.put(fieldName, cst.n)
} else {
val unfolded = unfold1(cst.n)
if (unfolded != null) {
indirectDecoders.put(fieldName, unfolded)
}
}
}
}
encoders.forEach { fieldName, cst ->
if (cst is Const.Direct) {
if (isInvertible(cst.n)) {
directDecoders.put(fieldName, invert(cst.n))
} else {
val unfolded = unfold1(cst.n)
if (unfolded != null) {
indirectDecoders.put(fieldName, invert(unfolded))
}
}
}
}
candidateFields.forEach { f ->
val direct = directDecoders.get(f) ?: return@forEach
val indirect = indirectDecoders.get(f)
val dir = direct.maxBy { Collections.frequency(direct, it) }
if (dir != null) {
result[f] = dir
}
}
candidateFields.forEach { f ->
val dir = result[f]
if (dir == null) {
val enc = encoders[f]
val cst = enc.maxBy { Collections.frequency(enc, it) }
if (cst is Const.FieldFolded) {
val other = result[cst.f]
if (other != null) {
val n: Number = when (other) {
is Int -> cst.n.toInt() / other
is Long -> cst.n.toLong() / other
else -> error(other)
}
val unfold = unfold1(n)
if (unfold != null) {
result[f] = invert(unfold)
}
}
}
}
}
return result
}
private val AbstractInsnNode.stackProduced: Int get() {
if (opcode < 0) return 0
return org.apache.bcel.Const.getConsumeStack(opcode).coerceAtLeast(0)
}
private val AbstractInsnNode.stackConsumed: Int get() {
if (opcode < 0) return 0
return org.apache.bcel.Const.getProduceStack(opcode).coerceAtLeast(0)
}
private fun candidateFields(classNodes: Iterable<ClassNode>): Set<String> {
val set = HashSet<String>()
classNodes.forEach { c ->
c.fields.forEach { f ->
if (f.desc == INT_TYPE.descriptor || f.desc == LONG_TYPE.descriptor) {
set.add("${c.name}.${f.name}")
}
}
}
return set
}
interface Slot {
interface Operand : Slot {
data class Ldc(val n: Number) : Operand
data class Field(val f: String) : Operand
}
interface Mul : Slot {
data class Field(val n: Number, val f: String) : Mul
data class Other(val n: Number) : Mul
}
}
interface Const {
data class Direct(val n: Number) : Const
data class FieldFolded(val n: Number, val f: String) : Const
}
}
| 0
|
Kotlin
|
0
| 0
|
b15c07570af82377bcd2be48b00a5e9708be08ab
| 9,570
|
client
|
MIT License
|
app/src/main/java/com/example/pokinfo/viewModels/AbilityViewModel.kt
|
T1396
| 792,347,025
| false
|
{"Kotlin": 440915}
|
package com.example.pokinfo.viewModels
import android.app.Application
import androidx.lifecycle.AndroidViewModel
import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.viewModelScope
import com.example.pokeinfo.data.graphModel.AbilityDetailQuery
import com.example.pokeinfo.data.graphModel.AllAbilitiesQuery
import com.example.pokinfo.R
import com.example.pokinfo.adapter.abilities.AbilityListAdapter
import com.example.pokinfo.adapter.home.detail.AbilityEffectText
import com.example.pokinfo.data.RepositoryProvider
import com.example.pokinfo.data.enums.AbilityFilter
import com.example.pokinfo.data.models.database.pokemon.LanguageNames
import com.example.pokinfo.data.models.database.pokemon.PokemonForList
import com.example.pokinfo.data.models.database.pokemon.PokemonTypeName
import com.example.pokinfo.data.models.database.pokemon.VersionNames
import com.example.pokinfo.data.util.sharedPreferences
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
class AbilityViewModel(application: Application, private val sharedViewModel: SharedViewModel) :
AndroidViewModel(application) {
private val repository = RepositoryProvider.provideRepository(application)
private var languageId by application.sharedPreferences("languageId", 9)
var versionNames: List<VersionNames> = emptyList()
private set
var languageNames: List<LanguageNames> = emptyList()
private set
var pokemonTypeNames: List<PokemonTypeName> = emptyList()
private set
init {
loadGenericData()
}
private fun loadGenericData() {
viewModelScope.launch(Dispatchers.IO) {
versionNames = repository.getVersionNames(languageId)
languageNames = repository.getLanguageNames()
pokemonTypeNames = repository.getPokemonTypeNames(languageId)
}
}
private val _allAbilities = MutableLiveData<List<AbilityListAdapter.AbilityInfo>?>()
private val abilityMapper: (AllAbilitiesQuery.Data?) -> List<AbilityListAdapter.AbilityInfo> = { response ->
response?.response?.data?.map { ability ->
AbilityListAdapter.AbilityInfo(
abilityId = ability.id,
name = ability.names.firstOrNull()?.name ?: "No Name found",
generationNr = ability.generation_id ?: 1,
)
} ?: emptyList()
}
private var _isLoading = MutableLiveData(false)
val isLoading: LiveData<Boolean> get() = _isLoading
private var _abilityDetails = MutableLiveData<AbilityDetailQuery.Data?>()
val abilityDetail: LiveData<AbilityDetailQuery.Data?>
get() = _abilityDetails
// Define a mapper function for ability details similar to abilityMapper
private val detailMapper: (AbilityDetailQuery.Data?) -> List<AbilityEffectText> = { data ->
data?.data?.firstOrNull()?.let { detail ->
detail.effectTexts.map { effectText ->
val effectTextLangId = effectText.language_id
AbilityEffectText(
abilityId = effectText.ability_id ?: -1,
name = detail.names.nodes.find { it.language_id == effectTextLangId }?.name
?: "No name found",
languageId = effectTextLangId ?: -1,
textLong = effectText.effect,
textShort = effectText.short_effect,
slot = -1
)
}.sortedWith(compareBy { it.languageId != languageId })
} ?: emptyList()
}
// Use the mapper to transform the LiveData from repository data
fun prepareAbilityDetails() {
val ability = _abilityDetails.value
val mappedDetails = detailMapper(ability)
_abilityEffectTexts.postValue(mappedDetails)
}
private val _abilityEffectTexts = MutableLiveData<List<AbilityEffectText>>()
val abilityEffectTexts: LiveData<List<AbilityEffectText>> get() = _abilityEffectTexts
private val _selectedAbilityFilter = MutableLiveData<AbilityFilter?>()
private val selectedAbilityFilter: LiveData<AbilityFilter?>
get() = _selectedAbilityFilter
private val _filteredAbilityList = MutableLiveData<List<AbilityListAdapter.AbilityInfo>?>()
val filteredAbilityList: LiveData<List<AbilityListAdapter.AbilityInfo>?>
get() = _filteredAbilityList
private val _searchInputAbility = MutableLiveData("")
fun setSearchInput(input: String) {
_searchInputAbility.value = input
filterAbilities()
}
fun getAllAbilities() {
_isLoading.value = true
viewModelScope.launch(Dispatchers.IO) {
val abilitiesList = repository.loadAllAbilities(languageId)
if (abilitiesList == null) {
sharedViewModel.postMessage(R.string.failed_to_load_abilities) {
// pass this function as lambda to make a retry function
getAllAbilities()
}
_allAbilities.postValue(null)
_filteredAbilityList.postValue(null)
_isLoading.postValue(false)
} else {
viewModelScope.launch(Dispatchers.Main) {
_allAbilities.value = abilityMapper.invoke(abilitiesList)
_filteredAbilityList.value = _allAbilities.value
_isLoading.value = false
}
}
}
}
fun getAbilityDetail(abilityId: Int) {
viewModelScope.launch(Dispatchers.IO) {
val abilityDetail = repository.loadAbilityDetails(abilityId)
_abilityDetails.postValue(abilityDetail)
}
}
/** Gets all Pokemon who learns the move the user is inspecting */
fun getPokemonListWhoHaveAbility(onLoadFinished: (List<PokemonForList>) -> Unit) {
val ids = _abilityDetails.value?.data?.firstOrNull()?.pokemonList?.mapNotNull {
it.pokemon_id
} ?: return
viewModelScope.launch(Dispatchers.IO) {
val list = repository.getPokemonListFromIdList(ids)
onLoadFinished(list)
}
}
fun selectAbilitiesFilter(filter: AbilityFilter, isSelected: Boolean) {
if (isSelected) {
_selectedAbilityFilter.value = filter
} else {
_selectedAbilityFilter.value = null // remove filter
}
filterAbilities()
}
private fun filterAbilities() {
val searchInput = _searchInputAbility.value.orEmpty()
val currentFilters = selectedAbilityFilter.value
val allAbilities = _allAbilities.value.orEmpty()
// filter depending on the active filter (currentFilters)
val filteredList = allAbilities.filter { ability ->
// first filter with searchInput
ability.name.contains(searchInput, true) &&
(currentFilters == null || ability.generationNr == currentFilters.genId)
// if a filter is selected filter the ability where genID match with filter genID else don't filter
}
_filteredAbilityList.postValue(filteredList)
}
fun getAbilityName(): String {
val ability = _abilityDetails.value?.data?.firstOrNull()
val abilityName = ability?.names?.nodes?.find { it.language_id == this.languageId }?.name
return abilityName ?: ability?.name ?: "No Name found"
}
}
| 0
|
Kotlin
|
0
| 0
|
f6cb3ab047fb1b67d08db0eda2f138000402c91a
| 7,427
|
PokemonApp
|
Info-ZIP License
|
app/src/main/java/divyansh/tech/animeclassroom/animeDetail/AnimeDetailFragment.kt
|
justdvnsh
| 361,118,759
| false
| null |
package divyansh.tech.animeclassroom.animeDetail
import android.os.Bundle
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.Fragment
import androidx.fragment.app.viewModels
import androidx.lifecycle.Observer
import androidx.navigation.fragment.findNavController
import androidx.navigation.fragment.navArgs
import androidx.recyclerview.widget.GridLayoutManager
import com.google.android.material.snackbar.Snackbar
import dagger.hilt.android.AndroidEntryPoint
import divyansh.tech.animeclassroom.common.utils.EventObserver
import divyansh.tech.animeclassroom.common.utils.ResultWrapper
import divyansh.tech.animeclassroom.animeDetail.callbacks.EpisodeClickCallback
import divyansh.tech.animeclassroom.animeDetail.callbacks.FavoriteClickCallback
import divyansh.tech.animeclassroom.animeDetail.epoxy.EpoxyAnimeDetailController
import divyansh.tech.animeclassroom.databinding.FragmentAnimeDetailsBinding
@AndroidEntryPoint
class AnimeDetailFragment: Fragment() {
private lateinit var _binding: FragmentAnimeDetailsBinding
val binding: FragmentAnimeDetailsBinding get() = _binding
private val viewModel by viewModels<AnimeDetailViewModel>()
private val args by navArgs<AnimeDetailFragmentArgs>()
private val animeDetailController by lazy {
val clickCallback = EpisodeClickCallback(viewModel)
val favoriteClickCallback = FavoriteClickCallback(viewModel)
EpoxyAnimeDetailController(clickCallback, favoriteClickCallback, args.animeUrl)
}
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View {
_binding = FragmentAnimeDetailsBinding.inflate(inflater, container, false)
return binding.root
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
setupObservers()
setupRecyclerView()
}
private fun setupRecyclerView() {
binding.animeDetailRv.apply {
layoutManager = GridLayoutManager(requireActivity(), 3)
animeDetailController.spanCount = 3
(layoutManager as GridLayoutManager).spanSizeLookup = animeDetailController.spanSizeLookup
adapter = animeDetailController.adapter
}
}
private fun setupObservers() {
viewModel.animeDetailLiveData.observe(
viewLifecycleOwner,
Observer {
when (it) {
is ResultWrapper.Success -> {
Log.i("ANIME DETAIL -> ", it.data.toString())
animeDetailController.setData(it.data, viewModel.episodeListLiveData.value?.data)
}
is ResultWrapper.Error -> Log.i("ANIME DETAIL", it.message.toString())
is ResultWrapper.Loading -> {}
}
}
)
viewModel.episodeListLiveData.observe(
viewLifecycleOwner,
Observer {
when (it) {
is ResultWrapper.Success -> animeDetailController.setData(viewModel.animeDetailLiveData.value?.data, it.data)
is ResultWrapper.Error -> Log.i("ANIME DETAIL", it.message.toString())
is ResultWrapper.Loading -> {}
}
}
)
viewModel.animeSavedLiveData.observe(
viewLifecycleOwner,
EventObserver {
if (it)
Snackbar.make(
requireView(),
"Anime Saved Successfully",
Snackbar.LENGTH_SHORT
).show()
else
Snackbar.make(
requireView(),
"Anime Could not be saved !",
Snackbar.LENGTH_SHORT
).show()
}
)
viewModel.navigation.observe(
viewLifecycleOwner,
EventObserver {
findNavController().navigate(it)
}
)
}
override fun onResume() {
super.onResume()
viewModel.getAnimeDetails(args.animeUrl)
}
}
| 47
| null |
32
| 95
|
53aa9258daa16022cad3b3dd961ceb60be01e67e
| 4,305
|
AnimeClassroom
|
MIT License
|
jvm/src/main/kotlin/org/ionproject/core/calendar/icalendar/properties/calendar/ProductIdentifier.kt
|
i-on-project
| 242,369,946
| false
| null |
package org.ionproject.core.calendar.icalendar.properties.calendar
import org.ionproject.core.calendar.icalendar.properties.Property
import org.ionproject.core.calendar.icalendar.types.Text
import org.ionproject.core.calendar.toText
class Method(
text: String
) : Property {
override val value: Text = text.toText()
override val name: String
get() = iCalName
companion object {
private const val iCalName = "METHOD"
}
}
| 14
|
Kotlin
|
0
| 3
|
339407d56e66ec164ecdc4172347272d97cc26b3
| 461
|
core
|
Apache License 2.0
|
libs/string-parser/src/commonMain/kotlin/kotl/parser/Parser.kt
|
kotlin-telegram
| 697,770,526
| false
|
{"Kotlin": 61657}
|
package kotl.parser
public fun interface Parser<out T> {
public fun parse(string: String): ParserResult<T>
}
| 0
|
Kotlin
|
0
| 9
|
24baf9d20f9be26db48d6176e204cba6df1a3899
| 114
|
koTL
|
MIT License
|
AndroidFlutterApp/app/src/main/java/ru/gc986/testhybridappandroidflutter/MainActivity.kt
|
gc986
| 277,557,370
| false
|
{"Dart": 8906, "Kotlin": 4695}
|
package ru.gc986.testhybridappandroidflutter
import android.os.Bundle
import android.util.Log
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import io.flutter.embedding.android.FlutterFragment
import io.flutter.plugin.common.MethodChannel
import kotlinx.android.synthetic.main.activity_main.*
import ru.gc986.testhybridappandroidflutter.MyApplication.Companion.ENGINE_ID
class MainActivity : AppCompatActivity() {
private var flutterFragment: FlutterFragment? = null
private val TAG_FLUTTER_FRAGMENT = "TAG_FLUTTER_FRAGMENT"
private val FLATTER_CHANEL = "samples.flutter.dev/battery"
private var channelResult: MethodChannel.Result? = null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
openFlutterScreen()
btRoot.setOnClickListener {
Toast.makeText(this, "/", Toast.LENGTH_LONG).show()
try {
channelResult?.success("/")
} catch (e: Exception) {
e.printStackTrace()
}
}
btOpenCalculator.setOnClickListener {
Toast.makeText(this, "calculator", Toast.LENGTH_LONG).show()
try {
channelResult?.success("/calculator")
} catch (e: Exception) {
e.printStackTrace()
}
}
btOpenSettings.setOnClickListener {
Toast.makeText(this, "settings", Toast.LENGTH_LONG).show()
try {
channelResult?.success("/settings")
} catch (e: Exception) {
e.printStackTrace()
}
}
btBack.setOnClickListener {
Toast.makeText(this, "back", Toast.LENGTH_LONG).show()
try {
channelResult?.success("back")
} catch (e: Exception) {
e.printStackTrace()
}
}
}
private fun openFlutterScreen() {
flutterFragment = FlutterFragment.withCachedEngine(ENGINE_ID).build()
flutterFragment?.let {
replaceFragment(it, TAG_FLUTTER_FRAGMENT)
}
MethodChannel(
MyApplication.flutterEngine.dartExecutor.binaryMessenger,
FLATTER_CHANEL
).setMethodCallHandler { call, result ->
channelResult = result
}
}
private fun replaceFragment(flutterFragment: FlutterFragment, tag: String) {
supportFragmentManager
.beginTransaction()
.replace(
R.id.flFlutterContainer,
flutterFragment,
tag
)
.commit()
}
}
| 0
|
Dart
|
0
| 0
|
3ae30471d8707f68fcc94371ef2d30c431c50fe7
| 2,710
|
FlatterHybridNavigator
|
Apache License 2.0
|
app/src/main/java/com/np/composesideeffects/practicals/RememberCoroutineScope.kt
|
nirajphutane
| 799,476,164
| false
|
{"Kotlin": 61202}
|
package com.np.composesideeffects.practicals
import android.os.Bundle
import android.text.Html
import android.view.View
import android.widget.Toast
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.material3.Button
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Surface
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.key
import androidx.compose.runtime.mutableIntStateOf
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.runtime.setValue
import androidx.compose.runtime.staticCompositionLocalOf
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.tooling.preview.Preview
import androidx.core.text.HtmlCompat
import com.np.composesideeffects.base_pkgs.BaseFragment
import com.np.composesideeffects.core.appLog
import com.np.composesideeffects.ui.theme.ComposeSideEffectsTheme
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
class RememberCoroutineScope: BaseFragment() {
@Composable
override fun View() = ComposeView()
@Preview @Composable
override fun Preview() = ComposeView()
private val screen = "RememberCoroutineScope"
private val localScreen = staticCompositionLocalOf { screen }
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
appLog(screen)
}
@Composable
private fun ComposeView() {
ComposeSideEffectsTheme {
Surface(
modifier = Modifier.fillMaxSize(),
color = MaterialTheme.colorScheme.background
) {
var recompose by remember { mutableIntStateOf(1001) }
var composeAgain by remember { mutableStateOf(false) }
var showCompose by remember { mutableStateOf(true) }
Column(
modifier = Modifier.fillMaxSize(),
horizontalAlignment = Alignment.CenterHorizontally,
verticalArrangement = Arrangement.Center
) {
Text(localScreen.current)
Button(onClick = { recompose += 123 }) {
Text("Recompose")
}
Button(onClick = { composeAgain = !composeAgain }) {
Text("Compose Again")
}
Button(onClick = { showCompose = !showCompose }) {
Text((if(showCompose) "Remove" else "Add") + " Compose")
}
if(showCompose) {
key(composeAgain) {
Counter(recompose)
}
}
}
}
}
}
@Composable
fun Counter(state: Int) {
appLog("State: $state")
var count by remember { mutableIntStateOf(0) }
var isEnabled by remember { mutableStateOf(true) }
val coroutineScope = rememberCoroutineScope()
Text("State: $state")
Button(
onClick = {
isEnabled = false
coroutineScope.launch {
count = 0
try {
while (count < 5) {
delay(1000)
count++
appLog("Tick: $count")
}
Toast.makeText(context, Html.fromHtml("<font color='#00FF00'>Counter finished!!</font>", HtmlCompat.FROM_HTML_MODE_COMPACT), Toast.LENGTH_SHORT).show()
} catch(e: Exception) {
appLog("Error: ${e.message}")
Toast.makeText(context, Html.fromHtml("<font color='#FF0000'>Error: ${e.message}</font>", HtmlCompat.FROM_HTML_MODE_COMPACT), Toast.LENGTH_SHORT).show()
}
isEnabled = true
}
},
enabled = isEnabled
) {
Text("Start 5sec Counter")
}
Text("Count: $count")
}
}
/*
To launch a coroutine outside of a composable, but scoped so that it will be automatically
canceled once it leaves the composition, use rememberCoroutineScope. Also use rememberCoroutineScope
whenever you need to control the lifecycle of one or more coroutines manually.
The rememberCoroutineScope is a composable function that returns a CoroutineScope bound to the
point of the Composition where it's called. The scope will be cancelled when the call leaves the
Composition. It can be use to obtain a composition-aware scope to launch coroutine outside
composable.
The rememberCoroutineScope is used to create a coroutine scope that is tied to the Composable
function's lifecycle. This lets you manage coroutines efficiently and safely by ensuring they are
cancelled when the Composable function is removed from the composition. You can use the launch
function within the scope to easily and safely manage asynchronous operations.
By using rememberCoroutineScope(), do finite jobs in this coroutine scope. Do not write infinite
job in this coroutine scope.
Also, this coroutine scope will launch in the callback when it call, and if callback is called
multiple times then this coroutine will launch multiple times and will run parallel. So take care of
this behaviour.
Use this scope for launching another independent coroutine, calling suspend function and for
performing UI operations such as to show Toast or Snackbar, open / close navigation drawer, for
route / navigation purpose etc.
Use cases of rememberCoroutineScope:
Network Requests / Database Operations
Animation
State Management
Dialogs, Snackbar and Toasts
Navigation
*/
| 0
|
Kotlin
|
0
| 0
|
10f6f7131fcbcc38439a29705ecae1d4bea2f86a
| 6,178
|
Jetpack_Compose_Side_Effects
|
MIT License
|
src/test/kotlin/org/opensearch/indexmanagement/indexstatemanagement/transport/action/getpolicy/GetPolicyRequestTests.kt
|
opensearch-project
| 354,094,562
| false
| null |
/*
* Copyright OpenSearch Contributors
* SPDX-License-Identifier: Apache-2.0
*/
package org.opensearch.indexmanagement.indexstatemanagement.transport.action.getpolicy
import org.opensearch.common.io.stream.BytesStreamOutput
import org.opensearch.core.common.io.stream.StreamInput
import org.opensearch.search.fetch.subphase.FetchSourceContext
import org.opensearch.test.OpenSearchTestCase
class GetPolicyRequestTests : OpenSearchTestCase() {
fun `test get policy request`() {
val policyID = "policyID"
val version: Long = 123
val fetchSrcContext = FetchSourceContext.DO_NOT_FETCH_SOURCE
val req = GetPolicyRequest(policyID, version, fetchSrcContext)
val out = BytesStreamOutput()
req.writeTo(out)
val sin = StreamInput.wrap(out.bytes().toBytesRef().bytes)
val newReq = GetPolicyRequest(sin)
assertEquals(policyID, newReq.policyID)
assertEquals(version, newReq.version)
assertEquals(fetchSrcContext, newReq.fetchSrcContext)
}
}
| 97
| null |
96
| 53
|
c0942eb60921070385d1b10c7453eee5e148e44f
| 1,031
|
index-management
|
Apache License 2.0
|
src/main/kotlin/com/codacy/intellij/plugin/services/api/models/ListRepositoryPullRequestsResponse.kt
|
codacy
| 733,924,872
| false
|
{"Kotlin": 82395, "HTML": 2163}
|
package com.codacy.intellij.plugin.services.api.models
data class ListRepositoryPullRequestsResponse(
val data: List<GetRepositoryPullRequestResponse>,
val pagination: Pagination
)
| 2
|
Kotlin
|
0
| 2
|
03598a859d051b95bb22a364cba32b47c7862ee6
| 190
|
codacy-intellij-extension
|
MIT License
|
Core/src/commonMain/kotlin/io/nacular/doodle/drawing/Paint.kt
|
nacular
| 108,631,782
| false
| null |
package io.nacular.doodle.drawing
/**
* Used to fill regions when drawing shapes on a [Canvas].
*
* @author Nicholas Eddy
*/
public abstract class Paint internal constructor() {
/**
* `true` if the Paint is visible. This could be false if the Paint's attributes (i.e. color) make it
* invisible if used for rendering. Returning `false` in such a case allows the rendering system to avoid
* unnecessary operations that won't be visible to the user.
*/
public abstract val visible: Boolean
}
| 5
| null |
26
| 613
|
f7414d4c30cdd7632992071234223653e52b978c
| 522
|
doodle
|
MIT License
|
android/src/main/java/com/systemmedia/SystemMediaPackage.kt
|
arnielabs
| 859,562,266
| false
|
{"Kotlin": 11174, "TypeScript": 7126, "Ruby": 3175, "Objective-C": 2376, "JavaScript": 1424, "Objective-C++": 1127, "Swift": 294, "C": 103}
|
package com.systemmedia
import com.facebook.react.ReactPackage
import com.facebook.react.bridge.NativeModule
import com.facebook.react.bridge.ReactApplicationContext
import com.facebook.react.uimanager.ViewManager
class SystemMediaPackage : ReactPackage {
override fun createNativeModules(reactContext: ReactApplicationContext): List<NativeModule> {
return listOf(SystemMediaModule(reactContext))
}
override fun createViewManagers(reactContext: ReactApplicationContext): List<ViewManager<*, *>> {
return emptyList()
}
}
| 0
|
Kotlin
|
0
| 0
|
a70abf85e793f1ddc076685c392948f65d491fc2
| 540
|
react-native-system-media
|
MIT License
|
pleo-antaeus-batch/src/test/kotlin/io/pleo/antaeus/batch/worker/BatchRetryInvoicePaymentWorkerTest.kt
|
hectorjsmith
| 456,267,035
| false
|
{"Kotlin": 86133, "Shell": 794, "Dockerfile": 249}
|
package io.pleo.antaeus.batch.worker
import io.mockk.every
import io.mockk.mockk
import io.mockk.slot
import io.mockk.verify
import io.pleo.antaeus.core.external.NotificationService
import io.pleo.antaeus.core.services.BillingService
import io.pleo.antaeus.core.services.InvoiceService
import io.pleo.antaeus.models.Currency
import io.pleo.antaeus.models.Invoice
import io.pleo.antaeus.models.InvoiceStatus
import io.pleo.antaeus.models.Money
import org.joda.time.DateTime
import org.junit.jupiter.api.Assertions.assertEquals
import org.junit.jupiter.api.Assertions.assertNull
import org.junit.jupiter.api.Test
import java.math.BigDecimal
internal class BatchRetryInvoicePaymentWorkerTest {
private val notificationService = mockk<NotificationService>(relaxed = true)
private val billingService = mockk<BillingService>(relaxed = true)
@Test
fun given_BatchWorker_When_Run_Then_FetchFunctionCalledOnceWithCorrectStatus() {
// Assemble
val invoiceService = mockk<InvoiceService>(relaxed = true)
val worker = BatchRetryInvoicePaymentWorker(
invoiceService,
billingService,
notificationService
)
// Act
worker.run()
// Assert
verify(exactly = 1) { invoiceService.fetchAllByStatusAndRetryPaymentTime(
statusList = setOf(InvoiceStatus.FAILED, InvoiceStatus.PROCESSING),
maxRetryPaymentTime = any()
) }
}
@Test
fun given_BatchWorker_When_RunFindsProcessingInvoices_Then_InvoicesSetToFailedAndRetryTimeIsNull() {
// Assemble
var invoiceInDb = newInvoice(InvoiceStatus.PROCESSING)
val invoiceSlot = slot<Invoice>()
val invoiceService = mockk<InvoiceService>(relaxed = true) {
every { fetchAllByStatusAndRetryPaymentTime(any(), any()) } answers { listOf(invoiceInDb) }
every { update(capture(invoiceSlot)) } answers {
invoiceInDb = invoiceSlot.captured
invoiceInDb
}
}
val worker = BatchRetryInvoicePaymentWorker(
invoiceService,
billingService,
notificationService
)
// Act
worker.run()
// Assert
assertEquals(InvoiceStatus.FAILED, invoiceInDb.status, "Invoice status should be set to FAILED when invoice stuck in PROCESSING")
assertNull(invoiceInDb.retryPaymentTime, "Invoice retry time should be null when invoice stuck in PROCESSING")
}
private fun newInvoice(status: InvoiceStatus): Invoice {
return Invoice(10, 20, Money(BigDecimal.valueOf(10), Currency.EUR), status, DateTime.now().minusDays(2), DateTime.now().minusDays(1))
}
}
| 0
|
Kotlin
|
0
| 0
|
f34656326ad02f9b8ef38a6e7b78916f0de7e4f0
| 2,716
|
antaeus
|
Creative Commons Zero v1.0 Universal
|
decoder/wasm/src/commonTest/kotlin/io/github/charlietap/chasm/decoder/wasm/decoder/instruction/control/BinaryIfDecoderTest.kt
|
CharlieTap
| 743,980,037
| false
| null |
package io.github.charlietap.chasm.decoder.wasm.decoder.instruction.control
import com.github.michaelbull.result.Ok
import io.github.charlietap.chasm.ast.instruction.MemoryInstruction
import io.github.charlietap.chasm.ast.instruction.NumericInstruction
import io.github.charlietap.chasm.decoder.wasm.decoder.instruction.ELSE
import io.github.charlietap.chasm.decoder.wasm.decoder.instruction.END
import io.github.charlietap.chasm.decoder.wasm.decoder.instruction.I32_EQZ
import io.github.charlietap.chasm.decoder.wasm.decoder.instruction.InstructionDecoder
import io.github.charlietap.chasm.decoder.wasm.decoder.instruction.MEMORY_GROW
import io.github.charlietap.chasm.decoder.wasm.fixture.ioError
import io.github.charlietap.chasm.decoder.wasm.reader.FakeUByteReader
import io.github.charlietap.chasm.decoder.wasm.reader.IOErrorWasmFileReader
import kotlin.test.Test
import kotlin.test.assertEquals
class BinaryIfDecoderTest {
@Test
fun `can decode an if instruction block`() {
val byteStream = sequenceOf(I32_EQZ, END).iterator()
val reader = FakeUByteReader {
Ok(byteStream.next())
}
val instructionDecoder: InstructionDecoder = { _, byte ->
assertEquals(I32_EQZ, byte)
Ok(NumericInstruction.I32Eqz)
}
val expected = Ok(listOf(NumericInstruction.I32Eqz) to null)
val actual = BinaryIfDecoder(reader, instructionDecoder)
assertEquals(expected, actual)
}
@Test
fun `can decode an if else instruction block`() {
val byteStream = sequenceOf(I32_EQZ, ELSE, MEMORY_GROW, END).iterator()
val reader = FakeUByteReader {
Ok(byteStream.next())
}
val instructionDecoder: InstructionDecoder = { _, byte ->
if (byte == I32_EQZ) {
Ok(NumericInstruction.I32Eqz)
} else {
Ok(MemoryInstruction.MemoryGrow)
}
}
val expected = Ok(listOf(NumericInstruction.I32Eqz) to listOf(MemoryInstruction.MemoryGrow))
val actual = BinaryIfDecoder(reader, instructionDecoder)
assertEquals(expected, actual)
}
@Test
fun `returns io error when read fails`() {
val err = ioError()
val reader = IOErrorWasmFileReader(err)
val actual = io.github.charlietap.chasm.decoder.wasm.decoder.instruction.BinaryExpressionDecoder(reader)
assertEquals(err, actual)
}
}
| 2
| null |
2
| 43
|
addbd2285ab2c9a7f0c12bb0d9fd246241f59513
| 2,452
|
chasm
|
Apache License 2.0
|
src/main/kotlin/com/lykke/matching/engine/daos/CopyWrapper.kt
|
LykkeCity
| 52,304,364
| false
| null |
package com.swisschain.matching.engine.daos
class CopyWrapper<out T : Copyable>(value: T, isNew: Boolean = false) {
val origin: T?
val copy: T
fun applyToOrigin(): T {
if (origin == null) {
return copy
}
copy.applyToOrigin(origin)
return origin
}
init {
if (isNew) {
origin = null
copy = value
} else {
origin = value
@Suppress("unchecked_cast")
copy = value.copy() as T
}
}
}
| 5
| null |
16
| 31
|
937b360b10d461e444ebc7133dd9ab6b64ae4cb5
| 533
|
MatchingEngine
|
MIT License
|
model/src/main/kotlin/CopyrightFinding.kt
|
andreas-bauer
| 165,835,940
| false
| null |
/*
* Copyright (C) 2017-2019 HERE Europe B.V.
*
* 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.
*
* SPDX-License-Identifier: Apache-2.0
* License-Filename: LICENSE
*/
package com.here.ort.model
import com.fasterxml.jackson.core.JsonParser
import com.fasterxml.jackson.databind.DeserializationContext
import com.fasterxml.jackson.databind.JsonNode
import com.fasterxml.jackson.databind.annotation.JsonDeserialize
import com.fasterxml.jackson.databind.deser.std.StdDeserializer
import com.fasterxml.jackson.module.kotlin.treeToValue
import com.here.ort.utils.SortedSetComparator
import com.here.ort.utils.constructTreeSetType
import java.util.SortedSet
import java.util.TreeSet
@JsonDeserialize(using = CopyrightFindingDeserializer::class)
data class CopyrightFinding(
val statement: String,
val locations: SortedSet<TextLocation>
) : Comparable<CopyrightFinding> {
companion object {
val SORTED_SET_COMPARATOR = SortedSetComparator<CopyrightFinding>()
val TREE_SET_TYPE by lazy { jsonMapper.typeFactory.constructTreeSetType(CopyrightFinding::class.java) }
}
override fun compareTo(other: CopyrightFinding) =
compareValuesBy(
this,
other,
compareBy(CopyrightFinding::statement)
.thenBy(TextLocation.SORTED_SET_COMPARATOR, CopyrightFinding::locations)
) { it }
}
class CopyrightFindingDeserializer : StdDeserializer<CopyrightFinding>(CopyrightFinding::class.java) {
override fun deserialize(p: JsonParser, ctxt: DeserializationContext): CopyrightFinding {
val node = p.codec.readTree<JsonNode>(p)
return when {
node.isTextual -> CopyrightFinding(node.textValue(), sortedSetOf())
else -> {
val statement = jsonMapper.treeToValue<String>(node["statement"])
val locations = jsonMapper.readValue<TreeSet<TextLocation>>(
jsonMapper.treeAsTokens(node["locations"]),
TextLocation.TREE_SET_TYPE
)
CopyrightFinding(statement, locations)
}
}
}
}
| 0
| null |
0
| 1
|
b0b8117a5eccc8c4c2833a1089c91c7eb0c2dcc9
| 2,631
|
oss-review-toolkit
|
Apache License 2.0
|
straight/src/commonMain/kotlin/me/localx/icons/straight/outline/Mobile.kt
|
localhostov
| 808,861,591
| false
|
{"Kotlin": 79430321, "HTML": 331, "CSS": 102}
|
package me.localx.icons.straight.outline
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.PathFillType.Companion.NonZero
import androidx.compose.ui.graphics.SolidColor
import androidx.compose.ui.graphics.StrokeCap.Companion.Butt
import androidx.compose.ui.graphics.StrokeJoin.Companion.Miter
import androidx.compose.ui.graphics.vector.ImageVector
import androidx.compose.ui.graphics.vector.ImageVector.Builder
import androidx.compose.ui.graphics.vector.path
import androidx.compose.ui.unit.dp
import me.localx.icons.straight.Icons
public val Icons.Outline.Mobile: ImageVector
get() {
if (_mobile != null) {
return _mobile!!
}
_mobile = Builder(name = "Mobile", defaultWidth = 512.0.dp, defaultHeight = 512.0.dp,
viewportWidth = 24.0f, viewportHeight = 24.0f).apply {
path(fill = SolidColor(Color(0xFF000000)), stroke = null, strokeLineWidth = 0.0f,
strokeLineCap = Butt, strokeLineJoin = Miter, strokeLineMiter = 4.0f,
pathFillType = NonZero) {
moveToRelative(18.0f, 0.0f)
horizontalLineToRelative(-12.0f)
arcToRelative(3.0f, 3.0f, 0.0f, false, false, -3.0f, 3.0f)
verticalLineToRelative(21.0f)
horizontalLineToRelative(18.0f)
verticalLineToRelative(-21.0f)
arcToRelative(3.0f, 3.0f, 0.0f, false, false, -3.0f, -3.0f)
close()
moveTo(19.0f, 22.0f)
horizontalLineToRelative(-6.0f)
verticalLineToRelative(-2.0f)
horizontalLineToRelative(-2.0f)
verticalLineToRelative(2.0f)
horizontalLineToRelative(-6.0f)
verticalLineToRelative(-19.0f)
arcToRelative(1.0f, 1.0f, 0.0f, false, true, 1.0f, -1.0f)
horizontalLineToRelative(12.0f)
arcToRelative(1.0f, 1.0f, 0.0f, false, true, 1.0f, 1.0f)
close()
moveTo(11.0f, 11.0f)
horizontalLineToRelative(2.0f)
verticalLineToRelative(1.0f)
horizontalLineToRelative(2.0f)
verticalLineToRelative(-1.707f)
arcToRelative(6.964f, 6.964f, 0.0f, false, false, -0.621f, -2.883f)
lineToRelative(-0.522f, -1.152f)
arcToRelative(2.0f, 2.0f, 0.0f, false, false, -3.7f, -0.041f)
lineToRelative(-0.536f, 1.194f)
arcToRelative(6.956f, 6.956f, 0.0f, false, false, -0.621f, 2.882f)
verticalLineToRelative(1.707f)
horizontalLineToRelative(2.0f)
close()
moveTo(12.018f, 7.041f)
lineTo(12.556f, 8.233f)
arcToRelative(4.953f, 4.953f, 0.0f, false, true, 0.253f, 0.767f)
horizontalLineToRelative(-1.618f)
arcToRelative(4.9f, 4.9f, 0.0f, false, true, 0.252f, -0.766f)
close()
moveTo(8.0f, 14.0f)
horizontalLineToRelative(8.0f)
verticalLineToRelative(2.0f)
horizontalLineToRelative(-8.0f)
close()
}
}
.build()
return _mobile!!
}
private var _mobile: ImageVector? = null
| 1
|
Kotlin
|
0
| 5
|
cbd8b510fca0e5e40e95498834f23ec73cc8f245
| 3,342
|
icons
|
MIT License
|
idea/testData/inspectionsLocal/branched/ifThenToSafeAccess/conditionNotBinaryExpr.kt
|
JakeWharton
| 99,388,807
| false
| null |
// IS_APPLICABLE: false
operator fun String?.times(a: Int): Boolean = a == 0
fun main(args: Array<String>) {
val foo: String = "foo"
if (foo * 10<caret>) {
foo.length
}
else null
}
| 0
| null |
4
| 83
|
4383335168338df9bbbe2a63cb213a68d0858104
| 206
|
kotlin
|
Apache License 2.0
|
feature/welcome/src/commonMain/kotlin/com/cdcoding/welcome/ui/WelcomeScreen.kt
|
Christophe-DC
| 822,562,468
| false
|
{"Kotlin": 728291, "Ruby": 4739, "Swift": 617}
|
package com.cdcoding.welcome.ui
import androidx.compose.foundation.Image
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.width
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Add
import androidx.compose.material.icons.filled.ArrowDownward
import androidx.compose.material3.Card
import androidx.compose.material3.CardDefaults
import androidx.compose.material3.FilledTonalIconButton
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButtonDefaults
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.unit.dp
import cafe.adriel.voyager.core.registry.rememberScreen
import cafe.adriel.voyager.core.screen.Screen
import cafe.adriel.voyager.navigator.LocalNavigator
import cafe.adriel.voyager.navigator.currentOrThrow
import com.cdcoding.core.designsystem.hooks.useEffect
import com.cdcoding.core.designsystem.hooks.useInject
import com.cdcoding.core.navigation.CreateWalletDestination
import com.cdcoding.core.navigation.HomeDestination
import com.cdcoding.core.navigation.ImportWalletDestination
import com.cdcoding.core.resource.Res
import com.cdcoding.core.resource.create_wallet
import com.cdcoding.core.resource.import_wallet
import com.cdcoding.core.resource.secure_wallet_logo
import com.cdcoding.core.resource.welcome_msg
import com.cdcoding.system.ui.theme.largeMarginDimens
import com.cdcoding.system.ui.theme.mediumMarginDimens
import com.cdcoding.welcome.presentation.WelcomeViewModel
import org.jetbrains.compose.resources.painterResource
import org.jetbrains.compose.resources.stringResource
class WelcomeScreen : Screen {
@Composable
override fun Content() {
val navigator = LocalNavigator.currentOrThrow
val viewModel: WelcomeViewModel = useInject()
val createWalletScreen = rememberScreen(CreateWalletDestination.CreateWallet)
val importWalletScreen = rememberScreen(ImportWalletDestination.ImportWallet)
val homeScreen = rememberScreen(HomeDestination.Home)
useEffect(viewModel.uiState.value.hasSession) {
if (viewModel.uiState.value.hasSession) {
navigator.replace(homeScreen)
}
}
WelcomeScreenContent(
navigateToCreateWallet = { navigator.push(createWalletScreen) },
navigateToImportWallet = { navigator.push(importWalletScreen) },
)
}
}
@Composable
fun WelcomeScreenContent(
modifier: Modifier = Modifier,
navigateToCreateWallet: () -> Unit = {},
navigateToImportWallet: () -> Unit = {}
) {
Column(
modifier.fillMaxWidth()
.padding(largeMarginDimens.margin),
horizontalAlignment = Alignment.CenterHorizontally
) {
Spacer(Modifier.height(largeMarginDimens.margin))
Text(
style = MaterialTheme.typography.displayMedium,
fontWeight = FontWeight.Bold,
textAlign = TextAlign.Center,
color = MaterialTheme.colorScheme.onBackground,
text = stringResource(Res.string.welcome_msg)
)
Spacer(Modifier.height(largeMarginDimens.margin))
Image(painterResource(Res.drawable.secure_wallet_logo), null)
Spacer(Modifier.height(48.dp))
Card(
Modifier
.fillMaxWidth()
.clickable { navigateToCreateWallet.invoke() },
colors = CardDefaults.cardColors(
containerColor = MaterialTheme.colorScheme.surfaceContainerLow,
)
) {
Row(
Modifier.padding(largeMarginDimens.margin),
verticalAlignment = Alignment.CenterVertically
) {
FilledTonalIconButton(
onClick = {},
colors = IconButtonDefaults.filledTonalIconButtonColors(
containerColor = MaterialTheme.colorScheme.primaryContainer.copy(alpha = 0.2f),
contentColor = MaterialTheme.colorScheme.onPrimaryContainer
)
) {
Icon(Icons.Filled.Add, contentDescription = "Create wallet")
}
Spacer(Modifier.width(mediumMarginDimens.margin))
Text(stringResource(Res.string.create_wallet))
}
}
Spacer(Modifier.height(largeMarginDimens.margin))
Card(
Modifier
.fillMaxWidth()
.clickable { navigateToImportWallet() },
colors = CardDefaults.cardColors(
containerColor = MaterialTheme.colorScheme.surfaceContainerLow,
)
) {
Row(
Modifier.padding(largeMarginDimens.margin),
verticalAlignment = Alignment.CenterVertically
) {
FilledTonalIconButton(
onClick = {},
colors = IconButtonDefaults.filledTonalIconButtonColors(
containerColor = MaterialTheme.colorScheme.primaryContainer.copy(alpha = 0.2f),
contentColor = MaterialTheme.colorScheme.onPrimaryContainer
)
) {
Icon(Icons.Filled.ArrowDownward, contentDescription = "Import wallet")
}
Spacer(Modifier.width(mediumMarginDimens.margin))
Text(stringResource(Res.string.import_wallet))
}
}
}
}
| 0
|
Kotlin
|
0
| 0
|
e8bff388ccebb64e6810d62a1ea4dddfabe83c71
| 6,040
|
secureWallet
|
Apache License 2.0
|
Chapter10/PopularMovies/app/src/test/java/com/example/popularmovies/MovieRepositoryTest.kt
|
PacktPublishing
| 810,886,298
| false
|
{"Kotlin": 989730}
|
package com.example.popularmovies
import com.example.popularmovies.model.Movie
import com.example.popularmovies.network.MovieService
import io.mockk.coEvery
import io.mockk.impl.annotations.MockK
import io.mockk.junit4.MockKRule
import kotlinx.coroutines.runBlocking
import org.junit.Assert.assertEquals
import org.junit.Rule
import org.junit.Test
import java.util.Calendar
class MovieRepositoryTest {
@get:Rule
val mockkRule = MockKRule(this)
@MockK
lateinit var movieService: MovieService
@Test
fun getPopularMovies() {
val movies = listOf(
Movie(
title = "Title",
releaseDate = Calendar.getInstance().get(Calendar.YEAR).toString()
)
)
val movieRepository = MovieRepository(movieService)
runBlocking {
coEvery { movieService.getPopularMovies() } returns movies
assertEquals(movies, movieRepository.getPopularMovies())
}
}
}
| 0
|
Kotlin
|
2
| 2
|
c8aa1dd9b7dbea064681fbb492619aab4e969fbe
| 980
|
How-to-Build-Android-Apps-with-Kotlin-Third-Edition
|
MIT License
|
sample/console/src/main/kotlin/dev/gumil/kaskade/sample/Main.kt
|
gumil
| 120,153,669
| false
| null |
package dev.gumil.kaskade.sample
import dev.gumil.kaskade.stateEmitter
@Suppress("ComplexMethod", "LabeledExpression")
fun main() {
println(
"""
########################
# KASKADE MUSIC PLAYER #
########################
########################
# controls: #
# z = stop #
# x = pause/play #
# c = previous #
# v = next #
# q = exit #
########################
""".trimIndent()
)
val kaskade = MusicPlayerKaskade().kaskade
kaskade.stateEmitter().subscribe { state ->
when (state) {
is PlayerState.Playing -> println("Now Playing: ${state.music}")
PlayerState.Stopped -> println("STOPPED")
PlayerState.Paused -> println("Paused")
}
}
loop@ while (true) {
val action = readLine()?.get(0) ?: 'q'
when (action) {
'z' -> kaskade.process(PlayerAction.Stop)
'x' -> kaskade.process(PlayerAction.PausePlay)
'c' -> kaskade.process(PlayerAction.Previous)
'v' -> kaskade.process(PlayerAction.Next)
else -> break@loop
}
}
}
| 10
|
Kotlin
|
6
| 228
|
cd88de5e622c66d3ef4a505b551d23ebe22bc618
| 1,243
|
Kaskade
|
Apache License 2.0
|
cache/src/main/java/co/sentinel/dvpn/cache/data/LastSessionDatastore.kt
|
sentinel-official
| 578,087,836
| false
| null |
package co.sentinel.dvpn.cache.data
import android.content.Context
import androidx.datastore.core.DataStore
import androidx.datastore.preferences.core.Preferences
import androidx.datastore.preferences.core.edit
import androidx.datastore.preferences.core.stringPreferencesKey
import androidx.datastore.preferences.preferencesDataStore
import co.sentinel.dvpn.cache.data.LastSessionDatastore.PreferencesKeys.LAST_SESSION
import co.sentinel.dvpn.cache.data.LastSessionDatastore.PreferencesKeys.dataStore
import co.sentinel.dvpn.domain.features.hub.model.Session
import com.google.gson.Gson
import kotlinx.coroutines.flow.first
class LastSessionDatastore(context: Context) {
private val dataStore = context.dataStore
suspend fun getLastSession() =
dataStore.data.first().toPreferences()[LAST_SESSION]?.let {
Gson().fromJson(it, Session::class.java)
}
suspend fun setLastSession(session: Session) {
dataStore.edit { preferences ->
preferences[LAST_SESSION] = Gson().toJson(session)
}
}
private object PreferencesKeys {
val Context.dataStore: DataStore<Preferences> by preferencesDataStore(name = "last_session")
val LAST_SESSION = stringPreferencesKey("session")
}
}
| 1
| null |
4
| 4
|
58b79967924e5049397c5297bb9b2aefe98060f0
| 1,263
|
sentinel-dvpn-for-android
|
MIT License
|
src/main/kotlin/coverstats/server/models/coverage/Models.kt
|
pawitp
| 189,834,428
| false
| null |
package coverstats.server.models.coverage
import coverstats.server.models.scm.ScmFileType
import java.util.*
// Report for fast access (stored in cache)
data class ProcessedCoverageReport(
val files: Map<String, ProcessedCoverageFile>
)
data class ProcessedCoverageFile(
val path: String,
val type: ScmFileType,
val parentPath: String,
val childrenPaths: Set<String>,
val statements: List<CoverageStatement>,
val missedStatements: Int,
val coveredStatements: Int,
val missedBranches: Int,
val coveredBranches: Int
)
// Raw report stored in database
data class CoverageReport(
val scm: String,
val repo: String,
val commitId: String,
val files: List<CoverageFile>,
val createdAt: Date
)
data class CoverageFile(
val path: String,
val statements: List<CoverageStatement>
)
// Patch coverage summary
data class PatchCoverageReport(
val missedStatements: Int,
val coveredStatements: Int
)
// Smallest unit of coverage. If start == end == -1, then the statement is the full line.
data class CoverageStatement(
val lineNumber: Int,
val start: Int,
val end: Int,
val status: CoverageStatus,
val missedBranches: Int,
val coveredBranches: Int
)
enum class CoverageStatus {
FULL, PARTIAL, NONE
}
| 0
|
Kotlin
|
0
| 0
|
d45a3629d971321f2f4320ecf6d582565a6a8203
| 1,298
|
coverstats
|
MIT License
|
project/fantasy/app/src/main/java/com/example/fantasy/domain/usecase/GetDateAndWeekUseCase.kt
|
radical-p
| 568,745,863
| false
|
{"Kotlin": 227219}
|
package com.example.fantasy.domain.usecase
import android.util.Log
import com.example.fantasy.domain.repository.DateAndWeekRepo
import com.example.fantasy.domain.repository.DateAndWeek
import kotlinx.coroutines.delay
class GetDateAndWeekUseCase(private val DateAndWeekRepo: DateAndWeekRepo) {
suspend fun execute(): DateAndWeek {
return DateAndWeekRepo.getDateAndWeek()
}
}
| 0
|
Kotlin
|
0
| 3
|
f6d6744cdaa7a600d5b2cd026b89dd48c1ece78b
| 392
|
Summer-2022-Tapsi-and-Rahnema-Internship
|
MIT License
|
src/main/kotlin/com/fantasy/ladbe/socket/service/BidLogSocketService.kt
|
fantasy-fans-ko
| 420,898,576
| false
|
{"HTML": 1023453, "Kotlin": 74755}
|
package com.fantasy.ladbe.socket.service
import com.fantasy.ladbe.handler.exception.BusinessException
import com.fantasy.ladbe.handler.exception.Exceptions
import com.fantasy.ladbe.model.BidLog
import com.fantasy.ladbe.repository.AuctionRepository
import com.fantasy.ladbe.repository.BidLogRepository
import com.fantasy.ladbe.repository.BidderRepository
import com.fantasy.ladbe.repository.PlayerRepository
import com.fantasy.ladbe.socket.dto.BidLogSocketDto
import org.springframework.stereotype.Service
import org.springframework.transaction.annotation.Transactional
@Service
class BidLogSocketService(
val bidLogRepository: BidLogRepository,
val playerRepository: PlayerRepository,
val bidderRepository: BidderRepository,
val auctionRepository: AuctionRepository,
) {
@Transactional
// bidder 엔티티의 값을 가져올 때, 연관관계인 auction을 다시 접근하기에 트랜젝션을 통해 1번만 접근하도록 변경
fun saveBidLog(
requestBidLog: BidLogSocketDto.Request.BidLogContent,
): BidLogSocketDto.Response.BidLogContent {
val auction = auctionRepository.findById(requestBidLog.auctionId)
.orElseThrow { throw BusinessException(Exceptions.AUCTION_NOT_FOUND) }
val bidder =
bidderRepository.findById(requestBidLog.bidderId)
.orElseThrow { throw BusinessException(Exceptions.BIDDER_NOT_FOUND) }
val player =
playerRepository.findById(requestBidLog.playerId)
.orElseThrow { throw BusinessException(Exceptions.PLAYER_NOT_FOUND) }
val bidLog = BidLog(price = requestBidLog.price, bidder = bidder, auction = auction, player = player)
return bidLogRepository.save(bidLog).toDtoWithUpdateTime()
}
}
| 6
|
HTML
|
0
| 4
|
575112118816e80da943bbbf8237fa6fcb65411b
| 1,697
|
lad-be
|
MIT License
|
src/main/kotlin/com/github/oduig/auctionswindler/blizzard/generated/Self.kt
|
Oduig
| 201,813,155
| false
| null |
package com.github.oduig.auctionswindler.blizzard.generated
data class Self(
val href: String
)
| 0
|
Kotlin
|
0
| 0
|
fbe50b740e65280122d5677b7ca33d4c760539eb
| 100
|
auction-swindler
|
Apache License 2.0
|
data/src/main/java/com/gentalhacode/github/data/features/search/model/DataOwner.kt
|
thgMatajs
| 239,887,486
| false
| null |
package com.gentalhacode.github.data.features.search.model
import com.gentalhacode.github.model.Owner
/**
* .:.:.:. Created by @thgMatajs on 13/02/20 .:.:.:.
*/
data class DataOwner(
override val name: String,
override val urlPhoto: String) : Owner
| 0
|
Kotlin
|
0
| 5
|
f3e8465cdbc92c9375f32c20085afdeac69dd04d
| 260
|
GitHubSearch
|
The Unlicense
|
opendc-web/opendc-web-proto/src/main/kotlin/org/opendc/web/proto/Workload.kt
|
atlarge-research
| 79,902,234
| false
|
{"Kotlin": 1128256, "Java": 446828, "JavaScript": 339363, "Python": 46381, "MDX": 36554, "CSS": 18038, "Dockerfile": 3592, "Shell": 280}
|
/*
* Copyright (c) 2021 AtLarge Research
*
* 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 org.opendc.web.proto
import jakarta.validation.constraints.DecimalMax
import jakarta.validation.constraints.DecimalMin
/**
* The workload to simulate for a scenario.
*/
public data class Workload(val trace: Trace, val samplingFraction: Double) {
/**
* Specification for a workload.
*
* @param trace The unique identifier of the trace.
* @param samplingFraction The fraction of the workload to sample.
*/
public data class Spec(
val trace: String,
@DecimalMin(value = "0.001", message = "Sampling fraction must be non-zero")
@DecimalMax(value = "1", message = "Sampling fraction cannot exceed one")
val samplingFraction: Double,
)
}
| 33
|
Kotlin
|
47
| 70
|
5a365dbc068f2a8cdfa9813c39cc84bb30e15637
| 1,835
|
opendc
|
MIT License
|
libraries/tools/kotlin-gradle-plugin/src/test/kotlin/org/jetbrains/kotlin/gradle/internal/testing/tcsmc/TCServiceMessagesClientTest.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}
|
package org.jetbrains.kotlin.gradle.internal.testing.tcsmc
import jetbrains.buildServer.messages.serviceMessages.ServiceMessage
import org.jetbrains.kotlin.gradle.internal.testing.RecordingTestResultProcessor
import org.jetbrains.kotlin.gradle.internal.testing.TCServiceMessagesClient
import org.jetbrains.kotlin.gradle.internal.testing.TCServiceMessagesClientSettings
import org.jetbrains.kotlin.test.util.trimTrailingWhitespaces
import org.slf4j.LoggerFactory
import kotlin.test.assertEquals
open class TCServiceMessagesClientTest {
protected var rootNodeName: String = "root"
protected var treatFailedTestOutputAsStacktrace: Boolean = false
internal fun assertEvents(assertion: String, produceServiceMessage: TCServiceMessagesClient.() -> Unit) {
val results = RecordingTestResultProcessor()
val client = createClient(results)
client.root {
client.produceServiceMessage()
}
assertEquals(
assertion.trimTrailingWhitespaces().trim(),
results.output.toString().trimTrailingWhitespaces().trim()
)
}
internal open fun createClient(results: RecordingTestResultProcessor): TCServiceMessagesClient {
return TCServiceMessagesClient(
results,
TCServiceMessagesClientSettings(
rootNodeName,
treatFailedTestOutputAsStacktrace = treatFailedTestOutputAsStacktrace
),
LoggerFactory.getLogger("test"),
)
}
internal fun TCServiceMessagesClient.serviceMessage(name: String, attributes: Map<String, String>) =
serviceMessage(ServiceMessage.parse(ServiceMessage.asString(name, attributes))!!)
}
| 181
|
Kotlin
|
5748
| 49,172
|
33eb9cef3d146062c103f9853d772f0a1da0450e
| 1,700
|
kotlin
|
Apache License 2.0
|
app/src/main/java/com/jonadaly/brood/db/entities/Chicken.kt
|
jonadaly
| 160,943,818
| false
| null |
package com.jonadaly.brood.db.entities
import android.arch.persistence.room.*
@Entity(foreignKeys = [
ForeignKey(
entity = Brood::class,
parentColumns = arrayOf("id"),
childColumns = arrayOf("brood_id")
)
], indices = [
Index("brood_id")
])
data class Chicken(
@PrimaryKey(autoGenerate = true) var id: Long = 0,
var broodUuid: String = "",
var name: String = "",
var created: String = "",
var openweatherIconId: String = "",
var status: String = "",
var temperature: Float = 0f,
var uuid: String = "",
@ColumnInfo(name = "brood_id") var broodId: Long = -1
)
| 0
|
Kotlin
|
0
| 0
|
c34f0d27fdc85de73306227b1dccec1086cb1216
| 631
|
brood-android
|
Apache License 2.0
|
test/integ/KotlinLayzyDelegate.kt
|
facebook
| 54,664,770
| false
| null |
/*
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
class FooDelagates {
val lazyValue: String by lazy { expensiveFn() }
fun expensiveFn(): String {
return "Help"
}
}
class DelegateTest {
fun main() {
val foo = FooDelagates()
println(foo.lazyValue)
println(foo.lazyValue)
}
}
| 81
| null |
670
| 6,031
|
428d8686918e4a77f6ebe251bdac51f1fc9e5a5e
| 443
|
redex
|
MIT License
|
backend/src/main/kotlin/com/mobilispect/backend/schedule/transit_land/internal/client/TransitLandStop.kt
|
alandovskis
| 502,662,711
| false
|
{"Kotlin": 358753, "Shell": 472, "Swift": 345}
|
@file:OptIn(ExperimentalSerializationApi::class)
@file:Suppress("unused") // Deleting any of the unused fields will be break deserialization.
package com.mobilispect.backend.schedule.transit_land.internal.client
import kotlinx.serialization.ExperimentalSerializationApi
import kotlinx.serialization.Serializable
import kotlinx.serialization.json.JsonNames
@Serializable
internal class TransitLandStop(
@JsonNames("feed_version") val feed: FeedVersion,
val geometry: PointGeometry? = null,
val id: Int? = null,
val level: Int? = null,
@JsonNames("location_type") val locationType: Int? = null,
@JsonNames("onestop_id") val onestopID: String,
val parent: ParentStop? = null,
@JsonNames("platform_code") val platformCode: String? = null,
@JsonNames("stop_code") val stopCode: String? = null,
@JsonNames("stop_desc") val description: String? = null,
@JsonNames("stop_id") val stopID: String,
@JsonNames("stop_name") val name: String,
@JsonNames("stop_timezone") val timezone: String? = null,
@JsonNames("stop_url") val url: String? = null,
@JsonNames("tts_stop_name") val ttsStopName: String? = null,
@JsonNames("wheelchair_boarding") val wheelchairBoarding: Int? = null,
@JsonNames("zone_id") val zoneID: String? = null
)
@Serializable
internal class ParentStop(
val geometry: PointGeometry? = null,
val id: Int? = null,
@JsonNames("stop_id") val stopID: String?,
@JsonNames("stop_name") val name: String?
)
| 4
|
Kotlin
|
0
| 1
|
7b48fafb75d432509e71107d501b6c7e2563bd00
| 1,493
|
mobilispect
|
Apache License 2.0
|
python-extension/src/nativeMain/kotlin/jetbrains/datalore/plot/pythonExtension/pngj/chunks/PngChunkPLTE.kt
|
JetBrains
| 176,771,727
| false
| null |
/*
* Copyright (c) 2023. JetBrains s.r.o.
* Use of this source code is governed by the MIT license that can be found in the LICENSE file.
*/
@file:Suppress("unused")
package jetbrains.datalore.plot.pythonExtension.pngj.chunks
import jetbrains.datalore.plot.pythonExtension.pngj.ImageInfo
import jetbrains.datalore.plot.pythonExtension.pngj.PngjException
/**
* PLTE chunk.
*
*
* see http://www.w3.org/TR/PNG/#11PLTE
*
*
* Critical chunk
*/
class PngChunkPLTE(info: ImageInfo?) : PngChunkSingle(ID, info) {
// http://www.w3.org/TR/PNG/#11PLTE
private var nentries = 0
/**
* RGB8 packed in one integer
*/
private var entries: IntArray? = null
override val orderingConstraint: ChunkOrderingConstraint
get() = ChunkOrderingConstraint.NA
override fun createRawChunk(): ChunkRaw {
val len = 3 * nentries
val rgb = IntArray(3)
val c: ChunkRaw = createEmptyChunk(len, true)
var n = 0
var i = 0
while (n < nentries) {
getEntryRgb(n, rgb)
c.data!![i++] = rgb[0].toByte()
c.data!![i++] = rgb[1].toByte()
c.data!![i++] = rgb[2].toByte()
n++
}
return c
}
override fun parseFromRaw(chunk: ChunkRaw) {
setNentries(chunk.len / 3)
var n = 0
var i = 0
while (n < nentries) {
setEntry(
n,
(chunk.data!![i++].toInt() and 0xff),
(chunk.data!![i++].toInt() and 0xff),
(chunk.data!![i++].toInt() and 0xff)
)
n++
}
}
fun setNentries(n: Int) {
nentries = n
if (nentries < 1 || nentries > 256) throw PngjException("invalid pallette - nentries=$nentries")
if (entries == null || entries!!.size != nentries) { // alloc
entries = IntArray(nentries)
}
}
fun getNentries(): Int {
return nentries
}
fun setEntry(n: Int, r: Int, g: Int, b: Int) {
entries!![n] = r shl 16 or (g shl 8) or b
}
fun getEntry(n: Int): Int {
return entries!![n]
}
private fun getEntryRgb(n: Int, rgb: IntArray) {
getEntryRgb(n, rgb, 0)
}
fun getEntryRgb(n: Int, rgb: IntArray, offset: Int) {
val v = entries!![n]
rgb[offset + 0] = v and 0xff0000 shr 16
rgb[offset + 1] = v and 0xff00 shr 8
rgb[offset + 2] = v and 0xff
}
fun minBitDepth(): Int {
return if (nentries <= 2) 1 else if (nentries <= 4) 2 else if (nentries <= 16) 4 else 8
}
companion object {
const val ID: String = ChunkHelper.PLTE
}
}
| 93
| null |
51
| 889
|
2fb1fe8e812ed0b84cd32954331a76775e75d4d2
| 2,673
|
lets-plot
|
MIT License
|
app/src/androidMain/kotlin/dev/sergiobelda/todometer/app/glance/theme/TodometerWidgetTheme.kt
|
serbelga
| 301,817,067
| false
| null |
/*
* Copyright 2023 Sergio Belda
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package dev.sergiobelda.todometer.app.glance.theme
import android.os.Build
import androidx.compose.runtime.Composable
import androidx.glance.GlanceComposable
import androidx.glance.GlanceTheme
import androidx.glance.material3.ColorProviders
import dev.sergiobelda.todometer.app.common.designsystem.theme.DarkColorScheme
import dev.sergiobelda.todometer.app.common.designsystem.theme.LightColorScheme
@Composable
fun TodometerWidgetTheme(
content: @GlanceComposable @Composable () -> Unit
) {
GlanceTheme(
colors = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
GlanceTheme.colors
} else {
ColorProviders(
light = LightColorScheme,
dark = DarkColorScheme
)
},
content = content
)
}
| 8
| null |
37
| 585
|
9a097cd4df924cbf66c0b6af6fa1fed667d30ca0
| 1,399
|
Todometer-KMP
|
Apache License 2.0
|
app/src/main/java/com/firelord/socialx/adapters/ViewPagerAdapter.kt
|
FireLord
| 511,029,411
| false
|
{"Kotlin": 41463}
|
package com.firelord.socialx.adapters
import androidx.fragment.app.Fragment
import androidx.fragment.app.FragmentManager
import androidx.lifecycle.Lifecycle
import androidx.viewpager2.adapter.FragmentStateAdapter
import com.firelord.socialx.ui.fragments.LoginFragment
import com.firelord.socialx.ui.fragments.SignUpFragment
class ViewPagerAdapter(fragmentManager: FragmentManager, lifecycle: Lifecycle): FragmentStateAdapter(fragmentManager,lifecycle)
{
override fun getItemCount(): Int {
return 2
}
override fun createFragment(position: Int): Fragment {
return when(position){
0->{
LoginFragment()
}
1->{
SignUpFragment()
}
else->{
Fragment()
}
}
}
}
| 0
|
Kotlin
|
0
| 0
|
9a2f320278f9f68a171931bb75f2030f4afc33a5
| 814
|
socialx
|
The Unlicense
|
app/src/main/java/com/poke/montty/app/data/remote/manager/type/TypeAPIManager.kt
|
EmmanuelMontt
| 765,499,007
| false
|
{"Kotlin": 19715}
|
package com.poke.montty.app.data.remote.manager.type
import com.poke.montty.app.data.remote.model.type.list.TypeListResponse
interface TypeAPIManager {
suspend fun getTypeList(offset: Int, limit: Int): TypeListResponse
}
| 0
|
Kotlin
|
0
| 0
|
7cf872c4dd28aefafe0cf4c1db3dbf7f37c2e504
| 229
|
poke-app
|
Apache License 2.0
|
import-export/android/src/main/kotlin/studio/lunabee/onesafe/importexport/utils/FileDetailsExt.kt
|
LunabeeStudio
| 624,544,471
| false
|
{"Kotlin": 3214461, "Java": 11987, "Python": 3979}
|
/*
* Copyright (c) 2024 Lunabee Studio
*
* 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.
*
* Created by Lunabee Studio / Date - 4/12/2024 - for the oneSafe6 SDK.
* Last modified 4/12/24, 3:01 PM
*/
package studio.lunabee.onesafe.importexport.utils
import studio.lunabee.onesafe.commonui.utils.FileDetails
import studio.lunabee.onesafe.importexport.model.ImportExportConstant
fun FileDetails?.isOsFile(): Boolean {
return this != null
&& extension != null
&& (extension == ImportExportConstant.ExtensionOs6Backup || extension == ImportExportConstant.ExtensionOs6Sharing)
}
| 1
|
Kotlin
|
1
| 2
|
4d6199939c91e0d6d31aa5328549a3ac442d046a
| 1,106
|
oneSafe6_SDK_Android
|
Apache License 2.0
|
app/src/main/java/com/driuft/random_pets_starter/PetAdapter.kt
|
gaeldiab
| 623,657,139
| false
| null |
package com.driuft.random_pets_starter
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import androidx.recyclerview.widget.RecyclerView
import com.bumptech.glide.Glide
class PetAdapter (private val petList: List<String>):RecyclerView.Adapter<PetAdapter.ViewHolder>() {
class ViewHolder(view: View) : RecyclerView.ViewHolder(view) {
val petImage: ImageView
init {
// Find our RecyclerView item's ImageView for future use
petImage = view.findViewById(R.id.pet_image)
}
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
val view = LayoutInflater.from(parent.context)
.inflate(R.layout.pet_item, parent, false)
return ViewHolder(view)
}
override fun getItemCount() = petList.size
override fun onBindViewHolder(holder: ViewHolder, position: Int) {
Glide.with(holder.itemView)
.load(petList[position])
.centerCrop()
.into(holder.petImage)
}
}
| 0
|
Kotlin
|
0
| 0
|
fad862d9dd2d3b237f15a5a696aa5b7f15ad6686
| 1,098
|
CODEPATH-PROJECT6-7
|
Apache License 2.0
|
shared/src/main/java/de/loosetie/k8s/dsl/impls/ConfigMapVolumeSource.kt
|
loosetie
| 283,145,621
| false
|
{"Kotlin": 12443871}
|
package de.loosetie.k8s.dsl.impls
import com.fasterxml.jackson.annotation.JsonIgnore
import com.fasterxml.jackson.annotation.JsonPropertyOrder
import de.loosetie.k8s.dsl.K8sManifest
import de.loosetie.k8s.dsl.HasParent
import de.loosetie.k8s.dsl.manifests.*
@JsonPropertyOrder("name", "defaultMode", "items", "optional")
class ConfigMapVolumeSource_core_v1_k8s1_16Impl(
@JsonIgnore
override val parent: K8sManifest? = null
)
: ConfigMapVolumeSource_core_v1_k8s1_16, HasParent {
override var name: String? = null
override var defaultMode: Int? = null
override var items: List<KeyToPath_core_v1_k8s1_16>? = null
override var optional: Boolean? = null
}
typealias ConfigMapVolumeSource_core_v1_k8s1_17Impl = ConfigMapVolumeSource_core_v1_k8s1_16Impl
typealias ConfigMapVolumeSource_core_v1_k8s1_18Impl = ConfigMapVolumeSource_core_v1_k8s1_17Impl
@JsonPropertyOrder("name", "defaultMode", "items", "optional")
class ConfigMapVolumeSource_core_v1_k8s1_19Impl(
@JsonIgnore
override val parent: K8sManifest? = null
)
: ConfigMapVolumeSource_core_v1_k8s1_19, HasParent {
override var name: String? = null
override var defaultMode: Int? = null
override var items: List<KeyToPath_core_v1_k8s1_19>? = null
override var optional: Boolean? = null
}
typealias ConfigMapVolumeSource_core_v1_k8s1_20Impl = ConfigMapVolumeSource_core_v1_k8s1_19Impl
typealias ConfigMapVolumeSource_core_v1_k8s1_21Impl = ConfigMapVolumeSource_core_v1_k8s1_20Impl
| 0
|
Kotlin
|
0
| 1
|
3dd2d00220dbf71151d56b75b3bd7f26583b1fd3
| 1,453
|
k8s-dsl
|
Apache License 2.0
|
app/src/main/java/com/kasuminotes/ui/app/exEquip/ExEquipSkill.kt
|
chilbi
| 399,723,451
| false
| null |
package com.kasuminotes.ui.app.exEquip
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.material.Divider
import androidx.compose.material.Icon
import androidx.compose.material.IconButton
import androidx.compose.material.LocalContentAlpha
import androidx.compose.material.LocalContentColor
import androidx.compose.material.MaterialTheme
import androidx.compose.material.Text
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Code
import androidx.compose.runtime.Composable
import androidx.compose.runtime.derivedStateOf
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import com.kasuminotes.BuildConfig
import com.kasuminotes.R
import com.kasuminotes.action.ActionBuilder
import com.kasuminotes.action.D
import com.kasuminotes.action.getUnknown
import com.kasuminotes.action.stringDescription
import com.kasuminotes.data.Property
import com.kasuminotes.data.SkillData
import com.kasuminotes.ui.components.ActionLabel
import com.kasuminotes.ui.components.PlaceImage
import com.kasuminotes.ui.components.UnderlineLabelColumn
import com.kasuminotes.utils.UrlUtil
@Composable
fun ExEquipSkill(
passiveSkill1: SkillData?,
passiveSkill2: SkillData?,
baseProperty: Property
) {
UnderlineLabelColumn(
label = stringResource(R.string.equip_skill),
color = MaterialTheme.colors.primary
) {
if (passiveSkill1 != null) {
ExEquipSkillItem(passiveSkill1, baseProperty)
}
if (passiveSkill2 != null) {
Divider(Modifier.padding(vertical = 4.dp))
ExEquipSkillItem(passiveSkill2, baseProperty)
}
}
}
@Composable
private fun ExEquipSkillItem(
passiveSkill: SkillData,
baseProperty: Property
) {
val visible = remember { mutableStateOf(false) }
val descriptionList: List<D> by remember(passiveSkill, baseProperty) {
derivedStateOf {
ActionBuilder(
passiveSkill.rawDepends,
passiveSkill.actions,
true
).buildDescriptionList(0, baseProperty)
}
}
Row(
modifier = Modifier.padding(4.dp),
verticalAlignment = Alignment.CenterVertically
) {
Box(Modifier.size(32.dp)) {
PlaceImage(UrlUtil.getSkillIconUrl(passiveSkill.iconType))
}
Text(
text = passiveSkill.name,
modifier = Modifier.padding(start = 4.dp),
fontSize = 16.sp
)
if (BuildConfig.DEBUG) {
Spacer(Modifier.weight(1f))
IconButton(onClick = { visible.value = !visible.value }) {
Icon(
imageVector = Icons.Filled.Code,
contentDescription = null,
tint = if (visible.value) MaterialTheme.colors.secondary
else LocalContentColor.current.copy(alpha = LocalContentAlpha.current)
)
}
}
}
Text(
text = passiveSkill.description,
modifier = Modifier.padding(4.dp),
fontSize = 14.sp
)
if (!visible.value) {
descriptionList.forEachIndexed { index, d ->
Row(Modifier.padding(4.dp)) {
ActionLabel(index + 1)
Text(
text = stringDescription(d),
modifier = Modifier.padding(start = 4.dp),
fontSize = 14.sp,
lineHeight = 28.sp
)
}
}
}
if (visible.value && BuildConfig.DEBUG) {
passiveSkill.actions.forEachIndexed { index, action ->
Row(Modifier.padding(4.dp)) {
ActionLabel(index + 1)
Text(
text = stringDescription(action.getUnknown()),
modifier = Modifier.padding(start = 4.dp),
fontSize = 14.sp,
lineHeight = 28.sp
)
}
}
}
}
| 0
|
Kotlin
|
0
| 0
|
30bc201fc1cea999ab4db2f2b9a75843bb83b30d
| 4,444
|
KasumiNotes
|
Apache License 2.0
|
src/main/java/dev/blachut/svelte/lang/psi/blocks/SvelteBlock.kt
|
tomblachut
| 184,821,501
| false
|
{"JavaScript": 467590, "Kotlin": 424107, "Java": 81911, "Lex": 16310, "Svelte": 14923, "HTML": 2052, "TypeScript": 709}
|
package dev.blachut.svelte.lang.psi.blocks
import com.intellij.lang.ASTNode
import com.intellij.lang.javascript.psi.JSElement
import dev.blachut.svelte.lang.psi.SveltePsiElement
import dev.blachut.svelte.lang.psi.SvelteTag
abstract class SvelteBlock(node: ASTNode) : SveltePsiElement(node), JSElement {
val startTag: SvelteTag get() = primaryBranch.tag
val endTag: SvelteTag? get() = lastChild as? SvelteTag
val primaryBranch get() = firstChild as SveltePrimaryBranch
}
| 59
|
JavaScript
|
38
| 467
|
183c1af2ece3cf35dbd21c03b6b258ebfe105c20
| 485
|
svelte-intellij
|
MIT License
|
src/test/kotlin/uk/gov/justice/digital/hmpps/managerecallsapi/component/health/HealthCheckComponentTest.kt
|
ministryofjustice
| 371,053,303
| false
| null |
package uk.gov.justice.digital.hmpps.managerecallsapi.component.health
import org.junit.jupiter.api.Test
import org.junit.jupiter.api.TestInstance
import org.junit.jupiter.params.ParameterizedTest
import org.junit.jupiter.params.provider.Arguments
import org.junit.jupiter.params.provider.MethodSource
import org.springframework.boot.test.autoconfigure.web.reactive.AutoConfigureWebTestClient
import org.springframework.http.HttpStatus
import org.springframework.http.HttpStatus.INTERNAL_SERVER_ERROR
import org.springframework.http.HttpStatus.OK
import org.springframework.http.HttpStatus.SERVICE_UNAVAILABLE
import org.springframework.test.context.ActiveProfiles
import org.springframework.test.web.reactive.server.WebTestClient
import uk.gov.justice.digital.hmpps.managerecallsapi.component.ComponentTestBase
import uk.gov.justice.digital.hmpps.managerecallsapi.integration.mockservers.HealthServer
import java.time.LocalDateTime
import java.time.format.DateTimeFormatter.ISO_DATE
import java.util.stream.Stream
@ActiveProfiles("db-test-no-clam")
@TestInstance(TestInstance.Lifecycle.PER_CLASS)
@AutoConfigureWebTestClient(timeout = "15000")
class HealthCheckComponentTest : ComponentTestBase() {
@Test
fun `healthy service returns status of each health check and version details`() {
prisonerOffenderSearchMockServer.isHealthy()
gotenbergMockServer.isHealthy()
prisonRegisterMockServer.isHealthy()
courtRegisterMockServer.isHealthy()
hmppsAuthMockServer.isHealthy()
healthCheckIsUpWith(
"/health",
"status" to "UP",
"components.prisonerOffenderSearch.status" to "UP",
"components.prisonerOffenderSearch.details.status" to OK.name,
"components.gotenberg.status" to "UP",
"components.gotenberg.details.status" to OK.name,
"components.healthInfo.details.version" to LocalDateTime.now().format(ISO_DATE),
"components.db.status" to "UP",
"components.s3.status" to "UP",
"components.prisonRegister.status" to "UP",
"components.courtRegister.status" to "UP",
"components.clamAV.status" to "UP",
"components.hmppsAuth.status" to "UP",
"components.bankHoliday.status" to "UP",
"components.policeUkApi.status" to "UP"
)
}
@Test
fun `timeout is handled gracefully as down`() {
prisonerOffenderSearchMockServer.isSlow(INTERNAL_SERVER_ERROR, 3000)
gotenbergMockServer.isSlow(INTERNAL_SERVER_ERROR, 3000)
prisonRegisterMockServer.isSlow(INTERNAL_SERVER_ERROR, 3000)
courtRegisterMockServer.isSlow(INTERNAL_SERVER_ERROR, 3000)
hmppsAuthMockServer.isSlow(INTERNAL_SERVER_ERROR, 3000)
healthCheckIsUpWith(
"/health",
"status" to "UP",
"components.db.status" to "UP",
"components.s3.status" to "UP",
"components.clamAV.status" to "UP",
"components.healthInfo.details.version" to LocalDateTime.now().format(ISO_DATE),
"components.prisonerOffenderSearch.status" to "UNKNOWN",
"components.prisonerOffenderSearch.details.body" to "java.lang.IllegalStateException: Timeout on blocking read for 2000000000 NANOSECONDS",
"components.gotenberg.status" to "UNKNOWN",
"components.gotenberg.details.body" to "java.lang.IllegalStateException: Timeout on blocking read for 2000000000 NANOSECONDS",
"components.prisonRegister.status" to "UNKNOWN",
"components.prisonRegister.details.body" to "java.lang.IllegalStateException: Timeout on blocking read for 2000000000 NANOSECONDS",
"components.bankHoliday.status" to "UNKNOWN",
"components.bankHoliday.details.body" to "java.lang.IllegalStateException: Timeout on blocking read for 2000000000 NANOSECONDS",
"components.policeUkApi.status" to "UNKNOWN",
"components.policeUkApi.details.body" to "java.lang.IllegalStateException: Timeout on blocking read for 2000000000 NANOSECONDS",
"components.courtRegister.status" to "UNKNOWN",
"components.courtRegister.details.body" to "java.lang.IllegalStateException: Timeout on blocking read for 2000000000 NANOSECONDS",
"components.hmppsAuth.status" to "UNKNOWN",
"components.hmppsAuth.details.body" to "java.lang.IllegalStateException: Timeout on blocking read for 2000000000 NANOSECONDS",
"components.bankHoliday.status" to "UNKNOWN",
"components.bankHoliday.details.body" to "java.lang.IllegalStateException: Timeout on blocking read for 2000000000 NANOSECONDS"
)
}
@ParameterizedTest(name = "service is unhealthy when {0} is unhealthy")
@MethodSource("parameterArrays")
fun `service is unhealthy when dependency is unhealthy`(
dependency: String,
mockServer: HealthServer
) {
mockServer.isUnhealthy()
healthCheckIsDownWith(
SERVICE_UNAVAILABLE,
"components.$dependency.details.status" to INTERNAL_SERVER_ERROR.name
)
}
private fun parameterArrays(): Stream<Arguments>? {
return Stream.of(
Arguments.of("prisonerOffenderSearch", prisonerOffenderSearchMockServer),
Arguments.of("courtRegister", courtRegisterMockServer),
Arguments.of("prisonRegister", prisonRegisterMockServer),
Arguments.of("bankHoliday", prisonRegisterMockServer), // using prisonRegisterMock as mock per profile config
Arguments.of("policeUkApi", prisonRegisterMockServer), // using prisonRegisterMock as mock per profile config
Arguments.of("gotenberg", gotenbergMockServer),
Arguments.of("hmppsAuth", hmppsAuthMockServer),
)
}
@Test
fun `Health ping page is accessible`() {
healthCheckIsUp("/health/ping")
}
@Test
fun `readiness reports ok`() {
healthCheckIsUp("/health/readiness")
}
@Test
fun `liveness reports ok`() {
healthCheckIsUp("/health/liveness")
}
private fun healthCheckIsUp(healthUrl: String) {
healthCheckIsUpWith(healthUrl, "status" to "UP")
}
private fun healthCheckIsDownWith(expectedStatus: HttpStatus, vararg jsonPathAssertions: Pair<String, String>) {
unauthenticatedGet("/health", expectedStatus)
.jsonPath("status").isEqualTo("DOWN")
.apply {
jsonPathAssertions.forEach { (jsonPath, equalTo) ->
hasJsonPath(jsonPath, equalTo)
}
}
}
private fun healthCheckIsUpWith(healthUrl: String, vararg jsonPathAssertions: Pair<String, String>, expectedStatus: HttpStatus = OK) {
unauthenticatedGet(healthUrl, expectedStatus)
.apply {
jsonPathAssertions.forEach { (jsonPath, equalTo) ->
hasJsonPath(jsonPath, equalTo)
}
}
}
private fun WebTestClient.BodyContentSpec.hasJsonPath(jsonPath: String, equalTo: String) =
jsonPath(jsonPath).isEqualTo(equalTo)
}
| 3
|
Kotlin
|
0
| 1
|
708e801435483b0406197fdc61e85ab7c2d2cc82
| 6,642
|
manage-recalls-api
|
MIT License
|
src/test/kotlin/kotlinx/fuzzer/testclasses/singleclasstest/TestClass.kt
|
zuevmaxim
| 245,368,264
| false
|
{"Kotlin": 125295, "Java": 24863, "Shell": 1145}
|
package kotlinx.fuzzer.testclasses.singleclasstest
import kotlinx.fuzzer.coverage.SingleClassCoverageRunnerTest
import java.nio.ByteBuffer
import kotlin.random.Random
@Suppress("unused", "UNUSED_PARAMETER", "NOTHING_TO_INLINE", "LiftReturnOrAssignment", "LiftReturnOrAssignment")
internal class TestClass {
private inline fun currentFunctionName() = Thread.currentThread().stackTrace[1].methodName
private inline fun register() = SingleClassCoverageRunnerTest.doneMethods.add(currentFunctionName())
fun testRunning(bytes: ByteArray) = register().let { 1 }
fun simpleCoverageTest(bytes: ByteArray): Int {
val x = Random.nextInt()
val y = Random.nextInt()
return x + y
}
fun simpleTest(bytes: ByteArray) = 1
fun coverageTest(bytes: ByteArray): Int {
val buffer = ByteBuffer.wrap(bytes)
val x = buffer.int
val y = buffer.int
return if (x % 2 == 0 && y % 2 == 0) {
1
} else if (x % 2 == 0 && y % 2 == 1) {
2
} else if (x % 2 == 1 && y % 2 == 0) {
3
} else {
4
}
}
fun conditionTest(bytes: ByteArray): Int {
check(bytes.size != 2)
require(bytes.size != 1)
if (bytes.size == 4) return 1
return 0
}
fun failTest(bytes: ByteArray): Int = error("Crash")
}
| 1
|
Kotlin
|
0
| 3
|
34255b0a35ee479021a165f2bdbe6ffe0b3109c5
| 1,368
|
kotlin-fuzzer
|
MIT License
|
src/main/kotlin/io/projectenv/intellijplugin/listeners/ProjectEnvConfigFileListener.kt
|
Project-Env
| 324,322,609
| false
|
{"Kotlin": 50790}
|
package io.projectenv.intellijplugin.listeners
import com.intellij.openapi.components.service
import com.intellij.openapi.project.Project
import com.intellij.openapi.vfs.VirtualFileManager
import com.intellij.openapi.vfs.newvfs.BulkFileListener
import com.intellij.openapi.vfs.newvfs.events.VFileEvent
import io.projectenv.intellijplugin.notifications.ProjectEnvNotificationGroup
import io.projectenv.intellijplugin.services.ProjectEnvConfigFileResolverService
import org.apache.commons.lang3.StringUtils
class ProjectEnvConfigFileListener(val project: Project) : BulkFileListener {
override fun after(events: List<VFileEvent>) {
val projectEnvConfigFileUrl = getProjectEnvConfigFileUrl()
for (event in events) {
val virtualFile = event.file ?: continue
if (StringUtils.equals(projectEnvConfigFileUrl, virtualFile.url)) {
ProjectEnvNotificationGroup.showReloadNotification(
"Project-Env config file has been updated",
project
)
return
}
}
}
private fun getProjectEnvConfigFileUrl(): String? {
val projectEnvConfigFile = project.service<ProjectEnvConfigFileResolverService>().resolveConfig() ?: return null
return VirtualFileManager.getInstance()
.findFileByNioPath(projectEnvConfigFile.toPath())?.url
}
}
| 4
|
Kotlin
|
1
| 7
|
6bb6816c5f2ab7624d391d293ab99146a34e020b
| 1,404
|
project-env-intellij-plugin
|
MIT License
|
ProjectEuler/P7.kt
|
Code-With-Aagam
| 455,843,406
| true
|
{"C++": 2823238, "Kotlin": 190162, "Swift": 170085, "Java": 56114, "Python": 14574, "C": 3440, "Shell": 732, "JavaScript": 719}
|
fun main() {
val T = readLine()?.toInt() ?: 0
val N = (5e5).toInt()
val isPrime = MutableList(N + 1) { true }
val primeNumbers = mutableListOf<Int>()
for (num in 2 until N + 1) {
if (isPrime[num]) {
primeNumbers.add(num)
for (nextNum in 2 * num until N + 1 step num) {
isPrime[nextNum] = false
}
}
}
repeat(T) {
val n = readLine()?.toInt() ?: 0
println(primeNumbers[n - 1])
}
}
| 0
| null |
0
| 2
|
610520cc396fb13a03c606b5fb6739cfd68cc444
| 493
|
competitive-programming
|
MIT License
|
app/src/main/kotlin/com/baculsoft/kotlin/android/views/base/IPresenter.kt
|
KotlinID
| 72,181,347
| false
| null |
package com.baculsoft.kotlin.android.views.base
/**
* @author <NAME> (<EMAIL>)
*/
interface IPresenter<in T : IView> {
fun onAttach(view: T)
fun onDetach()
}
| 0
|
Kotlin
|
9
| 11
|
d8e7983dcb7f4fa224adea3466af081fe57a4fa3
| 169
|
kotlin-android
|
Apache License 2.0
|
selekt-java/src/integrationTest/kotlin/com/bloomberg/selekt/jvm/SQLiteDatabaseSampleTest.kt
|
bloomberg
| 281,998,984
| false
| null |
/*
* Copyright 2022 Bloomberg Finance L.P.
*
* 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.bloomberg.selekt.jvm
import com.bloomberg.selekt.SQLiteJournalMode
import java.io.File
import kotlin.test.assertEquals
import org.junit.jupiter.api.Test
internal class SQLiteDatabaseSampleTest {
private val database = openOrCreateDatabase(
File(requireNotNull(javaClass.classLoader?.getResource("databases/sample.sqlcipher.db")?.file)),
SQLiteJournalMode.WAL.databaseConfiguration,
ByteArray(32) { 0x42 }
)
@Test
fun readDatabase() {
database.query("SELECT * FROM Users", emptyArray()).use {
assertEquals(1, it.count)
}
}
}
| 5
| null |
8
| 46
|
519361cfb24c16fdb602fd5b6f156ce4cdabce72
| 1,219
|
selekt
|
Apache License 2.0
|
kotlin/basic/src/test/kotlin/com/shengsiyuan/kotlin/Run_Let_With_Also_Apply.kt
|
cuixbo
| 538,532,557
| true
|
{"Java": 745660, "Kotlin": 323125, "JavaScript": 80254, "Dart": 24553, "Python": 8877, "HTML": 5008, "Objective-C": 4465, "Starlark": 1916, "Ruby": 776, "CSS": 773, "Thrift": 670, "Swift": 404, "Makefile": 273}
|
package com.shengsiyuan.kotlin
/**
* run
* 可以將 run 想像成一個獨立出來的 Scope, run 會把最後一行的東西回傳或是帶到下一個 chain
*/
fun run1() {
val whatsMyName = "Francis"
run {
val whatsMyName = "Ajax"
println("Call my name! $whatsMyName")
}
println("What's my name? $whatsMyName")
}
open class Telephone : Parcelable() {
var whoCallMe: String = ""
var fromWhere: String = ""
fun callMe(myName: String) {
println("$whoCallMe ! Call me $myName !!")
}
}
/**
* run 還能將最後一行的東西回傳,或傳給下一個 chain ,也就是說能這麼寫:
*/
fun run2() {
run {
val telephone = Telephone()
telephone.whoCallMe = "English"
telephone // <-- telephone 被帶到下一個 Chain
}.callMe("Softest part of heart") // <-- 這裡可以執行 `Telephone` Class 的方法
println("=========================")
val wowCall = run {
val telephone = Telephone()
telephone.fromWhere = "Sagittarius"
telephone.whoCallMe = "Still Unknown"
telephone // <-- telephone 回傳,wowCall 型態成為 Telephone
}
println("WOW, This signal is from ${wowCall.fromWhere}")
}
class GoodSmartPhone : Telephone() {
var hello: Boolean = false
fun setCleanSystemInterface(b: Boolean) {
}
fun setGreatBatteryLife(b: Boolean) {
}
fun setGreatBuildQuality(b: Boolean) {
}
fun setNouch(b: Boolean) {
hello = b
}
}
/**
* with 一般常常作為初始化時使用, with(T) 之中的傳入值可以以 this (稱作 identifier) 在 scope 中取用,不用打出 this也沒關係。
* 雖然, with 也會將最後一行回傳,但目前看起來大部分還是只用它來做初始化。透過 with()很明確知道是為了括弧中的變數進行設定。
*
* 但很多使用狀況變數可能是可為空的變數,如此一來 with的 scope 中就必須要宣告 「?」或「!!」來取用該物件的方法 (Method)。
*/
fun with1(good: GoodSmartPhone?) {
val greatSmartphone = GoodSmartPhone()
with(greatSmartphone) {
this.setCleanSystemInterface(true)
// `this` is not necessary
setGreatBatteryLife(true)
setGreatBuildQuality(true)
setNouch(true)
"123"
}
val str = with(good) {
println("setCleanSystemInterface: ")
this?.setCleanSystemInterface(true)
println("setNouch: ")
this?.setNouch(true)
"123"
}
println(good?.hello)
println(str)
}
/**
* T.run
* 什⋯ 什麼嘛,多了 T 是怎麼一回事!
* 這些 function 的使用方式,需要接在一個變數後面才行。像是 someVariable.run { /* do something */ },
* 包含 T.run 下面四個 let also apply 都屬於這種 extension function。
* 因為 run有兩種用法,這裡為了避免混淆而將 T 寫出來。
*
* T.run 也能像 with 一樣來做初始化,而且 extension function
* 有個好處是可以在使用時就進行 「?」 或 「!!」 的宣告。另外,T 能夠以 this 的形式在 scope 內取用。
* 像是上面的範例,如果用 T.run來 做初始化,就會是:
*
* 當然如果傳進來的變數是空值, T.run{} 內的程式碼就根本不會執行了
* 除此之外,T.run 和 run 的特性完全一樣。可以將最後一行的東西回傳,或是傳給下一個 chain
*/
open class TPhone : Telephone() {
fun tRun(goodSmartPhone: GoodSmartPhone?) {
goodSmartPhone?.run {
this.setCleanSystemInterface(true)
// `this` is not necessary
setGreatBatteryLife(true)
setGreatBuildQuality(true)
setNouch(true)
/*
* 但實作上 T.run 有可能需要取用外層變數或方法,但 this 已經被變數 T 佔用。例如,取得 Activity 則要這樣處理
*/
this@TPhone.fromWhere
}
}
/*
* 有沒有其他的做法,可以讓 identifier 不是 this呢?
* 這就需要來介紹下一位: let
*/
}
/**
* let
* 又或者可以寫成 T.let,也是一個 extension function。
* T 在 scope 內則是用 it 來存取而不是 this。也可以依照需求改成其他的名字,增加可讀性。
* 與 run 相同,會將最後一行帶到下一個 chain 或是回傳。
*/
class TreasureBox {
private val passwd = "<PASSWORD>"
private val treasure = "You've got a Windows install USB"
fun open(key: String?): String {
return key?.let {
// `it` is the key String.
// `this` is TreasureBox.
var treasure = "error"
if (it == passwd) {
treasure = this.treasure
}
treasure
} ?: "error"
}
}
/**
* 希望能自訂 identifier 時,或是希望 this 可以存取到上層內容時,建議使用 let
*
* identifier -> 身份标识,例如 this super,他们后面跟上 @ 符号; 或者自定义类似这种身份标识
*/
fun let1() {
val treasureBox = TreasureBox()
var open = treasureBox.open(null)
println(open)
open = treasureBox.open("admin")
println(open)
open = treasureBox.open("123456")
println(open)
}
/**
* also
* 也可以寫作 T.also
* 剩下的 also和 apply 決大部分也是使用於初始化物件。前文提到:這幾種 Standard Library Function 其實可以互相替換,選擇合適的場景使用即可。
* 而它們與上面的 run 與 let的不同之處在於: run與 let 會將最後一行傳給下個 Chain 或是回傳,物件類型依最後一行而定; also和 apply 則是將「自己 (this)」回傳或傳入下個 chain。
* 有點像是 builder pattern ,做完一次設定後又將自己回傳回去。另外, also在 scope 內可以透過 it 來存取 T本身。
*/
fun also1() {
val goodSmartPhone = GoodSmartPhone().also {
it.setCleanSystemInterface(true)
}.also {
it.setGreatBatteryLife(true)
}.also {
it.setGreatBuildQuality(true)
}.also {
it.setNouch(true)
}
println(goodSmartPhone)
}
/**
* apply
* 也可以寫作 T.apply 。
* apply與 also 有 87 分像,不同的地方是 apply 在 scope 內 T 的存取方式是 this ,其他都與 also 一樣。
*
* 這裡的範例以 Fragment 生成時,需要時做的 newInstance()方法。利用 apply 和 also 在 Kotlin 之中如何改寫:
*/
class ListFragment {
var arguments: Bundle = Bundle()
}
class Bundle {
fun putParcelableArrayList(key: String, value: ArrayList<out Parcelable>) {
}
}
open class Parcelable
class XActivity {
companion object {
private const val COFFEE_SHOP_LIST_KEY = "coffee-list-key"
fun newInstance(coffeeShops: List<Telephone>): ListFragment {
return ListFragment().apply {
// `this` is `ListFragment` in apply scope
arguments = Bundle().also {
// `it` is `Bundle` in also scope
// `this` is `ListFragment`
it.putParcelableArrayList(COFFEE_SHOP_LIST_KEY, coffeeShops as ArrayList<out Parcelable>)
}
}
}
fun newInstance2(coffeeShops: List<Telephone>): ListFragment {
return ListFragment().also {
it.arguments = Bundle().also {
it.putParcelableArrayList(COFFEE_SHOP_LIST_KEY, coffeeShops as ArrayList<out Parcelable>)
}
}
}
}
}
/**
* Created by andy
* 2019/1/22.
* Email: <EMAIL>
*/
fun main() {
run1()
run2()
println("*****************")
with1(null)
println("*****************")
let1()
also1()
}
| 0
| null |
0
| 0
|
8934028fb0bf69c289b82f737682fa5565f1dd76
| 6,165
|
ShengSiYuan
|
Apache License 2.0
|
app/src/main/java/com/junerver/cloudnote/utils/NetUtils.kt
|
junerver
| 67,023,500
| false
|
{"Gradle": 3, "Java Properties": 2, "Shell": 1, "Text": 1, "Ignore List": 2, "Batchfile": 1, "Markdown": 1, "Proguard": 1, "Kotlin": 29, "XML": 23, "Java": 5}
|
package com.junerver.cloudnote.utils
import android.Manifest.permission
import android.app.Activity
import android.content.ComponentName
import android.content.Context
import android.content.Intent
import android.net.ConnectivityManager
import android.net.NetworkInfo
import androidx.annotation.RequiresPermission
/**
* Created by Junerver on 2015/11/12.
* 跟网络相关的工具类
*/
/**
*
*/
object NetUtils {
/**
* 判断网络是否连接
* @param context
* @return
*/
@JvmStatic
fun isConnected(context: Context): Boolean {
val connectivity = context
.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager
if (null != connectivity) {
val info = connectivity.activeNetworkInfo
if (null != info && info.isConnected) {
if (info.state == NetworkInfo.State.CONNECTED) {
return true
}
}
}
return false
}
/**
* 判断是否是wifi连接
*/
fun isWifi(context: Context): Boolean {
val cm = context
.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager
?: return false
return cm.activeNetworkInfo!!.type == ConnectivityManager.TYPE_WIFI
}
/**
* 打开网络设置界面
*/
fun openSetting(activity: Activity) {
val intent = Intent("/")
val cm = ComponentName(
"com.android.settings",
"com.android.settings.WirelessSettings"
)
intent.component = cm
intent.action = "android.intent.action.VIEW"
activity.startActivityForResult(intent, 0)
}
}
| 0
|
Kotlin
|
5
| 23
|
dced9fc5f03fcf93247f1f79528fbc5fa7b884dc
| 1,642
|
CloudNote
|
Apache License 2.0
|
DSLs/kubernetes/dsl/src/main/kotlin-gen/com/fkorotkov/kubernetes/autoscaling/v2beta2/metadata.kt
|
fkorotkov
| 84,911,320
| false
| null |
// GENERATED
package com.fkorotkov.kubernetes.autoscaling.v2beta2
import io.fabric8.kubernetes.api.model.ListMeta as model_ListMeta
import io.fabric8.kubernetes.api.model.ObjectMeta as model_ObjectMeta
import io.fabric8.kubernetes.api.model.autoscaling.v2beta2.HorizontalPodAutoscaler as v2beta2_HorizontalPodAutoscaler
import io.fabric8.kubernetes.api.model.autoscaling.v2beta2.HorizontalPodAutoscalerList as v2beta2_HorizontalPodAutoscalerList
fun v2beta2_HorizontalPodAutoscaler.`metadata`(block: model_ObjectMeta.() -> Unit = {}) {
if(this.`metadata` == null) {
this.`metadata` = model_ObjectMeta()
}
this.`metadata`.block()
}
fun v2beta2_HorizontalPodAutoscalerList.`metadata`(block: model_ListMeta.() -> Unit = {}) {
if(this.`metadata` == null) {
this.`metadata` = model_ListMeta()
}
this.`metadata`.block()
}
| 6
|
Kotlin
|
19
| 317
|
ef8297132e6134b6f65ace3e50869dbb2b686b21
| 846
|
k8s-kotlin-dsl
|
MIT License
|
app/src/main/kotlin/com/softteco/template/ui/feature/forgotPassword/ForgotPasswordScreen.kt
|
SoftTeco
| 644,768,318
| false
|
{"Kotlin": 106892, "Shell": 354}
|
package com.softteco.template.ui.feature.forgotPassword
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.runtime.Composable
import androidx.compose.runtime.collectAsState
import androidx.compose.runtime.getValue
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.hilt.navigation.compose.hiltViewModel
import com.softteco.template.R
import com.softteco.template.ui.components.CustomTopAppBar
import com.softteco.template.ui.components.EmailField
import com.softteco.template.ui.components.PrimaryButton
import com.softteco.template.ui.components.TextSnackbarContainer
import com.softteco.template.ui.theme.AppTheme
import com.softteco.template.ui.theme.Dimens
@Composable
fun ForgotPasswordScreen(
modifier: Modifier = Modifier,
viewModel: ForgotPasswordViewModel = hiltViewModel(),
onBackClicked: () -> Unit = {}
) {
val state by viewModel.state.collectAsState()
ScreenContent(
modifier = modifier,
state = state,
onBackClicked = onBackClicked
)
}
@Composable
private fun ScreenContent(
state: ForgotPasswordViewModel.State,
modifier: Modifier = Modifier,
onBackClicked: () -> Unit = {}
) {
TextSnackbarContainer(
modifier = modifier,
snackbarText = stringResource(state.snackBar.textId),
showSnackbar = state.snackBar.show,
onDismissSnackbar = state.dismissSnackBar,
) {
Column(
modifier = Modifier.fillMaxSize(),
verticalArrangement = Arrangement.spacedBy(Dimens.PaddingExtraLarge),
horizontalAlignment = Alignment.CenterHorizontally
) {
CustomTopAppBar(
stringResource(id = R.string.forgot_password),
showBackIcon = true,
modifier = Modifier.fillMaxWidth(),
onBackClicked = onBackClicked
)
Column(
modifier = Modifier.padding(Dimens.PaddingNormal),
verticalArrangement = Arrangement.Center,
horizontalAlignment = Alignment.CenterHorizontally
) {
EmailField(
emailValue = state.emailValue,
onEmailChanged = state.onEmailChanged,
fieldStateEmail = state.fieldStateEmail,
modifier = Modifier.fillMaxWidth()
)
PrimaryButton(
buttonText = stringResource(id = R.string.restore_password),
loading = state.loading,
modifier = Modifier
.fillMaxWidth()
.padding(top = Dimens.PaddingLarge),
onClick = { state.onRestorePasswordClicked() }
)
}
}
}
}
@Preview
@Composable
private fun Preview() {
AppTheme {
ScreenContent(state = ForgotPasswordViewModel.State())
}
}
| 21
|
Kotlin
|
6
| 4
|
576c3f81e8a6d274e86b224031d2b78dc92d7a07
| 3,255
|
AndroidAppTemplate
|
MIT License
|
shared/src/commonMain/kotlin/ru/kontur/mobile/visualfsm/sample_kmm/feature/auth/fsm/actions/HandleAuthResult.kt
|
Kontur-Mobile
| 535,246,746
| false
| null |
package ru.kontur.mobile.visualfsm.sample_android.feature.auth.fsm.actions
import ru.kontur.mobile.visualfsm.Transition
import ru.kontur.mobile.visualfsm.sample_android.feature.auth.fsm.AuthFSMState.*
import ru.kontur.mobile.visualfsm.sample_android.feature.auth.data.AuthResult
class HandleAuthResult(val result: AuthResult) : AuthFSMAction() {
inner class Success : Transition<AsyncWorkState.Authenticating, UserAuthorized>() {
override fun predicate(state: AsyncWorkState.Authenticating): Boolean {
return result == AuthResult.SUCCESS
}
override fun transform(state: AsyncWorkState.Authenticating): UserAuthorized {
return UserAuthorized(state.mail)
}
}
inner class BadCredential : Transition<AsyncWorkState.Authenticating, Login>() {
override fun predicate(state: AsyncWorkState.Authenticating): Boolean {
return result == AuthResult.BAD_CREDENTIAL
}
override fun transform(state: AsyncWorkState.Authenticating): Login {
return Login(state.mail, state.password, "Bad credential")
}
}
inner class ConnectionFailed : Transition<AsyncWorkState.Authenticating, Login>() {
override fun predicate(state: AsyncWorkState.Authenticating): Boolean {
return result == AuthResult.NO_INTERNET
}
override fun transform(state: AsyncWorkState.Authenticating): Login {
return Login(state.mail, state.password, "No internet")
}
}
}
| 0
|
Kotlin
|
0
| 6
|
3c586754590a7347e4aaed097a1d2a5f934bb1b7
| 1,517
|
VisualFSM-Sample-KMM
|
MIT License
|
app/src/main/java/by/d1makrat/microblogging_app/ui/activity/MainActivity.kt
|
DzmitryLakisau
| 143,532,842
| false
| null |
package by.d1makrat.microblogging_app.ui.activity
import android.app.Activity
import android.app.FragmentManager
import android.content.Intent
import android.os.Bundle
import android.support.design.widget.NavigationView
import android.support.v4.view.GravityCompat
import android.support.v7.app.ActionBarDrawerToggle
import android.view.MenuItem
import android.view.View
import by.d1makrat.microblogging_app.R
import by.d1makrat.microblogging_app.R.id.*
import by.d1makrat.microblogging_app.R.string.*
import by.d1makrat.microblogging_app.presenter.activity.MainPresenter
import by.d1makrat.microblogging_app.ui.fragment.AddPostFragment
import by.d1makrat.microblogging_app.ui.fragment.AllPostsFragment
import by.d1makrat.microblogging_app.ui.fragment.HomeFragment
import by.d1makrat.microblogging_app.ui.fragment.ProfileFragment
import by.d1makrat.microblogging_app.workers.FirebaseAuthenticationWorker
import kotlinx.android.synthetic.main.activity_main.*
import kotlinx.android.synthetic.main.app_bar_main.*
import kotlinx.android.synthetic.main.nav_header_main.*
class MainActivity: Activity(), NavigationView.OnNavigationItemSelectedListener, MainPresenter.View {
private val manager: FragmentManager = fragmentManager
private val mainPresenter = MainPresenter()
override fun onBackPressed() {
if (drawer_layout.isDrawerOpen(GravityCompat.START)) {
drawer_layout.closeDrawer(GravityCompat.START)
} else {
super.onBackPressed()
}
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
mainPresenter.attachView(this)
floatingActionButton.setOnClickListener{
manager.beginTransaction().replace(R.id.content_main, AddPostFragment()).commit()
toolbar.title = getString(nav_add)
floatingActionButton.visibility = View.GONE
}
val toggle = ActionBarDrawerToggle(
this, drawer_layout, toolbar, navigation_drawer_open, navigation_drawer_close)
drawer_layout.addDrawerListener(toggle)
toggle.syncState()
navigationView.setNavigationItemSelectedListener(this)
manager.beginTransaction().replace(R.id.content_main, HomeFragment()).commit()
toolbar?.title = getString(nav_home)
}
override fun onStart() {
super.onStart()
mainPresenter.getUserInfo()
}
override fun onDestroy() {
mainPresenter.detachView()
super.onDestroy()
}
override fun onNavigationItemSelected(item: MenuItem): Boolean {
floatingActionButton.visibility = View.VISIBLE
when (item.itemId){
all_posts -> {
manager.beginTransaction().replace(R.id.content_main, AllPostsFragment()).commit()
toolbar?.title = getString(nav_all_posts)
}
home ->{
manager.beginTransaction().replace(R.id.content_main, HomeFragment()).commit()
toolbar.title = getString(nav_home)
}
add ->{
manager.beginTransaction().replace(R.id.content_main, AddPostFragment()).commit()
toolbar?.title = getString(nav_add)
floatingActionButton.visibility = View.GONE
}
profile ->{
manager.beginTransaction().replace(R.id.content_main, ProfileFragment()).commit()
toolbar?.title = getString(nav_profile)
}
logout ->{
FirebaseAuthenticationWorker().signOut()
startSignInScreen()
finish()
}
}
drawer_layout.closeDrawer(GravityCompat.START)
return true
}
private fun startSignInScreen(){
startActivity(Intent(this, SignInActivity::class.java))
}
override fun showUserInfoInHeader(userName: String, userSurname: String, userMail: String) {
textView_header_title.text = getString(name_surname, userName, userSurname)
textView_header_subtitle.text = userMail
}
}
| 0
|
Kotlin
|
0
| 1
|
a7c99196060e4e3b6605ec8744b841833923a507
| 4,129
|
Microblogging-App
|
Apache License 2.0
|
src/main/kotlin/org/ivcode/core/claimquery/JwtClaimStatementParser.kt
|
iv-host
| 743,368,620
| false
|
{"Kotlin": 69527, "TypeScript": 52806, "Shell": 3061, "HTML": 1720, "Dockerfile": 841, "CSS": 147}
|
package org.ivcode.homeportal.utils.claimquery
internal class JwtClaimStatementParser {
fun parse(tokens: List<Token>): Statement {
val tokenWalker = TokenWalker(tokens)
val statement = statementNode(tokenWalker)
val next = tokenWalker.next()
if(next!=null) {
throw IllegalArgumentException("Unexpected Token: tokens found after root statement: index=${next.index}")
}
return statement
}
private fun statementNode(tokens: TokenWalker): Statement {
val token = tokens.next()!!
when(token.type) {
TokenType.DOT -> {
throw IllegalArgumentException("statements cannot start with a dot. index=${token.index}")
}
TokenType.OPEN_PARENTHESIS -> {
throw IllegalArgumentException("statements cannot start with open parenthesis. index=${token.index}")
}
TokenType.CLOSE_PARENTHESIS -> {
throw IllegalArgumentException("statements cannot start with close parenthesis. index=${token.index}")
}
TokenType.COMMA -> {
throw IllegalArgumentException("statements cannot start with close parenthesis. index=${token.index}")
}
TokenType.STRING_LITERAL -> {
return StringLiteralStatement(token.index, token.value as String)
}
TokenType.BOOLEAN_LITERAL -> {
return BooleanLiteralStatement(token.index, token.value as Boolean)
}
TokenType.IDENTIFIER -> {
return identifierNode(tokens)
}
}
}
private fun identifierNode(tokens: TokenWalker, parent: VariableStatement?=null): Statement {
val identifierToken = tokens.get()!!
if(identifierToken.type!=TokenType.IDENTIFIER) {
throw IllegalArgumentException("unexpected token type: expected IDENTIFIER but found ${identifierToken.type}. index=${identifierToken.index}")
}
val token = tokens.peekAhead()!!
when(token.type) {
TokenType.DOT -> {
tokens.next() // consume dot
var next = tokens.next()!! // consume next
if(next.type!=TokenType.IDENTIFIER) {
throw IllegalArgumentException("Unexpected Token: Dot separators must be followed by an identifier. index=${token.index}")
}
return identifierNode(tokens, VariableStatement(token.index, identifierToken.value as String, parent))
}
TokenType.OPEN_PARENTHESIS -> {
tokens.next() // consume open paren
return functionNode(tokens, token.index, identifierToken.value as String, parent)
}
TokenType.CLOSE_PARENTHESIS -> {
return VariableStatement(token.index, identifierToken.value as String, parent)
}
TokenType.COMMA -> {
return VariableStatement(token.index, identifierToken.value as String, parent)
}
TokenType.STRING_LITERAL -> {
throw IllegalArgumentException("identifiers cannot end with a string literal. index=${token.index}")
}
TokenType.BOOLEAN_LITERAL -> {
throw IllegalArgumentException("identifiers cannot end with a boolean literal. index=${token.index}")
}
TokenType.IDENTIFIER -> {
throw IllegalArgumentException("identifiers cannot follow identifiers. index=${token.index}")
}
}
}
private fun functionNode(tokens: TokenWalker, index: Int, name: String, parent: VariableStatement?): FunctionStatement {
var next: Token = tokens.peekAhead()!!
if(next.type==TokenType.CLOSE_PARENTHESIS) {
// function without params
return FunctionStatement(
index = index,
name = name,
params = listOf(),
parent = parent
)
}
val params = mutableListOf<Statement>()
do {
params.add(statementNode(tokens))
next = tokens.next()!!
if(next.type!=TokenType.CLOSE_PARENTHESIS && next.type!=TokenType.COMMA) {
throw IllegalArgumentException("Unexpected Token: function params must end in a comma or close paren. index=${next.index}")
}
} while (next.type!=TokenType.CLOSE_PARENTHESIS)
return FunctionStatement(
index = index,
name = name,
params = params,
parent = parent
)
}
}
| 2
|
Kotlin
|
0
| 0
|
ca187a0686460439dd2befcf97d921cb45af9e9a
| 4,658
|
home-portal
|
Apache License 2.0
|
butterfly/src/main/java/com/morpho/butterfly/lexicons/com/atproto/admin/getInviteCodes.kt
|
morpho-app
| 752,463,268
| false
|
{"Kotlin": 811512}
|
package com.atproto.admin
import com.atproto.server.InviteCode
import kotlin.Any
import kotlin.Long
import kotlin.Pair
import kotlin.String
import kotlinx.collections.immutable.toImmutableList
import kotlinx.serialization.Serializable
import radiant.nimbus.api.model.ReadOnlyList
@Serializable
public data class GetInviteCodesQueryParams(
public val sort: GetInviteCodesSort? = GetInviteCodesSort.RECENT,
public val limit: Long? = 100,
public val cursor: String? = null,
) {
init {
require(limit == null || limit >= 1) {
"limit must be >= 1, but was $limit"
}
require(limit == null || limit <= 500) {
"limit must be <= 500, but was $limit"
}
}
public fun asList(): ReadOnlyList<Pair<String, Any?>> = buildList {
add("sort" to sort)
add("limit" to limit)
add("cursor" to cursor)
}.toImmutableList()
}
@Serializable
public data class GetInviteCodesResponse(
public val cursor: String? = null,
public val codes: ReadOnlyList<InviteCode>,
)
| 21
|
Kotlin
|
0
| 8
|
525b2f18e9cef6d973c66cf2b3684a06d38332ab
| 999
|
Morpho
|
Apache License 2.0
|
samples/emoji-search/android-tests/src/main/kotlin/com/example/redwood/emojisearch/android/tests/AbstractEmojiSearchUiTest.kt
|
cashapp
| 305,409,146
| false
| null |
/*
* Copyright (C) 2023 Square, 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.example.redwood.emojisearch.android.tests
import android.content.Context
import android.content.Intent.FLAG_ACTIVITY_CLEAR_TASK
import androidx.test.core.app.ApplicationProvider
import androidx.test.platform.app.InstrumentationRegistry
import androidx.test.uiautomator.By
import androidx.test.uiautomator.By.pkg
import androidx.test.uiautomator.UiDevice
import androidx.test.uiautomator.UiSelector
import androidx.test.uiautomator.Until
import kotlin.time.Duration
import kotlin.time.Duration.Companion.seconds
import org.junit.Before
import org.junit.Test
abstract class AbstractEmojiSearchUiTest(private val appPackage: String) {
private val device = UiDevice.getInstance(InstrumentationRegistry.getInstrumentation())!!
private val search get() = device.findObject(By.clazz("android.widget.EditText"))!!
@Before fun before() {
val context = ApplicationProvider.getApplicationContext<Context>()
val intent = context.packageManager.getLaunchIntentForPackage(appPackage)!!.apply {
addFlags(FLAG_ACTIVITY_CLEAR_TASK)
}
context.startActivity(intent)
device.wait(Until.hasObject(pkg(appPackage).depth(0)), 5_000)
}
@Test fun searchTrees() {
awaitText("0. +1")
search.text = "tree"
awaitText("301. christmas_tree")
search.clear()
awaitText("0. +1")
}
private fun awaitText(value: String, duration: Duration = 10.seconds) {
val text = device.findObject(UiSelector().text(value))
if (!text.waitForExists(duration.inWholeMilliseconds)) {
throw AssertionError("Waited $duration for \"$value\" but never appeared")
}
}
}
| 112
| null |
73
| 1,648
|
3f14e622c2900ec7e0dfaff5bd850c95a7f29937
| 2,209
|
redwood
|
Apache License 2.0
|
src/main/kotlin/me/phantomx/pekonime/bot/utils/BotUtils.kt
|
adi-itgg
| 561,369,447
| false
|
{"Kotlin": 26277}
|
package me.phantomx.pekonime.bot.utils
import eu.vendeli.tgbot.interfaces.Action
import eu.vendeli.tgbot.interfaces.Event
import eu.vendeli.tgbot.interfaces.sendAsync
import eu.vendeli.tgbot.types.User
import eu.vendeli.tgbot.types.internal.Response
import kotlinx.coroutines.Deferred
val User.mention: String get() = "<a href=\"tg://user?id=$id\">@$firstName</a>"
suspend fun <T> Action<T>.send(e: Event) {
send(e.chatId, e.bot)
}
suspend inline fun <reified ReturnType> Action<ReturnType>.sendAsync(
e: Event
): Deferred<Response<out ReturnType>> =
sendAsync(e.chatId, e.bot)
| 0
|
Kotlin
|
0
| 1
|
883b3280205fa639ae7f7992e4180bd5bb837b8b
| 594
|
PekoTelegramBot
|
MIT License
|
src/jsMain/kotlin/main/ConfigPopup.kt
|
elizarov
| 337,522,862
| false
| null |
package polyhedra.js.main
import polyhedra.common.util.*
import polyhedra.js.components.*
import polyhedra.js.params.*
import react.*
import react.dom.*
fun RBuilder.configPopup(params: RootParams) {
child(ConfigPopup::class) {
attrs {
this.params = params
}
}
}
@Suppress("NON_EXPORTABLE_TYPE")
@JsExport
class ConfigPopup(props: PComponentProps<RootParams>) : RComponent<PComponentProps<RootParams>, RState>(props) {
private inner class Context(params: RootParams) : Param.Context(params, Param.TargetValue) {
val hasFaces by { params.render.view.display.value.hasFaces() }
val animateUpdates by { params.animationParams.animateValueUpdates.value }
val rotate by { params.animationParams.animatedRotation.value }
val scale by { params.export.size.targetValue / 2 }
val faceWidth by { params.render.view.faceWidth.targetValue }
val faceRim by { params.render.view.faceRim.targetValue }
init { setup() }
override fun update() {
forceUpdate()
}
}
private val ctx = Context(props.params)
override fun componentWillUnmount() {
ctx.destroy()
}
override fun RBuilder.render() {
groupHeader("View")
tableBody {
controlRow("Base scale") { pDropdown(props.params.render.poly.baseScale) }
controlRow("View scale") { pSlider(props.params.render.view.scale) }
controlRow("Expand") { pSlider(props.params.render.view.expandFaces) }
controlRow("Display") { pDropdown(props.params.render.view.display) }
}
groupHeader("Faces")
tableBody {
controlRow("Transparent") { pSlider(props.params.render.view.transparentFaces, !ctx.hasFaces) }
controlRow("Width") {
pSlider(props.params.render.view.faceWidth, !ctx.hasFaces, showValue = false)
span { +"${(ctx.scale * ctx.faceWidth).fmt(1)} (mm)" }
}
controlRow("Rim") {
pSlider(props.params.render.view.faceRim, !ctx.hasFaces, showValue = false)
span { +"${(ctx.scale * ctx.faceRim).fmt(1)} (mm)" }
}
}
groupHeader("Animation")
tableBody {
controlRow2("Rotation", { pCheckbox(props.params.animationParams.animatedRotation) }) {
pSlider(props.params.animationParams.rotationSpeed, !ctx.rotate)
}
controlRow2("Angle", {}, {
pSlider(props.params.animationParams.rotationAngle, !ctx.rotate)
})
controlRow2("Updates", { pCheckbox(props.params.animationParams.animateValueUpdates) }) {
pSlider(props.params.animationParams.animationDuration, !ctx.animateUpdates)
}
}
groupHeader("Lighting")
tableBody {
controlRow("Ambient") { pSlider(props.params.render.lighting.ambientLight, !ctx.hasFaces) }
controlRow("Diffuse") { pSlider(props.params.render.lighting.diffuseLight, !ctx.hasFaces) }
controlRow("Specular") { pSlider(props.params.render.lighting.specularLight, !ctx.hasFaces) }
controlRow("Shininess") { pSlider(props.params.render.lighting.specularPower, !ctx.hasFaces) }
}
}
}
| 0
|
Kotlin
|
0
| 28
|
ac15c7fe326e472470562a42f9fd519b24dfb455
| 3,308
|
PolyhedraExplorer
|
Apache License 2.0
|
components/src/commonMain/kotlin/com/paligot/movies/components/Rating.kt
|
GerardPaligot
| 312,828,696
| false
| null |
package com.paligot.movies.components
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.BoxWithConstraints
import androidx.compose.foundation.layout.aspectRatio
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.wrapContentSize
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.material.MaterialTheme
import androidx.compose.material.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.draw.drawBehind
import androidx.compose.ui.geometry.Offset
import androidx.compose.ui.geometry.Size
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.StrokeCap
import androidx.compose.ui.graphics.drawscope.Stroke
import androidx.compose.ui.unit.sp
import com.paligot.movies.theming.green900
import com.paligot.movies.theming.greenDark
import com.paligot.movies.theming.orange900
import com.paligot.movies.theming.red900
@Composable
fun Rating(
percentage: Int,
modifier: Modifier = Modifier
) {
val color = if (percentage >= 70) green900 else if (percentage >= 30) orange900 else red900
BoxWithConstraints(
modifier = modifier
.fillMaxWidth()
.aspectRatio(1f)
.clip(CircleShape)
.background(color = greenDark, shape = CircleShape)
.drawBehind {
val largestSize = if (size.width > size.height) size.height else size.width
val strokeWidth = 0.05f * largestSize
val padding = 0.07f * largestSize
val sweepAngle = (percentage / 100f) * 360f
val topLeft = Offset(x = padding, y = padding)
val topLeftSize = Size(size.width - (padding * 2), size.height - (padding * 2))
drawArc(
color = color.copy(alpha = 0.3f),
startAngle = -90f,
sweepAngle = 360f,
topLeft = topLeft,
size = topLeftSize,
useCenter = false,
style = Stroke(strokeWidth),
)
drawArc(
color = color,
startAngle = -90f,
sweepAngle = sweepAngle,
useCenter = false,
style = Stroke(strokeWidth, cap = StrokeCap.Round),
topLeft = topLeft,
size = topLeftSize
)
}
.wrapContentSize(align = Alignment.Center),
content = {
val largestSize = if (maxWidth > maxHeight) maxHeight else maxWidth
val fontSize = 0.34f * largestSize.value
Text(
text = "$percentage",
style = MaterialTheme.typography.button.copy(fontSize = fontSize.sp),
color = Color.White
)
}
)
}
| 0
|
Kotlin
|
0
| 47
|
0ad52c9df8646f78a3496a6916aeb5d254079b87
| 2,698
|
discovering-movies
|
Apache License 2.0
|
data/base/src/main/java/io/edugma/data/base/repository/PathRepositoryImpl.kt
|
Edugma
| 474,423,768
| false
| null |
package io.edugma.data.base.repository
import android.content.Context
import io.edugma.domain.base.repository.PathRepository
class PathRepositoryImpl(
private val appContext: Context,
) : PathRepository {
override fun getDatastorePath(dataStoreFileName: String): String {
return appContext.filesDir.resolve(dataStoreFileName).absolutePath
}
override fun getImageCachePath(): String {
return appContext.cacheDir.resolve("images").absolutePath
}
override fun getIconCachePath(): String {
return appContext.cacheDir.resolve("icons").absolutePath
}
// //iOS
// actual fun ComponentRegistryBuilder.setupDefaultComponents() = this.setupDefaultComponents()
// actual fun getImageCacheDirectoryPath(): Path {
// val cacheDir = NSSearchPathForDirectoriesInDomains(
// NSCachesDirectory,
// NSUserDomainMask,
// true
// ).first() as String
// return (cacheDir + "/media").toPath()
// }
}
| 1
|
Kotlin
|
0
| 2
|
d67e8c33ec49f2f99511bb6612a07486b4b4bd49
| 965
|
app
|
MIT License
|
line-awesome/src/commonMain/kotlin/compose/icons/lineawesomeicons/Envelope.kt
|
DevSrSouza
| 311,134,756
| false
| null |
package compose.icons.lineawesomeicons
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.PathFillType.Companion.NonZero
import androidx.compose.ui.graphics.SolidColor
import androidx.compose.ui.graphics.StrokeCap.Companion.Butt
import androidx.compose.ui.graphics.StrokeJoin.Companion.Miter
import androidx.compose.ui.graphics.vector.ImageVector
import androidx.compose.ui.graphics.vector.ImageVector.Builder
import androidx.compose.ui.graphics.vector.path
import androidx.compose.ui.unit.dp
import compose.icons.LineAwesomeIcons
public val LineAwesomeIcons.Envelope: ImageVector
get() {
if (_envelope != null) {
return _envelope!!
}
_envelope = Builder(name = "Envelope", defaultWidth = 32.0.dp, defaultHeight = 32.0.dp,
viewportWidth = 32.0f, viewportHeight = 32.0f).apply {
path(fill = SolidColor(Color(0xFF000000)), stroke = null, strokeLineWidth = 0.0f,
strokeLineCap = Butt, strokeLineJoin = Miter, strokeLineMiter = 4.0f,
pathFillType = NonZero) {
moveTo(3.0f, 8.0f)
lineTo(3.0f, 26.0f)
lineTo(29.0f, 26.0f)
lineTo(29.0f, 8.0f)
close()
moveTo(7.3125f, 10.0f)
lineTo(24.6875f, 10.0f)
lineTo(16.0f, 15.7813f)
close()
moveTo(5.0f, 10.875f)
lineTo(15.4375f, 17.8438f)
lineTo(16.0f, 18.1875f)
lineTo(16.5625f, 17.8438f)
lineTo(27.0f, 10.875f)
lineTo(27.0f, 24.0f)
lineTo(5.0f, 24.0f)
close()
}
}
.build()
return _envelope!!
}
private var _envelope: ImageVector? = null
| 17
| null |
25
| 571
|
a660e5f3033e3222e3553f5a6e888b7054aed8cd
| 1,822
|
compose-icons
|
MIT License
|
browser-kotlin/src/jsMain/kotlin/web/events/EventType.kt
|
karakum-team
| 393,199,102
| false
| null |
// Automatically generated - do not modify!
@file:Suppress(
"NOTHING_TO_INLINE",
)
package web.events
sealed external interface EventType<out T : Event>
inline fun <T : Event> EventType(
value: String,
): EventType<T> =
value.unsafeCast<EventType<T>>()
| 0
| null |
6
| 28
|
2e94b60c9e3838c464ab9da211ca44de54e74133
| 269
|
types-kotlin
|
Apache License 2.0
|
app/src/main/java/com/kaelesty/cryptocurrencies_observer/CoinPricesAdapter.kt
|
Kaelesty
| 668,404,861
| false
| null |
package com.kaelesty.cryptocurrencies_observer
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.TextView
import androidx.recyclerview.widget.RecyclerView.Adapter
import androidx.recyclerview.widget.RecyclerView.ViewHolder
import com.bumptech.glide.Glide
import com.kaelesty.cryptocurrencies_observer.databinding.CoinPriceBinding
class CoinPricesAdapter: Adapter<CoinPricesAdapter.CoinPriceViewHolder>() {
var coinPrices: ArrayList<Coin> = ArrayList()
set(value) {
field = value
notifyDataSetChanged()
}
var onClickListener: ((coinItem: Coin) -> Unit)? = null
var onReachEndListener: (() -> Unit)? = null
inner class CoinPriceViewHolder(val binding: CoinPriceBinding) :
ViewHolder(binding.root) {
var textViewCoinName: TextView = binding.textViewCoinName
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): CoinPriceViewHolder {
return CoinPriceViewHolder(CoinPriceBinding.inflate(
LayoutInflater.from(parent.context),
parent,
false
))
}
override fun getItemCount(): Int {
return coinPrices.size
}
override fun onBindViewHolder(holder: CoinPriceViewHolder, position: Int) {
val coin = coinPrices[position]
holder.binding.textViewCoinPrice.text = coin.display?.usd?.price
with(holder.binding) {
textViewCoinName.text = "${coin.coinInfo?.name} / USD"
textViewCoinPrice.text = coin.display?.usd?.price
textViewLastUpdate.text = coin.display?.usd?.lastUpdate
Glide.with(holder.itemView)
.load("https://cryptocompare.com${coin.coinInfo?.imageUrl}")
.into(imageViewCoinLogo)
}
holder.itemView.setOnClickListener {
onClickListener?.let {
it(coin)
}
}
if (position == coinPrices.size - 2) {
onReachEndListener?.let {
it()
}
}
}
}
| 0
|
Kotlin
|
0
| 0
|
6d578f05f9a6ba34fced9e587ef421798e79710e
| 2,149
|
study-android-cryptocurrencies_observer
|
The Unlicense
|
src/test/kotlin/no/nav/reka/river/examples/example_5_capture_fail_from_listener/services/FormatDokumentService.kt
|
alpet
| 657,993,647
| false
|
{"Kotlin": 227850}
|
package no.nav.reka.river.examples.example_5_capture_fail_from_listener.services
import no.nav.helse.rapids_rivers.RapidsConnection
import no.nav.helse.rapids_rivers.River
import no.nav.helse.rapids_rivers.isMissingOrNull
import no.nav.reka.river.basic.Løser
import no.nav.reka.river.Key
import no.nav.reka.river.MessageType
import no.nav.reka.river.demandValue
import no.nav.reka.river.examples.example_1_basic_løser.BehovName
import no.nav.reka.river.examples.example_1_basic_løser.DataFelt
import no.nav.reka.river.examples.example_1_basic_løser.EventName
import no.nav.reka.river.interestedIn
import no.nav.reka.river.model.Behov
import no.nav.reka.river.publish
class FormatDokumentService(rapidsConnection: RapidsConnection) : Løser(rapidsConnection) {
override val event: MessageType.Event = EventName.DOCUMENT_RECIEVED
override fun accept(): River.PacketValidation = River.PacketValidation {
it.demandValue(Key.BEHOV,BehovName.FORMAT_DOCUMENT)
it.interestedIn(DataFelt.RAW_DOCUMENT)
it.interestedIn(DataFelt.RAW_DOCUMENT_FORMAT)
}
private fun formatDocument(rawDocument:String) {
println("Document is now formated $rawDocument")
}
override fun onBehov(packet: Behov) {
formatDocument(packet[DataFelt.RAW_DOCUMENT].asText())
val documentFormat = packet[DataFelt.RAW_DOCUMENT_FORMAT].takeUnless { it.isMissingOrNull() }?.asText()
if (documentFormat != "ebcdic") {
rapidsConnection.publish(
packet.createBehov(
BehovName.PERSIST_DOCUMENT,
mapOf(DataFelt.FORMATED_DOCUMENT to "This is my formated document")
)
)
}
else {
rapidsConnection.publish(packet.createFail("Unable to process files with EBCDIC charset"))
}
}
}
| 0
|
Kotlin
|
0
| 0
|
10b272d9b0b96fac21aaba4cb7c9a18dd9f497ba
| 1,844
|
reka
|
MIT License
|
app/src/main/java/com/awscherb/cardkeeper/data/model/ScannedCodeModel.kt
|
LateNightProductions
| 66,697,395
| false
| null |
package com.awscherb.cardkeeper.data.model
import com.google.zxing.BarcodeFormat
interface ScannedCodeModel : SavedItem {
val id: Int
val format: BarcodeFormat
val text: String
val title: String
}
| 1
|
Kotlin
|
19
| 101
|
3c47475b0698dcb3b97bd4bb3b2e897238e213b2
| 215
|
CardKeeper
|
Apache License 2.0
|
core/network/src/main/java/dev/sijanrijal/popularmovies/core/network/services/search/Search.kt
|
sijanr
| 263,267,988
| false
|
{"Kotlin": 87745}
|
package dev.sijanrijal.popularmovies.core.network.services.search
import com.google.gson.annotations.SerializedName
data class MovieSearchNetworkModel(
@SerializedName("page") val pageNumber: Int,
@SerializedName("results") val searchResults: List<MovieSearchNetwork>
)
data class MovieSearchNetwork(
@SerializedName("poster_path") val posterPath: String?,
val overview: String,
@SerializedName("release_date") val releaseDate: String,
@SerializedName("id") val movieID: Int,
@SerializedName("title") val movieTitle: String,
@SerializedName("vote_average") val rating: Float,
)
| 4
|
Kotlin
|
0
| 0
|
85da1e7726ecef24868626b65025d1c9628e47a3
| 612
|
popular-movies
|
Apache License 2.0
|
app/src/main/java/com/muedsa/tvbox/demoplugin/service/MainScreenService.kt
|
muedsa
| 872,828,287
| false
|
{"Kotlin": 17815}
|
package com.muedsa.tvbox.demoplugin.service
import com.muedsa.tvbox.api.data.MediaCard
import com.muedsa.tvbox.api.data.MediaCardRow
import com.muedsa.tvbox.api.service.IMainScreenService
class MainScreenService(
private val danDanPlayApiService: DanDanPlayApiService
) : IMainScreenService {
private var rowSize: Int = 30
override suspend fun getRowsData(): List<MediaCardRow> {
val resp = danDanPlayApiService.bangumiShin()
if (resp.errorCode != 0) {
throw RuntimeException(resp.errorMessage)
}
if (resp.bangumiList.isEmpty())
return emptyList()
val rows = splitListBySize(resp.bangumiList, rowSize)
return rows.mapIndexed { index, row ->
MediaCardRow(
title = "新番列表 ${index + 1}",
cardWidth = 210 / 2,
cardHeight = 302 / 2,
list = row.map {
MediaCard(
id = it.animeId.toString(),
title = it.animeTitle,
detailUrl = it.animeId.toString(),
coverImageUrl = it.imageUrl
)
}
)
}
}
private fun <T> splitListBySize(inputList: List<T>, size: Int): List<List<T>> {
val result = mutableListOf<List<T>>()
var index = 0
while (index < inputList.size) {
result.add(inputList.subList(index, (index + size).coerceAtMost(inputList.size)))
index += size
}
return result
}
}
| 0
|
Kotlin
|
0
| 0
|
4e5f5fd827989154b7687031f75c2937ac88e579
| 1,572
|
TvBoxDemoPlugin
|
MIT License
|
chapter06/microservice/src/main/kotlin/com/microservices/chapter06/microservice/GreetingsController.kt
|
gomahera-mymoota
| 851,482,914
| false
|
{"Kotlin": 23374, "HTML": 193}
|
package com.microservices.chapter06.microservice
import org.springframework.beans.factory.annotation.Value
import org.springframework.web.bind.annotation.GetMapping
import org.springframework.web.bind.annotation.RestController
@RestController
class GreetingsController {
@Value("\${microservice.example.greetings}")
private lateinit var greetings: String
@GetMapping("/greetings")
fun greetings() = greetings
}
| 0
|
Kotlin
|
0
| 0
|
e1d61889787dc9b2bbb151fff140e85b02ac9207
| 432
|
hands-on-microservices-with-kotlin
|
Apache License 2.0
|
src/main/kotlin/com/petukhovsky/snake/prot/ServerMessage.kt
|
arthur-snake
| 114,157,008
| false
| null |
package com.petukhovsky.snake.prot
import com.fasterxml.jackson.annotation.JsonInclude
import com.fasterxml.jackson.annotation.JsonSubTypes
import com.fasterxml.jackson.annotation.JsonTypeInfo
@JsonTypeInfo(use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.PROPERTY, property = "act")
@JsonSubTypes(
JsonSubTypes.Type(value = UpdMessage::class, name = "upd"),
JsonSubTypes.Type(value = InitMessage::class, name = "init")
)
open class ServerMessage
open class UpdMessage(
@JsonInclude(JsonInclude.Include.NON_EMPTY) val a : String,
@JsonInclude(JsonInclude.Include.NON_EMPTY) val u : Array<IdInfo>,
@JsonInclude(JsonInclude.Include.NON_EMPTY) val c : Array<ChatUpdate> = arrayOf()
) : ServerMessage()
@JsonInclude(JsonInclude.Include.NON_NULL)
data class IdInfo(
val id: String,
val type: String,
val color: String,
val nick: String? = null
)
class InitMessage(
a: String,
u: Array<IdInfo>,
val rows: Int,
val columns: Int
) : UpdMessage(a, u)
data class ChatUpdate(
val id: String,
val msg: String
)
| 4
|
Kotlin
|
0
| 3
|
e24da15441f6b6c673d1f1128ced494f4ed3d313
| 1,129
|
server
|
MIT License
|
rounded/src/commonMain/kotlin/me/localx/icons/rounded/bold/SortCircleDown.kt
|
localhostov
| 808,861,591
| false
|
{"Kotlin": 79430321, "HTML": 331, "CSS": 102}
|
package me.localx.icons.rounded.bold
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.PathFillType.Companion.NonZero
import androidx.compose.ui.graphics.SolidColor
import androidx.compose.ui.graphics.StrokeCap.Companion.Butt
import androidx.compose.ui.graphics.StrokeJoin.Companion.Miter
import androidx.compose.ui.graphics.vector.ImageVector
import androidx.compose.ui.graphics.vector.ImageVector.Builder
import androidx.compose.ui.graphics.vector.path
import androidx.compose.ui.unit.dp
import me.localx.icons.rounded.Icons
public val Icons.Bold.SortCircleDown: ImageVector
get() {
if (_sortCircleDown != null) {
return _sortCircleDown!!
}
_sortCircleDown = Builder(name = "SortCircleDown", defaultWidth = 24.0.dp, defaultHeight =
24.0.dp, viewportWidth = 24.0f, viewportHeight = 24.0f).apply {
path(fill = SolidColor(Color(0xFF000000)), stroke = null, strokeLineWidth = 0.0f,
strokeLineCap = Butt, strokeLineJoin = Miter, strokeLineMiter = 4.0f,
pathFillType = NonZero) {
moveToRelative(12.0f, 0.0f)
curveTo(5.383f, 0.0f, 0.0f, 5.383f, 0.0f, 12.0f)
reflectiveCurveToRelative(5.383f, 12.0f, 12.0f, 12.0f)
reflectiveCurveToRelative(12.0f, -5.383f, 12.0f, -12.0f)
reflectiveCurveTo(18.617f, 0.0f, 12.0f, 0.0f)
close()
moveTo(12.0f, 21.0f)
curveToRelative(-4.963f, 0.0f, -9.0f, -4.037f, -9.0f, -9.0f)
reflectiveCurveTo(7.037f, 3.0f, 12.0f, 3.0f)
reflectiveCurveToRelative(9.0f, 4.037f, 9.0f, 9.0f)
reflectiveCurveToRelative(-4.037f, 9.0f, -9.0f, 9.0f)
close()
moveTo(16.529f, 8.409f)
curveToRelative(0.603f, 0.568f, 0.63f, 1.518f, 0.062f, 2.12f)
curveToRelative(-0.295f, 0.312f, -0.692f, 0.471f, -1.091f, 0.471f)
curveToRelative(-0.369f, 0.0f, -0.739f, -0.136f, -1.029f, -0.409f)
lineToRelative(-2.471f, -2.331f)
lineToRelative(-2.471f, 2.331f)
curveToRelative(-0.603f, 0.569f, -1.552f, 0.541f, -2.12f, -0.062f)
reflectiveCurveToRelative(-0.541f, -1.552f, 0.062f, -2.12f)
lineToRelative(2.928f, -2.763f)
curveToRelative(0.811f, -0.812f, 2.361f, -0.843f, 3.234f, 0.03f)
lineToRelative(2.896f, 2.732f)
close()
moveTo(16.893f, 13.946f)
curveToRelative(0.228f, 0.571f, 0.083f, 1.223f, -0.364f, 1.645f)
lineToRelative(-2.928f, 2.763f)
curveToRelative(-0.405f, 0.406f, -0.985f, 0.646f, -1.602f, 0.646f)
reflectiveCurveToRelative(-1.196f, -0.24f, -1.633f, -0.677f)
lineToRelative(-2.896f, -2.732f)
curveToRelative(-0.447f, -0.422f, -0.592f, -1.073f, -0.364f, -1.645f)
curveToRelative(0.227f, -0.571f, 0.779f, -0.946f, 1.394f, -0.946f)
horizontalLineToRelative(7.0f)
curveToRelative(0.614f, 0.0f, 1.167f, 0.375f, 1.394f, 0.946f)
close()
}
}
.build()
return _sortCircleDown!!
}
private var _sortCircleDown: ImageVector? = null
| 1
|
Kotlin
|
0
| 5
|
cbd8b510fca0e5e40e95498834f23ec73cc8f245
| 3,357
|
icons
|
MIT License
|
src/main/kotlin/com/github/pawelkowalski92/aoc/day05/Runner.kt
|
pawelkowalski92
| 726,175,728
| false
|
{"Kotlin": 77190}
|
package com.github.pawelkowalski92.aoc.day05
import com.github.pawelkowalski92.aoc.day05.garden.AlmanacParser
import com.github.pawelkowalski92.aoc.day05.garden.seed.BasicSeedParser
import com.github.pawelkowalski92.aoc.day05.garden.seed.RangeSeedParser
import com.github.pawelkowalski92.aoc.util.getResource
class Runner {
object Part1 {
@JvmStatic
fun main(vararg args: String) {
val almanacParser = AlmanacParser()
val seedParser = BasicSeedParser()
val result = getResource("inputs/day-5.txt").readLines()
.let {
val seedLocationFinder = almanacParser.parseAlmanach(it).let(::SeedLocationFinder)
seedParser.parseSeeds(it).let(seedLocationFinder::findLowestSeedLocation)
}
println(result)
}
}
object Part2 {
@JvmStatic
fun main(vararg args: String) {
val almanacParser = AlmanacParser()
val seedParser = RangeSeedParser()
val result = getResource("inputs/day-5.txt").readLines()
.let {
val seedLocationFinder = almanacParser.parseAlmanach(it).let(::SeedLocationFinder)
seedParser.parseSeeds(it).let(seedLocationFinder::findLowestSeedLocation)
}
println(result)
}
}
}
| 0
|
Kotlin
|
0
| 0
|
96879809e9175073ac1d19a93db8d76d90686500
| 1,383
|
advent-of-code-2023
|
Apache License 2.0
|
library/src/test/kotlin/ru/kontur/kinfra/kfixture/data/objects/random1/Inside.kt
|
skbkontur
| 212,616,062
| false
| null |
package ru.kontur.kinfra.kfixture.data.objects.random1
data class Inside(
val able: Boolean,
val accurate: Double,
val act: Boolean,
val affect: Boolean,
val after: Boolean,
val age: String,
val alone: Int,
val already: Int,
val around: Boolean,
val article: Boolean,
val away: String,
val bark: Boolean,
val barn: Boolean,
val bell: Boolean,
val bent: Int,
val between: Double,
val beyond: Boolean,
val biggest: Boolean,
val birth: Double,
val built: Boolean,
val cage: String,
val cannot: Double,
val castle: String,
val century: Boolean,
val chief: Chief,
val child: String,
val citizen: Boolean,
val clock: Double,
val cloud: Boolean,
val coat: String,
val colony: Boolean,
val company: String,
val corner: Double,
val count: Double,
val couple: Double,
val court: String,
val cry: String,
val dance: String,
val dark: String,
val dead: Double,
val death: Boolean,
val declared: Boolean,
val design: String,
val difficulty: Boolean,
val disease: Int,
val does: Boolean,
val driven: String,
val drove: Boolean,
val dull: Boolean,
val ear: Boolean,
val earth: Boolean,
val east: Double,
val education: Boolean,
val either: Boolean,
val engineer: Boolean,
val equator: String,
val express: Int,
val face: Boolean,
val farther: String,
val feathers: Int,
val fifteen: String,
val fix: Boolean,
val flew: Int,
val floating: String,
val force: Int,
val former: Boolean,
val fresh: Double,
val frighten: Boolean,
val from: Boolean,
val fuel: String,
val gas: Boolean,
val gentle: Int,
val group: Int,
val guess: String,
val handle: Boolean,
val heat: Boolean,
val hit: String,
val hurry: Boolean,
val indeed: String,
val influence: String,
val instrument: Boolean,
val joy: String,
val just: String,
val knife: String,
val language: Int,
val laugh: Boolean,
val left: Boolean,
val machinery: Boolean,
val made: String,
val managed: String,
val map: Boolean,
val market: Boolean,
val mean: String,
val mental: Boolean,
val molecular: Boolean,
val more: Double,
val musical: Boolean,
val nearly: String,
val nine: String,
val nodded: Boolean,
val off: Boolean,
val on: String,
val or: Double,
val orange: String,
val ordinary: String,
val organization: Boolean,
val own: Boolean,
val past: Boolean,
val picture: String,
val pictured: Double,
val pitch: Boolean,
val plan: String,
val poem: Boolean,
val post: Boolean,
val power: String,
val powerful: Boolean,
val previous: String,
val prize: Double,
val produce: Boolean,
val prove: Boolean,
val push: Boolean,
val queen: Boolean,
val quickly: Int,
val rabbit: Int,
val raw: Double,
val receive: Boolean,
val regular: Double,
val rod: String,
val roll: Int,
val route: String,
val safe: Boolean,
val said: Boolean,
val sang: Int,
val saw: Int,
val science: Int,
val search: String,
val sent: Boolean,
val service: String,
val shallow: Boolean,
val shells: Boolean,
val short: Int,
val shot: Double,
val should: String,
val similar: String,
val simple: String,
val single: String,
val sky: String,
val slabs: String,
val smile: Double,
val smoke: Int,
val soap: Double,
val special: Int,
val speed: Boolean,
val split: Boolean,
val spoken: String,
val sport: Double,
val spring: Double,
val stairs: String,
val star: Double,
val state: Double,
val student: String,
val sunlight: String,
val swim: Int,
val taught: String,
val team: String,
val tent: Int,
val than: Boolean,
val themselves: Boolean,
val then: Boolean,
val though: String,
val tonight: String,
val took: Double,
val trick: Double,
val unit: String,
val useful: Double,
val variety: String,
val vegetable: Boolean,
val victory: Boolean,
val wagon: String,
val wealth: String,
val weigh: Boolean,
val `where`: Int,
val `while`: Boolean,
val whole: Boolean,
val will: Double,
val win: Double,
val wing: String,
val wooden: Boolean,
val worry: String,
val younger: Int
)
| 7
|
Kotlin
|
1
| 1
|
e1845e8c9737c66b63cfa49925ad3bb9c589fbd1
| 4,537
|
KFixture
|
MIT License
|
networking/src/main/java/io/iamjosephmj/networking/service/base/RetrofitService.kt
|
iamjosephmj
| 347,596,083
| false
| null |
/*
* MIT License
*
* Copyright (c) 2021 <NAME>
*
* 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 io.iamjosephmj.networking.service.base
import android.content.Context
import io.iamjosephmj.networking.R
import io.reactivex.schedulers.Schedulers
import okhttp3.OkHttpClient
import okhttp3.logging.HttpLoggingInterceptor
import retrofit2.Retrofit
import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory
import retrofit2.converter.moshi.MoshiConverterFactory
import java.util.concurrent.TimeUnit
/**
* Base Service class for retrofit.
*
* @author <NAME>
*/
class RetrofitService {
private lateinit var retrofit: Retrofit
/**
* Initialize{@link Moshi}and{@link Retrofit}
*/
fun init(context: Context?): RetrofitService {
val httpClientBuilder = OkHttpClient.Builder()
.connectTimeout(30, TimeUnit.SECONDS) // Modify as necessary
// log
val httpLoggingInterceptor = HttpLoggingInterceptor()
val logInterceptor =
httpLoggingInterceptor.apply {
httpLoggingInterceptor.level = HttpLoggingInterceptor.Level.BODY
}
if (!httpClientBuilder.interceptors().contains(logInterceptor)) {
httpClientBuilder.addInterceptor(logInterceptor)
}
retrofit = Retrofit.Builder()
.baseUrl(context?.getString(R.string.base_url) ?: "") // Modify as necessary
.addConverterFactory(MoshiConverterFactory.create())
.addCallAdapterFactory(RxJava2CallAdapterFactory.createWithScheduler(Schedulers.io()))
.client(httpClientBuilder.build())
.build()
return this
}
/**
* This is a generic method for service creation.
*/
fun <T> createService(serviceClass: Class<T>): T = retrofit.create(serviceClass)
}
| 0
|
Kotlin
|
0
| 2
|
c98b95542857eab6ecc0deb47382c70ef82c756d
| 2,830
|
Rx-Clean
|
MIT License
|
proto-router/src/main/kotlin/actor/proto/router/GroupRouterConfig.kt
|
asynkron
| 96,669,281
| false
| null |
package actor.proto.router
import actor.proto.Context
import actor.proto.PID
abstract class GroupRouterConfig(private var routees: Set<PID>) : RouterConfig() {
override fun onStarted(context: Context, router: RouterState) = router.setRoutees(routees)
}
| 8
|
Kotlin
|
21
| 211
|
5d42177ff79969000b64a150ac4433dee3209b45
| 260
|
protoactor-kotlin
|
Apache License 2.0
|
recyclerviewscreen/src/main/java/com/example/road/to/effective/snapshot/testing/recyclerviewscreen/dataproviders/memorise/MemoriseProvider.kt
|
sergio-sastre
| 394,010,429
| false
| null |
package com.example.road.to.effective.snapshot.testing.recyclerviewscreen.dataproviders.memorise
import com.example.road.to.effective.snapshot.testing.recyclerviewscreen.data.Memorise
interface MemoriseProvider {
fun getMemorises(): List<com.example.road.to.effective.snapshot.testing.recyclerviewscreen.data.Memorise>
}
| 3
|
Kotlin
|
11
| 145
|
56055666226fb1c3ddd8aff7f98c7979ff1aa839
| 326
|
Android-screenshot-testing-playground
|
MIT License
|
remix/src/commonMain/kotlin/com/woowla/compose/icon/collections/remix/remix/business/PieChartLine.kt
|
walter-juan
| 868,046,028
| false
|
{"Kotlin": 34345428}
|
package com.woowla.compose.icon.collections.remix.remix.business
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.PathFillType.Companion.NonZero
import androidx.compose.ui.graphics.SolidColor
import androidx.compose.ui.graphics.StrokeCap.Companion.Butt
import androidx.compose.ui.graphics.StrokeJoin.Companion.Miter
import androidx.compose.ui.graphics.vector.ImageVector
import androidx.compose.ui.graphics.vector.ImageVector.Builder
import androidx.compose.ui.graphics.vector.path
import androidx.compose.ui.unit.dp
import com.woowla.compose.icon.collections.remix.remix.BusinessGroup
public val BusinessGroup.PieChartLine: ImageVector
get() {
if (_pieChartLine != null) {
return _pieChartLine!!
}
_pieChartLine = Builder(name = "PieChartLine", defaultWidth = 24.0.dp, defaultHeight =
24.0.dp, viewportWidth = 24.0f, viewportHeight = 24.0f).apply {
path(fill = SolidColor(Color(0xFF000000)), stroke = null, strokeLineWidth = 0.0f,
strokeLineCap = Butt, strokeLineJoin = Miter, strokeLineMiter = 4.0f,
pathFillType = NonZero) {
moveTo(9.0f, 2.458f)
verticalLineTo(4.582f)
curveTo(6.068f, 5.768f, 4.0f, 8.643f, 4.0f, 12.0f)
curveTo(4.0f, 16.418f, 7.582f, 20.0f, 12.0f, 20.0f)
curveTo(15.357f, 20.0f, 18.232f, 17.932f, 19.419f, 15.0f)
horizontalLineTo(21.542f)
curveTo(20.268f, 19.057f, 16.478f, 22.0f, 12.0f, 22.0f)
curveTo(6.477f, 22.0f, 2.0f, 17.523f, 2.0f, 12.0f)
curveTo(2.0f, 7.522f, 4.943f, 3.732f, 9.0f, 2.458f)
close()
moveTo(12.0f, 2.0f)
curveTo(17.523f, 2.0f, 22.0f, 6.477f, 22.0f, 12.0f)
curveTo(22.0f, 12.337f, 21.983f, 12.671f, 21.951f, 13.0f)
horizontalLineTo(11.0f)
verticalLineTo(2.049f)
curveTo(11.329f, 2.017f, 11.663f, 2.0f, 12.0f, 2.0f)
close()
moveTo(13.0f, 4.062f)
verticalLineTo(11.0f)
horizontalLineTo(19.938f)
curveTo(19.487f, 7.381f, 16.619f, 4.513f, 13.0f, 4.062f)
close()
}
}
.build()
return _pieChartLine!!
}
private var _pieChartLine: ImageVector? = null
| 0
|
Kotlin
|
0
| 3
|
eca6c73337093fbbfbb88546a88d4546482cfffc
| 2,416
|
compose-icon-collections
|
MIT License
|
app/src/main/java/com/example/stunthink/data/remote/dto/login/LoginDto.kt
|
MFachriA
| 646,533,160
| false
| null |
package com.example.stunthink.data.remote.dto.login
data class LoginDto (
val token: String
)
| 0
|
Kotlin
|
0
| 1
|
f50be971748dac420777604e226751933f505756
| 99
|
StunThink
|
Freetype Project License
|
privacy-config/privacy-config/src/main/java/com/duckduckgo/privacy/config/store/PrivacyConfigDatabaseModels.kt
|
hojat72elect
| 558,362,610
| false
| null |
/*
* Copyright (c) 2022 DuckDuckGo
*
* 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.duckduckgo.privacy.config.store
import androidx.room.Entity
import androidx.room.PrimaryKey
import androidx.room.TypeConverter
import com.squareup.moshi.JsonAdapter
import com.squareup.moshi.Moshi
import com.squareup.moshi.Types
@Entity(tableName = "tracker_allowlist")
data class TrackerAllowlistEntity(
@PrimaryKey val domain: String,
val rules: List<AllowlistRuleEntity>
)
class AllowlistRuleEntity(
val rule: String,
val domains: List<String>,
val reason: String
)
class RuleTypeConverter {
@TypeConverter
fun toRules(value: String): List<AllowlistRuleEntity> {
return Adapters.ruleListAdapter.fromJson(value)!!
}
@TypeConverter
fun fromRules(value: List<AllowlistRuleEntity>): String {
return Adapters.ruleListAdapter.toJson(value)
}
}
@Entity(tableName = "drm_exceptions")
data class DrmExceptionEntity(
@PrimaryKey val domain: String,
val reason: String
)
fun DrmExceptionEntity.toDrmException(): com.duckduckgo.privacy.config.api.DrmException {
return com.duckduckgo.privacy.config.api.DrmException(
domain = this.domain,
reason = this.reason
)
}
@Entity(tableName = "unprotected_temporary")
data class UnprotectedTemporaryEntity(
@PrimaryKey val domain: String,
val reason: String
)
@Entity(tableName = "https_exceptions")
data class HttpsExceptionEntity(
@PrimaryKey val domain: String,
val reason: String
)
fun HttpsExceptionEntity.toHttpsException(): com.duckduckgo.privacy.config.api.HttpsException {
return com.duckduckgo.privacy.config.api.HttpsException(
domain = this.domain,
reason = this.reason
)
}
@Entity(tableName = "autofill_exceptions")
data class AutofillExceptionEntity(
@PrimaryKey val domain: String,
val reason: String
)
fun AutofillExceptionEntity.toAutofillException(): com.duckduckgo.privacy.config.api.AutofillException {
return com.duckduckgo.privacy.config.api.AutofillException(
domain = this.domain,
reason = this.reason
)
}
@Entity(tableName = "gpc_header_enabled_sites")
data class GpcHeaderEnabledSiteEntity(@PrimaryKey val domain: String)
fun GpcHeaderEnabledSiteEntity.toGpcHeaderEnabledSite(): com.duckduckgo.privacy.config.api.GpcHeaderEnabledSite {
return com.duckduckgo.privacy.config.api.GpcHeaderEnabledSite(domain = this.domain)
}
@Entity(tableName = "gpc_exceptions")
data class GpcExceptionEntity(@PrimaryKey val domain: String)
fun GpcExceptionEntity.toGpcException(): com.duckduckgo.privacy.config.api.GpcException {
return com.duckduckgo.privacy.config.api.GpcException(domain = this.domain)
}
@Entity(tableName = "gpc_content_scope_config")
data class GpcContentScopeConfigEntity(
@PrimaryKey val id: Int = 1,
val config: String
)
@Entity(tableName = "content_blocking_exceptions")
data class ContentBlockingExceptionEntity(
@PrimaryKey val domain: String,
val reason: String
)
fun ContentBlockingExceptionEntity.toContentBlockingException(): com.duckduckgo.privacy.config.api.ContentBlockingException {
return com.duckduckgo.privacy.config.api.ContentBlockingException(
domain = this.domain,
reason = this.reason
)
}
@Entity(tableName = "user_agent_exceptions")
data class UserAgentExceptionEntity(
@PrimaryKey val domain: String,
val reason: String,
val omitApplication: Boolean,
val omitVersion: Boolean
)
fun UserAgentExceptionEntity.toUserAgentException(): com.duckduckgo.privacy.config.api.UserAgentException {
return com.duckduckgo.privacy.config.api.UserAgentException(
domain = this.domain,
reason = this.reason
)
}
@Entity(tableName = "privacy_config")
data class PrivacyConfig(
@PrimaryKey val id: Int = 1,
val version: Long,
val readme: String
)
@Entity(tableName = "amp_link_formats")
data class AmpLinkFormatEntity(
@PrimaryKey val format: String
)
@Entity(tableName = "amp_keywords")
data class AmpKeywordEntity(
@PrimaryKey val keyword: String
)
@Entity(tableName = "amp_exceptions")
data class AmpLinkExceptionEntity(
@PrimaryKey val domain: String,
val reason: String
)
@Entity(tableName = "tracking_parameters")
data class TrackingParameterEntity(
@PrimaryKey val parameter: String
)
@Entity(tableName = "tracking_parameter_exceptions")
data class TrackingParameterExceptionEntity(
@PrimaryKey val domain: String,
val reason: String
)
fun AmpLinkExceptionEntity.toAmpLinkException(): com.duckduckgo.privacy.config.api.AmpLinkException {
return com.duckduckgo.privacy.config.api.AmpLinkException(
domain = this.domain,
reason = this.reason
)
}
fun TrackingParameterExceptionEntity.toTrackingParameterException(): com.duckduckgo.privacy.config.api.TrackingParameterException {
return com.duckduckgo.privacy.config.api.TrackingParameterException(
domain = this.domain,
reason = this.reason
)
}
fun UnprotectedTemporaryEntity.toUnprotectedTemporaryException(): com.duckduckgo.privacy.config.api.UnprotectedTemporaryException {
return com.duckduckgo.privacy.config.api.UnprotectedTemporaryException(
domain = this.domain,
reason = this.reason
)
}
class Adapters {
companion object {
private val moshi = Moshi.Builder().build()
private val ruleListType =
Types.newParameterizedType(List::class.java, AllowlistRuleEntity::class.java)
val ruleListAdapter: JsonAdapter<List<AllowlistRuleEntity>> = moshi.adapter(ruleListType)
}
}
| 0
|
Kotlin
|
0
| 0
|
ed9a0dcca1ffae0851cd1fab0cd3981a928d4d4f
| 6,146
|
SmartBrowser
|
Apache License 2.0
|
data/src/main/java/com/al/data/db/ExploreDatabase.kt
|
abdullahHanif
| 381,480,403
| false
| null |
package com.al.data.db
import androidx.room.Database
import androidx.room.RoomDatabase
import com.al.data.db.dao.ImageDao
import com.al.data.model.Image
@Database(entities = [Image::class], version = 1, exportSchema = false)
abstract class ExploreDatabase : RoomDatabase() {
abstract fun imageDao(): ImageDao
companion object {
val DATABASE_NAME: String = "explore_db"
}
}
| 0
|
Kotlin
|
0
| 1
|
0d0069d5cf524029f532b04e46fe5f01d4cc2ea7
| 396
|
Explore
|
Apache License 2.0
|
data/src/main/java/com/al/data/db/ExploreDatabase.kt
|
abdullahHanif
| 381,480,403
| false
| null |
package com.al.data.db
import androidx.room.Database
import androidx.room.RoomDatabase
import com.al.data.db.dao.ImageDao
import com.al.data.model.Image
@Database(entities = [Image::class], version = 1, exportSchema = false)
abstract class ExploreDatabase : RoomDatabase() {
abstract fun imageDao(): ImageDao
companion object {
val DATABASE_NAME: String = "explore_db"
}
}
| 0
|
Kotlin
|
0
| 1
|
0d0069d5cf524029f532b04e46fe5f01d4cc2ea7
| 396
|
Explore
|
Apache License 2.0
|
one.lfa.updater.main/src/main/java/au/org/libraryforall/updater/main/InventoryFailureListAdapter.kt
|
AULFA
| 189,855,520
| false
| null |
package au.org.libraryforall.updater.app
import android.content.Context
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.TextView
import androidx.recyclerview.widget.RecyclerView
import one.lfa.updater.inventory.api.InventoryTaskStep
class InventoryFailureListAdapter(
private val context: Context,
private val steps: List<InventoryTaskStep>)
: RecyclerView.Adapter<InventoryFailureListAdapter.ViewHolder>() {
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
val inflater =
LayoutInflater.from(parent.context)
val item =
inflater.inflate(R.layout.failure_item, parent, false)
return this.ViewHolder(item)
}
override fun getItemCount(): Int =
this.steps.size
override fun onBindViewHolder(holder: ViewHolder, position: Int) {
val step = this.steps[position]
if (step.failed) {
holder.icon.setImageResource(R.drawable.error_small)
} else {
holder.icon.setImageResource(R.drawable.ok_small)
}
holder.stepNumber.text = String.format("%d.", position + 1)
holder.description.text = step.description
holder.resolution.text = step.resolution
}
inner class ViewHolder(parent: View) : RecyclerView.ViewHolder(parent) {
val icon =
parent.findViewById<ImageView>(R.id.failureItemIcon)
val description =
parent.findViewById<TextView>(R.id.failureItemDescription)
val resolution =
parent.findViewById<TextView>(R.id.failureItemResolution)
val stepNumber =
parent.findViewById<TextView>(R.id.failureItemStepNumber)
}
}
| 2
| null |
1
| 1
|
5cde488e4e9f9e60f5737d9e1a8fc8817f6b22a8
| 1,666
|
updater
|
Apache License 2.0
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.