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 |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|
protocol/kotlin/src/solarxr_protocol/datatypes/Temperature.kt | SlimeVR | 456,320,520 | false | {"Rust": 790111, "Java": 650829, "TypeScript": 507384, "C++": 434772, "Kotlin": 356034, "PowerShell": 959, "Shell": 910, "Nix": 587} | // automatically generated by the FlatBuffers compiler, do not modify
package solarxr_protocol.datatypes
import java.nio.*
import kotlin.math.sign
import com.google.flatbuffers.*
/**
* Temperature in degrees celsius
*/
@Suppress("unused")
class Temperature : Struct() {
fun __init(_i: Int, _bb: ByteBuffer) {
__reset(_i, _bb)
}
fun __assign(_i: Int, _bb: ByteBuffer) : Temperature {
__init(_i, _bb)
return this
}
val temp : Float get() = bb.getFloat(bb_pos + 0)
companion object {
@JvmStatic
fun createTemperature(builder: FlatBufferBuilder, temp: Float) : Int {
builder.prep(4, 4)
builder.putFloat(temp)
return builder.offset()
}
}
}
| 11 | Rust | 20 | 19 | 60f3146f914e2a9e35d759a8146be213e715d6d2 | 754 | SolarXR-Protocol | Apache License 2.0 |
app/src/main/java/ar/com/wolox/android/example/ui/viewpager/request/RequestPresenter.kt | Wolox | 32,873,198 | false | null | package ar.com.wolox.android.example.ui.viewpager.request
import ar.com.wolox.android.example.model.Post
import ar.com.wolox.android.example.network.builder.networkRequest
import ar.com.wolox.android.example.network.repository.PostRepository
import ar.com.wolox.wolmo.core.presenter.CoroutineBasePresenter
import kotlinx.coroutines.launch
import javax.inject.Inject
class RequestPresenter @Inject constructor(
private val postRepository: PostRepository
) : CoroutineBasePresenter<RequestView>() {
fun onSearchRequested(postId: Int?) = launch {
if (postId == null) {
view?.showInvalidInput()
return@launch
}
networkRequest(postRepository.getPostById(postId)) {
onResponseSuccessful { response -> showPost(response!!) }
onResponseFailed { _, _ -> view?.showError() }
onCallFailure { view?.showError() }
}
}
private fun showPost(post: Post) = view?.run {
setTitle(post.title)
setBody(post.body)
}
}
| 2 | Kotlin | 10 | 3 | b4bf4f17f40e93162b195aefb2645925ec2a484b | 1,029 | WoloxAndroidBootstrap | MIT License |
shared/src/iosTest/kotlin/io/template/app/shared/GreetingTestIos.kt | CoreWillSoft | 590,037,035 | false | null | package io.template.app.shared
import kotlin.test.Test
import kotlin.test.assertTrue
class GreetingTestsIos {
@Test
fun testHello() {
assertTrue("iOS" in Greeting().greet())
}
}
| 1 | Kotlin | 0 | 0 | 9be0e3ab0d0649081d6991d135ef09e163f36c3d | 201 | kmp-mobile-template | MIT License |
plugins/kotlin/refactorings/kotlin.refactorings.common/src/org/jetbrains/kotlin/idea/refactoring/move/java/MoveKotlinMemberHandler.kt | ingokegel | 72,937,917 | false | null | // Copyright 2000-2023 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package org.jetbrains.kotlin.idea.refactoring.move.java
import com.intellij.psi.PsiClass
import com.intellij.psi.PsiMember
import com.intellij.psi.PsiReference
import com.intellij.refactoring.move.moveMembers.MoveJavaMemberHandler
import com.intellij.refactoring.move.moveMembers.MoveMembersOptions
import com.intellij.refactoring.move.moveMembers.MoveMembersProcessor
import org.jetbrains.kotlin.idea.references.KtSimpleNameReference
class MoveKotlinMemberHandler : MoveJavaMemberHandler() {
override fun getUsage(
member: PsiMember,
psiReference: PsiReference,
membersToMove: MutableSet<PsiMember>,
targetClass: PsiClass
): MoveMembersProcessor.MoveMembersUsageInfo? {
if (psiReference is KtSimpleNameReference && psiReference.getImportAlias() != null) return null
return super.getUsage(member, psiReference, membersToMove, targetClass)
}
override fun changeExternalUsage(options: MoveMembersOptions, usage: MoveMembersProcessor.MoveMembersUsageInfo): Boolean {
val reference = usage.getReference()
if (reference is KtSimpleNameReference && reference.getImportAlias() != null) return true
return super.changeExternalUsage(options, usage)
}
} | 284 | null | 5162 | 2 | b07eabd319ad5b591373d63c8f502761c2b2dfe8 | 1,360 | intellij-community | Apache License 2.0 |
src/app/src/main/java/io/capsulo/min808/core/domain/ReactiveInteractor.kt | lemarcque | 190,186,868 | false | null | package io.capsulo.min808.core.domain
import io.reactivex.Completable
import io.reactivex.Observable
import io.reactivex.Single
import polanski.option.Option
/**
* Interfaces for Interactors.
* This interfaces represent use cases (this means any use case in the application should implement
* this contract).
*
* sources : https://github.com/n26/N26AndroidSamples/blob/master/base/src/main/java/de/n26/n26androidsamples/base/domain/ReactiveInteractor.java
*/
interface ReactiveInteractor {
/**
* Retrieves changes from the data layer.
* It returns an [Flowable] that emits updates for the retrieved object. The returned [Flowable] will never complete,
* but it can error if there are any problems performing the required actions to serve the data.
*/
interface RetrieveInteractor<Param, Object> :
ReactiveInteractor {
fun getBehaviorStream(params: Option<Param>) : Single<Object>
}
/**
* The request retrieveNote is used to request some result once. The returned observable is a single, emits once and then completes or errors.
* @param <Params> the type of the returned data.
* @param <Result> required parameters for the request.
</Result></Params>
*/
interface RequestInteractor<Params, Result> :
ReactiveInteractor {
fun getSingle(params: Option<Params>): Single<Result>
}
/**
* Sends changes to data layer.
* It returns a [Single] that will emit the result of the send operation.
* @param <Result> the type of the send operation result.
* @param <Params> required parameters for the send.
</Params></Result> */
interface SendInteractor<Params, Result> {
fun getSingle(params: Option<Params>): Completable
}
/**
* The delete retrieveNote is used to delete entities from data layer. The response for the delete operation comes as onNext
* event in the returned observable.
* @param <Result> the type of the delete response.
* @param <Params> required parameters for the delete.
</Params></Result> */
interface DeleteInteractor<Params, Result> : ReactiveInteractor {
fun getSingle(params: Option<Params>): Single<Result>
}
} | 0 | Kotlin | 0 | 1 | e99464346b6a6177beb614b002ebf60f94a92ab2 | 2,236 | min808 | MIT License |
web/src/main/kotlin/bz/stewart/bracken/web/Main.kt | abigpotostew | 92,021,572 | false | null | package bz.stewart.bracken.web
import bz.stewart.bracken.shared.conf.FileProperties
import bz.stewart.bracken.web.conf.EnvironmentProperties
import bz.stewart.bracken.web.conf.WebDefaultProperties
fun main(args: Array<String>) {
EnvironmentProperties.values()
.filter { it.required && it.isEmpty() }
.forEach { error("Missing required java property: ${it.propName}") }
val props = FileProperties<WebDefaultProperties>(WebDefaultProperties.values().toList())
println("Loading main properties from: ${EnvironmentProperties.WEB_PROPS_FILE.getOrDefault()}")
props.loadFile(EnvironmentProperties.WEB_PROPS_FILE.getOrDefault())
if (props.hasMissingRequiredDef())
throw props.getMissingPropertyException()
ServiceRunner(MainSparkConfig(props), props.getProperty(WebDefaultProperties.REST_SERVICE_URL)).run()
} | 0 | Kotlin | 0 | 0 | edd326981cc23168d7bf23852e638767dbac3547 | 853 | easypolitics | Apache License 2.0 |
app/src/main/kotlin/net/primal/android/core/compose/feed/model/FeedPostsSyncStats.kt | PrimalHQ | 639,579,258 | false | {"Kotlin": 2548226} | package net.primal.android.core.compose.feed.model
import net.primal.android.attachments.domain.CdnImage
data class FeedPostsSyncStats(
val postsCount: Int = 0,
val postIds: List<String> = emptyList(),
val avatarCdnImages: List<CdnImage> = emptyList(),
)
| 56 | Kotlin | 12 | 98 | 438072af7f67762c71c5dceffa0c83dedd8e2e85 | 269 | primal-android-app | MIT License |
src/main/kotlin/vibroad/service/graphql/DataFetcher.kt | si87 | 252,811,532 | false | null | package vibroad.service.graphql
import graphql.schema.DataFetcher
import graphql.schema.DataFetchingEnvironment
import vibroad.service.model.Video
import vibroad.service.service.VideoService
import java.util.UUID
import javax.inject.Singleton
@Singleton
class VideosDataFetcher(
private val videoService: VideoService
) : DataFetcher<List<Video>> {
override fun get(env: DataFetchingEnvironment): List<Video> = videoService.getAll()
}
@Singleton
class VideoDataFetcher(
private val videoService: VideoService
) : DataFetcher<Video> {
override fun get(env: DataFetchingEnvironment): Video? {
val id = UUID.fromString(env.getArgument<String>("id"))
return videoService.getById(id)
}
}
@Singleton
class VideoByNameFetcher(
private val videoService: VideoService
) : DataFetcher<List<Video>> {
override fun get(env: DataFetchingEnvironment): List<Video> {
val name = env.getArgument<String>("name")
return videoService.getByName(name)
}
}
| 0 | Kotlin | 0 | 0 | ff729e096fc72b9a8afd098ac318b99a55f7cde4 | 1,015 | viBroad-service | MIT License |
src/main/java/nextstep/subway/line/dto/LineResponse.kt | just-hazard | 407,830,124 | false | {"SCSS": 108481, "Kotlin": 66945, "Vue": 63508, "JavaScript": 23902, "Java": 1995, "HTML": 1000} | package nextstep.subway.line.dto
import nextstep.subway.line.domain.Line
import nextstep.subway.station.dto.StationResponse
import java.time.LocalDateTime
class LineResponse(
var id: Long,
var name: String,
var color: String,
var stations: List<StationResponse>,
var createdDate: LocalDateTime,
var modifiedDate: LocalDateTime
) {
companion object {
fun of(line: Line, stations: List<StationResponse>): LineResponse {
return LineResponse(line.id, line.name, line.color, stations, line.createdDate, line.modifiedDate)
}
}
}
| 0 | SCSS | 0 | 0 | 3c64c2cba5fe7f99f99835d16ebdd88fb397ad7e | 585 | kotlin-subway-service | MIT License |
learnroom/src/main/java/com/simplation/learnroom/MyDatabase.kt | Simplation | 324,966,218 | false | null | package com.simplation.learnroom
import android.content.Context
import androidx.room.Database
import androidx.room.Room
import androidx.room.RoomDatabase
import androidx.room.migration.Migration
import androidx.sqlite.db.SupportSQLiteDatabase
@Database(entities = [Student::class], version = 1, exportSchema = false)
abstract class MyDatabase : RoomDatabase() {
companion object {
private const val DATA_BASE = "my_db"
private var databaseInstance: MyDatabase? = null
private val MIGRATION_1_2 = object : Migration(1, 2) {
override fun migrate(database: SupportSQLiteDatabase) {
database.execSQL("") // 根据业务需要添加相应的 SQL 语句
// database.execSQL("ALTER TABLE my_db ADD COLUMN bar_data INTEGER NOT NULL DEFAULT 1")
}
}
//region 删除数据库中的表某一列
private val MIGRATION_DROP_ROW = object : Migration(2, 3) {
override fun migrate(database: SupportSQLiteDatabase) {
// 1.创建新表
database.execSQL("CREATE TABLE WORD_TEMP(id INTEGER PRIMARY KEY NOT NULL, english_word TEXT, chinese_meaning TEXT)")
// 2.查找并插入新表所需要的数据
database.execSQL("INSERT INTO WORD_TEMP(id, english_word, chinese_meaning) SELECT id, english_word, chinese_meaning FROM WORD")
// 3.删除旧表
database.execSQL("DROP TABLE WORD")
// 4.对创建的新表进行重命名
database.execSQL("ALTER TABLE WORD_TEMP RENAME TO WORD")
}
}
//endregion
fun getInstance(context: Context): MyDatabase {
if (databaseInstance == null) {
databaseInstance =
Room.databaseBuilder(
context.applicationContext,
MyDatabase::class.java,
DATA_BASE
)
// .allowMainThreadQueries() 允许在主线程中操作
// .fallbackToDestructiveMigration() 破坏性迁移的操作,不建议
.addMigrations(MIGRATION_1_2)
.build()
}
return databaseInstance as MyDatabase
}
}
abstract fun studentDao(): StudentDao
} | 0 | Kotlin | 0 | 2 | 9ff56c255a2f0e28791017ed528650de680a13b6 | 2,304 | LearnJetpack | Apache License 2.0 |
android/src/main/kotlin/com/sidlatau/flutterdocumentpicker/FlutterDocumentPickerPlugin.kt | mishatron | 187,657,335 | false | {"Dart": 9876, "Kotlin": 9305, "Swift": 5454, "Ruby": 695, "Objective-C": 438} | package com.sidlatau.flutterdocumentpicker
import io.flutter.plugin.common.MethodCall
import io.flutter.plugin.common.MethodChannel
import io.flutter.plugin.common.MethodChannel.MethodCallHandler
import io.flutter.plugin.common.MethodChannel.Result
import io.flutter.plugin.common.PluginRegistry.Registrar
class FlutterDocumentPickerPlugin(
private val delegate: FlutterDocumentPickerDelegate
) : MethodCallHandler {
companion object {
const val TAG = "flutter_document_picker"
private const val ARG_ALLOWED_FILE_EXTENSIONS = "allowedFileExtensions"
private const val ARG_ALLOWED_MIME_TYPES = "allowedMimeTypes"
private const val ARG_INVALID_FILENAME_SYMBOLS = "invalidFileNameSymbols"
@JvmStatic
fun registerWith(registrar: Registrar) {
val channel = MethodChannel(registrar.messenger(), "flutter_document_picker")
val delegate = FlutterDocumentPickerDelegate(
activity = registrar.activity()
)
registrar.addActivityResultListener(delegate)
channel.setMethodCallHandler(
FlutterDocumentPickerPlugin(delegate)
)
}
}
override fun onMethodCall(call: MethodCall, result: Result) {
if (call.method == "pickDocument") {
delegate.pickDocument(
result,
allowedFileExtensions = parseArray(call, ARG_ALLOWED_FILE_EXTENSIONS),
allowedMimeTypes = parseArray(call, ARG_ALLOWED_MIME_TYPES),
invalidFileNameSymbols = parseArray(call, ARG_INVALID_FILENAME_SYMBOLS)
)
} else {
result.notImplemented()
}
}
private fun parseArray(call: MethodCall, arg: String): Array<String>? {
if (call.hasArgument(arg)) {
return call.argument<ArrayList<String>>(arg)?.toTypedArray()
}
return null
}
}
| 0 | Dart | 0 | 2 | d96606a687e14162f429fe0d15e21fdcdb8055d9 | 1,954 | flutter_file_picker | Apache License 2.0 |
src/test/kotlin/com/dadjokes/DadJokesApi/DadJokesApiApplicationTests.kt | AnthonyShannon | 743,661,381 | false | {"Kotlin": 501} | package com.dadjokes.DadJokesApi
import org.junit.jupiter.api.Test
import org.springframework.boot.test.context.SpringBootTest
@SpringBootTest
class DadJokesApiApplicationTests {
@Test
fun contextLoads() {
}
}
| 0 | Kotlin | 0 | 0 | ab17d97f5635ebf15130686221d5ea4de0731287 | 217 | dad-jokes-api | MIT License |
sample-android/src/main/kotlin/com/vanniktech/locale/sample/android/LocaleApplication.kt | vanniktech | 562,822,028 | false | null | package com.vanniktech.locale.sample.android
import android.app.Application
import timber.log.Timber
class LocaleApplication : Application() {
override fun onCreate() {
super.onCreate()
Timber.plant(Timber.DebugTree())
}
}
| 1 | Kotlin | 0 | 7 | 217714b4611ef0c8a25848f3ab16dad5de665253 | 237 | multiplatform-locale | Apache License 2.0 |
src/test/kotlin/uk/gov/justice/digital/hmpps/incidentreporting/dto/EntityToDtoMappingEdgeCaseTest.kt | ministryofjustice | 725,638,590 | false | {"Kotlin": 317162, "Dockerfile": 1365} | package uk.gov.justice.digital.hmpps.incidentreporting.dto
import org.assertj.core.api.Assertions.assertThat
import org.assertj.core.api.Assertions.assertThatThrownBy
import org.junit.jupiter.api.BeforeEach
import org.junit.jupiter.api.Test
import org.springframework.beans.factory.annotation.Autowired
import uk.gov.justice.digital.hmpps.incidentreporting.constants.InformationSource
import uk.gov.justice.digital.hmpps.incidentreporting.helper.buildIncidentReport
import uk.gov.justice.digital.hmpps.incidentreporting.integration.SqsIntegrationTestBase
import uk.gov.justice.digital.hmpps.incidentreporting.jpa.repository.EventRepository
import uk.gov.justice.digital.hmpps.incidentreporting.jpa.repository.ReportRepository
/**
* Tests for edge cases when converting JPA entities to DTO classes.
* Largely, these mappings are field-by-field copies.
* NB: most conversions are already covered by resource and service tests.
*/
class EntityToDtoMappingEdgeCaseTest : SqsIntegrationTestBase() {
@Autowired
lateinit var eventRepository: EventRepository
@Autowired
lateinit var reportRepository: ReportRepository
@BeforeEach
fun setUp() {
reportRepository.deleteAll()
eventRepository.deleteAll()
}
@Test
fun `report must have a non-null id to map to the dto`() {
val unsavedReport = buildIncidentReport(
incidentNumber = "1234",
reportTime = now,
)
assertThat(unsavedReport.id).isNull()
assertThatThrownBy { unsavedReport.toDto() }
.isInstanceOf(NullPointerException::class.java)
val savedReport = reportRepository.save(unsavedReport)
assertThat(savedReport.id).isNotNull()
assertThat(savedReport.toDto().id).isEqualTo(savedReport.id)
}
@Test
fun `report dto reflects whether the entity's source was NOMIS`() {
val reportFromNomis = reportRepository.save(
buildIncidentReport(
incidentNumber = "1234",
reportTime = now,
source = InformationSource.NOMIS,
),
)
assertThat(reportFromNomis.toDto().createdInNomis).isTrue()
val reportFromDps = reportRepository.save(
buildIncidentReport(
incidentNumber = "1235",
reportTime = now,
source = InformationSource.DPS,
),
)
assertThat(reportFromDps.toDto().createdInNomis).isFalse()
}
}
| 2 | Kotlin | 1 | 0 | b1f764364308b3a69481dc1de8fa3d2f9f944567 | 2,311 | hmpps-incident-reporting-api | MIT License |
app/src/main/java/com/wengelef/kotlinmvvmtest/db/UserDB.kt | wengelef | 88,400,511 | false | null | package com.wengelef.kotlinmvvmtest.db
import android.content.Context
import android.content.SharedPreferences
import com.google.gson.GsonBuilder
import com.google.gson.reflect.TypeToken
import com.wengelef.kotlinmvvmtest.extension.put
import com.wengelef.kotlinmvvmtest.model.User
import javax.inject.Inject
class UserDB @Inject constructor(context: Context) {
private val sharedPrefs: SharedPreferences by lazy { context.getSharedPreferences("UsersDB", Context.MODE_PRIVATE) }
private val gson = GsonBuilder().setPrettyPrinting().create()
private val KEY = "USERS_KEY"
fun put(users: List<User>) {
sharedPrefs.put { putString(KEY, gson.toJson(users).toString()) }
}
fun get(): List<User>? {
return sharedPrefs.getString(KEY, null)?.let {
gson.fromJson(it, object : TypeToken<List<User>>(){}.type)
}
}
} | 0 | Kotlin | 2 | 2 | 05dcd5b0466013eb2857df69a3bdcc522e1c43e9 | 875 | KotlinMVVM | Apache License 2.0 |
widgets/src/commonMain/kotlin/dev/icerock/moko/widgets/factory/DefaultStatefulWidgetViewFactory.kt | MaTriXy | 228,468,295 | true | {"Kotlin": 311344} | /*
* Copyright 2019 IceRock MAG Inc. Use of this source code is governed by the Apache 2.0 license.
*/
package dev.icerock.moko.widgets.factory
import dev.icerock.moko.widgets.StatefulWidget
import dev.icerock.moko.widgets.core.ViewFactory
import dev.icerock.moko.widgets.style.background.Background
import dev.icerock.moko.widgets.style.view.Backgrounded
import dev.icerock.moko.widgets.style.view.MarginValues
import dev.icerock.moko.widgets.style.view.Margined
import dev.icerock.moko.widgets.style.view.Padded
import dev.icerock.moko.widgets.style.view.PaddingValues
import dev.icerock.moko.widgets.style.view.WidgetSize
expect class DefaultStatefulWidgetViewFactory(
style: Style = Style()
) : DefaultStatefulWidgetViewFactoryBase
abstract class DefaultStatefulWidgetViewFactoryBase(
val style: Style
) : ViewFactory<StatefulWidget<out WidgetSize, *, *>> {
data class Style(
override val background: Background? = null,
override val margins: MarginValues? = null,
override val padding: PaddingValues? = null
) : Backgrounded, Margined, Padded
}
| 0 | null | 0 | 0 | 15318995f432351762def5ddc291b9696ac87516 | 1,097 | moko-widgets | Apache License 2.0 |
clients/kotlin-vertx/generated/src/main/kotlin/org/openapitools/server/api/verticle/AudienceInsightsApi.kt | oapicf | 489,369,143 | false | {"Markdown": 13009, "YAML": 64, "Text": 6, "Ignore List": 43, "JSON": 688, "Makefile": 2, "JavaScript": 2261, "F#": 1305, "XML": 1120, "Shell": 44, "Batchfile": 10, "Scala": 4677, "INI": 23, "Dockerfile": 14, "Maven POM": 22, "Java": 13384, "Emacs Lisp": 1, "Haskell": 75, "Swift": 551, "Ruby": 1149, "Cabal Config": 2, "OASv3-yaml": 16, "Go": 2224, "Go Checksums": 1, "Go Module": 4, "CMake": 9, "C++": 6688, "TOML": 3, "Rust": 556, "Nim": 541, "Perl": 540, "Microsoft Visual Studio Solution": 2, "C#": 1645, "HTML": 545, "Xojo": 1083, "Gradle": 20, "R": 1079, "JSON with Comments": 8, "QMake": 1, "Kotlin": 3280, "Python": 1, "Crystal": 1060, "ApacheConf": 2, "PHP": 3940, "Gradle Kotlin DSL": 1, "Protocol Buffer": 538, "C": 1598, "Ada": 16, "Objective-C": 1098, "Java Properties": 2, "Erlang": 1097, "PlantUML": 1, "robots.txt": 1, "HTML+ERB": 2, "Lua": 1077, "SQL": 512, "AsciiDoc": 1, "CSS": 3, "PowerShell": 1083, "Elixir": 5, "Apex": 1054, "Visual Basic 6.0": 3, "TeX": 1, "ObjectScript": 1, "OpenEdge ABL": 1, "Option List": 2, "Eiffel": 583, "Gherkin": 1, "Dart": 538, "Groovy": 539, "Elm": 31} | package org.openapitools.server.api.verticle
import org.openapitools.server.api.model.AudienceDefinitionResponse
import org.openapitools.server.api.model.AudienceInsightType
import org.openapitools.server.api.model.AudienceInsightsResponse
import org.openapitools.server.api.model.Error
import io.vertx.core.Vertx
import io.vertx.core.json.JsonObject
import io.vertx.core.json.JsonArray
import com.github.wooyme.openapi.Response
import io.vertx.ext.web.api.OperationRequest
import io.vertx.kotlin.ext.web.api.contract.openapi3.OpenAPI3RouterFactory
import io.vertx.serviceproxy.ServiceBinder
import io.vertx.ext.web.handler.CookieHandler
import io.vertx.ext.web.handler.SessionHandler
import io.vertx.ext.web.sstore.LocalSessionStore
import java.util.List
import java.util.Map
interface AudienceInsightsApi {
fun init(vertx:Vertx,config:JsonObject)
/* audienceInsightsGet
* Get audience insights */
suspend fun audienceInsightsGet(adAccountId:kotlin.String?,audienceInsightType:AudienceInsightType?,context:OperationRequest):Response<AudienceInsightsResponse>
/* audienceInsightsScopeAndTypeGet
* Get audience insights scope and type */
suspend fun audienceInsightsScopeAndTypeGet(adAccountId:kotlin.String?,context:OperationRequest):Response<AudienceDefinitionResponse>
companion object {
const val address = "AudienceInsightsApi-service"
suspend fun createRouterFactory(vertx: Vertx,path:String): io.vertx.ext.web.api.contract.openapi3.OpenAPI3RouterFactory {
val routerFactory = OpenAPI3RouterFactory.createAwait(vertx,path)
routerFactory.addGlobalHandler(CookieHandler.create())
routerFactory.addGlobalHandler(SessionHandler.create(LocalSessionStore.create(vertx)))
routerFactory.setExtraOperationContextPayloadMapper{
JsonObject().put("files",JsonArray(it.fileUploads().map { it.uploadedFileName() }))
}
val opf = routerFactory::class.java.getDeclaredField("operations")
opf.isAccessible = true
val operations = opf.get(routerFactory) as Map<String, Any>
for (m in AudienceInsightsApi::class.java.methods) {
val methodName = m.name
val op = operations[methodName]
if (op != null) {
val method = op::class.java.getDeclaredMethod("mountRouteToService",String::class.java,String::class.java)
method.isAccessible = true
method.invoke(op,address,methodName)
}
}
routerFactory.mountServiceInterface(AudienceInsightsApi::class.java, address)
return routerFactory
}
}
}
| 0 | Java | 0 | 2 | dcd328f1e62119774fd8ddbb6e4bad6d7878e898 | 2,717 | pinterest-sdk | MIT License |
app/src/main/java/com/adictosalainformatica/kotlinclean/base/presentation/presenter/BasePresenterViewInterface.kt | rmiguel1985 | 172,973,839 | false | {"Gradle": 4, "Java Properties": 2, "Shell": 1, "Text": 1, "Ignore List": 2, "Batchfile": 1, "Markdown": 1, "Proguard": 1, "Kotlin": 57, "JSON": 3, "XML": 12, "Java": 1} | package com.adictosalainformatica.kotlinclean.base.presentation.presenter
interface BasePresenterViewInterface {
fun showError(message: String)
fun showMessage(message: String)
fun showWarning(message: String)
fun showProgress()
fun hideProgress()
} | 0 | Kotlin | 0 | 3 | e5fbf4993dfb886b4e81002b1d92b7b51ce9382b | 270 | KotlinMvpArchitecture | The Unlicense |
execute-around/src/test/kotlin/io/kommons/designpatterns/execute/around/SimpleFileWriterTest.kt | debop | 235,066,649 | false | null | package io.kommons.designpatterns.execute.around
import io.kommons.junit.jupiter.folder.TempFolder
import io.kommons.junit.jupiter.folder.TempFolderExtension
import io.kommons.logging.KLogging
import org.amshove.kluent.shouldBeFalse
import org.amshove.kluent.shouldBeTrue
import org.amshove.kluent.shouldEqual
import org.amshove.kluent.shouldNotBeNull
import org.junit.jupiter.api.BeforeEach
import org.junit.jupiter.api.Test
import org.junit.jupiter.api.assertThrows
import org.junit.jupiter.api.extension.ExtendWith
import java.io.File
import java.io.IOException
import java.nio.file.Files
/**
* SimpleFileWriterTest
*/
@ExtendWith(TempFolderExtension::class)
class SimpleFileWriterTest {
companion object: KLogging()
private lateinit var tempFolder: TempFolder
@BeforeEach
fun beforeEach(tempFolder: TempFolder) {
this.tempFolder = tempFolder
}
@Test
fun `writer not null`() {
val file = tempFolder.createFile("newFile")
SimpleFileWriter(file.path) { writer ->
writer.shouldNotBeNull()
}
}
@Test
fun `create non existing file`() {
val file = File(tempFolder.root, "non-exsisting-file")
file.exists().shouldBeFalse()
SimpleFileWriter(file.path) { writer ->
writer.shouldNotBeNull()
}
file.exists().shouldBeTrue()
}
@Test
fun `write contents to file`() {
val testMessage = "Test message"
val file = tempFolder.createFile("testMessage")
file.exists().shouldBeTrue()
SimpleFileWriter(file.path) { writer ->
writer.write(testMessage)
}
Files.lines(file.toPath()).allMatch { it == testMessage }.shouldBeTrue()
}
@Test
fun `ripples IOException occurred while writing`() {
val message = "Some error"
assertThrows<IOException> {
val file = tempFolder.createFile("error")
SimpleFileWriter(file.path) { writer ->
throw IOException(message)
}
}.localizedMessage shouldEqual message
}
} | 0 | Kotlin | 11 | 53 | c00bcc0542985bbcfc4652d0045f31e5c1304a70 | 2,091 | kotlin-design-patterns | Apache License 2.0 |
implementation/src/test/kotlin/io/github/tomplum/aoc/display/DisplayAnalyserTest.kt | TomPlum | 431,391,240 | false | null | package io.github.tomplum.aoc.display
import assertk.assertThat
import assertk.assertions.isEqualTo
import io.github.tomplum.aoc.input.TestInputReader
import org.junit.jupiter.api.Test
class DisplayAnalyserTest {
@Test
fun examplePartOne() {
val input = TestInputReader.read<String>("/day8/larger-example.txt")
val analyser = DisplayAnalyser(input.value)
assertThat(analyser.countUniqueSegmentsInstances()).isEqualTo(26)
}
@Test
fun smallerExamplePartTwo() {
val input = TestInputReader.read<String>("/day8/example.txt")
val analyser = DisplayAnalyser(input.value)
assertThat(analyser.getOutputValueSum()).isEqualTo(5353)
}
@Test
fun largerExamplePartTwo() {
val input = TestInputReader.read<String>("/day8/larger-example.txt")
val analyser = DisplayAnalyser(input.value)
assertThat(analyser.getOutputValueSum()).isEqualTo(61229)
}
}
| 0 | Kotlin | 0 | 0 | cccb15593378d0bb623117144f5b4eece264596d | 946 | advent-of-code-2021 | Apache License 2.0 |
app/src/main/java/com/hegesoftware/snookerscore/domain/BreakUsecases.kt | Henkkagg | 611,836,646 | false | {"Kotlin": 119473, "HTML": 81} | package com.hegesoftware.snookerscore.domain
import com.hegesoftware.snookerscore.domain.usecases.*
import javax.inject.Inject
data class BreakUsecases @Inject constructor(
val newGame: NewGame,
val newBreak: NewBreak,
val getBreakStream: GetBreakStream,
val getScoreStream: GetScoreStream,
val getLegalBallsStream: GetLegalBallsStream,
val getPlayerInTurn: GetPlayerInTurn,
val addPoint: AddPoint,
val addFoul: AddFoul,
val undo: Undo,
) | 0 | Kotlin | 0 | 0 | 2061a815ca17edabbd81ba8180b33089fd4b470c | 476 | SnookerScore | Apache License 2.0 |
rowi-jda/src/main/kotlin/com/abyssaldev/rowi/jda/ArgumentSetExtensions.kt | jacksonrakena | 324,772,735 | false | null | package com.abyssaldev.rowi.jda
import com.abyssaldev.rowi.core.ArgumentSet
import net.dv8tion.jda.api.entities.Member
import net.dv8tion.jda.api.entities.Role
import net.dv8tion.jda.api.entities.TextChannel
import net.dv8tion.jda.api.entities.User
val ArgumentSet.ArgumentValue.member: Member?
get() {
if (this.request !is JdaCommandRequest) throw JdaCompatibleErrors.usedOnInvalidObject("ArgumentValue.member")
return (this.request as JdaCommandRequest).guild?.getMemberById(value)
}
val ArgumentSet.ArgumentValue.user: User?
get() {
if (this.request !is JdaCommandRequest) throw JdaCompatibleErrors.usedOnInvalidObject("ArgumentValue.user")
return (request as JdaCommandRequest).jda.getUserById(value)
}
val ArgumentSet.ArgumentValue.channel: TextChannel?
get() {
if (this.request !is JdaCommandRequest) throw JdaCompatibleErrors.usedOnInvalidObject("ArgumentValue.channel")
return (request as JdaCommandRequest).jda.getTextChannelById(value)
}
val ArgumentSet.ArgumentValue.role: Role?
get() {
if (this.request !is JdaCommandRequest) throw JdaCompatibleErrors.usedOnInvalidObject("ArgumentValue.role")
return (request as JdaCommandRequest).guild?.getRoleById(value)
} | 0 | Kotlin | 0 | 2 | 6db407401d3a43c062683808815d180c74063189 | 1,272 | rowi | MIT License |
app/src/test/java/mwvdev/berightthere/android/service/BeRightThereServiceTest.kt | mwvdev | 336,762,028 | false | null | package mwvdev.berightthere.android.service
import com.fatboyindustrial.gsonjavatime.Converters
import com.google.common.truth.Truth.assertThat
import com.google.gson.Gson
import com.google.gson.GsonBuilder
import kotlinx.coroutines.runBlocking
import kotlinx.coroutines.test.runBlockingTest
import mwvdev.berightthere.android.TestDataHelper
import okhttp3.mockwebserver.MockResponse
import okhttp3.mockwebserver.MockWebServer
import org.junit.After
import org.junit.Before
import org.junit.Test
import retrofit2.Retrofit
import retrofit2.converter.gson.GsonConverterFactory
import retrofit2.create
class BeRightThereServiceTest {
private lateinit var gson: Gson
private var server = MockWebServer()
private lateinit var beRightThereService: BeRightThereService
@Before
fun setUp() {
gson = Converters.registerOffsetDateTime(GsonBuilder()).create()
val retrofit = Retrofit.Builder()
.baseUrl(server.url("/"))
.addConverterFactory(GsonConverterFactory.create(gson))
.build()
beRightThereService = retrofit.create()
}
@Test
fun checkin() = runBlockingTest {
server.enqueue(MockResponse().setBody(gson.toJson(TestDataHelper.checkinDto())))
runBlocking {
var checkinDto = beRightThereService.checkin()
val recordedRequest = server.takeRequest()
assertThat(checkinDto.identifier).isEqualTo(TestDataHelper.tripIdentifier)
assertThat(recordedRequest.path).isEqualTo("/api/trip/checkin")
}
}
@Test
fun addLocation() = runBlockingTest {
server.enqueue(MockResponse())
val locationDto = TestDataHelper.locationDto()
runBlocking { beRightThereService.addLocation(TestDataHelper.tripIdentifier, locationDto) }
val recordedRequest = server.takeRequest()
assertThat(recordedRequest.path).isEqualTo("/api/trip/${TestDataHelper.tripIdentifier}/addLocation")
assertThat(recordedRequest.method).isEqualTo("POST")
assertThat(recordedRequest.body.readUtf8()).isEqualTo(gson.toJson(locationDto))
}
@After
fun tearDown() {
server.shutdown()
}
} | 0 | Kotlin | 0 | 0 | 1333ccc8613aa913bd1032e1ab6b851fdba46b53 | 2,197 | berightthere_android | MIT License |
src/main/kotlin/sk/vildibald/polls/payload/PollResponse.kt | vildibald | 170,035,422 | false | null | package sk.vildibald.polls.payload
import java.time.Instant
data class PollResponse(
val id: Long,
val question: String,
val choices: List<ChoiceResponse>,
val expirationDateTime: Instant,
val createdBy: Long,
val updatedBy: Long,
val createdAt: Instant,
val updatedAt: Instant
) | 0 | Kotlin | 0 | 0 | ef12abc33bbd6cf41113d64f85d3648092ba1330 | 345 | polls | BSD Zero Clause License |
mobile/src/main/java/be/mygod/vpnhotspot/TetheringFragment.kt | ztc1997 | 121,736,656 | true | {"Kotlin": 70061} | package be.mygod.vpnhotspot
import android.content.ComponentName
import android.content.Context
import android.content.Intent
import android.content.ServiceConnection
import android.databinding.BaseObservable
import android.databinding.DataBindingUtil
import android.os.Bundle
import android.os.IBinder
import android.support.v4.app.Fragment
import android.support.v4.content.ContextCompat
import android.support.v7.util.SortedList
import android.support.v7.widget.DefaultItemAnimator
import android.support.v7.widget.LinearLayoutManager
import android.support.v7.widget.RecyclerView
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import be.mygod.vpnhotspot.databinding.FragmentTetheringBinding
import be.mygod.vpnhotspot.databinding.ListitemInterfaceBinding
import be.mygod.vpnhotspot.net.ConnectivityManagerHelper
import be.mygod.vpnhotspot.net.TetherType
import java.net.NetworkInterface
class TetheringFragment : Fragment(), ServiceConnection {
companion object {
private const val VIEW_TYPE_INTERFACE = 0
private const val VIEW_TYPE_MANAGE = 1
}
private abstract class BaseSorter<T> : SortedList.Callback<T>() {
override fun onInserted(position: Int, count: Int) { }
override fun areContentsTheSame(oldItem: T?, newItem: T?): Boolean = oldItem == newItem
override fun onMoved(fromPosition: Int, toPosition: Int) { }
override fun onChanged(position: Int, count: Int) { }
override fun onRemoved(position: Int, count: Int) { }
override fun areItemsTheSame(item1: T?, item2: T?): Boolean = item1 == item2
override fun compare(o1: T?, o2: T?): Int =
if (o1 == null) if (o2 == null) 0 else 1 else if (o2 == null) -1 else compareNonNull(o1, o2)
abstract fun compareNonNull(o1: T, o2: T): Int
}
private open class DefaultSorter<T : Comparable<T>> : BaseSorter<T>() {
override fun compareNonNull(o1: T, o2: T): Int = o1.compareTo(o2)
}
private object TetheredInterfaceSorter : DefaultSorter<TetheredInterface>()
inner class Data(val iface: TetheredInterface) : BaseObservable() {
val icon: Int get() = TetherType.ofInterface(iface.name).icon
val active = binder?.active?.contains(iface.name) == true
}
private class InterfaceViewHolder(val binding: ListitemInterfaceBinding) : RecyclerView.ViewHolder(binding.root),
View.OnClickListener {
init {
itemView.setOnClickListener(this)
}
override fun onClick(view: View) {
val context = itemView.context
val data = binding.data!!
if (data.active) context.startService(Intent(context, TetheringService::class.java)
.putExtra(TetheringService.EXTRA_REMOVE_INTERFACE, data.iface.name))
else ContextCompat.startForegroundService(context, Intent(context, TetheringService::class.java)
.putExtra(TetheringService.EXTRA_ADD_INTERFACE, data.iface.name))
}
}
private class ManageViewHolder(view: View) : RecyclerView.ViewHolder(view), View.OnClickListener {
init {
view.setOnClickListener(this)
}
override fun onClick(v: View?) = itemView.context.startActivity(Intent()
.setClassName("com.android.settings", "com.android.settings.Settings\$TetherSettingsActivity"))
}
class TetheredInterface(val name: String, lookup: Map<String, NetworkInterface>) : Comparable<TetheredInterface> {
val addresses = lookup[name]?.formatAddresses() ?: ""
override fun compareTo(other: TetheredInterface) = name.compareTo(other.name)
}
inner class TetheringAdapter : RecyclerView.Adapter<RecyclerView.ViewHolder>() {
private val tethered = SortedList(TetheredInterface::class.java, TetheredInterfaceSorter)
fun update(data: Set<String>) {
val lookup = NetworkInterface.getNetworkInterfaces().asSequence().associateBy { it.name }
tethered.clear()
tethered.addAll(data.map { TetheredInterface(it, lookup) })
notifyDataSetChanged()
}
override fun getItemCount() = tethered.size() + 1
override fun getItemViewType(position: Int) =
if (position == tethered.size()) VIEW_TYPE_MANAGE else VIEW_TYPE_INTERFACE
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): RecyclerView.ViewHolder {
val inflater = LayoutInflater.from(parent.context)
return when (viewType) {
VIEW_TYPE_INTERFACE -> InterfaceViewHolder(ListitemInterfaceBinding.inflate(inflater, parent, false))
VIEW_TYPE_MANAGE -> ManageViewHolder(inflater.inflate(R.layout.listitem_manage, parent, false))
else -> throw IllegalArgumentException("Invalid view type")
}
}
override fun onBindViewHolder(holder: RecyclerView.ViewHolder, position: Int) {
when (holder) {
is InterfaceViewHolder -> holder.binding.data = Data(tethered[position])
}
}
}
private lateinit var binding: FragmentTetheringBinding
private var binder: TetheringService.TetheringBinder? = null
val adapter = TetheringAdapter()
private val receiver = broadcastReceiver { _, intent ->
adapter.update(ConnectivityManagerHelper.getTetheredIfaces(intent.extras))
}
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
binding = DataBindingUtil.inflate(inflater, R.layout.fragment_tethering, container, false)
binding.interfaces.layoutManager = LinearLayoutManager(context, LinearLayoutManager.VERTICAL, false)
val animator = DefaultItemAnimator()
animator.supportsChangeAnimations = false // prevent fading-in/out when rebinding
binding.interfaces.itemAnimator = animator
binding.interfaces.adapter = adapter
return binding.root
}
override fun onStart() {
super.onStart()
val context = context!!
context.registerReceiver(receiver, intentFilter(ConnectivityManagerHelper.ACTION_TETHER_STATE_CHANGED))
context.bindService(Intent(context, TetheringService::class.java), this, Context.BIND_AUTO_CREATE)
}
override fun onStop() {
val context = context!!
context.unbindService(this)
context.unregisterReceiver(receiver)
super.onStop()
}
override fun onServiceConnected(name: ComponentName?, service: IBinder?) {
val binder = service as TetheringService.TetheringBinder
this.binder = binder
binder.fragment = this
}
override fun onServiceDisconnected(name: ComponentName?) {
binder?.fragment = null
binder = null
}
}
| 0 | Kotlin | 0 | 0 | eb4fe13003198512030ac1daf4ef7c0578b7adb8 | 6,856 | VPNHotspot | Apache License 2.0 |
app/src/main/java/cn/edu/sdu/online/isdu/ui/activity/SchoolBusActivity.kt | Grapedge | 161,661,122 | false | {"Gradle": 3, "Java Properties": 2, "Shell": 1, "Text": 1, "Ignore List": 2, "Batchfile": 1, "Markdown": 3, "Proguard": 1, "JSON": 1, "Kotlin": 83, "XML": 180, "Java": 127, "HTML": 1} | package cn.edu.sdu.online.isdu.ui.activity
import android.content.Intent
import android.os.Bundle
import android.view.View
import android.widget.*
import cn.edu.sdu.online.isdu.R
import cn.edu.sdu.online.isdu.app.SlideActivity
import cn.edu.sdu.online.isdu.ui.design.button.SchoolImageButton
import kotlinx.android.synthetic.main.activity_school_bus.*
/**
****************************************************
* @author zsj
* Last Modifier: Cola_Mentos
* Last Modify Time: 2018/7/12
*
* 校车活动
****************************************************
*/
class SchoolBusActivity : SlideActivity() , View.OnClickListener{
private var clearBtn : Button ?= null
private var searchBtn : Button ?= null
private var workdayBtn : Button ?= null
private var non_workdayBtn : Button ?= null
private var backBtn : ImageView ?= null
private var searchNum : Int = 0
private var fromP : Int = 0
private var toP : Int = 0
private val xqBtn : Array<SchoolImageButton?> = arrayOfNulls(10)
private val xqName = arrayOf("","中心校区","洪家楼校区","趵突泉校区","软件园校区","兴隆山校区","千佛山校区")
private var tipText : TextView ?= null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_school_bus)
initView()
}
/**
* 初始化view
*/
private fun initView(){
clearBtn = btn_clear
searchBtn = btn_search
workdayBtn = workday
non_workdayBtn = non_workday
tipText = tips
backBtn = btn_back
xqBtn[1] = btn_zhongxin
xqBtn[2] = btn_hongjialou
xqBtn[3] = btn_baotuquan
xqBtn[4] = btn_ruanjianyuan
xqBtn[5] = btn_xinglongshan
xqBtn[6] = btn_qianfoshan
clearBtn!!.setOnClickListener(this)
searchBtn!!.setOnClickListener(this)
workdayBtn!!.setOnClickListener(this)
non_workdayBtn!!.setOnClickListener(this)
backBtn!!.setOnClickListener(this)
for (i in 1..6){
xqBtn[i]!!.setOnClickListener(this)
}
}
override fun onClick(v: View?) {
when(v!!.id){
/**
* 重置按钮
*/
btn_clear.id->{
fromP=0
toP=0
for (i in 1..6){
xqBtn[i]!!.setBacColor(resources.getColor(R.color.colorWhite))
xqBtn[i]!!.setText(xqName[i])
xqBtn[i]!!.setColor(resources.getColor(R.color.colorPrimaryText))
}
tipText!!.text=""
}
/**
* 查询按钮
*/
btn_search.id->{
if (fromP == 0 && toP == 0){
tipText!!.text = "请选择起点和终点"
}
else if (toP == 0){
tipText!!.text = "请选择终点"
}
else if (fromP == 0){
tipText!!.text = "请选择起点"
}
else {
tipText!!.text = ""
val intent = Intent(this,SchoolBusTableActivity::class.java)
intent.putExtra("searchNum",searchNum)
intent.putExtra("fromP",fromP)
intent.putExtra("toP",toP)
startActivity(intent)
}
}
workday.id->{
searchNum = 0
}
non_workday.id->{
searchNum = 1
}
btn_back.id->{
finish()
}
/**
* 校区选择按钮
*/
else ->{
for (i in 1..6){
if (v.id == xqBtn[i]!!.id){
//将当前选择的校区背景变成灰色
xqBtn[i]!!.setBacColor(resources.getColor(R.color.colorThemeGrey))
//如果没有选择出发地,并且当前点击的校区之前没有被选中,那么久作为出发地,否则取消选中
if (fromP == 0) {
if (toP != i) {
fromP = i
xqBtn[i]!!.setText("从 " + xqName[i])
xqBtn[i]!!.setColor(resources.getColor(R.color.colorPurpleDark))
}
else {
changeAppearance(i)
toP = 0
}
}
//如果当前校区之前被选为出发地了,那么就取消选择
else if (i == fromP){
changeAppearance(i)
fromP=0
}
//如果当前校区之前被选为目的地了,那么就取消选择
else if(i == toP){
changeAppearance(i)
toP=0
}
else {
if (toP != 0){
changeAppearance(fromP)
fromP = toP
xqBtn[fromP]!!.setColor(resources.getColor(R.color.colorPurpleDark))
xqBtn[fromP]!!.setText("从 "+xqName[fromP])
}
toP = i
xqBtn[i]!!.setText("到 "+xqName[i])
xqBtn[i]!!.setColor(resources.getColor(R.color.colorPurpleDark))
}
}
}
}
}
}
/**
* 将校区的按钮恢复原样
*
* @param i 校区编号
*/
private fun changeAppearance(i : Int){
xqBtn[i]!!.setBacColor(resources.getColor(R.color.colorWhite))
xqBtn[i]!!.setText(xqName[i])
xqBtn[i]!!.setColor(resources.getColor(R.color.colorPrimaryText))
}
}
| 0 | Kotlin | 0 | 1 | 580e1cce5f4837644e8366f5e141d2e0f4fbcaf5 | 5,764 | isdu-app | Apache License 2.0 |
aws-auth-plugins-core/src/main/java/com/amplifyframework/auth/plugins/core/AuthHubEventEmitter.kt | aws-amplify | 177,009,933 | false | {"Java": 5271326, "Kotlin": 3564857, "Shell": 28043, "Groovy": 11755, "Python": 3681, "Ruby": 1874} | /*
* Copyright 2023 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package com.amplifyframework.auth.plugins.core
import com.amplifyframework.core.Amplify
import com.amplifyframework.hub.HubChannel
import com.amplifyframework.hub.HubEvent
import java.util.concurrent.atomic.AtomicReference
class AuthHubEventEmitter {
private val lastPublishedHubEventName = AtomicReference<String>()
fun sendHubEvent(eventName: String) {
if (lastPublishedHubEventName.getAndSet(eventName) != eventName) {
Amplify.Hub.publish(HubChannel.AUTH, HubEvent.create(eventName))
}
}
}
| 105 | Java | 115 | 245 | 14c71f38f052a964b96d7abaff6e157bd21a64d8 | 1,117 | amplify-android | Apache License 2.0 |
app/src/main/java/com/engineerfred/kotlin/next/domain/repository/NotificationRepository.kt | EngFred | 780,343,776 | false | {"Kotlin": 734480} | package com.engineerfred.kotlin.next.domain.repository
import com.engineerfred.kotlin.next.domain.model.Notification
import com.engineerfred.kotlin.next.utils.Response
import kotlinx.coroutines.flow.Flow
interface NotificationRepository {
suspend fun addNotification( notification: Notification ) : Response<Any>
suspend fun deleteNotification( notificationId: String ) : Response<Any>
suspend fun updateNotification( notificationId: String )
fun getUserNotifications( userId: String ) : Flow<Response<List<Notification>>>
} | 0 | Kotlin | 0 | 0 | 6ee4254723c338e8475109c2634cf1200a7c259c | 542 | Blogify-app | MIT License |
covid19-stats-bago/app/src/main/java/gov/mm/covid19statsbago/adapter/viewholder/TableCellDeathCountViewHolder.kt | kyawhtut-cu | 252,343,874 | false | {"Text": 2, "Ignore List": 3, "Gradle": 3, "JSON": 8, "Java Properties": 2, "Shell": 1, "Batchfile": 1, "Proguard": 1, "Kotlin": 46, "XML": 69, "Java": 11} | package gov.mm.covid19statsbago.adapter.viewholder
import android.view.View
import android.widget.LinearLayout
import com.evrencoskun.tableview.adapter.recyclerview.holder.AbstractViewHolder
import gov.mm.covid19statsbago.R
import gov.mm.covid19statsbago.datas.TableCellVO
import gov.mm.covid19statsbago.util.getColorValue
import kotlinx.android.synthetic.main.tableview_cell_count_layout.view.*
/**
* Created by <NAME> on 4/4/2020.
*/
class TableCellDeathCountViewHolder(private val view: View) : AbstractViewHolder(view) {
fun bind(data: TableCellVO) {
view.tv_count.text = data.data as String
// view.layoutParams.width = LinearLayout.LayoutParams.WRAP_CONTENT
// view.tv_count.requestLayout()
}
override fun setSelected(selectionState: SelectionState) {
super.setSelected(selectionState)
view.tv_count.setTextColor(
view.context.getColorValue(
if (selectionState == SelectionState.SELECTED) R.color.selected_text_color
else R.color.colorRed
)
)
}
} | 0 | Kotlin | 0 | 0 | 6bd6b30d1683b44534989f6f92d4f4ef651c5866 | 1,079 | covid19-stats-bago | Apache License 2.0 |
feature/tutorial/src/main/java/com/hanbikan/nook/feature/tutorial/AddUserViewModel.kt | hanbikan | 737,877,468 | false | {"Kotlin": 289515} | package com.hanbikan.nook.feature.tutorial
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.hanbikan.nook.core.domain.model.User
import com.hanbikan.nook.core.domain.usecase.AddUserUseCase
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import javax.inject.Inject
@HiltViewModel
class AddUserViewModel @Inject constructor(
private val addUserUseCase: AddUserUseCase,
) : ViewModel() {
private val _name: MutableStateFlow<String> = MutableStateFlow("")
val name = _name.asStateFlow()
private val _islandName: MutableStateFlow<String> = MutableStateFlow("")
val islandName = _islandName.asStateFlow()
private val _isNorth: MutableStateFlow<Boolean> = MutableStateFlow(true)
val isNorth = _isNorth.asStateFlow()
private val _isLoading: MutableStateFlow<Boolean> = MutableStateFlow(false)
val isLoading = _isLoading.asStateFlow()
fun setName(newName: String) {
if (newName.length >= User.NAME_MAX_LENGTH) return
_name.value = newName
}
fun setIslandName(newIslandName: String) {
if (newIslandName.length >= User.ISLAND_NAME_MAX_LENGTH) return
_islandName.value = newIslandName
}
fun setIsNorth(newIsNorth: Boolean) {
_isNorth.value = newIsNorth
}
fun addUser(onComplete: () -> Unit) {
if (name.value.isEmpty() || islandName.value.isEmpty()) return
viewModelScope.launch(Dispatchers.IO) {
val user = User(
name = name.value,
islandName = islandName.value,
isNorth = isNorth.value,
)
addUserUseCase(user)
// onComplete에서 navigate와 같은 동작을 수행하므로 Main Thread에서 수행되어야 합니다.
withContext(Dispatchers.Main) {
onComplete()
}
}
}
fun setIsLoading(newIsLoading: Boolean) {
_isLoading.value = newIsLoading
}
} | 0 | Kotlin | 0 | 0 | 8af82dee87fdc0a6699b986cb3bd689c3537508a | 2,130 | Nook | Apache License 2.0 |
app/src/main/java/com/inz/z/note_book/viewmodel/RecordViewModel.kt | Memory-Z | 234,554,362 | false | {"Gradle": 7, "Java Properties": 2, "Shell": 1, "Text": 1, "Ignore List": 6, "Batchfile": 1, "Markdown": 1, "Proguard": 5, "Java": 94, "Kotlin": 161, "XML": 301, "INI": 2} | package com.inz.z.note_book.viewmodel
import android.text.TextUtils
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import com.inz.z.base.util.BaseTools
import com.inz.z.note_book.bean.record.RecordInfoStatus
import com.inz.z.note_book.database.bean.RecordInfo
import com.inz.z.note_book.database.controller.RecordInfoController
import java.util.*
/**
*
* @author Zhenglj
* @version 1.0.0
* Create by inz in 2020/09/10 14:14.
*/
class RecordViewModel : ViewModel() {
private var recordInfoList: MutableLiveData<MutableList<RecordInfoStatus>>? = null
/**
* 记录列表数量
*/
private var recordListSizeLiveData: MutableLiveData<Int>? = null
/**
* 获取记录列表
*/
fun getRecordInfoList(): MutableLiveData<MutableList<RecordInfoStatus>> {
if (recordListSizeLiveData == null) {
recordListSizeLiveData = MutableLiveData()
}
if (recordInfoList == null) {
recordInfoList = MutableLiveData()
refreshRecordList()
}
return recordInfoList!!
}
/**
* 设置记录列表
*/
fun setRecordInfoList(recordInfoList: MutableList<RecordInfo>) {
recordInfoList.sortWith(RecordListComparator())
val orderList = mutableListOf<Array<String>>()
val recordInfoStatusList = mutableListOf<RecordInfoStatus>()
var lastTime = "0"
for (position in 0..(recordInfoList.size - 1)) {
val info = recordInfoList.get(position)
val recordInfoStatus = RecordInfoStatus()
recordInfoStatus.setRecordInfo(info)
recordInfoStatus.isTitle = false
recordInfoStatusList.add(recordInfoStatus)
val timeStr =
BaseTools.getDateFormat("yyyy-MM", Locale.getDefault()).format(info.recordDate)
if (lastTime != timeStr) {
orderList.add(arrayOf(position.toString(), timeStr))
lastTime = timeStr
}
}
for (position in (orderList.size - 1)..0) {
val recordInfoStatus = RecordInfoStatus()
recordInfoStatus.isTitle = true
recordInfoStatus.titleName = orderList.get(position)[1].toString()
recordInfoStatusList.add(orderList.get(position)[0].toInt(), recordInfoStatus)
}
this.recordInfoList?.value = recordInfoStatusList
}
/**
* 刷新
*/
fun refreshRecordList() {
queryRecordList("", false)
}
/**
* 查询记录列表
*/
fun queryRecordList(searchContent: String, isSearch: Boolean) {
var list: MutableList<RecordInfo>? = null
if (TextUtils.isEmpty(searchContent)) {
list = RecordInfoController.findAll()
} else {
list = RecordInfoController.querySearchList(searchContent, 10, isSearch)
}
resetRecordList(list)
}
private fun resetRecordList(list: MutableList<RecordInfo>?) {
recordListSizeLiveData?.value = (if (list == null) 0 else list.size)
if (list != null && list.size > 0) {
setRecordInfoList(list)
} else {
recordInfoList?.value = mutableListOf()
}
}
private class RecordListComparator : Comparator<RecordInfo> {
override fun compare(o1: RecordInfo?, o2: RecordInfo?): Int {
if (o1 == null || o2 == null) {
return 1
}
return if (o1.recordDate.time > o2.recordDate.time) {
1
} else if (o1.recordDate.time < o2.createDate.time) {
-1
} else {
0
}
}
}
/**
* 获取记录数量
*/
fun getRecordInfoListSize(): MutableLiveData<Int> {
if (recordInfoList == null) {
recordInfoList = MutableLiveData()
}
if (recordListSizeLiveData == null) {
recordListSizeLiveData = MutableLiveData(0)
refreshRecordList()
}
return recordListSizeLiveData!!
}
} | 1 | null | 1 | 1 | 387a68ede15df55eb95477515452f415fdd23e19 | 4,015 | NoteBook | Apache License 2.0 |
app/src/main/java/me/mauricee/dreamscape/daydream/DisplayManager.kt | Dumblydore | 168,185,395 | false | null | package me.mauricee.dreamscape.daydream
import android.os.Build
import android.util.DisplayMetrics
import me.mauricee.ext.logd
import javax.inject.Inject
class DisplayManager @Inject constructor(private val service: DayDreamService) {
fun isHdrSupported() = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
service.windowManager.defaultDisplay.isHdr
} else {
false
}
fun getDisplayType(): DisplayType {
val displayMetrics = DisplayMetrics()
val width: Int = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
service.windowManager.defaultDisplay.supportedModes
.map { it.physicalHeight }
.maxBy { it } ?: 0
} else {
service.windowManager.defaultDisplay.getMetrics(displayMetrics)
displayMetrics.widthPixels
}
logd("width: $width")
return when {
width < 1080 -> DisplayType.SD
width in 1080..2160 -> DisplayType.HD
else -> DisplayType.UHD
}
}
enum class DisplayType {
UHD,
HD,
SD
}
} | 0 | Kotlin | 0 | 1 | 2da7590de28214a9642b63508a8906d890469895 | 1,133 | DreamScape | MIT License |
app/src/androidTest/java/com/unagit/douuajobsevents/ui/MainActivityTest.kt | mirokolodii | 147,497,109 | false | {"Gradle": 5, "Java Properties": 2, "Shell": 1, "Text": 1, "Ignore List": 4, "Batchfile": 1, "Markdown": 1, "Java": 4, "Kotlin": 35, "Proguard": 1, "XML": 31} | package com.unagit.douuajobsevents.ui
import androidx.test.espresso.Espresso.onView
import androidx.test.espresso.action.ViewActions.click
import androidx.test.espresso.matcher.ViewMatchers.withId
import androidx.test.ext.junit.runners.AndroidJUnit4
import androidx.test.filters.LargeTest
import androidx.test.rule.ActivityTestRule
import com.unagit.douuajobsevents.R
import com.unagit.douuajobsevents.ui.list.MainActivity
import org.junit.Rule
import org.junit.Test
import org.junit.runner.RunWith
@LargeTest
@RunWith(AndroidJUnit4::class)
class MainActivityTest {
@Rule
@JvmField
var mActivityTestRule = ActivityTestRule(MainActivity::class.java)
@Test
fun mainActivityTest1() {
val bottomNavigationItemView = onView((withId(R.id.navigation_events)))
bottomNavigationItemView.perform(click())
// textView.check(matches(withText("Vacancies")))
}
}
| 1 | null | 1 | 1 | d2b2f25596c8826180a2e097f5a92180890cb389 | 907 | Dou.ua-Jobs-Events | Apache License 2.0 |
openopenradioservice/src/main/java/com/charlyghislain/openopenradio/service/radio/settings/SettingsService.kt | cghislai | 839,943,421 | false | {"Kotlin": 97513, "Java": 52469} | package com.charlyghislain.openopenradio.service.radio.settings
import android.app.Service
import android.content.Intent
import android.os.IBinder
import androidx.datastore.core.DataStore
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import dagger.hilt.android.AndroidEntryPoint
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.FlowPreview
import kotlinx.coroutines.channels.BufferOverflow
import kotlinx.coroutines.channels.Channel
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.catch
import kotlinx.coroutines.flow.consumeAsFlow
import kotlinx.coroutines.flow.debounce
import kotlinx.coroutines.launch
import javax.inject.Inject
@AndroidEntryPoint
class SettingsService : Service() {
@Inject
lateinit var dataStore: DataStore<Settings>
override fun onBind(intent: Intent?): IBinder? {
TODO("Not yet implemented")
}
}
@HiltViewModel
class SettingsViewModel @Inject constructor(
private val dataStore: DataStore<Settings>,
) : ViewModel() {
private val saveSettingsChannel = Channel<Settings>(
capacity = 1,
onBufferOverflow = BufferOverflow.DROP_OLDEST
)
val settingsFlow: Flow<Settings> = dataStore.data.catch { _ ->
// Handle exceptions, e.g., emit default settings
emit(Settings())
}
init {
@OptIn(FlowPreview::class)
viewModelScope.launch {
saveSettingsChannel.consumeAsFlow()
.debounce(500)
.collect { newSettings ->
dataStore.updateData { currentSettings ->
currentSettings.copy(
connectTimeoutMs = newSettings.connectTimeoutMs,
readTimeoutMs = newSettings.readTimeoutMs,
liveTargetOffsetMs = newSettings.liveTargetOffsetMs,
fallbackMaxPlaybackSpeed = newSettings.fallbackMaxPlaybackSpeed,
fallbackMinPlaybackSpeed = newSettings.fallbackMinPlaybackSpeed
)
}
}
}
}
fun saveSettings(newSettings: Settings) {
viewModelScope.launch {
saveSettingsChannel.send(newSettings)
}
}
}
| 0 | Kotlin | 0 | 0 | 8ca2a7684638c12781819964366bc3c098d3a217 | 2,303 | openopenradio | MIT License |
bukkit/rpk-auctions-bukkit/src/main/kotlin/com/rpkit/auctions/bukkit/database/table/RPKBidTable.kt | Nyrheim | 269,929,653 | true | {"Kotlin": 2944589, "Java": 1237516, "HTML": 94789, "JavaScript": 640, "CSS": 607} | /*
* Copyright 2016 <NAME>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.rpkit.auctions.bukkit.database.table
import com.rpkit.auctions.bukkit.RPKAuctionsBukkit
import com.rpkit.auctions.bukkit.auction.RPKAuction
import com.rpkit.auctions.bukkit.auction.RPKAuctionProvider
import com.rpkit.auctions.bukkit.bid.RPKBid
import com.rpkit.auctions.bukkit.bid.RPKBidImpl
import com.rpkit.auctions.bukkit.database.jooq.rpkit.Tables.RPKIT_BID
import com.rpkit.characters.bukkit.character.RPKCharacterProvider
import com.rpkit.core.database.Database
import com.rpkit.core.database.Table
import org.ehcache.config.builders.CacheConfigurationBuilder
import org.ehcache.config.builders.ResourcePoolsBuilder
import org.jooq.impl.DSL.constraint
import org.jooq.impl.SQLDataType
/**
* Represents the bid table.
*/
class RPKBidTable(database: Database, private val plugin: RPKAuctionsBukkit): Table<RPKBid>(database, RPKBid::class) {
private val cache = if (plugin.config.getBoolean("caching.rpkit_bid.id.enabled")) {
database.cacheManager.createCache("rpk-auctions-bukkit.rpkit_bid.id", CacheConfigurationBuilder
.newCacheConfigurationBuilder(Int::class.javaObjectType, RPKBid::class.java,
ResourcePoolsBuilder.heap(plugin.config.getLong("caching.rpkit_bid.id.size"))))
} else {
null
}
override fun create() {
database.create
.createTableIfNotExists(RPKIT_BID)
.column(RPKIT_BID.ID, SQLDataType.INTEGER.identity(true))
.column(RPKIT_BID.AUCTION_ID, SQLDataType.INTEGER)
.column(RPKIT_BID.CHARACTER_ID, SQLDataType.INTEGER)
.column(RPKIT_BID.AMOUNT, SQLDataType.INTEGER)
.constraints(
constraint("pk_rpkit_bid").primaryKey(RPKIT_BID.ID)
)
.execute()
}
override fun applyMigrations() {
if (database.getTableVersion(this) == null) {
database.setTableVersion(this, "0.4.0")
}
}
override fun insert(entity: RPKBid): Int {
database.create
.insertInto(
RPKIT_BID,
RPKIT_BID.AUCTION_ID,
RPKIT_BID.CHARACTER_ID,
RPKIT_BID.AMOUNT
)
.values(
entity.auction.id,
entity.character.id,
entity.amount
)
.execute()
val id = database.create.lastID().toInt()
entity.id = id
cache?.put(id, entity)
return id
}
override fun update(entity: RPKBid) {
database.create
.update(RPKIT_BID)
.set(RPKIT_BID.AUCTION_ID, entity.auction.id)
.set(RPKIT_BID.CHARACTER_ID, entity.character.id)
.set(RPKIT_BID.AMOUNT, entity.amount)
.where(RPKIT_BID.ID.eq(entity.id))
.execute()
cache?.put(entity.id, entity)
}
override fun get(id: Int): RPKBid? {
if (cache?.containsKey(id) == true) {
return cache.get(id)
} else {
val result = database.create
.select(
RPKIT_BID.AUCTION_ID,
RPKIT_BID.CHARACTER_ID,
RPKIT_BID.AMOUNT
)
.from(RPKIT_BID)
.where(RPKIT_BID.ID.eq(id))
.fetchOne() ?: return null
val auctionProvider = plugin.core.serviceManager.getServiceProvider(RPKAuctionProvider::class)
val auctionId = result.get(RPKIT_BID.AUCTION_ID)
val auction = auctionProvider.getAuction(auctionId)
val characterProvider = plugin.core.serviceManager.getServiceProvider(RPKCharacterProvider::class)
val characterId = result.get(RPKIT_BID.CHARACTER_ID)
val character = characterProvider.getCharacter(characterId)
if (auction != null && character != null) {
val bid = RPKBidImpl(
id,
auction,
character,
result.get(RPKIT_BID.AMOUNT)
)
cache?.put(bid.id, bid)
return bid
} else {
database.create
.deleteFrom(RPKIT_BID)
.where(RPKIT_BID.ID.eq(id))
.execute()
return null
}
}
}
/**
* Gets all bids for a particular auction.
*
* @return A list of the bids made on the auction
*/
fun get(auction: RPKAuction): List<RPKBid> {
val results = database.create
.select(RPKIT_BID.ID)
.from(RPKIT_BID)
.where(RPKIT_BID.AUCTION_ID.eq(auction.id))
.fetch()
return results.map { result ->
get(result.get(RPKIT_BID.ID))
}.filterNotNull()
}
override fun delete(entity: RPKBid) {
database.create
.deleteFrom(RPKIT_BID)
.where(RPKIT_BID.ID.eq(entity.id))
.execute()
cache?.remove(entity.id)
}
} | 0 | null | 0 | 0 | f2196a76e0822b2c60e4a551de317ed717bbdc7e | 5,878 | RPKit | Apache License 2.0 |
src/main/kotlin/org/jetbrains/plugins/template/api/data/BitbucketIssueState.kt | arthas-choi | 282,000,001 | false | {"Gradle Kotlin DSL": 2, "Markdown": 5, "Java Properties": 1, "YAML": 3, "Shell": 1, "Text": 1, "Ignore List": 1, "Batchfile": 1, "INI": 2, "Java": 73, "XML": 3, "SVG": 1, "Kotlin": 284} | // Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.plugins.template.api.data
@Suppress("EnumEntryName")
enum class BitbucketIssueState {
open, closed;
}
| 1 | null | 1 | 1 | 8f5821fdaf4c933abab1b4c7fb62f4fd58f72138 | 268 | intellij-bitbucket | Apache License 2.0 |
data/src/main/java/com/eram/data/remote/RemoteDataSourceImpl.kt | mreram | 280,694,936 | false | null | package com.eram.data.remote
import android.content.Context
import com.eram.data.R
import com.eram.data.mapper.mapToDailyForecast
import com.eram.data.mapper.mapToForecast
import com.eram.data.mapper.mapToWeather
import com.eram.domain.entity.Weather
import dagger.hilt.android.qualifiers.ApplicationContext
import javax.inject.Inject
public class RemoteDataSourceImpl @Inject constructor(
@ApplicationContext private val context: Context,
private val service: OpenWeatherApiService
) : RemoteDataSource {
companion object {
}
override suspend fun getCurrentWeather(cityId: Int): Weather {
val currentWeather = service.getCurrentWeather(
cityId = cityId,
units = "metric",
appId = context.getString(R.string.app_id)
)
return mapToWeather(currentWeather)
}
override suspend fun getMultipleDaysWeather(cityId: Int, cnt: Int): List<Weather> {
val multipleDaysWeather = service.getMultipleDaysWeather(
cityId,
"metric",
"en",
cnt,
context.getString(R.string.app_id)
)
return mapToDailyForecast(multipleDaysWeather)
}
override suspend fun getMultipleTimesWeather(cityId: Int, cnt: Int): List<Weather> {
val multipleTimesWeather = service.getMultipleTimesWeather(
cityId,
"metric",
"en",
cnt,
context.getString(R.string.app_id)
)
return mapToForecast(multipleTimesWeather)
}
} | 0 | Kotlin | 4 | 18 | 31bbcb7f89a8afe387154c1e5bb161ed6daf947c | 1,548 | WeatherApp | MIT License |
datamodule/src/main/java/schalker/datamodule/Repository.kt | SteveChalker | 113,263,191 | false | {"Gradle": 4, "Java Properties": 2, "Shell": 1, "Text": 1, "Ignore List": 3, "Batchfile": 1, "Proguard": 2, "Java": 2, "XML": 17, "Kotlin": 14} | package schalker.datamodule
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.functions.Consumer
import io.reactivex.schedulers.Schedulers
import schalker.datamodule.local.HeroesDao
import schalker.datamodule.remote.HotsService
import java.util.*
import javax.inject.Inject
class Repository @Inject constructor(var hotsService: HotsService, var heroesDao: HeroesDao) {
fun getHeroes() = heroesDao.getAllHeroes()
fun refreshData() = hotsService.getHeroes().subscribeOn(Schedulers.io())
.subscribe{response -> heroesDao.insertHeroes(response)}
} | 0 | Kotlin | 0 | 0 | 3229cb06117cf6ce2ccafad83e079bfe4ad8ccc8 | 594 | hotsdata | Apache License 2.0 |
feature/profile/src/main/kotlin/com/adewan/mystuff/feature/account/AccountNavigation.kt | abhishekdewan101 | 564,174,144 | false | null | package com.adewan.mystuff.feature.account
import androidx.navigation.NavController
import androidx.navigation.NavGraphBuilder
import androidx.navigation.compose.composable
const val accountRoute = "account_route"
fun NavController.navigateToAccountView() {
this.navigate(accountRoute)
}
fun NavGraphBuilder.accountView(showBottomBar: (Boolean) -> Unit) {
composable(route = accountRoute) {
showBottomBar(true)
AccountView()
}
}
| 2 | Kotlin | 0 | 0 | a8cc7eccd83f8aa23a0225bae79952c7298cc80f | 461 | My-Lists | MIT License |
css-gg/src/commonMain/kotlin/compose/icons/cssggicons/RadioChecked.kt | DevSrSouza | 311,134,756 | false | {"Kotlin": 36719092} | package compose.icons.cssggicons
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.PathFillType.Companion.EvenOdd
import androidx.compose.ui.graphics.PathFillType.Companion.NonZero
import androidx.compose.ui.graphics.SolidColor
import androidx.compose.ui.graphics.StrokeCap
import androidx.compose.ui.graphics.StrokeCap.Companion.Butt
import androidx.compose.ui.graphics.StrokeJoin
import androidx.compose.ui.graphics.StrokeJoin.Companion.Miter
import androidx.compose.ui.graphics.vector.ImageVector
import androidx.compose.ui.graphics.vector.ImageVector.Builder
import androidx.compose.ui.graphics.vector.path
import androidx.compose.ui.unit.dp
import compose.icons.CssGgIcons
public val CssGgIcons.RadioChecked: ImageVector
get() {
if (_radioChecked != null) {
return _radioChecked!!
}
_radioChecked = Builder(name = "RadioChecked", defaultWidth = 24.0.dp, defaultHeight =
24.0.dp, viewportWidth = 24.0f, viewportHeight = 24.0f).apply {
path(fill = SolidColor(Color(0xFF000000)), stroke = null, strokeLineWidth = 0.0f,
strokeLineCap = Butt, strokeLineJoin = Miter, strokeLineMiter = 4.0f,
pathFillType = NonZero) {
moveTo(12.0f, 16.0f)
curveTo(14.209f, 16.0f, 16.0f, 14.209f, 16.0f, 12.0f)
curveTo(16.0f, 9.791f, 14.209f, 8.0f, 12.0f, 8.0f)
curveTo(9.791f, 8.0f, 8.0f, 9.791f, 8.0f, 12.0f)
curveTo(8.0f, 14.209f, 9.791f, 16.0f, 12.0f, 16.0f)
close()
}
path(fill = SolidColor(Color(0xFF000000)), stroke = null, strokeLineWidth = 0.0f,
strokeLineCap = Butt, strokeLineJoin = Miter, strokeLineMiter = 4.0f,
pathFillType = EvenOdd) {
moveTo(22.0f, 12.0f)
curveTo(22.0f, 17.523f, 17.523f, 22.0f, 12.0f, 22.0f)
curveTo(6.477f, 22.0f, 2.0f, 17.523f, 2.0f, 12.0f)
curveTo(2.0f, 6.477f, 6.477f, 2.0f, 12.0f, 2.0f)
curveTo(17.523f, 2.0f, 22.0f, 6.477f, 22.0f, 12.0f)
close()
moveTo(20.0f, 12.0f)
curveTo(20.0f, 16.418f, 16.418f, 20.0f, 12.0f, 20.0f)
curveTo(7.582f, 20.0f, 4.0f, 16.418f, 4.0f, 12.0f)
curveTo(4.0f, 7.582f, 7.582f, 4.0f, 12.0f, 4.0f)
curveTo(16.418f, 4.0f, 20.0f, 7.582f, 20.0f, 12.0f)
close()
}
}
.build()
return _radioChecked!!
}
private var _radioChecked: ImageVector? = null
| 17 | Kotlin | 25 | 571 | a660e5f3033e3222e3553f5a6e888b7054aed8cd | 2,618 | compose-icons | MIT License |
HTTPShortcuts/app/src/main/kotlin/ch/rmy/android/http_shortcuts/scripting/actions/types/WakeOnLanAction.kt | Waboodoo | 34,525,124 | false | null | package ch.rmy.android.http_shortcuts.scripting.actions.types
import ch.rmy.android.framework.extensions.logException
import ch.rmy.android.http_shortcuts.R
import ch.rmy.android.http_shortcuts.exceptions.ActionException
import ch.rmy.android.http_shortcuts.scripting.ExecutionContext
import kotlinx.coroutines.CancellationException
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.delay
import kotlinx.coroutines.withContext
import java.net.DatagramPacket
import java.net.DatagramSocket
import java.net.InetAddress
import kotlin.time.Duration.Companion.milliseconds
class WakeOnLanAction(
private val macAddress: String,
private val ipAddress: String,
private val port: Int,
) : BaseAction() {
override suspend fun execute(executionContext: ExecutionContext) {
val macAddress = parseMacAddress(macAddress)
withContext(Dispatchers.IO) {
try {
sendMagicPacket(
macAddress = macAddress,
ipAddress = InetAddress.getByName(ipAddress),
port = port,
)
} catch (e: CancellationException) {
throw e
} catch (e: Exception) {
logException(e)
throw ActionException {
getString(R.string.error_action_type_send_wol_failed, e.message)
}
}
}
}
companion object {
private const val FF: Byte = 0xff.toByte()
private const val RESEND_PACKET_COUNT = 3
private val RESEND_DELAY = 350.milliseconds
internal suspend fun sendMagicPacket(macAddress: List<Byte>, ipAddress: InetAddress, port: Int) {
val data = mutableListOf(FF, FF, FF, FF, FF, FF)
for (i in 0 until 16) {
data.addAll(macAddress)
}
val bytes = data.toByteArray()
val packet = DatagramPacket(bytes, bytes.size, ipAddress, port)
DatagramSocket()
.use { socket ->
for (i in 0 until RESEND_PACKET_COUNT) {
if (i != 0) {
delay(RESEND_DELAY)
}
socket.send(packet)
}
}
}
internal fun parseMacAddress(macAddress: String): List<Byte> =
macAddress.split(':', '-')
.mapNotNull {
it
.takeIf { it.length <= 2 }
?.toIntOrNull(16)
?.toByte()
}
.takeIf { it.size == 6 }
?: throw ActionException {
getString(R.string.error_action_type_send_wol_invalid_mac_address, macAddress)
}
}
}
| 18 | Kotlin | 100 | 749 | 72abafd7e3bbe68647a109cb4d5a1d3b97a73d31 | 2,819 | HTTP-Shortcuts | MIT License |
HTTPShortcuts/app/src/main/kotlin/ch/rmy/android/http_shortcuts/scripting/actions/types/WakeOnLanAction.kt | Waboodoo | 34,525,124 | false | null | package ch.rmy.android.http_shortcuts.scripting.actions.types
import ch.rmy.android.framework.extensions.logException
import ch.rmy.android.http_shortcuts.R
import ch.rmy.android.http_shortcuts.exceptions.ActionException
import ch.rmy.android.http_shortcuts.scripting.ExecutionContext
import kotlinx.coroutines.CancellationException
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.delay
import kotlinx.coroutines.withContext
import java.net.DatagramPacket
import java.net.DatagramSocket
import java.net.InetAddress
import kotlin.time.Duration.Companion.milliseconds
class WakeOnLanAction(
private val macAddress: String,
private val ipAddress: String,
private val port: Int,
) : BaseAction() {
override suspend fun execute(executionContext: ExecutionContext) {
val macAddress = parseMacAddress(macAddress)
withContext(Dispatchers.IO) {
try {
sendMagicPacket(
macAddress = macAddress,
ipAddress = InetAddress.getByName(ipAddress),
port = port,
)
} catch (e: CancellationException) {
throw e
} catch (e: Exception) {
logException(e)
throw ActionException {
getString(R.string.error_action_type_send_wol_failed, e.message)
}
}
}
}
companion object {
private const val FF: Byte = 0xff.toByte()
private const val RESEND_PACKET_COUNT = 3
private val RESEND_DELAY = 350.milliseconds
internal suspend fun sendMagicPacket(macAddress: List<Byte>, ipAddress: InetAddress, port: Int) {
val data = mutableListOf(FF, FF, FF, FF, FF, FF)
for (i in 0 until 16) {
data.addAll(macAddress)
}
val bytes = data.toByteArray()
val packet = DatagramPacket(bytes, bytes.size, ipAddress, port)
DatagramSocket()
.use { socket ->
for (i in 0 until RESEND_PACKET_COUNT) {
if (i != 0) {
delay(RESEND_DELAY)
}
socket.send(packet)
}
}
}
internal fun parseMacAddress(macAddress: String): List<Byte> =
macAddress.split(':', '-')
.mapNotNull {
it
.takeIf { it.length <= 2 }
?.toIntOrNull(16)
?.toByte()
}
.takeIf { it.size == 6 }
?: throw ActionException {
getString(R.string.error_action_type_send_wol_invalid_mac_address, macAddress)
}
}
}
| 18 | Kotlin | 100 | 749 | 72abafd7e3bbe68647a109cb4d5a1d3b97a73d31 | 2,819 | HTTP-Shortcuts | MIT License |
src/main/kotlin/it/skrape/selects/html5/InteractiveElementPickers.kt | djcass44 | 215,034,200 | true | {"Kotlin": 136261, "HTML": 1597} | package it.skrape.selects.html5
import it.skrape.SkrapeItDslMarker
import it.skrape.core.Doc
import it.skrape.selects.elements
import org.jsoup.select.Elements
/**
* Will pick all occurrences of <details> elements from a Doc.
* The selection can be specified/limited by an additional css-selector.
* @param cssSelector
* @return Elements
*/
@SkrapeItDslMarker
fun Doc.details(cssSelector: String = "", init: Elements.() -> Unit) = elements("details$cssSelector", init)
/**
* Will pick all occurrences of <dialog> elements from a Doc.
* The selection can be specified/limited by an additional css-selector.
* @param cssSelector
* @return Elements
*/
@SkrapeItDslMarker
fun Doc.dialog(cssSelector: String = "", init: Elements.() -> Unit) = elements("dialog$cssSelector", init)
/**
* Will pick all occurrences of <menu> elements from a Doc.
* The selection can be specified/limited by an additional css-selector.
* @param cssSelector
* @return Elements
*/
@SkrapeItDslMarker
fun Doc.menu(cssSelector: String = "", init: Elements.() -> Unit) = elements("menu$cssSelector", init)
/**
* Will pick all occurrences of <menuitem> elements from a Doc.
* The selection can be specified/limited by an additional css-selector.
* @param cssSelector
* @return Elements
*/
@SkrapeItDslMarker
fun Doc.menuitem(cssSelector: String = "", init: Elements.() -> Unit) = elements("menuitem$cssSelector", init)
/**
* Will pick all occurrences of <summary> elements from a Doc.
* The selection can be specified/limited by an additional css-selector.
* @param cssSelector
* @return Elements
*/
@SkrapeItDslMarker
fun Doc.summary(cssSelector: String = "", init: Elements.() -> Unit) = elements("summary$cssSelector", init)
| 0 | Kotlin | 0 | 0 | 800935472219082c5cdf41e6070fa4b62c078447 | 1,727 | skrape.it | MIT License |
datagen/src/main/kotlin/juuxel/adorn/datagen/Id.kt | Juuxel | 182,782,106 | false | {"Kotlin": 547440, "Java": 27621} | package juuxel.adorn.datagen
import java.io.Serializable
/**
* A namespaced ID. Mimics `net.minecraft.util.Identifier`.
*/
data class Id(val namespace: String, val path: String) : Serializable {
init {
require(validateIdCharacters(namespace, isPath = false)) {
"ID namespace '$namespace' contains characters not matching [a-z0-9.-_]"
}
require(validateIdCharacters(path, isPath = true)) {
"ID path '$path' contains characters not matching [a-z0-9.-_/]"
}
}
/**
* Suffixes the path with a [suffix] without separation.
*/
fun rawSuffixed(suffix: String): Id = Id(namespace, path + suffix)
/**
* Suffixes the path with an underscore-separated [suffix].
*/
fun suffixed(suffix: String): Id = rawSuffixed("_$suffix")
override fun toString() = "$namespace:$path"
companion object {
fun parse(id: String): Id {
require(':' in id) { "Id '$id' does not contain colon (:)!" }
val parts = id.split(":")
require(parts.size == 2) { "Id '$id' must consist of exactly two parts! Found: ${parts.size}" }
val (ns, path) = parts
return Id(ns, path)
}
private fun validateIdCharacters(component: String, isPath: Boolean): Boolean =
component.all {
it in 'a'..'z' || it in '0'..'9' || it == '.' || it == '-' || it == '_' || (isPath && it == '/')
}
}
}
| 54 | Kotlin | 30 | 93 | 3d47e109812c8be26fc4fb581b9945c39ba6c96a | 1,477 | Adorn | MIT License |
Oxygen/core/src/main/kotlin/cc/fyre/stark/core/pidgin/morph/adapter/impl/UUIDTypeAdapter.kt | AndyReckt | 364,514,997 | false | {"Java": 12055418, "Kotlin": 766337, "Shell": 5518} | /*
* Copyright (c) 2020.
* Created by YoloSanta
* Created On 10/22/20, 1:23 AM
*/
package cc.fyre.stark.core.pidgin.morph.adapter.impl
import cc.fyre.stark.core.pidgin.morph.adapter.JsonTypeAdapter
import com.google.gson.JsonElement
import com.google.gson.JsonPrimitive
import java.util.*
class UUIDTypeAdapter : JsonTypeAdapter<UUID> {
override fun toJson(src: UUID): JsonElement {
return JsonPrimitive(src.toString())
}
override fun toType(element: JsonElement): UUID {
return UUID.fromString(element.asString)
}
}
| 1 | null | 1 | 1 | 200501c7eb4aaf5709b4adceb053fee6707173fa | 559 | Old-Code | Apache License 2.0 |
core/data/src/main/java/cardosofgui/android/pokedexcompose/core/data/database/dao/TypeDao.kt | CardosofGui | 609,740,815 | false | null | package cardosofgui.android.pokedexcompose.core.data.database.dao
import androidx.room.Dao
import androidx.room.Insert
import androidx.room.OnConflictStrategy
import androidx.room.Query
import cardosofgui.android.pokedexcompose.core.data.database.entity.TypeEntity
import kotlinx.coroutines.flow.Flow
@Dao
interface TypeDao {
@Query("SELECT * FROM type")
fun queryAll(): Flow<List<TypeEntity>>
@Query("SELECT * FROM type WHERE id = :id")
fun queryById(id: Long): Flow<TypeEntity?>
@Query("SELECT * FROM type WHERE name = :name")
fun queryByName(name: String): Flow<TypeEntity?>
@Query("DELETE from type")
suspend fun deleteAllType()
@Insert(onConflict = OnConflictStrategy.REPLACE)
suspend fun insert(typeEntity: TypeEntity): Long
} | 0 | Kotlin | 0 | 1 | 67c081c7e0ba18bbb06dd736ffb41699defa3836 | 780 | pokedex-app-compose | MIT License |
app/src/main/java/com/androidstarter/ui/productdetails/ProductDetailsFragment.kt | syedtehrimabbas | 526,100,544 | false | null | package com.androidstarter.ui.productdetails
import android.os.Bundle
import android.view.Menu
import android.view.View
import android.widget.ImageView
import android.widget.TextView
import androidx.appcompat.content.res.AppCompatResources
import androidx.constraintlayout.widget.ConstraintLayout
import androidx.fragment.app.viewModels
import com.dida.procop.BR
import com.dida.procop.R
import com.androidstarter.base.clickevents.setOnClick
import com.androidstarter.base.navgraph.BaseNavViewModelFragment
import com.androidstarter.base.viewmodel.Dispatcher
import com.dida.procop.databinding.FragmentProductDetailsBinding
import com.androidstarter.ui.home.adapter.ProductAttributeAdapter
import com.androidstarter.ui.interfaces.ProductUpdateListener
import com.androidstarter.ui.productdetails.adapter.ProductImagesSliderAdapter
import com.smarteist.autoimageslider.IndicatorView.animation.type.IndicatorAnimationType
import com.smarteist.autoimageslider.SliderAnimations
import com.smarteist.autoimageslider.SliderView
import dagger.hilt.android.AndroidEntryPoint
import me.gilo.woodroid.models.Product
import me.gilo.woodroid.models.ProductAttribute
import javax.inject.Inject
@AndroidEntryPoint
class ProductDetailsFragment :
BaseNavViewModelFragment<FragmentProductDetailsBinding, IProductDetails.State, ProductDetailsVM>(),
ProductUpdateListener {
override val bindingVariableId = BR.viewModel
override val bindingViewStateVariableId = BR.viewState
override val viewModel: ProductDetailsVM by viewModels()
override val layoutResId: Int = R.layout.fragment_product_details
override fun getToolBarTitle() = ""
override fun toolBarVisibility(): Boolean = true
override fun hasOptionMenu() = true
override fun onClick(id: Int) {
when (id) {
R.id.addToCartBtn -> {
viewModel.databaseHelper.cartCount()
val product = viewState.product.value
if (product?.price == "0.0") {
showToast(getString(R.string.price_unavailable))
return
}
if (viewModel.isInCart) {
setAddCartText()
} else {
setRemoveCartText()
}
product?.let {
val messageId = viewModel.databaseHelper.addToCart(product)
showToast(getString(messageId))
}
}
R.id.addToFavBtn -> {
viewModel.databaseHelper.favouriteCount()
val product = viewState.product.value
if (product?.price == "0.0") {
showToast(getString(R.string.price_unavailable))
return
}
if (viewModel.isFav) {
unFavourite()
} else {
favourite()
}
product?.let {
viewModel.databaseHelper.addToFav(product)
}
}
}
}
@Inject
lateinit var attributeAdapter: ProductAttributeAdapter
@Inject
lateinit var productImagesSliderAdapter: ProductImagesSliderAdapter
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
viewState.product.observe(viewLifecycleOwner) {
viewModel.launch(Dispatcher.Background) {
viewModel.databaseHelper.getProductById(it.id)?.let { _ ->
setRemoveCartText()
} ?: setAddCartText()
viewModel.databaseHelper.getFavProductById(it.id)?.let { _ ->
favourite()
} ?: unFavourite()
}
attributeAdapter.setList(it.productAttributes.filter { productAttribute -> productAttribute.isVisible })
productImagesSliderAdapter.setList(it.images)
}
initRecyclerView()
setupSlider()
}
private fun setAddCartText() {
viewModel.isInCart = false
viewModel.launch(Dispatcher.Main) {
mViewDataBinding.addToCartBtn.text = getString(R.string.common_add_to_cart)
}
}
private fun setRemoveCartText() {
viewModel.isInCart = true
viewModel.launch(Dispatcher.Main) {
mViewDataBinding.addToCartBtn.text = getString(R.string.common_remove_to_cart)
}
}
private fun unFavourite() {
viewModel.isFav = false
viewModel.launch(Dispatcher.Main) {
mViewDataBinding.addToFavBtn.setImageDrawable(context?.let {
AppCompatResources.getDrawable(
it, R.drawable.circle_white_heart
)
})
}
}
private fun favourite() {
viewModel.isFav = true
viewModel.launch(Dispatcher.Main) {
mViewDataBinding.addToFavBtn.setImageDrawable(context?.let {
AppCompatResources.getDrawable(
it, R.drawable.circle_red_heart
)
})
}
}
private fun initRecyclerView() {
with(mViewDataBinding) {
attributeAdapter.onItemClickListener = attributeClickListener
attributeRecyclerView.adapter = attributeAdapter
}
}
private fun setupSlider() {
with(mViewDataBinding) {
sliderView.setSliderAdapter(productImagesSliderAdapter)
sliderView.setIndicatorAnimation(
IndicatorAnimationType.WORM
) //set indicator animation by using IndicatorAnimationType. :WORM or THIN_WORM or COLOR or DROP or FILL or NONE or SCALE or SCALE_DOWN or SLIDE and SWAP!!
sliderView.setSliderTransformAnimation(SliderAnimations.SIMPLETRANSFORMATION)
sliderView.autoCycleDirection = SliderView.AUTO_CYCLE_DIRECTION_BACK_AND_FORTH
sliderView.scrollTimeInSec = 4 //set scroll delay in seconds :
sliderView.startAutoCycle()
}
}
override fun onProductUpdate(product: Product) {
}
override fun onAttributeUpdate(attribute: ProductAttribute, selectedValue: String) {
val productAttribute =
viewState.product.value?.productAttributes?.find { it.id == attribute.id }
val index = viewState.product.value?.productAttributes?.indexOf(productAttribute)
if (index != null) {
if (index > -1) {
productAttribute?.selectedAttribute = selectedValue
productAttribute?.let {
viewState.product.value?.productAttributes?.set(index, it)
viewState.product.value?.productAttributes?.filter { productAttribute -> productAttribute.isVisible }?.let { productAttributes ->
attributeAdapter.setList(productAttributes)
}
viewModel.setVariationPrice(requireContext())
}
}
}
}
private val attributeClickListener =
{ view: View, position: Int, data: ProductAttribute? ->
AttributeBottomSheet(data, this).show(parentFragmentManager, "AttributeBottomSheet")
}
override fun onPrepareOptionsMenu(menu: Menu) {
val menuItem = menu.findItem(R.id.itemCartMenu)
val cartLayout = menuItem.actionView as ConstraintLayout
val cartButton = cartLayout.findViewById<ImageView>(R.id.cartImage)
val cartCount = cartLayout.findViewById<TextView>(R.id.cartCount)
val favImage = cartLayout.findViewById<ImageView>(R.id.favImage)
val favCount = cartLayout.findViewById<TextView>(R.id.favCount)
cartCount.text = viewModel.databaseHelper.cartCount.value.toString()
favCount.text = viewModel.databaseHelper.favCount.value.toString()
cartButton.setOnClick {
navigateToCart(viewModel.databaseHelper)
}
favImage.setOnClick {
navigateToFavourite(viewModel.databaseHelper)
}
}
override fun onResume() {
super.onResume()
viewModel.databaseHelper.cartCount()
viewModel.databaseHelper.favouriteCount()
}
override fun postExecutePendingBindings(savedInstanceState: Bundle?) {
super.postExecutePendingBindings(savedInstanceState)
viewModel.databaseHelper.cartCount.observe(viewLifecycleOwner) {
requireActivity().invalidateOptionsMenu()
}
viewModel.databaseHelper.favCount.observe(viewLifecycleOwner) {
requireActivity().invalidateOptionsMenu()
}
}
} | 0 | Kotlin | 0 | 0 | 705c0d72a2df3ded12f55b7b9baeec85fe645555 | 8,604 | dida-procop-android | MIT License |
platform/statistics/src/com/intellij/internal/statistic/StructuredIdeActivity.kt | balagurusurendar | 242,815,939 | false | {"Text": 6171, "XML": 6227, "YAML": 417, "Ant Build System": 13, "Shell": 560, "Markdown": 506, "Ignore List": 92, "Git Attributes": 9, "EditorConfig": 227, "Batchfile": 27, "SVG": 2342, "Java": 74289, "C++": 34, "HTML": 2868, "Kotlin": 38979, "DTrace": 1, "Gradle": 450, "Java Properties": 202, "INI": 408, "JFlex": 31, "CSS": 55, "Groovy": 3447, "XSLT": 112, "JavaScript": 197, "JSON": 835, "desktop": 1, "Python": 11783, "JAR Manifest": 16, "PHP": 47, "Gradle Kotlin DSL": 260, "Protocol Buffer": 3, "C#": 37, "Smalltalk": 17, "Diff": 131, "Erlang": 1, "Rich Text Format": 2, "AspectJ": 2, "Perl": 6, "HLSL": 2, "Objective-C": 22, "CoffeeScript": 3, "HTTP": 2, "JSON with Comments": 58, "OpenStep Property List": 46, "Tcl": 1, "PlantUML": 4, "fish": 1, "Dockerfile": 3, "Prolog": 2, "ColdFusion": 2, "Turtle": 2, "TeX": 11, "Elixir": 2, "Ruby": 4, "XML Property List": 86, "Vim Script": 7, "Vim Snippet": 3, "Vim Help File": 2, "Starlark": 2, "E-mail": 18, "Roff": 245, "Roff Manpage": 39, "Swift": 3, "Maven POM": 60, "C": 46, "TOML": 42, "Proguard": 2, "Checksums": 58, "Java Server Pages": 8, "GraphQL": 49, "AMPL": 4, "Linux Kernel Module": 1, "Makefile": 1, "CMake": 14, "Microsoft Visual Studio Solution": 4, "VBScript": 1, "NSIS": 5, "Thrift": 3, "Cython": 14, "reStructuredText": 55, "Regular Expression": 3, "JSON5": 4} | // Copyright 2000-2021 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.internal.statistic
import com.intellij.internal.statistic.eventLog.EventLogGroup
import com.intellij.internal.statistic.eventLog.events.EventField
import com.intellij.internal.statistic.eventLog.events.EventFields
import com.intellij.internal.statistic.eventLog.events.EventPair
import com.intellij.internal.statistic.eventLog.events.VarargEventId
import com.intellij.openapi.diagnostic.Logger
import com.intellij.openapi.project.Project
import com.intellij.util.TimeoutUtil
import org.jetbrains.annotations.ApiStatus
import org.jetbrains.concurrency.Promise
import java.util.concurrent.atomic.AtomicInteger
private val LOG = Logger.getInstance(StructuredIdeActivity::class.java)
/**
* New style API to record information about process.
* It allows you to record start/finish events, calculate duration and link them by common id.
*
* To record a process:
* - Register ide activity in event log group (see [com.intellij.internal.statistic.eventLog.EventLogGroup.registerIdeActivity]).
* - Use [com.intellij.internal.statistic.IdeActivityDefinition.started] or
* [com.intellij.internal.statistic.IdeActivityDefinition.startedAsync] to record start event and
* [com.intellij.internal.statistic.StructuredIdeActivity.finished] to record finish event.
*
* See example in dev-guide/fus-collectors.md.
*/
@ApiStatus.Internal
class StructuredIdeActivity internal constructor(private val projectOrNullForApplication: Project?,
private val ideActivityDefinition: IdeActivityDefinition) {
private val id = counter.incrementAndGet()
private var state = IdeActivityState.NOT_STARTED
private var startedTimestamp = 0L
@JvmOverloads
fun started(dataSupplier: (() -> List<EventPair<*>>)? = null): StructuredIdeActivity {
if (!LOG.assertTrue(state == IdeActivityState.NOT_STARTED, state.name)) return this
state = IdeActivityState.STARTED
val data: MutableList<EventPair<*>> = mutableListOf(IdeActivityDefinition.activityId.with(id))
if (dataSupplier != null) {
data.addAll(dataSupplier())
}
startedTimestamp = System.nanoTime()
ideActivityDefinition.started.log(projectOrNullForApplication, data)
return this
}
fun startedAsync(dataSupplier: () -> Promise<List<EventPair<*>>>): StructuredIdeActivity {
if (!LOG.assertTrue(state == IdeActivityState.NOT_STARTED, state.name)) return this
state = IdeActivityState.STARTED
startedTimestamp = System.nanoTime()
val data: MutableList<EventPair<*>> = mutableListOf(IdeActivityDefinition.activityId.with(id))
dataSupplier().then { additionalData ->
data.addAll(additionalData)
ideActivityDefinition.started.log(projectOrNullForApplication, data)
}
return this
}
@JvmOverloads
fun stageStarted(stage: VarargEventId, dataSupplier: (() -> List<EventPair<*>>)? = null): StructuredIdeActivity {
if (!LOG.assertTrue(state == IdeActivityState.STARTED, state.name)) return this
val data: MutableList<EventPair<*>> = mutableListOf(IdeActivityDefinition.activityId.with(id))
if (dataSupplier != null) {
data.addAll(dataSupplier())
}
stage.log(projectOrNullForApplication, data)
return this
}
@JvmOverloads
fun finished(dataSupplier: (() -> List<EventPair<*>>)? = null): StructuredIdeActivity {
if (!LOG.assertTrue(state == IdeActivityState.STARTED, state.name)) return this
state = IdeActivityState.FINISHED
val data: MutableList<EventPair<*>> = mutableListOf(IdeActivityDefinition.activityId.with(id))
if (dataSupplier != null) {
data.addAll(dataSupplier())
}
data.add(EventFields.DurationMs.with(TimeoutUtil.getDurationMillis(startedTimestamp)))
ideActivityDefinition.finished.log(projectOrNullForApplication, data)
return this
}
companion object {
private val counter = AtomicInteger(0)
}
}
class IdeActivityDefinition internal constructor(val group: EventLogGroup,
val activityName: String?,
startEventAdditionalFields: Array<EventField<*>> = emptyArray(),
finishEventAdditionalFields: Array<EventField<*>> = emptyArray()) {
val started = group.registerVarargEvent(appendActivityName(activityName, "started"), activityId, *startEventAdditionalFields)
val finished = group.registerVarargEvent(appendActivityName(activityName, "finished"), activityId, EventFields.DurationMs,
*finishEventAdditionalFields)
@JvmOverloads
fun started(project: Project?, dataSupplier: (() -> List<EventPair<*>>)? = null): StructuredIdeActivity {
return StructuredIdeActivity(project, this).started(dataSupplier)
}
fun startedAsync(project: Project?, dataSupplier: () -> Promise<List<EventPair<*>>>): StructuredIdeActivity {
return StructuredIdeActivity(project, this).startedAsync(dataSupplier)
}
private fun appendActivityName(activityName: String?, state: String): String {
if (activityName == null) return state
return "$activityName.$state"
}
@JvmOverloads
fun registerStage(stageName: String, additionalFields: Array<EventField<*>> = emptyArray()): VarargEventId = group.registerVarargEvent(
appendActivityName(activityName, stageName), activityId, *additionalFields)
companion object {
val activityId = EventFields.Int("ide_activity_id")
}
} | 1 | null | 1 | 1 | 7977da3c835d356e27f2cd5541178fb794ca094f | 5,614 | intellij-community | Apache License 2.0 |
app/src/main/java/com/mlievens/listdetailapp/ui/details/DetailsViewModel.kt | mjl757 | 593,397,660 | false | null | package com.mlievens.listdetailapp.ui.details
import androidx.lifecycle.SavedStateHandle
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.mlievens.listdetailapp.domain.models.ItemDetail
import com.mlievens.listdetailapp.domain.repositories.ItemDetailRepository
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.launch
import javax.inject.Inject
@HiltViewModel
class DetailsViewModel @Inject constructor(
private val itemDetailRepository: ItemDetailRepository,
savedStateHandle: SavedStateHandle
) : ViewModel() {
private val itemId: String? = savedStateHandle["itemId"]
private val _detailState: MutableStateFlow<DetailViewState> =
MutableStateFlow(DetailViewState.LoadingState)
val detailState: StateFlow<DetailViewState> get() = _detailState
init {
loadDetails()
}
fun loadDetails() {
viewModelScope.launch {
itemId?.let { id ->
itemDetailRepository.getItemDetail(id)
.onSuccess { _detailState.emit(DetailViewState.SuccessState(it)) }
.onFailure { _detailState.emit(DetailViewState.ErrorState) }
} ?: _detailState.emit(DetailViewState.ErrorState)
}
}
}
sealed class DetailViewState {
object LoadingState : DetailViewState()
data class SuccessState(val detail: ItemDetail) : DetailViewState()
object ErrorState : DetailViewState()
} | 0 | Kotlin | 0 | 0 | 6d9684560c1c78f5fb92a2522ab523997a180673 | 1,557 | ListDetailApp | MIT License |
src/main/kotlin/com/handtruth/avltree/Extensions.kt | Ktlo | 155,204,875 | false | null | @file:Suppress("unused")
package com.handtruth.avltree
fun <K: Comparable<K>, V> avlTreeMapOf() = AVLTreeMap<K, V>()
fun <K: Comparable<K>, V> avlTreeMapOf(vararg pairs: Pair<K, V>) =
AVLTreeMap<K, V>().apply { pairs.forEach { pair -> put(pair.first, pair.second) } }
fun <K: Any, V> avlTreeMapOf(comparator: Comparator<K>) = AVLTreeMap<K, V>(comparator)
fun <K: Any, V> avlTreeMapOf(vararg pairs: Pair<K, V>, comparator: Comparator<K>) =
AVLTreeMap<K, V>(comparator).apply { pairs.forEach { pair -> put(pair.first, pair.second) } }
fun <T: Comparable<T>> avlTreeSetOf() = AVLTreeSet<T>()
fun <T: Comparable<T>> avlTreeSetOf(vararg items: T) =
AVLTreeSet<T>().apply { items.forEach { item -> add(item) } }
fun <T: Any> avlTreeSetOf(comparator: Comparator<T>) = AVLTreeSet(comparator)
fun <T: Any> avlTreeSetOf(vararg items: T, comparator: Comparator<T>) =
AVLTreeSet(comparator).apply { items.forEach { item -> add(item) } }
| 0 | Kotlin | 0 | 0 | c8547e42e680e0f096b183781f55240fd59ad34a | 966 | AVLTree | MIT License |
core/src/main/kotlin/ch/ergon/dope/resolvable/expression/unaliased/type/function/stringfunction/MBLengthExpression.kt | ergon | 745,483,606 | false | {"Kotlin": 1886765} | package ch.ergon.dope.resolvable.expression.unaliased.type.function.stringfunction
import ch.ergon.dope.resolvable.expression.TypeExpression
import ch.ergon.dope.resolvable.expression.unaliased.type.function.FunctionExpression
import ch.ergon.dope.resolvable.expression.unaliased.type.toDopeType
import ch.ergon.dope.validtype.NumberType
import ch.ergon.dope.validtype.StringType
class MBLengthExpression(inStr: TypeExpression<StringType>) : FunctionExpression<NumberType>("MB_LENGTH", inStr)
fun mbLength(inStr: TypeExpression<StringType>) = MBLengthExpression(inStr)
fun mbLength(inStr: String) = mbLength(inStr.toDopeType())
| 2 | Kotlin | 0 | 6 | 40b18241d25c360080768902fc108ea70bb2f211 | 632 | dope-query-builder | MIT License |
src/main/kotlin/org/jetbrains/plugins/git/custompush/actions/PushWithOptionAction.kt | EvoGroupTN | 735,165,477 | false | {"Kotlin": 15430} | package org.jetbrains.plugins.git.custompush.actions
import com.intellij.openapi.actionSystem.AnActionEvent
import com.intellij.util.ui.JButtonAction
class PushWithOptionAction: JButtonAction("Push with Options...") {
private val gitRepoAction: GitRepoAction = GitRepoAction()
override fun actionPerformed(p0: AnActionEvent) {
return gitRepoAction.actionPerformed(p0)
}
} | 0 | Kotlin | 1 | 3 | b891793ce7829fde57aef7a60786f649eca3d002 | 394 | push-with-options-intellij-plugin | Apache License 2.0 |
src/test/kotlin/QRSegmentFactoryTest.kt | janBorowy | 833,332,515 | false | {"Kotlin": 42954} | import org.junit.jupiter.api.Test
import org.junit.jupiter.api.assertThrows
import pl.student.InputMode
import pl.student.QREncodingExcpetion
import kotlin.test.assertEquals
class QRSegmentFactoryTest {
@Test
fun shouldEncodeEmpty() {
assertThrows<IllegalArgumentException> { QRSegmentFactory.makeSegment("") }
}
@Test
fun shouldEncodeNumeric() {
assertEquals(
qrSegmentFromBitsString("0000001100 0101011001 1000011", 8, InputMode.NUMERIC),
QRSegmentFactory.makeSegment("01234567")
)
assertEquals(
qrSegmentFromBitsString("0000001100 0101011001 1010100110", 9, InputMode.NUMERIC),
QRSegmentFactory.makeSegment("012345678")
)
assertEquals(
qrSegmentFromBitsString("0000001100 0101011001 0110", 7, InputMode.NUMERIC),
QRSegmentFactory.makeSegment("0123456")
)
}
@Test
fun shouldEncodeAlphanumeric() {
assertEquals(
qrSegmentFromBitsString("01100001011 01111000110 10001011100 10110111000 10011010100 001101", 11, InputMode.ALPHANUMERIC),
QRSegmentFactory.makeSegment("HELLO WORLD")
)
assertEquals(
qrSegmentFromBitsString("00111001110 11100111001 000010", 5, InputMode.ALPHANUMERIC),
QRSegmentFactory.makeSegment("AC-42")
)
assertEquals(
qrSegmentFromBitsString("00111001110 00010110110", 4, InputMode.ALPHANUMERIC),
QRSegmentFactory.makeSegment("AC42")
)
}
@Test
fun shouldEncodeBinary() {
assertEquals(
qrSegmentFromBitsString(
""" |01000001
|01000011
|00101101
|00101000
|00110100
|00110010
|00101001
""".trimMargin()
, 7
, InputMode.BINARY),
QRSegmentFactory.makeSegment("AC-(42)")
)
}
} | 0 | Kotlin | 0 | 0 | 51e2cbcfffa81d163546e0ac7833fd2648254365 | 2,018 | QRKod | MIT License |
puzzlelayout/src/main/java/com/hypersoft/pzlayout/layouts/straight/FiveStraightLayout.kt | hypersoftdev | 859,698,909 | false | {"Kotlin": 308865} | package com.hypersoft.pzlayout.layouts.straight
import com.hypersoft.pzlayout.interfaces.Line
/**
* Developer: <NAME>
* Date: 16/09/2024
* Profile:
* -> github.com/CelestialBeats
* -> linkedin.com/in/celestialbeats
*/
class FiveStraightLayout(theme: Int) : NumberStraightLayout(theme) {
override fun getThemeCount(): Int {
return 19
}
override fun layout() {
when (theme) {
0 -> cutAreaEqualPart(0, 5, Line.Direction.HORIZONTAL)
1 -> cutAreaEqualPart(0, 5, Line.Direction.VERTICAL)
2 -> {
addLine(0, Line.Direction.HORIZONTAL, 2f / 5)
addLine(0, Line.Direction.VERTICAL, 1f / 2)
cutAreaEqualPart(2, 3, Line.Direction.VERTICAL)
}
3 -> {
addLine(0, Line.Direction.HORIZONTAL, 3f / 5)
cutAreaEqualPart(0, 3, Line.Direction.VERTICAL)
addLine(3, Line.Direction.VERTICAL, 1f / 2)
}
4 -> {
addLine(0, Line.Direction.VERTICAL, 2f / 5)
cutAreaEqualPart(0, 3, Line.Direction.HORIZONTAL)
addLine(1, Line.Direction.HORIZONTAL, 1f / 2)
}
5 -> {
addLine(0, Line.Direction.VERTICAL, 2f / 5)
cutAreaEqualPart(1, 3, Line.Direction.HORIZONTAL)
addLine(0, Line.Direction.HORIZONTAL, 1f / 2)
}
6 -> {
addLine(0, Line.Direction.HORIZONTAL, 3f / 4)
cutAreaEqualPart(1, 4, Line.Direction.VERTICAL)
}
7 -> {
addLine(0, Line.Direction.HORIZONTAL, 1f / 4)
cutAreaEqualPart(0, 4, Line.Direction.VERTICAL)
}
8 -> {
addLine(0, Line.Direction.VERTICAL, 3f / 4)
cutAreaEqualPart(1, 4, Line.Direction.HORIZONTAL)
}
9 -> {
addLine(0, Line.Direction.VERTICAL, 1f / 4)
cutAreaEqualPart(0, 4, Line.Direction.HORIZONTAL)
}
10 -> {
addLine(0, Line.Direction.HORIZONTAL, 1f / 4)
addLine(1, Line.Direction.HORIZONTAL, 2f / 3)
addLine(0, Line.Direction.VERTICAL, 1f / 2)
addLine(3, Line.Direction.VERTICAL, 1f / 2)
}
11 -> {
addLine(0, Line.Direction.VERTICAL, 1f / 4)
addLine(1, Line.Direction.VERTICAL, 2f / 3)
addLine(0, Line.Direction.HORIZONTAL, 1f / 2)
addLine(2, Line.Direction.HORIZONTAL, 1f / 2)
}
12 -> {
addCross(0, 1f / 3)
addLine(2, Line.Direction.HORIZONTAL, 1f / 2)
}
13 -> {
addCross(0, 2f / 3)
addLine(1, Line.Direction.HORIZONTAL, 1f / 2)
}
14 -> {
addCross(0, 1f / 3, 2f / 3)
addLine(3, Line.Direction.HORIZONTAL, 1f / 2)
}
15 -> {
addCross(0, 2f / 3, 1f / 3)
addLine(0, Line.Direction.HORIZONTAL, 1f / 2)
}
16 -> cutSpiral(0)
17 -> {
addLine(0, Line.Direction.HORIZONTAL, 2f / 3)
cutAreaEqualPart(0, 1, 1)
}
18 -> {
addLine(0, Line.Direction.VERTICAL, 2f / 3)
addLine(1, Line.Direction.HORIZONTAL, 1f / 3)
addLine(0, Line.Direction.HORIZONTAL, 2f / 3)
addLine(0, Line.Direction.HORIZONTAL, 1f / 3)
}
else -> cutAreaEqualPart(0, 5, Line.Direction.HORIZONTAL)
}
}
}
| 0 | Kotlin | 1 | 0 | 420b9296ddbd5cbe033d4658568151333ef4e5c4 | 3,728 | PuzzleLayout | Apache License 2.0 |
app/src/test/java/com/denysnovoa/nzbmanager/movies/domain/DeleteMovieUseCaseShould.kt | denysnovoa | 90,066,913 | false | {"Gradle": 3, "Java Properties": 2, "Shell": 1, "Text": 1, "Ignore List": 2, "Batchfile": 1, "Markdown": 1, "JSON": 4, "Proguard": 1, "Java": 2, "Kotlin": 110, "XML": 37} | package com.denysnovoa.nzbmanager.movies.domain
import com.denysnovoa.nzbmanager.radarr.movie.detail.domain.DeleteMovieUseCase
import com.denysnovoa.nzbmanager.radarr.movie.list.repository.api.MoviesApiClient
import org.junit.Before
import org.junit.Test
import org.mockito.Mock
import org.mockito.Mockito
import org.mockito.MockitoAnnotations
class DeleteMovieUseCaseShould {
private val DELETE_FILE: Boolean = true
private val MOVIE_ID: Int = 12
private val EXCLUDE_FROM_IMPORTS: Boolean = false
@Mock
lateinit var moviesApiClient: MoviesApiClient
@Before
fun setUp() {
MockitoAnnotations.initMocks(this)
}
@Test
fun callRepositoryToDeleteMovie() {
val deleteMovieUseCase = DeleteMovieUseCase(moviesApiClient)
deleteMovieUseCase.delete(MOVIE_ID, DELETE_FILE, EXCLUDE_FROM_IMPORTS)
Mockito.verify(moviesApiClient).delete(MOVIE_ID, DELETE_FILE, EXCLUDE_FROM_IMPORTS)
}
} | 0 | Kotlin | 0 | 1 | 8944e3bae4c073856f9856bf2e5064a6dadde4f7 | 954 | radarrsonarr | Apache License 2.0 |
floatwindow/src/main/java/org/yameida/floatwindow/listener/OnClickListener.kt | gallonyin | 473,181,796 | false | null | package org.yameida.floatwindow.listener
import android.view.View
/**
* Created by Gallon on 2019/8/11.
*/
interface OnClickListener {
fun onClick(v: View, event: Int)
} | 1 | Kotlin | 118 | 643 | 12eda85c122129cef74cd53d2ce5ca8f95af4422 | 178 | worktool | Apache License 2.0 |
app/src/main/java/io/github/pelmenstar1/digiDict/data/ComplexMeaning.kt | pelmenstar1 | 512,710,767 | false | null | package io.github.pelmenstar1.digiDict.data
import android.os.Parcel
import android.os.Parcelable
import io.github.pelmenstar1.digiDict.common.android.readStringOrThrow
import io.github.pelmenstar1.digiDict.common.decimalDigitCount
import io.github.pelmenstar1.digiDict.common.equalsPattern
import io.github.pelmenstar1.digiDict.common.parsePositiveInt
import io.github.pelmenstar1.digiDict.common.unsafeNewArray
enum class MeaningType {
COMMON,
LIST
}
sealed class ComplexMeaning : Parcelable {
var rawText: String = ""
protected set
/**
* A meaning with only one entry.
* Raw text scheme:
* - Mark character is 'C'
* - Actual text is after the mark character
*/
class Common : ComplexMeaning {
override val type: MeaningType
get() = MeaningType.COMMON
val text: String
constructor(parcel: Parcel) {
text = parcel.readStringOrThrow()
rawText = createCommonRawText(text)
}
constructor(text: String) {
this.text = text
rawText = createCommonRawText(text)
}
constructor(text: String, rawText: String) {
this.text = text
this.rawText = rawText
}
override fun writeToParcel(dest: Parcel, flags: Int) {
dest.writeString(text)
}
override fun equals(other: Any?) = equalsPattern(other) { o ->
text == o.text
}
override fun hashCode(): Int = text.hashCode()
override fun toString(): String {
return "ComplexMeaning.Common(text=$text)"
}
companion object CREATOR : Parcelable.Creator<Common> {
override fun createFromParcel(parcel: Parcel) = Common(parcel)
override fun newArray(size: Int) = arrayOfNulls<Common>(size)
}
}
/**
* A meaning that contains multiple distinct meanings.
*
* Raw text scheme:
* - Mark character is 'L'
* - Count of elements is after the mark character
* - Then as a delimiter '@' character
* - Actual elements are after '@' divided by [ComplexMeaning.LIST_NEW_ELEMENT_SEPARATOR] (GS) character.
*/
class List : ComplexMeaning {
override val type: MeaningType
get() = MeaningType.LIST
val elements: Array<out String>
constructor(parcel: Parcel) {
val size = parcel.readInt()
rawText = parcel.readStringOrThrow()
elements = Array(size) { parcel.readStringOrThrow() }
}
constructor(elements: Array<out String>) {
this.elements = elements
rawText = createListRawText(elements)
}
internal constructor(elements: Array<out String>, rawText: String) {
this.rawText = rawText
this.elements = elements
}
override fun writeToParcel(dest: Parcel, flags: Int) {
dest.writeInt(elements.size)
dest.writeString(rawText)
elements.forEach(dest::writeString)
}
override fun equals(other: Any?) = equalsPattern(other) { o ->
return elements.contentEquals(o.elements)
}
override fun hashCode(): Int = elements.contentHashCode()
override fun toString(): String {
return "ComplexMeaning.List(elements=${elements.contentToString()})"
}
companion object CREATOR : Parcelable.Creator<List> {
override fun createFromParcel(parcel: Parcel) = List(parcel)
override fun newArray(size: Int) = arrayOfNulls<List>(size)
}
}
abstract val type: MeaningType
abstract override fun equals(other: Any?): Boolean
abstract override fun hashCode(): Int
abstract override fun toString(): String
override fun describeContents() = 0
companion object {
const val COMMON_MARKER = 'C'
const val LIST_MARKER = 'L'
const val LIST_OLD_ELEMENT_SEPARATOR = '\n'
// 0x1D - group separator.
const val LIST_NEW_ELEMENT_SEPARATOR = 0x1D.toChar()
internal fun createCommonRawText(text: String): String {
val buffer = CharArray(text.length + 1)
buffer[0] = COMMON_MARKER
text.toCharArray(buffer, 1)
return String(buffer)
}
internal fun createListRawText(elements: Array<out String>): String {
val size = elements.size
val lastIndex = size - 1
var capacity = 2 /* L and @ */ + size.decimalDigitCount()
elements.forEachIndexed { index, element ->
capacity += element.length
// Increase capacity for new line symbol only if it's not the last element
if (index < lastIndex) {
capacity++
}
}
return buildString(capacity) {
append(LIST_MARKER)
append(size)
append('@')
elements.forEachIndexed { index, element ->
append(element)
if (index < lastIndex) {
append(LIST_NEW_ELEMENT_SEPARATOR)
}
}
}
}
fun throwInvalidFormat(rawText: String): Nothing {
throw IllegalArgumentException("Invalid format (rawText=$rawText)")
}
/**
* Returns how much distinct meaning is stored in a raw meaning string.
* The method does a little bit of validating the meaning but it may return wrong value in case the meaning is
* encoded incorrectly.
*
* @throws IllegalArgumentException if rawText is in invalid format.
*/
fun getMeaningCount(rawText: String): Int {
if (rawText.isEmpty()) {
throwInvalidFormat(rawText)
}
return when (rawText[0]) {
COMMON_MARKER -> 1
LIST_MARKER -> {
// Skip mark character
val firstDelimiterIndex = rawText.indexOf('@', 1)
if (firstDelimiterIndex < 0) {
throwInvalidFormat(rawText)
}
// parsePositiveInt() returns -1 when format is invalid.
val count = rawText.parsePositiveInt(1, firstDelimiterIndex)
if (count < 0) {
throwInvalidFormat(rawText)
}
count
}
else -> throwInvalidFormat(rawText)
}
}
/**
* Parses raw meaning string to the object-like form that always contains only valid meaning.
*
* @throws IllegalArgumentException if the [rawText] is in invalid format.
*/
fun parse(rawText: String): ComplexMeaning {
if (rawText.isEmpty()) {
throwInvalidFormat(rawText)
}
return when (rawText[0]) {
COMMON_MARKER -> {
Common(rawText.substring(1), rawText)
}
LIST_MARKER -> {
// Skip mark character
val firstDelimiterIndex = rawText.indexOf('@', 1)
if (firstDelimiterIndex < 0) {
throwInvalidFormat(rawText)
}
// parsePositiveInt() returns -1 when format is invalid.
val count = rawText.parsePositiveInt(1, firstDelimiterIndex)
if (count < 0) {
throwInvalidFormat(rawText)
}
// Content starts after '@' symbol, so +1
val contentStart = firstDelimiterIndex + 1
var prevPos = contentStart
val elements = unsafeNewArray<String>(count)
for (i in 0 until count) {
val nextPos = indexOfListSeparatorOrLength(rawText, prevPos)
val element = rawText.substring(prevPos, nextPos)
elements[i] = element
prevPos = nextPos + 1
}
List(elements, rawText)
}
else -> throwInvalidFormat(rawText)
}
}
/**
* Iterates each list element range of given list meaning.
*
* @param rawText a raw list meaning string to iterate the ranges of
* @param block a lambda that processes each range. Start is inclusive, end is exclusive.
*/
inline fun iterateListElementRanges(
rawText: String,
block: (start: Int, end: Int) -> Unit
) {
// Skip mark character
val firstDelimiterIndex = rawText.indexOf('@', 1)
if (firstDelimiterIndex < 0) {
throwInvalidFormat(rawText)
}
val count = rawText.parsePositiveInt(1, firstDelimiterIndex)
when {
count < 0 -> throwInvalidFormat(rawText)
count == 0 -> return
}
var i = firstDelimiterIndex + 1
repeat(count) {
val nextDelimiterPos = indexOfListSeparatorOrLength(rawText, i)
block(i, nextDelimiterPos)
i = nextDelimiterPos + 1
}
}
/**
* Converts a list meaning encoded in old format (with \n as element separator) to the new list meaning format.
*/
fun recodeListOldFormatToNew(meaning: String): String {
return meaning.replace(LIST_OLD_ELEMENT_SEPARATOR, LIST_NEW_ELEMENT_SEPARATOR)
}
/**
* Converts a list meaning encoded in new format to the old meaning format.
*
* [meaning] should not contain any \n as a part of the list elements.
*/
fun recodeListNewFormatToOld(meaning: String): String {
return meaning.replace(LIST_NEW_ELEMENT_SEPARATOR, LIST_OLD_ELEMENT_SEPARATOR)
}
/**
* Finds an index of [ComplexMeaning.LIST_NEW_ELEMENT_SEPARATOR] in the given string starting from [startIndex].
* If the index is not found, returns length of the string.
*/
fun indexOfListSeparatorOrLength(str: String, startIndex: Int): Int {
var index = str.indexOf(LIST_NEW_ELEMENT_SEPARATOR, startIndex)
if (index < 0) {
index = str.length
}
return index
}
/**
* Determines whether raw meaning string is a correctly encoded meaning.
*/
fun isValid(rawText: String): Boolean {
val textLength = rawText.length
if (textLength < 2) {
return false
}
return when (rawText[0] /* mark char */) {
COMMON_MARKER -> true
LIST_MARKER -> {
// Skip mark character
val firstDelimiterIndex = rawText.indexOf('@', 1)
if (firstDelimiterIndex < 0) {
return false
}
val count = rawText.parsePositiveInt(1, firstDelimiterIndex)
if (count <= 0) {
return false
}
// There's at least one element without any separators
var actualElementCount = 1
for (i in firstDelimiterIndex until textLength) {
if (rawText[i] == LIST_NEW_ELEMENT_SEPARATOR) {
actualElementCount++
}
}
actualElementCount == count
}
else -> false
}
}
}
} | 6 | Kotlin | 0 | 3 | 76a8229099c3775bb36fff5cedb15b5bf54945df | 11,939 | DigiDictionary | MIT License |
Lyngua/app/src/main/java/com/app/lyngua/models/photos/PhotoDatabase.kt | ilangofman | 294,172,384 | false | null | package com.app.lyngua.models.photos
import android.content.Context
import androidx.room.*
/*
This is class to set up the database for the categories.
The database was set up through the tutorial found here:
https://www.youtube.com/watch?v=3USvr1Lz8g8
*/
@Database(
entities = [Photo::class],
version = 11,
exportSchema = false )
@TypeConverters(PhotoTypeConverter::class)
abstract class PhotoDatabase: RoomDatabase() {
abstract fun photoDao(): PhotoDao
companion object{
@Volatile
private var INSTANCE: PhotoDatabase? = null
/*
* Purpose: Get an instance of the database. If one already exists, return it, otherwise create it
* Input: context - The current app context
* Output: the PhotoDatabase object
*/
fun getDatabase(context: Context): PhotoDatabase {
val instanceCopy = INSTANCE
if(instanceCopy != null){
return instanceCopy
}
return createDatabase(context)
}
/*
* Purpose: If the database hasn't been created, create it
* Input: context - The current app context
* Output: the PhotoDatabase object
*/
private fun createDatabase(context: Context): PhotoDatabase {
synchronized(PhotoDatabase::class){
val instance=Room.databaseBuilder(
context.applicationContext,
PhotoDatabase::class.java,
"Photo_database")
.fallbackToDestructiveMigration()
.build()
INSTANCE = instance
return instance
}
}
}
} | 0 | Kotlin | 2 | 1 | 8e21f30b12ca2401d41d3d2779766b4f1d615823 | 1,719 | Language-Learning-App | MIT License |
src/commonMain/kotlin/io/github/jan/supabase/network/KtorSupabaseHttpClient.kt | supabase-community | 495,084,592 | false | null | package io.github.jan.supabase.network
import io.github.aakira.napier.Napier
import io.github.jan.supabase.exceptions.HttpRequestException
import io.github.jan.supabase.supabaseJson
import io.ktor.client.HttpClient
import io.ktor.client.HttpClientConfig
import io.ktor.client.engine.HttpClientEngine
import io.ktor.client.plugins.DefaultRequest
import io.ktor.client.plugins.HttpRequestTimeoutException
import io.ktor.client.plugins.HttpTimeout
import io.ktor.client.plugins.contentnegotiation.ContentNegotiation
import io.ktor.client.plugins.websocket.webSocketSession
import io.ktor.client.request.HttpRequestBuilder
import io.ktor.client.request.headers
import io.ktor.client.request.request
import io.ktor.client.statement.HttpResponse
import io.ktor.serialization.kotlinx.json.json
/**
* A [SupabaseHttpClient] that uses ktor to send requests
*/
class KtorSupabaseHttpClient(
private val supabaseKey: String,
modifiers: List<HttpClientConfig<*>.() -> Unit> = listOf(),
private val requestTimeout: Long,
engine: HttpClientEngine? = null,
): SupabaseHttpClient() {
private val httpClient =
if(engine != null) HttpClient(engine) { applyDefaultConfiguration(modifiers) }
else HttpClient { applyDefaultConfiguration(modifiers) }
override suspend fun request(url: String, builder: HttpRequestBuilder.() -> Unit): HttpResponse {
val request = HttpRequestBuilder().apply {
builder()
}
val response = try {
httpClient.request(url, builder)
} catch(e: HttpRequestTimeoutException) {
Napier.d { "Request timed out after $requestTimeout ms" }
throw e
} catch(e: Exception) {
Napier.d { "Request failed with ${e.message}" }
throw HttpRequestException(e.message ?: "", request)
}
return response
}
suspend fun webSocketSession(url: String, block: HttpRequestBuilder.() -> Unit = {}) = httpClient.webSocketSession(url, block)
fun close() = httpClient.close()
private fun HttpClientConfig<*>.applyDefaultConfiguration(modifiers: List<HttpClientConfig<*>.() -> Unit>) {
install(DefaultRequest) {
headers {
if(supabaseKey.isNotBlank()) {
append("apikey", supabaseKey)
}
}
port = 443
}
install(ContentNegotiation) {
json(supabaseJson)
}
install(HttpTimeout) {
requestTimeoutMillis = requestTimeout
}
modifiers.forEach { it.invoke(this) }
}
} | 2 | Kotlin | 8 | 80 | 1a4d3803201ad4e10a65862b3ef40be66d03e47f | 2,595 | supabase-kt | MIT License |
shared/presentation/recipes/src/androidMain/kotlin/com/iwanickimarcel/recipes/RecipesScreen.kt | MarcelIwanicki | 712,987,885 | false | {"Kotlin": 376361, "Swift": 342} | package com.iwanickimarcel.recipes
import androidx.compose.foundation.ExperimentalFoundationApi
import androidx.compose.foundation.clickable
import androidx.compose.foundation.combinedClickable
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.PaddingValues
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.lazy.staggeredgrid.LazyVerticalStaggeredGrid
import androidx.compose.foundation.lazy.staggeredgrid.StaggeredGridCells
import androidx.compose.foundation.lazy.staggeredgrid.itemsIndexed
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Add
import androidx.compose.material.icons.outlined.Favorite
import androidx.compose.material.icons.outlined.Search
import androidx.compose.material3.AlertDialog
import androidx.compose.material3.BottomSheetDefaults
import androidx.compose.material3.ElevatedFilterChip
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.ExtendedFloatingActionButton
import androidx.compose.material3.FilterChipDefaults
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.ModalBottomSheet
import androidx.compose.material3.OutlinedTextField
import androidx.compose.material3.Scaffold
import androidx.compose.material3.Text
import androidx.compose.material3.TextButton
import androidx.compose.material3.TopAppBar
import androidx.compose.material3.TopAppBarDefaults
import androidx.compose.material3.rememberModalBottomSheetState
import androidx.compose.material3.rememberTopAppBarState
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.collectAsState
import androidx.compose.runtime.getValue
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.input.nestedscroll.nestedScroll
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import cafe.adriel.voyager.navigator.LocalNavigator
import cafe.adriel.voyager.navigator.Navigator
import com.iwanickimarcel.core.NavigationBarFactory
fun interface AddRecipeNavigation {
operator fun invoke(navigator: Navigator, recipeId: Long?)
}
@OptIn(ExperimentalMaterial3Api::class, ExperimentalFoundationApi::class)
@Composable
fun RecipesScreen(
getViewModel: @Composable () -> RecipesViewModel,
navigationBarFactory: NavigationBarFactory,
navigateToRecipesSearch: (Navigator) -> Unit,
navigateToAddRecipe: AddRecipeNavigation,
searchQuery: String?
) {
val viewModel = getViewModel()
val navigator = LocalNavigator.current ?: return
val state by viewModel.state.collectAsState()
val bottomSheetState = rememberModalBottomSheetState(
skipPartiallyExpanded = true
)
val scrollBehavior = TopAppBarDefaults.enterAlwaysScrollBehavior(rememberTopAppBarState())
searchQuery?.let {
LaunchedEffect(Unit) {
viewModel.onEvent(RecipesEvent.OnSearchQuery(it))
}
}
if (state.searchBarPressed) {
navigateToRecipesSearch(navigator)
}
state.recipeToDelete?.let {
AlertDialog(
onDismissRequest = {
viewModel.onEvent(RecipesEvent.OnDeleteRecipeMenuDismiss)
},
title = {
Text(
text = buildString {
append("Delete ")
append(it.name)
append("?")
}
)
},
text = {
Text(text = "You will not be able to recover it")
},
confirmButton = {
TextButton(
onClick = {
viewModel.onEvent(RecipesEvent.OnDeleteRecipeConfirm)
}
) {
Text("Delete")
}
},
dismissButton = {
TextButton(
onClick = {
viewModel.onEvent(RecipesEvent.OnDeleteRecipeMenuDismiss)
}
) {
Text("Cancel")
}
}
)
}
state.recipeToEdit?.let {
LaunchedEffect(Unit) {
navigateToAddRecipe(
navigator = navigator,
recipeId = it.id
)
}
}
state.longPressedRecipe?.let {
ModalBottomSheet(
onDismissRequest = {
viewModel.onEvent(RecipesEvent.OnRecipeLongPressDismiss)
},
sheetState = bottomSheetState,
windowInsets = BottomSheetDefaults.windowInsets
) {
LongPressBottomSheetContent(
productsState = state,
onDeleteProductPressed = {
viewModel.onEvent(
RecipesEvent.OnDeleteRecipePress(
state.longPressedRecipe ?: return@LongPressBottomSheetContent
)
)
},
onEditProductPressed = {
viewModel.onEvent(
RecipesEvent.OnEditRecipePress(
state.longPressedRecipe ?: return@LongPressBottomSheetContent
)
)
}
)
}
}
Scaffold(
modifier = Modifier.nestedScroll(scrollBehavior.nestedScrollConnection),
topBar = {
TopAppBar(
modifier = Modifier.padding(16.dp),
title = {},
actions = {
OutlinedTextField(
value = state.searchQuery,
readOnly = true,
enabled = false,
placeholder = {
Text(text = "Search for recipes...")
},
onValueChange = { },
shape = RoundedCornerShape(20.dp),
modifier = Modifier
.fillMaxWidth()
.clickable {
viewModel.onEvent(RecipesEvent.OnSearchBarClick)
},
leadingIcon = {
Icon(
imageVector = Icons.Outlined.Search,
contentDescription = "Search for recipes"
)
}
)
},
scrollBehavior = scrollBehavior,
colors = TopAppBarDefaults.topAppBarColors(
scrolledContainerColor = MaterialTheme.colorScheme.background
)
)
},
content = {
LazyVerticalStaggeredGrid(
modifier = Modifier.padding(it),
columns = StaggeredGridCells.Fixed(2),
contentPadding = PaddingValues(16.dp),
horizontalArrangement = Arrangement.spacedBy(16.dp),
verticalItemSpacing = 16.dp
) {
itemsIndexed(state.recipes) { index, item ->
val offset = index % 5
val height = if (offset == 1 || offset == 3) {
256.dp
} else {
120.dp
}
Box(
modifier = Modifier
.fillMaxWidth()
.height(height)
.clip(RoundedCornerShape(10.dp))
.combinedClickable(
onClick = {
},
onLongClick = {
viewModel.onEvent(RecipesEvent.OnRecipeLongPress(item))
}
),
) {
RecipePhoto(
recipe = item,
modifier = Modifier.fillMaxSize()
)
Column(
modifier = Modifier
.fillMaxSize()
.padding(12.dp),
verticalArrangement = Arrangement.SpaceBetween
) {
Row(
modifier = Modifier
.fillMaxWidth(),
horizontalArrangement = Arrangement.SpaceBetween
) {
item.tags.firstOrNull()?.let {
ElevatedFilterChip(
selected = false,
onClick = { },
label = {
Text(it.name)
},
shape = RoundedCornerShape(16.dp),
colors = FilterChipDefaults.filterChipColors(
containerColor = MaterialTheme.colorScheme.tertiary,
labelColor = MaterialTheme.colorScheme.onTertiary
)
)
}
IconButton(
onClick = {
viewModel.onEvent(RecipesEvent.OnFavoriteClick(item))
},
content = {
Icon(
imageVector = Icons.Outlined.Favorite,
contentDescription = "Favorite",
tint = if (item.isFavorite) {
MaterialTheme.colorScheme.error
} else {
MaterialTheme.colorScheme.onBackground
}
)
},
)
}
Column {
Text(
text = item.name,
fontWeight = FontWeight.Bold
)
Text(
text = buildString {
append("You have ")
append(item.ownedProductsPercent)
append("% of ingredients")
},
fontSize = 10.sp
)
}
}
}
}
}
},
bottomBar = {
with(navigationBarFactory) {
NavigationBar()
}
},
floatingActionButton = {
ExtendedFloatingActionButton(
onClick = {
navigateToAddRecipe(
navigator = navigator,
recipeId = null
)
},
text = {
Text(text = "Add recipe")
},
icon = {
Icon(
imageVector = Icons.Filled.Add,
contentDescription = "Add recipe"
)
},
)
}
)
} | 0 | Kotlin | 0 | 1 | 0d9676a542ba3d9b8b2bdf366aefadf298e6da81 | 12,574 | freat | The Unlicense |
aTalk/src/main/java/org/atalk/util/event/VideoListener.kt | cmeng-git | 704,328,019 | false | {"Kotlin": 14462775, "Java": 2824517, "C": 275021, "Shell": 49203, "Makefile": 28273, "C++": 13642, "HTML": 7793, "CSS": 3127, "JavaScript": 2758, "AIDL": 375} | /*
* Copyright @ 2015 Atlassian Pty Ltd
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.atalk.util.event
import java.util.*
/**
* Defines the notification support informing about changes in the availability
* of visual `Component`s representing video such as adding and removing.
*
* @author <NAME>
* @author <NAME>
*/
interface VideoListener : EventListener {
/**
* Notifies that a visual `Component` representing video has been
* added to the provider this listener has been added to.
*
* @param event a `VideoEvent` describing the added visual
* `Component` representing video and the provider it was added into
*/
fun videoAdded(event: VideoEvent)
/**
* Notifies that a visual `Component` representing video has been
* removed from the provider this listener has been added to.
*
* @param event a `VideoEvent` describing the removed visual
* `Component` representing video and the provider it was removed
* from
*/
fun videoRemoved(event: VideoEvent)
/**
* Notifies about an update to a visual `Component` representing video.
*
* @param event a `VideoEvent` describing the visual
* `Component` related to the update and the details of the specific
* update
*/
fun videoUpdate(event: VideoEvent)
} | 0 | Kotlin | 0 | 0 | 393d94a8b14913b718800238838801ce6cdf5a1f | 1,856 | atalk-hmos_kotlin | Apache License 2.0 |
application/src/main/java/de/pbauerochse/worklogviewer/view/ReportColumn.kt | pbauerochse | 34,003,778 | false | null | package de.pbauerochse.worklogviewer.view
class ReportColumn {
} | 8 | null | 10 | 38 | 5615a820fa88a78f8769d2522a6b55099abe1a01 | 65 | youtrack-worklog-viewer | MIT License |
app/src/main/java/com/skt/nugu/sampleapp/utils/Directive.kt | umrhiumrhi | 515,390,621 | false | {"Kotlin": 2646293, "Java": 1646, "Ruby": 1432} | package com.skt.nugu.sampleapp.utils
import com.google.gson.annotations.SerializedName
data class Directive(
@SerializedName("data")
val data: Data,
@SerializedName("type")
val type: String,
@SerializedName("version")
val version: String
) | 0 | Kotlin | 0 | 0 | 6c4bc151d2cfe4d18e409c04e66c190f49d4e284 | 266 | skt-summer-internship-2022 | Apache License 2.0 |
app/templates/app-kotlin/src/main/java/ui/base/BaseAdapter.kt | javagrails | 139,724,208 | true | {"JavaScript": 111668, "Kotlin": 93618, "Java": 14691} | package <%= appPackage %>.ui.base
import android.support.annotation.LayoutRes
import android.support.transition.TransitionManager
import android.support.v7.widget.RecyclerView
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.AdapterView
import android.widget.Filter
import android.widget.Filterable
import java.util.*
abstract class BaseAdapter<T> : RecyclerView.Adapter<BaseAdapter.ViewHolder<T>>(), Filterable {
private var items: MutableList<T>
protected var originalItems: List<T>
private var mOnItemClickListener: AdapterView.OnItemClickListener? = null
private var baseFilter: BaseFilter<T>? = null
protected var parent : ViewGroup? = null
init {
items = ArrayList<T>()
originalItems = ArrayList<T>()
}
protected fun setItems(items: MutableList<T>) {
this.items = items
}
@LayoutRes
protected abstract fun getLayoutForType(viewType: Int): Int
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder<T> {
val inflatedView = LayoutInflater.from(parent.context).inflate(getLayoutForType(viewType), parent, false)
this.parent = parent
return onCreateViewHolder(inflatedView, viewType)
}
protected abstract fun onCreateViewHolder(inflatedView: View, viewType: Int = 0): ViewHolder<T>
override fun onBindViewHolder(holder: ViewHolder<T>, position: Int) {
holder.bindItem(items[position], position)
}
fun getItem(position: Int): T? {
return this.items[position]
}
override fun getFilter(): Filter {
if (baseFilter == null){
originalItems = ArrayList<T>(items)
baseFilter = BaseFilter(this, originalItems)
}
return baseFilter as BaseFilter
}
protected fun getBaseFilter(): BaseFilter<T> {
if (baseFilter == null){
originalItems = ArrayList<T>(items)
baseFilter = BaseFilter(this, originalItems)
}
return baseFilter as BaseFilter
}
/**
* @param item
* *
* @param position
*/
fun add(item: T?, position: Int) {
if (item == null || position >= items.size || position == -1) {
return
}
items.add(position, item)
notifyItemInserted(position)
notifyDataSetChanged()
}
/**
* @param item
*/
fun add(item: T?) {
if (item == null) {
return
}
items.add(item)
notifyItemInserted(items.size - 1)
}
/**
* @param item
*/
fun remove(item: T?) {
if (item == null) {
return
}
val position = items.indexOf(item)
items.remove(item)
notifyItemRemoved(position)
notifyDataSetChanged()
}
/**
* @param items
*/
fun addAll(items: List<T>?) {
if (items == null) {
return
}
val length = items.size
val start = itemCount
this.items.addAll(items)
notifyItemRangeInserted(start, length)
}
/**
* @param items
*/
fun replace(items: List<T>?) {
if (items == null) {
this.items = ArrayList<T>()
} else {
this.items = ArrayList(items)
}
notifyDataSetChanged()
}
fun clear() {
this.items = ArrayList<T>()
notifyDataSetChanged()
}
override fun getItemCount(): Int {
return items.size
}
fun setOnItemClickListener(onItemClickListener: AdapterView.OnItemClickListener) {
mOnItemClickListener = onItemClickListener
}
private fun onItemHolderClick(itemHolder: ViewHolder<T>) {
if (mOnItemClickListener != null) {
mOnItemClickListener?.onItemClick(null, itemHolder.itemView,
itemHolder.adapterPosition, itemHolder.itemId)
}
}
abstract class ViewHolder<T>(root: View?, val adapter: BaseAdapter<T>) : RecyclerView.ViewHolder(root), View.OnClickListener {
init {
root?.setOnClickListener(this)
}
abstract fun bindItem(value: T, position: Int)
override fun onClick(v: View) {
adapter.onItemHolderClick(this)
}
}
inner class BaseFilter<T>(val baseAdapter : BaseAdapter<T>, val originalList : List<T>) : Filter() {
var filteredList : MutableList<T> = mutableListOf()
var filterExpression: ((predicate: T, filterPattern: String) -> Boolean )? = null
override fun performFiltering(constraint: CharSequence?): FilterResults {
filteredList.clear()
val results = FilterResults()
if(filterExpression == null) filterExpression = { predicate, filterPattern -> predicate.toString().contains(filterPattern) }
if (constraint?.length == 0) {
filteredList.addAll(originalList)
} else {
val filterPattern: String = constraint.toString().toLowerCase().trim()
filteredList.addAll(
originalList.filter { filterExpression?.invoke(it, filterPattern) ?: false }
)
}
results.values = filteredList
results.count = filteredList.size
return results
}
@Suppress("UNCHECKED_CAST")
override fun publishResults(constraint: CharSequence?, results: FilterResults?) {
baseAdapter.clear()
baseAdapter.addAll(results?.values as ArrayList<T>)
}
}
interface OnItemClick<T> {
fun itemClick(item: T, position: Int)
}
}
| 0 | JavaScript | 0 | 0 | cb10ae572b7106ae851ef9271a3eea465ee794df | 5,679 | generator-android-hipster | Apache License 2.0 |
platform/platform-tests/testSrc/com/intellij/execution/wsl/WSLDistributionTest.kt | JetBrains | 2,489,216 | false | null | // Copyright 2000-2023 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
@file:Suppress("ClassName")
package com.intellij.execution.wsl
import com.intellij.execution.configurations.GeneralCommandLine
import com.intellij.openapi.Disposable
import com.intellij.testFramework.junit5.TestApplication
import com.intellij.testFramework.junit5.TestDisposable
import io.kotest.assertions.assertSoftly
import io.kotest.assertions.withClue
import io.kotest.matchers.be
import io.kotest.matchers.collections.beEmpty
import io.kotest.matchers.collections.haveSize
import io.kotest.matchers.nulls.beNull
import io.kotest.matchers.should
import org.junit.jupiter.api.BeforeEach
import org.junit.jupiter.api.Nested
import org.junit.jupiter.api.Test
import java.nio.file.FileSystems
@TestApplication
class WSLDistributionTest {
val distro = object : WSLDistribution("mock-wsl-id") {
init {
testOverriddenShellPath = "/bin/bash"
}
}
val wslExe: String = FileSystems.getDefault().rootDirectories.first().resolve("mock-path").resolve("wsl.exe").toString()
val toolsRoot = "/mnt/c/mock-path"
@BeforeEach
fun patchWslExePath(
@TestDisposable disposable: Disposable,
) {
WSLDistribution.testOverriddenWslExe(FileSystems.getDefault().getPath(wslExe), disposable)
testOverrideWslToolRoot(toolsRoot, disposable)
}
@Nested
inner class patchCommandLine {
@Test
fun `simple case`() {
val cmd = distro.patchCommandLine(GeneralCommandLine("true"), null, WSLCommandLineOptions())
assertSoftly(cmd) {
exePath should be(wslExe)
parametersList.list should be(listOf(
"--distribution", "mock-wsl-id", "--exec", "$toolsRoot/ttyfix", "/bin/bash", "-l", "-c", "true",
))
environment.entries should beEmpty()
}
}
@Test
fun `arguments and environment`() {
val cmd = distro.patchCommandLine(
GeneralCommandLine("printf", "foo", "bar", "'o\"ops 1'")
.withEnvironment("FOOBAR", "'o\"ops 2'"),
null,
WSLCommandLineOptions(),
)
assertSoftly(cmd) {
exePath should be(wslExe)
parametersList.list should be(listOf(
"--distribution", "mock-wsl-id", "--exec", "$toolsRoot/ttyfix", "/bin/bash", "-l", "-c",
"""export FOOBAR=''"'"'o"ops 2'"'"'' && printf foo bar ''"'"'o"ops 1'"'"''"""
))
environment.entries should beEmpty()
}
}
@Nested
inner class `different WSLCommandLineOptions` {
@Test
fun `setExecuteCommandInShell false`() {
val options = WSLCommandLineOptions()
.apply {
withClue("Checking the default value") {
isExecuteCommandInShell should be(true)
}
}
.setExecuteCommandInShell(false)
val cmd = distro.patchCommandLine(GeneralCommandLine("date"), null, options)
assertSoftly(cmd) {
exePath should be(wslExe)
parametersList.list should be(listOf(
"--distribution", "mock-wsl-id", "--exec", "date",
))
environment.entries should beEmpty()
}
}
@Test
fun `setExecuteCommandInShell false and environment variables`() {
val commandLine = GeneralCommandLine("printenv")
.withEnvironment("FOO", "BAR")
.withEnvironment("HURR", "DURR")
val options = WSLCommandLineOptions()
.setExecuteCommandInShell(false)
val cmd = distro.patchCommandLine(commandLine, null, options)
assertSoftly(cmd) {
exePath should be(wslExe)
parametersList.list should be(listOf(
"--distribution", "mock-wsl-id", "--exec", "printenv",
))
environment should be(mapOf(
"FOO" to "BAR",
"HURR" to "DURR",
"WSLENV" to "FOO/u:HURR/u",
))
}
}
@Test
fun `setExecuteCommandInInteractiveShell true`() {
val options = WSLCommandLineOptions()
.apply {
withClue("Checking the default value") {
isExecuteCommandInInteractiveShell should be(false)
}
}
.setExecuteCommandInInteractiveShell(true)
val cmd = distro.patchCommandLine(GeneralCommandLine("date"), null, options)
assertSoftly(cmd) {
exePath should be(wslExe)
parametersList.list should be(listOf(
"--distribution", "mock-wsl-id", "--exec", "$toolsRoot/ttyfix", "/bin/bash", "-i", "-l", "-c", "date",
))
environment.entries should beEmpty()
}
}
@Test
fun `setExecuteCommandInLoginShell false`() {
val options = WSLCommandLineOptions()
.apply {
withClue("Checking the default value") {
isExecuteCommandInLoginShell should be(true)
}
}
.setExecuteCommandInLoginShell(false)
val cmd = distro.patchCommandLine(GeneralCommandLine("date"), null, options)
assertSoftly(cmd) {
exePath should be(wslExe)
parametersList.list should be(listOf(
"--distribution", "mock-wsl-id", "--exec", "$toolsRoot/ttyfix", "/bin/bash", "-c", "date",
))
environment.entries should beEmpty()
}
}
@Test
fun `setExecuteCommandInDefaultShell true`() {
val options = WSLCommandLineOptions()
.apply {
withClue("Checking the default value") {
isExecuteCommandInDefaultShell should be(false)
}
}
.setExecuteCommandInDefaultShell(true)
val cmd = distro.patchCommandLine(GeneralCommandLine("date"), null, options)
assertSoftly(cmd) {
exePath should be(wslExe)
parametersList.list should be(listOf(
"--distribution", "mock-wsl-id", "$toolsRoot/ttyfix", "\$SHELL", "-c", "date",
))
environment.entries should beEmpty()
}
}
@Test
fun `setSudo true`() {
val options = WSLCommandLineOptions()
.apply {
withClue("Checking the default value") {
isSudo should be(false)
}
}
.setSudo(true)
val cmd = distro.patchCommandLine(GeneralCommandLine("date"), null, options)
assertSoftly(cmd) {
exePath should be(wslExe)
parametersList.list should be(listOf(
"--distribution", "mock-wsl-id", "-u", "root", "--exec", "$toolsRoot/ttyfix", "/bin/bash", "-l", "-c", "date",
))
environment.entries should beEmpty()
}
}
@Test
fun setRemoteWorkingDirectory() {
val options = WSLCommandLineOptions()
.apply {
withClue("Checking the default value") {
remoteWorkingDirectory should beNull()
}
}
.setRemoteWorkingDirectory("/foo/bar/baz")
val cmd = distro.patchCommandLine(GeneralCommandLine("date"), null, options)
assertSoftly(cmd) {
exePath should be(wslExe)
parametersList.list should be(listOf(
"--distribution", "mock-wsl-id", "--exec", "$toolsRoot/ttyfix", "/bin/bash", "-l", "-c", "cd /foo/bar/baz && date",
))
environment.entries should beEmpty()
}
}
@Test
fun `setPassEnvVarsUsingInterop true`() {
val commandLine = GeneralCommandLine("date")
.withEnvironment("FOO", "BAR")
.withEnvironment("HURR", "DURR")
val options = WSLCommandLineOptions()
.apply {
withClue("Checking the default value") {
isPassEnvVarsUsingInterop should be(false)
}
}
.setPassEnvVarsUsingInterop(true)
val cmd = distro.patchCommandLine(commandLine, null, options)
assertSoftly(cmd) {
exePath should be(wslExe)
parametersList.list should be(listOf(
"--distribution", "mock-wsl-id", "--exec", "$toolsRoot/ttyfix", "/bin/bash", "-l", "-c", "date",
))
environment should be(mapOf(
"FOO" to "BAR",
"HURR" to "DURR",
"WSLENV" to "FOO/u:HURR/u",
))
}
}
@Test
fun addInitCommand() {
val options = WSLCommandLineOptions()
.apply {
withClue("Checking the default value") {
initShellCommands should haveSize(0)
}
}
.addInitCommand("whoami")
.addInitCommand("printf 'foo bar' && echo 'hurr durr'") // Allows various shell injections.
val cmd = distro.patchCommandLine(GeneralCommandLine("date"), null, options)
assertSoftly(cmd) {
exePath should be(wslExe)
parametersList.list should be(listOf(
"--distribution", "mock-wsl-id", "--exec", "$toolsRoot/ttyfix", "/bin/bash", "-l", "-c",
"printf 'foo bar' && echo 'hurr durr' && whoami && date",
))
environment.entries should beEmpty()
}
}
}
}
} | 250 | null | 5074 | 16,130 | e7a787ae2af47a6694da9e0e3b1d8fcd0f397775 | 9,137 | intellij-community | Apache License 2.0 |
app/src/main/java/org/stepik/android/view/injection/feedback/FeedbackModule.kt | StepicOrg | 42,045,161 | false | null | package org.stepik.android.view.injection.feedback
import android.arch.lifecycle.ViewModel
import dagger.Binds
import dagger.Module
import dagger.multibindings.IntoMap
import org.stepik.android.presentation.base.injection.ViewModelKey
import org.stepik.android.presentation.feedback.FeedbackPresenter
@Module
abstract class FeedbackModule {
/**
* Presentation
*/
@Binds
@IntoMap
@ViewModelKey(FeedbackPresenter::class)
internal abstract fun bindFeedbackPresenter(feedbackPresenter: FeedbackPresenter): ViewModel
} | 13 | null | 54 | 189 | dd12cb96811a6fc2a7addcd969381570e335aca7 | 545 | stepik-android | Apache License 2.0 |
domains/domain_home/src/main/java/com/bael/dads/domain/home/mapper/DadJokeDBMapper.kt | virendersran01 | 356,644,618 | true | {"Kotlin": 200059} | package com.bael.dads.domain.home.mapper
import com.bael.dads.domain.common.mapper.Mapper
import com.bael.dads.domain.home.model.DadJoke
import javax.inject.Inject
import com.bael.dads.lib.database.entity.DadJoke as DadJokeDB
/**
* Created by ErickSumargo on 01/01/21.
*/
internal class DadJokeDBMapper @Inject constructor() : Mapper<DadJokeDB, DadJoke> {
override fun map(data: DadJokeDB): DadJoke {
return DadJoke(
id = data.id,
setup = data.setup,
punchline = data.punchline,
favored = data.favored,
seen = data.seen,
updatedAt = data.updatedAt
)
}
}
| 0 | null | 0 | 1 | 0dab6bcc5d7a6f726140e80fc21f503ab8b07c07 | 656 | Dads | MIT License |
app/shared/keybox/fake/src/commonMain/kotlin/build/wallet/keybox/KeyboxDaoMock.kt | proto-at-block | 761,306,853 | false | {"C": 10551861, "Kotlin": 6455657, "Rust": 1874547, "Swift": 629125, "Python": 329146, "HCL": 257498, "Shell": 97542, "TypeScript": 81148, "C++": 64770, "Meson": 64252, "JavaScript": 36229, "Just": 26345, "Ruby": 9265, "Dockerfile": 5755, "Makefile": 3839, "Open Policy Agent": 1456, "Procfile": 80} | package build.wallet.keybox
import app.cash.turbine.Turbine
import app.cash.turbine.plusAssign
import build.wallet.LoadableValue
import build.wallet.bitkey.app.AppAuthPublicKeys
import build.wallet.bitkey.keybox.Keybox
import build.wallet.bitkey.keybox.KeyboxMock
import build.wallet.bitkey.spending.SpendingKeyset
import build.wallet.db.DbError
import build.wallet.unwrapLoadedValue
import com.github.michaelbull.result.Err
import com.github.michaelbull.result.Ok
import com.github.michaelbull.result.Result
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.first
class KeyboxDaoMock(
turbine: (name: String) -> Turbine<Unit>,
private val defaultActiveKeybox: Keybox? = null,
private val defaultOnboardingKeybox: Keybox? = null,
) : KeyboxDao {
val clearCalls = turbine("clear calls KeyboxDaoMock")
val rotateAuthKeysCalls = turbine("rotate auth keys calls")
val activeKeybox = MutableStateFlow<Result<Keybox?, DbError>>(Ok(defaultActiveKeybox))
val onboardingKeybox =
MutableStateFlow<Result<LoadableValue<Keybox?>, DbError>>(
Ok(LoadableValue.LoadedValue(defaultOnboardingKeybox))
)
var keyset: SpendingKeyset? = null
override fun activeKeybox(): Flow<Result<Keybox?, DbError>> = activeKeybox
override fun onboardingKeybox(): Flow<Result<LoadableValue<Keybox?>, DbError>> = onboardingKeybox
override suspend fun getActiveOrOnboardingKeybox(): Result<Keybox?, DbError> {
return when (val activeKeyboxResult = activeKeybox().first()) {
is Err -> activeKeyboxResult
is Ok ->
when (activeKeyboxResult.value) {
null -> onboardingKeybox().unwrapLoadedValue().first()
else -> activeKeyboxResult
}
}
}
override suspend fun activateNewKeyboxAndCompleteOnboarding(
keybox: Keybox,
): Result<Unit, DbError> {
this.activeKeybox.value = Ok(keybox)
this.onboardingKeybox.value = Ok(LoadableValue.LoadedValue(null))
return Ok(Unit)
}
override suspend fun rotateKeyboxAuthKeys(
keyboxToRotate: Keybox,
appAuthKeys: AppAuthPublicKeys,
): Result<Keybox, DbError> {
rotateAuthKeysCalls += Unit
return Ok(KeyboxMock)
}
override suspend fun saveKeyboxAndBeginOnboarding(keybox: Keybox): Result<Unit, DbError> {
this.onboardingKeybox.value = Ok(LoadableValue.LoadedValue(keybox))
return Ok(Unit)
}
override suspend fun saveKeyboxAsActive(keybox: Keybox): Result<Unit, DbError> {
this.activeKeybox.value = Ok(keybox)
return Ok(Unit)
}
override suspend fun clear(): Result<Unit, DbError> {
clearCalls += Unit
activeKeybox.value = Ok(null)
return Ok(Unit)
}
fun reset() {
onboardingKeybox.value = Ok(LoadableValue.LoadedValue(defaultOnboardingKeybox))
activeKeybox.value = Ok(defaultActiveKeybox)
keyset = null
}
}
| 0 | C | 6 | 74 | b7401e0b96f9378cbd96eb01914a4f888e0a9303 | 2,865 | bitkey | MIT License |
app/src/main/java/heb/apps/mathtrainer/memory/db/tasks/levels/GetLevelsTask.kt | MatanelAbayof | 375,713,729 | false | null | package heb.apps.mathtrainer.memory.db.tasks.levels
import android.content.Context
import heb.apps.mathtrainer.data.quiz.level.Level
import heb.apps.mathtrainer.memory.db.MathDB
import heb.apps.mathtrainer.memory.db.tasks.MathDBTask
class GetLevelsTask(ctx: Context) : MathDBTask<Void, List<Level>>(ctx) {
override fun doInBack(db: MathDB, input: Void?): List<Level>? = db.levelDao().getLevels()
} | 0 | Kotlin | 0 | 0 | c614b5f09be150b4a8712d965ad79bd3c91cdbdc | 405 | Math-Trainer | Apache License 2.0 |
idea/idea-completion/src/org/jetbrains/kotlin/idea/completion/DeclarationLookupObjectImpl.kt | staltz | 39,123,650 | false | {"Markdown": 34, "XML": 688, "Ant Build System": 40, "Ignore List": 8, "Git Attributes": 1, "Kotlin": 18742, "Java": 4339, "Protocol Buffer": 4, "Text": 4184, "JavaScript": 63, "JAR Manifest": 3, "Roff": 30, "Roff Manpage": 10, "INI": 7, "HTML": 135, "Groovy": 20, "Maven POM": 50, "Gradle": 72, "Java Properties": 10, "CSS": 3, "Proguard": 1, "JFlex": 2, "Shell": 9, "Batchfile": 8, "ANTLR": 1} | /*
* Copyright 2010-2015 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jetbrains.kotlin.idea.completion
import com.intellij.openapi.diagnostic.Logger
import com.intellij.openapi.util.Iconable
import com.intellij.psi.PsiDocCommentOwner
import com.intellij.psi.PsiElement
import org.jetbrains.kotlin.builtins.KotlinBuiltIns
import org.jetbrains.kotlin.descriptors.DeclarationDescriptor
import org.jetbrains.kotlin.idea.caches.resolve.ResolutionFacade
import org.jetbrains.kotlin.idea.core.completion.DeclarationLookupObject
import org.jetbrains.kotlin.util.descriptorsEqualWithSubstitution
import javax.swing.Icon
/**
* Stores information about resolved descriptor and position of that descriptor.
* Position will be used for sorting
*/
public abstract class DeclarationLookupObjectImpl(
public final override val descriptor: DeclarationDescriptor?,
public final override val psiElement: PsiElement?,
private val resolutionFacade: ResolutionFacade
): DeclarationLookupObject {
init {
assert(descriptor != null || psiElement != null)
}
override fun toString() = super<DeclarationLookupObject>.toString() + " " + (descriptor ?: psiElement)
override fun hashCode(): Int {
return if (descriptor != null) descriptor.getOriginal().hashCode() else psiElement!!.hashCode()
}
override fun equals(other: Any?): Boolean {
if (this identityEquals other) return true
if (other == null || javaClass != other.javaClass) return false
val lookupObject = other as DeclarationLookupObjectImpl
if (resolutionFacade != lookupObject.resolutionFacade) {
LOG.warn("Descriptors from different resolve sessions")
return false
}
return descriptorsEqualWithSubstitution(descriptor, lookupObject.descriptor) && psiElement == lookupObject.psiElement
}
override val isDeprecated = if (descriptor != null) KotlinBuiltIns.isDeprecated(descriptor) else (psiElement as? PsiDocCommentOwner)?.isDeprecated() ?: false
companion object {
private val LOG = Logger.getInstance("#" + javaClass<DeclarationLookupObject>().getName())
}
}
| 1 | null | 1 | 1 | e82adc9d90e5e0b65bf9cb2fd854b542ad1ff58e | 2,708 | kotlin | Apache License 2.0 |
tracer-core/src/main/kotlin/malibu/tracer/ThrowableExt.kt | adrenalinee | 640,443,973 | false | null | package malibu.tracer
import java.io.PrintWriter
import java.io.StringWriter
fun Throwable.traceToString(): String {
val sw = StringWriter()
this.printStackTrace(PrintWriter(sw))
return sw.toString()
} | 0 | Kotlin | 0 | 0 | 2e8b3a7f2cfcea2d7641fb0df3b8a769be646a8a | 216 | tracer | Apache License 2.0 |
app/src/main/java/com/teobaranga/monica/data/user/UserDao.kt | teobaranga | 686,113,276 | false | {"Kotlin": 269714} | package com.teobaranga.monica.data.user
import androidx.room.Dao
import androidx.room.Query
import androidx.room.Transaction
import androidx.room.Upsert
import kotlinx.coroutines.flow.Flow
@Dao
interface UserDao {
@Transaction
@Query("select * from me")
fun getMe(): Flow<MeFullDetails?>
@Upsert
suspend fun upsertMe(entity: MeEntity)
}
| 1 | Kotlin | 1 | 8 | 370462ffeaa6982e2475a416ef0ec6c2d435da14 | 361 | monica | Apache License 2.0 |
app/src/main/java/com/speakerboxlite/rxentity/ArrayKeyObservableCollectionExtra.kt | AlexExiv | 240,526,542 | false | null | package com.speakerboxlite.rxentity
import io.reactivex.rxjava3.core.Scheduler
import io.reactivex.rxjava3.core.Single
import io.reactivex.rxjava3.subjects.PublishSubject
import java.lang.ref.WeakReference
data class KeyParams<K, Extra, CollectionExtra>(val refreshing: Boolean = false,
val resetCache: Boolean = false,
val first: Boolean = false,
val keys: List<K>,
val extra: Extra? = null,
val collectionExtra: CollectionExtra? = null)
typealias ArrayFetchCallback<K, E, Extra, CollectionExtra> = (KeyParams<K, Extra, CollectionExtra>) -> Single<List<E>>
class ArrayKeyObservableCollectionExtra<K: Comparable<K>, E: Entity<K>, Extra, CollectionExtra>(
holder: EntityCollection<K, E>,
keys: List<K>,
start: Boolean = true,
extra: Extra? = null,
protected var collectionExtra: CollectionExtra? = null,
queue: Scheduler,
fetch: ArrayFetchCallback<K, E, Extra, CollectionExtra>): ArrayKeyObservableExtra<K, E, Extra>(holder, keys, extra, queue)
{
val rxKeys = PublishSubject.create<KeyParams<K, Extra, CollectionExtra>>()
override var _keys: MutableList<K>
get() = super._keys
set(value)
{
lock.lock()
super._keys = value
try
{
rxKeys.onNext(KeyParams(keys = value, extra = extra, collectionExtra = collectionExtra))
}
finally
{
lock.unlock()
}
}
init
{
val weak = WeakReference(this)
val disp = rxKeys
.filter { it.keys.size > 0 }
.doOnNext { weak.get()?.rxLoader?.onNext(if (it.first) Loading.FirstLoading else Loading.Loading) }
.observeOn(queue)
.switchMap {
(weak.get()?.RxFetchElements(params = it, fetch = fetch) ?: Single.just(listOf()))
.toObservable()
.onErrorReturn {
weak.get()?.rxError?.onNext(it)
weak.get()?.rxLoader?.onNext(Loading.None)
listOf()
}
}
.observeOn(queue)
.doOnNext { weak.get()?.rxLoader?.onNext(Loading.None) }
.flatMap { weak.get()?.collection?.get()?.RxRequestForCombine(source = weak.get()?.uuid ?: "", entities = it)?.toObservable() ?: just(listOf()) }
.subscribe { v -> weak.get()?.setEntities(entities = v) }
val keysDisp = rxKeys
.filter { it.keys.isEmpty() }
.observeOn(queue)
.doOnNext { weak.get()?.rxLoader?.onNext(Loading.None) }
.subscribe { weak.get()?.setEntities(entities = listOf()) }
dispBag.add(disp)
dispBag.add(keysDisp)
if (start)
rxKeys.onNext(KeyParams(first = true, keys = keys, extra = extra, collectionExtra = collectionExtra))
}
constructor(holder: EntityCollection<K, E>, initial: List<E>, collectionExtra: CollectionExtra? = null, queue: Scheduler, fetch: ArrayFetchCallback<K, E, Extra, CollectionExtra>) :
this(holder = holder, keys = initial.map { it._key }.toList(), start = false, collectionExtra = collectionExtra, queue = queue, fetch = fetch)
{
val weak = WeakReference(this)
val disp = Single
.just(true)
.observeOn(queue)
.flatMap { weak.get()?.collection?.get()?.RxRequestForCombine(source = weak.get()?.uuid ?: "", entities = initial) ?: Single.just(listOf()) }
.subscribe { v -> weak.get()?.setEntities(entities = v) }
dispBag.add(disp)
}
override fun refresh(resetCache: Boolean, extra: Extra?)
{
collectionRefresh(resetCache = resetCache, extra = extra)
}
override fun _refresh(resetCache: Boolean, extra: Extra?)
{
_collectionRefresh(resetCache = resetCache, extra = extra)
}
override fun refreshData(resetCache: Boolean, data: Any?)
{
_collectionRefresh(resetCache = resetCache, collectionExtra = data as? CollectionExtra)
}
fun collectionRefresh(resetCache: Boolean = false, extra: Extra? = null, collectionExtra: CollectionExtra? = null) {
val disp = Single.create<Boolean> {
this._collectionRefresh(resetCache = resetCache, extra = extra, collectionExtra = collectionExtra)
it.onSuccess(true)
}
.observeOn(queue)
.subscribeOn(queue)
.subscribe()
dispBag.add(disp)
}
fun _collectionRefresh(resetCache: Boolean = false, extra: Extra? = null, collectionExtra: CollectionExtra? = null)
{
super._refresh(resetCache = resetCache, extra = extra)
this.collectionExtra = collectionExtra ?: this.collectionExtra
rxKeys.onNext(KeyParams(refreshing = true, resetCache = resetCache, keys = keys, extra = this.extra, collectionExtra = this.collectionExtra))
}
private fun RxFetchElements(params: KeyParams<K, Extra, CollectionExtra>, fetch: ArrayFetchCallback<K, E, Extra, CollectionExtra>) : Single<List<E>>
{
if (params.refreshing)
return fetch(params)
val exist = params.keys.mapNotNull { k -> collection.get()?.sharedEntities?.get(k) ?: entities.firstOrNull { k == it._key } }
if (exist.size != keys.size)
{
val _params = KeyParams(refreshing = params.refreshing, resetCache = params.resetCache, first = params.first, keys = params.keys.filter { collection.get()?.sharedEntities?.get(it) == null }, extra = extra, collectionExtra = collectionExtra)
return zip(just(exist), fetch(_params).toObservable(), { e, n ->
val _exist = e.toEntitiesMap()
val new = n.toEntitiesMap()
params.keys.mapNotNull { _exist[it] ?: new[it] }
})
.first(listOf())
}
return Single.just(exist)
}
} | 0 | Kotlin | 0 | 0 | d100c2a1bd34c0e791df6e812f30a611b6779725 | 6,163 | RxEntity-Kotlin | MIT License |
core/src/main/java/com/lloydsbyte/core/custombottomsheet/ErrorBottomsheet.kt | Jeremyscell82 | 742,598,615 | false | {"Kotlin": 248610} | package com.lloydsbyte.core.custombottomsheet
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.FrameLayout
import com.google.android.material.bottomsheet.BottomSheetBehavior
import com.google.android.material.bottomsheet.BottomSheetDialog
import com.google.android.material.bottomsheet.BottomSheetDialogFragment
import com.lloydsbyte.core.databinding.BottomsheetErrorBinding
/**
* To be used during testing to allow the user to see the error and report it if they notice it in other areas too.
* The error will be reported prior to launching this dialog as it does not have access to the main app and it's analytics classes
*/
class ErrorBottomsheet : BottomSheetDialogFragment() {
companion object {
fun createInstance(errorTitle: String, errorMessage: String?): ErrorBottomsheet {
val fragment = ErrorBottomsheet()
fragment.title = errorTitle
fragment.message = errorMessage?:"NA"
return fragment
}
}
var title: String = ""
var message: String = ""
lateinit var binding: BottomsheetErrorBinding
override fun onStart() {
super.onStart()
val sheetContainer = requireView().parent as? ViewGroup ?: return
sheetContainer.layoutParams.height = ViewGroup.LayoutParams.WRAP_CONTENT
}
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View {
binding = BottomsheetErrorBinding.inflate(inflater, container, false)
dialog?.setOnShowListener { dialog ->
val layout: FrameLayout? = (dialog as BottomSheetDialog).findViewById(com.google.android.material.R.id.design_bottom_sheet)
layout?.let {
val behavior = BottomSheetBehavior.from(it)
behavior.state = BottomSheetBehavior.STATE_EXPANDED
behavior.skipCollapsed = true
}
}
return binding.root
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
binding.apply {
errorCloseBttn.setOnClickListener {
dialog?.dismiss()
}
errorTitle.text = title
errorMessage.text = message
}
}
} | 0 | Kotlin | 0 | 0 | a0721aa0a0f3b21e8a7e1192c1ae7c8e20fbec02 | 2,398 | CareerAdvr_AI | Apache License 2.0 |
modules/core/src/main/java/de/deutschebahn/bahnhoflive/ui/station/shop/RimapShop.kt | dbbahnhoflive | 267,806,942 | false | null | /*
* SPDX-FileCopyrightText: 2020 DB Station&Service AG <<EMAIL>>
*
* SPDX-License-Identifier: Apache-2.0
*/
package de.deutschebahn.bahnhoflive.ui.station.shop
import android.content.Context
import android.text.TextUtils
import de.deutschebahn.bahnhoflive.backend.rimap.model.LevelMapping
import de.deutschebahn.bahnhoflive.backend.rimap.model.RimapPOI
import de.deutschebahn.bahnhoflive.ui.station.shop.OpenStatusResolver.DAY_IN_MINUTES
import java.util.*
import java.util.regex.Pattern
class RimapShop(private val rimapPOI: RimapPOI) : Shop {
private val openStatusResolver: OpenStatusResolver
val remainingOpenMinutes: Int?
get() = openStatusResolver.remainingOpenMinutes
init {
openStatusResolver = OpenStatusResolver(createOpenHours())
}
override fun getName(): String? {
return rimapPOI.displname
}
override fun isOpen(): Boolean? {
return openStatusResolver.isOpen
}
private fun createOpenHours(): List<OpenHour> {
val weekLists = ArrayList<OpenHour>(4)
rimapPOI.openings?.forEach { openingTimes ->
openingTimes.forEach { openingTime ->
openingTime.openTimes?.forEach { openTime ->
findOpenHours(weekLists, openingTime.days, openTime)
}
}
}
return weekLists
}
private fun findOpenHours(
weekLists: MutableList<OpenHour>,
dayString: String?,
timeString: String?
) {
val timeMatcher = TIME_RANGE_PATTERN.matcher(timeString ?: "")
if (!timeMatcher.matches()) {
return
}
val dayMatcher = DAY_RANGE_PATTERN.matcher(dayString ?: "")
if (!dayMatcher.matches()) {
return
}
val firstDay = DAYS.indexOf(dayMatcher.group(1))
var lastDay = DAYS.indexOf(dayMatcher.group(3))
val beginMinuteOfDay = OpenStatusResolver.getMinuteOfDay(timeMatcher.group(1), timeMatcher.group(2))
var endMinuteOfDay = OpenStatusResolver.getMinuteOfDay(timeMatcher.group(3), timeMatcher.group(4))
if (firstDay < 0 || beginMinuteOfDay < 0 || endMinuteOfDay < 0) {
return
}
if (lastDay < 0) {
lastDay = firstDay
} else if (lastDay <= firstDay) {
lastDay += 7
}
if (endMinuteOfDay <= beginMinuteOfDay) {
endMinuteOfDay += DAY_IN_MINUTES
}
for (day in firstDay..lastDay) {
val dayOffset = day % 7 * DAY_IN_MINUTES
weekLists.add(OpenHour(dayOffset + beginMinuteOfDay, dayOffset + endMinuteOfDay))
}
}
private fun putOpenHours(weekLists: MutableList<OpenHour>, openHour: OpenHour, firstDay: Int, lastDay: Int) {
val endDay = lastDay + if (lastDay <= firstDay) 7 else 0
for (day in firstDay..endDay) {
weekLists.add(openHour)
}
}
override fun getOpenHoursInfo(): String {
val hoursLines = ArrayList<String>()
rimapPOI.openings?.forEach { openingTimes ->
openingTimes.forEach { openingTime ->
openingTime.openTimes?.forEach { openTime ->
appendHours(hoursLines, openingTime.days, openTime)
}
}
}
return TextUtils.join("\n", hoursLines)
}
private fun appendHours(list: MutableList<String>, day: String?, time: String?) {
if (TextUtils.isEmpty(day) || TextUtils.isEmpty(time)) {
return
}
list.add(String.format("%s: %s", day, time))
}
override fun getLocationDescription(context: Context): CharSequence {
return RimapPOI.renderFloorDescription(
context,
LevelMapping.codeToLevel(rimapPOI.level) ?: 0
)
}
override fun getPaymentTypes(): List<String>? {
return null
}
override fun getIcon(): Int {
val category = ShopCategory.of(rimapPOI)
return category?.icon ?: 0
}
override fun getPhone(): String? {
return rimapPOI.phone
}
override fun getWeb(): String? {
return rimapPOI.website
}
override fun getEmail(): String? {
return rimapPOI.email
}
override fun getRimapPOI(): RimapPOI {
return rimapPOI
}
override fun toString(): String {
return rimapPOI.toString()
}
val kotlinTags by lazy {
rimapPOI.tags?.let { rimapTags ->
TAGS_PATTERN.matchEntire(rimapTags)?.groups?.get(1)?.value
?.splitToSequence(',')
?.flatMap { tag ->
val subTags = SUB_TAG_PATTERN.findAll(tag).map {
it.value
}
subTags.plus(subTags.reduce { acc, subTag -> acc + subTag }).distinct()
}
?.toMutableList()
}.let {
if (name == "everyworks") {
mutableListOf(
"every",
"work",
"Arbeit",
"office",
"Büro",
"Buero",
"coworking",
"working",
"smart",
"city",
"Arbeitsplatz",
"Platz",
"Meeting",
"Room",
"Meetingraum",
"Raum"
).apply {
if (it != null) {
addAll(it)
}
}
} else {
it
}
}
}
override fun getTags() = kotlinTags
companion object {
private val DAYS = Arrays.asList("Sonntag", "Montag", "Dienstag", "Mittwoch", "Donnerstag", "Freitag", "Samstag")
val TIME_RANGE_PATTERN = Pattern.compile(".*(\\d\\d).*[:.].*(\\d\\d).*-.*(\\d\\d).*[:.].*(\\d\\d).*")
val DAY_RANGE_PATTERN = Pattern.compile(".*?(\\w+).*?(-.*?(\\w+)?.*?)?")
val TAGS_PATTERN = "\\((.*)\\)".toRegex()
val SUB_TAG_PATTERN = "[\\p{L}\\p{N}]+".toRegex()
}
}
| 0 | Kotlin | 4 | 33 | 3f453685d33215dbc6e9d289ce925ac430550f32 | 6,159 | dbbahnhoflive-android | Apache License 2.0 |
library/springboot/springboot-mongo/src/main/kotlin/de/lise/fluxflow/mongo/workflow/query/sort/WorkflowDocumentSort.kt | lisegmbh | 740,936,659 | false | {"Kotlin": 732949} | package de.lise.fluxflow.mongo.workflow.query.sort
import de.lise.fluxflow.mongo.query.sort.MongoDefaultSort
import de.lise.fluxflow.mongo.query.sort.MongoSort
import de.lise.fluxflow.persistence.workflow.query.sort.WorkflowDataIdSort
import de.lise.fluxflow.persistence.workflow.query.sort.WorkflowDataModelSort
import de.lise.fluxflow.persistence.workflow.query.sort.WorkflowDataSort
import de.lise.fluxflow.query.sort.UnsupportedSortException
import org.springframework.data.domain.Sort
interface WorkflowDocumentSort {
companion object {
fun toMongoSort(
sort: WorkflowDataSort
): Sort {
return when (sort) {
is WorkflowDataIdSort -> MongoDefaultSort<String>(sort.direction).apply("id")
is WorkflowDataModelSort -> MongoSort.toMongoSort(sort.sort).apply("model")
else -> throw UnsupportedSortException(sort)
}
}
}
} | 19 | Kotlin | 0 | 7 | a5093f624fb14cc278155efca79beac56b724111 | 937 | fluxflow | Apache License 2.0 |
lib/basic/src/main/java/com/dinesh/basic/app/network/api/serializers/AnySerializer.kt | Dinesh2811 | 745,880,179 | false | {"Kotlin": 1167046, "Java": 206284, "JavaScript": 20260} | package com.dinesh.basic.app.network.api.serializers
import kotlinx.serialization.KSerializer
import kotlinx.serialization.SerializationException
import kotlinx.serialization.descriptors.PrimitiveKind
import kotlinx.serialization.descriptors.PrimitiveSerialDescriptor
import kotlinx.serialization.descriptors.SerialDescriptor
import kotlinx.serialization.encoding.Decoder
import kotlinx.serialization.encoding.Encoder
import kotlinx.serialization.json.JsonDecoder
import kotlinx.serialization.json.JsonPrimitive
import kotlinx.serialization.json.boolean
import kotlinx.serialization.json.booleanOrNull
import kotlinx.serialization.json.double
import kotlinx.serialization.json.doubleOrNull
import kotlinx.serialization.json.int
import kotlinx.serialization.json.intOrNull
import kotlinx.serialization.json.long
import kotlinx.serialization.json.longOrNull
import java.math.BigDecimal
object AnySerializer : KSerializer<Any> {
override val descriptor: SerialDescriptor = PrimitiveSerialDescriptor("Any", PrimitiveKind.STRING)
override fun serialize(encoder: Encoder, value: Any) {
try {
when (value) {
is Int, is Double, is Float, is Long, is BigDecimal -> encoder.encodeString(BigDecimal(value.toString()).toString())
is Boolean -> encoder.encodeBoolean(value)
is String -> encoder.encodeString(value)
else -> encoder.encodeString(value.toString())
}
} catch (e: Exception) {
e.printStackTrace()
encoder.encodeString("")
}
}
override fun deserialize(decoder: Decoder): Any {
return try {
val input = decoder as? JsonDecoder ?: throw SerializationException("This class can be loaded only by Json")
val tree = input.decodeJsonElement()
try {
when (tree) {
is kotlinx.serialization.json.JsonPrimitive -> {
when {
tree.isString -> tree.content
tree.booleanOrNull != null -> tree.boolean
tree.intOrNull != null -> {
if (BigDecimal(tree.content) > BigDecimal(tree.int)) {
tree.content
} else {
tree.int
}
}
tree.longOrNull != null -> {
if (BigDecimal(tree.content) > BigDecimal(tree.long)) {
tree.content
} else {
tree.long
}
}
tree.doubleOrNull != null -> {
if (BigDecimal(tree.content) > BigDecimal(tree.double)) {
tree.content
} else {
tree.double
}
}
else -> tree.content
}
}
else -> throw SerializationException("Invalid Any type")
}
} catch (e: Exception) {
e.printStackTrace()
when (tree) {
is JsonPrimitive -> {
tree.content
}
else -> throw SerializationException("Invalid Any type")
}
}
} catch (e: Exception) {
e.printStackTrace()
""
}
}
}
| 0 | Kotlin | 0 | 1 | d050009b544ab4b2a5cac99fef9804e78419637b | 3,742 | Android101 | Apache License 2.0 |
src/main/kotlin/com/odim/simulator/tree/templates/redfish/MemoryTemplate.kt | ODIM-Project | 355,910,204 | false | null | // Copyright (c) Intel Corporation
//
// 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.odim.simulator.tree.templates.redfish
import com.odim.simulator.tree.RedfishVersion.V1_0_0
import com.odim.simulator.tree.RedfishVersion.V1_0_1
import com.odim.simulator.tree.RedfishVersion.V1_0_10
import com.odim.simulator.tree.RedfishVersion.V1_0_2
import com.odim.simulator.tree.RedfishVersion.V1_0_3
import com.odim.simulator.tree.RedfishVersion.V1_0_4
import com.odim.simulator.tree.RedfishVersion.V1_0_5
import com.odim.simulator.tree.RedfishVersion.V1_0_6
import com.odim.simulator.tree.RedfishVersion.V1_0_7
import com.odim.simulator.tree.RedfishVersion.V1_0_8
import com.odim.simulator.tree.RedfishVersion.V1_0_9
import com.odim.simulator.tree.RedfishVersion.V1_10_0
import com.odim.simulator.tree.RedfishVersion.V1_1_0
import com.odim.simulator.tree.RedfishVersion.V1_1_1
import com.odim.simulator.tree.RedfishVersion.V1_1_2
import com.odim.simulator.tree.RedfishVersion.V1_1_3
import com.odim.simulator.tree.RedfishVersion.V1_1_4
import com.odim.simulator.tree.RedfishVersion.V1_1_5
import com.odim.simulator.tree.RedfishVersion.V1_1_6
import com.odim.simulator.tree.RedfishVersion.V1_1_7
import com.odim.simulator.tree.RedfishVersion.V1_1_8
import com.odim.simulator.tree.RedfishVersion.V1_1_9
import com.odim.simulator.tree.RedfishVersion.V1_2_0
import com.odim.simulator.tree.RedfishVersion.V1_2_1
import com.odim.simulator.tree.RedfishVersion.V1_2_2
import com.odim.simulator.tree.RedfishVersion.V1_2_3
import com.odim.simulator.tree.RedfishVersion.V1_2_4
import com.odim.simulator.tree.RedfishVersion.V1_2_5
import com.odim.simulator.tree.RedfishVersion.V1_2_6
import com.odim.simulator.tree.RedfishVersion.V1_2_7
import com.odim.simulator.tree.RedfishVersion.V1_2_8
import com.odim.simulator.tree.RedfishVersion.V1_3_0
import com.odim.simulator.tree.RedfishVersion.V1_3_1
import com.odim.simulator.tree.RedfishVersion.V1_3_2
import com.odim.simulator.tree.RedfishVersion.V1_3_3
import com.odim.simulator.tree.RedfishVersion.V1_3_4
import com.odim.simulator.tree.RedfishVersion.V1_3_5
import com.odim.simulator.tree.RedfishVersion.V1_3_6
import com.odim.simulator.tree.RedfishVersion.V1_3_7
import com.odim.simulator.tree.RedfishVersion.V1_3_8
import com.odim.simulator.tree.RedfishVersion.V1_4_0
import com.odim.simulator.tree.RedfishVersion.V1_4_1
import com.odim.simulator.tree.RedfishVersion.V1_4_2
import com.odim.simulator.tree.RedfishVersion.V1_4_3
import com.odim.simulator.tree.RedfishVersion.V1_4_4
import com.odim.simulator.tree.RedfishVersion.V1_4_5
import com.odim.simulator.tree.RedfishVersion.V1_4_6
import com.odim.simulator.tree.RedfishVersion.V1_4_7
import com.odim.simulator.tree.RedfishVersion.V1_4_8
import com.odim.simulator.tree.RedfishVersion.V1_5_0
import com.odim.simulator.tree.RedfishVersion.V1_5_1
import com.odim.simulator.tree.RedfishVersion.V1_5_2
import com.odim.simulator.tree.RedfishVersion.V1_5_3
import com.odim.simulator.tree.RedfishVersion.V1_5_4
import com.odim.simulator.tree.RedfishVersion.V1_5_5
import com.odim.simulator.tree.RedfishVersion.V1_5_6
import com.odim.simulator.tree.RedfishVersion.V1_5_7
import com.odim.simulator.tree.RedfishVersion.V1_6_0
import com.odim.simulator.tree.RedfishVersion.V1_6_1
import com.odim.simulator.tree.RedfishVersion.V1_6_2
import com.odim.simulator.tree.RedfishVersion.V1_6_3
import com.odim.simulator.tree.RedfishVersion.V1_6_4
import com.odim.simulator.tree.RedfishVersion.V1_6_5
import com.odim.simulator.tree.RedfishVersion.V1_6_6
import com.odim.simulator.tree.RedfishVersion.V1_7_0
import com.odim.simulator.tree.RedfishVersion.V1_7_1
import com.odim.simulator.tree.RedfishVersion.V1_7_2
import com.odim.simulator.tree.RedfishVersion.V1_7_3
import com.odim.simulator.tree.RedfishVersion.V1_7_4
import com.odim.simulator.tree.RedfishVersion.V1_7_5
import com.odim.simulator.tree.RedfishVersion.V1_8_0
import com.odim.simulator.tree.RedfishVersion.V1_8_1
import com.odim.simulator.tree.RedfishVersion.V1_8_2
import com.odim.simulator.tree.RedfishVersion.V1_8_3
import com.odim.simulator.tree.RedfishVersion.V1_9_0
import com.odim.simulator.tree.RedfishVersion.V1_9_1
import com.odim.simulator.tree.RedfishVersion.V1_9_2
import com.odim.simulator.tree.RedfishVersion.V1_9_3
import com.odim.simulator.tree.ResourceTemplate
import com.odim.simulator.tree.Template
import com.odim.simulator.tree.structure.Action
import com.odim.simulator.tree.structure.ActionType.DISABLE_PASSPHRASE
import com.odim.simulator.tree.structure.ActionType.OVERWRITE_UNIT
import com.odim.simulator.tree.structure.ActionType.RESET
import com.odim.simulator.tree.structure.ActionType.SECURE_ERASE_UNIT
import com.odim.simulator.tree.structure.ActionType.SET_PASSPHRASE
import com.odim.simulator.tree.structure.ActionType.UNLOCK_UNIT
import com.odim.simulator.tree.structure.Actions
import com.odim.simulator.tree.structure.EmbeddedObjectType.MEMORY_LOCATION
import com.odim.simulator.tree.structure.EmbeddedObjectType.POWER_MANAGEMENT_POLICY
import com.odim.simulator.tree.structure.EmbeddedObjectType.REGION_SET
import com.odim.simulator.tree.structure.EmbeddedObjectType.RESOURCE_LOCATION
import com.odim.simulator.tree.structure.EmbeddedObjectType.SECURITY_CAPABILITIES
import com.odim.simulator.tree.structure.EmbeddedObjectType.STATUS
import com.odim.simulator.tree.structure.LinkableResource
import com.odim.simulator.tree.structure.Resource.Companion.embeddedArray
import com.odim.simulator.tree.structure.Resource.Companion.embeddedObject
import com.odim.simulator.tree.structure.Resource.Companion.resourceObject
import com.odim.simulator.tree.structure.ResourceType.ASSEMBLY
import com.odim.simulator.tree.structure.ResourceType.CHASSIS
import com.odim.simulator.tree.structure.ResourceType.MEMORY
import com.odim.simulator.tree.structure.ResourceType.MEMORY_METRICS
import com.odim.simulator.tree.structure.SingletonResource
/**
* This is generated class. Please don't edit it's contents.
*/
@Template(MEMORY)
open class MemoryTemplate : ResourceTemplate() {
init {
version(V1_0_0, resourceObject(
"Oem" to embeddedObject(),
"Id" to 0,
"Description" to "Memory Description",
"Name" to "Memory",
"MemoryType" to null,
"MemoryDeviceType" to null,
"BaseModuleType" to null,
"MemoryMedia" to embeddedArray(),
"CapacityMiB" to null,
"DataWidthBits" to null,
"BusWidthBits" to null,
"Manufacturer" to null,
"SerialNumber" to null,
"PartNumber" to null,
"AllowedSpeedsMHz" to embeddedArray(),
"FirmwareRevision" to null,
"FirmwareApiVersion" to null,
"FunctionClasses" to embeddedArray(),
"VendorID" to null,
"DeviceID" to null,
"SubsystemVendorID" to null,
"SubsystemDeviceID" to null,
"MaxTDPMilliWatts" to embeddedArray(),
"SecurityCapabilities" to embeddedObject(SECURITY_CAPABILITIES),
"SpareDeviceCount" to null,
"RankCount" to null,
"DeviceLocator" to null,
"MemoryLocation" to embeddedObject(MEMORY_LOCATION),
"ErrorCorrection" to null,
"OperatingSpeedMhz" to null,
"VolatileRegionSizeLimitMiB" to null,
"PersistentRegionSizeLimitMiB" to null,
"Regions" to embeddedArray(REGION_SET),
"OperatingMemoryModes" to embeddedArray(),
"PowerManagementPolicy" to embeddedObject(POWER_MANAGEMENT_POLICY),
"IsSpareDeviceEnabled" to false,
"IsRankSpareEnabled" to false,
"Metrics" to SingletonResource(MEMORY_METRICS),
"Actions" to Actions(
Action(UNLOCK_UNIT),
Action(SECURE_ERASE_UNIT),
Action(SET_PASSPHRASE),
Action(DISABLE_PASSPHRASE)
)
))
version(V1_0_1, V1_0_0)
version(V1_0_2, V1_0_1)
version(V1_0_3, V1_0_2)
version(V1_0_4, V1_0_3)
version(V1_0_5, V1_0_4)
version(V1_0_6, V1_0_5)
version(V1_0_7, V1_0_6)
version(V1_0_8, V1_0_7)
version(V1_0_9, V1_0_8)
version(V1_0_10, V1_0_9)
version(V1_1_0, V1_0_1, resourceObject(
"Status" to embeddedObject(STATUS)
))
version(V1_1_1, V1_1_0)
version(V1_1_2, V1_1_1)
version(V1_1_3, V1_1_2)
version(V1_1_4, V1_1_3)
version(V1_1_5, V1_1_4)
version(V1_1_6, V1_1_5)
version(V1_1_7, V1_1_6)
version(V1_1_8, V1_1_7)
version(V1_1_9, V1_1_8)
version(V1_2_0, V1_1_1, resourceObject(
"VolatileRegionNumberLimit" to null,
"PersistentRegionNumberLimit" to null,
"VolatileRegionSizeMaxMiB" to null,
"PersistentRegionSizeMaxMiB" to null,
"AllocationIncrementMiB" to null,
"AllocationAlignmentMiB" to null,
"Links" to embeddedObject(
"Oem" to embeddedObject(),
"Chassis" to LinkableResource(CHASSIS)
)
))
version(V1_2_1, V1_2_0)
version(V1_2_2, V1_2_1)
version(V1_2_3, V1_2_2)
version(V1_2_4, V1_2_3)
version(V1_2_5, V1_2_4)
version(V1_2_6, V1_2_5)
version(V1_2_7, V1_2_6)
version(V1_2_8, V1_2_7)
version(V1_3_0, V1_2_0, resourceObject(
"ModuleManufacturerID" to null,
"ModuleProductID" to null,
"MemorySubsystemControllerManufacturerID" to null,
"MemorySubsystemControllerProductID" to null
))
version(V1_3_1, V1_3_0)
version(V1_3_2, V1_3_1)
version(V1_3_3, V1_3_2)
version(V1_3_4, V1_3_3)
version(V1_3_5, V1_3_4)
version(V1_3_6, V1_3_5)
version(V1_3_7, V1_3_6)
version(V1_3_8, V1_3_7)
version(V1_4_0, V1_3_1, resourceObject(
"VolatileSizeMiB" to null,
"NonVolatileSizeMiB" to null,
"CacheSizeMiB" to null,
"LogicalSizeMiB" to null,
"Location" to embeddedObject(RESOURCE_LOCATION),
"Assembly" to SingletonResource(ASSEMBLY)
))
version(V1_4_1, V1_4_0)
version(V1_4_2, V1_4_1)
version(V1_4_3, V1_4_2)
version(V1_4_4, V1_4_3)
version(V1_4_5, V1_4_4)
version(V1_4_6, V1_4_5)
version(V1_4_7, V1_4_6)
version(V1_4_8, V1_4_7)
version(V1_5_0, V1_4_1)
version(V1_5_1, V1_5_0)
version(V1_5_2, V1_5_1)
version(V1_5_3, V1_5_2)
version(V1_5_4, V1_5_3)
version(V1_5_5, V1_5_4)
version(V1_5_6, V1_5_5)
version(V1_5_7, V1_5_6)
version(V1_6_0, V1_5_1, embeddedObject(
"Actions" to Actions(
Action(OVERWRITE_UNIT)
)
))
version(V1_6_1, V1_6_0)
version(V1_6_2, V1_6_1)
version(V1_6_3, V1_6_2)
version(V1_6_4, V1_6_3)
version(V1_6_5, V1_6_4)
version(V1_6_6, V1_6_5)
version(V1_7_0, V1_6_1, resourceObject(
"SecurityState" to null,
"ConfigurationLocked" to null
))
version(V1_7_1, V1_7_0)
version(V1_7_2, V1_7_1)
version(V1_7_3, V1_7_2)
version(V1_7_4, V1_7_3)
version(V1_7_5, V1_7_4)
version(V1_8_0, V1_7_2, embeddedObject(
"Actions" to Actions(
Action(RESET, "ResetType", mutableListOf(
"On",
"ForceOff",
"GracefulShutdown",
"GracefulRestart",
"ForceRestart",
"Nmi",
"ForceOn",
"PushPowerButton",
"PowerCycle"
))
)
))
version(V1_8_1, V1_8_0)
version(V1_8_2, V1_8_1)
version(V1_8_3, V1_8_2)
version(V1_9_0, V1_8_0)
version(V1_9_1, V1_9_0)
version(V1_9_2, V1_9_1)
version(V1_9_3, V1_9_2)
version(V1_10_0, V1_9_3, resourceObject(
"LocationIndicatorActive" to null
))
}
}
| 1 | Kotlin | 0 | 7 | 7e8a3030ca83c040678f8edf76def588b2b01cca | 13,227 | BMCSimulator | Apache License 2.0 |
app/common/src/commonMain/kotlin/com/denchic45/studiversity/ui/user/UserListItem.common.kt | denchic45 | 435,895,363 | false | {"Kotlin": 2110094, "Vue": 15083, "JavaScript": 2830, "CSS": 1496, "HTML": 867} | package com.denchic45.studiversity.ui.component
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.height
import androidx.compose.material3.ListItem
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.unit.dp
import com.denchic45.studiversity.domain.model.UserItem
@Composable
fun UserListItem(
item: UserItem,
avatarContent: @Composable () -> Unit,
trailingContent: (@Composable () -> Unit)? = null,
modifier: Modifier = Modifier
) {
item.apply {
ListItem(
headlineContent = {
Column {
Text(title, style = MaterialTheme.typography.bodyLarge)
subtitle?.let { Text(it, style = MaterialTheme.typography.labelMedium) }
}
},
leadingContent = { avatarContent() },
trailingContent = trailingContent,
modifier = modifier.height(64.dp)
)
}
} | 0 | Kotlin | 0 | 7 | 9d1744ffd9e1652e93af711951e924b739e96dcc | 1,088 | Studiversity | Apache License 2.0 |
app/src/main/java/com/asilbek/messenger/Messages/NewMessageActivity.kt | TheBukharian | 209,550,596 | false | null | package com.asilbek.messenger.Messages
import android.content.Intent
import android.graphics.drawable.AnimationDrawable
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.util.Log
import android.view.View
import android.widget.LinearLayout
import androidx.recyclerview.widget.RecyclerView
import com.asilbek.messenger.R
import com.asilbek.messenger.RegisterLogin.User
import com.google.firebase.database.DataSnapshot
import com.google.firebase.database.DatabaseError
import com.google.firebase.database.FirebaseDatabase
import com.google.firebase.database.ValueEventListener
import com.squareup.picasso.Picasso
import com.xwray.groupie.GroupAdapter
import com.xwray.groupie.GroupieViewHolder
import com.xwray.groupie.Item
import kotlinx.android.synthetic.main.activity_new_message.*
import kotlinx.android.synthetic.main.user_row_new_message.view.*
class NewMessageActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_new_message)
val your_Layout2 = findViewById<RecyclerView>(R.id.recyclerView_newMessage)
val animationDrawable = your_Layout2.background as AnimationDrawable
animationDrawable.setEnterFadeDuration(4000)
animationDrawable.setExitFadeDuration(4000)
animationDrawable.start()
supportActionBar?.title="Select User"
fetchUsers()
}
companion object{
val USER_KEY="USER_KEY"
}
private fun fetchUsers(){
val ref = FirebaseDatabase.getInstance().getReference("/users")
ref.addListenerForSingleValueEvent(object: ValueEventListener{
override fun onDataChange(p0: DataSnapshot) {
val adapter = GroupAdapter<GroupieViewHolder>()
val bi = findViewById<View>(R.id.Network)
p0.children.forEach{
Log.d("NewMessage",it.toString())
val user =it.getValue(User::class.java)
if (user!=null){
adapter.add(UserItem(user))
bi.visibility = View.GONE
imageView6.visibility=View.GONE
}
else {
imageView6.visibility=View.VISIBLE
bi.visibility = View.VISIBLE
}
}
adapter.setOnItemClickListener{item,view->
val userItem = item as UserItem
val intent =Intent(view.context,ChatLogActivity::class.java)
intent.putExtra(USER_KEY,userItem.user)
startActivity(intent)
finish()
}
recyclerView_newMessage.adapter =adapter
}
override fun onCancelled(p0: DatabaseError) {
}
})
}
}
class UserItem(val user: User):Item<GroupieViewHolder>(){
override fun bind(viewHolder: GroupieViewHolder, position: Int) {
viewHolder.itemView.userName_textView.text=user.username
// This downloads Avatar for users from FirebaseDatabase
Picasso.get().load(user.profileImage).into(viewHolder.itemView.imageView_userName)
}
override fun getLayout(): Int {
return R.layout.user_row_new_message
}
}
| 0 | Kotlin | 0 | 0 | 9422953ef8b6a99e14f531a53a4e56c3dacac8dd | 3,396 | Limond-messenger | Apache License 2.0 |
WorkIt/app/src/main/java/prot3ct/workit/views/list_tasks/base/ListTasksContract.kt | prot3ct | 510,755,420 | false | {"Kotlin": 213557, "C#": 92299, "Java": 2259, "ASP.NET": 107} | package prot3ct.workit.views.list_tasks.base
import prot3ct.workit.base.BaseView
import prot3ct.workit.view_models.AvailableTasksListViewModel
interface ListTasksContract {
interface View : BaseView<Presenter> {
fun showCreateJobActivity()
fun showLoginActivity()
fun notifySuccessful(message: String)
fun filterTask(query: String)
fun updateTasks(tasks: List<AvailableTasksListViewModel>)
fun notifyError(msg: String)
fun showEndProgressBar()
fun hideEndProgressBar()
}
interface Presenter {
fun getAllTasks(page: Int)
fun getSearchedAvailableTasks(page: Int, search: String)
}
} | 0 | Kotlin | 0 | 0 | b4381df44e222232c6a8c08e9453080742d9e3df | 679 | WorkItNow | MIT License |
domain/src/main/java/com/thomaskioko/paybillmanager/domain/interactor/billcategory/CreateBillsCategory.kt | c0de-wizard | 60,256,636 | false | null | package com.thomaskioko.paybillmanager.domain.interactor.billcategory
import com.thomaskioko.paybillmanager.domain.executor.PostExecutionThread
import com.thomaskioko.paybillmanager.domain.executor.ThreadExecutor
import com.thomaskioko.paybillmanager.domain.model.BillCategory
import com.thomaskioko.paybillmanager.domain.repository.BillCategoryRepository
import com.thomaskioko.paybillmanager.domain.usecase.CompletableUseCase
import io.reactivex.Completable
import javax.inject.Inject
open class CreateBillsCategory @Inject constructor(
private val repository: BillCategoryRepository,
threadExecutor: ThreadExecutor,
postExecutionThread: PostExecutionThread
) : CompletableUseCase<CreateBillsCategory.Params>(threadExecutor, postExecutionThread) {
public override fun buildUseCaseCompletable(params: Params?): Completable {
if (params == null) throw IllegalArgumentException("Params can't be null!")
return repository.createBillCategory(params.billCategory)
}
data class Params constructor(val billCategory: BillCategory) {
companion object {
fun forBillCategory(billCategory: BillCategory): Params {
return Params(billCategory)
}
}
}
} | 7 | Kotlin | 15 | 48 | e79ca3f073764d78d9a34f640fdfaec78839fe45 | 1,254 | paybill-manager | Apache License 2.0 |
app/src/main/java/net/komunan/komunantw/common/Preference.kt | ofnhwx | 127,734,456 | false | {"Kotlin": 115360} | package net.komunan.komunantw.common
import com.marcinmoskala.kotlinpreferences.PreferenceHolder
import net.komunan.komunantw.core.repository.entity.Consumer
import twitter4j.auth.RequestToken
@Suppress("ObjectPropertyName")
object Preference : PreferenceHolder() {
var currentPage: Int by bindToPreferenceField(0)
var pageSize: Int by bindToPreferenceField(100)
var fetchCount: Int by bindToPreferenceField(200)
var fetchInterval: Long by bindToPreferenceField(180)
var fetchIntervalThreshold: Float by bindToPreferenceField(0.8f)
var debugMode: Boolean by bindToPreferenceField(true)
var fetchIntervalMillis: Long
get() = fetchInterval * 1000
private set(_) = throw NotImplementedError("使用しない")
private var _requestToken: String? by bindToPreferenceFieldNullable()
var requestToken: RequestToken?
get() = _requestToken?.let { gson.fromJson(it, RequestTokenHolder::class.java).to() }
set(value) {
_requestToken = value?.let { gson.toJson(RequestTokenHolder.from(it)).toString() }
}
private var _consumer: String? by bindToPreferenceFieldNullable()
var consumer: Consumer?
get() = _consumer?.let { gson.fromJson(it, Consumer::class.java) }
set(value) {
_consumer = value?.let { gson.toJson(value).toString() }
}
private data class RequestTokenHolder(val token: String, val tokenSecret: String) {
companion object {
fun from(requestToken: RequestToken) = RequestTokenHolder(requestToken.token, requestToken.tokenSecret)
}
fun to() = RequestToken(token, tokenSecret)
}
}
| 8 | Kotlin | 0 | 0 | 80c366a0eeb67619761eb38a8a992074fd85aad7 | 1,652 | KomunanTW | Apache License 2.0 |
app/src/main/java/com/opengl/learnkotling/Note.kt | JesuisOriginal | 310,411,015 | false | {"Kotlin": 27330} | class Note (
note: Notes,
octave: Int,
) {
var octave = octave
var note = note
var myPosition: Int
var intervals: MutableList<Interval> = mutableListOf()
init {
myPosition = notesList.NoteList.indexOf(note) + 1
// println("MyPos: " + (myPosition - 1) + " Got: " + notesList.NoteList.get(myPosition - 1))
// println("List Size: " + Notes.values().size)
//
// println()
var offset = 0
var addingNote = note
for (i in 0..13) {
var lastIndex = intervals.toTypedArray().lastIndex
if (intervals.size == 0) {
addingNote = notesList.NoteList.get((i + myPosition) % 16)
// println("adding note initing")
}
var addingInterval = Intervals.values().get(i)
// println("i: " + i + " getting: " + ((i + myPosition)%14))
// println("LastIndex: " + lastIndex)
if (lastIndex > -1) {
// println("Last Element: " + intervals.elementAt(lastIndex).note.toString() + " equalNote: " + intervals.elementAt(lastIndex).note.equalNote + " addinNote: " + addingNote.toString() + " addNote Cypher: " + addingNote.cipher + " addNote Equal: " + addingNote.equalNote)
// println("Equal? " + (intervals.elementAt(lastIndex).note.equalNote === addingNote.cipher || intervals.elementAt(lastIndex).note == addingNote) )
// addingNote = notesList.NoteList.get(notesList.NoteList.indexOf(intervals.get(lastIndex).note) + 1)
// println("indexOf(${intervals.get(lastIndex).note})")
// println("This note ${addingNote.extenseName} -> next note ${notesList.NoteList.get(notesList.NoteList.indexOf(addingNote) + 1)} ")
if (intervals.elementAt(lastIndex).note.equalNote == addingNote.cipher || intervals.elementAt(lastIndex).note == addingNote) {
// Equivalent Note Already added
// println("Repeated Note Skipping with offset ${i + offset + myPosition}")
// addingNote = notesList.NoteList.get((i + 1 + myPosition ) % 16)
// addingInterval = Intervals.values().get(i)
// println("While Equal? " + (intervals.elementAt(lastIndex).note.equalNote === addingNote.cipher || intervals.elementAt(lastIndex).note == addingNote) )
while ((intervals.elementAt(lastIndex).note.equalNote === addingNote.cipher || intervals.elementAt(lastIndex).note == addingNote) ) {
offset += 1
// println("Repeated Note Skipping (AGAIN =_= < ...) ${offset + i + myPosition}")
addingNote = notesList.NoteList.get((i + offset + myPosition ) % 16)
// println(" addinNote: " + addingNote.toString() + " addNote Cypher: " + addingNote.cipher + " addNote Equal: " + addingNote.equalNote)
}
if (addingInterval.tonalInterval == intervals.elementAt(lastIndex).interval.tonalInterval ) {
// if is equivalent intervals, pick last note and next interval
// println("Last Element: " + intervals.elementAt(lastIndex).note.toString() + " equalNote: " + intervals.elementAt(lastIndex).note.equalNote + " addinNote: " + addingNote.toString() + " addNote Cypher: " + addingNote.cipher + " addNote Equal: " + addingNote.equalNote)
// println("Repeated Tonal Interval => Put same note")
intervals.add(Interval(intervals.elementAt(lastIndex).note, addingInterval))
// println(".add(Interval(${intervals.elementAt(lastIndex).note}, ${addingInterval}))")
// println("Jumpping to next note ===> ${addingNote.extenseName}".toUpperCase())
addingNote = notesList.NoteList.get(notesList.NoteList.indexOf(addingNote) + 1)
// println("\n Adding Note ${addingNote.extenseName}".toUpperCase())
} else {
// println("Last Element: " + intervals.elementAt(lastIndex).note.toString() + " equalNote: " + intervals.elementAt(lastIndex).note.equalNote + " addinNote: " + addingNote.toString() + " addNote Cypher: " + addingNote.cipher + " addNote Equal: " + addingNote.equalNote)
intervals.add(Interval(addingNote, addingInterval))
// println(".add(Interval(" + addingNote.toString() + ", " + addingInterval.toString() + " ))")
}
}
else {
// Pick Next
// println("Picking Next => This note ${addingNote.extenseName} -> next note ${notesList.NoteList.get((i + (offset + 1)+ myPosition ) % 16)} ")
intervals.add(Interval(addingNote, addingInterval))
// println(".add(Interval(${addingNote.extenseName} , ${Intervals.values().get(i).toString()} ))")
}
} else {
// If List Empty, populate first
intervals.add(Interval(addingNote, addingInterval))
// println(".add(Interval(" + notesList.NoteList.get((i + myPosition ) % 16).toString() + ", " + Intervals.values().get(i).toString() + " ))")
}
// println()
}
}
}
class NotesList() {
var NoteList : MutableList<Notes> = Notes.values().toMutableList()
}
var notesList = NotesList()
enum class Intervals(val intervalName: String, val tonalInterval: Double){
SEGUNDA_MENOR("2-", 0.5),
SEGUNDA_MAIOR("2", 1.0),
TERCA_MENOR("3-", 1.5),
TERCA_MAIOR("3", 2.0),
QUARTA_JUSTA("4", 2.5),
QUARTA_AUMENTADA("4+", 3.0),
QUINNTA_DIMINUTA("5-", 3.0),
QUINTA_JUSTA("5", 3.5),
QUINTA_AUMENTADA("5+", 4.0),
SEXTA_MENOR("6-",4.0),
SEXTA_MAIOR("6", 4.5),
SETIMA_MENOR("7", 5.0),
SETIMA_MAIOR("7+", 5.5),
OITAVA("8", 6.0)
}
data class Interval(var note: Notes, var interval: Intervals)
enum class Notes(val extenseName: String, val cipher: String, val toNextNote: Double,
val wholeNote: Boolean, val isAcidental: Boolean, val equalNote: String) {
C("Dó", "C",1.0, true, false, "B#"),
Cs("Dó Sustenido","C#", 0.5, false, true, "Db"),
Db("Ré bemol","Db", 0.5, false, true, "C#"),
D("Ré", "D", 1.0, true, false, "D"),
Ds("Ré Sustenido","D#", 1.0, true, true, "Eb"),
Eb("Mi bemol","Eb", 0.5, false, true, "D#"),
E("Mi", "E", 0.5, false, false, "Fb"),
F("Fá", "F",1.0, true, false, "E#"),
Fs("Fá Sustenido", "F#", 0.5, true, true, "Gb"),
Gb("Sol Bemol", "Gb", 0.5, true, true, "F#"),
G("Sol", "G", 1.0, true, true, "G"),
Gs("Sol Sustenido", "G#", 0.5, true, true, "Ab"),
Ab("La Bemol", "Ab", 0.5, true, true, "G#"),
A("Lá", "A",1.0, true, true, "A"),
As("Lá Sustenido", "A#", 0.5, true, true, "Bb"),
Bb("Sí Bemol", "Bb", 0.5, false, true, "A#"),
B("Si", "B",0.5, false, false, "Cb"),
}
//fun main() {
// var myNote: Note = Note(Notes.C, 0)
// println(myNote.note.extenseName)
// for (interval in myNote.intervals) {
//// println("NoteName:" + interval.note.cipher.toString() + " Interval: " + interval.interval.toString() )
//
// println(interval.note.extenseName + " ${interval.interval}")
// }
//}
| 0 | Kotlin | 0 | 0 | 18e59fca6701b0173c7e9ef5cfa37b1156d73808 | 7,410 | LearningKotlin | Apache License 2.0 |
browser-kotlin/src/jsMain/kotlin/web/events/Event.types.deprecated.kt | karakum-team | 393,199,102 | false | {"Kotlin": 6891970} | // Automatically generated - do not modify!
@file:Suppress(
"NON_ABSTRACT_MEMBER_OF_EXTERNAL_INTERFACE",
)
package web.events
import seskar.js.JsValue
sealed external interface EventTypes_deprecated {
@Deprecated(
message = "Legacy type declaration. Use type function instead!",
replaceWith = ReplaceWith("Event.abort()"),
)
@JsValue("abort")
val ABORT: EventType<Event<EventTarget>>
get() = definedExternally
@Deprecated(
message = "Legacy type declaration. Use type function instead!",
replaceWith = ReplaceWith("Event.cancel()"),
)
@JsValue("cancel")
val CANCEL: EventType<Event<EventTarget>>
get() = definedExternally
@Deprecated(
message = "Legacy type declaration. Use type function instead!",
replaceWith = ReplaceWith("Event.change()"),
)
@JsValue("change")
val CHANGE: EventType<Event<EventTarget>>
get() = definedExternally
@Deprecated(
message = "Legacy type declaration. Use type function instead!",
replaceWith = ReplaceWith("Event.close()"),
)
@JsValue("close")
val CLOSE: EventType<Event<EventTarget>>
get() = definedExternally
@Deprecated(
message = "Legacy type declaration. Use type function instead!",
replaceWith = ReplaceWith("Event.closing()"),
)
@JsValue("closing")
val CLOSING: EventType<Event<EventTarget>>
get() = definedExternally
@Deprecated(
message = "Legacy type declaration. Use type function instead!",
replaceWith = ReplaceWith("Event.complete()"),
)
@JsValue("complete")
val COMPLETE: EventType<Event<EventTarget>>
get() = definedExternally
@Deprecated(
message = "Legacy type declaration. Use type function instead!",
replaceWith = ReplaceWith("Event.error()"),
)
@JsValue("error")
val ERROR: EventType<Event<EventTarget>>
get() = definedExternally
@Deprecated(
message = "Legacy type declaration. Use type function instead!",
replaceWith = ReplaceWith("Event.open()"),
)
@JsValue("open")
val OPEN: EventType<Event<EventTarget>>
get() = definedExternally
@Deprecated(
message = "Legacy type declaration. Use type function instead!",
replaceWith = ReplaceWith("Event.success()"),
)
@JsValue("success")
val SUCCESS: EventType<Event<EventTarget>>
get() = definedExternally
}
| 0 | Kotlin | 7 | 28 | 8b3f4024ebb4f67e752274e75265afba423a8c38 | 2,484 | types-kotlin | Apache License 2.0 |
shared/src/commonMain/kotlin/domain/model/Message.kt | gleb-skobinsky | 634,563,581 | false | {"Kotlin": 250953, "Swift": 580, "HTML": 312, "Shell": 228, "Ruby": 101} | package domain.model
import androidx.compose.runtime.Immutable
import common.util.uuid
import kotlinx.datetime.LocalDateTime
import kotlinx.serialization.Serializable
import kotlinx.serialization.Transient
@Immutable
@Serializable
data class Message(
@Transient
val id: String = uuid(),
val roomId: String, // uuid
val author: User,
val content: String,
val timestamp: LocalDateTime,
val images: List<String> = emptyList()
)
| 0 | Kotlin | 0 | 10 | f576586312c1d2729e1a0100a8ccc60bfaf310f7 | 457 | compose-connect | Apache License 2.0 |
dsl/src/main/kotlin/cloudshift/awscdk/dsl/services/apprunner/CfnServiceSourceConfigurationPropertyDsl.kt | cloudshiftinc | 667,063,030 | false | null | @file:Suppress("RedundantVisibilityModifier","RedundantUnitReturnType","RemoveRedundantQualifierName","unused","UnusedImport","ClassName","REDUNDANT_PROJECTION","DEPRECATION")
package cloudshift.awscdk.dsl.services.apprunner
import cloudshift.awscdk.common.CdkDslMarker
import kotlin.Boolean
import software.amazon.awscdk.IResolvable
import software.amazon.awscdk.services.apprunner.CfnService
/**
* Describes the source deployed to an AWS App Runner service.
*
* It can be a code or an image repository.
*
* Example:
*
* ```
* // The code below shows an example of how to instantiate this type.
* // The values are placeholders you should change.
* import software.amazon.awscdk.services.apprunner.*;
* SourceConfigurationProperty sourceConfigurationProperty = SourceConfigurationProperty.builder()
* .authenticationConfiguration(AuthenticationConfigurationProperty.builder()
* .accessRoleArn("accessRoleArn")
* .connectionArn("connectionArn")
* .build())
* .autoDeploymentsEnabled(false)
* .codeRepository(CodeRepositoryProperty.builder()
* .repositoryUrl("repositoryUrl")
* .sourceCodeVersion(SourceCodeVersionProperty.builder()
* .type("type")
* .value("value")
* .build())
* // the properties below are optional
* .codeConfiguration(CodeConfigurationProperty.builder()
* .configurationSource("configurationSource")
* // the properties below are optional
* .codeConfigurationValues(CodeConfigurationValuesProperty.builder()
* .runtime("runtime")
* // the properties below are optional
* .buildCommand("buildCommand")
* .port("port")
* .runtimeEnvironmentSecrets(List.of(KeyValuePairProperty.builder()
* .name("name")
* .value("value")
* .build()))
* .runtimeEnvironmentVariables(List.of(KeyValuePairProperty.builder()
* .name("name")
* .value("value")
* .build()))
* .startCommand("startCommand")
* .build())
* .build())
* .build())
* .imageRepository(ImageRepositoryProperty.builder()
* .imageIdentifier("imageIdentifier")
* .imageRepositoryType("imageRepositoryType")
* // the properties below are optional
* .imageConfiguration(ImageConfigurationProperty.builder()
* .port("port")
* .runtimeEnvironmentSecrets(List.of(KeyValuePairProperty.builder()
* .name("name")
* .value("value")
* .build()))
* .runtimeEnvironmentVariables(List.of(KeyValuePairProperty.builder()
* .name("name")
* .value("value")
* .build()))
* .startCommand("startCommand")
* .build())
* .build())
* .build();
* ```
*
* [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-apprunner-service-sourceconfiguration.html)
*/
@CdkDslMarker
public class CfnServiceSourceConfigurationPropertyDsl {
private val cdkBuilder: CfnService.SourceConfigurationProperty.Builder =
CfnService.SourceConfigurationProperty.builder()
/**
* @param authenticationConfiguration Describes the resources that are needed to authenticate
* access to some source repositories.
*/
public fun authenticationConfiguration(authenticationConfiguration: IResolvable) {
cdkBuilder.authenticationConfiguration(authenticationConfiguration)
}
/**
* @param authenticationConfiguration Describes the resources that are needed to authenticate
* access to some source repositories.
*/
public
fun authenticationConfiguration(authenticationConfiguration: CfnService.AuthenticationConfigurationProperty) {
cdkBuilder.authenticationConfiguration(authenticationConfiguration)
}
/**
* @param autoDeploymentsEnabled If `true` , continuous integration from the source repository is
* enabled for the App Runner service.
* Each repository change (including any source code commit or new image version) starts a
* deployment.
*
* Default: App Runner sets to `false` for a source image that uses an ECR Public repository or an
* ECR repository that's in an AWS account other than the one that the service is in. App Runner sets
* to `true` in all other cases (which currently include a source code repository or a source image
* using a same-account ECR repository).
*/
public fun autoDeploymentsEnabled(autoDeploymentsEnabled: Boolean) {
cdkBuilder.autoDeploymentsEnabled(autoDeploymentsEnabled)
}
/**
* @param autoDeploymentsEnabled If `true` , continuous integration from the source repository is
* enabled for the App Runner service.
* Each repository change (including any source code commit or new image version) starts a
* deployment.
*
* Default: App Runner sets to `false` for a source image that uses an ECR Public repository or an
* ECR repository that's in an AWS account other than the one that the service is in. App Runner sets
* to `true` in all other cases (which currently include a source code repository or a source image
* using a same-account ECR repository).
*/
public fun autoDeploymentsEnabled(autoDeploymentsEnabled: IResolvable) {
cdkBuilder.autoDeploymentsEnabled(autoDeploymentsEnabled)
}
/**
* @param codeRepository The description of a source code repository.
* You must provide either this member or `ImageRepository` (but not both).
*/
public fun codeRepository(codeRepository: IResolvable) {
cdkBuilder.codeRepository(codeRepository)
}
/**
* @param codeRepository The description of a source code repository.
* You must provide either this member or `ImageRepository` (but not both).
*/
public fun codeRepository(codeRepository: CfnService.CodeRepositoryProperty) {
cdkBuilder.codeRepository(codeRepository)
}
/**
* @param imageRepository The description of a source image repository.
* You must provide either this member or `CodeRepository` (but not both).
*/
public fun imageRepository(imageRepository: IResolvable) {
cdkBuilder.imageRepository(imageRepository)
}
/**
* @param imageRepository The description of a source image repository.
* You must provide either this member or `CodeRepository` (but not both).
*/
public fun imageRepository(imageRepository: CfnService.ImageRepositoryProperty) {
cdkBuilder.imageRepository(imageRepository)
}
public fun build(): CfnService.SourceConfigurationProperty = cdkBuilder.build()
}
| 1 | Kotlin | 0 | 0 | 17c41bdaffb2e10d31b32eb2282b73dd18be09fa | 6,213 | awscdk-dsl-kotlin | Apache License 2.0 |
src/main/kotlin/no/nav/syfo/brukerinformasjon/api/BrukerinformasjonApi.kt | navikt | 238,714,111 | false | null | package no.nav.syfo.brukerinformasjon.api
import io.ktor.application.call
import io.ktor.auth.jwt.JWTPrincipal
import io.ktor.auth.principal
import io.ktor.http.HttpHeaders
import io.ktor.response.respond
import io.ktor.routing.Route
import io.ktor.routing.get
import io.ktor.routing.route
import no.nav.syfo.arbeidsgivere.model.Arbeidsgiverinfo
import no.nav.syfo.arbeidsgivere.service.ArbeidsgiverService
import no.nav.syfo.client.StsOidcClient
import no.nav.syfo.pdl.service.PdlPersonService
import java.util.UUID
fun Route.registrerBrukerinformasjonApi(arbeidsgiverService: ArbeidsgiverService, pdlPersonService: PdlPersonService, stsOidcClient: StsOidcClient) {
route("api/v1") {
get("/brukerinformasjon") {
val principal = call.principal<JWTPrincipal>()!!
val fnr = principal.payload.subject
val token = call.request.headers[HttpHeaders.Authorization]!!
val stsToken = stsOidcClient.oidcToken()
val person = pdlPersonService.getPerson(
fnr = fnr,
userToken = token,
callId = UUID.randomUUID().toString(),
stsToken = stsToken.access_token
)
val arbeidsgivere = if (person.diskresjonskode) emptyList() else arbeidsgiverService.getArbeidsgivere(
fnr = fnr,
token = token,
sykmeldingId = UUID.randomUUID().toString()
)
call.respond(
Brukerinformasjon(
strengtFortroligAdresse = person.diskresjonskode,
arbeidsgivere = arbeidsgivere
)
)
}
get("/syforest/brukerinformasjon") {
val principal = call.principal<JWTPrincipal>()!!
val fnr = principal.payload.subject
val token = call.request.headers[HttpHeaders.Authorization]!!
val stsToken = stsOidcClient.oidcToken()
val person = pdlPersonService.getPerson(
fnr = fnr,
userToken = token,
callId = UUID.randomUUID().toString(),
stsToken = stsToken.access_token
)
call.respond(
BrukerinformasjonSyforest(strengtFortroligAdresse = person.diskresjonskode)
)
}
}
}
data class BrukerinformasjonSyforest(
val strengtFortroligAdresse: Boolean
)
data class Brukerinformasjon(
val arbeidsgivere: List<Arbeidsgiverinfo>,
val strengtFortroligAdresse: Boolean
)
| 1 | Kotlin | 0 | 0 | 2a8e5d27901790b931c82833c272ba2c30ef63f5 | 2,538 | sykmeldinger-backend | MIT License |
src/test/kotlin/org/rust/ide/inspections/RustInspectionsTest.kt | ninjabear | 60,753,746 | true | {"Kotlin": 352733, "Rust": 63867, "Lex": 11971, "Java": 7923, "HTML": 698, "RenderScript": 91} | package org.rust.ide.inspections
import com.intellij.codeInspection.LocalInspectionTool
import org.rust.lang.RustTestCaseBase
class RustInspectionsTest : RustTestCaseBase() {
override val dataPath = "org/rust/ide/inspections/fixtures"
fun testApproxConstant() = doTest<ApproxConstantInspection>()
fun testSelfConvention() = doTest<SelfConventionInspection>()
fun testUnresolvedModuleDeclaration() = doTest<UnresolvedModuleDeclarationInspection>()
fun testUnresolvedModuleDeclarationQuickFix() = checkByDirectory {
enableInspection<UnresolvedModuleDeclarationInspection>()
openFileInEditor("mod.rs")
applyQuickFix("Create module file")
}
fun testUnresolvedLocalModuleDeclaration() = doTest<UnresolvedModuleDeclarationInspection>()
private inline fun<reified T: LocalInspectionTool>enableInspection() {
myFixture.enableInspections(T::class.java)
}
private inline fun <reified T: LocalInspectionTool>doTest() {
enableInspection<T>()
myFixture.testHighlighting(true, false, true, fileName)
}
private fun applyQuickFix(name: String) {
val action = myFixture.getAvailableIntention(name)!!
myFixture.launchAction(action)
}
}
| 0 | Kotlin | 0 | 0 | 283f8ac1b441147c1227ebc5992b7dc75fbbacb0 | 1,244 | intellij-rust | MIT License |
kotlin-js/src/jsMain/kotlin/js/reflect/upcast.kt | JetBrains | 93,250,841 | false | {"Kotlin": 12635434, "JavaScript": 423801} | @file:Suppress(
"NOTHING_TO_INLINE",
)
package js.reflect
inline fun <T> T.upcast(): T =
this
| 38 | Kotlin | 162 | 1,347 | 997ed3902482883db4a9657585426f6ca167d556 | 104 | kotlin-wrappers | Apache License 2.0 |
android/core/src/main/java/com/iprayforgod/core/domain/features/analytics/AnalyticsFeature.kt | devrath | 507,511,543 | false | {"Kotlin": 219977, "Java": 712} | package com.iprayforgod.core.domain.features.analytics
interface AnalyticsFeature {
// fun loginStatus(userId: Int, isSuccessful: Boolean, reasonForFailure: String)
}
| 0 | Kotlin | 4 | 18 | 060080c93dc97279603be3efe5a228eadc71f41a | 172 | droid-pure-kotlin-application | Apache License 2.0 |
app/src/main/java/com/allat/mboychenko/silverthread/data/storage/db/diary/DiaryNotesData.kt | mboychenko | 184,405,918 | false | null | package com.allat.mboychenko.silverthread.data.storage.db.diary
import androidx.room.*
import com.allat.mboychenko.silverthread.data.storage.db.diary.DiaryFieldsContract.DIARY_NOTES_TABLE_NAME
import java.util.*
@Entity(tableName = DIARY_NOTES_TABLE_NAME)
data class DiaryNotesData(
@ColumnInfo(name = DiaryFieldsContract.ID) @PrimaryKey(autoGenerate = false) val id: String,
@ColumnInfo(name = DiaryFieldsContract.NOTES) val note: String,
@ColumnInfo(name = DiaryFieldsContract.START) val start: Calendar = Calendar.getInstance()
)
| 0 | Kotlin | 1 | 2 | 31fa2a6ccfcb2ee49bd7dbb6c0a29dd4286f477a | 547 | SilverThread | Apache License 2.0 |
decompose/navigation-koin-compose/src/commonMain/kotlin/io/github/dmitriy1892/kmp/libs/decompose/navigation/koin/compose/KoinComposeNavGraph.kt | Dmitriy1892 | 782,469,883 | false | {"Kotlin": 133960, "Shell": 2195, "Swift": 1932} | package io.github.dmitriy1892.kmp.libs.decompose.navigation.koin.compose
import androidx.lifecycle.ViewModelProvider
import com.arkivanov.decompose.ComponentContext
import io.github.dmitriy1892.kmp.libs.decompose.navigation.compose.ComposeNavGraph
import kotlinx.serialization.Serializable
import org.koin.core.component.inject
abstract class KoinComposeNavGraph<Config: @Serializable Any, Destination: Any>(
componentContext: ComponentContext
) : ComposeNavGraph<Config, Destination>(componentContext), KoinComposeComponentContext {
override val viewModelFactory: Lazy<ViewModelProvider.Factory> = inject()
} | 0 | Kotlin | 0 | 0 | 2e5cc7a90ac097a0c28fc8c3083e217ddee04fca | 620 | kmp-libs | Apache License 2.0 |
library-compose/src/main/java/com/spendesk/grapes/compose/appbar/GrapesTopAppBarDefaults.kt | Spendesk | 364,042,096 | false | {"Kotlin": 628975} | package com.spendesk.grapes.compose.appbar
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.TopAppBarDefaults
import androidx.compose.runtime.Composable
import androidx.compose.ui.graphics.Color
import com.spendesk.grapes.compose.theme.GrapesTheme
object GrapesTopAppBarDefaults {
@Composable
@OptIn(ExperimentalMaterial3Api::class)
fun colors(
containerColor: Color = GrapesTheme.colors.structureBackground,
scrolledContainerColor: Color = GrapesTheme.colors.structureBackground,
navigationIconContentColor: Color = GrapesTheme.colors.structureComplementary,
titleContentColor: Color = GrapesTheme.colors.structureComplementary,
actionIconContentColor: Color = GrapesTheme.colors.structureComplementary,
) = TopAppBarDefaults.mediumTopAppBarColors(
containerColor = containerColor,
scrolledContainerColor = scrolledContainerColor,
navigationIconContentColor = navigationIconContentColor,
titleContentColor = titleContentColor,
actionIconContentColor = actionIconContentColor,
)
}
| 1 | Kotlin | 5 | 9 | 3f754ca2312d27f2639c8bb3f8fb906ff515b870 | 1,128 | grapes-android | Apache License 2.0 |
app/src/test/java/com/mehmedmert/gameofthroneshouses/ui/common/NavigationEventTest.kt | mmert1988 | 504,935,746 | false | {"Kotlin": 30660} | package com.mehmedmert.gameofthroneshouses.ui.common
import androidx.navigation.NavController
import org.junit.Test
import org.junit.runner.RunWith
import org.mockito.Mock
import org.mockito.junit.MockitoJUnitRunner
import org.mockito.kotlin.times
import org.mockito.kotlin.verify
@RunWith(MockitoJUnitRunner::class)
class NavigationEventTest {
@Mock lateinit var navController: NavController
@Test
fun `verify consumed only once`() {
// given
val navigationEvent = NavigationEvent.Back
// when
navigationEvent.consume(navController)
navigationEvent.consume(navController)
// then
verify(navController, times(1)).popBackStack()
}
}
| 0 | Kotlin | 0 | 0 | 15d4c28401ef85a7b0f06ee3117e1dea745da5fc | 709 | game-of-thrones-houses | Apache License 2.0 |
common/src/androidMain/kotlin/dev/zwander/common/util/pathTo.kt | zacharee | 641,202,797 | false | {"Kotlin": 465345, "Swift": 10431, "Ruby": 2751, "Shell": 470} | package dev.zwander.common.util
import dev.zwander.common.App
actual fun pathTo(subPath: String, startingTag: String): String {
return "${App.instance?.filesDir?.path}/$subPath"
} | 5 | Kotlin | 4 | 91 | 3d958ae0b2581815d4e496b0fef69186cc3a8c4f | 185 | ArcadyanKVD21Control | MIT License |
src/main/kotlin/io/github/jokoroukwu/zephyrgradleplugin/ZephyrConfigurationInternal.kt | jokoroukwu | 479,408,912 | false | {"Kotlin": 11081} | package io.github.jokoroukwu.zephyrgradleplugin
import io.github.jokoroukwu.zephyrapi.config.ZephyrConfig
import java.net.URL
import java.time.ZoneId
internal class ZephyrConfigurationInternal(zephyrPluginConfiguration: ZephyrPluginConfiguration) :
ZephyrConfig {
override val jiraUrl: URL = zephyrPluginConfiguration.jiraURLProvider.get()
override val projectKey: String = zephyrPluginConfiguration.projectKeyProvider.get()
override val timeZone: ZoneId = zephyrPluginConfiguration.timeZoneProvider.get()
override val username: String = zephyrPluginConfiguration.userNameProvider.get()
override val password: String = zephyrPluginConfiguration.passwordProvider.get()
override fun toString(): String =
"${javaClass.simpleName}: { projectKey: '$projectKey', timeZone: '$timeZone', jiraURL: '$jiraUrl'," +
" userName: '$username'," +
" password: ${"*".repeat(password.length)} }"
} | 0 | Kotlin | 0 | 0 | 0481a13776e4dc196e8675642f1527ffc33ff4a3 | 956 | zephyr-gradle-plugin | Apache License 2.0 |
web/src/main/kotlin/ru/iriyc/cc/server/service/CookieService.kt | Pastor | 69,604,231 | false | {"Maven POM": 2, "Text": 1, "Ignore List": 2, "Markdown": 2, "HTML": 1, "Kotlin": 34, "Java Server Pages": 1, "XML": 2, "Java": 1} | package ru.iriyc.cc.server.service
import ru.iriyc.cc.server.service.TokenService.TOKEN_TTL
import javax.servlet.http.Cookie
import javax.servlet.http.HttpServletRequest
import javax.servlet.http.HttpServletResponse
internal object CookieService {
private const val TOKEN_NAME = "X-Authority-Token"
internal fun token(request: HttpServletRequest): String? {
return request.cookies
.firstOrNull { it.name!!.contentEquals(TOKEN_NAME) }
?.value
}
internal fun addCookie(token: String, resp: HttpServletResponse) {
val cookie = Cookie(TOKEN_NAME, token)
cookie.path = "/"
cookie.maxAge = (TOKEN_TTL * 60 * 60).toInt()
resp.addCookie(cookie)
}
internal fun eraseCookie(req: HttpServletRequest, resp: HttpServletResponse) {
val cookies = req.cookies
if (cookies != null) {
for (i in cookies.indices) {
cookies[i].value = ""
cookies[i].path = "/"
cookies[i].maxAge = 0
resp.addCookie(cookies[i])
}
}
}
} | 5 | null | 1 | 1 | cfb8fc4ebdde8268a13d1d326659a034722980a0 | 1,115 | cc | Apache License 2.0 |
app/src/main/kotlin/no/nav/tiltakspenger/vedtak/routes/behandling/BehandlingRoutes.kt | navikt | 487,246,438 | false | {"Kotlin": 875417, "Shell": 1309, "Dockerfile": 495, "HTML": 45} | package no.nav.tiltakspenger.vedtak.routes.behandling
import io.ktor.http.HttpStatusCode
import io.ktor.server.application.call
import io.ktor.server.request.receive
import io.ktor.server.response.respond
import io.ktor.server.routing.Route
import io.ktor.server.routing.get
import io.ktor.server.routing.post
import kotlinx.coroutines.delay
import mu.KotlinLogging
import no.nav.tiltakspenger.felles.BehandlingId
import no.nav.tiltakspenger.felles.Saksbehandler
import no.nav.tiltakspenger.innsending.domene.Aktivitetslogg
import no.nav.tiltakspenger.innsending.domene.meldinger.InnsendingUtdatertHendelse
import no.nav.tiltakspenger.innsending.ports.InnsendingMediator
import no.nav.tiltakspenger.saksbehandling.domene.behandling.Førstegangsbehandling
import no.nav.tiltakspenger.saksbehandling.ports.AttesteringRepo
import no.nav.tiltakspenger.saksbehandling.service.behandling.BehandlingService
import no.nav.tiltakspenger.saksbehandling.service.sak.SakService
import no.nav.tiltakspenger.vedtak.routes.behandling.SaksopplysningDTOMapper.lagSaksopplysningMedVilkår
import no.nav.tiltakspenger.vedtak.routes.behandling.SammenstillingForBehandlingDTOMapper.mapSammenstillingDTO
import no.nav.tiltakspenger.vedtak.routes.parameter
import no.nav.tiltakspenger.vedtak.tilgang.InnloggetSaksbehandlerProvider
private val SECURELOG = KotlinLogging.logger("tjenestekall")
private val LOG = KotlinLogging.logger {}
internal const val behandlingPath = "/behandling"
internal const val behandlingerPath = "/behandlinger"
data class IdentDTO(
val ident: String?,
)
fun Route.behandlingRoutes(
innloggetSaksbehandlerProvider: InnloggetSaksbehandlerProvider,
behandlingService: BehandlingService,
sakService: SakService,
innsendingMediator: InnsendingMediator,
attesteringRepo: AttesteringRepo,
) {
get("$behandlingPath/{behandlingId}") {
SECURELOG.debug("Mottatt request på $behandlingPath/behandlingId")
val saksbehandler: Saksbehandler = innloggetSaksbehandlerProvider.krevInnloggetSaksbehandler(call)
val behandlingId = BehandlingId.fromString(call.parameter("behandlingId"))
val sak = sakService.hentMedBehandlingId(behandlingId, saksbehandler)
if (sak.personopplysninger.erTom()) {
return@get call.respond(
message = "Sak mangler personopplysninger",
status = HttpStatusCode.NotFound,
)
}
val behandling = sak.behandlinger.filterIsInstance<Førstegangsbehandling>().firstOrNull {
it.id == behandlingId
} ?: return@get call.respond(message = "Behandling ikke funnet", status = HttpStatusCode.NotFound)
// her burde vi nok ikke bare hente den første, men finne den riktige og evnt feilmelding hvis vi ikke finner den
// val behandling = behandlingService.hentBehandling(behandlingId) Skal vi hente behandling direkte eller via sak?
val attesteringer = attesteringRepo.hentForBehandling(behandling.id)
val dto = mapSammenstillingDTO(
behandling = behandling,
personopplysninger = sak.personopplysninger.søkere(),
attesteringer = attesteringer,
)
call.respond(status = HttpStatusCode.OK, dto)
}
post("$behandlingPath/{behandlingId}") {
SECURELOG.debug("Mottatt request på $behandlingPath/")
val saksbehandler: Saksbehandler = innloggetSaksbehandlerProvider.krevInnloggetSaksbehandler(call)
val behandlingId = BehandlingId.fromString(call.parameter("behandlingId"))
val nySaksopplysning = call.receive<SaksopplysningDTO>()
behandlingService.leggTilSaksopplysning(
behandlingId,
lagSaksopplysningMedVilkår(saksbehandler, nySaksopplysning),
)
call.respond(status = HttpStatusCode.OK, message = "{}")
}
post("$behandlingPath/beslutter/{behandlingId}") {
SECURELOG.debug("Mottatt request. $behandlingPath/ skal sendes til beslutter")
val saksbehandler = innloggetSaksbehandlerProvider.krevInnloggetSaksbehandler(call)
val behandlingId = BehandlingId.fromString(call.parameter("behandlingId"))
behandlingService.sendTilBeslutter(behandlingId, saksbehandler)
call.respond(status = HttpStatusCode.OK, message = "{}")
}
post("$behandlingPath/oppdater/{behandlingId}") {
SECURELOG.debug { "Vi har mottatt melding om oppfriskning av fakta" }
val saksbehandler = innloggetSaksbehandlerProvider.krevInnloggetSaksbehandler(call)
val behandlingId = BehandlingId.fromString(call.parameter("behandlingId"))
SECURELOG.info { "Saksbehandler $saksbehandler ba om oppdatering av saksopplysninger for behandling $behandlingId" }
// TODO: Rollesjekk ikke helt landet
behandlingService.hentBehandling(behandlingId).let {
val innsendingUtdatertHendelse = InnsendingUtdatertHendelse(
aktivitetslogg = Aktivitetslogg(),
journalpostId = it.søknad().journalpostId,
)
innsendingMediator.håndter(innsendingUtdatertHendelse)
}
// TODO: Skriv denne om til en sjekk på om det faktisk er oppdatert
delay(3000)
call.respond(message = "{}", status = HttpStatusCode.OK)
}
post("$behandlingPath/avbrytbehandling/{behandlingId}") {
SECURELOG.debug { "Mottatt request om å fjerne saksbehandler på behandlingen" }
val saksbehandler = innloggetSaksbehandlerProvider.krevInnloggetSaksbehandler(call)
val behandlingId = BehandlingId.fromString(call.parameter("behandlingId"))
behandlingService.frataBehandling(behandlingId, saksbehandler)
call.respond(message = "{}", status = HttpStatusCode.OK)
}
post("$behandlingPath/opprettrevurdering/{}") {
val behandlingId = call.parameters["behandlingId"]?.let { BehandlingId.fromString(it) }
?: return@post call.respond(message = "BehandlingId ikke funnet", status = HttpStatusCode.NotFound)
LOG.info { "Mottatt request om å opprette en revurdering på behandlingen: $behandlingId" }
val saksbehandler = innloggetSaksbehandlerProvider.hentInnloggetSaksbehandler(call)
?: return@post call.respond(message = "JWTToken ikke funnet", status = HttpStatusCode.Unauthorized)
val revurdering = behandlingService.opprettRevurdering(behandlingId, saksbehandler)
LOG.info { "Revurderingen: $revurdering" }
call.respond(message = "{ \"id\":\"${revurdering.id}\"}", status = HttpStatusCode.OK)
}
}
| 3 | Kotlin | 0 | 1 | 7bc0886a7b0300aa9293b84cfddfe90b968744bf | 6,573 | tiltakspenger-vedtak | MIT License |
client/src/main/kotlin/com/ecwid/upsource/rpc/UpsourceRPC.kt | turchenkoalex | 266,583,029 | false | null | // Generated by the codegen. Please DO NOT EDIT!
// source: service.ftl
package com.ecwid.upsource.rpc
import com.ecwid.upsource.ClientBuilderImpl
import com.ecwid.upsource.EmptyClientBuilder
import com.ecwid.upsource.transport.RpcResponse
/**
* Main RPC service
*/
interface UpsourceRPC {
/**
* Accepts the end user agreement for a given user
*/
fun acceptUserAgreement(request: com.ecwid.upsource.rpc.ids.VoidMessage): RpcResponse<com.ecwid.upsource.rpc.ids.VoidMessage>
/**
* Returns the text of the end user agreement
*/
fun getUserAgreementText(request: com.ecwid.upsource.rpc.ids.VoidMessage): RpcResponse<com.ecwid.upsource.rpc.misc.UserAgreementTextDTO>
/**
* In the case of an empty request, returns the list of all short project infos. Otherwise returns the list of project infos for a given set of project IDs. In any case only the projects the user has access to are returned.
*/
fun getAllProjects(request: com.ecwid.upsource.rpc.ids.ProjectIdListDTO): RpcResponse<com.ecwid.upsource.rpc.projects.ShortProjectInfoListDTO>
/**
* Returns the list of projects matching a given search criteria
*/
fun findProjects(request: com.ecwid.upsource.rpc.projects.FindProjectsRequestDTO): RpcResponse<com.ecwid.upsource.rpc.projects.ShortProjectInfoListDTO>
/**
* Returns basic information about the project - name, project model, latest revision, etc.
*/
fun getProjectInfo(request: com.ecwid.upsource.rpc.ids.ProjectIdDTO): RpcResponse<com.ecwid.upsource.rpc.projects.ProjectInfoDTO>
/**
* Returns VCS repository URL(s) for a given project
*/
fun getProjectVcsLinks(request: com.ecwid.upsource.rpc.ids.ProjectIdDTO): RpcResponse<com.ecwid.upsource.rpc.projects.VcsRepoListDTO>
/**
* Returns README (README.md) contents from the latest revision
*/
fun getProjectReadme(request: com.ecwid.upsource.rpc.ids.ProjectIdDTO): RpcResponse<com.ecwid.upsource.rpc.projects.ProjectReadmeResponseDTO>
/**
* Returns all registered code review patterns across all projects
*/
fun getCodeReviewPatterns(request: com.ecwid.upsource.rpc.ids.VoidMessage): RpcResponse<com.ecwid.upsource.rpc.projects.CodeReviewPatternsDTO>
/**
* Returns the revision descriptor for the latest revision - ID, date, commit message, authors, parent revisions, etc.
*/
fun getHeadRevision(request: com.ecwid.upsource.rpc.ids.ProjectIdDTO): RpcResponse<com.ecwid.upsource.rpc.projects.RevisionInfoDTO>
/**
* Returns the list of revisions in a given project (optionally with revision graph)
*/
fun getRevisionsList(request: com.ecwid.upsource.rpc.projects.RevisionsListRequestDTO): RpcResponse<com.ecwid.upsource.rpc.projects.RevisionDescriptorListDTO>
/**
* Returns the list of revisions that match the given search query
*/
fun getRevisionsListFiltered(request: com.ecwid.upsource.rpc.projects.RevisionsListFilteredRequestDTO): RpcResponse<com.ecwid.upsource.rpc.projects.RevisionDescriptorListDTO>
/**
* Returns the list of revisions across all projects authored by the specified user and (optionally) matching the specified query
*/
fun getUserRevisionsList(request: com.ecwid.upsource.rpc.projects.UserRevisionsListRequestDTO): RpcResponse<com.ecwid.upsource.rpc.projects.RevisionDescriptorListDTO>
/**
* Returns the list of revisions since the given revision
*/
fun getRevisionsListUpdate(request: com.ecwid.upsource.rpc.projects.RevisionsListUpdateRequestDTO): RpcResponse<com.ecwid.upsource.rpc.projects.RevisionsListUpdateResponseDTO>
/**
* Returns the revision descriptor - ID, date, commit message, authors, parent revisions, etc.
*/
fun getRevisionInfo(request: com.ecwid.upsource.rpc.ids.RevisionInProjectDTO): RpcResponse<com.ecwid.upsource.rpc.projects.RevisionInfoDTO>
/**
* Returns the list of changes (files that were added, removed, or modified) in a revision
*/
fun getRevisionChanges(request: com.ecwid.upsource.rpc.projects.RevisionChangesRequestDTO): RpcResponse<com.ecwid.upsource.rpc.projects.RevisionsDiffDTO>
/**
* Returns the list of branches a revision is part of
*/
fun getRevisionBranches(request: com.ecwid.upsource.rpc.ids.RevisionInProjectDTO): RpcResponse<com.ecwid.upsource.rpc.projects.RevisionBranchesResponseDTO>
/**
* Returns the project structure tree starting from the given file
*/
fun getProjectSubtree(request: com.ecwid.upsource.rpc.ids.FileInRevisionDTO): RpcResponse<com.ecwid.upsource.rpc.projects.ProjectItemsListDTO>
/**
* Returns meta information about a file (is deleted, is latest revision, etc.)
*/
fun getFileMeta(request: com.ecwid.upsource.rpc.ids.FileInRevisionDTO): RpcResponse<com.ecwid.upsource.rpc.projects.FileMetaResponseDTO>
/**
* Returns the line-by-line file annotation
*/
fun getFileAnnotation(request: com.ecwid.upsource.rpc.ids.FileInRevisionDTO): RpcResponse<com.ecwid.upsource.rpc.projects.FileAnnotationResponseDTO>
/**
* Returns the file contributors
*/
fun getFileContributors(request: com.ecwid.upsource.rpc.ids.FileInRevisionDTO): RpcResponse<com.ecwid.upsource.rpc.fileordirectorycontent.FileContributorsResponseDTO>
/**
* Returns the authors of the given file fragment
*/
fun getFileFragmentAuthors(request: com.ecwid.upsource.rpc.projects.FileFragmentAuthorsRequestDTO): RpcResponse<com.ecwid.upsource.rpc.users.UsersListDTO>
/**
* Returns the history (list of revision IDs and change types) of the file
*/
fun getFileHistory(request: com.ecwid.upsource.rpc.projects.FileHistoryRequestDTO): RpcResponse<com.ecwid.upsource.rpc.projects.FileHistoryResponseDTO>
/**
* Returns the diff (changed lines and ranges) between the given revisions of a file
*/
fun getFileDiff(request: com.ecwid.upsource.rpc.projects.FileDiffRequestDTO): RpcResponse<com.ecwid.upsource.rpc.projects.FileDiffResponseDTO>
/**
* Returns the inline diff (changed lines and ranges, line numbers mapping) for the given file
*/
fun getFileInlineDiff(request: com.ecwid.upsource.rpc.projects.FileDiffRequestDTO): RpcResponse<com.ecwid.upsource.rpc.projects.FileInlineDiffResponseDTO>
/**
* Returns the inline diff of a file after the merge with the base branch
*/
fun getFileMergeInlineDiff(request: com.ecwid.upsource.rpc.projects.FileMergeInlineDiffRequestDTO): RpcResponse<com.ecwid.upsource.rpc.projects.FileInlineDiffResponseDTO>
/**
* Returns the contents of the given file
*/
fun getFileContent(request: com.ecwid.upsource.rpc.ids.FileInRevisionDTO): RpcResponse<com.ecwid.upsource.rpc.fileordirectorycontent.FileContentResponseDTO>
/**
* Returns the semantic markup of the given file
*/
fun getFilePsi(request: com.ecwid.upsource.rpc.fileordirectorycontent.FilePsiRequestDTO): RpcResponse<com.ecwid.upsource.rpc.fileordirectorycontent.FilePsiResponseDTO>
/**
* Returns the text range of the given PSI element
*/
fun getStubNavigationRange(request: com.ecwid.upsource.rpc.findusages.StubIdDTO): RpcResponse<com.ecwid.upsource.rpc.findusages.NavigationTargetItemDTO>
/**
* Returns the text representation of the given PSI element
*/
fun getElementDescription(request: com.ecwid.upsource.rpc.findusages.PsiElementIdDTO): RpcResponse<com.ecwid.upsource.rpc.findusages.TargetDescriptionDTO>
/**
* Returns the documentation (e.g. Javadoc) for the given PSI element
*/
fun getElementDocumentation(request: com.ecwid.upsource.rpc.findusages.PsiElementIdDTO): RpcResponse<com.ecwid.upsource.rpc.findusages.ElementDocumentationDTO>
/**
* Returns the list of usages for the given PSI element
*/
fun findUsages(request: com.ecwid.upsource.rpc.findusages.PsiElementIdDTO): RpcResponse<com.ecwid.upsource.rpc.findusages.FindUsagesResponseDTO>
/**
* Returns the usages diff for the given PSI element between two revisions
*/
fun getUsagesDiff(request: com.ecwid.upsource.rpc.findusages.UsagesDiffRequestDTO): RpcResponse<com.ecwid.upsource.rpc.findusages.UsagesDiffResponseDTO>
/**
* Returns the list of inheritors and ancestors for the given PSI element
*/
fun findHierarchy(request: com.ecwid.upsource.rpc.findusages.PsiElementIdDTO): RpcResponse<com.ecwid.upsource.rpc.findusages.FindHierarchyResultDTO>
/**
* Returns the files matched by the search query in a given revision, review, project-wide, or service-wide
*/
fun gotoFileByName(request: com.ecwid.upsource.rpc.findusages.GotoFileRequestDTO): RpcResponse<com.ecwid.upsource.rpc.findusages.GotoFileResponseDTO>
/**
* Performs full-text search across all commits and files (either service-wide or project-wide)
*/
fun textSearch(request: com.ecwid.upsource.rpc.findusages.TextSearchRequestDTO): RpcResponse<com.ecwid.upsource.rpc.findusages.TextSearchResponseDTO>
/**
* Performs project-wide search by branch name
*/
fun findBranches(request: com.ecwid.upsource.rpc.findusages.FindBranchRequestDTO): RpcResponse<com.ecwid.upsource.rpc.findusages.FindBranchResponseDTO>
/**
* Returns the list of changes in the given branch
*/
fun getBranchDiff(request: com.ecwid.upsource.rpc.projects.BranchRequestDTO): RpcResponse<com.ecwid.upsource.rpc.projects.RevisionsDiffDTO>
/**
* Returns the list of changes between any two revisions
*/
fun getRevisionsDiff(request: com.ecwid.upsource.rpc.projects.RevisionsDiffRequestDTO): RpcResponse<com.ecwid.upsource.rpc.projects.RevisionsDiffDTO>
/**
* Compare page
*/
fun getCompareInfo(request: com.ecwid.upsource.rpc.projects.CompareRequestDTO): RpcResponse<com.ecwid.upsource.rpc.projects.CompareInfoDTO>
/**
* Revision graph for compare page
*/
fun getCompareGraph(request: com.ecwid.upsource.rpc.projects.RevisionsDiffRequestDTO): RpcResponse<com.ecwid.upsource.rpc.projects.CompareGraphDTO>
/**
* Branch page
*/
fun getBranchInfo(request: com.ecwid.upsource.rpc.projects.BranchRequestDTO): RpcResponse<com.ecwid.upsource.rpc.projects.BranchInfoDTO>
/**
* Revision graph for branch page
*/
fun getBranchGraph(request: com.ecwid.upsource.rpc.projects.BranchRequestDTO): RpcResponse<com.ecwid.upsource.rpc.projects.BranchGraphDTO>
/**
* Returns the list of branches in a project
*/
fun getBranches(request: com.ecwid.upsource.rpc.projects.BranchesRequestDTO): RpcResponse<com.ecwid.upsource.rpc.projects.BranchListDTO>
/**
* Finds commit(s) with the given commit hash
*/
fun findCommits(request: com.ecwid.upsource.rpc.projects.FindCommitsRequestDTO): RpcResponse<com.ecwid.upsource.rpc.projects.FindCommitsResponseDTO>
/**
* Returns the discussions in the project, matching given query
*/
fun getProjectDiscussions(request: com.ecwid.upsource.rpc.projects.DiscussionsInProjectRequestDTO): RpcResponse<com.ecwid.upsource.rpc.projects.DiscussionsInProjectDTO>
/**
* Returns the discussions in the given file
*/
fun getFileDiscussions(request: com.ecwid.upsource.rpc.ids.FileInRevisionDTO): RpcResponse<com.ecwid.upsource.rpc.projects.DiscussionsInFileDTO>
/**
* Returns the discussions in the given revision
*/
fun getInlineDiscussionsInRevision(request: com.ecwid.upsource.rpc.ids.RevisionInProjectDTO): RpcResponse<com.ecwid.upsource.rpc.projects.DiscussionsInFilesDTO>
/**
* Creates a new discussion
*/
fun createDiscussion(request: com.ecwid.upsource.rpc.projects.CreateDiscussionRequestDTO): RpcResponse<com.ecwid.upsource.rpc.projects.DiscussionInFileDTO>
/**
* Updates a discussion
*/
fun resolveDiscussion(request: com.ecwid.upsource.rpc.projects.ResolveDiscussionRequestDTO): RpcResponse<com.ecwid.upsource.rpc.projects.ResolveDiscussionResponseDTO>
/**
* Checks if current user can resolve the given discussion
*/
fun getCurrentUserCanResolveDiscussion(request: com.ecwid.upsource.rpc.projects.DiscussionIdDTO): RpcResponse<com.ecwid.upsource.rpc.ids.VoidMessage>
/**
* Adds a label to a discussion
*/
fun addDiscussionLabel(request: com.ecwid.upsource.rpc.projects.UpdateDiscussionLabelRequestDTO): RpcResponse<com.ecwid.upsource.rpc.projects.LabelDTO>
/**
* Adds a label to a review
*/
fun addReviewLabel(request: com.ecwid.upsource.rpc.projects.UpdateReviewLabelRequestDTO): RpcResponse<com.ecwid.upsource.rpc.projects.UpdateReviewLabelResponseDTO>
/**
* Removes a label from a discussion
*/
fun removeDiscussionLabel(request: com.ecwid.upsource.rpc.projects.UpdateDiscussionLabelRequestDTO): RpcResponse<com.ecwid.upsource.rpc.ids.VoidMessage>
/**
* Removes a label from a review
*/
fun removeReviewLabel(request: com.ecwid.upsource.rpc.projects.UpdateReviewLabelRequestDTO): RpcResponse<com.ecwid.upsource.rpc.projects.UpdateReviewLabelResponseDTO>
/**
* Stars a discussion
*/
fun starDiscussion(request: com.ecwid.upsource.rpc.projects.UpdateDiscussionFlagRequestDTO): RpcResponse<com.ecwid.upsource.rpc.ids.VoidMessage>
/**
* Toggles the read/unread state of a discussion
*/
fun readDiscussion(request: com.ecwid.upsource.rpc.projects.UpdateDiscussionFlagRequestDTO): RpcResponse<com.ecwid.upsource.rpc.ids.VoidMessage>
/**
* Adds a comment to the discussion
*/
fun addComment(request: com.ecwid.upsource.rpc.projects.AddCommentRequestDTO): RpcResponse<com.ecwid.upsource.rpc.projects.CommentDTO>
/**
* Updates the comment
*/
fun updateComment(request: com.ecwid.upsource.rpc.projects.UpdateCommentRequestDTO): RpcResponse<com.ecwid.upsource.rpc.projects.UpdateCommentResponseDTO>
/**
* Removes the comment
*/
fun removeComment(request: com.ecwid.upsource.rpc.projects.RemoveCommentRequestDTO): RpcResponse<com.ecwid.upsource.rpc.projects.RemoveCommentResponseDTO>
/**
* Updates the task list embedded in a comment
*/
fun updateTaskList(request: com.ecwid.upsource.rpc.projects.UpdateTaskListRequestDTO): RpcResponse<com.ecwid.upsource.rpc.projects.UpdateCommentResponseDTO>
/**
* Adds or removes a reaction to a specified target
*/
fun toggleReaction(request: com.ecwid.upsource.rpc.projects.ToggleReactionRequestDTO): RpcResponse<com.ecwid.upsource.rpc.ids.VoidMessage>
/**
* Returns the news feed
*/
fun getFeed(request: com.ecwid.upsource.rpc.projects.FeedRequestDTO): RpcResponse<com.ecwid.upsource.rpc.projects.FeedDTO>
/**
* Returns the discussions in the given revision
*/
fun getRevisionDiscussions(request: com.ecwid.upsource.rpc.ids.RevisionInProjectDTO): RpcResponse<com.ecwid.upsource.rpc.projects.DiscussionsInRevisionDTO>
/**
* Returns short review information for a set of revisions
*/
fun getRevisionReviewInfo(request: com.ecwid.upsource.rpc.projects.RevisionListDTO): RpcResponse<com.ecwid.upsource.rpc.projects.RevisionReviewInfoListDTO>
/**
* Returns review suggestions for a set of revisions
*/
fun getSuggestedReviewsForRevisions(request: com.ecwid.upsource.rpc.projects.RevisionListDTO): RpcResponse<com.ecwid.upsource.rpc.projects.SuggestedReviewListDTO>
/**
* Returns review suggestion for the uncommitted revision
*/
fun getSuggestedReviewForGhosts(request: com.ecwid.upsource.rpc.projects.UncommittedRevisionDTO): RpcResponse<com.ecwid.upsource.rpc.projects.ReviewSuggestDTO>
/**
* Returns discussion counters for a set of revisions
*/
fun getRevisionDiscussionCounters(request: com.ecwid.upsource.rpc.projects.RevisionDiscussionCountersRequestDTO): RpcResponse<com.ecwid.upsource.rpc.projects.RevisionDiscussionCountersListDTO>
/**
* Returns build status for revisions
*/
fun getRevisionBuildStatus(request: com.ecwid.upsource.rpc.projects.RevisionListDTO): RpcResponse<com.ecwid.upsource.rpc.projects.RevisionBuildStatusListDTO>
/**
* Returns the code ownership summary for given revisions
*/
fun getRevisionsOwnershipSummary(request: com.ecwid.upsource.rpc.projects.RevisionListDTO): RpcResponse<com.ecwid.upsource.rpc.projects.RevisionsOwnershipSummaryDTO>
/**
* Returns the diff of external inspections compared to the previous run
*/
fun getRevisionsExternalInspectionsDiff(request: com.ecwid.upsource.rpc.projects.RevisionListDTO): RpcResponse<com.ecwid.upsource.rpc.projects.RevisionsExternalInspectionsDiffResponseDTO>
/**
* Returns the suggested users to be mentioned in a comment
*/
fun getUsersForMention(request: com.ecwid.upsource.rpc.users.UsersForMentionRequestDTO): RpcResponse<com.ecwid.upsource.rpc.users.UsersListDTO>
/**
* Returns the suggested reviewers for a given review
*/
fun getUsersForReview(request: com.ecwid.upsource.rpc.users.UsersForReviewRequestDTO): RpcResponse<com.ecwid.upsource.rpc.users.UsersForReviewDTO>
/**
* Returns the list of non-empty user groups relevant to a given project
*/
fun getProjectUserGroups(request: com.ecwid.upsource.rpc.users.ProjectUserGroupsRequestDTO): RpcResponse<com.ecwid.upsource.rpc.users.UserGroupsListDTO>
/**
* Returns the list of user groups by given IDs
*/
fun getUserGroupsByIds(request: com.ecwid.upsource.rpc.users.UserGroupsIdsListDTO): RpcResponse<com.ecwid.upsource.rpc.users.UserGroupsListDTO>
/**
* Returns the list of users matching a given search criteria
*/
fun findUsers(request: com.ecwid.upsource.rpc.users.FindUsersRequestDTO): RpcResponse<com.ecwid.upsource.rpc.users.UserInfoResponseDTO>
/**
* Returns the list of discussion labels
*/
fun getLabels(request: com.ecwid.upsource.rpc.projects.LabelsRequestDTO): RpcResponse<com.ecwid.upsource.rpc.projects.LabelsListDTO>
/**
* Returns the list of review labels
*/
fun getReviewLabels(request: com.ecwid.upsource.rpc.projects.LabelsRequestDTO): RpcResponse<com.ecwid.upsource.rpc.projects.LabelsListDTO>
/**
* Returns the list of reviews
*/
fun getReviews(request: com.ecwid.upsource.rpc.projects.ReviewsRequestDTO): RpcResponse<com.ecwid.upsource.rpc.projects.ReviewListDTO>
/**
* Creates a review
*/
fun createReview(request: com.ecwid.upsource.rpc.projects.CreateReviewRequestDTO): RpcResponse<com.ecwid.upsource.rpc.projects.ReviewDescriptorDTO>
/**
* Closes a review
*/
fun closeReview(request: com.ecwid.upsource.rpc.projects.CloseReviewRequestDTO): RpcResponse<com.ecwid.upsource.rpc.projects.CloseReviewResponseDTO>
/**
* Renames a review
*/
fun renameReview(request: com.ecwid.upsource.rpc.projects.RenameReviewRequestDTO): RpcResponse<com.ecwid.upsource.rpc.projects.RenameReviewResponseDTO>
/**
* Sets review description
*/
fun editReviewDescription(request: com.ecwid.upsource.rpc.projects.EditReviewDescriptionRequestDTO): RpcResponse<com.ecwid.upsource.rpc.projects.EditReviewDescriptionResponseDTO>
/**
* Returns review details
*/
fun getReviewDetails(request: com.ecwid.upsource.rpc.ids.ReviewIdDTO): RpcResponse<com.ecwid.upsource.rpc.projects.ReviewDescriptorDTO>
/**
* Returns the code ownership summary for a given review
*/
fun getReviewOwnershipSummary(request: com.ecwid.upsource.rpc.ids.ReviewIdDTO): RpcResponse<com.ecwid.upsource.rpc.projects.ReviewOwnershipSummaryDTO>
/**
* Returns participants' progress in a given review
*/
fun getReviewProgress(request: com.ecwid.upsource.rpc.ids.ReviewIdDTO): RpcResponse<com.ecwid.upsource.rpc.projects.ReviewProgressDTO>
/**
* Returns the diff of inspections between two revisions
*/
fun getReviewInspectionsDiff(request: com.ecwid.upsource.rpc.projects.ReviewInspectionsDiffRequestDTO): RpcResponse<com.ecwid.upsource.rpc.fileordirectorycontent.InspectionsDiffDTO>
/**
* Attaches a revision to a review
*/
fun addRevisionToReview(request: com.ecwid.upsource.rpc.projects.RevisionsInReviewDTO): RpcResponse<com.ecwid.upsource.rpc.ids.VoidMessage>
/**
* Initiates branch tracking for a given review
*/
fun startBranchTracking(request: com.ecwid.upsource.rpc.projects.StartBranchTrackingRequestDTO): RpcResponse<com.ecwid.upsource.rpc.ids.VoidMessage>
/**
* Stops branch tracking for a given review
*/
fun stopBranchTracking(request: com.ecwid.upsource.rpc.projects.StopBranchTrackingRequestDTO): RpcResponse<com.ecwid.upsource.rpc.ids.VoidMessage>
/**
* Rebase the review to a single squashed revision
*/
fun squashReviewRevisions(request: com.ecwid.upsource.rpc.ids.ReviewIdDTO): RpcResponse<com.ecwid.upsource.rpc.ids.VoidMessage>
/**
* Removes a revision from a review
*/
fun removeRevisionFromReview(request: com.ecwid.upsource.rpc.projects.RevisionsInReviewDTO): RpcResponse<com.ecwid.upsource.rpc.ids.VoidMessage>
/**
* Returns the list of revisions in a review
*/
fun getRevisionsInReview(request: com.ecwid.upsource.rpc.ids.ReviewIdDTO): RpcResponse<com.ecwid.upsource.rpc.projects.RevisionsInReviewResponseDTO>
/**
* Returns the list of suggested revisions for a particular review
*/
fun getSuggestedRevisionsForReview(request: com.ecwid.upsource.rpc.ids.ReviewIdDTO): RpcResponse<com.ecwid.upsource.rpc.projects.SuggestedRevisionListDTO>
/**
* Adds a participant (reviewer or watcher) to a review
*/
fun addParticipantToReview(request: com.ecwid.upsource.rpc.projects.ParticipantInReviewRequestDTO): RpcResponse<com.ecwid.upsource.rpc.ids.VoidMessage>
/**
* Adds a group of participants (reviewers or watchers) to a review
*/
fun addGroupToReview(request: com.ecwid.upsource.rpc.projects.AddGroupToReviewRequestDTO): RpcResponse<com.ecwid.upsource.rpc.projects.AddGroupToReviewResponseDTO>
/**
* Updates the participant's state
*/
fun updateParticipantInReview(request: com.ecwid.upsource.rpc.projects.UpdateParticipantInReviewRequestDTO): RpcResponse<com.ecwid.upsource.rpc.projects.UpdateParticipantInReviewResponseDTO>
/**
* Removes a participant from a review
*/
fun removeParticipantFromReview(request: com.ecwid.upsource.rpc.projects.ParticipantInReviewRequestDTO): RpcResponse<com.ecwid.upsource.rpc.ids.VoidMessage>
/**
* Mutes activities taking place in a certain review or cancels muting that was previously set
*/
fun toggleReviewMuted(request: com.ecwid.upsource.rpc.projects.ToggleReviewMutedRequestDTO): RpcResponse<com.ecwid.upsource.rpc.ids.VoidMessage>
/**
* Sets/clears review due date
*/
fun setReviewDeadline(request: com.ecwid.upsource.rpc.projects.ReviewDeadlineRequestDTO): RpcResponse<com.ecwid.upsource.rpc.ids.VoidMessage>
/**
* Merge review: sets target branch
*/
fun setReviewTargetBranch(request: com.ecwid.upsource.rpc.projects.ReviewTargetBranchDTO): RpcResponse<com.ecwid.upsource.rpc.projects.SetReviewTargetBranchResponseDTO>
/**
* Returns the list of changes (sum of all revisions) in a review
*/
fun getReviewSummaryChanges(request: com.ecwid.upsource.rpc.projects.ReviewSummaryChangesRequestDTO): RpcResponse<com.ecwid.upsource.rpc.projects.ReviewSummaryChangesResponseDTO>
/**
* Returns the diff (sum of all revisions) of a file in review
*/
fun getFileInReviewSummaryInlineChanges(request: com.ecwid.upsource.rpc.projects.FileInReviewDiffRequestDTO): RpcResponse<com.ecwid.upsource.rpc.projects.FileInlineDiffResponseDTO>
/**
* Returns the diff (sum of all revisions) of a file in review
*/
fun getFileInReviewSummaryDiff(request: com.ecwid.upsource.rpc.projects.FileInReviewDiffRequestDTO): RpcResponse<com.ecwid.upsource.rpc.projects.FileDiffResponseDTO>
/**
* Track file read status
*/
fun setFileInReviewReadStatus(request: com.ecwid.upsource.rpc.projects.FileInReviewReadStatusRequestDTO): RpcResponse<com.ecwid.upsource.rpc.ids.VoidMessage>
/**
* Returns the review discussions
*/
fun getReviewSummaryDiscussions(request: com.ecwid.upsource.rpc.projects.ReviewSummaryDiscussionsRequestDTO): RpcResponse<com.ecwid.upsource.rpc.projects.DiscussionsInFilesDTO>
/**
* Removes the review
*/
fun removeReview(request: com.ecwid.upsource.rpc.ids.ReviewIdDTO): RpcResponse<com.ecwid.upsource.rpc.ids.VoidMessage>
/**
* Returns matching revisions for stacktrace
*/
fun getMatchingRevisionsForStacktrace(request: com.ecwid.upsource.rpc.projects.StacktraceDTO): RpcResponse<com.ecwid.upsource.rpc.projects.MatchingRevisionsResponseDTO>
/**
* Returns full paths and vcs commit ids for lines of stacktrace in context of revision
*/
fun getStacktraceInContextOfRevision(request: com.ecwid.upsource.rpc.projects.StacktraceDTO): RpcResponse<com.ecwid.upsource.rpc.projects.StacktracePositionsDTO>
/**
* Returns the user info for a currently logged-in user
*/
fun getCurrentUser(request: com.ecwid.upsource.rpc.ids.VoidMessage): RpcResponse<com.ecwid.upsource.rpc.users.CurrentUserResponseDTO>
/**
* Checks if current user can close given review
*/
fun getCurrentUserCanCloseReview(request: com.ecwid.upsource.rpc.ids.ReviewIdDTO): RpcResponse<com.ecwid.upsource.rpc.ids.VoidMessage>
/**
* Checks if current user can delete given review
*/
fun getCurrentUserCanDeleteReview(request: com.ecwid.upsource.rpc.ids.ReviewIdDTO): RpcResponse<com.ecwid.upsource.rpc.ids.VoidMessage>
/**
* Returns user info for given users
*/
fun getUserInfo(request: com.ecwid.upsource.rpc.users.UserInfoRequestDTO): RpcResponse<com.ecwid.upsource.rpc.users.UserInfoResponseDTO>
/**
* Returns presence info for given users
*/
fun getUsersPresenceInfo(request: com.ecwid.upsource.rpc.users.UserInfoRequestDTO): RpcResponse<com.ecwid.upsource.rpc.users.UsersPresenceInfoResponseDTO>
/**
* Maps a VCS username/email to a Hub account
*/
fun bindVcsUsername(request: com.ecwid.upsource.rpc.users.BindVcsUsernameRequestDTO): RpcResponse<com.ecwid.upsource.rpc.ids.VoidMessage>
/**
* Returns the list of projects the specified user contributed to
*/
fun getUserProjects(request: com.ecwid.upsource.rpc.users.UserProjectsRequestDTO): RpcResponse<com.ecwid.upsource.rpc.users.UserProjectsResponseDTO>
/**
* Sets or clears a user absence
*/
fun setUserAbsence(request: com.ecwid.upsource.rpc.users.UserAbsenceRequestDTO): RpcResponse<com.ecwid.upsource.rpc.ids.VoidMessage>
/**
* Returns the value of a user setting by name
*/
fun getUserSetting(request: com.ecwid.upsource.rpc.misc.GetSettingRequestDTO): RpcResponse<com.ecwid.upsource.rpc.misc.GetSettingResponseDTO>
/**
* Updates the value of a user setting by name
*/
fun setUserSetting(request: com.ecwid.upsource.rpc.misc.SetSettingRequestDTO): RpcResponse<com.ecwid.upsource.rpc.ids.VoidMessage>
/**
* Returns the value of a cluster-wide setting by name
*/
fun getClusterSetting(request: com.ecwid.upsource.rpc.misc.GetSettingRequestDTO): RpcResponse<com.ecwid.upsource.rpc.misc.GetSettingResponseDTO>
/**
* Updates the value of a cluster-wide setting by name
*/
fun setClusterSetting(request: com.ecwid.upsource.rpc.misc.SetSettingRequestDTO): RpcResponse<com.ecwid.upsource.rpc.ids.VoidMessage>
/**
* Sets the server motto
*/
fun setMotto(request: com.ecwid.upsource.rpc.misc.SetMottoRequestDTO): RpcResponse<com.ecwid.upsource.rpc.ids.VoidMessage>
/**
* Returns the value of a project setting by name
*/
fun getProjectSetting(request: com.ecwid.upsource.rpc.misc.GetProjectSettingRequestDTO): RpcResponse<com.ecwid.upsource.rpc.misc.GetSettingResponseDTO>
/**
* Updates the value of a project setting by name
*/
fun setProjectSetting(request: com.ecwid.upsource.rpc.misc.SetProjectSettingRequestDTO): RpcResponse<com.ecwid.upsource.rpc.ids.VoidMessage>
/**
* Updates the set of webhooks in a project
*/
fun setProjectWebhooks(request: com.ecwid.upsource.rpc.misc.SetProjectWebhooksRequestDTO): RpcResponse<com.ecwid.upsource.rpc.ids.VoidMessage>
/**
* Creates a project
*/
fun createProject(request: com.ecwid.upsource.rpc.projects.CreateProjectRequestDTO): RpcResponse<com.ecwid.upsource.rpc.ids.VoidMessage>
/**
* Loads project settings
*/
fun loadProject(request: com.ecwid.upsource.rpc.ids.ProjectIdDTO): RpcResponse<com.ecwid.upsource.rpc.projects.ProjectSettingsDTO>
/**
* Updates project settings
*/
fun editProject(request: com.ecwid.upsource.rpc.projects.EditProjectRequestDTO): RpcResponse<com.ecwid.upsource.rpc.ids.VoidMessage>
/**
* Deletes a project
*/
fun deleteProject(request: com.ecwid.upsource.rpc.ids.ProjectIdDTO): RpcResponse<com.ecwid.upsource.rpc.ids.VoidMessage>
/**
* Completely reset a project
*/
fun resetProject(request: com.ecwid.upsource.rpc.ids.ProjectIdDTO): RpcResponse<com.ecwid.upsource.rpc.ids.VoidMessage>
/**
* Loads project settings
*/
fun getProjectConfigurationParameters(request: com.ecwid.upsource.rpc.ids.VoidMessage): RpcResponse<com.ecwid.upsource.rpc.projects.ProjectConfigurationResponseDTO>
/**
* Loads VCS Hosting services
*/
fun getVcsHostingServices(request: com.ecwid.upsource.rpc.projects.VcsHostingRequestDTO): RpcResponse<com.ecwid.upsource.rpc.projects.VcsHostingResponseDTO>
/**
* Creates/updates a discussion label in a project
*/
fun createOrEditLabel(request: com.ecwid.upsource.rpc.projects.EditLabelRequestDTO): RpcResponse<com.ecwid.upsource.rpc.projects.LabelDTO>
/**
* Creates/updates a review label in a project
*/
fun createOrEditReviewLabel(request: com.ecwid.upsource.rpc.projects.EditLabelRequestDTO): RpcResponse<com.ecwid.upsource.rpc.projects.LabelDTO>
/**
* Hides predefined discussion labels in a project
*/
fun hidePredefinedLabels(request: com.ecwid.upsource.rpc.projects.HidePredefinedLabelsRequestDTO): RpcResponse<com.ecwid.upsource.rpc.ids.VoidMessage>
/**
* Hides predefined review labels in a project
*/
fun hidePredefinedReviewLabels(request: com.ecwid.upsource.rpc.projects.HidePredefinedLabelsRequestDTO): RpcResponse<com.ecwid.upsource.rpc.ids.VoidMessage>
/**
* Deletes a discussion label from a project
*/
fun deleteLabel(request: com.ecwid.upsource.rpc.projects.EditLabelRequestDTO): RpcResponse<com.ecwid.upsource.rpc.ids.VoidMessage>
/**
* Deletes a review label from a project
*/
fun deleteReviewLabel(request: com.ecwid.upsource.rpc.projects.EditLabelRequestDTO): RpcResponse<com.ecwid.upsource.rpc.ids.VoidMessage>
/**
* Merges two or more discussion labels into one
*/
fun mergeLabels(request: com.ecwid.upsource.rpc.projects.EditLabelsRequestDTO): RpcResponse<com.ecwid.upsource.rpc.projects.LabelDTO>
/**
* Checks connection to a given VCS repository
*/
fun testVcsConnection(request: com.ecwid.upsource.rpc.projects.TestConnectionRequestDTO): RpcResponse<com.ecwid.upsource.rpc.projects.TestConnectionResponseDTO>
/**
* Checks availability of a given POP3 mailbox
*/
fun testPOP3Mailbox(request: com.ecwid.upsource.rpc.misc.TestPOP3MailboxRequestDTO): RpcResponse<com.ecwid.upsource.rpc.misc.TestPOP3MailboxResponseDTO>
/**
* Checks if server is in read-only mode
*/
fun getReadOnlyMode(request: com.ecwid.upsource.rpc.ids.VoidMessage): RpcResponse<com.ecwid.upsource.rpc.misc.ReadOnlyModeDTO>
/**
* Enables/disables the read-only mode
*/
fun setReadOnlyMode(request: com.ecwid.upsource.rpc.misc.ReadOnlyModeDTO): RpcResponse<com.ecwid.upsource.rpc.ids.VoidMessage>
fun getEmailBounces(request: com.ecwid.upsource.rpc.ids.VoidMessage): RpcResponse<com.ecwid.upsource.rpc.misc.EmailBouncesResponseDTO>
fun resetEmailBounces(request: com.ecwid.upsource.rpc.ids.VoidMessage): RpcResponse<com.ecwid.upsource.rpc.ids.VoidMessage>
/**
* Returns all roles available in Hub
*/
fun getAllRoles(request: com.ecwid.upsource.rpc.ids.VoidMessage): RpcResponse<com.ecwid.upsource.rpc.projects.AllRolesResponseDTO>
/**
* Returns users that have any access to the project and role keys associated with each user
*/
fun getUsersRoles(request: com.ecwid.upsource.rpc.projects.UsersRolesRequestDTO): RpcResponse<com.ecwid.upsource.rpc.projects.UsersRolesResponseDTO>
/**
* Adds a user role
*/
fun addUserRole(request: com.ecwid.upsource.rpc.projects.AddRoleRequestDTO): RpcResponse<com.ecwid.upsource.rpc.ids.VoidMessage>
/**
* Deletes a user role (not the role itself, but the association)
*/
fun deleteUserRole(request: com.ecwid.upsource.rpc.projects.DeleteRoleRequestDTO): RpcResponse<com.ecwid.upsource.rpc.ids.VoidMessage>
/**
* Searches for user in Hub by an email, and sends an invitation if not found
*/
fun inviteUser(request: com.ecwid.upsource.rpc.projects.InviteUserRequestDTO): RpcResponse<com.ecwid.upsource.rpc.projects.InviteUserResponseDTO>
/**
* Exports user-generated data - reviews, discussions, settings
*/
fun exportData(request: com.ecwid.upsource.rpc.ids.VoidMessage): RpcResponse<com.ecwid.upsource.rpc.misc.ExportDataResponseDTO>
/**
* Returns project activity distribution over time, i.e. the number of commits per time period
*/
fun getProjectActivity(request: com.ecwid.upsource.rpc.analytics.ProjectActivityRequestDTO): RpcResponse<com.ecwid.upsource.rpc.analytics.ProjectActivityDTO>
/**
* Returns contributors distribution over time, i.e. the number of commits per time period per committer
*/
fun getContributorsDistribution(request: com.ecwid.upsource.rpc.analytics.ContributorsDistributionRequestDTO): RpcResponse<com.ecwid.upsource.rpc.analytics.ContributorsDistributionDTO>
/**
* Returns commits distribution in a given date range over all committers and modules
*/
fun getResponsibilityDistribution(request: com.ecwid.upsource.rpc.analytics.ResponsibilityDistributionRequestDTO): RpcResponse<com.ecwid.upsource.rpc.analytics.ResponsibilityDistributionDTO>
/**
* Returns all committers throughout the project history
*/
fun getProjectCommitters(request: com.ecwid.upsource.rpc.ids.ProjectIdDTO): RpcResponse<com.ecwid.upsource.rpc.analytics.ProjectCommittersDTO>
/**
* Returns project activity distribution over time, i.e. the number of commits per time period for a specified set of committers
*/
fun getUserActivity(request: com.ecwid.upsource.rpc.analytics.UserActivityRequestDTO): RpcResponse<com.ecwid.upsource.rpc.analytics.UserActivityDTO>
/**
* Returns per-module activity distribution in the project
*/
fun getModulesDistribution(request: com.ecwid.upsource.rpc.analytics.ModulesDistributionRequestDTO): RpcResponse<com.ecwid.upsource.rpc.analytics.ModulesDistributionDTO>
/**
* Returns the summary for the specified date range and set of committers: total number of commits, number of commits that aren't part of any module, total number of modules changed
*/
fun getCommitsSummary(request: com.ecwid.upsource.rpc.analytics.CommitsSummaryRequestDTO): RpcResponse<com.ecwid.upsource.rpc.analytics.CommitsSummaryDTO>
/**
* Returns the revisions in the specified module, in the specified date range and for the specified committers
*/
fun getCommitsDetails(request: com.ecwid.upsource.rpc.analytics.CommitsDetailsRequestDTO): RpcResponse<com.ecwid.upsource.rpc.analytics.CommitsDetailsDTO>
/**
* Returns the data required to display an animated chart of distribution of individual files in project across "edits - age" plane
*/
fun getFileHistoryChart(request: com.ecwid.upsource.rpc.analytics.FileHistoryChartRequestDTO): RpcResponse<com.ecwid.upsource.rpc.analytics.FileHistoryChartDTO>
/**
* Returns the list of files in a project and their content sizes required to build the interactive treemap chart
*/
fun getProjectTreeMap(request: com.ecwid.upsource.rpc.analytics.ProjectTreeMapRequestDTO): RpcResponse<com.ecwid.upsource.rpc.analytics.ProjectTreeMapDTO>
/**
* Returns the activity pulse for a specified project
*/
fun getProjectPulse(request: com.ecwid.upsource.rpc.analytics.ProjectPulseRequestDTO): RpcResponse<com.ecwid.upsource.rpc.analytics.PulseResponseDTO>
/**
* Returns the activity pulse of a given user across all projects (`allValues` time series is always empty)
*/
fun getUserPulse(request: com.ecwid.upsource.rpc.analytics.UserPulseRequestDTO): RpcResponse<com.ecwid.upsource.rpc.analytics.PulseResponseDTO>
/**
* Returns the general review statistics in the project
*/
fun getReviewStatistics(request: com.ecwid.upsource.rpc.analytics.ReviewStatisticsRequestDTO): RpcResponse<com.ecwid.upsource.rpc.analytics.ReviewStatisticsDTO>
/**
* Returns the number of revisions covered by reviews in the project
*/
fun getReviewCoverage(request: com.ecwid.upsource.rpc.analytics.ReviewCoverageRequestDTO): RpcResponse<com.ecwid.upsource.rpc.analytics.ReviewCoverageDTO>
/**
* Returns the time distribution of reviews and review iterations
*/
fun getReviewTimeStatistics(request: com.ecwid.upsource.rpc.analytics.ReviewTimeStatisticsRequestDTO): RpcResponse<com.ecwid.upsource.rpc.analytics.ReviewTimeStatisticsDTO>
/**
* Returns review activity graph for the project
*/
fun getReviewersGraph(request: com.ecwid.upsource.rpc.analytics.ReviewersGraphRequestDTO): RpcResponse<com.ecwid.upsource.rpc.analytics.ReviewersGraphDTO>
/**
* Updates user timezone
*/
fun updateUserTimezone(request: com.ecwid.upsource.rpc.misc.UpdateUserTimezoneDTO): RpcResponse<com.ecwid.upsource.rpc.ids.VoidMessage>
/**
* Updates the time when the user last saw the list of his/her achievements
*/
fun updateAchievementsLastSeen(request: com.ecwid.upsource.rpc.misc.UserActionNotificationDTO): RpcResponse<com.ecwid.upsource.rpc.ids.VoidMessage>
/**
* Returns the list of achievements the user has unlocked
*/
fun getUnlockedUserAchievements(request: com.ecwid.upsource.rpc.misc.UserAchievementsRequestDTO): RpcResponse<com.ecwid.upsource.rpc.misc.AchievementsListDTO>
/**
* Returns a count of unread achievements the user has unlocked
*/
fun getUnreadUnlockedUserAchievementsCount(request: com.ecwid.upsource.rpc.ids.VoidMessage): RpcResponse<com.ecwid.upsource.rpc.misc.UserAchievementsCountDTO>
/**
* Returns the list of all achievements with information about whether the achievement was unlocked by the user or not
*/
fun getUserAchievements(request: com.ecwid.upsource.rpc.misc.UserAchievementsRequestDTO): RpcResponse<com.ecwid.upsource.rpc.misc.AchievementsListDTO>
/**
* Returns the list of available issue trackers
*/
fun getAvailableIssueTrackerProviders(request: com.ecwid.upsource.rpc.ids.VoidMessage): RpcResponse<com.ecwid.upsource.rpc.issuetrackers.IssueTrackerProvidersListDTO>
/**
* Returns detailed issue information
*/
fun getIssueInfo(request: com.ecwid.upsource.rpc.issuetrackers.IssueInfoRequestDTO): RpcResponse<com.ecwid.upsource.rpc.issuetrackers.IssueInfoDTO>
/**
* Creates an issue from the discussion in a given issue tracker
*/
fun createIssueFromDiscussion(request: com.ecwid.upsource.rpc.issuetrackers.CreateIssueFromDiscussionRequestDTO): RpcResponse<com.ecwid.upsource.rpc.issuetrackers.IssueIdDTO>
/**
* Creates an issue from the review in a given issue tracker
*/
fun createIssueFromReview(request: com.ecwid.upsource.rpc.issuetrackers.CreateIssueFromReviewRequestDTO): RpcResponse<com.ecwid.upsource.rpc.issuetrackers.IssueIdDTO>
companion object {
fun newBuilder(): EmptyClientBuilder<UpsourceRPC> {
return ClientBuilderImpl.newClientBuilder { transport, serializer ->
com.ecwid.upsource.rpc.impl.UpsourceRPCImpl(transport, serializer)
}
}
}
}
| 0 | Kotlin | 1 | 3 | bc93adb930157cd77b6955ed86b3b2fc7f78f6a2 | 38,747 | upsource-rpc | Apache License 2.0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.