code
stringlengths
6
1.04M
language
stringclasses
1 value
AST_depth
int64
-1
40
alphanumeric_fraction
float64
0
0.97
max_line_length
int64
0
1k
avg_line_length
float64
0
171
num_lines
int64
0
4.25k
source
stringclasses
1 value
<gh_stars>0 package com.headlessideas.http.util import com.headlessideas.http.Header import java.nio.file.Files import java.nio.file.Path val Path.contentTypeHeader: Header get() = getContentType(this) private fun getContentType(path: Path) = when (path.extension) { "html", "htm" -> html "css" -> css "csv" -> csv "png" -> png "jpg", "jpeg" -> jpeg "gif" -> gif "js" -> js "json" -> json "svg" -> svg else -> plain } fun Path.exists(): Boolean = Files.exists(this) fun Path.readable(): Boolean = Files.isReadable(this) val Path.extension: String get() = toFile().extension
kotlin
8
0.6448
64
22.185185
27
starcoderdata
<gh_stars>0 package com.rawa.notes.ui.feature.detail import com.rawa.notes.domain.Note interface DetailView { fun noteId(): Long } data class DetailViewState( val note: Note? = null )
kotlin
7
0.723077
40
15.25
12
starcoderdata
package com.enxy.domain.features.settings.model import androidx.annotation.Keep import androidx.appcompat.app.AppCompatDelegate data class AppSettings( val apiUrl: String, val darkTheme: Theme = Theme.SYSTEM, val notifyWifiChange: Boolean = true ) { val isDarkTheme: Boolean get() = when (darkTheme) { Theme.DARK -> true else -> false } companion object { fun default() = AppSettings( apiUrl = "192.168.0.10", darkTheme = Theme.SYSTEM, notifyWifiChange = true ) } @Keep enum class Theme { SYSTEM, LIGHT, DARK; companion object { fun from(darkTheme: Boolean) = when { darkTheme -> DARK else -> LIGHT } } fun getNightMode() = when (this) { SYSTEM -> AppCompatDelegate.MODE_NIGHT_FOLLOW_SYSTEM LIGHT -> AppCompatDelegate.MODE_NIGHT_NO DARK -> AppCompatDelegate.MODE_NIGHT_YES } } }
kotlin
13
0.551367
64
23.113636
44
starcoderdata
package dev.kord.rest.json.request import dev.kord.common.annotation.KordPreview import dev.kord.common.entity.* import dev.kord.common.entity.optional.Optional import dev.kord.common.entity.optional.OptionalBoolean import kotlinx.serialization.SerialName import kotlinx.serialization.Serializable import java.io.InputStream @Serializable @KordPreview data class ApplicationCommandCreateRequest( val name: String, val description: String, val options: Optional<List<ApplicationCommandOption>> = Optional.Missing(), @SerialName("default_permission") val defaultPermission: OptionalBoolean = OptionalBoolean.Missing ) @Serializable @KordPreview data class ApplicationCommandModifyRequest( val name: Optional<String> = Optional.Missing(), val description: Optional<String> = Optional.Missing(), val options: Optional<List<ApplicationCommandOption>> = Optional.Missing(), @SerialName("default_permission") val defaultPermission: OptionalBoolean = OptionalBoolean.Missing ) @Serializable @KordPreview data class InteractionResponseModifyRequest( val content: Optional<String> = Optional.Missing(), val embeds: Optional<List<EmbedRequest>> = Optional.Missing(), @SerialName("allowed_mentions") val allowedMentions: Optional<AllowedMentions> = Optional.Missing(), val flags: Optional<MessageFlags> = Optional.Missing() ) @KordPreview data class MultipartInteractionResponseModifyRequest( val request: InteractionResponseModifyRequest, val files: List<Pair<String, InputStream>> = emptyList(), ) @Serializable @KordPreview data class InteractionResponseCreateRequest( val type: InteractionResponseType, val data: Optional<InteractionApplicationCommandCallbackData> = Optional.Missing() ) @KordPreview data class MultipartInteractionResponseCreateRequest( val request: InteractionResponseCreateRequest, val files: List<Pair<String, InputStream>> = emptyList() ) @Serializable @KordPreview class InteractionApplicationCommandCallbackData( val tts: OptionalBoolean = OptionalBoolean.Missing, val content: Optional<String> = Optional.Missing(), val embeds: Optional<List<EmbedRequest>> = Optional.Missing(), @SerialName("allowed_mentions") val allowedMentions: Optional<AllowedMentions> = Optional.Missing(), val flags: Optional<MessageFlags> = Optional.Missing() ) @KordPreview data class MultipartFollowupMessageCreateRequest( val request: FollowupMessageCreateRequest, val files: List<Pair<String, InputStream>> = emptyList(), ) @Serializable @KordPreview class FollowupMessageCreateRequest( val content: Optional<String> = Optional.Missing(), val username: Optional<String> = Optional.Missing(), @SerialName("avatar_url") val avatar: Optional<String> = Optional.Missing(), val tts: OptionalBoolean = OptionalBoolean.Missing, val embeds: Optional<List<EmbedRequest>> = Optional.Missing(), val allowedMentions: Optional<AllowedMentions> = Optional.Missing() ) @Serializable @KordPreview data class FollowupMessageModifyRequest( val content: Optional<String> = Optional.Missing(), val embeds: Optional<List<EmbedRequest>> = Optional.Missing(), @SerialName("allowed_mentions") val allowedMentions: Optional<AllowedMentions> = Optional.Missing(), ) @KordPreview data class MultipartFollowupMessageModifyRequest( val request: FollowupMessageModifyRequest, val files: List<Pair<String, java.io.InputStream>> = emptyList(), ) @Serializable @KordPreview data class ApplicationCommandPermissionsEditRequest( val permissions: List<DiscordGuildApplicationCommandPermission> )
kotlin
11
0.778387
86
32.449541
109
starcoderdata
package pl.polciuta.qrscanner.utils import android.content.Context import android.util.Size import android.view.Gravity import android.widget.Toast import com.google.mlkit.vision.common.InputImage import pl.polciuta.qrscanner.card.InfoRow inline fun Boolean.alsoIfTrue(block: () -> Unit): Boolean { if (this) block() return this } inline fun Boolean.alsoIfFalse(block: () -> Unit): Boolean { if (!this) block() return this } val InputImage.size get() = Size(width, height) object Helpers { fun showToast(context: Context, message: String, gravity: Int = Gravity.CENTER, yOffset: Int = 0) { Toast.makeText(context, message, Toast.LENGTH_LONG).apply { setGravity(gravity, 0, yOffset) show() } } fun createRowList(pairList: List<Pair<String, String?>>) = pairList.mapNotNull { pair -> pair.second?.let { if (it.isNotBlank()) InfoRow(pair.first, it) else null } } }
kotlin
23
0.668041
103
24.552632
38
starcoderdata
package ko5hian import android.view.ViewGroup import android.view.ViewManager import android.widget.FrameLayout import android.widget.ViewSwitcher import kotlin.contracts.* @ExperimentalContracts inline fun <P : ViewManager, L> Ko5hian<P, *, L>.viewSwitcher( ko5hianAction: Ko5hianParentAction<ViewSwitcher, L, FrameLayout.LayoutParams> ): ViewSwitcher { contract { callsInPlace(ko5hianAction, InvocationKind.EXACTLY_ONCE) } return addView( ::ViewSwitcher, frameLayoutParamsInstantiator, ko5hianAction ) } @ExperimentalContracts inline fun <P : ViewGroup, L> Ko5hian<P, *, L>.viewSwitcher( withName: String, ko5hianAction: Ko5hianParentAction<ViewSwitcher, L, FrameLayout.LayoutParams> ) { contract { callsInPlace(ko5hianAction, InvocationKind.AT_LEAST_ONCE) } mutateView( withName, frameLayoutParamsInstantiator, ko5hianAction ) }
kotlin
15
0.733836
83
25.514286
35
starcoderdata
<filename>kotlin-html/src/genTest/kotlin/dev/scottpierce/html/element/ITest.kt package dev.scottpierce.html.element import dev.scottpierce.html.write.StringBuilderHtmlWriter import dev.scottpierce.html.write.WriteOptions import kotlin.test.Test class ITest { @Test fun writerNoCustomAttributeTest() { createWriter().apply { i(id = "test-id", classes = "test-class") } assertEquals { """ <i id="test-id" class="test-class"> </i> """.trimIndent() } } @Test fun writerVarArgAttributeTest() { createWriter().apply { i("custom-attr" to "custom-attr-value", id = "test-id", classes = "test-class") } assertEquals { """ <i id="test-id" class="test-class" custom-attr="custom-attr-value"> </i> """.trimIndent() } } @Test fun writerListAttributeTest() { createWriter().apply { i(attrs = listOf("custom-attr" to "custom-attr-value"), id = "test-id", classes = "test-class") } assertEquals { """ <i id="test-id" class="test-class" custom-attr="custom-attr-value"> </i> """.trimIndent() } } @Test fun contextNoCustomAttributeTest() { val writer = createWriter() BodyContext(writer).i(id = "test-id", classes = "test-class") writer assertEquals { """ <i id="test-id" class="test-class"> </i> """.trimIndent() } } @Test fun contextVarArgAttributeTest() { val writer = createWriter() BodyContext(writer).i("custom-attr" to "custom-attr-value", id = "test-id", classes = "test-class") writer assertEquals { """ <i id="test-id" class="test-class" custom-attr="custom-attr-value"> </i> """.trimIndent() } } @Test fun contextListAttributeTest() { val writer = createWriter() BodyContext(writer).i(attrs = listOf("custom-attr" to "custom-attr-value"), id = "test-id", classes = "test-class") writer assertEquals { """ <i id="test-id" class="test-class" custom-attr="custom-attr-value"> </i> """.trimIndent() } } private fun createWriter(): StringBuilderHtmlWriter { return StringBuilderHtmlWriter(options = WriteOptions(indent = " ")) } private infix fun StringBuilderHtmlWriter.assertEquals(expected: () -> String) { kotlin.test.assertEquals(expected(), this.toString()) } }
kotlin
21
0.546816
123
27.404255
94
starcoderdata
plugins { id("com.android.library") } group="com.github.topjohnwu.libsu" android { namespace = "com.topjohnwu.superuser" defaultConfig { consumerProguardFiles("proguard-rules.pro") } } dependencies { implementation(fileTree(mapOf("dir" to "libs", "include" to listOf("*.jar")))) api("androidx.annotation:annotation:1.3.0") javadocDeps("androidx.annotation:annotation:1.3.0") }
kotlin
23
0.680288
82
22.111111
18
starcoderdata
<reponame>piclane/FoltiaApi package com.xxuz.piclane.foltiaapi.foltia import com.xxuz.piclane.foltiaapi.dao.LiveInfoDao import com.xxuz.piclane.foltiaapi.dao.NowRecordingDao import com.xxuz.piclane.foltiaapi.dao.StationDao import com.xxuz.piclane.foltiaapi.dao.SubtitleDao import com.xxuz.piclane.foltiaapi.model.* import com.xxuz.piclane.foltiaapi.model.vo.DeleteSubtitleVideoInput import com.xxuz.piclane.foltiaapi.model.vo.LiveResult import com.xxuz.piclane.foltiaapi.model.vo.UploadSubtitleVideoInput import com.xxuz.piclane.foltiaapi.util.StreamUtil import com.xxuz.piclane.foltiaapi.util.pipeLog import com.xxuz.piclane.foltiaapi.util.readFirstLine import org.slf4j.LoggerFactory import org.springframework.beans.factory.annotation.Autowired import org.springframework.stereotype.Repository import org.springframework.transaction.PlatformTransactionManager import org.springframework.transaction.support.TransactionTemplate import java.io.BufferedInputStream import java.io.BufferedOutputStream import java.io.File import java.io.FileOutputStream import java.io.IOException import java.nio.file.Files import java.nio.file.Path import java.nio.file.StandardCopyOption import java.time.Duration import java.time.format.DateTimeFormatter import java.util.concurrent.atomic.AtomicReference import javax.annotation.PreDestroy import javax.servlet.http.Part import kotlin.streams.asSequence @Repository class FoltiaManipulation( @Autowired private val config: FoltiaConfig, @Autowired private val makeDlnaStructure: MakeDlnaStructure, @Autowired private val subtitleDao: SubtitleDao, @Autowired private val stationDao: StationDao, @Autowired private val nowRecordingDao: NowRecordingDao, @Autowired private val liveInfoDao: LiveInfoDao, @Autowired private val txMgr: PlatformTransactionManager, ) { private val logger = LoggerFactory.getLogger(FoltiaManipulation::class.java) /** * 終了 */ @PreDestroy fun shutdown() { stopLiveAll() } /** * トランスコードを開始します */ fun startTranscode() { val transcodePl = config.perlPath("ipodtranscode.pl") ProcessBuilder() .directory(config.perlToolPath) .command(transcodePl.absolutePath) .redirectError(ProcessBuilder.Redirect.DISCARD) .redirectOutput(ProcessBuilder.Redirect.DISCARD) .start() } /** ファイル名向け日付フォーマッター */ private val dtfFilename = DateTimeFormatter.ofPattern("yyyyMMdd-HHmm") /** * 放送のファイル名を生成します */ private fun buildVideoFilename(subtitle: Subtitle, videoType: VideoType): String { val station = stationDao.get(subtitle.stationId) ?: throw IllegalArgumentException("stationId ${subtitle.stationId} is invalid.") val base = "${subtitle.tId}-${subtitle.countNo}-${dtfFilename.format(subtitle.startDateTime)}-${station.digitalCh}" return when(videoType) { VideoType.TS -> "$base.m2t" VideoType.SD -> "MAQ-$base.MP4" VideoType.HD -> "MAQ-$base.MP4" } } /** * 放送の動画をアップロードします */ fun uploadSubtitleVideo(input: UploadSubtitleVideoInput, video: Part): Subtitle { val tx = TransactionTemplate(txMgr) val txStatus = txMgr.getTransaction(tx) val subtitle = subtitleDao.updateVideo(input.pId, input.videoType, this::buildVideoFilename) ?: throw IllegalArgumentException("pId ${input.pId} is invalid.") val videoPath = config.videoPath(subtitle, input.videoType) ?: throw RuntimeException("failed to build videoPath.") // ファイルコピー try { BufferedInputStream(video.inputStream).use { inputStream -> BufferedOutputStream(FileOutputStream(videoPath)).use { outputStream -> StreamUtil.pumpStream(inputStream, outputStream) } } } catch (e: Exception) { txMgr.rollback(txStatus) throw e } return subtitle } /** * 放送の動画を削除します */ fun deleteSubtitleVideo(target: DeleteSubtitleVideoInput, physical: Boolean) { val tx = TransactionTemplate(txMgr) val txStatus = txMgr.getTransaction(tx) val mitaPath = config.recFolderPath.toPath().resolve("mita") val moved = mutableListOf<VideoMovementResult>() val rollback = { moved.forEach { result -> try { Files.move(result.dst, result.src) makeDlnaStructure.process(result.src.toFile()) logger.info("[deleteSubtitleVideo] Rollback success: pId=${target.pId}, videoType=${result.videoType}, src=${result.dst}, dst=${result.src}") } catch (e: IOException) { logger.error("[deleteSubtitleVideo] Rollback failed: pId=${target.pId}, videoType=${result.videoType}, src=${result.dst}, dst=${result.src}", e) } } } // DB から動画を削除 val (oldSubtitle) = subtitleDao.deleteVideo(target.pId, target.videoTypes) ?: return // ファイルを mita に移動 target.videoTypes.forEach { videoType -> val file = config.videoPath(oldSubtitle, videoType) ?: return@forEach val src = file.toPath() val dst = mitaPath.resolve(file.name) try { Files.move(src, dst, StandardCopyOption.REPLACE_EXISTING) makeDlnaStructure.delete(file) moved.add(VideoMovementResult(src, dst, videoType)) if(!physical) { logger.info("[deleteSubtitleVideo] Moved: pId=${target.pId}, videoType=${videoType}, src=${src}, dst=${dst}") } } catch(e: IOException) { logger.error("[deleteSubtitleVideo] Failed to move file: pId=${target.pId}, videoType=${videoType}, src=${src}, dst=${dst}", e) txMgr.rollback(txStatus) rollback() throw DeleteVideoFailedException(target.pId, videoType, file, e) } } // トランザクションをコミット txMgr.commit(txStatus) // ファイルを物理削除 if(physical) { val itr = moved.iterator() while (itr.hasNext()) { val result = itr.next() try { Files.deleteIfExists(result.dst) itr.remove() logger.info("[deleteSubtitleVideo] Deleted: pId=${target.pId}, videoType=${result.videoType}, path=${result.src}") } catch (e: IOException) { logger.error("[deleteSubtitleVideo] Failed to delete file: pId=${target.pId}, videoType=${result.videoType}, path=${result.dst}", e) rollback() throw DeleteVideoFailedException(target.pId, result.videoType, result.src.toFile(), e) } } } } /** * 動画ファイル移動実績 */ private data class VideoMovementResult( /** 移動元 */ val src: Path, /** 移動先 */ val dst: Path, /** 動画種別 */ val videoType: VideoType, ) /** * dropInfo を取得します */ fun loadDropInfo(subtitle: Subtitle): DropInfoSummary? { val dropInfoFile = config.dropInfoPath(subtitle) ?: return null if(!dropInfoFile.exists()) { return null } val details = mutableListOf<DropInfoDetail>() dropInfoFile.bufferedReader().use { reader -> for(line in reader.lineSequence()) { val m = regexDropInfo.matchEntire(line) if(m != null) { details.add(DropInfoDetail( pid = m.groupValues[1].toInt(16), total = m.groupValues[2].toLong(), drop = m.groupValues[3].toLong(), scrambling = m.groupValues[4].toLong(), )) } } } return DropInfoSummary(details) } /** * 指定されたチャンネルのライブを開始します * * @param stationId チャンネルID * @param liveQuality ライブ品質 */ fun startLive(stationId: Long, liveQuality: LiveQuality): LiveResult { val station = stationDao.get(stationId) if(station == null || station.digitalStationBand == Station.DigitalStationBand.RADIO || station.digitalStationBand == Station.DigitalStationBand.UNDEFINED) { throw IllegalArgumentException("The specified station does not support live broadcasting. stationId=$stationId") } // 既に m3u8 ファイルが存在する場合はそちらを優先 var liveId = "${stationId}_${liveQuality.qualityName}" var preferredBufferTime = config.liveBufferTime.toLong() Files.list(config.livePath.toPath()) .asSequence() .map { it.fileName.toString() } .any { it == "$liveId.m3u8" } .also { existsM3u8 -> if(existsM3u8) { return LiveResult( liveId, m3u8Uri = config.httpMediaMapPath.resolve("live/$liveId.m3u8"), preferredBufferTime = (preferredBufferTime - getLiveDuration(liveId).toSeconds()) .coerceAtLeast(0L) .let { Duration.ofSeconds(it) } ) } } // 指定されたチャンネルが録画中の場合は、録画中の TS から再生させる val nowRecording = nowRecordingDao.getByStation(stationId) val videoSrc = if(nowRecording == null) { stationId.toString() } else { val m2pFilename = m2pToLiveFilename(nowRecording.recFilename) liveId = "${m2pFilename.substringBeforeLast(".")}_${liveQuality.qualityName}" preferredBufferTime = config.chasingPlaybackBufferTime.toLong() m2pFilename } // ライブプロセスを起動する logger.info("[startLive][$liveId] Starting live stream.") ProcessBuilder() .command( config.perlPath("live_process_starter.pl").absolutePath, liveQuality.code.toString(), "/tv/live", videoSrc ) .redirectInput(ProcessBuilder.Redirect.PIPE) .redirectError(ProcessBuilder.Redirect.PIPE) .directory(config.perlToolPath) .start() .pipeLog("[startLive][$liveId]", logger) .waitFor() .also { if(it != 0) { val message = "live_process_starter.pl terminated with exit code $it." logger.error("[ ][startLive][$liveId] $message") throw RuntimeException(message) } } logger.info("[startLive][$liveId] Started live stream.") return LiveResult( liveId, m3u8Uri = config.httpMediaMapPath.resolve("live/$liveId.m3u8"), preferredBufferTime = Duration.ofSeconds(preferredBufferTime) ) } /** * ライブのバッファされている秒数を取得します * * @param liveId ライブID */ fun getLiveDuration(liveId: String): Duration { val m3u8File = File(config.livePath, "$liveId.m3u8") if(!m3u8File.isFile) { return Duration.ZERO } val firstLine = AtomicReference("") val exitCode = ProcessBuilder() .command( "ffprobe", "-i", m3u8File.absolutePath, "-select_streams", "v:0", "-show_entries", "format=start_time", "-v", "quiet", "-of", "csv=p=0" ) .redirectInput(ProcessBuilder.Redirect.PIPE) .redirectError(ProcessBuilder.Redirect.DISCARD) .start() .readFirstLine(firstLine) .waitFor() if(exitCode != 0) { return Duration.ZERO } return try { Duration.ofSeconds(firstLine.get().toDouble().toLong()) } catch (_: java.lang.NumberFormatException) { Duration.ZERO } } // Files.list(config.livePath.toPath()) // .asSequence() // .map { it.fileName.toString() } // .filter { it.startsWith(liveId) && it.endsWith(".ts") } // .count() // .let { Duration.ofSeconds(it * 10L) } /** * ライブを停止します * * @param liveId ライブID */ fun stopLive(liveId: String) { val m3u8File = File(config.livePath, "$liveId.m3u8") if(!m3u8File.isFile) { return } logger.info("[stopLive][$liveId] Stopping live stream.") ProcessBuilder() .command( config.perlPath("live_stop.pl").absolutePath, liveId, ) .redirectInput(ProcessBuilder.Redirect.PIPE) .redirectError(ProcessBuilder.Redirect.PIPE) .directory(config.perlToolPath) .start() .pipeLog("[stopLive][$liveId]", logger) .waitFor() .also { if(it != 0) { val message = "live_stop.pl terminated with exit code $it." logger.error(message) throw RuntimeException(message) } } logger.info("[stopLive][$liveId] Stopped live stream.") } /** * 全てのライブを停止します */ fun stopLiveAll() = liveInfoDao.findLiveIds().also { logger.info("[stopAllLive] ${it.size} live stream(s) will be stopped.") it.forEach { liveInfo -> stopLive(liveInfo) } logger.info("[stopAllLive] ${it.size} live stream(s) has been stopped.") } companion object { private val regexDropInfo = Regex("""^pid=\s*0x([0-9a-f]+),\s*total=\s*(\d+),\s*drop=\s*(\d+),\s*scrambling=\s*(\d+)$""", RegexOption.IGNORE_CASE) private val regexM2pToLive = Regex("""^-1-""") /** * "-1-" で始まるファイル名を "A-" に変換する (実際には "a-" に変換される) */ private fun m2pToLiveFilename(filename: String) = regexM2pToLive.replace(filename, "a-") } }
kotlin
31
0.57761
166
34.35396
404
starcoderdata
<filename>docs/build.gradle.kts<gh_stars>0 plugins { id("com.eden.orchidPlugin") version "0.21.1" `copper-leaf-base` `copper-leaf-version` `copper-leaf-lint` } repositories { jcenter() } dependencies { orchidRuntimeOnly("io.github.javaeden.orchid:OrchidDocs:0.21.1") orchidRuntimeOnly("io.github.javaeden.orchid:OrchidCopper:0.21.1") orchidRuntimeOnly("io.github.javaeden.orchid:OrchidGithub:0.21.1") orchidRuntimeOnly("io.github.javaeden.orchid:OrchidKotlindoc:0.21.1") orchidRuntimeOnly("io.github.javaeden.orchid:OrchidPluginDocs:0.21.1") orchidRuntimeOnly("io.github.javaeden.orchid:OrchidSnippets:0.21.1") } // Orchid setup // --------------------------------------------------------------------------------------------------------------------- val publishConfiguration: PublishConfiguration = Config.publishConfiguration(project) orchid { githubToken = publishConfiguration.githubToken version = Config.projectVersion(project).documentationVersion } val build by tasks val check by tasks val orchidServe by tasks val orchidBuild by tasks val orchidDeploy by tasks orchidBuild.mustRunAfter(check) build.dependsOn(orchidBuild) val copyExampleComposeWebSources by tasks.registering(Copy::class) { from(project.rootDir.resolve("examples/compose-web/build/distributions")) into(project.projectDir.resolve("src/orchid/resources/assets/example/distributions")) } orchidServe.dependsOn(copyExampleComposeWebSources) orchidBuild.dependsOn(copyExampleComposeWebSources) orchidDeploy.dependsOn(copyExampleComposeWebSources) val publish by tasks.registering { dependsOn(orchidDeploy) }
kotlin
16
0.730188
120
31.411765
51
starcoderdata
package com.linkedin.android.litr.utils import android.media.MediaFormat import android.os.Build class MediaFormatUtils { companion object { @JvmStatic fun getIFrameInterval(format: MediaFormat, defaultValue: Number): Number { return getNumber(format, MediaFormat.KEY_I_FRAME_INTERVAL) ?: defaultValue } @JvmStatic fun getFrameRate(format: MediaFormat, defaultValue: Number): Number { return getNumber(format, MediaFormat.KEY_FRAME_RATE) ?: defaultValue } @JvmStatic fun getChannelCount(format: MediaFormat, defaultValue: Number): Number { return getNumber(format, MediaFormat.KEY_CHANNEL_COUNT) ?: defaultValue } @JvmStatic fun getSampleRate(format: MediaFormat, defaultValue: Number): Number { return getNumber(format, MediaFormat.KEY_SAMPLE_RATE) ?: defaultValue } @JvmStatic fun getNumber(format: MediaFormat, key: String): Number? { return when { !format.containsKey(key) -> null Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q -> format.getNumber(key) else -> runCatching { format.getInteger(key) }.recoverCatching { format.getFloat(key) }.getOrNull() } } } }
kotlin
25
0.602158
87
32.926829
41
starcoderdata
/* * Copyright 2019 Square Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.squareup.wire.internal import com.squareup.wire.GrpcCall import com.squareup.wire.GrpcClient import com.squareup.wire.GrpcMethod import kotlinx.coroutines.suspendCancellableCoroutine import okhttp3.Call import okhttp3.Callback import okhttp3.Response import okio.IOException import okio.Timeout import java.util.concurrent.TimeUnit import kotlin.coroutines.resume import kotlin.coroutines.resumeWithException internal class RealGrpcCall<S : Any, R : Any>( private val grpcClient: GrpcClient, private val grpcMethod: GrpcMethod<S, R> ) : GrpcCall<S, R> { /** Non-null until the call is executed. */ private var call: Call? = null private var canceled = false override val timeout: Timeout = LateInitTimeout() override fun cancel() { canceled = true call?.cancel() } override fun isCanceled(): Boolean = canceled override suspend fun execute(request: S): R { val call = initCall(request) return suspendCancellableCoroutine { continuation -> continuation.invokeOnCancellation { cancel() } call.enqueue(object : Callback { override fun onFailure(call: Call, e: IOException) { continuation.resumeWithException(e) } override fun onResponse(call: Call, response: Response) { var message: R? = null var exception: IOException? = null try { message = response.messageSource(grpcMethod.responseAdapter).readExactlyOneAndClose() exception = response.grpcStatusToException() } catch (e: IOException) { exception = e } if (exception != null) { continuation.resumeWithException(exception) } else { continuation.resume(message!!) } } }) } } override fun executeBlocking(request: S): R { val call = initCall(request) val response = call.execute() response.use { val message: R = response.messageSource(grpcMethod.responseAdapter).readExactlyOneAndClose() val exception: IOException? = response.grpcStatusToException() if (exception != null) throw exception return message } } override fun enqueue(request: S, callback: GrpcCall.Callback<S, R>) { val call = initCall(request) call.enqueue(object : Callback { override fun onFailure(call: Call, e: IOException) { callback.onFailure(this@RealGrpcCall, e) } override fun onResponse(call: Call, response: Response) { response.use { var message: R? = null var exception: IOException? try { message = response.messageSource(grpcMethod.responseAdapter).readExactlyOneAndClose() exception = response.grpcStatusToException() } catch (e: IOException) { exception = e } if (exception != null) { callback.onFailure(this@RealGrpcCall, exception) } else { callback.onSuccess(this@RealGrpcCall, message!!) } } } }) } override fun isExecuted(): Boolean = call?.isExecuted() ?: false override fun clone(): GrpcCall<S, R> { val result = RealGrpcCall(grpcClient, grpcMethod) val oldTimeout = this.timeout result.timeout.also { newTimeout -> newTimeout.timeout(oldTimeout.timeoutNanos(), TimeUnit.NANOSECONDS) if (oldTimeout.hasDeadline()) newTimeout.deadlineNanoTime(oldTimeout.deadlineNanoTime()) } return result } private fun initCall(request: S): Call { check(this.call == null) { "already executed" } val requestBody = newRequestBody(grpcMethod.requestAdapter, request) val result = grpcClient.newCall(grpcMethod.path, requestBody) this.call = result if (canceled) result.cancel() (timeout as LateInitTimeout).init(result.timeout()) return result } }
kotlin
32
0.671297
98
30.652482
141
starcoderdata
package com.chrynan.sitetheme.model typealias ID = String
kotlin
3
0.827586
35
18.666667
3
starcoderdata
/* * Use of this source code is governed by the MIT license that can be * found in the LICENSE file. */ package org.rust.cargo.project.model.impl import com.intellij.openapi.Disposable import com.intellij.openapi.project.Project import com.intellij.openapi.util.Disposer import com.intellij.openapi.vfs.VirtualFile import com.intellij.util.Consumer import com.intellij.util.indexing.LightDirectoryIndex import org.rust.cargo.project.model.CargoProject import org.rust.cargo.project.model.CargoProjectsService import org.rust.cargo.project.workspace.CargoWorkspace.Package import org.rust.openapiext.checkReadAccessAllowed import org.rust.openapiext.checkWriteAccessAllowed import java.util.* class CargoPackageIndex( private val project: Project, private val service: CargoProjectsService ) : CargoProjectsService.CargoProjectsListener { private val indices: MutableMap<CargoProject, LightDirectoryIndex<Optional<Package>>> = hashMapOf() private var indexDisposable: Disposable? = null init { project.messageBus.connect(project).subscribe(CargoProjectsService.CARGO_PROJECTS_TOPIC, this) } override fun cargoProjectsUpdated(projects: Collection<CargoProject>) { checkWriteAccessAllowed() resetIndex() val disposable = Disposer.newDisposable("CargoPackageIndexDisposable") Disposer.register(project, disposable) for (cargoProject in projects) { val packages = cargoProject.workspace?.packages.orEmpty() indices[cargoProject] = LightDirectoryIndex(disposable, Optional.empty(), Consumer { index -> for (pkg in packages) { val info = Optional.of(pkg) index.putInfo(pkg.contentRoot, info) for (target in pkg.targets) { index.putInfo(target.crateRoot?.parent, info) index.putInfo(target.outDir, info) } } }) } indexDisposable = disposable } fun findPackageForFile(file: VirtualFile): Package? { checkReadAccessAllowed() val cargoProject = service.findProjectForFile(file) ?: return null return indices[cargoProject]?.getInfoForFile(file)?.orElse(null) } private fun resetIndex() { val disposable = indexDisposable if (disposable != null) { Disposer.dispose(disposable) } indexDisposable = null indices.clear() } }
kotlin
32
0.686102
105
35.823529
68
starcoderdata
<reponame>Gazer022/TachiyomiEH package eu.kanade.tachiyomi.ui.setting import android.os.Build import android.os.Handler import android.support.v7.preference.PreferenceScreen import android.widget.Toast import com.afollestad.materialdialogs.MaterialDialog import com.bluelinelabs.conductor.RouterTransaction import com.bluelinelabs.conductor.changehandler.FadeChangeHandler import com.f2prateek.rx.preferences.Preference import com.github.salomonbrys.kotson.fromJson import com.google.gson.Gson import com.kizitonwose.time.Interval import com.kizitonwose.time.days import com.kizitonwose.time.hours import eu.kanade.tachiyomi.R import eu.kanade.tachiyomi.data.database.DatabaseHelper import eu.kanade.tachiyomi.data.preference.PreferenceKeys import eu.kanade.tachiyomi.data.preference.getOrDefault import eu.kanade.tachiyomi.util.toast import exh.EH_SOURCE_ID import exh.EXH_SOURCE_ID import exh.eh.EHentaiUpdateWorker import exh.eh.EHentaiUpdateWorkerConstants import exh.eh.EHentaiUpdaterStats import exh.favorites.FavoritesIntroDialog import exh.favorites.LocalFavoritesStorage import exh.metadata.metadata.EHentaiSearchMetadata import exh.metadata.metadata.base.getFlatMetadataForManga import exh.metadata.nullIfBlank import exh.uconfig.WarnConfigureDialogController import exh.ui.login.LoginController import exh.util.await import exh.util.trans import humanize.Humanize import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.GlobalScope import kotlinx.coroutines.launch import kotlinx.coroutines.withContext import rx.android.schedulers.AndroidSchedulers import rx.schedulers.Schedulers import uy.kohesive.injekt.injectLazy import java.util.* /** * EH Settings fragment */ class SettingsEhController : SettingsController() { private val gson: Gson by injectLazy() private val db: DatabaseHelper by injectLazy() private fun Preference<*>.reconfigure(): Boolean { //Listen for change commit asObservable() .skip(1) //Skip first as it is emitted immediately .take(1) //Only listen for first commit .observeOn(AndroidSchedulers.mainThread()) .subscribeUntilDestroy { //Only listen for first change commit WarnConfigureDialogController.uploadSettings(router) } //Always return true to save changes return true } override fun setupPreferenceScreen(screen: PreferenceScreen) = with(screen) { title = "E-Hentai" switchPreference { title = "Enable ExHentai" summaryOff = "Requires login" key = PreferenceKeys.eh_enableExHentai isPersistent = false defaultValue = false preferences.enableExhentai() .asObservable() .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .subscribeUntilDestroy { isChecked = it } onChange { newVal -> newVal as Boolean if(!newVal) { preferences.enableExhentai().set(false) true } else { router.pushController(RouterTransaction.with(LoginController()) .pushChangeHandler(FadeChangeHandler()) .popChangeHandler(FadeChangeHandler())) false } } } switchPreference { title = "Use Hentai@Home Network" summary = "Do you wish to load images through the Hentai@Home Network? Disabling this option will reduce the amount of pages you are able to view" key = "enable_hah" defaultValue = true onChange { preferences.useHentaiAtHome().reconfigure() } }.dependency = PreferenceKeys.eh_enableExHentai switchPreference { title = "Show Japanese titles in search results" summaryOn = "Currently showing Japanese titles in search results. Clear the chapter cache after changing this (in the Advanced section)" summaryOff = "Currently showing English/Romanized titles in search results. Clear the chapter cache after changing this (in the Advanced section)" key = "use_jp_title" defaultValue = false onChange { preferences.useJapaneseTitle().reconfigure() } }.dependency = PreferenceKeys.eh_enableExHentai switchPreference { title = "Use original images" summaryOn = "Currently using original images" summaryOff = "Currently using resampled images" key = PreferenceKeys.eh_useOrigImages defaultValue = false onChange { preferences.eh_useOriginalImages().reconfigure() } }.dependency = PreferenceKeys.eh_enableExHentai switchPreference { defaultValue = true key = "secure_exh" title = "Secure ExHentai/E-Hentai" summary = "Use the HTTPS version of ExHentai/E-Hentai." } listPreference { defaultValue = "auto" key = "ehentai_quality" summary = "The quality of the downloaded images" title = "Image quality" entries = arrayOf( "Auto", "2400x", "1600x", "1280x", "980x", "780x" ) entryValues = arrayOf( "auto", "ovrs_2400", "ovrs_1600", "high", "med", "low" ) onChange { preferences.imageQuality().reconfigure() } }.dependency = PreferenceKeys.eh_enableExHentai switchPreference { title = "Force ascending sort on gallery versions" key = PreferenceKeys.eh_forceSortEhVersionsAsc defaultValue = true } preferenceCategory { title = "Favorites sync" switchPreference { title = "Disable favorites uploading" summary = "Favorites are only downloaded from ExHentai. Any changes to favorites in the app will not be uploaded. Prevents accidental loss of favorites on ExHentai. Note that removals will still be downloaded (if you remove a favorites on ExHentai, it will be removed in the app as well)." key = PreferenceKeys.eh_readOnlySync defaultValue = false } preference { title = "Show favorites sync notes" summary = "Show some information regarding the favorites sync feature" onClick { activity?.let { FavoritesIntroDialog().show(it) } } } switchPreference { title = "Ignore sync errors when possible" summary = "Do not abort immediately when encountering errors during the sync process. Errors will still be displayed when the sync is complete. Can cause loss of favorites in some cases. Useful when syncing large libraries." key = PreferenceKeys.eh_lenientSync defaultValue = false } preference { title = "Force sync state reset" summary = "Performs a full resynchronization on the next sync. Removals will not be synced. All favorites in the app will be re-uploaded to ExHentai and all favorites on ExHentai will be re-downloaded into the app. Useful for repairing sync after sync has been interrupted." onClick { activity?.let { MaterialDialog.Builder(it) .title("Are you sure?") .content("Resetting the sync state can cause your next sync to be extremely slow.") .positiveText("Yes") .onPositive { _, _ -> LocalFavoritesStorage().apply { getRealm().use { it.trans { clearSnapshots(it) } } } it.toast("Sync state reset", Toast.LENGTH_LONG) } .negativeText("No") .cancelable(false) .show() } } } } if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { preferenceCategory { title = "Gallery update checker" intListPreference { key = PreferenceKeys.eh_autoUpdateFrequency title = "Time between update batches" entries = arrayOf("Never update galleries", "1 hour", "2 hours", "3 hours", "6 hours", "12 hours", "24 hours", "48 hours") entryValues = arrayOf("0", "1", "2", "3", "6", "12", "24", "48") defaultValue = "0" preferences.eh_autoUpdateFrequency().asObservable().subscribeUntilDestroy { newVal -> summary = if(newVal == 0) { "${context.getString(R.string.app_name)} will currently never check galleries in your library for updates." } else { "${context.getString(R.string.app_name)} checks/updates galleries in batches. " + "This means it will wait $newVal hour(s), check ${EHentaiUpdateWorkerConstants.UPDATES_PER_ITERATION} galleries," + " wait $newVal hour(s), check ${EHentaiUpdateWorkerConstants.UPDATES_PER_ITERATION} and so on..." } } onChange { newValue -> val interval = (newValue as String).toInt() EHentaiUpdateWorker.scheduleBackground(context, interval) true } } multiSelectListPreference { key = PreferenceKeys.eh_autoUpdateRestrictions title = "Auto update restrictions" entriesRes = arrayOf(R.string.wifi, R.string.charging) entryValues = arrayOf("wifi", "ac") summaryRes = R.string.pref_library_update_restriction_summary preferences.eh_autoUpdateFrequency().asObservable() .subscribeUntilDestroy { isVisible = it > 0 } onChange { // Post to event looper to allow the preference to be updated. Handler().post { EHentaiUpdateWorker.scheduleBackground(context) } true } } preference { title = "Show updater statistics" onClick { val progress = MaterialDialog.Builder(context) .progress(true, 0) .content("Collecting statistics...") .cancelable(false) .show() GlobalScope.launch(Dispatchers.IO) { val updateInfo = try { val stats = preferences.eh_autoUpdateStats().getOrDefault().nullIfBlank()?.let { gson.fromJson<EHentaiUpdaterStats>(it) } val statsText = if (stats != null) { "The updater last ran ${Humanize.naturalTime(Date(stats.startTime))}, and checked ${stats.updateCount} out of the ${stats.possibleUpdates} galleries that were ready for checking." } else "The updater has not ran yet." val allMeta = db.getFavoriteMangaWithMetadata().await().filter { it.source == EH_SOURCE_ID || it.source == EXH_SOURCE_ID }.mapNotNull { db.getFlatMetadataForManga(it.id!!).await()?.raise<EHentaiSearchMetadata>() }.toList() fun metaInRelativeDuration(duration: Interval<*>): Int { val durationMs = duration.inMilliseconds.longValue return allMeta.asSequence().filter { System.currentTimeMillis() - it.lastUpdateCheck < durationMs }.count() } """ $statsText Galleries that were checked in the last: - hour: ${metaInRelativeDuration(1.hours)} - 6 hours: ${metaInRelativeDuration(6.hours)} - 12 hours: ${metaInRelativeDuration(12.hours)} - day: ${metaInRelativeDuration(1.days)} - 2 days: ${metaInRelativeDuration(2.days)} - week: ${metaInRelativeDuration(7.days)} - month: ${metaInRelativeDuration(30.days)} - year: ${metaInRelativeDuration(365.days)} """.trimIndent() } finally { progress.dismiss() } withContext(Dispatchers.Main) { MaterialDialog.Builder(context) .title("Gallery updater statistics") .content(updateInfo) .positiveText("Ok") .show() } } } } } } } }
kotlin
40
0.518443
305
43.392749
331
starcoderdata
<gh_stars>0 package modeling import org.openrndr.draw.BufferWriter import org.openrndr.math.Vector2 import org.openrndr.math.Vector3 import org.openrndr.shape.ShapeContour import org.openrndr.shape.Triangulator fun extrudeContour(contour: ShapeContour, extrusion: Double, objectId: Double, writer: BufferWriter, flipNormals: Boolean = false, generateBottom: Boolean = true, zBase: Double = 0.0) { val linear = contour.sampleLinear(2.0) val z = Vector3(0.0, 0.0, zBase) linear.segments.forEach { writer.apply { val n = (it.end - it.start).normalized.perpendicular.xy0 * if (flipNormals) -1.0 else 1.0 write(it.start.xy0 + z, n) write(objectId.toFloat()) write(Vector3.ZERO) write(it.end.xy0 + z, n) write(objectId.toFloat()) write(Vector3.ZERO) write(it.end.vector3(z = extrusion) + z, n) write(objectId.toFloat()) write(Vector3.UNIT_Z) write(it.end.vector3(z = extrusion) + z, n) write(objectId.toFloat()) write(Vector3.UNIT_Z) write(it.start.vector3(z = extrusion) + z, n) write(objectId.toFloat()) write(Vector3.UNIT_Z) write(it.start.xy0 + z, n) write(objectId.toFloat()) write(Vector3.ZERO) } } Triangulator().triangulate(linear).let { tris -> if (generateBottom) { tris.forEach { writer.write(it.xy0 + z, Vector3.UNIT_Z * if (flipNormals) -1.0 else 1.0) writer.write(objectId.toFloat()) writer.write(Vector3.ZERO) } } tris.forEach { writer.write(it.vector3(z = extrusion) + z, Vector3.UNIT_Z * -1.0 * if (flipNormals) -1.0 else 1.0) writer.write(objectId.toFloat()) writer.write(Vector3.UNIT_Z) } } } fun extrudeContourUV(contour: ShapeContour, extrusion: Double, objectId: Double, writer: BufferWriter, flipNormals: Boolean = false, generateBottom: Boolean = true, zBase: Double = 0.0) { val linear = contour.sampleLinear(2.0) val length = linear.length val z = Vector3(0.0, 0.0, zBase) var uOffset = 0.0 linear.segments.forEach { writer.apply { val n = (it.end - it.start).normalized.perpendicular.xy0 * if (flipNormals) -1.0 else 1.0 val u0 = uOffset / length val u1 = u0 + (it.end - it.start).length / length write(it.start.xy0 + z, n) write(objectId.toFloat()) write(Vector3.ZERO) write(Vector2(u0, 0.0)) write(it.end.xy0 + z, n) write(objectId.toFloat()) write(Vector3.ZERO) write(Vector2(u1, 0.0)) write(it.end.vector3(z = extrusion) + z, n) write(objectId.toFloat()) write(Vector3.UNIT_Z) write(Vector2(u1, 1.0)) write(it.end.vector3(z = extrusion) + z, n) write(objectId.toFloat()) write(Vector3.UNIT_Z) write(Vector2(u1, 1.0)) write(it.start.vector3(z = extrusion) + z, n) write(objectId.toFloat()) write(Vector3.UNIT_Z) write(Vector2(u0, 1.0)) write(it.start.xy0 + z, n) write(objectId.toFloat()) write(Vector3.ZERO) write(Vector2(u0, 0.0)) uOffset += (it.end - it.start).length } } Triangulator().triangulate(linear).let { tris -> if (generateBottom) { tris.forEach { writer.write(it.xy0 + z, Vector3.UNIT_Z * if (flipNormals) -1.0 else 1.0) writer.write(objectId.toFloat()) writer.write(Vector3.ZERO) writer.write(Vector2.ZERO) } } tris.forEach { writer.write(it.vector3(z = extrusion) + z, Vector3.UNIT_Z * -1.0 * if (flipNormals) -1.0 else 1.0) writer.write(objectId.toFloat()) writer.write(Vector3.UNIT_Z) writer.write(Vector2.ZERO) } } }
kotlin
25
0.539112
187
33.483333
120
starcoderdata
<filename>buildSrc/src/main/kotlin/com/supertramp/plugin/ext/DingExtension.kt package com.supertramp.plugin.ext open class DingExtension { var enable : Boolean = false //控制功能是否生效 var webHook : String = ""//钉钉机器人唯一识别 var robotSecret : String = "" var appName : String = "" var testApkName : String = ""//测试环境 var productApkName : String = ""//生产环境apk名称 var apkServerPath : String = ""//apk在打包服务器上的路径 var apkVersion : String = "" var atUser : String = ""//需要at的用户 var atAll : Boolean = false var atMsg : String = "最新包" var jenkinsUsername : String = "" var jenkinsPassword : String = "" }
kotlin
10
0.661466
77
31.1
20
starcoderdata
@file:Suppress("unused") package com.beust.klaxon import org.assertj.core.api.Assertions.assertThat import org.testng.annotations.Test import java.util.* data class ConferenceDataModel( val events: Map<String, EventModel>, val rooms: Map<String, RoomModel>, val sections: Map<String, SectionModel>, val speakers: Map<String, SpeakerModel>, val tracks: Map<String, TrackModel> ) data class EventModel( val name: String, val description: String, val duration: String, val isGeneralEvent: Boolean, val isPublished: Boolean, val startTime: String, //Date, val roomIds: Map<String, Boolean>? = emptyMap(), val speakerIds: Map<String, Boolean>? = emptyMap(), val trackId: String? = null, var roomNames: Map<String, Boolean>? = emptyMap(), var speakerNames: Map<String, Boolean>? = emptyMap(), var trackName: String? = null, val updatedAt: Long, val updatedBy: String ) data class RoomModel( val name: String, val updatedAt: Long, val updatedBy: String ) data class SectionModel( val name: String, val title: String, val startTime: String,//Date, val endTime: String,//Date, val updatedAt: Long, val updatedBy: String ) data class SpeakerModel( val name: String, val title: String? = null, val org: String? = null, val bio: String, val pictureId: String? = null, val pictureUrl: String? = null, val isFeatured: Boolean, val socialProfiles: Map<String,String>? = emptyMap(), val updatedAt: Long, val updatedBy: String ) data class TrackModel( val name: String, val description: String, val sortOrder: Int, val updatedAt: Long, val updatedBy: String ) data class Node(val nodeName: String) class Root(val nodes: Map<String, Node>) @Test class MapTest { @Test(enabled = false) fun hashMap() { val r = Klaxon() .parse<HashMap<String, Node>>("""{ "key1": { "nodeName": "node1" }, "key2": { "nodeName": "node2" } }""") assertThat(r!!.size).isEqualTo(2) assertThat(r["key1"]).isEqualTo(Node("node1")) assertThat(r["key2"]).isEqualTo(Node("node2")) println(r) } class Model(val events: Map<String, Node>) fun modelWithHashMap() { val r = Klaxon() .parse<Model>("""{ "events": { "key1": { "nodeName": "node1" }, "key2": { "nodeName": "node2" } } }""") assertThat(r!!.events["key1"]).isEqualTo(Node("node1")) } fun bigFile() { val ins = MapTest::class.java.getResourceAsStream("/data.json") ?: throw IllegalArgumentException("Couldn't find data.json") val r = Klaxon().parse<ConferenceDataModel>(ins)!! assertThat(r.events.size).isEqualTo(5) assertThat(r.events["-L3daccTVLOcYi9hVHsD"]?.name).isEqualTo("Registration & Breakfast") } } class Employee(val firstName: String, val lastName: String, val age: Int) { val lazyValue: String by lazy { val result = "" result } }
kotlin
16
0.577385
96
27.254237
118
starcoderdata
package com.mohfahmi.mkaassesment.domain.usecase import androidx.lifecycle.LiveData import com.mohfahmi.mkaassesment.data.source.remote.network.ApiResponse import com.mohfahmi.mkaassesment.data.source.remote.response.DetailResponse import com.mohfahmi.mkaassesment.data.source.remote.response.ReposResponseItem import com.mohfahmi.mkaassesment.domain.entity.UsersGithubEntity interface UsersGithubUseCase { fun geDetailUserOnMainGithub(query: String): LiveData<ArrayList<UsersGithubEntity>> fun getDetailDataUserFromRepo(username: String): LiveData<ApiResponse<DetailResponse>> fun getReposUserFromRepo(username: String): LiveData<ApiResponse<List<ReposResponseItem>>> }
kotlin
14
0.852339
94
51.692308
13
starcoderdata
<reponame>RishiKumarRay/MathTools<gh_stars>0 package mathtools.numbers.factors import mathtools.numbers.factors.NumberFactors.isProductOf2 /** Functions that operate on 32-bit Integers * @author DK96-OS : 2020 - 2022 */ object IntOperations { /** Perform Base 10 shift up to Int Max value. * If an overflow occurs, Int MaxValue is returned * Negative shifts are allowed * @param x The value to shift * @param e The power of base 10 applied * @return The shifted value, or MaxValue if known that the shift is too large */ fun tenShift( x: Int, e: Int, ) : Int = when { e == 0 -> x x == 0 -> 0 x < 0 -> -tenShift(-x, e) e < 0 -> when { e < -9 -> 0 e < -3 -> tenShift(x / 10_000, e + 4) e == -3 -> x / 1000 e == -2 -> x / 100 else -> x / 10 } e > 9 -> Int.MAX_VALUE else -> { // Protect against overflow using Long val testShift = when (e) { 1 -> x * 10L 2 -> x * 100L 3 -> x * 1000L else -> x * 10_000L } if (testShift <= Int.MAX_VALUE) { if (e < 5) testShift.toInt() else tenShift(testShift.toInt(), e - 4) } else Int.MAX_VALUE } } /** Compute an exponent, while checking for Integer Overflow * Negative Powers are not allowed - will be returned * @param x The base value of the exponent * @param power The power of the exponent * @return The product, and the remaining power that would cause an overflow */ fun exponent( x: Int, power: Int, ) : Pair<Int, Int> { when { power < 0 -> return x to power power == 0 -> return 1 to 0 x < 2 -> return when (x) { 1 -> 1 to 0 0 -> 0 to 0 -1 -> when { isProductOf2(power) -> 1 to 0 else -> -1 to 0 } else -> { val (product, remaining) = exponent(-x, power) if (isProductOf2(power - remaining)) product to remaining else -product to remaining } } power == 1 -> return x to 0 } val longX = x.toLong() var product = longX * longX // check for overflow if (product <= x || Int.MAX_VALUE < product) return x to power if (power == 2) return product.toInt() to 0 for (e in 2 until power) { val next = product * longX if (next <= x || Int.MAX_VALUE < next) { // Integer Overflow return product.toInt() to power - e } product = next } return product.toInt() to 0 } }
kotlin
21
0.594166
82
24.075269
93
starcoderdata
<filename>core/src/rustyice/game/tiles/WallTile.kt package rustyice.game.tiles import com.badlogic.gdx.graphics.Color import com.badlogic.gdx.graphics.g2d.Sprite import rustyengine.RustyEngine import rustyice.Core import rustyice.editor.annotations.ComponentProperty import rustyice.game.physics.RectWallComponent import rustyengine.resources.Resources class WallTile() : Tile(true, true) { @ComponentProperty var color = Color.BLUE set(value) { field = value sprite?.color = color } override fun init() { super.init() val sprite = Sprite(RustyEngine.resorces.box) sprite.color = color this.sprite = sprite } init { tilePhysics = RectWallComponent() } }
kotlin
14
0.686275
53
22.181818
33
starcoderdata
<filename>app/src/main/java/jastzeonic/com/jastzeonictodolist/SampleDatabindingActivity.kt package jastzeonic.com.jastzeonictodolist import androidx.lifecycle.ViewModelProviders import androidx.databinding.DataBindingUtil import androidx.appcompat.app.AppCompatActivity import android.os.Bundle import jastzeonic.com.jastzeonictodolist.databinding.ActivitySampleDatabindingBinding import jastzeonic.com.jastzeonictodolist.view.model.SampleViewModel class SampleDatabindingActivity : AppCompatActivity() { lateinit var viewModel: SampleViewModel override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) viewModel = ViewModelProviders.of(this).get(SampleViewModel::class.java) val binding = DataBindingUtil.setContentView<ActivitySampleDatabindingBinding>(this, R.layout.activity_sample_databinding) binding.sampleViewModel = viewModel setContentView(binding.root) } }
kotlin
14
0.819038
130
38.833333
24
starcoderdata
<filename>jpetstore/src/main/kotlin/org/komapper/example/service/ItemService.kt package org.komapper.example.service import org.komapper.example.model.ItemAggregate import org.komapper.example.repository.ItemRepository import org.springframework.stereotype.Service @Service class ItemService(private val itemRepository: ItemRepository) { fun getItemAggregate(itemId: String): ItemAggregate? { return itemRepository.fetchItemAggregate(itemId) } }
kotlin
11
0.818966
79
34.692308
13
starcoderdata
<filename>jetbrains-core/src/software/aws/toolkits/jetbrains/services/schemas/ViewSchemaAction.kt // Copyright 2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 package software.aws.toolkits.jetbrains.services.schemas import com.intellij.openapi.actionSystem.AnActionEvent import com.intellij.openapi.project.DumbAware import icons.AwsIcons import software.aws.toolkits.jetbrains.core.explorer.actions.SingleResourceNodeAction import software.aws.toolkits.resources.message class ViewSchemaAction() : SingleResourceNodeAction<SchemaNode>(message("schemas.schema.view.action"), null, AwsIcons.Actions.SCHEMA_VIEW), DumbAware { override fun actionPerformed(selected: SchemaNode, e: AnActionEvent) { SchemaViewer(selected.nodeProject).downloadAndViewSchema(selected.value.name, selected.value.registryName) } }
kotlin
14
0.818594
128
48
18
starcoderdata
<filename>backpack-android/app/src/main/java/net/skyscanner/backpack/demo/BackpackDemoApplication.kt /** * Backpack for Android - Skyscanner's Design System * * Copyright 2018-2021 Skyscanner 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 net.skyscanner.backpack.demo import android.app.Application import android.content.Context import android.content.Intent import androidx.appcompat.app.AppCompatDelegate import com.facebook.stetho.Stetho import com.jakewharton.threetenabp.AndroidThreeTen /** * Application class registered in AndroidManifest.xml */ class BackpackDemoApplication : Application() { companion object { private lateinit var instance: BackpackDemoApplication fun triggerRebirth(context: Context) { val packageManager = context.packageManager val intent = packageManager.getLaunchIntentForPackage(context.packageName) val componentName = intent!!.component val mainIntent = Intent.makeRestartActivityTask(componentName) context.startActivity(mainIntent) Runtime.getRuntime().exit(0) } } override fun onCreate() { super.onCreate() AndroidThreeTen.init(this) instance = applicationContext!! as BackpackDemoApplication Stetho.initializeWithDefaults(this) AppCompatDelegate.setCompatVectorFromResourcesEnabled(true) this.registerActivityLifecycleCallbacks(ThemeApplier) } }
kotlin
15
0.771654
100
31.844828
58
starcoderdata
<gh_stars>0 package com.babestudios.hopin import androidx.hilt.lifecycle.ViewModelInject import androidx.lifecycle.ViewModel import androidx.lifecycle.viewModelScope import androidx.navigation.NavController import com.babestudios.hopin.data.network.HopinRepositoryContract import com.babestudios.hopin.model.GetSessionRequest import com.babestudios.hopin.model.GetStageStatusResponse import com.babestudios.hopin.model.GetStagesResponse import com.babestudios.hopin.navigation.HopinNavigator import kotlinx.coroutines.launch import java.util.* class HopinViewModel @ViewModelInject constructor( private val hopinRepository: HopinRepositoryContract, private val hopinNavigator: HopinNavigator, ) : ViewModel() { fun userTokenReceived(cookies: String) { val sp = cookies.split("; ") val spl = sp.filter { it.startsWith("user.token") } if (spl.isNotEmpty()) { val userToken = spl[0].removePrefix("user.token=") viewModelScope.launch { if (convertUserId(userToken)) hopinNavigator.mainToStreamer() else { //error handling } } } } private suspend fun convertUserId(userToken: String): Boolean { val getSessionRequest = GetSessionRequest("babe-project") return hopinRepository.convertUserId( "user.token=$userToken", getSessionRequest ) } suspend fun getStreamUrl(): String? { val uuid = getStages().stages[0].uuid val status = getStageStatus(uuid) val broadcast = status.broadcasts.filter { it.broadcast_type == "mixer" }.getOrNull(0) return broadcast?.stream_url } private suspend fun getStages(): GetStagesResponse { return hopinRepository.getStages() } private suspend fun getStageStatus(uuid: String): GetStageStatusResponse { return hopinRepository.getStageStatus( UUID.fromString(uuid) ) } fun bindNavController(navController: NavController) { hopinNavigator.bind(navController) } }
kotlin
20
0.675047
94
32.061538
65
starcoderdata
/* * Copyright 2010-2021 JetBrains s.r.o. and Kotlin Programming Language contributors. * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ package org.jetbrains.kotlin.fir.analysis.checkers.declaration import org.jetbrains.kotlin.KtFakeSourceElementKind import org.jetbrains.kotlin.KtSourceElement import org.jetbrains.kotlin.descriptors.Visibilities import org.jetbrains.kotlin.diagnostics.DiagnosticReporter import org.jetbrains.kotlin.diagnostics.reportOn import org.jetbrains.kotlin.fir.analysis.checkers.FirModifierList import org.jetbrains.kotlin.fir.analysis.checkers.contains import org.jetbrains.kotlin.fir.analysis.checkers.context.CheckerContext import org.jetbrains.kotlin.fir.analysis.checkers.getModifierList import org.jetbrains.kotlin.fir.analysis.diagnostics.FirErrors import org.jetbrains.kotlin.fir.analysis.diagnostics.withSuppressedDiagnostics import org.jetbrains.kotlin.fir.declarations.FirClass import org.jetbrains.kotlin.fir.declarations.FirMemberDeclaration import org.jetbrains.kotlin.fir.declarations.FirProperty import org.jetbrains.kotlin.fir.declarations.FirSimpleFunction import org.jetbrains.kotlin.fir.declarations.impl.FirDefaultPropertyAccessor import org.jetbrains.kotlin.fir.declarations.utils.* import org.jetbrains.kotlin.fir.resolve.diagnostics.ConeLocalVariableNoTypeOrInitializer import org.jetbrains.kotlin.fir.types.FirErrorTypeRef import org.jetbrains.kotlin.lexer.KtTokens // See old FE's [DeclarationsChecker] object FirTopLevelPropertiesChecker : FirPropertyChecker() { override fun check(declaration: FirProperty, context: CheckerContext, reporter: DiagnosticReporter) { // Only report on top level callable declarations if (context.containingDeclarations.size > 1) return val source = declaration.source ?: return if (source.kind is KtFakeSourceElementKind) return // If multiple (potentially conflicting) modality modifiers are specified, not all modifiers are recorded at `status`. // So, our source of truth should be the full modifier list retrieved from the source. val modifierList = source.getModifierList() withSuppressedDiagnostics(declaration, context) { ctx -> checkPropertyInitializer( containingClass = null, declaration, modifierList, isInitialized = declaration.initializer != null, reporter, ctx ) checkExpectDeclarationVisibilityAndBody(declaration, source, reporter, ctx) } } } // TODO: check class too internal fun checkExpectDeclarationVisibilityAndBody( declaration: FirMemberDeclaration, source: KtSourceElement, reporter: DiagnosticReporter, context: CheckerContext ) { if (declaration.isExpect) { if (Visibilities.isPrivate(declaration.visibility)) { reporter.reportOn(source, FirErrors.EXPECTED_PRIVATE_DECLARATION, context) } if (declaration is FirSimpleFunction && declaration.hasBody) { reporter.reportOn(source, FirErrors.EXPECTED_DECLARATION_WITH_BODY, context) } } } // Matched FE 1.0's [DeclarationsChecker#checkPropertyInitializer]. internal fun checkPropertyInitializer( containingClass: FirClass?, property: FirProperty, modifierList: FirModifierList?, isInitialized: Boolean, reporter: DiagnosticReporter, context: CheckerContext, reachable: Boolean = true ) { val inInterface = containingClass?.isInterface == true val hasAbstractModifier = KtTokens.ABSTRACT_KEYWORD in modifierList val isAbstract = property.isAbstract || hasAbstractModifier if (isAbstract) { val returnTypeRef = property.returnTypeRef if (property.initializer == null && property.delegate == null && returnTypeRef is FirErrorTypeRef && returnTypeRef.diagnostic is ConeLocalVariableNoTypeOrInitializer ) { property.source?.let { reporter.reportOn(it, FirErrors.PROPERTY_WITH_NO_TYPE_NO_INITIALIZER, context) } } return } val backingFieldRequired = property.hasBackingField if (inInterface && backingFieldRequired && property.hasAccessorImplementation) { property.source?.let { reporter.reportOn(it, FirErrors.BACKING_FIELD_IN_INTERFACE, context) } } val isExpect = property.isEffectivelyExpect(containingClass, context) when { property.initializer != null -> { property.initializer?.source?.let { when { inInterface -> { reporter.reportOn(it, FirErrors.PROPERTY_INITIALIZER_IN_INTERFACE, context) } isExpect -> { reporter.reportOn(it, FirErrors.EXPECTED_PROPERTY_INITIALIZER, context) } !backingFieldRequired -> { reporter.reportOn(it, FirErrors.PROPERTY_INITIALIZER_NO_BACKING_FIELD, context) } property.receiverTypeRef != null -> { reporter.reportOn(it, FirErrors.EXTENSION_PROPERTY_WITH_BACKING_FIELD, context) } } } } property.delegate != null -> { property.delegate?.source?.let { when { inInterface -> { reporter.reportOn(it, FirErrors.DELEGATED_PROPERTY_IN_INTERFACE, context) } isExpect -> { reporter.reportOn(it, FirErrors.EXPECTED_DELEGATED_PROPERTY, context) } } } } else -> { val propertySource = property.source ?: return val isExternal = property.isEffectivelyExternal(containingClass, context) if ( backingFieldRequired && !inInterface && !property.isLateInit && !isExpect && !isInitialized && !isExternal && !property.hasExplicitBackingField ) { if (property.receiverTypeRef != null && !property.hasAccessorImplementation) { reporter.reportOn(propertySource, FirErrors.EXTENSION_PROPERTY_MUST_HAVE_ACCESSORS_OR_BE_ABSTRACT, context) } else if (reachable) { // TODO: can be suppressed not to report diagnostics about no body if (containingClass == null || property.hasAccessorImplementation) { reporter.reportOn(propertySource, FirErrors.MUST_BE_INITIALIZED, context) } else { reporter.reportOn(propertySource, FirErrors.MUST_BE_INITIALIZED_OR_BE_ABSTRACT, context) } } } if (property.isLateInit) { if (isExpect) { reporter.reportOn(propertySource, FirErrors.EXPECTED_LATEINIT_PROPERTY, context) } // TODO: like [BindingContext.MUST_BE_LATEINIT], we should consider variable with uninitialized error. if (backingFieldRequired && !inInterface && isInitialized) { reporter.reportOn(propertySource, FirErrors.UNNECESSARY_LATEINIT, context) } } } } } private val FirProperty.hasAccessorImplementation: Boolean get() = (getter !is FirDefaultPropertyAccessor && getter?.hasBody == true) || (setter !is FirDefaultPropertyAccessor && setter?.hasBody == true)
kotlin
25
0.64822
127
43.297143
175
starcoderdata
package io.briones.gradle.format import java.time.Duration /** Return a string that contains the given lines surrounded by a box. */ fun joinInBox(vararg lines: String): String { val lineLength = lines.map { it.length }.max()!! val bordered = mutableListOf<String>() bordered.add("┌${"─".repeat(lineLength + 2)}┐") lines.forEach { val padded = it.padEnd(lineLength, ' ') bordered.add("│ $padded │") } bordered.add("└${"─".repeat(lineLength + 2)}┘") return bordered.joinToString("\n", postfix = "\n") } /** Return the duration as a human-readable string. e.g `123000ms` is formatted as `2m 3s` */ @Suppress("MagicNumber") fun humanReadableDuration(duration: Duration): String { val secondsPart = duration.toSecondsPart() val millisPart = duration.toMillisPart() val segments = mutableListOf<String>() if (duration.toHours() > 0) { segments.add("${duration.toHours()}h") } if (duration.toMinutesPart() > 0) { segments.add("${duration.toMinutesPart()}m") } val finalSegment = when { duration > Duration.ofMinutes(1) -> "${secondsPart}s" duration < Duration.ofSeconds(1) -> "${millisPart}ms" else -> { val tenths = duration.toMillisPart() / 100 "${duration.toSecondsPart()}.${tenths}s" } } segments.add(finalSegment) return segments.joinToString(separator = " ") }
kotlin
16
0.628772
93
33.756098
41
starcoderdata
<reponame>BrunoSilvaFreire/ShiroiFramework package me.ddevil.shiroi.craft.config.loader import me.ddevil.shiroi.util.misc.item.Material class ShiroiMaterialLoader : AbstractConfigLoader<String, Material>(String::class.java, Material::class.java) { override fun load(type: String): Material { return Material.matchMaterial(type) ?: throw IllegalArgumentException("Unknown material $type") } }
kotlin
14
0.780488
111
36.363636
11
starcoderdata
<reponame>Between-freedom-and-Space/Backend package com.between_freedom_and_space.mono_backend.auth.api.models import kotlinx.serialization.SerialName import kotlinx.serialization.Serializable @Serializable data class RegisterUserResponse( @SerialName("id") val id: Long, @SerialName("nickname") val nickName: String )
kotlin
9
0.778761
66
21.6
15
starcoderdata
package com.alexandre.skiresort.ui.skiresortlist import androidx.lifecycle.* import com.alexandre.skiresort.data.SkiResortRepo import com.alexandre.skiresort.domain.model.SkiResortUiModel import kotlinx.coroutines.launch class SkiResortListViewModel(private val skiResortRepo: SkiResortRepo) : ViewModel() { //list of all the ski resorts val skiResortUiModelList: LiveData<List<SkiResortUiModel>> = skiResortRepo.getAllSkiResorts().asLiveData(viewModelScope.coroutineContext) //change the fav value fun toggleFav(skiResortUiModel: SkiResortUiModel) { viewModelScope.launch { skiResortRepo.updateSkiResortFav(skiResortUiModel.skiResortId, !skiResortUiModel.isFav) } } }
kotlin
18
0.777778
99
33.761905
21
starcoderdata
package com.ffsilva.pontointeligente.dtos import org.hibernate.validator.constraints.Length import javax.validation.constraints.Email import javax.validation.constraints.NotBlank data class FuncionarioDto( val id: String? = null, @get:NotBlank(message = "Nome não pode ser vazio.") @get:Length(min = 3, max = 200, message = "Nome deve conter entre 3 e 200 caracteres.") val nome: String = "", @get:NotBlank(message = "Email não pode ser vazio.") @get:Length(min = 5, max = 200, message = "Email deve conter entre 5 e 200 caracteres.") @get:Email(message = "Email inválido.") val email: String = "", val senha: String? = <PASSWORD>, val valorHora: String? = null, val qtdHorasTrabalhoDia: String? = null, val qtdHorasAlmoco: String? = null )
kotlin
9
0.653207
96
34.125
24
starcoderdata
<filename>entity-service/src/test/kotlin/com/egm/stellio/entity/service/IAMListenerTests.kt package com.egm.stellio.entity.service import com.egm.stellio.shared.model.NgsiLdProperty import com.egm.stellio.shared.model.NgsiLdRelationship import com.egm.stellio.shared.util.GlobalRole import com.egm.stellio.shared.util.loadSampleData import com.egm.stellio.shared.util.toUri import com.ninjasquad.springmockk.MockkBean import io.mockk.confirmVerified import io.mockk.verify import org.junit.jupiter.api.Test import org.springframework.beans.factory.annotation.Autowired import org.springframework.boot.test.context.SpringBootTest import org.springframework.test.context.ActiveProfiles @SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.NONE, classes = [IAMListener::class]) @ActiveProfiles("test") class IAMListenerTests { @Autowired private lateinit var iamListener: IAMListener @MockkBean(relaxed = true) private lateinit var entityService: EntityService @Test fun `it should parse and transmit user creation event`() { val userCreateEvent = loadSampleData("events/authorization/UserCreateEvent.json") iamListener.processMessage(userCreateEvent) verify { entityService.createEntity( match { it.id == "urn:ngsi-ld:User:6ad19fe0-fc11-4024-85f2-931c6fa6f7e0".toUri() && it.properties.size == 1 && it.properties[0].compactName == "username" && it.properties[0].instances.size == 1 && it.properties[0].instances[0].value == "stellio" } ) } confirmVerified() } @Test fun `it should parse and transmit user deletion event`() { val userDeleteEvent = loadSampleData("events/authorization/UserDeleteEvent.json") iamListener.processMessage(userDeleteEvent) verify { entityService.deleteEntity("urn:ngsi-ld:User:6ad19fe0-fc11-4024-85f2-931c6fa6f7e0".toUri()) } confirmVerified() } @Test fun `it should parse and transmit group creation event`() { val groupCreateEvent = loadSampleData("events/authorization/GroupCreateEvent.json") iamListener.processMessage(groupCreateEvent) verify { entityService.createEntity( match { it.id == "urn:ngsi-ld:Group:ab67edf3-238c-4f50-83f4-617c620c62eb".toUri() } ) } confirmVerified() } @Test fun `it should parse and transmit group update event`() { val groupUpdateEvent = loadSampleData("events/authorization/GroupUpdateEvent.json") iamListener.processMessage(groupUpdateEvent) verify { entityService.updateEntityAttributes( "urn:ngsi-ld:Group:ab67edf3-238c-4f50-83f4-617c620c62eb".toUri(), match { it.size == 1 && it[0].compactName == "name" && it[0] is NgsiLdProperty && (it[0] as NgsiLdProperty).instances.size == 1 && (it[0] as NgsiLdProperty).instances[0].value == "EGM Team" } ) } confirmVerified() } @Test fun `it should parse and transmit group deletion event`() { val groupDeleteEvent = loadSampleData("events/authorization/GroupDeleteEvent.json") iamListener.processMessage(groupDeleteEvent) verify { entityService.deleteEntity("urn:ngsi-ld:Group:a11c00f9-43bc-47a8-9d23-13d67696bdb8".toUri()) } confirmVerified() } @Test fun `it should parse and transmit client creation event`() { val clientCreateEvent = loadSampleData("events/authorization/ClientCreateEvent.json") iamListener.processMessage(clientCreateEvent) verify { entityService.createEntity( match { it.id == "urn:ngsi-ld:Client:191a6f0d-df07-4697-afde-da9d8a91d954".toUri() && it.properties.size == 1 && it.properties[0].compactName == "clientId" && it.properties[0].instances.size == 1 && it.properties[0].instances[0].value == "stellio-client" } ) } confirmVerified() } @Test fun `it should parse and transmit client deletion event`() { val clientDeleteEvent = loadSampleData("events/authorization/ClientDeleteEvent.json") iamListener.processMessage(clientDeleteEvent) verify { entityService.deleteEntity("urn:ngsi-ld:Client:6ad19fe0-fc11-4024-85f2-931c6fa6f7e0".toUri()) } confirmVerified() } @Test fun `it should parse and transmit group membership append event`() { val groupMembershipAppendEvent = loadSampleData("events/authorization/GroupMembershipAppendEvent.json") iamListener.processMessage(groupMembershipAppendEvent) verify { entityService.appendEntityAttributes( "urn:ngsi-ld:User:96e1f1e9-d798-48d7-820e-59f5a9a2abf5".toUri(), match { it.size == 1 && it[0].name == "https://ontology.eglobalmark.com/authorization#isMemberOf" && it[0] is NgsiLdRelationship && (it[0] as NgsiLdRelationship).instances[0].datasetId == "urn:ngsi-ld:Dataset:7cdad168-96ee-4649-b768-a060ac2ef435".toUri() && (it[0] as NgsiLdRelationship).instances[0].objectId == "urn:ngsi-ld:Group:7cdad168-96ee-4649-b768-a060ac2ef435".toUri() }, false ) } confirmVerified() } @Test fun `it should parse and transmit group membership deletion event`() { val groupMembershipDeleteEvent = loadSampleData("events/authorization/GroupMembershipDeleteEvent.json") iamListener.processMessage(groupMembershipDeleteEvent) verify { entityService.deleteEntityAttributeInstance( "urn:ngsi-ld:User:96e1f1e9-d798-48d7-820e-59f5a9a2abf5".toUri(), "https://ontology.eglobalmark.com/authorization#isMemberOf", "urn:ngsi-ld:Dataset:7cdad168-96ee-4649-b768-a060ac2ef435".toUri() ) } } @Test fun `it should parse and transmit role update event with two roles`() { val roleAppendEvent = loadSampleData("events/authorization/RealmRoleAppendEventTwoRoles.json") iamListener.processMessage(roleAppendEvent) verify { entityService.appendEntityAttributes( "urn:ngsi-ld:Group:ab67edf3-238c-4f50-83f4-617c620c62eb".toUri(), match { it.size == 1 && it[0].compactName == "roles" && it[0] is NgsiLdProperty && (it[0] as NgsiLdProperty).instances.size == 1 && (it[0] as NgsiLdProperty).instances[0].value is List<*> && ((it[0] as NgsiLdProperty).instances[0].value as List<*>) .containsAll(setOf(GlobalRole.STELLIO_ADMIN.key, GlobalRole.STELLIO_CREATOR.key)) }, false ) } confirmVerified() } @Test fun `it should parse and transmit role update event with one role`() { val roleAppendEvent = loadSampleData("events/authorization/RealmRoleAppendEventOneRole.json") iamListener.processMessage(roleAppendEvent) verify { entityService.appendEntityAttributes( "urn:ngsi-ld:Group:ab67edf3-238c-4f50-83f4-617c620c62eb".toUri(), match { it.size == 1 && it[0].compactName == "roles" && it[0] is NgsiLdProperty && (it[0] as NgsiLdProperty).instances.size == 1 && (it[0] as NgsiLdProperty).instances[0].value is String && (it[0] as NgsiLdProperty).instances[0].value == GlobalRole.STELLIO_ADMIN.key }, false ) } confirmVerified() } @Test fun `it should parse and transmit role update event with no roles`() { val roleAppendEvent = loadSampleData("events/authorization/RealmRoleAppendEventNoRole.json") iamListener.processMessage(roleAppendEvent) verify { entityService.appendEntityAttributes( "urn:ngsi-ld:Group:ab67edf3-238c-4f50-83f4-617c620c62eb".toUri(), match { it.size == 1 && it[0].compactName == "roles" && it[0] is NgsiLdProperty && (it[0] as NgsiLdProperty).instances.size == 1 && (it[0] as NgsiLdProperty).instances[0].value is List<*> && ((it[0] as NgsiLdProperty).instances[0].value as List<*>).isEmpty() }, false ) } confirmVerified() } @Test fun `it should parse and transmit role update event for a client`() { val roleAppendEvent = loadSampleData("events/authorization/RealmRoleAppendToClient.json") iamListener.processMessage(roleAppendEvent) verify { entityService.appendEntityAttributes( "urn:ngsi-ld:Client:ab67edf3-238c-4f50-83f4-617c620c62eb".toUri(), match { it.size == 1 && it[0].compactName == "roles" }, false ) } confirmVerified() } }
kotlin
34
0.586319
112
36.862069
261
starcoderdata
/* * Copyright 2018 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.example.android.watchface.watchfacekotlin.service import android.content.BroadcastReceiver import android.content.Context import android.content.Intent import android.content.IntentFilter import android.graphics.Bitmap import android.graphics.BitmapFactory import android.graphics.Canvas import android.graphics.Color import android.graphics.ColorMatrix import android.graphics.ColorMatrixColorFilter import android.graphics.Paint import android.graphics.Rect import android.os.Bundle import android.os.Handler import android.os.Message import android.support.wearable.watchface.CanvasWatchFaceService import android.support.wearable.watchface.WatchFaceService import android.support.wearable.watchface.WatchFaceStyle import android.view.SurfaceHolder import com.example.android.watchface.watchfacekotlin.model.AnalogWatchFaceStyle import com.example.android.watchface.watchfacekotlin.model.WatchFaceBackgroundImage import java.lang.ref.WeakReference import java.util.Calendar import java.util.TimeZone /** * Updates rate in milliseconds for interactive mode. We update once a second to advance the * second hand. */ private const val INTERACTIVE_UPDATE_RATE_MS = 1000 /** * Handler message id for updating the time periodically in interactive mode. */ private const val MSG_UPDATE_TIME = 0 /** * This is a helper class which renders an analog watch face based on a data object passed in * representing the style. The class implements all best practices for watch faces, so the * developer can just focus on designing the watch face they want. * * Analog watch face with a ticking second hand. In ambient mode, the second hand isn't * shown. On devices with low-bit ambient mode, the hands are drawn without anti-aliasing in ambient * mode. The watch face is drawn with less contrast in mute mode. * * * Important Note: Because watch face apps do not have a default Activity in * their project, you will need to set your Configurations to * "Do not launch Activity" for both the Wear and/or Application modules. If you * are unsure how to do this, please review the "Run Starter project" section * in the * [Watch Face Code Lab](https://codelabs.developers.google.com/codelabs/watchface/index.html#0) */ abstract class AbstractKotlinWatchFace : CanvasWatchFaceService() { private lateinit var analogWatchFaceStyle: AnalogWatchFaceStyle abstract fun getWatchFaceStyle():AnalogWatchFaceStyle override fun onCreateEngine(): Engine { return Engine() } private class EngineHandler(reference: AbstractKotlinWatchFace.Engine) : Handler() { private val weakReference: WeakReference<AbstractKotlinWatchFace.Engine> = WeakReference(reference) override fun handleMessage(msg: Message) { val engine = weakReference.get() if (engine != null) { when (msg.what) { MSG_UPDATE_TIME -> engine.handleUpdateTimeMessage() } } } } inner class Engine : CanvasWatchFaceService.Engine() { private lateinit var calendar: Calendar private var registeredTimeZoneReceiver = false private var muteMode: Boolean = false private var centerX: Float = 0F private var centerY: Float = 0F private var secondHandLengthRatio: Float = 0F private var minuteHandLengthRatio: Float = 0F private var hourHandLengthRatio: Float = 0F private lateinit var hourPaint: Paint private lateinit var minutePaint: Paint private lateinit var secondPaint: Paint private lateinit var tickAndCirclePaint: Paint private lateinit var backgroundPaint: Paint // Best practice is to always use black for watch face in ambient mode (saves battery // and prevents burn-in. private val backgroundAmbientPaint:Paint = Paint().apply { color = Color.BLACK } private var backgroundImageEnabled:Boolean = false private lateinit var backgroundBitmap: Bitmap private lateinit var grayBackgroundBitmap: Bitmap private var ambient: Boolean = false private var lowBitAmbient: Boolean = false private var burnInProtection: Boolean = false /* Handler to update the time once a second in interactive mode. */ private val updateTimeHandler = EngineHandler(this) private val timeZoneReceiver = object : BroadcastReceiver() { override fun onReceive(context: Context, intent: Intent) { calendar.timeZone = TimeZone.getDefault() invalidate() } } override fun onCreate(holder: SurfaceHolder) { super.onCreate(holder) analogWatchFaceStyle = getWatchFaceStyle() setWatchFaceStyle( WatchFaceStyle.Builder(this@AbstractKotlinWatchFace) .setAcceptsTapEvents(true) .build() ) calendar = Calendar.getInstance() initializeBackground() initializeWatchFace() } private fun initializeBackground() { backgroundImageEnabled = analogWatchFaceStyle.watchFaceBackgroundImage.backgroundImageResource != WatchFaceBackgroundImage.EMPTY_IMAGE_RESOURCE if (backgroundImageEnabled) { backgroundBitmap = BitmapFactory.decodeResource( resources, analogWatchFaceStyle.watchFaceBackgroundImage.backgroundImageResource ) } } private fun initializeWatchFace() { hourPaint = Paint().apply { color = analogWatchFaceStyle.watchFaceColors.main strokeWidth = analogWatchFaceStyle.watchFaceDimensions.hourHandWidth isAntiAlias = true strokeCap = Paint.Cap.ROUND setShadowLayer( analogWatchFaceStyle.watchFaceDimensions.shadowRadius, 0f, 0f, analogWatchFaceStyle.watchFaceColors.shadow ) } minutePaint = Paint().apply { color = analogWatchFaceStyle.watchFaceColors.main strokeWidth = analogWatchFaceStyle.watchFaceDimensions.minuteHandWidth isAntiAlias = true strokeCap = Paint.Cap.ROUND setShadowLayer( analogWatchFaceStyle.watchFaceDimensions.shadowRadius, 0f, 0f, analogWatchFaceStyle.watchFaceColors.shadow ) } secondPaint = Paint().apply { color = analogWatchFaceStyle.watchFaceColors.highlight strokeWidth = analogWatchFaceStyle.watchFaceDimensions.secondHandWidth isAntiAlias = true strokeCap = Paint.Cap.ROUND setShadowLayer( analogWatchFaceStyle.watchFaceDimensions.shadowRadius, 0f, 0f, analogWatchFaceStyle.watchFaceColors.shadow ) } tickAndCirclePaint = Paint().apply { color = analogWatchFaceStyle.watchFaceColors.main strokeWidth = analogWatchFaceStyle.watchFaceDimensions.secondHandWidth isAntiAlias = true style = Paint.Style.STROKE setShadowLayer( analogWatchFaceStyle.watchFaceDimensions.shadowRadius, 0f, 0f, analogWatchFaceStyle.watchFaceColors.shadow ) } backgroundPaint = Paint().apply { color = analogWatchFaceStyle.watchFaceColors.background } } override fun onDestroy() { updateTimeHandler.removeMessages(MSG_UPDATE_TIME) super.onDestroy() } override fun onPropertiesChanged(properties: Bundle) { super.onPropertiesChanged(properties) lowBitAmbient = properties.getBoolean( WatchFaceService.PROPERTY_LOW_BIT_AMBIENT, false ) burnInProtection = properties.getBoolean( WatchFaceService.PROPERTY_BURN_IN_PROTECTION, false ) } override fun onTimeTick() { super.onTimeTick() invalidate() } override fun onAmbientModeChanged(inAmbientMode: Boolean) { super.onAmbientModeChanged(inAmbientMode) ambient = inAmbientMode updateWatchHandStyle() // Check and trigger whether or not timer should be running (only // in active mode). updateTimer() } private fun updateWatchHandStyle() { if (ambient) { hourPaint.color = Color.WHITE minutePaint.color = Color.WHITE secondPaint.color = Color.WHITE tickAndCirclePaint.color = Color.WHITE hourPaint.isAntiAlias = false minutePaint.isAntiAlias = false secondPaint.isAntiAlias = false tickAndCirclePaint.isAntiAlias = false hourPaint.clearShadowLayer() minutePaint.clearShadowLayer() secondPaint.clearShadowLayer() tickAndCirclePaint.clearShadowLayer() } else { hourPaint.color = analogWatchFaceStyle.watchFaceColors.main minutePaint.color = analogWatchFaceStyle.watchFaceColors.main secondPaint.color = analogWatchFaceStyle.watchFaceColors.highlight tickAndCirclePaint.color = analogWatchFaceStyle.watchFaceColors.main hourPaint.isAntiAlias = true minutePaint.isAntiAlias = true secondPaint.isAntiAlias = true tickAndCirclePaint.isAntiAlias = true hourPaint.setShadowLayer( analogWatchFaceStyle.watchFaceDimensions.shadowRadius, 0f, 0f, analogWatchFaceStyle.watchFaceColors.shadow ) minutePaint.setShadowLayer( analogWatchFaceStyle.watchFaceDimensions.shadowRadius, 0f, 0f, analogWatchFaceStyle.watchFaceColors.shadow ) secondPaint.setShadowLayer( analogWatchFaceStyle.watchFaceDimensions.shadowRadius, 0f, 0f, analogWatchFaceStyle.watchFaceColors.shadow ) tickAndCirclePaint.setShadowLayer( analogWatchFaceStyle.watchFaceDimensions.shadowRadius, 0f, 0f, analogWatchFaceStyle.watchFaceColors.shadow ) } } override fun onInterruptionFilterChanged(interruptionFilter: Int) { super.onInterruptionFilterChanged(interruptionFilter) val inMuteMode = interruptionFilter == WatchFaceService.INTERRUPTION_FILTER_NONE /* Dim display in mute mode. */ if (muteMode != inMuteMode) { muteMode = inMuteMode hourPaint.alpha = if (inMuteMode) 100 else 255 minutePaint.alpha = if (inMuteMode) 100 else 255 secondPaint.alpha = if (inMuteMode) 80 else 255 invalidate() } } override fun onSurfaceChanged(holder: SurfaceHolder, format: Int, width: Int, height: Int) { super.onSurfaceChanged(holder, format, width, height) /* * Find the coordinates of the center point on the screen, and ignore the window * insets, so that, on round watches with a "chin", the watch face is centered on the * entire screen, not just the usable portion. */ centerX = width / 2f centerY = height / 2f /* * Calculate lengths of different hands based on watch screen size. */ secondHandLengthRatio = (centerX * analogWatchFaceStyle.watchFaceDimensions.secondHandRadiusRatio) minuteHandLengthRatio = (centerX * analogWatchFaceStyle.watchFaceDimensions.minuteHandRadiusRatio) hourHandLengthRatio = (centerX * analogWatchFaceStyle.watchFaceDimensions.hourHandRadiusRatio) if (backgroundImageEnabled) { // Scale loaded background image (more efficient) if surface dimensions change. val scale = width.toFloat() / backgroundBitmap.width.toFloat() backgroundBitmap = Bitmap.createScaledBitmap( backgroundBitmap, (backgroundBitmap.width * scale).toInt(), (backgroundBitmap.height * scale).toInt(), true ) /* * Create a gray version of the image only if it will look nice on the device in * ambient mode. That means we don't want devices that support burn-in * protection (slight movements in pixels, not great for images going all the way * to edges) and low ambient mode (degrades image quality). * * Also, if your watch face will know about all images ahead of time (users aren't * selecting their own photos for the watch face), it will be more * efficient to create a black/white version (png, etc.) and load that when * you need it. */ if (!burnInProtection && !lowBitAmbient) { initGrayBackgroundBitmap() } } } private fun initGrayBackgroundBitmap() { grayBackgroundBitmap = Bitmap.createBitmap( backgroundBitmap.width, backgroundBitmap.height, Bitmap.Config.ARGB_8888 ) val canvas = Canvas(grayBackgroundBitmap) val grayPaint = Paint() val colorMatrix = ColorMatrix() colorMatrix.setSaturation(0f) val filter = ColorMatrixColorFilter(colorMatrix) grayPaint.colorFilter = filter canvas.drawBitmap(backgroundBitmap, 0f, 0f, grayPaint) } override fun onDraw(canvas: Canvas, bounds: Rect) { val now = System.currentTimeMillis() calendar.timeInMillis = now drawBackground(canvas) drawWatchFace(canvas) } private fun drawBackground(canvas: Canvas) { if (ambient && (lowBitAmbient || burnInProtection)) { canvas.drawColor(backgroundAmbientPaint.color) } else if (ambient && backgroundImageEnabled) { canvas.drawBitmap(grayBackgroundBitmap, 0f, 0f, backgroundAmbientPaint) } else if (backgroundImageEnabled) { canvas.drawBitmap(backgroundBitmap, 0f, 0f, backgroundPaint) } else { canvas.drawColor(backgroundPaint.color) } } private fun drawWatchFace(canvas: Canvas) { /* * Draw ticks. Usually you will want to bake this directly into the photo, but in * cases where you want to allow users to select their own photos, this dynamically * creates them on top of the photo. */ val innerTickRadius = centerX - 10 val outerTickRadius = centerX for (tickIndex in 0..11) { val tickRot = (tickIndex.toDouble() * Math.PI * 2.0 / 12).toFloat() val innerX = Math.sin(tickRot.toDouble()).toFloat() * innerTickRadius val innerY = (-Math.cos(tickRot.toDouble())).toFloat() * innerTickRadius val outerX = Math.sin(tickRot.toDouble()).toFloat() * outerTickRadius val outerY = (-Math.cos(tickRot.toDouble())).toFloat() * outerTickRadius canvas.drawLine( centerX + innerX, centerY + innerY, centerX + outerX, centerY + outerY, tickAndCirclePaint ) } /* * These calculations reflect the rotation in degrees per unit of time, e.g., * 360 / 60 = 6 and 360 / 12 = 30. */ val seconds = calendar.get(Calendar.SECOND) + calendar.get(Calendar.MILLISECOND) / 1000f val secondsRotation = seconds * 6f val minutesRotation = calendar.get(Calendar.MINUTE) * 6f val hourHandOffset = calendar.get(Calendar.MINUTE) / 2f val hoursRotation = calendar.get(Calendar.HOUR) * 30 + hourHandOffset /* * Save the canvas state before we can begin to rotate it. */ canvas.save() val distanceFromCenterToArms = analogWatchFaceStyle.watchFaceDimensions.innerCircleRadius + analogWatchFaceStyle.watchFaceDimensions.innerCircleToArmsDistance canvas.rotate(hoursRotation, centerX, centerY) canvas.drawLine( centerX, centerY - distanceFromCenterToArms, centerX, centerY - hourHandLengthRatio, hourPaint ) canvas.rotate(minutesRotation - hoursRotation, centerX, centerY) canvas.drawLine( centerX, centerY - distanceFromCenterToArms, centerX, centerY - minuteHandLengthRatio, minutePaint ) /* * Ensure the "seconds" hand is drawn only when we are in interactive mode. * Otherwise, we only update the watch face once a minute. */ if (!ambient) { canvas.rotate(secondsRotation - minutesRotation, centerX, centerY) canvas.drawLine( centerX, centerY - distanceFromCenterToArms, centerX, centerY - secondHandLengthRatio, secondPaint ) } canvas.drawCircle( centerX, centerY, analogWatchFaceStyle.watchFaceDimensions.innerCircleRadius, tickAndCirclePaint ) /* Restore the canvas' original orientation. */ canvas.restore() } override fun onVisibilityChanged(visible: Boolean) { super.onVisibilityChanged(visible) if (visible) { registerReceiver() /* Update time zone in case it changed while we weren't visible. */ calendar.timeZone = TimeZone.getDefault() invalidate() } else { unregisterReceiver() } /* Check and trigger whether or not timer should be running (only in active mode). */ updateTimer() } private fun registerReceiver() { if (registeredTimeZoneReceiver) { return } registeredTimeZoneReceiver = true val filter = IntentFilter(Intent.ACTION_TIMEZONE_CHANGED) this@AbstractKotlinWatchFace.registerReceiver(timeZoneReceiver, filter) } private fun unregisterReceiver() { if (!registeredTimeZoneReceiver) { return } registeredTimeZoneReceiver = false this@AbstractKotlinWatchFace.unregisterReceiver(timeZoneReceiver) } /** * Starts/stops the [.updateTimeHandler] timer based on the state of the watch face. */ private fun updateTimer() { updateTimeHandler.removeMessages(MSG_UPDATE_TIME) if (shouldTimerBeRunning()) { updateTimeHandler.sendEmptyMessage(MSG_UPDATE_TIME) } } /** * Returns whether the [.updateTimeHandler] timer should be running. The timer * should only run in active mode. */ private fun shouldTimerBeRunning(): Boolean { return isVisible && !ambient } /** * Handle updating the time periodically in interactive mode. */ fun handleUpdateTimeMessage() { invalidate() if (shouldTimerBeRunning()) { val timeMs = System.currentTimeMillis() val delayMs = INTERACTIVE_UPDATE_RATE_MS - timeMs % INTERACTIVE_UPDATE_RATE_MS updateTimeHandler.sendEmptyMessageDelayed(MSG_UPDATE_TIME, delayMs) } } } }
kotlin
24
0.5893
100
38.044405
563
starcoderdata
package no.nav.syfo.papirsykmelding import no.nav.syfo.aksessering.db.oracle.getSykmeldingsDokument import no.nav.syfo.aksessering.db.oracle.updateDocument import no.nav.syfo.db.DatabaseOracle import no.nav.syfo.db.DatabasePostgres import no.nav.syfo.log import no.nav.syfo.model.toMap import no.nav.syfo.persistering.db.postgres.updateUtdypendeOpplysninger class SlettInformasjonService(private val databaseoracle: DatabaseOracle, private val databasePostgres: DatabasePostgres) { val sykmeldingId = "" val nySvartekst = "Tekst slettet pga feil tekst fra lege. Se sykmelding som erstatter denne for korrekt informasjon" fun start() { val result = databaseoracle.getSykmeldingsDokument(sykmeldingId) if (result.rows.isNotEmpty()) { log.info("updating sykmelding dokument with sykmelding id {}", sykmeldingId) val document = result.rows.first() if (document != null) { val utdypendeOpplysning64 = document.utdypendeOpplysninger.spmGruppe.find { it.spmGruppeId == "6.4" } if (utdypendeOpplysning64 == null) { log.error("Fant ikke utdypende opplysning 6.4!") throw IllegalStateException("Fant ikke utdypende opplysning 6.4!") } else { val utdypendeOpplysning641 = utdypendeOpplysning64.spmSvar.find { it.spmId == "6.4.1" } if (utdypendeOpplysning641 == null) { log.error("Fant ikke utdypende opplysning 6.4.1!") throw IllegalStateException("Fant ikke utdypende opplysning 6.4.1!") } else { utdypendeOpplysning641.svarTekst = nySvartekst databaseoracle.updateDocument(document, sykmeldingId) databasePostgres.updateUtdypendeOpplysninger(sykmeldingId, document.utdypendeOpplysninger.toMap()) } } } } else { log.info("could not find sykmelding with id {}", sykmeldingId) } } }
kotlin
26
0.640977
123
46.477273
44
starcoderdata
package com.genesys.cloud.messenger.androidcomposeprototype.ui.testbed import android.content.Context import android.util.Log import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.setValue import androidx.lifecycle.ViewModel import com.genesys.cloud.messenger.androidcomposeprototype.BuildConfig import com.genesys.cloud.messenger.transport.core.Attachment.State.Detached import com.genesys.cloud.messenger.transport.core.Configuration import com.genesys.cloud.messenger.transport.core.MessageEvent import com.genesys.cloud.messenger.transport.core.MessageEvent.AttachmentUpdated import com.genesys.cloud.messenger.transport.core.MessagingClient import com.genesys.cloud.messenger.transport.core.MessagingClient.State import com.genesys.cloud.messenger.transport.core.MobileMessenger import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.Job import kotlinx.coroutines.launch import kotlinx.coroutines.runBlocking import kotlinx.coroutines.withContext private const val ATTACHMENT_FILE_NAME = "test_asset.png" class TestBedViewModel : ViewModel(), CoroutineScope { override val coroutineContext = Dispatchers.IO + Job() private val TAG = TestBedViewModel::class.simpleName private lateinit var client: MessagingClient private lateinit var attachment: ByteArray private val attachedIds = mutableListOf<String>() var command: String by mutableStateOf("") private set var commandWaiting: Boolean by mutableStateOf(false) private set var socketMessage: String by mutableStateOf("") private set var clientState: State by mutableStateOf(State.Idle) private set var deploymentId: String by mutableStateOf("") private set var region: String by mutableStateOf("inindca") private set val regions = listOf("inindca") suspend fun init(context: Context) { val mmsdkConfiguration = Configuration( deploymentId = BuildConfig.DEPLOYMENT_ID, domain = BuildConfig.DEPLOYMENT_DOMAIN, tokenStoreKey = "com.genesys.cloud.messenger", logging = true ) client = MobileMessenger.createMessagingClient( context = context, configuration = mmsdkConfiguration, ) with(client) { stateListener = { runBlocking { onClientState(it) } } messageListener = { onEvent(it) } clientState = client.currentState } withContext(Dispatchers.IO) { context.assets.open(ATTACHMENT_FILE_NAME).use { inputStream -> inputStream.readBytes().also { attachment = it } } } } fun onCommandChanged(newCommand: String) { command = newCommand } fun onDeploymentIdChanged(newDeploymentId: String) { deploymentId = newDeploymentId } fun onRegionChanged(newRegion: String) { region = newRegion } fun onCommandSend() = launch(Dispatchers.IO) { withContext(Dispatchers.Main) { commandWaiting = true } val components = command.split(" ", limit = 2) when (components.firstOrNull()) { "connect" -> doConnect() "bye" -> doDisconnect() "configure" -> doConfigureSession() "send" -> doSendMessage(components) "history" -> fetchNextPage() "healthCheck" -> doSendHealthCheck() "attach" -> doAttach() "detach" -> doDetach(components) "deployment" -> doDeployment() "clearConversation" -> doClearConversation() else -> { Log.e(TAG, "Invalid command") withContext(Dispatchers.Main) { commandWaiting = false } } } } private suspend fun doDeployment() { try { onSocketMessageReceived( MobileMessenger.fetchDeploymentConfig( BuildConfig.DEPLOYMENT_DOMAIN, BuildConfig.DEPLOYMENT_ID, true, ).toString() ) } catch (t: Throwable) { handleException(t, "fetch deployment config") } } private suspend fun doConnect() { try { client.connect() } catch (t: Throwable) { handleException(t, "connect") } } private suspend fun doDisconnect() { try { client.disconnect() } catch (t: Throwable) { handleException(t, "disconnect") } } private suspend fun doConfigureSession() { try { client.configureSession() } catch (t: Throwable) { handleException(t, "configure session") } } private suspend fun doSendMessage(components: List<String>) { try { val message = components.getOrNull(1) ?: "" client.sendMessage(message) } catch (t: Throwable) { handleException(t, "send message") } } private suspend fun fetchNextPage() { try { client.fetchNextPage() commandWaiting = false } catch (t: Throwable) { handleException(t, "request history") } } private suspend fun doSendHealthCheck() { try { client.sendHealthCheck() } catch (t: Throwable) { handleException(t, "send health check") } } private suspend fun doAttach() { try { client.attach( attachment, ATTACHMENT_FILE_NAME ) { progress -> println("Attachment upload progress: $progress") }.also { attachedIds.add(it) } } catch (t: Throwable) { handleException(t, "attach") } } private suspend fun doDetach(components: List<String>) { try { val attachmentId = components.getOrNull(1) ?: "" client.detach(attachmentId) } catch (t: Throwable) { handleException(t, "detach") } } private suspend fun doClearConversation() { client.invalidateConversationCache() clearCommand() } private suspend fun onClientState(state: State) { Log.v(TAG, "onClientState(state = $state)") clientState = state val statePayloadMessage = when (state) { is State.Configured -> "connected: ${state.connected}, newSession: ${state.newSession}" is State.Closing -> "code: ${state.code}, reason: ${state.reason}" is State.Closed -> "code: ${state.code}, reason: ${state.reason}" is State.Error -> "code: ${state.code}, message: ${state.message}" else -> "" } onSocketMessageReceived(statePayloadMessage) withContext(Dispatchers.Main) { commandWaiting = false } } private suspend fun onSocketMessageReceived(message: String) { Log.v(TAG, "onSocketMessageReceived(message = $message)") clearCommand() withContext(Dispatchers.Main) { socketMessage = message } } private suspend fun clearCommand() { withContext(Dispatchers.Main) { command = "" commandWaiting = false } } private suspend fun handleException(t: Throwable, action: String) { val failMessage = "Failed to $action" Log.e(TAG, failMessage, t) onSocketMessageReceived(t.message ?: failMessage) withContext(Dispatchers.Main) { commandWaiting = false } } private fun onEvent(event: MessageEvent) { val eventMessage = when (event) { is MessageEvent.MessageUpdated -> event.message.toString() is MessageEvent.MessageInserted -> event.message.toString() is MessageEvent.HistoryFetched -> "start of conversation: ${event.startOfConversation}, messages: ${event.messages}" is AttachmentUpdated -> { when (event.attachment.state) { Detached -> { attachedIds.remove(event.attachment.id) event.attachment.toString() } else -> event.attachment.toString() } } else -> event.toString() } launch { onSocketMessageReceived(eventMessage) } } }
kotlin
23
0.599371
128
31.782443
262
starcoderdata
/** * Copyright 2019 <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.num4k.tensor class TransposeOneDimensionalTensor<T>(private val original: Tensor<T>) : Tensor<T>() { init { if (original.rank() != 1) { throw IllegalArgumentException("The original tensor must be rank one, but it's ${original.rank()}") } } private val d = intArrayOf(1, original.dimension()[0]) override fun get(vararg position: Int): T? { if (position.size != 2) { throw IndexOutOfBoundsException("Length of position must be 2, but it's ${position.size}") } if (position[0] != 0) { throw IndexOutOfBoundsException("Index is ${position[0]} which is not zero") } return original[position[1]] } override fun set(value: T?, position: IntArray) { if (position.size != 2) { throw IndexOutOfBoundsException("Length of position must be 2, but it's ${position.size}") } if (position[0] != 0) { throw IndexOutOfBoundsException("Index is ${position[0]} which is not zero") } original[position[1]] = value } override fun rank(): Int = 2 override fun dimension(): IntArray = d override fun default(): T? = original.default() }
kotlin
18
0.644948
111
33.188679
53
starcoderdata
/* * Copyright 2018 Google, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.plaidapp.designernews.data.votes import io.plaidapp.core.data.Result import io.plaidapp.designernews.data.votes.model.UpvoteCommentRequest import io.plaidapp.designernews.data.votes.model.UpvoteStoryRequest import io.plaidapp.core.util.safeApiCall import io.plaidapp.designernews.data.api.DesignerNewsService import java.io.IOException import javax.inject.Inject /** * Class that works with the Designer News API to up/down vote comments and stories */ class VotesRemoteDataSource @Inject constructor(private val service: DesignerNewsService) { suspend fun upvoteStory(storyId: Long, userId: Long) = safeApiCall( call = { requestUpvoteStory(storyId, userId) }, errorMessage = "Unable to upvote story" ) private suspend fun requestUpvoteStory(storyId: Long, userId: Long): Result<Unit> { val request = UpvoteStoryRequest(storyId, userId) val response = service.upvoteStory(request) return if (response.isSuccessful) { Result.Success(Unit) } else { Result.Error( IOException( "Unable to upvote story ${response.code()} ${response.errorBody()?.string()}" ) ) } } suspend fun upvoteComment(commentId: Long, userId: Long) = safeApiCall( call = { requestUpvoteComment(commentId, userId) }, errorMessage = "Unable to upvote comment" ) private suspend fun requestUpvoteComment(commentId: Long, userId: Long): Result<Unit> { val request = UpvoteCommentRequest(commentId, userId) val response = service.upvoteComment(request) return if (response.isSuccessful) { Result.Success(Unit) } else { Result.Error( IOException( "Unable to upvote comment ${response.code()} ${response.errorBody()?.string()}" ) ) } } }
kotlin
25
0.672189
99
35.73913
69
starcoderdata
<reponame>ramesh-kr/tivi /* * Copyright 2018 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package app.tivi.utils import app.tivi.data.TiviDatabase import app.tivi.data.entities.Episode import app.tivi.data.entities.EpisodeWatchEntry import app.tivi.data.entities.FollowedShowEntry import app.tivi.data.entities.PendingAction import app.tivi.data.entities.Season import app.tivi.data.entities.TiviShow import org.threeten.bp.OffsetDateTime const val showId = 1L val show = TiviShow(id = showId, title = "Down Under", traktId = 243) const val show2Id = 2L val show2 = TiviShow(id = show2Id, title = "G'day mate", traktId = 546) internal suspend fun insertShow(db: TiviDatabase) = db.showDao().insert(show) internal suspend fun deleteShow(db: TiviDatabase) = db.showDao().delete(show) const val s1_id = 1L val s1 = Season( id = s1_id, showId = showId, title = "Season 1", number = 1, traktId = 5443 ) const val s2_id = 2L val s2 = Season( id = s2_id, showId = showId, title = "Season 2", number = 2, traktId = 5434 ) const val s0_id = 3L val s0 = Season( id = s0_id, showId = showId, title = "Specials", number = Season.NUMBER_SPECIALS, traktId = 7042 ) val s1e1 = Episode(id = 1, title = "Kangaroo Court", seasonId = s1.id, number = 0, traktId = 59830) val s1e2 = Episode(id = 2, title = "Bushtucker", seasonId = s1.id, number = 1, traktId = 33435) val s1e3 = Episode(id = 3, title = "Wallaby Bungee", seasonId = s1.id, number = 2, traktId = 44542) val s2e1 = Episode(id = 4, title = "Noosa Pool", seasonId = s2.id, number = 0, traktId = 5656) val s2e2 = Episode(id = 5, title = "<NAME>", seasonId = s2.id, number = 1, traktId = 8731) val s1_episodes = listOf(s1e1, s1e2, s1e3) val s2_episodes = listOf(s2e1, s2e2) const val s1e1w_id = 1L val s1e1w = EpisodeWatchEntry( id = s1e1w_id, watchedAt = OffsetDateTime.now(), episodeId = s1e1.id, traktId = 435214 ) const val s1e1w2_id = 2L val s1e1w2 = s1e1w.copy(id = s1e1w2_id, traktId = 4385783) val episodeWatch2PendingSend = s1e1w2.copy(pendingAction = PendingAction.UPLOAD) val episodeWatch2PendingDelete = s1e1w2.copy(pendingAction = PendingAction.DELETE) internal suspend fun insertFollowedShow(db: TiviDatabase) = db.followedShowsDao().insert(followedShow1) const val followedShowId = 1L val followedShow1 = FollowedShowEntry(followedShowId, showId) val followedShow1PendingDelete = followedShow1.copy(pendingAction = PendingAction.DELETE) val followedShow1PendingUpload = followedShow1.copy(pendingAction = PendingAction.UPLOAD) const val followedShow2Id = 2L val followedShow2 = FollowedShowEntry(followedShow2Id, show2Id)
kotlin
9
0.708919
103
32.418367
98
starcoderdata
/* * Copyright 2020 Google LLC * Copyright 2010-2020 JetBrains s.r.o. and Kotlin Programming Language contributors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.devtools.ksp.symbol.impl.kotlin import com.google.devtools.ksp.symbol.KSClassifierReference import com.google.devtools.ksp.symbol.KSTypeArgument import com.google.devtools.ksp.symbol.Location import com.google.devtools.ksp.symbol.Origin import com.google.devtools.ksp.symbol.impl.KSObjectCache import com.google.devtools.ksp.symbol.impl.toLocation import org.jetbrains.kotlin.psi.* class KSClassifierReferenceImpl private constructor(val ktUserType: KtUserType) : KSClassifierReference { companion object : KSObjectCache<KtUserType, KSClassifierReferenceImpl>() { fun getCached(ktUserType: KtUserType) = cache.getOrPut(ktUserType) { KSClassifierReferenceImpl(ktUserType) } } override val origin = Origin.KOTLIN override val location: Location by lazy { ktUserType.toLocation() } override val typeArguments: List<KSTypeArgument> by lazy { ktUserType.typeArguments.map { KSTypeArgumentKtImpl.getCached(it) } } override fun referencedName(): String { return ktUserType.referencedName ?: "" } override val qualifier: KSClassifierReference? by lazy { if (ktUserType.qualifier == null) { null } else { KSClassifierReferenceImpl.getCached(ktUserType.qualifier!!) } } override fun toString() = referencedName() }
kotlin
20
0.739941
116
34.754386
57
starcoderdata
package esw.ocs.dsl.highlevel.models import csw.params.core.models.* import csw.prefix.models.Subsystem // ******** Helpers to access values from ExposureId ******** val ExposureId.obsId: ObsId? get() = obsId().getOrElse(null) val ExposureId.det: String get() = det() val ExposureId.subsystem: Subsystem get() = subsystem() val ExposureId.typLevel: TYPLevel get() = typLevel() val ExposureId.exposureNumber: ExposureNumber get() = exposureNumber() // *********** Helpers to create models for ExposureId ************* fun TYPLevel(value: String): TYPLevel = TYPLevel.apply(value) fun ExposureNumber(value: String): ExposureNumber = ExposureNumber.apply(value) fun ExposureId(value: String): ExposureId = ExposureId.fromString(value)
kotlin
9
0.736054
79
44.9375
16
starcoderdata
package pers.acp.test.kotlin.test.google import org.apache.commons.codec.binary.Base32 import org.apache.commons.codec.binary.Base64 import org.apache.commons.codec.binary.Hex import java.math.BigInteger import java.security.SecureRandom import javax.crypto.Mac import javax.crypto.spec.SecretKeySpec import kotlin.experimental.and /** * @author zhangbin * @date 16/03/2018 * @since JDK 11 */ object GoogleAuthenticatorUtils { /** * 生成随机密钥 */ fun generateSecretKey(): String { val sr: SecureRandom? = SecureRandom.getInstance("SHA1PRNG") sr!!.setSeed(Base64.decodeBase64("g8GjEvTbW5oVSV7avLBdwIHqGlUYNzK<KEY>")) return String(Base32().encode(sr.generateSeed(10))).toUpperCase() } /** * 进行验证 * @param secretKey 密钥 * @param code 验证码 * @param crypto hash算法,默认 HmacSHA1,支持:HmacSHA1、HmacSHA256、HmacSHA512 * @param timeExcursionConfig 时间偏移量,默认 1 * 用于防止客户端时间不精确导致生成的TOTP与服务器端的TOTP一直不一致 * 如果为0,当前时间为 10:10:15 * 则表明在 10:10:00-10:10:30 之间生成的TOTP 能校验通过 * 如果为1,则表明在 * 10:09:30-10:10:00 * 10:10:00-10:10:30 * 10:10:30-10:11:00 之间生成的TOTP 能校验通过 * 以此类推 */ fun verify( secretKey: String, code: String, crypto: String = "HmacSHA1", timeExcursionConfig: String? = "1" ): Boolean { setupParam(crypto, timeExcursionConfig) val time = System.currentTimeMillis() / 1000 / 30 for (i in -timeExcursion..timeExcursion) { val totp = getTOTP(secretKey, time + i) println("vtotp=$totp") if (code == totp) { return true } } return false } /** * 参数设置 * @param crypto hash算法 * @param timeExcursionConfig 时间偏移量 */ private fun setupParam(crypto: String, timeExcursionConfig: String?) { GoogleAuthenticatorUtils.crypto = crypto if (!timeExcursionConfig.isNullOrBlank()) { timeExcursion = timeExcursionConfig.toInt() } } /** * 计算动态随机码 * @param secretKey 密钥 * @param time 时间戳 */ private fun getTOTP(secretKey: String, time: Long): String = generateTOTP( Hex.encodeHexString(Base32().decode(secretKey.toUpperCase())), java.lang.Long.toHexString(time), 6 ) /** * 生成动态随机码 * @param key 密钥 * @param timeStr 时间戳 * @parma returnDigits 随机码位数 */ private fun generateTOTP(key: String, timeStr: String, returnDigits: Int): String { var time = timeStr while (time.length < 16) time = "0$time" val hash = dpHash(hexStr2Bytes(key), hexStr2Bytes(time)) val offset = (hash[hash.size - 1] and 0xf).toInt() val binary = ((hash[offset].toInt() and 0x7f) shl 24) or ((hash[offset + 1].toInt() and 0xff) shl 16) or ((hash[offset + 2].toInt() and 0xff) shl 8) or (hash[offset + 3].toInt() and 0xff) val digitsPower = intArrayOf(1, 10, 100, 1000, 10000, 100000, 1000000, 10000000, 100000000) val otp = binary % digitsPower[returnDigits] var result = otp.toString() while (result.length < returnDigits) { result = "0$result" } return result } /** * 十六进制字符串转字节数组 */ private fun hexStr2Bytes(hex: String): ByteArray { val bArray = BigInteger("10$hex", 16).toByteArray() val ret = ByteArray(bArray.size - 1) for (i in ret.indices) ret[i] = bArray[i + 1] return ret } /** * 计算mac */ private fun dpHash(keyBytes: ByteArray, text: ByteArray): ByteArray = Mac.getInstance(crypto).let { it.init(SecretKeySpec(keyBytes, "RAW")) it.doFinal(text) } /** * 时间前后偏移量 * 用于防止客户端时间不精确导致生成的TOTP与服务器端的TOTP一直不一致 * 如果为0,当前时间为 10:10:15 * 则表明在 10:10:00-10:10:30 之间生成的TOTP 能校验通过 * 如果为1,则表明在 * 10:09:30-10:10:00 * 10:10:00-10:10:30 * 10:10:30-10:11:00 之间生成的TOTP 能校验通过 * 以此类推 */ private var timeExcursion: Int = 1 /** * 计算随机码mac算法 * 支持:HmacSHA1、HmacSHA256、HmacSHA512 */ private var crypto = "HmacSHA1" }
kotlin
21
0.591928
99
27.635135
148
starcoderdata
<reponame>jmanday/Commerce package com.manday.management import java.util.regex.Pattern private const val regex = "^(1[0-2]|0[1-9])/(3[01]|[12][0-9]|0[1-9])/[0-9]{4}$" private val pattern= Pattern.compile(regex) fun String.isDateValidate(): Boolean { val matcher = pattern.matcher(this) return (this.isNotEmpty() && matcher.matches()) }
kotlin
10
0.697406
79
28
12
starcoderdata
<reponame>lukaswelte/kotlin<gh_stars>1-10 // IGNORE_BACKEND: JVM_IR // IGNORE_BACKEND: JS_IR // TODO: muted automatically, investigate should it be ran for JS or not // IGNORE_BACKEND: JS, NATIVE // WITH_REFLECT import kotlin.test.assertEquals @Retention(AnnotationRetention.SOURCE) annotation class SourceAnno @Retention(AnnotationRetention.BINARY) annotation class BinaryAnno @Retention(AnnotationRetention.RUNTIME) annotation class RuntimeAnno @SourceAnno @BinaryAnno @RuntimeAnno fun box(): String { assertEquals(listOf(RuntimeAnno::class.java), ::box.annotations.map { it.annotationClass.java }) return "OK" }
kotlin
16
0.780604
100
23.192308
26
starcoderdata
package net.corda.node import com.typesafe.config.Config import com.typesafe.config.ConfigException import com.typesafe.config.ConfigFactory import net.corda.cliutils.CommonCliConstants.BASE_DIR import net.corda.common.configuration.parsing.internal.Configuration import net.corda.common.validation.internal.Validated import net.corda.common.validation.internal.Validated.Companion.invalid import net.corda.common.validation.internal.Validated.Companion.valid import net.corda.core.internal.div import net.corda.core.utilities.loggerFor import net.corda.node.services.config.ConfigHelper import net.corda.node.services.config.NodeConfiguration import net.corda.node.services.config.Valid import net.corda.node.services.config.parseAsNodeConfiguration import net.corda.nodeapi.internal.config.UnknownConfigKeysPolicy import picocli.CommandLine.Option import java.nio.file.Path import java.nio.file.Paths open class SharedNodeCmdLineOptions { private companion object { private val logger by lazy { loggerFor<SharedNodeCmdLineOptions>() } } @Option( names = ["-b", BASE_DIR], description = ["The node working directory where all the files are kept."] ) var baseDirectory: Path = Paths.get(".").toAbsolutePath().normalize() @Option( names = ["-f", "--config-file"], description = ["The path to the config file. By default this is node.conf in the base directory."] ) private var _configFile: Path? = null val configFile: Path get() = _configFile ?: (baseDirectory / "node.conf") @Option( names = ["--on-unknown-config-keys"], description = ["How to behave on unknown node configuration. \${COMPLETION-CANDIDATES}"] ) var unknownConfigKeysPolicy: UnknownConfigKeysPolicy = UnknownConfigKeysPolicy.FAIL @Option( names = ["-d", "--dev-mode"], description = ["Runs the node in development mode. Unsafe for production."] ) var devMode: Boolean? = null open fun parseConfiguration(configuration: Config): Valid<NodeConfiguration> { val option = Configuration.Options(strict = unknownConfigKeysPolicy == UnknownConfigKeysPolicy.FAIL) return configuration.parseAsNodeConfiguration(option) } open fun rawConfiguration(): Validated<Config, ConfigException> { return try { valid(ConfigHelper.loadConfig(baseDirectory, configFile)) } catch (e: ConfigException) { return invalid(e) } } fun copyFrom(other: SharedNodeCmdLineOptions) { baseDirectory = other.baseDirectory _configFile = other._configFile unknownConfigKeysPolicy= other.unknownConfigKeysPolicy devMode = other.devMode } fun logRawConfigurationErrors(errors: Set<ConfigException>) { if (errors.isNotEmpty()) { logger.error("There were error(s) while attempting to load the node configuration:") } errors.forEach { error -> when (error) { is ConfigException.IO -> logger.error(configFileNotFoundMessage(configFile, error.cause)) else -> logger.error(error.message) } } } private fun configFileNotFoundMessage(configFile: Path, cause: Throwable?): String { return """ Unable to load the node config file from '$configFile'. ${cause?.message?.let { "Cause: $it" } ?: ""} Try setting the --base-directory flag to change which directory the node is looking in, or use the --config-file flag to specify it explicitly. """.trimIndent() } } class InitialRegistrationCmdLineOptions : SharedNodeCmdLineOptions() { override fun parseConfiguration(configuration: Config): Valid<NodeConfiguration> { return super.parseConfiguration(configuration).doIfValid { config -> require(!config.devMode || config.devModeOptions?.allowCompatibilityZone == true) { "Cannot perform initial registration when 'devMode' is true, unless 'devModeOptions.allowCompatibilityZone' is also true." } @Suppress("DEPRECATION") require(config.compatibilityZoneURL != null || config.networkServices != null) { "compatibilityZoneURL or networkServices must be present in the node configuration file in registration mode." } } } } open class NodeCmdLineOptions : SharedNodeCmdLineOptions() { @Option( names = ["--sshd"], description = ["If set, enables SSH server for node administration."] ) var sshdServer: Boolean = false @Option( names = ["--sshd-port"], description = ["The port to start the SSH server on, if enabled."] ) var sshdServerPort: Int = 2222 @Option( names = ["-n", "--no-local-shell"], description = ["Do not start the embedded shell locally."] ) var noLocalShell: Boolean = false @Option( names = ["--just-generate-node-info"], description = ["DEPRECATED. Performs the node start-up tasks necessary to generate the nodeInfo file, saves it to disk, then exits."], hidden = true ) var justGenerateNodeInfo: Boolean = false @Option( names = ["--just-generate-rpc-ssl-settings"], description = ["DEPRECATED. Generates the SSL key and trust stores for a secure RPC connection."], hidden = true ) var justGenerateRpcSslCerts: Boolean = false @Option( names = ["--clear-network-map-cache"], description = ["DEPRECATED. Clears local copy of network map, on node startup it will be restored from server or file system."], hidden = true ) var clearNetworkMapCache: Boolean = false @Option( names = ["--initial-registration"], description = ["DEPRECATED. Starts initial node registration with Corda network to obtain certificate from the permissioning server."], hidden = true ) var isRegistration: Boolean = false @Option( names = ["-t", "--network-root-truststore"], description = ["DEPRECATED. Network root trust store obtained from network operator."], hidden = true ) var networkRootTrustStorePathParameter: Path? = null @Option( names = ["-p", "--network-root-truststore-password"], description = ["DEPRECATED. Network root trust store password obtained from network operator."], hidden = true ) var networkRootTrustStorePassword: String? = null override fun parseConfiguration(configuration: Config): Valid<NodeConfiguration> { return super.parseConfiguration(configuration).doIfValid { config -> if (isRegistration) { @Suppress("DEPRECATION") require(config.compatibilityZoneURL != null || config.networkServices != null) { "compatibilityZoneURL or networkServices must be present in the node configuration file in registration mode." } } } } override fun rawConfiguration(): Validated<Config, ConfigException> { val configOverrides = mutableMapOf<String, Any>() configOverrides += "noLocalShell" to noLocalShell if (sshdServer) { configOverrides += "sshd" to mapOf("port" to sshdServerPort.toString()) } devMode?.let { configOverrides += "devMode" to it } return try { valid(ConfigHelper.loadConfig(baseDirectory, configFile, configOverrides = ConfigFactory.parseMap(configOverrides))) } catch (e: ConfigException) { return invalid(e) } } } data class NodeRegistrationOption(val networkRootTrustStorePath: Path, val networkRootTrustStorePassword: String)
kotlin
25
0.654243
147
39.111111
198
starcoderdata
<reponame>EddieRingle/kotlin // WITH_RUNTIME // SUGGESTED_RETURN_TYPES: kotlin.Boolean?, kotlin.Boolean // PARAM_DESCRIPTOR: value-parameter it: kotlin.collections.Map.Entry<(Boolean..Boolean?), (Boolean..Boolean?)> defined in test.<anonymous> // PARAM_TYPES: kotlin.collections.Map.Entry<(Boolean..Boolean?), (Boolean..Boolean?)> fun test() { J.getMap().filter { <selection>it.key</selection> } }
kotlin
12
0.733167
139
49.25
8
starcoderdata
<filename>libraries/stdlib/js-ir/runtime/coreRuntime.kt /* * Copyright 2010-2018 JetBrains s.r.o. and Kotlin Programming Language contributors. * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ package kotlin.js import kotlin.js.internal.BitUtils fun equals(obj1: dynamic, obj2: dynamic): Boolean { if (obj1 == null) { return obj2 == null } if (obj2 == null) { return false } if (jsTypeOf(obj1) == "object" && jsTypeOf(obj1.equals) == "function") { return (obj1.equals)(obj2) } if (obj1 !== obj1) { return obj2 !== obj2 } if (jsTypeOf(obj1) == "number" && jsTypeOf(obj2) == "number") { return obj1 === obj2 && (obj1 !== 0 || 1.asDynamic() / obj1 === 1.asDynamic() / obj2) } return obj1 === obj2 } fun toString(o: dynamic): String = when { o == null -> "null" isArrayish(o) -> "[...]" else -> (o.toString)().unsafeCast<String>() } fun anyToString(o: dynamic): String = js("Object").prototype.toString.call(o) private fun hasOwnPrototypeProperty(o: Any, name: String): Boolean { return JsObject.getPrototypeOf(o).hasOwnProperty(name).unsafeCast<Boolean>() } fun hashCode(obj: dynamic): Int { if (obj == null) return 0 return when (jsTypeOf(obj)) { "object" -> if ("function" === jsTypeOf(obj.hashCode)) (obj.hashCode)() else getObjectHashCode(obj) "function" -> getObjectHashCode(obj) "number" -> BitUtils.getNumberHashCode(obj) "boolean" -> if(obj.unsafeCast<Boolean>()) 1 else 0 else -> getStringHashCode(js("String(obj)")) } } private var POW_2_32 = 4294967296 private var OBJECT_HASH_CODE_PROPERTY_NAME = "kotlinHashCodeValue$" fun getObjectHashCode(obj: dynamic): Int { if (!jsIn(OBJECT_HASH_CODE_PROPERTY_NAME, obj)) { var hash = jsBitwiseOr(js("Math").random() * POW_2_32, 0) // Make 32-bit singed integer. var descriptor = js("new Object()") descriptor.value = hash descriptor.enumerable = false js("Object").defineProperty(obj, OBJECT_HASH_CODE_PROPERTY_NAME, descriptor) } return obj[OBJECT_HASH_CODE_PROPERTY_NAME].unsafeCast<Int>(); } fun getStringHashCode(str: String): Int { var hash = 0 val length: Int = str.length // TODO: Implement WString.length for (i in 0..length-1) { val code: Int = str.asDynamic().charCodeAt(i) hash = hash * 31 + code } return hash } fun identityHashCode(obj: Any?): Int = getObjectHashCode(obj) internal fun captureStack(instance: Throwable) { if (js("Error").captureStackTrace != null) { js("Error").captureStackTrace(instance, instance::class.js) } else { instance.asDynamic().stack = js("new Error()").stack } } internal fun newThrowable(message: String?, cause: Throwable?): Throwable { val throwable = js("new Error()") throwable.message = message ?: cause?.toString() ?: undefined throwable.cause = cause throwable.name = "Throwable" return throwable.unsafeCast<Throwable>() } internal fun extendThrowable(this_: dynamic, message: String?, cause: Throwable?) { js("Error").call(this_) if (!hasOwnPrototypeProperty(this_, "message")) { this_.message = message ?: cause?.toString() ?: undefined } if (!hasOwnPrototypeProperty(this_, "cause")) { this_.cause = cause } this_.name = JsObject.getPrototypeOf(this_).constructor.name captureStack(this_) } @JsName("Object") internal external class JsObject { companion object { fun getPrototypeOf(obj: Any?): dynamic } } internal fun <T, R> boxIntrinsic(x: T): R = error("Should be lowered") internal fun <T, R> unboxIntrinsic(x: T): R = error("Should be lowered")
kotlin
19
0.641073
115
30.429752
121
starcoderdata
<reponame>Mhynlo/yubioath-android package com.yubico.yubioath.ui import android.content.Context import android.content.Intent import android.content.SharedPreferences import android.nfc.NfcAdapter import android.os.Build import android.os.Bundle import android.util.Log import android.view.WindowManager import androidx.appcompat.app.AppCompatActivity import androidx.lifecycle.Observer import androidx.lifecycle.ViewModelProviders import androidx.preference.PreferenceManager import com.yubico.yubikit.YubiKitManager import com.yubico.yubikit.application.ApduException import com.yubico.yubikit.application.oath.OathApplication import com.yubico.yubikit.transport.OnYubiKeyListener import com.yubico.yubikit.transport.YubiKeyTransport import com.yubico.yubikit.transport.nfc.NordpolNfcDispatcher import com.yubico.yubioath.R import com.yubico.yubioath.client.KeyManager import com.yubico.yubioath.client.OathClient import com.yubico.yubioath.exc.PasswordRequiredException import com.yubico.yubioath.keystore.ClearingMemProvider import com.yubico.yubioath.keystore.KeyStoreProvider import com.yubico.yubioath.keystore.SharedPrefProvider import kotlinx.coroutines.* import kotlinx.coroutines.android.asCoroutineDispatcher import org.jetbrains.anko.toast import kotlin.coroutines.CoroutineContext abstract class BaseActivity<T : BaseViewModel>(private var modelClass: Class<T>) : AppCompatActivity(), CoroutineScope, OnYubiKeyListener { companion object { private const val SP_STORED_AUTH_KEYS = "com.yubico.yubioath.SP_STORED_AUTH_KEYS" private val MEM_STORE = ClearingMemProvider() } protected lateinit var viewModel: T protected val prefs: SharedPreferences by lazy { PreferenceManager.getDefaultSharedPreferences(this) } private lateinit var job: Job override val coroutineContext: CoroutineContext get() = Dispatchers.Main + job private lateinit var yubiKitManager: YubiKitManager private lateinit var nfcDispatcher: NordpolNfcDispatcher private lateinit var exec: CoroutineDispatcher protected val keyManager: KeyManager by lazy { KeyManager( if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { KeyStoreProvider() } else { SharedPrefProvider(getSharedPreferences(SP_STORED_AUTH_KEYS, Context.MODE_PRIVATE)) }, MEM_STORE ) } override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) job = Job() if (prefs.getBoolean("hideThumbnail", true)) { window.setFlags(WindowManager.LayoutParams.FLAG_SECURE, WindowManager.LayoutParams.FLAG_SECURE) } if (prefs.getString("themeSelect", null) == "Light"){ setTheme(R.style.AppThemeLight) } else if (prefs.getString("themeSelect", null) == "Dark") { setTheme(R.style.AppThemeDark) } else if (prefs.getString("themeSelect", null) == "AMOLED") { setTheme(R.style.AppThemeAmoled) } viewModel = ViewModelProviders.of(this).get(modelClass) nfcDispatcher = NordpolNfcDispatcher(this) { it.enableReaderMode(!prefs.getBoolean("disableNfcReaderMode", false)).enableUnavailableNfcUserPrompt(false) } yubiKitManager = YubiKitManager(this, null, nfcDispatcher) exec = yubiKitManager.handler.asCoroutineDispatcher() yubiKitManager.setOnYubiKeyListener(this) if (intent.action == NfcAdapter.ACTION_NDEF_DISCOVERED) { nfcDispatcher.interceptIntent(intent) } viewModel.needsDevice.observe(this, Observer { if (it) { yubiKitManager.triggerOnYubiKey() } }) } override fun onYubiKey(transport: YubiKeyTransport?) { transport?.let { launch(exec) { useTransport(it) } } } open suspend fun useTransport(transport: YubiKeyTransport) { try { transport.connect().use { viewModel.onClient(OathClient(it, keyManager)) } } catch (e: PasswordRequiredException) { coroutineScope { launch(Dispatchers.Main) { supportFragmentManager.apply { if (findFragmentByTag("dialog_require_password") == null) { RequirePasswordDialog.newInstance(keyManager, e.deviceId, e.salt, e.isMissing).show(beginTransaction(), "dialog_require_password") } } } } } catch (e: Exception) { Log.e("yubioath", "Error using OathClient", e) val message = if (e is ApduException) { when (e.sw) { OathApplication.SW_FILE_NOT_FOUND -> R.string.no_applet OathApplication.SW_WRONG_DATA -> R.string.no_applet OathApplication.SW_FILE_FULL -> R.string.storage_full else -> R.string.tag_error } } else R.string.tag_error coroutineScope { launch(Dispatchers.Main) { toast(message) } } } } override fun onDestroy() { job.cancel() super.onDestroy() } override fun onNewIntent(intent: Intent) { nfcDispatcher.interceptIntent(intent) } public override fun onPause() { yubiKitManager.pause() super.onPause() } public override fun onResume() { super.onResume() yubiKitManager.resume() if (prefs.getBoolean("warnNfc", true) && !viewModel.nfcWarned) { when (val adapter = NfcAdapter.getDefaultAdapter(this)) { null -> R.string.no_nfc else -> if (!adapter.isEnabled) R.string.nfc_off else null }?.let { toast(it) viewModel.nfcWarned = true } } } }
kotlin
35
0.642562
158
34.846154
169
starcoderdata
<gh_stars>1-10 package io.truereactive.demo.flickr.common.data.device import android.content.Context import android.net.ConnectivityManager import android.net.Network import android.net.NetworkCapabilities import android.net.NetworkRequest.Builder import android.os.Build import android.os.HandlerThread import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.channels.awaitClose import kotlinx.coroutines.flow.callbackFlow import kotlinx.coroutines.flow.distinctUntilChanged import kotlinx.coroutines.flow.flowOn import kotlinx.coroutines.flow.onStart import javax.inject.Inject import javax.inject.Singleton @Singleton class NetworkStateRepository @Inject constructor( private val context: Context ) { private val connectivityThread by lazy { HandlerThread(CONNECTIVITY_THREAD).apply { start() } } val observable by lazy { val cm = context.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager callbackFlow<Boolean> { val callback = object : ConnectivityManager.NetworkCallback() { override fun onAvailable(network: Network) { offer(true) } override fun onLost(network: Network) { offer(false) } override fun onUnavailable() { offer(false) } } awaitClose { cm.unregisterNetworkCallback(callback) } val networkRequest = Builder().build() cm.registerNetworkCallback(networkRequest, callback) }.onStart { emit(getCurrentStategetCurrentState(cm)) } .distinctUntilChanged() .flowOn(Dispatchers.Main) // .replay(1) // .refCount() // .subscribeOn(looperScheduler) // .observeOn(Schedulers.computation()) } private fun getCurrentStategetCurrentState(connectivityManager: ConnectivityManager): Boolean { return if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) { connectivityManager.getNetworkCapabilities(connectivityManager.activeNetwork) ?.let { it.hasTransport(NetworkCapabilities.TRANSPORT_WIFI) || it.hasTransport(NetworkCapabilities.TRANSPORT_CELLULAR) || it.hasTransport(NetworkCapabilities.TRANSPORT_ETHERNET) } } else { connectivityManager.activeNetworkInfo?.isConnected } ?: false } companion object { private const val CONNECTIVITY_THREAD = "connectivity_thread" } }
kotlin
32
0.652289
99
31.641975
81
starcoderdata
<reponame>Savion1162336040/uidemo22 package com.pengyeah.flowview.func /** * Created by pengyeah on 2020/9/2 * 佛祖开光,永无bug * God bless U */ class Func6 : BaseFuncImpl { constructor(initValue: Float, inParamMax: Float) : super(initValue, inParamMax) override fun execute(offset: Float): Float { super.execute(offset) if (initValue + offset > inParamMax) { return inParamMax } else if (initValue + offset <= 0) { return 0F } else { return initValue + offset * 2 } } }
kotlin
14
0.608541
83
23.478261
23
starcoderdata
<filename>app/src/main/java/kr/kwonho87/firebasedbsample/MainActivity.kt package kr.kwonho87.firebasedbsample import android.support.v7.app.AppCompatActivity import android.os.Bundle import android.support.v7.widget.LinearLayoutManager import android.widget.Toast import com.google.firebase.FirebaseApp 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 kotlinx.android.synthetic.main.activity_main.* import kr.kwonho87.firebasedbsample.widget.MyAdapter import android.support.v7.widget.DividerItemDecoration /** * <EMAIL> * 2019-03-07 */ class MainActivity : AppCompatActivity() { companion object { var myAdapter = MyAdapter() } override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) // init FirebaseApp FirebaseApp.initializeApp(this) // make RecycleView listView.apply { layoutManager = LinearLayoutManager(context) adapter = myAdapter addItemDecoration(DividerItemDecoration(context, DividerItemDecoration.VERTICAL)) } // init RecycleView data updateListView() // insert button btnInsert.setOnClickListener{ insert() } } /** * Get insert value and request Firebase Service. */ private fun insert() { var data = Data() data.apply { id = editId.editableText.toString() name = editName.editableText.toString() age = editAge.editableText.toString() gender = editGender.editableText.toString() } post(data) } /** * Request Firebase Realtime Database. * And insert value. */ private fun post(data: Data) { var requestData = HashMap<String, Any>() requestData["/list/${data.id}"] = data.toMap() var task = FirebaseDatabase.getInstance().reference.updateChildren(requestData) task.addOnCompleteListener { Toast.makeText(baseContext, "Success", Toast.LENGTH_SHORT).show() updateListView() } } /** * After request, update listview. */ private fun updateListView() { var query = FirebaseDatabase.getInstance().reference.child("list").orderByChild("id") query.addListenerForSingleValueEvent(ValueListener()) } /** * Firebase Database query listener. */ class ValueListener: ValueEventListener { override fun onDataChange(dataSnapShot: DataSnapshot) { var list = ArrayList<Data>() list.clear() for(postSnapshot in dataSnapShot.children) { var get = postSnapshot.getValue(Data::class.java) list.add(get!!) } myAdapter.setData(list) myAdapter.notifyDataSetChanged() } override fun onCancelled(error: DatabaseError) {} } }
kotlin
21
0.651476
93
28.121495
107
starcoderdata
package nice.fontaine.models.csv import assertk.assertions.isEqualTo import nice.fontaine.GtfsReader import org.junit.Before import org.junit.Test class TransferTest { private lateinit var transfers: MutableList<CsvTransfer> @Before fun setUp() { val gtfs = GtfsReader() transfers = gtfs.read("full/transfers.txt", CsvTransfer::class.java) } @Test fun `should read transfers size`() { assertk.assert(transfers.size).isEqualTo(2) } @Test fun `should read transfer from stop id`() { assertk.assert(transfers[0].fromStopId).isEqualTo("000008012713") } @Test fun `should read transfer to stop id`() { assertk.assert(transfers[0].toStopId).isEqualTo("000008012713") } @Test fun `should read transfer type`() { assertk.assert(transfers[0].type).isEqualTo(2) } @Test fun `should read transfer time in seconds`() { assertk.assert(transfers[0].seconds).isEqualTo(300) } @Test fun `should read transfer from route id`() { assertk.assert(transfers[0].fromRouteId).isEqualTo("") } @Test fun `should read transfer to route id`() { assertk.assert(transfers[0].toRouteId).isEqualTo("") } @Test fun `should read transfer from trip id`() { assertk.assert(transfers[0].fromTripId).isEqualTo("") } @Test fun `should read transfer to trip id`() { assertk.assert(transfers[0].toTripId).isEqualTo("") } }
kotlin
15
0.658487
76
27.764706
51
starcoderdata
<reponame>readingbat/readingbat-core<gh_stars>1-10 /* * Copyright © 2021 <NAME> (<EMAIL>) * * 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.github.readingbat.server.ws import com.github.pambrose.common.util.md5Of import com.github.readingbat.common.ClassCode import com.github.readingbat.common.Constants.NO import com.github.readingbat.common.Constants.UNANSWERED import com.github.readingbat.common.Constants.YES import com.github.readingbat.common.Endpoints.STUDENT_SUMMARY_ENDPOINT import com.github.readingbat.common.Endpoints.WS_ROOT import com.github.readingbat.common.Metrics import com.github.readingbat.common.User.Companion.toUser import com.github.readingbat.dsl.InvalidRequestException import com.github.readingbat.dsl.ReadingBatContent import com.github.readingbat.dsl.agentLaunchId import com.github.readingbat.server.LanguageName import com.github.readingbat.server.ServerUtils.fetchUser import com.github.readingbat.server.ws.WsCommon.CLASS_CODE import com.github.readingbat.server.ws.WsCommon.LANGUAGE_NAME import com.github.readingbat.server.ws.WsCommon.STUDENT_ID import com.github.readingbat.server.ws.WsCommon.closeChannels import com.github.readingbat.server.ws.WsCommon.validateContext import io.ktor.http.cio.websocket.* import io.ktor.http.cio.websocket.CloseReason.Codes.* import io.ktor.routing.* import io.ktor.websocket.* import kotlinx.coroutines.flow.collect import kotlinx.coroutines.flow.consumeAsFlow import kotlinx.coroutines.flow.mapNotNull import kotlinx.serialization.Serializable import kotlinx.serialization.json.Json import mu.KLogging import org.jetbrains.exposed.sql.transactions.transaction import java.util.concurrent.atomic.AtomicBoolean internal object StudentSummaryWs : KLogging() { fun Routing.studentSummaryWsEndpoint(metrics: Metrics, contentSrc: () -> ReadingBatContent) { webSocket("$WS_ROOT$STUDENT_SUMMARY_ENDPOINT/{$LANGUAGE_NAME}/{$STUDENT_ID}/{$CLASS_CODE}") { try { val finished = AtomicBoolean(false) logger.debug { "Opened student summary websocket" } outgoing.invokeOnClose { logger.debug { "Close received for student summary websocket" } finished.set(true) incoming.cancel() } metrics.wsStudentSummaryCount.labels(agentLaunchId()).inc() metrics.wsStudentSummaryGauge.labels(agentLaunchId()).inc() metrics.measureEndpointRequest("/websocket_student_summary") { val content = contentSrc.invoke() val p = call.parameters val languageName = p[LANGUAGE_NAME]?.let { LanguageName(it) } ?: throw InvalidRequestException("Missing language") val student = p[STUDENT_ID]?.toUser() ?: throw InvalidRequestException("Missing student id") val classCode = p[CLASS_CODE]?.let { ClassCode(it) } ?: throw InvalidRequestException("Missing class code") val user = fetchUser() ?: throw InvalidRequestException("Null user") //val email = user.email //fetchEmail() //val remote = call.request.origin.remoteHost //val desc = "${pathOf(WS_ROOT, CLASS_SUMMARY_ENDPOINT, languageName, student.userId, classCode)} - $remote - $email" validateContext(languageName, null, classCode, student, user) incoming .consumeAsFlow() .mapNotNull { it as? Frame.Text } .collect { for (challengeGroup in content.findLanguage(languageName).challengeGroups) { for (challenge in challengeGroup.challenges) { val funcInfo = challenge.functionInfo() val groupName = challengeGroup.groupName val challengeName = challenge.challengeName //val numCalls = funcInfo.invocationCount //var likes = 0 //var dislikes = 0 var incorrectAttempts = 0 var attempted = 0 val results = mutableListOf<String>() for (invocation in funcInfo.invocations) { transaction { val historyMd5 = md5Of(languageName, groupName, challengeName, invocation) if (student.historyExists(historyMd5, invocation)) { attempted++ results += student.answerHistory(historyMd5, invocation) .let { incorrectAttempts += it.incorrectAttempts if (it.correct) YES else if (it.incorrectAttempts > 0) NO else UNANSWERED } } else { results += UNANSWERED } } if (finished.get()) break } val likeDislike = student.likeDislike(challenge) if (incorrectAttempts > 0 || results.any { it != UNANSWERED } || likeDislike != 0) { val stats = if (incorrectAttempts == 0 && results.all { it == UNANSWERED }) "" else incorrectAttempts.toString() val json = StudentSummary( groupName.encode(), challengeName.encode(), results, stats, student.likeDislikeEmoji(likeDislike) ).toJson() metrics.wsClassSummaryResponseCount.labels(agentLaunchId()).inc() logger.debug { "Sending data $json" } if (!finished.get()) outgoing.send(Frame.Text(json)) } if (finished.get()) break } } // Shut things down to exit collect incoming.cancel() } } } finally { // In case exited early closeChannels() close(CloseReason(GOING_AWAY, "Client disconnected")) metrics.wsStudentSummaryGauge.labels(agentLaunchId()).dec() logger.debug { "Closed student summary websocket" } } } } @Serializable @Suppress("unused") class StudentSummary( val groupName: String, val challengeName: String, val results: List<String>, val stats: String, val likeDislike: String ) { fun toJson() = Json.encodeToString(serializer(), this) } }
kotlin
40
0.62317
127
39.906977
172
starcoderdata
package com.aoc.intcode.droid.cryo.command.runtime import assertk.assertThat import assertk.assertions.contains import assertk.assertions.containsOnly import assertk.assertions.isInstanceOf import com.aoc.Day import com.aoc.droid.cryo.command.runtime.TestCommandReader import com.aoc.droid.cryo.droid.TestDroidLogger import com.aoc.input.InputReader import com.aoc.intcode.droid.cryo.command.system.HelpCommand import com.aoc.intcode.droid.cryo.droid.DroidLogger import org.junit.jupiter.api.BeforeEach import org.junit.jupiter.api.Test class CommandRuntimeTest { private val input = InputReader.read<String>(Day(25)).asSingleString() private val runtime = CommandRuntime(input) private val reader = TestCommandReader() private val logger = TestDroidLogger() @BeforeEach fun setUp() { runtime.reader = reader runtime.logger = logger } @Test fun startAndQuit() { reader.inputCommand("quit") runtime.start() assertThat(logger.logs).containsOnly("Booting Cryostasis Droid runtime environment...\n") } @Test fun help() { reader.inputCommand("help") reader.inputCommand("quit") runtime.start() assertThat(logger.logs).contains(HelpCommand().getCommands()) } @Test fun validCommandIsIssuedToDroid() { reader.inputCommand("east") reader.inputCommand("quit") runtime.start() } @Test fun invalidCommandLogsErrorMessage() { reader.inputCommand("ojhdfls") reader.inputCommand("quit") runtime.start() assertThat(logger.logs).contains("Invalid command: ojhdfls") } @Test fun invalidCommandLogsCommandHelpMessage() { reader.inputCommand("ojhdfls") reader.inputCommand("quit") runtime.start() assertThat(logger.logs).contains("Use command 'help' to view a complete list of commands\n") } @Test fun cliDefaultsToDroidCommandReader() { assertThat(CommandRuntime(input).reader).isInstanceOf(DroidCommandReader::class) } @Test fun loggerDefaultsToDroidLogger() { assertThat(CommandRuntime(input).logger).isInstanceOf(DroidLogger::class) } }
kotlin
17
0.699099
100
28.223684
76
starcoderdata
package com.prog.communityaid.data.repositories import com.google.firebase.firestore.ktx.firestore import com.google.firebase.ktx.Firebase import com.prog.communityaid.data.models.Complaint class ComplaintRepository : Repository<Complaint>(Firebase.firestore.collection("complaints")) { override fun hydrator(doc: Map<String, Any>): Complaint { val complaint = Complaint() complaint.id = doc["id"] as String complaint.at = doc["at"] as Number complaint.description = doc["description"] as String complaint.title = doc["title"] as String complaint.video = doc["video"] as String complaint.picture = doc["picture"] as String complaint.lat = doc["lat"] as Number complaint.long = doc["long"] as Number complaint.userId = doc["userId"] as String @Suppress("UNCHECKED_CAST") complaint.complaintInfo = (doc["complaintInfo"] as MutableMap<String, String>) complaint.complaintType = doc["complaintType"] as String complaint.solved = if (doc["solved"] != null) doc["solved"] as Boolean else false return complaint } }
kotlin
13
0.684534
96
44.56
25
starcoderdata
package uk.gov.justice.digital.hmpps.hmppsinterventionsservice.authorization import com.microsoft.applicationinsights.TelemetryClient import com.nhaarman.mockitokotlin2.mock import com.nhaarman.mockitokotlin2.verify import com.nhaarman.mockitokotlin2.whenever import org.assertj.core.api.Assertions.assertThat import org.junit.jupiter.api.BeforeEach import org.junit.jupiter.api.DisplayName import org.junit.jupiter.api.Nested import org.junit.jupiter.api.Test import org.junit.jupiter.api.assertThrows import uk.gov.justice.digital.hmpps.hmppsinterventionsservice.config.AccessError import uk.gov.justice.digital.hmpps.hmppsinterventionsservice.jpa.entity.AuthUser import uk.gov.justice.digital.hmpps.hmppsinterventionsservice.jpa.entity.DynamicFrameworkContract import uk.gov.justice.digital.hmpps.hmppsinterventionsservice.jpa.entity.SampleData import uk.gov.justice.digital.hmpps.hmppsinterventionsservice.jpa.entity.ServiceProvider import uk.gov.justice.digital.hmpps.hmppsinterventionsservice.jpa.repository.DynamicFrameworkContractRepository import uk.gov.justice.digital.hmpps.hmppsinterventionsservice.jpa.repository.ServiceProviderRepository import uk.gov.justice.digital.hmpps.hmppsinterventionsservice.service.HMPPSAuthService class ServiceProviderAccessScopeMapperTest { private lateinit var mapper: ServiceProviderAccessScopeMapper private val userTypeChecker = UserTypeChecker() private val hmppsAuthService = mock<HMPPSAuthService>() private val serviceProviderRepository = mock<ServiceProviderRepository>() private val dynamicFrameworkContractRepository = mock<DynamicFrameworkContractRepository>() private val telemetryClient = mock<TelemetryClient>() private val spUser = AuthUser(id = "b<PASSWORD>", userName = "<EMAIL>", authSource = "auth") private val ppUser = AuthUser(id = "123456789", userName = "TEST_USER", authSource = "delius") @BeforeEach fun setup() { mapper = ServiceProviderAccessScopeMapper( hmppsAuthService = hmppsAuthService, serviceProviderRepository = serviceProviderRepository, dynamicFrameworkContractRepository = dynamicFrameworkContractRepository, userTypeChecker = userTypeChecker, telemetryClient = telemetryClient ) } @Test fun `throws AccessError if the user is not a service provider`() { val error = assertThrows<AccessError> { mapper.fromUser(ppUser) } assertThat(error.user).isEqualTo(ppUser) assertThat(error.message).isEqualTo("could not map service provider user to access scope") assertThat(error.errors).containsExactly("user is not a service provider") } @Test fun `throws AccessError if the user's auth groups cannot be retrieved`() { whenever(hmppsAuthService.getUserGroups(spUser)).thenReturn(null) val error = assertThrows<AccessError> { mapper.fromUser(spUser) } assertThat(error.user).isEqualTo(spUser) assertThat(error.message).isEqualTo("could not map service provider user to access scope") assertThat(error.errors).containsExactly("cannot find user in hmpps auth") } // the business behaviour is tested through integration tests at // src/test/kotlin/uk/gov/justice/digital/hmpps/hmppsinterventionsservice/integration/authorization @Nested @DisplayName("for valid provider scopes") inner class ForValidScope { private lateinit var providers: List<ServiceProvider> private lateinit var contracts: List<DynamicFrameworkContract> @BeforeEach fun setup() { whenever(hmppsAuthService.getUserGroups(spUser)) .thenReturn(listOf("INT_SP_TEST_P1", "INT_SP_TEST_A2", "INT_CR_TEST_C0001", "INT_CR_TEST_A0002")) val p1 = ServiceProvider(id = "TEST_P1", name = "Test 1 Ltd") val p2 = ServiceProvider(id = "TEST_A2", name = "Test 2 Ltd") providers = listOf(p1, p2) whenever(serviceProviderRepository.findAllById(listOf("TEST_P1", "TEST_A2"))) .thenReturn(providers) val c1 = SampleData.sampleContract(contractReference = "TEST_C0001", primeProvider = p1) val c2 = SampleData.sampleContract(contractReference = "TEST_A0002", primeProvider = p2) contracts = listOf(c1, c2) whenever(dynamicFrameworkContractRepository.findAllByContractReferenceIn(listOf("TEST_C0001", "TEST_A0002"))) .thenReturn(contracts) } @Test fun `returns the access scope with providers sorted by their ID`() { val scope = mapper.fromUser(spUser) assertThat(scope.serviceProviders.map { it.id }).containsExactly("TEST_A2", "TEST_P1") } @Test fun `returns the access scope with contracts sorted by their contract reference`() { val scope = mapper.fromUser(spUser) assertThat(scope.contracts.map { it.contractReference }).containsExactly("TEST_A0002", "TEST_C0001") } @Test fun `tracks the event in AppInsights telemetry`() { mapper.fromUser(spUser) verify(telemetryClient).trackEvent( "InterventionsAuthorizedProvider", mapOf( "userId" to "b40ac52d-037d-4732-a3cd-bf5484c6ab6a", "userName" to "<EMAIL>", "userAuthSource" to "auth", "contracts" to "TEST_A0002,TEST_C0001", "providers" to "TEST_A2,TEST_P1", ), null ) } } }
kotlin
22
0.752432
115
43.058824
119
starcoderdata
package com.arman.kotboy.core.cpu import com.arman.kotboy.core.cpu.util.Flags enum class Flag(override val bit: Int) : Flags { /* |-------------------------------| | 7 | 6 | 5 | 4 | 3 | 2 | 1 | 0 | |-------------------------------| | Z | N | H | C | 0 | 0 | 0 | 0 | |-------------------------------| Z | Zero Flag N | Subtract Flag H | Half Carry Flag C | Carry Flag 0 | Not used, always zero */ Z(1 shl Flag.Z_INDEX), N(1 shl Flag.N_INDEX), H(1 shl Flag.H_INDEX), C(1 shl Flag.C_INDEX), UNUSED_3(1 shl 3), UNUSED_2(1 shl 2), UNUSED_1(1 shl 1), UNUSED_0(1 shl 0), UNDEFINED(0); companion object { const val Z_INDEX = 7 const val N_INDEX = 6 const val H_INDEX = 5 const val C_INDEX = 4 } }
kotlin
9
0.452555
48
19.575
40
starcoderdata
<filename>build-common/src/org/jetbrains/kotlin/incremental/ChangesCollector.kt /* * Copyright 2010-2017 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.incremental import org.jetbrains.kotlin.metadata.ProtoBuf import org.jetbrains.kotlin.metadata.deserialization.Flags import org.jetbrains.kotlin.metadata.deserialization.NameResolver import org.jetbrains.kotlin.metadata.deserialization.supertypes import org.jetbrains.kotlin.name.FqName import org.jetbrains.kotlin.protobuf.MessageLite import org.jetbrains.kotlin.serialization.deserialization.getClassId class ChangesCollector { private val removedMembers = hashMapOf<FqName, MutableSet<String>>() private val changedParents = hashMapOf<FqName, MutableSet<FqName>>() private val changedMembers = hashMapOf<FqName, MutableSet<String>>() private val areSubclassesAffected = hashMapOf<FqName, Boolean>() //TODO for test only: ProtoData or ProtoBuf private val storage = hashMapOf<FqName, ProtoData>() private val removed = ArrayList<FqName>() //TODO change to immutable map fun protoDataChanges(): Map<FqName, ProtoData> = storage fun protoDataRemoved(): List<FqName> = removed companion object { fun <T> T.getNonPrivateNames(nameResolver: NameResolver, vararg members: T.() -> List<MessageLite>) = members.flatMap { this.it().filterNot { it.isPrivate }.names(nameResolver) }.toSet() fun ClassProtoData.getNonPrivateMemberNames(): Set<String> { return proto.getNonPrivateNames( nameResolver, ProtoBuf.Class::getConstructorList, ProtoBuf.Class::getFunctionList, ProtoBuf.Class::getPropertyList ) + proto.enumEntryList.map { nameResolver.getString(it.name) } } } fun changes(): List<ChangeInfo> { val changes = arrayListOf<ChangeInfo>() for ((fqName, members) in removedMembers) { if (members.isNotEmpty()) { changes.add(ChangeInfo.Removed(fqName, members)) } } for ((fqName, members) in changedMembers) { if (members.isNotEmpty()) { changes.add(ChangeInfo.MembersChanged(fqName, members)) } } for ((fqName, areSubclassesAffected) in areSubclassesAffected) { changes.add(ChangeInfo.SignatureChanged(fqName, areSubclassesAffected)) } for ((fqName, changedParents) in changedParents) { changes.add(ChangeInfo.ParentsChanged(fqName, changedParents)) } return changes } private fun <T, R> MutableMap<T, MutableSet<R>>.getSet(key: T) = getOrPut(key) { HashSet() } private fun collectChangedMember(scope: FqName, name: String) { changedMembers.getSet(scope).add(name) } private fun collectRemovedMember(scope: FqName, name: String) { removedMembers.getSet(scope).add(name) } private fun collectChangedMembers(scope: FqName, names: Collection<String>) { if (names.isNotEmpty()) { changedMembers.getSet(scope).addAll(names) } } private fun collectRemovedMembers(scope: FqName, names: Collection<String>) { if (names.isNotEmpty()) { removedMembers.getSet(scope).addAll(names) } } fun collectProtoChanges(oldData: ProtoData?, newData: ProtoData?, collectAllMembersForNewClass: Boolean = false, packageProtoKey: String? = null) { if (oldData == null && newData == null) { throw IllegalStateException("Old and new value are null") } if (newData != null) { when (newData) { is ClassProtoData -> { val fqName = newData.nameResolver.getClassId(newData.proto.fqName).asSingleFqName() storage[fqName] = newData } is PackagePartProtoData -> { //TODO fqName is not unique. It's package and can be present in both java and kotlin val fqName = newData.packageFqName storage[packageProtoKey?.let { FqName(it) } ?: fqName] = newData } } } else { when (oldData) { is ClassProtoData -> { removed.add(oldData.nameResolver.getClassId(oldData.proto.fqName).asSingleFqName()) } is PackagePartProtoData -> { //TODO fqName is not unique. It's package and can be present in both java and kotlin removed.add(packageProtoKey?.let { FqName(it) } ?: oldData.packageFqName) } } } if (oldData == null) { newData!!.collectAll(isRemoved = false, isAdded = true, collectAllMembersForNewClass = collectAllMembersForNewClass) return } if (newData == null) { oldData.collectAll(isRemoved = true, isAdded = false) return } when (oldData) { is ClassProtoData -> { when (newData) { is ClassProtoData -> { val fqName = oldData.nameResolver.getClassId(oldData.proto.fqName).asSingleFqName() val diff = DifferenceCalculatorForClass(oldData, newData).difference() if (diff.isClassAffected) { collectSignature(oldData, diff.areSubclassesAffected) } collectChangedMembers(fqName, diff.changedMembersNames) addChangedParents(fqName, diff.changedSupertypes) } is PackagePartProtoData -> { collectSignature(oldData, areSubclassesAffected = true) } } } is PackagePartProtoData -> { when (newData) { is ClassProtoData -> { collectSignature(newData, areSubclassesAffected = false) } is PackagePartProtoData -> { val diff = DifferenceCalculatorForPackageFacade(oldData, newData).difference() collectChangedMembers(oldData.packageFqName, diff.changedMembersNames) } } } } } fun <T> T.getNonPrivateNames(nameResolver: NameResolver, vararg members: T.() -> List<MessageLite>) = members.flatMap { this.it().filterNot { it.isPrivate }.names(nameResolver) }.toSet() //TODO remember all sealed parent classes private fun ProtoData.collectAll(isRemoved: Boolean, isAdded: Boolean, collectAllMembersForNewClass: Boolean = false) = when (this) { is PackagePartProtoData -> collectAllFromPackage(isRemoved) is ClassProtoData -> collectAllFromClass(isRemoved, isAdded, collectAllMembersForNewClass) } private fun PackagePartProtoData.collectAllFromPackage(isRemoved: Boolean) { val memberNames = proto.getNonPrivateNames( nameResolver, ProtoBuf.Package::getFunctionList, ProtoBuf.Package::getPropertyList ) if (isRemoved) { collectRemovedMembers(packageFqName, memberNames) } else { collectChangedMembers(packageFqName, memberNames) } } private fun ClassProtoData.collectAllFromClass(isRemoved: Boolean, isAdded: Boolean, collectAllMembersForNewClass: Boolean = false) { val classFqName = nameResolver.getClassId(proto.fqName).asSingleFqName() val kind = Flags.CLASS_KIND.get(proto.flags) if (kind == ProtoBuf.Class.Kind.COMPANION_OBJECT) { val memberNames = getNonPrivateMemberNames() val collectMember = if (isRemoved) this@ChangesCollector::collectRemovedMember else this@ChangesCollector::collectChangedMember collectMember(classFqName.parent(), classFqName.shortName().asString()) memberNames.forEach { collectMember(classFqName, it) } } else { if (!isRemoved && collectAllMembersForNewClass) { val memberNames = getNonPrivateMemberNames() memberNames.forEach { this@ChangesCollector.collectChangedMember(classFqName, it) } } collectSignature(classFqName, areSubclassesAffected = true) } if (isRemoved || isAdded) { collectChangedParents(classFqName, proto.supertypeList) } } private fun addChangedParents(fqName: FqName, parents: Collection<FqName>) { if (parents.isNotEmpty()) { changedParents.getOrPut(fqName) { HashSet() }.addAll(parents) } } private fun ClassProtoData.collectChangedParents(fqName: FqName, parents: Collection<ProtoBuf.Type>) { val changedParentsFqNames = parents.map { type -> nameResolver.getClassId(type.className).asSingleFqName() } addChangedParents(fqName, changedParentsFqNames) } fun collectMemberIfValueWasChanged(scope: FqName, name: String, oldValue: Any?, newValue: Any?) { if (oldValue == null && newValue == null) { throw IllegalStateException("Old and new value are null for $scope#$name") } if (oldValue != null && newValue == null) { collectRemovedMember(scope, name) } else if (oldValue != newValue) { collectChangedMember(scope, name) } } private fun collectSignature(classData: ClassProtoData, areSubclassesAffected: Boolean) { val fqName = classData.nameResolver.getClassId(classData.proto.fqName).asSingleFqName() collectSignature(fqName, areSubclassesAffected) } fun collectSignature(fqName: FqName, areSubclassesAffected: Boolean) { val prevValue = this.areSubclassesAffected[fqName] ?: false this.areSubclassesAffected[fqName] = prevValue || areSubclassesAffected } }
kotlin
27
0.627971
151
40.100775
258
starcoderdata
<filename>idea/tests/org/jetbrains/kotlin/idea/inspections/AbstractLocalInspectionTest.kt /* * Copyright 2010-2019 JetBrains s.r.o. and Kotlin Programming Language contributors. * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ package org.jetbrains.kotlin.idea.inspections import com.google.common.collect.Lists import com.intellij.codeHighlighting.HighlightDisplayLevel import com.intellij.codeHighlighting.Pass import com.intellij.codeInsight.daemon.impl.HighlightInfoType import com.intellij.codeInsight.intention.EmptyIntentionAction import com.intellij.codeInspection.ProblemHighlightType import com.intellij.openapi.util.SystemInfo import com.intellij.openapi.util.io.FileUtil import com.intellij.profile.codeInspection.ProjectInspectionProfileManager import com.intellij.testFramework.fixtures.impl.CodeInsightTestFixtureImpl import junit.framework.ComparisonFailure import junit.framework.TestCase import org.jetbrains.kotlin.idea.test.DirectiveBasedActionUtils import org.jetbrains.kotlin.idea.test.KotlinLightCodeInsightFixtureTestCase import org.jetbrains.kotlin.idea.test.configureCompilerOptions import org.jetbrains.kotlin.idea.test.rollbackCompilerOptions import org.jetbrains.kotlin.idea.util.application.executeWriteCommand import org.jetbrains.kotlin.psi.KtFile import org.jetbrains.kotlin.test.InTextDirectivesUtils import org.jetbrains.kotlin.test.KotlinTestUtils import org.junit.Assert import java.io.File abstract class AbstractLocalInspectionTest : KotlinLightCodeInsightFixtureTestCase() { private val inspectionFileName: String get() = ".inspection" private val afterFileNameSuffix: String get() = ".after" private val expectedProblemDirectiveName: String get() = "PROBLEM" private val expectedProblemHighlightType: String get() = "HIGHLIGHT" private val fixTextDirectiveName: String get() = "FIX" private fun createInspection(testDataFile: File): AbstractKotlinInspection { val candidateFiles = Lists.newArrayList<File>() var current: File? = testDataFile.parentFile while (current != null) { val candidate = File(current, inspectionFileName) if (candidate.exists()) { candidateFiles.add(candidate) } current = current.parentFile } if (candidateFiles.isEmpty()) { throw AssertionError( ".inspection file is not found for " + testDataFile + "\nAdd it to base directory of test data. It should contain fully-qualified name of inspection class." ) } if (candidateFiles.size > 1) { throw AssertionError( "Several .inspection files are available for " + testDataFile + "\nPlease remove some of them\n" + candidateFiles ) } val className = FileUtil.loadFile(candidateFiles[0]).trim { it <= ' ' } return Class.forName(className).newInstance() as AbstractKotlinInspection } protected open fun doTest(path: String) { val mainFile = File(path) val inspection = createInspection(mainFile) val fileText = FileUtil.loadFile(mainFile, true) TestCase.assertTrue("\"<caret>\" is missing in file \"$mainFile\"", fileText.contains("<caret>")) val configured = configureCompilerOptions(fileText, project, module) try { val minJavaVersion = InTextDirectivesUtils.findStringWithPrefixes(fileText, "// MIN_JAVA_VERSION: ") if (minJavaVersion != null && !SystemInfo.isJavaVersionAtLeast(minJavaVersion)) return if (file is KtFile && !InTextDirectivesUtils.isDirectiveDefined(fileText, "// SKIP_ERRORS_BEFORE")) { DirectiveBasedActionUtils.checkForUnexpectedErrors(file as KtFile) } var i = 1 val extraFileNames = mutableListOf<String>() extraFileLoop@ while (true) { for (extension in EXTENSIONS) { val extraFile = File(mainFile.parent, FileUtil.getNameWithoutExtension(mainFile) + "." + i + extension) if (extraFile.exists()) { extraFileNames += extraFile.name i++ continue@extraFileLoop } } break } val parentFile = mainFile.parentFile if (parentFile != null) { for (file in parentFile.walkTopDown().maxDepth(1)) { if (file.name.endsWith(".lib.kt")) { extraFileNames += file.name } } } myFixture.configureByFiles(*(listOf(mainFile.name) + extraFileNames).toTypedArray()).first() doTestFor(mainFile.name, inspection, fileText) if (file is KtFile && !InTextDirectivesUtils.isDirectiveDefined(fileText, "// SKIP_ERRORS_AFTER")) { DirectiveBasedActionUtils.checkForUnexpectedErrors(file as KtFile) } } finally { if (configured) { rollbackCompilerOptions(project, module) } } } protected fun runInspectionWithFixesAndCheck( inspection: AbstractKotlinInspection, expectedProblemString: String?, expectedHighlightString: String?, localFixTextString: String? ): Boolean { val problemExpected = expectedProblemString == null || expectedProblemString != "none" myFixture.enableInspections(inspection::class.java) // Set default level to WARNING to make possible to test DO_NOT_SHOW val inspectionProfileManager = ProjectInspectionProfileManager.getInstance(project) val inspectionProfile = inspectionProfileManager.currentProfile val state = inspectionProfile.getToolDefaultState(inspection.shortName, project) state.level = HighlightDisplayLevel.WARNING val caretOffset = myFixture.caretOffset val highlightInfos = CodeInsightTestFixtureImpl.instantiateAndRun( file, editor, intArrayOf( Pass.LINE_MARKERS, Pass.EXTERNAL_TOOLS, Pass.POPUP_HINTS, Pass.UPDATE_ALL, Pass.UPDATE_FOLDING, Pass.WOLF ), (file as? KtFile)?.isScript() == true ).filter { it.description != null && caretOffset in it.startOffset..it.endOffset } Assert.assertTrue( if (!problemExpected) "No problems should be detected at caret\n" + "Detected problems: ${highlightInfos.joinToString { it.description }}" else "Expected at least one problem at caret", problemExpected == highlightInfos.isNotEmpty() ) if (!problemExpected || highlightInfos.isEmpty()) return false highlightInfos .filter { it.type != HighlightInfoType.INFORMATION } .forEach { val description = it.description Assert.assertTrue( "Problem description should not contain 'can': $description", " can " !in description ) } if (expectedProblemString != null) { Assert.assertTrue( "Expected the following problem at caret: $expectedProblemString\n" + "Active problems: ${highlightInfos.joinToString { it.description }}", highlightInfos.any { it.description == expectedProblemString } ) } val expectedHighlightType = when (expectedHighlightString) { null -> null ProblemHighlightType.GENERIC_ERROR_OR_WARNING.name -> HighlightDisplayLevel.WARNING.name else -> expectedHighlightString } if (expectedHighlightType != null) { Assert.assertTrue( "Expected the following problem highlight type: $expectedHighlightType\n" + "Actual type: ${highlightInfos.joinToString { it.type.toString() }}", highlightInfos.all { expectedHighlightType in it.type.toString() } ) } val allLocalFixActions = highlightInfos.flatMap { it.quickFixActionMarkers ?: emptyList() }.map { it.first.action } val localFixActions = if (localFixTextString == null || localFixTextString == "none") { allLocalFixActions } else { allLocalFixActions.filter { fix -> fix.text == localFixTextString } } val availableDescription = allLocalFixActions.joinToString { it.text } val fixDescription = localFixTextString?.let { "with specified text '$localFixTextString'" } ?: "" TestCase.assertTrue( "No fix action $fixDescription\n" + "Available actions: $availableDescription", localFixActions.isNotEmpty() ) val localFixAction = localFixActions.singleOrNull { it !is EmptyIntentionAction } if (localFixTextString == "none") { Assert.assertTrue("Expected no fix action", localFixAction == null) return false } TestCase.assertTrue( "More than one fix action $fixDescription\n" + "Available actions: $availableDescription", localFixAction != null ) project.executeWriteCommand(localFixAction!!.text, null) { localFixAction.invoke(project, editor, file) } return true } private fun doTestFor(mainFilePath: String, inspection: AbstractKotlinInspection, fileText: String) { val expectedProblemString = InTextDirectivesUtils.findStringWithPrefixes( fileText, "// $expectedProblemDirectiveName: " ) val expectedHighlightString = InTextDirectivesUtils.findStringWithPrefixes( fileText, "// $expectedProblemHighlightType: " ) val localFixTextString = InTextDirectivesUtils.findStringWithPrefixes( fileText, "// $fixTextDirectiveName: " ) if (!runInspectionWithFixesAndCheck(inspection, expectedProblemString, expectedHighlightString, localFixTextString)) { return } val canonicalPathToExpectedFile = mainFilePath + afterFileNameSuffix try { myFixture.checkResultByFile(canonicalPathToExpectedFile) } catch (e: ComparisonFailure) { KotlinTestUtils.assertEqualsToFile( File(testDataPath, canonicalPathToExpectedFile), editor.document.text ) } } companion object { private val EXTENSIONS = arrayOf(".kt", ".kts", ".java", ".groovy") } }
kotlin
26
0.638224
126
41.084942
259
starcoderdata
<gh_stars>1-10 // !LANGUAGE: +MultiPlatformProjects // IGNORE_BACKEND_FIR: JVM_IR // IGNORE_BACKEND: NATIVE // FILE: common.kt expect interface I { fun test(source: String = "expect") } expect interface J : I // FILE: platform.kt actual interface I { // This test should be updated once KT-22818 is fixed; default values are not allowed in the actual function @Suppress("ACTUAL_FUNCTION_WITH_DEFAULT_ARGUMENTS") actual fun test(source: String = "actual") } actual interface J : I { override fun test(source: String) { if (source != "actual") throw AssertionError(source) } } class K : J fun box(): String { K().test() return "OK" }
kotlin
13
0.667158
112
20.21875
32
starcoderdata
<gh_stars>1-10 rootProject.name = "kstatus" include( "core", "api", "scheduler", "worker" )
kotlin
5
0.60396
28
10.222222
9
starcoderdata
package ru.dreamkas.semver import ru.dreamkas.semver.comparators.VersionComparator import ru.dreamkas.semver.prerelease.PreRelease /** * Version object corresponding to [Semantic Versioning 2.0.0 Specification](http://semver.org/spec/v2.0.0.html) * * Field examples for 1.5.8-beta.22+revision.2ed49def * Use [VersionBuilder.build] for instance * * [major] 1 * * [minor] 5 * * [patch] 8 * * [preRelease] beta.22 * * [metaData] revision.2ed49def */ class Version internal constructor( val major: Int, val minor: Int = 0, val patch: Int = 0, val preRelease: PreRelease = PreRelease.EMPTY, val metaData: MetaData = MetaData.EMPTY ) : Comparable<Version> { val base: Version get() = truncateToPatch() val comparable: Version get() = truncateToPreRelease() fun isPreRelease() = preRelease.preRelease != null fun isRelease() = !isPreRelease() override fun compareTo(other: Version): Int { return VersionComparator.SEMVER.compare(this, other) } fun truncateToMajor(): Version = Version(major) fun truncateToMinor(): Version = Version(major, minor) fun truncateToPatch(): Version = Version(major, minor, patch) fun truncateToPreRelease(): Version = Version(major, minor, patch, preRelease) fun gt(other: Version): Boolean = this > other fun lt(other: Version): Boolean = this < other fun le(other: Version): Boolean = this <= other fun ge(other: Version): Boolean = this >= other fun toComparableString(): String { return "$major.$minor.$patch" + preRelease.toString() } override fun toString(): String { return toComparableString() + metaData.toString() } override fun equals(other: Any?): Boolean { if (this === other) return true if (other?.javaClass != javaClass) return false other as Version if (major != other.major) return false if (minor != other.minor) return false if (patch != other.patch) return false if (preRelease != other.preRelease) return false return true } override fun hashCode(): Int { var result = major.hashCode() result = 31 * result + minor.hashCode() result = 31 * result + patch.hashCode() result = 31 * result + preRelease.hashCode() return result } companion object { @JvmStatic fun of(version: String): Version { return VersionBuilder.build(version) } @JvmStatic fun matches(version: String): Boolean { return VersionBuilder.matches(version) } @JvmStatic @JvmOverloads fun of(major: Int, minor: Int = 0, patch: Int = 0): Version { return Version(major, minor, patch) } } }
kotlin
13
0.629301
112
28.989362
94
starcoderdata
/* * Use of this source code is governed by the MIT license that can be * found in the LICENSE file. */ package org.rust.lang.core.types.borrowck import org.rust.lang.core.psi.RsBlock import org.rust.lang.core.psi.RsPat import org.rust.lang.core.psi.ext.RsElement import org.rust.lang.core.types.borrowck.LoanPathElement.Interior import org.rust.lang.core.types.borrowck.LoanPathKind.Downcast import org.rust.lang.core.types.borrowck.LoanPathKind.Extend import org.rust.lang.core.types.borrowck.gatherLoans.isAdtWithDestructor import org.rust.lang.core.types.infer.Cmt import org.rust.lang.core.types.infer.MemoryCategorizationContext import org.rust.lang.core.types.inference class CheckLoanContext(private val bccx: BorrowCheckContext, private val moveData: FlowedMoveData) : Delegate { override fun consume(element: RsElement, cmt: Cmt, mode: ConsumeMode) { consumeCommon(element, cmt) } override fun matchedPat(pat: RsPat, cmt: Cmt, mode: MatchMode) {} override fun consumePat(pat: RsPat, cmt: Cmt, mode: ConsumeMode) { consumeCommon(pat, cmt) } private fun checkIfPathIsMoved(element: RsElement, loanPath: LoanPath) { moveData.eachMoveOf(element, loanPath) { move, _ -> bccx.reportUseOfMovedValue(loanPath, move) false } } override fun declarationWithoutInit(element: RsElement) {} override fun mutate(assignmentElement: RsElement, assigneeCmt: Cmt, mode: MutateMode) { val loanPath = LoanPath.computeFor(assigneeCmt) ?: return when (mode) { MutateMode.Init, MutateMode.JustWrite -> { // In a case like `path = 1`, path does not have to be FULLY initialized, but we still // must be careful lest it contains derefs of pointers. checkIfAssignedPathIsMoved(assigneeCmt.element, loanPath) } MutateMode.WriteAndRead -> { // In a case like `path += 1`, path must be fully initialized, since we will read it before we write it checkIfPathIsMoved(assigneeCmt.element, loanPath) } } } fun checkLoans(body: RsBlock) { val mc = MemoryCategorizationContext(bccx.implLookup, bccx.owner.inference) ExprUseWalker(this, mc).consumeBody(body) } /** * Reports an error if assigning to [loanPath] will use a moved/uninitialized value. * Mainly this is concerned with detecting derefs of uninitialized pointers. */ private fun checkIfAssignedPathIsMoved(element: RsElement, loanPath: LoanPath) { if (loanPath.kind is Downcast) { checkIfAssignedPathIsMoved(element, loanPath.kind.loanPath) } // assigning to `x` does not require that `x` is initialized, so process only `Extend` val extend = loanPath.kind as? Extend ?: return val baseLoanPath = extend.loanPath val lpElement = extend.lpElement if (lpElement is Interior.Field) { if (baseLoanPath.ty.isAdtWithDestructor) { moveData.eachMoveOf(element, baseLoanPath) { _, _ -> false } } else { checkIfAssignedPathIsMoved(element, baseLoanPath) } } else { checkIfPathIsMoved(element, baseLoanPath) } } private fun consumeCommon(element: RsElement, cmt: Cmt) { val loanPath = LoanPath.computeFor(cmt) ?: return checkIfPathIsMoved(element, loanPath) } }
kotlin
18
0.673358
119
39.08046
87
starcoderdata
<gh_stars>1-10 import androidx.compose.foundation.isSystemInDarkTheme import androidx.compose.material.Colors import androidx.compose.material.MaterialTheme import androidx.compose.material.darkColors import androidx.compose.material.lightColors import androidx.compose.runtime.Composable import com.foreverrafs.superdiary.ui.style.Shapes import com.foreverrafs.superdiary.ui.style.brandColorDark import com.foreverrafs.superdiary.ui.style.brandColorLight private val DarkColorPalette = darkColors( ) private val LightColorPalette = lightColors( ) val Colors.brand @Composable get() = if (isSystemInDarkTheme()) brandColorDark else brandColorLight @Composable fun SuperDiaryTheme( darkTheme: Boolean = true, content: @Composable () -> Unit ) { // only use dark color palette for now val colors = if (darkTheme) { DarkColorPalette } else { LightColorPalette } MaterialTheme MaterialTheme( colors = colors, typography = Typography, shapes = Shapes, content = content ) }
kotlin
8
0.740672
58
23.930233
43
starcoderdata
package net.xblacky.animexstream.ui.main.home import io.reactivex.Observable import io.reactivex.android.schedulers.AndroidSchedulers import io.reactivex.schedulers.Schedulers import io.realm.Realm import io.realm.Sort import net.xblacky.animexstream.utils.constants.C import net.xblacky.animexstream.utils.rertofit.NetworkInterface import net.xblacky.animexstream.utils.rertofit.RetrofitHelper import net.xblacky.animexstream.utils.model.AnimeMetaModel import net.xblacky.animexstream.utils.realm.InitalizeRealm import okhttp3.ResponseBody import retrofit2.Retrofit class HomeRepository { private var retrofit: Retrofit = RetrofitHelper.getRetrofitInstance()!! fun fetchRecentSubOrDub(page: Int, type: Int): Observable<ResponseBody> { val fetchHomeListService = retrofit.create(NetworkInterface.FetchRecentSubOrDub::class.java) return fetchHomeListService.get(page, type).subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) } fun fetchPopularFromAjax(page: Int): Observable<ResponseBody> { val fetchPopularListService = retrofit.create(NetworkInterface.FetchPopularFromAjax::class.java) return fetchPopularListService.get(page).subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) } fun fetchMovies(page: Int): Observable<ResponseBody> { val fetchMoviesListService = retrofit.create(NetworkInterface.FetchMovies::class.java) return fetchMoviesListService.get(page).subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) } fun fetchNewestAnime(page: Int): Observable<ResponseBody> { val fetchNewestSeasonService = retrofit.create(NetworkInterface.FetchNewestSeason::class.java) return fetchNewestSeasonService.get(page).subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) } fun addDataInRealm(animeList: ArrayList<AnimeMetaModel>) { val realm: Realm = Realm.getInstance(InitalizeRealm.getConfig()) try { realm.executeTransaction { realm1: Realm -> realm1.insertOrUpdate(animeList) } } catch (ignored: Exception) { } } fun removeFromRealm(){ val realm: Realm = Realm.getInstance(InitalizeRealm.getConfig()) realm.executeTransaction{ val results = it.where(AnimeMetaModel::class.java).lessThanOrEqualTo("timestamp", System.currentTimeMillis() - C.MAX_TIME_FOR_ANIME).findAll() results.deleteAllFromRealm() } } fun fetchFromRealm(typeValue: Int): ArrayList<AnimeMetaModel> { val realm: Realm = Realm.getInstance(InitalizeRealm.getConfig()) val list: ArrayList<AnimeMetaModel> = ArrayList() try { val results = realm.where(AnimeMetaModel::class.java)?.equalTo("typeValue", typeValue)?.sort("insertionOrder", Sort.ASCENDING)?.findAll() results?.let { list.addAll(it) } } catch (ignored: Exception) { } return list } }
kotlin
22
0.701816
154
35.511628
86
starcoderdata
<filename>app/src/main/java/com/mailerdaemon/app/home/Contact.kt package com.mailerdaemon.app.home data class Contact( val dept: String? = null, val email: String? = null, val image: String? = null, val name: String? = null, val phone: String? = null, val url: String? = null )
kotlin
10
0.666667
64
26.545455
11
starcoderdata
package com.kiptechie.composedictionary.feature_dictionary.data.local.entity import androidx.room.Entity import androidx.room.PrimaryKey import com.kiptechie.composedictionary.feature_dictionary.domain.models.Meaning import com.kiptechie.composedictionary.feature_dictionary.domain.models.WordInfo @Entity data class WordInfoEntity( val word: String, val phonetic: String?, val origin: String?, val meanings: List<Meaning>, @PrimaryKey val id: Int? = null ) { fun toWordInfo(): WordInfo { return WordInfo( word = word, phonetic = phonetic ?: "No Phonetic", origin = origin ?: "No Origin", meanings = meanings ) } }
kotlin
12
0.685472
80
28.541667
24
starcoderdata
<filename>OnlinePK-Android/lib-live-pk-service/src/main/java/com/netease/yunxin/lib_live_pk_service/delegate/PkDelegate.kt /* * Copyright (c) 2021 NetEase, Inc. All rights reserved. * Use of this source code is governed by a MIT license that can be found in the LICENSE file */ package com.netease.yunxin.lib_live_pk_service.delegate import com.netease.yunxin.lib_live_pk_service.bean.PkActionMsg import com.netease.yunxin.lib_live_pk_service.bean.PkEndInfo import com.netease.yunxin.lib_live_pk_service.bean.PkPunishInfo import com.netease.yunxin.lib_live_pk_service.bean.PkStartInfo interface PkDelegate { /** * anchor received pk request */ fun onPkRequestReceived(pkActionMsg: PkActionMsg){} /** * anchor's pk request been rejected */ fun onPkRequestRejected(pkActionMsg: PkActionMsg){} /** * pk request have been canceled */ fun onPkRequestCancel(pkActionMsg: PkActionMsg){} /** * pk request have been accepted */ fun onPkRequestAccept(pkActionMsg: PkActionMsg){} /** * pk request time out */ fun onPkRequestTimeout(pkActionMsg: PkActionMsg){} /** * pk state changed,pk start */ fun onPkStart(startInfo: PkStartInfo) /** * pk state changed,punish start */ fun onPunishStart(punishInfo: PkPunishInfo) /** * pk state changed,pk end */ fun onPkEnd(endInfo: PkEndInfo) }
kotlin
12
0.68833
122
25.518519
54
starcoderdata
<reponame>varsy/edu-for-kotlin package com.jetbrains.edu.learning.courseGeneration import com.intellij.openapi.vfs.VirtualFile import com.intellij.testFramework.HeavyPlatformTestCase import com.intellij.testFramework.runInEdtAndWait import com.jetbrains.edu.learning.courseFormat.Course import com.jetbrains.edu.learning.courseFormat.CourseMode import com.jetbrains.edu.learning.courseFormat.ext.configurator import com.jetbrains.edu.learning.createCourseFromJson import org.junit.internal.runners.JUnit38ClassRunner import org.junit.runner.RunWith @RunWith(JUnit38ClassRunner::class) // TODO: drop the annotation when issue with Gradle test scanning go away abstract class CourseGenerationTestBase<Settings> : HeavyPlatformTestCase() { abstract val defaultSettings: Settings protected val rootDir: VirtualFile by lazy { tempDir.createVirtualDir() } protected fun findFile(path: String): VirtualFile = rootDir.findFileByRelativePath(path) ?: error("Can't find $path") protected fun createCourseStructure(course: Course) { val configurator = course.configurator ?: error("Failed to find `EduConfigurator` for `${course.name}` course") val generator = configurator.courseBuilder.getCourseProjectGenerator(course) ?: error("given builder returns null as course project generator") val project = generator.doCreateCourseProject(rootDir.path, defaultSettings as Any) ?: error("Cannot create project") runInEdtAndWait { myProject = project } } protected fun generateCourseStructure(pathToCourseJson: String, courseMode: CourseMode = CourseMode.STUDENT): Course { val course = createCourseFromJson(pathToCourseJson, courseMode) createCourseStructure(course) return course } /** * It intentionally does nothing to avoid project creation in [setUp]. * * If you need to create course project, use [createCourseStructure] */ override fun setUpProject() {} }
kotlin
16
0.782407
121
41.26087
46
starcoderdata
package net.starlegacy.feature.multiblock.starshipweapon.turret import java.util.concurrent.TimeUnit import net.starlegacy.feature.multiblock.MultiblockShape import net.starlegacy.feature.starship.active.ActiveStarship import net.starlegacy.feature.starship.subsystem.weapon.TurretWeaponSubsystem import net.starlegacy.feature.starship.subsystem.weapon.secondary.TriTurretWeaponSubsystem import net.starlegacy.util.Vec3i import org.bukkit.Material.GRINDSTONE import org.bukkit.Material.IRON_TRAPDOOR import org.bukkit.block.BlockFace sealed class TriTurretMultiblock : TurretMultiblock() { override fun createSubsystem(starship: ActiveStarship, pos: Vec3i, face: BlockFace): TurretWeaponSubsystem { return TriTurretWeaponSubsystem(starship, pos, getFacing(pos, starship), this) } protected abstract fun getYFactor(): Int override val cooldownNanos: Long = TimeUnit.SECONDS.toNanos(3L) override val range: Double = 500.0 override val sound: String = "starship.weapon.turbolaser.tri.shoot" override val projectileSpeed: Int = 125 override val projectileParticleThickness: Double = 0.8 override val projectileExplosionPower: Float = 6f override val projectileShieldDamageMultiplier: Int = 3 override fun buildFirePointOffsets(): List<Vec3i> = listOf( Vec3i(-2, getYFactor() * 4, +3), Vec3i(+0, getYFactor() * 4, +4), Vec3i(+2, getYFactor() * 4, +3) ) override fun MultiblockShape.buildStructure() { y(getYFactor() * 2) { z(-1) { x(+0).sponge() } z(+0) { x(-1).sponge() x(+1).sponge() } z(+1) { x(+0).sponge() } } y(getYFactor() * 3) { z(-3) { x(-1).anyStairs() x(+0).stainedTerracotta() x(+1).anyStairs() } z(-2) { x(-2).ironBlock() x(-1..+1) { concrete() } x(+2).ironBlock() } z(-1) { x(-3).anyStairs() x(-2..+2) { concrete() } x(+3).anyStairs() } z(+0) { x(-3..-2) { stainedTerracotta() } x(-1..+1) { concrete() } x(+2..+3) { stainedTerracotta() } } z(+1) { x(-3).anyStairs() x(-2).stainedTerracotta() x(-1).concrete() x(+0).stainedTerracotta() x(+1).concrete() x(+2).stainedTerracotta() x(+3).anyStairs() } z(+2) { x(-2).ironBlock() x(-1).concrete() x(+0).stainedTerracotta() x(+1).concrete() x(+2).ironBlock() } z(+3) { x(-1).anyStairs() x(+0).anyStairs() x(+1).anyStairs() } } y(getYFactor() * 4) { z(-3) { x(+0).anyStairs() } z(-2) { x(-2).anySlab() x(-1).anyStairs() x(+0).stainedTerracotta() x(+1).anyStairs() x(+2).anySlab() } z(-1) { x(-2).stainedTerracotta() x(-1).stainedTerracotta() x(+0).stainedTerracotta() x(+1).stainedTerracotta() x(+2).stainedTerracotta() } z(+0) { x(-3).anyStairs() x(-2).type(GRINDSTONE) x(-1).anyStairs() x(+0).stainedTerracotta() x(+1).anyStairs() x(+2).type(GRINDSTONE) x(+3).anyStairs() } z(+1) { x(-2).endRod() x(-1).type(IRON_TRAPDOOR) x(+0).type(GRINDSTONE) x(+1).type(IRON_TRAPDOOR) x(+2).endRod() } z(+2) { x(-2).endRod() x(-1).type(IRON_TRAPDOOR) x(+0).endRod() x(+1).type(IRON_TRAPDOOR) x(+2).endRod() } z(+3) { x(+0).endRod() } } } } object TopTriTurretMultiblock : TriTurretMultiblock() { override fun getYFactor(): Int = 1 override fun getPilotOffset(): Vec3i = Vec3i(+0, +3, +2) } object BottomTriTurretMultiblock : TriTurretMultiblock() { override fun getYFactor(): Int = -1 override fun getPilotOffset(): Vec3i = Vec3i(+0, -4, +2) }
kotlin
24
0.617721
109
21.018405
163
starcoderdata
package uk.gov.justice.hmpps.prison.repository.sql enum class IncidentCaseRepositorySql(val sql: String) { QUESTIONNAIRE( """ select q.code, q.questionnaire_id, qq.questionnaire_que_id, qq.que_seq question_seq, qq.description question_desc, ans_seq answer_seq, qa.description answer_desc, qq.list_seq question_list_seq, qq.active_flag question_active_flag, qq.expiry_date question_expiry_date, qq.multiple_answer_flag, qa.questionnaire_ans_id, next_questionnaire_que_id, qa.list_seq answer_list_seq, qa.active_flag answer_active_flag, qa.expiry_date answer_expiry_date, qa.date_required_flag, qa.comment_required_flag from questionnaires q join questionnaire_questions qq on q.questionnaire_id = qq.questionnaire_id join questionnaire_answers qa on qa.QUESTIONNAIRE_QUE_ID = qq.QUESTIONNAIRE_QUE_ID where q.questionnaire_category = :category and q.code = :code """ ), GET_INCIDENT_CASE( """ select ic.INCIDENT_CASE_ID, ic.REPORTED_STAFF_ID, ic.REPORT_DATE, ic.REPORT_TIME, ic.INCIDENT_DATE, ic.INCIDENT_TIME, ic.INCIDENT_STATUS, ic.AGY_LOC_ID AGENCY_ID, ic.INCIDENT_TITLE, ic.INCIDENT_TYPE, ic.INCIDENT_DETAILS, ic.RESPONSE_LOCKED_FLAG, icq.question_seq, icq.questionnaire_que_id, qa.questionnaire_ans_id, qq.description question, qa.description answer, icr.RESPONSE_DATE, icr.RESPONSE_COMMENT_TEXT, icr.RECORD_STAFF_ID from INCIDENT_CASES ic join incident_case_questions icq on ic.INCIDENT_CASE_ID = icq.INCIDENT_CASE_ID join questionnaire_questions qq on qq.questionnaire_que_id = icq.questionnaire_que_id join incident_case_responses icr on icr.incident_case_id = icq.incident_case_id join questionnaire_answers qa on qa.QUESTIONNAIRE_ANS_ID = icr.QUESTIONNAIRE_ANS_ID and qa.QUESTIONNAIRE_QUE_ID = qq.QUESTIONNAIRE_QUE_ID where ic.INCIDENT_CASE_ID IN (:incidentCaseIds) """ ), GET_PARTIES_INVOLVED( """ select icp.INCIDENT_CASE_ID, icp.PARTY_SEQ, icp.OFFENDER_BOOK_ID BOOKING_ID, icp.STAFF_ID, icp.PERSON_ID, icp.PARTICIPATION_ROLE, icp.OUTCOME_CODE, icp.COMMENT_TEXT from INCIDENT_CASE_PARTIES icp where icp.INCIDENT_CASE_ID IN (:incidentCaseIds) """ ), GET_INCIDENT_CASES_BY_OFFENDER_NO( """ select DISTINCT icp.INCIDENT_CASE_ID from INCIDENT_CASE_PARTIES icp join INCIDENT_CASES ic on ic.INCIDENT_CASE_ID = icp.INCIDENT_CASE_ID join OFFENDER_BOOKINGS ob on ob.offender_book_id = icp.offender_book_id join OFFENDERS o on o.offender_id = ob.offender_id where o.offender_id_display = :offenderNo """ ), GET_INCIDENT_CASES_BY_BOOKING_ID( """ select DISTINCT icp.INCIDENT_CASE_ID from INCIDENT_CASE_PARTIES icp join INCIDENT_CASES ic on ic.INCIDENT_CASE_ID = icp.INCIDENT_CASE_ID where icp.OFFENDER_BOOK_ID = :bookingId """ ), FILTER_BY_PARTICIPATION( """ icp.participation_role IN (:participationRoles) """ ), FILTER_BY_TYPE( """ ic.incident_type IN (:incidentTypes) """ ), GET_INCIDENT_CANDIDATES( """ select distinct o.offender_id_display as offender_no from ( select icp.offender_book_id, ic.modify_datetime from incident_cases ic join incident_case_parties icp on ic.incident_case_id = icp.incident_case_id union select icp.offender_book_id, icr.modify_datetime as offender_no from incident_case_responses icr join incident_case_parties icp on icr.incident_case_id = icp.incident_case_id union select icp.offender_book_id, icp.modify_datetime as offender_no from incident_case_parties icp ) data join offender_bookings ob on ob.offender_book_id = data.offender_book_id join offenders o on o.offender_id = ob.offender_id where data.modify_datetime > :cutoffTimestamp """ ) }
kotlin
6
0.62143
115
32.669231
130
starcoderdata
<reponame>AgoraIO-Community/eEducation-Android package io.agora.education.api.message class GroupMemberInfoMessage( var uuid: String, val userName: String, val avatar: String, var reward: Int ) { var online: Boolean = false var onStage: Boolean = false /**用户上台*/ fun online() { online = true } fun offLine() { online = false } fun onStage() { onStage = true } fun offStage() { onStage = false } }
kotlin
8
0.564453
46
15.03125
32
starcoderdata
<filename>codegen/src/test/kotlin/com/michaelom/strikt/generator/kapt/sources/PrivateClass.kt package com.michaelom.strikt.generator.kapt.sources import com.michaelom.strikt.generator.annotation.GenerateAssertions @GenerateAssertions private data class PrivateClass(val property: String = "property")
kotlin
12
0.848185
93
42.285714
7
starcoderdata
<reponame>lianwt115/qmqiu<filename>app/src/main/java/com/lwt/qmqiu/adapter/GiftBuyAdapter.kt<gh_stars>1-10 package com.lwt.qmqiu.adapter import android.content.Context import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.ImageView import android.widget.TextView import com.bumptech.glide.Glide import com.lwt.qmqiu.App import com.lwt.qmqiu.R import com.lwt.qmqiu.bean.GiftInfo import com.lwt.qmqiu.utils.UiUtils class GiftBuyAdapter(context: Context, list: List<GiftInfo>, listen: GiftBuyClickListen, mExchange: Boolean) : androidx.recyclerview.widget.RecyclerView.Adapter<GiftBuyAdapter.ListViewHolder>() { private var mContext: Context = context private var mTotalList: List<GiftInfo> = list private var mInflater: LayoutInflater = LayoutInflater.from(mContext) private var mGiftBuyClickListen: GiftBuyClickListen? = listen private var index = -1 private var mExchange = mExchange override fun onBindViewHolder(holder: ListViewHolder, position: Int) { val obj= mTotalList[position] Glide.with(mContext).load(obj.imgPath).into(holder.giftbuy_img) holder.giftbuy_count.text=obj.count.toString() holder.giftbuy_price.text="青木球:${obj?.price}" //选择背景 holder.giftbuy_img.background = mContext.getDrawable(if (obj.select) R.drawable.bg_acc_rectangle_0 else R.drawable.bg_line_rectangle_lastpage_noradius) holder.giftbuy_img.setOnClickListener { //只显示当前选择 if (index!=-1) mTotalList[index].select =false obj.select = true index = position notifyDataSetChanged() if (mExchange) { //检查是否超出兑换 if (checkEnoughEx(position,obj.count)) { obj.count += 1 holder.giftbuy_count.text=obj.count.toString() sendCash() }else{ UiUtils.showToast(mContext.getString(R.string.ex_notenough)) } }else{ //检查是否超出购买力 if (checkEnough(obj.price)) { obj.count += 1 holder.giftbuy_count.text=obj.count.toString() sendCash() }else{ UiUtils.showToast(mContext.getString(R.string.coin_notenough)) } } } holder.giftbuy_delete.setOnClickListener { obj.count = obj.count-1 if (obj.count<0) obj.count=0 holder.giftbuy_count.text=obj.count.toString() sendCash() } } private fun checkEnoughEx(index: Int,count:Int):Boolean { var user =App.instanceApp().getLocalUser() if (user!=null){ var giftLocal = user.gift.split("*") if (index<giftLocal.size) return count < giftLocal[index].toInt() } return false } private fun checkEnough(price: Int):Boolean { var user =App.instanceApp().getLocalUser() if (user!=null){ return getCount() <= (user.coin-price) } return false } fun getCount():Int{ var count = 0 mTotalList.forEach { giftInfo -> count += giftInfo.price * giftInfo.count } return count } fun getGiftCount():String{ return mTotalList[0].count.toString().plus("*${mTotalList[1].count}*${mTotalList[2].count}*${mTotalList[3].count}") } fun getPriceCount():String{ return mTotalList[0].price.toString().plus("*${mTotalList[1].price}*${mTotalList[2].price}*${mTotalList[3].price}") } private fun sendCash() { if (mGiftBuyClickListen != null) { mGiftBuyClickListen?.giftBuyClick(getCount()) } } override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ListViewHolder { var itemView=mInflater.inflate(R.layout.item_giftbuy, parent, false) return ListViewHolder(itemView!!, mContext) } override fun getItemCount(): Int { return mTotalList.size } class ListViewHolder(itemView: View, context: Context) : androidx.recyclerview.widget.RecyclerView.ViewHolder(itemView) { var giftbuy_img: ImageView = itemView.findViewById(R.id.giftbuy_img) as ImageView var giftbuy_delete: ImageView = itemView.findViewById(R.id.giftbuy_delete) as ImageView var giftbuy_count: TextView = itemView.findViewById(R.id.giftbuy_count) as TextView var giftbuy_price: TextView = itemView.findViewById(R.id.giftbuy_price) as TextView } interface GiftBuyClickListen{ fun giftBuyClick(cash: Int) } }
kotlin
28
0.616136
195
22.930348
201
starcoderdata
package dsx.bps.crypto.eth.erc20 import com.uchuhimo.konf.Config import dsx.bps.DBservices.core.TxService import dsx.bps.config.currencies.EthConfig import dsx.bps.core.datamodel.Currency import dsx.bps.core.datamodel.Tx import dsx.bps.core.datamodel.TxId import dsx.bps.core.datamodel.TxStatus import dsx.bps.crypto.eth.EthManager import dsx.bps.crypto.eth.erc20.datamodel.Erc20Contract import dsx.bps.crypto.eth.ethereum.datamodel.EthAccount import org.web3j.crypto.WalletUtils import org.web3j.protocol.core.methods.response.TransactionReceipt import org.web3j.utils.Convert import java.math.BigDecimal import java.math.BigInteger class Erc20Coin(token: Currency, conf: Config, txServ: TxService) : EthManager(conf, txServ) { override val currency : Currency = token override val connector: Erc20Rpc override val explorer: Erc20Explorer val contract: Erc20Contract val accounts = mutableMapOf<String, Pair<EthAccount,Boolean>>() init { val config = conf val credentials = WalletUtils.loadCredentials(systemAccount.password, systemAccount.wallet) val contractAddress = config[EthConfig.Erc20.tokens] .getValue(token.name) connector = Erc20Rpc(commonConnector, contractAddress, credentials) val ct = ethService.getContractByAddress(contractAddress) if (ct == null) { contract = Erc20Contract(contractAddress, connector.decimals(), connector.owner()) ethService.addContract(contract) } else { contract = ct } explorer = Erc20Explorer(this, connector.token, frequency, txService) } fun getTransactionByHash(hash: String) = connector.ethRpc.getTransactionByHash(hash) override fun getBalance(): BigDecimal = convertAmountToDecimal(connector.balanceOf(systemAccount.address)) override fun getAddress() : String { val newAccount = connector.ethRpc.generateWalletFile(defaultPasswordForNewAddresses, walletsDir) accounts[newAccount.address] = Pair(newAccount, false) return newAccount.address } override fun getTx(txid: TxId): Tx { val erc20Tx = ethService.getTokensTransfer(txid.hash, contract.owner, contract.address) return constructTx(txid.hash, erc20Tx.to, erc20Tx.amount) } fun constructTx(ethTxHash: String, to: String, amount: BigDecimal, currency: Currency = this.currency): Tx { val ethTx = connector.ethRpc.getTransactionByHash(ethTxHash) return object: Tx { override fun currency() = currency override fun hash() = ethTxHash override fun amount() = amount override fun destination() = to override fun fee(): BigDecimal { return if (this.status() == TxStatus.VALIDATING) { Convert.fromWei(ethTx.gasPrice.multiply(ethTx.gas).toBigDecimal(), Convert.Unit.ETHER) } else { Convert.fromWei(ethTx.gasPrice .multiply(connector.ethRpc.getTransactionReceiptByHash(ethTx.hash).gasUsed).toBigDecimal(), Convert.Unit.ETHER) } } override fun status(): TxStatus { val latestBlock = connector.ethRpc.getLatestBlock() if (connector.ethRpc.getTransactionByHash(ethTxHash).blockHash == null) { return TxStatus.VALIDATING } else { val conf = latestBlock.number - ethTx.blockNumber if (conf < confirmations.toBigInteger()) { return TxStatus.VALIDATING } else { return TxStatus.CONFIRMED } } } } } override fun sendPayment(amount: BigDecimal, address: String, tag: String?): Tx { val intAmount = convertAmountToInteger(amount) val resultHash = connector.transfer(address, intAmount).transactionHash val tx = connector.ethRpc.getTransactionByHash(resultHash) val transaction = constructTx(resultHash, address, amount) val txs = txService.add(transaction.status(), transaction.destination(),"", transaction.amount(), transaction.fee(), transaction.hash(), transaction.index(), transaction.currency()) ethService.addEthTransaction(systemAccount.address, tx.nonce.toLong() , txs, connector.token.contractAddress) return transaction } fun convertAmountToDecimal(amount: BigInteger) : BigDecimal { return amount.toBigDecimal().divide(Math.pow(10.0, contract.decimals.toDouble()).toBigDecimal()) } fun convertAmountToInteger(amount: BigDecimal) : BigInteger { return (amount * Math.pow(10.0, contract.decimals.toDouble()).toBigDecimal()).toBigInteger() } fun transferFrom(holder: String, amount: BigDecimal): TransactionReceipt { val intAmount = convertAmountToInteger(amount) return connector.transferFrom(holder, systemAccount.address, intAmount) } fun transferAllFundsFrom(holder: String): Pair<TransactionReceipt, BigDecimal> { val balance = connector.balanceOf(holder) return Pair(connector.transferFrom(holder, systemAccount.address, balance), convertAmountToDecimal(balance)) } fun approveFrom(owner: EthAccount): TransactionReceipt { val amount = BigInteger("2").pow(256).subtract(BigInteger.ONE) .divide(BigInteger.TEN.pow(contract.decimals)) return connector.approveSystem(systemAccount.address, owner, amount) } }
kotlin
33
0.675999
117
41.172932
133
starcoderdata
<filename>livedata-validation/src/main/java/com/forntoh/livedata_validation/rule/EqualRule.kt package com.forntoh.livedata_validation.rule import androidx.lifecycle.LiveData /** * Rule to check if Input text is equal to the provided text. * * This rule can be used to confirm input text. * e.g. Confirm Password, Confirm Email */ class EqualRule : BaseRule { private val mText: LiveData<String> constructor(text: LiveData<String>, errorRes: Int) : super(arrayOf(errorRes)) { this.mText = text } constructor(text: LiveData<String>, error: String) : super(arrayOf(error)) { this.mText = text } override fun validate(text: String?) = text == mText.value }
kotlin
11
0.705966
93
27.16
25
starcoderdata
package org.ireader.presentation.theme import androidx.compose.foundation.isSystemInDarkTheme import androidx.compose.material.ripple.RippleTheme import androidx.compose.material3.ColorScheme import androidx.compose.runtime.Composable import androidx.compose.runtime.getValue import androidx.compose.runtime.remember import androidx.compose.ui.graphics.Color import androidx.compose.ui.graphics.luminance import androidx.compose.ui.graphics.takeOrElse import dagger.hilt.android.lifecycle.HiltViewModel import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.SupervisorJob import kotlinx.coroutines.cancel import kotlinx.coroutines.cancelChildren import org.ireader.core_ui.preferences.PreferenceValues import org.ireader.core_ui.preferences.UiPreferences import org.ireader.core_ui.theme.AppRippleTheme import org.ireader.core_ui.theme.ExtraColors import org.ireader.core_ui.theme.Theme import org.ireader.core_ui.theme.asState import org.ireader.core_ui.theme.dark import org.ireader.core_ui.theme.getDarkColors import org.ireader.core_ui.theme.getLightColors import org.ireader.core_ui.theme.isLight import org.ireader.core_ui.theme.light import org.ireader.core_ui.theme.themes import org.ireader.core_ui.viewmodel.BaseViewModel import javax.inject.Inject @HiltViewModel class AppThemeViewModel @Inject constructor( private val uiPreferences: UiPreferences, coilLoaderFactory: org.ireader.image_loader.coil.CoilLoaderFactory, ) : BaseViewModel() { private val themeMode by uiPreferences.themeMode().asState() private val colorTheme by uiPreferences.colorTheme().asState() // private val lightTheme by uiPreferences.lightTheme().asState() // private val darkTheme by uiPreferences.darkTheme().asState() private val baseThemeJob = SupervisorJob() private val baseThemeScope = CoroutineScope(baseThemeJob) @Composable fun getRippleTheme(): RippleTheme { return when (themeMode) { PreferenceValues.ThemeMode.System -> AppRippleTheme(!isSystemInDarkTheme()) PreferenceValues.ThemeMode.Light -> AppRippleTheme(true) PreferenceValues.ThemeMode.Dark -> AppRippleTheme(false) } } @Composable fun getColors(): Pair<ColorScheme, ExtraColors> { val baseTheme = getBaseTheme(themeMode, colorTheme) val isLight = baseTheme.materialColors.isLight() val colors = remember(baseTheme.materialColors.isLight()) { baseThemeJob.cancelChildren() if (isLight) { uiPreferences.getLightColors().asState(baseThemeScope) } else { uiPreferences.getDarkColors().asState(baseThemeScope) } } val material = getMaterialColors(baseTheme.materialColors, colors.primary, colors.secondary) val custom = getExtraColors(baseTheme.extraColors, colors.bars) return material to custom } @Composable private fun getBaseTheme( themeMode: PreferenceValues.ThemeMode, colorTheme: Int, ): Theme { @Composable fun getTheme(fallbackIsLight: Boolean): Theme { return themes.firstOrNull { it.id == colorTheme }?.let { if (fallbackIsLight) { it.light() }else { it.dark() } }?: themes.first { it.lightColor.isLight() == fallbackIsLight }.light() } return when (themeMode) { PreferenceValues.ThemeMode.System -> if (!isSystemInDarkTheme()) { getTheme(true,) } else { getTheme(false) } PreferenceValues.ThemeMode.Light -> getTheme(true) PreferenceValues.ThemeMode.Dark -> getTheme(false) } } private fun getMaterialColors( baseColors: ColorScheme, colorPrimary: Color, colorSecondary: Color, ): ColorScheme { val primary = colorPrimary.takeOrElse { baseColors.primary } val secondary = colorSecondary.takeOrElse { baseColors.secondary } return baseColors.copy( primary = primary, primaryContainer = primary, secondary = secondary, secondaryContainer = secondary, onPrimary = if (primary.luminance() > 0.5) Color.Black else Color.White, onSecondary = if (secondary.luminance() > 0.5) Color.Black else Color.White, ) } private fun getExtraColors(colors: ExtraColors, colorBars: Color): ExtraColors { val appbar = colorBars.takeOrElse { colors.bars } return ExtraColors( bars = appbar, onBars = if (appbar.luminance() > 0.5) Color.Black else Color.White ) } override fun onDestroy() { baseThemeScope.cancel() } }
kotlin
23
0.686552
100
37.18254
126
starcoderdata
<gh_stars>1-10 package com.ziggeo.androidsdk.demo.presentation.auth import com.arellomobile.mvp.MvpView import com.arellomobile.mvp.viewstate.strategy.AddToEndSingleStrategy import com.arellomobile.mvp.viewstate.strategy.StateStrategyType /** * Created by <NAME> on 25-Sep-19. * Ziggeo, Inc. * <EMAIL> */ @StateStrategyType(AddToEndSingleStrategy::class) interface AuthView : MvpView { fun showQrCannotBeEmptyError() fun showScannerButton() fun showEnterQrField() }
kotlin
7
0.777778
69
22.190476
21
starcoderdata
/* * Copyright 2000-2018 JetBrains s.r.o. and Kotlin Programming Language contributors. * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ package org.jetbrains.kotlin.descriptors import org.jetbrains.kotlin.descriptors.annotations.Annotations import org.jetbrains.kotlin.descriptors.impl.ClassDescriptorBase import org.jetbrains.kotlin.descriptors.impl.EmptyPackageFragmentDescriptor import org.jetbrains.kotlin.descriptors.impl.TypeParameterDescriptorImpl import org.jetbrains.kotlin.name.ClassId import org.jetbrains.kotlin.name.FqName import org.jetbrains.kotlin.name.Name import org.jetbrains.kotlin.resolve.descriptorUtil.module import org.jetbrains.kotlin.resolve.scopes.MemberScope import org.jetbrains.kotlin.storage.StorageManager import org.jetbrains.kotlin.types.ClassTypeConstructorImpl import org.jetbrains.kotlin.types.Variance import org.jetbrains.kotlin.types.checker.KotlinTypeRefiner class NotFoundClasses(private val storageManager: StorageManager, private val module: ModuleDescriptor) { /** * @param typeParametersCount list of numbers of type parameters in this class and all its outer classes, starting from this class */ private data class ClassRequest(val classId: ClassId, val typeParametersCount: List<Int>) private val packageFragments = storageManager.createMemoizedFunction<FqName, PackageFragmentDescriptor> { fqName -> EmptyPackageFragmentDescriptor(module, fqName) } private val classes = storageManager.createMemoizedFunction<ClassRequest, ClassDescriptor> { (classId, typeParametersCount) -> if (classId.isLocal) { throw UnsupportedOperationException("Unresolved local class: $classId") } val container = classId.outerClassId?.let { outerClassId -> getClass(outerClassId, typeParametersCount.drop(1)) } ?: packageFragments(classId.packageFqName) // Treat a class with a nested ClassId as inner for simplicity, otherwise the outer type cannot have generic arguments val isInner = classId.isNestedClass MockClassDescriptor(storageManager, container, classId.shortClassName, isInner, typeParametersCount.firstOrNull() ?: 0) } class MockClassDescriptor internal constructor( storageManager: StorageManager, container: DeclarationDescriptor, name: Name, private val isInner: Boolean, numberOfDeclaredTypeParameters: Int ) : ClassDescriptorBase(storageManager, container, name, SourceElement.NO_SOURCE, /* isExternal = */ false) { private val declaredTypeParameters = (0 until numberOfDeclaredTypeParameters).map { index -> TypeParameterDescriptorImpl.createWithDefaultBound( this, Annotations.EMPTY, false, Variance.INVARIANT, Name.identifier("T$index"), index, storageManager ) } private val typeConstructor = ClassTypeConstructorImpl(this, computeConstructorTypeParameters(), setOf(module.builtIns.anyType), storageManager) override fun getKind() = ClassKind.CLASS override fun getModality() = Modality.FINAL override fun getVisibility() = DescriptorVisibilities.PUBLIC override fun getTypeConstructor() = typeConstructor override fun getDeclaredTypeParameters() = declaredTypeParameters override fun isInner() = isInner override fun isCompanionObject() = false override fun isData() = false override fun isInline() = false override fun isFun() = false override fun isValue() = false override fun isExpect() = false override fun isActual() = false override fun isExternal() = false override val annotations: Annotations get() = Annotations.EMPTY override fun getUnsubstitutedMemberScope(kotlinTypeRefiner: KotlinTypeRefiner) = MemberScope.Empty override fun getStaticScope() = MemberScope.Empty override fun getConstructors(): Collection<ClassConstructorDescriptor> = emptySet() override fun getUnsubstitutedPrimaryConstructor(): ClassConstructorDescriptor? = null override fun getCompanionObjectDescriptor(): ClassDescriptor? = null override fun getSealedSubclasses(): Collection<ClassDescriptor> = emptyList() override fun toString() = "class $name (not found)" } // We create different ClassDescriptor instances for types with the same ClassId but different number of type arguments. // (This may happen when a class with the same FQ name is instantiated with different type arguments in different modules.) // It's better than creating just one descriptor because otherwise would fail in multiple places where it's asserted that // the number of type arguments in a type must be equal to the number of the type parameters of the class fun getClass(classId: ClassId, typeParametersCount: List<Int>): ClassDescriptor { return classes(ClassRequest(classId, typeParametersCount)) } }
kotlin
24
0.743706
134
51.412371
97
starcoderdata
<reponame>odiapratama/Android-Kotlin-COVID19 package com.covid19.monitoring.utils import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.GlobalScope import kotlinx.coroutines.launch import kotlin.coroutines.CoroutineContext fun <T> CoroutineScope.safeApiCall( call: suspend () -> T, error: (Throwable) -> Unit = {} ) { launch { try { call() } catch (t: Throwable) { error(t) } } } fun launchOn(coroutineContext: CoroutineContext, call: CoroutineScope.() -> (Unit)) { GlobalScope.launch(coroutineContext) { call(this) } }
kotlin
16
0.663415
85
22.692308
26
starcoderdata
/** * Created by Brendan * Date: 2/29/2020 * Time: 10:26 PM */ package com.soyle.stories.workspace.usecases import com.soyle.stories.domain.project.Project import com.soyle.stories.domain.validation.NonBlankString import com.soyle.stories.workspace.ProjectDoesNotExistAtLocation import com.soyle.stories.workspace.ProjectException import com.soyle.stories.workspace.UnexpectedProjectAlreadyOpenAtLocation import com.soyle.stories.workspace.entities.Workspace import com.soyle.stories.workspace.repositories.ProjectRepository import com.soyle.stories.workspace.repositories.WorkspaceRepository import com.soyle.stories.workspace.usecases.closeProject.CloseProject import com.soyle.stories.workspace.usecases.openProject.OpenProject import com.soyle.stories.workspace.usecases.openProject.OpenProjectUseCase import com.soyle.stories.workspace.valueobjects.ProjectFile import kotlinx.coroutines.runBlocking import org.junit.jupiter.api.Assertions.* import org.junit.jupiter.api.Test import java.util.* class OpenProjectTest { @Test fun `project does not exist`() { given { projectDoesNotExist() } `when` { openProject() } then { workspaceMustNotHaveBeenUpdated() val output = output.mustBe<ProjectDoesNotExistAtLocation> { "" } output.location.mustEqual(location) { "" } } } @Test fun `workspace has open project at requested location`() { given { projectExists() workspaceExists() workspaceHasProjectWithRequestedLocation() } `when` { openProject() } then { workspaceMustNotHaveBeenUpdated() val output = output.mustBe<UnexpectedProjectAlreadyOpenAtLocation> { "Output is of unexpected type" } output.location.mustEqual(location) { "" } } } @Test fun `open first project`() { given { projectExists() workspaceDoesNotExist() } `when` { openProject() } then { useCaseShouldHaveSucceeded() } } @Test fun `open second project`() { given { projectExists() workspaceExists() workspaceContainsOneProject() } `when` { openProject() } then { workspaceMustNotHaveBeenUpdated() projectMustBeInOutput() val output = output.mustBe<OpenProject.ResponseModel>() { "" } output.requiresConfirmation.mustEqual(true) { "" } } } @Test fun `open third project`() { given { projectExists() workspaceExists() workspaceContainsTwoProjects() } `when` { openProject() } then { useCaseShouldHaveSucceeded() firstProjectMustBeInWorkspace() secondProjectMustBeInWorkspace() } } @Test fun `force second project`() { given { projectExists() workspaceExists() workspaceContainsOneProject() } `when` { forceOpenProject() } then { useCaseShouldHaveSucceeded() firstProjectMustBeInWorkspace() } } @Test fun `replace first project with new project`() { given { projectExists() workspaceExists() workspaceContainsOneProject() } `when` { replaceOpenProject() } then { useCaseShouldHaveSucceeded() firstProjectMustNotBeInWorkspace() closeProjectOutput.mustBe<CloseProject.ResponseModel> { "Close project output is of incorrect type" } } } private lateinit var setup: OpenProjectTestSetup private fun given(setup: OpenProjectTestSetup.() -> Unit) { this.setup = OpenProjectTestSetup() this.setup.setup() } private class OpenProjectTestSetup { val workerId = UUID.randomUUID().toString() val projectFile = projectFile() val projectUUID = projectFile.projectId.uuid val projectName = projectFile.projectName val location = projectFile.location var projectExists: Boolean = false private set var workspace: Workspace? = null private set private fun projectFile() = ProjectFile( Project.Id(UUID.randomUUID()), "Project - ${UUID.randomUUID()}", "other.location.${UUID.randomUUID()}" ) fun projectDoesNotExist() { projectExists = false } fun projectExists() { projectExists = true } fun workspaceExists() { workspace = Workspace(workerId, listOf()) } fun workspaceDoesNotExist() { workspace = null } fun workspaceContainsOneProject() { workspace = Workspace(workerId, listOf(projectFile())) } fun workspaceContainsTwoProjects() { workspace = Workspace(workerId, listOf(projectFile(), projectFile())) } fun workspaceHasProjectWithRequestedLocation() { workspace = Workspace( workerId, (workspace?.openProjects ?: listOf()) + ProjectFile(Project.Id(UUID.randomUUID()), "Project - ${UUID.randomUUID()}", location) ) } } private lateinit var executable: OpenProjectExecution private fun `when`(executions: OpenProjectExecution.() -> Unit) { executable = OpenProjectExecution( setup.workerId, setup.location, setup.workspace, setup.projectFile.takeIf { setup.projectExists } ) executable.executions() } private class OpenProjectExecution( workerId: String, val location: String, val workspace: Workspace?, val project: ProjectFile? ) { var createdWorkspace: Workspace? = null private set var updatedWorkspace: Workspace? = null private set private val workspaceRepository = object : WorkspaceRepository { override suspend fun addNewWorkspace(workspace: Workspace) { createdWorkspace = workspace } override suspend fun getWorkSpaceForWorker(workerId: String): Workspace? = updatedWorkspace ?: createdWorkspace ?: workspace override suspend fun updateWorkspace(workspace: Workspace) { updatedWorkspace = workspace } } private val projectRepository = object : ProjectRepository { override suspend fun getProjectAtLocation(location: String): Project? = project?.let { Project(it.projectId, NonBlankString.create(it.projectName)!!) } } private val closeProjectUseCase = object : CloseProject { override suspend fun invoke(projectId: UUID, outputPort: CloseProject.OutputPort) { updatedWorkspace = Workspace(workerId, (updatedWorkspace?.openProjects?.filterNot { it.projectId.uuid == projectId } ?: listOf())) outputPort.receiveCloseProjectResponse(CloseProject.ResponseModel(projectId)) } } private val useCase: OpenProject = OpenProjectUseCase( workerId, workspaceRepository, projectRepository, closeProjectUseCase ) var result: Any? = null private set var closeProjectResult: Any? = null private set private val outputPort: OpenProject.OutputPort = object : OpenProject.OutputPort { override fun receiveOpenProjectFailure(failure: ProjectException) { result = failure } override suspend fun receiveCloseProjectResponse(response: CloseProject.ResponseModel) { closeProjectResult = response } override suspend fun receiveOpenProjectResponse(response: OpenProject.ResponseModel) { result = response } override fun receiveCloseProjectFailure(failure: Exception) { closeProjectResult = failure } } fun openProject() { runBlocking { useCase.invoke(location, outputPort) } } fun forceOpenProject() { runBlocking { useCase.forceOpenProject(location, outputPort) } } fun replaceOpenProject() { runBlocking { useCase.replaceOpenProject(location, outputPort) } } } private fun then(assert: OpenProjectAssertions.() -> Unit) { OpenProjectAssertions( executable.result, executable.closeProjectResult, executable.location, executable.project, executable.createdWorkspace, executable.updatedWorkspace, executable.workspace?.openProjects ?: listOf() ).assert() } class OpenProjectAssertions( val output: Any?, val closeProjectOutput: Any?, val location: String, val openedProject: ProjectFile?, private val createdWorkspace: Workspace?, private val updatedWorkspace: Workspace?, private val originalProjectList: List<ProjectFile> ) { inline fun <reified T> Any?.mustBe(message: () -> String = { "" }): T { assert(this is T) { "${message()}:\n $this is not ${T::class.simpleName}" } return this as T } fun Any?.mustEqual(expected: Any?, message: () -> String = { "" }) { assertEquals(expected, this) { message() } } fun workspaceMustNotHaveBeenUpdated() { assertNull(updatedWorkspace) { "Workspace should not have been updated" } } fun workspaceMustHaveBeenCreated() { assertNotNull(createdWorkspace) { "Workspace should have been created" } } fun projectMustBeInWorkspace() { if (openedProject == null) error("Opened project is null") val workspace = updatedWorkspace ?: createdWorkspace ?: error("Workspace was never updated or created") val openProject = workspace.openProjects.find { it.projectId == openedProject.projectId } ?: error("Workspace does not have project with opened project id") openProject.projectName.mustEqual(openedProject.projectName) { "Project names are not equal" } openProject.location.mustEqual(openedProject.location) { "Project locations are not equal" } } fun projectMustBeInOutput() { if (openedProject == null) error("Opened project is null") val output = output.mustBe<OpenProject.ResponseModel>() output.projectId.mustEqual(openedProject.projectId.uuid) { "Incorrect project id in output" } output.projectName.mustEqual(openedProject.projectName) { "Incorrect project name in output" } output.projectLocation.mustEqual(openedProject.location) { "Incorrect project location in output" } } fun workspaceMustHaveBeenUpdated() { assertNotNull(updatedWorkspace) { "Workspace should have been updated" } } fun firstProjectMustBeInWorkspace() { assert( updatedWorkspace!!.openProjects.contains(originalProjectList.first()) ) { "First project not in updated workspace" } } fun useCaseShouldHaveSucceeded() { workspaceMustHaveBeenUpdated() projectMustBeInWorkspace() projectMustBeInOutput() } fun firstProjectMustNotBeInWorkspace() { assert( updatedWorkspace?.openProjects?.contains(originalProjectList.first()) != true ) { "First project still in updated workspace" } } fun secondProjectMustBeInWorkspace() { assert( updatedWorkspace!!.openProjects.contains(originalProjectList.component2()) ) { "Second project not in updated workspace" } } } }
kotlin
27
0.602426
146
31.801061
377
starcoderdata
package io.github.chrislo27.rhre3.sfxdb enum class PlayalongInput(val id: String, val deprecatedIDs: List<String> = listOf(), val isTouchScreen: Boolean = false) { BUTTON_A("A"), BUTTON_B("B"), BUTTON_DPAD("+"), BUTTON_A_OR_DPAD("A_+"), BUTTON_DPAD_UP("+_up"), BUTTON_DPAD_DOWN("+_down"), BUTTON_DPAD_LEFT("+_left"), BUTTON_DPAD_RIGHT("+_right"), TOUCH_TAP("touch_tap", isTouchScreen = true), TOUCH_FLICK("touch_flick", isTouchScreen = true), TOUCH_RELEASE("touch_release", isTouchScreen = true), TOUCH_QUICK_TAP("touch_quick_tap", isTouchScreen = true), TOUCH_SLIDE("touch_slide", isTouchScreen = true); companion object { val VALUES: List<PlayalongInput> = values().toList() private val ID_MAP: Map<String, PlayalongInput> = VALUES.flatMap { pi -> listOf(pi.id to pi) + pi.deprecatedIDs.map { i -> i to pi } }.toMap() private val INDICES_MAP: Map<PlayalongInput, Int> = VALUES.associateWith(VALUES::indexOf) private val REVERSE_INDICES_MAP: Map<PlayalongInput, Int> = VALUES.associateWith { VALUES.size - 1 - VALUES.indexOf(it) } operator fun get(id: String): PlayalongInput? = ID_MAP[id] fun indexOf(playalongInput: PlayalongInput?): Int = if (playalongInput == null) -1 else INDICES_MAP.getOrDefault(playalongInput, -1) fun reverseIndexOf(playalongInput: PlayalongInput?): Int = if (playalongInput == null) -1 else REVERSE_INDICES_MAP.getOrDefault(playalongInput, -1) } } enum class PlayalongMethod(val instantaneous: Boolean, val isRelease: Boolean) { PRESS(true, false), PRESS_AND_HOLD(false, false), LONG_PRESS(false, false), RELEASE_AND_HOLD(false, true), RELEASE(true, true); // RELEASE is for Quick Tap companion object { val VALUES = values().toList() private val ID_MAP: Map<String, PlayalongMethod> = VALUES.associateBy { it.name } operator fun get(id: String): PlayalongMethod? = ID_MAP[id] } }
kotlin
21
0.667169
155
39.591837
49
starcoderdata
<reponame>zoldater/kotlin-spm-plugin<filename>settings.gradle.kts pluginManagement { repositories { gradlePluginPortal() mavenCentral() jcenter() } } rootProject.name = ("kotlin-gradle-spm-plugin") include(":example") includeBuild("plugin-build")
kotlin
14
0.690391
65
20.615385
13
starcoderdata
// Automatically generated - do not modify! package mui.material @Suppress("NAME_CONTAINS_ILLEGAL_CHARS") // language=JavaScript @JsName("""(/*union*/{primary: 'primary', secondary: 'secondary', error: 'error', info: 'info', success: 'success', warning: 'warning', default: 'default'}/*union*/)""") external enum class SwitchColor { primary, secondary, error, info, success, warning, default, ; }
kotlin
7
0.655093
169
23
18
starcoderdata
<filename>carp.protocols.core/src/commonTest/kotlin/dk/cachet/carp/protocols/domain/configuration/TaskConfigurationTest.kt package dk.cachet.carp.protocols.domain.configuration import dk.cachet.carp.common.infrastructure.test.StubTaskDescriptor import kotlin.test.* /** * Base class with tests for [TaskConfiguration] which can be used to test extending types. */ interface TaskConfigurationTest { /** * Called for each test to create a task configuration to run tests on. */ fun createTaskConfiguration(): TaskConfiguration @Test fun addTask_succeeds() { val configuration = createTaskConfiguration() val task = StubTaskDescriptor() val isAdded: Boolean = configuration.addTask( task ) assertTrue( isAdded ) assertTrue( configuration.tasks.contains( task ) ) } @Test fun removeTask_succeeds() { val configuration = createTaskConfiguration() val task = StubTaskDescriptor() configuration.addTask( task ) val isRemoved: Boolean = configuration.removeTask( task ) assertTrue( isRemoved ) assertFalse( configuration.tasks.contains( task ) ) } @Test fun removeTask_returns_false_when_task_not_present() { val configuration = createTaskConfiguration() val task = StubTaskDescriptor() val isRemoved: Boolean = configuration.removeTask( task ) assertFalse( isRemoved ) } @Test fun addTask_multiple_times_only_adds_first_time() { val configuration = createTaskConfiguration() val task = StubTaskDescriptor() configuration.addTask( task ) val isAdded: Boolean = configuration.addTask( task ) assertFalse( isAdded ) assertEquals( 1, configuration.tasks.count() ) } @Test fun do_not_allow_duplicate_names_for_tasks() { val configuration = createTaskConfiguration() configuration.addTask( StubTaskDescriptor( "Unique name" ) ) configuration.addTask( StubTaskDescriptor( "Duplicate name" ) ) // Adding an additional task with duplicate name should fail. assertFailsWith<IllegalArgumentException> { configuration.addTask( StubTaskDescriptor( "Duplicate name" ) ) } } }
kotlin
22
0.673753
122
28.935065
77
starcoderdata
package nnl.rocks.kactoos.list import nnl.rocks.kactoos.iterable.IterableOf import nnl.rocks.kactoos.scalar.StickyScalar /** * List decorator that goes through the list only once. * * The list is read only. * * There is no thread-safety guarantee. * * @param X Type of item * @since 0.4 */ class StickyList<X : Any> : ListEnvelope<X> { constructor(collection: Collection<X>) : super(StickyScalar { collection.toList() }) constructor(vararg items: X) : this(IterableOf(items.asIterable())) constructor(items: Iterable<X>) : this(ListOf(items)) }
kotlin
15
0.711033
88
23.826087
23
starcoderdata
<gh_stars>10-100 /* * Copyright (c) 2019 大前良介 (<NAME>) * * This software is released under the MIT License. * http://opensource.org/licenses/MIT */ package net.mm2d.upnp.internal.impl import com.google.common.truth.Truth.assertThat import io.mockk.every import io.mockk.mockk import io.mockk.verify import net.mm2d.upnp.HttpClient import net.mm2d.upnp.Icon import net.mm2d.upnp.SsdpMessage import net.mm2d.upnp.internal.message.FakeSsdpMessage import org.junit.Test import org.junit.runner.RunWith import org.junit.runners.JUnit4 import java.net.InetAddress @Suppress("TestFunctionName", "NonAsciiCharacters") @RunWith(JUnit4::class) class DeviceBuilderTest { @Test fun build() { val cp: ControlPointImpl = mockk(relaxed = true) val message: SsdpMessage = mockk(relaxed = true) val location = "location" val uuid = "uuid" every { message.location } returns location every { message.uuid } returns uuid val description = "description" val upc = "upc" val deviceType = "deviceType" val friendlyName = "friendlyName" val manufacture = "manufacture" val manufactureUrl = "manufactureUrl" val modelName = "modelName" val modelUrl = "modelUrl" val modelDescription = "modelDescription" val modelNumber = "modelNumber" val serialNumber = "serialNumber" val presentationUrl = "presentationUrl" val urlBase = "urlBase" val icon: Icon = mockk(relaxed = true) val service: ServiceImpl = mockk(relaxed = true) val serviceBuilder: ServiceImpl.Builder = mockk(relaxed = true) every { serviceBuilder.setDevice(any()) } returns serviceBuilder every { serviceBuilder.build() } returns service val device = DeviceImpl.Builder(cp, message) .setDescription(description) .setUdn(uuid) .setUpc(upc) .setDeviceType(deviceType) .setFriendlyName(friendlyName) .setManufacture(manufacture) .setManufactureUrl(manufactureUrl) .setModelName(modelName) .setModelUrl(modelUrl) .setModelDescription(modelDescription) .setModelNumber(modelNumber) .setSerialNumber(serialNumber) .setPresentationUrl(presentationUrl) .setUrlBase(urlBase) .addIcon(icon) .addServiceBuilder(serviceBuilder) .build() assertThat(device.description).isEqualTo(description) assertThat(device.udn).isEqualTo(uuid) assertThat(device.upc).isEqualTo(upc) assertThat(device.deviceType).isEqualTo(deviceType) assertThat(device.friendlyName).isEqualTo(friendlyName) assertThat(device.manufacture).isEqualTo(manufacture) assertThat(device.manufactureUrl).isEqualTo(manufactureUrl) assertThat(device.modelName).isEqualTo(modelName) assertThat(device.modelUrl).isEqualTo(modelUrl) assertThat(device.modelDescription).isEqualTo(modelDescription) assertThat(device.modelNumber).isEqualTo(modelNumber) assertThat(device.serialNumber).isEqualTo(serialNumber) assertThat(device.presentationUrl).isEqualTo(presentationUrl) assertThat(device.baseUrl).isEqualTo(urlBase) assertThat(device.iconList).contains(icon) assertThat(device.serviceList).contains(service) } @Test fun build_最低限のパラメータ() { val cp: ControlPointImpl = mockk(relaxed = true) val message: SsdpMessage = mockk(relaxed = true) val location = "location" val uuid = "uuid" every { message.location } returns location every { message.uuid } returns uuid val description = "description" val upc = "upc" val deviceType = "deviceType" val friendlyName = "friendlyName" val manufacture = "manufacture" val modelName = "modelName" val device = DeviceImpl.Builder(cp, message) .setDescription(description) .setUdn(uuid) .setUpc(upc) .setDeviceType(deviceType) .setFriendlyName(friendlyName) .setManufacture(manufacture) .setModelName(modelName) .build() assertThat(device.description).isEqualTo(description) assertThat(device.udn).isEqualTo(uuid) assertThat(device.upc).isEqualTo(upc) assertThat(device.deviceType).isEqualTo(deviceType) assertThat(device.friendlyName).isEqualTo(friendlyName) assertThat(device.manufacture).isEqualTo(manufacture) assertThat(device.modelName).isEqualTo(modelName) } @Test(expected = IllegalStateException::class) fun build_Description不足() { val cp: ControlPointImpl = mockk(relaxed = true) val message: SsdpMessage = mockk(relaxed = true) val location = "location" val uuid = "uuid" every { message.location } returns location every { message.uuid } returns uuid val deviceType = "deviceType" val friendlyName = "friendlyName" val manufacture = "manufacture" val modelName = "modelName" DeviceImpl.Builder(cp, message) .setUdn(uuid) .setDeviceType(deviceType) .setFriendlyName(friendlyName) .setManufacture(manufacture) .setModelName(modelName) .build() } @Test(expected = IllegalStateException::class) fun build_DeviceType不足() { val cp: ControlPointImpl = mockk(relaxed = true) val message: SsdpMessage = mockk(relaxed = true) val location = "location" val uuid = "uuid" every { message.location } returns location every { message.uuid } returns uuid val description = "description" val friendlyName = "friendlyName" val manufacture = "manufacture" val modelName = "modelName" DeviceImpl.Builder(cp, message) .setDescription(description) .setUdn(uuid) .setFriendlyName(friendlyName) .setManufacture(manufacture) .setModelName(modelName) .build() } @Test(expected = IllegalStateException::class) fun build_FriendlyName不足() { val cp: ControlPointImpl = mockk(relaxed = true) val message: SsdpMessage = mockk(relaxed = true) val location = "location" val uuid = "uuid" every { message.location } returns location every { message.uuid } returns uuid val description = "description" val deviceType = "deviceType" val manufacture = "manufacture" val modelName = "modelName" DeviceImpl.Builder(cp, message) .setDescription(description) .setUdn(uuid) .setDeviceType(deviceType) .setManufacture(manufacture) .setModelName(modelName) .build() } @Test(expected = IllegalStateException::class) fun build_Manufacture不足() { val cp: ControlPointImpl = mockk(relaxed = true) val message: SsdpMessage = mockk(relaxed = true) val location = "location" val uuid = "uuid" every { message.location } returns location every { message.uuid } returns uuid val description = "description" val deviceType = "deviceType" val friendlyName = "friendlyName" val modelName = "modelName" DeviceImpl.Builder(cp, message) .setDescription(description) .setUdn(uuid) .setDeviceType(deviceType) .setFriendlyName(friendlyName) .setModelName(modelName) .build() } @Test(expected = IllegalStateException::class) fun build_ModelName不足() { val cp: ControlPointImpl = mockk(relaxed = true) val message: SsdpMessage = mockk(relaxed = true) val location = "location" val uuid = "uuid" every { message.location } returns location every { message.uuid } returns uuid val description = "description" val deviceType = "deviceType" val friendlyName = "friendlyName" val manufacture = "manufacture" DeviceImpl.Builder(cp, message) .setDescription(description) .setUdn(uuid) .setDeviceType(deviceType) .setFriendlyName(friendlyName) .setManufacture(manufacture) .build() } @Test(expected = IllegalStateException::class) fun build_Udn不足() { val cp: ControlPointImpl = mockk(relaxed = true) val message: SsdpMessage = mockk(relaxed = true) val location = "location" val uuid = "uuid" every { message.location } returns location every { message.uuid } returns uuid val description = "description" val deviceType = "deviceType" val friendlyName = "friendlyName" val manufacture = "manufacture" val modelName = "modelName" DeviceImpl.Builder(cp, message) .setDescription(description) .setDeviceType(deviceType) .setFriendlyName(friendlyName) .setManufacture(manufacture) .setModelName(modelName) .build() } @Test(expected = IllegalStateException::class) fun build_Udn不一致() { val cp: ControlPointImpl = mockk(relaxed = true) val message: SsdpMessage = mockk(relaxed = true) val location = "location" val uuid = "uuid" every { message.location } returns location every { message.uuid } returns uuid val description = "description" val udn = "udn" val upc = "upc" val deviceType = "deviceType" val friendlyName = "friendlyName" val manufacture = "manufacture" val modelName = "modelName" DeviceImpl.Builder(cp, message) .setDescription(description) .setUdn(udn) .setUpc(upc) .setDeviceType(deviceType) .setFriendlyName(friendlyName) .setManufacture(manufacture) .setModelName(modelName) .build() } @Test fun build_PinnedSsdpMessage_update() { val message: FakeSsdpMessage = mockk(relaxed = true) every { message.location } returns "location" every { message.isPinned } returns true val newMessage: SsdpMessage = mockk(relaxed = true) val builder = DeviceImpl.Builder(mockk(relaxed = true), message) builder.updateSsdpMessage(newMessage) assertThat(builder.getSsdpMessage()).isEqualTo(message) } @Test(expected = IllegalArgumentException::class) fun build_不正なSsdpMessage1() { val illegalMessage: SsdpMessage = mockk(relaxed = true) every { illegalMessage.location } returns null DeviceImpl.Builder(mockk(relaxed = true), illegalMessage) } @Test(expected = IllegalArgumentException::class) fun build_不正なSsdpMessage2() { val message: SsdpMessage = mockk(relaxed = true) val location = "location" val uuid = "uuid" every { message.location } returns location every { message.uuid } returns uuid val illegalMessage: SsdpMessage = mockk(relaxed = true) every { illegalMessage.location } returns null DeviceImpl.Builder(mockk(relaxed = true), message) .updateSsdpMessage(illegalMessage) } @Test fun updateSsdpMessage_EmbeddedDeviceへの伝搬() { val message: SsdpMessage = mockk(relaxed = true) val location = "location" val uuid = "uuid" every { message.location } returns location every { message.uuid } returns uuid val embeddedDeviceBuilder: DeviceImpl.Builder = mockk(relaxed = true) DeviceImpl.Builder(mockk(relaxed = true), message) .setEmbeddedDeviceBuilderList(listOf(embeddedDeviceBuilder)) .updateSsdpMessage(message) verify(exactly = 1) { embeddedDeviceBuilder.updateSsdpMessage(message) } } @Test fun putTag_namespaceのnullと空白は等価() { val message: SsdpMessage = mockk(relaxed = true) every { message.location } returns "location" every { message.uuid } returns "uuid" val tag1 = "tag1" val value1 = "value1" val tag2 = "tag2" val value2 = "value2" val device = DeviceImpl.Builder(mockk(relaxed = true), message) .setDescription("description") .setUdn("uuid") .setUpc("upc") .setDeviceType("deviceType") .setFriendlyName("friendlyName") .setManufacture("manufacture") .setModelName("modelName") .putTag(null, tag1, value1) .putTag("", tag2, value2) .build() assertThat(device.getValueWithNamespace("", tag1)).isEqualTo(value1) assertThat(device.getValueWithNamespace("", tag2)).isEqualTo(value2) } @Test fun onDownloadDescription() { val message: FakeSsdpMessage = mockk(relaxed = true) every { message.location } returns "location" val builder = DeviceImpl.Builder(mockk(relaxed = true), message) val client: HttpClient = mockk(relaxed = true) val address = InetAddress.getByName("127.0.0.1") every { client.localAddress } returns address builder.setDownloadInfo(client) verify(exactly = 1) { client.localAddress } verify(exactly = 1) { message.localAddress = address } } @Test(expected = IllegalStateException::class) fun onDownloadDescription_before_download() { val message: FakeSsdpMessage = mockk(relaxed = true) every { message.location } returns "location" val builder = DeviceImpl.Builder(mockk(relaxed = true), message) val client = HttpClient() builder.setDownloadInfo(client) } }
kotlin
40
0.632414
80
36.021164
378
starcoderdata
<reponame>therealansh/kmath /* * Copyright 2018-2021 KMath contributors. * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ package space.kscience.kmath.internal import kotlin.math.ln import kotlin.math.min internal object InternalUtils { private val FACTORIALS = longArrayOf( 1L, 1L, 2L, 6L, 24L, 120L, 720L, 5040L, 40320L, 362880L, 3628800L, 39916800L, 479001600L, 6227020800L, 87178291200L, 1307674368000L, 20922789888000L, 355687428096000L, 6402373705728000L, 121645100408832000L, 2432902008176640000L ) private const val BEGIN_LOG_FACTORIALS = 2 fun factorial(n: Int): Long = FACTORIALS[n] fun validateProbabilities(probabilities: DoubleArray?): Double { require(!(probabilities == null || probabilities.isEmpty())) { "Probabilities must not be empty." } val sumProb = probabilities.sumOf { prob -> require(!(prob < 0 || prob.isInfinite() || prob.isNaN())) { "Invalid probability: $prob" } prob } require(!(sumProb.isInfinite() || sumProb <= 0)) { "Invalid sum of probabilities: $sumProb" } return sumProb } class FactorialLog private constructor(numValues: Int, cache: DoubleArray?) { private val logFactorials: DoubleArray = DoubleArray(numValues) init { val endCopy: Int if (cache != null && cache.size > BEGIN_LOG_FACTORIALS) { // Copy available values. endCopy = min(cache.size, numValues) cache.copyInto( logFactorials, BEGIN_LOG_FACTORIALS, BEGIN_LOG_FACTORIALS, endCopy ) } else // All values to be computed endCopy = BEGIN_LOG_FACTORIALS // Compute remaining values. (endCopy until numValues).forEach { i -> if (i < FACTORIALS.size) logFactorials[i] = ln(FACTORIALS[i].toDouble()) else logFactorials[i] = logFactorials[i - 1] + ln(i.toDouble()) } } fun value(n: Int): Double { if (n < logFactorials.size) return logFactorials[n] return if (n < FACTORIALS.size) ln(FACTORIALS[n].toDouble()) else InternalGamma.logGamma(n + 1.0) } companion object { fun create(): FactorialLog = FactorialLog(0, null) } } }
kotlin
26
0.586315
115
32.473684
76
starcoderdata
/* Copyright 2017-2022 <NAME>. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at 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 batect.execution.model.stages import batect.execution.model.events.TaskEvent import batect.execution.model.rules.TaskStepRule import batect.execution.model.rules.TaskStepRuleEvaluationResult abstract class Stage(rules: Set<TaskStepRule>) { private val remainingRules = rules.toMutableSet() fun popNextStep(pastEvents: Set<TaskEvent>, stepsStillRunning: Boolean): NextStepResult { if (remainingRules.isEmpty() && determineIfStageIsComplete(pastEvents, stepsStillRunning)) { return StageComplete } remainingRules.forEach { rule -> val result = rule.evaluate(pastEvents) if (result is TaskStepRuleEvaluationResult.Ready) { remainingRules.remove(rule) return StepReady(result.step) } } return NoStepsReady } protected abstract fun determineIfStageIsComplete(pastEvents: Set<TaskEvent>, stepsStillRunning: Boolean): Boolean }
kotlin
21
0.716285
118
34.727273
44
starcoderdata
package reactivecircus.flowbinding.activity import androidx.test.filters.LargeTest import com.google.common.truth.Truth.assertThat import org.junit.Test import reactivecircus.blueprint.testing.action.pressBack import reactivecircus.flowbinding.activity.fixtures.ActivityFragment import reactivecircus.flowbinding.testing.FlowRecorder import reactivecircus.flowbinding.testing.launchTest import reactivecircus.flowbinding.testing.recordWith @LargeTest class OnBackPressedDispatcherBackPressedFlowTest { @Test fun onBackPressedDispatcherBackPresses() { launchTest<ActivityFragment> { val recorder = FlowRecorder<Unit>(testScope) fragment.requireActivity().onBackPressedDispatcher.backPresses(owner = fragment).recordWith(recorder) pressBack() assertThat(recorder.takeValue()) .isEqualTo(Unit) recorder.assertNoMoreValues() cancelTestScope() pressBack() recorder.assertNoMoreValues() } } }
kotlin
20
0.740561
113
31.28125
32
starcoderdata
package com.tradingview.lightweightcharts.runtime.messaging import com.google.gson.JsonElement import com.google.gson.annotations.SerializedName open class BridgeMessage( val messageType: MessageType, val data: Data ) { override fun toString(): String { return "${this::class.java.simpleName}(messageType=$messageType, data=$data)" } } open class Data( open val uuid: String, open val fn: String? = null, open val params: Map<String, Any>? = null, open val result: JsonElement? = null, open val message: String? = null, open val logLevel: LogLevel? = null ) enum class LogLevel { @SerializedName("debug") DEBUG, @SerializedName("warning") WARNING, @SerializedName("error") ERROR, @SerializedName("none") NONE; fun isDebug(): Boolean = ordinal == 0 fun isWarning(): Boolean = ordinal <= 1 fun isError(): Boolean = ordinal <= 2 fun isEnabled(): Boolean = ordinal <= 3 }
kotlin
13
0.667355
85
24.5
38
starcoderdata
<reponame>gravetii/wordagam package io.github.gravetii.controller import io.github.gravetii.game.Game import io.github.gravetii.game.UserResult import io.github.gravetii.model.GameStats import io.github.gravetii.model.GridPoint import io.github.gravetii.model.WordResult import io.github.gravetii.validation.ValidationResult import javafx.fxml.FXML import javafx.scene.image.ImageView import javafx.scene.input.MouseEvent import javafx.scene.layout.GridPane class GameGridController(private val game: Game) : FxController { private val imgViewMap: MutableMap<String, ImageView> = mutableMapOf() private val validator = GamePlayValidator(game.result) private val userResult = UserResult() private lateinit var styler: GamePlayStyler @FXML private lateinit var gamePane: GridPane @FXML private lateinit var imgView_0_0: ImageView @FXML private lateinit var imgView_0_1: ImageView @FXML private lateinit var imgView_0_2: ImageView @FXML private lateinit var imgView_0_3: ImageView @FXML private lateinit var imgView_1_0: ImageView @FXML private lateinit var imgView_1_1: ImageView @FXML private lateinit var imgView_1_2: ImageView @FXML private lateinit var imgView_1_3: ImageView @FXML private lateinit var imgView_2_0: ImageView @FXML private lateinit var imgView_2_1: ImageView @FXML private lateinit var imgView_2_2: ImageView @FXML private lateinit var imgView_2_3: ImageView @FXML private lateinit var imgView_3_0: ImageView @FXML private lateinit var imgView_3_1: ImageView @FXML private lateinit var imgView_3_2: ImageView @FXML private lateinit var imgView_3_3: ImageView @FXML fun initialize() { imgViewMap["imgView_0_0"] = imgView_0_0 imgViewMap["imgView_0_1"] = imgView_0_1 imgViewMap["imgView_0_2"] = imgView_0_2 imgViewMap["imgView_0_3"] = imgView_0_3 imgViewMap["imgView_1_0"] = imgView_1_0 imgViewMap["imgView_1_1"] = imgView_1_1 imgViewMap["imgView_1_2"] = imgView_1_2 imgViewMap["imgView_1_3"] = imgView_1_3 imgViewMap["imgView_2_0"] = imgView_2_0 imgViewMap["imgView_2_1"] = imgView_2_1 imgViewMap["imgView_2_2"] = imgView_2_2 imgViewMap["imgView_2_3"] = imgView_2_3 imgViewMap["imgView_3_0"] = imgView_3_0 imgViewMap["imgView_3_1"] = imgView_3_1 imgViewMap["imgView_3_2"] = imgView_3_2 imgViewMap["imgView_3_3"] = imgView_3_3 styler = GamePlayStyler(gamePane, imgViewMap.values) } private fun String.getImageViewLabel(): GridPoint { val tokens = split("_") return GridPoint(tokens[1].toInt(), tokens[2].toInt()) } private fun applyStyleAfterValidation(imgView: ImageView, result: ValidationResult) { when (result) { ValidationResult.ALL_INVALID -> styler.invalidate() ValidationResult.LAST_INVALID -> styler.forLastInvalidClick(imgView) else -> styler.forValidClick(imgView) } } private fun revisit(result: WordResult) { val imgViews = result.seq.mapNotNull { val imgView = "imgView_${it.x}_${it.y}" imgViewMap[imgView] } validator.reset() styler.revisit(imgViews) } @FXML fun onImgViewClick(event: MouseEvent) { val imgView = event.source as ImageView val point = imgView.id.getImageViewLabel() val unit = game.getGridUnit(point) applyStyleAfterValidation(imgView, validator.validate(unit)) } fun rotate() = styler.rotate() fun validateWordOnBtnClick(): WordResult? { val word = validator.validate() val result = if (word == null) { styler.forIncorrectWord() null } else if (userResult.exists(word)) { styler.forRepeatedWord() null } else { val points = game.result.getPoints(word) val seq = validator.getSeq() val wordResult = WordResult(word, points, seq) userResult.add(word, wordResult) styler.forCorrectWord() wordResult } validator.reset() return result } fun revisitUserWord(word: String) = revisit(userResult.get(word)) fun revisitGameWord(word: String) = revisit(game.result.get(word)) fun getAllGameWords(): Map<String, WordResult> = game.result.all() fun getAllUserWords(): Map<String, WordResult> = userResult.all() fun endGame() { styler.applyEndTransition() imgViewMap.values.forEach { it.isDisable = true } validator.reset() styler.rotateOnEnd() } fun computeStats(): GameStats = GameStats(game.result, userResult) }
kotlin
17
0.651886
89
28.078313
166
starcoderdata
<gh_stars>10-100 /* * Copyright 2010-2020 JetBrains s.r.o. and Kotlin Programming Language contributors. * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ package org.jetbrains.kotlin.idea.fir.low.level.api.trackers import com.intellij.openapi.command.WriteCommandAction import com.intellij.openapi.module.Module import com.intellij.openapi.project.Project import com.intellij.openapi.util.ModificationTracker import com.intellij.openapi.vfs.LocalFileSystem import com.intellij.openapi.vfs.VirtualFileManager import com.intellij.psi.PsiDocumentManager import com.intellij.psi.PsiManager import com.intellij.testFramework.PsiTestUtil import junit.framework.Assert import org.jetbrains.kotlin.idea.caches.project.ModuleSourceInfo import org.jetbrains.kotlin.idea.caches.project.productionSourceInfo import org.jetbrains.kotlin.idea.fir.low.level.api.api.createModuleWithoutDependenciesOutOfBlockModificationTracker import org.jetbrains.kotlin.idea.fir.low.level.api.api.createProjectWideOutOfBlockModificationTracker import org.jetbrains.kotlin.idea.stubs.AbstractMultiModuleTest import org.jetbrains.kotlin.idea.util.application.runWriteAction import org.jetbrains.kotlin.idea.util.sourceRoots import org.jetbrains.kotlin.psi.KtFile import org.jetbrains.kotlin.psi.KtNamedFunction import org.jetbrains.kotlin.psi.KtProperty import org.jetbrains.kotlin.psi.KtPsiFactory import java.io.File import java.nio.file.Files import kotlin.io.path.ExperimentalPathApi import kotlin.io.path.writeText class KotlinModuleOutOfBlockTrackerTest : AbstractMultiModuleTest() { override fun getTestDataDirectory(): File = error("Should not be called") fun testThatModuleOutOfBlockChangeInfluenceOnlySingleModule() { val moduleA = createModuleWithModificationTracker("a") { listOf( FileWithText("main.kt", "fun main() = 10") ) } val moduleB = createModuleWithModificationTracker("b") val moduleC = createModuleWithModificationTracker("c") val moduleAWithTracker = ModuleWithModificationTracker(moduleA) val moduleBWithTracker = ModuleWithModificationTracker(moduleB) val moduleCWithTracker = ModuleWithModificationTracker(moduleC) moduleA.typeInFunctionBody("main.kt", textAfterTyping = "fun main() = hello10") Assert.assertTrue( "Out of block modification count for module A with out of block should change after typing, modification count is ${moduleAWithTracker.modificationCount}", moduleAWithTracker.changed() ) Assert.assertFalse( "Out of block modification count for module B without out of block should not change after typing, modification count is ${moduleBWithTracker.modificationCount}", moduleBWithTracker.changed() ) Assert.assertFalse( "Out of block modification count for module C without out of block should not change after typing, modification count is ${moduleCWithTracker.modificationCount}", moduleCWithTracker.changed() ) } fun testThatInEveryModuleOutOfBlockWillHappenAfterContentRootChange() { val moduleA = createModuleWithModificationTracker("a") val moduleB = createModuleWithModificationTracker("b") val moduleC = createModuleWithModificationTracker("c") val moduleAWithTracker = ModuleWithModificationTracker(moduleA) val moduleBWithTracker = ModuleWithModificationTracker(moduleB) val moduleCWithTracker = ModuleWithModificationTracker(moduleC) runWriteAction { moduleA.sourceRoots.first().createChildData(/* requestor = */ null, "file.kt") } Assert.assertTrue( "Out of block modification count for module A should change after content root change, modification count is ${moduleAWithTracker.modificationCount}", moduleAWithTracker.changed() ) Assert.assertTrue( "Out of block modification count for module B should change after content root change, modification count is ${moduleBWithTracker.modificationCount}", moduleBWithTracker.changed() ) Assert.assertTrue( "Out of block modification count for module C should change after content root change modification count is ${moduleCWithTracker.modificationCount}", moduleCWithTracker.changed() ) } fun testThatNonPhysicalFileChangeNotCausingBOOM() { val moduleA = createModuleWithModificationTracker("a") { listOf( FileWithText("main.kt", "fun main() {}") ) } val moduleB = createModuleWithModificationTracker("b") val moduleAWithTracker = ModuleWithModificationTracker(moduleA) val moduleBWithTracker = ModuleWithModificationTracker(moduleB) val projectWithModificationTracker = ProjectWithModificationTracker(project) runWriteAction { val nonPhysicalPsi = KtPsiFactory(moduleA.project).createFile("nonPhysical", "val a = c") nonPhysicalPsi.add(KtPsiFactory(moduleA.project).createFunction("fun x(){}")) } Assert.assertFalse( "Out of block modification count for module A should not change after non physical file change, modification count is ${moduleAWithTracker.modificationCount}", moduleAWithTracker.changed() ) Assert.assertFalse( "Out of block modification count for module B should not change after non physical file change, modification count is ${moduleBWithTracker.modificationCount}", moduleBWithTracker.changed() ) Assert.assertFalse( "Out of block modification count for project should not change after non physical file change, modification count is ${projectWithModificationTracker.modificationCount}", projectWithModificationTracker.changed() ) } private fun Module.typeInFunctionBody(fileName: String, textAfterTyping: String) { val file = "${sourceRoots.first().url}/$fileName" val virtualFile = VirtualFileManager.getInstance().findFileByUrl(file)!! val ktFile = PsiManager.getInstance(project).findFile(virtualFile) as KtFile configureByExistingFile(virtualFile) val singleFunction = ktFile.declarations.single() as KtNamedFunction editor.caretModel.moveToOffset(singleFunction.bodyExpression!!.textOffset) type("hello") PsiDocumentManager.getInstance(project).commitAllDocuments() Assert.assertEquals(textAfterTyping, ktFile.text) } @OptIn(ExperimentalPathApi::class) private fun createModuleWithModificationTracker( name: String, createFiles: () -> List<FileWithText> = { emptyList() }, ): Module { val tmpDir = createTempDirectory().toPath() createFiles().forEach { file -> Files.createFile(tmpDir.resolve(file.name)).writeText(file.text) } val module: Module = createModule("$tmpDir/$name", moduleType) val root = LocalFileSystem.getInstance().refreshAndFindFileByIoFile(tmpDir.toFile())!! WriteCommandAction.writeCommandAction(module.project).run<RuntimeException> { root.refresh(false, true) } PsiTestUtil.addSourceContentToRoots(module, root) return module } private data class FileWithText(val name: String, val text: String) abstract class WithModificationTracker(protected val modificationTracker: ModificationTracker) { private val initialModificationCount = modificationTracker.modificationCount val modificationCount: Long get() = modificationTracker.modificationCount fun changed(): Boolean = modificationTracker.modificationCount != initialModificationCount } private class ModuleWithModificationTracker(module: Module) : WithModificationTracker( module.productionSourceInfo()!!.createModuleWithoutDependenciesOutOfBlockModificationTracker(module.project) ) private class ProjectWithModificationTracker(project: Project) : WithModificationTracker( project.createProjectWideOutOfBlockModificationTracker() ) }
kotlin
23
0.731934
182
45.312849
179
starcoderdata
<reponame>v-rodionov/avito-android<gh_stars>100-1000 package com.avito.android.test.report.lifecycle import android.app.Activity import androidx.fragment.app.FragmentActivity import androidx.test.runner.lifecycle.ActivityLifecycleCallback import androidx.test.runner.lifecycle.Stage import com.avito.android.test.report.Report class ReportActivityLifecycleListener( factory: com.avito.logger.LoggerFactory, private val report: Report ) : ActivityLifecycleCallback { private val logger = factory.create("ReportActivityLifecycle") private val fragmentLifecycleListener = ReportFragmentLifecycleListener(factory, report) override fun onActivityLifecycleChanged(activity: Activity, stage: Stage) { val message = "Activity ${activity::class.java.simpleName} was $stage" logger.info(message) when (stage) { Stage.PRE_ON_CREATE -> if (activity is FragmentActivity) { /** * Look to [androidx.fragment.app.FragmentManager.unregisterFragmentLifecycleCallbacks] * All registered callbacks will be * automatically unregistered when this FragmentManager is destroyed */ activity .supportFragmentManager .registerFragmentLifecycleCallbacks( fragmentLifecycleListener, true ) } Stage.CREATED, Stage.RESUMED, Stage.PAUSED, Stage.DESTROYED -> report.addComment(message) else -> { // do nothing to avoid a lot of events } } } }
kotlin
17
0.636686
103
37.409091
44
starcoderdata
<filename>app/src/androidTest/java/uk/nhs/nhsx/sonar/android/app/testhelpers/ToastMatcher.kt /* * Copyright © 2020 NHSX. All rights reserved. */ package uk.nhs.nhsx.sonar.android.app.testhelpers import android.view.WindowManager import androidx.test.espresso.Root import org.hamcrest.Description import org.hamcrest.TypeSafeMatcher class ToastMatcher : TypeSafeMatcher<Root>() { override fun describeTo(description: Description) { description.appendText("is toast") } override fun matchesSafely(root: Root): Boolean { val type = root.windowLayoutParams.get().type @Suppress("DEPRECATION") if (type == WindowManager.LayoutParams.TYPE_TOAST) { val windowToken = root.decorView.windowToken val appToken = root.decorView.applicationWindowToken if (windowToken === appToken) { // windowToken == appToken means this window isn't contained by any other windows. // if it was a window for an activity, it would have TYPE_BASE_APPLICATION. return true } } return false } } fun isToast() = ToastMatcher()
kotlin
15
0.672384
98
29.684211
38
starcoderdata
<reponame>Revincx/DanDanPlayForAndroid<filename>user_component/src/main/java/com/xyoye/user_component/ui/activities/about_us/AboutUsViewModel.kt<gh_stars>100-1000 package com.xyoye.user_component.ui.activities.about_us import com.xyoye.common_component.base.BaseViewModel class AboutUsViewModel : BaseViewModel() { }
kotlin
14
0.833856
162
39
8
starcoderdata
<gh_stars>100-1000 package openfoodfacts.github.scrachx.openfood.models.entities.attribute import com.fasterxml.jackson.annotation.JsonIgnoreProperties import com.fasterxml.jackson.annotation.JsonInclude import com.fasterxml.jackson.annotation.JsonProperty @JsonInclude(JsonInclude.Include.NON_NULL) @JsonIgnoreProperties(ignoreUnknown = true) data class Attribute( @JsonProperty("match") val match: Float, @JsonProperty("id") val id: String, @JsonProperty("description_short") val descriptionShort: String?, @JsonProperty("status") val status: String, @JsonProperty("icon_url") val iconUrl: String?, @JsonProperty("title") val title: String?, @JsonProperty("name") val name: String?, @JsonProperty("description") val description: String?, @JsonProperty("debug") val debug: String? )
kotlin
10
0.731622
73
41.9
20
starcoderdata
<gh_stars>100-1000 // !CHECK_TYPE class A(val a:Int) { inner class B() { fun Byte.xx() : Double.() -> Any { checkSubtype<Byte>(this) val <!UNUSED_VARIABLE!>a<!>: Double.() -> Unit = { checkSubtype<Double>(this) checkSubtype<Byte>(this@xx) checkSubtype<B>(this@B) checkSubtype<A>(this@A) } val <!UNUSED_VARIABLE!>b<!>: Double.() -> Unit = a@{ checkSubtype<Double>(this@a) + checkSubtype<Byte>(this@xx) } val <!UNUSED_VARIABLE!>c<!> = a@{ -> <!NO_THIS!>this@a<!> <!DEBUG_INFO_ELEMENT_WITH_ERROR_TYPE!>+<!> checkSubtype<Byte>(this@xx) } return (a@{checkSubtype<Double>(this@a) + checkSubtype<Byte>(this@xx)}) } } }
kotlin
25
0.578035
136
35.473684
19
starcoderdata
@file:Suppress("NOTHING_TO_INLINE", "LoopToCallChain") package ktx.collections import com.badlogic.gdx.utils.* import com.badlogic.gdx.utils.ObjectMap.Entry /** Alias for [com.badlogic.gdx.utils.ObjectMap]. Added for consistency with other collections and factory methods. */ typealias GdxMap<Key, Value> = ObjectMap<Key, Value> /** * Default LibGDX map size used by most constructors. */ const val defaultMapSize = 51 /** * @param initialCapacity initial capacity of the map. Will be resized if necessary. * @param loadFactor decides under what load the map is resized. * @return a new [ObjectMap]. */ fun <Key, Value> gdxMapOf(initialCapacity: Int = defaultMapSize, loadFactor: Float = defaultLoadFactor): GdxMap<Key, Value> = GdxMap(initialCapacity, loadFactor) /** * @param keysToValues will be added to the map. * @param initialCapacity initial capacity of the map. Will be resized if necessary. * @param loadFactor decides under what load the map is resized. * @return a new [ObjectMap]. */ inline fun <Key, Value> gdxMapOf(vararg keysToValues: Pair<Key, Value>, initialCapacity: Int = defaultMapSize, loadFactor: Float = defaultLoadFactor): GdxMap<Key, Value> { val map = GdxMap<Key, Value>(initialCapacity, loadFactor) keysToValues.forEach { map[it.first] = it.second } return map } /** * A method wrapper over [ObjectMap.size] variable compatible with nullable types. * @return current amount of elements in the map. */ inline fun GdxMap<*, *>?.size(): Int = this?.size ?: 0 /** * @return true if the map is null or has no elements. */ inline fun GdxMap<*, *>?.isEmpty(): Boolean = this == null || this.size == 0 /** * @return true if the map is not null and contains at least one element. */ inline fun GdxMap<*, *>?.isNotEmpty(): Boolean = this != null && this.size > 0 /** * @param key a value might be assigned to this key and stored in the map. * @return true if a value is associated with passed key. False otherwise. */ operator fun <Key> GdxMap<Key, *>.contains(key: Key): Boolean = this.containsKey(key) /** * @param key the passed value will be linked with this key. * @param value will be stored in the map, accessible by the passed key. * @return old value associated with the key or null if none. */ operator fun <Key, Value> GdxMap<Key, Value>.set(key: Key, value: Value): Value? = this.put(key, value) /** * Allows to iterate over the map with Kotlin lambda syntax and direct access to [MutableIterator], which can remove * elements during iteration. * @param action will be invoked on each key and value pair. Passed iterator is ensured to be the same instance throughout * the iteration. It can be used to remove elements. */ inline fun <Key, Value> GdxMap<Key, Value>.iterate(action: (Key, Value, MutableIterator<Entry<Key, Value>>) -> Unit) { val iterator = this.iterator() while (iterator.hasNext) { val next = iterator.next() action(next.key, next.value, iterator) } } /** * @return keys from this map stored in an [ObjectSet]. */ fun <Key> GdxMap<Key, *>.toGdxSet(): ObjectSet<Key> = this.keys().toGdxSet() /** * @param initialCapacity initial capacity of the map. Will be resized if necessary. * @param loadFactor decides how many elements the map might contain in relation to its total capacity before it is resized. * @param keyProvider will consume each value in this iterable. The results will be treated as map keys for the values. * @return values copied from this iterable stored in a LibGDX map, mapped to the keys returned by the provider. */ inline fun <Key, Value> Iterable<Value>.toGdxMap(initialCapacity: Int = defaultMapSize, loadFactor: Float = defaultLoadFactor, keyProvider: (Value) -> Key): GdxMap<Key, Value> { val map = GdxMap<Key, Value>(initialCapacity, loadFactor) this.forEach { map[keyProvider(it)] = it } return map } /** * @param initialCapacity initial capacity of the map. Will be resized if necessary. * @param loadFactor decides how many elements the map might contain in relation to its total capacity before it is resized. * @param valueProvider will consume each value in this iterable. The results will be treated as map values. * @param keyProvider will consume each value in this iterable. The results will be treated as map keys for the values. * @return values converted from this iterable stored in a LibGDX map, mapped to the keys returned by the provider. */ inline fun <Type, Key, Value> Iterable<Type>.toGdxMap(initialCapacity: Int = defaultMapSize, loadFactor: Float = defaultLoadFactor, valueProvider: (Type) -> Value, keyProvider: (Type) -> Key): GdxMap<Key, Value> { val map = GdxMap<Key, Value>(initialCapacity, loadFactor) this.forEach { map[keyProvider(it)] = valueProvider(it) } return map } /** * @param initialCapacity initial capacity of the map. Will be resized if necessary. * @param loadFactor decides how many elements the map might contain in relation to its total capacity before it is resized. * @param keyProvider will consume each value in this iterable. The results will be treated as map keys for the values. * @return values copied from this array stored in a LibGDX map, mapped to the keys returned by the provider. */ inline fun <Key, Value> Array<Value>.toGdxMap(initialCapacity: Int = defaultMapSize, loadFactor: Float = defaultLoadFactor, keyProvider: (Value) -> Key): GdxMap<Key, Value> { val map = GdxMap<Key, Value>(initialCapacity, loadFactor) this.forEach { map[keyProvider(it)] = it } return map } /** * @param initialCapacity initial capacity of the map. Will be resized if necessary. * @param loadFactor decides how many elements the map might contain in relation to its total capacity before it is resized. * @param valueProvider will consume each value in this iterable. The results will be treated as map values. * @param keyProvider will consume each value in this iterable. The results will be treated as map keys for the values. * @return values converted from this array stored in a LibGDX map, mapped to the keys returned by the provider. */ inline fun <Type, Key, Value> Array<Type>.toGdxMap(initialCapacity: Int = defaultMapSize, loadFactor: Float = defaultLoadFactor, valueProvider: (Type) -> Value, keyProvider: (Type) -> Key): GdxMap<Key, Value> { val map = GdxMap<Key, Value>(initialCapacity, loadFactor) this.forEach { map[keyProvider(it)] = valueProvider(it) } return map } // Sadly, IdentityMap does NOT extend ObjectMap. It feels like it would require up to 2 overridden methods to set it up, // but NO. The utilities that apply to ObjectMaps will not work on IdentityMaps, and since its a lot of extra work (and // boilerplate) for such a pretty obscure class, only some basic functions are added - like factory methods and operators. /** * @param initialCapacity initial capacity of the map. Will be resized if necessary. * @param loadFactor decides under what load the map is resized. * @return a new [IdentityMap], which compares keys by references. */ fun <Key, Value> gdxIdentityMapOf(initialCapacity: Int = defaultMapSize, loadFactor: Float = defaultLoadFactor): IdentityMap<Key, Value> = IdentityMap(initialCapacity, loadFactor) /** * @param keysToValues will be added to the map. * @param initialCapacity initial capacity of the map. Will be resized if necessary. * @param loadFactor decides under what load the map is resized. * @return a new [IdentityMap], which compares keys by references. */ inline fun <Key, Value> gdxIdentityMapOf(vararg keysToValues: Pair<Key, Value>, initialCapacity: Int = defaultMapSize, loadFactor: Float = defaultLoadFactor): IdentityMap<Key, Value> { val map = IdentityMap<Key, Value>(initialCapacity, loadFactor) keysToValues.forEach { map[it.first] = it.second } return map } /** * @param key a value might be assigned to this key and stored in the map. * @return true if a value is associated with passed key. False otherwise. */ operator fun <Key> IdentityMap<Key, *>.contains(key: Key): Boolean = this.containsKey(key) /** * @param key the passed value will be linked with this key. * @param value will be stored in the map, accessible by the passed key. * @return old value associated with the key or null if none. */ operator fun <Key, Value> IdentityMap<Key, Value>.set(key: Key, value: Value): Value? = this.put(key, value) /** * Allows to iterate over the map with Kotlin lambda syntax and direct access to [MutableIterator], which can remove elements * during iteration. * @param action will be invoked on each key and value pair. Passed iterator is ensured to be the same instance throughout * the iteration. It can be used to remove elements. */ inline fun <Key, Value> IdentityMap<Key, Value>.iterate(action: (Key, Value, MutableIterator<Entry<Key, Value>>) -> Unit) { val iterator = this.iterator() while (iterator.hasNext()) { val next = iterator.next() action(next.key, next.value, iterator) } } // Some basic support is also provided for optimized LibGDX maps with primitive keys. Again, no common superclass hurts. /** * @param initialCapacity initial capacity of the map. Will be resized if necessary. * @param loadFactor decides under what load the map is resized. * @return a new [IntIntMap] with primitive int keys and values. */ fun gdxIntIntMap(initialCapacity: Int = defaultMapSize, loadFactor: Float = defaultLoadFactor): IntIntMap = IntIntMap(initialCapacity, loadFactor) /** * @param key a value might be assigned to this key and stored in the map. * @return true if a value is associated with passed key. False otherwise. */ operator fun IntIntMap.contains(key: Int): Boolean = this.containsKey(key) /** * @param key the passed value will be linked with this key. * @param value will be stored in the map, accessible by the passed key. */ operator fun IntIntMap.set(key: Int, value: Int) = this.put(key, value) /** * @param key a value might be assigned to this key and stored in the map. * @return value associated with this key if present in this map, 0f otherwise. Use [IntIntMap.get] with second argument * (default value) if you want predictable behavior in case of missing keys. * @see IntIntMap.get */ operator fun IntIntMap.get(key: Int): Int = this.get(key, 0) /** * @param initialCapacity initial capacity of the map. Will be resized if necessary. * @param loadFactor decides under what load the map is resized. * @return a new [IntFloatMap] with primitive int keys and primitive float values. */ fun gdxIntFloatMap(initialCapacity: Int = defaultMapSize, loadFactor: Float = defaultLoadFactor): IntFloatMap = IntFloatMap(initialCapacity, loadFactor) /** * @param key a value might be assigned to this key and stored in the map. * @return true if a value is associated with passed key. False otherwise. */ operator fun IntFloatMap.contains(key: Int): Boolean = this.containsKey(key) /** * @param key the passed value will be linked with this key. * @param value will be stored in the map, accessible by the passed key. */ operator fun IntFloatMap.set(key: Int, value: Float) = this.put(key, value) /** * @param key a value might be assigned to this key and stored in the map. * @return value associated with this key if present in this map, 0f otherwise. Use [IntFloatMap.get] with second argument * (default value) if you want predictable behavior in case of missing keys. * @see IntFloatMap.get */ operator fun IntFloatMap.get(key: Int): Float = this.get(key, 0f) /** * @param initialCapacity initial capacity of the map. Will be resized if necessary. * @param loadFactor decides under what load the map is resized. * @return a new [IntMap] with primitive int keys. */ fun <Value> gdxIntMap(initialCapacity: Int = defaultMapSize, loadFactor: Float = defaultLoadFactor): IntMap<Value> = IntMap(initialCapacity, loadFactor) /** * @param key a value might be assigned to this key and stored in the map. * @return true if a value is associated with passed key. False otherwise. */ operator fun IntMap<*>.contains(key: Int): Boolean = this.containsKey(key) /** * @param key the passed value will be linked with this key. * @param value will be stored in the map, accessible by the passed key. * @return old value associated with the key or null if none. */ operator fun <Value> IntMap<Value>.set(key: Int, value: Value): Value? = this.put(key, value) /** * Allows to destruct [ObjectMap.Entry] into key and value components. * @return [ObjectMap.Entry.key] */ inline operator fun <Key, Value> ObjectMap.Entry<Key, Value>.component1() = key!! /** * Allows to destruct [ObjectMap.Entry] into key and value components. Nullable, since [ObjectMap] allows null values. * @return [ObjectMap.Entry.value] */ inline operator fun <Key, Value> ObjectMap.Entry<Key, Value>.component2(): Value? = value /** * Allows to destruct [IntMap.Entry] into key and value components. * @return [IntMap.Entry.key] */ inline operator fun <Value> IntMap.Entry<Value>.component1() = key /** * Allows to destruct [IntMap.Entry] into key and value components. Nullable, since [IntMap] allows null values. * @return [IntMap.Entry.value] */ inline operator fun <Value> IntMap.Entry<Value>.component2(): Value? = value /** * Allows to destruct [LongMap.Entry] into key and value components. * @return [LongMap.Entry.key] */ inline operator fun <Value> LongMap.Entry<Value>.component1() = key /** * Allows to destruct [LongMap.Entry] into key and value components. Nullable, since [LongMap] allows null values. * @return [LongMap.Entry.value] */ inline operator fun <Value> LongMap.Entry<Value>.component2(): Value? = value /** * Allows to destruct [IntIntMap.Entry] into key and value components. * @return [IntIntMap.Entry.key] */ inline operator fun IntIntMap.Entry.component1() = key /** * Allows to destruct [IntIntMap.Entry] into key and value components. * @return [IntIntMap.Entry.value] */ inline operator fun IntIntMap.Entry.component2() = value /** * Allows to destruct [IntFloatMap.Entry] into key and value components. * @return [IntFloatMap.Entry.key] */ inline operator fun IntFloatMap.Entry.component1() = key /** * Allows to destruct [IntFloatMap.Entry] into key and value components. * @return [IntFloatMap.Entry.value] */ inline operator fun IntFloatMap.Entry.component2() = value /** * Allows to destruct [ObjectIntMap.Entry] into key and value components. * @return [ObjectIntMap.Entry.key] */ inline operator fun <Value> ObjectIntMap.Entry<Value>.component1() = key!! /** * Allows to destruct [ObjectIntMap.Entry] into key and value components. * @return [ObjectIntMap.Entry.value] */ inline operator fun <Value> ObjectIntMap.Entry<Value>.component2() = value /** * Returns a [GdxMap] containing the results of applying the given [transform] function * to each entry in the original [GdxMap]. */ inline fun <Key, Value, R> GdxMap<Key, Value>.map(transform: (Entry<Key, Value>) -> R): GdxMap<Key, R> { val destination = GdxMap<Key, R>(this.size) for (item in this) { destination[item.key] = transform(item) } return destination } /** * Returns a [GdxMap] containing only entries matching the given [predicate]. */ inline fun <Key, Value> GdxMap<Key, Value>.filter(predicate: (Entry<Key, Value>) -> Boolean): GdxMap<Key, Value> { val destination = GdxMap<Key, Value>() for (item in this) { if (predicate(item)) { destination[item.key] = item.value } } return destination } /** * Returns a single [GdxArray] of all elements from all collections in the given [GdxMap]. */ inline fun <Key, Type, Value : Iterable<Type>> GdxMap<Key, out Value>.flatten(): GdxArray<Type> { val destination = GdxArray<Type>() for (item in this) { destination.addAll(item.value) } return destination } /** * Returns a single [GdxArray] of all elements yielded from results of transform function being invoked * on each entry of original [GdxMap]. */ inline fun <Key, Value, R> GdxMap<Key, Value>.flatMap(transform: (Entry<Key, Value>) -> Iterable<R>): GdxArray<R> { return this.map(transform).flatten() }
kotlin
16
0.706034
126
41.902314
389
starcoderdata
<filename>kotlin/Test.kt package Test; import Foreign. PsRuntime.app val add = {a:Int -> {b:Int -> a+b}} fun main() { val a : Any = 2 val b : Any = 34 val m = PS.Main.Module.main as () -> Unit println(m()) }
kotlin
11
0.572687
45
15.285714
14
starcoderdata