path
stringlengths 4
280
| owner
stringlengths 2
39
| repo_id
int64 21.1k
756M
| is_fork
bool 2
classes | languages_distribution
stringlengths 12
2.44k
⌀ | content
stringlengths 6
6.29M
| issues
float64 0
10k
⌀ | main_language
stringclasses 128
values | forks
int64 0
54.2k
| stars
int64 0
157k
| commit_sha
stringlengths 40
40
| size
int64 6
6.29M
| name
stringlengths 1
100
| license
stringclasses 104
values |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|
core/src/main/kotlin/org/hertsig/quartets/api/Util.kt | jorn86 | 461,587,060 | false | {"Kotlin": 28312} | package org.hertsig.quartets.api
import org.hertsig.quartets.BlindQuartets
import org.hertsig.quartets.api.game.Game
import org.hertsig.quartets.api.setup.Rules
import org.hertsig.quartets.api.setup.TurnMode
fun setup(
players: List<Player>,
startingPlayer: Player = players.random(),
rules: Rules = Rules()
): Game = BlindQuartets(players, rules).start(startingPlayer)
fun Game.isCompleted() = completedQuartets.size == rules.quartets
fun Game.printGameState() {
val builder = StringBuilder()
builder.append("Players:\n")
players.forEach {
val hand = hand(it)
builder.append("\t${it.name} (${hand.size} cards)")
if (rules.turnMode != TurnMode.FREE_FOR_ALL && it == currentTurn) builder.append(" (turn)")
builder.append(":\n")
hand.joinTo(builder, "\n\t\t", "\t\t", "\n")
}
builder.append("Known cards:\n")
definedCategories.forEach {
builder.append("\t${it.name}: ")
definedCards(it).joinTo(builder, postfix = "\n")
}
builder.append("Cards left in deck: $deckSize\n")
cardsInDeck.count { it.isBlank }.also { if (it != 0) builder.append("\t$it Blank\n") }
cardsInDeck.filter { !it.isBlank }.forEach {
builder.append("\t$it\n")
}
println(builder)
}
| 0 | Kotlin | 0 | 0 | 6cde39cb82a14385c7ff35a69ceba60d88b1376a | 1,279 | blind-quartets | MIT License |
src/main/kotlin/day14/part1/MaskOp.kt | bagguley | 329,976,670 | false | null | package day14.part1
class MaskOp(private val value: String) : Operation {
override fun apply(computer: Computer) {
computer.setMask(value)
}
override fun toString(): String {
return value
}
} | 0 | Kotlin | 0 | 0 | 6afa1b890924e9459f37c604b4b67a8f2e95c6f2 | 225 | adventofcode2020 | MIT License |
app/src/main/java/com/jx3box/data/net/model/ArticleListResult.kt | JX3BOX | 296,293,464 | false | {"Kotlin": 416471, "Java": 413805} | /*
* Copyright (c) 2020. jx3box.com
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.jx3box.data.net.model
/**
*@author Carey
*@date 2020/10/4
*/
data class ArticleListResult(
var list: List<ArticleDetailResult>,
var page: Int,
var pages: Int,
var per: Int,
var total: Int
) | 0 | Kotlin | 0 | 0 | 6931ec7f5edc83595f6baeec3063fd9c18759c5f | 856 | jx3box-android | Apache License 2.0 |
compiler/util-klib/src/org/jetbrains/kotlin/library/encodings/WobblyTF8.kt | JetBrains | 3,432,266 | false | {"Kotlin": 74444760, "Java": 6669398, "Swift": 4261253, "C": 2620837, "C++": 1953730, "Objective-C": 640870, "Objective-C++": 170766, "JavaScript": 135724, "Python": 48402, "Shell": 30960, "TypeScript": 22754, "Lex": 18369, "Groovy": 17273, "Batchfile": 11693, "CSS": 11368, "Ruby": 10470, "EJS": 5241, "Dockerfile": 5136, "HTML": 5073, "CMake": 4448, "Pascal": 1698, "FreeMarker": 1393, "Roff": 725, "LLVM": 395, "Scala": 80} | /*
* Copyright 2010-2021 JetBrains s.r.o. and Kotlin Programming Language contributors.
* Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file.
*/
@file:Suppress("NOTHING_TO_INLINE")
package org.jetbrains.kotlin.library.encodings
/**
* Implementation of Wobbly Transformation Format 8, a superset of UTF-8
* that encodes surrogate code points if they are not in a pair.
*
* See also https://simonsapin.github.io/wtf-8/
*/
object WobblyTF8 {
fun encode(string: String): ByteArray {
val stringLength = string.length
if (stringLength == 0) return EMPTY_BYTE_ARRAY
val buffer = ByteArray(stringLength * 3) // Allocate for the worse case.
var writtenBytes = 0
var index = 0
while (index < stringLength) {
val char1 = string[index++]
if (char1 < '\u0080') {
// U+0000..U+007F -> 0xxxxxxx
// 7 meaningful bits -> 1 byte
buffer[writtenBytes++] = char1.toInt()
} else if (char1 < '\u0800') {
// U+0080..U+07FF -> 110xxxxx 10xxxxxx
// 11 meaningful bits -> 2 bytes
val codePoint = char1.toInt()
buffer[writtenBytes++] = (codePoint ushr 6) or 0b1100_0000
buffer[writtenBytes++] = (codePoint and 0b0011_1111) or 0b1000_0000
} else {
if (Character.isHighSurrogate(char1) && index < stringLength) {
val char2 = string[index]
if (Character.isLowSurrogate(char2)) {
// a pair of surrogates, encode as in traditional UTF8
// U+D800..U+DBFF + U+DC00..U+DFFF -> 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx
// 21 meaningful bits -> 4 bytes
index++
val codePoint = Character.toCodePoint(char1, char2)
buffer[writtenBytes++] = (codePoint ushr 18) or 0b1111_0000
buffer[writtenBytes++] = ((codePoint ushr 12) and 0b0011_1111) or 0b1000_0000
buffer[writtenBytes++] = ((codePoint ushr 6) and 0b0011_1111) or 0b1000_0000
buffer[writtenBytes++] = (codePoint and 0b0011_1111) or 0b1000_0000
continue
}
}
// U+0800..U+FFFF -> 1110xxxx 10xxxxxx 10xxxxxx
// 16 meaningful bits -> 3 bytes
val codePoint = char1.toInt()
buffer[writtenBytes++] = (codePoint ushr 12) or 0b1110_0000
buffer[writtenBytes++] = ((codePoint ushr 6) and 0b0011_1111) or 0b1000_0000
buffer[writtenBytes++] = (codePoint and 0b0011_1111) or 0b1000_0000
}
}
return if (buffer.size == writtenBytes) buffer else buffer.copyOf(writtenBytes)
}
fun decode(array: ByteArray): String {
val arraySize = array.size
if (arraySize == 0) return EMPTY_STRING
val buffer = CharArray(arraySize) // Allocate for the worse case.
var charsWritten = 0
var index = 0
while (index < arraySize) {
val byte1 = array.readByteAsInt(index++)
if (byte1 and 0b1000_0000 == 0) {
// 0xxxxxxx -> U+0000..U+007F
// 1 byte -> 7 meaningful bits
buffer[charsWritten++] = byte1
continue
} else if (byte1 ushr 5 == 0b000_0110) {
// 110xxxxx 10xxxxxx -> U+0080..U+07FF
// 2 bytes -> 11 meaningful bits
if (index < arraySize) {
val byte2 = array.readByteAsInt(index)
if (isValidContinuation(byte2)) {
index++
buffer[charsWritten++] = ((byte1 and 0b0001_1111) shl 6) or (byte2 and 0b0011_1111)
continue
}
}
} else if (byte1 ushr 4 == 0b0000_1110) {
// 1110xxxx 10xxxxxx 10xxxxxx -> U+0800..U+FFFF
// 3 bytes -> 16 meaningful bits
if (index < arraySize) {
val byte2 = array.readByteAsInt(index)
if (isValidContinuation(byte2)) {
index++
if (index < arraySize) {
val byte3 = array.readByteAsInt(index)
if (isValidContinuation(byte3)) {
index++
buffer[charsWritten++] = ((byte1 and 0b0000_1111) shl 12) or
((byte2 and 0b0011_1111) shl 6) or
(byte3 and 0b0011_1111)
continue
}
}
}
}
} else if (byte1 ushr 3 == 0b0001_1110) {
// 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx -> U+D800..U+DBFF + U+DC00..U+DFFF
// 4 bytes -> 21 meaningful bits
if (index < arraySize) {
val byte2 = array.readByteAsInt(index)
if (isValidContinuation(byte2)) {
index++
if (index < arraySize) {
val byte3 = array.readByteAsInt(index)
if (isValidContinuation(byte3)) {
index++
if (index < arraySize) {
val byte4 = array.readByteAsInt(index)
if (isValidContinuation(byte4)) {
index++
val codePoint = ((byte1 and 0b0000_0111) shl 18) or
((byte2 and 0b0011_1111) shl 12) or
((byte3 and 0b0011_1111) shl 6) or
(byte4 and 0b0011_1111)
buffer[charsWritten++] = Character.highSurrogate(codePoint)
buffer[charsWritten++] = Character.lowSurrogate(codePoint)
continue
}
}
}
}
}
}
}
// unexpected end of the byte sequence or unexpected bit pattern
buffer[charsWritten++] = REPLACEMENT_CHAR
}
return if (buffer.size == charsWritten) String(buffer) else String(buffer, 0, charsWritten)
}
private fun ByteArray.readByteAsInt(index: Int): Int = this[index].toInt() and 0b1111_1111
private operator fun ByteArray.set(index: Int, value: Int) {
this[index] = value.toByte()
}
private operator fun CharArray.set(index: Int, value: Int) {
this[index] = value.toChar()
}
private fun isValidContinuation(byteN: Int) = byteN ushr 6 == 0b0000_0010
private val EMPTY_BYTE_ARRAY = byteArrayOf()
private const val EMPTY_STRING = ""
private const val REPLACEMENT_CHAR = '\ufffd'
}
| 166 | Kotlin | 5,771 | 46,772 | bef0946ab7e5acd5b24b971eca532c43c8eba750 | 7,346 | kotlin | Apache License 2.0 |
fluent-icons-extended/src/commonMain/kotlin/com/konyaco/fluent/icons/filled/ScreenSearch.kt | Konyaco | 574,321,009 | false | {"Kotlin": 11029508, "Java": 256912} |
package com.konyaco.fluent.icons.filled
import androidx.compose.ui.graphics.vector.ImageVector
import com.konyaco.fluent.icons.Icons
import com.konyaco.fluent.icons.fluentIcon
import com.konyaco.fluent.icons.fluentPath
public val Icons.Filled.ScreenSearch: ImageVector
get() {
if (_screenSearch != null) {
return _screenSearch!!
}
_screenSearch = fluentIcon(name = "Filled.ScreenSearch") {
fluentPath {
moveTo(2.0f, 7.25f)
curveTo(2.0f, 5.45f, 3.46f, 4.0f, 5.25f, 4.0f)
horizontalLineToRelative(13.5f)
curveTo(20.55f, 4.0f, 22.0f, 5.46f, 22.0f, 7.25f)
verticalLineToRelative(9.5f)
curveToRelative(0.0f, 1.8f, -1.46f, 3.25f, -3.25f, 3.25f)
horizontalLineToRelative(-6.28f)
lineToRelative(-2.04f, -2.05f)
arcTo(5.5f, 5.5f, 0.0f, false, false, 2.0f, 11.25f)
verticalLineToRelative(-4.0f)
close()
moveTo(5.5f, 20.0f)
curveToRelative(0.97f, 0.0f, 1.87f, -0.3f, 2.6f, -0.83f)
lineToRelative(2.62f, 2.61f)
arcToRelative(0.75f, 0.75f, 0.0f, true, false, 1.06f, -1.06f)
lineToRelative(-2.61f, -2.61f)
arcTo(4.5f, 4.5f, 0.0f, true, false, 5.5f, 20.0f)
close()
moveTo(5.5f, 18.5f)
arcToRelative(3.0f, 3.0f, 0.0f, true, true, 0.0f, -6.0f)
arcToRelative(3.0f, 3.0f, 0.0f, false, true, 0.0f, 6.0f)
close()
}
}
return _screenSearch!!
}
private var _screenSearch: ImageVector? = null
| 4 | Kotlin | 4 | 155 | 9e86d93bf1f9ca63a93a913c990e95f13d8ede5a | 1,709 | compose-fluent-ui | Apache License 2.0 |
compiler/testData/codegen/box/inlineClasses/hiddenConstructor/constructorReferencedFromOtherFile2.kt | JetBrains | 3,432,266 | false | {"Kotlin": 74444760, "Java": 6669398, "Swift": 4261253, "C": 2620837, "C++": 1953730, "Objective-C": 640870, "Objective-C++": 170766, "JavaScript": 135724, "Python": 48402, "Shell": 30960, "TypeScript": 22754, "Lex": 18369, "Groovy": 17273, "Batchfile": 11693, "CSS": 11368, "Ruby": 10470, "EJS": 5241, "Dockerfile": 5136, "HTML": 5073, "CMake": 4448, "Pascal": 1698, "FreeMarker": 1393, "Roff": 725, "LLVM": 395, "Scala": 80} | // WITH_STDLIB
// WORKS_WHEN_VALUE_CLASS
// LANGUAGE: +ValueClasses
// FILE: 1.kt
fun box(): String = X(Z("OK")).z.result
// FILE: 2.kt
OPTIONAL_JVM_INLINE_ANNOTATION
value class Z(val result: String)
class X(val z: Z)
| 166 | Kotlin | 5,771 | 46,772 | bef0946ab7e5acd5b24b971eca532c43c8eba750 | 224 | kotlin | Apache License 2.0 |
build.gradle.kts | wasabi-muffin | 378,753,431 | false | {"Objective-C": 1112998, "Kotlin": 144204, "Swift": 6514, "Ruby": 2369, "JavaScript": 503, "HTML": 175, "Dockerfile": 121} | // Top-level build file where you can add configuration options common to all sub-projects/modules.
buildscript {
repositories {
google()
mavenCentral()
}
dependencies {
classpath(Deps.Gradle.sqlDelight)
classpath(Deps.Gradle.kotlinSerialization)
classpath(Deps.Gradle.androidGradle)
classpath(Deps.Gradle.kotlin)
classpath("org.jetbrains.kotlin:kotlin-gradle-plugin:1.5.20")
}
}
// plugins {
// id("org.jlleitschuh.gradle.ktlint") version Versions1.ktlint_gradle_plugin
// }
allprojects {
version = "0.0.1"
repositories {
google()
mavenCentral()
maven(url = "https://oss.sonatype.org/content/repositories/snapshots/")
}
}
subprojects {
// apply(plugin = "org.jlleitschuh.gradle.ktlint")
//
// ktlint {
// version.set("0.37.2")
// enableExperimentalRules.set(true)
// verbose.set(true)
// filter {
// exclude { it.file.path.contains("build/") }
// }
// }
// afterEvaluate {
// tasks.named("check").configure {
// dependsOn(tasks.getByName("ktlintCheck"))
// }
// }
}
| 0 | Objective-C | 0 | 1 | 088077dc5db7245e1e116e32b8c65b74c510326f | 1,189 | mvi-multiplatform | Apache License 2.0 |
src/test/kotlin/com/github/michaelbull/advent/day6/Day6AnswersTest.kt | michaelbull | 225,205,583 | false | null | package com.github.michaelbull.advent.day6
import org.junit.jupiter.api.Assertions.assertEquals
import org.junit.jupiter.api.Test
class Day6AnswersTest {
private val map = readLocalOrbits()
@Test
fun answer1() {
assertEquals(249308, map.totalOrbits())
}
@Test
fun answer2() {
assertEquals(349, map.minOrbitalTransfers(from = "YOU", to = "SAN"))
}
}
| 0 | Kotlin | 0 | 2 | d271a7c43c863acd411bd1203a93fd10485eade6 | 398 | advent-2019 | ISC License |
spring-boot-project/spring-boot-docs/src/main/kotlin/org/springframework/boot/docs/io/webservices/template/MyService.kt | spring-projects | 6,296,790 | false | {"Java": 24755733, "Kotlin": 451737, "HTML": 58426, "Shell": 45767, "JavaScript": 33592, "Groovy": 15015, "Ruby": 8017, "Smarty": 2882, "Batchfile": 2145, "Dockerfile": 2102, "Mustache": 449, "Vim Snippet": 135, "CSS": 117} | /*
* Copyright 2012-2022 the original author or authors.
*
* 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.springframework.boot.docs.io.webservices.template
import org.springframework.boot.webservices.client.WebServiceTemplateBuilder
import org.springframework.stereotype.Service
import org.springframework.ws.client.core.WebServiceTemplate
import org.springframework.ws.soap.client.core.SoapActionCallback
@Service
class MyService(webServiceTemplateBuilder: WebServiceTemplateBuilder) {
private val webServiceTemplate: WebServiceTemplate
init {
webServiceTemplate = webServiceTemplateBuilder.build()
}
fun someWsCall(detailsReq: SomeRequest?): SomeResponse {
return webServiceTemplate.marshalSendAndReceive(
detailsReq,
SoapActionCallback("https://ws.example.com/action")
) as SomeResponse
}
}
| 589 | Java | 40,158 | 71,299 | c3b710a1f093423d6a3c8aad2a15695a2897eb57 | 1,346 | spring-boot | Apache License 2.0 |
compiler/testData/compileKotlinAgainstCustomBinaries/missingDependencyConflictingLibraries/source.kt | JetBrains | 3,432,266 | false | {"Kotlin": 74444760, "Java": 6669398, "Swift": 4261253, "C": 2620837, "C++": 1953730, "Objective-C": 640870, "Objective-C++": 170766, "JavaScript": 135724, "Python": 48402, "Shell": 30960, "TypeScript": 22754, "Lex": 18369, "Groovy": 17273, "Batchfile": 11693, "CSS": 11368, "Ruby": 10470, "EJS": 5241, "Dockerfile": 5136, "HTML": 5073, "CMake": 4448, "Pascal": 1698, "FreeMarker": 1393, "Roff": 725, "LLVM": 395, "Scala": 80} | package c
import b.B1
import b.B2
fun testA(b1: B1, b2: B2) {
b2.consumeA(b1.produceA())
b2.consumeA(b1.produceAGeneric("foo"))
}
fun testAA(b1: B1, b2: B2) {
b2.consumeAA(b1.produceAA())
}
fun testAAA(b1: B1, b2: B2) {
b2.consumeAAA(b1.produceAAA())
} | 166 | Kotlin | 5,771 | 46,772 | bef0946ab7e5acd5b24b971eca532c43c8eba750 | 272 | kotlin | Apache License 2.0 |
brigitte/src/test/java/brigitte/shield/BaseRoboTest.kt | aucd29 | 159,471,417 | false | null | @file:Suppress("NOTHING_TO_INLINE", "unused")
package brigitte.shield
import android.annotation.SuppressLint
import android.app.Application
import android.net.ConnectivityManager
import android.net.NetworkInfo
import androidx.annotation.ColorRes
import androidx.annotation.StringRes
import androidx.test.core.app.ApplicationProvider
import brigitte.color
import brigitte.string
import brigitte.systemService
import org.mockito.MockitoAnnotations
import org.robolectric.Shadows
import org.robolectric.shadows.ShadowApplication
import org.robolectric.shadows.ShadowNetworkInfo
/**
* Created by <a href="mailto:<EMAIL>"><NAME></a> on 2019-08-23 <p/>
*/
open class BaseRoboTest constructor() {
protected open fun initMock() {
MockitoAnnotations.initMocks(this)
}
inline fun string(@StringRes resid: Int) = app.string(resid)
inline fun color(@ColorRes resid: Int) = app.color(resid)
////////////////////////////////////////////////////////////////////////////////////
//
// SHADOW
//
////////////////////////////////////////////////////////////////////////////////////
protected val app = ApplicationProvider.getApplicationContext<Application>()
// https://stackoverflow.com/questions/35031301/android-robolectric-unit-test-for-marshmallow-permissionhelper
protected var shadowApp: ShadowApplication? = null
protected inline fun mockApp() {
if (shadowApp == null) {
shadowApp = Shadows.shadowOf(app)
}
}
protected inline fun mockPermissions(vararg permissions: String) {
mockApp()
shadowApp?.grantPermissions(*permissions)
}
// https://github.com/robolectric/robolectric/blob/master/robolectric/src/test/java/org/robolectric/shadows/ShadowConnectivityManagerTest.java
protected var shadowNetworkInfo: ShadowNetworkInfo? = null
@SuppressLint("MissingPermission")
protected inline fun mockNetwork() {
app.systemService<ConnectivityManager>()?.let {
shadowNetworkInfo = Shadows.shadowOf(it.activeNetworkInfo)
}
}
protected inline fun mockEnableNetwork() {
shadowNetworkInfo?.setConnectionStatus(NetworkInfo.State.CONNECTED)
}
protected inline fun mockDisableNetwork() {
shadowNetworkInfo?.setConnectionStatus(NetworkInfo.State.DISCONNECTED)
}
} | 0 | Kotlin | 0 | 2 | 759e4a0bbb96578a47cccf591015eb3b715cb3dc | 2,359 | clone-daum | Apache License 2.0 |
src/main/kotlin/platform/mcp/gradle/McpProjectResolverExtension.kt | minecraft-dev | 42,327,118 | false | null | /*
* Minecraft Dev for IntelliJ
*
* https://minecraftdev.org
*
* Copyright (c) 2023 minecraft-dev
*
* MIT License
*/
package com.demonwav.mcdev.platform.mcp.gradle
import com.demonwav.mcdev.platform.mcp.gradle.datahandler.McpModelFG2Handler
import com.demonwav.mcdev.platform.mcp.gradle.datahandler.McpModelFG3Handler
import com.demonwav.mcdev.platform.mcp.gradle.tooling.McpModelFG2
import com.demonwav.mcdev.platform.mcp.gradle.tooling.McpModelFG3
import com.demonwav.mcdev.util.runGradleTask
import com.intellij.openapi.externalSystem.model.DataNode
import com.intellij.openapi.externalSystem.model.project.ModuleData
import com.intellij.openapi.externalSystem.model.project.ProjectData
import java.nio.file.Paths
import org.gradle.tooling.model.idea.IdeaModule
import org.jetbrains.plugins.gradle.service.project.AbstractProjectResolverExtension
class McpProjectResolverExtension : AbstractProjectResolverExtension() {
// Register our custom Gradle tooling API model in IntelliJ's project resolver
override fun getExtraProjectModelClasses(): Set<Class<out Any>> =
setOf(McpModelFG2::class.java, McpModelFG3::class.java)
override fun getToolingExtensionsClasses() = extraProjectModelClasses
override fun resolveFinished(projectDataNode: DataNode<ProjectData>) {
// FG3 requires us to run a task for each module
// We do it here so that we can do this one time for all modules
// We do need to have a project here though
val project = resolverCtx.externalSystemTaskId.findProject() ?: return
val allTaskNames = findAllTaskNames(projectDataNode)
if (allTaskNames.isEmpty()) {
// Seems to not be FG3
return
}
val projectDirPath = Paths.get(projectDataNode.data.linkedExternalProjectPath)
runGradleTask(project, projectDirPath) { settings ->
settings.taskNames = allTaskNames
}
super.resolveFinished(projectDataNode)
}
private fun findAllTaskNames(node: DataNode<*>): List<String> {
fun findAllTaskNames(node: DataNode<*>, taskNames: MutableList<String>) {
val data = node.data
if (data is McpModelData) {
data.taskName?.let { taskName ->
taskNames += taskName
}
}
for (child in node.children) {
findAllTaskNames(child, taskNames)
}
}
val res = arrayListOf<String>()
findAllTaskNames(node, res)
return res
}
override fun populateModuleExtraModels(gradleModule: IdeaModule, ideModule: DataNode<ModuleData>) {
for (handler in handlers) {
handler.build(gradleModule, ideModule, resolverCtx)
}
// Process the other resolver extensions
super.populateModuleExtraModels(gradleModule, ideModule)
}
companion object {
private val handlers = listOf(McpModelFG2Handler, McpModelFG3Handler)
}
}
| 204 | Kotlin | 152 | 1,154 | 36cc3d47f7f39c847c0ebdcbf84980bc7262dab7 | 3,001 | MinecraftDev | MIT License |
cordapp/enclave/src/main/kotlin/com/r3/conclave/cordapp/sample/enclave/CordaEnclave.kt | R3Conclave | 351,032,160 | false | null | package com.r3.conclave.cordapp.sample.enclave
import com.r3.conclave.cordapp.common.SenderIdentity
import com.r3.conclave.cordapp.common.internal.SenderIdentityImpl
import com.r3.conclave.enclave.Enclave
import com.r3.conclave.enclave.EnclavePostOffice
import com.r3.conclave.mail.EnclaveMail
import java.io.ByteArrayInputStream
import java.io.DataInputStream
import java.security.PublicKey
import java.security.cert.CertificateFactory
import java.security.cert.X509Certificate
import java.util.logging.Logger
/**
* The CordaEnclave class extends the [Enclave] class with CorDapp's application level concerns.
*/
abstract class CordaEnclave : Enclave() {
/**
* Tries to authenticate the sender by verifying that the provided certificate chain is trusted, and that
* the sender is actually the subject of the certificate by verifying the signed secret against the subject's
* public key.
*/
private fun tryAuthenticateAndStoreIdentity(
mail: EnclaveMail
): Boolean {
val bais = ByteArrayInputStream(mail.bodyAsBytes)
val dis = DataInputStream(bais)
val isAnonymousSender = dis.readBoolean()
if (isAnonymousSender) {
return true
}
val identity = SenderIdentityImpl.deserialize(dis)
val sharedSecret = mail.authenticatedSender.encoded
val authenticated = authenticateIdentity(sharedSecret, identity)
if (authenticated) {
storeIdentity(mail.authenticatedSender, identity)
}
return authenticated
}
private fun authenticateIdentity(sharedSecret: ByteArray, identity: SenderIdentityImpl): Boolean {
val isTrusted = identity.isTrusted(trustedRootCertificate)
val didSign: Boolean = identity.didSign(sharedSecret)
return isTrusted && didSign
}
private fun storeIdentity(authenticatedSender: PublicKey, identity: SenderIdentityImpl) {
synchronized(identities) {
identities.put(authenticatedSender, identity)
}
}
/**
* Retrieve a cached identity based on encrypted public key of the sender.
* @return the sender's identity if the sender sent it, null otherwise.
*/
private fun getSenderIdentity(authenticatedSenderKey: PublicKey): SenderIdentity? {
synchronized(identities) {
return identities[authenticatedSenderKey]
}
}
/**
* The default Enclave's message callback that is invoked when a mail has been delivered by the host
* is overridden here to handle Corda/CorDapp application level concerns. Messages that are not meant to be
* processed at this level, are forwarded to the abstract [CordaEnclave.receiveMail] callback which is defined
* by the derived class.
*/
final override fun receiveMail(mail: EnclaveMail, routingHint: String?) {
if (isTopicFirstMessage(mail)) {
// only login supported so far
val authenticated = tryAuthenticateAndStoreIdentity(mail)
val result = if (authenticated) "-ack" else "-nak"
val postOffice: EnclavePostOffice = postOffice(mail.authenticatedSender, mail.topic + result)
val reply: ByteArray = postOffice.encryptMail(emptyBytes)
postMail(reply, routingHint)
} else {
val identity = getSenderIdentity(mail.authenticatedSender)
receiveMail(mail, routingHint, identity)
}
}
/**
* Invoked when a mail has been delivered by the host (via `EnclaveHost.deliverMail`), successfully decrypted and authenticated.
* This method is similar to the same overload in [Enclave] but with an additional optional parameter which is the verified [SenderIdentity]
* of the sender, verified against the root certificate hardcoded into this enclave ([trustedRootCertificate]).
*
* Any uncaught exceptions thrown by this method propagate to the calling `EnclaveHost.deliverMail`. In Java, checked
* exceptions can be made to propagate by rethrowing them in an unchecked one.
*
* @param mail Access to the decrypted/authenticated mail body+envelope.
* @param routingHint An optional string provided by the host that can be passed to [postMail] to tell the
* host that you wish to reply to whoever provided it with this mail (e.g. connection ID). Note that this may
* not be the same as the logical sender of the mail if advanced anonymity techniques are being used, like
* users passing mail around between themselves before it's delivered.
* @param identity The identity of the sender validated by the enclave. This can be used to uniquely identify the sender.
* Please be aware that this parameter is null if the sender decides to keep its anonymity.
*/
protected abstract fun receiveMail(mail: EnclaveMail, routingHint: String?, identity: SenderIdentity?)
companion object {
private const val topicFirstMessageSequenceNumber = 0L
private val emptyBytes = ByteArray(0)
private val identities: HashMap<PublicKey, SenderIdentity> = HashMap()
private const val trustedRootCertificateResourcePath = "/trustedroot.cer"
/**
* The network CA root certificate used to validate the identity shared by the sender
*/
@JvmStatic
val trustedRootCertificate: X509Certificate = run {
try {
CordaEnclave::class.java.getResourceAsStream(trustedRootCertificateResourcePath).use {
val certificateFactory: CertificateFactory = CertificateFactory.getInstance("X509")
certificateFactory.generateCertificate(it) as X509Certificate
}
} catch (exception: Exception) {
// Log an error message to let people know what went wrong and throw the exception again to ensure
// the behaviour related to exceptions remains the same
Logger.getGlobal().severe("Failed to load trusted root certificate. Please ensure the resource " +
"exists and it is not corrupted. Resource path: $trustedRootCertificateResourcePath")
throw exception
}
}
private fun isTopicFirstMessage(mail: EnclaveMail): Boolean {
return mail.sequenceNumber == topicFirstMessageSequenceNumber
}
}
}
| 2 | Kotlin | 10 | 11 | 88b54dcff8b16226b33f46a7710139e2f17be231 | 6,388 | conclave-samples | Apache License 2.0 |
DemoApp/DemoAppKotlin/app/src/main/java/co/optable/androidsdkdemo/ui/Identify/IdentifyFragment.kt | Optable | 295,526,133 | false | null | /*
* Copyright © 2020 Optable Technologies Inc. All rights reserved.
* See LICENSE for details.
*/
package co.optable.androidsdkdemo.ui.Identify
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Button
import android.widget.EditText
import android.widget.Switch
import android.widget.TextView
import androidx.fragment.app.Fragment
import androidx.lifecycle.Observer
import co.optable.android_sdk.OptableSDK
import co.optable.androidsdkdemo.MainActivity
import co.optable.androidsdkdemo.R
class IdentifyFragment : Fragment() {
private lateinit var identifyView: TextView
private lateinit var emailText: EditText
private lateinit var gaidSwitch: Switch
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
val root = inflater.inflate(R.layout.fragment_identify, container, false)
identifyView = root.findViewById(R.id.identifyView)
emailText = root.findViewById(R.id.editTextTextEmailAddress)
gaidSwitch = root.findViewById(R.id.gaidSwitch)
var btn = root.findViewById(R.id.identifyButton) as Button
btn.setOnClickListener {
MainActivity.OPTABLE!!
.identify(emailText.text.toString(), gaidSwitch.isChecked)
.observe(viewLifecycleOwner, Observer
{ result ->
var msg = "Calling identify API... "
if (result.status == OptableSDK.Status.SUCCESS) {
msg += "Success"
} else {
msg += "\n\nOptableSDK Error: ${result.message}"
}
identifyView.setText(msg)
})
}
return root
}
} | 2 | Kotlin | 0 | 0 | 7e9eaee97740eadca55434248967d2d04b560175 | 1,837 | optable-android-sdk | Apache License 2.0 |
app/src/main/java/com/example/dora/ui/ExtrasActivity.kt | dora4 | 321,392,715 | false | {"Kotlin": 30909, "Java": 10200} | package com.example.dora.ui
import android.os.Bundle
import com.alibaba.android.arouter.facade.annotation.Route
import com.example.dora.ARouterPath
import com.example.dora.R
import com.example.dora.MessageEvent
import com.example.dora.databinding.ActivityExtrasBinding
import dora.BaseActivity
import dora.arouter.open
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode
@Route(path = ARouterPath.ACTIVITY_EXTRAS)
class ExtrasActivity : BaseActivity<ActivityExtrasBinding>() {
override fun getLayoutId(): Int {
return R.layout.activity_extras
}
override fun initData(savedInstanceState: Bundle?, binding: ActivityExtrasBinding) {
open(ARouterPath.ACTIVITY_WEB_VIEW) {
// 闭包中定义传参
withString("url", "https://github.com/dora4");
// withInt("other_params", 0);
}
}
@Subscribe(threadMode = ThreadMode.MAIN)
fun onMessageEvent(msg: MessageEvent) {
}
} | 0 | Kotlin | 0 | 16 | 66830ee689bd20d949d6ca66f809e5fdf326ea48 | 982 | dora_samples | Apache License 2.0 |
app/src/main/java/com/luigivampa92/xlogger/ui/InteractionLogDetailsAdapter.kt | LuigiVampa92 | 445,334,837 | false | null | package com.luigivampa92.xlogger.ui
import android.view.LayoutInflater
import android.view.ViewGroup
import androidx.recyclerview.widget.RecyclerView
import com.luigivampa92.xlogger.domain.InteractionLog
import com.luigivampa92.xlogger.domain.InteractionLogEntryAction
import com.luigivampa92.xlogger.domain.InteractionType.*
class InteractionLogDetailsAdapter (
private val onShareClickListener: ((InteractionLog) -> Unit)? = null
) : RecyclerView.Adapter<RecyclerView.ViewHolder>() {
private companion object {
private const val VIEW_TYPE_NFC_ENTRY = 1
private const val VIEW_TYPE_NFC_HEADER = 2
private const val VIEW_TYPE_BLE_GATT_ENTRY = 10
private const val VIEW_TYPE_BLE_GATT_HEADER = 11
}
private var record: InteractionLog? = null
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): RecyclerView.ViewHolder =
when (viewType) {
VIEW_TYPE_NFC_ENTRY -> InteractionLogNfcEntryViewHolder(LayoutInflater.from(parent.context), parent)
VIEW_TYPE_NFC_HEADER -> InteractionLogNfcHeaderViewHolder(LayoutInflater.from(parent.context), parent, onShareClickListener)
VIEW_TYPE_BLE_GATT_ENTRY -> InteractionLogBleGattEntryViewHolder(LayoutInflater.from(parent.context), parent)
VIEW_TYPE_BLE_GATT_HEADER -> InteractionLogBleGattHeaderViewHolder(LayoutInflater.from(parent.context), parent, onShareClickListener)
else -> throw RuntimeException("Unknown view type")
}
override fun onBindViewHolder(holder: RecyclerView.ViewHolder, position: Int) {
if (record != null) {
when (holder.itemViewType) {
VIEW_TYPE_NFC_ENTRY -> { (holder as? InteractionLogNfcEntryViewHolder)?.bind(record!!.entries[position - 1]) }
VIEW_TYPE_NFC_HEADER -> { (holder as? InteractionLogNfcHeaderViewHolder)?.bind(record!!) }
VIEW_TYPE_BLE_GATT_ENTRY -> { (holder as? InteractionLogBleGattEntryViewHolder)?.bind(record!!.entries[position - 1]) }
VIEW_TYPE_BLE_GATT_HEADER -> { (holder as? InteractionLogBleGattHeaderViewHolder)?.bind(record!!) }
}
}
}
override fun getItemViewType(position: Int): Int {
if (record != null) {
if (position == 0) {
if (NFC_TAG_RAW == record!!.type || HCE_NORMAL == record!!.type || HCE_NFC_F == record!!.type) {
return VIEW_TYPE_NFC_HEADER
} else if (BLE_GATT_INTERACTION == record!!.type) {
return VIEW_TYPE_BLE_GATT_HEADER
} else {
throw RuntimeException("Unknown header view type")
}
}
else {
if (record!!.entries[position - 1].action.value == InteractionLogEntryAction.TRANSFER_DATA_NFC.value) {
return VIEW_TYPE_NFC_ENTRY
} else if (record!!.entries[position - 1].action.value >= 200) {
return VIEW_TYPE_BLE_GATT_ENTRY
} else {
throw RuntimeException("Unknown entry view type")
}
}
} else {
throw RuntimeException("Error. Record is not set")
}
}
override fun getItemCount() = if (record != null) 1 + record!!.entries.size else 0
fun setRecord(record: InteractionLog) {
this.record = record
notifyDataSetChanged()
}
} | 0 | Java | 1 | 15 | b77c755170c6bce528d9a3504476a872af5e8452 | 3,451 | XLogger | Apache License 2.0 |
game/plugins/src/main/kotlin/gg/rsmod/plugins/content/areas/spawns/spawns_15184.plugin.kts | 2011Scape | 578,880,245 | false | {"Kotlin": 8100267, "Dockerfile": 1354} | package gg.rsmod.plugins.content.areas.spawns
spawn_npc(npc = 8978, x = 3811, z = 5156, height = 1, walkRadius = 5, direction = Direction.NORTH, static = false) //Spider added by trent
spawn_npc(npc = Npcs.MUNCHER, x = 3819, z = 5141, height = 0, walkRadius = 5, direction = Direction.NORTH, static = false) //Muncher added by trent
spawn_npc(npc = Npcs.GRIM_REAPER_8977, x = 3807, z = 5150, height = 0, walkRadius = 5, direction = Direction.NORTH, static = false) //Grim Reaper added by trent
| 30 | Kotlin | 100 | 26 | 72de83aa7764b0bb0691da0b4f5716cbf0cae79e | 495 | game | Apache License 2.0 |
domain/src/main/java/br/com/lucas/cordeiro/cryptowalletapp/domain/utils/DateUtils.kt | lucas-cordeiro | 331,486,180 | false | null | package br.com.lucas.cordeiro.cryptowalletapp.domain.utils
import br.com.lucas.cordeiro.cryptowalletapp.domain.utils.DateUtils.Companion.getDateFormatted
import br.com.lucas.cordeiro.cryptowalletapp.domain.utils.DateUtils.Companion.getDayFormatted
import br.com.lucas.cordeiro.cryptowalletapp.domain.utils.DateUtils.Companion.getHourFormatted
import br.com.lucas.cordeiro.cryptowalletapp.domain.utils.DateUtils.Companion.isOfWeek
import br.com.lucas.cordeiro.cryptowalletapp.domain.utils.DateUtils.Companion.isToday
import br.com.lucas.cordeiro.cryptowalletapp.domain.utils.DateUtils.Companion.isTomorrow
import br.com.lucas.cordeiro.cryptowalletapp.domain.utils.DateUtils.Companion.isYesterday
import java.text.SimpleDateFormat
import java.time.Year
import java.util.*
class DateUtils {
companion object {
fun Long?.getDateFormatted(): String {
return SimpleDateFormat("dd/MM/yyyy", Locale.getDefault()).format(this.fromUnixDate())
}
fun Long?.getHourFormatted(): String{
return SimpleDateFormat("HH:mm", Locale.getDefault()).format(this.fromUnixDate())
}
fun Long?.getDayOfWeek(): String{
return SimpleDateFormat("EEEE", Locale.getDefault()).format(this.fromUnixDate())
}
fun Long?.getDayOfWeekShort(): String{
return SimpleDateFormat("EE", Locale.getDefault()).format(this.fromUnixDate())
}
fun Long?.getDay(): String {
return SimpleDateFormat("dd", Locale.getDefault()).format(this.fromUnixDate())
}
fun Long?.getMonth(): String {
return SimpleDateFormat("MMMM", Locale.getDefault()).format(this.fromUnixDate())
}
fun Long?.getYear(): String {
return SimpleDateFormat("yyyy", Locale.getDefault()).format(this.fromUnixDate())
}
fun Long?.getDayFormatted(): String {
val date = this.fromUnixDate()
return when(true){
date.isYesterday() -> "Ontem, ${getHourFormatted()}"
date.isToday() -> "Hoje, ${getHourFormatted()}"
date.isTomorrow() -> "Amanhã, ${getHourFormatted()}"
date.isOfWeek() -> "${getDayOfWeek()}, ${getHourFormatted()}"
date.isOfYear() -> "${getDay()} de ${getMonth()}"
else -> "${getDay()} de ${getMonth()} de ${getYear()}"
}
}
fun Date?.isToday(): Boolean {
val cal = Calendar.getInstance()
cal.timeInMillis = System.currentTimeMillis()
cal.resetHour()
val calDiff = Calendar.getInstance()
calDiff.timeInMillis = this?.time?:0L
calDiff.resetHour()
return cal.get(Calendar.DAY_OF_MONTH) == calDiff.get(Calendar.DAY_OF_MONTH) &&
cal.get(Calendar.MONTH) == calDiff.get(Calendar.MONTH) &&
cal.get(Calendar.YEAR) == calDiff.get(Calendar.YEAR)
}
fun Date?.isYesterday(): Boolean {
val cal = Calendar.getInstance()
cal.timeInMillis = System.currentTimeMillis()
cal.add(Calendar.DAY_OF_MONTH, -1)
cal.resetHour()
val calDiff = Calendar.getInstance()
calDiff.timeInMillis = this?.time?:0L
calDiff.resetHour()
return cal.get(Calendar.DAY_OF_MONTH) == calDiff.get(Calendar.DAY_OF_MONTH) &&
cal.get(Calendar.MONTH) == calDiff.get(Calendar.MONTH) &&
cal.get(Calendar.YEAR) == calDiff.get(Calendar.YEAR)
}
fun Date?.isTomorrow(): Boolean {
val cal = Calendar.getInstance()
cal.timeInMillis = System.currentTimeMillis()
cal.add(Calendar.DAY_OF_MONTH, +1)
cal.resetHour()
val calDiff = Calendar.getInstance()
calDiff.timeInMillis = this?.time?:0L
calDiff.resetHour()
return cal.get(Calendar.DAY_OF_MONTH) == calDiff.get(Calendar.DAY_OF_MONTH) &&
cal.get(Calendar.MONTH) == calDiff.get(Calendar.MONTH) &&
cal.get(Calendar.YEAR) == calDiff.get(Calendar.YEAR)
}
fun Date?.isOfWeek(): Boolean {
val cal = Calendar.getInstance()
cal.timeInMillis = System.currentTimeMillis()
cal.resetHour()
val calDiff = Calendar.getInstance()
calDiff.timeInMillis = this?.time?:0L
calDiff.resetHour()
return cal.get(Calendar.WEEK_OF_MONTH) == calDiff.get(Calendar.WEEK_OF_MONTH)
}
fun Date?.isOfMonth(): Boolean {
val cal = Calendar.getInstance()
cal.timeInMillis = System.currentTimeMillis()
cal.resetHour()
val calDiff = Calendar.getInstance()
calDiff.timeInMillis = this?.time?:0L
calDiff.resetHour()
return cal.get(Calendar.MONTH) == calDiff.get(Calendar.MONTH)
}
fun Date?.isOfYear(): Boolean {
val cal = Calendar.getInstance()
cal.timeInMillis = System.currentTimeMillis()
cal.resetHour()
val calDiff = Calendar.getInstance()
calDiff.timeInMillis = this?.time?:0L
calDiff.resetHour()
return cal.get(Calendar.YEAR) == calDiff.get(Calendar.YEAR)
}
fun Long?.fromUnixDate(): Date {
return if(this!=null)Date(this*1000L) else Date()
}
fun Calendar.resetHour() {
this.set(Calendar.HOUR_OF_DAY, 0)
this.set(Calendar.MINUTE, 0)
this.set(Calendar.SECOND, 0)
}
}
} | 0 | Kotlin | 0 | 2 | a15631fad4e972d061dcba5e512be29b64534e01 | 5,645 | Crypto-Wallet-App | MIT License |
app/src/main/java/com/example/cookit/ui/theme/Theme.kt | Renekakpo | 605,760,439 | false | {"Kotlin": 168668} | package com.example.cookit.ui.theme
import androidx.compose.foundation.isSystemInDarkTheme
import androidx.compose.material.MaterialTheme
import androidx.compose.material.darkColors
import androidx.compose.material.lightColors
import androidx.compose.runtime.Composable
import androidx.compose.ui.graphics.Color
import com.google.accompanist.systemuicontroller.rememberSystemUiController
private val DarkColorPalette = darkColors(
primary = Teal400, // Primary color
primaryVariant = Teal700, // Primary color variant
secondary = Teal400, // Secondary color
background = Color.Black, // Background color
surface = Teal400.copy(alpha = 0.5f), // Surface color
onPrimary = Color.White, // Text color on primary background in dark mode
onSecondary = Color.White, // Text color on secondary background in dark mode
onBackground = Color.White, // Text color on background in dark mode
onSurface = Teal400, // Text color on surface in dark mode
)
private val LightColorPalette = lightColors(
primary = Teal400, // Main color used to display components across the app
primaryVariant = Teal700, // Variant of the main color used for components such as topBar and statusBar
background = Color.White, // Background color
secondary = Teal70O700, // Color used by components such as floating button, checkbox, highlight items...
surface = Teal400,
onPrimary = Color.White,
onSecondary = Color.White,
onBackground = Color.Black,
onSurface = Color.White
)
@Composable
fun CookItTheme(darkTheme: Boolean = isSystemInDarkTheme(), content: @Composable () -> Unit) {
val systemUiController = rememberSystemUiController()
val colors = if (darkTheme) {
systemUiController.setSystemBarsColor(
color = Color.Transparent
)
DarkColorPalette
} else {
systemUiController.setSystemBarsColor(
color = Teal700
)
LightColorPalette
}
MaterialTheme(
colors = colors,
typography = Typography,
shapes = Shapes,
content = content
)
} | 0 | Kotlin | 0 | 0 | 67d02ed5a335a73a72d6c4be63a7b600635d7903 | 2,106 | cookIt | MIT License |
ComposeQuill/src/main/java/io/tbib/composequill/services/convertUriVideoToBase64.kt | the-best-is-best | 746,046,746 | false | {"Kotlin": 405885} | package io.tbib.composequill.services
import android.content.Context
import android.database.Cursor
import android.net.Uri
import android.provider.MediaStore
import java.io.File
import java.io.FileInputStream
internal fun convertUriImageToFile(uri: Uri, context: Context): String? {
// Handle the URI here
val projection = arrayOf(MediaStore.Images.Media.DATA)
val cursor: Cursor? = context.contentResolver.query(uri, projection, null, null, null)
cursor?.use {
if (it.moveToFirst()) {
return try {
val columnIndex = it.getColumnIndexOrThrow(MediaStore.Video.Media.DATA)
it.getString(columnIndex)
val file = File(it.getString(columnIndex))
val fileInputStream = FileInputStream(file)
val bytes = ByteArray(file.length().toInt())
fileInputStream.read(bytes)
fileInputStream.close()
file.path
} catch (e: Exception) {
null
}
}
}
return null
}
| 0 | Kotlin | 0 | 0 | 1ef172cba3fa29a85a5b2e7ce1d8d1157c5b1894 | 1,065 | ComposeQuill | Apache License 2.0 |
app/src/main/java/com/github/cfogrady/vitalwear/composable/util/PositionOffsetRatios.kt | cfogrady | 619,941,986 | false | {"Kotlin": 546579} | package com.github.cfogrady.vitalwear.composable.util
class PositionOffsetRatios {
companion object {
const val CHARACTER_OFFSET_FROM_BOTTOM = -0.05f
const val SUPPORT_CHARACTER_OFFSET_FROM_BOTTOM = -0.55f
const val CHARACTER_JUMP_BACK_POSITION = .2f
const val ATTACK_OFFSET_FROM_BOTTOM = -.15f
const val SUPPORT_ATTACK_OFFSET_FROM_BOTTOM = -.65f
const val ATTACK_OFFSET_FROM_CENTER = -.1f
const val HEALTH_OFFSET_FROM_TOP = .1f
}
} | 18 | Kotlin | 0 | 4 | 7d8da38e0cc955bc28b41cb2002ec0932e800f98 | 509 | VitalWear | MIT License |
maps-wrapper/src/main/java/org/m0skit0/android/mapswrapper/model/BitmapDescriptorFactory.kt | m0skit0 | 264,286,853 | false | null | package org.m0skit0.android.mapswrapper.model
import android.graphics.Bitmap
import org.m0skit0.android.mapswrapper.executeOrNull
object BitmapDescriptorFactory {
const val HUE_RED = com.google.android.gms.maps.model.BitmapDescriptorFactory.HUE_RED
const val HUE_ORANGE = com.google.android.gms.maps.model.BitmapDescriptorFactory.HUE_ORANGE
const val HUE_YELLOW = com.google.android.gms.maps.model.BitmapDescriptorFactory.HUE_YELLOW
const val HUE_GREEN = com.google.android.gms.maps.model.BitmapDescriptorFactory.HUE_GREEN
const val HUE_CYAN = com.google.android.gms.maps.model.BitmapDescriptorFactory.HUE_CYAN
const val HUE_AZURE = com.google.android.gms.maps.model.BitmapDescriptorFactory.HUE_AZURE
const val HUE_BLUE = com.google.android.gms.maps.model.BitmapDescriptorFactory.HUE_BLUE
const val HUE_VIOLET = com.google.android.gms.maps.model.BitmapDescriptorFactory.HUE_VIOLET
const val HUE_MAGENTA = com.google.android.gms.maps.model.BitmapDescriptorFactory.HUE_MAGENTA
const val HUE_ROSE = com.google.android.gms.maps.model.BitmapDescriptorFactory.HUE_ROSE
fun fromResource(id: Int): BitmapDescriptor {
val google = executeOrNull { com.google.android.gms.maps.model.BitmapDescriptorFactory.fromResource(id) }
val huawei = executeOrNull { com.huawei.hms.maps.model.BitmapDescriptorFactory.fromResource(id) }
return BitmapDescriptor(google, huawei)
}
fun defaultMarker(): BitmapDescriptor {
val google = executeOrNull { com.google.android.gms.maps.model.BitmapDescriptorFactory.defaultMarker() }
val huawei = com.huawei.hms.maps.model.BitmapDescriptorFactory.defaultMarker()
return BitmapDescriptor(google, huawei)
}
fun defaultMarker(hue: Float): BitmapDescriptor {
val google = executeOrNull { com.google.android.gms.maps.model.BitmapDescriptorFactory.defaultMarker(hue) }
val huawei = com.huawei.hms.maps.model.BitmapDescriptorFactory.defaultMarker(hue)
return BitmapDescriptor(google, huawei)
}
fun fromBitmap(bitmap: Bitmap): BitmapDescriptor {
val google = executeOrNull { com.google.android.gms.maps.model.BitmapDescriptorFactory.fromBitmap(bitmap) }
val huawei = com.huawei.hms.maps.model.BitmapDescriptorFactory.fromBitmap(bitmap)
return BitmapDescriptor(google, huawei)
}
}
| 3 | Kotlin | 5 | 15 | 15eda5bc36dbbda43c0ca2c2ae68822a81d6d0bd | 2,363 | maps-wrapper | MIT License |
src/main/kotlin/util/db.kt | MHCoinPublic | 352,153,311 | false | {"Kotlin": 24390} | package util
import com.google.api.client.googleapis.auth.oauth2.GoogleCredential
import okhttp3.MediaType
import okhttp3.OkHttpClient
import okhttp3.Request
import okhttp3.RequestBody
import java.io.FileInputStream
import java.io.IOException
val firetoken = firetoken()
val dbid = getConfig()?.firebase?.id
fun dbPut(s : String, id : String): String? { // положить в дб
val client = OkHttpClient()
val json = MediaType.parse("application/json")
val body = RequestBody.create(json, s)
val request = Request.Builder()
.url("https://$dbid.firebaseio.com/users/${id}.json?access_token=$firetoken")
.put(body)
.build()
client.newCall(request).execute().use { response ->
if (!response.isSuccessful) throw IOException("Unexpected code $response")
return response.body()?.string()
}
}
fun dbGet(id : String): String? { // взять из бд
val client = OkHttpClient()
val request = Request.Builder()
.url("https://$dbid.firebaseio.com/users/${id}.json?access_token=$firetoken")
.build()
val response = client.newCall(request).execute()
if (!response.isSuccessful) throw IOException("Unexpected code $response")
return response.body()?.string()
}
fun dbDelete(id : String): String? { // удалить из бд
val client = OkHttpClient()
val request = Request.Builder()
.url("https://$dbid.firebaseio.com/users/${id}.json?access_token=$firetoken")
.delete()
.build()
val response = client.newCall(request).execute()
if (!response.isSuccessful) throw IOException("Unexpected code $response")
return response.body()?.string()
}
fun firetoken(): String? { // получить OAuth2 токен для firebase
val serviceAccount = FileInputStream(getConfig()?.firebase?.key)
val googleCred = GoogleCredential.fromStream(serviceAccount)
val scoped = googleCred.createScoped(
listOf(
"https://www.googleapis.com/auth/firebase.database",
"https://www.googleapis.com/auth/userinfo.email"
)
)
scoped.refreshToken()
return scoped.accessToken
} | 0 | Kotlin | 1 | 0 | ddfac6f441ebca7f5238d70f4c6429b551a05faa | 2,216 | mhbot | MIT License |
app/src/main/java/com/battagliandrea/pokedex/ui/items/loading/LoadingItem.kt | battagliandrea | 266,046,335 | false | null | package com.battagliandrea.pokedex.ui.items.loading
import com.battagliandrea.pokedex.ui.items.base.ListItem
data class LoadingItem(
override val id: Int = 0
): ListItem()
| 0 | Kotlin | 0 | 0 | da48e150e10725f1b18e61b7fdcbce6a45c55b3f | 183 | Pokedex | Apache License 2.0 |
src/main/kotlin/MultiPlatformLibrary.kt | thumbcat-io | 282,368,645 | true | {"Kotlin": 14877} | /*
* Copyright 2019 IceRock MAG Inc. Use of this source code is governed by the Apache 2.0 license.
*/
import org.gradle.api.Project
import org.gradle.kotlin.dsl.DependencyHandlerScope
import org.jetbrains.kotlin.gradle.plugin.mpp.Framework
import org.jetbrains.kotlin.konan.target.Architecture
data class MultiPlatformLibrary(
val android: String? = null,
val common: String? = null,
val iosX64: String? = null,
val iosArm64: String? = null
) : KotlinNativeExportable {
constructor(
android: String? = null,
common: String? = null,
ios: String? = null
) : this(
android = android,
common = common,
iosX64 = ios,
iosArm64 = ios
)
override fun export(project: Project, framework: Framework) {
val arch = framework.target.konanTarget.architecture
when (arch) {
Architecture.X64 -> iosX64?.let { framework.export(it) }
Architecture.ARM64 -> iosArm64?.let { framework.export(it) }
else -> throw IllegalArgumentException("unknown architecture $arch")
}
}
}
fun DependencyHandlerScope.mppLibrary(library: MultiPlatformLibrary) {
library.android?.let { "androidMainImplementation"(it) }
library.common?.let { "commonMainApi"(it) }
library.iosX64?.let { "iosX64MainImplementation"(it) }
library.iosArm64?.let { "iosArm64MainImplementation"(it) }
}
| 0 | Kotlin | 0 | 0 | 7e1fe409d60a08976b5e0871e04b50cae72c765c | 1,414 | mobile-multiplatform-gradle-plugin | Apache License 2.0 |
libraries/tools/kotlin-maven-plugin-test/src/it/java8/test-kapt-allopen/src/main/kotlin/Pump.kt | JetBrains | 3,432,266 | false | {"Kotlin": 74444760, "Java": 6669398, "Swift": 4261253, "C": 2620837, "C++": 1953730, "Objective-C": 640870, "Objective-C++": 170766, "JavaScript": 135724, "Python": 48402, "Shell": 30960, "TypeScript": 22754, "Lex": 18369, "Groovy": 17273, "Batchfile": 11693, "CSS": 11368, "Ruby": 10470, "EJS": 5241, "Dockerfile": 5136, "HTML": 5073, "CMake": 4448, "Pascal": 1698, "FreeMarker": 1393, "Roff": 725, "LLVM": 395, "Scala": 80} | package coffee
interface Pump {
fun pump()
}
| 166 | Kotlin | 5,771 | 46,772 | bef0946ab7e5acd5b24b971eca532c43c8eba750 | 50 | kotlin | Apache License 2.0 |
src/main/kotlin/id/walt/model/dif/InputDescriptorConstraints.kt | walt-id | 392,607,264 | false | {"Kotlin": 1154151, "Java": 9175, "Open Policy Agent": 2974, "Shell": 2842, "Dockerfile": 1615, "JavaScript": 891, "Python": 351} | package id.walt.model.dif
import com.beust.klaxon.Json
data class InputDescriptorConstraints(
val fields: List<InputDescriptorField>? = null,
@Json(serializeNull = false) val limit_disclosure: DisclosureLimitation? = null
)
| 5 | Kotlin | 33 | 95 | a533315d1239271d53e7715bf10381cfd9259633 | 234 | waltid-ssikit | Apache License 2.0 |
src/main/java/ink/anur/common/pool/EventDriverPool.kt | anurnomeru | 242,305,129 | false | null | package ink.anur.common.pool
import com.google.common.util.concurrent.ThreadFactoryBuilder
import ink.anur.common.Shutdownable
import ink.anur.common._KanashiExecutors
import ink.anur.exception.DuplicateHandlerPoolException
import ink.anur.exception.NoSuchHandlerPoolException
import org.slf4j.LoggerFactory
import java.util.concurrent.ArrayBlockingQueue
import java.util.concurrent.CountDownLatch
import java.util.concurrent.Executors
import java.util.concurrent.LinkedBlockingDeque
import java.util.concurrent.TimeUnit
/**
* Created by <NAME> on 2020/2/22
*
* 只需要对外暴露这个池子即可
*/
class EventDriverPool<T> private constructor(private val clazz: Class<T>,
private val poolSize: Int,
private val consumeInternal: Long,
private val timeUnit: TimeUnit,
private val howToConsumeItem: ((T) -> Unit)?,
private val initLatch: CountDownLatch) : Shutdownable {
companion object {
private val logger = LoggerFactory.getLogger(this::class.java)
private val HANDLER_POOLS = mutableMapOf<Any, Any>()
/**
* 注册一个池子
*/
fun <T> register(clazz: Class<T>,
poolSize: Int,
consumeInternal: Long,
timeUnit: TimeUnit,
howToConsumeItem: ((T) -> Unit)?) {
synchronized(clazz) {
if (HANDLER_POOLS[clazz] != null) {
throw DuplicateHandlerPoolException("class $clazz is already register in Handler pool")
}
val initLatch = CountDownLatch(1)
HANDLER_POOLS[clazz] = EventDriverPool(clazz, poolSize, consumeInternal, timeUnit, howToConsumeItem, initLatch)
initLatch.countDown()
logger.info("初始化 [$clazz] 处理池成功,共有 $poolSize 个请求池被创建")
}
}
/**
* 向池子注入元素供给消费
*/
fun offer(t: Any) {
getPool(t.javaClass).offer(t)
}
/**
* 获取某个消费池
*/
private fun <T> getPool(clazz: Class<T>): EventDriverPool<T> {
val any = HANDLER_POOLS[clazz] ?: throw NoSuchHandlerPoolException("class $clazz has not register in Handler pool")
return any as EventDriverPool<T>
}
}
private val pool = _KanashiExecutors(logger, 0, poolSize, 60, TimeUnit.SECONDS, LinkedBlockingDeque(), ThreadFactoryBuilder().setNameFormat("EventDriverPool - $clazz")
.build())
private val handlers = mutableListOf<PoolHandler<T>>()
private val requestQueue: ArrayBlockingQueue<T> = ArrayBlockingQueue(Runtime.getRuntime().availableProcessors() * 2)
init {
for (i in 0 until poolSize) {
val poolHandler = PoolHandler(clazz, consumeInternal, timeUnit, howToConsumeItem, initLatch);
handlers.add(poolHandler)
pool.submit(poolHandler)
}
}
private fun offer(something: T) {
requestQueue.put(something)
}
private fun poll(timeout: Long, unit: TimeUnit): T? {
return requestQueue.poll(timeout, unit)
}
override fun shutDown() {
for (handler in handlers) {
handler.shutDown()
}
}
/**
* Created by <NAME> on 2020/2/22
*
* 如何去消费池子里的东西
*/
private class PoolHandler<T>(
private val clazz: Class<T>,
private val consumeInternal: Long,
private val timeUnit: TimeUnit,
private val howToConsumeItem: ((T) -> Unit)?,
private val initLatch: CountDownLatch
) : Runnable, Shutdownable {
@Volatile
private var shutdown = false
override fun run() {
initLatch.await()
while (true) {
val consume = getPool(clazz).poll(consumeInternal, timeUnit)
consume?.also { howToConsumeItem?.invoke(it) }
if (shutdown) break
}
}
override fun shutDown() {
shutdown = true
}
}
} | 1 | Kotlin | 1 | 5 | 27db6442ef9d4abc594d7e7719a8c772f03e61b6 | 4,341 | kanashi | MIT License |
usvm-jvm/src/test/kotlin/org/usvm/samples/stdlib/JavaIOFileInputStreamCheckTest.kt | UnitTestBot | 586,907,774 | false | {"Kotlin": 2547205, "Java": 471958} | package org.usvm.samples.stdlib
import org.usvm.samples.JavaMethodTestRunner
internal class JavaIOFileInputStreamCheckTest : JavaMethodTestRunner() {
// TODO unsupported matchers
// @Test
// fun testRead() {
// checkMocksAndInstrumentation(
// JavaIOFileInputStreamCheck::read,
// eq(1),
// { _, _, instrumentation, r ->
// val constructorMock = instrumentation.single() as UtNewInstanceInstrumentation
//
// val classIdEquality = constructorMock.classId == java.io.FileInputStream::class.id
// val callSiteIdEquality = constructorMock.callSites.single() == JavaIOFileInputStreamCheck::class.id
// val instance = constructorMock.instances.single() as UtCompositeModel
// val methodMock = instance.mocks.entries.single()
// val methodNameEquality = methodMock.key.name == "read"
// val mockValueResult = r == (methodMock.value.single() as UtPrimitiveModel).value as Int
//
// classIdEquality && callSiteIdEquality && instance.isMock && methodNameEquality && mockValueResult
// },
// additionalMockAlwaysClasses = setOf(java.io.FileInputStream::class.id), // there is a problem with coverage calculation of mocked values
// )
// }
} | 39 | Kotlin | 0 | 7 | 94c5a49a0812737024dee5be9d642f22baf991a2 | 1,395 | usvm | Apache License 2.0 |
uigesturerecognizer/src/androidTest/java/it/sephiroth/android/library/uigestures/Interaction.kt | sephiroth74 | 74,084,602 | false | null | package it.sephiroth.android.library.uigestures
import android.app.UiAutomation
import android.graphics.Point
import android.graphics.PointF
import android.os.SystemClock
import android.util.Log
import android.view.InputDevice
import android.view.InputEvent
import android.view.MotionEvent
import android.view.MotionEvent.ACTION_DOWN
import android.view.MotionEvent.PointerCoords
import android.view.ViewConfiguration
import android.view.accessibility.AccessibilityEvent
import androidx.test.core.view.PointerCoordsBuilder
import androidx.test.platform.app.InstrumentationRegistry.getInstrumentation
import androidx.test.uiautomator.Configurator
import androidx.test.uiautomator.Tracer
import androidx.test.uiautomator.UiObject
import androidx.test.uiautomator.UiObjectNotFoundException
import timber.log.Timber
import java.util.concurrent.TimeoutException
import kotlin.math.min
class Interaction {
private var mDownTime: Long = 0
fun clickNoSync(x: Int, y: Int, tapTimeout: Long = REGULAR_CLICK_LENGTH): Boolean {
Log.d(LOG_TAG, "clickNoSync ($x, $y)")
if (touchDown(x, y)) {
SystemClock.sleep(tapTimeout)
if (touchUp(x, y))
return true
}
return false
}
fun clickAndSync(x: Int, y: Int, timeout: Long): Boolean {
val logString = String.format("clickAndSync(%d, %d)", x, y)
Log.d(LOG_TAG, logString)
return runAndWaitForEvents(clickRunnable(x, y), WaitForAnyEventPredicate(
AccessibilityEvent.TYPE_WINDOW_CONTENT_CHANGED or AccessibilityEvent.TYPE_VIEW_SELECTED), timeout) != null
}
fun longTapNoSync(x: Int, y: Int, timeout: Long = ViewConfiguration.getLongPressTimeout().toLong()): Boolean {
if (DEBUG) {
Log.d(LOG_TAG, "longTapNoSync ($x, $y)")
}
if (touchDown(x, y)) {
SystemClock.sleep(timeout)
if (touchUp(x, y)) {
return true
}
}
return false
}
fun longTapAndSync(x: Int, y: Int, timeout: Long): Boolean {
val logString = String.format("clickAndSync(%d, %d)", x, y)
Log.d(LOG_TAG, logString)
return runAndWaitForEvents(longTapRunnable(x, y), WaitForAnyEventPredicate(
AccessibilityEvent.TYPE_WINDOW_CONTENT_CHANGED or AccessibilityEvent.TYPE_VIEW_SELECTED), timeout) != null
}
@Throws(UiObjectNotFoundException::class)
fun swipeLeftMultiTouch(view: UiObject, steps: Int, fingers: Int = 1): Boolean {
if (steps < 2)
throw RuntimeException("at least 2 steps required")
if (fingers < 2)
throw RuntimeException("at least 2 fingers required")
Tracer.trace(steps)
Tracer.trace(fingers)
val rect = view.visibleBounds
rect.inset(SWIPE_MARGIN_LIMIT, SWIPE_MARGIN_LIMIT)
Timber.v("visibleBounds: $rect")
if (rect.width() <= SWIPE_MARGIN_LIMIT * 2) return false
val array = arrayListOf<Array<MotionEvent.PointerCoords>>()
var pointArray = Array(fingers, init = { PointerCoords() })
val height = rect.height() / 2
val stepHeight = height / (fingers - 1)
val top = rect.top + (rect.height() - height) / 2
val width = rect.width()
val startPoint = Point(rect.right, top)
for (i in 0 until fingers) {
pointArray[i] =
PointerCoordsBuilder.newBuilder()
.setCoords(startPoint.x.toFloat(), startPoint.y + (stepHeight * i).toFloat())
.setSize(1f)
.build()
}
array.add(pointArray)
for (step in 1 until steps) {
pointArray = Array(fingers, init = { PointerCoords() })
for (i in 0 until fingers) {
pointArray[i] =
PointerCoordsBuilder.newBuilder()
.setCoords(startPoint.x.toFloat() - (width / steps) * step, startPoint.y + (stepHeight * i).toFloat())
.setSize(1f)
.build()
}
array.add(pointArray)
}
return performMultiPointerGesture(array.toTypedArray())
}
fun swipe(downX: Int, downY: Int, upX: Int, upY: Int, steps: Int, drag: Boolean = false,
timeout: Long = ViewConfiguration.getLongPressTimeout().toLong()): Boolean {
var ret: Boolean
var swipeSteps = steps
var xStep: Double
var yStep: Double
if (swipeSteps == 0) swipeSteps = 1
xStep = (upX - downX).toDouble() / swipeSteps
yStep = (upY - downY).toDouble() / swipeSteps
ret = touchDown(downX, downY)
if (drag) SystemClock.sleep(timeout)
for (i in 1 until swipeSteps) {
ret = ret and touchMove(downX + (xStep * i).toInt(), downY + (yStep * i).toInt())
if (!ret) {
break
}
SystemClock.sleep(MOTION_EVENT_INJECTION_DELAY_MILLIS.toLong())
}
if (drag) SystemClock.sleep(REGULAR_CLICK_LENGTH)
ret = ret and touchUp(upX, upY)
return ret
}
fun touchDown(x: Int, y: Int): Boolean {
if (DEBUG) {
Log.d(LOG_TAG, "touchDown ($x, $y)")
}
mDownTime = SystemClock.uptimeMillis()
val event = getMotionEvent(mDownTime, mDownTime, ACTION_DOWN, x.toFloat(), y.toFloat())
return injectEventSync(event)
}
fun touchUp(x: Int, y: Int): Boolean {
if (DEBUG) {
Log.d(LOG_TAG, "touchUp ($x, $y)")
}
val eventTime = SystemClock.uptimeMillis()
val event = getMotionEvent(mDownTime, eventTime, MotionEvent.ACTION_UP, x.toFloat(), y.toFloat())
mDownTime = 0
return injectEventSync(event)
}
fun touchMove(x: Int, y: Int): Boolean {
if (DEBUG) {
Log.d(LOG_TAG, "touchMove ($x, $y)")
}
val eventTime = SystemClock.uptimeMillis()
val event = getMotionEvent(mDownTime, eventTime, MotionEvent.ACTION_MOVE, x.toFloat(), y.toFloat())
return injectEventSync(event)
}
fun rotate(view: UiObject, deg: Float, steps: Int): Boolean {
val rect = view.visibleBounds
val size = min(rect.height(), rect.width()).toFloat()
val pt1 = PointF(rect.centerX().toFloat(), (rect.centerY() - (size / 4)))
val pt2 = PointF(rect.centerX().toFloat(), (rect.centerY() + (size / 4)))
val pt11 = PointF(pt1.x, pt1.y)
val pt21 = PointF(pt2.x, pt2.y)
val center = PointF(rect.centerX().toFloat(), rect.centerY().toFloat())
val array = arrayListOf<Array<MotionEvent.PointerCoords>>()
array.add(arrayOf(
PointerCoordsBuilder.newBuilder().setCoords(pt1.x, pt1.y).setSize(1f).build(),
PointerCoordsBuilder.newBuilder().setCoords(pt2.x, pt2.y).setSize(1f).build()))
for (i in 1 until steps) {
val p1 = Point2D.rotateAroundBy(pt11, center, (i.toFloat() / (steps - 1)) * deg)
val p2 = Point2D.rotateAroundBy(pt21, center, (i.toFloat() / (steps - 1)) * deg)
array.add(arrayOf(
PointerCoordsBuilder.newBuilder().setCoords(p1.x, p1.y).setSize(1f).build(),
PointerCoordsBuilder.newBuilder().setCoords(p2.x, p2.y).setSize(1f).build()))
}
return performMultiPointerGesture(array.toTypedArray())
}
fun performMultiPointerGesture(touches: Array<Array<PointerCoords>>,
sleepBeforeMove: Long = MOTION_EVENT_INJECTION_DELAY_MILLIS.toLong(),
sleepBeforeUp: Long = MOTION_EVENT_INJECTION_DELAY_MILLIS.toLong()):
Boolean {
Log.i(LOG_TAG, "performMultiPointerGesture, size: ${touches.size}")
var ret = true
// Get the pointer with the max steps to inject.
val maxSteps = touches.size - 1
// ACTION_DOWN
val currentPointer = touches[0][0]
val downTime = SystemClock.uptimeMillis()
Log.i(LOG_TAG, "ACTION_DOWN (${currentPointer.x}, ${currentPointer.y})")
var event: MotionEvent
event =
getMotionEvent(downTime, ACTION_DOWN, currentPointer.x, currentPointer.y, currentPointer.pressure, currentPointer.size)
ret = ret and injectEventSync(event)
SystemClock.sleep(MOTION_EVENT_INJECTION_DELAY_MILLIS.toLong())
// ACTION_POINTER_DOWN
Log.i(LOG_TAG, "ACTION_POINTER_DOWN")
// specify the properties for each pointer as finger touch
var properties = arrayOfNulls<MotionEvent.PointerProperties>(touches[0].size)
var pointerCoords = Array(touches[0].size) { PointerCoords() }
for (x in touches[0].indices) {
val prop = MotionEvent.PointerProperties()
prop.id = x
prop.toolType = Configurator.getInstance().toolType
properties[x] = prop
pointerCoords[x] = touches[0][x]
}
for (x in 1 until touches[0].size) {
event = MotionEvent.obtain(downTime, SystemClock.uptimeMillis(),
getPointerAction(MotionEvent.ACTION_POINTER_DOWN, x), x + 1, properties,
pointerCoords, 0, 0, 1f, 1f, 0, 0, InputDevice.SOURCE_TOUCHSCREEN, 0)
ret = ret and injectEventSync(event)
}
// ACTION_MOVE
if (maxSteps > 1) {
SystemClock.sleep(sleepBeforeMove)
// specify the properties for each pointer as finger touch
for (step in 1..maxSteps) {
Log.i(LOG_TAG, "ACTION_MOVE, steps: $step of $maxSteps")
val currentTouchArray = touches[step]
properties = arrayOfNulls(currentTouchArray.size)
pointerCoords = currentTouchArray
for (touchIndex in currentTouchArray.indices) {
val prop = MotionEvent.PointerProperties()
prop.id = touchIndex
prop.toolType = Configurator.getInstance().toolType
properties[touchIndex] = prop
}
event = MotionEvent.obtain(downTime, SystemClock.uptimeMillis(),
MotionEvent.ACTION_MOVE, currentTouchArray.size, properties, pointerCoords, 0, 0, 1f, 1f,
0, 0, InputDevice.SOURCE_TOUCHSCREEN, 0)
ret = ret and injectEventSync(event)
SystemClock.sleep(MOTION_EVENT_INJECTION_DELAY_MILLIS.toLong())
}
}
SystemClock.sleep(sleepBeforeUp)
// ACTION_POINTER_UP
Log.i(LOG_TAG, "ACTION_POINTER_UP")
val currentTouchArray = touches[touches.size - 1]
for (x in 1 until currentTouchArray.size) {
event = MotionEvent.obtain(downTime, SystemClock.uptimeMillis(),
getPointerAction(MotionEvent.ACTION_POINTER_UP, x), x + 1, properties,
pointerCoords, 0, 0, 1f, 1f, 0, 0, InputDevice.SOURCE_TOUCHSCREEN, 0)
ret = ret and injectEventSync(event)
}
// first to touch down is last up
Log.i(LOG_TAG, "ACTION_UP")
event = MotionEvent.obtain(downTime, SystemClock.uptimeMillis(), MotionEvent.ACTION_UP, 1,
properties, pointerCoords, 0, 0, 1f, 1f, 0, 0, InputDevice.SOURCE_TOUCHSCREEN, 0)
ret = ret and injectEventSync(event)
return ret
}
fun clickRunnable(x: Int, y: Int): Runnable {
return Runnable {
if (touchDown(x, y)) {
SystemClock.sleep(REGULAR_CLICK_LENGTH)
touchUp(x, y)
}
}
}
fun longTapRunnable(x: Int, y: Int): Runnable {
return Runnable {
if (touchDown(x, y)) {
SystemClock.sleep(ViewConfiguration.getLongPressTimeout().toLong())
touchUp(x, y)
}
}
}
fun getUiAutomation(): UiAutomation {
return getInstrumentation().uiAutomation
}
private fun runAndWaitForEvents(command: Runnable,
filter: UiAutomation.AccessibilityEventFilter, timeout: Long): AccessibilityEvent? {
return try {
getUiAutomation().executeAndWaitForEvent(command, filter, timeout)
} catch (e: TimeoutException) {
Log.w(LOG_TAG, "runAndwaitForEvents timed out waiting for events")
null
} catch (e: Exception) {
Log.e(LOG_TAG, "exception from executeCommandAndWaitForAccessibilityEvent", e)
null
}
}
fun injectEventSync(event: InputEvent): Boolean {
return getUiAutomation().injectInputEvent(event, true)
}
internal inner class WaitForAnyEventPredicate(private var mMask: Int) : UiAutomation.AccessibilityEventFilter {
override fun accept(t: AccessibilityEvent): Boolean {
return t.eventType and mMask != 0
}
}
companion object {
const val DEBUG: Boolean = true
const val REGULAR_CLICK_LENGTH: Long = 100
const val MOTION_EVENT_INJECTION_DELAY_MILLIS = 5
const val SWIPE_MARGIN_LIMIT = 5
val LOG_TAG: String = Interaction::class.java.name
fun getMotionEvent(downTime: Long, eventTime: Long, action: Int,
x: Float, y: Float, pressure: Float = 1f, size: Float = 1f, pointerCount: Int = 1): MotionEvent {
val properties = MotionEvent.PointerProperties()
properties.id = 0
properties.toolType = Configurator.getInstance().toolType
val coords = MotionEvent.PointerCoords()
coords.pressure = pressure
coords.size = size
coords.x = x
coords.y = y
return MotionEvent.obtain(downTime, eventTime, action, pointerCount,
arrayOf(properties), arrayOf(coords),
0, 0, 1.0f, 1.0f, 0, 0, InputDevice.SOURCE_TOUCHSCREEN, 0)
}
fun getMotionEvent(downTime: Long, action: Int, x: Float, y: Float, pressure: Float = 1f, size: Float = 1f, pointerCount: Int = 1): MotionEvent {
return getMotionEvent(downTime, SystemClock.uptimeMillis(), action, x, y, pressure, size, pointerCount)
}
fun getPointerAction(motionEnvent: Int, index: Int): Int {
return motionEnvent + (index shl MotionEvent.ACTION_POINTER_INDEX_SHIFT)
}
}
}
object Point2D {
/**
* Rotate a point around a pivot point. The point will be updated in place
*
* @param position - The point to be rotated
* @param center - The center point
* @param angle - The angle, in degrees
*/
fun rotateAroundBy(position: PointF, center: PointF, angle: Float): PointF {
val angleInRadians = angle * (Math.PI / 180)
val cosTheta = Math.cos(angleInRadians)
val sinTheta = Math.sin(angleInRadians)
val x = (cosTheta * (position.x - center.x) - sinTheta * (position.y - center.y) + center.x).toFloat()
val y = (sinTheta * (position.x - center.x) + cosTheta * (position.y - center.y) + center.y).toFloat()
return PointF(x, y)
}
/**
* Rotate a point in place around it's origin
*
* @param point - point to rotate
* @param origin - origin point
* @param deg - angle in degrees
*/
fun rotateAroundOrigin(point: PointF, origin: PointF, deg: Float) {
val rad = radians(deg.toDouble()).toFloat()
val s = Math.sin(rad.toDouble()).toFloat()
val c = Math.cos(rad.toDouble()).toFloat()
point.x -= origin.x
point.y -= origin.y
val xnew = point.x * c - point.y * s
val ynew = point.x * s + point.y * c
point.x = xnew + origin.x
point.y = ynew + origin.y
}
/**
* Get the point between 2 points at the given t distance ( between 0 and 1 )
*
* @param pt1 the first point
* @param pt2 the second point
* @param t the distance to calculate the average point ( 0 >= t <= 1 )
* @param dstPoint the destination point
*/
fun getLerp(pt1: PointF, pt2: PointF, t: Float): PointF {
return PointF(pt1.x + (pt2.x - pt1.x) * t, pt1.y + (pt2.y - pt1.y) * t)
}
/**
* Degrees to radians.
*
* @param degree the degree
* @return the double
*/
fun radians(degree: Double): Double {
return degree * (Math.PI / 180)
}
} | 1 | Kotlin | 23 | 133 | 6ff29e6a2c19d82d5825b59ab33f8fe57801ecf3 | 16,569 | AndroidUIGestureRecognizer | MIT License |
compiler/testData/compileKotlinAgainstJava/InterfaceMemberClass.kt | JetBrains | 3,432,266 | false | {"Kotlin": 74444760, "Java": 6669398, "Swift": 4261253, "C": 2620837, "C++": 1953730, "Objective-C": 640870, "Objective-C++": 170766, "JavaScript": 135724, "Python": 48402, "Shell": 30960, "TypeScript": 22754, "Lex": 18369, "Groovy": 17273, "Batchfile": 11693, "CSS": 11368, "Ruby": 10470, "EJS": 5241, "Dockerfile": 5136, "HTML": 5073, "CMake": 4448, "Pascal": 1698, "FreeMarker": 1393, "Roff": 725, "LLVM": 395, "Scala": 80} | package test
private fun useInterfaceMemberClass() = InterfaceMemberClass.MemberClass().func()
| 166 | Kotlin | 5,771 | 46,772 | bef0946ab7e5acd5b24b971eca532c43c8eba750 | 96 | kotlin | Apache License 2.0 |
core/model/src/main/java/com/jeckonly/core_model/entity/TypeEntity.kt | JeckOnly | 564,735,658 | false | {"Kotlin": 493841, "Java": 69358} | package com.jeckonly.core_model.entity
import androidx.room.ColumnInfo
import androidx.room.Entity
import androidx.room.PrimaryKey
import com.jeckonly.core_model.entity.helper.ExpenseOrIncome
@Entity(tableName = "type_table")
data class TypeEntity(
@PrimaryKey(autoGenerate = true)@ColumnInfo(name = "type_type_id") val typeId: Int = 0,
@ColumnInfo(name = "type_name") val name: String,
@ColumnInfo(name = "icon_id") val iconId: Int,
@ColumnInfo(name = "order") val order: Int,
@ColumnInfo(name = "expense_or_income") val expenseOrIncome: ExpenseOrIncome,
)
| 0 | Kotlin | 0 | 2 | 21c3092c90c858023c0122682ab95bb3f4d92745 | 581 | Budget | Apache License 2.0 |
app/src/main/java/com/example/animation/MainActivity4.kt | Sadegh-kh | 511,390,041 | false | {"Kotlin": 7995} | package com.example.animation
import android.os.Bundle
import com.example.animation.databinding.ActivityMain4Binding
import com.example.animation.ext.BaseActivity
class MainActivity4 : BaseActivity() {
lateinit var binding: ActivityMain4Binding
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding= ActivityMain4Binding.inflate(layoutInflater)
setContentView(binding.root)
}
} | 0 | Kotlin | 0 | 1 | 723879bec6733ae36ac75517b5de31479c5328ad | 457 | animation | MIT License |
src/main/kotlin/de/codecentric/workshop/hexagonal/cinema/tickets/controller/RecommendationController.kt | cfranzen | 648,262,059 | false | null | package de.codecentric.workshop.hexagonal.cinema.tickets.controller
import de.codecentric.workshop.hexagonal.cinema.tickets.config.DatakrakenProperties
import de.codecentric.workshop.hexagonal.cinema.tickets.model.Customer
import de.codecentric.workshop.hexagonal.cinema.tickets.model.DatakrakenCustomerData
import de.codecentric.workshop.hexagonal.cinema.tickets.model.Genre
import de.codecentric.workshop.hexagonal.cinema.tickets.model.MovieState
import de.codecentric.workshop.hexagonal.cinema.tickets.repositories.CustomerRepository
import de.codecentric.workshop.hexagonal.cinema.tickets.repositories.MovieRepository
import org.springframework.boot.web.client.RestTemplateBuilder
import org.springframework.core.ParameterizedTypeReference
import org.springframework.http.HttpMethod
import org.springframework.http.MediaType
import org.springframework.transaction.annotation.Transactional
import org.springframework.web.bind.annotation.GetMapping
import org.springframework.web.bind.annotation.PathVariable
import org.springframework.web.bind.annotation.RestController
import org.springframework.web.client.RestClientException
@RestController
class MovieRecommendationController(
private val customerRepository: CustomerRepository,
private val movieRepository: MovieRepository,
private val datakrakenProperties: DatakrakenProperties,
private val restTemplateBuilder: RestTemplateBuilder
) {
companion object {
private const val MIN_RECOMMENDATIONS = 3
}
@GetMapping("/recommendation/{customerId}")
@Transactional
fun recommendMoviesToUser(@PathVariable("customerId") customerId: Int): List<RecommendationDTO> {
val customer = findCustomerById(customerId)
return calcRecommendations(customer)
}
@GetMapping("/recommendation/{customerId}/html", produces = [MediaType.TEXT_HTML_VALUE])
@Transactional
fun recommendMoviesToUserInHtml(@PathVariable("customerId") customerId: Int): String {
val customer = findCustomerById(customerId)
val recommendations = calcRecommendations(customer)
return """
<html>
<header>
<title>Customer Recommendations</title>
</header>
<body>
<table>
<th>
<td>Movie ID</td>
<td>Title</td>
<td>Probability</td>
</th>
${
recommendations.map { printRecommendationInfoAsHtml(it) }.joinToString(separator = "\n")
.prependIndent(" ")
}
</table>
</body>
</html>
""".trimIndent()
}
private fun calcRecommendations(customer: Customer): List<RecommendationDTO> {
val recommendations = mutableListOf<RecommendationDTO>()
recommendations.addAll(recommendByFavorites(customer))
if (recommendations.size < MIN_RECOMMENDATIONS) {
recommendations.addAll(fillUpByEqualGenre(recommendations))
}
if (recommendations.size < MIN_RECOMMENDATIONS) {
recommendations.addAll(fillUpByDatakrakenRecommendations(customer, recommendations))
}
if (recommendations.size < MIN_RECOMMENDATIONS) {
throw IllegalStateException("Could not recommend movies for customer with ID ${customer.id}")
}
return recommendations
}
private fun findCustomerById(customerId: Int): Customer =
customerRepository.findById(customerId)
.orElseThrow { IllegalArgumentException("Could not find customer with ID $customerId") }
private fun recommendByFavorites(customer: Customer): List<RecommendationDTO> {
val favoriteMovieIds = customer.data.favorites.map { it.movieId }
return movieRepository
.findAllById(favoriteMovieIds)
.filter { it.state == MovieState.IN_THEATER }
.map { RecommendationDTO(it.id, 0.5) }
}
private fun fillUpByEqualGenre(currentRecommendations: List<RecommendationDTO>): List<RecommendationDTO> {
val missingRecommendations = MIN_RECOMMENDATIONS - currentRecommendations.size
val movieIds = currentRecommendations.map { it.movieId }.toSet()
val moviesById = movieRepository.findAllById(movieIds).associateBy { it.id }
val currentGenres = currentRecommendations.mapNotNull { moviesById[it.movieId]?.genre }.toSet()
return movieRepository
.findByGenreIn(currentGenres)
.filter { !movieIds.contains(it.id) }
.sortedBy { it.id }
.take(missingRecommendations)
.map { RecommendationDTO(it.id, 0.05) }
}
private fun fillUpByDatakrakenRecommendations(
customer: Customer,
currentRecommendations: List<RecommendationDTO>
): List<RecommendationDTO> {
val restTemplate = restTemplateBuilder.rootUri(datakrakenProperties.url).build()
val response = try {
restTemplate.exchange(
"/api/?email={email}",
HttpMethod.GET,
null,
object : ParameterizedTypeReference<DatakrakenCustomerData>() {},
mapOf("email" to customer.email)
)
} catch (e: RestClientException) {
return emptyList()
}
if (response.statusCode.isError || response.body == null) {
return emptyList()
}
val foundGenres = response.body!!.data
.flatMap { dataEntry -> dataEntry.genres ?: emptyList() }
.map { datakrakenGenres -> Genre.findByName(datakrakenGenres) }
.filterNotNull()
val missingRecommendations = MIN_RECOMMENDATIONS - currentRecommendations.size
return movieRepository
.findByGenreIn(foundGenres)
.sortedBy { it.id }
.take(missingRecommendations)
.map { RecommendationDTO(it.id, 0.01) }
}
private fun printRecommendationInfoAsHtml(recommendation: RecommendationDTO): String {
val movie = movieRepository.findById(recommendation.movieId)
.orElseThrow { IllegalStateException("Could not find movie for ID ${recommendation.movieId}") }
return """
<tr>
<td>${movie.id}</td>
<td>${movie.title}</td>
<td>${recommendation.probability}</td>
</tr>
""".trimIndent()
}
}
data class RecommendationDTO(
val movieId: Int,
val probability: Double
)
| 0 | Kotlin | 0 | 0 | 9d410e86481371f99531d6c50390a08f9dbdb771 | 6,590 | cinema-tickets-hexa-workshop | MIT License |
vector/src/main/java/im/vector/activity/DeactivateAccountActivity.kt | vector-im | 48,181,728 | false | null | /*
* Copyright 2018 New Vector Ltd
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package im.vector.activity
import android.content.Context
import android.content.Intent
import android.widget.CheckBox
import android.widget.EditText
import butterknife.BindView
import butterknife.OnClick
import im.vector.Matrix
import im.vector.R
import org.matrix.androidsdk.MXSession
import org.matrix.androidsdk.core.callback.SimpleApiCallback
import org.matrix.androidsdk.core.model.MatrixError
/**
* Displays the Account deactivation screen.
*/
class DeactivateAccountActivity : VectorAppCompatActivity() {
/* ==========================================================================================
* UI
* ========================================================================================== */
@BindView(R.id.deactivate_account_erase_checkbox)
lateinit var eraseCheckBox: CheckBox
@BindView(R.id.deactivate_account_password)
lateinit var passwordEditText: EditText
/* ==========================================================================================
* DATA
* ========================================================================================== */
private lateinit var session: MXSession
/* ==========================================================================================
* Life cycle
* ========================================================================================== */
override fun getLayoutRes() = R.layout.activity_deactivate_account
override fun getTitleRes() = R.string.deactivate_account_title
override fun initUiAndData() {
super.initUiAndData()
configureToolbar()
waitingView = findViewById(R.id.waiting_view)
// Get the session
session = Matrix.getInstance(this).defaultSession
}
/* ==========================================================================================
* UI Event
* ========================================================================================== */
@OnClick(R.id.deactivate_account_button_submit)
internal fun onSubmit() {
// Validate field
val password = <PASSWORD>EditText.text.toString()
if (password.isEmpty()) {
passwordEditText.error = getString(R.string.auth_missing_password)
return
}
showWaitingView()
CommonActivityUtils.deactivateAccount(this,
session,
password,
eraseCheckBox.isChecked,
object : SimpleApiCallback<Void>(this) {
override fun onSuccess(info: Void?) {
hideWaitingView()
CommonActivityUtils.startLoginActivityNewTask(this@DeactivateAccountActivity)
}
override fun onMatrixError(e: MatrixError) {
hideWaitingView()
if (e.errcode == MatrixError.FORBIDDEN) {
passwordEditText.error = getString(R.string.auth_invalid_login_param)
} else {
super.onMatrixError(e)
}
}
override fun onNetworkError(e: Exception) {
hideWaitingView()
super.onNetworkError(e)
}
override fun onUnexpectedError(e: Exception) {
hideWaitingView()
super.onUnexpectedError(e)
}
}
)
}
@OnClick(R.id.deactivate_account_button_cancel)
internal fun onCancel() {
finish()
}
/* ==========================================================================================
* Companion
* ========================================================================================== */
companion object {
fun getIntent(context: Context) = Intent(context, DeactivateAccountActivity::class.java)
}
}
| 1,107 | Java | 417 | 1,423 | a763655c54c4e465d2ae81e3ecd6a5146564771f | 4,603 | riot-android | Apache License 2.0 |
core/src/main/java/at/specure/info/network/ActiveNetworkWatcher.kt | rtr-nettest | 195,193,208 | false | null | /*
* 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 at.specure.info.network
import android.content.Context
import android.net.ConnectivityManager
import android.net.Network
import android.os.Handler
import android.os.Looper
import android.telephony.SubscriptionManager
import android.telephony.TelephonyManager
import at.rmbt.client.control.getCorrectDataTelephonyManager
import at.rmbt.client.control.getCurrentDataSubscriptionId
import at.specure.info.TransportType
import at.specure.info.cell.CellNetworkInfo
import at.specure.info.connectivity.ConnectivityInfo
import at.specure.info.connectivity.ConnectivityWatcher
import at.specure.info.ip.CaptivePortal
import at.specure.info.wifi.WifiInfoWatcher
import at.specure.location.LocationState
import at.specure.location.LocationStateWatcher
import at.specure.util.filterOnlyPrimaryActiveDataCell
import at.specure.util.isFineLocationPermitted
import at.specure.util.isLocationServiceEnabled
import at.specure.util.isReadPhoneStatePermitted
import at.specure.util.mobileNetworkType
import at.specure.util.synchronizedForEach
import at.specure.util.toCellNetworkInfo
import cz.mroczis.netmonster.core.INetMonster
import cz.mroczis.netmonster.core.factory.NetMonsterFactory
import cz.mroczis.netmonster.core.model.cell.CellLte
import cz.mroczis.netmonster.core.model.cell.CellNr
import cz.mroczis.netmonster.core.model.cell.ICell
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.launch
import timber.log.Timber
import java.util.Collections
private const val CELL_UPDATE_DELAY = 1000L
/**
* Active network watcher that is aggregates all network watchers
* to detect which one is currently active and get its data
*/
class ActiveNetworkWatcher(
private val context: Context,
private val netMonster: INetMonster,
private val subscriptionManager: SubscriptionManager,
private val telephonyManager: TelephonyManager,
private val connectivityManager: ConnectivityManager,
private val connectivityWatcher: ConnectivityWatcher,
private val wifiInfoWatcher: WifiInfoWatcher,
private val locationStateWatcher: LocationStateWatcher,
private val captivePortal: CaptivePortal
) : LocationStateWatcher.Listener {
private val listeners = Collections.synchronizedSet(mutableSetOf<NetworkChangeListener>())
private var isCallbacksRegistered = false
private var lastConnectivityInfo: ConnectivityInfo? = null
private val handler = Looper.myLooper()?.let { Handler(it) }
private val signalUpdateRunnable = Runnable {
updateCellNetworkInfo()
}
private var _currentNetworkInfo: NetworkInfo? = null
set(value) {
field = value
listeners.synchronizedForEach {
it.onActiveNetworkChanged(value)
}
}
init {
locationStateWatcher.addListener(this)
}
/**
* Returns active network information [NetworkInfo] if it is available
*/
val currentNetworkInfo: NetworkInfo?
get() = _currentNetworkInfo
private val connectivityCallback = object : ConnectivityWatcher.ConnectivityChangeListener {
override fun onConnectivityChanged(connectivityInfo: ConnectivityInfo?, network: Network?) {
lastConnectivityInfo = connectivityInfo
Timber.d("NIFU: \n\n $connectivityInfo \n\n $network")
handler?.removeCallbacks(signalUpdateRunnable)
_currentNetworkInfo = if (connectivityInfo == null) {
null
} else {
when (connectivityInfo.transportType) {
TransportType.ETHERNET -> {
EthernetNetworkInfo(connectivityInfo.linkDownstreamBandwidthKbps, connectivityInfo.netId, null, connectivityInfo.capabilitiesRaw.toString())
}
TransportType.WIFI -> wifiInfoWatcher.activeWifiInfo.apply {
this?.locationEnabled = locationStateWatcher.state == LocationState.ENABLED
}
TransportType.CELLULAR -> {
updateCellNetworkInfo()
}
TransportType.BLUETOOTH -> {
BluetoothNetworkInfo(connectivityInfo.linkDownstreamBandwidthKbps, connectivityInfo.netId, null, connectivityInfo.capabilitiesRaw.toString())
}
TransportType.VPN -> {
VpnNetworkInfo(connectivityInfo.linkDownstreamBandwidthKbps, connectivityInfo.netId, null, connectivityInfo.capabilitiesRaw.toString())
}
else -> {
Timber.d("NIFU creating OtherNetworkInfo: \n\n $connectivityInfo")
OtherNetworkInfo(connectivityInfo.linkDownstreamBandwidthKbps, connectivityInfo.netId, null, connectivityInfo.capabilitiesRaw.toString())
}
}
}
GlobalScope.launch {
captivePortal.resetCaptivePortalStatus()
captivePortal.checkForCaptivePortal()
}
}
}
fun updateCellNetworkInfo(): CellNetworkInfo? {
if (context.isLocationServiceEnabled() && context.isFineLocationPermitted() && context.isReadPhoneStatePermitted()) {
try {
var cells: List<ICell>? = null
var activeCellNetwork: CellNetworkInfo? = null
cells = netMonster.getCells()
val dataSubscriptionId = subscriptionManager.getCurrentDataSubscriptionId()
val primaryCells = cells?.filterOnlyPrimaryActiveDataCell(dataSubscriptionId)
// changed to check if it is not empty because some devices report more than one
// PrimaryConnection cells but with same operator details, only with different
// technology e.g. in case of 5G NSA there is 5G and 4G cell for some devices/networks, but
// in some cases for 5G NSA there are 2 primary connections reported - 1. for 4G and 2. for 5G cell,
// so we need to move that 5G from primary connection to secondary list
var primaryCellsCorrected = mutableListOf<ICell>()
when (primaryCells?.size) {
2 -> {
if (primaryCells[0] is CellNr && primaryCells[0].mobileNetworkType(
netMonster
) == MobileNetworkType.NR_NSA && primaryCells[1] is CellLte
) {
primaryCellsCorrected.add(primaryCells[1])
} else if (primaryCells[1] is CellNr && primaryCells[1].mobileNetworkType(
netMonster
) == MobileNetworkType.NR_NSA && primaryCells[0] is CellLte
) {
primaryCellsCorrected.add(primaryCells[0])
} else {
// situation when there are 2 primary cells sent from netmonster library so we must choose one
primaryCellsCorrected.add(primaryCells[0])
}
}
else -> {
primaryCellsCorrected = primaryCells as MutableList<ICell>
}
}
if (primaryCellsCorrected.isNotEmpty()) {
activeCellNetwork = primaryCellsCorrected[0].toCellNetworkInfo(
connectivityManager.activeNetworkInfo?.extraInfo,
telephonyManager.getCorrectDataTelephonyManager(subscriptionManager),
NetMonsterFactory.getTelephony(
context,
primaryCellsCorrected[0].subscriptionId
),
primaryCellsCorrected[0].mobileNetworkType(netMonster),
dataSubscriptionId
)
// more than one primary cell for data subscription
} else {
Timber.e("NM network type unable to detect because of ${primaryCellsCorrected.size} primary cells for subscription")
activeCellNetwork = CellNetworkInfo("")
scheduleUpdate()
}
if (activeCellNetwork == null) {
scheduleUpdate()
}
return activeCellNetwork
} catch (e: SecurityException) {
Timber.e("SecurityException: Not able to read telephonyManager.allCellInfo")
} catch (e: IllegalStateException) {
Timber.e("IllegalStateException: Not able to read telephonyManager.allCellInfo")
} catch (e: NullPointerException) {
Timber.e("NullPointerException: Not able to read telephonyManager.allCellInfo from other reason")
}
}
// when we are not able to detect more than there is cellular connection (we have
// no permission granted to read more details or permissions are granted but location is off)
scheduleUpdate()
return CellNetworkInfo(cellUUID = "")
}
private fun scheduleUpdate() {
Timber.d("Scheduling mobile cell update")
handler?.removeCallbacks(signalUpdateRunnable)
handler?.postDelayed(signalUpdateRunnable, CELL_UPDATE_DELAY)
}
/**
* Add callback to start receiving active network changes
*/
fun addListener(listener: NetworkChangeListener) {
listeners.add(listener)
listener.onActiveNetworkChanged(currentNetworkInfo)
if (listeners.size == 1) {
registerCallbacks()
}
}
/**
* Remove callback from receiving updates of active network changes
*/
fun removeListener(listener: NetworkChangeListener) {
listeners.remove(listener)
if (listeners.isEmpty()) {
unregisterCallbacks()
}
}
private fun registerCallbacks() {
if (!isCallbacksRegistered) {
connectivityWatcher.addListener(connectivityCallback)
isCallbacksRegistered = true
}
}
private fun unregisterCallbacks() {
if (isCallbacksRegistered) {
connectivityWatcher.removeListener(connectivityCallback)
isCallbacksRegistered = false
}
}
/**
* Callback that is used to observe active network change tracked by [ActiveNetworkWatcher]
*/
interface NetworkChangeListener {
/**
* When active network change is detected this callback will be triggered
* if no active network is available null will be returned
*/
fun onActiveNetworkChanged(networkInfo: NetworkInfo?)
}
override fun onLocationStateChanged(state: LocationState?) {
val enabled = state == LocationState.ENABLED
if (listeners.isNotEmpty()) {
unregisterCallbacks()
registerCallbacks()
}
if (_currentNetworkInfo is WifiNetworkInfo) {
listeners.forEach {
it.onActiveNetworkChanged(
wifiInfoWatcher.activeWifiInfo?.apply { locationEnabled = enabled }
)
}
}
}
} | 2 | Kotlin | 9 | 15 | 0faf5304a99bde8c9564cc69f98d33562e6a612a | 11,843 | open-rmbt-android | Apache License 2.0 |
analysis/analysis-api/testData/components/referenceShortener/shortenRange/nestedClasses/nestedClassFromSupertypes2.kt | JetBrains | 3,432,266 | false | {"Kotlin": 74444760, "Java": 6669398, "Swift": 4261253, "C": 2620837, "C++": 1953730, "Objective-C": 640870, "Objective-C++": 170766, "JavaScript": 135724, "Python": 48402, "Shell": 30960, "TypeScript": 22754, "Lex": 18369, "Groovy": 17273, "Batchfile": 11693, "CSS": 11368, "Ruby": 10470, "EJS": 5241, "Dockerfile": 5136, "HTML": 5073, "CMake": 4448, "Pascal": 1698, "FreeMarker": 1393, "Roff": 725, "LLVM": 395, "Scala": 80} | // FILE: main.kt
import MyInterface.Nested
interface MyInterface {
class Nested
}
class Foo : MyInterface {
<expr>val prop: MyInterface.Nested = MyInterface.Nested()</expr>
}
| 166 | Kotlin | 5,771 | 46,772 | bef0946ab7e5acd5b24b971eca532c43c8eba750 | 185 | kotlin | Apache License 2.0 |
src/main/kotlin/ink/ptms/adyeshach/api/event/AdyeshachEntityTickEvent.kt | dengdads | 385,554,748 | true | {"Kotlin": 480930, "Java": 1066} | package ink.ptms.adyeshach.api.event
import ink.ptms.adyeshach.common.entity.EntityInstance
import io.izzel.taboolib.module.event.EventCancellable
import org.bukkit.Bukkit
/**
* @Author sky
* @Since 2020-08-14 19:21
*/
class AdyeshachEntityTickEvent(val entity: EntityInstance) : EventCancellable<AdyeshachEntityTickEvent>() {
init {
async(!Bukkit.isPrimaryThread())
}
} | 0 | Kotlin | 0 | 0 | b56a8cd1acd512e7260879aaf5e3a80d760a55eb | 392 | Adyeshach-1 | MIT License |
app/src/main/java/com/quickalertapp/api/dto/SettingsDto.kt | Tigler | 509,745,009 | false | {"Kotlin": 58023} | package com.quickalertapp.api.dto
import android.os.Parcelable
import kotlinx.parcelize.Parcelize
@Parcelize
data class SettingsDto(
val notifiables: MutableList<NotifiableDto>
): Parcelable
| 5 | Kotlin | 0 | 0 | 3c620764de2165d1c992d03d2d14e7e9b7ee29d7 | 197 | QuickAlert | MIT License |
compiler/src/main/kotlin/org/dotlin/compiler/backend/steps/src2ir/DynamicTypeDeserializer.kt | dotlin-org | 434,960,829 | false | {"Kotlin": 2136413, "Dart": 128641, "Java": 6266} | /*
* Copyright 2021-2022 <NAME>
*
* This file is part of Dotlin.
*
* Dotlin is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Dotlin is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with Dotlin. If not, see <https://www.gnu.org/licenses/>.
*/
package org.dotlin.compiler.backend.steps.src2ir
import org.jetbrains.kotlin.metadata.ProtoBuf
import org.jetbrains.kotlin.serialization.deserialization.FlexibleTypeDeserializer
import org.jetbrains.kotlin.types.KotlinType
import org.jetbrains.kotlin.types.KotlinTypeFactory
import org.jetbrains.kotlin.types.SimpleType
import org.jetbrains.kotlin.types.checker.StrictEqualityTypeChecker
import org.jetbrains.kotlin.types.createDynamicType
import org.jetbrains.kotlin.types.typeUtil.builtIns
object DynamicTypeDeserializer : FlexibleTypeDeserializer {
override fun create(
proto: ProtoBuf.Type,
flexibleId: String,
lowerBound: SimpleType,
upperBound: SimpleType
): KotlinType {
require(flexibleId == "kotlin.DynamicType") { "Invalid id: $flexibleId" }
infix fun SimpleType.strictlyEquals(other: SimpleType) = StrictEqualityTypeChecker.strictEqualTypes(this, other)
return lowerBound.builtIns.run {
when {
lowerBound strictlyEquals nothingType && upperBound strictlyEquals nullableAnyType -> {
createDynamicType(this)
}
else -> KotlinTypeFactory.flexibleType(lowerBound, upperBound)
}
}
}
} | 5 | Kotlin | 3 | 223 | 174ade2b64fb8275eb6914e29df2b18e6f74f85f | 1,987 | dotlin | Apache License 2.0 |
src/main/kotlin/net/rentalhost/plugins/php/hammer/services/ClassService.kt | hammer-tools | 509,864,102 | false | {"Kotlin": 295432, "PHP": 235029, "HTML": 21942, "Java": 1887} | package net.rentalhost.plugins.php.hammer.services
import com.intellij.openapi.project.Project
import com.intellij.openapi.util.text.StringUtil
import com.jetbrains.php.PhpIndex
import com.jetbrains.php.codeInsight.PhpCodeInsightUtil
import com.jetbrains.php.lang.PhpLangUtil
import com.jetbrains.php.lang.psi.PhpGroupUseElement
import com.jetbrains.php.lang.psi.PhpGroupUseElement.PhpUseKeyword
import com.jetbrains.php.lang.psi.PhpPsiElementFactory
import com.jetbrains.php.lang.psi.elements.ClassReference
import com.jetbrains.php.lang.psi.elements.PhpClass
import com.jetbrains.php.refactoring.move.member.PhpMoveMemberProcessor
object ClassService {
fun findFQN(namespacedClassname: String, project: Project): PhpClass? =
PhpIndex.getInstance(project).getClassesByFQN(namespacedClassname.lowercase()).firstOrNull()
fun import(classReference: ClassReference?, allowAliasing: Boolean = false) {
val classReferenceFQN = PhpLangUtil.toFQN(classReference?.text ?: return)
// If an `use` declaration with the same name already exists, it prevents the creation of an alias and retains it with absolute class name.
if (!allowAliasing) {
PhpCodeInsightUtil.collectImports(PhpCodeInsightUtil.findScopeForUseOperator(classReference)!!).forEach {
for (declaration in it.declarations) {
if (!PhpLangUtil.equalsClassNames(declaration.fqn, classReferenceFQN) &&
StringUtil.equals(PhpGroupUseElement.getKeyword(declaration, null), PhpUseKeyword.CLASS.value))
return
}
}
}
val classQualifiedName = PhpMoveMemberProcessor.importClassAndGetName(
classReference, emptyList(), classReferenceFQN
)
classReference.replace(
PhpPsiElementFactory.createClassReference(classReference.project, classQualifiedName)
)
}
}
| 5 | Kotlin | 0 | 56 | e6a4aac518dc8f306fd2171a0355f15a0547e52f | 1,819 | php-hammer | Apache License 2.0 |
presentation/src/main/java/hiennguyen/me/weatherapp/utils/Config.kt | hiennguyen1001 | 123,107,985 | false | {"Kotlin": 71429, "Shell": 1605, "Java": 816, "C": 217, "CMake": 164} | package hiennguyen.me.weatherapp.utils
object Config {
const val DATABASE_NAME = "market"
const val DATABASE_VERSION = 1L
const val API_URL = "http://www.mocky.io/v2/"
const val API_LOG = "HttpLog:"
}
| 0 | Kotlin | 0 | 2 | a1d782792ccfabcad5710097b4132fc69883ec71 | 218 | weather-app-kotlin | MIT License |
library/sha3/src/commonTest/kotlin/org/kotlincrypto/hash/sha3/SHAKEDigestUnitTest.kt | KotlinCrypto | 598,183,506 | false | {"Kotlin": 454771} | /*
* Copyright (c) 2023 <NAME>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* 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.kotlincrypto.hash.sha3
import kotlin.test.Test
import kotlin.test.assertEquals
class SHAKEDigestUnitTest {
@Test
fun givenSHAKEDigest_whenLengthNonDefault_thenReturnsExpectedByteSize() {
// This exercises ALL inheritors of SHAKEDigest and how they will
// function with a non-default outputLength argument (i.e. digestLength)
SHAKE128(outputLength = 0).let { digest ->
assertEquals(0, digest.digestLength())
assertEquals(0, digest.digest().size)
}
SHAKE256(outputLength = 500).let { digest ->
assertEquals(500, digest.digestLength())
assertEquals(500, digest.digest().size)
}
}
}
| 4 | Kotlin | 2 | 19 | 458efabdf35e28c83f23ba432df1af4c47e1b9db | 1,312 | hash | Apache License 2.0 |
src/test/kotlin/com/realworld/springmongo/user/UserFacadeTest.kt | a-mountain | 396,700,282 | false | null | package com.realworld.springmongo.user
import com.realworld.springmongo.exceptions.InvalidRequestException
import com.realworld.springmongo.security.JwtSigner
import helpers.UserSamples
import helpers.coCatchThrowable
import io.mockk.every
import io.mockk.mockk
import org.assertj.core.api.Assertions.assertThat
import org.junit.jupiter.api.Test
import reactor.kotlin.core.publisher.toMono
class UserFacadeTest {
companion object {
val passwordService = PasswordService()
val userRepository = mockk<UserRepository>()
val userFacade = UserFacade(
userRepository = userRepository,
passwordService = passwordService,
userTokenProvider = JwtSigner(),
)
}
@Test
fun `should throw error when signup with duplicate email`() {
every { userRepository.existsByEmail(any()) } returns true.toMono()
every { userRepository.existsByUsername(any()) } returns false.toMono()
val throwable = coCatchThrowable { userFacade.signup(UserSamples.sampleUserRegistrationRequest()) }
assertThat(throwable)
.isInstanceOf(InvalidRequestException::class.java)
.hasMessage("Email: already in use")
}
@Test
fun `should throw error when signup with duplicate username`() {
every { userRepository.existsByUsername(any()) } returns true.toMono()
every { userRepository.existsByEmail(any()) } returns false.toMono()
val throwable = coCatchThrowable { userFacade.signup(UserSamples.sampleUserRegistrationRequest()) }
assertThat(throwable)
.isInstanceOf(InvalidRequestException::class.java)
.hasMessage("Username: already in use")
}
@Test
fun `should throw error when login with unregistered user`() {
every { userRepository.findByEmail(any()) } returns emailNotFoundException()
val throwable = coCatchThrowable { userFacade.login(UserSamples.sampleUserAuthenticationRequest()) }
assertThat(throwable)
.isInstanceOf(InvalidRequestException::class.java)
.hasMessage("Email: not found")
}
@Test
fun `should throw error when wrong password`() {
every { userRepository.findByEmail(any()) } returns UserSamples.sampleUser().toMono()
val authRequest = UserSamples.sampleUserAuthenticationRequest().copy(password = "<PASSWORD>")
val throwable = coCatchThrowable { userFacade.login(authRequest) }
assertThat(throwable)
.isInstanceOf(InvalidRequestException::class.java)
.hasMessage("Password: invalid")
}
@Test
fun `should throw error when update user with duplicate email`() {
every { userRepository.existsByEmail(any()) } returns true.toMono()
every { userRepository.existsByUsername(any()) } returns false.toMono()
val user = UserSamples.sampleUser()
every { userRepository.findById(any<String>()) } returns user.toMono()
val updateRequest = UserSamples.sampleUpdateUserRequest()
val throwable = coCatchThrowable { userFacade.updateUser(updateRequest, UserSession(user, "token")) }
assertThat(throwable)
.isInstanceOf(InvalidRequestException::class.java)
.hasMessage("Email: already in use")
}
@Test
fun `should throw error when update user with duplicate username`() {
every { userRepository.existsByEmail(any()) } returns false.toMono()
every { userRepository.existsByUsername(any()) } returns true.toMono()
val user = UserSamples.sampleUser()
every { userRepository.findById(any<String>()) } returns user.toMono()
val updateRequest = UserSamples.sampleUpdateUserRequest()
val throwable = coCatchThrowable { userFacade.updateUser(updateRequest, UserSession(user, "token")) }
assertThat(throwable)
.isInstanceOf(InvalidRequestException::class.java)
.hasMessage("Username: already in use")
}
private fun emailNotFoundException() = InvalidRequestException("Email", "not found").toMono<User>()
} | 1 | Kotlin | 8 | 23 | 318a7c72d4fd9d5aea4f92e68c24233fd143dbb6 | 4,112 | realworld-spring-webflux-kt | MIT License |
src/main/kotlin/chat/willow/thumpcord/thump/DiscordServiceCommandHandler.kt | WillowChat | 79,364,607 | false | {"Kotlin": 19733} | package chat.willow.thumpcord.thump
import chat.willow.thump.api.ICommandHandler
import net.minecraft.command.ICommandSender
import net.minecraft.util.text.TextComponentString
object DiscordServiceCommandHandler: ICommandHandler {
private val command: String = "discord"
private val usage: String = "/thump service discord reconnect"
override fun addTabCompletionOptions(sender: ICommandSender, parameters: Array<String>): List<String> {
return if (parameters.isEmpty() || "reconnect".startsWith(parameters.first(), true)) { listOf("reconnect") } else { emptyList() }
}
override fun processParameters(sender: ICommandSender, parameters: Array<String>) {
if (parameters.isEmpty() || parameters.first().toLowerCase() != "reconnect") {
sender.sendMessage(TextComponentString("Invalid usage."))
sender.sendMessage(TextComponentString(" Usage: $usage"))
return
}
}
override fun getUsage(): String {
return usage
}
override fun getCommand(): String {
return command
}
} | 1 | Kotlin | 0 | 1 | 1329c61c6e7d8f156559bdb59bfabe07aa91aba2 | 1,086 | Thumpcord | ISC License |
compiler/test/data/typescript/node_modules/import/importAssignment/importAssignment.d.kt | Kotlin | 159,510,660 | false | {"Kotlin": 2656346, "WebIDL": 323681, "TypeScript": 135641, "JavaScript": 19475, "ANTLR": 11333} | // [test] importAssignment.module_importAssignment.kt
@file:Suppress("INTERFACE_WITH_SUPERCLASS", "OVERRIDING_FINAL_MEMBER", "RETURN_TYPE_MISMATCH_ON_OVERRIDE", "CONFLICTING_OVERLOADS")
import kotlin.js.*
import org.khronos.webgl.*
import org.w3c.dom.*
import org.w3c.dom.events.*
import org.w3c.dom.parsing.*
import org.w3c.dom.svg.*
import org.w3c.dom.url.*
import org.w3c.fetch.*
import org.w3c.files.*
import org.w3c.notifications.*
import org.w3c.performance.*
import org.w3c.workers.*
import org.w3c.xhr.*
external fun calcBasedOnStats(s: Stats)
external fun calcStats(): Stats
external fun ping(a: InterfaceA)
// ------------------------------------------------------------------------------------------
// [test] index.module__fs.kt
@file:Suppress("INTERFACE_WITH_SUPERCLASS", "OVERRIDING_FINAL_MEMBER", "RETURN_TYPE_MISMATCH_ON_OVERRIDE", "CONFLICTING_OVERLOADS")
import kotlin.js.*
import org.khronos.webgl.*
import org.w3c.dom.*
import org.w3c.dom.events.*
import org.w3c.dom.parsing.*
import org.w3c.dom.svg.*
import org.w3c.dom.url.*
import org.w3c.fetch.*
import org.w3c.files.*
import org.w3c.notifications.*
import org.w3c.performance.*
import org.w3c.workers.*
import org.w3c.xhr.*
external interface Stats
// ------------------------------------------------------------------------------------------
// [test] index.module__api.kt
@file:Suppress("INTERFACE_WITH_SUPERCLASS", "OVERRIDING_FINAL_MEMBER", "RETURN_TYPE_MISMATCH_ON_OVERRIDE", "CONFLICTING_OVERLOADS")
import kotlin.js.*
import org.khronos.webgl.*
import org.w3c.dom.*
import org.w3c.dom.events.*
import org.w3c.dom.parsing.*
import org.w3c.dom.svg.*
import org.w3c.dom.url.*
import org.w3c.fetch.*
import org.w3c.files.*
import org.w3c.notifications.*
import org.w3c.performance.*
import org.w3c.workers.*
import org.w3c.xhr.*
external interface InterfaceA | 242 | Kotlin | 43 | 508 | 55213ea607fb42ff13b6278613c8fbcced9aa418 | 1,846 | dukat | Apache License 2.0 |
app/src/main/java/com/paulrybitskyi/docskanner/ui/views/scanner/DocScannerView.kt | mars885 | 311,384,511 | false | null | /*
* Copyright 2020 <NAME>, <EMAIL>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.paulrybitskyi.docskanner.ui.views.scanner
import android.content.Context
import android.graphics.Bitmap
import android.graphics.drawable.BitmapDrawable
import android.util.AttributeSet
import androidx.constraintlayout.widget.ConstraintLayout
import androidx.core.view.isVisible
import androidx.core.view.updateLayoutParams
import com.paulrybitskyi.commons.ktx.getDimensionPixelSize
import com.paulrybitskyi.commons.ktx.layoutInflater
import com.paulrybitskyi.commons.ktx.showToast
import com.paulrybitskyi.commons.utils.observeChanges
import com.paulrybitskyi.docskanner.R
import com.paulrybitskyi.docskanner.core.providers.CoroutineScopeProvider
import com.paulrybitskyi.docskanner.core.providers.DispatcherProvider
import com.paulrybitskyi.docskanner.core.providers.StringProvider
import com.paulrybitskyi.docskanner.databinding.ViewDocScannerBinding
import com.paulrybitskyi.docskanner.imageloading.Config
import com.paulrybitskyi.docskanner.imageloading.ImageLoader
import com.paulrybitskyi.docskanner.imageloading.Target
import com.paulrybitskyi.docskanner.imageloading.TargetAdapter
import com.paulrybitskyi.docskanner.imageprocessing.crop.transform.CropTransformationFactory
import com.paulrybitskyi.docskanner.imageprocessing.crop.transform.Size
import com.paulrybitskyi.docskanner.imageprocessing.detector.DocShapeDetector
import com.paulrybitskyi.docskanner.ui.views.scanner.crop.toCropCoords
import com.paulrybitskyi.docskanner.ui.views.scanner.crop.toDocCropBorder
import dagger.hilt.android.AndroidEntryPoint
import kotlinx.coroutines.withContext
import java.io.File
import javax.inject.Inject
@AndroidEntryPoint
internal class DocScannerView @JvmOverloads constructor(
context: Context,
attrs: AttributeSet? = null,
defStyleAttr: Int = 0
) : ConstraintLayout(context, attrs, defStyleAttr) {
private val imageMargin = context.getDimensionPixelSize(R.dimen.doc_scanner_image_margin)
private val docCropBorderHandleSize = context.getDimensionPixelSize(R.dimen.doc_crop_border_handle_size)
private val hasImageFile: Boolean
get() = (imageFile != null)
private var isImageVisible: Boolean
set(value) { binding.imageView.isVisible = value }
get() = binding.imageView.isVisible
private var isDocCropBorderVisible: Boolean
set(value) { binding.docCropBorderView.isVisible = value }
get() = binding.docCropBorderView.isVisible
private var isProgressBarVisible: Boolean
set(value) { binding.progressBar.isVisible = value }
get() = binding.progressBar.isVisible
private var shouldRunShapeDetection = true
private var currentImageRotation = 0f
set(value) {
field = (value % 360)
shouldRunShapeDetection = true
reloadImage()
}
private val currentBitmap: Bitmap?
get() = (binding.imageView.drawable as? BitmapDrawable)?.bitmap
private var scannedDocTarget: Target? = null
private val binding = ViewDocScannerBinding.inflate(context.layoutInflater, this)
var imageFile by observeChanges<File?>(null) { _, _ ->
reloadImage()
}
@Inject lateinit var stringProvider: StringProvider
@Inject lateinit var imageLoader: ImageLoader
@Inject lateinit var coroutineScopeProvider: CoroutineScopeProvider
@Inject lateinit var dispatcherProvider: DispatcherProvider
@Inject lateinit var docShapeDetector: DocShapeDetector
@Inject lateinit var cropTransformationFactory: CropTransformationFactory
init {
initDefaults()
}
private fun initDefaults() {
isDocCropBorderVisible = false
isProgressBarVisible = false
}
fun rotateLeft() {
currentImageRotation -= 90f
}
fun rotateRight() {
currentImageRotation += 90f
}
private fun reloadImage() {
if(!hasImageFile) return
isImageVisible = true
isDocCropBorderVisible = false
isProgressBarVisible = true
val imageWidth = (width - (2 * imageMargin))
val imageHeight = (height - (2 * imageMargin))
imageLoader.loadImage(
Config.Builder()
.centerInside()
.rotate(currentImageRotation)
.resize(imageWidth, imageHeight)
.source(Config.Source.File(checkNotNull(imageFile)))
.destination(Config.Destination.View(binding.imageView))
.onSuccess(::onImageLoaded)
.build()
)
}
private fun onImageLoaded() {
resetDocCropBorder()
isProgressBarVisible = false
}
private fun resetDocCropBorder() {
val currentBitmap = checkNotNull(currentBitmap)
binding.docCropBorderView.updateLayoutParams {
this.width = (currentBitmap.width + docCropBorderHandleSize)
this.height = (currentBitmap.height + docCropBorderHandleSize)
}
detectDocumentShape(currentBitmap)
}
private fun detectDocumentShape(currentBitmap: Bitmap) {
if(!shouldRunShapeDetection) {
isDocCropBorderVisible = true
return
}
coroutineScopeProvider.launch(dispatcherProvider.computation) {
val docShape = docShapeDetector.detectShape(currentBitmap)
withContext(dispatcherProvider.main) {
binding.docCropBorderView.setCropBorder(docShape.toDocCropBorder())
shouldRunShapeDetection = false
isDocCropBorderVisible = true
}
}
}
fun scanDocument(onSuccess: (Bitmap) -> Unit) {
if(!hasImageFile) return
if(!binding.docCropBorderView.hasValidBorder()) {
context.showToast(stringProvider.getString(R.string.error_cannot_crop))
return
}
val docCropBorder = checkNotNull(binding.docCropBorderView.getCropBorder())
val viewSize = Size(binding.imageView.width.toFloat(), binding.imageView.height.toFloat())
val cropTransformation = cropTransformationFactory.createCropTransformation(
cropCoords = docCropBorder.toCropCoords(),
viewSize = viewSize
)
scannedDocTarget = TargetAdapter(
onLoaded = { onSuccess(it) },
onFailed = ::onDocScanFailed
)
isImageVisible = false
isDocCropBorderVisible = false
isProgressBarVisible = true
imageLoader.loadImage(
Config.Builder()
.transformation(cropTransformation)
.rotate(currentImageRotation)
.source(Config.Source.File(checkNotNull(imageFile)))
.destination(Config.Destination.Callback(checkNotNull(scannedDocTarget)))
.build()
)
}
private fun onDocScanFailed(error: Exception) {
context.showToast(stringProvider.getString(R.string.error_scan_failed))
}
override fun onDetachedFromWindow() {
super.onDetachedFromWindow()
coroutineScopeProvider.cancelChildren()
}
} | 4 | Java | 15 | 98 | 8397c7eba95194a741c03a96051571abd6c4494a | 7,694 | doc-skanner | Apache License 2.0 |
js/js.translator/testData/box/escapedIdentifiers/topLevelLocalClassMangling.kt | JetBrains | 3,432,266 | false | {"Kotlin": 74444760, "Java": 6669398, "Swift": 4261253, "C": 2620837, "C++": 1953730, "Objective-C": 640870, "Objective-C++": 170766, "JavaScript": 135724, "Python": 48402, "Shell": 30960, "TypeScript": 22754, "Lex": 18369, "Groovy": 17273, "Batchfile": 11693, "CSS": 11368, "Ruby": 10470, "EJS": 5241, "Dockerfile": 5136, "HTML": 5073, "CMake": 4448, "Pascal": 1698, "FreeMarker": 1393, "Roff": 725, "LLVM": 395, "Scala": 80} | // IGNORE_BACKEND: JS
// !LANGUAGE: +JsAllowInvalidCharsIdentifiersEscaping
package foo
class class_with_invalid_chars {
fun foo(): Int = 23
}
class `class@with$invalid chars` {
fun foo(): Int = 42
}
fun box(): String {
val a = class_with_invalid_chars()
val b = `class@with$invalid chars`()
assertEquals(true, a is class_with_invalid_chars)
assertEquals(true, b is `class@with$invalid chars`)
assertEquals(23, a.foo())
assertEquals(42, b.foo())
return "OK"
} | 166 | Kotlin | 5,771 | 46,772 | bef0946ab7e5acd5b24b971eca532c43c8eba750 | 502 | kotlin | Apache License 2.0 |
compiler/testData/diagnostics/tests/j+k/genericConstructorWithMultipleBounds.fir.kt | android | 263,405,600 | true | null | // !WITH_NEW_INFERENCE
// FILE: J.java
import java.io.Serializable;
public class J {
public <T extends Cloneable & Serializable> J(T t) {}
}
// FILE: K.kt
import java.io.Serializable
fun cloneable(c: Cloneable) = <!INAPPLICABLE_CANDIDATE!>J<!>(c)
fun serializable(s: Serializable) = <!INAPPLICABLE_CANDIDATE!>J<!>(s)
fun <T> both(t: T) where T : Cloneable, T : Serializable = J(t)
| 15 | Kotlin | 37 | 316 | 74126637a097f5e6b099a7b7a4263468ecfda144 | 392 | kotlin | Apache License 2.0 |
app/src/main/java/com/campuscoders/posterminalapp/presentation/sale/BaseViewModel.kt | CampusCoders | 690,583,133 | false | {"Kotlin": 361456, "Java": 47354} | package com.campuscoders.posterminalapp.presentation.sale
import android.content.Context
import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.campuscoders.posterminalapp.domain.model.Orders
import com.campuscoders.posterminalapp.domain.model.OrdersProducts
import com.campuscoders.posterminalapp.domain.model.Products
import com.campuscoders.posterminalapp.domain.model.ShoppingCart
import com.campuscoders.posterminalapp.domain.use_case.sale.FetchAllProductsByCategoryIdUseCase
import com.campuscoders.posterminalapp.domain.use_case.sale.FetchCustomerByVknTcknUseCase
import com.campuscoders.posterminalapp.domain.use_case.sale.FetchProductByBarcodeUseCase
import com.campuscoders.posterminalapp.domain.use_case.sale.FetchProductByProductIdUseCase
import com.campuscoders.posterminalapp.domain.use_case.sale.SaveAllOrdersProductsUseCase
import com.campuscoders.posterminalapp.domain.use_case.sale.SaveOrderUseCase
import com.campuscoders.posterminalapp.presentation.sale.views.ShoppingCartItems
import com.campuscoders.posterminalapp.utils.Constants
import com.campuscoders.posterminalapp.utils.CustomSharedPreferences
import com.campuscoders.posterminalapp.utils.PriceAndKdvCalculator
import com.campuscoders.posterminalapp.utils.Resource
import com.campuscoders.posterminalapp.utils.toCent
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.launch
import javax.inject.Inject
@HiltViewModel
class BaseViewModel @Inject constructor(
private val fetchProductByProductIdUseCase: FetchProductByProductIdUseCase,
private val fetchAllProductsByCategoryIdUseCase: FetchAllProductsByCategoryIdUseCase,
private val saveOrderUseCase: SaveOrderUseCase,
private val saveAllOrdersProductsByUseCase: SaveAllOrdersProductsUseCase,
private val fetchCustomerByVknTcknUseCase: FetchCustomerByVknTcknUseCase,
private val fetchProductByBarcodeUseCase: FetchProductByBarcodeUseCase
) : ViewModel() {
private var _statusTotal = MutableLiveData<String>()
val statusTotal: LiveData<String>
get() = _statusTotal
private var _statusTotalTax = MutableLiveData<String>()
val statusTotalTax: LiveData<String>
get() = _statusTotalTax
private var _statusAddProduct = MutableLiveData<Resource<Products>>()
val statusAddProduct: LiveData<Resource<Products>>
get() = _statusAddProduct
private var _statusShoppingCartList = MutableLiveData<MutableList<ShoppingCart>>()
val statusShoppingCartList: LiveData<MutableList<ShoppingCart>>
get() = _statusShoppingCartList
private var _statusShoppingCartQuantity = MutableLiveData<Int>()
val statusShoppingCartQuantity: LiveData<Int>
get() = _statusShoppingCartQuantity
private var _statusProductsList = MutableLiveData<Resource<List<Products>>>()
val statusProductsList: LiveData<Resource<List<Products>>>
get() = _statusProductsList
private var _statusSaveToDatabase = MutableLiveData<Resource<Boolean>>()
val statusSaveToDatabase: LiveData<Resource<Boolean>>
get() = _statusSaveToDatabase
fun getProductsByCategoryId(categoryId: String) {
_statusProductsList.value = Resource.Loading(null)
viewModelScope.launch {
val response = fetchAllProductsByCategoryIdUseCase.executeFetchAllProductsByCategoryId(categoryId)
_statusProductsList.value = response
}
}
fun addProductByBarcode(barcode: String) {
_statusAddProduct.value = Resource.Loading()
viewModelScope.launch {
val response = fetchProductByBarcodeUseCase.executeFetchProductByBarcode(barcode)
if (response is Resource.Success) {
val productId = response.data?.productId.toString()
addProduct(productId)
}
_statusAddProduct.value = response
}
}
private fun calculateTotal() {
_statusShoppingCartList.value?.let { shoppingCartList ->
var totalPrice = 0
var totalPriceCent = 0
var totalKdv = 0
var totalKdvCent = 0
for (item in shoppingCartList) {
totalPrice += item.productPrice.toInt()
totalPriceCent += item.productPriceCent.toInt()
totalKdv += item.productKdvPrice.toInt()
totalKdvCent += item.productKdvCent.toInt()
}
totalPrice += totalPriceCent / 100
totalPriceCent %= 100
totalKdv += totalKdvCent / 100
totalKdvCent %= 100
ShoppingCartItems.setTotalPrice("$totalPrice,${totalPriceCent.toCent()}")
ShoppingCartItems.setTotalTax("$totalKdv,${totalKdvCent.toCent()}")
_statusTotal.value = "₺$totalPrice,${totalPriceCent.toCent()}"
_statusTotalTax.value = "₺$totalKdv,${totalKdvCent.toCent()}"
}
_statusShoppingCartQuantity.value = _statusShoppingCartList.value?.size
}
fun addProduct(productId: String) {
var isProductExists = false
if (_statusShoppingCartList.value == null) {
_statusShoppingCartList.value = mutableListOf()
}
_statusShoppingCartList.value?.let { shoppingCartList ->
for (item in shoppingCartList) {
if (productId == item.productId) {
item.productQuantity = (item.productQuantity.toInt() + 1).toString()
val hashmap = PriceAndKdvCalculator.calculateTotalPriceAndKdv(item.originalPrice.toInt(),item.originalPriceCent.toInt(),
item.productKdv.toInt(),item.productQuantity.toInt())
hashmap["total_cent"] = hashmap["total_cent"]!!.toInt().toCent()
hashmap["total_kdv_after"] = hashmap["total_kdv_after"]!!.toInt().toCent()
item.productPrice = hashmap["total_price"]?:""
item.productPriceCent = hashmap["total_cent"]?:""
item.productKdvPrice = hashmap["total_kdv_before"]?:""
item.productKdvCent = hashmap["total_kdv_after"]?:""
isProductExists = true
calculateTotal()
}
}
}
if (!isProductExists) {
val newShoppingCart = _statusShoppingCartList.value
viewModelScope.launch {
val response = fetchProductByProductIdUseCase.executeFetchProductByProductId(productId)
if (response is Resource.Success) {
response.data?.let {
val hashmap = PriceAndKdvCalculator.calculateTotalPriceAndKdv(it.productPrice!!.toInt(),it.productPriceCents!!.toInt(),
it.productKdv!!.toInt(),1)
hashmap["total_cent"] = hashmap["total_cent"]!!.toInt().toCent()
hashmap["total_kdv_after"] = hashmap["total_kdv_after"]!!.toInt().toCent()
newShoppingCart?.add(ShoppingCart(it.productId.toString(),it.productBarcode!!,it.productName!!,"1", hashmap["total_price"]?:"",
hashmap["total_cent"]?:"",hashmap["total_kdv_before"]?:"",hashmap["total_kdv_after"]?:"",
it.productKdv!!,it.productImage!!,it.productPrice.toString(),it.productPriceCents.toString()))
ShoppingCartItems.setShoppingCartList(arrayListOf())
_statusShoppingCartList.value = newShoppingCart?: mutableListOf()
calculateTotal()
}
} else if (response is Resource.Error) {
_statusAddProduct.value = response
}
}
}
}
fun decreaseProduct(productId: String, position: Int) {
_statusShoppingCartList.value?.let { shoppingCartList ->
for (item in shoppingCartList) {
if (productId == item.productId) {
item.productQuantity = (item.productQuantity.toInt() - 1).toString()
if (item.productQuantity == "0") {
updateShoppingCartList(productId)
} else {
val hashmap = PriceAndKdvCalculator.calculateTotalPriceAndKdv(item.originalPrice.toInt(),item.originalPriceCent.toInt(),
item.productKdv.toInt(),item.productQuantity.toInt())
hashmap["total_cent"] = hashmap["total_cent"]!!.toInt().toCent()
hashmap["total_kdv_after"] = hashmap["total_kdv_after"]!!.toInt().toCent()
item.productPrice = hashmap["total_price"]?:""
item.productPriceCent = hashmap["total_cent"]?:""
item.productKdvPrice = hashmap["total_kdv_before"]?:""
item.productKdvCent = hashmap["total_kdv_after"]?:""
}
calculateTotal()
}
}
}
}
fun saveToDatabase(isCreditCard: Boolean, context: Context, vknTckn: String) {
_statusSaveToDatabase.value = Resource.Loading(null)
var paymentType = "Nakit"
if (isCreditCard) paymentType = "Kredi Kartı"
viewModelScope.launch {
val customerData = fetchCustomerByVknTcknUseCase.executeFetchCustomerByVknTckn(vknTckn)
if (customerData is Resource.Success) {
ShoppingCartItems.setCustomerName("${customerData.data!!.customerFirstName} ${customerData.data.customerLastName}")
ShoppingCartItems.setPaymentType(paymentType)
saveOrder(paymentType,context,customerData.data.customerId.toString())
} else {
_statusSaveToDatabase.value = Resource.Error(false,customerData.message?:"Error saveToDatabase")
}
}
}
private fun saveOrder(paymentType: String, context: Context, customerId: String) {
_statusSaveToDatabase.value = Resource.Loading(null)
val empty = ""
val customSharedPreferences = CustomSharedPreferences(context)
val mainUserInfo = customSharedPreferences.getMainUserLogin(context)
viewModelScope.launch {
val orderId = saveOrderUseCase.executeSaveOrder(
Orders(customerId,empty, paymentType, empty, empty, empty, empty, Constants.ORDER_MALI_ID,mainUserInfo["terminal_id"].toString(),
mainUserInfo["uye_isyeri_no"].toString(), Constants.ORDER_ETTN, Constants.ORDER_NO_BACKEND, empty, empty, null)
)
if (orderId is Resource.Success) {
ShoppingCartItems.setOrderId(orderId.data.toString())
saveOrdersProducts(orderId.data.toString())
} else {
_statusSaveToDatabase.value = Resource.Error(null,orderId.message?:"error saveOrder")
}
}
}
private fun saveOrdersProducts(orderId: String) {
_statusSaveToDatabase.value = Resource.Loading(null)
val ordersProductsList = arrayListOf<OrdersProducts>()
viewModelScope.launch {
_statusShoppingCartList.value?.let {
for (shoppingCartItem in it) {
ordersProductsList.add(
OrdersProducts(shoppingCartItem.productId,orderId,shoppingCartItem.productQuantity,
shoppingCartItem.productPrice,shoppingCartItem.productPriceCent,shoppingCartItem.productKdvPrice,
shoppingCartItem.productKdvCent)
)
}
}
val newList = ordersProductsList.toTypedArray()
val response = saveAllOrdersProductsByUseCase.executeSaveAllOrdersProducts(*newList)
if (response is Resource.Success) _statusSaveToDatabase.value = Resource.Success(true)
else _statusSaveToDatabase.value = Resource.Error(null,response.message?:"error saveOrdersProducts")
}
}
fun updateShoppingCartList(productId: String) {
_statusShoppingCartList.value = _statusShoppingCartList.value?.let {
it.filterIndexed { _, shoppingCart ->
shoppingCart.productId != productId
}
}?.toMutableList()
calculateTotal()
}
fun replaceOldVersion(oldList: MutableList<ShoppingCart>) {
_statusShoppingCartList.value = oldList
calculateTotal()
}
fun resetSaveToDatabaseLiveData() {
_statusSaveToDatabase = MutableLiveData<Resource<Boolean>>()
}
fun resetShoppingCartList() {
_statusShoppingCartList.value = mutableListOf()
calculateTotal()
}
} | 0 | Kotlin | 0 | 3 | 0b56df5b62789e3034619d693fcd77d1ee241cf7 | 12,781 | PosTerminalApp | MIT License |
compiler/testData/loadJava/compiledKotlin/prop/ExtValTIntInClass.kt | JetBrains | 3,432,266 | false | {"Kotlin": 74444760, "Java": 6669398, "Swift": 4261253, "C": 2620837, "C++": 1953730, "Objective-C": 640870, "Objective-C++": 170766, "JavaScript": 135724, "Python": 48402, "Shell": 30960, "TypeScript": 22754, "Lex": 18369, "Groovy": 17273, "Batchfile": 11693, "CSS": 11368, "Ruby": 10470, "EJS": 5241, "Dockerfile": 5136, "HTML": 5073, "CMake": 4448, "Pascal": 1698, "FreeMarker": 1393, "Roff": 725, "LLVM": 395, "Scala": 80} | package test
class ExtValPIntInClass<P> {
val P.asas: Int
get() = throw Exception()
}
| 166 | Kotlin | 5,771 | 46,772 | bef0946ab7e5acd5b24b971eca532c43c8eba750 | 99 | kotlin | Apache License 2.0 |
app/src/main/java/com/rviannaoliveira/vroutetrack/data/RegisterDao.kt | rviannaoliveira | 91,630,693 | false | null | package com.rviannaoliveira.vroutetrack.data
import android.arch.persistence.room.Dao
import android.arch.persistence.room.Insert
import android.arch.persistence.room.Query
import com.rviannaoliveira.vroutetrack.model.RegisterTrack
import io.reactivex.Flowable
/**
* Criado por rodrigo on 20/05/17.
*/
@Dao
interface RegisterDao {
@Insert
fun insert(register : RegisterTrack)
@Query("SELECT * from registers")
fun getAllRegisters(): Flowable<List<RegisterTrack>>
@Query("SELECT * from registers where id = :arg0 LIMIT 1")
fun findRegisterById(registerId : Int): RegisterTrack
} | 0 | Kotlin | 0 | 0 | a3c38db33f05b11c9510fddfd7e4d7efef9bf0fd | 606 | VRouteTrack | Apache License 2.0 |
kotlintest-tests/src/test/kotlin/com/sksamuel/kotlintest/tests/properties/GenTest.kt | utikeev | 155,193,641 | true | {"Kotlin": 783200, "Java": 6857} | @file:Suppress("USELESS_IS_CHECK")
package com.sksamuel.kotlintest.properties
import io.kotlintest.*
import io.kotlintest.matchers.beGreaterThan
import io.kotlintest.matchers.collections.contain
import io.kotlintest.matchers.gte
import io.kotlintest.matchers.lt
import io.kotlintest.matchers.string.include
import io.kotlintest.properties.Gen
import io.kotlintest.properties.forAll
import io.kotlintest.specs.WordSpec
import io.kotlintest.tables.headers
import io.kotlintest.tables.row
import io.kotlintest.tables.table
import java.util.Random
import kotlin.collections.ArrayList
class GenTest : WordSpec() {
init {
"Gen.string.nextPrintableString" should {
"give out a argument long string".config(invocations = 100, threads = 8) {
val random = Random()
var rand = random.nextInt(10000)
if (rand <= 0)
rand = 0 - rand
val string = Gen.string().nextPrintableString(rand)
string.forEach {
it.toInt() shouldBe gte(32)
it.toInt() shouldBe lt(127)
}
string.length shouldBe rand
}
}
"Gen.choose<int, int>" should {
"only give out numbers in the given range".config(invocations = 10000, threads = 8) {
val random = Random()
val min = random.nextInt(10000) - 10000
val max = random.nextInt(10000) + 10000
val rand = Gen.choose(min, max).random().take(10)
rand.forEach {
it shouldBe gte(min)
it shouldBe lt(max)
}
}
"support negative bounds".config(invocations = 1000, threads = 8) {
val random = Random()
val max = random.nextInt(10000)
val rand = Gen.choose(Int.MIN_VALUE, max).random().take(10)
rand.forEach {
it shouldBe gte(Int.MIN_VALUE)
it shouldBe lt(max)
}
}
}
"Gen.choose<long, long>" should {
"only give out numbers in the given range".config(invocations = 10000, threads = 8) {
val random = Random()
val min = random.nextInt(10000) - 10000
val max = random.nextInt(10000) + 10000
val rand = Gen.choose(min.toLong(), max.toLong()).random().take(10)
rand.forEach {
it shouldBe gte(min.toLong())
it shouldBe lt(max.toLong())
}
}
"support negative bounds".config(invocations = 10000, threads = 8) {
val random = Random()
val max = random.nextInt(10000) + 10000
val rand = Gen.choose(Long.MIN_VALUE, max.toLong()).random().take(10)
rand.forEach {
it shouldBe gte(Long.MIN_VALUE)
it shouldBe lt(max.toLong())
}
}
}
"Gen.forClassName" should {
"gives the right result" {
val table1 = table(
headers("name"),
row("java.lang.String"),
row("java.lang.Integer"),
row("java.lang.Long"),
row("java.lang.Boolean"),
row("java.lang.Float"),
row("java.lang.Double")
)
io.kotlintest.tables.forAll(table1) { clazz ->
Gen.forClassName(clazz).random().firstOrNull()?.javaClass?.name shouldBe clazz
}
val table2 = table(
headers("name"),
row("kotlin.String"),
row("kotlin.Long"),
row("kotlin.Boolean"),
row("kotlin.Float"),
row("kotlin.Double")
)
io.kotlintest.tables.forAll(table2) { clazz ->
val tmp = clazz.split(".").last()
Gen.forClassName(clazz).random().firstOrNull()?.javaClass?.name shouldBe "java.lang.$tmp"
}
Gen.forClassName("kotlin.Int").random().firstOrNull()?.javaClass?.name shouldBe "java.lang.Integer"
}
"throw an exception, with a wrong class" {
shouldThrow<IllegalArgumentException> {
Gen.forClassName("This.is.not.a.valid.class")
}
}
}
"Gen.create" should {
"create a Generator with the given function" {
Gen.create { 5 }.random().take(10).toList() shouldBe List(10, { 5 })
var i = 0
val gen = Gen.create { i++ }
gen.random().take(150).toList() shouldBe List(150, { it })
}
}
"Gen.default" should {
"generate the defaults for list" {
val gen = Gen.default<List<Int>>()
io.kotlintest.properties.forAll(10, gen) { inst ->
forAll(inst) { i ->
(i is Int) shouldBe true
}
true
}
}
"generate the defaults for set" {
val gen = Gen.default<Set<String>>()
io.kotlintest.properties.forAll(gen) { inst ->
forAll(inst) { i ->
(i is String) shouldBe true
}
true
}
}
"use forClass for everything else" {
val table = table(headers("name"),
row("java.lang.String"),
row("kotlin.String"),
row("java.lang.Integer"),
row("kotlin.Int"),
row("java.lang.Long"),
row("kotlin.Long"),
row("java.lang.Boolean"),
row("kotlin.Boolean"),
row("java.lang.Float"),
row("kotlin.Float"),
row("java.lang.Double"),
row("kotlin.Double"))
io.kotlintest.tables.forAll(table) { clazz ->
val tmp = clazz.split(".")
Gen.forClassName(clazz).random().firstOrNull()?.javaClass?.name shouldHave include(tmp[tmp.size - 1])
}
}
"throw an exeption, with a wrong class" {
shouldThrow<IllegalArgumentException> {
Gen.forClassName("This.is.not.a.valid.class")
}
}
}
"ConstGen " should {
"always generate the same thing" {
io.kotlintest.properties.forAll(Gen.constant(5)) {
it == 5
}
}
}
"Gen.orNull " should {
"have both values and nulls generated" {
Gen.constant(5).orNull().constants().toSet() shouldBe setOf(5, null)
fun <T> Gen<T>.toList(size: Int): List<T> =
ArrayList<T>(size).also { list ->
repeat(size) {
list += random().take(10)
}
}
Gen.constant(5).orNull().random().take(1000).toList().toSet() shouldBe setOf(5, null)
}
}
"Gen.filter " should {
"prevent values from being generated" {
io.kotlintest.properties.forAll(Gen.from(listOf(1, 2, 5)).filter { it != 2 }) {
it != 2
}
}
}
"Gen.map " should {
"correctly transform the values" {
io.kotlintest.properties.forAll(Gen.constant(5).map { it + 7 }) {
it == 12
}
}
}
"Gen.from " should {
"correctly handle null values" {
val list = listOf(null, 1,2,3)
val gen = Gen.from(list)
val firstElements = gen.random().take(100).toList()
firstElements shouldHave contain(null as Int?)
}
}
"Gen.constant" should {
"handle null value" {
io.kotlintest.properties.forAll(Gen.constant(null as Int?)) {n ->
n == null
}
}
}
"Gen.oneOf" should {
"correctly handle multiple generators" {
val gen = Gen.oneOf(Gen.positiveIntegers(), Gen.negativeIntegers())
var positiveNumbers = 0
var negativeNumbers = 0
forAll(gen) {
if (it > 0) {
positiveNumbers++
} else if (it < 0) {
negativeNumbers++
}
it shouldNotBe 0
true
}
positiveNumbers shouldBe beGreaterThan(1)
negativeNumbers shouldBe beGreaterThan(1)
}
}
}
}
| 1 | Kotlin | 0 | 0 | f7e08859343c09289778c17b16830b4325046f11 | 7,638 | kotlintest | Apache License 2.0 |
src/main/kotlin/com/timcastelijns/room15bot/data/repositories/UserStatsRepository.kt | TimCastelijns | 130,837,414 | false | null | package com.timcastelijns.room15bot.data.repositories
import com.timcastelijns.room15bot.network.UserStatsService
import org.jsoup.Jsoup
import org.jsoup.nodes.Document
class UserStatsRepository(
private val userStatsService: UserStatsService
) {
suspend fun getNumberOfQuestions(userId: Long): Int {
val data = userStatsService.getUserProfileQuestions(userId).await()
return Jsoup.parse(data).valueOfFirstCountClass()
}
suspend fun getNumberOfAnswers(userId: Long): Int {
val data = userStatsService.getUserProfileAnswers(userId).await()
return Jsoup.parse(data).valueOfFirstCountClass()
}
private fun Document.valueOfFirstCountClass(): Int {
val text = getElementsByClass("count").first().text()
return if (text.isNotEmpty()) text.replace("," , "").toInt() else 0
}
}
| 19 | Kotlin | 6 | 13 | 8a1c84d6d099461e855c0d10b8a9a374f3e0571b | 858 | Room15Bot | MIT License |
generators/test-generator/tests/org/jetbrains/kotlin/generators/NewTestGenerationDSL.kt | JetBrains | 3,432,266 | false | {"Kotlin": 74444760, "Java": 6669398, "Swift": 4261253, "C": 2620837, "C++": 1953730, "Objective-C": 640870, "Objective-C++": 170766, "JavaScript": 135724, "Python": 48402, "Shell": 30960, "TypeScript": 22754, "Lex": 18369, "Groovy": 17273, "Batchfile": 11693, "CSS": 11368, "Ruby": 10470, "EJS": 5241, "Dockerfile": 5136, "HTML": 5073, "CMake": 4448, "Pascal": 1698, "FreeMarker": 1393, "Roff": 725, "LLVM": 395, "Scala": 80} | /*
* Copyright 2010-2021 JetBrains s.r.o. and Kotlin Programming Language contributors.
* Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file.
*/
package org.jetbrains.kotlin.generators
import org.jetbrains.kotlin.generators.util.TestGeneratorUtil
fun generateTestGroupSuiteWithJUnit5(
args: Array<String>,
// Main class name can only be determined when running on the main thread.
// If this call is not made on the main thread, the main class name must be injected.
mainClassName: String? = TestGeneratorUtil.getMainClassName(),
additionalMethodGenerators: List<MethodGenerator<Nothing>> = emptyList(),
init: TestGroupSuite.() -> Unit,
) {
generateTestGroupSuiteWithJUnit5(InconsistencyChecker.hasDryRunArg(args), mainClassName, additionalMethodGenerators, init)
}
fun generateTestGroupSuiteWithJUnit5(
dryRun: Boolean = false,
// See above
mainClassName: String? = TestGeneratorUtil.getMainClassName(),
additionalMethodGenerators: List<MethodGenerator<Nothing>> = emptyList(),
init: TestGroupSuite.() -> Unit,
) {
val suite = TestGroupSuite(ReflectionBasedTargetBackendComputer).apply(init)
suite.forEachTestClassParallel { testClass ->
val (changed, testSourceFilePath) = NewTestGeneratorImpl(additionalMethodGenerators)
.generateAndSave(testClass, dryRun, mainClassName)
if (changed) {
InconsistencyChecker.inconsistencyChecker(dryRun).add(testSourceFilePath)
}
}
}
| 166 | Kotlin | 5,771 | 46,772 | bef0946ab7e5acd5b24b971eca532c43c8eba750 | 1,546 | kotlin | Apache License 2.0 |
application/Sample-Coroutines/app/src/main/java/com/demo/code/modules/legacycode/LegacyCallbackSampleOne.kt | devrath | 339,281,472 | false | {"Kotlin": 468482, "Java": 3273} | package com.demo.code.modules.legacycode
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.launch
import kotlin.concurrent.thread
import kotlin.coroutines.CoroutineContext
import kotlin.coroutines.suspendCoroutine
class LegacyCallbackSampleOne(
override val coroutineContext: CoroutineContext
) : CoroutineScope{
fun initiateDemo() {
launch {
getUser("111")
}
}
private suspend fun getUser(id: String): User = suspendCoroutine {
getUserFromNetworkCallback("101") { user, error ->
user?.run { println(this.userName) }
error?.run { println(this.message) }
}
}
private fun getUserFromNetworkCallback(
userId: String,
onUserResponse: (User?, Throwable?) -> Unit) {
thread {
try {
Thread.sleep(1000) // ---> Simulating the network delay
val user = User(userId, "Test User")
onUserResponse(user, null)
} catch (error: Throwable) {
onUserResponse(null, error)
}
}
}
} | 0 | Kotlin | 2 | 15 | 788c8472244eaa76c0b013a9686749541885876f | 1,119 | KotlinAlchemy | Apache License 2.0 |
ui/src/main/java/com/pyamsoft/fridge/ui/icons/SwapHoriz.kt | pyamsoft | 175,992,414 | false | null | /*
* Copyright 2021 <NAME>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.pyamsoft.fridge.ui.icons
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.materialIcon
import androidx.compose.material.icons.materialPath
import androidx.compose.ui.graphics.vector.ImageVector
// Copied from material-icons-extended since the library itself is too large
@Suppress("unused")
val Icons.Filled.SwapHoriz: ImageVector
get() {
if (_swapHoriz != null) {
return _swapHoriz!!
}
_swapHoriz =
materialIcon(name = "Filled.SwapHoriz") {
materialPath {
moveTo(6.99f, 11.0f)
lineTo(3.0f, 15.0f)
lineToRelative(3.99f, 4.0f)
verticalLineToRelative(-3.0f)
horizontalLineTo(14.0f)
verticalLineToRelative(-2.0f)
horizontalLineTo(6.99f)
verticalLineToRelative(-3.0f)
close()
moveTo(21.0f, 9.0f)
lineToRelative(-3.99f, -4.0f)
verticalLineToRelative(3.0f)
horizontalLineTo(10.0f)
verticalLineToRelative(2.0f)
horizontalLineToRelative(7.01f)
verticalLineToRelative(3.0f)
lineTo(21.0f, 9.0f)
close()
}
}
return _swapHoriz!!
}
@Suppress("ObjectPropertyName") private var _swapHoriz: ImageVector? = null
| 0 | Kotlin | 2 | 6 | c2cadba9366ebd71d4a224945d76ba71d5bf7784 | 1,928 | fridgefriend | Apache License 2.0 |
src/main/kotlin/site/wenlong/dimens/ui/UI.kt | Wenlong-Guo | 154,920,832 | false | null | package site.wenlong.dimens.ui
import com.intellij.openapi.util.IconLoader
import com.intellij.ui.components.labels.LinkLabel
import com.intellij.util.IconUtil
import com.intellij.util.ui.JBFont
import com.intellij.util.ui.JBUI
import com.intellij.util.ui.UIUtil
import net.miginfocom.layout.CC
import net.miginfocom.layout.LC
import net.miginfocom.layout.LayoutUtil
import net.miginfocom.swing.MigLayout
import java.awt.Color
import java.awt.image.RGBImageFilter
import javax.swing.Icon
import javax.swing.border.Border
/**
* UI
*/
object UI {
// 使用`get() = ...`以保证获得实时`ScaledFont`
val defaultFont: JBFont get() = JBFont.create(UIUtil.getLabelFont(UIUtil.FontSize.NORMAL))
data class FontPair(val primary: JBFont, val phonetic: JBFont)
@JvmStatic
fun Icon.disabled(): Icon = IconUtil.filterIcon(this, { DisabledFilter() }, null)
private class DisabledFilter(color: Color = JBUI.CurrentTheme.Label.disabledForeground()) : RGBImageFilter() {
private val rgb = color.rgb
override fun filterRGB(x: Int, y: Int, argb: Int): Int {
return argb and -0x1000000 or (rgb and 0x00ffffff)
}
}
@JvmStatic
fun getBordersColor(): Color = JBUI.CurrentTheme.Popup.borderColor(true)
fun <T> LinkLabel<T>.setIcons(baseIcon: Icon) {
icon = baseIcon
disabledIcon = IconLoader.getDisabledIcon(baseIcon)
setHoveringIcon(IconUtil.darker(baseIcon, 3))
}
fun migLayout(gapX: String = "0!", gapY: String = "0!", insets: String = "0") =
MigLayout(LC().fill().gridGap(gapX, gapY).insets(insets))
fun migLayoutVertical() =
MigLayout(LC().flowY().fill().gridGap("0!", "0!").insets("0"))
fun spanX(cells: Int = LayoutUtil.INF): CC = CC().spanX(cells)
fun fill(): CC = CC().grow().push()
fun fillX(): CC = CC().growX().pushX()
fun fillY(): CC = CC().growY().pushY()
fun wrap(): CC = CC().wrap()
fun emptyBorder(topAndBottom: Int, leftAndRight: Int) = JBUI.Borders.empty(topAndBottom, leftAndRight)
fun emptyBorder(offsets: Int) = JBUI.Borders.empty(offsets)
fun lineAbove(): Border = JBUI.Borders.customLine(getBordersColor(), 1, 0, 0, 0)
fun lineBelow(): Border = JBUI.Borders.customLine(getBordersColor(), 0, 0, 1, 0)
fun lineToRight(): Border = JBUI.Borders.customLine(getBordersColor(), 0, 0, 0, 1)
operator fun Border.plus(external: Border): Border = JBUI.Borders.merge(this, external, true)
} | 1 | Kotlin | 5 | 11 | 9e9b3b60941ff614261c84cb50d8299d7b945e7f | 2,477 | Dimens-Generating | MIT License |
app/src/main/java/net/hiknot/android_mvvm_firestore_todo/data/source/TaskRepositoryImpl.kt | hikiit | 558,477,728 | false | {"Kotlin": 26772} | package net.hiknot.android_mvvm_firestore_todo.data.source
import android.util.Log
import com.google.firebase.firestore.FieldValue
import com.google.firebase.firestore.FirebaseFirestore
import kotlinx.coroutines.channels.awaitClose
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.callbackFlow
import kotlinx.coroutines.tasks.await
import net.hiknot.android_mvvm_firestore_todo.data.Task
import javax.inject.Inject
class TaskRepositoryImpl @Inject constructor(
private val firebaseProfile: FirebaseProfileService,
private val firestore: FirebaseFirestore,
) : TaskRepository {
companion object {
private const val TAG = "TaskRepository"
}
private val tasksCollectionPath = firestore
.collection("users")
.document(firebaseProfile.uid!!)
.collection("tasks")
override fun addTask(task: Task) {
tasksCollectionPath.document().set(task)
}
override fun updateTaskStatus(task: Task) {
task.documentId?.let {
// FIXME fieldの指定はハードコーディングではなく、data classの変数名を利用できるようにしたい
tasksCollectionPath.document(it)
.update("isDone", task.isDone, "updateAt", FieldValue.serverTimestamp())
}
}
override fun removeTask(id: String) {
tasksCollectionPath.document(id).delete()
}
override suspend fun getTask(id: String): Task? {
return tasksCollectionPath.document(id).get().await().toObject(Task::class.java)
}
override fun getTasks(): Flow<List<Task>> = callbackFlow {
val register =
tasksCollectionPath.orderBy("createAt").addSnapshotListener { snapshot, error ->
if (error != null) {
Log.e(TAG, "Listen failed.", error)
close()
return@addSnapshotListener
}
if (snapshot != null && snapshot.documents.isNotEmpty()) {
val tasks = snapshot.toObjects(Task::class.java)
Log.d(TAG, "TaskStream: $tasks")
trySend(tasks)
} else {
Log.d(TAG, "TaskStream is null")
trySend(listOf())
}
}
awaitClose { register.remove() }
}
}
| 0 | Kotlin | 0 | 0 | 2c226995f07fd7db5d88c2023f567a2e0ed2a384 | 2,343 | android-mvvm-firestore-todo-sample | MIT License |
rsocket-tck-core/src/main/kotlin/io/rsocket/tck/expect/frame/ExtensionFrame.kt | rsocket | 62,747,936 | false | null | package io.rsocket.tck.expect.frame
import io.rsocket.tck.expect.*
import io.rsocket.tck.frame.*
import strikt.api.*
import strikt.assertions.*
infix fun ExtensionFrame.expect(expected: ExtensionFrame): Unit = expectThat(this) {
get("header", ExtensionFrame::header).isEqualToHeader(expected.header, extensionFlagsAssertion)
get("extended type", ExtensionFrame::extendedType).isEqualTo(expected.extendedType)
get("data", ExtensionFrame::data).isEqualToBuffer(expected.data)
}
private val extensionFlagsAssertion: FlagsAssertion<ExtensionFrameFlags> = { expected ->
get("ignore", ExtensionFrameFlags::ignore).isEqualTo(expected.ignore)
get("metadata", ExtensionFrameFlags::metadata).isEqualTo(expected.metadata)
}
| 9 | Kotlin | 11 | 10 | ea932e63928a5a8bc31e4f6b78e63c9bb140cb90 | 736 | rsocket-tck | Apache License 2.0 |
app/src/main/java/com/github/ked4ama/composecolortool/view/template/ShowCases.kt | ked4ma | 316,941,728 | false | null | package com.github.ked4ama.composecolortool.view.template
import androidx.compose.foundation.layout.ConstraintLayout
import androidx.compose.foundation.layout.ConstraintLayoutScope
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
fun showCaseSize() = 1
@Composable
fun ShowCase(case: Case) {
ShowCaseContainer {
when (case) {
Case.CARDS -> ShowCase1()
Case.TEXTS -> ShowCase2()
Case.BUTTONS -> ShowCase3()
}
}
}
@Composable
private fun ShowCaseContainer(content: @Composable ConstraintLayoutScope.() -> Unit) {
ConstraintLayout(modifier = Modifier.fillMaxSize()) {
content()
}
}
enum class Case {
CARDS, TEXTS, BUTTONS
} | 0 | Kotlin | 0 | 0 | 607a57955a51be4eb82a0230d225c66445c138ed | 789 | ComposeColorTool | Apache License 2.0 |
example/src/commonMain/kotlin/lt/libredrop/peerdiscovery/example/Main.kt | libredrop | 207,655,407 | false | {"Kotlin": 38059} | package lt.libredrop.peerdiscovery.example
import kotlinx.cli.CommandLineInterface
import kotlinx.cli.flagValueArgument
import kotlinx.cli.parse
import kotlinx.cli.positionalArgument
import kotlinx.coroutines.flow.collect
import lt.libredrop.peerdiscovery.PeerDiscovery
fun main(args: Array<String>) {
val cli = CommandLineInterface("kotlin MainKt")
val mode by cli.flagValueArgument<PeerDiscovery.Mode>(
flags = listOf("--mode", "-m"),
valueSyntax = "MODE",
help = """
MODE variants: NORMAL | SHOUT | LISTEN
""".trimIndent(),
initialValue = PeerDiscovery.Mode.NORMAL,
mapping = { value: String -> PeerDiscovery.Mode.valueOf(value.toUpperCase()) }
)
val serviceName by cli.positionalArgument(
name = "SERVICE_NAME",
help = "Service name used to recognize peers of the same service. All parties must use same name",
minArgs = 1
)
try {
cli.parse(args)
} catch (e: Exception) {
return
}
val peerDiscovery = PeerDiscovery.Builder()
.build()
blocking {
peerDiscovery.start(serviceName!!, mode = mode).collect {
println("Discovered peer: $it")
}
}
}
expect fun blocking(body: suspend () -> Unit)
| 1 | Kotlin | 0 | 2 | 88bbd210fe3e6db4863717799a410a3aae1734cd | 1,279 | peer-discovery-kotlin | MIT License |
app/src/main/java/br/com/lucolimac/pokedex/data/util/Constants.kt | lucasomac | 627,122,617 | false | {"Kotlin": 66216} | package br.com.lucolimac.pokedex.data.util
internal object Constants {
const val POKE_API_HOST = "https://pokeapi.co"
const val POKE_API_BASE_PATH: String = "/api/v2/pokemon"
const val POKE_API_POKEMON_PATH: String = "$POKE_API_BASE_PATH/{name}"
}
| 0 | Kotlin | 0 | 0 | 79fbfe20e877acd20378464ce32cb26035af1750 | 261 | Pokedex | RSA Message-Digest License |
analysis/analysis-api/src/org/jetbrains/kotlin/analysis/api/annotations/KtAnnotationApplication.kt | JetBrains | 3,432,266 | false | {"Kotlin": 74444760, "Java": 6669398, "Swift": 4261253, "C": 2620837, "C++": 1953730, "Objective-C": 640870, "Objective-C++": 170766, "JavaScript": 135724, "Python": 48402, "Shell": 30960, "TypeScript": 22754, "Lex": 18369, "Groovy": 17273, "Batchfile": 11693, "CSS": 11368, "Ruby": 10470, "EJS": 5241, "Dockerfile": 5136, "HTML": 5073, "CMake": 4448, "Pascal": 1698, "FreeMarker": 1393, "Roff": 725, "LLVM": 395, "Scala": 80} | /*
* Copyright 2010-2023 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.analysis.api.annotations
import org.jetbrains.kotlin.descriptors.annotations.AnnotationUseSiteTarget
import org.jetbrains.kotlin.name.ClassId
import org.jetbrains.kotlin.psi.KtCallElement
/**
* Application of annotation to some declaration, type, or as argument inside another annotation.
*
* Some examples:
* - For declarations: `@Deprecated("Should not be used") fun foo(){}`
* - For types: `fun foo(x: List<@A Int>){}`
* - Inside another annotation (`B` is annotation here): `@A(B()) fun foo(){}
*
* @see KtAnnotationApplicationInfo
* @see KtAnnotationApplicationWithArgumentsInfo
*/
public sealed interface KtAnnotationApplication {
/**
* The [ClassId] of applied annotation. [ClassId] is a fully qualified name on annotation class.
*/
public val classId: ClassId?
/**
* [com.intellij.psi.PsiElement] which was used to apply annotation to declaration/type.
*
* Present only for declarations from sources. For declarations from other places (libraries, stdlib) it's `null`
*/
public val psi: KtCallElement?
/**
* [AnnotationUseSiteTarget] to which annotation was applied. May be not-null only for annotation applications for declarations.
*
* See more details in [Kotlin Documentation](https://kotlinlang.org/docs/annotations.html#annotation-use-site-targets) for more information about annotation targets.
*/
public val useSiteTarget: AnnotationUseSiteTarget?
/**
* This property can be used to optimize some argument processing logic.
* For example, if you have [KtAnnotationApplicationInfo] from [KtAnnotated.annotationInfos] and [isCallWithArguments] is **false**,
* then you can avoid [KtAnnotated.annotationsByClassId] call,
* because effectively you already have all necessary information in [KtAnnotationApplicationInfo]
*/
public val isCallWithArguments: Boolean
/**
* An index of the annotation in an owner. `null` when annotation is used as an argument of other annotations
*/
public val index: Int?
}
| 166 | Kotlin | 5,771 | 46,772 | bef0946ab7e5acd5b24b971eca532c43c8eba750 | 2,296 | kotlin | Apache License 2.0 |
src/main/java/io/sc3/plethora/gameplay/client/entity/SquidFeatureRenderer.kt | SwitchCraftCC | 491,699,521 | false | {"Kotlin": 383687, "Java": 259087} | package io.sc3.plethora.gameplay.client.entity
import net.minecraft.client.network.AbstractClientPlayerEntity
import net.minecraft.client.render.OverlayTexture
import net.minecraft.client.render.RenderLayer
import net.minecraft.client.render.VertexConsumer
import net.minecraft.client.render.VertexConsumerProvider
import net.minecraft.client.render.entity.feature.FeatureRenderer
import net.minecraft.client.render.entity.feature.FeatureRendererContext
import net.minecraft.client.render.entity.model.PlayerEntityModel
import net.minecraft.client.util.math.MatrixStack
import net.minecraft.util.math.RotationAxis
import net.minecraft.util.math.Vec3d
import org.joml.Matrix4f
import io.sc3.plethora.Plethora.ModId
import java.util.*
import kotlin.math.abs
import kotlin.math.cos
import kotlin.math.exp
import kotlin.math.sin
private const val SEGMENTS = 5
private const val TENTACLES = 6
private const val BASE_ANGLE = 25
// Dimensions of the one tentacle
private const val LENGTH = 0.3f
private const val WIDTH = 0.15f
private const val EASING_TICKS = 5.0
private const val OFFSET_SPEED = 0.1
private const val OFFSET_VARIANCE = 7.0
private val SQUID_UUID = UUID.fromString("d3156e4b-c712-4fd3-87b0-b24b8ca94209")
class SquidFeatureRenderer(
ctx: FeatureRendererContext<AbstractClientPlayerEntity, PlayerEntityModel<AbstractClientPlayerEntity>>
) : FeatureRenderer<AbstractClientPlayerEntity, PlayerEntityModel<AbstractClientPlayerEntity>>(ctx) {
private val layer = RenderLayer.getEntitySolid(ModId("textures/misc/white.png"))
private val lastAngles = DoubleArray(TENTACLES * SEGMENTS)
private val offsets = DoubleArray(TENTACLES * SEGMENTS)
private var tick = 0.0
init {
for (i in lastAngles.indices) {
lastAngles[i] = BASE_ANGLE.toDouble()
offsets[i] = Math.random() * Math.PI * 2
}
}
override fun render(matrices: MatrixStack, consumers: VertexConsumerProvider, light: Int,
player: AbstractClientPlayerEntity, limbAngle: Float, limbDistance: Float, tickDelta: Float,
animationProgress: Float, headYaw: Float, headPitch: Float) {
val profile = player.gameProfile ?: return
if (profile.id != SQUID_UUID) return // TODO: config for fun render
matrices.push()
if (player.isInSneakingPose) {
matrices.translate(0.0, 0.2, 0.0)
matrices.multiply(RotationAxis.POSITIVE_X.rotationDegrees(90.0f / Math.PI.toFloat()))
}
matrices.multiply(RotationAxis.POSITIVE_X.rotationDegrees(90.0f))
matrices.translate(0.0, 0.1, -0.3)
val angle = if (player.hurtTime > 0) {
val progress = player.hurtTime.toDouble() / player.maxHurtTime.toDouble()
BASE_ANGLE - (progress * (BASE_ANGLE - OFFSET_VARIANCE))
} else {
val velocity = Vec3d(player.lastRenderX, player.lastRenderY, player.lastRenderZ)
.distanceTo(player.pos)
val adjusted = 1 - exp(velocity * -2)
BASE_ANGLE - adjusted * BASE_ANGLE
}
tick = (tick + tickDelta) % (Math.PI * 2 / OFFSET_SPEED)
val consumer = consumers.getBuffer(layer)
for (i in 0 until TENTACLES) {
matrices.push()
matrices.multiply(RotationAxis.POSITIVE_Y.rotationDegrees(360.0f / TENTACLES * i))
matrices.translate(0.1, 0.0, 0.0)
for (j in 0 until SEGMENTS) {
// Offset each tentacle by a random amount
val lastAngle = lastAngles[i * SEGMENTS + j]
var thisAngle = angle + sin(offsets[i * SEGMENTS + j] + tick * OFFSET_SPEED) * OFFSET_VARIANCE
// Angle each tentacle to get a "claw" effect
thisAngle *= cos(j * (Math.PI / (SEGMENTS - 1)))
// Provide some basic easing on the angle
// Basically the middle segments have a high "delta"
if (abs(lastAngle - thisAngle) > 1) {
thisAngle = lastAngle - (lastAngle - thisAngle) / EASING_TICKS
}
lastAngles[i * SEGMENTS + j] = thisAngle
matrices.multiply(RotationAxis.NEGATIVE_Z.rotationDegrees(thisAngle.toFloat()))
val matrix4f = matrices.peek().positionMatrix
tentacle(consumer, matrix4f, light)
matrices.translate(0.0, LENGTH - WIDTH / 2.0, 0.0)
}
matrices.pop()
}
matrices.pop()
}
private fun tentacle(consumer: VertexConsumer, matrix4f: Matrix4f, light: Int) {
vertex(consumer, matrix4f, 0.0f, 0.0f, -WIDTH / 2, light)
vertex(consumer, matrix4f, 0.0f, 0.0f, WIDTH / 2, light)
vertex(consumer, matrix4f, 0.0f, LENGTH, WIDTH / 2, light)
vertex(consumer, matrix4f, 0.0f, LENGTH, -WIDTH / 2, light)
vertex(consumer, matrix4f, WIDTH, 0.0f, -WIDTH / 2, light)
vertex(consumer, matrix4f, WIDTH, 0.0f, WIDTH / 2, light)
vertex(consumer, matrix4f, 0.0f, 0.0f, WIDTH / 2, light)
vertex(consumer, matrix4f, 0.0f, 0.0f, -WIDTH / 2, light)
vertex(consumer, matrix4f, 0.0f, 0.0f, -WIDTH / 2, light)
vertex(consumer, matrix4f, 0.0f, LENGTH, -WIDTH / 2, light)
vertex(consumer, matrix4f, WIDTH, LENGTH, -WIDTH / 2, light)
vertex(consumer, matrix4f, WIDTH, 0.0f, -WIDTH / 2, light)
vertex(consumer, matrix4f, WIDTH, LENGTH, -WIDTH / 2, light)
vertex(consumer, matrix4f, WIDTH, LENGTH, WIDTH / 2, light)
vertex(consumer, matrix4f, WIDTH, 0.0f, WIDTH / 2, light)
vertex(consumer, matrix4f, WIDTH, 0.0f, -WIDTH / 2, light)
vertex(consumer, matrix4f, 0.0f, LENGTH, -WIDTH / 2, light)
vertex(consumer, matrix4f, 0.0f, LENGTH, WIDTH / 2, light)
vertex(consumer, matrix4f, WIDTH, LENGTH, WIDTH / 2, light)
vertex(consumer, matrix4f, WIDTH, LENGTH, -WIDTH / 2, light)
vertex(consumer, matrix4f, WIDTH, 0.0f, WIDTH / 2, light)
vertex(consumer, matrix4f, WIDTH, LENGTH, WIDTH / 2, light)
vertex(consumer, matrix4f, 0.0f, LENGTH, WIDTH / 2, light)
vertex(consumer, matrix4f, 0.0f, 0.0f, WIDTH / 2, light)
}
private fun vertex(consumer: VertexConsumer, matrix4f: Matrix4f, x: Float, y: Float, z: Float,
light: Int, color: Float = 0.0f) {
consumer // POSITION_COLOR_TEXTURE_OVERLAY_LIGHT_NORMAL
.vertex(matrix4f, x, y, z)
.color(color, 0.0f, 0.0f, 1.0f)
.texture(0.0f, 0.0f)
.overlay(OverlayTexture.DEFAULT_UV)
.light(light)
.normal(0.0f, 0.0f, 1.0f)
.next()
}
}
| 26 | Kotlin | 8 | 16 | 1309c51911a9b146218e5dae65a16dc8f932b23e | 6,240 | Plethora-Fabric | MIT License |
fuzzer/fuzzing_output/crashing_tests/verified/asFunKSmall.kt-1353378570.kt | ItsLastDay | 102,885,402 | false | null | fun fn0(): Unit {
}
fun fn1(x: Any): Unit {
}
inline fun Unit.asFailsWithCCE(operation: String, block: (() -> Unit)): Unit {
try {
block()
}catch(e: java.lang.ClassCastException) {
return
}
catch(e: Throwable) {
throw AssertionError("$operation: should throw ClassCastException, got $e")
}
throw AssertionError("$operation: should throw ClassCastException, no exception thrown")
}
inline fun asSucceeds(operation: (String)?, block: ((() -> Unit))?): Unit {
try {
block()
}catch(e: (Throwable)?) {
throw AssertionError("$operation: should not throw exceptions, got $e")
}
}
class MyFun: Function<Any>
fun box(): String {
val f0 = (::fn0 as Any)
val f1 = (((::fn1))!!!! as Any)
val myFun = (MyFun() as Any)
asSucceeds("f0 as Function0<*>")({(f0 as Function0<*>)})
asFailsWithCCE("f0 as Function1<*, *>")({(f0 as Function1<*, *>)})
asFailsWithCCE("f1 as Function0<*>")({(f1 as Function0<*>)})
asSucceeds("f1 as Function1<*, *>")({(f1 as Function1<*, *>)})
asFailsWithCCE("myFun as Function0<*>")({(myFun as Function0<*>)})
asFailsWithCCE("myFun as Function1<*, *>")({(myFun as Function1<*, *>)})
return "OK"
} | 0 | Kotlin | 0 | 6 | bb80db8b1383a6c7f186bea95c53faff4c0e0281 | 1,110 | KotlinFuzzer | MIT License |
relateddigital-android/src/main/java/com/relateddigital/relateddigital_android/model/Domain.kt | relateddigital | 379,568,070 | false | {"Kotlin": 1485751, "HTML": 21295} | package com.relateddigital.relateddigital_android.model
enum class Domain {
LOG_LOGGER,
LOG_REAL_TIME,
LOG_S,
IN_APP_NOTIFICATION_ACT_JSON,
IN_APP_ACTION_MOBILE,
IN_APP_SPIN_TO_WIN_PROMO_CODE,
IN_APP_STORY_MOBILE,
IN_APP_RECOMMENDATION_JSON,
IN_APP_FAVS_RESPONSE_MOBILE,
GEOFENCE_GET_LIST,
GEOFENCE_TRIGGER
} | 0 | Kotlin | 2 | 5 | cedee02f6ab0f05d08a34a662193d47edf55a8f8 | 353 | relateddigital-android | Amazon Digital Services License |
app/src/main/java/com/example/intelligent_shopping_cart/logic/utils/CommodityFactory.kt | cxp-13 | 629,093,945 | false | null | package com.example.intelligent_shopping_cart.logic.utils
import com.example.intelligent_shopping_cart.model.Commodity
import com.tencent.tencentmap.mapsdk.maps.model.LatLng
val CURRENT_LOCATION = LatLng(34.383392, 108.980198)
object CommodityFactory {
private val names = arrayOf("Apple", "Banana", "Orange", "Mango", "Pear")
private val brands = arrayOf("BrandA", "BrandB", "BrandC")
private val types = arrayOf("Fruit", "Vegetable", "Snack")
fun createDummyCommodities(count: Int): List<Commodity> {
return (1..count).map { index ->
Commodity(
name = "${names.random()} $index",
img = "https://picsum.photos/300?random=$index",
price = (10..100).random(),
origin = "Origin $index",
brand = brands.random(),
specification = "Specification $index",
shelfLife = "2023-12-31",
description = "Description $index",
count = (0..10).random(),
type = types.random(),
latitude = CURRENT_LOCATION.latitude + (Math.random() - 0.5) * 0.1,
longitude = CURRENT_LOCATION.longitude + (Math.random() - 0.5) * 0.1
)
}
}
} | 0 | Kotlin | 0 | 0 | 6a003112f1b1b1f67e191cf5ed59d3942afc1d25 | 1,262 | Intelligent-Shopping-Cart-APP | Apache License 2.0 |
js/js.translator/testData/box/callableReference/function/classMemberOverridden.kt | JetBrains | 3,432,266 | false | {"Kotlin": 74444760, "Java": 6669398, "Swift": 4261253, "C": 2620837, "C++": 1953730, "Objective-C": 640870, "Objective-C++": 170766, "JavaScript": 135724, "Python": 48402, "Shell": 30960, "TypeScript": 22754, "Lex": 18369, "Groovy": 17273, "Batchfile": 11693, "CSS": 11368, "Ruby": 10470, "EJS": 5241, "Dockerfile": 5136, "HTML": 5073, "CMake": 4448, "Pascal": 1698, "FreeMarker": 1393, "Roff": 725, "LLVM": 395, "Scala": 80} | // EXPECTED_REACHABLE_NODES: 1291
package foo
open class A {
open fun foo(a:String,b:String): String = "fooA:" + a + b
}
class B : A() {
override fun foo(a:String,b:String): String = "fooB:" + a + b
}
fun box(): String {
val b = B()
var ref = A::foo
val result = ref(b, "1", "2")
return (if (result == "fooB:12") "OK" else result)
}
| 166 | Kotlin | 5,771 | 46,772 | bef0946ab7e5acd5b24b971eca532c43c8eba750 | 360 | kotlin | Apache License 2.0 |
feature/photo-detail/src/main/java/st/slex/csplashscreen/feature/feature_photo_detail/domain/interactor/ImageDetailInteractor.kt | stslex | 413,161,718 | false | {"Kotlin": 332621, "Ruby": 1145} | package st.slex.csplashscreen.feature.feature_photo_detail.domain.interactor
import kotlinx.coroutines.flow.Flow
import st.slex.csplashscreen.core.photos.ui.model.PhotoModel
import st.slex.csplashscreen.feature.feature_photo_detail.domain.model.ImageDetail
interface ImageDetailInteractor {
fun getImageDetail(id: String): Flow<ImageDetail>
suspend fun getDownloadLink(id: String): String
suspend fun like(photoModel: PhotoModel)
} | 2 | Kotlin | 0 | 3 | 94b3ee35d150cc907f23f37601bef8bb877b8d3d | 448 | CSplashScreen | Apache License 2.0 |
root-project/build.gradle.kts | samuelgenio | 625,003,247 | false | null | import com.google.cloud.tools.gradle.appengine.appyaml.AppEngineAppYamlExtension
buildscript {
repositories {
mavenLocal()
mavenCentral()
gradlePluginPortal()
}
dependencies {
classpath("com.google.cloud.tools:appengine-gradle-plugin:2.4.4")
}
}
apply {
plugin("com.google.cloud.tools.appengine")
}
plugins {
java
war
id("org.springframework.boot") version "2.7.8"
id("io.spring.dependency-management") version "1.0.11.RELEASE"
kotlin("jvm") version "1.7.22"
kotlin("plugin.spring") version "1.7.22"
}
group = "com.example.appengine"
version = "0.0.1-SNAPSHOT"
java {
sourceCompatibility = JavaVersion.VERSION_11
targetCompatibility = JavaVersion.VERSION_11
}
repositories {
mavenCentral()
}
dependencies {
implementation("org.springframework.boot:spring-boot-starter-actuator")
implementation("org.springframework.boot:spring-boot-starter-data-mongodb")
// LOG4J
implementation("io.github.microutils:kotlin-logging-jvm:2.1.21")
implementation(project(":controller"))
implementation(project(":application"))
implementation(project(":domain"))
testImplementation("org.springframework.boot:spring-boot-starter-test")
}
tasks.getByName<Test>("test") {
useJUnitPlatform()
}
tasks.register<Copy>("frontendInstall") {
val frontendOrigin = "../frontend/build"
val frontendTarget = "resources/main/static/."
from(layout.projectDirectory.dir(frontendOrigin))
include("**")
into(layout.buildDirectory.dir(frontendTarget))
}
configure<AppEngineAppYamlExtension> {
println("task name - $name")
stage {
setArtifact(tasks.bootJar.map { j -> j.archiveFile.get().asFile })
}
deploy {
projectId = "my-project-id"
version = "spring-react"
promote = false
}
}
/*
ORDER TO EXECUTE TASKS
*/
tasks.compileJava {
dependsOn(tasks.getByName("frontendInstall"))
}
tasks.getByName("appengineStage") {
dependsOn(tasks.bootJar)
}
| 0 | Kotlin | 0 | 0 | 39e285cb9483132c9727a7d67b7c6abd9797934f | 2,024 | springReactAppengineStandard | Apache License 2.0 |
app/src/main/java/com/example/shopkart/database/DatabaseEntities.kt | siddheshkothadi | 246,612,489 | false | null | package com.example.shopkart.database
import androidx.room.Entity
import androidx.room.PrimaryKey
//Entities
//For ItemType
@Entity
data class DatabaseItemType1 constructor(
@PrimaryKey
val id: String,
val name: String,
val imgSrcUrl: String,
val price: String)
@Entity
data class DatabaseItemType2 constructor(
@PrimaryKey
val id: String,
val name: String,
val imgSrcUrl: String,
val price: String)
@Entity
data class DatabaseItemType3 constructor(
@PrimaryKey
val id: String,
val name: String,
val imgSrcUrl: String,
val price: String)
//For KitType
@Entity
data class DatabaseKitType constructor(
@PrimaryKey
val id: String,
var name: String,
val imgSrcUrl: String,
val description: String,
val price: String)
//For cart
@Entity
data class DatabaseCart constructor(
@PrimaryKey
val id: String,
val name: String,
val imgSrcUrl: String,
val price: String)
//For Account
@Entity
data class DatabaseAccount constructor(
@PrimaryKey(autoGenerate = true)
val id: Int,
val price: Int) | 0 | Kotlin | 4 | 6 | 8b7192f9adeb6c1c5f87fb8cc7637fd051254823 | 1,102 | Shopkart | MIT License |
app/src/main/java/edu/rosehulman/condrak/roseschedule/Constants.kt | keith-cr | 164,172,313 | false | null | package edu.rosehulman.condrak.roseschedule
object Constants {
const val TAG = "ROSE-SCHEDULE"
const val USERS_COLLECTION = "users"
const val PREFS = "PREFS"
const val KEY_SCHEDULE = "schedule"
const val KEY_REQUEST_CODES = "requestCodes"
const val CLASS_NOTIFICATIONS_CHANNEL_ID = "classNotifications"
const val CLASS_ALARMS_CHANNEL_ID = "classAlarms"
const val KEY_NOTIFICATION_ID = "notificationId"
const val KEY_UID = "uid"
const val KEY_BUNDLE = "bundle"
} | 0 | Kotlin | 0 | 0 | 1c371a063edb6ba014bc34e7195ee5d5aae7b10d | 502 | rose-schedule | MIT License |
src/main/kotlin/de/axelrindle/broadcaster/command/StartCommand.kt | axelrindle | 63,272,124 | false | null | package de.axelrindle.broadcaster.command
import de.axelrindle.broadcaster.BroadcastingThread
import de.axelrindle.broadcaster.plugin
import de.axelrindle.pocketknife.PocketCommand
import de.axelrindle.pocketknife.util.sendMessageF
import org.bukkit.command.Command
import org.bukkit.command.CommandSender
/**
* Starts the broadcasting thread.
*
* @see BroadcastingThread
*/
class StartCommand : PocketCommand() {
override fun getName(): String {
return "start"
}
override fun getDescription(): String {
return plugin.localization.localize("CommandHelp.Start")!!
}
override fun getUsage(): String {
return "/brc start"
}
override fun getPermission(): String {
return "broadcaster.start"
}
override fun handle(sender: CommandSender, command: Command, args: Array<out String>): Boolean {
try {
BroadcastingThread.start()
sender.sendMessageF(plugin.localization.localize("Started")!!)
} catch (e: RuntimeException) {
sender.sendMessageF(plugin.localization.localize(e.message!!)!!)
}
return true
}
override fun sendHelp(sender: CommandSender) {
sender.sendMessageF("&9${getUsage()} &f- &3${getDescription()}")
}
} | 1 | Kotlin | 0 | 0 | 747e646b3c441d8cdb933ddb2be88dd11a46bb5e | 1,278 | Broadcaster-Plugin | MIT License |
src/main/java/com/keecker/services/interfaces/navigation/PerceptionClient.kt | keecker | 159,186,194 | false | {"Java": 184686, "Kotlin": 105063, "C++": 2300, "CMake": 285} | /*
* Copyright (C) 2018 KEECKER SAS (www.keecker.com)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* Created by <NAME> on 2018-11-30.
*/
package com.keecker.services.interfaces.navigation
import android.content.ComponentName
import android.content.Intent
import android.os.IBinder
import com.keecker.services.interfaces.ApiChecker
import com.keecker.services.interfaces.PersistentServiceConnection
import com.keecker.services.interfaces.ServiceBindingInfo
import com.keecker.services.interfaces.utils.CompletableFutureCompat
import com.keecker.services.interfaces.utils.asCompletableFuture
import kotlinx.coroutines.CompletableDeferred
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.async
import java.util.*
interface PerceptionCoroutineClient {
suspend fun subscribeToOdometry(subscriber: IOdometryListener)
suspend fun unsubscribeToOdometry(subscriber: IOdometryListener)
suspend fun subscribeToWallDetection(subscriber: IWallSegmentationListener)
suspend fun unsubscribeToWallDetection(subscriber: IWallSegmentationListener)
// TODO(cyril) check when does ot returns null
suspend fun detectWall(): PlaneSegmentationResult?
}
interface PerceptionAsyncClient {
fun subscribeToOdometryAsync(subscriber: IOdometryListener) : CompletableFutureCompat<Unit>
fun unsubscribeToOdometryAsync(subscriber: IOdometryListener) : CompletableFutureCompat<Unit>
fun subscribeToWallDetectionAsync(subscriber: IWallSegmentationListener):
CompletableFutureCompat<Unit>
fun unsubscribeToWallDetectionAsync(subscriber: IWallSegmentationListener):
CompletableFutureCompat<Unit>
fun detectWallAsync(): CompletableFutureCompat<PlaneSegmentationResult?>
}
class PerceptionClient(
private val mvtPerceptionConnection: PersistentServiceConnection<IMovementPerceptionService>,
private val perceptionConnection: PersistentServiceConnection<IPerceptionService>,
private val apiChecker: ApiChecker
) :
PerceptionCoroutineClient,
PerceptionAsyncClient {
init {
mvtPerceptionConnection.onServiceConnected {
for (subscriber in odometrySubscribers) {
it.unsubscribeToOdometry(subscriber)
}
}
}
companion object {
val mvtPerceptionBindingInfo = object : ServiceBindingInfo<IMovementPerceptionService> {
override fun getIntent(): Intent {
val intent = Intent("com.keecker.services.navigation.ACTION_BIND_MOVEMENT_PERCEPTION")
intent.component = ComponentName(
"com.keecker.services",
"com.keecker.services.navigation.MovementPerceptionService")
return intent
}
override fun toInterface(binder: IBinder): IMovementPerceptionService {
return IMovementPerceptionService.Stub.asInterface(binder)
}
}
val perceptionBindingInfo = object : ServiceBindingInfo<IPerceptionService> {
override fun getIntent(): Intent {
val intent = Intent("com.keecker.services.navigation.ACTION_BIND_PERCEPTION")
intent.component = ComponentName(
"com.keecker.services",
"com.keecker.services.navigation.perception.PerceptionService")
return intent
}
override fun toInterface(binder: IBinder): IPerceptionService {
return IPerceptionService.Stub.asInterface(binder)
}
}
}
private val odometrySubscribers = HashSet<IOdometryListener>()
override suspend fun subscribeToOdometry(listener: IOdometryListener) {
mvtPerceptionConnection.execute { it.subscribeToOdometry(listener) }
odometrySubscribers.add(listener)
}
override suspend fun unsubscribeToOdometry(listener: IOdometryListener) {
odometrySubscribers.remove(listener)
mvtPerceptionConnection.execute { it.unsubscribeToOdometry(listener) }
}
private val wallDetectionSubscribers = HashSet<IWallSegmentationListener>()
override suspend fun subscribeToWallDetection(subscriber: IWallSegmentationListener) {
perceptionConnection.execute { it.subscribeToWallSegmentation(subscriber) }
wallDetectionSubscribers.add(subscriber)
}
override suspend fun unsubscribeToWallDetection(subscriber: IWallSegmentationListener) {
wallDetectionSubscribers.remove(subscriber)
perceptionConnection.execute { it.unsubscribeToWallSegmentation(subscriber) }
}
override suspend fun detectWall() : PlaneSegmentationResult? {
val deferred = CompletableDeferred<PlaneSegmentationResult?>()
val subscriber = object : IWallSegmentationListener.Stub() {
override fun onWallSegmentation(segmentationResult: PlaneSegmentationResult?) {
deferred.complete(segmentationResult)
}
}
subscribeToWallDetection(subscriber)
// TODO(cyril) use default connection timeout?
deferred.await()
unsubscribeToWallDetection(subscriber)
return deferred.getCompleted()
}
override fun subscribeToOdometryAsync(subscriber: IOdometryListener):
CompletableFutureCompat<Unit> {
return GlobalScope.async {
subscribeToOdometry(subscriber)
}.asCompletableFuture()
}
override fun unsubscribeToOdometryAsync(subscriber: IOdometryListener):
CompletableFutureCompat<Unit> {
return GlobalScope.async {
unsubscribeToOdometry(subscriber)
}.asCompletableFuture()
}
override fun subscribeToWallDetectionAsync(subscriber: IWallSegmentationListener):
CompletableFutureCompat<Unit> {
return GlobalScope.async {
subscribeToWallDetection(subscriber)
}.asCompletableFuture()
}
override fun unsubscribeToWallDetectionAsync(subscriber: IWallSegmentationListener):
CompletableFutureCompat<Unit> {
return GlobalScope.async {
unsubscribeToWallDetection(subscriber)
}.asCompletableFuture()
}
override fun detectWallAsync(): CompletableFutureCompat<PlaneSegmentationResult?> {
return GlobalScope.async {
detectWall()
}.asCompletableFuture()
}
} | 3 | Java | 1 | 5 | a05b8b0400a7b900a377c5cdad8c82bc4a2f6e7e | 6,907 | services-api | Apache License 2.0 |
src/main/kotlin/de/fabmax/binparse/StructInstance.kt | fabmax | 46,639,067 | false | null | package de.fabmax.binparse
import java.util.*
/**
* Created by max on 18.11.2015.
*/
class StructInstance(structName: String, fields: HashMap<String, Field<*>> = HashMap<String, Field<*>>()) :
ContainerField<HashMap<String, Field<*>>>(structName, fields), Iterable<Field<*>> by fields.values {
override operator fun contains(key: String): Boolean {
return value.containsKey(key)
}
override fun get(index: Int): Field<*> {
return value.values.find { it.index == index } ?: throw NoSuchFieldException("Index not found: $index")
}
override fun get(name: String): Field<*> {
val path = name.splitToSequence('.').iterator()
var fName = path.next()
var field = value[fName] ?: throw NoSuchFieldException("No such field: $fName")
for (cName in path) {
if (field is StructInstance) {
field = field[cName]
fName = cName
} else {
throw NoSuchFieldException("No such field: $fName.$cName: $fName has no children")
}
}
return field
}
fun flat(): Iterator<Field<*>> {
return Flaterator(iterator())
}
override fun hasChildQualifier(qualifier: String): Boolean {
return value.values.find { it.hasQualifier(qualifier) } != null
}
override fun toString(): String {
val buf = StringBuilder()
buf.append("{ ")
value.values.sortedBy { it.index }.forEach { buf.append(it.name).append(" = ").append(it).append("; ") }
buf.append("}")
return buf.toString()
}
override fun toString(indent: Int, withFieldName: Boolean): String {
val buf = StringBuffer()
for (i in 1 .. indent) {
buf.append(' ')
}
val ind = buf.toString()
if (withFieldName) {
buf.append(name).append(" = ")
}
buf.append("{\n")
value.values.sortedBy { it.index }.forEach { buf.append(it.toString(indent + 2)).append('\n') }
buf.append(ind).append('}')
return buf.toString()
}
private class Flaterator(structIt: Iterator<Field<*>>) : Iterator<Field<*>> {
val stack = Stack<Iterator<Field<*>>>()
init {
stack.push(structIt);
}
override fun hasNext(): Boolean {
while (!stack.isEmpty() && !stack.peek().hasNext()) {
stack.pop()
}
return !stack.isEmpty()
}
override fun next(): Field<*> {
if (!hasNext()) {
throw NoSuchElementException("No more fields")
}
val field = stack.peek().next()
if (field is StructInstance) {
stack.push(field.iterator())
} else if (field is ArrayField) {
stack.push(field.iterator())
}
return field
}
}
override fun put(field: Field<*>) {
if (value.containsKey(field.name)) {
throw IllegalArgumentException("ParseResult already contains a field with name " + field.name)
}
field.index = value.size
value.put(field.name, field)
}
operator fun Field<*>.unaryPlus() {
put(this)
}
protected fun <F : Field<*>> initField(field: F, init: F.() -> Unit): F {
field.init()
put(field)
return field
}
fun array(name: String, init: ArrayField.() -> Unit) = initField(ArrayField(name), init)
fun int(name: String, init: IntField.() -> Unit) = initField(IntField(name, 0), init)
fun string(name: String, init: StringField.() -> Unit) = initField(StringField(name, ""), init)
fun struct(name: String, init: StructInstance.() -> Unit) = initField(StructInstance(name), init)
}
fun struct(name: String = "anonymous_struct", init: StructInstance.() -> Unit): StructInstance {
val struct = StructInstance(name)
struct.init()
return struct
} | 0 | Kotlin | 0 | 2 | e26b8b444951cb9e092079a083bfee3d21617267 | 3,970 | binparse | Apache License 2.0 |
examples/opcua-auto-discovery/src/main/kotlin/com/amazonaws/sfc/config/OpcuaAutoDiscoveryConfigProvider.kt | aws-samples | 700,380,828 | false | {"Kotlin": 2245850, "Python": 6111, "Dockerfile": 4679, "TypeScript": 4547, "JavaScript": 1171} | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: MIT-0
package com.amazonaws.sfc.config
import com.amazonaws.sfc.config.AutoDiscoveryProviderConfiguration.Companion.CONFIG_DEFAULT_MAX_RETRIES
import com.amazonaws.sfc.config.BaseConfiguration.Companion.CONFIG_CHANNELS
import com.amazonaws.sfc.config.BaseConfiguration.Companion.CONFIG_DESCRIPTION
import com.amazonaws.sfc.config.BaseConfiguration.Companion.CONFIG_SOURCES
import com.amazonaws.sfc.data.JsonHelper
import com.amazonaws.sfc.data.JsonHelper.Companion.gsonExtended
import com.amazonaws.sfc.log.Logger
import com.amazonaws.sfc.opcua.config.OpcuaAdapterConfiguration
import com.amazonaws.sfc.opcua.config.OpcuaConfiguration
import com.amazonaws.sfc.opcua.config.OpcuaConfiguration.Companion.CONFIG_NODE_ID
import com.amazonaws.sfc.opcua.config.OpcuaNodeChannelConfiguration.Companion.CONFIG_NODE_EVENT_TYPE
import com.amazonaws.sfc.opcua.config.OpcuaServerConfiguration
import com.amazonaws.sfc.opcua.config.OpcuaSourceConfiguration
import com.amazonaws.sfc.service.ConfigProvider
import com.amazonaws.sfc.util.buildScope
import kotlinx.coroutines.channels.Channel
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
import kotlinx.coroutines.runBlocking
import org.eclipse.milo.opcua.sdk.client.nodes.UaNode
import java.security.PublicKey
import java.util.regex.Pattern
import kotlin.time.Duration
// Custom config provider using autodiscovery to dynamically add channels to OPCUA source nodes from node
class OpcuaAutoDiscoveryConfigProvider(
private val configStr: String,
private val configVerificationKey: PublicKey?,
private val logger: Logger
) : ConfigProvider {
private val className = this::class.java.simpleName
private val scope = buildScope("CustomConfigProvider")
private var waitBeforeRetry: Duration? = null
private var maxRetries = CONFIG_DEFAULT_MAX_RETRIES
private var retryCount = 0
// channel to pass configuration to SFC core
override val configuration: Channel<String> = Channel<String>(1)
private var lastConfig: String? = null
private var providerConfig: AutoDiscoveryProviderConfiguration? = AutoDiscoveryProviderConfiguration()
val discoveryWorker = scope.launch {
val log = logger.getCtxLoggers(className, "discoveryWorker")
var allSourcesSuccessfullyDiscovered = false
while (!allSourcesSuccessfullyDiscovered) {
if (configVerificationKey != null) {
if (!ConfigVerification.verify(configStr, configVerificationKey)) {
log.error("Content of configuration could not be verified")
continue
}
}
// get a config reader for the input configuration data
val configReader = ConfigReader.createConfigReader(configStr, allowUnresolved = true)
try {
// get auto discovery config only, this needs verification
val autoDiscovery: OpcuaAutoDiscoveryConfiguration = configReader.getConfig(true)
providerConfig = autoDiscovery.autoDiscoveryProviderConfig
// if no autodiscovery sources just emit received configuration
if (providerConfig == null) {
log.error("No autodiscovery configured")
return@launch
}
// make config setting available in class scope
waitBeforeRetry = providerConfig?.waitForRetry
maxRetries = providerConfig?.maxRetries ?: CONFIG_DEFAULT_MAX_RETRIES
log.trace("Autodiscovery configured for sources ${providerConfig!!.sources.keys}")
// get opcua configuration, validation is switched off as it has not been processed by the config provider
val opcuaConfigInput: OpcuaConfiguration = configReader.getConfig(validate = false)
// get the input config as mutable map so channels for discovered nodes can be added
@Suppress("UNCHECKED_CAST")
val configOutput = gsonExtended().fromJson(configStr, Map::class.java) as MutableMap<String, Any>
// the sources in the output configuration
@Suppress("UNCHECKED_CAST")
val configOutputSources = configOutput[CONFIG_SOURCES] as MutableMap<String, Map<String, Any>>
try {
// validate if configured sources for autodiscovery are consistent with configured sources
checkIfConfiguredAutoDiscoverySourcesExist(opcuaConfigInput, providerConfig)
checkIfEmptySourcesHaveAutoDiscoveryConfiguration(opcuaConfigInput, providerConfig)
} catch (e: Exception) {
log.error("Error validating autodiscovery configuration, $e")
return@launch
}
allSourcesSuccessfullyDiscovered = true
// process all configured sources
opcuaConfigInput.sources.forEach { (sourceID, sourceConfig) ->
// add channels for discovered node to the source configuration
// addNodeChannelsForSource(sourceID, sourceConfig, opcuaConfigInput, configOutputSources)
// If no nodes were discovered then run autodiscovery after a wait period (if waitBeforeRetry is configured)
if (addNodeChannelsForSource(sourceID, sourceConfig, opcuaConfigInput, configOutputSources) == 0) {
log.error("No nodes discovered for source $sourceID")
allSourcesSuccessfullyDiscovered = false
}
}
// emit configuration if created sources configuration is valid
if (validateSources(configOutputSources, log)) {
emitConfiguration(buildConfigOutputString(configOutput))
}
// all sources have been discovered successfully, no need for retry to failed sources
if (allSourcesSuccessfullyDiscovered) {
return@launch
}
} catch (e: Exception) {
log.error("Error executing autodiscovery, $e")
}
// If a period for retry was configured retry if discovery for a source did not return any nodes.
retryCount += 1
if (waitBeforeRetry == null || retryCount > maxRetries) return@launch
log.error("Retrying autodiscovery in $waitBeforeRetry")
delay(waitBeforeRetry!!)
}
}
private fun addNodeChannelsForSource(
sourceID: String,
sourceConfig: OpcuaSourceConfiguration,
opcuaConfigInput: OpcuaConfiguration,
configOutputSources: MutableMap<String, Map<String, Any>>
): Int {
// nodes for source to browse
val nodesForSource: NodeDiscoveryConfigurations = providerConfig?.sources?.get(sourceID) ?: emptyList()
if (nodesForSource.isEmpty()) return 0
// discover nodes for this source
val discoveredNodesForSource = discoverSourceNodesNodes(sourceID, sourceConfig, opcuaConfigInput, nodesForSource)
// channels configuration for source
@Suppress("UNCHECKED_CAST")
var outputChannelsForSource = configOutputSources[sourceID]?.get(CONFIG_CHANNELS) as MutableMap<String, Map<String, Any>>?
if (outputChannelsForSource == null) {
outputChannelsForSource = mutableMapOf()
(configOutputSources[sourceID] as MutableMap<String, Any>?)?.set(CONFIG_CHANNELS, outputChannelsForSource)
}
// Add a channel for every discovered node
discoveredNodesForSource.forEach { discoveredNode: DiscoveredNode ->
val (channelName: String, channelMap) = buildNodeChannelMapEntry(discoveredNode)
outputChannelsForSource[channelName] = channelMap
}
// return number of added channels
return discoveredNodesForSource.size
}
private fun validateSources(
configOutputSources: MutableMap<String, Map<String, Any>>, log: Logger.ContextLogger
): Boolean {
// filter out all sources without any channels
val sourcesWithChannels = configOutputSources.filter { (s, c) ->
@Suppress("UNCHECKED_CAST")
val channelsForSource = c[CONFIG_CHANNELS] as MutableMap<String, Map<String, Any>>?
if (channelsForSource.isNullOrEmpty()) {
log.error("Removing source \"$s\" from configuration as it has no channels after auto discovery")
false
} else true
}
// configuration is valid if it does not contain any sources
if (sourcesWithChannels.isEmpty()) {
log.error("No sources with channels after auto discovery")
return false
}
return true
}
private fun discoverSourceNodesNodes(
sourceID: String,
sourceConfig: OpcuaSourceConfiguration,
opcuaConfigInput: OpcuaConfiguration,
nodesForSource: NodeDiscoveryConfigurations
): DiscoveredNodes {
// get the adapter used for the source
val adapterForSource = getProtocolAdapterForSource(sourceID, opcuaConfigInput, sourceConfig)
// get the server used to read this source
val server = if (adapterForSource != null) getServerForSource(sourceID, sourceConfig.sourceAdapterOpcuaServerID, adapterForSource) else null
// get the server profile, as it is needed to validate the event type of discovered event nodes
val serverProfile = adapterForSource?.serverProfiles?.get(server?.serverProfile)
// create an instance of OPCUA source used to discover the nodes
val opcuaSource = OpcuaDiscoverySource(
sourceID = sourceID,
configuration = opcuaConfigInput,
serverProfile = serverProfile,
logger = logger
)
// discover and return nodes for this source
return discoverNodes(opcuaSource, nodesForSource)
}
private fun discoverNodes(source: OpcuaDiscoverySource, nodesForSource: NodeDiscoveryConfigurations): DiscoveredNodes {
val log = logger.getCtxLoggers(className, "discoverNodes")
// get sub nodes up to specified depth
val nodes = sequence {
nodesForSource.forEach { node ->
val nodes = runBlocking {
source.discoverNodes(
nodeID = node.nodeID,
discoveryDepth = node.discoveryDepth,
nodeTypesToDiscover = node.nodeTypesToDiscover
)
}
// apply node filtering
val filteredNodes = applyNodeFilters(nodes, node)
this.yieldAll(filteredNodes)
}
}.toList()
log.info("Discovered ${nodes.size} nodes for source ${source.sourceID}")
return nodes
}
private fun applyNodeFilters(nodesToFilter: DiscoveredNodes, nodeConfiguration: NodeDiscoveryConfiguration): DiscoveredNodes {
val filteredNodes = selectIncludedNodes(nodesToFilter, nodeConfiguration.inclusions)
return filterOutExcludedNodes(filteredNodes, nodeConfiguration.exclusions)
}
private fun filterOutExcludedNodes(nodes: DiscoveredNodes, exclusionPatterns: List<Pattern>): DiscoveredNodes {
val trace = logger.getCtxTraceLog(className, "excludeNodes")
return nodes.filter { node ->
if (exclusionPatterns.isEmpty()) true
else {
var excluded = false
exclusionPatterns.forEach { excludePattern ->
if (!excluded) {
// exclude if pathname of node matches this exclude pattern
excluded = excludePattern.matcher(node.path).matches()
if (excluded) trace("Node \"${node.path}\" is excluded by pattern \"${excludePattern.pattern()}\"")
}
}
!excluded
}
}
}
private fun selectIncludedNodes(nodes: DiscoveredNodes, inclusionPatterns: List<Pattern>): DiscoveredNodes {
val trace = logger.getCtxTraceLog(className, "includedNodes")
return nodes.filter { node ->
if (inclusionPatterns.isEmpty()) true
else {
var included = false
inclusionPatterns.forEach { includePattern ->
if (!included) {
// include if pathname of node matches this include pattern
included = includePattern.matcher(node.path).matches()
if (included) trace("Node \"${node.path}\" is included by pattern \"${includePattern.pattern()}\"")
}
}
included
}
}
}
private fun buildNodeChannelMapEntry(discoveredNode: DiscoveredNode): Pair<String, MutableMap<String, Any>> {
// build the channelID to use as key in the map
val channelID: String = buildChannelIDForNode(discoveredNode.parents, discoveredNode.node)
val newChannel = mutableMapOf<String, Any>()
// the node to read/register for the channel
newChannel[CONFIG_NODE_ID] = discoveredNode.node.nodeId.toParseableString()
// if the node is an event add the type of the event
if (providerConfig?.includeDescription == true) {
val description = discoveredNode.node.description?.text
if (!description.isNullOrEmpty()) {
newChannel[CONFIG_DESCRIPTION] = discoveredNode.node.description.text.toString()
}
}
// if the node has a description add it as description for the channel
if (discoveredNode is EventNode) newChannel[CONFIG_NODE_EVENT_TYPE] =
discoveredNode.eventType
return channelID to newChannel
}
private suspend fun emitConfiguration(configStr: String) {
if (lastConfig != configStr) {
val log = logger.getCtxLoggers(className, "emitConfiguration")
log.trace("Emitting configuration to SFC core\n$configStr")
// send the configuration to the SFC Core
configuration.send(configStr)
saveConfiguration(configStr)
lastConfig = configStr
}
}
private fun saveConfiguration(configStr: String) {
// if a file name is configured then save the configuration to that file
val savedLastConfig = providerConfig?.savedLastConfig
if (savedLastConfig != null) {
val log = logger.getCtxLoggers(className, "saveConfiguration")
try {
log.info("Saving config to $savedLastConfig")
savedLastConfig.writeText(configStr)
} catch (e: Exception) {
log.error("Error saving last configuration to file $savedLastConfig, $e")
}
}
}
private fun getServerForSource(
sourceID: String,
sourceAdapterOpcuaServerID: String,
sourceAdapter: OpcuaAdapterConfiguration
): OpcuaServerConfiguration? {
val log = logger.getCtxLoggers(className, "getServerForSource")
val server = sourceAdapter.opcuaServers[sourceAdapterOpcuaServerID]
if (server == null) log.error("Server \"${sourceAdapterOpcuaServerID}\" for source \"$sourceID\" does not exists, available servers are ${sourceAdapter.opcuaServers}")
else log.trace("Used server for source \"$sourceID\" is \"$server\"")
return server
}
private fun getProtocolAdapterForSource(
sourceID: String,
inputConfiguration: OpcuaConfiguration,
sourceConfig: OpcuaSourceConfiguration
): OpcuaAdapterConfiguration? {
val log = logger.getCtxLoggers(className, "getProtocolAdapterForSource")
val adapterForSource = inputConfiguration.protocolAdapters[sourceConfig.protocolAdapterID]
if (adapterForSource == null) log.error("\"$sourceID\" protocol adapter \"${sourceConfig.protocolAdapterID}\" does not exist, available adapters are ${inputConfiguration.protocolAdapters.keys}")
log.trace("Adapter for source $sourceID is $adapterForSource")
return adapterForSource
}
private fun checkIfEmptySourcesHaveAutoDiscoveryConfiguration(opcuaConfigIn: OpcuaConfiguration, providerConfig: AutoDiscoveryProviderConfiguration?) {
val log = logger.getCtxLoggers(className, "checkIfEmptySourcesHaveAutoDiscoveryConfiguration")
if (providerConfig == null) return
opcuaConfigIn.sources.filter { it.value.channels.isEmpty() }.forEach {
if (!providerConfig.sources.containsKey(it.key))
log.error("Source \"${it.key}\" has no configured channels and no autodiscovery for this is configured")
}
}
private fun checkIfConfiguredAutoDiscoverySourcesExist(inputConfiguration: OpcuaConfiguration, providerConfig: AutoDiscoveryProviderConfiguration?) {
val log = logger.getCtxLoggers(className, "checkIfConfiguredAutoDiscoverySourcesExist")
providerConfig?.sources?.keys?.forEach {
if (!inputConfiguration.sources.keys.contains(it)) {
log.warning("Autodiscovery is configured for source \"$it\", but this source does not exist")
}
}
}
companion object {
private fun buildConfigOutputString(configOutput: MutableMap<String, Any>): String {
val gson = JsonHelper.gsonBuilder().setPrettyPrinting().disableHtmlEscaping().create()
return gson.toJson(configOutput)
}
private fun buildChannelIDForNode(parents: List<UaNode>, node: UaNode) =
// the channel is a concatenation, with a '/' separator of cleaned up browse names of the path for the node
(parents + listOf(node))
.joinToString(separator = "/") {
cleanupNameForNode(it)
}
private fun cleanupNameForNode(node: UaNode): String {
// cleanup browse name for use as channelID for the generated channels
return node.browseName.name.toString()
.replace("http://", "http_")
.replace("/", "_")
.replace(":", "_")
.replace(" ", "")
.trim('_')
}
@JvmStatic
@Suppress("unused")
fun newInstance(vararg createParameters: Any): ConfigProvider {
return OpcuaAutoDiscoveryConfigProvider(
createParameters[0] as String,
createParameters[1] as PublicKey?,
createParameters[2] as Logger
)
}
}
} | 5 | Kotlin | 2 | 15 | fd38dbb80bf6be06c00261d9992351cc8a103a63 | 18,875 | shopfloor-connectivity | MIT No Attribution |
src/main/kotlin/KI.kt | zeitlinger | 194,141,884 | false | null | import kotlin.math.max
enum class Strategie {
Angreifen,
Verteidigen,
Expandieren
}
fun produzierenKI(spieler: Spieler, gegner: Spieler): Pair<EinheitenTyp?, GebäudeTyp?> {
val gStrategie = scoutingAuswerten(gegner)
val einheit = if (gStrategie[0] + gStrategie[1] * 2 + (minOf(
gStrategie[2] / 5,
gebäudeAnzahl(gegner, fabrik)
) - minOf(spieler.minen, gebäudeAnzahl(spieler, kaserne) * 2)) <= 30
) {
infantrie
} else if (gStrategie[0] + minOf(gStrategie[2] / 5, gebäudeAnzahl(gegner, kaserne) * 2) >= einheitenAnzahl(
spieler,
infantrie
) + einheitenAnzahl(spieler, panzer) * 4 + minOf(spieler.minen, gebäudeAnzahl(spieler, fabrik))
) {
panzer
} else {
null
}
if (einheit != null && einheit.gebäudeTyp != null) {
if (gebäudeAnzahl(spieler, einheit.gebäudeTyp) == 0) {
return null to einheit.gebäudeTyp
}
}
return einheit to null
}
fun zielAuswählenKI(spieler: Spieler, einheit: Einheit, gegner: Spieler): Punkt? {
if (spieler.einheiten.size > 10) {
return gegner.startpunkt
}
return null
}
val konterStrategie = mapOf(
Strategie.Angreifen to Strategie.Verteidigen,
Strategie.Verteidigen to Strategie.Expandieren,
Strategie.Expandieren to Strategie.Angreifen
)
fun scoutingAuswerten(gegner: Spieler): List<Int> {
var angriff = gegner.einheiten.size - einheitenAnzahl(gegner, panzer)
var verteidigung = einheitenAnzahl(gegner, panzer) * 2
var expansion = gegner.minen * 5
val gesamtwert = angriff + verteidigung + expansion
angriff /= gesamtwert
angriff *= 100
verteidigung /= gesamtwert
verteidigung *= 100
expansion /= gesamtwert
expansion *= 100
return listOf(angriff, verteidigung, expansion)
} | 0 | Kotlin | 0 | 0 | aa02a9d4f882e00c2a62dba6eaed9a543df90d8b | 1,855 | starcraft-III | MIT License |
src/main/kotlin/com/developerphil/adbidea/action/extend/ScreenCaptureAction.kt | longforus | 146,382,514 | true | {"Kotlin": 132853, "Java": 38887} | package com.developerphil.adbidea.action.extend
import com.developerphil.adbidea.action.AdbAction
import com.developerphil.adbidea.adb.AdbFacade
import com.intellij.openapi.actionSystem.AnActionEvent
import com.intellij.openapi.fileChooser.FileChooserDescriptor
import com.intellij.openapi.fileChooser.ex.FileChooserDialogImpl
import com.intellij.openapi.project.Project
import com.intellij.openapi.vfs.VirtualFile
import java.io.File
import java.text.SimpleDateFormat
import java.util.*
/**
* Created by <NAME> on 8/28/2018 2:53 PM.
* Description : capture device screen via adb
*/
class ScreenCaptureAction : AdbAction() {
var deviceName = ""
init {
saveDirChooserDescriptor.title = "Select capture .png file save to..."
}
override fun actionPerformed(e: AnActionEvent, project: Project) {
AdbFacade.getDeviceModel(project){model:String->
deviceName = model
}
val choose = FileChooserDialogImpl(saveDirChooserDescriptor, project)
.choose(project, selectedFile)
if (choose.isNotEmpty()) {
selectedFile = choose[0]
val fileName = "${deviceName}_${dateFormat.format(Date())}.png"
AdbFacade.captureScreen(project, File(selectedFile?.canonicalPath),fileName)
}
}
companion object {
private var selectedFile: VirtualFile? = null
private var saveDirChooserDescriptor: FileChooserDescriptor = FileChooserDescriptor(false, true, false, false, false, false)
private var dateFormat = SimpleDateFormat("yyyyMMddHHmmss")
}
}
| 2 | Kotlin | 3 | 30 | 8e3c405ca80b9d341b419d65693d4c4d4e0c546e | 1,587 | adb-idea-plus | Apache License 2.0 |
petviewer/app/src/main/java/com/example/petviewer/network/PetInfoApiGatherer.kt | leakwok | 653,743,563 | false | null | package com.example.petviewer.network
import okhttp3.MultipartBody
import okhttp3.RequestBody
import retrofit2.Retrofit
import retrofit2.converter.gson.GsonConverterFactory
import retrofit2.http.GET
import retrofit2.http.Multipart
import retrofit2.http.POST
import retrofit2.http.Part
import retrofit2.http.Url
private const val PET_URL = "https://eulerity-hackathon.appspot.com/"
//private val moshi = Moshi.Builder()
// .add(KotlinJsonAdapterFactory())
// .build()
private val retrofit = Retrofit.Builder()
.addConverterFactory(GsonConverterFactory.create())
.baseUrl(PET_URL)
.build()
interface PetInfoApiGatherer {
@GET("pets")
suspend fun getInfo(): List<PetInfo>
@GET("upload")
suspend fun getUploadUrl(): UploadObject
@Multipart
@POST
suspend fun uploadImage(
@Url endpoint: String,
@Part("appid") name: RequestBody,
@Part("original") originalUrl: RequestBody,
@Part editedPetImage: MultipartBody.Part
)
}
val apiService = retrofit.create(PetInfoApiGatherer::class.java)
//object PetApi {
// val retrofitService: PetInfoApiGatherer by lazy { retrofit.create(PetInfoApiGatherer::class.java) }
//} | 0 | Kotlin | 0 | 0 | d73f9466f35aa6ef429225d81cf743c02f442ecc | 1,200 | simple-pet-app | MIT License |
app/src/main/java/com/bajicdusko/fragmentmanager/kotlinsample/ExampleFragmentChannel.kt | bajicdusko | 94,332,585 | false | {"Java": 16267, "Kotlin": 13253} | package com.bajicdusko.fragmentmanager.kotlinsample
/**
* Created by <NAME> on 14.06.17.
* GitHub @bajicdusko
*/
interface ExampleFragmentChannel : com.bajicdusko.kotlinfragmentmanager.FragmentChannel {
fun openSecondFragment()
} | 0 | Java | 1 | 6 | f9ed5195499f05bb2ef2b7a4f11165ec8a584044 | 242 | SimpleFragmentManager | Apache License 2.0 |
libraries/tools/kotlin-gradle-plugin-integration-tests/src/test/resources/testProject/hierarchical-mpp-published-modules/my-app/src/linuxX64Main/kotlin/AppLinux.kt | JetBrains | 3,432,266 | false | {"Kotlin": 74444760, "Java": 6669398, "Swift": 4261253, "C": 2620837, "C++": 1953730, "Objective-C": 640870, "Objective-C++": 170766, "JavaScript": 135724, "Python": 48402, "Shell": 30960, "TypeScript": 22754, "Lex": 18369, "Groovy": 17273, "Batchfile": 11693, "CSS": 11368, "Ruby": 10470, "EJS": 5241, "Dockerfile": 5136, "HTML": 5073, "CMake": 4448, "Pascal": 1698, "FreeMarker": 1393, "Roff": 725, "LLVM": 395, "Scala": 80} | package com.example.bar
import com.example.foo.*
fun appLinux() {
fooLinuxAndJs()
barLinuxAndJs()
} | 166 | Kotlin | 5,771 | 46,772 | bef0946ab7e5acd5b24b971eca532c43c8eba750 | 109 | kotlin | Apache License 2.0 |
backend/src/main/kotlin/io/github/artemy/osipov/shop/exception/EntityNotFoundException.kt | artemy-osipov | 45,270,467 | false | {"Kotlin": 55169, "Svelte": 37066, "TypeScript": 22855, "JavaScript": 9122, "HTML": 329} | package io.github.artemy.osipov.shop.exception
import java.lang.RuntimeException
import kotlin.reflect.KClass
class EntityNotFoundException(val targetClass: KClass<*>, val id: Any) : RuntimeException(
generateMessage(
targetClass, id
)
) {
private companion object {
fun generateMessage(targetClass: KClass<*>, id: Any): String {
return String.format(
"Entity '%s' with id '%s' not exists",
targetClass.simpleName, id
)
}
}
} | 0 | Kotlin | 0 | 1 | 1499774daaa527b8bd3c984cb58ebbcc5e266525 | 523 | present-constructor | MIT License |
data/src/main/java/com/jslee/data/database/dao/BookmarkDao.kt | JaesungLeee | 675,525,103 | false | {"Kotlin": 278145} | package com.jslee.data.database.dao
import androidx.room.Dao
import androidx.room.Insert
import androidx.room.OnConflictStrategy
import androidx.room.Query
import com.jslee.data.database.entity.BookmarkEntity
import kotlinx.coroutines.flow.Flow
/**
* MooBeside
* @author jaesung
* @created 2023/11/03
*/
@Dao
internal interface BookmarkDao {
@Query("SELECT * FROM `moobeside_bookmark.db`")
fun getAllBookmarks(): Flow<List<BookmarkEntity>>
@Query(
"""SELECT * FROM `moobeside_bookmark.db` ORDER BY
CASE WHEN :filter = 0 THEN released_date END DESC,
CASE WHEN :filter = 1 THEN bookmarked_at END DESC,
CASE WHEN :filter = 2 THEN runtime END ASC
"""
)
fun getBookmarksByOrder(filter: Int): Flow<List<BookmarkEntity>>
@Query("DELETE FROM `moobeside_bookmark.db` WHERE movie_id = :movieId")
suspend fun deleteBookmark(movieId: Long)
@Insert(onConflict = OnConflictStrategy.REPLACE)
suspend fun saveBookmark(bookmark: BookmarkEntity)
@Query("SELECT EXISTS(SELECT * FROM `moobeside_bookmark.db` WHERE movie_id = :movieId)")
fun isBookmarked(movieId: Long): Flow<Boolean>
} | 10 | Kotlin | 0 | 2 | c7be8313aeda0a658a9db416845b9868ab2a8125 | 1,156 | MooBeside | MIT License |
data/src/main/java/com/andysklyarov/data/network/GetLatestDateTime/RequestLatestDateTime.kt | andysklyarov | 302,335,276 | false | null | package com.andysklyarov.data.network.GetLatestDateTime
import org.simpleframework.xml.*
@Root(name = "soap:Envelope")
@NamespaceList(
Namespace(prefix = "xsi", reference = "http://www.w3.org/2001/XMLSchema-instance"),
Namespace(prefix = "xsd", reference = "http://www.w3.org/2001/XMLSchema"),
Namespace(prefix = "soap", reference = "http://www.w3.org/2003/05/soap-envelope")
)
data class RequestLatestDateTimeEnvelope @JvmOverloads constructor(
@get:Element(name = "Body")
@set:Element(name = "Body")
@get:Namespace(reference = "http://www.w3.org/2003/05/soap-envelope", prefix = "soap")
@set:Namespace(reference = "http://www.w3.org/2003/05/soap-envelope", prefix = "soap")
var body: RequestLatestDateTimeBody? = null
)
@Root(name = "soap:Body")
data class RequestLatestDateTimeBody @JvmOverloads constructor(
@get:Element(name = "GetLatestDateTime")
@set:Element(name = "GetLatestDateTime")
var latestDateTimeData: RequestLatestDateTimeData? = null
)
@Root(name = "GetLatestDateTime")
data class RequestLatestDateTimeData @JvmOverloads constructor(
@get:Attribute(name = "xmlns")
@set:Attribute(name = "xmlns")
var xmlns: String? = "http://web.cbr.ru/"
) | 0 | Kotlin | 0 | 0 | eaf34377b13c056a8d8cea11c3c52e7e4867d0e7 | 1,217 | fin_notify | Apache License 2.0 |
app/src/main/java/com/github/mvpbasearchitecture/di/component/ApplicationComponent.kt | gauravk95 | 148,177,936 | false | null | /*
Copyright 2018 <NAME>
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package com.github.mvpbasearchitecture.di.component
import android.app.Application
import android.content.Context
import com.github.mvpbasearchitecture.base.MainApplication
import com.github.mvpbasearchitecture.data.source.repository.AppDataRepository
import com.github.mvpbasearchitecture.data.source.repository.AppRepository
import com.github.mvpbasearchitecture.di.ApplicationContext
import com.github.mvpbasearchitecture.di.module.ApplicationModule
import com.github.mvpbasearchitecture.di.module.DataModule
import com.github.mvpbasearchitecture.di.module.NetworkModule
import javax.inject.Singleton
import dagger.Component
/**
* Application component connecting modules that have application scope
*
* Created by gk
*/
@Singleton
@Component(modules = [ApplicationModule::class, DataModule::class, NetworkModule::class])
interface ApplicationComponent {
fun getAppRepository(): AppRepository
fun inject(app: MainApplication)
@ApplicationContext
fun context(): Context
fun application(): Application
}
| 0 | Kotlin | 0 | 7 | f27c9577292a9e87e1a89eb8b14f637440e79141 | 1,635 | mvp-kotlin-android | Apache License 2.0 |
presentation/src/main/kotlin/com/dvinc/workouttimer/presentation/ui/base/BaseViewModel.kt | DEcSENT | 121,128,412 | false | {"Kotlin": 86263, "Java": 1132} | /*
* Copyright (c) 2018 by <NAME> (<EMAIL>)
* All rights reserved.
*/
package com.dvinc.workouttimer.presentation.ui.base
import androidx.lifecycle.ViewModel
import io.reactivex.disposables.CompositeDisposable
import io.reactivex.disposables.Disposable
abstract class BaseViewModel : ViewModel() {
private val compositeDisposable by lazy { CompositeDisposable() }
fun addSubscription(disposable: Disposable) {
compositeDisposable.add(disposable)
}
override fun onCleared() {
super.onCleared()
compositeDisposable.clear()
}
}
| 0 | Kotlin | 1 | 3 | 716b9ff353e6e3a7ee9362431ce4d909e781db1c | 597 | WorkoutTimer | MIT License |
kgl-vulkan/src/nativeMain/kotlin/com/kgl/vulkan/enums/ShaderStage.kt | NikkyAI | 168,431,916 | true | {"Kotlin": 1894114, "C": 1742775} | /**
* Copyright [2019] [<NAME>]
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.kgl.vulkan.enums
import com.kgl.vulkan.utils.VkFlag
import cvulkan.*
actual enum class ShaderStage(override val value: VkShaderStageFlagBits) : VkFlag<ShaderStage> {
VERTEX(VK_SHADER_STAGE_VERTEX_BIT),
TESSELLATION_CONTROL(VK_SHADER_STAGE_TESSELLATION_CONTROL_BIT),
TESSELLATION_EVALUATION(VK_SHADER_STAGE_TESSELLATION_EVALUATION_BIT),
GEOMETRY(VK_SHADER_STAGE_GEOMETRY_BIT),
FRAGMENT(VK_SHADER_STAGE_FRAGMENT_BIT),
COMPUTE(VK_SHADER_STAGE_COMPUTE_BIT),
TASK_NV(VK_SHADER_STAGE_TASK_BIT_NV),
MESH_NV(VK_SHADER_STAGE_MESH_BIT_NV),
RAYGEN_NV(VK_SHADER_STAGE_RAYGEN_BIT_NV),
ANY_HIT_NV(VK_SHADER_STAGE_ANY_HIT_BIT_NV),
CLOSEST_HIT_NV(VK_SHADER_STAGE_CLOSEST_HIT_BIT_NV),
MISS_NV(VK_SHADER_STAGE_MISS_BIT_NV),
INTERSECTION_NV(VK_SHADER_STAGE_INTERSECTION_BIT_NV),
CALLABLE_NV(VK_SHADER_STAGE_CALLABLE_BIT_NV);
companion object {
private val enumLookUpMap: Map<UInt, ShaderStage> = enumValues<ShaderStage>().associateBy({
it.value
})
fun fromMultiple(value: VkShaderStageFlagBits): VkFlag<ShaderStage> = VkFlag(value)
fun from(value: VkShaderStageFlagBits): ShaderStage = enumLookUpMap[value]!!
}
}
| 0 | Kotlin | 0 | 0 | 51dfa8a4c655ff8bcf017d8d4a2eb660e14473ed | 1,752 | kgl | Apache License 2.0 |
src/main/java/kr/co/byrobot/petroneapi/BLE/PetroneBLECallback.kt | petrone | 113,386,485 | false | null | package kr.co.byrobot.petroneapi.BLE
import android.bluetooth.BluetoothGatt
import java.util.*
/**
* Created by byrobot on 2017. 9. 18..
*/
interface PetroneBLECallback {
fun onFailed( uuid: UUID ,msg: String) { }
fun onFailed(msg: String ) { }
//Callback triggered as a result of a remote characteristic notification.
//BluetoothGattCallback#onCharacteristicChanged --> onCharacteristicNotification
fun onCharacteristicNotification(uuid : UUID, data: ByteArray ) { }
//Callback reporting the result of a characteristic read operation.
//BluetoothGattCallback#onCharacteristicChanged
fun onCharacteristicRead(uuid: UUID, data: ByteArray ) { }
//Callback indicating the result of a characteristic write operation.
//BluetoothGattCallback#onCharacteristicWrite
fun onCharacteristicWrite(uuid: UUID, status: Int) { }
//Callback indicating when GATT client has connected/disconnected to/from a remote GATT server.
//BluetoothGattCallback#onConnectionStateChange
fun onConnectionStateChange(status: Int, newStatus: Int) { }
//Callback reporting the result of a descriptor read operation.
//BluetoothGattCallback#onDescriptorRead
fun onDescriptorRead(uuid: UUID, data: ByteArray) { }
//Callback indicating the result of a descriptor write operation.
//BluetoothGattCallback#onDescriptorWrite
fun onDescriptorWrite(uuid: UUID, status: Int)
{
}
//Callback indicating the MTU for a given device connection has changed.
//BluetoothGattCallback#onConnectionStateChange
fun onMtuChanged(mtu: Int, status: Int)
{
}
//Callback reporting the RSSI for a remote device connection.
//BluetoothGattCallback#onReadRemoteRssi
fun onReadRemoteRssi(rssi: Int, status: Int)
{
}
//Callback invoked when a reliable write transaction has been completed.
//BluetoothGattCallback#onReliableWriteCompleted
fun onReliableWriteCompleted(status: Int)
{
}
//Callback invoked when the list of remote services,
// characteristics and descriptors for the remote device have been updated,
// ie new services have been discovered.
//BluetoothGattCallback#onServicesDiscovered
fun onServicesDiscovered(gatt: BluetoothGatt?, status: Int)
{
}
} | 0 | Kotlin | 1 | 0 | 5a4d803057b97c322acead2cb8ad4e2dd413b3a5 | 2,301 | drone | MIT License |
features/generatepassword/generatepassword-api/src/commonMain/kotlin/io/spherelabs/generatepasswordapi/domain/usecase/InsertPasswordHistoryUseCase.kt | getspherelabs | 687,455,894 | false | {"Kotlin": 917584, "Ruby": 6814, "Swift": 1128, "Shell": 1048} | package io.spherelabs.generatepasswordapi.domain.usecase
interface InsertPasswordHistoryUseCase {
suspend fun execute(password: String, createdAt: Long)
}
| 18 | Kotlin | 24 | 188 | 902a0505c5eaf0f3848a5e06afaec98c1ed35584 | 160 | anypass-kmp | Apache License 2.0 |
src/main/kotlin/com/keygenqt/plugin/simple/language/SimpleLanguage.kt | keygenqt | 260,680,880 | false | {"Kotlin": 64490, "Lex": 2075, "Java": 764} | /*
* Copyright 2020 <NAME>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.keygenqt.plugin.simple.language
import com.intellij.lang.Language
class SimpleLanguage : Language("Simple") {
companion object {
val INSTANCE = SimpleLanguage()
}
} | 0 | Kotlin | 0 | 0 | a88b15a2589099ddd711c0d4fc62f241128787e2 | 794 | skill-kotlin-intellij-plugin-gradle | Apache License 2.0 |
examples/ethereum/bitcoinjexample/src/main/java/io/pixelplex/bitcoinjexample/ethereum_components/RLPList.kt | cryptoapi-project | 245,105,614 | false | null | package io.pixelplex.bitcoinjexample.ethereum_components
class RLPList(override var rlpData: ByteArray? = null) : ArrayList<RLPElement>(), RLPElement
interface RLPElement : java.io.Serializable {
val rlpData: ByteArray?
}
class RLPItem(data: ByteArray) : RLPElement {
override var rlpData: ByteArray? = data
get() = if (field?.size == 0) null else field
}
| 0 | Kotlin | 0 | 0 | 8362c0cd1fed18c67edbb7e98087beae0c023ac7 | 378 | cryptoapi-kotlin | MIT License |
kotlin-native/tools/performance-server/src/main/kotlin/database/DatabaseRequests.kt | JetBrains | 3,432,266 | false | {"Kotlin": 74444760, "Java": 6669398, "Swift": 4261253, "C": 2620837, "C++": 1953730, "Objective-C": 640870, "Objective-C++": 170766, "JavaScript": 135724, "Python": 48402, "Shell": 30960, "TypeScript": 22754, "Lex": 18369, "Groovy": 17273, "Batchfile": 11693, "CSS": 11368, "Ruby": 10470, "EJS": 5241, "Dockerfile": 5136, "HTML": 5073, "CMake": 4448, "Pascal": 1698, "FreeMarker": 1393, "Roff": 725, "LLVM": 395, "Scala": 80} | /*
* Copyright 2010-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license
* that can be found in the LICENSE file.
*/
package org.jetbrains.database
import kotlin.js.Promise
import org.jetbrains.elastic.*
import org.jetbrains.utils.*
import org.jetbrains.report.json.*
import org.jetbrains.report.*
// Delete build information from ES index.
internal fun deleteBuildInfo(agentInfo: String, buildInfoIndex: ElasticSearchIndex,
buildNumber: String? = null): Promise<String> {
val queryDescription = """
{
"query": {
"bool": {
"must": [
{ "match": { "agentInfo": "$agentInfo" } }
${buildNumber?.let {
""",
{"match": { "buildNumber": "$it" }}
"""
} ?: ""}
]
}
}
}
""".trimIndent()
return buildInfoIndex.delete(queryDescription)
}
// Get infromation about builds details from database.
internal fun getBuildsDescription(type: String?, branch: String?, agentInfo: String, buildInfoIndex: ElasticSearchIndex,
buildsCountToShow: Int, beforeDate: String?, afterDate: String?,
onlyNumbers: Boolean = false): Promise<JsonArray> {
val queryDescription = """
{ "size": $buildsCountToShow,
${if (onlyNumbers) """"_source": ["buildNumber", "buildType"],""" else ""}
"sort": {"startTime": "desc" },
"query": {
"bool": {
${type?.let {"""
"must": [
{ "bool": {
"should": [
{ "regexp": { "buildNumber": { "value": "${if (it == "release")
".*eap.*|.*release.*|.*rc.*" else ".*dev.*"}" } }
},
{ "match": { "buildType": "${it.uppercase()}" } }
]
}},
{ "bool": {
"""} ?: ""}
"must": [
{ "match": { "agentInfo": "$agentInfo" } }
${beforeDate?.let {
""",
{ "range": { "startTime": { "lt": "$it" } } }
"""
} ?: ""}
${afterDate?.let {
""",
{ "range": { "startTime": { "gt": "$it" } } }
"""
} ?: ""}
${branch?.let {
""",
{"match": { "branch": "$it" }}
"""
} ?: ""}
]
${type?.let {"""
}}]
"""}}
}
}
}
""".trimIndent()
return buildInfoIndex.search(queryDescription, listOf("hits.hits._source")).then { responseString ->
val dbResponse = JsonTreeParser.parse(responseString).jsonObject
dbResponse.getObjectOrNull("hits")?.getArrayOrNull("hits") ?: error("Wrong response:\n$responseString")
}
}
// Check if current build already exists.
suspend fun buildExists(buildInfo: BuildInfo, buildInfoIndex: ElasticSearchIndex): Boolean {
val queryDescription = """
{ "size": 1,
"_source": ["buildNumber"],
"query": {
"bool": {
"must": [
{ "match": { "buildNumber": "${buildInfo.buildNumber}" } },
{ "match": { "agentInfo": "${buildInfo.agentInfo}" } },
{ "match": { "branch": "${buildInfo.branch}" } }
]
}
}
}
""".trimIndent()
return buildInfoIndex.search(queryDescription, listOf("hits.total.value")).then { responseString ->
val response = JsonTreeParser.parse(responseString).jsonObject
val value = response.getObjectOrNull("hits")?.getObjectOrNull("total")?.getPrimitiveOrNull("value")?.content
?: error("Error response from ElasticSearch:\n$responseString")
value.toInt() > 0
}.await()
}
// Get builds numbers corresponding to machine and branch.
fun getBuildsNumbers(type: String?, branch: String?, agentInfo: String, buildsCountToShow: Int,
buildInfoIndex: ElasticSearchIndex, beforeDate: String? = null, afterDate: String? = null) =
getBuildsDescription(type, branch, agentInfo, buildInfoIndex, buildsCountToShow, beforeDate, afterDate, true)
.then { responseArray ->
responseArray.map {
val build = (it as JsonObject).getObject("_source")
build.getPrimitiveOrNull("buildType")?.content to build.getPrimitive("buildNumber").content
}
}
// Get full builds information corresponding to machine and branch.
fun getBuildsInfo(type: String?, branch: String?, agentInfo: String, buildsCountToShow: Int,
buildInfoIndex: ElasticSearchIndex, beforeDate: String? = null,
afterDate: String? = null) =
getBuildsDescription(type, branch, agentInfo, buildInfoIndex, buildsCountToShow, beforeDate, afterDate).then { responseArray ->
responseArray.map { BuildInfo.create((it as JsonObject).getObject("_source")) }
}
// Get golden results from database.
fun getGoldenResults(goldenResultsIndex: GoldenResultsIndex): Promise<Map<String, List<BenchmarkResult>>> {
return goldenResultsIndex.search("", listOf("hits.hits._source")).then { responseString ->
val dbResponse = JsonTreeParser.parse(responseString).jsonObject
dbResponse.getObjectOrNull("hits")?.getArrayOrNull("hits")?.map {
val reportDescription = (it as JsonObject).getObject("_source")
BenchmarksReport.create(reportDescription).benchmarks
}?.reduce { acc, it -> acc + it } ?: error("Wrong format of response:\n $responseString")
}
}
// Get list of unstable benchmarks from database.
fun getUnstableResults(goldenResultsIndex: GoldenResultsIndex): Promise<List<String>> {
val queryDescription = """
{
"_source": ["env"],
"query": {
"nested" : {
"path" : "benchmarks",
"query" : {
"match": { "benchmarks.unstable": true }
},
"inner_hits": {
"size": 100,
"_source": ["benchmarks.name"]
}
}
}
}
""".trimIndent()
return goldenResultsIndex.search(queryDescription, listOf("hits.hits.inner_hits")).then { responseString ->
val dbResponse = JsonTreeParser.parse(responseString).jsonObject
val results = dbResponse.getObjectOrNull("hits")?.getArrayOrNull("hits")
?: error("Wrong response:\n$responseString")
results.getObjectOrNull(0)?.let {
it
.getObject("inner_hits")
.getObject("benchmarks")
.getObject("hits")
.getArray("hits").map {
(it as JsonObject).getObject("_source").getPrimitive("name").content
}
} ?: listOf<String>()
}
}
// Get distinct values for needed field from database.
fun distinctValues(field: String, index: ElasticSearchIndex): Promise<List<String>> {
val queryDescription = """
{
"aggs": {
"unique": {"terms": {"field": "$field", "size": 1000}}
}
}
""".trimIndent()
return index.search(queryDescription, listOf("aggregations.unique.buckets")).then { responseString ->
val dbResponse = JsonTreeParser.parse(responseString).jsonObject
dbResponse.getObjectOrNull("aggregations")?.getObjectOrNull("unique")?.getArrayOrNull("buckets")
?.map { (it as JsonObject).getPrimitiveOrNull("key")?.content }?.filterNotNull()
?: error("Wrong response:\n$responseString")
}
} | 166 | Kotlin | 5,771 | 46,772 | bef0946ab7e5acd5b24b971eca532c43c8eba750 | 8,519 | kotlin | Apache License 2.0 |
plugins/fir-plugin-prototype/src/org/jetbrains/kotlin/fir/plugin/checkers/SignedNumberCallChecker.kt | JetBrains | 3,432,266 | false | {"Kotlin": 74444760, "Java": 6669398, "Swift": 4261253, "C": 2620837, "C++": 1953730, "Objective-C": 640870, "Objective-C++": 170766, "JavaScript": 135724, "Python": 48402, "Shell": 30960, "TypeScript": 22754, "Lex": 18369, "Groovy": 17273, "Batchfile": 11693, "CSS": 11368, "Ruby": 10470, "EJS": 5241, "Dockerfile": 5136, "HTML": 5073, "CMake": 4448, "Pascal": 1698, "FreeMarker": 1393, "Roff": 725, "LLVM": 395, "Scala": 80} | /*
* Copyright 2010-2021 JetBrains s.r.o. and Kotlin Programming Language contributors.
* Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file.
*/
package org.jetbrains.kotlin.fir.plugin.checkers
import org.jetbrains.kotlin.diagnostics.DiagnosticReporter
import org.jetbrains.kotlin.diagnostics.InternalDiagnosticFactoryMethod
import org.jetbrains.kotlin.diagnostics.reportOn
import org.jetbrains.kotlin.fir.analysis.checkers.context.CheckerContext
import org.jetbrains.kotlin.fir.analysis.checkers.expression.FirFunctionCallChecker
import org.jetbrains.kotlin.fir.expressions.FirFunctionCall
import org.jetbrains.kotlin.fir.expressions.resolvedArgumentMapping
import org.jetbrains.kotlin.fir.plugin.types.ConeNumberSignAttribute
import org.jetbrains.kotlin.fir.plugin.types.numberSign
import org.jetbrains.kotlin.fir.types.coneType
import org.jetbrains.kotlin.fir.types.resolvedType
object SignedNumberCallChecker : FirFunctionCallChecker() {
@OptIn(InternalDiagnosticFactoryMethod::class)
override fun check(expression: FirFunctionCall, context: CheckerContext, reporter: DiagnosticReporter) {
val argumentMapping = expression.resolvedArgumentMapping ?: return
for ((argument, parameter) in argumentMapping.entries) {
val expectedSign = parameter.returnTypeRef.coneType.attributes.numberSign ?: continue
val actualSign = argument.resolvedType.attributes.numberSign
if (expectedSign != actualSign) {
reporter.reportOn(
argument.source, PluginErrors.ILLEGAL_NUMBER_SIGN, expectedSign.asString(), actualSign.asString(), context
)
}
}
}
private fun ConeNumberSignAttribute?.asString(): String = when (this?.sign) {
null -> "None"
else -> sign.name
}
}
| 166 | Kotlin | 5,771 | 46,772 | bef0946ab7e5acd5b24b971eca532c43c8eba750 | 1,876 | kotlin | Apache License 2.0 |
app/src/main/java/com/vctapps/iddogchallenge/core/domain/DogCategory.kt | victor-vct | 128,567,034 | false | null | package com.vctapps.iddogchallenge.core.domain
object DogCategory {
val categories = arrayListOf(
"husky",
"labrador",
"hound",
"pug"
)
} | 1 | Kotlin | 0 | 1 | d55d8b42041ecad88fa65e789a8b8552e3397e83 | 180 | IDdogChallenge | Apache License 2.0 |
analysis/low-level-api-fir/testData/getOrBuildFirBinary/publishedApi/publishedApiFunction.kt | JetBrains | 3,432,266 | false | {"Kotlin": 74444760, "Java": 6669398, "Swift": 4261253, "C": 2620837, "C++": 1953730, "Objective-C": 640870, "Objective-C++": 170766, "JavaScript": 135724, "Python": 48402, "Shell": 30960, "TypeScript": 22754, "Lex": 18369, "Groovy": 17273, "Batchfile": 11693, "CSS": 11368, "Ruby": 10470, "EJS": 5241, "Dockerfile": 5136, "HTML": 5073, "CMake": 4448, "Pascal": 1698, "FreeMarker": 1393, "Roff": 725, "LLVM": 395, "Scala": 80} | // DECLARATION_TYPE: org.jetbrains.kotlin.psi.KtFunction
@PublishedApi
internal fun published() = "OK" | 166 | Kotlin | 5,771 | 46,772 | bef0946ab7e5acd5b24b971eca532c43c8eba750 | 102 | kotlin | Apache License 2.0 |
src/main/kotlin/com/xmartlabs/snapshotpublisher/model/FirebaseAppDistributionReleaseConfig.kt | xmartlabs | 166,051,318 | false | null | package com.xmartlabs.snapshotpublisher.model
open class FirebaseAppDistributionReleaseConfig {
var appId: String? = null
var distributionEmails: String? = null
var distributionGroupAliases: String? = null
var serviceAccountCredentials: String? = null
}
| 1 | Kotlin | 6 | 145 | d126731e5190fac0e2d49f73251d6bdbe983163e | 263 | android-snapshot-publisher | MIT License |
feature/session/src/main/java/io/github/droidkaigi/confsched2019/session/ui/TabularFormSessionPageFragment.kt | DroidKaigi | 143,598,291 | false | null | package io.github.droidkaigi.confsched2019.session.ui
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.databinding.DataBindingUtil
import androidx.lifecycle.Lifecycle
import androidx.navigation.NavController
import androidx.recyclerview.widget.RecyclerView
import com.xwray.groupie.GroupAdapter
import com.xwray.groupie.databinding.BindableItem
import com.xwray.groupie.databinding.ViewHolder
import dagger.Module
import dagger.Provides
import io.github.droidkaigi.confsched2019.ext.Dispatchers
import io.github.droidkaigi.confsched2019.ext.changed
import io.github.droidkaigi.confsched2019.ext.coroutineScope
import io.github.droidkaigi.confsched2019.model.ServiceSession
import io.github.droidkaigi.confsched2019.model.Session
import io.github.droidkaigi.confsched2019.model.SessionType
import io.github.droidkaigi.confsched2019.model.SpeechSession
import io.github.droidkaigi.confsched2019.session.R
import io.github.droidkaigi.confsched2019.session.databinding.FragmentTabularFormSessionPageBinding
import io.github.droidkaigi.confsched2019.session.di.SessionPageScope
import io.github.droidkaigi.confsched2019.session.ui.item.TabularServiceSessionItem
import io.github.droidkaigi.confsched2019.session.ui.item.TabularSpacerItem
import io.github.droidkaigi.confsched2019.session.ui.item.TabularSpeechSessionItem
import io.github.droidkaigi.confsched2019.session.ui.store.SessionContentsStore
import io.github.droidkaigi.confsched2019.session.ui.store.SessionPagesStore
import io.github.droidkaigi.confsched2019.session.ui.widget.DaggerFragment
import io.github.droidkaigi.confsched2019.session.ui.widget.TimetableCurrentTimeLabelDecoration
import io.github.droidkaigi.confsched2019.session.ui.widget.TimetableCurrentTimeLineDecoration
import io.github.droidkaigi.confsched2019.session.ui.widget.TimetableLayoutManager
import io.github.droidkaigi.confsched2019.session.ui.widget.TimetableLunchDecoration
import io.github.droidkaigi.confsched2019.session.ui.widget.TimetableRoomLabelDecoration
import io.github.droidkaigi.confsched2019.session.ui.widget.TimetableTimeLabelDecoration
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
import javax.inject.Inject
import javax.inject.Provider
class TabularFormSessionPageFragment : DaggerFragment() {
private lateinit var binding: FragmentTabularFormSessionPageBinding
@Inject lateinit var tabularSpeechSessionItemFactory: TabularSpeechSessionItem.Factory
@Inject lateinit var tabularServiceSessionItemFactory: TabularServiceSessionItem.Factory
@Inject lateinit var sessionPagesStoreProvider: Provider<SessionPagesStore>
@Inject lateinit var navController: NavController
@Inject lateinit var sessionContentsStore: SessionContentsStore
private lateinit var args: TabularFormSessionPagesFragmentArgs
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
binding = DataBindingUtil.inflate(
inflater,
R.layout.fragment_tabular_form_session_page,
container,
false
)
return binding.root
}
override fun onActivityCreated(savedInstanceState: Bundle?) {
super.onActivityCreated(savedInstanceState)
args = TabularFormSessionPagesFragmentArgs.fromBundle(arguments ?: Bundle())
val groupAdapter = GroupAdapter<ViewHolder<*>>()
binding.tabularFormSessionsRecycler.apply {
val timetableCurrentTimeLabelDecoration =
TimetableCurrentTimeLabelDecoration(context, groupAdapter)
val timetableCurrentTimeLineDecoration =
TimetableCurrentTimeLineDecoration(context, groupAdapter)
addItemDecoration(TimetableTimeLabelDecoration(context, groupAdapter))
addItemDecoration(TimetableRoomLabelDecoration(context, groupAdapter))
addItemDecoration(TimetableLunchDecoration(context, groupAdapter))
addItemDecoration(timetableCurrentTimeLabelDecoration)
layoutManager = TimetableLayoutManager(
resources.getDimensionPixelSize(R.dimen.tabular_form_column_width),
resources.getDimensionPixelSize(R.dimen.tabular_form_px_per_minute)
) { position ->
val item = groupAdapter.getItem(position)
when (item) {
is TabularSpeechSessionItem ->
TimetableLayoutManager.PeriodInfo(
item.session.startTime.unixMillisLong,
item.session.endTime.unixMillisLong,
item.session.room.sequentialNumber
)
is TabularServiceSessionItem ->
TimetableLayoutManager.PeriodInfo(
item.session.startTime.unixMillisLong,
item.session.endTime.unixMillisLong,
item.session.room.sequentialNumber
)
is TabularSpacerItem ->
TimetableLayoutManager.PeriodInfo(
item.startUnixMillis,
item.endUnixMillis,
item.room.sequentialNumber
)
else -> TimetableLayoutManager.PeriodInfo(0, 0, 0)
}
}
addOnScrollListener(
object : RecyclerView.OnScrollListener() {
override fun onScrollStateChanged(recyclerView: RecyclerView, newState: Int) {
val job = viewLifecycleOwner.coroutineScope.launch(Dispatchers.Main) {
delay(500)
removeItemDecoration(timetableCurrentTimeLabelDecoration)
removeItemDecoration(timetableCurrentTimeLineDecoration)
addItemDecoration(timetableCurrentTimeLineDecoration)
}
super.onScrollStateChanged(recyclerView, newState)
if (newState == RecyclerView.SCROLL_STATE_IDLE) {
job.start()
} else {
if (job.isActive) { job.cancel() }
removeItemDecoration(timetableCurrentTimeLabelDecoration)
removeItemDecoration(timetableCurrentTimeLineDecoration)
addItemDecoration(timetableCurrentTimeLabelDecoration)
}
}
}
)
adapter = groupAdapter
}
sessionContentsStore.sessionsByDay(args.day)
.changed(viewLifecycleOwner) { sessions ->
groupAdapter.update(fillGaps(sessions))
}
}
private fun fillGaps(sessions: List<Session>): List<BindableItem<*>> {
if (sessions.isEmpty()) return emptyList()
val sortedSessions = sessions.sortedBy { it.startTime.unixMillisLong }
val firstSessionStart = sortedSessions.first().startTime.unixMillisLong
val lastSessionEnd =
sortedSessions.maxBy { it.endTime.unixMillisLong }?.endTime?.unixMillisLong
?: return emptyList()
val rooms = sortedSessions.map { it.room }.distinct()
// FIXME: Add lunch sessions for all rooms to get lunch item view.
val lunchSession = sortedSessions.find {
(it as? ServiceSession)?.sessionType == SessionType.LUNCH
} as? ServiceSession
val sortedSessionsWithLunch = sortedSessions + rooms
.filter { it.id != lunchSession?.room?.id }
.mapNotNull { lunchSession?.copy(room = it) }
val filledItems = ArrayList<BindableItem<*>>()
rooms.forEach { room ->
val sessionsInSameRoom = sortedSessionsWithLunch
.sortedBy { it.startTime.unixMillisLong }
.filter { it.room == room }
sessionsInSameRoom.forEachIndexed { index, session ->
if (index == 0 && session.startTime.unixMillisLong > firstSessionStart)
filledItems.add(
TabularSpacerItem(
firstSessionStart,
session.startTime.unixMillisLong,
room
)
)
val navDirections = TabularFormSessionPagesFragmentDirections
.actionTabularFormToSessionDetail(session.id)
filledItems.add(
when (session) {
is SpeechSession ->
tabularSpeechSessionItemFactory.create(session, navDirections)
is ServiceSession ->
tabularServiceSessionItemFactory.create(session, navDirections)
}
)
if (index == sessionsInSameRoom.size - 1 &&
session.endTime.unixMillisLong < lastSessionEnd
) {
filledItems.add(
TabularSpacerItem(
session.endTime.unixMillisLong,
lastSessionEnd,
room
)
)
}
val nextSession = sessionsInSameRoom.getOrNull(index + 1) ?: return@forEachIndexed
if (session.endTime.unixMillisLong != nextSession.startTime.unixMillisLong)
filledItems.add(
TabularSpacerItem(
session.endTime.unixMillisLong,
nextSession.startTime.unixMillisLong,
room
)
)
}
}
return filledItems.sortedBy {
when (it) {
is TabularSpeechSessionItem -> it.session.startTime.unixMillisLong
is TabularServiceSessionItem -> it.session.startTime.unixMillisLong
is TabularSpacerItem -> it.startUnixMillis
else -> 0
}
}
}
companion object {
fun newInstance(args: TabularFormSessionPagesFragmentArgs): TabularFormSessionPageFragment {
return TabularFormSessionPageFragment()
.apply { arguments = args.toBundle() }
}
}
}
@Module
abstract class TabularFormSessionPageFragmentModule {
@Module
companion object {
@JvmStatic
@Provides
@SessionPageScope
fun providesLifecycle(
tabularFromSessionPageFragment: TabularFormSessionPageFragment
): Lifecycle {
return tabularFromSessionPageFragment.viewLifecycleOwner.lifecycle
}
}
}
| 43 | Kotlin | 276 | 823 | 839b6dca4780aac1746c819f7ca8af6100afcda8 | 10,973 | conference-app-2019 | Apache License 2.0 |
app/src/main/java/architex/labs/coffeedrop/presentation/components/CoffeeDetailsDisplay.kt | dev-xero | 634,526,820 | false | null | /**
* Copyright (C) [2023 - Present] - Xero
*
* 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 architex.labs.coffeedrop.presentation.components
import androidx.compose.foundation.Image
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.widthIn
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.unit.dp
import androidx.compose.ui.zIndex
import architex.labs.coffeedrop.R
@Composable
fun CoffeeDetailsDisplay(
modifier: Modifier = Modifier,
imageResID: Int,
titleRedID: Int,
variant: String,
ratings: Double,
reviews: Int,
coffeeType: String,
onBackButtonClicked: () -> Unit
) {
Column(
modifier = modifier
.fillMaxSize()
.padding(12.dp)
) {
Box(
modifier = Modifier.widthIn(max = 400.dp).height(440.dp)
) {
Column(
verticalArrangement = Arrangement.SpaceBetween,
modifier = Modifier
.zIndex(99f)
.height(452.dp)
) {
CoffeeDetailsTopRow(
icons = Pair(R.drawable.icon_arrow_left, R.drawable.icon_heart_filled),
onBackButtonClicked = onBackButtonClicked,
modifier = Modifier
.zIndex(99f)
.padding(8.dp)
)
CoffeeDetailsDisplayBottomRow(
titleResID = titleRedID,
variant = variant,
modifier = Modifier
.padding(8.dp),
ratings = ratings,
reviews = reviews,
coffeeType = coffeeType
)
}
Image(
painter = painterResource(id = imageResID),
contentDescription = stringResource(id = R.string.description_coffee_image),
contentScale = ContentScale.Crop,
modifier = Modifier
.clip(
RoundedCornerShape(
topStart = 24.dp,
topEnd = 24.dp,
bottomStart = 12.dp,
bottomEnd = 12.dp
)
)
.size(width = 400.dp, height = 460.dp)
)
}
}
} | 2 | Kotlin | 0 | 35 | 9990c094005abbad8ee56f2dd0d64c09ca940a00 | 2,878 | coffee-drop-ui | Apache License 2.0 |
features/add-story/src/main/java/com/mohfahmi/storyapp/add_story/AddStoryActivity.kt | MohFahmi27 | 535,535,970 | false | {"Kotlin": 147264} | package com.mohfahmi.storyapp.add_story
import android.Manifest
import android.annotation.SuppressLint
import android.content.Intent
import android.content.Intent.ACTION_GET_CONTENT
import android.graphics.BitmapFactory
import android.location.Geocoder
import android.net.Uri
import android.os.Bundle
import android.provider.MediaStore
import android.viewbinding.library.activity.viewBinding
import androidx.activity.result.ActivityResultLauncher
import androidx.activity.result.contract.ActivityResultContracts
import androidx.appcompat.app.AppCompatActivity
import androidx.core.content.FileProvider
import androidx.core.widget.doAfterTextChanged
import androidx.lifecycle.lifecycleScope
import com.google.android.gms.location.FusedLocationProviderClient
import com.google.android.gms.location.LocationServices
import com.mohfahmi.storyapp.add_story.databinding.ActivityAddStoryBinding
import com.mohfahmi.storyapp.core.R.drawable.img_photo_loading
import com.mohfahmi.storyapp.core.R.string.*
import com.mohfahmi.storyapp.core.common_ui.ErrorBottomSheetDialogFragment
import com.mohfahmi.storyapp.core.common_ui.LoadingDialogFragment
import com.mohfahmi.storyapp.core.domain.models.UploadStory
import com.mohfahmi.storyapp.core.utils.*
import com.shashank.sony.fancytoastlib.FancyToast
import com.vmadalin.easypermissions.EasyPermissions
import com.vmadalin.easypermissions.dialogs.SettingsDialog
import kotlinx.coroutines.launch
import org.koin.androidx.viewmodel.ext.android.viewModel
import java.io.File
import java.util.*
class AddStoryActivity : AppCompatActivity(), EasyPermissions.PermissionCallbacks {
private val binding: ActivityAddStoryBinding by viewBinding()
private val viewModel: AddStoryViewModel by viewModel()
private val loadingFragment: LoadingDialogFragment by lazy {
LoadingDialogFragment()
}
private lateinit var launcherIntentCamera: ActivityResultLauncher<Intent>
private lateinit var launcherIntentGallery: ActivityResultLauncher<Intent>
private lateinit var currentPhotoPath: String
private lateinit var fusedLocationProviderClient: FusedLocationProviderClient
private var myImgStory: File? = null
private var lat: Double? = null
private var lng: Double? = null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
fusedLocationProviderClient = LocationServices.getFusedLocationProviderClient(this)
initCameraIntent()
initGalleryIntent()
initViews()
}
private fun initViews() {
with(binding) {
btnCamera.setOnClickListener {
if (hasCameraPermission()) {
startCamera()
} else {
requestCameraPermission()
}
}
btnGallery.setOnClickListener {
if (hasStoragePermission()) {
startGallery()
} else {
requestStoragePermission()
}
}
btnLocateMe.setOnClickListener {
if (hasLocationPermission()) {
getLocation()
} else {
requestLocationPermission()
}
}
edAddDescription.doAfterTextChanged {
viewModel.descriptionValue.value = it.toString()
}
btnUpload.setOnClickListener {
val file = reduceFileImage(myImgStory as File)
uploadStory(edAddDescription.text.toString(), file)
}
lifecycleScope.launch {
viewModel.isUploadButtonEnable.collect {
btnUpload.isEnabled = it
}
}
}
}
private fun initCameraIntent() {
launcherIntentCamera = registerForActivityResult(
ActivityResultContracts.StartActivityForResult()
) { result ->
if (result.resultCode == RESULT_OK) {
val myFile = File(currentPhotoPath)
val bitmapResult = rotateBitmap(
BitmapFactory.decodeFile(myFile.path),
true
)
viewModel.isImagePicked.value = true
myImgStory = myFile
binding.imgStory.setImageBitmap(bitmapResult)
} else {
binding.imgStory.setImageResource(img_photo_loading)
}
}
}
private fun initGalleryIntent() {
launcherIntentGallery = registerForActivityResult(
ActivityResultContracts.StartActivityForResult()
) { result ->
if (result.resultCode == RESULT_OK) {
val selectedImg: Uri = result.data?.data as Uri
myImgStory = uriToFile(selectedImg, this)
viewModel.isImagePicked.value = true
binding.imgStory.setImageURI(selectedImg)
} else {
binding.imgStory.setImageResource(img_photo_loading)
}
}
}
private fun startGallery() {
val intent = Intent()
intent.action = ACTION_GET_CONTENT
intent.type = "image/*"
val chooser = Intent.createChooser(intent, "Choose a Picture")
launcherIntentGallery.launch(chooser)
}
@SuppressLint("QueryPermissionsNeeded")
private fun startCamera() {
val intent = Intent(MediaStore.ACTION_IMAGE_CAPTURE)
intent.resolveActivity(packageManager)
createCustomTempFile(application).also {
val photoURI: Uri = FileProvider.getUriForFile(
this,
"com.mohfahmi.storyapp",
it
)
currentPhotoPath = it.absolutePath
myImgStory = File(currentPhotoPath)
intent.putExtra(MediaStore.EXTRA_OUTPUT, photoURI)
launcherIntentCamera.launch(intent)
}
}
override fun onRequestPermissionsResult(
requestCode: Int,
permissions: Array<out String>,
grantResults: IntArray
) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults)
EasyPermissions.onRequestPermissionsResult(
requestCode,
permissions,
grantResults,
this
)
}
override fun onPermissionsDenied(requestCode: Int, perms: List<String>) {
if (EasyPermissions.somePermissionPermanentlyDenied(this, perms)) {
SettingsDialog.Builder(this).build().show()
}
}
override fun onPermissionsGranted(requestCode: Int, perms: List<String>) {
FancyToast.makeText(
this,
getString(permission_granted),
FancyToast.LENGTH_SHORT,
FancyToast.SUCCESS,
false
).show()
}
private fun hasCameraPermission() =
EasyPermissions.hasPermissions(this, Manifest.permission.CAMERA)
private fun requestCameraPermission() {
if (!hasCameraPermission()) {
EasyPermissions.requestPermissions(
this,
getString(permission_camera_request),
REQUEST_CAMERA_PERMISSION,
Manifest.permission.CAMERA
)
}
}
private fun requestStoragePermission() {
EasyPermissions.requestPermissions(
this,
getString(permission_storage_request),
REQUEST_STORAGE_PERMISSION,
Manifest.permission.READ_EXTERNAL_STORAGE
)
}
private fun hasStoragePermission() =
EasyPermissions.hasPermissions(this, Manifest.permission.READ_EXTERNAL_STORAGE)
private fun requestLocationPermission() {
EasyPermissions.requestPermissions(
this,
getString(permission_location_request),
REQUEST_LOCATION_PERMISSION,
Manifest.permission.ACCESS_COARSE_LOCATION,
Manifest.permission.ACCESS_FINE_LOCATION,
)
}
private fun hasLocationPermission() =
EasyPermissions.hasPermissions(
this,
Manifest.permission.ACCESS_COARSE_LOCATION,
Manifest.permission.ACCESS_FINE_LOCATION
)
private fun uploadStory(description: String, img: File) {
viewModel.token().observe(this) {
viewModel.uploadStory(it, description, img, lat, lng).observe(
this,
::manageUploadStoryResponse
)
}
}
@SuppressLint("MissingPermission")
private fun getLocation() {
fusedLocationProviderClient.lastLocation.addOnSuccessListener { location ->
location?.let {
lat = location.latitude
lng = location.longitude
binding.tvLatLon.text = getAddress(lat as Double, lng as Double)
}
}.addOnFailureListener {
FancyToast.makeText(
this,
it.message,
FancyToast.LENGTH_SHORT,
FancyToast.ERROR,
false
)
}
}
private fun manageUploadStoryResponse(uiState: UiState<UploadStory>) {
when (uiState.status) {
Status.LOADING -> {
loadingFragment.show(supportFragmentManager, LoadingDialogFragment.TAG)
}
Status.HIDE_LOADING -> {
loadingFragment.dismiss()
}
Status.SUCCESS -> {
FancyToast.makeText(
this@AddStoryActivity,
getString(upload_story_success),
FancyToast.LENGTH_SHORT,
FancyToast.SUCCESS,
false
).show()
finish()
}
Status.ERROR -> {
ErrorBottomSheetDialogFragment(
uiState.message ?: getString(something_went_wrong)
).show(supportFragmentManager, ErrorBottomSheetDialogFragment.TAG)
}
}
}
private fun getAddress(latitude: Double, longitude: Double): String {
val myGeoCoder = Geocoder(this, Locale.getDefault())
val getAddress = myGeoCoder.getFromLocation(latitude, longitude, 1)
return getAddress[0].getAddressLine(0)
}
companion object {
private const val REQUEST_CAMERA_PERMISSION = 1
private const val REQUEST_STORAGE_PERMISSION = 2
private const val REQUEST_LOCATION_PERMISSION = 3
}
} | 0 | Kotlin | 0 | 3 | 33e94844c52da1ad24f68e204dc0e220d564c4c4 | 10,495 | MyIntermediateAndroidSubmission | Apache License 2.0 |