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
kotlinx-nodejs/src/nonDeclarations.net.kt
Kotlin
254,635,065
false
null
@file:Suppress("INTERFACE_WITH_SUPERCLASS", "OVERRIDING_FINAL_MEMBER", "RETURN_TYPE_MISMATCH_ON_OVERRIDE") package net import kotlin.js.* import kotlin.js.Json import org.khronos.webgl.* import org.w3c.dom.* import org.w3c.dom.events.* import org.w3c.dom.parsing.* import org.w3c.dom.svg.* import org.w3c.dom.url.* import org.w3c.fetch.* import org.w3c.files.* import org.w3c.notifications.* import org.w3c.performance.* import org.w3c.workers.* import org.w3c.xhr.* import dns.LookupOneOptions import NodeJS.ErrnoException typealias LookupFunction = (hostname: String, options: LookupOneOptions, callback: (err: ErrnoException?, address: String, family: Number) -> Unit) -> Unit external interface AddressInfo { var address: String var family: String var port: Number } external interface SocketConstructorOpts { var fd: Number? get() = definedExternally set(value) = definedExternally var allowHalfOpen: Boolean? get() = definedExternally set(value) = definedExternally var readable: Boolean? get() = definedExternally set(value) = definedExternally var writable: Boolean? get() = definedExternally set(value) = definedExternally } external interface OnReadOpts { var buffer: dynamic /* Uint8Array | () -> Uint8Array */ get() = definedExternally set(value) = definedExternally fun callback(bytesWritten: Number, buf: Uint8Array): Boolean } external interface ConnectOpts { var onread: OnReadOpts? get() = definedExternally set(value) = definedExternally } external interface TcpSocketConnectOpts : ConnectOpts { var port: Number var host: String? get() = definedExternally set(value) = definedExternally var localAddress: String? get() = definedExternally set(value) = definedExternally var localPort: Number? get() = definedExternally set(value) = definedExternally var hints: Number? get() = definedExternally set(value) = definedExternally var family: Number? get() = definedExternally set(value) = definedExternally var lookup: LookupFunction? get() = definedExternally set(value) = definedExternally } external interface IpcSocketConnectOpts : ConnectOpts { var path: String } external interface ListenOptions { var port: Number? get() = definedExternally set(value) = definedExternally var host: String? get() = definedExternally set(value) = definedExternally var backlog: Number? get() = definedExternally set(value) = definedExternally var path: String? get() = definedExternally set(value) = definedExternally var exclusive: Boolean? get() = definedExternally set(value) = definedExternally var readableAll: Boolean? get() = definedExternally set(value) = definedExternally var writableAll: Boolean? get() = definedExternally set(value) = definedExternally var ipv6Only: Boolean? get() = definedExternally set(value) = definedExternally } external interface `T$9` { var allowHalfOpen: Boolean? get() = definedExternally set(value) = definedExternally var pauseOnConnect: Boolean? get() = definedExternally set(value) = definedExternally } external interface TcpNetConnectOpts : TcpSocketConnectOpts, SocketConstructorOpts { var timeout: Number? get() = definedExternally set(value) = definedExternally } external interface IpcNetConnectOpts : IpcSocketConnectOpts, SocketConstructorOpts { var timeout: Number? get() = definedExternally set(value) = definedExternally }
11
Kotlin
18
211
7321c520021a9603cee2918e0724a89a51547831
3,796
kotlinx-nodejs
Apache License 2.0
app/src/main/java/com/tomorrowit/budgetgamer/common/di/PreferencesModule.kt
2Morrow-IT-Solutions
848,266,910
false
{"Kotlin": 429313}
package com.tomorrowit.budgetgamer.common.di import android.content.Context import androidx.datastore.core.DataStore import androidx.datastore.preferences.core.Preferences import com.tomorrowit.budgetgamer.common.config.extensions.dataStore import com.tomorrowit.budgetgamer.data.local.prefs.DataStorePreferences import dagger.Module import dagger.Provides import dagger.hilt.InstallIn import dagger.hilt.android.qualifiers.ApplicationContext import dagger.hilt.components.SingletonComponent import kotlinx.coroutines.CoroutineDispatcher import javax.inject.Singleton @Module @InstallIn(SingletonComponent::class) object PreferencesModule { @Provides @Singleton fun provideDataStore(@ApplicationContext context: Context): DataStore<Preferences> { return context.dataStore } @Provides @Singleton fun provideDataStorePreferences( dataStore: DataStore<Preferences>, @IoDispatcher coroutineDispatcher: CoroutineDispatcher ): DataStorePreferences { return DataStorePreferences(dataStore, coroutineDispatcher) } }
0
Kotlin
2
5
edcaff45925e39c15fa3ff8cb054bf06904c3cdf
1,079
budget-gamer-android
MIT License
data/src/main/java/com/eyther/lumbridge/data/model/loan/local/LoanCached.kt
ruialmeida51
249,223,684
false
{"Kotlin": 904675}
package com.eyther.lumbridge.data.model.loan.local data class LoanCached( val id: Long = -1, val name: String, val startDate: String, val endDate: String, val currentAmount: Float, val initialAmount: Float, val fixedTaegInterestRate: Float?, val variableEuribor: Float?, val variableSpread: Float?, val fixedTanInterestRate: Float?, val loanTypeOrdinal: Int, val loanCategoryOrdinal: Int )
6
Kotlin
0
7
5dd18b22448b2435f0238cccfc11a6826f200748
439
lumbridge-android
MIT License
exposed-dao/src/main/kotlin/org/jetbrains/exposed/dao/UUIDEntity.kt
JetBrains
11,765,017
false
{"Kotlin": 2350713}
package org.jetbrains.exposed.dao import org.jetbrains.exposed.dao.id.EntityID import org.jetbrains.exposed.dao.id.IdTable import java.util.* /** Base class for an [Entity] instance identified by an [id] comprised of a wrapped `UUID` value. */ abstract class UUIDEntity(id: EntityID<UUID>) : Entity<UUID>(id) /** * Base class representing the [EntityClass] that manages [UUIDEntity] instances and * maintains their relation to the provided [table]. * * @param [table] The [IdTable] object that stores rows mapped to entities of this class. * @param [entityType] The expected [UUIDEntity] type. This can be left `null` if it is the class of type * argument [E] provided to this [UUIDEntityClass] instance. If this `UUIDEntityClass` is defined as a companion * object of a custom `UUIDEntity` class, the parameter will be set to this immediately enclosing class by default. * @sample org.jetbrains.exposed.sql.tests.shared.DDLTests.testDropTableFlushesCache * @param [entityCtor] The function invoked to instantiate a [UUIDEntity] using a provided [EntityID] value. * If a reference to a specific constructor or a custom function is not passed as an argument, reflection will * be used to determine the primary constructor of the associated entity class on first access. If this `UUIDEntityClass` * is defined as a companion object of a custom `UUIDEntity` class, the constructor will be set to that of the * immediately enclosing class by default. * @sample org.jetbrains.exposed.sql.tests.shared.entities.EntityTests.testExplicitEntityConstructor */ abstract class UUIDEntityClass<out E : UUIDEntity>( table: IdTable<UUID>, entityType: Class<E>? = null, entityCtor: ((EntityID<UUID>) -> E)? = null ) : EntityClass<UUID, E>(table, entityType, entityCtor)
171
Kotlin
693
8,319
95712943cc3550e4018342d725b42371808be845
1,784
Exposed
Apache License 2.0
app/src/main/java/com/wwy/android/data/bean/base/GankResponse.kt
wwy863399246
209,758,901
false
null
package com.wwy.android.data.bean.base /** *@创建者wwy *@创建时间 2019/10/8 15:13 *@描述 */ data class GankResponse<out T>(var status: Int, val data: T)
0
Kotlin
9
71
672b054b5c1aba0b323e8e082a3dea13b25bf971
148
WanAndroid
Apache License 2.0
jetpack-hero/src/main/java/dev/itscorey/jetpackheromorphing/MainActivity.kt
lcszc
261,602,180
false
{"Kotlin": 2718}
package dev.itscorey.jetpackheromorphing import android.graphics.drawable.Animatable import android.os.Bundle import android.os.Handler import androidx.appcompat.app.AppCompatActivity import androidx.core.view.isVisible import androidx.vectordrawable.graphics.drawable.Animatable2Compat import kotlinx.android.synthetic.main.activity_main.* class MainActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) Handler().postDelayed({ imageHero.run { (drawable as Animatable).start() } }, 500) } }
4
Kotlin
1
9
5d88ec4cc8070a3c25cb18d0019b1b6bfd97482b
681
Trench
The Unlicense
app/src/main/java/com/z1/pokedex/core/network/mapper/BaseDtoMapper.kt
zero1code
757,161,296
false
{"Kotlin": 245388}
package com.z1.pokedex.core.network.mapper interface BaseDtoMapper<Model, DTO> { fun asModel(dto: DTO): Model }
0
Kotlin
0
7
320b1c045b313ce8ca419a12732b5d8926e9e7e9
116
pokedex-z1
Apache License 2.0
tasks/src/main/java/app/tivi/tasks/SyncAllFollowedShows.kt
dogscar
295,140,633
true
{"Kotlin": 970147, "Shell": 2825, "Dockerfile": 1796}
/* * Copyright 2018 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * 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 app.tivi.tasks import android.content.Context import androidx.hilt.Assisted import androidx.hilt.work.WorkerInject import androidx.work.CoroutineWorker import androidx.work.WorkerParameters import app.tivi.data.entities.RefreshType import app.tivi.domain.interactors.UpdateFollowedShows import app.tivi.util.Logger import dagger.hilt.android.qualifiers.ApplicationContext class SyncAllFollowedShows @WorkerInject constructor( @Assisted params: WorkerParameters, @Assisted @ApplicationContext context: Context, private val updateFollowedShows: UpdateFollowedShows, private val logger: Logger ) : CoroutineWorker(context, params) { companion object { const val TAG = "sync-all-followed-shows" const val NIGHTLY_SYNC_TAG = "night-sync-all-followed-shows" } override suspend fun doWork(): Result { logger.d("$TAG worker running") updateFollowedShows.executeSync(UpdateFollowedShows.Params(true, RefreshType.FULL)) return Result.success() } }
0
null
0
0
80b8da5cfb0062a25fd9e8b3f058846f8d453f7d
1,616
tivi
Apache License 2.0
src/main/kotlin/com/balsdon/androidallyplugin/ui/CustomIcon.kt
qbalsdon
729,827,162
false
{"Kotlin": 202709, "Shell": 167}
package com.balsdon.androidallyplugin.ui import com.intellij.openapi.util.IconLoader import javax.swing.Icon enum class CustomIcon(private val fileReference: String) { PHONE("phone"), WATCH("watch"), EMULATOR("emulator"), EMULATOR_WATCH("emulator_watch"), A11Y_OPEN_MENU("open_menu"), REFRESH("sync"), A11Y_ACTIONS("actions"), A11Y_SWIPE_LEFT("swipe_left"), A11Y_SWIPE_RIGHT("swipe_right"), A11Y_TAP("tap"), A11Y_TAP_LONG("tap_long"), INFO("info"), DEVICE_BACK("back"), DEVICE_HOME("home"), ; private fun createFileReference() = "$imageFolder$fileReference$imageType" fun create(): Icon = IconLoader.getIcon( createFileReference(), CustomIcon::class.java ) private val imageFolder = "/icons/" private val imageType = ".svg" }
0
Kotlin
0
3
8dad5a8000d686643e6b125d5f8e5fcc70d24ad9
846
android-ally-plugin
MIT License
app/src/main/java/org/loecasi/android/di/AppModule.kt
ramadani
107,663,364
false
{"Gradle": 3, "Shell": 1, "Text": 1, "Ignore List": 2, "Batchfile": 1, "Markdown": 1, "Java Properties": 1, "Proguard": 1, "Kotlin": 20, "XML": 14, "Java": 1}
package org.loecasi.android.di import android.app.Application import android.content.Context import dagger.Module import dagger.Provides import javax.inject.Singleton /** * Created by dani on 10/25/17. */ @Module class AppModule { @Provides @Singleton fun provideContext(app: Application): Context = app }
0
Kotlin
0
0
3410213d9ba8fe3a9080cee748ea3f8aeb9b1d66
323
Loecasi
MIT License
components/src/test/java/com/mercadolibre/android/andesui/button/AndesButtonA11YTest.kt
maaguero
252,283,086
false
{"Gradle": 9, "Markdown": 17, "Java Properties": 1, "Shell": 1, "Ignore List": 4, "Batchfile": 1, "YAML": 5, "XML": 150, "Proguard": 3, "Kotlin": 311, "INI": 1, "HTML": 1, "JSON": 1, "Java": 1}
package com.mercadolibre.android.andesui.button import android.app.Activity import android.content.Context import android.os.Build import android.view.View import android.view.accessibility.AccessibilityNodeInfo import android.widget.Button import androidx.test.core.app.ApplicationProvider import com.facebook.common.logging.FLog import com.facebook.drawee.backends.pipeline.Fresco import com.facebook.imagepipeline.core.ImagePipelineConfig import com.facebook.imagepipeline.listener.RequestListener import com.facebook.imagepipeline.listener.RequestLoggingListener import com.facebook.soloader.SoLoader import org.junit.Assert.assertEquals import org.junit.Before import org.junit.Test import org.junit.runner.RunWith import org.robolectric.Robolectric import org.robolectric.RobolectricTestRunner import org.robolectric.annotation.Config @RunWith(RobolectricTestRunner::class) @Config(sdk = [Build.VERSION_CODES.LOLLIPOP]) class AndesButtonA11YTest { private lateinit var context: Context private lateinit var andesButton: AndesButton private lateinit var nodeInfo: AccessibilityNodeInfo @Before fun setup() { context = ApplicationProvider.getApplicationContext() SoLoader.setInTestMode() val requestListeners = setOf<RequestListener>(RequestLoggingListener()) val config = ImagePipelineConfig.newBuilder(context) // other setters .setRequestListeners(requestListeners) .build() Fresco.initialize(context, config) FLog.setMinimumLoggingLevel(FLog.VERBOSE) } @Test fun `andes button correct role description`() { andesButton = AndesButton(context) val roleDescription = Button::class.java.name assertEquals(roleDescription, andesButton.accessibilityClassName) } @Test fun `verify that info content description is set for accessibility`() { val activity = Activity() val robolectricActivity = Robolectric.setupActivity(activity::class.java) val buttonText = "button text" andesButton = AndesButton(context = context, buttonText = buttonText) andesButton.addOnAttachStateChangeListener(object : View.OnAttachStateChangeListener { override fun onViewDetachedFromWindow(p0: View?) { TODO("Not yet implemented") } override fun onViewAttachedToWindow(p0: View?) { nodeInfo = andesButton.createAccessibilityNodeInfo() andesButton.onInitializeAccessibilityNodeInfo(nodeInfo) assertEquals(buttonText, nodeInfo.contentDescription) } }) robolectricActivity.setContentView(andesButton) } }
1
null
1
1
bc12913d8a91c4a71faed6ba7e5d6fdfa16de123
2,723
fury_andesui-android
MIT License
fluent-icons-extended/src/commonMain/kotlin/com/konyaco/fluent/icons/regular/DualScreenSettings.kt
Konyaco
574,321,009
false
null
package com.konyaco.fluent.icons.regular import androidx.compose.ui.graphics.vector.ImageVector import com.konyaco.fluent.icons.Icons import com.konyaco.fluent.icons.fluentIcon import com.konyaco.fluent.icons.fluentPath public val Icons.Regular.DualScreenSettings: ImageVector get() { if (_dualScreenSettings != null) { return _dualScreenSettings!! } _dualScreenSettings = fluentIcon(name = "Regular.DualScreenSettings") { fluentPath { moveTo(13.28f, 2.98f) arcToRelative(2.0f, 2.0f, 0.0f, false, true, -1.44f, 2.5f) lineToRelative(-0.59f, 0.14f) arcToRelative(5.73f, 5.73f, 0.0f, false, false, 0.01f, 1.8f) lineToRelative(0.54f, 0.13f) arcToRelative(2.0f, 2.0f, 0.0f, false, true, 1.45f, 2.51f) lineToRelative(-0.19f, 0.64f) curveToRelative(0.44f, 0.38f, 0.94f, 0.7f, 1.49f, 0.92f) lineToRelative(0.5f, -0.52f) arcToRelative(2.0f, 2.0f, 0.0f, false, true, 2.9f, 0.0f) lineToRelative(0.5f, 0.52f) arcToRelative(5.28f, 5.28f, 0.0f, false, false, 1.47f, -0.9f) lineToRelative(-0.2f, -0.7f) arcToRelative(2.0f, 2.0f, 0.0f, false, true, 1.45f, -2.5f) lineToRelative(0.58f, -0.14f) arcToRelative(5.72f, 5.72f, 0.0f, false, false, 0.0f, -1.8f) lineToRelative(-0.54f, -0.13f) arcToRelative(2.0f, 2.0f, 0.0f, false, true, -1.45f, -2.51f) lineToRelative(0.18f, -0.63f) curveToRelative(-0.44f, -0.39f, -0.94f, -0.7f, -1.48f, -0.93f) lineToRelative(-0.5f, 0.52f) arcToRelative(2.0f, 2.0f, 0.0f, false, true, -2.9f, 0.0f) lineToRelative(-0.5f, -0.52f) curveToRelative(-0.54f, 0.22f, -1.04f, 0.53f, -1.48f, 0.91f) lineToRelative(0.2f, 0.69f) close() moveTo(16.5f, 8.0f) curveToRelative(-0.8f, 0.0f, -1.45f, -0.67f, -1.45f, -1.5f) reflectiveCurveTo(15.7f, 5.0f, 16.5f, 5.0f) curveToRelative(0.8f, 0.0f, 1.45f, 0.67f, 1.45f, 1.5f) reflectiveCurveTo(17.3f, 8.0f, 16.5f, 8.0f) close() moveTo(10.0f, 6.5f) curveToRelative(0.0f, -0.17f, 0.0f, -0.33f, 0.02f, -0.5f) lineTo(3.75f, 6.0f) curveTo(2.78f, 6.0f, 2.0f, 6.78f, 2.0f, 7.75f) verticalLineToRelative(12.5f) curveTo(2.0f, 21.2f, 2.78f, 22.0f, 3.75f, 22.0f) horizontalLineToRelative(16.5f) curveToRelative(0.97f, 0.0f, 1.75f, -0.78f, 1.75f, -1.75f) lineTo(22.0f, 9.97f) curveToRelative(-0.4f, 0.64f, -0.91f, 1.2f, -1.5f, 1.66f) verticalLineToRelative(8.62f) curveToRelative(0.0f, 0.14f, -0.11f, 0.25f, -0.25f, 0.25f) horizontalLineToRelative(-7.5f) verticalLineToRelative(-8.7f) curveToRelative(-0.58f, -0.4f, -1.08f, -0.9f, -1.5f, -1.47f) lineTo(11.25f, 20.5f) horizontalLineToRelative(-7.5f) arcToRelative(0.25f, 0.25f, 0.0f, false, true, -0.25f, -0.25f) lineTo(3.5f, 7.75f) curveToRelative(0.0f, -0.14f, 0.11f, -0.25f, 0.25f, -0.25f) horizontalLineToRelative(6.33f) arcToRelative(6.54f, 6.54f, 0.0f, false, true, -0.08f, -1.0f) close() moveTo(17.0f, 18.25f) arcToRelative(0.75f, 0.75f, 0.0f, false, false, -0.76f, -0.75f) horizontalLineToRelative(-1.6f) arcToRelative(0.75f, 0.75f, 0.0f, false, false, 0.1f, 1.5f) horizontalLineToRelative(1.6f) arcToRelative(0.75f, 0.75f, 0.0f, false, false, 0.65f, -0.75f) close() moveTo(10.0f, 18.25f) arcToRelative(0.75f, 0.75f, 0.0f, false, false, -0.76f, -0.75f) horizontalLineToRelative(-1.6f) arcToRelative(0.75f, 0.75f, 0.0f, false, false, 0.1f, 1.5f) horizontalLineToRelative(1.6f) arcToRelative(0.75f, 0.75f, 0.0f, false, false, 0.65f, -0.75f) close() } } return _dualScreenSettings!! } private var _dualScreenSettings: ImageVector? = null
1
Kotlin
3
83
9e86d93bf1f9ca63a93a913c990e95f13d8ede5a
4,514
compose-fluent-ui
Apache License 2.0
app/src/main/java/io/github/drumber/kitsune/data/source/network/BasePagingDataSource.kt
Drumber
406,471,554
false
{"Kotlin": 993796, "Ruby": 2109}
package io.github.drumber.kitsune.data.source.network import androidx.paging.PagingSource import androidx.paging.PagingState import io.github.drumber.kitsune.constants.Kitsu import io.github.drumber.kitsune.data.common.exception.NoDataException import io.github.drumber.kitsune.util.logE abstract class BasePagingDataSource<Value : Any> : PagingSource<Int, Value>() { override suspend fun load(params: LoadParams<Int>): LoadResult<Int, Value> { return try { val pageOffset = params.key ?: Kitsu.DEFAULT_PAGE_OFFSET val pageData = requestPage(pageOffset) val data = pageData.data ?: throw NoDataException("Received data is 'null'.") LoadResult.Page( data = data, prevKey = pageData.prev, nextKey = pageData.next ) } catch (e: Exception) { logE("Error receiving data from API.", e) LoadResult.Error(e) } } abstract suspend fun requestPage(pageOffset: Int): PageData<Value> override fun getRefreshKey(state: PagingState<Int, Value>) = state.anchorPosition?.let { anchorPosition -> state.closestPageToPosition(anchorPosition)?.prevKey?.plus(1) ?: state.closestPageToPosition(anchorPosition)?.nextKey?.minus(1) } }
6
Kotlin
4
92
ba6f2a69cb71a9fd71d4825921ff6d9b6300471e
1,333
Kitsune
Apache License 2.0
app/src/main/java/me/codeenzyme/welearn/data/remote/FirebaseUserProfileService.kt
Victor-El
305,075,837
false
{"Gradle": 4, "Java Properties": 2, "Shell": 1, "Text": 1, "Ignore List": 3, "Batchfile": 1, "Markdown": 1, "YAML": 1, "JSON": 1, "Proguard": 2, "Kotlin": 47, "XML": 68, "Java": 1, "INI": 1}
package me.codeenzyme.welearn.data.remote import android.net.Uri import android.util.Log import com.google.firebase.auth.ktx.auth import com.google.firebase.auth.ktx.userProfileChangeRequest import com.google.firebase.firestore.ktx.firestore import com.google.firebase.firestore.ktx.toObject import com.google.firebase.ktx.Firebase import com.google.firebase.storage.ktx.storage import kotlinx.coroutines.tasks.await import me.codeenzyme.welearn.model.ProfileUpdateResponse import me.codeenzyme.welearn.model.User import me.codeenzyme.welearn.model.UserProfileResponse import me.codeenzyme.welearn.utils.USERS_COLLECTION import me.codeenzyme.welearn.utils.USERS_IMAGE_FOLDER import java.lang.Exception import java.util.* import javax.inject.Inject class FirebaseUserProfileService @Inject constructor( ): UserProfileService { val firebaseAuth = Firebase.auth val firestore = Firebase.firestore val storage = Firebase.storage override suspend fun updateUserProfile(photoUri: Uri?, user: User): ProfileUpdateResponse { return try { firebaseAuth.currentUser?.updateProfile( userProfileChangeRequest { if (photoUri != null) { val uploadRef = storage.reference.child("$USERS_IMAGE_FOLDER/${UUID.randomUUID()}") uploadRef.putFile(photoUri).await() this.photoUri = uploadRef.downloadUrl.await() } displayName = "${user.firstName} ${user.lastName}" } )?.await() if (user.email != firebaseAuth.currentUser?.email) { firebaseAuth.currentUser?.updateEmail(user.email)?.await() firebaseAuth.currentUser?.sendEmailVerification()?.await() } firestore.collection(USERS_COLLECTION).document(firebaseAuth.currentUser?.uid!!).set(user).await() ProfileUpdateResponse.Success } catch (e: Exception) { ProfileUpdateResponse.Failure } } override suspend fun getUserProfile(): UserProfileResponse { return try { val userProfile = firestore.collection(USERS_COLLECTION).document(firebaseAuth.currentUser?.uid!!) .get().await().toObject<User>()!! val userDisplayName = firebaseAuth.currentUser?.displayName!! val userPhotoUri = firebaseAuth.currentUser?.photoUrl UserProfileResponse.Success( userPhotoUri, userDisplayName, userProfile ) } catch (e: Exception) { Log.d("FirebaseUserService", e.localizedMessage!!) UserProfileResponse.Failure } } }
0
Kotlin
1
1
47e6e41b881c2654281ae128043293a435f8c2ae
2,730
WeLearn
MIT License
src/main/kotlin/com/yourssu/yls/domain/service/LoggingService.kt
yourssu
739,611,789
false
{"Kotlin": 5173, "Dockerfile": 128}
package com.yourssu.yls.domain.service import com.yourssu.yls.application.request.LoggingRequest import com.yourssu.yls.application.response.LoggingResponse import com.yourssu.yls.domain.model.document.LogDocument import com.yourssu.yls.domain.model.repository.LoggingRepository import org.springframework.stereotype.Service import org.springframework.transaction.annotation.Transactional @Service class LoggingService( private val loggingRepository: LoggingRepository, ) { @Transactional fun writeLog(request: LoggingRequest): LoggingResponse { val logDocument: LogDocument = LogAssembler.writeDocument(request) val savedLogDocument = loggingRepository.save(logDocument) return LogAssembler.writeDto(savedLogDocument) } }
0
Kotlin
0
0
e01a3ce83161ea0e9f5b3bf3e0af95e2aa4b062a
765
YLS-Backend
MIT License
funcify-feature-eng-schema/src/main/kotlin/funcify/feature/schema/vertex/ParameterContainerTypeVertex.kt
anticipasean
458,910,592
false
null
package funcify.feature.schema.vertex import funcify.feature.schema.SchematicVertex import funcify.feature.schema.index.CompositeParameterContainerType /** * * @author smccarron * @created 2022-06-18 */ interface ParameterContainerTypeVertex : SchematicVertex { val compositeParameterContainerType: CompositeParameterContainerType }
0
Kotlin
0
0
202a13324edc1d477c82b3de54a55a4cb72669ad
344
funcify-feature-eng
Apache License 2.0
app/src/main/java/erevacation/com/userlistanko/homescreen/list/ListFragmentPresenter.kt
highmobdevelopment
133,389,122
false
null
package erevacation.com.userlistanko.homescreen.list import android.support.v4.app.FragmentManager import erevacation.com.userlistanko.R import erevacation.com.userlistanko.basic.arhitecture.ViperContract import erevacation.com.userlistanko.datamodel.ListDM import erevacation.com.userlistanko.homescreen.HomeActivity import erevacation.com.userlistanko.homescreen.profile.ProfileFragment import erevacation.com.userlistanko.usecase.ListUC import erevacation.com.userlistanko.usecase.ListUCContract import javax.inject.Inject class ListFragmentPresenter @Inject constructor(val listUC: ListUC) : ListContract.ListPresenter, ListUCContract.ListUCOut { private var view: ListContract.ListView? = null private val listAdapter = ListRecyclerAdapter(this) private lateinit var fragmentManager: FragmentManager override fun viewAttach(view: ViperContract.View<*>) { this.view = view as ListContract.ListView this.listUC.setListUCOut(this) fragmentManager = ((view as ListFragment).context as HomeActivity).supportFragmentManager listUC.getList() buildLayout() } override fun publishListResults(list: MutableList<ListDM>) { listAdapter.updateList(list) } override fun viewDetach() { listUC.clearRequests() this.view = null } override fun onDestroyed() { this.view = null } override fun onContactClick(name: String, surname: String, image: String, profileInfoList: ArrayList<String>) { val fragmentProfile = ProfileFragment.newInstance(name, surname, image, profileInfoList) fragmentManager.beginTransaction() .setCustomAnimations(R.animator.right_in, R.animator.fui_slide_out_left, R.animator.fui_slide_in_right, R.animator.right_out) .add(R.id.container, fragmentProfile) .addToBackStack("contacts_back_stack") .commit() } private fun buildLayout() { (view as ListFragment).ankoFragmentListUI.recyclerViewList.adapter = listAdapter } }
0
Kotlin
0
0
bbd48c924f601865988a4a82d3d1f328e866ff80
2,063
userlist_anko
Apache License 2.0
src/main/kotlin/shou/retryconfig/RetryListener.kt
NSVN-NguyenDuyThang
661,492,559
false
null
package shou.retryconfig import org.testng.IAnnotationTransformer import org.testng.annotations.ITestAnnotation import java.lang.reflect.Constructor import java.lang.reflect.Method class RetryListener : IAnnotationTransformer { override fun transform( annotation: ITestAnnotation, testClass: Class<*>?, testConstructor: Constructor<*>?, testMethod: Method? ) { annotation.setRetryAnalyzer(RetryTestFailed::class.java) } }
0
Kotlin
0
0
b375d9d2ebb4981209025e6052a3080324042e33
476
playwright-kotlin
MIT License
tezos-rpc/src/main/kotlin/it/airgap/tezos/rpc/shell/monitor/Monitor.kt
airgap-it
460,351,851
false
null
package it.airgap.tezos.rpc.shell.monitor import it.airgap.tezos.core.type.encoded.ChainId import it.airgap.tezos.core.type.encoded.ProtocolHash import it.airgap.tezos.rpc.http.HttpHeader import it.airgap.tezos.rpc.internal.utils.Constants /** * [Shell RPCs](https://tezos.gitlab.io/shell/rpc.html): `/monitor` */ public interface Monitor { public val activeChains: ActiveChains public val bootstrapped: Bootstrapped public val heads: Heads public val protocols: Protocols public val validBlocks: ValidBlocks /** * [Shell RPCs](https://tezos.gitlab.io/shell/rpc.html): `/monitor/active_chains` */ public interface ActiveChains { public suspend fun get( headers: List<HttpHeader> = emptyList(), requestTimeout: Long? = null, connectionTimeout: Long? = null, ): MonitorActiveChainsResponse } /** * [Shell RPCs](https://tezos.gitlab.io/shell/rpc.html): `/monitor/bootstrapped` */ public interface Bootstrapped { public suspend fun get( headers: List<HttpHeader> = emptyList(), requestTimeout: Long? = null, connectionTimeout: Long? = null, ): MonitorBootstrappedResponse } /** * [Shell RPCs](https://tezos.gitlab.io/shell/rpc.html): `/monitor/heads` */ public interface Heads { public val main: Head get() = invoke(Constants.Chain.MAIN) public val test: Head get() = invoke(Constants.Chain.TEST) public operator fun invoke(chainId: String): Head public operator fun invoke(chainId: ChainId): Head = invoke(chainId.base58) public interface Head { public suspend fun get( nextProtocol: ProtocolHash? = null, headers: List<HttpHeader> = emptyList(), requestTimeout: Long? = null, connectionTimeout: Long? = null, ): MonitorHeadResponse } } /** * [Shell RPCs](https://tezos.gitlab.io/shell/rpc.html): `/monitor/protocols` */ public interface Protocols { public suspend fun get( headers: List<HttpHeader> = emptyList(), requestTimeout: Long? = null, connectionTimeout: Long? = null, ): MonitorProtocolsResponse } /** * [Shell RPCs](https://tezos.gitlab.io/shell/rpc.html): `/monitor/valid_blocks` */ public interface ValidBlocks { public suspend fun get( protocol: ProtocolHash? = null, nextProtocol: ProtocolHash? = null, chain: String? = null, headers: List<HttpHeader> = emptyList(), requestTimeout: Long? = null, connectionTimeout: Long? = null, ): MonitorValidBlocksResponse public suspend fun get( protocol: ProtocolHash? = null, nextProtocol: ProtocolHash? = null, chain: ChainId, headers: List<HttpHeader> = emptyList(), requestTimeout: Long? = null, connectionTimeout: Long? = null, ): MonitorValidBlocksResponse = get(protocol, nextProtocol, chain.base58, headers) } }
0
Kotlin
2
1
c5af5ffdd4940670bd66842580d82c2b9d682d84
3,216
tezos-kotlin-sdk
MIT License
app/src/main/java/com/hientran/wallpaper/presentation/ui/photocollection/PhotoCollectionViewModel.kt
hientranea
553,982,644
false
null
package com.hientran.wallpaper.presentation.ui.photocollection import androidx.lifecycle.viewModelScope import androidx.paging.cachedIn import com.hientran.wallpaper.domain.usecase.GetCollectionMediaUseCase import com.hientran.wallpaper.domain.usecase.GetCollectionMediaUseCase.Params import com.hientran.wallpaper.presentation.base.BaseViewModel import dagger.hilt.android.lifecycle.HiltViewModel import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.StateFlow import kotlinx.coroutines.flow.collectLatest import kotlinx.coroutines.flow.update import javax.inject.Inject @HiltViewModel class PhotoCollectionViewModel @Inject constructor( private val getCollectionMediaUseCase: GetCollectionMediaUseCase ): BaseViewModel() { private val _state = MutableStateFlow(PhotoCollectionViewState()) val state: StateFlow<PhotoCollectionViewState> = _state fun getCollectionMedia(id: String) { callApi { getCollectionMediaUseCase(Params(id)) .cachedIn(viewModelScope) .collectLatest { photos -> _state.update { it.copy(photos = photos) } } } } }
0
Kotlin
0
1
d2f1e69400c29f111357073a3c128b3ad31be7d5
1,180
Wallpaper
Apache License 2.0
src/main/kotlin/de/flapdoodle/sqlextract/db/ForeignKey.kt
flapdoodle-oss
363,965,979
false
null
package de.flapdoodle.sqlextract.db import de.flapdoodle.sqlextract.types.Comparators data class ForeignKey( override val sourceTable: Name, override val sourceColumn: String, override val destinationTable: Name, override var destinationColumn: String ): ColumnConnection { companion object { val Comparator = Comparators.orderingFor(Name.Comparator,ForeignKey::sourceTable) .then(Comparators.orderingFor(ForeignKey::sourceColumn)) .then(Comparators.orderingFor(Name.Comparator, ForeignKey::destinationTable)) .then(Comparators.orderingFor(ForeignKey::destinationColumn)) } }
0
Kotlin
0
0
69aa6dd554dc011d3bbc75fabcddfad173b41a79
647
de.flapdoodle.sqlextract
Apache License 2.0
src/builder/implementation/CarBuilderImpl.kt
imshyam
187,470,617
false
null
package builder.implementation class CarBuilderImpl : CarBuilder { private var tmpCar = Car() override fun build() = Car(tmpCar.wheels, tmpCar.color) override fun setColor(color: String): CarBuilder { tmpCar.color = color return this } override fun setWheels(wheels: Int): CarBuilder { tmpCar.wheels = wheels return this } }
0
Kotlin
0
0
6375a5e9a1dac9cffba89b99f0df91d4ca1fae00
386
design-patterns-kotlin
MIT License
app/src/main/java/com/gmart/gmovies/ui/screen/details/DetailsViewModel.kt
gimartinez17
771,233,885
false
{"Kotlin": 515365, "CMake": 1625, "C++": 259}
package com.gmart.gmovies.ui.screen.details import androidx.lifecycle.SavedStateHandle import androidx.lifecycle.viewModelScope import com.gmart.data.source.utils.IoDispatcher import com.gmart.domain.model.MediaType import com.gmart.domain.model.MediaType.Companion.fromString import com.gmart.domain.model.Resource import com.gmart.domain.usecase.ConfigUseCase import com.gmart.domain.usecase.DetailUseCase import com.gmart.domain.usecase.ListingsUseCase import com.gmart.domain.usecase.UserUseCase import com.gmart.gmovies.navigation.NavArgs.MEDIA_ID import com.gmart.gmovies.navigation.NavArgs.MEDIA_TYPE import com.gmart.gmovies.ui.base.BaseViewModel import com.gmart.gmovies.utils.Quadruple import com.gmart.gmovies.utils.combine import com.gmart.gmovies.utils.logE import com.gmart.gmovies.utils.toDate import dagger.hilt.android.lifecycle.HiltViewModel import kotlinx.coroutines.CoroutineDispatcher import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.async import kotlinx.coroutines.flow.catch import kotlinx.coroutines.flow.first import kotlinx.coroutines.flow.onStart import kotlinx.coroutines.launch import javax.inject.Inject @HiltViewModel class DetailsViewModel @Inject constructor( private val userUseCase: UserUseCase, private val detailUseCase: DetailUseCase, private val configUseCase: ConfigUseCase, private val listingsUseCase: ListingsUseCase, savedStateHandle: SavedStateHandle, @IoDispatcher private val dispatcher: CoroutineDispatcher, ) : BaseViewModel<DetailsViewState, DetailsEvent, DetailsEffect>(dispatcher) { private val id: Int = checkNotNull(savedStateHandle[MEDIA_ID]) private val mediaType: MediaType = checkNotNull(fromString(savedStateHandle[MEDIA_TYPE])) init { getDetails() } override fun setInitialState() = DetailsViewState() override fun handleEvents(event: DetailsEvent) { when (event) { DetailsEvent.GetDetails -> getDetails() is DetailsEvent.OnFavouriteClick -> postFavourite(event.isFavourite) is DetailsEvent.OnCastItemClick -> setEffect(DetailsEffect.NavigateToCast(event.id)) is DetailsEvent.OnMediaClick -> setEffect(DetailsEffect.NavigateToDetails(event.id, event.mediaType)) DetailsEvent.OnViewAllCastClick -> setEffect(DetailsEffect.NavigateToAllCast(id, mediaType)) is DetailsEvent.OnVideoClick -> setEffect(DetailsEffect.NavigateToVideoPlayerScreen(event.videoKey)) is DetailsEvent.OnAddToListClick -> addItemToList(event.listId, id, mediaType) } } private fun getDetails() { viewModelScope.launch(dispatcher) { val accessToken = userUseCase.getAccessToken().first() val countryCode = configUseCase.getCountry().first() val detailsDeferred = async(Dispatchers.IO) { detailUseCase.getDetails(mediaType, id) } val accountStatesDeferred = async(Dispatchers.IO) { detailUseCase.getAccountStates(mediaType, id) } val providersDeferred = async(Dispatchers.IO) { detailUseCase.getProviders(mediaType, id, countryCode) } val userListsDeferred = async(Dispatchers.IO) { listingsUseCase.getMyLists(userUseCase.getAccountId().first()) } combine( detailsDeferred.await(), accountStatesDeferred.await(), providersDeferred.await(), userListsDeferred.await(), ::Quadruple ).onStart { setViewState(DetailsViewState(isLoading = true)) }.catch { throwable -> logE(throwable.message.toString()) setViewState(DetailsViewState(errorMessage = "Something went wrong")) }.collect { resources -> val movieResource = resources.first val accountStatesResource = resources.second val providersResource = resources.third val userListsResource = resources.fourth var movieState = DetailsViewState() when (movieResource) { is Resource.Success -> movieState = movieState.copy(details = movieResource.response) is Resource.Failure -> { logE(movieResource.error?.message.toString()) setViewState(DetailsViewState(errorMessage = "Something went wrong")) return@collect } } when (accountStatesResource) { is Resource.Success -> if (accessToken.isNotEmpty()) movieState = movieState.copy(accountState = accountStatesResource.response) is Resource.Failure -> logE(accountStatesResource.error?.message.toString()) } when (providersResource) { is Resource.Success -> movieState = movieState.copy(watchProviders = providersResource.response) is Resource.Failure -> logE(providersResource.error?.message.toString()) } when (userListsResource) { is Resource.Success -> if (accessToken.isNotEmpty()) { val list = userListsResource.response.sortedBy { it.createdAt?.toDate() } movieState = movieState.copy(userList = list) } is Resource.Failure -> logE(userListsResource.error?.message.toString()) } setViewState(movieState) } } } private fun postFavourite(isFavourite: Boolean) { viewModelScope.launch(dispatcher) { val accountId = userUseCase.getAccountId().first() listingsUseCase.postFavourite(id, mediaType, isFavourite, accountId).onStart { updateViewState { copy(isLoading = true) } }.catch { throwable -> updateViewState { copy(isLoading = false) } logE(throwable.message.toString()) }.collect { resources -> when (resources) { is Resource.Success -> getAccountState(id, mediaType) is Resource.Failure -> { logE(resources.error?.message.toString()) updateViewState { copy(isLoading = false) } } } } } } private fun getAccountState(id: Int, mediaType: MediaType) { viewModelScope.launch(dispatcher) { detailUseCase.getAccountStates(mediaType, id).catch { throwable -> logE(throwable.message.toString()) updateViewState { copy(isLoading = false) } }.collect { resources -> when (resources) { is Resource.Success -> updateViewState { copy(isLoading = false, accountState = resources.response) } is Resource.Failure -> { logE(resources.error?.message.toString()) updateViewState { copy(isLoading = false) } } } } } } private fun addItemToList(listId: Int, mediaId: Int, mediaType: MediaType) { viewModelScope.launch(dispatcher) { listingsUseCase.addItems(listId, mediaId, mediaType).onStart { updateViewState { copy(isLoading = true) } }.catch { throwable -> updateViewState { copy(isLoading = false) } logE(throwable.message.toString()) }.collect { resources -> when (resources) { is Resource.Success -> updateViewState { copy(isLoading = false, snackBarMessage = "Item added successfully!") } is Resource.Failure -> { logE(resources.error?.message.toString()) updateViewState { copy(isLoading = false) } } } } } } }
0
Kotlin
1
1
da0854981d865fb7207767ae3e6a4c8ce1f441a8
8,341
movies-app
MIT License
core/src/commonTest/kotlin/kotlinx/fs/core/CopyTest.kt
qwwdfsad
133,036,116
false
null
package kotlinx.fs.core import kotlinx.io.errors.* import kotlin.test.* class CopyTest : TestBase() { @Test fun testCopyFile() { val expectedContent = ByteArray(5) { it.toByte() } val file = testFile("copy-file").createFile() file.writeBytes(expectedContent) val target = testFile("target-file") file.copyTo(target) assertTrue(expectedContent.contentEquals(target.readAllBytes())) assertTrue(expectedContent.contentEquals(file.readAllBytes())) assertTrue(file.exists()) } @Test fun testCopyDirectory() { val directory = testDirectory("copy-directory").createDirectory() val target = testDirectory("target-directory") assertFalse(target.exists()) directory.copyTo(target) assertTrue(directory.exists()) assertTrue(target.exists()) } @Test fun testCopyDirectoryWithContent() { val expectedContent = ByteArray(42) { it.toByte() } val directory = testDirectory("copy-directory-with-content").createDirectory() val file = Path(directory, "content.txt").createFile() file.writeBytes(expectedContent) val target = testDirectory("target-directory") val targetFile = Paths.getPath(target, "content.txt") assertFalse(target.exists()) assertFalse(targetFile.exists()) directory.copyTo(target) // Content is not copied, but directory is assertTrue(target.exists()) assertFalse(targetFile.exists()) } @Test fun testCopyNothing() { val file = testFile("nothing") val target = testFile("nothing-target") assertFailsWith<IOException> { file.copyTo(target) } } @Test fun testCopyToExistingFile() { val file = testFile("file").createFile() val target = testFile("existing-file").createFile() assertFailsWith<IOException> { file.copyTo(target) } } }
0
null
2
27
6720bce0bb9d17744a3c09171e3655e5d771de80
1,964
kotlinx-fs
Apache License 2.0
app/src/main/kotlin/com/czbix/v2ex/db/Comment.kt
CzBiX
36,221,300
false
null
package com.czbix.v2ex.db import androidx.room.ColumnInfo import androidx.room.Entity import androidx.room.PrimaryKey import com.czbix.v2ex.model.Ignorable import com.czbix.v2ex.model.Thankable import com.czbix.v2ex.network.RequestHelper @Entity data class Comment( @PrimaryKey val id: Int, @ColumnInfo(index = true) val topicId: Int, val page: Int, val content: String, val username: String, val addAt: String, val thanks: Int, val floor: Int, val thanked: Boolean ) : Thankable, Ignorable { override fun getIgnoreUrl(): String { return String.format("%s/ignore/reply/%d", RequestHelper.BASE_URL, id) } override fun getThankUrl(): String { return String.format("%s/thank/reply/%d", RequestHelper.BASE_URL, id) } override fun equals(other: Any?): Boolean { if (this === other) return true if (javaClass != other?.javaClass) return false other as Comment if (id != other.id) return false if (topicId != other.topicId) return false if (page != other.page) return false if (content != other.content) return false if (username != other.username) return false if (addAt != other.addAt) return false if (thanks != other.thanks) return false if (floor != other.floor) return false if (thanked != other.thanked) return false return true } override fun hashCode(): Int { var result = id result = 31 * result + topicId result = 31 * result + page result = 31 * result + content.hashCode() result = 31 * result + username.hashCode() result = 31 * result + addAt.hashCode() result = 31 * result + thanks result = 31 * result + floor result = 31 * result + thanked.hashCode() return result } class Builder { var topicId: Int = 0 var id: Int = 0 var page: Int = 0 lateinit var content: String lateinit var username: String lateinit var addAt: String var thanks: Int = 0 var floor: Int = 0 var thanked: Boolean = false fun build(): Comment { check(topicId > 0) check(id > 0) check(floor > 0) check(page > 0) return Comment(id, topicId, page, content, username, addAt, thanks, floor, thanked) } } }
2
Kotlin
25
138
f6a79a91b84ae8030930231d965845798c4ce0a8
2,471
v2ex-android
Apache License 2.0
kt/src/main/kotlin/Bot.kt
RainPlus-Team
676,775,641
false
null
import net.mamoe.mirai.event.Event class Bot { init { System.loadLibrary("bot") } external fun initialize() external fun eventListener(className: String, ptr: Long, bot: net.mamoe.mirai.Bot, event: Event) }
0
Rust
0
0
91c4035da5dc57cff4f20105d8cdd31967f61a33
232
mirai-jni-rs
MIT License
src/main/kotlin/com/github/attacktive/troubleshootereditor/model/Item.kt
Attacktive
517,579,517
false
null
package com.github.attacktive.troubleshootereditor.model import com.fasterxml.jackson.module.kotlin.jacksonObjectMapper import com.fasterxml.jackson.module.kotlin.readValue data class Item(val id: Long, val type: String, val count: Long, val status: String) { constructor(id: Long, type: String, count: Long, status: String, json: String): this(id, type, count, status) { properties = deserialize(json) } var properties = mapOf<String, String>() companion object { private fun deserialize(json: String): Map<String, String> { val objectMapper = jacksonObjectMapper() return objectMapper.readValue(json) } } }
0
Kotlin
0
1
d389067303157aab674adaab5363d71146d05f29
630
troubleshooter-editor-back-end
MIT License
app/src/main/java/jermaine/technews/ui/articles/ArticleViewHolder.kt
jermainedilao
124,178,104
false
null
package jermaine.technews.ui.articles import android.view.View import androidx.databinding.ViewDataBinding import androidx.recyclerview.widget.RecyclerView import jermaine.technews.BR // https://medium.com/google-developers/android-data-binding-recyclerview-db7c40d9f0e4 class ArticleViewHolder(private val binding: ViewDataBinding) : RecyclerView.ViewHolder(binding.root) { fun bind( item: Any, onArticleClick: View.OnClickListener, onBookmarkClick: View.OnClickListener, onSourceClick: View.OnClickListener ) { binding.setVariable(BR.item, item) binding.setVariable(BR.articleClick, onArticleClick) binding.setVariable(BR.bookmarkClick, onBookmarkClick) binding.setVariable(BR.sourceClick, onSourceClick) binding.executePendingBindings() } }
0
Kotlin
0
2
2bb2efc6067db95a5fce7ae16cbbcbda58c08b60
833
technews
Apache License 2.0
app/src/main/kotlin/org/mifos/mobile/cn/data/models/accounts/loan/CreditWorthinessFactor.kt
openMF
133,982,000
false
null
package org.mifos.mobile.cn.data.models.accounts.loan import android.os.Parcelable import com.google.gson.annotations.SerializedName import kotlinx.android.parcel.Parcelize @Parcelize data class CreditWorthinessFactor( @SerializedName("description") var description: String? = null, @SerializedName("amount") var amount: Double? = null ) : Parcelable
65
null
64
38
24a93032be5eb3ac55d79fe08b0409ba47f482e7
368
mifos-mobile-cn
Apache License 2.0
core-kotlin-modules/core-kotlin-concurrency/src/main/kotlin/com/baeldung/cancellationofcoroutines/CancellingCoroutines.kt
tauqeermajeed0081
419,066,422
true
{"Kotlin": 556097, "Java": 12505, "HTML": 1100}
package com.baeldung.cancellationofcoroutines import kotlinx.coroutines.* fun main() { //callCancel() //cancelWithTimeOut() //cooperativeCoroutines() //cancelJobs() } fun callCancel() = runBlocking { val job = launch { repeat(1000) { index -> println("$index. Printing numbers...") delay(500L) } } delay(1300L) // adding delay println("main: Waiting!!!") job.cancel() // cancels the job job.join() // waits for job’s completion println("main: Now I can quit.") } fun cancelJobs() = runBlocking { val parentJob = launch { val childJob = launch { var count = 1 val startTime = System.currentTimeMillis() var nextPrintTime = startTime while (count <= 5) { if (System.currentTimeMillis() >= nextPrintTime) { println("Count: $count") nextPrintTime += 100L count++ } } } } delay(250) println("Cancelling parent job") parentJob.cancel() parentJob.join() println("Parent job completed") } fun cancelWithTimeOut() = runBlocking { withTimeout(1300L) { repeat(1000) { i -> println("I'm sleeping $i ...") delay(500L) } } } fun cooperativeCoroutines() = runBlocking { val startTime = System.currentTimeMillis() val job = launch(Dispatchers.Default) { var nextPrintTime = startTime var i = 0 while (i < 5) { // computation loop, just wastes CPU // print a message twice a second if (System.currentTimeMillis() >= nextPrintTime) { println("job: I'm sleeping ${i++} ...") nextPrintTime += 500L } } } delay(1300L) println("main: I'm tired of waiting!") job.cancelAndJoin() // cancels the job and waits for its completion println("main: Now I can quit.") }
0
Kotlin
0
0
eff0e95af7f7458b804ae81ca4def1d1455220ed
2,003
kotlin-tutorials
MIT License
SDKAndroid/src/main/kotlin/app/cybrid/sdkandroid/components/accounts/compose/AccountsView_List_Empty.kt
Cybrid-app
498,874,863
false
{"Kotlin": 791821}
package app.cybrid.sdkandroid.components.accounts.compose import androidx.compose.foundation.layout.* import androidx.compose.material.Text import androidx.compose.runtime.* import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.res.colorResource import androidx.compose.ui.res.stringResource import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.sp import app.cybrid.sdkandroid.R import app.cybrid.sdkandroid.ui.Theme.robotoFont @Composable fun AccountsView_List_Empty() { Box( modifier = Modifier .height(120.dp) ) { Column( modifier = Modifier.fillMaxSize(), verticalArrangement = Arrangement.Center, horizontalAlignment = Alignment.CenterHorizontally ) { Text( text = stringResource(id = R.string.accounts_view_no_accounts_title), fontFamily = robotoFont, fontWeight = FontWeight.Normal, fontSize = 17.sp, color = colorResource(id = R.color.primary_color) ) } } }
15
Kotlin
2
6
c3fe39dd3ecbe0d90002ea227ed575f1dc2cabf7
1,172
cybrid-sdk-android
Apache License 2.0
poi_auth/src/test/kotlin/com/github/mrmeowcat/poi_auth/RegistrationServiceTests.kt
MrMeowCat
141,818,640
false
null
package com.github.mrmeowcat.poi_auth import com.github.mrmeowcat.poi_auth.document.AccountDocument import com.github.mrmeowcat.poi_auth.dto.Credentials import com.github.mrmeowcat.poi_auth.dto.RegistrationResponse import com.github.mrmeowcat.poi_auth.exception.RegistrationException import com.github.mrmeowcat.poi_auth.repository.AccountRepository import com.github.mrmeowcat.poi_auth.repository.versioning.AccountVersioningRepository import com.github.mrmeowcat.poi_auth.service.AccountService import com.github.mrmeowcat.poi_auth.service.RegistrationService import com.github.mrmeowcat.poi_auth.service.RegistrationService.ErrorCodes import com.github.mrmeowcat.poi_core.dto.dto import org.junit.Assert import org.junit.Assert.assertEquals import org.junit.Assert.assertNotNull import org.junit.Assert.assertTrue import org.junit.FixMethodOrder import org.junit.Test import org.junit.runner.RunWith import org.junit.runners.MethodSorters import org.springframework.beans.factory.annotation.Autowired import org.springframework.boot.test.autoconfigure.data.mongo.DataMongoTest import org.springframework.context.annotation.ComponentScan import org.springframework.data.mongodb.config.EnableMongoAuditing import org.springframework.data.mongodb.core.MongoTemplate import org.springframework.data.mongodb.core.query.Query import org.springframework.security.crypto.password.PasswordEncoder import org.springframework.test.context.junit4.SpringRunner @RunWith(SpringRunner::class) @DataMongoTest @ComponentScan("com.github.mrmeowcat.poi_auth") @EnableMongoAuditing @FixMethodOrder(MethodSorters.NAME_ASCENDING) class RegistrationServiceTests { @Autowired lateinit var registrationService: RegistrationService @Autowired lateinit var passwordEncoder: PasswordEncoder @Autowired lateinit var accountService: AccountService @Autowired lateinit var accountRepository: AccountRepository @Autowired lateinit var accountVersioningRepository: AccountVersioningRepository @Autowired lateinit var mongoTemplate: MongoTemplate var testUsername: String = "test" var testEmail: String = "<EMAIL>" var testPassword: String = "<PASSWORD>" @Test fun test01_setup() { accountService.deleteAll() Assert.assertEquals(0, accountService.findAll().size) mongoTemplate.remove(Query(), "accounts_versions") accountService.save(dto { username = testUsername email = testEmail password = <PASSWORD>(<PASSWORD>) }) } @Test(expected = RegistrationException::class) fun test02_registerEmpty() { val credentials: Credentials? = null registrationService.register(credentials) } @Test fun test03_registerEmptyFields() { var credentials: Credentials = dto { } try { registrationService.register(credentials) } catch (e: RegistrationException) { assertEquals(4, e.response.errors.size) } credentials = dto { username = "1219dj1" email = " " password = "<PASSWORD>" confirm = "<PASSWORD>" } try { registrationService.register(credentials) } catch (e: RegistrationException) { assertEquals(1, e.response.errors.size) assertEquals(ErrorCodes.EMAIL_EMPTY, e.response.errors[0]) } } @Test fun test04_registerIncorrectUsername() { val credentials: Credentials = dto { username = "null" email = "asdf" password = "<PASSWORD>" confirm = "<PASSWORD>" } try { registrationService.register(credentials) } catch (e: RegistrationException) { assertTrue(e.response.errors.contains(ErrorCodes.USERNAME_INCORRECT)) } credentials.username = "00000000000000000000000000000000000000000000000000000000000000" try { registrationService.register(credentials) } catch (e: RegistrationException) { assertTrue(e.response.errors.contains(ErrorCodes.USERNAME_INCORRECT)) } } @Test fun test05_registerIncorrectEmail() { val credentials: Credentials = dto { username = testUsername email = "222" password = <PASSWORD> confirm = <PASSWORD> } try { registrationService.register(credentials) } catch (e: RegistrationException) { assertTrue(e.response.errors.contains(ErrorCodes.EMAIL_INCORRECT)) } credentials.email = "abcd@fegh." try { registrationService.register(credentials) } catch (e: RegistrationException) { assertTrue(e.response.errors.contains(ErrorCodes.EMAIL_INCORRECT)) } } @Test fun test06_registerIncorrectPassword() { val credentials: Credentials = dto { username = testUsername email = testEmail password = "0" confirm = "1" } try { registrationService.register(credentials) } catch (e: RegistrationException) { assertTrue(e.response.errors.contains(ErrorCodes.PASSWORD_MISMATCH)) } credentials.password = "<PASSWORD>" try { registrationService.register(credentials) } catch (e: RegistrationException) { assertTrue(e.response.errors.contains(ErrorCodes.PASSWORD_INCORRECT)) } } @Test fun test07_registerExists() { val credentials: Credentials = dto { username = testUsername email = testEmail password = <PASSWORD> confirm = <PASSWORD> } try { registrationService.register(credentials) } catch (e: RegistrationException) { assertTrue(e.response.errors.contains(ErrorCodes.USERNAME_EXISTS)) assertTrue(e.response.errors.contains(ErrorCodes.EMAIL_EXISTS)) } } @Test fun test08_registerSuccess() { val credentials: Credentials = dto { username = "${testUsername}1" email = "${testEmail}1" password = <PASSWORD> confirm = <PASSWORD> } val response: RegistrationResponse = registrationService.register(credentials) assertTrue(response.success) val account: AccountDocument = accountRepository.findByUsername(credentials.username).get() assertNotNull(account) val version: AccountDocument = accountVersioningRepository.getVersion(account, 0) assertNotNull(version) } }
0
Kotlin
0
0
998a413a8ddc3c0da494c8a50118255b0cf2e004
6,713
poi-services
MIT License
src/apiTest/kotlin/dev3/blockchainapiservice/controller/ImportContractControllerApiTest.kt
0xDev3
539,904,697
false
null
package dev3.blockchainapiservice.controller import dev3.blockchainapiservice.ControllerTestBase import dev3.blockchainapiservice.TestData import dev3.blockchainapiservice.blockchain.DummyProxy import dev3.blockchainapiservice.blockchain.ExampleContract import dev3.blockchainapiservice.config.CustomHeaders import dev3.blockchainapiservice.exception.ErrorCode import dev3.blockchainapiservice.features.api.access.model.result.Project import dev3.blockchainapiservice.features.contract.deployment.model.json.ArtifactJson import dev3.blockchainapiservice.features.contract.deployment.model.json.FunctionDecorator import dev3.blockchainapiservice.features.contract.deployment.model.json.InterfaceManifestJson import dev3.blockchainapiservice.features.contract.deployment.model.json.ManifestJson import dev3.blockchainapiservice.features.contract.deployment.model.json.ReturnTypeDecorator import dev3.blockchainapiservice.features.contract.deployment.model.json.TypeDecorator import dev3.blockchainapiservice.features.contract.deployment.model.response.ContractDecoratorResponse import dev3.blockchainapiservice.features.contract.deployment.model.response.ContractDeploymentRequestResponse import dev3.blockchainapiservice.features.contract.deployment.model.result.ContractConstructor import dev3.blockchainapiservice.features.contract.deployment.model.result.ContractDecorator import dev3.blockchainapiservice.features.contract.deployment.model.result.ContractDeploymentRequest import dev3.blockchainapiservice.features.contract.deployment.model.result.ContractEvent import dev3.blockchainapiservice.features.contract.deployment.model.result.ContractFunction import dev3.blockchainapiservice.features.contract.deployment.model.result.ContractParameter import dev3.blockchainapiservice.features.contract.deployment.model.result.EventParameter import dev3.blockchainapiservice.features.contract.deployment.repository.ContractDecoratorRepository import dev3.blockchainapiservice.features.contract.deployment.repository.ContractDeploymentRequestRepository import dev3.blockchainapiservice.features.contract.deployment.repository.ContractMetadataRepository import dev3.blockchainapiservice.features.contract.deployment.repository.ImportedContractDecoratorRepository import dev3.blockchainapiservice.features.contract.importing.model.response.ImportPreviewResponse import dev3.blockchainapiservice.features.contract.importing.service.ContractImportServiceImpl.Companion.TypeAndValue import dev3.blockchainapiservice.features.contract.interfaces.model.response.ContractInterfaceManifestResponse import dev3.blockchainapiservice.features.contract.interfaces.model.response.SuggestedContractInterfaceManifestsResponse import dev3.blockchainapiservice.features.contract.interfaces.repository.ContractInterfacesRepository import dev3.blockchainapiservice.generated.jooq.enums.UserIdentifierType import dev3.blockchainapiservice.generated.jooq.id.ApiKeyId import dev3.blockchainapiservice.generated.jooq.id.ContractMetadataId import dev3.blockchainapiservice.generated.jooq.id.ProjectId import dev3.blockchainapiservice.generated.jooq.id.UserId import dev3.blockchainapiservice.generated.jooq.tables.records.ApiKeyRecord import dev3.blockchainapiservice.generated.jooq.tables.records.ContractMetadataRecord import dev3.blockchainapiservice.generated.jooq.tables.records.ProjectRecord import dev3.blockchainapiservice.generated.jooq.tables.records.UserIdentifierRecord import dev3.blockchainapiservice.model.ScreenConfig import dev3.blockchainapiservice.model.response.EventArgumentResponse import dev3.blockchainapiservice.model.response.EventArgumentResponseType import dev3.blockchainapiservice.model.response.EventInfoResponse import dev3.blockchainapiservice.model.response.TransactionResponse import dev3.blockchainapiservice.testcontainers.HardhatTestContainer import dev3.blockchainapiservice.testcontainers.SharedTestContainers import dev3.blockchainapiservice.util.Balance import dev3.blockchainapiservice.util.BaseUrl import dev3.blockchainapiservice.util.Constants import dev3.blockchainapiservice.util.ContractAddress import dev3.blockchainapiservice.util.ContractBinaryData import dev3.blockchainapiservice.util.ContractId import dev3.blockchainapiservice.util.ContractTag import dev3.blockchainapiservice.util.InterfaceId import dev3.blockchainapiservice.util.Status import dev3.blockchainapiservice.util.TransactionHash import dev3.blockchainapiservice.util.WalletAddress import dev3.blockchainapiservice.util.ZeroAddress import org.jooq.DSLContext import org.junit.jupiter.api.BeforeEach import org.junit.jupiter.api.Test import org.springframework.beans.factory.annotation.Autowired import org.springframework.http.MediaType import org.springframework.test.web.servlet.request.MockMvcRequestBuilders import org.springframework.test.web.servlet.result.MockMvcResultMatchers import org.web3j.tx.gas.DefaultGasProvider import java.math.BigInteger import java.util.UUID class ImportContractControllerApiTest : ControllerTestBase() { companion object { private val PROJECT_ID = ProjectId(UUID.randomUUID()) private val OWNER_ID = UserId(UUID.randomUUID()) private val PROJECT = Project( id = PROJECT_ID, ownerId = OWNER_ID, issuerContractAddress = ContractAddress("0"), baseRedirectUrl = BaseUrl("https://example.com/"), chainId = TestData.CHAIN_ID, customRpcUrl = null, createdAt = TestData.TIMESTAMP ) private const val API_KEY = "api-key" private val CONTRACT_DECORATOR = ContractDecorator( id = ContractId("examples.exampleContract"), name = "name", description = "description", binary = ContractBinaryData(ExampleContract.BINARY), tags = listOf(ContractTag("example"), ContractTag("simple")), implements = listOf(InterfaceId("traits.example"), InterfaceId("traits.exampleOwnable")), constructors = listOf( ContractConstructor( inputs = listOf( ContractParameter( name = "Owner address", description = "Contract owner address", solidityName = "owner", solidityType = "address", recommendedTypes = listOf(), parameters = null, hints = null ) ), description = "Main constructor", payable = true ) ), functions = listOf( ContractFunction( name = "Get contract owner", description = "Fetches contract owner", solidityName = "getOwner", signature = "getOwner()", inputs = listOf(), outputs = listOf( ContractParameter( name = "Owner address", description = "Contract owner address", solidityName = "", solidityType = "address", recommendedTypes = listOf(), parameters = null, hints = null ) ), emittableEvents = emptyList(), readOnly = true ) ), listOf( ContractEvent( name = "Example event", description = "Example event", solidityName = "ExampleEvent", signature = "ExampleEvent(tuple(address),tuple(address))", inputs = listOf( EventParameter( name = "Non-indexed struct", description = "Non-indexed struct", indexed = false, solidityName = "nonIndexedStruct", solidityType = "tuple", recommendedTypes = emptyList(), parameters = listOf( ContractParameter( name = "Owner address", description = "Contract owner address", solidityName = "owner", solidityType = "address", recommendedTypes = emptyList(), parameters = null, hints = null ) ), hints = null ), EventParameter( name = "Indexed struct", description = "Indexed struct", indexed = true, solidityName = "indexedStruct", solidityType = "tuple", recommendedTypes = emptyList(), parameters = listOf( ContractParameter( name = "Owner address", description = "Contract owner address", solidityName = "owner", solidityType = "address", recommendedTypes = emptyList(), parameters = null, hints = null ) ), hints = null ) ) ) ), manifest = ManifestJson.EMPTY, artifact = ArtifactJson.EMPTY ) private val CONTRACT_INTERFACE = InterfaceManifestJson( name = "Example Interface", description = "Example smart contract interface", tags = setOf("interface-tag"), eventDecorators = emptyList(), functionDecorators = listOf( FunctionDecorator( signature = "setOwner(address)", name = "Set owner", description = "Set contract owner", parameterDecorators = listOf( TypeDecorator( name = "New owner", description = "New owner of the contract", recommendedTypes = emptyList(), parameters = emptyList(), hints = emptyList() ) ), returnDecorators = emptyList(), emittableEvents = emptyList(), readOnly = false ), FunctionDecorator( signature = "getOwner()", name = "Get owner", description = "Get current contract owner", parameterDecorators = emptyList(), returnDecorators = listOf( ReturnTypeDecorator( name = "Current owner", description = "Current owner of the contract", solidityType = "address", recommendedTypes = emptyList(), parameters = emptyList(), hints = emptyList() ) ), emittableEvents = emptyList(), readOnly = true ) ) ) private val INCOMPATIBLE_INTERFACE = InterfaceManifestJson( name = "Incomaptible Interface", description = "Incomaptible smart contract interface", tags = setOf("interface-tag"), eventDecorators = emptyList(), functionDecorators = listOf( FunctionDecorator( signature = "nonExistent()", name = "", description = "", parameterDecorators = emptyList(), returnDecorators = emptyList(), emittableEvents = emptyList(), readOnly = false ) ) ) private val EVENTS_1 = listOf( EventInfoResponse( signature = "ExampleEvent(tuple(address),tuple(address))", arguments = listOf( EventArgumentResponse( name = "nonIndexedStruct", type = EventArgumentResponseType.VALUE, value = listOf(WalletAddress("a").rawValue), hash = null ), EventArgumentResponse( name = "indexedStruct", type = EventArgumentResponseType.HASH, value = null, hash = "0xc65a7bb8d6351c1cf70c95a316cc6a92839c986682d98bc35f958f4883f9d2a8" ) ) ) ) private val EVENTS_2 = listOf( EventInfoResponse( signature = "ExampleEvent(tuple(address),tuple(address))", arguments = listOf( EventArgumentResponse( name = "nonIndexedStruct", type = EventArgumentResponseType.VALUE, value = listOf("0x35e13c4870077f4610b74f23e887cbb10e21c19f"), hash = null ), EventArgumentResponse( name = "indexedStruct", type = EventArgumentResponseType.HASH, value = null, hash = "0xe412d7b15343cf0762057bcdfc6e0e1196c887a6e48273443abb85a65433a9e2" ) ) ) ) } private val accounts = HardhatTestContainer.ACCOUNTS @Suppress("unused") protected val manifestServiceContainer = SharedTestContainers.manifestServiceContainer @Autowired private lateinit var contractDeploymentRequestRepository: ContractDeploymentRequestRepository @Autowired private lateinit var contractDecoratorRepository: ContractDecoratorRepository @Autowired private lateinit var importedContractDecoratorRepository: ImportedContractDecoratorRepository @Autowired private lateinit var contractInterfacesRepository: ContractInterfacesRepository @Autowired private lateinit var contractMetadataRepository: ContractMetadataRepository @Autowired private lateinit var dslContext: DSLContext @BeforeEach fun beforeEach() { postgresContainer.cleanAllDatabaseTables(dslContext) dslContext.executeInsert( ContractMetadataRecord( id = ContractMetadataId(UUID.randomUUID()), name = CONTRACT_DECORATOR.name, description = CONTRACT_DECORATOR.description, contractId = CONTRACT_DECORATOR.id, contractTags = CONTRACT_DECORATOR.tags.map { it.value }.toTypedArray(), contractImplements = CONTRACT_DECORATOR.implements.map { it.value }.toTypedArray(), projectId = Constants.NIL_PROJECT_ID ) ) dslContext.executeInsert( UserIdentifierRecord( id = OWNER_ID, userIdentifier = "user-identifier", identifierType = UserIdentifierType.ETH_WALLET_ADDRESS, stripeClientId = null ) ) dslContext.executeInsert( ProjectRecord( id = PROJECT.id, ownerId = PROJECT.ownerId, issuerContractAddress = PROJECT.issuerContractAddress, baseRedirectUrl = PROJECT.baseRedirectUrl, chainId = PROJECT.chainId, customRpcUrl = PROJECT.customRpcUrl, createdAt = PROJECT.createdAt ) ) dslContext.executeInsert( ApiKeyRecord( id = ApiKeyId(UUID.randomUUID()), projectId = PROJECT_ID, apiKey = API_KEY, createdAt = TestData.TIMESTAMP ) ) contractDecoratorRepository.delete(CONTRACT_DECORATOR.id) } @Test fun mustCorrectlyPreviewSmartContractImport() { val interfaceId = InterfaceId("example.ownable") suppose("some contract interface is in the repository") { contractInterfacesRepository.store(interfaceId, CONTRACT_INTERFACE) } val mainAccount = accounts[0] val ownerAddress = WalletAddress(HardhatTestContainer.ACCOUNT_ADDRESS_10) val contract = suppose("simple ERC20 contract is deployed") { ExampleContract.deploy( hardhatContainer.web3j, mainAccount, DefaultGasProvider(), ownerAddress.rawValue ).send() } val chainId = TestData.CHAIN_ID val contractAddress = ContractAddress(contract.contractAddress) val response = suppose("request to preview smart contract import is made") { val response = mockMvc.perform( MockMvcRequestBuilders.get( "/v1/import-smart-contract/preview/${chainId.value}/contract/${contractAddress.rawValue}" ) ) .andExpect(MockMvcResultMatchers.status().isOk) .andReturn() objectMapper.readValue(response.response.contentAsString, ImportPreviewResponse::class.java) } val importedContractId = ContractId("imported-${contractAddress.rawValue}-${chainId.value}") verify("correct response is returned") { expectThat(response) .isEqualTo( ImportPreviewResponse( manifest = response.manifest, artifact = response.artifact, decorator = ContractDecoratorResponse( id = importedContractId.value, name = "Imported Contract", description = "Imported smart contract.", binary = response.decorator.binary, tags = listOf("interface-tag"), implements = listOf(interfaceId.value), constructors = emptyList(), functions = listOf( ContractFunction( name = "Set owner", description = "Set contract owner", solidityName = "setOwner", signature = "setOwner(address)", inputs = listOf( ContractParameter( name = "New owner", description = "New owner of the contract", solidityName = "param1", solidityType = "address", recommendedTypes = emptyList(), parameters = emptyList(), hints = emptyList() ) ), outputs = emptyList(), emittableEvents = emptyList(), readOnly = false ), ContractFunction( name = "Get owner", description = "Get current contract owner", solidityName = "getOwner", signature = "getOwner()", inputs = emptyList(), outputs = listOf( ContractParameter( name = "Current owner", description = "Current owner of the contract", solidityName = "", solidityType = "address", recommendedTypes = emptyList(), parameters = emptyList(), hints = emptyList() ) ), emittableEvents = emptyList(), readOnly = true ) ), events = emptyList() ) ) ) } verify("imported contract decorator is not stored in database") { val importedContractDecorator = importedContractDecoratorRepository.getByContractIdAndProjectId( contractId = importedContractId, projectId = Constants.NIL_PROJECT_ID ) expectThat(importedContractDecorator) .isEqualTo(null) } } @Test fun mustCorrectlyImportAlreadyDeployedSmartContract() { val alias = "alias" val ownerAddress = WalletAddress("a") val mainAccount = accounts[0] val deployerAddress = WalletAddress(mainAccount.address) val initialEthAmount = Balance.ZERO suppose("some contract decorator exists in the database") { contractDecoratorRepository.store(CONTRACT_DECORATOR) } val paramsJson = """ [ { "type": "address", "value": "${ownerAddress.rawValue}" } ] """.trimIndent() val createResponse = suppose("request to create contract deployment request is made") { val createResponse = mockMvc.perform( MockMvcRequestBuilders.post("/v1/deploy") .header(CustomHeaders.API_KEY_HEADER, API_KEY) .contentType(MediaType.APPLICATION_JSON) .content( """ { "alias": "$alias", "contract_id": "${CONTRACT_DECORATOR.id.value}", "constructor_params": $paramsJson, "deployer_address": "${deployerAddress.rawValue}", "initial_eth_amount": "${initialEthAmount.rawValue}", "arbitrary_data": { "test": true }, "screen_config": { "before_action_message": "before-action-message", "after_action_message": "after-action-message" } } """.trimIndent() ) ) .andExpect(MockMvcResultMatchers.status().isOk) .andReturn() objectMapper.readValue( createResponse.response.contentAsString, ContractDeploymentRequestResponse::class.java ) } val contract = suppose("contract is deployed") { ExampleContract.deploy( hardhatContainer.web3j, mainAccount, DefaultGasProvider(), ownerAddress.rawValue ).send() } suppose("transaction will have at least one block confirmation") { hardhatContainer.mine() } val receipt = contract.transactionReceipt.get() val txHash = TransactionHash(receipt.transactionHash) val contractAddress = ContractAddress(receipt.contractAddress) suppose("transaction info is attached to contract deployment request") { contractDeploymentRequestRepository.setTxInfo(createResponse.id, txHash, deployerAddress) contractDeploymentRequestRepository.setContractAddress(createResponse.id, contractAddress) } val newAlias = "new-alias" val importResponse = suppose("request to import smart contract is made") { val response = mockMvc.perform( MockMvcRequestBuilders.post("/v1/import-smart-contract") .header(CustomHeaders.API_KEY_HEADER, API_KEY) .contentType(MediaType.APPLICATION_JSON) .content( """ { "alias": "$newAlias", "contract_address": "${contractAddress.rawValue}", "arbitrary_data": { "test": true }, "screen_config": { "before_action_message": "before-action-message", "after_action_message": "after-action-message" } } """.trimIndent() ) ) .andExpect(MockMvcResultMatchers.status().isOk) .andReturn() objectMapper.readValue(response.response.contentAsString, ContractDeploymentRequestResponse::class.java) } verify("correct response is returned") { expectThat(importResponse) .isEqualTo( ContractDeploymentRequestResponse( id = importResponse.id, alias = newAlias, name = CONTRACT_DECORATOR.name, description = CONTRACT_DECORATOR.description, status = Status.SUCCESS, contractId = CONTRACT_DECORATOR.id.value, contractDeploymentData = createResponse.contractDeploymentData, constructorParams = createResponse.constructorParams, contractTags = CONTRACT_DECORATOR.tags.map { it.value }, contractImplements = CONTRACT_DECORATOR.implements.map { it.value }, initialEthAmount = BigInteger.ZERO, chainId = PROJECT.chainId.value, redirectUrl = PROJECT.baseRedirectUrl.value + "/request-deploy/${importResponse.id.value}/action", projectId = PROJECT_ID, createdAt = importResponse.createdAt, arbitraryData = importResponse.arbitraryData, screenConfig = ScreenConfig( beforeActionMessage = "before-action-message", afterActionMessage = "after-action-message" ), contractAddress = ContractAddress(contract.contractAddress).rawValue, deployerAddress = deployerAddress.rawValue, deployTx = createResponse.deployTx.copy( txHash = txHash.value, blockConfirmations = importResponse.deployTx.blockConfirmations, timestamp = importResponse.deployTx.timestamp ), imported = false, proxy = false, implementationContractAddress = null, events = EVENTS_1 ) ) expectThat(importResponse.createdAt) .isCloseToUtcNow(WITHIN_TIME_TOLERANCE) } verify("contract deployment request is correctly stored in database") { val storedRequest = contractDeploymentRequestRepository.getById(importResponse.id) expectThat(storedRequest) .isEqualTo( ContractDeploymentRequest( id = importResponse.id, alias = newAlias, name = CONTRACT_DECORATOR.name, description = CONTRACT_DECORATOR.description, contractId = CONTRACT_DECORATOR.id, contractData = ContractBinaryData(createResponse.contractDeploymentData), constructorParams = createResponse.constructorParams, contractTags = CONTRACT_DECORATOR.tags, contractImplements = CONTRACT_DECORATOR.implements, initialEthAmount = Balance.ZERO, chainId = PROJECT.chainId, redirectUrl = PROJECT.baseRedirectUrl.value + "/request-deploy/${importResponse.id.value}/action", projectId = PROJECT_ID, createdAt = storedRequest!!.createdAt, arbitraryData = importResponse.arbitraryData, screenConfig = ScreenConfig( beforeActionMessage = "before-action-message", afterActionMessage = "after-action-message" ), contractAddress = contractAddress, deployerAddress = deployerAddress, txHash = txHash, imported = false, proxy = false, implementationContractAddress = null ) ) expectThat(storedRequest.createdAt.value) .isCloseToUtcNow(WITHIN_TIME_TOLERANCE) } } @Test fun mustCorrectlyImportSmartContractForSomeExistingContractDecorator() { suppose("some contract decorator exists in the database") { contractDecoratorRepository.store(CONTRACT_DECORATOR) } val mainAccount = accounts[0] val ownerAddress = WalletAddress(HardhatTestContainer.ACCOUNT_ADDRESS_10) val contract = suppose("simple ERC20 contract is deployed") { ExampleContract.deploy( hardhatContainer.web3j, mainAccount, DefaultGasProvider(), ownerAddress.rawValue ).send() } val alias = "alias" val response = suppose("request to import smart contract is made") { val response = mockMvc.perform( MockMvcRequestBuilders.post("/v1/import-smart-contract") .header(CustomHeaders.API_KEY_HEADER, API_KEY) .contentType(MediaType.APPLICATION_JSON) .content( """ { "alias": "$alias", "contract_id": "${CONTRACT_DECORATOR.id.value}", "contract_address": "${contract.contractAddress}", "arbitrary_data": { "test": true }, "screen_config": { "before_action_message": "before-action-message", "after_action_message": "after-action-message" } } """.trimIndent() ) ) .andExpect(MockMvcResultMatchers.status().isOk) .andReturn() objectMapper.readValue(response.response.contentAsString, ContractDeploymentRequestResponse::class.java) } val deployerAddress = WalletAddress(mainAccount.address).rawValue val constructorParams = listOf(TypeAndValue(type = "address", value = ownerAddress.rawValue)) verify("correct response is returned") { expectThat(response) .isEqualTo( ContractDeploymentRequestResponse( id = response.id, alias = alias, name = CONTRACT_DECORATOR.name, description = CONTRACT_DECORATOR.description, status = Status.SUCCESS, contractId = CONTRACT_DECORATOR.id.value, contractDeploymentData = response.contractDeploymentData, constructorParams = objectMapper.valueToTree(constructorParams), contractTags = CONTRACT_DECORATOR.tags.map { it.value }, contractImplements = CONTRACT_DECORATOR.implements.map { it.value }, initialEthAmount = BigInteger.ZERO, chainId = PROJECT.chainId.value, redirectUrl = PROJECT.baseRedirectUrl.value + "/request-deploy/${response.id.value}/action", projectId = PROJECT_ID, createdAt = response.createdAt, arbitraryData = response.arbitraryData, screenConfig = ScreenConfig( beforeActionMessage = "before-action-message", afterActionMessage = "after-action-message" ), contractAddress = ContractAddress(contract.contractAddress).rawValue, deployerAddress = deployerAddress, deployTx = TransactionResponse( txHash = TransactionHash(contract.transactionReceipt.get().transactionHash).value, from = deployerAddress, to = ZeroAddress.rawValue, data = response.deployTx.data, value = BigInteger.ZERO, blockConfirmations = response.deployTx.blockConfirmations, timestamp = response.deployTx.timestamp ), imported = true, proxy = false, implementationContractAddress = null, events = EVENTS_2 ) ) expectThat(response.createdAt) .isCloseToUtcNow(WITHIN_TIME_TOLERANCE) } verify("contract deployment request is correctly stored in database") { val storedRequest = contractDeploymentRequestRepository.getById(response.id) expectThat(storedRequest) .isEqualTo( ContractDeploymentRequest( id = response.id, alias = alias, name = CONTRACT_DECORATOR.name, description = CONTRACT_DECORATOR.description, contractId = CONTRACT_DECORATOR.id, contractData = ContractBinaryData(response.contractDeploymentData), constructorParams = objectMapper.valueToTree(constructorParams), contractTags = CONTRACT_DECORATOR.tags, contractImplements = CONTRACT_DECORATOR.implements, initialEthAmount = Balance.ZERO, chainId = PROJECT.chainId, redirectUrl = PROJECT.baseRedirectUrl.value + "/request-deploy/${response.id.value}/action", projectId = PROJECT_ID, createdAt = storedRequest!!.createdAt, arbitraryData = response.arbitraryData, screenConfig = ScreenConfig( beforeActionMessage = "before-action-message", afterActionMessage = "after-action-message" ), contractAddress = ContractAddress(contract.contractAddress), deployerAddress = WalletAddress(deployerAddress), txHash = TransactionHash(contract.transactionReceipt.get().transactionHash), imported = true, proxy = false, implementationContractAddress = null ) ) expectThat(storedRequest.createdAt.value) .isCloseToUtcNow(WITHIN_TIME_TOLERANCE) } } @Test fun mustCorrectlyImportSmartContractWhenContractDecoratorIsNotSpecified() { val mainAccount = accounts[0] val ownerAddress = WalletAddress(HardhatTestContainer.ACCOUNT_ADDRESS_10) val contract = suppose("simple ERC20 contract is deployed") { ExampleContract.deploy( hardhatContainer.web3j, mainAccount, DefaultGasProvider(), ownerAddress.rawValue ).send() } val alias = "alias" val response = suppose("request to import smart contract is made") { val response = mockMvc.perform( MockMvcRequestBuilders.post("/v1/import-smart-contract") .header(CustomHeaders.API_KEY_HEADER, API_KEY) .contentType(MediaType.APPLICATION_JSON) .content( """ { "alias": "$alias", "contract_address": "${contract.contractAddress}", "arbitrary_data": { "test": true }, "screen_config": { "before_action_message": "before-action-message", "after_action_message": "after-action-message" } } """.trimIndent() ) ) .andExpect(MockMvcResultMatchers.status().isOk) .andReturn() objectMapper.readValue(response.response.contentAsString, ContractDeploymentRequestResponse::class.java) } val deployerAddress = WalletAddress(mainAccount.address).rawValue val constructorParams = listOf( TypeAndValue( type = "bytes32", value = ownerAddress.rawValue.removePrefix("0x").padStart(64, '0') .chunked(2).map { it.toUByte(16).toByte() } ) ) val importedContractId = ContractId("imported-${contract.contractAddress}-${PROJECT.chainId.value}") verify("correct response is returned") { expectThat(response) .isEqualTo( ContractDeploymentRequestResponse( id = response.id, alias = alias, name = "Imported Contract", description = "Imported smart contract.", status = Status.SUCCESS, contractId = importedContractId.value, contractDeploymentData = response.contractDeploymentData, constructorParams = objectMapper.valueToTree(constructorParams), contractTags = emptyList(), contractImplements = emptyList(), initialEthAmount = BigInteger.ZERO, chainId = PROJECT.chainId.value, redirectUrl = PROJECT.baseRedirectUrl.value + "/request-deploy/${response.id.value}/action", projectId = PROJECT_ID, createdAt = response.createdAt, arbitraryData = response.arbitraryData, screenConfig = ScreenConfig( beforeActionMessage = "before-action-message", afterActionMessage = "after-action-message" ), contractAddress = ContractAddress(contract.contractAddress).rawValue, deployerAddress = deployerAddress, deployTx = TransactionResponse( txHash = TransactionHash(contract.transactionReceipt.get().transactionHash).value, from = deployerAddress, to = ZeroAddress.rawValue, data = response.deployTx.data, value = BigInteger.ZERO, blockConfirmations = response.deployTx.blockConfirmations, timestamp = response.deployTx.timestamp ), imported = true, proxy = false, implementationContractAddress = null, events = response.events ) ) expectThat(response.createdAt) .isCloseToUtcNow(WITHIN_TIME_TOLERANCE) } verify("contract deployment request is correctly stored in database") { val storedRequest = contractDeploymentRequestRepository.getById(response.id) expectThat(storedRequest) .isEqualTo( ContractDeploymentRequest( id = response.id, alias = alias, name = "Imported Contract", description = "Imported smart contract.", contractId = importedContractId, contractData = ContractBinaryData(response.contractDeploymentData), constructorParams = objectMapper.valueToTree(constructorParams), contractTags = emptyList(), contractImplements = emptyList(), initialEthAmount = Balance.ZERO, chainId = PROJECT.chainId, redirectUrl = PROJECT.baseRedirectUrl.value + "/request-deploy/${response.id.value}/action", projectId = PROJECT_ID, createdAt = storedRequest!!.createdAt, arbitraryData = response.arbitraryData, screenConfig = ScreenConfig( beforeActionMessage = "before-action-message", afterActionMessage = "after-action-message" ), contractAddress = ContractAddress(contract.contractAddress), deployerAddress = WalletAddress(deployerAddress), txHash = TransactionHash(contract.transactionReceipt.get().transactionHash), imported = true, proxy = false, implementationContractAddress = null ) ) expectThat(storedRequest.createdAt.value) .isCloseToUtcNow(WITHIN_TIME_TOLERANCE) } verify("imported contract decorator is correctly stored in database") { val importedContractDecorator = importedContractDecoratorRepository.getByContractIdAndProjectId( contractId = importedContractId, projectId = PROJECT_ID )!! expectThat(importedContractDecorator) .isEqualTo( CONTRACT_DECORATOR.copy( id = importedContractId, name = "Imported Contract", description = "Imported smart contract.", tags = emptyList(), implements = emptyList(), constructors = emptyList(), events = emptyList(), functions = listOf( ContractFunction( name = "setOwner", description = "", solidityName = "setOwner", signature = "setOwner(address)", inputs = listOf( ContractParameter( name = "param1", description = "", solidityName = "param1", solidityType = "address", recommendedTypes = emptyList(), parameters = null, hints = null ) ), outputs = emptyList(), emittableEvents = emptyList(), readOnly = false ), ContractFunction( name = "getOwner", description = "", solidityName = "getOwner", signature = "getOwner()", inputs = emptyList(), outputs = emptyList(), emittableEvents = emptyList(), readOnly = false ) ), manifest = importedContractDecorator.manifest, artifact = importedContractDecorator.artifact ) ) } } @Test fun mustCorrectlyImportProxySmartContractWhenContractDecoratorIsNotSpecified() { val mainAccount = accounts[0] val ownerAddress = WalletAddress(HardhatTestContainer.ACCOUNT_ADDRESS_10) val contract = suppose("simple ERC20 contract is deployed") { ExampleContract.deploy( hardhatContainer.web3j, mainAccount, DefaultGasProvider(), ownerAddress.rawValue ).send() } val proxy = suppose("proxy contract is deployed") { DummyProxy.deploy( hardhatContainer.web3j, mainAccount, DefaultGasProvider(), contract.contractAddress ).send() } val alias = "alias" val response = suppose("request to import proxy smart contract is made") { val response = mockMvc.perform( MockMvcRequestBuilders.post("/v1/import-smart-contract") .header(CustomHeaders.API_KEY_HEADER, API_KEY) .contentType(MediaType.APPLICATION_JSON) .content( """ { "alias": "$alias", "contract_address": "${proxy.contractAddress}", "arbitrary_data": { "test": true }, "screen_config": { "before_action_message": "before-action-message", "after_action_message": "after-action-message" } } """.trimIndent() ) ) .andExpect(MockMvcResultMatchers.status().isOk) .andReturn() objectMapper.readValue(response.response.contentAsString, ContractDeploymentRequestResponse::class.java) } val deployerAddress = WalletAddress(mainAccount.address).rawValue val constructorParams = listOf( TypeAndValue( type = "bytes32", value = ContractAddress(contract.contractAddress).rawValue.removePrefix("0x").padStart(64, '0') .chunked(2).map { it.toUByte(16).toByte() } ) ) val importedContractId = ContractId("imported-${proxy.contractAddress}-${PROJECT.chainId.value}") verify("correct response is returned") { expectThat(response) .isEqualTo( ContractDeploymentRequestResponse( id = response.id, alias = alias, name = "Imported Contract", description = "Imported smart contract.", status = Status.SUCCESS, contractId = importedContractId.value, contractDeploymentData = response.contractDeploymentData, constructorParams = objectMapper.valueToTree(constructorParams), contractTags = emptyList(), contractImplements = emptyList(), initialEthAmount = BigInteger.ZERO, chainId = PROJECT.chainId.value, redirectUrl = PROJECT.baseRedirectUrl.value + "/request-deploy/${response.id.value}/action", projectId = PROJECT_ID, createdAt = response.createdAt, arbitraryData = response.arbitraryData, screenConfig = ScreenConfig( beforeActionMessage = "before-action-message", afterActionMessage = "after-action-message" ), contractAddress = ContractAddress(proxy.contractAddress).rawValue, deployerAddress = deployerAddress, deployTx = TransactionResponse( txHash = TransactionHash(proxy.transactionReceipt.get().transactionHash).value, from = deployerAddress, to = ZeroAddress.rawValue, data = response.deployTx.data, value = BigInteger.ZERO, blockConfirmations = response.deployTx.blockConfirmations, timestamp = response.deployTx.timestamp ), imported = true, proxy = true, implementationContractAddress = ContractAddress(contract.contractAddress).rawValue, events = emptyList() ) ) expectThat(response.createdAt) .isCloseToUtcNow(WITHIN_TIME_TOLERANCE) } verify("contract deployment request is correctly stored in database") { val storedRequest = contractDeploymentRequestRepository.getById(response.id) expectThat(storedRequest) .isEqualTo( ContractDeploymentRequest( id = response.id, alias = alias, name = "Imported Contract", description = "Imported smart contract.", contractId = importedContractId, contractData = ContractBinaryData(response.contractDeploymentData), constructorParams = objectMapper.valueToTree(constructorParams), contractTags = emptyList(), contractImplements = emptyList(), initialEthAmount = Balance.ZERO, chainId = PROJECT.chainId, redirectUrl = PROJECT.baseRedirectUrl.value + "/request-deploy/${response.id.value}/action", projectId = PROJECT_ID, createdAt = storedRequest!!.createdAt, arbitraryData = response.arbitraryData, screenConfig = ScreenConfig( beforeActionMessage = "before-action-message", afterActionMessage = "after-action-message" ), contractAddress = ContractAddress(proxy.contractAddress), deployerAddress = WalletAddress(deployerAddress), txHash = TransactionHash(proxy.transactionReceipt.get().transactionHash), imported = true, proxy = true, implementationContractAddress = ContractAddress(contract.contractAddress) ) ) expectThat(storedRequest.createdAt.value) .isCloseToUtcNow(WITHIN_TIME_TOLERANCE) } verify("imported contract decorator is correctly stored in database") { val importedContractDecorator = importedContractDecoratorRepository.getByContractIdAndProjectId( contractId = importedContractId, projectId = PROJECT_ID )!! expectThat(importedContractDecorator) .isEqualTo( CONTRACT_DECORATOR.copy( id = importedContractId, name = "Imported Contract", description = "Imported smart contract.", binary = importedContractDecorator.binary, tags = emptyList(), implements = emptyList(), constructors = emptyList(), events = emptyList(), functions = listOf( ContractFunction( name = "implementation", description = "", solidityName = "implementation", signature = "implementation()", inputs = emptyList(), outputs = emptyList(), emittableEvents = emptyList(), readOnly = false ), ContractFunction( name = "setOwner", description = "", solidityName = "setOwner", signature = "setOwner(address)", inputs = listOf( ContractParameter( name = "param1", description = "", solidityName = "param1", solidityType = "address", recommendedTypes = emptyList(), parameters = null, hints = null ) ), outputs = emptyList(), emittableEvents = emptyList(), readOnly = false ), ContractFunction( name = "getOwner", description = "", solidityName = "getOwner", signature = "getOwner()", inputs = emptyList(), outputs = emptyList(), emittableEvents = emptyList(), readOnly = false ) ), manifest = importedContractDecorator.manifest, artifact = importedContractDecorator.artifact ) ) } } @Test fun mustReturn404NotFoundWhenImportingSmartContractForNonExistentContractDecorator() { verify("404 is returned for non-existent contract decorator") { val response = mockMvc.perform( MockMvcRequestBuilders.post("/v1/import-smart-contract") .header(CustomHeaders.API_KEY_HEADER, API_KEY) .contentType(MediaType.APPLICATION_JSON) .content( """ { "alias": "alias", "contract_id": "${CONTRACT_DECORATOR.id.value}", "contract_address": "${ContractAddress("abc").rawValue}", "arbitrary_data": { "test": true }, "screen_config": { "before_action_message": "before-action-message", "after_action_message": "after-action-message" } } """.trimIndent() ) ) .andExpect(MockMvcResultMatchers.status().isNotFound) .andReturn() expectResponseErrorCode(response, ErrorCode.RESOURCE_NOT_FOUND) } } @Test fun mustReturn404NotFoundWhenImportingNonExistentSmartContract() { suppose("some contract decorator exists in the database") { contractDecoratorRepository.store(CONTRACT_DECORATOR) } verify("404 is returned for non-existent smart contract") { val response = mockMvc.perform( MockMvcRequestBuilders.post("/v1/import-smart-contract") .header(CustomHeaders.API_KEY_HEADER, API_KEY) .contentType(MediaType.APPLICATION_JSON) .content( """ { "alias": "alias", "contract_id": "${CONTRACT_DECORATOR.id.value}", "contract_address": "${ContractAddress("abc").rawValue}", "arbitrary_data": { "test": true }, "screen_config": { "before_action_message": "before-action-message", "after_action_message": "after-action-message" } } """.trimIndent() ) ) .andExpect(MockMvcResultMatchers.status().isNotFound) .andReturn() expectResponseErrorCode(response, ErrorCode.CONTRACT_NOT_FOUND) } } @Test fun mustReturn400BadRequestWhenContractBinaryMismatchesRequestedContractDecoratorBinary() { suppose("some contract decorator exists in the database") { contractDecoratorRepository.store(CONTRACT_DECORATOR.copy(binary = ContractBinaryData("abc"))) } val mainAccount = accounts[0] val ownerAddress = WalletAddress(HardhatTestContainer.ACCOUNT_ADDRESS_10) val contract = suppose("simple ERC20 contract is deployed") { ExampleContract.deploy( hardhatContainer.web3j, mainAccount, DefaultGasProvider(), ownerAddress.rawValue ).send() } verify("400 is returned for mismatching smart contract binary") { val response = mockMvc.perform( MockMvcRequestBuilders.post("/v1/import-smart-contract") .header(CustomHeaders.API_KEY_HEADER, API_KEY) .contentType(MediaType.APPLICATION_JSON) .content( """ { "alias": "alias", "contract_id": "${CONTRACT_DECORATOR.id.value}", "contract_address": "${contract.contractAddress}", "arbitrary_data": { "test": true }, "screen_config": { "before_action_message": "before-action-message", "after_action_message": "after-action-message" } } """.trimIndent() ) ) .andExpect(MockMvcResultMatchers.status().isBadRequest) .andReturn() expectResponseErrorCode(response, ErrorCode.CONTRACT_BINARY_MISMATCH) } } @Test fun mustCorrectlySuggestInterfacesForImportedSmartContractWhenContractDecoratorIsNotSpecified() { val mainAccount = accounts[0] val ownerAddress = WalletAddress(HardhatTestContainer.ACCOUNT_ADDRESS_10) val contract = suppose("simple ERC20 contract is deployed") { ExampleContract.deploy( hardhatContainer.web3j, mainAccount, DefaultGasProvider(), ownerAddress.rawValue ).send() } val alias = "alias" val importResponse = suppose("request to import smart contract is made") { val response = mockMvc.perform( MockMvcRequestBuilders.post("/v1/import-smart-contract") .header(CustomHeaders.API_KEY_HEADER, API_KEY) .contentType(MediaType.APPLICATION_JSON) .content( """ { "alias": "$alias", "contract_address": "${contract.contractAddress}", "arbitrary_data": { "test": true }, "screen_config": { "before_action_message": "before-action-message", "after_action_message": "after-action-message" } } """.trimIndent() ) ) .andExpect(MockMvcResultMatchers.status().isOk) .andReturn() objectMapper.readValue(response.response.contentAsString, ContractDeploymentRequestResponse::class.java) } val interfaceId = InterfaceId("example.ownable") suppose("some contract interface is in the repository") { contractInterfacesRepository.store(interfaceId, CONTRACT_INTERFACE) } val suggestedInterfacesResponse = suppose("suggested imported smart contract interfaces are fetched") { val response = mockMvc.perform( MockMvcRequestBuilders.get("/v1/import-smart-contract/${importResponse.id.value}/suggested-interfaces") ) .andExpect(MockMvcResultMatchers.status().isOk) .andReturn() objectMapper.readValue( response.response.contentAsString, SuggestedContractInterfaceManifestsResponse::class.java ) } verify("correct interface manifests are returned") { expectThat(suggestedInterfacesResponse) .isEqualTo( SuggestedContractInterfaceManifestsResponse( manifests = listOf(ContractInterfaceManifestResponse(interfaceId, CONTRACT_INTERFACE)), bestMatchingInterfaces = listOf(interfaceId.value) ) ) } } @Test fun mustCorrectlyAddInterfacesToImportedSmartContractWhenContractDecoratorIsNotSpecified() { val mainAccount = accounts[0] val ownerAddress = WalletAddress(HardhatTestContainer.ACCOUNT_ADDRESS_10) val contract = suppose("simple ERC20 contract is deployed") { ExampleContract.deploy( hardhatContainer.web3j, mainAccount, DefaultGasProvider(), ownerAddress.rawValue ).send() } val alias = "alias" val importResponse = suppose("request to import smart contract is made") { val response = mockMvc.perform( MockMvcRequestBuilders.post("/v1/import-smart-contract") .header(CustomHeaders.API_KEY_HEADER, API_KEY) .contentType(MediaType.APPLICATION_JSON) .content( """ { "alias": "$alias", "contract_address": "${contract.contractAddress}", "arbitrary_data": { "test": true }, "screen_config": { "before_action_message": "before-action-message", "after_action_message": "after-action-message" } } """.trimIndent() ) ) .andExpect(MockMvcResultMatchers.status().isOk) .andReturn() objectMapper.readValue(response.response.contentAsString, ContractDeploymentRequestResponse::class.java) } val interfaceId = InterfaceId("example.ownable") suppose("some contract interface is in the repository") { contractInterfacesRepository.store(interfaceId, CONTRACT_INTERFACE) } val interfacesResponse = suppose("interface is added to imported smart contract") { val response = mockMvc.perform( MockMvcRequestBuilders.patch("/v1/import-smart-contract/${importResponse.id.value}/add-interfaces") .header(CustomHeaders.API_KEY_HEADER, API_KEY) .contentType(MediaType.APPLICATION_JSON) .content( """ { "interfaces": ["${interfaceId.value}"] } """.trimIndent() ) ) .andExpect(MockMvcResultMatchers.status().isOk) .andReturn() objectMapper.readValue(response.response.contentAsString, ContractDeploymentRequestResponse::class.java) } val deployerAddress = WalletAddress(mainAccount.address).rawValue val constructorParams = listOf( TypeAndValue( type = "bytes32", value = ownerAddress.rawValue.removePrefix("0x").padStart(64, '0') .chunked(2).map { it.toUByte(16).toByte() } ) ) val importedContractId = ContractId("imported-${contract.contractAddress}-${PROJECT.chainId.value}") verify("correct response is returned") { expectThat(interfacesResponse) .isEqualTo( ContractDeploymentRequestResponse( id = interfacesResponse.id, alias = alias, name = "Imported Contract", description = "Imported smart contract.", status = Status.SUCCESS, contractId = importedContractId.value, contractDeploymentData = interfacesResponse.contractDeploymentData, constructorParams = objectMapper.valueToTree(constructorParams), contractTags = emptyList(), contractImplements = listOf(interfaceId.value), initialEthAmount = BigInteger.ZERO, chainId = PROJECT.chainId.value, redirectUrl = PROJECT.baseRedirectUrl.value + "/request-deploy/${interfacesResponse.id.value}/action", projectId = PROJECT_ID, createdAt = interfacesResponse.createdAt, arbitraryData = interfacesResponse.arbitraryData, screenConfig = ScreenConfig( beforeActionMessage = "before-action-message", afterActionMessage = "after-action-message" ), contractAddress = ContractAddress(contract.contractAddress).rawValue, deployerAddress = deployerAddress, deployTx = TransactionResponse( txHash = TransactionHash(contract.transactionReceipt.get().transactionHash).value, from = deployerAddress, to = ZeroAddress.rawValue, data = interfacesResponse.deployTx.data, value = BigInteger.ZERO, blockConfirmations = interfacesResponse.deployTx.blockConfirmations, timestamp = interfacesResponse.deployTx.timestamp ), imported = true, proxy = false, implementationContractAddress = null, events = interfacesResponse.events ) ) } } @Test fun mustReturn400BadRequestWhenAddingNonExistentContractInterface() { val mainAccount = accounts[0] val ownerAddress = WalletAddress(HardhatTestContainer.ACCOUNT_ADDRESS_10) val contract = suppose("simple ERC20 contract is deployed") { ExampleContract.deploy( hardhatContainer.web3j, mainAccount, DefaultGasProvider(), ownerAddress.rawValue ).send() } val alias = "alias" val importResponse = suppose("request to import smart contract is made") { val response = mockMvc.perform( MockMvcRequestBuilders.post("/v1/import-smart-contract") .header(CustomHeaders.API_KEY_HEADER, API_KEY) .contentType(MediaType.APPLICATION_JSON) .content( """ { "alias": "$alias", "contract_address": "${contract.contractAddress}", "arbitrary_data": { "test": true }, "screen_config": { "before_action_message": "before-action-message", "after_action_message": "after-action-message" } } """.trimIndent() ) ) .andExpect(MockMvcResultMatchers.status().isOk) .andReturn() objectMapper.readValue(response.response.contentAsString, ContractDeploymentRequestResponse::class.java) } val interfaceId = InterfaceId("non-existent") verify("400 is returned for non-existent smart contract interface") { val response = mockMvc.perform( MockMvcRequestBuilders.patch("/v1/import-smart-contract/${importResponse.id.value}/add-interfaces") .header(CustomHeaders.API_KEY_HEADER, API_KEY) .contentType(MediaType.APPLICATION_JSON) .content( """ { "interfaces": ["${interfaceId.value}"] } """.trimIndent() ) ) .andExpect(MockMvcResultMatchers.status().isBadRequest) .andReturn() expectResponseErrorCode(response, ErrorCode.CONTRACT_INTERFACE_NOT_FOUND) } } @Test fun mustReturn400BadRequestWhenAddingIncompatibleContractInterface() { val mainAccount = accounts[0] val ownerAddress = WalletAddress(HardhatTestContainer.ACCOUNT_ADDRESS_10) val contract = suppose("simple ERC20 contract is deployed") { ExampleContract.deploy( hardhatContainer.web3j, mainAccount, DefaultGasProvider(), ownerAddress.rawValue ).send() } val alias = "alias" val importResponse = suppose("request to import smart contract is made") { val response = mockMvc.perform( MockMvcRequestBuilders.post("/v1/import-smart-contract") .header(CustomHeaders.API_KEY_HEADER, API_KEY) .contentType(MediaType.APPLICATION_JSON) .content( """ { "alias": "$alias", "contract_address": "${contract.contractAddress}", "arbitrary_data": { "test": true }, "screen_config": { "before_action_message": "before-action-message", "after_action_message": "after-action-message" } } """.trimIndent() ) ) .andExpect(MockMvcResultMatchers.status().isOk) .andReturn() objectMapper.readValue(response.response.contentAsString, ContractDeploymentRequestResponse::class.java) } val interfaceId = InterfaceId("example.incompatible") suppose("some incompatible contract interface is in the repository") { contractInterfacesRepository.store(interfaceId, INCOMPATIBLE_INTERFACE) } verify("400 is returned for incompatible smart contract interface") { val response = mockMvc.perform( MockMvcRequestBuilders.patch("/v1/import-smart-contract/${importResponse.id.value}/add-interfaces") .header(CustomHeaders.API_KEY_HEADER, API_KEY) .contentType(MediaType.APPLICATION_JSON) .content( """ { "interfaces": ["${interfaceId.value}"] } """.trimIndent() ) ) .andExpect(MockMvcResultMatchers.status().isBadRequest) .andReturn() expectResponseErrorCode(response, ErrorCode.CONTRACT_DECORATOR_INCOMPATIBLE) } } @Test fun mustCorrectlyRemoveInterfacesFromImportedSmartContractWhenContractDecoratorIsNotSpecified() { val mainAccount = accounts[0] val ownerAddress = WalletAddress(HardhatTestContainer.ACCOUNT_ADDRESS_10) val contract = suppose("simple ERC20 contract is deployed") { ExampleContract.deploy( hardhatContainer.web3j, mainAccount, DefaultGasProvider(), ownerAddress.rawValue ).send() } val alias = "alias" val importResponse = suppose("request to import smart contract is made") { val response = mockMvc.perform( MockMvcRequestBuilders.post("/v1/import-smart-contract") .header(CustomHeaders.API_KEY_HEADER, API_KEY) .contentType(MediaType.APPLICATION_JSON) .content( """ { "alias": "$alias", "contract_address": "${contract.contractAddress}", "arbitrary_data": { "test": true }, "screen_config": { "before_action_message": "before-action-message", "after_action_message": "after-action-message" } } """.trimIndent() ) ) .andExpect(MockMvcResultMatchers.status().isOk) .andReturn() objectMapper.readValue(response.response.contentAsString, ContractDeploymentRequestResponse::class.java) } val interfaceId = InterfaceId("example.ownable") suppose("some contract interface is in the repository") { contractInterfacesRepository.store(interfaceId, CONTRACT_INTERFACE) } suppose("some smart contract interface is added to imported smart contract") { importedContractDecoratorRepository.updateInterfaces( contractId = ContractId(importResponse.contractId), projectId = importResponse.projectId, interfaces = listOf(interfaceId), manifest = importedContractDecoratorRepository.getManifestJsonByContractIdAndProjectId( contractId = ContractId(importResponse.contractId), projectId = importResponse.projectId )!!.copy(implements = setOf(interfaceId.value)) ) contractMetadataRepository.updateInterfaces( contractId = ContractId(importResponse.contractId), projectId = importResponse.projectId, interfaces = listOf(interfaceId) ) } val interfacesResponse = suppose("interface is removed from imported smart contract") { val response = mockMvc.perform( MockMvcRequestBuilders.patch("/v1/import-smart-contract/${importResponse.id.value}/remove-interfaces") .header(CustomHeaders.API_KEY_HEADER, API_KEY) .contentType(MediaType.APPLICATION_JSON) .content( """ { "interfaces": ["${interfaceId.value}"] } """.trimIndent() ) ) .andExpect(MockMvcResultMatchers.status().isOk) .andReturn() objectMapper.readValue(response.response.contentAsString, ContractDeploymentRequestResponse::class.java) } val deployerAddress = WalletAddress(mainAccount.address).rawValue val constructorParams = listOf( TypeAndValue( type = "bytes32", value = ownerAddress.rawValue.removePrefix("0x").padStart(64, '0') .chunked(2).map { it.toUByte(16).toByte() } ) ) val importedContractId = ContractId("imported-${contract.contractAddress}-${PROJECT.chainId.value}") verify("correct response is returned") { expectThat(interfacesResponse) .isEqualTo( ContractDeploymentRequestResponse( id = interfacesResponse.id, alias = alias, name = "Imported Contract", description = "Imported smart contract.", status = Status.SUCCESS, contractId = importedContractId.value, contractDeploymentData = interfacesResponse.contractDeploymentData, constructorParams = objectMapper.valueToTree(constructorParams), contractTags = emptyList(), contractImplements = emptyList(), initialEthAmount = BigInteger.ZERO, chainId = PROJECT.chainId.value, redirectUrl = PROJECT.baseRedirectUrl.value + "/request-deploy/${interfacesResponse.id.value}/action", projectId = PROJECT_ID, createdAt = interfacesResponse.createdAt, arbitraryData = interfacesResponse.arbitraryData, screenConfig = ScreenConfig( beforeActionMessage = "before-action-message", afterActionMessage = "after-action-message" ), contractAddress = ContractAddress(contract.contractAddress).rawValue, deployerAddress = deployerAddress, deployTx = TransactionResponse( txHash = TransactionHash(contract.transactionReceipt.get().transactionHash).value, from = deployerAddress, to = ZeroAddress.rawValue, data = interfacesResponse.deployTx.data, value = BigInteger.ZERO, blockConfirmations = interfacesResponse.deployTx.blockConfirmations, timestamp = interfacesResponse.deployTx.timestamp ), imported = true, proxy = false, implementationContractAddress = null, events = interfacesResponse.events ) ) } } @Test fun mustCorrectlySetInterfacesForImportedSmartContractWhenContractDecoratorIsNotSpecified() { val mainAccount = accounts[0] val ownerAddress = WalletAddress(HardhatTestContainer.ACCOUNT_ADDRESS_10) val contract = suppose("simple ERC20 contract is deployed") { ExampleContract.deploy( hardhatContainer.web3j, mainAccount, DefaultGasProvider(), ownerAddress.rawValue ).send() } val alias = "alias" val importResponse = suppose("request to import smart contract is made") { val response = mockMvc.perform( MockMvcRequestBuilders.post("/v1/import-smart-contract") .header(CustomHeaders.API_KEY_HEADER, API_KEY) .contentType(MediaType.APPLICATION_JSON) .content( """ { "alias": "$alias", "contract_address": "${contract.contractAddress}", "arbitrary_data": { "test": true }, "screen_config": { "before_action_message": "before-action-message", "after_action_message": "after-action-message" } } """.trimIndent() ) ) .andExpect(MockMvcResultMatchers.status().isOk) .andReturn() objectMapper.readValue(response.response.contentAsString, ContractDeploymentRequestResponse::class.java) } val interfaceId = InterfaceId("example.ownable") suppose("some contract interface is in the repository") { contractInterfacesRepository.store(interfaceId, CONTRACT_INTERFACE) } val interfacesResponse = suppose("interface is added to imported smart contract") { val response = mockMvc.perform( MockMvcRequestBuilders.patch("/v1/import-smart-contract/${importResponse.id.value}/set-interfaces") .header(CustomHeaders.API_KEY_HEADER, API_KEY) .contentType(MediaType.APPLICATION_JSON) .content( """ { "interfaces": ["${interfaceId.value}"] } """.trimIndent() ) ) .andExpect(MockMvcResultMatchers.status().isOk) .andReturn() objectMapper.readValue(response.response.contentAsString, ContractDeploymentRequestResponse::class.java) } val deployerAddress = WalletAddress(mainAccount.address).rawValue val constructorParams = listOf( TypeAndValue( type = "bytes32", value = ownerAddress.rawValue.removePrefix("0x").padStart(64, '0') .chunked(2).map { it.toUByte(16).toByte() } ) ) val importedContractId = ContractId("imported-${contract.contractAddress}-${PROJECT.chainId.value}") verify("correct response is returned") { expectThat(interfacesResponse) .isEqualTo( ContractDeploymentRequestResponse( id = interfacesResponse.id, alias = alias, name = "Imported Contract", description = "Imported smart contract.", status = Status.SUCCESS, contractId = importedContractId.value, contractDeploymentData = interfacesResponse.contractDeploymentData, constructorParams = objectMapper.valueToTree(constructorParams), contractTags = emptyList(), contractImplements = listOf(interfaceId.value), initialEthAmount = BigInteger.ZERO, chainId = PROJECT.chainId.value, redirectUrl = PROJECT.baseRedirectUrl.value + "/request-deploy/${interfacesResponse.id.value}/action", projectId = PROJECT_ID, createdAt = interfacesResponse.createdAt, arbitraryData = interfacesResponse.arbitraryData, screenConfig = ScreenConfig( beforeActionMessage = "before-action-message", afterActionMessage = "after-action-message" ), contractAddress = ContractAddress(contract.contractAddress).rawValue, deployerAddress = deployerAddress, deployTx = TransactionResponse( txHash = TransactionHash(contract.transactionReceipt.get().transactionHash).value, from = deployerAddress, to = ZeroAddress.rawValue, data = interfacesResponse.deployTx.data, value = BigInteger.ZERO, blockConfirmations = interfacesResponse.deployTx.blockConfirmations, timestamp = interfacesResponse.deployTx.timestamp ), imported = true, proxy = false, implementationContractAddress = null, events = interfacesResponse.events ) ) } } @Test fun mustReturn400BadRequestWhenSettingNonExistentContractInterface() { val mainAccount = accounts[0] val ownerAddress = WalletAddress(HardhatTestContainer.ACCOUNT_ADDRESS_10) val contract = suppose("simple ERC20 contract is deployed") { ExampleContract.deploy( hardhatContainer.web3j, mainAccount, DefaultGasProvider(), ownerAddress.rawValue ).send() } val alias = "alias" val importResponse = suppose("request to import smart contract is made") { val response = mockMvc.perform( MockMvcRequestBuilders.post("/v1/import-smart-contract") .header(CustomHeaders.API_KEY_HEADER, API_KEY) .contentType(MediaType.APPLICATION_JSON) .content( """ { "alias": "$alias", "contract_address": "${contract.contractAddress}", "arbitrary_data": { "test": true }, "screen_config": { "before_action_message": "before-action-message", "after_action_message": "after-action-message" } } """.trimIndent() ) ) .andExpect(MockMvcResultMatchers.status().isOk) .andReturn() objectMapper.readValue(response.response.contentAsString, ContractDeploymentRequestResponse::class.java) } val interfaceId = InterfaceId("non-existent") verify("400 is returned for non-existent smart contract interface") { val response = mockMvc.perform( MockMvcRequestBuilders.patch("/v1/import-smart-contract/${importResponse.id.value}/set-interfaces") .header(CustomHeaders.API_KEY_HEADER, API_KEY) .contentType(MediaType.APPLICATION_JSON) .content( """ { "interfaces": ["${interfaceId.value}"] } """.trimIndent() ) ) .andExpect(MockMvcResultMatchers.status().isBadRequest) .andReturn() expectResponseErrorCode(response, ErrorCode.CONTRACT_INTERFACE_NOT_FOUND) } } @Test fun mustReturn400BadRequestWhenSettingIncompatibleContractInterface() { val mainAccount = accounts[0] val ownerAddress = WalletAddress(HardhatTestContainer.ACCOUNT_ADDRESS_10) val contract = suppose("simple ERC20 contract is deployed") { ExampleContract.deploy( hardhatContainer.web3j, mainAccount, DefaultGasProvider(), ownerAddress.rawValue ).send() } val alias = "alias" val importResponse = suppose("request to import smart contract is made") { val response = mockMvc.perform( MockMvcRequestBuilders.post("/v1/import-smart-contract") .header(CustomHeaders.API_KEY_HEADER, API_KEY) .contentType(MediaType.APPLICATION_JSON) .content( """ { "alias": "$alias", "contract_address": "${contract.contractAddress}", "arbitrary_data": { "test": true }, "screen_config": { "before_action_message": "before-action-message", "after_action_message": "after-action-message" } } """.trimIndent() ) ) .andExpect(MockMvcResultMatchers.status().isOk) .andReturn() objectMapper.readValue(response.response.contentAsString, ContractDeploymentRequestResponse::class.java) } val interfaceId = InterfaceId("example.incompatible") suppose("some incompatible contract interface is in the repository") { contractInterfacesRepository.store(interfaceId, INCOMPATIBLE_INTERFACE) } verify("400 is returned for incompatible smart contract interface") { val response = mockMvc.perform( MockMvcRequestBuilders.patch("/v1/import-smart-contract/${importResponse.id.value}/set-interfaces") .header(CustomHeaders.API_KEY_HEADER, API_KEY) .contentType(MediaType.APPLICATION_JSON) .content( """ { "interfaces": ["${interfaceId.value}"] } """.trimIndent() ) ) .andExpect(MockMvcResultMatchers.status().isBadRequest) .andReturn() expectResponseErrorCode(response, ErrorCode.CONTRACT_DECORATOR_INCOMPATIBLE) } } }
0
Kotlin
0
0
d9aa8802cf140e0cdd3b701fa2a9c30764b4ad5f
94,855
blockchain-api-service
MIT License
shared/component/root/src/commonMain/kotlin/com/sedsoftware/tackle/root/integration/editor/EditorTabComponentSettings.kt
djkovrik
769,140,107
false
{"Kotlin": 795413, "Swift": 995}
package com.sedsoftware.tackle.root.integration.editor import com.sedsoftware.tackle.domain.api.TackleSettings import com.sedsoftware.tackle.editor.EditorComponentGateways internal class EditorTabComponentSettings( private val settings: TackleSettings, ) : EditorComponentGateways.Settings { override val ownAvatar: String get() = settings.ownAvatar override val ownNickname: String get() = settings.ownUsername override val domainShort: String get() = settings.domainShort override var emojiLastCachedTimestamp: String get() = settings.emojiLastCachedTimestamp set(value) { settings.emojiLastCachedTimestamp = value } override var lastSelectedLanguageName: String get() = settings.lastSelectedLanguageName set(value) { settings.lastSelectedLanguageName = value } override var lastSelectedLanguageCode: String get() = settings.lastSelectedLanguageCode set(value) { settings.lastSelectedLanguageCode = value } }
15
Kotlin
0
1
96e8f88b5b3e7e0ae3a55c8466ff9d7cdd5614b2
1,080
Tackle
MIT License
finch-kotlin-core/src/main/kotlin/com/tryfinch/api/services/async/RequestForwardingServiceAsync.kt
Finch-API
688,609,420
false
{"Kotlin": 918955, "Shell": 1245}
// File generated from our OpenAPI spec by Stainless. @file:Suppress("OVERLOADS_INTERFACE") // See https://youtrack.jetbrains.com/issue/KT-36102 package com.tryfinch.api.services.async import com.tryfinch.api.core.RequestOptions import com.tryfinch.api.models.RequestForwardingForwardParams import com.tryfinch.api.models.RequestForwardingForwardResponse interface RequestForwardingServiceAsync { /** The Forward API allows you to make direct requests to an employment system. */ suspend fun forward( params: RequestForwardingForwardParams, requestOptions: RequestOptions = RequestOptions.none() ): RequestForwardingForwardResponse }
0
Kotlin
0
0
94f6f214e37efddd74056b142f3cec0967f21e91
667
finch-api-kotlin
Apache License 2.0
zowe-cli/src/jsMain/kotlin/zowe/cli/zosfiles/strings/Temp103.kt
lppedd
761,812,661
false
{"Kotlin": 1887051}
package zowe.cli.zosfiles.strings external interface Temp103 { var DESCRIPTION: String var POSITIONALS: Temp104 var OPTIONS: Temp105 var EXAMPLES: Temp106 }
0
Kotlin
0
3
0f493d3051afa3de2016e5425a708c7a9ed6699a
166
kotlin-externals
MIT License
app/src/main/java/co/joshwel/uji/store/UjiStateSerializer.kt
markjoshwel
802,910,619
false
{"Kotlin": 36955}
package co.joshwel.uji.store import android.content.Context import androidx.datastore.core.CorruptionException import androidx.datastore.core.DataStore import androidx.datastore.core.Serializer import androidx.datastore.dataStore import androidx.datastore.preferences.protobuf.InvalidProtocolBufferException import java.io.InputStream import java.io.OutputStream object UjiStateSerializer : Serializer<UjiState> { override val defaultValue: UjiState = UjiState.getDefaultInstance() override suspend fun readFrom(input: InputStream): UjiState { try { return UjiState.parseFrom(input) } catch (exception: InvalidProtocolBufferException) { throw CorruptionException("Cannot read proto.", exception) } } override suspend fun writeTo(t: UjiState, output: OutputStream) = t.writeTo(output) } val Context.dataStore: DataStore<UjiState> by dataStore( fileName = "uji_state.pb", serializer = UjiStateSerializer )
0
Kotlin
0
0
0daf29f5c9cb8e8f2c79c6811808d721fa231d84
978
uji
The Unlicense
app/src/main/java/com/zipdabang/zipdabang_android/module/comment/data/remote/RecipeComment.kt
zipdabang
666,457,004
false
{"Kotlin": 1689597}
package com.zipdabang.zipdabang_android.module.comment.data.remote import kotlinx.serialization.Serializable @Serializable data class RecipeComment( val content: String, val createdAt: String, val isOwner: Boolean, val ownerImage: String, val ownerNickname: String, val commentId: Int, val ownerId: Int, val updatedAt: String )
6
Kotlin
1
2
64ee7ffe6a6d3ee12c3e2a93a598465e65ac583d
361
android
The Unlicense
app/src/main/java/com/apaluk/wsplayer/ui/search/SearchViewModel.kt
apaluk
576,009,487
false
null
package com.apaluk.wsplayer.ui.search import androidx.lifecycle.ViewModel import androidx.lifecycle.viewModelScope import com.apaluk.wsplayer.data.stream_cinema.StreamCinemaRepository import com.apaluk.wsplayer.domain.model.media.SearchResultItem import com.apaluk.wsplayer.ui.common.util.UiState import com.apaluk.wsplayer.ui.common.util.toUiState import dagger.hilt.android.lifecycle.HiltViewModel import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.asStateFlow import kotlinx.coroutines.flow.last import kotlinx.coroutines.flow.update import kotlinx.coroutines.launch import javax.inject.Inject @HiltViewModel class SearchViewModel @Inject constructor( private val streamCinemaRepository: StreamCinemaRepository ) : ViewModel() { private val _uiState = MutableStateFlow(SearchUiState()) val uiState = _uiState.asStateFlow() fun onSearchScreenAction(action: SearchScreenAction) { when(action) { is SearchScreenAction.SearchTextChanged -> onSearchTextChanged(action.text) is SearchScreenAction.MediaSelected -> if(action.mediaId == null) clearSelectedMedia() else onMediaSelected(action.mediaId) SearchScreenAction.TriggerSearch -> triggerSearch() SearchScreenAction.ClearSearch -> clearSearch() } } private fun onMediaSelected(mediaId: String) { _uiState.update { it.copy(selectedMediaId = mediaId) } } private fun clearSelectedMedia() { _uiState.update { it.copy(selectedMediaId = null) } } private fun onSearchTextChanged(text: String) { _uiState.update { it.copy(searchText = text) } } private fun triggerSearch() { viewModelScope.launch { _uiState.update { it.copy(searchState = UiState.Loading, scrollListToTop = true) } val searchResource = streamCinemaRepository.search(_uiState.value.searchText.trim()).last() _uiState.update { it.copy( searchResults = searchResource.data.orEmpty(), searchState = searchResource.toUiState(), scrollListToTop = false ) } } } private fun clearSearch() { _uiState.update { it.copy(searchText = "", searchResults = emptyList()) } } } data class SearchUiState( val selectedMediaId: String? = null, val searchText: String = "", val errorToast: String? = null, val searchResults: List<SearchResultItem> = emptyList(), val searchState: UiState = UiState.Idle, val scrollListToTop: Boolean = false ) sealed class SearchScreenAction { data class SearchTextChanged(val text: String): SearchScreenAction() object TriggerSearch: SearchScreenAction() object ClearSearch: SearchScreenAction() data class MediaSelected(val mediaId: String?): SearchScreenAction() }
0
Kotlin
0
0
42a06541f2860112cbe73cd94ebc90e0072017a9
2,855
ws-player-android
MIT License
app/src/main/kotlin/com/pnuema/bible/android/database/VerseCountOffline.kt
barnhill
98,140,541
false
null
package com.pnuema.bible.android.database import androidx.room.Entity import com.pnuema.bible.android.data.firefly.VerseCountDomain @Entity(tableName = "offlineVerseCount", primaryKeys = ["book_id", "chapter", "version"]) data class VerseCountOffline ( val book_id: Int, val chapter: Int, val version: String, val verseCount: Int = 0 ) { fun convertToVerseCount(): VerseCountDomain = VerseCountDomain(verseCount) }
1
null
4
18
2ec6e0113ba6d8cb97ee63b4f5a26834e441314c
438
Bible
Apache License 2.0
src/main/kotlin/no/nav/tilleggsstonader/kontrakter/dokarkiv/Dokument.kt
navikt
691,013,075
false
{"Kotlin": 90741}
package no.nav.tilleggsstonader.kontrakter.dokarkiv class Dokument( val dokument: ByteArray, val filtype: Filtype, val filnavn: String? = null, val tittel: String? = null, val dokumenttype: Dokumenttype, ) enum class Filtype { PDFA, JSON, }
2
Kotlin
0
0
7812164fb0d8e7ed01cadc3b4ee9439062fdf5f8
271
tilleggsstonader-kontrakter
MIT License
src/main/kotlin/http/HttpRequest.kt
ArjixWasTaken
833,220,452
false
{"Kotlin": 28545}
package com.arjix.http import java.net.URI import java.util.* import kotlin.jvm.optionals.getOrNull data class HttpRequest( val method: HttpVerb, val uri: URI, val headers: HttpHeaders ) { companion object { fun read(stream: Scanner): Optional<Result<HttpRequest>> { val lines = mutableListOf<String>() do { val line = stream.nextLine() if (line.trim().isEmpty()) break lines.add(line) } while (true); if (lines.isEmpty()) return Optional.empty() val statusLine = lines.removeFirst() val (verb, uri, version) = statusLine.split(" ") if (version != "HTTP/1.1") return Optional.of(Result.failure(HttpVersionNotSupported())) val method = HttpVerb.parse(verb).getOrNull() ?: return Optional.of(Result.failure(InvalidHttpMethod(verb))) val headers = HttpHeaders.parseLines(lines) return Optional.of(Result.success( HttpRequest( method=method, uri=URI.create(uri), headers=headers ) )) } } }
0
Kotlin
0
1
6d6fdfe2f4e2747d5db566da0cd6a02c5f2193b3
1,251
low-level-backend
MIT License
app/src/main/java/com/noto/app/label/LabelChooserDialogFrgament.kt
androiddevnotesforks
346,802,081
true
{"Kotlin": 138791}
package com.noto.app.label //import android.content.res.ColorStateList //import android.os.Bundle //import android.view.LayoutInflater //import android.view.View //import android.view.ViewGroup //import android.view.animation.AlphaAnimation //import android.view.animation.ScaleAnimation //import androidx.core.content.res.ResourcesCompat //import com.google.android.material.chip.Chip //import com.noto.app.BaseDialogFragment //import com.noto.app.R //import com.noto.app.databinding.LabelChooserDialogFragmentBinding //import com.noto.app.note.NoteViewModel //import com.noto.app.util.dp //import com.noto.app.util.toResource //import org.koin.androidx.viewmodel.ext.android.sharedViewModel // //class LabelChooserDialogFragment : BaseDialogFragment() { // // private lateinit var binding: LabelChooserDialogFragmentBinding // // private val notoViewModel by sharedViewModel<NoteViewModel>() // // private val labelViewModel by sharedViewModel<LabelViewModel>() // // override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? { // // binding = LabelChooserDialogFragmentBinding.inflate(inflater, container, false) // // val textColor = ResourcesCompat.getColor(resources, R.color.colorBackground, null) // // labelViewModel.labels.observe(viewLifecycleOwner) { labels -> // // binding.cg.removeAllViews() // // labels.forEach { label -> // // val labelColor = label.labelColor.toResource() // // val resourceLabelColor = ResourcesCompat.getColor(resources, labelColor, null) // // val chip = Chip(requireContext()).apply { // // setChipBackgroundColorResource(R.color.colorBackground) // setTextColor(resourceLabelColor) // chipStrokeColor = ColorStateList.valueOf(resourceLabelColor) // chipStrokeWidth = 5F // textSize = 16F // text = label.labelTitle // isCheckable = true // isChecked = notoViewModel.labels.value?.contains(label) ?: false // isCheckedIconVisible = false // chipEndPadding = 8.dp(requireContext()) // chipStartPadding = 8.dp(requireContext()) // chipMinHeight = 42.dp(requireContext()) // typeface = ResourcesCompat.getFont(requireContext(), R.font.arima_madurai_medium) // // setOnCheckedChangeListener { _, isChecked -> // // if (isChecked) { // setChipBackgroundColorResource(labelColor) // setTextColor(textColor) // chipStrokeColor = null // notoViewModel.labels.value?.add(label) // } else { // setChipBackgroundColorResource(R.color.colorBackground) // setTextColor(resourceLabelColor) // chipStrokeColor = ColorStateList.valueOf(resourceLabelColor) // notoViewModel.labels.value?.remove(label) // notoViewModel.labels.value.also { println(it.toString()) } // } // // notoViewModel.notifyLabelsObserver() // // val animation = AlphaAnimation(0.25f, 1f).apply { duration = 250 } // // startAnimation(animation) // // } // // } // // binding.cg.addView(chip) // } // } // // // val scaleAnimation = ScaleAnimation(0.95f, 1.0f, 0.95f, 1.0f).apply { // duration = 250 // } // // return binding.root // } // // val list = mutableListOf<Label>() // //// val labels = viewModel.labels // // val notoLabels = viewModel.notoLabels.value!! // Timber.i(notoLabels.toString()) // // if (labels.isEmpty()) { // binding.svCg.visibility = View.GONE // binding.cg.visibility = View.GONE // binding.tvLabel.visibility = View.GONE // binding.btnDone.visibility = View.GONE // binding.tvPlaceHolder.visibility = View.VISIBLE // binding.ivPlaceHolder.visibility = View.VISIBLE // } else { // // for (label in labels) { // // val chip = Chip(context).also { chip -> // // chip.isChecked = notoLabels.any { it.labelId == label.labelId } // // chip.id = label.labelId.toInt() //// chip.chipBackgroundColor = ColorStateList.valueOf(context.resources.getColor(label.notoColor.getValue())) // chip.text = label.labelTitle // chip.setTextColor(context.resources.getColor(R.color.colorPrimary)) // chip.gravity = Gravity.CENTER // chip.isCheckable = true // // chip.setOnCheckedChangeListener { _, isChecked -> // if (isChecked) { // list.add(label) // } else { // list.remove(label) // } // } // } // binding.cg.addView(chip) // } // binding.btnDone.setOnClickListener { // viewModel._notoLabels.postValue(list) // dismiss() // } // } //}
0
Kotlin
0
2
12a7068345e5f18a5e3e5c02839d3dd0d77d46ca
5,573
Noto
Apache License 2.0
shared/src/main/java/de/loosetie/k8s/dsl/impls/DaemonSetUpdateStrategy.kt
loosetie
283,145,621
false
{"Kotlin": 12443871}
package de.loosetie.k8s.dsl.impls import com.fasterxml.jackson.annotation.JsonIgnore import com.fasterxml.jackson.annotation.JsonPropertyOrder import de.loosetie.k8s.dsl.K8sManifest import de.loosetie.k8s.dsl.HasParent import de.loosetie.k8s.dsl.manifests.* @JsonPropertyOrder("rollingUpdate", "type") class DaemonSetUpdateStrategy_apps_v1_k8s1_16Impl( @JsonIgnore override val parent: K8sManifest? = null ) : DaemonSetUpdateStrategy_apps_v1_k8s1_16, HasParent { override var rollingUpdate: Rollingupdatedaemonset_apps_v1_k8s1_16? = null override var type: String? = null } typealias DaemonSetUpdateStrategy_apps_v1_k8s1_17Impl = DaemonSetUpdateStrategy_apps_v1_k8s1_16Impl typealias DaemonSetUpdateStrategy_apps_v1_k8s1_18Impl = DaemonSetUpdateStrategy_apps_v1_k8s1_17Impl typealias DaemonSetUpdateStrategy_apps_v1_k8s1_19Impl = DaemonSetUpdateStrategy_apps_v1_k8s1_18Impl typealias DaemonSetUpdateStrategy_apps_v1_k8s1_20Impl = DaemonSetUpdateStrategy_apps_v1_k8s1_19Impl typealias DaemonSetUpdateStrategy_apps_v1_k8s1_21Impl = DaemonSetUpdateStrategy_apps_v1_k8s1_20Impl
0
Kotlin
0
1
3dd2d00220dbf71151d56b75b3bd7f26583b1fd3
1,083
k8s-dsl
Apache License 2.0
app/src/main/java/com/example/trendyol_internship/data/listing/model/Game.kt
utkukalkanli
508,192,157
false
{"Kotlin": 33331}
package com.example.trendyol_internship.data.listing.model // release date // genres - list // playtime // publishers // reddit url // website url class Game( val id: Int?, val name: String?, val background_image: String? )
2
Kotlin
0
0
2c9e1ad46b05ed24544767fda74c85877ce6f1f1
247
games-list
Apache License 2.0
app/src/main/java/com/example/trendyol_internship/data/listing/model/Game.kt
utkukalkanli
508,192,157
false
{"Kotlin": 33331}
package com.example.trendyol_internship.data.listing.model // release date // genres - list // playtime // publishers // reddit url // website url class Game( val id: Int?, val name: String?, val background_image: String? )
2
Kotlin
0
0
2c9e1ad46b05ed24544767fda74c85877ce6f1f1
247
games-list
Apache License 2.0
examples/versioning-multimodule-example/dokka/parentProject/childProjectB/src/main/kotlin/demo/Functions.kt
adamko-dev
598,382,061
false
{"Kotlin": 421737, "Java": 1388, "CSS": 720}
package demo /** * New super function that does everything * * @since 1.0 */ fun superFunction42() {}
24
Kotlin
7
72
972dbb4aee371e60be6c10d42ca4757ed65c4651
107
dokkatoo
Apache License 2.0
examples/versioning-multimodule-example/dokka/parentProject/childProjectB/src/main/kotlin/demo/Functions.kt
adamko-dev
598,382,061
false
{"Kotlin": 421737, "Java": 1388, "CSS": 720}
package demo /** * New super function that does everything * * @since 1.0 */ fun superFunction42() {}
24
Kotlin
7
72
972dbb4aee371e60be6c10d42ca4757ed65c4651
107
dokkatoo
Apache License 2.0
app/src/main/java/com/hami/sports_assist/data/SoccerStatRepository.kt
hongwei-bai
345,632,970
false
null
package com.hami.sports_assist.data import com.hami.sports_assist.AppConfigurations import com.hami.sports_assist.data.local.AppSettings import com.hami.sports_assist.data.mapper.SoccerTeamScheduleMapper.map import com.hami.sports_assist.data.network.service.SoccerStatService import com.hami.sports_assist.data.room.soccer.SoccerTeamEvent import com.hami.sports_assist.data.room.soccer.SoccerTeamScheduleDao import com.hami.sports_assist.data.util.DataValidationUtil import com.hami.sports_assist.data.util.DataValidationUtil.dataMayOutdated import com.hami.sports_assist.ui.component.DataStatus import com.hami.sports_assist.util.LocalDateTimeUtil import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.channels.Channel import kotlinx.coroutines.flow.* import kotlinx.coroutines.withContext import javax.inject.Inject class SoccerStatRepository @Inject constructor( private val soccerStatService: SoccerStatService, private val soccerTeamScheduleDao: SoccerTeamScheduleDao ) { private val dataStatusChannel = Channel<DataStatus>() val dataStatus: Flow<DataStatus> = dataStatusChannel.receiveAsFlow() fun getNextGameInfo(team: String): Flow<SoccerTeamEvent> { return soccerTeamScheduleDao.getSoccerTeamSchedule().onEach { it ?: fetchSoccerTeamScheduleFromBackend(team) }.filterNotNull().map { it.events.firstOrNull { event -> DataValidationUtil.after(event.unixTimeStamp) } }.filterNotNull() } fun getTeamSchedule(team: String): Flow<List<SoccerTeamEvent>> { return soccerTeamScheduleDao.getSoccerTeamSchedule().onEach { when { it == null -> fetchSoccerTeamScheduleFromBackend(team) dataMayOutdated(it.timeStamp) -> { dataStatusChannel.send(DataStatus.DataMayOutdated) fetchSoccerTeamScheduleFromBackend(team, it.dataVersion) } } }.filterNotNull().map { it.events.filter { eventTime -> eventTime.unixTimeStamp > LocalDateTimeUtil.getFirstDayOfWeek(AppSettings.weekStartsFromMonday).timeInMillis } } } suspend fun fetchSoccerTeamScheduleFromBackend(team: String, dataVersion: Long? = null) { withContext(Dispatchers.IO) { val response = soccerStatService.getTeamSchedule(team, dataVersion ?: -1) val data = response.body() when (response.code()) { AppConfigurations.Network.HttpCode.HTTP_OK -> data?.let { soccerTeamScheduleDao.save(data.map()) } AppConfigurations.Network.HttpCode.HTTP_DATA_UP_TO_DATE -> { dataStatusChannel.send(DataStatus.DataIsUpToDate) soccerTeamScheduleDao.update(System.currentTimeMillis()) } else -> dataStatusChannel.send(DataStatus.ServiceError("Fetch soccer schedules data error, code: ${response.code()}")) } } } }
2
Kotlin
6
36
1189147834569489acbc36137495840125a0a5bd
3,018
android-nba-assist
Apache License 2.0
sample/src/main/kotlin/com/sugoiwada/sample/model/github/GitHubLinkHeader.kt
sugoi-wada
74,024,467
false
null
package com.sugoiwada.sample.model.github import android.net.Uri class GitHubLinkHeader(val first: Element?, val last: Element?, val next: Element?, val prev: Element?) { companion object { fun parse(string: String): GitHubLinkHeader? { val elements = string.split(",").map { Element.parse(it) } val first = elements.find { it?.rel == "first" } val last = elements.find { it?.rel == "last" } val next = elements.find { it?.rel == "next" } val prev = elements.find { it?.rel == "prev" } if (first == null && last == null && next == null && prev == null) { return null } return GitHubLinkHeader(first, last, next, prev) } } } class Element(val rel: String, val uri: String, val page: Int) { companion object { fun parse(string: String): Element? { val attr = string.split("; ") if (attr.count() != 2) { return null } fun trimString(string: String): String? { if (string.count() < 3) { return null } return string.drop(1).dropLast(1) } fun value(field: String): String? { val pair = field.split("=") if (pair.count() != 2) { return null } return pair.last().drop(1).dropLast(1) } fun parseInt(string: String): Int? { try { return string.toInt() } catch (e: NumberFormatException) { return null } } val uri = trimString(attr.first()) ?: return null val rel = value(attr.last()) ?: return null val page = parseInt(Uri.parse(uri).getQueryParameter("page")) ?: return null return Element(rel, uri, page) } } }
0
Kotlin
0
0
a5b14c7a24d27a313ee7775290eb5e048e5dad2c
1,987
flux-kotlin-android-sample
Apache License 2.0
app/src/main/java/com/example/droidconnyc22/view/PagingScrollListener.kt
orelzion
532,084,832
false
null
package com.example.droidconnyc22.view import androidx.recyclerview.widget.LinearLayoutManager import androidx.recyclerview.widget.RecyclerView abstract class PagingScrollListener(private val layoutManager: RecyclerView.LayoutManager?) : RecyclerView.OnScrollListener() { override fun onScrolled(recyclerView: RecyclerView, dx: Int, dy: Int) { super.onScrolled(recyclerView, dx, dy) if (layoutManager !is LinearLayoutManager) return val visibleItemCount = layoutManager.childCount val totalItemCount = layoutManager.itemCount val firstVisibleItemPosition = layoutManager.findFirstVisibleItemPosition() if (!isLoading) { if (visibleItemCount + firstVisibleItemPosition >= totalItemCount && firstVisibleItemPosition >= 0 ) { loadMoreItems() } } } protected abstract fun loadMoreItems() abstract val isLoading: Boolean }
0
Kotlin
0
0
d075cbcafa4c07230d39dac13fd14ed77caf0145
968
paging3-droidconnyc-22
MIT License
library/src/main/java/com/wss/library/ScaleSeekBar.kt
song234876
203,341,522
false
null
package com.wss.library import android.annotation.SuppressLint import android.content.Context import android.graphics.* import android.graphics.drawable.BitmapDrawable import android.graphics.drawable.Drawable import android.os.Build import android.util.AttributeSet import android.view.MotionEvent import android.view.View import androidx.annotation.DrawableRes import com.wss.library.utils.SizeUtils /** * ******************************* * 猿代码: Wss * Email: <EMAIL> * 时间轴:2019-06-25 17:44 * ******************************* * * 描述: * */ class ScaleSeekBar : View { /** 进度条画笔*/ private var mProgressPaint = Paint() /** 进度条画笔颜色*/ private var mProgressColor = 0 /** 线条画笔*/ private var mLinePaint = Paint() /** 线条画笔颜色*/ private var mLineColor = 0 /** 刻度值画笔*/ private var mTextPaint = Paint() /** 刻度值画笔颜色*/ private var mTextColor = 0 /** 默认间距*/ private var DEFALT_PADDING: Int = SizeUtils.dp2px(10f) /** 坐标左边点*/ private var lineLeft = 0f /** 坐标上边点*/ private var lineTop = 0f /** 坐标右边点*/ private var lineRight = 0f /** 坐标下边点*/ private var lineBottom = 0f /** 坐标线宽高度*/ private var lineWidth = 2f /** 坐标圆角值*/ private var lineCorners = 0f /** 刻度值间距*/ private var scaleDistance = 0f /** 大刻度高度*/ private var bigScaleHeight = SizeUtils.dp2px(10f) /** 小刻度高度*/ private var smallScaleHeight = SizeUtils.dp2px(6f) /** 刻度左边点*/ private var bigScaleLeft = 0f /** 刻度上边点*/ private var bigScaleTop = 0f /** 刻度右边点*/ private var bigScaleRight = 0f /** 刻度下边点*/ private var bigScaleBottom = 0f /** 大刻度圆角*/ private var bigScaleCorners = 0f /** 最大刻度值*/ private var maxScaleValue = 50f /** 最小刻度值*/ private var minScaleValue = 0f /** 每个刻度代表单位值*/ private var eachScaleValue = 1f /** 大小刻度换算权重*/ private var unitWeight = 10 /** 单位名称*/ private var unitName = "" /** 单位值高度*/ private var unitAreaHeight = SizeUtils.dp2px(18f) /** 单位值高度*/ private var centerDistance = SizeUtils.dp2px(12f) /** 指示器宽度*/ private var thumbWidth: Int = SizeUtils.dp2px(20f) /** 指示器高度*/ private var thumbHeight: Int = SizeUtils.dp2px(20f) private var thumbDrawableId: Int = R.drawable.rsb_default_thumb private var thumbBitmap: Bitmap? = null private var currPercent: Float = 0f private var firstScaleValue = 20f private var progressWidth = 0f private var viewHeight: Int = 0 private var viewWidth: Int = 0 private var touchDownX: Float = 0f private var mListener: OnSeekChangeListener? = null private var limitMinValue = 10f private var limitMinPercent = 0f private var limitMaxValue = maxScaleValue private var limitMaxPercent = 1f constructor(context: Context?) : this(context = context, attrs = null) constructor(context: Context?, attrs: AttributeSet?) : this( context = context, attrs = attrs, defStyleAttr = 0 ) constructor(context: Context?, attrs: AttributeSet?, defStyleAttr: Int) : super(context, attrs, defStyleAttr) { initAttrs(attrs) initPaint() } private fun initAttrs(attrs: AttributeSet?) { val array = context!!.obtainStyledAttributes(attrs, R.styleable.ScaleSeekBar) mTextColor = array.getColor(R.styleable.ScaleSeekBar_scaleTextColor, Color.parseColor("#A8A8A8")) mProgressColor = array.getColor(R.styleable.ScaleSeekBar_scaleFgColor, Color.parseColor("#FFFFFF")) mLineColor = array.getColor(R.styleable.ScaleSeekBar_scaleBgColor, Color.parseColor("#61615F")) DEFALT_PADDING = array.getDimensionPixelSize(R.styleable.ScaleSeekBar_defaultPadding, SizeUtils.dp2px(10f)) bigScaleHeight = array.getDimensionPixelSize(R.styleable.ScaleSeekBar_bigScaleHeight, SizeUtils.dp2px(10f)) smallScaleHeight = array.getDimensionPixelSize(R.styleable.ScaleSeekBar_smallScaleHeight, SizeUtils.dp2px(6f)) unitAreaHeight = array.getDimensionPixelSize(R.styleable.ScaleSeekBar_unitAreaHeight, SizeUtils.dp2px(18f)) centerDistance = array.getDimensionPixelSize(R.styleable.ScaleSeekBar_centerDistance, SizeUtils.dp2px(12f)) thumbWidth = array.getDimensionPixelSize(R.styleable.ScaleSeekBar_thumbWidth, SizeUtils.dp2px(20f)) thumbHeight = array.getDimensionPixelSize(R.styleable.ScaleSeekBar_thumbHeight, SizeUtils.dp2px(20f)) eachScaleValue = array.getFloat(R.styleable.ScaleSeekBar_eachScaleValue,1f) maxScaleValue = array.getFloat(R.styleable.ScaleSeekBar_maxScaleValue,50f) minScaleValue = array.getFloat(R.styleable.ScaleSeekBar_minScaleValue,0f) limitMinValue = array.getFloat(R.styleable.ScaleSeekBar_limitMinValue,0f) limitMaxValue = array.getFloat(R.styleable.ScaleSeekBar_limitMaxValue,maxScaleValue) firstScaleValue = array.getFloat(R.styleable.ScaleSeekBar_firstScaleValue,0f) unitWeight = array.getInt(R.styleable.ScaleSeekBar_unitWeight,10) unitName = if (array.getString(R.styleable.ScaleSeekBar_unitName) == null) "" else array.getString(R.styleable.ScaleSeekBar_unitName)!! array.recycle() limitMinPercent = limitMinValue / maxScaleValue limitMaxPercent = limitMaxValue / maxScaleValue currPercent = firstScaleValue / maxScaleValue setThumbDrawableId(thumbDrawableId, thumbWidth, thumbHeight) } private fun initPaint() { mProgressPaint.isAntiAlias = true mProgressPaint.color = mProgressColor mProgressPaint.style = Paint.Style.FILL mProgressPaint.strokeWidth = lineWidth mProgressPaint.strokeCap = Paint.Cap.ROUND mLinePaint.isAntiAlias = true mLinePaint.color = mLineColor mLinePaint.style = Paint.Style.FILL mLinePaint.strokeWidth = lineWidth mLinePaint.strokeCap = Paint.Cap.ROUND mTextPaint.isAntiAlias = true mTextPaint.textSize = 32f mTextPaint.color = mTextColor mTextPaint.textAlign = Paint.Align.CENTER } override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) { super.onMeasure(widthMeasureSpec, heightMeasureSpec) val heightModule = MeasureSpec.getMode(heightMeasureSpec) val heightSize = MeasureSpec.getSize(heightMeasureSpec) val widthSize = MeasureSpec.getSize(widthMeasureSpec) when (heightModule) { MeasureSpec.AT_MOST, MeasureSpec.UNSPECIFIED -> { viewHeight = (2 * DEFALT_PADDING + unitAreaHeight + thumbHeight + centerDistance + paddingTop + paddingBottom).toInt() } MeasureSpec.EXACTLY -> { viewHeight = heightSize + paddingTop + paddingBottom } } viewWidth = (widthSize + paddingLeft + paddingRight + 4 * DEFALT_PADDING).toInt() setMeasuredDimension(viewWidth, viewHeight) } override fun onDraw(canvas: Canvas) { super.onDraw(canvas) drawXLine(canvas) } /** * 画X轴 */ private fun drawXLine(canvas: Canvas) { lineLeft = (2 * DEFALT_PADDING).toFloat() lineRight = (width - 2 * DEFALT_PADDING).toFloat() progressWidth = lineRight - lineLeft lineTop = DEFALT_PADDING + unitAreaHeight + centerDistance + thumbHeight / 2f - lineWidth / 2f lineBottom = lineTop + lineWidth lineCorners = (lineBottom - lineTop) * 0.45f canvas.drawRoundRect(lineLeft, lineTop, lineRight, lineBottom, lineCorners, lineCorners, mLinePaint) scaleDistance = (width - 4f * DEFALT_PADDING) / (maxScaleValue / eachScaleValue) var totalScaleNum = (maxScaleValue / eachScaleValue).toInt() var currScaleNum = (maxScaleValue * currPercent / eachScaleValue).toInt() for (item in 0..totalScaleNum) { if ((minScaleValue + item * eachScaleValue) % (unitWeight * eachScaleValue) == 0f) { bigScaleLeft = lineLeft + item * scaleDistance bigScaleRight = bigScaleLeft + lineWidth bigScaleTop = DEFALT_PADDING + unitAreaHeight + centerDistance + thumbHeight / 2f - bigScaleHeight / 2f bigScaleBottom = bigScaleTop + bigScaleHeight bigScaleCorners = (bigScaleBottom - bigScaleTop) * 0.45f val fm = mTextPaint.fontMetricsInt val baseLineY = DEFALT_PADDING + unitAreaHeight - (fm.bottom + fm.top) / 2f val baseLineX = bigScaleLeft canvas.drawText( "${(minScaleValue + item * eachScaleValue).toInt()}$unitName", baseLineX, baseLineY, mTextPaint ) canvas.drawRoundRect( bigScaleLeft, bigScaleTop, bigScaleRight, bigScaleBottom, bigScaleCorners, bigScaleCorners, mLinePaint ) } else { bigScaleLeft = lineLeft + item * scaleDistance bigScaleRight = bigScaleLeft + lineWidth bigScaleTop = DEFALT_PADDING + unitAreaHeight + centerDistance + thumbHeight / 2f - smallScaleHeight / 2f bigScaleBottom = bigScaleTop + smallScaleHeight bigScaleCorners = (bigScaleBottom - bigScaleTop) * 0.45f canvas.drawRoundRect( bigScaleLeft, bigScaleTop, bigScaleRight, bigScaleBottom, bigScaleCorners, bigScaleCorners, mLinePaint ) } } canvas.drawRoundRect( lineLeft, lineTop, lineLeft + progressWidth * currPercent, lineBottom, lineCorners, lineCorners, mProgressPaint ) for (item in 0..currScaleNum) { if ((minScaleValue + item * eachScaleValue) % (unitWeight * eachScaleValue) == 0f) { bigScaleLeft = lineLeft + item * scaleDistance bigScaleRight = bigScaleLeft + lineWidth bigScaleTop = DEFALT_PADDING + unitAreaHeight + centerDistance + thumbHeight / 2f - bigScaleHeight / 2f bigScaleBottom = bigScaleTop + bigScaleHeight bigScaleCorners = (bigScaleBottom - bigScaleTop) * 0.45f canvas.drawRoundRect( bigScaleLeft, bigScaleTop, bigScaleRight, bigScaleBottom, bigScaleCorners, bigScaleCorners, mProgressPaint ) } else { bigScaleLeft = lineLeft + item * scaleDistance bigScaleRight = bigScaleLeft + lineWidth bigScaleTop = DEFALT_PADDING + unitAreaHeight + centerDistance + thumbHeight / 2f - smallScaleHeight / 2f bigScaleBottom = bigScaleTop + smallScaleHeight bigScaleCorners = (bigScaleBottom - bigScaleTop) * 0.45f canvas.drawRoundRect( bigScaleLeft, bigScaleTop, bigScaleRight, bigScaleBottom, bigScaleCorners, bigScaleCorners, mProgressPaint ) } } canvas.save() canvas.translate(progressWidth * currPercent + 2 * DEFALT_PADDING - thumbWidth / 2f, 0f) canvas.drawBitmap(thumbBitmap!!, 0f, DEFALT_PADDING + unitAreaHeight + centerDistance.toFloat(), null) canvas.restore() } override fun onTouchEvent(event: MotionEvent): Boolean { when (event.action) { MotionEvent.ACTION_DOWN -> { touchDownX = event.x return true } MotionEvent.ACTION_MOVE -> { touchDownX = event.x currPercent = (touchDownX - DEFALT_PADDING * 2) / progressWidth if (touchDownX < (DEFALT_PADDING * 2 + limitMinPercent * progressWidth)) { currPercent = limitMinPercent } if (touchDownX > limitMaxPercent * progressWidth + DEFALT_PADDING * 2) { currPercent = limitMaxPercent } mListener?.onSeek(Math.round(maxScaleValue * currPercent * 10) / 10f) invalidate() } MotionEvent.ACTION_UP -> { mListener?.OnSeekEnd(Math.round(maxScaleValue * currPercent * 10) / 10f) } } return super.onTouchEvent(event) } interface OnSeekChangeListener { fun onSeek(progress: Float) fun OnSeekEnd(progress: Float) } @SuppressLint("ObsoleteSdkInt") fun setThumbDrawableId(@DrawableRes thumbDrawableId: Int, width: Int, height: Int) { if (thumbDrawableId != 0 && resources != null && width > 0 && height > 0) { this.thumbDrawableId = thumbDrawableId if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { thumbBitmap = drawableToBitmap(width, height, resources!!.getDrawable(thumbDrawableId, null)) } else { thumbBitmap = drawableToBitmap(width, height, resources!!.getDrawable(thumbDrawableId)) } } } fun setOnSeekChangeListener(listener: OnSeekChangeListener) { this.mListener = listener } fun drawableToBitmap(width: Int, height: Int, drawable: Drawable): Bitmap? { var bitmap: Bitmap? = null try { if (drawable is BitmapDrawable) { bitmap = drawable.bitmap if (bitmap != null && bitmap.height > 0) { val matrix = Matrix() val scaleWidth = width * 1.0f / bitmap.width val scaleHeight = height * 1.0f / bitmap.height matrix.postScale(scaleWidth, scaleHeight) bitmap = Bitmap.createBitmap(bitmap, 0, 0, bitmap.width, bitmap.height, matrix, true) return bitmap } } bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888) val canvas = Canvas(bitmap!!) drawable.setBounds(0, 0, canvas.width, canvas.height) drawable.draw(canvas) } catch (e: Exception) { e.printStackTrace() } return bitmap } fun setFirstScaleValue(value: Float){ firstScaleValue = value currPercent = firstScaleValue / maxScaleValue invalidate() } }
0
null
0
6
5b135f78506b141689cc2bd655370cbe89e1dffe
14,473
ScaleSeekBar
Apache License 2.0
features/facts/src/test/java/io/dotanuki/norris/facts/util/factsTestModule.kt
dotanuki-labs
192,096,771
false
null
package io.dotanuki.norris.facts.util import io.dotanuki.norris.facts.ui.FactsScreen import org.kodein.di.DI import org.kodein.di.bind import org.kodein.di.singleton val factsTestModule = DI.Module("facts-test-module") { bind<FactsScreen>(overrides = true) { // Make sure the same instance is provided to both FactsActivity and Tests singleton { FakeFactsScreen() } } }
20
Kotlin
36
447
8d6e73d29a0a75231be79356afd4d73e218271ac
417
norris
MIT License
module_user/src/main/java/com/czl/module_user/widget/TodoFilterPopView.kt
cdalwyn
336,133,347
false
{"Kotlin": 630994, "Java": 115105}
package com.czl.module_user.widget import android.annotation.SuppressLint import androidx.databinding.DataBindingUtil import com.afollestad.materialdialogs.utils.MDUtil.getStringArray import com.blankj.utilcode.util.StringUtils import com.czl.lib_base.binding.command.BindingAction import com.czl.lib_base.binding.command.BindingCommand import com.czl.lib_base.binding.command.BindingConsumer import com.czl.module_user.R import com.czl.module_user.databinding.UserPopFilterBinding import com.czl.module_user.ui.fragment.UserTodoFragment import com.lxj.xpopup.core.DrawerPopupView /** * @author Alwyn * @Date 2021/1/19 * @Description */ @SuppressLint("ViewConstructor") class TodoFilterPopView( private val mFragment: UserTodoFragment, private val status: Int, private val todoType: Int, private val priority: Int, private val timeState: Int ) : DrawerPopupView(mFragment.requireContext()) { private var dataBinding: UserPopFilterBinding? = null private var mType = -1 private var mStatus = 0 private var mPriority = 0 override fun getImplLayoutId(): Int { return R.layout.user_pop_filter } override fun onCreate() { super.onCreate() dataBinding = DataBindingUtil.bind(popupImplView) dataBinding?.apply { pop = this@TodoFilterPopView status = this@TodoFilterPopView.status type = todoType priority = this@TodoFilterPopView.priority timeState = this@TodoFilterPopView.timeState executePendingBindings() } } val onConfirmClickCommand: BindingCommand<Void> = BindingCommand(BindingAction { mFragment.viewModel.apply { todoType = mType priority = mPriority status = mStatus } mFragment.binding.smartCommon.autoRefresh() dismiss() }) val onTypeGroupCheckCommand: BindingCommand<String> = BindingCommand(BindingConsumer { if (it == "全部") { mType = 0 return@BindingConsumer } mType = StringUtils.getStringArray(R.array.todo_type).indexOf(it) }) val onPriorityGroupCheckCommand: BindingCommand<String> = BindingCommand(BindingConsumer { mPriority = StringUtils.getStringArray(R.array.todo_priority).indexOf(it) + 1 }) val onStatusGroupCheckCommand: BindingCommand<String> = BindingCommand(BindingConsumer { mStatus = StringUtils.getStringArray(R.array.todo_status).indexOf(it) - 1 }) val onTimeStateGroupCheckCommand: BindingCommand<String> = BindingCommand(BindingConsumer { mFragment.viewModel.timeState = StringUtils.getStringArray(R.array.todo_time_state).indexOf(it) }) }
1
Kotlin
70
267
77298b416cc15f168499c0b29c8f9017e6c187ca
2,737
PlayAndroid
Apache License 2.0
feature-assets/src/main/java/io/novafoundation/nova/feature_assets/presentation/tokens/manage/chain/di/ManageChainTokensModule.kt
novasamatech
415,834,480
false
{"Kotlin": 7668451, "Java": 14723, "JavaScript": 425}
package io.novafoundation.nova.feature_assets.presentation.tokens.manage.chain.di import androidx.fragment.app.Fragment import androidx.lifecycle.ViewModel import androidx.lifecycle.ViewModelProvider import dagger.Module import dagger.Provides import dagger.multibindings.IntoMap import io.novafoundation.nova.common.di.viewmodel.ViewModelKey import io.novafoundation.nova.common.di.viewmodel.ViewModelModule import io.novafoundation.nova.feature_assets.domain.tokens.manage.ManageTokenInteractor import io.novafoundation.nova.feature_assets.presentation.tokens.manage.chain.ManageChainTokensPayload import io.novafoundation.nova.feature_assets.presentation.tokens.manage.chain.ManageChainTokensViewModel import io.novafoundation.nova.feature_assets.presentation.tokens.manage.model.MultiChainTokenMapper @Module(includes = [ViewModelModule::class]) class ManageChainTokensModule { @Provides internal fun provideViewModel(fragment: Fragment, factory: ViewModelProvider.Factory): ManageChainTokensViewModel { return ViewModelProvider(fragment, factory).get(ManageChainTokensViewModel::class.java) } @Provides @IntoMap @ViewModelKey(ManageChainTokensViewModel::class) fun provideViewModel( interactor: ManageTokenInteractor, uiMapper: MultiChainTokenMapper, payload: ManageChainTokensPayload, ): ViewModel { return ManageChainTokensViewModel( interactor = interactor, commonUiMapper = uiMapper, payload = payload, ) } }
11
Kotlin
6
9
b39307cb56302ce7298582dbd03f33f6b2e2a807
1,542
nova-wallet-android
Apache License 2.0
core/src/main/java/com/sagar/core/widget/TextView.kt
sagar-viradiya
345,684,249
false
null
package com.sagar.core.widget import android.text.Editable import android.text.TextWatcher import android.widget.TextView import kotlinx.coroutines.ExperimentalCoroutinesApi import kotlinx.coroutines.channels.awaitClose import kotlinx.coroutines.flow.callbackFlow /** * Sealed class to wrap [TextView]'s before, on and after changes. */ sealed class ChangeDetails { /** * Data class to wrap [TextView]'s details before change. * * @property s [CharSequence] before change * @property start Start index from where change will happen * @property count Number of character to be replaced * @property after New length after change */ data class BeforeChangeDetails( val s: CharSequence?, val start: Int, val count: Int, val after: Int ) : ChangeDetails() /** * Data class to wrap [TextView]'s details on change. * * @property s [CharSequence] before change * @property start Start index from where change happened * @property count New length after change * @property before Old length before change */ data class OnChangeDetails( val s: CharSequence?, val start: Int, val count: Int, val before: Int ) : ChangeDetails() /** * Data class to wrap [TextView]'s details after change. * * @property editable [Editable] instance after text change */ data class AfterChangeDetails(val editable: Editable?) : ChangeDetails() } /** * Observe [TextView] changes after it happens through flow. * This extension will take care of removing text watcher if coroutine gets cancelled. * * @return Flow of [ChangeDetails.AfterChangeDetails] */ @ExperimentalCoroutinesApi suspend fun TextView.afterTextChangeFlow() = callbackFlow<ChangeDetails.AfterChangeDetails> { val textWatcher = getTextWatcher { trySend(ChangeDetails.AfterChangeDetails(it)) } addTextChangedListener(textWatcher) awaitClose { removeTextChangedListener(textWatcher) } } /** * Observe [TextView] changes before it happens through flow. * This extension will take care of removing text watcher if coroutine gets cancelled. * * @return Flow of [ChangeDetails.BeforeChangeDetails] */ @ExperimentalCoroutinesApi suspend fun TextView.beforeTextChangeFlow() = callbackFlow<ChangeDetails.BeforeChangeDetails> { val textWatcher = getTextWatcher( beforeTextChanged = { s, start, count, after -> trySend(ChangeDetails.BeforeChangeDetails(s, start, count, after)) } ) addTextChangedListener(textWatcher) awaitClose { removeTextChangedListener(textWatcher) } } /** * Observe [TextView] changes as it happens through flow. * This extension will take care of removing text watcher if coroutine gets cancelled. * * @return Flow of [ChangeDetails.OnChangeDetails] */ @ExperimentalCoroutinesApi suspend fun TextView.onTextChangeFlow() = callbackFlow<ChangeDetails.OnChangeDetails> { val textWatcher = getTextWatcher( onTextChange = { s, start, before, count -> trySend(ChangeDetails.OnChangeDetails(s, start, count, before)) } ) addTextChangedListener(textWatcher) awaitClose { removeTextChangedListener(textWatcher) } } /** * Observe [TextView] before, after and on changes through flow. * This extension will take care of removing text watcher if coroutine gets cancelled. * * @return Flow of [ChangeDetails] */ @ExperimentalCoroutinesApi suspend fun TextView.textChangeFlow() = callbackFlow<ChangeDetails> { val textWatcher = getTextWatcher( onTextChange = { s, start, before, count -> trySend(ChangeDetails.OnChangeDetails(s, start, count, before)) }, beforeTextChanged = { s, start, count, after -> trySend(ChangeDetails.BeforeChangeDetails(s, start, count, after)) }, afterTextChanged = { trySend(ChangeDetails.AfterChangeDetails(it)) } ) addTextChangedListener(textWatcher) awaitClose { removeTextChangedListener(textWatcher) } } private inline fun getTextWatcher( crossinline beforeTextChanged: ( text: CharSequence?, start: Int, count: Int, after: Int ) -> Unit = { _, _, _, _ -> }, crossinline onTextChange: ( text: CharSequence?, start: Int, before: Int, count: Int ) -> Unit = { _, _, _, _ -> }, crossinline afterTextChanged: (text: Editable?) -> Unit = {} ): TextWatcher { return object : TextWatcher { override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) { beforeTextChanged.invoke(s, start, count, after) } override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) { onTextChange.invoke(s, start, before, count) } override fun afterTextChanged(s: Editable?) { afterTextChanged.invoke(s) } } }
1
Kotlin
7
171
b9b0f40001f8ef3d3b59713d4f616d6c49f32292
5,052
callback-ktx
Apache License 2.0
common_component/src/main/java/com/xyoye/common_component/database/dao/MediaLibraryDao.kt
xyoye
138,993,190
false
null
package com.xyoye.common_component.database.dao import androidx.lifecycle.LiveData import androidx.room.* import com.xyoye.data_component.entity.MediaLibraryEntity import com.xyoye.data_component.enums.MediaType import com.xyoye.data_component.helper.MediaTypeConverter /** * Created by xyoye on 2021/1/18. */ @Dao interface MediaLibraryDao { @Query("SELECT * FROM media_library ORDER BY id ASC") fun getAll(): LiveData<MutableList<MediaLibraryEntity>> @Query("SELECT * FROM media_library WHERE media_type = (:mediaType)") @TypeConverters(MediaTypeConverter::class) fun getByMediaType(mediaType: MediaType): LiveData<MediaLibraryEntity> @Query("SELECT * FROM media_library WHERE id = (:libraryId)") suspend fun getById(libraryId: Int): MediaLibraryEntity? @Query("SELECT * FROM media_library WHERE media_type = (:mediaType)") @TypeConverters(MediaTypeConverter::class) suspend fun getByMediaTypeSuspend(mediaType: MediaType): MutableList<MediaLibraryEntity> @Query("SELECT * FROM media_library WHERE url = (:url) AND media_type = (:mediaType)") @TypeConverters(MediaTypeConverter::class) suspend fun getByUrl(url: String, mediaType: MediaType): MediaLibraryEntity? @Insert(onConflict = OnConflictStrategy.REPLACE) suspend fun insert(vararg entity: MediaLibraryEntity) @Query("DELETE FROM media_library WHERE url = (:url) AND media_type = (:mediaType)") @TypeConverters(MediaTypeConverter::class) suspend fun delete(url: String, mediaType: MediaType) }
28
null
93
946
b60bd028ce160ff37aba3eaf70fd0b2cbfa5eab0
1,536
DanDanPlayForAndroid
Apache License 2.0
app/src/main/java/es/upm/bienestaremocional/app/ui/screen/SettingsScreen.kt
Emotional-Wellbeing
531,973,820
false
null
package es.upm.bienestaremocional.app.ui.screen import android.app.Activity import android.content.Context import androidx.annotation.StringRes import androidx.compose.foundation.layout.* import androidx.compose.foundation.rememberScrollState import androidx.compose.foundation.verticalScroll import androidx.compose.material3.* import androidx.compose.runtime.* import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.graphics.Color import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.res.painterResource import androidx.compose.ui.res.stringResource import androidx.compose.ui.tooling.preview.Preview import androidx.compose.ui.unit.dp import com.alorma.compose.settings.storage.base.SettingValueState import com.alorma.compose.settings.storage.base.rememberBooleanSettingState import com.alorma.compose.settings.storage.base.rememberIntSetSettingState import com.alorma.compose.settings.storage.base.rememberIntSettingState import com.alorma.compose.settings.ui.SettingsList import com.alorma.compose.settings.ui.SettingsListMultiSelect import com.alorma.compose.settings.ui.SettingsMenuLink import com.alorma.compose.settings.ui.SettingsSwitch import com.ramcosta.composedestinations.annotation.Destination import com.ramcosta.composedestinations.navigation.DestinationsNavigator import com.ramcosta.composedestinations.navigation.EmptyDestinationsNavigator import es.upm.bienestaremocional.R import es.upm.bienestaremocional.app.MainApplication import es.upm.bienestaremocional.app.data.alarm.AlarmsFrequency import es.upm.bienestaremocional.app.data.questionnaire.Questionnaire import es.upm.bienestaremocional.app.data.settings.ThemeMode import es.upm.bienestaremocional.app.ui.navigation.MenuEntry import es.upm.bienestaremocional.app.ui.screen.destinations.* import es.upm.bienestaremocional.app.ui.viewmodel.SettingsViewModel import es.upm.bienestaremocional.app.utils.* import es.upm.bienestaremocional.core.ui.component.AppBasicScreen import es.upm.bienestaremocional.core.ui.theme.BienestarEmocionalTheme @Composable private fun GroupText(@StringRes textRes : Int) { Row(modifier = Modifier .fillMaxWidth() .padding(start = 16.dp, bottom = 16.dp), horizontalArrangement = Arrangement.Start) { Text(text = stringResource(textRes), style = MaterialTheme.typography.headlineSmall, color = MaterialTheme.colorScheme.primary) } } private fun Modifier.defaultIconModifier() = this.then(padding(all = 2.dp).size(size = 28.dp)) private suspend fun showRestartInfo(snackbarHostState: SnackbarHostState, message : String, actionLabel : String, context: Context) { val result = snackbarHostState.showSnackbar(message = message, actionLabel = actionLabel, withDismissAction = true, duration = SnackbarDuration.Long) if (result === SnackbarResult.ActionPerformed) restartApp(activity = context as Activity) } private const val HEALTH_CONNECT_ACTION = "androidx.health.ACTION_HEALTH_CONNECT_SETTINGS" /** * Renders settings menu * @param navigator: needed for render menu * @param alarmFrequency: var that holds questionnaire frequency * @param questionnaires: var that stores additional questionnaires selection * @param language: var that stores the language of the app * @param themeMode: var that stores theme setting value * @param dynamicColor: var that stores dynamic setting value * @param android12OrAbove: boolean to print Android 12+ options * @param onAlarmFrequencyChange: callback to react alarm frequency setting changes * @param onQuestionnairesChange: callback to react questionnaires changes * @param onLanguageChange: callback to react language setting changes * @param onThemeChange: callback to react theme setting changes * @param onDynamicChange: callback to react dynamic setting changes */ @Composable private fun DrawSettingsScreen(navigator: DestinationsNavigator, alarmFrequency: SettingValueState<Int>, questionnaires: SettingValueState<Set<Int>>, language: SettingValueState<Int>, themeMode: SettingValueState<Int>, dynamicColor : SettingValueState<Boolean>, android12OrAbove : Boolean, onAlarmFrequencyChange : suspend (SettingValueState<Int>) -> Unit, onQuestionnairesChange : suspend (SettingValueState<Set<Int>>) -> Unit, onLanguageChange : @Composable (SettingValueState<Int>) -> Unit, onThemeChange : suspend (SettingValueState<Int>) -> Unit, onDynamicChange : suspend (SettingValueState<Boolean>) -> Unit) { val scope = rememberCoroutineScope() val snackbarHostState = remember { SnackbarHostState() } val context = LocalContext.current val windowSize = MainApplication.windowSize!! //avoid undesired launch val defaultAlarmFrequency : Int = remember { alarmFrequency.value } val alarmFrequencyChanged : MutableState<Boolean> = remember { mutableStateOf(false) } val defaultQuestionnaires : Set<Int> = remember { questionnaires.value } val defaultThemeValue : Int = remember { themeMode.value } val defaultDynamicValue : Boolean = remember { dynamicColor.value } val defaultLanguage : Int = remember { language.value } val restartToApplyChanges = stringResource(id = R.string.restart_apply_changes) val restartApplyAllChanges = stringResource(id = R.string.restart_apply_all_changes) val actionLabel = stringResource(id = R.string.restart) if (alarmFrequency.value != defaultAlarmFrequency || alarmFrequencyChanged.value) { if (alarmFrequency.value != defaultAlarmFrequency) alarmFrequencyChanged.value = true LaunchedEffect(alarmFrequency.value) { onAlarmFrequencyChange(alarmFrequency) } } if (questionnaires.value != defaultQuestionnaires) { LaunchedEffect(questionnaires.value) { onQuestionnairesChange(questionnaires) } } if (themeMode.value != defaultThemeValue) { LaunchedEffect(themeMode.value) { onThemeChange(themeMode) showRestartInfo(snackbarHostState = snackbarHostState, message = restartToApplyChanges, actionLabel = actionLabel, context = context) } } if (dynamicColor.value != defaultDynamicValue) { LaunchedEffect(dynamicColor.value) { onDynamicChange(dynamicColor) showRestartInfo(snackbarHostState = snackbarHostState, message = restartToApplyChanges, actionLabel = actionLabel, context = context) } } if (language.value != defaultLanguage) { onLanguageChange(language) LaunchedEffect(language.value) { showRestartInfo(snackbarHostState = snackbarHostState, message = restartApplyAllChanges, actionLabel = actionLabel, context = context) } } AppBasicScreen(navigator = navigator, entrySelected = MenuEntry.SettingsScreen, label = MenuEntry.SettingsScreen.labelId, scope = scope, snackbarHostState = snackbarHostState ) { Column( modifier = Modifier .fillMaxSize() .verticalScroll(rememberScrollState()) .padding(16.dp), horizontalAlignment = Alignment.CenterHorizontally ) { GroupText(textRes = R.string.privacy_group) SettingsMenuLink( icon = { Icon(painter = painterResource(R.drawable.storage), contentDescription = null, modifier = Modifier.defaultIconModifier()) }, title = { Text(text = stringResource(id = R.string.my_data_label), color = MaterialTheme.colorScheme.secondary) }, subtitle = { Text(stringResource(id = R.string.my_data_description)) }, onClick = { navigator.navigate(MyDataScreenDestination(windowSize)) }, ) SettingsMenuLink( icon = { Icon(painter = painterResource(R.drawable.security), contentDescription = null, modifier = Modifier.defaultIconModifier()) }, title = { Text(text = stringResource(id = R.string.privacy_policy_screen_label), color = MaterialTheme.colorScheme.secondary) }, subtitle = { Text(stringResource(id = R.string.privacy_policy_screen_description)) }, onClick = { navigator.navigate(PrivacyPolicyScreenDestination) }, ) SettingsMenuLink( icon = { Icon(painter = painterResource(R.drawable.health_connect_logo), contentDescription = null, modifier = Modifier.defaultIconModifier(), tint = Color.Unspecified) }, title = { Text(text = stringResource(id = R.string.health_connect_settings_label), color = MaterialTheme.colorScheme.secondary) }, subtitle = { Text(stringResource(id = R.string.health_connect_settings_description)) }, onClick = { openForeignActivity(context = context, action = HEALTH_CONNECT_ACTION) }, ) Divider(modifier = Modifier.padding(top = 16.dp, bottom = 16.dp)) GroupText(textRes = R.string.ui_group) SettingsList( icon = { Icon(painter = painterResource(R.drawable.language), contentDescription = null, modifier = Modifier.defaultIconModifier()) }, title = { Text(stringResource(R.string.language), color = MaterialTheme.colorScheme.secondary) }, state = language, items = MainApplication.languageManager.getSupportedLocalesLabel() ) if (android12OrAbove) { SettingsSwitch( icon = { Icon(painter = painterResource(R.drawable.palette), contentDescription = null, modifier = Modifier.defaultIconModifier()) }, title = { Text(text = stringResource(R.string.dynamic_colors_label), color = MaterialTheme.colorScheme.secondary) }, subtitle = { Text(text = stringResource(R.string.dynamic_colors_description)) }, state = dynamicColor ) } SettingsList( icon = { Icon(painter = painterResource(R.drawable.dark_mode), contentDescription = null, modifier = Modifier.defaultIconModifier()) }, title = { Text(stringResource(R.string.dark_mode), color = MaterialTheme.colorScheme.secondary) }, state = themeMode, items = ThemeMode.getLabels() ) Divider(modifier = Modifier.padding(top = 16.dp, bottom = 16.dp)) GroupText(textRes = R.string.notifications) SettingsMenuLink( icon = { Icon(painter = painterResource(R.drawable.notifications), contentDescription = null, modifier = Modifier.defaultIconModifier(), tint = Color.Unspecified) }, title = { Text(stringResource(R.string.permission_for_notifications), color = MaterialTheme.colorScheme.secondary) }, subtitle = { Text(stringResource(R.string.permission_for_notifications_body)) }, onClick = { openSettingsNotifications(context) }, ) if (android12OrAbove) { SettingsMenuLink( icon = { Icon( painter = painterResource(R.drawable.notification_important), contentDescription = null, modifier = Modifier.defaultIconModifier(), tint = Color.Unspecified ) }, title = { Text( stringResource(R.string.permission_for_exact_notifications), color = MaterialTheme.colorScheme.secondary ) }, subtitle = { Text(stringResource(R.string.permission_for_exact_notifications_body)) }, onClick = { openSettingsExactNotifications(context) }, ) } Divider(modifier = Modifier.padding(top = 16.dp, bottom = 16.dp)) GroupText(textRes = R.string.feedback_group) SettingsList( icon = { Icon(painter = painterResource(R.drawable.event_repeat), contentDescription = null, modifier = Modifier.defaultIconModifier()) }, title = { Text(stringResource(R.string.feedback_frequency), color = MaterialTheme.colorScheme.secondary) }, state = alarmFrequency, items = AlarmsFrequency.getLabels() ) SettingsListMultiSelect( icon = { Icon(painter = painterResource(R.drawable.question_answer), contentDescription = null, modifier = Modifier.defaultIconModifier()) }, title = { Text(stringResource(R.string.additional_questionnaires), color = MaterialTheme.colorScheme.secondary) }, state = questionnaires, items = Questionnaire.getOptionalLabels(), confirmButton = stringResource(R.string.accept) ) Divider(modifier = Modifier.padding(top = 16.dp, bottom = 16.dp)) GroupText(textRes = R.string.misc_group) SettingsMenuLink( icon = { Icon(painter = painterResource(R.drawable.help_outline), contentDescription = null, modifier = Modifier.defaultIconModifier()) }, title = { Text(text = stringResource(id = R.string.about_screen_label), color = MaterialTheme.colorScheme.secondary) }, subtitle = { Text(stringResource(id = R.string.about_screen_description)) }, onClick = { navigator.navigate(AboutScreenDestination) }, ) SettingsMenuLink( icon = { Icon(painter = painterResource(R.drawable.start), contentDescription = null, modifier = Modifier.defaultIconModifier()) }, title = { Text(text = stringResource(id = R.string.onboarding_screen_label), color = MaterialTheme.colorScheme.secondary) }, subtitle = { Text(stringResource(id = R.string.onboarding_screen_description)) }, onClick = { navigator.navigate(OnboardingScreenDestination(windowSize)) }, ) SettingsMenuLink( icon = { Icon(painter = painterResource(R.drawable.people_alt), contentDescription = null, modifier = Modifier.defaultIconModifier()) }, title = { Text(text = stringResource(id = R.string.credits_screen_label), color = MaterialTheme.colorScheme.secondary) }, subtitle = { Text(stringResource(id = R.string.credits_screen_description)) }, onClick = { navigator.navigate(CreditsScreenDestination(windowSize)) }, ) } } } /** * Public function to read SettingsScreen using [SettingsViewModel] */ @Destination @Composable fun SettingsScreen(navigator: DestinationsNavigator, viewModel: SettingsViewModel) { val alarmFrequency = viewModel.loadAlarmFrequency() val questionnaire = viewModel.loadQuestionnairesSelected() val language = viewModel.loadLanguage() val themeMode = viewModel.loadDarkMode() val dynamicColor = viewModel.loadDynamicColors() DrawSettingsScreen( navigator = navigator, alarmFrequency = alarmFrequency, questionnaires = questionnaire, language = language, themeMode = themeMode, dynamicColor = dynamicColor, android12OrAbove = android12OrAbove(), onAlarmFrequencyChange = { viewModel.changeAlarmFrequency(it)}, onQuestionnairesChange = { viewModel.changeQuestionnairesSelected(it) }, onThemeChange = {theme -> viewModel.changeDarkMode(theme)}, onDynamicChange = {dynamic -> viewModel.changeDynamicColors(dynamic)}, onLanguageChange = { viewModel.changeLanguage(LocalContext.current,it)} ) } @Preview(showBackground = true) @Composable fun SettingsScreenNoDynamicPreview() { BienestarEmocionalTheme() { DrawSettingsScreen( navigator = EmptyDestinationsNavigator, alarmFrequency = rememberIntSettingState(-1), questionnaires = rememberIntSetSettingState(), language = rememberIntSettingState(-1), themeMode = rememberIntSettingState(-1), dynamicColor = rememberBooleanSettingState(true), android12OrAbove = false, onAlarmFrequencyChange = {}, onQuestionnairesChange = {}, onThemeChange = {}, onDynamicChange = {}, onLanguageChange = {} ) } } @Preview(showBackground = true) @Composable fun SettingsScreenNoDynamicPreviewDarkTheme() { BienestarEmocionalTheme(darkTheme = true) { DrawSettingsScreen( navigator = EmptyDestinationsNavigator, alarmFrequency = rememberIntSettingState(-1), questionnaires = rememberIntSetSettingState(), language = rememberIntSettingState(-1), themeMode = rememberIntSettingState(-1), dynamicColor = rememberBooleanSettingState(true), android12OrAbove = false, onAlarmFrequencyChange = {}, onQuestionnairesChange = {}, onThemeChange = {}, onDynamicChange = {}, onLanguageChange = {} ) } } @Preview(showBackground = true) @Composable fun SettingsScreenPreview() { BienestarEmocionalTheme() { DrawSettingsScreen( navigator = EmptyDestinationsNavigator, alarmFrequency = rememberIntSettingState(-1), questionnaires = rememberIntSetSettingState(), language = rememberIntSettingState(-1), themeMode = rememberIntSettingState(-1), dynamicColor = rememberBooleanSettingState(true), android12OrAbove = true, onAlarmFrequencyChange = {}, onQuestionnairesChange = {}, onThemeChange = {}, onDynamicChange = {}, onLanguageChange = {} ) } } @Preview(showBackground = true) @Composable fun SettingsScreenPreviewDarkTheme() { BienestarEmocionalTheme(darkTheme = true) { DrawSettingsScreen( navigator = EmptyDestinationsNavigator, alarmFrequency = rememberIntSettingState(-1), questionnaires = rememberIntSetSettingState(), language = rememberIntSettingState(-1), themeMode = rememberIntSettingState(-1), dynamicColor = rememberBooleanSettingState(true), android12OrAbove = true, onAlarmFrequencyChange = {}, onQuestionnairesChange = {}, onThemeChange = {}, onDynamicChange = {}, onLanguageChange = {} ) } }
0
Kotlin
0
1
e45d8969c9cd1a89f53777fcc671a4196177b7e3
20,222
App
Apache License 2.0
src/main/kotlin/software/amazon/smithy/intellij/SmithyFileIndex.kt
iancaffey
455,381,865
false
{"Kotlin": 286598, "Lex": 5063, "Smithy": 2929}
package software.amazon.smithy.intellij import com.intellij.openapi.project.DumbService import com.intellij.psi.PsiManager import com.intellij.psi.search.FileTypeIndex import com.intellij.psi.search.GlobalSearchScope /** * A utility class providing query methods for [SmithyFile] on top of the [FileTypeIndex]. * * @author <NAME> * @since 1.0 */ object SmithyFileIndex { fun forEach(scope: GlobalSearchScope, action: (SmithyFile) -> Unit) { if (DumbService.isDumb(scope.project!!)) return FileTypeIndex.getFiles(SmithyFileType, scope).forEach { (PsiManager.getInstance(scope.project!!).findFile(it) as? SmithyFile)?.let(action) } } }
2
Kotlin
2
24
286adf8f042e9ebeeb28bbd99aa3ac320ed95f23
684
smithy-intellij-plugin
MIT License
behavior/src/main/java/com/angcyo/behavior/refresh/RefreshEffectBehavior.kt
angcyo
259,872,337
false
null
package com.angcyo.behavior.refresh import android.content.Context import android.util.AttributeSet import com.angcyo.behavior.BaseScrollBehavior /** * 刷新效果的行为, 只有效果, 不触发回调. * * Email:angcyo@126.com * @author angcyo * @date 2020/01/07 */ open class RefreshEffectBehavior(context: Context, attributeSet: AttributeSet? = null) : RefreshHeaderBehavior(context, attributeSet) { override fun onContentOverScroll(contentBehavior: BaseScrollBehavior<*>, dx: Int, dy: Int) { _refreshEffectConfig.onContentOverScroll(contentBehavior, dx, dy) } override fun onContentStopScroll(contentBehavior: BaseScrollBehavior<*>) { if (!contentBehavior.isTouchHold) { onSetRefreshBehaviorStatus(contentBehavior, IRefreshBehavior.STATUS_NORMAL) contentBehavior.startScrollTo(0, 0) } } }
1
Kotlin
5
23
6f06f225e0eae1f42184e4bd5d8428561a17ba67
842
DslBehavior
MIT License
src/test/kotlin/keymonitor/database/NotificationTest.kt
nmalkin
94,026,869
false
null
package keymonitor.database import keymonitor.common.PhoneNumber import keymonitor.common.closeTestingDatabase import keymonitor.common.query import keymonitor.common.useNewTestingDatabase import org.jetbrains.spek.api.Spek import org.jetbrains.spek.api.dsl.describe import org.jetbrains.spek.api.dsl.it import org.jetbrains.spek.api.dsl.on import java.time.Instant import kotlin.test.assertEquals class NotificationTest : Spek({ describe("a notification") { beforeGroup { useNewTestingDatabase() } on("saving an email notification") { val phone = "+15105550123" val user = createUser(PhoneNumber(phone)) val email = addEmail(user, "<EMAIL>") val time = Instant.now() val task = createTask(user.id, time, time) val key1 = saveKey(task, time, phone, "127.0.0.1", "010203") val key2 = saveKey(task, time, phone, "127.0.0.1", "010204") val change = saveChange(user.id, key1.id, key2.id) it("adds a row to the database") { val countBefore = query("SELECT COUNT(*) FROM notifications").getInt(1) saveNotificationEmail(user.id, change.id, email.id, time) val countAfter = query("SELECT COUNT(*) FROM notifications").getInt(1) assertEquals(countBefore + 1, countAfter) } it("saves the right values") { val notification = saveNotificationEmail(user.id, change.id, email.id, time) val result = query("SELECT * FROM notifications WHERE id = ${notification.id}") assertEquals(user.id, result.getInt("user_id")) assertEquals(change.id, result.getInt("change_id")) assertEquals(email.id, result.getInt("email_id")) assertEquals(time, Instant.parse(result.getString("sent"))) } it("automatically notes that this is an email notification") { val notification = saveNotificationEmail(user.id, change.id, email.id, time) val result = query("SELECT * FROM notifications WHERE id = ${notification.id}") assertEquals(NotificationType.EMAIL, NotificationType.valueOf(result.getString("notification_type"))) } it("returns an object with the expected values") { val notification = saveNotificationEmail(user.id, change.id, email.id, time) val expected = Notification(notification.id, user.id, change.id, NotificationType.EMAIL, email.id, time) assertEquals(expected, notification) } } afterGroup { closeTestingDatabase() } } })
0
Kotlin
0
0
8875e3c6d39e1cd06ebc96f24dbc44186c88d063
2,705
key-monitor
MIT License
plugins/kotlin/idea/tests/testData/quickfix/suppress/declarationKinds/var.kt
ingokegel
72,937,917
false
null
// "Suppress 'DIVISION_BY_ZERO' for var foo" "true" var foo = 2 / <caret>0 // FUS_K2_QUICKFIX_NAME: org.jetbrains.kotlin.idea.inspections.suppress.KotlinSuppressIntentionAction // FUS_QUICKFIX_NAME: org.jetbrains.kotlin.idea.inspections.suppress.KotlinSuppressIntentionAction
1
null
1
2
b07eabd319ad5b591373d63c8f502761c2b2dfe8
277
intellij-community
Apache License 2.0
fontawesome/src/de/msrd0/fontawesome/icons/FA_SPRAY_CAN.kt
msrd0
363,665,023
false
{"Kotlin": 3912511, "Jinja": 2214}
/* @generated * * This file is part of the FontAwesome Kotlin library. * https://github.com/msrd0/fontawesome-kt * * This library is not affiliated with FontAwesome. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package de.msrd0.fontawesome.icons import de.msrd0.fontawesome.Icon import de.msrd0.fontawesome.Style import de.msrd0.fontawesome.Style.SOLID /** Spray Can */ object FA_SPRAY_CAN: Icon { override val name get() = "Spray Can" override val unicode get() = "f5bd" override val styles get() = setOf(SOLID) override fun svg(style: Style) = when(style) { SOLID -> """<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 512 512"><path d="M192 0C209.7 0 224 14.33 224 32V128H96V32C96 14.33 110.3 0 128 0H192zM0 256C0 202.1 42.98 160 96 160H224C277 160 320 202.1 320 256V464C320 490.5 298.5 512 272 512H48C21.49 512 0 490.5 0 464V256zM160 256C115.8 256 80 291.8 80 336C80 380.2 115.8 416 160 416C204.2 416 240 380.2 240 336C240 291.8 204.2 256 160 256zM320 64C320 81.67 305.7 96 288 96C270.3 96 256 81.67 256 64C256 46.33 270.3 32 288 32C305.7 32 320 46.33 320 64zM352 64C352 46.33 366.3 32 384 32C401.7 32 416 46.33 416 64C416 81.67 401.7 96 384 96C366.3 96 352 81.67 352 64zM512 64C512 81.67 497.7 96 480 96C462.3 96 448 81.67 448 64C448 46.33 462.3 32 480 32C497.7 32 512 46.33 512 64zM448 160C448 142.3 462.3 128 480 128C497.7 128 512 142.3 512 160C512 177.7 497.7 192 480 192C462.3 192 448 177.7 448 160zM512 256C512 273.7 497.7 288 480 288C462.3 288 448 273.7 448 256C448 238.3 462.3 224 480 224C497.7 224 512 238.3 512 256zM352 160C352 142.3 366.3 128 384 128C401.7 128 416 142.3 416 160C416 177.7 401.7 192 384 192C366.3 192 352 177.7 352 160z"/></svg>""" else -> null } }
0
Kotlin
0
0
ee6a62d201fd5df2555859271cb0c6a7ee887e7a
2,229
fontawesome-kt
Apache License 2.0
Scanner/Android/app/src/main/java/ca/snmc/scanner/data/network/apis/testing/AuthenticateTestingApi.kt
snmcCode
272,461,777
false
{"C#": 420531, "Kotlin": 263098, "HTML": 148679, "TSQL": 22187, "CSS": 9706, "JavaScript": 920}
package ca.snmc.scanner.data.network.apis.testing import ca.snmc.scanner.data.network.NetworkConnectionInterceptor import ca.snmc.scanner.data.network.responses.AuthenticateResponse import okhttp3.OkHttpClient import retrofit2.Response import retrofit2.Retrofit import retrofit2.converter.gson.GsonConverterFactory import retrofit2.http.Field import retrofit2.http.FormUrlEncoded import retrofit2.http.Headers import retrofit2.http.POST // Used by Retrofit to make API call interface AuthenticateTestingApi { @FormUrlEncoded @POST("oauth2/v2.0/token") @Headers("Content-Type: application/x-www-form-urlencoded", "Cache-Control: max-age=640000") suspend fun scannerAuthenticate( @Field("grant_type") grantType: String, @Field("client_id") clientId: String, @Field("client_secret") clientSecret: String, @Field("scope") scope: String ) : Response<AuthenticateResponse> companion object { operator fun invoke( baseUrl: String, networkConnectionInterceptor: NetworkConnectionInterceptor ) : AuthenticateTestingApi { val okHttpClient = OkHttpClient.Builder() .addInterceptor(networkConnectionInterceptor) .retryOnConnectionFailure(false) .build() return Retrofit.Builder() .baseUrl(baseUrl) .client(okHttpClient) .addConverterFactory(GsonConverterFactory.create()) .build() .create(AuthenticateTestingApi::class.java) } } }
29
C#
1
6
f1bb550397b4e959beb501e77c27110d439a64b3
1,584
covidTracking
MIT License
src/main/kotlin/io/github/misawa/coassign/WeightScaling.kt
MiSawa
226,680,692
false
null
package io.github.misawa.coassign import io.github.misawa.coassign.collections.ActiveNodeQueue import io.github.misawa.coassign.collections.BucketsLL import io.github.misawa.coassign.collections.FIFOActiveNodeQueue import io.github.misawa.coassign.collections.FixedCapacityIntArrayList import io.github.misawa.coassign.utils.StatsTracker import mu.KLogging import kotlin.math.min class WeightScaling( private val graph: BipartiteGraph, private val params: Params, statsTracker: StatsTracker ) { private val globalRelabelStats = statsTracker.timer("GlobalRelabel") private val dfsStats = statsTracker.timer("DFS") private val tsortStats = statsTracker.timer("TSort") private val priceRefineStats = statsTracker.timer("PriceRefine") private val pushCount = statsTracker.counter("Push") private val dischargeStats = statsTracker.timer("Discharge") private val augRelabelNonVCStats = statsTracker.timer("DischargeNonVC") private val initialScale: LargeWeight private val rNumV: Int private val root: Node private val edgeStarts: IntArray private val sources: IntArray private val targets: IntArray private val reverse: IntArray private val weights: LargeWeightArray private val allNodes: NodeRange private val nonRootNodes: NodeRange private val leftNodes: NodeRange private val rightNodes: NodeRange private val allEdges: EdgeRange private val inVertexCover: BooleanArray private val maxRank: Int private var epsilon: LargeWeight private val potential: LargeWeightArray private val currentEdge: IntArray private val isResidual: BooleanArray private val excess: FlowArray private val buckets: BucketsLL private val deficitNodes: FixedCapacityIntArrayList private val capToRoot: FlowArray private val capFromRoot: FlowArray private val rcapToRoot: FlowArray private val rcapFromRoot: FlowArray private val activeNodes: ActiveNodeQueue private var relabelCount: Int = 0 companion object : KLogging() { fun run( graph: BipartiteGraph, params: Params = Params(), statsTracker: StatsTracker = StatsTracker.noop() ): Solution = WeightScaling(graph, params, statsTracker).run() } data class Params( val scalingFactor: Weight = 8, val checkIntermediateStatus: Boolean = false, val globalRelabelFreqFactor: Double = 0.6, val strategy: Strategy = Strategy.DINITZ ) { enum class Strategy { DINITZ, PUSH_RELABEL, } init { check(scalingFactor > 1) { "Scaling factor should be greater than 1 but was $scalingFactor" } } } init { initialScale = (graph.lSize + 2).toLargeWeight() * params.scalingFactor leftNodes = 0 until graph.lSize rightNodes = graph.lSize until graph.numV rNumV = graph.numV + 1 root = graph.numV allNodes = 0..graph.numV nonRootNodes = 0 until graph.numV val originalNodes = 0 until graph.numV val rNumE = graph.numE + graph.numV * 2 allEdges = 0 until rNumE edgeStarts = IntArray(graph.numV + 2) sources = IntArray(rNumE) targets = IntArray(rNumE) reverse = IntArray(rNumE) weights = LargeWeightArray(rNumE) for (u in originalNodes) { edgeStarts[u] = graph.edgeStarts[u] + u graph.sources.copyInto( destination = sources, destinationOffset = edgeStarts[u], startIndex = graph.edgeStarts[u], endIndex = graph.edgeStarts[u + 1] ) graph.targets.copyInto( destination = targets, destinationOffset = edgeStarts[u], startIndex = graph.edgeStarts[u], endIndex = graph.edgeStarts[u + 1] ) var newE: Edge = edgeStarts[u] for (originalE in graph.edgeStarts[u] until graph.edgeStarts[u + 1]) { reverse[newE] = graph.reverse[originalE] + graph.targets[originalE] weights[newE] = graph.weights[originalE].toLargeWeight() * initialScale ++newE } } edgeStarts[root] = graph.edgeStarts[graph.numV] + graph.numV edgeStarts[root + 1] = edgeStarts[root] + graph.numV for (u in originalNodes) { val e = edgeStarts[u + 1] - 1 val re = edgeStarts[root] + u sources[e] = u targets[e] = root reverse[e] = re sources[re] = root targets[re] = u reverse[re] = e } inVertexCover = BooleanArray(rNumV) { (it == root) || ((it < graph.lSize) == (graph.lSize <= graph.rSize)) } epsilon = weights.max() ?: initialScale isResidual = BooleanArray(rNumE) excess = FlowArray(rNumV) potential = LargeWeightArray(rNumV) currentEdge = IntArray(rNumV + 1) maxRank = (1 + params.scalingFactor) * (2 * graph.lSize + 2) + 1 logger.info { "max rank = $maxRank" } buckets = BucketsLL(maxRank, rNumV) deficitNodes = FixedCapacityIntArrayList(rNumV) capFromRoot = FlowArray(graph.numV) { if (it < graph.lSize) graph.multiplicities[it] else 0 } capToRoot = FlowArray(graph.numV) { if (it >= graph.lSize) graph.multiplicities[it] else 0 } rcapFromRoot = capFromRoot.clone() rcapToRoot = capToRoot.clone() activeNodes = FIFOActiveNodeQueue(rNumV) } private fun run(): Solution { check(graph.lSize > 0 && graph.rSize > 0) epsilon = weights.max() ?: 1 potential.fill(0) when (params.strategy) { Params.Strategy.DINITZ -> startDinitz() Params.Strategy.PUSH_RELABEL -> startPR() }.let {} // for exhaustiveness for (u in allNodes) potential[u] -= potential[root] for (u in allNodes) potential[u] = (potential[u].toReal() / initialScale.toReal()).roundToLargeWeight() * initialScale logger.info { "Tighten potential" } // Tighten dual variables using Bellman-Ford method run { var cnt = 0 var cont = true while (cont) { check(cnt++ < rNumV) cont = false for (e in allEdges) { if (isResidual[e]) { val u = sources[e] val v = targets[e] val tmp = potential[u] - weights[e] if (tmp < potential[v]) { potential[v] = tmp cont = true } } } } } // Adjust offset for (u in allNodes) potential[u] -= potential[root] val used = BooleanArray(graph.numE) for (u in nonRootNodes) for (e in edgeStarts[u] until (edgeStarts[u + 1] - 1)) used[e - u] = !isResidual[e] val pot = WeightArray(graph.numV) { (potential[it].toReal() / initialScale.toReal()).roundToLargeWeight().toWeight() } logger.info { "Finish everything" } return Solution(graph, used, pot) } private fun checkInvariants(eps: LargeWeight = epsilon) { if (!params.checkIntermediateStatus) return for (e in allEdges) { val u = sources[e] val v = targets[e] val rWeight = weights[e] - potential[u] + potential[v] val re = reverse[e] if (isResidual[re]) check(rWeight >= -eps) if (u == root) { check((rcapToRoot[v] > 0) == isResidual[re]) check((rcapFromRoot[v] > 0) == isResidual[e]) } else if (v == root) { check((rcapToRoot[u] > 0) == isResidual[e]) check((rcapFromRoot[u] > 0) == isResidual[re]) } else { check(isResidual[e] xor isResidual[re]) } } val ex = FlowArray(rNumV) for (u in leftNodes) for (e in edgeStarts[u] until edgeStarts[u + 1] - 1) if (!isResidual[e]) { --ex[u] ++ex[targets[e]] } for (u in nonRootNodes) { val flowFromRoot = capFromRoot[u] - rcapFromRoot[u] ex[u] += flowFromRoot ex[root] -= flowFromRoot } check(ex.contentEquals(excess)) } private fun initPhase() { edgeStarts.copyInto(currentEdge) isResidual.fill(true, fromIndex = leftNodes.first, toIndex = leftNodes.last + 1) isResidual.fill(false, fromIndex = leftNodes.last, toIndex = isResidual.size) excess.fill(0) // Saturate arcs that breaks 0-optimality to make the pseudo assignment 0-optimal for (u in leftNodes) { val potentialU = potential[u] for (e in edgeStarts[u] until edgeStarts[u + 1] - 1) { val v = targets[e] val rWeight = weights[e] - potentialU + potential[v] if (rWeight > 0) { isResidual[e] = false isResidual[reverse[e]] = true --excess[u] ++excess[v] } else { isResidual[e] = true isResidual[reverse[e]] = false } } } for (e in edgeStarts[root] until edgeStarts[root + 1]) { val v = targets[e] val rWeight = potential[v] - potential[root] val flowFromRoot = if (rWeight > 0) capFromRoot[v] else -capToRoot[v] excess[root] -= flowFromRoot excess[v] += flowFromRoot rcapFromRoot[v] = capFromRoot[v] - flowFromRoot rcapToRoot[v] = capToRoot[v] + flowFromRoot isResidual[e] = rcapFromRoot[v] > 0 isResidual[reverse[e]] = rcapToRoot[v] > 0 } checkInvariants() } private val tsortDFSStack = FixedCapacityIntArrayList(edgeStarts[root+1]) // 0: Not touched yet, 1: Seen, to-be-processed, 2: Processing, 3: Processed private val tsortDFSFlagArray = ByteArray(rNumV) private fun tsortDFS(result: FixedCapacityIntArrayList): Boolean { tsortStats.timed { result.clear() tsortDFSStack.clear() tsortDFSFlagArray.fill(0) for (initialNode in allNodes) { if (tsortDFSFlagArray[initialNode] != 0.toByte()) continue tsortDFSFlagArray[initialNode] = 1 tsortDFSStack.push(initialNode) while (tsortDFSStack.isNotEmpty()) { val u = tsortDFSStack.pop() if (tsortDFSFlagArray[u] == 3.toByte()) continue if (tsortDFSFlagArray[u] == 2.toByte()) { result.push(u) tsortDFSFlagArray[u] = 3 continue } tsortDFSFlagArray[u] = 2 tsortDFSStack.push(u) val potentialU = potential[u] for (e in edgeStarts[u] until edgeStarts[u + 1]) { if (!isResidual[e]) continue val v = targets[e] val rWeight = weights[e] - potentialU + potential[v] if (rWeight <= 0) continue if (tsortDFSFlagArray[v] == 2.toByte()) return false else if (tsortDFSFlagArray[v] != 3.toByte()) { tsortDFSFlagArray[v] = 1 tsortDFSStack.push(v) } } } } result.reverse() return true } } private val priceRefineTSortedNodes = FixedCapacityIntArrayList(rNumV) private fun priceRefine(): Boolean { priceRefineStats.timed { checkInvariants(epsilon * params.scalingFactor) val tsorted = priceRefineTSortedNodes while (tsortDFS(tsorted)) { buckets.clear(0) var maxBucket = 0 for (u in tsorted) { val potentialU = potential[u] val bucketU = buckets.getBucket(u) maxBucket = maxBucket.coerceAtLeast(bucketU) for (e in edgeStarts[u] until edgeStarts[u + 1]) { if (!isResidual[e]) continue val v = targets[e] val rWeight = weights[e] - potentialU + potential[v] if (rWeight <= 0) continue // min k s.t. rWeight + k epsilon >= - epsilon && k >= 0 val k = (rWeight - 1) / epsilon val newBucket = bucketU + k if (newBucket > buckets.getBucket(v) && newBucket <= maxRank) { buckets.setBucket(v, newBucket.toInt()) } } } var b = maxBucket if (b == 0) { logger.trace { "Price refinement succeed" } checkInvariants(epsilon) return true } while (b >= 0) { while (buckets.hasNextElement(b)) { val u = buckets.nextElement(b) val potentialU = potential[u] for (e in edgeStarts[u] until edgeStarts[u + 1]) { if (!isResidual[e]) continue val v = targets[e] val bucketV = buckets.getBucket(v) if (bucketV >= b) continue val rWeight = weights[e] - potentialU + potential[v] val newBucketV = if (rWeight <= 0) { val d = (-rWeight) / epsilon if (b <= d) 0 else (b - (d + 1)).toInt() } else { b } if (bucketV < newBucketV) { buckets.setBucket(v, newBucketV) } } potential[u] -= b * epsilon } --b } checkInvariants(epsilon * params.scalingFactor) } return false } } private fun adjustPotential(): Boolean { globalRelabelStats.timed { checkInvariants() edgeStarts.copyInto(currentEdge) deficitNodes.clear() buckets.clear(maxRank) var totalExcess = 0 for (u in allNodes) if (excess[u] > 0) { totalExcess += excess[u] buckets.setBucket(u, 0) } if (totalExcess == 0) return false var d = 0 while (d <= maxRank) { while (buckets.hasNextElement(d)) { val u = buckets.nextElement(d) if (excess[u] < 0) { deficitNodes.push(u) totalExcess += excess[u] if (totalExcess == 0) break } val potentialU = potential[u] for (e in edgeStarts[u] until edgeStarts[u + 1]) { if (!isResidual[e]) continue val v = targets[e] val currentDistV = buckets.getBucket(v) if (d >= currentDistV) continue val rWeight = weights[e] - potentialU + potential[v] val diff: Int = if (rWeight > 0) { 0 } else { val tmp = (((-rWeight) / epsilon) + 1) if (tmp < maxRank) tmp.toInt() else maxRank } val newDist = d + diff if (newDist < currentDistV) { buckets.setBucket(v, newDist) } } } if (totalExcess == 0) break ++d } for (u in allNodes) { potential[u] += min(d, buckets.getBucket(u)) * epsilon } check(deficitNodes.isNotEmpty()) checkInvariants() return true } } private fun pull(backwardPath: FixedCapacityIntArrayList) { if (backwardPath.size == 4 && ((backwardPath[1] == root) || (backwardPath[3] == root))) { val flowFromRoot = backwardPath[3] == root val eFromRoot = if (flowFromRoot) reverse[backwardPath[2]] else backwardPath[2] val eToRoot = if (!flowFromRoot) reverse[backwardPath[2]] else backwardPath[2] val other = if (flowFromRoot) backwardPath[1] else backwardPath[3] val flow = if (flowFromRoot) { min(excess[root], min(rcapFromRoot[other], -excess[other])) } else { -min(excess[other], min(rcapToRoot[other], -excess[root])) } excess[root] -= flow excess[other] += flow rcapFromRoot[other] -= flow rcapToRoot[other] += flow isResidual[eFromRoot] = rcapFromRoot[other] > 0 isResidual[eToRoot] = rcapToRoot[other] > 0 } else { ++excess[backwardPath[1]] --excess[backwardPath.top()] var i = 2 while (i < backwardPath.size) { val u = backwardPath[i - 1] val e = backwardPath[i] val v = backwardPath[i + 1] val re = reverse[e] if (u == root) { ++rcapFromRoot[v] --rcapToRoot[v] isResidual[e] = true if (rcapToRoot[v] == 0) isResidual[re] = false } else if (v == root) { --rcapFromRoot[u] ++rcapToRoot[u] isResidual[e] = true if (rcapFromRoot[u] == 0) isResidual[re] = false } else { isResidual[e] = true isResidual[re] = false } i += 2 } } checkInvariants() } private fun revRelabel(u: Int) { ++relabelCount currentEdge[u] = edgeStarts[u] potential[u] += epsilon checkInvariants() } private fun pullAugRelabelNonVC(u: Int, potentialU: LargeWeight, extraDeficit: Flow): Flow { augRelabelNonVCStats.timed { check(!inVertexCover[u]) if (excess[u] >= extraDeficit) { return extraDeficit } var e = currentEdge[u] - 1 val edgeToRoot = edgeStarts[u + 1] - 1 while (++e < edgeToRoot) { if (isResidual[e]) continue // means !isResidual[re] val v = targets[e] val rWeight = weights[e] - potentialU + potential[v] if (rWeight >= 0) continue if (excess[v] == 0) activeNodes.push(v) ++excess[u] --excess[v] isResidual[e] = true isResidual[reverse[e]] = false if (excess[u] == extraDeficit) { currentEdge[u] = e + 1 return extraDeficit } } if (potential[root] < potentialU) { val f = minOf(extraDeficit - excess[u], rcapFromRoot[u]) excess[u] += f excess[root] -= f rcapFromRoot[u] -= f rcapToRoot[u] += f isResidual[edgeToRoot] = true isResidual[reverse[edgeToRoot]] = rcapFromRoot[u] > 0 if (excess[root] < 0) activeNodes.push(root) } if (excess[u] < extraDeficit) { revRelabel(u) return maxOf(0, excess[u]) } else { currentEdge[u] = edgeToRoot return extraDeficit } } } // Return true iff u still is a deficit node private fun pullDischarge(u: Int): Boolean { dischargeStats.timed { checkInvariants() if (excess[u] >= 0) return false val potentialU = potential[u] if (u == root) { var v = (currentEdge[root] - edgeStarts[root]) - 1 while (++v < root) { if (rcapToRoot[v] == 0) continue val potentialV = potential[v] if (potentialV >= potentialU) continue if (currentEdge[v] == edgeStarts[v + 1]) continue var f = minOf(-excess[root], rcapToRoot[v]) if (!inVertexCover[v]) f = pullAugRelabelNonVC(v, potentialV, minOf(-excess[root], rcapToRoot[v])) if (f == 0) continue excess[root] += f excess[v] -= f if (excess[v] < 0) activeNodes.push(v) rcapToRoot[v] -= f rcapFromRoot[v] += f val e = edgeStarts[root] + v isResidual[e] = true isResidual[reverse[e]] = rcapToRoot[v] > 0 checkInvariants() if (excess[root] == 0) { currentEdge[root] = edgeStarts[root] + v return false } } revRelabel(root) return true } else { var e = currentEdge[u] - 1 val edgeToRoot = edgeStarts[u + 1] - 1 while (++e < edgeToRoot) { if (isResidual[e]) continue // meaning !isResidual[re] val v = targets[e] val potentialV = potential[v] val rWeight = weights[e] - potentialU + potentialV if (rWeight >= 0) continue if (!inVertexCover[v] && pullAugRelabelNonVC(v, potentialV, 1) == 0) continue if (excess[v] == 0) activeNodes.push(v) ++excess[u] --excess[v] isResidual[e] = true isResidual[reverse[e]] = false checkInvariants() if (excess[u] == 0) { currentEdge[u] = e + 1 return false } } currentEdge[u] = edgeToRoot if (rcapFromRoot[u] > 0 && potential[root] < potentialU) { val f = minOf(-excess[u], rcapFromRoot[u]) excess[u] += f excess[root] -= f rcapFromRoot[u] -= f rcapToRoot[u] += f isResidual[edgeStarts[root] + u] = rcapFromRoot[u] > 0 isResidual[edgeToRoot] = true if (excess[root] < 0) activeNodes.push(root) checkInvariants() } if (excess[u] == 0) return false revRelabel(u) checkInvariants() return true } } } private fun startPR() { initPhase() var numPhase = 0 val globalRelabelFreq = (rNumV * params.globalRelabelFreqFactor).toInt() var nextGlobalRelabel: Int do { checkInvariants() epsilon = ((epsilon + params.scalingFactor - 1) / params.scalingFactor).coerceAtLeast(1) logger.trace { "Phase $epsilon" } ++numPhase if (numPhase > 1 && priceRefine()) continue initPhase() checkInvariants() while (true) { if (!adjustPotential()) break nextGlobalRelabel = relabelCount + globalRelabelFreq for (u in allNodes) if (!inVertexCover[u] && excess[u] < 0) while (pullDischarge(u)); activeNodes.clear() for (u in allNodes) if (excess[u] < 0) activeNodes.push(u) while (activeNodes.isNotEmpty()) { val u = activeNodes.pop() if (excess[u] >= 0) continue pullDischarge(u) if (excess[u] < 0) activeNodes.push(u) if (relabelCount > nextGlobalRelabel) break } } } while (epsilon > 1) } private fun startDinitz() { initPhase() val path = FixedCapacityIntArrayList(rNumV * 2) val inPath = BooleanArray(rNumV) var numPhase = 0 val stillDeficit = FixedCapacityIntArrayList(rNumV) do { checkInvariants() epsilon = ((epsilon + params.scalingFactor - 1) / params.scalingFactor).coerceAtLeast(1) logger.trace { "Phase $epsilon" } ++numPhase if (numPhase > 1 && priceRefine()) continue initPhase() checkInvariants() while (adjustPotential()) { var contiguousNonpush = 0 while (true) { stillDeficit.clear() var pushed = false while (deficitNodes.isNotEmpty()) { val deficitNode = deficitNodes.top() if (excess[deficitNode] >= 0 || currentEdge[deficitNode] == edgeStarts[deficitNode + 1]) { if (excess[deficitNode] < 0) stillDeficit.push(deficitNode) deficitNodes.pop() continue } run { var i = 1 while (i < path.size) { inPath[path[i]] = false i += 2 } } path.clear() path.push(-1) path.push(deficitNode) inPath[deficitNode] = true dfsStats.start() run findPath@{ while (path.isNotEmpty()) { val u = path.top() if (excess[u] > 0) break val potentialU = potential[u] run onPathTip@{ var e = currentEdge[u] while (e < edgeStarts[u + 1]) { val isEdgeToRoot = u != root && e == edgeStarts[u + 1] - 1 val done = run onEdge@{ if (isEdgeToRoot) { if (rcapFromRoot[u] == 0) return@onEdge false } else if (u != root) { if (isResidual[e]) return@onEdge false // meaning !isResidual[re] } else if (rcapToRoot[targets[e]] == 0) return@onEdge false val v = targets[e] val rWeight = weights[e] - potentialU + potential[v] if (rWeight >= 0) return@onEdge false if (currentEdge[v] == edgeStarts[v + 1]) return@onEdge false path.push(e) path.push(v) if (inPath[v]) return@findPath inPath[v] = true return@onEdge true } if (done) { currentEdge[u] = e return@onPathTip } ++e } currentEdge[u] = edgeStarts[u] potential[u] += epsilon checkInvariants() inPath[path.pop()] = false path.pop() if (path.isNotEmpty()) ++currentEdge[path.top()] } } } dfsStats.stop() if (path.isEmpty) { if (excess[deficitNode] < 0) stillDeficit.push(deficitNode) deficitNodes.pop() continue } pushCount.inc(path.size / 2) pushed = true pull(path) checkInvariants() } if (stillDeficit.isEmpty) break if (!pushed) ++contiguousNonpush else contiguousNonpush = 0 if (contiguousNonpush < 2) { deficitNodes.addAll(stillDeficit.iterator()) } } } } while (epsilon > 1) } }
0
Kotlin
0
0
2b723480d16e7c9517cf1e5394405a466a5a5360
30,030
coassign
MIT License
src/main/kotlin/br/com/trucouro/controller/HelloController.kt
acaverna
374,253,546
false
null
package br.com.trucouro.controller import io.micronaut.http.MediaType import io.micronaut.http.annotation.Controller import io.micronaut.http.annotation.Get import io.micronaut.http.annotation.PathVariable @Controller("/hello") class HelloController { @Get(produces = [MediaType.TEXT_PLAIN]) fun hello():String{ return "Hello World!" } @Get("/{name}", produces = [MediaType.TEXT_PLAIN]) fun hello(@PathVariable name:String):String{ return "Hello $name" } }
0
Kotlin
0
0
ab55d291c8625883e859e4339e3f9d4c314d2c8a
501
trucouro-server
MIT License
bot/src/main/kotlin/bot/utils/jobs/CloseScoreUpdateJob.kt
Jonath22b
206,583,496
false
null
package bot.utils.jobs import bot.bridges.CloseScoreUpdateBridge import bot.bridges.ScoreUpdateBridge import org.quartz.Job import org.quartz.JobExecutionContext import bot.utils.DataRetriever class CloseScoreUpdateJob : Job { override fun execute(context: JobExecutionContext?) { println("Running Close Score Update Job...") val data = DataRetriever.getTeamsData() CloseScoreUpdateBridge.dataObserver.onNext(data) } }
0
Kotlin
0
0
3ab294f86d805fd794ddc626c3bbab90631af790
453
Tickle-Sum-TDs
MIT License
rounded/src/commonMain/kotlin/me/localx/icons/rounded/bold/BoxCircleCheck.kt
localhostov
808,861,591
false
{"Kotlin": 79430321, "HTML": 331, "CSS": 102}
package me.localx.icons.rounded.bold import androidx.compose.ui.graphics.Color import androidx.compose.ui.graphics.PathFillType.Companion.NonZero import androidx.compose.ui.graphics.SolidColor import androidx.compose.ui.graphics.StrokeCap.Companion.Butt import androidx.compose.ui.graphics.StrokeJoin.Companion.Miter import androidx.compose.ui.graphics.vector.ImageVector import androidx.compose.ui.graphics.vector.ImageVector.Builder import androidx.compose.ui.graphics.vector.path import androidx.compose.ui.unit.dp import me.localx.icons.rounded.Icons public val Icons.Bold.BoxCircleCheck: ImageVector get() { if (_boxCircleCheck != null) { return _boxCircleCheck!! } _boxCircleCheck = Builder(name = "BoxCircleCheck", defaultWidth = 24.0.dp, defaultHeight = 24.0.dp, viewportWidth = 24.0f, viewportHeight = 24.0f).apply { path(fill = SolidColor(Color(0xFF000000)), stroke = null, strokeLineWidth = 0.0f, strokeLineCap = Butt, strokeLineJoin = Miter, strokeLineMiter = 4.0f, pathFillType = NonZero) { moveToRelative(18.5f, 0.0f) lineTo(5.5f, 0.0f) curveTo(2.467f, 0.0f, 0.0f, 2.467f, 0.0f, 5.5f) verticalLineToRelative(1.0f) curveToRelative(0.0f, 0.951f, 0.382f, 1.815f, 1.0f, 2.447f) verticalLineToRelative(9.553f) curveToRelative(0.0f, 3.033f, 2.467f, 5.5f, 5.5f, 5.5f) horizontalLineToRelative(2.0f) curveToRelative(0.829f, 0.0f, 1.5f, -0.671f, 1.5f, -1.5f) reflectiveCurveToRelative(-0.671f, -1.5f, -1.5f, -1.5f) horizontalLineToRelative(-2.0f) curveToRelative(-1.378f, 0.0f, -2.5f, -1.122f, -2.5f, -2.5f) verticalLineToRelative(-8.5f) horizontalLineToRelative(16.5f) curveToRelative(1.93f, 0.0f, 3.5f, -1.57f, 3.5f, -3.5f) verticalLineToRelative(-1.0f) curveToRelative(0.0f, -3.033f, -2.467f, -5.5f, -5.5f, -5.5f) close() moveTo(21.0f, 6.5f) curveToRelative(0.0f, 0.276f, -0.224f, 0.5f, -0.5f, 0.5f) lineTo(3.5f, 7.0f) curveToRelative(-0.276f, 0.0f, -0.5f, -0.224f, -0.5f, -0.5f) verticalLineToRelative(-1.0f) curveToRelative(0.0f, -1.378f, 1.122f, -2.5f, 2.5f, -2.5f) horizontalLineToRelative(13.0f) curveToRelative(1.378f, 0.0f, 2.5f, 1.122f, 2.5f, 2.5f) verticalLineToRelative(1.0f) close() moveTo(18.0f, 12.0f) curveToRelative(-3.314f, 0.0f, -6.0f, 2.686f, -6.0f, 6.0f) reflectiveCurveToRelative(2.686f, 6.0f, 6.0f, 6.0f) reflectiveCurveToRelative(6.0f, -2.686f, 6.0f, -6.0f) reflectiveCurveToRelative(-2.686f, -6.0f, -6.0f, -6.0f) close() moveTo(21.683f, 17.712f) lineToRelative(-2.703f, 2.614f) curveToRelative(-0.452f, 0.446f, -1.052f, 0.671f, -1.653f, 0.671f) reflectiveCurveToRelative(-1.203f, -0.225f, -1.663f, -0.674f) lineToRelative(-1.354f, -1.332f) curveToRelative(-0.395f, -0.387f, -0.4f, -1.02f, -0.014f, -1.414f) curveToRelative(0.386f, -0.395f, 1.019f, -0.401f, 1.414f, -0.014f) lineToRelative(1.354f, 1.331f) curveToRelative(0.144f, 0.142f, 0.38f, 0.139f, 0.522f, -0.002f) lineToRelative(2.713f, -2.624f) curveToRelative(0.397f, -0.381f, 1.031f, -0.37f, 1.414f, 0.029f) curveToRelative(0.382f, 0.398f, 0.369f, 1.031f, -0.029f, 1.414f) close() } } .build() return _boxCircleCheck!! } private var _boxCircleCheck: ImageVector? = null
1
Kotlin
0
5
cbd8b510fca0e5e40e95498834f23ec73cc8f245
3,962
icons
MIT License
app/src/main/java/com/galgolabs/earthweather/ui/notifications/SettingsFragment.kt
john10mwangi
559,924,562
false
{"Kotlin": 67223}
package com.galgolabs.earthweather.ui.notifications import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.preference.DropDownPreference import androidx.preference.Preference import androidx.preference.Preference.OnPreferenceChangeListener import androidx.preference.PreferenceFragmentCompat import androidx.preference.PreferenceManager import com.galgolabs.earthweather.R class SettingsFragment : PreferenceFragmentCompat(), OnPreferenceChangeListener { override fun onCreatePreferences(savedInstanceState: Bundle?, rootKey: String?) { setPreferencesFromResource(R.xml.settings_layout, rootKey) } // override fun onCreateView( // inflater: LayoutInflater, // container: ViewGroup?, // savedInstanceState: Bundle? // ): View { // super.onCreateView(inflater, container, savedInstanceState) // return view // } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) val sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this.requireActivity().applicationContext) val langDropDownPreference = preferenceManager.findPreference<DropDownPreference>("weather_lang") val unitsDropDownPreference = preferenceManager.findPreference<DropDownPreference>("weather_unit") val locationLangDropDownPreference = preferenceManager.findPreference<DropDownPreference>("location_lang") unitsDropDownPreference?.onPreferenceChangeListener = this langDropDownPreference?.onPreferenceChangeListener = this locationLangDropDownPreference?.onPreferenceChangeListener = this } override fun onPreferenceChange(preference: Preference, newValue: Any?): Boolean { when (preference.key){ "weather_lang" -> { displayValue(preference.key, newValue) } "weather_unit" -> { displayValue(preference.key, newValue) } "location_lang" -> { displayValue(preference.key, newValue) } } return true } private fun displayValue(key: String, newValue: Any?) { println("Preference : $key") println("Value : ${newValue.toString()}") } }
0
Kotlin
0
0
6055ee263a336de0585fb19e05ba2bd8730bbc11
2,357
EarthWeather
MIT License
tipsLib/src/main/java/com/optimizer/tooltips/animations/fading_in/FadeInAnimator.kt
maxim-petlyuk
157,140,329
false
{"Kotlin": 40607, "Java": 761}
package com.optimizer.tooltips.animations.fading_in import android.animation.ObjectAnimator import android.view.View import com.optimizer.tooltips.animations.BaseViewAnimator class FadeInAnimator : BaseViewAnimator() { public override fun prepare(target: View) { animatorAgent.playTogether(ObjectAnimator.ofFloat(target, "alpha", 0F, 1F)) } }
1
Kotlin
9
39
5d5b73487efc3af1648af882940661692c90ba9f
363
initial_tips
Apache License 2.0
app/src/main/java/com/udacity/shoestore/utils/Constant.kt
RicardoBravoA
309,849,757
false
null
package com.udacity.shoestore.utils object Constant { const val KEY = "KEY" }
0
Kotlin
0
0
608013e9a8f5598d09065e574444fdd102b0e3cd
82
ShoeStore
Apache License 2.0
telegramit-core/src/main/kotlin/org/botlaxy/telegramit/core/conversation/persistence/PersisteneContextSerializer.kt
vitaxa
258,866,097
false
null
package org.botlaxy.telegramit.core.conversation.persistence interface PersistenceContextSerializer { fun serialize(conversationContext: ConversationData): ByteArray fun deserialize(byteArray: ByteArray): ConversationData }
0
Kotlin
2
9
2e7fdb9e1e3edf2638d7dbb0895b4f8a10fbaa43
236
telegramit
Apache License 2.0
tmp/arrays/youTrackTests/7237.kt
DaniilStepanov
228,623,440
false
null
// Original bug: KT-25664 fun foo(x: UInt) { println(x) } fun main(args: Array<String>) { foo(0xffff_ffffu) // Prints 4294967295 ::foo.call(0xffff_ffffu) // Exception -- WRONG!!! }
1
null
11
1
602285ec60b01eee473dcb0b08ce497b1c254983
195
bbfgradle
Apache License 2.0
app/src/main/java/com/mapcode/AppViewModel.kt
mapcode-foundation
497,300,332
false
null
/* * Copyright (C) 2022, Stichting Mapcode Foundation (http://www.mapcode.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.mapcode import androidx.lifecycle.ViewModel import androidx.lifecycle.viewModelScope import com.mapcode.data.Keys import com.mapcode.data.PreferenceRepository import dagger.hilt.android.lifecycle.HiltViewModel import kotlinx.coroutines.flow.SharingStarted import kotlinx.coroutines.flow.StateFlow import kotlinx.coroutines.flow.map import kotlinx.coroutines.flow.stateIn import javax.inject.Inject @HiltViewModel class AppViewModel @Inject constructor( private val preferences: PreferenceRepository ) : ViewModel() { val showOnboarding: StateFlow<Boolean> = preferences.get(Keys.finishedOnboarding) .map { if (it == null) { true } else { !it } }.stateIn(viewModelScope, SharingStarted.Eagerly, false) fun onFinishOnboarding() { preferences.set(Keys.finishedOnboarding, true) } }
4
Kotlin
0
1
d153c3f357fb8528980db60f4e88e03380e4a6ed
1,544
mapcode-android-app
Apache License 2.0
app/src/main/java/com/example/mytasks/views/login/CreateActivity.kt
gustavohd18
251,103,944
false
null
package com.example.mytasks.views.login import android.content.Context import android.content.Intent import androidx.appcompat.app.AppCompatActivity import android.os.Bundle import android.widget.Toast import com.example.mytasks.R import com.example.mytasks.controllers.login.LoginController import kotlinx.android.synthetic.main.activity_create.* class CreateActivity : AppCompatActivity() { private lateinit var loginController: LoginController override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_create) loginController = LoginController(this) val shared = this.getSharedPreferences("mytasks", Context.MODE_PRIVATE) buttonCreate.setOnClickListener { val email = editEmail.text.toString() val password = editTextPassword.text.toString() val name = editTextName.text.toString() val result = loginController.insert(email, password, name) if (result) { Toast.makeText(this, "Conta criada com sucesso", Toast.LENGTH_LONG).show() shared.edit().putString("EMAIL_USER", email).apply() startActivity(Intent(this, LoginActivity::class.java)) } else { Toast.makeText(this, "Não foi possivel criar a conta", Toast.LENGTH_LONG).show() } } imageBack.setOnClickListener { startActivity(Intent(this, LoginActivity::class.java)) } } }
5
Kotlin
0
0
4386fe693002b535b084d0770e90777daeb4b01c
1,517
Mytasks
MIT License
dependency-plugin/src/main/kotlin/ch/addere/dga/dependencyplugin/DgaModelBuilder.kt
ryru
658,943,263
false
{"Kotlin": 107990}
package ch.addere.dga.dependencyplugin import ch.addere.dga.dependencymodel.DependencyModel import ch.addere.dga.dependencymodel.DependencyModelImpl import org.gradle.api.Project import org.gradle.tooling.provider.model.ToolingModelBuilder class DgaModelBuilder : ToolingModelBuilder { override fun canBuild(modelName: String): Boolean { return modelName == DependencyModel::class.java.name } override fun buildAll(modelName: String, project: Project): DependencyModel { val projectName = extractProjectName(project) val projectModules = extractProjectModules(project) val moduleDependencies = extractModuleDependencies(project, projectModules) return DependencyModelImpl(projectName, projectModules, moduleDependencies) } }
0
Kotlin
0
2
04724dd7073a36c42f6e290a96229e08f1276e1d
785
dependency-graph-analyser
MIT License
app/src/main/kotlin/com/chad/baserecyclerviewadapterhelper/activity/ItemClickActivity.kt
neo-turak
725,016,480
false
{"Kotlin": 333393}
package com.chad.baserecyclerviewadapterhelper.activity import android.os.Bundle import android.view.MotionEvent import android.view.View import androidx.recyclerview.widget.LinearLayoutManager import androidx.recyclerview.widget.RecyclerView import com.chad.baserecyclerviewadapterhelper.R import com.chad.baserecyclerviewadapterhelper.adapter.ItemClickAdapter import com.chad.baserecyclerviewadapterhelper.base.BaseActivity import com.chad.baserecyclerviewadapterhelper.entity.ClickEntity import com.chad.baserecyclerviewadapterhelper.utils.Tips import com.chad.library.adapter.base.BaseQuickAdapter import com.chad.library.adapter.base.listener.OnItemChildClickListener import com.chad.library.adapter.base.listener.OnItemChildLongClickListener import com.chad.library.adapter.base.listener.OnItemClickListener import com.chad.library.adapter.base.listener.OnItemLongClickListener /** * @author Allen */ class ItemClickActivity : BaseActivity() { private lateinit var mRecyclerView: RecyclerView private var adapter: ItemClickAdapter? = null override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_universal_recycler) setBackBtn() setTitle("ItemClickActivity Activity") mRecyclerView = findViewById(R.id.rv) mRecyclerView.setLayoutManager(LinearLayoutManager(this)) initAdapter() adapter!!.setOnItemClickListener(object : OnItemClickListener { override fun onItemClick(adapter: BaseQuickAdapter<*, *>, view: View, position: Int) { Tips.show("onItemClick $position") } }) adapter!!.setOnItemLongClickListener(object : OnItemLongClickListener { override fun onItemLongClick( adapter: BaseQuickAdapter<*, *>, view: View, position: Int ): Boolean { Tips.show("onItemLongClick $position") return true } }) adapter!!.setOnItemChildClickListener(object : OnItemChildClickListener { override fun onItemChildClick( adapter: BaseQuickAdapter<*, *>, view: View, position: Int ) { Tips.show("onItemChildClick $position") } }) adapter!!.setOnItemChildLongClickListener(object : OnItemChildLongClickListener { override fun onItemChildLongClick( adapter: BaseQuickAdapter<*, *>, view: View, position: Int ): Boolean { Tips.show("onItemChildLongClick $position") return true } }) } private fun initAdapter() { val data: MutableList<ClickEntity> = ArrayList() data.add(ClickEntity(ClickEntity.CLICK_ITEM_VIEW)) data.add(ClickEntity(ClickEntity.CLICK_ITEM_CHILD_VIEW)) data.add(ClickEntity(ClickEntity.LONG_CLICK_ITEM_VIEW)) data.add(ClickEntity(ClickEntity.LONG_CLICK_ITEM_CHILD_VIEW)) data.add(ClickEntity(ClickEntity.NEST_CLICK_ITEM_CHILD_VIEW)) adapter = ItemClickAdapter(data) adapter!!.animationEnable = true mRecyclerView!!.setAdapter(adapter) } override fun dispatchTouchEvent(ev: MotionEvent): Boolean { return super.dispatchTouchEvent(ev) } }
0
Kotlin
0
1
57aae064f1d0941410e96c7fece043c05b9709c4
3,413
BaseRecyclerViewAdapterHelper
MIT License
app/src/main/java/com/core/app/lifecycle/activity/BroadcastActivityLifecycle.kt
raxden
165,669,612
false
null
package com.core.app.lifecycle.activity import androidx.appcompat.app.AppCompatActivity import androidx.lifecycle.Lifecycle import androidx.lifecycle.OnLifecycleEvent import com.core.app.lifecycle.BaseActivityLifecycle import com.core.app.util.BroadcastManager import javax.inject.Inject class BroadcastActivityLifecycle @Inject internal constructor( activity: AppCompatActivity, private val broadcastManager: BroadcastManager ) : BaseActivityLifecycle(activity) { @OnLifecycleEvent(Lifecycle.Event.ON_CREATE) private fun onCreate() { broadcastManager.registerReceiver() (activity as? BroadcastManager.Listener)?.let { broadcastManager.addListener(it) } } @OnLifecycleEvent(Lifecycle.Event.ON_DESTROY) private fun onDestroy() { (activity as? BroadcastManager.Listener)?.let { broadcastManager.removeListener(it) } broadcastManager.unregisterReceiver() } }
1
null
1
1
9ad3b3d2fffdaa7abdf567320e8d6d9f98a67746
931
android-core
Apache License 2.0
src/kotlin/gtlp/groundmc/lobby/event/EntityEventListener.kt
PanikFaser
80,982,772
false
null
package gtlp.groundmc.lobby.event import gtlp.groundmc.lobby.LobbyMain import org.bukkit.event.EventHandler import org.bukkit.event.Listener import org.bukkit.event.entity.EntityDamageEvent /** * Created by Marv1 on 14.11.2016. */ class EntityEventListener : Listener { @EventHandler fun preventDamage(event: EntityDamageEvent) { if (event.entity.world == LobbyMain.hubWorld) { event.isCancelled = true } } }
0
Kotlin
0
0
e8c5be499a1f71c7c47209cacfc480d158b71c0a
452
GroundMCPlugin
Apache License 2.0
modules/conflate-api/src/main/kotlin/com/encodeering/conflate/experimental/api/Reducer.kt
encodeering
81,722,175
false
null
package com.encodeering.conflate.experimental.api /** * A reducer conflates the payload of an action with the given state into a state object, and shall not * perform any kind of side-effect, that influences the outcome of the returned state object. * * An implementation must guarantee, that he following conditions are met: * * - Invocations with same arguments lead to same results, regardless of the invocation or execution time. * ``` * assert reduce (A0, S0) == reduce (A0, S0) * ``` * - Modifications to any state do not affect other states, regardless of the invocation or execution time. * ``` * assert reduce (A0, S0) != reduce (A0, S0).apply { this.p += 1 } * assert reduce (A0, S0) != reduce (A0, S0.apply { this.p += 1 }) * ``` * * Any of the following items may cause a side-effect, that contravenes one of the stated condition: * * - I/O * - Service-Computation * - Date/Time * - Seeding * - ... * * Any part of the previous state may be freely recycled, as long as the related parts to do not violate the contract or * prevent any form of memory cleanup. * * ### Official documentation: * * - Actions describe the fact that something happened, but don't specify how the application's state changes in response. * This is the job of reducers. [http://redux.js.org/docs/basics/Reducers.html] * * - Given the same arguments, it should calculate the next state and return it. No surprises. No side effects. No API calls. No mutations. * Just a calculation. [http://redux.js.org/docs/basics/Reducers.html] * * ### Sample * * ``` * data class Sub (val number : Int) : Action * data class Add (val number : Int) : Action * * object : Reducer<Int> { * * override fun reduce (action : Action, state : Int) : Int { * return when (action) { * is Sub -> action.number - state * is Add -> action.number + state * else -> state * } * } * * } * ``` * * @param State defines the type of the state container * @author <NAME> - <EMAIL> */ interface Reducer<State> { /** * Defines the actual conflation strategy. * * @param action specifies an action, whose payload shall be merged with the application's state * @param state specifies a state container * @return a new state container */ fun reduce (action : Action, state : State) : State }
3
Kotlin
0
1
51fd2e4cee32e29bb72cd182611393d7f8420914
2,452
conflate
Apache License 2.0
app/src/main/java/com/singularity/ipcaplus/drawer/DrawerActivty.kt
DiogoAntunesOliveira
420,277,496
false
{"Kotlin": 288875, "JavaScript": 42028, "HTML": 29226, "CSS": 6623, "Processing": 1981}
package com.singularity.ipcaplus.drawer import android.content.BroadcastReceiver import android.content.ContentValues import android.content.ContentValues.TAG import android.content.Context import android.content.Intent import androidx.appcompat.app.AppCompatActivity import android.os.Bundle import android.util.Log import android.view.Menu import android.view.MenuItem import android.view.View import android.view.WindowManager import android.widget.ImageView import android.widget.TextView import android.widget.Toast import androidx.drawerlayout.widget.DrawerLayout import androidx.navigation.findNavController import androidx.navigation.ui.AppBarConfiguration import androidx.navigation.ui.navigateUp import androidx.navigation.ui.setupActionBarWithNavController import androidx.navigation.ui.setupWithNavController import com.google.android.material.navigation.NavigationView import com.google.android.material.snackbar.Snackbar import com.google.firebase.Timestamp import com.google.firebase.auth.ktx.auth import com.google.firebase.firestore.ktx.firestore import com.google.firebase.ktx.Firebase import com.singularity.ipcaplus.R import com.singularity.ipcaplus.WelcomeActivity import com.singularity.ipcaplus.utils.PreferenceHelper.email import com.singularity.ipcaplus.utils.PreferenceHelper.password import com.singularity.ipcaplus.utils.PreferenceHelper.userId import com.singularity.ipcaplus.chat.SearchActivity import com.singularity.ipcaplus.cryptography.encryptMeta import com.singularity.ipcaplus.cryptography.metaGenrateKey import com.singularity.ipcaplus.databinding.ActivityDrawerActivtyBinding import com.singularity.ipcaplus.models.Chat import com.singularity.ipcaplus.models.Message import kotlin.random.Random import androidx.core.view.ViewCompat import androidx.core.app.ActivityOptionsCompat import com.google.android.gms.tasks.OnCompleteListener import com.google.firebase.messaging.FirebaseMessaging import com.singularity.ipcaplus.AddButtonActivity import com.singularity.ipcaplus.chat.CreateChatActivity import com.singularity.ipcaplus.databinding.ActivityProfileBinding import com.singularity.ipcaplus.models.EventCalendar import com.singularity.ipcaplus.utils.* import com.singularity.ipcaplus.utils.Backend.getAllTokens import com.singularity.ipcaplus.utils.Backend.postTokenAddress class DrawerActivty : AppCompatActivity() { private lateinit var appBarConfiguration: AppBarConfiguration private lateinit var binding: ActivityDrawerActivtyBinding private lateinit var binding2: ActivityProfileBinding val db = Firebase.firestore override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) binding = ActivityDrawerActivtyBinding.inflate(layoutInflater) setContentView(binding.root) binding.navView.getHeaderView(0).findViewById<ImageView>(R.id.imageView_profile) .setOnClickListener { val intent = Intent(this, ProfileActivity::class.java) intent.putExtra("userId", Firebase.auth.currentUser!!.uid) startActivity(intent) } Utilis.getFile(this, "profilePictures/" + Firebase.auth.uid + ".png", "png") { bitmap -> binding.navView.getHeaderView(0).findViewById<ImageView>(R.id.imageView_profile) .setImageBitmap(bitmap) } if (!UserLoggedIn.name.isNullOrEmpty()) { val name = Utilis.getFirstAndLastName(UserLoggedIn.name!!) binding.navView.getHeaderView(0).findViewById<TextView>(R.id.textView3).text = name binding.navView.getHeaderView(0).findViewById<TextView>(R.id.emailTextView).text = UserLoggedIn.email } // Getting device FCM token FirebaseMessaging.getInstance().token.addOnCompleteListener(OnCompleteListener { task -> if (!task.isSuccessful) { Log.w(ContentValues.TAG, "Fetching FCM registration token failed", task.exception) return@OnCompleteListener } // Get new FCM registration token var fcmToken = task.result // Posting FCM token address on firebase postTokenAddress(fcmToken.toString(), Firebase.auth.currentUser!!.uid) }) setSupportActionBar(binding.appBarMain.toolbar) window.setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN) binding.appBarMain.fabAddChat.setOnClickListener { view -> Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG) .setAction("Action", null).show() } val drawerLayout: DrawerLayout = binding.drawerLayout val navView: NavigationView = binding.navView val navController = findNavController(R.id.nav_host_fragment_content_main) // Passing each menu ID as a set of Ids because each // menu should be considered as top level destinations. appBarConfiguration = AppBarConfiguration( setOf( R.id.nav_home ), drawerLayout ) // Generate key for chats val keygen = metaGenrateKey() // Criação de Chat binding.appBarMain.fabAddChat.setOnClickListener { val intent = Intent(this, AddButtonActivity::class.java) startActivity(intent) } // Log Out Button binding.logoutLayout.setOnClickListener { val prefs = PreferenceHelper.customPreference(this, "User_data") prefs.password = <PASSWORD> prefs.email = null prefs.userId = null val intent = Intent(this, WelcomeActivity::class.java) startActivity(intent) } // Passing each fragment ID as a set of Ids setupActionBarWithNavController(navController, appBarConfiguration) navView.setupWithNavController(navController) // Vou buscar os tokens do utilizador FirebaseMessaging.getInstance().token.addOnCompleteListener(OnCompleteListener { task -> if (!task.isSuccessful) { Log.w(TAG, "Fetching FCM registration token failed", task.exception) return@OnCompleteListener } // Get new FCM registration token val token = task.result }) /*FirebaseMessaging.getInstance().token.addOnCompleteListener(OnCompleteListener { task -> if (!task.isSuccessful) { Log.w(ContentValues.TAG, "Fetching FCM registration token failed", task.exception) return@OnCompleteListener } // Get new FCM registration token var fcmToken = task.result // Log and toast Log.d(ContentValues.TAG, "O FCM é $fcmToken") Toast.makeText(this, "O FCM é $fcmToken", Toast.LENGTH_SHORT).show() }) db.collection("profile").document(Firebase.auth.currentUser!!.uid).collection("tokens") .add(message.toHash()) .addOnSuccessListener { documentReference -> Log.d(ContentValues.TAG, "DocumentSnapshot added with ID: ${documentReference.id}") } .addOnFailureListener { e -> Log.w(ContentValues.TAG, "Error adding document", e) } binding.editTextMessage.text.clear()*/ } /* Refresh Activity Content */ override fun onResume() { super.onResume() Utilis.getFile(this, "profilePictures/" + Firebase.auth.uid!! + ".png", "png") { bitmap -> binding.navView.getHeaderView(0).findViewById<ImageView>(R.id.imageView_profile) .setImageBitmap(bitmap) } } override fun onCreateOptionsMenu(menu: Menu): Boolean { // Inflate the menu; this adds items to the action bar if it is present. menuInflater.inflate(R.menu.drawer, menu) return true } override fun onSupportNavigateUp(): Boolean { val navController = findNavController(R.id.nav_host_fragment_content_main) return navController.navigateUp(appBarConfiguration) || super.onSupportNavigateUp() } override fun onOptionsItemSelected(item: MenuItem): Boolean { // Handle item selection return when (item.itemId) { R.id.search_btn -> { val intent = Intent(this, SearchActivity::class.java) startActivity(intent) true } else -> super.onOptionsItemSelected(item) } } }
0
Kotlin
1
5
0f2d68b73654d7b2a820ce6da04812e8477672b5
8,611
ipca_plus
MIT License
src/main/kotlin/dev/turingcomplete/intellijdevelopertoolsplugin/_internal/tool/editor/PsiKotlinUtils.kt
marcelkliemannel
605,260,384
false
{"Kotlin": 729243, "HTML": 1028}
package dev.turingcomplete.intellijdevelopertoolsplugin._internal.tool.editor import com.intellij.openapi.actionSystem.AnActionEvent import com.intellij.openapi.actionSystem.CommonDataKeys import com.intellij.openapi.util.TextRange import com.intellij.psi.PsiElement import com.intellij.psi.util.elementType import dev.turingcomplete.intellijdevelopertoolsplugin._internal.common.EditorUtils.getSelectedText import org.jetbrains.kotlin.lexer.KtTokens /** * Some code parts of this class are only available of the optional dependency * `org.jetbrains.kotlin` is available. */ internal object PsiKotlinUtils { // -- Variables --------------------------------------------------------------------------------------------------- // private val textElementKtTokens = setOf(KtTokens.REGULAR_STRING_PART, KtTokens.IDENTIFIER) // -- Initialization ---------------------------------------------------------------------------------------------- // // -- Exported Methods -------------------------------------------------------------------------------------------- // fun getTextFromStringValueOrIdentifier(e: AnActionEvent): Pair<String, TextRange>? { val psiFile = e.getData(CommonDataKeys.PSI_FILE) ?: return null val editor = e.getData(CommonDataKeys.EDITOR) ?: return null if (editor.getSelectedText() != null) { return null } val psiElement = psiFile.findElementAt(editor.caretModel.offset) ?: return null return getTextFromStringValueOrIdentifier(psiElement)?.let { it to psiElement.textRange } } fun getTextFromStringValueOrIdentifier(psiElement: PsiElement): String? { return if (textElementKtTokens.contains(psiElement.elementType)) { psiElement.text } else { null } } fun getTextFromStringValue(e: AnActionEvent): Pair<String, TextRange>? { val psiFile = e.getData(CommonDataKeys.PSI_FILE) ?: return null val editor = e.getData(CommonDataKeys.EDITOR) ?: return null if (editor.getSelectedText() != null) { return null } val psiElement = psiFile.findElementAt(editor.caretModel.offset) ?: return null return getTextFromStringValue(psiElement)?.let { it to psiElement.textRange } } fun getTextFromStringValue(psiElement: PsiElement): String? { return if (psiElement.elementType == KtTokens.REGULAR_STRING_PART) { psiElement.text } else { null } } // -- Private Methods --------------------------------------------------------------------------------------------- // // -- Inner Type -------------------------------------------------------------------------------------------------- // }
23
Kotlin
14
178
dc83a42ad60769981162c4634e1cc719f986380f
2,641
intellij-developer-tools-plugin
Apache License 2.0
core/src/io/github/doorbash/agario/util/color.kt
doorbash
294,905,107
false
null
package io.github.doorbash.agario.util import com.badlogic.gdx.graphics.Color fun Color.toInt(): Int { return ((255 * r).toInt() shl 24) or ((255 * g).toInt() shl 16) or ((255 * b).toInt() shl 8) or ((255 * a).toInt()) }
0
Kotlin
1
3
8312ba5ebabc2dca183fe3a7dcae72bbbaab31d0
226
agar-io
MIT License
app/src/main/java/com/example/famreen/application/items/NoteItem.kt
GinKukuruza
305,210,621
false
null
package com.example.famreen.application.items import android.os.Parcel import android.os.Parcelable import androidx.room.Entity import androidx.room.PrimaryKey import com.fasterxml.jackson.annotation.JsonProperty import com.google.firebase.database.Exclude import java.util.HashMap @Entity open class NoteItem : Parcelable{ @PrimaryKey(autoGenerate = true) var id = 0 var mTime: String? = null var mDescription: String? = null var mTitle: String? = null @JsonProperty("important") var mImportant: Boolean = false var mTag: String? = null constructor() protected constructor(parcel: Parcel) { id = parcel.readInt() mTime = parcel.readString() mDescription = parcel.readString() mTitle = parcel.readString() mImportant = parcel.readByte().toInt() != 0 mTag = parcel.readString() } @Exclude fun toMap(): Map<String, Any?> { val result: MutableMap<String, Any?> = HashMap() result["id"] = id result["time"] = mTime result["title"] = mTitle result["description"] = mDescription result["tag"] = mTag result["important"] = mImportant return result } override fun describeContents(): Int { return 0 } override fun writeToParcel(dest: Parcel, flags: Int) { dest.writeInt(id) dest.writeString(mTime) dest.writeString(mDescription) dest.writeString(mTitle) dest.writeByte((if (mImportant) 1 else 0).toByte()) dest.writeString(mTag) } companion object CREATOR : Parcelable.Creator<NoteItem> { override fun createFromParcel(parcel: Parcel): NoteItem { return NoteItem(parcel) } override fun newArray(size: Int): Array<NoteItem?> { return arrayOfNulls(size) } } }
0
Kotlin
0
1
ad6c16bf8c7ec522a64ec7d4a59a990c4ee2adf2
1,861
famreen
Apache License 2.0
src/commonMain/kotlin/dev/epicsquid/surrealkt/connection/client.kt
EpicSquid
611,923,051
false
null
package dev.epicsquid.surrealkt.connection import io.ktor.client.* import io.ktor.client.plugins.websocket.* import io.ktor.http.* import io.ktor.serialization.kotlinx.* import kotlinx.serialization.json.Json fun client() = HttpClient { install(WebSockets) { contentConverter = KotlinxWebsocketSerializationConverter(Json) pingInterval = 30 } }
1
Kotlin
0
1
dfa633169538318305020a24be7e6032dfd6fd38
352
surrealkt
Apache License 2.0
data/remote/src/test/java/com/ds/ciceksepeti/remote/ProductServiceTest.kt
developersancho
371,180,136
false
null
package com.ds.ciceksepeti.remote import android.os.Build import com.ds.ciceksepeti.remote.service.ProductService import kotlinx.coroutines.runBlocking import org.junit.Assert import org.junit.Test import org.junit.runner.RunWith import org.koin.core.component.inject import org.robolectric.RobolectricTestRunner import org.robolectric.annotation.Config @RunWith(RobolectricTestRunner::class) @Config(sdk = [Build.VERSION_CODES.O_MR1]) class ProductServiceTest : BaseServiceTest() { private val service by inject<ProductService>() @Test fun getProducts() = runBlocking { val detailList = listOf(2007217) val checkList = listOf(2007124) val priceList = listOf(1, 2, 3) val response = service.getProducts(detailList, checkList, priceList) println(response.result?.data?.products?.firstOrNull()?.name) println(response.result?.data?.products?.firstOrNull()?.installmentText) Assert.assertEquals(2787616, response.result?.data?.products?.firstOrNull()?.id) } @Test fun getProductsNoFilters() = runBlocking { val detailList = listOf<Int>() val checkList = listOf<Int>() val priceList = listOf<Int>() val response = service.getProducts(detailList, checkList, priceList) println(response.result?.data?.products?.firstOrNull()?.name) println(response.result?.data?.products?.firstOrNull()?.installmentText) Assert.assertEquals(2787616, response.result?.data?.products?.firstOrNull()?.id) } }
0
Kotlin
0
0
1ad877d404b6c6777db0d23b50d8b832b2a89d52
1,530
CicekSepeti-Challenge
Apache License 2.0
Application/core/core-logger/src/main/java/com/istudio/core_logger/data/repository/LoggerRepository.kt
devrath
570,594,617
false
{"Kotlin": 238294}
package com.istudio.core_logger.data.repository import com.istudio.core_logger.domain.LoggerFeature open class LoggerRepository( private val loggerFeature: LoggerFeature ) { open fun d(featureName: String?, msg: String?) { loggerFeature.d(featureName, msg) } open fun e(featureName: String?, msg: String?) { loggerFeature.e(featureName, msg) } open fun w(featureName: String?, msg: String?) { loggerFeature.w(featureName, msg) } open fun v(featureName: String?, msg: String?) { loggerFeature.v(featureName, msg) } open fun i(featureName: String?, msg: String?) { loggerFeature.i(featureName, msg) } }
0
Kotlin
3
6
17d03b535e2ced992b97cc1e3a6d40c5393afded
628
Distance-Tracker
Apache License 2.0
demokotlin/src/main/java/com/sankuai/waimai/router/demo/kotlin/TestViewModel.kt
meituan
144,974,148
false
null
package com.sankuai.waimai.router.demo.kotlin import android.content.Context import androidx.lifecycle.ViewModel import androidx.lifecycle.viewModelScope import com.sankuai.waimai.router.common.DefaultUriRequest import com.sankuai.waimai.router.demo.lib2.ToastUtils import com.wmrouter.adapter.coroutines.await import kotlinx.coroutines.CoroutineExceptionHandler import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.launch import kotlinx.coroutines.withContext import kotlin.coroutines.CoroutineContext /** * * @Author LiABao * @Since 2021/6/12 * */ class TestViewModel : ViewModel() { private val handler = CoroutineExceptionHandler { _: CoroutineContext, throwable: Throwable -> ToastUtils.showToast("跳转失败") } fun route(context: Context) { viewModelScope.launch(handler) { val response = DefaultUriRequest(context, JUMP_WITH_REQUEST) .activityRequestCode(100) .putExtra(INTENT_TEST_INT, 1) .putExtra(INTENT_TEST_STR, "str").await() ToastUtils.showToast(response.context, "跳转成功") } } companion object { const val JUMP_WITH_REQUEST = "/jump_with_request" const val INTENT_TEST_INT = "test_int" const val INTENT_TEST_STR = "test_str" } }
29
null
333
2,217
7c05c1050781412ee66931fffaf6e06e3e8abf52
1,305
WMRouter
Apache License 2.0
app/src/main/java/com/nguyen/shelter/ui/main/adapters/UserPagerAdapter.kt
dtnguyn
292,352,460
false
null
package com.nguyen.shelter.ui.main.adapters import androidx.fragment.app.Fragment import androidx.paging.ExperimentalPagingApi import androidx.viewpager2.adapter.FragmentStateAdapter import com.nguyen.shelter.ui.main.fragments.RentFragment import com.nguyen.shelter.ui.main.fragments.SaleFragment import com.nguyen.shelter.ui.main.fragments.SavedFragment import com.nguyen.shelter.ui.main.fragments.UserBlogFragment import kotlinx.coroutines.ExperimentalCoroutinesApi @ExperimentalCoroutinesApi @ExperimentalPagingApi class UserPagerAdapter (fragment: Fragment) : FragmentStateAdapter(fragment){ private val savedFragment = SavedFragment() private val userBlogFragment = UserBlogFragment() override fun getItemCount(): Int { return 2 } override fun createFragment(position: Int): Fragment { return when(position){ 0 -> savedFragment 1 -> userBlogFragment else -> savedFragment } } }
0
Kotlin
0
2
39bb09297edd9f999ed2710ee51608a53254aa8d
974
Shelter
The Unlicense
src/main/kotlin/br/com/zupacademy/witer/Application.kt
witermendonca
386,655,925
true
{"Kotlin": 36748, "Smarty": 2172, "Dockerfile": 161}
package br.com.zupacademy.witer import io.micronaut.runtime.Micronaut.* fun main(args: Array<String>) { build() .args(*args) .packages("br.com.zupacademy.witer") .start() }
0
Kotlin
0
0
fd46c21d5dac1b49085bfb03f7012211397d1942
185
orange-talents-05-template-pix-keymanager-rest
Apache License 2.0
core/src/main/kotlin/ru/mobileup/core/network/ErrorHandlingCallAdapterFactory.kt
MobileUpLLC
495,305,519
false
{"Kotlin": 82696}
package ru.mobileup.core.network import retrofit2.Call import retrofit2.CallAdapter import retrofit2.Retrofit import java.lang.reflect.ParameterizedType import java.lang.reflect.Type class ErrorHandlingCallAdapterFactory : CallAdapter.Factory() { override fun get( returnType: Type, annotations: Array<Annotation>, retrofit: Retrofit ): CallAdapter<*, *>? { if (Call::class.java != getRawType(returnType)) return null check(returnType is ParameterizedType) {} return ErrorHandlingCallAdapter<Any>(responseType = getParameterUpperBound(0, returnType)) } }
0
Kotlin
1
3
4f486b7a96775d262e8cd179ef70d7f0e2531f0b
617
Push-Notifications-Android
MIT License
old_srcs/playground/src/test/kotlin/practice/primes/PrimeNumbersTests.kt
JetBrains
52,014,223
false
null
package practice.primes import org.junit.Test import org.junit.Assert.assertArrayEquals import org.junit.Rule import org.junit.rules.ExpectedException class PrimeNumbersTests { @get:Rule val thrown: ExpectedException = ExpectedException.none(); @Test fun notInRange() { val n = 1 thrown.expect(NotInRangeException::class.java) thrown.expectMessage(getErrorMessage(n)) getPrimes(n) } @Test fun notInRange2() { val n = 1001 thrown.expect(NotInRangeException::class.java) thrown.expectMessage(getErrorMessage(n)) getPrimes(n) } @Test fun lastIsPrime() { val expected = intArrayOf(2, 3, 5, 7, 11, 13, 17, 19, 23, 29) val actual = getPrimes(29) assertArrayEquals(expected, actual) } @Test fun lastIsPrime2() { val expected = intArrayOf(2) val actual = getPrimes(2) assertArrayEquals(expected, actual) } @Test fun lastIsNotPrime() { val expected = intArrayOf(2, 3, 5, 7, 11, 13, 17, 19, 23) val actual = getPrimes(25) assertArrayEquals(expected, actual) } }
1
Kotlin
7
27
8db0eae79465d3068081f5d1284b319ea7d65881
1,146
email-parser
Apache License 2.0
app/src/main/java/io/github/artemnazarov/winesapp/data/WineDao.kt
temqua
545,973,712
false
null
package io.github.artemnazarov.winesapp.data import androidx.room.Dao import androidx.room.Delete import androidx.room.Insert import androidx.room.OnConflictStrategy.ABORT import androidx.room.Query import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.StateFlow @Dao interface WineDao { @Query("SELECT * FROM wines") fun getAll(): Flow<List<Wine>> @Query("SELECT * FROM wines WHERE wines.name LIKE :wine ") fun findByName(wine: String): Flow<List<Wine>> @Query("SELECT * FROM wines WHERE color LIKE '%red%'") fun getAllRed(): Flow<List<Wine>> @Query("SELECT * FROM wines WHERE color LIKE '%rose%'") fun getAllRose(): Flow<List<Wine>> @Query("SELECT * FROM wines WHERE color LIKE '%white%'") fun getAllWhite(): Flow<List<Wine>> @Query("SELECT * FROM wines WHERE color LIKE '%sparkling%'") fun getAllSparkling(): Flow<List<Wine>> @Query("SELECT * FROM wines WHERE color LIKE '%dessert%'") fun getAllDessert(): Flow<List<Wine>> @Query("SELECT * FROM wines WHERE color LIKE '%port%'") fun getAllPort(): Flow<List<Wine>> @Insert(onConflict = ABORT) suspend fun insert(vararg wines: Wine) @Insert(onConflict = ABORT) suspend fun insertAll(wines: List<Wine>) @Delete suspend fun delete(wine: Wine) @Query("DELETE FROM wines WHERE id > 0") suspend fun deleteAll() }
0
Kotlin
0
0
376ce2de025eba664196915a7b5c4975705a2b49
1,380
WinesApp
MIT License
src/main/kotlin/behavioralPatterns/visitor/Visitor.kt
takaakit
138,280,665
false
null
package behavioralPatterns.visitor // ˅ // ˄ interface Visitor { fun visit(file: File) fun visit(directory: Directory) // ˅ // ˄ } // ˅ // ˄
0
Kotlin
0
9
ce3f7ca0ac87a9e09c1bcce5092922187c71d3bf
168
design-pattern-examples-in-kotlin
Creative Commons Zero v1.0 Universal
src/main/kotlin/com/jobbble/user/Skill.kt
alexandrustoica
160,933,578
false
null
package com.jobbble.user import com.fasterxml.jackson.annotation.JsonIgnore import com.fasterxml.jackson.annotation.JsonIgnoreProperties import com.fasterxml.jackson.annotation.JsonProperty import org.bson.types.ObjectId import org.springframework.data.annotation.Id import org.springframework.data.annotation.PersistenceConstructor import org.springframework.data.mongodb.core.mapping.Document @Document @JsonIgnoreProperties(ignoreUnknown = true) data class Skill @PersistenceConstructor constructor( @JsonIgnore @Id val id: ObjectId = ObjectId(), private val value: String) { @JsonProperty("id") fun id(): String = id.toString() }
0
Kotlin
0
0
7ac44b785909c4117db09e45d222ab0d97536006
659
jobbble.engine
MIT License
src/main/kotlin/ch/leadrian/samp/kamp/fcnpcwrapper/constants/MoveSpeed.kt
Double-O-Seven
174,439,714
false
null
package ch.leadrian.samp.kamp.fcnpcwrapper.constants import ch.leadrian.samp.kamp.core.api.constants.ConstantValue import ch.leadrian.samp.kamp.core.api.constants.ConstantValueRegistry import ch.leadrian.samp.kamp.fcnpcwrapper.FCNPCConstants enum class MoveSpeed(override val value: Float) : ConstantValue<Float> { AUTO(FCNPCConstants.MOVE_SPEED_AUTO), WALK(FCNPCConstants.MOVE_SPEED_WALK), RUN(FCNPCConstants.MOVE_SPEED_RUN), SPRINT(FCNPCConstants.MOVE_SPEED_SPRINT); companion object : ConstantValueRegistry<Float, MoveSpeed>(MoveSpeed.values()) }
0
Kotlin
0
0
43835b06c08bad0a83f4702e685e31e826744023
572
kamp-fcnpc-wrapper
Apache License 2.0
app/src/main/java/com/danc/watchout/presentation/screens/PeopleStarDetails.kt
Danc-0
570,116,933
false
{"Kotlin": 96005}
package com.danc.watchout.presentation.screens import androidx.compose.foundation.BorderStroke import androidx.compose.foundation.border import androidx.compose.foundation.clickable import androidx.compose.foundation.layout.* import androidx.compose.foundation.lazy.LazyRow import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.material.* import androidx.compose.material.icons.Icons import androidx.compose.material.icons.filled.ArrowBack import androidx.compose.runtime.Composable import androidx.compose.runtime.collectAsState import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.graphics.Color import androidx.compose.ui.res.painterResource import androidx.compose.ui.text.TextStyle import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.text.style.TextDecoration import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.sp import androidx.hilt.navigation.compose.hiltViewModel import androidx.navigation.NavController import com.danc.watchout.R import com.danc.watchout.domain.models.PeoplesResult import com.danc.watchout.domain.models.SpecificFilmResult import com.danc.watchout.presentation.viewmodels.PeopleViewModel import com.danc.watchout.presentation.viewmodels.SpecificFilmViewModel import kotlin.random.Random @Composable fun PeopleStarDetails( viewModel: PeopleViewModel, navController: NavController ) { val peopleDetails = viewModel.peopleResult val specificFilmViewModel: SpecificFilmViewModel = hiltViewModel() specificFilmViewModel.loadFilms(peopleDetails.value?.films!!) val viewState = specificFilmViewModel.state.collectAsState() val scaffoldState = rememberScaffoldState() Scaffold( scaffoldState = scaffoldState, topBar = { TopBar(navController) }, content = { Column( Modifier.padding(it) ) { DetailsCard(peopleDetails.value!!) if (viewState.value.specificFilm != null) { FilmCard( viewState.value.specificFilm ) } } } ) } @Composable fun TopBar(navController: NavController) { Row( modifier = Modifier .padding(bottom = 10.dp) .fillMaxWidth(), horizontalArrangement = Arrangement.Start, verticalAlignment = Alignment.CenterVertically, content = { IconButton(onClick = { navController.popBackStack() }) { Icon(Icons.Filled.ArrowBack, contentDescription = "Back Arrow") } Text( text = "Character Details", style = TextStyle( fontWeight = FontWeight.Bold ) ) }, ) } @Composable fun DetailsCard(peopleDetails: PeoplesResult) { Card( modifier = Modifier .fillMaxWidth() .padding(start = 15.dp, end = 15.dp), elevation = 20.dp, backgroundColor = MaterialTheme.colors.onBackground, shape = RoundedCornerShape(10.dp) ) { Column( modifier = Modifier.padding(10.dp) ) { Row { Text( text = "Name:".uppercase(), style = TextStyle(color = MaterialTheme.colors.background) ) Spacer(modifier = Modifier.padding(2.dp)) Text( text = peopleDetails.name.uppercase(), style = TextStyle( color = MaterialTheme.colors.background, fontWeight = FontWeight.Bold ) ) } Spacer(modifier = Modifier.padding(2.dp)) Row { Text( text = "DOB:".uppercase(), style = TextStyle(color = MaterialTheme.colors.background) ) Spacer(modifier = Modifier.padding(2.dp)) Text( text = peopleDetails.dateOfBirth, style = TextStyle( color = MaterialTheme.colors.background, fontWeight = FontWeight.Bold ) ) } Spacer(modifier = Modifier.padding(2.dp)) Row { Text( text = "Gender:".uppercase(), style = TextStyle(color = MaterialTheme.colors.background) ) Spacer(modifier = Modifier.padding(2.dp)) Text( text = peopleDetails.gender.uppercase(), style = TextStyle( color = MaterialTheme.colors.background, fontWeight = FontWeight.Bold ) ) } Divider( modifier = Modifier.padding(top = 5.dp, bottom = 5.dp), thickness = 1.dp, color = MaterialTheme.colors.background ) Row( modifier = Modifier .fillMaxWidth(), horizontalArrangement = Arrangement.SpaceBetween ) { PeopleDescription(title = "Height", description = peopleDetails.height) PeopleDescription(title = "Mass", description = peopleDetails.height) PeopleDescription(title = "Hair Color", description = peopleDetails.hairColor) PeopleDescription(title = "Eye Color", description = peopleDetails.eyeColor) } } } } @Composable fun PeopleDescription(title: String, description: String) { Column( verticalArrangement = Arrangement.Center, horizontalAlignment = Alignment.CenterHorizontally ) { Text( text = title.uppercase(), style = TextStyle(color = MaterialTheme.colors.background) ) Text( text = description.uppercase(), style = TextStyle( color = MaterialTheme.colors.background, fontWeight = FontWeight.Bold ) ) } } @Composable fun FilmCard( films: List<SpecificFilmResult>? ) { Column( modifier = Modifier.padding( 10.dp ) ) { Text( text = "Films", style = TextStyle( color = MaterialTheme.colors.onBackground, fontWeight = FontWeight.Bold ) ) LazyRow { items(films?.size!!) { index -> val details = films[index] FilmItem(filmTitle = details.title, filmDescription = details.openingCrawl) } } } } @Composable fun FilmItem(filmTitle: String?, filmDescription: String?) { Box( modifier = Modifier .padding(5.dp) .border( border = BorderStroke(width = 1.dp, color = MaterialTheme.colors.onSurface), shape = RoundedCornerShape(10.dp) ), ) { Column( modifier = Modifier.padding(10.dp) ) { Text( text = filmTitle!!.uppercase(), style = TextStyle( fontWeight = FontWeight.SemiBold, fontSize = 15.sp, textDecoration = TextDecoration.Underline ) ) Text(text = filmDescription!!) } } }
0
Kotlin
0
0
8301e6d22e20aa3a13501700ab6bd511b2fec885
7,614
WATCHOUT
MIT License
src/main/kotlin/g2101_2200/s2160_minimum_sum_of_four_digit_number_after_splitting_digits/Solution.kt
javadev
190,711,550
false
{"Kotlin": 4909193, "TypeScript": 50446, "Python": 3646, "Shell": 994}
package g2101_2200.s2160_minimum_sum_of_four_digit_number_after_splitting_digits // #Easy #Math #Sorting #Greedy #2023_06_26_Time_133_ms_(88.24%)_Space_34.5_MB_(88.24%) @Suppress("NAME_SHADOWING") class Solution { fun minimumSum(num: Int): Int { var num = num val digit = IntArray(4) var cur = 0 while (num > 0) { digit[cur++] = num % 10 num /= 10 } digit.sort() val num1 = digit[0] * 10 + digit[2] val num2 = digit[1] * 10 + digit[3] return num1 + num2 } }
0
Kotlin
20
43
62708bc4d70ca2bfb6942e4bbfb4c64641e598e8
564
LeetCode-in-Kotlin
MIT License
base/src/main/java/co/base/search/SearchRepositoryImpl.kt
p-vincen-t
238,182,140
false
{"Gradle": 21, "XML": 215, "Java Properties": 2, "Shell": 1, "Text": 2, "Ignore List": 18, "Batchfile": 1, "Markdown": 1, "Proguard": 10, "YAML": 2, "Java": 13, "Kotlin": 236, "HTML": 2, "INI": 9, "JSON": 1}
/* * Copyright 2020, {{App}} * Licensed under the Apache License, Version 2.0, "{{App}} Inc". * 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 co.base.search import android.content.Context import android.util.ArrayMap import androidx.lifecycle.LiveData import androidx.lifecycle.MutableLiveData import co.app.common.addValue import co.app.common.search.Search import co.app.common.search.SearchRepository import co.app.common.search.SearchResult import co.base.DataScope import co.base.RepoScope import promise.commons.data.log.LogUtil import promise.commons.tx.AsyncEither import promise.commons.tx.Either import promise.model.Repository import java.lang.ref.WeakReference import javax.inject.Inject @DataScope class SearchRepositoryImpl @Inject constructor( private val searchRepo: Repository<Search> ) : SearchRepository() { private val recentSearchResultsMutable: MutableLiveData<Pair<Pair<String, Int>, List<SearchResult>>> = MutableLiveData() private val recentSearchMutable: MutableLiveData<List<Search>> = MutableLiveData() override val searchResults: LiveData<Pair<Pair<String, Int>, List<SearchResult>>> get() = recentSearchResultsMutable override fun recentSearchQueries(): LiveData<List<Search>> = recentSearchMutable override fun searchSuggestions(search: Search): LiveData<List<Search>> { TODO("Not yet implemented") } override fun search(context: WeakReference<Context>, search: Search): Either<Any> = AsyncEither { resolve, reject -> if (searchRepositories.isEmpty()) { reject(Exception("Search not ready, data sources not registered")) return@AsyncEither } resolve(Any()) LogUtil.e(TAG, "searching ${searchRepositories.size} repositories") val lock = Any() searchRepositories.forEach { repository -> repository.onSearch(context, search).yield({ result -> synchronized(lock) { if (result == null) return@synchronized recentSearchResultsMutable.postValue(result) } }, { reject(it) }) } recentSearchMutable.addValue(search) searchRepo.save(search, null) } override fun clearHistory(): Either<Boolean> = AsyncEither { resolve, reject -> searchRepo.clear(null, { recentSearchMutable.postValue(listOf()) resolve(true) }, { reject(it) }) } companion object { val TAG: String = LogUtil.makeTag(SearchRepositoryImpl::class.java) } }
1
null
1
1
74d1af99f1a563b6aa5ace72eb303e055c6ace5a
3,147
android-template
Apache License 2.0
Structural/Proxy/ProtectionProxy.kt
evabishchevich
166,403,981
true
{"Swift": 24470, "Kotlin": 21334}
// Implementation interface File { fun read(name: String) } class NormalFile: File { override fun read(name: String) = println("Reading file: $name") } class SecuredFile: File { val normalFile = NormalFile() var password: String = "" override fun read(name: String) { if (password == "<PASSWORD>") { println("Password is correct: $password") normalFile.read(name) } else { println("Incorrect password. Access denied!") } } } // Usage fun main(args: Array<String>) { val securedFile = SecuredFile() securedFile.read("readme.md") securedFile.password = "<PASSWORD>" securedFile.read("readme.md") }
0
Swift
0
1
7055623a8f734b51721944e0592b459766b00d17
702
Design-Patterns-In-Swift-Compare-Kotlin
MIT License