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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
android/src/com/android/tools/idea/startup/AdbFileProviderInitializer.kt | JetBrains | 60,701,247 | false | null | /*
* Copyright (C) 2020 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.android.tools.idea.startup
import com.android.tools.idea.adb.AdbFileProvider
import com.android.utils.reflection.qualifiedName
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.diagnostic.thisLogger
import com.intellij.openapi.project.Project
import com.intellij.openapi.project.ProjectManagerListener
import com.intellij.openapi.util.Key
import com.intellij.openapi.util.UserDataHolder
import org.jetbrains.android.sdk.AndroidSdkUtils
import java.io.File
import java.util.function.Supplier
/**
* Ensures [AdbFileProvider] is available for each new project
*
* Note: The reason this code need to live in the "android-core" module
* is that it depends on [AndroidSdkUtils] which has many dependencies
* that have not been factored out. Ideally, this class should be part
* of the "android-adb" module.
*/
class AdbFileProviderInitializer : ProjectManagerListener {
/**
* Sets up the [AdbFileProvider] for each [Project]
*
* Note: this code runs on the EDT thread, so we need to avoid slow operations.
*/
override fun projectOpened(project: Project) {
val supplier = Supplier<File?> { getAdbPathAndReportError(project, project) }
AdbFileProvider(supplier).storeInProject(project)
}
companion object {
@JvmStatic
fun initializeApplication() {
val supplier = Supplier<File?> { getAdbPathAndReportError(null, ApplicationManager.getApplication()) }
AdbFileProvider(supplier).storeInApplication()
}
private val LOG_ERROR_KEY: Key<Boolean> = Key.create(::LOG_ERROR_KEY.qualifiedName)
private fun getAdbPathAndReportError(project: Project?, userData: UserDataHolder): File? {
val result = AndroidSdkUtils.findAdb(project)
if (result.adbPath == null) {
// Log error only once per application or project
if (userData.getUserData(LOG_ERROR_KEY) != true) {
userData.putUserData(LOG_ERROR_KEY, true)
thisLogger().warn("Location of ADB could not be determined for ${project ?: "application"}.\n" +
"The following paths were searched:\n" +
result.searchedPaths.joinToString("\n"))
}
}
// Return path (it may be null)
return result.adbPath
}
}
}
| 1 | null | 220 | 857 | 8d22f48a9233679e85e42e8a7ed78bbff2c82ddb | 2,908 | android | Apache License 2.0 |
cesium-kotlin/src/jsMain/kotlin/cesium/engine/DataSourceDisplay.factory.kt | karakum-team | 393,199,102 | false | {"Kotlin": 6328371} | // Automatically generated - do not modify!
package cesium.engine
import js.objects.jso
inline fun DataSourceDisplay(
block: DataSourceDisplay.ConstructorOptions.() -> Unit,
): DataSourceDisplay =
DataSourceDisplay(options = jso(block))
| 0 | Kotlin | 7 | 35 | 0f192fb5e7be6207ea195f88dc6a0e766ad7f93b | 248 | types-kotlin | Apache License 2.0 |
cesium-kotlin/src/jsMain/kotlin/cesium/engine/DataSourceDisplay.factory.kt | karakum-team | 393,199,102 | false | {"Kotlin": 6328371} | // Automatically generated - do not modify!
package cesium.engine
import js.objects.jso
inline fun DataSourceDisplay(
block: DataSourceDisplay.ConstructorOptions.() -> Unit,
): DataSourceDisplay =
DataSourceDisplay(options = jso(block))
| 0 | Kotlin | 7 | 35 | 0f192fb5e7be6207ea195f88dc6a0e766ad7f93b | 248 | types-kotlin | Apache License 2.0 |
openrndr/src/main/kotlin/sketch/test/T19_DotProduct.kt | ericyd | 250,675,664 | false | {"Kotlin": 901946, "Rust": 540056, "JavaScript": 91876, "GLSL": 31121, "Processing": 6318, "HTML": 1074, "Shell": 873, "Makefile": 435} | /**
* I've never had any intuition about dot products, so here are some examples
*/
package sketch.test
import org.openrndr.application
import org.openrndr.color.ColorRGBa
import org.openrndr.draw.loadFont
import org.openrndr.extensions.Screenshots
import org.openrndr.math.Vector2
import org.openrndr.panel.elements.round
import org.openrndr.shape.LineSegment
import util.timestamp
import kotlin.math.PI
import kotlin.math.abs
import kotlin.math.cos
import kotlin.math.sin
fun main() = application {
configure {
width = 800
height = 800
}
program {
backgroundColor = ColorRGBa.WHITE
// find /System/Library/Fonts | grep ttf
val font = loadFont("/System/Library/Fonts/Supplemental/Arial.ttf", 12.0)
extend(Screenshots()) {
name = "screenshots/dot-product-demo/${timestamp()}.png"
}
extend {
drawer.fill = ColorRGBa.BLACK
drawer.stroke = ColorRGBa.BLACK
drawer.fontMap = font
val length = width * 0.05
val angleA = PI * 0.125
val vector = { angle: Double, vertex: Vector2, len: Double -> Vector2(cos(angle), sin(angle)) * len + vertex }
val anglePositionMap = mapOf(
PI * 0.12 to Vector2(width * 0.05, height * 0.1),
PI * 0.25 to Vector2(width * 0.25, height * 0.1),
PI * 0.38 to Vector2(width * 0.45, height * 0.1),
PI * 0.50 to Vector2(width * 0.65, height * 0.1),
PI * 0.64 to Vector2(width * 0.85, height * 0.1),
PI * 0.77 to Vector2(width * 0.05, height * 0.4),
PI * 0.90 to Vector2(width * 0.25, height * 0.4),
PI * 1.00 to Vector2(width * 0.45, height * 0.4),
PI * 1.12 to Vector2(width * 0.65, height * 0.4),
PI * 1.25 to Vector2(width * 0.85, height * 0.4),
PI * 1.38 to Vector2(width * 0.05, height * 0.7),
PI * 1.50 to Vector2(width * 0.25, height * 0.7),
PI * 1.64 to Vector2(width * 0.45, height * 0.7),
PI * 1.77 to Vector2(width * 0.65, height * 0.7),
PI * 1.99 to Vector2(width * 0.85, height * 0.7),
)
// for ((angleB, vertex) in anglePositionMap) {
// drawer.lineSegment(LineSegment(vertex, vector(angleA, vertex, length)))
// drawer.lineSegment(LineSegment(vertex, vector(angleB, vertex, length)))
// drawer.text("a", vector(angleA, vertex, length * 1.1))
// drawer.text("b", vector(angleB + PI * 0.075, vertex, length * 1.1))
//
// // For this demonstration I think it makes more sense to consider the vectors from the origin rather than the "vertex"
// // because the dot product is the sum of the product of the components (x,y), so it only makes sense to compare in relation to the origin
// drawer.text("a • b = ${vector(angleA, Vector2.ZERO, length).normalized.dot(vector(angleB, Vector2.ZERO, length).normalized).round(2)}", vertex + Vector2(0.0, height * 0.1))
// drawer.text("abs(a • b) = ${abs(vector(angleA, Vector2.ZERO, length).normalized.dot(vector(angleB, Vector2.ZERO, length).normalized).round(2))}", vertex + Vector2(0.0, height * 0.125))
// drawer.text("a x️ b = ${vector(angleA, Vector2.ZERO, length).normalized.cross(vector(angleB, Vector2.ZERO, length).normalized).round(2)}", vertex + Vector2(0.0, height * 0.15))
// drawer.text("abs(a x️ b) = ${abs(vector(angleA, Vector2.ZERO, length).normalized.cross(vector(angleB, Vector2.ZERO, length).normalized).round(2))}", vertex + Vector2(0.0, height * 0.175))
// }
// drawer.text("all vector calculations are performed on normalized vector quantities", width * 0.25, height * 0.05)
for ((angleB, vertex) in anglePositionMap) {
// drawer.circle(vertex, 5.0)
// drawer.lineSegment(LineSegment(vertex, vector(angleB, vertex, length)))
// drawer.text("a", vertex + vector(angleA, Vector2.ZERO, 5.0))
// drawer.text("b", vector(angleB + PI * 0.075, vertex, length * 1.1))
val vectorA = vector(angleA, vertex, length)
val vectorB = vector(angleB, vertex, length)
drawer.lineSegment(LineSegment(vertex, vectorA))
drawer.lineSegment(LineSegment(vertex, vectorB))
drawer.text("a", vector(angleA, vertex, length * 1.1))
drawer.text("b", vector(angleB + PI * 0.075, vertex, length * 1.1))
// For this demonstration I think it makes more sense to consider the vectors from the origin rather than the "vertex"
// because the dot product is the sum of the product of the components (x,y), so it only makes sense to compare in relation to the origin
drawer.text("a • b = ${vectorA.normalized.dot(vectorB.normalized).round(2)}", vertex + Vector2(0.0, height * 0.1))
drawer.text("abs(a • b) = ${abs(vectorA.normalized.dot(vectorB.normalized).round(2))}", vertex + Vector2(0.0, height * 0.125))
drawer.text("a x️ b = ${vectorA.normalized.cross(vectorB.normalized).round(2)}", vertex + Vector2(0.0, height * 0.15))
drawer.text("abs(a x️ b) = ${abs(vectorA.normalized.cross(vectorB.normalized).round(2))}", vertex + Vector2(0.0, height * 0.175))
}
drawer.text("all vector calculations are performed on NON-normalized vector quantities", width * 0.25, height * 0.05)
}
}
}
| 2 | Kotlin | 0 | 58 | 7f13fce0d4a871a4ab146df4936a40c0091b1ab3 | 5,220 | generative-art | MIT License |
bgw-gui/src/main/kotlin/tools/aqua/bgw/components/uicomponents/BinaryStateButton.kt | tudo-aqua | 377,420,862 | false | {"Kotlin": 1198455, "TypeScript": 2013, "JavaScript": 1242, "HTML": 507, "CSS": 359, "Ruby": 131} | /*
* Copyright 2021-2022 The BoardGameWork Authors
* SPDX-License-Identifier: Apache-2.0
*
* 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.
*/
@file:Suppress("unused", "LongParameterList")
package tools.aqua.bgw.components.uicomponents
import tools.aqua.bgw.core.Alignment
import tools.aqua.bgw.observable.properties.BooleanProperty
import tools.aqua.bgw.observable.properties.Property
import tools.aqua.bgw.util.Font
import tools.aqua.bgw.visual.Visual
/**
* Baseclass for [ToggleButton]s and [RadioButton]s.
*
* @param posX Horizontal coordinate for this [BinaryStateButton].
* @param posY Vertical coordinate for this [BinaryStateButton].
* @param width Width for this [BinaryStateButton].
* @param height Height for this [BinaryStateButton].
* @param text Text to be displayed for this [BinaryStateButton].
* @param font Font to be used for this [BinaryStateButton].
* @param alignment Alignment to be used for the [text].
* @param isWrapText Defines if [text] should be wrapped, if it exceeds the label's width.
* @param isSelected The initial state for this [BinaryStateButton].
* @param toggleGroup The ToggleGroup of this [BinaryStateButton].
* @param visual Background [Visual].
*
* @see ToggleGroup
*/
sealed class BinaryStateButton(
posX: Number,
posY: Number,
width: Number,
height: Number,
text: String,
font: Font,
alignment: Alignment,
isWrapText: Boolean,
isSelected: Boolean,
toggleGroup: ToggleGroup,
visual: Visual
) :
LabeledUIComponent(
posX = posX,
posY = posY,
width = width,
height = height,
text = text,
font = font,
alignment = alignment,
isWrapText = isWrapText,
visual = visual) {
/**
* The ToggleGroup of this ToggleButton.
*
* @see ToggleGroup
*/
var toggleGroup: ToggleGroup = toggleGroup
set(value) {
toggleGroup.removeButton(this)
value.addButton(this)
field = value
}
/**
* [Property] for the selected state of this [ToggleButton].
*
* @see isSelected
*/
val selectedProperty: BooleanProperty = BooleanProperty(isSelected)
/**
* Selected state for this [ToggleButton].
*
* @see selectedProperty
*/
var isSelected: Boolean
get() = selectedProperty.value
set(value) {
selectedProperty.value = value
}
init {
this.toggleGroup = toggleGroup
selectedProperty.internalListener = { _, _ -> toggleGroup.buttonSelectedStateChanged(this) }
}
}
| 31 | Kotlin | 16 | 24 | 266db439e4443d10bc1ec7eb7d9032f29daf6981 | 3,025 | bgw | Apache License 2.0 |
app/src/main/kotlin/com/flxrs/dankchat/data/api/TmiApiService.kt | flex3r | 186,238,019 | false | null | package com.flxrs.dankchat.data.api
import com.flxrs.dankchat.BuildConfig
import com.flxrs.dankchat.data.api.dto.ChatterCountDto
import com.flxrs.dankchat.data.api.dto.ChattersResultDto
import retrofit2.Response
import retrofit2.http.GET
import retrofit2.http.Headers
import retrofit2.http.Path
interface TmiApiService {
@GET("group/user/{channel}/chatters")
@Headers("User-Agent: dankchat/${BuildConfig.VERSION_NAME}")
suspend fun getChatters(@Path("channel") channel: String): Response<ChattersResultDto>
@GET("group/user/{channel}/chatters")
@Headers("User-Agent: dankchat/${BuildConfig.VERSION_NAME}")
suspend fun getChatterCount(@Path("channel") channel: String): Response<ChatterCountDto>
} | 30 | Kotlin | 33 | 114 | c8523ebbe68dc008b15f9cc05faab14b65abffc0 | 723 | DankChat | MIT License |
src/Day05.kt | hottendo | 572,708,982 | false | {"Kotlin": 41152} |
class Stack(crates: List<String>) {
var size = crates.size
var stackOfCrates = crates.toMutableList()
fun moveTo(otherStack: Stack, count: Int) {
// add count creates to the other stack (part 1)
// val movingCrates: List<String> = this.stackOfCrates.take(count).reversed()
// part 2: crate order does not get reversed
val movingCrates: List<String> = this.stackOfCrates.take(count)
otherStack.stackCrates(movingCrates)
// remove crates from this stack
removeCrates(count)
size = stackOfCrates.size
}
fun stackCrates(cratesToAdd: List<String>): Int {
this.stackOfCrates = (cratesToAdd.toMutableList() + this.stackOfCrates) as MutableList<String>
this.size = this.stackOfCrates.size
return size
}
fun removeCrates(count: Int) {
for(i in 0..(count-1)) {
this.stackOfCrates.removeAt(0)
}
}
override fun toString(): String {
var str = "Stack (size: $size) - ${stackOfCrates}\n"
return str
}
fun first(): String {
return stackOfCrates[0]
}
}
fun main() {
fun part1(input: List<String>): String {
var score = ""
val stacks = mutableListOf<Stack>()
stacks.add(Stack(mutableListOf("T", "Z", "B")))
stacks.add(Stack(mutableListOf("N", "D", "T", "H", "V")))
stacks.add(Stack(mutableListOf("D", "M", "F", "B")))
stacks.add(Stack(mutableListOf("L", "Q", "V", "W", "G", "J", "T")))
stacks.add(Stack(mutableListOf("M", "Q", "F", "V", "P", "G", "D", "W")))
stacks.add(Stack(mutableListOf("S", "F", "H", "G", "Q", "Z", "V")))
stacks.add(Stack(mutableListOf("W", "C", "T", "L", "R", "N", "S", "Z")))
stacks.add(Stack(mutableListOf("M", "R", "N", "J", "D", "W", "H", "Z")))
stacks.add(Stack(mutableListOf("S", "D", "F", "L", "Q", "M")))
for(s in stacks) {
print(s)
}
val regex = "^move (\\d+) from (\\d+) to (\\d+)$".toRegex()
for(instr in input) {
val match = regex.find(instr)
println(instr)
if(match != null) {
val count = match.groupValues[1].toInt()
val fromStack = stacks[match.groupValues[2].toInt()-1]
val toStack = stacks[match.groupValues[3].toInt()-1]
fromStack.moveTo(toStack, count)
print(fromStack)
print(toStack)
println()
}
}
for(s in stacks) {
score += s.first()
print(s)
}
return score
}
fun part2(input: List<String>): Int {
var score = 0
return score
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day05_test")
// println("Part 1 (Test): ${part1(testInput)}")
// println("Part 2 (Test): ${part2(testInput)}")
// check(part1(testInput) == 1)
val input = readInput("Day05")
println("Part 1 : ${part1(input)}")
// println("Part 2 : ${part2(input)}")
}
| 0 | Kotlin | 0 | 0 | a166014be8bf379dcb4012e1904e25610617c550 | 3,134 | advent-of-code-2022 | Apache License 2.0 |
businesslogic/schedule/src/main/java/de/droidcon/berlin2018/schedule/backend/BackendScheduleResponse.kt | OpenConference | 100,889,869 | false | null | package de.droidcon.berlin2018.schedule.backend
/**
* This data structure will be retuned from
*
* @author <NAME>
*/
data class BackendScheduleResponse<T> private constructor(val isNewerDataAvailable: Boolean,
val data: List<T>) {
companion object {
fun <R> nothingChanged() = BackendScheduleResponse(false, emptyList<R>())
fun <T> dataChanged(data: List<T>) = BackendScheduleResponse(true, data)
}
}
| 1 | null | 1 | 27 | 142effaf4eb04abb12d5b812e797a89922b649a5 | 424 | DroidconBerlin2017 | Apache License 2.0 |
src/main/kotlin/br/com/zup/edu/clients/itau/ContasItauClient.kt | micaelps | 359,457,305 | true | {"Kotlin": 68364} | package br.com.zup.edu.clients.itau
import io.micronaut.http.HttpResponse
import io.micronaut.http.annotation.Get
import io.micronaut.http.annotation.PathVariable
import io.micronaut.http.annotation.QueryValue
import io.micronaut.http.client.annotation.Client
@Client("\${itau.contas.url}")
interface ContasItauClient {
@Get("/api/v1/clientes/{clienteId}/contas{?tipo}")
fun buscaContaPorTipo(@PathVariable clienteId: String, @QueryValue tipo: String): HttpResponse<DadosContaItauResponse>
} | 0 | Kotlin | 0 | 0 | 1df60d6db03393cb1a400dfc30ec5322c9b28990 | 504 | orange-talents-02-template-pix-keymanager-grpc | Apache License 2.0 |
src/main/kotlin/no/njoh/pulseengine/modules/scene/entities/Backdrop.kt | NiklasJohansen | 239,208,354 | false | null | package entities
import no.njoh.pulseengine.core.PulseEngine
import no.njoh.pulseengine.core.asset.types.Texture
import no.njoh.pulseengine.core.graphics.Surface2D
import no.njoh.pulseengine.core.shared.annotations.AssetRef
import no.njoh.pulseengine.modules.scene.entities.StandardSceneEntity
import no.njoh.pulseengine.core.shared.primitives.Color
import no.njoh.pulseengine.modules.lighting.NormalMapRenderer.Orientation
import no.njoh.pulseengine.modules.lighting.NormalMapped
class Decoration : StandardSceneEntity(), NormalMapped
{
@AssetRef(Texture::class)
var textureName = ""
var color = Color(1f, 1f, 1f)
var xTiling = 1f
var yTiling = 1f
override var normalMapName = ""
override var normalMapIntensity = 1f
override var normalMapOrientation = Orientation.NORMAL
override fun onRender(engine: PulseEngine, surface: Surface2D)
{
surface.setDrawColor(color)
surface.drawTexture(
texture = engine.asset.getOrNull(textureName) ?: Texture.BLANK,
x = x,
y = y,
width = width,
height = height,
rot = rotation,
xOrigin = 0.5f,
yOrigin = 0.5f,
uTiling = xTiling,
vTiling = yTiling
)
}
} | 0 | null | 0 | 1 | c45a8028e1cef5259b76281a7d6083bcbfc51915 | 1,279 | PulseEngine | MIT License |
embrace-android-sdk/src/test/java/io/embrace/android/embracesdk/FragmentBreadcrumbTest.kt | embrace-io | 704,537,857 | false | {"Kotlin": 3067335, "C": 189946, "Java": 179438, "C++": 13140, "CMake": 4188} | package io.embrace.android.embracesdk
import com.squareup.moshi.JsonDataException
import io.embrace.android.embracesdk.payload.FragmentBreadcrumb
import org.junit.Assert.assertEquals
import org.junit.Assert.assertNotNull
import org.junit.Test
internal class FragmentBreadcrumbTest {
private val info = FragmentBreadcrumb(
"test",
1600000000,
1600001000,
)
@Test
fun testSerialization() {
assertJsonMatchesGoldenFile("fragment_breadcrumb_expected.json", info)
}
@Test
fun testDeserialization() {
val obj = deserializeJsonFromResource<FragmentBreadcrumb>("fragment_breadcrumb_expected.json")
assertEquals("test", obj.name)
assertEquals(1600000000, obj.getStartTime())
assertEquals(1600001000L, obj.endTime)
}
@Test(expected = JsonDataException::class)
fun testEmptyObject() {
val obj = deserializeEmptyJsonString<FragmentBreadcrumb>()
assertNotNull(obj)
}
}
| 20 | Kotlin | 7 | 130 | ca3da94e2055251ec6b3afc35fc9a1fc1bb5f57d | 986 | embrace-android-sdk | Apache License 2.0 |
app/src/main/java/com/pechuro/cashdebts/ui/base/activity/BaseActivity.kt | Ilyshka991 | 171,679,797 | false | null | package com.pechuro.cashdebts.ui.base.activity
import android.content.Context
import android.content.pm.PackageManager.GET_META_DATA
import android.os.Bundle
import androidx.annotation.LayoutRes
import androidx.appcompat.app.AppCompatActivity
import androidx.fragment.app.Fragment
import androidx.lifecycle.ViewModelProvider
import androidx.lifecycle.ViewModelProviders
import com.pechuro.cashdebts.AppEvent
import com.pechuro.cashdebts.model.locale.LocaleManager
import com.pechuro.cashdebts.ui.activity.version.NewVersionActivity
import com.pechuro.cashdebts.ui.base.BaseViewModel
import com.pechuro.cashdebts.ui.utils.EventManager
import dagger.android.AndroidInjection
import dagger.android.DispatchingAndroidInjector
import dagger.android.support.HasSupportFragmentInjector
import io.reactivex.disposables.CompositeDisposable
import io.reactivex.rxkotlin.addTo
import javax.inject.Inject
import kotlin.reflect.KClass
abstract class BaseActivity<V : BaseViewModel> : AppCompatActivity(),
HasSupportFragmentInjector {
@Inject
protected lateinit var fragmentDispatchingAndroidInjector: DispatchingAndroidInjector<Fragment>
@Inject
protected lateinit var viewModelFactory: ViewModelProvider.Factory
protected lateinit var viewModel: V
@get:LayoutRes
protected abstract val layoutId: Int
@Inject
protected lateinit var weakCompositeDisposable: CompositeDisposable
@Inject
protected lateinit var strongCompositeDisposable: CompositeDisposable
protected abstract fun getViewModelClass(): KClass<V>
override fun onCreate(savedInstanceState: Bundle?) {
performDI()
initViewModel()
super.onCreate(savedInstanceState)
setContentView(layoutId)
setAppEventListener()
resetTitle()
}
override fun attachBaseContext(base: Context) {
super.attachBaseContext(LocaleManager.updateLocale(base))
}
override fun onStop() {
super.onStop()
weakCompositeDisposable.clear()
}
override fun onDestroy() {
super.onDestroy()
strongCompositeDisposable.clear()
}
override fun supportFragmentInjector() = fragmentDispatchingAndroidInjector
private fun performDI() = AndroidInjection.inject(this)
private fun initViewModel() {
viewModel = ViewModelProviders.of(this, viewModelFactory).get(getViewModelClass().java)
}
private fun resetTitle() {
val info = packageManager.getActivityInfo(componentName, GET_META_DATA)
if (info.labelRes != 0) {
setTitle(info.labelRes)
}
}
private fun setAppEventListener() {
EventManager.listen(AppEvent::class.java, true).subscribe {
when (it) {
is AppEvent.OnNewVersionAvailable -> openNewVersionActivity()
}
}.addTo(strongCompositeDisposable)
}
private fun openNewVersionActivity() {
if (this !is NewVersionActivity) {
val intent = NewVersionActivity.newIntent(this)
startActivity(intent)
finish()
}
}
} | 0 | Kotlin | 0 | 3 | afb871ebb70b2863a1f2c290f7e06a3f5b9feab6 | 3,089 | CashDebts | Apache License 2.0 |
plugin-settings/src/main/kotlin/com/freeletics/gradle/plugin/SettingsExtension.kt | freeletics | 611,205,691 | false | {"Kotlin": 158054, "Shell": 2852} | package com.freeletics.gradle.plugin
import java.io.File
import org.gradle.api.initialization.Settings
public abstract class SettingsExtension(private val settings: Settings) {
/**
* Automatically find and include Gradle projects in this build. It will start from the root folder and find any
* project where the build file name matches the path, e.g. `:example` should have `example.gradle` as build file
* and `:foo:bar` should have `foo-bar.gradle.
*
* This does not support nested projects. E.g. `foo:api` and `foo:impl` are generally fine, but if `:foo` also
* is a project (has a build file) then these 2 are not considered.
*/
public fun discoverProjects() {
val root = settings.rootDir
val rootPath = root.canonicalPath
root.listFiles()!!.forEach {
discoverProjectsIn(it, rootPath)
}
}
/**
* Automatically find and include Gradle projects in this build. It will only search in the given folders and find
* any project where the build file name matches the path, e.g. `:example` should have `example.gradle` as build
* file and `:foo:bar` should have `foo-bar.gradle.
*
* This does not support nested projects. E.g. `foo:api` and `foo:impl` are generally fine, but if `:foo` also
* is a project (has a build file) then these 2 are not considered.
*/
public fun discoverProjectsIn(vararg directories: String) {
val root = settings.rootDir
val rootPath = root.canonicalPath
directories.forEach {
discoverProjectsIn(root.resolve(it), rootPath)
}
}
private val gradleFileRegex = Regex(".+\\.gradle(\\.kts)?")
private val ignoredDirectories = listOf("build", "gradle")
private fun discoverProjectsIn(directory: File, rootPath: String) {
if (!directory.isDirectory || directory.isHidden || ignoredDirectories.contains(directory.name)) {
return
}
val files = directory.listFiles()!!.toList()
val gradleFiles = files.filter { gradleFileRegex.matches(it.name) }
if (gradleFiles.any { it.name.startsWith("settings.gradle") }) {
return
} else if (gradleFiles.isNotEmpty()) {
val buildFile = gradleFiles.single()
val relativePath = buildFile.parent.substringAfter(rootPath)
if (relativePath.isNotEmpty()) {
val projectName = relativePath.replace(File.separator, ":")
settings.include(projectName)
settings.project(projectName).buildFileName = buildFile.name
}
} else {
files.forEach {
discoverProjectsIn(it, rootPath)
}
}
}
/**
* @param androidXBuildId buildId for androidx snapshot artifacts. Can be taken from here:
* https://androidx.dev/snapshots/builds
*/
@JvmOverloads
public fun snapshots(androidXBuildId: String? = null) {
settings.dependencyResolutionManagement { management ->
management.repositories { handler ->
handler.maven {
it.setUrl("https://oss.sonatype.org/content/repositories/snapshots/")
it.mavenContent { content ->
content.snapshotsOnly()
}
}
handler.maven {
it.setUrl("https://s01.oss.sonatype.org/content/repositories/snapshots/")
it.mavenContent { content ->
content.snapshotsOnly()
}
}
handler.maven {
it.setUrl("https://androidx.dev/storage/compose-compiler/repository/")
it.mavenContent { content ->
// limit to androidx.compose.compiler dev versions
content.includeVersionByRegex("^androidx.compose.compiler\$", ".*", ".+-dev-k.+")
}
}
if (androidXBuildId != null) {
handler.maven {
it.setUrl("https://androidx.dev/snapshots/builds/$androidXBuildId/artifacts/repository/")
it.mavenContent { content ->
// limit to AndroidX and SNAPSHOT versions
content.includeGroup("^androidx\\..*")
content.snapshotsOnly()
}
}
}
handler.maven {
it.setUrl("https://maven.pkg.jetbrains.space/kotlin/p/kotlin/bootstrap")
it.mavenContent { content ->
// limit to org.jetbrains.kotlin artifacts with -dev- or -release-
content.includeVersionByRegex("^org.jetbrains.kotlin.*", ".*", ".*-(dev|release)-.*")
}
}
handler.mavenLocal()
}
}
}
/**
* Replace any usage of Khonshu `navigator-compose` with `navigation-experimental` to try out the
* experimental navigation implementation.
*
* When using an included build the `experimentalNavigation` parameter on [includeKhonshu] should be used instead.
*/
public fun useKhonshuExperimentalNavigation() {
settings.gradle.beforeProject { project ->
project.configurations.configureEach { configuration ->
configuration.resolutionStrategy.eachDependency {
if (it.requested.group == "com.freeletics.khonshu" && it.requested.name == "navigation-compose") {
it.useTarget("com.freeletics.khonshu:navigation-experimental:${it.requested.version}")
}
}
}
}
}
/**
* Include a local clone of Khonshu in this build.
*
* When [experimentalNavigation] is `true` any usage of Khonshu `navigation-compose` will be replaced with
* `navigation-experimental` to try out the experimental navigation implementation.
*/
@JvmOverloads
public fun includeKhonshu(path: String = "../khonshu", experimentalNavigation: Boolean = false) {
settings.includeBuild(path) { build ->
build.dependencySubstitution {
it.substitute(it.module("com.freeletics.mad:state-machine"))
.using(it.project(":state-machine-legacy"))
it.substitute(it.module("com.freeletics.khonshu:state-machine"))
.using(it.project(":state-machine"))
it.substitute(it.module("com.freeletics.khonshu:state-machine-testing"))
.using(it.project(":state-machine-testing"))
it.substitute(it.module("com.freeletics.khonshu:text-resource"))
.using(it.project(":text-resource"))
it.substitute(it.module("com.freeletics.khonshu:navigation"))
.using(it.project(":navigation"))
it.substitute(it.module("com.freeletics.khonshu:navigation-androidx-nav"))
.using(it.project(":navigation-androidx"))
if (experimentalNavigation) {
it.substitute(it.module("com.freeletics.khonshu:navigation-compose"))
.using(it.project(":navigation-experimental"))
} else {
it.substitute(it.module("com.freeletics.khonshu:navigation-compose"))
.using(it.project(":navigation-compose"))
}
it.substitute(it.module("com.freeletics.khonshu:navigation-experimental"))
.using(it.project(":navigation-experimental"))
it.substitute(it.module("com.freeletics.khonshu:navigation-fragment"))
.using(it.project(":navigation-fragment"))
it.substitute(it.module("com.freeletics.khonshu:navigation-testing"))
.using(it.project(":navigation-testing"))
it.substitute(it.module("com.freeletics.khonshu:codegen-runtime"))
.using(it.project(":codegen"))
it.substitute(it.module("com.freeletics.khonshu:codegen-compose"))
.using(it.project(":codegen-compose"))
it.substitute(it.module("com.freeletics.khonshu:codegen-fragment"))
.using(it.project(":codegen-fragment"))
it.substitute(it.module("com.freeletics.khonshu:codegen-scope"))
.using(it.project(":codegen-scope"))
it.substitute(it.module("com.freeletics.khonshu:codegen-compiler"))
.using(it.project(":codegen-compiler"))
if (experimentalNavigation) {
it.substitute(it.project(":navigation-compose"))
.using(it.project(":navigation-experimental"))
}
}
}
}
@JvmOverloads
public fun includeFlowRedux(path: String = "../flowredux") {
settings.includeBuild(path) { build ->
build.dependencySubstitution {
it.substitute(it.module("com.freeletics.flowredux:flowredux"))
.using(it.project(":flowredux"))
it.substitute(it.module("com.freeletics.flowredux:compose"))
.using(it.project(":compose"))
}
}
}
}
| 7 | Kotlin | 2 | 9 | d5d74c8e0f6c05f37edf6af7b4658e31e894de00 | 9,465 | freeletics-gradle-plugins | Apache License 2.0 |
app/src/main/java/com/abmodel/uwheels/ui/shared/signup/SignUpFragment.kt | IntroCompuMovil202210J | 458,320,044 | false | null | package com.abmodel.uwheels.ui.shared.signup
import android.os.Bundle
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.view.inputmethod.EditorInfo
import android.widget.Toast
import androidx.annotation.StringRes
import androidx.fragment.app.viewModels
import androidx.navigation.fragment.findNavController
import com.abmodel.uwheels.R
import com.abmodel.uwheels.databinding.FragmentSignUpBinding
import com.abmodel.uwheels.ui.driver.apply.BecomeDriverFragment
class SignUpFragment : Fragment() {
companion object {
const val TAG = "SignUpFragment"
}
// Binding objects to access the view elements
private var _binding: FragmentSignUpBinding? = null
private val binding get() = _binding!!
private val signUpViewModel: SignUpViewModel by viewModels()
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View {
// Inflate the layout and binding for this fragment
_binding = FragmentSignUpBinding.inflate(inflater, container, false)
return binding.root
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
binding.apply {
passwordAgain.setOnEditorActionListener { _, actionId, _ ->
if (actionId == EditorInfo.IME_ACTION_DONE) {
onClickedSignUp()
}
false
}
signUp.setOnClickListener {
signUpViewModel.signUp(
name.text.toString(),
lastName.text.toString(),
phoneNumber.text.toString(),
email.text.toString(),
password.text.toString(),
passwordAgain.text.toString()
)
}
}
signUpViewModel.signUpResult.observe(viewLifecycleOwner) { signUpResult ->
signUpResult ?: return@observe
signUpResult.error?.let {
showSignUpFailed(it)
}
if (signUpResult.success) {
goToBecomeDriverScreen()
}
}
}
private fun onClickedSignUp() {
signUpViewModel.signUp(
binding.name.text.toString(),
binding.lastName.text.toString(),
binding.phoneNumber.text.toString(),
binding.email.text.toString(),
binding.password.text.toString(),
binding.passwordAgain.text.toString()
)
}
private fun showSignUpFailed(@StringRes errorString: Int) {
Toast.makeText(requireContext(), errorString, Toast.LENGTH_SHORT).show()
}
private fun goToBecomeDriverScreen() {
findNavController().navigate(
R.id.action_signUpFragment_to_becomeDriverFragment
)
}
override fun onDestroyView() {
super.onDestroyView()
_binding = null
}
}
| 0 | Kotlin | 1 | 1 | 9c60f269708dd512548ee79e07d3da5d83b777dc | 2,571 | UWheels | Apache License 2.0 |
src/main/kotlin/it/czerwinski/intellij/wavefront/settings/WavefrontObjSettingsComponent.kt | sczerwinski | 283,832,623 | false | null | /*
* Copyright 2020-2023 <NAME>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* 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 it.czerwinski.intellij.wavefront.settings
import com.intellij.ui.dsl.builder.panel
import it.czerwinski.intellij.wavefront.WavefrontObjBundle
import javax.swing.JComponent
import javax.swing.JPanel
/**
* UI component for Wavefront OBJ plugin settings.
*/
class WavefrontObjSettingsComponent : SettingsComponent, WavefrontObjSettingsState.Holder {
private val objSplitEditorSettingsGroup = ObjSplitEditorSettingsGroup()
private val objPreviewSettingsGroup = ObjPreviewSettingsGroup()
private val mtlEditorSettingsGroup = MtlEditorSettingsGroup()
private val mainPanel: JPanel = panel {
group(WavefrontObjBundle.message("settings.editor.fileTypes.obj.layout.title")) {
objSplitEditorSettingsGroup.createGroupContents(this)
}
group(WavefrontObjBundle.message("settings.editor.fileTypes.obj.preview.title")) {
objPreviewSettingsGroup.createGroupContents(this)
}
group(WavefrontObjBundle.message("settings.editor.fileTypes.mtl.material.title")) {
mtlEditorSettingsGroup.createGroupContents(this)
}
}
override var wavefrontObjSettings: WavefrontObjSettingsState
get() = WavefrontObjSettingsState(
objPreviewSettings = objPreviewSettingsGroup.objPreviewSettings,
mtlEditorSettings = mtlEditorSettingsGroup.mtlEditorSettings,
editorLayout = objSplitEditorSettingsGroup.defaultEditorLayout,
isVerticalSplit = objSplitEditorSettingsGroup.isVerticalSplit
)
set(value) {
objPreviewSettingsGroup.objPreviewSettings = value.objPreviewSettings
mtlEditorSettingsGroup.mtlEditorSettings = value.mtlEditorSettings
objSplitEditorSettingsGroup.defaultEditorLayout = value.editorLayout
objSplitEditorSettingsGroup.isVerticalSplit = value.isVerticalSplit
}
override fun getComponent(): JComponent = mainPanel
override fun getPreferredFocusedComponent(): JComponent = objPreviewSettingsGroup.getPreferredFocusedComponent()
override fun validateForm() {
objSplitEditorSettingsGroup.validateForm()
objPreviewSettingsGroup.validateForm()
}
}
| 26 | null | 1 | 9 | ca6ee47083cdca9b52cd2a59994d12a4a10033eb | 2,798 | wavefront-obj-intellij-plugin | Apache License 2.0 |
samples/openapi3/client/petstore/kotlin/src/main/kotlin/org/openapitools/client/models/EnumTest.kt | twitterdev | 334,329,847 | true | {"Shell": 764, "XML": 335, "Batchfile": 269, "YAML": 204, "Ruby": 638, "Ignore List": 266, "Maven POM": 241, "Dockerfile": 21, "Markdown": 5016, "Text": 73, "Git Attributes": 1, "INI": 120, "Gradle": 116, "Java": 5459, "JavaScript": 663, "JSON": 468, "CSS": 18, "SVG": 21, "CODEOWNERS": 1, "OASv2-json": 23, "HTML": 89, "OASv3-yaml": 104, "OASv3-json": 2, "AsciiDoc": 13, "C#": 1351, "JSON with Comments": 46, "Scala": 230, "OASv2-yaml": 29, "Mustache": 2579, "Kotlin": 601, "Go Checksums": 7, "Java Properties": 17, "ActionScript": 36, "Ant Build System": 2, "ApacheConf": 10, "Dotenv": 5, "PHP": 974, "robots.txt": 4, "Vue": 2, "SCSS": 4, "Blade": 2, "Option List": 13, "PowerShell": 55, "Apex": 25, "Python": 945, "HTML+ERB": 4, "Rust": 108, "Dart": 315, "GraphQL": 19, "Protocol Buffer": 21, "SQL": 2, "Gradle Kotlin DSL": 6, "Go": 467, "Go Module": 6, "TOML": 13, "Microsoft Visual Studio Solution": 14, "Makefile": 12, "F#": 49, "Gemfile.lock": 2, "Haskell": 26, "Cabal Config": 4, "CMake": 9, "C++": 182, "Gherkin": 1, "Erlang": 39, "OpenStep Property List": 87, "Swift": 1557, "Objective-C": 145, "Nim": 12, "Perl": 168, "R": 23, "C": 33, "Ada": 8, "MATLAB": 1, "Clojure": 14, "OCaml": 75, "Lua": 20, "Elixir": 59, "Elm": 57, "Eiffel": 65, "QMake": 2, "EditorConfig": 2, "Browserslist": 2, "Groovy": 11} | /**
* OpenAPI Petstore
* This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\
*
* OpenAPI spec version: 1.0.0
*
*
* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
* https://openapi-generator.tech
* Do not edit the class manually.
*/
package org.openapitools.client.models
import org.openapitools.client.models.OuterEnum
import com.squareup.moshi.Json
/**
*
* @param enumString
* @param enumStringRequired
* @param enumInteger
* @param enumNumber
* @param outerEnum
*/
data class EnumTest (
val enumStringRequired: EnumTest.EnumStringRequired,
val enumString: EnumTest.EnumString? = null,
val enumInteger: EnumTest.EnumInteger? = null,
val enumNumber: EnumTest.EnumNumber? = null,
val outerEnum: OuterEnum? = null
) {
/**
*
* Values: uPPER,lower,eMPTY
*/
enum class EnumString(val value: kotlin.String){
@Json(name = "UPPER") uPPER("UPPER"),
@Json(name = "lower") lower("lower"),
@Json(name = "") eMPTY("");
}
/**
*
* Values: uPPER,lower,eMPTY
*/
enum class EnumStringRequired(val value: kotlin.String){
@Json(name = "UPPER") uPPER("UPPER"),
@Json(name = "lower") lower("lower"),
@Json(name = "") eMPTY("");
}
/**
*
* Values: _1,minus1
*/
enum class EnumInteger(val value: kotlin.Int){
@Json(name = 1) _1(1),
@Json(name = -1) minus1(-1);
}
/**
*
* Values: _1period1,minus1Period2
*/
enum class EnumNumber(val value: kotlin.Double){
@Json(name = 1.1) _1period1(1.1),
@Json(name = -1.2) minus1Period2(-1.2);
}
}
| 54 | null | 3 | 5 | f8770d7c3388d9f1a5069a7f37378aeadcb81e16 | 1,848 | unreal-openapi-generator | Apache License 2.0 |
app/src/main/java/com/example/kitapp/retrofit/accessInfo.kt | BerkayKaramehmetoglu | 729,634,621 | false | {"Kotlin": 12773} | package com.example.kitapp.retrofit
import com.google.gson.annotations.Expose
import com.google.gson.annotations.SerializedName
data class accessInfo(
@SerializedName("country")
@Expose
var country: String?,
@SerializedName("viewability")
@Expose
var viewability: String?,
@SerializedName("pdf")
@Expose
var pdf: pdf,
@SerializedName("webReaderLink")
@Expose
var webReaderLink: String?,
@SerializedName("accessViewStatus")
@Expose
var accessViewStatus: String?,
)
| 1 | Kotlin | 0 | 0 | 61fe73ce5a861c6fac6115ab3fbb8b414968c46b | 526 | KitApp | MIT License |
app/src/main/kotlin/org/andstatus/app/net/social/Actor.kt | andstatus | 3,040,264 | false | null | /*
* Copyright (C) 2013-2018 yvolk (<NAME>), http://yurivolkov.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 org.andstatus.app.net.social
import android.database.Cursor
import android.net.Uri
import android.provider.BaseColumns
import io.vavr.control.Try
import org.andstatus.app.R
import org.andstatus.app.account.AccountName
import org.andstatus.app.actor.Group
import org.andstatus.app.actor.GroupType
import org.andstatus.app.context.ActorInTimeline
import org.andstatus.app.context.MyContext
import org.andstatus.app.context.MyPreferences
import org.andstatus.app.data.ActorSql
import org.andstatus.app.data.AvatarFile
import org.andstatus.app.data.DbUtils
import org.andstatus.app.data.DownloadStatus
import org.andstatus.app.data.MyQuery
import org.andstatus.app.data.OidEnum
import org.andstatus.app.database.table.ActorTable
import org.andstatus.app.origin.Origin
import org.andstatus.app.origin.OriginPumpio
import org.andstatus.app.origin.OriginType
import org.andstatus.app.os.AsyncUtil
import org.andstatus.app.service.CommandData
import org.andstatus.app.service.CommandEnum
import org.andstatus.app.service.MyServiceManager
import org.andstatus.app.timeline.meta.TimelineType
import org.andstatus.app.user.User
import org.andstatus.app.util.IsEmpty
import org.andstatus.app.util.LazyVal
import org.andstatus.app.util.MyHtml
import org.andstatus.app.util.MyLog
import org.andstatus.app.util.MyStringBuilder
import org.andstatus.app.util.NullUtil
import org.andstatus.app.util.RelativeTime
import org.andstatus.app.util.SharedPreferencesUtil
import org.andstatus.app.util.StringUtil
import org.andstatus.app.util.TriState
import org.andstatus.app.util.UriUtils
import org.andstatus.app.util.UrlUtils
import org.junit.Assert
import java.net.URL
import java.util.*
import java.util.function.Supplier
import java.util.stream.Collectors
/**
* @author <EMAIL>
*/
class Actor private constructor(// In our system
val origin: Origin,
val groupType: GroupType,
actorId: Long,
actorOid: String?) : Comparable<Actor>, IsEmpty {
val oid: String = if (actorOid.isNullOrEmpty()) "" else actorOid
private var parentActorId: Long = 0
private var parentActor: LazyVal<Actor> = LazyVal.of(EMPTY)
private var username: String = ""
private var webFingerId: String = ""
private var isWebFingerIdValid = false
private var realName: String = ""
private var summary: String = ""
var location: String = ""
private var profileUri = Uri.EMPTY
private var homepage: String = ""
private var avatarUri = Uri.EMPTY
val endpoints: ActorEndpoints = ActorEndpoints.from(origin.myContext, actorId)
private val connectionHost: LazyVal<String> = LazyVal.of { evalConnectionHost() }
private val idHost: LazyVal<String> = LazyVal.of { evalIdHost() }
var notesCount: Long = 0
var favoritesCount: Long = 0
var followingCount: Long = 0
var followersCount: Long = 0
private var createdDate = RelativeTime.DATETIME_MILLIS_NEVER
private var updatedDate = RelativeTime.DATETIME_MILLIS_NEVER
private var latestActivity: AActivity? = null
// Hack for Twitter-like origins...
var isMyFriend: TriState = TriState.UNKNOWN
@Volatile
var actorId = actorId
var avatarFile: AvatarFile = AvatarFile.EMPTY
@Volatile
var user: User = User.EMPTY
@Volatile
private var isFullyDefined: TriState = TriState.UNKNOWN
fun getDefaultMyAccountTimelineTypes(): List<TimelineType> {
return if (origin.originType.isPrivatePostsSupported()) TimelineType.getDefaultMyAccountTimelineTypes()
else TimelineType.getDefaultMyAccountTimelineTypes().stream()
.filter { t: TimelineType? -> t != TimelineType.PRIVATE }
.collect(Collectors.toList())
}
private fun betterToCache(other: Actor): Actor {
return if (isBetterToCacheThan(other)) this else other
}
/** this Actor is MyAccount and the Actor updates objActor */
fun update(objActor: Actor): AActivity {
return update(this, objActor)
}
/** this actor updates objActor */
fun update(accountActor: Actor, objActor: Actor): AActivity {
return if (objActor === EMPTY) AActivity.EMPTY else act(accountActor, ActivityType.UPDATE, objActor)
}
/** this actor acts on objActor */
fun act(accountActor: Actor, activityType: ActivityType, objActor: Actor): AActivity {
if (this === EMPTY || accountActor === EMPTY || objActor === EMPTY) {
return AActivity.EMPTY
}
val mbActivity: AActivity = AActivity.from(accountActor, activityType)
mbActivity.setActor(this)
mbActivity.setObjActor(objActor)
return mbActivity
}
fun isConstant(): Boolean {
return this === EMPTY || this === PUBLIC || this === FOLLOWERS
}
override val isEmpty: Boolean get() {
if (this === EMPTY) return true
return if (isConstant()) false else !origin.isValid ||
actorId == 0L && UriUtils.nonRealOid(oid) && !isWebFingerIdValid() && !isUsernameValid()
}
fun dontStore(): Boolean {
return isConstant()
}
fun isFullyDefined(): Boolean {
if (isFullyDefined.unknown) {
isFullyDefined = calcIsFullyDefined()
}
return isFullyDefined.isTrue
}
private fun calcIsFullyDefined(): TriState {
if (isEmpty || UriUtils.nonRealOid(oid)) return TriState.FALSE
return if (groupType.isGroupLike) TriState.TRUE
else TriState.fromBoolean(isWebFingerIdValid() && isUsernameValid())
}
fun isNotFullyDefined(): Boolean {
return !isFullyDefined()
}
fun isBetterToCacheThan(other: Actor): Boolean {
if (this === other) return false
if (other == null || other === EMPTY ||
isFullyDefined() && other.isNotFullyDefined()) return true
if (this === EMPTY || isNotFullyDefined() && other.isFullyDefined()) return false
return if (isFullyDefined()) {
if (getUpdatedDate() != other.getUpdatedDate()) {
return getUpdatedDate() > other.getUpdatedDate()
}
if (avatarFile.downloadedDate != other.avatarFile.downloadedDate) {
avatarFile.downloadedDate > other.avatarFile.downloadedDate
} else notesCount > other.notesCount
} else {
if (isOidReal() && !other.isOidReal()) return true
if (!isOidReal() && other.isOidReal()) return false
if (isUsernameValid() && !other.isUsernameValid()) return true
if (!isUsernameValid() && other.isUsernameValid()) return false
if (isWebFingerIdValid() && !other.isWebFingerIdValid()) return true
if (!isWebFingerIdValid() && other.isWebFingerIdValid()) return false
if (UriUtils.nonEmpty(profileUri) && UriUtils.isEmpty(other.profileUri)) return true
if (UriUtils.isEmpty(profileUri) && UriUtils.nonEmpty(other.profileUri)) false else getUpdatedDate() > other.getUpdatedDate()
}
}
fun isIdentified(): Boolean {
return actorId != 0L && isOidReal()
}
fun isOidReal(): Boolean {
return UriUtils.isRealOid(oid)
}
fun canGetActor(): Boolean {
return (isOidReal() || isWebFingerIdValid()) && getConnectionHost().isNotEmpty()
}
override fun toString(): String {
if (this === EMPTY) {
return "Actor:EMPTY"
}
val members: MyStringBuilder = MyStringBuilder.of("origin:" + origin.name)
.withComma("id", actorId)
.withComma("oid", oid)
.withComma(if (isWebFingerIdValid()) "webFingerId" else "", if (webFingerId.isEmpty()) ""
else if (isWebFingerIdValid()) webFingerId else "(invalid webFingerId)")
.withComma("username", username)
.withComma("realName", realName)
.withComma("groupType", if (groupType == GroupType.UNKNOWN) "" else groupType)
.withComma("", user) { user.nonEmpty }
.withComma<Uri?>("profileUri", profileUri, { obj: Uri? -> UriUtils.nonEmpty(obj) })
.withComma<Uri?>("avatar", avatarUri, { obj: Uri? -> UriUtils.nonEmpty(obj) })
.withComma<AvatarFile>("avatarFile", avatarFile, { obj: AvatarFile -> obj.nonEmpty })
.withComma("banner", endpoints.findFirst(ActorEndpointType.BANNER).orElse(null))
.withComma("", "latest note present", { hasLatestNote() })
if (parentActor.isEvaluated() && parentActor.get().nonEmpty) {
members.withComma("parent", parentActor.get())
} else if (parentActorId != 0L) {
members.withComma("parentId", parentActorId)
}
return MyStringBuilder.formatKeyValue(this, members)
}
fun getUsername(): String {
return username
}
fun getUniqueNameWithOrigin(): String {
return uniqueName + AccountName.ORIGIN_SEPARATOR + origin.name
}
val uniqueName: String
get() {
if (StringUtil.nonEmptyNonTemp(username)) return username + getOptAtHostForUniqueName()
if (StringUtil.nonEmptyNonTemp(realName)) return realName + getOptAtHostForUniqueName()
if (isWebFingerIdValid()) return webFingerId
return if (StringUtil.nonEmptyNonTemp(oid)) oid else "id:" + actorId + getOptAtHostForUniqueName()
}
private fun getOptAtHostForUniqueName(): String {
return if (origin.originType.uniqueNameHasHost()) if (getIdHost().isEmpty()) "" else "@" + getIdHost() else ""
}
fun withUniqueName(uniqueName: String?): Actor {
uniqueNameToUsername(origin, uniqueName).ifPresent { username: String? -> setUsername(username) }
uniqueNameToWebFingerId(origin, uniqueName).ifPresent { webFingerIdIn: String? -> setWebFingerId(webFingerIdIn) }
return this
}
fun setUsername(username: String?): Actor {
check(!(this === EMPTY)) { "Cannot set username of EMPTY Actor" }
this.username = if (username.isNullOrEmpty()) "" else username.trim { it <= ' ' }
return this
}
fun getProfileUrl(): String {
return profileUri.toString()
}
fun setProfileUrl(url: String?): Actor {
profileUri = UriUtils.fromString(url)
return this
}
fun setProfileUrlToOriginUrl(originUrl: URL?) {
profileUri = UriUtils.fromUrl(originUrl)
}
override fun equals(other: Any?): Boolean {
if (this === other) return true
return if (other !is Actor) false else isSame(other as Actor, true)
}
override fun hashCode(): Int {
var result = origin.hashCode()
if (actorId != 0L) {
return 31 * result + java.lang.Long.hashCode(actorId)
}
if (UriUtils.isRealOid(oid)) {
return 31 * result + oid.hashCode()
} else if (isWebFingerIdValid) {
return 31 * result + getWebFingerId().hashCode()
} else if (isUsernameValid()) {
result = 31 * result + getUsername().hashCode()
}
return result
}
/** Doesn't take origin into account */
fun isSame(that: Actor): Boolean {
return isSame(that, false)
}
fun isSame(other: Actor, sameOriginOnly: Boolean): Boolean {
if (this === other) return true
if (other == null) return false
if (actorId != 0L) {
if (actorId == other.actorId) return true
}
if (origin == other.origin) {
if (UriUtils.isRealOid(oid) && oid == other.oid) {
return true
}
} else if (sameOriginOnly) {
return false
}
if (isWebFingerIdValid()) {
if (webFingerId == other.webFingerId) return true
if (other.isWebFingerIdValid) return false
}
return if (groupType.isDifferentActor(other.groupType)) false
else isUsernameValid() && other.isUsernameValid() && username.equals(other.username, ignoreCase = true)
}
fun notSameUser(other: Actor): Boolean {
return !isSameUser(other)
}
fun isSameUser(other: Actor): Boolean {
return if (user.actorIds.isEmpty() || other.actorId == 0L) if (other.user.actorIds.isEmpty() || actorId == 0L) isSame(other) else other.user.actorIds.contains(actorId) else user.actorIds.contains(other.actorId)
}
fun build(): Actor {
if (this === EMPTY) return this
connectionHost.reset()
if (username.isEmpty() || isWebFingerIdValid) return this
if (username.contains("@") == true) {
setWebFingerId(username)
} else if (!UriUtils.isEmpty(profileUri)) {
if (origin.isValid) {
setWebFingerId(username + "@" + origin.fixUriForPermalink(profileUri).host)
} else {
setWebFingerId(username + "@" + profileUri.host)
}
// Don't infer "id host" from the Origin's host
}
return this
}
fun setWebFingerId(webFingerIdIn: String?): Actor {
if (webFingerIdIn.isNullOrEmpty() || !webFingerIdIn.contains("@")) return this
var potentialUsername = webFingerIdIn
val nameBeforeTheLastAt = webFingerIdIn.substring(0, webFingerIdIn.lastIndexOf("@"))
if (isWebFingerIdValid(webFingerIdIn)) {
webFingerId = webFingerIdIn.toLowerCase()
isWebFingerIdValid = true
potentialUsername = nameBeforeTheLastAt
} else {
val lastButOneIndex = nameBeforeTheLastAt.lastIndexOf("@")
if (lastButOneIndex > -1) {
val potentialWebFingerId = webFingerIdIn.substring(lastButOneIndex + 1)
if (isWebFingerIdValid(potentialWebFingerId)) {
webFingerId = potentialWebFingerId.toLowerCase()
isWebFingerIdValid = true
potentialUsername = webFingerIdIn.substring(0, lastButOneIndex)
}
}
}
if (!isUsernameValid() && origin.isUsernameValid(potentialUsername)) {
username = potentialUsername
}
return this
}
fun getWebFingerId(): String {
return webFingerId
}
fun isWebFingerIdValid(): Boolean {
return isWebFingerIdValid
}
fun getBestUri(): String {
if (!StringUtil.isEmptyOrTemp(oid)) {
return oid
}
if (isUsernameValid() && getIdHost().isNotEmpty()) {
return OriginPumpio.ACCOUNT_PREFIX + getUsername() + "@" + getIdHost()
}
return if (isWebFingerIdValid()) {
OriginPumpio.ACCOUNT_PREFIX + getWebFingerId()
} else ""
}
/** Lookup the application's id from other IDs */
fun lookupActorId() {
if (isConstant()) return
if (actorId == 0L && isOidReal()) {
actorId = MyQuery.oidToId(origin.myContext, OidEnum.ACTOR_OID, origin.id, oid)
}
if (actorId == 0L && isWebFingerIdValid()) {
actorId = MyQuery.webFingerIdToId(origin.myContext, origin.id, webFingerId, true)
}
if (actorId == 0L && username.isNotEmpty()) {
val actorId2 = origin.usernameToId(username)
if (actorId2 != 0L) {
var skip2 = false
if (isWebFingerIdValid()) {
val webFingerId2 = MyQuery.actorIdToWebfingerId(origin.myContext, actorId2)
if (isWebFingerIdValid(webFingerId2)) {
skip2 = !webFingerId.equals(webFingerId2, ignoreCase = true)
if (!skip2) actorId = actorId2
}
}
if (actorId == 0L && !skip2 && isOidReal()) {
val oid2 = MyQuery.idToOid(origin.myContext, OidEnum.ACTOR_OID, actorId2, 0)
if (UriUtils.isRealOid(oid2)) skip2 = !oid.equals(oid2, ignoreCase = true)
}
if (actorId == 0L && !skip2 && groupType != GroupType.UNKNOWN) {
val groupTypeStored = origin.myContext.users.idToGroupType(actorId2)
if (Group.groupTypeNeedsCorrection(groupTypeStored, groupType)) {
val updatedDateStored = MyQuery.actorIdToLongColumnValue(ActorTable.UPDATED_DATE, actorId)
if (getUpdatedDate() <= updatedDateStored) {
setUpdatedDate(Math.max(updatedDateStored + 1, RelativeTime.SOME_TIME_AGO + 1))
}
}
}
if (actorId == 0L && !skip2) {
actorId = actorId2
}
}
}
if (actorId == 0L) {
actorId = MyQuery.oidToId(origin.myContext, OidEnum.ACTOR_OID, origin.id, toTempOid())
}
if (actorId == 0L && hasAltTempOid()) {
actorId = MyQuery.oidToId(origin.myContext, OidEnum.ACTOR_OID, origin.id, toAltTempOid())
}
}
fun hasAltTempOid(): Boolean {
return toTempOid() != toAltTempOid() && username.isNotEmpty()
}
fun hasLatestNote(): Boolean {
return latestActivity?.isEmpty == false
}
fun toAltTempOid(): String {
return toTempOid("", username)
}
/** Tries to find this actor in his home origin (the same host...).
* Returns the same Actor, if not found */
fun toHomeOrigin(): Actor {
return if (origin.getHost() == getIdHost()) this else user.actorIds.stream()
.map { id: Long -> NullUtil.getOrDefault(origin.myContext.users.actors, id, EMPTY) }
.filter { a: Actor -> a.nonEmpty && a.origin.getHost() == getIdHost() }
.findAny().orElse(this)
}
fun extractActorsFromContent(text: String?, inReplyToActorIn: Actor): List<Actor> {
return _extractActorsFromContent(MyHtml.htmlToCompactPlainText(text), 0, ArrayList(),
inReplyToActorIn.withValidUsernameAndWebfingerId())
}
private fun _extractActorsFromContent(text: String, textStart: Int, actors: MutableList<Actor>, inReplyToActor: Actor): MutableList<Actor> {
val actorReference = origin.getActorReference(text, textStart)
if (actorReference.index < textStart) return actors
var validUsername: String? = ""
var validWebFingerId: String? = ""
var ind = actorReference.index
while (ind < text.length) {
if (Patterns.WEBFINGER_ID_CHARS.indexOf(text.get(ind)) < 0) {
break
}
val username = text.substring(actorReference.index, ind + 1)
if (origin.isUsernameValid(username)) {
validUsername = username
}
if (isWebFingerIdValid(username)) {
validWebFingerId = username
}
ind++
}
if (!validWebFingerId.isNullOrEmpty() || !validUsername.isNullOrEmpty()) {
addExtractedActor(actors, validWebFingerId, validUsername, actorReference.groupType, inReplyToActor)
}
return _extractActorsFromContent(text, ind + 1, actors, inReplyToActor)
}
private fun withValidUsernameAndWebfingerId(): Actor {
return if (isWebFingerIdValid && isUsernameValid() || actorId == 0L) this else load(origin.myContext, actorId)
}
fun isUsernameValid(): Boolean {
return StringUtil.nonEmptyNonTemp(username) && origin.isUsernameValid(username)
}
private fun addExtractedActor(actors: MutableList<Actor>, webFingerId: String?, validUsername: String?,
groupType: GroupType, inReplyToActor: Actor) {
var actor = newUnknown(origin, groupType)
if (isWebFingerIdValid(webFingerId)) {
actor.setWebFingerId(webFingerId)
actor.setUsername(validUsername)
} else {
// Is this a reply to Actor
if (validUsername.equals(inReplyToActor.getUsername(), ignoreCase = true)) {
actor = inReplyToActor
} else if (validUsername.equals(getUsername(), ignoreCase = true)) {
actor = this
} else {
// Don't infer "id host", if it wasn't explicitly provided
actor.setUsername(validUsername)
}
}
actor.build()
actors.add(actor)
}
fun getConnectionHost(): String {
return connectionHost.get()
}
private fun evalConnectionHost(): String {
if (origin.shouldHaveUrl()) {
return origin.getHost()
}
return if (!profileUri.host.isNullOrEmpty()) {
profileUri.host ?: ""
} else UrlUtils.getHost(oid).orElseGet {
if (isWebFingerIdValid) {
val pos = getWebFingerId().indexOf('@')
if (pos >= 0) {
return@orElseGet getWebFingerId().substring(pos + 1)
}
}
""
}
}
fun getIdHost(): String {
return idHost.get()
}
private fun evalIdHost(): String {
return UrlUtils.getHost(oid).orElseGet {
if (isWebFingerIdValid) {
val pos = getWebFingerId().indexOf('@')
if (pos >= 0) {
return@orElseGet getWebFingerId().substring(pos + 1)
}
}
if (!profileUri.host.isNullOrEmpty()) {
return@orElseGet profileUri.host
}
""
}
}
fun getSummary(): String {
return summary
}
fun setSummary(summary: String?): Actor {
if (!isEmpty && !summary.isNullOrEmpty() && !SharedPreferencesUtil.isEmpty(summary)) {
this.summary = summary
}
return this
}
fun getHomepage(): String {
return homepage
}
fun setHomepage(homepage: String?) {
if (!homepage.isNullOrEmpty() && !SharedPreferencesUtil.isEmpty(homepage)) {
this.homepage = homepage
}
}
fun getRecipientName(): String {
return if (groupType == GroupType.FOLLOWERS) {
origin.myContext.context.getText(R.string.followers).toString()
} else uniqueName
}
fun getActorNameInTimelineWithOrigin(): String {
return if (MyPreferences.getShowOrigin() && nonEmpty) {
val name = actorNameInTimeline + " / " + origin.name
if (origin.originType === OriginType.GNUSOCIAL && MyPreferences.isShowDebuggingInfoInUi()
&& oid.isNotEmpty()) {
"$name oid:$oid"
} else name
} else actorNameInTimeline
}
val actorNameInTimeline: String
get() {
val name1 = getActorNameInTimeline1()
return if (name1.isNotEmpty()) name1 else getUniqueNameWithOrigin()
}
private fun getActorNameInTimeline1(): String {
return when (MyPreferences.getActorInTimeline()) {
ActorInTimeline.AT_USERNAME -> if (username.isEmpty()) "" else "@$username"
ActorInTimeline.WEBFINGER_ID -> if (isWebFingerIdValid) webFingerId else ""
ActorInTimeline.REAL_NAME -> realName
ActorInTimeline.REAL_NAME_AT_USERNAME -> if (realName.isNotEmpty() && username.isNotEmpty()) "$realName @$username" else username
ActorInTimeline.REAL_NAME_AT_WEBFINGER_ID -> if (realName.isNotEmpty() && webFingerId.isNotEmpty()) "$realName @$webFingerId" else webFingerId
else -> username
}
}
fun getRealName(): String {
return realName
}
fun setRealName(realName: String?) {
if (!realName.isNullOrEmpty() && !SharedPreferencesUtil.isEmpty(realName)) {
this.realName = realName
}
}
fun getCreatedDate(): Long {
return createdDate
}
fun setCreatedDate(createdDate: Long) {
this.createdDate = if (createdDate < RelativeTime.SOME_TIME_AGO) RelativeTime.SOME_TIME_AGO else createdDate
}
fun getUpdatedDate(): Long {
return updatedDate
}
fun setUpdatedDate(updatedDate: Long) {
if (this.updatedDate >= updatedDate) return
this.updatedDate = if (updatedDate < RelativeTime.SOME_TIME_AGO) RelativeTime.SOME_TIME_AGO else updatedDate
}
override operator fun compareTo(other: Actor): Int {
if (actorId != 0L && other.actorId != 0L) {
if (actorId == other.actorId) {
return 0
}
return if (origin.id > other.origin.id) 1 else -1
}
return if (origin.id != other.origin.id) {
if (origin.id > other.origin.id) 1 else -1
} else oid.compareTo(other.oid)
}
fun getLatestActivity(): AActivity {
return latestActivity ?: AActivity.EMPTY
}
fun setLatestActivity(latestActivity: AActivity) {
this.latestActivity = latestActivity
if (latestActivity.getAuthor().isEmpty) {
latestActivity.setAuthor(this)
}
}
fun toActorTitle(): String {
val builder = StringBuilder()
val uniqueName = uniqueName
if (uniqueName.isNotEmpty()) {
builder.append("@$uniqueName")
}
if (getRealName().isNotEmpty()) {
MyStringBuilder.appendWithSpace(builder, "(" + getRealName() + ")")
}
return builder.toString()
}
fun lookupUser(): Actor {
return if(isEmpty) this else origin.myContext.users.lookupUser(this)
}
fun saveUser() {
if (user.isMyUser.unknown && origin.myContext.users.isMe(this)) {
user.isMyUser = TriState.TRUE
}
if (user.userId == 0L) user.setKnownAs(uniqueName)
user.save(origin.myContext)
}
fun hasAvatar(): Boolean {
return UriUtils.nonEmpty(avatarUri)
}
fun hasAvatarFile(): Boolean {
return AvatarFile.EMPTY !== avatarFile
}
fun requestDownload(isManuallyLaunched: Boolean) {
if (canGetActor()) {
MyLog.v(this) { "Actor $this will be loaded from the Internet" }
val command: CommandData = CommandData.newActorCommandAtOrigin(
CommandEnum.GET_ACTOR, this, getUsername(), origin)
.setManuallyLaunched(isManuallyLaunched)
MyServiceManager.sendForegroundCommand(command)
} else {
MyLog.v(this) { "Cannot get Actor $this" }
}
}
fun isPublic(): Boolean {
return groupType == GroupType.PUBLIC
}
fun isFollowers(): Boolean {
return groupType == GroupType.FOLLOWERS
}
fun nonPublic(): Boolean {
return !isPublic()
}
fun getAvatarUri(): Uri? {
return avatarUri
}
fun getAvatarUrl(): String {
return avatarUri.toString()
}
fun setAvatarUrl(avatarUrl: String?) {
setAvatarUri(UriUtils.fromString(avatarUrl))
}
fun setAvatarUri(avatarUri: Uri?) {
this.avatarUri = UriUtils.notNull(avatarUri)
if (hasAvatar() && avatarFile.isEmpty) {
avatarFile = AvatarFile.fromActorOnly(this)
}
}
fun requestAvatarDownload() {
if (hasAvatar() && MyPreferences.getShowAvatars() && avatarFile.downloadStatus != DownloadStatus.LOADED) {
avatarFile.requestDownload()
}
}
fun getEndpoint(type: ActorEndpointType?): Optional<Uri> {
val uri = endpoints.findFirst(type)
return if (uri.isPresent) uri else
if (type == ActorEndpointType.API_PROFILE) UriUtils.toDownloadableOptional(oid)
else Optional.empty()
}
fun assertContext() {
if (isConstant()) return
try {
origin.assertContext()
} catch (e: Throwable) {
Assert.fail("Failed on $this\n${e.message}")
}
}
fun setParentActorId(myContext: MyContext, parentActorId: Long): Actor {
if (this.parentActorId != parentActorId) {
this.parentActorId = parentActorId
parentActor = if (parentActorId == 0L) LazyVal.of(EMPTY)
else LazyVal.of { load(myContext, parentActorId) }
}
return this
}
fun getParentActorId(): Long {
return parentActorId
}
fun getParent(): Actor {
return parentActor.get()
}
fun toTempOid(): String {
return toTempOid(webFingerId, username)
}
companion object {
val EMPTY: Actor = newUnknown(Origin.EMPTY, GroupType.UNKNOWN).setUsername("Empty")
val TRY_EMPTY = Try.success(EMPTY)
val PUBLIC = fromTwoIds(Origin.EMPTY, GroupType.PUBLIC, 0,
"https://www.w3.org/ns/activitystreams#Public").setUsername("Public")
val FOLLOWERS = fromTwoIds(Origin.EMPTY, GroupType.FOLLOWERS, 0,
"org.andstatus.app.net.social.Actor#Followers").setUsername("Followers")
fun getEmpty(): Actor {
return EMPTY
}
fun load(myContext: MyContext, actorId: Long): Actor {
return load(myContext, actorId, false) { getEmpty() }
}
fun load(myContext: MyContext, actorId: Long, reloadFirst: Boolean, supplier: Supplier<Actor>): Actor {
if (actorId == 0L) return supplier.get()
val cached = myContext.users.actors.getOrDefault(actorId, EMPTY)
return if (AsyncUtil.nonUiThread && (reloadFirst || cached.isNotFullyDefined()))
loadFromDatabase(myContext, actorId, supplier, true).betterToCache(cached)
else cached
}
fun loadFromDatabase(myContext: MyContext, actorId: Long, supplier: Supplier<Actor>,
useCache: Boolean): Actor {
val sql = ("SELECT " + ActorSql.selectFullProjection()
+ " FROM " + ActorSql.allTables()
+ " WHERE " + ActorTable.TABLE_NAME + "." + BaseColumns._ID + "=" + actorId)
val function = { cursor: Cursor -> fromCursor(myContext, cursor, useCache) }
return MyQuery.get(myContext, sql, function).stream().findFirst().orElseGet(supplier)
}
/** Updates cache on load */
fun fromCursor(myContext: MyContext, cursor: Cursor, useCache: Boolean): Actor {
val updatedDate = DbUtils.getLong(cursor, ActorTable.UPDATED_DATE)
val actor = fromTwoIds(
myContext.origins.fromId(DbUtils.getLong(cursor, ActorTable.ORIGIN_ID)),
GroupType.fromId(DbUtils.getLong(cursor, ActorTable.GROUP_TYPE)),
DbUtils.getLong(cursor, ActorTable.ACTOR_ID),
DbUtils.getString(cursor, ActorTable.ACTOR_OID))
actor.setParentActorId(myContext, DbUtils.getLong(cursor, ActorTable.PARENT_ACTOR_ID))
actor.setRealName(DbUtils.getString(cursor, ActorTable.REAL_NAME))
actor.setUsername(DbUtils.getString(cursor, ActorTable.USERNAME))
actor.setWebFingerId(DbUtils.getString(cursor, ActorTable.WEBFINGER_ID))
actor.setSummary(DbUtils.getString(cursor, ActorTable.SUMMARY))
actor.location = DbUtils.getString(cursor, ActorTable.LOCATION)
actor.setProfileUrl(DbUtils.getString(cursor, ActorTable.PROFILE_PAGE))
actor.setHomepage(DbUtils.getString(cursor, ActorTable.HOMEPAGE))
actor.setAvatarUrl(DbUtils.getString(cursor, ActorTable.AVATAR_URL))
actor.notesCount = DbUtils.getLong(cursor, ActorTable.NOTES_COUNT)
actor.favoritesCount = DbUtils.getLong(cursor, ActorTable.FAVORITES_COUNT)
actor.followingCount = DbUtils.getLong(cursor, ActorTable.FOLLOWING_COUNT)
actor.followersCount = DbUtils.getLong(cursor, ActorTable.FOLLOWERS_COUNT)
actor.setCreatedDate(DbUtils.getLong(cursor, ActorTable.CREATED_DATE))
actor.setUpdatedDate(updatedDate)
actor.user = User.fromCursor(myContext, cursor, useCache)
actor.avatarFile = AvatarFile.fromCursor(actor, cursor)
return if (useCache) {
val cachedActor = myContext.users.actors.getOrDefault(actor.actorId, EMPTY)
if (actor.isBetterToCacheThan(cachedActor)) {
myContext.users.updateCache(actor)
return actor
}
cachedActor
} else {
actor
}
}
fun newUnknown(origin: Origin, groupType: GroupType): Actor {
return fromTwoIds(origin, groupType, 0, "")
}
fun fromId(origin: Origin, actorId: Long): Actor {
return fromTwoIds(origin, GroupType.UNKNOWN, actorId, "")
}
fun fromOid(origin: Origin, actorOid: String?): Actor {
return fromTwoIds(origin, GroupType.UNKNOWN, 0, actorOid)
}
fun fromTwoIds(origin: Origin, groupType: GroupType, actorId: Long, actorOid: String?): Actor {
return Actor(origin, groupType, actorId, actorOid)
}
fun uniqueNameToUsername(origin: Origin, uniqueName: String?): Optional<String> {
if (!uniqueName.isNullOrEmpty()) {
if (uniqueName.contains("@")) {
val nameBeforeTheLastAt = uniqueName.substring(0, uniqueName.lastIndexOf("@"))
if (isWebFingerIdValid(uniqueName)) {
if (origin.isUsernameValid(nameBeforeTheLastAt)) return Optional.of(nameBeforeTheLastAt)
} else {
val lastButOneIndex = nameBeforeTheLastAt.lastIndexOf("@")
if (lastButOneIndex > -1) {
// A case when a Username contains "@"
val potentialWebFingerId = uniqueName.substring(lastButOneIndex + 1)
if (isWebFingerIdValid(potentialWebFingerId)) {
val nameBeforeLastButOneAt = uniqueName.substring(0, lastButOneIndex)
if (origin.isUsernameValid(nameBeforeLastButOneAt)) return Optional.of(nameBeforeLastButOneAt)
}
}
}
}
if (origin.isUsernameValid(uniqueName)) return Optional.of(uniqueName)
}
return Optional.empty()
}
fun uniqueNameToWebFingerId(origin: Origin, uniqueName: String?): Optional<String> {
if (!uniqueName.isNullOrEmpty()) {
if (uniqueName.contains("@")) {
val nameBeforeTheLastAt = uniqueName.substring(0, uniqueName.lastIndexOf("@"))
if (isWebFingerIdValid(uniqueName)) {
return Optional.of(uniqueName.toLowerCase())
} else {
val lastButOneIndex = nameBeforeTheLastAt.lastIndexOf("@")
if (lastButOneIndex > -1) {
val potentialWebFingerId = uniqueName.substring(lastButOneIndex + 1)
if (isWebFingerIdValid(potentialWebFingerId)) {
return Optional.of(potentialWebFingerId.toLowerCase())
}
}
}
} else {
return Optional.of(uniqueName.toLowerCase() + "@" +
origin.fixUriForPermalink(UriUtils.fromUrl(origin.url)).host)
}
}
return Optional.empty()
}
fun isWebFingerIdValid(webFingerId: String?): Boolean {
return !webFingerId.isNullOrEmpty() && Patterns.WEBFINGER_ID_REGEX_PATTERN.matcher(webFingerId).matches()
}
fun toTempOid(webFingerId: String, validUserName: String?): String {
return StringUtil.toTempOid(if (isWebFingerIdValid(webFingerId)) webFingerId else validUserName)
}
}
}
| 86 | null | 69 | 306 | 6166aded1f115e6e6a7e66ca3756f39f0434663e | 36,570 | andstatus | Apache License 2.0 |
core/src/main/java/com/ttp/core/di/CoreModule.kt | Harrypulvirenti | 267,049,548 | false | null | package com.ttp.core.di
import com.ttp.core.dispatcher.DispatcherProviderImpl
import com.ttp.core.initializer.CoreInitializer
import com.ttp.shared.interfaces.ApplicationBundle
import com.ttp.shared.interfaces.DispatcherProvider
import com.ttp.shared.interfaces.extensions.appInitializer
import org.koin.android.ext.koin.androidContext
import org.koin.core.module.Module
import org.koin.dsl.module
internal fun createCoreModule(isDebug: Boolean): Module = module {
factory { ApplicationBundle(androidContext(), isDebug) }
appInitializer { CoreInitializer(get()) }
single<DispatcherProvider> { DispatcherProviderImpl() }
}
| 0 | null | 1 | 8 | 23c84e068944a69d543dccf6825b6395aa2c8137 | 639 | TimeToPlay | Apache License 2.0 |
library_swutils/src/main/java/com/swensun/swutils/util/UtilContentProvider.kt | yunshuipiao | 186,582,408 | false | {"Kotlin": 344102, "Java": 163601, "HTML": 2189} | package com.swensun.swutils.util
import android.app.Application
import android.content.ContentProvider
import android.content.ContentValues
import android.database.Cursor
import android.net.Uri
import com.swensun.swutils.SwUtils
class UtilContentProvider : ContentProvider() {
override fun query(
uri: Uri,
projection: Array<String>?,
selection: String?,
selectionArgs: Array<String>?,
sortOrder: String?
): Cursor? {
return null
}
override fun onCreate(): Boolean {
SwUtils.init(context as Application)
return true
}
override fun update(uri: Uri, values: ContentValues?, selection: String?, selectionArgs: Array<String>?): Int {
return 0
}
override fun delete(uri: Uri, selection: String?, selectionArgs: Array<String>?): Int {
return 0
}
override fun getType(uri: Uri): String? {
return null
}
override fun insert(uri: Uri, values: ContentValues?): Uri? {
return null
}
}
| 73 | Kotlin | 12 | 75 | 7036458d3b2d7b64730a9fa03f105460560e97fe | 1,029 | Potato | Apache License 2.0 |
src/main/kotlin/com/fiap/selfordermanagement/config/JWTSecurityConfig.kt | FIAP-3SOAT-G15 | 686,372,615 | false | null | package com.fiap.stock.application.config
import io.swagger.v3.oas.annotations.enums.SecuritySchemeType
import io.swagger.v3.oas.annotations.security.SecurityScheme
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty
import org.springframework.context.annotation.Bean
import org.springframework.context.annotation.Configuration
import org.springframework.security.config.annotation.web.builders.HttpSecurity
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity
import org.springframework.security.core.authority.SimpleGrantedAuthority
import org.springframework.security.oauth2.server.resource.authentication.JwtAuthenticationConverter
import org.springframework.security.web.SecurityFilterChain
@Configuration
@EnableWebSecurity
@SecurityScheme(
name = "Bearer Authentication",
type = SecuritySchemeType.HTTP,
bearerFormat = "JWT",
scheme = "bearer"
)
@ConditionalOnProperty(name = ["security.enable"], havingValue = "true", matchIfMissing = true)
class JWTSecurityConfig {
@Bean
fun securityFilterChain(http: HttpSecurity): SecurityFilterChain {
http
.csrf { csrf ->
csrf.disable()
}
.authorizeHttpRequests { authorize ->
authorize.anyRequest().permitAll()
}
.oauth2ResourceServer { oauth2 ->
oauth2.jwt { jwt ->
jwt.jwtAuthenticationConverter(grantedAuthoritiesExtractor())
}
}
return http.build()
}
private fun grantedAuthoritiesExtractor(): JwtAuthenticationConverter {
val jwtAuthenticationConverter = JwtAuthenticationConverter()
jwtAuthenticationConverter.setJwtGrantedAuthoritiesConverter { jwt ->
val list: List<String> = jwt.claims.getOrDefault("cognito:groups", emptyList<String>()) as List<String>
return@setJwtGrantedAuthoritiesConverter list
.map { obj: Any -> obj.toString() }
.map { role -> SimpleGrantedAuthority(role) }
}
return jwtAuthenticationConverter
}
}
| 3 | null | 1 | 4 | 4d88e0bd81de2e83cbf3aa5d3224529adbd25529 | 2,145 | tech-challenge | MIT License |
espresso/CustomTestWatcher.kt | aaron-goff | 377,574,855 | false | null | import org.junit.rules.TestWatcher
import org.junit.runner.Description
class CustomTestWatcher : TestWatcher() {
override fun starting(description: Description) {
}
override fun failed(e: Throwable?, description: Description) {
}
override fun succeeded(description: Description?) {
}
} | 0 | Kotlin | 0 | 0 | fc548d4d2d89f5afa244d821bb7e802b326fa359 | 315 | recipes | Apache License 2.0 |
InjuredAndroid/app/src/main/java/b3nac/injuredandroid/DeepLinkActivity.kt | JarLob | 268,610,835 | true | {"Text": 1, "Ignore List": 3, "Markdown": 2, "Gradle": 3, "XML": 59, "Java Properties": 2, "Shell": 1, "Batchfile": 1, "INI": 2, "JSON": 1, "Proguard": 1, "Java": 31, "Kotlin": 3} | package b3nac.injuredandroid
import android.content.Context
import android.content.Intent
import android.content.SharedPreferences
import android.os.Bundle
import android.util.Log
import android.view.View
import android.widget.EditText
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import com.google.android.material.floatingactionbutton.FloatingActionButton
import com.google.android.material.snackbar.Snackbar
import com.google.firebase.auth.FirebaseAuth
import com.google.firebase.database.DataSnapshot
import com.google.firebase.database.DatabaseError
import com.google.firebase.database.FirebaseDatabase
import com.google.firebase.database.ValueEventListener
class DeepLinkActivity : AppCompatActivity() {
internal var click = 0
private val TAG = "DeepLinkActivity"
private var mAuth: FirebaseAuth? = null
val refDirectory = "/binary"
var database = FirebaseDatabase.getInstance().reference
var childRef = database.child(refDirectory)
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_deep_link)
val intentToUri = getIntent()
val data = intentToUri.data
val appSchema = "flag11" == data!!.getScheme()
if (appSchema) {
//val convertScheme = "https://" + data.host
//startActivity(Intent(Intent.ACTION_VIEW, Uri.parse(convertScheme)))
startActivity(Intent(Intent.ACTION_VIEW))
} else {
startActivity(Intent(Intent.ACTION_VIEW))
}
val fab = findViewById<FloatingActionButton>(R.id.fab)
fab.setOnClickListener { view ->
if (click == 0) {
Snackbar.make(view, "This is one part of the puzzle.", Snackbar.LENGTH_LONG)
.setAction("Action", null).show()
//Figure out how to login anonymously on click
click++
} else if (click == 1) {
Snackbar.make(view, "Find the compiled treasure.", Snackbar.LENGTH_LONG)
.setAction("Action", null).show()
click = 0
}
}
}
fun submitFlag(view: View?) {
val editText5 = findViewById<EditText>(R.id.editText5)
val post = editText5.text.toString()
signInAnonymously()
childRef.addListenerForSingleValueEvent(object : ValueEventListener {
override fun onDataChange(dataSnapshot: DataSnapshot) {
val value = dataSnapshot.value as String?
val settings = getSharedPreferences("b3nac.injuredandroid", Context.MODE_PRIVATE)
Log.e(TAG, value)
if (post == value) {
FlagsOverview.flagElevenButtonColor = true
val editor: SharedPreferences.Editor = settings.edit()
editor.putBoolean("flagElevenButtonColor", true).commit()
correctFlag()
} else {
Toast.makeText(this@DeepLinkActivity, "Try again! :D",
Toast.LENGTH_SHORT).show()
}
}
override fun onCancelled(databaseError: DatabaseError) {
Log.e(TAG, "onCancelled", databaseError.toException())
}
})
}
fun signInAnonymously() {
mAuth = FirebaseAuth.getInstance()
mAuth!!.signInAnonymously()
.addOnCompleteListener(this) { task ->
if (task.isSuccessful) {
Toast.makeText(this@DeepLinkActivity, "Authentication succeeded.",
Toast.LENGTH_SHORT).show()
} else {
Toast.makeText(this@DeepLinkActivity, "Authentication failed.",
Toast.LENGTH_SHORT).show()
}
}
}
fun correctFlag() {
val intent = Intent(this, FlagOneSuccess::class.java)
startActivity(intent)
}
}
| 0 | null | 0 | 2 | 51b57e5e8b64b6da4b907d9b11bbd1239ee1dc03 | 4,063 | InjuredAndroid | Apache License 2.0 |
samples/src/main/java/io/github/staakk/cchart/samples/PopupChart.kt | staakk | 340,637,391 | false | null | package io.github.staakk.cchart.samples
import androidx.compose.foundation.background
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.aspectRatio
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.Surface
import androidx.compose.material.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.geometry.Offset
import androidx.compose.ui.geometry.Size
import androidx.compose.ui.graphics.SolidColor
import androidx.compose.ui.platform.LocalDensity
import androidx.compose.ui.text.ExperimentalTextApi
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import io.github.staakk.cchart.Chart
import io.github.staakk.cchart.data.Data
import io.github.staakk.cchart.data.Series
import io.github.staakk.cchart.data.Viewport
import io.github.staakk.cchart.features
import io.github.staakk.cchart.label.Labels.Companion.horizontalLabels
import io.github.staakk.cchart.label.Labels.Companion.verticalLabels
import io.github.staakk.cchart.axis.Axis
import io.github.staakk.cchart.axis.AxisOrientation
import io.github.staakk.cchart.point.DrawPoints
import io.github.staakk.cchart.style.PrimitiveStyle
@Composable
fun PopupChartScreen() {
@OptIn(ExperimentalTextApi::class)
val labels = arrayOf(
horizontalLabels(),
verticalLabels(),
)
val pointSize = with(LocalDensity.current) { Size(8.dp.toPx(), 8.dp.toPx()) }
val popupPosition = remember { mutableStateOf<Pair<Data<*>, Offset>?>(null)}
Chart(
modifier = Modifier
.padding(start = 32.dp, bottom = 32.dp)
.aspectRatio(1f, false),
viewport = Viewport(0f, 5.5f, 0f, 5.5f),
onClick = { offset, point ->
popupPosition.value = point to offset
}
) {
series(
Series(SampleData.series.take(25).toList()),
DrawPoints(
pointSize,
PrimitiveStyle(brush = SolidColor(Colors.Red)),
)
)
features(
Axis(AxisOrientation.Horizontal, 0.0f),
Axis(AxisOrientation.Vertical, 0.0f),
*labels,
)
popupPosition.value?.let { (point, _) ->
anchor(point) {
Text(
modifier = Modifier
.align(Alignment.Center)
.background(
brush = SolidColor(Colors.LightGreen),
shape = RoundedCornerShape(4.dp),
alpha = 0.5f
)
.clickable { popupPosition.value = null }
.padding(4.dp),
text = "Click to close",
)
}
}
}
}
@Preview
@Composable
fun PopupLineChartScreen() {
Surface {
PopupChartScreen()
}
} | 0 | Kotlin | 2 | 15 | e291c90e120614198a9104cb8c10c5ad8d5ce7c2 | 3,130 | cchart | Apache License 2.0 |
gluecodium/src/main/java/com/here/gluecodium/generator/ffi/FfiNameResolver.kt | Dschoordsch | 237,653,099 | false | {"Gradle": 18, "YAML": 5, "Markdown": 26, "INI": 19, "Batchfile": 5, "Shell": 29, "Text": 4, "Ignore List": 13, "CMake": 35, "XML": 55, "Kotlin": 338, "Java": 210, "Swift": 169, "C++": 338, "C": 46, "Dart": 54, "Mustache": 212, "Java Properties": 2, "ANTLR": 4, "OpenStep Property List": 3, "JSON": 1, "SVG": 4} | /*
* Copyright (C) 2016-2019 HERE Europe B.V.
*
* 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.
*
* SPDX-License-Identifier: Apache-2.0
* License-Filename: LICENSE
*/
package com.here.gluecodium.generator.ffi
import com.here.gluecodium.cli.GluecodiumExecutionException
import com.here.gluecodium.generator.common.NameResolver
import com.here.gluecodium.generator.common.NameRules
import com.here.gluecodium.model.lime.LimeBasicType
import com.here.gluecodium.model.lime.LimeElement
import com.here.gluecodium.model.lime.LimeEnumeration
import com.here.gluecodium.model.lime.LimeFunction
import com.here.gluecodium.model.lime.LimeList
import com.here.gluecodium.model.lime.LimeMap
import com.here.gluecodium.model.lime.LimeNamedElement
import com.here.gluecodium.model.lime.LimeSet
import com.here.gluecodium.model.lime.LimeSignatureResolver
import com.here.gluecodium.model.lime.LimeType
import com.here.gluecodium.model.lime.LimeTypeRef
internal class FfiNameResolver(
private val limeReferenceMap: Map<String, LimeElement>,
private val nameRules: NameRules
) : NameResolver {
private val signatureResolver = FfiSignatureResolver(limeReferenceMap, this)
override fun resolveName(element: Any): String =
when (element) {
is LimeTypeRef -> getTypeRefName(element)
is LimeFunction -> getMangledFullName(element)
is LimeType -> getTypeName(element)
is LimeNamedElement -> nameRules.getName(element)
else ->
throw GluecodiumExecutionException("Unsupported element type ${element.javaClass.name}")
}
private fun getTypeRefName(limeTypeRef: LimeTypeRef): String {
val limeType = limeTypeRef.type.actualType
return when {
limeTypeRef.isNullable -> OPAQUE_HANDLE_TYPE
limeType is LimeBasicType -> getBasicTypeRefName(limeType)
limeType is LimeEnumeration -> "uint32_t"
else -> OPAQUE_HANDLE_TYPE
}
}
private fun getTypeName(limeType: LimeType): String =
when (val actualType = limeType.actualType) {
is LimeList -> getListName(actualType.elementType)
is LimeSet -> getSetName(actualType.elementType)
is LimeMap -> getMapName(actualType.keyType, actualType.valueType)
else -> getMangledFullName(actualType)
}
private fun getBasicTypeRefName(limeType: LimeBasicType) =
when (limeType.typeId) {
LimeBasicType.TypeId.VOID -> "void"
LimeBasicType.TypeId.INT8 -> "int8_t"
LimeBasicType.TypeId.UINT8 -> "uint8_t"
LimeBasicType.TypeId.INT16 -> "int16_t"
LimeBasicType.TypeId.UINT16 -> "uint16_t"
LimeBasicType.TypeId.INT32 -> "int32_t"
LimeBasicType.TypeId.UINT32 -> "uint32_t"
LimeBasicType.TypeId.INT64 -> "int64_t"
LimeBasicType.TypeId.UINT64 -> "uint64_t"
LimeBasicType.TypeId.BOOLEAN -> "bool"
LimeBasicType.TypeId.FLOAT -> "float"
LimeBasicType.TypeId.DOUBLE -> "double"
LimeBasicType.TypeId.STRING -> OPAQUE_HANDLE_TYPE
LimeBasicType.TypeId.BLOB -> OPAQUE_HANDLE_TYPE
LimeBasicType.TypeId.DATE -> "uint64_t"
}
private fun getListName(elementType: LimeTypeRef) = "ListOf_${getTypeName(elementType.type)}"
private fun getSetName(elementType: LimeTypeRef) = "SetOf_${getTypeName(elementType.type)}"
private fun getMapName(keyType: LimeTypeRef, valueType: LimeTypeRef) =
"MapOf_${getTypeName(keyType.type)}_to_${getTypeName(valueType.type)}"
private fun getMangledFullName(limeElement: LimeNamedElement): String {
val prefix = when {
limeElement.path.hasParent -> {
val parentElement =
limeReferenceMap[limeElement.path.parent.toString()] as? LimeNamedElement
?: throw GluecodiumExecutionException(
"Failed to resolve parent for element ${limeElement.fullName}"
)
getMangledFullName(parentElement)
}
limeElement.path.head.isEmpty() -> null
else -> limeElement.path.head.joinToString("_")
}
val mangledName = mangleName(nameRules.getName(limeElement))
val fullName = listOfNotNull(prefix, mangledName).joinToString("_")
return when (limeElement) {
is LimeFunction -> {
val mangledSignature = signatureResolver.getSignature(limeElement)
.joinToString("_") { mangleName(it) }
if (mangledSignature.isEmpty()) fullName else "${fullName}__$mangledSignature"
}
else -> fullName
}
}
private fun mangleName(name: String) =
name.replace(" ", "").replace("_", "_1").replace("<", "Of_").replace(",", "_").replace(">", "")
private class FfiSignatureResolver(
limeReferenceMap: Map<String, LimeElement>,
private val nameResolver: FfiNameResolver
) : LimeSignatureResolver(limeReferenceMap) {
override fun getFunctionName(limeFunction: LimeFunction) =
nameResolver.nameRules.getName(limeFunction)
override fun getArrayName(elementType: LimeTypeRef) = nameResolver.getListName(elementType)
override fun getSetName(elementType: LimeTypeRef) = nameResolver.getSetName(elementType)
override fun getMapName(keyType: LimeTypeRef, valueType: LimeTypeRef) =
nameResolver.getMapName(keyType, valueType)
}
companion object {
private const val OPAQUE_HANDLE_TYPE = "FfiOpaqueHandle"
}
}
| 1 | null | 1 | 1 | a7b3833ce840284cadf968b6f8441888f970c134 | 6,178 | gluecodium | Apache License 2.0 |
app/src/main/java/com/sample/crackingcoroutines/ui/exceptions/ExceptionsViewModel.kt | dahlbergbob | 548,542,826 | false | {"Kotlin": 30523} | package com.sample.crackingcoroutines.ui.exceptions
import androidx.lifecycle.viewModelScope
import com.sample.crackingcoroutines.helpers.BaseViewModel
import com.sample.crackingcoroutines.helpers.Network
import com.sample.crackingcoroutines.helpers.javaClassShort
import kotlinx.coroutines.*
class ExceptionsViewModel : BaseViewModel() {
private val handler = CoroutineExceptionHandler { ctx, exception ->
outp("Handler got ${exception.javaClassShort}")
}
private val customScope = CoroutineScope(
Dispatchers.Default + handler
)
fun exceptionPropagationHierarchy() {
clear("Exceptions")
val job = viewModelScope.launch {
try {
val job1 = launch { delay(600) }
val job2 = launch {
val job2a = launch {
delay(300)
throw Error("Quits")
}
val job2b = launch { delay(800) }
job2a.invokeOnCompletion { outp("2a is ${it?.javaClassShort}") }
job2b.invokeOnCompletion { outp("2b is ${it?.javaClassShort}") }
}
job1.invokeOnCompletion { outp("1 is ${it?.javaClassShort}") }
job2.invokeOnCompletion { outp("2 is ${it?.javaClassShort}") }
}
catch (e:Throwable) {
outp("Handling exception: ${e.javaClassShort}")
}
}
}
// Uncaught exceptions are still uncaught exceptions
// Add handler on scope / not children
fun supervisorJob() {
clear("Exceptions supervisor")
val job = viewModelScope.launch(handler) {
val job1 = launch { delay(600) }
val job2 = launch {
val job2a = launch {
delay(300)
throw Error("Quits")
}
val job2b = launch { delay(800) }
job2a.invokeOnCompletion { outp("2a is ${it?.javaClassShort}") }
job2b.invokeOnCompletion { outp("2b is ${it?.javaClassShort}") }
}
job1.invokeOnCompletion { outp("1 is ${it?.javaClassShort}") }
job2.invokeOnCompletion { outp("2 is ${it?.javaClassShort}") }
}
}
// We can add SupervisorJob() but then we break the structure
// Add supervisorScope
fun tidyingUpSuspending() {
clear("Tidying up suspending")
val job = customScope.launch {
launch {
try {
launch {
delay(800)
outp("throwing")
throw Error("An error")
}.join()
}
catch (e:Throwable) {
outp("needs tidying up suspending..")
val result = Network.suspendingNetworkFetch()
outp("tidied up: $result")
}
}
}
}
// why doesn't suspending work to tidy up?
// withContext(NonCancellable)
fun asyncExceptions() {
clear("Async errors to handlers")
val job = viewModelScope.async {
launch {
try {
launch {
delay(800)
outp("throwing")
throw Error("An error")
}.join()
}
catch (e:Throwable) {
outp("catching")
}
}
}
}
// change back to launch
// called on await
/*
CoroutineScope(handler).launch {
delay(2000)
job.await()
}
*/
} | 0 | Kotlin | 0 | 1 | 52fa51aef959207a72021c95b352fbddc3db7418 | 3,713 | cracking-coroutines-droidcon-it | MIT License |
backend/src/test/kotlin/com/github/davinkevin/podcastserver/service/JdomServiceTest.kt | rrymm | 188,617,315 | true | {"HTML": 20676268, "Kotlin": 946925, "TypeScript": 162734, "JavaScript": 95206, "Java": 76050, "CSS": 26948, "Shell": 5639, "Dockerfile": 3085, "Smarty": 328} | package com.github.davinkevin.podcastserver.service
import com.github.davinkevin.podcastserver.IOUtils
import com.github.davinkevin.podcastserver.entity.*
import com.github.davinkevin.podcastserver.service.properties.PodcastServerParameters
import com.github.tomakehurst.wiremock.WireMockServer
import com.github.tomakehurst.wiremock.client.WireMock
import com.github.tomakehurst.wiremock.client.WireMock.*
import com.github.tomakehurst.wiremock.core.WireMockConfiguration
import com.github.tomakehurst.wiremock.core.WireMockConfiguration.*
import com.nhaarman.mockitokotlin2.whenever
import org.assertj.core.api.Assertions.assertThat
import org.junit.jupiter.api.AfterEach
import org.junit.jupiter.api.BeforeEach
import org.junit.jupiter.api.Test
import org.junit.jupiter.api.extension.ExtendWith
import org.mockito.InjectMocks
import org.mockito.Mock
import org.mockito.Mockito.*
import org.mockito.junit.jupiter.MockitoExtension
import java.net.URISyntaxException
import java.time.ZoneId
import java.time.ZonedDateTime
import java.util.*
/**
* Created by kevin on 08/09/15 for Podcast Server
*/
@ExtendWith(MockitoExtension::class)
class JdomServiceTest {
@Mock lateinit var podcastServerParameters: PodcastServerParameters
@Mock lateinit var mimeTypeService: MimeTypeService
@Mock lateinit var urlService: UrlService
@InjectMocks lateinit var jdomService: JdomService
private val itemId = listOf(
"789CEC3A-72CB-970A-264A-D5B4BF953183",
"374EA8C6-2390-EAB6-51D4-D3F5A8F5E7B7",
"5F6CDA11-24E1-1FC9-8494-17BC9140BC52",
"19508A7E-3588-8999-BAF4-BAD1215E3905",
"BA7AAE7E-EDED-B7A0-578F-87E40CC39946",
"8C352463-83F7-C2AD-355D-5D5741B359D4",
"0FADEB67-3024-9EB3-4DB5-8231B80FDA0F",
"7CD43954-67E6-50C1-BC3C-FE84A01EB007",
"C175E97C-83D9-E4E5-7C2D-8DB98F5624EB",
"37E4DB3C-E1D2-7A40-B438-63DE026C7108",
"28606EB1-DA7F-6BA2-20A3-6AAD64C6CA9D",
"C24B4DD3-DBE6-76B2-22AA-580D2515184C",
"6866C5CE-2DAF-F618-EBD4-18EFE49F7F83",
"D935B07E-34A9-ECFF-7105-9B0E07804593",
"8F717FAB-F672-A7D5-22AD-D961797B1571",
"05F62DD4-E345-3EEB-3E31-5A8A50A85175",
"A60CCE2C-1F9C-47BE-B06B-04065D96F551",
"655E53DB-0123-76D7-EB46-24A11A20FAB9",
"5642AD48-DB22-0C7E-32CA-865E83D58E48",
"2C2C2AD9-5A84-807B-81AF-55378B534B71",
"31B8DC7E-2776-EA51-337F-C1D6CC834D3C",
"C61CED6B-B4B0-9DC4-8250-B2FC970C2347",
"16965687-7681-A69F-E63F-D10CABA71289",
"BF6D3EFA-249F-318F-DAED-C98B4691374F",
"8921F70B-076C-C3A1-C4F9-575C4002B46C",
"EAAF0622-7666-7C56-3900-397F7C28F9A3",
"81B81969-9EE0-2096-7CAF-351CAE861FB2",
"1274A1DC-2FBC-0F23-1A74-04ACFEB0A1C4",
"0E6A7771-43A6-3AD8-0D32-CF310B51FC99",
"49B6CD3E-B753-54A9-F8AA-2328B2CCC5EE",
"B6A65D53-481A-2FA0-224A-1D2180E6A44B",
"80F5216A-523F-F44C-1AAF-05E691B129A9",
"F6EE0A71-4E72-145A-118B-CD50BB4F20E6",
"F0815CD5-8BAE-F606-7A21-1D8D78A24890",
"770FFB9C-B574-71E0-9A45-6D28C13EA6B3",
"A3A854AD-14F7-4AF0-C8DB-F87B1B907BD1",
"EDED32E2-1873-A6DF-ABF5-A807F4B952EF",
"5A685870-5983-6EB3-C4BE-3E6C9A060344",
"45C729EA-D07C-D432-903D-BA960F2C0138",
"4E678F7A-8BDD-EDDB-D2F4-9889E8812E31",
"8CA49DF0-74CF-46EA-AE40-31DCACC8343B",
"BAF6400A-86B7-26A3-0D15-3F4114FB6480",
"5F7FBD82-6193-C4A4-BE0C-A80D183EF71B",
"E89DD657-E0E7-22C1-182A-15C08E27CF2A",
"3ADA3D16-2532-23C0-A759-D40536971C84",
"76E6E670-DB1B-EBFA-00AF-C265FE190D2F",
"D4B4486D-9922-0803-9FD4-CECDFDADB404",
"233015A5-5DC0-5F27-833B-443FDEE78814",
"29E10DE5-7923-38F7-F344-D18EA3098E35",
"D5A8B94E-F3F8-3139-AA01-1EE1B87C994B",
"4E39FF2E-C38A-73E7-C149-80CE8FD04C30",
"EB2D2D61-B866-6F1E-38FB-DC7B7765AC9B",
"7A55E4C6-1292-7B88-7F5B-C298C122C080",
"C0226B7C-5DCF-CADC-1A57-A587BFB6A01D",
"E467ACEA-49B3-B1FD-E896-E36E9EDC0B27",
"E79FD812-CC75-F6E4-FE28-662C7D5DD2AB",
"AB018AC3-7AD1-2CE5-B2ED-2C1D31D5F81D",
"AF733DBB-A729-2249-EAD2-6D54D19A6649",
"33C6F564-4381-9A7F-90A4-AF170FB6C48B",
"7892B60C-3853-BD01-523F-771C035DCA2B",
"F60F9886-493A-1BBC-8309-D4C2059A7F16",
"61DC083F-72DF-2BA7-617F-EB0836B9A2FD",
"154B9A56-4837-47A8-BD9F-95460762CA2A",
"B7429E88-9DAA-7414-70DD-401C80A91277",
"1DD0FE7E-D68E-337A-CCF5-A0EA91B92DBB",
"ACC012B1-52EF-3C3C-79C3-A8158FE91956",
"3A661F7E-6B60-5C5E-FBFE-DBFC3A6DB929",
"CEFF6A05-BB29-B6EA-FD72-91C4FDAA80C6",
"C3EA327B-9B18-F6C3-2957-5A2C59DBAF7C",
"C096FC76-2E2E-91B3-68C1-FCC0C3695103",
"E73F450A-3E8A-B1D8-66F2-AAC2FD11F554",
"EF03ABAE-71F6-5BDC-925B-FC133400EF83",
"104D571B-B51E-A8ED-B467-3FA12799F2A8",
"3FB96AD3-A7D9-D507-BC8B-7DCBCFC70276",
"1F05E6A7-C7AB-B4D1-2EAB-4D96196E869C",
"C435D004-1CAD-0593-3D9A-E68F84973A59",
"9201E321-A8F7-4BD2-0681-FE2C63870E46",
"09E90274-403C-5C90-1254-229620D3401C",
"B20EAADC-B340-164C-BBFF-AA86106AA437",
"C3303127-5051-7343-6611-8C2B46197A08",
"C9F2B71E-C55C-3C39-796A-A839990A3391",
"41607B69-36AE-8219-2849-8012214A51FD",
"E05AB24E-3FBB-D34A-8EE7-E1BC4C72F773",
"FB887C66-3DC0-494D-C098-BE92539D50FA",
"65C633AE-9C92-96BF-F934-9B14CD7D179F",
"2A7FA7C4-44B4-6F78-7CAF-A95107BCD426",
"C7791472-F0F0-A856-7517-22F410131D8E",
"E5FEE21A-B7D2-8D72-75B1-E2BCD07D17D5",
"B974A2CF-1FAA-E6A0-106C-759CDAAF7E0F",
"65FEB3E5-3927-D930-C9B7-F3675A985EE6",
"55F7DE3F-D43B-CC07-6A59-5BCBB71AE693",
"372A81E1-1C7D-0B1F-CF23-E19E4C7B56F8",
"24F51D1F-1696-E68E-40C1-84034C2238F2",
"AF22D788-B903-09EC-699C-CEB963535B26",
"162DC965-3C11-1528-6DD0-5216CC8A8B29",
"46E45CF6-E978-1F13-5D67-7358E1000A0E",
"3B82BEE4-7ABE-6272-6861-8F26BE670055",
"CA3B7E39-58FD-FE7D-524A-3D743AB1469D",
"EDB9627B-F120-EE05-CAE6-1BA28F437D55",
"62927825-88E7-B99B-338E-4847D8B4142F"
)
val wireMockServer: WireMockServer = WireMockServer(wireMockConfig().port(8282))
@BeforeEach
fun beforeEach() {
wireMockServer.start()
WireMock.configureFor("localhost", 8282)
}
@AfterEach
fun afterEach() = wireMockServer.stop()
@Test
fun `should parse`() {
/* Given */
val url = "http://localhost:8282/a/valid.xml"
whenever(urlService.asStream(anyString())).then { i -> IOUtils.urlAsStream(i.getArgument(0)) }
stubFor(get(urlEqualTo("/a/valid.xml"))
.willReturn(aResponse()
.withStatus(200)
.withBodyFile("service/jdomService/valid.xml")))
/* When */
val document = jdomService.parse(url)
/* Then */
assertThat(document.isDefined).isTrue()
verify(urlService, only()).asStream(url)
}
@Test
fun `should generate xml from podcast with only 50 items`() {
/* Given */
whenever(podcastServerParameters.rssDefaultNumberItem).thenReturn(50L)
val podcast = Podcast().apply {
id = UUID.fromString("029d7820-b7e1-4c0f-a94f-235584ffb570")
title = "FakePodcast"
description = "<NAME>"
hasToBeDeleted = true
cover = Cover().apply { height = 200; width = 200; url = "http://fake.url/1234/cover.png" }
tags = setOf(Tag().apply { name = "Open-Source" })
signature = "123456789"
lastUpdate = ZonedDateTime.of(2015, 9, 8, 7, 0, 0, 0, ZoneId.of("Europe/Paris"))
items = generateItems(this, 100)
}
/* When */
val xml = jdomService.podcastToXMLGeneric(podcast, "http://localhost", true)
/* Then */
assertThat(xml).isXmlEqualToContentOf(IOUtils.get("/xml/podcast.output.50.xml").toFile())
}
@Test
fun `should generate xml from podcast with only all items`() {
/* Given */
val podcast = Podcast().apply {
id = UUID.fromString("214be5e3-a9e0-4814-8ee1-c9b7986bac82")
title = "FakePodcast"
description = "<NAME>"
hasToBeDeleted = true
cover = Cover().apply { height = 200; width = 200; url = "/1234/cover.png" }
tags = setOf(Tag().apply { name = "Open-Source" })
signature = "123456789"
lastUpdate = ZonedDateTime.of(2015, 9, 8, 7, 0, 0, 0, ZoneId.of("Europe/Paris"))
items = generateItems(this, 100)
}
/* When */
val xml = jdomService.podcastToXMLGeneric(podcast, "http://localhost", false)
/* Then */
assertThat(xml).isXmlEqualToContentOf(IOUtils.get("/xml/podcast.output.100.xml").toFile())
}
@Test
@Throws(URISyntaxException::class)
fun `should generate xml from watch list`() {
/* Given */
val podcastOne = Podcast().apply {
id = UUID.fromString("029d7820-b7e1-4c0f-a94f-235584ffb570")
title = "FakePodcast_1"
cover = Cover().apply { height = 200; width = 200; url = "http://fake.url/1234/cover.png" }
signature = "123456789"
lastUpdate = ZonedDateTime.of(2015, 9, 8, 7, 0, 0, 0, ZoneId.of("Europe/Paris"))
}
val podcastTwo = Podcast().apply {
id = UUID.fromString("526d5187-0563-4c44-801f-3bea447a86ea")
title = "FakePodcast_2"
cover = Cover().apply { height = 200; width = 200; url = "http://fake.url/1234/cover.png" }
signature = "987654321"
lastUpdate = ZonedDateTime.of(2015, 9, 8, 7, 0, 0, 0, ZoneId.of("Europe/Paris"))
}
val watchList = WatchList().apply {
id = UUID.fromString("c988babd-a2b1-4774-b8f8-fa4903dc3786")
name = "A custom WatchList"
items = (generateItems(podcastOne, 10) + (generateItems(podcastTwo, 20))).toMutableSet()
}
/* When */
val xml = jdomService.watchListToXml(watchList, "http://localhost")
/* Then */
assertThat(xml).isXmlEqualToContentOf(IOUtils.get("/xml/watchlist.output.xml").toFile())
}
@Test
fun `should generate opml from podcasts`() {
/* GIVEN */
val foo = Podcast().apply {
id = UUID.fromString("05F62DD4-E345-3EEB-3E31-5A8A50A85175")
title = "Foo"
description = "DescFoo"
}
val bar = Podcast().apply {
id = UUID.fromString("C24B4DD3-DBE6-76B2-22AA-580D2515184C")
title = "Bar"
description = "DescBar"
}
val last = Podcast().apply {
id = UUID.fromString("EDB9627B-F120-EE05-CAE6-1BA28F437D55")
title = "last"
description = "Desc Last"
}
/* WHEN */
val opml = jdomService.podcastsToOpml(listOf(foo, bar, last), "http://fake.url/")
/* THEN */
assertThat(opml).isEqualToIgnoringWhitespace(
"""<?xml version="1.0" encoding="UTF-8"?>
<opml version="2.0">
<head>
<title>Podcast-Server</title>
</head>
<body>
<outline text="Bar" description="DescBar" htmlUrl="http://fake.url//podcasts/c24b4dd3-dbe6-76b2-22aa-580d2515184c" title="Bar" type="rss" version="RSS2" xmlUrl="http://fake.url//api/podcasts/c24b4dd3-dbe6-76b2-22aa-580d2515184c/rss" />
<outline text="Foo" description="DescFoo" htmlUrl="http://fake.url//podcasts/05f62dd4-e345-3eeb-3e31-5a8a50a85175" title="Foo" type="rss" version="RSS2" xmlUrl="http://fake.url//api/podcasts/05f62dd4-e345-3eeb-3e31-5a8a50a85175/rss" />
<outline text="last" description="Desc Last" htmlUrl="http://fake.url//podcasts/edb9627b-f120-ee05-cae6-1ba28f437d55" title="last" type="rss" version="RSS2" xmlUrl="http://fake.url//api/podcasts/edb9627b-f120-ee05-cae6-1ba28f437d55/rss" />
</body>
</opml>""")
}
private fun generateItems(p: Podcast, limit: Int): MutableSet<Item> =
(0 until limit)
.map {
Item().apply {
id = UUID.fromString(itemId[it])
fileName = "name$it"
cover = Cover().apply {
height = 200
width = 200
url = "http://fake.url/1234/items/" + itemId[it] + "/cover.png"
}
url = "http://fake.url/1234/items/" + itemId[it] + "/item.mp4"
title = "name$it"
description = "$it Loren Ipsum"
downloadDate = ZonedDateTime.of(2015, 9, 8, 7, 0, 0, 0, ZoneId.of("Europe/Paris"))
length = it * 1024L
localUri = "http://fake.url/1234/items/${itemId[it]}/item.mp4"
mimeType = "video/mp4"
podcast = p
pubDate = ZonedDateTime.of(2015, 9, 8, 7, 0, 0, 0, ZoneId.of("Europe/Paris")).minusDays(it.toLong())
status = Status.FINISH
}
}.toMutableSet()
}
| 0 | HTML | 0 | 0 | 65533e8c266cdd929fa199f0d53a60117641199e | 13,958 | Podcast-Server | Apache License 2.0 |
kotlin-mui-icons/src/main/generated/mui/icons/material/ScannerOutlined.kt | JetBrains | 93,250,841 | false | null | // Automatically generated - do not modify!
@file:JsModule("@mui/icons-material/ScannerOutlined")
@file:JsNonModule
package mui.icons.material
@JsName("default")
external val ScannerOutlined: SvgIconComponent
| 12 | null | 5 | 983 | 372c0e4bdf95ba2341eda473d2e9260a5dd47d3b | 212 | kotlin-wrappers | Apache License 2.0 |
repository/src/main/java/com/ferelin/repository/converter/helpers/searchRequestsConverter/SearchRequestsConverter.kt | sarath940 | 391,107,525 | true | {"Kotlin": 768543} | /*
* Copyright 2021 Leah Nichita
*
* 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.ferelin.repository.converter.helpers.searchRequestsConverter
import com.ferelin.local.models.SearchRequest
import com.ferelin.remote.base.BaseResponse
import com.ferelin.repository.adaptiveModels.AdaptiveSearchRequest
import com.ferelin.repository.utils.RepositoryResponse
/**
* [SearchRequestsConverter] provides converters for searchRequest model
* */
interface SearchRequestsConverter {
fun convertAdaptiveRequestToRequest(searchRequest: AdaptiveSearchRequest) : SearchRequest
fun convertLocalRequestsResponseToAdaptiveRequests(
searchRequests: List<SearchRequest>
): List<AdaptiveSearchRequest>
fun convertNetworkRequestsResponseToRepositoryResponse(
response: BaseResponse<HashMap<Int, String>>?
): RepositoryResponse<List<AdaptiveSearchRequest>>
} | 0 | null | 0 | 0 | 2c0e4b045786fdf4b4d51bf890a3dbf0cd8099d1 | 1,406 | Android_Stock_Price | Apache License 2.0 |
cottontaildb-dbms/src/main/kotlin/org/vitrivr/cottontail/storage/serializers/values/xodus/BooleanValueXodusBinding.kt | vitrivr | 160,775,368 | false | {"Kotlin": 2317843, "Dockerfile": 548} | package org.vitrivr.cottontail.storage.serializers.values.xodus
import jetbrains.exodus.ByteIterable
import jetbrains.exodus.bindings.BooleanBinding
import jetbrains.exodus.bindings.ByteBinding
import org.vitrivr.cottontail.core.values.BooleanValue
import org.vitrivr.cottontail.core.values.types.Types
/**
* A [XodusBinding] for [BooleanValue] serialization and deserialization.
*
* @author <NAME>
* @version 1.0.0
*/
sealed class BooleanValueXodusBinding: XodusBinding<BooleanValue> {
override val type = Types.Boolean
/**
* [BooleanValueXodusBinding] used for non-nullable values.
*/
object NonNullable: BooleanValueXodusBinding() {
override fun entryToValue(entry: ByteIterable): BooleanValue = BooleanValue(BooleanBinding.entryToBoolean(entry))
override fun valueToEntry(value: BooleanValue?): ByteIterable {
require(value != null) { "Serialization error: Value cannot be null." }
return BooleanBinding.booleanToEntry(value.value)
}
}
/**
* [BooleanValueXodusBinding] used for nullable values.
*/
object Nullable: BooleanValueXodusBinding() {
private val NULL_VALUE = ByteBinding.byteToEntry(Byte.MIN_VALUE)
override fun entryToValue(entry: ByteIterable): BooleanValue? {
if (entry == NULL_VALUE) return null
return BooleanValue(BooleanBinding.entryToBoolean(entry))
}
override fun valueToEntry(value: BooleanValue?): ByteIterable {
if (value == null) return NULL_VALUE
return BooleanBinding.booleanToEntry(value.value)
}
}
} | 16 | Kotlin | 18 | 26 | 50cc8526952f637d685da9d18f4b1630b782f1ff | 1,623 | cottontaildb | MIT License |
src/jsMain/kotlin/materialui/types.kt | baaahs | 174,897,412 | false | null | package materialui
import baaahs.ui.Icon
import mui.icons.material.SvgIconComponent
import react.RBuilder
import react.create
fun RBuilder.icon(icon: Icon) = child(icon.getReactIcon().create())
fun RBuilder.icon(icon: SvgIconComponent) = child(icon.create())
//fun Theme.createTransition(vararg props: String, options: Transitions): kotlinx.css.properties.Transitions =
// transitions.create(props, options) | 82 | Kotlin | 5 | 24 | 01aa9e9530ff9acbada165a2d7048c4ad67ed74f | 413 | sparklemotion | MIT License |
vendor/vendor-android/base/src/main/kotlin/com/malinskiy/marathon/android/RemoteFileManager.kt | badoo | 251,365,845 | true | {"Kotlin": 530071, "JavaScript": 41573, "SCSS": 27631, "HTML": 2925, "Shell": 2350, "CSS": 1662} | package com.malinskiy.marathon.android
import com.malinskiy.marathon.test.Test
import java.io.File
import java.io.IOException
class RemoteFileManager(private val device: AndroidDevice) {
private val tempDir = "/data/local/tmp"
fun pullFile(remoteFilePath: String, localFile: File) {
device.pullFile(remoteFilePath, localFile.absolutePath)
}
fun pullFromFilesDir(applicationId: String, remoteDir: String, localDir: File) {
val files = device.safeExecuteShellCommand(
command = "run-as $applicationId find $remoteDir -type f"
).trimIndent().lines()
if (files.isNotEmpty()) {
val archiveFile = localDir.resolve("$applicationId.tar.gz")
val remoteArchiveFile = "$tempDir/${archiveFile.name}"
device.executeCommand(
command = "touch $remoteArchiveFile",
errorMessage = "Failed to create empty file $remoteArchiveFile"
)
device.executeCommand(
command = "run-as $applicationId sh -c \"cd $remoteDir && tar -czf $remoteArchiveFile *\"",
errorMessage = "Failed to archive files"
)
device.pullFile(remoteArchiveFile, archiveFile.absolutePath)
device.executeCommand(
command = "rm $remoteArchiveFile",
errorMessage = "Failed to delete temporary file $remoteArchiveFile"
)
untar(archiveFile, localDir)
}
}
fun remove(remotePath: String) {
device.executeCommand(
command = "rm -r $remotePath",
errorMessage = "Failed to delete $remotePath"
)
}
fun removeFromFilesDir(applicationId: String, remotePath: String) {
device.executeCommand(
command = "run-as $applicationId rm -r $remotePath",
errorMessage = "Failed to delete $remotePath"
)
}
fun remoteVideoForTest(test: Test): String {
val fileName = "${test.pkg}.${test.clazz}-${test.method}.mp4"
return "${device.getExternalStorageMount()}/$fileName"
}
fun getScreenshotsDir(applicationId: String): String =
"${getFilesDir(applicationId)}/screenshots/default"
private fun getFilesDir(applicationId: String): String =
"/data/data/$applicationId/files"
private fun untar(archive: File, destination: File) {
val process = ProcessBuilder()
.command("tar", "-xzf", archive.absolutePath)
.directory(destination)
.start()
if (process.waitFor() != 0) {
throw IOException("Failed to extract archive $archive to $destination")
}
}
}
| 1 | Kotlin | 6 | 1 | e07de46f42f42e7b0a335bc1f81682deaa769288 | 2,685 | marathon | Apache License 2.0 |
android/versioned-abis/expoview-abi48_0_0/src/main/java/abi48_0_0/expo/modules/videothumbnails/Exceptions.kt | betomoedano | 462,599,485 | true | {"TypeScript": 7804102, "Kotlin": 3383974, "Objective-C": 2722124, "Swift": 1723956, "Java": 1686584, "JavaScript": 847793, "C++": 310224, "C": 237463, "Objective-C++": 191888, "Ruby": 167983, "Shell": 59271, "HTML": 31107, "CMake": 25754, "Batchfile": 89, "CSS": 42} | package abi49_0_0.expo.modules.videothumbnails
import abi49_0_0.expo.modules.kotlin.exception.CodedException
class ThumbnailFileException :
CodedException("Can't read file")
class GenerateThumbnailException :
CodedException("Could not generate thumbnail")
class FilePermissionsModuleNotFound :
CodedException("File permissions module not found")
| 627 | TypeScript | 4443 | 4 | 52d6405570a39a87149648d045d91098374f4423 | 356 | expo | MIT License |
gluecodium/src/test/java/com/here/gluecodium/generator/jni/JniModelBuilderTest.kt | Dschoordsch | 237,653,099 | false | null | /*
* Copyright (C) 2016-2019 HERE Europe B.V.
*
* 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.
*
* SPDX-License-Identifier: Apache-2.0
* License-Filename: LICENSE
*/
package com.here.gluecodium.generator.jni
import com.here.gluecodium.generator.cpp.CppIncludeResolver
import com.here.gluecodium.generator.cpp.CppModelBuilder
import com.here.gluecodium.generator.java.JavaModelBuilder
import com.here.gluecodium.generator.java.JavaSignatureResolver
import com.here.gluecodium.model.common.Comments
import com.here.gluecodium.model.common.Include
import com.here.gluecodium.model.cpp.CppClass
import com.here.gluecodium.model.cpp.CppComplexTypeRef
import com.here.gluecodium.model.cpp.CppEnum
import com.here.gluecodium.model.cpp.CppEnumItem
import com.here.gluecodium.model.cpp.CppField
import com.here.gluecodium.model.cpp.CppMethod
import com.here.gluecodium.model.cpp.CppParameter
import com.here.gluecodium.model.cpp.CppPrimitiveTypeRef
import com.here.gluecodium.model.cpp.CppStruct
import com.here.gluecodium.model.cpp.CppValue
import com.here.gluecodium.model.java.JavaClass
import com.here.gluecodium.model.java.JavaCustomTypeRef
import com.here.gluecodium.model.java.JavaEnum
import com.here.gluecodium.model.java.JavaEnumItem
import com.here.gluecodium.model.java.JavaExceptionTypeRef
import com.here.gluecodium.model.java.JavaField
import com.here.gluecodium.model.java.JavaImport
import com.here.gluecodium.model.java.JavaInterface
import com.here.gluecodium.model.java.JavaMethod
import com.here.gluecodium.model.java.JavaPackage
import com.here.gluecodium.model.java.JavaParameter
import com.here.gluecodium.model.java.JavaPrimitiveTypeRef
import com.here.gluecodium.model.java.JavaTopLevelElement
import com.here.gluecodium.model.java.JavaValue
import com.here.gluecodium.model.java.JavaVisibility
import com.here.gluecodium.model.jni.JniContainer
import com.here.gluecodium.model.jni.JniElement
import com.here.gluecodium.model.jni.JniEnum
import com.here.gluecodium.model.jni.JniEnumerator
import com.here.gluecodium.model.jni.JniField
import com.here.gluecodium.model.jni.JniMethod
import com.here.gluecodium.model.jni.JniParameter
import com.here.gluecodium.model.jni.JniStruct
import com.here.gluecodium.model.jni.JniType
import com.here.gluecodium.model.lime.LimeAttributeType
import com.here.gluecodium.model.lime.LimeAttributes
import com.here.gluecodium.model.lime.LimeBasicTypeRef
import com.here.gluecodium.model.lime.LimeClass
import com.here.gluecodium.model.lime.LimeDirectTypeRef
import com.here.gluecodium.model.lime.LimeEnumeration
import com.here.gluecodium.model.lime.LimeEnumerator
import com.here.gluecodium.model.lime.LimeException
import com.here.gluecodium.model.lime.LimeField
import com.here.gluecodium.model.lime.LimeFunction
import com.here.gluecodium.model.lime.LimeInterface
import com.here.gluecodium.model.lime.LimeLazyTypeRef
import com.here.gluecodium.model.lime.LimeParameter
import com.here.gluecodium.model.lime.LimePath
import com.here.gluecodium.model.lime.LimePath.Companion.EMPTY_PATH
import com.here.gluecodium.model.lime.LimeProperty
import com.here.gluecodium.model.lime.LimeStruct
import com.here.gluecodium.model.lime.LimeThrownType
import com.here.gluecodium.model.lime.LimeTypesCollection
import com.here.gluecodium.test.AssertHelpers.assertContains
import com.here.gluecodium.test.MockContextStack
import io.mockk.MockKAnnotations
import io.mockk.every
import io.mockk.impl.annotations.MockK
import org.junit.Assert.assertEquals
import org.junit.Assert.assertFalse
import org.junit.Assert.assertNotNull
import org.junit.Assert.assertTrue
import org.junit.Before
import org.junit.Test
import org.junit.runner.RunWith
import org.junit.runners.JUnit4
@RunWith(JUnit4::class)
class JniModelBuilderTest {
@MockK private lateinit var javaBuilder: JavaModelBuilder
@MockK private lateinit var javaSignatureResolver: JavaSignatureResolver
@MockK private lateinit var cppBuilder: CppModelBuilder
@MockK private lateinit var cppIncludeResolver: CppIncludeResolver
private val javaMethodName = "fancyMEthoD_integer"
private val mangledMethodName = "fancyMEthoD_1integer"
private val javaMethod = JavaMethod(
name = javaMethodName,
returnType = JavaPrimitiveTypeRef.INT,
parameters = listOf(JavaParameter("theParam", JavaPrimitiveTypeRef.INT))
)
private val cppMethod = CppMethod(
name = "cPpWork3R_iNt",
fullyQualifiedName = "cPpWork3R_iNt",
returnType = CppPrimitiveTypeRef.INT8,
parameters = listOf(CppParameter("", CppPrimitiveTypeRef.INT8))
)
private val javaClassName = "jAvaClazz"
private val javaClass = JavaClass(javaClassName)
private val cppClass = CppClass("cPpClass", "::cPpClass")
private val javaEnum = JavaEnum("jAvaClazz")
private val cppEnum = CppEnum("cPpClass", "::cPpClass", emptyList(), false, emptyList())
private val javaCustomType = JavaCustomTypeRef("jAvaClazz")
private val javaField = JavaField("theParam", javaCustomType, JavaValue(""))
private val cppCustomType = CppComplexTypeRef("cPpClass")
private val cppField = CppField("cPpClass", "neSTed::cPpClass", cppCustomType)
private val jniParameter = JniParameter("theParam", JniType.VOID)
private val javaGetter =
JavaMethod("getFoo", Comments(), JavaVisibility.PUBLIC, JavaCustomTypeRef("FooType"))
private val cppGetter =
CppMethod("shootFoot", "shootFoot", Comments(), CppPrimitiveTypeRef.INT32)
private val javaSetter = JavaMethod(
name = "setFoo",
visibility = JavaVisibility.PUBLIC,
returnType = JavaPrimitiveTypeRef.VOID,
parameters = listOf(JavaParameter("value", JavaPrimitiveTypeRef.INT))
)
private val cppSetter = CppMethod(
name = "shootBothFeet",
fullyQualifiedName = "shootBothFeet",
parameters = listOf(CppParameter("value", CppPrimitiveTypeRef.INT8))
)
private val jniType = JniType(javaCustomType, cppCustomType)
private val cppInclude = Include.createInternalInclude("Foo.h")
private val cppStruct = CppStruct("cPpClass")
private val transientModel = mutableListOf<JniContainer>()
private val fooPath = LimePath(listOf("foo", "bar"), emptyList())
private val limeMethod = LimeFunction(EMPTY_PATH)
private val limeTypeCollection = LimeTypesCollection(EMPTY_PATH)
private val limeInterface = LimeInterface(fooPath)
private val limeTypeRef = LimeLazyTypeRef("", emptyMap())
private val limeStruct = LimeStruct(EMPTY_PATH)
private val limeEnum = LimeEnumeration(EMPTY_PATH)
private val limeParameter = LimeParameter(EMPTY_PATH, typeRef = LimeBasicTypeRef.INT)
private val limeSetter = LimeFunction(EMPTY_PATH, parameters = listOf(limeParameter))
private val limeProperty = LimeProperty(
EMPTY_PATH,
typeRef = limeTypeRef,
getter = LimeFunction(EMPTY_PATH),
setter = limeSetter
)
private val contextStack = MockContextStack<JniElement>()
private lateinit var modelBuilder: JniModelBuilder
@Before
fun setUp() {
MockKAnnotations.init(this, relaxed = true)
modelBuilder = JniModelBuilder(
contextStack = contextStack,
javaBuilder = javaBuilder,
javaSignatureResolver = javaSignatureResolver,
cppBuilder = cppBuilder,
cppIncludeResolver = cppIncludeResolver,
internalNamespace = INTERNAL_NAMESPACE,
buildTransientModel = { transientModel }
)
javaClass.javaPackage = JavaPackage(listOf("my", "java", "test"))
every { cppIncludeResolver.resolveIncludes(any()) } returns listOf(cppInclude)
every { javaBuilder.getFinalResult(JavaTopLevelElement::class.java) } returns javaClass
every { javaBuilder.getFinalResult(JavaClass::class.java) } returns javaClass
every { cppBuilder.getFinalResult(CppClass::class.java) } returns cppClass
every { javaBuilder.getFinalResult(JavaMethod::class.java) } returns javaMethod
every { cppBuilder.getFinalResult(CppMethod::class.java) } returns cppMethod
every { cppBuilder.getFinalResult(CppStruct::class.java) } returns cppStruct
every { javaBuilder.getFinalResult(JavaField::class.java) } returns javaField
every { cppBuilder.getFinalResult(CppField::class.java) } returns cppField
every { javaBuilder.getFinalResult(JavaEnum::class.java) } returns javaEnum
every { cppBuilder.getFinalResult(CppEnum::class.java) } returns cppEnum
every { javaBuilder.finalResults } returns listOf(javaGetter, javaSetter)
every { cppBuilder.finalResults } returns listOf(cppGetter, cppSetter)
}
@Test
fun finishBuildingTypeCollectionReadsStructs() {
val limeElement = LimeTypesCollection(EMPTY_PATH)
val jniStruct = JniStruct(javaClass.name, "cPpClass", javaClass.javaPackage)
contextStack.injectResult(jniStruct)
modelBuilder.finishBuilding(limeElement)
val jniContainer = modelBuilder.getFinalResult(JniContainer::class.java)
assertEquals(jniStruct.javaClass, jniContainer.structs.first().javaClass)
assertEquals(emptyList<String>(), jniContainer.cppNameSpaces)
assertEquals(INTERNAL_NAMESPACE, jniContainer.internalNamespace)
}
@Test
fun finishBuildingTypeCollectionReadsTypeIncludes() {
val limeElement = LimeTypesCollection(EMPTY_PATH, structs = listOf(limeStruct))
modelBuilder.finishBuilding(limeElement)
val jniContainer = modelBuilder.getFinalResult(JniContainer::class.java)
assertEquals(1, jniContainer.includes.size)
assertContains(cppInclude, jniContainer.includes)
}
@Test
fun finishBuildingTypeCollectionReadsEnums() {
val jniEnum = JniEnum("MyJavaEnumName", "MyCppEnumName", JavaPackage.DEFAULT)
contextStack.injectResult(jniEnum)
modelBuilder.finishBuilding(limeTypeCollection)
val jniContainer = modelBuilder.getFinalResult(JniContainer::class.java)
assertContains(jniEnum, jniContainer.enums)
}
@Test
fun finishBuildingClass() {
val limeElement = LimeClass(EMPTY_PATH)
modelBuilder.finishBuilding(limeElement)
val jniContainer = modelBuilder.getFinalResult(JniContainer::class.java)
assertEquals(JniContainer.ContainerType.CLASS, jniContainer.containerType)
}
@Test
fun finishBuildingInterface() {
modelBuilder.finishBuilding(limeInterface)
val jniContainer = modelBuilder.getFinalResult(JniContainer::class.java)
assertEquals(JniContainer.ContainerType.INTERFACE, jniContainer.containerType)
assertEquals("cPpClass", jniContainer.cppName)
assertEquals("jAvaClazz", jniContainer.javaNames.first())
assertEquals(listOf("foo", "bar"), jniContainer.cppNameSpaces)
assertEquals(listOf("my", "java", "test"), jniContainer.javaPackage.packageNames)
assertEquals(INTERNAL_NAMESPACE, jniContainer.internalNamespace)
}
@Test
fun finishBuildingInterfaceReadsJavaInterface() {
val javaInterface = JavaInterface("javaFAce")
javaInterface.javaPackage = JavaPackage(listOf("my", "java", "test"))
every { javaBuilder.getFinalResult(JavaTopLevelElement::class.java) } returns javaInterface
modelBuilder.finishBuilding(limeInterface)
val jniContainer = modelBuilder.getFinalResult(JniContainer::class.java)
assertEquals("javaFAce", jniContainer.javaInterfaceNames.first())
}
@Test
fun finishBuildingInterfaceReadsParentMethods() {
val parentContainer = JniContainer()
parentContainer.parentMethods.add(JniMethod())
parentContainer.methods.add(JniMethod())
transientModel += parentContainer
val limeElement = LimeInterface(fooPath, parent = LimeBasicTypeRef.INT)
modelBuilder.finishBuilding(limeElement)
val jniContainer = modelBuilder.getFinalResult(JniContainer::class.java)
assertEquals(2, jniContainer.parentMethods.size)
}
@Test
fun finishBuildingInterfaceReadsInterfaceInclude() {
modelBuilder.finishBuilding(limeInterface)
val jniContainer = modelBuilder.getFinalResult(JniContainer::class.java)
assertEquals(1, jniContainer.includes.size)
assertContains(cppInclude, jniContainer.includes)
}
@Test
fun finishBuildingInterfaceReadsTypeIncludes() {
val limeElement = LimeInterface(
LimePath(listOf("foo", "bar"), emptyList()),
structs = listOf(limeStruct)
)
val cppStructInclude = Include.createInternalInclude("Foo")
every { cppIncludeResolver.resolveIncludes(limeStruct) } returns listOf(cppStructInclude)
modelBuilder.finishBuilding(limeElement)
val jniContainer = modelBuilder.getFinalResult(JniContainer::class.java)
assertEquals(2, jniContainer.includes.size.toLong())
assertContains(cppStructInclude, jniContainer.includes)
}
@Test
fun finishBuildingInterfaceReadsEnums() {
val jniEnum = JniEnum("MyJavaEnumName", "MyCppEnumName", JavaPackage.DEFAULT)
contextStack.injectResult(jniEnum)
modelBuilder.finishBuilding(limeInterface)
val jniContainer = modelBuilder.getFinalResult(JniContainer::class.java)
assertContains(jniEnum, jniContainer.enums)
}
@Test
fun finishBuildingInterfaceReadsPointerEquatable() {
val limeElement = LimeClass(
fooPath,
attributes = LimeAttributes.Builder()
.addAttribute(LimeAttributeType.POINTER_EQUATABLE)
.build()
)
modelBuilder.finishBuilding(limeElement)
val jniContainer = modelBuilder.getFinalResult(JniContainer::class.java)
assertTrue(jniContainer.isPointerEquatable)
}
@Test
fun finishBuildingInterfaceReadsEquatable() {
val limeElement = LimeClass(
fooPath,
attributes = LimeAttributes.Builder()
.addAttribute(LimeAttributeType.EQUATABLE)
.build()
)
modelBuilder.finishBuilding(limeElement)
val jniContainer = modelBuilder.getFinalResult(JniContainer::class.java)
assertTrue(jniContainer.isEquatable)
}
@Test
fun finishBuildingMethodReadsJavaCppMethods() {
modelBuilder.finishBuilding(limeMethod)
val jniMethod = modelBuilder.getFinalResult(JniMethod::class.java)
assertEquals(mangledMethodName, jniMethod.javaMethodName)
assertEquals(cppMethod.name, jniMethod.cppMethodName)
assertNotNull(jniMethod.returnType)
assertEquals(javaMethod.returnType.name, jniMethod.returnType.javaName)
assertEquals(cppMethod.returnType.name, jniMethod.returnType.cppName)
}
@Test
fun finishBuildingMethodReadsJniParameters() {
contextStack.injectResult(jniParameter)
modelBuilder.finishBuilding(limeMethod)
val jniMethod = modelBuilder.getFinalResult(JniMethod::class.java)
assertEquals(jniParameter, jniMethod.parameters.first())
assertFalse(jniMethod.isStatic)
}
@Test
fun finishBuildingMethodReadsStaticMethods() {
contextStack.injectResult(jniParameter)
val cppStaticMethod = CppMethod(
name = "cPpWork3R_iNt",
fullyQualifiedName = "cPpWork3R_iNt",
returnType = CppPrimitiveTypeRef.INT8,
parameters = listOf(CppParameter("", CppPrimitiveTypeRef.INT8)),
specifiers = setOf(CppMethod.Specifier.STATIC)
)
every { cppBuilder.getFinalResult(CppMethod::class.java) } returns cppStaticMethod
modelBuilder.finishBuilding(limeMethod)
val jniMethod = modelBuilder.getFinalResult(JniMethod::class.java)
assertTrue(jniMethod.isStatic)
}
@Test
fun finishBuildingMethodReadsConstructor() {
contextStack.injectResult(jniParameter)
val javaConstructor =
JavaMethod("", isConstructor = true, returnType = JavaPrimitiveTypeRef.LONG)
every { javaBuilder.getFinalResult(JavaMethod::class.java) } returns javaConstructor
modelBuilder.finishBuilding(limeMethod)
val jniMethod = modelBuilder.getFinalResult(JniMethod::class.java)
assertTrue(jniMethod.returnsOpaqueHandle)
}
@Test
fun finishBuildingMethodReadsConstMethods() {
contextStack.injectResult(jniParameter)
val cppConstMethod = CppMethod(
name = "cPpWork3R_iNt",
fullyQualifiedName = "cPpWork3R_iNt",
returnType = CppPrimitiveTypeRef.INT8,
parameters = listOf(CppParameter("", CppPrimitiveTypeRef.INT8)),
qualifiers = setOf(CppMethod.Qualifier.CONST)
)
every { cppBuilder.getFinalResult(CppMethod::class.java) } returns cppConstMethod
modelBuilder.finishBuilding(limeMethod)
val jniMethod = modelBuilder.getFinalResult(JniMethod::class.java)
assertTrue(jniMethod.isConst)
}
@Test
fun finishBuildingMethodReadsDisambiguationSuffix() {
every { javaSignatureResolver.isOverloaded(limeMethod) } returns true
modelBuilder.finishBuilding(limeMethod)
val jniMethod = modelBuilder.getFinalResult(JniMethod::class.java)
assertTrue(jniMethod.isOverloaded)
}
@Test
fun finishBuildingMethodReadsException() {
val limeException = LimeException(EMPTY_PATH, errorType = LimeBasicTypeRef.INT)
val limeElement =
LimeFunction(EMPTY_PATH, thrownType = LimeThrownType(LimeDirectTypeRef(limeException)))
val javaExceptionType = JavaExceptionTypeRef(
"",
JavaImport("", JavaPackage.DEFAULT),
listOf("FooException"),
javaCustomType
)
val javaThrowingMethod =
JavaMethod(name = "fancyMEthoD_integer", exception = javaExceptionType)
val cppMethodWithError = CppMethod(name = "cPpWork3R_iNt", errorType = cppCustomType)
every { javaBuilder.getFinalResult(JavaMethod::class.java) } returns javaThrowingMethod
every { cppBuilder.getFinalResult(CppMethod::class.java) } returns cppMethodWithError
modelBuilder.finishBuilding(limeElement)
val jniMethod = modelBuilder.getFinalResult(JniMethod::class.java)
assertEquals("com/example/FooException", jniMethod.exception?.javaClassName)
assertEquals(javaCustomType.name, jniMethod.exception?.errorType?.javaName)
assertEquals(cppCustomType.name, jniMethod.exception?.errorType?.cppName)
}
@Test
fun finishBuildingParameterReadsJavaCppParameters() {
val javaParameter = JavaParameter("relative", javaCustomType)
val cppParameter = CppParameter("absolute", CppComplexTypeRef("foobar"))
every { javaBuilder.getFinalResult(JavaParameter::class.java) } returns javaParameter
every { cppBuilder.getFinalResult(CppParameter::class.java) } returns cppParameter
modelBuilder.finishBuilding(limeParameter)
val resultParameter = modelBuilder.getFinalResult(JniParameter::class.java)
assertEquals(javaParameter.name, resultParameter.name)
assertEquals(javaParameter.type.name, resultParameter.type.javaName)
assertEquals(cppParameter.type.name, resultParameter.type.cppName)
}
@Test
fun finishBuildingStructReadsJavaCppClasses() {
modelBuilder.finishBuilding(limeStruct)
val jniStruct = modelBuilder.getFinalResult(JniStruct::class.java)
assertEquals(javaClass.name, jniStruct.javaName)
assertEquals(javaClass.javaPackage, jniStruct.javaPackage)
assertEquals(cppStruct.fullyQualifiedName, jniStruct.cppFullyQualifiedName)
assertEquals(cppStruct.hasImmutableFields, jniStruct.hasImmutableFields)
}
@Test
fun finishBuildingStructReadsFields() {
val jniField = JniField(jniType, "javaName", null, cppField)
contextStack.injectResult(jniField)
modelBuilder.finishBuilding(limeStruct)
val jniStruct = modelBuilder.getFinalResult(JniStruct::class.java)
assertContains(jniField, jniStruct.fields)
}
@Test
fun finishBuildingStructReadsMethods() {
val jniMethod = JniMethod("foo", "bar")
contextStack.injectResult(jniMethod)
modelBuilder.finishBuilding(limeStruct)
val jniStruct = modelBuilder.getFinalResult(JniStruct::class.java)
assertContains(jniMethod, jniStruct.methods)
}
@Test
fun finishBuildingFieldReadsJavaCppFields() {
val limeElement = LimeField(EMPTY_PATH, typeRef = limeTypeRef)
contextStack.injectResult(jniType)
modelBuilder.finishBuilding(limeElement)
val jniField = modelBuilder.getFinalResult(JniField::class.java)
assertNotNull(jniField)
assertEquals(javaField.name, jniField.javaName)
assertEquals(javaClassName, jniField.javaCustomType)
assertEquals(cppField, jniField.cppField)
}
@Test
fun finishBuildingFieldReadsExternalAccessors() {
val limeElement = LimeField(EMPTY_PATH, typeRef = limeTypeRef)
val cppFieldWithAccessors = CppField(
name = "cPpClass",
fullyQualifiedName = "neSTed::cPpClass",
type = cppCustomType,
getterName = "get_foo",
setterName = "setFoo"
)
every { cppBuilder.getFinalResult(CppField::class.java) } returns cppFieldWithAccessors
contextStack.injectResult(jniType)
modelBuilder.finishBuilding(limeElement)
val jniField = modelBuilder.getFinalResult(JniField::class.java)
assertNotNull(jniField)
assertEquals("get_foo", jniField.cppGetterName)
assertEquals("setFoo", jniField.cppSetterName)
}
@Test
fun finishBuildingEnumerationsReadsNames() {
modelBuilder.finishBuilding(limeEnum)
val jniEnum = modelBuilder.getFinalResult(JniEnum::class.java)
assertEquals(javaEnum.name, jniEnum.javaName)
assertEquals(cppEnum.fullyQualifiedName, jniEnum.cppFullyQualifiedName)
}
@Test
fun finishBuildingEnumerationsReadsEnumerators() {
val jniEnumerator = JniEnumerator("oneJ", "oneC")
contextStack.injectResult(jniEnumerator)
modelBuilder.finishBuilding(limeEnum)
val jniEnum = modelBuilder.getFinalResult(JniEnum::class.java)
assertContains(jniEnumerator, jniEnum.enumerators)
}
@Test
fun finishBuildingEnumerator() {
val javaEnumItem = JavaEnumItem("javaEnumerator")
val cppEnumItem = CppEnumItem("cppEnumerator", "nested::cppEnumerator", null, CppValue("0"))
every { javaBuilder.getFinalResult(JavaEnumItem::class.java) } returns javaEnumItem
every { cppBuilder.getFinalResult(CppEnumItem::class.java) } returns cppEnumItem
val limeElement = LimeEnumerator(EMPTY_PATH)
modelBuilder.finishBuilding(limeElement)
val jniEnumItem = modelBuilder.getFinalResult(JniEnumerator::class.java)
assertEquals(jniEnumItem.cppName, "cppEnumerator")
assertEquals(jniEnumItem.javaName, "javaEnumerator")
}
@Test
fun finishBuildingAttributeCreatesGetter() {
modelBuilder.finishBuilding(limeProperty)
val jniMethod = modelBuilder.getFinalResult(JniMethod::class.java)
assertEquals(javaGetter.name, jniMethod.javaMethodName)
assertEquals(cppGetter.name, jniMethod.cppMethodName)
assertEquals(javaGetter.returnType.name, jniMethod.returnType.javaName)
assertEquals(cppGetter.returnType.name, jniMethod.returnType.cppName)
assertTrue(jniMethod.isConst)
}
@Test
fun finishBuildingAttributeCreatesSetter() {
modelBuilder.finishBuilding(limeProperty)
val methods = modelBuilder.finalResults.filterIsInstance<JniMethod>()
assertEquals(2, methods.size)
assertEquals(javaSetter.name, methods.last().javaMethodName)
assertEquals(cppSetter.name, methods.last().cppMethodName)
assertEquals("void", methods.last().returnType.cppName)
assertEquals("void", methods.last().returnType.javaName)
}
@Test
fun finishBuildingAttributeReadsParametersIntoSetter() {
modelBuilder.finishBuilding(limeProperty)
val methods = modelBuilder.finalResults.filterIsInstance<JniMethod>()
assertEquals(2, methods.size)
val setterParameter = methods.last().parameters.first()
assertEquals(javaSetter.parameters.first().name, setterParameter.name)
assertEquals(javaSetter.parameters.first().type.name, setterParameter.type.javaName)
assertEquals(cppSetter.parameters.first().type.name, setterParameter.type.cppName)
}
@Test
fun finishBuildingAttributeReadonly() {
val limeElement =
LimeProperty(EMPTY_PATH, typeRef = limeTypeRef, getter = LimeFunction(EMPTY_PATH))
modelBuilder.finishBuilding(limeElement)
val methods = modelBuilder.finalResults.filterIsInstance<JniMethod>()
assertEquals(1, methods.size)
assertEquals(javaGetter.name, methods.first().javaMethodName)
assertEquals(cppGetter.name, methods.first().cppMethodName)
assertEquals(javaGetter.returnType.name, methods.first().returnType.javaName)
assertEquals(cppGetter.returnType.name, methods.first().returnType.cppName)
}
@Test
fun finishBuildingAttributeStatic() {
val limeElement = LimeProperty(
EMPTY_PATH,
typeRef = limeTypeRef,
getter = LimeFunction(EMPTY_PATH),
setter = limeSetter,
isStatic = true
)
modelBuilder.finishBuilding(limeElement)
val methods = modelBuilder.finalResults.filterIsInstance<JniMethod>()
assertEquals(2, methods.size)
assertTrue(methods.first().isStatic)
assertTrue(methods.last().isStatic)
}
companion object {
private val INTERNAL_NAMESPACE = listOf("very", "internal")
}
}
| 1 | null | 1 | 1 | a7b3833ce840284cadf968b6f8441888f970c134 | 26,675 | gluecodium | Apache License 2.0 |
base/src/main/java/sk/kasper/base/SettingsManager.kt | BME-MIT-IET | 484,162,194 | false | null | package sk.kasper.base
import kotlinx.coroutines.flow.Flow
interface SettingsManager {
companion object {
const val PRODUCTION = 0
const val LOCALHOST = 1
const val RASPBERRY = 2
}
val showUnconfirmedLaunches: Boolean
var showLaunchNotifications: Boolean
val durationBeforeNotificationIsShown: Int
var nightMode: Int
val apiEndpoint: Int
val apiEndPointValues: List<Int>
val durationValues: List<Int>
val nightModeValues: List<Int>
fun getSettingChanges(): Flow<SettingKey>
fun getIntAsFlow(key: SettingKey): Flow<Int>
fun getBoolAsFlow(key: SettingKey): Flow<Boolean>
fun addSettingChangeListener(listener: SettingChangeListener)
fun removeSettingChangeListener(listener: SettingChangeListener)
fun toggleTheme()
fun getBoolean(key: SettingKey): Boolean
fun setBoolean(key: SettingKey, value: Boolean)
fun getInt(key: SettingKey): Int
fun setInt(key: SettingKey, value: Int)
} | 10 | null | 14 | 2 | d53a13dde49828c5ec473774408aab1ecae26952 | 985 | iet-hf-2022-houston | Apache License 2.0 |
src/main/kotlin/es/horm/easyadldetektplugin/detekt/rule/EasyAdlRuleSetProvider.kt | Tommyten | 585,151,541 | false | null | package es.horm.easyadldetektplugin.detekt.rule
import io.gitlab.arturbosch.detekt.api.Config
import io.gitlab.arturbosch.detekt.api.RuleSet
import io.gitlab.arturbosch.detekt.api.RuleSetProvider
class EasyAdlRuleSetProvider : RuleSetProvider {
override val ruleSetId: String = RULE_SET_ID
override fun instance(config: Config): RuleSet {
return RuleSet(ruleSetId, listOf(EasyAdlComplianceRule(config)))
}
companion object {
const val RULE_SET_ID = "EasyAdlRuleSet"
}
}
| 0 | Kotlin | 0 | 0 | 80174f2d81ab46e96449dce8bf3a2bab6aaeb9eb | 510 | easyAdlDetektPlugin | Apache License 2.0 |
amethyst/src/main/java/com/vitorpamplona/amethyst/ui/dal/NIP90ContentDiscoveryResponseFilter.kt | vitorpamplona | 587,850,619 | false | null | /**
* Copyright (c) 2024 <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 com.vitorpamplona.amethyst.ui.dal
import com.vitorpamplona.amethyst.model.Account
import com.vitorpamplona.amethyst.model.LocalCache
import com.vitorpamplona.amethyst.model.Note
import com.vitorpamplona.amethyst.model.observables.CreatedAtComparator
import com.vitorpamplona.quartz.events.MuteListEvent
import com.vitorpamplona.quartz.events.NIP90ContentDiscoveryResponseEvent
import com.vitorpamplona.quartz.events.PeopleListEvent
open class NIP90ContentDiscoveryResponseFilter(
val account: Account,
val dvmkey: String,
val request: String,
) : AdditiveFeedFilter<Note>() {
var latestNote: Note? = null
override fun feedKey(): String {
return account.userProfile().pubkeyHex + "-" + request
}
open fun followList(): String {
return account.defaultDiscoveryFollowList.value
}
override fun showHiddenKey(): Boolean {
return followList() == PeopleListEvent.blockListFor(account.userProfile().pubkeyHex) ||
followList() == MuteListEvent.blockListFor(account.userProfile().pubkeyHex)
}
fun acceptableEvent(note: Note): Boolean {
val noteEvent = note.event
return noteEvent is NIP90ContentDiscoveryResponseEvent && noteEvent.isTaggedEvent(request)
}
override fun feed(): List<Note> {
val params = buildFilterParams(account)
latestNote =
LocalCache.notes.maxOrNullOf(
filter = { idHex: String, note: Note ->
acceptableEvent(note)
},
comparator = CreatedAtComparator,
)
val noteEvent = latestNote?.event as? NIP90ContentDiscoveryResponseEvent ?: return listOf()
return noteEvent.innerTags().mapNotNull {
LocalCache.checkGetOrCreateNote(it)
}
}
override fun applyFilter(collection: Set<Note>): Set<Note> {
return innerApplyFilter(collection)
}
fun buildFilterParams(account: Account): FilterByListParams {
return FilterByListParams.create(
account.userProfile().pubkeyHex,
account.defaultDiscoveryFollowList.value,
account.liveDiscoveryFollowLists.value,
account.flowHiddenUsers.value,
)
}
protected open fun innerApplyFilter(collection: Collection<Note>): Set<Note> {
// val params = buildFilterParams(account)
val maxNote = collection.filter { acceptableEvent(it) }.maxByOrNull { it.createdAt() ?: 0 } ?: return emptySet()
if ((maxNote.createdAt() ?: 0) > (latestNote?.createdAt() ?: 0)) {
latestNote = maxNote
}
val noteEvent = latestNote?.event as? NIP90ContentDiscoveryResponseEvent ?: return setOf()
return noteEvent.innerTags().mapNotNull {
LocalCache.checkGetOrCreateNote(it)
}.toSet()
}
override fun sort(collection: Set<Note>): List<Note> {
return collection.toList() // collection.sortedWith(compareBy({ it.createdAt() }, { it.idHex })).reversed()
}
}
| 145 | null | 149 | 1,097 | 8b617fbd605540dcbb4b24c329db3bfe6eaabc88 | 4,135 | amethyst | MIT License |
app/src/main/java/jp/juggler/screenshotbutton/MyImageButton.kt | tateisu | 229,436,742 | false | null | package jp.juggler.screenshotbutton
import android.annotation.SuppressLint
import android.content.Context
import android.util.AttributeSet
import android.view.WindowManager
import android.widget.ImageButton
import android.widget.TextView
@SuppressLint("AppCompatCustomView")
class MyTextBox : TextView {
var windowLayoutParams : WindowManager.LayoutParams? = null
// private val myExclusionRects = listOf(Rect())
constructor(context: Context) : super(context, null)
constructor(context: Context, attrs: AttributeSet?) : super(context, attrs)
constructor(context: Context, attrs: AttributeSet?, defStyleAttr: Int) : super(context, attrs, defStyleAttr)
fun updateExclusion() {
// if( Build.VERSION.SDK_INT >= API_SYSTEM_GESTURE_EXCLUSION ){
// val maxSize = (200f * resources.displayMetrics.density).toInt()
// myExclusionRects[0].set(
// windowLayoutParams?.x ?: left,
// windowLayoutParams?.y ?: top,
// maxSize,
// maxSize
// ) // x,y,w,h なのか…?
// systemGestureExclusionRects = myExclusionRects
// }
}
// override fun onLayout(changedCanvas: Boolean, left: Int, top: Int, right: Int, bottom: Int) {
// super.onLayout(changedCanvas, left, top, right, bottom)
// if( Build.VERSION.SDK_INT >= API_SYSTEM_GESTURE_EXCLUSION ){
// val maxSize = (200f * resources.displayMetrics.density).toInt()
// myExclusionRects[0].set(
// windowLayoutParams?.x ?: left,
// windowLayoutParams?.y ?: top,
// maxSize,
// maxSize
// ) // x,y,w,h なのか…?
// systemGestureExclusionRects = myExclusionRects
// }
// }
}
| 1 | Kotlin | 0 | 5 | c59e9b4991982bdc6d89f233bdbf497fec04b97f | 1,780 | ScreenShotButton | Apache License 2.0 |
src/main/kotlin/columns/DbString.kt | JavaDream | 382,886,127 | false | null | package columns
class DbString(name: String) : Column(name) {
private var length = 250
override fun toSql(): String {
return "$name varchar($length)"
}
infix fun limit(length: Int): DbString {
this.length = length
return this
}
} | 0 | Kotlin | 0 | 1 | e0664a210018e7b354e062db69f1ac67b8ab318a | 276 | migration | Apache License 2.0 |
_lifecycle-handler/_activity/lifecycle-handler-compose-activity/src/main/java/io/androidalatan/lifecycle/handler/compose/activity/ComposeLifecycleBottomSheetDialogFragment.kt | android-alatan | 466,507,427 | false | null | package io.androidalatan.lifecycle.handler.compose.activity
import android.annotation.SuppressLint
import android.content.Context
import android.content.Intent
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.compose.runtime.Composable
import androidx.compose.runtime.CompositionLocalProvider
import androidx.compose.ui.platform.ComposeView
import androidx.fragment.app.Fragment
import androidx.fragment.app.FragmentActivity
import com.google.android.material.bottomsheet.BottomSheetDialogFragment
import io.androidalatan.backkey.handler.ActivityBackKeyObserver
import io.androidalatan.backkey.handler.BackKeyHandlerStreamImpl
import io.androidalatan.backkey.handler.api.BackKeyHandlerStream
import io.androidalatan.bundle.BundleDataImpl
import io.androidalatan.bundle.IntentDataImpl
import io.androidalatan.bundle.collector.BundleCollectorStreamImpl
import io.androidalatan.bundle.collector.api.BundleCollectorStream
import io.androidalatan.component.view.compose.ComposeViewInteractionTriggerImpl
import io.androidalatan.coroutine.dispatcher.api.DispatcherProvider
import io.androidalatan.lifecycle.handler.activity.LifecycleNotifierImpl
import io.androidalatan.lifecycle.handler.api.ChildLifecycleSource
import io.androidalatan.lifecycle.handler.api.LifecycleListener
import io.androidalatan.lifecycle.handler.api.LifecycleNotifier
import io.androidalatan.lifecycle.handler.compose.activity.localowners.LocalComposeEventTriggerOwner
import io.androidalatan.lifecycle.handler.compose.util.LocalLifecycleNotifierOwner
import io.androidalatan.lifecycle.handler.internal.invoke.AsyncInvokerManager
import io.androidalatan.lifecycle.handler.internal.invoke.InvokerManagerImpl
import io.androidalatan.lifecycle.handler.internal.invoke.SyncInvokerManager
import io.androidalatan.lifecycle.handler.internal.invoke.coroutine.CoroutineInvokerManagerImpl
import io.androidalatan.lifecycle.handler.invokeradapter.api.InvokeAdapterInitializer
import io.androidalatan.lifecycle.lazyprovider.LazyProvider
import io.androidalatan.request.permission.PermissionExplanationBuilderFactoryImpl
import io.androidalatan.request.permission.PermissionInvokerImpl
import io.androidalatan.request.permission.PermissionStreamImpl
import io.androidalatan.request.permission.api.PermissionStream
import io.androidalatan.result.handler.ResultStreamImpl
import io.androidalatan.result.handler.api.ResultStream
import io.androidalatan.router.FragmentRouter
import io.androidalatan.router.api.Router
import io.androidalatan.view.event.api.ViewInteractionStream
import io.androidalatan.view.event.compose.ViewInteractionControllerImpl
import io.androidalatan.view.event.impl.ViewInteractionStreamImpl
abstract class ComposeLifecycleBottomSheetDialogFragment(
private val lazyProvider: LazyProvider<Fragment>,
private val lazyActivityProvider: LazyProvider<FragmentActivity>,
private val bundleCollectorStream: BundleCollectorStreamImpl = BundleCollectorStreamImpl(),
private val resultStream: ResultStreamImpl = ResultStreamImpl(),
private val fragmentRouter: FragmentRouter = FragmentRouter(lazyProvider),
private val permissionStream: PermissionStreamImpl = PermissionStreamImpl(
PermissionInvokerImpl(lazyActivityProvider),
PermissionExplanationBuilderFactoryImpl(lazyActivityProvider)
),
private val backKeyHandlerStreamImpl: BackKeyHandlerStreamImpl = BackKeyHandlerStreamImpl(),
private val viewInteractionStream: ViewInteractionStreamImpl = ViewInteractionStreamImpl(),
) : BottomSheetDialogFragment(), ChildLifecycleSource,
BundleCollectorStream by bundleCollectorStream,
ResultStream by resultStream,
Router by fragmentRouter,
PermissionStream by permissionStream,
BackKeyHandlerStream by backKeyHandlerStreamImpl,
ViewInteractionStream by viewInteractionStream {
constructor() : this(LazyProvider<Fragment>(), LazyProvider<FragmentActivity>())
private val invokeManager = InvokerManagerImpl(
syncInvokerManager = SyncInvokerManager(
coroutineInvokerManager = CoroutineInvokerManagerImpl(DispatcherProvider())
),
asyncInvokerManager = AsyncInvokerManager(
parameterInstances = mapOf(
BundleCollectorStream::class.java to bundleCollectorStream,
PermissionStream::class.java to permissionStream,
ResultStream::class.java to resultStream,
Router::class.java to fragmentRouter,
BackKeyHandlerStream::class.java to backKeyHandlerStreamImpl,
ViewInteractionStream::class.java to viewInteractionStream,
),
invokeAdapters = kotlin.run {
val tempLifecycle = lifecycle
val tempLogger = InvokeAdapterInitializer.logger()
InvokeAdapterInitializer.factories()
.map {
it.create(tempLifecycle, tempLogger)
}
}
)
)
private val lifecycleNotifier: LifecycleNotifier = LifecycleNotifierImpl(invokeManager)
private val composeViewInteractionTrigger = ComposeViewInteractionTriggerImpl()
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
val composeView = ComposeView(requireContext())
composeView.setContent {
CompositionLocalProvider(
LocalComposeEventTriggerOwner provides composeViewInteractionTrigger,
LocalLifecycleNotifierOwner provides lifecycleNotifier
) {
LifecycleHandle {
contentView()
}
}
}
return composeView
}
@SuppressLint("ComposableNaming")
@Composable
abstract fun contentView()
override fun onAttach(context: Context) {
lazyProvider.set(this)
activity?.let {
lazyActivityProvider.set(it)
}
super.onAttach(context)
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
viewInteractionStream.setViewController(ViewInteractionControllerImpl(composeViewInteractionTrigger))
backKeyHandlerStreamImpl.setBackKeyObserver(ActivityBackKeyObserver(requireActivity()))
val bundle = Bundle()
savedInstanceState?.let { bundle.putAll(it) }
arguments?.let { extras -> bundle.putAll(extras) }
bundleCollectorStream.updateIntent(IntentDataImpl(Intent(), BundleDataImpl(bundle)))
}
@Suppress("DEPRECATION")
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
super.onActivityResult(requestCode, resultCode, data)
resultStream.newResultInfo(requestCode, resultCode, data)
}
@Suppress("DEPRECATION")
override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<String>, grantResults: IntArray) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults)
permissionStream.onResult(requestCode, permissions, grantResults)
}
override fun add(listener: LifecycleListener) {
lifecycleNotifier.add(listener)
}
override fun remove(listener: LifecycleListener) {
lifecycleNotifier.remove(listener)
}
} | 3 | null | 5 | 56 | 35b0ec7a89f8254db0af1830ac1de8a7124c6f09 | 7,409 | LifecycleComponents | MIT License |
lmos-router-vector-spring-boot-starter/src/main/kotlin/ai/ancf/lmos/router/vector/starter/SpringVectorSeedClient.kt | lmos-ai | 861,674,747 | false | {"Kotlin": 191217, "Jupyter Notebook": 98576} | // SPDX-FileCopyrightText: 2024 Deutsche Telekom AG
//
// SPDX-License-Identifier: Apache-2.0
package ai.ancf.lmos.router.vector.starter
import ai.ancf.lmos.router.core.Failure
import ai.ancf.lmos.router.core.Result
import ai.ancf.lmos.router.core.Success
import ai.ancf.lmos.router.vector.VectorClientException
import ai.ancf.lmos.router.vector.VectorRouteConstants.Companion.AGENT_FIELD_NAME
import ai.ancf.lmos.router.vector.VectorSeedClient
import ai.ancf.lmos.router.vector.VectorSeedRequest
import org.springframework.ai.document.Document
import org.springframework.ai.vectorstore.VectorStore
/**
* A Spring implementation of the VectorSeedClient.
*
* @param vectorStore The vector store to seed.
*/
class SpringVectorSeedClient(
private val vectorStore: VectorStore,
) : VectorSeedClient {
/**
* Seeds the vector store with the given documents.
*
* @param documents The documents to seed the vector store with.
* @return A result indicating success or failure.
*/
override fun seed(documents: List<VectorSeedRequest>): Result<Unit, VectorClientException> {
try {
val vectorDocuments =
documents.map {
Document(
it.text,
mapOf(AGENT_FIELD_NAME to it.agentName),
)
}
return Success(vectorStore.add(vectorDocuments))
} catch (e: Exception) {
return Failure(VectorClientException(e.message ?: "An error occurred while seeding the vector store"))
}
}
}
| 6 | Kotlin | 0 | 22 | 43647592a7460fd0c57621275b47cb5ab564462d | 1,584 | lmos-router | Apache License 2.0 |
app/src/main/java/com/qwlyz/androidstudy/fragment/StartActivityFragment.kt | lyzqw | 222,019,259 | false | {"Kotlin": 91509, "Java": 44171, "C++": 293} | //package com.qwlyz.androidstudy.fragment
//
//import android.Manifest
//import android.content.ContentValues
//import android.content.pm.PackageManager.PERMISSION_GRANTED
//import android.graphics.BitmapFactory
//import android.os.Build
//import android.provider.MediaStore
//import android.util.Log
//import androidx.annotation.RequiresApi
//import androidx.core.app.ActivityCompat
//import androidx.core.content.ContextCompat
//import com.blankj.utilcode.util.FileIOUtils
//import com.blankj.utilcode.util.Utils
//import com.qwlyz.androidstudy.BaseFragment
//import com.qwlyz.androidstudy.R
//import com.qwlyz.androidstudy.SimpleActivity
//import kotlinx.android.synthetic.main.fragment_start_activity.*
//import kotlinx.android.synthetic.main.fragment_storage.*
//import java.io.File
//
///**
// *
// * @author lyz
// */
//class StartActivityFragment : BaseFragment() {
//
// override fun getLayoutId(): Int = R.layout.fragment_start_activity
//
// override fun initData() {
// start.setOnClickListener {
// SimpleActivity.start(activity!!)
// }
// }
//
//}
//
| 0 | Kotlin | 0 | 0 | bb7e85e7d39e553bed9fccdc838113129e88ed0c | 1,099 | wyq_github_android_study | Apache License 2.0 |
app/src/main/java/com/denysnovoa/nzbmanager/radarr/movie/list/repository/api/RadarrMoviesApiRest.kt | denysnovoa | 90,066,913 | false | null | package com.denysnovoa.nzbmanager.radarr.movie.list.repository.api
import com.denysnovoa.nzbmanager.radarr.movie.list.repository.entity.MovieEntity
import io.reactivex.Completable
import io.reactivex.Flowable
import io.reactivex.Single
import retrofit2.http.DELETE
import retrofit2.http.GET
import retrofit2.http.Path
import retrofit2.http.Query
interface RadarrMoviesApiRest {
@GET("api/movie")
fun movies(): Flowable<List<MovieEntity>>
@GET("api/movie/{id}")
fun getDetail(@Path("id") id: Int): Single<MovieEntity>
@DELETE("api/movie/{id}")
fun delete(@Path("id") id: Int,
@Query("deleteFiles") deleteFiles: Boolean,
@Query("addExclusion") addExclusion: Boolean): Completable
} | 0 | Kotlin | 0 | 1 | 8944e3bae4c073856f9856bf2e5064a6dadde4f7 | 737 | radarrsonarr | Apache License 2.0 |
lib/src/main/java/com/github/preference/RingtonePreferenceSummaryProvider.kt | pnemonic78 | 149,122,819 | false | {"Kotlin": 206322} | package com.github.preference
import androidx.preference.Preference
class RingtonePreferenceSummaryProvider private constructor() :
Preference.SummaryProvider<RingtonePreference> {
override fun provideSummary(preference: RingtonePreference): CharSequence? {
return preference.getRingtoneTitle(preference.value)
}
companion object {
private var summaryProvider: RingtonePreferenceSummaryProvider? = null
/**
* Retrieve a singleton instance of this simple
* [androidx.preference.Preference.SummaryProvider] implementation.
*
* @return a singleton instance of this simple
* [androidx.preference.Preference.SummaryProvider] implementation
*/
@JvmStatic
fun getInstance(): RingtonePreferenceSummaryProvider {
var provider = summaryProvider
if (provider == null) {
provider = RingtonePreferenceSummaryProvider()
summaryProvider = provider
}
return provider
}
}
} | 0 | Kotlin | 0 | 1 | baaddab25c8cd075c4f6365a18f8bdf802ca82c3 | 1,063 | android-lib | Apache License 2.0 |
0469.Convex Polygon.kt | sarvex | 842,260,390 | false | {"Kotlin": 1775678, "PowerShell": 418} | internal class Solution {
fun isConvex(points: List<List<Int?>>): Boolean {
val n: Int = points.size()
var pre: Long = 0
var cur: Long = 0
for (i in 0 until n) {
val p1: Unit = points[i]
val p2: Unit = points[(i + 1) % n]
val p3: Unit = points[(i + 2) % n]
val x1: Int = p2.get(0) - p1.get(0)
val y1: Int = p2.get(1) - p1.get(1)
val x2: Int = p3.get(0) - p1.get(0)
val y2: Int = p3.get(1) - p1.get(1)
cur = (x1 * y2 - x2 * y1).toLong()
if (cur != 0L) {
if (cur * pre < 0) {
return false
}
pre = cur
}
}
return true
}
}
| 0 | Kotlin | 0 | 0 | 71f5d03abd6ae1cd397ec4f1d5ba04f792dd1b48 | 641 | kotlin-leetcode | MIT License |
FetLifeKotlin/app/src/main/java/com/bitlove/fetlife/model/network/job/getresource/GetConversationListJob.kt | chonamdoo | 125,962,896 | true | {"Markdown": 1, "Batchfile": 2, "Shell": 2, "Java Properties": 4, "Proguard": 4, "Kotlin": 68, "Java": 254, "JavaScript": 1} | package com.bitlove.fetlife.model.network.job.getresource
import com.bitlove.fetlife.FetLifeApplication
import com.bitlove.fetlife.model.dataobject.entity.ContentEntity
import com.bitlove.fetlife.model.dataobject.wrapper.Content
import retrofit2.Call
class GetConversationListJob : GetListResourceJob<ContentEntity>(PRIORITY_GET_RESOURCE_FRONT,false, TAG_GET_CONVERSATIONS, TAG_GET_RESOURCE) {
companion object {
val TAG_GET_CONVERSATIONS = "TAG_GET_CONVERSATIONS"
}
override fun saveToDb(resourceArray: Array<ContentEntity>) {
val memberDao = getDatabase().memberDao()
for (content in resourceArray) {
val memberRef = content.memberRef
if (memberRef != null) {
val memberId = memberDao.update(memberRef)
content.memberId = memberId
}
content.type = Content.TYPE.CONVERSATION.toString()
}
getDatabase().contentDao().insert(*resourceArray)
}
override fun getCall(): Call<Array<ContentEntity>> {
return FetLifeApplication.instance.fetlifeService.fetLifApi.getConversations("fsdfsf",null,null,null)
}
} | 0 | Java | 0 | 0 | ac680aed9629f51f38322d14df58c56142d49fed | 1,156 | android-1 | MIT License |
basicktest/src/main/java/com/mozhimen/basicktest/taskk/TaskKCountDownActivity.kt | mozhimen | 353,952,154 | false | {"Kotlin": 2273552, "Java": 246468, "AIDL": 1012} | package com.mozhimen.basicktest.taskk
import android.os.Bundle
import com.mozhimen.basick.elemk.androidx.appcompat.bases.BaseActivityVB
import com.mozhimen.basick.lintk.optin.OptInApiInit_ByLazy
import com.mozhimen.basick.lintk.optin.OptInApiCall_BindLifecycle
import com.mozhimen.basick.taskk.temps.ITaskKCountDownListener
import com.mozhimen.basick.taskk.temps.TaskKCountDown
import com.mozhimen.basicktest.databinding.ActivityTaskkCountDownBinding
import kotlin.math.roundToInt
class TaskKCountDownActivity : BaseActivityVB<ActivityTaskkCountDownBinding>() {
@OptIn(OptInApiInit_ByLazy::class, OptInApiCall_BindLifecycle::class)
private val _taskKCountDown: TaskKCountDown by lazy { TaskKCountDown().apply { bindLifecycle(this@TaskKCountDownActivity) } }
@OptIn(OptInApiInit_ByLazy::class, OptInApiCall_BindLifecycle::class)
override fun initView(savedInstanceState: Bundle?) {
_taskKCountDown.start(10000, object : ITaskKCountDownListener {
override fun onTick(millisUntilFinished: Long) {
vb.taskkCountDownTxt.text = (millisUntilFinished.toFloat() / 1000f).roundToInt().toString()
}
override fun onFinish() {
vb.taskkCountDownTxt.text = "结束啦"
}
})
}
} | 0 | Kotlin | 7 | 115 | 05064571d43ada3ea6488bafc33d2fe436c0618d | 1,277 | SwiftKit | Apache License 2.0 |
app/src/main/java/com/steleot/jetpackcompose/playground/service/JetpackComposePlaygroundFirebaseMessagingService.kt | Vivecstel | 338,792,534 | false | null | package com.steleot.jetpackcompose.playground.service
import com.google.firebase.messaging.FirebaseMessagingService
import com.google.firebase.messaging.RemoteMessage
import timber.log.Timber
class JetpackComposePlaygroundFirebaseMessagingService : FirebaseMessagingService() {
override fun onMessageReceived(message: RemoteMessage) {
Timber.d("Message received with data: ${message.data}")
}
override fun onNewToken(token: String) {
Timber.d("New token retrieved: $token")
}
} | 1 | Kotlin | 10 | 117 | e4f4c45b4376dac907cae4ef07db1f188c86d01c | 513 | Jetpack-Compose-Playground | Apache License 2.0 |
gaia/src/main/kotlin/dev/pooq/ichor/gaia/extensions/SystemExtensions.kt | kxmpxtxnt | 586,376,008 | false | null | package dev.pooq.ichor.gaia.extensions
val env: MutableMap<String, String> = System.getenv() | 0 | Kotlin | 0 | 3 | 29665855a4bde80b66eb4eadd6b14f6b91339a37 | 93 | ichor | Apache License 2.0 |
app/src/main/java/es/upm/bienestaremocional/ui/theme/Type.kt | Emotional-Wellbeing | 531,973,820 | false | null | package es.upm.bienestaremocional.ui.theme
import androidx.compose.material3.Typography
// Set of Material typography styles to start with
private val defaultTypography = Typography()
val Typography = Typography(
displayLarge = defaultTypography.displayLarge.copy(fontFamily = Quicksand),
displayMedium = defaultTypography.displayMedium.copy(fontFamily = Quicksand),
displaySmall = defaultTypography.displaySmall.copy(fontFamily = Quicksand),
headlineLarge = defaultTypography.headlineLarge.copy(fontFamily = Quicksand),
headlineMedium = defaultTypography.headlineMedium.copy(fontFamily = Quicksand),
headlineSmall = defaultTypography.headlineSmall.copy(fontFamily = Quicksand),
titleLarge = defaultTypography.titleLarge.copy(fontFamily = Quicksand),
titleMedium = defaultTypography.titleMedium.copy(fontFamily = Quicksand),
titleSmall = defaultTypography.titleSmall.copy(fontFamily = Quicksand),
bodyLarge = defaultTypography.bodyLarge.copy(fontFamily = Quicksand),
bodyMedium = defaultTypography.bodyMedium.copy(fontFamily = Quicksand),
bodySmall = defaultTypography.bodySmall.copy(fontFamily = Quicksand),
labelLarge = defaultTypography.labelLarge.copy(fontFamily = Quicksand),
labelMedium = defaultTypography.labelMedium.copy(fontFamily = Quicksand),
labelSmall = defaultTypography.labelSmall.copy(fontFamily = Quicksand),
/* Other default text styles to override
titleLarge = TextStyle(
fontFamily = FontFamily.Default,
fontWeight = FontWeight.Normal,
fontSize = 22.sp,
lineHeight = 28.sp,
letterSpacing = 0.sp
),
labelSmall = TextStyle(
fontFamily = FontFamily.Default,
fontWeight = FontWeight.Medium,
fontSize = 11.sp,
lineHeight = 16.sp,
letterSpacing = 0.5.sp
)
*/
)
| 0 | null | 0 | 2 | 55c24943d57d1c0cb91ddce569f27d7e5cd6ed8d | 1,844 | App | Apache License 2.0 |
core/domain/src/main/java/jp/mydns/kokoichi0206/domain/usecase/quiz_record/InsertRecordUseCase.kt | android-project-46group | 408,417,203 | false | null | package jp.mydns.kokoichi0206.domain.usecase.quiz_record
import jp.mydns.kokoichi0206.data.repository.QuizRecordRepository
/**
* UseCase of insert or update a quiz record.
*/
class InsertRecordUseCase(
private val repository: QuizRecordRepository,
) {
suspend operator fun invoke(record: jp.mydns.kokoichi0206.model.QuizRecord) {
repository.insertRecord(record)
}
}
| 14 | Kotlin | 0 | 2 | d69f08e815a4780bd93a0e1bf274dc770155b06e | 391 | android | MIT License |
app/src/main/java/com/example/simple_movie_app/MainActivity.kt | windy-itus | 796,164,236 | false | {"Kotlin": 66112} | package com.example.simple_movie_app
import android.os.Bundle
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Surface
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.navigation.compose.NavHost
import androidx.navigation.compose.composable
import androidx.navigation.compose.rememberNavController
import com.example.simple_movie_app.data.repository.MoviesRepository
import com.example.simple_movie_app.ui.screen.list_movies.MoviesScreen
import com.example.simple_movie_app.ui.screen.movie_details.MovieDetailsScreen
import com.example.simple_movie_app.ui.theme.Simple_movie_appTheme
import com.example.simple_movie_app.view_model.MovieDetailsViewModel
import com.example.simple_movie_app.view_model.MoviesViewModel
class MainActivity : ComponentActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
val moviesRepository = MoviesRepository(
apiKey = GlobalVariables.getApiKey() ?: ""
)
setContent {
Simple_movie_appTheme {
// A surface container using the 'background' color from the theme
Surface(
modifier = Modifier.fillMaxSize(), color = MaterialTheme.colorScheme.background
) {
AppNavigation(
MoviesViewModel(moviesRepository), MovieDetailsViewModel(moviesRepository)
)
}
}
}
}
}
@Composable
fun AppNavigation(moviesViewModel: MoviesViewModel, movieDetailsViewModel: MovieDetailsViewModel) {
val navController = rememberNavController()
NavHost(navController = navController, startDestination = "moviesList") {
composable("moviesList") {
MoviesScreen(viewModel = moviesViewModel, navController = navController)
}
composable("movieDetails/{movieId}") { backStackEntry ->
// Extract movieId from backStackEntry
val movieId =
backStackEntry.arguments?.getString("movieId")?.toIntOrNull() ?: return@composable
MovieDetailsScreen(viewModel = movieDetailsViewModel, movieId = movieId)
}
}
}
| 0 | Kotlin | 0 | 0 | f4677b844fc0bbfda2a32da71d76520e11e4688d | 2,400 | simple_movie_app | MIT License |
common/src/iosMain/kotlin/org/jetbrains/kotlinconf/api/Constants.kt | Sneyder2328 | 148,829,827 | true | {"Kotlin": 106023, "Swift": 21519, "Ruby": 309} | package org.jetbrains.kotlinconf.api
val END_POINT: String = "https://api.kotlinconf.com"
| 0 | Kotlin | 0 | 0 | 888920feba5908d68a6fd4e949588a91bf8f29d2 | 91 | kotlinconf-app | Apache License 2.0 |
app/src/main/java/com/acme/kotlinintervals/interactor/IntervalAssets.kt | damientl | 541,285,038 | false | {"Kotlin": 15932} | package com.acme.kotlinintervals.interactor
import com.acme.kotlinintervals.R
object IntervalAssets {
val AUDIO_RESOURCES = listOf(
R.raw.piano, R.raw.piano2, R.raw.`in`, R.raw.out, R.raw.hold, R.raw.assobio_fim,
R.raw.toco)
val PROGRAM_RESOURCES = mapOf(
10 to R.raw.prog10s,
8 to R.raw.prog8s,
5 to R.raw.prog5s
)
val DEFAULT_PROGRAM = R.raw.prog10s
} | 0 | Kotlin | 0 | 0 | e0b918ec176501355e772305f0b592e0843dc294 | 413 | kotlinIntervals | MIT License |
src/main/kotlin/uk/gov/justice/digital/hmpps/hmppscontactsapi/mapping/CountyEntityMappers.kt | ministryofjustice | 835,306,273 | false | {"Kotlin": 796959, "Shell": 2365, "Dockerfile": 1483} | package uk.gov.justice.digital.hmpps.hmppscontactsapi.mapping
import uk.gov.justice.digital.hmpps.hmppscontactsapi.entity.CountyEntity
import uk.gov.justice.digital.hmpps.hmppscontactsapi.model.response.County
fun CountyEntity.toModel(): County {
return County(
countyId = this.countyId,
nomisCode = this.nomisCode,
nomisDescription = this.nomisDescription,
displaySequence = this.displaySequence,
)
}
fun List<CountyEntity>.toModel() = map { it.toModel() }
| 5 | Kotlin | 0 | 0 | fdcb9649525c4bad4ee73ec6b844abf8ebbd466c | 481 | hmpps-contacts-api | MIT License |
SKIE/skie-gradle/plugin-shim-impl/src/kgp_1.8.0..1.8.20/gradle_common/kotlin/co/touchlab/skie/plugin/shim/LaunchSchedulerImpl.kt | touchlab | 685,579,240 | false | {"Kotlin": 1525287, "Swift": 6029, "Shell": 763} | package co.touchlab.skie.plugin.shim
import org.gradle.api.Project
class LaunchSchedulerImpl : LaunchScheduler {
override fun whenMinOsVersionCanBeSafelyChanged(project: Project, block: () -> Unit) {
if (project.state.executed) {
block()
} else {
project.afterEvaluate {
block()
}
}
}
}
actual fun LaunchScheduler(): LaunchScheduler = LaunchSchedulerImpl()
| 2 | Kotlin | 8 | 623 | beb653053135860f34558ae10b4abaa2cdec0826 | 445 | SKIE | Apache License 2.0 |
client/src/main/kotlin/ticketToRide/screens/ShowGameIdScreen.kt | Kiryushin-Andrey | 253,543,902 | false | null | package ticketToRide.screens
import com.ccfraser.muirwik.components.*
import com.ccfraser.muirwik.components.button.*
import com.ccfraser.muirwik.components.dialog.*
import kotlinx.browser.window
import react.*
import react.dom.a
import react.dom.attrs
import react.dom.p
import styled.*
import ticketToRide.*
external interface ShowGameIdScreenProps : Props {
var gameId: IGameId
var locale: Locale
var onClosed: () -> Unit
}
@JsExport
@Suppress("NON_EXPORTABLE_TYPE")
class ShowGameIdScreen : RComponent<ShowGameIdScreenProps, State>() {
override fun RBuilder.render() {
val gameUrl = window.location.href
// navigator.clipboard can actually be undefined
@Suppress("UNNECESSARY_SAFE_CALL")
window.navigator.clipboard?.writeText(gameUrl)
mDialog {
css {
+WelcomeScreen.ComponentStyles.welcomeDialog
}
attrs {
open = true
maxWidth = "sm"
fullWidth = true
onKeyDown = { e ->
if (e.keyCode == 13) props.onClosed()
}
}
mDialogContent {
p {
+str.sendThisLinkToOtherPlayers
if (window.navigator.clipboard != undefined)
+str.itIsAlreadyInClipboard
}
p {
a {
attrs {
href = gameUrl
target = "_blank"
}
+gameUrl
}
}
}
mDialogActions {
mButton(str.ok, MColor.primary, MButtonVariant.contained, onClick = { props.onClosed() })
}
}
}
private inner class Strings : LocalizedStrings({ props.locale }) {
val sendThisLinkToOtherPlayers by loc(
Locale.En to "Send this link to other players",
Locale.Ru to "Отправьте эту ссылку другим игрокам"
)
val itIsAlreadyInClipboard by loc(
Locale.En to " (it is already in your clipboard)",
Locale.Ru to " (она уже скопирована в буфер обмена)"
)
val ok by loc(Locale.En to "OK", Locale.Ru to "OK")
}
private val str = Strings()
}
fun RBuilder.showGameIdScreen(builder: ShowGameIdScreenProps.() -> Unit) {
child(ShowGameIdScreen::class) {
attrs {
builder()
}
}
} | 1 | null | 4 | 9 | 72392461e81d7fe9a877c43af108721e3eecb619 | 2,524 | TicketToRide | MIT License |
identity-sdjwt/src/main/java/com/android/identity/sdjwt/util/JsonWebKey.kt | openwallet-foundation-labs | 248,844,077 | false | {"Kotlin": 4132186, "Java": 591756, "JavaScript": 33071, "Swift": 28030, "HTML": 12029, "Shell": 372, "CSS": 200, "C": 104} | package com.android.identity.sdjwt.util
import com.android.identity.crypto.EcCurve
import com.android.identity.crypto.EcPublicKey
import com.android.identity.crypto.EcPublicKeyDoubleCoordinate
import com.android.identity.crypto.EcPublicKeyOkp
import com.android.identity.util.fromBase64Url
import com.android.identity.util.toBase64Url
import kotlinx.serialization.json.JsonObject
import kotlinx.serialization.json.JsonObjectBuilder
import kotlinx.serialization.json.JsonPrimitive
import kotlinx.serialization.json.buildJsonObject
import kotlinx.serialization.json.jsonObject
import kotlinx.serialization.json.jsonPrimitive
/**
* A JsonWeb(Public)Key, which can be serialized into JSON, or converted into
* a [EcPublicKey] object. It can be initialized either from a [EcPublicKey], or
* from a [JsonObject].
*
* The JSON object expected during initialization, and returned when converting
* this JsonWebKey to JSON, has the format:
*
* {
* jwk: {
* kty: ...
* crv: ...
* ...
* }
* }
*
*/
class JsonWebKey {
private val pubKey: EcPublicKey
constructor(pubKey: EcPublicKey) {
this.pubKey = pubKey
}
constructor(jwk: JsonObject) {
pubKey = jwk.getObject("jwk").toEcPublicKey
}
val asEcPublicKey: EcPublicKey
get() = pubKey
val asJwk: JsonObject
get() = buildJsonObject {
put("jwk", toRawJwk {})
}
fun toRawJwk(block: JsonObjectBuilder.() -> Unit): JsonObject {
return buildJsonObject {
when (pubKey) {
is EcPublicKeyOkp -> {
put("kty", JsonPrimitive("OKP"))
put("crv", JsonPrimitive(pubKey.curve.jwkName))
put("x", JsonPrimitive(pubKey.x.toBase64Url()))
}
is EcPublicKeyDoubleCoordinate -> {
put("kty", JsonPrimitive("EC"))
put("crv", JsonPrimitive(pubKey.curve.jwkName))
put("x", JsonPrimitive(pubKey.x.toBase64Url()))
put("y", JsonPrimitive(pubKey.y.toBase64Url()))
}
else -> throw IllegalStateException("Unsupported key $pubKey")
}
block()
}
}
private companion object {
fun convertJwkToEcPublicKey(key: JsonObject): EcPublicKey {
return when(val kty = key.getString("kty")) {
"OKP" -> {
EcPublicKeyOkp(
EcCurve.fromJwkName(key.getString("crv")),
key.getString("x").fromBase64Url()
)
}
"EC" -> {
EcPublicKeyDoubleCoordinate(
EcCurve.fromJwkName(key.getString("crv")),
key.getString("x").fromBase64Url(),
key.getString("y").fromBase64Url()
)
}
else -> throw IllegalArgumentException("Not supporting key type $kty")
}
}
private fun JsonObject.getString(key: String): String {
return this[key]?.jsonPrimitive?.content
?: throw IllegalStateException("missing or invalid '$key' entry in JWK $this")
}
}
private fun JsonObject.getObject(key: String): JsonObject {
return this[key]?.jsonObject
?: throw IllegalStateException("missing or invalid '$key' entry in JWK $this")
}
private val JsonObject.toEcPublicKey: EcPublicKey
get() = convertJwkToEcPublicKey(this)
}
| 99 | Kotlin | 83 | 163 | e6bf25766985521b9a39d4ed7999f22d57064db5 | 3,595 | identity-credential | Apache License 2.0 |
analytics/src/main/java/video/api/player/analytics/Options.kt | apivideo | 435,570,950 | false | null | package video.api.player.analytics
import java.io.IOException
import java.net.URL
/**
* The api.video video type.
*/
enum class VideoType(val type: String) {
/** Video is a live stream */
LIVE("live"),
/** Video is a video on demand */
VOD("vod")
}
/**
* Converts String to a [VideoType].
*
* @return corresponding [VideoType] or an exception
*/
fun String.toVideoType(): VideoType {
VideoType.values().forEach {
if (it.type == this) {
return it
}
}
throw IOException("Can't determine if video is vod or live.")
}
/**
* A class that describes a video from api.video.
* For custom domain, you must use this class.
* For custom VOD domain or custom live domain, you must use [VideoInfo.fromMediaURL].
*
* @param videoId the video id
* @param videoType the video type
* @param collectorDomainURL the URL for player analytics collector. Only for if you use a custom collector domain.
*/
data class VideoInfo(
val videoId: String,
val videoType: VideoType,
val collectorDomainURL: URL = URL(Options.DEFAULT_COLLECTOR_DOMAIN_URL)
) {
/**
* @param videoId the video id
* @param videoType the video type
* @param collectorDomainURL the URL for the player analytics collector. Only if you have a custom collector domain.
*/
constructor(videoId: String, videoType: VideoType, collectorDomainURL: String) : this(
videoId,
videoType,
URL(collectorDomainURL)
)
/**
* The URL for player analytics collector
*/
val pingUrl = "${collectorDomainURL}/${videoType.type}"
companion object {
/**
* Creates a [VideoInfo] from a media URL.
*
* @param mediaUrl the media URL to parse
* @param collectorDomainURL the URL for the player analytics collector. Only if you have a custom collector domain.
*/
fun fromMediaURL(
mediaUrl: URL,
collectorDomainURL: URL = URL(Options.DEFAULT_COLLECTOR_DOMAIN_URL)
): VideoInfo {
return Utils.parseMediaUrl(
mediaUrl,
collectorDomainURL
)
}
/**
* Creates a [VideoInfo] from a media URL.
*
* @param mediaUrl the media URL to parse
* @param collectorDomainURL the URL for the player analytics collector. Only if you have a custom collector domain.
*/
fun fromMediaURL(
mediaUrl: String,
collectorDomainURL: String = Options.DEFAULT_COLLECTOR_DOMAIN_URL
) = fromMediaURL(
URL(mediaUrl),
URL(collectorDomainURL),
)
}
}
/**
* An option class to configure the player analytics.
*
* @param videoInfo the video info. For custom domains, you must use this API.
* @param metadata the user metadata. See [metadata](https://api.video/blog/tutorials/dynamic-metadata).
* @param onSessionIdReceived the callback called when session id has been received
* @param onPing the callback called before sending [PlaybackPingMessage]
*/
data class Options(
val videoInfo: VideoInfo,
val metadata: Map<String, String> = emptyMap(),
val onSessionIdReceived: ((sessionId: String) -> Unit)? = null,
val onPing: ((message: PlaybackPingMessage) -> Unit)? = null
) {
/**
* @param mediaUrl the api.video URL of your video (for example: `https://vod.api.video/vod/vi5oDagRVJBSKHxSiPux5rYD/hls/manifest.m3u8`)
* @param metadata the user metadata. See [metadata](https://api.video/blog/tutorials/dynamic-metadata).
* @param onSessionIdReceived the callback called when session id has been received
* @param onPing the callback called before sending [PlaybackPingMessage]
*/
constructor(
mediaUrl: String,
metadata: Map<String, String> = emptyMap(),
onSessionIdReceived: ((sessionId: String) -> Unit)? = null,
onPing: ((message: PlaybackPingMessage) -> Unit)? = null
) : this(URL(mediaUrl), metadata, onSessionIdReceived, onPing)
/**
* @param mediaUrl the api.video URL of your video (for example: URL("https://vod.api.video/vod/vi5oDagRVJBSKHxSiPux5rYD/hls/manifest.m3u8"))
* @param metadata the user metadata. See [metadata](https://api.video/blog/tutorials/dynamic-metadata).
* @param onSessionIdReceived the callback called when session id has been received
* @param onPing the callback called before sending [PlaybackPingMessage]
*/
constructor(
mediaUrl: URL,
metadata: Map<String, String> = emptyMap(),
onSessionIdReceived: ((sessionId: String) -> Unit)? = null,
onPing: ((message: PlaybackPingMessage) -> Unit)? = null
) : this(
VideoInfo.fromMediaURL(mediaUrl),
metadata,
onSessionIdReceived,
onPing
)
companion object {
const val DEFAULT_COLLECTOR_DOMAIN_URL = "https://collector.api.video"
}
} | 0 | Kotlin | 1 | 12 | c38f7546a2d36344d4f2f0929d269e68d47f1ab8 | 4,955 | api.video-android-player-analytics | MIT License |
educational-core/src/com/jetbrains/edu/learning/codeforces/courseFormat/CodeforcesTask.kt | JetBrains | 43,696,115 | false | null | package com.jetbrains.edu.learning.codeforces.courseFormat
import com.intellij.openapi.diagnostic.Logger
import com.intellij.openapi.project.Project
import com.intellij.openapi.util.text.StringUtil.join
import com.intellij.openapi.vfs.VfsUtilCore.VFS_SEPARATOR_CHAR
import com.intellij.openapi.vfs.VirtualFile
import com.jetbrains.edu.learning.EduNames.GO
import com.jetbrains.edu.learning.EduNames.JAVA
import com.jetbrains.edu.learning.EduNames.JAVASCRIPT
import com.jetbrains.edu.learning.EduNames.KOTLIN
import com.jetbrains.edu.learning.EduNames.PYTHON
import com.jetbrains.edu.learning.EduNames.PYTHON_2_VERSION
import com.jetbrains.edu.learning.EduNames.PYTHON_3_VERSION
import com.jetbrains.edu.learning.EduNames.RUST
import com.jetbrains.edu.learning.EduNames.SCALA
import com.jetbrains.edu.learning.codeforces.CodeforcesLanguageProvider
import com.jetbrains.edu.learning.codeforces.CodeforcesNames
import com.jetbrains.edu.learning.codeforces.CodeforcesNames.CODEFORCES_SUBMIT
import com.jetbrains.edu.learning.codeforces.CodeforcesNames.CODEFORCES_TASK_TYPE
import com.jetbrains.edu.learning.codeforces.CodeforcesNames.TEST_DATA_FOLDER
import com.jetbrains.edu.learning.codeforces.CodeforcesUtils.isValidCodeforcesTestFolder
import com.jetbrains.edu.learning.courseDir
import com.jetbrains.edu.learning.courseFormat.DescriptionFormat
import com.jetbrains.edu.learning.courseFormat.Lesson
import com.jetbrains.edu.learning.courseFormat.TaskFile
import com.jetbrains.edu.learning.courseFormat.ext.getDir
import com.jetbrains.edu.learning.courseFormat.tasks.OutputTaskBase
import com.jetbrains.edu.learning.courseFormat.tasks.Task
import org.jsoup.nodes.Element
import org.jsoup.nodes.TextNode
open class CodeforcesTask : OutputTaskBase() {
override val itemType: String = CODEFORCES_TASK_TYPE
fun getTestFolders(project: Project): Array<out VirtualFile> {
return getDir(project.courseDir)?.findChild(TEST_DATA_FOLDER)?.children.orEmpty()
.filter { it.isValidCodeforcesTestFolder(this) }.toTypedArray()
}
private fun addSampleTests(htmlElement: Element) {
htmlElement.select("div.input").forEachIndexed { index, inputElement ->
val testFolderName = (index + 1).toString()
addTestTaskFile(inputElement, testFolderName, inputFileName)
val outputElement = inputElement.nextElementSibling() ?: error("HTML element is null")
addTestTaskFile(outputElement, testFolderName, outputFileName)
}
}
private fun addTestTaskFile(htmlElement: Element, testFolderName: String, fileName: String) {
val innerElement = htmlElement.select("pre")
if (innerElement.isEmpty()) {
error("Can't find HTML element with test data in ${htmlElement.text()}")
}
val firstInnerElement = innerElement.first() ?: error("Can't find HTML element with test data")
val text = firstInnerElement.childNodes().joinToString("") { node ->
when {
node is TextNode -> node.wholeText
node is Element && node.tagName() == "br" -> "\n"
node is Element && node.tagName() == "div" -> "${node.wholeText()}\n"
else -> {
LOG.info("Unexpected element: $node")
""
}
}
}.trimEnd()
val path = join(listOf(TEST_DATA_FOLDER, testFolderName, fileName), VFS_SEPARATOR_CHAR.toString())
addTaskFile(TaskFile(path, text))
}
companion object {
private val LOG: Logger = Logger.getInstance(CodeforcesTask::class.java)
fun create(htmlElement: Element, lesson: Lesson, index: Int): CodeforcesTask {
val isStandardIO = htmlElement.select("div.input-file, div.output-file").all { isStandardIOType(it) }
val task = if (isStandardIO) {
CodeforcesTask()
}
else {
val inputFileName = htmlElement.selectFirst("div.input-file")?.ownText() ?: error("No input file found")
val outputFileName = htmlElement.selectFirst("div.output-file")?.ownText() ?: error("No output file found")
CodeforcesTaskWithFileIO(inputFileName, outputFileName)
}
task.parent = lesson
task.index = index
// We don't have original problems ids here, so we have to use index to bind them with solutions
task.id = index
task.name = htmlElement.select("div.header").select("div.title").text()
htmlElement.select("img").forEach {
var srcValue = it.attr("src")
if (srcValue.startsWith(ESPRESSO_CODEFORCES_COM)) {
srcValue = srcValue.replace(ESPRESSO_CODEFORCES_COM, "https:$ESPRESSO_CODEFORCES_COM")
}
else if (srcValue.matches(URL_WITH_TRAILING_SLASH)) {
srcValue = srcValue.replace(TRAILING_SLASH, "${CodeforcesNames.CODEFORCES_URL}/")
}
it.attr("src", srcValue)
}
task.descriptionFormat = DescriptionFormat.HTML
htmlElement.getElementsByClass("test-example-line").append("\n").unwrap()
task.descriptionText = htmlElement.outerHtml()
// This replacement is needed for proper MathJax visualization
.replace("$$$", "$")
task.feedbackLink = codeforcesTaskLink(task)
CodeforcesLanguageProvider.generateTaskFiles(task)?.forEach {
task.addTaskFile(it)
}
val sampleTests = htmlElement.selectFirst("div.sample-test")
if (sampleTests != null) {
task.addSampleTests(sampleTests)
}
return task
}
fun codeforcesSubmitLink(task: Task): String {
val course = task.course as CodeforcesCourse
return "${course.getContestUrl()}/${CODEFORCES_SUBMIT}?locale=${course.languageCode}" +
"&programTypeId=${course.programTypeId ?: codeforcesDefaultProgramTypeId(course)}" +
"&submittedProblemIndex=${task.presentableName.substringBefore(".")}"
}
fun codeforcesTaskLink(task: Task): String {
val course = task.course as CodeforcesCourse
return "${course.getContestUrl()}/problem/${task.name.substringBefore(".")}?locale=${course.languageCode}"
}
@Deprecated("Only for backwards compatibility. Use CodeforcesCourse.programTypeId")
fun codeforcesDefaultProgramTypeId(course: CodeforcesCourse): String? {
val languageID = course.languageID
val languageVersion = course.languageVersion
return when {
GO == languageID -> GO_TYPE_ID
JAVA == languageID && "8" == languageVersion-> JAVA_8_TYPE_ID
JAVA == languageID && "11" == languageVersion -> JAVA_11_TYPE_ID
JAVASCRIPT == languageID -> JAVASCRIPT_TYPE_ID
KOTLIN == languageID -> KOTLIN_TYPE_ID
PYTHON == languageID && PYTHON_2_VERSION == languageVersion -> PYTHON_2_TYPE_ID
PYTHON == languageID && PYTHON_3_VERSION == languageVersion -> PYTHON_3_TYPE_ID
RUST == languageID -> RUST_TYPE_ID
SCALA == languageID -> SCALA_TYPE_ID
//only for tests
"TEXT" == languageID -> TEXT_TYPE_ID
else -> {
LOG.warn("Programming language was not detected: $languageID $languageVersion")
null
}
}?.toString()
}
private fun isStandardIOType(element: Element): Boolean {
val text = element.ownText()
return text.contains(STANDARD_INPUT_REGEX)
}
// For backwards compatibility. Don't use or update it
private const val GO_TYPE_ID = 32
private const val JAVA_8_TYPE_ID = 36
private const val JAVA_11_TYPE_ID = 60
private const val JAVASCRIPT_TYPE_ID = 34
private const val KOTLIN_TYPE_ID = 48
private const val PYTHON_2_TYPE_ID = 7
private const val PYTHON_3_TYPE_ID = 31
private const val RUST_TYPE_ID = 75
private const val SCALA_TYPE_ID = 20
//only for tests
private const val TEXT_TYPE_ID = 0
private const val ESPRESSO_CODEFORCES_COM = "//espresso.codeforces.com/"
private val TRAILING_SLASH = "^/".toRegex()
private val URL_WITH_TRAILING_SLASH = "^/.+".toRegex()
private val STANDARD_INPUT_REGEX = "^(standard|стандарт)[^.]*".toRegex()
}
} | 5 | null | 48 | 99 | cfc24fe13318de446b8adf6e05d1a7c15d9511b5 | 7,924 | educational-plugin | Apache License 2.0 |
components/src/androidTest/java/emperorfin/android/components/ui/utils/AuthenticationScreenTestUtil3.kt | emperorfin | 611,222,954 | false | null | /*
* Copyright 2023 Francis Nwokelo (emperorfin)
*
* 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 emperorfin.android.components.ui.utils
import android.content.Context
import androidx.compose.ui.test.*
import androidx.compose.ui.test.junit4.ComposeContentTestRule
import emperorfin.android.components.ui.extensions.semanticsmatcher.hasCircularProgressIndicatorColorArgb
import emperorfin.android.components.ui.res.theme.ComposeEmailAuthenticationTheme
import emperorfin.android.components.ui.screens.authentication.AuthenticationScreen
import emperorfin.android.components.ui.screens.authentication.uicomponents.tags.Tags.TAG_AUTHENTICATION_PROGRESS
import emperorfin.android.components.ui.screens.authentication.uicomponents.tags.Tags.TAG_AUTHENTICATION_SCREEN
import emperorfin.android.components.ui.constants.ColorArgbConstants.COLOR_ARGB_CIRCULAR_PROGRESS_INDICATOR_PRESET_COLOR
import emperorfin.android.components.ui.constants.StringConstants.THIS_STRING_MUST_BE_EMPTY
import emperorfin.android.components.ui.constants.StringConstants.THIS_STRING_COULD_BE_ANYTHING
import emperorfin.android.components.ui.constants.BooleanConstants.FALSE
import emperorfin.android.components.ui.constants.NothingConstants.NULL
/**
* @Author: Francis Nwokelo (emperorfin)
* @Date: Sunday 09th April, 2023.
*/
class AuthenticationScreenTestUtil3(
private val mContext: Context,
private val mTargetContext: Context,
private val composeTestRule: ComposeContentTestRule
) {
val authenticationButtonTestUtil3 = AuthenticationButtonTestUtil3(
mContext = mContext,
mTargetContext = mTargetContext,
composeTestRule = composeTestRule
)
val authenticationErrorDialogTestUtil3 = AuthenticationErrorDialogTestUtil3(
mContext = mContext,
mTargetContext = mTargetContext,
composeTestRule = composeTestRule
)
val authenticationTitleTestUtil3 = AuthenticationTitleTestUtil3(
mContext = mContext,
mTargetContext = mTargetContext,
composeTestRule = composeTestRule
)
val authenticationToggleModeTestUtil3 = AuthenticationToggleModeTestUtil3(
mContext = mContext,
mTargetContext = mTargetContext,
composeTestRule = composeTestRule
)
val emailInputTestUtil3 = EmailInputTestUtil3(
mContext = mContext,
mTargetContext = mTargetContext,
composeTestRule = composeTestRule
)
val passwordInputTestUtil3 = PasswordInputTestUtil3(
mContext = mContext,
mTargetContext = mTargetContext,
composeTestRule = composeTestRule
)
val passwordRequirementsTestUtil3 = PasswordRequirementsTestUtil3(
mContext = mContext,
mTargetContext = mTargetContext,
composeTestRule = composeTestRule
)
/**
* @param isSignInMode This is nullable should there's a case where
* [AuthenticationTitleTestUtil3.assertAuthenticationTitleAndTextExactlySignInToYourAccountIsDisplayed]
* or [navigateFromSignInToSignUpModesAndConfirmTitles] doesn't have to be run. But such case
* should be rare.
*/
fun setContentAsAuthenticationScreenAndAssertItIsDisplayed(
composeTestRule: ComposeContentTestRule = this.composeTestRule,
keyboardHelper: KeyboardHelper? = NULL,
isSignInMode: Boolean?
) {
setContentAsAuthenticationScreen(
composeTestRule = composeTestRule,
keyboardHelper = keyboardHelper
)
assertAuthenticationScreenIsDisplayed(composeTestRule)
isSignInMode?.let {
if (it) {
authenticationTitleTestUtil3.assertAuthenticationTitleAndTextExactlySignInToYourAccountIsDisplayed(
composeTestRule = composeTestRule
)
} else {
navigateFromSignInToSignUpModesAndConfirmTitles(composeTestRule = composeTestRule)
}
}
}
private fun setContentAsAuthenticationScreen(
composeTestRule: ComposeContentTestRule, keyboardHelper: KeyboardHelper?
) {
composeTestRule.setContent {
keyboardHelper?.initialize()
ComposeEmailAuthenticationTheme {
AuthenticationScreen()
}
}
}
private fun navigateFromSignInToSignUpModesAndConfirmTitles(
composeTestRule: ComposeContentTestRule = this.composeTestRule
) {
authenticationTitleTestUtil3.assertAuthenticationTitleAndTextExactlySignInToYourAccountIsDisplayed(composeTestRule)
authenticationToggleModeTestUtil3.onNodeWithAuthenticationToggleModeAndTextExactlyNeedAnAccount()
.performClick()
assertAuthenticationScreenIsDisplayed(composeTestRule)
authenticationTitleTestUtil3.assertAuthenticationTitleAndTextExactlySignUpForAnAccountIsDisplayed(composeTestRule)
}
/**
* This should be called in all test cases immediately after composing the [AuthenticationScreen]
* composable in the [ComposeContentTestRule.setContent]
*/
private fun assertAuthenticationScreenIsDisplayed(
composeTestRule: ComposeContentTestRule = this.composeTestRule
) {
onNodeWithAuthenticationScreen()
.assertIsDisplayed()
}
fun onNodeWithAuthenticationScreen(
useUnmergedTree: Boolean = FALSE
): SemanticsNodeInteraction {
return onNodeWithAuthenticationScreenAnd(
otherMatcher = hasTextExactly(
THIS_STRING_COULD_BE_ANYTHING,
includeEditableText = FALSE
).not(),
useUnmergedTree = useUnmergedTree
)
}
fun onNodeWithCircularProgressIndicatorAndCircularProgressIndicatorColorArgbPresetColor(
useUnmergedTree: Boolean = FALSE
): SemanticsNodeInteraction {
return onNodeWithCircularProgressIndicatorAnd(
otherMatcher = hasCircularProgressIndicatorColorArgbPresetColor(),
useUnmergedTree = useUnmergedTree
)
}
fun onNodeWithPasswordInputTrailingIcon(
useUnmergedTree: Boolean = FALSE
): SemanticsNodeInteraction {
return passwordInputTestUtil3.onNodeWithPasswordInputTrailingIconAnd(
otherMatcher = hasTextExactly(
THIS_STRING_COULD_BE_ANYTHING,
includeEditableText = FALSE
).not(),
useUnmergedTree = useUnmergedTree
)
}
private fun onNodeWithAuthenticationScreenAnd(
composeTestRule: ComposeContentTestRule = this.composeTestRule,
useUnmergedTree: Boolean = FALSE,
otherMatcher: SemanticsMatcher
): SemanticsNodeInteraction {
return composeTestRule
.onNode(
matcher = hasTestTagAuthenticationScreen().and(
other = otherMatcher
),
useUnmergedTree = useUnmergedTree
)
}
private fun onNodeWithCircularProgressIndicatorAnd(
composeTestRule: ComposeContentTestRule = this.composeTestRule,
useUnmergedTree: Boolean = FALSE,
otherMatcher: SemanticsMatcher
): SemanticsNodeInteraction {
return composeTestRule
.onNode(
matcher = hasTestTagCircularProgressIndicator().and(
other = otherMatcher
),
useUnmergedTree = useUnmergedTree
)
}
private fun hasTestTagAuthenticationScreen(): SemanticsMatcher {
return hasTestTagsAuthenticationScreenAnd(
otherTestTag = THIS_STRING_MUST_BE_EMPTY
)
}
private fun hasTestTagCircularProgressIndicator(): SemanticsMatcher {
return hasTestTagsCircularProgressIndicatorAnd(
otherTestTag = THIS_STRING_MUST_BE_EMPTY
)
}
private fun hasTestTagsAuthenticationScreenAnd(otherTestTag: String): SemanticsMatcher {
return hasTestTag(
testTag = TAG_AUTHENTICATION_SCREEN + otherTestTag
)
}
private fun hasTestTagsCircularProgressIndicatorAnd(otherTestTag: String): SemanticsMatcher {
return hasTestTag(
testTag = TAG_AUTHENTICATION_PROGRESS + otherTestTag
)
}
// Before using a semantics matcher, check the implementation of the utility functions in this
// section if it's already available to avoid duplication.
// The function names make the check easier.
private fun hasCircularProgressIndicatorColorArgbPresetColor(): SemanticsMatcher {
return hasCircularProgressIndicatorColorArgb(
circularProgressIndicatorColorInArgb =
COLOR_ARGB_CIRCULAR_PROGRESS_INDICATOR_PRESET_COLOR
)
}
fun hasTestTagCircularProgressIndicatorAndHasCircularProgressIndicatorColorArgbPresetColor():
SemanticsMatcher {
return hasTestTagCircularProgressIndicator().and(
other = hasCircularProgressIndicatorColorArgbPresetColor()
)
}
fun hasTestTagAuthenticationErrorDialogAndHasAlertDialogTitleWhoops(): SemanticsMatcher {
return authenticationErrorDialogTestUtil3.hasTestTagAuthenticationErrorDialog().and(
other = authenticationErrorDialogTestUtil3.hasAlertDialogTitleWhoops()
)
}
fun hasTestTagAuthenticationTitleAndHasTextExactlySignInToYourAccount(): SemanticsMatcher {
return authenticationTitleTestUtil3.hasTestTagAuthenticationTitle().and(
other = authenticationTitleTestUtil3.hasTextExactlySignInToYourAccount()
)
}
fun hasTestTagAuthenticationTitleAndHasTextExactlySignUpForAnAccount(): SemanticsMatcher {
return authenticationTitleTestUtil3.hasTestTagAuthenticationTitle().and(
other = authenticationTitleTestUtil3.hasTextExactlySignUpForAnAccount()
)
}
} | 0 | Kotlin | 0 | 28 | e0d9ad8b2b0fc13087d602b88b0c64cf6dddb3c2 | 10,354 | MilitaryJet | Apache License 2.0 |
components/src/androidTest/java/emperorfin/android/components/ui/utils/AuthenticationScreenTestUtil3.kt | emperorfin | 611,222,954 | false | null | /*
* Copyright 2023 Francis Nwokelo (emperorfin)
*
* 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 emperorfin.android.components.ui.utils
import android.content.Context
import androidx.compose.ui.test.*
import androidx.compose.ui.test.junit4.ComposeContentTestRule
import emperorfin.android.components.ui.extensions.semanticsmatcher.hasCircularProgressIndicatorColorArgb
import emperorfin.android.components.ui.res.theme.ComposeEmailAuthenticationTheme
import emperorfin.android.components.ui.screens.authentication.AuthenticationScreen
import emperorfin.android.components.ui.screens.authentication.uicomponents.tags.Tags.TAG_AUTHENTICATION_PROGRESS
import emperorfin.android.components.ui.screens.authentication.uicomponents.tags.Tags.TAG_AUTHENTICATION_SCREEN
import emperorfin.android.components.ui.constants.ColorArgbConstants.COLOR_ARGB_CIRCULAR_PROGRESS_INDICATOR_PRESET_COLOR
import emperorfin.android.components.ui.constants.StringConstants.THIS_STRING_MUST_BE_EMPTY
import emperorfin.android.components.ui.constants.StringConstants.THIS_STRING_COULD_BE_ANYTHING
import emperorfin.android.components.ui.constants.BooleanConstants.FALSE
import emperorfin.android.components.ui.constants.NothingConstants.NULL
/**
* @Author: Francis Nwokelo (emperorfin)
* @Date: Sunday 09th April, 2023.
*/
class AuthenticationScreenTestUtil3(
private val mContext: Context,
private val mTargetContext: Context,
private val composeTestRule: ComposeContentTestRule
) {
val authenticationButtonTestUtil3 = AuthenticationButtonTestUtil3(
mContext = mContext,
mTargetContext = mTargetContext,
composeTestRule = composeTestRule
)
val authenticationErrorDialogTestUtil3 = AuthenticationErrorDialogTestUtil3(
mContext = mContext,
mTargetContext = mTargetContext,
composeTestRule = composeTestRule
)
val authenticationTitleTestUtil3 = AuthenticationTitleTestUtil3(
mContext = mContext,
mTargetContext = mTargetContext,
composeTestRule = composeTestRule
)
val authenticationToggleModeTestUtil3 = AuthenticationToggleModeTestUtil3(
mContext = mContext,
mTargetContext = mTargetContext,
composeTestRule = composeTestRule
)
val emailInputTestUtil3 = EmailInputTestUtil3(
mContext = mContext,
mTargetContext = mTargetContext,
composeTestRule = composeTestRule
)
val passwordInputTestUtil3 = PasswordInputTestUtil3(
mContext = mContext,
mTargetContext = mTargetContext,
composeTestRule = composeTestRule
)
val passwordRequirementsTestUtil3 = PasswordRequirementsTestUtil3(
mContext = mContext,
mTargetContext = mTargetContext,
composeTestRule = composeTestRule
)
/**
* @param isSignInMode This is nullable should there's a case where
* [AuthenticationTitleTestUtil3.assertAuthenticationTitleAndTextExactlySignInToYourAccountIsDisplayed]
* or [navigateFromSignInToSignUpModesAndConfirmTitles] doesn't have to be run. But such case
* should be rare.
*/
fun setContentAsAuthenticationScreenAndAssertItIsDisplayed(
composeTestRule: ComposeContentTestRule = this.composeTestRule,
keyboardHelper: KeyboardHelper? = NULL,
isSignInMode: Boolean?
) {
setContentAsAuthenticationScreen(
composeTestRule = composeTestRule,
keyboardHelper = keyboardHelper
)
assertAuthenticationScreenIsDisplayed(composeTestRule)
isSignInMode?.let {
if (it) {
authenticationTitleTestUtil3.assertAuthenticationTitleAndTextExactlySignInToYourAccountIsDisplayed(
composeTestRule = composeTestRule
)
} else {
navigateFromSignInToSignUpModesAndConfirmTitles(composeTestRule = composeTestRule)
}
}
}
private fun setContentAsAuthenticationScreen(
composeTestRule: ComposeContentTestRule, keyboardHelper: KeyboardHelper?
) {
composeTestRule.setContent {
keyboardHelper?.initialize()
ComposeEmailAuthenticationTheme {
AuthenticationScreen()
}
}
}
private fun navigateFromSignInToSignUpModesAndConfirmTitles(
composeTestRule: ComposeContentTestRule = this.composeTestRule
) {
authenticationTitleTestUtil3.assertAuthenticationTitleAndTextExactlySignInToYourAccountIsDisplayed(composeTestRule)
authenticationToggleModeTestUtil3.onNodeWithAuthenticationToggleModeAndTextExactlyNeedAnAccount()
.performClick()
assertAuthenticationScreenIsDisplayed(composeTestRule)
authenticationTitleTestUtil3.assertAuthenticationTitleAndTextExactlySignUpForAnAccountIsDisplayed(composeTestRule)
}
/**
* This should be called in all test cases immediately after composing the [AuthenticationScreen]
* composable in the [ComposeContentTestRule.setContent]
*/
private fun assertAuthenticationScreenIsDisplayed(
composeTestRule: ComposeContentTestRule = this.composeTestRule
) {
onNodeWithAuthenticationScreen()
.assertIsDisplayed()
}
fun onNodeWithAuthenticationScreen(
useUnmergedTree: Boolean = FALSE
): SemanticsNodeInteraction {
return onNodeWithAuthenticationScreenAnd(
otherMatcher = hasTextExactly(
THIS_STRING_COULD_BE_ANYTHING,
includeEditableText = FALSE
).not(),
useUnmergedTree = useUnmergedTree
)
}
fun onNodeWithCircularProgressIndicatorAndCircularProgressIndicatorColorArgbPresetColor(
useUnmergedTree: Boolean = FALSE
): SemanticsNodeInteraction {
return onNodeWithCircularProgressIndicatorAnd(
otherMatcher = hasCircularProgressIndicatorColorArgbPresetColor(),
useUnmergedTree = useUnmergedTree
)
}
fun onNodeWithPasswordInputTrailingIcon(
useUnmergedTree: Boolean = FALSE
): SemanticsNodeInteraction {
return passwordInputTestUtil3.onNodeWithPasswordInputTrailingIconAnd(
otherMatcher = hasTextExactly(
THIS_STRING_COULD_BE_ANYTHING,
includeEditableText = FALSE
).not(),
useUnmergedTree = useUnmergedTree
)
}
private fun onNodeWithAuthenticationScreenAnd(
composeTestRule: ComposeContentTestRule = this.composeTestRule,
useUnmergedTree: Boolean = FALSE,
otherMatcher: SemanticsMatcher
): SemanticsNodeInteraction {
return composeTestRule
.onNode(
matcher = hasTestTagAuthenticationScreen().and(
other = otherMatcher
),
useUnmergedTree = useUnmergedTree
)
}
private fun onNodeWithCircularProgressIndicatorAnd(
composeTestRule: ComposeContentTestRule = this.composeTestRule,
useUnmergedTree: Boolean = FALSE,
otherMatcher: SemanticsMatcher
): SemanticsNodeInteraction {
return composeTestRule
.onNode(
matcher = hasTestTagCircularProgressIndicator().and(
other = otherMatcher
),
useUnmergedTree = useUnmergedTree
)
}
private fun hasTestTagAuthenticationScreen(): SemanticsMatcher {
return hasTestTagsAuthenticationScreenAnd(
otherTestTag = THIS_STRING_MUST_BE_EMPTY
)
}
private fun hasTestTagCircularProgressIndicator(): SemanticsMatcher {
return hasTestTagsCircularProgressIndicatorAnd(
otherTestTag = THIS_STRING_MUST_BE_EMPTY
)
}
private fun hasTestTagsAuthenticationScreenAnd(otherTestTag: String): SemanticsMatcher {
return hasTestTag(
testTag = TAG_AUTHENTICATION_SCREEN + otherTestTag
)
}
private fun hasTestTagsCircularProgressIndicatorAnd(otherTestTag: String): SemanticsMatcher {
return hasTestTag(
testTag = TAG_AUTHENTICATION_PROGRESS + otherTestTag
)
}
// Before using a semantics matcher, check the implementation of the utility functions in this
// section if it's already available to avoid duplication.
// The function names make the check easier.
private fun hasCircularProgressIndicatorColorArgbPresetColor(): SemanticsMatcher {
return hasCircularProgressIndicatorColorArgb(
circularProgressIndicatorColorInArgb =
COLOR_ARGB_CIRCULAR_PROGRESS_INDICATOR_PRESET_COLOR
)
}
fun hasTestTagCircularProgressIndicatorAndHasCircularProgressIndicatorColorArgbPresetColor():
SemanticsMatcher {
return hasTestTagCircularProgressIndicator().and(
other = hasCircularProgressIndicatorColorArgbPresetColor()
)
}
fun hasTestTagAuthenticationErrorDialogAndHasAlertDialogTitleWhoops(): SemanticsMatcher {
return authenticationErrorDialogTestUtil3.hasTestTagAuthenticationErrorDialog().and(
other = authenticationErrorDialogTestUtil3.hasAlertDialogTitleWhoops()
)
}
fun hasTestTagAuthenticationTitleAndHasTextExactlySignInToYourAccount(): SemanticsMatcher {
return authenticationTitleTestUtil3.hasTestTagAuthenticationTitle().and(
other = authenticationTitleTestUtil3.hasTextExactlySignInToYourAccount()
)
}
fun hasTestTagAuthenticationTitleAndHasTextExactlySignUpForAnAccount(): SemanticsMatcher {
return authenticationTitleTestUtil3.hasTestTagAuthenticationTitle().and(
other = authenticationTitleTestUtil3.hasTextExactlySignUpForAnAccount()
)
}
} | 0 | Kotlin | 0 | 28 | e0d9ad8b2b0fc13087d602b88b0c64cf6dddb3c2 | 10,354 | MilitaryJet | Apache License 2.0 |
src/main/kotlin/net/zero9178/mbed/editor/MbedAppLibDaemon.kt | zero9178 | 188,723,282 | false | null | package net.zero9178.mbed.editor
import com.intellij.openapi.editor.EditorFactory
import com.intellij.openapi.editor.event.DocumentEvent
import com.intellij.openapi.editor.event.DocumentListener
import com.intellij.openapi.fileEditor.FileDocumentManager
import com.intellij.openapi.project.Project
import com.intellij.openapi.startup.StartupActivity
import com.intellij.openapi.util.Key
import com.intellij.openapi.vfs.newvfs.BulkFileListener
import com.intellij.openapi.vfs.newvfs.events.VFileCreateEvent
import com.intellij.openapi.vfs.newvfs.events.VFileDeleteEvent
import com.intellij.openapi.vfs.newvfs.events.VFileEvent
import com.intellij.ui.EditorNotifications
import com.intellij.util.io.exists
import com.intellij.util.messages.Topic
import net.zero9178.mbed.gui.MbedPackagesView
import net.zero9178.mbed.state.MbedProjectState
import java.nio.file.Paths
/**
* Per project component which records if any files called mbed_lib.json or mbed_app.json have changed since last
* cmake regeneration. Sets NEEDS_RELOAD on the project when needed
*/
class MbedAppLibDaemon : StartupActivity.Background {
companion object {
val PROJECT_NEEDS_RELOAD = Key<Boolean>("MBED_NEEDS_RELOAD")
@JvmStatic
val PROJECT_IS_MBED_PROJECT = Key<Boolean>("IS_MBED_PROJECT")
@JvmStatic
val MBED_PROJECT_CHANGED = Topic.create("MBED_PROJECT_CHANGED", MbedAppListener::class.java)
}
interface MbedAppListener {
fun statusChanged(isMbedProject: Boolean) {}
}
override fun runActivity(project: Project) {
val basePath = project.basePath ?: return
val exists = Paths.get(basePath).resolve("mbed_app.json").exists()
project.putUserData(PROJECT_IS_MBED_PROJECT, exists)
project.messageBus.syncPublisher(MBED_PROJECT_CHANGED).statusChanged(exists)
if (exists) {
MbedPackagesView.getInstance(project).refreshTree()
}
EditorFactory.getInstance().eventMulticaster.addDocumentListener(object : DocumentListener {
override fun documentChanged(event: DocumentEvent) {
val vfs =
FileDocumentManager.getInstance().getFile(event.document) ?: return super.documentChanged(event)
if (vfs.name.toLowerCase() == "mbed_lib.json" || vfs.name.toLowerCase() == "mbed_app.json") {
project.putUserData(PROJECT_NEEDS_RELOAD, true)
EditorNotifications.getInstance(project).updateNotifications(vfs)
}
super.documentChanged(event)
}
}, MbedProjectState.getInstance(project))
}
}
private class MbedAppFileListener(private val project: Project) : BulkFileListener {
override fun after(events: MutableList<out VFileEvent>) {
val basePath = project.basePath ?: return
events.forEach {
val path = it.file?.path ?: return@forEach
if (Paths.get(path) == Paths.get(basePath).resolve("mbed_app.json")) {
val value = when (it) {
is VFileCreateEvent -> true
is VFileDeleteEvent -> false
else -> return@forEach
}
project.putUserData(MbedAppLibDaemon.PROJECT_IS_MBED_PROJECT, value)
project.messageBus.syncPublisher(MbedAppLibDaemon.MBED_PROJECT_CHANGED).statusChanged(value)
}
}
}
} | 2 | Kotlin | 1 | 9 | 6a3e8f6aa271bc30929bd03285a113dda218f022 | 3,422 | Mbed-Support-for-CLion | MIT License |
src/main/kotlin/dev/shtanko/algorithms/search/LinearSearch.kt | ashtanko | 515,874,521 | false | null | /*
* MIT License
* Copyright (c) 2022 <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 dev.shtanko.algorithms.search
/**
* Linear search is an algorithm which finds the position of a target value within an array (Usually unsorted)
*
* Worst-case performance O(n)
* Best-case performance O(1)
* Average performance O(n)
* Worst-case space complexity O(1)
*/
class LinearSearch<T> : AbstractSearchStrategy<T> {
override fun perform(arr: Array<T>, element: T): Int {
for ((i, a) in arr.withIndex()) {
if (a == element) {
return i
}
}
return -1
}
}
| 2 | Kotlin | 1 | 9 | ee3d5c874d2cb1ee88027ca5f214f876676e57b0 | 1,690 | the-algorithms | MIT License |
chronolens-cli/src/main/kotlin/org/chronolens/Subcommands.kt | andreihh | 83,168,079 | false | null | /*
* Copyright 2017-2021 <NAME> <<EMAIL>>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.chronolens
import org.chronolens.core.cli.Subcommand
import org.chronolens.core.cli.exit
import org.chronolens.core.model.sourcePath
import org.chronolens.core.model.walkSourceTree
import org.chronolens.core.repository.PersistentRepository
import org.chronolens.core.repository.PersistentRepository.Companion.persist
import org.chronolens.core.repository.PersistentRepository.ProgressListener
import java.io.File
class LsTree : Subcommand() {
override val help: String get() = """
Prints all the interpretable files of the repository from the specified
revision.
"""
private val rev by option<String>()
.help("the inspected revision (default: the <head> revision)")
.validateRevision(::repository)
private val repository by lazy(::connect)
private val revision: String get() = rev ?: repository.getHeadId()
override fun run() {
repository.listSources(revision).forEach(::println)
}
}
class RevList : Subcommand() {
override val help: String get() = """
Prints all revisions on the path from the currently checked-out (<head>)
revision to the root of the revision tree / graph in chronological
order.
"""
override fun run() {
val repository = connect()
repository.listRevisions().forEach(::println)
}
}
class Model : Subcommand() {
override val help: String get() = """
Prints the interpreted model of the source node with the specified id as
it is found in the given revision of the repository.
The path separator is '/', types are separated by ':' and functions and
variables are separated by '#'.
"""
private val id by option<String>()
.help("the inspected source node").required().validateId()
private val rev by option<String>()
.help("the inspected revision (default: the <head> revision)")
.validateRevision(::repository)
private val repository by lazy(::connect)
private val revision: String get() = rev ?: repository.getHeadId()
override fun run() {
val path = id.sourcePath
val model = repository.getSource(path, revision)
?: exit("File '$path' couldn't be interpreted or doesn't exist!")
val node = model.walkSourceTree()
.find { it.qualifiedId == id }
?.sourceNode
?: exit("Source node '$id' doesn't exist!")
PrettyPrinterVisitor(System.out).visit(node)
}
}
class Persist : Subcommand() {
override val help: String get() = """
Connects to the repository and persists the source and history model
from all the files that can be interpreted.
The model is persisted in the '.chronolens' directory from the
current working directory.
"""
override fun run() {
val repository = connect()
repository.persist(
File(repositoryDirectory),
object : ProgressListener {
private var sources = 0
private var transactions = 0
private var i = 0
override fun onSnapshotStart(headId: String, sourceCount: Int) {
println("Persisting snapshot '$headId'...")
sources = sourceCount
i = 0
}
override fun onSourcePersisted(path: String) {
i++
print("Persisted $i / $sources sources...\r")
}
override fun onSnapshotEnd() {
println()
println("Done!")
}
override fun onHistoryStart(revisionCount: Int) {
println("Persisting transactions...")
transactions = revisionCount
i = 0
}
override fun onTransactionPersisted(id: String) {
i++
print("Persisted $i / $transactions transactions...\r")
}
override fun onHistoryEnd() {
println()
println("Done!")
}
}
)
}
}
class Clean : Subcommand() {
override val help: String get() = """
Deletes the previously persisted repository from the current working
directory, if it exists.
"""
override fun run() {
PersistentRepository.clean(File(repositoryDirectory))
}
}
| 0 | Kotlin | 1 | 4 | 4b6f97ce04256d56774c419159346a58fb8872c7 | 5,087 | chronolens | Apache License 2.0 |
src/main/kotlin/counters/minter/sdk/minter_api/MinterApi.kt | counters | 196,465,317 | false | null | package counters.minter.sdk.minter_api
import counters.minter.grpc.client.BlockField
import counters.minter.sdk.minter.*
import counters.minter.sdk.minter.MinterRaw.BlockRaw
import counters.minter.sdk.minter.MinterRaw.EventRaw
import counters.minter.sdk.minter.enum.QueryTags
import counters.minter.sdk.minter.enum.Subscribe
import counters.minter.sdk.minter.enum.SwapFromTypes
import counters.minter.sdk.minter.models.AddressRaw
import counters.minter.sdk.minter.models.BestTrade
import counters.minter.sdk.minter.models.BestTradeType
import counters.minter.sdk.minter.models.TransactionRaw
import counters.minter.sdk.minter_api.grpc.GrpcOptions
import counters.minter.sdk.minter_api.http.HttpOptions
import io.grpc.ManagedChannelBuilder
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.flow
import mu.KotlinLogging
class MinterApi(
grpcOptions: GrpcOptions? = null, httpOptions: HttpOptions? = null
) : MinterMatch() {
var exception = true
set(value) {
field = value
minterHttpApi?.exception = value
minterAsyncHttpApi?.exception = value
minterCoroutinesHttpApi?.exception = value
minterGrpcApi?.exception = value
minterGrpcApiCoroutines?.exception = value
}
private val logger = KotlinLogging.logger {}
private var minterHttpApi: MinterHttpApiOld? = null
private var minterAsyncHttpApi: MinterAsyncHttpApi? = null
private var minterGrpcApiCoroutines: MinterApiCoroutines? = null
private var minterGrpcApi: MinterGrpcApi? = null
private var minterCoroutinesHttpApi: MinterCoroutinesHttpApi? = null
init {
if (grpcOptions != null) {
val channelBuilder = ManagedChannelBuilder.forAddress(grpcOptions.hostname, grpcOptions.port)
if (grpcOptions.ssl_contest != null) {
// channelBuilder.useTransportSecurity(grpcOptions.ssl_contest)
// channelBuilder.sslContext(grpcOptions.ssl_contest)
} else if (grpcOptions.useTransportSecurity) {
channelBuilder.useTransportSecurity()
} else {
channelBuilder.usePlaintext()
}
minterGrpcApiCoroutines = MinterApiCoroutines(grpcOptions)
minterGrpcApi = MinterGrpcApi(grpcOptions)
} else if (httpOptions != null) {
val timeoutD = if (httpOptions.timeout != null) httpOptions.timeout.toDouble() / 1000.0 else null
minterHttpApi = MinterHttpApiOld(httpOptions.raw!!, timeoutD, httpOptions.headers)
minterAsyncHttpApi = MinterAsyncHttpApi(httpOptions)
minterCoroutinesHttpApi = MinterCoroutinesHttpApi(httpOptions = httpOptions)
} else {
throw Exception("grpcOptions = null && httpOptions = null")
TODO("grpcOptions = null && httpOptions = null")
}
}
fun shutdown() {
minterGrpcApiCoroutines?.shutdown()
minterGrpcApi?.shutdown()
}
fun getStatus(deadline: Long? = null): Minter.Status? {
if (minterHttpApi != null) {
return minterHttpApi!!.getStatus()
} else {
return minterGrpcApi!!.getStatus(deadline)
}
}
fun getStatus(deadline: Long? = null, result: ((result: Minter.Status?) -> Unit)) {
minterAsyncHttpApi?.let {
it.getStatus(deadline, result)
} ?: run {
minterGrpcApi!!.asyncStatus(deadline, result)
}
}
suspend fun getStatusCoroutines(deadline: Long? = null): Minter.Status? {
minterCoroutinesHttpApi?.let {
return it.getStatus(deadline)
} ?: run {
return minterGrpcApiCoroutines!!.getStatus(deadline)
}
}
fun getBlock(height: Long, deadline: Long? = null): BlockRaw? {
if (minterHttpApi != null) {
return minterHttpApi!!.getBlockRaw(height)
} else {
return minterGrpcApi!!.block(height, deadline)
}
}
fun getBlock(height: Long, fields: List<BlockField>? = null, failed_txs: Boolean? = null, deadline: Long? = null, result: ((result: BlockRaw?) -> Unit)) {
minterAsyncHttpApi?.let {
it.getBlock(height, deadline, result)
} ?: run {
minterGrpcApi!!.asyncBlock(height, fields, failed_txs, deadline, result)
}
}
suspend fun getBlockCoroutines(height: Long, fields: List<BlockField>? = null, failed_txs: Boolean? = null, deadline: Long? = null): BlockRaw? {
minterCoroutinesHttpApi?.let {
return it.getBlock(height, minterCoroutinesHttpApi!!.BlockFieldHashSet(fields), failed_txs, null, deadline)
} ?: run {
return minterGrpcApiCoroutines!!.getBlock(height, fields, failed_txs, deadline)
}
}
/* @Deprecated(level = DeprecationLevel.ERROR, message = "for test")
suspend fun test_getBlockCoroutines(height: Long, fields: List<BlockField>? = null, failed_txs: Boolean? = null, deadline: Long? = null): BlockRaw? {
minterAsyncHttpApi?.let {
return it.test_getBlock(height, deadline)
} ?: run {
return minterGrpcApiCoroutines!!.getBlock(height, fields, failed_txs, deadline)
}
}*/
fun getTransaction(hash: String, deadline: Long? = null): TransactionRaw? {
if (minterHttpApi != null) {
return minterHttpApi!!.getTransactionRaw(hash)
} else {
return minterGrpcApi!!.transaction(hash, deadline)
}
}
fun getTransaction(hash: String, deadline: Long? = null, result: ((result: TransactionRaw?) -> Unit)) {
minterAsyncHttpApi?.let {
it.getTransaction(hash, deadline, result)
} ?: run {
minterGrpcApi!!.asyncTransaction(hash, deadline, result)
}
}
suspend fun getTransactionCoroutines(hash: String, deadline: Long? = null): TransactionRaw? {
minterCoroutinesHttpApi?.let {
return it.getTransaction(hash, deadline)
/* }
minterAsyncHttpApi?.let {
// return minterHttpApi!!.getTransactionRaw(hash)
var status: TransactionRaw?=null
val semaphore = kotlinx.coroutines.sync.Semaphore(1, 1)
it.getTransaction(hash, deadline) {
status = it
semaphore.release()
}
semaphore.acquire()
return status*/
} ?: run {
return minterGrpcApiCoroutines!!.getTransaction(hash, deadline)
}
}
fun getTransactions(
query: Map<QueryTags, String>,
page: Int = 1,
per_page: Int? = null,
deadline: Long? = null
): List<TransactionRaw>? {
if (minterHttpApi != null) {
return minterHttpApi!!.getTransactionsRaw(query, page, per_page)
} else {
return minterGrpcApi!!.transactions(query, page, per_page, deadline)
}
}
fun getLimitOrder(orderId: Long, height: Long? = null, deadline: Long? = null): LimitOrderRaw? {
if (minterHttpApi != null) {
return minterHttpApi!!.getLimitOrder(orderId, height, deadline)
} else {
return minterGrpcApi!!.getLimitOrder(orderId, height, deadline)
}
}
fun getLimitOrder(orderId: Long, height: Long? = null, deadline: Long? = null, result: ((result: LimitOrderRaw?) -> Unit)) {
minterAsyncHttpApi?.let {
it.getLimitOrder(orderId, height, deadline, result)
} ?: run {
minterGrpcApi!!.getLimitOrder(orderId, height, deadline, result)
}
}
fun getLimitOrders(ids: List<Long>, height: Long? = null, deadline: Long? = null): List<LimitOrderRaw>? {
if (minterHttpApi != null) {
return minterHttpApi!!.getLimitOrders(ids, height, deadline)
} else {
return minterGrpcApi!!.getLimitOrders(ids, height, deadline)
}
}
fun getLimitOrders(ids: List<Long>, height: Long? = null, deadline: Long? = null, result: ((result: List<LimitOrderRaw>?) -> Unit)) {
minterAsyncHttpApi?.let {
it.getLimitOrders(ids, height, deadline, result)
} ?: run {
minterGrpcApi!!.getLimitOrders(ids, height, deadline, result)
}
}
fun getLimitOrdersOfPool(sellCoin: Long, buyCoin: Long, limit: Int? = null, height: Long? = null, deadline: Long? = null): List<LimitOrderRaw>? {
if (minterHttpApi != null) {
return minterHttpApi!!.getLimitOrdersOfPool(sellCoin, buyCoin, limit, height)
} else {
return minterGrpcApi!!.getLimitOrdersOfPool(sellCoin, buyCoin, limit, height, deadline)
}
}
fun getLimitOrdersOfPool(sellCoin: Long, buyCoin: Long, limit: Int? = null, height: Long? = null, deadline: Long? = null, result: ((result: List<LimitOrderRaw>?) -> Unit)) {
minterAsyncHttpApi?.let {
it.getLimitOrdersOfPool(sellCoin, buyCoin, limit, height, deadline, result)
} ?: run {
minterGrpcApi!!.getLimitOrdersOfPool(sellCoin, buyCoin, limit, height, deadline, result)
}
}
suspend fun getLimitOrdersCoroutines(ids: List<Long>, height: Long? = null, deadline: Long? = null): List<LimitOrderRaw>? {
minterCoroutinesHttpApi?.let {
return it.getLimitOrders(ids, height, deadline)
} ?: run {
return minterGrpcApiCoroutines!!.getLimitOrders(ids, height, deadline)
}
}
suspend fun getLimitOrderCoroutines(orderId: Long, height: Long? = null, deadline: Long? = null): LimitOrderRaw? {
minterCoroutinesHttpApi?.let {
return it.getLimitOrder(orderId, height, deadline)
} ?: run {
return minterGrpcApiCoroutines!!.getLimitOrder(orderId, height, deadline)
}
}
suspend fun getLimitOrdersOfPoolCoroutines(sellCoin: Long, buyCoin: Long, limit: Int? = null, height: Long? = null, deadline: Long? = null): List<LimitOrderRaw>? {
minterCoroutinesHttpApi?.let {
return it.getLimitOrdersOfPool(sellCoin, buyCoin, limit, height, deadline)
} ?: run {
return minterGrpcApiCoroutines!!.getLimitOrdersOfPool(sellCoin, buyCoin, limit, height, deadline)
}
}
fun getEvent(height: Long, search: List<String>? = null/*, addSymbol: Boolean = false*/, deadline: Long? = null): List<EventRaw>? {
if (minterHttpApi != null) {
return minterHttpApi!!.getEventsRaw(height, search)
} else {
return minterGrpcApi!!.getEvents(height, search, deadline)
}
}
fun getEvent(height: Long, search: List<String>? = null, deadline: Long? = null, result: ((result: List<EventRaw>?) -> Unit)) {
minterAsyncHttpApi?.let {
it.getEvents(height, search, deadline, result)
} ?: run {
minterGrpcApi!!.getEvents(height, search, deadline, result)
}
}
suspend fun getEventCoroutines(height: Long, search: List<String>? = null, deadline: Long? = null): List<EventRaw>? {
minterCoroutinesHttpApi?.let {
return it.getEvents(height, search, deadline)
} ?: run {
return minterGrpcApiCoroutines!!.getEvents(height, search, deadline)
}
}
fun getAddress(address: String, height: Long? = null, delegated: Boolean = false, deadline: Long? = null): AddressRaw? {
if (minterHttpApi != null) {
return minterHttpApi!!.getAddressRaw(address, height, delegated, deadline)
} else {
return minterGrpcApi!!.getAddress(address, height, delegated, deadline)
}
}
suspend fun getAddressCoroutines(address: String, height: Long? = null, delegated: Boolean? = null, deadline: Long? = null): AddressRaw? {
minterCoroutinesHttpApi?.let {
return it.getAddress(address, height, delegated, deadline)
} ?: run {
return minterGrpcApiCoroutines!!.getAddress(address, height, delegated, deadline)
}
}
fun getAddress(address: String, height: Long? = null, delegated: Boolean = false, deadline: Long? = null, result: ((result: AddressRaw?) -> Unit)) {
minterAsyncHttpApi?.let {
it.getAddress(address, height, delegated, deadline, result)
} ?: run {
minterGrpcApi!!.getAddress(address, height, delegated, deadline, result)
}
}
suspend fun estimateCoinSellCoroutines(
coinToSell: Long,
valueToSell: Double,
coinToBuy: Long = 0,
height: Long? = null,
coin_id_commission: Long? = null,
swap_from: SwapFromTypes? = null,
route: List<Long>? = null,
deadline: Long? = null,
// notFoundCoin: ((notFount: Boolean) -> Unit)? = null
): Coin.EstimateCoin? {
minterCoroutinesHttpApi?.let {
return it.estimateCoinSell(coinToSell, valueToSell, coinToBuy, height, coin_id_commission, swap_from, route, deadline/*, notFoundCoin*/)
} ?: run {
return minterGrpcApiCoroutines!!.estimateCoinSell(coinToSell, valueToSell, coinToBuy, height, coin_id_commission, swap_from, route, deadline/*, notFoundCoin*/)
}
}
fun estimateCoinSell(
coinToSell: Long,
valueToSell: Double,
coinToBuy: Long = 0,
height: Long? = null,
coin_id_commission: Long? = null,
swap_from: SwapFromTypes? = null,
route: List<Long>? = null,
deadline: Long? = null,
// notFoundCoin: ((notFount: Boolean) -> Unit)? = null
): Coin.EstimateCoin? {
if (minterHttpApi != null) {
return minterHttpApi!!.estimateCoinSell(coinToSell, valueToSell, coinToBuy, height, coin_id_commission, swap_from, route)
} else {
return minterGrpcApi!!.estimateCoinSell(coinToSell, getPip(valueToSell), coinToBuy, height, coin_id_commission, swap_from, route, deadline)
}
}
fun estimateCoinSell(
coinToSell: Long,
valueToSell: Double,
coinToBuy: Long = 0,
height: Long? = null,
coin_id_commission: Long? = null,
swap_from: SwapFromTypes? = null,
route: List<Long>? = null,
deadline: Long? = null,
result: ((result: Coin.EstimateCoin?) -> Unit)
) {
minterAsyncHttpApi?.let {
it.estimateCoinSell(coinToSell, valueToSell, coinToBuy, height, coin_id_commission, swap_from, route, deadline, result)
} ?: run {
minterGrpcApi!!.estimateCoinSell(coinToSell, getPip(valueToSell), coinToBuy, height, coin_id_commission, swap_from, route, deadline, result)
}
}
fun estimateCoinSellAll(
coinToSell: Long,
valueToSell: Double,
coinToBuy: Long = 0,
height: Long? = null,
gas_price: Int? = null,
swap_from: SwapFromTypes? = null,
route: List<Long>? = null,
deadline: Long? = null
): Coin.EstimateCoin? {
if (minterHttpApi != null) {
return minterHttpApi!!.estimateCoinIdSellAll(coinToSell, valueToSell, coinToBuy, height, gas_price?.toLong(), swap_from, route)
} else {
return minterGrpcApi!!.estimateCoinSellAll(coinToSell, getPip(valueToSell), coinToBuy, height, gas_price, swap_from, route, deadline)
}
}
fun estimateCoinSellAll(
coinToSell: Long,
valueToSell: Double,
coinToBuy: Long = 0,
height: Long? = null,
gas_price: Int? = null,
swap_from: SwapFromTypes? = null,
route: List<Long>? = null,
deadline: Long? = null,
result: ((result: Coin.EstimateCoin?) -> Unit)
) {
minterAsyncHttpApi?.let {
it.estimateCoinSellAll(coinToSell, valueToSell, coinToBuy, height, gas_price, swap_from, route, deadline, result)
} ?: run {
minterGrpcApi!!.estimateCoinSellAll(coinToSell, getPip(valueToSell), coinToBuy, height, gas_price, swap_from, route, deadline, result)
}
}
suspend fun estimateCoinSellAllCoroutines(
coinToSell: Long,
valueToSell: Double,
coinToBuy: Long = 0,
height: Long? = null,
gas_price: Int? = null,
swap_from: SwapFromTypes? = null,
route: List<Long>? = null,
deadline: Long? = null
): Coin.EstimateCoin? {
minterCoroutinesHttpApi?.let {
return it.estimateCoinSellAll(coinToSell, valueToSell, coinToBuy, height, gas_price, swap_from, route, deadline)
} ?: run {
return minterGrpcApiCoroutines!!.estimateCoinSellAll(coinToSell, valueToSell, coinToBuy, height, gas_price, swap_from, route, deadline)
}
}
fun estimateCoinBuy(
coinToBuy: Long,
valueToBuy: Double,
coinToSell: Long = 0,
height: Long? = null,
coin_id_commission: Long? = null,
swap_from: SwapFromTypes? = null,
route: List<Long>? = null,
deadline: Long? = null
): Coin.EstimateCoin? {
if (minterHttpApi != null) {
return minterHttpApi!!.estimateCoinIdBuy(coinToBuy, getPip(valueToBuy), coinToSell, height ?: 0/*, coin_id_commission, swap_from, route*/)
} else {
return minterGrpcApi!!.estimateCoinBuy(coinToBuy, getPip(valueToBuy), coinToSell, height, coin_id_commission, swap_from, route, deadline)
}
}
fun estimateCoinBuy(
coinToBuy: Long,
valueToBuy: Double,
coinToSell: Long = 0,
height: Long? = null,
coin_id_commission: Long? = null,
swap_from: SwapFromTypes? = null,
route: List<Long>? = null,
deadline: Long? = null,
result: (result: Coin.EstimateCoin?) -> Unit
) {
minterAsyncHttpApi?.let {
it.estimateCoinBuy(coinToBuy, valueToBuy, coinToSell, height, coin_id_commission, swap_from, route, deadline, result)
} ?: run {
minterGrpcApi!!.estimateCoinBuy(coinToBuy, getPip(valueToBuy), coinToSell, height, coin_id_commission, swap_from, route, deadline, result)
}
}
suspend fun estimateCoinBuyCoroutines(
coinToBuy: Long,
valueToBuy: Double,
coinToSell: Long = 0,
height: Long? = null,
coin_id_commission: Long? = null,
swap_from: SwapFromTypes? = null,
route: List<Long>? = null,
deadline: Long? = null,
): Coin.EstimateCoin? {
minterCoroutinesHttpApi?.let {
return it.estimateCoinBuy(coinToBuy, valueToBuy, coinToSell, height, coin_id_commission, swap_from, route, deadline/*, notFoundCoin*/)
} ?: run {
return minterGrpcApiCoroutines!!.estimateCoinBuy(coinToBuy, getPip(valueToBuy), coinToSell, height, coin_id_commission, swap_from, route, deadline/*, notFoundCoin*/)
}
}
private fun streamSubscribe(query: Subscribe, deadline: Long? = null, result: (result: Minter.Status?) -> Unit) {
minterAsyncHttpApi?.let {
it.streamSubscribe(query, deadline, result)
} ?: run {
minterGrpcApi!!.streamSubscribe(query, deadline, result)
}
}
private fun streamSubscribe(query: Subscribe, deadline: Long? = null): Minter.Status? {
var status: Minter.Status? = null
minterAsyncHttpApi?.let {
it.streamSubscribe(query, deadline) {
status = it
}
} ?: run {
minterGrpcApi!!.streamSubscribe(query, deadline) {
status = it
}
}
return status
}
suspend fun streamSubscribeStatusCoroutines(deadline: Long? = null): Flow<Minter.Status?> = flow {
minterCoroutinesHttpApi?.let {
it.streamSubscribeStatus(deadline).collect {
emit(it)
}
} ?: run {
// return minterGrpcApiCoroutines!!.streamSubscribeStatus(deadline)
minterGrpcApiCoroutines!!.streamSubscribeStatus(deadline).collect {
emit(it)
}
}
}
fun streamSubscribeStatus(deadline: Long? = null, result: (result: Minter.Status?) -> Unit) {
minterAsyncHttpApi?.let {
it.streamSubscribe(Subscribe.TmEventNewBlock, deadline, result)
} ?: run {
minterGrpcApi!!.streamSubscribe(Subscribe.TmEventNewBlock, deadline, result)
}
}
fun getSwapPool(coin0: Long, coin1: Long, height: Long? = null, deadline: Long? = null): MinterRaw.SwapPoolRaw? {
if (minterHttpApi != null) {
return minterHttpApi!!.getSwapPool(coin0, coin1, height/*, deadline*/)
} else {
return minterGrpcApi!!.getSwapPool(coin0, coin1, height, deadline)
}
}
fun getSwapPool(coin0: Long, coin1: Long, height: Long? = null, deadline: Long? = null, result: (result: MinterRaw.SwapPoolRaw?) -> Unit) {
minterAsyncHttpApi?.let {
it.getSwapPool(coin0, coin1, height, deadline, result)
} ?: run {
minterGrpcApi!!.getSwapPool(coin0, coin1, height, deadline, result)
}
}
suspend fun getSwapPoolCoroutines(coin0: Long, coin1: Long, height: Long? = null, deadline: Long? = null): MinterRaw.SwapPoolRaw? {
minterCoroutinesHttpApi?.let {
return it.getSwapPool(coin0, coin1, height, deadline)
} ?: run {
return minterGrpcApiCoroutines!!.getSwapPool(coin0, coin1, height, deadline)
}
}
fun getCoinInfo(coin: Long, height: Long? = null, deadline: Long? = null): MinterRaw.CoinRaw? {
return if (minterHttpApi != null) {
minterHttpApi!!.getCoinRaw(coin, height/*, deadline*/)
} else {
minterGrpcApi!!.getCoinInfo(coin, height, deadline)
}
}
fun getCoinInfo(coin: Long, height: Long? = null, deadline: Long? = null, result: (result: MinterRaw.CoinRaw?) -> Unit) {
minterAsyncHttpApi?.let {
it.getCoin(coin, height, deadline, result)
} ?: run {
minterGrpcApi!!.getCoinInfo(coin, height, deadline, result)
}
}
fun getCoinInfo(symbol: String, height: Long? = null, deadline: Long? = null): MinterRaw.CoinRaw? {
return if (minterHttpApi != null) {
minterHttpApi!!.getCoinRaw(symbol, height/*, deadline*/)
} else {
minterGrpcApi!!.getCoinInfo(symbol, height, deadline)
}
}
fun getCoinInfo(symbol: String, height: Long? = null, deadline: Long? = null, result: (result: MinterRaw.CoinRaw?) -> Unit) {
minterAsyncHttpApi?.let {
it.getCoin(symbol, height, deadline, result)
} ?: run {
minterGrpcApi!!.getCoinInfo(symbol, height, deadline, result)
}
}
suspend fun getCoinInfoCoroutines(coin: Long, height: Long? = null, deadline: Long? = null): MinterRaw.CoinRaw? {
minterCoroutinesHttpApi?.let {
return it.getCoinInfo(coin, height, deadline)
// return null
} ?: run {
return minterGrpcApiCoroutines!!.getCoinInfo(coin, height, deadline)
}
}
suspend fun getCoinInfoCoroutines(coin: String, height: Long? = null, deadline: Long? = null): MinterRaw.CoinRaw? {
minterCoroutinesHttpApi?.let {
return it.getCoinInfo(coin, height, deadline)
// return null
} ?: run {
return minterGrpcApiCoroutines!!.getCoinInfo(coin, height, deadline)
}
}
suspend fun getBestTradeCoroutines(
sellCoin: Long,
buyCoin: Long,
amount: Double,
type: BestTradeType,
maxDepth: Int? = null,
height: Long? = null,
deadline: Long? = null
): BestTrade? {
minterCoroutinesHttpApi?.let {
return it.getBestTrade(sellCoin, buyCoin, amount, type, maxDepth, height, deadline)
} ?: run {
return minterGrpcApiCoroutines!!.getBestTrade(sellCoin, buyCoin, amount, type, maxDepth, height, deadline)
}
}
}
| 0 | null | 3 | 7 | dd03cc8a1e0b4c21ceb03dbceff7b0fe4136d4ca | 23,943 | minter-kotlin-sdk | Apache License 2.0 |
test/src/test/kotlin/graphql/nadel/tests/hooks/chain-rename-transform.kt | atlassian-labs | 121,346,908 | false | null | package graphql.nadel.tests.hooks
import graphql.language.EnumValue
import graphql.language.StringValue
import graphql.nadel.Service
import graphql.nadel.ServiceExecutionHydrationDetails
import graphql.nadel.ServiceExecutionResult
import graphql.nadel.enginekt.NadelExecutionContext
import graphql.nadel.enginekt.blueprint.NadelOverallExecutionBlueprint
import graphql.nadel.enginekt.transform.NadelTransform
import graphql.nadel.enginekt.transform.NadelTransformFieldResult
import graphql.nadel.enginekt.transform.query.NadelQueryTransformer
import graphql.nadel.enginekt.transform.result.NadelResultInstruction
import graphql.nadel.enginekt.transform.result.json.JsonNodes
import graphql.nadel.enginekt.util.toBuilder
import graphql.nadel.tests.EngineTestHook
import graphql.nadel.tests.UseHook
import graphql.normalized.ExecutableNormalizedField
import graphql.normalized.NormalizedInputValue
private class ChainRenameTransform : NadelTransform<Any> {
override suspend fun isApplicable(
executionContext: NadelExecutionContext,
executionBlueprint: NadelOverallExecutionBlueprint,
services: Map<String, Service>,
service: Service,
overallField: ExecutableNormalizedField,
hydrationDetails: ServiceExecutionHydrationDetails?,
): Any? {
return overallField.takeIf { it.name == "test" || it.name == "cities" }
}
override suspend fun transformField(
executionContext: NadelExecutionContext,
transformer: NadelQueryTransformer,
executionBlueprint: NadelOverallExecutionBlueprint,
service: Service,
field: ExecutableNormalizedField,
state: Any,
): NadelTransformFieldResult {
if (field.normalizedArguments["arg"] != null) {
return NadelTransformFieldResult(
newField = field.toBuilder()
.normalizedArguments(field.normalizedArguments.let {
it + ("arg" to NormalizedInputValue("String", StringValue("aaarrg")))
})
.build(),
)
}
if (field.normalizedArguments["continent"] != null) {
return NadelTransformFieldResult(
newField = field.toBuilder()
.normalizedArguments(field.normalizedArguments.let {
it + ("continent" to NormalizedInputValue("Continent", EnumValue("Asia")))
})
.build(),
)
}
error("Did not match transform conditions")
}
override suspend fun getResultInstructions(
executionContext: NadelExecutionContext,
executionBlueprint: NadelOverallExecutionBlueprint,
service: Service,
overallField: ExecutableNormalizedField,
underlyingParentField: ExecutableNormalizedField?,
result: ServiceExecutionResult,
state: Any,
nodes: JsonNodes,
): List<NadelResultInstruction> {
return emptyList()
}
}
@UseHook
class `chain-rename-transform` : EngineTestHook {
override val customTransforms: List<NadelTransform<Any>> = listOf(
ChainRenameTransform(),
)
}
@UseHook
class `chain-rename-transform-with-type-rename` : EngineTestHook {
override val customTransforms: List<NadelTransform<Any>> = listOf(
ChainRenameTransform(),
)
}
| 24 | null | 23 | 157 | d9bb3cf1f301c685ca6d578279c4b2c6d6a74158 | 3,362 | nadel | Apache License 2.0 |
base-android/src/test/kotlin/com/jpaya/base/extensions/CalendarExtensionsTest.kt | jpaya17 | 254,323,532 | false | null | /*
* Copyright 2020 <NAME>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.jpaya.base.extensions
import org.junit.Assert.assertEquals
import org.junit.Test
import java.util.Calendar
import kotlin.collections.HashMap
class CalendarExtensionsTest {
companion object {
private val TIMES: HashMap<Int, Boolean> = hashMapOf(
0 to true,
1 to true,
2 to true,
3 to true,
4 to true,
5 to true,
6 to false,
7 to false,
8 to false,
9 to false,
10 to false,
11 to false,
12 to false,
13 to false,
14 to false,
15 to false,
16 to false,
17 to false,
18 to false,
19 to true,
20 to true,
21 to true,
22 to true,
23 to true
)
}
@Test
fun `Check isNightTime works properly`() {
TIMES.forEach { (hour, expectedResult) ->
val calendar = Calendar.getInstance()
calendar.set(Calendar.HOUR_OF_DAY, hour)
assertEquals(expectedResult, calendar.isNightTime())
}
}
}
| 20 | Kotlin | 6 | 49 | 5f6b5583f1a259407e85f6ecad6333b208b98885 | 1,751 | englishisfun | Apache License 2.0 |
neat-form-core/src/main/java/com/nerdstone/neatformcore/form/json/JsonFormBuilder.kt | ellykits | 193,852,361 | false | null | package com.nerdstone.neatformcore.form.json
import android.content.Context
import android.view.View
import androidx.fragment.app.FragmentActivity
import androidx.lifecycle.ViewModelProvider
import com.nerdstone.neatformcore.datasource.AssetFile
import com.nerdstone.neatformcore.domain.builders.FormBuilder
import com.nerdstone.neatformcore.domain.model.NForm
import com.nerdstone.neatformcore.domain.model.NFormContent
import com.nerdstone.neatformcore.domain.model.NFormViewData
import com.nerdstone.neatformcore.domain.view.FormValidator
import com.nerdstone.neatformcore.form.common.FormErrorDialog
import com.nerdstone.neatformcore.form.json.JsonParser.parseJson
import com.nerdstone.neatformcore.utils.internationalization.LanguageHelper
import com.nerdstone.neatformcore.rules.NeatFormValidator
import com.nerdstone.neatformcore.rules.RulesFactory
import com.nerdstone.neatformcore.rules.RulesFactory.RulesFileType
import com.nerdstone.neatformcore.utils.*
import com.nerdstone.neatformcore.utils.Constants.ViewType
import com.nerdstone.neatformcore.viewmodel.DataViewModel
import com.nerdstone.neatformcore.viewmodel.FormViewModel
import com.nerdstone.neatformcore.views.containers.MultiChoiceCheckBox
import com.nerdstone.neatformcore.views.containers.RadioGroupView
import com.nerdstone.neatformcore.views.containers.VerticalRootView
import com.nerdstone.neatformcore.views.handlers.ViewDispatcher
import com.nerdstone.neatformcore.views.widgets.*
import kotlinx.coroutines.CoroutineScope
import timber.log.Timber
import java.lang.ref.WeakReference
import java.util.*
import kotlin.reflect.KClass
object JsonFormConstants {
const val FORM_VERSION = "form_version"
const val FORM_METADATA = "form_metadata"
const val FORM_DATA = "form_data"
const val FORM_NAME = "form_name"
}
/***
* @author <NAME>
*
* This class implements the [FormBuilder] and is used to build the form using JSON specification.
* This form builder works in 3 sequential steps. First it parses the JSON into a model, secondly it
* reads the rules file and finally creates the actual views. All these three tasks run one after the
* other but within a [CoroutineScope].
*
* To ensure that the the form builder will not attempt to create the views without first parsing
* the JSON a mutex [SingleRunner] is used to guarantee that the tasks run sequentially. This
* does not mean however that the tasks are running on the main thread.
*
* To parse the JSON for example is handled by [DispatcherProvider.default] method since it is a CPU intensive task.
* Reading of rules file however is run by [DispatcherProvider.io] whereas creation of views is done on the
* main thread using [DispatcherProvider.main] scope.
*/
class JsonFormBuilder() : FormBuilder {
internal val readOnlyFields = mutableSetOf<String>()
override lateinit var context: Context
override lateinit var dataViewModel: DataViewModel
override lateinit var formViewModel: FormViewModel
override val rulesFactory: RulesFactory = RulesFactory()
override val viewDispatcher: ViewDispatcher = ViewDispatcher(rulesFactory)
override val formValidator: FormValidator = NeatFormValidator()
override var registeredViews = mutableMapOf<String, KClass<*>>()
override var resourcesMap = mutableMapOf<String, Int>()
private val rulesHandler = rulesFactory.rulesHandler
var defaultContextProvider: DispatcherProvider
var form: NForm? = null
var fileSource: String? = null
var formDataJson: String? = null
override lateinit var formString: String
constructor(context: Context, fileSource: String) : this() {
this.context = context
this.fileSource = fileSource
this.dataViewModel =
ViewModelProvider(context as FragmentActivity)[DataViewModel::class.java]
this.formViewModel = ViewModelProvider(context)[FormViewModel::class.java]
}
constructor(jsonString: String, context: Context) : this() {
this.formString = jsonString
this.context = context
this.dataViewModel =
ViewModelProvider(context as FragmentActivity)[DataViewModel::class.java]
this.formViewModel = ViewModelProvider(context)[FormViewModel::class.java]
}
init {
rulesHandler.formBuilder = WeakReference(this)
defaultContextProvider = DefaultDispatcherProvider()
}
internal fun parseJsonForm() {
form = when {
this::formString.isInitialized && formString.isNotNull() -> parseJson<NForm>(formString)
fileSource.isNotNull() -> {
val bundleName = LanguageHelper.getBundleNameFromFileSource(fileSource!!)
val rawJsonStringTemplate = AssetFile.readAssetFileAsString(context, fileSource!!)
parseJson<NForm>(
parseTemplate(bundleName, Locale.getDefault(), rawJsonStringTemplate)
)
}
else -> null
}
}
private fun parseTemplate(bundleName: String, locale: Locale, template: String): String {
return try {
val bundle = ResourceBundle.getBundle(bundleName, locale)
LanguageHelper.getBundleStringSubstitutor(bundle).replace(template)
} catch (exception: MissingResourceException){
template
}
}
fun addViewsToVerticalRootView(
customViews: List<View>?, stepIndex: Int, formContent: NFormContent,
verticalRootView: VerticalRootView,
) {
val view = customViews?.getOrNull(stepIndex)
when {
view.isNotNull() -> {
verticalRootView.addView(view)
verticalRootView.addChildren(formContent.fields, this, true)
}
else -> verticalRootView.addChildren(formContent.fields, this)
}
}
override fun getFormMetaData(): Map<String, Any> {
return form?.formMetadata ?: mutableMapOf()
}
override fun getFormDataAsJson(): String {
if (formValidator.invalidFields.isEmpty() && formValidator.requiredFields.isEmpty()) {
val formDetails = hashMapOf<String, Any?>().also {
it[JsonFormConstants.FORM_NAME] = form?.formName
it[JsonFormConstants.FORM_METADATA] = form?.formMetadata
it[JsonFormConstants.FORM_VERSION] = form?.formVersion
it[JsonFormConstants.FORM_DATA] = dataViewModel.details.value
}
return formDetails.getJsonFromModel()
}
FormErrorDialog(context).show()
logInvalidFields()
return ""
}
override fun withFormData(formDataJson: String, readOnlyFields: MutableSet<String>):
FormBuilder {
this.formDataJson = formDataJson
this.readOnlyFields.addAll(readOnlyFields)
return this
}
override fun preFillForm() {
if (
this::dataViewModel.isInitialized && dataViewModel.details.value.isNullOrEmpty()
&& formDataJson.isNotNull()
) {
this.formViewModel.readOnlyFields.value?.addAll(readOnlyFields)
dataViewModel.updateDetails(formDataJson!!.parseFormDataJson())
}
}
override fun registerFormRulesFromFile(context: Context, rulesFileType: RulesFileType)
: Boolean {
form?.rulesFile?.also {
rulesFactory.readRulesFromFile(context, it, rulesFileType)
}
return true
}
override fun getFormData(): HashMap<String, NFormViewData> {
if (formValidator.invalidFields.isEmpty() && formValidator.requiredFields.isEmpty()) {
return dataViewModel.details.value!!
}
FormErrorDialog(context).show()
logInvalidFields()
return hashMapOf()
}
private fun logInvalidFields() {
Timber.d("Invalid fields (${formValidator.invalidFields.size}) -> ${formValidator.invalidFields}")
Timber.d("Required fields (${formValidator.requiredFields.size}) -> ${formValidator.requiredFields}")
}
override fun registerViews() {
registeredViews[ViewType.EDIT_TEXT] = EditTextNFormView::class
registeredViews[ViewType.TEXT_INPUT_EDIT_TEXT] = TextInputEditTextNFormView::class
registeredViews[ViewType.NUMBER_SELECTOR] = NumberSelectorNFormView::class
registeredViews[ViewType.SPINNER] = SpinnerNFormView::class
registeredViews[ViewType.DATETIME_PICKER] = DateTimePickerNFormView::class
registeredViews[ViewType.CHECKBOX] = CheckBoxNFormView::class
registeredViews[ViewType.MULTI_CHOICE_CHECKBOX] = MultiChoiceCheckBox::class
registeredViews[ViewType.RADIO_GROUP] = RadioGroupView::class
registeredViews[ViewType.TOAST_NOTIFICATION] = NotificationNFormView::class
}
} | 15 | null | 25 | 63 | 1d0dbdfe7045bdc5b571a5f7741b06a900beeb2d | 8,771 | neat-form | Apache License 2.0 |
app/src/main/java/com/duckduckgo/app/browser/history/NavigationHistorySheet.kt | duckduckgo | 78,869,127 | false | {"Kotlin": 14333964, "HTML": 63593, "Ruby": 20564, "C++": 10312, "JavaScript": 8463, "CMake": 1992, "C": 1076, "Shell": 784} | /*
* Copyright (c) 2022 DuckDuckGo
*
* 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.duckduckgo.app.browser.history
import android.annotation.SuppressLint
import android.content.Context
import android.os.Bundle
import android.view.LayoutInflater
import androidx.lifecycle.LifecycleOwner
import com.duckduckgo.app.browser.commands.Command.ShowBackNavigationHistory
import com.duckduckgo.app.browser.databinding.NavigationHistoryPopupViewBinding
import com.duckduckgo.app.browser.favicon.FaviconManager
import com.duckduckgo.app.browser.history.NavigationHistoryAdapter.NavigationHistoryListener
import com.google.android.material.bottomsheet.BottomSheetDialog
@SuppressLint("NoBottomSheetDialog")
class NavigationHistorySheet(
context: Context,
private val viewLifecycleOwner: LifecycleOwner,
private val faviconManager: FaviconManager,
private val tabId: String,
private val history: ShowBackNavigationHistory,
private val listener: NavigationHistorySheetListener,
) : BottomSheetDialog(context) {
private val binding = NavigationHistoryPopupViewBinding.inflate(LayoutInflater.from(context))
interface NavigationHistorySheetListener {
fun historicalPageSelected(stackIndex: Int)
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(binding.root)
binding.historyRecycler.also { recycler ->
NavigationHistoryAdapter(
viewLifecycleOwner,
faviconManager,
tabId,
object : NavigationHistoryListener {
override fun historicalPageSelected(stackIndex: Int) {
dismiss()
listener.historicalPageSelected(stackIndex)
}
},
).also { adapter ->
recycler.adapter = adapter
adapter.updateNavigationHistory(history.history)
}
}
}
}
| 67 | Kotlin | 901 | 3,823 | 6415f0f087a11a51c0a0f15faad5cce9c790417c | 2,518 | Android | Apache License 2.0 |
soapui-streams-direct/src/main/kotlin/eu/k5/soapui/streams/direct/Project.kt | denninger-eu | 244,302,123 | false | null | package eu.k5.soapui.streams.direct
import eu.k5.soapui.streams.model.SuProject
import eu.k5.soapui.streams.model.SuuProperties
import eu.k5.soapui.streams.model.rest.SuuRestService
import eu.k5.soapui.streams.model.test.SuuTestSuite
import eu.k5.soapui.streams.model.wsdl.SuuWsdlService
class Project : SuProject {
override var name: String
get() = TODO("not implemented") //To change initializer of created properties use File | Settings | File Templates.
set(value) {}
override var description: String?
get() = TODO("not implemented") //To change initializer of created properties use File | Settings | File Templates.
set(value) {}
override val properties: SuuProperties
get() = TODO("not implemented") //To change initializer of created properties use File | Settings | File Templates.
override val restServices: List<SuuRestService>
get() = TODO("not implemented") //To change initializer of created properties use File | Settings | File Templates.
override fun createRestService(name: String): SuuRestService {
TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
}
override val testSuites: List<SuuTestSuite>
get() = TODO("not implemented") //To change initializer of created properties use File | Settings | File Templates.
override fun createTestSuite(name: String): SuuTestSuite {
TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
}
override val wsdlServices: List<SuuWsdlService>
get() = TODO("not implemented") //To change initializer of created properties use File | Settings | File Templates.
override fun createWsdlService(name: String): SuuWsdlService {
TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
}
fun toXml(): Any? {
return ""
}
}
| 5 | Kotlin | 0 | 0 | 665e54e4ac65d6c7e9805bb1b44f30f9ec702ce3 | 1,965 | soapui-utils | Apache License 2.0 |
features/root/memory/src/jvmMain/kotlin/app/immich/kmp/features/root/memory/MemoryPortal.jvm.kt | eygraber | 738,812,490 | false | {"Kotlin": 281627, "Shell": 1809, "HTML": 635, "JavaScript": 543} | package app.immich.kmp.features.root.memory
import app.immich.kmp.core.ImmichSessionComponent
internal actual fun MemoryComponent.Companion.createA(
sessionComponent: ImmichSessionComponent,
route: Route,
): MemoryComponent = MemoryComponent.Companion.create(sessionComponent, route)
| 5 | Kotlin | 0 | 0 | 4156287793c3fbb0e91c0b24cf2298253085f72d | 290 | immich-kmp | MIT License |
paymentsheet-example/src/androidTest/java/com/stripe/android/TestBrowsers.kt | stripe | 6,926,049 | false | null | package com.stripe.android
import androidx.test.ext.junit.runners.AndroidJUnit4
import androidx.test.platform.app.InstrumentationRegistry
import androidx.test.uiautomator.UiDevice
import com.stripe.android.test.core.AuthorizeAction
import com.stripe.android.test.core.Automatic
import com.stripe.android.test.core.Billing
import com.stripe.android.test.core.Browser
import com.stripe.android.test.core.Currency
import com.stripe.android.test.core.Customer
import com.stripe.android.test.core.DelayedPMs
import com.stripe.android.test.core.GooglePayState
import com.stripe.android.test.core.IntentType
import com.stripe.android.test.core.LinkState
import com.stripe.android.test.core.PlaygroundTestDriver
import com.stripe.android.test.core.Shipping
import com.stripe.android.test.core.TestParameters
import com.stripe.android.utils.TestRules
import com.stripe.android.utils.initializedLpmRepository
import org.junit.Before
import org.junit.Ignore
import org.junit.Rule
import org.junit.Test
import org.junit.runner.RunWith
/**
* This tests that authorization works with firefox and chrome browsers. If a browser
* is specified in the test parameters and it is not available the test will be skipped.
* Note that if a webview is used because there is no browser or a returnURL is specified
* this it cannot be actuated with UI Automator.
*/
@RunWith(AndroidJUnit4::class)
class TestBrowsers {
@get:Rule
val rules = TestRules.create()
private lateinit var device: UiDevice
private lateinit var testDriver: PlaygroundTestDriver
@Before
fun before() {
device = UiDevice.getInstance(InstrumentationRegistry.getInstrumentation())
testDriver = PlaygroundTestDriver(device, rules.compose)
}
private val bancontactNewUser = TestParameters(
paymentMethod = lpmRepository.fromCode("bancontact")!!,
customer = Customer.New,
linkState = LinkState.Off,
googlePayState = GooglePayState.On,
currency = Currency.EUR,
intentType = IntentType.Pay,
billing = Billing.On,
shipping = Shipping.Off,
delayed = DelayedPMs.Off,
automatic = Automatic.Off,
saveCheckboxValue = false,
saveForFutureUseCheckboxVisible = false,
useBrowser = Browser.Chrome,
authorizationAction = AuthorizeAction.Authorize,
merchantCountryCode = "GB",
)
@Test
fun testAuthorizeChrome() {
testDriver.confirmNewOrGuestComplete(
bancontactNewUser.copy(
useBrowser = Browser.Chrome,
)
)
}
@Ignore("On browserstack's Google Pixel, the connection to stripe.com is deemed insecure and the page does not load.")
fun testAuthorizeFirefox() {
testDriver.confirmNewOrGuestComplete(
bancontactNewUser.copy(
useBrowser = Browser.Firefox,
)
)
}
@Test
fun testAuthorizeAnyAvailableBrowser() {
// Does not work when default browser is android
testDriver.confirmNewOrGuestComplete(
bancontactNewUser.copy(
useBrowser = null,
)
)
}
companion object {
private val lpmRepository = initializedLpmRepository(
context = InstrumentationRegistry.getInstrumentation().targetContext,
)
}
}
| 87 | Kotlin | 606 | 1,133 | 8103aa6791ce4de7739d201f35e3572334a60553 | 3,350 | stripe-android | MIT License |
mapcompose/src/main/java/ovh/plrapps/mapcompose/ui/markers/MarkerLayout.kt | p-lr | 359,208,603 | false | null | package ovh.plrapps.mapcompose.ui.markers
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.graphicsLayer
import androidx.compose.ui.layout.Layout
import androidx.compose.ui.layout.layoutId
import ovh.plrapps.mapcompose.ui.state.MarkerData
import ovh.plrapps.mapcompose.ui.state.ZoomPanRotateState
import ovh.plrapps.mapcompose.utils.rotateCenteredX
import ovh.plrapps.mapcompose.utils.rotateCenteredY
import ovh.plrapps.mapcompose.utils.toRad
@Composable
internal fun MarkerLayout(
modifier: Modifier,
zoomPRState: ZoomPanRotateState,
content: @Composable () -> Unit
) {
Layout(
content = content,
modifier
.graphicsLayer {
translationX = -zoomPRState.scrollX
translationY = -zoomPRState.scrollY
}
.background(Color.Transparent)
.fillMaxSize()
) { measurables, constraints ->
val placeableCst = constraints.copy(minHeight = 0, minWidth = 0)
layout(constraints.maxWidth, constraints.maxHeight) {
for (measurable in measurables) {
val data = measurable.layoutId as? MarkerData ?: continue
val placeable = measurable.measure(placeableCst)
val widthOffset =
placeable.measuredWidth * data.relativeOffset.x + data.absoluteOffset.x
val heightOffset =
placeable.measuredHeight * data.relativeOffset.y + data.absoluteOffset.y
if (zoomPRState.rotation == 0f) {
placeable.place(
x = (data.x * zoomPRState.fullWidth * zoomPRState.scale + widthOffset).toInt(),
y = (data.y * zoomPRState.fullHeight * zoomPRState.scale + heightOffset).toInt(),
zIndex = data.zIndex
)
} else {
with(zoomPRState) {
val angleRad = rotation.toRad()
val xFullPx = data.x * fullWidth * scale
val yFullPx = data.y * fullHeight * scale
val centerX = centroidX * fullWidth * scale
val centerY = centroidY * fullHeight * scale
placeable.place(
x = (rotateCenteredX(
xFullPx,
yFullPx,
centerX,
centerY,
angleRad
) + widthOffset).toInt(),
y = (rotateCenteredY(
xFullPx,
yFullPx,
centerX,
centerY,
angleRad
) + heightOffset).toInt(),
zIndex = data.zIndex
)
}
}
}
}
}
} | 8 | null | 7 | 96 | e65762b45cc7418cbae54e0673405d109da7aadd | 3,238 | MapCompose | Apache License 2.0 |
scripts/src/main/java/io/github/fate_grand_automata/scripts/enums/GameServerEnum.kt | Fate-Grand-Automata | 245,391,245 | false | null | package com.mathewsachin.fategrandautomata.scripts.enums
enum class GameServerEnum constructor(vararg val packageNames: String) {
En("com.aniplex.fategrandorder.en", "io.rayshift.betterfgo.en"),
Jp("com.aniplex.fategrandorder", "io.rayshift.betterfgo"),
Cn("com.bilibili.fatego", "com.bilibili.fatego.sharejoy"),
Tw("com.komoe.fgomycard", "com.xiaomeng.fategrandorder"),
Kr("com.netmarble.fgok");
companion object {
/**
* Maps an APK package name to the corresponding [GameServerEnum].
*/
fun fromPackageName(packageName: String): GameServerEnum? =
values().find { packageName in it.packageNames }
}
} | 84 | null | 177 | 961 | dcccf843c7ac3ce94f57f97b7709c4a1b8860f02 | 677 | FGA | MIT License |
example/android/app/src/main/kotlin/cc/colorcat/finder_example/MainActivity.kt | ccolorcat | 345,508,539 | false | {"Dart": 26153, "Ruby": 2196, "Kotlin": 1502, "Swift": 907, "Objective-C": 659} | package cc.colorcat.finder_example
import io.flutter.embedding.android.FlutterActivity
class MainActivity: FlutterActivity() {
}
| 0 | Dart | 0 | 3 | dbd0cec6071d468444a66d2d014ada53c7f62f90 | 131 | finder | Apache License 2.0 |
app/src/main/java/com/hypertrack/android/ui/MainActivity.kt | hypertrack | 241,723,736 | false | null | package com.hypertrack.android.ui
import android.content.Intent
import android.os.Bundle
import androidx.activity.viewModels
import androidx.navigation.NavDestination
import com.hypertrack.android.di.Injector
import com.hypertrack.android.ui.activity.ActivityViewModel
import com.hypertrack.android.ui.base.NavActivity
import com.hypertrack.android.ui.base.navigate
import com.hypertrack.android.ui.base.withErrorHandling
import com.hypertrack.android.ui.common.util.SnackBarUtil
import com.hypertrack.android.ui.common.util.observeWithErrorHandling
import com.hypertrack.android.utils.*
import com.hypertrack.logistics.android.github.R
import kotlinx.android.synthetic.main.activity_main.*
class MainActivity : NavActivity() {
private val crashReportsProvider = Injector.crashReportsProvider
private val vm: ActivityViewModel by viewModels {
MyApplication.newInjector.provideActivityViewModelFactory()
}
override val layoutRes: Int = R.layout.activity_main
override val navHostId: Int = R.id.navHost
override fun onCreate(savedInstanceState: Bundle?) {
// restoring activity state is disabled because it can restore
// fragments in wrong app state
super.onCreate(null)
withErrorHandling(vm::onError) {
vm.navigationEvent.observeWithErrorHandling(
this,
vm::onError,
) {
navController.navigate(it)
}
vm.showErrorMessageEvent.observeWithErrorHandling(
this,
vm::onError,
) {
SnackBarUtil.showErrorSnackBar(root, it)
}
vm.showAppMessageEvent.observeWithErrorHandling(
this,
vm::onError,
) {
SnackBarUtil.showSnackBar(root, it)
}
// todo test current fragment null
vm.onCreate(intent, getCurrentFragment())
}
}
override fun onStart() {
super.onStart()
withErrorHandling(vm::onError) {
crashReportsProvider.log("activity start")
vm.onStart(this, intent)
}
}
override fun onNewIntent(intent: Intent?) {
super.onNewIntent(intent)
withErrorHandling(vm::onError) {
// from branch tutorial, do we need this?
setIntent(intent)
vm.onNewIntent(intent, this, getCurrentFragment())
}
}
override fun onResume() {
super.onResume()
withErrorHandling(vm::onError) {
inForeground = true
crashReportsProvider.log("activity resume")
}
}
override fun onPause() {
withErrorHandling(vm::onError) {
inForeground = false
crashReportsProvider.log("activity pause")
super.onPause()
}
}
override fun onStop() {
super.onStop()
withErrorHandling(vm::onError) {
crashReportsProvider.log("activity stop")
}
}
override fun onDestinationChanged(destination: NavDestination) {
vm.onNavDestinationChanged(destination)
}
override fun onRequestPermissionsResult(
requestCode: Int,
permissions: Array<out String>,
grantResults: IntArray
) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults)
withErrorHandling(vm::onError) {
getCurrentFragment().onRequestPermissionsResult(requestCode, permissions, grantResults)
}
}
@Deprecated("Deprecated in Java")
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
super.onActivityResult(requestCode, resultCode, data)
withErrorHandling(vm::onError) {
getCurrentFragment().onActivityResult(requestCode, resultCode, data)
// todo to use case
if (requestCode == REQUEST_CODE_UPDATE) {
when (resultCode) {
RESULT_CANCELED, RESULT_OK -> {
}
else -> {
crashReportsProvider.logException(Exception("Update failed: resultCode=$resultCode, data=$data"))
}
}
}
}
}
override fun onBackPressed() {
withErrorHandling(vm::onError) {
if (getCurrentBaseFragment()?.onBackPressed() == false) {
super.onBackPressed()
}
}
}
override fun onSupportNavigateUp(): Boolean {
withErrorHandling(vm::onError) {
onBackPressed()
}
return true
}
override fun toString(): String = javaClass.simpleName
companion object {
var inForeground: Boolean = false
const val REQUEST_CODE_IMAGE_CAPTURE = 1
const val REQUEST_CODE_UPDATE = 2
const val REQUEST_CODE_COPY_TEXT_TO_CLIPBOARD = 3
}
}
| 1 | null | 17 | 31 | c5dd23621aed11ff188cf98ac037b67f435e9f5b | 4,923 | visits-android | MIT License |
plugins/settings-repository/src/readOnlySourcesEditor.kt | androidports | 115,100,208 | false | null | // Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.settingsRepository
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.diagnostic.runAndLogException
import com.intellij.openapi.fileChooser.FileChooserDescriptorFactory
import com.intellij.openapi.options.ConfigurableUi
import com.intellij.openapi.progress.runModalTask
import com.intellij.openapi.ui.TextBrowseFolderListener
import com.intellij.openapi.ui.TextFieldWithBrowseButton
import com.intellij.openapi.ui.ValidationInfo
import com.intellij.ui.components.dialog
import com.intellij.ui.layout.*
import com.intellij.util.Function
import com.intellij.util.containers.ContainerUtil
import com.intellij.util.io.delete
import com.intellij.util.io.exists
import com.intellij.util.text.nullize
import com.intellij.util.text.trimMiddle
import com.intellij.util.ui.table.TableModelEditor
import gnu.trove.THashSet
import org.jetbrains.settingsRepository.git.asProgressMonitor
import org.jetbrains.settingsRepository.git.cloneBare
import javax.swing.JTextField
private val COLUMNS = arrayOf(object : TableModelEditor.EditableColumnInfo<ReadonlySource, Boolean>() {
override fun getColumnClass() = Boolean::class.java
override fun valueOf(item: ReadonlySource) = item.active
override fun setValue(item: ReadonlySource, value: Boolean) {
item.active = value
}
},
object : TableModelEditor.EditableColumnInfo<ReadonlySource, String>() {
override fun valueOf(item: ReadonlySource) = item.url
override fun setValue(item: ReadonlySource, value: String) {
item.url = value
}
})
internal fun createReadOnlySourcesEditor(): ConfigurableUi<IcsSettings> {
val itemEditor = object : TableModelEditor.DialogItemEditor<ReadonlySource> {
override fun clone(item: ReadonlySource, forInPlaceEditing: Boolean) = ReadonlySource(item.url, item.active)
override fun getItemClass() = ReadonlySource::class.java
override fun edit(item: ReadonlySource, mutator: Function<ReadonlySource, ReadonlySource>, isAdd: Boolean) {
val urlField = TextFieldWithBrowseButton(JTextField(20))
urlField.addBrowseFolderListener(TextBrowseFolderListener(FileChooserDescriptorFactory.createSingleFolderDescriptor()))
val panel = panel {
row("URL:") {
urlField()
}
}
dialog(title = "Add read-only source", panel = panel, focusedComponent = urlField) {
val url = urlField.text.nullize(true)
validateUrl(url, null)?.let {
return@dialog listOf(ValidationInfo(it))
}
mutator.`fun`(item).url = url
return@dialog null
}
.show()
}
override fun applyEdited(oldItem: ReadonlySource, newItem: ReadonlySource) {
newItem.url = oldItem.url
}
override fun isUseDialogToAdd() = true
}
val editor = TableModelEditor(COLUMNS, itemEditor, "No sources configured")
editor.reset(if (ApplicationManager.getApplication().isUnitTestMode) emptyList() else icsManager.settings.readOnlySources)
return object : ConfigurableUi<IcsSettings> {
override fun isModified(settings: IcsSettings) = editor.isModified
override fun apply(settings: IcsSettings) {
val oldList = settings.readOnlySources
val toDelete = THashSet<String>(oldList.size)
for (oldSource in oldList) {
ContainerUtil.addIfNotNull(toDelete, oldSource.path)
}
val toCheckout = THashSet<ReadonlySource>()
val newList = editor.apply()
for (newSource in newList) {
val path = newSource.path
if (path != null && !toDelete.remove(path)) {
toCheckout.add(newSource)
}
}
if (toDelete.isEmpty && toCheckout.isEmpty) {
return
}
runModalTask(icsMessage("task.sync.title")) { indicator ->
indicator.isIndeterminate = true
val root = icsManager.readOnlySourcesManager.rootDir
if (toDelete.isNotEmpty()) {
indicator.text = "Deleting old repositories"
for (path in toDelete) {
indicator.checkCanceled()
LOG.runAndLogException {
indicator.text2 = path
root.resolve(path).delete()
}
}
}
if (toCheckout.isNotEmpty()) {
for (source in toCheckout) {
indicator.checkCanceled()
LOG.runAndLogException {
indicator.text = "Cloning ${source.url!!.trimMiddle(255)}"
val dir = root.resolve(source.path!!)
if (dir.exists()) {
dir.delete()
}
cloneBare(source.url!!, dir, icsManager.credentialsStore, indicator.asProgressMonitor()).close()
}
}
}
icsManager.readOnlySourcesManager.setSources(newList)
// blindly reload all
icsManager.schemeManagerFactory.value.process {
it.reload()
}
}
}
override fun reset(settings: IcsSettings) {
editor.reset(settings.readOnlySources)
}
override fun getComponent() = editor.createComponent()
}
}
| 6 | null | 5162 | 4 | 6e4f7135c5843ed93c15a9782f29e4400df8b068 | 5,207 | intellij-community | Apache License 2.0 |
lib_base/src/main/java/com/hzsoft/lib/base/view/BaseActivity.kt | zhouhuandev | 346,678,456 | false | null | package com.hzsoft.lib.base.view
import android.content.Context
import android.content.Intent
import android.os.Bundle
import android.text.TextUtils
import android.view.*
import android.widget.ImageView
import android.widget.TextView
import androidx.appcompat.widget.Toolbar
import com.alibaba.android.arouter.facade.Postcard
import com.alibaba.android.arouter.launcher.ARouter
import com.hzsoft.lib.base.R
import com.hzsoft.lib.base.event.common.BaseActivityEvent
import com.hzsoft.lib.base.mvvm.view.BaseView
import com.hzsoft.lib.base.utils.NetUtil
import com.hzsoft.lib.base.widget.LoadingInitView
import com.hzsoft.lib.base.widget.LoadingTransView
import com.hzsoft.lib.base.widget.NetErrorView
import com.hzsoft.lib.base.widget.NoDataView
import com.hzsoft.lib.log.KLog
import com.trello.rxlifecycle2.components.support.RxAppCompatActivity
import org.greenrobot.eventbus.EventBus
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode
/**
* 基础页面
* @author zhouhuan
* @time 2020/12/2
*/
abstract class BaseActivity : RxAppCompatActivity(), BaseView {
companion object {
val TAG: String = this::class.java.simpleName
}
protected lateinit var mContext: Context
protected var mTxtTitle: TextView? = null
protected var tvToolbarRight: TextView? = null
protected var ivToolbarRight: ImageView? = null
protected var mToolbar: Toolbar? = null
protected var mNetErrorView: NetErrorView? = null
protected var mNoDataView: NoDataView? = null
protected var mLoadingInitView: LoadingInitView? = null
protected var mLoadingTransView: LoadingTransView? = null
private lateinit var mViewStubToolbar: ViewStub
private lateinit var mViewStubContent: ViewStub
private lateinit var mViewStubInitLoading: ViewStub
private lateinit var mViewStubTransLoading: ViewStub
private lateinit var mViewStubNoData: ViewStub
private lateinit var mViewStubError: ViewStub
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
val currentTimeMillis = System.currentTimeMillis()
setContentView(R.layout.activity_root)
mContext = this
initBundle()
initCommonView()
ARouter.getInstance().inject(this)
initView()
initListener()
EventBus.getDefault().register(this)
val totalTime = System.currentTimeMillis() - currentTimeMillis
KLog.e(TAG, "onCreate: 当前进入的Activity: $localClassName 初始化时间:$totalTime ms")
}
protected open fun initCommonView() {
if (enableAllowFullScreen()) {
window.setFlags(
WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN
)
requestWindowFeature(Window.FEATURE_NO_TITLE);
}
mViewStubToolbar = findViewById(R.id.view_stub_toolbar)
mViewStubContent = findViewById(R.id.view_stub_content)
mViewStubInitLoading = findViewById(R.id.view_stub_init_loading)
mViewStubTransLoading = findViewById(R.id.view_stub_trans_loading)
mViewStubError = findViewById(R.id.view_stub_error)
mViewStubNoData = findViewById(R.id.view_stub_nodata)
if (enableToolbar()) {
mViewStubToolbar.layoutResource = onBindToolbarLayout()
val view = mViewStubToolbar.inflate()
initToolbar(view)
}
initContentView(mViewStubContent)
}
open fun initContentView(mViewStubContent: ViewStub) {
mViewStubContent.layoutResource = onBindLayout()
mViewStubContent.inflate()
}
protected fun initToolbar(view: View) {
mToolbar = view.findViewById(R.id.toolbar_root)
mTxtTitle = view.findViewById(R.id.toolbar_title)
tvToolbarRight = view.findViewById(R.id.tv_toolbar_right)
ivToolbarRight = view.findViewById(R.id.iv_toolbar_right)
if (mToolbar != null) {
setSupportActionBar(mToolbar)
//是否显示标题
supportActionBar!!.setDisplayShowTitleEnabled(false)
mToolbar?.setNavigationOnClickListener { onBackPressed() }
if (enableToolBarLeft()) {
//设置是否添加显示NavigationIcon.如果要用
supportActionBar!!.setDisplayHomeAsUpEnabled(true)
//设置NavigationIcon的icon.可以是Drawable ,也可以是ResId
mToolbar?.setNavigationIcon(getToolBarLeftIcon())
mToolbar?.setNavigationOnClickListener { onBackPressed() }
}
//当标题栏右边的文字不为空时进行填充文字信息
if (tvToolbarRight != null && !TextUtils.isEmpty(getToolBarRightTxt())) {
tvToolbarRight?.text = getToolBarRightTxt()
tvToolbarRight?.visibility = View.VISIBLE
tvToolbarRight?.setOnClickListener(getToolBarRightTxtClick())
}
//当标题右边的图标不为 默认0时进行填充图标
if (ivToolbarRight != null && getToolBarRightImg() != 0) {
ivToolbarRight?.setImageResource(getToolBarRightImg())
ivToolbarRight?.visibility = View.VISIBLE
ivToolbarRight?.setOnClickListener(getToolBarRightImgClick())
}
}
}
override fun onTitleChanged(title: CharSequence, color: Int) {
super.onTitleChanged(title, color)
if (mTxtTitle != null && !TextUtils.isEmpty(title)) {
mTxtTitle?.text = title
}
//可以再次覆盖设置title
val tootBarTitle = getTootBarTitle()
if (mTxtTitle != null && !TextUtils.isEmpty(tootBarTitle)) {
mTxtTitle?.text = tootBarTitle
}
}
override fun onResume() {
super.onResume()
initData()
}
open fun getTootBarTitle(): String {
return ""
}
/**
* 设置返回按钮的图样,可以是Drawable ,也可以是ResId
* 注:仅在 enableToolBarLeft 返回为 true 时候有效
*
* @return
*/
open fun getToolBarLeftIcon(): Int {
return R.drawable.ic_white_black_45dp
}
/**
* 是否打开返回
*
* @return
*/
open fun enableToolBarLeft(): Boolean {
return false
}
/**
* 设置标题右边显示文字
*
* @return
*/
open fun getToolBarRightTxt(): String {
return ""
}
/**
* 设置标题右边显示 Icon
*
* @return int resId 类型
*/
open fun getToolBarRightImg(): Int {
return 0
}
/**
* 右边文字监听回调
* @return
*/
open fun getToolBarRightTxtClick(): View.OnClickListener? {
return null
}
/**
* 右边图标监听回调
* @return
*/
open fun getToolBarRightImgClick(): View.OnClickListener? {
return null
}
open fun onBindToolbarLayout(): Int {
return R.layout.common_toolbar
}
override fun onDestroy() {
super.onDestroy()
EventBus.getDefault().unregister(this)
}
open fun initBundle() {
}
abstract fun onBindLayout(): Int
abstract fun initView()
abstract override fun initData()
override fun initListener() {}
override fun finishActivity() {
finish()
}
open fun enableAllowFullScreen(): Boolean {
return false
}
open fun enableToolbar(): Boolean {
return true
}
override fun showInitLoadView() {
showInitLoadView(true)
}
override fun hideInitLoadView() {
showInitLoadView(false)
}
override fun showTransLoadingView() {
showTransLoadingView(true)
}
override fun hideTransLoadingView() {
showTransLoadingView(false)
}
override fun showNoDataView() {
showNoDataView(true)
}
override fun showNoDataView(resid: Int) {
showNoDataView(true, resid)
}
override fun hideNoDataView() {
showNoDataView(false)
}
override fun hideNetWorkErrView() {
showNetWorkErrView(false)
}
override fun showNetWorkErrView() {
showNetWorkErrView(true)
}
open fun showInitLoadView(show: Boolean) {
if (mLoadingInitView == null) {
val view = mViewStubInitLoading.inflate()
mLoadingInitView = view.findViewById(R.id.view_init_loading)
}
mLoadingInitView?.visibility = if (show) View.VISIBLE else View.GONE
mLoadingInitView?.loading(show)
}
open fun showNetWorkErrView(show: Boolean) {
if (mNetErrorView == null) {
val view = mViewStubError.inflate()
mNetErrorView = view.findViewById(R.id.view_net_error)
mNetErrorView?.setOnClickListener(View.OnClickListener {
if (!NetUtil.checkNetToast()) {
return@OnClickListener
}
hideNetWorkErrView()
initData()
})
}
mNetErrorView?.visibility = if (show) View.VISIBLE else View.GONE
}
open fun showNoDataView(show: Boolean) {
if (mNoDataView == null) {
val view = mViewStubNoData.inflate()
mNoDataView = view.findViewById(R.id.view_no_data)
}
mNoDataView?.visibility = if (show) View.VISIBLE else View.GONE
}
open fun showNoDataView(show: Boolean, resid: Int) {
showNoDataView(show)
if (show) {
mNoDataView?.setNoDataView(resid)
}
}
open fun showTransLoadingView(show: Boolean) {
if (mLoadingTransView == null) {
val view = mViewStubTransLoading.inflate()
mLoadingTransView = view.findViewById(R.id.view_trans_loading)
}
mLoadingTransView?.visibility = if (show) View.VISIBLE else View.GONE
mLoadingTransView?.loading(show)
}
@Subscribe(threadMode = ThreadMode.MAIN)
open fun <T> onEvent(event: BaseActivityEvent<T>) {
}
open fun startActivity(clz: Class<*>?, bundle: Bundle?) {
val intent = Intent(this, clz)
if (bundle != null) {
intent.putExtras(bundle)
}
startActivity(intent)
}
/**
* 跳转方式
* 使用方法 startActivity<TargetActivity> { putExtra("param1", "data1") }
*/
inline fun <reified T> startActivity(block: Intent.() -> Unit) {
val intent = Intent(this, T::class.java)
intent.block()
startActivity(intent)
}
/**
* 阿里路由跳转
* open("填入你要跳转的ARouter路径") {
* withString("你要传递extra的key", "你要传递extra的value")
* }
*/
open fun open(path: String, block: Postcard.() -> Unit = {}) {
val postcard = ARouter.getInstance().build(path)
postcard.block()
postcard.navigation()
}
/**
* 阿里路由跳转并结束当前页面
*/
open fun openWithFinish(path: String, block: Postcard.() -> Unit = {}) {
open(path, block)
finish()
}
private var mLastButterKnifeClickTime: Long = 0
/**
* 是否快速点击
*
* @return true 是
*/
open fun beFastClick(): Boolean {
val currentClickTime = System.currentTimeMillis()
val flag = currentClickTime - mLastButterKnifeClickTime < 400L
mLastButterKnifeClickTime = currentClickTime
return flag
}
open fun onClick(v: View?) {
}
}
| 0 | null | 53 | 88 | c74e9e5e1059805e4373981633e17616a2328948 | 11,134 | BaseDemo | Apache License 2.0 |
kotlin-native/backend.native/compiler/ir/backend.native/src/org/jetbrains/kotlin/backend/konan/llvm/KotlinStaticData.kt | JetBrains | 3,432,266 | false | null | /*
* Copyright 2010-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license
* that can be found in the LICENSE file.
*/
package org.jetbrains.kotlin.backend.konan.llvm
import kotlinx.cinterop.cValuesOf
import llvm.*
import org.jetbrains.kotlin.backend.konan.Context
import org.jetbrains.kotlin.backend.konan.ir.llvmSymbolOrigin
import org.jetbrains.kotlin.ir.declarations.IrClass
import org.jetbrains.kotlin.ir.expressions.IrConst
private fun ConstPointer.add(index: Int): ConstPointer {
return constPointer(LLVMConstGEP(llvm, cValuesOf(Int32(index).llvm), 1)!!)
}
internal class KotlinStaticData(override val context: Context, module: LLVMModuleRef) : ContextUtils, StaticData(module) {
private val stringLiterals = mutableMapOf<String, ConstPointer>()
// Must match OBJECT_TAG_PERMANENT_CONTAINER in C++.
private fun permanentTag(typeInfo: ConstPointer): ConstPointer {
// Only pointer arithmetic via GEP works on constant pointers in LLVM.
return typeInfo.bitcast(int8TypePtr).add(1).bitcast(kTypeInfoPtr)
}
private fun objHeader(typeInfo: ConstPointer): Struct {
return Struct(runtime.objHeaderType, permanentTag(typeInfo))
}
private fun arrayHeader(typeInfo: ConstPointer, length: Int): Struct {
assert(length >= 0)
return Struct(runtime.arrayHeaderType, permanentTag(typeInfo), Int32(length))
}
private fun createRef(objHeaderPtr: ConstPointer) = objHeaderPtr.bitcast(kObjHeaderPtr)
private fun createKotlinStringLiteral(value: String): ConstPointer {
val elements = value.toCharArray().map(::Char16)
val objRef = createConstKotlinArray(context.ir.symbols.string.owner, elements)
return objRef
}
fun kotlinStringLiteral(value: String) = stringLiterals.getOrPut(value) { createKotlinStringLiteral(value) }
fun createConstKotlinArray(arrayClass: IrClass, elements: List<LLVMValueRef>) =
createConstKotlinArray(arrayClass, elements.map { constValue(it) }).llvm
fun createConstKotlinArray(arrayClass: IrClass, elements: List<ConstValue>): ConstPointer {
val typeInfo = arrayClass.typeInfoPtr
val bodyElementType: LLVMTypeRef = elements.firstOrNull()?.llvmType ?: int8Type
// (use [0 x i8] as body if there are no elements)
val arrayBody = ConstArray(bodyElementType, elements)
val compositeType = structType(runtime.arrayHeaderType, arrayBody.llvmType)
val global = this.createGlobal(compositeType, "")
val objHeaderPtr = global.pointer.getElementPtr(0)
val arrayHeader = arrayHeader(typeInfo, elements.size)
global.setInitializer(Struct(compositeType, arrayHeader, arrayBody))
global.setConstant(true)
global.setUnnamedAddr(true)
return createRef(objHeaderPtr)
}
fun createConstKotlinObject(type: IrClass, vararg fields: ConstValue): ConstPointer {
val typeInfo = type.typeInfoPtr
val objHeader = objHeader(typeInfo)
val global = this.placeGlobal("", Struct(objHeader, *fields))
global.setUnnamedAddr(true)
global.setConstant(true)
val objHeaderPtr = global.pointer.getElementPtr(0)
return createRef(objHeaderPtr)
}
fun createInitializer(type: IrClass, vararg fields: ConstValue): ConstValue =
Struct(objHeader(type.typeInfoPtr), *fields)
fun createUniqueInstance(
kind: UniqueKind, bodyType: LLVMTypeRef, typeInfo: ConstPointer): ConstPointer {
assert(getStructElements(bodyType).size == 1) // ObjHeader only.
val objHeader = when (kind) {
UniqueKind.UNIT -> objHeader(typeInfo)
UniqueKind.EMPTY_ARRAY -> arrayHeader(typeInfo, 0)
}
val global = this.placeGlobal(kind.llvmName, objHeader, isExported = true)
global.setConstant(true)
return global.pointer
}
fun unique(kind: UniqueKind): ConstPointer {
val descriptor = when (kind) {
UniqueKind.UNIT -> context.ir.symbols.unit.owner
UniqueKind.EMPTY_ARRAY -> context.ir.symbols.array.owner
}
return if (isExternal(descriptor)) {
constPointer(importGlobal(
kind.llvmName, runtime.objHeaderType, origin = descriptor.llvmSymbolOrigin
))
} else {
context.generationState.llvmDeclarations.forUnique(kind).pointer
}
}
/**
* Creates static instance of `konan.ImmutableByteArray` with given values of elements.
*
* @param args data for constant creation.
*/
fun createImmutableBlob(value: IrConst<String>): LLVMValueRef {
val args = value.value.map { Int8(it.code.toByte()).llvm }
return createConstKotlinArray(context.ir.symbols.immutableBlob.owner, args)
}
}
internal val ContextUtils.theUnitInstanceRef: ConstPointer
get() = staticData.unique(UniqueKind.UNIT) | 157 | Kotlin | 5209 | 42,102 | 65f712ab2d54e34c5b02ffa3ca8c659740277133 | 4,953 | kotlin | Apache License 2.0 |
app/src/main/java/today/kinema/data/source/RemoteDataSource.kt | manununhez | 288,487,056 | false | {"Kotlin": 191312} | package today.kinema.data.source
import today.kinema.data.api.dto.AttributeDto
import today.kinema.data.api.dto.GeneralResponse
import today.kinema.data.api.dto.MoviesDto
import today.kinema.ui.model.FilterAttribute
interface RemoteDataSource {
suspend fun searchMovies(filterAttribute: FilterAttribute): GeneralResponse<List<MoviesDto>>
suspend fun getAttributes(filterAttribute: FilterAttribute): GeneralResponse<AttributeDto>
suspend fun getSyncData(): GeneralResponse<String>
}
| 12 | Kotlin | 0 | 0 | 95582e5545fbae83136ac675d65107080f3b0c1c | 492 | pl-cinemas-app | MIT License |
solar/src/main/java/com/chiksmedina/solar/lineduotone/money/Dollar.kt | CMFerrer | 689,442,321 | false | {"Kotlin": 36591890} | package com.chiksmedina.solar.lineduotone.money
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.StrokeCap.Companion.Round
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 com.chiksmedina.solar.lineduotone.MoneyGroup
val MoneyGroup.Dollar: ImageVector
get() {
if (_dollar != null) {
return _dollar!!
}
_dollar = Builder(
name = "Dollar", defaultWidth = 24.0.dp, defaultHeight = 24.0.dp,
viewportWidth = 24.0f, viewportHeight = 24.0f
).apply {
path(
fill = SolidColor(Color(0x00000000)), stroke = SolidColor(Color(0xFF000000)),
fillAlpha = 0.5f, strokeAlpha = 0.5f, strokeLineWidth = 1.5f, strokeLineCap =
Butt, strokeLineJoin = Miter, strokeLineMiter = 4.0f, pathFillType = NonZero
) {
moveTo(12.0f, 12.0f)
moveToRelative(-10.0f, 0.0f)
arcToRelative(10.0f, 10.0f, 0.0f, true, true, 20.0f, 0.0f)
arcToRelative(10.0f, 10.0f, 0.0f, true, true, -20.0f, 0.0f)
}
path(
fill = SolidColor(Color(0x00000000)), stroke = SolidColor(Color(0xFF000000)),
strokeLineWidth = 1.5f, strokeLineCap = Round, strokeLineJoin = Miter,
strokeLineMiter = 4.0f, pathFillType = NonZero
) {
moveTo(12.0f, 6.0f)
verticalLineTo(18.0f)
}
path(
fill = SolidColor(Color(0x00000000)), stroke = SolidColor(Color(0xFF000000)),
strokeLineWidth = 1.5f, strokeLineCap = Round, strokeLineJoin = Miter,
strokeLineMiter = 4.0f, pathFillType = NonZero
) {
moveTo(15.0f, 9.5f)
curveTo(15.0f, 8.1193f, 13.6569f, 7.0f, 12.0f, 7.0f)
curveTo(10.3431f, 7.0f, 9.0f, 8.1193f, 9.0f, 9.5f)
curveTo(9.0f, 10.8807f, 10.3431f, 12.0f, 12.0f, 12.0f)
curveTo(13.6569f, 12.0f, 15.0f, 13.1193f, 15.0f, 14.5f)
curveTo(15.0f, 15.8807f, 13.6569f, 17.0f, 12.0f, 17.0f)
curveTo(10.3431f, 17.0f, 9.0f, 15.8807f, 9.0f, 14.5f)
}
}
.build()
return _dollar!!
}
private var _dollar: ImageVector? = null
| 0 | Kotlin | 0 | 0 | 3414a20650d644afac2581ad87a8525971222678 | 2,724 | SolarIconSetAndroid | MIT License |
app/src/main/java/com/tatuas/ghsv/ext/FragmentExt.kt | tatuas | 134,174,686 | false | {"Gradle": 6, "Java Properties": 2, "Shell": 1, "Text": 1, "Ignore List": 2, "Batchfile": 1, "Markdown": 1, "Kotlin": 27, "XML": 15, "Java": 1} | package com.tatuas.ghsv.ext
import android.view.LayoutInflater
import android.view.ViewGroup
import androidx.annotation.LayoutRes
import androidx.databinding.DataBindingUtil
import androidx.databinding.ViewDataBinding
import androidx.fragment.app.Fragment
import androidx.lifecycle.ViewModel
import androidx.lifecycle.ViewModelProviders
import com.tatuas.ghsv.data.viewmodel.ViewModelFactory
fun <T : ViewDataBinding> Fragment.buildDataBinding(@LayoutRes layoutId: Int,
inflater: LayoutInflater,
container: ViewGroup?): T =
DataBindingUtil.inflate(inflater, layoutId, container, false)
fun <T : ViewModel> Fragment.buildViewModel(modelClass: Class<T>): T =
ViewModelProviders.of(activity!!, ViewModelFactory(activity!!)).get(modelClass)
| 1 | null | 1 | 1 | 772b07639b5ec25dbeda8fc83933c82f125c12f6 | 860 | ghsv | MIT License |
netcode-mcbe/src/main/kotlin/com/valaphee/netcode/mcbe/network/packet/TradePacket.kt | valaphee | 431,915,568 | false | {"Kotlin": 1365906} | /*
* Copyright (c) 2021-2022, Valaphee.
*
* 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.valaphee.netcode.mcbe.network.packet
import com.fasterxml.jackson.annotation.JsonProperty
import com.fasterxml.jackson.module.kotlin.readValue
import com.valaphee.netcode.mcbe.network.Packet
import com.valaphee.netcode.mcbe.network.PacketBuffer
import com.valaphee.netcode.mcbe.network.PacketHandler
import com.valaphee.netcode.mcbe.network.Restrict
import com.valaphee.netcode.mcbe.network.Restriction
import com.valaphee.netcode.mcbe.world.inventory.WindowType
import com.valaphee.netcode.mcbe.world.item.ItemStack
import io.netty.buffer.ByteBufInputStream
import io.netty.buffer.ByteBufOutputStream
import java.io.OutputStream
/**
* @author <NAME>
*/
@Restrict(Restriction.ToClient)
class TradePacket(
val windowId: Int,
val type: WindowType,
val experience: Int,
val level: Int,
val uniqueEntityId: Long,
val playerUniqueEntityId: Long,
val title: String,
val v2: Boolean,
val restock: Boolean,
val data: Data
) : Packet() {
data class Data(
@JsonProperty("Recipes") val offers: List<Offer>,
@JsonProperty("TierExpRequirements") val tierExperienceRequirements: Map<Int, Int>
) {
data class Offer(
@JsonProperty("buyA") val buyA: ItemStack?,
@JsonProperty("buyCountA") val buyCountA: Int,
@JsonProperty("priceMultiplierA") val priceMultiplierA: Float,
@JsonProperty("sell") val sell: ItemStack?,
@JsonProperty("buyB") val buyB: ItemStack?,
@JsonProperty("buyCountB") val buyCountB: Int?,
@JsonProperty("priceMultiplierB") val priceMultiplierB: Float,
@JsonProperty("tier") val tier: Int,
@JsonProperty("uses") val sold: Int,
@JsonProperty("maxUses") val stock: Int,
@JsonProperty("traderExp") val experience: Int,
@JsonProperty("reward") val reward: Boolean,
@JsonProperty("demand") val demand: Int
)
}
override val id get() = 0x50
override fun write(buffer: PacketBuffer, version: Int) {
buffer.writeByte(windowId)
buffer.writeByte(type.id)
buffer.writeVarInt(experience)
buffer.writeVarInt(level)
buffer.writeVarLong(uniqueEntityId)
buffer.writeVarLong(playerUniqueEntityId)
buffer.writeString(title)
buffer.writeBoolean(v2)
buffer.writeBoolean(restock)
buffer.nbtVarIntObjectMapper.writeValue(ByteBufOutputStream(buffer) as OutputStream, data)
}
override fun handle(handler: PacketHandler) = handler.trade(this)
override fun toString() = "TradePacket(windowId=$windowId, type=$type, experience=$experience, level=$level, uniqueEntityId=$uniqueEntityId, playerUniqueEntityId=$playerUniqueEntityId, title='$title', v2=$v2, restock=$restock, data=$data)"
object Reader : Packet.Reader {
override fun read(buffer: PacketBuffer, version: Int) = TradePacket(buffer.readByte().toInt(), WindowType.byId(buffer.readByte().toInt()), buffer.readVarInt(), buffer.readVarInt(), buffer.readVarLong(), buffer.readVarLong(), buffer.readString(), buffer.readBoolean(), buffer.readBoolean(), buffer.nbtVarIntObjectMapper.readValue(ByteBufInputStream(buffer)))
}
}
| 0 | Kotlin | 0 | 2 | 4230a7ed71665360df32601956795b9ce8e2eb6c | 3,833 | netcode | Apache License 2.0 |
dessert-clicker/app/src/main/java/com/example/dessertclicker/ui/DessertViewModel.kt | Gabriel-Rodrigues13 | 741,078,861 | false | {"Kotlin": 280491} | package com.example.dessertclicker.ui
import androidx.lifecycle.ViewModel
import com.example.dessertclicker.data.Datasource.dessertList
import com.example.dessertclicker.data.DessertUiState
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.flow.update
class DessertViewModel: ViewModel() {
private val _dessertUiState = MutableStateFlow(DessertUiState())
val dessertUiState: StateFlow<DessertUiState> = _dessertUiState.asStateFlow()
fun onDessertClicked(){
_dessertUiState.update {cupcakeUiState ->
val dessertsSold = cupcakeUiState.dessertSold + 1
val nextDesertIndex = determineDessertToShow(dessertsSold)
cupcakeUiState.copy(
currentDessertIndex = nextDesertIndex,
dessertSold = dessertsSold,
totalRevenue = cupcakeUiState.totalRevenue + cupcakeUiState.currentDessertPrice,
currentDessertImageId = dessertList[nextDesertIndex].imageId,
currentDessertPrice = dessertList[nextDesertIndex].price
)
}
}
private fun determineDessertToShow(dessertsSold: Int): Int{
var dessertIndex = 0
for (index in dessertList.indices){
if(dessertsSold >= dessertList[index].startProductionAmount){
dessertIndex = index
}else{
break
}
}
return dessertIndex
}
} | 0 | Kotlin | 0 | 0 | 2317f01290b6e7f938ea3915ae555a40a5e31f45 | 1,527 | android_pathway | MIT License |
src/main/kotlin/net/ndrei/teslapoweredthingies/machines/treefarm/VanillaTreeBlock.kt | MinecraftModDevelopmentMods | 77,729,751 | false | {"Kotlin": 552829} | package net.ndrei.teslapoweredthingies.machines.treefarm
import net.minecraft.item.ItemStack
import net.minecraft.util.NonNullList
import net.minecraft.util.math.BlockPos
import net.minecraft.world.World
/**
* Created by CF on 2017-07-07.
*/
abstract class VanillaTreeBlock(protected val world: World, protected val pos: BlockPos)
: ITreeBlockWrapper {
override fun breakBlock(fortune: Int): List<ItemStack> {
val state = this.world.getBlockState(this.pos)
val stacks = NonNullList.create<ItemStack>()
state.block.getDrops(stacks, world, pos, state, fortune)
this.world.destroyBlock(this.pos, false)
return stacks
}
} | 21 | Kotlin | 4 | 2 | 22fdcf629e195a73dd85cf0ac0c5dda551085e71 | 676 | Tesla-Powered-Thingies | MIT License |
app/src/main/java/com/erickcapilla/dcyourself/RecoverPassword.kt | erickcapilla | 626,143,431 | false | null | package com.erickcapilla.dcyourself
import android.content.Intent
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.view.View
import android.widget.Button
import android.widget.EditText
import android.widget.ProgressBar
import android.widget.TextView
import androidx.appcompat.app.AlertDialog
import com.erickcapilla.dcyourself.util.UIUtils
import com.google.firebase.auth.FirebaseAuth
import com.google.firebase.auth.ktx.auth
import com.google.firebase.ktx.Firebase
class RecoverPassword : AppCompatActivity() {
private lateinit var auth: FirebaseAuth
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_recover_password)
auth = Firebase.auth
val uiModel = UIUtils()
val editEmail = findViewById<EditText>(R.id.editEmail)
val progressBar = findViewById<ProgressBar>(R.id.progressBar)
val progressTitle = findViewById<TextView>(R.id.progressTitle)
val goBack = findViewById<Button>(R.id.go_back)
val sendEmail = findViewById<Button>(R.id.next)
sendEmail.setOnClickListener {
if(uiModel.isEditEmpty(listOf(editEmail))) {
uiModel.showToast(applicationContext, "Ingresa tu correo")
return@setOnClickListener
}
val email = editEmail.text.toString()
if(!uiModel.isEmailValid(email)) {
uiModel.showToast(applicationContext, "Email no valido")
return@setOnClickListener
}
progressTitle.visibility = View.VISIBLE
progressBar.visibility = View.VISIBLE
sendEmail.isEnabled = false
sendEmail.setBackgroundResource(R.drawable.button_backgroun_unenable)
goBack.isEnabled = false
goBack.setBackgroundResource(R.drawable.button_backgroun_unenable)
auth.sendPasswordResetEmail(email)
.addOnCompleteListener {
if(it.isSuccessful) {
uiModel.showToast(this, "Email enviado. ¡Revisa tu correo!")
editEmail.setText("")
progressBar.visibility = View.GONE
progressTitle.visibility = View.GONE
sendEmail.isEnabled = true
sendEmail.setBackgroundResource(R.drawable.button_background_primary)
goBack.isEnabled = true
goBack.setBackgroundResource(R.drawable.button_background_secondary)
} else {
uiModel.showToast(this, "Hubo un problema")
editEmail.setText("")
progressBar.visibility = View.GONE
progressTitle.visibility = View.GONE
sendEmail.isEnabled = true
sendEmail.setBackgroundResource(R.drawable.button_background_primary)
goBack.isEnabled = true
goBack.setBackgroundResource(R.drawable.button_background_secondary)
}
}
}
goBack.setOnClickListener{
finish()
}
}
private fun goMain() {
val intent = Intent(this, MainActivity::class.java)
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP)
startActivity(intent)
}
@Deprecated("Deprecated in Java")
override fun onBackPressed() {
AlertDialog.Builder(this@RecoverPassword)
.setMessage("¿Salir de la aplicación?")
.setCancelable(false)
.setPositiveButton("Si") { dialog, whichButton ->
finishAffinity() //Sale de la aplicación.
}
.setNegativeButton("Cancelar") { dialog, whichButton ->
}
.show()
}
} | 0 | Kotlin | 0 | 0 | 646622d9a2af242cc0d03341a016beb1c074c9a4 | 3,907 | DCYourself | MIT License |
app/src/main/java/com/peteralexbizjak/ljbikes/api/services/BikesService.kt | sunderee | 407,182,934 | false | null | package com.peteralexbizjak.ljbikes.api.services
import com.peteralexbizjak.ljbikes.api.models.bikes.BikeModel
import retrofit2.http.GET
import retrofit2.http.Headers
import retrofit2.http.Query
internal interface BikesService {
@Headers(
"host: api.cyclocity.fr",
"accept: application/vnd.bikes.v3+json",
"user-agent: okhttp/4.9.0 vls.android.ljubljana:PRD/1.19.2"
)
@GET("contracts/ljubljana/bikes")
suspend fun requestBikesForStation(@Query("stationNumber") stationID: Int): List<BikeModel>
} | 0 | Kotlin | 0 | 1 | 624465405bfa257638a2f8bee5d122ae4ba0a49d | 537 | ljbikes | MIT License |
rounded/src/commonMain/kotlin/me/localx/icons/rounded/bold/Building.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.Building: ImageVector
get() {
if (_building != null) {
return _building!!
}
_building = Builder(name = "Building", defaultWidth = 512.0.dp, defaultHeight = 512.0.dp,
viewportWidth = 24.0f, viewportHeight = 24.0f).apply {
path(fill = SolidColor(Color(0xFF000000)), stroke = null, strokeLineWidth = 0.0f,
strokeLineCap = Butt, strokeLineJoin = Miter, strokeLineMiter = 4.0f,
pathFillType = NonZero) {
moveTo(18.5f, 5.0f)
lineTo(15.975f, 5.0f)
arcTo(5.506f, 5.506f, 0.0f, false, false, 10.5f, 0.0f)
horizontalLineToRelative(-5.0f)
arcTo(5.506f, 5.506f, 0.0f, false, false, 0.0f, 5.5f)
verticalLineToRelative(13.0f)
arcTo(5.506f, 5.506f, 0.0f, false, false, 5.5f, 24.0f)
horizontalLineToRelative(13.0f)
arcTo(5.506f, 5.506f, 0.0f, false, false, 24.0f, 18.5f)
verticalLineToRelative(-8.0f)
arcTo(5.506f, 5.506f, 0.0f, false, false, 18.5f, 5.0f)
close()
moveTo(3.0f, 18.5f)
lineTo(3.0f, 5.5f)
arcTo(2.5f, 2.5f, 0.0f, false, true, 5.5f, 3.0f)
horizontalLineToRelative(5.0f)
arcTo(2.5f, 2.5f, 0.0f, false, true, 13.0f, 5.5f)
lineTo(13.0f, 21.0f)
lineTo(5.5f, 21.0f)
arcTo(2.5f, 2.5f, 0.0f, false, true, 3.0f, 18.5f)
close()
moveTo(21.0f, 18.5f)
arcTo(2.5f, 2.5f, 0.0f, false, true, 18.5f, 21.0f)
lineTo(16.0f, 21.0f)
lineTo(16.0f, 8.0f)
horizontalLineToRelative(2.5f)
arcTo(2.5f, 2.5f, 0.0f, false, true, 21.0f, 10.5f)
close()
moveTo(20.0f, 11.5f)
arcTo(1.5f, 1.5f, 0.0f, true, true, 18.5f, 10.0f)
arcTo(1.5f, 1.5f, 0.0f, false, true, 20.0f, 11.5f)
close()
moveTo(20.0f, 16.5f)
arcTo(1.5f, 1.5f, 0.0f, true, true, 18.5f, 15.0f)
arcTo(1.5f, 1.5f, 0.0f, false, true, 20.0f, 16.5f)
close()
moveTo(7.0f, 6.5f)
arcTo(1.5f, 1.5f, 0.0f, true, true, 5.5f, 5.0f)
arcTo(1.5f, 1.5f, 0.0f, false, true, 7.0f, 6.5f)
close()
moveTo(7.0f, 11.5f)
arcTo(1.5f, 1.5f, 0.0f, true, true, 5.5f, 10.0f)
arcTo(1.5f, 1.5f, 0.0f, false, true, 7.0f, 11.5f)
close()
moveTo(12.0f, 6.5f)
arcTo(1.5f, 1.5f, 0.0f, true, true, 10.5f, 5.0f)
arcTo(1.5f, 1.5f, 0.0f, false, true, 12.0f, 6.5f)
close()
moveTo(12.0f, 11.5f)
arcTo(1.5f, 1.5f, 0.0f, true, true, 10.5f, 10.0f)
arcTo(1.5f, 1.5f, 0.0f, false, true, 12.0f, 11.5f)
close()
moveTo(7.0f, 16.5f)
arcTo(1.5f, 1.5f, 0.0f, true, true, 5.5f, 15.0f)
arcTo(1.5f, 1.5f, 0.0f, false, true, 7.0f, 16.5f)
close()
moveTo(12.0f, 16.5f)
arcTo(1.5f, 1.5f, 0.0f, true, true, 10.5f, 15.0f)
arcTo(1.5f, 1.5f, 0.0f, false, true, 12.0f, 16.5f)
close()
}
}
.build()
return _building!!
}
private var _building: ImageVector? = null
| 1 | Kotlin | 0 | 5 | cbd8b510fca0e5e40e95498834f23ec73cc8f245 | 4,109 | icons | MIT License |
preferences-adapter-flow/src/main/java/io/androidalatan/datastore/preference/adapter/flow/FlowClearAdapter.kt | android-alatan | 462,405,374 | false | null | package io.androidalatan.datastore.preference.adapter.flow
import android.content.SharedPreferences
import io.androidalatan.datastore.preference.adapter.api.ClearAdapter
import io.androidalatan.datastore.preference.adapter.api.ValueObserver
import kotlinx.coroutines.channels.awaitClose
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.callbackFlow
import kotlinx.coroutines.flow.flowOn
import kotlin.coroutines.CoroutineContext
class FlowClearAdapter(private val coroutineContext: CoroutineContext) : ClearAdapter {
override fun acceptable(returnType: Class<*>): Boolean {
return returnType == Flow::class.java
}
override fun adapt(returnType: Class<*>, sharedPreferences: SharedPreferences, valueObserver: ValueObserver): Any? {
return callbackFlow {
val listener = registerForOnetime(sharedPreferences) {
valueObserver.clear()
trySend(true)
close()
}
sharedPreferences.edit()
.clear()
.apply()
awaitClose {
sharedPreferences.unregisterOnSharedPreferenceChangeListener(listener)
}
}.flowOn(coroutineContext)
}
private fun registerForOnetime(
sharedPreferences: SharedPreferences,
notified: (SharedPreferences) -> Unit = {}
): SharedPreferences.OnSharedPreferenceChangeListener {
val onSharedPreferenceChangeListener = object : SharedPreferences.OnSharedPreferenceChangeListener {
override fun onSharedPreferenceChanged(sharedPreferences: SharedPreferences, key: String?) {
if (sharedPreferences.all.isEmpty()) {
sharedPreferences.unregisterOnSharedPreferenceChangeListener(this)
notified.invoke(sharedPreferences)
}
}
}
sharedPreferences.registerOnSharedPreferenceChangeListener(onSharedPreferenceChangeListener)
return onSharedPreferenceChangeListener
}
} | 0 | Kotlin | 1 | 2 | 6c7abf477c0ec251abd244df78ea0ca9ce15174d | 2,033 | Preferences | MIT License |
projector-launcher/src/main/kotlin/GlobalSettings.kt | JetBrains | 267,844,825 | false | null | /*
* MIT License
*
* Copyright (c) 2019-2023 JetBrains s.r.o.
*
* 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.
*/
class GlobalSettings {
companion object {
var node_path = require("path")
var node_os = require("os")
var LOG_LEVEL: String = "debug"
var DEVELOPER_TOOLS_ENABLED: Boolean = false
var USER_CONFIG_DIR: String = node_os.homedir() + node_path.sep + ".projector-launcher"
var USER_CONFIG_FILE: String = node_os.homedir() + node_path.sep + ".projector-launcher" + node_path.sep + "settings.json"
}
}
| 20 | null | 94 | 815 | 0f1e08a68f01c417a7ce8a58afe77d63603e22db | 1,567 | projector-client | MIT License |
work/work-runtime/src/main/java/androidx/work/impl/model/WorkSpecDao.kt | androidx | 256,589,781 | false | null | /*
* Copyright (C) 2017 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.work.impl.model
import android.annotation.SuppressLint
import androidx.lifecycle.LiveData
import androidx.room.Dao
import androidx.room.Insert
import androidx.room.OnConflictStrategy
import androidx.room.Query
import androidx.room.Transaction
import androidx.room.Update
import androidx.work.CONSTRAINTS_COLUMNS
import androidx.work.Data
import androidx.work.WorkInfo
import androidx.work.impl.model.WorkTypeConverters.StateIds.COMPLETED_STATES
import androidx.work.impl.model.WorkTypeConverters.StateIds.ENQUEUED
import java.util.UUID
import kotlinx.coroutines.CoroutineDispatcher
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.distinctUntilChanged
import kotlinx.coroutines.flow.flowOn
import kotlinx.coroutines.flow.map
import org.intellij.lang.annotations.Language
/**
* The Data Access Object for [WorkSpec]s.
*/
@Dao
@SuppressLint("UnknownNullness")
interface WorkSpecDao {
/**
* Attempts to insert a [WorkSpec] into the database.
*
* @param workSpec The WorkSpec to insert.
*/
@Insert(onConflict = OnConflictStrategy.IGNORE)
fun insertWorkSpec(workSpec: WorkSpec)
/**
* Deletes [WorkSpec]s from the database.
*
* @param id The WorkSpec id to delete.
*/
@Query("DELETE FROM workspec WHERE id=:id")
fun delete(id: String)
/**
* @param id The identifier
* @return The WorkSpec associated with that id
*/
@Query("SELECT * FROM workspec WHERE id=:id")
fun getWorkSpec(id: String): WorkSpec?
/**
*
* @param name The work graph name
* @return The [WorkSpec]s labelled with the given name
*/
@Query(
"SELECT id, state FROM workspec WHERE id IN " +
"(SELECT work_spec_id FROM workname WHERE name=:name)"
)
fun getWorkSpecIdAndStatesForName(name: String): List<WorkSpec.IdAndState>
/**
* @return All WorkSpec ids in the database.
*/
@Query("SELECT id FROM workspec")
fun getAllWorkSpecIds(): List<String>
/**
* @return A [LiveData] list of all WorkSpec ids in the database.
*/
@Transaction
@Query("SELECT id FROM workspec")
fun getAllWorkSpecIdsLiveData(): LiveData<List<String>>
/**
* Updates the state of at least one [WorkSpec] by ID.
*
* @param state The new state
* @param id The IDs for the [WorkSpec]s to update
* @return The number of rows that were updated
*/
@Query("UPDATE workspec SET state=:state WHERE id=:id")
fun setState(state: WorkInfo.State, id: String): Int
/**
* Increment periodic counter.
*/
@Query("UPDATE workspec SET period_count=period_count+1 WHERE id=:id")
fun incrementPeriodCount(id: String)
/**
* Updates the output of a [WorkSpec].
*
* @param id The [WorkSpec] identifier to update
* @param output The [Data] to set as the output
*/
@Query("UPDATE workspec SET output=:output WHERE id=:id")
fun setOutput(id: String, output: Data)
/**
* Updates the period start time of a [WorkSpec].
*
* @param id The [WorkSpec] identifier to update
* @param enqueueTime The time when the period started.
*/
@Query("UPDATE workspec SET last_enqueue_time=:enqueueTime WHERE id=:id")
fun setLastEnqueueTime(id: String, enqueueTime: Long)
/**
* Increment run attempt count of a [WorkSpec].
*
* @param id The identifier for the [WorkSpec]
* @return The number of rows that were updated (should be 0 or 1)
*/
@Query("UPDATE workspec SET run_attempt_count=run_attempt_count+1 WHERE id=:id")
fun incrementWorkSpecRunAttemptCount(id: String): Int
/**
* Reset run attempt count of a [WorkSpec].
*
* @param id The identifier for the [WorkSpec]
* @return The number of rows that were updated (should be 0 or 1)
*/
@Query("UPDATE workspec SET run_attempt_count=0 WHERE id=:id")
fun resetWorkSpecRunAttemptCount(id: String): Int
/**
* Resets the next schedule time override of a [WorkSpec] if the override generation has not
* changed.
*
* @param id The identifier for the [WorkSpec]
*/
@Query("UPDATE workspec SET next_schedule_time_override=${Long.MAX_VALUE} WHERE " +
"(id=:id AND next_schedule_time_override_generation=:overrideGeneration)")
fun resetWorkSpecNextScheduleTimeOverride(id: String, overrideGeneration: Int)
/**
* Retrieves the state of a [WorkSpec].
*
* @param id The identifier for the [WorkSpec]
* @return The state of the [WorkSpec]
*/
@Query("SELECT state FROM workspec WHERE id=:id")
fun getState(id: String): WorkInfo.State?
/**
* For a [WorkSpec] identifier, retrieves its [WorkSpec.WorkInfoPojo].
*
* @param id The identifier of the [WorkSpec]
* @return A list of [WorkSpec.WorkInfoPojo]
*/
@Transaction
@Query("SELECT $WORK_INFO_COLUMNS FROM workspec WHERE id=:id")
fun getWorkStatusPojoForId(id: String): WorkSpec.WorkInfoPojo?
/**
* For a list of [WorkSpec] identifiers, retrieves a [List] of their
* [WorkSpec.WorkInfoPojo].
*
* @param ids The identifier of the [WorkSpec]s
* @return A [List] of [WorkSpec.WorkInfoPojo]
*/
@Transaction
@Query("SELECT $WORK_INFO_COLUMNS FROM workspec WHERE id IN (:ids)")
fun getWorkStatusPojoForIds(ids: List<String>): List<WorkSpec.WorkInfoPojo>
/**
* For a list of [WorkSpec] identifiers, retrieves a [LiveData] list of their
* [WorkSpec.WorkInfoPojo].
*
* @param ids The identifier of the [WorkSpec]s
* @return A [LiveData] list of [WorkSpec.WorkInfoPojo]
*/
@Transaction
@Query(WORK_INFO_BY_IDS)
fun getWorkStatusPojoLiveDataForIds(ids: List<String>): LiveData<List<WorkSpec.WorkInfoPojo>>
/**
* For a list of [WorkSpec] identifiers, retrieves a [LiveData] list of their
* [WorkSpec.WorkInfoPojo].
*
* @param ids The identifier of the [WorkSpec]s
* @return A [Flow] list of [WorkSpec.WorkInfoPojo]
*/
@Transaction
@Query(WORK_INFO_BY_IDS)
fun getWorkStatusPojoFlowDataForIds(ids: List<String>): Flow<List<WorkSpec.WorkInfoPojo>>
/**
* Retrieves a list of [WorkSpec.WorkInfoPojo] for all work with a given tag.
*
* @param tag The tag for the [WorkSpec]s
* @return A list of [WorkSpec.WorkInfoPojo]
*/
@Transaction
@Query(
"""SELECT $WORK_INFO_COLUMNS FROM workspec WHERE id IN
(SELECT work_spec_id FROM worktag WHERE tag=:tag)"""
)
fun getWorkStatusPojoForTag(tag: String): List<WorkSpec.WorkInfoPojo>
/**
* Retrieves a [LiveData] list of [WorkSpec.WorkInfoPojo] for all work with a
* given tag.
*
* @param tag The tag for the [WorkSpec]s
* @return A [LiveData] list of [WorkSpec.WorkInfoPojo]
*/
@Transaction
@Query(WORK_INFO_BY_TAG)
fun getWorkStatusPojoFlowForTag(tag: String): Flow<List<WorkSpec.WorkInfoPojo>>
/**
* Retrieves a [LiveData] list of [WorkSpec.WorkInfoPojo] for all work with a
* given tag.
*
* @param tag The tag for the [WorkSpec]s
* @return A [LiveData] list of [WorkSpec.WorkInfoPojo]
*/
@Transaction
@Query(WORK_INFO_BY_TAG)
fun getWorkStatusPojoLiveDataForTag(tag: String): LiveData<List<WorkSpec.WorkInfoPojo>>
/**
* Retrieves a list of [WorkSpec.WorkInfoPojo] for all work with a given name.
*
* @param name The name of the [WorkSpec]s
* @return A list of [WorkSpec.WorkInfoPojo]
*/
@Transaction
@Query(
"SELECT $WORK_INFO_COLUMNS FROM workspec WHERE id IN " +
"(SELECT work_spec_id FROM workname WHERE name=:name)"
)
fun getWorkStatusPojoForName(name: String): List<WorkSpec.WorkInfoPojo>
/**
* Retrieves a [LiveData] list of [WorkSpec.WorkInfoPojo] for all work with a
* given name.
*
* @param name The name for the [WorkSpec]s
* @return A [LiveData] list of [WorkSpec.WorkInfoPojo]
*/
@Transaction
@Query(WORK_INFO_BY_NAME)
fun getWorkStatusPojoLiveDataForName(name: String): LiveData<List<WorkSpec.WorkInfoPojo>>
/**
* Retrieves a [Flow] list of [WorkSpec.WorkInfoPojo] for all work with a given name.
*
* @param name The name for the [WorkSpec]s
* @return A [LiveData] list of [WorkSpec.WorkInfoPojo]
*/
@Transaction
@Query(WORK_INFO_BY_NAME)
fun getWorkStatusPojoFlowForName(name: String): Flow<List<WorkSpec.WorkInfoPojo>>
/**
* Gets all inputs coming from prerequisites for a particular [WorkSpec]. These are
* [Data] set via `Worker#setOutputData()`.
*
* @param id The [WorkSpec] identifier
* @return A list of all inputs coming from prerequisites for `id`
*/
@Query(
"""SELECT output FROM workspec WHERE id IN
(SELECT prerequisite_id FROM dependency WHERE work_spec_id=:id)"""
)
fun getInputsFromPrerequisites(id: String): List<Data>
/**
* Retrieves work ids for unfinished work with a given tag.
*
* @param tag The tag used to identify the work
* @return A list of work ids
*/
@Query(
"SELECT id FROM workspec WHERE state NOT IN " + COMPLETED_STATES +
" AND id IN (SELECT work_spec_id FROM worktag WHERE tag=:tag)"
)
fun getUnfinishedWorkWithTag(tag: String): List<String>
/**
* Retrieves work ids for unfinished work with a given name.
*
* @param name THe tag used to identify the work
* @return A list of work ids
*/
@Query(
"SELECT id FROM workspec WHERE state NOT IN " + COMPLETED_STATES +
" AND id IN (SELECT work_spec_id FROM workname WHERE name=:name)"
)
fun getUnfinishedWorkWithName(name: String): List<String>
/**
* Retrieves work ids for all unfinished work.
*
* @return A list of work ids
*/
@Query("SELECT id FROM workspec WHERE state NOT IN " + COMPLETED_STATES)
fun getAllUnfinishedWork(): List<String>
/**
* @return `true` if there is pending work.
*/
@Query("SELECT COUNT(*) > 0 FROM workspec WHERE state NOT IN $COMPLETED_STATES LIMIT 1")
fun hasUnfinishedWork(): Boolean
/**
* Marks a [WorkSpec] as scheduled.
*
* @param id The identifier for the [WorkSpec]
* @param startTime The time at which the [WorkSpec] was scheduled.
* @return The number of rows that were updated (should be 0 or 1)
*/
@Query("UPDATE workspec SET schedule_requested_at=:startTime WHERE id=:id")
fun markWorkSpecScheduled(id: String, startTime: Long): Int
/**
* @return The time at which the [WorkSpec] was scheduled.
*/
@Query("SELECT schedule_requested_at FROM workspec WHERE id=:id")
fun getScheduleRequestedAtLiveData(id: String): LiveData<Long>
/**
* Resets the scheduled state on the [WorkSpec]s that are not in a a completed state.
* @return The number of rows that were updated
*/
@Query(
"UPDATE workspec SET schedule_requested_at=" + WorkSpec.SCHEDULE_NOT_REQUESTED_YET +
" WHERE state NOT IN " + COMPLETED_STATES
)
fun resetScheduledState(): Int
/**
* @return The List of [WorkSpec]s that are eligible to be scheduled.
*/
@Query(
"SELECT * FROM workspec WHERE " +
"state=" + ENQUEUED +
// We only want WorkSpecs which have not been previously scheduled.
" AND schedule_requested_at=" + WorkSpec.SCHEDULE_NOT_REQUESTED_YET +
// Order by period start time so we execute scheduled WorkSpecs in FIFO order
" ORDER BY last_enqueue_time" +
" LIMIT " +
"(SELECT MAX(:schedulerLimit" + "-COUNT(*), 0) FROM workspec WHERE" +
" schedule_requested_at<>" + WorkSpec.SCHEDULE_NOT_REQUESTED_YET +
// content_uri_triggers aren't counted here because they have separate limit
" AND LENGTH(content_uri_triggers)=0" +
" AND state NOT IN " + COMPLETED_STATES +
")"
)
fun getEligibleWorkForScheduling(schedulerLimit: Int): List<WorkSpec>
/**
* @return The List of [WorkSpec]s that are eligible to be scheduled.
*/
@Query(
"SELECT * FROM workspec WHERE " +
"state=$ENQUEUED" +
// We only want WorkSpecs which have not been previously scheduled.
" AND schedule_requested_at=${WorkSpec.SCHEDULE_NOT_REQUESTED_YET}" +
" AND LENGTH(content_uri_triggers)<>0" +
// Order by period start time so we execute scheduled WorkSpecs in FIFO order
" ORDER BY last_enqueue_time"
)
fun getEligibleWorkForSchedulingWithContentUris(): List<WorkSpec>
/**
* @return The List of [WorkSpec]s that can be scheduled irrespective of scheduling
* limits.
*/
@Query(
"SELECT * FROM workspec WHERE " +
"state=$ENQUEUED" +
// Order by period start time so we execute scheduled WorkSpecs in FIFO order
" ORDER BY last_enqueue_time" +
" LIMIT :maxLimit"
)
fun getAllEligibleWorkSpecsForScheduling(maxLimit: Int): List<WorkSpec> // Unfinished work
// We only want WorkSpecs which have been scheduled.
/**
* @return The List of [WorkSpec]s that are unfinished and scheduled.
*/
@Query(
"SELECT * FROM workspec WHERE " + // Unfinished work
"state=" + ENQUEUED + // We only want WorkSpecs which have been scheduled.
" AND schedule_requested_at<>" + WorkSpec.SCHEDULE_NOT_REQUESTED_YET
)
fun getScheduledWork(): List<WorkSpec>
/**
* @return The List of [WorkSpec]s that are running.
*/
@Query(
"SELECT * FROM workspec WHERE " + // Unfinished work
"state=" + WorkTypeConverters.StateIds.RUNNING
)
fun getRunningWork(): List<WorkSpec>
/**
* @return The List of [WorkSpec] which completed recently.
*/
@Query(
"SELECT * FROM workspec WHERE " +
"last_enqueue_time >= :startingAt" +
" AND state IN " + COMPLETED_STATES +
" ORDER BY last_enqueue_time DESC"
)
fun getRecentlyCompletedWork(startingAt: Long): List<WorkSpec>
/**
* Immediately prunes eligible work from the database meeting the following criteria:
* - Is finished (succeeded, failed, or cancelled)
* - Has zero unfinished dependents
*/
@Query(
"DELETE FROM workspec WHERE " +
"state IN " + COMPLETED_STATES +
" AND (SELECT COUNT(*)=0 FROM dependency WHERE " +
" prerequisite_id=id AND " +
" work_spec_id NOT IN " +
" (SELECT id FROM workspec WHERE state IN " + COMPLETED_STATES + "))"
)
fun pruneFinishedWorkWithZeroDependentsIgnoringKeepForAtLeast()
@Query("UPDATE workspec SET generation=generation+1 WHERE id=:id")
fun incrementGeneration(id: String)
@Update
fun updateWorkSpec(workSpec: WorkSpec)
@Query("Select COUNT(*) FROM workspec WHERE LENGTH(content_uri_triggers)<>0" +
" AND state NOT IN $COMPLETED_STATES"
)
fun countNonFinishedContentUriTriggerWorkers(): Int
}
fun WorkSpecDao.getWorkStatusPojoFlowDataForIds(id: UUID): Flow<WorkInfo?> =
getWorkStatusPojoFlowDataForIds(listOf("$id"))
.map { it.firstOrNull()?.toWorkInfo() }.distinctUntilChanged()
fun WorkSpecDao.getWorkStatusPojoFlowForName(
dispatcher: CoroutineDispatcher,
name: String
): Flow<List<WorkInfo>> = getWorkStatusPojoFlowForName(name).dedup(dispatcher)
fun WorkSpecDao.getWorkStatusPojoFlowForTag(
dispatcher: CoroutineDispatcher,
tag: String
): Flow<List<WorkInfo>> = getWorkStatusPojoFlowForTag(tag).dedup(dispatcher)
internal fun Flow<List<WorkSpec.WorkInfoPojo>>.dedup(
dispatcher: CoroutineDispatcher
): Flow<List<WorkInfo>> = map { list -> list.map { pojo -> pojo.toWorkInfo() } }
.distinctUntilChanged()
.flowOn(dispatcher)
private const val WORK_INFO_COLUMNS = "id, state, output, run_attempt_count, generation" +
", $CONSTRAINTS_COLUMNS, initial_delay, interval_duration, flex_duration, backoff_policy" +
", backoff_delay_duration, last_enqueue_time, period_count, next_schedule_time_override"
@Language("sql")
private const val WORK_INFO_BY_IDS = "SELECT $WORK_INFO_COLUMNS FROM workspec WHERE id IN (:ids)"
@Language("sql")
private const val WORK_INFO_BY_TAG = """SELECT $WORK_INFO_COLUMNS FROM workspec WHERE id IN
(SELECT work_spec_id FROM worktag WHERE tag=:tag)"""
@Language("sql")
private const val WORK_INFO_BY_NAME = "SELECT $WORK_INFO_COLUMNS FROM workspec WHERE id IN " +
"(SELECT work_spec_id FROM workname WHERE name=:name)"
| 29 | null | 937 | 5,321 | 98b929d303f34d569e9fd8a529f022d398d1024b | 17,452 | androidx | Apache License 2.0 |
app/src/main/java/com/hfut/schedule/logic/utils/Encrypt.kt | Chiu-xaH | 705,508,343 | false | {"Kotlin": 1386786, "HTML": 77257, "Java": 686} | package com.hfut.schedule.logic.utils
import android.os.Build
import android.util.Base64
import androidx.annotation.RequiresApi
import javax.crypto.Cipher
import javax.crypto.spec.SecretKeySpec
object Encrypt {
fun AESencrypt(input:String, password:String): String{
val cipher = Cipher.getInstance("AES")
val keySpec:SecretKeySpec? = SecretKeySpec(password.toByteArray(),"AES")
cipher.init(Cipher.ENCRYPT_MODE,keySpec)
val encrypt = cipher.doFinal(input.toByteArray())
return Base64.encodeToString(encrypt,Base64.NO_WRAP)
}
@RequiresApi(Build.VERSION_CODES.O)
fun encodeToBase64(input: String): String {
return java.util.Base64.getEncoder().encodeToString(input.toByteArray(Charsets.UTF_8))
}
}
| 0 | Kotlin | 1 | 3 | aead3d3e437531c52a0ba99d71fae27d4ea0fe4f | 766 | HFUT-Schedule | Apache License 2.0 |
app/src/main/java/com/hfut/schedule/logic/utils/Encrypt.kt | Chiu-xaH | 705,508,343 | false | {"Kotlin": 1386786, "HTML": 77257, "Java": 686} | package com.hfut.schedule.logic.utils
import android.os.Build
import android.util.Base64
import androidx.annotation.RequiresApi
import javax.crypto.Cipher
import javax.crypto.spec.SecretKeySpec
object Encrypt {
fun AESencrypt(input:String, password:String): String{
val cipher = Cipher.getInstance("AES")
val keySpec:SecretKeySpec? = SecretKeySpec(password.toByteArray(),"AES")
cipher.init(Cipher.ENCRYPT_MODE,keySpec)
val encrypt = cipher.doFinal(input.toByteArray())
return Base64.encodeToString(encrypt,Base64.NO_WRAP)
}
@RequiresApi(Build.VERSION_CODES.O)
fun encodeToBase64(input: String): String {
return java.util.Base64.getEncoder().encodeToString(input.toByteArray(Charsets.UTF_8))
}
}
| 0 | Kotlin | 1 | 3 | aead3d3e437531c52a0ba99d71fae27d4ea0fe4f | 766 | HFUT-Schedule | Apache License 2.0 |
src/main/kotlin/me/thevipershow/connectionprotocol/io/NetOut.kt | TheViperShow | 260,898,183 | false | null | // Copyright 2020 TheViperShow
//
// 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
//
package me.thevipershow.connectionprotocol.io
import java.io.IOException
import java.util.UUID
interface NetOut {
@Throws(IOException::class)
fun writeBoolean(boolean: Boolean)
@Throws(IOException::class)
fun writeByte(byte: Int)
@Throws(IOException::class)
fun writeShort(short: Int)
@Throws(IOException::class)
fun writeChar(char: Int)
@Throws(IOException::class)
fun writeInt(int: Int)
@Throws(IOException::class)
fun writeVarInt(int: Int)
@Throws(IOException::class)
fun writeLong(long: Long)
@Throws(IOException::class)
fun writeVarLong(varLong: Long)
@Throws(IOException::class)
fun writeFloat(float: Float)
@Throws(IOException::class)
fun writeDouble(double: Double)
@Throws(IOException::class)
fun writeBytes(byteArray: ByteArray)
@Throws(IOException::class)
fun writeBytes(byteArray: ByteArray, length: Int)
@Throws(IOException::class)
fun writeShorts(shortArray: ShortArray)
@Throws(IOException::class)
fun writeShorts(shortArray: ShortArray, length: Int)
@Throws(IOException::class)
fun writeInts(intArray: IntArray)
@Throws(IOException::class)
fun writeInts(intArray: IntArray, length: Int)
@Throws(IOException::class)
fun writeLongs(longArray: LongArray)
@Throws(IOException::class)
fun writeLongs(longArray: LongArray, length: Int)
@Throws(IOException::class)
fun writeString(string: String)
@Throws(IOException::class)
fun writeUUID(uuid: UUID)
@Throws(IOException::class)
fun flush()
} | 0 | Kotlin | 0 | 3 | 8f43e927c807721809c85aad5816b2163013c8ff | 1,852 | ConnectionProtocol | Apache License 2.0 |
idea/testData/copyPaste/plainTextLiteral/WithBackslashes.kt | JakeWharton | 99,388,807 | false | null | val pattern = "<caret>" | 0 | null | 28 | 83 | 4383335168338df9bbbe2a63cb213a68d0858104 | 23 | kotlin | Apache License 2.0 |
src/main/kotlin/me/nekomatamune/ygomaker/fx/CardListCtrl.kt | nekomatamune | 211,016,495 | false | null | package me.nekomatamune.ygomaker.fx
import javafx.fxml.FXML
import javafx.scene.control.Button
import javafx.scene.control.ComboBox
import javafx.scene.control.ListCell
import javafx.scene.control.ListView
import javafx.scene.control.TextField
import javafx.stage.DirectoryChooser
import me.nekomatamune.ygomaker.Card
import me.nekomatamune.ygomaker.Command
import me.nekomatamune.ygomaker.FileIO
import me.nekomatamune.ygomaker.Language
import me.nekomatamune.ygomaker.Pack
import me.nekomatamune.ygomaker.Result
import me.nekomatamune.ygomaker.failure
import mu.KotlinLogging
import java.lang.Integer.min
import java.nio.file.Path
private val logger = KotlinLogging.logger { }
open class CardListCtrl(
private val dataDir: Path = Command.dataDir,
private val directoryChooserFactory: () -> DirectoryChooser = { DirectoryChooser() },
private val fileIO: FileIO = FileIO()
) {
// region FXML components and backed properties
@FXML private lateinit var packNameTextField: TextField
@FXML private lateinit var packCodeTextField: TextField
@FXML private lateinit var languageComboBox: ComboBox<Language>
@FXML private lateinit var cardListView: ListView<Card>
@FXML private lateinit var addCardButton: Button
@FXML private lateinit var removeCardButton: Button
private lateinit var packDir: Path
private var pack: Pack
get() = Pack(
name = packNameTextField.text,
code = packCodeTextField.text,
language = languageComboBox.selectionModel.selectedItem,
cards = cardListView.items.toList()
)
set(value) {
handlerLock.lockAndRun {
packNameTextField.text = value.name
packCodeTextField.text = value.code
languageComboBox.selectionModel.select(value.language)
cardListView.items.setAll(value.cards)
cardListView.selectionModel.selectFirst()
}
}
private var selectedCardIdx: Int
get() = cardListView.selectionModel.selectedIndex
set(value) {
handlerLock.lockAndRun {
cardListView.selectionModel.select(value)
}
}
private var selectedCard: Card
get() = cardListView.selectionModel.selectedItem
set(value) {
handlerLock.lockAndRun {
cardListView.items[cardListView.selectionModel.selectedIndex] = value
}
}
// endregion
var cardSelectedHandler: (Card, Path) -> Result<Unit> = { _, _ ->
failure(IllegalStateException("Handler not set"))
}
private val handlerLock = HandlerLock()
private var disableOnSelectCard = false
@FXML
private fun initialize() {
logger.debug { "Initializing CardList" }
// sequenceOf(
// packNameTextField, packCodeTextField, languageComboBox
// ).forEach {
// it.addSimpleListener { onModifyPackInfo() }
// }
//
cardListView.apply {
setCellFactory {
object : ListCell<Card>() {
override fun updateItem(item: Card?, empty: Boolean) {
super.updateItem(item, empty)
text = if (item == null) null else "${item.code} ${item.name}"
}
}
}
selectionModel.selectedItemProperty()
.addListener(handlerLock) { _, newValue ->
cardSelectedHandler(newValue, packDir).alertFailure()
}
}
addCardButton.setOnAction { addCard().alertFailure() }
removeCardButton.setOnAction { removeCard().alertFailure() }
//
// languageComboBox.items = observableList(Language.values().toList())
// languageComboBox.selectionModel.selectFirst()
}
fun updatePackDir(newPackDir: Path) {
packDir = newPackDir
}
fun updatePack(newPack: Pack) {
pack = newPack
}
fun modifySelectedCard(newCard: Card) {
selectedCard = newCard
}
fun loadPack(newPackDir: Path? = null): Result<Unit> {
println("loadPack($newPackDir")
val newPackDir = newPackDir ?: directoryChooserFactory().apply {
title = "Select a Pack Directory to Load"
initialDirectory = dataDir.toFile()
}.showDialog(null).toPath()
pack = fileIO.readPack(newPackDir).onFailure {
return it
}
packDir = newPackDir
return cardSelectedHandler(selectedCard, newPackDir)
}
fun savePack(): Result<Unit> {
return fileIO.writePack(pack, packDir)
}
fun savePackAs(): Result<Unit> {
val fileChooser = directoryChooserFactory().apply {
title = "Select a Pack Directory to Save"
initialDirectory = dataDir.toFile()
}
val newPackDir = fileChooser.showDialog(null).toPath()
fileIO.copyPack(packDir, newPackDir).onFailure {
return it
}
packDir = newPackDir
return cardSelectedHandler(selectedCard, packDir)
}
fun addCard(): Result<Unit> {
pack = pack.copy(cards = pack.cards + Card(name = "New Card"))
selectedCardIdx = pack.cards.size - 1
return cardSelectedHandler(selectedCard, packDir)
}
fun removeCard(): Result<Unit> {
val previousSelectedCardIdx = selectedCardIdx
pack = pack.copy(cards = pack.cards - selectedCard)
selectedCardIdx = min(previousSelectedCardIdx, pack.cards.size - 1)
return cardSelectedHandler(selectedCard, packDir)
}
} | 4 | Kotlin | 0 | 0 | 1dcab6556262d4ac75f228126e7ded0799966425 | 4,872 | ygomaker | MIT License |
app/src/main/java/com/orange/ods/app/ui/components/listitem/ListItemCustomizationState.kt | Orange-OpenSource | 440,548,737 | false | {"Kotlin": 862831, "HTML": 13867, "CSS": 1444, "Shell": 587, "JavaScript": 197} | /*
*
* Copyright 2021 Orange
*
* Use of this source code is governed by an MIT-style
* license that can be found in the LICENSE file or at
* https://opensource.org/licenses/MIT.
* /
*/
package com.orange.ods.app.ui.components.listitem
import androidx.compose.material.BottomSheetScaffoldState
import androidx.compose.material.ExperimentalMaterialApi
import androidx.compose.material.rememberBottomSheetScaffoldState
import androidx.compose.runtime.Composable
import androidx.compose.runtime.MutableState
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.saveable.rememberSaveable
import com.orange.ods.compose.component.list.OdsListItemIconType
import com.orange.ods.compose.component.list.OdsListItemTrailing
import com.orange.ods.compose.component.list.OdsListItemTrailingCaption
import com.orange.ods.compose.component.list.OdsListItemTrailingCheckbox
import com.orange.ods.compose.component.list.OdsListItemTrailingIcon
import com.orange.ods.compose.component.list.OdsListItemTrailingRadioButton
import com.orange.ods.compose.component.list.OdsListItemTrailingSwitch
@OptIn(ExperimentalMaterialApi::class)
@Composable
fun rememberListItemCustomizationState(
bottomSheetScaffoldState: BottomSheetScaffoldState = rememberBottomSheetScaffoldState(),
lineCount: MutableState<Int> = rememberSaveable { mutableStateOf(ListItemCustomizationState.DefaultLineCount) },
selectedIconType: MutableState<OdsListItemIconType?> = rememberSaveable { mutableStateOf(null) },
selectedTrailing: MutableState<Class<out OdsListItemTrailing>?> = rememberSaveable { mutableStateOf(null) },
) = remember(lineCount) {
ListItemCustomizationState(bottomSheetScaffoldState, lineCount, selectedIconType, selectedTrailing)
}
@OptIn(ExperimentalMaterialApi::class)
class ListItemCustomizationState(
val bottomSheetScaffoldState: BottomSheetScaffoldState,
val lineCount: MutableState<Int>,
val selectedIconType: MutableState<OdsListItemIconType?>,
val selectedTrailing: MutableState<Class<out OdsListItemTrailing>?>,
) {
companion object {
const val DefaultLineCount = 2
const val MinLineCount = 1
const val MaxLineCount = 3
}
val trailings: List<Class<out OdsListItemTrailing>?>
get() = if (lineCount.value < MaxLineCount) {
listOf(
null,
OdsListItemTrailingCheckbox::class.java,
OdsListItemTrailingSwitch::class.java,
OdsListItemTrailingRadioButton::class.java,
OdsListItemTrailingIcon::class.java
)
} else {
listOf(null, OdsListItemTrailingCaption::class.java)
}
fun resetTrailing() {
selectedTrailing.value = null
}
} | 83 | Kotlin | 3 | 14 | 48df1aa53950dc221f1d938242d7170e35d050fc | 2,809 | ods-android | MIT License |
presentation/src/main/java/hiennguyen/me/weatherapp/common/binding/ImageConverters.kt | hiennguyen1001 | 123,107,985 | false | null | package hiennguyen.me.weatherapp.common.binding
import androidx.databinding.BindingAdapter
import android.graphics.drawable.Drawable
import android.view.View
import android.widget.ImageView
import com.bumptech.glide.load.engine.DiskCacheStrategy
import hiennguyen.me.weatherapp.utils.GlideApp
@BindingAdapter("backgroundRes")
fun setBackgroundDrawableRes(view: View?, resId: Int?) {
if (view == null || resId == null) {
return
}
view.setBackgroundResource(resId)
}
@BindingAdapter("imageRes")
fun setImageDrawableRes(view: ImageView?, resId: Int?) {
if (view == null || resId == null) {
return
}
view.setImageResource(resId)
}
@BindingAdapter(value = ["imageUrl", "placeholder"], requireAll = false)
fun setImageRemote(view: ImageView?, url: String?, placeholder: Drawable?) {
if (view == null || url == null) {
return
}
if (placeholder != null) {
GlideApp.with(view)
.load(url)
.diskCacheStrategy(DiskCacheStrategy.NONE)
.placeholder(placeholder)
.into(view)
} else {
GlideApp.with(view.context).load(url).into(view)
}
}
| 1 | Kotlin | 1 | 2 | a1d782792ccfabcad5710097b4132fc69883ec71 | 1,179 | weather-app-kotlin | MIT License |
app/src/main/java/com/example/noteapp_architecture_sample/feature_note/domain/note_list_redux/NoteListReducer.kt | hossainMuktaR | 667,001,535 | false | {"Kotlin": 60656} | package com.example.noteapp_architecture_sample.feature_note.domain.note_list_redux
import com.example.noteapp_architecture_sample.feature_note.presentation.note_list.NoteListState
import com.example.noteapp_architecture_sample.feature_note.redux.Container
import com.example.noteapp_architecture_sample.feature_note.redux.Reducer
class NoteListReducer : Reducer<NoteListAction, NoteListState> {
override fun reduce(
action: NoteListAction,
currentState: NoteListState,
): NoteListState {
return when(action) {
is NoteListAction.AllNoteLoaded -> {
currentState.copy(
notes = action.notes,
noteOrder = action.order
)
}
is NoteListAction.ToggleOrderSection -> {
currentState.copy(
isOrderSectionVisible = !currentState.isOrderSectionVisible
)
}
is NoteListAction.DeleteNote -> {
currentState.copy(
recentlyDeletedNote = action.note
)
}
is NoteListAction.RestoreNote -> {
currentState.copy(
recentlyDeletedNote = null
)
}
else -> currentState
}
}
} | 0 | Kotlin | 0 | 0 | d0bc2eee3ba5ef86de4bad75cb063e74a728ce62 | 1,330 | NoteApp-Architecture-Sample.Android | MIT License |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.