path
stringlengths 4
280
| owner
stringlengths 2
39
| repo_id
int64 21.1k
879M
| is_fork
bool 2
classes | languages_distribution
stringlengths 13
1.95k
⌀ | content
stringlengths 7
482k
| issues
int64 0
13.9k
| main_language
stringclasses 121
values | forks
stringlengths 1
5
| stars
int64 0
111k
| commit_sha
stringlengths 40
40
| size
int64 7
482k
| name
stringlengths 1
100
| license
stringclasses 93
values |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|
EvoMaster/core/src/main/kotlin/org/evomaster/core/search/gene/sql/SqlUUIDGene.kt | BrotherKim | 397,139,860 | false | null | package org.evomaster.core.search.gene.sql
import org.evomaster.core.output.OutputFormat
import org.evomaster.core.search.EvaluatedIndividual
import org.evomaster.core.search.gene.Gene
import org.evomaster.core.search.gene.GeneUtils
import org.evomaster.core.search.gene.LongGene
import org.evomaster.core.search.impact.GeneImpact
import org.evomaster.core.search.impact.GeneMutationSelectionMethod
import org.evomaster.core.search.impact.sql.SqlUUIDGeneImpact
import org.evomaster.core.search.service.AdaptiveParameterControl
import org.evomaster.core.search.service.Randomness
import org.evomaster.core.search.service.mutator.geneMutation.ArchiveMutator
import org.slf4j.Logger
import org.slf4j.LoggerFactory
import java.util.*
/**
* The data type uuid stores Universally Unique Identifiers (UUID) as defined by RFC 4122, ISO/IEC 9834-8:2005,
* and related standards. (Some systems refer to this data type as a globally unique identifier, or GUID, instead.)
*
* https://www.postgresql.org/docs/9.1/datatype-uuid.html
*/
class SqlUUIDGene(
name: String,
val mostSigBits: LongGene = LongGene("mostSigBits", 0L),
val leastSigBits: LongGene = LongGene("leastSigBits", 0L)
) : Gene(name) {
override fun copy(): Gene = SqlUUIDGene(
name,
mostSigBits.copy() as LongGene,
leastSigBits.copy() as LongGene
)
companion object{
private val log: Logger = LoggerFactory.getLogger(SqlUUIDGene::class.java)
}
override fun randomize(randomness: Randomness, forceNewValue: Boolean, allGenes: List<Gene>) {
mostSigBits.randomize(randomness, forceNewValue, allGenes)
leastSigBits.randomize(randomness, forceNewValue, allGenes)
}
override fun standardMutation(randomness: Randomness, apc: AdaptiveParameterControl, allGenes: List<Gene>) {
val gene = randomness.choose(listOf(mostSigBits, leastSigBits))
gene.standardMutation(randomness, apc, allGenes)
}
override fun getValueAsPrintableString(previousGenes: List<Gene>, mode: GeneUtils.EscapeMode?, targetFormat: OutputFormat?): String {
return "\"${getValueAsRawString()}\""
}
override fun getValueAsRawString(): String {
// https://www.postgresql.org/docs/9.1/datatype-uuid.html
return getValueAsUUID().toString()
}
fun getValueAsUUID(): UUID = UUID(mostSigBits.value, leastSigBits.value)
override fun copyValueFrom(other: Gene) {
if (other !is SqlUUIDGene) {
throw IllegalArgumentException("Invalid gene type ${other.javaClass}")
}
this.mostSigBits.copyValueFrom(other.mostSigBits)
this.leastSigBits.copyValueFrom(other.leastSigBits)
}
override fun containsSameValueAs(other: Gene): Boolean {
if (other !is SqlUUIDGene) {
throw IllegalArgumentException("Invalid gene type ${other.javaClass}")
}
return this.mostSigBits.containsSameValueAs(other.mostSigBits)
&& this.leastSigBits.containsSameValueAs(other.leastSigBits)
}
override fun flatView(excludePredicate: (Gene) -> Boolean): List<Gene> {
return if (excludePredicate(this)) listOf(this) else
listOf(this).plus(mostSigBits.flatView(excludePredicate))
.plus(leastSigBits.flatView(excludePredicate))
}
override fun archiveMutation(randomness: Randomness, allGenes: List<Gene>, apc: AdaptiveParameterControl, selection: GeneMutationSelectionMethod, impact: GeneImpact?, geneReference: String, archiveMutator: ArchiveMutator, evi: EvaluatedIndividual<*>, targets: Set<Int>) {
if (!archiveMutator.enableArchiveMutation()){
standardMutation(randomness, apc, allGenes)
return
}
var genes : List<Pair<Gene, GeneImpact>>? = null
val selects = if (archiveMutator.applyArchiveSelection() && impact != null && impact is SqlUUIDGeneImpact){
genes = listOf(
Pair(leastSigBits, impact.leastSigBitsImpact),
Pair(leastSigBits , impact.mostSigBitsImpact)
)
archiveMutator.selectGenesByArchive(genes, 1.0/2, targets)
}else
listOf(leastSigBits, leastSigBits)
val selected = randomness.choose(if (selects.isNotEmpty()) selects else listOf(leastSigBits, leastSigBits))
val selectedImpact = genes?.first { it.first == selected }?.second
selected.archiveMutation(randomness, allGenes, apc, selection, selectedImpact, geneReference, archiveMutator, evi, targets)
}
override fun archiveMutationUpdate(original: Gene, mutated: Gene, doesCurrentBetter: Boolean, archiveMutator: ArchiveMutator) {
if (archiveMutator.enableArchiveGeneMutation()){
if (original !is SqlUUIDGene){
log.warn("original ({}) should be SqlUUIDGene", original::class.java.simpleName)
return
}
if (mutated !is SqlUUIDGene){
log.warn("mutated ({}) should be SqlUUIDGene", mutated::class.java.simpleName)
return
}
if (!mutated.leastSigBits.containsSameValueAs(original.leastSigBits)){
leastSigBits.archiveMutationUpdate(original.leastSigBits, mutated.leastSigBits, doesCurrentBetter, archiveMutator)
}
if (!mutated.mostSigBits.containsSameValueAs(original.mostSigBits)){
mostSigBits.archiveMutationUpdate(original.mostSigBits, mutated.mostSigBits, doesCurrentBetter, archiveMutator)
}
}
}
override fun reachOptimal(): Boolean {
return leastSigBits.reachOptimal() && mostSigBits.reachOptimal()
}
} | 1 | null | 1 | 1 | a7a120fe7c3b63ae370e8a114f3cb71ef79c287e | 5,705 | ASE-Technical-2021-api-linkage-replication | MIT License |
app/src/main/java/com/apiguave/tinderclonecompose/ui/di/PresentationModule.kt | alejandro-piguave | 567,907,964 | false | {"Kotlin": 190150, "Java": 427} | package com.apiguave.tinderclonecompose.ui.di
import com.apiguave.tinderclonecompose.ui.chat.ChatViewModel
import com.apiguave.tinderclonecompose.ui.editprofile.EditProfileViewModel
import com.apiguave.tinderclonecompose.ui.home.HomeViewModel
import com.apiguave.tinderclonecompose.ui.login.LoginViewModel
import com.apiguave.tinderclonecompose.ui.matchlist.MatchListViewModel
import com.apiguave.tinderclonecompose.ui.newmatch.NewMatchViewModel
import com.apiguave.tinderclonecompose.ui.signup.SignUpViewModel
import org.koin.androidx.viewmodel.dsl.viewModel
import org.koin.dsl.module
val presentationModule = module {
//View models
viewModel { ChatViewModel(get()) }
viewModel { NewMatchViewModel(get()) }
viewModel { EditProfileViewModel(get(), get()) }
viewModel { SignUpViewModel(get(), get()) }
viewModel { LoginViewModel(get()) }
viewModel { HomeViewModel(get(), get()) }
viewModel { MatchListViewModel(get()) }
} | 1 | Kotlin | 7 | 21 | f30af595c58dea07ca329b70289d1e45a2b19a98 | 956 | TinderCloneCompose | MIT License |
postgresql/src/main/kotlin/io/github/clasicrando/kdbc/postgresql/query/PgAsyncPreparedQueryBatch.kt | ClasicRando | 722,364,579 | false | null | package io.github.clasicrando.kdbc.postgresql.query
import io.github.clasicrando.kdbc.core.query.BaseAsyncPreparedQueryBatch
import io.github.clasicrando.kdbc.core.result.StatementResult
import io.github.clasicrando.kdbc.postgresql.connection.PgAsyncConnection
/**
* Postgresql implementation of a [io.github.clasicrando.kdbc.core.connection.AsyncConnection].
* Uses query pipelining to execute all prepared statements as a pipeline to optimize round trips
* to the server. This allows for sending multiple prepared queries at once to the server, so you
* do not need to wait for previous queries to complete to request another result.
*
* ```
* Regular Pipelined
* | Client | Server | | Client | Server |
* |----------------|-----------------| |----------------|-----------------|
* | send query 1 | | | send query 1 | |
* | | process query 1 | | send query 2 | process query 1 |
* | receive rows 1 | | | send query 3 | process query 2 |
* | send query 2 | | | receive rows 1 | process query 3 |
* | | process query 2 | | receive rows 2 | |
* | receive rows 2 | | | receive rows 3 | |
* | send query 3 | |
* | | process query 3 |
* | receive rows 3 | |
* ```
*
* This can reduce server round trips, however there is one limitation to this client's
* implementation of query pipelining. Currently, the client takes an all or nothing approach
* where sync messages are sent after each query (instructing an autocommit by the server
* unless already in an open transaction) by default. To override this behaviour, allowing all
* statements after the failed one to be skipped and all previous statement changes to be
* rolled back, change the [syncAll] parameter to false.
*
* If you are sure each one of your statements do not impact each other and can be handled in
* separate transactions, keep the [syncAll] as default and catch exception thrown during
* query execution. Alternatively, you can also manually begin a transaction using
* [io.github.clasicrando.kdbc.core.connection.AsyncConnection.begin] and handle the
* transaction state of your connection yourself. In that case, any sync message sent to the server
* does not cause implicit transactional behaviour.
*
* @see PgAsyncConnection.pipelineQueries
*/
internal class PgAsyncPreparedQueryBatch(
connection: PgAsyncConnection,
) : BaseAsyncPreparedQueryBatch<PgAsyncConnection>(connection) {
/** Sync all parameter provided to the [PgAsyncConnection.pipelineQueries] method */
var syncAll: Boolean = true
override suspend fun vendorExecuteQueriesAggregating(): StatementResult {
checkNotNull(connection) { "QueryBatch already released its Connection" }
val pipelineQueries = Array(queries.size) {
queries[it].sql to queries[it].parameters
}
return connection!!.pipelineQueries(syncAll = syncAll, queries = pipelineQueries)
}
}
| 5 | null | 0 | 9 | 08679d4d012e1a1eea1564bd290129a7dc3f0c0b | 3,151 | kdbc | Apache License 2.0 |
androidApp/src/androidMain/kotlin/ru/mironov/logistics/MainScreen.kt | mironoff2007 | 655,211,419 | false | {"Kotlin": 212030, "Ruby": 1788, "Swift": 708, "Shell": 228} | package ru.mironov.logistics
import NavRoot
import androidx.activity.compose.BackHandler
import androidx.compose.foundation.isSystemInDarkTheme
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.material.MaterialTheme
import androidx.compose.material.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.DisposableEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.text.AnnotatedString
import androidx.compose.ui.text.TextStyle
import androidx.compose.ui.unit.sp
import com.google.accompanist.systemuicontroller.rememberSystemUiController
import com.mironov.di.ApplicationComponent
import com.mironov.localization.StringRes
import ru.mironov.common.res.localizedString
import ru.mironov.common.ui.theme.LogisticsTheme
import ru.mironov.logistics.ui.navigation.Navigator
import ru.mironov.logistics.ui.theme.Main
import ru.mironov.logistics.ui.theme.MainDark
@Composable
fun MainScreen() {
val darkTheme = isSystemInDarkTheme()
val useDarkIcons = false
val barColor = if (darkTheme) MainDark else Main
val systemUiController = rememberSystemUiController()
DisposableEffect(systemUiController, useDarkIcons) {
systemUiController.setSystemBarsColor(
color = barColor,
darkIcons = useDarkIcons
)
onDispose {}
}
LogisticsTheme(darkTheme = darkTheme) {
var onBackPressed by remember { mutableStateOf<(() -> Unit)?>(null) }
val backPressed = fun(callBack: () -> Unit) {
onBackPressed = callBack
}
BackHandler {
onBackPressed?.invoke()
onBackPressed = null
}
var grantedWrite by remember { mutableStateOf(false) }
val grantWriteFlagSwitch = fun() {
grantedWrite = true
}
requestWrite(grantWriteFlagSwitch)
var grantedRead by remember { mutableStateOf(false) }
val grantReadFlagSwitch = fun() {
grantedRead = true
}
if (grantedWrite) requestRead(grantReadFlagSwitch)
if (grantedRead && grantedWrite) {
val navigator = Navigator()
NavRoot(navigator, ApplicationComponent.getVmFactory(), backPressed)
} else {
Box(
modifier = Modifier.fillMaxSize(),
contentAlignment = Alignment.Center
) {
Text(
text = AnnotatedString(localizedString(StringRes.RequestPermissions)),
style = TextStyle(
fontFamily = MaterialTheme.typography.h4.fontFamily,
fontSize = 25.sp,
color = MaterialTheme.colors.onSurface
),
)
}
}
}
} | 0 | Kotlin | 0 | 0 | ab59c3db6305a56606b33325261459cca54df547 | 3,053 | logistics_kmm | Apache License 2.0 |
src/main/kotlin/intellij/riot/lang/v3/Riot3FileTypeFactory.kt | Munyola | 198,312,722 | true | {"Kotlin": 33561, "Lex": 6940} | package intellij.riot.lang.v3
import com.intellij.openapi.fileTypes.FileTypeConsumer
import com.intellij.openapi.fileTypes.FileTypeFactory
/**
* File type factories are deprecated but we want to keep it for 2019.1 compatibility
*/
class Riot3FileTypeFactory : FileTypeFactory() {
override fun createFileTypes(consumer: FileTypeConsumer) {
consumer.consume(Riot3HtmlFileType.INSTANCE, "tag")
}
} | 1 | Kotlin | 0 | 0 | 09eabfaccfc18e71ae72ffa98ccf92703739edd9 | 414 | intellij-riot.js | Apache License 2.0 |
src/test/code/de/tuchemnitz/se/exercise/core/configmanager/ConfigManagerTest.kt | xsoophx | 306,648,914 | false | null | package de.tuchemnitz.se.exercise.core.configmanager
import assertk.assertThat
import assertk.assertions.isEqualTo
import assertk.assertions.isNull
import com.mongodb.client.FindIterable
import de.tuchemnitz.se.exercise.DummyData
import de.tuchemnitz.se.exercise.persist.configs.CodeChartsConfig
import de.tuchemnitz.se.exercise.persist.configs.EyeTrackingConfig
import de.tuchemnitz.se.exercise.persist.configs.collections.CodeChartsConfigCollection
import io.kotest.matchers.shouldBe
import io.mockk.every
import io.mockk.mockk
import io.mockk.verify
import javafx.scene.input.KeyCode
import org.bson.BsonDocument
import org.junit.jupiter.api.AfterEach
import org.junit.jupiter.api.BeforeEach
import org.junit.jupiter.api.Test
import org.junit.jupiter.api.assertDoesNotThrow
import java.nio.file.Files
import java.nio.file.Path
import java.util.stream.Stream
class ConfigManagerTest {
private val mockedCollection = mockk<CodeChartsConfigCollection>()
companion object {
@JvmStatic
@Suppress("unused")
fun validPaths(): Stream<Path> = Stream.of(
Path.of("test.txt"),
Path.of("dummy.cfg"),
Path.of("./foo.conf"),
Path.of("../born.json"),
Files.createTempFile("", ".conf")
)
}
@Test
fun `comparing db and file content should work`() { // file content empty, file different from DB, file like DB
DummyData.configManager.checkDBSimilarity()
}
@Test
fun `writing to invalid path does not work`() {
val testPath = Path.of("bull/shit.txt")
assertDoesNotThrow {
DummyData.configManager.writeFileNoThrow(testPath)
}
}
@Test
fun `reading from invalid path does not work`() {
val testPath = Path.of("bull/shit.txt")
assertDoesNotThrow {
assertThat(DummyData.configManager.readFile(testPath)).isNull()
}
}
@Test
fun `invoking of get function of a config out of db by id should work`() {
}
@Test
fun `invoking of save function of a config into the db should work`() {
val mockedResult = mockk<FindIterable<CodeChartsConfig>>()
every { mockedCollection.find(any()) } returns mockedResult
mockedCollection.find(BsonDocument()) shouldBe mockedResult
verify { mockedCollection.find(any()) }
}
@Test
fun `invoking of saving functions of config should work`() {
}
@BeforeEach
fun setup() {
DummyData.codeChartsConfigs.forEach {
DummyData.codeChartsConfigCollection.saveOne(it)
}
DummyData.zoomMapsData.forEach {
DummyData.zoomMapsDataCollection.saveOne(it)
}
DummyData.zoomMapsConfigs().forEach {
DummyData.zoomMapsConfigCollection.saveOne(it)
}
}
@AfterEach
fun tearDown() {
DummyData.codeChartsConfigCollection.deleteMany()
DummyData.zoomMapsConfigCollection.deleteMany()
DummyData.zoomMapsDataCollection.deleteMany()
}
@Test
fun `assembling all database configs should work`() { // integration test
val recentZoomConfig = mostRecentZoomMapsData
val keyCode = recentZoomConfig?.zoomKey ?: KeyCode.C
val zoomImage = recentZoomConfig?.imagePath ?: ""
val zoomSpeed = recentZoomConfig?.zoomSpeed ?: 1.0
val expected = ToolConfigs(
codeChartsConfig = mostRecentCodeChartsConfig,
zoomMapsConfig = ConfigFileZoomMaps(
keyBindings = KeyBindings(
up = keyCode,
down = keyCode,
left = keyCode,
right = keyCode,
inKey = keyCode,
out = keyCode
),
pictures = listOf(ZoomInformation(name = zoomImage, zoomSpeed = zoomSpeed))
),
// TODO
eyeTrackingConfig = EyeTrackingConfig(pictures = emptyList()),
// TODO
bubbleViewConfig = BubbleViewConfig(
filter = setOf(
FilterInformation(
name = "", filter = Filter(
gradient = 1, type = "gaussianBlur"
)
)
)
)
)
val actual = DummyData.configManager.assembleAllConfigurations()
.copy(
eyeTrackingConfig = expected.eyeTrackingConfig,
bubbleViewConfig = expected.bubbleViewConfig
)
assertThat(actual).isEqualTo(expected)
}
private val mostRecentCodeChartsConfig =
DummyData.codeChartsConfigs.maxByOrNull { it.savedAt }
private val mostRecentZoomMapsData =
DummyData.zoomMapsData.maxByOrNull { it.savedAt }
}
| 0 | Kotlin | 2 | 2 | 2e33158921e2a6d8e0aeed77a3d12994e9f36609 | 4,826 | SoftwareEngineering | MIT License |
kt/godot-library/src/main/kotlin/godot/gen/godot/GLTFState.kt | utopia-rise | 289,462,532 | false | null | // THIS FILE IS GENERATED! DO NOT EDIT IT MANUALLY!
@file:Suppress("PackageDirectoryMismatch", "unused", "FunctionName", "RedundantModalityModifier",
"UNCHECKED_CAST", "JoinDeclarationAndAssignment", "USELESS_CAST",
"RemoveRedundantQualifierName", "NOTHING_TO_INLINE")
package godot
import godot.`annotation`.GodotBaseType
import godot.core.Dictionary
import godot.core.PoolByteArray
import godot.core.TransferContext
import godot.core.VariantArray
import godot.core.VariantType.ARRAY
import godot.core.VariantType.BOOL
import godot.core.VariantType.DICTIONARY
import godot.core.VariantType.LONG
import godot.core.VariantType.NIL
import godot.core.VariantType.OBJECT
import godot.core.VariantType.POOL_BYTE_ARRAY
import godot.core.VariantType.STRING
import kotlin.Any
import kotlin.Boolean
import kotlin.Long
import kotlin.String
import kotlin.Suppress
import kotlin.Unit
@GodotBaseType
public open class GLTFState : Resource() {
public open var accessors: VariantArray<Any?>
get() {
TransferContext.writeArguments()
TransferContext.callMethod(rawPtr, ENGINEMETHOD_ENGINECLASS_GLTFSTATE_GET_ACCESSORS, ARRAY)
return TransferContext.readReturnValue(ARRAY, false) as VariantArray<Any?>
}
set(`value`) {
TransferContext.writeArguments(ARRAY to value)
TransferContext.callMethod(rawPtr, ENGINEMETHOD_ENGINECLASS_GLTFSTATE_SET_ACCESSORS, NIL)
}
public open var animations: VariantArray<Any?>
get() {
TransferContext.writeArguments()
TransferContext.callMethod(rawPtr, ENGINEMETHOD_ENGINECLASS_GLTFSTATE_GET_ANIMATIONS, ARRAY)
return TransferContext.readReturnValue(ARRAY, false) as VariantArray<Any?>
}
set(`value`) {
TransferContext.writeArguments(ARRAY to value)
TransferContext.callMethod(rawPtr, ENGINEMETHOD_ENGINECLASS_GLTFSTATE_SET_ANIMATIONS, NIL)
}
public open var bufferViews: VariantArray<Any?>
get() {
TransferContext.writeArguments()
TransferContext.callMethod(rawPtr, ENGINEMETHOD_ENGINECLASS_GLTFSTATE_GET_BUFFER_VIEWS, ARRAY)
return TransferContext.readReturnValue(ARRAY, false) as VariantArray<Any?>
}
set(`value`) {
TransferContext.writeArguments(ARRAY to value)
TransferContext.callMethod(rawPtr, ENGINEMETHOD_ENGINECLASS_GLTFSTATE_SET_BUFFER_VIEWS, NIL)
}
public open var buffers: VariantArray<Any?>
get() {
TransferContext.writeArguments()
TransferContext.callMethod(rawPtr, ENGINEMETHOD_ENGINECLASS_GLTFSTATE_GET_BUFFERS, ARRAY)
return TransferContext.readReturnValue(ARRAY, false) as VariantArray<Any?>
}
set(`value`) {
TransferContext.writeArguments(ARRAY to value)
TransferContext.callMethod(rawPtr, ENGINEMETHOD_ENGINECLASS_GLTFSTATE_SET_BUFFERS, NIL)
}
public open var cameras: VariantArray<Any?>
get() {
TransferContext.writeArguments()
TransferContext.callMethod(rawPtr, ENGINEMETHOD_ENGINECLASS_GLTFSTATE_GET_CAMERAS, ARRAY)
return TransferContext.readReturnValue(ARRAY, false) as VariantArray<Any?>
}
set(`value`) {
TransferContext.writeArguments(ARRAY to value)
TransferContext.callMethod(rawPtr, ENGINEMETHOD_ENGINECLASS_GLTFSTATE_SET_CAMERAS, NIL)
}
public open var glbData: PoolByteArray
get() {
TransferContext.writeArguments()
TransferContext.callMethod(rawPtr, ENGINEMETHOD_ENGINECLASS_GLTFSTATE_GET_GLB_DATA,
POOL_BYTE_ARRAY)
return TransferContext.readReturnValue(POOL_BYTE_ARRAY, false) as PoolByteArray
}
set(`value`) {
TransferContext.writeArguments(POOL_BYTE_ARRAY to value)
TransferContext.callMethod(rawPtr, ENGINEMETHOD_ENGINECLASS_GLTFSTATE_SET_GLB_DATA, NIL)
}
public open var images: VariantArray<Any?>
get() {
TransferContext.writeArguments()
TransferContext.callMethod(rawPtr, ENGINEMETHOD_ENGINECLASS_GLTFSTATE_GET_IMAGES, ARRAY)
return TransferContext.readReturnValue(ARRAY, false) as VariantArray<Any?>
}
set(`value`) {
TransferContext.writeArguments(ARRAY to value)
TransferContext.callMethod(rawPtr, ENGINEMETHOD_ENGINECLASS_GLTFSTATE_SET_IMAGES, NIL)
}
public open var json: Dictionary<Any?, Any?>
get() {
TransferContext.writeArguments()
TransferContext.callMethod(rawPtr, ENGINEMETHOD_ENGINECLASS_GLTFSTATE_GET_JSON, DICTIONARY)
return TransferContext.readReturnValue(DICTIONARY, false) as Dictionary<Any?, Any?>
}
set(`value`) {
TransferContext.writeArguments(DICTIONARY to value)
TransferContext.callMethod(rawPtr, ENGINEMETHOD_ENGINECLASS_GLTFSTATE_SET_JSON, NIL)
}
public open var lights: VariantArray<Any?>
get() {
TransferContext.writeArguments()
TransferContext.callMethod(rawPtr, ENGINEMETHOD_ENGINECLASS_GLTFSTATE_GET_LIGHTS, ARRAY)
return TransferContext.readReturnValue(ARRAY, false) as VariantArray<Any?>
}
set(`value`) {
TransferContext.writeArguments(ARRAY to value)
TransferContext.callMethod(rawPtr, ENGINEMETHOD_ENGINECLASS_GLTFSTATE_SET_LIGHTS, NIL)
}
public open var majorVersion: Long
get() {
TransferContext.writeArguments()
TransferContext.callMethod(rawPtr, ENGINEMETHOD_ENGINECLASS_GLTFSTATE_GET_MAJOR_VERSION, LONG)
return TransferContext.readReturnValue(LONG, false) as Long
}
set(`value`) {
TransferContext.writeArguments(LONG to value)
TransferContext.callMethod(rawPtr, ENGINEMETHOD_ENGINECLASS_GLTFSTATE_SET_MAJOR_VERSION, NIL)
}
public open var materials: VariantArray<Any?>
get() {
TransferContext.writeArguments()
TransferContext.callMethod(rawPtr, ENGINEMETHOD_ENGINECLASS_GLTFSTATE_GET_MATERIALS, ARRAY)
return TransferContext.readReturnValue(ARRAY, false) as VariantArray<Any?>
}
set(`value`) {
TransferContext.writeArguments(ARRAY to value)
TransferContext.callMethod(rawPtr, ENGINEMETHOD_ENGINECLASS_GLTFSTATE_SET_MATERIALS, NIL)
}
public open var meshes: VariantArray<Any?>
get() {
TransferContext.writeArguments()
TransferContext.callMethod(rawPtr, ENGINEMETHOD_ENGINECLASS_GLTFSTATE_GET_MESHES, ARRAY)
return TransferContext.readReturnValue(ARRAY, false) as VariantArray<Any?>
}
set(`value`) {
TransferContext.writeArguments(ARRAY to value)
TransferContext.callMethod(rawPtr, ENGINEMETHOD_ENGINECLASS_GLTFSTATE_SET_MESHES, NIL)
}
public open var minorVersion: Long
get() {
TransferContext.writeArguments()
TransferContext.callMethod(rawPtr, ENGINEMETHOD_ENGINECLASS_GLTFSTATE_GET_MINOR_VERSION, LONG)
return TransferContext.readReturnValue(LONG, false) as Long
}
set(`value`) {
TransferContext.writeArguments(LONG to value)
TransferContext.callMethod(rawPtr, ENGINEMETHOD_ENGINECLASS_GLTFSTATE_SET_MINOR_VERSION, NIL)
}
public open var nodes: VariantArray<Any?>
get() {
TransferContext.writeArguments()
TransferContext.callMethod(rawPtr, ENGINEMETHOD_ENGINECLASS_GLTFSTATE_GET_NODES, ARRAY)
return TransferContext.readReturnValue(ARRAY, false) as VariantArray<Any?>
}
set(`value`) {
TransferContext.writeArguments(ARRAY to value)
TransferContext.callMethod(rawPtr, ENGINEMETHOD_ENGINECLASS_GLTFSTATE_SET_NODES, NIL)
}
public open var rootNodes: VariantArray<Any?>
get() {
TransferContext.writeArguments()
TransferContext.callMethod(rawPtr, ENGINEMETHOD_ENGINECLASS_GLTFSTATE_GET_ROOT_NODES, ARRAY)
return TransferContext.readReturnValue(ARRAY, false) as VariantArray<Any?>
}
set(`value`) {
TransferContext.writeArguments(ARRAY to value)
TransferContext.callMethod(rawPtr, ENGINEMETHOD_ENGINECLASS_GLTFSTATE_SET_ROOT_NODES, NIL)
}
public open var sceneName: String
get() {
TransferContext.writeArguments()
TransferContext.callMethod(rawPtr, ENGINEMETHOD_ENGINECLASS_GLTFSTATE_GET_SCENE_NAME, STRING)
return TransferContext.readReturnValue(STRING, false) as String
}
set(`value`) {
TransferContext.writeArguments(STRING to value)
TransferContext.callMethod(rawPtr, ENGINEMETHOD_ENGINECLASS_GLTFSTATE_SET_SCENE_NAME, NIL)
}
public open var skeletonToNode: Dictionary<Any?, Any?>
get() {
TransferContext.writeArguments()
TransferContext.callMethod(rawPtr, ENGINEMETHOD_ENGINECLASS_GLTFSTATE_GET_SKELETON_TO_NODE,
DICTIONARY)
return TransferContext.readReturnValue(DICTIONARY, false) as Dictionary<Any?, Any?>
}
set(`value`) {
TransferContext.writeArguments(DICTIONARY to value)
TransferContext.callMethod(rawPtr, ENGINEMETHOD_ENGINECLASS_GLTFSTATE_SET_SKELETON_TO_NODE,
NIL)
}
public open var skeletons: VariantArray<Any?>
get() {
TransferContext.writeArguments()
TransferContext.callMethod(rawPtr, ENGINEMETHOD_ENGINECLASS_GLTFSTATE_GET_SKELETONS, ARRAY)
return TransferContext.readReturnValue(ARRAY, false) as VariantArray<Any?>
}
set(`value`) {
TransferContext.writeArguments(ARRAY to value)
TransferContext.callMethod(rawPtr, ENGINEMETHOD_ENGINECLASS_GLTFSTATE_SET_SKELETONS, NIL)
}
public open var skins: VariantArray<Any?>
get() {
TransferContext.writeArguments()
TransferContext.callMethod(rawPtr, ENGINEMETHOD_ENGINECLASS_GLTFSTATE_GET_SKINS, ARRAY)
return TransferContext.readReturnValue(ARRAY, false) as VariantArray<Any?>
}
set(`value`) {
TransferContext.writeArguments(ARRAY to value)
TransferContext.callMethod(rawPtr, ENGINEMETHOD_ENGINECLASS_GLTFSTATE_SET_SKINS, NIL)
}
public open var textures: VariantArray<Any?>
get() {
TransferContext.writeArguments()
TransferContext.callMethod(rawPtr, ENGINEMETHOD_ENGINECLASS_GLTFSTATE_GET_TEXTURES, ARRAY)
return TransferContext.readReturnValue(ARRAY, false) as VariantArray<Any?>
}
set(`value`) {
TransferContext.writeArguments(ARRAY to value)
TransferContext.callMethod(rawPtr, ENGINEMETHOD_ENGINECLASS_GLTFSTATE_SET_TEXTURES, NIL)
}
public open var uniqueAnimationNames: VariantArray<Any?>
get() {
TransferContext.writeArguments()
TransferContext.callMethod(rawPtr,
ENGINEMETHOD_ENGINECLASS_GLTFSTATE_GET_UNIQUE_ANIMATION_NAMES, ARRAY)
return TransferContext.readReturnValue(ARRAY, false) as VariantArray<Any?>
}
set(`value`) {
TransferContext.writeArguments(ARRAY to value)
TransferContext.callMethod(rawPtr,
ENGINEMETHOD_ENGINECLASS_GLTFSTATE_SET_UNIQUE_ANIMATION_NAMES, NIL)
}
public open var uniqueNames: VariantArray<Any?>
get() {
TransferContext.writeArguments()
TransferContext.callMethod(rawPtr, ENGINEMETHOD_ENGINECLASS_GLTFSTATE_GET_UNIQUE_NAMES, ARRAY)
return TransferContext.readReturnValue(ARRAY, false) as VariantArray<Any?>
}
set(`value`) {
TransferContext.writeArguments(ARRAY to value)
TransferContext.callMethod(rawPtr, ENGINEMETHOD_ENGINECLASS_GLTFSTATE_SET_UNIQUE_NAMES, NIL)
}
public open var useNamedSkinBinds: Boolean
get() {
TransferContext.writeArguments()
TransferContext.callMethod(rawPtr,
ENGINEMETHOD_ENGINECLASS_GLTFSTATE_GET_USE_NAMED_SKIN_BINDS, BOOL)
return TransferContext.readReturnValue(BOOL, false) as Boolean
}
set(`value`) {
TransferContext.writeArguments(BOOL to value)
TransferContext.callMethod(rawPtr,
ENGINEMETHOD_ENGINECLASS_GLTFSTATE_SET_USE_NAMED_SKIN_BINDS, NIL)
}
public override fun __new(): Unit {
callConstructor(ENGINECLASS_GLTFSTATE)
}
public open fun getAnimationPlayer(idx: Long): AnimationPlayer? {
TransferContext.writeArguments(LONG to idx)
TransferContext.callMethod(rawPtr, ENGINEMETHOD_ENGINECLASS_GLTFSTATE_GET_ANIMATION_PLAYER,
OBJECT)
return TransferContext.readReturnValue(OBJECT, true) as AnimationPlayer?
}
public open fun getAnimationPlayersCount(idx: Long): Long {
TransferContext.writeArguments(LONG to idx)
TransferContext.callMethod(rawPtr,
ENGINEMETHOD_ENGINECLASS_GLTFSTATE_GET_ANIMATION_PLAYERS_COUNT, LONG)
return TransferContext.readReturnValue(LONG, false) as Long
}
public open fun getSceneNode(idx: Long): Node? {
TransferContext.writeArguments(LONG to idx)
TransferContext.callMethod(rawPtr, ENGINEMETHOD_ENGINECLASS_GLTFSTATE_GET_SCENE_NODE, OBJECT)
return TransferContext.readReturnValue(OBJECT, true) as Node?
}
}
| 47 | Kotlin | 25 | 301 | 0d33ac361b354b26c31bb36c7f434e6455583738 | 12,533 | godot-kotlin-jvm | MIT License |
app/src/main/java/dev/sijanrijal/note/viewmodels/SignupFragmentViewModel.kt | sijanr | 285,038,101 | false | null | package dev.sijanrijal.note.viewmodels
import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import com.google.firebase.auth.FirebaseAuth
import dev.sijanrijal.note.*
import timber.log.Timber
class SignupFragmentViewModel : ViewModel() {
private val _isSignUpSuccessful = MutableLiveData<Boolean>()
val isSignUpSuccessful: LiveData<Boolean>
get() = _isSignUpSuccessful
var errorMessage = ""
/**
* Authenticate a new user sign up process and if the authentication is successful, send a
* verification email to the user. If there was an issue validating user's email or password
* display the error message
* **/
fun onSignUpClicked(email: String?, password: String?) {
if (checkEmailPasswordValidity(email, password)) {
FirebaseAuth.getInstance().createUserWithEmailAndPassword(email!!, password!!)
.addOnCompleteListener { task ->
if (task.isSuccessful) {
Timber.d("onComplete: AuthState: ${FirebaseAuth.getInstance().currentUser?.uid}")
sendVerificationEmail()
FirebaseAuth.getInstance().signOut()
} else {
Timber.d("onComplete : task not successful")
errorMessage = ACCOUNT_SIGNUP_FAIL
_isSignUpSuccessful.value = false
}
}
} else {
errorMessage = VALIDITY_FAIL
_isSignUpSuccessful.value = false
}
}
/**
* Send a verification email to the new registered user
* **/
private fun sendVerificationEmail() {
val firebaseUser = FirebaseAuth.getInstance().currentUser
firebaseUser?.let { user ->
user.sendEmailVerification()
.addOnCompleteListener { task ->
_isSignUpSuccessful.value = task.isSuccessful
if (!task.isSuccessful) {
errorMessage = VERIFY_MESSAGE_ERROR
_isSignUpSuccessful.value = false
}
}
}
}
} | 0 | Kotlin | 0 | 0 | c7512252349f553bd024ead45af1d029c25ad383 | 2,215 | Note | Apache License 2.0 |
walletlibrary/src/main/java/com/microsoft/walletlibrary/networking/entities/openid4vci/credentialmetadata/SignedMetadataTokenClaims.kt | microsoft | 567,422,889 | false | {"Kotlin": 1363558} | package com.microsoft.walletlibrary.networking.entities.openid4vci.credentialmetadata
import com.microsoft.walletlibrary.util.TokenValidationException
import com.microsoft.walletlibrary.util.VerifiedIdExceptions
import kotlinx.serialization.Serializable
@Serializable
data class SignedMetadataTokenClaims(
val sub: String?,
val iat: String?,
val exp: String? = null,
val iss: String?,
val nbf: String? = null
) {
fun validateSignedMetadataTokenClaims(expectedSubject: String, expectedIssuer: String) {
validateSubject(expectedSubject)
validateIssuer(expectedIssuer)
validateIssuedAtTime()
validateExpiryTime()
}
private fun validateIssuer(expectedIssuer: String) {
if (iss == null) {
throw TokenValidationException(
"Issuer property missing in signed metadata.",
VerifiedIdExceptions.INVALID_PROPERTY_EXCEPTION.value
)
}
if (iss != expectedIssuer) {
throw TokenValidationException(
"Invalid issuer property in signed metadata.",
VerifiedIdExceptions.INVALID_PROPERTY_EXCEPTION.value
)
}
}
private fun validateSubject(expectedSubject: String) {
if (sub == null) {
throw TokenValidationException(
"Subject property missing in signed metadata.",
VerifiedIdExceptions.INVALID_PROPERTY_EXCEPTION.value
)
}
if (sub != expectedSubject) {
throw TokenValidationException(
"Invalid subject property in signed metadata.",
VerifiedIdExceptions.INVALID_PROPERTY_EXCEPTION.value
)
}
}
private fun validateIssuedAtTime() {
if (iat != null && iat.toLong() >= getCurrentTimeInSecondsWithSkew()) {
throw TokenValidationException(
"Issued at time is in the future.",
VerifiedIdExceptions.INVALID_PROPERTY_EXCEPTION.value
)
}
}
private fun validateExpiryTime() {
if (exp != null && exp.toLong() <= getCurrentTimeInSecondsWithSkew()) {
throw TokenValidationException(
"Token has expired.",
VerifiedIdExceptions.INVALID_PROPERTY_EXCEPTION.value
)
}
}
private fun getCurrentTimeInSecondsWithSkew(skew: Long = 300): Long {
return (System.currentTimeMillis() / 1000) + skew
}
} | 11 | Kotlin | 8 | 20 | 10881fd0cad0613cfc2194c12eeda0b26f2cd801 | 2,499 | entra-verifiedid-wallet-library-android | MIT License |
src/test/kotlin/util/PathfindingTest.kt | bjdupuis | 435,570,912 | false | {"Kotlin": 498025} | package util
import org.hamcrest.MatcherAssert
import org.hamcrest.core.Is.`is`
import org.junit.Test
class PathfindingTest {
val input = """
....OOO.O...
..S.O.OOOO..
..OOOO.O.E..
..O..OOO....
..OOOO......
""".trimIndent().lines()
@Test
fun `test that the pathfinder can do a dfs`() {
val pathfinding = Pathfinding<Point2d>()
val map = CharArray2d(input)
val path = pathfinding.dfs(
map.findFirst('S')!!,
Point2d::neighbors,
{ point -> point.isWithin(map) && map[point] != '.' }) { map[it] == 'E' }
MatcherAssert.assertThat(path.last(), `is`(Point2d(9, 2)))
MatcherAssert.assertThat(path.size, `is`(19))
}
@Test
fun `test that the pathfinder can do a bfs`() {
val pathfinding = Pathfinding<Point2d>()
val map = CharArray2d(input)
val path = pathfinding.bfs(
map.findFirst('S')!!,
Point2d::neighbors,
{ point -> point.isWithin(map) && map[point] != '.' }) { map[it] == 'E' }
MatcherAssert.assertThat(path.last(), `is`(Point2d(9, 2)))
MatcherAssert.assertThat(path.size, `is`(13))
}
@Test
fun `test that the pathfinder can do a bfs with diagonals`() {
val pathfinding = Pathfinding<Point2d>()
val map = CharArray2d(input)
val path = pathfinding.bfs(
map.findFirst('S')!!,
Point2d::allNeighbors,
{ point -> point.isWithin(map) && map[point] != '.' }) { map[it] == 'E' }
MatcherAssert.assertThat(path.last(), `is`(Point2d(9, 2)))
MatcherAssert.assertThat(path.size, `is`(8))
}
} | 0 | Kotlin | 0 | 1 | 8da2d31224769546a559280c47a13461a4f1e0a0 | 1,654 | Advent-Of-Code | Creative Commons Zero v1.0 Universal |
react-table-kotlin/src/jsMain/kotlin/tanstack/table/core/TableMeta.kt | karakum-team | 393,199,102 | false | {"Kotlin": 6272741} | // Automatically generated - do not modify!
package tanstack.table.core
external interface TableMeta<TData : RowData>
| 0 | Kotlin | 8 | 36 | 95b065622a9445caf058ad2581f4c91f9e2b0d91 | 120 | types-kotlin | Apache License 2.0 |
app/src/main/java/com/vpr/scheduleapp/presentation/SearchBar.kt | v1p3rrr | 544,626,284 | false | {"Kotlin": 70700} | package com.vpr.scheduleapp.presentation
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Search
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.Icon
import androidx.compose.material3.OutlinedTextField
import androidx.compose.material3.Text
import androidx.compose.runtime.*
import androidx.compose.ui.Modifier
@OptIn(ExperimentalMaterial3Api::class) //todo should i use some alternative??
@Composable
fun SearchBar(onQueryChange: (String) -> Unit, modifier: Modifier = Modifier) {
var queryState by remember { mutableStateOf("") }
OutlinedTextField(
value = queryState,
label = {
Text("Поиск")
},
onValueChange = {
queryState = it
onQueryChange(queryState)
},
singleLine = true,
leadingIcon = { Icon(Icons.Filled.Search, contentDescription = "Search Icon") },
modifier = modifier.fillMaxWidth(0.9f)
)
} | 0 | Kotlin | 0 | 1 | 3cd08a8424b5e613f3ab9c7c915b386a4d685d56 | 1,059 | ScheduleApp | MIT License |
autotracker-gradle-plugin/saas-gradle-plugin/src/main/kotlin/com/growingio/android/plugin/util/FilterUtils.kt | growingio | 486,100,482 | false | {"Kotlin": 393664, "Java": 22282, "Shell": 243} | /*
* Copyright (c) 2022 Beijing Yishu Technology Co., 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 com.growingio.android.plugin.util
import com.growingio.android.plugin.SaasAutoTrackerExtension
import com.growingio.android.plugin.hook.HookClassesConfig
/**
* <p>
*
* @author cpacm 2022/3/30
*/
internal fun shouldClassModified(
excludePackages: Array<String>, includePackages: Array<String>,
className: String
): Boolean {
if (isAndroidGenerated(className)) {
return false
}
includePackages.forEach {
if (className.startsWith(it)) {
return true
}
}
excludePackages.forEach {
if (className.startsWith(it)) {
return false
}
}
INCLUDED_PACKAGES.forEach {
if (className.startsWith(it)) {
return true
}
}
EXCLUDED_PACKAGES.forEach {
if (className.startsWith(it)) {
return false
}
}
return true
}
val INCLUDED_PACKAGES = arrayListOf(
"com.growingio.android.sdk.collection"
)
val EXCLUDED_PACKAGES = arrayListOf(
"com.growingio.android",
"com.growingio.giokit",
//"com.alibaba.mobileim.extra.xblink.webview",
//"com.alibaba.sdk.android.feedback.xblink",
//"com.tencent.smtt",
//"android.taobao.windvane.webview",
"com.sensorsdata.analytics", //sensorsdata
"com.blueware.agent.android", //bluware
"com.oneapm.agent.android", //OneAPM
"com.networkbench.agent",//tingyun
// OFFICIAL
//"androidx",
//"android.support",
//"org.jetbrains.kotlin",
"android.arch",
"androidx.lifecycle.ReportFragment",
//"androidx.navigation.fragment.NavHostFragment",
//"com.google.android",
//THIRD
"com.bumptech.glide",
"io.rectivex.rxjava",
"com.baidu.location",
"com.qiyukf",
"com.tencent.smtt",
"com.umeng.message",
"com.xiaomi.push",
"com.huawei.hms",
"cn.jpush.android",
"cn.jiguang",
"com.meizu.cloud.pushsdk",
"com.vivo.push",
"com.igexin",
"com.getui",
"com.xiaomi.mipush.sdk",
"com.heytap.msp.push",
"com.tencent.tinker",
"com.amap.api",
"com.google.iot",
//ignore RN 6.0 fragment page
"com.swmansion.rnscreens.ScreenFragment",
"com.swmansion.rnscreens.ScreenStackFragment",
)
val DEFAULT_INJECT_CLASS = arrayListOf(
"com.growingio.android.sdk.autotrack.inject.ActivityInjector",
"com.growingio.android.sdk.autotrack.inject.DialogInjector",
"com.growingio.android.sdk.autotrack.inject.FragmentInjector",
"com.growingio.android.sdk.autotrack.inject.FragmentV4Injector",
"com.growingio.android.sdk.autotrack.inject.MenuItemInjector",
"com.growingio.android.sdk.autotrack.inject.UcWebViewInjector",
"com.growingio.android.sdk.autotrack.inject.WebViewInjector",
"com.growingio.android.sdk.autotrack.inject.X5WebViewInjector",
"com.growingio.android.sdk.autotrack.inject.ViewClickInjector",
"com.growingio.android.sdk.autotrack.inject.ViewChangeInjector",
"com.growingio.android.sdk.autotrack.inject.WebChromeClientInjector",
"com.growingio.android.sdk.autotrack.inject.WindowShowInjector",
)
fun initInjectClass(extension: SaasAutoTrackerExtension) {
extension.injectClasses?.let {
DEFAULT_INJECT_CLASS.addAll(it)
}
with("com.growingio.android.sdk.plugin.rn.ReactNativeInjector") {
if (extension.enableRn) DEFAULT_INJECT_CLASS.add(this)
else DEFAULT_INJECT_CLASS.remove(this)
}
HookClassesConfig.initDefaultInjector(DEFAULT_INJECT_CLASS)
}
| 0 | Kotlin | 3 | 8 | 522d428d3739215f90473d647ee3939334037df7 | 4,116 | growingio-sdk-android-plugin | Apache License 2.0 |
app/src/main/java/kz/sozdik/di/modules/ApplicationModule.kt | sozdik-kz | 290,830,901 | false | null | package kz.sozdik.di.modules
import android.content.ClipboardManager
import android.content.Context
import android.preference.PreferenceManager
import com.akexorcist.localizationactivity.core.LocalizationContext
import dagger.Module
import dagger.Provides
import kz.sozdik.core.system.PrefsManager
@Module
object ApplicationModule {
@Provides
fun provideApplicationContext(context: Context): LocalizationContext = LocalizationContext(context)
@Provides
fun provideSharedPreferences(context: Context): PrefsManager =
PrefsManager(PreferenceManager.getDefaultSharedPreferences(context))
@Provides
fun provideClipboardManager(context: Context): ClipboardManager =
context.getSystemService(Context.CLIPBOARD_SERVICE) as ClipboardManager
} | 5 | Kotlin | 5 | 43 | cfbdffe47253c14ec75d0fba166d1077e028328c | 779 | sozdik-android | MIT License |
localtools/src/main/kotlin/tech/figure/classification/asset/localtools/feign/FeignUtil.kt | FigureTechnologies | 595,870,607 | false | null | package tech.figure.classification.asset.localtools.feign
import com.fasterxml.jackson.databind.ObjectMapper
import feign.Feign
import feign.Logger
import feign.Request
import feign.Response
import feign.RetryableException
import feign.Retryer
import feign.codec.ErrorDecoder
import feign.jackson.JacksonDecoder
import feign.jackson.JacksonEncoder
import tech.figure.classification.asset.util.objects.ACObjectMapperUtil
import java.util.concurrent.TimeUnit
object FeignUtil {
private val OBJECT_MAPPER by lazy { ACObjectMapperUtil.getObjectMapper() }
private const val RETRY_MS: Long = 120000L
private const val CONNECTION_TIMEOUT_SECONDS: Long = 1L
private const val READ_TIMEOUT_SECONDS: Long = 60L
fun getBuilder(mapper: ObjectMapper = OBJECT_MAPPER): Feign.Builder = Feign.builder()
.options(
Request.Options(
// Connection timeout
CONNECTION_TIMEOUT_SECONDS,
// Connection timeout unit
TimeUnit.SECONDS,
// Read timeout
READ_TIMEOUT_SECONDS,
// Read timeout unit
TimeUnit.SECONDS,
// Follow redirects
true
)
)
.logLevel(Logger.Level.BASIC)
.logger(FeignAppLogger())
.retryer(Retryer.Default(500, RETRY_MS, 10))
.decode404()
.encoder(JacksonEncoder(mapper))
.decoder(JacksonDecoder(mapper))
.errorDecoder(FeignErrorDecoder())
private class FeignAppLogger : Logger() {
override fun log(configKey: String?, format: String?, vararg args: Any?) {
println(String.format(methodTag(configKey) + format, *args))
}
}
private class FeignErrorDecoder : ErrorDecoder.Default() {
override fun decode(methodKey: String, response: Response?): Exception = when (response?.status()) {
502 -> retryableException(response, "502: Bad Gateway")
503 -> retryableException(response, "503: Service Unavailable")
504 -> retryableException(response, "504: Gateway Timeout")
else -> super.decode(methodKey, response)
}
private fun retryableException(response: Response, message: String): RetryableException = RetryableException(
// Status code
response.status(),
// Exception message
message,
// Request HTTP Method
response.request().httpMethod(),
// Retry after Date (set to null to indicate no retries)
null,
// Source request
response.request()
)
}
}
| 5 | Kotlin | 0 | 0 | d0eb720d750dc1ece826afab1d461f3b6d40a423 | 2,658 | group-member-approval-smart-contract | Apache License 2.0 |
app/src/main/java/com/denysnovoa/nzbmanager/radarr/movie/release/view/mapper/MovieReleaseViewMapper.kt | denysnovoa | 90,066,913 | false | null | package com.denysnovoa.nzbmanager.radarr.movie.release.view.mapper
import com.denysnovoa.nzbmanager.radarr.movie.release.repository.model.MovieReleaseModel
import com.denysnovoa.nzbmanager.radarr.movie.release.view.model.MovieReleaseViewModel
interface MovieReleaseViewMapper {
fun transform(movieRelease: List<MovieReleaseModel>): List<MovieReleaseViewModel>
fun transform(movieRelease: MovieReleaseModel): MovieReleaseViewModel
fun transform(movieRelease: MovieReleaseViewModel): MovieReleaseModel
}
| 0 | Kotlin | 0 | 1 | 8944e3bae4c073856f9856bf2e5064a6dadde4f7 | 518 | radarrsonarr | Apache License 2.0 |
app/src/main/java/com/anytypeio/anytype/di/feature/multiplayer/ShareSpaceInject.kt | anyproto | 647,371,233 | false | null | package com.anytypeio.anytype.di.feature.multiplayer
import androidx.lifecycle.ViewModelProvider
import com.anytypeio.anytype.core_utils.di.scope.PerDialog
import com.anytypeio.anytype.core_utils.di.scope.PerScreen
import com.anytypeio.anytype.di.common.ComponentDependencies
import com.anytypeio.anytype.domain.auth.repo.AuthRepository
import com.anytypeio.anytype.domain.base.AppCoroutineDispatchers
import com.anytypeio.anytype.domain.block.repo.BlockRepository
import com.anytypeio.anytype.domain.config.ConfigStorage
import com.anytypeio.anytype.domain.library.StorelessSubscriptionContainer
import com.anytypeio.anytype.domain.misc.UrlBuilder
import com.anytypeio.anytype.domain.multiplayer.UserPermissionProvider
import com.anytypeio.anytype.domain.workspace.SpaceManager
import com.anytypeio.anytype.presentation.multiplayer.ShareSpaceViewModel
import com.anytypeio.anytype.ui.multiplayer.ShareSpaceFragment
import dagger.Binds
import dagger.BindsInstance
import dagger.Component
import dagger.Module
@Component(
dependencies = [ShareSpaceDependencies::class],
modules = [
ShareSpaceModule::class,
ShareSpaceModule.Declarations::class
]
)
@PerDialog
interface ShareSpaceComponent {
@Component.Builder
interface Builder {
fun withDependencies(dependencies: ShareSpaceDependencies): Builder
@BindsInstance
fun withParams(params: ShareSpaceViewModel.Params): Builder
fun build(): ShareSpaceComponent
}
fun inject(fragment: ShareSpaceFragment)
}
@Module
object ShareSpaceModule {
@Module
interface Declarations {
@PerScreen
@Binds
fun bindViewModelFactory(factory: ShareSpaceViewModel.Factory): ViewModelProvider.Factory
}
}
interface ShareSpaceDependencies : ComponentDependencies {
fun blockRepository(): BlockRepository
fun auth() : AuthRepository
fun urlBuilder(): UrlBuilder
fun spaceManager(): SpaceManager
fun dispatchers(): AppCoroutineDispatchers
fun container(): StorelessSubscriptionContainer
fun config(): ConfigStorage
fun permissions(): UserPermissionProvider
} | 45 | null | 43 | 528 | c708958dcb96201ab7bb064c838ffa8272d5f326 | 2,128 | anytype-kotlin | RSA Message-Digest License |
src/main/kotlin/organization/p3/FileC.kt | softbluecursoscode | 603,710,984 | false | null | package somepackage
fun c1() {
println("c1()")
}
| 0 | null | 2 | 5 | d9d3b179af5fcf851947fe59fe4e13a825532417 | 54 | kotlin | MIT License |
zircon.core/src/commonMain/kotlin/org/hexworks/zircon/internal/component/renderer/DefaultParagraphRenderer.kt | Hexworks | 94,116,947 | false | null | package org.hexworks.zircon.internal.component.renderer
import org.hexworks.zircon.api.component.renderer.ComponentRenderContext
import org.hexworks.zircon.api.component.renderer.ComponentRenderer
import org.hexworks.zircon.api.graphics.TextWrap
import org.hexworks.zircon.api.graphics.TextWrap.WORD_WRAP
import org.hexworks.zircon.api.graphics.impl.DrawWindow
import org.hexworks.zircon.internal.component.impl.DefaultParagraph
class DefaultParagraphRenderer(
private val textWrap: TextWrap = WORD_WRAP
) : ComponentRenderer<DefaultParagraph> {
override fun render(drawWindow: DrawWindow, context: ComponentRenderContext<DefaultParagraph>) {
drawWindow.fillWithText(context.component.text, context.currentStyle, textWrap)
}
}
| 42 | null | 138 | 738 | 55a0ccc19a3f1b80aecd5f1fbe859db94ba9c0c6 | 750 | zircon | Apache License 2.0 |
acra-core/src/main/java/org/acra/builder/ReportExecutor.kt | ACRA | 5,890,835 | false | {"Kotlin": 396263, "MDX": 42827, "Java": 16527, "JavaScript": 5285, "CSS": 1328, "Shell": 199} | /*
* Copyright (c) 2017
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.acra.builder
import android.content.Context
import android.os.Debug
import android.os.Looper
import android.os.StrictMode
import android.widget.Toast
import org.acra.ACRAConstants
import org.acra.ReportField
import org.acra.config.CoreConfiguration
import org.acra.config.ReportingAdministrator
import org.acra.data.CrashReportData
import org.acra.data.CrashReportDataFactory
import org.acra.file.CrashReportPersister
import org.acra.file.ReportLocator
import org.acra.interaction.ReportInteractionExecutor
import org.acra.log.debug
import org.acra.log.error
import org.acra.log.info
import org.acra.log.warn
import org.acra.plugins.loadEnabled
import org.acra.scheduler.SchedulerStarter
import org.acra.util.ProcessFinisher
import org.acra.util.ToastSender.sendToast
import java.io.File
import java.lang.RuntimeException
/**
* Collates, records and initiates the sending of a report.
*
* @since 4.8.0
*/
class ReportExecutor(private val context: Context, private val config: CoreConfiguration, private val crashReportDataFactory: CrashReportDataFactory,
// A reference to the system's previous default UncaughtExceptionHandler
// kept in order to execute the default exception handling after sending the report.
private val defaultExceptionHandler: Thread.UncaughtExceptionHandler?, private val processFinisher: ProcessFinisher,
private val schedulerStarter: SchedulerStarter,
private val lastActivityManager: LastActivityManager) {
private val reportingAdministrators: List<ReportingAdministrator> = config.pluginLoader.loadEnabled(config)
var isEnabled = false
/**
* pass-through to default handler
*
* @param t the crashed thread
* @param e the uncaught exception
*/
fun handReportToDefaultExceptionHandler(t: Thread, e: Throwable) {
if (defaultExceptionHandler != null) {
info { "ACRA is disabled for " + context.packageName + " - forwarding uncaught Exception on to default ExceptionHandler" }
defaultExceptionHandler.uncaughtException(t, e)
} else {
error { "ACRA is disabled for ${context.packageName} - no default ExceptionHandler" }
error(e) { "ACRA caught a ${e.javaClass.simpleName} for ${context.packageName}" }
}
}
/**
* Try to create a report. Also starts [LegacySenderService]
*
* @param reportBuilder The report builder used to assemble the report
*/
fun execute(reportBuilder: ReportBuilder) {
if (!isEnabled) {
warn { "ACRA is disabled. Report not sent." }
return
}
var blockingAdministrator: ReportingAdministrator? = null
for (administrator in reportingAdministrators) {
try {
if (!administrator.shouldStartCollecting(context, config, reportBuilder)) {
blockingAdministrator = administrator
}
} catch (t: Exception) {
warn(t) { "ReportingAdministrator ${administrator.javaClass.name} threw exception" }
}
}
val crashReportData: CrashReportData?
if (blockingAdministrator == null) {
crashReportData = crashReportDataFactory.createCrashData(reportBuilder)
for (administrator in reportingAdministrators) {
try {
if (!administrator.shouldSendReport(context, config, crashReportData)) {
blockingAdministrator = administrator
}
} catch (t: Exception) {
warn(t) { "ReportingAdministrator ${administrator.javaClass.name} threw exception" }
}
}
} else {
crashReportData = null
debug { "Not collecting crash report because of ReportingAdministrator " + blockingAdministrator.javaClass.name }
}
if (reportBuilder.isEndApplication) {
var finishActivity = true
for (administrator in reportingAdministrators) {
try {
if (!administrator.shouldFinishActivity(context, config, lastActivityManager)) {
finishActivity = false
}
} catch (t: Exception) {
warn(t) { "ReportingAdministrator " + administrator.javaClass.name + " threw exception" }
}
}
if (finishActivity) {
// Finish the last activity early to prevent restarts on android 7+
processFinisher.finishLastActivity(reportBuilder.uncaughtExceptionThread)
}
}
if (blockingAdministrator == null) {
val oldPolicy = StrictMode.allowThreadDiskWrites()
val reportFile = getReportFileName(crashReportData!!)
saveCrashReportFile(reportFile, crashReportData)
val executor = ReportInteractionExecutor(context, config)
if (reportBuilder.isSendSilently) {
//if no interactions are present we can send all reports
sendReport(reportFile, executor.hasInteractions())
} else {
if (executor.performInteractions(reportFile)) {
sendReport(reportFile, false)
}
}
StrictMode.setThreadPolicy(oldPolicy)
} else {
debug { "Not sending crash report because of ReportingAdministrator ${blockingAdministrator.javaClass.name}" }
try {
blockingAdministrator.notifyReportDropped(context, config)
} catch (t: Exception) {
warn(t) { "ReportingAdministrator ${blockingAdministrator.javaClass.name} threw exeption" }
}
}
debug { "Wait for Interactions + worker ended. Kill Application ? ${reportBuilder.isEndApplication}" }
if (reportBuilder.isEndApplication) {
var endApplication = true
for (administrator in reportingAdministrators) {
try {
if (!administrator.shouldKillApplication(context, config, reportBuilder, crashReportData)) {
endApplication = false
}
} catch (t: Exception) {
warn(t) { "ReportingAdministrator ${administrator.javaClass.name} threw exception" }
}
}
if (endApplication) {
if (Debug.isDebuggerConnected()) {
//Killing a process with a debugger attached would kill the whole application including our service, so we can't do that.
val warning = "Warning: Acra may behave differently with a debugger attached"
Thread {
Looper.prepare()
sendToast(context, warning, Toast.LENGTH_LONG)
Looper.loop()
}.start()
warn { warning }
} else {
endApplication(reportBuilder.uncaughtExceptionThread, reportBuilder.exception?: RuntimeException())
}
}
}
}
/**
* End the application.
*/
private fun endApplication(uncaughtExceptionThread: Thread?, th: Throwable) {
val letDefaultHandlerEndApplication: Boolean = config.alsoReportToAndroidFramework
if (uncaughtExceptionThread != null && letDefaultHandlerEndApplication && defaultExceptionHandler != null) {
// Let the system default handler do it's job and display the force close dialog.
debug { "Handing Exception on to default ExceptionHandler" }
defaultExceptionHandler.uncaughtException(uncaughtExceptionThread, th)
} else {
processFinisher.endApplication()
}
}
/**
* Starts a Process to start sending outstanding error reports.
*
* @param onlySendSilentReports If true then only send silent reports.
*/
private fun sendReport(report: File, onlySendSilentReports: Boolean) {
if (isEnabled) {
schedulerStarter.scheduleReports(report, onlySendSilentReports)
} else {
warn { "Would be sending reports, but ACRA is disabled" }
}
}
private fun getReportFileName(crashData: CrashReportData): File {
val timestamp = crashData.getString(ReportField.USER_CRASH_DATE)
val isSilent = crashData.getString(ReportField.IS_SILENT)
val fileName = timestamp + (if (isSilent != null && java.lang.Boolean.parseBoolean(isSilent)) ACRAConstants.SILENT_SUFFIX else "") + ACRAConstants.REPORTFILE_EXTENSION
val reportLocator = ReportLocator(context)
return File(reportLocator.unapprovedFolder, fileName)
}
/**
* Store a report
*
* @param file the file to store in
* @param crashData the content
*/
private fun saveCrashReportFile(file: File, crashData: CrashReportData) {
try {
debug { "Writing crash report file $file" }
CrashReportPersister().store(crashData, file)
} catch (e: Exception) {
error(e) { "An error occurred while writing the report file..." }
}
}
} | 11 | Kotlin | 1135 | 6,309 | 3cfb0e03e0fea333f1964d15caba3855ff221043 | 9,870 | acra | Apache License 2.0 |
solutions/src/solutions/y21/day 15.kt | Kroppeb | 225,582,260 | false | null | @file:Suppress("PackageDirectoryMismatch", "UnusedImport")
package solutions.y21
/*
import grid.Clock
import helpers.*
import itertools.*
import kotlin.math.*
*/
import collections.counter
import grid.Clock
import helpers.*
import itertools.count
import java.util.*
import kotlin.collections.ArrayDeque
val xxxxx = Clock(6, 3);
/*
*/
private fun part1() {
var data = getLines(2021_15).digits()
val queue = ArrayDeque<Pair<Point, Long>>()
queue.addLast(Pair(Point(0, 0), 0))
val bestPoints = mutableMapOf<Point, Long>()
var best = Long.MAX_VALUE;
while(queue.isNotEmpty()) {
val (p, steps) = queue.removeFirst()
if(bestPoints.containsKey(p) && bestPoints[p]!! < steps) continue
if(p.x + 1 == data.size && p.y + 1 == data[0].size) {
best = min(best, steps)
}
for(np in p.getQuadNeighbours()) {
if(np.x >= 0 && np.y >= 0 && np.x < data.size && np.y < data[0].size) {
var second = steps + data[np.x][np.y]
if(np !in bestPoints || bestPoints[np]!! > second) {
bestPoints[np] = second
queue.addLast(Pair(np, second))
}
}
}
}
best.log()
}
private fun part2() {
var data = getLines(2021_15).digits()
val queue = ArrayDeque<Pair<Point, Long>>()
queue.addLast(Pair(Point(0, 0), 0))
val bestPoints = mutableMapOf<Point, Long>()
var best = Long.MAX_VALUE;
var newData = data
repeat(4){u->
newData += data.map { it.map{x -> (x + u) % 9 + 1} }
}
newData = newData.transpose()
data = newData
repeat(4){u->
newData += data.map { it.map{x -> (x + u) % 9 + 1} }
}
data = newData.transpose()
while(queue.isNotEmpty()) {
val (p, steps) = queue.removeFirst()
if(bestPoints.containsKey(p) && bestPoints[p]!! < steps) continue
if(p.x + 1 == data.size && p.y + 1 == data[0].size) {
best = min(best, steps)
}
for(np in p.getQuadNeighbours()) {
if(np.x >= 0 && np.y >= 0 && np.x < data.size && np.y < data[0].size) {
var second = steps + data[np.x][np.y]
if(np !in bestPoints || bestPoints[np]!! > second) {
bestPoints[np] = second
queue.addLast(Pair(np, second))
}
}
}
}
best.log()
}
fun main() {
println("Day 15: ")
part1()
part2()
}
fun <T> T.log(): T = also { println(this) } | 0 | Kotlin | 0 | 1 | 744b02b4acd5c6799654be998a98c9baeaa25a79 | 2,551 | AdventOfCodeSolutions | MIT License |
src/main/kotlin/dayFolders/day1/medianOfArrays.kt | lilimapradhan9 | 255,344,059 | false | null | package dayFolders.day1
fun findMedianSortedArrays(nums1: IntArray, nums2: IntArray): Double {
val allElements = mutableListOf<Int>()
allElements.addAll(nums1.toList())
allElements.addAll(nums2.toList())
allElements.sort()
val midPoint = allElements.size / 2
if (allElements.size % 2 == 0) {
return (allElements[midPoint] + allElements[midPoint - 1]) / 2.0
}
return allElements[midPoint].toDouble()
}
| 0 | Kotlin | 0 | 0 | 356cef0db9f0ba1106c308d33c13358077aa0674 | 444 | kotlin-problems | MIT License |
LavalinkServer/src/main/java/lavalink/server/io/WebSocketHandler.kt | HerryOP69 | 576,424,943 | true | {"Java": 72644, "Kotlin": 71955, "Dockerfile": 297} | package lavalink.server.io
import com.sedmelluq.discord.lavaplayer.track.TrackMarker
import dev.arbjerg.lavalink.api.AudioFilterExtension
import dev.arbjerg.lavalink.api.WebSocketExtension
import lavalink.server.player.TrackEndMarkerHandler
import lavalink.server.player.filters.Band
import lavalink.server.player.filters.FilterChain
import lavalink.server.util.Util
import moe.kyokobot.koe.VoiceServerInfo
import org.json.JSONObject
import org.slf4j.Logger
import org.slf4j.LoggerFactory
import kotlin.reflect.KFunction1
class WebSocketHandler(
private val context: SocketContext,
private val wsExtensions: List<WebSocketExtension>,
private val filterExtensions: List<AudioFilterExtension>
) {
companion object {
private val log: Logger = LoggerFactory.getLogger(WebSocketHandler::class.java)
}
private var loggedVolumeDeprecationWarning = false
private var loggedEqualizerDeprecationWarning = false
private val handlers: Map<String, (JSONObject) -> Unit> = mutableMapOf(
"voiceUpdate" to ::voiceUpdate,
"play" to ::play,
"stop" to ::stop,
"pause" to ::pause,
"seek" to ::seek,
"volume" to ::volume,
"equalizer" to ::equalizer,
"filters" to ::filters,
"destroy" to ::destroy,
"configureResuming" to ::configureResuming
).apply {
wsExtensions.forEach {
val func = fun(json: JSONObject) { it.onInvocation(context, json) }
this[it.opName] = func as KFunction1<JSONObject, Unit>
}
}
fun handle(json: JSONObject) {
val op = json.getString("op")
val handler = handlers[op] ?: return log.warn("Unknown op '$op'")
handler(json)
}
private fun voiceUpdate(json: JSONObject) {
val sessionId = json.getString("sessionId")
val guildId = json.getLong("guildId")
val event = json.getJSONObject("event")
val endpoint: String? = event.optString("endpoint")
val token: String = event.getString("token")
//discord sometimes send a partial server update missing the endpoint, which can be ignored.
endpoint ?: return
//clear old connection
context.koe.destroyConnection(guildId)
val player = context.getPlayer(guildId)
val conn = context.getVoiceConnection(player)
conn.connect(VoiceServerInfo(sessionId, endpoint, token)).whenComplete { _, _ ->
player.provideTo(conn)
}
}
private fun play(json: JSONObject) {
val player = context.getPlayer(json.getString("guildId"))
val noReplace = json.optBoolean("noReplace", false)
if (noReplace && player.playingTrack != null) {
log.info("Skipping play request because of noReplace")
return
}
val track = Util.toAudioTrack(context.audioPlayerManager, json.getString("track"))
if (json.has("startTime")) {
track.position = json.getLong("startTime")
}
player.setPause(json.optBoolean("pause", false))
if (json.has("volume")) {
if(!loggedVolumeDeprecationWarning) log.warn("The volume property in the play operation has been deprecated " +
"and will be removed in v4. Please configure a filter instead. Note that the new filter takes a " +
"float value with 1.0 being 100%")
loggedVolumeDeprecationWarning = true
val filters = player.filters ?: FilterChain()
filters.volume = json.getFloat("volume") / 100
player.filters = filters
}
if (json.has("endTime")) {
val stopTime = json.getLong("endTime")
if (stopTime > 0) {
val handler = TrackEndMarkerHandler(player)
val marker = TrackMarker(stopTime, handler)
track.setMarker(marker)
}
}
player.play(track)
val conn = context.getVoiceConnection(player)
context.getPlayer(json.getString("guildId")).provideTo(conn)
}
private fun stop(json: JSONObject) {
val player = context.getPlayer(json.getString("guildId"))
player.stop()
}
private fun pause(json: JSONObject) {
val player = context.getPlayer(json.getString("guildId"))
player.setPause(json.getBoolean("pause"))
SocketServer.sendPlayerUpdate(context, player)
}
private fun seek(json: JSONObject) {
val player = context.getPlayer(json.getString("guildId"))
player.seekTo(json.getLong("position"))
SocketServer.sendPlayerUpdate(context, player)
}
private fun volume(json: JSONObject) {
val player = context.getPlayer(json.getString("guildId"))
player.setVolume(json.getInt("volume"))
}
private fun equalizer(json: JSONObject) {
if (!loggedEqualizerDeprecationWarning) log.warn("The 'equalizer' op has been deprecated in favour of the " +
"'filters' op. Please switch to use that one, as this op will get removed in v4.")
loggedEqualizerDeprecationWarning = true
val player = context.getPlayer(json.getString("guildId"))
val list = mutableListOf<Band>()
json.getJSONArray("bands").forEach { b ->
val band = b as JSONObject
list.add(Band(band.getInt("band"), band.getFloat("gain")))
}
val filters = player.filters ?: FilterChain()
filters.equalizer = list
player.filters = filters
}
private fun filters(json: JSONObject) {
val player = context.getPlayer(json.getLong("guildId"))
player.filters = FilterChain.parse(json, filterExtensions)
}
private fun destroy(json: JSONObject) {
context.destroyPlayer(json.getLong("guildId"))
}
private fun configureResuming(json: JSONObject) {
context.resumeKey = json.optString("key", null)
if (json.has("timeout")) context.resumeTimeout = json.getLong("timeout")
}
}
| 0 | Java | 0 | 0 | ef59de90a587d52e09d85d9bbe840446cc8fcbf1 | 6,013 | luvulink | MIT License |
steerAndPut/src/main/java/se/geecity/android/steerandput/station/StationFragment.kt | widarlein | 121,007,812 | false | null | /*
* MIT License
*
* Copyright (c) 2019 <NAME>
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package se.geecity.android.steerandput.station
import android.location.Location
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.Fragment
import androidx.lifecycle.observe
import com.google.android.gms.maps.CameraUpdateFactory
import com.google.android.gms.maps.model.CameraPosition
import com.google.android.gms.maps.model.LatLng
import com.google.android.gms.maps.model.MarkerOptions
import kotlinx.android.synthetic.main.fragment_station.*
import org.koin.android.ext.android.inject
import org.koin.android.viewmodel.ext.android.viewModel
import se.geecity.android.data.model.ParcelableStationObject
import se.geecity.android.data.model.toParcelable
import se.geecity.android.domain.entities.Failure
import se.geecity.android.domain.entities.Resource
import se.geecity.android.domain.entities.StationObject
import se.geecity.android.domain.entities.Success
import se.geecity.android.steerandput.R
import se.geecity.android.steerandput.common.adapter.StationInteractionListener
import se.geecity.android.steerandput.common.logging.FirebaseLoggerV2
import se.geecity.android.steerandput.common.util.getDistanceBetweenAsString
import se.geecity.android.steerandput.common.util.hasCoarseLocationPermission
import se.geecity.android.steerandput.common.util.hasFineLocationPermission
import se.geecity.android.steerandput.common.view.ViewIdentifier
import se.geecity.android.steerandput.common.view.gone
class StationFragment : Fragment() {
private val station: StationObject by lazy { station() }
private val stationViewModel: StationViewModel by viewModel()
private val firebaseLogger: FirebaseLoggerV2 by inject()
private val stationInteractionListener: StationInteractionListener by inject()
companion object {
private val EXTRA_STATION = "station"
fun createArguments(station: StationObject): Bundle {
return Bundle().apply { putParcelable(EXTRA_STATION, station.toParcelable()) }
}
private fun StationFragment.station(): StationObject {
val station = arguments?.getParcelable<ParcelableStationObject>(EXTRA_STATION)?.toDomainObject()
if (station != null) {
return station
}
throw IllegalStateException("No station argument for StationFragment")
}
}
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
return inflater.inflate(R.layout.fragment_station, container, false)
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
mapView.onCreate(savedInstanceState)
setupMap()
chart.gone()
chartTitle.gone()
setStationInfo(station)
swipeRefreshLayout.setOnRefreshListener {
stationViewModel.fetchStationObject()
}
firebaseLogger.pageView(ViewIdentifier.STATION, station)
firebaseLogger.stationDetailsView()
}
override fun onStart() {
super.onStart()
stationViewModel.location.observe(this) {
setLocationText(it)
}
stationViewModel.stationObjectId = station.id
stationViewModel.stationObject.observe(this) { stationResource ->
when (stationResource) {
Resource.Loading -> swipeRefreshLayout.isRefreshing = true
is Success -> {
setStationInfo(stationResource.body)
swipeRefreshLayout.isRefreshing = false
}
is Failure -> {
swipeRefreshLayout.isRefreshing = false
}
}
}
}
private fun setStationInfo(station: StationObject) {
stationName.text = station.name
stationBikeText.text = station.availableBikes.toString()
stationStandsText.text = station.availableBikeStands.toString()
}
private fun setLocationText(location: Location) {
stationDistance.text = getDistanceBetweenAsString(station, location)
}
private fun setupMap() {
mapView.getMapAsync { map ->
if (hasFineLocationPermission(activity!!) || hasCoarseLocationPermission(activity!!)) {
map.isMyLocationEnabled = true
}
val pos = LatLng(station.lat, station.longitude)
val cp = CameraPosition.Builder()
.target(pos)
.zoom(15.5f)
.build()
val update = CameraUpdateFactory.newCameraPosition(cp)
map.moveCamera(update)
map.uiSettings.isMapToolbarEnabled = false
val markerOptions = MarkerOptions().position(pos)
map.addMarker(markerOptions)
map.setOnMapClickListener {
stationInteractionListener.onStationClicked(station)
firebaseLogger.mapClicked(station)
}
}
}
} | 0 | Kotlin | 0 | 1 | c00a207a1d0acdec597fab176c6966687ec66581 | 6,131 | SteerAndPut | MIT License |
steerAndPut/src/main/java/se/geecity/android/steerandput/station/StationFragment.kt | widarlein | 121,007,812 | false | null | /*
* MIT License
*
* Copyright (c) 2019 <NAME>
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package se.geecity.android.steerandput.station
import android.location.Location
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.Fragment
import androidx.lifecycle.observe
import com.google.android.gms.maps.CameraUpdateFactory
import com.google.android.gms.maps.model.CameraPosition
import com.google.android.gms.maps.model.LatLng
import com.google.android.gms.maps.model.MarkerOptions
import kotlinx.android.synthetic.main.fragment_station.*
import org.koin.android.ext.android.inject
import org.koin.android.viewmodel.ext.android.viewModel
import se.geecity.android.data.model.ParcelableStationObject
import se.geecity.android.data.model.toParcelable
import se.geecity.android.domain.entities.Failure
import se.geecity.android.domain.entities.Resource
import se.geecity.android.domain.entities.StationObject
import se.geecity.android.domain.entities.Success
import se.geecity.android.steerandput.R
import se.geecity.android.steerandput.common.adapter.StationInteractionListener
import se.geecity.android.steerandput.common.logging.FirebaseLoggerV2
import se.geecity.android.steerandput.common.util.getDistanceBetweenAsString
import se.geecity.android.steerandput.common.util.hasCoarseLocationPermission
import se.geecity.android.steerandput.common.util.hasFineLocationPermission
import se.geecity.android.steerandput.common.view.ViewIdentifier
import se.geecity.android.steerandput.common.view.gone
class StationFragment : Fragment() {
private val station: StationObject by lazy { station() }
private val stationViewModel: StationViewModel by viewModel()
private val firebaseLogger: FirebaseLoggerV2 by inject()
private val stationInteractionListener: StationInteractionListener by inject()
companion object {
private val EXTRA_STATION = "station"
fun createArguments(station: StationObject): Bundle {
return Bundle().apply { putParcelable(EXTRA_STATION, station.toParcelable()) }
}
private fun StationFragment.station(): StationObject {
val station = arguments?.getParcelable<ParcelableStationObject>(EXTRA_STATION)?.toDomainObject()
if (station != null) {
return station
}
throw IllegalStateException("No station argument for StationFragment")
}
}
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
return inflater.inflate(R.layout.fragment_station, container, false)
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
mapView.onCreate(savedInstanceState)
setupMap()
chart.gone()
chartTitle.gone()
setStationInfo(station)
swipeRefreshLayout.setOnRefreshListener {
stationViewModel.fetchStationObject()
}
firebaseLogger.pageView(ViewIdentifier.STATION, station)
firebaseLogger.stationDetailsView()
}
override fun onStart() {
super.onStart()
stationViewModel.location.observe(this) {
setLocationText(it)
}
stationViewModel.stationObjectId = station.id
stationViewModel.stationObject.observe(this) { stationResource ->
when (stationResource) {
Resource.Loading -> swipeRefreshLayout.isRefreshing = true
is Success -> {
setStationInfo(stationResource.body)
swipeRefreshLayout.isRefreshing = false
}
is Failure -> {
swipeRefreshLayout.isRefreshing = false
}
}
}
}
private fun setStationInfo(station: StationObject) {
stationName.text = station.name
stationBikeText.text = station.availableBikes.toString()
stationStandsText.text = station.availableBikeStands.toString()
}
private fun setLocationText(location: Location) {
stationDistance.text = getDistanceBetweenAsString(station, location)
}
private fun setupMap() {
mapView.getMapAsync { map ->
if (hasFineLocationPermission(activity!!) || hasCoarseLocationPermission(activity!!)) {
map.isMyLocationEnabled = true
}
val pos = LatLng(station.lat, station.longitude)
val cp = CameraPosition.Builder()
.target(pos)
.zoom(15.5f)
.build()
val update = CameraUpdateFactory.newCameraPosition(cp)
map.moveCamera(update)
map.uiSettings.isMapToolbarEnabled = false
val markerOptions = MarkerOptions().position(pos)
map.addMarker(markerOptions)
map.setOnMapClickListener {
stationInteractionListener.onStationClicked(station)
firebaseLogger.mapClicked(station)
}
}
}
} | 0 | Kotlin | 0 | 1 | c00a207a1d0acdec597fab176c6966687ec66581 | 6,131 | SteerAndPut | MIT License |
vector/src/main/java/im/vector/app/features/login2/created/AccountCreatedViewState.kt | vector-im | 151,282,063 | false | null | /*
* Copyright (c) 2021 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.app.features.login2.created
import com.airbnb.mvrx.Async
import com.airbnb.mvrx.MvRxState
import com.airbnb.mvrx.Uninitialized
import org.matrix.android.sdk.api.util.MatrixItem
data class AccountCreatedViewState(
val userId: String = "",
val isLoading: Boolean = false,
val currentUser: Async<MatrixItem.UserItem> = Uninitialized,
val hasBeenModified: Boolean = false
) : MvRxState
| 55 | null | 418 | 1,995 | abe07c73a4f21e476e4eb1fd40fb84638177cff6 | 1,037 | element-android | Apache License 2.0 |
app/src/main/java/com/jeanbarrossilva/power/CalculatorFragment.kt | jeanbarrossilva | 200,567,989 | false | null | package com.jeanbarrossilva.power
import android.annotation.SuppressLint
import android.content.Context
import android.graphics.Typeface
import android.os.Bundle
import android.text.Editable
import android.text.TextWatcher
import android.view.*
import android.view.animation.Animation
import android.view.animation.AnimationUtils
import android.widget.Button
import android.widget.EditText
import android.widget.HorizontalScrollView
import android.widget.ImageButton
import androidx.fragment.app.Fragment
import com.jeanbarrossilva.power.MainActivity.Companion.LAST_PARENTHESIS_LEFT
import com.jeanbarrossilva.power.MainActivity.Companion.LAST_PARENTHESIS_RIGHT
import net.objecthunter.exp4j.Expression
import net.objecthunter.exp4j.ExpressionBuilder
import java.util.*
open class CalculatorFragment : Fragment() {
lateinit var fragmentView: View
internal lateinit var context: Context
private lateinit var mainActivity: MainActivity
private lateinit var keypadIn: Animation
private lateinit var keypadOut: Animation
private var isScientific: Boolean = false
private val keypad: View by lazy {
fragmentView.findViewById<View>(R.id.keypad_delete).findViewById<View>(R.id.keypad)
}
val keypadButtons: Array<Button> by lazy {
arrayOf<Button>(
keypad.findViewById(R.id.zero),
keypad.findViewById(R.id.one),
keypad.findViewById(R.id.two),
keypad.findViewById(R.id.three),
keypad.findViewById(R.id.four),
keypad.findViewById(R.id.five),
keypad.findViewById(R.id.six),
keypad.findViewById(R.id.seven),
keypad.findViewById(R.id.eight),
keypad.findViewById(R.id.nine),
keypad.findViewById(R.id.decimal_separator)
)
}
internal lateinit var input: EditText
private lateinit var othersHorizontalScrollView: HorizontalScrollView
private lateinit var number: Button
private lateinit var parenthesis: Array<Button>
private lateinit var operator: Button
private val operators = intArrayOf(R.id.plus, R.id.minus, R.id.times, R.id.division)
lateinit var calculatorMode: ImageButton
lateinit var delete: ImageButton
private lateinit var equal: Button
override fun onAttach(context: Context) {
super.onAttach(context)
this.context = context
if (context != this)
isScientific = false
}
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
fragmentView = inflater.inflate(R.layout.fragment_calculator, container, false)
context = Objects.requireNonNull<Context>(getContext())
mainActivity = activity as MainActivity
keypadIn = AnimationUtils.loadAnimation(context, R.anim.keypad_in)
keypadOut = AnimationUtils.loadAnimation(context, R.anim.keypad_out)
input = fragmentView.findViewById(R.id.input)
// Disables the keyboard, since the app already has predefined buttons.
input.isFocusable = false
parenthesis = arrayOf(fragmentView.findViewById(R.id.left_parenthesis), fragmentView.findViewById(R.id.right_parenthesis))
othersHorizontalScrollView = fragmentView.findViewById(R.id.others_horizontal_scroll_view)
othersHorizontalScrollView.isHorizontalScrollBarEnabled = false
calculatorMode = fragmentView.findViewById(R.id.calculator_mode)
delete = fragmentView.findViewById(R.id.delete)
equal = fragmentView.findViewById(R.id.equal)
mainActivity.calculatorMode(context, calculatorMode)
inputNumber(input)
inputDecimalSeparator(input)
inputOperator(input)
inputParenthesis(input)
delete(input, delete)
calc(false)
return fragmentView
}
private fun isInputLastNumber(input: EditText): Boolean {
return if (input.text.toString().isNotEmpty()) Character.isDigit(input.text.toString()[input.text.toString().length - 1]) else false
}
private fun isInputLastDecimalSeparator(input: EditText): Boolean {
for (decimalSeparator in StringUtils.Punctuation.decimalSeparators) {
return input.text.toString().endsWith(decimalSeparator)
}
return false
}
private fun isInputLastOperator(input: EditText): Boolean {
val operators = arrayOf("+", "-", "*", "/")
for (operator in operators) {
if (input.text.toString().isNotEmpty()) {
val buffer = StringBuilder(input.text.toString())
return buffer[input.length() - 1] == operator[0]
}
}
return false
}
private fun isInputLastParenthesis(input: EditText, parenthesis: Int): Boolean {
when (parenthesis) {
LAST_PARENTHESIS_LEFT -> return input.text.toString().endsWith("(")
LAST_PARENTHESIS_RIGHT -> return input.text.toString().endsWith(")")
}
return false
}
private fun inputFormat(input: EditText, result: String) {
var result = result
if (!(isInputLastOperator(input) && isInputLastDecimalSeparator(input)))
try {
if (result.contains("E")) {
result = result.replace("E", "e")
}
if (result.endsWith(".0")) {
result = result.replace(".0", "")
}
if (result.contains("Infinity")) {
result = result.replace("Infinity", "∞")
}
if (result.length > 16) {
result = result.substring(17, result.length - 1)
}
input.setText(result)
if (mainActivity.shareUsageData)
println("Calc result: $result")
} catch (exception: Exception) {
input.setText(getString(R.string.error))
}
else {
input.setText("0")
}
}
/**
* Inputs a number in a text field.
*
* @param input Represents the text field itself.
*/
@SuppressLint("ClickableViewAccessibility")
private fun inputNumber(input: EditText) {
val onTouchListener = View.OnTouchListener { view, event ->
number = view as Button
when (event.action) {
MotionEvent.ACTION_DOWN -> mainActivity.bounceIn(view, 0.5, 5.0)
MotionEvent.ACTION_UP -> {
number.startAnimation(mainActivity.bounceOut)
if (input.text.toString() != getString(R.string.error)) {
input.append(number.text)
} else {
input.setText("")
number = view
input.append(number.text)
}
}
}
true
}
for (number in mainActivity.numbers) {
fragmentView.findViewById<View>(number).setOnTouchListener(onTouchListener)
}
}
/**
* Inputs a decimal separator in a text field.
*
* @param input Represents the text field itself.
*/
@SuppressLint("ClickableViewAccessibility")
fun inputDecimalSeparator(input: EditText) {
try {
keypadButtons[10].setOnTouchListener { view, event ->
when (event.action) {
MotionEvent.ACTION_DOWN -> mainActivity.bounceIn(view, 0.5, 5.0)
MotionEvent.ACTION_UP -> {
view.startAnimation(mainActivity.bounceOut)
if (isInputLastNumber(input))
input.append(".")
}
}
true
}
} catch (nullPointerException: NullPointerException) {
nullPointerException.printStackTrace()
}
}
/**
* Inputs an operator in a text field.
*
* @param input Represents the text field itself.
*/
@SuppressLint("ClickableViewAccessibility")
private fun inputOperator(input: EditText) {
val onTouchListener = View.OnTouchListener { view, event ->
operator = view as Button
when (event.action) {
MotionEvent.ACTION_DOWN -> mainActivity.bounceIn(view, 0.5, 5.0)
MotionEvent.ACTION_UP -> {
operator.startAnimation(mainActivity.bounceOut)
for (power in StringUtils.Superscript.powers) {
if (!isInputLastOperator(input)) {
if (operator.id == R.id.plus || operator.id == R.id.minus || input.text.toString().endsWith(power)) {
if (input.text.toString().isNotEmpty())
input.append(" " + operator.text + " ")
else if ((isInputLastNumber(input) || isInputLastParenthesis(input, LAST_PARENTHESIS_LEFT) || isInputLastParenthesis(input, LAST_PARENTHESIS_LEFT)) and !isInputLastOperator(input))
input.append(operator.text.toString() + " ")
else
input.append(" " + operator.text + " ")
} else if (operator.id == R.id.times || operator.id == R.id.division) {
if (!(input.text.toString().isEmpty() && isInputLastDecimalSeparator(input) && isInputLastParenthesis(input, LAST_PARENTHESIS_LEFT)))
input.append(" " + operator.text + " ")
}
}
}
}
}
true
}
for (operator in operators) {
fragmentView.findViewById<View>(operator).setOnTouchListener(onTouchListener)
}
}
/**
* Inputs a parenthesis in a text field.
*
* @param input Represents the text field itself.
*/
@SuppressLint("ClickableViewAccessibility")
private fun inputParenthesis(input: EditText) {
val listener = View.OnTouchListener { view, event ->
val parenthesis = view as Button
when (event.action) {
MotionEvent.ACTION_DOWN -> mainActivity.bounceIn(view, 0.5, 5.0)
MotionEvent.ACTION_UP -> {
parenthesis.startAnimation(mainActivity.bounceOut)
for (parenthesisButton in [email protected]) {
when (parenthesisButton.id) {
R.id.left_parenthesis -> if (!isInputLastDecimalSeparator(input))
input.append("(")
else if (isInputLastNumber(input))
input.append(" " + StringUtils.Operator.Stylized.TIMES + " " + parenthesis)
R.id.right_parenthesis -> if (isInputLastNumber(input))
input.append(")")
}
}
}
}
true
}
for (parenthesis in parenthesis) {
fragmentView.findViewById<View>(parenthesis.id).setOnTouchListener(listener)
}
}
@SuppressLint("ClickableViewAccessibility")
private fun delete(input: EditText, delete: ImageButton) {
delete.setOnTouchListener { view, event ->
val calc = input.text.toString()
when (event.action) {
MotionEvent.ACTION_DOWN -> mainActivity.bounceIn(view, 0.5, 1.0)
MotionEvent.ACTION_UP -> {
delete.startAnimation(mainActivity.bounceOut)
delete.performHapticFeedback(HapticFeedbackConstants.VIRTUAL_KEY)
if (calc.isNotEmpty())
try {
input.setText(if (calc.endsWith(" ")) calc.substring(0, calc.length - 2) else calc.substring(0, calc.length - 1))
} catch (exception: Exception) {
input.setText("")
}
}
}
true
}
}
@SuppressLint("ClickableViewAccessibility")
private fun calc(cancel: Boolean) {
equal.setOnTouchListener { _, event ->
when (event.action) {
MotionEvent.ACTION_DOWN -> equal.performHapticFeedback(HapticFeedbackConstants.VIRTUAL_KEY)
MotionEvent.ACTION_UP -> {
if (!cancel) {
val expression: Expression
if (input.text.toString().isNotEmpty()) {
expression = ExpressionBuilder(mainActivity.reformatCalc(input.text.toString())!!).build()
try {
val result = expression.evaluate().toString()
input.setText(result)
} catch (exception: Exception) {
// If the calc is unfinished, "String.valueOf(expression.evaluate())" throws an IllegalArgumentException.
if (input.text.toString().isNotEmpty())
input.append(if (input.text.toString().endsWith(" ")) getString(R.string.zero) else " " + getString(R.string.zero))
else
input.append(getString(R.string.zero))
equal.performClick()
}
val previousCalc = input.text.toString()
inputFormat(input, input.text.toString())
}
}
if (mainActivity.shareUsageData) {
println("\"isScientific\": $isScientific")
}
}
}
false
}
equal.setOnLongClickListener {
isScientific = !isScientific
scientific()
true
}
}
@SuppressLint("ClickableViewAccessibility")
private fun scientific() {
calc(true)
keypad.startAnimation(if (isScientific) keypadOut else keypadIn)
for (keypadButton in keypadButtons) {
for (index in keypadButtons.indices) {
if (isScientific) {
if (keypadButtons[index].id == keypadButton.id) {
keypadButton.tag = "placeholder$index"
break
}
}
if (keypadButton.tag != "placeholder10")
keypadButton.text = index.toString()
else
keypadButton.text = "."
}
keypadButton.setTypeface(keypadButton.typeface, if (isScientific) Typeface.NORMAL else Typeface.BOLD)
if (isScientific) {
when (keypadButton.id) {
R.id.seven -> {
keypadButton.tag = "powerTwo"
// Dynamic text preview.
input.addTextChangedListener(object : TextWatcher {
override fun beforeTextChanged(s: CharSequence, start: Int, count: Int, after: Int) {
}
override fun onTextChanged(s: CharSequence, start: Int, before: Int, count: Int) {
if (isScientific) {
keypadButton.text = if (s.toString().length == 1 && isInputLastNumber(input)) s.toString()[0] + StringUtils.Superscript.POWER_TWO else getString(R.string.x_power_two)
} else {
keypadButton.text = getString(R.string.seven)
}
}
override fun afterTextChanged(s: Editable) {
}
})
keypadButton.setOnTouchListener { view, event ->
when (event.action) {
MotionEvent.ACTION_DOWN -> mainActivity.bounceIn(view, 0.5, 5.0)
MotionEvent.ACTION_UP -> {
view.startAnimation(mainActivity.bounceOut)
if (isInputLastNumber(input) && isInputLastParenthesis(input, LAST_PARENTHESIS_RIGHT))
input.append(StringUtils.Superscript.POWER_TWO)
}
}
true
}
}
}
} else {
inputNumber(input)
}
}
}
} | 1 | Kotlin | 0 | 2 | fc794f2d3fb19253f6cad29261a80dfd71190e55 | 17,003 | Power | Apache License 2.0 |
fourthline/src/main/java/de/solarisbank/sdk/fourthline/data/kyc/storage/KycInfoInMemoryDataSource.kt | Solarisbank | 336,233,277 | false | {"Kotlin": 468901, "Java": 6478, "Shell": 1215} | package de.solarisbank.sdk.fourthline.data.kyc.storage
import android.annotation.SuppressLint
import com.fourthline.core.DeviceMetadata
import com.fourthline.core.DocumentFileSide
import com.fourthline.core.DocumentType
import com.fourthline.core.Gender
import com.fourthline.core.location.Coordinate
import com.fourthline.core.mrz.MrtdMrzInfo
import com.fourthline.kyc.*
import com.fourthline.vision.document.DocumentScannerResult
import com.fourthline.vision.document.DocumentScannerStepResult
import com.fourthline.vision.selfie.SelfieScannerResult
import de.solarisbank.sdk.data.dto.PersonDataDto
import de.solarisbank.sdk.fourthline.data.dto.Location
import de.solarisbank.sdk.fourthline.parseDateFromString
import de.solarisbank.sdk.fourthline.streetNumber
import de.solarisbank.sdk.fourthline.streetSuffix
import kotlinx.coroutines.sync.Mutex
import timber.log.Timber
import java.util.*
interface KycInfoDataSource {
suspend fun finalizeAndGetKycInfo(): KycInfo
suspend fun getKycDocument(): Document
suspend fun updateWithPersonDataDto(personDataDto: PersonDataDto, providerName: String)
suspend fun updateKycWithSelfieScannerResult(result: SelfieScannerResult)
suspend fun updateKycInfoWithDocumentScannerStepResult(docType: DocumentType, result: DocumentScannerStepResult)
suspend fun updateKycInfoWithDocumentSecondaryScan(docType: DocumentType, result: DocumentScannerStepResult)
suspend fun updateKycInfoWithDocumentScannerResult(docType: DocumentType, result: DocumentScannerResult)
suspend fun updateIpAddress(ipAddress: String)
suspend fun updateKycLocation(resultLocation: Location)
suspend fun updateExpireDate(expireDate: Date)
suspend fun updateDocumentNumber(number: String)
suspend fun overrideKycInfo(kycInfo: KycInfo)
}
class KycInfoInMemoryDataSource: KycInfoDataSource {
private val mutex: Mutex = Mutex()
private var kycInfo = KycInfo().also {
it.person = Person()
it.metadata = DeviceMetadata()
}
private val docPagesMap = LinkedHashMap<DocPageKey, Attachment.Document>()
private val secondaryPagesMap = LinkedHashMap<DocPageKey, Attachment.Document>()
private var _personDataDto: PersonDataDto? = null
override suspend fun finalizeAndGetKycInfo(): KycInfo {
mutex.lock()
try {
finalizeSecondaryDocuments()
return kycInfo
} finally {
mutex.unlock()
}
}
override suspend fun overrideKycInfo(kycInfo: KycInfo) {
mutex.lock()
try {
this.kycInfo = kycInfo
} finally {
mutex.unlock()
}
}
/**
* Provides @Document for display
*/
override suspend fun getKycDocument(): Document {
mutex.lock()
try {
return kycInfo.document!!
} finally {
mutex.unlock()
}
}
override suspend fun updateWithPersonDataDto(personDataDto: PersonDataDto, providerName: String) {
mutex.lock()
Timber.d("updateWithPersonDataDto : $personDataDto")
try {
_personDataDto = personDataDto
kycInfo.provider = Provider(
name = providerName,
clientNumber = personDataDto.personUid
)
kycInfo.address = Address().also {
personDataDto.address?.apply {
it.street = street
/* Fourthline indicated that this field is mandatory on their API even though
It's optional here. They asked us to send 0 if no streetNumber was available */
it.streetNumber = streetNumber?.streetNumber() ?: 0
it.streetNumberSuffix = streetNumber?.streetSuffix()
it.city = city
it.countryCode = personDataDto.address?.country
it.postalCode = postalCode
}
}
kycInfo.contacts = Contacts().also {
it.mobile = personDataDto.mobileNumber
it.email = personDataDto.email
}
kycInfo.person.also {
it.firstName = _personDataDto?.firstName
it.lastName = _personDataDto?.lastName
it.gender = when (_personDataDto?.gender?.lowercase(Locale.US)) {
Gender.MALE.name.lowercase(Locale.US) -> Gender.MALE
Gender.FEMALE.name.lowercase(Locale.US) -> Gender.FEMALE
else -> Gender.UNKNOWN
}
it.birthDate = _personDataDto?.birthDate?.parseDateFromString()
it.nationalityCode = personDataDto.nationality
it.birthPlace = personDataDto.birthPlace
}
personDataDto.taxIdentification?.let {
kycInfo.taxInfo = TaxInfo(
taxpayerIdentificationNumber = it.number,
taxationCountryCode = it.country
)
}
} finally {
mutex.unlock()
}
}
@SuppressLint("BinaryOperationInTimber")
override suspend fun updateKycWithSelfieScannerResult(result: SelfieScannerResult) {
mutex.lock()
try {
Timber.d("updateKycWithSelfieScannerResult : " +
"\ntimestamp:${result.metadata.timestamp}" +
"\nlocation.latitude: ${result.metadata.location?.latitude}" +
"\nlocation.longitude: ${result.metadata.location?.longitude}"
)
kycInfo.selfie = Attachment.Selfie(
image = result.image.full,
timestamp = result.metadata.timestamp.time,
location = result.metadata.location,
videoRecording = result.videoRecording
)
} finally {
mutex.unlock()
}
}
override suspend fun updateIpAddress(ipAddress: String) {
mutex.lock()
try {
kycInfo.metadata.ipAddress = ipAddress
} finally {
mutex.unlock()
}
}
/**
* Retains document pages' photos and stores them to map
* Called from DocScanFragment.onStepSuccess()
*/
@SuppressLint("BinaryOperationInTimber")
override suspend fun updateKycInfoWithDocumentScannerStepResult(docType: DocumentType, result: DocumentScannerStepResult) {
mutex.lock()
try {
Timber.d("updateKycInfoWithDocumentScannerStepResult : " +
"\ntimestamp:${result.metadata.timestamp}" +
"\nlocation.latitude: ${result.metadata.location?.latitude}" +
"\nlocation.longitude: ${result.metadata.location?.longitude}"
)
val resultMap =
docPagesMap
.entries
.filter { it.key.docType == docType }
.associateByTo(LinkedHashMap(), { it.key}, { it.value})
docPagesMap.clear()
docPagesMap.putAll(resultMap)
docPagesMap[DocPageKey(docType, result.metadata.fileSide, result.metadata.isAngled)] =
Attachment.Document(
image = result.image.full,
fileSide = result.metadata.fileSide,
isAngled = result.metadata.isAngled,
timestamp = result.metadata.timestamp.time,
location = result.metadata.location
)
} finally {
mutex.unlock()
}
}
override suspend fun updateKycInfoWithDocumentSecondaryScan(docType: DocumentType, result: DocumentScannerStepResult) {
mutex.lock()
try {
secondaryPagesMap[DocPageKey(docType, result.metadata.fileSide, result.metadata.isAngled)] = Attachment.Document(
image = result.image.full,
fileSide = result.metadata.fileSide,
isAngled = result.metadata.isAngled,
timestamp = result.metadata.timestamp.time,
location = result.metadata.location
)
} finally {
mutex.unlock()
}
}
/**
* Retains recognized String data of the documents
*/
override suspend fun updateKycInfoWithDocumentScannerResult(docType: DocumentType, result: DocumentScannerResult) {
mutex.lock()
try {
obtainDocument(docType, result)
updateKycPerson(result)
} finally {
mutex.unlock()
}
}
private fun obtainDocument(docType: DocumentType, result: DocumentScannerResult) {
val mrtd = (result.mrzInfo as? MrtdMrzInfo)
kycInfo.document = Document(
images = docPagesMap.entries.filter { it.key.docType == docType }.map { it.value }.toList(),
videoRecording = result.videoRecording,
number = mrtd?.documentNumber,
expirationDate = mrtd?.expirationDate,
type = docType
)
}
private fun finalizeSecondaryDocuments() {
if (secondaryPagesMap.isEmpty())
return
kycInfo.secondaryDocuments = listOf(
SecondaryDocument(
type = secondaryPagesMap.entries.first().key.docType,
images = secondaryPagesMap.values.toList()
)
)
}
/**
* A part of kycInfo.person is obtained in updateWithPersonDataDto.
* Here provides person data that has been recognized from document scanning
*/
@SuppressLint("BinaryOperationInTimber")
private fun updateKycPerson(result: DocumentScannerResult) {
val mrtd = result.mrzInfo as? MrtdMrzInfo
kycInfo.person.apply {
val recognizedFirstNames = mrtd?.firstNames?.joinToString(separator = " ")
val recognizedLastNames = mrtd?.lastNames?.joinToString(separator = " ")
val recognizedBirthDate = mrtd?.birthDate
Timber.d(
"updateKycPerson : " +
"\nrecognizedFirstNames: $recognizedFirstNames}" +
"\nrecognizedLastNames: $recognizedLastNames" +
"\nlrecognizedBirthDate: $recognizedBirthDate" +
"\nlmrtd.gender: ${mrtd?.gender}"
)
if (!recognizedFirstNames.isNullOrBlank()) {
firstName = recognizedFirstNames
}
if (!recognizedLastNames.isNullOrBlank()) {
lastName = recognizedLastNames
}
if (
(gender == null || gender == Gender.UNKNOWN) &&
mrtd?.gender != null &&
mrtd.gender != Gender.UNKNOWN
) {
gender = mrtd.gender
}
if (birthDate == null && recognizedBirthDate != null) {
birthDate = recognizedBirthDate
}
}
}
override suspend fun updateKycLocation(resultLocation: Location) {
mutex.lock()
try {
kycInfo.metadata.location = Coordinate(resultLocation.latitude, resultLocation.longitude)
} finally {
mutex.unlock()
}
}
override suspend fun updateExpireDate(expireDate: Date) {
mutex.lock()
try {
kycInfo.document!!.expirationDate = expireDate
} finally {
mutex.unlock()
}
}
override suspend fun updateDocumentNumber(number: String) {
mutex.lock()
try {
kycInfo.document!!.number = number
} finally {
mutex.unlock()
}
}
private data class DocPageKey(
val docType: DocumentType,
val docSide: DocumentFileSide,
val isAngled: Boolean
)
} | 0 | Kotlin | 0 | 6 | 555ae8cb524ad592115245f13d73bd4cfdd46c9c | 11,861 | identhub-android | MIT License |
shared/src/commonMain/kotlin/utils/HelperKoin.kt | AndreVero | 735,628,501 | false | {"Kotlin": 81117, "Swift": 717, "Shell": 228} | package utils
import goaldetails.di.goalDetails
import home.di.goalModule
import org.koin.core.context.startKoin
import statistic.di.statistic
import tasks.di.platformModule
import tasks.di.tasksModule
object HelperKoin {
fun initKoin() {
startKoin {
modules(goalModule() + tasksModule() + goalDetails() + statistic() + platformModule)
}
}
}
| 0 | Kotlin | 0 | 0 | ec3512844819f6dd56a479d131937d6dca413587 | 380 | EasyTask | Apache License 2.0 |
springmvc/spring-springmvc-mybatis-kotlin/src/main/java/com/jiangKlijna/web/service/impl/UserServiceImpl.kt | JiangKlijna | 73,813,096 | false | {"Java": 59106, "Kotlin": 42873, "Python": 3997, "Go": 3433, "HTML": 1679, "CSS": 221} | package com.jiangKlijna.web.service.impl
import com.jiangKlijna.web.dao.IUserDao
import org.springframework.stereotype.Service
import com.jiangKlijna.web.bean.Result
import com.jiangKlijna.web.bean.User
import com.jiangKlijna.web.service.BaseService
import com.jiangKlijna.web.service.UserService
import javax.annotation.Resource
@Service("userService")
class UserServiceImpl : BaseService(), UserService {
@Resource
private val userDao: IUserDao? = null
override fun regist(username: String, password: String): Result {
try {
userDao!!.save(User(username, password))
return sucessResult()
} catch (e: Exception) {
return errorResult(e.toString())
}
}
override fun remove(id: Int): Result {
try {
userDao!!.delete(id)
return sucessResult()
} catch (e: Exception) {
return errorResult(e.toString())
}
}
override fun find(id: Int): Result {
try {
return sucessResult(userDao!!.get(id))
} catch (e: Exception) {
return errorResult(e.toString())
}
}
}
| 1 | null | 1 | 1 | a12a8a139e3bfd26835a168c5db8e8ea92eae4e0 | 1,160 | framework-learning | Apache License 2.0 |
game-plugins/src/main/kotlin/org/alter/plugins/service/restapi/controllers/CommandsController.kt | AlterRSPS | 421,831,790 | false | null | package org.alter.plugins.service.restapi.controllers
import com.google.gson.JsonArray
import com.google.gson.JsonObject
import org.alter.game.model.World
import org.alter.game.model.item.Item
import spark.Request
import spark.Response
class CommandsController(req: Request, resp: Response, auth: Boolean) : Controller(req, resp, auth) {
val req = req
val auth = auth
override fun init(world: World): JsonObject {
if(!super.authState && auth) {
val arr = JsonArray()
val obj = JsonObject()
obj.addProperty("error", "Auth code not supplied or invalid.")
arr.add(obj)
return obj
}
val itemId = req.params("id").toInt()
val amount = req.params("amount").toInt()
val player = req.params("player")
world.getPlayerForName(player)?.inventory?.add(Item(itemId, amount))
return JsonObject()
}
} | 8 | Kotlin | 33 | 23 | 9dbd62d67de547cfedc43b902797306c5db8fb55 | 924 | Alter | Apache License 2.0 |
app/src/main/java/com/example/studyspot/MainActivity.kt | yagmurdere | 776,868,129 | false | {"Kotlin": 160141} | package com.example.studyspot
import android.annotation.SuppressLint
import android.os.Bundle
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.navigation.compose.rememberNavController
import com.example.studyspot.modules.bottomnavbar.BottomNav
import com.example.studyspot.ui.theme.StudySpotTheme
class MainActivity : ComponentActivity() {
@SuppressLint("UnusedMaterial3ScaffoldPaddingParameter")
@OptIn(ExperimentalMaterial3Api::class)
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContent {
StudySpotTheme {
val navController = rememberNavController()
StudySpotTheme {
BottomNav()
}
}
}
}
}
| 0 | Kotlin | 4 | 0 | 62f80043bd5c07aafcebd3a20e5e89aaacdaeade | 912 | AndroidProject | MIT License |
app/src/main/java/pt/rfsfernandes/pocketalbum/domain/use_cases/GetAlbumInfo.kt | rfsfernandes | 452,097,308 | false | {"Kotlin": 79217} | package pt.rfsfernandes.pocketalbum.domain.use_cases
import kotlinx.coroutines.flow.Flow
import pt.rfsfernandes.pocketalbum.data.models.album.Album
import pt.rfsfernandes.pocketalbum.data.repository.Repository
import pt.rfsfernandes.pocketalbum.utils.Resource
/**
* Class GetAlbumInfo created at 22/01/2022 22:56 for the project PocketAlbum
* By: rodrigofernandes
*/
class GetAlbumInfo(private val repository: Repository) {
operator fun invoke(albumName: String?, artistName: String?): Flow<Resource<Album>> {
return repository.getAlbumInfo(albumName, artistName)
}
} | 0 | Kotlin | 0 | 0 | ea5693601a004b5a57d49ad62d4f6cc980112c39 | 586 | pocket_album | MIT License |
spikes/mmg-loader-example/src/test/kotlin/gov/cdc/dataExchange/VocabTest.kt | CDCgov | 510,836,864 | false | {"Kotlin": 741457, "Scala": 208820, "Python": 44391, "Java": 18075, "Batchfile": 11894, "Go": 8661, "JavaScript": 7609, "Groovy": 4230, "HTML": 2177, "Shell": 1362, "CSS": 979} | package gov.cdc.dataExchange
import com.google.gson.Gson
import com.google.gson.reflect.TypeToken
import open.HL7PET.tools.HL7StaticParser
import org.junit.jupiter.api.Test
import redis.clients.jedis.DefaultJedisClientConfig
import redis.clients.jedis.Jedis
import scala.Enumeration.Value
import kotlin.test.DefaultAsserter.assertTrue
class VocabTest {
val REDIS_PWD = System.getenv("REDISCACHEKEY")
val jedis = Jedis(MMGValidator.REDIS_CACHE_NAME, 6380, DefaultJedisClientConfig.builder()
.password(REDIS_PWD)
.ssl(true)
.build()
)
@Test
fun testLoadVocab() {
val conceptStr = jedis.get("PHVS_County_FIPS_6-4")
val listType = object : TypeToken<List<ValueSetConcept>>() {}.type
val concepts:List<ValueSetConcept> = Gson().fromJson(conceptStr, listType)
println(concepts)
}
@Test
fun testLoadVocabFromMMGValidator() {
val mmgValidator = MMGValidator()
val concepts = mmgValidator.retrieveValueSetConcepts("PHVS_State_FIPS_5-2")
println(concepts)
}
@Test
fun testGetRedisKeys() {
val keys = jedis.keys("*")
println(keys.size)
println(keys)
}
@Test
fun testGetConcpets() {
val concepts = jedis.hgetAll("PHVS_ClinicalManifestation_TBRD")
println(concepts.keys)
assertTrue("is M in there?" , concepts.keys.contains("M"))
}
@Test
fun testInvalidKey() {
val mmgValidator = MMGValidator()
try {
val unknownKey = mmgValidator.retrieveValueSetConcepts("Unknown_key")
println(unknownKey)
} catch (e: InvalidConceptKey) {
assertTrue("Exception properly thrown", true)
}
}
@Test
fun testMultipleKeys() {
val result = jedis.mget("PHVS_YesNoUnkNA_NND", "unknwon", "PHVS_ReasonForHospitalization_VZ")
println(result)
}
@Test
fun testGetFirtValue() {
val msg = this::class.java.getResource("/testMessage.hl7").readText()
val msgValue = HL7StaticParser.getFirstValue(msg, "MSH-21[3].1")
if (msgValue.isDefined)
println(msgValue.get())
else
println("No value found")
}
} | 118 | Kotlin | 14 | 9 | 4eaaf1ce43722d9b623218418cfabd5cdda434f0 | 2,231 | data-exchange-hl7 | Apache License 2.0 |
app/src/main/java/com/andre_max/tiktokclone/utils/map/SmartAction.kt | Andre-max | 291,054,765 | false | null | /*
* MIT License
*
* Copyright (c) 2021 Andre-max
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package com.andre_max.tiktokclone.utils.map
enum class SmartAction {
Add, AddAll, AddElement, AddFirst, AddLast,
Clear,
DrainTo,
Fill,
InsertElementAt,
Offer, OfferFirst, OfferLast,
Poll, PollFirst, PollLast, Pop, Push, Put, PutAll, PutFirst, PutLast,
Remove, RemoveAll, RemoveAt, RemoveElementAt, RemoveFirst, RemoveFirstOccurrence, RemoveIf,
RemoveLast, RemoveLastOccurrence, ReplaceAll, RetainAll, Reverse,
Set, SetElementAt, Shuffle, Sort,
Take, TakeFirst, TakeLast
} | 7 | Kotlin | 27 | 56 | 0dcbc62d6b7d388744c213881a8125157eaf51e2 | 1,649 | TikTok-Clone | MIT License |
lib-androscope/src/main/java/nl/ngti/androscope/responses/database/DatabaseResponse.kt | ngti | 158,838,163 | false | null | package nl.ngti.androscope.responses.database
import android.content.Context
import android.database.DatabaseUtils
import android.text.format.Formatter
import com.google.gson.Gson
import fi.iki.elonen.NanoHTTPD
import nl.ngti.androscope.responses.common.MultiSchemeDataProvider
import nl.ngti.androscope.responses.common.RequestResult
import nl.ngti.androscope.responses.common.toDownloadResponse
import nl.ngti.androscope.server.SessionParams
import nl.ngti.androscope.server.dbUri
import nl.ngti.androscope.server.get
import nl.ngti.androscope.server.readSql
import nl.ngti.androscope.utils.AndroscopeMetadata
import java.io.File
private const val TABLE_SQLITE_MASTER = "sqlite_master"
internal class DatabaseResponse(
private val context: Context,
private val metadata: AndroscopeMetadata,
uriDataProvider: MultiSchemeDataProvider,
private val jsonConverter: Gson
) {
private val databaseManager = DatabaseManager(context).also {
uriDataProvider.addProvider(DbUri.SCHEME, it)
}
fun getList(): List<Database> {
val result = ArrayList<Database>()
metadata.databaseName?.run {
if (isNotBlank()) {
result += DbConfig(context, this).run {
Database(
databaseName,
title = name,
description = "Configured in manifest",
error = errorMessage
)
}
}
}
context.databaseList()
.mapTo(HashSet()) {
context.getDatabasePath(it).mainDatabaseFile
}
.filter {
it.exists() && it.isFile
}
.sorted()
.mapTo(result) {
Database(it.name)
}
return result
}
fun getTitle(sessionParams: SessionParams): String {
return sessionParams.dbUri.toConfig(context).name
}
fun getInfo(sessionParams: SessionParams): DatabaseInfo {
val uri = sessionParams.dbUri
val config = uri.toConfig(context)
val databaseFile = config.databaseFile
val size = Formatter.formatFileSize(context, databaseFile.length())
return try {
DatabaseInfo(
true,
fullPath = databaseFile.absolutePath,
size = size
).apply {
fillDatabaseInfo(uri, this)
}
} catch (e: Throwable) {
DatabaseInfo(false, errorMessage = e.message)
}
}
private fun fillDatabaseInfo(uri: DbUri, result: DatabaseInfo) {
databaseManager.query(
uri,
tableName = TABLE_SQLITE_MASTER,
projection = arrayOf(
/* 0 */ "name",
/* 1 */ "type"
),
sortOrder = "type ASC, name ASC"
)?.use { cursor ->
while (cursor.moveToNext()) {
val list = when (cursor.getString(1)) {
"table" -> result.tables
"view" -> result.views
"trigger" -> result.triggers
"index" -> result.indexes
else -> null
}
list?.apply {
this += cursor.getString(0)
}
}
}
result.tables += TABLE_SQLITE_MASTER
}
fun getCanQuery(sessionParams: SessionParams): Boolean {
val sql = sessionParams.readSql(jsonConverter)
val type = DatabaseUtils.getSqlStatementType(sql)
return type == DatabaseUtils.STATEMENT_SELECT
}
fun executeSql(sessionParams: SessionParams): RequestResult {
return try {
val sql = sessionParams.readSql(jsonConverter)
databaseManager.executeSql(sessionParams.dbUri, sql)
RequestResult.success("Executed")
} catch (e: Throwable) {
return RequestResult.error(e.message ?: e.javaClass.name)
}
}
fun getDatabaseToDownload(sessionParams: SessionParams): NanoHTTPD.Response? {
val file = sessionParams.dbUri.toConfig(context).databaseFile
return file.toDownloadResponse()
}
fun uploadDatabase(sessionParams: SessionParams): RequestResult? {
val databaseFile = sessionParams.dbUri.toConfig(context).databaseFile
val body = HashMap<String, String>()
sessionParams.parseBody(body)
body.forEach { (key, value) ->
val bodyFile = File(value)
val replaceStrategy = if (databaseFile.exists())
BackupOriginalStrategy() else NoBackupStrategy()
return replaceStrategy.replace(bodyFile, databaseFile, key)
}
return RequestResult.error("No input file")
}
fun getSql(sessionParams: SessionParams): String {
val name = sessionParams["name"]!!
return databaseManager.query(
sessionParams.dbUri,
tableName = TABLE_SQLITE_MASTER,
projection = arrayOf(
/* 0 */ "sql"
),
selection = "name=?",
selectionArgs = arrayOf(name)
)?.use {
if (it.moveToFirst()) {
it.getString(0)
} else null
} ?: "Cannot find '$name' sql"
}
}
private abstract class ReplaceStrategy {
fun replace(sourceFile: File, destFile: File, sourceName: String): RequestResult {
onBeforeReplace(sourceFile, destFile)?.let {
return it
}
if (!sourceFile.renameTo(destFile)) {
onReplaceFailed(destFile)
return RequestResult.error("Failed to replace database with: $sourceName")
}
onReplaceSuccess()
return RequestResult.success()
}
open fun onBeforeReplace(sourceFile: File, destFile: File): RequestResult? {
// Override in ancestors if needed
return null
}
open fun onReplaceSuccess() {
// Override in ancestors if needed
}
open fun onReplaceFailed(destFile: File) {
// Override in ancestors if needed
}
}
private class NoBackupStrategy : ReplaceStrategy()
private class BackupOriginalStrategy : ReplaceStrategy() {
private lateinit var backup: FileBatch
override fun onBeforeReplace(sourceFile: File, destFile: File): RequestResult? {
val tempDir = createTempDir(directory = destFile.parentFile)
backup = destFile.collectAllDatabaseFiles().moveTo(tempDir)
?: return RequestResult.error(
"Cannot backup original database into: ${tempDir.absolutePath}." +
" There might be active writes into it."
)
return null
}
override fun onReplaceFailed(destFile: File) {
// Attempt to restore old destination database
backup.moveTo(destFile.parentFile!!, revertIfFailed = false)
}
override fun onReplaceSuccess() {
backup.parentDirectory.deleteRecursively()
}
}
| 3 | Kotlin | 2 | 12 | 73492d74967ebfcce584e9985651bf2744464323 | 7,211 | androscope | MIT License |
src/test/kotlin/com/github/blindpirate/junit/extension/unroll/UnrollTestNameFormatterTest.kt | blindpirate | 126,752,942 | false | null | package com.github.blindpirate.junit.extension.unroll
import org.junit.jupiter.api.Test
@Suppress("UNUSED_PARAMETER", "UNCHECKED_CAST")
class UnrollTestNameFormatterTest {
@Test
fun `can replace {number}`() {
assertTemplateRender("{0}", "", "")
assertTemplateRender("{0}{1}{2}", "[]{1}{2}", listOf<Any>())
assertTemplateRender("{0}", "[foo, bar]", listOf("foo", "bar"))
assertTemplateRender("{0}", "42", 42)
assertTemplateRender("{0}", "foo", "foo")
assertTemplateRender("{0} {1}{2}", "foo 42", "foo", 42, "")
assertTemplateRender("{0} {1} {2}{3}{4}{{{}{}{}{}{5}{6}{7}{8}{9}{10}{11}",
"0 1 234{{{}{}{}{}567891011", *(0..20).toList().toTypedArray())
}
@Test
fun `fallback to methodName(index)`() {
assertFallbackTemplateRender("method", "method [0]", 0)
assertFallbackTemplateRender("method", "method [1]", 1)
assertFallbackTemplateRender("method{}", "method{} [12345]", 12345)
}
private fun assertFallbackTemplateRender(template: String, expected: String, invocationIndex: Int) {
assert(UnrollTestNameFormatter(template).format(invocationIndex, arrayOf("whatever")) == expected)
}
private fun assertTemplateRender(template: String, expected: String, vararg args: Any?) {
assert(UnrollTestNameFormatter(template).format(0, args as Array<out Any>) == expected)
}
} | 0 | Kotlin | 3 | 8 | eeba0f51d824ac2b3fa1b49bc186d80ffeb32cdd | 1,420 | junit5-unroll-extension | Apache License 2.0 |
ksoup/src/jsMain/kotlin/com/tajmoti/ksoup/KSoup.kt | Tajmoti | 391,138,914 | false | null | package com.tajmoti.ksoup
import org.w3c.dom.parsing.DOMParser
actual object KSoup {
actual fun parse(html: String): KDocument {
return KDocument(DOMParser().parseFromString(html, "text/html"))
}
} | 6 | Kotlin | 0 | 1 | 7dd02fe23b3205967e02d0efff2b7efd191fe138 | 215 | Tulip | MIT License |
app/src/main/java/net/slingspot/myapplication/App.kt | jeremygriffes | 526,441,968 | false | {"Kotlin": 30528} | package net.slingspot.myapplication
import android.app.Application
import dagger.hilt.android.HiltAndroidApp
import net.slingspot.androidlogger.LogLevel
@HiltAndroidApp
class App : Application() {
companion object {
val logLevel = if (BuildConfig.DEBUG) LogLevel.VERBOSE else LogLevel.INFO
}
}
| 0 | Kotlin | 0 | 0 | c690ad45c562c762c7017e7b1bd46f8ca2cbe088 | 312 | AndroidTemplate | Apache License 2.0 |
libs/serialization/serialization-kryo/src/main/kotlin/net/corda/kryoserialization/serializers/X500PrincipalSerializer.kt | corda | 346,070,752 | false | {"Kotlin": 20585419, "Java": 308202, "Smarty": 115357, "Shell": 54409, "Groovy": 30246, "PowerShell": 6470, "TypeScript": 5826, "Solidity": 2024, "Batchfile": 244} | package net.corda.kryoserialization.serializers
import com.esotericsoftware.kryo.Kryo
import com.esotericsoftware.kryo.Serializer
import com.esotericsoftware.kryo.io.Input
import com.esotericsoftware.kryo.io.Output
import javax.security.auth.x500.X500Principal
/**
* For general use X500Principal class manages serialization/deserialization internally by way of being a
* java.io.Serializable and using transient fields. Using Kryo's stock JavaSerializer is not recommended because it's
* inefficient, but regardless causes an exception to be thrown on deserialization when used with Corda.
* It is actually trivial to serialize/deserialize objects of this type as the whole content is encapsulated in the
* name.
*/
class X500PrincipalSerializer: Serializer<X500Principal>() {
override fun write(kryo: Kryo, output: Output, obj: X500Principal) {
output.writeString(obj.name)
}
override fun read(kryo: Kryo, input: Input, type: Class<out X500Principal>): X500Principal {
return X500Principal(input.readString())
}
}
| 71 | Kotlin | 9 | 69 | d478e119ab288af663910f9a2df42a7a7b9f5bce | 1,057 | corda-runtime-os | Apache License 2.0 |
android/src/main/kotlin/com/apparence/camerawesome/cameraX/CameraPermissions.kt | Apparence-io | 281,904,557 | false | null | package com.apparence.camerawesome.cameraX
import android.Manifest
import android.app.Activity
import android.content.Context
import android.content.pm.PackageManager
import android.util.Log
import androidx.core.app.ActivityCompat
import androidx.core.content.ContextCompat
import com.apparence.camerawesome.exceptions.PermissionNotDeclaredException
import io.flutter.plugin.common.EventChannel
import io.flutter.plugin.common.EventChannel.EventSink
import io.flutter.plugin.common.PluginRegistry.RequestPermissionsResultListener
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import java.util.*
import kotlin.coroutines.Continuation
import kotlin.coroutines.resume
import kotlin.coroutines.suspendCoroutine
class CameraPermissions : EventChannel.StreamHandler, RequestPermissionsResultListener {
private var permissionGranted = false
private var events: EventSink? = null
private var callbacks: MutableList<PermissionRequest> = mutableListOf()
// ---------------------------------------------
// EventChannel.StreamHandler
// ---------------------------------------------
override fun onListen(arguments: Any?, events: EventSink?) {
this.events = events
}
override fun onCancel(arguments: Any?) {
if (events != null) {
events!!.endOfStream()
events = null
}
}
// ---------------------------------------------
// PluginRegistry.RequestPermissionsResultListener
// ---------------------------------------------
override fun onRequestPermissionsResult(
requestCode: Int, permissions: Array<String>, grantResults: IntArray
): Boolean {
val grantedPermissions = mutableListOf<String>()
val deniedPermissions = mutableListOf<String>()
permissionGranted = true
for (i in permissions.indices) {
if (grantResults[i] == PackageManager.PERMISSION_GRANTED) {
grantedPermissions.add(permissions[i])
} else {
permissionGranted = false
deniedPermissions.add(permissions[i])
}
}
val toRemove = mutableListOf<PermissionRequest>()
for (c in callbacks) {
if (c.permissionsAsked.containsAll(permissions.toList()) && permissions.toList()
.containsAll(c.permissionsAsked)
) {
c.callback(grantedPermissions, deniedPermissions)
toRemove.add(c)
}
}
callbacks.removeAll(toRemove)
if (events != null) {
Log.d(
TAG,
"_onRequestPermissionsResult: granted " + java.lang.String.join(", ", *permissions)
)
events!!.success(permissionGranted)
} else {
Log.d(
TAG, "_onRequestPermissionsResult: received permissions but the EventSink is closed"
)
}
return permissionGranted
}
fun requestBasePermissions(
activity: Activity,
saveGps: Boolean,
recordAudio: Boolean,
callback: (granted: List<String>) -> Unit
) {
val declared = declaredCameraPermissions(activity)
// Remove declared permissions not required now
if (!saveGps) {
declared.remove(Manifest.permission.ACCESS_FINE_LOCATION)
declared.remove(Manifest.permission.ACCESS_COARSE_LOCATION)
}
if (!recordAudio) {
declared.remove(Manifest.permission.RECORD_AUDIO)
}
// Throw exception if permission not declared but required here
if (saveGps && !declared.contains(Manifest.permission.ACCESS_FINE_LOCATION)) {
throw PermissionNotDeclaredException(Manifest.permission.ACCESS_FINE_LOCATION)
}
if (saveGps && !declared.contains(Manifest.permission.ACCESS_COARSE_LOCATION)) {
throw PermissionNotDeclaredException(Manifest.permission.ACCESS_COARSE_LOCATION)
}
if (recordAudio && !declared.contains(Manifest.permission.RECORD_AUDIO)) {
throw PermissionNotDeclaredException(Manifest.permission.RECORD_AUDIO)
}
// Check if some of the permissions have already been given
val permissionsToAsk: MutableList<String> = ArrayList()
val permissionsGranted: MutableList<String> = ArrayList()
for (permission in declared) {
if (ContextCompat.checkSelfPermission(
activity, permission
) != PackageManager.PERMISSION_GRANTED
) {
permissionsToAsk.add(permission)
} else {
permissionsGranted.add(permission)
}
}
permissionGranted = permissionsToAsk.size == 0
if (permissionsToAsk.isEmpty()) {
callback(permissionsGranted)
} else {
// Request the not granted permissions
CoroutineScope(Dispatchers.IO).launch {
requestPermissions(activity, permissionsToAsk, PERMISSIONS_MULTIPLE_REQUEST) {
callback(permissionsGranted.apply { addAll(it) })
}
}
}
}
/**
* Returns the list of declared camera related permissions
*/
private fun declaredCameraPermissions(context: Context): MutableList<String> {
val packageInfo = context.packageManager.getPackageInfo(
context.packageName, PackageManager.GET_PERMISSIONS
)
val permissions = packageInfo.requestedPermissions
val declaredPermissions = mutableListOf<String>()
if (permissions.isNullOrEmpty()) return declaredPermissions
for (perm in permissions) {
if (allPermissions.contains(perm)) {
declaredPermissions.add(perm)
}
}
return declaredPermissions
}
fun hasPermission(activity: Activity, permissions: List<String>): Boolean {
var granted = true
for (p in permissions) {
if (ContextCompat.checkSelfPermission(
activity, p
) != PackageManager.PERMISSION_GRANTED
) {
granted = false
break
}
}
return granted
}
suspend fun requestPermissions(
activity: Activity,
permissions: List<String>,
requestCode: Int,
callback: (denied: List<String>) -> Unit
) {
val result: List<String> = suspendCoroutine { continuation: Continuation<List<String>> ->
ActivityCompat.requestPermissions(
activity, permissions.toTypedArray(), requestCode
)
callbacks.add(
PermissionRequest(UUID.randomUUID().toString(),
permissions,
callback = { granted, _ ->
continuation.resume(granted)
})
)
}
callback(result)
}
companion object {
private val TAG = CameraPermissions::class.java.name
const val PERMISSIONS_MULTIPLE_REQUEST = 550
const val PERMISSION_GEOLOC = 560
const val PERMISSION_RECORD_AUDIO = 570
val allPermissions = listOf(
Manifest.permission.CAMERA,
Manifest.permission.WRITE_EXTERNAL_STORAGE,
Manifest.permission.RECORD_AUDIO,
Manifest.permission.ACCESS_FINE_LOCATION,
Manifest.permission.ACCESS_COARSE_LOCATION,
)
}
}
data class PermissionRequest(
var id: String,
val permissionsAsked: List<String>,
val callback: (permissionsGranted: List<String>, permissionsDenied: List<String>) -> Unit
) {} | 33 | null | 97 | 934 | 0c0e669d59e8a1b5d566cc64b8927ecadc1df558 | 7,751 | CamerAwesome | MIT License |
plugins/kotlin/base/fir/analysis-api-providers/testData/sealedInheritors/illegalDistributedSealedClass/module1/foo/SealedClass.kt | JetBrains | 2,489,216 | false | null | package foo
sealed class SealedClass
class InheritorSameModuleSamePackage1 : SealedClass()
class InheritorSameModuleSamePackage2 : SealedClass()
| 284 | null | 5162 | 16,707 | def6433a5dd9f0a984cbc6e2835d27c97f2cb5f0 | 147 | intellij-community | Apache License 2.0 |
ui/src/main/java/io/snabble/sdk/ui/utils/ViewGroupExt.kt | snabble | 124,525,499 | false | null | @file:JvmName("ViewGroupExt")
package io.snabble.sdk.ui.utils
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.annotation.LayoutRes
fun ViewGroup.inflate(
@LayoutRes resource: Int,
root: ViewGroup? = this,
attachToRoot: Boolean = false
): View = LayoutInflater.from(this.context).inflate(resource, root, attachToRoot)
| 2 | null | 1 | 6 | 616deec75e44da50e3bd7819d962ffb782aa64e3 | 389 | Android-SDK | MIT License |
sample/common/src/main/kotlin/com/walletconnect/sample/common/ui/commons/Buttons.kt | WalletConnect | 435,951,419 | false | null | package com.walletconnect.sample.common.ui.commons
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.Button
import androidx.compose.material.ButtonDefaults
import androidx.compose.material.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.unit.dp
@Composable
fun BlueButton(
text: String,
onClick: () -> Unit,
modifier: Modifier = Modifier
) {
val contentColor = Color(0xFFE5E7E7)
Button(
shape = RoundedCornerShape(12.dp),
modifier = modifier,
colors = ButtonDefaults.buttonColors(
backgroundColor = Color(0xFF3496ff),
contentColor = contentColor
),
onClick = {
onClick()
},
) {
Text(text = text, color = contentColor)
}
}
| 156 | null | 71 | 171 | dda3aac207a2c9d9696764efd4a2f5bb585707b4 | 892 | WalletConnectKotlinV2 | Apache License 2.0 |
stream-chat-android-ui-components-sample/src/main/kotlin/io/getstream/chat/ui/sample/feature/channel/add/UserListItem.kt | GetStream | 177,873,527 | false | {"Kotlin": 8578375, "MDX": 2150736, "Java": 271477, "JavaScript": 6737, "Shell": 5229} | /*
* Copyright (c) 2014-2022 Stream.io Inc. All rights reserved.
*
* Licensed under the Stream License;
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://github.com/GetStream/stream-chat-android/blob/main/LICENSE
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.getstream.chat.ui.sample.feature.channel.add
import io.getstream.chat.android.models.User
sealed class UserListItem {
val id: String
get() = when (this) {
is Separator -> letter.toString()
is UserItem -> userInfo.user.id
}
data class Separator(val letter: Char) : UserListItem()
data class UserItem(val userInfo: UserInfo) : UserListItem()
}
data class UserInfo(val user: User, val isSelected: Boolean)
| 24 | Kotlin | 273 | 1,451 | 8e46f46a68810d8086c48a88f0fff29faa2629eb | 1,093 | stream-chat-android | FSF All Permissive License |
rounded/src/commonMain/kotlin/me/localx/icons/rounded/bold/KeyboardDown.kt | localhostov | 808,861,591 | false | {"Kotlin": 79430321, "HTML": 331, "CSS": 102} | package me.localx.icons.rounded.bold
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.PathFillType.Companion.NonZero
import androidx.compose.ui.graphics.SolidColor
import androidx.compose.ui.graphics.StrokeCap.Companion.Butt
import androidx.compose.ui.graphics.StrokeJoin.Companion.Miter
import androidx.compose.ui.graphics.vector.ImageVector
import androidx.compose.ui.graphics.vector.ImageVector.Builder
import androidx.compose.ui.graphics.vector.path
import androidx.compose.ui.unit.dp
import me.localx.icons.rounded.Icons
public val Icons.Bold.KeyboardDown: ImageVector
get() {
if (_keyboardDown != null) {
return _keyboardDown!!
}
_keyboardDown = Builder(name = "KeyboardDown", defaultWidth = 24.0.dp, defaultHeight =
24.0.dp, viewportWidth = 24.0f, viewportHeight = 24.0f).apply {
path(fill = SolidColor(Color(0xFF000000)), stroke = null, strokeLineWidth = 0.0f,
strokeLineCap = Butt, strokeLineJoin = Miter, strokeLineMiter = 4.0f,
pathFillType = NonZero) {
moveToRelative(18.5f, 0.0f)
lineTo(5.5f, 0.0f)
curveTo(2.467f, 0.0f, 0.0f, 2.467f, 0.0f, 5.5f)
verticalLineToRelative(7.0f)
curveToRelative(0.0f, 3.032f, 2.467f, 5.5f, 5.5f, 5.5f)
horizontalLineToRelative(13.0f)
curveToRelative(3.033f, 0.0f, 5.5f, -2.468f, 5.5f, -5.5f)
verticalLineToRelative(-7.0f)
curveToRelative(0.0f, -3.033f, -2.467f, -5.5f, -5.5f, -5.5f)
close()
moveTo(21.0f, 12.5f)
curveToRelative(0.0f, 1.379f, -1.122f, 2.5f, -2.5f, 2.5f)
lineTo(5.5f, 15.0f)
curveToRelative(-1.378f, 0.0f, -2.5f, -1.121f, -2.5f, -2.5f)
verticalLineToRelative(-7.0f)
curveToRelative(0.0f, -1.378f, 1.122f, -2.5f, 2.5f, -2.5f)
horizontalLineToRelative(13.0f)
curveToRelative(1.378f, 0.0f, 2.5f, 1.122f, 2.5f, 2.5f)
verticalLineToRelative(7.0f)
close()
moveTo(19.0f, 6.5f)
curveToRelative(0.0f, 0.829f, -0.671f, 1.5f, -1.5f, 1.5f)
horizontalLineToRelative(-1.0f)
curveToRelative(-0.829f, 0.0f, -1.5f, -0.671f, -1.5f, -1.5f)
reflectiveCurveToRelative(0.671f, -1.5f, 1.5f, -1.5f)
horizontalLineToRelative(1.0f)
curveToRelative(0.829f, 0.0f, 1.5f, 0.671f, 1.5f, 1.5f)
close()
moveTo(13.0f, 11.5f)
curveToRelative(0.0f, 0.829f, -0.671f, 1.5f, -1.5f, 1.5f)
horizontalLineToRelative(-5.0f)
curveToRelative(-0.829f, 0.0f, -1.5f, -0.671f, -1.5f, -1.5f)
reflectiveCurveToRelative(0.671f, -1.5f, 1.5f, -1.5f)
horizontalLineToRelative(5.0f)
curveToRelative(0.829f, 0.0f, 1.5f, 0.671f, 1.5f, 1.5f)
close()
moveTo(19.0f, 11.5f)
curveToRelative(0.0f, 0.829f, -0.671f, 1.5f, -1.5f, 1.5f)
horizontalLineToRelative(-1.0f)
curveToRelative(-0.829f, 0.0f, -1.5f, -0.671f, -1.5f, -1.5f)
reflectiveCurveToRelative(0.671f, -1.5f, 1.5f, -1.5f)
horizontalLineToRelative(1.0f)
curveToRelative(0.829f, 0.0f, 1.5f, 0.671f, 1.5f, 1.5f)
close()
moveTo(5.0f, 6.5f)
curveToRelative(0.0f, -0.828f, 0.672f, -1.5f, 1.5f, -1.5f)
reflectiveCurveToRelative(1.5f, 0.672f, 1.5f, 1.5f)
reflectiveCurveToRelative(-0.672f, 1.5f, -1.5f, 1.5f)
reflectiveCurveToRelative(-1.5f, -0.672f, -1.5f, -1.5f)
close()
moveTo(13.0f, 6.5f)
curveToRelative(0.0f, 0.828f, -0.672f, 1.5f, -1.5f, 1.5f)
reflectiveCurveToRelative(-1.5f, -0.672f, -1.5f, -1.5f)
reflectiveCurveToRelative(0.672f, -1.5f, 1.5f, -1.5f)
reflectiveCurveToRelative(1.5f, 0.672f, 1.5f, 1.5f)
close()
moveTo(15.058f, 21.255f)
lineToRelative(-2.172f, 2.374f)
curveToRelative(-0.443f, 0.494f, -1.217f, 0.494f, -1.66f, 0.0f)
lineToRelative(-2.172f, -2.374f)
curveToRelative(-0.44f, -0.481f, -0.099f, -1.255f, 0.553f, -1.255f)
horizontalLineToRelative(4.899f)
curveToRelative(0.652f, 0.0f, 0.993f, 0.775f, 0.553f, 1.255f)
close()
}
}
.build()
return _keyboardDown!!
}
private var _keyboardDown: ImageVector? = null
| 1 | Kotlin | 0 | 5 | cbd8b510fca0e5e40e95498834f23ec73cc8f245 | 4,780 | icons | MIT License |
src/aws/lambdas/incremental_distribution/cta/src/main/java/uk/nhs/nhsx/keyfederation/upload/JWS.kt | Alexmakes | 298,249,605 | true | {"Kotlin": 1588541, "HCL": 484131, "Ruby": 385358, "Python": 81257, "HTML": 7697, "Java": 7597, "Shell": 4822, "Dockerfile": 2996, "JavaScript": 554, "Makefile": 539} | package uk.nhs.nhsx.keyfederation.upload
import uk.nhs.nhsx.core.signature.Signer
import java.util.*
class JWS(private val signer: Signer) {
fun sign(payload: String): String {
val signedComponent = "${encode("""{"alg":"ES256"}""")}.${encode(payload)}"
val signature = signer.sign(signedComponent.toByteArray())
val encodedSignature = URL_ENCODER.encodeToString(signature.asJWSCompatible())
return "$signedComponent.$encodedSignature"
}
private fun encode(string: String): String = URL_ENCODER.encodeToString(string.toByteArray())
companion object {
private val URL_ENCODER = Base64.getUrlEncoder()
}
}
| 0 | Kotlin | 0 | 0 | 265c2d4a452951245b9a2d7c737036c3862909e2 | 667 | covid19-app-system-public | MIT License |
lib/src/main/java/com/kotlin/inaction/chapter_5/5_5_4_2_Run.kt | jhwsx | 167,022,805 | false | null | package com.kotlin.inaction.chapter_5
/**
*
* @author wzc
* @date 2019/8/18
*/
fun main(args: Array<String>) {
val hexNumberRegex = run {
val digits = "0-9"
val hexDigits = "A-Fa-f"
val sign = "+-"
Regex("[$sign]?[$digits$hexDigits]+")
}
for (match in hexNumberRegex.findAll("+1234 -FFFF no-a-number")) {
println(match.value)
}
}
/**
* 总结:
* run 函数不是扩展函数的例子,返回值还是 lambda 结果,但不用获取上下文对象了。
*/
| 1 | Kotlin | 1 | 1 | 1cdb279920c229fa4e00a09a8165f32e71cadd3e | 457 | KotlinInAction | MIT License |
src/main/kotlin/no/roedt/frivilligsystem/FrivilligService.kt | Roedt | 300,015,002 | false | null | package no.roedt.frivilligsystem
import jakarta.enterprise.context.ApplicationScoped
import no.roedt.Emojifjerner
import no.roedt.Kilde
import no.roedt.brukere.GenerellRolle
import no.roedt.frivilligsystem.kontakt.KontaktService
import no.roedt.frivilligsystem.registrer.Aktivitet
import no.roedt.frivilligsystem.registrer.AktivitetForFrivillig
import no.roedt.frivilligsystem.registrer.AktivitetForFrivilligService
import no.roedt.frivilligsystem.registrer.AutentisertRegistrerNyFrivilligRequest
import no.roedt.frivilligsystem.registrer.AutentisertSoMeFrivilligRequest
import no.roedt.frivilligsystem.registrer.ErMedlemStatus
import no.roedt.frivilligsystem.registrer.RegistrerNyFrivilligRequest
import no.roedt.fylke.FylkeService
import no.roedt.lokallag.LokallagService
import no.roedt.person.Oppdateringskilde
import no.roedt.person.Person
import no.roedt.person.PersonDTO
import no.roedt.person.PersonService
import no.roedt.person.UserId
import no.roedt.postnummer.PostnummerService
import no.roedt.ringesentralen.RingespesifikkRolle
import no.roedt.ringesentralen.brukere.RingesentralenGroupID
import java.time.Instant
import java.util.Optional
@ApplicationScoped
class FrivilligService(
val frivilligRepository: FrivilligRepository,
val personService: PersonService,
val kontaktService: KontaktService,
val lokallagService: LokallagService,
val fylkeService: FylkeService,
val aktivitetForFrivilligService: AktivitetForFrivilligService,
val frivilligOpptattAvService: FrivilligOpptattAvService,
val frivilligKoronaService: FrivilligKoronaService,
val postnummerService: PostnummerService
) {
fun hentAlle(
userId: UserId,
roller: Set<String>
) = hentFrivilligeUtFraMinRolle(roller, personService.getPerson(userId))
.map { Pair(it, personService.findById(it.personId)) }
.map {
FrivilligResponse(
frivillig = it.first,
person = PersonDTO.fra(it.second),
aktiviteter = aktivitetForFrivilligService.hent(it.first.id),
fylke = fylkeService.findById(it.second.fylke),
lokallag = lokallagService.findById(it.second.lokallag),
kontakt = kontaktService.hentKontakt(it.first.id),
opptattAv = frivilligOpptattAvService.hent(it.first.id),
frivilligKorona = frivilligKoronaService.hent(it.first.id)
)
}
private fun hentFrivilligeUtFraMinRolle(
roller: Set<String>,
ringer: Person
): List<Frivillig> =
when {
roller.contains(GenerellRolle.ADMIN) -> frivilligRepository.listAll()
roller.contains(RingespesifikkRolle.GODKJENNER) -> frivilligRepository.hentFrivilligeIFylket(ringer.fylke)
else -> frivilligRepository.hentFrivilligeILokallaget(ringer.lokallag)
}
fun registrerNyFrivillig(autentisertRequest: AutentisertRegistrerNyFrivilligRequest): Pair<Boolean, Frivillig> {
val request = autentisertRequest.request
val person = request.toPerson()
val id = personService.save(person, Oppdateringskilde.RegistrertFrivillig)
val personId = person.id?.toInt() ?: id.toInt()
if (frivilligRepository.count("personId", personId) > 0L) {
return Pair(false, frivilligRepository.find("personId", personId).firstResult())
}
val frivillig =
Frivillig(
personId = personId,
alleredeAktivILokallag = request.alleredeAktivILokallag,
medlemIRoedt = request.medlemIRoedt,
spesiellKompetanse = Emojifjerner.fjernEmojis(request.spesiellKompetanse),
andreTingDuVilBidraMed = Emojifjerner.fjernEmojis(request.andreTingDuVilBidraMed),
spraak = Emojifjerner.fjernEmojis(request.spraak),
fortellLittOmDegSelv = Emojifjerner.fjernEmojis(request.fortellLittOmDegSelv),
registrertTidspunkt = request.tidspunkt ?: Instant.now()
)
frivilligRepository.persist(frivillig)
request.kanTenkeSegAaBidraMedAktiviteter
.map { AktivitetForFrivillig(frivillig_id = frivillig.id.toInt(), aktivitet = it) }
.forEach { aktivitetForFrivilligService.persist(it) }
lagreOpptattAv(request, frivillig)
frivilligKoronaService.persist(
FrivilligKorona(
frivillig_id = frivillig.id,
haandtering = Emojifjerner.fjernEmojis(request.haandtering) ?: "",
personlig = request.personlig,
tydelig = Emojifjerner.fjernEmojis(request.tydelig) ?: "",
forslag = Emojifjerner.fjernEmojis(request.forslag) ?: ""
)
)
return Pair(true, frivillig)
}
private fun lagreOpptattAv(
request: RegistrerNyFrivilligRequest,
frivillig: Frivillig
) {
try {
request.opptattAv
.map { OpptattAv.valueOf(it) }
.map { FrivilligOpptattAv(frivillig_id = frivillig.id, opptattAv = it) }
.forEach { frivilligOpptattAvService.persist(it) }
} catch (ex: Exception) {
ex.printStackTrace()
}
}
private fun RegistrerNyFrivilligRequest.toPerson(): Person {
val postnr = postnummerService.findById(postnummer)
val lokallag = lokallagService.fromPostnummer(postnr)
val person =
Person(
hypersysID = null,
fornavn = fornavn,
etternavn = etternavn,
telefonnummer = telefonnummer,
email = epost,
postnummer = postnr,
fylke = fylkeService.getFylke(lokallag, postnr),
lokallag = lokallag,
groupID = RingesentralenGroupID.Frivillig.nr,
kilde = Kilde.Frivillig,
sistOppdatert = null
)
val eksisterendePerson = personService.finnPerson(person = person)
if (!RingesentralenGroupID.isBrukerEllerVenter(eksisterendePerson?.groupID() ?: -1)) {
eksisterendePerson?.setGroupID(RingesentralenGroupID.Frivillig)
}
return eksisterendePerson ?: person
}
fun hentAlleForAktivitet(
userId: UserId,
groups: Set<String>,
aktivitet: Aktivitet
) = hentAlle(userId, groups)
.filter { frivillig -> frivillig.aktiviteter.map { it.aktivitet }.contains(aktivitet) }
fun registrerNySoMeFrivillig(autentisertSoMeFrivilligRequest: AutentisertSoMeFrivilligRequest): Pair<Boolean, Frivillig> =
registrerNyFrivillig(
AutentisertRegistrerNyFrivilligRequest(
userId = autentisertSoMeFrivilligRequest.userId,
request =
RegistrerNyFrivilligRequest(
tidspunkt = Instant.now(),
fornavn = autentisertSoMeFrivilligRequest.request.fornavn,
etternavn = autentisertSoMeFrivilligRequest.request.etternavn,
telefonnummer = autentisertSoMeFrivilligRequest.request.telefonnummer,
postnummer = autentisertSoMeFrivilligRequest.request.postnummer,
alleredeAktivILokallag = false,
andreTingDuVilBidraMed = "Meldte seg direkte som SoMe-frivillig",
epost = autentisertSoMeFrivilligRequest.request.email ?: "",
forslag = "",
fortellLittOmDegSelv = "Meldte seg direkte som SoMe-frivillig",
haandtering = "",
kanTenkeSegAaBidraMedAktiviteter = listOf(Aktivitet.SoMe),
medlemIRoedt = ErMedlemStatus.Ukjent,
opptattAv = listOf(),
personlig = false,
spesiellKompetanse = "",
spraak = "",
tydelig = ""
)
)
)
fun finnFraPersonId(personId: Int): Optional<Frivillig> = frivilligRepository.find("personId", personId).firstResultOptional()
fun slett(id: Int) = frivilligRepository.deleteById(id)
}
| 17 | null | 0 | 1 | 3e04de69024fdf383a086309406eeed9d94608f2 | 8,254 | ringesentralen-backend | MIT License |
app/src/main/java/com/andreesperanca/deolhonobus/adapters/BusLineFavoriteAdapter.kt | andreesperanca | 532,135,124 | false | {"Kotlin": 76827} | package com.andreesperanca.deolhonobus.adapters
import android.view.LayoutInflater
import android.view.ViewGroup
import androidx.navigation.findNavController
import androidx.recyclerview.widget.RecyclerView.Adapter
import androidx.recyclerview.widget.RecyclerView.ViewHolder
import com.andreesperanca.deolhonobus.R
import com.andreesperanca.deolhonobus.databinding.RvBusLineFavoriteItemBinding
import com.andreesperanca.deolhonobus.models.BusLine
import com.andreesperanca.deolhonobus.ui.fragments.FavoriteFragmentDirections
class BusLineFavoriteAdapter() : Adapter<BusLineFavoriteAdapter.BusLineFavoriteViewHolder>() {
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): BusLineFavoriteViewHolder {
val inflater = LayoutInflater.from(parent.context)
val binding = RvBusLineFavoriteItemBinding.inflate(inflater, parent, false)
return BusLineFavoriteViewHolder(binding)
}
private var busLineList: List<BusLine> = emptyList()
override fun onBindViewHolder(holder: BusLineFavoriteViewHolder, position: Int) {
holder.bind(busLineList[position])
}
override fun getItemCount(): Int = busLineList.size
fun updateList(data: List<BusLine>?) {
data?.let {
busLineList = data
}
notifyItemChanged(busLineList.size)
}
inner class BusLineFavoriteViewHolder(private val binding: RvBusLineFavoriteItemBinding) :
ViewHolder
(binding.root) {
fun bind(busLine: BusLine) {
if (busLine.direction == 1) {
binding.tvOrigin.text =
binding.root.context.getString(R.string.origin, busLine.mainTerminal)
binding.tvDestination.text =
binding.root.context.getString(R.string.destination, busLine.secondaryTerminal)
} else {
binding.tvOrigin.text =
binding.root.context.getString(R.string.origin, busLine.secondaryTerminal)
binding.tvDestination.text =
binding.root.context.getString(R.string.destination, busLine.mainTerminal)
}
binding.tvNumberLine.text =
binding.root.context.getString(R.string.busNumber, busLine.firstLabel)
binding.root.setOnClickListener {
it.findNavController()
.navigate(FavoriteFragmentDirections.actionHomeFragmentToBusDetailsFragment(busLine))
}
}
}
} | 0 | Kotlin | 0 | 0 | 8dc20c6384b9232010a0786967f2e4d18584c572 | 2,487 | de-olho-no-bus | MIT License |
app/src/main/java/com/ivo/ganev/datamuse_kotlin/feature/adapter/HardConstraintAdapter.kt | ivoGanev | 319,790,467 | false | null | /**
* Copyright (C) 2020 Ivo Ganev
*
* 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.ivo.ganev.datamuse_kotlin.feature.adapter
import android.content.Context
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.BaseAdapter
import android.widget.SpinnerAdapter
import android.widget.TextView
import com.ivo.ganev.datamuse_kotlin.R
import com.ivo.ganev.datamuse_kotlin.feature.ConstraintElement.*
class HardConstraintAdapter(
context: Context,
) : BaseAdapter(), SpinnerAdapter {
/*
* The list is related only with this adapter and its read-only
* so there is no point to stay in the activity.
* */
val constraints = listOf(
MeansLikeElement, SoundsLikeElement, SpelledLikeElement, RelatedWordsElement
)
private val layoutInflater = LayoutInflater.from(context)
override fun getCount(): Int {
return constraints.size
}
override fun getItem(position: Int): Any {
return constraints[position]
}
override fun getItemId(position: Int): Long {
return position.toLong()
}
override fun getView(position: Int, convertView: View?, parent: ViewGroup?): View {
val view = convertView ?: layoutInflater.inflate(R.layout.spinner_item, parent, false)
val text = view.findViewById<TextView>(R.id.tv_spinner_item)
text?.text = constraints[position].label
return view
}
override fun getDropDownView(position: Int, convertView: View?, parent: ViewGroup?): View {
return getView(position, convertView, parent)
}
}
| 0 | Kotlin | 0 | 0 | bc0bc056d0288d6b445cc850d05ac8cdc5f22877 | 2,134 | datamuse-kotlin | Apache License 2.0 |
common/common_base/src/main/java/com/cl/common_base/init/AppInitializer.kt | aaaaaaaazmx | 528,318,389 | false | {"Kotlin": 3779032, "Java": 1498865} | package com.cl.common_base.init
import android.app.Application
import android.content.Context
import android.os.Build
import androidx.startup.Initializer
import com.alibaba.android.arouter.launcher.ARouter
import com.bhm.ble.BleManager
import com.bhm.ble.attribute.BleOptions
import com.bhm.demo.util.JavaAirBagConfig
import com.cl.common_base.util.crash.StabilityOptimize
import com.cl.common_base.BuildConfig
import com.cl.common_base.constants.Constants
import com.cl.common_base.help.BleConnectHandler
import com.orhanobut.logger.AndroidLogAdapter
import com.orhanobut.logger.Logger
import com.orhanobut.logger.PrettyFormatStrategy
import com.tencent.bugly.crashreport.CrashReport
import com.tencent.bugly.crashreport.CrashReport.UserStrategy
import com.tencent.mmkv.MMKV
import com.thingclips.smart.home.sdk.ThingHomeSdk
/**
* 可以手动初始化,因为有些第三方库,需要同意隐私协议之后才可以初始化
*/
class AppInitializer : Initializer<Unit> {
override fun create(context: Context) {
MMKV.initialize(context)
if (BuildConfig.DEBUG) { // 这两行必须写在init之前,否则这些配置在init过程中将无效
ARouter.openLog() // 打印日志
ARouter.openDebug() // 开启调试模式(如果在InstantRun模式下运行,必须开启调试模式!线上版本需要关闭,否则有安全风险)
}
ARouter.init(context.applicationContext as? Application)
initLogConfig()
// 涂鸦,需要同意隐私协议
ThingHomeSdk.init(
context.applicationContext as? Application,
"wxwdkkqchswudekgsrqv",
"t77armdv4h7ncx97akumfkht7jtpm4xh"
)
ThingHomeSdk.setDebugMode(true)
// bugly 初始化符合合规要求
val strategy = UserStrategy(context.applicationContext as? Application)
CrashReport.setIsDevelopmentDevice(context, BuildConfig.DEBUG) // 开发测试阶段设备为调试设备
CrashReport.initCrashReport(
context.applicationContext as? Application, "2d55fff670",
false,
strategy
)
// 蓝牙SDK初始化
(context.applicationContext as? Application)?.let {
BleManager.get().init(
it,
BleOptions.Builder()
.setBleConnectCallback(BleConnectHandler.connectCallBack)
.setScanMillisTimeOut(5000)
.setConnectMillisTimeOut(5000)
.setScanDeviceName(Constants.Ble.KEY_PH_DEVICE_NAME)
//一般不推荐autoSetMtu,因为如果设置的等待时间会影响其他操作
.setMtu(100, true)
.setAutoConnect(false) // 不自动重连
.setMaxConnectNum(Constants.Ble.KEY_BLE_MAX_CONNECT)
// .setConnectRetryCountAndInterval(2, 1000) // 掉线不重连
.build()
)
}
// crash兜底
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.CUPCAKE) {
if (!BuildConfig.DEBUG) {
StabilityOptimize.setUpJavaAirBag(mutableListOf<JavaAirBagConfig>().toList())
}
}
return Unit
}
/**
* 初始化日志
*/
private fun initLogConfig() {
val formatStrategy = PrettyFormatStrategy.newBuilder()
.showThreadInfo(false) // (Optional) Whether to show thread info or not. Default true
.methodCount(1) // (Optional) How many method line to show. Default 2
.methodOffset(2) // (Optional) Hides internal method calls up to offset. Default 5
.tag(Constants.APP_TAG) // (Optional) Global tag for every log. Default PRETTY_LOGGER
.build()
Logger.addLogAdapter(object : AndroidLogAdapter(formatStrategy) {
override fun isLoggable(priority: Int, tag: String?): Boolean {
return BuildConfig.DEBUG
}
})
}
override fun dependencies(): MutableList<Class<out Initializer<*>>> = mutableListOf()
} | 0 | Kotlin | 0 | 0 | 49a74a32c320a273dbe04c785af49f874f1d711b | 3,791 | abby | Apache License 2.0 |
drm-backend/src/main/kotlin/controller/UserController.kt | Smileslime47 | 738,883,139 | false | {"Kotlin": 26975, "Vue": 12723, "TypeScript": 6174, "CSS": 993, "HTML": 390} | package moe._47saikyo.controller
import com.auth0.jwt.JWT
import com.auth0.jwt.algorithms.Algorithm
import domain.Group
import domain.User
import io.ktor.server.application.*
import io.ktor.server.auth.*
import io.ktor.server.auth.jwt.*
import io.ktor.server.request.*
import io.ktor.server.response.*
import io.ktor.server.routing.*
import kotlinx.serialization.Serializable
import moe._47saikyo.constant.Constant
import moe._47saikyo.constant.HttpStatus
import moe._47saikyo.constant.getProperties
import moe._47saikyo.models.HttpResponse
import moe._47saikyo.service.UserService
import moe._47saikyo.constant.getProperty
import moe._47saikyo.plugins.security.authenticateAfterLogin
import moe._47saikyo.service.GroupService
import org.koin.java.KoinJavaComponent
import org.koin.java.KoinJavaComponent.inject
import java.util.*
/**
* User HTTP Controller
*
* @author 刘一邦
* @since 2024/01/05
*/
fun Application.userController() {
val userService: UserService by inject(UserService::class.java)
val groupService: GroupService by inject(GroupService::class.java)
val properties = getProperties()
routing {
route("/user") {
authenticateAfterLogin(Constant.Authentication.NEED_LOGIN) {
get {
//检查参数格式
val targetIdStr = call.request.queryParameters["id"]
if (targetIdStr == null || !targetIdStr.matches(Regex("[0-9]*"))) {
call.respond(HttpResponse(HttpStatus.INVALID_ARGUMENT))
return@get
}
//检查用户是否存在
val targetId = targetIdStr.toLong()
val targetUser = userService.getUser(targetId)
if (targetUser == null) {
call.respond(HttpResponse(HttpStatus.NOT_FOUND))
return@get
}
//检查该用户是否有展示权限
val loginId = call.principal<JWTPrincipal>()!!.payload.getClaim("userid")
if (!loginId.equals(targetId) && !groupService.authenticate(
targetUser.permissionId,
Group::permissionShowProfile
)
) {
call.respond(HttpResponse(HttpStatus(HttpStatus.Code.FORBIDDEN, "该用户无展示信息权限")))
return@get
}
call.respond(HttpResponse(HttpStatus.SUCCESS, targetUser))
}
}
post("/login") {
data class LoginForm(
val username: String,
val password: <PASSWORD>,
val rememberMe: Boolean,
)
val loginForm = call.receive<LoginForm>()
//检查用户合法性
val loginUser = userService.getUser(loginForm.username)
if (loginUser == null || loginUser.password != loginForm.password) {
call.respond(HttpResponse(HttpStatus.FORBIDDEN))
return@post
}
//检查用户组登陆权限
if (!groupService.authenticate(loginUser.permissionId, Group::permissionLogin)) {
call.respond(HttpResponse(HttpStatus(HttpStatus.Code.FORBIDDEN, "该用户组已被封禁")))
return@post
}
//签发jwt
val jwtSubject = properties.jwtSubject
val jwtIssuer = properties.jwtIssuer
val jwtAudience = properties.jwtAudience
val jwtSecret = properties.jwtSecret
val token = JWT.create()
//主题:Digital Right Manager Access License
.withSubject(jwtSubject)
//签发者:Digital Right Manager
.withIssuer(jwtIssuer)
//签发受众:Browser Application
.withAudience(jwtAudience)
//被签发人身份
.withClaim(Constant.Authentication.USER_ID_CLAIM, loginUser.id)
.withClaim(Constant.Authentication.GROUP_ID_CLAIM, loginUser.permissionId)
//签发日期
.withIssuedAt(Date(System.currentTimeMillis()))
//过期日期
.withExpiresAt(Date(System.currentTimeMillis() + 3600000))//一小时
.sign(Algorithm.HMAC256(jwtSecret))
call.respond(HttpResponse(HttpStatus.SUCCESS, token))
}
}
}
}
| 0 | Kotlin | 0 | 0 | bc395c4fbf8995febdae3a5652854127ce0aa46f | 4,557 | Digital-Rights-Management | MIT License |
paymentsheet-example/src/main/java/com/stripe/android/paymentsheet/example/playground/settings/PaymentMethodConfigurationSettingsDefinition.kt | stripe | 6,926,049 | false | {"Kotlin": 11740437, "Java": 70838, "Ruby": 22569, "Shell": 20293, "Python": 19910, "HTML": 7519} | package com.stripe.android.paymentsheet.example.playground.settings
import com.stripe.android.paymentsheet.example.playground.model.CheckoutRequest
internal object PaymentMethodConfigurationSettingsDefinition :
PlaygroundSettingDefinition<String>,
PlaygroundSettingDefinition.Saveable<String>,
PlaygroundSettingDefinition.Displayable<String> {
override val key: String = "paymentMethodConfigurationId"
override val displayName: String = "Payment Method Configuration ID"
override val defaultValue: String = ""
override val options: List<PlaygroundSettingDefinition.Displayable.Option<String>> = emptyList()
override fun convertToString(value: String): String = value
override fun convertToValue(value: String): String = value
override fun configure(
value: String,
checkoutRequestBuilder: CheckoutRequest.Builder,
) {
if (value.isNotEmpty()) {
checkoutRequestBuilder.paymentMethodConfigurationId(value)
}
}
}
| 133 | Kotlin | 625 | 1,217 | f6a4dec103efb8de39074d5643350f5bc21654ed | 1,005 | stripe-android | MIT License |
module/module-login/src/main/java/com/fm/module/login/LoginActivityMain.kt | Luo-DH | 425,160,566 | false | {"C++": 4599833, "C": 412084, "Java": 132679, "CMake": 95927, "Kotlin": 89758} | package com.fm.module.login
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import com.alibaba.android.arouter.facade.annotation.Route
import com.alibaba.android.arouter.launcher.ARouter
import com.fm.library.common.constants.RouterPath
@Route(path = RouterPath.Login.PAGE_LOGIN)
class LoginActivityMain : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.login_activity_main)
ARouter.getInstance().inject(this)
}
} | 0 | C++ | 0 | 2 | 343f948b68eabffb3ba05bb5b8488ecc5ac09caf | 559 | HelloFace-Android | Apache License 2.0 |
android/app/src/main/java/com/fabirt/debty/data/db/converter/BitmapConverter.kt | fabirt | 349,736,814 | false | {"Kotlin": 164948} | package com.fabirt.debty.data.db.converter
import android.graphics.Bitmap
import android.graphics.BitmapFactory
import androidx.room.TypeConverter
import java.io.ByteArrayOutputStream
class BitmapConverter {
@TypeConverter
fun toBitmap(bytes: ByteArray?): Bitmap? {
return bytes?.let {
BitmapFactory.decodeByteArray(it, 0, it.size)
}
}
@TypeConverter
fun fromBitmap(bitmap: Bitmap?): ByteArray? {
return bitmap?.let {
val outputStream = ByteArrayOutputStream()
it.compress(Bitmap.CompressFormat.JPEG, 50, outputStream)
outputStream.toByteArray()
}
}
} | 0 | Kotlin | 8 | 46 | fd9e7b97728f57c93104caa1c4c6ae70ff770ec7 | 659 | debty-v2 | MIT License |
span/src/main/java/me/reezy/cosmo/span/compat/QuoteCompatSpan.kt | czy1121 | 874,719,761 | false | null | package me.reezy.cosmo.span.compat
import android.graphics.Canvas
import android.graphics.Paint
import android.os.Parcel
import android.text.Layout
import android.text.ParcelableSpan
import android.text.style.LeadingMarginSpan
class QuoteCompatSpan : LeadingMarginSpan, ParcelableSpan {
private val color: Int
private val stripe: Int
private val gap: Int
constructor(color: Int, stripe: Int, gap: Int) {
this.color = color
this.stripe = stripe
this.gap = gap
}
constructor(src: Parcel) {
color = src.readInt()
stripe = src.readInt()
gap = src.readInt()
}
override fun getSpanTypeId(): Int {
return 9
}
override fun describeContents(): Int {
return 0
}
override fun writeToParcel(dest: Parcel, flags: Int) {
dest.writeInt(color)
dest.writeInt(stripe)
dest.writeInt(gap)
}
override fun getLeadingMargin(first: Boolean): Int {
return stripe + gap
}
override fun drawLeadingMargin(
c: Canvas, p: Paint, x: Int, dir: Int,
top: Int, baseline: Int, bottom: Int,
text: CharSequence, start: Int, end: Int,
first: Boolean, layout: Layout,
) {
val style = p.style
val color = p.color
p.style = Paint.Style.FILL
p.color = this.color
c.drawRect(x.toFloat(), top.toFloat(), (x + dir * stripe).toFloat(), bottom.toFloat(), p)
p.style = style
p.color = color
}
} | 0 | null | 0 | 3 | dded0412663cca0a0ef2cf665d7f0d45655f4466 | 1,513 | span | Apache License 2.0 |
src/plugin/SpriteEncodingType.kt | scape-tools | 230,707,611 | false | null | package plugin
enum class SpriteEncodingType(val id: Int, val displayName : String) {
HORIZONTAL(0, "Horizontal"),
VERTICAL(1, "Vertical");
override fun toString(): String {
return displayName
}
} | 0 | Kotlin | 3 | 1 | ee00e9fc5a710291696446350740310a1639f567 | 223 | scape-editor-vanilla-317-sprite-plugin | MIT License |
completable-reactor-graph-viewer-app/src/main/kotlin/ru/fix/completable/reactor/graph/viewer/app/FileWatcher.kt | ru-fix | 81,559,336 | false | null | package ru.fix.crudility.engine
import mu.KotlinLogging
import java.io.Closeable
import java.nio.file.FileSystems
import java.nio.file.Path
import java.nio.file.StandardWatchEventKinds
import java.util.concurrent.CompletableFuture
import java.util.concurrent.Executors
import java.util.concurrent.TimeUnit
import java.util.concurrent.atomic.AtomicBoolean
private val log = KotlinLogging.logger {}
class FileWatcher(private val filePath: Path,
private val callListenerAfterConstruction: Boolean = true,
private val listener: (Path) -> Any) : Closeable {
private val watchThread = Executors.newSingleThreadExecutor { Thread(it, javaClass.canonicalName) }
private val shutdownFlag = AtomicBoolean(false)
fun start(): CompletableFuture<Boolean> {
val feature = CompletableFuture<Boolean>()
watchThread.submit {
try {
FileSystems.getDefault().newWatchService().use {
log.info { "Watching for $filePath" }
filePath.parent.register(it, StandardWatchEventKinds.ENTRY_MODIFY)
if (callListenerAfterConstruction) {
listener(filePath)
}
feature.complete(true)
while (!shutdownFlag.get() || Thread.currentThread().isInterrupted) {
val watchKey = it.poll(5, TimeUnit.SECONDS) ?: continue
for (event in watchKey.pollEvents()) {
val entryFileNamePath = event.context() as Path
if (entryFileNamePath.fileName == filePath.fileName) {
if (event.kind() == StandardWatchEventKinds.ENTRY_MODIFY) {
log.trace { "Detected file modification: $filePath" }
listener.invoke(filePath)
}
}
}
if (!watchKey.reset()) {
log.warn { "maybe directory does not exist" }
break
}
}
}
} catch (exc: Exception) {
log.error(exc) { "Failed to watch for $filePath" }
feature.completeExceptionally(exc)
} finally {
feature.complete(false)
}
}
return feature
}
override fun close() {
shutdownFlag.set(true)
watchThread.shutdown()
if (!watchThread.awaitTermination(5, TimeUnit.SECONDS)) {
watchThread.shutdownNow()
}
}
} | 16 | null | 2 | 14 | 69aa01c9d2d046a195f609e703a3c554795d9c8d | 2,721 | completable-reactor | MIT License |
app/src/main/java/com/cwlarson/deviceid/di/AppModule.kt | opt05 | 370,757,069 | false | {"Kotlin": 765955} | package com.cwlarson.deviceid.di
import android.content.Context
import androidx.datastore.core.DataStore
import androidx.datastore.preferences.core.PreferenceDataStoreFactory
import androidx.datastore.preferences.core.Preferences
import androidx.datastore.preferences.preferencesDataStoreFile
import com.cwlarson.deviceid.settings.PreferenceManager
import com.cwlarson.deviceid.util.DispatcherProvider
import com.google.android.play.core.appupdate.AppUpdateManager
import com.google.android.play.core.appupdate.AppUpdateManagerFactory
import dagger.Module
import dagger.Provides
import dagger.hilt.InstallIn
import dagger.hilt.android.qualifiers.ApplicationContext
import dagger.hilt.components.SingletonComponent
import javax.inject.Singleton
@Module
@InstallIn(SingletonComponent::class)
object AppModule {
@Singleton
@Provides
fun providesDispatcherProvider(): DispatcherProvider = DispatcherProvider
@Provides
@Singleton
fun providesDataStore(@ApplicationContext context: Context): DataStore<Preferences> =
PreferenceDataStoreFactory.create { context.preferencesDataStoreFile("user_preferences") }
@Provides
@Singleton
fun providesPreferences(
dispatcherProvider: DispatcherProvider, @ApplicationContext context: Context,
dataStore: DataStore<Preferences>
): PreferenceManager =
PreferenceManager(dispatcherProvider, context, dataStore)
@Provides
@Singleton
fun providesAppManger(@ApplicationContext context: Context): AppUpdateManager =
AppUpdateManagerFactory.create(context)
} | 0 | Kotlin | 1 | 2 | 5e01e6b5356d3a2e80f7a102ecf513936b226269 | 1,580 | deviceid | MIT License |
app/src/main/java/br/com/lucaspires/tibiainfotracker/domain/usecase/support/SupportUseCaseImp.kt | lucaspiresdba | 363,201,525 | false | null | package br.com.lucaspires.tibiainfotracker.domain.usecase.support
import br.com.lucaspires.tibiainfotracker.domain.model.support.SupportModel
import br.com.lucaspires.tibiainfotracker.domain.repository.Repository
import io.reactivex.Single
internal class SupportUseCaseImp(private val repository: Repository) : SupportUseCase {
override fun getSuppSites(): Single<List<SupportModel>> {
return repository.getSuppSites()
}
} | 5 | Kotlin | 0 | 1 | f13dcded23bb3f21d605e71f003099d228d97daf | 440 | tibiainfotracker_public | Apache License 2.0 |
video-sdk/src/test/java/com/kaleyra/video_sdk/ui/call/callaction/AnswerActionTest.kt | KaleyraVideo | 686,975,102 | false | {"Kotlin": 5207104, "Shell": 7470, "Python": 6799, "Java": 2583} | package com.kaleyra.video_sdk.ui.call.callaction
import androidx.activity.ComponentActivity
import androidx.compose.ui.Modifier
import androidx.compose.ui.platform.testTag
import androidx.compose.ui.test.assertIsEnabled
import androidx.compose.ui.test.assertWidthIsEqualTo
import androidx.compose.ui.test.junit4.createAndroidComposeRule
import androidx.compose.ui.test.onNodeWithTag
import androidx.compose.ui.test.onNodeWithText
import androidx.compose.ui.test.performClick
import com.kaleyra.video_sdk.R
import com.kaleyra.video_sdk.call.bottomsheet.view.sheetcontent.sheetitemslayout.SheetItemsSpacing
import com.kaleyra.video_sdk.call.callactions.view.AnswerAction
import com.kaleyra.video_sdk.call.callactions.view.AnswerActionExtendedMultiplier
import com.kaleyra.video_sdk.call.callactions.view.AnswerActionMultiplier
import com.kaleyra.video_sdk.call.callactions.view.CallActionDefaults
import org.junit.Assert
import org.junit.Rule
import org.junit.Test
import org.junit.runner.RunWith
import org.robolectric.RobolectricTestRunner
@RunWith(RobolectricTestRunner::class)
class AnswerActionTest {
@get:Rule
val composeTestRule = createAndroidComposeRule<ComponentActivity>()
@Test
fun testDefaultButton() {
val testTag = "testTag"
composeTestRule.setContent {
AnswerAction(
extended = false,
onClick = { },
modifier = Modifier.testTag(testTag)
)
}
val width = CallActionDefaults.MinButtonSize * AnswerActionMultiplier + SheetItemsSpacing
composeTestRule.onNodeWithTag(testTag).assertWidthIsEqualTo(width)
}
@Test
fun testExtendedButton() {
val testTag = "testTag"
composeTestRule.setContent {
AnswerAction(
extended = true,
onClick = { },
modifier = Modifier.testTag(testTag)
)
}
val width = CallActionDefaults.MinButtonSize * AnswerActionExtendedMultiplier + SheetItemsSpacing * (AnswerActionExtendedMultiplier - 1)
composeTestRule.onNodeWithTag(testTag).assertWidthIsEqualTo(width)
}
@Test
fun testOnClickInvoked() {
val text = composeTestRule.activity.getString(R.string.kaleyra_call_sheet_answer)
var clicked = false
composeTestRule.setContent {
AnswerAction(onClick = { clicked = true }, extended = true)
}
composeTestRule.onNodeWithText(text).assertIsEnabled()
composeTestRule.onNodeWithText(text).performClick()
Assert.assertEquals(true, clicked)
}
} | 0 | Kotlin | 0 | 1 | 9faa41e5903616889f2d0cd79ba21e18afe800ed | 2,606 | VideoAndroidSDK | Apache License 2.0 |
app/src/main/java/jp/co/archive/copo/ui/eventList/EventListViewModel.kt | vkdlxh | 272,697,015 | false | null | package jp.co.archive.copo.ui.eventList
import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import jp.co.archive.copo.data.model.Event
import jp.co.archive.copo.data.model.Result
import jp.co.archive.copo.data.repository.FirabaseRepository
import java.lang.Exception
class EventListViewModel(
private val repository: FirabaseRepository
) : ViewModel() {
private val _eventList: MutableLiveData<List<Event>> = MutableLiveData()
val eventList: LiveData<List<Event>>
get() = _eventList
fun getEventList() {
repository.getEventList(object : Result<List<Event>> {
override fun onSuccess(response: List<Event>) {
_eventList.value = response
}
override fun onFailure(e: Exception) {
TODO("Not yet implemented")
}
})
}
} | 1 | Kotlin | 0 | 0 | 03d516787c84429a49824266736da32f465e4573 | 906 | COPO_Android | MIT License |
packages/SystemUI/tests/src/com/android/systemui/screenrecord/ScreenRecordDialogTest.kt | liu-wanshun | 595,904,109 | true | null | /*
* Copyright (C) 2022 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/*
* Copyright (C) 2022 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.android.systemui.screenrecord
import android.testing.AndroidTestingRunner
import android.testing.TestableLooper
import android.view.View
import androidx.test.filters.SmallTest
import com.android.systemui.R
import com.android.systemui.SysuiTestCase
import com.android.systemui.animation.DialogLaunchAnimator
import com.android.systemui.flags.FeatureFlags
import com.android.systemui.flags.Flags
import com.android.systemui.plugins.ActivityStarter
import com.android.systemui.settings.UserContextProvider
import com.google.common.truth.Truth.assertThat
import org.junit.After
import org.junit.Before
import org.junit.Test
import org.junit.runner.RunWith
import org.mockito.Mock
import org.mockito.MockitoAnnotations
import org.mockito.Mockito.`when` as whenever
@SmallTest
@RunWith(AndroidTestingRunner::class)
@TestableLooper.RunWithLooper(setAsMainLooper = true)
class ScreenRecordDialogTest : SysuiTestCase() {
@Mock
private lateinit var starter: ActivityStarter
@Mock
private lateinit var controller: RecordingController
@Mock
private lateinit var userContextProvider: UserContextProvider
@Mock
private lateinit var flags: FeatureFlags
@Mock
private lateinit var dialogLaunchAnimator: DialogLaunchAnimator
@Mock
private lateinit var onStartRecordingClicked: Runnable
private lateinit var dialog: ScreenRecordDialog
@Before
fun setUp() {
MockitoAnnotations.initMocks(this)
dialog = ScreenRecordDialog(
context, controller, starter, userContextProvider, flags, dialogLaunchAnimator,
onStartRecordingClicked
)
}
@After
fun teardown() {
if (::dialog.isInitialized) {
dialog.dismiss()
}
}
@Test
fun testShowDialog_partialScreenSharingDisabled_appButtonIsNotVisible() {
whenever(flags.isEnabled(Flags.WM_ENABLE_PARTIAL_SCREEN_SHARING)).thenReturn(false)
dialog.show()
val visibility = dialog.requireViewById<View>(R.id.button_app).visibility
assertThat(visibility).isEqualTo(View.GONE)
}
@Test
fun testShowDialog_partialScreenSharingEnabled_appButtonIsVisible() {
whenever(flags.isEnabled(Flags.WM_ENABLE_PARTIAL_SCREEN_SHARING)).thenReturn(true)
dialog.show()
val visibility = dialog.requireViewById<View>(R.id.button_app).visibility
assertThat(visibility).isEqualTo(View.VISIBLE)
}
}
| 0 | Java | 1 | 2 | e99201cd9b6a123b16c30cce427a2dc31bb2f501 | 3,689 | platform_frameworks_base | Apache License 2.0 |
universalview/src/main/java/com/weimu/universalview/helper/SMSCountDownTimer.kt | caoyanglee | 158,797,807 | false | {"Gradle": 4, "Java Properties": 2, "Shell": 1, "Ignore List": 3, "Batchfile": 1, "Markdown": 2, "Proguard": 2, "Text": 1, "Git Attributes": 1, "XML": 47, "Kotlin": 108, "Java": 1} | package com.weimu.universalview.helper
import android.os.CountDownTimer
import android.widget.TextView
//短信倒计时
class SMSCountDownTimer(
var tv_send_code: TextView? = null,
val countDownSecond: Int = 60
) {
private var cd: CountDownTimer
var getCodeIng = false//正在获取验证码中
init {
cd = object : CountDownTimer((countDownSecond * 1000).toLong(), 1000) {
override fun onTick(l: Long) {
val str = "重新发送(${l / 1000}s)"
tv_send_code?.text = str
}
override fun onFinish() {
endCountTime()
}
}
}
//开始倒计时
fun startCountTime() {
getCodeIng = true
tv_send_code?.isEnabled = false
cd.start()
}
//结束倒计时
fun endCountTime() {
cd.cancel()
getCodeIng = false
tv_send_code?.text = "获取验证码"
tv_send_code?.isEnabled = true
}
}
| 1 | null | 1 | 1 | ca104f46225f3c8b17ffd4143516da95aeb5f0a8 | 936 | universalui | Apache License 2.0 |
trackerSdk/src/main/java/com/crossclassify/trackersdk/data/config/Api.kt | crossclassify | 503,334,079 | false | {"Java": 324126, "Kotlin": 119052} | package com.crossclassify.trackersdk.data.config
import android.content.Context
import com.chuckerteam.chucker.api.ChuckerInterceptor
import com.crossclassify.trackersdk.data.dao.ApiInterface
import com.crossclassify.trackersdk.utils.base.TrackerSdkApplication
import com.hrg.variables.Variables
import okhttp3.Interceptor
import okhttp3.OkHttpClient
import okhttp3.logging.HttpLoggingInterceptor
import retrofit2.Retrofit
import retrofit2.converter.gson.GsonConverterFactory
object Api {
private var baseUrl = "https://api.crossclassify.com/collect/"
private var client: ApiInterface? = null
fun client(context: Context): ApiInterface {
return if (client == null) {
val interceptor by lazy {
Interceptor { chain ->
val builder = chain.request().newBuilder()
builder
.addHeader("User-Agent", TrackerSdkApplication.userAgent)
.addHeader("x-api-key", Variables.token)
.addHeader(
"Content-Type",
"application/x-www-form-urlencoded; charset=utf-8"
)
.addHeader("Connection", "keep-alive")
chain.proceed(builder.build())
}
}
val loggingInterceptor = HttpLoggingInterceptor().apply {
level = HttpLoggingInterceptor.Level.HEADERS
}
val okHttpClient: OkHttpClient = OkHttpClient.Builder().addInterceptor(
ChuckerInterceptor.Builder(context)
.build()
).addInterceptor(interceptor).addInterceptor(loggingInterceptor)
.build()
val retrofit: Retrofit = Retrofit.Builder()
.baseUrl(baseUrl)
.addConverterFactory(GsonConverterFactory.create())
.client(okHttpClient)
.build()
client = retrofit.create(ApiInterface::class.java)
client!!
} else {
client!!
}
}
} | 1 | null | 1 | 1 | de70e51725ad04edb456a0384a15ce966262e034 | 2,111 | xc-sdk-android | Apache License 2.0 |
platf-w3c/src/jsMain/kotlin/org/jetbrains/letsPlot/platf/w3c/mapping/svg/mapper/css/CssDisplay.kt | JetBrains | 176,771,727 | false | null | /*
* Copyright (c) 2023. JetBrains s.r.o.
* Use of this source code is governed by the MIT license that can be found in the LICENSE file.
*/
package org.jetbrains.letsPlot.platf.w3c.mapping.svg.css
object CssDisplay {
const val DEFAULT = "default"
const val NONE = "none"
const val BLOCK = "block"
const val FLEX = "flex"
const val GRID = "grid"
const val INLINE_BLOCK = "inline-block"
}
| 97 | Kotlin | 47 | 889 | c5c66ceddc839bec79b041c06677a6ad5f54e416 | 418 | lets-plot | MIT License |
vuesaxicons/src/commonMain/kotlin/moe/tlaster/icons/vuesax/vuesaxicons/crypto/bulk/Hederahashgraph.kt | Tlaster | 560,394,734 | false | {"Kotlin": 25133302} | package moe.tlaster.icons.vuesax.vuesaxicons.crypto.bulk
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.PathFillType
import androidx.compose.ui.graphics.PathFillType.Companion.NonZero
import androidx.compose.ui.graphics.SolidColor
import androidx.compose.ui.graphics.StrokeCap
import androidx.compose.ui.graphics.StrokeCap.Companion.Butt
import androidx.compose.ui.graphics.StrokeCap.Companion.Round
import androidx.compose.ui.graphics.StrokeJoin
import androidx.compose.ui.graphics.StrokeJoin.Companion.Miter
import androidx.compose.ui.graphics.vector.ImageVector
import androidx.compose.ui.graphics.vector.ImageVector.Builder
import androidx.compose.ui.graphics.vector.path
import androidx.compose.ui.unit.dp
import moe.tlaster.icons.vuesax.vuesaxicons.crypto.BulkGroup
public val BulkGroup.Hederahashgraph: ImageVector
get() {
if (_hederahashgraph != null) {
return _hederahashgraph!!
}
_hederahashgraph = Builder(name = "Hederahashgraph", defaultWidth = 24.0.dp, defaultHeight =
24.0.dp, viewportWidth = 24.0f, viewportHeight = 24.0f).apply {
path(fill = SolidColor(Color(0x00000000)), stroke = SolidColor(Color(0xFF292D32)),
strokeLineWidth = 1.5f, strokeLineCap = Round, strokeLineJoin =
StrokeJoin.Companion.Round, strokeLineMiter = 4.0f, pathFillType = NonZero) {
moveTo(7.5f, 17.4001f)
verticalLineTo(6.6001f)
}
path(fill = SolidColor(Color(0x00000000)), stroke = SolidColor(Color(0xFF292D32)),
strokeLineWidth = 1.5f, strokeLineCap = Round, strokeLineJoin =
StrokeJoin.Companion.Round, strokeLineMiter = 4.0f, pathFillType = NonZero) {
moveTo(7.5f, 9.7559f)
horizontalLineTo(16.5f)
}
path(fill = SolidColor(Color(0xFF292D32)), stroke = null, fillAlpha = 0.4f, strokeAlpha
= 0.4f, strokeLineWidth = 0.0f, strokeLineCap = Butt, strokeLineJoin = Miter,
strokeLineMiter = 4.0f, pathFillType = NonZero) {
moveTo(12.0f, 24.0f)
curveTo(18.6274f, 24.0f, 24.0f, 18.6274f, 24.0f, 12.0f)
curveTo(24.0f, 5.3726f, 18.6274f, 0.0f, 12.0f, 0.0f)
curveTo(5.3726f, 0.0f, 0.0f, 5.3726f, 0.0f, 12.0f)
curveTo(0.0f, 18.6274f, 5.3726f, 24.0f, 12.0f, 24.0f)
close()
}
path(fill = SolidColor(Color(0xFF292D32)), stroke = null, strokeLineWidth = 0.0f,
strokeLineCap = Butt, strokeLineJoin = Miter, strokeLineMiter = 4.0f,
pathFillType = NonZero) {
moveTo(16.4996f, 18.3002f)
curveTo(16.0076f, 18.3002f, 15.5996f, 17.8922f, 15.5996f, 17.4002f)
verticalLineTo(6.6002f)
curveTo(15.5996f, 6.1082f, 16.0076f, 5.7002f, 16.4996f, 5.7002f)
curveTo(16.9916f, 5.7002f, 17.3996f, 6.1082f, 17.3996f, 6.6002f)
verticalLineTo(17.4002f)
curveTo(17.3996f, 17.8922f, 16.9916f, 18.3002f, 16.4996f, 18.3002f)
close()
}
path(fill = SolidColor(Color(0xFF292D32)), stroke = null, strokeLineWidth = 0.0f,
strokeLineCap = Butt, strokeLineJoin = Miter, strokeLineMiter = 4.0f,
pathFillType = NonZero) {
moveTo(16.5001f, 15.1437f)
horizontalLineTo(7.5001f)
curveTo(7.0081f, 15.1437f, 7.6001f, 14.7357f, 7.6001f, 14.2437f)
curveTo(7.6001f, 13.7517f, 7.0081f, 13.3438f, 7.5001f, 13.3438f)
horizontalLineTo(16.5001f)
curveTo(16.9921f, 13.3438f, 17.4001f, 13.7517f, 17.4001f, 14.2437f)
curveTo(17.4001f, 14.7357f, 16.9921f, 15.1437f, 16.5001f, 15.1437f)
close()
}
}
.build()
return _hederahashgraph!!
}
private var _hederahashgraph: ImageVector? = null
| 0 | Kotlin | 0 | 2 | b8a8231e6637c2008f675ae76a3423b82ee53950 | 4,062 | VuesaxIcons | MIT License |
app/src/main/java/com/example/androiddevchallenge/data/Puppy.kt | SrikantKanekar | 342,564,602 | false | null | /*
* Copyright 2021 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.example.androiddevchallenge.data
data class Puppy(
val id: Int,
val name: String,
val breed: String,
val imageId: Int,
val color: String,
val age: String,
val gender: String,
val address: String,
val distance: String,
val status: String,
val time: String
)
object Breed {
const val ALL = "ALL"
const val PUG = "Pug"
const val BEAGLE = "Beagle"
const val SAMOYED = "Samoyed"
const val SHAR_PEI = "<NAME>"
const val JACK_RUSSELL_TERRIER = "<NAME>"
const val POMERANIAN = "Pomeranian"
const val GOLDEN_RETRIEVER = "Golden Retriever"
const val DACHSHUND = "Dachshund"
const val SAINT_BERNARD = "<NAME>"
const val DALMATIAN = "Dalmatian"
fun categories(): MutableList<String> {
return mutableListOf(
ALL,
PUG,
BEAGLE,
SAMOYED,
SHAR_PEI,
JACK_RUSSELL_TERRIER,
POMERANIAN,
GOLDEN_RETRIEVER,
DACHSHUND,
SAINT_BERNARD,
DALMATIAN
)
}
}
object Gender {
const val MALE = "MALE"
const val FEMALE = "FEMALE"
}
object Status {
const val AVAILABLE = "AVAILABLE"
const val ADOPTED = "ADOPTED"
}
| 0 | Kotlin | 0 | 0 | 7708c9b3672f1c25d85b546949ecde3ab000449c | 1,871 | PuppyAdoptionApp-Android | Apache License 2.0 |
droid-dex/src/main/kotlin/com/blinkit/droiddex/factory/base/PerformanceManager.kt | grofers | 761,605,614 | false | {"Kotlin": 44720, "Shell": 448} | package com.blinkit.droiddex.factory.base
import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import com.blinkit.droiddex.constants.PerformanceClass
import com.blinkit.droiddex.constants.PerformanceLevel
import com.blinkit.droiddex.utils.Logger
import com.blinkit.droiddex.utils.runAsyncPeriodically
import kotlin.concurrent.Volatile
internal abstract class PerformanceManager(private val isInDebugMode: Boolean) {
@Volatile
var performanceLevel = PerformanceLevel.UNKNOWN
private set
private val _performanceLevelLd = MutableLiveData(PerformanceLevel.UNKNOWN)
val performanceLevelLd: LiveData<PerformanceLevel>
get() = _performanceLevelLd
protected val logger by lazy { Logger(isInDebugMode, getPerformanceClass()) }
fun init() {
runAsyncPeriodically({
try {
measurePerformanceLevel().also {
val hasPerformanceLevelChanged = performanceLevelLd.value != it
if (hasPerformanceLevelChanged) {
performanceLevel = it
_performanceLevelLd.postValue(it)
}
logger.logPerformanceLevelChange(it, hasPerformanceLevelChanged)
}
} catch (e: Exception) {
logger.logError(e)
}
}, delayInSecs = getDelayInSecs())
}
@PerformanceClass
protected abstract fun getPerformanceClass(): Int
protected abstract fun getDelayInSecs(): Float
protected abstract fun measurePerformanceLevel(): PerformanceLevel
protected fun logInfo(message: String) = logger.logInfo(message)
protected fun logDebug(message: String) = logger.logDebug(message)
protected fun logError(throwable: Throwable) = logger.logError(throwable)
}
| 0 | Kotlin | 0 | 1 | 7d4250dd75d6dc47c1426f994a98ac949d537acb | 1,601 | droid-dex | Apache License 2.0 |
app/src/main/java/com/example/bitfit/ListFetcher.kt | SDAxium | 551,707,380 | false | null | package com.example.bitfit
class ListFetcher {
companion object {
var foodList: MutableList<DisplayFood> = ArrayList()
fun GetFoodList(): MutableList<DisplayFood> {
return foodList
}
fun AddToFoodList(food:DisplayFood):MutableList<DisplayFood>{
foodList.add(food)
return foodList
}
}
} | 2 | Kotlin | 0 | 0 | 9a970900d5c4646bc2cfa74415c9f2a662c4f39c | 372 | BitFit | Apache License 2.0 |
code-reader-kt/src/main/java/com/loopeer/codereaderkt/ui/view/Checker.kt | loopeer | 64,836,918 | false | null | package com.loopeer.codereaderkt.ui.view
abstract class Checker(internal var mCheckObserver: CheckObserver) {
interface CheckObserver {
fun check(b: Boolean)
}
internal abstract val isEnable: Boolean
}
| 5 | null | 152 | 934 | 075007d1827b39280111dbe767a1d64484f816f6 | 224 | code-reader | Apache License 2.0 |
mobile/src/main/java/com/siliconlabs/bledemo/features/demo/esl_demo/fragments/QrCodeScannerFragment.kt | SiliconLabs | 85,345,875 | false | null | package com.siliconlabs.bledemo.features.demo.esl_demo.fragments
import android.os.Bundle
import android.view.View
import android.widget.Toast
import androidx.fragment.app.Fragment
import androidx.fragment.app.FragmentActivity
import by.kirich1409.viewbindingdelegate.viewBinding
import com.budiyev.android.codescanner.AutoFocusMode
import com.budiyev.android.codescanner.CodeScanner
import com.budiyev.android.codescanner.DecodeCallback
import com.budiyev.android.codescanner.ErrorCallback
import com.budiyev.android.codescanner.ScanMode
import com.google.zxing.BarcodeFormat
import com.siliconlabs.bledemo.R
import com.siliconlabs.bledemo.databinding.FragmentEslQrScanBinding
import com.siliconlabs.bledemo.features.demo.esl_demo.activities.EslDemoActivity
import com.siliconlabs.bledemo.features.demo.esl_demo.model.QrCodeData
class QrCodeScannerFragment : Fragment(R.layout.fragment_esl_qr_scan) {
private val binding by viewBinding(FragmentEslQrScanBinding::bind)
private lateinit var codeScanner: CodeScanner
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
initCodeScanner()
}
override fun onPause() {
super.onPause()
codeScanner.also {
it.stopPreview()
it.releaseResources()
}
}
override fun onResume() {
super.onResume()
codeScanner.startPreview()
}
private fun initCodeScanner() {
activity?.let { activity ->
codeScanner = CodeScanner(activity, binding.scannerView).apply {
camera = CodeScanner.CAMERA_BACK
formats = listOf(BarcodeFormat.QR_CODE)
autoFocusMode = AutoFocusMode.SAFE
scanMode = ScanMode.SINGLE
isAutoFocusEnabled = true
isFlashEnabled = false
decodeCallback = DecodeCallback {
val qrCodeData = QrCodeData.decode(it.text)
if (qrCodeData.isValid()) {
(activity as EslDemoActivity).handleScannedQrCode(qrCodeData)
} else {
showLongToast(getString(R.string.qr_code_unrecognized))
}
exitScannerFragment(activity)
}
errorCallback = ErrorCallback {
showLongToast(getString(R.string.qr_scan_error,it.message ?: "unknown"))
exitScannerFragment(activity)
}
}
}
}
private fun exitScannerFragment(activity: FragmentActivity) {
activity.supportFragmentManager.popBackStack()
activity.runOnUiThread {
(activity as EslDemoActivity).toggleFullscreen(toggleOn = false)
}
}
private fun showLongToast(message: String) {
context?.let {
activity?.runOnUiThread {
Toast.makeText(it, message, Toast.LENGTH_LONG).show()
}
}
}
} | 10 | Kotlin | 54 | 96 | 2d3bc7b9fe358bc2f8b988479acfd8fc40794101 | 3,023 | EFRConnect-android | Apache License 2.0 |
app/src/main/java/com/weather/android/logic/model/PlaceResponse.kt | RSL45 | 284,571,865 | false | null | package com.weather.android.logic.model
import com.google.gson.annotations.SerializedName
/*地址查询*/
data class PlaceResponse(val status:String,val places:List<Place>)
data class Place(val id:String,val name:String,val location:Location,@SerializedName("formatted_address") val address:String)
data class Location(val lng:String,val lat:String) | 0 | Kotlin | 0 | 0 | c951b2bbc40e984117f4cd9f162ba5fe2478d962 | 346 | Weather | Apache License 2.0 |
app/src/main/java/com/projectseoul/stockmarkettest/recyclerview/ItemRecyclerViewAdapter.kt | kingjinho | 411,890,525 | false | {"Kotlin": 286299} | package com.projectseoul.stockmarkettest.recyclerview
import android.view.ViewGroup
import androidx.recyclerview.widget.DiffUtil
import androidx.recyclerview.widget.ListAdapter
import com.projectseoul.stockmarkettest.models.*
import com.projectseoul.stockmarkettest.screens.main.ScreenMainMvc
import com.projectseoul.stockmarkettest.utils.Const
/**
* Created by <NAME> on 9/18/2021
*/
class ItemRecyclerViewAdapter<T : Any>(
private val items: List<T>,
private val areItemsTheSame: (oldItem: T, newItem: T) -> Boolean,
private val areContentsTheSame: (oldItem: T, newItem: T) -> Boolean,
private val listener: ScreenMainMvc.ItemClickListener? = null
) :
ListAdapter<T, BaseViewHolder>(
object : DiffUtil.ItemCallback<T>() {
override fun areItemsTheSame(oldItem: T, newItem: T): Boolean {
return areItemsTheSame(oldItem, newItem)
}
override fun areContentsTheSame(oldItem: T, newItem: T): Boolean {
return areContentsTheSame(oldItem, newItem)
}
}
) {
override fun getItemViewType(position: Int): Int {
return when (items[position]) {
is StockByFluctuation ->
Const.LAYOUT_STOCK_FLUCTUATION_SHORT
is StockByTransaction ->
Const.LAYOUT_STOCK_TRANSACTION_SHORT
is StockByMarketCap ->
Const.LAYOUT_STOCK_MARKET_CAP_SHORT
is StockByUpperLowerLimit ->
Const.LAYOUT_STOCK_UPPER_LOWER_LIMIT_SHORT
is StockByForeigner ->
Const.LAYOUT_STOCK_FOREIGNER_SHORT
is StockByTurnover ->
Const.LAYOUT_STOCK_TURNOVER_SHORT
is StockByBlockDeal ->
Const.LAYOUT_STOCK_BLOCK_DEAL_SHORT
is Grain ->
Const.LAYOUT_GRAIN_SHORT
is CrudeOil ->
Const.LAYOUT_OIL_SHORT
is BDIIndex ->
Const.LAYOUT_BALTIC_INDICES_SHORT
is StockBaseInfo ->
Const.LAYOUT_STOCK_BASIC_INFO
is StockFinancialStatement ->
Const.LAYOUT_STOCK_FINANCIAL_STATEMENT
is MonthlyTrading ->
Const.LAYOUT_MONTHLY_TRADING
is List<*> ->
Const.LAYOUT_STOCK_SINGLE_LINE_CHART
else -> {
throw IllegalArgumentException("item type should match one of listed")
}
}
}
override fun getItemCount() = items.size
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): BaseViewHolder {
return ItemViewHolderFactory.createByViewType(parent, viewType, listener)
}
override fun onBindViewHolder(holder: BaseViewHolder, position: Int) {
items[position].let {
holder.bind(it)
}
}
} | 0 | Kotlin | 0 | 0 | d9335f4953eb6b02312365d4f11da6e675e7d291 | 2,848 | burst-out-your-greed | Apache License 2.0 |
pocket-api/src/main/kotlin/com/uwefuchs/demo/kotlin/pocket/api/Sort.kt | Uwe-Fuchs | 608,285,178 | false | null | package com.uwefuchs.demo.kotlin.pocket.api
/**
* The sorting of a collection of pocket-items
*/
enum class Sort(private val value: String) {
NEWEST("newest"), OLDEST("oldest"), TITLE("title"), SITE("site")
} | 0 | Kotlin | 0 | 0 | b60a64000642ed940c93e3f1466b55855afa4ede | 215 | my-janitor | Apache License 2.0 |
src/main/kotlin/com/bh/planners/core/kether/compat/adyeshach/ActionAdyeshachSpawn.kt | postyizhan | 754,476,430 | false | {"Kotlin": 652703, "Java": 215} | package com.bh.planners.core.kether.compat.adyeshach
import com.bh.planners.api.common.SimpleTimeoutTask
import com.bh.planners.api.entity.ProxyAdyeshachEntity
import com.bh.planners.api.entity.ProxyEntity
import com.bh.planners.core.effect.Target
import com.bh.planners.core.effect.Target.Companion.target
import com.bh.planners.core.kether.containerOrOrigin
import com.bh.planners.util.safeSync
import ink.ptms.adyeshach.api.AdyeshachAPI
import ink.ptms.adyeshach.common.entity.EntityInstance
import ink.ptms.adyeshach.common.entity.EntityTypes
import org.bukkit.Location
import taboolib.library.kether.ParsedAction
import taboolib.module.kether.*
import java.util.*
import java.util.concurrent.CompletableFuture
import java.util.function.Consumer
class ActionAdyeshachSpawn : ScriptAction<Target.Container>() {
lateinit var type: ParsedAction<*>
lateinit var name: ParsedAction<*>
lateinit var timeout: ParsedAction<*>
var selector: ParsedAction<*>? = null
fun spawn(entityType: EntityTypes, locations: List<Location>, name: String, tick: Long): CompletableFuture<List<ProxyEntity>> {
val future = CompletableFuture<List<ProxyEntity>>()
spawn(entityType, locations, block = { it.setCustomName(name) }).thenAccept {
it.forEach { register(it, tick) }
future.complete(it)
}
return future
}
fun spawn(entityType: EntityTypes, locations: List<Location>, block: Consumer<EntityInstance>): CompletableFuture<List<ProxyAdyeshachEntity>> {
val future = CompletableFuture<List<ProxyAdyeshachEntity>>()
safeSync {
future.complete(locations.map { spawn(entityType, it, block) })
}
return future
}
fun spawn(entityType: EntityTypes, location: Location, block: Consumer<EntityInstance>): ProxyAdyeshachEntity {
return ProxyAdyeshachEntity(AdyeshachAPI.getEntityManagerPublicTemporary().create(entityType, location, block))
}
fun register(entity: ProxyAdyeshachEntity, tick: Long): String {
// 注册销毁任务
SimpleTimeoutTask.createSimpleTask(tick, true) {
if (!entity.isDeleted) {
entity.instance.delete()
}
}
return "ady:${entity.uniqueId}"
}
override fun run(frame: ScriptFrame): CompletableFuture<Target.Container> {
val container = Target.Container()
val future = CompletableFuture<Target.Container>()
frame.run(type).str {
val type = EntityTypes.valueOf(it.uppercase(Locale.getDefault()))
frame.run(name).str { name ->
frame.run(timeout).long { timeout ->
frame.containerOrOrigin(selector).thenAccept {
val locations = it.filterIsInstance<Target.Location>().map { it.value }
spawn(type, locations, name, timeout).thenAccept {
container += it.map { it.target() }
future.complete(container)
}
}
}
}
}
return future
}
} | 0 | Kotlin | 1 | 0 | dea343908592d722cd03d9dbadbc659372131dfe | 3,127 | planners | Creative Commons Zero v1.0 Universal |
kbomber-collections/src/main/kotlin/kbomber/collections/values/MutableLoadableValue.kt | LM-96 | 517,382,094 | false | {"Kotlin": 253830} | package kbomber.collections.values
/**
* Represents a value that **could** be loaded.
* This class extends [LoadableValue] exposing methods that allow
* to load, reload or unload the value.
*/
class MutableLoadableValue<T>() : LoadableValue<T>() {
internal constructor(value : T?, status : LoadStatus, error : Exception?) : this() {
this.value = value
this.status = status
this.error = error
}
/**
* Applies the loader passed as parameter putting its result
* into this object. Notice that **if the loader throws an exception,
* it will be stored into [error] var** of this object and the
* status will be [LoadStatus.NOT_FOUND].
* Otherwise, if all goes good, the result is stored into [value] and the
* status will be [LoadStatus.LOADED].
* **If the values has previously been loaded, this method throws an exception** because
* it is not possible to use it to reload the value (see [loadOrReload] or [reload])
* @throws IllegalStateException if the value is already loaded
* @return this object after the `loader` was applied
*/
fun load(loader : () -> T) : MutableLoadableValue<T> {
if(status != LoadStatus.UNTOUCHED)
throw IllegalStateException("Value is already loaded")
return loadOrReload(loader)
}
/**
* Applies the loader passed as parameter putting its result
* into this object. Notice that **if the loader throws an exception,
* it will be stored into [error] var** of this object and the
* status will be [LoadStatus.NOT_FOUND].
* Otherwise, if all goes good, the result is stored into [value] and the
* status will be [LoadStatus.LOADED] if it was untouched or [LoadStatus.RELOADED] in
* the other cases
* @return this object after the `loader` is applied
*/
fun loadOrReload(loader: () -> T) : MutableLoadableValue<T> {
try {
value = loader()
status = when(status) {
LoadStatus.UNTOUCHED -> LoadStatus.LOADED
else -> LoadStatus.RELOADED
}
if(error != null)
error = null
} catch (e : Exception) {
this.status = LoadStatus.NOT_FOUND
this.error = e
}
return this
}
/**
* Applies the loader passed as parameter putting its result
* into this object. Notice that **if the loader throws an exception,
* it will be stored into [error] var** of this object and the
* status will be [LoadStatus.NOT_FOUND].
* Otherwise, if all goes good, the result is stored into [value] and the
* status will be [LoadStatus.RELOADED].
* **If the values has not previously been loaded, this method throws an exception** because
* it is not possible to use it to load the value for the first time (see [loadOrReload] or [load])
* @throws IllegalStateException if the value has never been loaded for the first time
* @return this object after the `loader` was applied
*/
fun reload(loader: () -> T) : MutableLoadableValue<T> {
if(status == LoadStatus.UNTOUCHED)
throw IllegalStateException("Value is never been loaded: unable to reload")
return loadOrReload(loader)
}
/**
* Unloads the value encapsulated into this object.
* After the invocation of this method, the [value] and [error] variables
* are set to `null` and the status is [LoadStatus.UNLOADED]
* @return this object after unload
*/
fun unload() : MutableLoadableValue<T> {
return when(status) {
LoadStatus.UNTOUCHED ->
throw IllegalStateException("Value is never been loaded: unable to unload")
LoadStatus.NOT_FOUND ->
throw IllegalStateException("Values has not been found: unable to unload")
else -> {
this.value = null
this.error = null
this.status = LoadStatus.UNLOADED
this
}
}
}
/**
* Performs the given action on this object if the current status is the desired, otherwise
* nothing will be done
* @param status the desired status
* @param action the action to invoke on this object
* @return this object
*/
fun ifMutableStatus(status : LoadStatus, action : MutableLoadableValue<T>.() -> Unit): MutableLoadableValue<T> {
if(this.status == status)
action(this)
return this
}
/**
* Performs the given action on this object if the current status is [LoadStatus.LOADED].
* If the status is different, nothing will be done
* @param the action to invoke on this object
* @return this object
*/
fun ifMutableLoaded(action: MutableLoadableValue<T>.() -> Unit) : MutableLoadableValue<T> {
if(isLoaded()) this.action()
return this
}
/**
* Performs the given action on this object if the current status is [LoadStatus.RELOADED].
* If the status is different, nothing will be done
* @param the action to invoke on this object
* @return this object
*/
fun ifMutableReloaded(action: MutableLoadableValue<T>.() -> Unit) : MutableLoadableValue<T> {
if(isReloaded()) this.action()
return this
}
/**
* Performs the given action on this object if the current status is **not** [LoadStatus.LOADED].
* So, the action will be invoked **only** if the value of this object is not loaded;
* notice that the action will be however performed if the object has been *reloaded*
* (use [ifMutableNotLoadedOrReloaded] if you don't want this)
*
* @param the action to invoke on this object
* @return this object
*/
fun ifMutableNotLoaded(action: MutableLoadableValue<T>.() -> Unit) : MutableLoadableValue<T> {
if(!isLoaded()) this.action()
return this
}
/**
* Performs the given action on this object if the current status is **not** [LoadStatus.LOADED]
* and not [LoadStatus.RELOADED].
* So, the action will be invoked if the value of this object is not loaded or reloaded
*
* @param the action to invoke on this object
* @return this object
*/
fun ifMutableNotLoadedOrReloaded(action: MutableLoadableValue<T>.() -> Unit) : MutableLoadableValue<T> {
if(!isLoaded() && !isReloaded()) this.action()
return this
}
/**
* Performs the given action on this object if the current status is [LoadStatus.UNTOUCHED].
* If the status is different, nothing will be done
* @param the action to invoke on this object
* @return this object
*/
fun ifMutableUntouched(action: MutableLoadableValue<T>.() -> Unit) : MutableLoadableValue<T> {
if(isUntouched()) this.action()
return this
}
/**
* Performs the given action on this object if the current status is **not** [LoadStatus.UNTOUCHED].
* So, the action will be invoked if at least one operation on this object has been performed
*
* @param the action to invoke on this object
* @return this object
*/
fun ifMutableNotUntouched(action: MutableLoadableValue<T>.() -> Unit) : MutableLoadableValue<T> {
if(!isUntouched()) action.invoke(this)
return this
}
/**
* Performs the given action on this object if the current status is [LoadStatus.UNLOADED].
* If the status is different, nothing will be done
* @param the action to invoke on this object
* @return this object
*/
fun ifMutableUnloaded(action: MutableLoadableValue<T>.() -> Unit) : MutableLoadableValue<T> {
if(isUnLoaded()) action.invoke(this)
return this
}
/**
* Performs the given action on this object if the current status is **not** [LoadStatus.UNLOADED].
* Notice that the action will be invoked even if this object is untouched
* (use [ifMutableLoadedButNotUnloaded] if you don't want this)
*
* @param the action to invoke on this object
* @return this object
*/
fun ifMutableNotUnloaded(action: MutableLoadableValue<T>.() -> Unit) : MutableLoadableValue<T> {
if(!isUnLoaded()) action.invoke(this)
return this
}
/**
* Performs the given action on this object if the current status is **not** [LoadStatus.UNLOADED]
* but it has been previously loaded, reloaded or if it is not found
*
* @param the action to invoke on this object
* @return this object
*/
fun ifMutableLoadedButNotUnloaded(action: MutableLoadableValue<T>.() -> Unit) : MutableLoadableValue<T> {
if(!isUnLoaded() && !isUntouched()) action.invoke(this)
return this
}
/**
* Performs the given action on this object if the current status is [LoadStatus.NOT_FOUND]
*
* @param the action to invoke on this object
* @return this object
*/
fun ifMutableNotFound(action : MutableLoadableValue<T>.() -> Unit) : MutableLoadableValue<T> {
if(isNotFound()) action.invoke(this)
return this
}
/**
* Performs the given action on this object if the current status is **not** [LoadStatus.NOT_FOUND].
* Notice that this includes that the action is performed even if this object is untouched
* (use [ifMutableLoadedAndFound] if you don't want this)
*
* @param the action to invoke on this object
* @return this object
*/
fun ifMutableFound(action : MutableLoadableValue<T>.() -> Unit) : MutableLoadableValue<T> {
if(!isNotFound()) action.invoke(this)
return this
}
/**
* Performs the given action on this object if the value has been correct loaded or
* reloaded, so a value is present
*
* @param the action to invoke on this object
* @return this object
*/
fun ifMutableLoadedOrReloaded(action : MutableLoadableValue<T>.() -> Unit) : MutableLoadableValue<T> {
if(isLoaded() || isReloaded()) action.invoke(this)
return this
}
/**
* Returns this object as [LoadableValue]
* @return this object as [LoadableValue]
*/
fun asLoadableValue() : LoadableValue<T> {
return this
}
} | 0 | Kotlin | 0 | 2 | f5c087635ffcb4cea4fea71a4738adf9d3dbfc74 | 10,300 | KBomber | MIT License |
src/test/kotlin/com/ryanmoelter/splity/EnsureZeroBalanceOnCreditCardTest.kt | ryanmoelter | 270,082,440 | false | {"Kotlin": 373051} | package co.moelten.splity
import co.moelten.splity.database.toBudgetId
import io.kotest.core.spec.style.AnnotationSpec
import kotlinx.coroutines.runBlocking
import strikt.api.expect
import strikt.assertions.isEqualTo
class EnsureZeroBalanceOnCreditCardTest : AnnotationSpec() {
private lateinit var ynab: FakeYnabClient
private fun setUpDatabase(setUp: FakeYnabServerDatabase.() -> Unit) {
ynab = FakeYnabClient(FakeYnabServerDatabase(setUp = setUp))
}
@Test
fun noAction_zero() {
setUpDatabase {
budgets = listOf(fromBudget)
budgetToAccountsMap =
mapOf(
fromBudget.id.toBudgetId() to listOf(
firstCreditCardAccountSapphire,
firstCreditCardAccountFreedom
)
)
budgetToCategoryGroupsMap =
mapOf(fromBudget.id.toBudgetId() to listOf(firstCreditCardCategoryGroup))
setBalanceForAccount(FIRST_CREDIT_CARD_ACCOUNT_SAPPHIRE_ID, balanceAmount = 0)
setBalanceForAccount(FIRST_CREDIT_CARD_ACCOUNT_FREEDOM_ID, balanceAmount = 0)
setBudgetedAmountForCategory(
FIRST_CREDIT_CARD_CATEGORY_SAPPHIRE_ID,
balanceAmount = 0,
budgetedAmount = 0
)
setBudgetedAmountForCategory(
FIRST_CREDIT_CARD_CATEGORY_FREEDOM_ID,
balanceAmount = 0,
budgetedAmount = 0
)
}
runBlocking {
ensureZeroBalanceOnCreditCardsForOneAccount(
ynab,
firstAccountConfig,
ynab.budgets.getBudgets(true).data
)
}
expect {
that(
ynab.fakeYnabServerDatabase.getBudgetedAmountForCategory(
FIRST_CREDIT_CARD_CATEGORY_SAPPHIRE_ID
)
).isEqualTo(0)
that(
ynab.fakeYnabServerDatabase.getBudgetedAmountForCategory(
FIRST_CREDIT_CARD_CATEGORY_FREEDOM_ID
)
).isEqualTo(0)
}
}
@Test
fun noAction_nonZero() {
setUpDatabase {
budgets = listOf(fromBudget)
budgetToAccountsMap =
mapOf(
fromBudget.id.toBudgetId() to listOf(
firstCreditCardAccountSapphire,
firstCreditCardAccountFreedom
)
)
budgetToCategoryGroupsMap =
mapOf(fromBudget.id.toBudgetId() to listOf(firstCreditCardCategoryGroup))
setBalanceForAccount(FIRST_CREDIT_CARD_ACCOUNT_SAPPHIRE_ID, balanceAmount = -50)
setBalanceForAccount(FIRST_CREDIT_CARD_ACCOUNT_FREEDOM_ID, balanceAmount = -100)
setBudgetedAmountForCategory(
FIRST_CREDIT_CARD_CATEGORY_SAPPHIRE_ID,
balanceAmount = 50,
budgetedAmount = 25
)
setBudgetedAmountForCategory(
FIRST_CREDIT_CARD_CATEGORY_FREEDOM_ID,
balanceAmount = 100,
budgetedAmount = 100
)
}
runBlocking {
ensureZeroBalanceOnCreditCardsForOneAccount(
ynab,
firstAccountConfig,
ynab.budgets.getBudgets(true).data
)
}
expect {
that(
ynab.fakeYnabServerDatabase.getBudgetedAmountForCategory(
FIRST_CREDIT_CARD_CATEGORY_SAPPHIRE_ID
)
).isEqualTo(25)
that(
ynab.fakeYnabServerDatabase.getBudgetedAmountForCategory(
FIRST_CREDIT_CARD_CATEGORY_FREEDOM_ID
)
).isEqualTo(100)
}
}
@Test
fun fixMismatchedBalances() {
setUpDatabase {
budgets = listOf(fromBudget)
budgetToAccountsMap =
mapOf(
fromBudget.id.toBudgetId() to listOf(
firstCreditCardAccountSapphire,
firstCreditCardAccountFreedom
)
)
budgetToCategoryGroupsMap =
mapOf(fromBudget.id.toBudgetId() to listOf(firstCreditCardCategoryGroup))
setBalanceForAccount(
FIRST_CREDIT_CARD_ACCOUNT_SAPPHIRE_ID,
balanceAmount = -100
)
setBalanceForAccount(FIRST_CREDIT_CARD_ACCOUNT_FREEDOM_ID, balanceAmount = -25)
setBudgetedAmountForCategory(
FIRST_CREDIT_CARD_CATEGORY_SAPPHIRE_ID,
balanceAmount = 50,
budgetedAmount = 30
)
setBudgetedAmountForCategory(
FIRST_CREDIT_CARD_CATEGORY_FREEDOM_ID,
balanceAmount = 25,
budgetedAmount = 100
)
}
runBlocking {
ensureZeroBalanceOnCreditCardsForOneAccount(
ynab,
firstAccountConfig,
ynab.budgets.getBudgets(true).data
)
}
expect {
that(
ynab.fakeYnabServerDatabase.getBudgetedAmountForCategory(
FIRST_CREDIT_CARD_CATEGORY_SAPPHIRE_ID
)
).isEqualTo(80)
that(
ynab.fakeYnabServerDatabase.getBudgetedAmountForCategory(
FIRST_CREDIT_CARD_CATEGORY_FREEDOM_ID
)
).isEqualTo(100)
}
}
}
| 4 | Kotlin | 0 | 3 | a723623516c3993169ec7cc3f000d1581747d8a6 | 4,665 | splity | Apache License 2.0 |
lib_base/src/main/java/com/czl/lib_base/config/AppConstants.kt | pigletzzzzzz | 516,985,475 | false | {"Kotlin": 723880, "Java": 176802} | package com.czl.lib_base.config
/**
* @author Alwyn
* @Date 2020/10/22
* @Description 常量管理类
*/
interface AppConstants {
object Url {
// const val BASE_URL: String = "https://xpzx.xjxpzx.com.cn/"//项目地址正式环境
const val BASE_URL: String = "https://xpzx.xjxpzx.com.cn:9174/"//项目地址测试环境
//项目资源下载地址
const val IMG_UPLOAD_URL: String = "https://xpzx.xjxpzx.com.cn:8098/"
//项目头像上传地址
const val IMG_UPLOAD_AVATAR_URL: String = "xpzx/platform/upload/uploadFile?folder=0&saveMode=false"
}
object HttpKey {
const val NAME_BASE_URL = "BaseUrlName"
}
object AppKey {
const val BUGLY_KEY = ""
}
object SpKey {
const val LOGIN_NAME: String = "login_name"
const val USER_ID: String = "user_id"
const val USER_JSON_DATA: String = "user_json_data"
const val SYS_UI_MODE: String = "sys_ui_mode"
const val USER_UI_MODE: String = "user_ui_mode"
const val APP_ACCOUNT: String = "app_account"
const val APP_PASSWORD: String = "app_password"
const val APP_TOOKEN: String = "app_user_token"
const val APP_TOOKEN_NAME: String = "Token"
const val IS_LOGIN: String = "user_is_login"
const val USER_IDCODE: String = "user_idcode"
}
object BundleKey {
const val WEB_URL = "web_url"//地址
const val WEB_TYPE = "web_type"
const val WEB_NAME = "web_name"
const val WEB_ITEM_ID = "web_item_id"
const val WEB_URL_COLLECT_FLAG = "web_url_collect_flag"
const val EXAM_TYPE = "exam_type"//考试状态类别
const val GO_EXAM_TYPE = "go_exam_type"//想要跳转到那个type页
const val KNOWLEDGE_ID = "knowledge_id"//知识点ID
const val KNOWLEDGE_NAME = "knowledge_name"//知识点名称
const val KNOWLEDGE_TYPE = "knowledge_type"//知识点类别
const val KNOWLEDGE_TYPE_ID = "knowledge_type_id"//知识点类别id
const val SPECIAL_TYPE = "special_type"//专项练习类别
const val SCENET_ID = "scene_id"//正式考试id
const val EXAM_NAME = "exam_name"//正式考试名称
const val EXAM_TIME = "exam_time"//正式考试名称
const val MESSAGE_TYPE = "message_type"//我的消息类别
const val MY_COURSE_NOTID = "my_course_notid"//我的课程notid
const val MY_COURSE_COURSEID = "my_course_courseid"//我的课程courseId
const val REGISTER_TYPE = "register_type"//培训类别
const val MY_REGISTER_ID = "my_register_id"//报名入口课程id
const val MY_REGISTER_NID = "my_register_nid"//报名入口课程nid
const val INVOICING_ID = "invoicing_id"//发票id
}
object CacheKey{
// 缓存有效期时长1天 数据刷新会重新刷新时长
const val CACHE_SAVE_TIME_SECONDS = 86400
const val CACHE_ALL_DEPART = "cache_all_depart"//所有部门
const val CACHE_JOB_LEVEL = "cache_job_level"//岗位级别
const val CACHE_NATIONALITY = "cache_nationality"//民族
const val CACHE_SKILL_LEVEL = "cache_skill_level"//技能级别
const val CACHE_EDUCATION = "cache_education"//学历
}
/**
* value规则: /(module后缀)/(所在类名)
* 路由 A_ : Activity
* F_ : Fragment
*/
interface Router {
object Web {
const val F_WEB = "/web/WebFragment"
const val F_WEB_NA = "/web/NewAgentWebFragment"
const val F_WEB_OR = "/web/OrdinaryWebFragment"
}
object Login {
const val F_LOGIN = "/login/LoginFragment"
const val F_REGISTER = "/login/RegisterFragment"
const val F_DEPT = "/login/AllDeptFragment"
}
object Announcement {
const val F_ANNOU = "/announcement/AnnounceFragment"
}
object Course{
const val F_COURSE = "/course/CourseFragment"
const val F_PRACTICE = "/course/PracticeTestFragment"
const val F_REAL_EXAM = "/course/RealExamFragment"
const val F_END_EXAM = "/course/EndExamFragment"
const val F_COURSE_DETAIL = "/course/CourseDetailsFragment"
}
object Home{
const val A_MAIN = "/home/MainActivity"
const val F_HOME = "/home/HomeFragment"
const val F_REGISTER = "/home/RegisterFragment"
const val F_REGISTER_DETAIL = "/home/RegisterDetailFragment"
const val F_REGISTER_SETTLEMENT = "/home/RegistrationSettlementFragment"
const val F_MY_INVOICING = "/home/MyInvoicingFragment"
const val F_ADD_INVOICING = "/home/AddInvoicingFragment"
}
object Mine{
const val F_MINE = "/mine/MineFragment"
const val F_SET = "/mine/SetingFragment"
const val F_USER_INFO = "/mine/UserInfoFragment"
const val F_MY_COURSES = "/mine/MyCoursesFragment"
const val F_MY_QUESTION_BANK = "/mine/MyQuestionBankFragment"
const val F_ALL_KNOWLEDGE = "/mine/AllKnowledgeFragment"
const val F_MY_EXAM = "/mine/MyExamFragment"
const val F_MY_EXAM_LIST = "/mine/MyExamListFragment"
const val F_MY_MESSAGE = "/mine/MyMessageFragment"
const val F_MY_MESSAGE_LIST = "/mine/MyMessageListFragment"
const val F_MY_CERT = "/mine/MyCertificateFragment"
const val F_MY_SHOPPING_CRT = "/mine/MyShoppingCartFragment"
const val F_MY_SIGN_IN = "/mine/MySignInFragment"
const val F_JOB_LEARNING = "/mine/JobLearningFragment"
}
}
} | 0 | Kotlin | 0 | 0 | a3276c0149c7d2d3284a6a4d83fa5cb3874664e9 | 5,373 | XPZX-New_Kotlin | Apache License 2.0 |
shared/src/commonMain/kotlin/com/architect/kmpessentials/versionTracking/KmpVersionTracking.kt | TheArchitect123 | 801,452,364 | false | {"Kotlin": 51950, "Ruby": 2156} | package com.architect.kmpessentials.versionTracking
class KmpVersionTracking {
} | 0 | Kotlin | 0 | 3 | 8725489a2f91701a166cbe092409ba8b32bef873 | 81 | KmpEssentials | MIT License |
src/commonMain/kotlin/app/obyte/client/ObyteConnection.kt | pmiklos | 279,186,572 | false | null | package app.obyte.client
import app.obyte.client.protocol.ObyteMessage
import app.obyte.client.protocol.ObyteMessageSerializer
import app.obyte.client.protocol.Request
import app.obyte.client.protocol.Response
import io.ktor.client.features.logging.Logger
import io.ktor.client.features.websocket.DefaultClientWebSocketSession
import io.ktor.http.cio.websocket.Frame
import kotlinx.coroutines.TimeoutCancellationException
import kotlinx.coroutines.channels.BroadcastChannel
import kotlinx.coroutines.channels.Channel
import kotlinx.coroutines.withTimeout
import kotlinx.serialization.json.Json
internal class ObyteConnection(
private val json: Json,
private val logger: Logger,
private val webSocketSession: DefaultClientWebSocketSession,
private val responseChannel: BroadcastChannel<Response>
) {
suspend fun send(message: ObyteMessage) {
val jsonMessage = json.encodeToString(ObyteMessageSerializer, message)
logger.log("OUTGOING: $jsonMessage")
webSocketSession.send(Frame.Text(jsonMessage))
}
suspend fun request(request: Request): Response? {
val subscription = responseChannel.openSubscription()
return try {
send(request)
withTimeout(30000L) {
for (response in subscription) {
if (response.tag == request.tag) {
return@withTimeout response
}
}
return@withTimeout null
}
} catch (e: TimeoutCancellationException) {
return null
} finally {
subscription.cancel()
}
}
} | 0 | Kotlin | 0 | 0 | 764c1d779b7b5cdfcb98994cae100ba0b161704d | 1,648 | obyte.kt | MIT License |
src/commonMain/kotlin/mvc/Usuario.kt | KenyOnFire | 749,573,175 | false | {"Kotlin": 77624, "Shell": 127} | package mvc
import kotlinx.serialization.Serializable
// Modelo de Usuario
@Serializable
data class Usuario(var nombreUsuario: String, var dineroActual: Int)
| 0 | Kotlin | 0 | 1 | 75508a351aaafc16962d8ea8db2f8efef2193904 | 160 | RuletaAdrianGabriel | MIT License |
src/test/kotlin/eu/europa/ec/eudi/openid4vp/internal/request/AttestationIssuer.kt | eu-digital-identity-wallet | 642,355,309 | false | {"Kotlin": 258500} | /*
* Copyright (c) 2023 European Commission
*
* 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 eu.europa.ec.eudi.openid4vp.internal.request
import com.nimbusds.jose.JOSEObjectType
import com.nimbusds.jose.JWSHeader
import com.nimbusds.jose.JWSVerifier
import com.nimbusds.jose.crypto.factories.DefaultJWSSignerFactory
import com.nimbusds.jose.crypto.factories.DefaultJWSVerifierFactory
import com.nimbusds.jose.jwk.JWK
import com.nimbusds.jwt.JWTClaimsSet
import com.nimbusds.jwt.SignedJWT
import java.net.URI
import java.time.Clock
import java.time.Instant
import java.util.*
import kotlin.time.Duration.Companion.seconds
object AttestationIssuer {
const val ID = "Attestation Issuer"
private val algAndKey by lazy { randomKey() }
private val attestationDuration = 10.seconds
val verifier: JWSVerifier by lazy {
val (alg, key) = algAndKey
val h = JWSHeader.Builder(alg).build()
DefaultJWSVerifierFactory().createJWSVerifier(h, key.toPublicKey())
}
fun attestation(
clock: Clock,
clientId: String,
clientPubKey: JWK,
redirectUris: List<URI>? = null,
responseUris: List<URI>? = null,
): SignedJWT {
val (alg, key) = algAndKey
val signer = DefaultJWSSignerFactory().createJWSSigner(key, alg)
val header = JWSHeader.Builder(alg)
.type(JOSEObjectType("verifier-attestation+jwt"))
.build()
val now = clock.instant()
require(!clientPubKey.isPrivate) { "clientPubKey should be public" }
val cnf = mapOf("jwk" to clientPubKey.toPublicJWK().toJSONObject())
val claimSet = with(JWTClaimsSet.Builder()) {
issuer(ID)
subject(clientId)
issueTime(now.toDate())
expirationTime(expiration(now).toDate())
claim("cnf", cnf)
redirectUris?.let { uris -> claim("redirect_uris", uris.map { it.toString() }) }
responseUris?.let { uris -> claim("response_urls", uris.map { it.toString() }) }
build()
}
return SignedJWT(header, claimSet).apply { sign(signer) }
}
private fun expiration(iat: Instant) = iat.plusSeconds(attestationDuration.inWholeSeconds)
private fun Instant.toDate() = Date.from(this)
}
| 3 | Kotlin | 2 | 9 | 3686cc52744e36f342001097df218c77118e18d8 | 2,801 | eudi-lib-jvm-siop-openid4vp-kt | Apache License 2.0 |
bending-api/src/main/kotlin/pw/dotdash/bending/api/util/LocationExt.kt | Arvenwood | 236,423,077 | false | null | package pw.dotdash.bending.api.util
import com.flowpowered.math.vector.Vector3d
import org.spongepowered.api.effect.particle.ParticleEffect
import org.spongepowered.api.entity.Entity
import org.spongepowered.api.world.Location
import org.spongepowered.api.world.World
fun Location<World>.distance(to: Location<World>): Double {
return this.position.distance(to.position)
}
fun Location<World>.distanceSquared(to: Location<World>): Double {
return this.position.distanceSquared(to.position)
}
fun Location<World>.isNearDiagonalWall(direction: Vector3d): Boolean =
LocationUtil.isNearDiagonalWall(this, direction)
fun Location<World>.spawnParticles(particleEffect: ParticleEffect) =
this.extent.spawnParticles(particleEffect, this.position)
fun Location<World>.spawnParticles(particleEffect: ParticleEffect, radius: Int) =
this.extent.spawnParticles(particleEffect, this.position, radius)
fun Location<World>.getNearbyLocations(radius: Double): Collection<Location<World>> =
LocationUtil.getNearbyLocations(this, radius)
fun Location<World>.getNearbyEntities(radius: Double): Collection<Entity> =
this.extent.getNearbyEntities(this.position, radius)
fun Location<World>.setX(x: Double): Location<World> =
LocationUtil.setX(this, x)
fun Location<World>.setY(y: Double): Location<World> =
LocationUtil.setY(this, y)
fun Location<World>.setZ(z: Double): Location<World> =
LocationUtil.setZ(this, z) | 0 | Kotlin | 0 | 1 | deef3fdfe1f434bc7df4133c78e596ea3ba7785c | 1,444 | Bending | MIT License |
feature_workbrowse/src/main/java/com/andtv/flicknplay/workbrowse/presentation/presenter/AccountSettingDetailPresenter.kt | procoder1128 | 553,094,605 | false | null | package com.andtv.flicknplay.workbrowse.presentation.presenter
import android.util.Log
import com.andtv.flicknplay.presentation.di.annotation.FragmentScope
import com.andtv.flicknplay.presentation.extension.addTo
import com.andtv.flicknplay.presentation.presenter.AutoDisposablePresenter
import com.andtv.flicknplay.presentation.scheduler.RxScheduler
import com.andtv.flicknplay.workbrowse.data.remote.model.AllSocialResponse
import com.andtv.flicknplay.workbrowse.data.remote.model.ErrorResponse
import com.andtv.flicknplay.workbrowse.data.remote.model.SocialLoginModel
import com.andtv.flicknplay.workbrowse.data.remote.model.SocialResponse
import com.andtv.flicknplay.workbrowse.data.remote.model.accountSettingDetail.AccountDetailRequest
import com.andtv.flicknplay.workbrowse.data.remote.model.accountSettingDetail.ResetPasswordRequest
import com.andtv.flicknplay.workbrowse.data.remote.model.accountSettingDetail.User
import com.andtv.flicknplay.workbrowse.data.remote.model.login.LoginResponse
import com.andtv.flicknplay.workbrowse.domain.*
import com.google.gson.Gson
import com.jakewharton.retrofit2.adapter.rxjava2.HttpException
import okhttp3.ResponseBody
import timber.log.Timber
import javax.inject.Inject
@FragmentScope
class AccountSettingDetailPresenter@Inject constructor(
private val accountSettingDetailUseCase: AccountSettingDetailUseCase,
private val view: AccountSettingDetailPresenter.View,
private val getSocialConnection : GetSocialConnectionUseCase,
private val getUpdateAccountDetailUseCase: GetUpdateAccountDetailUseCase,
private val getAllSocialUseCase: GetAllSocialUseCase,
private val getUpdatePasswordUseCase:GetUpdatePasswordUseCase,
private val rxScheduler: RxScheduler
): AutoDisposablePresenter(){
fun getAccountSettingDetail(id:Int) {
accountSettingDetailUseCase(id)
.subscribeOn(rxScheduler.ioScheduler)
.observeOn(rxScheduler.mainScheduler)
.doOnSubscribe { view.onShowProgress() }
.doFinally { view.onHideProgress() }
.subscribe({ result->
Timber.i(Gson().toJson(result))
if(result.status == "success")
view.onGetAccountSettingDetail(result.user)
else
view.onGetAccountSettingDetailFailed()
}, { throwable ->
if (throwable is HttpException && throwable.response().errorBody() is ResponseBody) {
val errorBody: String = (throwable.response().errorBody() as ResponseBody).string()
view.onErrorWorksLoaded(
Gson().fromJson(
errorBody,
ErrorResponse::class.java
)
)
}
Timber.e(throwable, "Error while loading the works by genre")
}).addTo(compositeDisposable)
}
fun socialConnection(provider:String,action:String,request: SocialLoginModel) {
Timber.i( Gson().toJson(request))
getSocialConnection(provider,action,request)
.subscribeOn(rxScheduler.ioScheduler)
.observeOn(rxScheduler.computationScheduler)
.observeOn(rxScheduler.mainScheduler)
.doOnSubscribe { view.onShowProgress() }
.doFinally {
view.onHideProgress()
}
.subscribe({ workPage ->
workPage?.let {
Timber.i( Gson().toJson(it))
view.onSocialAccountResponse(it)
}
}, { throwable ->
view.onError("Email miss matched, Make sure its your account")
if (throwable is HttpException && throwable.response().errorBody() is ResponseBody) {
Timber.e(throwable,throwable.response().body().toString())
val errorBody: String = (throwable.response().errorBody() as ResponseBody).string()
Timber.e(throwable,errorBody)
view.onErrorWorksLoaded(
Gson().fromJson(
errorBody,
ErrorResponse::class.java
)
)
}
Timber.e(throwable, "Error while loading the works by genre")
}).addTo(compositeDisposable)
}
fun updateUserProfile(id:String,request: AccountDetailRequest) {
Timber.i( Gson().toJson(request))
getUpdateAccountDetailUseCase(id,request)
.subscribeOn(rxScheduler.ioScheduler)
.observeOn(rxScheduler.computationScheduler)
.observeOn(rxScheduler.mainScheduler)
.doOnSubscribe { view.onShowProgress() }
.doFinally {
view.onHideProgress()
}
.subscribe({ workPage ->
workPage?.let {
Timber.i( Gson().toJson(it))
view.onAccountUpdate(it)
}
}, { throwable ->
if (throwable is HttpException && throwable.response().errorBody() is ResponseBody) {
Timber.e(throwable,throwable.response().body().toString())
val errorBody: String = (throwable.response().errorBody() as ResponseBody).string()
Timber.e(throwable,errorBody)
view.onErrorWorksLoaded(
Gson().fromJson(
errorBody,
ErrorResponse::class.java
)
)
}
Timber.e(throwable, "Error while loading the works by genre")
}).addTo(compositeDisposable)
}
fun updatePassword(request: ResetPasswordRequest) {
Timber.i( Gson().toJson(request))
getUpdatePasswordUseCase(request)
.subscribeOn(rxScheduler.ioScheduler)
.observeOn(rxScheduler.computationScheduler)
.observeOn(rxScheduler.mainScheduler)
.doOnSubscribe { view.onShowProgress() }
.doFinally {
view.onHideProgress()
}
.subscribe({ workPage ->
workPage?.let {
Timber.i( Gson().toJson(it))
view.onPasswordUpdate(it)
}
}, { throwable ->
if (throwable is HttpException && throwable.response().errorBody() is ResponseBody) {
Timber.e(throwable,throwable.response().body().toString())
val errorBody: String = (throwable.response().errorBody() as ResponseBody).string()
Timber.e(throwable,errorBody)
view.onErrorWorksLoaded(
Gson().fromJson(
errorBody,
ErrorResponse::class.java
)
)
}
Timber.e(throwable, "Error while loading the works by genre")
}).addTo(compositeDisposable)
}
fun getAllSocialProfile(request: SocialLoginModel) {
Timber.i( Gson().toJson(request))
getAllSocialUseCase(request)
.subscribeOn(rxScheduler.ioScheduler)
.observeOn(rxScheduler.computationScheduler)
.observeOn(rxScheduler.mainScheduler)
.doOnSubscribe { view.onShowProgress() }
.doFinally {
view.onHideProgress()
}
.subscribe({ workPage ->
workPage?.let {
Timber.i( Gson().toJson(it))
view.onAllSocialAccount(it)
}
}, { throwable ->
if (throwable is HttpException && throwable.response().errorBody() is ResponseBody) {
Timber.e(throwable,throwable.response().body().toString())
val errorBody: String = (throwable.response().errorBody() as ResponseBody).string()
Timber.e(throwable,errorBody)
view.onErrorWorksLoaded(
Gson().fromJson(
errorBody,
ErrorResponse::class.java
)
)
}
Timber.e(throwable, "Error while loading the works by genre")
}).addTo(compositeDisposable)
}
interface View {
fun onPasswordUpdate(socialResponse : SocialResponse)
fun onAllSocialAccount(allSocialResponse: AllSocialResponse)
fun onAccountUpdate(socialResponse : SocialResponse)
fun onSocialAccountResponse(socialResponse : AllSocialResponse)
fun onGetAccountSettingDetail(user:User)
fun onGetAccountSettingDetailFailed()
fun onShowProgress()
fun onHideProgress()
fun onError(message:String)
fun onErrorWorksLoaded(errorResponse: ErrorResponse)
}
} | 0 | Kotlin | 1 | 4 | 45d661d6b872c13b6a1235bbb9a44c91740d3f9d | 9,014 | blockchain | Apache License 2.0 |
ink/ink-geometry/src/jvmAndroidMain/kotlin/androidx/ink/geometry/Angle.kt | androidx | 256,589,781 | false | null | /*
* Copyright (C) 2024 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package androidx.ink.geometry
import androidx.annotation.FloatRange
import androidx.ink.nativeloader.NativeLoader
/**
* A utility for working with a signed angle. A positive value represents rotation from the positive
* x-axis to the positive y-axis. Angle functions manage the conversion of angle values in degrees
* and radians. Most of Strokes API requires angle values in radians.
*/
public object Angle {
init {
NativeLoader.load()
}
@JvmStatic
@AngleRadiansFloat
public fun degreesToRadians(@AngleDegreesFloat degrees: Float): Float =
degrees * RADIANS_PER_DEGREE
@JvmStatic
@AngleDegreesFloat
public fun radiansToDegrees(@AngleRadiansFloat radians: Float): Float =
radians * DEGREES_PER_RADIAN
@JvmStatic
@AngleRadiansFloat
@FloatRange(from = 0.0, to = Angle.FULL_TURN_RADIANS_DOUBLE)
public fun normalized(@AngleRadiansFloat radians: Float): Float = nativeNormalized(radians)
@JvmStatic
@AngleRadiansFloat
@FloatRange(from = -Angle.HALF_TURN_RADIANS_DOUBLE, to = Angle.HALF_TURN_RADIANS_DOUBLE)
public fun normalizedAboutZero(@AngleRadiansFloat radians: Float): Float =
nativeNormalizedAboutZero(radians)
private const val DEGREES_PER_RADIAN = 180.0f / Math.PI.toFloat()
private const val RADIANS_PER_DEGREE = Math.PI.toFloat() / 180.0f
private const val HALF_TURN_RADIANS_DOUBLE = Math.PI
private const val FULL_TURN_RADIANS_DOUBLE = 2 * Math.PI
/** Angle of zero radians. */
@JvmField @AngleRadiansFloat public val ZERO: Float = 0.0f
/** Angle of PI radians. */
@JvmField
@AngleRadiansFloat
public val HALF_TURN_RADIANS: Float = HALF_TURN_RADIANS_DOUBLE.toFloat()
/** Angle of PI/2 radians. */
@JvmField
@AngleRadiansFloat
public val QUARTER_TURN_RADIANS: Float = (HALF_TURN_RADIANS_DOUBLE / 2.0).toFloat()
/** Angle of 2*PI radians. */
@JvmField
@AngleRadiansFloat
public val FULL_TURN_RADIANS: Float = FULL_TURN_RADIANS_DOUBLE.toFloat()
private external fun nativeNormalized(
radians: Float
): Float // TODO: b/355248266 - @Keep must go in Proguard config file instead.
private external fun nativeNormalizedAboutZero(
radians: Float
): Float // TODO: b/355248266 - @Keep must go in Proguard config file instead.
}
| 29 | null | 1011 | 5,321 | 98b929d303f34d569e9fd8a529f022d398d1024b | 2,963 | androidx | Apache License 2.0 |
plugin-build/src/main/kotlin/io/github/sunnhas/poeditor/config/PoGradleExtension.kt | sunnhas | 755,941,134 | false | {"Kotlin": 33408} | package io.github.sunnhas.poeditor.config
import org.gradle.api.NamedDomainObjectContainer
import org.gradle.api.provider.Property
abstract class PoGradleExtension {
abstract val apiToken: Property<String>
abstract val projects: NamedDomainObjectContainer<ProjectExtension>
} | 0 | Kotlin | 0 | 0 | a011b1791b2db27805535a1a14fce0c6478b9ebc | 288 | po-gradle-plugin | Apache License 2.0 |
Section 6/UserService.kt | PacktPublishing | 187,770,226 | false | null | package com.markodevcic.coroutinesexamoples
import kotlinx.coroutines.experimental.CommonPool
import kotlinx.coroutines.experimental.Deferred
import kotlinx.coroutines.experimental.async
import kotlinx.coroutines.experimental.delay
class UserService {
fun getUserCountryAsync(): Deferred<String> = async(CommonPool) {
delay(1500)
"Sweden"
}
fun getUserFirstName(): Deferred<String> = async(CommonPool) {
delay(1500)
"John"
}
fun getUserLastNameAsync(): Deferred<String> = async(CommonPool) {
delay(2000)
"Doe"
}
fun isUserLoggedIn(fullName: String): Deferred<String> = async(CommonPool) {
delay(750)
"true"
}
suspend fun failAsync() {
delay(1000)
throw RuntimeException("I failed")
}
} | 1 | null | 2 | 3 | 79ca85b1ac6d71408dfa8ed2061785aa42dc111f | 722 | Mastering-Kotlin-for-Android-Development | MIT License |
Data/src/main/java/com/sdk/data/model/ResponseListModel.kt | inplayer-org | 161,477,099 | false | null | package com.sdk.data.model
/**
* Created by victor on 3/13/19
*/
data class ResponseListModel<T>(val total: Int, val collection: List<T>) | 2 | Kotlin | 1 | 5 | b5e0b0adb794bca08b503dab2e84c61aaec2a447 | 140 | inplayer-android-sdk | MIT License |
src/main/kotlin/us/frollo/frollosdk/network/api/ServiceStatusAPI.kt | frollous | 261,670,220 | false | null | /*
* Copyright 2019 Frollo
*
* 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 us.frollo.frollosdk.network.api
import retrofit2.Call
import retrofit2.http.GET
import retrofit2.http.Url
import us.frollo.frollosdk.model.api.servicestatus.ServiceOutageResponse
import us.frollo.frollosdk.model.api.servicestatus.ServiceStatusResponse
internal interface ServiceStatusAPI {
@GET
fun fetchServiceStatus(@Url url: String): Call<ServiceStatusResponse>
@GET
fun fetchServiceOutages(@Url url: String): Call<List<ServiceOutageResponse>>
}
| 5 | null | 1 | 2 | bb026203a43a2f7d06cc8dd557ae1be4697d067e | 1,067 | frollo-android-sdk | Apache License 2.0 |
core/src/main/kotlin/com/mobillium/core/ext/FragmentExt.kt | mobillium | 303,412,402 | false | null | /*
* Copyright 2020 http://www.mobillium.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.mobillium.core.ext
import android.content.Intent
import android.os.Bundle
import androidx.fragment.app.Fragment
import com.mobillium.core.markers.CanFetchExtras
import com.mobillium.core.markers.CanHandleBackPressEvents
import com.mobillium.core.markers.CanHandleNewIntent
/**
* @author @karacca
* @since 1.0.0
*/
/**
* Passes the extras for further handling to the
* Fragment if [CanFetchExtras] is implemented
*/
fun Fragment.handleExtras(extras: Bundle) =
(this as? CanFetchExtras)?.fetchExtras(extras)
/**
* Applies [handleExtras] to each of the [Fragment] in a collection.
*/
fun Collection<Fragment>.handleExtras(extras: Bundle) =
this.forEach { it.handleExtras(extras) }
/**
* Passes the new [Intent] for further handling to the
* Fragment if [CanHandleNewIntent] is implemented.
*/
fun Fragment.handleNewIntent(intent: Intent) =
(this as? CanHandleNewIntent)?.handleNewIntent(intent)
/**
* Applies [handleNewIntent] to each of the [Fragment] in a collection.
*/
fun Collection<Fragment>.handleNewIntent(intent: Intent) =
this.forEach { it.handleNewIntent(intent) }
/**
* Propagates the Back Press Event for further handling to the specified [Fragment]
* only if it (the specified [Fragment]) can handle the Back Press Event
* (if it (the specified [Fragment]) implements the [CanHandleBackPressEvents] interface)
*
* @return whether the Back Press Event has been consumed or not (see: [CanHandleBackPressEvents.onBackPressed])
*/
fun Fragment.handleBackPressEvent() =
this is CanHandleBackPressEvents && this.onBackPressed()
/**
* Applies [handleBackPressEvent] to each [Fragment] in a collection.
*/
fun Collection<Fragment>.handleBackPressEvent(): Boolean {
for (fragment in this) {
if (fragment.handleBackPressEvent()) {
return true
}
}
return false
}
| 1 | null | 1 | 6 | b988de827ae36aa2f0dc762eb92cd5510b55dc5d | 2,475 | ground | Apache License 2.0 |
sample/src/main/java/com/zilchzz/sample/BaseApplication.kt | zilchzz | 149,627,208 | false | null | package com.zilchzz.sample
import android.app.Application
import com.zilchzz.library.widgets.EasySwitcher
class BaseApplication : Application() {
override fun onCreate() {
super.onCreate()
EasySwitcher.setDefaultOpenBgColor("#FFFF00FF")
EasySwitcher.setDefaultCloseBgColor("#FFF1F1F1")
EasySwitcher.setDefaultAnimTime(350)
}
} | 0 | Kotlin | 0 | 5 | 3a55ac4b0434f70b12d96447e413e5bdd24761b0 | 368 | EasySwitcher | The Unlicense |
app/src/main/java/com/kylix/submissionbajp3/ui/movie/MovieFragment.kt | KylixEza | 323,485,823 | false | null | @file:Suppress("DEPRECATION")
package com.kylix.submissionbajp3.ui.movie
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.Fragment
import androidx.lifecycle.Observer
import androidx.lifecycle.ViewModelProviders
import androidx.recyclerview.widget.GridLayoutManager
import com.kylix.submissionbajp3.R
import com.kylix.submissionbajp3.model.local.entity.MovieModel
import com.kylix.submissionbajp3.ui.adapter.MovieAdapter
import com.kylix.submissionbajp3.utils.Status
import com.kylix.submissionbajp3.utils.ViewModelFactory
import kotlinx.android.synthetic.main.movie_fragment.*
class MovieFragment : Fragment() {
private var movieList : List<MovieModel> = listOf()
private val movieViewModel by lazy {
val viewModelFactory= activity?.application?.let { ViewModelFactory.getInstance(it) }
ViewModelProviders.of(this,viewModelFactory).get(MovieViewModel::class.java)
}
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
return inflater.inflate(R.layout.movie_fragment, container, false)
}
override fun onActivityCreated(savedInstanceState: Bundle?) {
super.onActivityCreated(savedInstanceState)
val movieAdapter = MovieAdapter(context)
movieViewModel.movies.observe(viewLifecycleOwner, Observer {
movie_progress_bar.visibility = View.GONE
movieList = it
movieAdapter.getList(movieList)
getMovies()
})
rv_movie.apply {
layoutManager = GridLayoutManager(context, 2)
adapter = movieAdapter
}
}
private fun getMovies() {
movieViewModel.getMovies.observe(viewLifecycleOwner, Observer {
when (it.status) {
Status.SUCCESS -> {
movie_progress_bar.visibility = View.GONE
if (it.data.isNullOrEmpty()) {
movieViewModel.insertMovies(movieList)
}
}
Status.ERROR -> movie_progress_bar.visibility = View.GONE
Status.LOADING -> {}
}
})
}
} | 0 | Kotlin | 0 | 3 | 81841574ec752bf40946592ad333b790c5abb933 | 2,278 | Submission-BAJP3-Dicoding | MIT License |
library/controller/kmp-tor-controller-common/src/commonMain/kotlin/io/matthewnelson/kmp/tor/controller/common/config/TorConfig.kt | 05nelsonm | 456,238,754 | false | null | /*
* Copyright (c) 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
*
* 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 io.matthewnelson.kmp.tor.controller.common.config
import io.matthewnelson.kmp.tor.common.address.IPAddressV4
import io.matthewnelson.kmp.tor.common.address.IPAddressV6
import io.matthewnelson.kmp.tor.common.address.Port
import io.matthewnelson.kmp.tor.common.address.PortProxy
import io.matthewnelson.kmp.tor.common.annotation.ExperimentalTorApi
import io.matthewnelson.kmp.tor.common.annotation.InternalTorApi
import io.matthewnelson.kmp.tor.common.annotation.SealedValueClass
import io.matthewnelson.kmp.tor.common.internal.TorStrings.REDACTED
import io.matthewnelson.kmp.tor.common.internal.TorStrings.SP
import io.matthewnelson.kmp.tor.controller.common.config.TorConfig.Option.TorF.False
import io.matthewnelson.kmp.tor.controller.common.config.TorConfig.Option.TorF.True
import io.matthewnelson.kmp.tor.controller.common.file.Path
import io.matthewnelson.kmp.tor.controller.common.internal.PlatformUtil
import io.matthewnelson.kmp.tor.controller.common.internal.appendTo
import io.matthewnelson.kmp.tor.controller.common.internal.filterSupportedOnly
import io.matthewnelson.kmp.tor.controller.common.internal.isUnixPath
import kotlinx.atomicfu.AtomicBoolean
import kotlinx.atomicfu.AtomicRef
import kotlinx.atomicfu.atomic
import kotlinx.atomicfu.update
import kotlin.jvm.*
import kotlin.reflect.KClass
/**
* Holder for Tor configuration information.
*
* @see [Builder]
* @see [Setting]
* @see [Option]
* @see [KeyWord]
* */
@OptIn(ExperimentalTorApi::class, InternalTorApi::class)
@Suppress("RemoveRedundantQualifierName", "SpellCheckingInspection")
class TorConfig private constructor(
@JvmField
val settings: Set<TorConfig.Setting<*>>,
@JvmField
val text: String,
) {
fun newBuilder(action: Builder.() -> Builder): Builder = Builder {
put(this@TorConfig)
action.invoke(this)
}
fun newBuilder(): Builder = Builder().put(this)
override fun equals(other: Any?): Boolean {
return other != null &&
other is TorConfig &&
other.text == text
}
override fun hashCode(): Int {
return 17 * 31 + text.hashCode()
}
override fun toString(): String {
return "TorConfig(settings=$REDACTED, text=$REDACTED)"
}
/**
* Build your [TorConfig] to write to disk (torrc file), or load via the controller.
*
* Ex:
*
import io.matthewnelson.kmp.tor.common.address.Port
import io.matthewnelson.kmp.tor.controller.common.config.TorConfig
// importing subclasses makes things less painful.
import io.matthewnelson.kmp.tor.controller.common.config.TorConfig.*
import io.matthewnelson.kmp.tor.controller.common.config.TorConfig.Setting.*
import io.matthewnelson.kmp.tor.controller.common.config.TorConfig.Option.*
class TorConfig_Builder_Example {
val myConfigBuilder: Builder = Builder {
put(DisableNetwork().set(TorF.False))
}
val myConfig: TorConfig = myConfigBuilder.build()
val myUpdatedConfig: TorConfig = myConfig.newBuilder {
put(Ports.Control().set(AorDorPort.Value(Port(9051))))
remove(DisableNetwork())
removeInstanceOf(DisableNetwork::class)
}.build()
}
* */
class Builder {
init {
// Reference so that localhostAddress for JVM can have its initial
// value set immediately from BG thread.
PlatformUtil
}
private val settings: MutableSet<TorConfig.Setting<*>> = mutableSetOf()
fun remove(setting: TorConfig.Setting<*>): Builder = apply {
settings.remove(setting)
}
@Suppress("unchecked_cast")
fun <T: Setting<*>> removeInstanceOf(clazz: KClass<T>): Builder = apply {
val toRemove = mutableListOf<T>()
for (setting in settings) {
if (setting::class == clazz) {
toRemove.add(setting as T)
}
}
for (setting in toRemove) {
settings.remove(setting)
}
}
fun put(config: TorConfig): Builder = apply {
for (setting in config.settings) {
if (!settings.add(setting)) {
settings.remove(setting)
settings.add(setting)
}
}
}
fun put(setting: TorConfig.Setting<*>): Builder = apply {
setting.value?.let {
val clone = setting.clone()
if (!settings.add(clone)) {
settings.remove(clone)
settings.add(clone)
}
} ?: remove(setting)
}
fun put(settings: Collection<TorConfig.Setting<*>>): Builder = apply {
for (setting in settings) {
put(setting)
}
}
fun putIfAbsent(setting: TorConfig.Setting<*>): Builder = apply {
setting.value?.let { settings.add(setting.clone()) } ?: remove(setting)
}
fun build(): TorConfig {
val sb = StringBuilder()
val disabledPorts = mutableSetOf<KeyWord>()
val sorted = settings.sortedBy { setting ->
when (setting) {
// Ports must come before UnixSocket to ensure
// disabled ports are removed
is Setting.Ports -> {
if (setting.value is Option.AorDorPort.Disable) {
disabledPorts.add(setting.keyword)
}
"AAAA${setting.keyword}"
}
is Setting.UnixSockets -> {
"AAA${setting.keyword}"
}
else -> {
setting.keyword.toString()
}
}
}
val writtenDisabledPorts: MutableSet<KeyWord> = LinkedHashSet(disabledPorts.size)
val newSettings = mutableSetOf<Setting<*>>()
for (setting in sorted) {
when (setting) {
is Setting.Ports -> {
if (disabledPorts.contains(setting.keyword)) {
if (!writtenDisabledPorts.contains(setting.keyword)) {
sb.append(setting.keyword)
sb.append(SP)
sb.append(Option.AorDorPort.Disable.value)
sb.appendLine()
writtenDisabledPorts.add(setting.keyword)
}
if (setting.value is Option.AorDorPort.Disable) {
newSettings.add(setting.setImmutable())
}
continue
}
if (!setting.appendTo(sb, isWriteTorConfig = true)) {
continue
}
}
is Setting.UnixSockets -> {
if (disabledPorts.contains(setting.keyword)) continue
if (!setting.appendTo(sb, isWriteTorConfig = true)) {
continue
}
}
else -> {
if (!setting.appendTo(sb, isWriteTorConfig = true)) {
continue
}
}
}
newSettings.add(setting.setImmutable())
sb.appendLine()
}
return TorConfig(newSettings.toSet(), sb.toString())
}
companion object {
operator fun invoke(block: Builder.() -> Builder): Builder =
block.invoke(Builder())
}
}
/**
* Settings's for configuring Tor.
*
* Ex:
*
* val socksPort = Setting.Ports.Socks()
* .setFlags(flags = setOf(
* Setting.Ports.Socks.Flag.OnionTrafficOnly
* ))
* .setIsolationFlags(flags = setOf(
* Setting.Ports.IsolationFlag.IsolateClientProtocol,
* Setting.Ports.IsolationFlag.IsolateDestAddr,
* ))
* .set(Option.AorDorPort.Value(port = Port(9250)))
*
* https://2019.www.torproject.org/docs/tor-manual.html.en
* */
@Suppress(
"ClassName",
"PropertyName",
"CanBePrimaryConstructorProperty"
)
sealed class Setting<T: Option?>(
@JvmField
val keyword: TorConfig.KeyWord,
@JvmField
val default: T,
isStartArgument: Boolean,
) {
private val _value: AtomicRef<T> = atomic(default)
@get:JvmName("value")
val value: T get() = _value.value
@get:JvmName("isDefault")
val isDefault: Boolean get() = value == default
private val _isMutable: AtomicBoolean = atomic(true)
@get:JvmName("isMutable")
val isMutable: Boolean get() = _isMutable.value
@JvmField
@InternalTorApi
val isStartArgument: Boolean = isStartArgument
@JvmSynthetic
internal fun setImmutable(): Setting<T> {
_isMutable.update { false }
return this
}
open fun set(value: T): Setting<T> {
if (isMutable) {
_value.update { value }
}
return this
}
open fun setDefault(): Setting<T> {
if (isMutable) {
_value.update { default }
}
return this
}
abstract fun clone(): Setting<T>
override fun equals(other: Any?): Boolean {
return other != null &&
other is Setting<*> &&
other.keyword == keyword
}
override fun hashCode(): Int {
return 17 * 31 + keyword.hashCode()
}
override fun toString(): String {
return "${this::class.simpleName}(keyword=$keyword, value=$value, default=$default)"
}
/**
* https://2019.www.torproject.org/docs/tor-manual.html.en#AutomapHostsOnResolve
* */
class AutomapHostsOnResolve : Setting<Option.TorF>(
keyword = KeyWord.AutomapHostsOnResolve,
default = Option.TorF.True,
isStartArgument = false,
) {
override fun clone(): AutomapHostsOnResolve {
return AutomapHostsOnResolve().set(value) as AutomapHostsOnResolve
}
}
/**
* https://2019.www.torproject.org/docs/tor-manual.html.en#CacheDirectory
* */
class CacheDirectory : Setting<Option.FileSystemDir?>(
keyword = KeyWord.CacheDirectory,
default = null,
isStartArgument = true,
) {
override fun set(value: Option.FileSystemDir?): Setting<Option.FileSystemDir?> {
return super.set(value?.nullIfEmpty)
}
override fun clone(): CacheDirectory {
return CacheDirectory().set(value) as CacheDirectory
}
}
/**
* https://2019.www.torproject.org/docs/tor-manual.html.en#ClientOnionAuthDir
* */
class ClientOnionAuthDir : Setting<Option.FileSystemDir?>(
keyword = KeyWord.ClientOnionAuthDir,
default = null,
isStartArgument = true,
) {
override fun set(value: Option.FileSystemDir?): Setting<Option.FileSystemDir?> {
return super.set(value?.nullIfEmpty)
}
override fun clone(): ClientOnionAuthDir {
return ClientOnionAuthDir().set(value) as ClientOnionAuthDir
}
companion object {
const val DEFAULT_NAME = "auth_private_files"
}
}
/**
* https://2019.www.torproject.org/docs/tor-manual.html.en#ConnectionPadding
* */
class ConnectionPadding : Setting<Option.AorTorF>(
keyword = KeyWord.ConnectionPadding,
default = Option.AorTorF.Auto,
isStartArgument = false,
) {
override fun clone(): ConnectionPadding {
return ConnectionPadding().set(value) as ConnectionPadding
}
}
/**
* https://2019.www.torproject.org/docs/tor-manual.html.en#ConnectionPaddingReduced
* */
class ConnectionPaddingReduced : Setting<Option.TorF>(
keyword = KeyWord.ReducedConnectionPadding,
default = Option.TorF.False,
isStartArgument = false,
) {
override fun clone(): ConnectionPaddingReduced {
return ConnectionPaddingReduced().set(value) as ConnectionPaddingReduced
}
}
/**
* https://2019.www.torproject.org/docs/tor-manual.html.en#ControlPortWriteToFile
* */
class ControlPortWriteToFile : Setting<Option.FileSystemFile?>(
keyword = KeyWord.ControlPortWriteToFile,
default = null,
isStartArgument = true,
) {
override fun set(value: Option.FileSystemFile?): Setting<Option.FileSystemFile?> {
return super.set(value?.nullIfEmpty)
}
override fun clone(): ControlPortWriteToFile {
return ControlPortWriteToFile().set(value) as ControlPortWriteToFile
}
companion object {
const val DEFAULT_NAME = "control.txt"
}
}
/**
* https://2019.www.torproject.org/docs/tor-manual.html.en#CookieAuthentication
* */
class CookieAuthentication : Setting<Option.TorF>(
keyword = KeyWord.CookieAuthentication,
default = Option.TorF.True,
isStartArgument = true,
) {
override fun clone(): CookieAuthentication {
return CookieAuthentication().set(value) as CookieAuthentication
}
}
/**
* https://2019.www.torproject.org/docs/tor-manual.html.en#CookieAuthFile
* */
class CookieAuthFile : Setting<Option.FileSystemFile?>(
keyword = KeyWord.CookieAuthFile,
default = null,
isStartArgument = true,
) {
override fun set(value: Option.FileSystemFile?): Setting<Option.FileSystemFile?> {
return super.set(value?.nullIfEmpty)
}
override fun clone(): CookieAuthFile {
return CookieAuthFile().set(value) as CookieAuthFile
}
companion object {
const val DEFAULT_NAME = "control_auth_cookie"
}
}
/**
* https://2019.www.torproject.org/docs/tor-manual.html.en#DataDirectory
* */
class DataDirectory : Setting<Option.FileSystemDir?>(
keyword = KeyWord.DataDirectory,
default = null,
isStartArgument = true,
) {
override fun set(value: Option.FileSystemDir?): Setting<Option.FileSystemDir?> {
return super.set(value?.nullIfEmpty)
}
override fun clone(): DataDirectory {
return DataDirectory().set(value) as DataDirectory
}
companion object {
const val DEFAULT_NAME = "data"
}
}
/**
* https://2019.www.torproject.org/docs/tor-manual.html.en#DisableNetwork
* */
class DisableNetwork : Setting<Option.TorF>(
keyword = KeyWord.DisableNetwork,
default = Option.TorF.False,
isStartArgument = true,
) {
override fun clone(): DisableNetwork {
return DisableNetwork().set(value) as DisableNetwork
}
}
/**
* https://2019.www.torproject.org/docs/tor-manual.html.en#DormantCanceledByStartup
* */
class DormantCanceledByStartup : Setting<Option.TorF>(
keyword = KeyWord.DormantCanceledByStartup,
default = Option.TorF.False,
isStartArgument = true,
) {
override fun clone(): DormantCanceledByStartup {
return DormantCanceledByStartup().set(value) as DormantCanceledByStartup
}
}
/**
* https://2019.www.torproject.org/docs/tor-manual.html.en#DormantClientTimeout
* */
class DormantClientTimeout : Setting<Option.Time>(
keyword = KeyWord.DormantClientTimeout,
default = Option.Time.Hours(24),
isStartArgument = false,
) {
override fun set(value: Option.Time): Setting<Option.Time> {
return if (value is Option.Time.Minutes && value.time < 10) {
super.set(Option.Time.Minutes(10))
} else {
super.set(value)
}
}
override fun clone(): DormantClientTimeout {
return DormantClientTimeout().set(value) as DormantClientTimeout
}
}
/**
* https://2019.www.torproject.org/docs/tor-manual.html.en#DormantOnFirstStartup
* */
class DormantOnFirstStartup : Setting<Option.TorF>(
keyword = KeyWord.DormantOnFirstStartup,
default = Option.TorF.False,
isStartArgument = true,
) {
override fun clone(): DormantOnFirstStartup {
return DormantOnFirstStartup().set(value) as DormantOnFirstStartup
}
}
/**
* https://2019.www.torproject.org/docs/tor-manual.html.en#DormantTimeoutDisabledByIdleStreams
* */
class DormantTimeoutDisabledByIdleStreams : Setting<Option.TorF>(
keyword = KeyWord.DormantTimeoutDisabledByIdleStreams,
default = Option.TorF.True,
isStartArgument = false,
) {
override fun clone(): DormantTimeoutDisabledByIdleStreams {
return DormantTimeoutDisabledByIdleStreams().set(value) as DormantTimeoutDisabledByIdleStreams
}
}
/**
* https://2019.www.torproject.org/docs/tor-manual.html.en#GeoIPExcludeUnknown
* */
class GeoIPExcludeUnknown : Setting<Option.AorTorF>(
keyword = KeyWord.GeoIPExcludeUnknown,
default = Option.AorTorF.Auto,
isStartArgument = false,
) {
override fun clone(): GeoIPExcludeUnknown {
return GeoIPExcludeUnknown().set(value) as GeoIPExcludeUnknown
}
}
/**
* https://2019.www.torproject.org/docs/tor-manual.html.en#GeoIPFile
* */
class GeoIPFile : Setting<Option.FileSystemFile?>(
keyword = KeyWord.GeoIPFile,
default = null,
isStartArgument = true,
) {
override fun set(value: Option.FileSystemFile?): Setting<Option.FileSystemFile?> {
return super.set(value?.nullIfEmpty)
}
override fun clone(): GeoIPFile {
return GeoIPFile().set(value) as GeoIPFile
}
}
/**
* https://2019.www.torproject.org/docs/tor-manual.html.en#GeoIPv6File
* */
class GeoIpV6File : Setting<Option.FileSystemFile?>(
keyword = KeyWord.GeoIPv6File,
default = null,
isStartArgument = true,
) {
override fun set(value: Option.FileSystemFile?): Setting<Option.FileSystemFile?> {
return super.set(value?.nullIfEmpty)
}
override fun clone(): GeoIpV6File {
return GeoIpV6File().set(value) as GeoIpV6File
}
}
/**
* val hsDirPath = workDir.builder {
* addSegment(HiddenService.DEFAULT_PARENT_DIR_NAME)
* addSegment("my_hidden_service")
* }
*
* val myHiddenService = Setting.HiddenService()
* .setPorts(ports = setOf(
* Setting.HiddenService.UnixSocket(virtualPort = Port(80), targetUnixSocket = hsDirPath.builder {
* addSegment(Setting.HiddenService.UnixSocket.DEFAULT_UNIX_SOCKET_NAME)
* })
* Setting.HiddenService.Ports(virtualPort = Port(22))
* Setting.HiddenService.Ports(virtualPort = Port(8022), targetPort = Port(22))
* ))
* .setMaxStreams(maxStreams = Setting.HiddenService.MaxStreams(2))
* .setMaxStreamsCloseCircuit(value = TorF.False)
* .set(FileSystemDir(hsDirPath))
*
* Note that both `set` and `setPorts` _must_ be called for it to be added
* to your config.
*
* https://2019.www.torproject.org/docs/tor-manual.html.en#HiddenServiceDir
* https://2019.www.torproject.org/docs/tor-manual.html.en#HiddenServicePort
* https://2019.www.torproject.org/docs/tor-manual.html.en#HiddenServiceMaxStreams
* https://2019.www.torproject.org/docs/tor-manual.html.en#HiddenServiceMaxStreamsCloseCircuit
* */
class HiddenService : Setting<Option.FileSystemDir?>(
keyword = KeyWord.HiddenServiceDir,
default = null,
isStartArgument = false,
) {
/**
* See [HiddenService.VirtualPort]
* */
private val _ports: AtomicRef<Set<HiddenService.VirtualPort>?> = atomic(null)
@get:JvmName("ports")
val ports: Set<HiddenService.VirtualPort>? get() = _ports.value
/**
* A value of `null` means it will not be written to the config and falls
* back to Tor's default value of 0 (unlimited).
*
* @see [MaxStreams]
* */
private val _maxStreams: AtomicRef<MaxStreams?> = atomic(null)
@get:JvmName("maxStreams")
val maxStreams: MaxStreams? get() = _maxStreams.value
/**
* A value of `null` means it will not be written to the config and falls
* back to Tor's default setting of [Option.TorF.False]
* */
private val _maxStreamsCloseCircuit: AtomicRef<Option.TorF?> = atomic(null)
@get:JvmName("maxStreamsCloseCircuit")
val maxStreamsCloseCircuit: Option.TorF? get() = _maxStreamsCloseCircuit.value
override fun set(value: Option.FileSystemDir?): Setting<Option.FileSystemDir?> {
return super.set(value?.nullIfEmpty)
}
fun setPorts(ports: Set<VirtualPort>?): HiddenService {
if (isMutable) {
if (ports.isNullOrEmpty()) {
_ports.update { null }
} else {
val filtered = ports.filterSupportedOnly()
_ports.update { filtered }
}
}
return this
}
fun setMaxStreams(maxStreams: MaxStreams?): HiddenService {
if (isMutable) {
_maxStreams.update { maxStreams }
}
return this
}
fun setMaxStreamsCloseCircuit(value: Option.TorF?): HiddenService {
if (isMutable) {
_maxStreamsCloseCircuit.update { value }
}
return this
}
override fun setDefault(): HiddenService {
if (isMutable) {
super.setDefault()
_ports.update { null }
_maxStreams.update { null }
_maxStreamsCloseCircuit.update { null }
}
return this
}
override fun clone(): HiddenService {
return HiddenService()
.setPorts(ports)
.setMaxStreams(maxStreams)
.setMaxStreamsCloseCircuit(maxStreamsCloseCircuit)
.set(value) as HiddenService
}
override fun equals(other: Any?): Boolean {
return other is HiddenService && other.value == value
}
override fun hashCode(): Int {
return 14 * 31 + value.hashCode()
}
/**
* See [HiddenService.Ports] && [HiddenService.UnixSocket]
* */
sealed class VirtualPort
/**
* By default, [virtualPort] is always mapped to <localhostIp>:[targetPort]. This
* can be overridden by expressing a different value for [targetPort].
*
* EX:
* - Server running on Port(31276) with endpoint `/api/v1/endpoint`
* - Listen for all http traffic:
* Ports(virtualPort = Port(80), targetPort = Port(31276))
*
* http://<onion-address>.onion/api/v1/endpoint
*
* - Server configured for SSL connections, listen for all https traffic:
* Ports(virtualPort = Port(443), targetPort = Port(31276))
*
* https://<onion-address>.onion/api/v1/endpoint
*
* - Server configured for SSL connections:
* Ports(virtualPort = Port(31276))
*
* https://<onion-address>.onion:31276/api/v1/endpoint
*
* https://2019.www.torproject.org/docs/tor-manual.html.en#HiddenServicePort
* */
data class Ports(
@JvmField
val virtualPort: Port,
@JvmField
val targetPort: Port = virtualPort,
): VirtualPort()
/**
* Instead of directing traffic to a server on the local machine via
* TCP connection (and potentially leaking info), use a Unix Domain
* Socket and communicate via IPC.
*
* Support for this is only available for linux. If not on linux (or
* android). All [UnixSocket]s will be removed when [setPorts] is
* called, so it is safe to call this from common code.
*
* You can check [PlatformUtil.isLinux] when setting up your hidden
* service if you need to implement a fallback to use TCP.
*
* EX:
* - Server running on unix domain socket with endpoint `/api/v1/endpoint`
* - Listen for all http traffic:
* UnixSocket(
* virtualPort = Port(80),
* targetUnixSocket = Path("/home/user/.myApp/torservice/hidden_services/my_service/hs.sock")
* )
*
* http://<onion-address>.onion/api/v1/endpoint
*
* https://2019.www.torproject.org/docs/tor-manual.html.en#HiddenServicePort
* */
data class UnixSocket(
@JvmField
val virtualPort: Port,
@JvmField
val targetUnixSocket: Path,
): VirtualPort() {
companion object {
const val DEFAULT_UNIX_SOCKET_NAME = "hs.sock"
}
}
/**
* https://2019.www.torproject.org/docs/tor-manual.html.en#HiddenServiceMaxStreams
*
* @throws [IllegalArgumentException] if [value] is not within the inclusive range
* of 0 and 65535
* */
@SealedValueClass
sealed interface MaxStreams {
val value: Int
companion object {
@JvmStatic
@Throws(IllegalArgumentException::class)
operator fun invoke(value: Int): MaxStreams {
return RealMaxStreams(value)
}
}
}
@JvmInline
private value class RealMaxStreams(override val value: Int): MaxStreams {
init {
require(value in Port.MIN..Port.MAX) {
"MaxStreams.value must be between ${Port.MIN} and ${Port.MAX}"
}
}
override fun toString(): String {
return "MaxStreams(value=$value)"
}
}
companion object {
const val DEFAULT_PARENT_DIR_NAME = "hidden_services"
}
}
/**
* https://torproject.gitlab.io/torspec/control-spec/#takeownership
* */
class __OwningControllerProcess : Setting<Option.ProcessId?>(
keyword = KeyWord.__OwningControllerProcess,
default = null,
isStartArgument = true,
) {
override fun clone(): __OwningControllerProcess {
return __OwningControllerProcess().set(value) as __OwningControllerProcess
}
}
/**
* Configure TCP Ports for Tor's
* - [KeyWord.ControlPort]
* - [KeyWord.DnsPort]
* - [KeyWord.HttpTunnelPort]
* - [KeyWord.SocksPort]
* - [KeyWord.TransPort]
*
* @see [UnixSockets]
* */
sealed class Ports(
keyword: TorConfig.KeyWord,
default: Option.AorDorPort,
isStartArgument: Boolean,
) : Setting<Option.AorDorPort>(
keyword,
default,
isStartArgument
) {
override fun equals(other: Any?): Boolean {
if (other == null) {
return false
}
if (other !is Ports) {
return false
}
val otherValue = other.value
val thisValue = value
return if (
otherValue is Option.AorDorPort.Value &&
thisValue is Option.AorDorPort.Value
) {
// compare ports as to disallow setting same port for different Ports
otherValue == thisValue
} else {
other.keyword == keyword && otherValue == thisValue
}
}
override fun hashCode(): Int {
var result = 17 - 2
if (value is Option.AorDorPort.Value) {
// take value of the port only
result = result * 31 + value.hashCode()
} else {
result = result * 31 + keyword.hashCode()
result = result * 31 + value.hashCode()
}
return result
}
/**
*
* Note that Tor's default value as per the spec is disabled (0), so
* excluding it from your config will not set it to a Port. As this
* library depends on the [Control] port, the default value here differs
* and cannot be set to [Option.AorDorPort.Disable].
*
* It is not necessary to add this to your [TorConfig] when using TorManager,
* as if it is absent `TorManager.start` will automatically configure the
* [KeyWord.ControlPort] and open a Tor control connection for you.
*
* https://2019.www.torproject.org/docs/tor-manual.html.en#ControlPort
*
* @see [UnixSockets.Control]
* */
class Control : Ports(
keyword = KeyWord.ControlPort,
default = Option.AorDorPort.Auto,
isStartArgument = true,
) {
override fun set(value: Option.AorDorPort): Setting<Option.AorDorPort> {
return if (value !is Option.AorDorPort.Disable) {
super.set(value)
} else {
this
}
}
override fun clone(): Control {
return Control().set(value) as Control
}
}
/**
* https://2019.www.torproject.org/docs/tor-manual.html.en#DNSPort
* */
class Dns : Ports(
keyword = KeyWord.DnsPort,
default = Option.AorDorPort.Disable,
isStartArgument = false,
) {
private val _isolationFlags: AtomicRef<Set<IsolationFlag>?> = atomic(null)
@get:JvmName("isolationFlags")
val isolationFlags: Set<IsolationFlag>? get() = _isolationFlags.value
override fun setDefault(): Dns {
if (isMutable) {
super.setDefault()
_isolationFlags.update { null }
}
return this
}
fun setIsolationFlags(flags: Set<IsolationFlag>?): Dns {
if (isMutable) {
_isolationFlags.update { flags?.toSet() }
}
return this
}
override fun clone(): Dns {
return Dns().setIsolationFlags(isolationFlags).set(value) as Dns
}
}
/**
* https://2019.www.torproject.org/docs/tor-manual.html.en#HTTPTunnelPort
* */
class HttpTunnel : Ports(
keyword = KeyWord.HttpTunnelPort,
default = Option.AorDorPort.Disable,
isStartArgument = false,
) {
private val _isolationFlags: AtomicRef<Set<IsolationFlag>?> = atomic(null)
@get:JvmName("isolationFlags")
val isolationFlags: Set<IsolationFlag>? get() = _isolationFlags.value
override fun setDefault(): HttpTunnel {
if (isMutable) {
super.setDefault()
_isolationFlags.update { null }
}
return this
}
fun setIsolationFlags(flags: Set<IsolationFlag>?): HttpTunnel {
if (isMutable) {
_isolationFlags.update { flags?.toSet() }
}
return this
}
override fun clone(): HttpTunnel {
return HttpTunnel().setIsolationFlags(isolationFlags).set(value) as HttpTunnel
}
}
/**
* https://2019.www.torproject.org/docs/tor-manual.html.en#SocksPort
* */
class Socks : Ports(
keyword = KeyWord.SocksPort,
default = Option.AorDorPort.Value(PortProxy(9050)),
isStartArgument = false,
) {
private val _flags: AtomicRef<Set<Flag>?> = atomic(null)
@get:JvmName("flags")
val flags: Set<Flag>? get() = _flags.value
private val _isolationFlags: AtomicRef<Set<IsolationFlag>?> = atomic(null)
@get:JvmName("isolationFlags")
val isolationFlags: Set<IsolationFlag>? get() = _isolationFlags.value
override fun setDefault(): Socks {
if (isMutable) {
super.setDefault()
_flags.update { null }
_isolationFlags.update { null }
}
return this
}
fun setFlags(flags: Set<Flag>?): Socks {
if (isMutable) {
_flags.update { flags?.toSet() }
}
return this
}
fun setIsolationFlags(flags: Set<IsolationFlag>?): Socks {
if (isMutable) {
_isolationFlags.update { flags?.toSet() }
}
return this
}
override fun clone(): Socks {
return Socks()
.setFlags(flags)
.setIsolationFlags(isolationFlags)
.set(value) as Socks
}
sealed class Flag(@JvmField val value: String) {
override fun toString(): String = value
object NoIPv4Traffic : Flag("NoIPv4Traffic")
object IPv6Traffic : Flag("IPv6Traffic")
object PreferIPv6 : Flag("PreferIPv6")
object NoDNSRequest : Flag("NoDNSRequest")
object NoOnionTraffic : Flag("NoOnionTraffic")
object OnionTrafficOnly : Flag("OnionTrafficOnly")
object CacheIPv4DNS : Flag("CacheIPv4DNS")
object CacheIPv6DNS : Flag("CacheIPv6DNS")
object CacheDNS : Flag("CacheDNS")
object UseIPv4Cache : Flag("UseIPv4Cache")
object UseIPv6Cache : Flag("UseIPv6Cache")
object UseDNSCache : Flag("UseDNSCache")
object PreferIPv6Automap : Flag("PreferIPv6Automap")
object PreferSOCKSNoAuth : Flag("PreferSOCKSNoAuth")
}
}
/**
* https://2019.www.torproject.org/docs/tor-manual.html.en#TransPort
* */
class Trans : Ports(
keyword = KeyWord.TransPort,
default = Option.AorDorPort.Disable,
isStartArgument = false,
) {
private val _isolationFlags: AtomicRef<Set<IsolationFlag>?> = atomic(null)
@get:JvmName("isolationFlags")
val isolationFlags: Set<IsolationFlag>? get() = _isolationFlags.value
override fun set(value: Option.AorDorPort): Setting<Option.AorDorPort> {
return if (PlatformUtil.isLinux) {
super.set(value)
} else {
this
}
}
override fun setDefault(): Trans {
if (isMutable) {
super.setDefault()
_isolationFlags.update { null }
}
return this
}
fun setIsolationFlags(flags: Set<IsolationFlag>?): Trans {
if (isMutable) {
_isolationFlags.update { flags?.toSet() }
}
return this
}
override fun clone(): Trans {
return Trans().setIsolationFlags(isolationFlags).set(value) as Trans
}
}
/**
* https://2019.www.torproject.org/docs/tor-manual.html.en#SocksPort
* */
sealed class IsolationFlag(@JvmField val value: String) {
override fun toString(): String = value
object IsolateClientAddr : IsolationFlag("IsolateClientAddr")
object IsolateSOCKSAuth : IsolationFlag("IsolateSOCKSAuth")
object IsolateClientProtocol : IsolationFlag("IsolateClientProtocol")
object IsolateDestPort : IsolationFlag("IsolateDestPort")
object IsolateDestAddr : IsolationFlag("IsolateDestAddr")
object KeepAliveIsolateSOCKSAuth : IsolationFlag("KeepAliveIsolateSOCKSAuth")
class SessionGroup(id: Int) : IsolationFlag("SessionGroup=$id") {
init {
require(id >= 0) {
"SessionGroup.id must be greater than or equal to 0"
}
}
override fun equals(other: Any?): Boolean {
return other != null && other is SessionGroup
}
override fun hashCode(): Int {
return 17 * 31 + "SessionGroup".hashCode()
}
}
}
}
/**
* Specific [Setting] for using unix domain sockets for the [KeyWord.ControlPort] and
* [KeyWord.SocksPort]. Unix Domain Socket support is limited by Tor to Linux (and Android).
*
* @see [UnixSockets.Control]
* @see [UnixSockets.Socks]
* */
sealed class UnixSockets(
keyword: TorConfig.KeyWord,
isStartArgument: Boolean,
) : Setting<Option.FileSystemFile?>(
keyword,
default = null,
isStartArgument
) {
final override fun set(value: Option.FileSystemFile?): Setting<Option.FileSystemFile?> {
if (!(PlatformUtil.isLinux || PlatformUtil.isDarwin)) return this
// Do not set if unix domain sockets are not supported for control port
if (this is Control && !PlatformUtil.hasControlUnixDomainSocketSupport) return this
// First character of the path must be / (Unix FileSystem) root dir char
if (value?.path?.isUnixPath != true) return this
return super.set(value)
}
final override fun equals(other: Any?): Boolean {
return other is UnixSockets && other.value == value
}
final override fun hashCode(): Int {
var result = 17 - 3
result = result * 31 + value.hashCode()
return result
}
/**
* [UnixSockets.Control] must have support to be added to the [TorConfig]. For Android,
* nothing is needed as native support is had via `android.net.LocalSocket`. For the JVM,
* the extension `kmp-tor-ext-unix-socket` must be added to you Linux distrobution.
*
* If [PlatformUtil.hasControlUnixDomainSocketSupport] is false, calling [Control.set] will
* result in the [Option.FileSystemFile] not being set, and thus not being added to
* [TorConfig].
*
* It is not necessary to add this to your [TorConfig] when using TorManager, as if
* [PlatformUtil.hasControlUnixDomainSocketSupport] is true, it will automatically be
* added for you as the preferred way to establish a Tor control connection. To override
* this behavior, you can specify [Ports.Control] with your provided config.
*
* https://2019.www.torproject.org/docs/tor-manual.html.en#ControlPort
* */
class Control : UnixSockets(
keyword = KeyWord.ControlPort,
isStartArgument = true,
) {
private val _unixFlags: AtomicRef<Set<UnixSockets.Control.Flag>?> = atomic(null)
@get:JvmName("unixFlags")
val unixFlags: Set<UnixSockets.Control.Flag>? get() = _unixFlags.value
override fun setDefault(): Control {
if (isMutable) {
super.setDefault()
_unixFlags.update { null }
}
return this
}
fun setUnixFlags(flags: Set<UnixSockets.Control.Flag>?): Control {
if (isMutable) {
_unixFlags.update { flags?.toSet() }
}
return this
}
override fun clone(): Control {
return Control().setUnixFlags(unixFlags).set(value) as Control
}
sealed class Flag(@JvmField val value: String) {
override fun toString(): String = value
object RelaxDirModeCheck : Flag("RelaxDirModeCheck")
// conveniences...
companion object {
@get:JvmStatic
val GroupWritable get() = UnixSockets.Flag.GroupWritable
@get:JvmStatic
val WorldWritable get() = UnixSockets.Flag.WorldWritable
}
}
companion object {
const val DEFAULT_NAME = "control.sock"
}
}
/**
* [UnixSockets.Socks] must have support to be added to the [TorConfig].
*
* If [PlatformUtil.isLinux] is false, calling [Socks.set] will result in
* the [Option.FileSystemFile] not being set, and thus not being added to
* [TorConfig].
*
* If using TorManager, when you provide your [TorConfig] and there is
* neither a [Ports.Socks] or [UnixSockets.Socks] present, [Ports.Socks]
* will automatically be added for you. So, you can always add this [Setting]
* when providing your [TorConfig] to prefer using [UnixSockets] over [Ports].
*
* The resulting [Path] for [UnixSockets.Socks] will be dispatched via
* `AddressInfo.unixSocks` property when Tor bootstrapping is complete.
*
* https://2019.www.torproject.org/docs/tor-manual.html.en#SocksPort
* */
class Socks : UnixSockets(
keyword = KeyWord.SocksPort,
isStartArgument = false,
) {
private val _flags: AtomicRef<Set<Ports.Socks.Flag>?> = atomic(null)
@get:JvmName("flags")
val flags: Set<Ports.Socks.Flag>? get() = _flags.value
private val _unixFlags: AtomicRef<Set<UnixSockets.Flag>?> = atomic(null)
@get:JvmName("unixFlags")
val unixFlags: Set<UnixSockets.Flag>? get() = _unixFlags.value
private val _isolationFlags: AtomicRef<Set<Ports.IsolationFlag>?> = atomic(null)
@get:JvmName("isolationFlags")
val isolationFlags: Set<Ports.IsolationFlag>? get() = _isolationFlags.value
override fun setDefault(): Socks {
if (isMutable) {
super.setDefault()
_flags.update { null }
_unixFlags.update { null }
_isolationFlags.update { null }
}
return this
}
fun setFlags(flags: Set<Ports.Socks.Flag>?): Socks {
if (isMutable) {
_flags.update { flags?.toSet() }
}
return this
}
fun setUnixFlags(flags: Set<UnixSockets.Flag>?): Socks {
if (isMutable) {
_unixFlags.update { flags?.toSet() }
}
return this
}
fun setIsolationFlags(flags: Set<Ports.IsolationFlag>?): Socks {
if (isMutable) {
_isolationFlags.update { flags?.toSet() }
}
return this
}
override fun clone(): Socks {
return Socks()
.setFlags(flags)
.setUnixFlags(unixFlags)
.setIsolationFlags(isolationFlags)
.set(value) as Socks
}
companion object {
const val DEFAULT_NAME = "socks.sock"
}
}
sealed class Flag(value: String): UnixSockets.Control.Flag(value) {
object GroupWritable : Flag("GroupWritable")
object WorldWritable : Flag("WorldWritable")
}
}
/**
* https://2019.www.torproject.org/docs/tor-manual.html.en#RunAsDaemon
* */
class RunAsDaemon : Setting<Option.TorF>(
keyword = KeyWord.RunAsDaemon,
default = Option.TorF.False,
isStartArgument = true,
) {
override fun clone(): RunAsDaemon {
return RunAsDaemon().set(value) as RunAsDaemon
}
}
/**
* https://2019.www.torproject.org/docs/tor-manual.html.en#SyslogIdentityTag
* */
class SyslogIdentityTag : Setting<Option.FieldId?>(
keyword = KeyWord.SyslogIdentityTag,
default = null,
isStartArgument = true,
) {
override fun set(value: Option.FieldId?): Setting<Option.FieldId?> {
return super.set(value?.nullIfEmpty)
}
override fun clone(): SyslogIdentityTag {
return SyslogIdentityTag().set(value) as SyslogIdentityTag
}
}
/**
* https://2019.www.torproject.org/docs/tor-manual.html.en#VirtualAddrNetworkIPv4
* */
class VirtualAddrNetworkIPv4 : Setting<Option.Range.NetworkIPv4>(
keyword = KeyWord.VirtualAddrNetworkIPv4,
default = Option.Range.NetworkIPv4(
address = IPAddressV4("127.192.0.0"),
bits = 10,
),
isStartArgument = false
) {
override fun clone(): VirtualAddrNetworkIPv4 {
return VirtualAddrNetworkIPv4().set(value) as VirtualAddrNetworkIPv4
}
}
/**
* https://2019.www.torproject.org/docs/tor-manual.html.en#VirtualAddrNetworkIPv6
* */
class VirtualAddrNetworkIPv6 : Setting<Option.Range.NetworkIPv6>(
keyword = KeyWord.VirtualAddrNetworkIPv6,
default = Option.Range.NetworkIPv6(
address = IPAddressV6("FE80::"),
bits = 10,
),
isStartArgument = false
) {
override fun clone(): VirtualAddrNetworkIPv6 {
return VirtualAddrNetworkIPv6().set(value) as VirtualAddrNetworkIPv6
}
}
@Deprecated(
message = "Use TorConfig.Setting.GeoIPFile",
replaceWith = ReplaceWith(expression = "TorConfig.Setting.GeoIPFile")
)
class GeoIpV4File : Setting<Option.FileSystemFile?>(
keyword = KeyWord.GeoIPFile,
default = null,
isStartArgument = true,
) {
override fun set(value: Option.FileSystemFile?): Setting<Option.FileSystemFile?> {
return super.set(value?.nullIfEmpty)
}
@Suppress("DEPRECATION")
override fun clone(): GeoIpV4File {
return GeoIpV4File().set(value) as GeoIpV4File
}
}
/**
* https://torproject.gitlab.io/torspec/control-spec/#takeownership
* */
@Deprecated(
message = "Use TorConfig.Setting.__OwningControllerProcess",
replaceWith = ReplaceWith("TorConfig.Setting.__OwningControllerProcess")
)
class OwningControllerProcess : Setting<Option.ProcessId?>(
keyword = KeyWord.__OwningControllerProcess,
default = null,
isStartArgument = true,
) {
@Suppress("DEPRECATION")
override fun clone(): OwningControllerProcess {
return OwningControllerProcess().set(value) as OwningControllerProcess
}
}
}
sealed interface Option {
val value: String
/**
* Either [True] or [False]
* */
sealed interface TorF : AorTorF {
object True : TorF {
override val value: String = "1"
override fun toString(): String = value
}
object False : TorF {
override val value: String = "0"
override fun toString(): String = value
}
}
/**
* Either [Auto], [True], or [False]
* */
sealed interface AorTorF : Option {
object Auto : AorTorF {
override val value: String = "auto"
override fun toString(): String = value
}
// conveniences...
companion object {
@get:JvmStatic
val True: TorF.True get() = TorF.True
@get:JvmStatic
val False: TorF.False get() = TorF.False
}
}
/**
* Either [Auto], [Disable], or [Value] containing a [Port]
* */
sealed interface AorDorPort : Option {
object Auto : AorDorPort {
override val value: String get() = AorTorF.Auto.value
override fun toString(): String = value
}
object Disable : AorDorPort {
override val value: String get() = TorF.False.value
override fun toString(): String = value
}
@SealedValueClass
sealed interface Value : AorDorPort {
val port: PortProxy
companion object {
@JvmStatic
operator fun invoke(port: PortProxy): Value {
return RealValue(port)
}
}
}
@JvmInline
private value class RealValue(override val port: PortProxy) : Value {
override val value: String get() = port.value.toString()
override fun toString(): String = value
}
}
@SealedValueClass
sealed interface FileSystemFile : Option {
val path: Path
val nullIfEmpty: FileSystemFile?
companion object {
@JvmStatic
operator fun invoke(path: Path): FileSystemFile {
return RealFileSystemFile(path)
}
}
}
@JvmInline
private value class RealFileSystemFile(override val path: Path): FileSystemFile {
override val value: String get() = path.value
override val nullIfEmpty: FileSystemFile? get() = if (value.isEmpty()) null else this
override fun toString(): String = value
}
@SealedValueClass
sealed interface FileSystemDir : Option {
val path: Path
val nullIfEmpty: FileSystemDir?
companion object {
@JvmStatic
operator fun invoke(path: Path): FileSystemDir {
return RealFileSystemDir(path)
}
}
}
@JvmInline
private value class RealFileSystemDir(override val path: Path) : FileSystemDir {
override val value: String get() = path.value
override val nullIfEmpty: FileSystemDir? get() = if (value.isEmpty()) null else this
override fun toString(): String = value
}
@SealedValueClass
sealed interface FieldId : Option {
val nullIfEmpty: FieldId?
companion object {
@JvmStatic
operator fun invoke(value: String): FieldId {
return RealFieldId(value)
}
}
}
@JvmInline
private value class RealFieldId(override val value: String) : FieldId {
override val nullIfEmpty: FieldId? get() = if (value.isEmpty()) null else this
override fun toString(): String = value
}
@SealedValueClass
sealed interface ProcessId : Option {
val pid: Int
companion object {
@JvmStatic
operator fun invoke(pid: Int): ProcessId {
return RealProcessId(pid)
}
}
}
@JvmInline
private value class RealProcessId(override val pid: Int) : ProcessId {
override val value: String get() = "$pid"
override fun toString(): String = value
}
sealed interface Range : Option {
@SealedValueClass
sealed interface NetworkIPv4 : Range {
companion object {
/**
* [bits] must be between 0 and 16
* */
@JvmStatic
@Throws(IllegalArgumentException::class)
operator fun invoke(address: IPAddressV4, bits: Int): NetworkIPv4 {
require(bits in 0..16) {
"bits must be between 0 and 16"
}
return RealNetworkIPv4Range("${address.canonicalHostname()}/$bits")
}
}
}
@JvmInline
private value class RealNetworkIPv4Range(override val value: String) : NetworkIPv4 {
override fun toString(): String = value
}
@SealedValueClass
sealed interface NetworkIPv6 : Range {
companion object {
/**
* [bits] must be between 0 and 104
* */
@JvmStatic
@Throws(IllegalArgumentException::class)
operator fun invoke(address: IPAddressV6, bits: Int): NetworkIPv6 {
require(bits in 0..104) {
"bits must be between 0 and 104"
}
return RealNetworkIPv6Range("${address.canonicalHostname()}/$bits")
}
}
}
@JvmInline
private value class RealNetworkIPv6Range(override val value: String): NetworkIPv6 {
override fun toString(): String = value
}
}
sealed interface Time : Option {
val time: Int
@SealedValueClass
sealed interface Minutes : Time {
companion object {
@JvmStatic
operator fun invoke(time: Int): Minutes {
return RealMinutes(time)
}
}
}
@JvmInline
private value class RealMinutes(override val time: Int) : Minutes {
override val value: String get() = if (time < 1) {
"1 minutes"
} else {
"$time minutes"
}
override fun toString(): String = value
}
@SealedValueClass
sealed interface Hours : Time {
companion object {
@JvmStatic
operator fun invoke(time: Int): Hours {
return RealHours(time)
}
}
}
@JvmInline
private value class RealHours(override val time: Int) : Hours {
override val value: String get() = if (time < 1) {
"1 hours"
} else {
"$time hours"
}
override fun toString(): String = value
}
@SealedValueClass
sealed interface Days : Time {
companion object {
@JvmStatic
operator fun invoke(time: Int): Days {
return RealDays(time)
}
}
}
@JvmInline
private value class RealDays(override val time: Int) : Days {
override val value: String get() = if (time < 1) {
"1 days"
} else {
"$time days"
}
override fun toString(): String = value
}
@SealedValueClass
sealed interface Weeks : Time {
companion object {
@JvmStatic
operator fun invoke(time: Int): Weeks {
return RealWeeks(time)
}
}
}
@JvmInline
private value class RealWeeks(override val time: Int) : Weeks {
override val value: String get() = if (time < 1) {
"1 weeks"
} else {
"$time weeks"
}
override fun toString(): String = value
}
}
}
/**
* KeyWords utilized in TorConfig, as defined in:
* - https://2019.www.torproject.org/docs/tor-manual.html.en
* - https://torproject.gitlab.io/torspec/control-spec/#tor-config-options-for-use-by-controllers
*
* Ordering of KeyWords match that of what is in the above manuals. To keep track of what
* has and has not been implemented as a [Setting], the following "headers" are used:
*
* /* IMPLEMENTED */
* /* NOT IMPLEMENTED */
* */
@Suppress("ClassName")
sealed class KeyWord: Comparable<String>, CharSequence {
// NOTE: If adding any KeyWords, be sure to update the integration test model at
// `:library:kmp-tor:commonTest/kotlin/io/matthewnelson/kmp/tor/helpers/model/KeyWordModel.kt`
// to validate it via the integration test.
final override val length: Int get() = toString().length
final override fun get(index: Int): Char = toString()[index]
final override fun subSequence(startIndex: Int, endIndex: Int): CharSequence {
return toString().subSequence(startIndex, endIndex)
}
final override fun compareTo(other: String): Int = toString().compareTo(other)
operator fun plus(other: Any?): String = toString() + other
final override fun equals(other: Any?): Boolean = other is KeyWord && other.toString() == toString()
final override fun hashCode(): Int = 21 * 31 + toString().hashCode()
/* IMPLEMENTED */
/* === GENERAL OPTIONS ======================== IMPLEMENTED as a TorConfig.Setting ================================== */
object DisableNetwork: KeyWord() { override fun toString(): String = "DisableNetwork" }
object ControlPort: KeyWord() { override fun toString(): String = "ControlPort" }
object CookieAuthentication: KeyWord() { override fun toString(): String = "CookieAuthentication" }
object CookieAuthFile: KeyWord() { override fun toString(): String = "CookieAuthFile" }
object ControlPortWriteToFile: KeyWord() { override fun toString(): String = "ControlPortWriteToFile" }
object DataDirectory: KeyWord() { override fun toString(): String = "DataDirectory" }
object CacheDirectory: KeyWord() { override fun toString(): String = "CacheDirectory" }
object RunAsDaemon: KeyWord() { override fun toString(): String = "RunAsDaemon" }
object SyslogIdentityTag: KeyWord() { override fun toString(): String = "SyslogIdentityTag" }
/* === CLIENT OPTIONS ========================= IMPLEMENTED as a TorConfig.Setting ================================== */
object ConnectionPadding: KeyWord() { override fun toString(): String = "ConnectionPadding" }
object ReducedConnectionPadding: KeyWord() { override fun toString(): String = "ReducedConnectionPadding" }
object GeoIPExcludeUnknown: KeyWord() { override fun toString(): String = "GeoIPExcludeUnknown" }
object ClientOnionAuthDir: KeyWord() { override fun toString(): String = "ClientOnionAuthDir" }
object SocksPort: KeyWord() { override fun toString(): String = "SocksPort" }
object VirtualAddrNetworkIPv4: KeyWord() { override fun toString(): String = "VirtualAddrNetworkIPv4" }
object VirtualAddrNetworkIPv6: KeyWord() { override fun toString(): String = "VirtualAddrNetworkIPv6" }
object HttpTunnelPort: KeyWord() { override fun toString(): String = "HTTPTunnelPort" }
object TransPort: KeyWord() { override fun toString(): String = "TransPort" }
object AutomapHostsOnResolve: KeyWord() { override fun toString(): String = "AutomapHostsOnResolve" }
object DnsPort: KeyWord() { override fun toString(): String = "DNSPort" }
object DormantClientTimeout: KeyWord() { override fun toString(): String = "DormantClientTimeout" }
object DormantTimeoutDisabledByIdleStreams: KeyWord() { override fun toString(): String = "DormantTimeoutDisabledByIdleStreams" }
object DormantOnFirstStartup: KeyWord() { override fun toString(): String = "DormantOnFirstStartup" }
object DormantCanceledByStartup: KeyWord() { override fun toString(): String = "DormantCanceledByStartup" }
/* === SERVER OPTIONS ========================= IMPLEMENTED as a TorConfig.Setting ================================== */
object GeoIPFile: KeyWord() { override fun toString(): String = "GeoIPFile" }
object GeoIPv6File: KeyWord() { override fun toString(): String = "GeoIPv6File" }
/* === DIRECTORY SERVER OPTIONS =============== IMPLEMENTED as a TorConfig.Setting ================================== */
/* === DENAIL OF SERVICE MITIGATION OPTIONS === IMPLEMENTED as a TorConfig.Setting ================================== */
/* === DIRECTORY AUTHORITY SERVER OPTIONS ===== IMPLEMENTED as a TorConfig.Setting ================================== */
/* === HIDDEN SERVICE OPTIONS ================= IMPLEMENTED as a TorConfig.Setting ================================== */
object HiddenServiceDir: KeyWord() { override fun toString(): String = "HiddenServiceDir" }
object HiddenServicePort: KeyWord() { override fun toString(): String = "HiddenServicePort" }
object HiddenServiceMaxStreams: KeyWord() { override fun toString(): String = "HiddenServiceMaxStreams" }
object HiddenServiceMaxStreamsCloseCircuit: KeyWord() { override fun toString(): String = "HiddenServiceMaxStreamsCloseCircuit" }
/* === TESTING NETWORK OPTIONS ================ IMPLEMENTED as a TorConfig.Setting ================================== */
/* === NON-PERSISTENT OPTIONS ================= IMPLEMENTED as a TorConfig.Setting ================================== */
/* === NON-PERSISTENT CONTROLLER OPTIONS ====== IMPLEMENTED as a TorConfig.Setting ================================== */
object __OwningControllerProcess: KeyWord() { override fun toString(): String = "__OwningControllerProcess" }
/* NOT IMPLEMENTED */
/* === GENERAL OPTIONS ======================== NOT yet implemented as a TorConfig.Setting ========================== */
object BandwidthRate: KeyWord() { override fun toString(): String = "BandwidthRate" }
object BandwidthBurst: KeyWord() { override fun toString(): String = "BandwidthBurst" }
object MaxAdvertisedBandwidth: KeyWord() { override fun toString(): String = "MaxAdvertisedBandwidth" }
object RelayBandwidthRate: KeyWord() { override fun toString(): String = "RelayBandwidthRate" }
object RelayBandwidthBurst: KeyWord() { override fun toString(): String = "RelayBandwidthBurst" }
object PerConnBWRate: KeyWord() { override fun toString(): String = "PerConnBWRate" }
object PerConnBWBurst: KeyWord() { override fun toString(): String = "PerConnBWBurst" }
object ClientTransportPlugin: KeyWord() { override fun toString(): String = "ClientTransportPlugin" }
object ServerTransportPlugin: KeyWord() { override fun toString(): String = "ServerTransportPlugin" }
object ServerTransportListenAddr: KeyWord() { override fun toString(): String = "ServerTransportListenAddr" }
object ServerTransportOptions: KeyWord() { override fun toString(): String = "ServerTransportOptions" }
object ExtORPort: KeyWord() { override fun toString(): String = "ExtORPort" }
object ExtORPortCookieAuthFile: KeyWord() { override fun toString(): String = "ExtORPortCookieAuthFile" }
object ExtORPortCookieAuthFileGroupReadable: KeyWord() { override fun toString(): String = "ExtORPortCookieAuthFileGroupReadable" }
object ConnLimit: KeyWord() { override fun toString(): String = "ConnLimit" }
// DisableNetwork (IMPLEMENTED)
object ConstrainedSockets: KeyWord() { override fun toString(): String = "ConstrainedSockets" }
object ConstrainedSockSize: KeyWord() { override fun toString(): String = "ConstrainedSockSize" }
// ControlPort (IMPLEMENTED)
object ControlSocket: KeyWord() { override fun toString(): String = "ControlSocket" }
object ControlSocketsGroupWritable: KeyWord() { override fun toString(): String = "ControlSocketsGroupWritable" }
object HashedControlPassword: KeyWord() { override fun toString(): String = "HashedControlPassword" }
// CookieAuthentication (IMPLEMENTED)
// CookieAuthFile (IMPLEMENTED)
object CookieAuthFileGroupReadable: KeyWord() { override fun toString(): String = "CookieAuthFileGroupReadable" }
// ControlPortWriteToFile (IMPLEMENTED)
object ControlPortFileGroupReadable: KeyWord() { override fun toString(): String = "ControlPortFileGroupReadable" }
// DataDirectory (IMPLEMENTED)
object DataDirectoryGroupReadable: KeyWord() { override fun toString(): String = "DataDirectoryGroupReadable" }
// CacheDirectory (IMPLEMENTED)
object CacheDirectoryGroupReadable: KeyWord() { override fun toString(): String = "CacheDirectoryGroupReadable" }
object FallbackDir: KeyWord() { override fun toString(): String = "FallbackDir" }
object UseDefaultFallbackDirs: KeyWord() { override fun toString(): String = "UseDefaultFallbackDirs" }
object DirAuthority: KeyWord() { override fun toString(): String = "DirAuthority" }
object DirAuthorityFallbackRate: KeyWord() { override fun toString(): String = "DirAuthorityFallbackRate" }
object AlternateBridgeAuthority: KeyWord() { override fun toString(): String = "AlternateBridgeAuthority" }
object DisableAllSwap: KeyWord() { override fun toString(): String = "DisableAllSwap" }
object DisableDebuggerAttachment: KeyWord() { override fun toString(): String = "DisableDebuggerAttachment" }
object FetchDirInfoEarly: KeyWord() { override fun toString(): String = "FetchDirInfoEarly" }
object FetchDirInfoExtraEarly: KeyWord() { override fun toString(): String = "FetchDirInfoExtraEarly" }
object FetchHidServDescriptors: KeyWord() { override fun toString(): String = "FetchHidServDescriptors" }
object FetchServerDescriptors: KeyWord() { override fun toString(): String = "FetchServerDescriptors" }
object FetchUselessDescriptors: KeyWord() { override fun toString(): String = "FetchUselessDescriptors" }
// HTTPProxy (DEPRECATED)
// HTTPProxyAuthenticator (DEPRECATED)
object HTTPSProxy: KeyWord() { override fun toString(): String = "HTTPSProxy" }
object HTTPSProxyAuthenticator: KeyWord() { override fun toString(): String = "HTTPSProxyAuthenticator" }
object Sandbox: KeyWord() { override fun toString(): String = "Sandbox" }
object Socks4Proxy: KeyWord() { override fun toString(): String = "Socks4Proxy" }
object Socks5Proxy: KeyWord() { override fun toString(): String = "Socks5Proxy" }
object Socks5ProxyPassword: KeyWord() { override fun toString(): String = "Socks5ProxyPassword" }
object UnixSocksGroupWritable: KeyWord() { override fun toString(): String = "UnixSocksGroupWritable" }
object KeepalivePeriod: KeyWord() { override fun toString(): String = "KeepalivePeriod" }
object Log: KeyWord() { override fun toString(): String = "Log" }
object LogMessageDomains: KeyWord() { override fun toString(): String = "LogMessageDomains" }
object MaxUnparseableDescSizeToLog: KeyWord() { override fun toString(): String = "MaxUnparseableDescSizeToLog" }
object OutboundBindAddress: KeyWord() { override fun toString(): String = "OutboundBindAddress" }
object OutboundBindAddressOR: KeyWord() { override fun toString(): String = "OutboundBindAddressOR" }
object OutboundBindAddressExit: KeyWord() { override fun toString(): String = "OutboundBindAddressExit" }
object PidFile: KeyWord() { override fun toString(): String = "PidFile" }
object ProtocolWarnings: KeyWord() { override fun toString(): String = "ProtocolWarnings" }
// RunAsDaemon (IMPLEMENTED)
object LogTimeGranularity: KeyWord() { override fun toString(): String = "LogTimeGranularity" }
object TruncateLogFile: KeyWord() { override fun toString(): String = "TruncateLogFile" }
// SyslogIdentityTag (IMPLEMENTED)
object AndroidIdentityTag: KeyWord() { override fun toString(): String = "AndroidIdentityTag" }
object SafeLogging: KeyWord() { override fun toString(): String = "SafeLogging" }
object User: KeyWord() { override fun toString(): String = "User" }
object KeepBindCapabilities: KeyWord() { override fun toString(): String = "KeepBindCapabilities" }
object HardwareAccel: KeyWord() { override fun toString(): String = "HardwareAccel" }
object AccelName: KeyWord() { override fun toString(): String = "AccelName" }
object AccelDir: KeyWord() { override fun toString(): String = "AccelDir" }
object AvoidDiskWrites: KeyWord() { override fun toString(): String = "AvoidDiskWrites" }
object CircuitPriorityHalflife: KeyWord() { override fun toString(): String = "CircuitPriorityHalflife" }
object CountPrivateBandwidth: KeyWord() { override fun toString(): String = "CountPrivateBandwidth" }
object ExtendByEd25519ID: KeyWord() { override fun toString(): String = "ExtendByEd25519ID" }
object NoExec: KeyWord() { override fun toString(): String = "NoExec" }
object Schedulers: KeyWord() { override fun toString(): String = "Schedulers" }
object KISTSchedRunInterval: KeyWord() { override fun toString(): String = "KISTSchedRunInterval" }
object KISTSockBufSizeFactor: KeyWord() { override fun toString(): String = "KISTSockBufSizeFactor" }
/* === CLIENT OPTIONS ========================= NOT yet implemented as a TorConfig.Setting ========================== */
object Bridge: KeyWord() { override fun toString(): String = "Bridge" }
object LearnCircuitBuildTimeout: KeyWord() { override fun toString(): String = "LearnCircuitBuildTimeout" }
object CircuitBuildTimeout: KeyWord() { override fun toString(): String = "CircuitBuildTimeout" }
object CircuitsAvailableTimeout: KeyWord() { override fun toString(): String = "CircuitsAvailableTimeout" }
object CircuitStreamTimeout: KeyWord() { override fun toString(): String = "CircuitStreamTimeout" }
object ClientOnly: KeyWord() { override fun toString(): String = "ClientOnly" }
// ConnectionPadding (IMPLEMENTED)
// ReducedConnectionPadding (IMPLEMENTED)
object ExcludeNodes: KeyWord() { override fun toString(): String = "ExcludeNodes" }
object ExcludeExitNodes: KeyWord() { override fun toString(): String = "ExcludeExitNodes" }
// GeoIPExcludeUnknown (IMPLEMENTED)
object ExitNodes: KeyWord() { override fun toString(): String = "ExitNodes" }
object MiddleNodes: KeyWord() { override fun toString(): String = "MiddleNodes" }
object EntryNodes: KeyWord() { override fun toString(): String = "EntryNodes" }
object StrictNodes: KeyWord() { override fun toString(): String = "StrictNodes" }
object FascistFirewall: KeyWord() { override fun toString(): String = "FascistFirewall" }
// FirewallPorts (DEPRECATED)
object ReachableAddresses: KeyWord() { override fun toString(): String = "ReachableAddresses" }
// ReachableDirAddresses (DEPRECATED)
object ReachableORAddresses: KeyWord() { override fun toString(): String = "ReachableORAddresses" }
object HidServAuth: KeyWord() { override fun toString(): String = "HidServAuth" }
// ClientOnionAuthDir (IMPLEMENTED)
object LongLivedPorts: KeyWord() { override fun toString(): String = "LongLivedPorts" }
object MapAddress: KeyWord() { override fun toString(): String = "MapAddress" }
object NewCircuitPeriod: KeyWord() { override fun toString(): String = "NewCircuitPeriod" }
object MaxCircuitDirtiness: KeyWord() { override fun toString(): String = "MaxCircuitDirtiness" }
object MaxClientCircuitsPending: KeyWord() { override fun toString(): String = "MaxClientCircuitsPending" }
object NodeFamily: KeyWord() { override fun toString(): String = "NodeFamily" }
object EnforceDistinctSubnets: KeyWord() { override fun toString(): String = "EnforceDistinctSubnets" }
// SocksPort (IMPLEMENTED)
object SocksPolicy: KeyWord() { override fun toString(): String = "SocksPolicy" }
object SocksTimeout: KeyWord() { override fun toString(): String = "SocksTimeout" }
object TokenBucketRefillInterval: KeyWord() { override fun toString(): String = "TokenBucketRefillInterval" }
object TrackHostExits: KeyWord() { override fun toString(): String = "TrackHostExits" }
object TrackHostExitsExpire: KeyWord() { override fun toString(): String = "TrackHostExitsExpire" }
object UpdateBridgesFromAuthority: KeyWord() { override fun toString(): String = "UpdateBridgesFromAuthority" }
object UseBridges: KeyWord() { override fun toString(): String = "UseBridges" }
object UseEntryGuards: KeyWord() { override fun toString(): String = "UseEntryGuards" }
object GuardfractionFile: KeyWord() { override fun toString(): String = "GuardfractionFile" }
object UseGuardFraction: KeyWord() { override fun toString(): String = "UseGuardFraction" }
object NumEntryGuards: KeyWord() { override fun toString(): String = "NumEntryGuards" }
object NumPrimaryGuards: KeyWord() { override fun toString(): String = "NumPrimaryGuards" }
object NumDirectoryGuards: KeyWord() { override fun toString(): String = "NumDirectoryGuards" }
object GuardLifetime: KeyWord() { override fun toString(): String = "GuardLifetime" }
object SafeSocks: KeyWord() { override fun toString(): String = "SafeSocks" }
object TestSocks: KeyWord() { override fun toString(): String = "TestSocks" }
// VirtualAddrNetworkIPv4 (IMPLEMENTED)
// VirtualAddrNetworkIPv6 (IMPLEMENTED)
object AllowNonRFC953Hostnames: KeyWord() { override fun toString(): String = "AllowNonRFC953Hostnames" }
// HTTPTunnelPort (IMPLEMENTED)
// TransPort (IMPLEMENTED)
object TransProxyType: KeyWord() { override fun toString(): String = "TransProxyType" }
object NATDPort: KeyWord() { override fun toString(): String = "NATDPort" }
// AutomapHostsOnResolve (IMPLEMENTED)
object AutomapHostsSuffixes: KeyWord() { override fun toString(): String = "AutomapHostsSuffixes" }
// DNSPort (IMPLEMENTED)
object ClientDNSRejectInternalAddresses: KeyWord() { override fun toString(): String = "ClientDNSRejectInternalAddresses" }
object ClientRejectInternalAddresses: KeyWord() { override fun toString(): String = "ClientRejectInternalAddresses" }
object DownloadExtraInfo: KeyWord() { override fun toString(): String = "DownloadExtraInfo" }
object WarnPlaintextPorts: KeyWord() { override fun toString(): String = "WarnPlaintextPorts" }
object RejectPlaintextPorts: KeyWord() { override fun toString(): String = "RejectPlaintextPorts" }
object OptimisticData: KeyWord() { override fun toString(): String = "OptimisticData" }
object HSLayer2Nodes: KeyWord() { override fun toString(): String = "HSLayer2Nodes" }
object HSLayer3Nodes: KeyWord() { override fun toString(): String = "HSLayer3Nodes" }
object UseMicrodescriptors: KeyWord() { override fun toString(): String = "UseMicrodescriptors" }
object PathBiasScaleThreshold: KeyWord() { override fun toString(): String = "PathBiasScaleThreshold" }
object PathBiasScaleUseThreshold: KeyWord() { override fun toString(): String = "PathBiasScaleUseThreshold" }
object ClientUseIPv4: KeyWord() { override fun toString(): String = "ClientUseIPv4" }
object ClientUseIPv6: KeyWord() { override fun toString(): String = "ClientUseIPv6" }
object ClientPreferIPv6ORPort: KeyWord() { override fun toString(): String = "ClientPreferIPv6ORPort" }
object ClientAutoIPv6ORPort: KeyWord() { override fun toString(): String = "ClientAutoIPv6ORPort" }
object PathsNeededToBuildCircuits: KeyWord() { override fun toString(): String = "PathsNeededToBuildCircuits" }
object ClientBootstrapConsensusAuthorityDownloadInitialDelay: KeyWord() { override fun toString(): String = "ClientBootstrapConsensusAuthorityDownloadInitialDelay" }
object ClientBootstrapConsensusFallbackDownloadInitialDelay: KeyWord() { override fun toString(): String = "ClientBootstrapConsensusFallbackDownloadInitialDelay" }
object ClientBootstrapConsensusAuthorityOnlyDownloadInitialDelay: KeyWord() { override fun toString(): String = "ClientBootstrapConsensusAuthorityOnlyDownloadInitialDelay" }
object ClientBootstrapConsensusMaxInProgressTries: KeyWord() { override fun toString(): String = "ClientBootstrapConsensusMaxInProgressTries" }
// DormantClientTimeout (IMPLEMENTED)
// DormantTimeoutDisabledByIdleStreams (IMPLEMENTED)
// DormantOnFirstStartup (IMPLEMENTED)
// DormantCanceledByStartup (IMPLEMENTED)
/* === SERVER OPTIONS ========================= NOT yet implemented as a TorConfig.Setting ========================== */
object Address: KeyWord() { override fun toString(): String = "Address" }
object AssumeReachable: KeyWord() { override fun toString(): String = "AssumeReachable" }
object BridgeRelay: KeyWord() { override fun toString(): String = "BridgeRelay" }
object BridgeDistribution: KeyWord() { override fun toString(): String = "BridgeDistribution" }
object ContactInfo: KeyWord() { override fun toString(): String = "ContactInfo" }
object ExitRelay: KeyWord() { override fun toString(): String = "ExitRelay" }
object ExitPolicy: KeyWord() { override fun toString(): String = "ExitPolicy" }
object ExitPolicyRejectPrivate: KeyWord() { override fun toString(): String = "ExitPolicyRejectPrivate" }
object ExitPolicyRejectLocalInterfaces: KeyWord() { override fun toString(): String = "ExitPolicyRejectLocalInterfaces" }
object ReducedExitPolicy: KeyWord() { override fun toString(): String = "ReducedExitPolicy" }
object IPv6Exit: KeyWord() { override fun toString(): String = "IPv6Exit" }
object MaxOnionQueueDelay: KeyWord() { override fun toString(): String = "MaxOnionQueueDelay" }
object MyFamily: KeyWord() { override fun toString(): String = "MyFamily" }
object Nickname: KeyWord() { override fun toString(): String = "Nickname" }
object NumCPUs: KeyWord() { override fun toString(): String = "NumCPUs" }
object ORPort: KeyWord() { override fun toString(): String = "ORPort" }
object PublishServerDescriptor: KeyWord() { override fun toString(): String = "PublishServerDescriptor" }
object ShutdownWaitLength: KeyWord() { override fun toString(): String = "ShutdownWaitLength" }
object SSLKeyLifetime: KeyWord() { override fun toString(): String = "SSLKeyLifetime" }
object HeartbeatPeriod: KeyWord() { override fun toString(): String = "HeartbeatPeriod" }
object MainloopStats: KeyWord() { override fun toString(): String = "MainloopStats" }
object AccountingMax: KeyWord() { override fun toString(): String = "AccountingMax" }
object AccountingRule: KeyWord() { override fun toString(): String = "AccountingRule" }
object AccountingStart: KeyWord() { override fun toString(): String = "AccountingStart" }
object RefuseUnknownExits: KeyWord() { override fun toString(): String = "RefuseUnknownExits" }
object ServerDNSResolvConfFile: KeyWord() { override fun toString(): String = "ServerDNSResolvConfFile" }
object ServerDNSAllowBrokenConfig: KeyWord() { override fun toString(): String = "ServerDNSAllowBrokenConfig" }
object ServerDNSSearchDomains: KeyWord() { override fun toString(): String = "ServerDNSSearchDomains" }
object ServerDNSDetectHijacking: KeyWord() { override fun toString(): String = "ServerDNSDetectHijacking" }
object ServerDNSTestAddresses: KeyWord() { override fun toString(): String = "ServerDNSTestAddresses" }
object ServerDNSAllowNonRFC953Hostnames: KeyWord() { override fun toString(): String = "ServerDNSAllowNonRFC953Hostnames" }
object BridgeRecordUsageByCountry: KeyWord() { override fun toString(): String = "BridgeRecordUsageByCountry" }
object ServerDNSRandomizeCase: KeyWord() { override fun toString(): String = "ServerDNSRandomizeCase" }
// GeoIPFile (IMPLEMENTED)
// GeoIPv6File (IMPLEMENTED)
object CellStatistics: KeyWord() { override fun toString(): String = "CellStatistics" }
object PaddingStatistics: KeyWord() { override fun toString(): String = "PaddingStatistics" }
object DirReqStatistics: KeyWord() { override fun toString(): String = "DirReqStatistics" }
object EntryStatistics: KeyWord() { override fun toString(): String = "EntryStatistics" }
object ExitPortStatistics: KeyWord() { override fun toString(): String = "ExitPortStatistics" }
object ConnDirectionStatistics: KeyWord() { override fun toString(): String = "ConnDirectionStatistics" }
object HiddenServiceStatistics: KeyWord() { override fun toString(): String = "HiddenServiceStatistics" }
object ExtraInfoStatistics: KeyWord() { override fun toString(): String = "ExtraInfoStatistics" }
object ExtendAllowPrivateAddresses: KeyWord() { override fun toString(): String = "ExtendAllowPrivateAddresses" }
object MaxMemInQueues: KeyWord() { override fun toString(): String = "MaxMemInQueues" }
object DisableOOSCheck: KeyWord() { override fun toString(): String = "DisableOOSCheck" }
object SigningKeyLifetime: KeyWord() { override fun toString(): String = "SigningKeyLifetime" }
object OfflineMasterKey: KeyWord() { override fun toString(): String = "OfflineMasterKey" }
object KeyDirectory: KeyWord() { override fun toString(): String = "KeyDirectory" }
object KeyDirectoryGroupReadable: KeyWord() { override fun toString(): String = "KeyDirectoryGroupReadable" }
object RephistTrackTime: KeyWord() { override fun toString(): String = "RephistTrackTime" }
/* === DIRECTORY SERVER OPTIONS =============== NOT yet implemented as a TorConfig.Setting ========================== */
object DirPortFrontPage: KeyWord() { override fun toString(): String = "DirPortFrontPage" }
object DirPort: KeyWord() { override fun toString(): String = "DirPort" }
object DirPolicy: KeyWord() { override fun toString(): String = "DirPolicy" }
object DirCache: KeyWord() { override fun toString(): String = "DirCache" }
object MaxConsensusAgeForDiffs: KeyWord() { override fun toString(): String = "MaxConsensusAgeForDiffs" }
/* === DENAIL OF SERVICE MITIGATION OPTIONS === NOT yet implemented as a TorConfig.Setting ========================== */
object DoSCircuitCreationEnabled: KeyWord() { override fun toString(): String = "DoSCircuitCreationEnabled" }
object DoSCircuitCreationMinConnections: KeyWord() { override fun toString(): String = "DoSCircuitCreationMinConnections" }
object DoSCircuitCreationRate: KeyWord() { override fun toString(): String = "DoSCircuitCreationRate" }
object DoSCircuitCreationBurst: KeyWord() { override fun toString(): String = "DoSCircuitCreationBurst" }
object DoSCircuitCreationDefenseType: KeyWord() { override fun toString(): String = "DoSCircuitCreationDefenseType" }
object DoSCircuitCreationDefenseTimePeriod: KeyWord() { override fun toString(): String = "DoSCircuitCreationDefenseTimePeriod" }
object DoSConnectionEnabled: KeyWord() { override fun toString(): String = "DoSConnectionEnabled" }
object DoSConnectionMaxConcurrentCount: KeyWord() { override fun toString(): String = "DoSConnectionMaxConcurrentCount" }
object DoSConnectionDefenseType: KeyWord() { override fun toString(): String = "DoSConnectionDefenseType" }
object DoSRefuseSingleHopClientRendezvous: KeyWord() { override fun toString(): String = "DoSRefuseSingleHopClientRendezvous" }
/* === DIRECTORY AUTHORITY SERVER OPTIONS ===== NOT yet implemented as a TorConfig.Setting ========================== */
object AuthoritativeDirectory: KeyWord() { override fun toString(): String = "AuthoritativeDirectory" }
object V3AuthoritativeDirectory: KeyWord() { override fun toString(): String = "V3AuthoritativeDirectory" }
object VersioningAuthoritativeDirectory: KeyWord() { override fun toString(): String = "VersioningAuthoritativeDirectory" }
object RecommendedVersions: KeyWord() { override fun toString(): String = "RecommendedVersions" }
object RecommendedPackages: KeyWord() { override fun toString(): String = "RecommendedPackages" }
object RecommendedClientVersions: KeyWord() { override fun toString(): String = "RecommendedClientVersions" }
object BridgeAuthoritativeDir: KeyWord() { override fun toString(): String = "BridgeAuthoritativeDir" }
object MinUptimeHidServDirectoryV2: KeyWord() { override fun toString(): String = "MinUptimeHidServDirectoryV2" }
object RecommendedServerVersions: KeyWord() { override fun toString(): String = "RecommendedServerVersions" }
object ConsensusParams: KeyWord() { override fun toString(): String = "ConsensusParams" }
object DirAllowPrivateAddresses: KeyWord() { override fun toString(): String = "DirAllowPrivateAddresses" }
object AuthDirBadExit: KeyWord() { override fun toString(): String = "AuthDirBadExit" }
object AuthDirInvalid: KeyWord() { override fun toString(): String = "AuthDirInvalid" }
object AuthDirReject: KeyWord() { override fun toString(): String = "AuthDirReject" }
object AuthDirRejectCCs: KeyWord() { override fun toString(): String = "AuthDirRejectCCs" }
object AuthDirListBadExits: KeyWord() { override fun toString(): String = "AuthDirListBadExits" }
object AuthDirMaxServersPerAddr: KeyWord() { override fun toString(): String = "AuthDirMaxServersPerAddr" }
object AuthDirFastGuarantee: KeyWord() { override fun toString(): String = "AuthDirFastGuarantee" }
object AuthDirGuardBWGuarantee: KeyWord() { override fun toString(): String = "AuthDirGuardBWGuarantee" }
object AuthDirPinKeys: KeyWord() { override fun toString(): String = "AuthDirPinKeys" }
object AuthDirSharedRandomness: KeyWord() { override fun toString(): String = "AuthDirSharedRandomness" }
object AuthDirTestEd25519LinkKeys: KeyWord() { override fun toString(): String = "AuthDirTestEd25519LinkKeys" }
object BridgePassword: KeyWord() { override fun toString(): String = "BridgePassword" }
object V3AuthVotingInterval: KeyWord() { override fun toString(): String = "V3AuthVotingInterval" }
object V3AuthVoteDelay: KeyWord() { override fun toString(): String = "V3AuthVoteDelay" }
object V3AuthDistDelay: KeyWord() { override fun toString(): String = "V3AuthDistDelay" }
object V3AuthNIntervalsValid: KeyWord() { override fun toString(): String = "V3AuthNIntervalsValid" }
object V3BandwidthsFile: KeyWord() { override fun toString(): String = "V3BandwidthsFile" }
object V3AuthUseLegacyKey: KeyWord() { override fun toString(): String = "V3AuthUseLegacyKey" }
object AuthDirHasIPv6Connectivity: KeyWord() { override fun toString(): String = "AuthDirHasIPv6Connectivity" }
object MinMeasuredBWsForAuthToIgnoreAdvertised: KeyWord() { override fun toString(): String = "MinMeasuredBWsForAuthToIgnoreAdvertised" }
/* === HIDDEN SERVICE OPTIONS ================= NOT yet implemented as a TorConfig.Setting ========================== */
// HiddenServiceDir (IMPLEMENTED)
// HiddenServicePort (IMPLEMENTED)
object PublishHidServDescriptors: KeyWord() { override fun toString(): String = "PublishHidServDescriptors" }
object HiddenServiceVersion: KeyWord() { override fun toString(): String = "HiddenServiceVersion" }
object HiddenServiceAuthorizeClient: KeyWord() { override fun toString(): String = "HiddenServiceAuthorizeClient" }
object HiddenServiceAllowUnknownPorts: KeyWord() { override fun toString(): String = "HiddenServiceAllowUnknownPorts" }
object HiddenServiceExportCircuitID: KeyWord() { override fun toString(): String = "HiddenServiceExportCircuitID" }
// HiddenServiceMaxStreams (IMPLEMENTED)
// HiddenServiceMaxStreamsCloseCircuit (IMPLEMENTED)
object RendPostPeriod: KeyWord() { override fun toString(): String = "RendPostPeriod" }
object HiddenServiceDirGroupReadable: KeyWord() { override fun toString(): String = "HiddenServiceDirGroupReadable" }
object HiddenServiceNumIntroductionPoints: KeyWord() { override fun toString(): String = "HiddenServiceNumIntroductionPoints" }
object HiddenServiceSingleHopMode: KeyWord() { override fun toString(): String = "HiddenServiceSingleHopMode" }
object HiddenServiceNonAnonymousMode: KeyWord() { override fun toString(): String = "HiddenServiceNonAnonymousMode" }
/* === TESTING NETWORK OPTIONS ================ NOT yet implemented as a TorConfig.Setting ========================== */
object TestingTorNetwork: KeyWord() { override fun toString(): String = "TestingTorNetwork" }
object TestingV3AuthInitialVotingInterval: KeyWord() { override fun toString(): String = "TestingV3AuthInitialVotingInterval" }
object TestingV3AuthInitialVoteDelay: KeyWord() { override fun toString(): String = "TestingV3AuthInitialVoteDelay" }
object TestingV3AuthInitialDistDelay: KeyWord() { override fun toString(): String = "TestingV3AuthInitialDistDelay" }
object TestingV3AuthVotingStartOffset: KeyWord() { override fun toString(): String = "TestingV3AuthVotingStartOffset" }
object TestingAuthDirTimeToLearnReachability: KeyWord() { override fun toString(): String = "TestingAuthDirTimeToLearnReachability" }
object TestingMinFastFlagThreshold: KeyWord() { override fun toString(): String = "TestingMinFastFlagThreshold" }
object TestingServerDownloadInitialDelay: KeyWord() { override fun toString(): String = "TestingServerDownloadInitialDelay" }
object TestingClientDownloadInitialDelay: KeyWord() { override fun toString(): String = "TestingClientDownloadInitialDelay" }
object TestingServerConsensusDownloadInitialDelay: KeyWord() { override fun toString(): String = "TestingServerConsensusDownloadInitialDelay" }
object TestingClientConsensusDownloadInitialDelay: KeyWord() { override fun toString(): String = "TestingClientConsensusDownloadInitialDelay" }
object TestingBridgeDownloadInitialDelay: KeyWord() { override fun toString(): String = "TestingBridgeDownloadInitialDelay" }
object TestingBridgeBootstrapDownloadInitialDelay: KeyWord() { override fun toString(): String = "TestingBridgeBootstrapDownloadInitialDelay" }
object TestingClientMaxIntervalWithoutRequest: KeyWord() { override fun toString(): String = "TestingClientMaxIntervalWithoutRequest" }
object TestingDirConnectionMaxStall: KeyWord() { override fun toString(): String = "TestingDirConnectionMaxStall" }
object TestingDirAuthVoteExit: KeyWord() { override fun toString(): String = "TestingDirAuthVoteExit" }
object TestingDirAuthVoteExitIsStrict: KeyWord() { override fun toString(): String = "TestingDirAuthVoteExitIsStrict" }
object TestingDirAuthVoteGuard: KeyWord() { override fun toString(): String = "TestingDirAuthVoteGuard" }
object TestingDirAuthVoteGuardIsStrict: KeyWord() { override fun toString(): String = "TestingDirAuthVoteGuardIsStrict" }
object TestingDirAuthVoteHSDir: KeyWord() { override fun toString(): String = "TestingDirAuthVoteHSDir" }
object TestingDirAuthVoteHSDirIsStrict: KeyWord() { override fun toString(): String = "TestingDirAuthVoteHSDirIsStrict" }
object TestingEnableConnBwEvent: KeyWord() { override fun toString(): String = "TestingEnableConnBwEvent" }
object TestingEnableCellStatsEvent: KeyWord() { override fun toString(): String = "TestingEnableCellStatsEvent" }
object TestingMinExitFlagThreshold: KeyWord() { override fun toString(): String = "TestingMinExitFlagThreshold" }
object TestingLinkCertLifetime: KeyWord() { override fun toString(): String = "TestingLinkCertLifetime" }
object TestingAuthKeyLifetime: KeyWord() { override fun toString(): String = "TestingAuthKeyLifetime" }
object TestingSigningKeySlop: KeyWord() { override fun toString(): String = "TestingSigningKeySlop" }
/* === NON-PERSISTENT OPTIONS ================= NOT yet implemented as a TorConfig.Setting ========================== */
object __ControlPort: KeyWord() { override fun toString(): String = "__ControlPort" }
object __DirPort: KeyWord() { override fun toString(): String = "__DirPort" }
object __DNSPort: KeyWord() { override fun toString(): String = "__DNSPort" }
object __ExtORPort: KeyWord() { override fun toString(): String = "__ExtORPort" }
object __NATDPort: KeyWord() { override fun toString(): String = "__NATDPort" }
object __ORPort: KeyWord() { override fun toString(): String = "__ORPort" }
object __SocksPort: KeyWord() { override fun toString(): String = "__SocksPort" }
object __HttpTunnelPort: KeyWord() { override fun toString(): String = "__HttpTunnelPort" }
object __TransPort: KeyWord() { override fun toString(): String = "__TransPort" }
/* === NON-PERSISTENT CONTROLLER OPTIONS ====== NOT yet implemented as a TorConfig.Setting ========================== */
// See: https://torproject.gitlab.io/torspec/control-spec/#tor-config-options-for-use-by-controllers
object __AllDirActionsPrivate: KeyWord() { override fun toString(): String = "__AllDirActionsPrivate" }
object __DisablePredictedCircuits: KeyWord() { override fun toString(): String = "__DisablePredictedCircuits" }
object __LeaveStreamsUnattached: KeyWord() { override fun toString(): String = "__LeaveStreamsUnattached" }
object __HashedControlSessionPassword: KeyWord() { override fun toString(): String = "__HashedControlSessionPassword" }
object __ReloadTorrcOnSIGHUP: KeyWord() { override fun toString(): String = "__ReloadTorrcOnSIGHUP" }
object __OwningControllerFD: KeyWord() { override fun toString(): String = "__OwningControllerFD" }
object __DisableSignalHandlers: KeyWord() { override fun toString(): String = "__DisableSignalHandlers" }
// DEPRECATED
@Deprecated(message = "DEPRECATED: As of 0.3.1.0-alpha you should use HTTPSProxy.")
object HTTPProxy: KeyWord() { override fun toString(): String = "HTTPProxy" }
@Deprecated(message = "DEPRECATED: As of 0.3.1.0-alpha you should use HTTPSProxyAuthenticator.")
object HTTPProxyAuthenticator: KeyWord() { override fun toString(): String = "HTTPProxyAuthenticator" }
@Deprecated(message = "This option is deprecated; use ReachableAddresses instead.")
object FirewallPorts: KeyWord() { override fun toString(): String = "FirewallPorts" }
@Deprecated(message = "DEPRECATED: This option has had no effect for some time.")
object ReachableDirAddresses: KeyWord() { override fun toString(): String = "ReachableDirAddresses" }
@Deprecated(message = "DEPRECATED: This option has had no effect for some time.")
object ClientPreferIPv6DirPort: KeyWord() { override fun toString(): String = "ClientPreferIPv6DirPort" }
@Deprecated(message = "Use KeyWord.GeoIPFile", replaceWith = ReplaceWith(expression = "TorConfig.KeyWord.GeoIPFile"))
object GeoIpV4File: KeyWord() { override fun toString(): String = "GeoIPFile" }
@Deprecated(message = "Use KeyWord.__OwningControllerProcess", replaceWith = ReplaceWith(expression = "TorConfig.KeyWord.__OwningControllerProcess"))
object OwningControllerProcess: KeyWord() { override fun toString(): String = "__OwningControllerProcess" }
}
}
| 36 | null | 5 | 33 | 7888dc90b99b04f8d28f8abe7ccfb7402e2bd1bc | 104,231 | kmp-tor | Apache License 2.0 |
app/src/main/java/com/leon/app/watchlist/model/Person.kt | LeonErath | 93,735,611 | false | {"Kotlin": 114700, "Java": 4570} | package com.leon.app.watchlist.model
import io.realm.RealmList
import io.realm.RealmObject
import io.realm.annotations.PrimaryKey
/**
* Created by Leon on 07.07.17.
*/
open class Person : RealmObject() {
@PrimaryKey
var id: Int = 0
var adult: Boolean = false
var biography: String = ""
var birthday: String = ""
var deathday: String? = ""
// 0 männlich 1 weiblich
var gender: Int = 0
var homepage: String? = ""
var name: String = ""
var place_of_birth: String = ""
var popularity: Int = 0
var profile_path: String? = ""
var movies: RealmList<Movie> = RealmList()
} | 0 | Kotlin | 0 | 1 | 5b059ada8c2a5273d0874deca82cb425e7d3030d | 625 | Watchlist | MIT License |
parsely/src/main/java/com/parsely/parselyandroid/HeartbeatIntervalCalculator.kt | Parsely | 9,324,299 | false | {"Kotlin": 94744, "Java": 4558} | package com.parsely.parselyandroid
import kotlin.time.Duration
import kotlin.time.Duration.Companion.minutes
import kotlin.time.Duration.Companion.seconds
internal open class HeartbeatIntervalCalculator(private val clock: Clock) {
open fun calculate(startTime: Duration): Long {
val nowDuration = clock.now
val totalTrackedTime = nowDuration - startTime
val totalWithOffset = totalTrackedTime + OFFSET_MATCHING_BASE_INTERVAL
val newInterval = totalWithOffset * BACKOFF_PROPORTION
val clampedNewInterval = minOf(MAX_TIME_BETWEEN_HEARTBEATS, newInterval)
return clampedNewInterval.inWholeMilliseconds
}
companion object {
const val BACKOFF_PROPORTION = 0.3
val OFFSET_MATCHING_BASE_INTERVAL = 35.seconds
val MAX_TIME_BETWEEN_HEARTBEATS = 15.minutes
}
}
| 11 | Kotlin | 6 | 5 | 704f3723086d6e048e663e3cee49794ac5b2847e | 844 | parsely-android | Apache License 2.0 |
app/src/main/java/net/vezk/contact_form/domain/MainViewModelFactory.kt | va3mezk | 430,224,358 | false | {"Kotlin": 10946} | package net.vezk.contact_form.domain
import androidx.lifecycle.*
/**
* 🇪🇸
*En la configuración de ViewModel, necesitamos crear una clase y extender ViewModel.
* La clase ViewModel que tiene la lógica de negocios y las implementaciones de llamadas a la API.
* En el constructor ViewModel, necesitamos pasar el repositorio de datos para manejar los datos.
*
* 🇺🇸
* In the ViewModel configuration, we need to create a class and extend ViewModel.
* The ViewModel class that has the business logic and API call implementations.
* In the ViewModel constructor, we need to pass the data repository to handle the data.
**/
class MainViewModelFactory constructor(private val repository: MainRepository) : ViewModelProvider.Factory {
override fun <T : ViewModel> create(modelClass: Class<T>): T {
return if (modelClass.isAssignableFrom(MainViewModel::class.java)) {
MainViewModel(this.repository) as T
} else {
throw IllegalArgumentException("ViewModel Not Found")
}
}
} | 0 | Kotlin | 0 | 1 | d239b217c53244e11f124a2a50a54a3385572c14 | 1,029 | contact_form | MIT License |
src/main/kotlin/dev/supergrecko/vexe/llvm/ir/PassManager.kt | arkencl | 275,663,397 | true | {"Kotlin": 372536, "Makefile": 227} | package dev.supergrecko.vexe.llvm.ir
import dev.supergrecko.vexe.llvm.internal.contracts.ContainsReference
import dev.supergrecko.vexe.llvm.internal.contracts.Disposable
import dev.supergrecko.vexe.llvm.target.TargetMachine
import org.bytedeco.llvm.LLVM.LLVMPassManagerRef
import org.bytedeco.llvm.global.LLVM
public class PassManager internal constructor() : Disposable,
ContainsReference<LLVMPassManagerRef> {
public override lateinit var ref: LLVMPassManagerRef
public override var valid: Boolean = true
public constructor(pass: LLVMPassManagerRef) : this() {
ref = pass
}
//region Target
/**
* Add target-specific analysis passes to the pass manager
*
* @see LLVM.LLVMAddAnalysisPasses
*/
public fun addPassesForTargetMachine(machine: TargetMachine) {
LLVM.LLVMAddAnalysisPasses(machine.ref, ref)
}
//endregion Target
override fun dispose() {
require(valid) { "This module has already been disposed." }
valid = false
LLVM.LLVMDisposePassManager(ref)
}
}
| 0 | Kotlin | 0 | 0 | 673522b620db4c8a619db5ccc5dfe62197b12f11 | 1,073 | llvm4kt | Apache License 2.0 |
redwood-leak-detector/src/nativeMain/kotlin/app/cash/redwood/leaks/Gc.kt | cashapp | 305,409,146 | false | {"Kotlin": 2089205, "Swift": 20649, "Objective-C": 4497, "Java": 1583, "Shell": 253, "HTML": 235, "C": 129} | /*
* Copyright (C) 2024 Square, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package app.cash.redwood.leaks
import kotlin.native.runtime.GC
import kotlin.native.runtime.NativeRuntimeApi
internal actual fun detectGc(): Gc = KotlinNativeGc()
@OptIn(NativeRuntimeApi::class)
private class KotlinNativeGc : Gc {
override suspend fun collect() {
GC.collect()
}
}
| 108 | Kotlin | 73 | 1,648 | 3f14e622c2900ec7e0dfaff5bd850c95a7f29937 | 893 | redwood | Apache License 2.0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.