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/com/guoyi/listeninglove/data/FolderLoader.kt
GuoyiZhang
242,757,044
false
null
package com.cyl.musiclake.bean.data import android.content.Context import android.provider.MediaStore import com.cyl.musiclake.MusicApp import com.cyl.musiclake.bean.FolderInfo import com.cyl.musiclake.common.NavigationHelper import io.reactivex.Observable import java.io.File import java.util.* object FolderLoader { fun getFoldersWithSong(context: Context): Observable<List<FolderInfo>> { val folderInfos = ArrayList<FolderInfo>() val num_of_songs = "num_of_songs" val projection = arrayOf(MediaStore.Files.FileColumns.DATA, "count(" + MediaStore.Files.FileColumns.PARENT + ") as " + num_of_songs) val selection = ("duration>60000 AND is_music=1 AND title != '' " + " ) " + " group by ( " + MediaStore.Files.FileColumns.PARENT) return Observable.create { subscriber -> val cursor = context.contentResolver.query( MediaStore.Files.getContentUri("external"), projection, selection, null, null) if (cursor != null) { val index_data = cursor.getColumnIndex(MediaStore.Files.FileColumns.DATA) val index_num_of_songs = cursor.getColumnIndex(num_of_songs) while (cursor.moveToNext()) { // 获取每个目录下的歌曲数量 val songCount = cursor.getInt(index_num_of_songs) // 获取文件的路径,如/storage/sdcard0/MIUI/music/Baby.mp3 val filepath = cursor.getString(index_data) // 获取文件所属文件夹的路径,如/storage/sdcard0/MIUI/music val folderpath = filepath.substring(0, filepath.lastIndexOf(File.separator)) //刷新文件夹 NavigationHelper.scanFileAsync(MusicApp.mContext, folderpath) // 获取文件所属文件夹的名称,如music val foldername = folderpath.substring(folderpath.lastIndexOf(File.separator) + 1) folderInfos.add(FolderInfo(foldername, folderpath, songCount)) } } cursor?.close() subscriber.onNext(folderInfos) } } }
1
null
1
5
6d9442bad15910fe6d813bdf556fe1562d950947
2,104
077-Android-ListeningLove
Apache License 2.0
fragment/fragment-lint/src/main/java/androidx/fragment/lint/FragmentIssueRegistry.kt
RikkaW
389,105,112
false
null
/* * Copyright 2019 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package androidx.fragment.lint import com.android.tools.lint.client.api.IssueRegistry import com.android.tools.lint.client.api.Vendor import com.android.tools.lint.detector.api.CURRENT_API /** * Issue Registry containing Fragment specific lint Issues. */ @Suppress("UnstableApiUsage") class FragmentIssueRegistry : IssueRegistry() { // tests are run with this version. We ensure that with ApiLintVersionsTest override val api = 14 override val minApi = CURRENT_API override val issues get() = listOf( FragmentTagDetector.ISSUE, UnsafeFragmentLifecycleObserverDetector.ADD_MENU_PROVIDER_ISSUE, UnsafeFragmentLifecycleObserverDetector.BACK_PRESSED_ISSUE, UnsafeFragmentLifecycleObserverDetector.LIVEDATA_ISSUE, UseRequireInsteadOfGet.ISSUE, UseGetLayoutInflater.ISSUE, OnCreateDialogIncorrectCallbackDetector.ISSUE, UnsafeRepeatOnLifecycleDetector.ISSUE, AttachAndDetachInSameTransactionDetector.DETACH_ATTACH_OPERATIONS_ISSUE ) override val vendor = Vendor( feedbackUrl = "https://issuetracker.google.com/issues/new?component=460964", identifier = "androidx.fragment", vendorName = "Android Open Source Project", ) }
6
null
937
7
6d53f95e5d979366cf7935ad7f4f14f76a951ea5
1,861
androidx
Apache License 2.0
library/src/main/java/com/fanhl/util/CompatibleHelper.kt
dyguests
135,561,336
false
null
package com.fanhl.util import android.os.Build import android.view.View /** * 版本兼容处理 * * @author fanhl */ object CompatibleHelper { fun postInvalidateOnAnimation(view: View?) { view?.apply { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) { postInvalidateOnAnimation() } else { postInvalidate() } } } }
1
null
11
108
8979112cad6d42bdaa75afe736c82d541fcb68a0
413
FlameBarChart
Apache License 2.0
unify/src/commonTest/kotlin/it/unibo/tuprolog/unify/UnificatorTest.kt
tuProlog
230,784,338
false
null
package it.unibo.tuprolog.unify import it.unibo.tuprolog.core.Atom import it.unibo.tuprolog.core.Integer import it.unibo.tuprolog.core.Real import it.unibo.tuprolog.core.Substitution import it.unibo.tuprolog.core.Var import it.unibo.tuprolog.unify.Unificator.Companion.matches import it.unibo.tuprolog.unify.Unificator.Companion.mguWith import it.unibo.tuprolog.unify.Unificator.Companion.unifyWith import it.unibo.tuprolog.unify.testutils.UnificatorUtils import it.unibo.tuprolog.unify.testutils.UnificatorUtils.assertMatchCorrect import it.unibo.tuprolog.unify.testutils.UnificatorUtils.assertMguCorrect import it.unibo.tuprolog.unify.testutils.UnificatorUtils.assertUnifiedTermCorrect import kotlin.test.Test import kotlin.test.assertEquals /** * Test class for [Unificator] companion object * * @author Enrico */ internal class UnificatorTest { private val aVar = Var.of("A") private val myExampleContext = Substitution.of("A", Atom.of("a")) @Test fun naiveWithoutArgsCreateUnificationStrategyWithEmptyContext() { assertEquals(Substitution.empty(), Unificator.naive().context) } @Test fun passingNaiveAContextThisWillBeTheStrategyContext() { assertEquals(myExampleContext, Unificator.naive(myExampleContext).context) assertEquals(Substitution.failed(), Unificator.naive(Substitution.failed()).context) } @Test fun strictWithoutArgsCreateUnificationStrategyWithEmptyContext() { assertEquals(Substitution.empty(), Unificator.strict().context) } @Test fun passingStrictAContextThisWillBeTheStrategyContext() { assertEquals(myExampleContext, Unificator.strict(myExampleContext).context) assertEquals(Substitution.failed(), Unificator.strict(Substitution.failed()).context) } @Test fun naiveStrategyComparesNumbersByValue() { assertEquals(Substitution.empty(), Unificator.naive().mgu(Integer.of(1), Real.of(1.0))) } @Test fun strictStrategyComparesAllDataTypesWithEquals() { val firstA = Var.of("A") val secondA = Var.of("A") assertEquals(Substitution.of(firstA to secondA), Unificator.strict().mgu(firstA, secondA)) assertEquals(Substitution.empty(), Unificator.strict().mgu(aVar, aVar)) assertEquals(Substitution.failed(), Unificator.strict().mgu(Integer.of(1), Real.of(1.0))) } @Test fun mguWithFunctionWorksAsExpected() { val toTestUnification = UnificatorUtils.successfulUnifications + UnificatorUtils.failedUnifications assertMguCorrect(toTestUnification) { term1, term2 -> term1 mguWith term2 } } @Test fun matchesFunctionWorksAsExpected() { val toTestUnification = UnificatorUtils.successfulUnifications + UnificatorUtils.failedUnifications assertMatchCorrect(toTestUnification) { term1, term2 -> term1 matches term2 } } @Test fun unifyWithFunctionWorksAsExpected() { val toTestUnification = UnificatorUtils.successfulUnifications + UnificatorUtils.failedUnifications assertUnifiedTermCorrect(toTestUnification) { term1, term2 -> term1 unifyWith term2 } } }
92
null
14
93
3223ffc302e5da0efe2b254045fa1b6a1a122519
3,145
2p-kt
Apache License 2.0
data/src/main/java/com/jfalck/data/di/MoviesDatabaseModule.kt
jeremyfalck
552,366,176
false
null
package com.jfalck.data.di import android.content.Context import androidx.room.Room import com.jfalck.data.local.db.MoviesDatabase import dagger.Module import dagger.Provides import dagger.hilt.InstallIn import dagger.hilt.android.qualifiers.ApplicationContext import dagger.hilt.components.SingletonComponent import javax.inject.Singleton @Module @InstallIn(SingletonComponent::class) object MoviesDatabaseModule { private const val DB_NAME = "movies-db" @Singleton @Provides fun providesMoviesDatabase(@ApplicationContext applicationContext: Context) = Room.databaseBuilder( applicationContext, MoviesDatabase::class.java, DB_NAME ).build() }
0
Kotlin
0
0
166e2693595948b925f8d4dcfc5ad5780cd7f4a3
705
Mooviz
MIT License
features/employees/src/main/kotlin/co/ke/xently/learnspring/features/employees/exceptions/advices/EmployeeNotFoundAdvice.kt
ajharry69
600,428,197
false
null
package co.ke.xently.learnspring.features.employees.exceptions.advices import co.ke.xently.learnspring.features.employees.exceptions.EmployeeNotFoundException import org.springframework.hateoas.MediaTypes import org.springframework.hateoas.mediatype.problem.Problem import org.springframework.http.HttpHeaders import org.springframework.http.HttpStatus import org.springframework.http.ResponseEntity import org.springframework.web.bind.annotation.ControllerAdvice import org.springframework.web.bind.annotation.ExceptionHandler import org.springframework.web.bind.annotation.ResponseBody @ControllerAdvice class EmployeeNotFoundAdvice { @ResponseBody @ExceptionHandler(EmployeeNotFoundException::class) fun handler(exception: EmployeeNotFoundException) = ResponseEntity.status(HttpStatus.NOT_FOUND) .header(HttpHeaders.CONTENT_TYPE, MediaTypes.HTTP_PROBLEM_DETAILS_JSON_VALUE) .body( Problem.create().withDetail(exception.localizedMessage).withProperties(mapOf("code" to "not_found")) .withStatus(HttpStatus.NOT_FOUND) ) }
1
Kotlin
0
0
7b93ba79d89d2c621f5323f2d1e9e2f8f0375544
1,088
learning-spring-boot
Apache License 2.0
dependency-injection/test-component/src/main/kotlin/studio/lunabee/di/SettingsTestModule.kt
LunabeeStudio
624,544,471
false
null
/* * Copyright (c) 2023-2023 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/7/2023 - for the oneSafe6 SDK. * Last modified 4/7/23, 12:30 AM */ package studio.lunabee.di import android.content.Context import androidx.datastore.core.DataStore import androidx.datastore.preferences.core.PreferenceDataStoreFactory import androidx.datastore.preferences.core.Preferences import androidx.datastore.preferences.preferencesDataStoreFile import dagger.Module import dagger.Provides import dagger.hilt.android.qualifiers.ApplicationContext import dagger.hilt.components.SingletonComponent import dagger.hilt.testing.TestInstallIn import studio.lunabee.onesafe.SettingsModule import javax.inject.Singleton @Module @TestInstallIn( components = [SingletonComponent::class], replaces = [SettingsModule::class], ) object SettingsTestModule { var datastoreIncSuffix: Int = 0 /** * Provide a different datastore for each test to avoid * [IllegalStateException]: There are multiple DataStores active for the same file */ @Provides @Singleton fun providePreferenceDataStore( @ApplicationContext context: Context, ): DataStore<Preferences> { return PreferenceDataStoreFactory.create { context.preferencesDataStoreFile("datastore_settings_" + datastoreIncSuffix++).apply { deleteOnExit() } } } }
0
null
1
2
a34f0ddaf9dc649c2f2082dc2526921bb1a491df
1,965
oneSafe6_SDK_Android
Apache License 2.0
matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/crypto/keysbackup/tasks/UpdateKeysBackupVersionTask.kt
matrix-org
287,466,066
false
null
/* * Copyright 2019 New Vector Ltd * Copyright 2020 The Matrix.org Foundation C.I.C. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.matrix.android.sdk.internal.crypto.keysbackup.tasks import org.matrix.android.sdk.internal.crypto.keysbackup.api.RoomKeysApi import org.matrix.android.sdk.internal.crypto.keysbackup.model.rest.UpdateKeysBackupVersionBody import org.matrix.android.sdk.internal.network.executeRequest import org.matrix.android.sdk.internal.task.Task import org.greenrobot.eventbus.EventBus import javax.inject.Inject internal interface UpdateKeysBackupVersionTask : Task<UpdateKeysBackupVersionTask.Params, Unit> { data class Params( val version: String, val keysBackupVersionBody: UpdateKeysBackupVersionBody ) } internal class DefaultUpdateKeysBackupVersionTask @Inject constructor( private val roomKeysApi: RoomKeysApi, private val eventBus: EventBus ) : UpdateKeysBackupVersionTask { override suspend fun execute(params: UpdateKeysBackupVersionTask.Params) { return executeRequest(eventBus) { apiCall = roomKeysApi.updateKeysBackupVersion(params.version, params.keysBackupVersionBody) } } }
75
null
6
97
55cc7362de34a840c67b4bbb3a14267bc8fd3b9c
1,723
matrix-android-sdk2
Apache License 2.0
log4k/src/commonMain/kotlin/io/github/smyrgeorge/log4k/impl/registry/AppenderRegistry.kt
smyrgeorge
873,865,353
false
{"Kotlin": 26332, "Shell": 399}
package io.github.smyrgeorge.log4k.impl.registry import io.github.smyrgeorge.log4k.Appender import io.github.smyrgeorge.log4k.impl.extensions.witLock import kotlinx.coroutines.sync.Mutex @Suppress("unused") class AppenderRegistry<T> { private val mutex = Mutex() private val appenders = mutableListOf<Appender<T>>() fun all(): List<Appender<T>> = mutex.witLock { appenders.toList() } fun get(name: String): Appender<T>? = mutex.witLock { appenders.find { it.name == name } } fun register(appender: Appender<T>) = mutex.witLock { appenders.add(appender) } fun unregister(name: String) = mutex.witLock { appenders.removeAll { it.name == name } } fun unregisterAll() = mutex.witLock { appenders.clear() } }
0
Kotlin
0
7
45fc715f030990785a111d7bf5aabbc03d4eb1e3
733
log4k
MIT License
app/src/main/java/de/p72b/umi/github/utils/Utils.kt
P72B
217,081,677
false
null
package de.p72b.umi.github.utils import android.view.View import android.widget.TextView import androidx.core.content.ContextCompat import com.google.android.material.snackbar.Snackbar import de.p72b.umi.github.App import de.p72b.umi.github.R object Utils { const val DATE_FORMAT = "yyyy-MM-dd'T'HH:mm:ss.SSSZ" //2014-02-04T14:38:36-08:00 fun showSnackbar( rootView: View, message: CharSequence, duration: Int = Snackbar.LENGTH_LONG, actionMessage: String? = null, actionClickListener: View.OnClickListener? = null ): Snackbar? { return Snackbar.make(rootView, message, duration).apply { if (actionClickListener != null && actionMessage != null) { setAction(actionMessage, actionClickListener) } view.findViewById<TextView>(com.google.android.material.R.id.snackbar_text).apply { setTextColor(ContextCompat.getColor(App.sInstance, R.color.white)) maxLines = 5 } show() } } }
0
Kotlin
0
0
e75b98e39c30f305ecffd12a2a5a9c1a881d163e
1,058
GithubBrowserSample
MIT License
core/src/commonTest/kotlin/codes/laurence/warden/information/InformationPointAggregateTest.kt
lgwillmore
230,963,216
false
{"Kotlin": 146883}
package codes.laurence.warden.information import assertk.assertThat import assertk.assertions.isSameAs import codes.laurence.warden.coroutines.runBlockingTest import codes.laurence.warden.test.accessRequestFixture import io.mockk.coEvery import io.mockk.mockk import kotlin.test.Test class InformationPointAggregateTest { @Test fun enrich() = runBlockingTest { val originalRequest = accessRequestFixture() val enrichedBy1Request = accessRequestFixture() val enrichedBy2Request = accessRequestFixture() val informationPoint1Mock = mockk<InformationPoint> { coEvery { enrich(originalRequest) } returns enrichedBy1Request } val informationPoint2Mock = mockk<InformationPoint> { coEvery { enrich(enrichedBy1Request) } returns enrichedBy2Request } val testObj = InformationPointAggregate( listOf(informationPoint1Mock, informationPoint2Mock) ) val actual = testObj.enrich(originalRequest) assertThat(actual).isSameAs(enrichedBy2Request) } }
13
Kotlin
3
17
68849fc726ce2a8df09d644e4f80401d7a1b27f6
1,078
warden
MIT License
kotlin-cdk-wrapper/src/main/kotlin/io/cloudshiftdev/awscdk/services/elasticloadbalancingv2/ApplicationListenerProps.kt
cloudshiftinc
667,063,030
false
null
@file:Suppress("RedundantVisibilityModifier","RedundantUnitReturnType","RemoveRedundantQualifierName","unused","UnusedImport","ClassName","REDUNDANT_PROJECTION","DEPRECATION") package io.cloudshiftdev.awscdk.services.elasticloadbalancingv2 import io.cloudshiftdev.awscdk.common.CdkDslMarker import io.cloudshiftdev.awscdk.common.CdkObject import io.cloudshiftdev.awscdk.common.CdkObjectWrappers import kotlin.Boolean import kotlin.Number import kotlin.Unit import kotlin.collections.List /** * Properties for defining a standalone ApplicationListener. * * Example: * * ``` * // The code below shows an example of how to instantiate this type. * // The values are placeholders you should change. * import io.cloudshiftdev.awscdk.services.elasticloadbalancingv2.*; * ApplicationLoadBalancer applicationLoadBalancer; * ApplicationTargetGroup applicationTargetGroup; * ListenerAction listenerAction; * ListenerCertificate listenerCertificate; * ApplicationListenerProps applicationListenerProps = ApplicationListenerProps.builder() * .loadBalancer(applicationLoadBalancer) * // the properties below are optional * .certificates(List.of(listenerCertificate)) * .defaultAction(listenerAction) * .defaultTargetGroups(List.of(applicationTargetGroup)) * .open(false) * .port(123) * .protocol(ApplicationProtocol.HTTP) * .sslPolicy(SslPolicy.RECOMMENDED_TLS) * .build(); * ``` */ public interface ApplicationListenerProps : BaseApplicationListenerProps { /** * The load balancer to attach this listener to. */ public fun loadBalancer(): IApplicationLoadBalancer /** * A builder for [ApplicationListenerProps] */ @CdkDslMarker public interface Builder { /** * @param certificates Certificate list of ACM cert ARNs. * You must provide exactly one certificate if the listener protocol is HTTPS or TLS. */ public fun certificates(certificates: List<IListenerCertificate>) /** * @param certificates Certificate list of ACM cert ARNs. * You must provide exactly one certificate if the listener protocol is HTTPS or TLS. */ public fun certificates(vararg certificates: IListenerCertificate) /** * @param defaultAction Default action to take for requests to this listener. * This allows full control of the default action of the load balancer, * including Action chaining, fixed responses and redirect responses. * * See the `ListenerAction` class for all options. * * Cannot be specified together with `defaultTargetGroups`. */ public fun defaultAction(defaultAction: ListenerAction) /** * @param defaultTargetGroups Default target groups to load balance to. * All target groups will be load balanced to with equal weight and without * stickiness. For a more complex configuration than that, use * either `defaultAction` or `addAction()`. * * Cannot be specified together with `defaultAction`. */ public fun defaultTargetGroups(defaultTargetGroups: List<IApplicationTargetGroup>) /** * @param defaultTargetGroups Default target groups to load balance to. * All target groups will be load balanced to with equal weight and without * stickiness. For a more complex configuration than that, use * either `defaultAction` or `addAction()`. * * Cannot be specified together with `defaultAction`. */ public fun defaultTargetGroups(vararg defaultTargetGroups: IApplicationTargetGroup) /** * @param loadBalancer The load balancer to attach this listener to. */ public fun loadBalancer(loadBalancer: IApplicationLoadBalancer) /** * @param open Allow anyone to connect to the load balancer on the listener port. * If this is specified, the load balancer will be opened up to anyone who can reach it. * For internal load balancers this is anyone in the same VPC. For public load * balancers, this is anyone on the internet. * * If you want to be more selective about who can access this load * balancer, set this to `false` and use the listener's `connections` * object to selectively grant access to the load balancer on the listener port. */ public fun `open`(`open`: Boolean) /** * @param port The port on which the listener listens for requests. */ public fun port(port: Number) /** * @param protocol The protocol to use. */ public fun protocol(protocol: ApplicationProtocol) /** * @param sslPolicy The security policy that defines which ciphers and protocols are supported. */ public fun sslPolicy(sslPolicy: SslPolicy) } private class BuilderImpl : Builder { private val cdkBuilder: software.amazon.awscdk.services.elasticloadbalancingv2.ApplicationListenerProps.Builder = software.amazon.awscdk.services.elasticloadbalancingv2.ApplicationListenerProps.builder() /** * @param certificates Certificate list of ACM cert ARNs. * You must provide exactly one certificate if the listener protocol is HTTPS or TLS. */ override fun certificates(certificates: List<IListenerCertificate>) { cdkBuilder.certificates(certificates.map(IListenerCertificate.Companion::unwrap)) } /** * @param certificates Certificate list of ACM cert ARNs. * You must provide exactly one certificate if the listener protocol is HTTPS or TLS. */ override fun certificates(vararg certificates: IListenerCertificate): Unit = certificates(certificates.toList()) /** * @param defaultAction Default action to take for requests to this listener. * This allows full control of the default action of the load balancer, * including Action chaining, fixed responses and redirect responses. * * See the `ListenerAction` class for all options. * * Cannot be specified together with `defaultTargetGroups`. */ override fun defaultAction(defaultAction: ListenerAction) { cdkBuilder.defaultAction(defaultAction.let(ListenerAction.Companion::unwrap)) } /** * @param defaultTargetGroups Default target groups to load balance to. * All target groups will be load balanced to with equal weight and without * stickiness. For a more complex configuration than that, use * either `defaultAction` or `addAction()`. * * Cannot be specified together with `defaultAction`. */ override fun defaultTargetGroups(defaultTargetGroups: List<IApplicationTargetGroup>) { cdkBuilder.defaultTargetGroups(defaultTargetGroups.map(IApplicationTargetGroup.Companion::unwrap)) } /** * @param defaultTargetGroups Default target groups to load balance to. * All target groups will be load balanced to with equal weight and without * stickiness. For a more complex configuration than that, use * either `defaultAction` or `addAction()`. * * Cannot be specified together with `defaultAction`. */ override fun defaultTargetGroups(vararg defaultTargetGroups: IApplicationTargetGroup): Unit = defaultTargetGroups(defaultTargetGroups.toList()) /** * @param loadBalancer The load balancer to attach this listener to. */ override fun loadBalancer(loadBalancer: IApplicationLoadBalancer) { cdkBuilder.loadBalancer(loadBalancer.let(IApplicationLoadBalancer.Companion::unwrap)) } /** * @param open Allow anyone to connect to the load balancer on the listener port. * If this is specified, the load balancer will be opened up to anyone who can reach it. * For internal load balancers this is anyone in the same VPC. For public load * balancers, this is anyone on the internet. * * If you want to be more selective about who can access this load * balancer, set this to `false` and use the listener's `connections` * object to selectively grant access to the load balancer on the listener port. */ override fun `open`(`open`: Boolean) { cdkBuilder.`open`(`open`) } /** * @param port The port on which the listener listens for requests. */ override fun port(port: Number) { cdkBuilder.port(port) } /** * @param protocol The protocol to use. */ override fun protocol(protocol: ApplicationProtocol) { cdkBuilder.protocol(protocol.let(ApplicationProtocol.Companion::unwrap)) } /** * @param sslPolicy The security policy that defines which ciphers and protocols are supported. */ override fun sslPolicy(sslPolicy: SslPolicy) { cdkBuilder.sslPolicy(sslPolicy.let(SslPolicy.Companion::unwrap)) } public fun build(): software.amazon.awscdk.services.elasticloadbalancingv2.ApplicationListenerProps = cdkBuilder.build() } private class Wrapper( cdkObject: software.amazon.awscdk.services.elasticloadbalancingv2.ApplicationListenerProps, ) : CdkObject(cdkObject), ApplicationListenerProps { /** * Certificate list of ACM cert ARNs. * * You must provide exactly one certificate if the listener protocol is HTTPS or TLS. * * Default: - No certificates. */ override fun certificates(): List<IListenerCertificate> = unwrap(this).getCertificates()?.map(IListenerCertificate::wrap) ?: emptyList() /** * Default action to take for requests to this listener. * * This allows full control of the default action of the load balancer, * including Action chaining, fixed responses and redirect responses. * * See the `ListenerAction` class for all options. * * Cannot be specified together with `defaultTargetGroups`. * * Default: - None. */ override fun defaultAction(): ListenerAction? = unwrap(this).getDefaultAction()?.let(ListenerAction::wrap) /** * Default target groups to load balance to. * * All target groups will be load balanced to with equal weight and without * stickiness. For a more complex configuration than that, use * either `defaultAction` or `addAction()`. * * Cannot be specified together with `defaultAction`. * * Default: - None. */ override fun defaultTargetGroups(): List<IApplicationTargetGroup> = unwrap(this).getDefaultTargetGroups()?.map(IApplicationTargetGroup::wrap) ?: emptyList() /** * The load balancer to attach this listener to. */ override fun loadBalancer(): IApplicationLoadBalancer = unwrap(this).getLoadBalancer().let(IApplicationLoadBalancer::wrap) /** * Allow anyone to connect to the load balancer on the listener port. * * If this is specified, the load balancer will be opened up to anyone who can reach it. * For internal load balancers this is anyone in the same VPC. For public load * balancers, this is anyone on the internet. * * If you want to be more selective about who can access this load * balancer, set this to `false` and use the listener's `connections` * object to selectively grant access to the load balancer on the listener port. * * Default: true */ override fun `open`(): Boolean? = unwrap(this).getOpen() /** * The port on which the listener listens for requests. * * Default: - Determined from protocol if known. */ override fun port(): Number? = unwrap(this).getPort() /** * The protocol to use. * * Default: - Determined from port if known. */ override fun protocol(): ApplicationProtocol? = unwrap(this).getProtocol()?.let(ApplicationProtocol::wrap) /** * The security policy that defines which ciphers and protocols are supported. * * Default: - The current predefined security policy. */ override fun sslPolicy(): SslPolicy? = unwrap(this).getSslPolicy()?.let(SslPolicy::wrap) } public companion object { public operator fun invoke(block: Builder.() -> Unit = {}): ApplicationListenerProps { val builderImpl = BuilderImpl() return Wrapper(builderImpl.apply(block).build()) } internal fun wrap(cdkObject: software.amazon.awscdk.services.elasticloadbalancingv2.ApplicationListenerProps): ApplicationListenerProps = CdkObjectWrappers.wrap(cdkObject) as? ApplicationListenerProps ?: Wrapper(cdkObject) internal fun unwrap(wrapped: ApplicationListenerProps): software.amazon.awscdk.services.elasticloadbalancingv2.ApplicationListenerProps = (wrapped as CdkObject).cdkObject as software.amazon.awscdk.services.elasticloadbalancingv2.ApplicationListenerProps } }
4
null
0
4
db2b3a364f5e74d8f80490e7850da7f1e7f1e7d0
12,693
kotlin-cdk-wrapper
Apache License 2.0
app/src/main/java/com/androidyug/marsrover/ui/intro/AndroidLogoPaths.kt
betafactory
206,523,382
false
null
package com.androidyug.marsrover.ui.intro /** * Created by derek on 2/6/15. */ object AndroidLogoPaths { val ANDROID_GLYPHS = arrayOf("M 535.59,68.00" + "C 535.59,68.00 528.28,57.00 528.28,57.00" + " 523.84,50.62 516.32,42.18 517.20,34.00" + " 518.38,22.98 530.74,17.59 539.96,23.23" + " 545.09,26.36 555.10,43.15 559.00,49.00" + " 559.00,49.00 597.83,107.00 597.83,107.00" + " 597.83,107.00 611.31,127.00 611.31,127.00" + " 612.67,129.10 615.09,133.65 617.47,134.49" + " 619.30,135.14 623.10,133.69 625.00,133.14" + " 625.00,133.14 643.00,127.86 643.00,127.86" + " 663.41,122.08 684.11,118.51 705.00,115.08" + " 705.00,115.08 768.00,109.00 768.00,109.00" + " 768.00,109.00 798.00,109.00 798.00,109.00" + " 798.00,109.00 833.00,109.00 833.00,109.00" + " 833.00,109.00 889.00,114.13 889.00,114.13" + " 912.39,117.38 935.13,121.68 958.00,127.63" + " 958.00,127.63 977.00,133.14 977.00,133.14" + " 978.83,133.67 982.59,135.16 984.33,134.52" + " 986.44,133.74 989.49,128.92 990.86,127.00" + " 990.86,127.00 1004.86,106.00 1004.86,106.00" + " 1004.86,106.00 1035.67,60.00 1035.67,60.00" + " 1035.67,60.00 1056.43,29.01 1056.43,29.01" + " 1059.11,25.38 1061.47,22.75 1066.00,21.56" + " 1076.11,18.90 1085.86,26.43 1084.80,37.00" + " 1084.27,42.30 1080.86,46.71 1078.00,51.00" + " 1078.00,51.00 1065.33,70.00 1065.33,70.00" + " 1065.33,70.00 1014.00,147.00 1014.00,147.00" + " 1033.28,153.73 1060.01,169.12 1077.00,180.66" + " 1145.24,227.01 1187.58,288.02 1212.50,366.00" + " 1219.87,389.05 1224.76,412.95 1227.17,437.00" + " 1227.17,437.00 1229.00,458.00 1229.00,458.00" + " 1229.00,458.00 374.00,458.00 374.00,458.00" + " 374.00,458.00 376.84,433.00 376.84,433.00" + " 387.66,331.91 442.01,236.32 527.00,179.67" + " 542.71,169.19 570.44,153.13 588.00,147.00" + " 588.00,147.00 535.59,68.00 535.59,68.00 Z" + "M 952.17,253.67" + "C 920.69,281.08 938.42,335.99 983.00,335.99" + " 1013.42,335.99 1034.26,309.42 1028.74,280.00" + " 1027.09,271.21 1023.01,262.70 1016.70,256.29" + " 1007.39,246.82 995.93,243.23 983.00,242.57" + " 970.90,243.18 961.62,245.44 952.17,253.67 Z" + "M 592.00,250.22" + "C 561.69,271.06 566.00,319.37 601.00,332.58" + " 606.19,334.53 611.43,335.86 617.00,335.99" + " 650.87,336.76 674.16,303.47 661.80,272.00" + " 659.34,265.76 655.90,259.80 650.96,255.17" + " 638.99,243.96 625.71,241.80 610.00,243.29" + " 603.45,244.39 597.52,246.42 592.00,250.22 Z", "M 311.00,593.00" + "C 311.00,593.00 311.00,1013.00 311.00,1013.00" + " 310.98,1023.46 308.73,1033.77 303.69,1043.00" + " 290.33,1067.47 257.50,1083.96 230.00,1084.00" + " 216.00,1084.02 207.91,1084.52 194.00,1080.57" + " 163.33,1071.88 136.05,1047.68 136.00,1014.00" + " 136.00,1014.00 136.00,592.00 136.00,592.00" + " 136.05,559.26 161.52,536.20 191.00,526.75" + " 198.64,524.29 205.20,523.56 213.00,522.42" + " 256.68,517.11 310.92,543.89 311.00,593.00 Z", "M 461.00,1278.55" + "C 437.84,1273.89 415.58,1259.98 400.44,1242.00" + " 383.61,1222.03 375.04,1195.97 375.00,1170.00" + " 375.00,1170.00 375.00,1146.00 375.00,1146.00" + " 375.00,1146.00 375.00,1090.00 375.00,1090.00" + " 375.00,1090.00 375.00,742.00 375.00,742.00" + " 375.00,742.00 375.00,569.00 375.00,569.00" + " 375.00,569.00 375.00,523.00 375.00,523.00" + " 375.14,515.51 377.26,516.01 384.00,516.00" + " 384.00,516.00 1228.00,516.00 1228.00,516.00" + " 1228.00,516.00 1228.00,1178.00 1228.00,1178.00" + " 1227.99,1186.20 1226.85,1191.15 1224.87,1199.00" + " 1215.20,1237.54 1185.61,1267.63 1147.00,1277.52" + " 1139.20,1279.52 1130.04,1280.99 1122.00,1281.00" + " 1122.00,1281.00 1062.00,1281.00 1062.00,1281.00" + " 1062.00,1281.00 1062.00,1517.00 1062.00,1517.00" + " 1061.96,1545.82 1041.88,1568.83 1016.00,1579.40" + " 1003.62,1584.45 996.15,1585.90 983.00,1587.17" + " 978.89,1587.57 977.57,1588.14 973.00,1587.96" + " 939.16,1586.65 903.67,1571.40 890.61,1538.00" + " 887.95,1531.20 887.01,1524.27 887.00,1517.00" + " 887.00,1517.00 887.00,1281.00 887.00,1281.00" + " 887.00,1281.00 716.00,1281.00 716.00,1281.00" + " 716.00,1281.00 716.00,1518.00 716.00,1518.00" + " 715.96,1544.74 698.11,1565.68 675.00,1577.24" + " 662.62,1583.43 650.59,1585.85 637.00,1587.17" + " 632.89,1587.57 631.57,1588.14 627.00,1587.96" + " 592.95,1586.64 555.66,1570.58 544.00,1536.00" + " 541.73,1529.26 541.01,1524.07 541.00,1517.00" + " 541.00,1517.00 541.00,1281.00 541.00,1281.00" + " 518.86,1281.00 481.29,1282.63 461.00,1278.55 Z" + "M 484.00,1282.00" + "C 484.00,1282.00 483.00,1283.00 483.00,1283.00" + " 483.00,1283.00 483.00,1282.00 483.00,1282.00" + " 483.00,1282.00 484.00,1282.00 484.00,1282.00 Z" + "M 540.00,1282.00" + "C 540.00,1282.00 539.00,1283.00 539.00,1283.00" + " 539.00,1283.00 539.00,1282.00 539.00,1282.00" + " 539.00,1282.00 540.00,1282.00 540.00,1282.00 Z" + "M 718.00,1282.00" + "C 718.00,1282.00 717.00,1283.00 717.00,1283.00" + " 717.00,1283.00 717.00,1282.00 717.00,1282.00" + " 717.00,1282.00 718.00,1282.00 718.00,1282.00 Z" + "M 1064.00,1282.00" + "C 1064.00,1282.00 1063.00,1283.00 1063.00,1283.00" + " 1063.00,1283.00 1063.00,1282.00 1063.00,1282.00" + " 1063.00,1282.00 1064.00,1282.00 1064.00,1282.00 Z", "M 1469.00,590.00" + "C 1469.00,590.00 1469.00,1016.00 1469.00,1016.00" + " 1468.94,1056.41 1425.05,1083.94 1388.00,1084.00" + " 1388.00,1084.00 1375.00,1084.00 1375.00,1084.00" + " 1343.38,1083.95 1306.70,1063.24 1297.02,1032.00" + " 1295.13,1025.89 1294.03,1018.40 1294.00,1012.00" + " 1294.00,1012.00 1294.00,594.00 1294.00,594.00" + " 1294.06,557.55 1321.80,533.90 1355.00,525.16" + " 1355.00,525.16 1371.00,522.42 1371.00,522.42" + " 1412.21,517.39 1468.93,542.72 1469.00,590.00 Z") val ANDROID_GLYPHS_2 = arrayOf("M907.229,361.573c0,111.422-25.466,220.65-76.381,327.703c-43.841,91.99-99.413,169.115-166.717,231.355" + "c-63.33,58.284-118.457,87.426-165.387,87.426c-46.94,0-102.07-29.142-165.387-87.426" + "c-67.313-62.24-122.878-139.365-166.715-231.355c-50.925-107.053-76.383-216.28-76.383-327.703" + "c0-104.674,34.091-189.127,102.287-253.36C265.609,39.222,367.667,4.727,498.744,4.727c131.067,0,233.135,34.495,306.196,103.486" + "C873.127,172.446,907.229,256.899,907.229,361.573z M423.025,680.949c-0.447-18.232-1.993-35.284-4.649-51.146" + "c-6.643-37.266-17.498-65.023-32.547-83.263c-27.461-31.718-84.136-54.124-170.036-67.208" + "c-2.222,61.853,11.726,108.049,41.845,138.576C286.417,647.252,341.545,668.268,423.025,680.949z M781.694,479.333" + "c-25.238,3.967-48.051,8.92-68.414,14.868c-49.149,13.882-83.024,31.325-101.619,52.339" + "c-23.029,26.566-35.434,71.368-37.198,134.409c23.463-3.565,45.168-8.12,65.091-13.678c47.378-13.084,80.808-29.534,100.296-49.363" + "C769.956,587.382,783.904,541.186,781.694,479.333z", " ", " ", " ") }
2
Kotlin
6
7
4aaad8c706e844ebbe6d098f221ebdd4dd5a0313
8,175
MarsRoverAndroid
Apache License 2.0
aes-android/src/main/java/com/fevziomurtekin/aes/CipherTransformations.kt
fevziomurtekin
372,067,982
false
null
package com.fevziomurtekin.aes /** * @author: fevziomurtekin * @date: 29/05/2021 */ object CipherTransformations { const val AesCbcNoPadding: String = "AES/CBC/NoPadding" const val AesCbcPkcs5Padding: String = "AES/CBC/PKCS5Padding" const val AesEcbNoPadding: String = "AES/CBC/PKCS5Padding" const val DesCbcNoPadding: String = "DES/CBC/NoPadding" const val DesCbcPkcs5Padding: String = "DES/CBC/PKCS5Padding" const val DesEcbNoPadding: String = "DES/ECB/NoPadding" const val DesedeCbcNoPadding: String = "DESede/CBC/NoPadding" const val DesedeCbcPkcs5Padding: String = "DESede/CBC/PKCS5Padding" const val RsaEcbPkcs1Padding: String = "RSA/ECB/PKCS1Padding" const val RsaEcbOaepWithSHA1AndMGF1Padding: String = "RSA/ECB/OAEPWithSHA-1AndMGF1Padding" const val RsaEcbOaepWithSHA256AndMGF1Padding: String = "RSA/ECB/OAEPWithSHA-256AndMGF1Padding" }
0
Kotlin
0
9
b29a6addccc9f4e1638fa67005a5f91a7659a623
871
Aes-android
MIT License
app/src/main/java/io/github/gmathi/novellibrary/network/NovelApi_SearchTerm.kt
ahamedcool
288,104,783
true
{"Kotlin": 520507}
package io.github.gmathi.novellibrary.network import io.github.gmathi.novellibrary.model.Novel import java.io.IOException fun NovelApi.searchRoyalRoad(searchTerms: String): ArrayList<Novel>? { var searchResults: ArrayList<Novel>? = null try { searchResults = ArrayList() val document = getDocument("https://royalroadl.com/fictions/search?keyword=$searchTerms&name=&author=&minPages=0&maxPages=10000&minRating=0&maxRating=5&status=ALL&orderBy=popularity&dir=desc&type=ALL") val elements = document.body().getElementsByClass("search-item").filter { it.tagName() == "li" } for (element in elements) { val searchContentElement = element.getElementsByClass("search-content").firstOrNull() if (searchContentElement != null) { val urlElement = searchContentElement.getElementsByTag("a")?.firstOrNull() val novel = Novel(urlElement?.text()!!, "https://www.royalroadl.com${urlElement.attr("href")}") novel.imageUrl = element.getElementsByTag("img").firstOrNull()?.attr("src") novel.metaData["Author(s)"] = searchContentElement.getElementsByClass("author")?.firstOrNull { it.tagName() == "span" }?.text()?.substring(3) novel.rating = "N/A" novel.longDescription = searchContentElement.getElementsByTag("div")?.firstOrNull { it.hasClass("fiction-description") }?.text() novel.shortDescription = novel.longDescription?.split("\n")?.firstOrNull() searchResults.add(novel) } } } catch (e: IOException) { e.printStackTrace() } return searchResults } fun NovelApi.searchNovelUpdates(searchTerms: String): ArrayList<Novel>? { var searchResults: ArrayList<Novel>? = null try { searchResults = ArrayList() val document = getDocumentWithUserAgent("http://www.novelupdates.com/?s=" + searchTerms) val titleElements = document.body().getElementsByClass("w-blog-entry-title").filter { it.tagName() == "h2" } val dataElements = document.body().getElementsByClass("w-blog-entry").filter { it.tagName() == "div" } var i = 0 while (i < dataElements.size) { val novel = Novel(titleElements[i].getElementsByTag("span").firstOrNull { it.hasClass("w-blog-entry-title-h") }?.text()!!, titleElements[i].getElementsByTag("a").firstOrNull()?.attr("href")!!) novel.imageUrl = dataElements[i].getElementsByTag("img").firstOrNull()?.attr("src") novel.rating = dataElements[i].getElementsByTag("span").firstOrNull { it.hasClass("userrate") }?.text()?.replace("Rating: ", "")?.trim() novel.genres = dataElements[i].getElementsByTag("span").firstOrNull { it.className() == "s-genre" }?.children()?.map { it.text() } novel.shortDescription = dataElements[i].getElementsByTag("div").firstOrNull { it.className() == "w-blog-entry-short" }?.textNodes()?.get(0)?.text() novel.longDescription = dataElements[i].getElementsByTag("span").firstOrNull { it.attr("style") == "display:none" }?.textNodes()?.map { it.text() }?.joinToString(separator = "\n") { it } searchResults.add(novel) i++ } } catch (e: IOException) { e.printStackTrace() } return searchResults } fun NovelApi.searchWlnUpdates(searchTerms: String): ArrayList<Novel>? { var searchResults: ArrayList<Novel>? = null try { searchResults = ArrayList() val document = getDocument("https://www.wlnupdates.com/search?title=" + searchTerms) val elements = document.body().getElementsByTag("td") elements.mapTo(searchResults) { Novel(it.getElementsByTag("a").firstOrNull()?.text()!!, it.getElementsByTag("a").firstOrNull()?.absUrl("href")!!) } } catch (e: IOException) { e.printStackTrace() } return searchResults }
0
Kotlin
0
0
dfbd1af4e3c82624fa637b0b90e3be8fc555a270
3,906
NovelLibrary
Apache License 2.0
domain/src/test/kotlin/fr/sacane/jmanager/domain/AuthenticationTest.kt
Sacane
531,082,439
false
{"Kotlin": 115428, "Vue": 43310, "TypeScript": 18019, "JavaScript": 602, "CSS": 134}
package fr.sacane.jmanager.domain import fr.sacane.jmanager.domain.models.Response import fr.sacane.jmanager.domain.models.ResponseState import org.junit.jupiter.api.Assertions.assertEquals import org.junit.jupiter.api.Test interface AuthenticationTest { val action: List<Response<out Any>> @Test fun badAuthTest() { action.forEach { assertEquals(ResponseState.UNAUTHORIZED, it.status) } } }
1
Kotlin
0
0
9238109ddfd0f25846eb8b9acb8e2ba19bb79eb5
438
JManager
MIT License
tmdb-api/src/main/java/com/chahine/tmdb/api/entities/TvSeason.kt
chahine
120,981,876
false
{"Kotlin": 141261}
package com.chahine.tmdb.api.entities import com.squareup.moshi.Json import com.squareup.moshi.JsonClass @JsonClass(generateAdapter = true) class TvSeason( val id: Int? = null, @Json(name = "poster_path") val posterPath: String? = null, @Json(name = "season_number") val seasonNumber: Int? = null, // @Json(name = "air_date") val airDate: ZonedDateTime? = null, val episodes: List<TvEpisode>? = null, val name: String? = null, val overview: String? = null, val credits: Credits? = null, val images: Images? = null, val videos: Videos? = null, @Json(name = "external_ids") val externalIds: TvSeasonExternalIds? = null )
7
Kotlin
1
6
f28df033cef99881570c35e7455ea3fd23073fe6
664
showhive
MIT License
buildSrc/src/main/kotlin/Libs.kt
diconium
472,377,158
false
{"Kotlin": 20208}
import kotlin.String /** * Generated by * $ ./gradlew buildSrcLibs * Re-run when you add a new dependency to the build * * Find which updates are available by running * $ ./gradlew refreshVersions * And edit the file `versions.properties` * * See https://github.com/jmfayard/refreshVersions */ public object Libs { public const val activity: String = "androidx.activity:activity:_" public const val activity_ktx: String = "androidx.activity:activity-ktx:_" public const val appcompat: String = "androidx.appcompat:appcompat:_" public const val animation: String = "androidx.compose.animation:animation:_" public const val foundation: String = "androidx.compose.foundation:foundation:_" public const val androidx_compose_material_material: String = "androidx.compose.material:material:_" public const val material_icons_core: String = "androidx.compose.material:material-icons-core:_" public const val material_ripple: String = "androidx.compose.material:material-ripple:_" public const val androidx_compose_runtime_runtime: String = "androidx.compose.runtime:runtime:_" public const val ui: String = "androidx.compose.ui:ui:_" public const val ui_graphics: String = "androidx.compose.ui:ui-graphics:_" public const val ui_text: String = "androidx.compose.ui:ui-text:_" public const val ui_tooling: String = "androidx.compose.ui:ui-tooling:_" public const val constraintlayout: String = "androidx.constraintlayout:constraintlayout:_" public const val constraintlayout_compose: String = "androidx.constraintlayout:constraintlayout-compose:_" public const val androidx_core_core: String = "androidx.core:core:_" public const val core_ktx: String = "androidx.core:core-ktx:_" public const val fragment: String = "androidx.fragment:fragment:_" public const val fragment_ktx: String = "androidx.fragment:fragment-ktx:_" public const val lifecycle_livedata: String = "androidx.lifecycle:lifecycle-livedata:_" public const val lifecycle_livedata_ktx: String = "androidx.lifecycle:lifecycle-livedata-ktx:_" public const val lifecycle_process: String = "androidx.lifecycle:lifecycle-process:_" public const val lifecycle_viewmodel: String = "androidx.lifecycle:lifecycle-viewmodel:_" public const val lifecycle_viewmodel_compose: String = "androidx.lifecycle:lifecycle-viewmodel-compose:_" public const val lifecycle_viewmodel_ktx: String = "androidx.lifecycle:lifecycle-viewmodel-ktx:_" public const val lifecycle_viewmodel_savedstate: String = "androidx.lifecycle:lifecycle-viewmodel-savedstate:_" public const val navigation_compose: String = "androidx.navigation:navigation-compose:_" public const val recyclerview: String = "androidx.recyclerview:recyclerview:_" public const val espresso_core: String = "androidx.test.espresso:espresso-core:_" public const val junit_ktx: String = "androidx.test.ext:junit-ktx:_" public const val com_android_tools_build_gradle: String = "com.android.tools.build:gradle:_" public const val glide: String = "com.github.bumptech.glide:glide:_" public const val com_google_android_material_material: String = "com.google.android.material:material:_" public const val retrofit2_kotlinx_serialization_converter: String = "com.jakewharton.retrofit:retrofit2-kotlinx-serialization-converter:_" public const val okhttp: String = "com.squareup.okhttp3:okhttp:_" public const val retrofit: String = "com.squareup.retrofit2:retrofit:_" public const val de_fayard_buildsrclibs_gradle_plugin: String = "de.fayard.buildSrcLibs:de.fayard.buildSrcLibs.gradle.plugin:_" public const val junit: String = "junit:junit:_" public const val org_jacoco_ant: String = "org.jacoco:org.jacoco.ant:_" public const val kotlin_gradle_plugin: String = "org.jetbrains.kotlin:kotlin-gradle-plugin:_" public const val kotlinx_coroutines_android: String = "org.jetbrains.kotlinx:kotlinx-coroutines-android:_" public const val kotlinx_coroutines_test: String = "org.jetbrains.kotlinx:kotlinx-coroutines-test:_" public const val kotlinx_serialization_json: String = "org.jetbrains.kotlinx:kotlinx-serialization-json:_" }
10
Kotlin
0
0
6b9171a7c14a58cb7e9e9d07084b7c39570546c0
4,378
bermob-android-marvelous
MIT License
app/src/main/kotlin/jp/co/yumemi/android/code_check/search/SearchAdapter.kt
yuka1324
527,100,696
false
null
package jp.co.yumemi.android.code_check.search import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.TextView import androidx.recyclerview.widget.DiffUtil import androidx.recyclerview.widget.ListAdapter import androidx.recyclerview.widget.RecyclerView import jp.co.yumemi.android.code_check.R import jp.co.yumemi.android.code_check.data.SearchResultContents class SearchAdapter : ListAdapter<SearchResultContents, SearchAdapter.ViewHolder>(diffUtil) { private lateinit var listener: OnItemClickListener class ViewHolder(view: View) : RecyclerView.ViewHolder(view) interface OnItemClickListener { fun itemClick(item: SearchResultContents) } fun setOnItemClickListener(listener: OnItemClickListener) { this.listener = listener } override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder { val view = LayoutInflater.from(parent.context) .inflate(R.layout.layout_item, parent, false) return ViewHolder(view) } override fun onBindViewHolder(holder: ViewHolder, position: Int) { val item = getItem(position) (holder.itemView.findViewById<View>(R.id.repositoryNameView) as TextView).text = item.full_name holder.itemView.setOnClickListener { listener.itemClick(item) } } } val diffUtil = object : DiffUtil.ItemCallback<SearchResultContents>() { override fun areItemsTheSame( oldItem: SearchResultContents, newItem: SearchResultContents ): Boolean { return oldItem.full_name == newItem.full_name } override fun areContentsTheSame( oldItem: SearchResultContents, newItem: SearchResultContents ): Boolean { return oldItem == newItem } }
0
Kotlin
0
0
9261186fd2c38ea513da92709f91485ea9f0614c
1,829
android-engineer-codecheck
Apache License 2.0
app/src/main/java/edu/gvsu/art/gallery/ui/ArtistDetailScreen.kt
gvsucis
655,904,905
false
{"Kotlin": 293209, "Makefile": 1977, "Ruby": 1690, "Java": 1027}
package edu.gvsu.art.gallery.ui import androidx.compose.foundation.clickable import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.Spacer import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.height import androidx.compose.foundation.layout.padding import androidx.compose.foundation.lazy.LazyColumn import androidx.compose.foundation.lazy.items import androidx.compose.foundation.lazy.itemsIndexed import androidx.compose.foundation.lazy.rememberLazyListState import androidx.compose.material.icons.Icons import androidx.compose.material.icons.automirrored.filled.ArrowBack import androidx.compose.material3.ExperimentalMaterial3Api import androidx.compose.material3.HorizontalDivider import androidx.compose.material3.Icon import androidx.compose.material3.IconButton import androidx.compose.material3.LargeTopAppBar import androidx.compose.material3.MaterialTheme.colorScheme import androidx.compose.material3.MediumTopAppBar import androidx.compose.material3.Scaffold import androidx.compose.material3.Surface import androidx.compose.material3.Text import androidx.compose.material3.TopAppBarDefaults import androidx.compose.material3.TopAppBarDefaults.exitUntilCollapsedScrollBehavior import androidx.compose.runtime.Composable import androidx.compose.ui.Modifier import androidx.compose.ui.input.nestedscroll.nestedScroll import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.tooling.preview.Preview import androidx.compose.ui.unit.dp import androidx.navigation.NavController import edu.gvsu.art.client.Artist import edu.gvsu.art.gallery.extensions.nestedScaffoldPadding import edu.gvsu.art.gallery.lib.Async import edu.gvsu.art.gallery.navigateToArtworkDetail import edu.gvsu.art.gallery.ui.foundation.LocalTabScreen import edu.gvsu.art.gallery.ui.theme.ArtGalleryTheme @OptIn(ExperimentalMaterial3Api::class) @Composable fun ArtistDetailScreen(navController: NavController, artistID: String?) { artistID ?: return val currentTab = LocalTabScreen.current fun navigateToArtwork(artworkID: String) { navController.navigateToArtworkDetail(currentTab, artworkID) } val artist = when (val data = useArtist(artistID)) { is Async.Success -> data() else -> Artist() } val artistWorks = artist.relatedWorks val scrollState = rememberLazyListState() val scrollBehavior = exitUntilCollapsedScrollBehavior() Scaffold( modifier = Modifier.nestedScroll(scrollBehavior.nestedScrollConnection), topBar = { MediumTopAppBar( title = { Text(artist.name) }, colors = TopAppBarDefaults.topAppBarColors(containerColor = colorScheme.background), navigationIcon = { IconButton(onClick = { navController.popBackStack() }) { Icon(Icons.AutoMirrored.Filled.ArrowBack, contentDescription = null) } }, scrollBehavior = scrollBehavior, ) } ) { padding -> LazyColumn( state = scrollState, modifier = Modifier.nestedScaffoldPadding(padding) ) { item(key = "artist_biography") { ArtistDetailBiography(artist = artist) HorizontalDivider() } itemsIndexed( artistWorks, key = { _, artwork -> "artwork:${artwork.id}" } ) { index, artwork -> if (index == 0) { Spacer(Modifier.height(8.dp)) } ArtworkRow( artwork = artwork, modifier = Modifier .clickable { navigateToArtwork(artwork.id) } .fillMaxWidth() .padding(horizontal = 16.dp, vertical = 8.dp) ) } } } } @Composable private fun ArtistDetailBiography(artist: Artist) { Column( modifier = Modifier.padding(16.dp), verticalArrangement = Arrangement.spacedBy(8.dp) ) { Row( horizontalArrangement = Arrangement.spacedBy(8.dp) ) { if (artist.lifeDates.isNotBlank()) { Text( artist.lifeDates, fontWeight = FontWeight.SemiBold ) } if (artist.nationality.isNotBlank()) { Text(artist.nationality) } } if (artist.biography.isNotBlank()) { Text(artist.biography) } } } @Composable @Preview("ArtistDetailBiography light") fun PreviewArtistDetailBiography() { val artist = Artist( id = "637", name = "<NAME>", nationality = "German American", lifeDates = "1871-1938", biography = "Alten's view of Grand Rapids captured the expansion and development" + " of a city through images including its downtown streets," + " Reeds Lake and Alten's own backyard..." ) ArtGalleryTheme(darkTheme = false) { Surface { ArtistDetailBiography(artist = artist) } } } @Composable @Preview("ArtistDetailBiography dark") fun PreviewArtistDetailBiographyDark() { val artist = Artist( id = "637", name = "<NAME>", nationality = "German American", lifeDates = "1871-1938", biography = "Alten's view of Grand Rapids captured the expansion and development" + " of a city through images including its downtown streets," + " Reeds Lake and Alten's own backyard..." ) ArtGalleryTheme(darkTheme = true) { Surface { ArtistDetailBiography(artist = artist) } } }
2
Kotlin
1
1
cf747daea721238fc1287dba50cb71e386463b29
5,950
art-at-gvsu-android
Apache License 2.0
fabric/src/main/kotlin/me/ricky/forgric/fabric/FabricRegistry.kt
Ricky12Awesome
344,844,565
false
null
package me.ricky.forgric.fabric import me.ricky.forgric.common.* import net.minecraft.util.Identifier import net.minecraft.util.registry.MutableRegistry import net.minecraft.util.registry.Registry fun Id.toNativeId() = Identifier(namespace, path) class FabricRegistry<C : Any, T>( val registry: MutableRegistry<T>, val toNative: (C) -> T, ) : CommonRegistry<C> { val toCommon = mutableMapOf<Id, C>() override fun set(id: Id, value: C) { Registry.register(registry, id.toNativeId(), toNative(value)) toCommon[id] = value } override fun get(id: Id): C { return toCommon[id]!! } } class FabricRegistries(private val adaptor: FabricAdaptor) : CommonRegistries { val registries = mutableMapOf<CommonRegistries.Key<*>, CommonRegistry<*>>( CommonRegistries.Key.Item to FabricRegistry(Registry.ITEM, adaptor::toNativeItem), CommonRegistries.Key.Block to FabricRegistry(Registry.BLOCK, adaptor::toNativeBlock) ) override fun <T : Any> get(key: CommonRegistries.Key<T>): CommonRegistry<T> { return registries[key] as CommonRegistry<T> } }
0
Kotlin
0
0
4fb0b252c93f9eeff83fb053bbc1680b7184fb42
1,081
forgric
MIT License
src/test/kotlin/test/pl/treksoft/kvision/toolbar/ToolbarSpec.kt
wf-tlazenka
132,161,484
true
{"Kotlin": 657748, "CSS": 2721, "JavaScript": 1986, "HTML": 1858}
/* * Copyright (c) 2018. <NAME> */ package test.pl.treksoft.kvision.toolbar import pl.treksoft.kvision.panel.Root import pl.treksoft.kvision.toolbar.Toolbar import test.pl.treksoft.kvision.DomSpec import kotlin.browser.document import kotlin.test.Test class ToolbarSpec : DomSpec { @Test fun render() { run { val root = Root("test", true) val toolbar = Toolbar() root.add(toolbar) val element = document.getElementById("test") assertEqualsHtml( "<div class=\"btn-toolbar\" role=\"toolbar\"></div>", element?.innerHTML, "Should render correct toolbar" ) } } }
0
Kotlin
0
0
5f8c1decc2ec0d63ed97d7018a0d7cc6e4dc2667
713
kvision
MIT License
substrate-sdk-android/src/test/java/io/novasama/substrate_sdk_android/runtime/definitions/types/generics/EraTypeTest.kt
novasamatech
429,839,517
false
{"Kotlin": 647838, "Rust": 10421, "Java": 4208}
package io.novasama.substrate_sdk_android.runtime.definitions.types.generics import io.novasama.substrate_sdk_android.common.assertInstance import io.novasama.substrate_sdk_android.runtime.definitions.types.BaseTypeTest import io.novasama.substrate_sdk_android.runtime.definitions.types.fromHex import io.novasama.substrate_sdk_android.runtime.definitions.types.generics.Era.Companion.getPeriodPhaseFromBlockPeriod import io.novasama.substrate_sdk_android.runtime.definitions.types.toHex import org.junit.Assert.* import org.junit.Test class EraTypeTest : BaseTypeTest() { @Test fun `get period and phase from block number`() { val (period, phase) = getPeriodPhaseFromBlockPeriod(97506, 64) performMortalEncodeTest("0x2502", period, phase) } @Test fun `should decode immortal`() { val decoded = EraType.fromHex(runtime, "0x00") assertEquals(Era.Immortal, decoded) } @Test fun `should decode mortal`() { performMortalDecodeTest("0x4e9c", period = 32768, phase = 20000) performMortalDecodeTest("0xc503", period = 64, phase = 60) performMortalDecodeTest("0x8502", period = 64, phase = 40) } @Test fun `should encode immortal`() { val inHex = "0x00" val encoded = EraType.toHex(runtime, Era.Immortal) assertEquals(inHex, encoded) } @Test fun `should encode mortal`() { performMortalEncodeTest("0x4e9c", period = 32768, phase = 20000) performMortalEncodeTest("0xc503", period = 64, phase = 60) performMortalEncodeTest("0x8502", period = 64, phase = 40) } private fun performMortalDecodeTest(inHex: String, period: Int, phase: Int) { val decoded = EraType.fromHex(runtime, inHex) assertInstance<Era.Mortal>(decoded) assertEquals(period, decoded.period) assertEquals(phase, decoded.phase) } private fun performMortalEncodeTest(inHex: String, period: Int, phase: Int) { val encoded = EraType.toHex(runtime, Era.Mortal(period, phase)) assertEquals(inHex, encoded) } }
4
Kotlin
7
9
8deb9bcec9a5d9d74c509ccc6393cfd0b4ef7144
2,100
substrate-sdk-android
Apache License 2.0
android/src/main/kotlin/com/adapty/flutter/push/AdaptyFlutterPushHandler.kt
OnelightApps
431,496,730
true
{"Dart": 108394, "Kotlin": 38254, "Swift": 32840, "Ruby": 936, "Objective-C": 731}
package com.adapty.flutter.push import android.content.Context import com.adapty.flutter.R import com.adapty.push.AdaptyPushHandler class AdaptyFlutterPushHandler(context: Context) : AdaptyPushHandler(context) { override val clickAction = "ADAPTY_PROMO_CLICK_ACTION" override val smallIconResId = R.drawable.ic_adapty_promo_push }
0
Dart
0
0
a5b29caf648396455d9697cbd7899d865f6f94d8
342
AdaptySDK-Flutter
MIT License
jdk/src/main/kotlin/cz/petrbalat/klib/jdk/datetime/localDateUtils.kt
petrbalat
228,852,482
false
null
package cz.petrbalat.klib.jdk.datetime import java.sql.Timestamp import java.time.* import java.time.temporal.ChronoUnit import java.util.* /** * Created by <NAME> */ inline val today: LocalDate get() = LocalDate.now() inline val now: LocalDateTime get() = LocalDateTime.now() fun LocalDate?.orMin(): LocalDate = this ?: LocalDate.MIN fun LocalDate?.orMax(): LocalDate = this ?: LocalDate.MAX fun LocalDateTime?.orMin(): LocalDateTime = this ?: LocalDateTime.MIN fun LocalDateTime?.orMax(): LocalDateTime = this ?: LocalDateTime.MAX fun LocalDate.toDate(zoneId: ZoneId = ZoneId.systemDefault()): Date = atStartOfDay().toDate(zoneId) fun LocalDateTime.toInstant(zoneId: ZoneId = ZoneId.systemDefault()) = this.atZone(zoneId).toInstant() fun LocalDateTime.toDate(zoneId: ZoneId = ZoneId.systemDefault()): Date = Date.from(toInstant()) fun ZoneId.toOffset(): ZoneOffset = Instant.now().atZone(this).offset fun Date.toLocalDate(zoneId: ZoneId = ZoneId.systemDefault()): LocalDate = toLocalDateTime(zoneId).toLocalDate() fun Date.toLocalDateTime(zoneId: ZoneId = ZoneId.systemDefault()): LocalDateTime { val instant = Instant.ofEpochMilli(time) return LocalDateTime.ofInstant(instant, zoneId) } fun LocalDateTime.toOffsetDateTime(zoneId: ZoneId = ZoneId.systemDefault()): OffsetDateTime = atZone(zoneId).toOffsetDateTime() fun LocalDateTime.toSystemZone(): ZonedDateTime = atZone(ZoneId.systemDefault()) fun LocalDateTime.toUtcZone(): ZonedDateTime = atZone(ZoneOffset.UTC) fun ZonedDateTime.toUtcZone(): ZonedDateTime = withZoneSameInstant(ZoneOffset.UTC) fun LocalDateTime.toTimestamp(): Timestamp = Timestamp(toInstant().epochSecond) fun Long.toLocalDateTime(zoneId: ZoneId = ZoneId.systemDefault()): LocalDateTime { val instant = Instant.ofEpochMilli(this) return LocalDateTime.ofInstant(instant, zoneId) } fun Instant.toLocalDateTime(zoneId: ZoneId = ZoneId.systemDefault()): LocalDateTime = LocalDateTime.ofInstant(this, zoneId) fun LocalDateTime.removeSec(): LocalDateTime = LocalDateTime.of(year, month, dayOfMonth, hour, minute) infix fun LocalDateTime.duration(other: LocalDateTime): Duration = Duration.between(this, other) infix fun LocalDate.duration(other: LocalDate): Duration = Duration.between(this, other) infix fun LocalDate.period(other: LocalDate): Period = Period.between(this, other) fun LocalDateTime.isFuture(now: LocalDateTime = LocalDateTime.now()): Boolean = this >= now fun LocalDate.isFuture(now: LocalDate = today): Boolean = this > now infix fun LocalDate.minusDays(other: LocalDate): Long = ChronoUnit.DAYS.between(other, this) infix fun LocalDateTime.minusSecond(other: LocalDateTime): Long = ChronoUnit.SECONDS.between(other, this) infix fun LocalDateTime.minusMinutes(other: LocalDateTime): Long = ChronoUnit.MINUTES.between(other, this) infix fun LocalDateTime.minusHours(other: LocalDateTime): Long = ChronoUnit.HOURS.between(other, this) infix fun LocalDateTime.minusDays(other: LocalDateTime): Long = ChronoUnit.DAYS.between(other, this) fun LocalDate.startWeek(start: DayOfWeek = DayOfWeek.MONDAY, minus:Boolean = true): LocalDate { var day = this while (true) { val dayOfWeek: DayOfWeek = day.dayOfWeek if (dayOfWeek == start) return day day = if(minus) day.minusDays(1) else day.plusDays(1) } }
0
Kotlin
0
2
647d9daa241cfc751788e11b1ab84310fe998990
3,346
klib
MIT License
libraries/async/src/wasmJsMain/kotlin/com/zegreatrob/testmints/async/TestStyleAsync.wasmJs.kt
robertfmurdock
172,112,213
false
{"Kotlin": 174018, "JavaScript": 796, "Batchfile": 697, "Dockerfile": 282}
package com.zegreatrob.testmints.async import kotlinx.coroutines.await import kotlinx.coroutines.test.TestResult import kotlin.js.Promise actual suspend fun waitForTest(testFunction: () -> TestResult) { val testResult = testFunction() @Suppress("UNCHECKED_CAST_TO_EXTERNAL_INTERFACE", "CAST_NEVER_SUCCEEDS") (testResult as JsAny).unsafeCast<Promise<JsAny>>().await<JsAny?>() } actual fun <T> eventLoopProtect(thing: () -> T): T = thing()
0
Kotlin
2
5
2511f5495ccc1acb23297d03d826e60575225266
453
testmints
MIT License
libraries/async/src/wasmJsMain/kotlin/com/zegreatrob/testmints/async/TestStyleAsync.wasmJs.kt
robertfmurdock
172,112,213
false
{"Kotlin": 174018, "JavaScript": 796, "Batchfile": 697, "Dockerfile": 282}
package com.zegreatrob.testmints.async import kotlinx.coroutines.await import kotlinx.coroutines.test.TestResult import kotlin.js.Promise actual suspend fun waitForTest(testFunction: () -> TestResult) { val testResult = testFunction() @Suppress("UNCHECKED_CAST_TO_EXTERNAL_INTERFACE", "CAST_NEVER_SUCCEEDS") (testResult as JsAny).unsafeCast<Promise<JsAny>>().await<JsAny?>() } actual fun <T> eventLoopProtect(thing: () -> T): T = thing()
0
Kotlin
2
5
2511f5495ccc1acb23297d03d826e60575225266
453
testmints
MIT License
app/src/main/java/co/tami/basketball/team/data/source/fake/FakeData.kt
Hydratant
747,542,242
false
{"Kotlin": 96293}
@file:Suppress( "NonAsciiCharacters", "PrivatePropertyName", "SpellCheckingInspection", "ObjectPropertyName" ) package co.tami.basketball.team.data.source.fake import co.tami.basketball.team.data.PlayerAttributesData import co.tami.basketball.team.data.PlayerData import co.tami.basketball.team.data.PlayerPosition import co.tami.basketball.team.data.리바운드데이터 import co.tami.basketball.team.data.수비데이터 import co.tami.basketball.team.data.슛데이터 import co.tami.basketball.team.data.컨트롤데이터 import co.tami.basketball.team.data.패스데이터 import co.tami.basketball.team.data.피지컬데이터 private val 루카피지컬: 피지컬데이터 = 피지컬데이터( 속도 = 84, 가속 = 84, 힘 = 72, 지구력 = 98, 허슬 = 98 ) private val 루카슛: 슛데이터 = 슛데이터( 레이업 = 98, 미들슛 = 87, _3점슛 = 88, 자유투 = 83, 포스트훅 = 98, 센스 = 98, ) private val 루카컨트롤: 컨트롤데이터 = 컨트롤데이터( 볼컨트롤 = 98, 볼리시브 = 98, 드리블속도 = 83 ) private val 루카패스: 패스데이터 = 패스데이터( 정확도 = 98, 센스 = 98, 시야 = 96 ) private val 루카수비: 수비데이터 = 수비데이터( 박스아웃 = 66, 스틸 = 59, 블락 = 65, 도움수비 = 74, 패스차단 = 76, ) private val 루카리바운드: 리바운드데이터 = 리바운드데이터( 공격 = 68, 수비 = 81, 볼키핑 = 73 ) private val lukaAttributesData: PlayerAttributesData = PlayerAttributesData( 피지컬 = 루카피지컬, 슛 = 루카슛, 컨트롤 = 루카컨트롤, 패스 = 루카패스, 수비 = 루카수비, 리바운드 = 루카리바운드 ) val lukaPlayer: PlayerData = PlayerData( id = 0, name = "루카 돈치치", age = 34, jersey = 77, image = "test", positions = listOf( PlayerPosition.PG, PlayerPosition.SG ), attributes = lukaAttributesData ) private val 상혁피지컬: 피지컬데이터 = 피지컬데이터( 속도 = 84, 가속 = 84, 힘 = 72, 지구력 = 98, 허슬 = 98 ) private val 상혁슛: 슛데이터 = 슛데이터( 레이업 = 98, 미들슛 = 87, _3점슛 = 88, 자유투 = 83, 포스트훅 = 98, 센스 = 98, ) private val 상혁컨트롤: 컨트롤데이터 = 컨트롤데이터( 볼컨트롤 = 98, 볼리시브 = 98, 드리블속도 = 83 ) private val 상혁패스: 패스데이터 = 패스데이터( 정확도 = 98, 센스 = 98, 시야 = 96 ) private val 상혁수비: 수비데이터 = 수비데이터( 박스아웃 = 66, 스틸 = 59, 블락 = 65, 도움수비 = 74, 패스차단 = 76, ) private val 상혁리바운드: 리바운드데이터 = 리바운드데이터( 공격 = 68, 수비 = 81, 볼키핑 = 73 ) private val 상혁데이터: PlayerAttributesData = PlayerAttributesData( 피지컬 = 상혁피지컬, 슛 = 상혁슛, 컨트롤 = 상혁컨트롤, 패스 = 상혁패스, 수비 = 상혁수비, 리바운드 = 상혁리바운드 ) val 박상혁: PlayerData = PlayerData( id = 1, name = "박상혁", age = 34, jersey = 17, image = "test", positions = listOf( PlayerPosition.PG, PlayerPosition.SF ), attributes = 상혁데이터 )
2
Kotlin
0
0
fe817d06e63403b312ad37fca2ebeecd01b3d9d8
2,874
team
Apache License 2.0
src/main/kotlin/io/github/grassmc/mcdev/gradle/platform/pluginmeta/PluginMetaBase.kt
GrassMC
603,643,726
false
null
/* * Copyright 2023 GrassMC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.github.grassmc.mcdev.gradle.platform import org.gradle.api.Project import org.gradle.api.tasks.Input import org.gradle.api.tasks.Optional sealed class PluginMetaBase(project: Project) : PluginMeta { @get:Input override var main: String = "" @get:Input override var version: String = defaultVersion(project) @get:Input @get:Optional override var description: String? = project.description } sealed class NamedPluginMetaBase(project: Project) : NamedPlugin, PluginMetaBase(project) { @get:Input override var name: String = defaultName(project) } sealed class IdentifiedPluginMetaBase(project: Project) : IdentifiedPlugin, PluginMetaBase(project) { @get:Input override var id: String = defaultId(project) }
6
Kotlin
0
1
ee72e57643ddbb50f3a0c48c0797118cd443ef6f
1,357
mcdev-gradle-plugin
Apache License 2.0
legacy/src/test/java/jp/hazuki/yuzubrowser/legacy/action/item/CloseAutoSelectActionTest.kt
hazuki0x0
84,384,224
false
null
/* * Copyright (C) 2017-2019 DiepDT * * 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.onevn.browser.legacy.action.item import assertk.assertThat import assertk.assertions.isEqualTo import assertk.assertions.isInstanceOf import com.squareup.moshi.JsonReader import com.onevn.browser.legacy.action.SingleAction import okio.buffer import okio.source import org.junit.Test import java.io.ByteArrayInputStream class CloseAutoSelectActionTest { @Test fun testDecode() { val actionJson = "[[1001,null]]" val json = """{"0":$actionJson, "1":$actionJson, "2":$actionJson}""" val reader = JsonReader.of(ByteArrayInputStream(json.toByteArray()).source().buffer()) val action = CloseAutoSelectAction(SingleAction.PAGE_AUTO_SCROLL, reader) assertThat(action.defaultAction[0]).isInstanceOf(SingleAction::class.java) assertThat(action.intentAction[0]).isInstanceOf(SingleAction::class.java) assertThat(action.windowAction[0]).isInstanceOf(SingleAction::class.java) assertThat(action.defaultAction[0].id).isEqualTo(1001) assertThat(action.intentAction[0].id).isEqualTo(1001) assertThat(action.windowAction[0].id).isEqualTo(1001) assertThat(reader.peek()).isEqualTo(JsonReader.Token.END_DOCUMENT) } @Test fun testNothingDecode() { val actionJson = "[]" val json = """{"0":$actionJson, "1":$actionJson, "2":$actionJson}""" val reader = JsonReader.of(ByteArrayInputStream(json.toByteArray()).source().buffer()) val action = CloseAutoSelectAction(SingleAction.PAGE_AUTO_SCROLL, reader) assertThat(action.defaultAction.size).isEqualTo(0) assertThat(action.intentAction.size).isEqualTo(0) assertThat(action.windowAction.size).isEqualTo(0) assertThat(reader.peek()).isEqualTo(JsonReader.Token.END_DOCUMENT) } }
115
null
95
301
6a867f406b7fc6b29f1899c7ca622e7ce75fafa0
2,402
YuzuBrowser
Apache License 2.0
compiler/testData/psi/recovery/ForWithOnlyOneLParInEOF.kt
JakeWharton
99,388,807
false
null
fun test() = for (
179
null
5640
83
4383335168338df9bbbe2a63cb213a68d0858104
18
kotlin
Apache License 2.0
launch/src/main/java/cn/leizy/lauch/task/ITask.kt
Leizxy
223,341,470
false
{"Gradle": 8, "Java Properties": 2, "Text": 1, "Ignore List": 6, "Markdown": 1, "Proguard": 5, "Kotlin": 98, "XML": 26, "INI": 2, "Java": 5, "JSON": 1}
package cn.leizy.lauch.task import android.os.Process import androidx.annotation.IntRange import java.util.concurrent.Executor /** * @author Created by wulei * @date 2020/8/5, 005 * @description */ interface ITask { /** * 优先级的范围,可根据Task重要程度及工作量指定;之后根据实际情况决定是否有必要放更大 * * @return */ @IntRange(from = Process.THREAD_PRIORITY_FOREGROUND.toLong(), to = Process.THREAD_PRIORITY_LOWEST.toLong()) fun priority(): Int fun run() /** * Task执行所在的线程池,可指定,一般默认 * * @return */ fun runOn(): Executor? /** * 依赖关系 * * @return */ fun dependsOn(): List<Class<out Task?>?>? /** * 异步线程执行的Task是否需要在被调用await的时候等待,默认不需要 * * @return */ fun needWait(): Boolean /** * 是否在主线程执行 * * @return */ fun runOnMainThread(): Boolean /** * 只是在主进程执行 * * @return */ fun onlyInMainProcess(): Boolean /** * Task主任务执行完成之后需要执行的任务 * * @return */ fun getTailRunnable(): Runnable? fun setTaskCallBack(callBack: TaskCallback?) fun needCall(): Boolean }
0
Kotlin
0
0
7f3a0cd0343fd851f4d4accbe5ab65ebd3af6bd8
1,129
MyKotlinMVP
MIT License
src/main/kotlin/com/azhapps/lagbot/commands/ResumeCommand.kt
Azhrei251
447,149,817
false
{"Kotlin": 71940, "Dockerfile": 238, "Shell": 115}
package com.azhapps.lagbot.commands import com.azhapps.lagbot.commands.model.CommandContext fun Commands.resume(context: CommandContext) { val scheduler = context.scheduler if (scheduler == null) { context.onResponse("Nothing to resume!") } else { context.onResponse("Resumed") scheduler.resume() } }
4
Kotlin
0
1
b186db70d69da72e98a6ef628e4cef43f2d3209c
342
lagbot
Apache License 2.0
plugin/src/main/kotlin/ru/astrainteractive/astrashop/command/CommandManager.kt
Astra-Interactive
562,599,158
false
{"Kotlin": 72924}
package ru.astrainteractive.astrashop.command import ru.astrainteractive.astrashop.AstraShop import ru.astrainteractive.astrashop.command.di.CommandModule import ru.astrainteractive.klibs.kdi.Factory class CommandManager( private val plugin: AstraShop, private val module: CommandModule ) : Factory<Unit> { override fun create() { reload(plugin, module) shop(plugin, module) } }
3
Kotlin
1
0
ddad585065465555a50822aaeba0264be6e1dbc5
414
AstraShop
MIT License
android/src/main/java/ru/gbixahue/eu4d/android/text/transformer/chain/ColorDecorator.kt
GooSync
244,564,338
false
null
package ru.gbixahue.eu4d.android.text.transformer.chain import android.text.style.ForegroundColorSpan import androidx.annotation.ColorInt /** * Created by Anton Zhilenkov on 29.10.18. */ class ColorDecorator( @ColorInt private val color: Int, start: Int, end: Int, source: CharSequence? = null ): BaseChainDecorator<CharSequence>(start, end, source) { override fun transform(): CharSequence { val builder = getBuilder() builder.setSpan(ForegroundColorSpan(color), start, end, 0) return builder } }
0
Kotlin
0
0
3b7b64fc93e6560378fdbce612a6de1981df95a0
526
eu4d
Apache License 2.0
app/src/main/java/com/viatom/sevenweather/ui/place/PlaceViewModel.kt
sun-11225
410,492,840
false
null
package com.viatom.sevenweather.ui.place import androidx.lifecycle.MutableLiveData import androidx.lifecycle.Transformations import androidx.lifecycle.ViewModel import com.viatom.sevenweather.house.Repository import com.viatom.sevenweather.logic.dao.PlaceDao import com.viatom.sevenweather.logic.model.Place import java.util.* /** * @author:created by sunhao * 创建时间:2021/9/27 17:03 * 邮箱:sunhao@viatomtech.com * 类说明: Place ViewModel */ class PlaceViewModel : ViewModel() { private val searchLiveData = MutableLiveData<String>() //缓存城市数据 val placeList = LinkedList<Place>() //如果ViewModel中的某个LiveData对象是调用另外的方法获取的,借助switchMap()方法,将这个LiveData对象转换成另外一个可观察的LiveData对象。 val placeLiveData = Transformations.switchMap(searchLiveData) { query -> Repository.searchPlaces(query) } /** * 查询城市信息 * * @param query String */ fun searchPlaces(query: String) { searchLiveData.value = query } /** * 保存选中的城市 * * @param place Place */ fun savePlace(place: Place) = Repository.savePlace(place) /** * 获取保存的城市 * * @return Place */ fun getSavedPlace() = Repository.getSavedPlace() /** * 判断是否储存有城市数据 * * @return Boolean */ fun isPlaceSaved() = Repository.isPlaceSaved() }
1
null
1
1
01b74feaa50c3ee092565bf71f1910816c6c8909
1,316
SevenWeather
Apache License 2.0
hard/kotlin/c0004_30_substring-with-concatenation-of-all-words/00_leetcode_0004.kt
drunkwater
127,843,545
false
{"Text": 2, "Shell": 7, "Markdown": 3, "Perl": 12, "HTML": 3645, "C": 2246, "Java": 738, "Swift": 738, "Go": 738, "C#": 750, "Microsoft Visual Studio Solution": 4, "XML": 8, "Makefile": 1476, "Python": 1476, "Kotlin": 738, "Ruby": 738, "JavaScript": 738, "Scala": 738, "C++": 1484}
// DRUNKWATER TEMPLATE(add description and prototypes) // Question Title and Description on leetcode.com // Function Declaration and Function Prototypes on leetcode.com //30. Substring with Concatenation of All Words //You are given a string, s, and a list of words, words, that are all of the same length. Find all starting indices of substring(s) in s that is a concatenation of each word in words exactly once and without any intervening characters. //Example 1: //Input: // s = "barfoothefoobarman", // words = ["foo","bar"] //Output: [0,9] //Explanation: Substrings starting at index 0 and 9 are "barfoor" and "foobar" respectively. //The output order does not matter, returning [9,0] is fine too. //Example 2: //Input: // s = "wordgoodstudentgoodword", // words = ["word","student"] //Output: [] //class Solution { // fun findSubstring(s: String, words: Array<String>): List<Int> { // } //} // Time Is Money
1
null
1
1
8cc4a07763e71efbaedb523015f0c1eff2927f60
926
leetcode
Ruby License
browser/src/main/java/com/snxun/browser/module/fragment/IFragmentBackPressed.kt
YassKnight
316,117,283
false
{"Java": 185752, "Kotlin": 20265}
package com.snxun.browser.module.fragment /** * 让Fragment实现返回按钮监听接口 * Created by zhouL on 2018/6/20. */ interface IFragmentBackPressed { fun onPressBack(): Boolean }
1
Java
1
6
7ab89c738260ec36821819411dd96b569d7f94ce
173
LimeBrowser
Apache License 2.0
vuesaxicons/src/commonMain/kotlin/moe/tlaster/icons/vuesax/vuesaxicons/outline/Sidebarleft.kt
Tlaster
560,394,734
false
{"Kotlin": 25133302}
package moe.tlaster.icons.vuesax.vuesaxicons.outline import androidx.compose.ui.graphics.Color import androidx.compose.ui.graphics.PathFillType import androidx.compose.ui.graphics.PathFillType.Companion.NonZero import androidx.compose.ui.graphics.SolidColor import androidx.compose.ui.graphics.StrokeCap import androidx.compose.ui.graphics.StrokeCap.Companion.Butt import androidx.compose.ui.graphics.StrokeJoin 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 moe.tlaster.icons.vuesax.vuesaxicons.OutlineGroup public val OutlineGroup.Sidebarleft: ImageVector get() { if (_sidebarleft != null) { return _sidebarleft!! } _sidebarleft = Builder(name = "Sidebarleft", defaultWidth = 24.0.dp, defaultHeight = 24.0.dp, viewportWidth = 24.0f, viewportHeight = 24.0f).apply { path(fill = SolidColor(Color(0xFF292D32)), stroke = null, strokeLineWidth = 0.0f, strokeLineCap = Butt, strokeLineJoin = Miter, strokeLineMiter = 4.0f, pathFillType = NonZero) { moveTo(14.9707f, 22.75f) horizontalLineTo(8.9707f) curveTo(3.5407f, 22.75f, 1.2207f, 20.43f, 1.2207f, 15.0f) verticalLineTo(9.0f) curveTo(1.2207f, 3.57f, 3.5407f, 1.25f, 8.9707f, 1.25f) horizontalLineTo(14.9707f) curveTo(20.4007f, 1.25f, 22.7207f, 3.57f, 22.7207f, 9.0f) verticalLineTo(15.0f) curveTo(22.7207f, 20.43f, 20.4107f, 22.75f, 14.9707f, 22.75f) close() moveTo(8.9707f, 2.75f) curveTo(4.3607f, 2.75f, 2.7207f, 4.39f, 2.7207f, 9.0f) verticalLineTo(15.0f) curveTo(2.7207f, 19.61f, 4.3607f, 21.25f, 8.9707f, 21.25f) horizontalLineTo(14.9707f) curveTo(19.5807f, 21.25f, 21.2207f, 19.61f, 21.2207f, 15.0f) verticalLineTo(9.0f) curveTo(21.2207f, 4.39f, 19.5807f, 2.75f, 14.9707f, 2.75f) horizontalLineTo(8.9707f) close() } path(fill = SolidColor(Color(0xFF292D32)), stroke = null, strokeLineWidth = 0.0f, strokeLineCap = Butt, strokeLineJoin = Miter, strokeLineMiter = 4.0f, pathFillType = NonZero) { moveTo(7.9707f, 22.75f) curveTo(7.5607f, 22.75f, 7.2207f, 22.41f, 7.2207f, 22.0f) verticalLineTo(2.0f) curveTo(7.2207f, 1.59f, 7.5607f, 1.25f, 7.9707f, 1.25f) curveTo(8.3807f, 1.25f, 8.7207f, 1.59f, 8.7207f, 2.0f) verticalLineTo(22.0f) curveTo(8.7207f, 22.41f, 8.3907f, 22.75f, 7.9707f, 22.75f) close() } path(fill = SolidColor(Color(0xFF292D32)), stroke = null, strokeLineWidth = 0.0f, strokeLineCap = Butt, strokeLineJoin = Miter, strokeLineMiter = 4.0f, pathFillType = NonZero) { moveTo(14.9696f, 15.3099f) curveTo(14.7796f, 15.3099f, 14.5896f, 15.2399f, 14.4396f, 15.0899f) lineTo(11.8796f, 12.5299f) curveTo(11.5896f, 12.2399f, 11.5896f, 11.7599f, 11.8796f, 11.4699f) lineTo(14.4396f, 8.9099f) curveTo(14.7296f, 8.6199f, 15.2096f, 8.6199f, 15.4996f, 8.9099f) curveTo(15.7896f, 9.1999f, 15.7896f, 9.6799f, 15.4996f, 9.9699f) lineTo(13.4796f, 11.9999f) lineTo(15.5096f, 14.0299f) curveTo(15.7996f, 14.3199f, 15.7996f, 14.7999f, 15.5096f, 15.0899f) curveTo(15.3596f, 15.2399f, 15.1696f, 15.3099f, 14.9696f, 15.3099f) close() } } .build() return _sidebarleft!! } private var _sidebarleft: ImageVector? = null
0
Kotlin
0
2
b8a8231e6637c2008f675ae76a3423b82ee53950
4,102
VuesaxIcons
MIT License
src/main/kotlin/com/atlassian/performance/tools/jiraactions/api/action/CreateIssueAction.kt
atlassian
162,422,950
false
{"Kotlin": 214499, "Java": 1959}
package com.atlassian.performance.tools.jiraactions.api.action import com.atlassian.performance.tools.jiraactions.api.* import com.atlassian.performance.tools.jiraactions.api.measure.ActionMeter import com.atlassian.performance.tools.jiraactions.api.memories.ProjectMemory import org.apache.logging.log4j.LogManager import org.apache.logging.log4j.Logger class CreateIssueAction( private val jira: WebJira, private val meter: ActionMeter, private val projectMemory: ProjectMemory, private val seededRandom: SeededRandom ) : Action { private val logger: Logger = LogManager.getLogger(this::class.java) override fun run() { val project = projectMemory.recall() if (project == null) { logger.debug("Skipping Create issue action. I have no knowledge of projects.") return } meter.measure(CREATE_ISSUE) { val dashboardPage = meter.measure(VIEW_DASHBOARD) { jira.goToDashboard().waitForDashboard() }.apply { dismissAllPopups(); } val issueCreateDialog = dashboardPage.openIssueCreateDialog() val filledForm = issueCreateDialog .waitForDialog() .showAllFields() .selectProject(project.name) .selectIssueType( seededRandom.pick( issueCreateDialog.getIssueTypes().filter { it != "Epic" } )!! ) .fill("summary", "This is a simple summary") issueCreateDialog.fillRequiredFields() meter.measure(CREATE_ISSUE_SUBMIT) { filledForm.submit() } } } }
8
Kotlin
31
26
10b363eda1e171f8342eaeeb6deac843b1d34df3
1,705
jira-actions
Apache License 2.0
compiler/ir/backend.common/src/org/jetbrains/kotlin/backend/common/phaser/PhaseBuilders.kt
android
263,405,600
true
null
/* * Copyright 2010-2019 JetBrains s.r.o. and Kotlin Programming Language contributors. * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ package org.jetbrains.kotlin.backend.common.phaser import org.jetbrains.kotlin.backend.common.CommonBackendContext import org.jetbrains.kotlin.backend.common.FileLoweringPass import org.jetbrains.kotlin.backend.common.lower import org.jetbrains.kotlin.ir.IrElement import org.jetbrains.kotlin.ir.declarations.IrFile import org.jetbrains.kotlin.ir.declarations.IrModuleFragment // Phase composition. private class CompositePhase<Context : CommonBackendContext, Input, Output>( val phases: List<CompilerPhase<Context, Any?, Any?>> ) : CompilerPhase<Context, Input, Output> { override fun invoke(phaseConfig: PhaseConfig, phaserState: PhaserState<Input>, context: Context, input: Input): Output { @Suppress("UNCHECKED_CAST") var currentState = phaserState as PhaserState<Any?> var result = phases.first().invoke(phaseConfig, currentState, context, input) for ((previous, next) in phases.zip(phases.drop(1))) { if (next !is SameTypeCompilerPhase<*, *>) { // Discard `stickyPostcoditions`, they are useless since data type is changing. currentState = currentState.changeType() } currentState.stickyPostconditions.addAll(previous.stickyPostconditions) result = next.invoke(phaseConfig, currentState, context, result) } @Suppress("UNCHECKED_CAST") return result as Output } override fun getNamedSubphases(startDepth: Int): List<Pair<Int, AnyNamedPhase>> = phases.flatMap { it.getNamedSubphases(startDepth) } override val stickyPostconditions get() = phases.last().stickyPostconditions } @Suppress("UNCHECKED_CAST") infix fun <Context : CommonBackendContext, Input, Mid, Output> CompilerPhase<Context, Input, Mid>.then( other: CompilerPhase<Context, Mid, Output> ): CompilerPhase<Context, Input, Output> { val unsafeThis = this as CompilerPhase<Context, Any?, Any?> val unsafeOther = other as CompilerPhase<Context, Any?, Any?> return CompositePhase(if (this is CompositePhase<Context, *, *>) phases + unsafeOther else listOf(unsafeThis, unsafeOther)) } fun <Context : CommonBackendContext> namedIrModulePhase( name: String, description: String, prerequisite: Set<AnyNamedPhase> = emptySet(), lower: CompilerPhase<Context, IrModuleFragment, IrModuleFragment>, preconditions: Set<Checker<IrModuleFragment>> = emptySet(), postconditions: Set<Checker<IrModuleFragment>> = emptySet(), stickyPostconditions: Set<Checker<IrModuleFragment>> = lower.stickyPostconditions, actions: Set<Action<IrModuleFragment, Context>> = setOf(defaultDumper, validationAction), nlevels: Int = 1 ) = SameTypeNamedPhaseWrapper( name, description, prerequisite, lower, preconditions, postconditions, stickyPostconditions, actions, nlevels ) fun <Context : CommonBackendContext> namedIrFilePhase( name: String, description: String, prerequisite: Set<AnyNamedPhase> = emptySet(), lower: CompilerPhase<Context, IrFile, IrFile>, preconditions: Set<Checker<IrFile>> = emptySet(), postconditions: Set<Checker<IrFile>> = emptySet(), stickyPostconditions: Set<Checker<IrFile>> = lower.stickyPostconditions, actions: Set<Action<IrFile, Context>> = setOf(defaultDumper, validationAction), nlevels: Int = 1 ) = SameTypeNamedPhaseWrapper( name, description, prerequisite, lower, preconditions, postconditions, stickyPostconditions, actions, nlevels ) fun <Context : CommonBackendContext, Element : IrElement> makeCustomPhase( op: (Context, Element) -> Unit, description: String, name: String, prerequisite: Set<AnyNamedPhase> = emptySet(), preconditions: Set<Checker<Element>> = emptySet(), postconditions: Set<Checker<Element>> = emptySet(), stickyPostconditions: Set<Checker<Element>> = emptySet(), actions: Set<Action<Element, Context>> = setOf(defaultDumper, validationAction), nlevels: Int = 1 ) = SameTypeNamedPhaseWrapper( name, description, prerequisite, preconditions = preconditions, postconditions = postconditions, stickyPostconditions = stickyPostconditions, actions = actions, nlevels = nlevels, lower = object : SameTypeCompilerPhase<Context, Element> { override fun invoke( phaseConfig: PhaseConfig, phaserState: PhaserState<Element>, context: Context, input: Element ): Element { op(context, input) return input } } ) fun <Context : CommonBackendContext> namedUnitPhase( name: String, description: String, prerequisite: Set<AnyNamedPhase> = emptySet(), nlevels: Int = 1, lower: CompilerPhase<Context, Unit, Unit> ) = SameTypeNamedPhaseWrapper( name, description, prerequisite, lower = lower, nlevels = nlevels ) fun <Context : CommonBackendContext> namedOpUnitPhase( name: String, description: String, prerequisite: Set<AnyNamedPhase>, op: Context.() -> Unit ) = namedUnitPhase( name, description, prerequisite, nlevels = 0, lower = object : SameTypeCompilerPhase<Context, Unit> { override fun invoke(phaseConfig: PhaseConfig, phaserState: PhaserState<Unit>, context: Context, input: Unit) { context.op() } } ) fun <Context : CommonBackendContext> performByIrFile( name: String = "PerformByIrFile", description: String = "Perform phases by IrFile", prerequisite: Set<AnyNamedPhase> = emptySet(), preconditions: Set<Checker<IrModuleFragment>> = emptySet(), postconditions: Set<Checker<IrModuleFragment>> = emptySet(), stickyPostconditions: Set<Checker<IrModuleFragment>> = emptySet(), actions: Set<Action<IrModuleFragment, Context>> = setOf(defaultDumper), lower: CompilerPhase<Context, IrFile, IrFile> ) = namedIrModulePhase( name, description, prerequisite, preconditions = preconditions, postconditions = postconditions, stickyPostconditions = stickyPostconditions, actions = actions, nlevels = 1, lower = object : SameTypeCompilerPhase<Context, IrModuleFragment> { override fun invoke( phaseConfig: PhaseConfig, phaserState: PhaserState<IrModuleFragment>, context: Context, input: IrModuleFragment ): IrModuleFragment { for (irFile in input.files) { lower.invoke(phaseConfig, phaserState.changeType(), context, irFile) } // TODO: no guarantee that module identity is preserved by `lower` return input } override fun getNamedSubphases(startDepth: Int) = lower.getNamedSubphases(startDepth) } ) fun <Context : CommonBackendContext> makeIrFilePhase( lowering: (Context) -> FileLoweringPass, name: String, description: String, prerequisite: Set<AnyNamedPhase> = emptySet(), preconditions: Set<Checker<IrFile>> = emptySet(), postconditions: Set<Checker<IrFile>> = emptySet(), stickyPostconditions: Set<Checker<IrFile>> = emptySet(), actions: Set<Action<IrFile, Context>> = setOf(defaultDumper, validationAction) ) = namedIrFilePhase( name, description, prerequisite, preconditions = preconditions, postconditions = postconditions, stickyPostconditions = stickyPostconditions, actions = actions, nlevels = 0, lower = object : SameTypeCompilerPhase<Context, IrFile> { override fun invoke(phaseConfig: PhaseConfig, phaserState: PhaserState<IrFile>, context: Context, input: IrFile): IrFile { lowering(context).lower(input) return input } } ) fun <Context : CommonBackendContext> makeIrModulePhase( lowering: (Context) -> FileLoweringPass, name: String, description: String, prerequisite: Set<AnyNamedPhase> = emptySet(), preconditions: Set<Checker<IrModuleFragment>> = emptySet(), postconditions: Set<Checker<IrModuleFragment>> = emptySet(), stickyPostconditions: Set<Checker<IrModuleFragment>> = emptySet(), actions: Set<Action<IrModuleFragment, Context>> = setOf(defaultDumper, validationAction) ) = namedIrModulePhase( name, description, prerequisite, preconditions=preconditions, postconditions = postconditions, stickyPostconditions = stickyPostconditions, actions = actions, nlevels = 0, lower = object : SameTypeCompilerPhase<Context, IrModuleFragment> { override fun invoke( phaseConfig: PhaseConfig, phaserState: PhaserState<IrModuleFragment>, context: Context, input: IrModuleFragment ): IrModuleFragment { lowering(context).lower(input) return input } } ) fun <Context : CommonBackendContext, Input> unitPhase( name: String, description: String, prerequisite: Set<AnyNamedPhase>, preconditions: Set<Checker<Input>>, op: Context.() -> Unit ) = object : AbstractNamedPhaseWrapper<Context, Input, Unit>( name, description, prerequisite, preconditions = preconditions, nlevels = 0, lower = object : CompilerPhase<Context, Input, Unit> { override fun invoke(phaseConfig: PhaseConfig, phaserState: PhaserState<Input>, context: Context, input: Input) { context.op() } } ) {} fun <Context : CommonBackendContext, Input> unitSink() = object : CompilerPhase<Context, Input, Unit> { override fun invoke(phaseConfig: PhaseConfig, phaserState: PhaserState<Input>, context: Context, input: Input) {} } // Intermediate phases to change the object of transformations fun <Context : CommonBackendContext, OldData, NewData> takeFromContext(op: (Context) -> NewData) = object : CompilerPhase<Context, OldData, NewData> { override fun invoke(phaseConfig: PhaseConfig, phaserState: PhaserState<OldData>, context: Context, input: OldData) = op(context) } fun <Context : CommonBackendContext, OldData, NewData> transform(op: (OldData) -> NewData) = object : CompilerPhase<Context, OldData, NewData> { override fun invoke(phaseConfig: PhaseConfig, phaserState: PhaserState<OldData>, context: Context, input: OldData) = op(input) }
1
Kotlin
37
316
74126637a097f5e6b099a7b7a4263468ecfda144
10,509
kotlin
Apache License 2.0
src/main/kotlin/com/tddworks/spring/kotlin/examples/coroutines/user/api/UsersApi.kt
tddworks
863,607,454
false
{"Kotlin": 5929}
package com.tddworks.spring.kotlin.examples.coroutines.user.api import kotlinx.coroutines.flow.Flow interface UsersApi : FlowUsersApi { suspend fun createUser(user: User): User suspend fun getUser(id: Long): User? suspend fun updateUser(user: User): User suspend fun deleteUser(id: Long) suspend fun getUsers(): List<User> } interface FlowUsersApi { fun getFlowUsers(): Flow<User> }
0
Kotlin
0
0
1fdfd2ea4a4693d9aa247419851485806886292e
409
spring-kotlin-examples
Apache License 2.0
src/main/kotlin/io/github/projectmapk/jackson/module/kogera/deser/value_instantiator/KotlinValueInstantiator.kt
ProjectMapK
488,347,906
false
null
package com.fasterxml.jackson.module.kotlin.deser.value_instantiator import com.fasterxml.jackson.databind.BeanDescription import com.fasterxml.jackson.databind.DeserializationConfig import com.fasterxml.jackson.databind.DeserializationContext import com.fasterxml.jackson.databind.JavaType import com.fasterxml.jackson.databind.JsonMappingException import com.fasterxml.jackson.databind.deser.SettableBeanProperty import com.fasterxml.jackson.databind.deser.ValueInstantiator import com.fasterxml.jackson.databind.deser.ValueInstantiators import com.fasterxml.jackson.databind.deser.impl.NullsAsEmptyProvider import com.fasterxml.jackson.databind.deser.impl.PropertyValueBuffer import com.fasterxml.jackson.databind.deser.std.StdValueInstantiator import com.fasterxml.jackson.module.kotlin.MissingKotlinParameterException import com.fasterxml.jackson.module.kotlin.ReflectionCache import com.fasterxml.jackson.module.kotlin.deser.value_instantiator.creator.ValueCreator import java.lang.reflect.Executable private fun JsonMappingException.wrapWithPath(refFrom: Any?, refFieldName: String) = JsonMappingException.wrapWithPath(this, refFrom, refFieldName) internal class KotlinValueInstantiator( src: StdValueInstantiator, private val cache: ReflectionCache, private val nullToEmptyCollection: Boolean, private val nullToEmptyMap: Boolean, private val nullIsSameAsDefault: Boolean ) : StdValueInstantiator(src) { private fun JavaType.requireEmptyValue() = (nullToEmptyCollection && this.isCollectionLikeType) || (nullToEmptyMap && this.isMapLikeType) override fun createFromObjectWith( ctxt: DeserializationContext, props: Array<out SettableBeanProperty>, buffer: PropertyValueBuffer ): Any? { val valueCreator: ValueCreator<*> = cache.valueCreatorFromJava(_withArgsCreator.annotated as Executable) ?: return super.createFromObjectWith(ctxt, props, buffer) val bucket = valueCreator.generateBucket() valueCreator.valueParameters.forEachIndexed { idx, paramDef -> val jsonProp = props[idx] val isMissing = !buffer.hasParameter(jsonProp) if (isMissing && paramDef.isOptional) { return@forEachIndexed } var paramVal = if (!isMissing || paramDef.isPrimitive || jsonProp.hasInjectableValueId()) { buffer.getParameter(jsonProp).apply { if (nullIsSameAsDefault && this == null && paramDef.isOptional) return@forEachIndexed } } else { if (paramDef.isNullable) { // do not try to create any object if it is nullable and the value is missing null } else { // to get suitable "missing" value provided by deserializer jsonProp.valueDeserializer?.getAbsentValue(ctxt) } } if (paramVal == null) { if (jsonProp.type.requireEmptyValue()) { paramVal = NullsAsEmptyProvider(jsonProp.valueDeserializer).getNullValue(ctxt) } else { val isMissingAndRequired = isMissing && jsonProp.isRequired if (isMissingAndRequired || (!paramDef.isGenericType && !paramDef.isNullable)) { throw MissingKotlinParameterException( parameter = paramDef, processor = ctxt.parser, msg = "Instantiation of $valueTypeDesc value failed for JSON property ${jsonProp.name} " + "due to missing (therefore NULL) value for creator parameter ${paramDef.name} " + "which is a non-nullable type" ).wrapWithPath(this.valueClass, jsonProp.name) } } } bucket[idx] = paramVal } valueCreator.checkAccessibility(ctxt) return valueCreator.callBy(bucket) } private fun SettableBeanProperty.hasInjectableValueId(): Boolean = injectableValueId != null } internal class KotlinInstantiators( private val cache: ReflectionCache, private val nullToEmptyCollection: Boolean, private val nullToEmptyMap: Boolean, private val nullIsSameAsDefault: Boolean ) : ValueInstantiators { override fun findValueInstantiator( deserConfig: DeserializationConfig, beanDescriptor: BeanDescription, defaultInstantiator: ValueInstantiator ): ValueInstantiator { return if (beanDescriptor.beanClass.declaredAnnotations.any { it is Metadata }) { if (defaultInstantiator::class == StdValueInstantiator::class) { KotlinValueInstantiator( defaultInstantiator as StdValueInstantiator, cache, nullToEmptyCollection, nullToEmptyMap, nullIsSameAsDefault ) } else { // TODO: return defaultInstantiator and let default method parameters and nullability go unused? // or die with exception: throw IllegalStateException( "KotlinValueInstantiator requires that the default ValueInstantiator is StdValueInstantiator" ) } } else { defaultInstantiator } } }
7
null
1
85
8c2d7cbafefc35ab98bbb17506b9e2379923b1eb
5,490
jackson-module-kogera
Apache License 2.0
simplex/src/test/java/io/em2m/simplex/TreeTest.kt
em2m
114,274,216
false
null
package io.em2m.simplex import com.fasterxml.jackson.databind.SerializationFeature import com.fasterxml.jackson.module.kotlin.jacksonObjectMapper import com.fasterxml.jackson.module.kotlin.readValue import io.em2m.simplex.model.BasicKeyResolver import io.em2m.simplex.model.ConstKeyHandler import io.em2m.simplex.model.Expr import io.em2m.simplex.model.Key import io.em2m.simplex.parser.SimplexModule import io.em2m.simplex.std.Numbers import io.em2m.utils.coerce import org.junit.Assert.assertEquals import org.junit.Assert.assertNotNull import org.junit.Test import kotlin.test.assertTrue class TreeTest { val people = listOf(mapOf("name" to "Fred"), mapOf("name" to "Barney"), mapOf("name" to "Wilma"), mapOf("name" to "Betty")) val keyResolver = BasicKeyResolver(mapOf( Key("ns", "key1") to ConstKeyHandler("value1"), Key("ns", "key2") to ConstKeyHandler("value2"), Key("ns", "people") to ConstKeyHandler(people) )).delegate(Numbers.keys) val simplex = Simplex().keys(keyResolver) val mapper = jacksonObjectMapper().registerModule(SimplexModule(simplex)).enable(SerializationFeature.INDENT_OUTPUT) @Test fun testParseValue() { val expr: Expr = mapper.readValue(""" "#{ns:key1 | upperCase}" """.replace("#", "$")) val value = expr.call(emptyMap()) requireNotNull(expr) assertEquals("VALUE1", value) } @Test fun testParseObject() { val json = """ { "obj": { "v1": "#{ns:key1 | capitalize}", "v2": "#{ns:key2 | upperCase}" }, "value": "#{ns:key1} #{ns:key2}" } """.trimIndent().replace("#", "$") val rule: Rule = mapper.readValue(json) assertNotNull(rule) val obj = rule.obj.call(emptyMap()) as Map<String, Any?> assertNotNull(obj) assertEquals("Value1", obj["v1"]) assertEquals("VALUE2", obj["v2"]) val value = rule.value.call(emptyMap()) assertEquals("value1 value2", value) } data class Rule(val obj: Expr, val value: Expr) @Test fun testContainerWhen() { val json = """ { "foo": "bar", "@container": { "@when" : [ { "@if": "#{Bool:false}", "value": 1 }, { "value": 2 } ] } }""".replace("#", "$") val tree: Expr = mapper.readValue(json) val obj = tree.call(emptyMap()) assertEquals("{foo=bar, value=2}", obj.toString()) } @Test fun testValueWhen() { val json = """ { "@when" : [ { "@if": "#{Bool:false}", "@value": 1 }, { "@value": 2 } ] }""".replace("#", "$") val tree: Expr = mapper.readValue(json) val result = tree.call(emptyMap()) assertEquals(2, result) } @Test fun testRepeat() { val json = """ { "@repeat": "#{ns:people}", "name": "#{repeat:item.name}", "index": "#{repeat:index}" }""".replace("#", "$") val tree: Expr = mapper.readValue(json) val value = tree.call(emptyMap()) assertTrue { value is List<*> } } @Test fun testTags() { val json = """ { "Hello": { "@if": "#{ns:key1 | cond:StringEquals:value1}", "@repeat": "#{ns:people}", "name": "#{repeat:item.name}", "index": "#{repeat:index}", "@container": [ { "@if": "#{repeat:index | plus:1 | cond:NumberEquals:2}", "second": "This is the second item" }, { "@if": "#{repeat:odd}", "label": "This item is odd!" }, { "@if": "#{repeat:even}", "label": "This item is even!" }, { "@if": "#{repeat:last}", "last": "This is the last item!" }, { "@if": "#{repeat:first}", "first": "This is the first item!" }, { "index": "#{repeat:index}" } ] }, "Goodbye": { "@if": { "StringEquals": { "ns:key1" : "value1" } }, "@value": "Space" }, "PS": { "@when": [ { "@if": "#{repeat:first}", "label": "This is the first item!" }, { "@if": "#{repeat:index | plus:1 | cond:NumberEquals:2}", "label": "This is the second item" }, { "@if": "#{repeat:last}", "label": "This is the last item!" }, { "@if": "#{repeat:odd}", "label": "This item is odd and not first, second or last!!" }, { "label": "This item is even and not first, second, or last!" } ] }, "PSS": [ { "@if": "#{Bool:true}", "@value": 1 }, { "@if": "#{Bool:true}", "@value": 2 } ], "TestWhenValue": { "@when" : [ { "@if": "#{Bool:false}", "@value": 1 }, { "@value": 2 } ] } } """.trimIndent().replace("#", "$") println(json) val tree: Expr = mapper.readValue(json) val obj = tree.call(emptyMap()) println(mapper.writeValueAsString(obj)) assertNotNull(obj) assertEquals(2, obj.evalPath("PSS").coerce<List<Int>>()?.size) } }
2
Kotlin
14
3
89e0645d56e491a6a938c593c06330efe7752547
6,093
em2m-java-sdk
Apache License 2.0
app/src/main/java/com/example/myhealthpassport/ViewModels/AgentViewModel.kt
anuragkanojiya1
839,037,663
false
{"Kotlin": 171170}
package com.example.myhealthpassport.ViewModels import androidx.lifecycle.LiveData import androidx.lifecycle.MutableLiveData import androidx.lifecycle.ViewModel import androidx.lifecycle.viewModelScope import com.example.myhealthpassport.Agent.AgentInstance import com.example.myhealthpassport.Agent.MistralMessage import com.example.myhealthpassport.Agent.MistralRequest import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.launch import kotlinx.coroutines.withContext import retrofit2.HttpException class AgentViewModel : ViewModel() { private val mistralAgentApi = AgentInstance.mistralAgentApi // LiveData to hold the agent response private val _agentResponse = MutableLiveData<Result<String>>() val agentResponse: LiveData<Result<String>> = _agentResponse // Function to send query to the agent and update LiveData fun sendQueryToAgent(query: String) { viewModelScope.launch { try { // Create the request body val messages = listOf(MistralMessage(role = "user", content = query)) val request = MistralRequest(agent_id = "ag:54631716:20240929:untitled-agent:1c20a87a", messages = messages) // Make the API call val response = withContext(Dispatchers.IO) { mistralAgentApi.agentCompletion("Bearer 5WayNMBMumbUkfrDh3yoJDO9mdtn8niM", request).execute() } // Handle the API response if (response.isSuccessful) { val responseBody = response.body() val result = responseBody?.choices?.firstOrNull()?.message?.content _agentResponse.postValue(Result.success(result ?: "No content")) // Update LiveData } else { val errorResponse = response.errorBody()?.string() ?: "Unknown error" _agentResponse.postValue(Result.failure(Exception(errorResponse))) // Update LiveData with error } } catch (e: HttpException) { val errorMessage = e.response()?.errorBody()?.string() ?: "HTTP exception occurred" _agentResponse.postValue(Result.failure(Exception(errorMessage))) // Handle HTTP error } catch (e: Exception) { _agentResponse.postValue(Result.failure(e)) // Handle other exceptions } } } }
0
Kotlin
1
2
b2a7b5db4d083fa5f64b3d75a238d75e9f239549
2,419
MyHealthPassport
MIT License
samples/wearable-standalone/src/main/kotlin/researchstack/wearable/standalone/domain/usecase/profile/RegisterProfileUseCase.kt
S-ResearchStack
520,365,275
false
{"Kotlin": 178868, "AIDL": 4785}
package researchstack.wearable.standalone.domain.usecase.profile import researchstack.wearable.standalone.domain.model.UserProfileModel import researchstack.wearable.standalone.domain.repository.ProfileRepository import javax.inject.Inject class RegisterProfileUseCase @Inject constructor( private val profileRepository: ProfileRepository, ) { suspend operator fun invoke(userProfileModel: UserProfileModel): Result<Unit> { return profileRepository.registerProfile(userProfileModel) } }
0
Kotlin
20
26
58b4b9b64623a7d2a0865307d490a59a7538d7cd
509
app-sdk
Apache License 2.0
source_code/app/src/main/java/com/example/speakingtopics/network/apiservice/ApiServiceImpl.kt
radocodes
565,788,532
false
{"Kotlin": 26458}
package com.example.speakingtopics.network.apiservice import com.example.speakingtopics.network.ApiRoutes import com.example.speakingtopics.network.models.topics.JsonBinResponseModel import com.example.speakingtopics.network.models.topics.TopicResponseModel import io.ktor.client.* import io.ktor.client.call.* import io.ktor.client.request.* class ApiServiceImpl(private val httpClient: HttpClient) : ApiService { override suspend fun getDefaultTopics(): List<TopicResponseModel> { val result = httpClient.get(ApiRoutes.ALL_DEFAULT_TOPICS).body<JsonBinResponseModel>() return result.record } }
0
Kotlin
0
0
3d262bac0d3dece0e1993171021a5e217bd89714
620
Speaking-Topics
MIT License
app/src/main/java/com/rokoblak/chatbackup/ui/commonui/ConversationDisplay.kt
oblakr24
598,672,859
false
null
package com.rokoblak.chatbackup.commonui import androidx.compose.foundation.background import androidx.compose.foundation.layout.* import androidx.compose.material.Checkbox import androidx.compose.material.CheckboxDefaults import androidx.compose.material.MaterialTheme import androidx.compose.material.Text import androidx.compose.runtime.Composable import androidx.compose.ui.Modifier import androidx.compose.ui.graphics.Color import androidx.compose.ui.text.AnnotatedString import androidx.compose.ui.tooling.preview.Preview import androidx.compose.ui.unit.dp import androidx.constraintlayout.compose.ConstraintLayout import androidx.constraintlayout.compose.Dimension import com.rokoblak.chatbackup.ui.theme.ChatBackupTheme import com.rokoblak.chatbackup.ui.theme.LocalTypography data class ConversationDisplayData( val contactId: String, val number: String, val id: String, val title: AnnotatedString, val subtitle: AnnotatedString, val date: String, val checked: Boolean?, val avatar: AvatarData, ) @Composable fun ConversationDisplay( modifier: Modifier = Modifier, background: Color = MaterialTheme.colors.background, data: ConversationDisplayData, onCheckedChanged: (Boolean) -> Unit ) { ConstraintLayout( modifier = modifier .fillMaxWidth() .wrapContentHeight() .background(background) .padding(8.dp), ) { val (avatar, checkbox, title, subtitle, date) = createRefs() if (data.checked != null) { Checkbox( modifier = Modifier .constrainAs(checkbox) { start.linkTo(parent.start) top.linkTo(parent.top) } .height(36.dp), checked = data.checked, onCheckedChange = onCheckedChanged, colors = CheckboxDefaults.colors(), ) } else { Spacer(modifier = Modifier .widthIn(8.dp) .constrainAs(checkbox) { start.linkTo(parent.start) top.linkTo(parent.top) }) } AvatarBadge(data = data.avatar, modifier = Modifier.constrainAs(avatar) { start.linkTo(checkbox.end) top.linkTo(parent.top) }) Text( modifier = Modifier.constrainAs(title) { start.linkTo(avatar.end, 12.dp) top.linkTo(parent.top) }, text = data.title, style = LocalTypography.current.bodySemiBold ) Text( modifier = Modifier.constrainAs(subtitle) { start.linkTo(avatar.end, 12.dp) top.linkTo(title.bottom) end.linkTo(parent.end) width = Dimension.fillToConstraints }, text = data.subtitle, style = LocalTypography.current.captionRegular, ) Text( modifier = Modifier.constrainAs(date) { top.linkTo(parent.top) end.linkTo(parent.end) }, text = data.date, style = LocalTypography.current.captionRegular, ) } } @Preview @Composable fun ConversationDisplayPreview() { ChatBackupTheme { ConversationDisplay( data = ConversationDisplayData( contactId = "C_id1", id = "id1", number = "num1", title = AnnotatedString("Conv title"), subtitle = AnnotatedString("conv subtitle long message to make it really long and fit more than one line"), date = "13th Mar 2022 19:45:44", checked = true, avatar = AvatarData.Initials("CO", Color.Blue), ), onCheckedChanged = {} ) } }
0
null
0
2
ebca08b724a7663ec0cf36b70278b876cc0e315a
3,901
chat-backup-app
Apache License 2.0
buildSrc/src/main/kotlin/Versions.kt
rdietrichberlin
504,472,022
false
{"Kotlin": 55596}
object Versions { const val kotlin = "1.5.31" // "1.6.21" const val kotlinCoroutines = "1.5.2" const val mockk = "1.12.3" const val material = "1.6.1" const val gson = "2.9.0" const val retrofit = "2.9.0" const val okhttp = "4.9.0" const val junitJupiter = "5.6.2" const val koin = "3.1.5" object AndroidX { const val core = "1.7.0" const val annotation = "1.1.0" const val appcompat = "1.4.1" const val navigation = "2.4.2" const val extJUnit = "1.1.2" const val espresso = "3.4.0" } object AndroidArch { const val coreTesting = "2.1.0" } }
0
Kotlin
0
1
d74df262aed7e221cb27e87b34159e537e36c4d7
652
dbchallenge
MIT License
src/main/kotlin/com/jessecorbett/diskord/api/client/internal/RestClient.kt
incendium
163,341,694
true
{"Kotlin": 124695}
package com.jessecorbett.diskord.api.client.internal import com.jessecorbett.diskord.api.DiscordUserType import com.jessecorbett.diskord.api.exception.* import com.jessecorbett.diskord.internal.* import kotlinx.coroutines.delay import okhttp3.* import java.io.IOException import java.time.Instant import kotlin.coroutines.resume import kotlin.coroutines.resumeWithException import kotlin.coroutines.suspendCoroutine private const val discordApi = "https://discordapp.com/api" private fun jsonBody(value: Any?) = RequestBody.create(MediaType.get("application/json; charset=utf-8"), jsonMapper.writeValueAsString(value)) abstract class RestClient(val token: String, val userType: DiscordUserType) { private val rateInfo = RateLimitInfo(1, 1, Instant.MAX) var botUrl: String = defaultUserAgentUrl var botVersion: String = defaultUserAgentVersion fun getRateLimit() = rateInfo.limit fun getRateRemaining() = rateInfo.remaining fun getRateResetTime() = rateInfo.resetTime private fun captureFailure(response: Response) { when (response.code()) { 400 -> throw DiscordBadRequestException(response.body()?.string()) 401 -> throw DiscordUnauthorizedException() 403 -> throw DiscordBadPermissionsException() 404 -> throw DiscordNotFoundException() 429 -> response.bodyAs<RateLimitExceeded>().let { throw DiscordRateLimitException(it.message, Instant.now().plusMillis(it.retryAfter), it.isGlobal) } 502 -> throw DiscordGatewayException() in 500..599 -> throw DiscordInternalServerException() } } private fun commonRequest(url: String) = Request.Builder() .url(discordApi + url) .header("Authorization", "$userType $token") .header("User-Agent", "DiscordBot: ($botUrl, $botVersion)") private suspend fun makeRequest(request: Request, rateLimit: RateLimitInfo): Response { if (rateLimit.remaining < 1) { delay(rateLimit.resetTime.toEpochMilli() - Instant.now().toEpochMilli()) } try { return suspendCoroutine { cont -> httpClient.newCall(request).enqueue(object : Callback { override fun onFailure(call: Call, exception: IOException) { cont.resumeWithException(exception) } override fun onResponse(call: Call, response: Response) { rateInfo.limit = response.header("X-RateLimit-Limit")?.toInt() ?: rateLimit.limit rateLimit.remaining = response.header("X-RateLimit-Remaining")?.toInt() ?: rateLimit.remaining rateLimit.resetTime = Instant.ofEpochSecond(response.headers().get("X-RateLimit-Reset")?.toLong() ?: rateLimit.resetTime.epochSecond) if (!response.isSuccessful) { try { captureFailure(response) } catch (discordException: DiscordException) { cont.resumeWithException(discordException) return } } cont.resume(response) } }) } } catch (rateLimitException: DiscordRateLimitException) { return makeRequest(request, rateLimit) } } protected suspend fun getRequest(url: String, rateLimit: RateLimitInfo = rateInfo) = makeRequest(commonRequest(url).get().build(), rateLimit) protected suspend fun postRequest(url: String, body: Any, rateLimit: RateLimitInfo = rateInfo) = makeRequest(commonRequest(url).post(jsonBody(body)).build(), rateLimit) protected suspend fun postRequest(url: String, rateLimit: RateLimitInfo = rateInfo) = makeRequest(commonRequest(url).post(jsonBody(null)).build(), rateLimit) protected suspend fun putRequest(url: String, body: Any, rateLimit: RateLimitInfo = rateInfo) = makeRequest(commonRequest(url).put(jsonBody(body)).build(), rateLimit) protected suspend fun putRequest(url: String, rateLimit: RateLimitInfo = rateInfo) = makeRequest(commonRequest(url).put(jsonBody(null)).build(), rateLimit) protected suspend fun patchRequest(url: String, body: Any, rateLimit: RateLimitInfo = rateInfo) = makeRequest(commonRequest(url).patch(jsonBody(body)).build(), rateLimit) protected suspend fun deleteRequest(url: String, rateLimit: RateLimitInfo = rateInfo) = makeRequest(commonRequest(url).delete().build(), rateLimit) }
0
Kotlin
0
0
53d1f557d0cafc0a8d85f5333405df60bfffebe6
4,672
Diskord
The Unlicense
uranium-arkade-htmlcanvas/src/jsMain/kotlin/pl/karol202/uranium/arkade/htmlcanvas/dom/input/NativeKeyboardEvent.kt
karol-202
269,330,616
false
null
package pl.karol202.uranium.arkade.htmlcanvas.dom.input import org.w3c.dom.events.KeyboardEvent internal actual class NativeKeyboardEvent(private val event: KeyboardEvent) { actual val type get() = event.type actual val key get() = event.key actual val code get() = event.code actual val repeat get() = event.repeat actual val altKey get() = event.altKey actual val ctrlKey get() = event.ctrlKey actual val metaKey get() = event.metaKey actual val shiftKey get() = event.shiftKey }
1
Kotlin
1
3
ed458611e89b2bdb85d0a23c30c9dd6c0611d30f
492
uranium-arkade
MIT License
testSrc/com/koxudaxi/poetry/PoetryTestCase.kt
koxudaxi
262,716,981
false
null
package com.koxudaxi.poetry import com.intellij.openapi.vfs.VirtualFile import com.intellij.openapi.vfs.impl.local.LocalFileSystemImpl import com.intellij.testFramework.fixtures.BasePlatformTestCase import org.jetbrains.kotlin.konan.file.File abstract class PoetryTestCase : BasePlatformTestCase() { protected open val testClassName: String = this.javaClass.simpleName.replace("Test", "") protected val dataDir: String get() { return "testData" + File.separator + testClassName + File.separator + getTestName(true) } fun getTestData(fileName: String): VirtualFile { return LocalFileSystemImpl.getInstance().findFileByPath(dataDir + File.separator + fileName)!! } fun getTestDataAsText(fileName: String): String { return getTestData(fileName).inputStream.bufferedReader().readText() } }
27
Kotlin
14
178
51b33be1c68a151459c8fb4cb5bedd1f93c502f4
857
poetry-pycharm-plugin
Apache License 2.0
app-examples/example-kt-03adapters/src/test/java/foo/bar/example/foreadapterskt/feature/playlist/MutablePlaylistModelTest.kt
erdo
92,027,307
false
null
package foo.bar.example.foreadapterskt.feature.playlist import org.junit.Assert import org.junit.Before import org.junit.Test import co.early.fore.adapters.mutable.UpdateSpec import co.early.fore.kt.core.logging.SystemLogger import co.early.fore.core.observer.Observer import co.early.fore.core.time.SystemTimeWrapper import co.early.fore.kt.core.delegate.Fore import co.early.fore.kt.core.delegate.TestDelegateDefault import foo.bar.example.foreadapterskt.feature.playlist.mutable.MutablePlaylistModel import io.mockk.MockKAnnotations import io.mockk.every import io.mockk.impl.annotations.MockK import io.mockk.verify import io.mockk.mockk /** * */ class MutablePlaylistModelTest { private val logger = SystemLogger() private lateinit var playlistAdvancedModel: MutablePlaylistModel @MockK private lateinit var mockSystemTimeWrapper: SystemTimeWrapper private val RELAXED_AGE_LIMIT_FOR_UPDATE_SPEC: Long = 500 private val ACTUAL_AGE_LIMIT_FOR_UPDATE_SPEC: Long = 50 @Before fun setup() { MockKAnnotations.init(this, relaxed = true) // make the code run synchronously, reroute Log.x to // System.out.println() so we see it in the test log Fore.setDelegate(TestDelegateDefault()) playlistAdvancedModel = MutablePlaylistModel(logger) } @Test @Throws(Exception::class) fun initialConditions() { //arrange //act //assert Assert.assertEquals(0, playlistAdvancedModel.getItemCount().toLong()) Assert.assertEquals(false, playlistAdvancedModel.hasObservers()) Assert.assertEquals(UpdateSpec.UpdateType.FULL_UPDATE, playlistAdvancedModel.getAndClearLatestUpdateSpec(50).type) } @Test @Throws(Exception::class) fun addNewTrack() { //arrange //act playlistAdvancedModel.addNTracks(1) //assert Assert.assertEquals(1, playlistAdvancedModel.getItemCount().toLong()) Assert.assertEquals(1, playlistAdvancedModel.getItem(0).numberOfPlaysRequested.toLong()) } @Test @Throws(Exception::class) fun removeTrack() { //arrange playlistAdvancedModel.addNTracks(1) //act playlistAdvancedModel.removeTrack(0) //assert Assert.assertEquals(0, playlistAdvancedModel.getItemCount().toLong()) } @Test @Throws(Exception::class) fun add5NewTracks() { //arrange //act playlistAdvancedModel.addNTracks(5) //assert Assert.assertEquals(5, playlistAdvancedModel.getItemCount().toLong()) Assert.assertEquals(1, playlistAdvancedModel.getItem(4).numberOfPlaysRequested.toLong()) } @Test @Throws(Exception::class) fun remove5Tracks() { //arrange playlistAdvancedModel.addNTracks(5) //act playlistAdvancedModel.removeNTracks(5) //assert Assert.assertEquals(0, playlistAdvancedModel.getItemCount().toLong()) } @Test @Throws(Exception::class) fun increasePlays() { //arrange playlistAdvancedModel.addNTracks(1) //act playlistAdvancedModel.increasePlaysForTrack(0) //assert Assert.assertEquals(2, playlistAdvancedModel.getItem(0).numberOfPlaysRequested.toLong()) } @Test @Throws(Exception::class) fun decreasePlays() { //arrange playlistAdvancedModel.addNTracks(1) playlistAdvancedModel.increasePlaysForTrack(0) //act playlistAdvancedModel.decreasePlaysForTrack(0) //assert Assert.assertEquals(1, playlistAdvancedModel.getItem(0).numberOfPlaysRequested.toLong()) } @Test @Throws(Exception::class) fun removeAllTracks() { //arrange playlistAdvancedModel.addNTracks(5) playlistAdvancedModel.addNTracks(1) playlistAdvancedModel.addNTracks(1) //act playlistAdvancedModel.removeAllTracks() //assert Assert.assertEquals(0, playlistAdvancedModel.getItemCount().toLong()) } /** * * NB all we are checking here is that observers are called AT LEAST once * * We don't really want tie our tests (OR any observers in production code) * to an expected number of times this method might be called. (This would be * testing an implementation detail and make the tests unnecessarily brittle) * * The contract says nothing about how many times observers will get called, * only that they will be called if something changes ("something" is not defined * and can change between implementations). * * See the databinding readme for more information about this * * @throws Exception */ @Test @Throws(Exception::class) fun observersNotifiedAtLeastOnceForAddTrack() { //arrange val mockObserver: Observer = mockk(relaxed = true) playlistAdvancedModel.addObserver(mockObserver) //act playlistAdvancedModel.addNTracks(1) //assert verify(atLeast = 1) { mockObserver.somethingChanged() } } @Test @Throws(Exception::class) fun observersNotifiedAtLeastOnceForIncreasePlays() { //arrange playlistAdvancedModel.addNTracks(1) val mockObserver: Observer = mockk(relaxed = true) playlistAdvancedModel.addObserver(mockObserver) //act playlistAdvancedModel.increasePlaysForTrack(0) //assert verify(atLeast = 1) { mockObserver.somethingChanged() } } /** * * Here we make some tests to verify the UpdateSpec returned is correct so that we * know that we can correctly drive a ChangeAwareAdapter with this model * * @throws Exception */ @Test @Throws(Exception::class) fun updateSpecCorrectForAddTrack() { //arrange //act playlistAdvancedModel.addNTracks(1) //assert val updateSpec = playlistAdvancedModel.getAndClearLatestUpdateSpec(RELAXED_AGE_LIMIT_FOR_UPDATE_SPEC) Assert.assertEquals(UpdateSpec.UpdateType.ITEM_INSERTED, updateSpec.type) Assert.assertEquals(0, updateSpec.rowPosition.toLong()) Assert.assertEquals(1, updateSpec.rowsEffected.toLong()) } @Test @Throws(Exception::class) fun updateSpecCorrectForIncreasePlays() { //arrange playlistAdvancedModel.addNTracks(1) playlistAdvancedModel.addNTracks(5) //act playlistAdvancedModel.increasePlaysForTrack(3) //assert val updateSpec = playlistAdvancedModel.getAndClearLatestUpdateSpec(RELAXED_AGE_LIMIT_FOR_UPDATE_SPEC) Assert.assertEquals(UpdateSpec.UpdateType.ITEM_CHANGED, updateSpec.type) Assert.assertEquals(3, updateSpec.rowPosition.toLong()) Assert.assertEquals(1, updateSpec.rowsEffected.toLong()) } @Test @Throws(Exception::class) fun updateSpecCorrectForRemove5Tracks() { //arrange playlistAdvancedModel.addNTracks(5) playlistAdvancedModel.addNTracks(1) //act playlistAdvancedModel.removeNTracks(5) //assert val updateSpec = playlistAdvancedModel.getAndClearLatestUpdateSpec(RELAXED_AGE_LIMIT_FOR_UPDATE_SPEC) Assert.assertEquals(UpdateSpec.UpdateType.ITEM_REMOVED, updateSpec.type) Assert.assertEquals(0, updateSpec.rowPosition.toLong()) Assert.assertEquals(5, updateSpec.rowsEffected.toLong()) } @Test @Throws(Exception::class) fun updateSpecCorrectForClearAllTracks() { //arrange playlistAdvancedModel.addNTracks(5) playlistAdvancedModel.addNTracks(1) //act playlistAdvancedModel.removeAllTracks() //assert val updateSpec = playlistAdvancedModel.getAndClearLatestUpdateSpec(RELAXED_AGE_LIMIT_FOR_UPDATE_SPEC) Assert.assertEquals(UpdateSpec.UpdateType.ITEM_REMOVED, updateSpec.type) Assert.assertEquals(0, updateSpec.rowPosition.toLong()) Assert.assertEquals(6, updateSpec.rowsEffected.toLong()) } @Test @Throws(Exception::class) fun updateSpecCorrectWithinMaxAge() { //arrange Fore.setDelegate(TestDelegateDefault(systemTimeWrapper = mockSystemTimeWrapper)) playlistAdvancedModel.addNTracks(5) playlistAdvancedModel.addNTracks(1) //act playlistAdvancedModel.increasePlaysForTrack(3) every { mockSystemTimeWrapper.currentTimeMillis() } returns (ACTUAL_AGE_LIMIT_FOR_UPDATE_SPEC - 1) //assert val updateSpec = playlistAdvancedModel.getAndClearLatestUpdateSpec(ACTUAL_AGE_LIMIT_FOR_UPDATE_SPEC) Assert.assertEquals(UpdateSpec.UpdateType.ITEM_CHANGED, updateSpec.type) Assert.assertEquals(3, updateSpec.rowPosition.toLong()) Assert.assertEquals(1, updateSpec.rowsEffected.toLong()) } @Test @Throws(Exception::class) fun updateSpecCorrectPastMaxAge() { //arrange Fore.setDelegate(TestDelegateDefault(systemTimeWrapper = mockSystemTimeWrapper)) playlistAdvancedModel.addNTracks(5) playlistAdvancedModel.addNTracks(1) //act playlistAdvancedModel.increasePlaysForTrack(3) every { mockSystemTimeWrapper.currentTimeMillis() } returns (ACTUAL_AGE_LIMIT_FOR_UPDATE_SPEC + 1) //assert val updateSpec = playlistAdvancedModel.getAndClearLatestUpdateSpec(ACTUAL_AGE_LIMIT_FOR_UPDATE_SPEC) Assert.assertEquals(UpdateSpec.UpdateType.FULL_UPDATE, updateSpec.type) Assert.assertEquals(0, updateSpec.rowPosition.toLong()) Assert.assertEquals(0, updateSpec.rowsEffected.toLong()) } }
3
null
4
46
1af5bd3ad9b2395a636fac12c40016fd2c815d0c
9,791
android-fore
Apache License 2.0
ExampleApp/app/src/main/java/com/example/exampleapp/ui/fragments/main/MainFragment.kt
MarkMurillo
444,558,624
false
{"Kotlin": 20766}
package com.example.exampleapp.ui.fragments.main import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.fragment.app.viewModels import com.example.exampleapp.databinding.MainFragmentBinding import com.example.exampleapp.ui.common.BaseFragment import com.example.exampleapp.ui.common.BaseViewModel import com.example.exampleapp.ui.fragments.main.MainViewModel import dagger.hilt.android.AndroidEntryPoint /** * Fragments and activities MUST have the @AndroidEntryPoint annotation. */ @AndroidEntryPoint class MainFragment : BaseFragment() { /** * use viewModels() to scope it to this fragment * use activityViewModels() to scope it to its activity */ private val viewModel by viewModels<MainViewModel>() override fun getViewModel(): BaseViewModel = viewModel override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View { val binding = MainFragmentBinding.inflate(inflater, container, false) binding.nextButton.setOnClickListener { viewModel.navigateToNextFragment() } binding.secondActivityButton.setOnClickListener { viewModel.navigateToSecondActivity() } binding.message.text = viewModel.appName return binding.root } }
0
Kotlin
0
0
bc1eaf9fefc3229f34f00a56bb91b1c170b7823a
1,395
android_example
MIT License
app/src/main/java/com/joshhn/workoutapp/ExerciseStatusAdapter.kt
joshhn
508,356,450
false
null
package com.example.a7minutesworkout import android.graphics.Color import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.core.content.ContextCompat import androidx.recyclerview.widget.RecyclerView import com.example.a7minutesworkout.databinding.ItemExerciseStatusBinding class ExerciseStatusAdapter(val items: ArrayList<ExerciseModel>): RecyclerView.Adapter<ExerciseStatusAdapter.ViewHolder>() { class ViewHolder(binding: ItemExerciseStatusBinding): RecyclerView.ViewHolder(binding.root){ val tvItem = binding.tvItem } override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder { return ViewHolder(ItemExerciseStatusBinding.inflate(LayoutInflater.from(parent .context),parent,false)) } override fun onBindViewHolder(holder: ViewHolder, position: Int) { val model : ExerciseModel = items[position] holder.tvItem.text = model.getId().toString() when { model.getIsSelected() -> { holder.tvItem.background = ContextCompat.getDrawable( holder.itemView.context, R.drawable.item_circular_thin_color_accent_border ) holder.tvItem.setTextColor(Color.parseColor("#212121")) } model.getIsCompleted() -> { holder.tvItem.background = ContextCompat.getDrawable( holder.itemView.context, R.drawable.item_circular_color_accent_background ) holder.tvItem.setTextColor(Color.parseColor("#FFFFFF")) } else->{ holder.tvItem.background = ContextCompat.getDrawable( holder.itemView.context, R.drawable.item_circular_color_gray_background ) holder.tvItem.setTextColor(Color.parseColor("#212121")) } } } override fun getItemCount(): Int { return items.size } }
0
Kotlin
0
2
105cdf2d525cfd92c475687096c94b39adf35f77
2,369
WorkoutApp
Apache License 2.0
app/src/main/kotlin/com/ivanovsky/passnotes/data/entity/EncryptedDatabaseElement.kt
aivanovski
95,774,290
false
null
package com.ivanovsky.passnotes.data.entity /** * Interface for [Group], [Note] and [Property] */ interface EncryptedDatabaseElement
6
null
4
53
83605c13c7f13e1f484aa00f6b3e9af622880888
135
keepassvault
Apache License 2.0
domain/src/main/java/com/linhtetko/domain/repositories/WeatherRepository.kt
lin-htet-ko
726,358,254
false
{"Kotlin": 95925, "CMake": 1249, "C++": 502}
package com.linhtetko.domain.repositories import com.linhtetko.domain.vos.WeatherVO import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.flow.Flow interface WeatherRepository { suspend fun addCurrentWeather(weather: WeatherVO) suspend fun addForecastWeathers(weathers: List<WeatherVO>) fun getCurrentWeather(): Flow<WeatherVO?> fun get5DaysForecastWeathers(): Flow<List<WeatherVO>> suspend fun requestCurrentWeather( scope: CoroutineScope, city: String, onSuccess: (WeatherVO?) -> Unit, onFailure: (String) -> Unit ) suspend fun searchWeatherByCity( city: String, onSuccess: (WeatherVO?) -> Unit, onFailure: (String) -> Unit ) suspend fun request5DaysForecastWeathers( scope: CoroutineScope, city: String, onSuccess: (List<WeatherVO>) -> Unit, onFailure: (String) -> Unit ) }
0
Kotlin
0
0
dea33ddf60850d8e3ec8fc6d121cb161ea65bd1a
926
efficient_weather_app
Apache License 2.0
shared-ui/src/commonMain/kotlin/com/foreverrafs/superdiary/ui/feature/creatediary/screen/CreateDiaryScreen.kt
rafsanjani
315,355,130
false
null
package com.foreverrafs.superdiary.ui.feature.creatediary.screen import androidx.compose.runtime.Composable import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.runtime.rememberCoroutineScope import androidx.compose.runtime.setValue import cafe.adriel.voyager.core.screen.Screen import cafe.adriel.voyager.koin.getScreenModel import com.foreverrafs.superdiary.data.model.Diary import com.foreverrafs.superdiary.ui.LocalScreenNavigator import kotlinx.coroutines.flow.catch import kotlinx.coroutines.flow.onCompletion import kotlinx.coroutines.flow.onStart import kotlinx.coroutines.launch import kotlinx.datetime.Clock class CreateDiaryScreen : Screen { @Composable override fun Content() { val createDiaryScreenModel: CreateDiaryViewModel = getScreenModel() val navigator = LocalScreenNavigator.current val undoManager = rememberUndoableRichTextState() val richTextState = undoManager.richTextState val coroutineScope = rememberCoroutineScope() var isGeneratingFromAI by remember { mutableStateOf(false) } CreateDiaryScreenContent( onNavigateBack = navigator::pop, richTextState = richTextState, isGeneratingFromAi = isGeneratingFromAI, onGenerateAI = { prompt, wordCount -> undoManager.save() var generatedWords = "" coroutineScope.launch { createDiaryScreenModel .generateAIDiary( prompt = prompt, wordCount = wordCount, ) .onStart { isGeneratingFromAI = true richTextState.setHtml("<p>Generating diary...</p>") } .catch { isGeneratingFromAI = false richTextState.setHtml("<p style=\"color:red\">Error generating entry</p>") } .onCompletion { isGeneratingFromAI = false } .collect { chunk -> generatedWords += chunk richTextState.setHtml("<p>$generatedWords</p>") } } }, ) { entry -> createDiaryScreenModel.saveDiary( Diary( entry = entry, date = Clock.System.now(), isFavorite = false, ), ) navigator.pop() } } }
14
null
0
8
4db59c9093ddac1360a6457f886bf57121bfe5ed
2,792
superdiary
MIT License
shared-ui/src/commonMain/kotlin/com/foreverrafs/superdiary/ui/feature/creatediary/screen/CreateDiaryScreen.kt
rafsanjani
315,355,130
false
null
package com.foreverrafs.superdiary.ui.feature.creatediary.screen import androidx.compose.runtime.Composable import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.runtime.rememberCoroutineScope import androidx.compose.runtime.setValue import cafe.adriel.voyager.core.screen.Screen import cafe.adriel.voyager.koin.getScreenModel import com.foreverrafs.superdiary.data.model.Diary import com.foreverrafs.superdiary.ui.LocalScreenNavigator import kotlinx.coroutines.flow.catch import kotlinx.coroutines.flow.onCompletion import kotlinx.coroutines.flow.onStart import kotlinx.coroutines.launch import kotlinx.datetime.Clock class CreateDiaryScreen : Screen { @Composable override fun Content() { val createDiaryScreenModel: CreateDiaryViewModel = getScreenModel() val navigator = LocalScreenNavigator.current val undoManager = rememberUndoableRichTextState() val richTextState = undoManager.richTextState val coroutineScope = rememberCoroutineScope() var isGeneratingFromAI by remember { mutableStateOf(false) } CreateDiaryScreenContent( onNavigateBack = navigator::pop, richTextState = richTextState, isGeneratingFromAi = isGeneratingFromAI, onGenerateAI = { prompt, wordCount -> undoManager.save() var generatedWords = "" coroutineScope.launch { createDiaryScreenModel .generateAIDiary( prompt = prompt, wordCount = wordCount, ) .onStart { isGeneratingFromAI = true richTextState.setHtml("<p>Generating diary...</p>") } .catch { isGeneratingFromAI = false richTextState.setHtml("<p style=\"color:red\">Error generating entry</p>") } .onCompletion { isGeneratingFromAI = false } .collect { chunk -> generatedWords += chunk richTextState.setHtml("<p>$generatedWords</p>") } } }, ) { entry -> createDiaryScreenModel.saveDiary( Diary( entry = entry, date = Clock.System.now(), isFavorite = false, ), ) navigator.pop() } } }
14
null
0
8
4db59c9093ddac1360a6457f886bf57121bfe5ed
2,792
superdiary
MIT License
filmes-api/src/main/kotlin/com/pedroulissespu/filmesapi/repository/FilmesRepository.kt
pedroulissespu
564,922,069
false
null
package com.pedroulissespu.filmesapi.repository import com.pedroulissespu.filmesapi.model.Filme import org.springframework.data.jpa.repository.JpaRepository interface FilmesRepository : JpaRepository<Filme, Long> { }
0
Kotlin
1
2
dd912b378c242a766d1242c7449e7f697fcb9589
218
filmes-api
MIT License
articleFlow/src/main/java/com/common/entity/FileType.kt
ihareshvaghela
777,749,632
false
{"Kotlin": 219746}
/* * Copyright (c) 2022-2023.8.11 * All right reserved 2023 * Created by Haresh Vaghela */ package com.common.entity object FileType { const val image = "image" const val video = "video" const val pdf = "pdf" }
0
Kotlin
0
0
f48657be3418d39ff15663da5ce8c53cba7ea34a
228
Android-Tech-Test
MIT License
app/src/main/java/dgca/verifier/app/android/verification/VerificationDialogFragment.kt
andypandy47
368,791,581
true
{"Kotlin": 99183, "JavaScript": 708}
/* * ---license-start * eu-digital-green-certificates / dgca-verifier-app-android * --- * Copyright (C) 2021 T-Systems International GmbH and all other contributors * --- * 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. * ---license-end * * Created by mykhailo.nester on 4/24/21 2:10 PM */ package dgca.verifier.app.android.verification import android.app.Dialog import android.content.res.ColorStateList import android.os.Bundle import android.util.DisplayMetrics import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.FrameLayout import androidx.core.content.ContextCompat import androidx.core.view.isVisible import androidx.fragment.app.viewModels import androidx.navigation.fragment.navArgs import androidx.recyclerview.widget.LinearLayoutManager import com.google.android.material.bottomsheet.BottomSheetBehavior import com.google.android.material.bottomsheet.BottomSheetDialog import com.google.android.material.bottomsheet.BottomSheetDialogFragment import com.google.android.material.button.MaterialButton import dagger.hilt.android.AndroidEntryPoint import dgca.verifier.app.android.FORMATTED_YEAR_MONTH_DAY import dgca.verifier.app.android.R import dgca.verifier.app.android.YEAR_MONTH_DAY import dgca.verifier.app.android.databinding.DialogFragmentVerificationBinding import dgca.verifier.app.android.dpToPx import dgca.verifier.app.android.model.CertificateData import dgca.verifier.app.android.model.CertificateModel import dgca.verifier.app.android.parseFromTo @ExperimentalUnsignedTypes @AndroidEntryPoint class VerificationDialogFragment : BottomSheetDialogFragment() { private val args by navArgs<VerificationDialogFragmentArgs>() private val viewModel by viewModels<VerificationViewModel>() private var _binding: DialogFragmentVerificationBinding? = null private val binding get() = _binding!! private lateinit var adapter: CertListAdapter override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) adapter = CertListAdapter(layoutInflater) } override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View { _binding = DialogFragmentVerificationBinding.inflate(inflater, container, false) return binding.root } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) setViewHeight() dialog.expand() val layoutManager = LinearLayoutManager(requireContext()) binding.recyclerView.layoutManager = layoutManager binding.recyclerView.adapter = adapter binding.actionBtn.setOnClickListener { dismiss() } viewModel.verificationResult.observe(viewLifecycleOwner, { setCertStatusUI(it.isValid()) }) viewModel.certificate.observe(viewLifecycleOwner, { certificate -> if (certificate != null) { toggleButton(certificate) showUserData(certificate) val list = getCertificateListData(certificate) adapter.update(list) } }) viewModel.inProgress.observe(viewLifecycleOwner, { binding.progressContainer.isVisible = it }) viewModel.init(args.qrCodeText) } override fun onDestroyView() { super.onDestroyView() _binding = null } private fun setViewHeight() { val displayMetrics = DisplayMetrics() requireActivity().windowManager.defaultDisplay.getMetrics(displayMetrics) val height = displayMetrics.heightPixels val params = binding.content.layoutParams as FrameLayout.LayoutParams params.height = height - TOP_MARGIN.dpToPx() } private fun setCertStatusUI(isValid: Boolean) { val text: String val imageId: Int val statusColor: ColorStateList val actionBtnText: String if (isValid) { text = getString(R.string.cert_valid) imageId = R.drawable.check statusColor = ColorStateList.valueOf(ContextCompat.getColor(requireContext(), R.color.green)) actionBtnText = getString(R.string.done) } else { text = getString(R.string.cert_invalid) imageId = R.drawable.error statusColor = ColorStateList.valueOf(ContextCompat.getColor(requireContext(), R.color.red)) actionBtnText = getString(R.string.retry) } binding.status.text = text binding.certStatusIcon.setImageResource(imageId) binding.verificationStatusBg.backgroundTintList = statusColor binding.actionBtn.isVisible = true binding.actionBtn.backgroundTintList = statusColor binding.actionBtn.text = actionBtnText binding.actionBtn.isVisible = true } private fun getCertificateListData(certificate: CertificateModel): List<CertificateData> { val list = mutableListOf<CertificateData>() list.addAll(certificate.vaccinations ?: emptyList()) list.addAll(certificate.tests ?: emptyList()) list.addAll(certificate.recoveryStatements ?: emptyList()) return list } private fun showUserData(certificate: CertificateModel) { binding.personFullName.text = getString(R.string.person_full_name_placeholder, certificate.person.givenName, certificate.person.familyName) binding.personStandardisedFamilyName.text = certificate.person.standardisedFamilyName binding.personStandardisedGivenName.text = certificate.person.standardisedGivenName binding.dateOfBirth.text = certificate.dateOfBirth.parseFromTo(YEAR_MONTH_DAY, FORMATTED_YEAR_MONTH_DAY) } private fun toggleButton(certificate: CertificateModel) { when { certificate.vaccinations?.isNotEmpty() == true -> enableToggleBtn(binding.vacToggle) certificate.recoveryStatements?.isNotEmpty() == true -> enableToggleBtn(binding.recToggle) certificate.tests?.isNotEmpty() == true -> enableToggleBtn(binding.testToggle) } } private fun enableToggleBtn(button: MaterialButton) { button.toggle() button.setTextColor(ContextCompat.getColor(requireContext(), R.color.black)) } companion object { private const val TOP_MARGIN = 50 } } fun Dialog?.expand() { this?.let { dialog -> dialog.setOnShowListener { dialogInterface -> val bottomSheetDialog = dialogInterface as BottomSheetDialog val bottomSheetInternal = bottomSheetDialog.findViewById<View>(com.google.android.material.R.id.design_bottom_sheet) bottomSheetInternal?.let { val bottomSheetBehavior = BottomSheetBehavior.from(it) bottomSheetBehavior.state = BottomSheetBehavior.STATE_EXPANDED bottomSheetBehavior.peekHeight = it.height it.setBackgroundResource(android.R.color.transparent) } } } }
0
null
0
0
223ea28bf8b50bcc8a67ba276d3e28f51cb81863
7,593
dgca-verifier-app-android
Apache License 2.0
src/main/kotlin/com/yangga/kopringrestapiboilerplate/module/user/application/UserService.kt
yangga
692,578,157
false
{"Kotlin": 63382, "Shell": 273}
package com.yangga.kopringrestapiboilerplate.module.user.application import com.yangga.kopringrestapiboilerplate.common.error.enums.ErrorCode import com.yangga.kopringrestapiboilerplate.common.error.exception.ApiException import com.yangga.kopringrestapiboilerplate.module.user.application.port.`in`.UserUseCase import com.yangga.kopringrestapiboilerplate.module.user.application.port.out.UserDaoPort import com.yangga.kopringrestapiboilerplate.module.user.domain.RegisterUser import com.yangga.kopringrestapiboilerplate.module.user.domain.User import org.springframework.stereotype.Service @Service class UserService( private val userDaoPort: UserDaoPort ) : UserUseCase { override suspend fun registerUser(data: RegisterUser): User { val oldUser = userDaoPort.findByEmail(data.email) if (oldUser != null) { throw ApiException.of(ErrorCode.ALREADY_EXIST, "User already exist", data.email) } val user = User( email = data.email, username = data.username, ) return userDaoPort.add(user, data.password) } override suspend fun loginUser(email: String, password: String): User { return userDaoPort.findByEmailAndPassword(email, password) ?: throw ApiException.of( ErrorCode.NOT_FOUND, "User not found", email ) } override suspend fun getUser(id: Long): User { return userDaoPort.findById(id) ?: throw ApiException.of(ErrorCode.NOT_FOUND, "User not found", id) } override suspend fun getUserAll(): List<User> { return userDaoPort.findAll() } }
0
Kotlin
0
0
52f95908f0da71c33b05f1a27362d2c519c9cb14
1,633
kopring-restapi-boilerplate
MIT License
app/src/main/java/io/cricket/app/ui/modules/history/live_match/LiveMatchItemVM.kt
amirishaque
375,128,729
false
null
package io.cricket.app.ui.modules.history.live_match import android.os.Bundle import android.view.View import androidx.lifecycle.MutableLiveData import io.cricket.app.R import io.cricket.app.base.BaseListDataViewModel import io.cricket.app.model.Match import io.cricket.app.model.MatchToUpload import io.cricket.app.ui.modules.history.live_match_stats.LiveMatchStatsFragment import io.cricket.app.utils.Constants.DATA class LiveMatchItemVM constructor() : BaseListDataViewModel<MatchToUpload>() { private lateinit var item: MatchToUpload var match: Match? = null var result = MutableLiveData("") var avatar = MutableLiveData<String>() set(value) { field = value notifyChange() } override fun setItem(item: MatchToUpload) { this.item = item this.match = item.match result.value = when (match?.resultStatus?.toInt()) { 1 -> { "Match is in progress" } 2 -> { "You Won the match" } else -> { "You loss the match" } } } override fun getItem() = item override fun layoutRes() = R.layout.item_live_match_history override fun onItemClick(v: View, item: MatchToUpload) { val bundle = Bundle() bundle.putParcelable(DATA, item.matchStats) navigatorHelper?.startFragmentWithToolbar<LiveMatchStatsFragment>( LiveMatchStatsFragment::class.java.name, bundle = bundle ) } }
0
Kotlin
0
0
42808ddd775b5ac6f7bff0d8cf518091588df844
1,551
Cricklub_livecode
MIT License
app/src/main/java/com/superwall/superapp/MainActivity.kt
superwall
642,585,064
false
{"Kotlin": 1190760}
package com.superwall.superapp import android.content.Intent import androidx.appcompat.app.AppCompatActivity import android.os.Bundle import android.widget.Button import com.superwall.sdk.Superwall import com.superwall.superapp.test.UITestActivity class MainActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) // Setup deep linking handling respondToDeepLinks() // campaign_trigger val campaignTriggerButton: Button = findViewById(R.id.campaignTriggerButton) // Attach a click listener to the button campaignTriggerButton.setOnClickListener { val app = application as? MainApplication app?.invokeRegister("campaign_trigger") } // campaign_trigger_v3 val campaignTriggerV3Button: Button = findViewById(R.id.campaignTriggerV3Button) // Attach a click listener to the button campaignTriggerV3Button.setOnClickListener { val app = application as? MainApplication app?.invokeRegister("campaign_trigger_v3") } // another_paywall val anotherPaywallButton: Button = findViewById(R.id.anotherPaywallButton) // Attach a click listener to the button anotherPaywallButton.setOnClickListener { val app = application as? MainApplication app?.invokeRegister("another_paywall") } // wide_paywall val widePaywallButton: Button = findViewById(R.id.widePaywallButton) // Attach a click listener to the button widePaywallButton.setOnClickListener { val app = application as? MainApplication app?.invokeRegister("wide_paywall") } // jetpack compose activity val jetpackComposeButton: Button = findViewById(R.id.jetpackComposeButton) // Attach a click listener to the button jetpackComposeButton.setOnClickListener { val intent = Intent(this, ComposeActivity::class.java) startActivity(intent) } // UITest button val uiTestButton: Button = findViewById(R.id.uiTest) uiTestButton.setOnClickListener { val intent = Intent(this, UITestActivity::class.java) startActivity(intent) } val devicePropertiesTestButton: Button = findViewById(R.id.devicePropertiesTest) devicePropertiesTestButton.setOnClickListener { val app = application as? MainApplication app?.invokeRegister("device_product_test") } val backboneTestButton: Button = findViewById(R.id.backboneTest) backboneTestButton.setOnClickListener { val app = application as? MainApplication app?.invokeRegister("game_controller") // Wait for 5 seconds then press down, then press up // CoroutineScope(Dispatchers.Main).launch { // delay(5000) // Superwall.instance.dispatchKeyEvent(KeyEvent(KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_BUTTON_A)) // delay(1000) // Superwall.instance.dispatchKeyEvent(KeyEvent(KeyEvent.ACTION_UP, KeyEvent.KEYCODE_BUTTON_A)) // } } } /* override fun onKeyDown(keyCode: Int, event: KeyEvent?): Boolean { if (event == null) { return super.onKeyDown(keyCode, event) } Superwall.instance.dispatchKeyEvent(event) return true } override fun onKeyUp(keyCode: Int, event: KeyEvent?): Boolean { if (event == null) { return super.onKeyUp(keyCode, event) } Superwall.instance.dispatchKeyEvent(event) return true } override fun onGenericMotionEvent(event: MotionEvent?): Boolean { if (event == null) { return super.onGenericMotionEvent(event) } Superwall.instance.dispatchMotionEvent(event) return true } */ //region Deep Links private fun respondToDeepLinks() { intent?.data?.let { uri -> Superwall.instance.handleDeepLink(uri) } } //endregion }
9
Kotlin
3
9
2582de8d48af7c0ad080e30949d920e8a34d9219
4,242
Superwall-Android
MIT License
backend/base/src/main/kotlin/one/ifelse/module/base/helper/sql/Builder.kt
ifelsedotonestd
696,103,275
false
{"Kotlin": 105363}
package one.ifelse.module.base.helper.sql interface Builder<T> { fun build(): JpaQueryExecutor<T> }
0
Kotlin
0
0
488005ab1190d6927a93dabf23e59ffa66ed4def
104
spring-vue-admin-template
The Unlicense
shared_resources/src/main/java/com/thewizrd/shared_resources/lifecycle/LifecycleAwareFragment.kt
SimpleAppProjects
197,253,270
false
null
package com.thewizrd.shared_resources.lifecycle import androidx.fragment.app.Fragment import androidx.lifecycle.Lifecycle import androidx.lifecycle.lifecycleScope import kotlinx.coroutines.* import kotlin.coroutines.CoroutineContext import kotlin.coroutines.EmptyCoroutineContext abstract class LifecycleAwareFragment : Fragment() { /** * Check if the current fragment's lifecycle is alive * * @return Returns true if fragment's lifecycle is at least initialized */ val isAlive: Boolean get() = lifecycle.currentState.isAtLeast(Lifecycle.State.INITIALIZED) /** * Check if the current fragment's view lifecycle is alive * * @return Returns true if fragment's lifecycle is at least created and the view has been created but not yet destroyed */ val isViewAlive: Boolean get() { val isFragmentCreated = lifecycle.currentState.isAtLeast(Lifecycle.State.CREATED) if (isFragmentCreated) { try { return viewLifecycleOwner.lifecycle.currentState.isAtLeast(Lifecycle.State.INITIALIZED) } catch (ignored: IllegalStateException) { // Can't access the Fragment View's LifecycleOwner when the fragment's getView() is null i.e., before onCreateView() or after onDestroyView() } } return false } /** * Launches and runs the given runnable if the fragment is at least initialized * The action will be signalled to cancel if the fragment goes into the destroyed state * Note: This will run on the UI thread * * @param action The runnable to be executed */ protected fun runOnUiThread(action: Runnable) { lifecycleScope.launch(Dispatchers.Main.immediate) { action.run() } } /** * Launches and runs the given runnable when the fragment is in the started * The action will be signalled to cancel if the fragment goes into the destroyed state * Note: This will run on the UI thread * * @param action The runnable to be executed; Should be initialized with the fragment's lifecycle */ protected fun runWhenStarted(action: Runnable) { lifecycleScope.launchWhenStarted { withContext(Dispatchers.Main.immediate) { action.run() } } } /** * Launches and runs the given runnable if the fragment is at least initialized * The action will be signalled to cancel if the fragment goes into the destroyed state * Note: This will run on the UI thread * * @param action The runnable to be executed; Should be initialized with the viewLifeCycleOwner's lifecycle */ protected fun runWithView(action: Runnable) { runCatching { viewLifecycleOwner.lifecycleScope }.onFailure { // no-op }.onSuccess { it.launch(Dispatchers.Main.immediate) { action.run() } } } /** * Launches and runs the given runnable if the fragment is at least initialized * The action will be signalled to cancel if the fragment goes into the destroyed state * Note: This will run on the UI thread * * @param context additional to [CoroutineScope.coroutineContext] context of the coroutine. * @param block the coroutine code which will be invoked in the context of the viewLifeCyclerOwner lifecycle scope. */ fun runWithView(context: CoroutineContext = EmptyCoroutineContext, block: suspend CoroutineScope.() -> Unit) { runCatching { viewLifecycleOwner.lifecycleScope }.onFailure { // no-op }.onSuccess { it.launch(context = context, block = block) } } /** * Launches and runs the given runnable when the fragment is in the started * The action will be signalled to cancel if the fragment goes into the destroyed state * Note: This will run on the UI thread * * @param action The runnable to be executed; Should be initialized with the viewLifeCyclerOwner's lifecycle */ protected fun runWhenViewStarted(action: Runnable) { runCatching { viewLifecycleOwner.lifecycleScope }.onFailure { // no-op }.onSuccess { it.launchWhenStarted { withContext(Dispatchers.Main.immediate) { action.run() } } } } /** * Launches and runs the given runnable when the fragment is in the started * The action will be signalled to cancel if the fragment goes into the destroyed state * Note: This will run on the UI thread * * @param block the coroutine code which will be invoked when [Lifecycle] is at least in [Lifecycle.State.STARTED] state. */ protected fun runWhenViewStarted(block: suspend CoroutineScope.() -> Unit) { runCatching { viewLifecycleOwner.lifecycleScope }.onFailure { // no-op }.onSuccess { it.launchWhenStarted(block = block) } } }
9
null
8
99
f8df1f9b321130e3b7d031ed2e2e3bbe7d196c86
5,209
SimpleWear
Apache License 2.0
androidTestClient/src/main/java/com/trevjonez/kontrast/LayoutHelper.kt
trevjonez
96,487,923
false
null
/* * Copyright 2017 <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.trevjonez.kontrast import android.annotation.SuppressLint import android.graphics.Bitmap import android.graphics.Canvas import android.os.Build import android.os.Bundle import android.util.Log import android.util.TypedValue import android.view.View import android.view.View.MeasureSpec.EXACTLY import android.view.View.MeasureSpec.UNSPECIFIED import android.view.View.MeasureSpec.makeMeasureSpec import androidx.test.platform.app.InstrumentationRegistry import java.io.File class LayoutHelper(val view: View, val className: String, val methodName: String, val testKey: String, val parameterizedName: String?) { companion object { const val KONTRAST_SIGNAL_CODE = 42 const val CLASS_NAME = "ClassName" const val METHOD_NAME = "MethodName" const val PARAMETERIZED_NAME = "ParameterizedName" const val TEST_KEY = "TestKey" const val EXTRAS = "Extras" const val DESCRIPTION = "Description" const val OUTPUT_DIR = "OutputDir" const val KONTRAST = "Kontrast" } val outputDirectory: File by lazy { val subDirectoryPath = "Kontrast${File.separator}$className${File.separator}$methodName${File.separator}$testKey" view.context.getExternalFilesDir(subDirectoryPath) } var widthSpec = makeMeasureSpec(0, UNSPECIFIED) var heightSpec = makeMeasureSpec(0, UNSPECIFIED) var description: String? = null val extras = mutableMapOf<String, String>().apply { put("Width", "wrap_content") put("Height", "wrap_content") } fun setWidthDp(dp: Int) = apply { widthSpec = makeMeasureSpec(dp.dp2Px(), EXACTLY) extra("Width", "${dp}dp") } fun setWidthPx(px: Int) = apply { widthSpec = makeMeasureSpec(px, EXACTLY) extra("Width", "${px}px") } fun setHeightDp(dp: Int) = apply { heightSpec = makeMeasureSpec(dp.dp2Px(), EXACTLY) extra("Height", "${dp}dp") } fun setHeightPx(px: Int) = apply { heightSpec = makeMeasureSpec(px, EXACTLY) extra("Height", "${px}px") } fun description(value: String) = apply { description = value } fun extra(key: String, value: String) = apply { extras.put(key, value) } fun layout() = apply { do { view.measure(widthSpec, heightSpec) view.layout(0, 0, view.measuredWidth, view.measuredHeight) } while (view.isLayoutRequested) } fun draw(): Bitmap { return Bitmap.createBitmap(view.width, view.height, Bitmap.Config.ARGB_8888).apply { WindowAttachment.emulateAttach(view).use { view.draw(Canvas(this)) } } } @SuppressLint("SetWorldReadable", "NewApi", "SdCardPath") fun capture() { val snapshot = layout().draw() if (!outputDirectory.mkdirs() && !outputDirectory.exists()) { Log.e("LayoutHelper", "Unable to create output dir(s) ${outputDirectory.absolutePath}") } File(outputDirectory, "image.png").apply { createNewFile() outputStream().use { snapshot.compress(Bitmap.CompressFormat.PNG, 100, it) } setReadable(true, false) } //TODO layout hierarchy //uiautomator dump [file] val outputPath = if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) "/sdcard" + outputDirectory.absolutePath.removePrefix("/storage/emulated/0") else outputDirectory.absolutePath val data = Bundle().apply { putString("$KONTRAST:$CLASS_NAME", className) putString("$KONTRAST:$METHOD_NAME", methodName) putString("$KONTRAST:$PARAMETERIZED_NAME", parameterizedName) putString("$KONTRAST:$TEST_KEY", testKey) putString("$KONTRAST:$EXTRAS", extras.map({ (k, v) -> """"$k"KVP_DELIMITER"$v"""" }).joinToString(prefix = "[", postfix = "]", separator = "EXTRA_DELIMITER")) putString("$KONTRAST:$DESCRIPTION", description) putString("$KONTRAST:$OUTPUT_DIR", outputPath) } InstrumentationRegistry.getInstrumentation().sendStatus(KONTRAST_SIGNAL_CODE, data) } private fun Int.dp2Px(): Int { return TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, this.toFloat(), view.context.resources.displayMetrics).toInt() } }
5
null
2
28
136f3bc5d3ecb87320f87ef2144533babec13226
5,184
Kontrast
Apache License 2.0
commons/src/commonMain/kotlin/org/jetbrains/letsPlot/commons/intern/util/VecUtil.kt
JetBrains
176,771,727
false
{"Kotlin": 7616680, "Python": 1299756, "Shell": 3453, "C": 3039, "JavaScript": 931, "Dockerfile": 94}
/* * Copyright (c) 2024. JetBrains s.r.o. * Use of this source code is governed by the MIT license that can be found in the LICENSE file. */ package org.jetbrains.letsPlot.commons.intern.util import org.jetbrains.letsPlot.commons.intern.typedGeometry.Scalar import org.jetbrains.letsPlot.commons.intern.typedGeometry.Vec import org.jetbrains.letsPlot.commons.intern.typedGeometry.algorithms.AdaptiveResampler import org.jetbrains.letsPlot.commons.intern.util.VectorAdapter.Companion.VEC_ADAPTER object VecUtil { fun <T> padLineString(lineString: List<Vec<T>>, startPadding: Double, endPadding: Double): List<Vec<T>> { val paddingHelper = PaddingHelper(VEC_ADAPTER) val lineStringAfterPadding = paddingHelper.padLineString( lineString = lineString, startPadding = startPadding, endPadding = endPadding ) @Suppress("UNCHECKED_CAST") return lineStringAfterPadding as List<Vec<T>> } fun <T> createArrowHeadGeometry( geometry: List<Vec<T>>, angle: Double, arrowLength: Double, onStart: Boolean, onEnd: Boolean, closed: Boolean, minTailLength: Scalar<T>, minHeadLength: Scalar<T>, ): Pair<List<Vec<T>>, List<Vec<T>>> { val arrowHelper = ArrowSupport.ArrowHelper(VEC_ADAPTER) val heads = arrowHelper.createArrowHeads( lineString = geometry, angle = angle, arrowLength = arrowLength, onStart = onStart, onEnd = onEnd, closed = closed, minTailLength = minTailLength.value, minHeadLength = minHeadLength.value ) @Suppress("UNCHECKED_CAST") return heads as Pair<List<Vec<T>>, List<Vec<T>>> } fun <InT, OutT> resample(points: List<Vec<InT>>, precision: Double, transform: (Vec<InT>) -> Vec<OutT>?): List<Vec<OutT>> { val resampler = AdaptiveResampler.generic(precision, VEC_ADAPTER) { @Suppress("UNCHECKED_CAST") transform(it as Vec<InT>) } @Suppress("UNCHECKED_CAST") return resampler.resample(points) as List<Vec<OutT>> } fun <InT, OutT> resample(p1: Vec<InT>, p2: Vec<InT>, precision: Double, transform: (Vec<InT>) -> Vec<OutT>?,): List<Vec<OutT>> { val resampler = AdaptiveResampler.generic(precision, VEC_ADAPTER) { @Suppress("UNCHECKED_CAST") transform(it as Vec<InT>) } @Suppress("UNCHECKED_CAST") return resampler.resample(p1, p2) as List<Vec<OutT>> } }
150
Kotlin
51
1,561
c8db300544974ddd35a82a90072772b788600ac6
2,587
lets-plot
MIT License
inference/inference-core/src/commonMain/kotlin/io/kinference.core/operators/math/MathUtils.kt
JetBrains-Research
244,400,016
false
null
package io.kinference.operators.math import kotlin.math.exp inline fun tanh(value: Float): Float { var temp = exp(2.0f * value) if (temp.isInfinite()) temp = Float.MAX_VALUE return ((temp - 1.0f) / (temp + 1.0f)) } inline fun tanh(value: Double): Double { return ((exp(2.0 * value) - 1.0) / (exp(2.0 * value) + 1.0)) } inline fun fgelu(x: Float): Float { return x * (0.5f + 0.5f * tanh(x * (0.035677408136300125f * x * x + 0.7978845608028654f))) } inline fun fgelu(x: Double): Double { return x * (0.5 + 0.5 * tanh(x * (0.035677408136300125 * x * x + 0.7978845608028654))) }
2
Kotlin
5
74
5cd3ac9c79f3f1ebb9ec5c83adb706dc8325a852
604
kinference
Apache License 2.0
shared/src/commonMain/kotlin/utils/Extensions.kt
sunildhiman90
672,833,519
false
{"Kotlin": 310248, "Swift": 6652, "JavaScript": 4142, "HTML": 663, "Shell": 228, "Ruby": 101}
package utils import androidx.compose.ui.unit.dp import core.ComposeScreenConfiguration object ResponsiveHelper { val isTablet: Boolean get() = isTablet val isDesktop: Boolean get() = isDesktop val isMobile: Boolean get() = isMobile } fun ComposeScreenConfiguration.isTablet(): Boolean { return this.width > 730.dp } fun ComposeScreenConfiguration.isDesktop(): Boolean { return this.width > 1200.dp } fun ComposeScreenConfiguration.isMobile(): Boolean { return !this.isTablet() && !this.isDesktop() }
0
Kotlin
0
1
59fb3a1cc1e84fb777d6806bf1368e7def123364
559
YourFlixer-KMP
Apache License 2.0
aoc-day8/src/Signal.kt
rnicoll
438,043,402
false
{"Kotlin": 90620, "Rust": 1313}
enum class Signal { a, b, c, d, e, f, g }
0
Kotlin
0
0
8c3aa2a97cb7b71d76542f5aa7f81eedd4015661
69
adventofcode2021
MIT License
app/src/main/java/com/bluehub/fastmixer/screens/mixing/MixingRepository.kt
Solunadigital
314,575,015
true
{"C++": 80949, "Kotlin": 68260, "CMake": 4609, "C": 1990}
package com.bluehub.fastmixer.screens.mixing class MixingRepository(val mixingEngineProxy: MixingEngineProxy) { fun createMixingEngine() { mixingEngineProxy.create() } fun readSamples(filePath: String): Array<Float> = mixingEngineProxy.readSamples(filePath) fun getTotalSamples(filePath: String): Int = mixingEngineProxy.getTotalSamples(filePath) fun deleteMixingEngine() = mixingEngineProxy.delete() }
0
null
0
0
fa05fb9e3df420d4194c160464f927db60e6c83d
434
fast-mixer
MIT License
mb-common/src/main/kotlin/com/nomkhonwaan/mb/common/messaging/attachment/AttachmentEvents.kt
nomkhonwaan
164,768,574
false
null
package com.nomkhonwaan.mb.common.messaging.attachment import com.nomkhonwaan.mb.common.messaging.Event import java.io.InputStream /** * An uploading Attachment Event. * * @param id An identifier of the Attachment * @param inputStream An uploaded file input stream * @param size A size of the uploaded file * @param path A path that the file will be uploaded to */ data class UploadingAttachmentEvent( override val id: String, val inputStream: InputStream, val size: Long, val path: String ) : Event<String>(id) /** * An Attachment uploaded Event. * <p> * This Event will be fired once the uploading process has been completed. * * @param id An identifier of the Attachment */ data class AttachmentUploadedEvent(override val id: String) : Event<String>(id) /** * A rollback uploaded Attachment Event. * <p> * This Event will be fired once the uploading process has been failed. */ data class AttachmentRolledbackEvent(override val id: String, val path: String) : Event<String>(id)
0
Kotlin
0
0
481c3b60568cac387be12cdaeb05f7c538494772
1,057
mb
MIT License
app/src/main/java/sgtmelon/adventofcode/app/presentation/model/Year.kt
SerjantArbuz
559,224,296
false
{"Kotlin": 152755}
package sgtmelon.adventofcode.app.presentation.model data class Year(val id: Int, val dayList: List<Day>) { val doneCount = dayList.count { it.solution == Solution.FULL } }
0
Kotlin
0
0
26a57b8431c03e2d09071f7302d6360ba91bfd2f
179
AdventOfCode
Apache License 2.0
app/src/main/java/sgtmelon/adventofcode/app/presentation/model/Year.kt
SerjantArbuz
559,224,296
false
{"Kotlin": 152755}
package sgtmelon.adventofcode.app.presentation.model data class Year(val id: Int, val dayList: List<Day>) { val doneCount = dayList.count { it.solution == Solution.FULL } }
0
Kotlin
0
0
26a57b8431c03e2d09071f7302d6360ba91bfd2f
179
AdventOfCode
Apache License 2.0
fabric/src/main/kotlin/com/plasmoverse/rpshare/DownloadTask.kt
plasmoapp
655,924,413
false
null
package com.plasmoverse.rpshare import com.plasmoverse.rpshare.ResourcePackShareClient.scope import com.plasmoverse.rpshare.gui.ErrorScreen import com.plasmoverse.rpshare.model.DownloadData import kotlinx.coroutines.Job import kotlinx.coroutines.isActive import kotlinx.coroutines.launch import net.minecraft.client.MinecraftClient import java.io.BufferedInputStream import java.io.File import java.net.URLConnection import java.net.URLDecoder import kotlin.Exception class DownloadTask(private val data: DownloadData) { private var job: Job? = null var fileSize: Int = 0 private set var progress: Int = 0 private set val percent get() = runCatching { progress * 100 / fileSize }.getOrNull() ?: 0 fun start() { job?.cancel() job = launchJob() } fun cancel() { job?.cancel() } private fun handleError(e: Throwable) { val instance = MinecraftClient.getInstance() instance.executeSync { instance.setScreen(ErrorScreen(data, e)) } } private fun launchJob() = scope.launch { val connection = runCatching { data.url.openConnection() } .onFailure(::handleError) .getOrNull() ?: return@launch val fileName = getFileNameFromConnection(connection) ?.takeIf { it.isNotBlank() } ?: run { handleError(Exception("Invalid file name")) return@launch } val path = File( MinecraftClient.getInstance().resourcePackDir.toFile(), fileName, ) try { fileSize = connection.contentLength progress = 0 val inputStream = BufferedInputStream(connection.getInputStream()) val outputStream = path.outputStream() val buffer = ByteArray(1024) var bytesRead = 0 while (isActive && inputStream.read(buffer).also { bytesRead = it } != -1) { outputStream.write(buffer, 0, bytesRead) progress += bytesRead } outputStream.flush() } finally { val instance = MinecraftClient.getInstance() if (isActive) instance.executeSync { onComplete(fileName) } else if (path.exists()) path.deleteRecursively() } } private fun onComplete(fileName: String) { val instance = MinecraftClient.getInstance() val manager = instance.resourcePackManager val profile = "file/$fileName" manager.scanPacks() if (!manager.hasProfile(profile)) { handleError(Exception("File is not a resource pack")) File(instance.resourcePackDir.toFile(), fileName).also { if (it.exists()) it.deleteRecursively() } } instance.setScreen(null) manager.setEnabledProfiles( manager.enabledProfiles.map { it.name } + "file/$fileName" ) instance.reloadResources() } private fun getFileNameFromConnection(connection: URLConnection): String? { val contentDisposition = connection.getHeaderField("Content-Disposition") if (contentDisposition != null) { val fileNameStartIndex = contentDisposition.indexOf("filename=") if (fileNameStartIndex >= 0) { val fileNameWithQuotes = contentDisposition.substring(fileNameStartIndex + 9) val fileName = fileNameWithQuotes.trim('\"') return URLDecoder.decode(fileName, "UTF-8") } } val path = connection.url.path val lastPathSegment = path.substring(path.lastIndexOf('/') + 1) return URLDecoder.decode(lastPathSegment, "UTF-8") } }
0
Kotlin
0
1
b9a55364d5acd7a6a8471fd5972a1af62eb4040f
3,778
RPShare
MIT License
src/main/kotlin/xyz/chlamydomonos/hyphacraft/loaders/BlockTagLoader.kt
Chlamydomonos
832,406,228
false
{"Kotlin": 331361, "Java": 6074}
package xyz.chlamydomonos.hyphacraft.loaders import net.minecraft.tags.TagKey import net.minecraft.world.level.block.Block import xyz.chlamydomonos.hyphacraft.blocks.tags.BaseBlockTag import xyz.chlamydomonos.hyphacraft.blocks.tags.minecraft.MineableWithAxeTag import xyz.chlamydomonos.hyphacraft.blocks.tags.minecraft.MineableWithHoeTag import xyz.chlamydomonos.hyphacraft.blocks.tags.minecraft.MineableWithPickaxeTag import xyz.chlamydomonos.hyphacraft.blocks.tags.minecraft.MineableWithShovelTag import xyz.chlamydomonos.hyphacraft.blocks.tags.mod.* object BlockTagLoader { val TAGS = mutableListOf<BaseBlockTag>() fun register(builder: () -> BaseBlockTag): TagKey<Block> { val tag = builder() TAGS.add(tag) return tag.key } init { register(::MineableWithPickaxeTag) register(::MineableWithShovelTag) register(::MineableWithAxeTag) register(::MineableWithHoeTag) } val PRESERVE_LEAVES = register(::PreserveLeavesTag) val HYPHA_TREE = register(::HyphaTreeTag) val GRANDISPORIA_STIPE_CONNECTABLE = register(::GrandisporiaStipeConnectableTag) val CARNIVORAVITIS_VINE_CONNECTABLE = register(::CarnivoravitisVineConnectableTag) val CARNIVORAVITIS_PLANT = register(::CarnivoravitisPlantTag) val XENOLICHEN_REPLACEABLE = register(::XenolichenReplaceableTag) val MYCOVASTUS_HYPHA_REPLACEABLE = register(::MycovastusHyphaReplaceableTag) val TUMIDUSIO_HYPHA_REPLACEABLE = register(::TumidusioHyphaReplaceableTag) val ALIEN_SOIL_DESTROYED = register(::AlienSoilDestroyedTag) val TUMIDUSIO_REPLACEABLE = register(::TumidusioReplaceableTag) val ALIEN_SOIL = register(::AlienSoilTag) }
0
Kotlin
0
0
66942935b237b4ce243958544411809a09118e35
1,699
HyphaCraft
MIT License
easy/kotlin/c0098_405_convert-a-number-to-hexadecimal/00_leetcode_0098.kt
drunkwater
127,843,545
false
null
// DRUNKWATER TEMPLATE(add description and prototypes) // Question Title and Description on leetcode.com // Function Declaration and Function Prototypes on leetcode.com //405. Convert a Number to Hexadecimal //Given an integer, write an algorithm to convert it to hexadecimal. For negative integer, two’s complement method is used. //Note: //All letters in hexadecimal (a-f) must be in lowercase. //The hexadecimal string must not contain extra leading 0s. If the number is zero, it is represented by a single zero character '0'; otherwise, the first character in the hexadecimal string will not be the zero character. //The given number is guaranteed to fit within the range of a 32-bit signed integer. //You must not use any method provided by the library which converts/formats the number to hex directly. //Example 1: //Input: //26 //Output: //"1a" //Example 2: //Input: //-1 //Output: //"ffffffff" //class Solution { // fun toHex(num: Int): String { // } //} // Time Is Money
1
null
1
1
8cc4a07763e71efbaedb523015f0c1eff2927f60
989
leetcode
Ruby License
app/src/main/java/com/github/zawadz88/exoplayeraudiosample/presentation/main/viewmodel/MainViewModel.kt
zawadz88
165,692,093
false
null
package com.github.zawadz88.exoplayeraudiosample.presentation.main.viewmodel import androidx.lifecycle.ViewModel import com.github.zawadz88.exoplayeraudiosample.domain.interactor.LoadPlaylist import com.github.zawadz88.exoplayeraudiosample.internal.rx.EmptySingleObserver import timber.log.Timber import javax.inject.Inject class MainViewModel @Inject constructor( private val loadPlaylist: LoadPlaylist ) : ViewModel() { init { Timber.d("created: $this") } override fun onCleared() { super.onCleared() Timber.d("onCleared") loadPlaylist.dispose() } fun loadContent() { Timber.d("Loading content") loadPlaylist(observer = object : EmptySingleObserver<List<String>>() { override fun onSuccess(result: List<String>) { Timber.d("songs: $result") } }) } }
1
null
2
9
75675ce3eba05fbc8eb7cc6e2b9569a55670d37d
881
ExoPlayerAudioSample
MIT License
app/src/main/java/com/example/pazaramamovieapp/presentation/home/HomeUiState.kt
ozturksahinyetisir
743,101,052
false
{"Kotlin": 33302}
package com.example.pazaramamovieapp.presentation.home import com.example.pazaramamovieapp.domain.model.Movie data class HomeUiState( val movies: List<Movie> = emptyList(), val isLoading: Boolean = false, val searchQuery: String = "Batman", val errorMessage: String? = null )
0
Kotlin
0
0
597eedd0d1fb748be7a536a5943d1fa37ff9eb33
294
Pazarama-MovieApp
MIT License
buildSrc/src/main/java/co/anitrend/arch/buildSrc/plugin/components/ProjectMaven.kt
AniTrend
155,243,365
false
{"Kotlin": 396351}
package co.anitrend.arch.buildSrc.plugin.components import co.anitrend.arch.buildSrc.plugin.extensions.props import co.anitrend.arch.buildSrc.plugin.extensions.publishingExtension import org.gradle.api.Project import org.gradle.api.publish.maven.MavenPublication import org.gradle.api.tasks.bundling.Jar internal fun Project.configureMaven(sourcesJar: Jar) { publishingExtension().publications { val component = components.findByName("kotlin") ?: components.findByName("java") logger.lifecycle("Configuring maven publication options for ${path}:maven with component -> ${component?.name}") create("maven", MavenPublication::class.java) { groupId = "co.anitrend.arch" artifactId = project.name version = props[PropertyTypes.VERSION] val releaseFile = "${layout.buildDirectory.get()}/outputs/aar/${project.name}-release.aar" if (file(releaseFile).exists()) { artifact(releaseFile) } artifact(sourcesJar) if (component != null) { from(component) } pom { name.set("support-arch") description.set("A multi-module template library that attempts to make clean arch apps easier to build") url.set("https://github.com/anitrend/support-arch") licenses { license { name.set("Apache License, Version 2.0") url.set("http://www.apache.org/licenses/LICENSE-2.0.txt") } } developers { developer { id.set("wax911") name.set("<NAME>") organizationUrl.set("https://github.com/anitrend") } } } } } }
2
Kotlin
1
7
aa2074c3e2b57eee580b21ea688bbf0c1eb7352e
1,901
support-arch
Apache License 2.0
domain/src/main/java/io/homeassistant/companion/android/domain/integration/IntegrationUseCase.kt
jsmeyers
291,310,220
true
{"Kotlin": 530456}
package io.homeassistant.companion.android.domain.integration interface IntegrationUseCase { suspend fun registerDevice(deviceRegistration: DeviceRegistration) suspend fun updateRegistration( appVersion: String? = null, deviceName: String? = null, manufacturer: String? = null, model: String? = null, osVersion: String? = null, pushUrl: String? = null, pushToken: String? = null ) suspend fun getRegistration(): DeviceRegistration suspend fun isRegistered(): Boolean suspend fun renderTemplate(template: String, variables: Map<String, String> = mapOf()): String suspend fun updateLocation(updateLocation: UpdateLocation) suspend fun callService(domain: String, service: String, serviceData: HashMap<String, Any>) suspend fun fireEvent(eventType: String, eventData: Map<String, Any>) suspend fun scanTag(data: HashMap<String, Any>) suspend fun getZones(): Array<Entity<ZoneAttributes>> suspend fun setFullScreenEnabled(enabled: Boolean) suspend fun isFullScreenEnabled(): Boolean suspend fun sessionTimeOut(value: Int) suspend fun getSessionTimeOut(): Int suspend fun setSessionExpireMillis(value: Long) suspend fun getSessionExpireMillis(): Long suspend fun getServices(): Array<Service> suspend fun getEntities(): Array<Entity<Any>> suspend fun getThemeColor(): String suspend fun getHomeAssistantVersion(): String suspend fun getPanels(): Array<Panel> suspend fun registerSensor(sensorRegistration: SensorRegistration<Any>) suspend fun updateSensors(sensors: Array<SensorRegistration<Any>>): Boolean }
0
Kotlin
0
0
72981d2360167c36c24029d7dbefdcecbe84c9bc
1,676
android
Apache License 2.0
gl/src/main/kotlin/imgui/impl/gl/ImplGL3.kt
kotlin-graphics
59,469,938
false
null
package imgui.impl.gl import glm_.L import glm_.glm import glm_.i import glm_.vec2.Vec2 import glm_.vec4.Vec4ub import gln.* import gln.glf.semantic import gln.identifiers.GlBuffers import gln.identifiers.GlProgram import gln.identifiers.GlVertexArray import gln.uniform.glUniform import gln.vertexArray.glVertexAttribPointer import imgui.BackendFlag import imgui.DEBUG import imgui.ImGui.io import imgui.impl.mat import imgui.internal.DrawData import imgui.internal.DrawIdx import imgui.internal.DrawVert import imgui.or import kool.* import org.lwjgl.opengl.GL import org.lwjgl.opengl.GL30C.* import org.lwjgl.opengl.GL32C.glDrawElementsBaseVertex import org.lwjgl.opengl.GL33C import org.lwjgl.opengl.GL33C.glBindSampler import org.lwjgl.opengl.GL45C.GL_CLIP_ORIGIN import org.lwjgl.system.Platform class ImplGL3 : GLInterface { var program = GlProgram(0) var matUL = -1 val buffers = GlBuffers<Buffer>() var vao = GlVertexArray() init { // query for GL version glVersion = when { !OPENGL_ES2 -> glGetInteger(GL_MAJOR_VERSION) * 100 + glGetInteger(GL_MINOR_VERSION) * 10 else -> 200 // GLES 2 } // Setup back-end capabilities flags io.backendRendererName = "imgui_impl_opengl3" if (MAY_HAVE_DRAW_WITH_BASE_VERTEX) if (glVersion >= 320) io.backendFlags = io.backendFlags or BackendFlag.RendererHasVtxOffset // We can honor the ImDrawCmd::VtxOffset field, allowing for large meshes. } override fun shutdown() = destroyDeviceObjects() override fun newFrame() { if (program.isInvalid) createDeviceObjects() } fun setupRenderState(drawData: DrawData, fbWidth: Int, fbHeight: Int) { // Setup render state: alpha-blending enabled, no face culling, no depth testing, scissor enabled glEnable(GL_BLEND) glBlendEquation(GL_FUNC_ADD) glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA) glDisable(GL_CULL_FACE) glDisable(GL_DEPTH_TEST) glEnable(GL_SCISSOR_TEST) if (POLYGON_MODE) glPolygonMode(GL_FRONT_AND_BACK, GL_FILL) // Support for GL 4.5 rarely used glClipControl(GL_UPPER_LEFT) val clipOriginLowerLeft = when { CLIP_ORIGIN && Platform.get() != Platform.MACOSX -> glGetInteger(GL_CLIP_ORIGIN) != GL_UPPER_LEFT else -> true } // Setup viewport, orthographic projection matrix // Our visible imgui space lies from draw_data->DisplayPos (top left) to draw_data->DisplayPos+data_data->DisplaySize (bottom right). // DisplayPos is (0,0) for single viewport apps. glViewport(0, 0, fbWidth, fbHeight) val L = drawData.displayPos.x val R = drawData.displayPos.x + drawData.displaySize.x var T = drawData.displayPos.y var B = drawData.displayPos.y + drawData.displaySize.y if (!clipOriginLowerLeft) { val tmp = T; T = B; B = tmp; } // Swap top and bottom if origin is upper left val orthoProjection = glm.ortho(L, R, B, T, mat) glUseProgram(program.name) glUniform(matUL, orthoProjection) if (OPENGL_MAY_HAVE_BIND_SAMPLER && glVersion > 330) glBindSampler(0, 0) // We use combined texture/sampler state. Applications using GL 3.3 may set that otherwise. vao.bind() // Bind vertex/index buffers and setup attributes for ImDrawVert glBindBuffer(GL_ARRAY_BUFFER, buffers[Buffer.Vertex].name) glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, buffers[Buffer.Element].name) glEnableVertexAttribArray(semantic.attr.POSITION) glEnableVertexAttribArray(semantic.attr.TEX_COORD) glEnableVertexAttribArray(semantic.attr.COLOR) glVertexAttribPointer(semantic.attr.POSITION, Vec2.length, GL_FLOAT, false, DrawVert.SIZE, 0) glVertexAttribPointer(semantic.attr.TEX_COORD, Vec2.length, GL_FLOAT, false, DrawVert.SIZE, Vec2.size) glVertexAttribPointer(semantic.attr.COLOR, Vec4ub.length, GL_UNSIGNED_BYTE, true, DrawVert.SIZE, Vec2.size * 2) } /** OpenGL3 Render function. * (this used to be set in io.renderDrawListsFn and called by ImGui::render(), but you can now call this directly * from your main loop) * Note that this implementation is little overcomplicated because we are saving/setting up/restoring every OpenGL * state explicitly, in order to be able to run within any OpenGL engine that doesn't do so. */ override fun renderDrawData(drawData: DrawData) { // Avoid rendering when minimized, scale coordinates for retina displays (screen coordinates != framebuffer coordinates) val fbWidth = (drawData.displaySize.x * drawData.framebufferScale.x).i val fbHeight = (drawData.displaySize.y * drawData.framebufferScale.y).i if (fbWidth == 0 || fbHeight == 0) return // Backup GL state val lastActiveTexture = glGetInteger(GL_ACTIVE_TEXTURE) glActiveTexture(GL_TEXTURE0 + semantic.sampler.DIFFUSE) val lastProgram = glGetInteger(GL_CURRENT_PROGRAM) val lastTexture = glGetInteger(GL_TEXTURE_BINDING_2D) val lastSampler = when { !OPENGL_MAY_HAVE_BIND_SAMPLER && glVersion > 330 -> glGetInteger(GL33C.GL_SAMPLER_BINDING) else -> 0 } val lastArrayBuffer = glGetInteger(GL_ARRAY_BUFFER_BINDING) val lastVertexArray = glGetInteger(GL_VERTEX_ARRAY_BINDING) val lastElementBuffer = glGetInteger(GL_ELEMENT_ARRAY_BUFFER_BINDING) val lastPolygonMode = glGetVec2i(GL_POLYGON_MODE)[0] val lastViewport = glGetVec4i(GL_VIEWPORT) val lastScissorBox = glGetVec4i(GL_SCISSOR_BOX) val lastBlendSrcRgb = glGetInteger(GL_BLEND_SRC_RGB) val lastBlendDstRgb = glGetInteger(GL_BLEND_DST_RGB) val lastBlendSrcAlpha = glGetInteger(GL_BLEND_SRC_ALPHA) val lastBlendDstAlpha = glGetInteger(GL_BLEND_DST_ALPHA) val lastBlendEquationRgb = glGetInteger(GL_BLEND_EQUATION_RGB) val lastBlendEquationAlpha = glGetInteger(GL_BLEND_EQUATION_ALPHA) val lastEnableBlend = glIsEnabled(GL_BLEND) val lastEnableCullFace = glIsEnabled(GL_CULL_FACE) val lastEnableDepthTest = glIsEnabled(GL_DEPTH_TEST) val lastEnableScissorTest = glIsEnabled(GL_SCISSOR_TEST) // Setup desired GL state setupRenderState(drawData, fbWidth, fbHeight) // Will project scissor/clipping rectangles into framebuffer space val clipOff = drawData.displayPos // (0,0) unless using multi-viewports val clipScale = drawData.framebufferScale // (1,1) unless using retina display which are often (2,2) // Render command lists for (cmdList in drawData.cmdLists) { var idxBufferOffset = 0L // Upload vertex/index buffers nglBufferData(GL_ARRAY_BUFFER, cmdList.vtxBuffer.data.lim.L, cmdList.vtxBuffer.data.adr, GL_STREAM_DRAW) nglBufferData(GL_ELEMENT_ARRAY_BUFFER, cmdList.idxBuffer.lim * DrawIdx.BYTES.L, cmdList.idxBuffer.adr, GL_STREAM_DRAW) for (cmd in cmdList.cmdBuffer) { val userCB = cmd.userCallback if (userCB != null) { // User callback, registered via ImDrawList::AddCallback() // (ImDrawCallback_ResetRenderState is a special callback value used by the user to request the renderer to reset render state.) if (cmd.resetRenderState) setupRenderState(drawData, fbWidth, fbHeight) else userCB(cmdList, cmd) } else { // Project scissor/clipping rectangles into framebuffer space val clipRectX = (cmd.clipRect.x - clipOff.x) * clipScale.x val clipRectY = (cmd.clipRect.y - clipOff.y) * clipScale.y val clipRectZ = (cmd.clipRect.z - clipOff.x) * clipScale.x val clipRectW = (cmd.clipRect.w - clipOff.y) * clipScale.y if (clipRectX < fbWidth && clipRectY < fbHeight && clipRectZ >= 0f && clipRectW >= 0f) { // Apply scissor/clipping rectangle glScissor(clipRectX.i, (fbHeight - clipRectW).i, (clipRectZ - clipRectX).i, (clipRectW - clipRectY).i) // Bind texture, Draw glBindTexture(GL_TEXTURE_2D, cmd.textureId!!) if (MAY_HAVE_DRAW_WITH_BASE_VERTEX && glVersion >= 320) glDrawElementsBaseVertex(GL_TRIANGLES, cmd.elemCount, GL_UNSIGNED_INT, cmd.idxOffset.L * DrawIdx.BYTES, cmd.vtxOffset) else glDrawElements(GL_TRIANGLES, cmd.elemCount, GL_UNSIGNED_INT, cmd.idxOffset.L * DrawIdx.BYTES) } } idxBufferOffset += cmd.elemCount * DrawIdx.BYTES } } // Restore modified GL state glUseProgram(lastProgram) glBindTexture(GL_TEXTURE_2D, lastTexture) if (OPENGL_MAY_HAVE_BIND_SAMPLER && glVersion > 330) glBindSampler(0, lastSampler) glActiveTexture(lastActiveTexture) glBindVertexArray(lastVertexArray) glBindBuffer(GL_ARRAY_BUFFER, lastArrayBuffer) glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, lastElementBuffer) glBlendEquationSeparate(lastBlendEquationRgb, lastBlendEquationAlpha) glBlendFuncSeparate(lastBlendSrcRgb, lastBlendDstRgb, lastBlendSrcAlpha, lastBlendDstAlpha) if (lastEnableBlend) glEnable(GL_BLEND) else glDisable(GL_BLEND) if (lastEnableCullFace) glEnable(GL_CULL_FACE) else glDisable(GL_CULL_FACE) if (lastEnableDepthTest) glEnable(GL_DEPTH_TEST) else glDisable(GL_DEPTH_TEST) if (lastEnableScissorTest) glEnable(GL_SCISSOR_TEST) else glDisable(GL_SCISSOR_TEST) if (POLYGON_MODE) glPolygonMode(GL_FRONT_AND_BACK, lastPolygonMode) glViewport(lastViewport) glScissor(lastScissorBox) } /** Build texture atlas */ override fun createFontsTexture(): Boolean { /* Load as RGBA 32-bit (75% of the memory is wasted, but default font is so small) because it is more likely to be compatible with user's existing shaders. If your ImTextureId represent a higher-level concept than just a GL texture id, consider calling GetTexDataAsAlpha8() instead to save on GPU memory. */ val (pixels, size) = io.fonts.getTexDataAsRGBA32() // Upload texture to graphics system val lastTexture = glGetInteger(GL_TEXTURE_BINDING_2D) glGenTextures(fontTexture) glBindTexture(GL_TEXTURE_2D, fontTexture[0]) glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR) glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR) if (UNPACK_ROW_LENGTH) glPixelStorei(GL_UNPACK_ROW_LENGTH, 0) glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, size.x, size.y, 0, GL_RGBA, GL_UNSIGNED_BYTE, pixels) // Store our identifier io.fonts.texID = fontTexture[0] // Restore state glBindTexture(GL_TEXTURE_2D, lastTexture) return when { DEBUG -> checkError("mainLoop") else -> true } } override fun destroyFontsTexture() { if (fontTexture[0] != 0) { glDeleteTextures(fontTexture) io.fonts.texID = 0 fontTexture[0] = 0 } } override fun createDeviceObjects(): Boolean { // Backup GL state [JVM] we have to save also program since we do the uniform mat and texture setup once here val lastProgram = glGetInteger(GL_CURRENT_PROGRAM) val lastTexture = glGetInteger(GL_TEXTURE_BINDING_2D) val lastArrayBuffer = glGetInteger(GL_ARRAY_BUFFER_BINDING) val lastElementBuffer = glGetInteger(GL_ELEMENT_ARRAY_BUFFER_BINDING) program = createProgram() program.use { matUL = "ProjMtx".uniform "Texture".unit = semantic.sampler.DIFFUSE } // Create buffers buffers.gen() createFontsTexture() vao = GlVertexArray.gen() // Restore modified GL state glUseProgram(lastProgram) glBindTexture(GL_TEXTURE_2D, lastTexture) glBindBuffer(GL_ARRAY_BUFFER, lastArrayBuffer) glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, lastElementBuffer) return when { DEBUG -> checkError("mainLoop") else -> true } } override fun destroyDeviceObjects() { vao.delete() buffers.delete() if (program.isValid) program.delete() destroyFontsTexture() } companion object { var OPENGL_ES2 = false var OPENGL_ES3 = false // Desktop GL 3.2+ has glDrawElementsBaseVertex() which GL ES and WebGL don't have. val OPENGL_MAY_HAVE_VTX_OFFSET by lazy { !OPENGL_ES2 && !OPENGL_ES3 && glVersion >= 330 } // Desktop GL 3.3+ has glBindSampler() val OPENGL_MAY_HAVE_BIND_SAMPLER by lazy { !OPENGL_ES2 && !OPENGL_ES3 && glVersion >= 330 } var CLIP_ORIGIN = false && Platform.get() != Platform.MACOSX var POLYGON_MODE = true var UNPACK_ROW_LENGTH = true var SINGLE_GL_CONTEXT = true // #if defined(IMGUI_IMPL_OPENGL_ES2) || defined(IMGUI_IMPL_OPENGL_ES3) || !defined(GL_VERSION_3_2) -> false var MAY_HAVE_DRAW_WITH_BASE_VERTEX = true } /*private fun debugSave(fbWidth: Int, fbHeight: Int) { if (g.frameCount % 60 == 0) { glReadBuffer(GL11C.GL_BACK) // no more alignment problems by texture updating glPixelStorei(GL_UNPACK_ALIGNMENT, 1) // upload glPixelStorei(GL_PACK_ALIGNMENT, 1) // download val colorBufferImg = BufferedImage(fbWidth, fbHeight, BufferedImage.TYPE_INT_ARGB) val graphicsColor = colorBufferImg.graphics val buffer = ByteBuffer(fbWidth * fbHeight * 4) glReadPixels(0, 0, fbWidth, fbHeight, GL_RGBA, GL_UNSIGNED_BYTE, buffer) var i = 0 for (h in 0 until fbHeight) { for (w in 0 until fbWidth) { val iR = buffer[i + 0].toUInt() val iG = buffer[i + 1].toUInt() val iB = buffer[i + 2].toUInt() val iA = buffer[i + 3].toInt() and 0xff graphicsColor.color = Color(iR, iG, iB, iA) graphicsColor.fillRect(w, fbHeight - h - 1, 1, 1) // height - h is for flipping the image i += 4 } } val imgNameColor = "whate_(${System.currentTimeMillis()}).png" ImageIO.write(colorBufferImg, "png", File("""C:\Users\gbarbieri\Pictures\$imgNameColor""")) graphicsColor.dispose() buffer.free() } }*/ }
23
null
34
531
0091e9b297eb940cd91a78bb71c3036bb4463269
15,062
imgui
MIT License
src/com/github/bhryno/chlorine/util/Utils.kt
Bhryno
731,845,405
false
{"Kotlin": 6268}
package com.github.bhryno.chlorine.util import com.github.bhryno.chlorine.model.ModelRegistry import com.google.gson.Gson import com.google.gson.GsonBuilder import java.io.FileReader import java.util.prefs.Preferences typealias RegistryCallback = (String) -> Unit object RegistryUtil { fun registryWrite( hive: String, path: String, type: String, value: String, key: String, name: String, ignore: String, folder: String, callback: RegistryCallback ) { val result = runCatching { val node = when (hive) { "HKEY_CURRENT_USER" -> Preferences.userRoot() "HKEY_LOCAL_MACHINE" -> Preferences.systemRoot() else -> throw Exception("Invalid hive") } val registryType = when (type) { "REG_DWORD" -> 4 "REG_SZ" -> 1 "REG_QWORD" -> 11 "REG_BINARY" -> 3 "REG_MULTI_SZ" -> 7 "REG_EXPAND_SZ" -> 2 else -> throw Exception("Invalid type") } val registryValue = when (type) { "REG_SZ", "REG_EXPAND_SZ", "REG_MULTI_SZ" -> value "REG_QWORD" -> value.toLong().toString() "REG_BINARY" -> value.toByteArray().joinToString(",") else -> throw Exception("Invalid type") } val originalRegistry = node.node(path) val currentRegistry = node.node("$path\\$key") // Create key originalRegistry.node(key) currentRegistry.put(name, registryValue) callback("Wrote to registry: $key in $hive with name $node.") }.onFailure { e -> callback("Error: ${e.message}") }.getOrNull() result?.let { println("Result: $it") } } } object JsonUtil { fun jsonRead(fileName: String): List<ModelRegistry>? { val gson = Gson() return runCatching { FileReader(fileName).use { reader -> gson.fromJson(reader, Array<ModelRegistry>::class.java).toList() } }.onFailure { e -> e.printStackTrace() }.getOrNull() } }
0
Kotlin
0
0
5f4cd7b100c6e17b0c7924c37751fd6eeb7bca98
2,272
Chlorine
MIT License
port-out/src/main/kotlin/com/yapp/bol/group/member/MemberCommandRepository.kt
YAPP-Github
634,125,780
false
null
package com.yapp.bol.group.member interface MemberCommandRepository { fun createMember(member: Member): Member fun createMembers(members: MemberList): MemberList }
6
Kotlin
0
9
b3b6b4824fb5ea417a85d3c6c147021dec8ccf97
174
22nd-Android-Team-2-BE
Apache License 2.0
app/src/main/java/com/example/fitme/core/ui/BaseActivity.kt
anarkulov
438,526,656
false
{"Kotlin": 128897}
package com.example.fitme.core.ui import android.os.Bundle import android.view.LayoutInflater import android.widget.ProgressBar import androidx.appcompat.app.AppCompatActivity import androidx.viewbinding.ViewBinding import com.example.fitme.R import com.example.fitme.core.extentions.visible abstract class BaseActivity<out VM : BaseViewModel, VB : ViewBinding>: AppCompatActivity() { protected abstract val viewModel: VM protected lateinit var binding: VB protected abstract fun inflateViewBinding(inflater: LayoutInflater): VB override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) binding = inflateViewBinding(LayoutInflater.from(this)) setContentView(binding.root) initViewModel() initView() initListeners() } open fun initViewModel() { // viewModel.loading.observe(this, { // findViewById<ProgressBar>(R.id.progress_bar).visible = it // }) } open fun initView() {} open fun initListeners() {} fun showLoading(value: Boolean) { viewModel.loading.postValue(value) } }
0
Kotlin
0
1
6ab4414c8822fdbf3f69178889c81e55ec4f5d84
1,138
fitMe
MIT License
app/src/main/java/com/sirekanian/warmongr/data/local/TagEntity.kt
sirekanian
537,624,000
false
null
package com.sirekanian.warmongr.data.local import androidx.room.Entity import androidx.room.PrimaryKey @Entity class TagEntity( @PrimaryKey val id: Int, val name: String, val ruName: String, )
0
Kotlin
1
1
bdce92ed3842eab97e8ffb192f55785987ca761e
210
warmongr
MIT License
common/src/main/java/common/IoDispatcher.kt
lcszc
256,382,727
false
{"Kotlin": 201531}
package common import javax.inject.Qualifier @Qualifier @MustBeDocumented @Retention annotation class IoDispatcher
2
Kotlin
2
35
a2f02de29c4c074b5ecbda4a46349ac5b864842d
117
Boletinhos
MIT License
app/src/main/java/io/github/drumber/kitsune/util/rating/RatingSystemUtil.kt
Drumber
406,471,554
false
{"Kotlin": 797542, "Ruby": 2045}
package io.github.drumber.kitsune.util import io.github.drumber.kitsune.domain.model.infrastructure.user.RatingSystemPreference import io.github.drumber.kitsune.domain.repository.UserRepository import org.koin.core.component.KoinComponent import org.koin.core.component.inject import kotlin.math.floor import kotlin.math.roundToInt object RatingSystemUtil : KoinComponent { private val DEFAULT = RatingSystemPreference.Regular private val userRepository: UserRepository by inject() fun getRatingSystem(): RatingSystemPreference { return userRepository.user?.ratingSystem ?: DEFAULT } fun formatRating(ratingTwenty: Int, ratingSystem: RatingSystemPreference = getRatingSystem()): String { return ratingSystem.convertFrom(ratingTwenty).toString() } fun Int.formatRatingTwenty() = formatRating(this) fun Int.fromRatingTwentyTo(ratingSystem: RatingSystemPreference = getRatingSystem()) = ratingSystem.convertFrom(this) fun Float.toRatingTwentyFrom(ratingSystem: RatingSystemPreference = getRatingSystem()) = ratingSystem.convertToRatingTwenty(this) fun RatingSystemPreference.convertFrom(ratingTwenty: Int): Float { return when (this) { RatingSystemPreference.Simple -> when (ratingTwenty) { in 1..7 -> 1f in 8..13 -> 2f in 14..19 -> 3f else -> 4f } RatingSystemPreference.Regular -> (ratingTwenty / 2.0f).roundToInt() / 2.0f RatingSystemPreference.Advanced -> ratingTwenty / 2.0f } } fun RatingSystemPreference.convertToRatingTwenty(rating: Float): Int { return when (this) { RatingSystemPreference.Simple -> when (rating) { 1f -> 2 2f -> 8 3f -> 14 else -> 20 } RatingSystemPreference.Regular -> floor(rating * 4).toInt() RatingSystemPreference.Advanced -> floor(rating * 2).toInt() } } fun RatingSystemPreference.stepSize(): Float { return when (this) { RatingSystemPreference.Simple -> 1f RatingSystemPreference.Regular -> 0.5f RatingSystemPreference.Advanced -> 0.5f } } }
7
Kotlin
4
61
6ab88cfacd8ee4daad23edbe4a134ab1f2b1f62c
2,286
Kitsune
Apache License 2.0
src/main/kotlin/com/framstag/semtrail/parser/IntegerValue.kt
Framstag
166,638,904
false
{"Kotlin": 54869, "HTML": 9890, "CSS": 5572, "Dockerfile": 432, "Shell": 182}
package com.framstag.semtrail.parser class IntegerValue : Value { override fun isIntegerValue(): Boolean { return true } override fun toIntegerValue(): IntegerValue { return this } }
7
Kotlin
0
0
af5a9bea2d92e71de52c36fb3e74887c14297d1f
216
semtrail
Apache License 2.0
bandyer-android-design/src/main/java/com/bandyer/sdk_design/bottom_sheet/BandyerActionBottomSheet.kt
Bandyer
337,367,845
false
null
/* * Copyright 2021-2022 Bandyer @ https://www.bandyer.com * * 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.bandyer.sdk_design.bottom_sheet import androidx.annotation.StyleRes import androidx.appcompat.app.AppCompatActivity import com.bandyer.sdk_design.bottom_sheet.items.ActionItem import com.bandyer.sdk_design.bottom_sheet.view.BottomSheetLayoutType /** * A Bandyer BottomSheet specialized in handling actions * @author kristiyan */ open class BandyerActionBottomSheet<T> constructor(context: AppCompatActivity, views: List<T>, peekHeight: Int?, bottomSheetLayoutType: BottomSheetLayoutType, @StyleRes bottomSheetLayoutStyle: Int) : BaseBandyerBottomSheet(context, views, peekHeight, bottomSheetLayoutType, bottomSheetLayoutStyle) where T : ActionItem { /** * Listener for actions on the items of the bottomSheet */ var onActionBottomSheetListener: OnActionBottomSheetListener<*, *>? = null /** * Generic interface handling action events * * @param T ActionItem where the event has been fired from * @param F BottomSheet enclosing the actions * @constructor Create On action bottom sheet listener */ fun interface OnActionBottomSheetListener<T, F> where T : ActionItem, F : BandyerBottomSheet { /** * Called when an action has received a click event * @param bottomSheet F bottomSheet container * @param action T action clicked * @param position Int position of item in the bottomSheet * @return true if handled false otherwise */ fun onActionClicked(bottomSheet: F, action: T, position: Int): Boolean } }
0
Kotlin
1
1
d25c7b14302015cdad2df298391a2cb891df1a8e
2,392
Bandyer-Android-Design
Apache License 2.0
src/main/kotlin/com/autonomousapps/internal/android/AndroidGradlePlugin4_2.kt
autonomousapps
217,134,508
false
null
@file:Suppress("ClassName", "UnstableApiUsage") package com.autonomousapps.internal.android import com.android.build.gradle.BaseExtension import org.gradle.api.Project import org.gradle.api.file.RegularFile import org.gradle.api.file.RegularFileProperty import org.gradle.api.provider.Provider import org.gradle.kotlin.dsl.the import org.gradle.kotlin.dsl.withGroovyBuilder internal class AndroidGradlePlugin4_2( project: Project, agpVersion: String ) : BaseAndroidGradlePlugin(project, agpVersion) { override val bundleTaskType: String = "com.android.build.gradle.internal.tasks.BundleLibraryClassesJar" override val bundleTaskOutputMethodName: String = "getOutput" override fun getBundleTaskOutput(variantName: String): Provider<RegularFile> { val bundleTaskName = "bundleLibCompileToJar$variantName" val type = getBundleTaskType() val task = project.tasks.named(bundleTaskName, type) val outputMethod = getOutputMethod(type) return task.flatMap { outputMethod.invoke(it) as RegularFileProperty } } override fun isViewBindingEnabled(): Boolean = project.the<BaseExtension>().withGroovyBuilder { getProperty("buildFeatures").withGroovyBuilder { getProperty("viewBinding") } as Boolean? ?: false } override fun isDataBindingEnabled(): Boolean = project.the<BaseExtension>().withGroovyBuilder { getProperty("buildFeatures").withGroovyBuilder { getProperty("dataBinding") } as Boolean? ?: false } }
70
null
51
775
e9a79a956c859b525d24879c91f2e728396566b6
1,475
dependency-analysis-android-gradle-plugin
Apache License 2.0
components/core/ktx/src/main/java/com/flipperdevices/core/ktx/jre/AtomicInt.kt
flipperdevices
288,258,832
false
{"Kotlin": 2760721, "FreeMarker": 10084, "CMake": 1780, "C++": 1152, "Fluent": 21}
package com.flipperdevices.core.ktx.jre import java.util.concurrent.atomic.AtomicInteger /** * Copy from AtomicInteger#updateAndGet */ fun AtomicInteger.updateAndGetSafe(updater: (Int) -> Int): Int { var prev: Int var next: Int do { prev = get() next = updater(prev) } while (!compareAndSet(prev, next)) return next }
13
Kotlin
131
999
ef27b6b6a78a59b603ac858de2c88f75b743f432
358
Flipper-Android-App
MIT License
app/src/main/java/top/maybesix/xhhttpdemo/MyApiResult.kt
maybesix
254,575,221
false
null
package top.maybesix.xhhttpdemo import top.maybesix.xhhttp.annotation.ApiRename import top.maybesix.xhhttp.annotation.ApiSuccessCode import top.maybesix.xhhttp.model.ApiResult /** * @author MaybeSix * @date 2020/5/6 * @desc TODO. */ class MyApiResult<T> : ApiResult<T>() { @ApiRename("errorCode") override var code: Int = 0 @ApiRename("errorMsg") override var msg: String = "" @ApiSuccessCode(0) override var successCode: Int = 0 }
0
Kotlin
0
3
b4258a91db8de220ccd02be94f353ad532fe4d6f
463
XHHttp
Apache License 2.0
android/SSOSDK/src/main/java/com/doters/ssosdk/models/RefreshToken.kt
solemti
647,001,598
false
null
package com.doters.ssosdk.models data class RefreshToken( val accessToken: String, val expiresIn: Int, val idToken: String, val refreshToken: String, val scope: String, val tokenType: String ) { constructor() : this("", 0, "", "", "", "") }
0
Kotlin
0
0
726d8abce16bb9c838e4ad600152066faf54a3ae
270
Doters-SSO-SDK-Android
MIT License
compiler/testData/diagnostics/tests/inline/capture.kt
JakeWharton
99,388,807
false
null
// FIR_IDENTICAL // LANGUAGE: +ForbidExtensionCallsOnInlineFunctionalParameters // DIAGNOSTICS: -UNUSED_EXPRESSION -UNUSED_PARAMETER -UNUSED_VARIABLE -NOTHING_TO_INLINE -NON_LOCAL_RETURN_NOT_ALLOWED infix fun Function1<Int, Unit>.noInlineExt(p: Int) {} inline infix fun Function1<Int, Unit>.inlineExt2(p: Int) { { noInlineExt(11) this.noInlineExt(11) this noInlineExt 11 this }() } inline fun Function1<Int, Unit>.inlineExt() { { inlineExt2(1) this.inlineExt2(1) this inlineExt2 1 this(11) }() } inline fun inlineFunWithInvoke(s: (p: Int) -> Unit) { { s(11) s.invoke(11) s <!INFIX_MODIFIER_REQUIRED!>invoke<!> 11 }() } inline fun inlineFunWithInvokeNonInline(noinline s: (p: Int) -> Unit) { { s(11) s.invoke(11) s <!INFIX_MODIFIER_REQUIRED!>invoke<!> 11 }() } inline fun testExtension(s: (p: Int) -> Unit) { { <!USAGE_IS_NOT_INLINABLE!>s<!>.inlineExt() } () } inline fun inlineFunWrongExtension(s: (p: Int) -> Unit) { { <!USAGE_IS_NOT_INLINABLE!>s<!>.noInlineExt(11) } () }
181
null
5748
83
4383335168338df9bbbe2a63cb213a68d0858104
1,158
kotlin
Apache License 2.0
Barlom-Foundation-JS/src/main/kotlin/x/barlom/infrastructure/uuids/Uuid.kt
martin-nordberg
82,682,055
false
null
// // (C) Copyright 2017-2018 <NAME> // Apache 2.0 License // package /*js*/x.barlom.infrastructure.uuids /** * JavaScript implementation of UUID as simple string container. */ class Uuid( val uuidStr: String ) : Comparable<Uuid> { /** * Compares this UUID with the specified UUID. The first of two UUIDs is greater than the second if the most * significant field in which the UUIDs differ is greater for the first UUID. * @param other `UUID` to which this `UUID` is to be compared * @return -1, 0 or 1 as this `UUID` is less than, equal to, or greater than `other` */ override operator fun compareTo(other: Uuid): Int { // The ordering is intentionally set up so that the UUIDs // can simply be numerically compared as two numbers return when { this.uuidStr < other.uuidStr -> -1 this.uuidStr > other.uuidStr -> 1 else -> 0 } } /** * Compares this object to the specified object. The result is `true` if and only if the argument is not `null`, is a `UUID` * object, has the same variant, and contains the same value, bit for bit, * as this `UUID`. * @param other The object to be compared * @return `true` if the objects are the same; `false` otherwise */ override fun equals(other: Any?): Boolean { if (null == other || other !is Uuid) { return false } return uuidStr == other.uuidStr } /** * Returns a hash code for this `UUID`. * @return A hash code value for this `UUID` */ override fun hashCode(): Int { return uuidStr.hashCode() } fun hasNextInReservedBlock(): Boolean { val nybble7 = uuidStr[7] val nybble6 = uuidStr[6] return nybble6 != 'F' || nybble7 != 'F' } fun nextInReservedBlock(): Uuid { check(hasNextInReservedBlock()) { "Reserved block exhausted." } val nybble7 = uuidStr[7] when (nybble7) { '0' -> return Uuid.fromString(uuidStr.substring(0, 7) + '1' + uuidStr.substring(8)) '1' -> return Uuid.fromString(uuidStr.substring(0, 7) + '2' + uuidStr.substring(8)) '2' -> return Uuid.fromString(uuidStr.substring(0, 7) + '3' + uuidStr.substring(8)) '3' -> return Uuid.fromString(uuidStr.substring(0, 7) + '4' + uuidStr.substring(8)) '4' -> return Uuid.fromString(uuidStr.substring(0, 7) + '5' + uuidStr.substring(8)) '5' -> return Uuid.fromString(uuidStr.substring(0, 7) + '6' + uuidStr.substring(8)) '6' -> return Uuid.fromString(uuidStr.substring(0, 7) + '7' + uuidStr.substring(8)) '7' -> return Uuid.fromString(uuidStr.substring(0, 7) + '8' + uuidStr.substring(8)) '8' -> return Uuid.fromString(uuidStr.substring(0, 7) + '9' + uuidStr.substring(8)) '9' -> return Uuid.fromString(uuidStr.substring(0, 7) + 'A' + uuidStr.substring(8)) 'A' -> return Uuid.fromString(uuidStr.substring(0, 7) + 'B' + uuidStr.substring(8)) 'B' -> return Uuid.fromString(uuidStr.substring(0, 7) + 'C' + uuidStr.substring(8)) 'C' -> return Uuid.fromString(uuidStr.substring(0, 7) + 'D' + uuidStr.substring(8)) 'D' -> return Uuid.fromString(uuidStr.substring(0, 7) + 'E' + uuidStr.substring(8)) 'E' -> return Uuid.fromString(uuidStr.substring(0, 7) + 'F' + uuidStr.substring(8)) } val nybble6 = uuidStr[6] when (nybble6) { '0' -> return Uuid.fromString(uuidStr.substring(0, 6) + "10" + uuidStr.substring(8)) '1' -> return Uuid.fromString(uuidStr.substring(0, 6) + "20" + uuidStr.substring(8)) '2' -> return Uuid.fromString(uuidStr.substring(0, 6) + "30" + uuidStr.substring(8)) '3' -> return Uuid.fromString(uuidStr.substring(0, 6) + "40" + uuidStr.substring(8)) '4' -> return Uuid.fromString(uuidStr.substring(0, 6) + "50" + uuidStr.substring(8)) '5' -> return Uuid.fromString(uuidStr.substring(0, 6) + "60" + uuidStr.substring(8)) '6' -> return Uuid.fromString(uuidStr.substring(0, 6) + "70" + uuidStr.substring(8)) '7' -> return Uuid.fromString(uuidStr.substring(0, 6) + "80" + uuidStr.substring(8)) '8' -> return Uuid.fromString(uuidStr.substring(0, 6) + "90" + uuidStr.substring(8)) '9' -> return Uuid.fromString(uuidStr.substring(0, 6) + "A0" + uuidStr.substring(8)) 'A' -> return Uuid.fromString(uuidStr.substring(0, 6) + "B0" + uuidStr.substring(8)) 'B' -> return Uuid.fromString(uuidStr.substring(0, 6) + "C0" + uuidStr.substring(8)) 'C' -> return Uuid.fromString(uuidStr.substring(0, 6) + "D0" + uuidStr.substring(8)) 'D' -> return Uuid.fromString(uuidStr.substring(0, 6) + "E0" + uuidStr.substring(8)) 'E' -> return Uuid.fromString(uuidStr.substring(0, 6) + "F0" + uuidStr.substring(8)) } throw IllegalArgumentException("Reserved block exhausted.") } /** * Returns a `String` object representing this `UUID`. * * The UUID string representation is as described by this BNF: * UUID = <time_low> "-" <time_mid> "-" * <time_high_and_version> "-" * <variant_and_sequence> "-" * <node> * time_low = 4*<hexOctet> * time_mid = 2*<hexOctet> * time_high_and_version = 2*<hexOctet> * variant_and_sequence = 2*<hexOctet> * node = 6*<hexOctet> * hexOctet = <hexDigit><hexDigit> * hexDigit = * "0" | "1" | "2" | "3" | "4" | "5" | "6" | "7" | "8" | "9" * | "a" | "b" | "c" | "d" | "e" | "f" * | "A" | "B" | "C" | "D" | "E" | "F" * @return A string representation of this `UUID` */ override fun toString(): String { return uuidStr } companion object { /** * Creates a `UUID` from the string standard representation as described in the [.toString] method. * @param uuidStr A string that specifies a `UUID`. * @return A `UUID` with the specified value. * TODO: check the format of the input */ fun fromString(uuidStr: String): Uuid { return Uuid(uuidStr) } } }
0
Kotlin
0
0
337b46f01f6eec6dfb3b86824c26f1c103e9d9a2
6,392
ZZ-Barlom
Apache License 2.0
app/src/main/java/com/awalideck/moovies/popularmovies/CategoryMovieFragment.kt
davidwekesar
376,802,342
false
null
package com.awalideck.moovies.popularmovies import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.fragment.app.Fragment import androidx.lifecycle.ViewModelProvider import androidx.navigation.fragment.findNavController import com.awalideck.moovies.databinding.FragmentCategoryMovieBinding class CategoryMovieFragment : Fragment() { private var _binding: FragmentCategoryMovieBinding? = null private val binding get() = _binding!! private lateinit var viewModel: MoviesViewModel private lateinit var viewModelFactory: MoviesViewModelFactory override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View { _binding = FragmentCategoryMovieBinding.inflate(inflater, container, false) arguments?.takeIf { it.containsKey(ARG_CATEGORY_PATH) }?.apply { val path = getString(ARG_CATEGORY_PATH) path?.let { viewModelFactory = MoviesViewModelFactory(it) } } viewModel = ViewModelProvider(this, viewModelFactory) .get(MoviesViewModel::class.java) viewModel.response.observe(viewLifecycleOwner, { movies -> val movieAdapter = MovieAdapter(requireContext(), movies, MovieItemListener { movieId -> val action = MoviesFragmentDirections.actionMoviesFragmentToDetailsActivity(movieId) findNavController().navigate(action) }) binding.movieList.adapter = movieAdapter }) return binding.root } override fun onDestroyView() { super.onDestroyView() _binding = null } }
0
Kotlin
0
0
9de6ffac3c5c79015b958fc9780f9f21518ef3d6
1,744
Moovies
MIT License
app/src/main/java/ca/andries/vpnmanager/RuleMode.kt
DJAndries
411,571,682
false
null
package ca.andries.vpnmanager enum class RuleMode { ALL, SOME, NONE }
0
Kotlin
0
0
be14a888fc006e417fe9b529890eaeb598b74558
82
vpnmanager-android
MIT License