path
stringlengths
4
280
owner
stringlengths
2
39
repo_id
int64
21.1k
879M
is_fork
bool
2 classes
languages_distribution
stringlengths
13
1.95k
content
stringlengths
7
482k
issues
int64
0
13.9k
main_language
stringclasses
121 values
forks
stringlengths
1
5
stars
int64
0
111k
commit_sha
stringlengths
40
40
size
int64
7
482k
name
stringlengths
1
100
license
stringclasses
93 values
src/jvmMain/kotlin/cn/netdiscovery/monica/opencv/LoadManager.kt
fengzhizi715
791,824,947
false
{"Kotlin": 641636}
package cn.netdiscovery.monica.opencv import cn.netdiscovery.monica.utils.* import org.slf4j.Logger import java.io.File import java.io.FileOutputStream /** * * @FileName: * cn.netdiscovery.monica.opencv.LoadManager * @author: Tony Shen * @date: 2024/7/16 14:06 * @version: V1.0 <描述当前版本功能> */ object LoadManager { private val logger: Logger = logger<LoadManager>() val loadPath by lazy { if (isMac) { File("").absolutePath + File.separator + "resources" + File.separator + "macos" + File.separator } else if (isWindows) { File("").absolutePath + File.separator } else { File("").absolutePath + File.separator + "resources" + File.separator + "linux" + File.separator } } /** * 对于不同的平台加载的库是不同的,mac 是 dylib 库,windows 是 dll 库,linux 是 so 库 */ fun load() { if (isMac) { if (arch == "aarch64") { // 即使是 mac 系统,针对不同的芯片 也需要加载不同的 dylib 库 System.load("${ImageProcess.loadPath}libMonicaImageProcess_aarch64.dylib") } else { System.load("${ImageProcess.loadPath}libMonicaImageProcess.dylib") } } else if (isWindows) { System.load("${LoadManager.loadPath}MonicaImageProcess.dll") } } /** * 拷贝各个平台所必须的图像处理库 */ fun copy() { logger.info("loadPath: $loadPath") if (isMac) { if (arch == "aarch64") { // 即使是 mac 系统,针对不同的芯片 也需要加载不同的 dylib 库 copyLibrary("libMonicaImageProcess_aarch64.dylib") } else { copyLibrary("libMonicaImageProcess.dylib") } } else if (isWindows) { copyLibrary("MonicaImageProcess.dll") copyLibrary("opencv_world481.dll") } } /** * 拷贝人脸检测模块所需要的模型 */ fun copyFaceDetectModels() { copyLibrary("age_deploy.prototxt") copyLibrary("age_net.caffemodel") copyLibrary("gender_deploy.prototxt") copyLibrary("gender_net.caffemodel") copyLibrary("opencv_face_detector.pbtxt") copyLibrary("opencv_face_detector_uint8.pb") } fun copySketchDrawingModel() { copyLibrary("opensketch_style_512x512.onnx") } private fun copyLibrary(libName: String) { try { val resource = this.javaClass.classLoader.getResource(libName) resource?.apply { val dir = File(loadPath + libName) val inputStream = resource.openStream() logger.info("file compare: ${inputStream.available()} / ${dir.length()}") // if (inputStream.available().toLong() == dir.length()) return logger.info("copyPath: $dir") if (dir.parentFile != null && !dir.parentFile.exists()) { dir.parentFile.mkdirs() } val out = FileOutputStream(dir) //缓存dll位置 var i: Int val buf = ByteArray(1024) try { while (inputStream.read(buf).also { i = it } != -1) { out.write(buf, 0, i) } } finally { closeQuietly(inputStream,out) } } } catch (e: Exception) { e.printStackTrace() logger.info("load jni error: ${e.message}") } } }
0
Kotlin
4
51
5334d0822ec173004dd0dbecf7a8c7fb3b7c755b
3,422
Monica
Apache License 2.0
sdk/src/main/java/io/radar/sdk/model/RadarFraud.kt
radarlabs
61,604,202
false
{"Kotlin": 634499, "Groovy": 30206, "Shell": 285}
package io.radar.sdk.model import org.json.JSONObject /** * Represents fraud detection signals for location verification. * * Note that these values should not be trusted unless you called `trackVerified()` instead of `trackOnce()`. * * @see [](https://radar.com/documentation/fraud) */ data class RadarFraud( /** * A boolean indicating whether the user passed fraud detection checks. May be `false` if Fraud is not enabled. */ val passed: Boolean, /** * A boolean indicating whether fraud detection checks were bypassed for the user for testing. May be `false` if Fraud is not enabled. */ val bypassed: Boolean, /** * A boolean indicating whether the request was made with SSL pinning configured successfully. May be `false` if Fraud is not enabled. */ val verified: Boolean, /** * A boolean indicating whether the user's IP address is a known proxy. May be `false` if Fraud is not enabled. */ val proxy: Boolean, /** * A boolean indicating whether the user's location is being mocked, such as in a simulator or using a location spoofing app. May be * `false` if Fraud is not enabled. */ val mocked: Boolean, /** * A boolean indicating whether the user's device has been compromised according to the Play Integrity API. May be `false` if Fraud is not enabled. * * @see [](https://developer.android.com/google/play/integrity/overview) */ val compromised: Boolean, /** * A boolean indicating whether the user moved too far too fast. May be `false` if Fraud is not enabled. */ val jumped: Boolean, /** * A boolean indicating whether the user is screen sharing. May be `false` if Fraud is not enabled. */ val sharing: Boolean, /** * A boolean indicating whether the user's location is not accurate enough. May be `false` if Fraud is not enabled. */ val inaccurate: Boolean ) { companion object { private const val PASSED = "passed" private const val BYPASSED = "bypassed" private const val VERIFIED = "verified" private const val PROXY = "proxy" private const val MOCKED = "mocked" private const val COMPROMISED = "compromised" private const val JUMPED = "jumped" private const val SHARING = "sharing" private const val INACCURATE = "inaccurate" @JvmStatic fun fromJson(json: JSONObject?): RadarFraud { return RadarFraud( passed = json?.optBoolean(PASSED, false) ?: false, bypassed = json?.optBoolean(BYPASSED, false) ?: false, verified = json?.optBoolean(VERIFIED, false) ?: false, proxy = json?.optBoolean(PROXY, false) ?: false, mocked = json?.optBoolean(MOCKED, false) ?: false, compromised = json?.optBoolean(COMPROMISED, false) ?: false, jumped = json?.optBoolean(JUMPED, false) ?: false, sharing = json?.optBoolean(SHARING, false) ?: false, inaccurate = json?.optBoolean(INACCURATE, false) ?: false ) } } fun toJson(): JSONObject { return JSONObject().apply { putOpt(PASSED, passed) putOpt(BYPASSED, bypassed) putOpt(VERIFIED, verified) putOpt(PROXY, proxy) putOpt(MOCKED, mocked) putOpt(COMPROMISED, compromised) putOpt(JUMPED, jumped) putOpt(SHARING, sharing) putOpt(INACCURATE, inaccurate) } } }
28
Kotlin
21
75
8a4fd286b99e21172b052e1738de528dcee0d196
3,602
radar-sdk-android
Apache License 2.0
jsonstream/src/main/kotlin/saffih/streamtools/jsonParser.kt
saffih
153,232,987
false
null
/* * Copyright (c) 2018. <NAME>. * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package saffih.streamtools import com.fasterxml.jackson.core.JsonFactory import com.fasterxml.jackson.core.JsonParser import com.fasterxml.jackson.core.JsonToken import com.fasterxml.jackson.core.TreeNode import com.fasterxml.jackson.core.type.TypeReference import com.fasterxml.jackson.databind.ObjectMapper import java.io.IOException import java.io.Reader import java.lang.reflect.ParameterizedType import java.util.stream.Stream class KJsonStreamParser { private val objectMapper = ObjectMapper() private val jsonFactory = JsonFactory(objectMapper) @Throws(IOException::class) fun parse(input: Reader): JsonStreamParserState { return JsonStreamParserState(input) } internal inner class UnexpectedError(s: String) : Exception(s) inner class JsonStreamParserState @Throws(IOException::class) constructor(input: Reader) { private val jp: JsonParser = jsonFactory.createParser(input) val fields = HashMap<String, TreeNode>() val streamFields = HashMap<String, Stream<TreeNode>>() init { this.jp.nextToken() } fun <T> parseObject(ref: TypeReference<T>, fieldname: String, callback: (java.lang.Exception) -> Unit): Stream<T> { val clazz = (if (ref.type is ParameterizedType) (ref.type as ParameterizedType).rawType else ref.type) as Class<T> return parseObject(fieldname, callback).map { it -> objectMapper.treeToValue(it, clazz) } } fun parseObject(fieldname: String, callback: (java.lang.Exception) -> Unit): Stream<TreeNode> { if (readStart(JsonToken.START_OBJECT, callback)) { readTillField(fieldname) val result = readStreamField(fieldname, callback) this.streamFields[fieldname] = result return result } else { return Stream.empty() } } private fun readStreamField(fieldname: String, callback: (java.lang.Exception) -> Unit): Stream<TreeNode> { if (jp.currentName == null) { callback(UnexpectedError("Expected missing field $fieldname")) return Stream.empty() } if (jp.currentName != fieldname) { callback(UnexpectedError("Bug wrong field $fieldname")) } jp.nextToken() // done fieldname return if (readStart(JsonToken.START_ARRAY, callback)) { streamUtil.generatorTillNull { this.parseTreeElement(JsonToken.END_ARRAY, callback) } } else Stream.empty() } private fun readTillField(fieldname: String) { while (JsonToken.FIELD_NAME == jp.currentToken() && jp.currentName != fieldname) { jp.nextToken() this.fields[jp.currentName] = jp.readValueAsTree() jp.nextToken() } } fun parseRest(callback: (java.lang.Exception) -> Unit) { while (JsonToken.FIELD_NAME == jp.currentToken()) { jp.nextToken() this.fields[jp.currentName] = jp.readValueAsTree() jp.nextToken() } } fun <T> parseArray(ref: TypeReference<T>, callback: (java.lang.Exception) -> Unit): Stream<T> { return if (readStart(JsonToken.START_ARRAY, callback)) streamUtil.generatorTillNull { this.parseElement(JsonToken.END_ARRAY, ref, callback) } else Stream.empty() } fun <T> parseObject(ref: TypeReference<T>, callback: (java.lang.Exception) -> Unit): Stream<T> { return if (readStart(JsonToken.START_ARRAY, callback)) streamUtil.generatorTillNull { this.parseElement(JsonToken.END_OBJECT, ref, callback) } else Stream.empty() } private fun readStart(start: JsonToken, callback: (java.lang.Exception) -> Unit): Boolean { val currentToken = jp.currentToken() if (currentToken != start) { callback(UnexpectedError("Expected start $start found $currentToken")) } else { try { jp.nextToken() } catch (e: IOException) { callback(e) return false } } return true } private fun parseTreeElement(end: JsonToken, callback: (Exception) -> Unit): TreeNode? { try { if (jp.currentToken() == end) { return null } return jp.readValueAsTree<TreeNode>() } catch (e: IOException) { callback(e) return null } finally { jp.nextToken() } } private fun <T> parseElement(end: JsonToken, ref: TypeReference<T>, callback: (Exception) -> Unit): T? { try { if (jp.currentToken() == end) { return null } return jp.readValueAs<T>(ref) } catch (e: IOException) { callback(e) return null } finally { jp.nextToken() } } } }
0
Kotlin
0
0
baecc9d233c69dabde343c7c6878313499476200
6,328
stream-tools
MIT License
src/main/kotlin/no/nav/helse/flex/domain/Arbeidssituasjon.kt
navikt
475,306,289
false
null
package no.nav.helse.flex.domain enum class Arbeidssituasjon(val navn: String) { NAERINGSDRIVENDE("selvstendig næringsdrivende"), FRILANSER("frilanser"), ARBEIDSTAKER("arbeidstaker"), ARBEIDSLEDIG("arbeidsledig"), ANNET("annet"), ; override fun toString(): String { return navn } }
8
null
0
4
4c07a767676b309ebf7db20c76674b152f3ec2ee
324
sykepengesoknad-backend
MIT License
src/test/java/org/jetbrains/plugins/ideavim/action/motion/leftright/MotionHomeActionTest.kt
JetBrains
1,459,486
false
null
/* * Copyright 2003-2023 The IdeaVim authors * * Use of this source code is governed by an MIT-style * license that can be found in the LICENSE.txt file or at * https://opensource.org/licenses/MIT. */ @file:Suppress("RemoveCurlyBracesFromTemplate") package org.jetbrains.plugins.ideavim.action.motion.leftright import com.maddyhome.idea.vim.options.OptionConstants import com.maddyhome.idea.vim.state.mode.Mode import com.maddyhome.idea.vim.state.mode.SelectionType import org.jetbrains.plugins.ideavim.SkipNeovimReason import org.jetbrains.plugins.ideavim.TestOptionConstants import org.jetbrains.plugins.ideavim.TestWithoutNeovim import org.jetbrains.plugins.ideavim.VimTestCase import org.jetbrains.plugins.ideavim.impl.OptionTest import org.jetbrains.plugins.ideavim.impl.TraceOptions import org.jetbrains.plugins.ideavim.impl.VimOption import kotlin.test.assertTrue @TraceOptions(TestOptionConstants.keymodel) class MotionHomeActionTest : VimTestCase() { @TestWithoutNeovim(SkipNeovimReason.OPTION) @OptionTest(VimOption(TestOptionConstants.keymodel, doesntAffectTest = true)) fun `test motion home`() { val keys = "<Home>" val before = """ A Discovery I found it in a ${c}legendary land all rocks and lavender and tufted grass, where it was settled on some sodden sand hard by the torrent of a mountain pass. """.trimIndent() val after = """ A Discovery ${c}I found it in a legendary land all rocks and lavender and tufted grass, where it was settled on some sodden sand hard by the torrent of a mountain pass. """.trimIndent() doTest(keys, before, after, Mode.NORMAL()) } @OptionTest(VimOption(TestOptionConstants.keymodel, doesntAffectTest = true)) fun `test default stop select`() { val keymodel = optionsNoEditor().keymodel assertTrue(OptionConstants.keymodel_stopselect in keymodel) } @TestWithoutNeovim(SkipNeovimReason.OPTION) @OptionTest(VimOption(TestOptionConstants.keymodel, limitedValues = [""])) fun `test continue visual`() { val keys = listOf("v", "<Home>") val before = """ A Discovery I found it in a ${c}legendary land all rocks and lavender and tufted grass, where it was settled on some sodden sand hard by the torrent of a mountain pass. """.trimIndent() val after = """ A Discovery ${s}${c}I found it in a l${se}egendary land all rocks and lavender and tufted grass, where it was settled on some sodden sand hard by the torrent of a mountain pass. """.trimIndent() doTest(keys, before, after, Mode.VISUAL(SelectionType.CHARACTER_WISE)) } @TestWithoutNeovim(SkipNeovimReason.OPTION) @OptionTest(VimOption(TestOptionConstants.keymodel, limitedValues = [""])) fun `test continue select`() { val keys = listOf("gh", "<Home>") val before = """ A Discovery I found it in a ${c}legendary land all rocks and lavender and tufted grass, where it was settled on some sodden sand hard by the torrent of a mountain pass. """.trimIndent() val after = """ A Discovery ${s}${c}I found it in a ${se}legendary land all rocks and lavender and tufted grass, where it was settled on some sodden sand hard by the torrent of a mountain pass. """.trimIndent() doTest(keys, before, after, Mode.SELECT(SelectionType.CHARACTER_WISE)) } @TestWithoutNeovim(SkipNeovimReason.OPTION) @OptionTest(VimOption(TestOptionConstants.keymodel, limitedValues = [OptionConstants.keymodel_stopvisual])) fun `test exit visual`() { val keys = listOf("v", "<Home>") val before = """ A Discovery I found it in a ${c}legendary land all rocks and lavender and tufted grass, where it was settled on some sodden sand hard by the torrent of a mountain pass. """.trimIndent() val after = """ A Discovery ${c}I found it in a legendary land all rocks and lavender and tufted grass, where it was settled on some sodden sand hard by the torrent of a mountain pass. """.trimIndent() doTest(keys, before, after, Mode.NORMAL()) } @TestWithoutNeovim(SkipNeovimReason.OPTION) @OptionTest(VimOption(TestOptionConstants.keymodel, limitedValues = [OptionConstants.keymodel_stopselect])) fun `test exit select`() { val keys = listOf("gh", "<Home>") val before = """ A Discovery I found it in a ${c}legendary land all rocks and lavender and tufted grass, where it was settled on some sodden sand hard by the torrent of a mountain pass. """.trimIndent() val after = """ A Discovery ${c}I found it in a legendary land all rocks and lavender and tufted grass, where it was settled on some sodden sand hard by the torrent of a mountain pass. """.trimIndent() doTest(keys, before, after, Mode.NORMAL()) } }
7
null
749
9,241
66b01b0b0d48ffec7b0148465b85e43dfbc908d3
5,263
ideavim
MIT License
src/test/java/org/jetbrains/plugins/ideavim/action/motion/leftright/MotionHomeActionTest.kt
JetBrains
1,459,486
false
null
/* * Copyright 2003-2023 The IdeaVim authors * * Use of this source code is governed by an MIT-style * license that can be found in the LICENSE.txt file or at * https://opensource.org/licenses/MIT. */ @file:Suppress("RemoveCurlyBracesFromTemplate") package org.jetbrains.plugins.ideavim.action.motion.leftright import com.maddyhome.idea.vim.options.OptionConstants import com.maddyhome.idea.vim.state.mode.Mode import com.maddyhome.idea.vim.state.mode.SelectionType import org.jetbrains.plugins.ideavim.SkipNeovimReason import org.jetbrains.plugins.ideavim.TestOptionConstants import org.jetbrains.plugins.ideavim.TestWithoutNeovim import org.jetbrains.plugins.ideavim.VimTestCase import org.jetbrains.plugins.ideavim.impl.OptionTest import org.jetbrains.plugins.ideavim.impl.TraceOptions import org.jetbrains.plugins.ideavim.impl.VimOption import kotlin.test.assertTrue @TraceOptions(TestOptionConstants.keymodel) class MotionHomeActionTest : VimTestCase() { @TestWithoutNeovim(SkipNeovimReason.OPTION) @OptionTest(VimOption(TestOptionConstants.keymodel, doesntAffectTest = true)) fun `test motion home`() { val keys = "<Home>" val before = """ A Discovery I found it in a ${c}legendary land all rocks and lavender and tufted grass, where it was settled on some sodden sand hard by the torrent of a mountain pass. """.trimIndent() val after = """ A Discovery ${c}I found it in a legendary land all rocks and lavender and tufted grass, where it was settled on some sodden sand hard by the torrent of a mountain pass. """.trimIndent() doTest(keys, before, after, Mode.NORMAL()) } @OptionTest(VimOption(TestOptionConstants.keymodel, doesntAffectTest = true)) fun `test default stop select`() { val keymodel = optionsNoEditor().keymodel assertTrue(OptionConstants.keymodel_stopselect in keymodel) } @TestWithoutNeovim(SkipNeovimReason.OPTION) @OptionTest(VimOption(TestOptionConstants.keymodel, limitedValues = [""])) fun `test continue visual`() { val keys = listOf("v", "<Home>") val before = """ A Discovery I found it in a ${c}legendary land all rocks and lavender and tufted grass, where it was settled on some sodden sand hard by the torrent of a mountain pass. """.trimIndent() val after = """ A Discovery ${s}${c}I found it in a l${se}egendary land all rocks and lavender and tufted grass, where it was settled on some sodden sand hard by the torrent of a mountain pass. """.trimIndent() doTest(keys, before, after, Mode.VISUAL(SelectionType.CHARACTER_WISE)) } @TestWithoutNeovim(SkipNeovimReason.OPTION) @OptionTest(VimOption(TestOptionConstants.keymodel, limitedValues = [""])) fun `test continue select`() { val keys = listOf("gh", "<Home>") val before = """ A Discovery I found it in a ${c}legendary land all rocks and lavender and tufted grass, where it was settled on some sodden sand hard by the torrent of a mountain pass. """.trimIndent() val after = """ A Discovery ${s}${c}I found it in a ${se}legendary land all rocks and lavender and tufted grass, where it was settled on some sodden sand hard by the torrent of a mountain pass. """.trimIndent() doTest(keys, before, after, Mode.SELECT(SelectionType.CHARACTER_WISE)) } @TestWithoutNeovim(SkipNeovimReason.OPTION) @OptionTest(VimOption(TestOptionConstants.keymodel, limitedValues = [OptionConstants.keymodel_stopvisual])) fun `test exit visual`() { val keys = listOf("v", "<Home>") val before = """ A Discovery I found it in a ${c}legendary land all rocks and lavender and tufted grass, where it was settled on some sodden sand hard by the torrent of a mountain pass. """.trimIndent() val after = """ A Discovery ${c}I found it in a legendary land all rocks and lavender and tufted grass, where it was settled on some sodden sand hard by the torrent of a mountain pass. """.trimIndent() doTest(keys, before, after, Mode.NORMAL()) } @TestWithoutNeovim(SkipNeovimReason.OPTION) @OptionTest(VimOption(TestOptionConstants.keymodel, limitedValues = [OptionConstants.keymodel_stopselect])) fun `test exit select`() { val keys = listOf("gh", "<Home>") val before = """ A Discovery I found it in a ${c}legendary land all rocks and lavender and tufted grass, where it was settled on some sodden sand hard by the torrent of a mountain pass. """.trimIndent() val after = """ A Discovery ${c}I found it in a legendary land all rocks and lavender and tufted grass, where it was settled on some sodden sand hard by the torrent of a mountain pass. """.trimIndent() doTest(keys, before, after, Mode.NORMAL()) } }
7
null
749
9,241
66b01b0b0d48ffec7b0148465b85e43dfbc908d3
5,263
ideavim
MIT License
el/src/main/kotlin/com/enlink/platform/searchs.kt
quinncch
133,957,926
false
{"Kotlin": 392388, "JavaScript": 25549, "Vue": 2273, "Java": 302, "HTML": 272}
package com.enlink.platform import org.elasticsearch.search.sort.SortOrder import java.io.Serializable import java.util.* /** * 功能描述:查询 * @auther changgq */ class Condition( val preciseConditions: Map<String, Array<String>> = emptyMap(), val ambiguousConditions: Map<String, String> = emptyMap(), val rangeConditionList: List<RangeCondition> = emptyList(), val sortConditions: Map<String, SortOrder> = emptyMap(), val currentPage: Int = 1, val pageSize: Int = 10, val scrollId: String = "" ) : Serializable class DownloadCondition( val preciseConditions: Map<String, Array<String>> = emptyMap(), val ambiguousConditions: Map<String, String> = emptyMap(), val rangeConditionList: List<RangeCondition> = emptyList(), val logType: String ) : Serializable /** * 功能描述:范围查询条件 * @auther changgq */ class RangeCondition(val type: Type = Type.DATE, var choice: String = "", val conditionName: String = "date", var gteValue: String = "", var lteValue: String = "", val timeZone: String = "+08:00") { init { when (choice) { "week" -> { // 当前周 gteValue = DateTimeUtils.currentWeekFirst().date2string() lteValue = DateTimeUtils.currentWeekLast().date2string() } "month" -> { // 最近一月 gteValue = DateTimeUtils.currentMonthFirst().date2string() lteValue = DateTimeUtils.currentMonthLast().date2string() } "3months" -> { // 最近三个月 gteValue = DateTimeUtils.last3monthsFirst().date2string() lteValue = Date().date2string() } "6months" -> { // 最近六个月 gteValue = DateTimeUtils.last6monthsFirst().date2string() lteValue = Date().date2string() } "12months" -> { // 最近一年 gteValue = DateTimeUtils.last12monthsFirst().date2string() lteValue = Date().date2string() } "year" -> { // 当前整年 gteValue = DateTimeUtils.currentYearFirst().date2string() lteValue = DateTimeUtils.currentYearLast().date2string() } "day" -> { // 当前整年 gteValue = Date().date2string() lteValue = Date().date2string() } else -> { gteValue = gteValue lteValue = lteValue } } } enum class Type { DATE, NUMBER, STRING } } class Pager(var currentPage: Int = 1, var pageSize: Int = 10, var totalHits: Long = 0, var pageDatas: List<Any>? = emptyList(), var scrollId: String? = "", var pageCount: Int = 1) { init { if (currentPage <= 0) currentPage = 1 if (pageSize <= 0) pageSize = 10 if (totalHits > 10000) totalHits = 10000 pageCount = (totalHits / pageSize).toInt() } }
0
Kotlin
0
0
f6a723d605a58b949cfe182b7d35164866874bd6
2,967
springboot-kotlin-elasticsearch-jest
Apache License 2.0
RtManager/src/main/java/cn/rubintry/rtmanager/callback/RuntimeAddCallback.kt
RubinTry
469,049,968
false
null
package cn.rubintry.rtmanager.callback import cn.rubintry.rtmanager.db.CustomRuntimeInfo import java.io.Serializable interface RuntimeAddCallback : Serializable { fun onAdd(info: CustomRuntimeInfo) }
0
Kotlin
0
0
e877fbbe636d56b87431ae46782011a6937c9baa
205
RuntimeManager
Apache License 2.0
compose/ui/ui-inspection/src/androidTest/java/androidx/compose/ui/inspection/inspector/LayoutInspectorTreeTest.kt
RikkaW
389,105,112
false
null
/* * Copyright 2020 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package androidx.compose.ui.inspection.inspector import android.view.View import android.view.ViewGroup import android.view.inspector.WindowInspector import android.widget.TextView import androidx.compose.animation.Crossfade import androidx.compose.foundation.Image import androidx.compose.foundation.background import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.Spacer import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.height import androidx.compose.foundation.layout.heightIn import androidx.compose.foundation.layout.padding import androidx.compose.foundation.lazy.LazyColumn import androidx.compose.foundation.text.BasicText import androidx.compose.material.AlertDialog import androidx.compose.material.Button import androidx.compose.material.Icon import androidx.compose.material.LinearProgressIndicator import androidx.compose.material.MaterialTheme import androidx.compose.material.ModalDrawer import androidx.compose.material.Scaffold import androidx.compose.material.Surface import androidx.compose.material.Text import androidx.compose.material.icons.Icons import androidx.compose.material.icons.filled.Call import androidx.compose.material.icons.filled.FavoriteBorder import androidx.compose.runtime.Composable import androidx.compose.runtime.CompositionLocalProvider import androidx.compose.runtime.InternalComposeApi import androidx.compose.runtime.currentComposer import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.runtime.rememberCompositionContext import androidx.compose.runtime.setValue import androidx.compose.runtime.tooling.CompositionData import androidx.compose.runtime.tooling.LocalInspectionTables import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.R import androidx.compose.ui.graphics.Color import androidx.compose.ui.graphics.graphicsLayer import androidx.compose.ui.inspection.compose.flatten import androidx.compose.ui.inspection.testdata.TestActivity import androidx.compose.ui.inspection.util.ThreadUtils import androidx.compose.ui.layout.GraphicLayerInfo import androidx.compose.ui.node.Ref import androidx.compose.ui.platform.LocalDensity import androidx.compose.ui.platform.LocalInspectionMode import androidx.compose.ui.platform.isDebugInspectorInfoEnabled import androidx.compose.ui.platform.testTag import androidx.compose.ui.semantics.clearAndSetSemantics import androidx.compose.ui.semantics.semantics import androidx.compose.ui.semantics.text import androidx.compose.ui.test.junit4.createAndroidComposeRule import androidx.compose.ui.test.onNodeWithTag import androidx.compose.ui.test.onNodeWithText import androidx.compose.ui.test.performClick import androidx.compose.ui.test.performScrollToIndex import androidx.compose.ui.text.AnnotatedString import androidx.compose.ui.text.TextStyle import androidx.compose.ui.text.font.Font import androidx.compose.ui.text.font.toFontFamily import androidx.compose.ui.text.style.TextDecoration import androidx.compose.ui.tooling.data.Group import androidx.compose.ui.tooling.data.UiToolingDataApi import androidx.compose.ui.tooling.data.asTree import androidx.compose.ui.tooling.data.position import androidx.compose.ui.unit.Density import androidx.compose.ui.unit.Dp import androidx.compose.ui.unit.TextUnit import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.sp import androidx.compose.ui.viewinterop.AndroidView import androidx.compose.ui.window.Popup import androidx.test.ext.junit.runners.AndroidJUnit4 import androidx.test.filters.LargeTest import androidx.test.filters.SdkSuppress import com.google.common.truth.Truth.assertThat import com.google.common.truth.Truth.assertWithMessage import java.util.Collections import java.util.WeakHashMap import kotlin.math.roundToInt import org.junit.After import org.junit.Before import org.junit.Rule import org.junit.Test import org.junit.runner.RunWith private const val DEBUG = false private const val ROOT_ID = 3L private const val MAX_RECURSIONS = 2 private const val MAX_ITERABLE_SIZE = 5 @LargeTest @RunWith(AndroidJUnit4::class) @SdkSuppress(minSdkVersion = 29) // Render id is not returned for api < 29 @OptIn(UiToolingDataApi::class) class LayoutInspectorTreeTest { private lateinit var density: Density @get:Rule val composeTestRule = createAndroidComposeRule<TestActivity>() private val fontFamily = Font(androidx.testutils.fonts.R.font.sample_font).toFontFamily() @Before fun before() { composeTestRule.activityRule.scenario.onActivity { density = Density(it) } isDebugInspectorInfoEnabled = true } private fun findAndroidComposeView(): View { return findAllAndroidComposeViews().single() } private fun findAllAndroidComposeViews(): List<View> = findAllViews("AndroidComposeView") private fun findAllViews(className: String): List<View> { val views = mutableListOf<View>() WindowInspector.getGlobalWindowViews().forEach { collectAllViews(it.rootView, className, views) } return views } private fun collectAllViews(view: View, className: String, views: MutableList<View>) { if (view.javaClass.simpleName == className) { views.add(view) } if (view !is ViewGroup) { return } for (i in 0 until view.childCount) { collectAllViews(view.getChildAt(i), className, views) } } @After fun after() { isDebugInspectorInfoEnabled = false } @Test fun doNotCommitWithDebugSetToTrue() { assertThat(DEBUG).isFalse() } @Test fun buildTree() { val slotTableRecord = CompositionDataRecord.create() val localDensity = Density(density = 1f, fontScale = 1f) show { Inspectable(slotTableRecord) { CompositionLocalProvider(LocalDensity provides localDensity) { Column { // width: 100.dp, height: 10.dp Text( text = "helloworld", color = Color.Green, fontSize = 10.sp, lineHeight = 10.sp, fontFamily = fontFamily ) // width: 24.dp, height: 24.dp Icon(Icons.Filled.FavoriteBorder, null) Surface { // minwidth: 64.dp, height: 42.dp Button(onClick = {}) { // width: 20.dp, height: 10.dp Text( text = "ok", fontSize = 10.sp, lineHeight = 10.sp, fontFamily = fontFamily ) } } } } } } // TODO: Find out if we can set "settings put global debug_view_attributes 1" in tests val view = findAndroidComposeView() view.setTag(R.id.inspection_slot_table_set, slotTableRecord.store) val builder = LayoutInspectorTree() builder.includeAllParameters = true val nodes = builder.convert(view) dumpNodes(nodes, view, builder) validate(nodes, builder, density = localDensity) { node( name = "Column", fileName = "LayoutInspectorTreeTest.kt", left = 0.0.dp, top = 0.0.dp, width = 100.dp, height = 82.dp, children = listOf("Text", "Icon", "Surface"), inlined = true, ) node( name = "Text", isRenderNode = true, fileName = "LayoutInspectorTreeTest.kt", left = 0.dp, top = 0.0.dp, width = 100.dp, height = 10.dp, ) node( name = "Icon", isRenderNode = true, fileName = "LayoutInspectorTreeTest.kt", left = 0.dp, top = 10.dp, width = 24.dp, height = 24.dp, ) node( name = "Surface", fileName = "LayoutInspectorTreeTest.kt", isRenderNode = true, left = 0.dp, top = 34.dp, width = 64.dp, height = 48.dp, children = listOf("Button") ) node( name = "Button", fileName = "LayoutInspectorTreeTest.kt", isRenderNode = true, left = 0.dp, top = 40.dp, width = 64.dp, height = 36.dp, children = listOf("Text") ) node( name = "Text", isRenderNode = true, fileName = "LayoutInspectorTreeTest.kt", left = 21.dp, top = 53.dp, width = 23.dp, height = 10.dp, ) } } @Test fun buildTreeWithTransformedText() { val slotTableRecord = CompositionDataRecord.create() val localDensity = Density(density = 1f, fontScale = 1f) show { Inspectable(slotTableRecord) { CompositionLocalProvider(LocalDensity provides localDensity) { Column { Text( text = "helloworld", fontSize = 10.sp, fontFamily = fontFamily, modifier = Modifier.graphicsLayer(rotationZ = -90f) ) } } } } // TODO: Find out if we can set "settings put global debug_view_attributes 1" in tests val view = findAndroidComposeView() view.setTag(R.id.inspection_slot_table_set, slotTableRecord.store) val builder = LayoutInspectorTree() val nodes = builder.convert(view) dumpNodes(nodes, view, builder) validate(nodes, builder, density = localDensity) { node( name = "Column", hasTransformations = false, fileName = "LayoutInspectorTreeTest.kt", left = 0.dp, top = 0.dp, width = 100.dp, height = 10.dp, children = listOf("Text"), inlined = true, ) node( name = "Text", isRenderNode = true, hasTransformations = true, fileName = "LayoutInspectorTreeTest.kt", left = 45.dp, top = 55.dp, width = 100.dp, height = 10.dp, ) } } @Test fun testStitchTreeFromModelDrawerLayout() { val slotTableRecord = CompositionDataRecord.create() show { Inspectable(slotTableRecord) { ModalDrawer( drawerContent = { Text("Something") }, content = { Column { Text(text = "Hello World", color = Color.Green) Button(onClick = {}) { Text(text = "OK") } } } ) } } val view = findAndroidComposeView() view.setTag(R.id.inspection_slot_table_set, slotTableRecord.store) dumpSlotTableSet(slotTableRecord) val builder = LayoutInspectorTree() val nodes = builder.convert(view) dumpNodes(nodes, view, builder) validate(nodes, builder) { node("ModalDrawer", isRenderNode = true, children = listOf("Column", "Text")) node("Column", inlined = true, children = listOf("Text", "Button")) node("Text", isRenderNode = true) node("Button", isRenderNode = true, children = listOf("Text")) node("Text", isRenderNode = true) node("Text", isRenderNode = true) } assertThat(nodes.size).isEqualTo(1) } @Test fun testStitchTreeFromModelDrawerLayoutWithSystemNodes() { val slotTableRecord = CompositionDataRecord.create() show { Inspectable(slotTableRecord) { ModalDrawer( drawerContent = { Text("Something") }, content = { Column { Text(text = "Hello World", color = Color.Green) Button(onClick = {}) { Text(text = "OK") } } } ) } } val view = findAndroidComposeView() view.setTag(R.id.inspection_slot_table_set, slotTableRecord.store) dumpSlotTableSet(slotTableRecord) val builder = LayoutInspectorTree() builder.hideSystemNodes = false val nodes = builder.convert(view) dumpNodes(nodes, view, builder) if (DEBUG) { validate(nodes, builder) { node("ModalDrawer", children = listOf("WithConstraints")) node("WithConstraints", children = listOf("SubcomposeLayout")) node("SubcomposeLayout", children = listOf("Box")) node("Box", children = listOf("Box", "Canvas", "Surface")) node("Box", children = listOf("Column")) node("Column", children = listOf("Text", "Button")) node("Text", children = listOf("Text")) node("Text", children = listOf("CoreText")) node("CoreText", children = listOf()) node("Button", children = listOf("Surface")) node("Surface", children = listOf("ProvideTextStyle")) node("ProvideTextStyle", children = listOf("Row")) node("Row", children = listOf("Text")) node("Text", children = listOf("Text")) node("Text", children = listOf("CoreText")) node("CoreText", children = listOf()) node("Canvas", children = listOf("Spacer")) node("Spacer", children = listOf()) node("Surface", children = listOf("Column")) node("Column", children = listOf("Text")) node("Text", children = listOf("Text")) node("Text", children = listOf("CoreText")) node("CoreText", children = listOf()) } } assertThat(nodes.size).isEqualTo(1) } @Test fun testSpacer() { val slotTableRecord = CompositionDataRecord.create() show { Inspectable(slotTableRecord) { Column { Text(text = "Hello World", color = Color.Green) Spacer(Modifier.height(16.dp)) Image(Icons.Filled.Call, null) } } } val view = findAndroidComposeView() view.setTag(R.id.inspection_slot_table_set, slotTableRecord.store) val builder = LayoutInspectorTree() val node = builder.convert(view).flatMap { flatten(it) }.firstOrNull { it.name == "Spacer" } // Spacer should show up in the Compose tree: assertThat(node).isNotNull() } @Test // regression test b/174855322 fun testBasicText() { val slotTableRecord = CompositionDataRecord.create() show { Inspectable(slotTableRecord) { Column { BasicText( text = "Some text", style = TextStyle(textDecoration = TextDecoration.Underline) ) } } } val view = findAndroidComposeView() view.setTag(R.id.inspection_slot_table_set, slotTableRecord.store) val builder = LayoutInspectorTree() builder.includeAllParameters = false val node = builder.convert(view).flatMap { flatten(it) }.firstOrNull { it.name == "BasicText" } assertThat(node).isNotNull() assertThat(node?.parameters).isEmpty() // Get parameters for the Spacer after getting the tree without parameters: val paramsNode = builder.findParameters(view, node!!.anchorId)!! val params = builder.convertParameters( ROOT_ID, paramsNode, ParameterKind.Normal, MAX_RECURSIONS, MAX_ITERABLE_SIZE ) assertThat(params).isNotEmpty() val text = params.find { it.name == "text" } assertThat(text?.value).isEqualTo("Some text") } @Test fun testTextId() { val slotTableRecord = CompositionDataRecord.create() show { Inspectable(slotTableRecord) { Text(text = "Hello World") } } val view = findAndroidComposeView() view.setTag(R.id.inspection_slot_table_set, slotTableRecord.store) val builder = LayoutInspectorTree() val node = builder.convert(view).flatMap { flatten(it) }.firstOrNull { it.name == "Text" } // LayoutNode id should be captured by the Text node: assertThat(node?.id).isGreaterThan(0) } @Test fun testSemantics() { val slotTableRecord = CompositionDataRecord.create() show { Inspectable(slotTableRecord) { Column { Text(text = "Studio") Row(modifier = Modifier.semantics(true) {}) { Text(text = "Hello") Text(text = "World") } Row(modifier = Modifier.clearAndSetSemantics { text = AnnotatedString("to") }) { Text(text = "Hello") Text(text = "World") } } } } val androidComposeView = findAndroidComposeView() androidComposeView.setTag(R.id.inspection_slot_table_set, slotTableRecord.store) val builder = LayoutInspectorTree() val nodes = builder.convert(androidComposeView) validate(nodes, builder, checkSemantics = true) { node("Column", children = listOf("Text", "Row", "Row"), inlined = true) node( name = "Text", isRenderNode = true, mergedSemantics = "[Studio]", unmergedSemantics = "[Studio]", ) node( name = "Row", children = listOf("Text", "Text"), mergedSemantics = "[Hello, World]", inlined = true, ) node("Text", isRenderNode = true, unmergedSemantics = "[Hello]") node("Text", isRenderNode = true, unmergedSemantics = "[World]") node( name = "Row", children = listOf("Text", "Text"), mergedSemantics = "[to]", unmergedSemantics = "[to]", inlined = true, ) node("Text", isRenderNode = true, unmergedSemantics = "[Hello]") node("Text", isRenderNode = true, unmergedSemantics = "[World]") } } @Test fun testDialog() { val slotTableRecord = CompositionDataRecord.create() show { Inspectable(slotTableRecord) { Column { Text("Hello World!") AlertDialog( onDismissRequest = {}, confirmButton = { Button({}) { Text("This is the Confirm Button") } } ) } } } val composeViews = findAllAndroidComposeViews() val appView = composeViews[0] val dialogView = composeViews[1] assertThat(composeViews).hasSize(2) appView.setTag(R.id.inspection_slot_table_set, slotTableRecord.store) dialogView.setTag(R.id.inspection_slot_table_set, slotTableRecord.store) val builder = LayoutInspectorTree() val appNodes = builder.convert(appView) dumpSlotTableSet(slotTableRecord) dumpNodes(appNodes, appView, builder) // Verify that the main app does not contain the Popup validate(appNodes, builder) { node( name = "Column", fileName = "LayoutInspectorTreeTest.kt", children = listOf("Text"), inlined = true, ) node( name = "Text", isRenderNode = true, fileName = "LayoutInspectorTreeTest.kt", ) } val dialogContentNodes = builder.convert(dialogView) val dialogNodes = builder.addSubCompositionRoots(dialogView, dialogContentNodes) dumpNodes(dialogNodes, dialogView, builder) // Verify that the AlertDialog is captured with content validate(dialogNodes, builder) { node( name = "AlertDialog", fileName = "LayoutInspectorTreeTest.kt", children = listOf("Button") ) node( name = "Button", fileName = "LayoutInspectorTreeTest.kt", isRenderNode = true, children = listOf("Text") ) node( name = "Text", isRenderNode = true, fileName = "LayoutInspectorTreeTest.kt", ) } } @Test fun testPopup() { val slotTableRecord = CompositionDataRecord.create() show { Inspectable(slotTableRecord) { Column(modifier = Modifier.fillMaxSize()) { Text("Compose Text") Popup(alignment = Alignment.Center) { Text("This is a popup") } } } } val composeViews = findAllAndroidComposeViews() val appView = composeViews[0] val popupView = composeViews[1] appView.setTag(R.id.inspection_slot_table_set, slotTableRecord.store) popupView.setTag(R.id.inspection_slot_table_set, slotTableRecord.store) val builder = LayoutInspectorTree() val appNodes = builder.convert(appView) dumpNodes(appNodes, appView, builder) // Verify that the main app does not contain the Popup validate(appNodes, builder) { node( name = "Column", isRenderNode = true, fileName = "LayoutInspectorTreeTest.kt", children = listOf("Text"), inlined = true, ) node( name = "Text", isRenderNode = true, fileName = "LayoutInspectorTreeTest.kt", ) } val popupContentNodes = builder.convert(popupView) val popupNodes = builder.addSubCompositionRoots(popupView, popupContentNodes) dumpNodes(popupNodes, popupView, builder) // Verify that the Popup is captured with content validate(popupNodes, builder) { node(name = "Popup", fileName = "LayoutInspectorTreeTest.kt", children = listOf("Text")) node( name = "Text", isRenderNode = true, fileName = "LayoutInspectorTreeTest.kt", ) } } @Test fun testAndroidView() { val slotTableRecord = CompositionDataRecord.create() show { Inspectable(slotTableRecord) { Column { Text("Compose Text") AndroidView({ context -> TextView(context).apply { text = "AndroidView" } }) } } } val composeView = findAndroidComposeView() as ViewGroup composeView.setTag(R.id.inspection_slot_table_set, slotTableRecord.store) val builder = LayoutInspectorTree() builder.hideSystemNodes = false val nodes = builder.convert(composeView) dumpNodes(nodes, composeView, builder) val androidView = nodes.flatMap { flatten(it) }.first { it.name == "AndroidView" } assertThat(androidView.viewId).isEqualTo(0) validate(listOf(androidView), builder) { node( name = "AndroidView", fileName = "LayoutInspectorTreeTest.kt", children = listOf("AndroidView") ) node( name = "AndroidView", fileName = "AndroidView.android.kt", children = listOf("ComposeNode") ) node( name = "ComposeNode", fileName = "AndroidView.android.kt", hasViewIdUnder = composeView, inlined = true, ) } } @Test fun testAndroidViewWithOnResetOverload() { val slotTableRecord = CompositionDataRecord.create() show { Inspectable(slotTableRecord) { Column { Text("Compose Text") AndroidView( factory = { context -> TextView(context).apply { text = "AndroidView" } }, onReset = { // Do nothing, just use the overload. } ) } } } val composeView = findAndroidComposeView() as ViewGroup composeView.setTag(R.id.inspection_slot_table_set, slotTableRecord.store) val builder = LayoutInspectorTree() builder.hideSystemNodes = false val nodes = builder.convert(composeView) dumpNodes(nodes, composeView, builder) val androidView = nodes.flatMap { flatten(it) }.first { it.name == "AndroidView" } assertThat(androidView.viewId).isEqualTo(0) validate(listOf(androidView), builder) { node( name = "AndroidView", fileName = "LayoutInspectorTreeTest.kt", children = listOf("ReusableComposeNode") ) node( name = "ReusableComposeNode", fileName = "AndroidView.android.kt", hasViewIdUnder = composeView, inlined = true, ) } } @Test fun testDoubleAndroidView() { val slotTableRecord = CompositionDataRecord.create() show { Inspectable(slotTableRecord) { Column { Text("Compose Text1") AndroidView({ context -> TextView(context).apply { text = "first" } }) Text("Compose Text2") AndroidView({ context -> TextView(context).apply { text = "second" } }) } } } val composeView = findAndroidComposeView() as ViewGroup composeView.setTag(R.id.inspection_slot_table_set, slotTableRecord.store) val builder = LayoutInspectorTree() builder.hideSystemNodes = false val nodes = builder.convert(composeView) dumpSlotTableSet(slotTableRecord) dumpNodes(nodes, composeView, builder) val textViews = findAllViews("TextView") val firstTextView = textViews.filterIsInstance<TextView>().first { it.text == "first" } val secondTextView = textViews.filterIsInstance<TextView>().first { it.text == "second" } val composeNodes = nodes.flatMap { it.flatten() }.filter { it.name == "ComposeNode" } assertThat(composeNodes[0].viewId).isEqualTo(viewParent(secondTextView)?.uniqueDrawingId) assertThat(composeNodes[1].viewId).isEqualTo(viewParent(firstTextView)?.uniqueDrawingId) } // WARNING: The formatting of the lines below here affect test results. val titleLine = Throwable().stackTrace[0].lineNumber + 3 @Composable private fun Title() { val maxOffset = with(LocalDensity.current) { 80.dp.toPx() } val minOffset = with(LocalDensity.current) { 80.dp.toPx() } val offset = maxOffset.coerceAtLeast(minOffset) Column( verticalArrangement = Arrangement.Bottom, modifier = Modifier.heightIn(min = 128.dp) .graphicsLayer { translationY = offset } .background(color = MaterialTheme.colors.background) ) { Spacer(Modifier.height(16.dp)) Text( text = "Snack", style = MaterialTheme.typography.h4, color = MaterialTheme.colors.secondary, modifier = Modifier.padding(horizontal = 24.dp) ) Text( text = "Tagline", style = MaterialTheme.typography.subtitle2, fontSize = 20.sp, color = MaterialTheme.colors.secondary, modifier = Modifier.padding(horizontal = 24.dp) ) Spacer(Modifier.height(4.dp)) Text( text = "$2.95", style = MaterialTheme.typography.h6, color = MaterialTheme.colors.primary, modifier = Modifier.padding(horizontal = 24.dp) ) Spacer(Modifier.height(8.dp)) } } // WARNING: End formatted section @Test fun testLineNumbers() { // WARNING: The formatting of the lines below here affect test results. val testLine = Throwable().stackTrace[0].lineNumber val slotTableRecord = CompositionDataRecord.create() show { Inspectable(slotTableRecord) { Column { Title() } } } // WARNING: End formatted section val androidComposeView = findAndroidComposeView() androidComposeView.setTag(R.id.inspection_slot_table_set, slotTableRecord.store) val builder = LayoutInspectorTree() val nodes = builder.convert(androidComposeView) dumpNodes(nodes, androidComposeView, builder) validate(nodes, builder, checkLineNumbers = true, checkRenderNodes = false) { node("Column", lineNumber = testLine + 3, children = listOf("Title"), inlined = true) node("Title", lineNumber = testLine + 3, children = listOf("Column")) node( name = "Column", lineNumber = titleLine + 4, children = listOf("Spacer", "Text", "Text", "Spacer", "Text", "Spacer"), inlined = true, ) node("Spacer", lineNumber = titleLine + 11) node("Text", lineNumber = titleLine + 12) node("Text", lineNumber = titleLine + 18) node("Spacer", lineNumber = titleLine + 25) node("Text", lineNumber = titleLine + 26) node("Spacer", lineNumber = titleLine + 32) } } @Composable @Suppress("UNUSED_PARAMETER") fun First(p1: Int) { Text("First") } @Composable @Suppress("UNUSED_PARAMETER") fun Second(p2: Int) { Text("Second") } @Test fun testCrossfade() { val slotTableRecord = CompositionDataRecord.create() show { Inspectable(slotTableRecord) { Column { var showFirst by remember { mutableStateOf(true) } Button(onClick = { showFirst = !showFirst }) { Text("Button") } Crossfade(showFirst) { when (it) { true -> First(p1 = 1) false -> Second(p2 = 2) } } } } } val androidComposeView = findAndroidComposeView() androidComposeView.setTag(R.id.inspection_slot_table_set, slotTableRecord.store) val builder = LayoutInspectorTree() builder.includeAllParameters = true val tree1 = builder.convert(androidComposeView) val first = tree1.flatMap { flatten(it) }.single { it.name == "First" } val hash = packageNameHash(this.javaClass.name.substringBeforeLast('.')) assertThat(first.fileName).isEqualTo("LayoutInspectorTreeTest.kt") assertThat(first.packageHash).isEqualTo(hash) assertThat(first.parameters.map { it.name }).contains("p1") val cross1 = tree1.flatMap { flatten(it) }.single { it.name == "Crossfade" } val button1 = tree1.flatMap { flatten(it) }.single { it.name == "Button" } val column1 = tree1.flatMap { flatten(it) }.single { it.name == "Column" } assertThat(cross1.id).isGreaterThan(RESERVED_FOR_GENERATED_IDS) assertThat(button1.id).isGreaterThan(RESERVED_FOR_GENERATED_IDS) assertThat(column1.id).isLessThan(RESERVED_FOR_GENERATED_IDS) composeTestRule.onNodeWithText("Button").performClick() composeTestRule.runOnIdle { val tree2 = builder.convert(androidComposeView) val second = tree2.flatMap { flatten(it) }.first { it.name == "Second" } assertThat(second.fileName).isEqualTo("LayoutInspectorTreeTest.kt") assertThat(second.packageHash).isEqualTo(hash) assertThat(second.parameters.map { it.name }).contains("p2") val cross2 = tree2.flatMap { flatten(it) }.first { it.name == "Crossfade" } val button2 = tree2.flatMap { flatten(it) }.single { it.name == "Button" } val column2 = tree2.flatMap { flatten(it) }.single { it.name == "Column" } assertThat(cross2.id).isNotEqualTo(cross1.id) assertThat(button2.id).isEqualTo(button1.id) assertThat(column2.id).isEqualTo(column1.id) } } @Test fun testInlineParameterTypes() { val slotTableRecord = CompositionDataRecord.create() show { Inspectable(slotTableRecord) { InlineParameters(20.5.dp, 30.sp) } } val androidComposeView = findAndroidComposeView() androidComposeView.setTag(R.id.inspection_slot_table_set, slotTableRecord.store) val builder = LayoutInspectorTree() builder.hideSystemNodes = false builder.includeAllParameters = true val inlineParameters = builder .convert(androidComposeView) .flatMap { flatten(it) } .first { it.name == "InlineParameters" } assertThat(inlineParameters.parameters[0].name).isEqualTo("size") assertThat(inlineParameters.parameters[0].value?.javaClass).isEqualTo(Dp::class.java) assertThat(inlineParameters.parameters[1].name).isEqualTo("fontSize") assertThat(inlineParameters.parameters[1].value?.javaClass).isEqualTo(TextUnit::class.java) assertThat(inlineParameters.parameters).hasSize(2) } @Test fun testRemember() { val slotTableRecord = CompositionDataRecord.create() // Regression test for: b/235526153 // The method: SubCompositionRoots.remember had code like this: // group.data.filterIsInstance<Ref<ViewRootForInspector>>().singleOrNull()?.value // which would cause a ClassCastException if the data contained a Ref to something // else than a ViewRootForInspector instance. This would crash the app. show { Inspectable(slotTableRecord) { rememberCompositionContext() val stringReference = remember { Ref<String>() } stringReference.value = "Hello" } } val androidComposeView = findAndroidComposeView() androidComposeView.setTag(R.id.inspection_slot_table_set, slotTableRecord.store) val builder = LayoutInspectorTree() builder.hideSystemNodes = false builder.includeAllParameters = false } @Test // regression test for b/311436726 fun testLazyColumn() { val slotTableRecord = CompositionDataRecord.create() show { Inspectable(slotTableRecord) { LazyColumn(modifier = Modifier.testTag("LazyColumn")) { items(100) { index -> Text(text = "Item: $index") } } } } val androidComposeView = findAndroidComposeView() androidComposeView.setTag(R.id.inspection_slot_table_set, slotTableRecord.store) val builder = LayoutInspectorTree() builder.hideSystemNodes = false builder.includeAllParameters = true ThreadUtils.runOnMainThread { builder.convert(androidComposeView) } for (index in 20..40) { composeTestRule.onNodeWithTag("LazyColumn").performScrollToIndex(index) } ThreadUtils.runOnMainThread { builder.convert(androidComposeView) } } @Test fun testScaffold() { val slotTableRecord = CompositionDataRecord.create() show { Inspectable(slotTableRecord) { Scaffold { Column { LinearProgressIndicator(progress = 0.3F) } } } } val androidComposeView = findAndroidComposeView() androidComposeView.setTag(R.id.inspection_slot_table_set, slotTableRecord.store) val builder = LayoutInspectorTree() builder.hideSystemNodes = false builder.includeAllParameters = true val linearProgressIndicator = builder .convert(androidComposeView) .flatMap { flatten(it) } .firstOrNull { it.name == "LinearProgressIndicator" } assertThat(linearProgressIndicator).isNotNull() } @Suppress("SameParameterValue") private fun validate( result: List<InspectorNode>, builder: LayoutInspectorTree, checkParameters: Boolean = false, checkSemantics: Boolean = false, checkLineNumbers: Boolean = false, checkRenderNodes: Boolean = true, density: Density = this.density, block: TreeValidationReceiver.() -> Unit = {} ) { if (DEBUG) { return } val nodes = result.flatMap { flatten(it) }.listIterator() val tree = TreeValidationReceiver( nodes, density, checkParameters, checkSemantics, checkLineNumbers, checkRenderNodes, builder ) tree.block() } private class TreeValidationReceiver( val nodeIterator: Iterator<InspectorNode>, val density: Density, val checkParameters: Boolean, val checkSemantics: Boolean, val checkLineNumbers: Boolean, val checkRenderNodes: Boolean, val builder: LayoutInspectorTree ) { fun node( name: String, fileName: String? = null, lineNumber: Int = -1, isRenderNode: Boolean = false, inlined: Boolean = false, hasViewIdUnder: View? = null, hasTransformations: Boolean = false, mergedSemantics: String = "", unmergedSemantics: String = "", left: Dp = Dp.Unspecified, top: Dp = Dp.Unspecified, width: Dp = Dp.Unspecified, height: Dp = Dp.Unspecified, children: List<String> = listOf(), block: ParameterValidationReceiver.() -> Unit = {} ) { assertWithMessage("No such node found: $name").that(nodeIterator.hasNext()).isTrue() val node = nodeIterator.next() assertThat(node.name).isEqualTo(name) assertThat(node.anchorId).isNotEqualTo(UNDEFINED_ID) val message = "Node: $name" assertWithMessage(message) .that(node.children.map { it.name }) .containsExactlyElementsIn(children) .inOrder() fileName?.let { assertWithMessage(message).that(node.fileName).isEqualTo(fileName) } if (lineNumber != -1) { assertWithMessage(message).that(node.lineNumber).isEqualTo(lineNumber) } assertWithMessage(message).that(node.inlined).isEqualTo(inlined) if (checkRenderNodes) { if (isRenderNode) { assertWithMessage(message).that(node.id).isGreaterThan(0L) } else { assertWithMessage(message).that(node.id).isLessThan(0L) } } if (hasViewIdUnder != null) { assertWithMessage(message).that(node.viewId).isGreaterThan(0L) assertWithMessage(message).that(hasViewIdUnder.hasChild(node.viewId)).isTrue() } else { assertWithMessage(message).that(node.viewId).isEqualTo(0L) } if (hasTransformations) { assertWithMessage(message).that(node.bounds).isNotNull() } else { assertWithMessage(message).that(node.bounds).isNull() } if (left != Dp.Unspecified) { with(density) { assertWithMessage(message) .that(node.left.toDp().value) .isWithin(2.0f) .of(left.value) assertWithMessage(message) .that(node.top.toDp().value) .isWithin(2.0f) .of(top.value) assertWithMessage(message) .that(node.width.toDp().value) .isWithin(2.0f) .of(width.value) assertWithMessage(message) .that(node.height.toDp().value) .isWithin(2.0f) .of(height.value) } } if (checkSemantics) { val merged = node.mergedSemantics.singleOrNull { it.name == "Text" }?.value assertWithMessage(message).that(merged?.toString() ?: "").isEqualTo(mergedSemantics) val unmerged = node.unmergedSemantics.singleOrNull { it.name == "Text" }?.value assertWithMessage(message) .that(unmerged?.toString() ?: "") .isEqualTo(unmergedSemantics) } if (checkLineNumbers) { assertThat(node.lineNumber).isEqualTo(lineNumber) } if (checkParameters) { val params = builder.convertParameters( ROOT_ID, node, ParameterKind.Normal, MAX_RECURSIONS, MAX_ITERABLE_SIZE ) val receiver = ParameterValidationReceiver(params.listIterator()) receiver.block() receiver.checkFinished(name) } } private fun View.hasChild(id: Long): Boolean { if (uniqueDrawingId == id) { return true } if (this !is ViewGroup) { return false } for (index in 0..childCount) { if (getChildAt(index).hasChild(id)) { return true } } return false } } private fun flatten(node: InspectorNode): List<InspectorNode> = listOf(node).plus(node.children.flatMap { flatten(it) }) private fun viewParent(view: View): View? = view.parent as? View private fun show(composable: @Composable () -> Unit) = composeTestRule.setContent(composable) // region DEBUG print methods private fun dumpNodes(nodes: List<InspectorNode>, view: View, builder: LayoutInspectorTree) { @Suppress("ConstantConditionIf") if (!DEBUG) { return } println() println("=================== Nodes ==========================") nodes.forEach { dumpNode(it, indent = 0) } println() println("=================== validate statements ==========================") nodes.forEach { generateValidate(it, view, builder) } } private fun dumpNode(node: InspectorNode, indent: Int) { println( "\"${" ".repeat(indent * 2)}\", \"${node.name}\", \"${node.fileName}\", " + "${node.lineNumber}, ${node.left}, ${node.top}, " + "${node.width}, ${node.height}" ) node.children.forEach { dumpNode(it, indent + 1) } } private fun generateValidate( node: InspectorNode, view: View, builder: LayoutInspectorTree, generateParameters: Boolean = false ) { with(density) { val left = round(node.left.toDp()) val top = round(node.top.toDp()) val width = if (node.width == view.width) "viewWidth" else round(node.width.toDp()) val height = if (node.height == view.height) "viewHeight" else round(node.height.toDp()) print( """ validate( name = "${node.name}", fileName = "${node.fileName}", left = $left, top = $top, width = $width, height = $height """ .trimIndent() ) } if (node.id > 0L) { println(",") print(" isRenderNode = true") } if (node.children.isNotEmpty()) { println(",") val children = node.children.joinToString { "\"${it.name}\"" } print(" children = listOf($children)") } println() print(")") if (generateParameters && node.parameters.isNotEmpty()) { generateParameters( builder.convertParameters( ROOT_ID, node, ParameterKind.Normal, MAX_RECURSIONS, MAX_ITERABLE_SIZE ), 0 ) } println() node.children.forEach { generateValidate(it, view, builder) } } private fun generateParameters(parameters: List<NodeParameter>, indent: Int) { val indentation = " ".repeat(indent * 2) println(" {") for (param in parameters) { val name = param.name val type = param.type val value = toDisplayValue(type, param.value) print("$indentation parameter(name = \"$name\", type = $type, value = $value)") if (param.elements.isNotEmpty()) { generateParameters(param.elements, indent + 1) } println() } print("$indentation}") } private fun toDisplayValue(type: ParameterType, value: Any?): String = when (type) { ParameterType.Boolean -> value.toString() ParameterType.Color -> "0x${Integer.toHexString(value as Int)}${if (value < 0) ".toInt()" else ""}" ParameterType.DimensionSp, ParameterType.DimensionDp -> "${value}f" ParameterType.Int32 -> value.toString() ParameterType.String -> "\"$value\"" else -> value?.toString() ?: "null" } private fun dumpSlotTableSet(slotTableRecord: CompositionDataRecord) { @Suppress("ConstantConditionIf") if (!DEBUG) { return } println() println("=================== Groups ==========================") slotTableRecord.store.forEach { dumpGroup(it.asTree(), indent = 0) } } private fun dumpGroup(group: Group, indent: Int) { val location = group.location val position = group.position?.let { "\"$it\"" } ?: "null" val box = group.box val id = group.modifierInfo .mapNotNull { (it.extra as? GraphicLayerInfo)?.layerId } .singleOrNull() ?: 0 println( "\"${" ".repeat(indent)}\", ${group.javaClass.simpleName}, \"${group.name}\", " + "file: ${location?.sourceFile} hash: ${location?.packageHash}, " + "params: ${group.parameters.size}, children: ${group.children.size}, " + "$id, $position, " + "${box.left}, ${box.right}, ${box.right - box.left}, ${box.bottom - box.top}" ) for (parameter in group.parameters) { println("\"${" ".repeat(indent + 4)}\"- ${parameter.name}") } group.children.forEach { dumpGroup(it, indent + 1) } } private fun round(dp: Dp): Dp = Dp((dp.value * 10.0f).roundToInt() / 10.0f) // endregion } /** Storage for the preview generated [CompositionData]s. */ internal interface CompositionDataRecord { val store: Set<CompositionData> companion object { fun create(): CompositionDataRecord = CompositionDataRecordImpl() } } private class CompositionDataRecordImpl : CompositionDataRecord { @OptIn(InternalComposeApi::class) override val store: MutableSet<CompositionData> = Collections.newSetFromMap(WeakHashMap()) } /** * A wrapper for compositions in inspection mode. The composition inside the Inspectable component * is in inspection mode. * * @param compositionDataRecord [CompositionDataRecord] to record the SlotTable used in the * composition of [content] */ @Composable @OptIn(InternalComposeApi::class) internal fun Inspectable( compositionDataRecord: CompositionDataRecord, content: @Composable () -> Unit ) { currentComposer.collectParameterInformation() val store = (compositionDataRecord as CompositionDataRecordImpl).store store.add(currentComposer.compositionData) CompositionLocalProvider( LocalInspectionMode provides true, LocalInspectionTables provides store, content = content ) } @Composable fun InlineParameters(size: Dp, fontSize: TextUnit) { Text("$size $fontSize") }
6
null
984
7
6d53f95e5d979366cf7935ad7f4f14f76a951ea5
51,182
androidx
Apache License 2.0
packages/expo-image-picker/android/src/main/java/expo/modules/imagepicker/exporters/CompressionImageExporter.kt
luoxuhai
474,851,682
true
{"Objective-C": 21098327, "Java": 12710084, "C++": 10387208, "Kotlin": 7081090, "TypeScript": 6149256, "Objective-C++": 4571681, "Swift": 1749750, "JavaScript": 1047031, "Starlark": 636449, "Ruby": 462733, "C": 287204, "Makefile": 201127, "Shell": 117022, "Assembly": 46741, "CMake": 33526, "HTML": 23933, "Batchfile": 378}
package expo.modules.imagepicker.exporters import android.graphics.Bitmap import android.net.Uri import androidx.annotation.FloatRange import expo.modules.imagepicker.exporters.ImageExporter.Listener import expo.modules.interfaces.imageloader.ImageLoaderInterface import org.apache.commons.io.FilenameUtils import java.io.ByteArrayOutputStream import java.io.File import java.io.FileOutputStream import java.io.IOException class CompressionImageExporter( private val imageLoader: ImageLoaderInterface, @FloatRange(from = 0.0, to = 1.0) quality: Double, private val base64: Boolean ) : ImageExporter { private val quality: Int = (quality * 100).toInt() override fun export(source: Uri, output: File, exporterListener: Listener) { val imageLoaderHandler = object : ImageLoaderInterface.ResultListener { override fun onSuccess(bitmap: Bitmap) { val width = bitmap.width val height = bitmap.height (if (base64) ByteArrayOutputStream() else null).use { base64Stream -> try { val compressFormat = if (FilenameUtils.getExtension(output.path).contains("png")) { Bitmap.CompressFormat.PNG } else { Bitmap.CompressFormat.JPEG } saveBitmap(bitmap, compressFormat, output, base64Stream) exporterListener.onResult(base64Stream, width, height) } catch (e: IOException) { exporterListener.onFailure(e) } } } override fun onFailure(cause: Throwable?) { exporterListener.onFailure(cause) } } imageLoader.loadImageForManipulationFromURL(source.toString(), imageLoaderHandler) } /** * Compress and save the `bitmap` to `file`, optionally saving it in `out` if * base64 is requested. * * @param bitmap bitmap to be saved * @param compressFormat compression format to save the image in * @param output file to save the image to * @param out if not null, the stream to save the image to */ @Throws(IOException::class) private fun saveBitmap(bitmap: Bitmap, compressFormat: Bitmap.CompressFormat, output: File, out: ByteArrayOutputStream?) { writeImage(bitmap, output, compressFormat) if (base64) { bitmap.compress(Bitmap.CompressFormat.JPEG, quality, out) } } @Throws(IOException::class) private fun writeImage(image: Bitmap, output: File, compressFormat: Bitmap.CompressFormat) { FileOutputStream(output).use { out -> image.compress(compressFormat, quality, out) } } }
0
Objective-C
0
0
8948d665a96976b0817c0d8ce7e3c4009777e95a
2,536
expo
MIT License
src/main/kotlin/dodd/Block.kt
tomdodd4598
678,195,171
false
{"Kotlin": 11319}
package dodd import java.io.File abstract class Block { fun writeToFile(blockName: String) { File(getFileName(blockName)).writeText(getJsonContents(blockName)) } abstract fun getFileName(blockName: String): String abstract fun getJsonContents(blockName: String): String } class Sink : Block() { override fun getFileName(blockName: String) = "solid_fission_sink_$blockName.json" override fun getJsonContents(blockName: String) = """{ "forge_marker": 1, "defaults": { "model": "cube_all", "textures": { "all": "nuclearcraft:blocks/sink_$blockName" } }, "variants": { "inventory": [{}], "normal": [{}] } } """ } class Heater : Block() { override fun getFileName(blockName: String) = "salt_fission_heater_$blockName.json" override fun getJsonContents(blockName: String) = """{ "forge_marker": 1, "defaults": { "model": "cube_all", "textures": { "all": "nuclearcraft:blocks/heater_$blockName" } }, "variants": { "inventory": [{}], "normal": [{}] } } """ } class HeaterPort : Block() { override fun getFileName(blockName: String) = "fission_heater_port_$blockName.json" override fun getJsonContents(blockName: String) = """{ "forge_marker": 1, "defaults": { "model": "nuclearcraft:fission_port_overlayed", "textures": { "front": "nuclearcraft:blocks/heater_port_$blockName", "overlay": "nuclearcraft:blocks/fission/port/heater/off" } }, "variants": { "inventory": [{}], "active": { "false": {}, "true": { "textures": { "overlay": "nuclearcraft:blocks/fission/port/heater/on" } } }, "axis": { "x": {"y": 90}, "y": {"x": 90}, "z": {} } } } """ } class Source : Block() { override fun getFileName(blockName: String) = "fission_source_$blockName.json" override fun getJsonContents(blockName: String) = """{ "forge_marker": 1, "defaults": { "model": "nuclearcraft:wall_part", "textures": { "in": "nuclearcraft:blocks/source_$blockName", "out": "nuclearcraft:blocks/fission/source_out_off", "side": "nuclearcraft:blocks/fission/source_side", "top": "nuclearcraft:blocks/fission/source_side" } }, "variants": { "inventory": [{ "y": 180 }], "active": { "false": {}, "true": { "textures": { "out": "nuclearcraft:blocks/fission/source_out_on" } } }, "facing": { "down": {"x": 90}, "up": {"x": 270}, "north": {}, "east": {"y": 90}, "south": {"y": 180}, "west": {"y": 270} } } } """ } class Shield : Block() { override fun getFileName(blockName: String) = "fission_shield_$blockName.json" override fun getJsonContents(blockName: String) = """{ "forge_marker": 1, "defaults": { "model": "nuclearcraft:cube_all_overlayed", "textures": { "all": "nuclearcraft:blocks/shield_$blockName", "overlay": "nuclearcraft:blocks/fission/shield/on" } }, "variants": { "inventory": [{}], "active": { "false": { "textures": { "overlay": "nuclearcraft:blocks/fission/shield/off" } }, "true": {} } } } """ } class Coil : Block() { override fun getFileName(blockName: String) = "turbine_dynamo_coil_$blockName.json" override fun getJsonContents(blockName: String) = """{ "forge_marker": 1, "defaults": { "model": "cube_all", "textures": { "all": "nuclearcraft:blocks/coil_$blockName" } }, "variants": { "inventory": [{}], "normal": [{}] } } """ } class Blade : Block() { override fun getFileName(blockName: String) = "turbine_rotor_blade_$blockName.json" override fun getJsonContents(blockName: String) = """{ "forge_marker": 1, "defaults": { "model": "nuclearcraft:turbine_rotor_blade", "textures": { "texture": "nuclearcraft:blocks/blade_$blockName" } }, "variants": { "inventory": [{}], "dir": { "invisible": { "model": "nuclearcraft:block_invisible" }, "x": {"x": 90, "y": 90}, "y": {}, "z": {"x": 90} } } } """ } class Stator : Block() { override fun getFileName(blockName: String) = "turbine_rotor_stator_$blockName.json" override fun getJsonContents(blockName: String) = """{ "forge_marker": 1, "defaults": { "model": "nuclearcraft:turbine_rotor_stator", "textures": { "texture": "nuclearcraft:blocks/stator_$blockName" } }, "variants": { "inventory": [{}], "dir": { "invisible": { "model": "nuclearcraft:block_invisible" }, "x": {"x": 90, "y": 90}, "y": {}, "z": {"x": 90} } } } """ } class RTG : Block() { override fun getFileName(blockName: String) = "rtg_$blockName.json" override fun getJsonContents(blockName: String) = """{ "forge_marker": 1, "defaults": { "model": "cube_column", "textures": { "end": "nuclearcraft:blocks/rtg_${blockName}_top", "side": "nuclearcraft:blocks/rtg_${blockName}_side" } }, "variants": { "inventory": [{}], "normal": [{}] } } """ } class Battery : Block() { override fun getFileName(blockName: String) = "battery_$blockName.json" override fun getJsonContents(blockName: String) = """{ "forge_marker": 1, "defaults": { "textures": { "particle": "nuclearcraft:blocks/battery_${blockName}_side_in", "north": "nuclearcraft:blocks/battery_${blockName}_side_in", "east": "nuclearcraft:blocks/battery_${blockName}_side_in", "south": "nuclearcraft:blocks/battery_${blockName}_side_in", "west": "nuclearcraft:blocks/battery_${blockName}_side_in", "up": "nuclearcraft:blocks/battery_${blockName}_top_in", "down": "nuclearcraft:blocks/battery_${blockName}_top_in" }, "model": "cube", "transform": "forge:default-block" }, "variants": { "inventory": [{}], "north": { "in": {}, "out": { "textures": { "north": "nuclearcraft:blocks/battery_${blockName}_side_out" } }, "non": { "textures": { "north": "nuclearcraft:blocks/battery_${blockName}_side_non" } } }, "east": { "in": {}, "out": { "textures": { "east": "nuclearcraft:blocks/battery_${blockName}_side_out" } }, "non": { "textures": { "east": "nuclearcraft:blocks/battery_${blockName}_side_non" } } }, "south": { "in": {}, "out": { "textures": { "south": "nuclearcraft:blocks/battery_${blockName}_side_out" } }, "non": { "textures": { "south": "nuclearcraft:blocks/battery_${blockName}_side_non" } } }, "west": { "in": {}, "out": { "textures": { "west": "nuclearcraft:blocks/battery_${blockName}_side_out" } }, "non": { "textures": { "west": "nuclearcraft:blocks/battery_${blockName}_side_non" } } }, "up": { "in": {}, "out": { "textures": { "up": "nuclearcraft:blocks/battery_${blockName}_top_out" } }, "non": { "textures": { "up": "nuclearcraft:blocks/battery_${blockName}_top_non" } } }, "down": { "in": {}, "out": { "textures": { "down": "nuclearcraft:blocks/battery_${blockName}_top_out" } }, "non": { "textures": { "down": "nuclearcraft:blocks/battery_${blockName}_top_non" } } } } } """ } class RFCavity : Block() { override fun getFileName(blockName: String) = "accelerator_rf_cavity_$blockName.json" override fun getJsonContents(blockName: String) = """{ "forge_marker": 1, "defaults": { "model": "cube_all", "textures": { "all": "nuclearcraft:blocks/rf_cavity_$blockName" } }, "variants": { "inventory": [{}], "normal": [{}] } } """ } class Machine : Block() { override fun getFileName(blockName: String) = "$blockName.json" override fun getJsonContents(blockName: String) = """{ "forge_marker": 1, "defaults": { "model": "nuclearcraft:machine", "textures": { "top": "nuclearcraft:blocks/${blockName}_top", "bottom": "nuclearcraft:blocks/${blockName}_side", "front": "nuclearcraft:blocks/${blockName}_front_off", "side": "nuclearcraft:blocks/${blockName}_side", "back": "nuclearcraft:blocks/${blockName}_side" } }, "variants": { "inventory": [{}], "active": { "false": {}, "true": { "textures": { "front": "nuclearcraft:blocks/${blockName}_front_on" } } }, "facing": { "north": {}, "east": {"y": 90}, "south": {"y": 180}, "west": {"y": 270} } } } """ } class Processor : Block() { override fun getFileName(blockName: String) = "$blockName.json" override fun getJsonContents(blockName: String) = """{ "forge_marker": 1, "defaults": { "model": "nuclearcraft:processor", "textures": { "front": "nuclearcraft:blocks/${blockName}_front_off" } }, "variants": { "inventory": [{}], "active": { "false": {}, "true": { "textures": { "front": "nuclearcraft:blocks/${blockName}_front_on" } } }, "facing": { "north": {}, "east": {"y": 90}, "south": {"y": 180}, "west": {"y": 270} } } } """ } class Magnet : Block() { override fun getFileName(blockName: String) = "accelerator_magnet_$blockName.json" override fun getJsonContents(blockName: String) = """{ "forge_marker": 1, "defaults": { "model": "cube_all", "textures": { "all": "nuclearcraft:blocks/magnet_$blockName" } }, "variants": { "inventory": [{}], "normal": [{}] } } """ } class Detector : Block() { override fun getFileName(blockName: String) = "particle_chamber_detector_$blockName.json" override fun getJsonContents(blockName: String) = """{ "forge_marker": 1, "defaults": { "model": "cube_all", "textures": { "all": "nuclearcraft:blocks/detector_$blockName" } }, "variants": { "inventory": [{}], "normal": [{}] } } """ } class ChamberHeater : Block() { override fun getFileName(blockName: String) = "vacuum_chamber_heater_$blockName.json" override fun getJsonContents(blockName: String) = """{ "forge_marker": 1, "defaults": { "model": "cube_all", "textures": { "all": "nuclearcraft:blocks/chamber_heater_$blockName" } }, "variants": { "inventory": [{}], "normal": [{}] } } """ }
0
Kotlin
0
0
7ca3671d6cd5ccf575d4db92af4617af5b402412
10,050
SABJG
MIT License
network/src/main/java/com/quxianggif/network/model/DownloadListener.kt
guolindev
167,902,491
false
null
/* * Copyright (C) guolin, Suzhou Quxiang Inc. Open source codes for study only. * Do not use for commercial purpose. * * 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.quxianggif.network.model /** * 网络下载的回调接口 * * @author guolin * @since 17/3/1 */ interface DownloadListener { /** * 当下载进度变化时回调此方法 * @param percent 已下载的百分值 */ fun onProgress(percent: Int) /** * 当下载完成时会回调此方法 */ fun onCompleted(filePath: String) /** * 当下载失败时会回调此方法。 * * @param errorMsg 错误信息 * @param tr 异常对象 */ fun onFailure(errorMsg: String, tr: Throwable) }
30
null
692
3,448
26227595483a8f2508f23d947b3fe99721346e0f
1,141
giffun
Apache License 2.0
feature-wallet-api/src/main/java/jp/co/soramitsu/wallet/impl/domain/CurrentAccountAddressUseCase.kt
soramitsu
278,060,397
false
null
package jp.co.soramitsu.wallet.impl.domain import jp.co.soramitsu.account.api.domain.interfaces.AccountRepository import jp.co.soramitsu.account.api.domain.model.address import jp.co.soramitsu.runtime.multiNetwork.ChainRegistry import jp.co.soramitsu.runtime.multiNetwork.chain.model.ChainId class CurrentAccountAddressUseCase(private val accountRepository: AccountRepository, private val chainRegistry: ChainRegistry) { suspend operator fun invoke(chainId: ChainId): String? { val account = accountRepository.getSelectedMetaAccount() val chain = chainRegistry.getChain(chainId) return account.address(chain) } }
15
null
30
89
812c6ed5465d19a0616865cbba3e946d046720a1
647
fearless-Android
Apache License 2.0
jcplayer/src/main/java/com/example/jean/jcplayer/service/JcPlayerService.kt
jeancsanchez
64,754,344
false
{"XML": 33, "Gradle": 4, "Java Properties": 2, "Shell": 1, "Text": 1, "Ignore List": 2, "Batchfile": 1, "Markdown": 2, "Proguard": 2, "Java": 14, "Kotlin": 12, "YAML": 1}
package com.example.jean.jcplayer.service import android.app.Service import android.content.Intent import android.content.res.AssetFileDescriptor import android.media.MediaPlayer import android.net.Uri import android.os.Binder import android.os.IBinder import com.example.jean.jcplayer.general.JcStatus import com.example.jean.jcplayer.general.Origin import com.example.jean.jcplayer.general.errors.AudioAssetsInvalidException import com.example.jean.jcplayer.general.errors.AudioFilePathInvalidException import com.example.jean.jcplayer.general.errors.AudioRawInvalidException import com.example.jean.jcplayer.general.errors.AudioUrlInvalidException import com.example.jean.jcplayer.model.JcAudio import java.io.File import java.io.IOException import java.util.concurrent.TimeUnit /** * This class is an Android [Service] that handles all player changes on background. * @author <NAME> (Github: @jeancsanchez) * @date 02/07/16. * Jesus loves you. */ class JcPlayerService : Service(), MediaPlayer.OnPreparedListener, MediaPlayer.OnCompletionListener, MediaPlayer.OnBufferingUpdateListener, MediaPlayer.OnErrorListener { private val binder = JcPlayerServiceBinder() private var mediaPlayer: MediaPlayer? = null var isPlaying: Boolean = false private set var isPaused: Boolean = true private set var currentAudio: JcAudio? = null private set private val jcStatus = JcStatus() private var assetFileDescriptor: AssetFileDescriptor? = null // For Asset and Raw file. var serviceListener: JcPlayerServiceListener? = null inner class JcPlayerServiceBinder : Binder() { val service: JcPlayerService get() = this@JcPlayerService } override fun onBind(intent: Intent): IBinder = binder fun play(jcAudio: JcAudio): JcStatus { val tempJcAudio = currentAudio currentAudio = jcAudio var status = JcStatus() if (isAudioFileValid(jcAudio.path, jcAudio.origin)) { try { mediaPlayer?.let { if (isPlaying) { stop() play(jcAudio) } else { if (tempJcAudio !== jcAudio) { stop() play(jcAudio) } else { status = updateStatus(jcAudio, JcStatus.PlayState.CONTINUE) updateTime() serviceListener?.onContinueListener(status) } } } ?: let { mediaPlayer = MediaPlayer().also { when (jcAudio.origin) { Origin.URL -> it.setDataSource(jcAudio.path) Origin.RAW -> assetFileDescriptor = applicationContext.resources.openRawResourceFd( Integer.parseInt(jcAudio.path) ).also { descriptor -> it.setDataSource( descriptor.fileDescriptor, descriptor.startOffset, descriptor.length ) descriptor.close() assetFileDescriptor = null } Origin.ASSETS -> { assetFileDescriptor = applicationContext.assets.openFd(jcAudio.path) .also { descriptor -> it.setDataSource( descriptor.fileDescriptor, descriptor.startOffset, descriptor.length ) descriptor.close() assetFileDescriptor = null } } Origin.FILE_PATH -> it.setDataSource(applicationContext, Uri.parse(jcAudio.path)) } it.prepareAsync() it.setOnPreparedListener(this) it.setOnBufferingUpdateListener(this) it.setOnCompletionListener(this) it.setOnErrorListener(this) status = updateStatus(jcAudio, JcStatus.PlayState.PREPARING) } } } catch (e: IOException) { e.printStackTrace() } } else { throwError(jcAudio.path, jcAudio.origin) } return status } fun pause(jcAudio: JcAudio): JcStatus { val status = updateStatus(jcAudio, JcStatus.PlayState.PAUSE) serviceListener?.onPausedListener(status) return status } fun stop(): JcStatus { val status = updateStatus(status = JcStatus.PlayState.STOP) serviceListener?.onStoppedListener(status) return status } fun seekTo(time: Int) { mediaPlayer?.seekTo(time) } override fun onBufferingUpdate(mediaPlayer: MediaPlayer, i: Int) {} override fun onCompletion(mediaPlayer: MediaPlayer) { serviceListener?.onCompletedListener() } override fun onError(mediaPlayer: MediaPlayer, i: Int, i1: Int): Boolean { return false } override fun onPrepared(mediaPlayer: MediaPlayer) { this.mediaPlayer = mediaPlayer val status = updateStatus(currentAudio, JcStatus.PlayState.PLAY) updateTime() serviceListener?.onPreparedListener(status) } private fun updateStatus(jcAudio: JcAudio? = null, status: JcStatus.PlayState): JcStatus { currentAudio = jcAudio jcStatus.jcAudio = jcAudio jcStatus.playState = status mediaPlayer?.let { jcStatus.duration = it.duration.toLong() jcStatus.currentPosition = it.currentPosition.toLong() } when (status) { JcStatus.PlayState.PLAY -> { try { mediaPlayer?.start() isPlaying = true isPaused = false } catch (exception: Exception) { serviceListener?.onError(exception) } } JcStatus.PlayState.STOP -> { mediaPlayer?.let { it.stop() it.reset() it.release() mediaPlayer = null } isPlaying = false isPaused = true } JcStatus.PlayState.PAUSE -> { mediaPlayer?.pause() isPlaying = false isPaused = true } JcStatus.PlayState.PREPARING -> { isPlaying = false isPaused = true } JcStatus.PlayState.PLAYING -> { isPlaying = true isPaused = false } else -> { // CONTINUE case mediaPlayer?.start() isPlaying = true isPaused = false } } return jcStatus } private fun updateTime() { object : Thread() { override fun run() { while (isPlaying) { try { val status = updateStatus(currentAudio, JcStatus.PlayState.PLAYING) serviceListener?.onTimeChangedListener(status) sleep(TimeUnit.SECONDS.toMillis(1)) } catch (e: IllegalStateException) { e.printStackTrace() } catch (e: InterruptedException) { e.printStackTrace() } catch (e: NullPointerException) { e.printStackTrace() } } } }.start() } private fun isAudioFileValid(path: String, origin: Origin): Boolean { when (origin) { Origin.URL -> return path.startsWith("http") || path.startsWith("https") Origin.RAW -> { assetFileDescriptor = null assetFileDescriptor = applicationContext.resources.openRawResourceFd(Integer.parseInt(path)) return assetFileDescriptor != null } Origin.ASSETS -> return try { assetFileDescriptor = null assetFileDescriptor = applicationContext.assets.openFd(path) assetFileDescriptor != null } catch (e: IOException) { e.printStackTrace() //TODO: need to give user more readable error. false } Origin.FILE_PATH -> { val file = File(path) //TODO: find an alternative to checking if file is exist, this code is slower on average. //read more: http://stackoverflow.com/a/8868140 return file.exists() } else -> // We should never arrive here. return false // We don't know what the origin of the Audio File } } private fun throwError(path: String, origin: Origin) { when (origin) { Origin.URL -> throw AudioUrlInvalidException(path) Origin.RAW -> try { throw AudioRawInvalidException(path) } catch (e: AudioRawInvalidException) { e.printStackTrace() } Origin.ASSETS -> try { throw AudioAssetsInvalidException(path) } catch (e: AudioAssetsInvalidException) { e.printStackTrace() } Origin.FILE_PATH -> try { throw AudioFilePathInvalidException(path) } catch (e: AudioFilePathInvalidException) { e.printStackTrace() } } } fun getMediaPlayer(): MediaPlayer? { return mediaPlayer } fun finalize() { onDestroy() stopSelf() } }
37
Kotlin
110
267
a0a2cadf9c07d76f0ac9818d1b889f3915acc8db
10,585
JcPlayer
Apache License 2.0
app/src/main/java/com/example/ardin/numberfactapp/api/ApiBuilder.kt
muhtarudinsiregar
121,367,142
false
null
package com.example.ardin.numberfactapp.api import retrofit2.Retrofit import retrofit2.converter.gson.GsonConverterFactory class ApiBuilder { companion object { val BASE_URL = "http://numbersapi.com" } fun call(): NumberFactService { val retrofit = Retrofit.Builder() .baseUrl(BASE_URL) .addConverterFactory(GsonConverterFactory.create()) .build() return retrofit.create(NumberFactService::class.java) } }
0
Kotlin
0
0
ba5eee6eb874c788634e7a7573e894a502dfafbe
497
NumberFactApp
MIT License
j2k/tests/testData/ast/arrayInitializerExpression/javaLangFloatArray.kt
hhariri
21,116,939
true
{"Markdown": 19, "XML": 443, "Ant Build System": 23, "Ignore List": 7, "Protocol Buffer": 2, "Java": 3757, "Kotlin": 11162, "Roff": 59, "JAR Manifest": 1, "INI": 7, "Text": 916, "Java Properties": 10, "HTML": 102, "Roff Manpage": 8, "Groovy": 7, "Gradle": 61, "Maven POM": 34, "CSS": 10, "JavaScript": 42, "JFlex": 3, "Batchfile": 7, "Shell": 7}
val a = array<java.lang.Float>(1.0, 2.0, 3.0)
0
Java
0
0
d150bfbce0e2e47d687f39e2fd233ea55b2ccd26
45
kotlin
Apache License 2.0
platform/bootstrap/src/com/intellij/idea/Main.kt
ingokegel
72,937,917
false
null
// Copyright 2000-2023 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. @file:JvmName("Main") @file:Suppress("RAW_RUN_BLOCKING", "JAVA_MODULE_DOES_NOT_EXPORT_PACKAGE") package com.intellij.idea import com.intellij.concurrency.IdeaForkJoinWorkerThreadFactory import com.intellij.diagnostic.StartUpMeasurer import com.intellij.diagnostic.rootTask import com.intellij.diagnostic.runActivity import com.intellij.ide.BootstrapBundle import com.intellij.ide.BytecodeTransformer import com.intellij.ide.plugins.StartupAbortedException import com.intellij.ide.startup.StartupActionScriptManager import com.intellij.openapi.application.ApplicationNamesInfo import com.intellij.openapi.application.PathManager import com.intellij.openapi.application.impl.ApplicationInfoImpl import com.intellij.platform.impl.toolkit.IdeFontManager import com.intellij.platform.impl.toolkit.IdeGraphicsEnvironment import com.intellij.platform.impl.toolkit.IdeToolkit import com.intellij.util.lang.PathClassLoader import com.intellij.util.lang.UrlClassLoader import com.jetbrains.JBR import kotlinx.coroutines.* import sun.font.FontManagerFactory import java.awt.GraphicsEnvironment import java.awt.Toolkit import java.io.IOException import java.lang.invoke.MethodHandles import java.lang.invoke.MethodType import java.nio.file.Files import java.nio.file.Path import java.util.* import kotlin.coroutines.AbstractCoroutineContextElement import kotlin.coroutines.CoroutineContext import kotlin.system.exitProcess private const val MARKETPLACE_BOOTSTRAP_JAR = "marketplace-bootstrap.jar" fun main(rawArgs: Array<String>) { val startupTimings = ArrayList<Any>(12) addBootstrapTiming("startup begin", startupTimings) val args = preprocessArgs(rawArgs) AppMode.setFlags(args) try { bootstrap(startupTimings) addBootstrapTiming("main scope creating", startupTimings) runBlocking { StartUpMeasurer.addTimings(startupTimings, "bootstrap") val appInitPreparationActivity = StartUpMeasurer.startActivity("app initialization preparation") val initScopeActivity = StartUpMeasurer.startActivity("init scope creating") val busyThread = Thread.currentThread() withContext(Dispatchers.Default + StartupAbortedExceptionHandler() + rootTask()) { initScopeActivity.end() // not IO-, but CPU-bound due to descrambling, don't use here IO dispatcher val appStarterDeferred = async(CoroutineName("main class loading")) { val aClass = AppStarter::class.java.classLoader.loadClass("com.intellij.idea.MainImpl") MethodHandles.lookup().findConstructor(aClass, MethodType.methodType(Void.TYPE)).invoke() as AppStarter } launch(CoroutineName("ForkJoin CommonPool configuration")) { IdeaForkJoinWorkerThreadFactory.setupForkJoinCommonPool(AppMode.isHeadless()) } initRemoteDevIfNeeded(args) StartUpMeasurer.appInitPreparationActivity = appInitPreparationActivity startApplication(args = args, appStarterDeferred = appStarterDeferred, mainScope = this@runBlocking, busyThread = busyThread) } awaitCancellation() } } catch (e: Throwable) { StartupErrorReporter.showMessage(BootstrapBundle.message("bootstrap.error.title.start.failed"), e) exitProcess(AppExitCodes.STARTUP_EXCEPTION) } } private fun initRemoteDevIfNeeded(args: List<String>) { val command = args.firstOrNull() val isRemoteDevEnabled = AppMode.CWM_HOST_COMMAND == command || AppMode.CWM_HOST_NO_LOBBY_COMMAND == command || AppMode.REMOTE_DEV_HOST_COMMAND == command if (!isRemoteDevEnabled) { return } if (!JBR.isGraphicsUtilsSupported()) { error("JBR version 17.0.6b796 or later is required to run a remote-dev server with lux") } runActivity("cwm host init") { initRemoteDevGraphicsEnvironment() if (isLuxEnabled()) { initLux() } else { initProjector() } } } private fun isLuxEnabled() = System.getProperty("lux.enabled", "true").toBoolean() private fun initProjector() { val projectorMainClass = AppStarter::class.java.classLoader.loadClass("org.jetbrains.projector.server.ProjectorLauncher\$Starter") MethodHandles.privateLookupIn(projectorMainClass, MethodHandles.lookup()).findStatic( projectorMainClass, "runProjectorServer", MethodType.methodType(Boolean::class.javaPrimitiveType) ).invoke() } private fun initRemoteDevGraphicsEnvironment() { JBR.getProjectorUtils().setLocalGraphicsEnvironmentProvider { if (isLuxEnabled()) { IdeGraphicsEnvironment.instance } else { AppStarter::class.java.classLoader.loadClass("org.jetbrains.projector.awt.image.PGraphicsEnvironment") .getDeclaredMethod("getInstance") .invoke(null) as GraphicsEnvironment } } } private fun setStaticField(clazz: Class<out Any>, fieldName: String, value: Any) { val lookup = MethodHandles.lookup() val field = clazz.getDeclaredField(fieldName) field.isAccessible = true val handle = lookup.unreflectSetter(field) handle.invoke(value) } private fun initLux() { if (!isLuxEnabled()) { return } System.setProperty("java.awt.headless", false.toString()) System.setProperty("swing.volatileImageBufferEnabled", false.toString()) System.setProperty("keymap.current.os.only", false.toString()) System.setProperty("awt.nativeDoubleBuffering", false.toString()) System.setProperty("swing.bufferPerWindow", true.toString()) setStaticField(Toolkit::class.java, "toolkit", IdeToolkit()) System.setProperty("awt.toolkit", IdeToolkit::class.java.canonicalName) setStaticField(FontManagerFactory::class.java, "instance", IdeFontManager()) @Suppress("SpellCheckingInspection") System.setProperty("sun.font.fontmanager", IdeFontManager::class.java.canonicalName) } private fun bootstrap(startupTimings: MutableList<Any>) { addBootstrapTiming("properties loading", startupTimings) PathManager.loadProperties() addBootstrapTiming("plugin updates install", startupTimings) // this check must be performed before system directories are locked if (!AppMode.isCommandLine() || java.lang.Boolean.getBoolean(AppMode.FORCE_PLUGIN_UPDATES)) { val configImportNeeded = !AppMode.isHeadless() && !Files.exists(Path.of(PathManager.getConfigPath())) if (!configImportNeeded) { // Consider following steps: // - user opens settings, and installs some plugins; // - the plugins are downloaded and saved somewhere; // - IDE prompts for restart; // - after restart, the plugins are moved to proper directories ("installed") by the next line. // TODO get rid of this: plugins should be installed before restarting the IDE installPluginUpdates() } } addBootstrapTiming("classloader init", startupTimings) initClassLoader(AppMode.isRemoteDevHost() && !isLuxEnabled()) } fun initClassLoader(addCwmLibs: Boolean) { val distDir = Path.of(PathManager.getHomePath()) val classLoader = AppMode::class.java.classLoader as? PathClassLoader ?: throw RuntimeException("You must run JVM with -Djava.system.class.loader=com.intellij.util.lang.PathClassLoader") val preinstalledPluginDir = distDir.resolve("plugins") var pluginDir = preinstalledPluginDir var marketPlaceBootDir = BootstrapClassLoaderUtil.findMarketplaceBootDir(pluginDir) var mpBoot = marketPlaceBootDir.resolve(MARKETPLACE_BOOTSTRAP_JAR) // enough to check for existence as preinstalled plugin is always compatible var installMarketplace = Files.exists(mpBoot) if (!installMarketplace) { pluginDir = Path.of(PathManager.getPluginsPath()) marketPlaceBootDir = BootstrapClassLoaderUtil.findMarketplaceBootDir(pluginDir) mpBoot = marketPlaceBootDir.resolve(MARKETPLACE_BOOTSTRAP_JAR) installMarketplace = BootstrapClassLoaderUtil.isMarketplacePluginCompatible(distDir, pluginDir, mpBoot) } val classpath = LinkedHashSet<Path>() if (installMarketplace) { val marketplaceImpl = marketPlaceBootDir.resolve("marketplace-impl.jar") if (Files.exists(marketplaceImpl)) { classpath.add(marketplaceImpl) } else { installMarketplace = false } } var updateSystemClassLoader = false if (addCwmLibs) { // Remote dev requires Projector libraries in system classloader due to AWT internals (see below) // At the same time, we don't want to ship them with base (non-remote) IDE due to possible unwanted interference with plugins // See also: com.jetbrains.codeWithMe.projector.PluginClassPathRuntimeCustomizer val relativeLibPath = "cwm-plugin-projector/lib/projector" var remoteDevPluginLibs = preinstalledPluginDir.resolve(relativeLibPath) var exists = Files.exists(remoteDevPluginLibs) if (!exists) { remoteDevPluginLibs = Path.of(PathManager.getPluginsPath(), relativeLibPath) exists = Files.exists(remoteDevPluginLibs) } if (exists) { Files.newDirectoryStream(remoteDevPluginLibs).use { dirStream -> // add all files in that dir except for plugin jar for (f in dirStream) { if (f.toString().endsWith(".jar")) { classpath.add(f) } } } } // AWT can only use builtin and system class loaders to load classes, // so set the system loader to something that can find projector libs updateSystemClassLoader = true } if (!classpath.isEmpty()) { classLoader.classPath.addFiles(classpath) } if (installMarketplace) { try { val spiLoader = PathClassLoader(UrlClassLoader.build().files(listOf(mpBoot)).parent(classLoader)) val transformers = ServiceLoader.load(BytecodeTransformer::class.java, spiLoader).iterator() if (transformers.hasNext()) { classLoader.setTransformer(BytecodeTransformerAdapter(transformers.next())) } } catch (e: Throwable) { // at this point, logging is not initialized yet, so reporting the error directly val path = pluginDir.resolve(BootstrapClassLoaderUtil.MARKETPLACE_PLUGIN_DIR).toString() val message = "As a workaround, you may uninstall or update JetBrains Marketplace Support plugin at $path" StartupErrorReporter.showMessage(BootstrapBundle.message("bootstrap.error.title.jetbrains.marketplace.boot.failure"), Exception(message, e)) } } if (updateSystemClassLoader) { val aClass = ClassLoader::class.java MethodHandles.privateLookupIn(aClass, MethodHandles.lookup()).findStaticSetter(aClass, "scl", aClass).invoke(classLoader) } } private fun addBootstrapTiming(name: String, startupTimings: MutableList<Any>) { startupTimings.add(name) startupTimings.add(System.nanoTime()) } private fun preprocessArgs(args: Array<String>): List<String> { if (args.isEmpty()) { return Collections.emptyList() } // a buggy DE may fail to strip an unused parameter from a .desktop file if (args.size == 1 && args[0] == "%f") { return Collections.emptyList() } @Suppress("SuspiciousPackagePrivateAccess") if (AppMode.HELP_OPTION in args) { println(""" Some of the common commands and options (sorry, the full list is not yet supported): --help prints a short list of commands and options --version shows version information /project/dir opens a project from the given directory [/project/dir|--temp-project] [--wait] [--line <line>] [--column <column>] file opens the file, either in a context of the given project or as a temporary single-file project, optionally waiting until the editor tab is closed diff <left> <right> opens a diff window between <left> and <right> files/directories merge <local> <remote> [base] <merged> opens a merge window between <local> and <remote> files (with optional common <base>), saving the result to <merged> """.trimIndent()) exitProcess(0) } @Suppress("SuspiciousPackagePrivateAccess") if (AppMode.VERSION_OPTION in args) { val appInfo = ApplicationInfoImpl.getShadowInstance() val edition = ApplicationNamesInfo.getInstance().editionName?.let { " (${it})" } ?: "" println("${appInfo.fullApplicationName}${edition}\nBuild #${appInfo.build.asString()}") exitProcess(0) } val (propertyArgs, otherArgs) = args.partition { it.startsWith("-D") && it.contains('=') } propertyArgs.forEach { arg -> val (option, value) = arg.removePrefix("-D").split('=', limit = 2) System.setProperty(option, value) } return otherArgs } @Suppress("HardCodedStringLiteral") private fun installPluginUpdates() { try { // referencing `StartupActionScriptManager` is OK - a string constant will be inlined val scriptFile = Path.of(PathManager.getPluginTempPath(), StartupActionScriptManager.ACTION_SCRIPT_FILE) if (Files.isRegularFile(scriptFile)) { // load StartupActionScriptManager and all other related class (ObjectInputStream and so on loaded as part of class define) // only if there is an action script to execute StartupActionScriptManager.executeActionScript() } } catch (e: IOException) { StartupErrorReporter.showMessage( "Plugin Installation Error", """ The IDE failed to install or update some plugins. Please try again, and if the problem persists, please report it to https://jb.gg/ide/critical-startup-errors The cause: $e """.trimIndent(), false ) } } // separate class for nicer presentation in dumps private class StartupAbortedExceptionHandler : AbstractCoroutineContextElement(CoroutineExceptionHandler), CoroutineExceptionHandler { override fun handleException(context: CoroutineContext, exception: Throwable) { StartupAbortedException.processException(exception) } override fun toString() = "StartupAbortedExceptionHandler" } private class BytecodeTransformerAdapter(private val impl: BytecodeTransformer) : PathClassLoader.BytecodeTransformer { override fun isApplicable(className: String, loader: ClassLoader): Boolean { return impl.isApplicable(className, loader, null) } override fun transform(loader: ClassLoader, className: String, classBytes: ByteArray): ByteArray { return impl.transform(loader, className, null, classBytes) } }
233
null
4931
2
b07eabd319ad5b591373d63c8f502761c2b2dfe8
14,429
intellij-community
Apache License 2.0
app/src/main/java/com/eyepetizer/android/ui/common/ui/vassonic/SonicJavaScriptInterface.kt
VIPyinzhiwei
259,029,682
false
null
/* * Copyright (C) 2017 THL A29 Limited, a Tencent company. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * 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.example.eyedemo.ui.common.ui.vassonic import android.content.Intent import android.os.Handler import android.os.Looper import android.webkit.JavascriptInterface import org.json.JSONObject /** * Sonic javaScript Interface (Android API Level >= 17) */ class SonicJavaScriptInterface(private val sessionClient: SonicSessionClientImpl?, private val intent: Intent) { // the callback function of demo page is hardcode as 'getDiffDataCallback' @get:JavascriptInterface val diffData: Unit get() { // the callback function of demo page is hardcode as 'getDiffDataCallback' getDiffData2("getDiffDataCallback") } @JavascriptInterface fun getDiffData2(jsCallbackFunc: String) { sessionClient?.getDiffData { resultData -> val callbackRunnable = Runnable { val jsCode = "javascript:" + jsCallbackFunc + "('" + toJsString(resultData) + "')" sessionClient.webView?.loadUrl(jsCode) } if (Looper.getMainLooper() == Looper.myLooper()) { callbackRunnable.run() } else { Handler(Looper.getMainLooper()).post(callbackRunnable) } } } @get:JavascriptInterface val performance: String get() { val clickTime = intent.getLongExtra(PARAM_CLICK_TIME, -1) val loadUrlTime = intent.getLongExtra(PARAM_LOAD_URL_TIME, -1) try { val result = JSONObject() result.put(PARAM_CLICK_TIME, clickTime) result.put(PARAM_LOAD_URL_TIME, loadUrlTime) return result.toString() } catch (e: Exception) { } return "" } companion object { const val PARAM_CLICK_TIME = "clickTime" const val PARAM_LOAD_URL_TIME = "loadUrlTime" /** * From RFC 4627, "All Unicode characters may be placed within the quotation marks except * for the characters that must be escaped: quotation mark, * reverse solidus, and the control characters (U+0000 through U+001F)." */ private fun toJsString(value: String?): String { if (value == null) { return "null" } val out = StringBuilder(1024) var i = 0 val length = value.length while (i < length) { val c = value[i] when (c) { '"', '\\', '/' -> out.append('\\').append(c) '\t' -> out.append("\\t") '\b' -> out.append("\\b") '\n' -> out.append("\\n") '\r' -> out.append("\\r") '\u000C' -> out.append("\\f") //Kotlin 转义字符 - 换页符 "\f" 提示错误 Illegal escape: '\f' 解决方案:https://www.jianshu.com/p/a59a24f76c4b,使用 Kotlin "\u000C",使用 Java "\f" else -> if (c.toInt() <= 0x1F) { out.append(String.format("\\u%04x", c.toInt())) } else { out.append(c) } } i++ } return out.toString() } } }
3
null
404
1,759
bc2feccace17deac2917ae26728915030ed6ed22
3,873
Eyepetizer
Apache License 2.0
shared/src/commonMain/kotlin/com/luizmatias/todoapp/data/repositories/AccountRepositoryImpl.kt
luiz-matias
437,346,131
false
null
package com.luizmatias.todoapp.data.repositories import com.luizmatias.todoapp.data.remote.ApiConstants import com.luizmatias.todoapp.data.remote.models.PasswordRequest import com.luizmatias.todoapp.domain.entities.User import com.luizmatias.todoapp.domain.repositories.AccountRepository import io.ktor.client.* import io.ktor.client.request.* class AccountRepositoryImpl(private val httpClient: HttpClient) : AccountRepository { override suspend fun getProfile(): User { return httpClient.get(ApiConstants.BASEURL + "/account") } override suspend fun editProfile(newUser: User) { return httpClient.put(ApiConstants.BASEURL + "/account") { body = newUser } } override suspend fun logout() { httpClient.post<String>(ApiConstants.BASEURL + "/account/logout") } override suspend fun changePassword(newPassword: String) { httpClient.post<String>(ApiConstants.BASEURL + "/account/changepassword") { body = PasswordRequest(newPassword) } } }
0
Kotlin
0
2
c5cf39a3f2abc03fc1ca9b4bd650ddb3044f6196
1,046
todolist-kmm
MIT License
app/src/main/java/tech/muso/demo/architecture/ui/stocks/StockDataBindingAdapters.kt
musotec
262,890,579
false
null
package tech.muso.demo.architecture.ui.stocks import android.widget.ImageView import androidx.databinding.BindingAdapter import com.bumptech.glide.Glide import com.bumptech.glide.load.resource.drawable.DrawableTransitionOptions import tech.muso.demo.common.entity.Profile /** * Create a custom DataBinding adapter so that we can hide the image loading logic of Glide. * * The [Profile] object only contains the image url for the stock, but could potentially handle * bindings for a more complex object (logo + background, graph, etc.) */ @BindingAdapter("stockProfile") fun bindImageFromUrl(view: ImageView, stockProfile: Profile) { val imageUrl: String? = stockProfile.logoUrl if (!imageUrl.isNullOrEmpty()) { Glide.with(view.context) .load(imageUrl) .transition(DrawableTransitionOptions.withCrossFade()) .into(view) } }
0
Kotlin
0
0
a8c481a742ab5b36d2ac922840bbbdfdd1f27a82
885
archdemo-finance
MIT License
libBase/src/main/java/com/effective/android/base/tips/keeplive/KeepLiveService.kt
YummyLau
118,240,800
false
null
package com.effective.android.base.tips.keeplive import android.app.Notification import android.app.Service import android.content.Intent import android.os.Build import android.os.IBinder import android.util.Log /** * 方案二 * 8.0以下尝试用前台服务降低优先级,但是7.0以下notification才不会提示,7.0会在通知栏显示isRunning * 模范tinker实现 * Created by yummyLau on 2018/7/19. * Email: <EMAIL> * blog: yummylau.com */ class KeepLiveService : Service() { companion object { private val TAG = KeepLiveService::class.java.simpleName private val notificationId = 1 } override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int { val result = super.onStartCommand(intent, flags, startId) if (Build.VERSION.SDK_INT >= 26) { Log.i(TAG, "for system version >= Android O, we just ignore increasingPriority " + "job to avoid crash or toasts.") return result } if ("ZUK" == Build.MANUFACTURER) { Log.i(TAG, "for ZUK device, we just ignore increasingPriority " + "job to avoid crash.") return result } Log.i(TAG, "try to increase process priority") try { val notification = Notification() if (Build.VERSION.SDK_INT < 18) { startForeground(notificationId, notification) } else { startForeground(notificationId, notification) startService(Intent(this, InnerService::class.java)) } } catch (e: Throwable) { Log.i(TAG, "try to increase patch process priority error:$e") } return result } override fun onBind(intent: Intent?): IBinder? = null /** * start a service to keep alive! */ class InnerService : Service() { override fun onCreate() { super.onCreate() try { startForeground(notificationId, Notification()) } catch (e: Throwable) { Log.e(TAG, "InnerService set service for push exception:%s.", e) } // kill stopSelf() } override fun onDestroy() { stopForeground(true) super.onDestroy() } override fun onBind(intent: Intent): IBinder? { return null } } }
1
null
32
187
f9bad2216051e5b848b2d862cab7958f1bcdc5e8
2,322
AndroidModularArchiteture
MIT License
app/src/main/java/de/seemoo/at_tracking_detection/notifications/ScheduledNotificationReceiver.kt
seemoo-lab
385,199,222
false
null
package de.seemoo.at_tracking_detection.notifications import android.content.BroadcastReceiver import android.content.Context import android.content.Intent import de.seemoo.at_tracking_detection.ATTrackingDetectionApplication import de.seemoo.at_tracking_detection.util.SharedPrefs import timber.log.Timber class ScheduledNotificationReceiver: BroadcastReceiver() { override fun onReceive(context: Context?, intent: Intent?) { Timber.d("Broadcast received ${intent?.action}") val notificationService = ATTrackingDetectionApplication.getCurrentApp()?.notificationService SharedPrefs.dismissSurveyInformation = false notificationService?.sendSurveyInfoNotification() } }
28
null
99
1,877
597ee7a4ae8b1a96d7a1a147fa3320f7316cfad5
711
AirGuard
Apache License 2.0
Edu-Kotlin/testSrc/com/jetbrains/edu/kotlin/hyperskill/KtHyperskillCourseGenerationTest.kt
telezhnaya
264,863,128
true
{"Kotlin": 2477547, "Java": 634238, "HTML": 131915, "CSS": 12844, "Python": 3994, "JavaScript": 315}
package com.jetbrains.edu.kotlin.hyperskill import com.intellij.testFramework.LightPlatformTestCase import com.jetbrains.edu.coursecreator.CCUtils import com.jetbrains.edu.jvm.JdkProjectSettings import com.jetbrains.edu.learning.EduTestCase import com.jetbrains.edu.learning.FileTreeBuilder import com.jetbrains.edu.learning.fileTree import com.jetbrains.edu.learning.stepik.hyperskill.courseFormat.HyperskillCourse import org.jetbrains.kotlin.idea.KotlinLanguage class KtHyperskillCourseGenerationTest : EduTestCase() { fun `test course structure creation`() { courseWithFiles(courseProducer = ::HyperskillCourse, language = KotlinLanguage.INSTANCE, courseMode = CCUtils.COURSE_MODE, settings = JdkProjectSettings.emptySettings()) {} checkFileTree { dir("lesson1/task1") { dir("src") { file("Task.kt") } dir("test") { file("Tests.kt") } file("task.html") } file("build.gradle") file("settings.gradle") } } private fun checkFileTree(block: FileTreeBuilder.() -> Unit) { fileTree(block).assertEquals(LightPlatformTestCase.getSourceRoot(), myFixture) } }
0
null
0
0
9f9492f7505fb86df37c9d582814c075aa3a611d
1,184
educational-plugin
Apache License 2.0
rounded/src/commonMain/kotlin/me/localx/icons/rounded/outline/PhotoVideo.kt
localhostov
808,861,591
false
{"Kotlin": 79430321, "HTML": 331, "CSS": 102}
package me.localx.icons.rounded.outline import androidx.compose.ui.graphics.Color import androidx.compose.ui.graphics.PathFillType.Companion.NonZero import androidx.compose.ui.graphics.SolidColor import androidx.compose.ui.graphics.StrokeCap.Companion.Butt import androidx.compose.ui.graphics.StrokeJoin.Companion.Miter import androidx.compose.ui.graphics.vector.ImageVector import androidx.compose.ui.graphics.vector.ImageVector.Builder import androidx.compose.ui.graphics.vector.path import androidx.compose.ui.unit.dp import me.localx.icons.rounded.Icons public val Icons.Outline.PhotoVideo: ImageVector get() { if (_photoVideo != null) { return _photoVideo!! } _photoVideo = Builder(name = "PhotoVideo", defaultWidth = 512.0.dp, defaultHeight = 512.0.dp, viewportWidth = 24.0f, viewportHeight = 24.0f).apply { path(fill = SolidColor(Color(0xFF000000)), stroke = null, strokeLineWidth = 0.0f, strokeLineCap = Butt, strokeLineJoin = Miter, strokeLineMiter = 4.0f, pathFillType = NonZero) { moveTo(17.0f, 16.0f) curveToRelative(-0.552f, 0.0f, -1.0f, 0.448f, -1.0f, 1.0f) verticalLineToRelative(1.0f) horizontalLineToRelative(-2.0f) verticalLineToRelative(-1.0f) curveToRelative(0.0f, -0.552f, -0.448f, -1.0f, -1.0f, -1.0f) reflectiveCurveToRelative(-1.0f, 0.448f, -1.0f, 1.0f) verticalLineToRelative(5.0f) lineTo(6.0f, 22.0f) lineTo(6.0f, 11.0f) curveToRelative(0.0f, -0.552f, -0.448f, -1.0f, -1.0f, -1.0f) horizontalLineToRelative(-0.5f) curveToRelative(-2.481f, 0.0f, -4.5f, 2.019f, -4.5f, 4.5f) verticalLineToRelative(5.0f) curveToRelative(0.0f, 2.481f, 2.019f, 4.5f, 4.5f, 4.5f) lineTo(13.5f, 24.0f) curveToRelative(2.481f, 0.0f, 4.5f, -2.019f, 4.5f, -4.5f) verticalLineToRelative(-2.5f) curveToRelative(0.0f, -0.552f, -0.448f, -1.0f, -1.0f, -1.0f) close() moveTo(4.0f, 16.0f) verticalLineToRelative(2.0f) lineTo(2.0f, 18.0f) verticalLineToRelative(-2.0f) horizontalLineToRelative(2.0f) close() moveTo(4.0f, 12.05f) verticalLineToRelative(1.95f) horizontalLineToRelative(-1.945f) curveToRelative(0.2f, -0.977f, 0.968f, -1.75f, 1.945f, -1.95f) close() moveTo(2.055f, 20.0f) horizontalLineToRelative(1.945f) verticalLineToRelative(1.95f) curveToRelative(-0.978f, -0.199f, -1.745f, -0.972f, -1.945f, -1.95f) close() moveTo(14.0f, 21.949f) verticalLineToRelative(-1.949f) horizontalLineToRelative(1.949f) curveToRelative(-0.199f, 0.978f, -0.971f, 1.75f, -1.949f, 1.949f) close() moveTo(19.0f, 0.0f) horizontalLineToRelative(-6.0f) curveToRelative(-2.757f, 0.0f, -5.0f, 2.243f, -5.0f, 5.0f) verticalLineToRelative(4.0f) curveToRelative(0.0f, 2.757f, 2.243f, 5.0f, 5.0f, 5.0f) horizontalLineToRelative(6.0f) curveToRelative(2.757f, 0.0f, 5.0f, -2.243f, 5.0f, -5.0f) lineTo(24.0f, 5.0f) curveToRelative(0.0f, -2.757f, -2.243f, -5.0f, -5.0f, -5.0f) close() moveTo(10.0f, 5.0f) curveToRelative(0.0f, -1.654f, 1.346f, -3.0f, 3.0f, -3.0f) horizontalLineToRelative(6.0f) curveToRelative(1.147f, 0.0f, 2.134f, 0.654f, 2.638f, 1.602f) lineToRelative(-3.457f, 3.464f) lineToRelative(-0.475f, -0.48f) curveToRelative(-0.736f, -0.737f, -1.896f, -0.789f, -2.705f, -0.113f) lineToRelative(-4.621f, 3.961f) curveToRelative(-0.235f, -0.428f, -0.381f, -0.911f, -0.381f, -1.433f) lineTo(9.999f, 5.0f) close() moveTo(19.0f, 12.0f) horizontalLineToRelative(-6.0f) curveToRelative(-0.395f, 0.0f, -0.771f, -0.081f, -1.117f, -0.221f) lineToRelative(4.406f, -3.784f) lineToRelative(0.475f, 0.48f) curveToRelative(0.779f, 0.78f, 2.049f, 0.781f, 2.829f, 0.0f) lineToRelative(2.408f, -2.408f) verticalLineToRelative(2.932f) curveToRelative(0.0f, 1.654f, -1.346f, 3.0f, -3.0f, 3.0f) close() moveTo(11.0f, 4.5f) curveToRelative(0.0f, -0.828f, 0.672f, -1.5f, 1.5f, -1.5f) reflectiveCurveToRelative(1.5f, 0.672f, 1.5f, 1.5f) reflectiveCurveToRelative(-0.672f, 1.5f, -1.5f, 1.5f) reflectiveCurveToRelative(-1.5f, -0.672f, -1.5f, -1.5f) close() } } .build() return _photoVideo!! } private var _photoVideo: ImageVector? = null
1
Kotlin
0
5
cbd8b510fca0e5e40e95498834f23ec73cc8f245
5,292
icons
MIT License
app/src/main/java/com/kmmania/runninguserpreferences/user_prefs/UserPrefsDao.kt
dlgiao
399,046,961
false
null
package com.kmmania.runninguserpreferences.user_prefs import androidx.room.* import kotlinx.coroutines.flow.Flow @Dao interface UserPrefsDao { @Insert(onConflict = OnConflictStrategy.REPLACE) suspend fun insert(userPrefs: UserPrefs) @Query("DELETE FROM user_prefs_table") suspend fun deleteAll() @Query("SELECT * FROM user_prefs_table") fun getUserPrefs(): Flow<UserPrefs> }
0
Kotlin
0
0
346e0990218a72a61ab0c1030a213a2056343532
402
running_user_prefs_android
MIT License
idea/tests/test/org/jetbrains/kotlin/idea/script/AbstractScriptConfigurationHighlightingTest.kt
JetBrains
278,369,660
false
null
/* * Copyright 2010-2019 JetBrains s.r.o. and Kotlin Programming Language contributors. * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ package org.jetbrains.kotlin.idea.script import com.intellij.codeInsight.highlighting.HighlightUsagesHandler import com.intellij.testFramework.exceptionCases.AbstractExceptionCase import org.jetbrains.kotlin.idea.core.script.ScriptConfigurationManager import org.jetbrains.kotlin.test.InTextDirectivesUtils import org.junit.ComparisonFailure abstract class AbstractScriptConfigurationHighlightingTest : AbstractScriptConfigurationTest() { fun doTest(path: String) { configureScriptFile(path) // Highlight references at caret HighlightUsagesHandler.invoke(project, editor, myFile) checkHighlighting( editor, InTextDirectivesUtils.isDirectiveDefined(file.text, "// CHECK_WARNINGS"), InTextDirectivesUtils.isDirectiveDefined(file.text, "// CHECK_INFOS") ) } fun doComplexTest(path: String) { configureScriptFile(path) assertException(object : AbstractExceptionCase<ComparisonFailure>() { override fun getExpectedExceptionClass(): Class<ComparisonFailure> = ComparisonFailure::class.java override fun tryClosure() { checkHighlighting(editor, false, false) } }) ScriptConfigurationManager.updateScriptDependenciesSynchronously(myFile) checkHighlighting(editor, false, false) } }
1
null
37
82
cc81d7505bc3e9ad503d706998ae8026c067e838
1,574
intellij-kotlin
Apache License 2.0
compose/ui/ui-test-junit4/src/desktopMain/kotlin/androidx/compose/ui/test/junit4/MainTestClockImpl.desktop.kt
JetBrains
351,708,598
false
null
/* * Copyright 2020 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package androidx.compose.ui.test import kotlinx.coroutines.ExperimentalCoroutinesApi import kotlinx.coroutines.test.TestCoroutineScheduler @OptIn(ExperimentalCoroutinesApi::class) internal class MainTestClockImpl( testScheduler: TestCoroutineScheduler, frameDelayMillis: Long, onTimeAdvanced: (Long) -> Unit ) : AbstractMainTestClock( testScheduler = testScheduler, frameDelayMillis = frameDelayMillis, runOnUiThread = ::runOnUiThread, onTimeAdvanced = onTimeAdvanced )
28
null
937
59
e18ad812b77fc8babb00aacfcea930607b0794b5
1,116
androidx
Apache License 2.0
SourceEditor/app/src/main/java/com/microsoft/device/display/wm_samples/sourceeditor/CodeFragment.kt
conceptdev
648,744,747
false
{"Kotlin": 506269, "HTML": 1512}
/* * * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. * */ package com.microsoft.device.display.wm_samples.sourceeditor import android.content.Context import android.os.Bundle import android.text.Editable import android.text.TextWatcher import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.Button import android.widget.LinearLayout import android.widget.ScrollView import androidx.fragment.app.Fragment import androidx.lifecycle.ViewModelProvider import com.google.android.material.textfield.TextInputEditText import com.microsoft.device.display.wm_samples.sourceeditor.includes.Defines import com.microsoft.device.display.wm_samples.sourceeditor.includes.DragHandler import com.microsoft.device.display.wm_samples.sourceeditor.viewmodel.DualScreenViewModel import com.microsoft.device.display.wm_samples.sourceeditor.viewmodel.ScrollViewModel import com.microsoft.device.display.wm_samples.sourceeditor.viewmodel.WebViewModel import java.io.BufferedReader import java.io.InputStreamReader /* Fragment that defines functionality for source code editor */ class CodeFragment : Fragment() { private lateinit var buttonToolbar: LinearLayout private lateinit var codeLayout: LinearLayout private lateinit var scrollView: ScrollView private lateinit var previewBtn: Button private lateinit var textField: TextInputEditText private lateinit var dualScreenVM: DualScreenViewModel private lateinit var scrollVM: ScrollViewModel private lateinit var webVM: WebViewModel private var scrollingBuffer: Int = Defines.DEFAULT_BUFFER_SIZE private var scrollRange: Int = Defines.DEFAULT_RANGE private var rangeFound: Boolean = false override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View? { val view = inflater.inflate(R.layout.fragment_item_code, container, false) activity?.let { // initialize ViewModels (find existing or create a new one) dualScreenVM = ViewModelProvider(requireActivity()).get(DualScreenViewModel::class.java) scrollVM = ViewModelProvider(requireActivity()).get(ScrollViewModel::class.java) webVM = ViewModelProvider(requireActivity()).get(WebViewModel::class.java) textField = view.findViewById(R.id.textinput_code) scrollView = view.findViewById(R.id.scrollview_code) val isDualScreen = dualScreenVM.getIsDualScreen().value ?: false handleSpannedModeSelection(view, isDualScreen) dualScreenVM.getIsDualScreen().observe( requireActivity(), { bool -> handleSpannedModeSelection(view, bool) } ) if (webVM.getText().value == null) { webVM.setText(readFile(Defines.DEFAULT_SOURCE_PATH, context)) } webVM.getText().observe( requireActivity(), { str -> if (str != textField.text.toString()) { textField.setText(str) } } ) textField.setText(webVM.getText().value) setOnChangeListenerForTextInput(textField) } return view } // read from a base file in the assets folder private fun readFile(file: String, context: Context?): String { return BufferedReader(InputStreamReader(context?.assets?.open(file))).useLines { lines -> val results = StringBuilder() lines.forEach { results.append(it + System.getProperty("line.separator")) } results.toString() } } // mirror scrolling logic private fun handleScrolling(observing: Boolean, int: Int) { if (!rangeFound) { calibrateScrollView() } else { if (observing) { autoScroll(int) } else { updateScrollValues(int, Defines.CODE_KEY) } } } // single screen vs. dual screen logic private fun handleSpannedModeSelection(view: View, isDualMode: Boolean) { activity?.let { codeLayout = view.findViewById(R.id.code_layout) previewBtn = view.findViewById(R.id.btn_switch_to_preview) buttonToolbar = view.findViewById(R.id.button_toolbar) if (isDualMode) { initializeDualScreen() } else { initializeSingleScreen() } } } // spanned selection helper private fun initializeSingleScreen() { buttonToolbar.visibility = View.VISIBLE initializeDragListener() previewBtn.setOnClickListener { startPreviewFragment() } } // spanned selection helper private fun initializeDualScreen() { buttonToolbar.visibility = View.GONE scrollingBuffer = Defines.DEFAULT_BUFFER_SIZE scrollRange = Defines.DEFAULT_RANGE rangeFound = false // set event and data listeners scrollView.setOnScrollChangeListener { _, _, scrollY, _, _ -> handleScrolling(false, scrollY) } scrollVM.getScroll().observe( requireActivity(), { state -> if (state.scrollKey != Defines.CODE_KEY) { handleScrolling(true, state.scrollPercentage) } } ) } // method that triggers transition to preview fragment private fun startPreviewFragment() { parentFragmentManager.beginTransaction() .replace( R.id.primary_fragment_container, PreviewFragment(), "PreviewFragment" ).addToBackStack("PreviewFragment") .commit() } // listener for changes to text in code editor private fun setOnChangeListenerForTextInput(field: TextInputEditText) { field.addTextChangedListener(object : TextWatcher { override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {} override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) { webVM.setText(s.toString()) } override fun afterTextChanged(s: Editable?) {} }) } // get bounds of scroll window private fun calibrateScrollView() { if (scrollView.scrollY > Defines.MIN_RANGE_THRESHOLD) { scrollRange = scrollView.scrollY // successfully calibrated rangeFound = true } else { scrollView.fullScroll(View.FOCUS_DOWN) } } // mirror scrolling events triggered on preview window private fun autoScroll(int: Int) { scrollingBuffer = Defines.EMPTY_BUFFER_SIZE val y = (scrollRange * int) / 100 scrollView.scrollTo(scrollView.scrollX, y) } // handle scroll events triggered on editor window private fun updateScrollValues(int: Int, str: String) { if (scrollingBuffer >= Defines.DEFAULT_BUFFER_SIZE) { val percentage = (int * 100) / scrollRange scrollVM.setScroll(str, percentage) } else { // filter out scrolling events caused by auto scrolling scrollingBuffer++ } } // create drop targets for the editor screen private fun initializeDragListener() { val handler = DragHandler(requireActivity(), webVM, requireActivity().contentResolver) // Main target will trigger when textField has content textField.setOnDragListener { _, event -> handler.onDrag(event) } // Sub target will trigger when textField is empty codeLayout.setOnDragListener { _, event -> handler.onDrag(event) } } }
0
Kotlin
14
9
aa6f5b4cae5ac2aef8ffcadd357f1dc11d746e60
7,924
droidcon-sf-23
Apache License 2.0
nugu-agent/src/main/java/com/skt/nugu/sdk/agent/DefaultMicrophoneAgent.kt
nugu-developers
214,067,023
false
null
/** * Copyright (c) 2019 SK Telecom Co., Ltd. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * 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.skt.nugu.sdk.agent import com.google.gson.JsonObject import com.google.gson.annotations.SerializedName import com.skt.nugu.sdk.agent.microphone.Microphone import com.skt.nugu.sdk.agent.util.IgnoreErrorContextRequestor import com.skt.nugu.sdk.agent.util.MessageFactory import com.skt.nugu.sdk.agent.version.Version import com.skt.nugu.sdk.core.interfaces.common.NamespaceAndName import com.skt.nugu.sdk.core.interfaces.context.* import com.skt.nugu.sdk.core.interfaces.directive.BlockingPolicy import com.skt.nugu.sdk.core.interfaces.message.MessageRequest import com.skt.nugu.sdk.core.interfaces.message.MessageSender import com.skt.nugu.sdk.core.interfaces.message.Status import com.skt.nugu.sdk.core.interfaces.message.request.EventMessageRequest import com.skt.nugu.sdk.core.utils.Logger import java.util.concurrent.Executors class DefaultMicrophoneAgent( private val messageSender: MessageSender, private val contextManager: ContextManagerInterface, private val defaultMicrophone: Microphone? ) : AbstractCapabilityAgent(NAMESPACE), Microphone.OnSettingChangeListener { internal data class SetMicPayload( @SerializedName("playServiceId") val playServiceId: String, @SerializedName("status") val status: String ) companion object { private const val TAG = "MicrophoneAgent" const val NAMESPACE = "Mic" private val VERSION = Version(1, 0) const val NAME_SET_MIC = "SetMic" private const val NAME_SET_MIC_SUCCEEDED = "SetMicSucceeded" private const val NAME_SET_MIC_FAILED = "SetMicFailed" val SET_MIC = NamespaceAndName( NAMESPACE, NAME_SET_MIC ) const val KEY_STATUS = "status" } private val executor = Executors.newSingleThreadExecutor() internal data class StateContext(private val settings: Microphone.Settings?) : BaseContextState { companion object { private fun buildCompactContext(): JsonObject = JsonObject().apply { addProperty("version", VERSION.toString()) } private val COMPACT_STATE: String = buildCompactContext().toString() val CompactContextState = object : BaseContextState { override fun value(): String = COMPACT_STATE } } override fun value(): String = buildCompactContext().apply { addProperty("micStatus", if (settings?.onOff == true) "ON" else "OFF") }.toString() } init { defaultMicrophone?.addListener(this) contextManager.setStateProvider(namespaceAndName, this) } override fun onSettingsChanged(settings: Microphone.Settings) { provideState(contextManager, namespaceAndName, ContextType.FULL, 0) } override fun preHandleDirective(info: DirectiveInfo) { // no-op } override fun handleDirective(info: DirectiveInfo) { when (info.directive.getNamespaceAndName()) { SET_MIC -> handleSetMic(info) } } private fun handleSetMic(info: DirectiveInfo) { val directive = info.directive val payload = MessageFactory.create(directive.payload, SetMicPayload::class.java) if (payload == null) { Logger.e(TAG, "[handleSetMic] invalid payload: ${directive.payload}") setHandlingFailed(info, "[handleSetMic] invalid payload: ${directive.payload}") return } val status = payload.status.toUpperCase() if (status != "ON" && status != "OFF") { Logger.e(TAG, "[handleSetMic] invalid status: $status") setHandlingFailed(info, "[handleSetMic] invalid status: $status") return } setHandlingCompleted(info) executor.submit { val referrerDialogRequestId = info.directive.header.dialogRequestId if (executeHandleSetMic(status)) { sendEvent( NAME_SET_MIC_SUCCEEDED, payload.playServiceId, payload.status, referrerDialogRequestId ) } else { sendEvent( NAME_SET_MIC_FAILED, payload.playServiceId, payload.status, referrerDialogRequestId ) } } } private fun sendEvent( eventName: String, playServiceId: String, micStatus: String, referrerDialogRequestId: String ) { contextManager.getContext(object : IgnoreErrorContextRequestor() { override fun onContext(jsonContext: String) { messageSender.newCall( EventMessageRequest.Builder( jsonContext, NAMESPACE, eventName, VERSION.toString() ).payload(JsonObject().apply { addProperty("playServiceId", playServiceId) addProperty("micStatus", micStatus) }.toString()) .referrerDialogRequestId(referrerDialogRequestId) .build() ).enqueue(object : MessageSender.Callback { override fun onFailure(request: MessageRequest, status: Status) { } override fun onSuccess(request: MessageRequest) { } override fun onResponseStart(request: MessageRequest) { } }) } }) } private fun executeHandleSetMic(status: String): Boolean { return when (status) { "ON" -> defaultMicrophone?.on() ?: false "OFF" -> defaultMicrophone?.off() ?: false else -> false } } private fun setHandlingCompleted(info: DirectiveInfo) { info.result.setCompleted() } private fun setHandlingFailed(info: DirectiveInfo, description: String) { info.result.setFailed(description) } override fun cancelDirective(info: DirectiveInfo) { } override fun getConfiguration(): Map<NamespaceAndName, BlockingPolicy> { val nonBlockingPolicy = BlockingPolicy() val configuration = HashMap<NamespaceAndName, BlockingPolicy>() configuration[SET_MIC] = nonBlockingPolicy return configuration } override fun provideState( contextSetter: ContextSetterInterface, namespaceAndName: NamespaceAndName, contextType: ContextType, stateRequestToken: Int ) { executor.submit { Logger.d( TAG, "[provideState] namespaceAndName: $namespaceAndName, contextType: $contextType, stateRequestToken: $stateRequestToken" ) contextSetter.setState( namespaceAndName, if (contextType == ContextType.COMPACT) StateContext.CompactContextState else StateContext( defaultMicrophone?.getSettings() ), StateRefreshPolicy.ALWAYS, contextType, stateRequestToken ) } } }
5
null
18
27
9d90dcbb8463f7b8f98713126a93de7e291da86c
7,881
nugu-android
Apache License 2.0
app/src/main/java/com/example/twitturin/tweet/presentation/postTweet/ui/PublicPostPolicyFragment.kt
extractive-mana-pulse
708,689,521
false
{"Kotlin": 318582, "Java": 2351}
package com.example.twitturin.tweet.presentation.postTweet.ui import android.annotation.SuppressLint import android.content.Context import android.content.SharedPreferences import android.os.Bundle import androidx.fragment.app.Fragment import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.lifecycle.lifecycleScope import androidx.navigation.fragment.findNavController import com.example.twitturin.R import com.example.twitturin.databinding.FragmentPublicPostPolicyBinding import com.example.twitturin.tweet.presentation.postTweet.util.Constants import io.noties.markwon.Markwon class PublicPostPolicyFragment : Fragment() { private val binding by lazy { FragmentPublicPostPolicyBinding.inflate(layoutInflater) } override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? { return binding.root } @SuppressLint("SetTextI18n") override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) binding.apply { policyToolbar.setNavigationOnClickListener { findNavController().navigateUp() } policyAgreeBtn.setOnClickListener { findNavController().navigate(R.id.action_publicPostPolicyFragment_to_publicPostFragment) } Markwon.create(requireContext()).setMarkdown(policyContextTv, "## At TwitturIn, we are committed to protecting the privacy and security of our users. This Privacy Policy explains how we collect, use, and protect your personal information when you use our chat application.\n" + "\n" + "### Information We Collect\n" + "\n" + " * **User Account Information**: When you create an account with us, we may collect your username, email address, and other profile information you provide.\n" + "\n * **Chat Messages**: The content of the messages you send and receive through our chat app is stored temporarily to enable the chat functionality. We do not access or read the content of your messages.\n" + "\n * **Device Information**: We may collect information about the device you use to access our app, such as the device model, operating system, and IP address.\n" + "### How We Use Your Information\n" + "\n" + "\n * **Account Management**: We use your account information to create and maintain your user profile, enable the chat functionality, and provide customer support.\n" + "\n * **Improving Our Services**: We may use the information we collect to analyze usage patterns and trends, and to improve the features and performance of our chat app.\n" + "\n * **Legal Compliance**: We may use or disclose your information if we are required to do so by law or in response to valid requests by public authorities.\n" + "###Data Retention and Security\n" + "\n" + "\n * **Message Retention**: We temporarily store the content of your chat messages to enable the chat functionality. The messages are automatically deleted after [X] days.\n" + "\n * **Data Security**: We implement appropriate technical and organizational measures to protect your personal information from unauthorized access, disclosure, or misuse.\n" + "\n ### Your Rights and Choices\n" + "\n" + "\n * **Access and Correction**: You have the right to access, update, and correct the personal information we have about you.\n" + "\n * **Deletion**: You can request the deletion of your account and personal information by contacting our support team.\n" + "\n * **Opt-Out**: You can opt-out of receiving certain communications from us, such as marketing or promotional messages, by adjusting your account settings or by following the unsubscribe instructions in the communication.\n" + "\n ### Changes to this Privacy Policy\n" + "We may update this Privacy Policy from time to time to reflect changes in our practices or applicable laws. We will notify you of any material changes by posting the updated policy on our app or website.\n" + "\n" + "Contact Us\n" + "If you have any questions or concerns about our privacy practices, please contact us at [Gmail](https://mail.google.com/mail/u/0/#inbox?compose=new)" + "\n" + "### Chat Etiquette and Guidelines\n" + "\n" + "\n 1. **Respect and Inclusivity**:\n" + "Refrain from using discriminatory, hateful, or derogatory language based on race, ethnicity, gender, sexual orientation, religion, or any other protected characteristic.\n" + "Be respectful and considerate of others, regardless of their background or beliefs.\n" + "\n 2. **Appropriate Content**:\n" + "Do not engage in or encourage illegal activities.\n" + "Avoid posting explicit, violent, or sexually suggestive content that may be inappropriate or offensive to other users.\n" + "Do not share private or confidential information about yourself or others without permission.\n" + "\n 3. **Constructive Communication**:\n" + "Express yourself clearly and avoid misunderstandings by being mindful of your tone and word choice.\n" + "Engage in productive discussions and provide constructive feedback, rather than resorting to personal attacks or flame wars.\n" + "If you encounter disagreements or conflicts, try to resolve them respectfully and avoid escalating the situation.\n" + "\n 4. **Privacy and Security**:\n" + "Do not share your own or others' personal information, such as phone numbers, addresses, or financial details, without consent.\n" + "Be cautious about clicking on links or attachments from unknown sources, as they may contain malware or inappropriate content.\n" + "\n 5. **Moderation and Reporting**:\n" + "If you encounter any content or behavior that violates these guidelines, report it to the chat app's moderation team or administrators.\n" + "Cooperate with the app's moderators and administrators if they need to investigate or address any issues.\n" + "\n 6. **Responsible Use**:\n" + "Use the chat app in a manner that does not disrupt or interfere with others' ability to engage in the platform.\n" + "Avoid spamming, flooding, or engaging in any other behavior that may be considered abusive or disruptive.") } } }
1
Kotlin
0
1
9c94fd0f8b139cdf0412839140f6632e8cbf3c91
7,067
Twittur-In-
MIT License
src/main/kotlin/io/github/ivsokol/poe/action/IPolicyActionRefOrValueSerializer.kt
ivsokol
850,045,264
false
{"Kotlin": 1891986}
package io.github.ivsokol.poe.action import kotlinx.serialization.DeserializationStrategy import kotlinx.serialization.json.JsonContentPolymorphicSerializer import kotlinx.serialization.json.JsonElement import kotlinx.serialization.json.JsonObject /** * Serializes and deserializes [IPolicyActionRefOrValue] instances to and from JSON. * * This serializer handles both [PolicyActionRef] and [IPolicyAction] instances, selecting the * appropriate deserializer based on the JSON element structure. */ object IPolicyActionRefOrValueSerializer : JsonContentPolymorphicSerializer<IPolicyActionRefOrValue>(IPolicyActionRefOrValue::class) { override fun selectDeserializer( element: JsonElement ): DeserializationStrategy<IPolicyActionRefOrValue> = when { element is JsonObject -> parseJsonObject(element) else -> throw IllegalArgumentException( "Not correct JsonElement for IPolicyActionRefOrValue DeserializationStrategy") } private fun parseJsonObject(element: JsonObject) = when { element.containsKey("refType") -> PolicyActionRef.serializer() element.containsKey("type") -> IPolicyActionSerializer else -> throw IllegalArgumentException( "No corresponding field for IPolicyActionRefOrValue DeserializationStrategy") } }
0
Kotlin
0
1
e1513c000ced3eafefad6778fc6085df8c4b17ee
1,362
policy-engine
Apache License 2.0
gis/src/commonMain/kotlin/jetbrains/gis/geoprotocol/GeocodingService.kt
JetBrains
176,771,727
false
null
/* * Copyright (c) 2019. JetBrains s.r.o. * Use of this source code is governed by the MIT license that can be found in the LICENSE file. */ package jetbrains.gis.geoprotocol import org.jetbrains.letsPlot.commons.intern.async.Async import jetbrains.gis.geoprotocol.GeoResponse.* import jetbrains.gis.geoprotocol.GeoResponse.AmbiguousGeoResponse.AmbiguousFeature import jetbrains.gis.geoprotocol.GeoResponse.SuccessGeoResponse.GeocodedFeature import jetbrains.gis.geoprotocol.GeoResponse.SuccessGeoResponse.GeocodingAnswer class GeocodingService(private val myTransport: GeoTransport) { fun execute(request: GeoRequest): Async<List<GeocodedFeature>> { return myTransport .send(request) .map { response -> when (response) { is SuccessGeoResponse -> response.answers.flatMap(GeocodingAnswer::geocodedFeatures) is AmbiguousGeoResponse -> throw RuntimeException(createAmbiguousMessage(response.features)) is ErrorGeoResponse -> throw RuntimeException("GIS error: " + response.message) else -> throw IllegalStateException("Unknown response status: $response") } } } companion object { internal fun createAmbiguousMessage(ambiguousFeatures: List<AmbiguousFeature>): String { val message = StringBuilder().append("Geocoding errors:\n") ambiguousFeatures.forEach { ambiguousFeature -> when { ambiguousFeature.namesakeCount == 1 -> {} ambiguousFeature.namesakeCount > 1 -> { message .append("Multiple objects (${ambiguousFeature.namesakeCount}") .append(") were found for '${ambiguousFeature.request}'") .append(if (ambiguousFeature.namesakes.isEmpty()) "." else ":") ambiguousFeature.namesakes .map { (name, parents) -> "- ${name}${parents.joinToString(prefix = "(", transform = { it.name }, postfix = ")")}"} .sorted() .forEach { message.append("\n$it") } } else -> message.append("No objects were found for '${ambiguousFeature.request}'.") } message.append("\n") } return message.toString() } } }
96
null
51
889
2fb1fe8e812ed0b84cd32954331a76775e75d4d2
2,483
lets-plot
MIT License
src/main/kotlin/org/jaqpot/api/service/prediction/runtime/runtimes/JaqpotPyV6Runtime.kt
ntua-unit-of-control-and-informatics
790,773,279
false
{"Kotlin": 176168, "FreeMarker": 2174}
package org.jaqpot.api.service.prediction.runtime.runtimes import org.jaqpot.api.dto.prediction.PredictionModelDto import org.jaqpot.api.model.DatasetDto import org.jaqpot.api.service.model.dto.PredictionRequestDto import org.jaqpot.api.service.prediction.runtime.config.RuntimeConfiguration import org.springframework.http.HttpEntity import org.springframework.stereotype.Component @Component class JaqpotPyV6Runtime(private val runtimeConfiguration: RuntimeConfiguration) : RuntimeBase() { override fun createRequestBody(predictionModelDto: PredictionModelDto, datasetDto: DatasetDto): HttpEntity<Any> { val predictionRequestDto = PredictionRequestDto( predictionModelDto, datasetDto, predictionModelDto.extraConfig ) return HttpEntity( predictionRequestDto ) } override fun getRuntimeUrl(): String { return runtimeConfiguration.jaqpotpyInferenceV6Url } override fun getRuntimePath(predictionModelDto: PredictionModelDto): String { return "/predict/" } }
0
Kotlin
0
0
5707aed75155d3955865b68f6b5678c451b0cd93
1,082
jaqpot-api
MIT License
src/main/kotlin/co/anbora/labs/firebase/ide/actions/CreateStorageFileAction.kt
anboralabs
302,825,861
false
null
package co.anbora.labs.firebase.ide.actions import co.anbora.labs.firebase.ide.icons.FirebaseIcons import com.intellij.ide.actions.CreateFileFromTemplateAction import com.intellij.ide.actions.CreateFileFromTemplateDialog import com.intellij.openapi.project.Project import com.intellij.psi.PsiDirectory class CreateStorageFileAction: CreateFileFromTemplateAction(CAPTION, "", FirebaseIcons.FILE) { private companion object { private const val CAPTION = "Firestore File" } override fun buildDialog(project: Project, directory: PsiDirectory, builder: CreateFileFromTemplateDialog.Builder) { builder.setTitle(CAPTION).addKind("Empty Rules file", FirebaseIcons.FILE, "Storage Rule File") } override fun getActionName(directory: PsiDirectory?, newName: String, templateName: String?): String = CAPTION }
1
Kotlin
6
26
aca37769ce7578ff8f2e08a5d05890a18bf918fe
847
intellij-firebase-highlighter
MIT License
src/main/kotlin/no/nav/aap/api/oppslag/kontaktinformasjon/KontaktinformasjonDTO.kt
navikt
402,698,973
false
null
package no.nav.aap.api.oppslag.kontaktinformasjon import com.fasterxml.jackson.annotation.JsonAlias import com.fasterxml.jackson.annotation.JsonIgnoreProperties import javax.validation.constraints.Email import no.nav.aap.api.oppslag.kontaktinformasjon.Kontaktinformasjon.Companion.EMPTY import no.nav.aap.util.LoggerUtil.getLogger @JsonIgnoreProperties(ignoreUnknown = true) data class KontaktinformasjonDTO(@JsonAlias("spraak") val målform: Målform? = Målform.NB, val reservert: Boolean? = null, val kanVarsles: Boolean? = false, val aktiv: Boolean? = false, @JsonAlias("epostadresse") @Email val epost: String? = null, @JsonAlias("mobiltelefonnummer") val mobil: String? = null) { private val log = getLogger(javaClass) fun tilKontaktinfo() = when (aktiv) { true -> when (kanVarsles) { true -> Kontaktinformasjon(epost, mobil) else -> EMPTY.also { log.trace("Kan ikke varsles, kanVarsles er false i KRR") } } else -> EMPTY.also { log.trace("Er ikke aktiv i KRR") } } } data class Kontaktinformasjon(val epost: String? = null, val mobil: String? = null) { companion object { val EMPTY = Kontaktinformasjon() } } enum class Målform { NB, NN, EN, SE }
4
Kotlin
1
3
d4456fdd7934f79503123f0d9ce9318c081b45ba
1,428
aap-soknad-api
MIT License
app/src/main/java/com/amazon/ivs/optimizations/ui/home/HomeFragment.kt
aws-samples
409,741,381
false
null
package com.amazon.ivs.optimizations.ui.home import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.fragment.app.Fragment import com.amazon.ivs.optimizations.App import com.amazon.ivs.optimizations.R import com.amazon.ivs.optimizations.cache.PREFERENCES_NAME import com.amazon.ivs.optimizations.cache.PreferenceProvider import com.amazon.ivs.optimizations.common.lazyViewModel import com.amazon.ivs.optimizations.common.openFragment import com.amazon.ivs.optimizations.databinding.FragmentHomeBinding import com.amazon.ivs.optimizations.ui.precaching.PreCachingViewModel class HomeFragment : Fragment() { private lateinit var binding: FragmentHomeBinding private val preferences by lazy { PreferenceProvider(requireContext(), PREFERENCES_NAME) } private val viewModel by lazyViewModel( { requireActivity().application as App }, { PreCachingViewModel(preferences) } ) override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View { binding = FragmentHomeBinding.inflate(layoutInflater) return binding.root } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) binding.rebufferToLive.setOnClickListener { openFragment(R.id.navigation_rebuff_to_live) } binding.catchUpToLive.setOnClickListener { openFragment(R.id.navigation_catch_up_to_live) } binding.preCaching.setOnClickListener { viewModel.play() openFragment(R.id.navigation_pre_caching) } } override fun onResume() { super.onResume() viewModel.initPlayer(requireContext(), preferences.playbackUrl) } }
1
Kotlin
2
1
1582c972e70b9e2befae2bd2789dbce5817c7b52
1,857
amazon-ivs-optimizations-android-demo
MIT No Attribution
module/minecraft/minecraft-chat/src/main/kotlin/taboolib/module/chat/impl/DefaultComponent.kt
TabooLib
120,413,612
false
null
package taboolib.module.chat.impl import net.md_5.bungee.api.ChatColor import net.md_5.bungee.api.chat.* import net.md_5.bungee.api.chat.hover.content.Entity import net.md_5.bungee.api.chat.hover.content.Item import net.md_5.bungee.api.chat.hover.content.Text import net.md_5.bungee.chat.ComponentSerializer import taboolib.common.platform.ProxyCommandSender import taboolib.common.platform.ProxyPlayer import taboolib.common.platform.function.onlinePlayers import taboolib.module.chat.* import java.awt.Color /** * TabooLib * taboolib.module.chat.impl.DefaultComponent * * @author 坏黑 * @since 2023/2/9 20:36 */ class DefaultComponent() : ComponentText { constructor(from: List<BaseComponent>) : this() { left.addAll(from) } private val left = arrayListOf<BaseComponent>() private val latest = arrayListOf<BaseComponent>() private val component: BaseComponent get() = when { left.isEmpty() && latest.size == 1 -> latest[0] latest.isEmpty() && left.size == 1 -> left[0] else -> TextComponent(*(left + latest).toTypedArray()) } init { color(StandardColors.RESET) } override fun toRawMessage(): String { return ComponentSerializer.toString(component) } override fun toLegacyText(): String { return ComponentToString.toLegacyString(*(left + latest).toTypedArray()) } override fun toPlainText(): String { return TextComponent.toPlainText(*(left + latest).toTypedArray()) } override fun broadcast() { onlinePlayers().forEach { sendTo(it) } } override fun sendTo(sender: ProxyCommandSender) { if (sender is ProxyPlayer) { sender.sendRawMessage(toRawMessage()) } else { sender.sendMessage(toLegacyText()) } } override fun newLine(): ComponentText { return append("\n") } override fun plusAssign(text: String) { append(text) } override fun plusAssign(other: ComponentText) { append(other) } override fun append(text: String): ComponentText { flush() latest += try { TextComponent.fromLegacyText(text, ChatColor.RESET) } catch (_: NoSuchMethodError) { TextComponent.fromLegacyText("${ChatColor.RESET}$text") } return this } override fun append(other: ComponentText): ComponentText { other as? DefaultComponent ?: error("Unsupported component type.") flush() latest += other.component return this } override fun appendTranslation(text: String, vararg obj: Any): ComponentText { return appendTranslation(text, obj.toList()) } override fun appendTranslation(text: String, obj: List<Any>): ComponentText { flush() latest += TranslatableComponent(text, obj.map { if (it is DefaultComponent) it.component else it }) return this } override fun appendKeybind(key: String): ComponentText { flush() latest += KeybindComponent(key) return this } override fun appendScore(name: String, objective: String): ComponentText { flush() latest += ScoreComponent(name, objective) return this } override fun appendSelector(selector: String): ComponentText { flush() latest += SelectorComponent(selector) return this } override fun hoverText(text: String): ComponentText { return hoverText(ComponentText.of(text)) } override fun hoverText(text: List<String>): ComponentText { val component = ComponentText.empty() text.forEachIndexed { index, s -> component.append(s) if (index != text.size - 1) { component.newLine() } } return hoverText(component) } override fun hoverText(text: ComponentText): ComponentText { text as? DefaultComponent ?: error("Unsupported component type.") try { latest.forEach { it.hoverEvent = HoverEvent(HoverEvent.Action.SHOW_TEXT, Text(arrayOf(text.component))) } } catch (_: NoClassDefFoundError) { latest.forEach { it.hoverEvent = HoverEvent(HoverEvent.Action.SHOW_TEXT, arrayOf(text.component)) } } catch (_: NoSuchMethodError) { latest.forEach { it.hoverEvent = HoverEvent(HoverEvent.Action.SHOW_TEXT, arrayOf(text.component)) } } return this } override fun hoverItem(id: String, nbt: String): ComponentText { try { latest.forEach { it.hoverEvent = HoverEvent(HoverEvent.Action.SHOW_ITEM, Item(id, 1, ItemTag.ofNbt(nbt))) } } catch (_: NoClassDefFoundError) { latest.forEach { it.hoverEvent = HoverEvent(HoverEvent.Action.SHOW_ITEM, ComponentBuilder("{id:\"$id\",Count:1b,tag:$nbt}").create()) } } catch (_: NoSuchMethodError) { latest.forEach { it.hoverEvent = HoverEvent(HoverEvent.Action.SHOW_ITEM, ComponentBuilder("{id:\"$id\",Count:1b,tag:$nbt}").create()) } } return this } override fun hoverEntity(id: String, type: String?, name: String?): ComponentText { try { val component = if (name != null) TextComponent(name) else null latest.forEach { it.hoverEvent = HoverEvent(HoverEvent.Action.SHOW_ENTITY, Entity(type, id, component)) } } catch (_: NoClassDefFoundError) { TODO("Unsupported hover entity for this version.") } return this } override fun hoverEntity(id: String, type: String?, name: ComponentText?): ComponentText { try { val component = if (name is DefaultComponent) name.component else null latest.forEach { it.hoverEvent = HoverEvent(HoverEvent.Action.SHOW_ENTITY, Entity(type, id, component)) } } catch (_: NoClassDefFoundError) { TODO("Unsupported hover entity for this version.") } return this } override fun click(action: ClickAction, value: String): ComponentText { when (action) { ClickAction.OPEN_URL, ClickAction.OPEN_FILE, ClickAction.RUN_COMMAND, ClickAction.SUGGEST_COMMAND, ClickAction.CHANGE_PAGE, ClickAction.COPY_TO_CLIPBOARD -> latest.forEach { it.clickEvent = ClickEvent(ClickEvent.Action.valueOf(action.name), value) } // 插入文本 ClickAction.INSERTION -> clickInsertText(value) } return this } override fun clickOpenURL(url: String): ComponentText { return click(ClickAction.OPEN_URL, url) } override fun clickOpenFile(file: String): ComponentText { return click(ClickAction.OPEN_FILE, file) } override fun clickRunCommand(command: String): ComponentText { return click(ClickAction.RUN_COMMAND, command) } override fun clickSuggestCommand(command: String): ComponentText { return click(ClickAction.SUGGEST_COMMAND, command) } override fun clickChangePage(page: Int): ComponentText { return click(ClickAction.CHANGE_PAGE, page.toString()) } override fun clickCopyToClipboard(text: String): ComponentText { return click(ClickAction.COPY_TO_CLIPBOARD, text) } override fun clickInsertText(text: String): ComponentText { latest.forEach { it.insertion = text } return this } override fun decoration(decoration: Decoration): ComponentText { when (decoration) { Decoration.BOLD -> bold() Decoration.ITALIC -> italic() Decoration.UNDERLINE -> underline() Decoration.STRIKETHROUGH -> strikethrough() Decoration.OBFUSCATED -> obfuscated() } return this } override fun undecoration(decoration: Decoration): ComponentText { when (decoration) { Decoration.BOLD -> unbold() Decoration.ITALIC -> unitalic() Decoration.UNDERLINE -> ununderline() Decoration.STRIKETHROUGH -> unstrikethrough() Decoration.OBFUSCATED -> unobfuscated() } return this } override fun undecoration(): ComponentText { unbold() unitalic() ununderline() unstrikethrough() unobfuscated() return this } override fun bold(): ComponentText { latest.forEach { it.isBold = true } return this } override fun unbold(): ComponentText { latest.forEach { it.isBold = false } return this } override fun italic(): ComponentText { latest.forEach { it.isItalic = true } return this } override fun unitalic(): ComponentText { latest.forEach { it.isItalic = false } return this } override fun underline(): ComponentText { latest.forEach { it.isUnderlined = true } return this } override fun ununderline(): ComponentText { latest.forEach { it.isUnderlined = false } return this } override fun strikethrough(): ComponentText { latest.forEach { it.isStrikethrough = true } return this } override fun unstrikethrough(): ComponentText { latest.forEach { it.isStrikethrough = false } return this } override fun obfuscated(): ComponentText { latest.forEach { it.isObfuscated = true } return this } override fun unobfuscated(): ComponentText { latest.forEach { it.isObfuscated = false } return this } override fun font(font: String): ComponentText { latest.forEach { it.font = font } return this } override fun unfont(): ComponentText { latest.forEach { it.font = null } return this } override fun color(color: StandardColors): ComponentText { latest.forEach { it.color = color.toChatColor() } return this } override fun color(color: Color): ComponentText { latest.forEach { it.color = ChatColor.of(color) } return this } override fun uncolor(): ComponentText { latest.forEach { it.color = null } return this } override fun toSpigotObject(): BaseComponent { return component } /** 释放缓冲区 */ fun flush() { left.addAll(latest) latest.clear() } override fun toString(): String { return toRawMessage() } }
9
null
88
307
f1178ac797c650042c977bfdf7a25e926522c032
10,493
taboolib
MIT License
telegram/src/main/kotlin/me/ivmg/telegram/entities/InlineKeyboardButton.kt
seik
284,789,498
false
null
package me.ivmg.telegram.entities import com.google.gson.annotations.SerializedName as Name data class InlineKeyboardButton( val text: String, val url: String? = null, @Name("callback_data") val callbackData: String? = null, @Name("switch_inline_query") val switchInlineQuery: String? = null, @Name("switch_inline_query_current_chat") val switchInlineQueryCurrentChat: String? = null ) : ReplyMarkup
0
null
0
1
92f6ab6f96589380f5fba6a0259379b256532c55
422
kotlin-telegram-bot
Apache License 2.0
tui/src/commonMain/kotlin/kotlinbars/tui/Main.kt
jamesward
350,496,939
false
null
/* * Copyright 2020 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 kotlinbars.tui import kotlinbars.common.Bar import kotlinbars.rpc.BarsRPC import kotlinx.coroutines.runBlocking suspend fun loop(url: String) { val rpc = BarsRPC(url) while (true) { val bars = rpc.fetchBars() if (bars.isEmpty()) { println("\nNo Bars") } else { println("\nBars:") bars.forEach { println(" ${it.name}") } } print("\nCreate a Bar: ") val name = readLine() if (!name.isNullOrEmpty()) { val bar = Bar(null, name) rpc.addBar(bar) // todo: check response code } } } fun main() = runBlocking { println("Connecting to: ${Config.barsUrl}") loop(Config.barsUrl) }
1
Kotlin
4
44
9e8e21f16b92162c30ea95a468e380eff9e4740f
1,338
kotlin-bars
Apache License 2.0
app/src/main/java/ca/sudbury/hghasemi/notifyplus/ApkListAdapter.kt
hojat72elect
157,974,752
false
{"Kotlin": 94572}
package ca.sudbury.hghasemi.notifyplus import android.annotation.SuppressLint import android.content.pm.ApplicationInfo import android.content.pm.PackageManager import android.graphics.Color import android.graphics.drawable.Drawable import android.os.Handler import android.text.Spannable import android.text.SpannableString import android.text.style.ForegroundColorSpan import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.ImageView import android.widget.TextView import androidx.recyclerview.widget.RecyclerView import ca.sudbury.hghasemi.notifyplus.fragments.AppsDialog import java.util.* import java.util.concurrent.Executors /** * Created by <NAME> on Saturday , 27 May 2017. * Contact the author at "https://github.com/hojat72elect" */ class ApkListAdapter(activity: MainActivity, appsDialog: AppsDialog) : RecyclerView.Adapter<ApkListAdapter.ViewHolder>() { val packageManager: PackageManager = activity.packageManager var namesToLoad = 0 private val list = ArrayList<ApplicationInfo>() private val listOriginal = ArrayList<ApplicationInfo>() private val executorServiceNames = Executors.newFixedThreadPool(3) private val executorServiceIcons = Executors.newFixedThreadPool(3) private val handler = Handler() private val cacheAppName = Collections.synchronizedMap(LinkedHashMap<String, String?>(10, 1.5f, true)) private val cacheAppIcon = Collections.synchronizedMap(LinkedHashMap<String, Drawable>(10, 1.5f, true)) private var searchPattern: String? = null // Returns the ViewHolder which contains the UI of each row of RecyclerView override fun onCreateViewHolder(viewGroup: ViewGroup, i: Int): ViewHolder { return ViewHolder( LayoutInflater.from(viewGroup.context) .inflate(R.layout.appnameandicon, viewGroup, false) ) } // Called by RecyclerView to display the data at the specified position override fun onBindViewHolder(holder: ViewHolder, position: Int) { val item = list[position] holder.setPackageName(item.packageName, searchPattern) if (cacheAppIcon.containsKey(item.packageName) && cacheAppName.containsKey(item.packageName)) { holder.setAppName(cacheAppName[item.packageName], searchPattern) holder.imgIcon.setImageDrawable(cacheAppIcon[item.packageName]) } else { holder.setAppName(item.packageName, searchPattern) holder.imgIcon.setImageDrawable(null) executorServiceIcons.submit(GuiLoader(holder, item)) } } override fun getItemCount(): Int { return list.size } @SuppressLint("NotifyDataSetChanged") fun addItem(item: ApplicationInfo) { namesToLoad++ executorServiceNames.submit(AppNameLoader(item)) listOriginal.add(item) filterListByPattern() notifyDataSetChanged() } @SuppressLint("NotifyDataSetChanged") fun setSearchPattern(pattern: String) { searchPattern = pattern.lowercase(Locale.getDefault()) filterListByPattern() notifyDataSetChanged() } private fun filterListByPattern() { list.clear() for (info in listOriginal) { var add = true do { if (searchPattern == null || searchPattern!!.isEmpty()) { break // empty search pattern: add everything } if (cacheAppName.containsKey(info.packageName) && cacheAppName[info.packageName] ?.lowercase(Locale.getDefault())?.contains( searchPattern!! ) == true ) { break // search in application name } add = false } while (false) if (add) list.add(info) } } class ViewHolder(v: View) : RecyclerView.ViewHolder(v), View.OnClickListener { var imgIcon: ImageView = v.findViewById(R.id.appicon) private val txtPackageName: TextView = v.findViewById(R.id.apppackagename) private val txtAppName: TextView = v.findViewById(R.id.appname) override fun onClick(v: View) { mAppsDialog.backToMainActivity(imgIcon, txtPackageName) } fun setAppName(name: String?, highlight: String?) { setAndHighlight(txtAppName, name, highlight) } fun setPackageName(name: String?, highlight: String?) { setAndHighlight(txtPackageName, name, highlight) } private fun setAndHighlight(view: TextView, value: String?, pattern: String?) { view.text = value if (pattern == null || pattern.isEmpty()) return // nothing to highlight val lowerCaseValue = value!!.lowercase(Locale.getDefault()) var offset = 0 var index = lowerCaseValue.indexOf(pattern, offset) while (index >= 0 && offset < lowerCaseValue.length) { val span: Spannable = SpannableString(view.text) span.setSpan( ForegroundColorSpan(Color.BLUE), index, index + pattern.length, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE ) view.text = span offset += index + pattern.length index = lowerCaseValue.indexOf(pattern, offset) } } init { v.setOnClickListener(this) } } internal inner class AppNameLoader(private val applicationInfo: ApplicationInfo) : Runnable { override fun run() { cacheAppName[applicationInfo.packageName] = applicationInfo.loadLabel(packageManager) as String handler.post { namesToLoad-- if (namesToLoad == 0) mAppsDialog.hideProgressBar() } } } internal inner class GuiLoader( private val viewHolder: ViewHolder, private val applicationInfo: ApplicationInfo ) : Runnable { override fun run() { var first = true do { try { val appName = if (cacheAppName.containsKey(applicationInfo.packageName)) cacheAppName[applicationInfo.packageName] else applicationInfo.loadLabel( packageManager ) as String val icon = applicationInfo.loadIcon(packageManager) cacheAppName[applicationInfo.packageName] = appName cacheAppIcon[applicationInfo.packageName] = icon handler.post { viewHolder.setAppName(appName, searchPattern) viewHolder.imgIcon.setImageDrawable(icon) } } catch (ex: OutOfMemoryError) { cacheAppIcon.clear() cacheAppName.clear() if (first) { first = false continue } } break } while (true) } } companion object { @SuppressLint("StaticFieldLeak") lateinit var mAppsDialog: AppsDialog } init { mAppsDialog = appsDialog } }
3
Kotlin
0
2
3fa48e5196d6baba7063a3f8c65fabd2170bb9c6
7,425
Notifyplus
MIT License
libs/main/polynomial/src/commonMain/kotlin/dev/lounres/kone/polynomial/ListPolynomial.kt
lounres
516,842,873
false
null
/* * Copyright © 2023 <NAME> * All rights reserved. Licensed under the Apache License, Version 2.0. See the license in file LICENSE */ @file:Suppress("NOTHING_TO_INLINE", "KotlinRedundantDiagnosticSuppress") package com.lounres.kone.polynomial import com.lounres.kone.algebraic.Field import com.lounres.kone.algebraic.Ring import kotlin.math.max import kotlin.math.min public data class ListPolynomial<C>( public val coefficients: List<C> ) : Polynomial<C> { override fun toString(): String = "ListPolynomial$coefficients" } public open class ListPolynomialSpace<C, out A : Ring<C>>( public override val ring: A, ) : PolynomialSpaceWithRing<C, ListPolynomial<C>, A> { override val zero: ListPolynomial<C> = ListPolynomial(emptyList()) override val one: ListPolynomial<C> by lazy { constantOne.asListPolynomial() } public val freeVariable: ListPolynomial<C> by lazy { ListPolynomial(constantZero, constantOne) } public override infix fun ListPolynomial<C>.equalsTo(other: ListPolynomial<C>): Boolean { for (index in 0 .. max(this.coefficients.lastIndex, other.coefficients.lastIndex)) when (index) { !in this.coefficients.indices -> if (other.coefficients[index].isNotZero()) return false !in other.coefficients.indices -> if (this.coefficients[index].isNotZero()) return false else -> if (!(other.coefficients[index] equalsTo this.coefficients[index])) return false } return true } public override fun ListPolynomial<C>.isZero(): Boolean = coefficients.all { it.isZero() } public override fun ListPolynomial<C>.isOne(): Boolean = coefficients.subList(1, coefficients.size).all { it.isZero() } public override fun valueOf(value: C): ListPolynomial<C> = value.asListPolynomial() public override operator fun ListPolynomial<C>.plus(other: Int): ListPolynomial<C> = if (other == 0) this else ListPolynomial( coefficients .toMutableList() .apply { val result = getOrElse(0) { constantZero } + other if(size == 0) add(result) else this[0] = result } ) public override operator fun ListPolynomial<C>.minus(other: Int): ListPolynomial<C> = if (other == 0) this else ListPolynomial( coefficients .toMutableList() .apply { val result = getOrElse(0) { constantZero } - other if(size == 0) add(result) else this[0] = result } ) public override operator fun ListPolynomial<C>.times(other: Int): ListPolynomial<C> = when (other) { 0 -> zero 1 -> this else -> ListPolynomial( coefficients.map { it * other } ) } public override operator fun ListPolynomial<C>.plus(other: Long): ListPolynomial<C> = if (other == 0L) this else ListPolynomial( coefficients .toMutableList() .apply { val result = getOrElse(0) { constantZero } + other if(size == 0) add(result) else this[0] = result } ) public override operator fun ListPolynomial<C>.minus(other: Long): ListPolynomial<C> = if (other == 0L) this else ListPolynomial( coefficients .toMutableList() .apply { val result = getOrElse(0) { constantZero } - other if(size == 0) add(result) else this[0] = result } ) public override operator fun ListPolynomial<C>.times(other: Long): ListPolynomial<C> = when (other) { 0L -> zero 1L -> this else -> ListPolynomial( coefficients.map { it * other } ) } public override operator fun Int.plus(other: ListPolynomial<C>): ListPolynomial<C> = if (this == 0) other else ListPolynomial( other.coefficients .toMutableList() .apply { val result = this@plus + getOrElse(0) { constantZero } if(size == 0) add(result) else this[0] = result } ) public override operator fun Int.minus(other: ListPolynomial<C>): ListPolynomial<C> = ListPolynomial( other.coefficients .toMutableList() .apply { if (this@minus == 0) { indices.forEach { this[it] = -this[it] } } else { (1..lastIndex).forEach { this[it] = -this[it] } val result = this@minus - getOrElse(0) { constantZero } if (size == 0) add(result) else this[0] = result } } ) public override operator fun Int.times(other: ListPolynomial<C>): ListPolynomial<C> = when (this) { 0 -> zero 1 -> other else -> ListPolynomial( other.coefficients.map { this@times * it } ) } public override operator fun Long.plus(other: ListPolynomial<C>): ListPolynomial<C> = if (this == 0L) other else ListPolynomial( other.coefficients .toMutableList() .apply { val result = this@plus + getOrElse(0) { constantZero } if(size == 0) add(result) else this[0] = result } ) public override operator fun Long.minus(other: ListPolynomial<C>): ListPolynomial<C> = ListPolynomial( other.coefficients .toMutableList() .apply { if (this@minus == 0L) { indices.forEach { this[it] = -this[it] } } else { (1..lastIndex).forEach { this[it] = -this[it] } val result = this@minus - getOrElse(0) { constantZero } if (size == 0) add(result) else this[0] = result } } ) public override operator fun Long.times(other: ListPolynomial<C>): ListPolynomial<C> = when (this) { 0L -> zero 1L -> other else -> ListPolynomial( other.coefficients.map { this@times * it } ) } public override operator fun C.plus(other: ListPolynomial<C>): ListPolynomial<C> = with(other.coefficients) { if (isEmpty()) ListPolynomial(listOf(this@plus)) else ListPolynomial( toMutableList() .apply { val result = if (size == 0) this@plus else this@plus + get(0) if(size == 0) add(result) else this[0] = result } ) } public override operator fun C.minus(other: ListPolynomial<C>): ListPolynomial<C> = with(other.coefficients) { if (isEmpty()) ListPolynomial(listOf(this@minus)) else ListPolynomial( toMutableList() .apply { (1 .. lastIndex).forEach { this[it] = -this[it] } val result = if (size == 0) this@minus else this@minus - get(0) if(size == 0) add(result) else this[0] = result } ) } public override operator fun C.times(other: ListPolynomial<C>): ListPolynomial<C> = ListPolynomial( other.coefficients.map { this@times * it } ) public override operator fun ListPolynomial<C>.plus(other: C): ListPolynomial<C> = with(coefficients) { if (isEmpty()) ListPolynomial(listOf(other)) else ListPolynomial( toMutableList() .apply { val result = if (size == 0) other else get(0) + other if(size == 0) add(result) else this[0] = result } ) } public override operator fun ListPolynomial<C>.minus(other: C): ListPolynomial<C> = with(coefficients) { if (isEmpty()) ListPolynomial(listOf(-other)) else ListPolynomial( toMutableList() .apply { val result = if (size == 0) other else get(0) - other if(size == 0) add(result) else this[0] = result } ) } public override operator fun ListPolynomial<C>.times(other: C): ListPolynomial<C> = ListPolynomial( coefficients.map { it * other } ) public override operator fun ListPolynomial<C>.unaryMinus(): ListPolynomial<C> = ListPolynomial(coefficients.map { -it }) public override operator fun ListPolynomial<C>.plus(other: ListPolynomial<C>): ListPolynomial<C> { val thisDegree = degree val otherDegree = other.degree return ListPolynomial( List(max(thisDegree, otherDegree) + 1) { when { it > thisDegree -> other.coefficients[it] it > otherDegree -> coefficients[it] else -> coefficients[it] + other.coefficients[it] } } ) } public override operator fun ListPolynomial<C>.minus(other: ListPolynomial<C>): ListPolynomial<C> { val thisDegree = degree val otherDegree = other.degree return ListPolynomial( List(max(thisDegree, otherDegree) + 1) { when { it > thisDegree -> -other.coefficients[it] it > otherDegree -> coefficients[it] else -> coefficients[it] - other.coefficients[it] } } ) } public override operator fun ListPolynomial<C>.times(other: ListPolynomial<C>): ListPolynomial<C> { val thisDegree = degree val otherDegree = other.degree return ListPolynomial( List(thisDegree + otherDegree + 1) { d -> (max(0, d - otherDegree)..min(thisDegree, d)) .map { coefficients[it] * other.coefficients[d - it] } .reduce { acc, rational -> acc + rational } } ) } // TODO: To optimize boxing override fun power(base: ListPolynomial<C>, exponent: UInt): ListPolynomial<C> = super.power(base, exponent) public override val ListPolynomial<C>.degree: Int get() = coefficients.lastIndex // TODO: When context receivers will be ready move all of this substitutions and invocations to utilities with // [ListPolynomialSpace] as a context receiver public inline fun ListPolynomial<C>.substitute(argument: C): C = substitute(ring, argument) public inline fun ListPolynomial<C>.substitute(argument: ListPolynomial<C>): ListPolynomial<C> = substitute(ring, argument) public inline fun ListPolynomial<C>.asFunction(): (C) -> C = asFunctionOver(ring) public inline fun ListPolynomial<C>.asFunctionOfConstant(): (C) -> C = asFunctionOfConstantOver(ring) public inline fun ListPolynomial<C>.asFunctionOfPolynomial(): (ListPolynomial<C>) -> ListPolynomial<C> = asFunctionOfPolynomialOver(ring) public inline operator fun ListPolynomial<C>.invoke(argument: C): C = substitute(ring, argument) public inline operator fun ListPolynomial<C>.invoke(argument: ListPolynomial<C>): ListPolynomial<C> = substitute(ring, argument) } public class ListPolynomialSpaceOverField<C, out A : Field<C>>( ring: A, ) : ListPolynomialSpace<C, A>(ring), PolynomialSpaceWithField<C, ListPolynomial<C>, A> { public override fun ListPolynomial<C>.div(other: C): ListPolynomial<C> = ListPolynomial( coefficients.map { it / other } ) }
23
null
0
5
1d3fad2e9cb1a158571b93410f023d1bdca20b40
12,588
Kone
Apache License 2.0
pensjon-brevbaker/src/main/kotlin/no/nav/pensjon/etterlatte/maler/omstillingsstoenad/revurdering/OmstillingsstoenadRevurdering.kt
navikt
375,334,697
false
{"Kotlin": 3391349, "TypeScript": 519756, "TeX": 12813, "Shell": 9251, "CSS": 8104, "Python": 4661, "JavaScript": 4382, "Dockerfile": 2406, "HTML": 1053}
package no.nav.pensjon.etterlatte.maler.omstillingsstoenad.revurdering import no.nav.pensjon.brev.template.Language.Bokmal import no.nav.pensjon.brev.template.Language.English import no.nav.pensjon.brev.template.Language.Nynorsk import no.nav.pensjon.brev.template.dsl.createTemplate import no.nav.pensjon.brev.template.dsl.expression.equalTo import no.nav.pensjon.brev.template.dsl.expression.expr import no.nav.pensjon.brev.template.dsl.expression.format import no.nav.pensjon.brev.template.dsl.expression.not import no.nav.pensjon.brev.template.dsl.expression.notNull import no.nav.pensjon.brev.template.dsl.expression.plus import no.nav.pensjon.brev.template.dsl.helpers.TemplateModelHelpers import no.nav.pensjon.brev.template.dsl.languages import no.nav.pensjon.brev.template.dsl.text import no.nav.pensjon.brev.template.dsl.textExpr import no.nav.pensjon.brevbaker.api.model.LetterMetadata import no.nav.pensjon.etterlatte.EtterlatteBrevKode import no.nav.pensjon.etterlatte.EtterlatteTemplate import no.nav.pensjon.etterlatte.maler.BrevDTO import no.nav.pensjon.etterlatte.maler.Element import no.nav.pensjon.etterlatte.maler.FeilutbetalingType import no.nav.pensjon.etterlatte.maler.Hovedmal import no.nav.pensjon.etterlatte.maler.OmstillingsstoenadBeregning import no.nav.pensjon.etterlatte.maler.OmstillingsstoenadEtterbetaling import no.nav.pensjon.etterlatte.maler.fraser.omstillingsstoenad.OmstillingsstoenadFellesFraser import no.nav.pensjon.etterlatte.maler.fraser.omstillingsstoenad.OmstillingsstoenadRevurderingFraser import no.nav.pensjon.etterlatte.maler.konverterElementerTilBrevbakerformat import no.nav.pensjon.etterlatte.maler.omstillingsstoenad.revurdering.OmstillingsstoenadRevurderingDTOSelectors.beregning import no.nav.pensjon.etterlatte.maler.omstillingsstoenad.revurdering.OmstillingsstoenadRevurderingDTOSelectors.datoVedtakOmgjoering import no.nav.pensjon.etterlatte.maler.omstillingsstoenad.revurdering.OmstillingsstoenadRevurderingDTOSelectors.erEndret import no.nav.pensjon.etterlatte.maler.omstillingsstoenad.revurdering.OmstillingsstoenadRevurderingDTOSelectors.erOmgjoering import no.nav.pensjon.etterlatte.maler.omstillingsstoenad.revurdering.OmstillingsstoenadRevurderingDTOSelectors.etterbetaling import no.nav.pensjon.etterlatte.maler.omstillingsstoenad.revurdering.OmstillingsstoenadRevurderingDTOSelectors.feilutbetaling import no.nav.pensjon.etterlatte.maler.omstillingsstoenad.revurdering.OmstillingsstoenadRevurderingDTOSelectors.harFlereUtbetalingsperioder import no.nav.pensjon.etterlatte.maler.omstillingsstoenad.revurdering.OmstillingsstoenadRevurderingDTOSelectors.harUtbetaling import no.nav.pensjon.etterlatte.maler.omstillingsstoenad.revurdering.OmstillingsstoenadRevurderingDTOSelectors.innhold import no.nav.pensjon.etterlatte.maler.omstillingsstoenad.revurdering.OmstillingsstoenadRevurderingDTOSelectors.lavEllerIngenInntekt import no.nav.pensjon.etterlatte.maler.vedlegg.omstillingsstoenad.beregningAvOmstillingsstoenad import no.nav.pensjon.etterlatte.maler.vedlegg.omstillingsstoenad.dineRettigheterOgPlikter import no.nav.pensjon.etterlatte.maler.vedlegg.omstillingsstoenad.forhaandsvarselFeilutbetaling import no.nav.pensjon.etterlatte.maler.vedlegg.omstillingsstoenad.informasjonOmOmstillingsstoenad import java.time.LocalDate data class OmstillingsstoenadRevurderingDTO( override val innhold: List<Element>, val innholdForhaandsvarsel: List<Element>, val erEndret: Boolean, val erOmgjoering: Boolean, val datoVedtakOmgjoering: LocalDate?, val beregning: OmstillingsstoenadBeregning, val etterbetaling: OmstillingsstoenadEtterbetaling?, val harFlereUtbetalingsperioder: Boolean, val harUtbetaling: Boolean, val lavEllerIngenInntekt: Boolean, val feilutbetaling: FeilutbetalingType ): BrevDTO @TemplateModelHelpers object OmstillingsstoenadRevurdering : EtterlatteTemplate<OmstillingsstoenadRevurderingDTO>, Hovedmal { override val kode: EtterlatteBrevKode = EtterlatteBrevKode.OMSTILLINGSSTOENAD_REVURDERING override val template = createTemplate( name = kode.name, letterDataType = OmstillingsstoenadRevurderingDTO::class, languages = languages(Bokmal, Nynorsk, English), letterMetadata = LetterMetadata( displayTitle = "Vedtak - Revurdering av omstillingsstønad", isSensitiv = true, distribusjonstype = LetterMetadata.Distribusjonstype.VEDTAK, brevtype = LetterMetadata.Brevtype.VEDTAKSBREV, ) ) { title { text( Bokmal to "Vi har ", Nynorsk to "Vi har ", English to "We have ", ) showIf(erOmgjoering) { ifNotNull(datoVedtakOmgjoering) { textExpr( Bokmal to "omgjort vedtaket om omstillingsstønad av ".expr() + it.format(), Nynorsk to "gjort om vedtaket om omstillingsstønad av ".expr() + it.format(), English to "reversed our decision regarding the adjustment allowance on ".expr() + it.format(), ) } }.orShow { showIf(erEndret) { text( Bokmal to "endret", Nynorsk to "endra", English to "changed", ) } orShow { text( Bokmal to "vurdert", Nynorsk to "vurdert", English to "evaluated", ) } text( Bokmal to " omstillingsstønaden din", Nynorsk to " omstillingsstønaden din", English to " your adjustment allowance", ) } } outline { includePhrase(OmstillingsstoenadRevurderingFraser.RevurderingVedtak( erEndret, beregning, etterbetaling.notNull(), harFlereUtbetalingsperioder, harUtbetaling )) konverterElementerTilBrevbakerformat(innhold) includePhrase(OmstillingsstoenadFellesFraser.HvorLengerKanDuFaaOmstillingsstoenad(beregning, lavEllerIngenInntekt)) showIf(lavEllerIngenInntekt.not()) { includePhrase(OmstillingsstoenadRevurderingFraser.Aktivitetsplikt) } includePhrase(OmstillingsstoenadFellesFraser.MeldFraOmEndringer) includePhrase(OmstillingsstoenadFellesFraser.SpesieltOmInntektsendring) includePhrase(OmstillingsstoenadFellesFraser.Etteroppgjoer) includePhrase(OmstillingsstoenadFellesFraser.DuHarRettTilAaKlage) includePhrase(OmstillingsstoenadFellesFraser.HarDuSpoersmaal) } includeAttachment(beregningAvOmstillingsstoenad, beregning) includeAttachment(informasjonOmOmstillingsstoenad, innhold) includeAttachment(dineRettigheterOgPlikter, innhold) includeAttachment(forhaandsvarselFeilutbetaling, this.argument, feilutbetaling.equalTo(FeilutbetalingType.FEILUTBETALING_MED_VARSEL)) } }
7
Kotlin
3
1
ec81ca12f0bc17173b0e38e43441ddde8ae70922
7,227
pensjonsbrev
MIT License
js/js.translator/testData/box/closure/closureValToScopeWithSameNameDeclaration.kt
JakeWharton
99,388,807
false
null
// EXPECTED_REACHABLE_NODES: 992 package foo val f = true fun box(): String { val bar = "test " val boo = "another " fun baz(): String { var result = bar if (f) { val bar = 42 result += bar val boo = 7 result += boo } result += boo result += bar return result } val r = baz() if (r != "test 427another test ") return r; return "OK" }
184
null
5691
83
4383335168338df9bbbe2a63cb213a68d0858104
467
kotlin
Apache License 2.0
letsrebug/app/src/main/java/com/gitclonepeace/letsrebug/mfragment/SettingFragment.kt
asv0018
293,206,641
false
null
package com.gitclonepeace.letsrebug.mfragment import android.app.Activity import android.app.AlertDialog import android.app.ProgressDialog import android.content.DialogInterface import android.content.Intent import android.net.Uri import android.os.Bundle import android.os.storage.StorageManager import androidx.fragment.app.Fragment import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.EditText import android.widget.Toast import com.google.android.gms.tasks.Continuation import com.google.android.gms.tasks.Task import com.google.firebase.auth.FirebaseAuth import com.google.firebase.auth.FirebaseUser import com.google.firebase.database.* import com.google.firebase.storage.FirebaseStorage import com.google.firebase.storage.StorageReference import com.google.firebase.storage.StorageTask import com.google.firebase.storage.UploadTask import com.squareup.picasso.Picasso import com.teamvpn.devhub.ModelClass.Users import com.teamvpn.devhub.R import kotlinx.android.synthetic.main.fragment_maps.* import kotlinx.android.synthetic.main.fragment_setting.view.* /** * A simple [Fragment] subclass. */ class SettingFragment : Fragment() { var UserReference : DatabaseReference? = null var UserReferenceM : DatabaseReference? = null var firebaseUser: FirebaseUser? = null private val RequestCode = 438 private var imageUri: Uri? = null private var StorageRef: StorageReference? = null private var coverChecker : String? = null private var socialChecker : String? = "" override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View? { // Inflate the layout for this fragment val view = inflater.inflate(R.layout.fragment_setting, container, false) firebaseUser = FirebaseAuth.getInstance().currentUser UserReference = FirebaseDatabase.getInstance().reference.child("ChatUsersDB").child(firebaseUser!!.uid) UserReferenceM = FirebaseDatabase.getInstance().reference.child("users").child(firebaseUser!!.uid) StorageRef = FirebaseStorage.getInstance().reference.child("user_profile_pictures")//check UserReference!!.addValueEventListener(object : ValueEventListener{ override fun onDataChange(p0: DataSnapshot) { if(p0.exists()) { val user: Users? = p0.getValue(Users::class.java) if(context!=null) { view.username_settings.text= user!!.getUserName() Picasso.get().load(user.getProfile()).into(view.profile_image_settings) Picasso.get().load(user.getCover()).into(view.cover_image_settings) } } } override fun onCancelled(error: DatabaseError) { } }) view.profile_image_settings.setOnClickListener{ pickImage() } view.cover_image_settings.setOnClickListener{ coverChecker = "cover" pickImage() } view.set_link.setOnClickListener{ socialChecker = "linkedin" setSocialLinks() } view.set_git.setOnClickListener{ socialChecker = "github" setSocialLinks() } view.set_stack.setOnClickListener{ socialChecker = "stackof" setSocialLinks() } return view } private fun setSocialLinks() { val builder: AlertDialog.Builder = AlertDialog.Builder(context, R.style.Theme_AppCompat_DayNight_Dialog_Alert) if(socialChecker == "github") { builder.setTitle("Write Username:") } else { builder.setTitle("Write URL:") } val editText = EditText(context) if(socialChecker == "github") { editText.hint = ("Eg: Felirox") } else { editText.hint = ("Eg: www.website.com/...") } builder.setView(editText) builder.setPositiveButton("Create", DialogInterface.OnClickListener{ dialog, which -> var str = editText.text.toString() if(str == "") { Toast.makeText(context, "Hey! Write something.", Toast.LENGTH_LONG).show() } else { saveSocialLink(str) } }) builder.setNegativeButton("Cancel", DialogInterface.OnClickListener { dialog, which -> }) builder.show() } private fun saveSocialLink(str: String) { val mapSocial = HashMap<String, Any>() // mapSocial = "cover"] = mUri //overChecker = "" when(socialChecker) { "linkedin" -> { mapSocial["linkedin"] = "https://$str" } "github" -> { mapSocial["github"] = "https://www.github.com/$str" } "stackof" -> { mapSocial["stackof"] = "https://$str" } } UserReference!!.updateChildren(mapSocial).addOnCompleteListener{ task -> if (task.isSuccessful) { Toast.makeText(context, "Updated Successfully!", Toast.LENGTH_SHORT).show() } } } private fun pickImage() { val intent = Intent() intent.type = "image/*" intent.action = Intent.ACTION_GET_CONTENT startActivityForResult(intent, RequestCode ) } override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) { super.onActivityResult(requestCode, resultCode, data) if(requestCode == RequestCode && resultCode == Activity.RESULT_OK && data!!.data != null) { imageUri = data.data Toast.makeText(context, "Uploading!", Toast.LENGTH_LONG).show() uploadImageToDatabase() } } private fun uploadImageToDatabase() { val progressBar = ProgressDialog(context) progressBar.setMessage("Image is uploading, please wait!") progressBar.show() if (imageUri!=null && coverChecker == "cover") { val fileRef = StorageRef!!.child(firebaseUser!!.uid.toString()+"Cover Pic") var uploadTask: StorageTask<*> uploadTask = fileRef.putFile(imageUri!!) uploadTask.continueWithTask(Continuation < UploadTask.TaskSnapshot, Task<Uri>>{ task -> if (!task.isSuccessful) { task.exception?.let{ throw it } } return@Continuation fileRef.downloadUrl } ).addOnCompleteListener{ task -> if (task.isSuccessful) { val downloadUrl = task.result val mUri = downloadUrl.toString() if(coverChecker == "cover") { val mapCoverImg = HashMap<String, Any>() mapCoverImg["cover"] = mUri UserReference!!.updateChildren(mapCoverImg) coverChecker = "" } else { val mapProfileImg = HashMap<String, Any>() mapProfileImg["profile"] = mUri UserReference!!.updateChildren(mapProfileImg) mapProfileImg["image_url"] = mUri UserReferenceM!!.updateChildren(mapProfileImg) coverChecker = "" } progressBar.dismiss() } } } else if (imageUri!=null) { val fileRef = StorageRef!!.child(firebaseUser!!.uid.toString()) var uploadTask: StorageTask<*> uploadTask = fileRef.putFile(imageUri!!) uploadTask.continueWithTask(Continuation < UploadTask.TaskSnapshot, Task<Uri>>{ task -> if (!task.isSuccessful) { task.exception?.let{ throw it } } return@Continuation fileRef.downloadUrl } ).addOnCompleteListener{ task -> if (task.isSuccessful) { val downloadUrl = task.result val mUri = downloadUrl.toString() if(coverChecker == "cover") { val mapCoverImg = HashMap<String, Any>() mapCoverImg["cover"] = mUri UserReference!!.updateChildren(mapCoverImg) coverChecker = "" } else { val mapProfileImg = HashMap<String, Any>() mapProfileImg["profile"] = mUri UserReference!!.updateChildren(mapProfileImg) mapProfileImg["image_url"] = mUri UserReferenceM!!.updateChildren(mapProfileImg) coverChecker = "" } progressBar.dismiss() } } } } }
0
Kotlin
0
0
19104b25c35b3dde3123d031838a43d3e869a2cb
9,516
HACK-GUJARAT-SUBMISSION
Boost Software License 1.0
demo/src/main/java/de/check24/compose/demo/features/tablayout/AndroidUITabItemActivity.kt
check24-profis
469,706,312
false
null
package de.check24.compose.demo.features.tablayout import android.os.Bundle import androidx.appcompat.app.AppCompatActivity import de.check24.compose.demo.R import de.check24.compose.demo.databinding.TabItemBinding class AndroidUITabItemActivity : AppCompatActivity(){ private lateinit var binding : TabItemBinding override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) binding = TabItemBinding.inflate(layoutInflater) setContentView(binding.root) supportActionBar?.title = "TabItem" binding.tabItemText.apply { addTab(newTab().setText("MUSIC")) addTab(newTab().setText("MARKET")) addTab(newTab().setText("FILMS")) addTab(newTab().setText("BOOKS")) } binding.tabItemIcons.apply { addTab(newTab().setIcon(R.drawable.ic_baseline_save_24)) addTab(newTab().setIcon(R.drawable.ic_baseline_date_range)) addTab(newTab().setIcon(R.drawable.ic_baseline_favorite_24)) addTab(newTab().setIcon(R.drawable.ic_baseline_cloud_download_24)) } binding.tabItemTextAndIcons.apply { addTab(newTab().setText("MUSIC").setIcon(R.drawable.ic_baseline_save_24)) addTab(newTab().setText("MARKET").setIcon(R.drawable.ic_baseline_date_range)) addTab(newTab().setText("FILMS").setIcon(R.drawable.ic_baseline_favorite_24)) addTab(newTab().setText("BOOKS").setIcon(R.drawable.ic_baseline_cloud_download_24)) } } }
0
Kotlin
3
11
abd64a7d2edac0dbedb4d67d3c0f7b49d9173b88
1,558
jetpack-compose-is-like-android-view
MIT License
sources/base/ui/src/main/kotlin/com/egoriku/ladyhappy/ui/dialog/BaseDialogFragment.kt
egorikftp
102,286,802
false
null
package com.egoriku.ladyhappy.ui.dialog import android.app.Dialog import android.content.DialogInterface import android.os.Bundle import android.view.KeyEvent import androidx.appcompat.app.AppCompatDialogFragment import com.egoriku.ladyhappy.ui.R import com.google.android.material.dialog.MaterialAlertDialogBuilder abstract class BaseDialogFragment : AppCompatDialogFragment(), DialogInterface.OnClickListener { override fun onCreateDialog(savedInstanceState: Bundle?): Dialog { val builder = MaterialAlertDialogBuilder(requireContext()) .setTitle(dialogTitleResId) return onBuildDialog(builder, savedInstanceState) .setOnKeyListener { _, keyCode, event -> return@setOnKeyListener keyCode == KeyEvent.KEYCODE_BACK && event.action == KeyEvent.ACTION_UP } .setPositiveButton(R.string.ok, this) .setNegativeButton(R.string.cancel, this) .create() } override fun onClick(dialog: DialogInterface?, which: Int) { when (which) { DialogInterface.BUTTON_POSITIVE -> onPositiveButtonClick() DialogInterface.BUTTON_NEGATIVE -> onNegativeButtonClick() } } abstract val dialogTitleResId: Int abstract fun onBuildDialog( builder: MaterialAlertDialogBuilder, savedInstanceState: Bundle? ): MaterialAlertDialogBuilder open fun onPositiveButtonClick() = Unit open fun onNegativeButtonClick() = Unit }
12
null
22
261
da53bf026e104b84eebb7c2660c2feae26c6d965
1,534
Lady-happy-Android
Apache License 2.0
features/src/com/jetbrains/completion/feature/impl/FeatureReader.kt
JetBrains
45,971,220
false
null
/* * Copyright 2000-2018 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.jetbrains.completion.feature.impl import com.google.gson.Gson import com.google.gson.reflect.TypeToken typealias DoubleFeatureInfo = Map<String, Double> typealias CategoricalFeatureInfo = Map<String, Set<String>> typealias BinaryFeatureInfo = Map<String, Map<String, Double>> typealias IgnoredFeatureInfo = Set<String> object FeatureUtils { const val UNDEFINED: String = "UNDEFINED" const val INVALID_CACHE: String = "INVALID_CACHE" const val OTHER: String = "OTHER" const val NONE: String = "NONE" const val ML_RANK: String = "ml_rank" const val BEFORE_ORDER: String = "before_rerank_order" const val DEFAULT: String = "default" fun getOtherCategoryFeatureName(name: String): String = "$name=$OTHER" fun getUndefinedFeatureName(name: String): String = "$name=$UNDEFINED" fun prepareRevelanceMap(relevance: List<Pair<String, Any?>>, position: Int, prefixLength: Int, elementLength: Int) : Map<String, Any> { val relevanceMap = mutableMapOf<String, Any>() for ((name, value) in relevance) { if(value == null) continue if (name == "proximity") { val proximityMap = value.toString().toProximityMap() relevanceMap.putAll(proximityMap) } else { relevanceMap[name] = value } } relevanceMap["position"] = position relevanceMap["query_length"] = prefixLength relevanceMap["result_length"] = elementLength return relevanceMap } /** * Proximity features now came like [samePsiFile=true, openedInEditor=false], need to convert to proper map */ private fun String.toProximityMap(): Map<String, Any> { val items = replace("[", "").replace("]", "").split(",") return items.map { val (key, value) = it.trim().split("=") "prox_$key" to value }.toMap() } } object FeatureReader { private val gson = Gson() fun completionFactors(): CompletionFactors { val text = fileContent("features/all_features.json") val typeToken = object : TypeToken<Map<String, Set<String>>>() {} val map = gson.fromJson<Map<String, Set<String>>>(text, typeToken.type) val relevance: Set<String> = map["javaRelevance"] ?: emptySet() val proximity: Set<String> = map["javaProximity"] ?: emptySet() return CompletionFactors(proximity, relevance) } fun binaryFactors(): BinaryFeatureInfo { val text = fileContent("features/binary.json") val typeToken = object : TypeToken<BinaryFeatureInfo>() {} return gson.fromJson<BinaryFeatureInfo>(text, typeToken.type) } fun categoricalFactors(): CategoricalFeatureInfo { val text = fileContent("features/categorical.json") val typeToken = object : TypeToken<CategoricalFeatureInfo>() {} return gson.fromJson<CategoricalFeatureInfo>(text, typeToken.type) } fun ignoredFactors(): IgnoredFeatureInfo { val text = fileContent("features/ignored.json") val typeToken = object : TypeToken<IgnoredFeatureInfo>() {} return gson.fromJson<IgnoredFeatureInfo>(text, typeToken.type) } fun doubleFactors(): DoubleFeatureInfo { val text = fileContent("features/float.json") val typeToken = object : TypeToken<DoubleFeatureInfo>() {} return gson.fromJson<DoubleFeatureInfo>(text, typeToken.type) } fun featuresOrder(): Map<String, Int> { val text = fileContent("features/final_features_order.txt") var index = 0 val map = mutableMapOf<String, Int>() text.split("\n").forEach { val featureName = it.trim() map[featureName] = index++ } return map } private fun fileContent(fileName: String): String { val fileStream = FeatureReader.javaClass.classLoader.getResourceAsStream(fileName) return fileStream.reader().readText() } fun jsonMap(fileName: String): List<MutableMap<String, Any>> { val text = fileContent(fileName) val typeToken = object : TypeToken<List<Map<String, Any>>>() {} return gson.fromJson<List<MutableMap<String, Any>>>(text, typeToken.type) } }
2
null
2
8
3db7f480f7996504ee4edf3265469c88f182cae3
4,883
intellij-stats-collector
Apache License 2.0
sample/src/main/java/com/github/aachartmodel/aainfographics/demo/chartcomposer/JSFunctionForAAChartEventsComposer2.kt
AAChartModel
120,119,119
false
{"Kotlin": 171402, "JavaScript": 4670, "HTML": 1152}
package com.github.aachartmodel.aainfographics.demo.chartcomposer import com.github.aachartmodel.aainfographics.aachartcreator.AAChartLineDashStyleType import com.github.aachartmodel.aainfographics.aachartcreator.AAChartStackingType import com.github.aachartmodel.aainfographics.aachartcreator.AAChartType import com.github.aachartmodel.aainfographics.aachartcreator.AAOptions import com.github.aachartmodel.aainfographics.aachartcreator.AASeriesElement import com.github.aachartmodel.aainfographics.aaoptionsmodel.AAChart import com.github.aachartmodel.aainfographics.aaoptionsmodel.AAChartEvents import com.github.aachartmodel.aainfographics.aaoptionsmodel.AACrosshair import com.github.aachartmodel.aainfographics.aaoptionsmodel.AADataLabels import com.github.aachartmodel.aainfographics.aaoptionsmodel.AAMarker import com.github.aachartmodel.aainfographics.aaoptionsmodel.AAPlotOptions import com.github.aachartmodel.aainfographics.aaoptionsmodel.AASeries import com.github.aachartmodel.aainfographics.aaoptionsmodel.AAStyle import com.github.aachartmodel.aainfographics.aaoptionsmodel.AATitle import com.github.aachartmodel.aainfographics.aaoptionsmodel.AATooltip import com.github.aachartmodel.aainfographics.aaoptionsmodel.AAXAxis import com.github.aachartmodel.aainfographics.aaoptionsmodel.AAYAxis import com.github.aachartmodel.aainfographics.aatools.AAColor object JSFunctionForAAChartEventsComposer2 { //https://github.com/AAChartModel/AAChartKit/issues/1557 //https://github.com/AAChartModel/AAChartCore/issues/199 //https://developer.mozilla.org/zh-CN/docs/Web/API/Touch_events/Using_Touch_Events //https://developer.mozilla.org/zh-CN/docs/Web/API/MouseEvent /* 在 JavaScript 中,与触摸事件对应的鼠标事件分别是: - `touchstart` 对应 `mousedown` - `touchend` 对应 `mouseup` 因此,将你的代码中的触摸事件改为鼠标事件后,代码可以改写为: 1. ```javascript // 监听 mousedown 事件 container.addEventListener('mousedown', function() { hideDataLabels(chart); }); // 监听 mouseup 事件 container.addEventListener('mouseup', function() { showDataLabels(chart); }); ``` 或者也可以改成为: 2. ```javascript // 监听 mouseenter 事件 container.addEventListener('mouseenter', function() { hideDataLabels(chart); }); // 监听 mouseleave 事件 container.addEventListener('mouseleave', function() { showDataLabels(chart); }); ``` */ fun toggleDataLabelsOnTouch(): AAOptions { val options = AAOptions() .chart(AAChart() .type(AAChartType.Areaspline) .events(AAChartEvents() .load(""" function() { const chart = this; const container = document.getElementById('container'); container.addEventListener('touchstart', function() { hideDataLabels(chart); }); container.addEventListener('touchend', function() { showDataLabels(chart); }); function hideDataLabels(chart) { chart.series.forEach(function(series) { series.data.forEach(function(point) { point.update({ dataLabels: { enabled: false } }); }); }); } function showDataLabels(chart) { chart.series.forEach(function(series) { series.data.forEach(function(point) { point.update({ dataLabels: { enabled: true } }); }); }); } } """.trimIndent()))) .xAxis(AAXAxis() .categories(arrayOf("一月", "二月", "三月", "四月", "五月", "六月", "七月", "八月", "九月", "十月", "十一月", "十二月"))) .series(arrayOf( AASeriesElement() .data(arrayOf(7.0, 6.9, 2.5, 14.5, 18.2, 21.5, 5.2, 26.5, 23.3, 45.3, 13.9, 9.6)) .dataLabels(AADataLabels() .enabled(true)) .marker(AAMarker() .lineColor(AAColor.Red) .lineWidth(3f) .radius(10f)) )) return options } //https://github.com/AAChartModel/AAChartKit/issues/1557 /* 🖱鼠标事件 function () { const chart = this; let currentIndex = 0; let intervalId; let isHovered = false; function moveTooltip() { const pointsToShow = []; for (let i = 0; i < chart.series.length; i++) { const point = chart.series[i].points[currentIndex]; if (point) { pointsToShow.push(point); } } if (pointsToShow.length > 0) { chart.tooltip.refresh(pointsToShow); chart.xAxis[0].drawCrosshair(null, pointsToShow[0]); currentIndex = (currentIndex + 1) % chart.series[0].points.length; } } function startInterval() { if (intervalId) { clearInterval(intervalId); } intervalId = setInterval(moveTooltip, 2000); // 每2秒切换一次 } // 立即显示第一个点的 tooltip 和十字线 moveTooltip(); // 初始启动 interval startInterval(); // 鼠标进入图表 chart.container.onmouseenter = function() { isHovered = true; if (intervalId) { clearInterval(intervalId); intervalId = null; } }; // 鼠标在图表上移动 chart.container.onmousemove = function(e) { if (isHovered) { const event = chart.pointer.normalize(e); const point = chart.series[0].searchPoint(event, true); // 可以考虑使用更通用的方法选择点 if (point) { currentIndex = chart.series[0].points.indexOf(point); const pointsToShow = []; for (let i = 0; i < chart.series.length; i++) { const pointInSeries = chart.series[i].points[currentIndex]; if (pointInSeries) { pointsToShow.push(pointInSeries); } } chart.tooltip.refresh(pointsToShow); chart.xAxis[0].drawCrosshair(event, point); } } }; // 鼠标离开图表 chart.container.onmouseleave = function() { isHovered = false; if (!intervalId) { // 立即移动到下一个点,然后开始 interval moveTooltip(); startInterval(); } }; // 在图表销毁时清除 interval this.callbacks.push(function() { if (intervalId) { clearInterval(intervalId); } }); } */ /* 👋手势事件 function() { const chart = this; let currentIndex = 0; let intervalId; let isTouched = false; function moveTooltip() { const pointsToShow = []; for (let i = 0; i < chart.series.length; i++) { const point = chart.series[i].points[currentIndex]; if (point) { pointsToShow.push(point); } } if (pointsToShow.length > 0) { chart.tooltip.refresh(pointsToShow); chart.xAxis[0].drawCrosshair(null, pointsToShow[0]); currentIndex = (currentIndex + 1) % chart.series[0].points.length; } } function startInterval() { if (intervalId) { clearInterval(intervalId); } intervalId = setInterval(moveTooltip, 2000); // 每2秒切换一次 } // 立即显示第一个点的 tooltip 和十字线 moveTooltip(); // 初始启动 interval startInterval(); // 触摸开始 chart.container.ontouchstart = function(e) { isTouched = true; if (intervalId) { clearInterval(intervalId); intervalId = null; } handleTouch(e); }; // 触摸移动 chart.container.ontouchmove = function(e) { if (isTouched) { handleTouch(e); } }; function handleTouch(e) { e.preventDefault(); // 阻止默认的滚动行为 const touch = e.touches[0]; const event = chart.pointer.normalize(touch); const point = chart.series[0].searchPoint(event, true); if (point) { currentIndex = chart.series[0].points.indexOf(point); const pointsToShow = []; for (let i = 0; i < chart.series.length; i++) { const pointInSeries = chart.series[i].points[currentIndex]; if (pointInSeries) { pointsToShow.push(pointInSeries); } } chart.tooltip.refresh(pointsToShow); chart.xAxis[0].drawCrosshair(event, point); } } // 触摸结束 chart.container.ontouchend = function() { isTouched = false; if (!intervalId) { // 立即移动到下一个点,然后开始 interval moveTooltip(); startInterval(); } }; // 在图表销毁时清除 interval this.callbacks.push(function() { if (intervalId) { clearInterval(intervalId); } }); } */ fun createChartOptions(): AAOptions { return AAOptions() .title(AATitle() .text("Auto Crosshair And Tooltip")) .chart(AAChart() .type(AAChartType.Areaspline) .events(AAChartEvents() .load(""" function() { const chart = this; let currentIndex = 0; let intervalId; let isTouched = false; function moveTooltip() { const pointsToShow = []; for (let i = 0; i < chart.series.length; i++) { const point = chart.series[i].points[currentIndex]; if (point) { pointsToShow.push(point); } } if (pointsToShow.length > 0) { chart.tooltip.refresh(pointsToShow); chart.xAxis[0].drawCrosshair(null, pointsToShow[0]); currentIndex = (currentIndex + 1) % chart.series[0].points.length; } } function startInterval() { if (intervalId) { clearInterval(intervalId); } intervalId = setInterval(moveTooltip, 2000); } moveTooltip(); startInterval(); chart.container.ontouchstart = function(e) { isTouched = true; if (intervalId) { clearInterval(intervalId); intervalId = null; } handleTouch(e); }; chart.container.ontouchmove = function(e) { if (isTouched) { handleTouch(e); } }; function handleTouch(e) { e.preventDefault(); const touch = e.touches[0]; const event = chart.pointer.normalize(touch); const point = chart.series[0].searchPoint(event, true); if (point) { currentIndex = chart.series[0].points.indexOf(point); const pointsToShow = []; for (let i = 0; i < chart.series.length; i++) { const pointInSeries = chart.series[i].points[currentIndex]; if (pointInSeries) { pointsToShow.push(pointInSeries); } } chart.tooltip.refresh(pointsToShow); chart.xAxis[0].drawCrosshair(event, point); } } chart.container.ontouchend = function() { isTouched = false; if (!intervalId) { moveTooltip(); startInterval(); } }; this.callbacks.push(function() { if (intervalId) { clearInterval(intervalId); } }); } """.trimIndent()))) .colors(arrayOf("#04d69f", "#1e90ff", "#ef476f", "#ffd066")) .plotOptions(AAPlotOptions() .series(AASeries() .stacking(AAChartStackingType.Normal) .marker(AAMarker() .radius(0)))) .tooltip(AATooltip() .style(AAStyle().color(AAColor.White)) .backgroundColor("#050505") .borderColor("#050505")) .xAxis(AAXAxis() .crosshair(AACrosshair() .color(AAColor.DarkGray) .dashStyle(AAChartLineDashStyleType.LongDashDotDot) .width(2f))) .yAxis(AAYAxis() .visible(false)) .series(arrayOf( AASeriesElement() .name("Tokyo Hot") .lineWidth(5.0f) .fillOpacity(0.4f) .data(arrayOf(0.45, 0.43, 0.50, 0.55, 0.58, 0.62, 0.83, 0.39, 0.56, 0.67, 0.50, 0.34, 0.50, 0.67, 0.58, 0.29, 0.46, 0.23, 0.47, 0.46, 0.38, 0.56, 0.48, 0.36)), AASeriesElement() .name("Berlin Hot") .lineWidth(5.0f) .fillOpacity(0.4f) .data(arrayOf(0.38, 0.31, 0.32, 0.32, 0.64, 0.66, 0.86, 0.47, 0.52, 0.75, 0.52, 0.56, 0.54, 0.60, 0.46, 0.63, 0.54, 0.51, 0.58, 0.64, 0.60, 0.45, 0.36, 0.67)), AASeriesElement() .name("London Hot") .lineWidth(5.0f) .fillOpacity(0.4f) .data(arrayOf(0.46, 0.32, 0.53, 0.58, 0.86, 0.68, 0.85, 0.73, 0.69, 0.71, 0.91, 0.74, 0.60, 0.50, 0.39, 0.67, 0.55, 0.49, 0.65, 0.45, 0.64, 0.47, 0.63, 0.64)), AASeriesElement() .name("NewYork Hot") .lineWidth(5.0f) .fillOpacity(0.4f) .data(arrayOf(0.60, 0.51, 0.52, 0.53, 0.64, 0.84, 0.65, 0.68, 0.63, 0.47, 0.72, 0.60, 0.65, 0.74, 0.66, 0.65, 0.71, 0.59, 0.65, 0.77, 0.52, 0.53, 0.58, 0.53)) )) } }
94
Kotlin
117
996
4b2fe6526dac0a28b8a18ef44ac8c262c1a67e7d
15,881
AAChartCore-Kotlin
Apache License 2.0
tool/automation/framework/app/src/main/kotlin/com/jetbrains/teamcity/docker/hub/DockerRegistryAccessor.kt
JetBrains
261,739,564
false
{"Dockerfile": 199712, "C#": 194974, "Kotlin": 50785, "Batchfile": 18861, "Shell": 13946, "Python": 6106, "PowerShell": 5194}
package com.jetbrains.teamcity.docker.hub import com.jetbrains.teamcity.common.constants.ValidationConstants import com.jetbrains.teamcity.common.network.HttpRequestsUtilities import com.jetbrains.teamcity.docker.DockerImage import com.jetbrains.teamcity.docker.hub.auth.DockerhubCredentials import com.jetbrains.teamcity.docker.hub.data.DockerRegistryInfoAboutImages import com.jetbrains.teamcity.docker.hub.data.DockerRepositoryInfo import com.jetbrains.teamcity.docker.hub.data.DockerhubPersonalAccessToken import kotlinx.serialization.decodeFromString import kotlinx.serialization.json.Json import kotlinx.serialization.json.JsonObject import kotlinx.serialization.json.JsonPrimitive import java.net.http.HttpResponse /** * Provides access to Docker registry. * @param uri - Docker Registry URI * @param credentials - (optional) - credentials for the access of Dockerhub REST API */ class DockerRegistryAccessor(private val uri: String, private val ignoreStaging: Boolean, credentials: DockerhubCredentials?) { private val httpRequestsUtilities: HttpRequestsUtilities = HttpRequestsUtilities() private val token: String? private val jsonSerializer: Json = Json { // -- remove the necessity to include parsing of unused fields ignoreUnknownKeys = true // -- parse JSON fields that don't have an assigned serializer into a String, e.g.: Number isLenient = true } init { this.token = if (credentials != null && credentials.isUsable()) this.getPersonalAccessToken(credentials) else "" } constructor(uri: String, credentials: DockerhubCredentials?) : this(uri, false, credentials) /** * Returns general information about Docker Repository. * @param image image for which the "repository" (all associated images: OS, OS Version, arch.) would be ... * ... retrieved. * @return information about the repository; null in case inaccessible */ fun getRepositoryInfo(image: DockerImage): DockerRepositoryInfo { val registryResponse: HttpResponse<String?> = this.httpRequestsUtilities.getJsonWithAuth( "${this.uri}/repositories/${image.repo}/tags/${image.tag}", this.token ) val result = registryResponse.body() ?: "" if (!this.httpRequestsUtilities.isResponseSuccessful(registryResponse) || result.isEmpty()) { throw IllegalStateException("Unable to get information about the repository from Docker registry: $registryResponse") } return jsonSerializer.decodeFromString(result) } /** * Returns information about images within given registry. * @param image image from given registry * @param pageSize maximal amount of images to be included into Dockerhub's response */ fun getInfoAboutImagesInRegistry(image: DockerImage, pageSize: Int): DockerRegistryInfoAboutImages? { val repo = if (ignoreStaging) image.repo.replace(ValidationConstants.STAGING_POSTFIX, "") else image.repo val registryResponse: HttpResponse<String?> = httpRequestsUtilities.getJsonWithAuth( "${this.uri}/repositories" + "/${repo}/tags?page_size=$pageSize", this.token ) val result = registryResponse.body() ?: "" if (!this.httpRequestsUtilities.isResponseSuccessful(registryResponse) || result.isEmpty()) { throw IllegalStateException("Unable to get information about the repository from Docker registry: $registryResponse") } return jsonSerializer.decodeFromString(result) } /** * Determines previous image pushed into the registry. * @param currentImage original Docker image * @param targetOs Operating System for which previous image should be found. Multiple images might have an equal ... * ... repository and tags, but different target OS. The size will be different as well. * @param osVersion - version of operating system. Used mostly for Windows images. */ fun getPreviousImages( currentImage: DockerImage, targetOs: String = "linux", osVersion: String? = "" ): DockerRepositoryInfo? { val registryInfo = this.getInfoAboutImagesInRegistry(currentImage, 50) if (registryInfo == null) { print("Registry information for given image was not found: $currentImage") return null } // get the TAG of previous image. It might have multiple corresponding images (same tag, but different target OS) val previousImageRepository = registryInfo.results // Remove current & EAP (non-production) tags .asSequence() .filter { return@filter ((it.name != currentImage.tag) // EAP & latest && (!it.name.contains(ValidationConstants.PRE_PRODUCTION_IMAGE_PREFIX)) && (!it.name.contains(ValidationConstants.LATEST))) } // Remove releases that were after the image under test .filter { return@filter isPrevRelease(it.name, currentImage.tag) } // lookup previous image for specific distribution, e.g. 2023.05-linux, 2023.05-windowsservercore, etc. .filter { return@filter isSameDistribution(currentImage.tag, it.name) } // Sort based on tag .sortedWith { lhs, rhs -> imageTagComparator(lhs.name, rhs.name) } .lastOrNull() ?: throw RuntimeException("Previous images weren't found for $currentImage") // -- 1. Filter by OS type previousImageRepository.images = previousImageRepository.images.filter { it.os == targetOs } if (previousImageRepository.images.isNotEmpty() && !osVersion.isNullOrEmpty()) { // --- 2. Filter by OS version (e.g. specific version of Windows, Linux) val imagesFilteredByTarget = previousImageRepository.images.filter { it.osVersion.equals(osVersion) } if (imagesFilteredByTarget.isEmpty()) { // Found images that matches OS type, but doesn't match OS version, e.g. ... // ... - Previous: teamcity-agent:2022.10.1--windowsservercore-2004 (Windows 10.0.17763.3650) // ... - Current : teamcity-agent:2022.10.2-windowsservercore-2004 (Windows 10.0.17763.3887) println( "$currentImage - found previous image - ${previousImageRepository.name}, but OS version is " + "different - $osVersion and ${previousImageRepository.images.first().osVersion} \n" + "Images with mismatching OS versions, but matching tags will be compared." ) return previousImageRepository } previousImageRepository.images = imagesFilteredByTarget } return previousImageRepository } /** * Compares image tags, e.g. (2023.05.1 > 2023.05) */ private fun imageTagComparator(lhsImageTag: String, rhsImageTag: String): Int { val lhsTagComponents = lhsImageTag.split("-")[0].split(".").map { it.toIntOrNull() } val rhsTagComponents = rhsImageTag.split("-")[0].split(".").map { it.toIntOrNull() } for (i in 0 until maxOf(lhsTagComponents.size, rhsTagComponents.size)) { // e.g. 2023.05 transforms into 2023.05.0 for comparison purposes val lhsTagComponent: Int = lhsTagComponents.getOrNull(i) ?: 0 val rhsTagComponent = rhsTagComponents.getOrNull(i) ?: 0 if (lhsTagComponent != rhsTagComponent) { return lhsTagComponent.compareTo(rhsTagComponent) } } return lhsTagComponents.size.compareTo(rhsTagComponents.size) } /** * returns true if lhs was earlier release than rhs */ private fun isPrevRelease(lhsTag: String, rhsTag: String): Boolean { return imageTagComparator(lhsTag, rhsTag) < 0 } /** * Returns true if both images below to the same distribution, e.g. lhs="2023.05.1-windowsservercore", rhs= ... * ...="2023.05-windowsservercore" will return true. */ private fun isSameDistribution(lhsTag: String, rhsTag: String): Boolean { val nameComponents = lhsTag.split("-") if (nameComponents.size == 1) { // e.g. "2023.05" return true } return try { // 2023.05-linux-amd64 => linux-amd64 val something = lhsTag.split("-", limit = 2)[1] rhsTag.contains(something) } catch (e: Exception) { println("Image name does not match the expected pattern, thus would be filtered out: $rhsTag") false } } /** * Creates a session-based Personal Access Token (PAT) for DockerHub REST API access to private repositories. * See: https://docs.docker.com/docker-hub/api/latest/#tag/authentication/operation/PostUsersLogin * @param credentials - objects containing username and access token * @return session-based personal-access token (PAT) */ private fun getPersonalAccessToken(credentials: DockerhubCredentials): String { val webTokenRequestBody = JsonObject( mapOf( "username" to JsonPrimitive(credentials.username), // instead of "password", we could supply persistent personal-access token ... // ... to generate JSON Web Token (JWT) "password" to JsonPrimitive(credentials.token) ) ) val response = httpRequestsUtilities.putJsonWithAuth( "${this.uri}/users/login", webTokenRequestBody.toString() ) if (response.body().isNullOrEmpty()) { throw RuntimeException("Unable to obtain Dockerhub JSON Web Token, status: ${response.statusCode()}") } if (response.statusCode() == 401) { throw IllegalArgumentException("Unable to generate Dockerhub JSON Web Token - provided credentials are incorrect \n ${response.body()}") } else if (response.statusCode() == 429) { throw IllegalStateException("Unable to generate Dockerhub JSON Web Token - credentials are incorrect with too many failed attempts.") } // Retrieve web token in JSON format as string val webTokenJsonString = response.body() ?: "" if (webTokenJsonString.isEmpty()) { throw RuntimeException("Failed to obtain JSON Web Token - response body is empty. \n $response \n ${this.uri}") } val authResponseJson = jsonSerializer.decodeFromString<DockerhubPersonalAccessToken>(webTokenJsonString) return authResponseJson.token } }
9
Dockerfile
58
97
883ff049c2a47c0443c00b4c32425bd29efac01c
10,770
teamcity-docker-images
Apache License 2.0
tool/automation/framework/app/src/main/kotlin/com/jetbrains/teamcity/docker/hub/DockerRegistryAccessor.kt
JetBrains
261,739,564
false
{"Dockerfile": 199712, "C#": 194974, "Kotlin": 50785, "Batchfile": 18861, "Shell": 13946, "Python": 6106, "PowerShell": 5194}
package com.jetbrains.teamcity.docker.hub import com.jetbrains.teamcity.common.constants.ValidationConstants import com.jetbrains.teamcity.common.network.HttpRequestsUtilities import com.jetbrains.teamcity.docker.DockerImage import com.jetbrains.teamcity.docker.hub.auth.DockerhubCredentials import com.jetbrains.teamcity.docker.hub.data.DockerRegistryInfoAboutImages import com.jetbrains.teamcity.docker.hub.data.DockerRepositoryInfo import com.jetbrains.teamcity.docker.hub.data.DockerhubPersonalAccessToken import kotlinx.serialization.decodeFromString import kotlinx.serialization.json.Json import kotlinx.serialization.json.JsonObject import kotlinx.serialization.json.JsonPrimitive import java.net.http.HttpResponse /** * Provides access to Docker registry. * @param uri - Docker Registry URI * @param credentials - (optional) - credentials for the access of Dockerhub REST API */ class DockerRegistryAccessor(private val uri: String, private val ignoreStaging: Boolean, credentials: DockerhubCredentials?) { private val httpRequestsUtilities: HttpRequestsUtilities = HttpRequestsUtilities() private val token: String? private val jsonSerializer: Json = Json { // -- remove the necessity to include parsing of unused fields ignoreUnknownKeys = true // -- parse JSON fields that don't have an assigned serializer into a String, e.g.: Number isLenient = true } init { this.token = if (credentials != null && credentials.isUsable()) this.getPersonalAccessToken(credentials) else "" } constructor(uri: String, credentials: DockerhubCredentials?) : this(uri, false, credentials) /** * Returns general information about Docker Repository. * @param image image for which the "repository" (all associated images: OS, OS Version, arch.) would be ... * ... retrieved. * @return information about the repository; null in case inaccessible */ fun getRepositoryInfo(image: DockerImage): DockerRepositoryInfo { val registryResponse: HttpResponse<String?> = this.httpRequestsUtilities.getJsonWithAuth( "${this.uri}/repositories/${image.repo}/tags/${image.tag}", this.token ) val result = registryResponse.body() ?: "" if (!this.httpRequestsUtilities.isResponseSuccessful(registryResponse) || result.isEmpty()) { throw IllegalStateException("Unable to get information about the repository from Docker registry: $registryResponse") } return jsonSerializer.decodeFromString(result) } /** * Returns information about images within given registry. * @param image image from given registry * @param pageSize maximal amount of images to be included into Dockerhub's response */ fun getInfoAboutImagesInRegistry(image: DockerImage, pageSize: Int): DockerRegistryInfoAboutImages? { val repo = if (ignoreStaging) image.repo.replace(ValidationConstants.STAGING_POSTFIX, "") else image.repo val registryResponse: HttpResponse<String?> = httpRequestsUtilities.getJsonWithAuth( "${this.uri}/repositories" + "/${repo}/tags?page_size=$pageSize", this.token ) val result = registryResponse.body() ?: "" if (!this.httpRequestsUtilities.isResponseSuccessful(registryResponse) || result.isEmpty()) { throw IllegalStateException("Unable to get information about the repository from Docker registry: $registryResponse") } return jsonSerializer.decodeFromString(result) } /** * Determines previous image pushed into the registry. * @param currentImage original Docker image * @param targetOs Operating System for which previous image should be found. Multiple images might have an equal ... * ... repository and tags, but different target OS. The size will be different as well. * @param osVersion - version of operating system. Used mostly for Windows images. */ fun getPreviousImages( currentImage: DockerImage, targetOs: String = "linux", osVersion: String? = "" ): DockerRepositoryInfo? { val registryInfo = this.getInfoAboutImagesInRegistry(currentImage, 50) if (registryInfo == null) { print("Registry information for given image was not found: $currentImage") return null } // get the TAG of previous image. It might have multiple corresponding images (same tag, but different target OS) val previousImageRepository = registryInfo.results // Remove current & EAP (non-production) tags .asSequence() .filter { return@filter ((it.name != currentImage.tag) // EAP & latest && (!it.name.contains(ValidationConstants.PRE_PRODUCTION_IMAGE_PREFIX)) && (!it.name.contains(ValidationConstants.LATEST))) } // Remove releases that were after the image under test .filter { return@filter isPrevRelease(it.name, currentImage.tag) } // lookup previous image for specific distribution, e.g. 2023.05-linux, 2023.05-windowsservercore, etc. .filter { return@filter isSameDistribution(currentImage.tag, it.name) } // Sort based on tag .sortedWith { lhs, rhs -> imageTagComparator(lhs.name, rhs.name) } .lastOrNull() ?: throw RuntimeException("Previous images weren't found for $currentImage") // -- 1. Filter by OS type previousImageRepository.images = previousImageRepository.images.filter { it.os == targetOs } if (previousImageRepository.images.isNotEmpty() && !osVersion.isNullOrEmpty()) { // --- 2. Filter by OS version (e.g. specific version of Windows, Linux) val imagesFilteredByTarget = previousImageRepository.images.filter { it.osVersion.equals(osVersion) } if (imagesFilteredByTarget.isEmpty()) { // Found images that matches OS type, but doesn't match OS version, e.g. ... // ... - Previous: teamcity-agent:2022.10.1--windowsservercore-2004 (Windows 10.0.17763.3650) // ... - Current : teamcity-agent:2022.10.2-windowsservercore-2004 (Windows 10.0.17763.3887) println( "$currentImage - found previous image - ${previousImageRepository.name}, but OS version is " + "different - $osVersion and ${previousImageRepository.images.first().osVersion} \n" + "Images with mismatching OS versions, but matching tags will be compared." ) return previousImageRepository } previousImageRepository.images = imagesFilteredByTarget } return previousImageRepository } /** * Compares image tags, e.g. (2023.05.1 > 2023.05) */ private fun imageTagComparator(lhsImageTag: String, rhsImageTag: String): Int { val lhsTagComponents = lhsImageTag.split("-")[0].split(".").map { it.toIntOrNull() } val rhsTagComponents = rhsImageTag.split("-")[0].split(".").map { it.toIntOrNull() } for (i in 0 until maxOf(lhsTagComponents.size, rhsTagComponents.size)) { // e.g. 2023.05 transforms into 2023.05.0 for comparison purposes val lhsTagComponent: Int = lhsTagComponents.getOrNull(i) ?: 0 val rhsTagComponent = rhsTagComponents.getOrNull(i) ?: 0 if (lhsTagComponent != rhsTagComponent) { return lhsTagComponent.compareTo(rhsTagComponent) } } return lhsTagComponents.size.compareTo(rhsTagComponents.size) } /** * returns true if lhs was earlier release than rhs */ private fun isPrevRelease(lhsTag: String, rhsTag: String): Boolean { return imageTagComparator(lhsTag, rhsTag) < 0 } /** * Returns true if both images below to the same distribution, e.g. lhs="2023.05.1-windowsservercore", rhs= ... * ...="2023.05-windowsservercore" will return true. */ private fun isSameDistribution(lhsTag: String, rhsTag: String): Boolean { val nameComponents = lhsTag.split("-") if (nameComponents.size == 1) { // e.g. "2023.05" return true } return try { // 2023.05-linux-amd64 => linux-amd64 val something = lhsTag.split("-", limit = 2)[1] rhsTag.contains(something) } catch (e: Exception) { println("Image name does not match the expected pattern, thus would be filtered out: $rhsTag") false } } /** * Creates a session-based Personal Access Token (PAT) for DockerHub REST API access to private repositories. * See: https://docs.docker.com/docker-hub/api/latest/#tag/authentication/operation/PostUsersLogin * @param credentials - objects containing username and access token * @return session-based personal-access token (PAT) */ private fun getPersonalAccessToken(credentials: DockerhubCredentials): String { val webTokenRequestBody = JsonObject( mapOf( "username" to JsonPrimitive(credentials.username), // instead of "password", we could supply persistent personal-access token ... // ... to generate JSON Web Token (JWT) "password" to JsonPrimitive(credentials.token) ) ) val response = httpRequestsUtilities.putJsonWithAuth( "${this.uri}/users/login", webTokenRequestBody.toString() ) if (response.body().isNullOrEmpty()) { throw RuntimeException("Unable to obtain Dockerhub JSON Web Token, status: ${response.statusCode()}") } if (response.statusCode() == 401) { throw IllegalArgumentException("Unable to generate Dockerhub JSON Web Token - provided credentials are incorrect \n ${response.body()}") } else if (response.statusCode() == 429) { throw IllegalStateException("Unable to generate Dockerhub JSON Web Token - credentials are incorrect with too many failed attempts.") } // Retrieve web token in JSON format as string val webTokenJsonString = response.body() ?: "" if (webTokenJsonString.isEmpty()) { throw RuntimeException("Failed to obtain JSON Web Token - response body is empty. \n $response \n ${this.uri}") } val authResponseJson = jsonSerializer.decodeFromString<DockerhubPersonalAccessToken>(webTokenJsonString) return authResponseJson.token } }
9
Dockerfile
58
97
883ff049c2a47c0443c00b4c32425bd29efac01c
10,770
teamcity-docker-images
Apache License 2.0
pulsar-skeleton/src/main/kotlin/ai/platon/pulsar/common/options/deprecated/CrawlOptions.kt
platonai
124,882,400
false
null
package ai.platon.pulsar.common.options import ai.platon.pulsar.common.config.CapabilityTypes import ai.platon.pulsar.common.config.ImmutableConfig import ai.platon.pulsar.common.config.Params import ai.platon.pulsar.common.config.PulsarConstants import com.beust.jcommander.Parameter import org.apache.commons.lang3.StringUtils import java.text.DecimalFormat import java.time.Duration import java.time.ZoneId import java.util.* /** * Created by vincent on 17-3-18. * Copyright @ 2013-2017 Platon AI. All rights reserved */ class CrawlOptions : CommonOptions { @Parameter(names = ["-log", "-verbose"], description = "Log level for this crawl task") val verbose = 0 @Parameter(names = ["-i", "--fetch-interval"], converter = DurationConverter::class, description = "Fetch interval") var fetchInterval = Duration.ofHours(1) @Parameter(names = ["-p", "--fetch-priority"], description = "Fetch priority") val fetchPriority = PulsarConstants.FETCH_PRIORITY_DEFAULT @Parameter(names = ["-s", "--score"], description = "Injected score") var score = 0 @Parameter(names = ["-d", "--depth"], description = "Max crawl depth. Do not crawl anything deeper") var depth = 1 @Parameter(names = ["-z", "--zone-id"], description = "The zone id of the website we crawl") var zoneId = ZoneId.systemDefault().id @Parameter(names = ["-w", "--keywords"], converter = WeightedKeywordsConverter::class, description = "Keywords with weight, ") var keywords: Map<String, Double> = HashMap() @Parameter(names = ["-idx", "--indexer-url"], description = "Indexer url") var indexerUrl: String = "" var linkOptions = LinkOptions() private set constructor(): super() { addObjects(this, linkOptions) } constructor(args: String): super(args.replace("=".toRegex(), " ")) { addObjects(this, linkOptions) } constructor(args: String, conf: ImmutableConfig): super(args.replace("=".toRegex(), " ")) { this.init(conf) addObjects(this, linkOptions) } constructor(argv: Array<String>) : super(argv) { addObjects(this, linkOptions) } constructor(argv: Array<String>, conf: ImmutableConfig): super(argv) { this.init(conf) addObjects(this, linkOptions) } constructor(argv: Map<String, String>) : super(argv) { addObjects(this, linkOptions) } constructor(argv: Map<String, String>, conf: ImmutableConfig) : super(argv) { this.init(conf) addObjects(this, linkOptions) } private fun init(conf: ImmutableConfig) { this.fetchInterval = conf.getDuration(CapabilityTypes.FETCH_INTERVAL, fetchInterval) this.score = conf.getInt(CapabilityTypes.INJECT_SCORE, score) this.depth = conf.getUint(CapabilityTypes.CRAWL_MAX_DISTANCE, depth)!! this.linkOptions = LinkOptions("", conf) } fun formatKeywords(): String { val df = DecimalFormat("##.#") return keywords.entries.map { it.key + "^" + df.format(it.value) }.joinToString { it } } override fun getParams(): Params { return Params.of( "-log", verbose, "-i", fetchInterval, "-p", fetchPriority, "-s", score, "-d", depth, "-z", zoneId, "-w", formatKeywords(), "-idx", indexerUrl ) .filter { p -> StringUtils.isNotEmpty(p.value.toString()) } .merge(linkOptions.params) } override fun toString(): String { return params.withKVDelimiter(" ").formatAsLine().replace("\\s+".toRegex(), " ") } companion object { @JvmField val DEFAULT = CrawlOptions() fun parse(args: String, conf: ImmutableConfig): CrawlOptions { Objects.requireNonNull(args) Objects.requireNonNull(conf) if (StringUtils.isBlank(args)) { return CrawlOptions(arrayOf(), conf) } val options = CrawlOptions(args, conf) options.parse() return options } } }
1
null
32
110
f93bccf5075009dc7766442d3a23b5268c721f54
4,148
pulsar
Apache License 2.0
src/test/kotlin/ca/softwareadd/domain/routers/CommandRouterTest.kt
development-sketches
257,418,716
false
null
package ca.softwareadd.domain.routers import ca.softwareadd.country.Country import ca.softwareadd.country.CountryCreatedEvent import ca.softwareadd.country.CreateCountryCommand import ca.softwareadd.domain.resolvers.CommandHandlerResolver import ca.softwareadd.domain.resolvers.CommandTypeResolver import com.fasterxml.jackson.databind.ObjectMapper import org.junit.jupiter.api.Assertions.assertEquals import org.junit.jupiter.api.Test import org.junit.jupiter.api.extension.ExtendWith import org.springframework.beans.factory.annotation.Autowired import org.springframework.context.annotation.Bean import org.springframework.context.annotation.Configuration import org.springframework.context.annotation.Import import org.springframework.test.context.ContextConfiguration import org.springframework.test.context.junit.jupiter.SpringExtension import java.util.* private const val CREATE_COUNTRY_COMMAND = "create-country" @ExtendWith(SpringExtension::class) @ContextConfiguration(classes = [ CommandRouter::class, CommandHandlerResolver::class, CommandTypeResolver::class ]) @Import(CommandRouterTest.TestConfiguration::class) internal class CommandRouterTest { @Autowired private lateinit var router: CommandRouter @Autowired private lateinit var mapper: ObjectMapper @Test internal fun `test handler invocation`() { val events = mutableListOf<Any>() val country = Country(UUID.randomUUID()) { _, event -> events.add(event) } val command = CreateCountryCommand().apply { alpha2code = "CA" alpha3code = "CAN" fullName = "Canada" numericCode = "123" shortName = "Canada" } val json = mapper.writeValueAsString(command) router.route(country, CREATE_COUNTRY_COMMAND, json) assertEquals(1, events.size) val event = events[0] as CountryCreatedEvent assertEquals(command.alpha2code, event.alpha2code) assertEquals(command.alpha3code, event.alpha3code) assertEquals(command.fullName, event.fullName) assertEquals(command.numericCode, event.numericCode) assertEquals(command.shortName, event.shortName) } @Configuration class TestConfiguration { @Bean fun mapper(): ObjectMapper = ObjectMapper() } }
1
Kotlin
1
1
956c79d78d97d33a18c7a81d52e2505c838a2f95
2,337
location-service-sample
MIT License
src/main/kotlin/com/github/subat0m1c/hatecheaters/pvgui/v2/pages/Dungeons.kt
SubAt0m1c
854,316,644
false
{"Kotlin": 145667, "Java": 7021}
package com.github.subat0m1c.hatecheaters.pvgui.v2.pages import com.github.subat0m1c.hatecheaters.pvgui.v2.Pages import com.github.subat0m1c.hatecheaters.pvgui.v2.Pages.centeredText import com.github.subat0m1c.hatecheaters.pvgui.v2.pages.Dungeons.ct import com.github.subat0m1c.hatecheaters.pvgui.v2.utils.Utils.without import com.github.subat0m1c.hatecheaters.pvgui.v2.utils.profileLazy import com.github.subat0m1c.hatecheaters.utils.ApiUtils.cataLevel import com.github.subat0m1c.hatecheaters.utils.ApiUtils.classAverage import com.github.subat0m1c.hatecheaters.utils.ApiUtils.classLevel import com.github.subat0m1c.hatecheaters.utils.ChatUtils.colorClass import com.github.subat0m1c.hatecheaters.utils.ChatUtils.colorize import com.github.subat0m1c.hatecheaters.utils.ChatUtils.colorizeNumber import com.github.subat0m1c.hatecheaters.utils.ChatUtils.commas import com.github.subat0m1c.hatecheaters.utils.ChatUtils.secondsToMinutes import com.github.subat0m1c.hatecheaters.utils.jsonobjects.HypixelProfileData import me.odinmain.utils.capitalizeFirst import me.odinmain.utils.render.getMCTextHeight import me.odinmain.utils.render.mcText import me.odinmain.utils.render.roundedRectangle import me.odinmain.utils.round object Dungeons: Pages.PVPage("Dungeons") { private val cataLineWidth = mainCenterX - mainX - lineY private val cataLineY = mainHeight*0.1 private val cataCenter = mainCenterX - mainWidth/4 private val mmComps: Int by profileLazy { (profile.dungeons.dungeonTypes.mastermode.tierComps.without("total")).values.sum() } private val floorComps: Int by profileLazy { (profile.dungeons.dungeonTypes.catacombs.tierComps.without("total")).values.sum() } private val text: List<String> by profileLazy { listOf( "§bSecrets§7: ${profile.dungeons.secrets.commas.colorizeNumber(100000)}", "§dAverage Secret Count§7: ${(profile.dungeons.secrets.toDouble()/(mmComps + floorComps)).round(2).colorize(15.0)}", "§cBlood Mob Kills§7: ${((profile.playerStats.kills["watcher_summon_undead"] ?: 0) + (profile.playerStats.kills["master_watcher_summon_undead"] ?: 0)).commas}", "§7Spirit Pet: ${if (profile.pets.pets.any { it.type == "SPIRIT" && it.tier == "LEGENDARY" }) "§l§2Found!" else "§o§4Missing!"}", ) } private val textEntryHeight: Double by profileLazy { (mainHeight/2 - (cataLineY + lineY)) / text.size } private val cataText: String by profileLazy { "§4Cata Level§7: §${ct.fontCode}${profile.dungeons.dungeonTypes.cataLevel.round(2).colorize(50)}" } private val classTextList: List<String> by profileLazy { profile.dungeons.classes.entries.map { "${it.key.capitalizeFirst().colorClass}§7: ${it.value.classLevel.round(2).colorize(50)}" } } private val classAverageText: String by profileLazy { "§6Class Average§7: ${profile.dungeons.classAverage.round(2).colorize(50)}" } private val selectedClass: String by profileLazy { "§aSelected Class§7: §${ct.fontCode}${profile.dungeons.selectedClass?.capitalizeFirst()?.colorClass}" } private val classEntryText: List<String> by profileLazy { listOf(selectedClass) + classTextList } private val classEntrySize: Double by profileLazy { (mainHeight/2 - cataLineY + lineY*2)/classEntryText.size } private val floorData: List<String> by profileLazy { (0..7).map { "§3${profile.dungeons.dungeonTypes.catacombs.floorStats(it.toString())}" } } private val mmData: List<String> by profileLazy { (1..7).map { "§cMM ${profile.dungeons.dungeonTypes.mastermode.floorStats(it.toString())}" } } private val floorHeight: Int by profileLazy { (mainHeight/2 - lineY) / floorData.size } private val mmHeight: Int by profileLazy { (mainHeight/2 - lineY) / mmData.size } override fun draw() { roundedRectangle(mainCenterX, lineY, ot, mainHeight, ct.line) centeredText(cataText, cataCenter, lineY + cataLineY/2, 4, ct.font) text.forEachIndexed { i, text -> val y = ((cataLineY + lineY) + textEntryHeight*i + textEntryHeight/2) - (getMCTextHeight()*2.5)/2 mcText(text, mainX, y, 2.5, ct.font, shadow = true, center = false) } centeredText(classAverageText, cataCenter, mainHeight/2 + cataLineY/2, 3.5, ct.font) roundedRectangle(mainX, mainHeight/2 - lineY + cataLineY, cataLineWidth, ot, ct.line) classEntryText.forEachIndexed { i, text -> val y = mainHeight/2 + cataLineY - lineY + classEntrySize*i + classEntrySize/2 if (i == 0) centeredText(text, cataCenter, y, 2.5, ct.font) else mcText(text, mainX, y-(getMCTextHeight()*2.5)/2, 2.5, ct.font, shadow = true, center = false) } roundedRectangle(mainX, cataLineY, cataLineWidth, ot, ct.line) floorData.forEachIndexed { i, text -> val y = lineY + (floorHeight*i) + mmHeight/2 - getMCTextHeight() mcText(text, mainCenterX + ot + lineY, y, 2, ct.font, shadow = true, center = false) } mmData.forEachIndexed { i, text -> val y = lineY + mainHeight/2 + lineY + mmHeight*i + mmHeight/2 - getMCTextHeight() mcText(text, mainCenterX + ot + lineY, y, 2, ct.font, shadow = true, center = false) } roundedRectangle(mainCenterX + ot + lineY, lineY + mainHeight/2, cataLineWidth, ot, ct.line) } } fun HypixelProfileData.DungeonTypeData.floorStats(floor: String): String { val start = if (floor == "0") "Entrance" else "Floor $floor" val string = "$start: §$${ct.fontCode}${this.tierComps[floor]?.commas} " + "§7| §${ct.fontCode}${this.fastestTimes[floor]?.let { secondsToMinutes(it*0.001) } ?: "§cDNF"} " + "§7| §${ct.fontCode}${this.fastestTimeS[floor]?.let { secondsToMinutes(it*0.001) } ?: "§cDNF"} " + "§7| §a${this.fastestTimeSPlus[floor]?.let { secondsToMinutes(it*0.001) } ?: "§cDNF"}" return string }
0
Kotlin
0
1
facc4dbc82ad6aa6d02bb7d52c6d45a1f3c9d4a3
5,904
HateCheaters
MIT License
data/src/main/java/com/no1/taiwan/stationmusicfm/data/data/lastfm/TagTopTrackInfoData.kt
SmashKs
168,842,876
false
null
package com.no1.taiwan.stationmusicfm.data.data.lastfm import com.no1.taiwan.stationmusicfm.data.data.Data data class TagTopTrackInfoData( val tracks: TopTrackInfoData.TracksData ) : Data
0
Kotlin
1
5
696fadc54bc30fe72f9115bdec2dacdac8cd4394
194
StationMusicFM
MIT License
Pokedex/app/src/main/java/com/example/pokedex/view/MainActivity.kt
NicolasNobrega
607,452,286
false
null
package com.example.pokedex.view import androidx.appcompat.app.AppCompatActivity import android.os.Bundle import android.util.Log import android.view.LayoutInflater import androidx.recyclerview.widget.GridLayoutManager import androidx.recyclerview.widget.LinearLayoutManager import androidx.recyclerview.widget.RecyclerView import com.example.pokedex.R import com.example.pokedex.api.PokemonRepository import com.example.pokedex.core.Constants import com.example.pokedex.core.Constants.URL_BASE import com.example.pokedex.databinding.ActivityMainBinding import com.example.pokedex.databinding.PokemonItemBinding import com.example.pokedex.domain.Pokemon import com.example.pokedex.domain.PokemonType class MainActivity : AppCompatActivity() { lateinit var binding: ActivityMainBinding override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) binding = ActivityMainBinding.inflate( layoutInflater ) setContentView(binding.root) // Estuda Coroutines Thread(Runnable { loadPokemons() }).start() } private fun loadPokemons() { val pokemonsApiResult = PokemonRepository.listPokemons() pokemonsApiResult?.results?.let { val pokemons: List<Pokemon?> = it.map { pokemonResult -> val number = pokemonResult.url .replace("${URL_BASE}pokemon/", "") .replace("/", "").toInt() val pokemonApiResult = PokemonRepository.getPokemon(number) pokemonApiResult?.let { Pokemon( pokemonApiResult.id, pokemonApiResult.name, pokemonApiResult.types.map { type -> type.type } ) } } val layoutManager = GridLayoutManager(applicationContext, 2) binding.rvPokemons.post { with(binding) { rvPokemons.layoutManager = layoutManager rvPokemons.adapter = PokemonAdapter(pokemons) } } } } }
0
Kotlin
0
0
d87dfbb110e5503e238ddbbaa53c766e96a5ec17
2,223
Kotlin
MIT License
tripart/src/main/java/com/jn/kiku/ttp/pay/wxpay/WxPayInfoVO.kt
JerrNeon
196,114,074
false
{"Gradle": 8, "Java Properties": 2, "Shell": 1, "Text": 1, "Ignore List": 6, "Batchfile": 1, "Markdown": 1, "Proguard": 43, "INI": 1, "Kotlin": 253, "XML": 83, "Java": 2}
package com.jn.kiku.ttp.pay.wxpay import android.os.Parcelable import kotlinx.parcelize.Parcelize /** * Author:Stevie.Chen Time:2020/09/08 15:25 * Class Comment:微信支付信息实体(自己服务器返回) */ @Parcelize data class WxPayInfoVO( var appid: String?= null,// String 公众账号ID var partnerid: String?= null,// String 商户号 var prepayid: String?= null, // String 预支付交易会话ID var noncestr: String?= null,// String 随机字符串 var timestamp: String?= null,// String 时间戳 var sign: String?= null, //String 签名 var orderid: String?= null// String 商户订单号 ) : Parcelable
0
Kotlin
1
1
bc6675aee4514111981626b48a888efdcbe5ddc2
564
Kiku-kotlin
Apache License 2.0
src/me/anno/mesh/MeshUtils.kt
AntonioNoack
456,513,348
false
null
package me.anno.mesh import me.anno.ecs.Entity import me.anno.ecs.components.collider.Collider import me.anno.ecs.components.mesh.Mesh import me.anno.io.ISaveable import me.anno.mesh.assimp.AnimGameItem import org.joml.* import kotlin.math.abs import kotlin.math.max object MeshUtils { fun centerMesh(stack: Matrix4f, localStack: Matrix4x3f, mesh: Mesh, targetFrameUsage: Float = 0.95f) { mesh.ensureBounds() centerMesh(stack, localStack, AABBd().set(mesh.aabb), { mesh.getBounds(it, false) }, targetFrameUsage) } fun centerMesh(stack: Matrix4f, localStack: Matrix4x3f, mesh: Entity, targetFrameUsage: Float = 0.95f) { mesh.validateAABBs() val aabb = AABBf() centerMesh(stack, localStack, AABBd().set(mesh.aabb), { aabb.set(mesh.aabb) aabb.transform(it) }, targetFrameUsage) } fun centerMesh(stack: Matrix4f, localStack: Matrix4x3f, collider: Collider, targetFrameUsage: Float = 0.95f) { val aabb = AABBd() collider.fillSpace(Matrix4x3d(), aabb) centerMesh(stack, localStack, aabb, { transform -> val aabb2 = AABBd() collider.fillSpace(Matrix4x3d(), aabb2) AABBf().set(aabb2).transformProject(transform) }, targetFrameUsage) } fun centerMesh(stack: Matrix4f, localStack: Matrix4x3f, model0: AnimGameItem, targetFrameUsage: Float = 0.95f) { centerMesh(stack, localStack, model0.staticAABB.value, { model0.getBounds(it) }, targetFrameUsage) } fun centerMesh( transform: ISaveable?, stack: Matrix4f, localStack: Matrix4x3f, model0: AnimGameItem, targetFrameUsage: Float = 0.95f ) { val staticAABB = model0.staticAABB.value if (!staticAABB.isEmpty()) { if (transform == null) { centerMesh(stack, localStack, staticAABB, { model0.getBounds(it) }, targetFrameUsage) } else { AnimGameItem.centerStackFromAABB(localStack, staticAABB) } } } /** * whenever possible, this optimization should be on another thread * (because for high-poly meshes, it is expensive) * */ fun centerMesh( cameraMatrix: Matrix4f, modelMatrix: Matrix4x3f, aabb0: AABBd, getBounds: (Matrix4f) -> AABBf, targetFrameUsage: Float = 0.95f ) { if (aabb0.isEmpty()) return if (modelMatrix.determinant().isNaN()) return // rough approximation using bounding box AnimGameItem.centerStackFromAABB(modelMatrix, aabb0) val modelViewProjectionMatrix = Matrix4f() modelViewProjectionMatrix .set(cameraMatrix) .mul(modelMatrix) val m0 = getBounds(modelViewProjectionMatrix) val dx = m0.avgX() val dy = m0.avgY() val scale = 2f * targetFrameUsage / max(m0.deltaX(), m0.deltaY()) if (abs(dx) + abs(dy) < 5f && scale in 0.1f..10f) { cameraMatrix.translateLocal(-dx, -dy, 0f) cameraMatrix.scaleLocal(scale, scale, scale) } } }
0
null
1
9
b2532f7d40527eb2c9e24e3659dd904aa725a1aa
3,142
RemsEngine
Apache License 2.0
app/src/main/java/com/karl/demo/demo/app/RoomModule.kt
liaodongxiaoxiao
329,031,269
false
null
package com.karl.demo.demo.app import android.content.Context import androidx.room.Room import androidx.room.RoomDatabase import com.karl.demo.demo.model.AppDatabase import com.karl.demo.demo.model.DivisionDAO import dagger.Module import dagger.Provides import dagger.hilt.InstallIn import dagger.hilt.android.qualifiers.ApplicationContext import dagger.hilt.components.SingletonComponent import javax.inject.Singleton @Module @InstallIn(SingletonComponent::class) class RoomModule { @Singleton @Provides fun provideAppDatabase(@ApplicationContext context: Context): AppDatabase { return Room.databaseBuilder( context, AppDatabase::class.java, "weather.db" ).allowMainThreadQueries() .setJournalMode(RoomDatabase.JournalMode.TRUNCATE) .build() } @Singleton @Provides fun provideDivisionDAO(appDatabase: AppDatabase): DivisionDAO { return appDatabase.divisionDao() } }
0
Kotlin
0
0
39147ca3a467f0b5ec8fa99bebe810c8bc33825a
976
DemoForDev
Apache License 2.0
vertk/vertk-cron/src/test/java/com/ufoscout/vertk/cron/exec/IntervalExecutionStrategyTest.kt
ufoscout
134,148,676
false
{"Java": 128496, "Kotlin": 128136}
package com.ufoscout.vertk.cron.exec import com.ufoscout.vertk.BaseTest import org.junit.jupiter.api.Assertions.assertTrue import org.junit.jupiter.api.Test import java.util.* /** * @author <NAME>' 04/giu/2010 */ class IntervalExecutionStrategyTest : BaseTest() { @Test fun testCount() { val interval = 100L val delay = 20L val executionStrategy = IntervalExecutionStrategy(interval, delay) System.out.println(executionStrategy.toString()) assertTrue(executionStrategy.toString().contains("" + interval)) assertTrue(executionStrategy.hasOtherExecution()) var now = Date() assertTrue(interval + delay >= executionStrategy.nextExecutionDateAfter(now).time - now.time) Thread.sleep(delay) now = Date() assertTrue(interval >= executionStrategy.nextExecutionDateAfter(now).time - Date().time) Thread.sleep(interval) assertTrue(executionStrategy.hasOtherExecution()) System.out.println(executionStrategy.toString()) assertTrue(executionStrategy.toString().contains("" + interval)) } }
2
null
1
1
b62a5c6f08ea1ca1f8c907ff1dd316816cba7871
1,123
coreutils-java
MIT License
wear/src/main/java/com/vlad1m1r/watchface/components/ticks/TicksLayoutOriginal.kt
rohitnotes
316,923,584
true
{"Kotlin": 144583}
package com.vlad1m1r.watchface.components.ticks import android.content.Context import android.graphics.Canvas import android.graphics.Paint import com.vlad1m1r.watchface.R import com.vlad1m1r.watchface.data.ColorStorage import com.vlad1m1r.watchface.data.DataStorage import com.vlad1m1r.watchface.model.Mode import com.vlad1m1r.watchface.model.Point import com.vlad1m1r.watchface.utils.getLighterGrayscale import kotlin.math.PI import kotlin.math.cos import kotlin.math.sin class TicksLayoutOriginal( context: Context, dataStorage: DataStorage, colorStorage: ColorStorage ) : TicksLayout(context, dataStorage) { private val tickLength = context.resources.getDimension(R.dimen.original_tick_length) private val watchTickColor = colorStorage.getHourTicksColor() private val tickWidth = context.resources.getDimension(R.dimen.original_tick_width) private val tickBurnInPadding = context.resources.getDimension(R.dimen.original_tick_padding) private var tickPadding = tickBurnInPadding override var centerInvalidated = true private set private val tickPaint = Paint().apply { color = watchTickColor strokeWidth = tickWidth isAntiAlias = true style = Paint.Style.STROKE setShadowLayer( shadowRadius, 0f, 0f, shadowColor ) } private var center = Point() private var outerTickRadius: Float = 0f private var innerTickRadius: Float = 0f override fun setCenter(center: Point) { centerInvalidated = false this.center = center this.outerTickRadius = center.x - tickPadding this.innerTickRadius = center.x - tickLength - tickPadding } override fun draw(canvas: Canvas) { for (tickIndex in 0..11) { val tickRotation = tickIndex * PI / 6 val adjust = if(shouldAdjustToSquareScreen) adjustToSquare(tickRotation) else 1.0 val innerX = sin(tickRotation) * innerTickRadius * adjust val innerY = -cos(tickRotation) * innerTickRadius * adjust val outerX = sin(tickRotation) * outerTickRadius * adjust val outerY = -cos(tickRotation) * outerTickRadius * adjust canvas.drawLine( (center.x + innerX).toFloat(), (center.y + innerY).toFloat(), (center.x + outerX).toFloat(), (center.y + outerY).toFloat(), tickPaint ) } } override fun setMode(mode: Mode) { tickPaint.apply { if (mode.isAmbient) { inAmbientMode(getLighterGrayscale(watchTickColor)) if (mode.isBurnInProtection) { strokeWidth = 0f } } else { inInteractiveMode(watchTickColor) strokeWidth = tickWidth } } tickPadding = if (shouldAdjustForBurnInProtection(mode)) { tickBurnInPadding } else { 0f } centerInvalidated = true } }
0
null
0
0
cf16eb5984e06348d2553a62f9f6117e87c55348
3,004
AnalogWatchFace
Apache License 2.0
app/src/main/java/com/example/myapplication/domain/usecase/GetTopHeadlinesUseCase.kt
DeMoss15
222,141,463
false
null
package com.example.myapplication.domain.usecase import com.example.myapplication.domain.usecase.base.RxUseCaseSingle import com.example.myapplication.data.repository.TopHeadlinesRepository import com.example.myapplication.domain.model.Article import io.reactivex.Single class GetTopHeadlinesUseCase(private val topHeadlinesRepository: TopHeadlinesRepository) : RxUseCaseSingle<List<Article>, GetTopHeadlinesUseCase.Params>() { override fun buildUseCaseObservable(params: Params): Single<List<Article>> = params.let { topHeadlinesRepository.getTopHeadlines(it.page, it.query, it.sources, it.category, it.country) } class Params( var page: Int, var query: String? = null, var sources: String? = null, var category: String? = null, var country: String? = null ) }
0
Kotlin
0
0
bc9dd558000f8fbe996cca82477bea98dd2a5c31
833
PaginatorRenderKit
Apache License 2.0
app/src/main/java/ru/russianpost/digitalperiodicals/utils/Constants.kt
saintedlittle
811,022,037
false
{"Kotlin": 372590}
package ru.russianpost.digitalperiodicals.utils const val MIN_PRICE_VALUE = 1f const val MAX_PRICE_VALUE = 500f const val NO_RESULTS_STATUS = 404 const val NO_RIGHTS_STATUS = 410 const val RC_AUTH = 1 const val RC_END_SESSION = 2 const val ENCRYPTED_SHARED_PREFERENCES = "ENCRYPTED_SHARED_PREFERENCES" const val AUTHENTICATION_TOKEN = "AUTHENTICATION_TOKEN" const val TOKEN_ID = "TOKEN_ID" const val HOST = "https://passport-pre.test.russianpost.ru" const val REDIRECT_URL = "russianpostdpb.pre://callback" const val REDIRECT_LOGOUT_URL = "russianpostdpb.pre://logout" const val CLIENT_ID = "WsgTIZhjqmhRPSZF7dDWhI6jYNIa" const val LOGIN = "login" const val USERNAME_OPENID_EMAIL = "userName openid email" const val SETTINGS_SCREEN = "SETTINGS_SCREEN" const val PUSH_NOTIFICATIONS_SCREEN = "PUSH_NOTIFICATIONS_SCREEN" const val EMAIL_NOTIFICATIONS_SCREEN = "EMAIL_NOTIFICATIONS_SCREEN" const val REGION_SCREEN = "REGION_SCREEN" const val THEME_SCREEN = "THEME_SCREEN" const val PUSH_NOTIFICATIONS_MODE = "PUSH_NOTIFICATIONS_MODE" const val EMAIL_NOTIFICATIONS_MODE = "EMAIL_NOTIFICATIONS_MODE" const val PUSH_NOTIFICATIONS_TYPE = 1 const val EMAIL_NOTIFICATIONS_TYPE = 2 const val ALL_NOTIFICATIONS = 0 const val RELEASE_NOTIFICATIONS = 1 const val DISABLE_NOTIFICATIONS = 2 const val ADDRESS = "ADDRESS" const val ADDRESS_UNKNOWN = "Неизвестно" const val REGION_PRIORITY = "REGION_PRIORITY" const val THEME_MODE = "THEME_MODE" const val ERROR_NAME = "ERROR_NAME" const val LIGHT_THEME = 0 const val DARK_THEME = 1 const val BATTERY_SAFE = 2 const val SORT_TITLE = "TITLE" const val SORT_TITLE_ID = 0 const val SORT_PRICE = "PRICE" const val SORT_PRICE_ID = 1 const val SORT_ASC = "ASC" const val SORT_DESC = "DESC"
0
Kotlin
0
0
d07a2593694616235974bbf19f993d309d014260
1,717
russianpost-app
MIT License
store/src/commonMain/kotlin/org/mobilenativefoundation/store/store5/StoreReadResponse.kt
MobileNativeFoundation
226,169,258
false
{"Kotlin": 361534}
/* * Copyright 2019 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 org.mobilenativefoundation.store.store5 /** * Holder for responses from Store. * * Instead of using regular error channels (a.k.a. throwing exceptions), Store uses this holder * class to represent each response. This allows the flow to keep running even if an error happens * so that if there is an observable single source of truth, application can keep observing it. */ sealed class StoreReadResponse<out Output> { /** * Represents the source of the Response. */ abstract val origin: StoreReadResponseOrigin /** * Loading event dispatched by [Store] to signal the [Fetcher] is in progress. */ data class Loading(override val origin: StoreReadResponseOrigin) : StoreReadResponse<Nothing>() /** * Data dispatched by [Store] */ data class Data<Output>(val value: Output, override val origin: StoreReadResponseOrigin) : StoreReadResponse<Output>() /** * No new data event dispatched by Store to signal the [Fetcher] returned no data (i.e the * returned [kotlinx.coroutines.Flow], when collected, was empty). */ data class NoNewData(override val origin: StoreReadResponseOrigin) : StoreReadResponse<Nothing>() /** * Error dispatched by a pipeline */ sealed class Error : StoreReadResponse<Nothing>() { data class Exception( val error: Throwable, override val origin: StoreReadResponseOrigin ) : Error() data class Message( val message: String, override val origin: StoreReadResponseOrigin ) : Error() } /** * Returns the available data or throws [NullPointerException] if there is no data. */ fun requireData(): Output { return when (this) { is Data -> value is Error -> this.doThrow() else -> throw NullPointerException("there is no data in $this") } } /** * If this [StoreReadResponse] is of type [StoreReadResponse.Error], throws the exception * Otherwise, does nothing. */ fun throwIfError() { if (this is Error) { this.doThrow() } } /** * If this [StoreReadResponse] is of type [StoreReadResponse.Error], returns the available error * from it. Otherwise, returns `null`. */ fun errorMessageOrNull(): String? { return when (this) { is Error.Message -> message is Error.Exception -> error.message ?: "exception: ${error::class}" else -> null } } /** * If there is data available, returns it; otherwise returns null. */ fun dataOrNull(): Output? = when (this) { is Data -> value else -> null } @Suppress("UNCHECKED_CAST") internal fun <T> swapType(): StoreReadResponse<T> = when (this) { is Error -> this is Loading -> this is NoNewData -> this is Data -> throw RuntimeException("cannot swap type for StoreResponse.Data") } } /** * Represents the origin for a [StoreReadResponse]. */ enum class StoreReadResponseOrigin { /** * [StoreReadResponse] is sent from the cache */ Cache, /** * [StoreReadResponse] is sent from the persister */ SourceOfTruth, /** * [StoreReadResponse] is sent from a fetcher, */ Fetcher } fun StoreReadResponse.Error.doThrow(): Nothing = when (this) { is StoreReadResponse.Error.Exception -> throw error is StoreReadResponse.Error.Message -> throw RuntimeException(message) }
57
Kotlin
202
3,174
f9072fc59cc8bfe95cfe008cc8a9ce999301b242
4,165
Store
Apache License 2.0
compiler/testData/diagnostics/tests/multiplatform/hmpp/kt57320.kt
JetBrains
3,432,266
false
null
// LANGUAGE: +MultiPlatformProjects // MODULE: common // TARGET_PLATFORM: Common // FILE: StringValue.kt expect class <!NO_ACTUAL_FOR_EXPECT{JS}!>StringValue<!> expect fun StringValue.<!NO_ACTUAL_FOR_EXPECT{JS}!>plus<!>(other: String): StringValue // MODULE: commonJS()()(common) // TARGET_PLATFORM: JS // FILE: StringValueJs.kt actual class StringValue(val value: String) actual fun StringValue.plus(other: String) = StringValue(this.value + other) // MODULE: intermediate()()(common) // TARGET_PLATFORM: Common // FILE: StringDemoInterface.kt expect interface StringDemoInterface interface KotlinXStringDemoInterface { val value: String } expect fun StringDemoInterface.plusK(): <!NO_ACTUAL_FOR_EXPECT{JS}!>String<!> // MODULE: js()()(common, intermediate) // TARGET_PLATFORM: JS // FILE: StringDemoInterfaceJs.kt actual typealias StringDemoInterface = KotlinXStringDemoInterface actual fun StringDemoInterface.<!ACTUAL_WITHOUT_EXPECT("Actual function 'plusK'; The following declaration is incompatible because return type is different: public expect fun StringDemoInterface /* = KotlinXStringDemoInterface */.plusK(): String")!>plusK<!>() = <!RESOLUTION_TO_CLASSIFIER!>StringValue<!>(value).<!DEBUG_INFO_MISSING_UNRESOLVED!>plus<!>("K").<!DEBUG_INFO_MISSING_UNRESOLVED!>value<!> // FILE: main.kt class StringDemo(override val value: String) : StringDemoInterface fun box() = StringDemo("O").plusK()
181
null
5748
49,172
33eb9cef3d146062c103f9853d772f0a1da0450e
1,424
kotlin
Apache License 2.0
sdk-scrapper/src/test/kotlin/io/github/wulkanowy/sdk/scrapper/exams/ExamsTest.kt
wulkanowy
138,756,468
false
null
package io.github.wulkanowy.sdk.scrapper.exams import io.github.wulkanowy.sdk.scrapper.BaseLocalTest import kotlinx.coroutines.runBlocking import org.junit.Assert.assertEquals import org.junit.Test class ExamsTest : BaseLocalTest() { private val exams by lazy { runBlocking { getStudentRepo(ExamsTest::class.java, "Sprawdziany.json").getExams(getLocalDate(2018, 10, 1)) } } @Test fun getExamsSizeTest() { assertEquals(6, exams.size) } @Test fun getExam_normal() { with(exams[0]) { assertEquals("<NAME>", subject) assertEquals("Sprawdzian", typeName) assertEquals("Dwudziestolecie", description) assertEquals("<NAME>", teacher) assertEquals("CA", teacherSymbol) assertEquals(getDate(2018, 9, 16), entryDate) } } @Test fun getExam_group() { with(exams[1]) { assertEquals("<NAME>", subject) assertEquals("Sprawdzian", typeName) assertEquals("Czasy teraźniejsze", description) assertEquals("<NAME>", teacher) assertEquals("NN", teacherSymbol) assertEquals(getDate(2018, 9, 17), entryDate) } } @Test fun getExam_type() { with(exams[2]) { assertEquals("Metodologia programowania", subject) assertEquals("Kartkówka", typeName) assertEquals("programowanie obiektowe", description) assertEquals("<NAME>", teacher) assertEquals("MN", teacherSymbol) assertEquals(getDate(2018, 9, 16), entryDate) } } @Test fun getExam_emptyDescription() { with(exams[3]) { assertEquals("Metodologia programowania", subject) assertEquals("Praca klasowa", typeName) assertEquals("", description) assertEquals("<NAME>", teacher) assertEquals("MN", teacherSymbol) assertEquals(getDate(2018, 9, 16), entryDate) } } }
9
null
5
8
340245d8ccc2790dcb75219c2839e8bdd8b448a4
2,028
sdk
Apache License 2.0
src/main/kotlin/command/CommandManager.kt
pallaw
640,997,172
false
null
package command /** * Created by <NAME> */ object CommandManager { /** * Map which stores command and their corresponding required input values */ private val commandsParameterMap: HashMap<String, Int> = HashMap() init { commandsParameterMap.put(Command.CREATE_PARKING.inputCommand, 1) commandsParameterMap.put(Command.PARK.inputCommand, 1) commandsParameterMap.put(Command.LEAVE.inputCommand, 2) commandsParameterMap.put(Command.STATUS.inputCommand, 0) commandsParameterMap.put(Command.HELP.inputCommand, 0) commandsParameterMap.put(Command.EXIT.inputCommand, 0) } fun getCommandParamMap(): HashMap<String, Int> = commandsParameterMap }
0
Kotlin
0
0
c264975d2d5c2e48c414b508134f65b6658b05c1
721
Parkingalotsystem
MIT License
app/src/test/java/com/example/fetchassesment/model/SectionHeadingDataModelTest.kt
NirvanaDogra
706,349,308
false
{"Kotlin": 23697}
package com.example.fetchassesment.model import org.junit.Assert import org.junit.Assert.* import org.junit.Test internal class SectionHeadingDataModelTest { @Test fun `when SectionHeadingDataModel is initialized then validate the values`() { // given val model = SectionHeadingDataModel("name") // when // then assertEquals("name", model.heading) } }
0
Kotlin
0
0
5f7d7fac4de35d7916b33bde6eaed7ab248464ac
405
FetchAndroid
Apache License 2.0
protocol/osrs-221-desktop/src/main/kotlin/net/rsprot/protocol/game/outgoing/codec/varp/VarpLargeEncoder.kt
blurite
771,753,685
false
null
package net.rsprot.protocol.game.outgoing.codec.varp import io.netty.channel.ChannelHandlerContext import net.rsprot.buffer.JagByteBuf import net.rsprot.protocol.ServerProt import net.rsprot.protocol.game.outgoing.prot.GameServerProt import net.rsprot.protocol.game.outgoing.varp.VarpLarge import net.rsprot.protocol.message.codec.MessageEncoder public class VarpLargeEncoder : MessageEncoder<VarpLarge> { override val prot: ServerProt = GameServerProt.VARP_LARGE override fun encode( ctx: ChannelHandlerContext, buffer: JagByteBuf, message: VarpLarge, ) { buffer.p2Alt2(message.id) buffer.p4Alt1(message.value) } }
4
null
6
7
b72a9ddbbf607e357b783c4c8a1f5dc91b5de4f0
675
rsprot
MIT License
app/src/main/java/com/naveenkumawat/transactions/data/local/TransactionDao.kt
CoderNaveen
658,369,659
false
null
package com.naveenkumawat.transactions.data.local import androidx.lifecycle.LiveData import androidx.room.Dao import androidx.room.Delete import androidx.room.Insert import androidx.room.OnConflictStrategy import androidx.room.Query import androidx.room.TypeConverters import com.naveenkumawat.transactions.domain.model.Transaction @Dao @TypeConverters(Converters::class) interface TransactionDao { @Query("SELECT * FROM transactions ORDER BY date DESC") fun getAllTransactions(): LiveData<List<Transaction>> @Insert(onConflict = OnConflictStrategy.REPLACE) fun insertTransaction(transaction: Transaction) @Delete fun deleteTransaction(transaction: Transaction) }
0
Kotlin
0
0
abfd455070b13ad63b34bf1e38047421d6bc67b0
692
Transactions
MIT License
plugins/kotlin/idea/tests/test/org/jetbrains/kotlin/idea/navigationToolbar/AbstractKotlinNavBarTest.kt
ingokegel
72,937,917
false
null
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. package org.jetbrains.kotlin.idea.navigationToolbar import com.intellij.ide.navigationToolbar.NavBarModel import com.intellij.ide.navigationToolbar.NavBarPresentation import com.intellij.openapi.actionSystem.DataContext import com.intellij.openapi.editor.ex.EditorEx import org.jetbrains.kotlin.idea.base.test.InTextDirectivesUtils import org.jetbrains.kotlin.idea.test.KotlinLightCodeInsightFixtureTestCase abstract class AbstractKotlinNavBarTest : KotlinLightCodeInsightFixtureTestCase() { // inspired by: com.intellij.ide.navigationToolbar.JavaNavBarTest#assertNavBarModel protected fun doTest(testPath: String) { val psiFile = myFixture.configureByFile(dataFile().name) val model = NavBarModel(myFixture.project) model::class.java.getDeclaredMethod("updateModel", DataContext::class.java) .apply { isAccessible = true } .invoke(model, (myFixture.editor as EditorEx).dataContext) val actualItems = (0 until model.size()).map { NavBarPresentation.calcPresentableText(model[it], false) } val expectedItems = InTextDirectivesUtils.findListWithPrefixes(psiFile.text, "// NAV_BAR_ITEMS:") assertOrderedEquals(actualItems, expectedItems) } }
1
null
1
2
b07eabd319ad5b591373d63c8f502761c2b2dfe8
1,371
intellij-community
Apache License 2.0
ontrack-extension-slack/src/test/java/net/nemerosa/ontrack/extension/slack/notifications/SlackNotificationChannelTest.kt
nemerosa
19,351,480
false
null
package net.nemerosa.ontrack.extension.slack.notifications import io.mockk.every import io.mockk.mockk import io.mockk.verify import net.nemerosa.ontrack.extension.notifications.channels.NotificationResultType import net.nemerosa.ontrack.extension.slack.SlackSettings import net.nemerosa.ontrack.extension.slack.service.SlackService import net.nemerosa.ontrack.model.events.Event import net.nemerosa.ontrack.model.events.EventFactory import net.nemerosa.ontrack.model.settings.CachedSettingsService import net.nemerosa.ontrack.model.structure.ID import net.nemerosa.ontrack.model.structure.NameDescription import net.nemerosa.ontrack.model.structure.Project import net.nemerosa.ontrack.model.support.OntrackConfigProperties import org.junit.jupiter.api.BeforeEach import org.junit.jupiter.api.Test import kotlin.test.assertEquals import kotlin.test.assertFalse import kotlin.test.assertNull import kotlin.test.assertTrue class SlackNotificationChannelTest { private lateinit var project: Project private lateinit var event: Event private lateinit var cachedSettingsService: CachedSettingsService private lateinit var slackService: SlackService private lateinit var channel: SlackNotificationChannel @BeforeEach fun before() { slackService = mockk() cachedSettingsService = mockk() channel = SlackNotificationChannel( slackService, cachedSettingsService, SlackNotificationEventRenderer(OntrackConfigProperties()) ) project = Project.of(NameDescription.nd("project", "Test project")).withId(ID.of(1)) event = Event.of(EventFactory.DISABLE_PROJECT).withProject(project).get() } @Test fun `Using the event renderer to format the message`() { every { cachedSettingsService.getCachedSettings(SlackSettings::class.java) } returns SlackSettings( enabled = true ) every { slackService.sendNotification(any(), any()) } returns true val config = SlackNotificationChannelConfig(channel = "#test") val result = channel.publish(config, event) verify { slackService.sendNotification("#test", "Project <http://localhost:8080/#/project/1|project> has been disabled.") } assertEquals(NotificationResultType.OK, result.type) assertNull(result.message) } @Test fun `Returning an error when the Slack message cannot be sent`() { every { cachedSettingsService.getCachedSettings(SlackSettings::class.java) } returns SlackSettings( enabled = true ) every { slackService.sendNotification(any(), any()) } returns false // <== returning an error val config = SlackNotificationChannelConfig(channel = "#test") val result = channel.publish(config, event) assertEquals(NotificationResultType.ERROR, result.type) assertEquals("Slack message could not be sent. Check the operational logs.", result.message) } @Test fun `Channel enabled if Slack settings are enabled`() { every { cachedSettingsService.getCachedSettings(SlackSettings::class.java) } returns SlackSettings( enabled = true ) assertTrue(channel.enabled, "Channel is disabled") } @Test fun `Channel disabled if Slack settings are disabled`() { every { cachedSettingsService.getCachedSettings(SlackSettings::class.java) } returns SlackSettings( enabled = false ) assertFalse(channel.enabled, "Channel is disabled") } }
57
Kotlin
27
97
7c71a3047401e088ba0c6d43aa3a96422024857f
3,557
ontrack
MIT License
valiktor-core/src/test/kotlin/org/valiktor/constraints/DateConstraintsTest.kt
valiktor
127,146,179
false
null
/* * Copyright 2018-2019 https://www.valiktor.org * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.valiktor.constraints import org.assertj.core.api.Assertions.assertThat import org.assertj.core.api.Assertions.entry import org.valiktor.i18n.SupportedLocales import org.valiktor.i18n.interpolatedMessages import kotlin.test.Test class TodayTest { @Test fun `should validate messages`() { assertThat(Today.interpolatedMessages()).containsExactly( entry(SupportedLocales.DEFAULT, "Must be today"), entry(SupportedLocales.CA, "Ha de ser avui"), entry(SupportedLocales.DE, "Muss heute sein"), entry(SupportedLocales.EN, "Must be today"), entry(SupportedLocales.ES, "Tiene que ser hoy"), entry(SupportedLocales.PT_BR, "Deve ser hoje")) } } class NotTodayTest { @Test fun `should validate messages`() { assertThat(NotToday.interpolatedMessages()).containsExactly( entry(SupportedLocales.DEFAULT, "Must not be today"), entry(SupportedLocales.CA, "No pot ser avui"), entry(SupportedLocales.DE, "Darf nicht heute sein"), entry(SupportedLocales.EN, "Must not be today"), entry(SupportedLocales.ES, "No puede ser hoy"), entry(SupportedLocales.PT_BR, "Não deve ser hoje")) } }
32
null
36
405
1b8e71d82ff1a91b66815fc93536ebdf4d148650
1,875
valiktor
Apache License 2.0
ksoup-network/src/nonJsMain/kotlin/com/fleeksoft/ksoup/network/KsoupNetworkBlocking.kt
fleeksoft
719,100,459
false
null
package com.fleeksoft.ksoup.network import com.fleeksoft.ksoup.Ksoup import com.fleeksoft.ksoup.nodes.Document import com.fleeksoft.ksoup.parser.Parser import io.ktor.client.request.* import io.ktor.client.statement.* /** * Use to fetch and parse a HTML page. * * Use examples: * * * `Document doc = Ksoup.parseGetRequest("http://example.com")` * * @param url URL to connect to. The protocol must be `http` or `https`. * @return sane HTML * */ public suspend fun Ksoup.parseGetRequest( url: String, httpRequestBuilder: HttpRequestBuilder.() -> Unit = {}, parser: Parser = Parser.htmlParser(), ): Document { val httpResponse = NetworkHelperKtor.instance.get(url, httpRequestBuilder = httpRequestBuilder) // url can be changed after redirection val finalUrl = httpResponse.request.url.toString() return parse(sourceReader = httpResponse.asSourceReader(), parser = parser, baseUri = finalUrl) } /** * Use to fetch and parse a HTML page. * * Use examples: * * * `Document doc = Ksoup.parseSubmitRequest("http://example.com", params = mapOf("param1Key" to "param1Value"))` * * @param url URL to connect to. The protocol must be `http` or `https`. * @return sane HTML * */ public suspend fun Ksoup.parseSubmitRequest( url: String, params: Map<String, String> = emptyMap(), httpRequestBuilder: HttpRequestBuilder.() -> Unit = {}, parser: Parser = Parser.htmlParser(), ): Document { val httpResponse = NetworkHelperKtor.instance.submitForm( url = url, params = params, httpRequestBuilder = httpRequestBuilder, ) // url can be changed after redirection val finalUrl = httpResponse.request.url.toString() return parse(sourceReader = httpResponse.asSourceReader(), parser = parser, baseUri = finalUrl) } /** * Use to fetch and parse a HTML page. * * Use examples: * * * `Document doc = Ksoup.parsePostRequest("http://example.com")` * * @param url URL to connect to. The protocol must be `http` or `https`. * @return sane HTML * */ public suspend fun Ksoup.parsePostRequest( url: String, httpRequestBuilder: HttpRequestBuilder.() -> Unit = {}, parser: Parser = Parser.htmlParser(), ): Document { val httpResponse = NetworkHelperKtor.instance.post( url = url, httpRequestBuilder = httpRequestBuilder, ) // url can be changed after redirection val finalUrl = httpResponse.request.url.toString() return parse(sourceReader = httpResponse.asSourceReader(), parser = parser, baseUri = finalUrl) }
7
null
5
73
6fea1b08ccb423778ef5f9e250204216da8380cc
2,593
ksoup
Apache License 2.0
app/src/main/kotlin/no/nav/tms/utkast/utkastApi.kt
navikt
565,849,666
false
{"Kotlin": 84583, "Dockerfile": 243}
package no.nav.tms.utkast import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule import com.fasterxml.jackson.module.kotlin.jacksonObjectMapper import io.ktor.http.* import io.ktor.serialization.jackson.* import io.ktor.server.application.* import io.ktor.server.auth.* import io.ktor.server.plugins.contentnegotiation.* import io.ktor.server.plugins.statuspages.* import io.ktor.server.request.* import io.ktor.server.response.* import io.ktor.server.routing.* import io.ktor.util.pipeline.* import nav.no.tms.common.metrics.installTmsApiMetrics import no.nav.tms.token.support.tokenx.validation.tokenX import no.nav.tms.token.support.tokenx.validation.user.TokenXUserFactory import no.nav.tms.utkast.config.logExceptionAsWarning import no.nav.tms.utkast.database.DatabaseException import no.nav.tms.utkast.database.UtkastRepository import java.text.DateFormat import java.util.* internal fun Application.utkastApi( utkastRepository: UtkastRepository, digisosHttpClient: DigisosHttpClient, installAuthenticatorsFunction: Application.() -> Unit = installAuth(), ) { installAuthenticatorsFunction() installTmsApiMetrics { setupMetricsRoute = false } install(StatusPages) { exception<Throwable> { call, cause -> when (cause) { is DatabaseException -> { logExceptionAsWarning( unsafeLogInfo = "Henting fra database feilet for kall til ${call.request.uri}", secureLogInfo = cause.details, cause = cause ) call.respond(HttpStatusCode.InternalServerError) } is DigisosException -> { val ident = TokenXUserFactory.createTokenXUser(call) logExceptionAsWarning( unsafeLogInfo = cause.message!!, secureLogInfo = "${cause.message} for $ident", cause = cause.originalException ) call.respond(HttpStatusCode.ServiceUnavailable) } else -> { logExceptionAsWarning( unsafeLogInfo = "Ukjent feil for kall til ${call.request.uri}", cause = cause ) call.respond(HttpStatusCode.InternalServerError) } } } } install(ContentNegotiation) { jackson { registerModule(JavaTimeModule()) dateFormat = DateFormat.getDateTimeInstance() } } routing { authenticate { route("utkast") { get { call.respond(utkastRepository.getUtkastForIdent(userIdent, localeParam)) } get("antall") { val antall = utkastRepository.getUtkastForIdent(userIdent).size call.respond(jacksonObjectMapper().createObjectNode().put("antall", antall)) } get("digisos") { call.respond(digisosHttpClient.getUtkast(accessToken)) } get("digisos/antall") { val antall = digisosHttpClient.getAntall(accessToken) call.respond(jacksonObjectMapper().createObjectNode().put("antall", antall)) } } } } } private fun installAuth(): Application.() -> Unit = { authentication { tokenX { setAsDefault = true } } } private val PipelineContext<Unit, ApplicationCall>.userIdent get() = TokenXUserFactory.createTokenXUser(call).ident private val PipelineContext<Unit, ApplicationCall>.accessToken get() = TokenXUserFactory.createTokenXUser(call).tokenString private val PipelineContext<Unit, ApplicationCall>.localeParam get() = call.request.queryParameters["la"]?.let { Locale( it ) }
2
Kotlin
1
1
fba38c427fe21d22445da1445d7afd7370e53491
4,009
tms-utkast
MIT License
app/src/main/java/com/athorfeo/source/di/key/ViewModelKey.kt
Athorfeo
201,696,582
false
null
package com.athorfeo.source.di.key import androidx.lifecycle.ViewModel import dagger.MapKey import kotlin.reflect.KClass /** * Anotacion para ViewModel * @version 1.0 * @author Juan Ortiz * @date 10/09/2019 */ @MustBeDocumented @Target( AnnotationTarget.FUNCTION, AnnotationTarget.PROPERTY_GETTER, AnnotationTarget.PROPERTY_SETTER ) @Retention(AnnotationRetention.RUNTIME) @MapKey annotation class ViewModelKey(val value: KClass<out ViewModel>)
0
Kotlin
1
0
07c300ff5c6337b0ba9dc55b5dfba368119519ae
463
CoroutinesAndroid
MIT License
src/test/kotlin/uk/gov/justice/digital/hmpps/prisonregister/model/VideolinkConferencingCentreRepositoryTest.kt
ministryofjustice
337,466,567
false
null
package uk.gov.justice.digital.hmpps.prisonregister.model import org.assertj.core.api.Assertions.assertThat import org.assertj.core.api.Assertions.fail import org.junit.jupiter.api.Test import org.springframework.beans.factory.annotation.Autowired import org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTest import org.springframework.data.repository.findByIdOrNull import org.springframework.test.context.ActiveProfiles import org.springframework.test.context.transaction.TestTransaction import org.springframework.transaction.annotation.Transactional @ActiveProfiles("test") @DataJpaTest @Transactional class VideolinkConferencingCentreRepositoryTest( @Autowired val prisonRepository: PrisonRepository, @Autowired val vccRepository: VideoLinkConferencingCentreRepository, ) { @Test fun lifecycle() { val prisonId = "MDI" val prison = prisonRepository.findByIdOrNull(prisonId) ?: fail("Expected to find Prison") vccRepository.save(VideolinkConferencingCentre(prison = prison, emailAddress = "<EMAIL>")) TestTransaction.flagForCommit() TestTransaction.end() TestTransaction.start() val vcc = vccRepository.findByIdOrNull(prisonId) ?: fail("Expected to find VCC") with(vcc) { assertThat(emailAddress).isEqualTo("<EMAIL>") } vccRepository.deleteById(prisonId) TestTransaction.flagForCommit() TestTransaction.end() TestTransaction.start() assertThat(vccRepository.findById(prisonId)).isEmpty } }
4
Kotlin
1
2
342ec2191ec8e8c098c19f4d6c01d6bb943c6c89
1,485
prison-register
MIT License
app/src/main/kotlin/net/rubygrapefruit/gen/builders/ProjectContentsBuilder.kt
adammurdoch
430,814,411
false
{"Kotlin": 181951}
package net.rubygrapefruit.gen.builders import net.rubygrapefruit.gen.files.BuildScriptBuilder import net.rubygrapefruit.gen.specs.ProjectSpec class ProjectContentsBuilder( val spec: ProjectSpec, val buildScript: BuildScriptBuilder )
0
Kotlin
0
0
0d47884136b4764f7dc901009614cfe435de5dda
244
build-gen
Apache License 2.0
common/ui-theme/src/main/kotlin/ru/maksonic/beresta/common/ui_theme/palette/BluePalette.kt
maksonic
580,058,579
false
{"Kotlin": 1622432}
package ru.maksonic.beresta.common.ui_theme.palette import ru.maksonic.beresta.common.ui_theme.colors.Palette /** * @Author maksonic on 26.02.2023 */ val filledLightBluePalette = baseLightPalette.copy( primary = Palette.Blue.azureRadiance, onPrimary = Palette.Blue.coolBlack, onPrimaryContainer = Palette.Blue.eerieBlue, secondary = Palette.Red.cinderella, onSecondary = Palette.Blue.eerieBlue, secondaryContainer = Palette.Blue.solitude, onSecondaryContainer = Palette.Blue.paleCornflowerBlue, tertiary = Palette.Red.melon, tertiaryContainer = Palette.Blue.coolBlack, onTertiaryContainer = Palette.white, background = Palette.Blue.zircon, surface = Palette.Blue.zircon, onSurface = Palette.Blue.coolBlack, surfaceVariant = Palette.Blue.frenchPassLight, onSurfaceVariant = Palette.Blue.paleCornflowerBlue, inverseSurface = Palette.Blue.coolBlack, inversePrimary = Palette.Red.roseBud, surfaceTint = Palette.Blue.azureRadiance, outlineVariant = Palette.Blue.solitude, onSnack = Palette.Blue.anakiwa, ) val filledDarkBluePalette = baseNightPalette.copy( primary = Palette.Blue.x0, onPrimary = Palette.Blue.x0, primaryContainer = Palette.Blue.x2, onPrimaryContainer = Palette.white, secondary = Palette.Blue.x4, onSecondary = Palette.white, secondaryContainer = Palette.Blue.x2, onSecondaryContainer = Palette.Blue.x5, tertiary = Palette.Blue.x5, tertiaryContainer = Palette.Blue.x0, onTertiaryContainer = Palette.Blue.x1, background = Palette.Blue.x1, surface = Palette.Blue.x1, surfaceVariant = Palette.Blue.x3, onSurfaceVariant = Palette.Blue.x4, surfaceTint = Palette.black, inversePrimary = Palette.Blue.x5, outlineVariant = Palette.Blue.x3, snack = Palette.Blue.eerieBlue, onSnack = Palette.Blue.anakiwa, onSnackContainer = Palette.white ) val outlinedDarkBluePalette = baseNightPalette.copy( primary = Palette.Blue.anakiwa, tertiaryContainer = Palette.Blue.anakiwa, onPrimary = Palette.Blue.anakiwa, onSnack = Palette.Blue.coolBlack, ) val highContrastBluePalette = darkPalette.copy( primary = Palette.Blue.azureRadiance, tertiaryContainer = Palette.Blue.azureRadiance, onTertiaryContainer = Palette.white, onPrimary = Palette.Blue.azureRadiance, )
0
Kotlin
0
0
227b0a5f6c27b0f731b1f6e81b1fe2deeaa720aa
2,352
Beresta
MIT License
app/src/main/java/ke/co/tulivuapps/hoteltours/features/screen/popular/PopularViewModel.kt
RushiChavan-dev
740,244,295
false
{"Kotlin": 872337}
package ke.co.tulivuapps.hoteltours.features.screen.popular import androidx.lifecycle.viewModelScope import dagger.hilt.android.lifecycle.HiltViewModel import ke.co.tulivuapps.hoteltours.data.remote.utils.DataState import ke.co.tulivuapps.hoteltours.domain.repository.PopularRepository import ke.co.tulivuapps.hoteltours.domain.viewstate.IViewEvent import ke.co.tulivuapps.hoteltours.domain.viewstate.popular.PopularViewState import ke.co.tulivuapps.hoteltours.features.base.BaseViewModel import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.launch import javax.inject.Inject /** * Created by Rushi on 19.03.2023 */ @HiltViewModel class PopularViewModel @Inject constructor( private val episodesRepository: PopularRepository ) : BaseViewModel<PopularViewState, PopularViewEvent>() { init { getAllPopular() } fun getAllPopular() { viewModelScope.launch(Dispatchers.IO) { setState { currentState.copy(isLoading = true) } episodesRepository.getAllPopular().collect { when (it) { is DataState.Success -> { setState { currentState.copy(data = it.data.results, isLoading = false) } } is DataState.Error -> { setState { currentState.copy(isLoading = false) } setEvent(PopularViewEvent.SnackBarError(it.apiError?.message)) } is DataState.Loading -> { setState { currentState.copy(isLoading = true) } } } } } } override fun createInitialState() = PopularViewState() override fun onTriggerEvent(event: PopularViewEvent) {} } sealed class PopularViewEvent : IViewEvent { class SnackBarError(val message: String?) : PopularViewEvent() }
0
Kotlin
0
0
ad74422b1b7930e5665c94cc9368ec69d425ffba
1,885
HotelApp
Apache License 2.0
dokument/src/main/kotlin/no/nav/helsearbeidsgiver/felles/inntektsmelding/felles/Naturalytelse.kt
navikt
495,713,363
false
null
@file:UseSerializers(LocalDateSerializer::class) package no.nav.helsearbeidsgiver.felles.inntektsmelding.felles import kotlinx.serialization.Serializable import kotlinx.serialization.UseSerializers import no.nav.helsearbeidsgiver.felles.serializers.LocalDateSerializer import java.time.LocalDate @Serializable data class Naturalytelse( val naturalytelse: NaturalytelseKode, val dato: LocalDate, val beløp: Double ) /** * https://github.com/navikt/tjenestespesifikasjoner/blob/IM_nye_kodeverdier/nav-altinn-inntektsmelding/src/main/xsd/Inntektsmelding_kodelister_20210216.xsd */ /* ktlint-disable enum-entry-name-case */ /* ktlint-disable EnumEntryName */ @Suppress("EnumEntryName", "unused") enum class NaturalytelseKode { AksjerGrunnfondsbevisTilUnderkurs, Losji, KostDoegn, BesoeksreiserHjemmetAnnet, KostbesparelseIHjemmet, RentefordelLaan, Bil, KostDager, Bolig, SkattepliktigDelForsikringer, FriTransport, Opsjoner, TilskuddBarnehageplass, Annet, Bedriftsbarnehageplass, YrkebilTjenestligbehovKilometer, YrkebilTjenestligbehovListepris, InnbetalingTilUtenlandskPensjonsordning, ElektroniskKommunikasjon }
2
Kotlin
0
2
d7d47418b3e70fff37e103a8c39632399569c121
1,204
helsearbeidsgiver-inntektsmelding
MIT License
examples/android/src/main/kotlin/com/algolia/instantsearch/examples/android/guides/gettingstarted/ProductFragment.kt
algolia
55,971,521
false
null
package com.algolia.instantsearch.examples.android.guides.gettingstarted import android.os.Bundle import android.view.View import android.widget.Button import androidx.fragment.app.Fragment import androidx.fragment.app.activityViewModels import androidx.recyclerview.widget.RecyclerView import com.algolia.instantsearch.android.paging3.liveData import com.algolia.instantsearch.android.searchbox.SearchBoxViewAppCompat import com.algolia.instantsearch.android.stats.StatsTextView import com.algolia.instantsearch.core.connection.ConnectionHandler import com.algolia.instantsearch.examples.android.R import com.algolia.instantsearch.examples.android.guides.extension.configure import com.algolia.instantsearch.searchbox.connectView import com.algolia.instantsearch.stats.DefaultStatsPresenter import com.algolia.instantsearch.stats.connectView class ProductFragment : Fragment(R.layout.fragment_product) { private val viewModel: MyViewModel by activityViewModels() private val connection = ConnectionHandler() override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) val adapterProduct = ProductAdapter() viewModel.paginator.liveData.observe(viewLifecycleOwner) { pagingData -> adapterProduct.submitData(lifecycle, pagingData) } val productList = view.findViewById<RecyclerView>(R.id.productList) productList.configure(adapterProduct) val searchBoxView = SearchBoxViewAppCompat(view.findViewById(R.id.searchView)) connection += viewModel.searchBox.connectView(searchBoxView) val statsView = StatsTextView(view.findViewById(R.id.stats)) connection += viewModel.stats.connectView(statsView, DefaultStatsPresenter()) view.findViewById<Button>(R.id.filters).setOnClickListener { viewModel.navigateToFilters() } } override fun onDestroyView() { super.onDestroyView() connection.clear() } }
5
null
32
156
cb068acebbe2cd6607a6bbeab18ddafa582dd10b
2,013
instantsearch-android
Apache License 2.0
underdocs-renderer/src/main/kotlin/underdocs/renderer/representation/Type.kt
underdocs
260,535,022
false
null
package underdocs.renderer.representation interface Type
26
Kotlin
0
2
63841ebabd76a0d86e420fce5f5395d5cbf02991
58
underdocs
Apache License 2.0
OrderCenter/src/main/java/com/kotlin/order/ui/activity/OrderConfirmActivity.kt
heisexyyoumo
145,665,152
false
null
package com.kotlin.order.ui.activity import android.os.Bundle import android.support.v7.widget.LinearLayoutManager import com.alibaba.android.arouter.facade.annotation.Autowired import com.alibaba.android.arouter.facade.annotation.Route import com.alibaba.android.arouter.launcher.ARouter import com.eightbitlab.rxbus.Bus import com.eightbitlab.rxbus.registerInBus import com.kotlin.base.ext.onClick import com.kotlin.base.ext.setVisible import com.kotlin.base.ui.activity.BaseMvpActivity import com.kotlin.base.utils.YuanFenConverter import com.kotlin.order.R import com.kotlin.order.data.protocol.Order import com.kotlin.order.data.protocol.ShipAddress import com.kotlin.order.event.SelectAddressEvent import com.kotlin.order.injection.component.DaggerOrderComponent import com.kotlin.order.injection.module.OrderModule import com.kotlin.order.presenter.OrderConfirmPresenter import com.kotlin.order.presenter.view.OrderConfirmView import com.kotlin.order.ui.adapter.OrderGoodsAdapter import com.kotlin.provider.common.ProviderConstant import com.kotlin.provider.router.RouterPath import kotlinx.android.synthetic.main.activity_order_confirm.* import kotlinx.android.synthetic.main.layout.* import org.jetbrains.anko.startActivity import org.jetbrains.anko.toast @Route(path = RouterPath.OrderCenter.PATH_ORDER_CONFIRM) class OrderConfirmActivity : BaseMvpActivity<OrderConfirmPresenter>(), OrderConfirmView { @Autowired(name = ProviderConstant.KEY_ORDER_ID) @JvmField var mOrderId: Int = 0 private lateinit var mAdapter: OrderGoodsAdapter private var mCurrentOrder: Order? = null override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_order_confirm) initView() initObserve() loadData() } override fun injectComponent() { DaggerOrderComponent.builder().activityComponent(activityComponent) .orderModule(OrderModule()).build().inject(this) mPresenter.mView = this } private fun initView() { mShipView.onClick { startActivity<ShipAddressActivity>() } mSelectShipTv.onClick { startActivity<ShipAddressActivity>() } mSubmitOrderBtn.onClick { mCurrentOrder?.let { mPresenter.submitOrder(it) } } mOrderGoodsRv.layoutManager = LinearLayoutManager(this) mAdapter = OrderGoodsAdapter(this) mOrderGoodsRv.adapter = mAdapter } private fun initObserve() { Bus.observe<SelectAddressEvent>() .subscribe { t: SelectAddressEvent -> run { mCurrentOrder?.let { it.shipAddress = t.address } updateAddressView() } } .registerInBus(this) } private fun loadData() { toast("$mOrderId") mPresenter.getOrderById(mOrderId) } override fun onGetOrderByIdResult(result: Order) { mCurrentOrder = result mAdapter.setData(result.orderGoodsList) mTotalPriceTv.text = "合计${YuanFenConverter.changeF2YWithUnit(result.totalPrice)}" updateAddressView() } private fun updateAddressView() { mCurrentOrder?.let { if (it.shipAddress == null) { mSelectShipTv.setVisible(true) mShipView.setVisible(false) } else { mSelectShipTv.setVisible(false) mShipView.setVisible(true) mShipNameTv.text = it.shipAddress!!.shipUserName + " " + it.shipAddress!!.shipUserMobile mShipAddressTv.text = it.shipAddress!!.shipAddress } } } override fun onSubmitOrderResult(result: Boolean) { toast("订单提交成功") ARouter.getInstance() .build(RouterPath.PaySDK.PATH_PAY) .withInt(ProviderConstant.KEY_ORDER_ID, mCurrentOrder!!.id) .withLong(ProviderConstant.KEY_ORDER_PRICE, mCurrentOrder!!.totalPrice) .navigation() finish() } override fun onDestroy() { super.onDestroy() Bus.unregister(this) } }
0
Kotlin
1
2
27fea0090cea5fb636f8db5025379d274693b1b4
4,341
KotlinMall
Apache License 2.0
desktopApp/src/jvmMain/kotlin/com/hoc081098/compose_multiplatform_kmpviewmodel_sample/navigation.kt
hoc081098
675,918,221
false
{"Kotlin": 173732, "Swift": 580, "Shell": 228, "Ruby": 143}
package com.hoc081098.compose_multiplatform_kmpviewmodel_sample import androidx.compose.runtime.Stable import androidx.compose.runtime.remember import com.freeletics.khonshu.navigation.NavEventNavigator import com.freeletics.khonshu.navigation.compose.NavDestination import com.freeletics.khonshu.navigation.compose.NavigationSetup import com.freeletics.khonshu.navigation.compose.ScreenDestination import com.hoc081098.compose_multiplatform_kmpviewmodel_sample.koin_utils.declareSetMultibinding import com.hoc081098.compose_multiplatform_kmpviewmodel_sample.koin_utils.intoSetMultibinding import com.hoc081098.compose_multiplatform_kmpviewmodel_sample.navigation_shared.PhotoDetailRoute import com.hoc081098.compose_multiplatform_kmpviewmodel_sample.navigation_shared.SearchPhotoRoute import com.hoc081098.compose_multiplatform_kmpviewmodel_sample.photo_detail.PhotoDetailScreen import com.hoc081098.compose_multiplatform_kmpviewmodel_sample.search_photo.SearchPhotoScreen import org.koin.compose.koinInject import org.koin.core.module.dsl.singleOf import org.koin.core.qualifier.qualifier import org.koin.dsl.module @Stable @JvmField val AllDestinationsQualifier = qualifier("AllDestinationsQualifier") @JvmField val NavigationModule = module { singleOf(::NavEventNavigator) declareSetMultibinding<NavDestination>(qualifier = AllDestinationsQualifier) intoSetMultibinding( key = SearchPhotoRoute::class.java, multibindingQualifier = AllDestinationsQualifier, ) { ScreenDestination<SearchPhotoRoute> { route -> val navigator = koinInject<NavEventNavigator>() NavigationSetup(navigator) SearchPhotoScreen( route = route, navigateToPhotoDetail = remember(navigator) { { navigator.navigateTo(PhotoDetailRoute(id = it)) } }, ) } } intoSetMultibinding( key = PhotoDetailRoute::class.java, multibindingQualifier = AllDestinationsQualifier, ) { ScreenDestination<PhotoDetailRoute> { route -> val navigator = koinInject<NavEventNavigator>() NavigationSetup(navigator) PhotoDetailScreen( route = route, onNavigationBack = remember(navigator) { navigator::navigateBack }, ) } } }
12
Kotlin
4
8
539c189185a5c77646e020928ec3a23334722317
2,337
Compose-Multiplatform-KmpViewModel-Unsplash-Sample
Apache License 2.0
compiler/testData/codegen/box/reified/reifiedIntersectionTypeArgumentCrossModule.kt
JetBrains
3,432,266
false
null
// WITH_STDLIB // See KT-37163 import kotlin.reflect.typeOf class In<in T> interface A interface B class C() : A, B // TODO check real effects to fix the behavior when we reach consensus // and to be sure that something is not dropped by optimizations. var l = "" fun log(s: String) { l += s + ";" } fun consume(a: Any?) {} @OptIn(kotlin.ExperimentalStdlibApi::class) inline fun <reified K> select(x: K, y: Any): K where K : A, K : B { log((x is K).toString()) log((y is K).toString()) consume(K::class) log("KClass was created") consume(typeOf<K>()) log("KType was created") consume(Array<K>(1) { x }) log("array was created") return x as K } fun test(a: Any, b: Any) { if (a is A && a is B) { select(a, b) } } fun box(): String { test(C(), object : A, B {}) test(C(), object : A {}) test(C(), object : B {}) test(C(), object {}) test(C(), Any()) // if ( // l != "true;true;KClass was created;KType was created;array was created;" + // "true;false;KClass was created;KType was created;array was created;" + // "true;false;KClass was created;KType was created;array was created;" + // "true;false;KClass was created;KType was created;array was created;" + // "true;false;KClass was created;KType was created;array was created;" // ) { // return "fail: $l" // } return "OK" }
34
null
5748
49,172
33eb9cef3d146062c103f9853d772f0a1da0450e
1,439
kotlin
Apache License 2.0
Kotlin/src/main/kotlin/com/gildedrose/Quality.kt
rstraub
229,895,161
true
{"C++": 724486, "XSLT": 19568, "C#": 13851, "Kotlin": 12487, "Pascal": 9282, "C": 9261, "Smalltalk": 8793, "ABAP": 8568, "Java": 8402, "F#": 8361, "PHP": 7837, "Ada": 7270, "JavaScript": 7008, "Common Lisp": 6116, "CMake": 5462, "Scheme": 5368, "Swift": 4798, "Groovy": 4478, "PLSQL": 4471, "Erlang": 4392, "Perl": 4384, "D": 4258, "COBOL": 4067, "TypeScript": 3925, "Haskell": 3880, "Rust": 3786, "Makefile": 3644, "TSQL": 3598, "Ruby": 3448, "Python": 3402, "Scala": 3343, "Perl 6": 3281, "R": 3160, "Dart": 3119, "Elixir": 2885, "Go": 2568, "PLpgSQL": 2159, "Shell": 180, "SQLPL": 133}
package com.gildedrose class Quality(points: Int) { companion object { const val LEGENDARY_POINTS = 80 const val MAX_POINTS = 50 const val MIN_POINTS = 0 val MAX_QUALITY = Quality(MAX_POINTS) val MIN_QUALITY = Quality(MIN_POINTS) } val points: Int init { this.points = when { points == LEGENDARY_POINTS -> LEGENDARY_POINTS points > MAX_POINTS -> MAX_POINTS points < MIN_POINTS -> MIN_POINTS else -> points } } operator fun plus(amount: Int) = Quality(points + amount) operator fun minus(amount: Int) = Quality(points - amount) }
0
C++
0
0
a259f0abe65d54828a98a7ca44bcab628cbf6a0d
666
GildedRose-Refactoring-Kata
MIT License
src/main/kotlin/br/com/zupacademy/ratkovski/pix/registra/GrpcExtensions.kt
Ratkovski
395,480,677
true
{"Kotlin": 104442, "Smarty": 2172, "Dockerfile": 164}
package br.com.zupacademy.ratkovski.pix.registra import br.com.zupacademy.ratkovski.AccountType import br.com.zupacademy.ratkovski.KeyType import br.com.zupacademy.ratkovski.RegisterKeyPixRequest import br.com.zupacademy.ratkovski.pix.grpcenum.TipoChave import br.com.zupacademy.ratkovski.pix.grpcenum.TipoConta fun RegisterKeyPixRequest.toModel(): NovaChavePix { return NovaChavePix( clienteId = clienteId, tipo = when (tipoChave) { KeyType.UNKNOWN_KEY -> null else -> TipoChave.valueOf(tipoChave.name) }, chave = chave, tipoConta = when (tipoConta) { AccountType.UNKNOWN_ACCOUNT -> null else -> TipoConta.valueOf(tipoConta.name) } ) }
0
Kotlin
0
0
c4123d9e88247192717061e47fcb1ed6c55b2d9b
751
orange-talents-05-template-pix-keymanager-grpc
Apache License 2.0
raft/src/main/kotlin/raft/log/snapshot/EntryInSnapshotException.kt
WyattJia
287,940,061
false
{"Kotlin": 268400}
package raft.log.snapshot import raft.log.LogException class EntryInSnapshotException(val index: Int) : LogException()
0
Kotlin
9
44
ce055b10d422177e01a9d32ad07a789599e8d7c1
123
Kites
MIT License
idea-plugin/p3c-common/src/main/kotlin/com/alibaba/p3c/idea/inspection/AliPmdInspection.kt
wang-yan-github
109,469,673
false
null
/* * Copyright 1999-2017 Alibaba Group. * * 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.alibaba.p3c.idea.inspection import com.alibaba.p3c.idea.inspection.AliLocalInspectionToolProvider.ShouldInspectChecker import com.alibaba.p3c.idea.util.NumberConstants import com.alibaba.p3c.idea.util.QuickFixes import com.intellij.codeHighlighting.HighlightDisplayLevel import com.intellij.codeInspection.InspectionManager import com.intellij.codeInspection.LocalInspectionTool import com.intellij.codeInspection.LocalQuickFix import com.intellij.codeInspection.ProblemDescriptor import com.intellij.psi.PsiElement import com.intellij.psi.PsiFile import net.sourceforge.pmd.Rule import org.jetbrains.annotations.Nls /** * @author caikang * @date 2016/12/16 */ class AliPmdInspection(private val ruleName: String) : LocalInspectionTool(), AliBaseInspection, PmdRuleInspectionIdentify { override fun manualBuildFix(psiElement: PsiElement, isOnTheFly: Boolean): LocalQuickFix? { return QuickFixes.getQuickFix(ruleName, isOnTheFly) } private val staticDescription: String = RuleInspectionUtils.getRuleStaticDescription(ruleName) private val displayName: String private val shouldInspectChecker: ShouldInspectChecker private val defaultLevel: HighlightDisplayLevel private val rule: Rule init { val ruleInfo = AliLocalInspectionToolProvider.ruleInfoMap[ruleName]!! shouldInspectChecker = ruleInfo.shouldInspectChecker rule = ruleInfo.rule displayName = rule.message defaultLevel = RuleInspectionUtils.getHighlightDisplayLevel(rule.priority) } override fun runForWholeFile(): Boolean { return true } override fun checkFile( file: PsiFile, manager: InspectionManager, isOnTheFly: Boolean ): Array<ProblemDescriptor>? { if (!shouldInspectChecker.shouldInspect(file)) { return null } return AliPmdInspectionInvoker.invokeInspection(file, manager, rule, isOnTheFly) } override fun getStaticDescription(): String? { return staticDescription } override fun ruleName(): String { return ruleName } @Nls override fun getDisplayName(): String { return displayName } override fun getDefaultLevel(): HighlightDisplayLevel { return defaultLevel } @Nls override fun getGroupDisplayName(): String { return AliBaseInspection.GROUP_NAME } override fun isEnabledByDefault(): Boolean { return true } override fun getShortName(): String { var shortName = "Alibaba" + ruleName val index = shortName.lastIndexOf("Rule") if (index > NumberConstants.INDEX_0) { shortName = shortName.substring(NumberConstants.INDEX_0, index) } return shortName } }
27
null
5
7
34383b4d04258a984088dcc448f5307ec37702de
3,392
p3c
Apache License 2.0
matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/room/RoomDirectoryService.kt
matrix-org
287,466,066
false
null
/* * Copyright 2020 The Matrix.org Foundation C.I.C. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.matrix.android.sdk.api.session.room import org.matrix.android.sdk.api.session.room.model.RoomDirectoryVisibility import org.matrix.android.sdk.api.session.room.model.roomdirectory.PublicRoomsParams import org.matrix.android.sdk.api.session.room.model.roomdirectory.PublicRoomsResponse /** * This interface defines methods to get and join public rooms. It's implemented at the session level. */ interface RoomDirectoryService { /** * Get rooms from directory. */ suspend fun getPublicRooms(server: String?, publicRoomsParams: PublicRoomsParams): PublicRoomsResponse /** * Get the visibility of a room in the directory. */ suspend fun getRoomDirectoryVisibility(roomId: String): RoomDirectoryVisibility /** * Set the visibility of a room in the directory. */ suspend fun setRoomDirectoryVisibility(roomId: String, roomDirectoryVisibility: RoomDirectoryVisibility) suspend fun checkAliasAvailability(aliasLocalPart: String?): AliasAvailabilityResult }
86
null
4
97
55cc7362de34a840c67b4bbb3a14267bc8fd3b9c
1,671
matrix-android-sdk2
Apache License 2.0
clients/kotlin/generated/src/main/kotlin/org/openapitools/client/models/OrgApacheSlingScriptingJspJspScriptEngineFactoryProperties.kt
shinesolutions
190,217,155
false
null
/** * Adobe Experience Manager OSGI config (AEM) API * Swagger AEM OSGI is an OpenAPI specification for Adobe Experience Manager (AEM) OSGI Configurations API * * OpenAPI spec version: 1.0.0-pre.0 * Contact: [email protected] * * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). * https://openapi-generator.tech * Do not edit the class manually. */ package org.openapitools.client.models import org.openapitools.client.models.ConfigNodePropertyBoolean import org.openapitools.client.models.ConfigNodePropertyString /** * * @param jasperPeriodcompilerTargetVM * @param jasperPeriodcompilerSourceVM * @param jasperPeriodclassdebuginfo * @param jasperPeriodenablePooling * @param jasperPeriodieClassId * @param jasperPeriodgenStringAsCharArray * @param jasperPeriodkeepgenerated * @param jasperPeriodmappedfile * @param jasperPeriodtrimSpaces * @param jasperPerioddisplaySourceFragments * @param defaultPeriodisPeriodsession */ data class OrgApacheSlingScriptingJspJspScriptEngineFactoryProperties ( val jasperPeriodcompilerTargetVM: ConfigNodePropertyString? = null, val jasperPeriodcompilerSourceVM: ConfigNodePropertyString? = null, val jasperPeriodclassdebuginfo: ConfigNodePropertyBoolean? = null, val jasperPeriodenablePooling: ConfigNodePropertyBoolean? = null, val jasperPeriodieClassId: ConfigNodePropertyString? = null, val jasperPeriodgenStringAsCharArray: ConfigNodePropertyBoolean? = null, val jasperPeriodkeepgenerated: ConfigNodePropertyBoolean? = null, val jasperPeriodmappedfile: ConfigNodePropertyBoolean? = null, val jasperPeriodtrimSpaces: ConfigNodePropertyBoolean? = null, val jasperPerioddisplaySourceFragments: ConfigNodePropertyBoolean? = null, val defaultPeriodisPeriodsession: ConfigNodePropertyBoolean? = null ) { }
12
null
1
4
c2f6e076971d2592c1cbd3f70695c679e807396b
1,867
swagger-aem-osgi
Apache License 2.0
app/src/main/java/com/wan/android/ui/main/MainActivity.kt
qinghuaAndroid
252,683,218
false
null
package com.wan.android.ui.main import android.view.Menu import android.view.MenuItem import androidx.activity.viewModels import androidx.appcompat.app.ActionBarDrawerToggle import androidx.appcompat.app.AppCompatDelegate import androidx.drawerlayout.widget.DrawerLayout import androidx.navigation.fragment.NavHostFragment import androidx.navigation.ui.AppBarConfiguration import androidx.navigation.ui.setupActionBarWithNavController import androidx.navigation.ui.setupWithNavController import com.alibaba.android.arouter.facade.annotation.Route import com.alibaba.android.arouter.launcher.ARouter import com.google.android.material.badge.BadgeDrawable import com.google.android.material.bottomnavigation.BottomNavigationView import com.google.android.material.navigation.NavigationView import com.jeremyliao.liveeventbus.LiveEventBus import com.wan.android.R import com.wan.android.bean.CoinInfo import com.wan.android.databinding.ActivityMainBinding import com.wan.android.databinding.NavHeaderMainBinding import com.wan.android.ui.account.AccountViewModel import com.wan.baselib.ext.getThemeColor import com.wan.baselib.ext.showToast import com.wan.baselib.mvvm.BaseVMActivity import com.wan.baselib.utils.SettingUtil import com.wan.common.arouter.ArouterPath import com.wan.common.ext.navigation import dagger.hilt.android.AndroidEntryPoint import org.jetbrains.anko.backgroundColor import org.jetbrains.anko.sdk27.coroutines.onClick @AndroidEntryPoint @Route(path = ArouterPath.ACTIVITY_MAIN) class MainActivity : BaseVMActivity<MainViewModel, ActivityMainBinding>() { private val accountViewModel by viewModels<AccountViewModel>() private val mainViewModel by viewModels<MainViewModel>() private lateinit var navHeaderMainBinding: NavHeaderMainBinding override fun getLayoutId(): Int = R.layout.activity_main override fun initData() { receiveNotice() } override fun initView() { initDrawerLayout() initNavigation() initNavView() setThemeColor() initBottom() } private fun initDrawerLayout() { binding.drawerLayout.run { val toggle = ActionBarDrawerToggle( this@MainActivity, this, findViewById(com.wan.baselib.R.id.toolbar), R.string.navigation_drawer_open, R.string.navigation_drawer_close ) addDrawerListener(toggle) toggle.syncState() } } private fun initNavigation() { val navView: BottomNavigationView = binding.btmNavigation val drawerLayout: DrawerLayout = binding.drawerLayout val navHost = supportFragmentManager.findFragmentById(R.id.nav_host_fragment_activity_main) as NavHostFragment val navController = navHost.navController // Passing each menu ID as a set of Ids because each // menu should be considered as top level destinations. val topLevelDestinationIds = setOf( R.id.navigation_home, R.id.navigation_system, R.id.navigation_official, R.id.navigation_navigation, R.id.navigation_project ) val appBarConfiguration = AppBarConfiguration(topLevelDestinationIds, drawerLayout) setupActionBarWithNavController(navController, appBarConfiguration) navView.setupWithNavController(navController) } override fun loadData() { } override fun onCreateOptionsMenu(menu: Menu): Boolean { menuInflater.inflate(R.menu.menu_main, menu) return super.onCreateOptionsMenu(menu) } override fun onOptionsItemSelected(item: MenuItem): Boolean { when (item.itemId) { R.id.action_search -> { ARouter.getInstance().build(ArouterPath.ACTIVITY_SEARCH).navigation() return true } } return super.onOptionsItemSelected(item) } /** * init NavigationView */ private fun initNavView() { navHeaderMainBinding = NavHeaderMainBinding.bind(binding.navView.getHeaderView(0)) binding.navView.setNavigationItemSelectedListener(onDrawerNavigationItemSelectedListener) navHeaderMainBinding.tvUsername.onClick { if (accountViewModel.isLogin.not()) { ARouter.getInstance().build(ArouterPath.ACTIVITY_LOGIN).navigation() } } } /** * NavigationView 监听 */ private val onDrawerNavigationItemSelectedListener = NavigationView.OnNavigationItemSelectedListener { item -> when (item.itemId) { R.id.nav_score -> { ARouter.getInstance().build(ArouterPath.ACTIVITY_INTEGRAL).navigation(this) { onInterrupt { ARouter.getInstance().build(ArouterPath.ACTIVITY_LOGIN).with(it?.extras) .navigation() } } } R.id.nav_collect -> { ARouter.getInstance().build(ArouterPath.ACTIVITY_COLLECT).navigation(this) { onInterrupt { ARouter.getInstance().build(ArouterPath.ACTIVITY_LOGIN).with(it?.extras) .navigation() } } } R.id.nav_question -> { ARouter.getInstance().build(ArouterPath.ACTIVITY_QUESTION).navigation() } R.id.nav_setting -> { ARouter.getInstance().build(ArouterPath.ACTIVITY_SETTING).navigation() } R.id.nav_about_us -> { } R.id.nav_logout -> { logout() } R.id.nav_night_mode -> { switchNightMode() } R.id.nav_todo -> { } R.id.nav_square -> { ARouter.getInstance().build(ArouterPath.ACTIVITY_SHARE_LIST).navigation() } } // drawer_layout.closeDrawer(GravityCompat.START) true } private fun logout() { accountViewModel.logout() } /** * 切换日夜间模式 */ private fun switchNightMode() { if (SettingUtil.getIsNightMode()) { SettingUtil.setIsNightMode(false) AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_NO) } else { SettingUtil.setIsNightMode(true) AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_YES) } window.setWindowAnimations(R.style.WindowAnimationFadeInOut) recreate() } private fun initBottom() { binding.btmNavigation.run { //用于分配,检索,检查和清除徽章内显示的数字。默认情况下,显示的徽章没有数字 val badge = getOrCreateBadge(R.id.navigation_home) badge.clearNumber() val badge1 = getOrCreateBadge(R.id.navigation_system) badge1.number = 2 val badge2 = getOrCreateBadge(R.id.navigation_official) badge2.number = 100 //用于设置/获取徽章数字中允许的最大字符数,然后将其用'+'截断。预设值为4。 badge2.maxCharacterCount = 3 val badge3 = getOrCreateBadge(R.id.navigation_navigation) badge3.clearNumber() val badge4 = getOrCreateBadge(R.id.navigation_project) badge4.number = 30 badge4.maxCharacterCount = 3 //用于设置/获取它可以是徽章的严重性TOP_END,TOP_START,BOTTOM_END或BOTTOM_START。默认值为TOP_END badge4.badgeGravity = BadgeDrawable.TOP_START } } private fun showUserInfo(coinInfo: CoinInfo?) { navHeaderMainBinding.data = coinInfo binding.navView.menu.findItem(R.id.nav_logout).isVisible = (coinInfo != null) } private fun receiveNotice() { LiveEventBus.get(com.wan.common.constant.Const.THEME_COLOR, Int::class.java) .observe(this) { setThemeColor() } } private fun setThemeColor() { navHeaderMainBinding.root.backgroundColor = getThemeColor() } override fun startObserve() { mainViewModel.uiState.observe(this) { if (it.showLoading) showProgressDialog() else dismissProgressDialog() it.showSuccess?.let { userInfoEntity -> showUserInfo(userInfoEntity.coinInfo) } it.showError?.let { errorMsg -> showToast(errorMsg) } } accountViewModel.uiState.observe(this) { if (it.showLoading) showProgressDialog() else dismissProgressDialog() it.showSuccess?.let { showUserInfo(null) } it.showError?.let { errorMsg -> showToast(errorMsg) } } accountViewModel.isLogged.observe(this) { mainViewModel.getUserInfo() } } }
0
Kotlin
2
1
66bd36d4f8b94c2be53d40182b470dc6160791e3
8,901
WanAndroid-qh
Apache License 2.0
core/src/main/java/org/roylance/yaclib/core/utilities/InitUtilities.kt
roylanceMichael
64,247,402
false
null
package utilities object InitUtilities { const val OsNameProperty = "os.name" const val DpkgDeb = "dpkg-deb" const val Chmod = "chmod" const val ChmodExecutable = "755" const val RemoveDirectory = "rm" const val Find = "find" const val Move = "mv" const val Bash = "bash" const val Curl = "curl" const val Gradle = "gradle" const val Maven = "mvn" const val Nuget = "nuget" const val DotNet = "dotnet" const val Python = "python" const val Pip = "pip" const val XCodeBuild = "xcodebuild" const val Carthage = "carthage" const val TypeScriptCompiler = "tsc" const val NPM = "npm" const val Protoc = "protoc" const val Separator = """---------------------------------------------------------------------------------------------------------""" const val MinimumRequiredErrorMessage = """Minimum requirements to run Yaclib not met. Please ensure the following requirements are met: OS is OSX/MacOS or Linux protoc, mvn, gradle, python, tsc, npm can all be located with "which" optional: dotnet and nuget can be located with "which" MAKE SURE THAT ~/.bashrc or ~/.bash_profile PATH contains references to the folder these apps are located in! """ fun hasMinimumRequired(): Boolean { return isNotWindows() && hasNPM() && hasTypeScriptCompiler() && hasPython() && hasGradle() && hasProtoc() && hasMaven() } fun hasCSharp(): Boolean { return hasDotNet() && hasNuget() } fun hasProtoc(): Boolean { return FileProcessUtilities.getActualLocation(Protoc).isNotEmpty() } fun hasGradle(): Boolean { return FileProcessUtilities.getActualLocation(Gradle).isNotEmpty() } fun hasMaven(): Boolean { return FileProcessUtilities.getActualLocation(Maven).isNotEmpty() } fun hasDotNet(): Boolean { return FileProcessUtilities.getActualLocation(DotNet).isNotEmpty() } fun hasNuget(): Boolean { return FileProcessUtilities.getActualLocation(Nuget).isNotEmpty() } fun hasPython(): Boolean { return FileProcessUtilities.getActualLocation(Python).isNotEmpty() } fun hasTypeScriptCompiler(): Boolean { return FileProcessUtilities.getActualLocation(TypeScriptCompiler).isNotEmpty() } fun hasNPM(): Boolean { return FileProcessUtilities.getActualLocation(NPM).isNotEmpty() } fun isNotWindows(): Boolean { return !System.getProperty(OsNameProperty).toLowerCase().startsWith("window") } fun buildPhaseMessage(message: String): String { return """$Separator $message $Separator""" } }
3
null
1
1
df672db4e16d84885ec3aa84e74c57e1e9bc1ce3
2,749
yaorm
MIT License
beagle/src/main/kotlin/br/com/zup/beagle/android/data/serializer/BeagleJsonSerializerFactory.kt
ZupIT
391,144,851
false
null
/* * Copyright 2020, 2022 ZUP IT SERVICOS EM TECNOLOGIA E INOVACAO SA * * 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 br.com.zup.beagle.android.data.serializer import com.squareup.moshi.Moshi object BeagleJsonSerializerFactory { internal fun create(moshi: Moshi): BeagleJsonSerializer = BeagleSerializer(moshi) }
0
Kotlin
13
20
0240e15aa07e31d390e67dbeed4789b2b7ab76da
843
beagle-android
Apache License 2.0
Chapter04/src/main/kotlin/3_State.kt
PacktPublishing
373,735,637
false
null
fun main() { val snail = Snail() snail.seeHero() snail.getHit(1) snail.getHit(10) } interface WhatCanHappen { fun seeHero() fun getHit(pointsOfDamage: Int) fun calmAgain() } class Snail : WhatCanHappen { private var healthPoints = 10 private var mood: Mood = Still override fun seeHero() { mood = when (mood) { is Still -> { println("Aggressive") Aggressive } else -> { println("No change") mood } } } override fun getHit(pointsOfDamage: Int) { println("Hit for $pointsOfDamage points") healthPoints -= pointsOfDamage println("Health: $healthPoints") mood = when { (healthPoints <= 0) -> { println("Dead") Dead } mood is Aggressive -> { println("Retreating") Retreating } else -> { println("No change") mood } } } override fun calmAgain() { } } /* sealed class Mood { // Some abstract methods here, like draw(), for example } data object Still : Mood() data object Aggressive : Mood() data object Retreating : Mood() data object Dead : Mood()*/ sealed interface Mood { // Some abstract methods here, like draw(), for example } data object Still : Mood { } data object Aggressive : Mood data object Retreating : Mood data object Dead : Mood
0
null
9
7
887086024fbc675d35deb2d077ef0f4ed3d158e6
1,566
Kotlin-Design-Patterns-and-Best-Practices
MIT License
engrave2/src/main/java/com/angcyo/engrave2/data/TransitionParam.kt
angcyo
229,037,684
false
null
package com.angcyo.engrave2.data import android.graphics.Matrix import com.angcyo.bluetooth.fsc.laserpacker.HawkEngraveKeys import com.angcyo.bluetooth.fsc.laserpacker.bean._cutGCodeHeight import com.angcyo.bluetooth.fsc.laserpacker.bean._cutGCodeWidth import com.angcyo.bluetooth.fsc.laserpacker.bean._cutLoopCount import com.angcyo.bluetooth.fsc.laserpacker.bean._gcodeLineSpace import com.angcyo.bluetooth.fsc.laserpacker.bean._isAutoCnc import com.angcyo.bluetooth.fsc.laserpacker.bean._isGCodeUsePathData import com.angcyo.bluetooth.fsc.laserpacker.bean._sliceGranularity import com.angcyo.library.annotation.MM import com.angcyo.library.annotation.Pixel import com.angcyo.library.component.hawk.LibHawkKeys import com.angcyo.library.unit.toMm import com.angcyo.library.unit.toPixel /**转换需要的一些额外参数 * * [com.angcyo.engrave2.transition.EngraveTransitionHelper] * * @author <a href="mailto:[email protected]">angcyo</a> * @since 2022/10/10 */ data class TransitionParam( //---抖动算法需要的参数--- /**进行图片转抖动时, 图片是否已经反色了*/ val isBitmapInvert: Boolean = true, /**是否反色, 用来决定进入抖动算法前, 图片透明颜色应该使用什么颜色填充*/ val invert: Boolean = false, /**对比度 [-1~1]*/ val contrast: Float = 0f, /**亮度 [-1~1]*/ val brightness: Float = 0f, /**是否使用新的抖动算法*/ val useNewDithering: Boolean = HawkEngraveKeys.useNewDithering, //---GCode算法需要的参数--- /**是否仅使用图片转GCode的方式处理, 这样会强制忽略[android.graphics.Path]的转换 * 否则会自动优先先使用[android.graphics.Path]转GCode, * 然后在使用[android.graphics.Bitmap]转GCode*/ var onlyUseBitmapToGCode: Boolean = false, /**在处理图片转GCode时, 是否使用OpenCV的算法 */ var useOpenCvHandleGCode: Boolean = true, /**转GCode时, 是否要自动开关激光*/ val isAutoCnc: Boolean = _isAutoCnc, /**[_isGCodeUsePathData]*/ val gcodeUsePathData: Boolean = _isGCodeUsePathData, /**图片转GCode时, 是否是简单的线生成的图片. * 如果是线条生成的图片, 则开启此开关, 会有优化处理. 尤其是虚线 * 只在[useOpenCvHandleGCode=false]的情况下有效 * */ val isSingleLine: Boolean = false, /**[com.angcyo.opencv.OpenCV.bitmapToGCode]相关参数 * * 0:.svg文件 * 1:为静态图像文件 * 2:只获取轮廓(等同于线距足够大时的效果)(包括bmp,jpeg,png均可) * 3:不打印轮廓 */ var bitmapToGCodeType: Int = 2, /**向文件末尾写入M2*/ var bitmapToGCodeIsLast: Boolean = true, /**最先打印轮廓 or 最后打印轮廓*/ var bitmapToGCodeBoundFirst: Boolean = false, /**填充时的线距*/ var bitmapToGCodeLineSpace: Double = _gcodeLineSpace, /**使用图片像素转GCode时, 扫描像素的步长*/ @Pixel val pixelGCodeGapValue: Float = LibHawkKeys.pathPixelGapValue.toPixel(), /**路径采样步长*/ @MM var pathStep: Float? = null, /**路径采样公差 * [LibHawkKeys.pathTolerance]*/ @MM var pathTolerance: Float? = null, /**是否激活压缩输出GCode * [com.angcyo.engrave2.transition.EngraveTransitionHelper.transitionToGCode]*/ val enableGCodeShrink: Boolean = HawkEngraveKeys.enableGCodeShrink, //---切割相关--- /**是否使用GCode切割数据*/ val enableGCodeCutData: Boolean = false, /**切割数据循环次数*/ val cutLoopCount: Int? = _cutLoopCount, /**切割数据的宽度*/ val cutGCodeWidth: Float? = _cutGCodeWidth, /**切割数据的高度*/ val cutGCodeHeight: Float? = _cutGCodeHeight, /**GCode数据额外需要偏移的距离 * LX1 画笔模块数据偏移*/ @Pixel val gcodeOffsetLeft: Float = 0f, @Pixel val gcodeOffsetTop: Float = 0f, //-----------------切片相关----------------- /**是否要激活图片的切片*/ val enableSlice: Boolean = false, /**切片数量*/ val sliceCount: Int = 0, /**切片下降的高度*/ @MM val sliceHeight: Float = HawkEngraveKeys.minSliceHeight, /**切片的粒度*/ val sliceGranularity: Int? = _sliceGranularity, ) { /**需要平移的矩阵信息*/ @MM val translateMatrix: Matrix? get() = if (gcodeOffsetLeft != 0f || gcodeOffsetTop != 0f) { Matrix().apply { postTranslate(gcodeOffsetLeft.toMm(), gcodeOffsetTop.toMm()) } } else { null } /**需要平移的矩阵信息*/ @Pixel val translatePixelMatrix: Matrix? get() = if (gcodeOffsetLeft != 0f || gcodeOffsetTop != 0f) { Matrix().apply { postTranslate(gcodeOffsetLeft, gcodeOffsetTop) } } else { null } }
0
null
4
4
9e5646677153f5fba31c31a1bc8ce5753b84660a
4,175
UICoreEx
MIT License
src/main/kotlin/br/com/jiratorio/client/config/JiraClientConfiguration.kt
andrelugomes
230,294,644
true
{"Kotlin": 541514, "PLSQL": 366, "Dockerfile": 315, "TSQL": 269}
package br.com.jiratorio.client.config import br.com.jiratorio.config.internationalization.MessageResolver import br.com.jiratorio.domain.Account import br.com.jiratorio.domain.jira.JiraError import br.com.jiratorio.exception.JiraException import br.com.jiratorio.exception.UnauthorizedException import br.com.jiratorio.extension.account import br.com.jiratorio.extension.log import com.fasterxml.jackson.databind.ObjectMapper import feign.RequestInterceptor import feign.codec.ErrorDecoder import org.springframework.context.annotation.Bean import org.springframework.security.core.context.SecurityContextHolder import javax.servlet.http.HttpServletResponse class JiraClientConfiguration( private val objectMapper: ObjectMapper, private val messageResolver: MessageResolver ) { @Bean fun requestInterceptor() = RequestInterceptor { val principal: Account? = SecurityContextHolder.getContext().account if (principal != null) { it.header("Authorization", principal.token) } } @Bean fun errorDecoder() = ErrorDecoder { methodKey, response -> log.info("Method=errorDecoder, methodKey={}, response={}", methodKey, response) if (response.status() == HttpServletResponse.SC_UNAUTHORIZED) { UnauthorizedException() } else { JiraException( try { objectMapper.readValue(response.body().asInputStream(), JiraError::class.java) } catch (e: Exception) { log.error("Method=errorDecoder, methodKey={}, response={}", methodKey, response, e) JiraError(messageResolver.resolve("errors.session-timeout"), response.status().toLong()) } ) } } }
0
null
0
1
168de10e5e53f31734937816811ac9dae6940202
1,775
jirareport
MIT License
compiler/testData/codegen/box/inlineClasses/checkBoxingOnFunctionCallsGeneric.kt
JetBrains
3,432,266
false
{"Kotlin": 79571273, "Java": 6776465, "Swift": 4063829, "C": 2609744, "C++": 1957654, "Objective-C++": 175279, "JavaScript": 130754, "Python": 59855, "Shell": 34920, "Objective-C": 21463, "Lex": 21452, "Batchfile": 11382, "CSS": 11368, "Ruby": 10470, "Dockerfile": 9907, "Groovy": 7092, "EJS": 5241, "CMake": 4473, "HTML": 2699, "Puppet": 1698, "FreeMarker": 1393, "Roff": 725, "Scala": 80}
// WITH_STDLIB // WORKS_WHEN_VALUE_CLASS // LANGUAGE: +ValueClasses, +GenericInlineClassParameter OPTIONAL_JVM_INLINE_ANNOTATION value class InlineNotNullPrimitive<T: Int>(val x: T) OPTIONAL_JVM_INLINE_ANNOTATION value class InlineNotNullReference<T: String>(val y: T) fun <A, T: Int> testNotNullPrimitive(a: Any, b: A, c: InlineNotNullPrimitive<T>, d: InlineNotNullPrimitive<T>?) {} fun <A, T: String> testNotNullReference(a: Any, b: A, c: InlineNotNullReference<T>, d: InlineNotNullReference<T>?) {} fun test(a: InlineNotNullPrimitive<Int>, b: InlineNotNullReference<String>) { testNotNullPrimitive(a, a, a, a) // 3 box testNotNullReference(b, b, b, b) // 2 box } fun box(): String { val a = InlineNotNullPrimitive(10) val b = InlineNotNullReference("some") test(a, b) return "OK" }
181
Kotlin
5748
49,172
33eb9cef3d146062c103f9853d772f0a1da0450e
815
kotlin
Apache License 2.0
app/src/main/java/br/com/djalmahenry/pokedex/view/ui/pokedex/PokedexFragment.kt
DjalmaHenry
497,372,986
false
null
package br.com.djalmahenry.pokedex.view.ui.pokedex import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.ImageView import android.widget.TextView import androidx.fragment.app.Fragment import androidx.lifecycle.Observer import androidx.lifecycle.ViewModelProvider import androidx.recyclerview.widget.LinearLayoutManager import androidx.recyclerview.widget.RecyclerView import br.com.djalmahenry.pokedex.R import br.com.djalmahenry.pokedex.domain.Pokemon import br.com.djalmahenry.pokedex.view.PokemonAdapter class PokedexFragment : Fragment() { private lateinit var pokedexViewModel: PokedexViewModel private lateinit var recyclerView: RecyclerView private lateinit var loadingImageView:ImageView private lateinit var loadingTextView:TextView private val viewModel by lazy { ViewModelProvider(this, PokedexViewModelFactory()) .get(PokedexViewModel::class.java) } override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View? { pokedexViewModel = ViewModelProvider(this).get(PokedexViewModel::class.java) val root = inflater.inflate(R.layout.fragment_pokedex, container, false) recyclerView = root.findViewById(R.id.rvPokemons) loadingImageView = root.findViewById(R.id.loading_image_view) loadingImageView.setVisibility(View.VISIBLE) loadingTextView = root.findViewById(R.id.loading_text_view) loadingTextView.setVisibility(View.VISIBLE) viewModel.pokemons.observe(viewLifecycleOwner, Observer { loadRecyclerView(it) loadingTextView.setVisibility(View.GONE) loadingImageView.setVisibility(View.GONE) }) return root } private fun loadRecyclerView(pokemons: List<Pokemon?>) { recyclerView.layoutManager = LinearLayoutManager(getContext()) recyclerView.adapter = PokemonAdapter(pokemons) } }
0
Kotlin
0
0
e8f2865f00a5dbdf1ce504771cc4a52009477a8a
2,049
pokedex-android
MIT License
collect_app/src/main/java/org/odk/collect/android/configure/SettingsImporter.kt
ebayraktar
378,508,306
false
null
package org.odk.collect.android.configure import org.json.JSONException import org.json.JSONObject import org.odk.collect.android.application.initialization.SettingsMigrator import org.odk.collect.android.configure.qr.AppConfigurationKeys import org.odk.collect.android.preferences.source.SettingsProvider import org.odk.collect.projects.Project import org.odk.collect.projects.ProjectsRepository import org.odk.collect.shared.Settings class SettingsImporter( private val settingsProvider: SettingsProvider, private val settngsMigrator: SettingsMigrator, private val settingsValidator: SettingsValidator, private val generalDefaults: Map<String, Any>, private val adminDefaults: Map<String, Any>, private val settingsChangedHandler: SettingsChangeHandler, private val projectsRepository: ProjectsRepository ) { fun fromJSON(json: String, project: Project.Saved): Boolean { if (!settingsValidator.isValid(json)) { return false } val generalSettings = settingsProvider.getGeneralSettings(project.uuid) val adminSettings = settingsProvider.getAdminSettings(project.uuid) generalSettings.clear() adminSettings.clear() try { val jsonObject = JSONObject(json) val general = jsonObject.getJSONObject(AppConfigurationKeys.GENERAL) importToPrefs(general, generalSettings) val admin = jsonObject.getJSONObject(AppConfigurationKeys.ADMIN) importToPrefs(admin, adminSettings) if (jsonObject.has(AppConfigurationKeys.PROJECT)) { importProjectDetails(jsonObject.getJSONObject(AppConfigurationKeys.PROJECT), project) } } catch (ignored: JSONException) { // Ignored } settngsMigrator.migrate(generalSettings, adminSettings) clearUnknownKeys(generalSettings, generalDefaults) clearUnknownKeys(adminSettings, adminDefaults) loadDefaults(generalSettings, generalDefaults) loadDefaults(adminSettings, adminDefaults) for ((key, value) in generalSettings.getAll()) { settingsChangedHandler.onSettingChanged(project.uuid, value, key) } for ((key, value) in adminSettings.getAll()) { settingsChangedHandler.onSettingChanged(project.uuid, value, key) } return true } private fun importToPrefs(jsonObject: JSONObject, preferences: Settings) { jsonObject.keys().forEach { preferences.save(it, jsonObject[it]) } } private fun loadDefaults(preferences: Settings, defaults: Map<String, Any>) { defaults.forEach { (key, value) -> if (!preferences.contains(key)) { preferences.save(key, value) } } } private fun clearUnknownKeys(preferences: Settings, defaults: Map<String, Any>) { preferences.getAll().forEach { (key, _) -> if (!defaults.containsKey(key)) { preferences.remove(key) } } } private fun importProjectDetails(projectJson: JSONObject, project: Project.Saved) { val projectName = if (projectJson.has(AppConfigurationKeys.PROJECT_NAME)) projectJson.get(AppConfigurationKeys.PROJECT_NAME).toString() else project.name val projectIcon = if (projectJson.has(AppConfigurationKeys.PROJECT_ICON)) projectJson.get(AppConfigurationKeys.PROJECT_ICON).toString() else project.icon val projectColor = if (projectJson.has(AppConfigurationKeys.PROJECT_COLOR)) projectJson.get(AppConfigurationKeys.PROJECT_COLOR).toString() else project.color projectsRepository.save( project.copy( name = projectName, icon = projectIcon, color = projectColor ) ) } }
0
null
0
1
23f088204949e41e9e2683a7e2f401ede9732552
3,853
collect
Apache License 2.0