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)
[email protected](timeZoneReceiver, filter)
}
private fun unregisterReceiver() {
if (!registeredTimeZoneReceiver) {
return
}
registeredTimeZoneReceiver = false
[email protected](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 |
End of preview. Expand
in Dataset Viewer.
No dataset card yet
- Downloads last month
- 6